From b0d13ca228c9855ac633f45e279f28b06c9623db Mon Sep 17 00:00:00 2001 From: Pavel Kovalenko Date: Mon, 13 Oct 2014 02:33:58 +0400 Subject: [PATCH] Format xrCore sources. --- src/xrCore/ChooseTypes.H | 73 +- src/xrCore/ELocatorAPI.cpp | 701 ++--- src/xrCore/ELocatorAPI.h | 109 +- src/xrCore/FS.cpp | 717 ++--- src/xrCore/FS.h | 460 ++-- src/xrCore/FS_impl.h | 409 +-- src/xrCore/FS_internal.h | 130 +- src/xrCore/FTimer.cpp | 52 +- src/xrCore/FTimer.h | 276 +- src/xrCore/FileSystem.cpp | 425 +-- src/xrCore/FileSystem.h | 45 +- src/xrCore/FileSystem_borland.cpp | 101 +- src/xrCore/FixedMap.h | 501 ++-- src/xrCore/FixedSet.h | 343 +-- src/xrCore/FixedVector.h | 111 +- src/xrCore/LocatorAPI.cpp | 2451 ++++++++--------- src/xrCore/LocatorAPI.h | 295 ++- src/xrCore/LocatorAPI_Notifications.cpp | 115 +- src/xrCore/LocatorAPI_Notifications.h | 59 +- src/xrCore/LocatorAPI_auth.cpp | 159 +- src/xrCore/LocatorAPI_defs.cpp | 147 +- src/xrCore/LocatorAPI_defs.h | 94 +- src/xrCore/LzHuf.cpp | 832 +++--- src/xrCore/Model.cpp | 6 +- src/xrCore/NET_utils.cpp | 477 ++-- src/xrCore/PPMdType.h | 18 +- src/xrCore/Xr_ini.cpp | 1306 ++++----- src/xrCore/_bitwise.h | 194 +- src/xrCore/_color.h | 460 ++-- src/xrCore/_compressed_normal.cpp | 212 +- src/xrCore/_compressed_normal.h | 6 +- src/xrCore/_cylinder.h | 277 +- src/xrCore/_fbox.h | 661 ++--- src/xrCore/_fbox2.h | 451 ++-- src/xrCore/_flags.h | 61 +- src/xrCore/_math.cpp | 682 ++--- src/xrCore/_math.h | 94 +- src/xrCore/_matrix.h | 1346 ++++++---- src/xrCore/_matrix33.h | 670 ++--- src/xrCore/_obb.h | 194 +- src/xrCore/_plane.h | 259 +- src/xrCore/_plane2.h | 188 +- src/xrCore/_quaternion.h | 887 ++++--- src/xrCore/_random.h | 54 +- src/xrCore/_rect.h | 157 +- src/xrCore/_sphere.cpp | 442 ++-- src/xrCore/_sphere.h | 299 ++- src/xrCore/_std_extensions.cpp | 46 +- src/xrCore/_std_extensions.h | 274 +- src/xrCore/_stl_extensions.h | 374 +-- src/xrCore/_type_traits.h | 72 +- src/xrCore/_types.h | 94 +- src/xrCore/_vector2.h | 175 +- src/xrCore/_vector3d.h | 954 +++---- src/xrCore/_vector3d_ext.h | 162 +- src/xrCore/_vector4.h | 99 +- src/xrCore/buffer_vector.h | 143 +- src/xrCore/buffer_vector_inline.h | 372 +-- src/xrCore/client_id.h | 23 +- src/xrCore/clsid.cpp | 23 +- src/xrCore/clsid.h | 8 +- src/xrCore/compression_ppmd_stream.h | 26 +- src/xrCore/compression_ppmd_stream_inline.h | 49 +- src/xrCore/cpuid.h | 59 +- src/xrCore/crc32.cpp | 184 +- src/xrCore/doug_lea_allocator.cpp | 54 +- src/xrCore/doug_lea_allocator.h | 47 +- src/xrCore/dump_string.cpp | 60 +- src/xrCore/dump_string.h | 18 +- src/xrCore/fastdelegate.h | 2652 +++++++++---------- src/xrCore/file_stream_reader.cpp | 41 +- src/xrCore/file_stream_reader.h | 11 +- src/xrCore/intrusive_ptr.h | 118 +- src/xrCore/intrusive_ptr_inline.h | 142 +- src/xrCore/log.cpp | 276 +- src/xrCore/log.h | 38 +- src/xrCore/lzhuf.h | 8 +- src/xrCore/lzo_compressor.cpp | 26 +- src/xrCore/lzo_compressor.h | 18 +- src/xrCore/memory_allocation_stats.cpp | 264 +- src/xrCore/memory_allocator_options.h | 6 +- src/xrCore/memory_monitor.cpp | 228 +- src/xrCore/memory_monitor.h | 23 +- src/xrCore/memory_usage.cpp | 57 +- src/xrCore/net_utils.h | 480 ++-- src/xrCore/os_clipboard.cpp | 125 +- src/xrCore/os_clipboard.h | 16 +- src/xrCore/ppmd_compressor.cpp | 252 +- src/xrCore/ppmd_compressor.h | 22 +- src/xrCore/resource.h | 24 +- src/xrCore/rt_compressor.cpp | 46 +- src/xrCore/rt_compressor.h | 18 +- src/xrCore/rt_compressor9.cpp | 146 +- src/xrCore/rt_lzo.cpp | 2510 +++++++++--------- src/xrCore/stream_reader.cpp | 280 +- src/xrCore/stream_reader.h | 89 +- src/xrCore/stream_reader_inline.h | 66 +- src/xrCore/string_concatenations.cpp | 419 +-- src/xrCore/string_concatenations.h | 54 +- src/xrCore/string_concatenations_inline.h | 299 ++- src/xrCore/vector.h | 647 +++-- src/xrCore/xrCore.cpp | 234 +- src/xrCore/xrCore.h | 311 +-- src/xrCore/xrCore_platform.h | 22 +- src/xrCore/xrDebug.cpp | 528 ++-- src/xrCore/xrDebug.h | 74 +- src/xrCore/xrDebugNew.cpp | 1413 +++++----- src/xrCore/xrDebug_macros.h | 108 +- src/xrCore/xrMEMORY_POOL.h | 64 +- src/xrCore/xrMemory.cpp | 419 +-- src/xrCore/xrMemory.h | 179 +- src/xrCore/xrMemory_POOL.cpp | 40 +- src/xrCore/xrMemory_align.cpp | 276 +- src/xrCore/xrMemory_align.h | 12 +- src/xrCore/xrMemory_debug.cpp | 276 +- src/xrCore/xrMemory_pso.h | 6 +- src/xrCore/xrMemory_pso_Copy.cpp | 369 +-- src/xrCore/xrMemory_pso_Fill.cpp | 4 +- src/xrCore/xrMemory_pso_Fill32.cpp | 117 +- src/xrCore/xrMemory_pure.h | 8 +- src/xrCore/xrMemory_subst_borland.cpp | 30 +- src/xrCore/xrMemory_subst_borland.h | 55 +- src/xrCore/xrMemory_subst_msvc.cpp | 386 +-- src/xrCore/xrMemory_subst_msvc.h | 198 +- src/xrCore/xrPool.h | 92 +- src/xrCore/xrSyncronize.cpp | 95 +- src/xrCore/xrSyncronize.h | 54 +- src/xrCore/xr_ini.h | 277 +- src/xrCore/xr_resource.h | 115 +- src/xrCore/xr_shared.cpp | 10 +- src/xrCore/xr_shared.h | 129 +- src/xrCore/xr_trims.cpp | 577 ++-- src/xrCore/xr_trims.h | 74 +- src/xrCore/xrsharedmem.cpp | 155 +- src/xrCore/xrsharedmem.h | 130 +- src/xrCore/xrstring.cpp | 667 ++--- src/xrCore/xrstring.h | 154 +- 137 files changed, 19847 insertions(+), 18534 deletions(-) diff --git a/src/xrCore/ChooseTypes.H b/src/xrCore/ChooseTypes.H index dd7e7282dc9..9674b8fb1c6 100644 --- a/src/xrCore/ChooseTypes.H +++ b/src/xrCore/ChooseTypes.H @@ -1,7 +1,8 @@ #ifndef ChooseTypesH #define ChooseTypesH -enum EChooseMode{ +enum EChooseMode +{ smCustom = 0, smSoundSource, smSoundEnv, @@ -25,50 +26,54 @@ enum EChooseMode{ smGameSMotions, }; -enum EChooseFlags{ - cfMultiSelect = (1<<0), - cfAllowNone = (1<<1), - cfFullExpand = (1<<2), +enum EChooseFlags +{ + cfMultiSelect = (1 << 0), + cfAllowNone = (1 << 1), + cfFullExpand = (1 << 2), }; -struct SChooseItem{ - shared_str name; - shared_str hint; - SChooseItem (LPCSTR nm, LPCSTR ht):name(nm),hint(ht){} +struct SChooseItem +{ + shared_str name; + shared_str hint; + SChooseItem(LPCSTR nm, LPCSTR ht) :name(nm), hint(ht) {} }; -DEFINE_VECTOR(SChooseItem,ChooseItemVec,ChooseItemVecIt); +DEFINE_VECTOR(SChooseItem, ChooseItemVec, ChooseItemVecIt); // typedef -typedef fastdelegate::FastDelegate2 TOnChooseFillItems; -typedef fastdelegate::FastDelegate2 TOnChooseSelectItem; -typedef fastdelegate::FastDelegate3 TOnDrawThumbnail; -typedef fastdelegate::FastDelegate0<> TOnChooseClose; +typedef fastdelegate::FastDelegate2 TOnChooseFillItems; +typedef fastdelegate::FastDelegate2 TOnChooseSelectItem; +typedef fastdelegate::FastDelegate3 TOnDrawThumbnail; +typedef fastdelegate::FastDelegate0<> TOnChooseClose; -typedef void (*TOnChooseFillEvents)(); +typedef void(*TOnChooseFillEvents)(); -struct SChooseEvents{ - enum{ - flAnimated = (1<<0), +struct SChooseEvents +{ + enum + { + flAnimated = (1 << 0), }; - shared_str caption; - TOnChooseFillItems on_fill; - TOnChooseSelectItem on_sel; - TOnDrawThumbnail on_thm; - TOnChooseClose on_close; - Flags32 flags; - SChooseEvents (){caption="Select Item";flags.zero();} - SChooseEvents (LPCSTR capt, TOnChooseFillItems f, TOnChooseSelectItem s, TOnDrawThumbnail t, TOnChooseClose c, u32 fl) + shared_str caption; + TOnChooseFillItems on_fill; + TOnChooseSelectItem on_sel; + TOnDrawThumbnail on_thm; + TOnChooseClose on_close; + Flags32 flags; + SChooseEvents() { caption = "Select Item"; flags.zero(); } + SChooseEvents(LPCSTR capt, TOnChooseFillItems f, TOnChooseSelectItem s, TOnDrawThumbnail t, TOnChooseClose c, u32 fl) { - Set (capt,f,s,t,c,fl); + Set(capt, f, s, t, c, fl); } - void Set (LPCSTR capt, TOnChooseFillItems f, TOnChooseSelectItem s, TOnDrawThumbnail t, TOnChooseClose c, u32 fl) + void Set(LPCSTR capt, TOnChooseFillItems f, TOnChooseSelectItem s, TOnDrawThumbnail t, TOnChooseClose c, u32 fl) { - caption = capt; - on_fill = f; - on_sel = s; - on_thm = t; - on_close = c; - flags.assign (fl); + caption = capt; + on_fill = f; + on_sel = s; + on_thm = t; + on_close = c; + flags.assign(fl); } }; diff --git a/src/xrCore/ELocatorAPI.cpp b/src/xrCore/ELocatorAPI.cpp index 799c72e3e12..2a4309e1aaf 100644 --- a/src/xrCore/ELocatorAPI.cpp +++ b/src/xrCore/ELocatorAPI.cpp @@ -14,12 +14,12 @@ #include "FS_internal.h" -CLocatorAPI* xr_FS = NULL; +CLocatorAPI* xr_FS = NULL; #ifdef _EDITOR -#define FSLTX "fs.ltx" +#define FSLTX "fs.ltx" #else -#define FSLTX "fsgame.ltx" +#define FSLTX "fsgame.ltx" #endif ////////////////////////////////////////////////////////////////////// @@ -27,524 +27,569 @@ CLocatorAPI* xr_FS = NULL; ////////////////////////////////////////////////////////////////////// CLocatorAPI::CLocatorAPI() { - m_Flags.zero (); - // get page size - SYSTEM_INFO sys_inf; - GetSystemInfo (&sys_inf); - dwAllocGranularity = sys_inf.dwAllocationGranularity; - dwOpenCounter = 0; + m_Flags.zero(); + // get page size + SYSTEM_INFO sys_inf; + GetSystemInfo(&sys_inf); + dwAllocGranularity = sys_inf.dwAllocationGranularity; + dwOpenCounter = 0; } CLocatorAPI::~CLocatorAPI() { } -void CLocatorAPI::_initialize (u32 flags, LPCSTR target_folder, LPCSTR fs_fname) +void CLocatorAPI::_initialize(u32 flags, LPCSTR target_folder, LPCSTR fs_fname) { - char _delimiter = '|'; //',' - if (m_Flags.is(flReady))return; + char _delimiter = '|'; //',' + if (m_Flags.is(flReady))return; - Log ("Initializing File System..."); - m_Flags.set (flags,TRUE); + Log("Initializing File System..."); + m_Flags.set(flags, TRUE); - append_path ("$fs_root$", "", 0, FALSE); + append_path("$fs_root$", "", 0, FALSE); - // append application path + // append application path - if (m_Flags.is(flScanAppRoot)){ - append_path ("$app_root$",Core.ApplicationPath,0,FALSE); + if (m_Flags.is(flScanAppRoot)) + { + append_path("$app_root$", Core.ApplicationPath, 0, FALSE); } - if (m_Flags.is(flTargetFolderOnly)){ - append_path ("$target_folder$",target_folder,0,TRUE); - }else{ - IReader* F = r_open((fs_fname&&fs_fname[0])?fs_fname:FSLTX); - if (!F&&m_Flags.is(flScanAppRoot)) - F = r_open("$app_root$",(fs_fname&&fs_fname[0])?fs_fname:FSLTX); - R_ASSERT3 (F,"Can't open file:", (fs_fname&&fs_fname[0])?fs_fname:FSLTX); - // append all pathes - string_path buf; - string_path id, temp, root, add, def, capt; - LPCSTR lp_add, lp_def, lp_capt; - string16 b_v; - while(!F->eof()){ - F->r_string (buf,sizeof(buf)); - _GetItem(buf,0,id,'='); - if (id[0]==';') continue; - _GetItem(buf,1,temp,'='); - int cnt = _GetItemCount(temp,_delimiter); R_ASSERT(cnt>=3); - u32 fl = 0; - _GetItem (temp,0,b_v,_delimiter); if (CInifile::IsBOOL(b_v)) fl |= FS_Path::flRecurse; - _GetItem (temp,1,b_v,_delimiter); if (CInifile::IsBOOL(b_v)) fl |= FS_Path::flNotif; - _GetItem (temp,2,root,_delimiter); - _GetItem (temp,3,add,_delimiter); - _GetItem (temp,4,def,_delimiter); - _GetItem (temp,5,capt,_delimiter); - xr_strlwr (id); if (!m_Flags.is(flBuildCopy)&&(0==xr_strcmp(id,"$build_copy$"))) continue; - xr_strlwr (root); - lp_add =(cnt>=4)?xr_strlwr(add):0; - lp_def =(cnt>=5)?def:0; - lp_capt =(cnt>=6)?capt:0; - PathPairIt p_it = pathes.find(root); - std::pair I; - FS_Path* P = xr_new((p_it!=pathes.end())?p_it->second->m_Path:root,lp_add,lp_def,lp_capt,fl); - I = pathes.insert(mk_pair(xr_strdup(id),P)); - - R_ASSERT (I.second); - } - r_close (F); - }; - - m_Flags.set (flReady,TRUE); - - CreateLog (0!=strstr(Core.Params,"-nolog")); -} - -void CLocatorAPI::_destroy () -{ - CloseLog (); - - for(PathPairIt p_it=pathes.begin(); p_it!=pathes.end(); p_it++){ - char* str = LPSTR(p_it->first); - xr_free (str); - xr_delete (p_it->second); + if (m_Flags.is(flTargetFolderOnly)) + { + append_path("$target_folder$", target_folder, 0, TRUE); } - pathes.clear (); + else + { + IReader* F = r_open((fs_fname&&fs_fname[0]) ? fs_fname : FSLTX); + if (!F&&m_Flags.is(flScanAppRoot)) + F = r_open("$app_root$", (fs_fname&&fs_fname[0]) ? fs_fname : FSLTX); + R_ASSERT3(F, "Can't open file:", (fs_fname&&fs_fname[0]) ? fs_fname : FSLTX); + // append all pathes + string_path buf; + string_path id, temp, root, add, def, capt; + LPCSTR lp_add, lp_def, lp_capt; + string16 b_v; + while (!F->eof()) + { + F->r_string(buf, sizeof(buf)); + _GetItem(buf, 0, id, '='); + if (id[0] == ';') continue; + _GetItem(buf, 1, temp, '='); + int cnt = _GetItemCount(temp, _delimiter); + R_ASSERT(cnt >= 3); + u32 fl = 0; + _GetItem(temp, 0, b_v, _delimiter); + if (CInifile::IsBOOL(b_v)) fl |= FS_Path::flRecurse; + _GetItem(temp, 1, b_v, _delimiter); + if (CInifile::IsBOOL(b_v)) fl |= FS_Path::flNotif; + _GetItem(temp, 2, root, _delimiter); + _GetItem(temp, 3, add, _delimiter); + _GetItem(temp, 4, def, _delimiter); + _GetItem(temp, 5, capt, _delimiter); + xr_strlwr(id); + if (!m_Flags.is(flBuildCopy) && (0 == xr_strcmp(id, "$build_copy$"))) continue; + xr_strlwr(root); + lp_add = (cnt >= 4) ? xr_strlwr(add) : 0; + lp_def = (cnt >= 5) ? def : 0; + lp_capt = (cnt >= 6) ? capt : 0; + PathPairIt p_it = pathes.find(root); + std::pair I; + FS_Path* P = xr_new((p_it != pathes.end()) ? p_it->second->m_Path : root, lp_add, lp_def, lp_capt, fl); + I = pathes.insert(mk_pair(xr_strdup(id), P)); + + R_ASSERT(I.second); + } + r_close(F); + }; + + m_Flags.set(flReady, TRUE); + + CreateLog(0 != strstr(Core.Params, "-nolog")); +} + +void CLocatorAPI::_destroy() +{ + CloseLog(); + + for (PathPairIt p_it = pathes.begin(); p_it != pathes.end(); p_it++) + { + char* str = LPSTR(p_it->first); + xr_free(str); + xr_delete(p_it->second); + } + pathes.clear(); } BOOL CLocatorAPI::file_find(LPCSTR full_name, FS_File& f) { - intptr_t hFile; - _FINDDATA_T sFile; - // find all files - if (-1!=(hFile=_findfirst((LPSTR)full_name, &sFile))){ - f = FS_File(sFile); - _findclose (hFile); - return TRUE; - }else{ - return FALSE; + intptr_t hFile; + _FINDDATA_T sFile; + // find all files + if (-1 != (hFile = _findfirst((LPSTR)full_name, &sFile))) + { + f = FS_File(sFile); + _findclose(hFile); + return TRUE; + } + else + { + return FALSE; } } -BOOL CLocatorAPI::exist (const char* fn) +BOOL CLocatorAPI::exist(const char* fn) { - return ::GetFileAttributes(fn) != u32(-1); + return ::GetFileAttributes(fn) != u32(-1); } -BOOL CLocatorAPI::exist (const char* path, const char* name) +BOOL CLocatorAPI::exist(const char* path, const char* name) { - string_path temp; - update_path (temp,path,name); - return exist (temp); + string_path temp; + update_path(temp, path, name); + return exist(temp); } -BOOL CLocatorAPI::exist (string_path& fn, const char* path, const char* name) +BOOL CLocatorAPI::exist(string_path& fn, const char* path, const char* name) { - update_path (fn,path,name); - return exist (fn); + update_path(fn, path, name); + return exist(fn); } -BOOL CLocatorAPI::exist (string_path& fn, const char* path, const char* name, const char* ext) +BOOL CLocatorAPI::exist(string_path& fn, const char* path, const char* name, const char* ext) { - string_path nm; - strconcat (sizeof(nm),nm,name,ext); - update_path (fn,path,nm); - return exist (fn); + string_path nm; + strconcat(sizeof(nm), nm, name, ext); + update_path(fn, path, nm); + return exist(fn); } bool ignore_name(const char* _name) { - // ignore processing ".svn" folders - return ( _name[0]=='.' && _name[1]=='s' && _name[2]=='v' && _name[3]=='n' && _name[4]==0) ; + // ignore processing ".svn" folders + return (_name[0] == '.' && _name[1] == 's' && _name[2] == 'v' && _name[3] == 'n' && _name[4] == 0); } -typedef void (__stdcall * TOnFind) (_finddata_t&, void*); -void Recurse (LPCSTR, bool, TOnFind, void*); -void ProcessOne (LPCSTR path, _finddata_t& F, bool root_only, TOnFind on_find_cb, void* data) +typedef void(__stdcall* TOnFind) (_finddata_t&, void*); +void Recurse(LPCSTR, bool, TOnFind, void*); +void ProcessOne(LPCSTR path, _finddata_t& F, bool root_only, TOnFind on_find_cb, void* data) { - string_path N; - strcpy (N,path); - strcat (N,F.name); - xr_strlwr (N); + string_path N; + strcpy(N, path); + strcat(N, F.name); + xr_strlwr(N); - if (ignore_name(N)) return; - - if (F.attrib&_A_HIDDEN) return; + if (ignore_name(N)) return; - if (F.attrib&_A_SUBDIR) { - if (root_only) return; - if (0==xr_strcmp(F.name,".")) return; - if (0==xr_strcmp(F.name,"..")) return; - strcat (N,"\\"); - strcpy (F.name,N); - on_find_cb (F,data); - Recurse (F.name,root_only,on_find_cb,data); - } else { - strcpy (F.name,N); - on_find_cb (F,data); - } + if (F.attrib&_A_HIDDEN) return; + + if (F.attrib&_A_SUBDIR) + { + if (root_only) return; + if (0 == xr_strcmp(F.name, ".")) return; + if (0 == xr_strcmp(F.name, "..")) return; + strcat(N, "\\"); + strcpy(F.name, N); + on_find_cb(F, data); + Recurse(F.name, root_only, on_find_cb, data); + } + else + { + strcpy(F.name, N); + on_find_cb(F, data); + } } void Recurse(LPCSTR path, bool root_only, TOnFind on_find_cb, void* data) { - xr_string fpath = path; - fpath += "*.*"; + xr_string fpath = path; + fpath += "*.*"; // begin search - _finddata_t sFile; - intptr_t hFile; - - // find all files - if (-1==(hFile=_findfirst((LPSTR)fpath.c_str(), &sFile))) - return; - do{ - ProcessOne (path,sFile, root_only, on_find_cb, data); - }while(_findnext(hFile,&sFile)==0); - _findclose ( hFile ); + _finddata_t sFile; + intptr_t hFile; + + // find all files + if (-1 == (hFile = _findfirst((LPSTR)fpath.c_str(), &sFile))) + return; + do + { + ProcessOne(path, sFile, root_only, on_find_cb, data); + } + while (_findnext(hFile, &sFile) == 0); + _findclose(hFile); } struct file_list_cb_data { - size_t base_len; - u32 flags; + size_t base_len; + u32 flags; SStringVec* masks; FS_FileSet* dest; }; void __stdcall file_list_cb(_finddata_t& entry, void* data) { - file_list_cb_data* D = (file_list_cb_data*)data; + file_list_cb_data* D = (file_list_cb_data*)data; - LPCSTR end_symbol = entry.name+xr_strlen(entry.name)-1; - if ((*end_symbol)!='\\'){ + LPCSTR end_symbol = entry.name + xr_strlen(entry.name) - 1; + if ((*end_symbol) != '\\') + { // file - if ((D->flags&FS_ListFiles) == 0) return; - LPCSTR entry_begin = entry.name+D->base_len; - if ((D->flags&FS_RootOnly)&&strstr(entry_begin,"\\")) return; // folder in folder + if ((D->flags&FS_ListFiles) == 0) return; + LPCSTR entry_begin = entry.name + D->base_len; + if ((D->flags&FS_RootOnly) && strstr(entry_begin, "\\")) return; // folder in folder // check extension - if (D->masks){ - bool bOK = false; - for (SStringVecIt it=D->masks->begin(); it!=D->masks->end(); it++) - if (PatternMatch(entry_begin,it->c_str())){bOK=true; break;} - if (!bOK) return; + if (D->masks) + { + bool bOK = false; + for (SStringVecIt it = D->masks->begin(); it != D->masks->end(); it++) + if (PatternMatch(entry_begin, it->c_str())) { bOK = true; break; } + if (!bOK) return; } - xr_string fn = entry_begin; + xr_string fn = entry_begin; // insert file entry - if (D->flags&FS_ClampExt) fn=EFS.ChangeFileExt(fn,""); - D->dest->insert (FS_File(fn,entry)); - } else { + if (D->flags&FS_ClampExt) fn = EFS.ChangeFileExt(fn, ""); + D->dest->insert(FS_File(fn, entry)); + } + else + { // folder - if ((D->flags&FS_ListFolders) == 0) return; - LPCSTR entry_begin = entry.name+D->base_len; - D->dest->insert (FS_File(entry_begin,entry)); + if ((D->flags&FS_ListFolders) == 0) return; + LPCSTR entry_begin = entry.name + D->base_len; + D->dest->insert(FS_File(entry_begin, entry)); } } int CLocatorAPI::file_list(FS_FileSet& dest, LPCSTR path, u32 flags, LPCSTR mask) { - R_ASSERT (path); - VERIFY (flags); - - string_path fpath; - if (path_exist(path)) - update_path (fpath,path,""); + R_ASSERT(path); + VERIFY(flags); + + string_path fpath; + if (path_exist(path)) + update_path(fpath, path, ""); else - strcpy(fpath,path); + strcpy(fpath, path); // build mask - SStringVec masks; - _SequenceToList (masks,mask); + SStringVec masks; + _SequenceToList(masks, mask); file_list_cb_data data; - data.base_len = xr_strlen(fpath); - data.flags = flags; - data.masks = masks.empty()?0:&masks; - data.dest = &dest; + data.base_len = xr_strlen(fpath); + data.flags = flags; + data.masks = masks.empty() ? 0 : &masks; + data.dest = &dest; - Recurse (fpath,!!(flags&FS_RootOnly),file_list_cb,&data); - return dest.size(); + Recurse(fpath, !!(flags&FS_RootOnly), file_list_cb, &data); + return dest.size(); } -IReader* CLocatorAPI::r_open (LPCSTR path, LPCSTR _fname) +IReader* CLocatorAPI::r_open(LPCSTR path, LPCSTR _fname) { - IReader* R = 0; + IReader* R = 0; - // correct path - string_path fname; - strcpy (fname,_fname); - xr_strlwr (fname); - if (path&&path[0]) update_path(fname,path,fname); + // correct path + string_path fname; + strcpy(fname, _fname); + xr_strlwr(fname); + if (path&&path[0]) update_path(fname, path, fname); - // Search entry - FS_File desc; - if (!file_find(fname,desc)) return NULL; + // Search entry + FS_File desc; + if (!file_find(fname, desc)) return NULL; - dwOpenCounter ++; + dwOpenCounter++; - LPCSTR source_name = &fname[0]; + LPCSTR source_name = &fname[0]; // open file - if (desc.size<256*1024) R = xr_new (fname); - else R = xr_new (fname); - + if (desc.size < 256 * 1024) R = xr_new(fname); + else R = xr_new(fname); + #ifdef DEBUG - if ( R && m_Flags.is(flBuildCopy|flReady) ){ - string_path cpy_name; - string_path e_cpy_name; - FS_Path* P; - if (source_name==strstr(source_name,(P=get_path("$server_root$"))->m_Path)|| - source_name==strstr(source_name,(P=get_path("$server_data_root$"))->m_Path)){ - update_path (cpy_name,"$build_copy$",source_name+xr_strlen(P->m_Path)); - IWriter* W = w_open (cpy_name); - if (W){ - W->w (R->pointer(),R->length()); - w_close (W); - set_file_age(cpy_name,get_file_age(source_name)); - if (m_Flags.is(flEBuildCopy)){ - LPCSTR ext = strext(cpy_name); - if (ext){ - IReader* R = 0; - if (0==xr_strcmp(ext,".dds")){ - P = get_path("$game_textures$"); - update_path (e_cpy_name,"$textures$",source_name+xr_strlen(P->m_Path)); + if (R && m_Flags.is(flBuildCopy | flReady)) + { + string_path cpy_name; + string_path e_cpy_name; + FS_Path* P; + if (source_name == strstr(source_name, (P = get_path("$server_root$"))->m_Path) || + source_name == strstr(source_name, (P = get_path("$server_data_root$"))->m_Path)) + { + update_path(cpy_name, "$build_copy$", source_name + xr_strlen(P->m_Path)); + IWriter* W = w_open(cpy_name); + if (W) + { + W->w(R->pointer(), R->length()); + w_close(W); + set_file_age(cpy_name, get_file_age(source_name)); + if (m_Flags.is(flEBuildCopy)) + { + LPCSTR ext = strext(cpy_name); + if (ext) + { + IReader* R = 0; + if (0 == xr_strcmp(ext, ".dds")) + { + P = get_path("$game_textures$"); + update_path(e_cpy_name, "$textures$", source_name + xr_strlen(P->m_Path)); // tga - *strext (e_cpy_name) = 0; - strcat (e_cpy_name,".tga"); - r_close (R=r_open(e_cpy_name)); + *strext(e_cpy_name) = 0; + strcat(e_cpy_name, ".tga"); + r_close(R = r_open(e_cpy_name)); // thm - *strext (e_cpy_name) = 0; - strcat (e_cpy_name,".thm"); - r_close (R=r_open(e_cpy_name)); - }else if (0==xr_strcmp(ext,".ogg")){ - P = get_path("$game_sounds$"); - update_path (e_cpy_name,"$sounds$",source_name+xr_strlen(P->m_Path)); + *strext(e_cpy_name) = 0; + strcat(e_cpy_name, ".thm"); + r_close(R = r_open(e_cpy_name)); + } + else if (0 == xr_strcmp(ext, ".ogg")) + { + P = get_path("$game_sounds$"); + update_path(e_cpy_name, "$sounds$", source_name + xr_strlen(P->m_Path)); // wav - *strext (e_cpy_name) = 0; - strcat (e_cpy_name,".wav"); - r_close (R=r_open(e_cpy_name)); + *strext(e_cpy_name) = 0; + strcat(e_cpy_name, ".wav"); + r_close(R = r_open(e_cpy_name)); // thm - *strext (e_cpy_name) = 0; - strcat (e_cpy_name,".thm"); - r_close (R=r_open(e_cpy_name)); - }else if (0==xr_strcmp(ext,".object")){ - strcpy (e_cpy_name,source_name); + *strext(e_cpy_name) = 0; + strcat(e_cpy_name, ".thm"); + r_close(R = r_open(e_cpy_name)); + } + else if (0 == xr_strcmp(ext, ".object")) + { + strcpy(e_cpy_name, source_name); // object thm - *strext (e_cpy_name) = 0; - strcat (e_cpy_name,".thm"); - R = r_open(e_cpy_name); - if (R) r_close (R); + *strext(e_cpy_name) = 0; + strcat(e_cpy_name, ".thm"); + R = r_open(e_cpy_name); + if (R) r_close(R); } } } - }else{ - Log ("!Can't build:",source_name); } - } - } + else + { + Log("!Can't build:", source_name); + } + } + } #endif // DEBUG - return R; + return R; } -void CLocatorAPI::r_close (IReader* &fs) +void CLocatorAPI::r_close(IReader*& fs) { - xr_delete (fs); + xr_delete(fs); } -IWriter* CLocatorAPI::w_open (LPCSTR path, LPCSTR _fname) +IWriter* CLocatorAPI::w_open(LPCSTR path, LPCSTR _fname) { - string_path fname; - xr_strlwr(strcpy(fname,_fname));//,".$"); - if (path&&path[0]) update_path(fname,path,fname); - CFileWriter* W = xr_new(fname,false); + string_path fname; + xr_strlwr(strcpy(fname, _fname));//,".$"); + if (path&&path[0]) update_path(fname, path, fname); + CFileWriter* W = xr_new(fname, false); #ifdef _EDITOR - if (!W->valid()) xr_delete(W); -#endif - return W; + if (!W->valid()) xr_delete(W); +#endif + return W; } -IWriter* CLocatorAPI::w_open_ex (LPCSTR path, LPCSTR _fname) +IWriter* CLocatorAPI::w_open_ex(LPCSTR path, LPCSTR _fname) { - string_path fname; - xr_strlwr(strcpy(fname,_fname));//,".$"); - if (path&&path[0]) update_path(fname,path,fname); - CFileWriter* W = xr_new(fname,true); + string_path fname; + xr_strlwr(strcpy(fname, _fname));//,".$"); + if (path&&path[0]) update_path(fname, path, fname); + CFileWriter* W = xr_new(fname, true); #ifdef _EDITOR - if (!W->valid()) xr_delete(W); -#endif - return W; + if (!W->valid()) xr_delete(W); +#endif + return W; } -void CLocatorAPI::w_close(IWriter* &S) +void CLocatorAPI::w_close(IWriter*& S) { - if (S){ - R_ASSERT (S->fName.size()); - xr_delete (S); + if (S) + { + R_ASSERT(S->fName.size()); + xr_delete(S); } } struct dir_delete_cb_data { - FS_FileSet* folders; - BOOL remove_files; + FS_FileSet* folders; + BOOL remove_files; }; void __stdcall dir_delete_cb(_finddata_t& entry, void* data) { - dir_delete_cb_data* D = (dir_delete_cb_data*)data; + dir_delete_cb_data* D = (dir_delete_cb_data*)data; - if (entry.attrib&_A_SUBDIR) D->folders->insert (FS_File(entry)); - else if (D->remove_files) FS.file_delete (entry.name); + if (entry.attrib&_A_SUBDIR) D->folders->insert(FS_File(entry)); + else if (D->remove_files) FS.file_delete(entry.name); } BOOL CLocatorAPI::dir_delete(LPCSTR initial, LPCSTR nm, BOOL remove_files) { - string_path fpath; - if (initial&&initial[0]) - update_path (fpath,initial,nm); + string_path fpath; + if (initial&&initial[0]) + update_path(fpath, initial, nm); else - strcpy (fpath,nm); + strcpy(fpath, nm); - FS_FileSet folders; - folders.insert (FS_File(fpath)); + FS_FileSet folders; + folders.insert(FS_File(fpath)); // recurse find - dir_delete_cb_data data; - data.folders = &folders; - data.remove_files = remove_files; - Recurse (fpath,false,dir_delete_cb,&data); + dir_delete_cb_data data; + data.folders = &folders; + data.remove_files = remove_files; + Recurse(fpath, false, dir_delete_cb, &data); // remove folders FS_FileSet::reverse_iterator r_it = folders.rbegin(); - for (;r_it!=folders.rend();r_it++) - _rmdir (r_it->name.c_str()); + for (; r_it != folders.rend(); r_it++) + _rmdir(r_it->name.c_str()); return TRUE; -} +} void CLocatorAPI::file_delete(LPCSTR path, LPCSTR nm) { - string_path fname; - if (path&&path[0]) - update_path (fname,path,nm); + string_path fname; + if (path&&path[0]) + update_path(fname, path, nm); else - strcpy (fname,nm); - unlink (fname); + strcpy(fname, nm); + unlink(fname); } void CLocatorAPI::file_copy(LPCSTR src, LPCSTR dest) { - if (exist(src)){ - IReader* S = r_open(src); - if (S){ - IWriter* D = w_open(dest); - if (D){ - D->w (S->pointer(),S->length()); - w_close (D); + if (exist(src)) + { + IReader* S = r_open(src); + if (S) + { + IWriter* D = w_open(dest); + if (D) + { + D->w(S->pointer(), S->length()); + w_close(D); } - r_close (S); + r_close(S); } - } + } } void CLocatorAPI::file_rename(LPCSTR src, LPCSTR dest, bool bOwerwrite) { - if (bOwerwrite&&exist(dest)) unlink(dest); + if (bOwerwrite&&exist(dest)) unlink(dest); // physically rename file - VerifyPath (dest); - rename (src,dest); + VerifyPath(dest); + rename(src, dest); } -int CLocatorAPI::file_length(LPCSTR src) +int CLocatorAPI::file_length(LPCSTR src) { - FS_File F; - return (file_find(src,F))?F.size:-1; + FS_File F; + return (file_find(src, F)) ? F.size : -1; } BOOL CLocatorAPI::path_exist(LPCSTR path) { - PathPairIt P = pathes.find(path); - return (P!=pathes.end()); + PathPairIt P = pathes.find(path); + return (P != pathes.end()); } FS_Path* CLocatorAPI::append_path(LPCSTR path_alias, LPCSTR root, LPCSTR add, BOOL recursive) { - VERIFY (root/*&&root[0]*/); - VERIFY (false==path_exist(path_alias)); - FS_Path* P = xr_new(root,add,LPCSTR(0),LPCSTR(0),0); - pathes.insert (mk_pair(xr_strdup(path_alias),P)); - return P; + VERIFY(root/*&&root[0]*/); + VERIFY(false == path_exist(path_alias)); + FS_Path* P = xr_new(root, add, LPCSTR(0), LPCSTR(0), 0); + pathes.insert(mk_pair(xr_strdup(path_alias), P)); + return P; } FS_Path* CLocatorAPI::get_path(LPCSTR path) { - PathPairIt P = pathes.find(path); - R_ASSERT2(P!=pathes.end(),path); + PathPairIt P = pathes.find(path); + R_ASSERT2(P != pathes.end(), path); return P->second; } LPCSTR CLocatorAPI::update_path(string_path& dest, LPCSTR initial, LPCSTR src) { - return get_path(initial)->_update(dest,src); + return get_path(initial)->_update(dest, src); } /* void CLocatorAPI::update_path(xr_string& dest, LPCSTR initial, LPCSTR src) { - return get_path(initial)->_update(dest,src); +return get_path(initial)->_update(dest,src); } */ time_t CLocatorAPI::get_file_age(LPCSTR nm) { - FS_File F; - return (file_find(nm,F))?F.time_write:-1; + FS_File F; + return (file_find(nm, F)) ? F.time_write : -1; } void CLocatorAPI::set_file_age(LPCSTR nm, time_t age) { // set file - _utimbuf tm; - tm.actime = age; - tm.modtime = age; - int res = _utime(nm,&tm); - if (0!=res) Msg("!Can't set file age: '%s'. Error: '%s'",nm,_sys_errlist[errno]); + _utimbuf tm; + tm.actime = age; + tm.modtime = age; + int res = _utime(nm, &tm); + if (0 != res) Msg("!Can't set file age: '%s'. Error: '%s'", nm, _sys_errlist[errno]); } BOOL CLocatorAPI::can_write_to_folder(LPCSTR path) { - if (path&&path[0]){ - string_path temp; - LPCSTR fn = "$!#%TEMP%#!$.$$$"; - strconcat (sizeof(temp),temp,path,path[xr_strlen(path)-1]!='\\'?"\\":"",fn); - FILE* hf = fopen (temp, "wb"); - if (hf==0) return FALSE; - else{ - fclose (hf); - unlink (temp); - return TRUE; + if (path&&path[0]) + { + string_path temp; + LPCSTR fn = "$!#%TEMP%#!$.$$$"; + strconcat(sizeof(temp), temp, path, path[xr_strlen(path) - 1] != '\\' ? "\\" : "", fn); + FILE* hf = fopen(temp, "wb"); + if (hf == 0) return FALSE; + else + { + fclose(hf); + unlink(temp); + return TRUE; } - }else{ - return FALSE; + } + else + { + return FALSE; } } BOOL CLocatorAPI::can_write_to_alias(LPCSTR path) { - string_path temp; - update_path (temp,path,""); - return can_write_to_folder(temp); + string_path temp; + update_path(temp, path, ""); + return can_write_to_folder(temp); } BOOL CLocatorAPI::can_modify_file(LPCSTR fname) { - FILE* hf = fopen (fname, "r+b"); - if (hf){ - fclose (hf); - return TRUE; - }else{ - return FALSE; + FILE* hf = fopen(fname, "r+b"); + if (hf) + { + fclose(hf); + return TRUE; + } + else + { + return FALSE; } } BOOL CLocatorAPI::can_modify_file(LPCSTR path, LPCSTR name) { - string_path temp; - update_path (temp,path,name); - return can_modify_file(temp); + string_path temp; + update_path(temp, path, name); + return can_modify_file(temp); } diff --git a/src/xrCore/ELocatorAPI.h b/src/xrCore/ELocatorAPI.h index 29dbfdd2efe..dee8df4fa51 100644 --- a/src/xrCore/ELocatorAPI.h +++ b/src/xrCore/ELocatorAPI.h @@ -8,76 +8,77 @@ #include "LocatorAPI_defs.h" -class XRCORE_API CLocatorAPI +class XRCORE_API CLocatorAPI { - friend class FS_Path; + friend class FS_Path; public: private: - DEFINE_MAP_PRED (LPCSTR,FS_Path*,PathMap,PathPairIt,pred_str); - PathMap pathes; + DEFINE_MAP_PRED(LPCSTR, FS_Path*, PathMap, PathPairIt, pred_str); + PathMap pathes; public: - enum{ - flNeedRescan = (1<<0), - flBuildCopy = (1<<1), - flReady = (1<<2), - flEBuildCopy = (1<<3), -//. flEventNotificator = (1<<4), - flTargetFolderOnly = (1<<5), - flCacheFiles = (1<<6), - flScanAppRoot = (1<<7), - }; - Flags32 m_Flags ; - u32 dwAllocGranularity; - u32 dwOpenCounter; + enum + { + flNeedRescan = (1 << 0), + flBuildCopy = (1 << 1), + flReady = (1 << 2), + flEBuildCopy = (1 << 3), + //. flEventNotificator = (1<<4), + flTargetFolderOnly = (1 << 5), + flCacheFiles = (1 << 6), + flScanAppRoot = (1 << 7), + }; + Flags32 m_Flags; + u32 dwAllocGranularity; + u32 dwOpenCounter; public: - CLocatorAPI (); - ~CLocatorAPI (); - void _initialize (u32 flags, LPCSTR target_folder=0, LPCSTR fs_fname=0); - void _destroy (); + CLocatorAPI(); + ~CLocatorAPI(); + void _initialize(u32 flags, LPCSTR target_folder = 0, LPCSTR fs_fname = 0); + void _destroy(); - IReader* r_open (LPCSTR initial, LPCSTR N); - IC IReader* r_open (LPCSTR N){return r_open(0,N);} - void r_close (IReader* &S); + IReader* r_open(LPCSTR initial, LPCSTR N); + IC IReader* r_open(LPCSTR N) { return r_open(0, N); } + void r_close(IReader*& S); - IWriter* w_open (LPCSTR initial, LPCSTR N); - IWriter* w_open_ex (LPCSTR initial, LPCSTR N); - IC IWriter* w_open (LPCSTR N){return w_open(0,N);} - IC IWriter* w_open_ex (LPCSTR N){return w_open_ex(0,N);} - void w_close (IWriter* &S); + IWriter* w_open(LPCSTR initial, LPCSTR N); + IWriter* w_open_ex(LPCSTR initial, LPCSTR N); + IC IWriter* w_open(LPCSTR N) { return w_open(0, N); } + IC IWriter* w_open_ex(LPCSTR N) { return w_open_ex(0, N); } + void w_close(IWriter*& S); - BOOL exist (LPCSTR N); - BOOL exist (LPCSTR path, LPCSTR name); - BOOL exist (string_path& fn, LPCSTR path, LPCSTR name); - BOOL exist (string_path& fn, LPCSTR path, LPCSTR name, LPCSTR ext); + BOOL exist(LPCSTR N); + BOOL exist(LPCSTR path, LPCSTR name); + BOOL exist(string_path& fn, LPCSTR path, LPCSTR name); + BOOL exist(string_path& fn, LPCSTR path, LPCSTR name, LPCSTR ext); - BOOL can_write_to_folder (LPCSTR path); - BOOL can_write_to_alias (LPCSTR path); - BOOL can_modify_file (LPCSTR fname); - BOOL can_modify_file (LPCSTR path, LPCSTR name); + BOOL can_write_to_folder(LPCSTR path); + BOOL can_write_to_alias(LPCSTR path); + BOOL can_modify_file(LPCSTR fname); + BOOL can_modify_file(LPCSTR path, LPCSTR name); - BOOL dir_delete (LPCSTR initial, LPCSTR N,BOOL remove_files); - BOOL dir_delete (LPCSTR full_path,BOOL remove_files){return dir_delete(0,full_path,remove_files);} - void file_delete (LPCSTR path,LPCSTR nm); - void file_delete (LPCSTR full_path){file_delete(0,full_path);} - void file_copy (LPCSTR src, LPCSTR dest); - void file_rename (LPCSTR src, LPCSTR dest,bool bOwerwrite=true); - int file_length (LPCSTR src); + BOOL dir_delete(LPCSTR initial, LPCSTR N, BOOL remove_files); + BOOL dir_delete(LPCSTR full_path, BOOL remove_files) { return dir_delete(0, full_path, remove_files); } + void file_delete(LPCSTR path, LPCSTR nm); + void file_delete(LPCSTR full_path) { file_delete(0, full_path); } + void file_copy(LPCSTR src, LPCSTR dest); + void file_rename(LPCSTR src, LPCSTR dest, bool bOwerwrite = true); + int file_length(LPCSTR src); - time_t get_file_age (LPCSTR nm); - void set_file_age (LPCSTR nm, time_t age); + time_t get_file_age(LPCSTR nm); + void set_file_age(LPCSTR nm, time_t age); - BOOL path_exist (LPCSTR path); - FS_Path* get_path (LPCSTR path); - FS_Path* append_path (LPCSTR path_alias, LPCSTR root, LPCSTR add, BOOL recursive); - LPCSTR update_path (string_path& dest, LPCSTR initial, LPCSTR src); + BOOL path_exist(LPCSTR path); + FS_Path* get_path(LPCSTR path); + FS_Path* append_path(LPCSTR path_alias, LPCSTR root, LPCSTR add, BOOL recursive); + LPCSTR update_path(string_path& dest, LPCSTR initial, LPCSTR src); - BOOL file_find (LPCSTR full_name, FS_File& f); + BOOL file_find(LPCSTR full_name, FS_File& f); - int file_list (FS_FileSet& dest, LPCSTR path, u32 flags=FS_ListFiles, LPCSTR mask=0); -//. void update_path (xr_string& dest, LPCSTR initial, LPCSTR src); + int file_list(FS_FileSet& dest, LPCSTR path, u32 flags = FS_ListFiles, LPCSTR mask = 0); + //. void update_path (xr_string& dest, LPCSTR initial, LPCSTR src); }; -extern XRCORE_API CLocatorAPI* xr_FS; +extern XRCORE_API CLocatorAPI* xr_FS; #define FS (*xr_FS) #endif // ELocatorAPIH diff --git a/src/xrCore/FS.cpp b/src/xrCore/FS.cpp index 81d0c2b4edb..92347177114 100644 --- a/src/xrCore/FS.cpp +++ b/src/xrCore/FS.cpp @@ -11,66 +11,66 @@ #pragma warning(default:4995) //typedef void DUMMY_STUFF (const void*,const u32&,void*); -//XRCORE_API DUMMY_STUFF *g_dummy_stuff = 0; +//XRCORE_API DUMMY_STUFF *g_dummy_stuff = 0; #ifdef M_BORLAND -# define O_SEQUENTIAL 0 +# define O_SEQUENTIAL 0 #endif // M_BORLAND #ifdef FS_DEBUG - XRCORE_API u32 g_file_mapped_memory = 0; - u32 g_file_mapped_count = 0; - typedef xr_map > FILE_MAPPINGS; - FILE_MAPPINGS g_file_mappings; +XRCORE_API u32 g_file_mapped_memory = 0; +u32 g_file_mapped_count = 0; +typedef xr_map > FILE_MAPPINGS; +FILE_MAPPINGS g_file_mappings; -void register_file_mapping (void *address, const u32 &size, LPCSTR file_name) +void register_file_mapping(void* address, const u32& size, LPCSTR file_name) { - FILE_MAPPINGS::const_iterator I = g_file_mappings.find(*(u32*)&address); - VERIFY (I == g_file_mappings.end()); - g_file_mappings.insert (std::make_pair(*(u32*)&address,std::make_pair(size,shared_str(file_name)))); + FILE_MAPPINGS::const_iterator I = g_file_mappings.find(*(u32*)&address); + VERIFY(I == g_file_mappings.end()); + g_file_mappings.insert(std::make_pair(*(u32*)&address, std::make_pair(size, shared_str(file_name)))); -// Msg ("++register_file_mapping(%2d): [0x%08x]%s", g_file_mapped_count + 1, *((u32*)&address), file_name); + // Msg ("++register_file_mapping(%2d): [0x%08x]%s", g_file_mapped_count + 1, *((u32*)&address), file_name); - g_file_mapped_memory += size; - ++g_file_mapped_count; + g_file_mapped_memory += size; + ++g_file_mapped_count; #ifdef USE_MEMORY_MONITOR -// memory_monitor::monitor_alloc (addres,size,"file mapping"); - string512 temp; - xr_sprintf (temp, sizeof(temp),"file mapping: %s",file_name); - memory_monitor::monitor_alloc (address,size,temp); + // memory_monitor::monitor_alloc (addres,size,"file mapping"); + string512 temp; + xr_sprintf(temp, sizeof(temp), "file mapping: %s", file_name); + memory_monitor::monitor_alloc(address, size, temp); #endif // USE_MEMORY_MONITOR } -void unregister_file_mapping (void *address, const u32 &size) +void unregister_file_mapping(void* address, const u32& size) { - FILE_MAPPINGS::iterator I = g_file_mappings.find(*(u32*)&address); - VERIFY (I != g_file_mappings.end()); -// VERIFY2 ((*I).second.first == size,make_string("file mapping sizes are different: %d -> %d",(*I).second.first,size)); - g_file_mapped_memory -= (*I).second.first; - --g_file_mapped_count; + FILE_MAPPINGS::iterator I = g_file_mappings.find(*(u32*)&address); + VERIFY(I != g_file_mappings.end()); + // VERIFY2 ((*I).second.first == size,make_string("file mapping sizes are different: %d -> %d",(*I).second.first,size)); + g_file_mapped_memory -= (*I).second.first; + --g_file_mapped_count; -// Msg ("--unregister_file_mapping(%2d): [0x%08x]%s", g_file_mapped_count + 1, *((u32*)&address), (*I).second.second.c_str()); + // Msg ("--unregister_file_mapping(%2d): [0x%08x]%s", g_file_mapped_count + 1, *((u32*)&address), (*I).second.second.c_str()); - g_file_mappings.erase (I); + g_file_mappings.erase(I); #ifdef USE_MEMORY_MONITOR - memory_monitor::monitor_free (address); + memory_monitor::monitor_free(address); #endif // USE_MEMORY_MONITOR } -XRCORE_API void dump_file_mappings () +XRCORE_API void dump_file_mappings() { - Msg ("* active file mappings (%d):",g_file_mappings.size()); + Msg("* active file mappings (%d):", g_file_mappings.size()); - FILE_MAPPINGS::const_iterator I = g_file_mappings.begin(); - FILE_MAPPINGS::const_iterator E = g_file_mappings.end(); - for ( ; I != E; ++I) - Msg ( - "* [0x%08x][%d][%s]", - (*I).first, - (*I).second.first, - (*I).second.second.c_str() - ); + FILE_MAPPINGS::const_iterator I = g_file_mappings.begin(); + FILE_MAPPINGS::const_iterator E = g_file_mappings.end(); + for (; I != E; ++I) + Msg( + "* [0x%08x][%d][%s]", + (*I).first, + (*I).second.first, + (*I).second.second.c_str() + ); } #endif // DEBUG ////////////////////////////////////////////////////////////////////// @@ -79,130 +79,140 @@ XRCORE_API void dump_file_mappings () //--------------------------------------------------- void VerifyPath(LPCSTR path) { - string1024 tmp; - for(int i=0;path[i];i++){ - if( path[i]!='\\' || i==0 ) - continue; - CopyMemory( tmp, path, i ); - tmp[i] = 0; + string1024 tmp; + for (int i = 0; path[i]; i++) + { + if (path[i] != '\\' || i == 0) + continue; + CopyMemory(tmp, path, i); + tmp[i] = 0; _mkdir(tmp); - } + } } #ifdef _EDITOR -bool file_handle_internal (LPCSTR file_name, u32 &size, int &hFile) -{ - hFile = _open(file_name,O_RDONLY|O_BINARY|O_SEQUENTIAL); - if (hFile <= 0) { - Sleep (1); - hFile = _open(file_name,O_RDONLY|O_BINARY|O_SEQUENTIAL); - if (hFile <= 0) - return (false); - } - - size = filelength(hFile); - return (true); +bool file_handle_internal(LPCSTR file_name, u32& size, int& hFile) +{ + hFile = _open(file_name, O_RDONLY | O_BINARY | O_SEQUENTIAL); + if (hFile <= 0) + { + Sleep(1); + hFile = _open(file_name, O_RDONLY | O_BINARY | O_SEQUENTIAL); + if (hFile <= 0) + return (false); + } + + size = filelength(hFile); + return (true); } #else // EDITOR -static errno_t open_internal(LPCSTR fn, int &handle) -{ - return ( - _sopen_s( - &handle, - fn, - _O_RDONLY | _O_BINARY, - _SH_DENYNO, - _S_IREAD - ) - ); -} - -bool file_handle_internal (LPCSTR file_name, u32 &size, int &file_handle) -{ - if (open_internal(file_name, file_handle)) { - Sleep (1); - if (open_internal(file_name, file_handle)) - return (false); - } - - size = _filelength(file_handle); - return (true); +static errno_t open_internal(LPCSTR fn, int& handle) +{ + return ( + _sopen_s( + &handle, + fn, + _O_RDONLY | _O_BINARY, + _SH_DENYNO, + _S_IREAD + ) + ); +} + +bool file_handle_internal(LPCSTR file_name, u32& size, int& file_handle) +{ + if (open_internal(file_name, file_handle)) + { + Sleep(1); + if (open_internal(file_name, file_handle)) + return (false); + } + + size = _filelength(file_handle); + return (true); } #endif // EDITOR -void *FileDownload (LPCSTR file_name, const int &file_handle, u32 &file_size) +void* FileDownload(LPCSTR file_name, const int& file_handle, u32& file_size) { - void *buffer = Memory.mem_alloc ( - file_size + void* buffer = Memory.mem_alloc( + file_size #ifdef DEBUG_MEMORY_NAME - ,"FILE in memory" + , "FILE in memory" #endif // DEBUG_MEMORY_NAME - ); + ); - int r_bytes = _read(file_handle,buffer,file_size); - R_ASSERT3 ( -// !file_size || -// (r_bytes && (file_size >= (u32)r_bytes)), - file_size == (u32)r_bytes, - "can't read from file : ", - file_name - ); + int r_bytes = _read(file_handle, buffer, file_size); + R_ASSERT3( + // !file_size || + // (r_bytes && (file_size >= (u32)r_bytes)), + file_size == (u32)r_bytes, + "can't read from file : ", + file_name + ); -// file_size = r_bytes; + // file_size = r_bytes; - R_ASSERT3 ( - !_close(file_handle), - "can't close file : ", - file_name - ); + R_ASSERT3( + !_close(file_handle), + "can't close file : ", + file_name + ); - return (buffer); + return (buffer); } -void *FileDownload (LPCSTR file_name, u32 *buffer_size) +void* FileDownload(LPCSTR file_name, u32* buffer_size) { - int file_handle; - R_ASSERT3 ( - file_handle_internal(file_name, *buffer_size, file_handle), - "can't open file : ", - file_name - ); + int file_handle; + R_ASSERT3( + file_handle_internal(file_name, *buffer_size, file_handle), + "can't open file : ", + file_name + ); - return (FileDownload(file_name, file_handle, *buffer_size)); + return (FileDownload(file_name, file_handle, *buffer_size)); } typedef char MARK[9]; IC void mk_mark(MARK& M, const char* S) -{ strncpy_s(M,sizeof(M),S,8); } +{ + strncpy_s(M, sizeof(M), S, 8); +} -void FileCompress (const char *fn, const char* sign, void* data, u32 size) +void FileCompress(const char* fn, const char* sign, void* data, u32 size) { - MARK M; mk_mark(M,sign); + MARK M; + mk_mark(M, sign); - int H = open(fn,O_BINARY|O_CREAT|O_WRONLY|O_TRUNC,S_IREAD|S_IWRITE); - R_ASSERT2(H>0,fn); - _write (H,&M,8); - _writeLZ(H,data,size); - _close (H); + int H = open(fn, O_BINARY | O_CREAT | O_WRONLY | O_TRUNC, S_IREAD | S_IWRITE); + R_ASSERT2(H > 0, fn); + _write(H, &M, 8); + _writeLZ(H, data, size); + _close(H); } -void* FileDecompress (const char *fn, const char* sign, u32* size) +void* FileDecompress(const char* fn, const char* sign, u32* size) { - MARK M,F; mk_mark(M,sign); + MARK M, F; + mk_mark(M, sign); - int H = open (fn,O_BINARY|O_RDONLY); - R_ASSERT2(H>0,fn); - _read (H,&F,8); - if (strncmp(M,F,8)!=0) { - F[8]=0; Msg("FATAL: signatures doesn't match, file(%s) / requested(%s)",F,sign); - } - R_ASSERT(strncmp(M,F,8)==0); + int H = open(fn, O_BINARY | O_RDONLY); + R_ASSERT2(H > 0, fn); + _read(H, &F, 8); + if (strncmp(M, F, 8) != 0) + { + F[8] = 0; + Msg("FATAL: signatures doesn't match, file(%s) / requested(%s)", F, sign); + } + R_ASSERT(strncmp(M, F, 8) == 0); - void* ptr = 0; u32 SZ; - SZ = _readLZ (H, ptr, filelength(H)-8); - _close (H); - if (size) *size = SZ; - return ptr; + void* ptr = 0; + u32 SZ; + SZ = _readLZ(H, ptr, filelength(H) - 8); + _close(H); + if (size) *size = SZ; + return ptr; } ////////////////////////////////////////////////////////////////////// @@ -210,143 +220,157 @@ void* FileDecompress (const char *fn, const char* sign, u32* size) ////////////////////////////////////////////////////////////////////// //--------------------------------------------------- // memory -CMemoryWriter::~CMemoryWriter() -{ xr_free(data); } +CMemoryWriter::~CMemoryWriter() +{ + xr_free(data); +} -void CMemoryWriter::w (const void* ptr, u32 count) +void CMemoryWriter::w(const void* ptr, u32 count) { - if (position+count > mem_size) { - // reallocate - if (mem_size==0) mem_size=128; - while (mem_size <= (position+count)) mem_size*=2; - if (0==data) data = (BYTE*) Memory.mem_alloc (mem_size + if (position + count > mem_size) + { + // reallocate + if (mem_size == 0) mem_size = 128; + while (mem_size <= (position + count)) mem_size *= 2; + if (0 == data) data = (BYTE*)Memory.mem_alloc(mem_size #ifdef DEBUG_MEMORY_NAME - , "CMemoryWriter - storage" + , "CMemoryWriter - storage" #endif // DEBUG_MEMORY_NAME - ); - else data = (BYTE*) Memory.mem_realloc (data,mem_size + ); + else data = (BYTE*)Memory.mem_realloc(data, mem_size #ifdef DEBUG_MEMORY_NAME - , "CMemoryWriter - storage" + , "CMemoryWriter - storage" #endif // DEBUG_MEMORY_NAME - ); - } - CopyMemory (data+position,ptr,count); - position +=count; - if (position>file_size) file_size=position; + ); + } + CopyMemory(data + position, ptr, count); + position += count; + if (position > file_size) file_size = position; } //static const u32 mb_sz = 0x1000000; -bool CMemoryWriter::save_to (LPCSTR fn) -{ - IWriter* F = FS.w_open(fn); - if (F){ - F->w (pointer(),size()); - FS.w_close (F); - return true; +bool CMemoryWriter::save_to(LPCSTR fn) +{ + IWriter* F = FS.w_open(fn); + if (F) + { + F->w(pointer(), size()); + FS.w_close(F); + return true; } return false; } -void IWriter::open_chunk (u32 type) +void IWriter::open_chunk(u32 type) { - w_u32(type); - chunk_pos.push(tell()); - w_u32(0); // the place for 'size' + w_u32(type); + chunk_pos.push(tell()); + w_u32(0); // the place for 'size' } -void IWriter::close_chunk () +void IWriter::close_chunk() { - VERIFY(!chunk_pos.empty()); + VERIFY(!chunk_pos.empty()); - int pos = tell(); - seek (chunk_pos.top()); - w_u32 (pos-chunk_pos.top()-4); - seek (pos); - chunk_pos.pop (); + int pos = tell(); + seek(chunk_pos.top()); + w_u32(pos - chunk_pos.top() - 4); + seek(pos); + chunk_pos.pop(); } -u32 IWriter::chunk_size () // returns size of currently opened chunk, 0 otherwise +u32 IWriter::chunk_size() // returns size of currently opened chunk, 0 otherwise { - if (chunk_pos.empty()) return 0; - return tell() - chunk_pos.top()-4; + if (chunk_pos.empty()) return 0; + return tell() - chunk_pos.top() - 4; } -void IWriter::w_compressed(void* ptr, u32 count) +void IWriter::w_compressed(void* ptr, u32 count) { - BYTE* dest = 0; - unsigned dest_sz = 0; - _compressLZ (&dest,&dest_sz,ptr,count); - -// if (g_dummy_stuff) -// g_dummy_stuff (dest,dest_sz,dest); + BYTE* dest = 0; + unsigned dest_sz = 0; + _compressLZ(&dest, &dest_sz, ptr, count); - if (dest && dest_sz) - w(dest,dest_sz); - xr_free (dest); + // if (g_dummy_stuff) + // g_dummy_stuff (dest,dest_sz,dest); + + if (dest && dest_sz) + w(dest, dest_sz); + xr_free(dest); } -void IWriter::w_chunk(u32 type, void* data, u32 size) +void IWriter::w_chunk(u32 type, void* data, u32 size) { - open_chunk (type); - if (type & CFS_CompressMark) w_compressed(data,size); - else w (data,size); - close_chunk (); + open_chunk(type); + if (type & CFS_CompressMark) w_compressed(data, size); + else w(data, size); + close_chunk(); } -void IWriter::w_sdir (const Fvector& D) +void IWriter::w_sdir(const Fvector& D) { - Fvector C; - float mag = D.magnitude(); - if (mag>EPS_S) { - C.div (D,mag); - } else { - C.set (0,0,1); - mag = 0; - } - w_dir (C); - w_float (mag); + Fvector C; + float mag = D.magnitude(); + if (mag > EPS_S) + { + C.div(D, mag); + } + else + { + C.set(0, 0, 1); + mag = 0; + } + w_dir(C); + w_float(mag); } -void IWriter::w_printf(const char* format, ...) +void IWriter::w_printf(const char* format, ...) { - va_list mark; - char buf[1024]; + va_list mark; + char buf[1024]; - va_start( mark , format ); -#ifndef _EDITOR - vsprintf_s( buf , format , mark ); + va_start(mark, format); +#ifndef _EDITOR + vsprintf_s(buf, format, mark); #else - vsprintf( buf , format , mark ); + vsprintf(buf, format, mark); #endif - va_end( mark ); + va_end(mark); - w ( buf, xr_strlen(buf) ); + w(buf, xr_strlen(buf)); } //--------------------------------------------------- // base stream -IReader* IReader::open_chunk(u32 ID) -{ - BOOL bCompressed; - - u32 dwSize = find_chunk(ID,&bCompressed); - if (dwSize!=0) { - if (bCompressed) { - BYTE* dest; - unsigned dest_sz; - _decompressLZ(&dest,&dest_sz,pointer(),dwSize); - return xr_new (dest, dest_sz, tell()+dwSize); - } else { - return xr_new (pointer(), dwSize, tell()+dwSize); - } - } else return 0; +IReader* IReader::open_chunk(u32 ID) +{ + BOOL bCompressed; + + u32 dwSize = find_chunk(ID, &bCompressed); + if (dwSize != 0) + { + if (bCompressed) + { + BYTE* dest; + unsigned dest_sz; + _decompressLZ(&dest, &dest_sz, pointer(), dwSize); + return xr_new(dest, dest_sz, tell() + dwSize); + } + else + { + return xr_new(pointer(), dwSize, tell() + dwSize); + } + } + else return 0; }; -void IReader::close() -{ xr_delete((IReader*)this); } +void IReader::close() +{ + xr_delete((IReader*)this); +} #include "FS_impl.h" #ifdef TESTING_IREADER IReaderTestPolicy::~IReaderTestPolicy() { - xr_delete(m_test); + xr_delete(m_test); }; #endif // TESTING_IREADER @@ -354,208 +378,221 @@ IReaderTestPolicy::~IReaderTestPolicy() find_chunk_counter g_find_chunk_counter; #endif // FIND_CHUNK_BENCHMARK_ENABLE -u32 IReader::find_chunk (u32 ID, BOOL* bCompressed) +u32 IReader::find_chunk(u32 ID, BOOL* bCompressed) { - return inherited::find_chunk(ID, bCompressed); + return inherited::find_chunk(ID, bCompressed); } -IReader* IReader::open_chunk_iterator (u32& ID, IReader* _prev) +IReader* IReader::open_chunk_iterator(u32& ID, IReader* _prev) { - if (0==_prev) { - // first - rewind (); - } else { - // next - seek (_prev->iterpos); - _prev->close(); - } + if (0 == _prev) + { + // first + rewind(); + } + else + { + // next + seek(_prev->iterpos); + _prev->close(); + } - // open - if (elapsed()<8) return NULL; - ID = r_u32 () ; - u32 _size = r_u32 () ; - if ( ID & CFS_CompressMark ) - { - // compressed - u8* dest ; - unsigned dest_sz ; - _decompressLZ (&dest,&dest_sz,pointer(),_size); - return xr_new (dest, dest_sz, tell()+_size); - } else { - // normal - return xr_new (pointer(), _size, tell()+_size); - } + // open + if (elapsed() < 8) return NULL; + ID = r_u32(); + u32 _size = r_u32(); + if (ID & CFS_CompressMark) + { + // compressed + u8* dest; + unsigned dest_sz; + _decompressLZ(&dest, &dest_sz, pointer(), _size); + return xr_new(dest, dest_sz, tell() + _size); + } + else + { + // normal + return xr_new(pointer(), _size, tell() + _size); + } } -void IReader::r (void *p,int cnt) +void IReader::r(void* p, int cnt) { - VERIFY (Pos+cnt<=Size); - CopyMemory (p,pointer(),cnt); - advance (cnt); + VERIFY(Pos + cnt <= Size); + CopyMemory(p, pointer(), cnt); + advance(cnt); #ifdef DEBUG - BOOL bShow = FALSE ; - if (dynamic_cast(this)) bShow = TRUE; - if (dynamic_cast(this)) bShow = TRUE; - if (bShow) { - FS.dwOpenCounter ++ ; - } + BOOL bShow = FALSE; + if (dynamic_cast(this)) bShow = TRUE; + if (dynamic_cast(this)) bShow = TRUE; + if (bShow) + { + FS.dwOpenCounter++; + } #endif }; -IC BOOL is_term (char a) { return (a==13)||(a==10); }; -IC u32 IReader::advance_term_string() +IC BOOL is_term(char a) { return (a == 13) || (a == 10); }; +IC u32 IReader::advance_term_string() { - u32 sz = 0; - char *src = (char *) data; - while (!eof()) { + u32 sz = 0; + char* src = (char*)data; + while (!eof()) + { Pos++; sz++; - if (!eof()&&is_term(src[Pos])) - { - while(!eof() && is_term(src[Pos])) - Pos++; - break; - } - } + if (!eof() && is_term(src[Pos])) + { + while (!eof() && is_term(src[Pos])) + Pos++; + break; + } + } return sz; } -void IReader::r_string (char *dest, u32 tgt_sz) +void IReader::r_string(char* dest, u32 tgt_sz) { - char *src = (char *) data+Pos; - u32 sz = advance_term_string(); - R_ASSERT2(sz<(tgt_sz-1),"Dest string less than needed."); - R_ASSERT (!IsBadReadPtr((void*)src,sz)); + char* src = (char*)data + Pos; + u32 sz = advance_term_string(); + R_ASSERT2(sz < (tgt_sz - 1), "Dest string less than needed."); + R_ASSERT(!IsBadReadPtr((void*)src, sz)); #ifdef _EDITOR - CopyMemory (dest,src,sz); + CopyMemory(dest, src, sz); #else - strncpy_s (dest,tgt_sz, src,sz); + strncpy_s(dest, tgt_sz, src, sz); #endif - dest[sz] = 0; + dest[sz] = 0; } -void IReader::r_string (xr_string& dest) +void IReader::r_string(xr_string& dest) { - char *src = (char *) data+Pos; - u32 sz = advance_term_string(); - dest.assign (src,sz); + char* src = (char*)data + Pos; + u32 sz = advance_term_string(); + dest.assign(src, sz); } -void IReader::r_stringZ (char *dest, u32 tgt_sz) +void IReader::r_stringZ(char* dest, u32 tgt_sz) { - char *src = (char *) data; - u32 sz = xr_strlen(src); - R_ASSERT2(sz chunk_pos; + xr_stack chunk_pos; public: - shared_str fName; + shared_str fName; public: - IWriter () - { - } - virtual ~IWriter () - { - R_ASSERT3 (chunk_pos.empty(),"Opened chunk not closed.",*fName); - } - - // kernel - virtual void seek (u32 pos) = 0; - virtual u32 tell () = 0; - - virtual void w (const void* ptr, u32 count) = 0; - - // generalized writing functions - IC void w_u64 (u64 d) { w(&d,sizeof(u64)); } - IC void w_u32 (u32 d) { w(&d,sizeof(u32)); } - IC void w_u16 (u16 d) { w(&d,sizeof(u16)); } - IC void w_u8 (u8 d) { w(&d,sizeof(u8)); } - IC void w_s64 (s64 d) { w(&d,sizeof(s64)); } - IC void w_s32 (s32 d) { w(&d,sizeof(s32)); } - IC void w_s16 (s16 d) { w(&d,sizeof(s16)); } - IC void w_s8 (s8 d) { w(&d,sizeof(s8)); } - IC void w_float (float d) { w(&d,sizeof(float));} - IC void w_string(const char *p) { w(p,(u32)xr_strlen(p));w_u8(13);w_u8(10); } - IC void w_stringZ(const char *p) { w(p,(u32)xr_strlen(p)+1); } - IC void w_stringZ(const shared_str& p) { w(*p?*p:"",p.size());w_u8(0); } - IC void w_stringZ(shared_str& p) { w(*p?*p:"",p.size());w_u8(0); } - IC void w_stringZ(const xr_string& p) { w(p.c_str()?p.c_str():"",(u32)p.size());w_u8(0); } - IC void w_fcolor(const Fcolor &v) { w(&v,sizeof(Fcolor)); } - IC void w_fvector4(const Fvector4 &v) { w(&v,sizeof(Fvector4)); } - IC void w_fvector3(const Fvector3 &v) { w(&v,sizeof(Fvector3)); } - IC void w_fvector2(const Fvector2 &v) { w(&v,sizeof(Fvector2)); } - IC void w_ivector4(const Ivector4 &v) { w(&v,sizeof(Ivector4)); } - IC void w_ivector3(const Ivector3 &v) { w(&v,sizeof(Ivector3)); } - IC void w_ivector2(const Ivector2 &v) { w(&v,sizeof(Ivector2)); } + IWriter() + { + } + virtual ~IWriter() + { + R_ASSERT3(chunk_pos.empty(), "Opened chunk not closed.", *fName); + } + + // kernel + virtual void seek(u32 pos) = 0; + virtual u32 tell() = 0; + + virtual void w(const void* ptr, u32 count) = 0; + + // generalized writing functions + IC void w_u64(u64 d) { w(&d, sizeof(u64)); } + IC void w_u32(u32 d) { w(&d, sizeof(u32)); } + IC void w_u16(u16 d) { w(&d, sizeof(u16)); } + IC void w_u8(u8 d) { w(&d, sizeof(u8)); } + IC void w_s64(s64 d) { w(&d, sizeof(s64)); } + IC void w_s32(s32 d) { w(&d, sizeof(s32)); } + IC void w_s16(s16 d) { w(&d, sizeof(s16)); } + IC void w_s8(s8 d) { w(&d, sizeof(s8)); } + IC void w_float(float d) { w(&d, sizeof(float)); } + IC void w_string(const char* p) { w(p, (u32)xr_strlen(p)); w_u8(13); w_u8(10); } + IC void w_stringZ(const char* p) { w(p, (u32)xr_strlen(p) + 1); } + IC void w_stringZ(const shared_str& p) { w(*p ? *p : "", p.size()); w_u8(0); } + IC void w_stringZ(shared_str& p) { w(*p ? *p : "", p.size()); w_u8(0); } + IC void w_stringZ(const xr_string& p) { w(p.c_str() ? p.c_str() : "", (u32)p.size()); w_u8(0); } + IC void w_fcolor(const Fcolor& v) { w(&v, sizeof(Fcolor)); } + IC void w_fvector4(const Fvector4& v) { w(&v, sizeof(Fvector4)); } + IC void w_fvector3(const Fvector3& v) { w(&v, sizeof(Fvector3)); } + IC void w_fvector2(const Fvector2& v) { w(&v, sizeof(Fvector2)); } + IC void w_ivector4(const Ivector4& v) { w(&v, sizeof(Ivector4)); } + IC void w_ivector3(const Ivector3& v) { w(&v, sizeof(Ivector3)); } + IC void w_ivector2(const Ivector2& v) { w(&v, sizeof(Ivector2)); } // quant writing functions - IC void w_float_q16 (float a, float min, float max) - { - VERIFY (a>=min && a<=max); - float q = (a-min)/(max-min); - w_u16 (u16(iFloor(q*65535.f+.5f))); - } - IC void w_float_q8 (float a, float min, float max) - { - VERIFY (a>=min && a<=max); - float q = (a-min)/(max-min); - w_u8 (u8(iFloor(q*255.f+.5f))); - } - IC void w_angle16 (float a) { w_float_q16 (angle_normalize(a),0,PI_MUL_2);} - IC void w_angle8 (float a) { w_float_q8 (angle_normalize(a),0,PI_MUL_2);} - IC void w_dir (const Fvector& D) { w_u16(pvCompress(D)); } - void w_sdir (const Fvector& D); - void __cdecl w_printf (const char* format, ...); - - // generalized chunking - u32 align (); - void open_chunk (u32 type); - void close_chunk (); - u32 chunk_size (); // returns size of currently opened chunk, 0 otherwise - void w_compressed(void* ptr, u32 count); - void w_chunk (u32 type, void* data, u32 size); - virtual bool valid () {return true;} - virtual void flush () = 0; + IC void w_float_q16(float a, float min, float max) + { + VERIFY(a >= min && a <= max); + float q = (a - min) / (max - min); + w_u16(u16(iFloor(q*65535.f + .5f))); + } + IC void w_float_q8(float a, float min, float max) + { + VERIFY(a >= min && a <= max); + float q = (a - min) / (max - min); + w_u8(u8(iFloor(q*255.f + .5f))); + } + IC void w_angle16(float a) { w_float_q16(angle_normalize(a), 0, PI_MUL_2); } + IC void w_angle8(float a) { w_float_q8(angle_normalize(a), 0, PI_MUL_2); } + IC void w_dir(const Fvector& D) { w_u16(pvCompress(D)); } + void w_sdir(const Fvector& D); + void __cdecl w_printf(const char* format, ...); + + // generalized chunking + u32 align(); + void open_chunk(u32 type); + void close_chunk(); + u32 chunk_size(); // returns size of currently opened chunk, 0 otherwise + void w_compressed(void* ptr, u32 count); + void w_chunk(u32 type, void* data, u32 size); + virtual bool valid() { return true; } + virtual void flush() = 0; }; class XRCORE_API CMemoryWriter : public IWriter { - u8* data; - u32 position; - u32 mem_size; - u32 file_size; + u8* data; + u32 position; + u32 mem_size; + u32 file_size; public: - CMemoryWriter() { - data = 0; - position = 0; - mem_size = 0; - file_size = 0; - } - virtual ~CMemoryWriter(); - - // kernel - virtual void w (const void* ptr, u32 count); - - virtual void seek (u32 pos) { position = pos; } - virtual u32 tell () { return position; } - - // specific - IC u8* pointer () { return data; } - IC u32 size () const { return file_size; } - IC void clear () { file_size=0; position=0; } + CMemoryWriter() + { + data = 0; + position = 0; + mem_size = 0; + file_size = 0; + } + virtual ~CMemoryWriter(); + + // kernel + virtual void w(const void* ptr, u32 count); + + virtual void seek(u32 pos) { position = pos; } + virtual u32 tell() { return position; } + + // specific + IC u8* pointer() { return data; } + IC u32 size() const { return file_size; } + IC void clear() { file_size = 0; position = 0; } #pragma warning(push) #pragma warning(disable:4995) - IC void free () { file_size=0; position=0; mem_size=0; xr_free(data); } + IC void free() { file_size = 0; position = 0; mem_size = 0; xr_free(data); } #pragma warning(pop) - bool save_to (LPCSTR fn); - virtual void flush () { }; + bool save_to(LPCSTR fn); + virtual void flush() { }; }; //------------------------------------------------------------------------------------ @@ -142,9 +143,9 @@ struct IReaderBase_Test; struct XRCORE_API IReaderTestPolicy { - IReaderBase_Test* m_test; - IReaderTestPolicy() { m_test = NULL; } - ~IReaderTestPolicy(); // defined in FS.cpp + IReaderBase_Test* m_test; + IReaderTestPolicy() { m_test = NULL; } + ~IReaderTestPolicy(); // defined in FS.cpp }; #endif // TESTING_IREADER @@ -152,168 +153,175 @@ template class IReaderBase #ifdef TESTING_IREADER - : public IReaderTestPolicy // inheriting + : public IReaderTestPolicy // inheriting #endif //TESTING_IREADER { public: - IC IReaderBase () : m_last_pos (0) {} - virtual ~IReaderBase() {} - - IC implementation_type&impl () {return *(implementation_type*)this;} - IC const implementation_type&impl() const {return *(implementation_type*)this;} - - IC BOOL eof () const {return impl().elapsed()<=0; }; - - IC void r (void *p,int cnt) {impl().r(p,cnt);} - - IC Fvector r_vec3 () {Fvector tmp;r(&tmp,3*sizeof(float));return tmp; }; - IC Fvector4 r_vec4 () {Fvector4 tmp;r(&tmp,4*sizeof(float));return tmp; }; - IC u64 r_u64 () { u64 tmp; r(&tmp,sizeof(tmp)); return tmp; }; - IC u32 r_u32 () { u32 tmp; r(&tmp,sizeof(tmp)); return tmp; }; - IC u16 r_u16 () { u16 tmp; r(&tmp,sizeof(tmp)); return tmp; }; - IC u8 r_u8 () { u8 tmp; r(&tmp,sizeof(tmp)); return tmp; }; - IC s64 r_s64 () { s64 tmp; r(&tmp,sizeof(tmp)); return tmp; }; - IC s32 r_s32 () { s32 tmp; r(&tmp,sizeof(tmp)); return tmp; }; - IC s16 r_s16 () { s16 tmp; r(&tmp,sizeof(tmp)); return tmp; }; - IC s8 r_s8 () { s8 tmp; r(&tmp,sizeof(tmp)); return tmp; }; - IC float r_float () { float tmp; r(&tmp,sizeof(tmp)); return tmp; }; - IC void r_fvector4 (Fvector4 &v){ r(&v,sizeof(Fvector4)); } - IC void r_fvector3 (Fvector3 &v){ r(&v,sizeof(Fvector3)); } - IC void r_fvector2 (Fvector2 &v){ r(&v,sizeof(Fvector2)); } - IC void r_ivector4 (Ivector4 &v){ r(&v,sizeof(Ivector4)); } - IC void r_ivector4 (Ivector3 &v){ r(&v,sizeof(Ivector3)); } - IC void r_ivector4 (Ivector2 &v){ r(&v,sizeof(Ivector2)); } - IC void r_fcolor (Fcolor &v) { r(&v,sizeof(Fcolor)); } - - IC float r_float_q16 (float min, float max) - { - u16 val = r_u16(); - float A = (float(val)*(max-min))/65535.f + min; // floating-point-error possible - VERIFY ((A >= min-EPS_S) && (A <= max+EPS_S)); + IC IReaderBase() : m_last_pos(0) {} + virtual ~IReaderBase() {} + + IC implementation_type& impl() { return *(implementation_type*)this; } + IC const implementation_type& impl() const { return *(implementation_type*)this; } + + IC BOOL eof() const { return impl().elapsed() <= 0; }; + + IC void r(void* p, int cnt) { impl().r(p, cnt); } + + IC Fvector r_vec3() { Fvector tmp; r(&tmp, 3 * sizeof(float)); return tmp; }; + IC Fvector4 r_vec4() { Fvector4 tmp; r(&tmp, 4 * sizeof(float)); return tmp; }; + IC u64 r_u64() { u64 tmp; r(&tmp, sizeof(tmp)); return tmp; }; + IC u32 r_u32() { u32 tmp; r(&tmp, sizeof(tmp)); return tmp; }; + IC u16 r_u16() { u16 tmp; r(&tmp, sizeof(tmp)); return tmp; }; + IC u8 r_u8() { u8 tmp; r(&tmp, sizeof(tmp)); return tmp; }; + IC s64 r_s64() { s64 tmp; r(&tmp, sizeof(tmp)); return tmp; }; + IC s32 r_s32() { s32 tmp; r(&tmp, sizeof(tmp)); return tmp; }; + IC s16 r_s16() { s16 tmp; r(&tmp, sizeof(tmp)); return tmp; }; + IC s8 r_s8() { s8 tmp; r(&tmp, sizeof(tmp)); return tmp; }; + IC float r_float() { float tmp; r(&tmp, sizeof(tmp)); return tmp; }; + IC void r_fvector4(Fvector4& v) { r(&v, sizeof(Fvector4)); } + IC void r_fvector3(Fvector3& v) { r(&v, sizeof(Fvector3)); } + IC void r_fvector2(Fvector2& v) { r(&v, sizeof(Fvector2)); } + IC void r_ivector4(Ivector4& v) { r(&v, sizeof(Ivector4)); } + IC void r_ivector4(Ivector3& v) { r(&v, sizeof(Ivector3)); } + IC void r_ivector4(Ivector2& v) { r(&v, sizeof(Ivector2)); } + IC void r_fcolor(Fcolor& v) { r(&v, sizeof(Fcolor)); } + + IC float r_float_q16(float min, float max) + { + u16 val = r_u16(); + float A = (float(val)*(max - min)) / 65535.f + min; // floating-point-error possible + VERIFY((A >= min - EPS_S) && (A <= max + EPS_S)); return A; - } - IC float r_float_q8 (float min, float max) - { - u8 val = r_u8(); - float A = (float(val)/255.0001f) *(max-min) + min; // floating-point-error possible - VERIFY ((A >= min) && (A <= max)); - return A; - } - IC float r_angle16 () { return r_float_q16(0,PI_MUL_2); } - IC float r_angle8 () { return r_float_q8 (0,PI_MUL_2); } - IC void r_dir (Fvector& A){ u16 t=r_u16(); pvDecompress(A,t); } - IC void r_sdir (Fvector& A) - { - u16 t = r_u16(); - float s = r_float(); - pvDecompress(A,t); - A.mul (s); - } - // Set file pointer to start of chunk data (0 for root chunk) - IC void rewind () { impl().seek(0); } - - u32 find_chunk (u32 ID, BOOL* bCompressed); - - IC BOOL r_chunk (u32 ID, void *dest) // ÷òåíèå XR Chunk'îâ (4b-ID,4b-size,??b-data) - { - u32 dwSize = ((implementation_type*)this)->find_chunk(ID); - if (dwSize!=0) { - r(dest,dwSize); - return TRUE; - } else return FALSE; - } - - IC BOOL r_chunk_safe(u32 ID, void *dest, u32 dest_size) // ÷òåíèå XR Chunk'îâ (4b-ID,4b-size,??b-data) - { - u32 dwSize = ((implementation_type*)this)->find_chunk(ID); - if (dwSize!=0) { - R_ASSERT(dwSize==dest_size); - r(dest,dwSize); - return TRUE; - } else return FALSE; - } + } + IC float r_float_q8(float min, float max) + { + u8 val = r_u8(); + float A = (float(val) / 255.0001f) *(max - min) + min; // floating-point-error possible + VERIFY((A >= min) && (A <= max)); + return A; + } + IC float r_angle16() { return r_float_q16(0, PI_MUL_2); } + IC float r_angle8() { return r_float_q8(0, PI_MUL_2); } + IC void r_dir(Fvector& A) { u16 t = r_u16(); pvDecompress(A, t); } + IC void r_sdir(Fvector& A) + { + u16 t = r_u16(); + float s = r_float(); + pvDecompress(A, t); + A.mul(s); + } + // Set file pointer to start of chunk data (0 for root chunk) + IC void rewind() { impl().seek(0); } + + u32 find_chunk(u32 ID, BOOL* bCompressed); + + IC BOOL r_chunk(u32 ID, void* dest) // ÷òåíèå XR Chunk'îâ (4b-ID,4b-size,??b-data) + { + u32 dwSize = ((implementation_type*)this)->find_chunk(ID); + if (dwSize != 0) + { + r(dest, dwSize); + return TRUE; + } + else return FALSE; + } + + IC BOOL r_chunk_safe(u32 ID, void* dest, u32 dest_size) // ÷òåíèå XR Chunk'îâ (4b-ID,4b-size,??b-data) + { + u32 dwSize = ((implementation_type*)this)->find_chunk(ID); + if (dwSize != 0) + { + R_ASSERT(dwSize == dest_size); + r(dest, dwSize); + return TRUE; + } + else return FALSE; + } private: - u32 m_last_pos; + u32 m_last_pos; }; -class XRCORE_API IReader : public IReaderBase { +class XRCORE_API IReader : public IReaderBase < IReader > +{ protected: - char * data ; - int Pos ; - int Size ; - int iterpos ; + char* data; + int Pos; + int Size; + int iterpos; public: - IC IReader () - { - Pos = 0; - } + IC IReader() + { + Pos = 0; + } - virtual ~IReader () {} + virtual ~IReader() {} - IC IReader (void *_data, int _size, int _iterpos=0) - { - data = (char *)_data ; - Size = _size ; - Pos = 0 ; - iterpos = _iterpos ; - } + IC IReader(void* _data, int _size, int _iterpos = 0) + { + data = (char*)_data; + Size = _size; + Pos = 0; + iterpos = _iterpos; + } protected: - IC u32 correction (u32 p) - { - if (p%16) { - return ((p%16)+1)*16 - p; - } return 0; - } - - u32 advance_term_string (); + IC u32 correction(u32 p) + { + if (p % 16) + { + return ((p % 16) + 1) * 16 - p; + } + return 0; + } + + u32 advance_term_string(); public: - IC int elapsed () const { return Size-Pos; }; - IC int tell () const { return Pos; }; - IC void seek (int ptr) { Pos=ptr; VERIFY((Pos<=Size) && (Pos>=0));}; - IC int length () const { return Size; }; - IC void* pointer () const { return &(data[Pos]); }; - IC void advance (int cnt) { Pos+=cnt;VERIFY((Pos<=Size) && (Pos>=0));}; + IC int elapsed() const { return Size - Pos; }; + IC int tell() const { return Pos; }; + IC void seek(int ptr) { Pos = ptr; VERIFY((Pos <= Size) && (Pos >= 0)); }; + IC int length() const { return Size; }; + IC void* pointer() const { return &(data[Pos]); }; + IC void advance(int cnt) { Pos += cnt; VERIFY((Pos <= Size) && (Pos >= 0)); }; public: - void r (void *p,int cnt); + void r(void* p, int cnt); - void r_string (char *dest, u32 tgt_sz); - void r_string (xr_string& dest); + void r_string(char* dest, u32 tgt_sz); + void r_string(xr_string& dest); - void skip_stringZ(); + void skip_stringZ(); - void r_stringZ (char *dest, u32 tgt_sz); - void r_stringZ (shared_str& dest); - void r_stringZ (xr_string& dest); + void r_stringZ(char* dest, u32 tgt_sz); + void r_stringZ(shared_str& dest); + void r_stringZ(xr_string& dest); public: - void close (); + void close(); public: - // ïîèñê XR Chunk'îâ - âîçâðàò - ðàçìåð èëè 0 - IReader* open_chunk (u32 ID); + // ïîèñê XR Chunk'îâ - âîçâðàò - ðàçìåð èëè 0 + IReader* open_chunk(u32 ID); - // iterators - IReader* open_chunk_iterator (u32& ID, IReader* previous=NULL); // NULL=first + // iterators + IReader* open_chunk_iterator(u32& ID, IReader* previous = NULL); // NULL=first - u32 find_chunk (u32 ID, BOOL* bCompressed = 0); + u32 find_chunk(u32 ID, BOOL* bCompressed = 0); private: - typedef IReaderBase inherited; + typedef IReaderBase inherited; }; class XRCORE_API CVirtualFileRW : public IReader { private: - void *hSrcFile, *hSrcMap; + void* hSrcFile, *hSrcMap; public: - CVirtualFileRW (const char *cFileName); - virtual ~CVirtualFileRW (); + CVirtualFileRW(const char* cFileName); + virtual ~CVirtualFileRW(); }; #endif // fsH diff --git a/src/xrCore/FS_impl.h b/src/xrCore/FS_impl.h index 34f32ea03ea..5eac40b5cf7 100644 --- a/src/xrCore/FS_impl.h +++ b/src/xrCore/FS_impl.h @@ -11,29 +11,29 @@ //#define FIND_CHUNK_VEC //#define FIND_CHUNK_MAP -// Uncomment to log time of find_chunk (search +// Uncomment to log time of find_chunk (search //#define FIND_CHUNK_BENCHMARK_ENABLE #ifdef FIND_CHUNK_BENCHMARK_ENABLE struct find_chunk_counter { - CTimer timer; - - u64 ticks; - u32 calls; - - find_chunk_counter() - { - ticks = 0; - calls = 0; - } - - void flush () - { - float secs = (float)ticks / CPU::qpc_freq; - Msg("find_chunk sec: %f", secs); - } + CTimer timer; + + u64 ticks; + u32 calls; + + find_chunk_counter() + { + ticks = 0; + calls = 0; + } + + void flush () + { + float secs = (float)ticks / CPU::qpc_freq; + Msg("find_chunk sec: %f", secs); + } }; #ifdef INCLUDE_FROM_ENGINE @@ -46,54 +46,57 @@ extern bool g_initialize_cpu_called; struct find_chunk_auto_timer { - find_chunk_auto_timer() - { - if ( g_initialize_cpu_called ) - { - g_find_chunk_counter.timer.Start(); - } - } - - ~find_chunk_auto_timer() - { - if ( g_initialize_cpu_called ) - { - g_find_chunk_counter.ticks += g_find_chunk_counter.timer.GetElapsed_ticks(); - } - } + find_chunk_auto_timer() + { + if ( g_initialize_cpu_called ) + { + g_find_chunk_counter.timer.Start(); + } + } + + ~find_chunk_auto_timer() + { + if ( g_initialize_cpu_called ) + { + g_find_chunk_counter.ticks += g_find_chunk_counter.timer.GetElapsed_ticks(); + } + } }; #endif // FIND_CHUNK_BENCHMARK_ENABLE #ifdef FIND_CHUNK_STD -struct IReaderBase_Test { +struct IReaderBase_Test +{ }; template -IC u32 IReaderBase::find_chunk (u32 ID, BOOL* bCompressed) +IC u32 IReaderBase::find_chunk (u32 ID, BOOL* bCompressed) { #ifdef FIND_CHUNK_BENCHMARK_ENABLE - find_chunk_auto_timer timer; + find_chunk_auto_timer timer; #endif // FIND_CHUNK_BENCHMARK_ENABLE - u32 dwSize,dwType; + u32 dwSize,dwType; - rewind(); - while (!eof()) { - dwType = r_u32(); - dwSize = r_u32(); - if ((dwType&(~CFS_CompressMark)) == ID) { + rewind(); + while (!eof()) + { + dwType = r_u32(); + dwSize = r_u32(); + if ((dwType&(~CFS_CompressMark)) == ID) + { - VERIFY ((u32)impl().tell() + dwSize <= (u32)impl().length()); - if (bCompressed) *bCompressed = dwType&CFS_CompressMark; - return dwSize; - } - else impl().advance(dwSize); - } + VERIFY ((u32)impl().tell() + dwSize <= (u32)impl().length()); + if (bCompressed) *bCompressed = dwType&CFS_CompressMark; + return dwSize; + } + else impl().advance(dwSize); + } - return 0; + return 0; } #endif // #ifdef FIND_CHUNK_STD @@ -104,67 +107,67 @@ struct IReaderBase_Test {}; #pragma warning (disable:4701) template -IC u32 IReaderBase::find_chunk (u32 ID, BOOL* bCompressed) +IC u32 IReaderBase::find_chunk (u32 ID, BOOL* bCompressed) { #ifdef FIND_CHUNK_BENCHMARK_ENABLE - find_chunk_auto_timer timer; + find_chunk_auto_timer timer; #endif // FIND_CHUNK_BENCHMARK_ENABLE - u32 dwSize, dwType; - - bool success = false; - - if ( m_last_pos != 0 ) - { - impl().seek(m_last_pos); - dwType = r_u32(); - dwSize = r_u32(); - - if ( (dwType & (~CFS_CompressMark)) == ID ) - { - success = true; - } - } - - if ( !success ) - { - rewind(); - while ( !eof() ) - { - dwType = r_u32(); - dwSize = r_u32(); - if ( (dwType & (~CFS_CompressMark)) == ID ) - { - success = true; - break; - } - else - { - impl().advance(dwSize); - } - } - - if ( !success ) - { - m_last_pos = 0; - return 0; - } - } - - VERIFY ((u32)impl().tell() + dwSize <= (u32)impl().length()); - if (bCompressed) *bCompressed = dwType & CFS_CompressMark; - - const int dwPos = impl().tell(); - if ( dwPos + dwSize < (u32)impl().length() ) - { - m_last_pos = dwPos + dwSize; - } - else - { - m_last_pos = 0; - } - - return dwSize; + u32 dwSize, dwType; + + bool success = false; + + if (m_last_pos != 0) + { + impl().seek(m_last_pos); + dwType = r_u32(); + dwSize = r_u32(); + + if ((dwType & (~CFS_CompressMark)) == ID) + { + success = true; + } + } + + if (!success) + { + rewind(); + while (!eof()) + { + dwType = r_u32(); + dwSize = r_u32(); + if ((dwType & (~CFS_CompressMark)) == ID) + { + success = true; + break; + } + else + { + impl().advance(dwSize); + } + } + + if (!success) + { + m_last_pos = 0; + return 0; + } + } + + VERIFY((u32)impl().tell() + dwSize <= (u32)impl().length()); + if (bCompressed) *bCompressed = dwType & CFS_CompressMark; + + const int dwPos = impl().tell(); + if (dwPos + dwSize < (u32)impl().length()) + { + m_last_pos = dwPos + dwSize; + } + else + { + m_last_pos = 0; + } + + return dwSize; } #pragma warning (default:4701) @@ -175,67 +178,68 @@ IC u32 IReaderBase::find_chunk (u32 ID, BOOL* bCompressed) #include "../xrServerEntities/associative_vector.h" -struct IReaderBase_Test { +struct IReaderBase_Test +{ - typedef associative_vector id2pos_container; - id2pos_container id2pos; + typedef associative_vector id2pos_container; + id2pos_container id2pos; }; template -IC u32 IReaderBase::find_chunk (u32 ID, BOOL* bCompressed) +IC u32 IReaderBase::find_chunk (u32 ID, BOOL* bCompressed) { #ifdef FIND_CHUNK_BENCHMARK_ENABLE - find_chunk_auto_timer timer; + find_chunk_auto_timer timer; #endif // FIND_CHUNK_BENCHMARK_ENABLE - u32 dwSize, dwType; - - if ( !m_test ) - { - m_test = xr_new(); - - rewind(); - int num_chunks = 0; - while (!eof()) - { - r_u32(); - impl().advance(r_u32()); - ++num_chunks; - } - - ((std::vector< std::pair >*)&m_test->id2pos)->reserve(num_chunks); - - rewind(); - while ( !eof() ) - { - u32 dwPos = impl().tell(); - - dwType = r_u32(); - dwSize = r_u32(); - - u32 dwId = dwType & (~CFS_CompressMark); - VERIFY ((u32)impl().tell() + dwSize <= (u32)impl().length()); - - m_test->id2pos.insert( IReaderBase_Test::id2pos_container::value_type(dwId, dwPos) ); - - impl().advance(dwSize); - } - } - - IReaderBase_Test::id2pos_container::iterator it = m_test->id2pos.find(ID); - if ( it != m_test->id2pos.end() ) - { - impl().seek(it->second); - dwType = r_u32(); - dwSize = r_u32(); - - VERIFY ( (dwType&(~CFS_CompressMark)) == ID ); - - if ( bCompressed ) *bCompressed = dwType & CFS_CompressMark; - return dwSize; - } - - return 0; + u32 dwSize, dwType; + + if ( !m_test ) + { + m_test = xr_new(); + + rewind(); + int num_chunks = 0; + while (!eof()) + { + r_u32(); + impl().advance(r_u32()); + ++num_chunks; + } + + ((std::vector< std::pair >*)&m_test->id2pos)->reserve(num_chunks); + + rewind(); + while ( !eof() ) + { + u32 dwPos = impl().tell(); + + dwType = r_u32(); + dwSize = r_u32(); + + u32 dwId = dwType & (~CFS_CompressMark); + VERIFY ((u32)impl().tell() + dwSize <= (u32)impl().length()); + + m_test->id2pos.insert( IReaderBase_Test::id2pos_container::value_type(dwId, dwPos) ); + + impl().advance(dwSize); + } + } + + IReaderBase_Test::id2pos_container::iterator it = m_test->id2pos.find(ID); + if ( it != m_test->id2pos.end() ) + { + impl().seek(it->second); + dwType = r_u32(); + dwSize = r_u32(); + + VERIFY ( (dwType&(~CFS_CompressMark)) == ID ); + + if ( bCompressed ) *bCompressed = dwType & CFS_CompressMark; + return dwSize; + } + + return 0; } #endif // #ifdef FIND_CHUNK_VEC @@ -244,71 +248,72 @@ IC u32 IReaderBase::find_chunk (u32 ID, BOOL* bCompressed) #include "../xrServerEntities/associative_vector.h" -struct IReaderBase_Test { +struct IReaderBase_Test +{ - typedef xr_hash_map id2pos_container; + typedef xr_hash_map id2pos_container; - id2pos_container id2pos; - u32 last_pos; + id2pos_container id2pos; + u32 last_pos; }; template -IC u32 IReaderBase::find_chunk (u32 ID, BOOL* bCompressed) +IC u32 IReaderBase::find_chunk (u32 ID, BOOL* bCompressed) { #ifdef FIND_CHUNK_BENCHMARK_ENABLE - find_chunk_auto_timer timer; + find_chunk_auto_timer timer; #endif // FIND_CHUNK_BENCHMARK_ENABLE - u32 dwSize, dwType; + u32 dwSize, dwType; - if ( !m_test ) - { - m_test = xr_new(); - m_test->last_pos = 0; - } + if ( !m_test ) + { + m_test = xr_new(); + m_test->last_pos = 0; + } - IReaderBase_Test::id2pos_container::iterator it = m_test->id2pos.find(ID); - if ( it != m_test->id2pos.end() ) - { - impl().seek(it->second); - dwType = r_u32(); - dwSize = r_u32(); + IReaderBase_Test::id2pos_container::iterator it = m_test->id2pos.find(ID); + if ( it != m_test->id2pos.end() ) + { + impl().seek(it->second); + dwType = r_u32(); + dwSize = r_u32(); - VERIFY ( (dwType&(~CFS_CompressMark)) == ID ); + VERIFY ( (dwType&(~CFS_CompressMark)) == ID ); - if ( bCompressed ) *bCompressed = dwType & CFS_CompressMark; - return dwSize; - } + if ( bCompressed ) *bCompressed = dwType & CFS_CompressMark; + return dwSize; + } - impl().seek(m_test->last_pos); - while ( !eof() ) - { - u32 dwPos = impl().tell(); + impl().seek(m_test->last_pos); + while ( !eof() ) + { + u32 dwPos = impl().tell(); - dwType = r_u32(); - dwSize = r_u32(); + dwType = r_u32(); + dwSize = r_u32(); - VERIFY((u32)impl().tell() + dwSize <= (u32)impl().length()); + VERIFY((u32)impl().tell() + dwSize <= (u32)impl().length()); - u32 dwId = dwType & (~CFS_CompressMark); + u32 dwId = dwType & (~CFS_CompressMark); - m_test->id2pos.insert( IReaderBase_Test::id2pos_container::value_type(dwId, dwPos) ); + m_test->id2pos.insert( IReaderBase_Test::id2pos_container::value_type(dwId, dwPos) ); - if ( dwId == ID ) - { - if (bCompressed) *bCompressed = dwType&CFS_CompressMark; + if ( dwId == ID ) + { + if (bCompressed) *bCompressed = dwType&CFS_CompressMark; - m_test->last_pos = impl().tell() + dwSize; - return dwSize; - } - else - { - impl().advance(dwSize); - } - } + m_test->last_pos = impl().tell() + dwSize; + return dwSize; + } + else + { + impl().advance(dwSize); + } + } - m_test->last_pos = impl().tell(); - return 0; + m_test->last_pos = impl().tell(); + return 0; } #endif // #ifdef FIND_CHUNK_MAP diff --git a/src/xrCore/FS_internal.h b/src/xrCore/FS_internal.h index 3aace297392..bb03a8bedc8 100644 --- a/src/xrCore/FS_internal.h +++ b/src/xrCore/FS_internal.h @@ -8,102 +8,110 @@ #include #include -void* FileDownload (LPCSTR fn, u32* pdwSize=NULL); -void FileCompress (const char *fn, const char* sign, void* data, u32 size); -void * FileDecompress (const char *fn, const char* sign, u32* size=NULL); +void* FileDownload(LPCSTR fn, u32* pdwSize = NULL); +void FileCompress(const char* fn, const char* sign, void* data, u32 size); +void* FileDecompress(const char* fn, const char* sign, u32* size = NULL); class CFileWriter : public IWriter { private: - FILE* hf; + FILE* hf; public: - CFileWriter (const char *name, bool exclusive) - { - R_ASSERT (name && name[0]); - fName = name; - VerifyPath (*fName); - if (exclusive){ - int handle = _sopen(*fName,_O_WRONLY|_O_TRUNC|_O_CREAT|_O_BINARY,SH_DENYWR); + CFileWriter(const char* name, bool exclusive) + { + R_ASSERT(name && name[0]); + fName = name; + VerifyPath(*fName); + if (exclusive) + { + int handle = _sopen(*fName,_O_WRONLY|_O_TRUNC|_O_CREAT|_O_BINARY,SH_DENYWR); #ifdef _EDITOR - if (handle==-1) - Msg ("!Can't create file: '%s'. Error: '%s'.",*fName,_sys_errlist[errno]); + if (handle==-1) + Msg("!Can't create file: '%s'. Error: '%s'.", *fName, _sys_errlist[errno]); #endif - hf = _fdopen(handle,"wb"); - }else{ - hf = fopen(*fName,"wb"); - if (hf==0) - Msg ("!Can't write file: '%s'. Error: '%s'.",*fName,_sys_errlist[errno]); - } - } + hf = _fdopen(handle, "wb"); + } + else + { + hf = fopen(*fName, "wb"); + if (hf == 0) + Msg("!Can't write file: '%s'. Error: '%s'.", *fName, _sys_errlist[errno]); + } + } - virtual ~CFileWriter() - { - if (0!=hf){ - fclose (hf); - // release RO attrib - DWORD dwAttr = GetFileAttributes(*fName); - if ((dwAttr != u32(-1))&&(dwAttr&FILE_ATTRIBUTE_READONLY)){ - dwAttr &=~ FILE_ATTRIBUTE_READONLY; + virtual ~CFileWriter() + { + if (0 != hf) + { + fclose(hf); + // release RO attrib + DWORD dwAttr = GetFileAttributes(*fName); + if ((dwAttr != u32(-1)) && (dwAttr&FILE_ATTRIBUTE_READONLY)) + { + dwAttr &= ~FILE_ATTRIBUTE_READONLY; SetFileAttributes(*fName, dwAttr); } } - } - // kernel - virtual void w (const void* _ptr, u32 count) - { - if ((0!=hf) && (0!=count)){ - const u32 mb_sz = 0x1000000; - u8* ptr = (u8*)_ptr; - int req_size; - for (req_size = count; req_size>mb_sz; req_size-=mb_sz, ptr+=mb_sz){ - size_t W = fwrite(ptr,mb_sz,1,hf); - R_ASSERT3(W==1,"Can't write mem block to file. Disk maybe full.",_sys_errlist[errno]); - } - if (req_size) { - size_t W = fwrite(ptr,req_size,1,hf); - R_ASSERT3(W==1,"Can't write mem block to file. Disk maybe full.",_sys_errlist[errno]); - } - } + } + // kernel + virtual void w(const void* _ptr, u32 count) + { + if ((0 != hf) && (0 != count)) + { + const u32 mb_sz = 0x1000000; + u8* ptr = (u8*)_ptr; + int req_size; + for (req_size = count; req_size > mb_sz; req_size -= mb_sz, ptr += mb_sz) + { + size_t W = fwrite(ptr, mb_sz, 1, hf); + R_ASSERT3(W == 1, "Can't write mem block to file. Disk maybe full.", _sys_errlist[errno]); + } + if (req_size) + { + size_t W = fwrite(ptr, req_size, 1, hf); + R_ASSERT3(W == 1, "Can't write mem block to file. Disk maybe full.", _sys_errlist[errno]); + } + } }; - virtual void seek (u32 pos) { if (0!=hf) fseek(hf,pos,SEEK_SET); }; - virtual u32 tell () { return (0!=hf)?ftell(hf):0; }; - virtual bool valid () { return (0!=hf);} - virtual void flush () { if (hf) fflush(hf); }; + virtual void seek(u32 pos) { if (0 != hf) fseek(hf, pos, SEEK_SET); }; + virtual u32 tell() { return (0 != hf) ? ftell(hf) : 0; }; + virtual bool valid() { return (0 != hf); } + virtual void flush() { if (hf) fflush(hf); }; }; // It automatically frees memory after destruction class CTempReader : public IReader { public: - CTempReader(void *_data, int _size, int _iterpos) : IReader(_data,_size,_iterpos) {} - virtual ~CTempReader(); + CTempReader(void* _data, int _size, int _iterpos) : IReader(_data, _size, _iterpos) {} + virtual ~CTempReader(); }; class CPackReader : public IReader { - void* base_address; + void* base_address; public: - CPackReader(void* _base, void* _data, int _size) : IReader(_data,_size){base_address=_base;} - virtual ~CPackReader(); + CPackReader(void* _base, void* _data, int _size) : IReader(_data, _size) { base_address = _base; } + virtual ~CPackReader(); }; class XRCORE_API CFileReader : public IReader { public: - CFileReader(const char *name); - virtual ~CFileReader(); + CFileReader(const char* name); + virtual ~CFileReader(); }; class CCompressedReader : public IReader { public: - CCompressedReader(const char *name, const char *sign); - virtual ~CCompressedReader(); + CCompressedReader(const char* name, const char* sign); + virtual ~CCompressedReader(); }; class CVirtualFileReader : public IReader { private: - void *hSrcFile, *hSrcMap; + void* hSrcFile, *hSrcMap; public: - CVirtualFileReader(const char *cFileName); - virtual ~CVirtualFileReader(); + CVirtualFileReader(const char* cFileName); + virtual ~CVirtualFileReader(); }; #endif \ No newline at end of file diff --git a/src/xrCore/FTimer.cpp b/src/xrCore/FTimer.cpp index ad66b1be1e5..86875d75258 100644 --- a/src/xrCore/FTimer.cpp +++ b/src/xrCore/FTimer.cpp @@ -1,52 +1,54 @@ #include "stdafx.h" #pragma hdrstop -XRCORE_API BOOL g_bEnableStatGather = FALSE; +XRCORE_API BOOL g_bEnableStatGather = FALSE; CStatTimer::CStatTimer() { - accum = 0; - result = 0.f; - count = 0; + accum = 0; + result = 0.f; + count = 0; } -void CStatTimer::FrameStart () +void CStatTimer::FrameStart() { - accum = 0; - count = 0; + accum = 0; + count = 0; } -void CStatTimer::FrameEnd () +void CStatTimer::FrameEnd() { - float _time = 1000.f*float(double(accum)/double(CPU::qpc_freq) ) ; - if (_time > result) result = _time ; - else result = 0.99f*result + 0.01f*_time; + float _time = 1000.f*float(double(accum) / double(CPU::qpc_freq)); + if (_time > result) result = _time; + else result = 0.99f*result + 0.01f*_time; } -XRCORE_API pauseMngr g_pauseMngr; +XRCORE_API pauseMngr g_pauseMngr; -pauseMngr::pauseMngr ():m_paused(FALSE) +pauseMngr::pauseMngr() :m_paused(FALSE) { - m_timers.reserve (3); + m_timers.reserve(3); } void pauseMngr::Pause(BOOL b) { - if(m_paused == b)return; + if (m_paused == b)return; - xr_vector::iterator it = m_timers.begin(); - for(;it!=m_timers.end();++it) - (*it)->Pause(b); + xr_vector::iterator it = m_timers.begin(); + for (; it != m_timers.end(); ++it) + (*it)->Pause(b); - m_paused = b; + m_paused = b; } -void pauseMngr::Register (CTimer_paused* t){ - m_timers.push_back(t); +void pauseMngr::Register(CTimer_paused* t) +{ + m_timers.push_back(t); } -void pauseMngr::UnRegister (CTimer_paused* t){ - xr_vector::iterator it = std::find(m_timers.begin(),m_timers.end(),t); - if( it!=m_timers.end() ) - m_timers.erase(it); +void pauseMngr::UnRegister(CTimer_paused* t) +{ + xr_vector::iterator it = std::find(m_timers.begin(), m_timers.end(), t); + if (it != m_timers.end()) + m_timers.erase(it); } diff --git a/src/xrCore/FTimer.h b/src/xrCore/FTimer.h index b9485eb41c7..5c3dfac7ee9 100644 --- a/src/xrCore/FTimer.h +++ b/src/xrCore/FTimer.h @@ -2,189 +2,199 @@ #define FTimerH #pragma once -class CTimer_paused; +class CTimer_paused; -class XRCORE_API pauseMngr +class XRCORE_API pauseMngr { - xr_vector m_timers; - BOOL m_paused; + xr_vector m_timers; + BOOL m_paused; public: - pauseMngr (); - BOOL Paused (){return m_paused;}; - void Pause (BOOL b); - void Register (CTimer_paused* t); - void UnRegister (CTimer_paused* t); + pauseMngr(); + BOOL Paused() { return m_paused; }; + void Pause(BOOL b); + void Register(CTimer_paused* t); + void UnRegister(CTimer_paused* t); }; -extern XRCORE_API pauseMngr g_pauseMngr; +extern XRCORE_API pauseMngr g_pauseMngr; -class XRCORE_API CTimerBase { +class XRCORE_API CTimerBase +{ protected: - u64 qwStartTime ; - u64 qwPausedTime ; - u64 qwPauseAccum ; - BOOL bPause ; + u64 qwStartTime; + u64 qwPausedTime; + u64 qwPauseAccum; + BOOL bPause; public: - CTimerBase () : qwStartTime(0),qwPausedTime(0),qwPauseAccum(0),bPause(FALSE) { } - ICF void Start () { if(bPause) return; qwStartTime = CPU::QPC()-qwPauseAccum; } - ICF u64 GetElapsed_ticks()const { if(bPause) return qwPausedTime; else return CPU::QPC()-qwStartTime-CPU::qpc_overhead-qwPauseAccum; } - IC u32 GetElapsed_ms ()const { return u32(GetElapsed_ticks()*u64(1000)/CPU::qpc_freq ); } - IC float GetElapsed_sec ()const { + CTimerBase() : qwStartTime(0), qwPausedTime(0), qwPauseAccum(0), bPause(FALSE) { } + ICF void Start() { if (bPause) return; qwStartTime = CPU::QPC() - qwPauseAccum; } + ICF u64 GetElapsed_ticks()const { if (bPause) return qwPausedTime; else return CPU::QPC() - qwStartTime - CPU::qpc_overhead - qwPauseAccum; } + IC u32 GetElapsed_ms()const { return u32(GetElapsed_ticks()*u64(1000) / CPU::qpc_freq); } + IC float GetElapsed_sec()const + { #ifndef _EDITOR - FPU::m64r () ; -#endif - float _result = float(double(GetElapsed_ticks())/double(CPU::qpc_freq ) ) ; + FPU::m64r(); +#endif + float _result = float(double(GetElapsed_ticks()) / double(CPU::qpc_freq)); #ifndef _EDITOR - FPU::m24r () ; + FPU::m24r(); #endif - return _result ; - } - IC void Dump () const - { - Msg("* Elapsed time (sec): %f",GetElapsed_sec()); - } + return _result; + } + IC void Dump() const + { + Msg("* Elapsed time (sec): %f", GetElapsed_sec()); + } }; -class XRCORE_API CTimer : public CTimerBase { +class XRCORE_API CTimer : public CTimerBase +{ private: - typedef CTimerBase inherited; + typedef CTimerBase inherited; private: - float m_time_factor; - u64 m_real_ticks; - u64 m_ticks; + float m_time_factor; + u64 m_real_ticks; + u64 m_ticks; private: - IC u64 GetElapsed_ticks(const u64 ¤t_ticks) const - { - u64 delta = current_ticks - m_real_ticks; - double delta_d = (double)delta; - double time_factor_d = time_factor(); - double time = delta_d*time_factor_d + .5; - u64 result = (u64)time; - return (m_ticks + result); - } + IC u64 GetElapsed_ticks(const u64& current_ticks) const + { + u64 delta = current_ticks - m_real_ticks; + double delta_d = (double)delta; + double time_factor_d = time_factor(); + double time = delta_d*time_factor_d + .5; + u64 result = (u64)time; + return (m_ticks + result); + } public: - IC CTimer () : m_time_factor(1.f), m_real_ticks(0), m_ticks(0) {} - - ICF void Start () - { - if (bPause) - return; - - inherited::Start(); - - m_real_ticks = 0; - m_ticks = 0; - } - - IC const float &time_factor () const - { - return (m_time_factor); - } - - IC void time_factor (const float &time_factor) - { - u64 current = inherited::GetElapsed_ticks(); - m_ticks = GetElapsed_ticks(current); - m_real_ticks = current; - m_time_factor = time_factor; - } - - IC u64 GetElapsed_ticks() const - { + IC CTimer() : m_time_factor(1.f), m_real_ticks(0), m_ticks(0) {} + + ICF void Start() + { + if (bPause) + return; + + inherited::Start(); + + m_real_ticks = 0; + m_ticks = 0; + } + + IC const float& time_factor() const + { + return (m_time_factor); + } + + IC void time_factor(const float& time_factor) + { + u64 current = inherited::GetElapsed_ticks(); + m_ticks = GetElapsed_ticks(current); + m_real_ticks = current; + m_time_factor = time_factor; + } + + IC u64 GetElapsed_ticks() const + { #ifndef _EDITOR - FPU::m64r (); + FPU::m64r(); #endif // _EDITOR - u64 result = GetElapsed_ticks(inherited::GetElapsed_ticks()); + u64 result = GetElapsed_ticks(inherited::GetElapsed_ticks()); #ifndef _EDITOR - FPU::m24r (); + FPU::m24r(); #endif // _EDITOR - return (result); - } + return (result); + } + + IC u32 GetElapsed_ms() const + { + return (u32(GetElapsed_ticks()*u64(1000) / CPU::qpc_freq)); + } - IC u32 GetElapsed_ms () const - { - return (u32(GetElapsed_ticks()*u64(1000)/CPU::qpc_freq)); - } - - IC float GetElapsed_sec () const - { + IC float GetElapsed_sec() const + { #ifndef _EDITOR - FPU::m64r (); -#endif - float result = float(double(GetElapsed_ticks())/double(CPU::qpc_freq ) ) ; + FPU::m64r(); +#endif + float result = float(double(GetElapsed_ticks()) / double(CPU::qpc_freq)); #ifndef _EDITOR - FPU::m24r (); + FPU::m24r(); #endif - return (result); - } + return (result); + } - IC void Dump () const - { - Msg ("* Elapsed time (sec): %f",GetElapsed_sec()); - } + IC void Dump() const + { + Msg("* Elapsed time (sec): %f", GetElapsed_sec()); + } }; -class XRCORE_API CTimer_paused_ex : public CTimer { - u64 save_clock; +class XRCORE_API CTimer_paused_ex : public CTimer +{ + u64 save_clock; public: - CTimer_paused_ex () { } - virtual ~CTimer_paused_ex () { } - IC BOOL Paused ()const { return bPause; } - IC void Pause (BOOL b){ - if(bPause==b) return ; - - u64 _current = CPU::QPC()-CPU::qpc_overhead ; - if( b ) { - save_clock = _current ; - qwPausedTime = CTimerBase::GetElapsed_ticks() ; - }else { - qwPauseAccum += _current - save_clock; - } - bPause = b; - } + CTimer_paused_ex() { } + virtual ~CTimer_paused_ex() { } + IC BOOL Paused()const { return bPause; } + IC void Pause(BOOL b) + { + if (bPause == b) return; + + u64 _current = CPU::QPC() - CPU::qpc_overhead; + if (b) + { + save_clock = _current; + qwPausedTime = CTimerBase::GetElapsed_ticks(); + } + else + { + qwPauseAccum += _current - save_clock; + } + bPause = b; + } }; -class XRCORE_API CTimer_paused : public CTimer_paused_ex { +class XRCORE_API CTimer_paused : public CTimer_paused_ex +{ public: - CTimer_paused () { g_pauseMngr.Register(this); } - virtual ~CTimer_paused () { g_pauseMngr.UnRegister(this); } + CTimer_paused() { g_pauseMngr.Register(this); } + virtual ~CTimer_paused() { g_pauseMngr.UnRegister(this); } }; -extern XRCORE_API BOOL g_bEnableStatGather; +extern XRCORE_API BOOL g_bEnableStatGather; class XRCORE_API CStatTimer { public: - CTimer T; - u64 accum; - float result; - u32 count; + CTimer T; + u64 accum; + float result; + u32 count; public: - CStatTimer (); - void FrameStart (); - void FrameEnd (); + CStatTimer(); + void FrameStart(); + void FrameEnd(); - ICF void Begin () { if (!g_bEnableStatGather) return; count++; T.Start(); } - ICF void End () { if (!g_bEnableStatGather) return; accum += T.GetElapsed_ticks(); } + ICF void Begin() { if (!g_bEnableStatGather) return; count++; T.Start(); } + ICF void End() { if (!g_bEnableStatGather) return; accum += T.GetElapsed_ticks(); } - ICF u64 GetElapsed_ticks()const { return accum; } + ICF u64 GetElapsed_ticks()const { return accum; } - IC u32 GetElapsed_ms ()const { return u32(GetElapsed_ticks()*u64(1000)/CPU::qpc_freq ); } - IC float GetElapsed_sec ()const { + IC u32 GetElapsed_ms()const { return u32(GetElapsed_ticks()*u64(1000) / CPU::qpc_freq); } + IC float GetElapsed_sec()const + { #ifndef _EDITOR - FPU::m64r () ; -#endif - float _result = float(double(GetElapsed_ticks())/double(CPU::qpc_freq ) ) ; + FPU::m64r(); +#endif + float _result = float(double(GetElapsed_ticks()) / double(CPU::qpc_freq)); #ifndef _EDITOR - FPU::m24r () ; + FPU::m24r(); #endif - return _result ; - } + return _result; + } }; #endif // FTimerH diff --git a/src/xrCore/FileSystem.cpp b/src/xrCore/FileSystem.cpp index fea0edbaf95..57b6218b6d3 100644 --- a/src/xrCore/FileSystem.cpp +++ b/src/xrCore/FileSystem.cpp @@ -9,9 +9,9 @@ #include "commdlg.h" #include "vfw.h" -EFS_Utils* xr_EFS = NULL; +EFS_Utils* xr_EFS = NULL; //---------------------------------------------------- -EFS_Utils::EFS_Utils( ) +EFS_Utils::EFS_Utils() { } @@ -19,51 +19,54 @@ EFS_Utils::~EFS_Utils() { } -xr_string EFS_Utils::ExtractFileName(LPCSTR src) +xr_string EFS_Utils::ExtractFileName(LPCSTR src) { - string_path name; - _splitpath (src,0,0,name,0); + string_path name; + _splitpath(src, 0, 0, name, 0); return xr_string(name); } -xr_string EFS_Utils::ExtractFileExt(LPCSTR src) +xr_string EFS_Utils::ExtractFileExt(LPCSTR src) { - string_path ext; - _splitpath (src,0,0,0,ext); + string_path ext; + _splitpath(src, 0, 0, 0, ext); return xr_string(ext); } -xr_string EFS_Utils::ExtractFilePath(LPCSTR src) +xr_string EFS_Utils::ExtractFilePath(LPCSTR src) { - string_path drive,dir; - _splitpath (src,drive,dir,0,0); - return xr_string(drive)+dir; + string_path drive, dir; + _splitpath(src, drive, dir, 0, 0); + return xr_string(drive) + dir; } -xr_string EFS_Utils::ExcludeBasePath(LPCSTR full_path, LPCSTR excl_path) +xr_string EFS_Utils::ExcludeBasePath(LPCSTR full_path, LPCSTR excl_path) { - LPCSTR sub = strstr(full_path,excl_path); - if (0!=sub) return xr_string(sub+xr_strlen(excl_path)); - else return xr_string(full_path); + LPCSTR sub = strstr(full_path, excl_path); + if (0 != sub) return xr_string(sub + xr_strlen(excl_path)); + else return xr_string(full_path); } -xr_string EFS_Utils::ChangeFileExt(LPCSTR src, LPCSTR ext) +xr_string EFS_Utils::ChangeFileExt(LPCSTR src, LPCSTR ext) { - xr_string tmp; - LPSTR src_ext = strext(src); - if (src_ext){ - size_t ext_pos = src_ext-src; - tmp.assign (src,0,ext_pos); - }else{ - tmp = src; + xr_string tmp; + LPSTR src_ext = strext(src); + if (src_ext) + { + size_t ext_pos = src_ext - src; + tmp.assign(src, 0, ext_pos); + } + else + { + tmp = src; } - tmp += ext; + tmp += ext; return tmp; } -xr_string EFS_Utils::ChangeFileExt(const xr_string& src, LPCSTR ext) +xr_string EFS_Utils::ChangeFileExt(const xr_string& src, LPCSTR ext) { - return ChangeFileExt(src.c_str(),ext); + return ChangeFileExt(src.c_str(), ext); } //---------------------------------------------------- @@ -73,249 +76,263 @@ void MakeFilter(string1024& dest, LPCSTR info, LPCSTR ext) if (ext) { - res += info; - res += "("; - res += ext; - res += ")|"; - res += ext; - res += "|"; - int icnt = _GetItemCount(ext,';'); - if(icnt>1) + res += info; + res += "("; + res += ext; + res += ")|"; + res += ext; + res += "|"; + int icnt = _GetItemCount(ext, ';'); + if (icnt > 1) { - for(int idx=0; idx0)); - FS_Path& P = *FS.get_path(initial); - string1024 flt; - MakeFilter (flt,P.m_FilterCaption?P.m_FilterCaption:"",P.m_DefExt); + VERIFY(buffer && (sz_buf > 0)); + FS_Path& P = *FS.get_path(initial); + string1024 flt; + MakeFilter(flt, P.m_FilterCaption ? P.m_FilterCaption : "", P.m_DefExt); - OPENFILENAME ofn; - Memory.mem_fill ( &ofn, 0, sizeof(ofn) ); + OPENFILENAME ofn; + Memory.mem_fill(&ofn, 0, sizeof(ofn)); if (xr_strlen(buffer)) { - string_path dr; - if (!(buffer[0]=='\\' && buffer[1]=='\\')){ // if !network - _splitpath (buffer,dr,0,0,0); + string_path dr; + if (!(buffer[0] == '\\' && buffer[1] == '\\')) // if !network + { + _splitpath(buffer, dr, 0, 0, 0); - if (0==dr[0]) + if (0 == dr[0]) { - string_path bb; - P._update (bb, buffer); - xr_strcpy (buffer, sz_buf, bb); - } + string_path bb; + P._update(bb, buffer); + xr_strcpy(buffer, sz_buf, bb); + } } } - ofn.lStructSize = sizeof(OPENFILENAME); - ofn.hwndOwner = GetForegroundWindow(); - ofn.lpstrDefExt = P.m_DefExt; - ofn.lpstrFile = buffer; - ofn.nMaxFile = sz_buf; - ofn.lpstrFilter = flt; - ofn.nFilterIndex = start_flt_ext+2; - ofn.lpstrTitle = "Open a File"; - string512 path; - xr_strcpy (path,(offset&&offset[0])?offset:P.m_Path); - ofn.lpstrInitialDir = path; - ofn.Flags = OFN_PATHMUSTEXIST | - OFN_FILEMUSTEXIST | - OFN_HIDEREADONLY | - OFN_FILEMUSTEXIST | - OFN_NOCHANGEDIR | - (bMulti?OFN_ALLOWMULTISELECT|OFN_EXPLORER:0); - - ofn.FlagsEx = OFN_EX_NOPLACESBAR; - -/* - unsigned int dwVersion = GetVersion(); - unsigned int dwWindowsMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion))); - if ( dwWindowsMajorVersion == 6 ) - { - ofn.Flags |= OFN_ENABLEHOOK; - ofn.lpfnHook = OFNHookProcOldStyle; - } -*/ - - bool bRes = !!GetOpenFileName( &ofn ); + ofn.lStructSize = sizeof(OPENFILENAME); + ofn.hwndOwner = GetForegroundWindow(); + ofn.lpstrDefExt = P.m_DefExt; + ofn.lpstrFile = buffer; + ofn.nMaxFile = sz_buf; + ofn.lpstrFilter = flt; + ofn.nFilterIndex = start_flt_ext + 2; + ofn.lpstrTitle = "Open a File"; + string512 path; + xr_strcpy(path, (offset&&offset[0]) ? offset : P.m_Path); + ofn.lpstrInitialDir = path; + ofn.Flags = OFN_PATHMUSTEXIST | + OFN_FILEMUSTEXIST | + OFN_HIDEREADONLY | + OFN_FILEMUSTEXIST | + OFN_NOCHANGEDIR | + (bMulti ? OFN_ALLOWMULTISELECT | OFN_EXPLORER : 0); + + ofn.FlagsEx = OFN_EX_NOPLACESBAR; + + /* + unsigned int dwVersion = GetVersion(); + unsigned int dwWindowsMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion))); + if ( dwWindowsMajorVersion == 6 ) + { + ofn.Flags |= OFN_ENABLEHOOK; + ofn.lpfnHook = OFNHookProcOldStyle; + } + */ + + bool bRes = !!GetOpenFileName(&ofn); if (!bRes) { - u32 err = CommDlgExtendedError(); - switch(err) + u32 err = CommDlgExtendedError(); + switch (err) { - case FNERR_BUFFERTOOSMALL: - Log("Too many files selected."); + case FNERR_BUFFERTOOSMALL: + Log("Too many files selected."); break; } - } + } if (bRes && bMulti) { - Log ("buff=",buffer); - int cnt = _GetItemCount(buffer,0x0); - if (cnt>1) + Log("buff=", buffer); + int cnt = _GetItemCount(buffer, 0x0); + if (cnt > 1) { - char dir [255*255]; - char buf [255*255]; - char fns [255*255]; + char dir[255 * 255]; + char buf[255 * 255]; + char fns[255 * 255]; - xr_strcpy (dir, buffer); - xr_strcpy (fns, dir); - xr_strcat (fns, "\\"); - xr_strcat (fns, _GetItem (buffer,1,buf,0x0)); + xr_strcpy(dir, buffer); + xr_strcpy(fns, dir); + xr_strcat(fns, "\\"); + xr_strcat(fns, _GetItem(buffer, 1, buf, 0x0)); - for (int i=2; i -class FixedMAP { - enum { - SG_REALLOC_ADVANCE = 64 - }; +class FixedMAP +{ + enum + { + SG_REALLOC_ADVANCE = 64 + }; public: - struct TNode { - K key; - T val; - TNode *left,*right; - }; - typedef void __fastcall callback (TNode*); - typedef bool __fastcall callback_cmp(TNode& N1, TNode& N2); + struct TNode + { + K key; + T val; + TNode* left, *right; + }; + typedef void __fastcall callback(TNode*); + typedef bool __fastcall callback_cmp(TNode& N1, TNode& N2); private: - TNode* nodes; - u32 pool; - u32 limit; + TNode* nodes; + u32 pool; + u32 limit; - IC u32 Size(u32 Count) - { return Count*sizeof(TNode); } + IC u32 Size(u32 Count) + { + return Count*sizeof(TNode); + } - void Realloc() - { - u32 newLimit = limit + SG_REALLOC_ADVANCE; - VERIFY(newLimit%SG_REALLOC_ADVANCE == 0); - TNode* newNodes = (TNode*)allocator::alloc(sizeof(TNode)*newLimit); - VERIFY(newNodes); + void Realloc() + { + u32 newLimit = limit + SG_REALLOC_ADVANCE; + VERIFY(newLimit%SG_REALLOC_ADVANCE == 0); + TNode* newNodes = (TNode*)allocator::alloc(sizeof(TNode)*newLimit); + VERIFY(newNodes); - ZeroMemory(newNodes, Size(newLimit)); - if (limit) CopyMemory (newNodes, nodes, Size(limit)); + ZeroMemory(newNodes, Size(newLimit)); + if (limit) CopyMemory(newNodes, nodes, Size(limit)); - for (u32 I=0; Ileft) { - size_t Lid = Nold->left - nodes; - Nnew->left = newNodes + Lid; - } - if (Nold->right) { - size_t Rid = Nold->right - nodes; - Nnew->right = newNodes + Rid; - } - } - if (nodes) allocator::dealloc(nodes); + if (Nold->left) + { + size_t Lid = Nold->left - nodes; + Nnew->left = newNodes + Lid; + } + if (Nold->right) + { + size_t Rid = Nold->right - nodes; + Nnew->right = newNodes + Rid; + } + } + if (nodes) allocator::dealloc(nodes); - nodes = newNodes; - limit = newLimit; - } + nodes = newNodes; + limit = newLimit; + } - IC TNode* Alloc (const K& key) - { - if (pool==limit) Realloc(); - TNode *node = nodes + pool; - node->key = key; - node->right = node->left = 0; - pool++ ; - return node ; - } - IC TNode* CreateChild (TNode* &parent, const K& key) - { - size_t PID = size_t(parent-nodes); - TNode* N = Alloc (key); - parent = nodes+PID; - return N; - } + IC TNode* Alloc(const K& key) + { + if (pool == limit) Realloc(); + TNode* node = nodes + pool; + node->key = key; + node->right = node->left = 0; + pool++; + return node; + } + IC TNode* CreateChild(TNode*& parent, const K& key) + { + size_t PID = size_t(parent - nodes); + TNode* N = Alloc(key); + parent = nodes + PID; + return N; + } - IC void recurseLR (TNode* N, callback CB) - { - if (N->left) recurseLR(N->left,CB); - CB(N); - if (N->right) recurseLR(N->right,CB); - } - IC void recurseRL (TNode* N, callback CB) - { - if (N->right) recurseRL(N->right,CB); - CB(N); - if (N->left) recurseRL(N->left,CB); - } - IC void getLR (TNode* N, xr_vector::result>& D) - { - if (N->left) getLR(N->left,D); - D.push_back (N->val); - if (N->right) getLR(N->right,D); - } - IC void getRL (TNode* N, xr_vector::result>& D) - { - if (N->right) getRL(N->right,D); - D.push_back (N->val); - if (N->left) getRL(N->left,D); - } - IC void getLR_P (TNode* N, xr_vector::result>& D) - { - if (N->left) getLR_P(N->left,D); - D.push_back (N); - if (N->right) getLR_P(N->right,D); - } - IC void getRL_P (TNode* N, xr_vector::result>& D) - { - if (N->right) getRL_P(N->right,D); - D.push_back (N); - if (N->left) getRL_P(N->left,D); - } + IC void recurseLR(TNode* N, callback CB) + { + if (N->left) recurseLR(N->left, CB); + CB(N); + if (N->right) recurseLR(N->right, CB); + } + IC void recurseRL(TNode* N, callback CB) + { + if (N->right) recurseRL(N->right, CB); + CB(N); + if (N->left) recurseRL(N->left, CB); + } + IC void getLR(TNode* N, xr_vector::result>& D) + { + if (N->left) getLR(N->left, D); + D.push_back(N->val); + if (N->right) getLR(N->right, D); + } + IC void getRL(TNode* N, xr_vector::result>& D) + { + if (N->right) getRL(N->right, D); + D.push_back(N->val); + if (N->left) getRL(N->left, D); + } + IC void getLR_P(TNode* N, xr_vector::result>& D) + { + if (N->left) getLR_P(N->left, D); + D.push_back(N); + if (N->right) getLR_P(N->right, D); + } + IC void getRL_P(TNode* N, xr_vector::result>& D) + { + if (N->right) getRL_P(N->right, D); + D.push_back(N); + if (N->left) getRL_P(N->left, D); + } public: - FixedMAP() { - pool = 0; - limit = 0; - nodes = 0; - } - ~FixedMAP() { - destroy (); - } - void destroy() - { - if (nodes) { - for (TNode* cur = begin(); cur!=last(); cur++) - cur->~TNode(); - allocator::dealloc(nodes); - } - } - IC TNode* insert(const K& k) { - if (pool) { - TNode* node = nodes; + FixedMAP() + { + pool = 0; + limit = 0; + nodes = 0; + } + ~FixedMAP() + { + destroy(); + } + void destroy() + { + if (nodes) + { + for (TNode* cur = begin(); cur != last(); cur++) + cur->~TNode(); + allocator::dealloc(nodes); + } + } + IC TNode* insert(const K& k) + { + if (pool) + { + TNode* node = nodes; - once_more: - if (k < node->key) { - if (node->left) { - node = node->left; - goto once_more; - } else { - TNode* N = CreateChild(node,k); - node->left = N; - return N; - } - } else if (k > node->key) { - if (node->right) { - node = node->right; - goto once_more; - } else { - TNode* N = CreateChild(node,k); - node->right = N; - return N; - } - } else return node; - - } else { - return Alloc(k); - } - } - IC TNode* insertInAnyWay(const K& k) { - if (pool) { - TNode* node = nodes; + once_more: + if (k < node->key) + { + if (node->left) + { + node = node->left; + goto once_more; + } + else + { + TNode* N = CreateChild(node, k); + node->left = N; + return N; + } + } + else if (k > node->key) + { + if (node->right) + { + node = node->right; + goto once_more; + } + else + { + TNode* N = CreateChild(node, k); + node->right = N; + return N; + } + } + else return node; - once_more: - if (k <= node->key) { - if (node->left) { - node = node->left; - goto once_more; - } else { - TNode* N = CreateChild(node,k); - node->left = N; - return N; - } - } else { - if (node->right) { - node = node->right; - goto once_more; - } else { - TNode* N = CreateChild(node,k); - node->right = N; - return N; - } - } - } else { - return Alloc(k); - } - } - IC TNode* insert (const K& k, const T& v) - { - TNode* N = insert(k); - N->val = v; - return N; - } - IC TNode* insertInAnyWay(const K& k, const T& v) - { - TNode* N = insertInAnyWay(k); - N->val = v; - return N; - } - IC void discard() { if (nodes) allocator::dealloc(nodes); nodes = 0; pool=0; limit=0; } - IC u32 allocated() { return this->limit; } - IC void clear() { pool=0; } - IC TNode* begin() { return nodes; } - IC TNode* end() { return nodes+pool; } - IC TNode* last() { return nodes+limit; } // for setup only - IC u32 size() { return pool; } - IC TNode& operator[] (int v) { return nodes[v]; } + } + else + { + return Alloc(k); + } + } + IC TNode* insertInAnyWay(const K& k) + { + if (pool) + { + TNode* node = nodes; - IC void traverseLR (callback CB) - { if (pool) recurseLR(nodes,CB); } - IC void traverseRL (callback CB) - { if (pool) recurseRL(nodes,CB); } - IC void traverseANY (callback CB) { - TNode* _end = end(); - for (TNode* cur = begin(); cur!=_end; cur++) - CB(cur); - } + once_more: + if (k <= node->key) + { + if (node->left) + { + node = node->left; + goto once_more; + } + else + { + TNode* N = CreateChild(node, k); + node->left = N; + return N; + } + } + else + { + if (node->right) + { + node = node->right; + goto once_more; + } + else + { + TNode* N = CreateChild(node, k); + node->right = N; + return N; + } + } + } + else + { + return Alloc(k); + } + } + IC TNode* insert(const K& k, const T& v) + { + TNode* N = insert(k); + N->val = v; + return N; + } + IC TNode* insertInAnyWay(const K& k, const T& v) + { + TNode* N = insertInAnyWay(k); + N->val = v; + return N; + } + IC void discard() { if (nodes) allocator::dealloc(nodes); nodes = 0; pool = 0; limit = 0; } + IC u32 allocated() { return this->limit; } + IC void clear() { pool = 0; } + IC TNode* begin() { return nodes; } + IC TNode* end() { return nodes + pool; } + IC TNode* last() { return nodes + limit; } // for setup only + IC u32 size() { return pool; } + IC TNode& operator[] (int v) { return nodes[v]; } - IC void getLR (xr_vector::result>& D) - { if (pool) getLR(nodes,D); } - IC void getLR_P (xr_vector::result>& D) - { if (pool) getLR_P(nodes,D); } - IC void getRL (xr_vector::result>& D) - { if (pool) getRL(nodes,D); } - IC void getRL_P (xr_vector::result>& D) - { if (pool) getRL_P(nodes,D); } - IC void getANY (xr_vector::result>& D) - { - TNode* _end = end(); - for (TNode* cur = begin(); cur!=_end; cur++) D.push_back(cur->val); - } - IC void getANY_P (xr_vector::result>& D) - { - D.resize (size()); - TNode** _it = &*D.begin(); - TNode* _end = end(); - for (TNode* cur = begin(); cur!=_end; cur++,_it++) *_it = cur; - } - IC void getANY_P (xr_vector::result>& D) - { - D.resize (size()); - void** _it = &*D.begin(); - TNode* _end = end(); - for (TNode* cur = begin(); cur!=_end; cur++,_it++) *_it = cur; - } - IC void setup(callback CB) { - for (int i=0; i::result>& D) + { + if (pool) getLR(nodes, D); + } + IC void getLR_P(xr_vector::result>& D) + { + if (pool) getLR_P(nodes, D); + } + IC void getRL(xr_vector::result>& D) + { + if (pool) getRL(nodes, D); + } + IC void getRL_P(xr_vector::result>& D) + { + if (pool) getRL_P(nodes, D); + } + IC void getANY(xr_vector::result>& D) + { + TNode* _end = end(); + for (TNode* cur = begin(); cur != _end; cur++) D.push_back(cur->val); + } + IC void getANY_P(xr_vector::result>& D) + { + D.resize(size()); + TNode** _it = &*D.begin(); + TNode* _end = end(); + for (TNode* cur = begin(); cur != _end; cur++, _it++) *_it = cur; + } + IC void getANY_P(xr_vector::result>& D) + { + D.resize(size()); + void** _it = &*D.begin(); + TNode* _end = end(); + for (TNode* cur = begin(); cur != _end; cur++, _it++) *_it = cur; + } + IC void setup(callback CB) + { + for (int i = 0; i < limit; i++) + CB(nodes + i); + } }; #endif \ No newline at end of file diff --git a/src/xrCore/FixedSet.h b/src/xrCore/FixedSet.h index a9ab5acff9a..e3626171d18 100644 --- a/src/xrCore/FixedSet.h +++ b/src/xrCore/FixedSet.h @@ -5,168 +5,211 @@ template class FixedSET { - enum { - SG_REALLOC_ADVANCE = 64, - SG_REALLOC_ALIGN = 64 - }; + enum + { + SG_REALLOC_ADVANCE = 64, + SG_REALLOC_ALIGN = 64 + }; public: - struct TNode { - K key; - TNode *left,*right; - }; - typedef void __fastcall callback(TNode*); + struct TNode + { + K key; + TNode* left, *right; + }; + typedef void __fastcall callback(TNode*); private: - TNode* nodes; - u32 pool; - u32 limit; + TNode* nodes; + u32 pool; + u32 limit; - IC u32 Size(u32 Count) - { return Count*sizeof(TNode); } + IC u32 Size(u32 Count) + { + return Count*sizeof(TNode); + } - void Realloc() - { - u32 newLimit = limit + SG_REALLOC_ADVANCE; - VERIFY(newLimit%SG_REALLOC_ADVANCE == 0); - TNode* newNodes = (TNode*)allocator::alloc(sizeof(TNode)*newLimit); - VERIFY(newNodes); + void Realloc() + { + u32 newLimit = limit + SG_REALLOC_ADVANCE; + VERIFY(newLimit%SG_REALLOC_ADVANCE == 0); + TNode* newNodes = (TNode*)allocator::alloc(sizeof(TNode)*newLimit); + VERIFY(newNodes); - ZeroMemory(newNodes, Size(newLimit)); - if (limit) CopyMemory(newNodes, nodes, Size(limit)); + ZeroMemory(newNodes, Size(newLimit)); + if (limit) CopyMemory(newNodes, nodes, Size(limit)); - for (u32 I=0; Ileft) { - u32 Lid = u32(Nold->left - nodes); - Nnew->left = newNodes + Lid; - } - if (Nold->right) { - u32 Rid = u32(Nold->right - nodes); - Nnew->right = newNodes + Rid; - } - } - if (nodes) allocator:dealloc(nodes); + if (Nold->left) + { + u32 Lid = u32(Nold->left - nodes); + Nnew->left = newNodes + Lid; + } + if (Nold->right) + { + u32 Rid = u32(Nold->right - nodes); + Nnew->right = newNodes + Rid; + } + } + if (nodes) allocator: + dealloc(nodes); - nodes = newNodes; - limit = newLimit; - } - IC TNode* Alloc(const K& key) - { - if (pool==limit) Realloc(); - TNode *node = nodes + pool; - node->key = key; - node->right = node->left = 0; - pool++; - return node; - } - IC TNode* CreateChild(TNode* &parent, const K& key) - { - u32 PID = u32(parent-nodes); - TNode* N = Alloc(key); - parent = nodes+PID; - return N; - } + nodes = newNodes; + limit = newLimit; + } + IC TNode* Alloc(const K& key) + { + if (pool == limit) Realloc(); + TNode* node = nodes + pool; + node->key = key; + node->right = node->left = 0; + pool++; + return node; + } + IC TNode* CreateChild(TNode*& parent, const K& key) + { + u32 PID = u32(parent - nodes); + TNode* N = Alloc(key); + parent = nodes + PID; + return N; + } - IC void recurseLR (TNode* N, callback CB) - { - if (N->left) recurseLR(N->left,CB); - CB(N); - if (N->right) recurseLR(N->right,CB); - } - IC void recurseRL (TNode* N, callback CB) - { - if (N->right) recurseRL(N->right,CB); - CB(N); - if (N->left) recurseRL(N->left,CB); - } + IC void recurseLR(TNode* N, callback CB) + { + if (N->left) recurseLR(N->left, CB); + CB(N); + if (N->right) recurseLR(N->right, CB); + } + IC void recurseRL(TNode* N, callback CB) + { + if (N->right) recurseRL(N->right, CB); + CB(N); + if (N->left) recurseRL(N->left, CB); + } public: - FixedSET() { - pool = 0; - limit = 0; - nodes = 0; - } - ~FixedSET() { - allocator:dealloc(nodes); - } - IC TNode* insert(const K& k) { - if (pool) { - TNode* node = nodes; + FixedSET() + { + pool = 0; + limit = 0; + nodes = 0; + } + ~FixedSET() + { + allocator: + dealloc(nodes); + } + IC TNode* insert(const K& k) + { + if (pool) + { + TNode* node = nodes; - once_more: - if (k < node->key) { - if (node->left) { - node = node->left; - goto once_more; - } else { - TNode* N = CreateChild(node,k); - node->left = N; - return N; - } - } else if (k > node->key) { - if (node->right) { - node = node->right; - goto once_more; - } else { - TNode* N = CreateChild(node,k); - node->right = N; - return N; - } - } else return node; - - } else { - return Alloc(k); - } - } - IC TNode* insertInAnyWay(const K& k) { - if (pool) { - TNode* node = nodes; + once_more: + if (k < node->key) + { + if (node->left) + { + node = node->left; + goto once_more; + } + else + { + TNode* N = CreateChild(node, k); + node->left = N; + return N; + } + } + else if (k > node->key) + { + if (node->right) + { + node = node->right; + goto once_more; + } + else + { + TNode* N = CreateChild(node, k); + node->right = N; + return N; + } + } + else return node; - once_more: - if (k <= node->key) { - if (node->left) { - node = node->left; - goto once_more; - } else { - TNode* N = CreateChild(node,k); - node->left = N; - return N; - } - } else { - if (node->right) { - node = node->right; - goto once_more; - } else { - TNode* N = CreateChild(node,k); - node->right = N; - return N; - } - } - } else { - return Alloc(k); - } - } - IC void clear() { pool=0; } - IC TNode* begin() { return nodes; } - IC TNode* end() { return nodes+pool; } - IC TNode* last() { return nodes+limit; } // for setup only - IC u32 size() { return pool; } - IC TNode& operator[] (int v) { return nodes[v]; } + } + else + { + return Alloc(k); + } + } + IC TNode* insertInAnyWay(const K& k) + { + if (pool) + { + TNode* node = nodes; - IC void traverseLR (callback CB) - { if (pool) recurseLR(nodes,CB); } - IC void traverseRL (callback CB) - { if (pool) recurseRL(nodes,CB); } - IC void traverseANY (callback CB) { - TNode* _end = end(); - for (TNode* cur = begin(); cur!=_end; cur++) - CB(cur); - } - IC void for_each (callback CB) { - for (int i=0; ikey) + { + if (node->left) + { + node = node->left; + goto once_more; + } + else + { + TNode* N = CreateChild(node, k); + node->left = N; + return N; + } + } + else + { + if (node->right) + { + node = node->right; + goto once_more; + } + else + { + TNode* N = CreateChild(node, k); + node->right = N; + return N; + } + } + } + else + { + return Alloc(k); + } + } + IC void clear() { pool = 0; } + IC TNode* begin() { return nodes; } + IC TNode* end() { return nodes + pool; } + IC TNode* last() { return nodes + limit; } // for setup only + IC u32 size() { return pool; } + IC TNode& operator[] (int v) { return nodes[v]; } + + IC void traverseLR(callback CB) + { + if (pool) recurseLR(nodes, CB); + } + IC void traverseRL(callback CB) + { + if (pool) recurseRL(nodes, CB); + } + IC void traverseANY(callback CB) + { + TNode* _end = end(); + for (TNode* cur = begin(); cur != _end; cur++) + CB(cur); + } + IC void for_each(callback CB) + { + for (int i = 0; i < limit; i++) + CB(nodes + i); + } }; #endif \ No newline at end of file diff --git a/src/xrCore/FixedVector.h b/src/xrCore/FixedVector.h index a26b4cd849a..45ad4b0b9c5 100644 --- a/src/xrCore/FixedVector.h +++ b/src/xrCore/FixedVector.h @@ -3,72 +3,75 @@ #pragma once template -class svector +class svector { public: - typedef size_t size_type; - typedef T value_type; - typedef value_type* iterator; - typedef const value_type* const_iterator; - typedef value_type& reference; - typedef const value_type& const_reference; + typedef size_t size_type; + typedef T value_type; + typedef value_type* iterator; + typedef const value_type* const_iterator; + typedef value_type& reference; + typedef const value_type& const_reference; private: - value_type array[dim]; - u32 count; + value_type array[dim]; + u32 count; public: - svector() : count(0) - {} - svector(iterator p, int c) - { assign(p,c); } + svector() : count(0) + {} + svector(iterator p, int c) + { + assign(p, c); + } - IC iterator begin() { return array; } - IC iterator end () { return array+count; } - IC const_iterator begin() const { return array; } - IC const_iterator end () const { return array+count; } - IC u32 size() const { return count; } - IC void clear() { count=0; } - IC void resize(int c) { VERIFY(c<=dim); count=c; } - IC void reserve(int c) { } + IC iterator begin() { return array; } + IC iterator end() { return array + count; } + IC const_iterator begin() const { return array; } + IC const_iterator end() const { return array + count; } + IC u32 size() const { return count; } + IC void clear() { count = 0; } + IC void resize(int c) { VERIFY(c <= dim); count = c; } + IC void reserve(int c) { } - IC void push_back(value_type e) { VERIFY(countint(id); i--) array[i] = array[i-1]; - count++; - array[id] = V; - } - IC void assign(iterator p, int c) { VERIFY(c>0 && c& base) const - { - if (size()!=base.size()) return FALSE; - for (u32 cmp=0; cmp int(id); i--) array[i] = array[i - 1]; + count++; + array[id] = V; + } + IC void assign(iterator p, int c) { VERIFY(c > 0 && c < dim); CopyMemory(array, p, c*sizeof(value_type)); count = c; } + IC BOOL equal(const svector& base) const + { + if (size() != base.size()) return FALSE; + for (u32 cmp = 0; cmp < size(); cmp++) if ((*this)[cmp] != base[cmp]) return FALSE; + return TRUE; + } }; #endif \ No newline at end of file diff --git a/src/xrCore/LocatorAPI.cpp b/src/xrCore/LocatorAPI.cpp index 7d88501d0b7..ed800ce36d5 100644 --- a/src/xrCore/LocatorAPI.cpp +++ b/src/xrCore/LocatorAPI.cpp @@ -15,539 +15,566 @@ #include "stream_reader.h" #include "file_stream_reader.h" -const u32 BIG_FILE_READER_WINDOW_SIZE = 1024*1024; +const u32 BIG_FILE_READER_WINDOW_SIZE = 1024*1024; //typedef void DUMMY_STUFF (const void*,const u32&,void*); -//XRCORE_API DUMMY_STUFF *g_temporary_stuff = 0; +//XRCORE_API DUMMY_STUFF *g_temporary_stuff = 0; -# pragma warning(push) -# pragma warning(disable:4995) -# include -# pragma warning(pop) +# pragma warning(push) +# pragma warning(disable:4995) +# include +# pragma warning(pop) -CLocatorAPI* xr_FS = NULL; +CLocatorAPI* xr_FS = NULL; #ifdef _EDITOR -# define FSLTX "fs.ltx" +# define FSLTX "fs.ltx" #else -# define FSLTX "fsgame.ltx" +# define FSLTX "fsgame.ltx" #endif struct _open_file { - union { - IReader* _reader; - CStreamReader* _stream_reader; - }; - shared_str _fn; - u32 _used; + union + { + IReader* _reader; + CStreamReader* _stream_reader; + }; + shared_str _fn; + u32 _used; }; template struct eq_pointer; template <> -struct eq_pointer{ - IReader* _val; - eq_pointer(IReader* p):_val(p){} - bool operator () (_open_file& itm){ - return ( _val==itm._reader ); - } +struct eq_pointer < IReader > +{ + IReader* _val; + eq_pointer(IReader* p) :_val(p) {} + bool operator () (_open_file& itm) + { + return (_val == itm._reader); + } }; template <> -struct eq_pointer{ - CStreamReader* _val; - eq_pointer(CStreamReader* p):_val(p){} - bool operator () (_open_file& itm){ - return ( _val==itm._stream_reader ); - } +struct eq_pointer < CStreamReader > +{ + CStreamReader* _val; + eq_pointer(CStreamReader* p) :_val(p) {} + bool operator () (_open_file& itm) + { + return (_val == itm._stream_reader); + } }; -struct eq_fname_free{ - shared_str _val; - eq_fname_free(shared_str s){_val = s;} - bool operator () (_open_file& itm){ - return ( _val==itm._fn && itm._reader==NULL); - } +struct eq_fname_free +{ + shared_str _val; + eq_fname_free(shared_str s) { _val = s; } + bool operator () (_open_file& itm) + { + return (_val == itm._fn && itm._reader == NULL); + } }; -struct eq_fname_check{ - shared_str _val; - eq_fname_check(shared_str s){_val = s;} - bool operator () (_open_file& itm){ - return ( _val==itm._fn && itm._reader!=NULL); - } +struct eq_fname_check +{ + shared_str _val; + eq_fname_check(shared_str s) { _val = s; } + bool operator () (_open_file& itm) + { + return (_val == itm._fn && itm._reader != NULL); + } }; -XRCORE_API xr_vector<_open_file> g_open_files; +XRCORE_API xr_vector<_open_file> g_open_files; void _check_open_file(const shared_str& _fname) { - xr_vector<_open_file>::iterator it = std::find_if(g_open_files.begin(), g_open_files.end(), eq_fname_check(_fname) ); - if(it!=g_open_files.end()) - Log("file opened at least twice", _fname.c_str()); + xr_vector<_open_file>::iterator it = std::find_if(g_open_files.begin(), g_open_files.end(), eq_fname_check(_fname)); + if (it != g_open_files.end()) + Log("file opened at least twice", _fname.c_str()); } _open_file& find_free_item(const shared_str& _fname) { - xr_vector<_open_file>::iterator it = std::find_if(g_open_files.begin(), g_open_files.end(), eq_fname_free(_fname) ); - if(it==g_open_files.end()) - { - g_open_files.resize (g_open_files.size()+1); - _open_file& _of = g_open_files.back(); - _of._fn = _fname; - _of._used = 0; - return _of; - } - return *it; + xr_vector<_open_file>::iterator it = std::find_if(g_open_files.begin(), g_open_files.end(), eq_fname_free(_fname)); + if (it == g_open_files.end()) + { + g_open_files.resize(g_open_files.size() + 1); + _open_file& _of = g_open_files.back(); + _of._fn = _fname; + _of._used = 0; + return _of; + } + return *it; } void setup_reader(CStreamReader* _r, _open_file& _of) { - _of._stream_reader = _r; + _of._stream_reader = _r; } void setup_reader(IReader* _r, _open_file& _of) { - _of._reader = _r; + _of._reader = _r; } template void _register_open_file(T* _r, LPCSTR _fname) { - xrCriticalSection _lock; - _lock.Enter (); + xrCriticalSection _lock; + _lock.Enter(); - shared_str f = _fname; - _check_open_file (f); - - _open_file& _of = find_free_item(_fname); - setup_reader (_r,_of); - _of._used += 1; + shared_str f = _fname; + _check_open_file(f); - _lock.Leave (); + _open_file& _of = find_free_item(_fname); + setup_reader(_r, _of); + _of._used += 1; + + _lock.Leave(); } template void _unregister_open_file(T* _r) { - xrCriticalSection _lock; - _lock.Enter (); + xrCriticalSection _lock; + _lock.Enter(); - xr_vector<_open_file>::iterator it = std::find_if(g_open_files.begin(), g_open_files.end(), eq_pointer(_r) ); - VERIFY (it!=g_open_files.end()); - _open_file& _of = *it; - _of._reader = NULL; - _lock.Leave (); + xr_vector<_open_file>::iterator it = std::find_if(g_open_files.begin(), g_open_files.end(), eq_pointer(_r)); + VERIFY(it != g_open_files.end()); + _open_file& _of = *it; + _of._reader = NULL; + _lock.Leave(); } XRCORE_API void _dump_open_files(int mode) { - xr_vector<_open_file>::iterator it = g_open_files.begin(); - xr_vector<_open_file>::iterator it_e = g_open_files.end(); - - bool bShow = false; - if(mode==1) - { - for(; it!=it_e; ++it) - { - _open_file& _of = *it; - if(_of._reader!=NULL) - { - if(!bShow) - Log("----opened files"); - - bShow = true; - Msg("[%d] fname:%s", _of._used ,_of._fn.c_str()); - } - } - }else - { - Log("----un-used"); - for(it = g_open_files.begin(); it!=it_e; ++it) - { - _open_file& _of = *it; - if(_of._reader==NULL) - Msg("[%d] fname:%s", _of._used ,_of._fn.c_str()); - } - } - if(bShow) - Log("----total count=",g_open_files.size()); + xr_vector<_open_file>::iterator it = g_open_files.begin(); + xr_vector<_open_file>::iterator it_e = g_open_files.end(); + + bool bShow = false; + if (mode == 1) + { + for (; it != it_e; ++it) + { + _open_file& _of = *it; + if (_of._reader != NULL) + { + if (!bShow) + Log("----opened files"); + + bShow = true; + Msg("[%d] fname:%s", _of._used, _of._fn.c_str()); + } + } + } + else + { + Log("----un-used"); + for (it = g_open_files.begin(); it != it_e; ++it) + { + _open_file& _of = *it; + if (_of._reader == NULL) + Msg("[%d] fname:%s", _of._used, _of._fn.c_str()); + } + } + if (bShow) + Log("----total count=", g_open_files.size()); } CLocatorAPI::CLocatorAPI() #ifdef PROFILE_CRITICAL_SECTIONS - :m_auth_lock (MUTEX_PROFILE_ID(CLocatorAPI::m_auth_lock)) + :m_auth_lock(MUTEX_PROFILE_ID(CLocatorAPI::m_auth_lock)) #endif // PROFILE_CRITICAL_SECTIONS { - m_Flags.zero (); - // get page size - SYSTEM_INFO sys_inf; - GetSystemInfo (&sys_inf); - dwAllocGranularity = sys_inf.dwAllocationGranularity; - m_iLockRescan = 0; - dwOpenCounter = 0; + m_Flags.zero(); + // get page size + SYSTEM_INFO sys_inf; + GetSystemInfo(&sys_inf); + dwAllocGranularity = sys_inf.dwAllocationGranularity; + m_iLockRescan = 0; + dwOpenCounter = 0; } CLocatorAPI::~CLocatorAPI() { - VERIFY (0==m_iLockRescan); - _dump_open_files (1); -} - -void CLocatorAPI::Register (LPCSTR name, u32 vfs, u32 crc, u32 ptr, u32 size_real, u32 size_compressed, u32 modif) -{ - //Msg("Register[%d] [%s]",vfs,name); - string256 temp_file_name; - xr_strcpy (temp_file_name,sizeof(temp_file_name),name); - xr_strlwr (temp_file_name); - - // Register file - file desc; -// desc.name = xr_strlwr(xr_strdup(name)); - desc.name = temp_file_name; - desc.vfs = vfs; - desc.crc = crc; - desc.ptr = ptr; - desc.size_real = size_real; - desc.size_compressed= size_compressed; - desc.modif = modif & (~u32(0x3)); -// Msg("registering file %s - %d", name, size_real); -// if file already exist - update info - files_it I = m_files.find(desc); - if (I != m_files.end()) { -//. Msg("-- file already scanned [%s]", I->name); - desc.name = I->name; - - // sad but true, performance option - // correct way is to erase and then insert new record: - const_cast(*I) = desc; - return; - } - else { - desc.name = xr_strdup(desc.name); - } - - // otherwise insert file - m_files.insert (desc); - - // Try to register folder(s) - string_path temp; - xr_strcpy (temp,sizeof(temp),desc.name); - string_path path; - string_path folder; - while (temp[0]) - { - _splitpath (temp, path, folder, 0, 0 ); - xr_strcat (path,folder); - if (!exist(path)) - { - desc.name = xr_strdup(path); - desc.vfs = 0xffffffff; - desc.ptr = 0; - desc.size_real = 0; - desc.size_compressed= 0; - desc.modif = u32(-1); - std::pair I = m_files.insert(desc); + VERIFY(0 == m_iLockRescan); + _dump_open_files(1); +} + +void CLocatorAPI::Register(LPCSTR name, u32 vfs, u32 crc, u32 ptr, u32 size_real, u32 size_compressed, u32 modif) +{ + //Msg("Register[%d] [%s]",vfs,name); + string256 temp_file_name; + xr_strcpy(temp_file_name, sizeof(temp_file_name), name); + xr_strlwr(temp_file_name); + + // Register file + file desc; + // desc.name = xr_strlwr(xr_strdup(name)); + desc.name = temp_file_name; + desc.vfs = vfs; + desc.crc = crc; + desc.ptr = ptr; + desc.size_real = size_real; + desc.size_compressed = size_compressed; + desc.modif = modif & (~u32(0x3)); + // Msg("registering file %s - %d", name, size_real); + // if file already exist - update info + files_it I = m_files.find(desc); + if (I != m_files.end()) + { + //. Msg("-- file already scanned [%s]", I->name); + desc.name = I->name; + + // sad but true, performance option + // correct way is to erase and then insert new record: + const_cast(*I) = desc; + return; + } + else + { + desc.name = xr_strdup(desc.name); + } + + // otherwise insert file + m_files.insert(desc); + + // Try to register folder(s) + string_path temp; + xr_strcpy(temp, sizeof(temp), desc.name); + string_path path; + string_path folder; + while (temp[0]) + { + _splitpath(temp, path, folder, 0, 0); + xr_strcat(path, folder); + if (!exist(path)) + { + desc.name = xr_strdup(path); + desc.vfs = 0xffffffff; + desc.ptr = 0; + desc.size_real = 0; + desc.size_compressed = 0; + desc.modif = u32(-1); + std::pair I = m_files.insert(desc); R_ASSERT(I.second); - } - xr_strcpy (temp,sizeof(temp),folder); - if (xr_strlen(temp)) temp[xr_strlen(temp)-1]=0; - } -} - -IReader* open_chunk(void* ptr, u32 ID) -{ - BOOL res; - u32 dwType, dwSize; - DWORD read_byte; - u32 pt = SetFilePointer(ptr,0,0,FILE_BEGIN); VERIFY(pt!=INVALID_SET_FILE_POINTER); - while (true){ - res = ReadFile (ptr,&dwType,4,&read_byte,0); - if(read_byte==0) - return NULL; -//. VERIFY(res&&(read_byte==4)); - - res = ReadFile (ptr,&dwSize,4,&read_byte,0); - if(read_byte==0) - return NULL; -//. VERIFY(res&&(read_byte==4)); - - if ((dwType&(~CFS_CompressMark)) == ID) { - u8* src_data = xr_alloc(dwSize); - res = ReadFile (ptr,src_data,dwSize,&read_byte,0); VERIFY(res&&(read_byte==dwSize)); - if (dwType&CFS_CompressMark) { - BYTE* dest; - unsigned dest_sz; -// if (g_temporary_stuff) -// g_temporary_stuff (src_data,dwSize,src_data); - _decompressLZ (&dest,&dest_sz,src_data,dwSize); - xr_free (src_data); - return xr_new(dest,dest_sz,0); - } else { - return xr_new(src_data,dwSize,0); - } - }else{ - pt = SetFilePointer(ptr,dwSize,0,FILE_CURRENT); - if (pt==INVALID_SET_FILE_POINTER) return 0; - } - } - return 0; + } + xr_strcpy(temp, sizeof(temp), folder); + if (xr_strlen(temp)) temp[xr_strlen(temp) - 1] = 0; + } +} + +IReader* open_chunk(void* ptr, u32 ID) +{ + BOOL res; + u32 dwType, dwSize; + DWORD read_byte; + u32 pt = SetFilePointer(ptr, 0, 0, FILE_BEGIN); + VERIFY(pt != INVALID_SET_FILE_POINTER); + while (true) + { + res = ReadFile(ptr, &dwType, 4, &read_byte, 0); + if (read_byte == 0) + return NULL; + //. VERIFY(res&&(read_byte==4)); + + res = ReadFile(ptr, &dwSize, 4, &read_byte, 0); + if (read_byte == 0) + return NULL; + //. VERIFY(res&&(read_byte==4)); + + if ((dwType&(~CFS_CompressMark)) == ID) + { + u8* src_data = xr_alloc(dwSize); + res = ReadFile(ptr, src_data, dwSize, &read_byte, 0); + VERIFY(res && (read_byte == dwSize)); + if (dwType&CFS_CompressMark) + { + BYTE* dest; + unsigned dest_sz; + // if (g_temporary_stuff) + // g_temporary_stuff (src_data,dwSize,src_data); + _decompressLZ(&dest, &dest_sz, src_data, dwSize); + xr_free(src_data); + return xr_new(dest, dest_sz, 0); + } + else + { + return xr_new(src_data, dwSize, 0); + } + } + else + { + pt = SetFilePointer(ptr, dwSize, 0, FILE_CURRENT); + if (pt == INVALID_SET_FILE_POINTER) return 0; + } + } + return 0; }; void CLocatorAPI::LoadArchive(archive& A, LPCSTR entrypoint) { - // Create base path - string_path fs_entry_point; - fs_entry_point[0] = 0; - if(A.header) - { - - shared_str read_path = A.header->r_string("header","entry_point"); - if(0==stricmp(read_path.c_str(),"gamedata")) - { - read_path = "$fs_root$"; - PathPairIt P = pathes.find(read_path.c_str()); - if(P!=pathes.end()) - { - FS_Path* root = P->second; -// R_ASSERT3 (root, "path not found ", read_path.c_str()); - xr_strcpy (fs_entry_point, sizeof(fs_entry_point), root->m_Path); - } - xr_strcat (fs_entry_point,"gamedata\\"); - }else - { - string256 alias_name; - alias_name[0] = 0; - R_ASSERT2 (*read_path.c_str()=='$', read_path.c_str()); - - int count = sscanf(read_path.c_str(),"%[^\\]s", alias_name); - R_ASSERT2 (count==1,read_path.c_str()); - - PathPairIt P = pathes.find(alias_name); - - if(P!=pathes.end()) - { - FS_Path* root = P->second; - // R_ASSERT3 (root, "path not found ", alias_name); - xr_strcpy (fs_entry_point, sizeof(fs_entry_point), root->m_Path); - } - xr_strcat (fs_entry_point, sizeof(fs_entry_point), read_path.c_str()+xr_strlen(alias_name)+1); - } - - }else - { - R_ASSERT2 (0, "unsupported"); - xr_strcpy (fs_entry_point, sizeof(fs_entry_point), A.path.c_str()); - if(strext(fs_entry_point)) - *strext(fs_entry_point) = 0; - } - if(entrypoint) - xr_strcpy (fs_entry_point, sizeof(fs_entry_point), entrypoint); - - -// DUMMY_STUFF *g_temporary_stuff_subst = NULL; -// -// if(strstr(A.path.c_str(),".xdb")) -// { -// g_temporary_stuff_subst = g_temporary_stuff; -// g_temporary_stuff = NULL; -// } - - // Read FileSystem - A.open (); - IReader* hdr = open_chunk(A.hSrcFile,1); - R_ASSERT (hdr); - RStringVec fv; - while (!hdr->eof()) - { - string_path name,full; - string1024 buffer_start; - u16 buffer_size = hdr->r_u16(); - VERIFY (buffer_size < sizeof(name) + 4*sizeof(u32)); - VERIFY (buffer_size < sizeof(buffer_start)); - u8 *buffer = (u8*)&*buffer_start; - hdr->r (buffer,buffer_size); - - u32 size_real = *(u32*)buffer; - buffer += sizeof(size_real); - - u32 size_compr = *(u32*)buffer; - buffer += sizeof(size_compr); - - u32 crc = *(u32*)buffer; - buffer += sizeof(crc); - - u32 name_length = buffer_size - 4*sizeof(u32); - Memory.mem_copy (name,buffer,name_length); - name[name_length] = 0; - buffer += buffer_size - 4*sizeof(u32); - - u32 ptr = *(u32*)buffer; - buffer += sizeof(ptr); - - strconcat (sizeof(full), full, fs_entry_point, name); - - Register (full,A.vfs_idx,crc,ptr,size_real,size_compr,0); - } - hdr->close (); - -// if(g_temporary_stuff_subst) -// g_temporary_stuff = g_temporary_stuff_subst; + // Create base path + string_path fs_entry_point; + fs_entry_point[0] = 0; + if (A.header) + { + + shared_str read_path = A.header->r_string("header", "entry_point"); + if (0 == stricmp(read_path.c_str(), "gamedata")) + { + read_path = "$fs_root$"; + PathPairIt P = pathes.find(read_path.c_str()); + if (P != pathes.end()) + { + FS_Path* root = P->second; + // R_ASSERT3 (root, "path not found ", read_path.c_str()); + xr_strcpy(fs_entry_point, sizeof(fs_entry_point), root->m_Path); + } + xr_strcat(fs_entry_point, "gamedata\\"); + } + else + { + string256 alias_name; + alias_name[0] = 0; + R_ASSERT2(*read_path.c_str() == '$', read_path.c_str()); + + int count = sscanf(read_path.c_str(), "%[^\\]s", alias_name); + R_ASSERT2(count == 1, read_path.c_str()); + + PathPairIt P = pathes.find(alias_name); + + if (P != pathes.end()) + { + FS_Path* root = P->second; + // R_ASSERT3 (root, "path not found ", alias_name); + xr_strcpy(fs_entry_point, sizeof(fs_entry_point), root->m_Path); + } + xr_strcat(fs_entry_point, sizeof(fs_entry_point), read_path.c_str() + xr_strlen(alias_name) + 1); + } + + } + else + { + R_ASSERT2(0, "unsupported"); + xr_strcpy(fs_entry_point, sizeof(fs_entry_point), A.path.c_str()); + if (strext(fs_entry_point)) + *strext(fs_entry_point) = 0; + } + if (entrypoint) + xr_strcpy(fs_entry_point, sizeof(fs_entry_point), entrypoint); + + + // DUMMY_STUFF *g_temporary_stuff_subst = NULL; + // + // if(strstr(A.path.c_str(),".xdb")) + // { + // g_temporary_stuff_subst = g_temporary_stuff; + // g_temporary_stuff = NULL; + // } + + // Read FileSystem + A.open(); + IReader* hdr = open_chunk(A.hSrcFile, 1); + R_ASSERT(hdr); + RStringVec fv; + while (!hdr->eof()) + { + string_path name, full; + string1024 buffer_start; + u16 buffer_size = hdr->r_u16(); + VERIFY(buffer_size < sizeof(name) + 4 * sizeof(u32)); + VERIFY(buffer_size < sizeof(buffer_start)); + u8* buffer = (u8*)&*buffer_start; + hdr->r(buffer, buffer_size); + + u32 size_real = *(u32*)buffer; + buffer += sizeof(size_real); + + u32 size_compr = *(u32*)buffer; + buffer += sizeof(size_compr); + + u32 crc = *(u32*)buffer; + buffer += sizeof(crc); + + u32 name_length = buffer_size - 4 * sizeof(u32); + Memory.mem_copy(name, buffer, name_length); + name[name_length] = 0; + buffer += buffer_size - 4 * sizeof(u32); + + u32 ptr = *(u32*)buffer; + buffer += sizeof(ptr); + + strconcat(sizeof(full), full, fs_entry_point, name); + + Register(full, A.vfs_idx, crc, ptr, size_real, size_compr, 0); + } + hdr->close(); + + // if(g_temporary_stuff_subst) + // g_temporary_stuff = g_temporary_stuff_subst; } void CLocatorAPI::archive::open() { - // Open the file - if(hSrcFile && hSrcMap) - return; + // Open the file + if (hSrcFile && hSrcMap) + return; - hSrcFile = CreateFile(*path, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0); - R_ASSERT (hSrcFile!=INVALID_HANDLE_VALUE); - hSrcMap = CreateFileMapping (hSrcFile, 0, PAGE_READONLY, 0, 0, 0); - R_ASSERT (hSrcMap!=INVALID_HANDLE_VALUE); - size = GetFileSize(hSrcFile,0); - R_ASSERT (size>0); + hSrcFile = CreateFile(*path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0); + R_ASSERT(hSrcFile != INVALID_HANDLE_VALUE); + hSrcMap = CreateFileMapping(hSrcFile, 0, PAGE_READONLY, 0, 0, 0); + R_ASSERT(hSrcMap != INVALID_HANDLE_VALUE); + size = GetFileSize(hSrcFile, 0); + R_ASSERT(size > 0); } void CLocatorAPI::archive::close() { - CloseHandle (hSrcMap); - hSrcMap = NULL; - CloseHandle (hSrcFile); - hSrcFile = NULL; + CloseHandle(hSrcMap); + hSrcMap = NULL; + CloseHandle(hSrcFile); + hSrcFile = NULL; } void CLocatorAPI::ProcessArchive(LPCSTR _path) { - // find existing archive - shared_str path = _path; + // find existing archive + shared_str path = _path; + + for (archives_it it = m_archives.begin(); it != m_archives.end(); ++it) + if (it->path == path) + return; - for (archives_it it=m_archives.begin(); it!=m_archives.end(); ++it) - if (it->path==path) - return; + m_archives.push_back(archive()); + archive& A = m_archives.back(); + A.vfs_idx = m_archives.size() - 1; + A.path = path; - m_archives.push_back (archive()); - archive& A = m_archives.back(); - A.vfs_idx = m_archives.size()-1; - A.path = path; + A.open(); - A.open (); + // Read header + BOOL bProcessArchiveLoading = TRUE; - // Read header - BOOL bProcessArchiveLoading = TRUE; + // DUMMY_STUFF *g_temporary_stuff_subst = NULL; + // g_temporary_stuff_subst = g_temporary_stuff; + // g_temporary_stuff = NULL; -// DUMMY_STUFF *g_temporary_stuff_subst = NULL; -// g_temporary_stuff_subst = g_temporary_stuff; -// g_temporary_stuff = NULL; + IReader* hdr = open_chunk(A.hSrcFile, CFS_HeaderChunkID); + if (hdr) + { + A.header = xr_new(hdr, "archive_header"); + hdr->close(); + bProcessArchiveLoading = A.header->r_bool("header", "auto_load"); + } + // g_temporary_stuff = g_temporary_stuff_subst; - IReader* hdr = open_chunk(A.hSrcFile, CFS_HeaderChunkID); - if(hdr) - { - A.header = xr_new(hdr,"archive_header"); - hdr->close (); - bProcessArchiveLoading = A.header->r_bool("header","auto_load"); - } -// g_temporary_stuff = g_temporary_stuff_subst; - - if(bProcessArchiveLoading || strstr(Core.Params, "-auto_load_arch")) - LoadArchive (A); - else - A.close (); + if (bProcessArchiveLoading || strstr(Core.Params, "-auto_load_arch")) + LoadArchive(A); + else + A.close(); } void CLocatorAPI::unload_archive(CLocatorAPI::archive& A) { - files_it I = m_files.begin(); - for (; I!=m_files.end(); ++I) - { - const file& entry = *I; - if(entry.vfs==A.vfs_idx) - { + files_it I = m_files.begin(); + for (; I != m_files.end(); ++I) + { + const file& entry = *I; + if (entry.vfs == A.vfs_idx) + { #ifndef MASTER_GOLD - Msg("unregistering file [%s]", I->name); + Msg("unregistering file [%s]", I->name); #endif // #ifndef MASTER_GOLD - char* str = LPSTR(I->name); - xr_free (str); - m_files.erase (I); - break; - } - } - A.close(); + char* str = LPSTR(I->name); + xr_free(str); + m_files.erase(I); + break; + } + } + A.close(); } bool CLocatorAPI::load_all_unloaded_archives() { - archives_it it = m_archives.begin(); - archives_it it_e = m_archives.end(); - bool res = false; - for(;it!=it_e;++it) - { - archive& A = *it; - if(A.hSrcFile==NULL) - { - LoadArchive(A); - res = true; - } - } - return res; + archives_it it = m_archives.begin(); + archives_it it_e = m_archives.end(); + bool res = false; + for (; it != it_e; ++it) + { + archive& A = *it; + if (A.hSrcFile == NULL) + { + LoadArchive(A); + res = true; + } + } + return res; } void CLocatorAPI::ProcessOne(LPCSTR path, const _finddata_t& entry) { - string_path N; - xr_strcpy (N,sizeof(N),path); - xr_strcat (N,entry.name); - xr_strlwr (N); - - if (entry.attrib&_A_HIDDEN) return; - - if (entry.attrib&_A_SUBDIR) { - if (bNoRecurse) return; - if (0==xr_strcmp(entry.name,".")) return; - if (0==xr_strcmp(entry.name,"..")) return; - xr_strcat (N,"\\"); - Register (N,0xffffffff,0,0,entry.size,entry.size,(u32)entry.time_write); - Recurse (N); - } else { - if (strext(N) && (0==strncmp(strext(N),".db",3) || 0==strncmp(strext(N),".xdb",4)) ) - ProcessArchive (N); - else - Register (N,0xffffffff,0,0,entry.size,entry.size,(u32)entry.time_write); - } + string_path N; + xr_strcpy(N, sizeof(N), path); + xr_strcat(N, entry.name); + xr_strlwr(N); + + if (entry.attrib&_A_HIDDEN) return; + + if (entry.attrib&_A_SUBDIR) + { + if (bNoRecurse) return; + if (0 == xr_strcmp(entry.name, ".")) return; + if (0 == xr_strcmp(entry.name, "..")) return; + xr_strcat(N, "\\"); + Register(N, 0xffffffff, 0, 0, entry.size, entry.size, (u32)entry.time_write); + Recurse(N); + } + else + { + if (strext(N) && (0 == strncmp(strext(N), ".db", 3) || 0 == strncmp(strext(N), ".xdb", 4))) + ProcessArchive(N); + else + Register(N, 0xffffffff, 0, 0, entry.size, entry.size, (u32)entry.time_write); + } } IC bool pred_str_ff(const _finddata_t& x, const _finddata_t& y) -{ - return xr_strcmp(x.name,y.name)<0; +{ + return xr_strcmp(x.name, y.name) < 0; } bool ignore_name(const char* _name) { - // ignore processing ".svn" folders - return ( _name[0]=='.' && _name[1]=='s' && _name[2]=='v' && _name[3]=='n' && _name[4]==0); + // ignore processing ".svn" folders + return (_name[0] == '.' && _name[1] == 's' && _name[2] == 'v' && _name[3] == 'n' && _name[4] == 0); } // we need to check for file existance -// because Unicode file names can +// because Unicode file names can // be interpolated by FindNextFile() -bool ignore_path(const char* _path){ - HANDLE h = CreateFile( _path, 0, 0, NULL, OPEN_EXISTING, - FILE_ATTRIBUTE_READONLY | FILE_FLAG_NO_BUFFERING, NULL); +bool ignore_path(const char* _path) +{ + HANDLE h = CreateFile(_path, 0, 0, NULL, OPEN_EXISTING, + FILE_ATTRIBUTE_READONLY | FILE_FLAG_NO_BUFFERING, NULL); - if (h!=INVALID_HANDLE_VALUE) - { - CloseHandle(h); - return false; - } - else - return true; + if (h != INVALID_HANDLE_VALUE) + { + CloseHandle(h); + return false; + } + else + return true; } -bool CLocatorAPI::Recurse (const char* path) +bool CLocatorAPI::Recurse(const char* path) { string_path scanPath; xr_strcpy(scanPath, sizeof(scanPath), path); @@ -586,10 +613,10 @@ bool CLocatorAPI::Recurse (const char* path) size_t newSize = rec_files.size(); if (newSize > oldSize) { - std::sort(rec_files.begin()+oldSize, rec_files.end(), pred_str_ff); + std::sort(rec_files.begin() + oldSize, rec_files.end(), pred_str_ff); for (size_t i = oldSize; i < newSize; i++) ProcessOne(path, rec_files[i]); - rec_files.erase(rec_files.begin()+oldSize, rec_files.end()); + rec_files.erase(rec_files.begin() + oldSize, rec_files.end()); } // insert self if (path && path[0] != 0) @@ -597,826 +624,856 @@ bool CLocatorAPI::Recurse (const char* path) return true; } -bool file_handle_internal (LPCSTR file_name, u32 &size, int &file_handle); -void *FileDownload (LPCSTR file_name, const int &file_handle, u32 &file_size); +bool file_handle_internal(LPCSTR file_name, u32& size, int& file_handle); +void* FileDownload(LPCSTR file_name, const int& file_handle, u32& file_size); -void CLocatorAPI::setup_fs_path (LPCSTR fs_name, string_path &fs_path) +void CLocatorAPI::setup_fs_path(LPCSTR fs_name, string_path& fs_path) { - xr_strcpy (fs_path,fs_name ? fs_name : ""); - LPSTR slash = strrchr(fs_path,'\\'); - if (!slash) - slash = strrchr(fs_path,'/'); - if (!slash) { - xr_strcpy (fs_path,""); - return; - } + xr_strcpy(fs_path, fs_name ? fs_name : ""); + LPSTR slash = strrchr(fs_path, '\\'); + if (!slash) + slash = strrchr(fs_path, '/'); + if (!slash) + { + xr_strcpy(fs_path, ""); + return; + } - *(slash+1) = 0; + *(slash + 1) = 0; } -void CLocatorAPI::setup_fs_path (LPCSTR fs_name) +void CLocatorAPI::setup_fs_path(LPCSTR fs_name) { - string_path fs_path; - setup_fs_path (fs_name, fs_path); + string_path fs_path; + setup_fs_path(fs_name, fs_path); - string_path full_current_directory; - _fullpath (full_current_directory, fs_path, sizeof(full_current_directory)); + string_path full_current_directory; + _fullpath(full_current_directory, fs_path, sizeof(full_current_directory)); - FS_Path *path = xr_new(full_current_directory,"","","",0); + FS_Path* path = xr_new(full_current_directory, "", "", "", 0); #ifdef DEBUG - Msg ("$fs_root$ = %s", full_current_directory); + Msg("$fs_root$ = %s", full_current_directory); #endif // #ifdef DEBUG - pathes.insert ( - std::make_pair( - xr_strdup("$fs_root$"), - path - ) - ); + pathes.insert( + std::make_pair( + xr_strdup("$fs_root$"), + path + ) + ); } -IReader *CLocatorAPI::setup_fs_ltx (LPCSTR fs_name) +IReader* CLocatorAPI::setup_fs_ltx(LPCSTR fs_name) { - setup_fs_path (fs_name); + setup_fs_path(fs_name); + + // if (m_Flags.is(flTargetFolderOnly)) { + // append_path ("$fs_root$", "", 0, FALSE); + // return (0); + // } -// if (m_Flags.is(flTargetFolderOnly)) { -// append_path ("$fs_root$", "", 0, FALSE); -// return (0); -// } + LPCSTR fs_file_name = FSLTX; + if (fs_name && *fs_name) + fs_file_name = fs_name; - LPCSTR fs_file_name = FSLTX; - if (fs_name && *fs_name) - fs_file_name= fs_name; - - Log ("using fs-ltx",fs_file_name); + Log("using fs-ltx", fs_file_name); - int file_handle; - u32 file_size; - IReader *result = 0; - CHECK_OR_EXIT ( - file_handle_internal(fs_file_name, file_size, file_handle), - make_string("Cannot open file \"%s\".\nCheck your working folder.",fs_file_name) - ); + int file_handle; + u32 file_size; + IReader* result = 0; + CHECK_OR_EXIT( + file_handle_internal(fs_file_name, file_size, file_handle), + make_string("Cannot open file \"%s\".\nCheck your working folder.", fs_file_name) + ); - void *buffer = FileDownload(fs_file_name, file_handle, file_size); - result = xr_new(buffer,file_size,0); + void* buffer = FileDownload(fs_file_name, file_handle, file_size); + result = xr_new(buffer, file_size, 0); #ifdef DEBUG - if (result && m_Flags.is(flBuildCopy|flReady)) - copy_file_to_build (result, fs_file_name); + if (result && m_Flags.is(flBuildCopy | flReady)) + copy_file_to_build(result, fs_file_name); #endif // DEBUG - if (m_Flags.test(flDumpFileActivity)) - _register_open_file (result, fs_file_name); + if (m_Flags.test(flDumpFileActivity)) + _register_open_file(result, fs_file_name); - return (result); + return (result); } -void CLocatorAPI::_initialize (u32 flags, LPCSTR target_folder, LPCSTR fs_name) +void CLocatorAPI::_initialize(u32 flags, LPCSTR target_folder, LPCSTR fs_name) { - char _delimiter = '|'; //',' - if (m_Flags.is(flReady))return; - CTimer t; - t.Start(); - Log ("Initializing File System..."); - u32 M1 = Memory.mem_usage(); + char _delimiter = '|'; //',' + if (m_Flags.is(flReady))return; + CTimer t; + t.Start(); + Log("Initializing File System..."); + u32 M1 = Memory.mem_usage(); - m_Flags.set (flags,TRUE); + m_Flags.set(flags, TRUE); - // scan root directory - bNoRecurse = TRUE; - string4096 buf; + // scan root directory + bNoRecurse = TRUE; + string4096 buf; - // append application path - if (m_Flags.is(flScanAppRoot)) - append_path ("$app_root$",Core.ApplicationPath,0,FALSE); + // append application path + if (m_Flags.is(flScanAppRoot)) + append_path("$app_root$", Core.ApplicationPath, 0, FALSE); - //----------------------------------------------------------- - // append application data path - // target folder - if (m_Flags.is(flTargetFolderOnly)) - { - append_path ("$target_folder$",target_folder,0,TRUE); - }else - { - IReader *pFSltx = setup_fs_ltx(fs_name); -/* - LPCSTR fs_ltx = (fs_name&&fs_name[0])?fs_name:FSLTX; - F = r_open(fs_ltx); - if (!F&&m_Flags.is(flScanAppRoot)) - F = r_open("$app_root$",fs_ltx); - - if (!F) - { - string_path tmpAppPath = ""; - xr_strcpy(tmpAppPath,sizeof(tmpAppPath), Core.ApplicationPath); - if (xr_strlen(tmpAppPath)) - { - tmpAppPath[xr_strlen(tmpAppPath)-1] = 0; - if (strrchr(tmpAppPath, '\\')) - *(strrchr(tmpAppPath, '\\')+1) = 0; - - FS_Path* pFSRoot = FS.get_path("$fs_root$"); - pFSRoot->_set_root (tmpAppPath); - rescan_path (pFSRoot->m_Path, pFSRoot->m_Flags.is(FS_Path::flRecurse)); - } - F = r_open("$fs_root$",fs_ltx); - } - - Log ("using fs-ltx",fs_ltx); -*/ - // append all pathes - string_path id, root, add, def, capt; - LPCSTR lp_add, lp_def, lp_capt; - string16 b_v; - string4096 temp; - - while(!pFSltx->eof()) - { - pFSltx->r_string (buf,sizeof(buf)); - if(buf[0]==';') continue; - - _GetItem (buf,0,id,'='); - - if (!m_Flags.is(flBuildCopy)&&(0==xr_strcmp(id,"$build_copy$"))) - continue; - - _GetItem (buf,1,temp,'='); - int cnt = _GetItemCount(temp,_delimiter); - R_ASSERT2 (cnt>=3,temp); - u32 fl = 0; - _GetItem (temp,0,b_v,_delimiter); - - if (CInifile::IsBOOL(b_v)) - fl |= FS_Path::flRecurse; - - _GetItem (temp,1,b_v,_delimiter); - if (CInifile::IsBOOL(b_v)) - fl |= FS_Path::flNotif; - - _GetItem (temp,2,root,_delimiter); - _GetItem (temp,3,add,_delimiter); - _GetItem (temp,4,def,_delimiter); - _GetItem (temp,5,capt,_delimiter); - xr_strlwr (id); - - - xr_strlwr (root); - lp_add =(cnt>=4)?xr_strlwr(add):0; - lp_def =(cnt>=5)?def:0; - lp_capt =(cnt>=6)?capt:0; - - PathPairIt p_it = pathes.find(root); - - std::pair I; - FS_Path* P = xr_new((p_it!=pathes.end())?p_it->second->m_Path:root,lp_add,lp_def,lp_capt,fl); - bNoRecurse = !(fl&FS_Path::flRecurse); - Recurse (P->m_Path); - I = pathes.insert(mk_pair(xr_strdup(id),P)); + //----------------------------------------------------------- + // append application data path + // target folder + if (m_Flags.is(flTargetFolderOnly)) + { + append_path("$target_folder$", target_folder, 0, TRUE); + } + else + { + IReader* pFSltx = setup_fs_ltx(fs_name); + /* + LPCSTR fs_ltx = (fs_name&&fs_name[0])?fs_name:FSLTX; + F = r_open(fs_ltx); + if (!F&&m_Flags.is(flScanAppRoot)) + F = r_open("$app_root$",fs_ltx); + + if (!F) + { + string_path tmpAppPath = ""; + xr_strcpy(tmpAppPath,sizeof(tmpAppPath), Core.ApplicationPath); + if (xr_strlen(tmpAppPath)) + { + tmpAppPath[xr_strlen(tmpAppPath)-1] = 0; + if (strrchr(tmpAppPath, '\\')) + *(strrchr(tmpAppPath, '\\')+1) = 0; + + FS_Path* pFSRoot = FS.get_path("$fs_root$"); + pFSRoot->_set_root (tmpAppPath); + rescan_path (pFSRoot->m_Path, pFSRoot->m_Flags.is(FS_Path::flRecurse)); + } + F = r_open("$fs_root$",fs_ltx); + } + + Log ("using fs-ltx",fs_ltx); + */ + // append all pathes + string_path id, root, add, def, capt; + LPCSTR lp_add, lp_def, lp_capt; + string16 b_v; + string4096 temp; + + while (!pFSltx->eof()) + { + pFSltx->r_string(buf, sizeof(buf)); + if (buf[0] == ';') continue; + + _GetItem(buf, 0, id, '='); + + if (!m_Flags.is(flBuildCopy) && (0 == xr_strcmp(id, "$build_copy$"))) + continue; + + _GetItem(buf, 1, temp, '='); + int cnt = _GetItemCount(temp, _delimiter); + R_ASSERT2(cnt >= 3, temp); + u32 fl = 0; + _GetItem(temp, 0, b_v, _delimiter); + + if (CInifile::IsBOOL(b_v)) + fl |= FS_Path::flRecurse; + + _GetItem(temp, 1, b_v, _delimiter); + if (CInifile::IsBOOL(b_v)) + fl |= FS_Path::flNotif; + + _GetItem(temp, 2, root, _delimiter); + _GetItem(temp, 3, add, _delimiter); + _GetItem(temp, 4, def, _delimiter); + _GetItem(temp, 5, capt, _delimiter); + xr_strlwr(id); + + + xr_strlwr(root); + lp_add = (cnt >= 4) ? xr_strlwr(add) : 0; + lp_def = (cnt >= 5) ? def : 0; + lp_capt = (cnt >= 6) ? capt : 0; + + PathPairIt p_it = pathes.find(root); + + std::pair I; + FS_Path* P = xr_new((p_it != pathes.end()) ? p_it->second->m_Path : root, lp_add, lp_def, lp_capt, fl); + bNoRecurse = !(fl&FS_Path::flRecurse); + Recurse(P->m_Path); + I = pathes.insert(mk_pair(xr_strdup(id), P)); #ifndef DEBUG - m_Flags.set (flCacheFiles,FALSE); + m_Flags.set(flCacheFiles, FALSE); #endif // DEBUG - CHECK_OR_EXIT (I.second,"The file 'fsgame.ltx' is corrupted (it contains duplicated lines).\nPlease reinstall the game or fix the problem manually."); - } - r_close (pFSltx); - R_ASSERT (path_exist("$app_data_root$")); - }; - + CHECK_OR_EXIT(I.second, "The file 'fsgame.ltx' is corrupted (it contains duplicated lines).\nPlease reinstall the game or fix the problem manually."); + } + r_close(pFSltx); + R_ASSERT(path_exist("$app_data_root$")); + }; + - u32 M2 = Memory.mem_usage(); - Msg ("FS: %d files cached %d archives, %dKb memory used.",m_files.size(),m_archives.size(), (M2-M1)/1024); + u32 M2 = Memory.mem_usage(); + Msg("FS: %d files cached %d archives, %dKb memory used.", m_files.size(), m_archives.size(), (M2 - M1) / 1024); - m_Flags.set (flReady,TRUE); + m_Flags.set(flReady, TRUE); - Msg("Init FileSystem %f sec",t.GetElapsed_sec()); - //----------------------------------------------------------- - if (strstr(Core.Params, "-overlaypath")) - { - string1024 c_newAppPathRoot; - sscanf (strstr(Core.Params,"-overlaypath ")+13,"%[^ ] ",c_newAppPathRoot); - FS_Path* pLogsPath = FS.get_path("$logs$"); - FS_Path* pAppdataPath = FS.get_path("$app_data_root$"); + Msg("Init FileSystem %f sec", t.GetElapsed_sec()); + //----------------------------------------------------------- + if (strstr(Core.Params, "-overlaypath")) + { + string1024 c_newAppPathRoot; + sscanf(strstr(Core.Params, "-overlaypath ") + 13, "%[^ ] ", c_newAppPathRoot); + FS_Path* pLogsPath = FS.get_path("$logs$"); + FS_Path* pAppdataPath = FS.get_path("$app_data_root$"); - if (pLogsPath) pLogsPath->_set_root(c_newAppPathRoot); - if (pAppdataPath) - { - pAppdataPath->_set_root(c_newAppPathRoot); - rescan_path(pAppdataPath->m_Path, pAppdataPath->m_Flags.is(FS_Path::flRecurse)); - } + if (pLogsPath) pLogsPath->_set_root(c_newAppPathRoot); + if (pAppdataPath) + { + pAppdataPath->_set_root(c_newAppPathRoot); + rescan_path(pAppdataPath->m_Path, pAppdataPath->m_Flags.is(FS_Path::flRecurse)); + } - int x=0; - x=x; - } + int x = 0; + x = x; + } - rec_files.clear (); - //----------------------------------------------------------- + rec_files.clear(); + //----------------------------------------------------------- - CreateLog (0!=strstr(Core.Params,"-nolog")); + CreateLog(0 != strstr(Core.Params, "-nolog")); } -void CLocatorAPI::_destroy () +void CLocatorAPI::_destroy() { - CloseLog (); + CloseLog(); - for (files_it I=m_files.begin(); I!=m_files.end(); I++) - { - char* str = LPSTR(I->name); - xr_free (str); - } - m_files.clear (); - for (PathPairIt p_it=pathes.begin(); p_it!=pathes.end(); p_it++) + for (files_it I = m_files.begin(); I != m_files.end(); I++) + { + char* str = LPSTR(I->name); + xr_free(str); + } + m_files.clear(); + for (PathPairIt p_it = pathes.begin(); p_it != pathes.end(); p_it++) { - char* str = LPSTR(p_it->first); - xr_free (str); - xr_delete (p_it->second); + char* str = LPSTR(p_it->first); + xr_free(str); + xr_delete(p_it->second); } - pathes.clear (); - for (archives_it a_it=m_archives.begin(); a_it!=m_archives.end(); a_it++) + pathes.clear(); + for (archives_it a_it = m_archives.begin(); a_it != m_archives.end(); a_it++) { - xr_delete (a_it->header); - a_it->close (); + xr_delete(a_it->header); + a_it->close(); } - m_archives.clear (); + m_archives.clear(); } -const CLocatorAPI::file* CLocatorAPI::exist (const char* fn) +const CLocatorAPI::file* CLocatorAPI::exist(const char* fn) { - files_it it = file_find_it(fn); - return (it!=m_files.end())?&(*it):0; + files_it it = file_find_it(fn); + return (it != m_files.end()) ? &(*it) : 0; } -const CLocatorAPI::file* CLocatorAPI::exist (const char* path, const char* name) +const CLocatorAPI::file* CLocatorAPI::exist(const char* path, const char* name) { - string_path temp; - update_path (temp,path,name); - return exist(temp); + string_path temp; + update_path(temp, path, name); + return exist(temp); } -const CLocatorAPI::file* CLocatorAPI::exist (string_path& fn, LPCSTR path, LPCSTR name) +const CLocatorAPI::file* CLocatorAPI::exist(string_path& fn, LPCSTR path, LPCSTR name) { - update_path (fn,path,name); - return exist(fn); + update_path(fn, path, name); + return exist(fn); } -const CLocatorAPI::file* CLocatorAPI::exist (string_path& fn, LPCSTR path, LPCSTR name, LPCSTR ext) +const CLocatorAPI::file* CLocatorAPI::exist(string_path& fn, LPCSTR path, LPCSTR name, LPCSTR ext) { - string_path nm; - strconcat (sizeof(nm),nm,name,ext); - update_path (fn,path,nm); - return exist(fn); + string_path nm; + strconcat(sizeof(nm), nm, name, ext); + update_path(fn, path, nm); + return exist(fn); } -xr_vector* CLocatorAPI::file_list_open (const char* initial, const char* folder, u32 flags) +xr_vector* CLocatorAPI::file_list_open(const char* initial, const char* folder, u32 flags) { - string_path N; - R_ASSERT (initial&&initial[0]); - update_path (N,initial,folder); - return file_list_open(N,flags); + string_path N; + R_ASSERT(initial&&initial[0]); + update_path(N, initial, folder); + return file_list_open(N, flags); } -xr_vector* CLocatorAPI::file_list_open (const char* _path, u32 flags) +xr_vector* CLocatorAPI::file_list_open(const char* _path, u32 flags) { - R_ASSERT (_path); - VERIFY (flags); - // ïðîâåðèòü íóæíî ëè ïåðåñêàíèðîâàòü ïóòè - check_pathes (); + R_ASSERT(_path); + VERIFY(flags); + // ïðîâåðèòü íóæíî ëè ïåðåñêàíèðîâàòü ïóòè + check_pathes(); - string_path N; + string_path N; - if (path_exist(_path)) - update_path (N,_path,""); - else - xr_strcpy(N,sizeof(N), _path); + if (path_exist(_path)) + update_path(N, _path, ""); + else + xr_strcpy(N, sizeof(N), _path); - file desc; - desc.name = N; - files_it I = m_files.find(desc); - if (I==m_files.end()) return 0; - - xr_vector* dest = xr_new > (); + file desc; + desc.name = N; + files_it I = m_files.find(desc); + if (I == m_files.end()) return 0; + + xr_vector* dest = xr_new >(); + + size_t base_len = xr_strlen(N); + for (++I; I != m_files.end(); I++) + { + const file& entry = *I; + if (0 != strncmp(entry.name, N, base_len)) break; // end of list + const char* end_symbol = entry.name + xr_strlen(entry.name) - 1; + if ((*end_symbol) != '\\') + { + // file + if ((flags&FS_ListFiles) == 0) continue; + + const char* entry_begin = entry.name + base_len; + if ((flags&FS_RootOnly) && strstr(entry_begin, "\\")) continue; // folder in folder + dest->push_back(xr_strdup(entry_begin)); + LPSTR fname = dest->back(); + if (flags&FS_ClampExt) if (0 != strext(fname)) *strext(fname) = 0; + } + else + { + // folder + if ((flags&FS_ListFolders) == 0)continue; + const char* entry_begin = entry.name + base_len; - size_t base_len = xr_strlen(N); - for (++I; I!=m_files.end(); I++) - { - const file& entry = *I; - if (0!=strncmp(entry.name,N,base_len)) break; // end of list - const char* end_symbol = entry.name+xr_strlen(entry.name)-1; - if ((*end_symbol) !='\\') { - // file - if ((flags&FS_ListFiles) == 0) continue; + if ((flags&FS_RootOnly) && (strstr(entry_begin, "\\") != end_symbol)) continue; // folder in folder - const char* entry_begin = entry.name+base_len; - if ((flags&FS_RootOnly)&&strstr(entry_begin,"\\")) continue; // folder in folder - dest->push_back (xr_strdup(entry_begin)); - LPSTR fname = dest->back(); - if (flags&FS_ClampExt) if (0!=strext(fname)) *strext(fname)=0; - } else { - // folder - if ((flags&FS_ListFolders) == 0)continue; - const char* entry_begin = entry.name+base_len; - - if ((flags&FS_RootOnly)&&(strstr(entry_begin,"\\")!=end_symbol)) continue; // folder in folder - - dest->push_back (xr_strdup(entry_begin)); - } - } - return dest; + dest->push_back(xr_strdup(entry_begin)); + } + } + return dest; } -void CLocatorAPI::file_list_close (xr_vector* &lst) +void CLocatorAPI::file_list_close(xr_vector*& lst) { - if (lst) - { - for (xr_vector::iterator I=lst->begin(); I!=lst->end(); I++) - xr_free (*I); - xr_delete (lst); - } + if (lst) + { + for (xr_vector::iterator I = lst->begin(); I != lst->end(); I++) + xr_free(*I); + xr_delete(lst); + } } int CLocatorAPI::file_list(FS_FileSet& dest, LPCSTR path, u32 flags, LPCSTR mask) { - R_ASSERT (path); - VERIFY (flags); - // ïðîâåðèòü íóæíî ëè ïåðåñêàíèðîâàòü ïóòè - check_pathes (); - - string_path N; - if (path_exist(path)) - update_path (N,path,""); - else - xr_strcpy(N,sizeof(N),path); - - file desc; - desc.name = N; - files_it I = m_files.find(desc); - if (I==m_files.end()) return 0; - - SStringVec masks; - _SequenceToList (masks,mask); - BOOL b_mask = !masks.empty(); - - size_t base_len = xr_strlen(N); - for (++I; I!=m_files.end(); ++I) - { - const file& entry = *I; - if (0!=strncmp(entry.name,N,base_len)) break; // end of list - LPCSTR end_symbol = entry.name+xr_strlen(entry.name)-1; - if ((*end_symbol) !='\\') - { - // file - if ((flags&FS_ListFiles) == 0) continue; - LPCSTR entry_begin = entry.name+base_len; - if ((flags&FS_RootOnly)&&strstr(entry_begin,"\\")) continue; // folder in folder - // check extension - if (b_mask){ - bool bOK = false; - for (SStringVecIt it=masks.begin(); it!=masks.end(); it++) - { - if (PatternMatch(entry_begin,it->c_str())) - { - bOK=true; - break; - } - } - if (!bOK) continue; - } + R_ASSERT(path); + VERIFY(flags); + // ïðîâåðèòü íóæíî ëè ïåðåñêàíèðîâàòü ïóòè + check_pathes(); + + string_path N; + if (path_exist(path)) + update_path(N, path, ""); + else + xr_strcpy(N, sizeof(N), path); + + file desc; + desc.name = N; + files_it I = m_files.find(desc); + if (I == m_files.end()) return 0; + + SStringVec masks; + _SequenceToList(masks, mask); + BOOL b_mask = !masks.empty(); + + size_t base_len = xr_strlen(N); + for (++I; I != m_files.end(); ++I) + { + const file& entry = *I; + if (0 != strncmp(entry.name, N, base_len)) break; // end of list + LPCSTR end_symbol = entry.name + xr_strlen(entry.name) - 1; + if ((*end_symbol) != '\\') + { + // file + if ((flags&FS_ListFiles) == 0) continue; + LPCSTR entry_begin = entry.name + base_len; + if ((flags&FS_RootOnly) && strstr(entry_begin, "\\")) continue; // folder in folder + // check extension + if (b_mask) + { + bool bOK = false; + for (SStringVecIt it = masks.begin(); it != masks.end(); it++) + { + if (PatternMatch(entry_begin, it->c_str())) + { + bOK = true; + break; + } + } + if (!bOK) continue; + } FS_File file; - if (flags&FS_ClampExt) + if (flags&FS_ClampExt) file.name = EFS.ChangeFileExt(entry_begin, ""); - else + else file.name = entry_begin; - u32 fl = (entry.vfs!=0xffffffff?FS_File::flVFS:0); - file.size = entry.size_real; - file.time_write = entry.modif; - file.attrib = fl; + u32 fl = (entry.vfs != 0xffffffff ? FS_File::flVFS : 0); + file.size = entry.size_real; + file.time_write = entry.modif; + file.attrib = fl; dest.insert(file); - } else { - // folder - if ((flags&FS_ListFolders) == 0) continue; - LPCSTR entry_begin = entry.name+base_len; - - if ((flags&FS_RootOnly)&&(strstr(entry_begin,"\\")!=end_symbol)) continue; // folder in folder - u32 fl = FS_File::flSubDir|(entry.vfs?FS_File::flVFS:0); - dest.insert(FS_File(entry_begin,entry.size_real,entry.modif,fl)); - } - } - return dest.size(); -} - -void CLocatorAPI::check_cached_files (LPSTR fname, const u32 &fname_size, const file &desc, LPCSTR &source_name) -{ - string_path fname_copy; - if (pathes.size() <= 1) - return; - - if (!path_exist("$server_root$")) - return; - - LPCSTR path_base = get_path("$server_root$")->m_Path; - u32 len_base = xr_strlen(path_base); - LPCSTR path_file = fname; - u32 len_file = xr_strlen(path_file); - if (len_file <= len_base) - return; - - if ((len_base == 1) && (*path_base == '\\')) - len_base = 0; - - if (0!=memcmp(path_base,fname,len_base)) - return; - - BOOL bCopy = FALSE; - - string_path fname_in_cache ; - update_path (fname_in_cache,"$cache$",path_file+len_base); - files_it fit = file_find_it(fname_in_cache); - if (fit!=m_files.end()) - { - // use - const file& fc = *fit; - if ((fc.size_real == desc.size_real)&&(fc.modif==desc.modif)) { - // use - } else { - // copy & use - Msg ("copy: db[%X],cache[%X] - '%s', ",desc.modif,fc.modif,fname); - bCopy = TRUE; - } - } else { - // copy & use - bCopy = TRUE; - } - - // copy if need - if (bCopy) { - IReader *_src; - if (desc.size_real<256*1024) _src = xr_new (fname); - else _src = xr_new (fname); - IWriter* _dst = xr_new (fname_in_cache,false); - _dst->w (_src->pointer(),_src->length()); - xr_delete (_dst); - xr_delete (_src); - set_file_age (fname_in_cache,desc.modif); - Register (fname_in_cache,0xffffffff,0,0,desc.size_real,desc.size_real,desc.modif); - } - - // Use - source_name = &fname_copy[0]; - xr_strcpy (fname_copy,sizeof(fname_copy),fname); - xr_strcpy (fname,fname_size,fname_in_cache); -} - -void CLocatorAPI::file_from_cache_impl (IReader *&R, LPSTR fname, const file &desc) -{ - if (desc.size_real<16*1024) { - R = xr_new(fname); - return; - } - - R = xr_new(fname); -} - -void CLocatorAPI::file_from_cache_impl (CStreamReader *&R, LPSTR fname, const file &desc) -{ - CFileStreamReader *r = xr_new(); - r->construct (fname,BIG_FILE_READER_WINDOW_SIZE); - R = r; + } + else + { + // folder + if ((flags&FS_ListFolders) == 0) continue; + LPCSTR entry_begin = entry.name + base_len; + + if ((flags&FS_RootOnly) && (strstr(entry_begin, "\\") != end_symbol)) continue; // folder in folder + u32 fl = FS_File::flSubDir | (entry.vfs ? FS_File::flVFS : 0); + dest.insert(FS_File(entry_begin, entry.size_real, entry.modif, fl)); + } + } + return dest.size(); +} + +void CLocatorAPI::check_cached_files(LPSTR fname, const u32& fname_size, const file& desc, LPCSTR& source_name) +{ + string_path fname_copy; + if (pathes.size() <= 1) + return; + + if (!path_exist("$server_root$")) + return; + + LPCSTR path_base = get_path("$server_root$")->m_Path; + u32 len_base = xr_strlen(path_base); + LPCSTR path_file = fname; + u32 len_file = xr_strlen(path_file); + if (len_file <= len_base) + return; + + if ((len_base == 1) && (*path_base == '\\')) + len_base = 0; + + if (0 != memcmp(path_base, fname, len_base)) + return; + + BOOL bCopy = FALSE; + + string_path fname_in_cache; + update_path(fname_in_cache, "$cache$", path_file + len_base); + files_it fit = file_find_it(fname_in_cache); + if (fit != m_files.end()) + { + // use + const file& fc = *fit; + if ((fc.size_real == desc.size_real) && (fc.modif == desc.modif)) + { + // use + } + else + { + // copy & use + Msg("copy: db[%X],cache[%X] - '%s', ", desc.modif, fc.modif, fname); + bCopy = TRUE; + } + } + else + { + // copy & use + bCopy = TRUE; + } + + // copy if need + if (bCopy) + { + IReader* _src; + if (desc.size_real < 256 * 1024) _src = xr_new(fname); + else _src = xr_new(fname); + IWriter* _dst = xr_new(fname_in_cache, false); + _dst->w(_src->pointer(), _src->length()); + xr_delete(_dst); + xr_delete(_src); + set_file_age(fname_in_cache, desc.modif); + Register(fname_in_cache, 0xffffffff, 0, 0, desc.size_real, desc.size_real, desc.modif); + } + + // Use + source_name = &fname_copy[0]; + xr_strcpy(fname_copy, sizeof(fname_copy), fname); + xr_strcpy(fname, fname_size, fname_in_cache); +} + +void CLocatorAPI::file_from_cache_impl(IReader*& R, LPSTR fname, const file& desc) +{ + if (desc.size_real < 16 * 1024) + { + R = xr_new(fname); + return; + } + + R = xr_new(fname); +} + +void CLocatorAPI::file_from_cache_impl(CStreamReader*& R, LPSTR fname, const file& desc) +{ + CFileStreamReader* r = xr_new(); + r->construct(fname, BIG_FILE_READER_WINDOW_SIZE); + R = r; } template -void CLocatorAPI::file_from_cache (T *&R, LPSTR fname, const u32 &fname_size, const file &desc, LPCSTR &source_name) +void CLocatorAPI::file_from_cache(T*& R, LPSTR fname, const u32& fname_size, const file& desc, LPCSTR& source_name) { #ifdef DEBUG - if (m_Flags.is(flCacheFiles)) - check_cached_files (fname,fname_size,desc,source_name); + if (m_Flags.is(flCacheFiles)) + check_cached_files(fname, fname_size, desc, source_name); #endif // DEBUG - - file_from_cache_impl (R,fname,desc); + + file_from_cache_impl(R, fname, desc); } -void CLocatorAPI::file_from_archive (IReader *&R, LPCSTR fname, const file &desc) +void CLocatorAPI::file_from_archive(IReader*& R, LPCSTR fname, const file& desc) { - // Archived one - archive& A = m_archives[desc.vfs]; - u32 start = (desc.ptr/dwAllocGranularity)*dwAllocGranularity; - u32 end = (desc.ptr+desc.size_compressed)/dwAllocGranularity; - if ((desc.ptr+desc.size_compressed)%dwAllocGranularity) end+=1; - end *= dwAllocGranularity; - if (end>A.size) end = A.size; - u32 sz = (end-start); - u8* ptr = (u8*)MapViewOfFile(A.hSrcMap, FILE_MAP_READ, 0, start, sz); VERIFY3(ptr,"cannot create file mapping on file",fname); + // Archived one + archive& A = m_archives[desc.vfs]; + u32 start = (desc.ptr / dwAllocGranularity)*dwAllocGranularity; + u32 end = (desc.ptr + desc.size_compressed) / dwAllocGranularity; + if ((desc.ptr + desc.size_compressed) % dwAllocGranularity) end += 1; + end *= dwAllocGranularity; + if (end > A.size) end = A.size; + u32 sz = (end - start); + u8* ptr = (u8*)MapViewOfFile(A.hSrcMap, FILE_MAP_READ, 0, start, sz); + VERIFY3(ptr, "cannot create file mapping on file", fname); - string512 temp; - xr_sprintf (temp, sizeof(temp),"%s:%s",*A.path,fname); + string512 temp; + xr_sprintf(temp, sizeof(temp), "%s:%s", *A.path, fname); #ifdef FS_DEBUG - register_file_mapping (ptr,sz,temp); + register_file_mapping(ptr, sz, temp); #endif // DEBUG - u32 ptr_offs = desc.ptr-start; - if (desc.size_real == desc.size_compressed) { - R = xr_new(ptr,ptr+ptr_offs,desc.size_real); - return; - } + u32 ptr_offs = desc.ptr - start; + if (desc.size_real == desc.size_compressed) + { + R = xr_new(ptr, ptr + ptr_offs, desc.size_real); + return; + } - // Compressed - u8* dest = xr_alloc(desc.size_real); - rtc_decompress (dest,desc.size_real,ptr+ptr_offs,desc.size_compressed); - R = xr_new(dest,desc.size_real,0); - UnmapViewOfFile (ptr); + // Compressed + u8* dest = xr_alloc(desc.size_real); + rtc_decompress(dest, desc.size_real, ptr + ptr_offs, desc.size_compressed); + R = xr_new(dest, desc.size_real, 0); + UnmapViewOfFile(ptr); #ifdef FS_DEBUG - unregister_file_mapping (ptr,sz); + unregister_file_mapping(ptr, sz); #endif // DEBUG } -void CLocatorAPI::file_from_archive (CStreamReader *&R, LPCSTR fname, const file &desc) +void CLocatorAPI::file_from_archive(CStreamReader*& R, LPCSTR fname, const file& desc) { - archive &A = m_archives[desc.vfs]; - R_ASSERT2 ( - desc.size_compressed == desc.size_real, - make_string( - "cannot use stream reading for compressed data %s, do not compress data to be streamed", - fname - ) - ); + archive& A = m_archives[desc.vfs]; + R_ASSERT2( + desc.size_compressed == desc.size_real, + make_string( + "cannot use stream reading for compressed data %s, do not compress data to be streamed", + fname + ) + ); - R = xr_new(); - R->construct ( - A.hSrcMap, - desc.ptr, - desc.size_compressed, - A.size, - BIG_FILE_READER_WINDOW_SIZE - ); + R = xr_new(); + R->construct( + A.hSrcMap, + desc.ptr, + desc.size_compressed, + A.size, + BIG_FILE_READER_WINDOW_SIZE + ); } -void CLocatorAPI::copy_file_to_build (IWriter *W, IReader *r) +void CLocatorAPI::copy_file_to_build(IWriter* W, IReader* r) { - W->w (r->pointer(),r->length()); + W->w(r->pointer(), r->length()); } -void CLocatorAPI::copy_file_to_build (IWriter *W, CStreamReader *r) +void CLocatorAPI::copy_file_to_build(IWriter* W, CStreamReader* r) { - u32 buffer_size = r->length(); - u8 *buffer = xr_alloc(buffer_size); - r->r (buffer,buffer_size); - W->w (buffer,buffer_size); - xr_free (buffer); - r->seek (0); + u32 buffer_size = r->length(); + u8* buffer = xr_alloc(buffer_size); + r->r(buffer, buffer_size); + W->w(buffer, buffer_size); + xr_free(buffer); + r->seek(0); } template -void CLocatorAPI::copy_file_to_build (T *&r, LPCSTR source_name) -{ - string_path cpy_name; - string_path e_cpy_name; - FS_Path* P; - //if (!(source_name==strstr(source_name,(P=get_path("$server_root$"))->m_Path)|| - // source_name==strstr(source_name,(P=get_path("$server_data_root$"))->m_Path))) - // return; - - string_path fs_root; - update_path (fs_root,"$fs_root$",""); - LPCSTR const position = strstr(source_name, fs_root); - if ( position == source_name ) - update_path (cpy_name,"$build_copy$",source_name + xr_strlen(fs_root)); - else - update_path (cpy_name,"$build_copy$",source_name); - - IWriter* W = w_open (cpy_name); - if (!W) { - Log ("!Can't build:",source_name); - return; - } - - copy_file_to_build (W,r); - w_close (W); - set_file_age(cpy_name,get_file_age(source_name)); +void CLocatorAPI::copy_file_to_build(T*& r, LPCSTR source_name) +{ + string_path cpy_name; + string_path e_cpy_name; + FS_Path* P; + //if (!(source_name==strstr(source_name,(P=get_path("$server_root$"))->m_Path)|| + // source_name==strstr(source_name,(P=get_path("$server_data_root$"))->m_Path))) + // return; + + string_path fs_root; + update_path(fs_root, "$fs_root$", ""); + LPCSTR const position = strstr(source_name, fs_root); + if (position == source_name) + update_path(cpy_name, "$build_copy$", source_name + xr_strlen(fs_root)); + else + update_path(cpy_name, "$build_copy$", source_name); + + IWriter* W = w_open(cpy_name); + if (!W) + { + Log("!Can't build:", source_name); + return; + } + + copy_file_to_build(W, r); + w_close(W); + set_file_age(cpy_name, get_file_age(source_name)); if (!m_Flags.is(flEBuildCopy)) - return; + return; - LPCSTR ext = strext(cpy_name); + LPCSTR ext = strext(cpy_name); if (!ext) - return; + return; - IReader* R = 0; - if (0==xr_strcmp(ext,".dds")){ - P = get_path("$game_textures$"); - update_path (e_cpy_name,"$textures$",source_name+xr_strlen(P->m_Path)); + IReader* R = 0; + if (0 == xr_strcmp(ext, ".dds")) + { + P = get_path("$game_textures$"); + update_path(e_cpy_name, "$textures$", source_name + xr_strlen(P->m_Path)); // tga - *strext (e_cpy_name) = 0; - xr_strcat (e_cpy_name,".tga"); - r_close (R=r_open(e_cpy_name)); + *strext(e_cpy_name) = 0; + xr_strcat(e_cpy_name, ".tga"); + r_close(R = r_open(e_cpy_name)); // thm - *strext (e_cpy_name) = 0; - xr_strcat (e_cpy_name,".thm"); - r_close (R=r_open(e_cpy_name)); - return; + *strext(e_cpy_name) = 0; + xr_strcat(e_cpy_name, ".thm"); + r_close(R = r_open(e_cpy_name)); + return; } - - if (0==xr_strcmp(ext,".ogg")){ - P = get_path("$game_sounds$"); - update_path (e_cpy_name,"$sounds$",source_name+xr_strlen(P->m_Path)); + + if (0 == xr_strcmp(ext, ".ogg")) + { + P = get_path("$game_sounds$"); + update_path(e_cpy_name, "$sounds$", source_name + xr_strlen(P->m_Path)); // wav - *strext (e_cpy_name) = 0; - xr_strcat (e_cpy_name,".wav"); - r_close (R=r_open(e_cpy_name)); + *strext(e_cpy_name) = 0; + xr_strcat(e_cpy_name, ".wav"); + r_close(R = r_open(e_cpy_name)); // thm - *strext (e_cpy_name) = 0; - xr_strcat (e_cpy_name,".thm"); - r_close (R=r_open(e_cpy_name)); - return; + *strext(e_cpy_name) = 0; + xr_strcat(e_cpy_name, ".thm"); + r_close(R = r_open(e_cpy_name)); + return; } - - if (0==xr_strcmp(ext,".object")){ - xr_strcpy (e_cpy_name,sizeof(e_cpy_name),source_name); + + if (0 == xr_strcmp(ext, ".object")) + { + xr_strcpy(e_cpy_name, sizeof(e_cpy_name), source_name); // object thm - *strext (e_cpy_name) = 0; - xr_strcat (e_cpy_name,".thm"); - R = r_open(e_cpy_name); - if (R) r_close (R); + *strext(e_cpy_name) = 0; + xr_strcat(e_cpy_name, ".thm"); + R = r_open(e_cpy_name); + if (R) r_close(R); } } -bool CLocatorAPI::check_for_file (LPCSTR path, LPCSTR _fname, string_path& fname, const file *&desc) +bool CLocatorAPI::check_for_file(LPCSTR path, LPCSTR _fname, string_path& fname, const file*& desc) { - // ïðîâåðèòü íóæíî ëè ïåðåñêàíèðîâàòü ïóòè - check_pathes (); + // ïðîâåðèòü íóæíî ëè ïåðåñêàíèðîâàòü ïóòè + check_pathes(); - // correct path - xr_strcpy (fname,_fname); - xr_strlwr (fname); - if (path&&path[0]) - update_path (fname,path,fname); + // correct path + xr_strcpy(fname, _fname); + xr_strlwr(fname); + if (path&&path[0]) + update_path(fname, path, fname); - // Search entry - file desc_f; - desc_f.name = fname; + // Search entry + file desc_f; + desc_f.name = fname; - files_it I = m_files.find(desc_f); - if (I == m_files.end()) - return (false); + files_it I = m_files.find(desc_f); + if (I == m_files.end()) + return (false); - ++dwOpenCounter; - desc = &*I; - return (true); + ++dwOpenCounter; + desc = &*I; + return (true); } template -T *CLocatorAPI::r_open_impl (LPCSTR path, LPCSTR _fname) +T* CLocatorAPI::r_open_impl(LPCSTR path, LPCSTR _fname) { - T *R = 0; - string_path fname; - const file *desc = 0; - LPCSTR source_name = &fname[0]; + T* R = 0; + string_path fname; + const file* desc = 0; + LPCSTR source_name = &fname[0]; - if (!check_for_file(path,_fname,fname,desc)) - return (0); + if (!check_for_file(path, _fname, fname, desc)) + return (0); - // OK, analyse - if (0xffffffff == desc->vfs) - file_from_cache (R,fname,sizeof(fname),*desc,source_name); - else - file_from_archive (R,fname,*desc); + // OK, analyse + if (0xffffffff == desc->vfs) + file_from_cache(R, fname, sizeof(fname), *desc, source_name); + else + file_from_archive(R, fname, *desc); #ifdef DEBUG - if (R && m_Flags.is(flBuildCopy|flReady)) - copy_file_to_build (R,source_name); + if (R && m_Flags.is(flBuildCopy | flReady)) + copy_file_to_build(R, source_name); #endif // DEBUG - if (m_Flags.test(flDumpFileActivity)) - _register_open_file (R,fname); + if (m_Flags.test(flDumpFileActivity)) + _register_open_file(R, fname); - return (R); + return (R); } -CStreamReader* CLocatorAPI::rs_open (LPCSTR path, LPCSTR _fname) +CStreamReader* CLocatorAPI::rs_open(LPCSTR path, LPCSTR _fname) { - return (r_open_impl(path,_fname)); + return (r_open_impl(path, _fname)); } -IReader *CLocatorAPI::r_open (LPCSTR path, LPCSTR _fname) +IReader* CLocatorAPI::r_open(LPCSTR path, LPCSTR _fname) { - return (r_open_impl(path,_fname)); + return (r_open_impl(path, _fname)); } -void CLocatorAPI::r_close (IReader* &fs) +void CLocatorAPI::r_close(IReader*& fs) { - if( m_Flags.test(flDumpFileActivity) ) - _unregister_open_file (fs); + if (m_Flags.test(flDumpFileActivity)) + _unregister_open_file(fs); - xr_delete (fs); + xr_delete(fs); } -void CLocatorAPI::r_close (CStreamReader* &fs) +void CLocatorAPI::r_close(CStreamReader*& fs) { - if( m_Flags.test(flDumpFileActivity) ) - _unregister_open_file (fs); + if (m_Flags.test(flDumpFileActivity)) + _unregister_open_file(fs); - fs->close (); + fs->close(); } -IWriter* CLocatorAPI::w_open (LPCSTR path, LPCSTR _fname) +IWriter* CLocatorAPI::w_open(LPCSTR path, LPCSTR _fname) { - string_path fname; - xr_strcpy(fname,_fname); - xr_strlwr(fname);//,".$"); - if (path&&path[0]) update_path(fname,path,fname); - CFileWriter* W = xr_new(fname,false); + string_path fname; + xr_strcpy(fname, _fname); + xr_strlwr(fname);//,".$"); + if (path&&path[0]) update_path(fname, path, fname); + CFileWriter* W = xr_new(fname, false); #ifdef _EDITOR - if (!W->valid()) xr_delete(W); -#endif - return W; + if (!W->valid()) xr_delete(W); +#endif + return W; } -IWriter* CLocatorAPI::w_open_ex (LPCSTR path, LPCSTR _fname) +IWriter* CLocatorAPI::w_open_ex(LPCSTR path, LPCSTR _fname) { - string_path fname; - xr_strcpy(fname,_fname); - xr_strlwr(fname);//,".$"); - if (path&&path[0]) update_path(fname,path,fname); - CFileWriter* W = xr_new(fname,true); + string_path fname; + xr_strcpy(fname, _fname); + xr_strlwr(fname);//,".$"); + if (path&&path[0]) update_path(fname, path, fname); + CFileWriter* W = xr_new(fname, true); #ifdef _EDITOR - if (!W->valid()) xr_delete(W); -#endif - return W; -} - -void CLocatorAPI::w_close(IWriter* &S) -{ - if (S){ - R_ASSERT (S->fName.size()); - string_path fname; - xr_strcpy (fname,sizeof(fname),*S->fName); - bool bReg = S->valid(); - xr_delete (S); - - if(bReg) - { - struct _stat st; - _stat (fname,&st); - Register (fname,0xffffffff,0,0,st.st_size,st.st_size,(u32)st.st_mtime); - } + if (!W->valid()) xr_delete(W); +#endif + return W; +} + +void CLocatorAPI::w_close(IWriter*& S) +{ + if (S) + { + R_ASSERT(S->fName.size()); + string_path fname; + xr_strcpy(fname, sizeof(fname), *S->fName); + bool bReg = S->valid(); + xr_delete(S); + + if (bReg) + { + struct _stat st; + _stat(fname, &st); + Register(fname, 0xffffffff, 0, 0, st.st_size, st.st_size, (u32)st.st_mtime); + } } } CLocatorAPI::files_it CLocatorAPI::file_find_it(LPCSTR fname) { - // ïðîâåðèòü íóæíî ëè ïåðåñêàíèðîâàòü ïóòè - check_pathes (); - - file desc_f; - string_path file_name; - VERIFY (xr_strlen(fname)*sizeof(char) < sizeof(file_name)); - xr_strcpy (file_name,sizeof(file_name),fname); - desc_f.name = file_name; -// desc_f.name = xr_strlwr(xr_strdup(fname)); - files_it I = m_files.find(desc_f); -// xr_free (desc_f.name); - return (I); -} - -BOOL CLocatorAPI::dir_delete(LPCSTR path,LPCSTR nm,BOOL remove_files) -{ - string_path fpath; - if (path&&path[0]) update_path(fpath,path,nm); - else xr_strcpy(fpath,sizeof(fpath),nm); - - files_set folders; - files_it I; - // remove files - I = file_find_it(fpath); - if (I!=m_files.end()){ - size_t base_len = xr_strlen(fpath); - for (; I!=m_files.end(); ){ - files_it cur_item = I; - const file& entry = *cur_item; - I = cur_item; I++; - if (0!=strncmp(entry.name,fpath,base_len)) break; // end of list - const char* end_symbol = entry.name+xr_strlen(entry.name)-1; - if ((*end_symbol) !='\\'){ -// const char* entry_begin = entry.name+base_len; - if (!remove_files) return FALSE; - unlink (entry.name); - m_files.erase (cur_item); - }else{ - folders.insert(entry); + // ïðîâåðèòü íóæíî ëè ïåðåñêàíèðîâàòü ïóòè + check_pathes(); + + file desc_f; + string_path file_name; + VERIFY(xr_strlen(fname)*sizeof(char) < sizeof(file_name)); + xr_strcpy(file_name, sizeof(file_name), fname); + desc_f.name = file_name; + // desc_f.name = xr_strlwr(xr_strdup(fname)); + files_it I = m_files.find(desc_f); + // xr_free (desc_f.name); + return (I); +} + +BOOL CLocatorAPI::dir_delete(LPCSTR path, LPCSTR nm, BOOL remove_files) +{ + string_path fpath; + if (path&&path[0]) update_path(fpath, path, nm); + else xr_strcpy(fpath, sizeof(fpath), nm); + + files_set folders; + files_it I; + // remove files + I = file_find_it(fpath); + if (I != m_files.end()) + { + size_t base_len = xr_strlen(fpath); + for (; I != m_files.end();) + { + files_it cur_item = I; + const file& entry = *cur_item; + I = cur_item; + I++; + if (0 != strncmp(entry.name, fpath, base_len)) break; // end of list + const char* end_symbol = entry.name + xr_strlen(entry.name) - 1; + if ((*end_symbol) != '\\') + { + // const char* entry_begin = entry.name+base_len; + if (!remove_files) return FALSE; + unlink(entry.name); + m_files.erase(cur_item); + } + else + { + folders.insert(entry); } } } // remove folders files_set::reverse_iterator r_it = folders.rbegin(); - for (;r_it!=folders.rend();r_it++){ - const char* end_symbol = r_it->name+xr_strlen(r_it->name)-1; - if ((*end_symbol) =='\\'){ - _rmdir (r_it->name); - m_files.erase (*r_it); + for (; r_it != folders.rend(); r_it++) + { + const char* end_symbol = r_it->name + xr_strlen(r_it->name) - 1; + if ((*end_symbol) == '\\') + { + _rmdir(r_it->name); + m_files.erase(*r_it); } } return TRUE; @@ -1424,232 +1481,254 @@ BOOL CLocatorAPI::dir_delete(LPCSTR path,LPCSTR nm,BOOL remove_files) void CLocatorAPI::file_delete(LPCSTR path, LPCSTR nm) { - string_path fname; - if (path&&path[0]) update_path(fname,path,nm); - else xr_strcpy(fname,sizeof(fname),nm); - - const files_it I = file_find_it(fname); - if (I!=m_files.end()){ - // remove file - unlink (I->name); - char* str = LPSTR(I->name); - xr_free (str); - m_files.erase (I); + string_path fname; + if (path&&path[0]) update_path(fname, path, nm); + else xr_strcpy(fname, sizeof(fname), nm); + + const files_it I = file_find_it(fname); + if (I != m_files.end()) + { + // remove file + unlink(I->name); + char* str = LPSTR(I->name); + xr_free(str); + m_files.erase(I); } } void CLocatorAPI::file_copy(LPCSTR src, LPCSTR dest) { - if (exist(src)){ - IReader* S = r_open(src); - if (S){ - IWriter* D = w_open(dest); - if (D){ - D->w (S->pointer(),S->length()); - w_close (D); + if (exist(src)) + { + IReader* S = r_open(src); + if (S) + { + IWriter* D = w_open(dest); + if (D) + { + D->w(S->pointer(), S->length()); + w_close(D); } - r_close (S); + r_close(S); } - } + } } void CLocatorAPI::file_rename(LPCSTR src, LPCSTR dest, bool bOwerwrite) { - files_it S = file_find_it(src); - if (S!=m_files.end()){ - files_it D = file_find_it(dest); - if (D!=m_files.end()){ - if (!bOwerwrite) return; - unlink (D->name); - char* str = LPSTR(D->name); - xr_free (str); - m_files.erase (D); + files_it S = file_find_it(src); + if (S != m_files.end()) + { + files_it D = file_find_it(dest); + if (D != m_files.end()) + { + if (!bOwerwrite) return; + unlink(D->name); + char* str = LPSTR(D->name); + xr_free(str); + m_files.erase(D); } - file new_desc = *S; - // remove existing item - char* str = LPSTR(S->name); - xr_free (str); - m_files.erase (S); - // insert updated item - new_desc.name = xr_strlwr(xr_strdup(dest)); - m_files.insert (new_desc); - + file new_desc = *S; + // remove existing item + char* str = LPSTR(S->name); + xr_free(str); + m_files.erase(S); + // insert updated item + new_desc.name = xr_strlwr(xr_strdup(dest)); + m_files.insert(new_desc); + // physically rename file - VerifyPath (dest); - rename (src,dest); - } + VerifyPath(dest); + rename(src, dest); + } } -int CLocatorAPI::file_length(LPCSTR src) +int CLocatorAPI::file_length(LPCSTR src) { - files_it I = file_find_it(src); - return (I!=m_files.end())?I->size_real:-1; + files_it I = file_find_it(src); + return (I != m_files.end()) ? I->size_real : -1; } bool CLocatorAPI::path_exist(LPCSTR path) { - PathPairIt P = pathes.find(path); - return (P!=pathes.end()); + PathPairIt P = pathes.find(path); + return (P != pathes.end()); } FS_Path* CLocatorAPI::append_path(LPCSTR path_alias, LPCSTR root, LPCSTR add, BOOL recursive) { - VERIFY (root/**&&root[0]/**/); - VERIFY (false==path_exist(path_alias)); - FS_Path* P = xr_new(root,add,LPCSTR(0),LPCSTR(0),0); - bNoRecurse = !recursive; - Recurse (P->m_Path); - pathes.insert (mk_pair(xr_strdup(path_alias),P)); - return P; + VERIFY(root/**&&root[0]/**/); + VERIFY(false == path_exist(path_alias)); + FS_Path* P = xr_new(root, add, LPCSTR(0), LPCSTR(0), 0); + bNoRecurse = !recursive; + Recurse(P->m_Path); + pathes.insert(mk_pair(xr_strdup(path_alias), P)); + return P; } FS_Path* CLocatorAPI::get_path(LPCSTR path) { - PathPairIt P = pathes.find(path); - R_ASSERT2(P!=pathes.end(),path); + PathPairIt P = pathes.find(path); + R_ASSERT2(P != pathes.end(), path); return P->second; } LPCSTR CLocatorAPI::update_path(string_path& dest, LPCSTR initial, LPCSTR src) { - return get_path(initial)->_update(dest,src); + return get_path(initial)->_update(dest, src); } /* void CLocatorAPI::update_path(xr_string& dest, LPCSTR initial, LPCSTR src) { - return get_path(initial)->_update(dest,src); +return get_path(initial)->_update(dest,src); }*/ u32 CLocatorAPI::get_file_age(LPCSTR nm) { - // ïðîâåðèòü íóæíî ëè ïåðåñêàíèðîâàòü ïóòè - check_pathes (); + // ïðîâåðèòü íóæíî ëè ïåðåñêàíèðîâàòü ïóòè + check_pathes(); - files_it I = file_find_it(nm); - return (I!=m_files.end())?I->modif:u32(-1); + files_it I = file_find_it(nm); + return (I != m_files.end()) ? I->modif : u32(-1); } void CLocatorAPI::set_file_age(LPCSTR nm, u32 age) { - // ïðîâåðèòü íóæíî ëè ïåðåñêàíèðîâàòü ïóòè - check_pathes (); + // ïðîâåðèòü íóæíî ëè ïåðåñêàíèðîâàòü ïóòè + check_pathes(); // set file - _utimbuf tm; - tm.actime = age; - tm.modtime = age; - int res = _utime(nm,&tm); - if (0!=res){ - Msg ("!Can't set file age: '%s'. Error: '%s'",nm,_sys_errlist[errno]); - }else{ + _utimbuf tm; + tm.actime = age; + tm.modtime = age; + int res = _utime(nm, &tm); + if (0 != res) + { + Msg("!Can't set file age: '%s'. Error: '%s'", nm, _sys_errlist[errno]); + } + else + { // update record - files_it I = file_find_it(nm); - if (I!=m_files.end()){ - file& F = (file&)*I; - F.modif = age; + files_it I = file_find_it(nm); + if (I != m_files.end()) + { + file& F = (file&)*I; + F.modif = age; } } } void CLocatorAPI::rescan_path(LPCSTR full_path, BOOL bRecurse) { - file desc; - desc.name = full_path; - files_it I = m_files.lower_bound(desc); - if (I==m_files.end()) return; - - size_t base_len = xr_strlen(full_path); - for (; I!=m_files.end(); ){ - files_it cur_item = I; - const file& entry = *cur_item; - I = cur_item; I++; - if (0!=strncmp(entry.name,full_path,base_len)) break; // end of list - if (entry.vfs!=0xFFFFFFFF) continue; - const char* entry_begin = entry.name+base_len; - if (!bRecurse&&strstr(entry_begin,"\\")) continue; + file desc; + desc.name = full_path; + files_it I = m_files.lower_bound(desc); + if (I == m_files.end()) return; + + size_t base_len = xr_strlen(full_path); + for (; I != m_files.end();) + { + files_it cur_item = I; + const file& entry = *cur_item; + I = cur_item; + I++; + if (0 != strncmp(entry.name, full_path, base_len)) break; // end of list + if (entry.vfs != 0xFFFFFFFF) continue; + const char* entry_begin = entry.name + base_len; + if (!bRecurse&&strstr(entry_begin, "\\")) continue; // erase item - char* str = LPSTR(cur_item->name); - xr_free (str); - m_files.erase (cur_item); - } - bNoRecurse = !bRecurse; - Recurse (full_path); + char* str = LPSTR(cur_item->name); + xr_free(str); + m_files.erase(cur_item); + } + bNoRecurse = !bRecurse; + Recurse(full_path); } -void CLocatorAPI::rescan_pathes() +void CLocatorAPI::rescan_pathes() { - m_Flags.set(flNeedRescan,FALSE); - for (PathPairIt p_it=pathes.begin(); p_it!=pathes.end(); p_it++) + m_Flags.set(flNeedRescan, FALSE); + for (PathPairIt p_it = pathes.begin(); p_it != pathes.end(); p_it++) { - FS_Path* P = p_it->second; - if (P->m_Flags.is(FS_Path::flNeedRescan)){ - rescan_path(P->m_Path,P->m_Flags.is(FS_Path::flRecurse)); - P->m_Flags.set(FS_Path::flNeedRescan,FALSE); + FS_Path* P = p_it->second; + if (P->m_Flags.is(FS_Path::flNeedRescan)) + { + rescan_path(P->m_Path, P->m_Flags.is(FS_Path::flRecurse)); + P->m_Flags.set(FS_Path::flNeedRescan, FALSE); } } } void CLocatorAPI::lock_rescan() { - m_iLockRescan++; + m_iLockRescan++; } void CLocatorAPI::unlock_rescan() { - m_iLockRescan--; VERIFY(m_iLockRescan>=0); - if ((0==m_iLockRescan)&&m_Flags.is(flNeedRescan)) - rescan_pathes(); + m_iLockRescan--; + VERIFY(m_iLockRescan >= 0); + if ((0 == m_iLockRescan) && m_Flags.is(flNeedRescan)) + rescan_pathes(); } void CLocatorAPI::check_pathes() { - if (m_Flags.is(flNeedRescan)&&(0==m_iLockRescan)){ - lock_rescan (); - rescan_pathes (); - unlock_rescan (); + if (m_Flags.is(flNeedRescan) && (0 == m_iLockRescan)) + { + lock_rescan(); + rescan_pathes(); + unlock_rescan(); } } BOOL CLocatorAPI::can_write_to_folder(LPCSTR path) { - if (path&&path[0]){ - string_path temp; - LPCSTR fn = "$!#%TEMP%#!$.$$$"; - strconcat (sizeof(temp),temp,path,path[xr_strlen(path)-1]!='\\'?"\\":"",fn); - FILE* hf = fopen (temp, "wb"); - if (hf==0) return FALSE; - else{ - fclose (hf); - unlink (temp); - return TRUE; + if (path&&path[0]) + { + string_path temp; + LPCSTR fn = "$!#%TEMP%#!$.$$$"; + strconcat(sizeof(temp), temp, path, path[xr_strlen(path) - 1] != '\\' ? "\\" : "", fn); + FILE* hf = fopen(temp, "wb"); + if (hf == 0) return FALSE; + else + { + fclose(hf); + unlink(temp); + return TRUE; } - }else{ - return FALSE; + } + else + { + return FALSE; } } BOOL CLocatorAPI::can_write_to_alias(LPCSTR path) { - string_path temp; - update_path (temp,path,""); - return can_write_to_folder(temp); + string_path temp; + update_path(temp, path, ""); + return can_write_to_folder(temp); } BOOL CLocatorAPI::can_modify_file(LPCSTR fname) { - FILE* hf = fopen (fname, "r+b"); - if (hf){ - fclose (hf); - return TRUE; - }else{ - return FALSE; + FILE* hf = fopen(fname, "r+b"); + if (hf) + { + fclose(hf); + return TRUE; + } + else + { + return FALSE; } } BOOL CLocatorAPI::can_modify_file(LPCSTR path, LPCSTR name) { - string_path temp; - update_path (temp,path,name); - return can_modify_file(temp); + string_path temp; + update_path(temp, path, name); + return can_modify_file(temp); } diff --git a/src/xrCore/LocatorAPI.h b/src/xrCore/LocatorAPI.h index bb0307fee6c..54c0f0d1816 100644 --- a/src/xrCore/LocatorAPI.h +++ b/src/xrCore/LocatorAPI.h @@ -15,172 +15,175 @@ class XRCORE_API CStreamReader; -class XRCORE_API CLocatorAPI +class XRCORE_API CLocatorAPI { - friend class FS_Path; + friend class FS_Path; public: - struct file - { - LPCSTR name; // low-case name - u32 vfs; // 0xffffffff - standart file - u32 crc; // contents CRC - u32 ptr; // pointer inside vfs - u32 size_real; // - u32 size_compressed;// if (size_real==size_compressed) - uncompressed - u32 modif; // for editor - }; - struct archive - { - shared_str path; - void *hSrcFile, *hSrcMap; - u32 size; - CInifile* header; - u32 vfs_idx; - archive():hSrcFile(NULL),hSrcMap(NULL),header(NULL),size(0),vfs_idx(u32(-1)){} - void open(); - void close(); - }; - DEFINE_VECTOR (archive,archives_vec,archives_it); - archives_vec m_archives; - void LoadArchive (archive& A, LPCSTR entrypoint=NULL); + struct file + { + LPCSTR name; // low-case name + u32 vfs; // 0xffffffff - standart file + u32 crc; // contents CRC + u32 ptr; // pointer inside vfs + u32 size_real; // + u32 size_compressed;// if (size_real==size_compressed) - uncompressed + u32 modif; // for editor + }; + struct archive + { + shared_str path; + void* hSrcFile, *hSrcMap; + u32 size; + CInifile* header; + u32 vfs_idx; + archive() :hSrcFile(NULL), hSrcMap(NULL), header(NULL), size(0), vfs_idx(u32(-1)) {} + void open(); + void close(); + }; + DEFINE_VECTOR(archive, archives_vec, archives_it); + archives_vec m_archives; + void LoadArchive(archive& A, LPCSTR entrypoint = NULL); private: - struct file_pred: public std::binary_function - { - IC bool operator() (const file& x, const file& y) const - { return xr_strcmp(x.name,y.name)<0; } - }; - DEFINE_MAP_PRED (LPCSTR,FS_Path*,PathMap,PathPairIt,pred_str); - PathMap pathes; + struct file_pred : public std::binary_function < file&, file&, bool > + { + IC bool operator() (const file& x, const file& y) const + { + return xr_strcmp(x.name, y.name) < 0; + } + }; + DEFINE_MAP_PRED(LPCSTR, FS_Path*, PathMap, PathPairIt, pred_str); + PathMap pathes; - DEFINE_SET_PRED (file,files_set,files_it,file_pred); + DEFINE_SET_PRED(file, files_set, files_it, file_pred); - DEFINE_VECTOR (_finddata_t,FFVec,FFIt); - FFVec rec_files; + DEFINE_VECTOR(_finddata_t, FFVec, FFIt); + FFVec rec_files; - int m_iLockRescan ; - void check_pathes (); + int m_iLockRescan; + void check_pathes(); - files_set m_files ; - BOOL bNoRecurse ; + files_set m_files; + BOOL bNoRecurse; - xrCriticalSection m_auth_lock ; - u64 m_auth_code ; + xrCriticalSection m_auth_lock; + u64 m_auth_code; - void Register (LPCSTR name, u32 vfs, u32 crc, u32 ptr, u32 size_real, u32 size_compressed, u32 modif); - void ProcessArchive (LPCSTR path); - void ProcessOne (LPCSTR path, const _finddata_t& entry); - bool Recurse (LPCSTR path); + void Register(LPCSTR name, u32 vfs, u32 crc, u32 ptr, u32 size_real, u32 size_compressed, u32 modif); + void ProcessArchive(LPCSTR path); + void ProcessOne(LPCSTR path, const _finddata_t& entry); + bool Recurse(LPCSTR path); - files_it file_find_it (LPCSTR n); + files_it file_find_it(LPCSTR n); public: - enum{ - flNeedRescan = (1<<0), - flBuildCopy = (1<<1), - flReady = (1<<2), - flEBuildCopy = (1<<3), - flEventNotificator = (1<<4), - flTargetFolderOnly = (1<<5), - flCacheFiles = (1<<6), - flScanAppRoot = (1<<7), - flNeedCheck = (1<<8), - flDumpFileActivity = (1<<9), - }; - Flags32 m_Flags ; - u32 dwAllocGranularity; - u32 dwOpenCounter; + enum + { + flNeedRescan = (1 << 0), + flBuildCopy = (1 << 1), + flReady = (1 << 2), + flEBuildCopy = (1 << 3), + flEventNotificator = (1 << 4), + flTargetFolderOnly = (1 << 5), + flCacheFiles = (1 << 6), + flScanAppRoot = (1 << 7), + flNeedCheck = (1 << 8), + flDumpFileActivity = (1 << 9), + }; + Flags32 m_Flags; + u32 dwAllocGranularity; + u32 dwOpenCounter; private: - void check_cached_files (LPSTR fname, const u32 &fname_size, const file &desc, LPCSTR &source_name); - - void file_from_cache_impl(IReader *&R, LPSTR fname, const file &desc); - void file_from_cache_impl(CStreamReader *&R, LPSTR fname, const file &desc); - template - void file_from_cache (T *&R, LPSTR fname, const u32 &fname_size, const file &desc, LPCSTR &source_name); - - void file_from_archive (IReader *&R, LPCSTR fname, const file &desc); - void file_from_archive (CStreamReader *&R, LPCSTR fname, const file &desc); - - void copy_file_to_build (IWriter *W, IReader *r); - void copy_file_to_build (IWriter *W, CStreamReader *r); - template - void copy_file_to_build (T *&R, LPCSTR source_name); - - bool check_for_file (LPCSTR path, LPCSTR _fname, string_path& fname, const file *&desc); - - template - IC T *r_open_impl (LPCSTR path, LPCSTR _fname); + void check_cached_files(LPSTR fname, const u32& fname_size, const file& desc, LPCSTR& source_name); + + void file_from_cache_impl(IReader*& R, LPSTR fname, const file& desc); + void file_from_cache_impl(CStreamReader*& R, LPSTR fname, const file& desc); + template + void file_from_cache(T*& R, LPSTR fname, const u32& fname_size, const file& desc, LPCSTR& source_name); + + void file_from_archive(IReader*& R, LPCSTR fname, const file& desc); + void file_from_archive(CStreamReader*& R, LPCSTR fname, const file& desc); + + void copy_file_to_build(IWriter* W, IReader* r); + void copy_file_to_build(IWriter* W, CStreamReader* r); + template + void copy_file_to_build(T*& R, LPCSTR source_name); + + bool check_for_file(LPCSTR path, LPCSTR _fname, string_path& fname, const file*& desc); + + template + IC T* r_open_impl(LPCSTR path, LPCSTR _fname); private: - void setup_fs_path (LPCSTR fs_name, string_path &fs_path); - void setup_fs_path (LPCSTR fs_name); - IReader *setup_fs_ltx (LPCSTR fs_name); + void setup_fs_path(LPCSTR fs_name, string_path& fs_path); + void setup_fs_path(LPCSTR fs_name); + IReader* setup_fs_ltx(LPCSTR fs_name); public: - CLocatorAPI (); - ~CLocatorAPI (); - void _initialize (u32 flags, LPCSTR target_folder=0, LPCSTR fs_name=0); - void _destroy (); - - CStreamReader* rs_open (LPCSTR initial, LPCSTR N); - IReader* r_open (LPCSTR initial, LPCSTR N); - IC IReader* r_open (LPCSTR N){return r_open(0,N);} - void r_close (IReader* &S); - void r_close (CStreamReader* &fs); - - IWriter* w_open (LPCSTR initial, LPCSTR N); - IC IWriter* w_open (LPCSTR N){return w_open(0,N);} - IWriter* w_open_ex (LPCSTR initial, LPCSTR N); - IC IWriter* w_open_ex (LPCSTR N){return w_open_ex(0,N);} - void w_close (IWriter* &S); - - const file* exist (LPCSTR N); - const file* exist (LPCSTR path, LPCSTR name); - const file* exist (string_path& fn, LPCSTR path, LPCSTR name); - const file* exist (string_path& fn, LPCSTR path, LPCSTR name, LPCSTR ext); - - BOOL can_write_to_folder (LPCSTR path); - BOOL can_write_to_alias (LPCSTR path); - BOOL can_modify_file (LPCSTR fname); - BOOL can_modify_file (LPCSTR path, LPCSTR name); - - BOOL dir_delete (LPCSTR path,LPCSTR nm,BOOL remove_files); - BOOL dir_delete (LPCSTR full_path,BOOL remove_files){return dir_delete(0,full_path,remove_files);} - void file_delete (LPCSTR path,LPCSTR nm); - void file_delete (LPCSTR full_path){file_delete(0,full_path);} - void file_copy (LPCSTR src, LPCSTR dest); - void file_rename (LPCSTR src, LPCSTR dest,bool bOwerwrite=true); - int file_length (LPCSTR src); - - u32 get_file_age (LPCSTR nm); - void set_file_age (LPCSTR nm, u32 age); - - xr_vector* file_list_open (LPCSTR initial, LPCSTR folder, u32 flags=FS_ListFiles); - xr_vector* file_list_open (LPCSTR path, u32 flags=FS_ListFiles); - void file_list_close (xr_vector* &lst); - - bool path_exist (LPCSTR path); - FS_Path* get_path (LPCSTR path); - FS_Path* append_path (LPCSTR path_alias, LPCSTR root, LPCSTR add, BOOL recursive); - LPCSTR update_path (string_path& dest, LPCSTR initial, LPCSTR src); - - int file_list (FS_FileSet& dest, LPCSTR path, u32 flags=FS_ListFiles, LPCSTR mask=0); - - bool load_all_unloaded_archives(); - void unload_archive (archive& A); - - void auth_generate (xr_vector& ignore, xr_vector& important); - u64 auth_get (); - void auth_runtime (void*); - - void rescan_path (LPCSTR full_path, BOOL bRecurse); - // editor functions - void rescan_pathes (); - void lock_rescan (); - void unlock_rescan (); + CLocatorAPI(); + ~CLocatorAPI(); + void _initialize(u32 flags, LPCSTR target_folder = 0, LPCSTR fs_name = 0); + void _destroy(); + + CStreamReader* rs_open(LPCSTR initial, LPCSTR N); + IReader* r_open(LPCSTR initial, LPCSTR N); + IC IReader* r_open(LPCSTR N) { return r_open(0, N); } + void r_close(IReader*& S); + void r_close(CStreamReader*& fs); + + IWriter* w_open(LPCSTR initial, LPCSTR N); + IC IWriter* w_open(LPCSTR N) { return w_open(0, N); } + IWriter* w_open_ex(LPCSTR initial, LPCSTR N); + IC IWriter* w_open_ex(LPCSTR N) { return w_open_ex(0, N); } + void w_close(IWriter*& S); + + const file* exist(LPCSTR N); + const file* exist(LPCSTR path, LPCSTR name); + const file* exist(string_path& fn, LPCSTR path, LPCSTR name); + const file* exist(string_path& fn, LPCSTR path, LPCSTR name, LPCSTR ext); + + BOOL can_write_to_folder(LPCSTR path); + BOOL can_write_to_alias(LPCSTR path); + BOOL can_modify_file(LPCSTR fname); + BOOL can_modify_file(LPCSTR path, LPCSTR name); + + BOOL dir_delete(LPCSTR path, LPCSTR nm, BOOL remove_files); + BOOL dir_delete(LPCSTR full_path, BOOL remove_files) { return dir_delete(0, full_path, remove_files); } + void file_delete(LPCSTR path, LPCSTR nm); + void file_delete(LPCSTR full_path) { file_delete(0, full_path); } + void file_copy(LPCSTR src, LPCSTR dest); + void file_rename(LPCSTR src, LPCSTR dest, bool bOwerwrite = true); + int file_length(LPCSTR src); + + u32 get_file_age(LPCSTR nm); + void set_file_age(LPCSTR nm, u32 age); + + xr_vector* file_list_open(LPCSTR initial, LPCSTR folder, u32 flags = FS_ListFiles); + xr_vector* file_list_open(LPCSTR path, u32 flags = FS_ListFiles); + void file_list_close(xr_vector*& lst); + + bool path_exist(LPCSTR path); + FS_Path* get_path(LPCSTR path); + FS_Path* append_path(LPCSTR path_alias, LPCSTR root, LPCSTR add, BOOL recursive); + LPCSTR update_path(string_path& dest, LPCSTR initial, LPCSTR src); + + int file_list(FS_FileSet& dest, LPCSTR path, u32 flags = FS_ListFiles, LPCSTR mask = 0); + + bool load_all_unloaded_archives(); + void unload_archive(archive& A); + + void auth_generate(xr_vector& ignore, xr_vector& important); + u64 auth_get(); + void auth_runtime(void*); + + void rescan_path(LPCSTR full_path, BOOL bRecurse); + // editor functions + void rescan_pathes(); + void lock_rescan(); + void unlock_rescan(); }; -extern XRCORE_API CLocatorAPI* xr_FS; +extern XRCORE_API CLocatorAPI* xr_FS; #define FS (*xr_FS) #endif // LocatorAPIH diff --git a/src/xrCore/LocatorAPI_Notifications.cpp b/src/xrCore/LocatorAPI_Notifications.cpp index 8517d36bfc2..e8d481d19d5 100644 --- a/src/xrCore/LocatorAPI_Notifications.cpp +++ b/src/xrCore/LocatorAPI_Notifications.cpp @@ -9,16 +9,16 @@ void CThread::startup(void* P) { - CThread* T = (CThread*)P; - T->Execute (); + CThread* T = (CThread*)P; + T->Execute(); } static CRITICAL_SECTION CS; //--------------------------------------------------------------------------- // TShellChangeThread ------------------------------------------------------- -CFS_PathNotificator::CFS_PathNotificator():CThread(0) +CFS_PathNotificator::CFS_PathNotificator() :CThread(0) { - FMutex = CreateMutex(NULL, true /* initial owner - must be Release'd by this thread*/, NULL); + FMutex = CreateMutex(NULL, true /* initial owner - must be Release'd by this thread*/, NULL); if (FMutex) WaitForSingleObject(FMutex, INFINITE); } @@ -26,92 +26,101 @@ CFS_PathNotificator::CFS_PathNotificator():CThread(0) CFS_PathNotificator::~CFS_PathNotificator(void) { - for (PathIt it=events.begin(); it!=events.end(); it++){ - Path& P = *it; - P.FChangeEvent = 0; - if (P.FWaitHandle != INVALID_HANDLE_VALUE){ - HANDLE hOld = P.FWaitHandle; - P.FWaitHandle= 0; + for (PathIt it = events.begin(); it != events.end(); it++) + { + Path& P = *it; + P.FChangeEvent = 0; + if (P.FWaitHandle != INVALID_HANDLE_VALUE) + { + HANDLE hOld = P.FWaitHandle; + P.FWaitHandle = 0; FindCloseChangeNotification(hOld); } } - events.clear (); + events.clear(); } //--------------------------------------------------------------------------- void CFS_PathNotificator::RegisterPath(FS_Path& path) -{ -// R_ASSERT2(Suspended,"Can't register path. Thread already started."); - shared_str dir = path.m_Path; - for (PathIt it=events.begin(); it!=events.end(); it++) - if ((it->FDirectory==dir)&&(it->bRecurse==path.m_Flags.is(FS_Path::flRecurse))) return; +{ + // R_ASSERT2(Suspended,"Can't register path. Thread already started."); + shared_str dir = path.m_Path; + for (PathIt it = events.begin(); it != events.end(); it++) + if ((it->FDirectory == dir) && (it->bRecurse == path.m_Flags.is(FS_Path::flRecurse))) return; - events.push_back (Path()); - Path& P = events.back(); - P.FDirectory = path.m_Path; - P.bRecurse = path.m_Flags.is(FS_Path::flRecurse); - P.FChangeEvent.bind (&path,&FS_Path::rescan_path_cb); - P.FWaitHandle = INVALID_HANDLE_VALUE; + events.push_back(Path()); + Path& P = events.back(); + P.FDirectory = path.m_Path; + P.bRecurse = path.m_Flags.is(FS_Path::flRecurse); + P.FChangeEvent.bind(&path, &FS_Path::rescan_path_cb); + P.FWaitHandle = INVALID_HANDLE_VALUE; } //--------------------------------------------------------------------------- void CFS_PathNotificator::Execute(void) { EnterCriticalSection(&CS); - for (PathIt it=events.begin(); it!=events.end(); it++){ - Path& P = *it; - P.FWaitHandle = FindFirstChangeNotification(P.FDirectory.c_str(), P.bRecurse, FNotifyOptionFlags); + for (PathIt it = events.begin(); it != events.end(); it++) + { + Path& P = *it; + P.FWaitHandle = FindFirstChangeNotification(P.FDirectory.c_str(), P.bRecurse, FNotifyOptionFlags); if (P.FWaitHandle == INVALID_HANDLE_VALUE) #ifndef __BORLANDC__ - Debug.fatal (DEBUG_INFO,"Can't create notify handle for path: '%s'\nwith error: '%s'",P.FDirectory.c_str(),Debug.error2string(GetLastError())); + Debug.fatal(DEBUG_INFO, "Can't create notify handle for path: '%s'\nwith error: '%s'", P.FDirectory.c_str(), Debug.error2string(GetLastError())); #else // __BORLANDC__ - Debug.fatal ("Can't create notify handle for path: '%s'\nwith error: '%s'",P.FDirectory.c_str(),Debug.error2string(GetLastError())); + Debug.fatal("Can't create notify handle for path: '%s'\nwith error: '%s'", P.FDirectory.c_str(), Debug.error2string(GetLastError())); #endif // __BORLANDC__ } LeaveCriticalSection(&CS); -// if (FWaitHandle == INVALID_HANDLE_VALUE) -// return; - while(!Terminated) + // if (FWaitHandle == INVALID_HANDLE_VALUE) + // return; + while (!Terminated) { HANDLEVec hHandles; hHandles.push_back(FMutex); - for (PathIt it=events.begin(); it!=events.end(); it++) - hHandles.push_back(it->FWaitHandle); + for (PathIt it = events.begin(); it != events.end(); it++) + hHandles.push_back(it->FWaitHandle); int Obj = WaitForMultipleObjects(hHandles.size(), &*hHandles.begin(), false, INFINITE); - if (Obj==WAIT_OBJECT_0){ + if (Obj == WAIT_OBJECT_0) + { ReleaseMutex(FMutex); break; - }else if (Obj>WAIT_OBJECT_0){ - u32 idx = Obj-WAIT_OBJECT_0-1; - if (idx WAIT_OBJECT_0) + { + u32 idx = Obj - WAIT_OBJECT_0 - 1; + if (idx < events.size()) + { + Path& P = events[idx]; + if (!P.FChangeEvent.empty())P.FChangeEvent(); + if (P.FWaitHandle) FindNextChangeNotification(P.FWaitHandle); } - }else - return; + } + else + return; } } //--------------------------------------------------------------------------- void CLocatorAPI::SetEventNotification() { - InitializeCriticalSection (&CS); - FThread = xr_new(); - FThread->FNotifyOptionFlags = FILE_NOTIFY_CHANGE_FILE_NAME|FILE_NOTIFY_CHANGE_DIR_NAME|FILE_NOTIFY_CHANGE_LAST_WRITE; - for(PathPairIt p_it=pathes.begin(); p_it!=pathes.end(); p_it++) - if (p_it->second->m_Flags.is(FS_Path::flNotif)) FThread->RegisterPath(*p_it->second); - FThread->Start (); + InitializeCriticalSection(&CS); + FThread = xr_new(); + FThread->FNotifyOptionFlags = FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE; + for (PathPairIt p_it = pathes.begin(); p_it != pathes.end(); p_it++) + if (p_it->second->m_Flags.is(FS_Path::flNotif)) FThread->RegisterPath(*p_it->second); + FThread->Start(); } - + void CLocatorAPI::ClearEventNotification() { - if (FThread){ - FThread->Terminate (); - ReleaseMutex (FThread->FMutex); // this current thread must release the mutex - xr_delete (FThread); + if (FThread) + { + FThread->Terminate(); + ReleaseMutex(FThread->FMutex); // this current thread must release the mutex + xr_delete(FThread); } - DeleteCriticalSection (&CS); + DeleteCriticalSection(&CS); } diff --git a/src/xrCore/LocatorAPI_Notifications.h b/src/xrCore/LocatorAPI_Notifications.h index fe643621f25..1277c064a47 100644 --- a/src/xrCore/LocatorAPI_Notifications.h +++ b/src/xrCore/LocatorAPI_Notifications.h @@ -2,48 +2,49 @@ #define LocatorAPI_NotificationsH #pragma once -class CThread +class CThread { - static void startup (void* P); + static void startup(void* P); protected: - volatile u32 thID; - volatile BOOL Terminated; + volatile u32 thID; + volatile BOOL Terminated; public: - CThread (u32 _ID) - { - thID = _ID; - Terminated = FALSE; + CThread(u32 _ID) + { + thID = _ID; + Terminated = FALSE; } - virtual ~CThread (){} - void Start () - { - thread_spawn (startup,"FS-notify",0,this); - } - virtual void Execute () = 0; - void Terminate () {Terminated=TRUE;} + virtual ~CThread() {} + void Start() + { + thread_spawn(startup, "FS-notify", 0, this); + } + virtual void Execute() = 0; + void Terminate() { Terminated = TRUE; } }; class CFS_PathNotificator : public CThread { private: - struct Path { - shared_str FDirectory; - void* FWaitHandle; - fastdelegate::FastDelegate0<> FChangeEvent; - BOOL bRecurse; + struct Path + { + shared_str FDirectory; + void* FWaitHandle; + fastdelegate::FastDelegate0<> FChangeEvent; + BOOL bRecurse; }; - DEFINE_VECTOR (HANDLE,HANDLEVec,HANDLEIt); - DEFINE_VECTOR (Path,PathVec,PathIt); - PathVec events; + DEFINE_VECTOR(HANDLE, HANDLEVec, HANDLEIt); + DEFINE_VECTOR(Path, PathVec, PathIt); + PathVec events; public: - void* FMutex; - unsigned FNotifyOptionFlags; + void* FMutex; + unsigned FNotifyOptionFlags; protected: - virtual void Execute (); + virtual void Execute(); public: - CFS_PathNotificator (); - virtual ~CFS_PathNotificator(); - void RegisterPath (FS_Path& path); + CFS_PathNotificator(); + virtual ~CFS_PathNotificator(); + void RegisterPath(FS_Path& path); }; #endif // LocatorAPI_borlandH diff --git a/src/xrCore/LocatorAPI_auth.cpp b/src/xrCore/LocatorAPI_auth.cpp index 748308af083..831d760ca35 100644 --- a/src/xrCore/LocatorAPI_auth.cpp +++ b/src/xrCore/LocatorAPI_auth.cpp @@ -1,112 +1,119 @@ #include "stdafx.h" #pragma hdrstop -struct auth_options { - xr_vector ignore; - xr_vector important; +struct auth_options +{ + xr_vector ignore; + xr_vector important; }; -void auth_entry (void* p) +void auth_entry(void* p) { - FS.auth_runtime (p); + FS.auth_runtime(p); } -void CLocatorAPI::auth_generate (xr_vector& ignore, xr_vector& important) +void CLocatorAPI::auth_generate(xr_vector& ignore, xr_vector& important) { - auth_options* _o = xr_new (); - _o->ignore = ignore ; - _o->important = important ; + auth_options* _o = xr_new(); + _o->ignore = ignore; + _o->important = important; #if 1 - FS.auth_runtime (_o); + FS.auth_runtime (_o); #else - thread_spawn (auth_entry,"checksum",0,_o); + thread_spawn(auth_entry, "checksum", 0, _o); #endif } -u64 CLocatorAPI::auth_get () +u64 CLocatorAPI::auth_get() { - m_auth_lock.Enter () ; - m_auth_lock.Leave () ; - return m_auth_code ; + m_auth_lock.Enter(); + m_auth_lock.Leave(); + return m_auth_code; } -void CLocatorAPI::auth_runtime (void* params) +void CLocatorAPI::auth_runtime(void* params) { - m_auth_lock.Enter () ; - auth_options* _o = (auth_options*) params ; + m_auth_lock.Enter(); + auth_options* _o = (auth_options*)params; - CMemoryWriter writer; - pSettingsAuth->save_as (writer); - m_auth_code = crc32(writer.pointer(), writer.size()); + CMemoryWriter writer; + pSettingsAuth->save_as(writer); + m_auth_code = crc32(writer.pointer(), writer.size()); #ifdef DEBUG - if (strstr(Core.Params,"auth_debug")) - { - string_path tmp_path; - update_path(tmp_path, "$app_data_root$", "auth_psettings.ltx"); - IWriter* tmp_dst = w_open(tmp_path); - pSettingsAuth->save_as(*tmp_dst, false); - w_close(tmp_dst); - } + if (strstr(Core.Params, "auth_debug")) + { + string_path tmp_path; + update_path(tmp_path, "$app_data_root$", "auth_psettings.ltx"); + IWriter* tmp_dst = w_open(tmp_path); + pSettingsAuth->save_as(*tmp_dst, false); + w_close(tmp_dst); + } #endif - bool do_break = false; + bool do_break = false; #ifdef DEBUG - bool b_extern_auth = !!strstr(Core.Params,"asdf"); - if (!b_extern_auth) + bool b_extern_auth = !!strstr(Core.Params, "asdf"); + if (!b_extern_auth) #endif // DEBUG - { - for (files_it it = m_files.begin(); it!=m_files.end(); ++it) { - const file& f = *it; - - // test for skip - BOOL bSkip = FALSE; - for (u32 s=0; s<_o->ignore.size(); s++) { - if (strstr(f.name,_o->ignore[s].c_str())) - bSkip = TRUE; - } - - if (bSkip) - continue; - - // test for important - for (s=0; s<_o->important.size(); s++) { - if ((f.size_real != 0) && strstr(f.name,_o->important[s].c_str())) { - // crc for file - IReader* r = FS.r_open (f.name); - if (!r) { - do_break = true; - break; - } - u32 crc = crc32 (r->pointer(),r->length()); - + { + for (files_it it = m_files.begin(); it != m_files.end(); ++it) + { + const file& f = *it; + + // test for skip + BOOL bSkip = FALSE; + for (u32 s = 0; s < _o->ignore.size(); s++) + { + if (strstr(f.name, _o->ignore[s].c_str())) + bSkip = TRUE; + } + + if (bSkip) + continue; + + // test for important + for (s = 0; s < _o->important.size(); s++) + { + if ((f.size_real != 0) && strstr(f.name, _o->important[s].c_str())) + { + // crc for file + IReader* r = FS.r_open(f.name); + if (!r) + { + do_break = true; + break; + } + u32 crc = crc32(r->pointer(), r->length()); + #ifdef DEBUG - if(strstr(Core.Params,"auth_debug")) - Msg("auth %s = 0x%08x",f.name,crc); + if (strstr(Core.Params, "auth_debug")) + Msg("auth %s = 0x%08x", f.name, crc); #endif // DEBUG - FS.r_close (r); - m_auth_code ^= u64(crc); - } - } - - if (do_break) - break; - } + FS.r_close(r); + m_auth_code ^= u64(crc); + } + } + + if (do_break) + break; + } #ifdef DEBUG - Msg ( "auth_code = %d" , m_auth_code ); + Msg("auth_code = %d", m_auth_code); #endif // DEBUG - } + } #ifdef DEBUG - else { - string64 c_auth_code; - sscanf (strstr(Core.Params,"asdf ")+5,"%[^ ] ",c_auth_code); - m_auth_code = _atoi64(c_auth_code); - } + else + { + string64 c_auth_code; + sscanf(strstr(Core.Params, "asdf ") + 5, "%[^ ] ", c_auth_code); + m_auth_code = _atoi64(c_auth_code); + } #endif // DEBUG - xr_delete (_o); + xr_delete(_o); - m_auth_lock.Leave () ; + m_auth_lock.Leave(); } diff --git a/src/xrCore/LocatorAPI_defs.cpp b/src/xrCore/LocatorAPI_defs.cpp index be846a64fc1..66dd3aee199 100644 --- a/src/xrCore/LocatorAPI_defs.cpp +++ b/src/xrCore/LocatorAPI_defs.cpp @@ -12,112 +12,115 @@ ////////////////////////////////////////////////////////////////////// // FS_File ////////////////////////////////////////////////////////////////////// -FS_File::FS_File(const xr_string& nm, long sz, time_t modif,unsigned attr) {set(nm,sz,modif,attr);} -FS_File::FS_File(const xr_string& nm) {set(nm,0,0,0);} -FS_File::FS_File(const _FINDDATA_T& f) {set(f.name,f.size,f.time_write,(f.attrib&_A_SUBDIR)?flSubDir:0);} -FS_File::FS_File(const xr_string& nm, const _FINDDATA_T& f) {set(nm,f.size,f.time_write,(f.attrib&_A_SUBDIR)?flSubDir:0);} +FS_File::FS_File(const xr_string& nm, long sz, time_t modif, unsigned attr) { set(nm, sz, modif, attr); } +FS_File::FS_File(const xr_string& nm) { set(nm, 0, 0, 0); } +FS_File::FS_File(const _FINDDATA_T& f) { set(f.name, f.size, f.time_write, (f.attrib&_A_SUBDIR) ? flSubDir : 0); } +FS_File::FS_File(const xr_string& nm, const _FINDDATA_T& f) { set(nm, f.size, f.time_write, (f.attrib&_A_SUBDIR) ? flSubDir : 0); } -void FS_File::set(const xr_string& nm, long sz, time_t modif,unsigned attr) +void FS_File::set(const xr_string& nm, long sz, time_t modif, unsigned attr) { - name = nm; xr_strlwr (name); - size = sz; - time_write = modif; - attrib = attr; + name = nm; + xr_strlwr(name); + size = sz; + time_write = modif; + attrib = attr; } ////////////////////////////////////////////////////////////////////// // FS_Path ////////////////////////////////////////////////////////////////////// -FS_Path::FS_Path (LPCSTR _Root, LPCSTR _Add, LPCSTR _DefExt, LPCSTR _FilterCaption, u32 flags) +FS_Path::FS_Path(LPCSTR _Root, LPCSTR _Add, LPCSTR _DefExt, LPCSTR _FilterCaption, u32 flags) { -// VERIFY (_Root&&_Root[0]); - string_path temp; - xr_strcpy (temp,sizeof(temp),_Root); - if (_Add) xr_strcat(temp,_Add); - if (temp[0] && temp[xr_strlen(temp)-1]!='\\') xr_strcat(temp,"\\"); - m_Path = xr_strlwr(xr_strdup(temp)); - m_DefExt = _DefExt?xr_strlwr(xr_strdup(_DefExt)):0; - m_FilterCaption = _FilterCaption?xr_strlwr(xr_strdup(_FilterCaption)):0; - m_Add = _Add?xr_strlwr(xr_strdup(_Add)):0; - m_Root = _Root?xr_strlwr(xr_strdup(_Root)):0; - m_Flags.assign (flags); + // VERIFY (_Root&&_Root[0]); + string_path temp; + xr_strcpy(temp, sizeof(temp), _Root); + if (_Add) xr_strcat(temp, _Add); + if (temp[0] && temp[xr_strlen(temp) - 1] != '\\') xr_strcat(temp, "\\"); + m_Path = xr_strlwr(xr_strdup(temp)); + m_DefExt = _DefExt ? xr_strlwr(xr_strdup(_DefExt)) : 0; + m_FilterCaption = _FilterCaption ? xr_strlwr(xr_strdup(_FilterCaption)) : 0; + m_Add = _Add ? xr_strlwr(xr_strdup(_Add)) : 0; + m_Root = _Root ? xr_strlwr(xr_strdup(_Root)) : 0; + m_Flags.assign(flags); #ifdef _EDITOR - // Editor(s)/User(s) wants pathes already created in "real" file system :) - VerifyPath (m_Path); + // Editor(s)/User(s) wants pathes already created in "real" file system :) + VerifyPath(m_Path); #endif } -FS_Path::~FS_Path () +FS_Path::~FS_Path() { - xr_free (m_Root); - xr_free (m_Path); - xr_free (m_Add); - xr_free (m_DefExt); - xr_free (m_FilterCaption); + xr_free(m_Root); + xr_free(m_Path); + xr_free(m_Add); + xr_free(m_DefExt); + xr_free(m_FilterCaption); } -void FS_Path::_set (LPCSTR add) +void FS_Path::_set(LPCSTR add) { - // m_Add - R_ASSERT (add); - xr_free (m_Add); - m_Add = xr_strlwr(xr_strdup(add)); + // m_Add + R_ASSERT(add); + xr_free(m_Add); + m_Add = xr_strlwr(xr_strdup(add)); - // m_Path - string_path temp; - strconcat (sizeof(temp),temp,m_Root,m_Add); - if (temp[xr_strlen(temp)-1]!='\\') xr_strcat(temp,"\\"); - xr_free (m_Path); - m_Path = xr_strlwr(xr_strdup(temp)); + // m_Path + string_path temp; + strconcat(sizeof(temp), temp, m_Root, m_Add); + if (temp[xr_strlen(temp) - 1] != '\\') xr_strcat(temp, "\\"); + xr_free(m_Path); + m_Path = xr_strlwr(xr_strdup(temp)); } -void FS_Path::_set_root (LPCSTR root) +void FS_Path::_set_root(LPCSTR root) { - string_path temp; - xr_strcpy ( temp, root ); - if (m_Root[0] && m_Root[xr_strlen(m_Root)-1]!='\\') xr_strcat(temp,"\\"); - xr_free (m_Root); - m_Root = xr_strlwr(xr_strdup(temp)); + string_path temp; + xr_strcpy(temp, root); + if (m_Root[0] && m_Root[xr_strlen(m_Root) - 1] != '\\') xr_strcat(temp, "\\"); + xr_free(m_Root); + m_Root = xr_strlwr(xr_strdup(temp)); - // m_Path - strconcat (sizeof(temp),temp,m_Root,m_Add ? m_Add : ""); - if (*temp && temp[xr_strlen(temp)-1]!='\\') xr_strcat(temp,"\\"); - xr_free (m_Path); - m_Path = xr_strlwr(xr_strdup(temp)); + // m_Path + strconcat(sizeof(temp), temp, m_Root, m_Add ? m_Add : ""); + if (*temp && temp[xr_strlen(temp) - 1] != '\\') xr_strcat(temp, "\\"); + xr_free(m_Path); + m_Path = xr_strlwr(xr_strdup(temp)); } LPCSTR FS_Path::_update(string_path& dest, LPCSTR src)const { - R_ASSERT (dest); - R_ASSERT (src); - string_path temp; - xr_strcpy (temp, sizeof(temp), src); - strconcat (sizeof(dest), dest, m_Path, temp); - return xr_strlwr (dest); + R_ASSERT(dest); + R_ASSERT(src); + string_path temp; + xr_strcpy(temp, sizeof(temp), src); + strconcat(sizeof(dest), dest, m_Path, temp); + return xr_strlwr(dest); } /* void FS_Path::_update(xr_string& dest, LPCSTR src)const { - R_ASSERT(src); - dest = xr_string(m_Path)+src; - xr_strlwr (dest); +R_ASSERT(src); +dest = xr_string(m_Path)+src; +xr_strlwr (dest); }*/ -void FS_Path::rescan_path_cb () +void FS_Path::rescan_path_cb() { - m_Flags.set(flNeedRescan,TRUE); - FS.m_Flags.set(CLocatorAPI::flNeedRescan,TRUE); + m_Flags.set(flNeedRescan, TRUE); + FS.m_Flags.set(CLocatorAPI::flNeedRescan, TRUE); } bool XRCORE_API PatternMatch(LPCSTR s, LPCSTR mask) { - LPCSTR cp=0; - LPCSTR mp=0; - for (; *s&&*mask!='*'; mask++,s++) if (*mask!=*s&&*mask!='?') return false; - for (;;) { - if (!*s) { while (*mask=='*') mask++; return !*mask; } - if (*mask=='*') { if (!*++mask) return true; mp=mask; cp=s+1; continue; } - if (*mask==*s||*mask=='?') { mask++, s++; continue; } - mask=mp; s=cp++; - } + LPCSTR cp = 0; + LPCSTR mp = 0; + for (; *s&&*mask != '*'; mask++, s++) if (*mask != *s&&*mask != '?') return false; + for (;;) + { + if (!*s) { while (*mask == '*') mask++; return !*mask; } + if (*mask == '*') { if (!*++mask) return true; mp = mask; cp = s + 1; continue; } + if (*mask == *s || *mask == '?') { mask++, s++; continue; } + mask = mp; + s = cp++; + } } diff --git a/src/xrCore/LocatorAPI_defs.h b/src/xrCore/LocatorAPI_defs.h index d114f243523..86ee62709f0 100644 --- a/src/xrCore/LocatorAPI_defs.h +++ b/src/xrCore/LocatorAPI_defs.h @@ -5,68 +5,72 @@ enum FS_List { - FS_ListFiles =(1<<0), - FS_ListFolders =(1<<1), - FS_ClampExt =(1<<2), - FS_RootOnly =(1<<3), - FS_forcedword =u32(-1) + FS_ListFiles = (1 << 0), + FS_ListFolders = (1 << 1), + FS_ClampExt = (1 << 2), + FS_RootOnly = (1 << 3), + FS_forcedword = u32(-1) }; class XRCORE_API FS_Path { public: - enum{ - flRecurse = (1<<0), - flNotif = (1<<1), - flNeedRescan= (1<<2), + enum + { + flRecurse = (1 << 0), + flNotif = (1 << 1), + flNeedRescan = (1 << 2), }; public: - LPSTR m_Path; - LPSTR m_Root; - LPSTR m_Add; - LPSTR m_DefExt; - LPSTR m_FilterCaption; - Flags32 m_Flags; + LPSTR m_Path; + LPSTR m_Root; + LPSTR m_Add; + LPSTR m_DefExt; + LPSTR m_FilterCaption; + Flags32 m_Flags; public: - FS_Path (LPCSTR _Root, LPCSTR _Add, LPCSTR _DefExt=0, LPCSTR _FilterString=0, u32 flags=0); - ~FS_Path (); - LPCSTR _update (string_path& dest, LPCSTR src) const; - void _set (LPCSTR add); - void _set_root (LPCSTR root); + FS_Path(LPCSTR _Root, LPCSTR _Add, LPCSTR _DefExt = 0, LPCSTR _FilterString = 0, u32 flags = 0); + ~FS_Path(); + LPCSTR _update(string_path& dest, LPCSTR src) const; + void _set(LPCSTR add); + void _set_root(LPCSTR root); - void __stdcall rescan_path_cb (); + void __stdcall rescan_path_cb(); }; #ifdef _EDITOR - namespace std{ - struct _finddata_t; - }; -# define _FINDDATA_T std::_finddata_t +namespace std +{ +struct _finddata_t; +}; +# define _FINDDATA_T std::_finddata_t #else - struct _finddata64i32_t; -# define _FINDDATA_T _finddata64i32_t +struct _finddata64i32_t; +# define _FINDDATA_T _finddata64i32_t #endif -struct XRCORE_API FS_File{ - enum{ - flSubDir= (1<<0), - flVFS = (1<<1), - }; - unsigned attrib; - time_t time_write; - long size; - xr_string name; // low-case name - void set (const xr_string& nm, long sz, time_t modif,unsigned attr); +struct XRCORE_API FS_File +{ + enum + { + flSubDir = (1 << 0), + flVFS = (1 << 1), + }; + unsigned attrib; + time_t time_write; + long size; + xr_string name; // low-case name + void set(const xr_string& nm, long sz, time_t modif, unsigned attr); public: - FS_File (){} - FS_File (const xr_string& nm); - FS_File (const _FINDDATA_T& f); - FS_File (const xr_string& nm, const _FINDDATA_T& f); - FS_File (const xr_string& nm, long sz, time_t modif,unsigned attr); - bool operator< (const FS_File& _X) const {return xr_strcmp(name.c_str(),_X.name.c_str())<0; } + FS_File() {} + FS_File(const xr_string& nm); + FS_File(const _FINDDATA_T& f); + FS_File(const xr_string& nm, const _FINDDATA_T& f); + FS_File(const xr_string& nm, long sz, time_t modif, unsigned attr); + bool operator< (const FS_File& _X) const { return xr_strcmp(name.c_str(), _X.name.c_str()) < 0; } }; -DEFINE_SET (FS_File,FS_FileSet,FS_FileSetIt); +DEFINE_SET(FS_File, FS_FileSet, FS_FileSetIt); -extern bool XRCORE_API PatternMatch(LPCSTR s, LPCSTR mask); +extern bool XRCORE_API PatternMatch(LPCSTR s, LPCSTR mask); #endif //LocatorAPI_defsH diff --git a/src/xrCore/LzHuf.cpp b/src/xrCore/LzHuf.cpp index ff38cd1a0a3..5ecf503ef7b 100644 --- a/src/xrCore/LzHuf.cpp +++ b/src/xrCore/LzHuf.cpp @@ -12,192 +12,216 @@ //typedef unsigned char BYTE; -unsigned textsize = 0, codesize = 0; +unsigned textsize = 0, codesize = 0; -char wterr[] = "Can't write."; +char wterr[] = "Can't write."; /********** LZSS compression **********/ -#define N 4096 /* buffer size */ -#define F 60 /* lookahead buffer size */ -#define THRESHOLD 2 -#define NIL N /* leaf of tree */ +#define N 4096 /* buffer size */ +#define F 60 /* lookahead buffer size */ +#define THRESHOLD 2 +#define NIL N /* leaf of tree */ -#define N_CHAR (256 - THRESHOLD + F) /* kinds of characters (character code = 0..N_CHAR-1) */ -#define T (N_CHAR * 2 - 1) /* size of table */ -#define R (T - 1) /* position of root */ -#define MAX_FREQ 0x4000 /* updates tree when the */ +#define N_CHAR (256 - THRESHOLD + F) /* kinds of characters (character code = 0..N_CHAR-1) */ +#define T (N_CHAR * 2 - 1) /* size of table */ +#define R (T - 1) /* position of root */ +#define MAX_FREQ 0x4000 /* updates tree when the */ -u8 text_buf[N + F]; -int match_position, match_length, lson[N + 1], rson[N + 257], dad[N + 1]; +u8 text_buf[N + F]; +int match_position, match_length, lson[N + 1], rson[N + 257], dad[N + 1]; -unsigned code, len; -unsigned tim_size=0; +unsigned code, len; +unsigned tim_size = 0; -unsigned freq[T + 1]; /* frequency table */ +unsigned freq[T + 1]; /* frequency table */ -int prnt[T + N_CHAR+1]; /* pointers to parent nodes, except for the */ -/* elements [T..T + N_CHAR - 1] which are used to get */ -/* the positions of leaves corresponding to the codes. */ +int prnt[T + N_CHAR + 1]; /* pointers to parent nodes, except for the */ +/* elements [T..T + N_CHAR - 1] which are used to get */ +/* the positions of leaves corresponding to the codes. */ -int son[T]; /* pointers to child nodes (son[], son[] + 1) */ +int son[T]; /* pointers to child nodes (son[], son[] + 1) */ //************************** Internal FS -//typedef xr_vector vecB; -class LZfs { +//typedef xr_vector vecB; +class LZfs +{ private: - unsigned getbuf; - unsigned getlen; - - unsigned putbuf; - unsigned putlen; - - u8* in_start; - u8* in_end; - u8* in_iterator; - - u8* out_start; - u8* out_end; - u8* out_iterator; + unsigned getbuf; + unsigned getlen; + + unsigned putbuf; + unsigned putlen; + + u8* in_start; + u8* in_end; + u8* in_iterator; + + u8* out_start; + u8* out_end; + u8* out_iterator; public: - IC int _getb() { - if (in_iterator==in_end) return EOF; - return *in_iterator++; - } - IC void _putb(int c) { - if (out_iterator==out_end) { - u32 out_size= u32(out_end-out_start); - out_start = (u8*) xr_realloc(out_start,out_size+1024); - out_iterator= out_start+out_size; - out_end = out_iterator+1024; - } - *out_iterator++ = u8(c&0xFF); - } - - LZfs() { - in_start = in_end = in_iterator = 0; - out_start = out_end = out_iterator = 0; - } - - IC void Init_Input(u8* _start, u8* _end) { - // input - in_start = _start; - in_end = _end; - in_iterator = in_start; - - // bitwise input/output - getbuf = getlen = putbuf = putlen = 0; - } - IC void Init_Output(int _rsize) { - // output - out_start = (u8*)xr_malloc(_rsize); - out_end = out_start + _rsize; - out_iterator= out_start; - } - IC u32 InputSize () { - return u32(in_end-in_start); - } - IC u32 OutSize () { - return u32(out_iterator-out_start); - } - IC u8* OutPointer () { - return out_start; - } - IC void OutRelease () { - xr_free (out_start); - out_start = 0; - out_end = 0; - out_iterator= 0; - } - IC int GetBit(void) /* get one bit */ - { - unsigned i; - - while (getlen <= 8) { - if ((int)(i = _getb()) < 0) i = 0; - getbuf |= i << (8 - getlen); - getlen += 8; - } - i = getbuf; - getbuf <<= 1; - getlen--; - return (int)((i & 0x8000) >> 15); - } - - IC int GetByte(void) /* get one byte */ - { - unsigned i; - - while (getlen <= 8) { - if ((int)(i = _getb()) < 0) i = 0; - getbuf |= i << (8 - getlen); - getlen += 8; - } - i = getbuf; - getbuf <<= 8; - getlen -= 8; - return (int)((i & 0xff00) >> 8); - } - - IC void PutCode(int l, unsigned c) /* output c bits of code */ - { - putbuf |= c >> putlen; - if ((putlen += l) >= 8) { - _putb(putbuf >> 8); - if ((putlen -= 8) >= 8) { - _putb(putbuf); - codesize += 2; - putlen -= 8; - putbuf = c << (l - putlen); - } else { - putbuf <<= 8; - codesize++; - } - } - } - IC void PutFlush() - { - if (putlen) { - _putb(putbuf >> 8); - codesize++; - } - } + IC int _getb() + { + if (in_iterator == in_end) return EOF; + return *in_iterator++; + } + IC void _putb(int c) + { + if (out_iterator == out_end) + { + u32 out_size = u32(out_end - out_start); + out_start = (u8*)xr_realloc(out_start, out_size + 1024); + out_iterator = out_start + out_size; + out_end = out_iterator + 1024; + } + *out_iterator++ = u8(c & 0xFF); + } + + LZfs() + { + in_start = in_end = in_iterator = 0; + out_start = out_end = out_iterator = 0; + } + + IC void Init_Input(u8* _start, u8* _end) + { + // input + in_start = _start; + in_end = _end; + in_iterator = in_start; + + // bitwise input/output + getbuf = getlen = putbuf = putlen = 0; + } + IC void Init_Output(int _rsize) + { + // output + out_start = (u8*)xr_malloc(_rsize); + out_end = out_start + _rsize; + out_iterator = out_start; + } + IC u32 InputSize() + { + return u32(in_end - in_start); + } + IC u32 OutSize() + { + return u32(out_iterator - out_start); + } + IC u8* OutPointer() + { + return out_start; + } + IC void OutRelease() + { + xr_free(out_start); + out_start = 0; + out_end = 0; + out_iterator = 0; + } + IC int GetBit(void) /* get one bit */ + { + unsigned i; + + while (getlen <= 8) + { + if ((int)(i = _getb()) < 0) i = 0; + getbuf |= i << (8 - getlen); + getlen += 8; + } + i = getbuf; + getbuf <<= 1; + getlen--; + return (int)((i & 0x8000) >> 15); + } + + IC int GetByte(void) /* get one byte */ + { + unsigned i; + + while (getlen <= 8) + { + if ((int)(i = _getb()) < 0) i = 0; + getbuf |= i << (8 - getlen); + getlen += 8; + } + i = getbuf; + getbuf <<= 8; + getlen -= 8; + return (int)((i & 0xff00) >> 8); + } + + IC void PutCode(int l, unsigned c) /* output c bits of code */ + { + putbuf |= c >> putlen; + if ((putlen += l) >= 8) + { + _putb(putbuf >> 8); + if ((putlen -= 8) >= 8) + { + _putb(putbuf); + codesize += 2; + putlen -= 8; + putbuf = c << (l - putlen); + } + else + { + putbuf <<= 8; + codesize++; + } + } + } + IC void PutFlush() + { + if (putlen) + { + _putb(putbuf >> 8); + codesize++; + } + } }; static LZfs fs; //************************** Internal FS -IC void InitTree(void) /* initialize trees */ +IC void InitTree(void) /* initialize trees */ { - int i; - - for (i = N + 1; i <= N + 256; i++) rson[i] = NIL; /* root */ - for (i = 0; i < N; i++) dad[i] = NIL; /* node */ + int i; + + for (i = N + 1; i <= N + 256; i++) rson[i] = NIL; /* root */ + for (i = 0; i < N; i++) dad[i] = NIL; /* node */ } -void InsertNode(int r) /* insert to tree */ +void InsertNode(int r) /* insert to tree */ { - int i, p, cmp; - u8 *key; - unsigned c; - + int i, p, cmp; + u8* key; + unsigned c; + cmp = 1; key = &text_buf[r]; p = N + 1 + key[0]; rson[r] = lson[r] = NIL; match_length = 0; - for ( ; ; ) { - if (cmp >= 0) { + for (;;) + { + if (cmp >= 0) + { if (rson[p] != NIL) p = rson[p]; - else { + else + { rson[p] = r; dad[r] = p; return; } - } else { + } + else + { if (lson[p] != NIL) p = lson[p]; - else { + else + { lson[p] = r; dad[r] = p; return; @@ -206,20 +230,24 @@ void InsertNode(int r) /* insert to tree */ for (i = 1; i < F; i++) if ((cmp = key[i] - text_buf[p + i]) != 0) break; - if (i > THRESHOLD) { - if (i > match_length) { - match_position = ((r - p) & (N - 1)) - 1; - if ((match_length = i) >= F) - break; - } - if (i == match_length) { - if ((c = ((r - p) & (N-1)) - 1) < (unsigned)match_position) { - match_position = c; - } - } - } + if (i > THRESHOLD) + { + if (i > match_length) + { + match_position = ((r - p) & (N - 1)) - 1; + if ((match_length = i) >= F) + break; + } + if (i == match_length) + { + if ((c = ((r - p) & (N - 1)) - 1) < (unsigned)match_position) + { + match_position = c; + } + } + } } - dad[r] = dad[p]; + dad[r] = dad[p]; lson[r] = lson[p]; rson[r] = rson[p]; dad[lson[p]] = r; @@ -231,41 +259,41 @@ void InsertNode(int r) /* insert to tree */ dad[p] = NIL; /* remove p */ } -void DeleteNode(int p) /* remove from tree */ +void DeleteNode(int p) /* remove from tree */ { - int q; - - if (dad[p] == NIL) return; /* not registered */ + int q; + + if (dad[p] == NIL) return; /* not registered */ if (rson[p] == NIL) - q = lson[p]; - else - { - if (lson[p] == NIL) - { - q = rson[p]; - } - else - { - q = lson[p]; - if (rson[q] != NIL) - { - do { q = rson[q]; } while (rson[q] != NIL); - - rson[dad[q]] = lson[q]; - dad[lson[q]] = dad[q]; - lson[q] = lson[p]; - dad[lson[p]] = q; - } - rson[q] = rson[p]; - dad[rson[p]] = q; - } - } - dad[q] = dad[p]; - if (rson[dad[p]] == p) - rson[dad[p]] = q; - else - lson[dad[p]] = q; - dad[p] = NIL; + q = lson[p]; + else + { + if (lson[p] == NIL) + { + q = rson[p]; + } + else + { + q = lson[p]; + if (rson[q] != NIL) + { + do { q = rson[q]; } while (rson[q] != NIL); + + rson[dad[q]] = lson[q]; + dad[lson[q]] = dad[q]; + lson[q] = lson[p]; + dad[lson[p]] = q; + } + rson[q] = rson[p]; + dad[rson[p]] = q; + } + } + dad[q] = dad[p]; + if (rson[dad[p]] == p) + rson[dad[p]] = q; + else + lson[dad[p]] = q; + dad[p] = NIL; } /* Huffman coding */ @@ -273,97 +301,101 @@ void DeleteNode(int p) /* remove from tree */ /* table for encoding and decoding the upper 6 bits of position */ /* for encoding */ -u8 p_len[64] = { +u8 p_len[64] = +{ 0x03, 0x04, 0x04, 0x04, 0x05, 0x05, 0x05, 0x05, - 0x05, 0x05, 0x05, 0x05, 0x06, 0x06, 0x06, 0x06, - 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, - 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, - 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, - 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, - 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, - 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08 + 0x05, 0x05, 0x05, 0x05, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, + 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, + 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, + 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, + 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08 }; -u8 p_code[64] = { +u8 p_code[64] = +{ 0x00, 0x20, 0x30, 0x40, 0x50, 0x58, 0x60, 0x68, - 0x70, 0x78, 0x80, 0x88, 0x90, 0x94, 0x98, 0x9C, - 0xA0, 0xA4, 0xA8, 0xAC, 0xB0, 0xB4, 0xB8, 0xBC, - 0xC0, 0xC2, 0xC4, 0xC6, 0xC8, 0xCA, 0xCC, 0xCE, - 0xD0, 0xD2, 0xD4, 0xD6, 0xD8, 0xDA, 0xDC, 0xDE, - 0xE0, 0xE2, 0xE4, 0xE6, 0xE8, 0xEA, 0xEC, 0xEE, - 0xF0, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, - 0xF8, 0xF9, 0xFA, 0xFB, 0xFC, 0xFD, 0xFE, 0xFF + 0x70, 0x78, 0x80, 0x88, 0x90, 0x94, 0x98, 0x9C, + 0xA0, 0xA4, 0xA8, 0xAC, 0xB0, 0xB4, 0xB8, 0xBC, + 0xC0, 0xC2, 0xC4, 0xC6, 0xC8, 0xCA, 0xCC, 0xCE, + 0xD0, 0xD2, 0xD4, 0xD6, 0xD8, 0xDA, 0xDC, 0xDE, + 0xE0, 0xE2, 0xE4, 0xE6, 0xE8, 0xEA, 0xEC, 0xEE, + 0xF0, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, + 0xF8, 0xF9, 0xFA, 0xFB, 0xFC, 0xFD, 0xFE, 0xFF }; /* for decoding */ -u8 d_code[256] = { +u8 d_code[256] = +{ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, - 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, - 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, - 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, - 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, - 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, - 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, - 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, - 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, - 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, - 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, - 0x0B, 0x0B, 0x0B, 0x0B, 0x0B, 0x0B, 0x0B, 0x0B, - 0x0C, 0x0C, 0x0C, 0x0C, 0x0D, 0x0D, 0x0D, 0x0D, - 0x0E, 0x0E, 0x0E, 0x0E, 0x0F, 0x0F, 0x0F, 0x0F, - 0x10, 0x10, 0x10, 0x10, 0x11, 0x11, 0x11, 0x11, - 0x12, 0x12, 0x12, 0x12, 0x13, 0x13, 0x13, 0x13, - 0x14, 0x14, 0x14, 0x14, 0x15, 0x15, 0x15, 0x15, - 0x16, 0x16, 0x16, 0x16, 0x17, 0x17, 0x17, 0x17, - 0x18, 0x18, 0x19, 0x19, 0x1A, 0x1A, 0x1B, 0x1B, - 0x1C, 0x1C, 0x1D, 0x1D, 0x1E, 0x1E, 0x1F, 0x1F, - 0x20, 0x20, 0x21, 0x21, 0x22, 0x22, 0x23, 0x23, - 0x24, 0x24, 0x25, 0x25, 0x26, 0x26, 0x27, 0x27, - 0x28, 0x28, 0x29, 0x29, 0x2A, 0x2A, 0x2B, 0x2B, - 0x2C, 0x2C, 0x2D, 0x2D, 0x2E, 0x2E, 0x2F, 0x2F, - 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, - 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, + 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, + 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, + 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, + 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, + 0x0B, 0x0B, 0x0B, 0x0B, 0x0B, 0x0B, 0x0B, 0x0B, + 0x0C, 0x0C, 0x0C, 0x0C, 0x0D, 0x0D, 0x0D, 0x0D, + 0x0E, 0x0E, 0x0E, 0x0E, 0x0F, 0x0F, 0x0F, 0x0F, + 0x10, 0x10, 0x10, 0x10, 0x11, 0x11, 0x11, 0x11, + 0x12, 0x12, 0x12, 0x12, 0x13, 0x13, 0x13, 0x13, + 0x14, 0x14, 0x14, 0x14, 0x15, 0x15, 0x15, 0x15, + 0x16, 0x16, 0x16, 0x16, 0x17, 0x17, 0x17, 0x17, + 0x18, 0x18, 0x19, 0x19, 0x1A, 0x1A, 0x1B, 0x1B, + 0x1C, 0x1C, 0x1D, 0x1D, 0x1E, 0x1E, 0x1F, 0x1F, + 0x20, 0x20, 0x21, 0x21, 0x22, 0x22, 0x23, 0x23, + 0x24, 0x24, 0x25, 0x25, 0x26, 0x26, 0x27, 0x27, + 0x28, 0x28, 0x29, 0x29, 0x2A, 0x2A, 0x2B, 0x2B, + 0x2C, 0x2C, 0x2D, 0x2D, 0x2E, 0x2E, 0x2F, 0x2F, + 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, + 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, }; -u8 d_len[256] = { +u8 d_len[256] = +{ + 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, + 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, - 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, - 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, - 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, - 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, - 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, - 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, - 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, - 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, - 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, - 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, - 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, - 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, - 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, - 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, - 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, - 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, - 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, - 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, - 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, - 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, - 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, - 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, - 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, - 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, - 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, - 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, - 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, - 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, - 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, - 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, - 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, + 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, + 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, + 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, + 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, + 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, + 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, + 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, + 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, + 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, + 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, + 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, + 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, + 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, + 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, + 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, + 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, + 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, }; @@ -372,18 +404,22 @@ u8 d_len[256] = { void StartHuff(void) { int i, j; - - for (i = 0; i < N_CHAR; i++) { - freq[i] = 1; - son [i] = i + T; + + for (i = 0; i < N_CHAR; i++) + { + freq[i] = 1; + son[i] = i + T; prnt[i + T] = i; } - i = 0; j = N_CHAR; - while (j <= R) { - freq[j] = freq[i] + freq[i + 1]; - son[j] = i; - prnt[i] = prnt[i + 1] = j; - i += 2; j++; + i = 0; + j = N_CHAR; + while (j <= R) + { + freq[j] = freq[i] + freq[i + 1]; + son[j] = i; + prnt[i] = prnt[i + 1] = j; + i += 2; + j++; } freq[T] = 0xffff; prnt[R] = 0; @@ -393,36 +429,43 @@ void StartHuff(void) /* reconstruction of tree */ void reconst(void) { - int i, j, k; - unsigned f, l; - + int i, j, k; + unsigned f, l; + /* collect leaf nodes in the first half of the table */ /* and replace the freq by (freq + 1) / 2. */ j = 0; - for (i = 0; i < T; i++) { - if (son[i] >= T) { + for (i = 0; i < T; i++) + { + if (son[i] >= T) + { freq[j] = (freq[i] + 1) / 2; son[j] = son[i]; j++; } } /* begin constructing tree by connecting sons */ - for (i = 0, j = N_CHAR; j < T; i += 2, j++) { + for (i = 0, j = N_CHAR; j < T; i += 2, j++) + { k = i + 1; f = freq[j] = freq[i] + freq[k]; for (k = j - 1; f < freq[k]; k--); k++; l = (j - k) * sizeof(unsigned); - memmove (&freq[k + 1], &freq[k], l); + memmove(&freq[k + 1], &freq[k], l); freq[k] = f; - memmove (&son[k + 1], &son[k], l); + memmove(&son[k + 1], &son[k], l); son[k] = i; } /* connect prnt */ - for (i = 0; i < T; i++) { - if ((k = son[i]) >= T) { + for (i = 0; i < T; i++) + { + if ((k = son[i]) >= T) + { prnt[k] = i; - } else { + } + else + { prnt[k] = prnt[k + 1] = i; } } @@ -433,55 +476,59 @@ void reconst(void) void update(int c) { int i, j, k, l; - - if (freq[R] == MAX_FREQ) { + + if (freq[R] == MAX_FREQ) + { reconst(); } c = prnt[c + T]; - do { + do + { k = ++freq[c]; - + /* if the order is disturbed, exchange nodes */ - if ((unsigned)k > freq[l = c + 1]) { + if ((unsigned)k > freq[l = c + 1]) + { while ((unsigned)k > freq[++l]); l--; freq[c] = freq[l]; freq[l] = k; - + i = son[c]; prnt[i] = l; if (i < T) prnt[i + 1] = l; - + j = son[l]; son[l] = i; - + prnt[j] = c; if (j < T) prnt[j + 1] = c; son[c] = j; - + c = l; } - } while ((c = prnt[c]) != 0); /* repeat up to root */ + } while ((c = prnt[c]) != 0); /* repeat up to root */ } void EncodeChar(unsigned c) { unsigned i; int j, k; - + i = 0; j = 0; k = prnt[c + T]; - + /* travel from leaf to root */ - do { + do + { i >>= 1; - + /* if node's address is odd-numbered, choose bigger brother node */ if (k & 1) i += 0x8000; - + j++; - k = prnt[k]; + k = prnt[k]; } while (k != R); fs.PutCode(j, i); code = i; @@ -492,11 +539,11 @@ void EncodeChar(unsigned c) void EncodePosition(unsigned c) { unsigned i; - + /* output upper 6 bits by table lookup */ i = c >> 6; fs.PutCode(p_len[i], (unsigned)p_code[i] << 8); - + /* output lower 6 bits verbatim */ fs.PutCode(6, (c & 0x3f) << 10); } @@ -504,13 +551,14 @@ void EncodePosition(unsigned c) int DecodeChar(void) { unsigned c; - + c = son[R]; - + /* travel from root to leaf, */ /* choosing the smaller child node (son[]) if the read bit is 0, */ /* the bigger (son[]+1} if 1 */ - while (c < T) { + while (c < T) + { c += fs.GetBit(); c = son[c]; } @@ -522,34 +570,35 @@ int DecodeChar(void) int DecodePosition(void) { unsigned i, j, c; - + /* recover upper 6 bits from table */ i = fs.GetByte(); c = (unsigned)d_code[i] << 6; j = d_len[i]; - + /* read lower 6 bits verbatim */ j -= 2; - while (j--) { + while (j--) + { i = (i << 1) + fs.GetBit(); } return (int)(c | (i & 0x3f)); } /* compression */ -void Encode(void) /* compression */ +void Encode(void) /* compression */ { - int i, c, len, r, s, last_match_length; - + int i, c, len, r, s, last_match_length; + textsize = fs.InputSize(); - fs.Init_Output(textsize); - fs._putb((textsize & 0xff)); - fs._putb((textsize & 0xff00) >> 8); - fs._putb((textsize & 0xff0000L) >> 16); - fs._putb((textsize & 0xff000000L) >> 24); + fs.Init_Output(textsize); + fs._putb((textsize & 0xff)); + fs._putb((textsize & 0xff00) >> 8); + fs._putb((textsize & 0xff0000L) >> 16); + fs._putb((textsize & 0xff000000L) >> 24); if (textsize == 0) return; - textsize = 0; /* rewind and re-read */ + textsize = 0; /* rewind and re-read */ StartHuff(); InitTree(); s = 0; @@ -562,20 +611,25 @@ void Encode(void) /* compression */ for (i = 1; i <= F; i++) InsertNode(r - i); InsertNode(r); - do { + do + { if (match_length > len) match_length = len; - if (match_length <= THRESHOLD) { + if (match_length <= THRESHOLD) + { match_length = 1; - // textsize==56158 - FATAL :( + // textsize==56158 - FATAL :( EncodeChar(text_buf[r]); - } else { + } + else + { EncodeChar(255 - THRESHOLD + match_length); EncodePosition(match_position); } last_match_length = match_length; for (i = 0; i < last_match_length && - (c = fs._getb()) != EOF; i++) { + (c = fs._getb()) != EOF; i++) + { DeleteNode(s); text_buf[s] = (unsigned char)c; if (s < F - 1) @@ -584,8 +638,9 @@ void Encode(void) /* compression */ r = (r + 1) & (N - 1); InsertNode(r); } - textsize += i; - while (i++ < last_match_length) { + textsize += i; + while (i++ < last_match_length) + { DeleteNode(s); s = (s + 1) & (N - 1); r = (r + 1) & (N - 1); @@ -593,37 +648,42 @@ void Encode(void) /* compression */ } } while (len > 0); fs.PutFlush(); - tim_size = textsize; + tim_size = textsize; } -void Decode(void) /* recover */ +void Decode(void) /* recover */ { - int i, j, k, r, c; - unsigned int count; - - textsize = (fs._getb()); + int i, j, k, r, c; + unsigned int count; + + textsize = (fs._getb()); textsize |= (fs._getb() << 8); textsize |= (fs._getb() << 16); textsize |= (fs._getb() << 24); if (textsize == 0) return; - - fs.Init_Output(textsize); - + + fs.Init_Output(textsize); + StartHuff(); for (i = 0; i < N - F; i++) text_buf[i] = 0x20; r = N - F; - for (count = 0; count < textsize; ) { + for (count = 0; count < textsize;) + { c = DecodeChar(); - if (c < 256) { + if (c < 256) + { fs._putb(c); text_buf[r++] = (unsigned char)c; r &= (N - 1); count++; - } else { + } + else + { i = (r - DecodePosition() - 1) & (N - 1); j = c - 255 + THRESHOLD; - for (k = 0; k < j; k++) { + for (k = 0; k < j; k++) + { c = text_buf[(i + k) & (N - 1)]; fs._putb(c); text_buf[r++] = (unsigned char)c; @@ -632,54 +692,54 @@ void Decode(void) /* recover */ } } } - tim_size = count; + tim_size = count; } -unsigned _writeLZ (int hf, void* d, unsigned size) +unsigned _writeLZ(int hf, void* d, unsigned size) { - u8* start = (u8*) d; - fs.Init_Input(start,start+size); - - // Actual compression - Encode (); - // Flush cache - int size_out = fs.OutSize(); - if (size_out) _write(hf,fs.OutPointer(),size_out); - fs.OutRelease (); - return size_out; + u8* start = (u8*)d; + fs.Init_Input(start, start + size); + + // Actual compression + Encode(); + // Flush cache + int size_out = fs.OutSize(); + if (size_out) _write(hf, fs.OutPointer(), size_out); + fs.OutRelease(); + return size_out; } -void _compressLZ (u8** dest, unsigned* dest_sz, void* src, unsigned src_sz) +void _compressLZ(u8** dest, unsigned* dest_sz, void* src, unsigned src_sz) { - u8* start = (u8*) src; - fs.Init_Input(start,start+src_sz); + u8* start = (u8*)src; + fs.Init_Input(start, start + src_sz); Encode(); - *dest = fs.OutPointer(); - *dest_sz = fs.OutSize(); + *dest = fs.OutPointer(); + *dest_sz = fs.OutSize(); } -void _decompressLZ (u8** dest, unsigned* dest_sz, void* src, unsigned src_sz) +void _decompressLZ(u8** dest, unsigned* dest_sz, void* src, unsigned src_sz) { - u8* start = (u8*) src; - fs.Init_Input(start,start+src_sz); + u8* start = (u8*)src; + fs.Init_Input(start, start + src_sz); Decode(); - *dest = fs.OutPointer(); - *dest_sz = fs.OutSize(); + *dest = fs.OutPointer(); + *dest_sz = fs.OutSize(); } -unsigned _readLZ (int hf, void* &d, unsigned size) +unsigned _readLZ(int hf, void*& d, unsigned size) { - // Read file in memory - u8* data = (u8*)xr_malloc(size); - _read (hf,data,size); - - fs.Init_Input(data,data+size); - - // Actual compression + // Read file in memory + u8* data = (u8*)xr_malloc(size); + _read(hf, data, size); + + fs.Init_Input(data, data + size); + + // Actual compression Decode(); - - // Flush cache - xr_free (data); - d = fs.OutPointer(); - return fs.OutSize(); + + // Flush cache + xr_free(data); + d = fs.OutPointer(); + return fs.OutSize(); } diff --git a/src/xrCore/Model.cpp b/src/xrCore/Model.cpp index 9e5f4d3b0c3..75e5841fe79 100644 --- a/src/xrCore/Model.cpp +++ b/src/xrCore/Model.cpp @@ -18,7 +18,7 @@ using namespace ppmd; enum { UP_FREQ=5, INT_BITS=7, PERIOD_BITS=7, TOT_BITS=INT_BITS+PERIOD_BITS, INTERVAL=1 << INT_BITS, BIN_SCALE=1 << TOT_BITS, MAX_FREQ=124, O_BOUND=9 }; -compression::ppmd::stream *trained_model = 0; +compression::ppmd::stream *trained_model = 0; template @@ -340,14 +340,14 @@ static void RestoreModelRare(PPM_CONTEXT* pc1,PPM_CONTEXT* MinContext, while ( MaxContext->Suffix ) MaxContext=MaxContext->Suffix; MaxContext->removeBinConts(0); MRMethod=MR_METHOD(MRMethod+1); GlueCount=0; OrderFall=MaxOrder; - } else if (MRMethod == MRM_RESTART || GetUsedMemory() < (SubAllocatorSize >> 1)) { + } else if (MRMethod == MRM_RESTART || GetUsedMemory() < (SubAllocatorSize >> 1)) { StartModelRare(MaxOrder,MRMethod); EscCount=0; PrintCount=0xFF; } else { while ( MaxContext->Suffix ) MaxContext=MaxContext->Suffix; do { MaxContext->cutOff(0); ExpandTextArea(); - } while (GetUsedMemory() > 3*(SubAllocatorSize >> 2)); + } while (GetUsedMemory() > 3*(SubAllocatorSize >> 2)); GlueCount=0; OrderFall=MaxOrder; } } diff --git a/src/xrCore/NET_utils.cpp b/src/xrCore/NET_utils.cpp index b654b008c70..bac027d6865 100644 --- a/src/xrCore/NET_utils.cpp +++ b/src/xrCore/NET_utils.cpp @@ -5,356 +5,369 @@ // ---NET_Packet // reading -void NET_Packet::read_start() { r_pos = 0; INI_W(move_begin());} +void NET_Packet::read_start() { r_pos = 0; INI_W(move_begin()); } -u32 NET_Packet::r_begin ( u16& type ) // returns time of receiving +u32 NET_Packet::r_begin(u16& type) // returns time of receiving { - r_pos = 0; - if(!inistream) - r_u16 (type); - else - inistream->r_u16(type); + r_pos = 0; + if (!inistream) + r_u16(type); + else + inistream->r_u16(type); - return timeReceive; + return timeReceive; } -void NET_Packet::w_seek (u32 pos, const void* p, u32 count) +void NET_Packet::w_seek(u32 pos, const void* p, u32 count) { - VERIFY(p && count && (pos+count<=B.count)); - CopyMemory(&B.data[pos],p,count); -//. INI_ASSERT (w_seek) + VERIFY(p && count && (pos + count <= B.count)); + CopyMemory(&B.data[pos], p, count); + //. INI_ASSERT (w_seek) } -void NET_Packet::r_seek (u32 pos) +void NET_Packet::r_seek(u32 pos) { - INI_ASSERT (r_seek) - VERIFY (pos < B.count); - r_pos = pos; + INI_ASSERT(r_seek) + VERIFY(pos < B.count); + r_pos = pos; } -u32 NET_Packet::r_tell() -{ - INI_ASSERT (r_tell) - return r_pos; +u32 NET_Packet::r_tell() +{ + INI_ASSERT(r_tell) + return r_pos; } BOOL NET_Packet::r_eof() { - INI_ASSERT (r_eof) - return (r_pos>=B.count); + INI_ASSERT(r_eof) + return (r_pos >= B.count); } u32 NET_Packet::r_elapsed() { - INI_ASSERT (r_elapsed) - return (B.count-r_pos); + INI_ASSERT(r_elapsed) + return (B.count - r_pos); } -void NET_Packet::r_advance(u32 size) +void NET_Packet::r_advance(u32 size) { - INI_ASSERT (r_advance) - r_pos += size; - VERIFY (r_pos<=B.count); + INI_ASSERT(r_advance) + r_pos += size; + VERIFY(r_pos <= B.count); } // reading - utilities -void NET_Packet::r_vec3(Fvector& A) -{ - if(!inistream) - r(&A,sizeof(Fvector)); - else - inistream->r_vec3(A); +void NET_Packet::r_vec3(Fvector& A) +{ + if (!inistream) + r(&A, sizeof(Fvector)); + else + inistream->r_vec3(A); } // vec3 -void NET_Packet::r_vec4(Fvector4& A) -{ - if(!inistream) - r(&A,sizeof(Fvector4)); - else - inistream->r_vec4(A); +void NET_Packet::r_vec4(Fvector4& A) +{ + if (!inistream) + r(&A, sizeof(Fvector4)); + else + inistream->r_vec4(A); } // vec4 -void NET_Packet::r_float(float& A ) -{ - if(!inistream) - r (&A,sizeof(float)); - else - inistream->r_float(A); +void NET_Packet::r_float(float& A) +{ + if (!inistream) + r(&A, sizeof(float)); + else + inistream->r_float(A); } // float -void NET_Packet::r_u64(u64& A) -{ - if(!inistream) - r(&A,sizeof(u64)); - else - inistream->r_u64(A); +void NET_Packet::r_u64(u64& A) +{ + if (!inistream) + r(&A, sizeof(u64)); + else + inistream->r_u64(A); } // qword (8b) -void NET_Packet::r_s64(s64& A) -{ - if(!inistream) - r(&A,sizeof(s64)); - else - inistream->r_s64(A); +void NET_Packet::r_s64(s64& A) +{ + if (!inistream) + r(&A, sizeof(s64)); + else + inistream->r_s64(A); } // qword (8b) -void NET_Packet::r_u32(u32& A) -{ - if(!inistream) - r(&A,sizeof(u32)); - else - inistream->r_u32(A); +void NET_Packet::r_u32(u32& A) +{ + if (!inistream) + r(&A, sizeof(u32)); + else + inistream->r_u32(A); } // dword (4b) -void NET_Packet::r_s32(s32& A) -{ - if(!inistream) - r(&A,sizeof(s32)); - else - inistream->r_s32(A); +void NET_Packet::r_s32(s32& A) +{ + if (!inistream) + r(&A, sizeof(s32)); + else + inistream->r_s32(A); } // dword (4b) -void NET_Packet::r_u16(u16& A) -{ - if(!inistream) - r(&A,sizeof(u16)); - else - inistream->r_u16(A); +void NET_Packet::r_u16(u16& A) +{ + if (!inistream) + r(&A, sizeof(u16)); + else + inistream->r_u16(A); } // word (2b) -void NET_Packet::r_s16(s16& A) -{ - if(!inistream) - r(&A,sizeof(s16)); - else - inistream->r_s16(A); +void NET_Packet::r_s16(s16& A) +{ + if (!inistream) + r(&A, sizeof(s16)); + else + inistream->r_s16(A); } // word (2b) -void NET_Packet::r_u8(u8& A) -{ - if(!inistream) - r(&A,sizeof(u8)); - else - inistream->r_u8(A); +void NET_Packet::r_u8(u8& A) +{ + if (!inistream) + r(&A, sizeof(u8)); + else + inistream->r_u8(A); } // byte (1b) -void NET_Packet::r_s8(s8& A) -{ - if(!inistream) - r(&A,sizeof(s8)); - else - inistream->r_s8(A); +void NET_Packet::r_s8(s8& A) +{ + if (!inistream) + r(&A, sizeof(s8)); + else + inistream->r_s8(A); } // byte (1b) // IReader compatibility -Fvector NET_Packet::r_vec3() +Fvector NET_Packet::r_vec3() { - Fvector A; - r_vec3 (A); - return (A); + Fvector A; + r_vec3(A); + return (A); } Fvector4 NET_Packet::r_vec4() { - Fvector4 A; - r_vec4 (A); - return (A); + Fvector4 A; + r_vec4(A); + return (A); } -float NET_Packet::r_float_q8(float min,float max) +float NET_Packet::r_float_q8(float min, float max) { - float A; - r_float_q8 (A,min,max); - return A; + float A; + r_float_q8(A, min, max); + return A; } float NET_Packet::r_float_q16(float min, float max) { - float A; - r_float_q16 (A,min,max); - return A; + float A; + r_float_q16(A, min, max); + return A; } -float NET_Packet::r_float() -{ - float A; - r_float (A); - return (A); +float NET_Packet::r_float() +{ + float A; + r_float(A); + return (A); } // float -u64 NET_Packet::r_u64() -{ - u64 A; - r_u64 (A); - return (A); +u64 NET_Packet::r_u64() +{ + u64 A; + r_u64(A); + return (A); } // qword (8b) -s64 NET_Packet::r_s64() -{ - s64 A; - r_s64 (A); - return (A); +s64 NET_Packet::r_s64() +{ + s64 A; + r_s64(A); + return (A); } // qword (8b) -u32 NET_Packet::r_u32() -{ - u32 A; - r_u32 (A); - return (A); +u32 NET_Packet::r_u32() +{ + u32 A; + r_u32(A); + return (A); } // dword (4b) -s32 NET_Packet::r_s32() -{ - s32 A; - r_s32 (A); - return (A); +s32 NET_Packet::r_s32() +{ + s32 A; + r_s32(A); + return (A); } // dword (4b) -u16 NET_Packet::r_u16() -{ - u16 A; - r_u16 (A); - return (A); +u16 NET_Packet::r_u16() +{ + u16 A; + r_u16(A); + return (A); } // word (2b) -s16 NET_Packet::r_s16() -{ - s16 A; - r_s16 (A); - return (A); +s16 NET_Packet::r_s16() +{ + s16 A; + r_s16(A); + return (A); } // word (2b) -u8 NET_Packet::r_u8() -{ - u8 A; - r_u8 (A); - return (A); +u8 NET_Packet::r_u8() +{ + u8 A; + r_u8(A); + return (A); } // byte (1b) -s8 NET_Packet::r_s8() -{ - s8 A; - r_s8 (A); - return (A); +s8 NET_Packet::r_s8() +{ + s8 A; + r_s8(A); + return (A); } void NET_Packet::r_float_q16(float& A, float min, float max) { - u16 val; - r_u16 (val); - A = (float(val)*(max-min))/65535.f + min; // floating-point-error possible - VERIFY ((A >= min-EPS_S) && (A <= max+EPS_S)); + u16 val; + r_u16(val); + A = (float(val)*(max - min)) / 65535.f + min; // floating-point-error possible + VERIFY((A >= min - EPS_S) && (A <= max + EPS_S)); } void NET_Packet::r_float_q8(float& A, float min, float max) { - u8 val; - r_u8 (val); - A = (float(val)/255.0001f) *(max-min) + min; // floating-point-error possible - VERIFY ((A >= min) && (A <= max)); + u8 val; + r_u8(val); + A = (float(val) / 255.0001f) *(max - min) + min; // floating-point-error possible + VERIFY((A >= min) && (A <= max)); } -void NET_Packet::r_angle16(float& A) -{ - r_float_q16 (A,0,PI_MUL_2); +void NET_Packet::r_angle16(float& A) +{ + r_float_q16(A, 0, PI_MUL_2); } -void NET_Packet::r_angle8(float& A) -{ - r_float_q8 (A,0,PI_MUL_2); +void NET_Packet::r_angle8(float& A) +{ + r_float_q8(A, 0, PI_MUL_2); } -void NET_Packet::r_dir(Fvector& A) -{ - u16 t; - r_u16 (t); - pvDecompress(A,t); +void NET_Packet::r_dir(Fvector& A) +{ + u16 t; + r_u16(t); + pvDecompress(A, t); } void NET_Packet::r_sdir(Fvector& A) { - u16 t; - float s; - r_u16 (t); - r_float (s); - pvDecompress (A,t); - A.mul (s); + u16 t; + float s; + r_u16(t); + r_float(s); + pvDecompress(A, t); + A.mul(s); } -void NET_Packet::r_stringZ( LPSTR S ) +void NET_Packet::r_stringZ(LPSTR S) { - if(!inistream) - { - LPCSTR data = LPCSTR(&B.data[r_pos]); - size_t len = xr_strlen(data); - r (S,(u32)len+1); - }else{ - inistream->r_string(S, 4096);//??? - } + if (!inistream) + { + LPCSTR data = LPCSTR(&B.data[r_pos]); + size_t len = xr_strlen(data); + r(S, (u32)len + 1); + } + else + { + inistream->r_string(S, 4096);//??? + } } -void NET_Packet::r_stringZ( xr_string& dest ) -{ - if(!inistream) - { - dest = LPCSTR(&B.data[r_pos]); - r_advance (u32(dest.size()+1)); - }else{ - string4096 buff; - inistream->r_string(buff, sizeof(buff)); - dest = buff; - } +void NET_Packet::r_stringZ(xr_string& dest) +{ + if (!inistream) + { + dest = LPCSTR(&B.data[r_pos]); + r_advance(u32(dest.size() + 1)); + } + else + { + string4096 buff; + inistream->r_string(buff, sizeof(buff)); + dest = buff; + } } void NET_Packet::r_stringZ(shared_str& dest) { - if(!inistream) - { - dest = LPCSTR(&B.data[r_pos]); - r_advance (dest.size()+1); - }else{ - string4096 buff; - inistream->r_string(buff, sizeof(buff)); - dest = buff; - } + if (!inistream) + { + dest = LPCSTR(&B.data[r_pos]); + r_advance(dest.size() + 1); + } + else + { + string4096 buff; + inistream->r_string(buff, sizeof(buff)); + dest = buff; + } } void NET_Packet::skip_stringZ() { - if (!inistream) - { - LPCSTR data = LPCSTR(&B.data[r_pos]); - u32 len = xr_strlen(data); - r_advance (len + 1); - } else { - inistream->skip_stringZ (); - } + if (!inistream) + { + LPCSTR data = LPCSTR(&B.data[r_pos]); + u32 len = xr_strlen(data); + r_advance(len + 1); + } + else + { + inistream->skip_stringZ(); + } } void NET_Packet::r_matrix(Fmatrix& M) { - r_vec3 (M.i); M._14_ = 0; - r_vec3 (M.j); M._24_ = 0; - r_vec3 (M.k); M._34_ = 0; - r_vec3 (M.c); M._44_ = 1; + r_vec3(M.i); + M._14_ = 0; + r_vec3(M.j); + M._24_ = 0; + r_vec3(M.k); + M._34_ = 0; + r_vec3(M.c); + M._44_ = 1; } void NET_Packet::r_clientID(ClientID& C) { - u32 tmp; - r_u32 (tmp); - C.set (tmp); + u32 tmp; + r_u32(tmp); + C.set(tmp); } -void NET_Packet::r_stringZ_s (LPSTR string, u32 const size) +void NET_Packet::r_stringZ_s(LPSTR string, u32 const size) { - if ( inistream ) { - inistream->r_string( string, size ); - return; - } - - LPCSTR data = LPCSTR( B.data + r_pos ); - u32 length = xr_strlen( data ); - R_ASSERT2 ( ( length+1 ) <= size, "buffer overrun" ); - r ( string, length+1 ); + if (inistream) + { + inistream->r_string(string, size); + return; + } + + LPCSTR data = LPCSTR(B.data + r_pos); + u32 length = xr_strlen(data); + R_ASSERT2((length + 1) <= size, "buffer overrun"); + r(string, length + 1); } \ No newline at end of file diff --git a/src/xrCore/PPMdType.h b/src/xrCore/PPMdType.h index b22ad30410d..796086790d8 100644 --- a/src/xrCore/PPMdType.h +++ b/src/xrCore/PPMdType.h @@ -51,18 +51,18 @@ const int MAX_O=16; /* maximum allowed model order */ /* PPMd module works with file streams via ...GETC/...PUTC macros only */ #ifndef VERIFY -# define VERIFY(a) -# define VERIFY2(a,b) -# define VERIFY_is_defined_in_ppmdtype_h +# define VERIFY(a) +# define VERIFY2(a,b) +# define VERIFY_is_defined_in_ppmdtype_h #endif // VERIFY - typedef unsigned char u8; - typedef unsigned int u32; -# include "compression_ppmd_stream.h" + typedef unsigned char u8; + typedef unsigned int u32; +# include "compression_ppmd_stream.h" #ifdef VERIFY_is_defined_in_ppmdtype_h -# undef VERIFY -# undef VERIFY2 -# undef VERIFY_is_defined_in_ppmdtype_h +# undef VERIFY +# undef VERIFY2 +# undef VERIFY_is_defined_in_ppmdtype_h #endif // VERIFY_is_defined_in_ppmdtype_h #include "compression_ppmd_stream.h" diff --git a/src/xrCore/Xr_ini.cpp b/src/xrCore/Xr_ini.cpp index 72df9634b3c..fbc944686fc 100644 --- a/src/xrCore/Xr_ini.cpp +++ b/src/xrCore/Xr_ini.cpp @@ -3,24 +3,28 @@ #include "fs_internal.h" -XRCORE_API CInifile const * pSettings = NULL; -XRCORE_API CInifile const * pSettingsAuth = NULL; +XRCORE_API CInifile const* pSettings = NULL; +XRCORE_API CInifile const* pSettingsAuth = NULL; CInifile* CInifile::Create(const char* szFileName, BOOL ReadOnly) -{ return xr_new(szFileName,ReadOnly); } +{ + return xr_new(szFileName, ReadOnly); +} void CInifile::Destroy(CInifile* ini) -{ xr_delete(ini); } +{ + xr_delete(ini); +} -bool sect_pred(const CInifile::Sect *x, LPCSTR val) +bool sect_pred(const CInifile::Sect* x, LPCSTR val) { - return xr_strcmp(*x->Name,val)<0; + return xr_strcmp(*x->Name, val) < 0; }; bool item_pred(const CInifile::Item& x, LPCSTR val) { - if ((!x.first) || (!val)) return x.firstfirst,L)==0){ - if (val) *val = *A->second; - return TRUE; + SectCIt A = std::lower_bound(Data.begin(), Data.end(), L, item_pred); + if (A != Data.end() && xr_strcmp(*A->first, L) == 0) + { + if (val) *val = *A->second; + return TRUE; } - return FALSE; + return FALSE; } //------------------------------------------------------------------------------ -CInifile::CInifile(IReader* F ,LPCSTR path - #ifndef _EDITOR - ,allow_include_func_t allow_include_func - #endif - ) -{ - m_file_name[0] = 0; - m_flags.zero (); - m_flags.set (eSaveAtEnd, FALSE); - m_flags.set (eReadOnly, TRUE); - m_flags.set (eOverrideNames, FALSE); - Load (F,path - #ifndef _EDITOR - , allow_include_func - #endif - ); +CInifile::CInifile(IReader* F, LPCSTR path +#ifndef _EDITOR + , allow_include_func_t allow_include_func +#endif + ) +{ + m_file_name[0] = 0; + m_flags.zero(); + m_flags.set(eSaveAtEnd, FALSE); + m_flags.set(eReadOnly, TRUE); + m_flags.set(eOverrideNames, FALSE); + Load(F, path +#ifndef _EDITOR + , allow_include_func +#endif + ); } CInifile::CInifile(LPCSTR szFileName, - BOOL ReadOnly, - BOOL bLoad, - BOOL SaveAtEnd, - u32 sect_count - #ifndef _EDITOR - ,allow_include_func_t allow_include_func - #endif - ) + BOOL ReadOnly, + BOOL bLoad, + BOOL SaveAtEnd, + u32 sect_count +#ifndef _EDITOR + , allow_include_func_t allow_include_func +#endif + ) { - if(szFileName && strstr(szFileName,"system")) - Msg("-----loading %s",szFileName); - - m_file_name[0] = 0; - m_flags.zero (); - if(szFileName) - xr_strcpy (m_file_name, sizeof(m_file_name), szFileName); - - m_flags.set (eSaveAtEnd, SaveAtEnd); - m_flags.set (eReadOnly, ReadOnly); - - if (bLoad) - { - string_path path,folder; - _splitpath (m_file_name, path, folder, 0, 0 ); - xr_strcat (path,sizeof(path),folder); - IReader* R = FS.r_open(szFileName); - if (R){ - if(sect_count) - DATA.reserve(sect_count); - Load (R, path - #ifndef _EDITOR - , allow_include_func - #endif - ); - FS.r_close (R); + if (szFileName && strstr(szFileName, "system")) + Msg("-----loading %s", szFileName); + + m_file_name[0] = 0; + m_flags.zero(); + if (szFileName) + xr_strcpy(m_file_name, sizeof(m_file_name), szFileName); + + m_flags.set(eSaveAtEnd, SaveAtEnd); + m_flags.set(eReadOnly, ReadOnly); + + if (bLoad) + { + string_path path, folder; + _splitpath(m_file_name, path, folder, 0, 0); + xr_strcat(path, sizeof(path), folder); + IReader* R = FS.r_open(szFileName); + if (R) + { + if (sect_count) + DATA.reserve(sect_count); + Load(R, path +#ifndef _EDITOR + , allow_include_func +#endif + ); + FS.r_close(R); } - } + } } -CInifile::~CInifile( ) +CInifile::~CInifile() { - if (!m_flags.test(eReadOnly) && m_flags.test(eSaveAtEnd)) - { - if (!save_as()) - Log ("!Can't save inifile:",m_file_name); - } + if (!m_flags.test(eReadOnly) && m_flags.test(eSaveAtEnd)) + { + if (!save_as()) + Log("!Can't save inifile:", m_file_name); + } - RootIt I = DATA.begin(); - RootIt E = DATA.end(); - for ( ; I != E; ++I) - xr_delete (*I); + RootIt I = DATA.begin(); + RootIt E = DATA.end(); + for (; I != E; ++I) + xr_delete(*I); } -static void insert_item(CInifile::Sect *tgt, const CInifile::Item& I) +static void insert_item(CInifile::Sect* tgt, const CInifile::Item& I) { - CInifile::SectIt_ sect_it = std::lower_bound(tgt->Data.begin(),tgt->Data.end(),*I.first,item_pred); - if (sect_it!=tgt->Data.end() && sect_it->first.equal(I.first)) - { - sect_it->second = I.second; -//#ifdef DEBUG -// sect_it->comment= I.comment; -//#endif - }else{ - tgt->Data.insert (sect_it,I); - } + CInifile::SectIt_ sect_it = std::lower_bound(tgt->Data.begin(), tgt->Data.end(), *I.first, item_pred); + if (sect_it != tgt->Data.end() && sect_it->first.equal(I.first)) + { + sect_it->second = I.second; + //#ifdef DEBUG + // sect_it->comment= I.comment; + //#endif + } + else + { + tgt->Data.insert(sect_it, I); + } } -IC BOOL is_empty_line_now(IReader* F) -{ - char* a0 = (char*)F->pointer()-4; - char* a1 = (char*)(F->pointer())-3; - char* a2 = (char*)F->pointer()-2; - char* a3 = (char*)(F->pointer())-1; - - return (*a0==13) && ( *a1==10) && (*a2==13) && ( *a3==10); +IC BOOL is_empty_line_now(IReader* F) +{ + char* a0 = (char*)F->pointer() - 4; + char* a1 = (char*)(F->pointer()) - 3; + char* a2 = (char*)F->pointer() - 2; + char* a3 = (char*)(F->pointer()) - 1; + + return (*a0 == 13) && (*a1 == 10) && (*a2 == 13) && (*a3 == 10); }; -void CInifile::Load(IReader* F, LPCSTR path - #ifndef _EDITOR - ,allow_include_func_t allow_include_func - #endif - ) -{ - R_ASSERT(F); - Sect *Current = 0; - string4096 str; - string4096 str2; - - BOOL bInsideSTR = FALSE; - - while (!F->eof()) - { - F->r_string (str,sizeof(str)); - _Trim (str); - LPSTR comm = strchr(str,';'); - LPSTR comm_1 = strchr(str,'/'); - - if(comm_1 && (*(comm_1+1)=='/') && ((!comm) || (comm && (comm_1eof()) + { + F->r_string(str, sizeof(str)); + _Trim(str); + LPSTR comm = strchr(str, ';'); + LPSTR comm_1 = strchr(str, '/'); + + if (comm_1 && (*(comm_1 + 1) == '/') && ((!comm) || (comm && (comm_1 < comm)))) + { + comm = comm_1; + } #ifdef DEBUG - LPSTR comment = 0; + LPSTR comment = 0; #endif - if (comm) - { - //."bla-bla-bla;nah-nah-nah" - char quot = '"'; - bool in_quot = false; - - LPCSTR q1 = strchr(str,quot); - if(q1 && q1comm) - in_quot = true; - } - - if(!in_quot) - { - *comm = 0; + if (comm) + { + //."bla-bla-bla;nah-nah-nah" + char quot = '"'; + bool in_quot = false; + + LPCSTR q1 = strchr(str, quot); + if (q1 && q1 < comm) + { + LPCSTR q2 = strchr(++q1, quot); + if (q2 && q2 > comm) + in_quot = true; + } + + if (!in_quot) + { + *comm = 0; #ifdef DEBUG - comment = comm+1; + comment = comm + 1; +#endif + } + } + + + if (str[0] && (str[0] == '#') && strstr(str, "#include")) //handle includes + { + string_path inc_name; + R_ASSERT(path&&path[0]); + if (_GetItem(str, 1, inc_name, '"')) + { + string_path fn, inc_path, folder; + strconcat(sizeof(fn), fn, path, inc_name); + _splitpath(fn, inc_path, folder, 0, 0); + xr_strcat(inc_path, sizeof(inc_path), folder); +#ifndef _EDITOR + if (!allow_include_func || allow_include_func(fn)) #endif - } - } - - - if (str[0] && (str[0]=='#') && strstr(str,"#include")) //handle includes - { - string_path inc_name; - R_ASSERT (path&&path[0]); - if (_GetItem (str,1,inc_name,'"')) - { - string_path fn,inc_path,folder; - strconcat (sizeof(fn),fn,path,inc_name); - _splitpath (fn,inc_path,folder, 0, 0 ); - xr_strcat (inc_path,sizeof(inc_path),folder); + { + IReader* I = FS.r_open(fn); + R_ASSERT3(I, "Can't find include file:", inc_name); + Load(I, inc_path #ifndef _EDITOR - if (!allow_include_func || allow_include_func(fn)) -#endif - { - IReader* I = FS.r_open(fn); R_ASSERT3(I,"Can't find include file:", inc_name); - Load (I,inc_path - #ifndef _EDITOR - , allow_include_func - #endif - ); - FS.r_close (I); - } + , allow_include_func +#endif + ); + FS.r_close(I); + } } - } - else if (str[0] && (str[0]=='[')) //new section ? - { - // insert previous filled section - if (Current) - { - //store previous section - RootIt I = std::lower_bound(DATA.begin(),DATA.end(),*Current->Name,sect_pred); - if ((I!=DATA.end())&&((*I)->Name==Current->Name)) - Debug.fatal(DEBUG_INFO,"Duplicate section '%s' found.",*Current->Name); - DATA.insert (I,Current); - } - Current = xr_new(); - Current->Name = 0; - // start new section - R_ASSERT3(strchr(str,']'),"Bad ini section found: ",str); - LPCSTR inherited_names = strstr(str,"]:"); - if (0!=inherited_names) - { - VERIFY2 (m_flags.test(eReadOnly),"Allow for readonly mode only."); - inherited_names += 2; - u32 cnt = _GetItemCount(inherited_names); - u32 total_count = 0; - u32 k = 0; - for (k=0; kData.reserve( Current->Data.size() + total_count ); - - for (k=0; kName = strlwr(str+1); - } - else // name = value - { - if (Current) - { - string4096 value_raw; - char* name = str; - char* t = strchr(name,'='); - if (t) - { - *t = 0; - _Trim (name); - ++t; - xr_strcpy (value_raw, sizeof(value_raw), t); - bInsideSTR = _parse(str2, value_raw); - if(bInsideSTR)//multiline str value - { - while(bInsideSTR) - { - xr_strcat (value_raw, sizeof(value_raw),"\r\n"); - string4096 str_add_raw; - F->r_string (str_add_raw, sizeof(str_add_raw)); - R_ASSERT2 ( - xr_strlen(value_raw) + xr_strlen(str_add_raw) < sizeof(value_raw), - make_string( - "Incorrect inifile format: section[%s], variable[%s]. Odd number of quotes (\") found, but should be even.", - Current->Name.c_str(), - name - ) - ); - xr_strcat (value_raw, sizeof(value_raw),str_add_raw); - bInsideSTR = _parse(str2, value_raw); - if(bInsideSTR) + } + else if (str[0] && (str[0] == '[')) //new section ? + { + // insert previous filled section + if (Current) + { + //store previous section + RootIt I = std::lower_bound(DATA.begin(), DATA.end(), *Current->Name, sect_pred); + if ((I != DATA.end()) && ((*I)->Name == Current->Name)) + Debug.fatal(DEBUG_INFO, "Duplicate section '%s' found.", *Current->Name); + DATA.insert(I, Current); + } + Current = xr_new(); + Current->Name = 0; + // start new section + R_ASSERT3(strchr(str, ']'), "Bad ini section found: ", str); + LPCSTR inherited_names = strstr(str, "]:"); + if (0 != inherited_names) + { + VERIFY2(m_flags.test(eReadOnly), "Allow for readonly mode only."); + inherited_names += 2; + u32 cnt = _GetItemCount(inherited_names); + u32 total_count = 0; + u32 k = 0; + for (k = 0; k < cnt; ++k) + { + string512 tmp; + _GetItem(inherited_names, k, tmp); + Sect& inherited_section = r_section(tmp); + total_count += inherited_section.Data.size(); + } + + Current->Data.reserve(Current->Data.size() + total_count); + + for (k = 0; k < cnt; ++k) + { + string512 tmp; + _GetItem(inherited_names, k, tmp); + Sect& inherited_section = r_section(tmp); + for (SectIt_ it = inherited_section.Data.begin(); it != inherited_section.Data.end(); it++) + insert_item(Current, *it); + } + } + *strchr(str, ']') = 0; + Current->Name = strlwr(str + 1); + } + else // name = value + { + if (Current) + { + string4096 value_raw; + char* name = str; + char* t = strchr(name, '='); + if (t) + { + *t = 0; + _Trim(name); + ++t; + xr_strcpy(value_raw, sizeof(value_raw), t); + bInsideSTR = _parse(str2, value_raw); + if (bInsideSTR)//multiline str value + { + while (bInsideSTR) + { + xr_strcat(value_raw, sizeof(value_raw), "\r\n"); + string4096 str_add_raw; + F->r_string(str_add_raw, sizeof(str_add_raw)); + R_ASSERT2( + xr_strlen(value_raw) + xr_strlen(str_add_raw) < sizeof(value_raw), + make_string( + "Incorrect inifile format: section[%s], variable[%s]. Odd number of quotes (\") found, but should be even.", + Current->Name.c_str(), + name + ) + ); + xr_strcat(value_raw, sizeof(value_raw), str_add_raw); + bInsideSTR = _parse(str2, value_raw); + if (bInsideSTR) { - if( is_empty_line_now(F) ) - xr_strcat (value_raw, sizeof(value_raw),"\r\n"); + if (is_empty_line_now(F)) + xr_strcat(value_raw, sizeof(value_raw), "\r\n"); } - } - } - } else - { - _Trim (name); - str2[0] = 0; - } - - Item I; - I.first = (name[0]?name:NULL); - I.second = (str2[0]?str2:NULL); -//#ifdef DEBUG -// I.comment = m_flags.test(eReadOnly)?0:comment; -//#endif - - if (m_flags.test(eReadOnly)) - { - if (*I.first) insert_item (Current,I); - } else - { - if ( - *I.first - || *I.second -//#ifdef DEBUG -// || *I.comment -//#endif - ) - insert_item (Current,I); - } - } - } - } - if (Current) - { - RootIt I = std::lower_bound(DATA.begin(),DATA.end(),*Current->Name,sect_pred); - if ((I!=DATA.end())&&((*I)->Name==Current->Name)) - Debug.fatal(DEBUG_INFO,"Duplicate section '%s' found.",*Current->Name); - DATA.insert (I,Current); - } -} - -void CInifile::save_as (IWriter& writer, bool bcheck) const -{ - string4096 temp,val; - for (RootCIt r_it=DATA.begin(); r_it!=DATA.end(); ++r_it) - { - xr_sprintf (temp, sizeof(temp), "[%s]", (*r_it)->Name.c_str()); - writer.w_string (temp); - if(bcheck) - { - xr_sprintf (temp, sizeof(temp), "; %d %d %d", (*r_it)->Name._get()->dwCRC, - (*r_it)->Name._get()->dwReference, - (*r_it)->Name._get()->dwLength); - writer.w_string (temp); - } - - for (SectCIt s_it=(*r_it)->Data.begin(); s_it!=(*r_it)->Data.end(); ++s_it) + } + } + } + else + { + _Trim(name); + str2[0] = 0; + } + + Item I; + I.first = (name[0] ? name : NULL); + I.second = (str2[0] ? str2 : NULL); + //#ifdef DEBUG + // I.comment = m_flags.test(eReadOnly)?0:comment; + //#endif + + if (m_flags.test(eReadOnly)) + { + if (*I.first) insert_item(Current, I); + } + else + { + if ( + *I.first + || *I.second + //#ifdef DEBUG + // || *I.comment + //#endif + ) + insert_item(Current, I); + } + } + } + } + if (Current) + { + RootIt I = std::lower_bound(DATA.begin(), DATA.end(), *Current->Name, sect_pred); + if ((I != DATA.end()) && ((*I)->Name == Current->Name)) + Debug.fatal(DEBUG_INFO, "Duplicate section '%s' found.", *Current->Name); + DATA.insert(I, Current); + } +} + +void CInifile::save_as(IWriter& writer, bool bcheck) const +{ + string4096 temp, val; + for (RootCIt r_it = DATA.begin(); r_it != DATA.end(); ++r_it) + { + xr_sprintf(temp, sizeof(temp), "[%s]", (*r_it)->Name.c_str()); + writer.w_string(temp); + if (bcheck) { - const Item& I = *s_it; - if (*I.first) - { - if (*I.second) - { - _decorate (val, *I.second); + xr_sprintf(temp, sizeof(temp), "; %d %d %d", (*r_it)->Name._get()->dwCRC, + (*r_it)->Name._get()->dwReference, + (*r_it)->Name._get()->dwLength); + writer.w_string(temp); + } + + for (SectCIt s_it = (*r_it)->Data.begin(); s_it != (*r_it)->Data.end(); ++s_it) + { + const Item& I = *s_it; + if (*I.first) + { + if (*I.second) + { + _decorate(val, *I.second); // only name and value - xr_sprintf (temp, sizeof(temp), "%8s%-32s = %-32s"," ",I.first.c_str(),val); - }else - { + xr_sprintf(temp, sizeof(temp), "%8s%-32s = %-32s", " ", I.first.c_str(), val); + } + else + { // only name - xr_sprintf(temp, sizeof(temp), "%8s%-32s = "," ",I.first.c_str()); + xr_sprintf(temp, sizeof(temp), "%8s%-32s = ", " ", I.first.c_str()); } - }else - { + } + else + { // no name, so no value - temp[0] = 0; + temp[0] = 0; } - _TrimRight (temp); - if (temp[0]) writer.w_string (temp); + _TrimRight(temp); + if (temp[0]) writer.w_string(temp); } - writer.w_string (" "); + writer.w_string(" "); } } -bool CInifile::save_as (LPCSTR new_fname) +bool CInifile::save_as(LPCSTR new_fname) { - // save if needed + // save if needed if (new_fname && new_fname[0]) - xr_strcpy (m_file_name, sizeof(m_file_name), new_fname); + xr_strcpy(m_file_name, sizeof(m_file_name), new_fname); - R_ASSERT (m_file_name&&m_file_name[0]); - IWriter* F = FS.w_open_ex(m_file_name); + R_ASSERT(m_file_name&&m_file_name[0]); + IWriter* F = FS.w_open_ex(m_file_name); if (!F) - return (false); + return (false); - save_as (*F); - FS.w_close (F); - return (true); + save_as(*F); + FS.w_close(F); + return (true); } -BOOL CInifile::section_exist( LPCSTR S )const +BOOL CInifile::section_exist(LPCSTR S)const { - RootCIt I = std::lower_bound(DATA.begin(), DATA.end(), S, sect_pred); - return (I!=DATA.end() && xr_strcmp(*(*I)->Name,S)==0); + RootCIt I = std::lower_bound(DATA.begin(), DATA.end(), S, sect_pred); + return (I != DATA.end() && xr_strcmp(*(*I)->Name, S) == 0); } -BOOL CInifile::line_exist( LPCSTR S, LPCSTR L )const +BOOL CInifile::line_exist(LPCSTR S, LPCSTR L)const { - if (!section_exist(S)) return FALSE; - Sect& I = r_section(S); - SectCIt A = std::lower_bound(I.Data.begin(),I.Data.end(),L,item_pred); - return (A!=I.Data.end() && xr_strcmp(*A->first,L)==0); + if (!section_exist(S)) return FALSE; + Sect& I = r_section(S); + SectCIt A = std::lower_bound(I.Data.begin(), I.Data.end(), L, item_pred); + return (A != I.Data.end() && xr_strcmp(*A->first, L) == 0); } -u32 CInifile::line_count(LPCSTR Sname)const +u32 CInifile::line_count(LPCSTR Sname)const { - Sect& S = r_section(Sname); - SectCIt I = S.Data.begin(); - u32 C = 0; - for (; I!=S.Data.end(); I++) if (*I->first) C++; - return C; + Sect& S = r_section(Sname); + SectCIt I = S.Data.begin(); + u32 C = 0; + for (; I != S.Data.end(); I++) if (*I->first) C++; + return C; } -u32 CInifile::section_count ( )const +u32 CInifile::section_count()const { - return DATA.size(); + return DATA.size(); } //-------------------------------------------------------------------------------------- -CInifile::Sect& CInifile::r_section ( const shared_str& S )const { return r_section(*S); } -BOOL CInifile::line_exist ( const shared_str& S, const shared_str& L )const { return line_exist(*S,*L); } -u32 CInifile::line_count ( const shared_str& S )const { return line_count(*S); } -BOOL CInifile::section_exist ( const shared_str& S )const { return section_exist(*S); } +CInifile::Sect& CInifile::r_section(const shared_str& S)const { return r_section(*S); } +BOOL CInifile::line_exist(const shared_str& S, const shared_str& L)const { return line_exist(*S, *L); } +u32 CInifile::line_count(const shared_str& S)const { return line_count(*S); } +BOOL CInifile::section_exist(const shared_str& S)const { return section_exist(*S); } //-------------------------------------------------------------------------------------- // Read functions //-------------------------------------------------------------------------------------- -CInifile::Sect& CInifile::r_section( LPCSTR S )const -{ - char section[256]; xr_strcpy(section,sizeof(section),S); strlwr(section); - RootCIt I = std::lower_bound(DATA.begin(),DATA.end(),section,sect_pred); - if (!(I!=DATA.end() && xr_strcmp(*(*I)->Name,section)==0)) - { - - //g_pStringContainer->verify(); - - //string_path ini_dump_fn, path; - //strconcat (sizeof(ini_dump_fn), ini_dump_fn, Core.ApplicationName, "_", Core.UserName, ".ini_log"); - // - //FS.update_path (path, "$logs$", ini_dump_fn); - //IWriter* F = FS.w_open_ex(path); - //save_as (*F); - //F->w_string ("shared strings:"); - //g_pStringContainer->dump(F); - //FS.w_close (F); - - Debug.fatal (DEBUG_INFO,"Can't open section '%s'. Please attach [*.ini_log] file to your bug report",S); - } - return **I; +CInifile::Sect& CInifile::r_section(LPCSTR S)const +{ + char section[256]; + xr_strcpy(section, sizeof(section), S); + strlwr(section); + RootCIt I = std::lower_bound(DATA.begin(), DATA.end(), section, sect_pred); + if (!(I != DATA.end() && xr_strcmp(*(*I)->Name, section) == 0)) + { + + //g_pStringContainer->verify(); + + //string_path ini_dump_fn, path; + //strconcat (sizeof(ini_dump_fn), ini_dump_fn, Core.ApplicationName, "_", Core.UserName, ".ini_log"); + // + //FS.update_path (path, "$logs$", ini_dump_fn); + //IWriter* F = FS.w_open_ex(path); + //save_as (*F); + //F->w_string ("shared strings:"); + //g_pStringContainer->dump(F); + //FS.w_close (F); + + Debug.fatal(DEBUG_INFO, "Can't open section '%s'. Please attach [*.ini_log] file to your bug report", S); + } + return **I; } -LPCSTR CInifile::r_string(LPCSTR S, LPCSTR L)const +LPCSTR CInifile::r_string(LPCSTR S, LPCSTR L)const { - Sect const& I = r_section(S); - SectCIt A = std::lower_bound(I.Data.begin(),I.Data.end(),L,item_pred); - if (A!=I.Data.end() && xr_strcmp(*A->first,L)==0) return *A->second; - else - Debug.fatal(DEBUG_INFO,"Can't find variable %s in [%s]",L,S); - return 0; + Sect const& I = r_section(S); + SectCIt A = std::lower_bound(I.Data.begin(), I.Data.end(), L, item_pred); + if (A != I.Data.end() && xr_strcmp(*A->first, L) == 0) return *A->second; + else + Debug.fatal(DEBUG_INFO, "Can't find variable %s in [%s]", L, S); + return 0; } -shared_str CInifile::r_string_wb(LPCSTR S, LPCSTR L)const +shared_str CInifile::r_string_wb(LPCSTR S, LPCSTR L)const { - LPCSTR _base = r_string(S,L); - - if (0==_base) return shared_str(0); + LPCSTR _base = r_string(S, L); + + if (0 == _base) return shared_str(0); - string4096 _original; - xr_strcpy (_original,sizeof(_original),_base); - u32 _len = xr_strlen(_original); - if (0==_len) return shared_str(""); - if ('"'==_original[_len-1]) _original[_len-1]=0; // skip end - if ('"'==_original[0]) return shared_str(&_original[0] + 1); // skip begin - return shared_str(_original); + string4096 _original; + xr_strcpy(_original, sizeof(_original), _base); + u32 _len = xr_strlen(_original); + if (0 == _len) return shared_str(""); + if ('"' == _original[_len - 1]) _original[_len - 1] = 0; // skip end + if ('"' == _original[0]) return shared_str(&_original[0] + 1); // skip begin + return shared_str(_original); } u8 CInifile::r_u8(LPCSTR S, LPCSTR L)const { - LPCSTR C = r_string(S,L); - return u8(atoi(C)); + LPCSTR C = r_string(S, L); + return u8(atoi(C)); } u16 CInifile::r_u16(LPCSTR S, LPCSTR L)const { - LPCSTR C = r_string(S,L); - return u16(atoi(C)); + LPCSTR C = r_string(S, L); + return u16(atoi(C)); } u32 CInifile::r_u32(LPCSTR S, LPCSTR L)const { - LPCSTR C = r_string(S,L); - return u32(atoi(C)); + LPCSTR C = r_string(S, L); + return u32(atoi(C)); } u64 CInifile::r_u64(LPCSTR S, LPCSTR L)const { - LPCSTR C = r_string(S,L); + LPCSTR C = r_string(S, L); #ifndef _EDITOR - return _strtoui64(C,NULL,10); + return _strtoui64(C, NULL, 10); #else - return (u64)_atoi64(C); + return (u64)_atoi64(C); #endif } s64 CInifile::r_s64(LPCSTR S, LPCSTR L)const { - LPCSTR C = r_string(S,L); - return _atoi64(C); + LPCSTR C = r_string(S, L); + return _atoi64(C); } s8 CInifile::r_s8(LPCSTR S, LPCSTR L)const { - LPCSTR C = r_string(S,L); - return s8(atoi(C)); + LPCSTR C = r_string(S, L); + return s8(atoi(C)); } s16 CInifile::r_s16(LPCSTR S, LPCSTR L)const { - LPCSTR C = r_string(S,L); - return s16(atoi(C)); + LPCSTR C = r_string(S, L); + return s16(atoi(C)); } s32 CInifile::r_s32(LPCSTR S, LPCSTR L)const { - LPCSTR C = r_string(S,L); - return s32(atoi(C)); + LPCSTR C = r_string(S, L); + return s32(atoi(C)); } float CInifile::r_float(LPCSTR S, LPCSTR L)const { - LPCSTR C = r_string(S,L); - return float(atof( C )); + LPCSTR C = r_string(S, L); + return float(atof(C)); } -Fcolor CInifile::r_fcolor( LPCSTR S, LPCSTR L )const +Fcolor CInifile::r_fcolor(LPCSTR S, LPCSTR L)const { - LPCSTR C = r_string(S,L); - Fcolor V={0,0,0,0}; - sscanf (C,"%f,%f,%f,%f",&V.r,&V.g,&V.b,&V.a); - return V; + LPCSTR C = r_string(S, L); + Fcolor V = {0, 0, 0, 0}; + sscanf(C, "%f,%f,%f,%f", &V.r, &V.g, &V.b, &V.a); + return V; } -u32 CInifile::r_color( LPCSTR S, LPCSTR L )const +u32 CInifile::r_color(LPCSTR S, LPCSTR L)const { - LPCSTR C = r_string(S,L); - u32 r=0,g=0,b=0,a=255; - sscanf (C,"%d,%d,%d,%d",&r,&g,&b,&a); - return color_rgba(r,g,b,a); + LPCSTR C = r_string(S, L); + u32 r = 0, g = 0, b = 0, a = 255; + sscanf(C, "%d,%d,%d,%d", &r, &g, &b, &a); + return color_rgba(r, g, b, a); } -Ivector2 CInifile::r_ivector2( LPCSTR S, LPCSTR L )const +Ivector2 CInifile::r_ivector2(LPCSTR S, LPCSTR L)const { - LPCSTR C = r_string(S,L); - Ivector2 V={0,0}; - sscanf (C,"%d,%d",&V.x,&V.y); - return V; + LPCSTR C = r_string(S, L); + Ivector2 V = {0, 0}; + sscanf(C, "%d,%d", &V.x, &V.y); + return V; } -Ivector3 CInifile::r_ivector3( LPCSTR S, LPCSTR L )const +Ivector3 CInifile::r_ivector3(LPCSTR S, LPCSTR L)const { - LPCSTR C = r_string(S,L); - Ivector V={0,0,0}; - sscanf (C,"%d,%d,%d",&V.x,&V.y,&V.z); - return V; + LPCSTR C = r_string(S, L); + Ivector V = {0, 0, 0}; + sscanf(C, "%d,%d,%d", &V.x, &V.y, &V.z); + return V; } -Ivector4 CInifile::r_ivector4( LPCSTR S, LPCSTR L )const +Ivector4 CInifile::r_ivector4(LPCSTR S, LPCSTR L)const { - LPCSTR C = r_string(S,L); - Ivector4 V={0,0,0,0}; - sscanf (C,"%d,%d,%d,%d",&V.x,&V.y,&V.z,&V.w); - return V; + LPCSTR C = r_string(S, L); + Ivector4 V = {0, 0, 0, 0}; + sscanf(C, "%d,%d,%d,%d", &V.x, &V.y, &V.z, &V.w); + return V; } -Fvector2 CInifile::r_fvector2( LPCSTR S, LPCSTR L )const +Fvector2 CInifile::r_fvector2(LPCSTR S, LPCSTR L)const { - LPCSTR C = r_string(S,L); - Fvector2 V={0.f,0.f}; - sscanf (C,"%f,%f",&V.x,&V.y); - return V; + LPCSTR C = r_string(S, L); + Fvector2 V = {0.f, 0.f}; + sscanf(C, "%f,%f", &V.x, &V.y); + return V; } -Fvector3 CInifile::r_fvector3( LPCSTR S, LPCSTR L )const +Fvector3 CInifile::r_fvector3(LPCSTR S, LPCSTR L)const { - LPCSTR C = r_string(S,L); - Fvector3 V={0.f,0.f,0.f}; - sscanf (C,"%f,%f,%f",&V.x,&V.y,&V.z); - return V; + LPCSTR C = r_string(S, L); + Fvector3 V = {0.f, 0.f, 0.f}; + sscanf(C, "%f,%f,%f", &V.x, &V.y, &V.z); + return V; } -Fvector4 CInifile::r_fvector4( LPCSTR S, LPCSTR L )const +Fvector4 CInifile::r_fvector4(LPCSTR S, LPCSTR L)const { - LPCSTR C = r_string(S,L); - Fvector4 V={0.f,0.f,0.f,0.f}; - sscanf (C,"%f,%f,%f,%f",&V.x,&V.y,&V.z,&V.w); - return V; + LPCSTR C = r_string(S, L); + Fvector4 V = {0.f, 0.f, 0.f, 0.f}; + sscanf(C, "%f,%f,%f,%f", &V.x, &V.y, &V.z, &V.w); + return V; } -BOOL CInifile::r_bool( LPCSTR S, LPCSTR L )const +BOOL CInifile::r_bool(LPCSTR S, LPCSTR L)const { - LPCSTR C = r_string(S,L); - VERIFY2 ( - xr_strlen(C) <= 5, - make_string( - "\"%s\" is not a valid bool value, section[%s], line[%s]", - C, - S, - L - ) - ); - char B[8]; - strncpy_s (B,sizeof(B),C,7); - B[7] = 0; - strlwr (B); - return IsBOOL(B); + LPCSTR C = r_string(S, L); + VERIFY2( + xr_strlen(C) <= 5, + make_string( + "\"%s\" is not a valid bool value, section[%s], line[%s]", + C, + S, + L + ) + ); + char B[8]; + strncpy_s(B, sizeof(B), C, 7); + B[7] = 0; + strlwr(B); + return IsBOOL(B); } -CLASS_ID CInifile::r_clsid( LPCSTR S, LPCSTR L)const +CLASS_ID CInifile::r_clsid(LPCSTR S, LPCSTR L)const { - LPCSTR C = r_string(S,L); - return TEXT2CLSID(C); + LPCSTR C = r_string(S, L); + return TEXT2CLSID(C); } -int CInifile::r_token( LPCSTR S, LPCSTR L, const xr_token *token_list)const +int CInifile::r_token(LPCSTR S, LPCSTR L, const xr_token* token_list)const { - LPCSTR C = r_string(S,L); - for( int i=0; token_list[i].name; i++ ) - if( !stricmp(C,token_list[i].name) ) - return token_list[i].id; - return 0; + LPCSTR C = r_string(S, L); + for (int i = 0; token_list[i].name; i++) + if (!stricmp(C, token_list[i].name)) + return token_list[i].id; + return 0; } -BOOL CInifile::r_line( LPCSTR S, int L, const char** N, const char** V )const +BOOL CInifile::r_line(LPCSTR S, int L, const char** N, const char** V)const { - Sect& SS = r_section(S); - if (L>=(int)SS.Data.size() || L<0 ) return FALSE; - for (SectCIt I=SS.Data.begin(); I!=SS.Data.end(); I++) - if (!(L--)){ - *N = *I->first; - *V = *I->second; - return TRUE; - } - return FALSE; + Sect& SS = r_section(S); + if (L >= (int)SS.Data.size() || L < 0) return FALSE; + for (SectCIt I = SS.Data.begin(); I != SS.Data.end(); I++) + if (!(L--)) + { + *N = *I->first; + *V = *I->second; + return TRUE; + } + return FALSE; } -BOOL CInifile::r_line( const shared_str& S, int L, const char** N, const char** V )const +BOOL CInifile::r_line(const shared_str& S, int L, const char** N, const char** V)const { - return r_line(*S,L,N,V); + return r_line(*S, L, N, V); } //-------------------------------------------------------------------------------------------------------- // Write functions //-------------------------------------------------------------------------------------- -void CInifile::w_string( LPCSTR S, LPCSTR L, LPCSTR V, LPCSTR comment) -{ - R_ASSERT (!m_flags.test(eReadOnly)); - - // section - string256 sect; - _parse (sect,S); - _strlwr (sect); - - if (!section_exist(sect)) - { - // create _new_ section - Sect *NEW = xr_new(); - NEW->Name = sect; - RootIt I = std::lower_bound(DATA.begin(),DATA.end(),sect,sect_pred); - DATA.insert (I,NEW); - } - - // parse line/value - string4096 line; - _parse (line,L); - string4096 value; - _parse (value,V); - - // duplicate & insert - Item I; - Sect& data = r_section (sect); - I.first = (line[0]?line:0); - I.second = (value[0]?value:0); - -//#ifdef DEBUG -// I.comment = (comment?comment:0); -//#endif - SectIt_ it = std::lower_bound(data.Data.begin(),data.Data.end(),*I.first,item_pred); - - if (it != data.Data.end()) - { - // Check for "first" matching - if (0==xr_strcmp(*it->first, *I.first)) - { - BOOL b = m_flags.test(eOverrideNames); - R_ASSERT2(b,make_string("name[%s] already exist in section[%s]",line,sect).c_str()); - *it = I; - } else - { - data.Data.insert(it,I); +void CInifile::w_string(LPCSTR S, LPCSTR L, LPCSTR V, LPCSTR comment) +{ + R_ASSERT(!m_flags.test(eReadOnly)); + + // section + string256 sect; + _parse(sect, S); + _strlwr(sect); + + if (!section_exist(sect)) + { + // create _new_ section + Sect* NEW = xr_new(); + NEW->Name = sect; + RootIt I = std::lower_bound(DATA.begin(), DATA.end(), sect, sect_pred); + DATA.insert(I, NEW); + } + + // parse line/value + string4096 line; + _parse(line, L); + string4096 value; + _parse(value, V); + + // duplicate & insert + Item I; + Sect& data = r_section(sect); + I.first = (line[0] ? line : 0); + I.second = (value[0] ? value : 0); + + //#ifdef DEBUG + // I.comment = (comment?comment:0); + //#endif + SectIt_ it = std::lower_bound(data.Data.begin(), data.Data.end(), *I.first, item_pred); + + if (it != data.Data.end()) + { + // Check for "first" matching + if (0 == xr_strcmp(*it->first, *I.first)) + { + BOOL b = m_flags.test(eOverrideNames); + R_ASSERT2(b, make_string("name[%s] already exist in section[%s]", line, sect).c_str()); + *it = I; } - } else { - data.Data.insert(it,I); + else + { + data.Data.insert(it, I); + } + } + else + { + data.Data.insert(it, I); } } -void CInifile::w_u8 ( LPCSTR S, LPCSTR L, u8 V, LPCSTR comment ) +void CInifile::w_u8(LPCSTR S, LPCSTR L, u8 V, LPCSTR comment) { - string128 temp; xr_sprintf (temp,sizeof(temp),"%d",V); - w_string (S,L,temp,comment); + string128 temp; + xr_sprintf(temp, sizeof(temp), "%d", V); + w_string(S, L, temp, comment); } -void CInifile::w_u16 ( LPCSTR S, LPCSTR L, u16 V, LPCSTR comment ) +void CInifile::w_u16(LPCSTR S, LPCSTR L, u16 V, LPCSTR comment) { - string128 temp; xr_sprintf (temp,sizeof(temp),"%d",V); - w_string (S,L,temp,comment); + string128 temp; + xr_sprintf(temp, sizeof(temp), "%d", V); + w_string(S, L, temp, comment); } -void CInifile::w_u32 ( LPCSTR S, LPCSTR L, u32 V, LPCSTR comment ) +void CInifile::w_u32(LPCSTR S, LPCSTR L, u32 V, LPCSTR comment) { - string128 temp; xr_sprintf (temp,sizeof(temp),"%d",V); - w_string (S,L,temp,comment); + string128 temp; + xr_sprintf(temp, sizeof(temp), "%d", V); + w_string(S, L, temp, comment); } -void CInifile::w_u64 ( LPCSTR S, LPCSTR L, u64 V, LPCSTR comment ) +void CInifile::w_u64(LPCSTR S, LPCSTR L, u64 V, LPCSTR comment) { - string128 temp; + string128 temp; #ifndef _EDITOR - _ui64toa_s (V, temp, sizeof(temp), 10); + _ui64toa_s(V, temp, sizeof(temp), 10); #else - _ui64toa (V, temp, 10); + _ui64toa(V, temp, 10); #endif - w_string (S,L,temp,comment); + w_string(S, L, temp, comment); } -void CInifile::w_s64 ( LPCSTR S, LPCSTR L, s64 V, LPCSTR comment ) +void CInifile::w_s64(LPCSTR S, LPCSTR L, s64 V, LPCSTR comment) { - string128 temp; + string128 temp; #ifndef _EDITOR - _i64toa_s (V, temp, sizeof(temp), 10); + _i64toa_s(V, temp, sizeof(temp), 10); #else - _i64toa (V, temp, 10); + _i64toa(V, temp, 10); #endif - w_string (S,L,temp,comment); + w_string(S, L, temp, comment); } -void CInifile::w_s8 ( LPCSTR S, LPCSTR L, s8 V, LPCSTR comment ) +void CInifile::w_s8(LPCSTR S, LPCSTR L, s8 V, LPCSTR comment) { - string128 temp; xr_sprintf (temp,sizeof(temp),"%d",V); - w_string (S,L,temp,comment); + string128 temp; + xr_sprintf(temp, sizeof(temp), "%d", V); + w_string(S, L, temp, comment); } -void CInifile::w_s16 ( LPCSTR S, LPCSTR L, s16 V, LPCSTR comment ) +void CInifile::w_s16(LPCSTR S, LPCSTR L, s16 V, LPCSTR comment) { - string128 temp; xr_sprintf (temp,sizeof(temp),"%d",V); - w_string (S,L,temp,comment); + string128 temp; + xr_sprintf(temp, sizeof(temp), "%d", V); + w_string(S, L, temp, comment); } -void CInifile::w_s32 ( LPCSTR S, LPCSTR L, s32 V, LPCSTR comment ) +void CInifile::w_s32(LPCSTR S, LPCSTR L, s32 V, LPCSTR comment) { - string128 temp; xr_sprintf (temp,sizeof(temp),"%d",V); - w_string (S,L,temp,comment); + string128 temp; + xr_sprintf(temp, sizeof(temp), "%d", V); + w_string(S, L, temp, comment); } -void CInifile::w_float ( LPCSTR S, LPCSTR L, float V, LPCSTR comment ) +void CInifile::w_float(LPCSTR S, LPCSTR L, float V, LPCSTR comment) { - string128 temp; xr_sprintf (temp,sizeof(temp),"%f",V); - w_string (S,L,temp,comment); + string128 temp; + xr_sprintf(temp, sizeof(temp), "%f", V); + w_string(S, L, temp, comment); } -void CInifile::w_fcolor ( LPCSTR S, LPCSTR L, const Fcolor& V, LPCSTR comment ) +void CInifile::w_fcolor(LPCSTR S, LPCSTR L, const Fcolor& V, LPCSTR comment) { - string128 temp; xr_sprintf (temp,sizeof(temp),"%f,%f,%f,%f", V.r, V.g, V.b, V.a); - w_string (S,L,temp,comment); + string128 temp; + xr_sprintf(temp, sizeof(temp), "%f,%f,%f,%f", V.r, V.g, V.b, V.a); + w_string(S, L, temp, comment); } -void CInifile::w_color ( LPCSTR S, LPCSTR L, u32 V, LPCSTR comment ) +void CInifile::w_color(LPCSTR S, LPCSTR L, u32 V, LPCSTR comment) { - string128 temp; xr_sprintf (temp,sizeof(temp),"%d,%d,%d,%d", color_get_R(V), color_get_G(V), color_get_B(V), color_get_A(V)); - w_string (S,L,temp,comment); + string128 temp; + xr_sprintf(temp, sizeof(temp), "%d,%d,%d,%d", color_get_R(V), color_get_G(V), color_get_B(V), color_get_A(V)); + w_string(S, L, temp, comment); } -void CInifile::w_ivector2 ( LPCSTR S, LPCSTR L, const Ivector2& V, LPCSTR comment ) +void CInifile::w_ivector2(LPCSTR S, LPCSTR L, const Ivector2& V, LPCSTR comment) { - string128 temp; xr_sprintf (temp,sizeof(temp),"%d,%d", V.x, V.y); - w_string (S,L,temp,comment); + string128 temp; + xr_sprintf(temp, sizeof(temp), "%d,%d", V.x, V.y); + w_string(S, L, temp, comment); } -void CInifile::w_ivector3 ( LPCSTR S, LPCSTR L, const Ivector3& V, LPCSTR comment ) +void CInifile::w_ivector3(LPCSTR S, LPCSTR L, const Ivector3& V, LPCSTR comment) { - string128 temp; xr_sprintf (temp,sizeof(temp),"%d,%d,%d", V.x, V.y, V.z); - w_string (S,L,temp,comment); + string128 temp; + xr_sprintf(temp, sizeof(temp), "%d,%d,%d", V.x, V.y, V.z); + w_string(S, L, temp, comment); } -void CInifile::w_ivector4 ( LPCSTR S, LPCSTR L, const Ivector4& V, LPCSTR comment ) +void CInifile::w_ivector4(LPCSTR S, LPCSTR L, const Ivector4& V, LPCSTR comment) { - string128 temp; xr_sprintf (temp,sizeof(temp),"%d,%d,%d,%d", V.x, V.y, V.z, V.w); - w_string (S,L,temp,comment); + string128 temp; + xr_sprintf(temp, sizeof(temp), "%d,%d,%d,%d", V.x, V.y, V.z, V.w); + w_string(S, L, temp, comment); } -void CInifile::w_fvector2 ( LPCSTR S, LPCSTR L, const Fvector2& V, LPCSTR comment ) +void CInifile::w_fvector2(LPCSTR S, LPCSTR L, const Fvector2& V, LPCSTR comment) { - string128 temp; xr_sprintf (temp,sizeof(temp),"%f,%f", V.x, V.y); - w_string (S,L,temp,comment); + string128 temp; + xr_sprintf(temp, sizeof(temp), "%f,%f", V.x, V.y); + w_string(S, L, temp, comment); } -void CInifile::w_fvector3 ( LPCSTR S, LPCSTR L, const Fvector3& V, LPCSTR comment ) +void CInifile::w_fvector3(LPCSTR S, LPCSTR L, const Fvector3& V, LPCSTR comment) { - string128 temp; xr_sprintf (temp,sizeof(temp),"%f,%f,%f", V.x, V.y, V.z); - w_string (S,L,temp,comment); + string128 temp; + xr_sprintf(temp, sizeof(temp), "%f,%f,%f", V.x, V.y, V.z); + w_string(S, L, temp, comment); } -void CInifile::w_fvector4 ( LPCSTR S, LPCSTR L, const Fvector4& V, LPCSTR comment ) +void CInifile::w_fvector4(LPCSTR S, LPCSTR L, const Fvector4& V, LPCSTR comment) { - string128 temp; xr_sprintf (temp,sizeof(temp),"%f,%f,%f,%f", V.x, V.y, V.z, V.w); - w_string (S,L,temp,comment); + string128 temp; + xr_sprintf(temp, sizeof(temp), "%f,%f,%f,%f", V.x, V.y, V.z, V.w); + w_string(S, L, temp, comment); } -void CInifile::w_bool ( LPCSTR S, LPCSTR L, BOOL V, LPCSTR comment ) +void CInifile::w_bool(LPCSTR S, LPCSTR L, BOOL V, LPCSTR comment) { - w_string (S,L,V?"on":"off",comment); + w_string(S, L, V ? "on" : "off", comment); } -void CInifile::remove_line ( LPCSTR S, LPCSTR L ) +void CInifile::remove_line(LPCSTR S, LPCSTR L) { - R_ASSERT (!m_flags.test(eReadOnly)); + R_ASSERT(!m_flags.test(eReadOnly)); - if (line_exist(S,L)){ - Sect& data = r_section (S); - SectIt_ A = std::lower_bound(data.Data.begin(),data.Data.end(),L,item_pred); - R_ASSERT(A!=data.Data.end() && xr_strcmp(*A->first,L)==0); + if (line_exist(S, L)) + { + Sect& data = r_section(S); + SectIt_ A = std::lower_bound(data.Data.begin(), data.Data.end(), L, item_pred); + R_ASSERT(A != data.Data.end() && xr_strcmp(*A->first, L) == 0); data.Data.erase(A); } } diff --git a/src/xrCore/_bitwise.h b/src/xrCore/_bitwise.h index 9d191e35ca4..251d9d2bfb4 100644 --- a/src/xrCore/_bitwise.h +++ b/src/xrCore/_bitwise.h @@ -3,156 +3,156 @@ #pragma once // float values defines -#define fdSGN 0x080000000 // mask for sign bit -#define fdMABS 0x07FFFFFFF // mask for absolute value (~sgn) -#define fdMANT 0x0007FFFFF // mask for mantissa -#define fdEXPO 0x07F800000 // mask for exponent -#define fdONE 0x03F800000 // 1.0f -#define fdHALF 0x03F000000 // 0.5f -#define fdTWO 0x040000000 // 2.0 -#define fdOOB 0x000000000 // "out of bounds" value -#define fdNAN 0x07fffffff // "Not a number" value -#define fdMAX 0x07F7FFFFF // FLT_MAX -#define fdRLE10 0x03ede5bdb // 1/ln10 +#define fdSGN 0x080000000 // mask for sign bit +#define fdMABS 0x07FFFFFFF // mask for absolute value (~sgn) +#define fdMANT 0x0007FFFFF // mask for mantissa +#define fdEXPO 0x07F800000 // mask for exponent +#define fdONE 0x03F800000 // 1.0f +#define fdHALF 0x03F000000 // 0.5f +#define fdTWO 0x040000000 // 2.0 +#define fdOOB 0x000000000 // "out of bounds" value +#define fdNAN 0x07fffffff // "Not a number" value +#define fdMAX 0x07F7FFFFF // FLT_MAX +#define fdRLE10 0x03ede5bdb // 1/ln10 // integer math on floats -#ifdef _M_AMD64 - IC bool negative(const float f) { return f<0; } - IC bool positive(const float f) { return f>=0; } - IC void set_negative(float &f) { f = -fabsf(f); } - IC void set_positive(float &f) { f = fabsf(f); } +#ifdef _M_AMD64 +IC bool negative(const float f) { return f < 0; } +IC bool positive(const float f) { return f >= 0; } +IC void set_negative(float& f) { f = -fabsf(f); } +IC void set_positive(float& f) { f = fabsf(f); } #else - IC BOOL negative(const float &f) { return (*((unsigned*)(&f))&fdSGN); } - IC BOOL positive(const float &f) { return (*((unsigned*)(&f))&fdSGN)==0; } - IC void set_negative(float &f) { (*(unsigned*)(&f)) |= fdSGN; } - IC void set_positive(float &f) { (*(unsigned*)(&f)) &= ~fdSGN; } +IC BOOL negative(const float& f) { return (*((unsigned*)(&f))&fdSGN); } +IC BOOL positive(const float& f) { return (*((unsigned*)(&f))&fdSGN) == 0; } +IC void set_negative(float& f) { (*(unsigned*)(&f)) |= fdSGN; } +IC void set_positive(float& f) { (*(unsigned*)(&f)) &= ~fdSGN; } #endif /* * Here are a few nice tricks for 2's complement based machines * that I discovered a few months ago. */ -IC int btwLowestBitMask(int v) { return (v & -v); } -IC u32 btwLowestBitMask(u32 x) { return x & ~(x-1); } +IC int btwLowestBitMask(int v) { return (v & -v); } +IC u32 btwLowestBitMask(u32 x) { return x & ~(x - 1); } /* Ok, so now we are cooking on gass. Here we use this function for some */ /* rather useful utility functions */ -IC bool btwIsPow2(int v) { return (btwLowestBitMask(v) == v); } -IC bool btwIsPow2(u32 v) { return (btwLowestBitMask(v) == v); } +IC bool btwIsPow2(int v) { return (btwLowestBitMask(v) == v); } +IC bool btwIsPow2(u32 v) { return (btwLowestBitMask(v) == v); } -IC int btwPow2_Ceil(int v) +IC int btwPow2_Ceil(int v) { - int i = btwLowestBitMask(v); - while(i < v) i <<= 1; - return i; + int i = btwLowestBitMask(v); + while (i < v) i <<= 1; + return i; } -IC u32 btwPow2_Ceil(u32 v) +IC u32 btwPow2_Ceil(u32 v) { - u32 i = btwLowestBitMask(v); - while(i < v) i <<= 1; - return i; + u32 i = btwLowestBitMask(v); + while (i < v) i <<= 1; + return i; } -// Couple more tricks -// Counting number of nonzero bits for 8bit number: -IC u8 btwCount1(u8 v) +// Couple more tricks +// Counting number of nonzero bits for 8bit number: +IC u8 btwCount1(u8 v) { - v = (v & 0x55) + ((v >> 1) & 0x55); - v = (v & 0x33) + ((v >> 2) & 0x33); - return (v & 0x0f) + ((v >> 4) & 0x0f); + v = (v & 0x55) + ((v >> 1) & 0x55); + v = (v & 0x33) + ((v >> 2) & 0x33); + return (v & 0x0f) + ((v >> 4) & 0x0f); } -//same for 32bit -IC u32 btwCount1(u32 v) +//same for 32bit +IC u32 btwCount1(u32 v) { - const u32 g31 = 0x49249249ul; // = 0100_1001_0010_0100_1001_0010_0100_1001 - const u32 g32 = 0x381c0e07ul; // = 0011_1000_0001_1100_0000_1110_0000_0111 - v = (v & g31) + ((v >> 1) & g31) + ((v >> 2) & g31); - v = ((v + (v >> 3)) & g32) + ((v >> 6) & g32); - return (v + (v >> 9) + (v >> 18) + (v >> 27)) & 0x3f; + const u32 g31 = 0x49249249ul; // = 0100_1001_0010_0100_1001_0010_0100_1001 + const u32 g32 = 0x381c0e07ul; // = 0011_1000_0001_1100_0000_1110_0000_0111 + v = (v & g31) + ((v >> 1) & g31) + ((v >> 2) & g31); + v = ((v + (v >> 3)) & g32) + ((v >> 6) & g32); + return (v + (v >> 9) + (v >> 18) + (v >> 27)) & 0x3f; } -IC u64 btwCount1(u64 v) +IC u64 btwCount1(u64 v) { - return btwCount1(u32(v&u32(-1)))+btwCount1(u32(v>>u64(32))); + return btwCount1(u32(v&u32(-1))) + btwCount1(u32(v >> u64(32))); } -ICF int iFloor (float x) +ICF int iFloor(float x) { - int a = *(const int*)(&x); - int exponent = (127 + 31) - ((a >> 23) & 0xFF); - int r = (((u32)(a) << 8) | (1U << 31)) >> exponent; - exponent += 31-127; + int a = *(const int*)(&x); + int exponent = (127 + 31) - ((a >> 23) & 0xFF); + int r = (((u32)(a) << 8) | (1U << 31)) >> exponent; + exponent += 31 - 127; { - int imask = (!(((( (1<<(exponent)))-1)>>8)&a)); - exponent -= (31-127)+32; - exponent >>= 31; - a >>= 31; - r -= (imask&a); - r &= exponent; - r ^= a; + int imask = (!(((((1 << (exponent))) - 1) >> 8)&a)); + exponent -= (31 - 127) + 32; + exponent >>= 31; + a >>= 31; + r -= (imask&a); + r &= exponent; + r ^= a; } return r; } /* intCeil() is a non-interesting variant, since effectively - ceil(x) == -floor(-x) -*/ -ICF int iCeil (float x) + ceil(x) == -floor(-x) + */ +ICF int iCeil(float x) { - int a = (*(const int*)(&x)); - int exponent = (127 + 31) - ((a >> 23) & 0xFF); - int r = (((u32)(a) << 8) | (1U << 31)) >> exponent; - exponent += 31-127; + int a = (*(const int*)(&x)); + int exponent = (127 + 31) - ((a >> 23) & 0xFF); + int r = (((u32)(a) << 8) | (1U << 31)) >> exponent; + exponent += 31 - 127; { - int imask = (!(((( (1<<(exponent)))-1)>>8)&a)); - exponent -= (31-127)+32; - exponent >>= 31; - a = ~((a-1)>>31); /* change sign */ - r -= (imask&a); - r &= exponent; - r ^= a; - r = -r; /* change sign */ + int imask = (!(((((1 << (exponent))) - 1) >> 8)&a)); + exponent -= (31 - 127) + 32; + exponent >>= 31; + a = ~((a - 1) >> 31); /* change sign */ + r -= (imask&a); + r &= exponent; + r ^= a; + r = -r; /* change sign */ } - return r; /* r = (int)(ceil(f)) */ + return r; /* r = (int)(ceil(f)) */ } // Validity checks -IC bool fis_gremlin ( const float &f ) +IC bool fis_gremlin(const float& f) { - u8 value = u8(((*(int*)&f & 0x7f800000)>>23)-0x20); - return value > 0xc0; + u8 value = u8(((*(int*)&f & 0x7f800000) >> 23) - 0x20); + return value > 0xc0; } -IC bool fis_denormal ( const float &f ) +IC bool fis_denormal(const float& f) { - return !(*(int*)&f & 0x7f800000); + return !(*(int*)&f & 0x7f800000); } // Approximated calculations -IC float apx_InvSqrt( const float& n ) +IC float apx_InvSqrt(const float& n) { - long tmp = (long(0xBE800000) - *(long*)&n) >> 1; - float y = *(float*)&tmp; + long tmp = (long(0xBE800000) - *(long*)&n) >> 1; + float y = *(float*)&tmp; return y * (1.47f - 0.47f * n * y * y); } -// Only for [0..1] (positive) range -IC float apx_asin (const float x) +// Only for [0..1] (positive) range +IC float apx_asin(const float x) { - const float c1 = 0.892399f; - const float c3 = 1.693204f; - const float c5 =-3.853735f; - const float c7 = 2.838933f; - - const float x2 = x * x; - const float d = x * (c1 + x2 * (c3 + x2 * (c5 + x2 * c7))); - - return d; + const float c1 = 0.892399f; + const float c3 = 1.693204f; + const float c5 = -3.853735f; + const float c7 = 2.838933f; + + const float x2 = x * x; + const float d = x * (c1 + x2 * (c3 + x2 * (c5 + x2 * c7))); + + return d; } -// Only for [0..1] (positive) range -IC float apx_acos (const float x) +// Only for [0..1] (positive) range +IC float apx_acos(const float x) { - return PI_DIV_2 - apx_asin(x); + return PI_DIV_2 - apx_asin(x); } #endif \ No newline at end of file diff --git a/src/xrCore/_color.h b/src/xrCore/_color.h index 1634fbd08f3..542df86ae16 100644 --- a/src/xrCore/_color.h +++ b/src/xrCore/_color.h @@ -2,243 +2,257 @@ #define __C__ // maps unsigned 8 bits/channel to D3DCOLOR -ICF u32 color_argb (u32 a, u32 r, u32 g, u32 b) { return ((a&0xff)<<24)|((r&0xff)<<16)|((g&0xff)<<8)|(b&0xff); } -ICF u32 color_rgba (u32 r, u32 g, u32 b, u32 a) { return color_argb(a,r,g,b); } -ICF u32 color_argb_f(f32 a, f32 r, f32 g, f32 b) +ICF u32 color_argb(u32 a, u32 r, u32 g, u32 b) { return ((a & 0xff) << 24) | ((r & 0xff) << 16) | ((g & 0xff) << 8) | (b & 0xff); } +ICF u32 color_rgba(u32 r, u32 g, u32 b, u32 a) { return color_argb(a, r, g, b); } +ICF u32 color_argb_f(f32 a, f32 r, f32 g, f32 b) { - s32 _r = clampr(iFloor(r*255.f),0,255); - s32 _g = clampr(iFloor(g*255.f),0,255); - s32 _b = clampr(iFloor(b*255.f),0,255); - s32 _a = clampr(iFloor(a*255.f),0,255); - return color_argb(_a,_r,_g,_b); + s32 _r = clampr(iFloor(r*255.f), 0, 255); + s32 _g = clampr(iFloor(g*255.f), 0, 255); + s32 _b = clampr(iFloor(b*255.f), 0, 255); + s32 _a = clampr(iFloor(a*255.f), 0, 255); + return color_argb(_a, _r, _g, _b); } -ICF u32 color_rgba_f(f32 r, f32 g, f32 b, f32 a) { return color_argb_f(a,r,g,b); } -ICF u32 color_xrgb (u32 r, u32 g, u32 b) { return color_argb(0xff,r,g,b); } -ICF u32 color_get_R (u32 rgba) { return (((rgba) >> 16) & 0xff); } -ICF u32 color_get_G (u32 rgba) { return (((rgba) >> 8) & 0xff); } -ICF u32 color_get_B (u32 rgba) { return ((rgba) & 0xff); } -ICF u32 color_get_A (u32 rgba) { return ((rgba) >> 24); } -ICF u32 subst_alpha (u32 rgba, u32 a) { return rgba&~color_rgba(0,0,0,0xff)|color_rgba(0,0,0,a);} -ICF u32 bgr2rgb (u32 bgr) { return color_rgba(color_get_B(bgr),color_get_G(bgr),color_get_R(bgr),0);} -ICF u32 rgb2bgr (u32 rgb) { return bgr2rgb(rgb);} +ICF u32 color_rgba_f(f32 r, f32 g, f32 b, f32 a) { return color_argb_f(a, r, g, b); } +ICF u32 color_xrgb(u32 r, u32 g, u32 b) { return color_argb(0xff, r, g, b); } +ICF u32 color_get_R(u32 rgba) { return (((rgba) >> 16) & 0xff); } +ICF u32 color_get_G(u32 rgba) { return (((rgba) >> 8) & 0xff); } +ICF u32 color_get_B(u32 rgba) { return ((rgba)& 0xff); } +ICF u32 color_get_A(u32 rgba) { return ((rgba) >> 24); } +ICF u32 subst_alpha(u32 rgba, u32 a) { return rgba&~color_rgba(0, 0, 0, 0xff) | color_rgba(0, 0, 0, a); } +ICF u32 bgr2rgb(u32 bgr) { return color_rgba(color_get_B(bgr), color_get_G(bgr), color_get_R(bgr), 0); } +ICF u32 rgb2bgr(u32 rgb) { return bgr2rgb(rgb); } template -struct _color { +struct _color +{ public: - typedef _color Self; - typedef Self& SelfRef; - typedef const Self& SelfCRef; + typedef _color Self; + typedef Self& SelfRef; + typedef const Self& SelfCRef; public: - T r,g,b,a; + T r, g, b, a; + + ICF SelfRef set(u32 dw) + { + const T f = T(1.0) / T(255.0); + a = f * T((dw >> 24) & 0xff); + r = f * T((dw >> 16) & 0xff); + g = f * T((dw >> 8) & 0xff); + b = f * T((dw >> 0) & 0xff); + return *this; + }; + IC SelfRef set(T _r, T _g, T _b, T _a) + { + r = _r; + g = _g; + b = _b; + a = _a; + return *this; + }; + IC SelfRef set(SelfCRef dw) + { + r = dw.r; + g = dw.g; + b = dw.b; + a = dw.a; + return *this; + }; + ICF u32 get() const { return color_rgba_f(r, g, b, a); } + IC u32 get_windows() const + { + BYTE _a, _r, _g, _b; + _a = (BYTE)(a*255.f); + _r = (BYTE)(r*255.f); + _g = (BYTE)(g*255.f); + _b = (BYTE)(b*255.f); + return ((u32)(_a << 24) | (_b << 16) | (_g << 8) | (_r)); + }; + IC SelfRef set_windows(u32 dw) + { + const T f = 1.0f / 255.0f; + a = f * (T)(BYTE)(dw >> 24); + b = f * (T)(BYTE)(dw >> 16); + g = f * (T)(BYTE)(dw >> 8); + r = f * (T)(BYTE)(dw >> 0); + return *this; + }; + IC SelfRef adjust_contrast(T f) // >1 - contrast will be increased + { + r = 0.5f + f * (r - 0.5f); + g = 0.5f + f * (g - 0.5f); + b = 0.5f + f * (b - 0.5f); + return *this; + }; + IC SelfRef adjust_contrast(SelfCRef in, T f) // >1 - contrast will be increased + { + r = 0.5f + f * (in.r - 0.5f); + g = 0.5f + f * (in.g - 0.5f); + b = 0.5f + f * (in.b - 0.5f); + return *this; + }; + IC SelfRef adjust_saturation(T s) + { + // Approximate values for each component's contribution to luminance. + // Based upon the NTSC standard described in ITU-R Recommendation BT.709. + T grey = r * 0.2125f + g * 0.7154f + b * 0.0721f; - ICF SelfRef set (u32 dw) - { - const T f = T(1.0) / T(255.0); - a = f * T((dw >> 24)& 0xff); - r = f * T((dw >> 16)& 0xff); - g = f * T((dw >> 8)& 0xff); - b = f * T((dw >> 0)& 0xff); - return *this; - }; - IC SelfRef set (T _r, T _g, T _b, T _a) - { - r = _r; g = _g; b = _b; a = _a; - return *this; - }; - IC SelfRef set (SelfCRef dw) - { - r=dw.r; g=dw.g; b=dw.b; a = dw.a; - return *this; - }; - ICF u32 get( ) const { return color_rgba_f(r,g,b,a); } - IC u32 get_windows ( ) const - { - BYTE _a, _r, _g, _b; - _a = (BYTE)(a*255.f); - _r = (BYTE)(r*255.f); - _g = (BYTE)(g*255.f); - _b = (BYTE)(b*255.f); - return ((u32)(_a<<24) | (_b<<16) | (_g<<8) | (_r)); - }; - IC SelfRef set_windows(u32 dw) - { - const T f = 1.0f / 255.0f; - a = f * (T) (BYTE) (dw >> 24); - b = f * (T) (BYTE) (dw >> 16); - g = f * (T) (BYTE) (dw >> 8); - r = f * (T) (BYTE) (dw >> 0); - return *this; - }; - IC SelfRef adjust_contrast(T f) // >1 - contrast will be increased - { - r = 0.5f + f * (r - 0.5f); - g = 0.5f + f * (g - 0.5f); - b = 0.5f + f * (b - 0.5f); - return *this; - }; - IC SelfRef adjust_contrast(SelfCRef in, T f) // >1 - contrast will be increased - { - r = 0.5f + f * (in.r - 0.5f); - g = 0.5f + f * (in.g - 0.5f); - b = 0.5f + f * (in.b - 0.5f); - return *this; - }; - IC SelfRef adjust_saturation(T s) - { - // Approximate values for each component's contribution to luminance. - // Based upon the NTSC standard described in ITU-R Recommendation BT.709. - T grey = r * 0.2125f + g * 0.7154f + b * 0.0721f; + r = grey + s * (r - grey); + g = grey + s * (g - grey); + b = grey + s * (b - grey); + return *this; + }; + IC SelfRef adjust_saturation(SelfCRef in, T s) + { + // Approximate values for each component's contribution to luminance. + // Based upon the NTSC standard described in ITU-R Recommendation BT.709. + T grey = in.r * 0.2125f + in.g * 0.7154f + in.b * 0.0721f; - r = grey + s * (r - grey); - g = grey + s * (g - grey); - b = grey + s * (b - grey); - return *this; - }; - IC SelfRef adjust_saturation(SelfCRef in, T s) - { - // Approximate values for each component's contribution to luminance. - // Based upon the NTSC standard described in ITU-R Recommendation BT.709. - T grey = in.r * 0.2125f + in.g * 0.7154f + in.b * 0.0721f; + r = grey + s * (in.r - grey); + g = grey + s * (in.g - grey); + b = grey + s * (in.b - grey); + return *this; + }; + IC SelfRef modulate(_color& in) + { + r *= in.r; + g *= in.g; + b *= in.b; + a *= in.a; + return *this; + }; + IC SelfRef modulate(SelfCRef in1, SelfCRef in2) + { + r = in1.r*in2.r; + g = in1.g*in2.g; + b = in1.b*in2.b; + a = in1.a*in2.a; + return *this; + }; + IC SelfRef negative(SelfCRef in) + { + r = 1.0f - in.r; + g = 1.0f - in.g; + b = 1.0f - in.b; + a = 1.0f - in.a; + return *this; + }; + IC SelfRef negative(void) + { + r = 1.0f - r; + g = 1.0f - g; + b = 1.0f - b; + a = 1.0f - a; + return *this; + }; + IC SelfRef sub_rgb(T s) + { + r -= s; + g -= s; + b -= s; + // a=1.0f-a; + return *this; + }; + IC SelfRef add_rgb(T s) + { + r += s; + g += s; + b += s; + return *this; + }; + IC SelfRef add_rgba(T s) + { + r += s; + g += s; + b += s; + a += s; + return *this; + }; + IC SelfRef mul_rgba(T s) + { + r *= s; + g *= s; + b *= s; + a *= s; + return *this; + }; + IC SelfRef mul_rgb(T s) + { + r *= s; + g *= s; + b *= s; + return *this; + }; + IC SelfRef mul_rgba(SelfCRef c, T s) + { + r = c.r*s; + g = c.g*s; + b = c.b*s; + a = c.a*s; + return *this; + }; + IC SelfRef mul_rgb(SelfCRef c, T s) + { + r = c.r*s; + g = c.g*s; + b = c.b*s; + return *this; + }; - r = grey + s * (in.r - grey); - g = grey + s * (in.g - grey); - b = grey + s * (in.b - grey); - return *this; - }; - IC SelfRef modulate(_color &in) - { - r*=in.r; - g*=in.g; - b*=in.b; - a*=in.a; - return *this; - }; - IC SelfRef modulate(SelfCRef in1, SelfCRef in2) - { - r=in1.r*in2.r; - g=in1.g*in2.g; - b=in1.b*in2.b; - a=in1.a*in2.a; - return *this; - }; - IC SelfRef negative(SelfCRef in) - { - r=1.0f-in.r; - g=1.0f-in.g; - b=1.0f-in.b; - a=1.0f-in.a; - return *this; - }; - IC SelfRef negative(void) - { - r=1.0f-r; - g=1.0f-g; - b=1.0f-b; - a=1.0f-a; - return *this; - }; - IC SelfRef sub_rgb(T s) - { - r-=s; - g-=s; - b-=s; -// a=1.0f-a; - return *this; - }; - IC SelfRef add_rgb(T s) - { - r+=s; - g+=s; - b+=s; - return *this; - }; - IC SelfRef add_rgba(T s) - { - r+=s; - g+=s; - b+=s; - a+=s; - return *this; - }; - IC SelfRef mul_rgba(T s) - { - r*=s; - g*=s; - b*=s; - a*=s; - return *this; - }; - IC SelfRef mul_rgb(T s) - { - r*=s; - g*=s; - b*=s; - return *this; - }; - IC SelfRef mul_rgba(SelfCRef c, T s) - { - r=c.r*s; - g=c.g*s; - b=c.b*s; - a=c.a*s; - return *this; - }; - IC SelfRef mul_rgb(SelfCRef c, T s) - { - r=c.r*s; - g=c.g*s; - b=c.b*s; - return *this; - }; - - // SQ magnitude - IC T magnitude_sqr_rgb(void) const { - return r*r + g*g + b*b; - } - // magnitude - IC T magnitude_rgb (void) const { - return _sqrt(magnitude_sqr_rgb()); - } - IC T intensity (void) const { - return (r + g + b)/3.f; - } + // SQ magnitude + IC T magnitude_sqr_rgb(void) const + { + return r*r + g*g + b*b; + } + // magnitude + IC T magnitude_rgb(void) const + { + return _sqrt(magnitude_sqr_rgb()); + } + IC T intensity(void) const + { + return (r + g + b) / 3.f; + } - // Normalize - IC SelfRef normalize_rgb(void) { - VERIFY(magnitude_sqr_rgb()>EPS_S); - return mul_rgb(1.f/magnitude_rgb()); - } - IC SelfRef normalize_rgb(SelfCRef c) - { - VERIFY(c.magnitude_sqr_rgb()>EPS_S); - return mul_rgb(c,1.f/c.magnitude_rgb()); - } - IC SelfRef lerp(SelfCRef c1, SelfCRef c2, T t) - { - T invt = 1.f-t; - r = c1.r*invt + c2.r*t; - g = c1.g*invt + c2.g*t; - b = c1.b*invt + c2.b*t; - a = c1.a*invt + c2.a*t; - return *this; - } - IC SelfRef lerp(SelfCRef c1, SelfCRef c2, SelfCRef c3, T t) - { - if (t>.5f){ - return lerp(c2,c3,t*2.f-1.f); - }else{ - return lerp(c1,c2,t*2.f); - } - } - IC BOOL similar_rgba(SelfCRef v, T E=EPS_L) const { return _abs(r-v.r) EPS_S); + return mul_rgb(1.f / magnitude_rgb()); + } + IC SelfRef normalize_rgb(SelfCRef c) + { + VERIFY(c.magnitude_sqr_rgb() > EPS_S); + return mul_rgb(c, 1.f / c.magnitude_rgb()); + } + IC SelfRef lerp(SelfCRef c1, SelfCRef c2, T t) + { + T invt = 1.f - t; + r = c1.r*invt + c2.r*t; + g = c1.g*invt + c2.g*t; + b = c1.b*invt + c2.b*t; + a = c1.a*invt + c2.a*t; + return *this; + } + IC SelfRef lerp(SelfCRef c1, SelfCRef c2, SelfCRef c3, T t) + { + if (t > .5f) + { + return lerp(c2, c3, t*2.f - 1.f); + } + else + { + return lerp(c1, c2, t*2.f); + } + } + IC BOOL similar_rgba(SelfCRef v, T E = EPS_L) const { return _abs(r - v.r) < E && _abs(g - v.g) < E && _abs(b - v.b) < E && _abs(a - v.a) < E; }; + IC BOOL similar_rgb(SelfCRef v, T E = EPS_L) const { return _abs(r - v.r) < E && _abs(g - v.g) < E && _abs(b - v.b) < E; }; }; -typedef _color Fcolor; -typedef _color Dcolor; +typedef _color Fcolor; +typedef _color Dcolor; template -BOOL _valid (const _color& c) { return _valid(c.r) && _valid(c.g) && _valid(c.b) && _valid(c.a); } +BOOL _valid(const _color& c) { return _valid(c.r) && _valid(c.g) && _valid(c.b) && _valid(c.a); } #endif diff --git a/src/xrCore/_compressed_normal.cpp b/src/xrCore/_compressed_normal.cpp index 36152b16433..01f75f4b9cb 100644 --- a/src/xrCore/_compressed_normal.cpp +++ b/src/xrCore/_compressed_normal.cpp @@ -2,124 +2,124 @@ #pragma hdrstop // upper 3 bits -#define pvSIGN_MASK 0xe000 -#define pvXSIGN_MASK 0x8000 -#define pvYSIGN_MASK 0x4000 -#define pvZSIGN_MASK 0x2000 +#define pvSIGN_MASK 0xe000 +#define pvXSIGN_MASK 0x8000 +#define pvYSIGN_MASK 0x4000 +#define pvZSIGN_MASK 0x2000 // middle 6 bits - xbits -#define pvTOP_MASK 0x1f80 +#define pvTOP_MASK 0x1f80 // lower 7 bits - ybits -#define pvBOTTOM_MASK 0x007f +#define pvBOTTOM_MASK 0x007f // static lookup table for unit vector3 decompression -float pvUVAdjustment [0x2000]; +float pvUVAdjustment[0x2000]; -void pvInitializeStatics (void) +void pvInitializeStatics(void) { - for ( int idx = 0; idx < 0x2000; idx++ ) - { - long xbits = idx >> 7; - long ybits = idx & pvBOTTOM_MASK; - - // map the numbers back to the triangle (0,0)-(0,127)-(127,0) - if (( xbits + ybits ) >= 127 ) - { - xbits = 127 - xbits; - ybits = 127 - ybits; - } - - // convert to 3D vectors - float x = float(xbits); - float y = float(ybits); - float z = float(126 - xbits - ybits ); - - // calculate the amount of normalization required - pvUVAdjustment[idx] = 1.0f / _sqrt( y*y + z*z + x*x ); - } + for (int idx = 0; idx < 0x2000; idx++) + { + long xbits = idx >> 7; + long ybits = idx & pvBOTTOM_MASK; + + // map the numbers back to the triangle (0,0)-(0,127)-(127,0) + if ((xbits + ybits) >= 127) + { + xbits = 127 - xbits; + ybits = 127 - ybits; + } + + // convert to 3D vectors + float x = float(xbits); + float y = float(ybits); + float z = float(126 - xbits - ybits); + + // calculate the amount of normalization required + pvUVAdjustment[idx] = 1.0f / _sqrt(y*y + z*z + x*x); + } } -u16 pvCompress ( const Fvector& vec ) +u16 pvCompress(const Fvector& vec) { - // save copy - Fvector tmp = vec; - - // input vector3 does not have to be unit length - u16 mVec = 0; - - if ( negative(tmp.x) ) { mVec |= pvXSIGN_MASK; set_positive(tmp.x); } - if ( negative(tmp.y) ) { mVec |= pvYSIGN_MASK; set_positive(tmp.y); } - if ( negative(tmp.z) ) { mVec |= pvZSIGN_MASK; set_positive(tmp.z); } - - // project the normal onto the plane that goes through - // X0=(1,0,0),Y0=(0,1,0),Z0=(0,0,1). - - // on that plane we choose an (projective!) coordinate system - // such that X0->(0,0), Y0->(126,0), Z0->(0,126),(0,0,0)->Infinity - - // a little slower... old pack was 4 multiplies and 2 adds. - // This is 2 multiplies, 2 adds, and a divide.... - float w = 126.0f / ( tmp.x + tmp.y + tmp.z ); - int xbits = iFloor( tmp.x * w ); - int ybits = iFloor( tmp.y * w ); - - /* - VERIFY( xbits < 127 ); - VERIFY( xbits >= 0 ); - VERIFY( ybits < 127 ); - VERIFY( ybits >= 0 ); - */ - - // Now we can be sure that 0<=xp<=126, 0<=yp<=126, 0<=xp+yp<=126 - - // however for the sampling we want to transform this triangle - // into a rectangle. - if ( xbits >= 64 ) - { - xbits = 127 - xbits; - ybits = 127 - ybits; - } - - // now we that have xp in the range (0,127) and yp in the range (0,63), - // we can pack all the bits together - mVec |= ( xbits << 7 ); - mVec |= ybits; - - return mVec; + // save copy + Fvector tmp = vec; + + // input vector3 does not have to be unit length + u16 mVec = 0; + + if (negative(tmp.x)) { mVec |= pvXSIGN_MASK; set_positive(tmp.x); } + if (negative(tmp.y)) { mVec |= pvYSIGN_MASK; set_positive(tmp.y); } + if (negative(tmp.z)) { mVec |= pvZSIGN_MASK; set_positive(tmp.z); } + + // project the normal onto the plane that goes through + // X0=(1,0,0),Y0=(0,1,0),Z0=(0,0,1). + + // on that plane we choose an (projective!) coordinate system + // such that X0->(0,0), Y0->(126,0), Z0->(0,126),(0,0,0)->Infinity + + // a little slower... old pack was 4 multiplies and 2 adds. + // This is 2 multiplies, 2 adds, and a divide.... + float w = 126.0f / (tmp.x + tmp.y + tmp.z); + int xbits = iFloor(tmp.x * w); + int ybits = iFloor(tmp.y * w); + + /* + VERIFY( xbits < 127 ); + VERIFY( xbits >= 0 ); + VERIFY( ybits < 127 ); + VERIFY( ybits >= 0 ); + */ + + // Now we can be sure that 0<=xp<=126, 0<=yp<=126, 0<=xp+yp<=126 + + // however for the sampling we want to transform this triangle + // into a rectangle. + if (xbits >= 64) + { + xbits = 127 - xbits; + ybits = 127 - ybits; + } + + // now we that have xp in the range (0,127) and yp in the range (0,63), + // we can pack all the bits together + mVec |= (xbits << 7); + mVec |= ybits; + + return mVec; } -void pvDecompress ( Fvector& vec, u16 mVec ) +void pvDecompress(Fvector& vec, u16 mVec) { - // if we do a straightforward backward transform - // we will get points on the plane X0,Y0,Z0 - // however we need points on a sphere that goes through these points. - // therefore we need to adjust x,y,z so that x^2+y^2+z^2=1 - - // by normalizing the vector3. We have already precalculated the amount - // by which we need to scale, so all we do is a table lookup and a - // multiplication - - // get the x and y bits - int xbits = (( mVec & pvTOP_MASK ) >> 7 ); - int ybits = ( mVec & pvBOTTOM_MASK ); - - // map the numbers back to the triangle (0,0)-(0,126)-(126,0) - if (( xbits + ybits ) >= 127 ) - { - xbits = 127 - xbits; - ybits = 127 - ybits; - } - - // do the inverse transform and normalization - // costs 3 extra multiplies and 2 subtracts. No big deal. - float uvadj = pvUVAdjustment[mVec & ~pvSIGN_MASK]; - vec.x = uvadj * float(xbits); - vec.y = uvadj * float(ybits); - vec.z = uvadj * float( 126 - xbits - ybits ); - - // set all the sign bits - if ( mVec & pvXSIGN_MASK ) set_negative(vec.x); - if ( mVec & pvYSIGN_MASK ) set_negative(vec.y); - if ( mVec & pvZSIGN_MASK ) set_negative(vec.z); + // if we do a straightforward backward transform + // we will get points on the plane X0,Y0,Z0 + // however we need points on a sphere that goes through these points. + // therefore we need to adjust x,y,z so that x^2+y^2+z^2=1 + + // by normalizing the vector3. We have already precalculated the amount + // by which we need to scale, so all we do is a table lookup and a + // multiplication + + // get the x and y bits + int xbits = ((mVec & pvTOP_MASK) >> 7); + int ybits = (mVec & pvBOTTOM_MASK); + + // map the numbers back to the triangle (0,0)-(0,126)-(126,0) + if ((xbits + ybits) >= 127) + { + xbits = 127 - xbits; + ybits = 127 - ybits; + } + + // do the inverse transform and normalization + // costs 3 extra multiplies and 2 subtracts. No big deal. + float uvadj = pvUVAdjustment[mVec & ~pvSIGN_MASK]; + vec.x = uvadj * float(xbits); + vec.y = uvadj * float(ybits); + vec.z = uvadj * float(126 - xbits - ybits); + + // set all the sign bits + if (mVec & pvXSIGN_MASK) set_negative(vec.x); + if (mVec & pvYSIGN_MASK) set_negative(vec.y); + if (mVec & pvZSIGN_MASK) set_negative(vec.z); } diff --git a/src/xrCore/_compressed_normal.h b/src/xrCore/_compressed_normal.h index 14c91097caa..855d507dcd9 100644 --- a/src/xrCore/_compressed_normal.h +++ b/src/xrCore/_compressed_normal.h @@ -8,8 +8,8 @@ // a compressed unit vector3. reasonable fidelty for unit vectors in a 16 bit // package. Good enough for surface normals we hope. -XRCORE_API u16 pvCompress ( const Fvector& vec ); -XRCORE_API void pvDecompress ( Fvector& vec, u16 mVec ); -XRCORE_API void pvInitializeStatics ( void ); +XRCORE_API u16 pvCompress(const Fvector& vec); +XRCORE_API void pvDecompress(Fvector& vec, u16 mVec); +XRCORE_API void pvInitializeStatics(void); #endif \ No newline at end of file diff --git a/src/xrCore/_cylinder.h b/src/xrCore/_cylinder.h index 16a2ba8d5e6..d2f2610603e 100644 --- a/src/xrCore/_cylinder.h +++ b/src/xrCore/_cylinder.h @@ -5,63 +5,71 @@ template class _cylinder { public: - typedef T TYPE; - typedef _cylinderSelf; - typedef Self& SelfRef; - typedef const Self& SelfCRef; + typedef T TYPE; + typedef _cylinderSelf; + typedef Self& SelfRef; + typedef const Self& SelfCRef; public: - _vector3 m_center; - _vector3 m_direction; - T m_height; - T m_radius; + _vector3 m_center; + _vector3 m_direction; + T m_height; + T m_radius; public: - IC SelfRef invalidate () { m_center.set(0,0,0); m_direction.set(0,0,0); m_height=0; m_radius=0; return *this; } - enum ecode { cyl_cap, cyl_wall, cyl_none }; - IC int intersect (const _vector3& start, const _vector3& dir, T afT[2], ecode code[2] ) const + IC SelfRef invalidate() { m_center.set(0, 0, 0); m_direction.set(0, 0, 0); m_height = 0; m_radius = 0; return *this; } + enum ecode { cyl_cap, cyl_wall, cyl_none }; + IC int intersect(const _vector3& start, const _vector3& dir, T afT[2], ecode code[2]) const { T fEpsilon = 1e-12f; // set up quadratic Q(t) = a*t^2 + 2*b*t + c _vector3 kU, kV, kW = m_direction; - _vector3::generate_orthonormal_basis(kW,kU,kV); - _vector3 kD; kD.set(kU.dotproduct(dir),kV.dotproduct(dir),kW.dotproduct(dir)); + _vector3::generate_orthonormal_basis(kW, kU, kV); + _vector3 kD; + kD.set(kU.dotproduct(dir), kV.dotproduct(dir), kW.dotproduct(dir)); #ifdef DEBUG - if(kD.square_magnitude() <= std::numeric_limits::min()) - { - Msg("dir :%f,%f,%f",dir.x,dir.y,dir.z); - Msg("kU :%f,%f,%f",kU.x,kU.y,kU.z); - Msg("kV :%f,%f,%f",kV.x,kV.y,kV.z); - Msg("kW :%f,%f,%f",kW.x,kW.y,kW.z); - VERIFY2(0,"KD is zero"); - } + if (kD.square_magnitude() <= std::numeric_limits::min()) + { + Msg("dir :%f,%f,%f", dir.x, dir.y, dir.z); + Msg("kU :%f,%f,%f", kU.x, kU.y, kU.z); + Msg("kV :%f,%f,%f", kV.x, kV.y, kV.z); + Msg("kW :%f,%f,%f", kW.x, kW.y, kW.z); + VERIFY2(0, "KD is zero"); + } #endif T fDLength = kD.normalize_magn(); - T fInvDLength = 1.0f/fDLength; - _vector3 kDiff; kDiff.sub(start,m_center); - _vector3 kP; kP.set(kU.dotproduct(kDiff),kV.dotproduct(kDiff),kW.dotproduct(kDiff)); + T fInvDLength = 1.0f / fDLength; + _vector3 kDiff; + kDiff.sub(start, m_center); + _vector3 kP; + kP.set(kU.dotproduct(kDiff), kV.dotproduct(kDiff), kW.dotproduct(kDiff)); T fHalfHeight = 0.5f*m_height; T fRadiusSqr = m_radius*m_radius; T fInv, fA, fB, fC, fDiscr, fRoot, fT, fT0, fT1, fTmp0, fTmp1; - if ( _abs(kD.z) >= 1.0f - fEpsilon ){ + if (_abs(kD.z) >= 1.0f - fEpsilon) + { // line is parallel to cylinder axis - if ( kP.x*kP.x+kP.y*kP.y <= fRadiusSqr ){ - fTmp0 = fInvDLength/kD.z; + if (kP.x*kP.x + kP.y*kP.y <= fRadiusSqr) + { + fTmp0 = fInvDLength / kD.z; afT[0] = (+fHalfHeight - kP.z)*fTmp0; afT[1] = (-fHalfHeight - kP.z)*fTmp0; - code[0] = cyl_cap; - code[1] = cyl_cap; + code[0] = cyl_cap; + code[1] = cyl_cap; return 2; } - else{ + else + { return 0; } } - if ( _abs(kD.z) <= fEpsilon ){ + if (_abs(kD.z) <= fEpsilon) + { // line is perpendicular to axis of cylinder - if ( _abs(kP.z) > fHalfHeight ){ + if (_abs(kP.z) > fHalfHeight) + { // line is outside the planar caps of cylinder return 0; } @@ -70,54 +78,59 @@ class _cylinder fB = kP.x*kD.x + kP.y*kD.y; fC = kP.x*kP.x + kP.y*kP.y - fRadiusSqr; fDiscr = fB*fB - fA*fC; - if ( fDiscr < 0.0f ){ + if (fDiscr < 0.0f) + { // line does not intersect cylinder wall return 0; } - else if ( fDiscr > 0.0f ){ + else if (fDiscr > 0.0f) + { fRoot = _sqrt(fDiscr); - fTmp0 = fInvDLength/fA; + fTmp0 = fInvDLength / fA; afT[0] = (-fB - fRoot)*fTmp0; afT[1] = (-fB + fRoot)*fTmp0; - code[0] = cyl_wall; - code[1] = cyl_wall; - return 2; //wall - }else{ - afT[0] = -fB*fInvDLength/fA; - code[0] = cyl_wall; + code[0] = cyl_wall; + code[1] = cyl_wall; + return 2; //wall + } + else + { + afT[0] = -fB*fInvDLength / fA; + code[0] = cyl_wall; return 1; //wall } } // test plane intersections first int iQuantity = 0; - fInv = 1.0f/kD.z; + fInv = 1.0f / kD.z; fT0 = (+fHalfHeight - kP.z)*fInv; fTmp0 = kP.x + fT0*kD.x; fTmp1 = kP.y + fT0*kD.y; - if ( fTmp0*fTmp0 + fTmp1*fTmp1 <= fRadiusSqr ) - { - code[iQuantity] = cyl_cap; - afT[iQuantity++]= fT0*fInvDLength; - - } + if (fTmp0*fTmp0 + fTmp1*fTmp1 <= fRadiusSqr) + { + code[iQuantity] = cyl_cap; + afT[iQuantity++] = fT0*fInvDLength; + + } fT1 = (-fHalfHeight - kP.z)*fInv; fTmp0 = kP.x + fT1*kD.x; fTmp1 = kP.y + fT1*kD.y; - if ( fTmp0*fTmp0 + fTmp1*fTmp1 <= fRadiusSqr ) - { - code[iQuantity] = cyl_cap; - afT[iQuantity++] = fT1*fInvDLength; - } + if (fTmp0*fTmp0 + fTmp1*fTmp1 <= fRadiusSqr) + { + code[iQuantity] = cyl_cap; + afT[iQuantity++] = fT1*fInvDLength; + } - if ( iQuantity == 2 ){ + if (iQuantity == 2) + { // line intersects both top and bottom return 2;//both caps } // If iQuantity == 1, then line must intersect cylinder wall - // somewhere between caps in a single point. This case is detected + // somewhere between caps in a single point. This case is detected // in the following code that tests for intersection between line and // cylinder wall. @@ -125,99 +138,119 @@ class _cylinder fB = kP.x*kD.x + kP.y*kD.y; fC = kP.x*kP.x + kP.y*kP.y - fRadiusSqr; fDiscr = fB*fB - fA*fC; - if ( fDiscr < 0.0f ){ + if (fDiscr < 0.0f) + { // line does not intersect cylinder wall //VERIFY( iQuantity == 0 ); return 0; - }else if ( fDiscr > 0.0f ){ + } + else if (fDiscr > 0.0f) + { fRoot = _sqrt(fDiscr); - fInv = 1.0f/fA; + fInv = 1.0f / fA; fT = (-fB - fRoot)*fInv; - if ( fT0 <= fT1 ){ - if ( fT0 <= fT && fT <= fT1 ) - { - code[iQuantity] = cyl_wall; - afT[iQuantity++] = fT*fInvDLength; - - } - }else{ - if ( fT1 <= fT && fT <= fT0 ) - { - code[iQuantity] = cyl_wall; - afT[iQuantity++] = fT*fInvDLength; - - } + if (fT0 <= fT1) + { + if (fT0 <= fT && fT <= fT1) + { + code[iQuantity] = cyl_wall; + afT[iQuantity++] = fT*fInvDLength; + + } + } + else + { + if (fT1 <= fT && fT <= fT0) + { + code[iQuantity] = cyl_wall; + afT[iQuantity++] = fT*fInvDLength; + + } } - if ( iQuantity == 2 ){ + if (iQuantity == 2) + { // Line intersects one of top/bottom of cylinder and once on // cylinder wall. return 2; } fT = (-fB + fRoot)*fInv; - if ( fT0 <= fT1 ){ - if ( fT0 <= fT && fT <= fT1 ) - { - code[iQuantity] = cyl_wall; - afT[iQuantity++] = fT*fInvDLength; - } - }else{ - if ( fT1 <= fT && fT <= fT0 ) - { - code[iQuantity] = cyl_wall; - afT[iQuantity++] = fT*fInvDLength; - } + if (fT0 <= fT1) + { + if (fT0 <= fT && fT <= fT1) + { + code[iQuantity] = cyl_wall; + afT[iQuantity++] = fT*fInvDLength; + } + } + else + { + if (fT1 <= fT && fT <= fT0) + { + code[iQuantity] = cyl_wall; + afT[iQuantity++] = fT*fInvDLength; + } + } + } + else + { + fT = -fB / fA; + if (fT0 <= fT1) + { + if (fT0 <= fT && fT <= fT1) + { + code[iQuantity] = cyl_wall; + afT[iQuantity++] = fT*fInvDLength; + } } - }else{ - fT = -fB/fA; - if ( fT0 <= fT1 ){ - if ( fT0 <= fT && fT <= fT1 ) - { - code[iQuantity] = cyl_wall; - afT[iQuantity++] = fT*fInvDLength; - } - }else{ - if ( fT1 <= fT && fT <= fT0 ) - { - code[iQuantity] = cyl_wall; + else + { + if (fT1 <= fT && fT <= fT0) + { + code[iQuantity] = cyl_wall; afT[iQuantity++] = fT*fInvDLength; - } + } } } return iQuantity; } - enum ERP_Result{ - rpNone = 0, - rpOriginInside = 1, - rpOriginOutside = 2, - fcv_forcedword = u32(-1) - }; - IC ERP_Result intersect (const _vector3& start, const _vector3& dir, T& dist) const + enum ERP_Result + { + rpNone = 0, + rpOriginInside = 1, + rpOriginOutside = 2, + fcv_forcedword = u32(-1) + }; + IC ERP_Result intersect(const _vector3& start, const _vector3& dir, T& dist) const { - T afT[2]; - ecode code[2]; + T afT[2]; + ecode code[2]; int cnt; - if (0!=(cnt=intersect(start,dir,afT,code))){ - bool o_inside = false; - bool b_result = false; - for (int k=0; k Fcylinder; -typedef _cylinder Dcylinder; +typedef _cylinder Fcylinder; +typedef _cylinder Dcylinder; template -BOOL _valid (const _cylinder& c) { return _valid(c.m_center) && _valid(c.m_direction) && _valid(c.m_height) && _valid(c.m_radius); } +BOOL _valid(const _cylinder& c) { return _valid(c.m_center) && _valid(c.m_direction) && _valid(c.m_height) && _valid(c.m_radius); } #endif // _DEBUG diff --git a/src/xrCore/_fbox.h b/src/xrCore/_fbox.h index 94d6214f60f..0b7f6afe9f9 100644 --- a/src/xrCore/_fbox.h +++ b/src/xrCore/_fbox.h @@ -5,328 +5,383 @@ template class _box3 { public: - typedef T TYPE; - typedef _box3 Self; - typedef Self& SelfRef; - typedef const Self& SelfCRef; - typedef _vector3 Tvector; - typedef _matrix Tmatrix; + typedef T TYPE; + typedef _box3 Self; + typedef Self& SelfRef; + typedef const Self& SelfCRef; + typedef _vector3 Tvector; + typedef _matrix Tmatrix; public: - union{ - struct{ - Tvector min; - Tvector max; - }; - struct{ - T x1, y1, z1; - T x2, y2, z2; - }; - }; + union + { + struct + { + Tvector min; + Tvector max; + }; + struct + { + T x1, y1, z1; + T x2, y2, z2; + }; + }; + + IC BOOL is_valid() { return (x2 >= x1) && (y2 >= y1) && (z2 >= z1); } + + IC const T* data() const { return &min.x; } + + IC SelfRef set(const Tvector& _min, const Tvector& _max) { min.set(_min); max.set(_max); return *this; }; + IC SelfRef set(T x1, T y1, T z1, T x2, T y2, T z2) { min.set(x1, y1, z1); max.set(x2, y2, z2); return *this; }; + IC SelfRef set(SelfCRef b) { min.set(b.min); max.set(b.max); return *this; }; + IC SelfRef setb(const Tvector& center, const Tvector& dim) { min.sub(center, dim); max.add(center, dim); return *this; } + + IC SelfRef null() { min.set(0, 0, 0); max.set(0, 0, 0); return *this; }; + IC SelfRef identity() { min.set(-0.5, -0.5, -0.5); max.set(0.5, 0.5, 0.5); return *this; }; + IC SelfRef invalidate() { min.set(type_max(T), type_max(T), type_max(T)); max.set(type_min(T), type_min(T), type_min(T)); return *this; } + + IC SelfRef shrink(T s) { min.add(s); max.sub(s); return *this; }; + IC SelfRef shrink(const Tvector& s) { min.add(s); max.sub(s); return *this; }; + IC SelfRef grow(T s) { min.sub(s); max.add(s); return *this; }; + IC SelfRef grow(const Tvector& s) { min.sub(s); max.add(s); return *this; }; + + IC SelfRef add(const Tvector& p) { min.add(p); max.add(p); return *this; }; + IC SelfRef sub(const Tvector& p) { min.sub(p); max.sub(p); return *this; }; + IC SelfRef offset(const Tvector& p) { min.add(p); max.add(p); return *this; }; + IC SelfRef add(SelfCRef b, const Tvector& p) { min.add(b.min, p); max.add(b.max, p); return *this; }; + + ICF BOOL contains(T x, T y, T z) const { return (x >= x1) && (x <= x2) && (y >= y1) && (y <= y2) && (z >= z1) && (z <= z2); }; + ICF BOOL contains(const Tvector& p) const { return contains(p.x, p.y, p.z); }; + ICF BOOL contains(SelfCRef b) const { return contains(b.min) && contains(b.max); }; - IC BOOL is_valid () {return (x2>=x1)&&(y2>=y1)&&(z2>=z1);} + IC BOOL similar(SelfCRef b) const { return min.similar(b.min) && max.similar(b.max); }; - IC const T* data () const { return &min.x; } + ICF SelfRef modify(const Tvector& p) { min.min(p); max.max(p); return *this; } + ICF SelfRef modify(T x, T y, T z) { _vector3 tmp = {x, y, z}; return modify(tmp); } + IC SelfRef merge(SelfCRef b) { modify(b.min); modify(b.max); return *this; }; + IC SelfRef merge(SelfCRef b1, SelfCRef b2) { invalidate(); merge(b1); merge(b2); return *this; } + ICF SelfRef xform(SelfCRef B, const Tmatrix& m) + { + // The three edges transformed: you can efficiently transform an X-only vector3 + // by just getting the "X" column of the matrix + Tvector vx, vy, vz; + vx.mul(m.i, B.max.x - B.min.x); + vy.mul(m.j, B.max.y - B.min.y); + vz.mul(m.k, B.max.z - B.min.z); - IC SelfRef set (const Tvector &_min, const Tvector &_max) { min.set(_min); max.set(_max); return *this; }; - IC SelfRef set (T x1, T y1, T z1, T x2, T y2, T z2) { min.set(x1,y1,z1);max.set(x2,y2,z2); return *this; }; - IC SelfRef set (SelfCRef b) { min.set(b.min); max.set(b.max); return *this; }; - IC SelfRef setb (const Tvector& center, const Tvector& dim) { min.sub(center,dim);max.add(center,dim);return *this; } + // Transform the min point + m.transform_tiny(min, B.min); + max.set(min); - IC SelfRef null () { min.set(0,0,0); max.set(0,0,0); return *this; }; - IC SelfRef identity () { min.set(-0.5,-0.5,-0.5); max.set(0.5,0.5,0.5); return *this; }; - IC SelfRef invalidate () { min.set(type_max(T),type_max(T),type_max(T)); max.set(type_min(T),type_min(T),type_min(T)); return *this; } - - IC SelfRef shrink (T s) { min.add(s); max.sub(s); return *this; }; - IC SelfRef shrink (const Tvector& s) { min.add(s); max.sub(s); return *this; }; - IC SelfRef grow (T s) { min.sub(s); max.add(s); return *this; }; - IC SelfRef grow (const Tvector& s) { min.sub(s); max.add(s); return *this; }; - - IC SelfRef add (const Tvector &p) { min.add(p); max.add(p); return *this; }; - IC SelfRef sub (const Tvector &p) { min.sub(p); max.sub(p); return *this; }; - IC SelfRef offset (const Tvector &p) { min.add(p); max.add(p); return *this; }; - IC SelfRef add (SelfCRef b, const Tvector &p) { min.add(b.min, p); max.add(b.max, p); return *this; }; - - ICF BOOL contains (T x, T y, T z) const { return (x>=x1) && (x<=x2) && (y>=y1) && (y<=y2) && (z>=z1) && (z<=z2); }; - ICF BOOL contains (const Tvector &p) const { return contains(p.x,p.y,p.z); }; - ICF BOOL contains (SelfCRef b) const { return contains(b.min) && contains(b.max); }; - - IC BOOL similar (SelfCRef b) const { return min.similar(b.min) && max.similar(b.max); }; - - ICF SelfRef modify (const Tvector &p) { min.min(p); max.max(p); return *this; } - ICF SelfRef modify (T x, T y, T z) { _vector3 tmp = {x,y,z}; return modify(tmp); } - IC SelfRef merge (SelfCRef b) { modify(b.min); modify(b.max); return *this; }; - IC SelfRef merge (SelfCRef b1, SelfCRef b2) { invalidate(); merge(b1); merge(b2); return *this; } - ICF SelfRef xform (SelfCRef B, const Tmatrix &m) - { - // The three edges transformed: you can efficiently transform an X-only vector3 - // by just getting the "X" column of the matrix - Tvector vx,vy,vz; - vx.mul (m.i, B.max.x-B.min.x); - vy.mul (m.j, B.max.y-B.min.y); - vz.mul (m.k, B.max.z-B.min.z); - - // Transform the min point - m.transform_tiny (min,B.min); - max.set (min); - - // Take the transformed min & axes and find _new_ extents - // Using CPU code in the right place is faster... - if(negative(vx.x)) min.x += vx.x; else max.x += vx.x; - if(negative(vx.y)) min.y += vx.y; else max.y += vx.y; - if(negative(vx.z)) min.z += vx.z; else max.z += vx.z; - if(negative(vy.x)) min.x += vy.x; else max.x += vy.x; - if(negative(vy.y)) min.y += vy.y; else max.y += vy.y; - if(negative(vy.z)) min.z += vy.z; else max.z += vy.z; - if(negative(vz.x)) min.x += vz.x; else max.x += vz.x; - if(negative(vz.y)) min.y += vz.y; else max.y += vz.y; - if(negative(vz.z)) min.z += vz.z; else max.z += vz.z; - return *this; - } - ICF SelfRef xform (const Tmatrix &m) + // Take the transformed min & axes and find _new_ extents + // Using CPU code in the right place is faster... + if (negative(vx.x)) min.x += vx.x; + else max.x += vx.x; + if (negative(vx.y)) min.y += vx.y; + else max.y += vx.y; + if (negative(vx.z)) min.z += vx.z; + else max.z += vx.z; + if (negative(vy.x)) min.x += vy.x; + else max.x += vy.x; + if (negative(vy.y)) min.y += vy.y; + else max.y += vy.y; + if (negative(vy.z)) min.z += vy.z; + else max.z += vy.z; + if (negative(vz.x)) min.x += vz.x; + else max.x += vz.x; + if (negative(vz.y)) min.y += vz.y; + else max.y += vz.y; + if (negative(vz.z)) min.z += vz.z; + else max.z += vz.z; + return *this; + } + ICF SelfRef xform(const Tmatrix& m) { - Self b; + Self b; b.set(*this); - return xform(b,m); + return xform(b, m); + } + + IC void getsize(Tvector& R) const { R.sub(max, min); }; + IC void getradius(Tvector& R) const { getsize(R); R.mul(0.5f); }; + IC T getradius() const { Tvector R; getradius(R); return R.magnitude(); }; + IC T getvolume() const { Tvector sz; getsize(sz); return sz.x*sz.y*sz.z; }; + IC SelfCRef getcenter(Tvector& C) const + { + C.x = (min.x + max.x) * 0.5f; + C.y = (min.y + max.y) * 0.5f; + C.z = (min.z + max.z) * 0.5f; + return *this; + }; + IC SelfCRef get_CD(Tvector& bc, Tvector& bd) const // center + dimensions + { + bd.sub(max, min).mul(.5f); + bc.add(min, bd); + return *this; + } + IC SelfRef scale(float s) // 0.1 means make 110%, -0.1 means make 90% + { + Fvector bd; + bd.sub(max, min).mul(s); + grow(bd); + return *this; } + IC SelfCRef getsphere(Tvector& C, T& R) const + { + getcenter(C); + R = C.distance_to(max); + return *this; + }; + + // Detects if this box intersect other + ICF BOOL intersect(SelfCRef box) + { + if (max.x < box.min.x) return FALSE; + if (max.y < box.min.y) return FALSE; + if (max.z < box.min.z) return FALSE; + if (min.x > box.max.x) return FALSE; + if (min.y > box.max.y) return FALSE; + if (min.z > box.max.z) return FALSE; + return TRUE; + }; + + // Does the vector3 intersects box + IC BOOL Pick(const Tvector& start, const Tvector& dir) + { + T alpha, xt, yt, zt; + Tvector rvmin, rvmax; + + rvmin.sub(min, start); + rvmax.sub(max, start); + + if (!fis_zero(dir.x)) + { + alpha = rvmin.x / dir.x; + yt = alpha * dir.y; + if (yt >= rvmin.y && yt <= rvmax.y) + { + zt = alpha * dir.z; + if (zt >= rvmin.z && zt <= rvmax.z) + return true; + } + alpha = rvmax.x / dir.x; + yt = alpha * dir.y; + if (yt >= rvmin.y && yt <= rvmax.y) + { + zt = alpha * dir.z; + if (zt >= rvmin.z && zt <= rvmax.z) + return true; + } + } + + if (!fis_zero(dir.y)) + { + alpha = rvmin.y / dir.y; + xt = alpha * dir.x; + if (xt >= rvmin.x && xt <= rvmax.x) + { + zt = alpha * dir.z; + if (zt >= rvmin.z && zt <= rvmax.z) + return true; + } + alpha = rvmax.y / dir.y; + xt = alpha * dir.x; + if (xt >= rvmin.x && xt <= rvmax.x) + { + zt = alpha * dir.z; + if (zt >= rvmin.z && zt <= rvmax.z) + return true; + } + } - IC void getsize (Tvector& R ) const { R.sub( max, min ); }; - IC void getradius (Tvector& R ) const { getsize(R); R.mul(0.5f); }; - IC T getradius () const { Tvector R; getradius(R); return R.magnitude(); }; - IC T getvolume () const { Tvector sz; getsize(sz); return sz.x*sz.y*sz.z; }; - IC SelfCRef getcenter (Tvector& C ) const { - C.x = (min.x + max.x) * 0.5f; - C.y = (min.y + max.y) * 0.5f; - C.z = (min.z + max.z) * 0.5f; - return *this; - }; - IC SelfCRef get_CD (Tvector& bc, Tvector& bd) const // center + dimensions - { - bd.sub (max,min).mul(.5f); - bc.add (min,bd); - return *this; - } - IC SelfRef scale (float s) // 0.1 means make 110%, -0.1 means make 90% - { - Fvector bd; bd.sub (max,min).mul(s); - grow (bd); - return *this; - } - IC SelfCRef getsphere (Tvector &C, T &R) const { - getcenter (C); - R = C.distance_to (max); - return *this; - }; - - // Detects if this box intersect other - ICF BOOL intersect (SelfCRef box ) - { - if( max.x < box.min.x ) return FALSE; - if( max.y < box.min.y ) return FALSE; - if( max.z < box.min.z ) return FALSE; - if( min.x > box.max.x ) return FALSE; - if( min.y > box.max.y ) return FALSE; - if( min.z > box.max.z ) return FALSE; - return TRUE; - }; + if (!fis_zero(dir.z)) + { + alpha = rvmin.z / dir.z; + xt = alpha * dir.x; + if (xt >= rvmin.x && xt <= rvmax.x) + { + yt = alpha * dir.y; + if (yt >= rvmin.y && yt <= rvmax.y) + return true; + } + alpha = rvmax.z / dir.z; + xt = alpha * dir.x; + if (xt >= rvmin.x && xt <= rvmax.x) + { + yt = alpha * dir.y; + if (yt >= rvmin.y && yt <= rvmax.y) + return true; + } + } + return false; + }; - // Does the vector3 intersects box - IC BOOL Pick (const Tvector& start, const Tvector& dir) - { - T alpha,xt,yt,zt; - Tvector rvmin,rvmax; + IC u32& IR(T& x) { return (u32&)x; } + enum ERP_Result + { + rpNone = 0, + rpOriginInside = 1, + rpOriginOutside = 2, + fcv_forcedword = u32(-1) + }; + IC ERP_Result Pick2(const Tvector& origin, const Tvector& dir, Tvector& coord) + { + BOOL Inside = TRUE; + Tvector MaxT; + MaxT.x = MaxT.y = MaxT.z = -1.0f; - rvmin.sub( min, start ); - rvmax.sub( max, start ); + // Find candidate planes. + { + if (origin[0] < min[0]) + { + coord[0] = min[0]; + Inside = FALSE; + if (IR(dir[0])) MaxT[0] = (min[0] - origin[0]) / dir[0]; // Calculate T distances to candidate planes + } + else if (origin[0] > max[0]) + { + coord[0] = max[0]; + Inside = FALSE; + if (IR(dir[0])) MaxT[0] = (max[0] - origin[0]) / dir[0]; // Calculate T distances to candidate planes + } + } + { + if (origin[1] < min[1]) + { + coord[1] = min[1]; + Inside = FALSE; + if (IR(dir[1])) MaxT[1] = (min[1] - origin[1]) / dir[1]; // Calculate T distances to candidate planes + } + else if (origin[1] > max[1]) + { + coord[1] = max[1]; + Inside = FALSE; + if (IR(dir[1])) MaxT[1] = (max[1] - origin[1]) / dir[1]; // Calculate T distances to candidate planes + } + } + { + if (origin[2] < min[2]) + { + coord[2] = min[2]; + Inside = FALSE; + if (IR(dir[2])) MaxT[2] = (min[2] - origin[2]) / dir[2]; // Calculate T distances to candidate planes + } + else if (origin[2] > max[2]) + { + coord[2] = max[2]; + Inside = FALSE; + if (IR(dir[2])) MaxT[2] = (max[2] - origin[2]) / dir[2]; // Calculate T distances to candidate planes + } + } - if( !fis_zero(dir.x) ){ - alpha = rvmin.x / dir.x; - yt = alpha * dir.y; - if( yt >= rvmin.y && yt <= rvmax.y ){ - zt = alpha * dir.z; - if( zt >= rvmin.z && zt <= rvmax.z ) - return true; - } - alpha = rvmax.x / dir.x; - yt = alpha * dir.y; - if( yt >= rvmin.y && yt <= rvmax.y ){ - zt = alpha * dir.z; - if( zt >= rvmin.z && zt <= rvmax.z ) - return true; - } - } + // Ray origin inside bounding box + if (Inside) + { + coord = origin; + return rpOriginInside; + } - if( !fis_zero(dir.y) ){ - alpha = rvmin.y / dir.y; - xt = alpha * dir.x; - if( xt >= rvmin.x && xt <= rvmax.x ){ - zt = alpha * dir.z; - if( zt >= rvmin.z && zt <= rvmax.z ) - return true; - } - alpha = rvmax.y / dir.y; - xt = alpha * dir.x; - if( xt >= rvmin.x && xt <= rvmax.x ){ - zt = alpha * dir.z; - if( zt >= rvmin.z && zt <= rvmax.z ) - return true; - } - } + // Get largest of the maxT's for final choice of intersection + u32 WhichPlane = 0; + if (MaxT[1] > MaxT[0]) WhichPlane = 1; + if (MaxT[2] > MaxT[WhichPlane]) WhichPlane = 2; - if( !fis_zero(dir.z) ){ - alpha = rvmin.z / dir.z; - xt = alpha * dir.x; - if( xt >= rvmin.x && xt <= rvmax.x ){ - yt = alpha * dir.y; - if( yt >= rvmin.y && yt <= rvmax.y ) - return true; - } - alpha = rvmax.z / dir.z; - xt = alpha * dir.x; - if( xt >= rvmin.x && xt <= rvmax.x ){ - yt = alpha * dir.y; - if( yt >= rvmin.y && yt <= rvmax.y ) - return true; - } - } - return false; - }; + // Check final candidate actually inside box + if (IR(MaxT[WhichPlane]) & 0x80000000) return rpNone; + + if (0 == WhichPlane) + { + // 1 & 2 + coord[1] = origin[1] + MaxT[0] * dir[1]; + if ((coord[1] < min[1]) || (coord[1] > max[1])) return rpNone; + coord[2] = origin[2] + MaxT[0] * dir[2]; + if ((coord[2] < min[2]) || (coord[2] > max[2])) return rpNone; + return rpOriginOutside; + } + if (1 == WhichPlane) + { + // 0 & 2 + coord[0] = origin[0] + MaxT[1] * dir[0]; + if ((coord[0] < min[0]) || (coord[0] > max[0])) return rpNone; + coord[2] = origin[2] + MaxT[1] * dir[2]; + if ((coord[2] < min[2]) || (coord[2] > max[2])) return rpNone; + return rpOriginOutside; + } + if (2 == WhichPlane) + { + // 0 & 1 + coord[0] = origin[0] + MaxT[2] * dir[0]; + if ((coord[0] < min[0]) || (coord[0] > max[0])) return rpNone; + coord[1] = origin[1] + MaxT[2] * dir[1]; + if ((coord[1] < min[1]) || (coord[1] > max[1])) return rpNone; + return rpOriginOutside; + } + return rpNone; + } - IC u32& IR(T &x) { return (u32&)x; } - enum ERP_Result{ - rpNone = 0, - rpOriginInside = 1, - rpOriginOutside = 2, - fcv_forcedword = u32(-1) - }; - IC ERP_Result Pick2(const Tvector& origin, const Tvector& dir, Tvector& coord) - { - BOOL Inside = TRUE; - Tvector MaxT; - MaxT.x=MaxT.y=MaxT.z=-1.0f; - - // Find candidate planes. - { - if(origin[0] < min[0]) { - coord[0] = min[0]; - Inside = FALSE; - if(IR(dir[0])) MaxT[0] = (min[0] - origin[0]) / dir[0]; // Calculate T distances to candidate planes - } else if(origin[0] > max[0]) { - coord[0] = max[0]; - Inside = FALSE; - if(IR(dir[0])) MaxT[0] = (max[0] - origin[0]) / dir[0]; // Calculate T distances to candidate planes - } - } - { - if(origin[1] < min[1]) { - coord[1] = min[1]; - Inside = FALSE; - if(IR(dir[1])) MaxT[1] = (min[1] - origin[1]) / dir[1]; // Calculate T distances to candidate planes - } else if(origin[1] > max[1]) { - coord[1] = max[1]; - Inside = FALSE; - if(IR(dir[1])) MaxT[1] = (max[1] - origin[1]) / dir[1]; // Calculate T distances to candidate planes - } - } - { - if(origin[2] < min[2]) { - coord[2] = min[2]; - Inside = FALSE; - if(IR(dir[2])) MaxT[2] = (min[2] - origin[2]) / dir[2]; // Calculate T distances to candidate planes - } else if(origin[2] > max[2]) { - coord[2] = max[2]; - Inside = FALSE; - if(IR(dir[2])) MaxT[2] = (max[2] - origin[2]) / dir[2]; // Calculate T distances to candidate planes - } - } - - // Ray origin inside bounding box - if(Inside) - { - coord = origin; - return rpOriginInside; - } - - // Get largest of the maxT's for final choice of intersection - u32 WhichPlane = 0; - if(MaxT[1] > MaxT[0]) WhichPlane = 1; - if(MaxT[2] > MaxT[WhichPlane]) WhichPlane = 2; - - // Check final candidate actually inside box - if(IR(MaxT[WhichPlane])&0x80000000) return rpNone; - - if (0==WhichPlane) - { - // 1 & 2 - coord[1] = origin[1] + MaxT[0] * dir[1]; - if((coord[1] < min[1]) || (coord[1] > max[1])) return rpNone; - coord[2] = origin[2] + MaxT[0] * dir[2]; - if((coord[2] < min[2]) || (coord[2] > max[2])) return rpNone; - return rpOriginOutside; - } - if (1==WhichPlane) - { - // 0 & 2 - coord[0] = origin[0] + MaxT[1] * dir[0]; - if((coord[0] < min[0]) || (coord[0] > max[0])) return rpNone; - coord[2] = origin[2] + MaxT[1] * dir[2]; - if((coord[2] < min[2]) || (coord[2] > max[2])) return rpNone; - return rpOriginOutside; - } - if (2==WhichPlane) - { - // 0 & 1 - coord[0] = origin[0] + MaxT[2] * dir[0]; - if((coord[0] < min[0]) || (coord[0] > max[0])) return rpNone; - coord[1] = origin[1] + MaxT[2] * dir[1]; - if((coord[1] < min[1]) || (coord[1] > max[1])) return rpNone; - return rpOriginOutside; - } - return rpNone; - } - - IC void getpoint( int index, Tvector& result ) const - { - switch( index ){ - case 0: result.set( min.x, min.y, min.z ); break; - case 1: result.set( min.x, min.y, max.z ); break; - case 2: result.set( max.x, min.y, max.z ); break; - case 3: result.set( max.x, min.y, min.z ); break; - case 4: result.set( min.x, max.y, min.z ); break; - case 5: result.set( min.x, max.y, max.z ); break; - case 6: result.set( max.x, max.y, max.z ); break; - case 7: result.set( max.x, max.y, min.z ); break; - default: result.set( 0, 0, 0 ); break; } - }; - IC void getpoints(Tvector* result) - { - result[0].set( min.x, min.y, min.z ); - result[1].set( min.x, min.y, max.z ); - result[2].set( max.x, min.y, max.z ); - result[3].set( max.x, min.y, min.z ); - result[4].set( min.x, max.y, min.z ); - result[5].set( min.x, max.y, max.z ); - result[6].set( max.x, max.y, max.z ); - result[7].set( max.x, max.y, min.z ); - }; + IC void getpoint(int index, Tvector& result) const + { + switch (index) + { + case 0: + result.set(min.x, min.y, min.z); + break; + case 1: + result.set(min.x, min.y, max.z); + break; + case 2: + result.set(max.x, min.y, max.z); + break; + case 3: + result.set(max.x, min.y, min.z); + break; + case 4: + result.set(min.x, max.y, min.z); + break; + case 5: + result.set(min.x, max.y, max.z); + break; + case 6: + result.set(max.x, max.y, max.z); + break; + case 7: + result.set(max.x, max.y, min.z); + break; + default: + result.set(0, 0, 0); + break; + } + }; + IC void getpoints(Tvector* result) + { + result[0].set(min.x, min.y, min.z); + result[1].set(min.x, min.y, max.z); + result[2].set(max.x, min.y, max.z); + result[3].set(max.x, min.y, min.z); + result[4].set(min.x, max.y, min.z); + result[5].set(min.x, max.y, max.z); + result[6].set(max.x, max.y, max.z); + result[7].set(max.x, max.y, min.z); + }; - IC SelfRef modify(SelfCRef src, const Tmatrix& M) - { - Tvector pt; - for(int i=0; i<8; i++){ - src.getpoint(i,pt); - M.transform_tiny(pt); - modify(pt); - } - return *this; - } + IC SelfRef modify(SelfCRef src, const Tmatrix& M) + { + Tvector pt; + for (int i = 0; i < 8; i++) + { + src.getpoint(i, pt); + M.transform_tiny(pt); + modify(pt); + } + return *this; + } }; -typedef _box3 Fbox; -typedef _box3 Fbox3; -typedef _box3 Dbox; -typedef _box3 Dbox3; +typedef _box3 Fbox; +typedef _box3 Fbox3; +typedef _box3 Dbox; +typedef _box3 Dbox3; template -BOOL _valid (const _box3& c) { return _valid(min) && _valid(max); } +BOOL _valid(const _box3& c) { return _valid(min) && _valid(max); } #endif diff --git a/src/xrCore/_fbox2.h b/src/xrCore/_fbox2.h index 5ed985967c2..2ab316791f6 100644 --- a/src/xrCore/_fbox2.h +++ b/src/xrCore/_fbox2.h @@ -2,221 +2,254 @@ #define __FBOX2 template -class _box2 { +class _box2 +{ public: - typedef T TYPE; - typedef _box2 Self; - typedef Self& SelfRef; - typedef const Self& SelfCRef; - typedef _vector2 Tvector; + typedef T TYPE; + typedef _box2 Self; + typedef Self& SelfRef; + typedef const Self& SelfCRef; + typedef _vector2 Tvector; public: - union{ - struct{ - Tvector min; - Tvector max; - }; - struct{ - T x1, y1; - T x2, y2; - }; - }; - - IC SelfRef set (const Tvector &_min, const Tvector &_max) { min.set(_min); max.set(_max); return *this; }; - IC SelfRef set (T x1, T y1, T x2, T y2) { min.set(x1,y1); max.set(x2,y2); return *this; }; - IC SelfRef set (SelfCRef b) { min.set(b.min); max.set(b.max); return *this; }; - - IC SelfRef null () { min.set(0.f,0.f); max.set(0.f,0.f); return *this; }; - IC SelfRef identity () { min.set(-0.5,-0.5,-0.5); max.set(0.5,0.5,0.5); return *this; }; - IC SelfRef invalidate () { min.set(type_max(T),type_max(T)); max.set(type_min(T),type_min(T)); return *this; } - - IC SelfRef shrink (T s) { min.add(s); max.sub(s); return *this; }; - IC SelfRef shrink (const Tvector& s) { min.add(s); max.sub(s); return *this; }; - IC SelfRef grow (T s) { min.sub(s); max.add(s); return *this; }; - IC SelfRef grow (const Tvector& s) { min.sub(s); max.add(s); return *this; }; - - IC SelfRef add (const Tvector &p) { min.add(p); max.add(p); return *this; }; - IC SelfRef offset (const Tvector &p) { min.add(p); max.add(p); return *this; }; - IC SelfRef add (SelfCRef b, const Tvector &p) { min.add(b.min, p); max.add(b.max, p); return *this; }; - - IC BOOL contains (T x, T y) { return (x>=x1) && (x<=x2) && (y>=y1) && (y<=y2); }; - IC BOOL contains (const Tvector &p) { return contains(p.x,p.y); }; - IC BOOL contains (SelfCRef b) { return contains(b.min) && contains(b.max); }; - - IC BOOL similar (SelfCRef b) { return min.similar(b.min) && max.similar(b.max); }; - - IC SelfRef modify (const Tvector &p) { min.min(p); max.max(p); return *this; } - IC SelfRef merge (SelfCRef b) { modify(b.min); modify(b.max); return *this; }; - IC SelfRef merge (SelfCRef b1, SelfCRef b2) { invalidate(); merge(b1); merge(b2); return *this; } - - IC void getsize (Tvector& R ) const { R.sub( max, min ); }; - IC void getradius (Tvector& R ) const { getsize(R); R.mul(0.5f); }; - IC T getradius () const { Tvector R; getsize(R); R.mul(0.5f); return R.magnitude(); }; - - IC void getcenter (Tvector& C ) const - { - C.x = (min.x + max.x) * 0.5f; - C.y = (min.y + max.y) * 0.5f; - }; - IC void getsphere (Tvector &C, T &R) const - { - getcenter(C); - R = C.distance_to(max); - }; - - // Detects if this box intersect other - IC BOOL intersect(SelfCRef box ) - { - if( max.x < box.min.x ) return FALSE; - if( max.y < box.min.y ) return FALSE; - if( min.x > box.max.x ) return FALSE; - if( min.y > box.max.y ) return FALSE; - return TRUE; - }; - - // Make's this box valid AABB + union + { + struct + { + Tvector min; + Tvector max; + }; + struct + { + T x1, y1; + T x2, y2; + }; + }; + + IC SelfRef set(const Tvector& _min, const Tvector& _max) { min.set(_min); max.set(_max); return *this; }; + IC SelfRef set(T x1, T y1, T x2, T y2) { min.set(x1, y1); max.set(x2, y2); return *this; }; + IC SelfRef set(SelfCRef b) { min.set(b.min); max.set(b.max); return *this; }; + + IC SelfRef null() { min.set(0.f, 0.f); max.set(0.f, 0.f); return *this; }; + IC SelfRef identity() { min.set(-0.5, -0.5, -0.5); max.set(0.5, 0.5, 0.5); return *this; }; + IC SelfRef invalidate() { min.set(type_max(T), type_max(T)); max.set(type_min(T), type_min(T)); return *this; } + + IC SelfRef shrink(T s) { min.add(s); max.sub(s); return *this; }; + IC SelfRef shrink(const Tvector& s) { min.add(s); max.sub(s); return *this; }; + IC SelfRef grow(T s) { min.sub(s); max.add(s); return *this; }; + IC SelfRef grow(const Tvector& s) { min.sub(s); max.add(s); return *this; }; + + IC SelfRef add(const Tvector& p) { min.add(p); max.add(p); return *this; }; + IC SelfRef offset(const Tvector& p) { min.add(p); max.add(p); return *this; }; + IC SelfRef add(SelfCRef b, const Tvector& p) { min.add(b.min, p); max.add(b.max, p); return *this; }; + + IC BOOL contains(T x, T y) { return (x >= x1) && (x <= x2) && (y >= y1) && (y <= y2); }; + IC BOOL contains(const Tvector& p) { return contains(p.x, p.y); }; + IC BOOL contains(SelfCRef b) { return contains(b.min) && contains(b.max); }; + + IC BOOL similar(SelfCRef b) { return min.similar(b.min) && max.similar(b.max); }; + + IC SelfRef modify(const Tvector& p) { min.min(p); max.max(p); return *this; } + IC SelfRef merge(SelfCRef b) { modify(b.min); modify(b.max); return *this; }; + IC SelfRef merge(SelfCRef b1, SelfCRef b2) { invalidate(); merge(b1); merge(b2); return *this; } + + IC void getsize(Tvector& R) const { R.sub(max, min); }; + IC void getradius(Tvector& R) const { getsize(R); R.mul(0.5f); }; + IC T getradius() const { Tvector R; getsize(R); R.mul(0.5f); return R.magnitude(); }; + + IC void getcenter(Tvector& C) const + { + C.x = (min.x + max.x) * 0.5f; + C.y = (min.y + max.y) * 0.5f; + }; + IC void getsphere(Tvector& C, T& R) const + { + getcenter(C); + R = C.distance_to(max); + }; + + // Detects if this box intersect other + IC BOOL intersect(SelfCRef box) + { + if (max.x < box.min.x) return FALSE; + if (max.y < box.min.y) return FALSE; + if (min.x > box.max.x) return FALSE; + if (min.y > box.max.y) return FALSE; + return TRUE; + }; + + // Make's this box valid AABB IC SelfRef sort() - { - T tmp; - if( min.x > max.x ) { tmp = min.x; min.x = max.x; max.x = tmp; } - if( min.y > max.y ) { tmp = min.y; min.y = max.y; max.y = tmp; } - return *this; - }; - - // Does the vector3 intersects box - IC BOOL Pick( const Tvector& start, const Tvector& dir ){ - T alpha,xt,yt; - Tvector rvmin,rvmax; - - rvmin.sub( min, start ); - rvmax.sub( max, start ); - - if( !fis_zero(dir.x) ){ - alpha = rvmin.x / dir.x; - yt = alpha * dir.y; - if( yt >= rvmin.y && yt <= rvmax.y ) - return true; - alpha = rvmax.x / dir.x; - yt = alpha * dir.y; - if( yt >= rvmin.y && yt <= rvmax.y ) - return true; - } - - if( !fis_zero(dir.y) ){ - alpha = rvmin.y / dir.y; - xt = alpha * dir.x; - if( xt >= rvmin.x && xt <= rvmax.x ) - return true; - alpha = rvmax.y / dir.y; - xt = alpha * dir.x; - if( xt >= rvmin.x && xt <= rvmax.x ) - return true; - } - return false; - }; - ICF BOOL pick_exact ( const Tvector& start, const Tvector& dir ){ - T alpha,xt,yt; - Tvector rvmin,rvmax; - - rvmin.sub ( min, start ); - rvmax.sub ( max, start ); - - if( _abs(dir.x)!=0 ){ - alpha = rvmin.x / dir.x; - yt = alpha * dir.y; - if( yt >= rvmin.y - EPS && yt <= rvmax.y + EPS) return true; - alpha = rvmax.x / dir.x; - yt = alpha * dir.y; - if( yt >= rvmin.y - EPS && yt <= rvmax.y + EPS) return true; - } - if( _abs(dir.y)!=0 ){ - alpha = rvmin.y / dir.y; - xt = alpha * dir.x; - if( xt >= rvmin.x - EPS && xt <= rvmax.x + EPS) return true; - alpha = rvmax.y / dir.y; - xt = alpha * dir.x; - if( xt >= rvmin.x - EPS && xt <= rvmax.x + EPS) return true; - } - return false; - }; - - IC u32& IR(T &x) { return (u32&)x; } - IC BOOL Pick2(const Tvector& origin, const Tvector& dir, Tvector& coord){ - BOOL Inside = TRUE; - Tvector MaxT; - MaxT.x=MaxT.y=-1.0f; - - // Find candidate planes. - { - if(origin[0] < min[0]) { - coord[0] = min[0]; - Inside = FALSE; - if(IR(dir[0])) MaxT[0] = (min[0] - origin[0]) / dir[0]; // Calculate T distances to candidate planes - } else if(origin[0] > max[0]) { - coord[0] = max[0]; - Inside = FALSE; - if(IR(dir[0])) MaxT[0] = (max[0] - origin[0]) / dir[0]; // Calculate T distances to candidate planes - } - } - { - if(origin[1] < min[1]) { - coord[1] = min[1]; - Inside = FALSE; - if(IR(dir[1])) MaxT[1] = (min[1] - origin[1]) / dir[1]; // Calculate T distances to candidate planes - } else if(origin[1] > max[1]) { - coord[1] = max[1]; - Inside = FALSE; - if(IR(dir[1])) MaxT[1] = (max[1] - origin[1]) / dir[1]; // Calculate T distances to candidate planes - } - } - - // Ray origin inside bounding box - if(Inside) - { - coord = origin; - return true; - } - - // Get largest of the maxT's for final choice of intersection - u32 WhichPlane = 0; - if(MaxT[1] > MaxT[0]) WhichPlane = 1; - - // Check final candidate actually inside box - if(IR(MaxT[WhichPlane])&0x80000000) return false; - - if (0==WhichPlane) - { - // 1 - coord[1] = origin[1] + MaxT[0] * dir[1]; - if((coord[1] < min[1]) || (coord[1] > max[1])) return false; - return true; - } else { - // 0 - coord[0] = origin[0] + MaxT[1] * dir[0]; - if((coord[0] < min[0]) || (coord[0] > max[0])) return false; - return true; - } - } - - IC void getpoint( int index, Tvector& result ){ - switch( index ){ - case 0: result.set( min.x, min.y ); break; - case 1: result.set( min.x, min.y ); break; - case 2: result.set( max.x, min.y ); break; - case 3: result.set( max.x, min.y ); break; - default: result.set(0.f,0.f); break; } - }; - IC void getpoints(Tvector* result){ - result[0].set( min.x, min.y ); - result[1].set( min.x, min.y ); - result[2].set( max.x, min.y ); - result[3].set( max.x, min.y ); - }; + { + T tmp; + if (min.x > max.x) { tmp = min.x; min.x = max.x; max.x = tmp; } + if (min.y > max.y) { tmp = min.y; min.y = max.y; max.y = tmp; } + return *this; + }; + + // Does the vector3 intersects box + IC BOOL Pick(const Tvector& start, const Tvector& dir) + { + T alpha, xt, yt; + Tvector rvmin, rvmax; + + rvmin.sub(min, start); + rvmax.sub(max, start); + + if (!fis_zero(dir.x)) + { + alpha = rvmin.x / dir.x; + yt = alpha * dir.y; + if (yt >= rvmin.y && yt <= rvmax.y) + return true; + alpha = rvmax.x / dir.x; + yt = alpha * dir.y; + if (yt >= rvmin.y && yt <= rvmax.y) + return true; + } + + if (!fis_zero(dir.y)) + { + alpha = rvmin.y / dir.y; + xt = alpha * dir.x; + if (xt >= rvmin.x && xt <= rvmax.x) + return true; + alpha = rvmax.y / dir.y; + xt = alpha * dir.x; + if (xt >= rvmin.x && xt <= rvmax.x) + return true; + } + return false; + }; + ICF BOOL pick_exact(const Tvector& start, const Tvector& dir) + { + T alpha, xt, yt; + Tvector rvmin, rvmax; + + rvmin.sub(min, start); + rvmax.sub(max, start); + + if (_abs(dir.x) != 0) + { + alpha = rvmin.x / dir.x; + yt = alpha * dir.y; + if (yt >= rvmin.y - EPS && yt <= rvmax.y + EPS) return true; + alpha = rvmax.x / dir.x; + yt = alpha * dir.y; + if (yt >= rvmin.y - EPS && yt <= rvmax.y + EPS) return true; + } + if (_abs(dir.y) != 0) + { + alpha = rvmin.y / dir.y; + xt = alpha * dir.x; + if (xt >= rvmin.x - EPS && xt <= rvmax.x + EPS) return true; + alpha = rvmax.y / dir.y; + xt = alpha * dir.x; + if (xt >= rvmin.x - EPS && xt <= rvmax.x + EPS) return true; + } + return false; + }; + + IC u32& IR(T& x) { return (u32&)x; } + IC BOOL Pick2(const Tvector& origin, const Tvector& dir, Tvector& coord) + { + BOOL Inside = TRUE; + Tvector MaxT; + MaxT.x = MaxT.y = -1.0f; + + // Find candidate planes. + { + if (origin[0] < min[0]) + { + coord[0] = min[0]; + Inside = FALSE; + if (IR(dir[0])) MaxT[0] = (min[0] - origin[0]) / dir[0]; // Calculate T distances to candidate planes + } + else if (origin[0] > max[0]) + { + coord[0] = max[0]; + Inside = FALSE; + if (IR(dir[0])) MaxT[0] = (max[0] - origin[0]) / dir[0]; // Calculate T distances to candidate planes + } + } + { + if (origin[1] < min[1]) + { + coord[1] = min[1]; + Inside = FALSE; + if (IR(dir[1])) MaxT[1] = (min[1] - origin[1]) / dir[1]; // Calculate T distances to candidate planes + } + else if (origin[1] > max[1]) + { + coord[1] = max[1]; + Inside = FALSE; + if (IR(dir[1])) MaxT[1] = (max[1] - origin[1]) / dir[1]; // Calculate T distances to candidate planes + } + } + + // Ray origin inside bounding box + if (Inside) + { + coord = origin; + return true; + } + + // Get largest of the maxT's for final choice of intersection + u32 WhichPlane = 0; + if (MaxT[1] > MaxT[0]) WhichPlane = 1; + + // Check final candidate actually inside box + if (IR(MaxT[WhichPlane]) & 0x80000000) return false; + + if (0 == WhichPlane) + { + // 1 + coord[1] = origin[1] + MaxT[0] * dir[1]; + if ((coord[1] < min[1]) || (coord[1] > max[1])) return false; + return true; + } + else + { + // 0 + coord[0] = origin[0] + MaxT[1] * dir[0]; + if ((coord[0] < min[0]) || (coord[0] > max[0])) return false; + return true; + } + } + + IC void getpoint(int index, Tvector& result) + { + switch (index) + { + case 0: + result.set(min.x, min.y); + break; + case 1: + result.set(min.x, min.y); + break; + case 2: + result.set(max.x, min.y); + break; + case 3: + result.set(max.x, min.y); + break; + default: + result.set(0.f, 0.f); + break; + } + }; + IC void getpoints(Tvector* result) + { + result[0].set(min.x, min.y); + result[1].set(min.x, min.y); + result[2].set(max.x, min.y); + result[3].set(max.x, min.y); + }; }; -typedef _box2 Fbox2; -typedef _box2 Dbox2; +typedef _box2 Fbox2; +typedef _box2 Dbox2; template -BOOL _valid (const _box2& c) { return _valid(c.min) && _valid(c.max); } +BOOL _valid(const _box2& c) { return _valid(c.min) && _valid(c.max); } #endif diff --git a/src/xrCore/_flags.h b/src/xrCore/_flags.h index 0246f4222ef..49ecbbed52a 100644 --- a/src/xrCore/_flags.h +++ b/src/xrCore/_flags.h @@ -2,38 +2,43 @@ #define __FLAGS_H__ template -struct _flags { +struct _flags +{ public: - typedef T TYPE; - typedef _flags Self; - typedef Self& SelfRef; - typedef const Self& SelfCRef; + typedef T TYPE; + typedef _flags Self; + typedef Self& SelfRef; + typedef const Self& SelfCRef; public: - T flags; + T flags; - IC TYPE get () const { return flags;} - IC SelfRef zero () { flags=T(0); return *this; } - IC SelfRef one () { flags=T(-1); return *this; } - IC SelfRef invert () { flags = ~flags; return *this; } - IC SelfRef invert (const Self& f) { flags = ~f.flags; return *this; } - IC SelfRef invert (const T mask) { flags ^= mask; return *this; } - IC SelfRef assign (const Self& f) { flags = f.flags; return *this; } - IC SelfRef assign (const T mask) { flags = mask; return *this; } - IC SelfRef set (const T mask, BOOL value) { if (value) flags|=mask; else flags&=~mask; return *this; } - IC BOOL is (const T mask) const { return mask==(flags&mask); } - IC BOOL is_any (const T mask) const { return BOOL(!!(flags&mask)); } - IC BOOL test (const T mask) const { return BOOL(!!(flags&mask)); } - IC SelfRef or (const T mask) { flags|=mask; return *this; } - IC SelfRef or (const Self& f, const T mask) { flags=f.flags|mask; return *this; } - IC SelfRef and (const T mask) { flags&=mask; return *this; } - IC SelfRef and (const Self& f, const T mask) { flags=f.flags&mask; return *this; } - IC BOOL equal (const Self& f) const { return flags==f.flags;} - IC BOOL equal (const Self& f, const T mask) const { return (flags&mask)==(f.flags&mask);} + IC TYPE get() const { return flags; } + IC SelfRef zero() { flags = T(0); return *this; } + IC SelfRef one() { flags = T(-1); return *this; } + IC SelfRef invert() { flags = ~flags; return *this; } + IC SelfRef invert(const Self& f) { flags = ~f.flags; return *this; } + IC SelfRef invert(const T mask) { flags ^= mask; return *this; } + IC SelfRef assign(const Self& f) { flags = f.flags; return *this; } + IC SelfRef assign(const T mask) { flags = mask; return *this; } + IC SelfRef set(const T mask, BOOL value) { if (value) flags |= mask; else flags &= ~mask; return *this; } + IC BOOL is(const T mask) const { return mask == (flags&mask); } + IC BOOL is_any(const T mask) const { return BOOL(!!(flags&mask)); } + IC BOOL test(const T mask) const { return BOOL(!!(flags&mask)); } + IC SelfRef or(const T mask) { flags |= mask; return *this; } + IC SelfRef or(const Self& f, const T mask) { flags = f.flags | mask; return *this; } + IC SelfRef and(const T mask) { flags &= mask; return *this; } + IC SelfRef and(const Self& f, const T mask) { flags = f.flags&mask; return *this; } + IC BOOL equal(const Self& f) const { return flags == f.flags; } + IC BOOL equal(const Self& f, const T mask) const { return (flags&mask) == (f.flags&mask); } }; -typedef _flags Flags8; typedef _flags flags8; -typedef _flags Flags16; typedef _flags flags16; -typedef _flags Flags32; typedef _flags flags32; -typedef _flags Flags64; typedef _flags flags64; +typedef _flags Flags8; +typedef _flags flags8; +typedef _flags Flags16; +typedef _flags flags16; +typedef _flags Flags32; +typedef _flags flags32; +typedef _flags Flags64; +typedef _flags flags64; #endif //__FLAGS_H__ diff --git a/src/xrCore/_math.cpp b/src/xrCore/_math.cpp index 7fea8ff195f..785111d8291 100644 --- a/src/xrCore/_math.cpp +++ b/src/xrCore/_math.cpp @@ -12,256 +12,277 @@ #include // Initialized on startup -XRCORE_API Fmatrix Fidentity; -XRCORE_API Dmatrix Didentity; -XRCORE_API CRandom Random; +XRCORE_API Fmatrix Fidentity; +XRCORE_API Dmatrix Didentity; +XRCORE_API CRandom Random; #ifdef _M_AMD64 -u16 getFPUsw() { return 0; } +u16 getFPUsw() { return 0; } -namespace FPU +namespace FPU { - XRCORE_API void m24 (void) { - _control87 ( _PC_24, MCW_PC ); - _control87 ( _RC_CHOP, MCW_RC ); - } - XRCORE_API void m24r (void) { - _control87 ( _PC_24, MCW_PC ); - _control87 ( _RC_NEAR, MCW_RC ); - } - XRCORE_API void m53 (void) { - _control87 ( _PC_53, MCW_PC ); - _control87 ( _RC_CHOP, MCW_RC ); - } - XRCORE_API void m53r (void) { - _control87 ( _PC_53, MCW_PC ); - _control87 ( _RC_NEAR, MCW_RC ); - } - XRCORE_API void m64 (void) { - _control87 ( _PC_64, MCW_PC ); - _control87 ( _RC_CHOP, MCW_RC ); - } - XRCORE_API void m64r (void) { - _control87 ( _PC_64, MCW_PC ); - _control87 ( _RC_NEAR, MCW_RC ); - } - - void initialize () {} +XRCORE_API void m24(void) +{ + _control87(_PC_24, MCW_PC); + _control87(_RC_CHOP, MCW_RC); +} +XRCORE_API void m24r(void) +{ + _control87(_PC_24, MCW_PC); + _control87(_RC_NEAR, MCW_RC); +} +XRCORE_API void m53(void) +{ + _control87(_PC_53, MCW_PC); + _control87(_RC_CHOP, MCW_RC); +} +XRCORE_API void m53r(void) +{ + _control87(_PC_53, MCW_PC); + _control87(_RC_NEAR, MCW_RC); +} +XRCORE_API void m64(void) +{ + _control87(_PC_64, MCW_PC); + _control87(_RC_CHOP, MCW_RC); +} +XRCORE_API void m64r(void) +{ + _control87(_PC_64, MCW_PC); + _control87(_RC_NEAR, MCW_RC); +} + +void initialize() {} }; #else -u16 getFPUsw() +u16 getFPUsw() +{ + u16 SW; + __asm fstcw SW; + return SW; +} + +namespace FPU +{ +u16 _24 = 0; +u16 _24r = 0; +u16 _53 = 0; +u16 _53r = 0; +u16 _64 = 0; +u16 _64r = 0; + +XRCORE_API void m24() +{ + u16 p = _24; + __asm fldcw p; +} +XRCORE_API void m24r() +{ + u16 p = _24r; + __asm fldcw p; +} +XRCORE_API void m53() +{ + u16 p = _53; + __asm fldcw p; +} +XRCORE_API void m53r() +{ + u16 p = _53r; + __asm fldcw p; +} +XRCORE_API void m64() +{ + u16 p = _64; + __asm fldcw p; +} +XRCORE_API void m64r() { - u16 SW; - __asm fstcw SW; - return SW; + u16 p = _64r; + __asm fldcw p; } -namespace FPU +void initialize() { - u16 _24 =0; - u16 _24r=0; - u16 _53 =0; - u16 _53r=0; - u16 _64 =0; - u16 _64r=0; - - XRCORE_API void m24 () { - u16 p = _24; - __asm fldcw p; - } - XRCORE_API void m24r () { - u16 p = _24r; - __asm fldcw p; - } - XRCORE_API void m53 () { - u16 p = _53; - __asm fldcw p; - } - XRCORE_API void m53r () { - u16 p = _53r; - __asm fldcw p; - } - XRCORE_API void m64 () { - u16 p = _64; - __asm fldcw p; - } - XRCORE_API void m64r () { - u16 p = _64r; - __asm fldcw p; - } - - void initialize () - { - _clear87 (); - - _control87 ( _PC_24, MCW_PC ); - _control87 ( _RC_CHOP, MCW_RC ); - _24 = getFPUsw(); // 24, chop - _control87 ( _RC_NEAR, MCW_RC ); - _24r = getFPUsw(); // 24, rounding - - _control87 ( _PC_53, MCW_PC ); - _control87 ( _RC_CHOP, MCW_RC ); - _53 = getFPUsw(); // 53, chop - _control87 ( _RC_NEAR, MCW_RC ); - _53r = getFPUsw(); // 53, rounding - - _control87 ( _PC_64, MCW_PC ); - _control87 ( _RC_CHOP, MCW_RC ); - _64 = getFPUsw(); // 64, chop - _control87 ( _RC_NEAR, MCW_RC ); - _64r = getFPUsw(); // 64, rounding + _clear87(); + + _control87(_PC_24, MCW_PC); + _control87(_RC_CHOP, MCW_RC); + _24 = getFPUsw(); // 24, chop + _control87(_RC_NEAR, MCW_RC); + _24r = getFPUsw(); // 24, rounding + + _control87(_PC_53, MCW_PC); + _control87(_RC_CHOP, MCW_RC); + _53 = getFPUsw(); // 53, chop + _control87(_RC_NEAR, MCW_RC); + _53r = getFPUsw(); // 53, rounding + + _control87(_PC_64, MCW_PC); + _control87(_RC_CHOP, MCW_RC); + _64 = getFPUsw(); // 64, chop + _control87(_RC_NEAR, MCW_RC); + _64r = getFPUsw(); // 64, rounding #ifndef XRCORE_STATIC - m24r (); + m24r(); -#endif //XRCORE_STATIC +#endif //XRCORE_STATIC - ::Random.seed ( u32(CPU::GetCLK()%(1i64<<32i64)) ); - } + ::Random.seed(u32(CPU::GetCLK() % (1i64 << 32i64))); +} }; #endif -namespace CPU +namespace CPU +{ +XRCORE_API u64 clk_per_second; +XRCORE_API u64 clk_per_milisec; +XRCORE_API u64 clk_per_microsec; +XRCORE_API u64 clk_overhead; +XRCORE_API float clk_to_seconds; +XRCORE_API float clk_to_milisec; +XRCORE_API float clk_to_microsec; +XRCORE_API u64 qpc_freq = 0; +XRCORE_API u64 qpc_overhead = 0; +XRCORE_API u32 qpc_counter = 0; + +XRCORE_API _processor_info ID; + +XRCORE_API u64 QPC() { - XRCORE_API u64 clk_per_second ; - XRCORE_API u64 clk_per_milisec ; - XRCORE_API u64 clk_per_microsec; - XRCORE_API u64 clk_overhead ; - XRCORE_API float clk_to_seconds ; - XRCORE_API float clk_to_milisec ; - XRCORE_API float clk_to_microsec ; - XRCORE_API u64 qpc_freq = 0 ; - XRCORE_API u64 qpc_overhead = 0 ; - XRCORE_API u32 qpc_counter = 0 ; - - XRCORE_API _processor_info ID; - - XRCORE_API u64 QPC () { - u64 _dest ; - QueryPerformanceCounter ((PLARGE_INTEGER)&_dest); - qpc_counter ++ ; - return _dest ; - } + u64 _dest; + QueryPerformanceCounter((PLARGE_INTEGER)&_dest); + qpc_counter++; + return _dest; +} #ifdef M_BORLAND - u64 __fastcall GetCLK (void) - { - _asm db 0x0F; - _asm db 0x31; - } +u64 __fastcall GetCLK(void) +{ + _asm db 0x0F; + _asm db 0x31; +} #endif - void Detect () - { - // General CPU identification - if (!_cpuid (&ID)) - { - // Core.Fatal ("Fatal error: can't detect CPU/FPU."); - abort (); - } - - // Timers & frequency - u64 start,end; - u32 dwStart,dwTest; - - SetPriorityClass (GetCurrentProcess(),REALTIME_PRIORITY_CLASS); - - // Detect Freq - dwTest = timeGetTime(); - do { dwStart = timeGetTime(); } while (dwTest==dwStart); - start = GetCLK(); - while (timeGetTime()-dwStart<1000) ; - end = GetCLK(); - clk_per_second = end-start; - - // Detect RDTSC Overhead - clk_overhead = 0; - u64 dummy = 0; - for (int i=0; i<256; i++) { - start = GetCLK(); - clk_overhead += GetCLK()-start-dummy; - } - clk_overhead /= 256; - - // Detect QPC Overhead - QueryPerformanceFrequency ((PLARGE_INTEGER)&qpc_freq) ; - qpc_overhead = 0; - for (i=0; i<256; i++) { - start = QPC(); - qpc_overhead += QPC()-start-dummy; - } - qpc_overhead /= 256; - - SetPriorityClass (GetCurrentProcess(),NORMAL_PRIORITY_CLASS); - - clk_per_second -= clk_overhead; - clk_per_milisec = clk_per_second/1000; - clk_per_microsec = clk_per_milisec/1000; - - _control87 ( _PC_64, MCW_PC ); -// _control87 ( _RC_CHOP, MCW_RC ); - double a,b; - a = 1; b = double(clk_per_second); - clk_to_seconds = float(double(a/b)); - a = 1000; b = double(clk_per_second); - clk_to_milisec = float(double(a/b)); - a = 1000000;b = double(clk_per_second); - clk_to_microsec = float(double(a/b)); - } +void Detect() +{ + // General CPU identification + if (!_cpuid(&ID)) + { + // Core.Fatal ("Fatal error: can't detect CPU/FPU."); + abort(); + } + + // Timers & frequency + u64 start, end; + u32 dwStart, dwTest; + + SetPriorityClass(GetCurrentProcess(), REALTIME_PRIORITY_CLASS); + + // Detect Freq + dwTest = timeGetTime(); + do { dwStart = timeGetTime(); } + while (dwTest == dwStart); + start = GetCLK(); + while (timeGetTime() - dwStart < 1000); + end = GetCLK(); + clk_per_second = end - start; + + // Detect RDTSC Overhead + clk_overhead = 0; + u64 dummy = 0; + for (int i = 0; i < 256; i++) + { + start = GetCLK(); + clk_overhead += GetCLK() - start - dummy; + } + clk_overhead /= 256; + + // Detect QPC Overhead + QueryPerformanceFrequency((PLARGE_INTEGER)&qpc_freq); + qpc_overhead = 0; + for (i = 0; i < 256; i++) + { + start = QPC(); + qpc_overhead += QPC() - start - dummy; + } + qpc_overhead /= 256; + + SetPriorityClass(GetCurrentProcess(), NORMAL_PRIORITY_CLASS); + + clk_per_second -= clk_overhead; + clk_per_milisec = clk_per_second / 1000; + clk_per_microsec = clk_per_milisec / 1000; + + _control87(_PC_64, MCW_PC); + // _control87 ( _RC_CHOP, MCW_RC ); + double a, b; + a = 1; + b = double(clk_per_second); + clk_to_seconds = float(double(a / b)); + a = 1000; + b = double(clk_per_second); + clk_to_milisec = float(double(a / b)); + a = 1000000; + b = double(clk_per_second); + clk_to_microsec = float(double(a / b)); +} }; bool g_initialize_cpu_called = false; //------------------------------------------------------------------------------------ -void _initialize_cpu (void) +void _initialize_cpu(void) { - Msg("* Detected CPU: %s [%s], F%d/M%d/S%d, %.2f mhz, %d-clk 'rdtsc'", - CPU::ID.model_name,CPU::ID.v_name, - CPU::ID.family,CPU::ID.model,CPU::ID.stepping, - float(CPU::clk_per_second/u64(1000000)), - u32(CPU::clk_overhead) - ); - -// DUMP_PHASE; - - if (strstr(Core.Params,"-x86")) { - CPU::ID.feature &= ~_CPU_FEATURE_MMX ; - CPU::ID.feature &= ~_CPU_FEATURE_3DNOW ; - CPU::ID.feature &= ~_CPU_FEATURE_SSE ; - CPU::ID.feature &= ~_CPU_FEATURE_SSE2 ; - CPU::ID.feature &= ~_CPU_FEATURE_SSE3 ; - CPU::ID.feature &= ~_CPU_FEATURE_SSSE3 ; - CPU::ID.feature &= ~_CPU_FEATURE_SSE4_1 ; - CPU::ID.feature &= ~_CPU_FEATURE_SSE4_2 ; - }; - - string256 features; xr_strcpy(features,sizeof(features),"RDTSC"); - if (CPU::ID.feature&_CPU_FEATURE_MMX) xr_strcat(features,", MMX"); - if (CPU::ID.feature&_CPU_FEATURE_3DNOW) xr_strcat(features,", 3DNow!"); - if (CPU::ID.feature&_CPU_FEATURE_SSE) xr_strcat(features,", SSE"); - if (CPU::ID.feature&_CPU_FEATURE_SSE2) xr_strcat(features,", SSE2"); - if (CPU::ID.feature&_CPU_FEATURE_SSE3) xr_strcat(features,", SSE3"); - if (CPU::ID.feature&_CPU_FEATURE_SSSE3) xr_strcat(features,", SSSE3"); - if (CPU::ID.feature&_CPU_FEATURE_SSE4_1)xr_strcat(features,", SSE4.1"); - if (CPU::ID.feature&_CPU_FEATURE_SSE4_2)xr_strcat(features,", SSE4.2"); - if (CPU::ID.feature&_CPU_FEATURE_HTT) xr_strcat(features,", HTT"); - - Msg("* CPU features: %s" , features ); - Msg("* CPU cores/threads: %d/%d\n" , CPU::ID.n_cores , CPU::ID.n_threads ); - - Fidentity.identity (); // Identity matrix - Didentity.identity (); // Identity matrix - pvInitializeStatics (); // Lookup table for compressed normals - FPU::initialize (); - _initialize_cpu_thread (); - - g_initialize_cpu_called = true; + Msg("* Detected CPU: %s [%s], F%d/M%d/S%d, %.2f mhz, %d-clk 'rdtsc'", + CPU::ID.model_name, CPU::ID.v_name, + CPU::ID.family, CPU::ID.model, CPU::ID.stepping, + float(CPU::clk_per_second / u64(1000000)), + u32(CPU::clk_overhead) + ); + + // DUMP_PHASE; + + if (strstr(Core.Params, "-x86")) + { + CPU::ID.feature &= ~_CPU_FEATURE_MMX; + CPU::ID.feature &= ~_CPU_FEATURE_3DNOW; + CPU::ID.feature &= ~_CPU_FEATURE_SSE; + CPU::ID.feature &= ~_CPU_FEATURE_SSE2; + CPU::ID.feature &= ~_CPU_FEATURE_SSE3; + CPU::ID.feature &= ~_CPU_FEATURE_SSSE3; + CPU::ID.feature &= ~_CPU_FEATURE_SSE4_1; + CPU::ID.feature &= ~_CPU_FEATURE_SSE4_2; + }; + + string256 features; + xr_strcpy(features, sizeof(features), "RDTSC"); + if (CPU::ID.feature&_CPU_FEATURE_MMX) xr_strcat(features, ", MMX"); + if (CPU::ID.feature&_CPU_FEATURE_3DNOW) xr_strcat(features, ", 3DNow!"); + if (CPU::ID.feature&_CPU_FEATURE_SSE) xr_strcat(features, ", SSE"); + if (CPU::ID.feature&_CPU_FEATURE_SSE2) xr_strcat(features, ", SSE2"); + if (CPU::ID.feature&_CPU_FEATURE_SSE3) xr_strcat(features, ", SSE3"); + if (CPU::ID.feature&_CPU_FEATURE_SSSE3) xr_strcat(features, ", SSSE3"); + if (CPU::ID.feature&_CPU_FEATURE_SSE4_1)xr_strcat(features, ", SSE4.1"); + if (CPU::ID.feature&_CPU_FEATURE_SSE4_2)xr_strcat(features, ", SSE4.2"); + if (CPU::ID.feature&_CPU_FEATURE_HTT) xr_strcat(features, ", HTT"); + + Msg("* CPU features: %s", features); + Msg("* CPU cores/threads: %d/%d\n", CPU::ID.n_cores, CPU::ID.n_threads); + + Fidentity.identity(); // Identity matrix + Didentity.identity(); // Identity matrix + pvInitializeStatics(); // Lookup table for compressed normals + FPU::initialize(); + _initialize_cpu_thread(); + + g_initialize_cpu_called = true; } #ifdef M_BORLAND -void _initialize_cpu_thread () +void _initialize_cpu_thread() { } #else @@ -273,142 +294,149 @@ void _initialize_cpu_thread () #define _MM_FLUSH_ZERO_ON 0x8000 #define _MM_SET_FLUSH_ZERO_MODE(mode) _mm_setcsr((_mm_getcsr() & ~_MM_FLUSH_ZERO_MASK) | (mode)) #define _MM_SET_DENORMALS_ZERO_MODE(mode) _mm_setcsr((_mm_getcsr() & ~_MM_DENORMALS_ZERO_MASK) | (mode)) -static BOOL _denormals_are_zero_supported = TRUE; -extern void __cdecl _terminate (); -void debug_on_thread_spawn (); +static BOOL _denormals_are_zero_supported = TRUE; +extern void __cdecl _terminate(); +void debug_on_thread_spawn(); -void _initialize_cpu_thread () +void _initialize_cpu_thread() { - debug_on_thread_spawn (); + debug_on_thread_spawn(); #ifndef XRCORE_STATIC - // fpu & sse - FPU::m24r (); -#endif // XRCORE_STATIC - if (CPU::ID.feature&_CPU_FEATURE_SSE) { - //_mm_setcsr ( _mm_getcsr() | (_MM_FLUSH_ZERO_ON+_MM_DENORMALS_ZERO_ON) ); - _MM_SET_FLUSH_ZERO_MODE (_MM_FLUSH_ZERO_ON); - if (_denormals_are_zero_supported) { - __try { - _MM_SET_DENORMALS_ZERO_MODE (_MM_DENORMALS_ZERO_ON); - } __except(EXCEPTION_EXECUTE_HANDLER) { - _denormals_are_zero_supported = FALSE; - } - } - } + // fpu & sse + FPU::m24r(); +#endif // XRCORE_STATIC + if (CPU::ID.feature&_CPU_FEATURE_SSE) + { + //_mm_setcsr ( _mm_getcsr() | (_MM_FLUSH_ZERO_ON+_MM_DENORMALS_ZERO_ON) ); + _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON); + if (_denormals_are_zero_supported) + { + __try + { + _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON); + } + __except (EXCEPTION_EXECUTE_HANDLER) + { + _denormals_are_zero_supported = FALSE; + } + } + } } #endif -// threading API +// threading API #pragma pack(push,8) -struct THREAD_NAME { - DWORD dwType; - LPCSTR szName; - DWORD dwThreadID; - DWORD dwFlags; +struct THREAD_NAME +{ + DWORD dwType; + LPCSTR szName; + DWORD dwThreadID; + DWORD dwFlags; }; -void thread_name (const char* name) +void thread_name(const char* name) { - THREAD_NAME tn; - tn.dwType = 0x1000; - tn.szName = name; - tn.dwThreadID = DWORD(-1); - tn.dwFlags = 0; - __try - { - RaiseException(0x406D1388,0,sizeof(tn)/sizeof(DWORD),(DWORD*)&tn); - } - __except(EXCEPTION_CONTINUE_EXECUTION) - { - } + THREAD_NAME tn; + tn.dwType = 0x1000; + tn.szName = name; + tn.dwThreadID = DWORD(-1); + tn.dwFlags = 0; + __try + { + RaiseException(0x406D1388, 0, sizeof(tn) / sizeof(DWORD), (DWORD*)&tn); + } + __except (EXCEPTION_CONTINUE_EXECUTION) + { + } } #pragma pack(pop) -struct THREAD_STARTUP +struct THREAD_STARTUP { - thread_t* entry ; - char* name ; - void* args ; + thread_t* entry; + char* name; + void* args; }; -void __cdecl thread_entry (void* _params ) { - // initialize - THREAD_STARTUP* startup = (THREAD_STARTUP*)_params ; - thread_name (startup->name); - thread_t* entry = startup->entry; - void* arglist = startup->args; - xr_delete (startup); - _initialize_cpu_thread (); - - // call - entry (arglist); +void __cdecl thread_entry(void* _params) +{ + // initialize + THREAD_STARTUP* startup = (THREAD_STARTUP*)_params; + thread_name(startup->name); + thread_t* entry = startup->entry; + void* arglist = startup->args; + xr_delete(startup); + _initialize_cpu_thread(); + + // call + entry(arglist); } -void thread_spawn (thread_t* entry, const char* name, unsigned stack, void* arglist ) +void thread_spawn(thread_t* entry, const char* name, unsigned stack, void* arglist) { - Debug._initialize (false); + Debug._initialize(false); - THREAD_STARTUP* startup = xr_new (); - startup->entry = entry; - startup->name = (char*)name; - startup->args = arglist; - _beginthread (thread_entry,stack,startup); + THREAD_STARTUP* startup = xr_new(); + startup->entry = entry; + startup->name = (char*)name; + startup->args = arglist; + _beginthread(thread_entry, stack, startup); } -void spline1 ( float t, Fvector *p, Fvector *ret ) +void spline1(float t, Fvector* p, Fvector* ret) { - float t2 = t * t; - float t3 = t2 * t; - float m[4]; - - ret->x=0.0f; - ret->y=0.0f; - ret->z=0.0f; - m[0] = ( 0.5f * ( (-1.0f * t3) + ( 2.0f * t2) + (-1.0f * t) ) ); - m[1] = ( 0.5f * ( ( 3.0f * t3) + (-5.0f * t2) + ( 0.0f * t) + 2.0f ) ); - m[2] = ( 0.5f * ( (-3.0f * t3) + ( 4.0f * t2) + ( 1.0f * t) ) ); - m[3] = ( 0.5f * ( ( 1.0f * t3) + (-1.0f * t2) + ( 0.0f * t) ) ); - - for( int i=0; i<4; i++ ) - { - ret->x += p[i].x * m[i]; - ret->y += p[i].y * m[i]; - ret->z += p[i].z * m[i]; - } + float t2 = t * t; + float t3 = t2 * t; + float m[4]; + + ret->x = 0.0f; + ret->y = 0.0f; + ret->z = 0.0f; + m[0] = (0.5f * ((-1.0f * t3) + (2.0f * t2) + (-1.0f * t))); + m[1] = (0.5f * ((3.0f * t3) + (-5.0f * t2) + (0.0f * t) + 2.0f)); + m[2] = (0.5f * ((-3.0f * t3) + (4.0f * t2) + (1.0f * t))); + m[3] = (0.5f * ((1.0f * t3) + (-1.0f * t2) + (0.0f * t))); + + for (int i = 0; i < 4; i++) + { + ret->x += p[i].x * m[i]; + ret->y += p[i].y * m[i]; + ret->z += p[i].z * m[i]; + } } -void spline2( float t, Fvector *p, Fvector *ret ) +void spline2(float t, Fvector* p, Fvector* ret) { - float s= 1.0f - t; - float t2 = t * t; - float t3 = t2 * t; - float m[4]; - - m[0] = s*s*s; - m[1] = 3.0f*t3 - 6.0f*t2 + 4.0f; - m[2] = -3.0f*t3 + 3.0f*t2 + 3.0f*t +1; - m[3] = t3; - - ret->x = (p[0].x*m[0]+p[1].x*m[1]+p[2].x*m[2]+p[3].x*m[3])/6.0f; - ret->y = (p[0].y*m[0]+p[1].y*m[1]+p[2].y*m[2]+p[3].y*m[3])/6.0f; - ret->z = (p[0].z*m[0]+p[1].z*m[1]+p[2].z*m[2]+p[3].z*m[3])/6.0f; + float s = 1.0f - t; + float t2 = t * t; + float t3 = t2 * t; + float m[4]; + + m[0] = s*s*s; + m[1] = 3.0f*t3 - 6.0f*t2 + 4.0f; + m[2] = -3.0f*t3 + 3.0f*t2 + 3.0f*t + 1; + m[3] = t3; + + ret->x = (p[0].x*m[0] + p[1].x*m[1] + p[2].x*m[2] + p[3].x*m[3]) / 6.0f; + ret->y = (p[0].y*m[0] + p[1].y*m[1] + p[2].y*m[2] + p[3].y*m[3]) / 6.0f; + ret->z = (p[0].z*m[0] + p[1].z*m[1] + p[2].z*m[2] + p[3].z*m[3]) / 6.0f; } #define beta1 1.0f #define beta2 0.8f -void spline3( float t, Fvector *p, Fvector *ret ) +void spline3(float t, Fvector* p, Fvector* ret) { - float s= 1.0f - t; - float t2 = t * t; - float t3 = t2 * t; - float b12=beta1*beta2; - float b13=b12*beta1; - float delta=2.0f-b13+4.0f*b12+4.0f*beta1+beta2+2.0f; - float d=1.0f/delta; - float b0=2.0f*b13*d*s*s*s; - float b3=2.0f*t3*d; - float b1=d*(2*b13*t*(t2-3*t+3)+2*b12*(t3-3*t2+2)+2*beta1*(t3-3*t+2)+beta2*(2*t3-3*t2+1)); - float b2=d*(2*b12*t2*(-t+3)+2*beta1*t*(-t2+3)+beta2*t2*(-2*t+3)+2*(-t3+1)); - - ret->x = p[0].x*b0+p[1].x*b1+p[2].x*b2+p[3].x*b3; - ret->y = p[0].y*b0+p[1].y*b1+p[2].y*b2+p[3].y*b3; - ret->z = p[0].z*b0+p[1].z*b1+p[2].z*b2+p[3].z*b3; + float s = 1.0f - t; + float t2 = t * t; + float t3 = t2 * t; + float b12 = beta1*beta2; + float b13 = b12*beta1; + float delta = 2.0f - b13 + 4.0f*b12 + 4.0f*beta1 + beta2 + 2.0f; + float d = 1.0f / delta; + float b0 = 2.0f*b13*d*s*s*s; + float b3 = 2.0f*t3*d; + float b1 = d*(2 * b13*t*(t2 - 3 * t + 3) + 2 * b12*(t3 - 3 * t2 + 2) + 2 * beta1*(t3 - 3 * t + 2) + beta2*(2 * t3 - 3 * t2 + 1)); + float b2 = d*(2 * b12*t2*(-t + 3) + 2 * beta1*t*(-t2 + 3) + beta2*t2*(-2 * t + 3) + 2 * (-t3 + 1)); + + ret->x = p[0].x*b0 + p[1].x*b1 + p[2].x*b2 + p[3].x*b3; + ret->y = p[0].y*b0 + p[1].y*b1 + p[2].y*b2 + p[3].y*b3; + ret->z = p[0].z*b0 + p[1].z*b1 + p[2].z*b2 + p[3].z*b3; } diff --git a/src/xrCore/_math.h b/src/xrCore/_math.h index 435b5eb2e15..c23ec26f04f 100644 --- a/src/xrCore/_math.h +++ b/src/xrCore/_math.h @@ -3,61 +3,65 @@ #include "cpuid.h" -namespace FPU { - XRCORE_API void m24 (void); - XRCORE_API void m24r (void); - XRCORE_API void m53 (void); - XRCORE_API void m53r (void); - XRCORE_API void m64 (void); - XRCORE_API void m64r (void); +namespace FPU +{ +XRCORE_API void m24(void); +XRCORE_API void m24r(void); +XRCORE_API void m53(void); +XRCORE_API void m53r(void); +XRCORE_API void m64(void); +XRCORE_API void m64r(void); }; -namespace CPU { - XRCORE_API extern u64 clk_per_second ; - XRCORE_API extern u64 clk_per_milisec ; - XRCORE_API extern u64 clk_per_microsec ; - XRCORE_API extern u64 clk_overhead ; - XRCORE_API extern float clk_to_seconds ; - XRCORE_API extern float clk_to_milisec ; - XRCORE_API extern float clk_to_microsec ; - - XRCORE_API extern u64 qpc_freq ; - XRCORE_API extern u64 qpc_overhead ; - XRCORE_API extern u32 qpc_counter ; - - XRCORE_API extern _processor_info ID ; - XRCORE_API extern u64 QPC () ; +namespace CPU +{ +XRCORE_API extern u64 clk_per_second; +XRCORE_API extern u64 clk_per_milisec; +XRCORE_API extern u64 clk_per_microsec; +XRCORE_API extern u64 clk_overhead; +XRCORE_API extern float clk_to_seconds; +XRCORE_API extern float clk_to_milisec; +XRCORE_API extern float clk_to_microsec; + +XRCORE_API extern u64 qpc_freq; +XRCORE_API extern u64 qpc_overhead; +XRCORE_API extern u32 qpc_counter; + +XRCORE_API extern _processor_info ID; +XRCORE_API extern u64 QPC(); #ifdef M_VISUAL - #ifndef _M_AMD64 - #pragma warning(disable:4035) - IC u64 GetCLK(void) { - _asm _emit 0x0F; - _asm _emit 0x31; - } - #pragma warning(default:4035) - #else - IC u64 GetCLK(void) { - return __rdtsc(); - } - #endif +#ifndef _M_AMD64 +#pragma warning(disable:4035) +IC u64 GetCLK(void) +{ + _asm _emit 0x0F; + _asm _emit 0x31; +} +#pragma warning(default:4035) +#else +IC u64 GetCLK(void) +{ + return __rdtsc(); +} +#endif #endif #ifdef M_BORLAND - XRCORE_API u64 __fastcall GetCLK (void); +XRCORE_API u64 __fastcall GetCLK (void); #endif }; -extern XRCORE_API void _initialize_cpu (); -extern XRCORE_API void _initialize_cpu_thread (); +extern XRCORE_API void _initialize_cpu(); +extern XRCORE_API void _initialize_cpu_thread(); // threading -typedef void thread_t ( void * ); -extern XRCORE_API void thread_name ( const char* name); -extern XRCORE_API void thread_spawn ( - thread_t* entry, - const char* name, - unsigned stack, - void* arglist - ); +typedef void thread_t(void*); +extern XRCORE_API void thread_name(const char* name); +extern XRCORE_API void thread_spawn( + thread_t* entry, + const char* name, + unsigned stack, + void* arglist +); #endif //__XR_MATH_H__ diff --git a/src/xrCore/_matrix.h b/src/xrCore/_matrix.h index c664ab42bda..bcf34483eaf 100644 --- a/src/xrCore/_matrix.h +++ b/src/xrCore/_matrix.h @@ -1,23 +1,23 @@ #ifndef __M__ #define __M__ /* -* DirectX-compliant, ie row-column order, ie m[Row][Col]. -* Same as: -* m11 m12 m13 m14 first row. -* m21 m22 m23 m24 second row. -* m31 m32 m33 m34 third row. -* m41 m42 m43 m44 fourth row. -* Translation is (m41, m42, m43), (m14, m24, m34, m44) = (0, 0, 0, 1). -* Stored in memory as m11 m12 m13 m14 m21... +* DirectX-compliant, ie row-column order, ie m[Row][Col]. +* Same as: +* m11 m12 m13 m14 first row. +* m21 m22 m23 m24 second row. +* m31 m32 m33 m34 third row. +* m41 m42 m43 m44 fourth row. +* Translation is (m41, m42, m43), (m14, m24, m34, m44) = (0, 0, 0, 1). +* Stored in memory as m11 m12 m13 m14 m21... * -* Multiplication rules: +* Multiplication rules: * -* [x'y'z'1] = [xyz1][M] +* [x'y'z'1] = [xyz1][M] * -* x' = x*m11 + y*m21 + z*m31 + m41 -* y' = x*m12 + y*m22 + z*m32 + m42 -* z' = x*m13 + y*m23 + z*m33 + m43 -* 1' = 0 + 0 + 0 + m44 +* x' = x*m11 + y*m21 + z*m31 + m41 +* y' = x*m12 + y*m22 + z*m32 + m42 +* z' = x*m13 + y*m23 + z*m33 + m43 +* 1' = 0 + 0 + 0 + m44 */ // NOTE_1: positive angle means clockwise rotation @@ -26,592 +26,778 @@ // NOTE_4: The rotation sequence is ZXY template -struct _matrix { +struct _matrix +{ public: - typedef T TYPE; - typedef _matrix Self; - typedef Self& SelfRef; - typedef const Self& SelfCRef; - typedef _vector3 Tvector; + typedef T TYPE; + typedef _matrix Self; + typedef Self& SelfRef; + typedef const Self& SelfCRef; + typedef _vector3 Tvector; public: - union { - struct { // Direct definition + union + { + struct // Direct definition + { T _11, _12, _13, _14; T _21, _22, _23, _24; T _31, _32, _33, _34; T _41, _42, _43, _44; - }; - struct{ - Tvector i; T _14_; - Tvector j; T _24_; - Tvector k; T _34_; - Tvector c; T _44_; }; - T m[4][4]; // Array - }; - - // Class members - ICF SelfRef set (const Self &a) - { - i.set(a.i); _14_=a._14; - j.set(a.j); _24_=a._24; - k.set(a.k); _34_=a._34; - c.set(a.c); _44_=a._44; - return *this; - } - ICF SelfRef set (const Tvector& R,const Tvector& N,const Tvector& D,const Tvector& C) - { - i.set(R); _14_=0; - j.set(N); _24_=0; - k.set(D); _34_=0; - c.set(C); _44_=1; - return *this; - } - ICF SelfRef identity (void) - { - _11=1; _12=0; _13=0; _14=0; - _21=0; _22=1; _23=0; _24=0; - _31=0; _32=0; _33=1; _34=0; - _41=0; _42=0; _43=0; _44=1; - return *this; - } - IC SelfRef rotation (const _quaternion &Q); - ICF SelfRef mk_xform (const _quaternion &Q, const Tvector &V); - - // Multiply RES = A[4x4]*B[4x4] (WITH projection) - ICF SelfRef mul (const Self &A,const Self &B) - { - VERIFY ((this!=&A)&&(this!=&B)); - m[0][0] = A.m[0][0] * B.m[0][0] + A.m[1][0] * B.m[0][1] + A.m[2][0] * B.m[0][2] + A.m[3][0] * B.m[0][3]; - m[0][1] = A.m[0][1] * B.m[0][0] + A.m[1][1] * B.m[0][1] + A.m[2][1] * B.m[0][2] + A.m[3][1] * B.m[0][3]; - m[0][2] = A.m[0][2] * B.m[0][0] + A.m[1][2] * B.m[0][1] + A.m[2][2] * B.m[0][2] + A.m[3][2] * B.m[0][3]; - m[0][3] = A.m[0][3] * B.m[0][0] + A.m[1][3] * B.m[0][1] + A.m[2][3] * B.m[0][2] + A.m[3][3] * B.m[0][3]; - - m[1][0] = A.m[0][0] * B.m[1][0] + A.m[1][0] * B.m[1][1] + A.m[2][0] * B.m[1][2] + A.m[3][0] * B.m[1][3]; - m[1][1] = A.m[0][1] * B.m[1][0] + A.m[1][1] * B.m[1][1] + A.m[2][1] * B.m[1][2] + A.m[3][1] * B.m[1][3]; - m[1][2] = A.m[0][2] * B.m[1][0] + A.m[1][2] * B.m[1][1] + A.m[2][2] * B.m[1][2] + A.m[3][2] * B.m[1][3]; - m[1][3] = A.m[0][3] * B.m[1][0] + A.m[1][3] * B.m[1][1] + A.m[2][3] * B.m[1][2] + A.m[3][3] * B.m[1][3]; - - m[2][0] = A.m[0][0] * B.m[2][0] + A.m[1][0] * B.m[2][1] + A.m[2][0] * B.m[2][2] + A.m[3][0] * B.m[2][3]; - m[2][1] = A.m[0][1] * B.m[2][0] + A.m[1][1] * B.m[2][1] + A.m[2][1] * B.m[2][2] + A.m[3][1] * B.m[2][3]; - m[2][2] = A.m[0][2] * B.m[2][0] + A.m[1][2] * B.m[2][1] + A.m[2][2] * B.m[2][2] + A.m[3][2] * B.m[2][3]; - m[2][3] = A.m[0][3] * B.m[2][0] + A.m[1][3] * B.m[2][1] + A.m[2][3] * B.m[2][2] + A.m[3][3] * B.m[2][3]; - - m[3][0] = A.m[0][0] * B.m[3][0] + A.m[1][0] * B.m[3][1] + A.m[2][0] * B.m[3][2] + A.m[3][0] * B.m[3][3]; - m[3][1] = A.m[0][1] * B.m[3][0] + A.m[1][1] * B.m[3][1] + A.m[2][1] * B.m[3][2] + A.m[3][1] * B.m[3][3]; - m[3][2] = A.m[0][2] * B.m[3][0] + A.m[1][2] * B.m[3][1] + A.m[2][2] * B.m[3][2] + A.m[3][2] * B.m[3][3]; - m[3][3] = A.m[0][3] * B.m[3][0] + A.m[1][3] * B.m[3][1] + A.m[2][3] * B.m[3][2] + A.m[3][3] * B.m[3][3]; - return *this; - } - - // Multiply RES = A[4x3]*B[4x3] (no projection), faster than ordinary multiply - ICF SelfRef mul_43 (const Self &A,const Self &B) - { - VERIFY ((this!=&A)&&(this!=&B)); - m[0][0] = A.m[0][0] * B.m[0][0] + A.m[1][0] * B.m[0][1] + A.m[2][0] * B.m[0][2]; - m[0][1] = A.m[0][1] * B.m[0][0] + A.m[1][1] * B.m[0][1] + A.m[2][1] * B.m[0][2]; - m[0][2] = A.m[0][2] * B.m[0][0] + A.m[1][2] * B.m[0][1] + A.m[2][2] * B.m[0][2]; - m[0][3] = 0; - - m[1][0] = A.m[0][0] * B.m[1][0] + A.m[1][0] * B.m[1][1] + A.m[2][0] * B.m[1][2]; - m[1][1] = A.m[0][1] * B.m[1][0] + A.m[1][1] * B.m[1][1] + A.m[2][1] * B.m[1][2]; - m[1][2] = A.m[0][2] * B.m[1][0] + A.m[1][2] * B.m[1][1] + A.m[2][2] * B.m[1][2]; - m[1][3] = 0; - - m[2][0] = A.m[0][0] * B.m[2][0] + A.m[1][0] * B.m[2][1] + A.m[2][0] * B.m[2][2]; - m[2][1] = A.m[0][1] * B.m[2][0] + A.m[1][1] * B.m[2][1] + A.m[2][1] * B.m[2][2]; - m[2][2] = A.m[0][2] * B.m[2][0] + A.m[1][2] * B.m[2][1] + A.m[2][2] * B.m[2][2]; - m[2][3] = 0; - - m[3][0] = A.m[0][0] * B.m[3][0] + A.m[1][0] * B.m[3][1] + A.m[2][0] * B.m[3][2] + A.m[3][0]; - m[3][1] = A.m[0][1] * B.m[3][0] + A.m[1][1] * B.m[3][1] + A.m[2][1] * B.m[3][2] + A.m[3][1]; - m[3][2] = A.m[0][2] * B.m[3][0] + A.m[1][2] * B.m[3][1] + A.m[2][2] * B.m[3][2] + A.m[3][2]; - m[3][3] = 1; - return *this; - } - IC SelfRef mulA_44 ( const Self &A ) // mul after - { - Self B; B.set( *this ); mul ( A, B ); - return *this; + struct + { + Tvector i; + T _14_; + Tvector j; + T _24_; + Tvector k; + T _34_; + Tvector c; + T _44_; + }; + T m[4][4]; // Array + }; + + // Class members + ICF SelfRef set(const Self& a) + { + i.set(a.i); + _14_ = a._14; + j.set(a.j); + _24_ = a._24; + k.set(a.k); + _34_ = a._34; + c.set(a.c); + _44_ = a._44; + return *this; + } + ICF SelfRef set(const Tvector& R, const Tvector& N, const Tvector& D, const Tvector& C) + { + i.set(R); + _14_ = 0; + j.set(N); + _24_ = 0; + k.set(D); + _34_ = 0; + c.set(C); + _44_ = 1; + return *this; + } + ICF SelfRef identity(void) + { + _11 = 1; + _12 = 0; + _13 = 0; + _14 = 0; + _21 = 0; + _22 = 1; + _23 = 0; + _24 = 0; + _31 = 0; + _32 = 0; + _33 = 1; + _34 = 0; + _41 = 0; + _42 = 0; + _43 = 0; + _44 = 1; + return *this; + } + IC SelfRef rotation(const _quaternion& Q); + ICF SelfRef mk_xform(const _quaternion& Q, const Tvector& V); + + // Multiply RES = A[4x4]*B[4x4] (WITH projection) + ICF SelfRef mul(const Self& A, const Self& B) + { + VERIFY((this != &A) && (this != &B)); + m[0][0] = A.m[0][0] * B.m[0][0] + A.m[1][0] * B.m[0][1] + A.m[2][0] * B.m[0][2] + A.m[3][0] * B.m[0][3]; + m[0][1] = A.m[0][1] * B.m[0][0] + A.m[1][1] * B.m[0][1] + A.m[2][1] * B.m[0][2] + A.m[3][1] * B.m[0][3]; + m[0][2] = A.m[0][2] * B.m[0][0] + A.m[1][2] * B.m[0][1] + A.m[2][2] * B.m[0][2] + A.m[3][2] * B.m[0][3]; + m[0][3] = A.m[0][3] * B.m[0][0] + A.m[1][3] * B.m[0][1] + A.m[2][3] * B.m[0][2] + A.m[3][3] * B.m[0][3]; + + m[1][0] = A.m[0][0] * B.m[1][0] + A.m[1][0] * B.m[1][1] + A.m[2][0] * B.m[1][2] + A.m[3][0] * B.m[1][3]; + m[1][1] = A.m[0][1] * B.m[1][0] + A.m[1][1] * B.m[1][1] + A.m[2][1] * B.m[1][2] + A.m[3][1] * B.m[1][3]; + m[1][2] = A.m[0][2] * B.m[1][0] + A.m[1][2] * B.m[1][1] + A.m[2][2] * B.m[1][2] + A.m[3][2] * B.m[1][3]; + m[1][3] = A.m[0][3] * B.m[1][0] + A.m[1][3] * B.m[1][1] + A.m[2][3] * B.m[1][2] + A.m[3][3] * B.m[1][3]; + + m[2][0] = A.m[0][0] * B.m[2][0] + A.m[1][0] * B.m[2][1] + A.m[2][0] * B.m[2][2] + A.m[3][0] * B.m[2][3]; + m[2][1] = A.m[0][1] * B.m[2][0] + A.m[1][1] * B.m[2][1] + A.m[2][1] * B.m[2][2] + A.m[3][1] * B.m[2][3]; + m[2][2] = A.m[0][2] * B.m[2][0] + A.m[1][2] * B.m[2][1] + A.m[2][2] * B.m[2][2] + A.m[3][2] * B.m[2][3]; + m[2][3] = A.m[0][3] * B.m[2][0] + A.m[1][3] * B.m[2][1] + A.m[2][3] * B.m[2][2] + A.m[3][3] * B.m[2][3]; + + m[3][0] = A.m[0][0] * B.m[3][0] + A.m[1][0] * B.m[3][1] + A.m[2][0] * B.m[3][2] + A.m[3][0] * B.m[3][3]; + m[3][1] = A.m[0][1] * B.m[3][0] + A.m[1][1] * B.m[3][1] + A.m[2][1] * B.m[3][2] + A.m[3][1] * B.m[3][3]; + m[3][2] = A.m[0][2] * B.m[3][0] + A.m[1][2] * B.m[3][1] + A.m[2][2] * B.m[3][2] + A.m[3][2] * B.m[3][3]; + m[3][3] = A.m[0][3] * B.m[3][0] + A.m[1][3] * B.m[3][1] + A.m[2][3] * B.m[3][2] + A.m[3][3] * B.m[3][3]; + return *this; + } + + // Multiply RES = A[4x3]*B[4x3] (no projection), faster than ordinary multiply + ICF SelfRef mul_43(const Self& A, const Self& B) + { + VERIFY((this != &A) && (this != &B)); + m[0][0] = A.m[0][0] * B.m[0][0] + A.m[1][0] * B.m[0][1] + A.m[2][0] * B.m[0][2]; + m[0][1] = A.m[0][1] * B.m[0][0] + A.m[1][1] * B.m[0][1] + A.m[2][1] * B.m[0][2]; + m[0][2] = A.m[0][2] * B.m[0][0] + A.m[1][2] * B.m[0][1] + A.m[2][2] * B.m[0][2]; + m[0][3] = 0; + + m[1][0] = A.m[0][0] * B.m[1][0] + A.m[1][0] * B.m[1][1] + A.m[2][0] * B.m[1][2]; + m[1][1] = A.m[0][1] * B.m[1][0] + A.m[1][1] * B.m[1][1] + A.m[2][1] * B.m[1][2]; + m[1][2] = A.m[0][2] * B.m[1][0] + A.m[1][2] * B.m[1][1] + A.m[2][2] * B.m[1][2]; + m[1][3] = 0; + + m[2][0] = A.m[0][0] * B.m[2][0] + A.m[1][0] * B.m[2][1] + A.m[2][0] * B.m[2][2]; + m[2][1] = A.m[0][1] * B.m[2][0] + A.m[1][1] * B.m[2][1] + A.m[2][1] * B.m[2][2]; + m[2][2] = A.m[0][2] * B.m[2][0] + A.m[1][2] * B.m[2][1] + A.m[2][2] * B.m[2][2]; + m[2][3] = 0; + + m[3][0] = A.m[0][0] * B.m[3][0] + A.m[1][0] * B.m[3][1] + A.m[2][0] * B.m[3][2] + A.m[3][0]; + m[3][1] = A.m[0][1] * B.m[3][0] + A.m[1][1] * B.m[3][1] + A.m[2][1] * B.m[3][2] + A.m[3][1]; + m[3][2] = A.m[0][2] * B.m[3][0] + A.m[1][2] * B.m[3][1] + A.m[2][2] * B.m[3][2] + A.m[3][2]; + m[3][3] = 1; + return *this; + } + IC SelfRef mulA_44(const Self& A) // mul after + { + Self B; + B.set(*this); + mul(A, B); + return *this; }; - IC SelfRef mulB_44 ( const Self &B ) // mul before - { - Self A; A.set( *this ); mul ( A, B ); - return *this; - }; - ICF SelfRef mulA_43 ( const Self &A ) // mul after (no projection) - { - Self B; B.set( *this ); mul_43 ( A, B ); - return *this; + IC SelfRef mulB_44(const Self& B) // mul before + { + Self A; + A.set(*this); + mul(A, B); + return *this; }; - ICF SelfRef mulB_43 ( const Self &B ) // mul before (no projection) - { - Self A; A.set( *this ); mul_43 ( A, B ); - return *this; - }; - IC SelfRef invert ( const Self &a ) { // important: this is 4x3 invert, not the 4x4 one - // faster than self-invert - T fDetInv = ( a._11 * ( a._22 * a._33 - a._23 * a._32 ) - - a._12 * ( a._21 * a._33 - a._23 * a._31 ) + - a._13 * ( a._21 * a._32 - a._22 * a._31 ) ); - - VERIFY(_abs(fDetInv)>flt_zero); - fDetInv=1.0f/fDetInv; - - _11 = fDetInv * ( a._22 * a._33 - a._23 * a._32 ); - _12 = -fDetInv * ( a._12 * a._33 - a._13 * a._32 ); - _13 = fDetInv * ( a._12 * a._23 - a._13 * a._22 ); - _14 = 0.0f; - - _21 = -fDetInv * ( a._21 * a._33 - a._23 * a._31 ); - _22 = fDetInv * ( a._11 * a._33 - a._13 * a._31 ); - _23 = -fDetInv * ( a._11 * a._23 - a._13 * a._21 ); - _24 = 0.0f; - - _31 = fDetInv * ( a._21 * a._32 - a._22 * a._31 ); - _32 = -fDetInv * ( a._11 * a._32 - a._12 * a._31 ); - _33 = fDetInv * ( a._11 * a._22 - a._12 * a._21 ); - _34 = 0.0f; - - _41 = -( a._41 * _11 + a._42 * _21 + a._43 * _31 ); - _42 = -( a._41 * _12 + a._42 * _22 + a._43 * _32 ); - _43 = -( a._41 * _13 + a._42 * _23 + a._43 * _33 ); - _44 = 1.0f; - return *this; - } - - IC bool invert_b ( const Self &a ) { // important: this is 4x3 invert, not the 4x4 one - // faster than self-invert - T fDetInv = ( a._11 * ( a._22 * a._33 - a._23 * a._32 ) - - a._12 * ( a._21 * a._33 - a._23 * a._31 ) + - a._13 * ( a._21 * a._32 - a._22 * a._31 ) ); - - if (_abs(fDetInv)<=flt_zero) return false; - fDetInv=1.0f/fDetInv; - - _11 = fDetInv * ( a._22 * a._33 - a._23 * a._32 ); - _12 = -fDetInv * ( a._12 * a._33 - a._13 * a._32 ); - _13 = fDetInv * ( a._12 * a._23 - a._13 * a._22 ); - _14 = 0.0f; - - _21 = -fDetInv * ( a._21 * a._33 - a._23 * a._31 ); - _22 = fDetInv * ( a._11 * a._33 - a._13 * a._31 ); - _23 = -fDetInv * ( a._11 * a._23 - a._13 * a._21 ); - _24 = 0.0f; - - _31 = fDetInv * ( a._21 * a._32 - a._22 * a._31 ); - _32 = -fDetInv * ( a._11 * a._32 - a._12 * a._31 ); - _33 = fDetInv * ( a._11 * a._22 - a._12 * a._21 ); - _34 = 0.0f; - - _41 = -( a._41 * _11 + a._42 * _21 + a._43 * _31 ); - _42 = -( a._41 * _12 + a._42 * _22 + a._43 * _32 ); - _43 = -( a._41 * _13 + a._42 * _23 + a._43 * _33 ); - _44 = 1.0f; - return true; - } - - IC SelfRef invert () // slower than invert other matrix - { - Self a; a.set(*this); invert(a); - return *this; - } - IC SelfRef transpose (const Self &matSource) // faster version of transpose - { - _11=matSource._11; _12=matSource._21; _13=matSource._31; _14=matSource._41; - _21=matSource._12; _22=matSource._22; _23=matSource._32; _24=matSource._42; - _31=matSource._13; _32=matSource._23; _33=matSource._33; _34=matSource._43; - _41=matSource._14; _42=matSource._24; _43=matSource._34; _44=matSource._44; - return *this; - } - IC SelfRef transpose () // self transpose - slower - { - Self a; a.set(*this); transpose(a); - return *this; - } - IC SelfRef translate (const Tvector &Loc ) // setup translation matrix - { - identity(); c.set (Loc.x,Loc.y,Loc.z); - return *this; - } - IC SelfRef translate (T _x, T _y, T _z ) // setup translation matrix - { - identity(); c.set (_x,_y,_z); - return *this; - } - IC SelfRef translate_over(const Tvector &Loc ) // modify only translation - { - c.set (Loc.x,Loc.y,Loc.z); - return *this; - } - IC SelfRef translate_over(T _x, T _y, T _z) // modify only translation - { - c.set (_x,_y,_z); - return *this; - } - IC SelfRef translate_add(const Tvector &Loc ) // combine translation - { - c.add (Loc); - return *this; - } - IC SelfRef scale (T x, T y, T z ) // setup scale matrix - { - identity(); m[0][0]=x; m[1][1]=y; m[2][2]=z; - return *this; - } - IC SelfRef scale(const Tvector &v ) // setup scale matrix - { return scale(v.x,v.y,v.z); } - - IC SelfRef rotateX (T Angle ) // rotation about X axis - { - T cosa = _cos(Angle); - T sina = _sin(Angle); - i.set (1, 0, 0 ); _14 = 0; - j.set (0, cosa, sina); _24 = 0; - k.set (0, -sina, cosa); _34 = 0; - c.set (0, 0, 0 ); _44 = 1; - return *this; - } - IC SelfRef rotateY (T Angle ) // rotation about Y axis - { - T cosa = _cos(Angle); - T sina = _sin(Angle); - i.set (cosa, 0, -sina); _14 = 0; - j.set (0, 1, 0 ); _24 = 0; - k.set (sina, 0, cosa); _34 = 0; - c.set (0, 0, 0 ); _44 = 1; - return *this; - } - IC SelfRef rotateZ (T Angle ) // rotation about Z axis - { - T cosa = _cos(Angle); - T sina = _sin(Angle); - i.set (cosa, sina, 0 ); _14 = 0; - j.set (-sina, cosa, 0 ); _24 = 0; - k.set (0, 0, 1 ); _34 = 0; - c.set (0, 0, 0 ); _44 = 1; - return *this; - } - - IC SelfRef rotation ( const Tvector &vdir, const Tvector &vnorm ) { - Tvector vright; - vright.crossproduct (vnorm,vdir).normalize(); - m[0][0] = vright.x; m[0][1] = vright.y; m[0][2] = vright.z; m[0][3]=0; - m[1][0] = vnorm.x; m[1][1] = vnorm.y; m[1][2] = vnorm.z; m[1][3]=0; - m[2][0] = vdir.x; m[2][1] = vdir.y; m[2][2] = vdir.z; m[2][3]=0; - m[3][0] = 0; m[3][1] = 0; m[3][2] = 0; m[3][3]=1; - return *this; - } - - IC SelfRef mapXYZ () {i.set(1, 0, 0);_14=0;j.set(0, 1, 0);_24=0;k.set(0, 0, 1);_34=0;c.set(0, 0, 0);_44=1; return *this; } - IC SelfRef mapXZY () {i.set(1, 0, 0);_14=0;j.set(0, 0, 1);_24=0;k.set(0, 1, 0);_34=0;c.set(0, 0, 0);_44=1; return *this; } - IC SelfRef mapYXZ () {i.set(0, 1, 0);_14=0;j.set(1, 0, 0);_24=0;k.set(0, 0, 1);_34=0;c.set(0, 0, 0);_44=1; return *this; } - IC SelfRef mapYZX () {i.set(0, 1, 0);_14=0;j.set(0, 0, 1);_24=0;k.set(1, 0, 0);_34=0;c.set(0, 0, 0);_44=1; return *this; } - IC SelfRef mapZXY () {i.set(0, 0, 1);_14=0;j.set(1, 0, 0);_24=0;k.set(0, 1, 0);_34=0;c.set(0, 0, 0);_44=1; return *this; } - IC SelfRef mapZYX () {i.set(0, 0, 1);_14=0;j.set(0, 1, 0);_24=0;k.set(1, 0, 0);_34=0;c.set(0, 0, 0);_44=1; return *this; } - - IC SelfRef rotation ( const Tvector &axis, T Angle ) { - T Cosine = _cos(Angle); - T Sine = _sin(Angle); - m [0][0] = axis.x * axis.x + ( 1 - axis.x * axis.x) * Cosine; - m [0][1] = axis.x * axis.y * ( 1 - Cosine ) + axis.z * Sine; - m [0][2] = axis.x * axis.z * ( 1 - Cosine ) - axis.y * Sine; - m [0][3] = 0; - m [1][0] = axis.x * axis.y * ( 1 - Cosine ) - axis.z * Sine; - m [1][1] = axis.y * axis.y + ( 1 - axis.y * axis.y) * Cosine; - m [1][2] = axis.y * axis.z * ( 1 - Cosine ) + axis.x * Sine; - m [1][3] = 0; - m [2][0] = axis.x * axis.z * ( 1 - Cosine ) + axis.y * Sine; - m [2][1] = axis.y * axis.z * ( 1 - Cosine ) - axis.x * Sine; - m [2][2] = axis.z * axis.z + ( 1 - axis.z * axis.z) * Cosine; - m [2][3] = 0; m [3][0] = 0; m [3][1] = 0; - m [3][2] = 0; m [3][3] = 1; - return *this; - } - - // mirror X - IC SelfRef mirrorX () { - identity(); m[0][0] = -1; - return *this; - } - IC SelfRef mirrorX_over () { - m[0][0] = -1; - return *this; - } - IC SelfRef mirrorX_add () { - m[0][0] *= -1; - return *this; - } - - // mirror Y - IC SelfRef mirrorY () { - identity(); m [1][1] = -1; - return *this; - } - IC SelfRef mirrorY_over () { - m[1][1] = -1; - return *this; - } - IC SelfRef mirrorY_add () { - m[1][1] *= -1; - return *this; - } - - // mirror Z - IC SelfRef mirrorZ () { - identity(); m [2][2] = -1; - return *this; - } - IC SelfRef mirrorZ_over () { - m[2][2] = -1; - return *this; - } - IC SelfRef mirrorZ_add () { - m[2][2] *= -1; - return *this; - } - IC SelfRef mul( const Self &A, T v ) { - m[0][0] = A.m [0][0] * v; m[0][1] = A.m [0][1] * v; m[0][2] = A.m [0][2] * v; m[0][3] = A.m [0][3] * v; - m[1][0] = A.m [1][0] * v; m[1][1] = A.m [1][1] * v; m[1][2] = A.m [1][2] * v; m[1][3] = A.m [1][3] * v; - m[2][0] = A.m [2][0] * v; m[2][1] = A.m [2][1] * v; m[2][2] = A.m [2][2] * v; m[2][3] = A.m [2][3] * v; - m[3][0] = A.m [3][0] * v; m[3][1] = A.m [3][1] * v; m[3][2] = A.m [3][2] * v; m[3][3] = A.m [3][3] * v; - return *this; - } - IC SelfRef mul( T v ) { - m[0][0] *= v; m[0][1] *= v; m[0][2] *= v; m[0][3] *= v; - m[1][0] *= v; m[1][1] *= v; m[1][2] *= v; m[1][3] *= v; - m[2][0] *= v; m[2][1] *= v; m[2][2] *= v; m[2][3] *= v; - m[3][0] *= v; m[3][1] *= v; m[3][2] *= v; m[3][3] *= v; - return *this; - } - IC SelfRef div( const Self &A, T v ) { - VERIFY(_abs(v)>0.000001f); - return mul(A,1.0f/v); - } - IC SelfRef div( T v ) { - VERIFY(_abs(v)>0.000001f); - return mul(1.0f/v); - } - // fov - IC SelfRef build_projection (T fFOV, T fAspect, T fNearPlane, T fFarPlane) { - return build_projection_HAT (tanf(fFOV/2.f),fAspect,fNearPlane,fFarPlane); - } - // half_fov-angle-tangent - IC SelfRef build_projection_HAT (T HAT, T fAspect, T fNearPlane, T fFarPlane) - { - VERIFY( _abs(fFarPlane-fNearPlane) > EPS_S ); - VERIFY( _abs(HAT) > EPS_S ); - - T cot = T(1)/HAT; - T w = fAspect * cot; - T h = T(1) * cot; - T Q = fFarPlane / ( fFarPlane - fNearPlane ); - - _11 = w; _12 = 0; _13 = 0; _14 = 0; - _21 = 0; _22 = h; _23 = 0; _24 = 0; - _31 = 0; _32 = 0; _33 = Q; _34 = 1.0f; - _41 = 0; _42 = 0; _43 = -Q*fNearPlane;_44 = 0; - return *this; - } - IC SelfRef build_projection_ortho (T w, T h, T zn, T zf) - { - _11 = T(2)/w; _12 = 0; _13 = 0; _14 = 0; - _21 = 0; _22 = T(2)/h; _23 = 0; _24 = 0; - _31 = 0; _32 = 0; _33 = T(1)/(zf-zn); _34 = 0; - _41 = 0; _42 = 0; _43 = zn/(zn-zf); _44 = T(1); - return *this; - } - IC SelfRef build_camera(const Tvector &vFrom, const Tvector &vAt, const Tvector &vWorldUp) - { - // Get the z basis vector3, which points straight ahead. This is the - // difference from the eyepoint to the lookat point. - Tvector vView; - vView.sub (vAt,vFrom).normalize(); - - // Get the dot product, and calculate the projection of the z basis - // vector3 onto the up vector3. The projection is the y basis vector3. - T fDotProduct = vWorldUp.dotproduct( vView ); - - Tvector vUp; - vUp.mul (vView, -fDotProduct).add(vWorldUp).normalize(); - - // The x basis vector3 is found simply with the cross product of the y - // and z basis vectors - Tvector vRight; - vRight.crossproduct( vUp, vView ); - - // Start building the Device.mView. The first three rows contains the basis - // vectors used to rotate the view to point at the lookat point - _11 = vRight.x; _12 = vUp.x; _13 = vView.x; _14 = 0.0f; - _21 = vRight.y; _22 = vUp.y; _23 = vView.y; _24 = 0.0f; - _31 = vRight.z; _32 = vUp.z; _33 = vView.z; _34 = 0.0f; - - // Do the translation values (rotations are still about the eyepoint) - _41 = - vFrom.dotproduct(vRight); - _42 = - vFrom.dotproduct( vUp ); - _43 = - vFrom.dotproduct(vView ); - _44 = 1.0f; - return *this; - } - IC SelfRef build_camera_dir(const Tvector &vFrom, const Tvector &vView, const Tvector &vWorldUp) - { - // Get the dot product, and calculate the projection of the z basis - // vector3 onto the up vector3. The projection is the y basis vector3. - T fDotProduct = vWorldUp.dotproduct( vView ); - - Tvector vUp; - vUp.mul (vView, -fDotProduct).add(vWorldUp).normalize(); - - // The x basis vector3 is found simply with the cross product of the y - // and z basis vectors - Tvector vRight; - vRight.crossproduct( vUp, vView ); - - // Start building the Device.mView. The first three rows contains the basis - // vectors used to rotate the view to point at the lookat point - _11 = vRight.x; _12 = vUp.x; _13 = vView.x; _14 = 0.0f; - _21 = vRight.y; _22 = vUp.y; _23 = vView.y; _24 = 0.0f; - _31 = vRight.z; _32 = vUp.z; _33 = vView.z; _34 = 0.0f; - - // Do the translation values (rotations are still about the eyepoint) - _41 = - vFrom.dotproduct(vRight); - _42 = - vFrom.dotproduct( vUp ); - _43 = - vFrom.dotproduct(vView ); - _44 = 1.0f; - return *this; - } - - IC SelfRef inertion(const Self &mat, T v) - { - T iv = 1.f-v; - for (int i=0; i<4; i++) - { - m[i][0] = m[i][0]*v + mat.m[i][0]*iv; - m[i][1] = m[i][1]*v + mat.m[i][1]*iv; - m[i][2] = m[i][2]*v + mat.m[i][2]*iv; - m[i][3] = m[i][3]*v + mat.m[i][3]*iv; - } - return *this; - } - ICF void transform_tiny (Tvector &dest, const Tvector &v) const // preferred to use - { - dest.x = v.x*_11 + v.y*_21 + v.z*_31 + _41; - dest.y = v.x*_12 + v.y*_22 + v.z*_32 + _42; - dest.z = v.x*_13 + v.y*_23 + v.z*_33 + _43; - } - ICF void transform_tiny32 (Fvector2 &dest, const Tvector &v) const // preferred to use - { - dest.x = v.x*_11 + v.y*_21 + v.z*_31 + _41; - dest.y = v.x*_12 + v.y*_22 + v.z*_32 + _42; - } - ICF void transform_tiny23 (Tvector &dest, const Fvector2 &v) const // preferred to use - { - dest.x = v.x*_11 + v.y*_21 + _41; - dest.y = v.x*_12 + v.y*_22 + _42; - dest.z = v.x*_13 + v.y*_23 + _43; - } - ICF void transform_dir (Tvector &dest, const Tvector &v) const // preferred to use - { - dest.x = v.x*_11 + v.y*_21 + v.z*_31; - dest.y = v.x*_12 + v.y*_22 + v.z*_32; - dest.z = v.x*_13 + v.y*_23 + v.z*_33; - } - IC void transform (Fvector4 &dest, const Tvector &v) const // preferred to use - { - dest.w = v.x*_14 + v.y*_24 + v.z*_34 + _44; - dest.x = (v.x*_11 + v.y*_21 + v.z*_31 + _41)/dest.w; - dest.y = (v.x*_12 + v.y*_22 + v.z*_32 + _42)/dest.w; - dest.z = (v.x*_13 + v.y*_23 + v.z*_33 + _43)/dest.w; - } - IC void transform (Tvector &dest, const Tvector &v) const // preferred to use - { - T iw = 1.f/(v.x*_14 + v.y*_24 + v.z*_34 + _44); - dest.x = (v.x*_11 + v.y*_21 + v.z*_31 + _41)*iw; - dest.y = (v.x*_12 + v.y*_22 + v.z*_32 + _42)*iw; - dest.z = (v.x*_13 + v.y*_23 + v.z*_33 + _43)*iw; - } - - IC void transform (Fvector4 &dest, const Fvector4 &v) const // preferred to use - { - dest.w = v.x*_14 + v.y*_24 + v.z*_34 + v.w*_44; - dest.x = v.x*_11 + v.y*_21 + v.z*_31 + v.w*_41; - dest.y = v.x*_12 + v.y*_22 + v.z*_32 + v.w*_42; - dest.z = v.x*_13 + v.y*_23 + v.z*_33 + v.w*_43; - } - - ICF void transform_tiny (Tvector &v) const - { - Tvector res; - transform_tiny (res,v); - v.set (res); - } - IC void transform (Tvector &v) const - { - Tvector res; - transform (res,v); - v.set (res); - } - ICF void transform_dir (Tvector &v) const - { - Tvector res; - transform_dir (res,v); - v.set (res); - } - ICF SelfRef setHPB (T h, T p, T b) - { + ICF SelfRef mulA_43(const Self& A) // mul after (no projection) + { + Self B; + B.set(*this); + mul_43(A, B); + return *this; + }; + ICF SelfRef mulB_43(const Self& B) // mul before (no projection) + { + Self A; + A.set(*this); + mul_43(A, B); + return *this; + }; + IC SelfRef invert(const Self& a) // important: this is 4x3 invert, not the 4x4 one + { + // faster than self-invert + T fDetInv = (a._11 * (a._22 * a._33 - a._23 * a._32) - + a._12 * (a._21 * a._33 - a._23 * a._31) + + a._13 * (a._21 * a._32 - a._22 * a._31)); + + VERIFY(_abs(fDetInv) > flt_zero); + fDetInv = 1.0f / fDetInv; + + _11 = fDetInv * (a._22 * a._33 - a._23 * a._32); + _12 = -fDetInv * (a._12 * a._33 - a._13 * a._32); + _13 = fDetInv * (a._12 * a._23 - a._13 * a._22); + _14 = 0.0f; + + _21 = -fDetInv * (a._21 * a._33 - a._23 * a._31); + _22 = fDetInv * (a._11 * a._33 - a._13 * a._31); + _23 = -fDetInv * (a._11 * a._23 - a._13 * a._21); + _24 = 0.0f; + + _31 = fDetInv * (a._21 * a._32 - a._22 * a._31); + _32 = -fDetInv * (a._11 * a._32 - a._12 * a._31); + _33 = fDetInv * (a._11 * a._22 - a._12 * a._21); + _34 = 0.0f; + + _41 = -(a._41 * _11 + a._42 * _21 + a._43 * _31); + _42 = -(a._41 * _12 + a._42 * _22 + a._43 * _32); + _43 = -(a._41 * _13 + a._42 * _23 + a._43 * _33); + _44 = 1.0f; + return *this; + } + + IC bool invert_b(const Self& a) // important: this is 4x3 invert, not the 4x4 one + { + // faster than self-invert + T fDetInv = (a._11 * (a._22 * a._33 - a._23 * a._32) - + a._12 * (a._21 * a._33 - a._23 * a._31) + + a._13 * (a._21 * a._32 - a._22 * a._31)); + + if (_abs(fDetInv) <= flt_zero) return false; + fDetInv = 1.0f / fDetInv; + + _11 = fDetInv * (a._22 * a._33 - a._23 * a._32); + _12 = -fDetInv * (a._12 * a._33 - a._13 * a._32); + _13 = fDetInv * (a._12 * a._23 - a._13 * a._22); + _14 = 0.0f; + + _21 = -fDetInv * (a._21 * a._33 - a._23 * a._31); + _22 = fDetInv * (a._11 * a._33 - a._13 * a._31); + _23 = -fDetInv * (a._11 * a._23 - a._13 * a._21); + _24 = 0.0f; + + _31 = fDetInv * (a._21 * a._32 - a._22 * a._31); + _32 = -fDetInv * (a._11 * a._32 - a._12 * a._31); + _33 = fDetInv * (a._11 * a._22 - a._12 * a._21); + _34 = 0.0f; + + _41 = -(a._41 * _11 + a._42 * _21 + a._43 * _31); + _42 = -(a._41 * _12 + a._42 * _22 + a._43 * _32); + _43 = -(a._41 * _13 + a._42 * _23 + a._43 * _33); + _44 = 1.0f; + return true; + } + + IC SelfRef invert() // slower than invert other matrix + { + Self a; + a.set(*this); + invert(a); + return *this; + } + IC SelfRef transpose(const Self& matSource) // faster version of transpose + { + _11 = matSource._11; + _12 = matSource._21; + _13 = matSource._31; + _14 = matSource._41; + _21 = matSource._12; + _22 = matSource._22; + _23 = matSource._32; + _24 = matSource._42; + _31 = matSource._13; + _32 = matSource._23; + _33 = matSource._33; + _34 = matSource._43; + _41 = matSource._14; + _42 = matSource._24; + _43 = matSource._34; + _44 = matSource._44; + return *this; + } + IC SelfRef transpose() // self transpose - slower + { + Self a; + a.set(*this); + transpose(a); + return *this; + } + IC SelfRef translate(const Tvector& Loc) // setup translation matrix + { + identity(); + c.set(Loc.x, Loc.y, Loc.z); + return *this; + } + IC SelfRef translate(T _x, T _y, T _z) // setup translation matrix + { + identity(); + c.set(_x, _y, _z); + return *this; + } + IC SelfRef translate_over(const Tvector& Loc) // modify only translation + { + c.set(Loc.x, Loc.y, Loc.z); + return *this; + } + IC SelfRef translate_over(T _x, T _y, T _z) // modify only translation + { + c.set(_x, _y, _z); + return *this; + } + IC SelfRef translate_add(const Tvector& Loc) // combine translation + { + c.add(Loc); + return *this; + } + IC SelfRef scale(T x, T y, T z) // setup scale matrix + { + identity(); + m[0][0] = x; + m[1][1] = y; + m[2][2] = z; + return *this; + } + IC SelfRef scale(const Tvector& v) // setup scale matrix + { + return scale(v.x, v.y, v.z); + } + + IC SelfRef rotateX(T Angle) // rotation about X axis + { + T cosa = _cos(Angle); + T sina = _sin(Angle); + i.set(1, 0, 0); + _14 = 0; + j.set(0, cosa, sina); + _24 = 0; + k.set(0, -sina, cosa); + _34 = 0; + c.set(0, 0, 0); + _44 = 1; + return *this; + } + IC SelfRef rotateY(T Angle) // rotation about Y axis + { + T cosa = _cos(Angle); + T sina = _sin(Angle); + i.set(cosa, 0, -sina); + _14 = 0; + j.set(0, 1, 0); + _24 = 0; + k.set(sina, 0, cosa); + _34 = 0; + c.set(0, 0, 0); + _44 = 1; + return *this; + } + IC SelfRef rotateZ(T Angle) // rotation about Z axis + { + T cosa = _cos(Angle); + T sina = _sin(Angle); + i.set(cosa, sina, 0); + _14 = 0; + j.set(-sina, cosa, 0); + _24 = 0; + k.set(0, 0, 1); + _34 = 0; + c.set(0, 0, 0); + _44 = 1; + return *this; + } + + IC SelfRef rotation(const Tvector& vdir, const Tvector& vnorm) + { + Tvector vright; + vright.crossproduct(vnorm, vdir).normalize(); + m[0][0] = vright.x; + m[0][1] = vright.y; + m[0][2] = vright.z; + m[0][3] = 0; + m[1][0] = vnorm.x; + m[1][1] = vnorm.y; + m[1][2] = vnorm.z; + m[1][3] = 0; + m[2][0] = vdir.x; + m[2][1] = vdir.y; + m[2][2] = vdir.z; + m[2][3] = 0; + m[3][0] = 0; + m[3][1] = 0; + m[3][2] = 0; + m[3][3] = 1; + return *this; + } + + IC SelfRef mapXYZ() { i.set(1, 0, 0); _14 = 0; j.set(0, 1, 0); _24 = 0; k.set(0, 0, 1); _34 = 0; c.set(0, 0, 0); _44 = 1; return *this; } + IC SelfRef mapXZY() { i.set(1, 0, 0); _14 = 0; j.set(0, 0, 1); _24 = 0; k.set(0, 1, 0); _34 = 0; c.set(0, 0, 0); _44 = 1; return *this; } + IC SelfRef mapYXZ() { i.set(0, 1, 0); _14 = 0; j.set(1, 0, 0); _24 = 0; k.set(0, 0, 1); _34 = 0; c.set(0, 0, 0); _44 = 1; return *this; } + IC SelfRef mapYZX() { i.set(0, 1, 0); _14 = 0; j.set(0, 0, 1); _24 = 0; k.set(1, 0, 0); _34 = 0; c.set(0, 0, 0); _44 = 1; return *this; } + IC SelfRef mapZXY() { i.set(0, 0, 1); _14 = 0; j.set(1, 0, 0); _24 = 0; k.set(0, 1, 0); _34 = 0; c.set(0, 0, 0); _44 = 1; return *this; } + IC SelfRef mapZYX() { i.set(0, 0, 1); _14 = 0; j.set(0, 1, 0); _24 = 0; k.set(1, 0, 0); _34 = 0; c.set(0, 0, 0); _44 = 1; return *this; } + + IC SelfRef rotation(const Tvector& axis, T Angle) + { + T Cosine = _cos(Angle); + T Sine = _sin(Angle); + m[0][0] = axis.x * axis.x + (1 - axis.x * axis.x) * Cosine; + m[0][1] = axis.x * axis.y * (1 - Cosine) + axis.z * Sine; + m[0][2] = axis.x * axis.z * (1 - Cosine) - axis.y * Sine; + m[0][3] = 0; + m[1][0] = axis.x * axis.y * (1 - Cosine) - axis.z * Sine; + m[1][1] = axis.y * axis.y + (1 - axis.y * axis.y) * Cosine; + m[1][2] = axis.y * axis.z * (1 - Cosine) + axis.x * Sine; + m[1][3] = 0; + m[2][0] = axis.x * axis.z * (1 - Cosine) + axis.y * Sine; + m[2][1] = axis.y * axis.z * (1 - Cosine) - axis.x * Sine; + m[2][2] = axis.z * axis.z + (1 - axis.z * axis.z) * Cosine; + m[2][3] = 0; + m[3][0] = 0; + m[3][1] = 0; + m[3][2] = 0; + m[3][3] = 1; + return *this; + } + + // mirror X + IC SelfRef mirrorX() + { + identity(); + m[0][0] = -1; + return *this; + } + IC SelfRef mirrorX_over() + { + m[0][0] = -1; + return *this; + } + IC SelfRef mirrorX_add() + { + m[0][0] *= -1; + return *this; + } + + // mirror Y + IC SelfRef mirrorY() + { + identity(); + m[1][1] = -1; + return *this; + } + IC SelfRef mirrorY_over() + { + m[1][1] = -1; + return *this; + } + IC SelfRef mirrorY_add() + { + m[1][1] *= -1; + return *this; + } + + // mirror Z + IC SelfRef mirrorZ() + { + identity(); + m[2][2] = -1; + return *this; + } + IC SelfRef mirrorZ_over() + { + m[2][2] = -1; + return *this; + } + IC SelfRef mirrorZ_add() + { + m[2][2] *= -1; + return *this; + } + IC SelfRef mul(const Self& A, T v) + { + m[0][0] = A.m[0][0] * v; + m[0][1] = A.m[0][1] * v; + m[0][2] = A.m[0][2] * v; + m[0][3] = A.m[0][3] * v; + m[1][0] = A.m[1][0] * v; + m[1][1] = A.m[1][1] * v; + m[1][2] = A.m[1][2] * v; + m[1][3] = A.m[1][3] * v; + m[2][0] = A.m[2][0] * v; + m[2][1] = A.m[2][1] * v; + m[2][2] = A.m[2][2] * v; + m[2][3] = A.m[2][3] * v; + m[3][0] = A.m[3][0] * v; + m[3][1] = A.m[3][1] * v; + m[3][2] = A.m[3][2] * v; + m[3][3] = A.m[3][3] * v; + return *this; + } + IC SelfRef mul(T v) + { + m[0][0] *= v; + m[0][1] *= v; + m[0][2] *= v; + m[0][3] *= v; + m[1][0] *= v; + m[1][1] *= v; + m[1][2] *= v; + m[1][3] *= v; + m[2][0] *= v; + m[2][1] *= v; + m[2][2] *= v; + m[2][3] *= v; + m[3][0] *= v; + m[3][1] *= v; + m[3][2] *= v; + m[3][3] *= v; + return *this; + } + IC SelfRef div(const Self& A, T v) + { + VERIFY(_abs(v) > 0.000001f); + return mul(A, 1.0f / v); + } + IC SelfRef div(T v) + { + VERIFY(_abs(v) > 0.000001f); + return mul(1.0f / v); + } + // fov + IC SelfRef build_projection(T fFOV, T fAspect, T fNearPlane, T fFarPlane) + { + return build_projection_HAT(tanf(fFOV / 2.f), fAspect, fNearPlane, fFarPlane); + } + // half_fov-angle-tangent + IC SelfRef build_projection_HAT(T HAT, T fAspect, T fNearPlane, T fFarPlane) + { + VERIFY(_abs(fFarPlane - fNearPlane) > EPS_S); + VERIFY(_abs(HAT) > EPS_S); + + T cot = T(1) / HAT; + T w = fAspect * cot; + T h = T(1) * cot; + T Q = fFarPlane / (fFarPlane - fNearPlane); + + _11 = w; + _12 = 0; + _13 = 0; + _14 = 0; + _21 = 0; + _22 = h; + _23 = 0; + _24 = 0; + _31 = 0; + _32 = 0; + _33 = Q; + _34 = 1.0f; + _41 = 0; + _42 = 0; + _43 = -Q*fNearPlane; + _44 = 0; + return *this; + } + IC SelfRef build_projection_ortho(T w, T h, T zn, T zf) + { + _11 = T(2) / w; + _12 = 0; + _13 = 0; + _14 = 0; + _21 = 0; + _22 = T(2) / h; + _23 = 0; + _24 = 0; + _31 = 0; + _32 = 0; + _33 = T(1) / (zf - zn); + _34 = 0; + _41 = 0; + _42 = 0; + _43 = zn / (zn - zf); + _44 = T(1); + return *this; + } + IC SelfRef build_camera(const Tvector& vFrom, const Tvector& vAt, const Tvector& vWorldUp) + { + // Get the z basis vector3, which points straight ahead. This is the + // difference from the eyepoint to the lookat point. + Tvector vView; + vView.sub(vAt, vFrom).normalize(); + + // Get the dot product, and calculate the projection of the z basis + // vector3 onto the up vector3. The projection is the y basis vector3. + T fDotProduct = vWorldUp.dotproduct(vView); + + Tvector vUp; + vUp.mul(vView, -fDotProduct).add(vWorldUp).normalize(); + + // The x basis vector3 is found simply with the cross product of the y + // and z basis vectors + Tvector vRight; + vRight.crossproduct(vUp, vView); + + // Start building the Device.mView. The first three rows contains the basis + // vectors used to rotate the view to point at the lookat point + _11 = vRight.x; + _12 = vUp.x; + _13 = vView.x; + _14 = 0.0f; + _21 = vRight.y; + _22 = vUp.y; + _23 = vView.y; + _24 = 0.0f; + _31 = vRight.z; + _32 = vUp.z; + _33 = vView.z; + _34 = 0.0f; + + // Do the translation values (rotations are still about the eyepoint) + _41 = -vFrom.dotproduct(vRight); + _42 = -vFrom.dotproduct(vUp); + _43 = -vFrom.dotproduct(vView); + _44 = 1.0f; + return *this; + } + IC SelfRef build_camera_dir(const Tvector& vFrom, const Tvector& vView, const Tvector& vWorldUp) + { + // Get the dot product, and calculate the projection of the z basis + // vector3 onto the up vector3. The projection is the y basis vector3. + T fDotProduct = vWorldUp.dotproduct(vView); + + Tvector vUp; + vUp.mul(vView, -fDotProduct).add(vWorldUp).normalize(); + + // The x basis vector3 is found simply with the cross product of the y + // and z basis vectors + Tvector vRight; + vRight.crossproduct(vUp, vView); + + // Start building the Device.mView. The first three rows contains the basis + // vectors used to rotate the view to point at the lookat point + _11 = vRight.x; + _12 = vUp.x; + _13 = vView.x; + _14 = 0.0f; + _21 = vRight.y; + _22 = vUp.y; + _23 = vView.y; + _24 = 0.0f; + _31 = vRight.z; + _32 = vUp.z; + _33 = vView.z; + _34 = 0.0f; + + // Do the translation values (rotations are still about the eyepoint) + _41 = -vFrom.dotproduct(vRight); + _42 = -vFrom.dotproduct(vUp); + _43 = -vFrom.dotproduct(vView); + _44 = 1.0f; + return *this; + } + + IC SelfRef inertion(const Self& mat, T v) + { + T iv = 1.f - v; + for (int i = 0; i < 4; i++) + { + m[i][0] = m[i][0] * v + mat.m[i][0] * iv; + m[i][1] = m[i][1] * v + mat.m[i][1] * iv; + m[i][2] = m[i][2] * v + mat.m[i][2] * iv; + m[i][3] = m[i][3] * v + mat.m[i][3] * iv; + } + return *this; + } + ICF void transform_tiny(Tvector& dest, const Tvector& v) const // preferred to use + { + dest.x = v.x*_11 + v.y*_21 + v.z*_31 + _41; + dest.y = v.x*_12 + v.y*_22 + v.z*_32 + _42; + dest.z = v.x*_13 + v.y*_23 + v.z*_33 + _43; + } + ICF void transform_tiny32(Fvector2& dest, const Tvector& v) const // preferred to use + { + dest.x = v.x*_11 + v.y*_21 + v.z*_31 + _41; + dest.y = v.x*_12 + v.y*_22 + v.z*_32 + _42; + } + ICF void transform_tiny23(Tvector& dest, const Fvector2& v) const // preferred to use + { + dest.x = v.x*_11 + v.y*_21 + _41; + dest.y = v.x*_12 + v.y*_22 + _42; + dest.z = v.x*_13 + v.y*_23 + _43; + } + ICF void transform_dir(Tvector& dest, const Tvector& v) const // preferred to use + { + dest.x = v.x*_11 + v.y*_21 + v.z*_31; + dest.y = v.x*_12 + v.y*_22 + v.z*_32; + dest.z = v.x*_13 + v.y*_23 + v.z*_33; + } + IC void transform(Fvector4& dest, const Tvector& v) const // preferred to use + { + dest.w = v.x*_14 + v.y*_24 + v.z*_34 + _44; + dest.x = (v.x*_11 + v.y*_21 + v.z*_31 + _41) / dest.w; + dest.y = (v.x*_12 + v.y*_22 + v.z*_32 + _42) / dest.w; + dest.z = (v.x*_13 + v.y*_23 + v.z*_33 + _43) / dest.w; + } + IC void transform(Tvector& dest, const Tvector& v) const // preferred to use + { + T iw = 1.f / (v.x*_14 + v.y*_24 + v.z*_34 + _44); + dest.x = (v.x*_11 + v.y*_21 + v.z*_31 + _41)*iw; + dest.y = (v.x*_12 + v.y*_22 + v.z*_32 + _42)*iw; + dest.z = (v.x*_13 + v.y*_23 + v.z*_33 + _43)*iw; + } + + IC void transform(Fvector4& dest, const Fvector4& v) const // preferred to use + { + dest.w = v.x*_14 + v.y*_24 + v.z*_34 + v.w*_44; + dest.x = v.x*_11 + v.y*_21 + v.z*_31 + v.w*_41; + dest.y = v.x*_12 + v.y*_22 + v.z*_32 + v.w*_42; + dest.z = v.x*_13 + v.y*_23 + v.z*_33 + v.w*_43; + } + + ICF void transform_tiny(Tvector& v) const + { + Tvector res; + transform_tiny(res, v); + v.set(res); + } + IC void transform(Tvector& v) const + { + Tvector res; + transform(res, v); + v.set(res); + } + ICF void transform_dir(Tvector& v) const + { + Tvector res; + transform_dir(res, v); + v.set(res); + } + ICF SelfRef setHPB(T h, T p, T b) + { T _ch, _cp, _cb, _sh, _sp, _sb, _cc, _cs, _sc, _ss; - _sh = _sin(h); _ch = _cos(h); - _sp = _sin(p); _cp = _cos(p); - _sb = _sin(b); _cb = _cos(b); - _cc = _ch*_cb; _cs = _ch*_sb; _sc = _sh*_cb; _ss = _sh*_sb; - - i.set(_cc-_sp*_ss, -_cp*_sb, _sp*_cs+_sc ); _14_=0; - j.set(_sp*_sc+_cs, _cp*_cb, _ss-_sp*_cc ); _24_=0; - k.set(-_cp*_sh, _sp, _cp*_ch ); _34_=0; - c.set(0, 0, 0 ); _44_=1; - return *this; - } - IC SelfRef setXYZ (T x, T y, T z) {return setHPB(y,x,z);} - IC SelfRef setXYZ (Tvector const& xyz) {return setHPB(xyz.y,xyz.x,xyz.z);} - IC SelfRef setXYZi (T x, T y, T z) {return setHPB(-y,-x,-z);} - IC SelfRef setXYZi (Tvector const& xyz) {return setHPB(-xyz.y,-xyz.x,-xyz.z);} - // - IC void getHPB (T& h, T& p, T& b) const - { + _sh = _sin(h); + _ch = _cos(h); + _sp = _sin(p); + _cp = _cos(p); + _sb = _sin(b); + _cb = _cos(b); + _cc = _ch*_cb; + _cs = _ch*_sb; + _sc = _sh*_cb; + _ss = _sh*_sb; + + i.set(_cc - _sp*_ss, -_cp*_sb, _sp*_cs + _sc); + _14_ = 0; + j.set(_sp*_sc + _cs, _cp*_cb, _ss - _sp*_cc); + _24_ = 0; + k.set(-_cp*_sh, _sp, _cp*_ch); + _34_ = 0; + c.set(0, 0, 0); + _44_ = 1; + return *this; + } + IC SelfRef setXYZ(T x, T y, T z) { return setHPB(y, x, z); } + IC SelfRef setXYZ(Tvector const& xyz) { return setHPB(xyz.y, xyz.x, xyz.z); } + IC SelfRef setXYZi(T x, T y, T z) { return setHPB(-y, -x, -z); } + IC SelfRef setXYZi(Tvector const& xyz) { return setHPB(-xyz.y, -xyz.x, -xyz.z); } + // + IC void getHPB(T& h, T& p, T& b) const + { T cy = _sqrt(j.y*j.y + i.y*i.y); - if (cy > 16.0f*type_epsilon(T)) { - h = (T) -atan2(k.x, k.z); - p = (T) -atan2(-k.y, cy); - b = (T) -atan2(i.y, j.y); - } else { - h = (T) -atan2(-i.z, i.x); - p = (T) -atan2(-k.y, cy); + if (cy > 16.0f*type_epsilon(T)) + { + h = (T)-atan2(k.x, k.z); + p = (T)-atan2(-k.y, cy); + b = (T)-atan2(i.y, j.y); + } + else + { + h = (T)-atan2(-i.z, i.x); + p = (T)-atan2(-k.y, cy); b = 0; } } - IC void getHPB (Tvector& hpb) const{getHPB(hpb.x,hpb.y,hpb.z);} - IC void getXYZ (T& x, T& y, T& z) const{getHPB(y,x,z);} - IC void getXYZ (Tvector& xyz) const{getXYZ(xyz.x,xyz.y,xyz.z);} - IC void getXYZi (T& x, T& y, T& z) const{getHPB(y,x,z);x*=-1.f;y*=-1.f;z*=-1.f;} - IC void getXYZi (Tvector& xyz) const{getXYZ(xyz.x,xyz.y,xyz.z);xyz.mul(-1.f);} + IC void getHPB(Tvector& hpb) const { getHPB(hpb.x, hpb.y, hpb.z); } + IC void getXYZ(T& x, T& y, T& z) const { getHPB(y, x, z); } + IC void getXYZ(Tvector& xyz) const { getXYZ(xyz.x, xyz.y, xyz.z); } + IC void getXYZi(T& x, T& y, T& z) const { getHPB(y, x, z); x *= -1.f; y *= -1.f; z *= -1.f; } + IC void getXYZi(Tvector& xyz) const { getXYZ(xyz.x, xyz.y, xyz.z); xyz.mul(-1.f); } }; -typedef _matrix Fmatrix; -typedef _matrix Dmatrix; +typedef _matrix Fmatrix; +typedef _matrix Dmatrix; template -BOOL _valid (const _matrix& m) -{ - return - _valid(m.i) && _valid(m._14_) && - _valid(m.j) && _valid(m._24_) && - _valid(m.k) && _valid(m._34_) && - _valid(m.c) && _valid(m._44_) - ; +BOOL _valid(const _matrix& m) +{ + return + _valid(m.i) && _valid(m._14_) && + _valid(m.j) && _valid(m._24_) && + _valid(m.k) && _valid(m._34_) && + _valid(m.c) && _valid(m._44_) + ; } -extern XRCORE_API Fmatrix Fidentity; -extern XRCORE_API Dmatrix Didentity; +extern XRCORE_API Fmatrix Fidentity; +extern XRCORE_API Dmatrix Didentity; #endif diff --git a/src/xrCore/_matrix33.h b/src/xrCore/_matrix33.h index 456fcfb80ee..b630b6f1378 100644 --- a/src/xrCore/_matrix33.h +++ b/src/xrCore/_matrix33.h @@ -2,137 +2,172 @@ #define _matrix33H_ template -struct _matrix33{ +struct _matrix33 +{ public: - typedef _matrix33Self; - typedef Self& SelfRef; - typedef const Self& SelfCRef; - typedef _vector3 Tvector; + typedef _matrix33Self; + typedef Self& SelfRef; + typedef const Self& SelfCRef; + typedef _vector3 Tvector; public: - union { - struct { // Direct definition + union + { + struct // Direct definition + { T _11, _12, _13; T _21, _22, _23; T _31, _32, _33; - }; - struct { - Tvector i; - Tvector j; - Tvector k; }; - float m[3][3]; // Array - }; - // Class members - IC SelfRef set_rapid(const _matrix &a) - { - m[0][0] = a.m[0][0]; m[0][1] = a.m[0][1]; m[0][2] = -a.m[0][2]; - m[1][0] = a.m[1][0]; m[1][1] = a.m[1][1]; m[1][2] = -a.m[1][2]; - m[2][0] = -a.m[2][0]; m[2][1] = -a.m[2][1]; m[2][2] = a.m[2][2]; - return *this; - } - IC SelfRef set(SelfCRef a) - { - CopyMemory(this,&a,9*sizeof(float)); - return *this; - } - IC SelfRef set(const _matrix &a) - { - _11=a._11; _12=a._12; _13=a._13; - _21=a._21; _22=a._22; _23=a._23; - _31=a._31; _32=a._32; _33=a._33; - return *this; - } - IC SelfRef identity(void) { - _11=1.f; _12=0.f; _13=0.f; - _21=0.f; _22=1.f; _23=0.f; - _31=0.f; _32=0.f; _33=1.f; - return *this; - } + struct + { + Tvector i; + Tvector j; + Tvector k; + }; + float m[3][3]; // Array + }; + // Class members + IC SelfRef set_rapid(const _matrix& a) + { + m[0][0] = a.m[0][0]; + m[0][1] = a.m[0][1]; + m[0][2] = -a.m[0][2]; + m[1][0] = a.m[1][0]; + m[1][1] = a.m[1][1]; + m[1][2] = -a.m[1][2]; + m[2][0] = -a.m[2][0]; + m[2][1] = -a.m[2][1]; + m[2][2] = a.m[2][2]; + return *this; + } + IC SelfRef set(SelfCRef a) + { + CopyMemory(this, &a, 9 * sizeof(float)); + return *this; + } + IC SelfRef set(const _matrix& a) + { + _11 = a._11; + _12 = a._12; + _13 = a._13; + _21 = a._21; + _22 = a._22; + _23 = a._23; + _31 = a._31; + _32 = a._32; + _33 = a._33; + return *this; + } + IC SelfRef identity(void) + { + _11 = 1.f; + _12 = 0.f; + _13 = 0.f; + _21 = 0.f; + _22 = 1.f; + _23 = 0.f; + _31 = 0.f; + _32 = 0.f; + _33 = 1.f; + return *this; + } - IC SelfRef transpose(SelfCRef matSource) // faster version of transpose - { - _11=matSource._11; _12=matSource._21; _13=matSource._31; - _21=matSource._12; _22=matSource._22; _23=matSource._32; - _31=matSource._13; _32=matSource._23; _33=matSource._33; - return *this; - } - IC SelfRef transpose(const _matrix &matSource) // faster version of transpose - { - _11=matSource._11; _12=matSource._21; _13=matSource._31; - _21=matSource._12; _22=matSource._22; _23=matSource._32; - _31=matSource._13; _32=matSource._23; _33=matSource._33; - return *this; - } - IC SelfRef transpose(void) // self transpose - slower - { - _matrix33 a; - CopyMemory(&a,this,9*sizeof(float)); // save matrix - transpose(a); - return *this; - } + IC SelfRef transpose(SelfCRef matSource) // faster version of transpose + { + _11 = matSource._11; + _12 = matSource._21; + _13 = matSource._31; + _21 = matSource._12; + _22 = matSource._22; + _23 = matSource._32; + _31 = matSource._13; + _32 = matSource._23; + _33 = matSource._33; + return *this; + } + IC SelfRef transpose(const _matrix& matSource) // faster version of transpose + { + _11 = matSource._11; + _12 = matSource._21; + _13 = matSource._31; + _21 = matSource._12; + _22 = matSource._22; + _23 = matSource._32; + _31 = matSource._13; + _32 = matSource._23; + _33 = matSource._33; + return *this; + } + IC SelfRef transpose(void) // self transpose - slower + { + _matrix33 a; + CopyMemory(&a, this, 9 * sizeof(float)); // save matrix + transpose(a); + return *this; + } IC SelfRef MxM(SelfCRef M1, SelfCRef M2) { - m[0][0] = ( M1.m[0][0] * M2.m[0][0] + - M1.m[0][1] * M2.m[1][0] + - M1.m[0][2] * M2.m[2][0]); - m[1][0] = ( M1.m[1][0] * M2.m[0][0] + - M1.m[1][1] * M2.m[1][0] + - M1.m[1][2] * M2.m[2][0]); - m[2][0] = ( M1.m[2][0] * M2.m[0][0] + - M1.m[2][1] * M2.m[1][0] + - M1.m[2][2] * M2.m[2][0]); - m[0][1] = ( M1.m[0][0] * M2.m[0][1] + - M1.m[0][1] * M2.m[1][1] + - M1.m[0][2] * M2.m[2][1]); - m[1][1] = ( M1.m[1][0] * M2.m[0][1] + - M1.m[1][1] * M2.m[1][1] + - M1.m[1][2] * M2.m[2][1]); - m[2][1] = ( M1.m[2][0] * M2.m[0][1] + - M1.m[2][1] * M2.m[1][1] + - M1.m[2][2] * M2.m[2][1]); - m[0][2] = ( M1.m[0][0] * M2.m[0][2] + - M1.m[0][1] * M2.m[1][2] + - M1.m[0][2] * M2.m[2][2]); - m[1][2] = ( M1.m[1][0] * M2.m[0][2] + - M1.m[1][1] * M2.m[1][2] + - M1.m[1][2] * M2.m[2][2]); - m[2][2] = ( M1.m[2][0] * M2.m[0][2] + - M1.m[2][1] * M2.m[1][2] + - M1.m[2][2] * M2.m[2][2]); - return *this; - } + m[0][0] = (M1.m[0][0] * M2.m[0][0] + + M1.m[0][1] * M2.m[1][0] + + M1.m[0][2] * M2.m[2][0]); + m[1][0] = (M1.m[1][0] * M2.m[0][0] + + M1.m[1][1] * M2.m[1][0] + + M1.m[1][2] * M2.m[2][0]); + m[2][0] = (M1.m[2][0] * M2.m[0][0] + + M1.m[2][1] * M2.m[1][0] + + M1.m[2][2] * M2.m[2][0]); + m[0][1] = (M1.m[0][0] * M2.m[0][1] + + M1.m[0][1] * M2.m[1][1] + + M1.m[0][2] * M2.m[2][1]); + m[1][1] = (M1.m[1][0] * M2.m[0][1] + + M1.m[1][1] * M2.m[1][1] + + M1.m[1][2] * M2.m[2][1]); + m[2][1] = (M1.m[2][0] * M2.m[0][1] + + M1.m[2][1] * M2.m[1][1] + + M1.m[2][2] * M2.m[2][1]); + m[0][2] = (M1.m[0][0] * M2.m[0][2] + + M1.m[0][1] * M2.m[1][2] + + M1.m[0][2] * M2.m[2][2]); + m[1][2] = (M1.m[1][0] * M2.m[0][2] + + M1.m[1][1] * M2.m[1][2] + + M1.m[1][2] * M2.m[2][2]); + m[2][2] = (M1.m[2][0] * M2.m[0][2] + + M1.m[2][1] * M2.m[1][2] + + M1.m[2][2] * M2.m[2][2]); + return *this; + } IC SelfRef MTxM(SelfCRef M1, SelfCRef M2) { - m[0][0] = ( M1.m[0][0] * M2.m[0][0] + - M1.m[1][0] * M2.m[1][0] + - M1.m[2][0] * M2.m[2][0]); - m[1][0] = ( M1.m[0][1] * M2.m[0][0] + - M1.m[1][1] * M2.m[1][0] + - M1.m[2][1] * M2.m[2][0]); - m[2][0] = ( M1.m[0][2] * M2.m[0][0] + - M1.m[1][2] * M2.m[1][0] + - M1.m[2][2] * M2.m[2][0]); - m[0][1] = ( M1.m[0][0] * M2.m[0][1] + - M1.m[1][0] * M2.m[1][1] + - M1.m[2][0] * M2.m[2][1]); - m[1][1] = ( M1.m[0][1] * M2.m[0][1] + - M1.m[1][1] * M2.m[1][1] + - M1.m[2][1] * M2.m[2][1]); - m[2][1] = ( M1.m[0][2] * M2.m[0][1] + - M1.m[1][2] * M2.m[1][1] + - M1.m[2][2] * M2.m[2][1]); - m[0][2] = ( M1.m[0][0] * M2.m[0][2] + - M1.m[1][0] * M2.m[1][2] + - M1.m[2][0] * M2.m[2][2]); - m[1][2] = ( M1.m[0][1] * M2.m[0][2] + - M1.m[1][1] * M2.m[1][2] + - M1.m[2][1] * M2.m[2][2]); - m[2][2] = ( M1.m[0][2] * M2.m[0][2] + - M1.m[1][2] * M2.m[1][2] + - M1.m[2][2] * M2.m[2][2]); - return *this; + m[0][0] = (M1.m[0][0] * M2.m[0][0] + + M1.m[1][0] * M2.m[1][0] + + M1.m[2][0] * M2.m[2][0]); + m[1][0] = (M1.m[0][1] * M2.m[0][0] + + M1.m[1][1] * M2.m[1][0] + + M1.m[2][1] * M2.m[2][0]); + m[2][0] = (M1.m[0][2] * M2.m[0][0] + + M1.m[1][2] * M2.m[1][0] + + M1.m[2][2] * M2.m[2][0]); + m[0][1] = (M1.m[0][0] * M2.m[0][1] + + M1.m[1][0] * M2.m[1][1] + + M1.m[2][0] * M2.m[2][1]); + m[1][1] = (M1.m[0][1] * M2.m[0][1] + + M1.m[1][1] * M2.m[1][1] + + M1.m[2][1] * M2.m[2][1]); + m[2][1] = (M1.m[0][2] * M2.m[0][1] + + M1.m[1][2] * M2.m[1][1] + + M1.m[2][2] * M2.m[2][1]); + m[0][2] = (M1.m[0][0] * M2.m[0][2] + + M1.m[1][0] * M2.m[1][2] + + M1.m[2][0] * M2.m[2][2]); + m[1][2] = (M1.m[0][1] * M2.m[0][2] + + M1.m[1][1] * M2.m[1][2] + + M1.m[2][1] * M2.m[2][2]); + m[2][2] = (M1.m[0][2] * M2.m[0][2] + + M1.m[1][2] * M2.m[1][2] + + M1.m[2][2] * M2.m[2][2]); + return *this; } @@ -141,7 +176,7 @@ struct _matrix33{ int IC Meigen(Tvector& dout, SelfRef a) { int i; - float tresh,theta,tau,t,sm,s,h,g,c; + float tresh, theta, tau, t, sm, s, h, g, c; int nrot; Tvector b; Tvector z; @@ -152,168 +187,207 @@ struct _matrix33{ b.set(a.m[0][0], a.m[1][1], a.m[2][2]); d.set(a.m[0][0], a.m[1][1], a.m[2][2]); - z.set(0,0,0); + z.set(0, 0, 0); nrot = 0; - for(i=0; i<50; i++){ - sm=0.0f; sm+=_abs(a.m[0][1]); sm+=_abs(a.m[0][2]); sm+=_abs(a.m[1][2]); + for (i = 0; i < 50; i++) + { + sm = 0.0f; + sm += _abs(a.m[0][1]); + sm += _abs(a.m[0][2]); + sm += _abs(a.m[1][2]); if (sm == 0.0) { set(v); dout.set(d); return i; } - if (i < 3) tresh=0.2f*sm/(3.0f*3.0f); else tresh=0.0f; + if (i < 3) tresh = 0.2f*sm / (3.0f*3.0f); + else tresh = 0.0f; { g = 100.0f*_abs(a.m[0][1]); - if (i>3 && _abs(d.x)+g==_abs(d.x) && _abs(d.y)+g==_abs(d.y)) - a.m[0][1]=0.0; - else if (_abs(a.m[0][1])>tresh){ - h = d.y-d.x; - if (_abs(h)+g == _abs(h)) t=(a.m[0][1])/h; - else{ - theta=0.5f*h/(a.m[0][1]); - t=1.0f/(_abs(theta)+_sqrt(1.0f+theta*theta)); + if (i>3 && _abs(d.x) + g == _abs(d.x) && _abs(d.y) + g == _abs(d.y)) + a.m[0][1] = 0.0; + else if (_abs(a.m[0][1]) > tresh) + { + h = d.y - d.x; + if (_abs(h) + g == _abs(h)) t = (a.m[0][1]) / h; + else + { + theta = 0.5f*h / (a.m[0][1]); + t = 1.0f / (_abs(theta) + _sqrt(1.0f + theta*theta)); if (theta < 0.0f) t = -t; } - c=1.0f/_sqrt(1+t*t); s=t*c; tau=s/(1.0f+c); h=t*a.m[0][1]; - z.x -= h; z.y += h; d.x -= h; d.y += h; - a.m[0][1]=0.0f; - ROT(a,0,2,1,2); ROT(v,0,0,0,1); ROT(v,1,0,1,1); ROT(v,2,0,2,1); + c = 1.0f / _sqrt(1 + t*t); + s = t*c; + tau = s / (1.0f + c); + h = t*a.m[0][1]; + z.x -= h; + z.y += h; + d.x -= h; + d.y += h; + a.m[0][1] = 0.0f; + ROT(a, 0, 2, 1, 2); + ROT(v, 0, 0, 0, 1); + ROT(v, 1, 0, 1, 1); + ROT(v, 2, 0, 2, 1); nrot++; } } { g = 100.0f*_abs(a.m[0][2]); - if (i>3 && _abs(d.x)+g==_abs(d.x) && _abs(d.z)+g==_abs(d.z)) - a.m[0][2]=0.0f; - else if (_abs(a.m[0][2])>tresh){ - h = d.z-d.x; - if (_abs(h)+g == _abs(h)) t=(a.m[0][2])/h; - else{ - theta=0.5f*h/(a.m[0][2]); - t=1.0f/(_abs(theta)+_sqrt(1.0f+theta*theta)); + if (i>3 && _abs(d.x) + g == _abs(d.x) && _abs(d.z) + g == _abs(d.z)) + a.m[0][2] = 0.0f; + else if (_abs(a.m[0][2]) > tresh) + { + h = d.z - d.x; + if (_abs(h) + g == _abs(h)) t = (a.m[0][2]) / h; + else + { + theta = 0.5f*h / (a.m[0][2]); + t = 1.0f / (_abs(theta) + _sqrt(1.0f + theta*theta)); if (theta < 0.0f) t = -t; } - c=1.0f/_sqrt(1+t*t); s=t*c; tau=s/(1.0f+c); h=t*a.m[0][2]; - z.x -= h; z.z += h; d.x -= h; d.z += h; - a.m[0][2]=0.0f; - ROT(a,0,1,1,2); ROT(v,0,0,0,2); ROT(v,1,0,1,2); ROT(v,2,0,2,2); + c = 1.0f / _sqrt(1 + t*t); + s = t*c; + tau = s / (1.0f + c); + h = t*a.m[0][2]; + z.x -= h; + z.z += h; + d.x -= h; + d.z += h; + a.m[0][2] = 0.0f; + ROT(a, 0, 1, 1, 2); + ROT(v, 0, 0, 0, 2); + ROT(v, 1, 0, 1, 2); + ROT(v, 2, 0, 2, 2); nrot++; } } { g = 100.0f*_abs(a.m[1][2]); - if (i>3 && _abs(d.y)+g==_abs(d.y) && _abs(d.z)+g==_abs(d.z)) - a.m[1][2]=0.0f; - else if (_abs(a.m[1][2])>tresh){ - h = d.z-d.y; - if (_abs(h)+g == _abs(h)) t=(a.m[1][2])/h; - else{ - theta=0.5f*h/(a.m[1][2]); - t=1.0f/(_abs(theta)+_sqrt(1.0f+theta*theta)); + if (i>3 && _abs(d.y) + g == _abs(d.y) && _abs(d.z) + g == _abs(d.z)) + a.m[1][2] = 0.0f; + else if (_abs(a.m[1][2]) > tresh) + { + h = d.z - d.y; + if (_abs(h) + g == _abs(h)) t = (a.m[1][2]) / h; + else + { + theta = 0.5f*h / (a.m[1][2]); + t = 1.0f / (_abs(theta) + _sqrt(1.0f + theta*theta)); if (theta < 0.0) t = -t; } - c=1.0f/_sqrt(1+t*t); s=t*c; tau=s/(1.0f+c); h=t*a.m[1][2]; - z.y -= h; z.z += h; d.y -= h; d.z += h; - a.m[1][2]=0.0f; - ROT(a,0,1,0,2); ROT(v,0,1,0,2); ROT(v,1,1,1,2); ROT(v,2,1,2,2); + c = 1.0f / _sqrt(1 + t*t); + s = t*c; + tau = s / (1.0f + c); + h = t*a.m[1][2]; + z.y -= h; + z.z += h; + d.y -= h; + d.z += h; + a.m[1][2] = 0.0f; + ROT(a, 0, 1, 0, 2); + ROT(v, 0, 1, 0, 2); + ROT(v, 1, 1, 1, 2); + ROT(v, 2, 1, 2, 2); nrot++; } } b.add(z); d.set(b); - z.set(0,0,0); + z.set(0, 0, 0); } -// Log.Msg("eigen: too many iterations in Jacobi transform (%d).\n", i); + // Log.Msg("eigen: too many iterations in Jacobi transform (%d).\n", i); return i; } #undef ROT -//-------------------------------------------------------------------------------- -// other unused function -//-------------------------------------------------------------------------------- + //-------------------------------------------------------------------------------- + // other unused function + //-------------------------------------------------------------------------------- IC SelfRef McolcMcol(int cr, SelfCRef M, int c) { m[0][cr] = M.m[0][c]; m[1][cr] = M.m[1][c]; m[2][cr] = M.m[2][c]; - return *this; + return *this; } IC SelfRef MxMpV(SelfCRef M1, SelfCRef M2, const Tvector& T) { - m[0][0] = ( M1.m[0][0] * M2.m[0][0] + - M1.m[0][1] * M2.m[1][0] + - M1.m[0][2] * M2.m[2][0] + T.x); - m[1][0] = ( M1.m[1][0] * M2.m[0][0] + - M1.m[1][1] * M2.m[1][0] + - M1.m[1][2] * M2.m[2][0] + T.y); - m[2][0] = ( M1.m[2][0] * M2.m[0][0] + - M1.m[2][1] * M2.m[1][0] + - M1.m[2][2] * M2.m[2][0] + T.z); - m[0][1] = ( M1.m[0][0] * M2.m[0][1] + - M1.m[0][1] * M2.m[1][1] + - M1.m[0][2] * M2.m[2][1] + T.x); - m[1][1] = ( M1.m[1][0] * M2.m[0][1] + - M1.m[1][1] * M2.m[1][1] + - M1.m[1][2] * M2.m[2][1] + T.y); - m[2][1] = ( M1.m[2][0] * M2.m[0][1] + - M1.m[2][1] * M2.m[1][1] + - M1.m[2][2] * M2.m[2][1] + T.z); - m[0][2] = ( M1.m[0][0] * M2.m[0][2] + - M1.m[0][1] * M2.m[1][2] + - M1.m[0][2] * M2.m[2][2] + T.x); - m[1][2] = ( M1.m[1][0] * M2.m[0][2] + - M1.m[1][1] * M2.m[1][2] + - M1.m[1][2] * M2.m[2][2] + T.y); - m[2][2] = ( M1.m[2][0] * M2.m[0][2] + - M1.m[2][1] * M2.m[1][2] + - M1.m[2][2] * M2.m[2][2] + T.z); - return *this; + m[0][0] = (M1.m[0][0] * M2.m[0][0] + + M1.m[0][1] * M2.m[1][0] + + M1.m[0][2] * M2.m[2][0] + T.x); + m[1][0] = (M1.m[1][0] * M2.m[0][0] + + M1.m[1][1] * M2.m[1][0] + + M1.m[1][2] * M2.m[2][0] + T.y); + m[2][0] = (M1.m[2][0] * M2.m[0][0] + + M1.m[2][1] * M2.m[1][0] + + M1.m[2][2] * M2.m[2][0] + T.z); + m[0][1] = (M1.m[0][0] * M2.m[0][1] + + M1.m[0][1] * M2.m[1][1] + + M1.m[0][2] * M2.m[2][1] + T.x); + m[1][1] = (M1.m[1][0] * M2.m[0][1] + + M1.m[1][1] * M2.m[1][1] + + M1.m[1][2] * M2.m[2][1] + T.y); + m[2][1] = (M1.m[2][0] * M2.m[0][1] + + M1.m[2][1] * M2.m[1][1] + + M1.m[2][2] * M2.m[2][1] + T.z); + m[0][2] = (M1.m[0][0] * M2.m[0][2] + + M1.m[0][1] * M2.m[1][2] + + M1.m[0][2] * M2.m[2][2] + T.x); + m[1][2] = (M1.m[1][0] * M2.m[0][2] + + M1.m[1][1] * M2.m[1][2] + + M1.m[1][2] * M2.m[2][2] + T.y); + m[2][2] = (M1.m[2][0] * M2.m[0][2] + + M1.m[2][1] * M2.m[1][2] + + M1.m[2][2] * M2.m[2][2] + T.z); + return *this; } IC SelfRef Mqinverse(SelfCRef M) { - int i,j; + int i, j; - for(i=0; i<3; i++) - for(j=0; j<3; j++){ - int i1 = (i+1)%3; - int i2 = (i+2)%3; - int j1 = (j+1)%3; - int j2 = (j+2)%3; - m[i][j] = (M.m[j1][i1]*M.m[j2][i2] - M.m[j1][i2]*M.m[j2][i1]); - } - return *this; + for (i = 0; i < 3; i++) + for (j = 0; j < 3; j++) + { + int i1 = (i + 1) % 3; + int i2 = (i + 2) % 3; + int j1 = (j + 1) % 3; + int j2 = (j + 2) % 3; + m[i][j] = (M.m[j1][i1] * M.m[j2][i2] - M.m[j1][i2] * M.m[j2][i1]); + } + return *this; } IC SelfRef MxMT(SelfCRef M1, SelfCRef M2) { - m[0][0] = ( M1.m[0][0] * M2.m[0][0] + - M1.m[0][1] * M2.m[0][1] + - M1.m[0][2] * M2.m[0][2]); - m[1][0] = ( M1.m[1][0] * M2.m[0][0] + - M1.m[1][1] * M2.m[0][1] + - M1.m[1][2] * M2.m[0][2]); - m[2][0] = ( M1.m[2][0] * M2.m[0][0] + - M1.m[2][1] * M2.m[0][1] + - M1.m[2][2] * M2.m[0][2]); - m[0][1] = ( M1.m[0][0] * M2.m[1][0] + - M1.m[0][1] * M2.m[1][1] + - M1.m[0][2] * M2.m[1][2]); - m[1][1] = ( M1.m[1][0] * M2.m[1][0] + - M1.m[1][1] * M2.m[1][1] + - M1.m[1][2] * M2.m[1][2]); - m[2][1] = ( M1.m[2][0] * M2.m[1][0] + - M1.m[2][1] * M2.m[1][1] + - M1.m[2][2] * M2.m[1][2]); - m[0][2] = ( M1.m[0][0] * M2.m[2][0] + - M1.m[0][1] * M2.m[2][1] + - M1.m[0][2] * M2.m[2][2]); - m[1][2] = ( M1.m[1][0] * M2.m[2][0] + - M1.m[1][1] * M2.m[2][1] + - M1.m[1][2] * M2.m[2][2]); - m[2][2] = ( M1.m[2][0] * M2.m[2][0] + - M1.m[2][1] * M2.m[2][1] + - M1.m[2][2] * M2.m[2][2]); - return *this; + m[0][0] = (M1.m[0][0] * M2.m[0][0] + + M1.m[0][1] * M2.m[0][1] + + M1.m[0][2] * M2.m[0][2]); + m[1][0] = (M1.m[1][0] * M2.m[0][0] + + M1.m[1][1] * M2.m[0][1] + + M1.m[1][2] * M2.m[0][2]); + m[2][0] = (M1.m[2][0] * M2.m[0][0] + + M1.m[2][1] * M2.m[0][1] + + M1.m[2][2] * M2.m[0][2]); + m[0][1] = (M1.m[0][0] * M2.m[1][0] + + M1.m[0][1] * M2.m[1][1] + + M1.m[0][2] * M2.m[1][2]); + m[1][1] = (M1.m[1][0] * M2.m[1][0] + + M1.m[1][1] * M2.m[1][1] + + M1.m[1][2] * M2.m[1][2]); + m[2][1] = (M1.m[2][0] * M2.m[1][0] + + M1.m[2][1] * M2.m[1][1] + + M1.m[2][2] * M2.m[1][2]); + m[0][2] = (M1.m[0][0] * M2.m[2][0] + + M1.m[0][1] * M2.m[2][1] + + M1.m[0][2] * M2.m[2][2]); + m[1][2] = (M1.m[1][0] * M2.m[2][0] + + M1.m[1][1] * M2.m[2][1] + + M1.m[1][2] * M2.m[2][2]); + m[2][2] = (M1.m[2][0] * M2.m[2][0] + + M1.m[2][1] * M2.m[2][1] + + M1.m[2][2] * M2.m[2][2]); + return *this; } IC SelfRef MskewV(const Tvector& v) @@ -325,78 +399,78 @@ struct _matrix33{ m[2][0] = -v.y; m[1][2] = -v.x; m[2][1] = v.x; - return *this; + return *this; + } + IC SelfRef sMxVpV(Tvector& R, float s1, const Tvector& V1, const Tvector& V2) const + { + R.x = s1 * (m[0][0] * V1.x + m[0][1] * V1.y + m[0][2] * V1.z) + V2.x; + R.y = s1 * (m[1][0] * V1.x + m[1][1] * V1.y + m[1][2] * V1.z) + V2.y; + R.z = s1 * (m[2][0] * V1.x + m[2][1] * V1.y + m[2][2] * V1.z) + V2.z; + return *this; + } + IC void MTxV(Tvector& R, const Tvector& V1) const + { + R.x = (m[0][0] * V1.x + m[1][0] * V1.y + m[2][0] * V1.z); + R.y = (m[0][1] * V1.x + m[1][1] * V1.y + m[2][1] * V1.z); + R.z = (m[0][2] * V1.x + m[1][2] * V1.y + m[2][2] * V1.z); + } + IC void MTxVpV(Tvector& R, const Tvector& V1, const Tvector& V2) const + { + R.x = (m[0][0] * V1.x + m[1][0] * V1.y + m[2][0] * V1.z + V2.x); + R.y = (m[0][1] * V1.x + m[1][1] * V1.y + m[2][1] * V1.z + V2.y); + R.z = (m[0][2] * V1.x + m[1][2] * V1.y + m[2][2] * V1.z + V2.z); + } + IC SelfRef MTxVmV(Tvector& R, const Tvector& V1, const Tvector& V2) const + { + R.x = (m[0][0] * V1.x + m[1][0] * V1.y + m[2][0] * V1.z - V2.x); + R.y = (m[0][1] * V1.x + m[1][1] * V1.y + m[2][1] * V1.z - V2.y); + R.z = (m[0][2] * V1.x + m[1][2] * V1.y + m[2][2] * V1.z - V2.z); + return *this; + } + IC SelfRef sMTxV(Tvector& R, float s1, const Tvector& V1) const + { + R.x = s1*(m[0][0] * V1.x + m[1][0] * V1.y + m[2][0] * V1.z); + R.y = s1*(m[0][1] * V1.x + m[1][1] * V1.y + m[2][1] * V1.z); + R.z = s1*(m[0][2] * V1.x + m[1][2] * V1.y + m[2][2] * V1.z); + } + IC SelfRef MxV(Tvector& R, const Tvector& V1) const + { + R.x = (m[0][0] * V1.x + m[0][1] * V1.y + m[0][2] * V1.z); + R.y = (m[1][0] * V1.x + m[1][1] * V1.y + m[1][2] * V1.z); + R.z = (m[2][0] * V1.x + m[2][1] * V1.y + m[2][2] * V1.z); + return *this; + } + IC void transform_dir(_vector2& dest, const _vector2& v) const // preferred to use + { + dest.x = v.x*_11 + v.y*_21; + dest.y = v.x*_12 + v.y*_22; + dest.z = v.x*_13 + v.y*_23; + } + IC void transform_dir(_vector2& v) const + { + _vector2 res; + transform_dir(res, v); + v.set(res); + } + IC SelfRef MxVpV(Tvector& R, const Tvector& V1, const Tvector& V2) const + { + R.x = (m[0][0] * V1.x + m[0][1] * V1.y + m[0][2] * V1.z + V2.x); + R.y = (m[1][0] * V1.x + m[1][1] * V1.y + m[1][2] * V1.z + V2.y); + R.z = (m[2][0] * V1.x + m[2][1] * V1.y + m[2][2] * V1.z + V2.z); + return *this; } - IC SelfRef sMxVpV(Tvector& R, float s1, const Tvector& V1, const Tvector& V2) const - { - R.x = s1 * (m[0][0] * V1.x + m[0][1] * V1.y + m[0][2] * V1.z) + V2.x; - R.y = s1 * (m[1][0] * V1.x + m[1][1] * V1.y + m[1][2] * V1.z) + V2.y; - R.z = s1 * (m[2][0] * V1.x + m[2][1] * V1.y + m[2][2] * V1.z) + V2.z; - return *this; - } - IC void MTxV(Tvector& R, const Tvector& V1) const - { - R.x = (m[0][0] * V1.x + m[1][0] * V1.y + m[2][0] * V1.z); - R.y = (m[0][1] * V1.x + m[1][1] * V1.y + m[2][1] * V1.z); - R.z = (m[0][2] * V1.x + m[1][2] * V1.y + m[2][2] * V1.z); - } - IC void MTxVpV(Tvector& R, const Tvector& V1, const Tvector& V2) const - { - R.x = (m[0][0] * V1.x + m[1][0] * V1.y + m[2][0] * V1.z + V2.x); - R.y = (m[0][1] * V1.x + m[1][1] * V1.y + m[2][1] * V1.z + V2.y); - R.z = (m[0][2] * V1.x + m[1][2] * V1.y + m[2][2] * V1.z + V2.z); - } - IC SelfRef MTxVmV(Tvector& R, const Tvector& V1, const Tvector& V2) const - { - R.x = (m[0][0] * V1.x + m[1][0] * V1.y + m[2][0] * V1.z - V2.x); - R.y = (m[0][1] * V1.x + m[1][1] * V1.y + m[2][1] * V1.z - V2.y); - R.z = (m[0][2] * V1.x + m[1][2] * V1.y + m[2][2] * V1.z - V2.z); - return *this; - } - IC SelfRef sMTxV(Tvector& R, float s1, const Tvector& V1) const - { - R.x = s1*(m[0][0] * V1.x + m[1][0] * V1.y + m[2][0] * V1.z); - R.y = s1*(m[0][1] * V1.x + m[1][1] * V1.y + m[2][1] * V1.z); - R.z = s1*(m[0][2] * V1.x + m[1][2] * V1.y + m[2][2] * V1.z); - } - IC SelfRef MxV(Tvector& R, const Tvector& V1) const - { - R.x = (m[0][0] * V1.x + m[0][1] * V1.y + m[0][2] * V1.z); - R.y = (m[1][0] * V1.x + m[1][1] * V1.y + m[1][2] * V1.z); - R.z = (m[2][0] * V1.x + m[2][1] * V1.y + m[2][2] * V1.z); - return *this; - } - IC void transform_dir (_vector2 &dest, const _vector2 &v) const // preferred to use - { - dest.x = v.x*_11 + v.y*_21; - dest.y = v.x*_12 + v.y*_22; - dest.z = v.x*_13 + v.y*_23; - } - IC void transform_dir (_vector2 &v) const - { - _vector2 res; - transform_dir (res,v); - v.set (res); - } - IC SelfRef MxVpV(Tvector& R, const Tvector& V1, const Tvector& V2) const - { - R.x = (m[0][0] * V1.x + m[0][1] * V1.y + m[0][2] * V1.z + V2.x); - R.y = (m[1][0] * V1.x + m[1][1] * V1.y + m[1][2] * V1.z + V2.y); - R.z = (m[2][0] * V1.x + m[2][1] * V1.y + m[2][2] * V1.z + V2.z); - return *this; - } }; -typedef _matrix33 Fmatrix33; -typedef _matrix33 Dmatrix33; +typedef _matrix33 Fmatrix33; +typedef _matrix33 Dmatrix33; template -BOOL _valid (const _matrix33& m) -{ - return - _valid(m.i)&& - _valid(m.j)&& - _valid(m.k); +BOOL _valid(const _matrix33& m) +{ + return + _valid(m.i) && + _valid(m.j) && + _valid(m.k); } #endif diff --git a/src/xrCore/_obb.h b/src/xrCore/_obb.h index 6fe740dfc2a..111f97732e8 100644 --- a/src/xrCore/_obb.h +++ b/src/xrCore/_obb.h @@ -2,115 +2,131 @@ #define FOBB_H template -struct _obb{ +struct _obb +{ public: - typedef _obb Self; - typedef Self& SelfRef; - typedef const Self& SelfCRef; - typedef _vector3 Tvector; - typedef _matrix Tmatrix; + typedef _obb Self; + typedef Self& SelfRef; + typedef const Self& SelfCRef; + typedef _vector3 Tvector; + typedef _matrix Tmatrix; protected: - static bool clip (T fDenom, T fNumer, T& rfT0, T& rfT1) + static bool clip(T fDenom, T fNumer, T& rfT0, T& rfT1) { // Return value is 'true' if line segment intersects the current test - // plane. Otherwise 'false' is returned in which case the line segment + // plane. Otherwise 'false' is returned in which case the line segment // is entirely clipped. - if ( fDenom > 0.0f ){ - if ( fNumer > fDenom*rfT1 ) return false; - if ( fNumer > fDenom*rfT0 ) rfT0 = fNumer/fDenom; + if (fDenom > 0.0f) + { + if (fNumer > fDenom*rfT1) return false; + if (fNumer > fDenom*rfT0) rfT0 = fNumer / fDenom; return true; - }else if ( fDenom < 0.0f ){ - if ( fNumer > fDenom*rfT0 ) return false; - if ( fNumer > fDenom*rfT1 ) rfT1 = fNumer/fDenom; + } + else if (fDenom < 0.0f) + { + if (fNumer > fDenom*rfT0) return false; + if (fNumer > fDenom*rfT1) rfT1 = fNumer / fDenom; return true; - }else{ + } + else + { return fNumer <= 0.0f; } } - static bool intersect (const Tvector& start, const Tvector& dir, const Tvector& extent, T& rfT0, T& rfT1) - { - T fSaveT0 = rfT0, fSaveT1 = rfT1; + static bool intersect(const Tvector& start, const Tvector& dir, const Tvector& extent, T& rfT0, T& rfT1) + { + T fSaveT0 = rfT0, fSaveT1 = rfT1; - bool bNotEntirelyClipped = - clip(+dir.x,-start.x-extent[0],rfT0,rfT1) && - clip(-dir.x,+start.x-extent[0],rfT0,rfT1) && - clip(+dir.y,-start.y-extent[1],rfT0,rfT1) && - clip(-dir.y,+start.y-extent[1],rfT0,rfT1) && - clip(+dir.z,-start.z-extent[2],rfT0,rfT1) && - clip(-dir.z,+start.z-extent[2],rfT0,rfT1); + bool bNotEntirelyClipped = + clip(+dir.x, -start.x - extent[0], rfT0, rfT1) && + clip(-dir.x, +start.x - extent[0], rfT0, rfT1) && + clip(+dir.y, -start.y - extent[1], rfT0, rfT1) && + clip(-dir.y, +start.y - extent[1], rfT0, rfT1) && + clip(+dir.z, -start.z - extent[2], rfT0, rfT1) && + clip(-dir.z, +start.z - extent[2], rfT0, rfT1); - return bNotEntirelyClipped && ( rfT0 != fSaveT0 || rfT1 != fSaveT1 ); - } + return bNotEntirelyClipped && (rfT0 != fSaveT0 || rfT1 != fSaveT1); + } public: - _matrix33 m_rotate; - Tvector m_translate; - Tvector m_halfsize; + _matrix33 m_rotate; + Tvector m_translate; + Tvector m_halfsize; - IC SelfRef invalidate() { - m_rotate.identity (); - m_translate.set (0,0,0); - m_halfsize.set (0,0,0); - return *this; - } - IC SelfRef identity() { - invalidate(); - m_halfsize.set( T(0.5), T(0.5), T(0.5) ); - return *this; - } - IC void xform_get(Tmatrix& D) const - { - D.i.set(m_rotate.i); D._14_ = 0; - D.j.set(m_rotate.j); D._24_ = 0; - D.k.set(m_rotate.k); D._34_ = 0; - D.c.set(m_translate);D._44_ = 1; - } - IC SelfRef xform_set(const Tmatrix& S) - { - m_rotate.i.set (S.i); - m_rotate.j.set (S.j); - m_rotate.k.set (S.k); - m_translate.set (S.c); - return *this; - } - IC void xform_full(Tmatrix& D) const - { - Tmatrix R,S; - xform_get (R); - S.scale (m_halfsize); - D.mul_43 (R,S); - } + IC SelfRef invalidate() + { + m_rotate.identity(); + m_translate.set(0, 0, 0); + m_halfsize.set(0, 0, 0); + return *this; + } + IC SelfRef identity() + { + invalidate(); + m_halfsize.set(T(0.5), T(0.5), T(0.5)); + return *this; + } + IC void xform_get(Tmatrix& D) const + { + D.i.set(m_rotate.i); + D._14_ = 0; + D.j.set(m_rotate.j); + D._24_ = 0; + D.k.set(m_rotate.k); + D._34_ = 0; + D.c.set(m_translate); + D._44_ = 1; + } + IC SelfRef xform_set(const Tmatrix& S) + { + m_rotate.i.set(S.i); + m_rotate.j.set(S.j); + m_rotate.k.set(S.k); + m_translate.set(S.c); + return *this; + } + IC void xform_full(Tmatrix& D) const + { + Tmatrix R, S; + xform_get(R); + S.scale(m_halfsize); + D.mul_43(R, S); + } - // NOTE: Unoptimized - IC SelfRef transform(SelfCRef src, const Tmatrix& M) - { - Tmatrix srcR,destR; + // NOTE: Unoptimized + IC SelfRef transform(SelfCRef src, const Tmatrix& M) + { + Tmatrix srcR, destR; - src.xform_get (srcR); - destR.mul_43 (M,srcR); - xform_set (destR); - m_halfsize.set (src.m_halfsize); - return *this; - } + src.xform_get(srcR); + destR.mul_43(M, srcR); + xform_set(destR); + m_halfsize.set(src.m_halfsize); + return *this; + } - IC bool intersect(const Tvector& start, const Tvector& dir, T& dist) const + IC bool intersect(const Tvector& start, const Tvector& dir, T& dist) const { // convert ray to box coordinates - Tvector kDiff; - kDiff.sub(start,m_translate); + Tvector kDiff; + kDiff.sub(start, m_translate); Tvector kOrigin; kOrigin.set(kDiff.dotproduct(m_rotate.i), kDiff.dotproduct(m_rotate.j), kDiff.dotproduct(m_rotate.k)); Tvector kDirection; - kDirection.set(dir.dotproduct(m_rotate.i),dir.dotproduct(m_rotate.j),dir.dotproduct(m_rotate.k)); + kDirection.set(dir.dotproduct(m_rotate.i), dir.dotproduct(m_rotate.j), dir.dotproduct(m_rotate.k)); T fT0 = 0.0f, fT1 = type_max(T); - if (intersect(kOrigin,kDirection,m_halfsize, fT0,fT1)){ - bool bPick=false; - if ( fT0 > 0.0f ){ - if (fT0 0.0f) + { + if (fT0 < dist) { dist = fT0; bPick = true; } + if (fT1 < dist) { dist = fT1; bPick = true; } + } + else + { + if (fT1 < dist) { dist = fT1; bPick = true; } } return bPick; } @@ -118,13 +134,13 @@ struct _obb{ } }; -typedef _obb Fobb; -typedef _obb Dobb; +typedef _obb Fobb; +typedef _obb Dobb; template -BOOL _valid (const _obb& m) -{ - return _valid(m_rotate) && _valid(m_translate) && _valid(m_halfsize); +BOOL _valid(const _obb& m) +{ + return _valid(m_rotate) && _valid(m_translate) && _valid(m_halfsize); } #endif \ No newline at end of file diff --git a/src/xrCore/_plane.h b/src/xrCore/_plane.h index 13302943ee9..a17dbf34fc5 100644 --- a/src/xrCore/_plane.h +++ b/src/xrCore/_plane.h @@ -2,148 +2,151 @@ #define _PLANE template -class _plane { +class _plane +{ public: - typedef T TYPE; - typedef _plane Self; - typedef Self& SelfRef; - typedef const Self& SelfCRef; + typedef T TYPE; + typedef _plane Self; + typedef Self& SelfRef; + typedef const Self& SelfCRef; public: - _vector3 n; - T d; + _vector3 n; + T d; public: - IC SelfRef set (Self &P) - { - n.set (P.n); - d = P.d; - return *this; - } - IC BOOL similar (Self &P, T eps_n=EPS, T eps_d=EPS) - { - return (n.similar(P.n,eps_n)&&(_abs(d-P.d) &v1, const _vector3 &v2, const _vector3 &v3) - { - _vector3 t1,t2; - n.crossproduct(t1.sub(v1,v2), t2.sub(v1,v3)).normalize(); - d = -n.dotproduct(v1); - return *this; - } - ICF SelfRef build_precise (const _vector3 &v1, const _vector3 &v2, const _vector3 &v3) - { - _vector3 t1,t2; - n.crossproduct(t1.sub(v1,v2), t2.sub(v1,v3)); exact_normalize(n); - d = -n.dotproduct(v1); - return *this; - } - ICF SelfRef build(const _vector3 &_p, const _vector3 &_n) - { - d = - n.normalize(_n).dotproduct(_p); - return *this; - } - ICF SelfRef build_unit_normal(const _vector3 &_p, const _vector3 &_n) - { - VERIFY (fsimilar(_n.magnitude(),1,EPS)); - d = - n.set(_n).dotproduct(_p); - return *this; - } - IC SelfCRef project(_vector3 &pdest, _vector3 const& psrc) const - { - pdest.mad (psrc,n,-classify(psrc)); - return *this; - } - IC SelfRef project(_vector3 &pdest, _vector3 const& psrc) - { - pdest.mad (psrc,n,-classify(psrc)); - return *this; - } - ICF T classify(const _vector3 &v) const - { - return n.dotproduct(v)+d; - } - IC SelfRef normalize() - { - T denom = 1.f / n.magnitude(); - n.mul(denom); - d*=denom; - return *this; - } - IC T distance (const _vector3 &v) - { - return _abs(classify(v)); - } - IC BOOL intersectRayDist(const _vector3& P, const _vector3& D, T& dist) - { - T numer = classify(P); - T denom = n.dotproduct(D); - - if (_abs(denom)0.f)||fis_zero(dist)); - } - ICF BOOL intersectRayPoint(const _vector3& P, const _vector3& D, _vector3& dest) - { - T numer = classify(P); - T denom = n.dotproduct(D); + IC SelfRef set(Self& P) + { + n.set(P.n); + d = P.d; + return *this; + } + IC BOOL similar(Self& P, T eps_n = EPS, T eps_d = EPS) + { + return (n.similar(P.n, eps_n) && (_abs(d - P.d) < eps_d)); + } + ICF SelfRef build(const _vector3& v1, const _vector3& v2, const _vector3& v3) + { + _vector3 t1, t2; + n.crossproduct(t1.sub(v1, v2), t2.sub(v1, v3)).normalize(); + d = -n.dotproduct(v1); + return *this; + } + ICF SelfRef build_precise(const _vector3& v1, const _vector3& v2, const _vector3& v3) + { + _vector3 t1, t2; + n.crossproduct(t1.sub(v1, v2), t2.sub(v1, v3)); + exact_normalize(n); + d = -n.dotproduct(v1); + return *this; + } + ICF SelfRef build(const _vector3& _p, const _vector3& _n) + { + d = -n.normalize(_n).dotproduct(_p); + return *this; + } + ICF SelfRef build_unit_normal(const _vector3& _p, const _vector3& _n) + { + VERIFY(fsimilar(_n.magnitude(), 1, EPS)); + d = -n.set(_n).dotproduct(_p); + return *this; + } + IC SelfCRef project(_vector3& pdest, _vector3 const& psrc) const + { + pdest.mad(psrc, n, -classify(psrc)); + return *this; + } + IC SelfRef project(_vector3& pdest, _vector3 const& psrc) + { + pdest.mad(psrc, n, -classify(psrc)); + return *this; + } + ICF T classify(const _vector3& v) const + { + return n.dotproduct(v) + d; + } + IC SelfRef normalize() + { + T denom = 1.f / n.magnitude(); + n.mul(denom); + d *= denom; + return *this; + } + IC T distance(const _vector3& v) + { + return _abs(classify(v)); + } + IC BOOL intersectRayDist(const _vector3& P, const _vector3& D, T& dist) + { + T numer = classify(P); + T denom = n.dotproduct(D); - if (_abs(denom)0.f)||fis_zero(dist)); - } - } - IC BOOL intersect ( - const _vector3& u, const _vector3& v, // segment - _vector3& isect) // intersection point - { - T denom,dist; - _vector3 t; + if (_abs(denom) < EPS_S) // normal is orthogonal to vector3, cant intersect + return FALSE; - t.sub(v,u); - denom = n.dotproduct(t); - if (_abs(denom) < EPS) return false; // they are parallel + dist = -(numer / denom); + return ((dist > 0.f) || fis_zero(dist)); + } + ICF BOOL intersectRayPoint(const _vector3& P, const _vector3& D, _vector3& dest) + { + T numer = classify(P); + T denom = n.dotproduct(D); - dist = -(n.dotproduct(u) + d) / denom; - if (dist < -EPS || dist > 1+EPS) return false; - isect.mad(u,t,dist); - return true; - } + if (_abs(denom) < EPS_S) return FALSE; // normal is orthogonal to vector3, cant intersect + else + { + float dist = -(numer / denom); + dest.mad(P, D, dist); + return ((dist > 0.f) || fis_zero(dist)); + } + } + IC BOOL intersect( + const _vector3& u, const _vector3& v, // segment + _vector3& isect) // intersection point + { + T denom, dist; + _vector3 t; - IC BOOL intersect_2 ( - const _vector3& u, const _vector3& v, // segment - _vector3& isect) // intersection point - { - T dist1, dist2; - _vector3 t; + t.sub(v, u); + denom = n.dotproduct(t); + if (_abs(denom) < EPS) return false; // they are parallel - dist1 = n.dotproduct(u)+d; - dist2 = n.dotproduct(v)+d; + dist = -(n.dotproduct(u) + d) / denom; + if (dist < -EPS || dist > 1 + EPS) return false; + isect.mad(u, t, dist); + return true; + } - if (dist1*dist2<0.0f) - return false; + IC BOOL intersect_2( + const _vector3& u, const _vector3& v, // segment + _vector3& isect) // intersection point + { + T dist1, dist2; + _vector3 t; - t.sub (v,u); - isect.mad (u,t,dist1/_abs(dist1-dist2)); + dist1 = n.dotproduct(u) + d; + dist2 = n.dotproduct(v) + d; - return true; - } - IC SelfRef transform(_matrix& M) - { - // rotate the normal - M.transform_dir (n); - // slide the offset - d -= M.c.dotproduct (n); - return *this; - } + if (dist1*dist2 < 0.0f) + return false; + + t.sub(v, u); + isect.mad(u, t, dist1 / _abs(dist1 - dist2)); + + return true; + } + IC SelfRef transform(_matrix& M) + { + // rotate the normal + M.transform_dir(n); + // slide the offset + d -= M.c.dotproduct(n); + return *this; + } }; -typedef _plane Fplane; -typedef _plane Dplane; +typedef _plane Fplane; +typedef _plane Dplane; template -BOOL _valid (const _plane& s) { return _valid(s.n) && _valid(s.d); } +BOOL _valid(const _plane& s) { return _valid(s.n) && _valid(s.d); } #endif diff --git a/src/xrCore/_plane2.h b/src/xrCore/_plane2.h index 4f111b4ce04..172211c1a9d 100644 --- a/src/xrCore/_plane2.h +++ b/src/xrCore/_plane2.h @@ -2,115 +2,117 @@ #define _PLANE2 template -class _plane2 { +class _plane2 +{ public: - typedef T TYPE; - typedef _plane2 Self; - typedef Self& SelfRef; - typedef const Self& SelfCRef; + typedef T TYPE; + typedef _plane2 Self; + typedef Self& SelfRef; + typedef const Self& SelfCRef; public: - _vector2 n; - T d; + _vector2 n; + T d; public: - IC SelfRef set (Self &P) - { - n.set (P.n); - d = P.d; - return *this; - } - IC BOOL similar (Self &P, T eps_n=EPS, T eps_d=EPS) - { - return (n.similar(P.n,eps_n)&&(_abs(d-P.d) &_p, const _vector2 &_n) - { - d = - n.normalize(_n).dotproduct(_p); - return *this; - } - IC SelfRef project (_vector2 &pdest, _vector2 &psrc) - { - pdest.mad (psrc,n,-classify(psrc)); - return *this; - } - IC T classify (const _vector2 &v) const - { - return n.dotproduct(v)+d; - } - IC SelfRef normalize () - { - T denom = 1.f / n.magnitude(); - n.mul(denom); - d*=denom; - return *this; - } - IC T distance (const _vector2 &v) - { - return _abs(classify(v)); - } - IC BOOL intersectRayDist(const _vector2& P, const _vector2& D, T& dist) - { - T numer = classify(P); - T denom = n.dotproduct(D); + IC SelfRef set(Self& P) + { + n.set(P.n); + d = P.d; + return *this; + } + IC BOOL similar(Self& P, T eps_n = EPS, T eps_d = EPS) + { + return (n.similar(P.n, eps_n) && (_abs(d - P.d) < eps_d)); + } + IC SelfRef build(const _vector2& _p, const _vector2& _n) + { + d = -n.normalize(_n).dotproduct(_p); + return *this; + } + IC SelfRef project(_vector2& pdest, _vector2& psrc) + { + pdest.mad(psrc, n, -classify(psrc)); + return *this; + } + IC T classify(const _vector2& v) const + { + return n.dotproduct(v) + d; + } + IC SelfRef normalize() + { + T denom = 1.f / n.magnitude(); + n.mul(denom); + d *= denom; + return *this; + } + IC T distance(const _vector2& v) + { + return _abs(classify(v)); + } + IC BOOL intersectRayDist(const _vector2& P, const _vector2& D, T& dist) + { + T numer = classify(P); + T denom = n.dotproduct(D); - if (_abs(denom)0.f)||fis_zero(dist)); - } - IC BOOL intersectRayPoint(const _vector2& P, const _vector2& D, _vector2& dest) - { - T numer = classify(P); - T denom = n.dotproduct(D); + dist = -(numer / denom); + return ((dist > 0.f) || fis_zero(dist)); + } + IC BOOL intersectRayPoint(const _vector2& P, const _vector2& D, _vector2& dest) + { + T numer = classify(P); + T denom = n.dotproduct(D); - if (_abs(denom)0.f)||fis_zero(dist)); - } - } - IC BOOL intersect ( - const _vector2& u, const _vector2& v, // segment - _vector2& isect) // intersection point - { - T denom,dist; - _vector2 t; + if (_abs(denom) < EPS_S) return FALSE; // normal is orthogonal to vector3, cant intersect + else + { + float dist = -(numer / denom); + dest.mad(P, D, dist); + return ((dist > 0.f) || fis_zero(dist)); + } + } + IC BOOL intersect( + const _vector2& u, const _vector2& v, // segment + _vector2& isect) // intersection point + { + T denom, dist; + _vector2 t; - t.sub(v,u); - denom = n.dotproduct(t); - if (_abs(denom) < EPS) return false; // they are parallel + t.sub(v, u); + denom = n.dotproduct(t); + if (_abs(denom) < EPS) return false; // they are parallel - dist = -(n.dotproduct(u) + d) / denom; - if (dist < -EPS || dist > 1+EPS) return false; - isect.mad(u,t,dist); - return true; - } + dist = -(n.dotproduct(u) + d) / denom; + if (dist < -EPS || dist > 1 + EPS) return false; + isect.mad(u, t, dist); + return true; + } - IC BOOL intersect_2 ( - const _vector2& u, const _vector2& v, // segment - _vector2& isect) // intersection point - { - T dist1, dist2; - _vector2 t; + IC BOOL intersect_2( + const _vector2& u, const _vector2& v, // segment + _vector2& isect) // intersection point + { + T dist1, dist2; + _vector2 t; - dist1 = n.dotproduct(u)+d; - dist2 = n.dotproduct(v)+d; + dist1 = n.dotproduct(u) + d; + dist2 = n.dotproduct(v) + d; - if (dist1*dist2<0.0f) - return false; + if (dist1*dist2 < 0.0f) + return false; - t.sub (v,u); - isect.mad (u,t,dist1/_abs(dist1-dist2)); + t.sub(v, u); + isect.mad(u, t, dist1 / _abs(dist1 - dist2)); - return true; - } + return true; + } }; -typedef _plane2 Fplane2; -typedef _plane2 Dplane2; +typedef _plane2 Fplane2; +typedef _plane2 Dplane2; template -BOOL _valid (const _plane2& s) { return _valid(s.n) && _valid(s.d); } +BOOL _valid(const _plane2& s) { return _valid(s.n) && _valid(s.d); } #endif diff --git a/src/xrCore/_quaternion.h b/src/xrCore/_quaternion.h index e31e2e80cc6..0ac52df2c1e 100644 --- a/src/xrCore/_quaternion.h +++ b/src/xrCore/_quaternion.h @@ -2,446 +2,473 @@ #define __Q__ /*************************************************************************** - The quatern module contains basic support for a quaternion object. - - quaternions are an extension of complex numbers that allows an - expression for rotation that can be easily interpolated. Quaternions are also - more numericaly stable for repeated rotations than matrices. - - - A quaternion is a 4 element 'vector3' [w,x,y,z] where: - - q = w + xi + yj + zk - i*i = -1 - j*j = -1 - k*k = -1 - i*j = -j*i = k - j*k = -k*j = i - k*i = -i*k = j - q' (conjugate) = w - xi - yj - zk - ||q|| (magnitude) = sqrt(q*q') = sqrt(w*w + x*x + y*y + z*z) - unit quaternion ||q|| == 1; this implies q' == qinverse - quaternions are associative (q1*q2)*q3 == q1*(q2*q3) - quaternions are not commutative q1*q2 != q2*q1 - qinverse (inverse (1/q) ) = q'/(q*q') - - q can be expressed by w + xi + yj + zk or [w,x,y,z] - or as in this implementation (s,v) where s=w, and v=[x,y,z] - - quaternions can represent a rotation. The rotation is an angle t, around a - unit vector3 u. q=(s,v); s= cos(t/2); v= u*sin(t/2). - - quaternions can apply the rotation to a point. let the point be p [px,py,pz], - and let P be a quaternion(0,p). Protated = q*P*qinverse - ( Protated = q*P*q' if q is a unit quaternion) - - concatenation rotations is similar to matrix concatenation. given two rotations - q1 and q2, to rotate by q1, then q2: let qc = (q2*q1), then the combined - rotation is given by qc*P*qcinverse (= qc*P*qc' if q is a unit quaternion) - - multiplication: - q1 = w1 + x1i + y1j + z1k - q2 = w2 + x2i + y2j + z2k - q1*q2 = q3 = - (w1*w2 - x1*x2 - y1*y2 - z1*z2) {w3} - (w1*x2 + x1*w2 + y1*z2 - z1*y2)i {x3} - (w1*y2 - x1*z2 + y1*w2 + z1*x2)j {y3} - (w1*z2 + x1*y2 + y1*x2 + z1*w2)k {z3} - - also, - q1 = (s1,v1) = [s1,(x1,y1,z1)] - q2 = (s2,v2) = [s2,(x2,y2,z2)] - q1*q2 = q3 = (s1*s2 - dot_product(v1,v2), {s3} - (s1*v2 + s2*v1 + cross_product(v1,v2)) {v3} - - interpolation - it is possible (and sometimes reasonable) to interpolate between - two quaternions by interpolating each component. This does not quarantee a - resulting unit quaternion, and will result in an animation with non-linear - rotational velocity. - - spherical interpolation: (slerp) treat the quaternions as vectors - find the angle between them (w = arccos(q1 dot q2) ). - given 0<=t<=1, q(t) = q1*(sin((1-t)*w)/sin(w) + q2 * sin(t*w)/sin(w). - since q == -q, care must be taken to rotate the proper way. - - this implementation uses the notation quaternion q = (quatS,quatV) - where quatS is a scalar, and quatV is a 3 element vector3. - - *************************************************************************** - - Quaternions are really strange mathematical objects, just like complex - numbers except that instead of just a real and imaginary part, you have - three imaginary components, so every quaternion is of the form a + bi + - cj + dk, where i, j, and k when squared equal -1. The odd thing about - these numbers is that they don't obey the commutative law of - multiplication pq != qp if p and q are quaternions. They're multiplied - by the distributive law, and by the rules: i^2 = j^2 = k^2 = -1, i*j = k - = -j*i, j*k = i = -k*j, and k*i = j = -i*k. For rotations in graphics, - you're going to be interested in the unit quaternions, quaternions for - which sqrt(a^2 + b^2 + c^2 + d^2) = 1, as in this form: - - cos(phi/2) + b*sin(phi/2)*i + c*sin(phi/2)*j + d*sin(phi/2)*k - - This corresponds to a rotation of an angle phi about the axis [ b c d ] - (which is a unit vector3, of course). A unit quaternion can also be - thought of as a point on the surface of a four-dimensional hypersphere, - so if you try to interpolate between two unit quaternions, you can get - an intermediate rotation. Gamasutra describes Shoemake's spherical - linear interpolation method, but I think getting the logarithm of the - quaternions and performing linear interpolation is easier. The - logarithm of a quaternion is given by - - ln(a + bi + cj + dk) = log(sqrt(a^2 + b^2 + c^2 + d^2)) - + i*b*arctan(r/a)/r - + j*c*arctan(r/a)/r - + k*d*arctan(r/a)/r - - where r = sqrt(b^2 + c^2 + d^2) - - Note that the first component will always be zero for unit quaternions. - Linearly interpolate each of the components of the logarithm of both - quaternions then perform the quaternion exponential on the result, given - by - - exp(a + bi + cj + dk) = exp(a)*cos(r) + - i*exp(a)*b*sin(r)/r + - j*exp(a)*c*sin(r)/r + - k*exp(a)*d*sin(r)/r - - where r is the same factor as above. This finds an intermediate - rotation. Now, to actually use the quaternion rotation q on a point - p=[x y z], you compute the quaternion product s' = qsq^-1 where q is the - unit quaternion a + bi + cj + dk for the rotation you want, q^-1 is a - - bi - cj - dk, and s = xi + yj + zk. s' will be of the form x'i + y'j + - z'k, so the rotated point is p'=[x' y' z']. The quaternion triple - product above is equivalent to a rotation matrix, as a lot of tedious - algebra can show. The proof is left as an exercise for the reader :-). - - For more information, you can check the Gamasutra article referred to - above, and Section 21.1 and Exercise 21.7 in Foley, et. al.'s "Computer - Graphics: Principles and Practice". I had to implement a lot of this - for my software renderer library... - -***************************************************************************/ - -#define UNIT_TOLERANCE 0.001f - // Quaternion magnitude must be closer than this tolerance to 1.0 to be - // considered a unit quaternion - -#define QZERO_TOLERANCE 0.00001f - // quaternion magnitude must be farther from this tolerance to 0.0 to be - // normalized - -#define TRACE_QZERO_TOLERANCE 0.1f - // trace of matrix must be greater than this to be used for converting a matrix - // to a quaternion. - -#define AA_QZERO_TOLERANCE 0.0001f -#define QEPSILON 0.00001f + The quatern module contains basic support for a quaternion object. + + quaternions are an extension of complex numbers that allows an + expression for rotation that can be easily interpolated. Quaternions are also + more numericaly stable for repeated rotations than matrices. + + + A quaternion is a 4 element 'vector3' [w,x,y,z] where: + + q = w + xi + yj + zk + i*i = -1 + j*j = -1 + k*k = -1 + i*j = -j*i = k + j*k = -k*j = i + k*i = -i*k = j + q' (conjugate) = w - xi - yj - zk + ||q|| (magnitude) = sqrt(q*q') = sqrt(w*w + x*x + y*y + z*z) + unit quaternion ||q|| == 1; this implies q' == qinverse + quaternions are associative (q1*q2)*q3 == q1*(q2*q3) + quaternions are not commutative q1*q2 != q2*q1 + qinverse (inverse (1/q) ) = q'/(q*q') + + q can be expressed by w + xi + yj + zk or [w,x,y,z] + or as in this implementation (s,v) where s=w, and v=[x,y,z] + + quaternions can represent a rotation. The rotation is an angle t, around a + unit vector3 u. q=(s,v); s= cos(t/2); v= u*sin(t/2). + + quaternions can apply the rotation to a point. let the point be p [px,py,pz], + and let P be a quaternion(0,p). Protated = q*P*qinverse + ( Protated = q*P*q' if q is a unit quaternion) + + concatenation rotations is similar to matrix concatenation. given two rotations + q1 and q2, to rotate by q1, then q2: let qc = (q2*q1), then the combined + rotation is given by qc*P*qcinverse (= qc*P*qc' if q is a unit quaternion) + + multiplication: + q1 = w1 + x1i + y1j + z1k + q2 = w2 + x2i + y2j + z2k + q1*q2 = q3 = + (w1*w2 - x1*x2 - y1*y2 - z1*z2) {w3} + (w1*x2 + x1*w2 + y1*z2 - z1*y2)i {x3} + (w1*y2 - x1*z2 + y1*w2 + z1*x2)j {y3} + (w1*z2 + x1*y2 + y1*x2 + z1*w2)k {z3} + + also, + q1 = (s1,v1) = [s1,(x1,y1,z1)] + q2 = (s2,v2) = [s2,(x2,y2,z2)] + q1*q2 = q3 = (s1*s2 - dot_product(v1,v2), {s3} + (s1*v2 + s2*v1 + cross_product(v1,v2)) {v3} + + interpolation - it is possible (and sometimes reasonable) to interpolate between + two quaternions by interpolating each component. This does not quarantee a + resulting unit quaternion, and will result in an animation with non-linear + rotational velocity. + + spherical interpolation: (slerp) treat the quaternions as vectors + find the angle between them (w = arccos(q1 dot q2) ). + given 0<=t<=1, q(t) = q1*(sin((1-t)*w)/sin(w) + q2 * sin(t*w)/sin(w). + since q == -q, care must be taken to rotate the proper way. + + this implementation uses the notation quaternion q = (quatS,quatV) + where quatS is a scalar, and quatV is a 3 element vector3. + + *************************************************************************** + + Quaternions are really strange mathematical objects, just like complex + numbers except that instead of just a real and imaginary part, you have + three imaginary components, so every quaternion is of the form a + bi + + cj + dk, where i, j, and k when squared equal -1. The odd thing about + these numbers is that they don't obey the commutative law of + multiplication pq != qp if p and q are quaternions. They're multiplied + by the distributive law, and by the rules: i^2 = j^2 = k^2 = -1, i*j = k + = -j*i, j*k = i = -k*j, and k*i = j = -i*k. For rotations in graphics, + you're going to be interested in the unit quaternions, quaternions for + which sqrt(a^2 + b^2 + c^2 + d^2) = 1, as in this form: + + cos(phi/2) + b*sin(phi/2)*i + c*sin(phi/2)*j + d*sin(phi/2)*k + + This corresponds to a rotation of an angle phi about the axis [ b c d ] + (which is a unit vector3, of course). A unit quaternion can also be + thought of as a point on the surface of a four-dimensional hypersphere, + so if you try to interpolate between two unit quaternions, you can get + an intermediate rotation. Gamasutra describes Shoemake's spherical + linear interpolation method, but I think getting the logarithm of the + quaternions and performing linear interpolation is easier. The + logarithm of a quaternion is given by + + ln(a + bi + cj + dk) = log(sqrt(a^2 + b^2 + c^2 + d^2)) + + i*b*arctan(r/a)/r + + j*c*arctan(r/a)/r + + k*d*arctan(r/a)/r + + where r = sqrt(b^2 + c^2 + d^2) + + Note that the first component will always be zero for unit quaternions. + Linearly interpolate each of the components of the logarithm of both + quaternions then perform the quaternion exponential on the result, given + by + + exp(a + bi + cj + dk) = exp(a)*cos(r) + + i*exp(a)*b*sin(r)/r + + j*exp(a)*c*sin(r)/r + + k*exp(a)*d*sin(r)/r + + where r is the same factor as above. This finds an intermediate + rotation. Now, to actually use the quaternion rotation q on a point + p=[x y z], you compute the quaternion product s' = qsq^-1 where q is the + unit quaternion a + bi + cj + dk for the rotation you want, q^-1 is a - + bi - cj - dk, and s = xi + yj + zk. s' will be of the form x'i + y'j + + z'k, so the rotated point is p'=[x' y' z']. The quaternion triple + product above is equivalent to a rotation matrix, as a lot of tedious + algebra can show. The proof is left as an exercise for the reader :-). + + For more information, you can check the Gamasutra article referred to + above, and Section 21.1 and Exercise 21.7 in Foley, et. al.'s "Computer + Graphics: Principles and Practice". I had to implement a lot of this + for my software renderer library... + + ***************************************************************************/ + +#define UNIT_TOLERANCE 0.001f +// Quaternion magnitude must be closer than this tolerance to 1.0 to be +// considered a unit quaternion + +#define QZERO_TOLERANCE 0.00001f +// quaternion magnitude must be farther from this tolerance to 0.0 to be +// normalized + +#define TRACE_QZERO_TOLERANCE 0.1f +// trace of matrix must be greater than this to be used for converting a matrix +// to a quaternion. + +#define AA_QZERO_TOLERANCE 0.0001f +#define QEPSILON 0.00001f template -struct XRCORE_API _quaternion { +struct XRCORE_API _quaternion +{ public: - typedef T TYPE; - typedef _quaternion Self; - typedef Self& SelfRef; - typedef const Self& SelfCRef; + typedef T TYPE; + typedef _quaternion Self; + typedef Self& SelfRef; + typedef const Self& SelfCRef; private: - IC T _asin_(T x) - { - const T c1 = 0.892399f; - const T c3 = 1.693204f; - const T c5 =-3.853735f; - const T c7 = 2.838933f; - - const T x2 = x * x; - const T d = x * (c1 + x2 * (c3 + x2 * (c5 + x2 * c7))); - - return d; - } - IC T _acos_(T x) - { - return PI_DIV_2 - _asin_(x); - } + IC T _asin_(T x) + { + const T c1 = 0.892399f; + const T c3 = 1.693204f; + const T c5 = -3.853735f; + const T c7 = 2.838933f; + + const T x2 = x * x; + const T d = x * (c1 + x2 * (c3 + x2 * (c5 + x2 * c7))); + + return d; + } + IC T _acos_(T x) + { + return PI_DIV_2 - _asin_(x); + } public: - T x,y,z,w; - - IC SelfRef set(T W, T X, T Y, T Z) // don't normalize - { x=X; y=Y; z=Z; w=W; return *this; } - IC SelfRef set(SelfCRef Q) // don't normalize - { set(Q.w, Q.x, Q.y, Q.z); return *this; } - - IC SelfRef set(const _matrix& m); - - // multiplies q1 * q2, and places the result in *this. - // no failure. renormalization not automatic - -/* - q1*q2 = q3 = - (w1*w2 - x1*x2 - y1*y2 - z1*z2) {w3} - (w1*x2 + x1*w2 + y1*z2 - z1*y2)i {x3} - (w1*y2 - x1*z2 + y1*w2 + z1*x2)j {y3} - (w1*z2 + x1*y2 - y1*x2 + z1*w2)k {z3} -*/ - IC SelfRef mul(SelfCRef q1l, SelfCRef q2l) - { - VERIFY( q1l.isValid() ); - VERIFY( q2l.isValid() ); - - w = ( (q1l.w*q2l.w) - (q1l.x*q2l.x) - - (q1l.y*q2l.y) - (q1l.z*q2l.z) ); - - x = ( (q1l.w*q2l.x) + (q1l.x*q2l.w) - + (q1l.y*q2l.z) - (q1l.z*q2l.y) ); - - y = ( (q1l.w*q2l.y) - (q1l.x*q2l.z) - + (q1l.y*q2l.w) + (q1l.z*q2l.x) ); - - z = ( (q1l.w*q2l.z) + (q1l.x*q2l.y) - - (q1l.y*q2l.x) + (q1l.z*q2l.w) ); - return *this; - } - - IC SelfRef add(SelfCRef q1, SelfCRef q2) - { - x = q1.x+q2.x; - y = q1.y+q2.y; - z = q1.z+q2.z; - w = q1.w+q2.w; - return *this; - } - IC SelfRef sub(SelfCRef q1, SelfCRef q2) - { - x = q1.x-q2.x; - y = q1.y-q2.y; - z = q1.z-q2.z; - w = q1.w-q2.w; - return *this; - } - - IC SelfRef add(SelfCRef q) - { - x += q.x; - y += q.y; - z += q.z; - w += q.w; - return *this; - } - IC SelfRef sub(SelfCRef q) - { - x -= q.x; - y -= q.y; - z -= q.z; - w -= q.w; - return *this; - } - - // validates numerical stability - IC const BOOL isValid(void) const - { - if ((w * w) < 0.0f) return false; - if ((x * x) < 0.0f) return false; - if ((y * y) < 0.0f) return false; - if ((z * z) < 0.0f) return false; - return true; - } - - // checks for Unit-length quanternion - IC const BOOL isUnit(void) - { - T m = magnitude(); - - if (( m < 1.0+UNIT_TOLERANCE ) && ( m > 1.0-UNIT_TOLERANCE )) - return true; - return false; - } - - // normalizes Q to be a unit geQuaternion - IC SelfRef normalize(void) - { - T m,one_over_magnitude; - - m = _sqrt(magnitude()); - - if (( m < QZERO_TOLERANCE ) && ( m > -QZERO_TOLERANCE )) - return *this; - - one_over_magnitude = 1.0f / m; - - w *= one_over_magnitude; - x *= one_over_magnitude; - y *= one_over_magnitude; - z *= one_over_magnitude; - return *this; - } - - // inversion - IC SelfRef inverse(SelfCRef Q) - { return set(Q.w,-Q.x,-Q.y,-Q.z); } - IC SelfRef inverse() - { return set(w,-x,-y,-z); } - IC SelfRef inverse_with_w(SelfCRef Q) - { return set(-Q.w,-Q.x,-Q.y,-Q.z); } - IC SelfRef inverse_with_w() - { return set(-w,-x,-y,-z); } - - // identity - no rotation - IC SelfRef identity(void) - { return set(1.f,0.f,0.f,0.f); } - - // square length - IC T magnitude(void) { - return w*w + x*x + y*y + z*z; - } - - // makes unit rotation - IC SelfRef rotationYawPitchRoll(T _x, T _y, T _z) - { - T fSinYaw = _sin(_x*.5f); - T fCosYaw = _cos(_x*.5f); - T fSinPitch = _sin(_y*.5f); - T fCosPitch = _cos(_y*.5f); - T fSinRoll = _sin(_z*.5f); - T fCosRoll = _cos(_z*.5f); - - x = fSinRoll * fCosPitch * fCosYaw - fCosRoll * fSinPitch * fSinYaw; - y = fCosRoll * fSinPitch * fCosYaw + fSinRoll * fCosPitch * fSinYaw; - z = fCosRoll * fCosPitch * fSinYaw - fSinRoll * fSinPitch * fCosYaw; - w = fCosRoll * fCosPitch * fCosYaw + fSinRoll * fSinPitch * fSinYaw; - return *this; - } - - // makes unit rotation - IC SelfRef rotationYawPitchRoll(const Fvector &ypr) - { return rotationYawPitchRoll(ypr.x,ypr.y,ypr.z); } - - // set a quaternion from an axis and a rotation around the axis - IC SelfRef rotation(Fvector &axis, T angle) - { - T sinTheta; - - w = _cos(angle*0.5f); - sinTheta= _sin(angle*0.5f); - x = sinTheta * axis.x; - y = sinTheta * axis.y; - z = sinTheta * axis.z; - return *this; - } - - // gets an axis and angle of rotation around the axis from a quaternion - // returns TRUE if there is an axis. - // returns FALSE if there is no axis (and Axis is set to 0,0,0, and Theta is 0) - - IC BOOL get_axis_angle(Fvector &axis, T &angle) - { - T s = _sqrt(x*x + y*y + z*z); - if ( s > EPS_S ) { - T OneOverSinTheta = 1.f/s; - axis.x = OneOverSinTheta * x; - axis.y = OneOverSinTheta * y; - axis.z = OneOverSinTheta * z; - angle = 2.0f * atan2(s,w); - return true; - } else { - axis.x = axis.y = axis.z = 0.0f; - angle = 0.0f; - return false; - } - } - - // spherical interpolation between q0 and q1. 0<=t<=1 - // resulting quaternion is 'between' q0 and q1 - // with t==0 being all q0, and t==1 being all q1. - // returns a quaternion with a positive W - always takes shortest route - // through the positive W domain. - ICF SelfRef slerp(SelfCRef Q0, SelfCRef Q1, T tm) - { - T Scale0,Scale1,sign; - -#ifdef DEBUG - if (!( ( T(0) <= tm ) && ( tm <= T(1) ) ) ) - Debug.fatal(DEBUG_INFO,"Quaternion::slerp - invalid 'tm' arrived: %f",tm); + T x, y, z, w; + + IC SelfRef set(T W, T X, T Y, T Z) // don't normalize + { + x = X; y = Y; z = Z; w = W; return *this; + } + IC SelfRef set(SelfCRef Q) // don't normalize + { + set(Q.w, Q.x, Q.y, Q.z); return *this; + } + + IC SelfRef set(const _matrix& m); + + // multiplies q1 * q2, and places the result in *this. + // no failure. renormalization not automatic + + /* + q1*q2 = q3 = + (w1*w2 - x1*x2 - y1*y2 - z1*z2) {w3} + (w1*x2 + x1*w2 + y1*z2 - z1*y2)i {x3} + (w1*y2 - x1*z2 + y1*w2 + z1*x2)j {y3} + (w1*z2 + x1*y2 - y1*x2 + z1*w2)k {z3} + */ + IC SelfRef mul(SelfCRef q1l, SelfCRef q2l) + { + VERIFY(q1l.isValid()); + VERIFY(q2l.isValid()); + + w = ((q1l.w*q2l.w) - (q1l.x*q2l.x) + - (q1l.y*q2l.y) - (q1l.z*q2l.z)); + + x = ((q1l.w*q2l.x) + (q1l.x*q2l.w) + + (q1l.y*q2l.z) - (q1l.z*q2l.y)); + + y = ((q1l.w*q2l.y) - (q1l.x*q2l.z) + + (q1l.y*q2l.w) + (q1l.z*q2l.x)); + + z = ((q1l.w*q2l.z) + (q1l.x*q2l.y) + - (q1l.y*q2l.x) + (q1l.z*q2l.w)); + return *this; + } + + IC SelfRef add(SelfCRef q1, SelfCRef q2) + { + x = q1.x + q2.x; + y = q1.y + q2.y; + z = q1.z + q2.z; + w = q1.w + q2.w; + return *this; + } + IC SelfRef sub(SelfCRef q1, SelfCRef q2) + { + x = q1.x - q2.x; + y = q1.y - q2.y; + z = q1.z - q2.z; + w = q1.w - q2.w; + return *this; + } + + IC SelfRef add(SelfCRef q) + { + x += q.x; + y += q.y; + z += q.z; + w += q.w; + return *this; + } + IC SelfRef sub(SelfCRef q) + { + x -= q.x; + y -= q.y; + z -= q.z; + w -= q.w; + return *this; + } + + // validates numerical stability + IC const BOOL isValid(void) const + { + if ((w * w) < 0.0f) return false; + if ((x * x) < 0.0f) return false; + if ((y * y) < 0.0f) return false; + if ((z * z) < 0.0f) return false; + return true; + } + + // checks for Unit-length quanternion + IC const BOOL isUnit(void) + { + T m = magnitude(); + + if ((m < 1.0 + UNIT_TOLERANCE) && (m > 1.0 - UNIT_TOLERANCE)) + return true; + return false; + } + + // normalizes Q to be a unit geQuaternion + IC SelfRef normalize(void) + { + T m, one_over_magnitude; + + m = _sqrt(magnitude()); + + if ((m < QZERO_TOLERANCE) && (m > -QZERO_TOLERANCE)) + return *this; + + one_over_magnitude = 1.0f / m; + + w *= one_over_magnitude; + x *= one_over_magnitude; + y *= one_over_magnitude; + z *= one_over_magnitude; + return *this; + } + + // inversion + IC SelfRef inverse(SelfCRef Q) + { + return set(Q.w, -Q.x, -Q.y, -Q.z); + } + IC SelfRef inverse() + { + return set(w, -x, -y, -z); + } + IC SelfRef inverse_with_w(SelfCRef Q) + { + return set(-Q.w, -Q.x, -Q.y, -Q.z); + } + IC SelfRef inverse_with_w() + { + return set(-w, -x, -y, -z); + } + + // identity - no rotation + IC SelfRef identity(void) + { + return set(1.f, 0.f, 0.f, 0.f); + } + + // square length + IC T magnitude(void) + { + return w*w + x*x + y*y + z*z; + } + + // makes unit rotation + IC SelfRef rotationYawPitchRoll(T _x, T _y, T _z) + { + T fSinYaw = _sin(_x*.5f); + T fCosYaw = _cos(_x*.5f); + T fSinPitch = _sin(_y*.5f); + T fCosPitch = _cos(_y*.5f); + T fSinRoll = _sin(_z*.5f); + T fCosRoll = _cos(_z*.5f); + + x = fSinRoll * fCosPitch * fCosYaw - fCosRoll * fSinPitch * fSinYaw; + y = fCosRoll * fSinPitch * fCosYaw + fSinRoll * fCosPitch * fSinYaw; + z = fCosRoll * fCosPitch * fSinYaw - fSinRoll * fSinPitch * fCosYaw; + w = fCosRoll * fCosPitch * fCosYaw + fSinRoll * fSinPitch * fSinYaw; + return *this; + } + + // makes unit rotation + IC SelfRef rotationYawPitchRoll(const Fvector& ypr) + { + return rotationYawPitchRoll(ypr.x, ypr.y, ypr.z); + } + + // set a quaternion from an axis and a rotation around the axis + IC SelfRef rotation(Fvector& axis, T angle) + { + T sinTheta; + + w = _cos(angle*0.5f); + sinTheta = _sin(angle*0.5f); + x = sinTheta * axis.x; + y = sinTheta * axis.y; + z = sinTheta * axis.z; + return *this; + } + + // gets an axis and angle of rotation around the axis from a quaternion + // returns TRUE if there is an axis. + // returns FALSE if there is no axis (and Axis is set to 0,0,0, and Theta is 0) + + IC BOOL get_axis_angle(Fvector& axis, T& angle) + { + T s = _sqrt(x*x + y*y + z*z); + if (s > EPS_S) + { + T OneOverSinTheta = 1.f / s; + axis.x = OneOverSinTheta * x; + axis.y = OneOverSinTheta * y; + axis.z = OneOverSinTheta * z; + angle = 2.0f * atan2(s, w); + return true; + } + else + { + axis.x = axis.y = axis.z = 0.0f; + angle = 0.0f; + return false; + } + } + + // spherical interpolation between q0 and q1. 0<=t<=1 + // resulting quaternion is 'between' q0 and q1 + // with t==0 being all q0, and t==1 being all q1. + // returns a quaternion with a positive W - always takes shortest route + // through the positive W domain. + ICF SelfRef slerp(SelfCRef Q0, SelfCRef Q1, T tm) + { + T Scale0, Scale1, sign; + +#ifdef DEBUG + if (!((T(0) <= tm) && (tm <= T(1)))) + Debug.fatal(DEBUG_INFO, "Quaternion::slerp - invalid 'tm' arrived: %f", tm); #endif - - T cosom = (Q0.w * Q1.w) + (Q0.x * Q1.x) + (Q0.y * Q1.y) + (Q0.z * Q1.z); - - if (cosom < 0) { - cosom = -cosom; - sign = -1.f; - } else { - sign = 1.f; - } - - if ( (1.0f - cosom) > EPS ) { - T omega = _acos_( cosom ); - T i_sinom = 1.f / _sin( omega ); - T t_omega = tm*omega; - Scale0 = _sin( omega - t_omega ) * i_sinom; - Scale1 = _sin( t_omega ) * i_sinom; - } else { - // has numerical difficulties around cosom == 0 - // in this case degenerate to linear interpolation - Scale0 = 1.0f - tm; - Scale1 = tm; - } - Scale1 *= sign; - - x = Scale0 * Q0.x + Scale1 * Q1.x; - y = Scale0 * Q0.y + Scale1 * Q1.y; - z = Scale0 * Q0.z + Scale1 * Q1.z; - w = Scale0 * Q0.w + Scale1 * Q1.w; - return *this; - } - - // return TRUE if quaternions differ elementwise by less than Tolerance. - IC BOOL cmp(SelfCRef Q, T Tolerance=0.0001f) - { - if ( // they are the same but with opposite signs - ( (_abs(x + Q.x) <= Tolerance ) - && (_abs(y + Q.y) <= Tolerance ) - && (_abs(z + Q.z) <= Tolerance ) - && (_abs(w + Q.w) <= Tolerance ) - ) - || // they are the same with same signs - ( (_abs(x - Q.x) <= Tolerance ) - && (_abs(y - Q.y) <= Tolerance ) - && (_abs(z - Q.z) <= Tolerance ) - && (_abs(w - Q.w) <= Tolerance ) - ) - ) - return true; - else - return false; - } - IC SelfRef ln(SelfCRef Q) - { - T n = Q.x*Q.x+Q.y*Q.y+Q.z*Q.z; - T r = _sqrt(n); - T t = (r>EPS_S)?atan2f(r,Q.w)/r: 0.f; - x = t*Q.x; - y = t*Q.y; - z = t*Q.z; - w = .5f*_log(n+Q.w*Q.w); - return *this; - } - IC SelfRef exp(SelfCRef Q) - { - T r = _sqrt(Q.x*Q.x+Q.y*Q.y+Q.z*Q.z); - T et = expf(Q.w); - T s = (r>=EPS_S)? et*_sin(r)/r: 0.f; - x = s*Q.x; - y = s*Q.y; - z = s*Q.z; - w = et*_cos(r); - return *this; - } + + T cosom = (Q0.w * Q1.w) + (Q0.x * Q1.x) + (Q0.y * Q1.y) + (Q0.z * Q1.z); + + if (cosom < 0) + { + cosom = -cosom; + sign = -1.f; + } + else + { + sign = 1.f; + } + + if ((1.0f - cosom) > EPS) + { + T omega = _acos_(cosom); + T i_sinom = 1.f / _sin(omega); + T t_omega = tm*omega; + Scale0 = _sin(omega - t_omega) * i_sinom; + Scale1 = _sin(t_omega) * i_sinom; + } + else + { + // has numerical difficulties around cosom == 0 + // in this case degenerate to linear interpolation + Scale0 = 1.0f - tm; + Scale1 = tm; + } + Scale1 *= sign; + + x = Scale0 * Q0.x + Scale1 * Q1.x; + y = Scale0 * Q0.y + Scale1 * Q1.y; + z = Scale0 * Q0.z + Scale1 * Q1.z; + w = Scale0 * Q0.w + Scale1 * Q1.w; + return *this; + } + + // return TRUE if quaternions differ elementwise by less than Tolerance. + IC BOOL cmp(SelfCRef Q, T Tolerance = 0.0001f) + { + if ( // they are the same but with opposite signs + ((_abs(x + Q.x) <= Tolerance) + && (_abs(y + Q.y) <= Tolerance) + && (_abs(z + Q.z) <= Tolerance) + && (_abs(w + Q.w) <= Tolerance) + ) + || // they are the same with same signs + ((_abs(x - Q.x) <= Tolerance) + && (_abs(y - Q.y) <= Tolerance) + && (_abs(z - Q.z) <= Tolerance) + && (_abs(w - Q.w) <= Tolerance) + ) + ) + return true; + else + return false; + } + IC SelfRef ln(SelfCRef Q) + { + T n = Q.x*Q.x + Q.y*Q.y + Q.z*Q.z; + T r = _sqrt(n); + T t = (r > EPS_S) ? atan2f(r, Q.w) / r : 0.f; + x = t*Q.x; + y = t*Q.y; + z = t*Q.z; + w = .5f*_log(n + Q.w*Q.w); + return *this; + } + IC SelfRef exp(SelfCRef Q) + { + T r = _sqrt(Q.x*Q.x + Q.y*Q.y + Q.z*Q.z); + T et = expf(Q.w); + T s = (r >= EPS_S) ? et*_sin(r) / r : 0.f; + x = s*Q.x; + y = s*Q.y; + z = s*Q.z; + w = et*_cos(r); + return *this; + } }; -typedef _quaternion Fquaternion; -typedef _quaternion Dquaternion; +typedef _quaternion Fquaternion; +typedef _quaternion Dquaternion; template -BOOL _valid (const _quaternion& s) { return _valid(s.x) && _valid(s.y) && _valid(s.z) && _valid(s.w); } +BOOL _valid(const _quaternion& s) { return _valid(s.x) && _valid(s.y) && _valid(s.z) && _valid(s.w); } #undef UNIT_TOLERANCE #undef QZERO_TOLERANCE diff --git a/src/xrCore/_random.h b/src/xrCore/_random.h index 86d7806c24b..17e82ae79a5 100644 --- a/src/xrCore/_random.h +++ b/src/xrCore/_random.h @@ -5,44 +5,44 @@ u32 dwRandSeed; IC u32 dwfRandom(u32 dwRange) { - u32 dwResult; - __asm { - mov eax,dwRange _eax = dwRange - imul edx,dwRandSeed,08088405H - inc edx - mov dwRandSeed,edx dwRandSeed = (dwRandSeed * 08088405H)+1 - mul edx return (u64(dwRange) * u64(dwRandSeed)) >> 32 - mov dwResult,edx - } - return(dwResult); +u32 dwResult; +__asm { +mov eax,dwRange _eax = dwRange +imul edx,dwRandSeed,08088405H +inc edx +mov dwRandSeed,edx dwRandSeed = (dwRandSeed * 08088405H)+1 +mul edx return (u64(dwRange) * u64(dwRandSeed)) >> 32 +mov dwResult,edx +} +return(dwResult); } */ class CRandom { private: - volatile s32 holdrand; + volatile s32 holdrand; public: - CRandom() : holdrand(1) {}; - CRandom(s32 _seed) : holdrand(_seed) {}; + CRandom() : holdrand(1) {}; + CRandom(s32 _seed) : holdrand(_seed) {}; - IC void seed (s32 val) { holdrand=val; } - IC s32 maxI () { return 32767; } + IC void seed(s32 val) { holdrand = val; } + IC s32 maxI() { return 32767; } - ICN s32 randI () { return(((holdrand = holdrand * 214013L + 2531011L) >> 16) & 0x7fff); } - IC s32 randI (s32 max) { VERIFY(max); return randI()%max; } - IC s32 randI (s32 min, s32 max) { return min+randI(max-min); } - IC s32 randIs (s32 range) { return randI(-range,range); } - IC s32 randIs (s32 range, s32 offs) { return offs+randIs(range); } + ICN s32 randI() { return(((holdrand = holdrand * 214013L + 2531011L) >> 16) & 0x7fff); } + IC s32 randI(s32 max) { VERIFY(max); return randI() % max; } + IC s32 randI(s32 min, s32 max) { return min + randI(max - min); } + IC s32 randIs(s32 range) { return randI(-range, range); } + IC s32 randIs(s32 range, s32 offs) { return offs + randIs(range); } - IC float maxF () { return 32767.f; } - IC float randF () { return float(randI())/maxF(); } - IC float randF (float max) { return randF()*max; } - IC float randF (float min,float max) { return min+randF(max-min); } - IC float randFs (float range) { return randF(-range,range); } - IC float randFs (float range, float offs) { return offs+randFs(range); } + IC float maxF() { return 32767.f; } + IC float randF() { return float(randI()) / maxF(); } + IC float randF(float max) { return randF()*max; } + IC float randF(float min, float max) { return min + randF(max - min); } + IC float randFs(float range) { return randF(-range, range); } + IC float randFs(float range, float offs) { return offs + randFs(range); } }; -XRCORE_API extern CRandom Random; +XRCORE_API extern CRandom Random; #endif \ No newline at end of file diff --git a/src/xrCore/_rect.h b/src/xrCore/_rect.h index a625ce34a1b..68169082c4f 100644 --- a/src/xrCore/_rect.h +++ b/src/xrCore/_rect.h @@ -2,89 +2,94 @@ #define __FRECT template -struct _rect { +struct _rect +{ public: - typedef T TYPE; - typedef _rect Self; - typedef Self& SelfRef; - typedef const Self& SelfCRef; - typedef _vector2 Tvector; + typedef T TYPE; + typedef _rect Self; + typedef Self& SelfRef; + typedef const Self& SelfCRef; + typedef _vector2 Tvector; public: - union{ - struct{ - T x1, y1, x2, y2; - }; - struct{ - T left, top, right, bottom; - }; - - struct{ - Tvector lt; - Tvector rb; - }; - T m[4]; - }; - - IC SelfRef set(const T _x1, const T _y1, const T _x2, const T _y2) { x1=_x1; y1=_y1; x2=_x2; y2=_y2; return *this; }; - IC SelfRef set(const Tvector &mn, const Tvector &mx) { x1=mn.x; y1=mn.y; x2=mx.x; y2=mx.y; return *this; }; - IC SelfRef set(const Self &r) { x1=r.x1; y1=r.y1; x2=r.x2; y2=r.y2; return *this; }; - IC SelfRef null( ) { x1=T(0); y1=T(0); x2=T(0); y2=T(0); return *this; }; - - IC SelfRef invalidate() { lt.x=type_max(T); lt.y=type_max(T); rb.x=type_min(T); rb.y=type_min(T); return *this; }; - IC bool valide () { return lt.x1 < rb.x && lt.y < rb.y; } - IC SelfRef set_empty () { return invalidate(); } - IC bool is_empty () { return !valide(); } - IC SelfRef add(T x, T y) { x1+=x; y1+=y; x2+=x; y2+=y; return *this; }; - IC SelfRef sub(T x, T y) { x1-=x; y1-=y; x2-=x; y2-=y; return *this; }; - IC SelfRef mul(T x, T y) { x1*=x; y1*=y; x2*=x; y2*=y; return *this; }; - IC SelfRef div(T x, T y) { x1/=x; y1/=y; x2/=x; y2/=y; return *this; }; - - IC SelfRef add(const Self& r, T x, T y) { x1=r.x1+x; y1=r.y1+y; x2=r.x2+x; y2=r.y2+y; return *this; }; - IC SelfRef sub(const Self& r, T x, T y) { x1=r.x1-x; y1=r.y1-y; x2=r.x2-x; y2=r.y2-y; return *this; }; - IC SelfRef mul(const Self& r, T x, T y) { x1=r.x1*x; y1=r.y1*y; x2=r.x2*x; y2=r.y2*y; return *this; }; - IC SelfRef div(const Self& r, T x, T y) { x1=r.x1/x; y1=r.y1/y; x2=r.x2/x; y2=r.y2/y; return *this; }; - - IC BOOL in (T x, T y) const { return (x>=x1) && (x<=x2) && (y>=y1) && (y<=y2); }; - IC BOOL in (Tvector &p) const { return (p.x>=x1) && (p.x<=x2) && (p.y>=y1) && (p.y<=y2); }; - IC BOOL cmp(_rect &r) { return x1==r.x1 && y1==r.y1 && x2==r.x2 && y2==r.y2; }; - IC BOOL cmp(_rect &r) { return fsimilar(x1,r.x1) && fsimilar(y1,r.y1) && fsimilar(x2,r.x2) && fsimilar(y2,r.y2); }; - - IC void getcenter(Tvector& center) const { center.add(rb,lt); center.div(2); } - IC void getsize(Tvector& sz) const { sz.sub(rb,lt); } - - IC T width() const {return rb.x-lt.x;} - IC T height() const {return rb.y-lt.y;} - - IC SelfRef shrink(T x, T y) { lt.x+=x; lt.y+=y; rb.x-=x; rb.y-=y; return *this; }; - IC SelfRef grow(T x, T y) { lt.x-=x; lt.y-=y; rb.x+=x; rb.y+=y; return *this; }; - - - - IC BOOL intersected(SelfCRef b1, SelfCRef b2) const {return !(b1.x1>b2.x2 || b1.x2b2.y2 || b1.y2= x1) && (x <= x2) && (y >= y1) && (y <= y2); }; + IC BOOL in(Tvector& p) const { return (p.x >= x1) && (p.x <= x2) && (p.y >= y1) && (p.y <= y2); }; + IC BOOL cmp(_rect& r) { return x1 == r.x1 && y1 == r.y1 && x2 == r.x2 && y2 == r.y2; }; + IC BOOL cmp(_rect& r) { return fsimilar(x1, r.x1) && fsimilar(y1, r.y1) && fsimilar(x2, r.x2) && fsimilar(y2, r.y2); }; + + IC void getcenter(Tvector& center) const { center.add(rb, lt); center.div(2); } + IC void getsize(Tvector& sz) const { sz.sub(rb, lt); } + + IC T width() const { return rb.x - lt.x; } + IC T height() const { return rb.y - lt.y; } + + IC SelfRef shrink(T x, T y) { lt.x += x; lt.y += y; rb.x -= x; rb.y -= y; return *this; }; + IC SelfRef grow(T x, T y) { lt.x -= x; lt.y -= y; rb.x += x; rb.y += y; return *this; }; + + + + IC BOOL intersected(SelfCRef b1, SelfCRef b2) const { return !(b1.x1 > b2.x2 || b1.x2b2.y2 || b1.y2 < b2.y1); } + IC BOOL intersected(SelfCRef b) const { return intersected(*this, b); } + + IC BOOL intersection(SelfCRef b1, SelfCRef b2) + { + if (!intersected(b1, b2)) + return (FALSE); + + x1 = _max(b1.x1, b2.x1); + y1 = _max(b1.y1, b2.y1); + x2 = _min(b1.x2, b2.x2); + y2 = _min(b1.y2, b2.y2); + return (TRUE); + } }; -typedef _rect Frect; -typedef _rect Drect; -typedef _rect Irect; +typedef _rect Frect; +typedef _rect Drect; +typedef _rect Irect; template -BOOL _valid (const _rect& m) -{ - return lt._valid() && rb._valid(); +BOOL _valid(const _rect& m) +{ + return lt._valid() && rb._valid(); } #endif diff --git a/src/xrCore/_sphere.cpp b/src/xrCore/_sphere.cpp index 2379fd1be6a..12e0801b0f5 100644 --- a/src/xrCore/_sphere.cpp +++ b/src/xrCore/_sphere.cpp @@ -6,39 +6,39 @@ class Basis; // Basis // ----- -class Basis +class Basis { private: - enum { d = 3 } eDimensions; + enum { d = 3 } eDimensions; - // data members - int m, s; // size and number of support vectors + // data members + int m, s; // size and number of support vectors - Fvector q0; + Fvector q0; - float z[d+1]; - float f[d+1]; - Fvector v[d+1]; - Fvector a[d+1]; - Fvector c[d+1]; - float sqr_r[d+1]; + float z[d + 1]; + float f[d + 1]; + Fvector v[d + 1]; + Fvector a[d + 1]; + Fvector c[d + 1]; + float sqr_r[d + 1]; - Fvector* current_c; // vectors to some c[j] - float current_sqr_r; + Fvector* current_c; // vectors to some c[j] + float current_sqr_r; public: - Basis(); - - // access - const Fvector* center () const; - float squared_radius () const; - int size () const; - int support_size () const; - float excess (const Fvector& p) const; - - // modification - void reset (); // generates empty sphere with m=s=0 - bool push (const Fvector& p); - void pop (); + Basis(); + + // access + const Fvector* center() const; + float squared_radius() const; + int size() const; + int support_size() const; + float excess(const Fvector& p) const; + + // modification + void reset(); // generates empty sphere with m=s=0 + bool push(const Fvector& p); + void pop(); }; // Miniball @@ -46,295 +46,295 @@ class Basis class Miniball { public: - // types - typedef xr_list VectorList; - typedef VectorList::iterator It; - typedef VectorList::const_iterator Cit; + // types + typedef xr_list VectorList; + typedef VectorList::iterator It; + typedef VectorList::const_iterator Cit; private: - // data members - VectorList L; // STL list keeping the gVectors - Basis B; // basis keeping the current ball - It support_end; // past-the-end iterator of support set - - // private methods - void mtf_mb (It k); - void pivot_mb (It k); - void move_to_front (It j); - float max_excess (It t, It i, It& pivot) const; - float abs (float r) const {return (r>0)? r: (-r);} - float sqr (float r) const {return r*r;} + // data members + VectorList L; // STL list keeping the gVectors + Basis B; // basis keeping the current ball + It support_end; // past-the-end iterator of support set + + // private methods + void mtf_mb(It k); + void pivot_mb(It k); + void move_to_front(It j); + float max_excess(It t, It i, It& pivot) const; + float abs(float r) const { return (r > 0) ? r : (-r); } + float sqr(float r) const { return r*r; } public: - // construction - Miniball() {} - void check_in (const Fvector& p); - void build (); - - // access - Fvector center () const; - float squared_radius () const; - int num_points () const; - Cit points_begin () const; - Cit points_end () const; - int nr_support_gVectors () const; - Cit support_points_begin () const; - Cit support_points_end () const; + // construction + Miniball() {} + void check_in(const Fvector& p); + void build(); + + // access + Fvector center() const; + float squared_radius() const; + int num_points() const; + Cit points_begin() const; + Cit points_end() const; + int nr_support_gVectors() const; + Cit support_points_begin() const; + Cit support_points_end() const; }; // Miniball // -------- -void Miniball::check_in (const Fvector& p) +void Miniball::check_in(const Fvector& p) { - L.push_back(p); + L.push_back(p); } -void Miniball::build () +void Miniball::build() { - B.reset(); - support_end = L.begin(); - - // @@ pivotting or not ? - if ( 1 ) - pivot_mb (L.end()); - else - mtf_mb (L.end()); + B.reset(); + support_end = L.begin(); + + // @@ pivotting or not ? + if (1) + pivot_mb(L.end()); + else + mtf_mb(L.end()); } -void Miniball::mtf_mb (It i) +void Miniball::mtf_mb(It i) { - support_end = L.begin(); - - if ((B.size())== 4) - return; - - for (It k=L.begin(); k!=i;) - { - It j=k++; - if (B.excess(*j) > 0) - { - if (B.push(*j)) - { - mtf_mb (j); - B.pop(); - move_to_front(j); - } - } - } + support_end = L.begin(); + + if ((B.size()) == 4) + return; + + for (It k = L.begin(); k != i;) + { + It j = k++; + if (B.excess(*j) > 0) + { + if (B.push(*j)) + { + mtf_mb(j); + B.pop(); + move_to_front(j); + } + } + } } -void Miniball::move_to_front (It j) +void Miniball::move_to_front(It j) { - if (support_end == j) - support_end++; - L.splice (L.begin(), L, j); + if (support_end == j) + support_end++; + L.splice(L.begin(), L, j); } -void Miniball::pivot_mb (It i) +void Miniball::pivot_mb(It i) { - It t = ++L.begin(); - mtf_mb (t); - float max_e, old_sqr_r = 0; - do - { - It pivot = L.begin(); - max_e = max_excess (t, i, pivot); - if (max_e > 0) - { - t = support_end; - if (t==pivot) ++t; - old_sqr_r = B.squared_radius(); - B.push (*pivot); - mtf_mb (support_end); - B.pop(); - move_to_front (pivot); - } - } while ((max_e > 0) && (B.squared_radius() > old_sqr_r)); + It t = ++L.begin(); + mtf_mb(t); + float max_e, old_sqr_r = 0; + do + { + It pivot = L.begin(); + max_e = max_excess(t, i, pivot); + if (max_e > 0) + { + t = support_end; + if (t == pivot) ++t; + old_sqr_r = B.squared_radius(); + B.push(*pivot); + mtf_mb(support_end); + B.pop(); + move_to_front(pivot); + } + } while ((max_e > 0) && (B.squared_radius() > old_sqr_r)); } -float Miniball::max_excess (It t, It i, It& pivot) const +float Miniball::max_excess(It t, It i, It& pivot) const { - const Fvector* pCenter = B.center(); - float sqr_r = B.squared_radius(); + const Fvector* pCenter = B.center(); + float sqr_r = B.squared_radius(); - float e, max_e = 0; + float e, max_e = 0; - for (It k=t; k!=i; ++k) - { - const Fvector & point = (*k); - e = -sqr_r; + for (It k = t; k != i; ++k) + { + const Fvector& point = (*k); + e = -sqr_r; - e += point.distance_to_sqr(*pCenter); + e += point.distance_to_sqr(*pCenter); - if (e > max_e) - { - max_e = e; - pivot = k; - } - } + if (e > max_e) + { + max_e = e; + pivot = k; + } + } - return max_e; + return max_e; } -Fvector Miniball::center () const +Fvector Miniball::center() const { - return *((Fvector *)B.center()); + return *((Fvector*)B.center()); } -float Miniball::squared_radius () const +float Miniball::squared_radius() const { - return B.squared_radius(); + return B.squared_radius(); } -int Miniball::num_points () const +int Miniball::num_points() const { - return L.size(); + return L.size(); } -Miniball::Cit Miniball::points_begin () const +Miniball::Cit Miniball::points_begin() const { - return L.begin(); + return L.begin(); } -Miniball::Cit Miniball::points_end () const +Miniball::Cit Miniball::points_end() const { - return L.end(); + return L.end(); } -int Miniball::nr_support_gVectors () const +int Miniball::nr_support_gVectors() const { - return B.support_size(); + return B.support_size(); } -Miniball::Cit Miniball::support_points_begin () const +Miniball::Cit Miniball::support_points_begin() const { - return L.begin(); + return L.begin(); } -Miniball::Cit Miniball::support_points_end () const +Miniball::Cit Miniball::support_points_end() const { - return support_end; + return support_end; } //---------------------------------------------------------------------- // Basis //--------------------------------------------------------------------- -const Fvector* Basis::center () const +const Fvector* Basis::center() const { - return current_c; + return current_c; } float Basis::squared_radius() const { - return current_sqr_r; + return current_sqr_r; } int Basis::size() const { - return m; + return m; } int Basis::support_size() const { - return s; + return s; } -float Basis::excess (const Fvector& p) const +float Basis::excess(const Fvector& p) const { - float e = -current_sqr_r; - e += p.distance_to_sqr(*current_c); - return e; + float e = -current_sqr_r; + e += p.distance_to_sqr(*current_c); + return e; } -void Basis::reset () +void Basis::reset() { - m = s = 0; - // we misuse c[0] for the center of the empty sphere - c[0].set(0,0,0); - current_c = c; - current_sqr_r = -1; + m = s = 0; + // we misuse c[0] for the center of the empty sphere + c[0].set(0, 0, 0); + current_c = c; + current_sqr_r = -1; } -Basis::Basis () +Basis::Basis() { - reset(); + reset(); } -void Basis::pop () +void Basis::pop() { - --m; + --m; } -bool Basis::push (const Fvector& p) +bool Basis::push(const Fvector& p) { - if (m==0) - { - q0 = p; - c[0] = q0; - sqr_r[0] = 0; - } - else - { - int i; - const float eps = 1e-16f; - - // set v_m to Q_m - v[m].sub(p,q0); - - // compute the a_{m,i}, i< m - for (i=1; i -struct _sphere { - _vector3 P; - T R; +struct _sphere +{ + _vector3 P; + T R; public: - IC void set(const _vector3 &_P, T _R) { P.set(_P); R = _R; } - IC void set(const _sphere &S) { P.set(S.P); R=S.R; } - IC void identity() { P.set(0,0,0); R=1; } - - enum ERP_Result{ - rpNone = 0, - rpOriginInside = 1, - rpOriginOutside = 2, - fcv_forcedword = u32(-1) - }; - // Ray-sphere intersection - ICF ERP_Result intersect (const _vector3& S, const _vector3& D, T range, int& quantity, T afT[2]) const - { - // set up quadratic Q(t) = a*t^2 + 2*b*t + c - _vector3 kDiff; kDiff.sub (S,P); - T fA = range*range; - T fB = kDiff.dotproduct(D) * range; - T fC = kDiff.square_magnitude() - R*R; - ERP_Result result = rpNone; - - T fDiscr = fB*fB - fA*fC; - if ( fDiscr < (T)0.0 ){ - quantity = 0; - } else if ( fDiscr > (T)0.0 ){ - T fRoot = _sqrt(fDiscr); - T fInvA = ((T)1.0)/fA; - afT[0] = range*(-fB - fRoot)*fInvA; - afT[1] = range*(-fB + fRoot)*fInvA; - if ( afT[0] >= (T)0.0 ) { quantity = 2; result = rpOriginOutside; } - else if ( afT[1] >= (T)0.0 ){ quantity = 1; afT[0] = afT[1]; result = rpOriginInside; } - else quantity = 0; - } else { - afT[0] = range*(-fB/fA); - if ( afT[0] >= (T)0.0 ) { quantity = 1; result = rpOriginOutside; } - else quantity = 0; - } - return result; - } -/* - int quantity; - float afT[2]; - Fsphere::ERP_Result result = sS.intersect(ray.pos,ray.fwd_dir,range,quantity,afT); - - if (Fsphere::rpOriginInside || ((result==Fsphere::rpOriginOutside)&&(afT[0]& start, const _vector3& dir, T& dist) const - { - int quantity; - float afT[2]; - Fsphere::ERP_Result result = intersect(start,dir,dist,quantity,afT); - - if (result == Fsphere::rpOriginInside || ((result==Fsphere::rpOriginOutside)&&(afT[0]& start, const _vector3& dir, T& dist) const - { - int quantity; - T afT[2]; - ERP_Result result = intersect(start,dir,dist,quantity,afT); - if (rpNone!=result){ - VERIFY (quantity>0); - if (afT[0]& S, const _vector3& D, T& range) const + IC void set(const _vector3& _P, T _R) { P.set(_P); R = _R; } + IC void set(const _sphere& S) { P.set(S.P); R = S.R; } + IC void identity() { P.set(0, 0, 0); R = 1; } + + enum ERP_Result + { + rpNone = 0, + rpOriginInside = 1, + rpOriginOutside = 2, + fcv_forcedword = u32(-1) + }; + // Ray-sphere intersection + ICF ERP_Result intersect(const _vector3& S, const _vector3& D, T range, int& quantity, T afT[2]) const + { + // set up quadratic Q(t) = a*t^2 + 2*b*t + c + _vector3 kDiff; + kDiff.sub(S, P); + T fA = range*range; + T fB = kDiff.dotproduct(D) * range; + T fC = kDiff.square_magnitude() - R*R; + ERP_Result result = rpNone; + + T fDiscr = fB*fB - fA*fC; + if (fDiscr < (T)0.0) + { + quantity = 0; + } + else if (fDiscr > (T)0.0) + { + T fRoot = _sqrt(fDiscr); + T fInvA = ((T)1.0) / fA; + afT[0] = range*(-fB - fRoot)*fInvA; + afT[1] = range*(-fB + fRoot)*fInvA; + if (afT[0] >= (T)0.0) { quantity = 2; result = rpOriginOutside; } + else if (afT[1] >= (T)0.0) { quantity = 1; afT[0] = afT[1]; result = rpOriginInside; } + else quantity = 0; + } + else + { + afT[0] = range*(-fB / fA); + if (afT[0] >= (T)0.0) { quantity = 1; result = rpOriginOutside; } + else quantity = 0; + } + return result; + } + /* + int quantity; + float afT[2]; + Fsphere::ERP_Result result = sS.intersect(ray.pos,ray.fwd_dir,range,quantity,afT); + + if (Fsphere::rpOriginInside || ((result==Fsphere::rpOriginOutside)&&(afT[0]& start, const _vector3& dir, T& dist) const + { + int quantity; + float afT[2]; + Fsphere::ERP_Result result = intersect(start, dir, dist, quantity, afT); + + if (result == Fsphere::rpOriginInside || ((result == Fsphere::rpOriginOutside) && (afT[0] < dist))) + { + switch (result) + { + case Fsphere::rpOriginInside: + dist = afT[0] < dist ? afT[0] : dist; + break; + case Fsphere::rpOriginOutside: + dist = afT[0]; + break; + } + } + return result; + } + + ICF ERP_Result intersect(const _vector3& start, const _vector3& dir, T& dist) const + { + int quantity; + T afT[2]; + ERP_Result result = intersect(start, dir, dist, quantity, afT); + if (rpNone != result) + { + VERIFY(quantity > 0); + if (afT[0] < dist) + { + dist = afT[0]; + return result; + } + } + return rpNone; + } + + IC ERP_Result intersect2(const _vector3& S, const _vector3& D, T& range) const + { + _vector3 Q; + Q.sub(P, S); + + T R2 = R*R; + T c2 = Q.square_magnitude(); + T v = Q.dotproduct(D); + T d = R2 - (c2 - v*v); + + if (d > 0.f) + { + T _range = v - _sqrt(d); + if (_range < range) + { + range = _range; + return (c2 < R2) ? rpOriginInside : rpOriginOutside; + } + } + return rpNone; + } + ICF BOOL intersect(const _vector3& S, const _vector3& D) const + { + _vector3 Q; + Q.sub(P, S); + + T c = Q.magnitude(); + T v = Q.dotproduct(D); + T d = R*R - (c*c - v*v); + return (d > 0); + } + ICF BOOL intersect(const _sphere& S) const + { + T SumR = R + S.R; + return P.distance_to_sqr(S.P) < SumR*SumR; + } + IC BOOL contains(const _vector3& PT) const + { + return P.distance_to_sqr(PT) <= (R*R + EPS_S); + } + + // returns true if this wholly contains the argument sphere + IC BOOL contains(const _sphere& S) const + { + // can't contain a sphere that's bigger than me ! + const T RDiff = R - S.R; + if (RDiff < 0) return false; + + return (P.distance_to_sqr(S.P) <= RDiff*RDiff); + } + + // return's volume of sphere + IC T volume() const { - _vector3 Q; Q.sub(P,S); - - T R2 = R*R; - T c2 = Q.square_magnitude (); - T v = Q.dotproduct (D); - T d = R2 - (c2 - v*v); - - if (d > 0.f) - { - T _range = v - _sqrt(d); - if (_range& S, const _vector3& D) const - { - _vector3 Q; Q.sub(P,S); - - T c = Q.magnitude (); - T v = Q.dotproduct (D); - T d = R*R - (c*c - v*v); - return (d > 0); - } - ICF BOOL intersect(const _sphere& S) const - { - T SumR = R+S.R; - return P.distance_to_sqr(S.P) < SumR*SumR; - } - IC BOOL contains(const _vector3& PT) const - { - return P.distance_to_sqr(PT) <= (R*R+EPS_S); - } - - // returns true if this wholly contains the argument sphere - IC BOOL contains(const _sphere& S) const - { - // can't contain a sphere that's bigger than me ! - const T RDiff = R - S.R; - if ( RDiff < 0 ) return false; - - return ( P.distance_to_sqr(S.P) <= RDiff*RDiff ); - } - - // return's volume of sphere - IC T volume () const - { - return T( PI_MUL_4 / 3 ) * (R*R*R); - } + return T(PI_MUL_4 / 3) * (R*R*R); + } }; -typedef _sphere Fsphere; +typedef _sphere Fsphere; typedef _sphere Dsphere; template -BOOL _valid (const _sphere& s) { return _valid(s.P) && _valid(s.R); } +BOOL _valid(const _sphere& s) { return _valid(s.P) && _valid(s.R); } -void XRCORE_API Fsphere_compute (Fsphere& dest, const Fvector *verts, int count); +void XRCORE_API Fsphere_compute(Fsphere& dest, const Fvector* verts, int count); #endif \ No newline at end of file diff --git a/src/xrCore/_std_extensions.cpp b/src/xrCore/_std_extensions.cpp index 0d25dfd8a48..c3b152801fd 100644 --- a/src/xrCore/_std_extensions.cpp +++ b/src/xrCore/_std_extensions.cpp @@ -4,38 +4,38 @@ #include #ifdef BREAK_AT_STRCMP -int xr_strcmp ( const char* S1, const char* S2 ) +int xr_strcmp(const char* S1, const char* S2) { #ifdef DEBUG_MEMORY_MANAGER - Memory.stat_strcmp ++; + Memory.stat_strcmp++; #endif // DEBUG_MEMORY_MANAGER - int res = (int)strcmp(S1,S2); - return res; + int res = (int)strcmp(S1, S2); + return res; } #endif -char* timestamp (string64& dest) +char* timestamp(string64& dest) { - string64 temp; + string64 temp; - /* Set time zone from TZ environment variable. If TZ is not set, - * the operating system is queried to obtain the default value - * for the variable. - */ - _tzset (); - u32 it; + /* Set time zone from TZ environment variable. If TZ is not set, + * the operating system is queried to obtain the default value + * for the variable. + */ + _tzset(); + u32 it; - // date - _strdate ( temp ); - for (it=0; it IC T _min (T a, T b) { return a IC T _max (T a, T b) { return a>b?a:b; } -template IC T _sqr (T a) { return a*a; } +template IC T _min(T a, T b) { return a < b ? a : b; } +template IC T _max(T a, T b) { return a > b ? a : b; } +template IC T _sqr(T a) { return a*a; } // float -IC float _abs (float x) { return fabsf(x); } -IC float _sqrt (float x) { return sqrtf(x); } -IC float _sin (float x) { return sinf(x); } -IC float _cos (float x) { return cosf(x); } -IC BOOL _valid (const float x) +IC float _abs(float x) { return fabsf(x); } +IC float _sqrt(float x) { return sqrtf(x); } +IC float _sin(float x) { return sinf(x); } +IC float _cos(float x) { return cosf(x); } +IC BOOL _valid(const float x) { - // check for: Signaling NaN, Quiet NaN, Negative infinity ( –INF), Positive infinity (+INF), Negative denormalized, Positive denormalized - int cls = _fpclass (double(x)); - if (cls&(_FPCLASS_SNAN+_FPCLASS_QNAN+_FPCLASS_NINF+_FPCLASS_PINF+_FPCLASS_ND+_FPCLASS_PD)) - return false; - - /* *****other cases are***** - _FPCLASS_NN Negative normalized non-zero - _FPCLASS_NZ Negative zero ( – 0) - _FPCLASS_PZ Positive 0 (+0) - _FPCLASS_PN Positive normalized non-zero - */ - return true; + // check for: Signaling NaN, Quiet NaN, Negative infinity ( –INF), Positive infinity (+INF), Negative denormalized, Positive denormalized + int cls = _fpclass(double(x)); + if (cls&(_FPCLASS_SNAN + _FPCLASS_QNAN + _FPCLASS_NINF + _FPCLASS_PINF + _FPCLASS_ND + _FPCLASS_PD)) + return false; + + /* *****other cases are***** + _FPCLASS_NN Negative normalized non-zero + _FPCLASS_NZ Negative zero ( – 0) + _FPCLASS_PZ Positive 0 (+0) + _FPCLASS_PN Positive normalized non-zero + */ + return true; } // double -IC double _abs (double x) { return fabs(x); } -IC double _sqrt (double x) { return sqrt(x); } -IC double _sin (double x) { return sin(x); } -IC double _cos (double x) { return cos(x); } -IC BOOL _valid (const double x) +IC double _abs(double x) { return fabs(x); } +IC double _sqrt(double x) { return sqrt(x); } +IC double _sin(double x) { return sin(x); } +IC double _cos(double x) { return cos(x); } +IC BOOL _valid(const double x) { - // check for: Signaling NaN, Quiet NaN, Negative infinity ( –INF), Positive infinity (+INF), Negative denormalized, Positive denormalized - int cls = _fpclass (x); - if (cls&(_FPCLASS_SNAN+_FPCLASS_QNAN+_FPCLASS_NINF+_FPCLASS_PINF+_FPCLASS_ND+_FPCLASS_PD)) - return false; - - /* *****other cases are***** - _FPCLASS_NN Negative normalized non-zero - _FPCLASS_NZ Negative zero ( – 0) - _FPCLASS_PZ Positive 0 (+0) - _FPCLASS_PN Positive normalized non-zero - */ - return true; + // check for: Signaling NaN, Quiet NaN, Negative infinity ( –INF), Positive infinity (+INF), Negative denormalized, Positive denormalized + int cls = _fpclass(x); + if (cls&(_FPCLASS_SNAN + _FPCLASS_QNAN + _FPCLASS_NINF + _FPCLASS_PINF + _FPCLASS_ND + _FPCLASS_PD)) + return false; + + /* *****other cases are***** + _FPCLASS_NN Negative normalized non-zero + _FPCLASS_NZ Negative zero ( – 0) + _FPCLASS_PZ Positive 0 (+0) + _FPCLASS_PN Positive normalized non-zero + */ + return true; } // int8 -IC s8 _abs (s8 x) { return (x>=0)? x : s8(-x); } -IC s8 _min (s8 x, s8 y) { return y + ((x - y) & ((x - y) >> (sizeof(s8 ) * 8 - 1))); }; -IC s8 _max (s8 x, s8 y) { return x - ((x - y) & ((x - y) >> (sizeof(s8 ) * 8 - 1))); }; +IC s8 _abs(s8 x) { return (x >= 0) ? x : s8(-x); } +IC s8 _min(s8 x, s8 y) { return y + ((x - y) & ((x - y) >> (sizeof(s8) * 8 - 1))); }; +IC s8 _max(s8 x, s8 y) { return x - ((x - y) & ((x - y) >> (sizeof(s8) * 8 - 1))); }; // unsigned int8 -IC u8 _abs (u8 x) { return x; } +IC u8 _abs(u8 x) { return x; } // int16 -IC s16 _abs (s16 x) { return (x>=0)? x : s16(-x); } -IC s16 _min (s16 x, s16 y) { return y + ((x - y) & ((x - y) >> (sizeof(s16) * 8 - 1))); }; -IC s16 _max (s16 x, s16 y) { return x - ((x - y) & ((x - y) >> (sizeof(s16) * 8 - 1))); }; +IC s16 _abs(s16 x) { return (x >= 0) ? x : s16(-x); } +IC s16 _min(s16 x, s16 y) { return y + ((x - y) & ((x - y) >> (sizeof(s16) * 8 - 1))); }; +IC s16 _max(s16 x, s16 y) { return x - ((x - y) & ((x - y) >> (sizeof(s16) * 8 - 1))); }; // unsigned int16 -IC u16 _abs (u16 x) { return x; } +IC u16 _abs(u16 x) { return x; } // int32 -IC s32 _abs (s32 x) { return (x>=0)? x : s32(-x); } -IC s32 _min (s32 x, s32 y) { return y + ((x - y) & ((x - y) >> (sizeof(s32) * 8 - 1))); }; -IC s32 _max (s32 x, s32 y) { return x - ((x - y) & ((x - y) >> (sizeof(s32) * 8 - 1))); }; +IC s32 _abs(s32 x) { return (x >= 0) ? x : s32(-x); } +IC s32 _min(s32 x, s32 y) { return y + ((x - y) & ((x - y) >> (sizeof(s32) * 8 - 1))); }; +IC s32 _max(s32 x, s32 y) { return x - ((x - y) & ((x - y) >> (sizeof(s32) * 8 - 1))); }; // int64 -IC s64 _abs (s64 x) { return (x>=0)? x : s64(-x); } -IC s64 _min (s64 x, s64 y) { return y + ((x - y) & ((x - y) >> (sizeof(s64) * 8 - 1))); }; -IC s64 _max (s64 x, s64 y) { return x - ((x - y) & ((x - y) >> (sizeof(s64) * 8 - 1))); }; +IC s64 _abs(s64 x) { return (x >= 0) ? x : s64(-x); } +IC s64 _min(s64 x, s64 y) { return y + ((x - y) & ((x - y) >> (sizeof(s64) * 8 - 1))); }; +IC s64 _max(s64 x, s64 y) { return x - ((x - y) & ((x - y) >> (sizeof(s64) * 8 - 1))); }; -IC u32 xr_strlen ( const char* S ); +IC u32 xr_strlen(const char* S); // string management // return pointer to ".ext" -IC char* strext ( const char* S ) -{ return (char*) strrchr(S,'.'); } +IC char* strext(const char* S) +{ + return (char*)strrchr(S, '.'); +} -IC u32 xr_strlen ( const char* S ) -{ return (u32)strlen(S); } +IC u32 xr_strlen(const char* S) +{ + return (u32)strlen(S); +} -IC char* xr_strlwr (char* S) -{ return strlwr(S); } +IC char* xr_strlwr(char* S) +{ + return strlwr(S); +} #ifdef BREAK_AT_STRCMP -XRCORE_API int xr_strcmp ( const char* S1, const char* S2 ); +XRCORE_API int xr_strcmp(const char* S1, const char* S2); #else -IC int xr_strcmp ( const char* S1, const char* S2 ) -{ return (int)strcmp(S1,S2); } +IC int xr_strcmp(const char* S1, const char* S2) +{ + return (int)strcmp(S1, S2); +} #endif -#ifndef _EDITOR +#ifndef _EDITOR #ifndef MASTER_GOLD -inline errno_t xr_strcpy ( LPSTR destination, size_t const destination_size, LPCSTR source ) +inline errno_t xr_strcpy(LPSTR destination, size_t const destination_size, LPCSTR source) { - return strcpy_s( destination, destination_size, source ); + return strcpy_s(destination, destination_size, source); } -inline errno_t xr_strcat ( LPSTR destination, size_t const buffer_size, LPCSTR source ) +inline errno_t xr_strcat(LPSTR destination, size_t const buffer_size, LPCSTR source) { - return strcat_s( destination, buffer_size, source ); + return strcat_s(destination, buffer_size, source); } -inline int __cdecl xr_sprintf ( LPSTR destination, size_t const buffer_size, LPCSTR format_string, ... ) +inline int __cdecl xr_sprintf(LPSTR destination, size_t const buffer_size, LPCSTR format_string, ...) { - va_list args; - va_start ( args, format_string); - return vsprintf_s( destination, buffer_size, format_string, args ); + va_list args; + va_start(args, format_string); + return vsprintf_s(destination, buffer_size, format_string, args); } template -inline int __cdecl xr_sprintf ( char (&destination)[count], LPCSTR format_string, ... ) +inline int __cdecl xr_sprintf(char(&destination)[count], LPCSTR format_string, ...) { - va_list args; - va_start ( args, format_string); - return vsprintf_s( destination, count, format_string, args ); + va_list args; + va_start(args, format_string); + return vsprintf_s(destination, count, format_string, args); } #else // #ifndef MASTER_GOLD -inline errno_t xr_strcpy ( LPSTR destination, size_t const destination_size, LPCSTR source ) +inline errno_t xr_strcpy(LPSTR destination, size_t const destination_size, LPCSTR source) { - return strncpy_s( destination, destination_size, source, destination_size ); + return strncpy_s(destination, destination_size, source, destination_size); } -inline errno_t xr_strcat ( LPSTR destination, size_t const buffer_size, LPCSTR source ) +inline errno_t xr_strcat(LPSTR destination, size_t const buffer_size, LPCSTR source) { - size_t const destination_length = xr_strlen(destination); - LPSTR i = destination + destination_length; - LPSTR const e = destination + buffer_size - 1; - if ( i > e ) - return 0; + size_t const destination_length = xr_strlen(destination); + LPSTR i = destination + destination_length; + LPSTR const e = destination + buffer_size - 1; + if (i > e) + return 0; - for ( LPCSTR j = source; *j && (i != e); ++i, ++j ) - *i = *j; + for (LPCSTR j = source; *j && (i != e); ++i, ++j) + *i = *j; - *i = 0; - return 0; + *i = 0; + return 0; } -inline int __cdecl xr_sprintf ( LPSTR destination, size_t const buffer_size, LPCSTR format_string, ... ) +inline int __cdecl xr_sprintf(LPSTR destination, size_t const buffer_size, LPCSTR format_string, ...) { - va_list args; - va_start ( args, format_string); - return vsnprintf_s( destination, buffer_size, buffer_size - 1, format_string, args ); + va_list args; + va_start(args, format_string); + return vsnprintf_s(destination, buffer_size, buffer_size - 1, format_string, args); } template -inline int __cdecl xr_sprintf ( char (&destination)[count], LPCSTR format_string, ... ) +inline int __cdecl xr_sprintf(char(&destination)[count], LPCSTR format_string, ...) { - va_list args; - va_start ( args, format_string); - return vsnprintf_s( destination, count, count - 1, format_string, args ); + va_list args; + va_start(args, format_string); + return vsnprintf_s(destination, count, count - 1, format_string, args); } #endif // #ifndef MASTER_GOLD -# pragma deprecated( strcpy, strcpy_s, sprintf, sprintf_s, strcat, strcat_s ) +# pragma deprecated( strcpy, strcpy_s, sprintf, sprintf_s, strcat, strcat_s ) template -inline errno_t xr_strcpy ( char (&destination)[count], LPCSTR source ) +inline errno_t xr_strcpy(char(&destination)[count], LPCSTR source) { - return xr_strcpy( destination, count, source ); + return xr_strcpy(destination, count, source); } template -inline errno_t xr_strcat ( char (&destination)[count], LPCSTR source ) +inline errno_t xr_strcat(char(&destination)[count], LPCSTR source) { - return xr_strcat( destination, count, source ); + return xr_strcat(destination, count, source); } #endif // #ifndef _EDITOR -XRCORE_API char* timestamp (string64& dest); +XRCORE_API char* timestamp(string64& dest); -extern XRCORE_API u32 crc32 (const void* P, u32 len); -extern XRCORE_API u32 crc32 (const void* P, u32 len, u32 starting_crc); -extern XRCORE_API u32 path_crc32 (const char* path, u32 len); // ignores '/' and '\' +extern XRCORE_API u32 crc32(const void* P, u32 len); +extern XRCORE_API u32 crc32(const void* P, u32 len, u32 starting_crc); +extern XRCORE_API u32 path_crc32(const char* path, u32 len); // ignores '/' and '\' #endif // _STD_EXT_internal \ No newline at end of file diff --git a/src/xrCore/_stl_extensions.h b/src/xrCore/_stl_extensions.h index 4951f951ff0..93a140695d9 100644 --- a/src/xrCore/_stl_extensions.h +++ b/src/xrCore/_stl_extensions.h @@ -5,17 +5,17 @@ using std::swap; #include "_type_traits.h" -#ifdef __BORLANDC__ +#ifdef __BORLANDC__ #define M_NOSTDCONTAINERS_EXT #endif -#ifdef _M_AMD64 +#ifdef _M_AMD64 #define M_DONTDEFERCLEAR_EXT #endif -#define M_DONTDEFERCLEAR_EXT //. for mem-debug only +#define M_DONTDEFERCLEAR_EXT //. for mem-debug only -//-------- -#ifdef M_NOSTDCONTAINERS_EXT +//-------- +#ifdef M_NOSTDCONTAINERS_EXT #define xr_list std::list #define xr_deque std::deque @@ -28,259 +28,271 @@ using std::swap; #define xr_string std::string template -class xr_vector : public std::vector { -public: - typedef size_t size_type; - typedef T& reference; - typedef const T& const_reference; -public: - xr_vector () : std::vector () {} - xr_vector (size_t _count, const T& _value): std::vector (_count,_value) {} - explicit xr_vector (size_t _count) : std::vector (_count) {} - void clear () { erase(begin(),end()); } - void clear_and_free () { std::vector::clear(); } - void clear_not_free () { erase(begin(),end()); } - ICF const_reference operator[] (size_type _Pos) const { {VERIFY(_Pos +{ +public: + typedef size_t size_type; + typedef T& reference; + typedef const T& const_reference; +public: + xr_vector() : std::vector() {} + xr_vector(size_t _count, const T& _value) : std::vector(_count, _value) {} + explicit xr_vector(size_t _count) : std::vector(_count) {} + void clear() { erase(begin(), end()); } + void clear_and_free() { std::vector::clear(); } + void clear_not_free() { erase(begin(), end()); } + ICF const_reference operator[] (size_type _Pos) const { {VERIFY(_Pos < size()); } return (*(begin() + _Pos)); } + ICF reference operator[] (size_type _Pos) { {VERIFY(_Pos < size()); } return (*(begin() + _Pos)); } }; -template <> -class xr_vector : public std::vector{ - typedef bool T; -public: - xr_vector () : std::vector () {} - xr_vector (size_t _count, const T& _value): std::vector (_count,_value) {} - explicit xr_vector (size_t _count) : std::vector (_count) {} - u32 size() const { return (u32)std::vector::size(); } - void clear() { erase(begin(),end()); } +template <> +class xr_vector : public std::vector < bool > +{ + typedef bool T; +public: + xr_vector() : std::vector() {} + xr_vector(size_t _count, const T& _value) : std::vector(_count, _value) {} + explicit xr_vector(size_t _count) : std::vector(_count) {} + u32 size() const { return (u32)std::vector::size(); } + void clear() { erase(begin(), end()); } }; #else template -class xalloc { +class xalloc +{ public: - typedef size_t size_type; - typedef ptrdiff_t difference_type; - typedef T* pointer; - typedef const T* const_pointer; - typedef T& reference; - typedef const T& const_reference; - typedef T value_type; + typedef size_t size_type; + typedef ptrdiff_t difference_type; + typedef T* pointer; + typedef const T* const_pointer; + typedef T& reference; + typedef const T& const_reference; + typedef T value_type; public: - template - struct rebind { typedef xalloc<_Other> other; }; + template + struct rebind { typedef xalloc<_Other> other; }; public: - pointer address (reference _Val) const { return (&_Val); } - const_pointer address (const_reference _Val) const { return (&_Val); } - xalloc () { } - xalloc (const xalloc&) { } - template xalloc (const xalloc<_Other>&) { } - template xalloc& operator= (const xalloc<_Other>&) { return (*this); } - pointer allocate (size_type n, const void* p=0) const { return xr_alloc((u32)n); } - char* _charalloc (size_type n) { return (char*)allocate(n); } - void deallocate (pointer p, size_type n) const { xr_free (p); } - void deallocate (void* p, size_type n) const { xr_free (p); } - void construct (pointer p, const T& _Val) { std::_Construct(p, _Val); } - void destroy (pointer p) { std::_Destroy(p); } - size_type max_size () const { size_type _Count = (size_type)(-1) / sizeof (T); return (0 < _Count ? _Count : 1); } + pointer address(reference _Val) const { return (&_Val); } + const_pointer address(const_reference _Val) const { return (&_Val); } + xalloc() { } + xalloc(const xalloc&) { } + template xalloc(const xalloc<_Other>&) { } + template xalloc& operator= (const xalloc<_Other>&) { return (*this); } + pointer allocate(size_type n, const void* p = 0) const { return xr_alloc((u32)n); } + char* _charalloc(size_type n) { return (char*)allocate(n); } + void deallocate(pointer p, size_type n) const { xr_free(p); } + void deallocate(void* p, size_type n) const { xr_free(p); } + void construct(pointer p, const T& _Val) { std::_Construct(p, _Val); } + void destroy(pointer p) { std::_Destroy(p); } + size_type max_size() const { size_type _Count = (size_type)(-1) / sizeof(T); return (0 < _Count ? _Count : 1); } }; -struct xr_allocator { - template - struct helper { - typedef xalloc result; - }; - - static void *alloc (const u32 &n) { return xr_malloc((u32)n); } - template - static void dealloc (T *&p) { xr_free(p); } +struct xr_allocator +{ + template + struct helper + { + typedef xalloc result; + }; + + static void* alloc(const u32& n) { return xr_malloc((u32)n); } + template + static void dealloc(T*& p) { xr_free(p); } }; -template inline bool operator==(const xalloc<_Ty>&, const xalloc<_Other>&) { return (true); } -template inline bool operator!=(const xalloc<_Ty>&, const xalloc<_Other>&) { return (false); } +template inline bool operator==(const xalloc<_Ty>&, const xalloc<_Other>&) { return (true); } +template inline bool operator!=(const xalloc<_Ty>&, const xalloc<_Other>&) { return (false); } namespace std { - template inline xalloc<_Tp2>& __stl_alloc_rebind(xalloc<_Tp1>& __a, const _Tp2*) { return (xalloc<_Tp2>&)(__a); } - template inline xalloc<_Tp2> __stl_alloc_create(xalloc<_Tp1>&, const _Tp2*) { return xalloc<_Tp2>(); } +template inline xalloc<_Tp2>& __stl_alloc_rebind(xalloc<_Tp1>& __a, const _Tp2*) { return (xalloc<_Tp2>&)(__a); } +template inline xalloc<_Tp2> __stl_alloc_create(xalloc<_Tp1>&, const _Tp2*) { return xalloc<_Tp2>(); } }; // string(char) -typedef std::basic_string, xalloc > xr_string; +typedef std::basic_string, xalloc > xr_string; // vector -template > -class xr_vector : public std::vector { +template > +class xr_vector : public std::vector < T, allocator > +{ private: - typedef std::vector inherited; + typedef std::vector inherited; public: - typedef allocator allocator_type; + typedef allocator allocator_type; public: - xr_vector () : inherited () {} - xr_vector (size_t _count, const T& _value) : inherited (_count,_value) {} - explicit xr_vector (size_t _count) : inherited (_count) {} - u32 size () const { return (u32)inherited::size();} + xr_vector() : inherited() {} + xr_vector(size_t _count, const T& _value) : inherited(_count, _value) {} + explicit xr_vector(size_t _count) : inherited(_count) {} + u32 size() const { return (u32)inherited::size(); } - void clear_and_free () { inherited::clear(); } - void clear_not_free () { erase(begin(),end()); } - void clear_and_reserve () { if ( capacity() <= (size()+size()/4) ) clear_not_free(); else { u32 old=size(); clear_and_free(); reserve(old); } } + void clear_and_free() { inherited::clear(); } + void clear_not_free() { erase(begin(), end()); } + void clear_and_reserve() { if (capacity() <= (size() + size() / 4)) clear_not_free(); else { u32 old = size(); clear_and_free(); reserve(old); } } #ifdef M_DONTDEFERCLEAR_EXT - void clear () { clear_and_free (); } + void clear() { clear_and_free(); } #else - void clear () { clear_not_free (); } + void clear() { clear_not_free(); } #endif - const_reference operator[] (size_type _Pos) const { {VERIFY2(_Pos template <> -class xr_vector > : public std::vector > { +class xr_vector > : public std::vector < bool, xalloc > +{ private: - typedef std::vector > inherited; + typedef std::vector > inherited; -public: - u32 size () const { return (u32)inherited::size();} - void clear () { erase(begin(),end()); } +public: + u32 size() const { return (u32)inherited::size(); } + void clear() { erase(begin(), end()); } }; template -class xr_vector : public std::vector { +class xr_vector : public std::vector < bool, allocator > +{ private: - typedef std::vector inherited; + typedef std::vector inherited; -public: - u32 size () const { return (u32)inherited::size();} - void clear () { erase(begin(),end()); } +public: + u32 size() const { return (u32)inherited::size(); } + void clear() { erase(begin(), end()); } }; // deque template > -class xr_deque : public std::deque { -public: - typedef typename allocator allocator_type; - typedef typename allocator_type::value_type value_type; - typedef typename allocator_type::size_type size_type; - u32 size () const {return (u32)__super::size(); } +class xr_deque : public std::deque < T, allocator > +{ +public: + typedef typename allocator allocator_type; + typedef typename allocator_type::value_type value_type; + typedef typename allocator_type::size_type size_type; + u32 size() const { return (u32)__super::size(); } }; // stack template > -class xr_stack { +class xr_stack +{ public: - typedef typename _C::allocator_type allocator_type; - typedef typename allocator_type::value_type value_type; - typedef typename allocator_type::size_type size_type; - - //explicit stack(const allocator_type& _Al = allocator_type()) : c(_Al) {} - allocator_type get_allocator () const {return (c.get_allocator()); } - bool empty () const {return (c.empty()); } - u32 size () const {return c.size(); } - value_type& top () {return (c.back()); } - const value_type& top () const {return (c.back()); } - void push (const value_type& _X) {c.push_back(_X); } - void pop () {c.pop_back(); } - bool operator== (const xr_stack<_Ty, _C>& _X) const {return (c == _X.c); } - bool operator!= (const xr_stack<_Ty, _C>& _X) const {return (!(*this == _X)); } - bool operator< (const xr_stack<_Ty, _C>& _X) const {return (c < _X.c); } - bool operator> (const xr_stack<_Ty, _C>& _X) const {return (_X < *this); } - bool operator<= (const xr_stack<_Ty, _C>& _X) const {return (!(_X < *this)); } - bool operator>= (const xr_stack<_Ty, _C>& _X) const {return (!(*this < _X)); } + typedef typename _C::allocator_type allocator_type; + typedef typename allocator_type::value_type value_type; + typedef typename allocator_type::size_type size_type; + + //explicit stack(const allocator_type& _Al = allocator_type()) : c(_Al) {} + allocator_type get_allocator() const { return (c.get_allocator()); } + bool empty() const { return (c.empty()); } + u32 size() const { return c.size(); } + value_type& top() { return (c.back()); } + const value_type& top() const { return (c.back()); } + void push(const value_type& _X) { c.push_back(_X); } + void pop() { c.pop_back(); } + bool operator== (const xr_stack<_Ty, _C>& _X) const { return (c == _X.c); } + bool operator!= (const xr_stack<_Ty, _C>& _X) const { return (!(*this == _X)); } + bool operator< (const xr_stack<_Ty, _C>& _X) const { return (c < _X.c); } + bool operator>(const xr_stack<_Ty, _C>& _X) const { return (_X < *this); } + bool operator<= (const xr_stack<_Ty, _C>& _X) const { return (!(_X < *this)); } + bool operator>= (const xr_stack<_Ty, _C>& _X) const { return (!(*this < _X)); } protected: - _C c; + _C c; }; -template > class xr_list : public std::list { public: u32 size() const {return (u32)__super::size(); } }; -template , typename allocator = xalloc > class xr_set : public std::set { public: u32 size() const {return (u32)__super::size(); } }; -template , typename allocator = xalloc > class xr_multiset : public std::multiset { public: u32 size() const {return (u32)__super::size(); } }; -template , typename allocator = xalloc > > class xr_map : public std::map { public: u32 size() const {return (u32)__super::size(); } }; -template , typename allocator = xalloc > > class xr_multimap : public std::multimap { public: u32 size() const {return (u32)__super::size(); } }; +template > class xr_list : public std::list < T, allocator > { public: u32 size() const { return (u32)__super::size(); } }; +template , typename allocator = xalloc > class xr_set : public std::set < K, P, allocator > { public: u32 size() const { return (u32)__super::size(); } }; +template , typename allocator = xalloc > class xr_multiset : public std::multiset < K, P, allocator > { public: u32 size() const { return (u32)__super::size(); } }; +template , typename allocator = xalloc > > class xr_map : public std::map < K, V, P, allocator > { public: u32 size() const { return (u32)__super::size(); } }; +template , typename allocator = xalloc > > class xr_multimap : public std::multimap < K, V, P, allocator > { public: u32 size() const { return (u32)__super::size(); } }; #ifdef STLPORT - template , class _EqualKey=std::equal_to, typename allocator = xalloc > class xr_hash_set : public std::hash_set { public: u32 size() const {return (u32)__super::size(); } }; - template , class _EqualKey=std::equal_to, typename allocator = xalloc > class xr_hash_multiset: public std::hash_multiset { public: u32 size() const {return (u32)__super::size(); } }; +template , class _EqualKey = std::equal_to, typename allocator = xalloc > class xr_hash_set : public std::hash_set < V, _HashFcn, _EqualKey, allocator > { public: u32 size() const { return (u32)__super::size(); } }; +template , class _EqualKey = std::equal_to, typename allocator = xalloc > class xr_hash_multiset : public std::hash_multiset < V, _HashFcn, _EqualKey, allocator > { public: u32 size() const { return (u32)__super::size(); } }; - template , class _EqualKey=std::equal_to, typename allocator = xalloc > > class xr_hash_map : public std::hash_map { public: u32 size() const {return (u32)__super::size(); } }; - template , class _EqualKey=std::equal_to, typename allocator = xalloc > > class xr_hash_multimap: public std::hash_multimap { public: u32 size() const {return (u32)__super::size(); } }; -#else - template >, typename allocator = xalloc > > class xr_hash_map : public stdext::hash_map { public: u32 size() const {return (u32)__super::size(); } }; +template , class _EqualKey = std::equal_to, typename allocator = xalloc > > class xr_hash_map : public std::hash_map < K, V, _HashFcn, _EqualKey, allocator > { public: u32 size() const { return (u32)__super::size(); } }; +template , class _EqualKey = std::equal_to, typename allocator = xalloc > > class xr_hash_multimap : public std::hash_multimap < K, V, _HashFcn, _EqualKey, allocator > { public: u32 size() const { return (u32)__super::size(); } }; +#else +template >, typename allocator = xalloc > > class xr_hash_map : public stdext::hash_map < K, V, _Traits, allocator > { public: u32 size() const { return (u32)__super::size(); } }; #endif // #ifdef STLPORT #endif -template inline std::pair<_Ty1, _Ty2> mk_pair (_Ty1 _Val1, _Ty2 _Val2) { return (std::pair<_Ty1, _Ty2>(_Val1, _Val2)); } +template inline std::pair<_Ty1, _Ty2> mk_pair(_Ty1 _Val1, _Ty2 _Val2) { return (std::pair<_Ty1, _Ty2>(_Val1, _Val2)); } -struct pred_str : public std::binary_function { - IC bool operator()(const char* x, const char* y) const { return xr_strcmp(x,y)<0; } +struct pred_str : public std::binary_function < char*, char*, bool > +{ + IC bool operator()(const char* x, const char* y) const { return xr_strcmp(x, y) < 0; } }; -struct pred_stri : public std::binary_function { - IC bool operator()(const char* x, const char* y) const { return stricmp(x,y)<0; } +struct pred_stri : public std::binary_function < char*, char*, bool > +{ + IC bool operator()(const char* x, const char* y) const { return stricmp(x, y) < 0; } }; // STL extensions -#define DEF_VECTOR(N,T) typedef xr_vector< T > N; typedef N::iterator N##_it; -#define DEF_LIST(N,T) typedef xr_list< T > N; typedef N::iterator N##_it; -#define DEF_DEQUE(N,T) typedef xr_deque< T > N; typedef N::iterator N##_it; -#define DEF_MAP(N,K,T) typedef xr_map< K, T > N; typedef N::iterator N##_it; - -#define DEFINE_DEQUE(T,N,I) typedef xr_deque< T > N; typedef N::iterator I; -#define DEFINE_LIST(T,N,I) typedef xr_list< T > N; typedef N::iterator I; -#define DEFINE_VECTOR(T,N,I) typedef xr_vector< T > N; typedef N::iterator I; -#define DEFINE_MAP(K,T,N,I) typedef xr_map< K , T > N; typedef N::iterator I; -#define DEFINE_MAP_PRED(K,T,N,I,P) typedef xr_map< K, T, P > N; typedef N::iterator I; -#define DEFINE_MMAP(K,T,N,I) typedef xr_multimap< K, T > N; typedef N::iterator I; -#define DEFINE_SVECTOR(T,C,N,I) typedef svector< T, C > N; typedef N::iterator I; -#define DEFINE_SET(T,N,I) typedef xr_set< T > N; typedef N::iterator I; -#define DEFINE_SET_PRED(T,N,I,P) typedef xr_set< T, P > N; typedef N::iterator I; -#define DEFINE_STACK(T,N) typedef xr_stack< T > N; +#define DEF_VECTOR(N,T) typedef xr_vector< T > N; typedef N::iterator N##_it; +#define DEF_LIST(N,T) typedef xr_list< T > N; typedef N::iterator N##_it; +#define DEF_DEQUE(N,T) typedef xr_deque< T > N; typedef N::iterator N##_it; +#define DEF_MAP(N,K,T) typedef xr_map< K, T > N; typedef N::iterator N##_it; + +#define DEFINE_DEQUE(T,N,I) typedef xr_deque< T > N; typedef N::iterator I; +#define DEFINE_LIST(T,N,I) typedef xr_list< T > N; typedef N::iterator I; +#define DEFINE_VECTOR(T,N,I) typedef xr_vector< T > N; typedef N::iterator I; +#define DEFINE_MAP(K,T,N,I) typedef xr_map< K , T > N; typedef N::iterator I; +#define DEFINE_MAP_PRED(K,T,N,I,P) typedef xr_map< K, T, P > N; typedef N::iterator I; +#define DEFINE_MMAP(K,T,N,I) typedef xr_multimap< K, T > N; typedef N::iterator I; +#define DEFINE_SVECTOR(T,C,N,I) typedef svector< T, C > N; typedef N::iterator I; +#define DEFINE_SET(T,N,I) typedef xr_set< T > N; typedef N::iterator I; +#define DEFINE_SET_PRED(T,N,I,P) typedef xr_set< T, P > N; typedef N::iterator I; +#define DEFINE_STACK(T,N) typedef xr_stack< T > N; #include "FixedVector.h" #include "buffer_vector.h" // auxilary definition -DEFINE_VECTOR(bool,boolVec,boolIt); -DEFINE_VECTOR(BOOL,BOOLVec,BOOLIt); -DEFINE_VECTOR(BOOL*,LPBOOLVec,LPBOOLIt); -DEFINE_VECTOR(Frect,FrectVec,FrectIt); -DEFINE_VECTOR(Irect,IrectVec,IrectIt); -DEFINE_VECTOR(Fplane,PlaneVec,PlaneIt); -DEFINE_VECTOR(Fvector2,Fvector2Vec,Fvector2It); -DEFINE_VECTOR(Fvector,FvectorVec,FvectorIt); -DEFINE_VECTOR(Fvector*,LPFvectorVec,LPFvectorIt); -DEFINE_VECTOR(Fcolor,FcolorVec,FcolorIt); -DEFINE_VECTOR(Fcolor*,LPFcolorVec,LPFcolorIt); -DEFINE_VECTOR(LPSTR,LPSTRVec,LPSTRIt); -DEFINE_VECTOR(LPCSTR,LPCSTRVec,LPCSTRIt); -DEFINE_VECTOR(string64,string64Vec,string64It); -DEFINE_VECTOR(xr_string,SStringVec,SStringVecIt); - -DEFINE_VECTOR(s8,S8Vec,S8It); -DEFINE_VECTOR(s8*,LPS8Vec,LPS8It); -DEFINE_VECTOR(s16,S16Vec,S16It); -DEFINE_VECTOR(s16*,LPS16Vec,LPS16It); -DEFINE_VECTOR(s32,S32Vec,S32It); -DEFINE_VECTOR(s32*,LPS32Vec,LPS32It); -DEFINE_VECTOR(u8,U8Vec,U8It); -DEFINE_VECTOR(u8*,LPU8Vec,LPU8It); -DEFINE_VECTOR(u16,U16Vec,U16It); -DEFINE_VECTOR(u16*,LPU16Vec,LPU16It); -DEFINE_VECTOR(u32,U32Vec,U32It); -DEFINE_VECTOR(u32*,LPU32Vec,LPU32It); -DEFINE_VECTOR(float,FloatVec,FloatIt); -DEFINE_VECTOR(float*,LPFloatVec,LPFloatIt); -DEFINE_VECTOR(int,IntVec,IntIt); -DEFINE_VECTOR(int*,LPIntVec,LPIntIt); +DEFINE_VECTOR(bool, boolVec, boolIt); +DEFINE_VECTOR(BOOL, BOOLVec, BOOLIt); +DEFINE_VECTOR(BOOL*, LPBOOLVec, LPBOOLIt); +DEFINE_VECTOR(Frect, FrectVec, FrectIt); +DEFINE_VECTOR(Irect, IrectVec, IrectIt); +DEFINE_VECTOR(Fplane, PlaneVec, PlaneIt); +DEFINE_VECTOR(Fvector2, Fvector2Vec, Fvector2It); +DEFINE_VECTOR(Fvector, FvectorVec, FvectorIt); +DEFINE_VECTOR(Fvector*, LPFvectorVec, LPFvectorIt); +DEFINE_VECTOR(Fcolor, FcolorVec, FcolorIt); +DEFINE_VECTOR(Fcolor*, LPFcolorVec, LPFcolorIt); +DEFINE_VECTOR(LPSTR, LPSTRVec, LPSTRIt); +DEFINE_VECTOR(LPCSTR, LPCSTRVec, LPCSTRIt); +DEFINE_VECTOR(string64, string64Vec, string64It); +DEFINE_VECTOR(xr_string, SStringVec, SStringVecIt); + +DEFINE_VECTOR(s8, S8Vec, S8It); +DEFINE_VECTOR(s8*, LPS8Vec, LPS8It); +DEFINE_VECTOR(s16, S16Vec, S16It); +DEFINE_VECTOR(s16*, LPS16Vec, LPS16It); +DEFINE_VECTOR(s32, S32Vec, S32It); +DEFINE_VECTOR(s32*, LPS32Vec, LPS32It); +DEFINE_VECTOR(u8, U8Vec, U8It); +DEFINE_VECTOR(u8*, LPU8Vec, LPU8It); +DEFINE_VECTOR(u16, U16Vec, U16It); +DEFINE_VECTOR(u16*, LPU16Vec, LPU16It); +DEFINE_VECTOR(u32, U32Vec, U32It); +DEFINE_VECTOR(u32*, LPU32Vec, LPU32It); +DEFINE_VECTOR(float, FloatVec, FloatIt); +DEFINE_VECTOR(float*, LPFloatVec, LPFloatIt); +DEFINE_VECTOR(int, IntVec, IntIt); +DEFINE_VECTOR(int*, LPIntVec, LPIntIt); #ifdef __BORLANDC__ -DEFINE_VECTOR(AnsiString,AStringVec,AStringIt); -DEFINE_VECTOR(AnsiString*,LPAStringVec,LPAStringIt); +DEFINE_VECTOR(AnsiString, AStringVec, AStringIt); +DEFINE_VECTOR(AnsiString*, LPAStringVec, LPAStringIt); #endif #endif \ No newline at end of file diff --git a/src/xrCore/_type_traits.h b/src/xrCore/_type_traits.h index 27c889fb3b7..da8b0bc4315 100644 --- a/src/xrCore/_type_traits.h +++ b/src/xrCore/_type_traits.h @@ -4,51 +4,59 @@ // 1. class or not class template -struct is_class { - struct _yes { char _a[1]; }; - struct _no { char _a[2]; }; +struct is_class +{ + struct _yes { char _a[1]; }; + struct _no { char _a[2]; }; - template static _yes is_class_tester(void(U::*)(void)); - template static _no is_class_tester(...); + template static _yes is_class_tester(void(U::*)(void)); + template static _no is_class_tester(...); - enum { result = (sizeof(_yes)==sizeof(is_class_tester(0))) }; + enum { result = (sizeof(_yes) == sizeof(is_class_tester(0))) }; }; // 2. is polymorphic (class) template -struct is_pm_class { - struct c1 : public T { - char padding [16]; - c1(); - c1(const c1&); - c1&operator=(const c1&); - }; - struct c2 : public T { - char padding [16]; - c2(); - c2(const c2&); - c2&operator=(const c2&); - virtual ~c2 (); - }; - enum { result = (sizeof(c1)==sizeof(c2)) }; +struct is_pm_class +{ + struct c1 : public T + { + char padding[16]; + c1(); + c1(const c1&); + c1& operator=(const c1&); + }; + struct c2 : public T + { + char padding[16]; + c2(); + c2(const c2&); + c2& operator=(const c2&); + virtual ~c2(); + }; + enum { result = (sizeof(c1) == sizeof(c2)) }; }; // 3. select result based on class/not class template -struct is_pm_classify { - template - struct _detail { enum { result = is_pm_class<_T>::result }; }; +struct is_pm_classify +{ + template + struct _detail { enum { result = is_pm_class<_T>::result }; }; }; template<> -struct is_pm_classify { - template - struct _detail { enum { result = false }; }; +struct is_pm_classify < false > +{ + template + struct _detail { enum { result = false }; }; }; -template -struct is_polymorphic { - enum { - result = is_pm_classify::result> :: _detail :: result - }; +template +struct is_polymorphic +{ + enum + { + result = is_pm_classify::result> ::_detail ::result + }; }; #endif diff --git a/src/xrCore/_types.h b/src/xrCore/_types.h index 355fa47cb6c..ec082f40b84 100644 --- a/src/xrCore/_types.h +++ b/src/xrCore/_types.h @@ -2,68 +2,68 @@ #define TYPES_H // Type defs -typedef signed char s8; -typedef unsigned char u8; +typedef signed char s8; +typedef unsigned char u8; -typedef signed short s16; -typedef unsigned short u16; +typedef signed short s16; +typedef unsigned short u16; -typedef signed int s32; -typedef unsigned int u32; - -typedef signed __int64 s64; -typedef unsigned __int64 u64; +typedef signed int s32; +typedef unsigned int u32; -typedef float f32; -typedef double f64; +typedef signed __int64 s64; +typedef unsigned __int64 u64; -typedef char* pstr; -typedef const char* pcstr; +typedef float f32; +typedef double f64; + +typedef char* pstr; +typedef const char* pcstr; // windoze stuff #ifndef _WINDOWS_ - typedef int BOOL; - typedef pstr LPSTR; - typedef pcstr LPCSTR; - #define TRUE true - #define FALSE false +typedef int BOOL; +typedef pstr LPSTR; +typedef pcstr LPCSTR; +#define TRUE true +#define FALSE false #endif // Type limits -#define type_max(T) (std::numeric_limits::max()) -#define type_min(T) (-std::numeric_limits::max()) -#define type_zero(T) (std::numeric_limits::min()) -#define type_epsilon(T) (std::numeric_limits::epsilon()) +#define type_max(T) (std::numeric_limits::max()) +#define type_min(T) (-std::numeric_limits::max()) +#define type_zero(T) (std::numeric_limits::min()) +#define type_epsilon(T) (std::numeric_limits::epsilon()) -#define int_max type_max(int) -#define int_min type_min(int) -#define int_zero type_zero(int) +#define int_max type_max(int) +#define int_min type_min(int) +#define int_zero type_zero(int) -#define flt_max type_max(float) -#define flt_min type_min(float) -//#define FLT_MAX 3.402823466e+38F /* max value */ -//#define FLT_MIN 1.175494351e-38F /* min positive value */ -#define FLT_MAX flt_max -#define FLT_MIN flt_min +#define flt_max type_max(float) +#define flt_min type_min(float) +//#define FLT_MAX 3.402823466e+38F /* max value */ +//#define FLT_MIN 1.175494351e-38F /* min positive value */ +#define FLT_MAX flt_max +#define FLT_MIN flt_min -#define flt_zero type_zero(float) -#define flt_eps type_epsilon(float) +#define flt_zero type_zero(float) +#define flt_eps type_epsilon(float) -#define dbl_max type_max(double) -#define dbl_min type_min(double) -#define dbl_zero type_zero(double) -#define dbl_eps type_epsilon(double) +#define dbl_max type_max(double) +#define dbl_min type_min(double) +#define dbl_zero type_zero(double) +#define dbl_eps type_epsilon(double) -typedef char string16 [16]; -typedef char string32 [32]; -typedef char string64 [64]; -typedef char string128 [128]; -typedef char string256 [256]; -typedef char string512 [512]; -typedef char string1024 [1024]; -typedef char string2048 [2048]; -typedef char string4096 [4096]; +typedef char string16[16]; +typedef char string32[32]; +typedef char string64[64]; +typedef char string128[128]; +typedef char string256[256]; +typedef char string512[512]; +typedef char string1024[1024]; +typedef char string2048[2048]; +typedef char string4096[4096]; -typedef char string_path [2*_MAX_PATH]; +typedef char string_path[2 * _MAX_PATH]; #endif \ No newline at end of file diff --git a/src/xrCore/_vector2.h b/src/xrCore/_vector2.h index 3bedc295880..e9ab462db46 100644 --- a/src/xrCore/_vector2.h +++ b/src/xrCore/_vector2.h @@ -2,55 +2,55 @@ #define __V2D__ template -struct _vector2 +struct _vector2 { public: - typedef T TYPE; - typedef _vector2 Self; - typedef Self& SelfRef; - typedef const Self& SelfCRef; + typedef T TYPE; + typedef _vector2 Self; + typedef Self& SelfRef; + typedef const Self& SelfCRef; public: - T x,y; + T x, y; - IC SelfRef set(float _u, float _v) { x=T(_u); y=T(_v); return *this; } - IC SelfRef set(double _u, double _v) { x=T(_u); y=T(_v); return *this; } - IC SelfRef set(int _u, int _v) { x=T(_u); y=T(_v); return *this; } - IC SelfRef set(const Self &p) { x=p.x; y=p.y; return *this; } - IC SelfRef abs(const Self &p) { x=_abs(p.x); y=_abs(p.y); return *this; } - IC SelfRef min(const Self &p) { x=_min(x,p.x); y=_min(y,p.y); return *this; } - IC SelfRef min(T _x, T _y) { x=_min(x,_x); y=_min(y,_y); return *this; } - IC SelfRef max(const Self &p) { x=_max(x,p.x); y=_max(y,p.y); return *this; } - IC SelfRef max(T _x, T _y) { x=_max(x,_x); y=_max(y,_y); return *this; } - IC SelfRef sub(const T p) { x-=p; y-=p; return *this; } - IC SelfRef sub(const Self &p) { x-=p.x; y-=p.y; return *this; } - IC SelfRef sub(const Self &p1, const Self &p2) { x=p1.x-p2.x; y=p1.y-p2.y; return *this; } - IC SelfRef sub(const Self &p, float d) { x=p.x-d; y=p.y-d; return *this; } - IC SelfRef add(const T p) { x+=p; y+=p; return *this; } - IC SelfRef add(const Self &p) { x+=p.x; y+=p.y; return *this; } - IC SelfRef add(const Self &p1, const Self &p2) { x=p1.x+p2.x; y=p1.y+p2.y; return *this; } - IC SelfRef add(const Self &p, float d) { x=p.x+d; y=p.y+d; return *this; } - IC SelfRef mul(const T s) { x*=s; y*=s; return *this; } - IC SelfRef mul(const Self &p) { x*=p.x; y*=p.y; return *this; } - IC SelfRef div(const T s) { x/=s; y/=s; return *this; } - IC SelfRef div(const Self &p) { x/=p.x; y/=p.y; return *this; } - IC SelfRef rot90(void) { float t=-x; x=y; y=t; return *this; } - IC SelfRef cross(const Self &D) { x = D.y; y = -D.x; return *this; } - IC T dot(Self &p) { return x*p.x + y*p.y; } - IC T dot(const Self &p) const { return x*p.x + y*p.y; } - IC SelfRef norm(void) { float m=_sqrt(x*x+y*y); x/=m; y/=m; return *this; } - IC SelfRef norm_safe(void) { float m=_sqrt(x*x+y*y); if(m) {x/=m; y/=m;} return *this; } - IC T distance_to(const Self &p) const { return _sqrt((x-p.x)*(x-p.x) + (y-p.y)*(y-p.y)); } - IC T square_magnitude(void) const { return x*x + y*y; } - IC T magnitude(void) const { return _sqrt(square_magnitude()); } + IC SelfRef set(float _u, float _v) { x = T(_u); y = T(_v); return *this; } + IC SelfRef set(double _u, double _v) { x = T(_u); y = T(_v); return *this; } + IC SelfRef set(int _u, int _v) { x = T(_u); y = T(_v); return *this; } + IC SelfRef set(const Self& p) { x = p.x; y = p.y; return *this; } + IC SelfRef abs(const Self& p) { x = _abs(p.x); y = _abs(p.y); return *this; } + IC SelfRef min(const Self& p) { x = _min(x, p.x); y = _min(y, p.y); return *this; } + IC SelfRef min(T _x, T _y) { x = _min(x, _x); y = _min(y, _y); return *this; } + IC SelfRef max(const Self& p) { x = _max(x, p.x); y = _max(y, p.y); return *this; } + IC SelfRef max(T _x, T _y) { x = _max(x, _x); y = _max(y, _y); return *this; } + IC SelfRef sub(const T p) { x -= p; y -= p; return *this; } + IC SelfRef sub(const Self& p) { x -= p.x; y -= p.y; return *this; } + IC SelfRef sub(const Self& p1, const Self& p2) { x = p1.x - p2.x; y = p1.y - p2.y; return *this; } + IC SelfRef sub(const Self& p, float d) { x = p.x - d; y = p.y - d; return *this; } + IC SelfRef add(const T p) { x += p; y += p; return *this; } + IC SelfRef add(const Self& p) { x += p.x; y += p.y; return *this; } + IC SelfRef add(const Self& p1, const Self& p2) { x = p1.x + p2.x; y = p1.y + p2.y; return *this; } + IC SelfRef add(const Self& p, float d) { x = p.x + d; y = p.y + d; return *this; } + IC SelfRef mul(const T s) { x *= s; y *= s; return *this; } + IC SelfRef mul(const Self& p) { x *= p.x; y *= p.y; return *this; } + IC SelfRef div(const T s) { x /= s; y /= s; return *this; } + IC SelfRef div(const Self& p) { x /= p.x; y /= p.y; return *this; } + IC SelfRef rot90(void) { float t = -x; x = y; y = t; return *this; } + IC SelfRef cross(const Self& D) { x = D.y; y = -D.x; return *this; } + IC T dot(Self& p) { return x*p.x + y*p.y; } + IC T dot(const Self& p) const { return x*p.x + y*p.y; } + IC SelfRef norm(void) { float m = _sqrt(x*x + y*y); x /= m; y /= m; return *this; } + IC SelfRef norm_safe(void) { float m = _sqrt(x*x + y*y); if (m) { x /= m; y /= m; } return *this; } + IC T distance_to(const Self& p) const { return _sqrt((x - p.x)*(x - p.x) + (y - p.y)*(y - p.y)); } + IC T square_magnitude(void) const { return x*x + y*y; } + IC T magnitude(void) const { return _sqrt(square_magnitude()); } - IC SelfRef mad (const Self &p, const Self& d, T r) - { + IC SelfRef mad(const Self& p, const Self& d, T r) + { x = p.x + d.x*r; y = p.y + d.y*r; - return *this; + return *this; } - IC Self Cross() - { + IC Self Cross() + { // vector3 orthogonal to (x,y) is (y,-x) Self kCross; kCross.x = y; @@ -58,63 +58,62 @@ struct _vector2 return kCross; } - IC bool similar(Self &p, T eu, T ev) const - { - return _abs(x-p.x) 0.0f) ? -PI_DIV_2 : PI_DIV_2); - else - if (y < 0.f) - return (-(atanf(x/y) - PI)); - else - return (-atanf(x/y)); - } + if (fis_zero(x)) + return (0.f); + else + return ((x > 0.0f) ? -PI_DIV_2 : PI_DIV_2); + else if (y < 0.f) + return (-(atanf(x / y) - PI)); + else + return (-atanf(x / y)); + } }; -typedef _vector2 Fvector2; -typedef _vector2 Dvector2; -typedef _vector2 Ivector2; +typedef _vector2 Fvector2; +typedef _vector2 Dvector2; +typedef _vector2 Ivector2; template -BOOL _valid (const _vector2& v) { return _valid((T)v.x) && _valid((T)v.y); } +BOOL _valid(const _vector2& v) { return _valid((T)v.x) && _valid((T)v.y); } #endif \ No newline at end of file diff --git a/src/xrCore/_vector3d.h b/src/xrCore/_vector3d.h index cc462755690..20d197747bb 100644 --- a/src/xrCore/_vector3d.h +++ b/src/xrCore/_vector3d.h @@ -7,386 +7,414 @@ #endif template -struct _vector3 { +struct _vector3 +{ public: - typedef T TYPE; - typedef _vector3 Self; - typedef Self& SelfRef; - typedef const Self& SelfCRef; + typedef T TYPE; + typedef _vector3 Self; + typedef Self& SelfRef; + typedef const Self& SelfCRef; public: - T x,y,z; - - // access operators - ICF T& operator[] (int i) { return *((T*)this + i); } - ICF T& operator[] (int i) const { return *((T*)this + i); } - - ICF SelfRef set(T _x, T _y, T _z) { x = _x; y = _y; z = _z; return *this; }; - ICF SelfRef set(const _vector3 &v) { x = T(v.x); y = T(v.y); z = T(v.z); return *this; }; - ICF SelfRef set(const _vector3 &v) { x = T(v.x); y = T(v.y); z = T(v.z); return *this; }; - ICF SelfRef set(float* p) { x = p[0]; y = p[1]; z = p[2]; return *this; }; - ICF SelfRef set(double* p) { x = p[0]; y = p[1]; z = p[2]; return *this; }; - - ICF SelfRef add(const Self &v) { x+=v.x; y+=v.y; z+=v.z; return *this; }; - ICF SelfRef add(T s) { x+=s; y+=s; z+=s; return *this; }; - ICF SelfRef add(const Self &a, const Self &v) { x=a.x+v.x;y=a.y+v.y; z=a.z+v.z; return *this; }; - ICF SelfRef add(const Self &a, T s) { x=a.x+s; y=a.y+s; z=a.z+s; return *this; }; - - ICF SelfRef sub(const Self &v) { x-=v.x; y-=v.y; z-=v.z; return *this; }; - ICF SelfRef sub(T s) { x-=s; y-=s; z-=s; return *this; }; - ICF SelfRef sub(const Self &a, const Self &v) { x=a.x-v.x;y=a.y-v.y; z=a.z-v.z; return *this; }; - ICF SelfRef sub(const Self &a, T s) { x=a.x-s; y=a.y-s; z=a.z-s; return *this; }; - - ICF SelfRef mul(const Self &v) { x*=v.x; y*=v.y; z*=v.z; return *this; }; - ICF SelfRef mul(T s) { x*=s; y*=s; z*=s; return *this; }; - ICF SelfRef mul(const Self &a, const Self &v) { x=a.x*v.x;y=a.y*v.y; z=a.z*v.z; return *this; }; - ICF SelfRef mul(const Self &a, T s) { x=a.x*s; y=a.y*s; z=a.z*s; return *this; }; - - ICF SelfRef div(const Self &v) { x/=v.x; y/=v.y; z/=v.z; return *this; }; - ICF SelfRef div(T s) { x/=s; y/=s; z/=s; return *this; }; - ICF SelfRef div(const Self &a, const Self &v) { x=a.x/v.x;y=a.y/v.y; z=a.z/v.z; return *this; }; - ICF SelfRef div(const Self &a, T s) { x=a.x/s; y=a.y/s; z=a.z/s; return *this; }; - - IC SelfRef invert() { x=-x; y=-y; z=-z; return *this; } - IC SelfRef invert(const Self &a) { x=-a.x; y=-a.y; z=-a.z; return *this; } - - IC SelfRef min(const Self &v1,const Self &v2) { x = _min(v1.x,v2.x); y = _min(v1.y,v2.y); z = _min(v1.z,v2.z); return *this; } - IC SelfRef min(const Self &v) { x = _min(x,v.x); y = _min(y,v.y); z = _min(z,v.z); return *this; } - IC SelfRef max(const Self &v1,const Self &v2) { x = _max(v1.x,v2.x); y = _max(v1.y,v2.y); z = _max(v1.z,v2.z); return *this; } - IC SelfRef max(const Self &v) { x = _max(x,v.x); y = _max(y,v.y); z = _max(z,v.z); return *this; } - - IC SelfRef abs(const Self &v) { x = _abs(v.x); y=_abs(v.y); z=_abs(v.z); return *this; } - ICF BOOL similar(const Self &v, T E=EPS_L) const { return _abs(x-v.x)=_abs(x)) { z /= _abs(z?z:1); x = 0; } - else { x /= _abs(x); z = 0; } - return *this; - } - - // Squeeze - IC SelfRef squeeze(T Epsilon) - { - if (_abs(x) < Epsilon) x = 0; - if (_abs(y) < Epsilon) y = 0; - if (_abs(z) < Epsilon) z = 0; - return *this; - } - - // Clamp vector3 - IC SelfRef clamp(const Self &min, const Self& max) - { - ::clamp(x,min.x,max.x); - ::clamp(y,min.y,max.y); - ::clamp(z,min.z,max.z); - return *this; - } - - IC SelfRef clamp(const Self &_v) - { - Self v; v.x = _abs(_v.x); v.y = _abs(_v.y); v.z = _abs(_v.z); - ::clamp(x,-v.x,v.x); - ::clamp(y,-v.y,v.y); - ::clamp(z,-v.z,v.z); - return *this; - } - - // Interpolate vectors (inertion) - IC SelfRef inertion(const Self &p, T v) - { - T inv = 1.f-v; - x = v*x + inv*p.x; - y = v*y + inv*p.y; - z = v*z + inv*p.z; - return *this; - } - IC SelfRef average(const Self &p) - { - x = (x+p.x)*0.5f; - y = (y+p.y)*0.5f; - z = (z+p.z)*0.5f; - return *this; - } - IC SelfRef average(const Self &p1, const Self &p2) - { - x = (p1.x+p2.x)*0.5f; - y = (p1.y+p2.y)*0.5f; - z = (p1.z+p2.z)*0.5f; - return *this; - } - IC SelfRef lerp(const Self &p1, const Self &p2, T t ) - { - T invt = 1.f-t; - x = p1.x*invt + p2.x*t; - y = p1.y*invt + p2.y*t; - z = p1.z*invt + p2.z*t; - return *this; - } - - // Direct vector3 from point P by dir D with length M - IC SelfRef mad(const Self &d, T m) - { - x += d.x*m; - y += d.y*m; - z += d.z*m; - return *this; - } - IC SelfRef mad(const Self &p, const Self &d, T m) - { - x = p.x + d.x*m; - y = p.y + d.y*m; - z = p.z + d.z*m; - return *this; - } - IC SelfRef mad(const Self& d, const Self& s) - { - x += d.x*s.x; - y += d.y*s.y; - z += d.z*s.z; - return *this; - } - IC SelfRef mad(const Self &p, const Self &d, const Self &s) - { - x = p.x + d.x*s.x; - y = p.y + d.y*s.y; - z = p.z + d.z*s.z; - return *this; - } - - // SQ magnitude - IC T square_magnitude(void) const - { - return x*x + y*y + z*z; - } - // magnitude - IC T magnitude(void) const - { - return _sqrt(square_magnitude()); - } - - // Normalize - IC T normalize_magn(void) - { - VERIFY(square_magnitude() > std::numeric_limits::min()); - T len = magnitude(); - T inv_len = T(1)/len; - x *= inv_len; - y *= inv_len; - z *= inv_len; + T x, y, z; + + // access operators + ICF T& operator[] (int i) { return *((T*)this + i); } + ICF T& operator[] (int i) const { return *((T*)this + i); } + + ICF SelfRef set(T _x, T _y, T _z) { x = _x; y = _y; z = _z; return *this; }; + ICF SelfRef set(const _vector3& v) { x = T(v.x); y = T(v.y); z = T(v.z); return *this; }; + ICF SelfRef set(const _vector3& v) { x = T(v.x); y = T(v.y); z = T(v.z); return *this; }; + ICF SelfRef set(float* p) { x = p[0]; y = p[1]; z = p[2]; return *this; }; + ICF SelfRef set(double* p) { x = p[0]; y = p[1]; z = p[2]; return *this; }; + + ICF SelfRef add(const Self& v) { x += v.x; y += v.y; z += v.z; return *this; }; + ICF SelfRef add(T s) { x += s; y += s; z += s; return *this; }; + ICF SelfRef add(const Self& a, const Self& v) { x = a.x + v.x; y = a.y + v.y; z = a.z + v.z; return *this; }; + ICF SelfRef add(const Self& a, T s) { x = a.x + s; y = a.y + s; z = a.z + s; return *this; }; + + ICF SelfRef sub(const Self& v) { x -= v.x; y -= v.y; z -= v.z; return *this; }; + ICF SelfRef sub(T s) { x -= s; y -= s; z -= s; return *this; }; + ICF SelfRef sub(const Self& a, const Self& v) { x = a.x - v.x; y = a.y - v.y; z = a.z - v.z; return *this; }; + ICF SelfRef sub(const Self& a, T s) { x = a.x - s; y = a.y - s; z = a.z - s; return *this; }; + + ICF SelfRef mul(const Self& v) { x *= v.x; y *= v.y; z *= v.z; return *this; }; + ICF SelfRef mul(T s) { x *= s; y *= s; z *= s; return *this; }; + ICF SelfRef mul(const Self& a, const Self& v) { x = a.x*v.x; y = a.y*v.y; z = a.z*v.z; return *this; }; + ICF SelfRef mul(const Self& a, T s) { x = a.x*s; y = a.y*s; z = a.z*s; return *this; }; + + ICF SelfRef div(const Self& v) { x /= v.x; y /= v.y; z /= v.z; return *this; }; + ICF SelfRef div(T s) { x /= s; y /= s; z /= s; return *this; }; + ICF SelfRef div(const Self& a, const Self& v) { x = a.x / v.x; y = a.y / v.y; z = a.z / v.z; return *this; }; + ICF SelfRef div(const Self& a, T s) { x = a.x / s; y = a.y / s; z = a.z / s; return *this; }; + + IC SelfRef invert() { x = -x; y = -y; z = -z; return *this; } + IC SelfRef invert(const Self& a) { x = -a.x; y = -a.y; z = -a.z; return *this; } + + IC SelfRef min(const Self& v1, const Self& v2) { x = _min(v1.x, v2.x); y = _min(v1.y, v2.y); z = _min(v1.z, v2.z); return *this; } + IC SelfRef min(const Self& v) { x = _min(x, v.x); y = _min(y, v.y); z = _min(z, v.z); return *this; } + IC SelfRef max(const Self& v1, const Self& v2) { x = _max(v1.x, v2.x); y = _max(v1.y, v2.y); z = _max(v1.z, v2.z); return *this; } + IC SelfRef max(const Self& v) { x = _max(x, v.x); y = _max(y, v.y); z = _max(z, v.z); return *this; } + + IC SelfRef abs(const Self& v) { x = _abs(v.x); y = _abs(v.y); z = _abs(v.z); return *this; } + ICF BOOL similar(const Self& v, T E = EPS_L) const { return _abs(x - v.x) < E && _abs(y - v.y) < E && _abs(z - v.z) < E; }; + + IC SelfRef set_length(T l) + { + mul(l / magnitude()); + return *this; + } + + // Align vector3 by axis (!y) + IC SelfRef align() + { + y = 0; + if (_abs(z) >= _abs(x)) { z /= _abs(z ? z : 1); x = 0; } + else { x /= _abs(x); z = 0; } + return *this; + } + + // Squeeze + IC SelfRef squeeze(T Epsilon) + { + if (_abs(x) < Epsilon) x = 0; + if (_abs(y) < Epsilon) y = 0; + if (_abs(z) < Epsilon) z = 0; + return *this; + } + + // Clamp vector3 + IC SelfRef clamp(const Self& min, const Self& max) + { + ::clamp(x, min.x, max.x); + ::clamp(y, min.y, max.y); + ::clamp(z, min.z, max.z); + return *this; + } + + IC SelfRef clamp(const Self& _v) + { + Self v; + v.x = _abs(_v.x); + v.y = _abs(_v.y); + v.z = _abs(_v.z); + ::clamp(x, -v.x, v.x); + ::clamp(y, -v.y, v.y); + ::clamp(z, -v.z, v.z); + return *this; + } + + // Interpolate vectors (inertion) + IC SelfRef inertion(const Self& p, T v) + { + T inv = 1.f - v; + x = v*x + inv*p.x; + y = v*y + inv*p.y; + z = v*z + inv*p.z; + return *this; + } + IC SelfRef average(const Self& p) + { + x = (x + p.x)*0.5f; + y = (y + p.y)*0.5f; + z = (z + p.z)*0.5f; + return *this; + } + IC SelfRef average(const Self& p1, const Self& p2) + { + x = (p1.x + p2.x)*0.5f; + y = (p1.y + p2.y)*0.5f; + z = (p1.z + p2.z)*0.5f; + return *this; + } + IC SelfRef lerp(const Self& p1, const Self& p2, T t) + { + T invt = 1.f - t; + x = p1.x*invt + p2.x*t; + y = p1.y*invt + p2.y*t; + z = p1.z*invt + p2.z*t; + return *this; + } + + // Direct vector3 from point P by dir D with length M + IC SelfRef mad(const Self& d, T m) + { + x += d.x*m; + y += d.y*m; + z += d.z*m; + return *this; + } + IC SelfRef mad(const Self& p, const Self& d, T m) + { + x = p.x + d.x*m; + y = p.y + d.y*m; + z = p.z + d.z*m; + return *this; + } + IC SelfRef mad(const Self& d, const Self& s) + { + x += d.x*s.x; + y += d.y*s.y; + z += d.z*s.z; + return *this; + } + IC SelfRef mad(const Self& p, const Self& d, const Self& s) + { + x = p.x + d.x*s.x; + y = p.y + d.y*s.y; + z = p.z + d.z*s.z; + return *this; + } + + // SQ magnitude + IC T square_magnitude(void) const + { + return x*x + y*y + z*z; + } + // magnitude + IC T magnitude(void) const + { + return _sqrt(square_magnitude()); + } + + // Normalize + IC T normalize_magn(void) + { + VERIFY(square_magnitude() > std::numeric_limits::min()); + T len = magnitude(); + T inv_len = T(1) / len; + x *= inv_len; + y *= inv_len; + z *= inv_len; return len; - } - - ICF SelfRef normalize(void) - { - VERIFY(square_magnitude() > std::numeric_limits::min()); - T mag=_sqrt(T(1)/(x*x + y*y + z*z)); - x *= mag; - y *= mag; - z *= mag; - return *this; - } - - // Safe-Normalize - ICF SelfRef normalize_safe(void) - { - T magnitude=x*x + y*y + z*z; - if (magnitude> std::numeric_limits::min()) { - magnitude=_sqrt(1/magnitude); - x *= magnitude; - y *= magnitude; - z *= magnitude; - } - return *this; - } - - // Normalize - ICF SelfRef normalize(const Self &v) - { - VERIFY((v.x*v.x+v.y*v.y+v.z*v.z)>flt_zero); - T mag=_sqrt(1/(v.x*v.x + v.y*v.y + v.z*v.z)); - x = v.x*mag; - y = v.y*mag; - z = v.z*mag; - return *this; - } - - // Safe-Normalize - ICF SelfRef normalize_safe(const Self &v) { - T magnitude=v.x*v.x + v.y*v.y + v.z*v.z; - if (magnitude>std::numeric_limits::min()) { - magnitude=_sqrt(1/magnitude); - x = v.x*magnitude; - y = v.y*magnitude; - z = v.z*magnitude; - } - return *this; - } - IC SelfRef random_dir (CRandom& R = ::Random) - { - //z = R.randF(-1,1); - z = _cos(R.randF(PI)); - T a = R.randF(PI_MUL_2); - T r = _sqrt(1-z*z); - T sa= _sin (a); - T ca= _cos (a); - x = r * ca; - y = r * sa; - return *this; - }; - IC SelfRef random_dir (const Self& ConeAxis, float ConeAngle, CRandom& R = ::Random) - { - Self rnd; - rnd.random_dir (R); - mad (ConeAxis,rnd,R.randF(tanf(ConeAngle))); - normalize (); - return *this; - } - IC SelfRef random_point (const Self& BoxSize, CRandom& R = ::Random) - { - x = R.randFs(BoxSize.x); - y = R.randFs(BoxSize.y); - z = R.randFs(BoxSize.z); - return *this; - } - IC SelfRef random_point (T r, CRandom& R = ::Random) - { - random_dir (R); - mul (R.randF(r)); - return *this; - } - - // DotProduct - ICF T dotproduct(const Self &v) const // v1*v2 - { return x*v.x + y*v.y + z*v.z; } - - // CrossProduct - ICF SelfRef crossproduct(const Self &v1, const Self &v2) // (v1,v2) -> this - { - x = v1.y * v2.z - v1.z * v2.y ; - y = v1.z * v2.x - v1.x * v2.z ; - z = v1.x * v2.y - v1.y * v2.x ; - return *this; - } - - // Distance calculation - IC T distance_to_xz(const Self &v) const - { return _sqrt( (x-v.x)*(x-v.x) + (z-v.z)*(z-v.z) ); } - IC T distance_to_xz_sqr(const Self &v) const - { return (x-v.x)*(x-v.x) + (z-v.z)*(z-v.z); } - - // Distance calculation - ICF T distance_to_sqr(const Self &v) const - { return (x-v.x)*(x-v.x) + (y-v.y)*(y-v.y) + (z-v.z)*(z-v.z); } - - // Distance calculation - ICF T distance_to(const Self &v) const - { return _sqrt(distance_to_sqr(v)); } - - // Barycentric coords - IC SelfRef from_bary (const Self &V1, const Self &V2, const Self &V3, T u, T v, T w) - { - x = V1.x*u + V2.x*v + V3.x*w; - y = V1.y*u + V2.y*v + V3.y*w; - z = V1.z*u + V2.z*v + V3.z*w; - return *this; - } - IC SelfRef from_bary (const Self &V1, const Self &V2, const Self &V3, const Self &B) - { - from_bary(V1,V2,V3,B.x,B.y,B.z); - return *this; - } - - IC SelfRef from_bary4 (const Self &V1, const Self &V2, const Self &V3, const Self &V4, T u, T v, T w, T t) - { - x = V1.x*u + V2.x*v + V3.x*w + V4.x*t; - y = V1.y*u + V2.y*v + V3.y*w + V4.y*t; - z = V1.z*u + V2.z*v + V3.z*w + V4.z*t; - return *this; - } - - IC SelfRef mknormal_non_normalized (const Self &p0, const Self & p1, const Self &p2 ) - { - _vector3 v01,v12; - v01.sub( p1, p0 ); - v12.sub( p2, p1 ); - crossproduct( v01, v12 ); - return *this; + } + + ICF SelfRef normalize(void) + { + VERIFY(square_magnitude() > std::numeric_limits::min()); + T mag = _sqrt(T(1) / (x*x + y*y + z*z)); + x *= mag; + y *= mag; + z *= mag; + return *this; + } + + // Safe-Normalize + ICF SelfRef normalize_safe(void) + { + T magnitude = x*x + y*y + z*z; + if (magnitude > std::numeric_limits::min()) + { + magnitude = _sqrt(1 / magnitude); + x *= magnitude; + y *= magnitude; + z *= magnitude; + } + return *this; + } + + // Normalize + ICF SelfRef normalize(const Self& v) + { + VERIFY((v.x*v.x + v.y*v.y + v.z*v.z) > flt_zero); + T mag = _sqrt(1 / (v.x*v.x + v.y*v.y + v.z*v.z)); + x = v.x*mag; + y = v.y*mag; + z = v.z*mag; + return *this; + } + + // Safe-Normalize + ICF SelfRef normalize_safe(const Self& v) + { + T magnitude = v.x*v.x + v.y*v.y + v.z*v.z; + if (magnitude > std::numeric_limits::min()) + { + magnitude = _sqrt(1 / magnitude); + x = v.x*magnitude; + y = v.y*magnitude; + z = v.z*magnitude; + } + return *this; + } + IC SelfRef random_dir(CRandom& R = ::Random) + { + //z = R.randF(-1,1); + z = _cos(R.randF(PI)); + T a = R.randF(PI_MUL_2); + T r = _sqrt(1 - z*z); + T sa = _sin(a); + T ca = _cos(a); + x = r * ca; + y = r * sa; + return *this; + }; + IC SelfRef random_dir(const Self& ConeAxis, float ConeAngle, CRandom& R = ::Random) + { + Self rnd; + rnd.random_dir(R); + mad(ConeAxis, rnd, R.randF(tanf(ConeAngle))); + normalize(); + return *this; + } + IC SelfRef random_point(const Self& BoxSize, CRandom& R = ::Random) + { + x = R.randFs(BoxSize.x); + y = R.randFs(BoxSize.y); + z = R.randFs(BoxSize.z); + return *this; + } + IC SelfRef random_point(T r, CRandom& R = ::Random) + { + random_dir(R); + mul(R.randF(r)); + return *this; + } + + // DotProduct + ICF T dotproduct(const Self& v) const // v1*v2 + { + return x*v.x + y*v.y + z*v.z; + } + + // CrossProduct + ICF SelfRef crossproduct(const Self& v1, const Self& v2) // (v1,v2) -> this + { + x = v1.y * v2.z - v1.z * v2.y; + y = v1.z * v2.x - v1.x * v2.z; + z = v1.x * v2.y - v1.y * v2.x; + return *this; + } + + // Distance calculation + IC T distance_to_xz(const Self& v) const + { + return _sqrt((x - v.x)*(x - v.x) + (z - v.z)*(z - v.z)); + } + IC T distance_to_xz_sqr(const Self& v) const + { + return (x - v.x)*(x - v.x) + (z - v.z)*(z - v.z); + } + + // Distance calculation + ICF T distance_to_sqr(const Self& v) const + { + return (x - v.x)*(x - v.x) + (y - v.y)*(y - v.y) + (z - v.z)*(z - v.z); + } + + // Distance calculation + ICF T distance_to(const Self& v) const + { + return _sqrt(distance_to_sqr(v)); + } + + // Barycentric coords + IC SelfRef from_bary(const Self& V1, const Self& V2, const Self& V3, T u, T v, T w) + { + x = V1.x*u + V2.x*v + V3.x*w; + y = V1.y*u + V2.y*v + V3.y*w; + z = V1.z*u + V2.z*v + V3.z*w; + return *this; + } + IC SelfRef from_bary(const Self& V1, const Self& V2, const Self& V3, const Self& B) + { + from_bary(V1, V2, V3, B.x, B.y, B.z); + return *this; + } + + IC SelfRef from_bary4(const Self& V1, const Self& V2, const Self& V3, const Self& V4, T u, T v, T w, T t) + { + x = V1.x*u + V2.x*v + V3.x*w + V4.x*t; + y = V1.y*u + V2.y*v + V3.y*w + V4.y*t; + z = V1.z*u + V2.z*v + V3.z*w + V4.z*t; + return *this; + } + + IC SelfRef mknormal_non_normalized(const Self& p0, const Self& p1, const Self& p2) + { + _vector3 v01, v12; + v01.sub(p1, p0); + v12.sub(p2, p1); + crossproduct(v01, v12); + return *this; }; - IC SelfRef mknormal( const Self &p0, const Self &p1, const Self &p2 ) - { - mknormal_non_normalized(p0,p1,p2); - normalize_safe(); - return *this; + IC SelfRef mknormal(const Self& p0, const Self& p1, const Self& p2) + { + mknormal_non_normalized(p0, p1, p2); + normalize_safe(); + return *this; }; - IC SelfRef setHP (T h, T p) - { - T _ch=_cos(h), _cp=_cos(p), _sh=_sin(h), _sp=_sin(p); + IC SelfRef setHP(T h, T p) + { + T _ch = _cos(h), _cp = _cos(p), _sh = _sin(h), _sp = _sin(p); x = -_cp*_sh; y = _sp; z = _cp*_ch; - return *this; + return *this; } - ICF void getHP (T& h, T& p) const + ICF void getHP(T& h, T& p) const { float hyp; - if (fis_zero(x)&& fis_zero(z)){ + if (fis_zero(x) && fis_zero(z)) + { h = 0.0f; - if (!fis_zero(float(y))) p = (y>0.0f)?PI_DIV_2:-PI_DIV_2; - else p = 0.0f; - }else{ - if (fis_zero(z)) h = (x>0.0f)?-PI_DIV_2:PI_DIV_2; - else if (z<0.0f) h = -(atanf(x/z)-PI); - else h = -atanf(x/z); - hyp = _sqrt(x*x+z*z); - if (fis_zero(float(hyp))) p = (y>0.0f)?PI_DIV_2:-PI_DIV_2; - else p = atanf(y/hyp); + if (!fis_zero(float(y))) p = (y > 0.0f) ? PI_DIV_2 : -PI_DIV_2; + else p = 0.0f; + } + else + { + if (fis_zero(z)) h = (x > 0.0f) ? -PI_DIV_2 : PI_DIV_2; + else if (z < 0.0f) h = -(atanf(x / z) - PI); + else h = -atanf(x / z); + hyp = _sqrt(x*x + z*z); + if (fis_zero(float(hyp))) p = (y > 0.0f) ? PI_DIV_2 : -PI_DIV_2; + else p = atanf(y / hyp); + } + } + ICF float getH() const + { + if (fis_zero(x) && fis_zero(z)) + { + return 0.0f; + } + else + { + if (fis_zero(z)) return (x > 0.0f) ? -PI_DIV_2 : PI_DIV_2; + else if (z < 0.0f) return -(atanf(x / z) - PI); + else return -atanf(x / z); } } - ICF float getH () const - { - if (fis_zero(x)&& fis_zero(z)){ - return 0.0f; - }else{ - if (fis_zero(z)) return (x>0.0f)?-PI_DIV_2:PI_DIV_2; - else if (z<0.0f) return -(atanf(x/z)-PI); - else return -atanf(x/z); - } - } - ICF float getP () const - { - if (fis_zero(x)&& fis_zero(z)){ - if (!fis_zero(float(y))) return (y>0.0f)?PI_DIV_2:-PI_DIV_2; - else return 0.0f; - }else{ - float hyp = _sqrt(x*x+z*z); - if (fis_zero(float(hyp))) return (y>0.0f)?PI_DIV_2:-PI_DIV_2; - else return atanf(y/hyp); - } - } - IC SelfRef reflect(const Self& dir, const Self& norm) - { - return mad(dir,norm,-2*dir.dotproduct(norm)); - } - IC SelfRef slide(const Self& dir, const Self& norm) - { // non normalized - return mad(dir,norm,-dir.dotproduct(norm)); - } + ICF float getP() const + { + if (fis_zero(x) && fis_zero(z)) + { + if (!fis_zero(float(y))) return (y > 0.0f) ? PI_DIV_2 : -PI_DIV_2; + else return 0.0f; + } + else + { + float hyp = _sqrt(x*x + z*z); + if (fis_zero(float(hyp))) return (y > 0.0f) ? PI_DIV_2 : -PI_DIV_2; + else return atanf(y / hyp); + } + } + IC SelfRef reflect(const Self& dir, const Self& norm) + { + return mad(dir, norm, -2 * dir.dotproduct(norm)); + } + IC SelfRef slide(const Self& dir, const Self& norm) + { + // non normalized + return mad(dir, norm, -dir.dotproduct(norm)); + } IC static void generate_orthonormal_basis(const _vector3& dir, _vector3& up, _vector3& right) { T fInvLength; - if ( _abs(dir.x) >= _abs(dir.y) ){ + if (_abs(dir.x) >= _abs(dir.y)) + { // W.x or W.z is the largest magnitude component, swap them - fInvLength = 1.f/_sqrt(dir.x*dir.x+dir.z*dir.z); + fInvLength = 1.f / _sqrt(dir.x*dir.x + dir.z*dir.z); up.x = -dir.z*fInvLength; up.y = 0.0f; up.z = +dir.x*fInvLength; @@ -394,118 +422,128 @@ struct _vector3 { else { // W.y or W.z is the largest magnitude component, swap them - fInvLength = 1.f/_sqrt(dir.y*dir.y+dir.z*dir.z); + fInvLength = 1.f / _sqrt(dir.y*dir.y + dir.z*dir.z); up.x = 0.0f; up.y = +dir.z*fInvLength; up.z = -dir.y*fInvLength; } - right.crossproduct(up,dir); //. <-> - } - IC static void generate_orthonormal_basis_normalized(_vector3& dir, _vector3& up, _vector3& right) - { - T fInvLength; - dir.normalize(); - if (fsimilar(dir.y,1.f,EPS)){ - up.set (0.f,0.f,1.f); - fInvLength = 1.f/_sqrt(dir.x*dir.x+dir.y*dir.y); - // cross (up,dir) and normalize (right) - right.x = -dir.y * fInvLength; - right.y = dir.x * fInvLength; - right.z = 0.f; - // cross (dir,right) - up.x = -dir.z * right.y; - up.y = dir.z * right.x; - up.z = dir.x * right.y - dir.y * right.x ; - }else{ - up.set (0.f,1.f,0.f); - fInvLength = 1.f/_sqrt(dir.x*dir.x+dir.z*dir.z); - // cross (up,dir) and normalize (right) - right.x = dir.z * fInvLength; - right.y = 0.f; - right.z = -dir.x * fInvLength; - // cross (dir,right) - up.x = dir.y * right.z; - up.y = dir.z * right.x - dir.x * right.z ; - up.z = -dir.y * right.x ; - } - } + right.crossproduct(up, dir); //. <-> + } + IC static void generate_orthonormal_basis_normalized(_vector3& dir, _vector3& up, _vector3& right) + { + T fInvLength; + dir.normalize(); + if (fsimilar(dir.y, 1.f, EPS)) + { + up.set(0.f, 0.f, 1.f); + fInvLength = 1.f / _sqrt(dir.x*dir.x + dir.y*dir.y); + // cross (up,dir) and normalize (right) + right.x = -dir.y * fInvLength; + right.y = dir.x * fInvLength; + right.z = 0.f; + // cross (dir,right) + up.x = -dir.z * right.y; + up.y = dir.z * right.x; + up.z = dir.x * right.y - dir.y * right.x; + } + else + { + up.set(0.f, 1.f, 0.f); + fInvLength = 1.f / _sqrt(dir.x*dir.x + dir.z*dir.z); + // cross (up,dir) and normalize (right) + right.x = dir.z * fInvLength; + right.y = 0.f; + right.z = -dir.x * fInvLength; + // cross (dir,right) + up.x = dir.y * right.z; + up.y = dir.z * right.x - dir.x * right.z; + up.z = -dir.y * right.x; + } + } }; -typedef _vector3 Fvector; -typedef _vector3 Fvector3; -typedef _vector3 Dvector; -typedef _vector3 Dvector3; -typedef _vector3 Ivector; -typedef _vector3 Ivector3; +typedef _vector3 Fvector; +typedef _vector3 Fvector3; +typedef _vector3 Dvector; +typedef _vector3 Dvector3; +typedef _vector3 Ivector; +typedef _vector3 Ivector3; template -BOOL _valid (const _vector3& v) { return _valid((T)v.x) && _valid((T)v.y) && _valid((T)v.z); } +BOOL _valid(const _vector3& v) { return _valid((T)v.x) && _valid((T)v.y) && _valid((T)v.z); } ////////////////////////////////////////////////////////////////////////// #pragma warning(push) #pragma warning(disable:4244) -ICF double rsqrt (double v) { return 1.0/_sqrt(v); } -IC BOOL exact_normalize (float* a) +ICF double rsqrt(double v) { return 1.0 / _sqrt(v); } +IC BOOL exact_normalize(float* a) { - double sqr_magnitude = a[0]*a[0] + a[1]*a[1] + a[2]*a[2]; - double epsilon = 1.192092896e-05F; - if (sqr_magnitude > epsilon) - { - double l = rsqrt(sqr_magnitude); - a[0] *= l; - a[1] *= l; - a[2] *= l; - return TRUE; - } - double a0,a1,a2,aa0,aa1,aa2,l; - a0 = a[0]; - a1 = a[1]; - a2 = a[2]; - aa0 = _abs(a0); - aa1 = _abs(a1); - aa2 = _abs(a2); - if (aa1 > aa0) { - if (aa2 > aa1) { - goto aa2_largest; - } - else { // aa1 is largest - a0 /= aa1; - a2 /= aa1; - l = rsqrt (a0*a0 + a2*a2 + 1); - a[0] = a0*l; - a[1] = (double)_copysign(l,a1); - a[2] = a2*l; - } - } - else { - if (aa2 > aa0) { -aa2_largest: // aa2 is largest - a0 /= aa2; - a1 /= aa2; - l = rsqrt (a0*a0 + a1*a1 + 1); - a[0] = a0*l; - a[1] = a1*l; - a[2] = (double)_copysign(l,a2); - } - else { // aa0 is largest - if (aa0 <= 0) { - // dDEBUGMSG ("vector has zero size"); ... this messace is annoying - a[0] = 0; // if all a's are zero, this is where we'll end up. - a[1] = 1; // return a default unit length vector. - a[2] = 0; - return FALSE; - } - a1 /= aa0; - a2 /= aa0; - l = rsqrt (a1*a1 + a2*a2 + 1); - a[0] = (double)_copysign(l,a0); - a[1] = a1*l; - a[2] = a2*l; - } - } - return TRUE; + double sqr_magnitude = a[0] * a[0] + a[1] * a[1] + a[2] * a[2]; + double epsilon = 1.192092896e-05F; + if (sqr_magnitude > epsilon) + { + double l = rsqrt(sqr_magnitude); + a[0] *= l; + a[1] *= l; + a[2] *= l; + return TRUE; + } + double a0, a1, a2, aa0, aa1, aa2, l; + a0 = a[0]; + a1 = a[1]; + a2 = a[2]; + aa0 = _abs(a0); + aa1 = _abs(a1); + aa2 = _abs(a2); + if (aa1 > aa0) + { + if (aa2 > aa1) + { + goto aa2_largest; + } + else // aa1 is largest + { + a0 /= aa1; + a2 /= aa1; + l = rsqrt(a0*a0 + a2*a2 + 1); + a[0] = a0*l; + a[1] = (double)_copysign(l, a1); + a[2] = a2*l; + } + } + else + { + if (aa2 > aa0) + { + aa2_largest: // aa2 is largest + a0 /= aa2; + a1 /= aa2; + l = rsqrt(a0*a0 + a1*a1 + 1); + a[0] = a0*l; + a[1] = a1*l; + a[2] = (double)_copysign(l, a2); + } + else // aa0 is largest + { + if (aa0 <= 0) + { + // dDEBUGMSG ("vector has zero size"); ... this messace is annoying + a[0] = 0; // if all a's are zero, this is where we'll end up. + a[1] = 1; // return a default unit length vector. + a[2] = 0; + return FALSE; + } + a1 /= aa0; + a2 /= aa0; + l = rsqrt(a1*a1 + a2*a2 + 1); + a[0] = (double)_copysign(l, a0); + a[1] = a1*l; + a[2] = a2*l; + } + } + return TRUE; } -IC BOOL exact_normalize (Fvector3& a) { return exact_normalize(&a.x); } +IC BOOL exact_normalize(Fvector3& a) { return exact_normalize(&a.x); } #pragma warning(pop) #endif diff --git a/src/xrCore/_vector3d_ext.h b/src/xrCore/_vector3d_ext.h index 63af8179534..a7fe4155e9f 100644 --- a/src/xrCore/_vector3d_ext.h +++ b/src/xrCore/_vector3d_ext.h @@ -4,166 +4,166 @@ #include "_vector3d.h" inline -Fvector cr_fvector3 (float f) +Fvector cr_fvector3(float f) { - Fvector res = { f, f, f }; - return res; + Fvector res = {f, f, f}; + return res; } inline -Fvector cr_fvector3 (float x, float y, float z) +Fvector cr_fvector3(float x, float y, float z) { - Fvector res = { x, y, z }; - return res; + Fvector res = {x, y, z}; + return res; } inline -Fvector cr_fvector3_hp (float h, float p) +Fvector cr_fvector3_hp(float h, float p) { - Fvector res; - res.setHP (h, p); - return res; + Fvector res; + res.setHP(h, p); + return res; } inline -Fvector operator + (const Fvector& v1, const Fvector& v2) +Fvector operator + (const Fvector& v1, const Fvector& v2) { - return cr_fvector3 (v1.x+v2.x, v1.y+v2.y, v1.z+v2.z); + return cr_fvector3(v1.x + v2.x, v1.y + v2.y, v1.z + v2.z); } inline -Fvector operator - (const Fvector& v1, const Fvector& v2) +Fvector operator - (const Fvector& v1, const Fvector& v2) { - return cr_fvector3 (v1.x-v2.x, v1.y-v2.y, v1.z-v2.z); + return cr_fvector3(v1.x - v2.x, v1.y - v2.y, v1.z - v2.z); } inline -Fvector operator - (const Fvector& v) +Fvector operator - (const Fvector& v) { - return cr_fvector3 (-v.x, -v.y, -v.z); + return cr_fvector3(-v.x, -v.y, -v.z); } inline -Fvector operator * (const Fvector& v, float f) +Fvector operator * (const Fvector& v, float f) { - return cr_fvector3 (v.x*f, v.y*f, v.z*f); + return cr_fvector3(v.x*f, v.y*f, v.z*f); } inline -Fvector operator * (float f, const Fvector& v) +Fvector operator * (float f, const Fvector& v) { - return cr_fvector3 (v.x*f, v.y*f, v.z*f); + return cr_fvector3(v.x*f, v.y*f, v.z*f); } inline -Fvector operator / (const Fvector& v, float f) +Fvector operator / (const Fvector& v, float f) { - const float repr_f = 1.f / f; - return cr_fvector3 (v.x*repr_f, v.y*repr_f, v.z*repr_f); + const float repr_f = 1.f / f; + return cr_fvector3(v.x*repr_f, v.y*repr_f, v.z*repr_f); } inline -Fvector _min (const Fvector& v1, const Fvector& v2) +Fvector _min(const Fvector& v1, const Fvector& v2) { - Fvector r; - r.min (v1, v2); - return r; + Fvector r; + r.min(v1, v2); + return r; } inline -Fvector _max (const Fvector& v1, const Fvector& v2) +Fvector _max(const Fvector& v1, const Fvector& v2) { - Fvector r; - r.max (v1, v2); - return r; + Fvector r; + r.max(v1, v2); + return r; } inline -Fvector _abs (const Fvector& v) +Fvector _abs(const Fvector& v) { - Fvector r; - r.abs (v); - return r; + Fvector r; + r.abs(v); + return r; } inline -Fvector normalize (const Fvector& v) +Fvector normalize(const Fvector& v) { - Fvector r(v); - r.normalize (); - return r; + Fvector r(v); + r.normalize(); + return r; } inline -float magnitude (const Fvector& v) +float magnitude(const Fvector& v) { - return v.magnitude(); + return v.magnitude(); } inline -float sqaure_magnitude (const Fvector& v) +float sqaure_magnitude(const Fvector& v) { - return v.square_magnitude(); + return v.square_magnitude(); } inline -float dotproduct (const Fvector& v1, const Fvector& v2) -{ - return v1.x*v2.x + v1.y*v2.y + v1.z*v2.z; +float dotproduct(const Fvector& v1, const Fvector& v2) +{ + return v1.x*v2.x + v1.y*v2.y + v1.z*v2.z; } // CrossProduct inline -Fvector crossproduct (const Fvector& v1, const Fvector& v2) +Fvector crossproduct(const Fvector& v1, const Fvector& v2) { - Fvector r; - r.crossproduct(v1, v2); - return r; + Fvector r; + r.crossproduct(v1, v2); + return r; } inline -Fvector cr_vectorHP (float h, float p) +Fvector cr_vectorHP(float h, float p) { - float ch = _cos(h), cp=_cos(p), sh=_sin(h), sp=_sin(p); - Fvector r; - r.x = -cp*sh; - r.y = sp; - r.z = cp*ch; - return r; + float ch = _cos(h), cp = _cos(p), sh = _sin(h), sp = _sin(p); + Fvector r; + r.x = -cp*sh; + r.y = sp; + r.z = cp*ch; + return r; } inline -float angle_between_vectors (Fvector const v1, Fvector const v2) +float angle_between_vectors(Fvector const v1, Fvector const v2) { - float const mag1 = v1.magnitude(); - float const mag2 = v2.magnitude(); - float const epsilon = 1e-6; - if ( mag1 < epsilon || mag2 < epsilon ) - { - return 0.f; - } + float const mag1 = v1.magnitude(); + float const mag2 = v2.magnitude(); + float const epsilon = 1e-6; + if (mag1 < epsilon || mag2 < epsilon) + { + return 0.f; + } - float angle_cos = dotproduct(v1, v2) / (mag1*mag2); - if ( angle_cos < -1.f ) - { - angle_cos = -1.f; - } - else if ( angle_cos > +1.f ) - { - angle_cos = +1.f; - } - return acosf(angle_cos); + float angle_cos = dotproduct(v1, v2) / (mag1*mag2); + if (angle_cos < -1.f) + { + angle_cos = -1.f; + } + else if (angle_cos > +1.f) + { + angle_cos = +1.f; + } + return acosf(angle_cos); } inline -Fvector rotate_point (Fvector const& point, float const angle) +Fvector rotate_point(Fvector const& point, float const angle) { - float const cos_alpha = _cos(angle); - float const sin_alpha = _sin(angle); + float const cos_alpha = _cos(angle); + float const sin_alpha = _sin(angle); - return Fvector().set(point.x*cos_alpha - point.z*sin_alpha, - 0, - point.x*sin_alpha + point.z*cos_alpha); + return Fvector().set(point.x*cos_alpha - point.z*sin_alpha, + 0, + point.x*sin_alpha + point.z*cos_alpha); } #endif // VECTOR3D_EXT_INCLUDED diff --git a/src/xrCore/_vector4.h b/src/xrCore/_vector4.h index 3ce42a5fd46..a89d957a071 100644 --- a/src/xrCore/_vector4.h +++ b/src/xrCore/_vector4.h @@ -3,71 +3,72 @@ #pragma once template -struct _vector4 { - typedef T TYPE; - typedef _vector4 Self; - typedef Self& SelfRef; - typedef const Self& SelfCRef; +struct _vector4 +{ + typedef T TYPE; + typedef _vector4 Self; + typedef Self& SelfRef; + typedef const Self& SelfCRef; public: - T x,y,z,w; + T x, y, z, w; - IC T& operator[] (int i) { return *((T*)this + i); } - IC T& operator[] (int i) const { return *((T*)this + i); } + IC T& operator[] (int i) { return *((T*)this + i); } + IC T& operator[] (int i) const { return *((T*)this + i); } - IC SelfRef set(T _x, T _y, T _z, T _w=1) { x=_x; y=_y; z=_z; w=_w; return *this; } - IC SelfRef set(const Self& v) { x=v.x; y=v.y; z=v.z; w=v.w; return *this; } + IC SelfRef set(T _x, T _y, T _z, T _w = 1) { x = _x; y = _y; z = _z; w = _w; return *this; } + IC SelfRef set(const Self& v) { x = v.x; y = v.y; z = v.z; w = v.w; return *this; } - IC SelfRef add(const Self &v) { x+=v.x; y+=v.y; z+=v.z; w+=v.w; return *this; } - IC SelfRef add(T s) { x+=s; y+=s; z+=s; w+=s; return *this; } - IC SelfRef add(const Self &a, const Self &v) { x=a.x+v.x;y=a.y+v.y; z=a.z+v.z; w=a.w+v.w; return *this; } - IC SelfRef add(const Self &a, T s) { x=a.x+s; y=a.y+s; z=a.z+s; w=a.w+s; return *this; } + IC SelfRef add(const Self& v) { x += v.x; y += v.y; z += v.z; w += v.w; return *this; } + IC SelfRef add(T s) { x += s; y += s; z += s; w += s; return *this; } + IC SelfRef add(const Self& a, const Self& v) { x = a.x + v.x; y = a.y + v.y; z = a.z + v.z; w = a.w + v.w; return *this; } + IC SelfRef add(const Self& a, T s) { x = a.x + s; y = a.y + s; z = a.z + s; w = a.w + s; return *this; } - IC SelfRef sub(T _x, T _y, T _z, T _w=1) { x-=_x; y-=_y; z-=_z; w-=_w; return *this; } - IC SelfRef sub(const Self &v) { x-=v.x; y-=v.y; z-=v.z; w-=v.w; return *this; } - IC SelfRef sub(T s) { x-=s; y-=s; z-=s; w-=s; return *this; } - IC SelfRef sub(const Self &a, const Self &v) { x=a.x-v.x;y=a.y-v.y; z=a.z-v.z; w=a.w-v.w; return *this; } - IC SelfRef sub(const Self &a, T s) { x=a.x-s; y=a.y-s; z=a.z-s; w=a.w-s; return *this; } + IC SelfRef sub(T _x, T _y, T _z, T _w = 1) { x -= _x; y -= _y; z -= _z; w -= _w; return *this; } + IC SelfRef sub(const Self& v) { x -= v.x; y -= v.y; z -= v.z; w -= v.w; return *this; } + IC SelfRef sub(T s) { x -= s; y -= s; z -= s; w -= s; return *this; } + IC SelfRef sub(const Self& a, const Self& v) { x = a.x - v.x; y = a.y - v.y; z = a.z - v.z; w = a.w - v.w; return *this; } + IC SelfRef sub(const Self& a, T s) { x = a.x - s; y = a.y - s; z = a.z - s; w = a.w - s; return *this; } - IC SelfRef mul(T _x, T _y, T _z, T _w=1) { x*=_x; y*=_y; z*=_z; w*=_w; return *this; } - IC SelfRef mul(const Self &v) { x*=v.x; y*=v.y; z*=v.z; w*=v.w; return *this; } - IC SelfRef mul(T s) { x*=s; y*=s; z*=s; w*=s; return *this; } - IC SelfRef mul(const Self &a, const Self &v) { x=a.x*v.x;y=a.y*v.y; z=a.z*v.z; w=a.w*v.w; return *this; } - IC SelfRef mul(const Self &a, T s) { x=a.x*s; y=a.y*s; z=a.z*s; w=a.w*s; return *this; } + IC SelfRef mul(T _x, T _y, T _z, T _w = 1) { x *= _x; y *= _y; z *= _z; w *= _w; return *this; } + IC SelfRef mul(const Self& v) { x *= v.x; y *= v.y; z *= v.z; w *= v.w; return *this; } + IC SelfRef mul(T s) { x *= s; y *= s; z *= s; w *= s; return *this; } + IC SelfRef mul(const Self& a, const Self& v) { x = a.x*v.x; y = a.y*v.y; z = a.z*v.z; w = a.w*v.w; return *this; } + IC SelfRef mul(const Self& a, T s) { x = a.x*s; y = a.y*s; z = a.z*s; w = a.w*s; return *this; } - IC SelfRef div(const Self &v) { x/=v.x; y/=v.y; z/=v.z; w/=v.w; return *this; } - IC SelfRef div(T s) { x/=s; y/=s; z/=s; w/=s; return *this; } - IC SelfRef div(const Self &a, const Self &v) { x=a.x/v.x;y=a.y/v.y; z=a.z/v.z; w=a.w/v.w; return *this; } - IC SelfRef div(const Self &a, T s) { x=a.x/s; y=a.y/s; z=a.z/s; w=a.w/s; return *this; } + IC SelfRef div(const Self& v) { x /= v.x; y /= v.y; z /= v.z; w /= v.w; return *this; } + IC SelfRef div(T s) { x /= s; y /= s; z /= s; w /= s; return *this; } + IC SelfRef div(const Self& a, const Self& v) { x = a.x / v.x; y = a.y / v.y; z = a.z / v.z; w = a.w / v.w; return *this; } + IC SelfRef div(const Self& a, T s) { x = a.x / s; y = a.y / s; z = a.z / s; w = a.w / s; return *this; } - IC BOOL similar(const Self& v, T E=EPS_L) { return _abs(x-v.x) Fvector4; -typedef _vector4 Dvector4; -typedef _vector4 Ivector4; +typedef _vector4 Fvector4; +typedef _vector4 Dvector4; +typedef _vector4 Ivector4; #ifndef __BORLANDC__ - typedef __declspec(align(16)) _vector4 Fvector4a; - typedef __declspec(align(16)) _vector4 Dvector4a; - typedef __declspec(align(16)) _vector4 Ivector4a; +typedef __declspec(align(16)) _vector4 Fvector4a; +typedef __declspec(align(16)) _vector4 Dvector4a; +typedef __declspec(align(16)) _vector4 Ivector4a; #endif template -BOOL _valid (const _vector4& v) { return _valid((T)v.x) && _valid((T)v.y) && _valid((T)v.z) && _valid((T)v.w); } +BOOL _valid(const _vector4& v) { return _valid((T)v.x) && _valid((T)v.y) && _valid((T)v.z) && _valid((T)v.w); } #endif \ No newline at end of file diff --git a/src/xrCore/buffer_vector.h b/src/xrCore/buffer_vector.h index 2112dc216b0..68804417688 100644 --- a/src/xrCore/buffer_vector.h +++ b/src/xrCore/buffer_vector.h @@ -1,112 +1,113 @@ //////////////////////////////////////////////////////////////////////////// -// Module : buffer_vector.h -// Created : 10.10.2007 -// Modified : 10.10.2007 -// Author : Dmitriy Iassenev -// Description : buffer vector template class +// Module : buffer_vector.h +// Created : 10.10.2007 +// Modified : 10.10.2007 +// Author : Dmitriy Iassenev +// Description : buffer vector template class //////////////////////////////////////////////////////////////////////////// #ifndef BUFFER_VECTOR_H_INCLUDED #define BUFFER_VECTOR_H_INCLUDED template -class buffer_vector { +class buffer_vector +{ public: - typedef T const * const_iterator; - typedef T const * const_pointer; - typedef T const & const_reference; - typedef std::reverse_iterator const_reverse_iterator; + typedef T const* const_iterator; + typedef T const* const_pointer; + typedef T const& const_reference; + typedef std::reverse_iterator const_reverse_iterator; - typedef T * iterator; - typedef T * pointer; - typedef T & reference; - typedef std::reverse_iterator reverse_iterator; + typedef T* iterator; + typedef T* pointer; + typedef T& reference; + typedef std::reverse_iterator reverse_iterator; - typedef ptrdiff_t difference_type; - typedef size_t size_type; - typedef T value_type; + typedef ptrdiff_t difference_type; + typedef size_t size_type; + typedef T value_type; private: - typedef buffer_vector self_type; + typedef buffer_vector self_type; public: - inline buffer_vector (void *buffer, size_type const &max_count); - inline buffer_vector (void *buffer, size_type const &max_count, size_type const &count, value_type const &value); - inline buffer_vector (void *buffer, size_type const &max_count, self_type const &other); - template - inline buffer_vector (void *buffer, size_type const &max_count, input_iterator const &begin, input_iterator const &last); - inline ~buffer_vector (); + inline buffer_vector(void* buffer, size_type const& max_count); + inline buffer_vector(void* buffer, size_type const& max_count, size_type const& count, value_type const& value); + inline buffer_vector(void* buffer, size_type const& max_count, self_type const& other); + template + inline buffer_vector(void* buffer, size_type const& max_count, input_iterator const& begin, input_iterator const& last); + inline ~buffer_vector(); - inline self_type &operator= (self_type const &other); + inline self_type& operator= (self_type const& other); - template - inline void assign (input_iterator begin, input_iterator const &end); - inline void assign (size_type const &count, const_reference value); + template + inline void assign(input_iterator begin, input_iterator const& end); + inline void assign(size_type const& count, const_reference value); - inline void swap (self_type &other); - inline void clear (); - inline void resize (size_type const &size); - inline void reserve (size_type const &size); + inline void swap(self_type& other); + inline void clear(); + inline void resize(size_type const& size); + inline void reserve(size_type const& size); - template - inline void insert (iterator const &where, input_iterator begin, input_iterator const &last); - inline void insert (iterator const &where, size_type const &count, const_reference value); - inline void insert (iterator const &where, const_reference value); + template + inline void insert(iterator const& where, input_iterator begin, input_iterator const& last); + inline void insert(iterator const& where, size_type const& count, const_reference value); + inline void insert(iterator const& where, const_reference value); - inline void erase (iterator const &begin, iterator const &end); - inline void erase (iterator const &where); + inline void erase(iterator const& begin, iterator const& end); + inline void erase(iterator const& where); - inline void pop_back (); - inline void push_back (const_reference value); + inline void pop_back(); + inline void push_back(const_reference value); - inline reference at (size_type const &index); - inline const_reference at (size_type const &index) const; + inline reference at(size_type const& index); + inline const_reference at(size_type const& index) const; - inline reference operator[] (size_type const &index); - inline const_reference operator[] (size_type const &index) const; + inline reference operator[] (size_type const& index); + inline const_reference operator[] (size_type const& index) const; - inline reference back (); - inline const_reference back () const; + inline reference back(); + inline const_reference back() const; - inline reference front (); - inline const_reference front () const; + inline reference front(); + inline const_reference front() const; - inline iterator begin (); - inline const_iterator begin () const; + inline iterator begin(); + inline const_iterator begin() const; - inline iterator end (); - inline const_iterator end () const; + inline iterator end(); + inline const_iterator end() const; - inline reverse_iterator rbegin (); - inline const_reverse_iterator rbegin () const; + inline reverse_iterator rbegin(); + inline const_reverse_iterator rbegin() const; - inline reverse_iterator rend (); - inline const_reverse_iterator rend () const; + inline reverse_iterator rend(); + inline const_reverse_iterator rend() const; - inline bool empty () const; - inline size_t size () const; + inline bool empty() const; + inline size_t size() const; - inline size_t capacity () const; - inline size_t max_size () const; + inline size_t capacity() const; + inline size_t max_size() const; private: - static inline void construct (pointer p); - static inline void construct (pointer p, const_reference value); - static inline void construct (iterator begin, iterator const &end); - static inline void construct (iterator begin, iterator const &end, const_reference value); + static inline void construct(pointer p); + static inline void construct(pointer p, const_reference value); + static inline void construct(iterator begin, iterator const& end); + static inline void construct(iterator begin, iterator const& end, const_reference value); private: - static inline void destroy (pointer p); - static inline void destroy (iterator begin, iterator const &end); + static inline void destroy(pointer p); + static inline void destroy(iterator begin, iterator const& end); private: - pointer m_begin; - pointer m_end; - pointer m_max_end; + pointer m_begin; + pointer m_end; + pointer m_max_end; }; - template - inline void swap (buffer_vector &left, buffer_vector &right); +template +inline void swap(buffer_vector& left, buffer_vector& right); #include "buffer_vector_inline.h" diff --git a/src/xrCore/buffer_vector_inline.h b/src/xrCore/buffer_vector_inline.h index 1165f18b8ff..dff0a1acc19 100644 --- a/src/xrCore/buffer_vector_inline.h +++ b/src/xrCore/buffer_vector_inline.h @@ -1,393 +1,397 @@ //////////////////////////////////////////////////////////////////////////// -// Module : buffer_vector_inline.h -// Created : 10.10.2007 -// Modified : 10.10.2007 -// Author : Dmitriy Iassenev -// Description : buffer vector template class inline functions +// Module : buffer_vector_inline.h +// Created : 10.10.2007 +// Modified : 10.10.2007 +// Author : Dmitriy Iassenev +// Description : buffer vector template class inline functions //////////////////////////////////////////////////////////////////////////// #ifndef BUFFER_VECTOR_INLINE_H_INCLUDED #define BUFFER_VECTOR_INLINE_H_INCLUDED -#define TEMPLATE_SPECIALIZATION template -#define buffer_vector_specialized buffer_vector +#define TEMPLATE_SPECIALIZATION template +#define buffer_vector_specialized buffer_vector TEMPLATE_SPECIALIZATION -inline buffer_vector_specialized::buffer_vector (void *buffer, size_type const &max_count) : - m_begin ((T*)buffer), - m_end ((T*)buffer), - m_max_end ((T*)buffer + max_count) +inline buffer_vector_specialized::buffer_vector(void* buffer, size_type const& max_count) : +m_begin((T*)buffer), +m_end((T*)buffer), +m_max_end((T*)buffer + max_count) { } TEMPLATE_SPECIALIZATION -inline buffer_vector_specialized::buffer_vector (void *buffer, size_type const &max_count, size_type const &count, value_type const &value) : - m_begin ((T*)buffer), - m_end ((T*)buffer), - m_max_end ((T*)buffer + max_count) +inline buffer_vector_specialized::buffer_vector(void* buffer, size_type const& max_count, size_type const& count, value_type const& value) : +m_begin((T*)buffer), +m_end((T*)buffer), +m_max_end((T*)buffer + max_count) { - assign (count, value); + assign(count, value); } TEMPLATE_SPECIALIZATION -inline buffer_vector_specialized::buffer_vector (void *buffer, size_type const &max_count, self_type const &other) : - m_begin ((T*)buffer), - m_end ((T*)buffer), - m_max_end ((T*)buffer + max_count) +inline buffer_vector_specialized::buffer_vector(void* buffer, size_type const& max_count, self_type const& other) : +m_begin((T*)buffer), +m_end((T*)buffer), +m_max_end((T*)buffer + max_count) { - assign (other.begin(), other.end()); + assign(other.begin(), other.end()); } TEMPLATE_SPECIALIZATION template -inline buffer_vector_specialized::buffer_vector (void *buffer, size_type const &max_count, input_iterator const &begin, input_iterator const &end) : - m_begin ((T*)buffer), - m_end ((T*)buffer), - m_max_end ((T*)buffer + max_count) +inline buffer_vector_specialized::buffer_vector(void* buffer, size_type const& max_count, input_iterator const& begin, input_iterator const& end) : +m_begin((T*)buffer), +m_end((T*)buffer), +m_max_end((T*)buffer + max_count) { - assign (begin, end); + assign(begin, end); } TEMPLATE_SPECIALIZATION inline buffer_vector_specialized::~buffer_vector() { - clear (); + clear(); } TEMPLATE_SPECIALIZATION -inline typename buffer_vector_specialized::self_type &buffer_vector_specialized::operator= (self_type const &other) +inline typename buffer_vector_specialized::self_type& buffer_vector_specialized::operator= (self_type const& other) { - assign (other.begin(), other.end()); + assign(other.begin(), other.end()); } TEMPLATE_SPECIALIZATION template -inline void buffer_vector_specialized::assign (input_iterator begin, input_iterator const &end) +inline void buffer_vector_specialized::assign(input_iterator begin, input_iterator const& end) { - destroy (m_begin, m_end); + destroy(m_begin, m_end); - m_end = m_begin + (end - begin); - VERIFY (m_max_end >= m_end); + m_end = m_begin + (end - begin); + VERIFY(m_max_end >= m_end); - for (iterator I = m_begin; begin != end; ++begin, ++I) - construct (I, *begin); + for (iterator I = m_begin; begin != end; ++begin, ++I) + construct(I, *begin); } TEMPLATE_SPECIALIZATION -inline void buffer_vector_specialized::assign (size_type const &count, const_reference value) +inline void buffer_vector_specialized::assign(size_type const& count, const_reference value) { - destroy (m_begin, m_end); + destroy(m_begin, m_end); - m_end = m_begin + count; - VERIFY (m_max_end >= m_end); + m_end = m_begin + count; + VERIFY(m_max_end >= m_end); - for (iterator I = m_begin; I != m_end; ++I) - construct (I, value); + for (iterator I = m_begin; I != m_end; ++I) + construct(I, value); } TEMPLATE_SPECIALIZATION -inline void buffer_vector_specialized::swap (self_type &other) +inline void buffer_vector_specialized::swap(self_type& other) { - std::swap (m_begin, other.m_begin); - std::swap (m_end, other.m_end); - std::swap (m_max_end, other.m_max_end); + std::swap(m_begin, other.m_begin); + std::swap(m_end, other.m_end); + std::swap(m_max_end, other.m_max_end); } TEMPLATE_SPECIALIZATION -inline void buffer_vector_specialized::clear () +inline void buffer_vector_specialized::clear() { - destroy (m_begin, m_end); - m_end = m_begin; + destroy(m_begin, m_end); + m_end = m_begin; } TEMPLATE_SPECIALIZATION -inline void buffer_vector_specialized::resize (size_type const &size) +inline void buffer_vector_specialized::resize(size_type const& size) { - size_type current_size = this->size(); - if (size == current_size) - return; + size_type current_size = this->size(); + if (size == current_size) + return; - if (size < current_size) { - destroy (m_begin + size, m_begin + current_size); - m_end = m_begin + size; - VERIFY (m_max_end >= m_end); - return; - } + if (size < current_size) + { + destroy(m_begin + size, m_begin + current_size); + m_end = m_begin + size; + VERIFY(m_max_end >= m_end); + return; + } - VERIFY (size > current_size); - construct (m_begin + current_size, m_begin + size); - m_end = m_begin + size; - VERIFY (m_max_end >= m_end); + VERIFY(size > current_size); + construct(m_begin + current_size, m_begin + size); + m_end = m_begin + size; + VERIFY(m_max_end >= m_end); } TEMPLATE_SPECIALIZATION -inline void buffer_vector_specialized::reserve (size_type const &size) +inline void buffer_vector_specialized::reserve(size_type const& size) { - // nothing to do here + // nothing to do here } TEMPLATE_SPECIALIZATION template -inline void buffer_vector_specialized::insert (iterator const &where, input_iterator begin, input_iterator const &end) +inline void buffer_vector_specialized::insert(iterator const& where, input_iterator begin, input_iterator const& end) { - VERIFY (where >= m_begin); + VERIFY(where >= m_begin); - difference_type count = end - begin; - VERIFY (m_end + count <= m_max_end); - - iterator j = m_end + count - 1; // new end - iterator i = m_end - 1; // old end - iterator e = where - 1; - for ( ; i != e; --i, --j) { - construct (j, *i); - destroy (i); - } + difference_type count = end - begin; + VERIFY(m_end + count <= m_max_end); - m_end += count; + iterator j = m_end + count - 1; // new end + iterator i = m_end - 1; // old end + iterator e = where - 1; + for (; i != e; --i, --j) + { + construct(j, *i); + destroy(i); + } - for (iterator i = where, e = i + count; i != e; ++i, ++begin) - construct (i, *begin); + m_end += count; + + for (iterator i = where, e = i + count; i != e; ++i, ++begin) + construct(i, *begin); } TEMPLATE_SPECIALIZATION -inline void buffer_vector_specialized::insert (iterator const &where, size_type const &count, const_reference value) +inline void buffer_vector_specialized::insert(iterator const& where, size_type const& count, const_reference value) { - VERIFY (where >= m_begin); - VERIFY (m_end + count <= m_max_end); + VERIFY(where >= m_begin); + VERIFY(m_end + count <= m_max_end); - iterator j = m_end + count - 1; // new end - iterator i = m_end - 1; // old end - iterator e = where - 1; - for ( ; i != e; --i, --j) { - construct (j, *i); - destroy (i); - } + iterator j = m_end + count - 1; // new end + iterator i = m_end - 1; // old end + iterator e = where - 1; + for (; i != e; --i, --j) + { + construct(j, *i); + destroy(i); + } - m_end += count; + m_end += count; - for (iterator i = where, e = i + count; i != e; ++i) - construct (i, value); + for (iterator i = where, e = i + count; i != e; ++i) + construct(i, value); } TEMPLATE_SPECIALIZATION -inline void buffer_vector_specialized::insert (iterator const &where, const_reference value) +inline void buffer_vector_specialized::insert(iterator const& where, const_reference value) { - insert (where, 1, value); + insert(where, 1, value); } TEMPLATE_SPECIALIZATION -inline void buffer_vector_specialized::erase (iterator const &begin, iterator const &end) +inline void buffer_vector_specialized::erase(iterator const& begin, iterator const& end) { - VERIFY (m_begin <= begin); - VERIFY (m_end >= begin); - - VERIFY (m_begin <= end); - VERIFY (m_end >= end); - - VERIFY (begin <= end); - if (begin == end) - return; + VERIFY(m_begin <= begin); + VERIFY(m_end >= begin); + + VERIFY(m_begin <= end); + VERIFY(m_end >= end); + + VERIFY(begin <= end); + if (begin == end) + return; - for (iterator i = begin, j = end; j != m_end; ++i, ++j) { - destroy (i); - construct (i, *j); - } + for (iterator i = begin, j = end; j != m_end; ++i, ++j) + { + destroy(i); + construct(i, *j); + } - size_type count = end - begin; - size_type size = this->size(); - VERIFY (size >= count); - size_type new_size = size - count; - destroy (m_begin + new_size, m_end); - m_end = m_begin + new_size; - VERIFY (m_max_end >= m_end); + size_type count = end - begin; + size_type size = this->size(); + VERIFY(size >= count); + size_type new_size = size - count; + destroy(m_begin + new_size, m_end); + m_end = m_begin + new_size; + VERIFY(m_max_end >= m_end); } TEMPLATE_SPECIALIZATION -inline void buffer_vector_specialized::erase (iterator const &where) +inline void buffer_vector_specialized::erase(iterator const& where) { - erase (where, where + 1); + erase(where, where + 1); } TEMPLATE_SPECIALIZATION -inline void buffer_vector_specialized::pop_back () +inline void buffer_vector_specialized::pop_back() { - VERIFY (!empty()); - --m_end; - destroy (m_end); + VERIFY(!empty()); + --m_end; + destroy(m_end); } TEMPLATE_SPECIALIZATION inline void buffer_vector_specialized::push_back(const_reference value) { - VERIFY (m_end < m_max_end); - construct (m_end, value); - ++m_end; + VERIFY(m_end < m_max_end); + construct(m_end, value); + ++m_end; } TEMPLATE_SPECIALIZATION -inline typename buffer_vector_specialized::reference buffer_vector_specialized::at (size_type const &index) +inline typename buffer_vector_specialized::reference buffer_vector_specialized::at(size_type const& index) { - VERIFY (index < size()); - return (m_begin[index]); + VERIFY(index < size()); + return (m_begin[index]); } TEMPLATE_SPECIALIZATION -inline typename buffer_vector_specialized::const_reference buffer_vector_specialized::at (size_type const &index) const +inline typename buffer_vector_specialized::const_reference buffer_vector_specialized::at(size_type const& index) const { - VERIFY (index < size()); - return (m_begin[index]); + VERIFY(index < size()); + return (m_begin[index]); } TEMPLATE_SPECIALIZATION -inline typename buffer_vector_specialized::reference buffer_vector_specialized::operator[] (size_type const &index) +inline typename buffer_vector_specialized::reference buffer_vector_specialized::operator[] (size_type const& index) { - VERIFY (index < size()); - return (m_begin[index]); + VERIFY(index < size()); + return (m_begin[index]); } TEMPLATE_SPECIALIZATION -inline typename buffer_vector_specialized::const_reference buffer_vector_specialized::operator[] (size_type const &index) const +inline typename buffer_vector_specialized::const_reference buffer_vector_specialized::operator[] (size_type const& index) const { - VERIFY (index < size()); - return (m_begin[index]); + VERIFY(index < size()); + return (m_begin[index]); } TEMPLATE_SPECIALIZATION -inline typename buffer_vector_specialized::reference buffer_vector_specialized::back () +inline typename buffer_vector_specialized::reference buffer_vector_specialized::back() { - VERIFY (!empty()); - return (*(m_end - 1)); + VERIFY(!empty()); + return (*(m_end - 1)); } TEMPLATE_SPECIALIZATION -inline typename buffer_vector_specialized::const_reference buffer_vector_specialized::back () const +inline typename buffer_vector_specialized::const_reference buffer_vector_specialized::back() const { - VERIFY (!empty()); - return (*(m_end - 1)); + VERIFY(!empty()); + return (*(m_end - 1)); } TEMPLATE_SPECIALIZATION -inline typename buffer_vector_specialized::reference buffer_vector_specialized::front () +inline typename buffer_vector_specialized::reference buffer_vector_specialized::front() { - VERIFY (!empty()); - return (*m_begin); + VERIFY(!empty()); + return (*m_begin); } TEMPLATE_SPECIALIZATION -inline typename buffer_vector_specialized::const_reference buffer_vector_specialized::front () const +inline typename buffer_vector_specialized::const_reference buffer_vector_specialized::front() const { - VERIFY (!empty()); - return (*m_begin); + VERIFY(!empty()); + return (*m_begin); } TEMPLATE_SPECIALIZATION -inline typename buffer_vector_specialized::iterator buffer_vector_specialized::begin () +inline typename buffer_vector_specialized::iterator buffer_vector_specialized::begin() { - return (m_begin); + return (m_begin); } TEMPLATE_SPECIALIZATION -inline typename buffer_vector_specialized::const_iterator buffer_vector_specialized::begin () const +inline typename buffer_vector_specialized::const_iterator buffer_vector_specialized::begin() const { - return (m_begin); + return (m_begin); } TEMPLATE_SPECIALIZATION -inline typename buffer_vector_specialized::iterator buffer_vector_specialized::end () +inline typename buffer_vector_specialized::iterator buffer_vector_specialized::end() { - return (m_end); + return (m_end); } TEMPLATE_SPECIALIZATION -inline typename buffer_vector_specialized::const_iterator buffer_vector_specialized::end () const +inline typename buffer_vector_specialized::const_iterator buffer_vector_specialized::end() const { - return (m_end); + return (m_end); } TEMPLATE_SPECIALIZATION -inline typename buffer_vector_specialized::reverse_iterator buffer_vector_specialized::rbegin () +inline typename buffer_vector_specialized::reverse_iterator buffer_vector_specialized::rbegin() { - return (reverse_iterator(end())); + return (reverse_iterator(end())); } TEMPLATE_SPECIALIZATION -inline typename buffer_vector_specialized::const_reverse_iterator buffer_vector_specialized::rbegin () const +inline typename buffer_vector_specialized::const_reverse_iterator buffer_vector_specialized::rbegin() const { - return (const_reverse_iterator(end())); + return (const_reverse_iterator(end())); } TEMPLATE_SPECIALIZATION -inline typename buffer_vector_specialized::reverse_iterator buffer_vector_specialized::rend () +inline typename buffer_vector_specialized::reverse_iterator buffer_vector_specialized::rend() { - return (reverse_iterator(begin())); + return (reverse_iterator(begin())); } TEMPLATE_SPECIALIZATION -inline typename buffer_vector_specialized::const_reverse_iterator buffer_vector_specialized::rend () const +inline typename buffer_vector_specialized::const_reverse_iterator buffer_vector_specialized::rend() const { - return (const_reverse_iterator(begin())); + return (const_reverse_iterator(begin())); } TEMPLATE_SPECIALIZATION -inline bool buffer_vector_specialized::empty () const +inline bool buffer_vector_specialized::empty() const { - return (m_begin == m_end); + return (m_begin == m_end); } TEMPLATE_SPECIALIZATION -inline typename buffer_vector_specialized::size_type buffer_vector_specialized::size () const +inline typename buffer_vector_specialized::size_type buffer_vector_specialized::size() const { - return (m_end - m_begin); + return (m_end - m_begin); } TEMPLATE_SPECIALIZATION -inline typename buffer_vector_specialized::size_type buffer_vector_specialized::capacity () const +inline typename buffer_vector_specialized::size_type buffer_vector_specialized::capacity() const { - return (m_max_end - m_begin); + return (m_max_end - m_begin); } TEMPLATE_SPECIALIZATION -inline typename buffer_vector_specialized::size_type buffer_vector_specialized::max_size () const +inline typename buffer_vector_specialized::size_type buffer_vector_specialized::max_size() const { - return (m_max_end - m_begin); + return (m_max_end - m_begin); } TEMPLATE_SPECIALIZATION inline void buffer_vector_specialized::construct(pointer p) { - new(p) T (); + new(p)T(); } TEMPLATE_SPECIALIZATION inline void buffer_vector_specialized::construct(pointer p, const_reference value) { - new(p) T (value); + new(p)T(value); } TEMPLATE_SPECIALIZATION -inline void buffer_vector_specialized::construct(iterator begin, iterator const &end) +inline void buffer_vector_specialized::construct(iterator begin, iterator const& end) { - for ( ; begin != end; ++begin) - construct (begin); + for (; begin != end; ++begin) + construct(begin); } TEMPLATE_SPECIALIZATION -inline void buffer_vector_specialized::destroy (pointer p) +inline void buffer_vector_specialized::destroy(pointer p) { - p->~T (); + p->~T(); } TEMPLATE_SPECIALIZATION -inline void buffer_vector_specialized::destroy (iterator begin, iterator const &end) +inline void buffer_vector_specialized::destroy(iterator begin, iterator const& end) { - for ( ; begin != end; ++begin) - destroy (begin); + for (; begin != end; ++begin) + destroy(begin); } TEMPLATE_SPECIALIZATION -inline void swap (buffer_vector_specialized &left, buffer_vector_specialized &right) +inline void swap(buffer_vector_specialized& left, buffer_vector_specialized& right) { - left.swap (right); + left.swap(right); } #undef TEMPLATE_SPECIALIZATION diff --git a/src/xrCore/client_id.h b/src/xrCore/client_id.h index 74b42ae1e4b..16b244e8669 100644 --- a/src/xrCore/client_id.h +++ b/src/xrCore/client_id.h @@ -3,18 +3,19 @@ #pragma once #pragma pack(push,1) -class ClientID { - u32 id; +class ClientID +{ + u32 id; public: - ClientID ():id(0) {}; - ClientID (u32 val):id(val) {}; - - u32 value ()const {return id;}; - void set (u32 v) {id=v;}; - bool compare (u32 v) const {return id == v;}; - bool operator == (const ClientID& other)const {return value() == other.value();}; - bool operator != (const ClientID& other)const {return value() != other.value();}; - bool operator < (const ClientID& other)const {return value() < other.value();}; + ClientID() :id(0) {}; + ClientID(u32 val) :id(val) {}; + + u32 value()const { return id; }; + void set(u32 v) { id = v; }; + bool compare(u32 v) const { return id == v; }; + bool operator == (const ClientID& other)const { return value() == other.value(); }; + bool operator != (const ClientID& other)const { return value() != other.value(); }; + bool operator < (const ClientID& other)const { return value() < other.value(); }; }; #pragma pack(pop) diff --git a/src/xrCore/clsid.cpp b/src/xrCore/clsid.cpp index 3a92e55c99a..2bbd2b91453 100644 --- a/src/xrCore/clsid.cpp +++ b/src/xrCore/clsid.cpp @@ -1,16 +1,19 @@ #include "stdafx.h" #pragma hdrstop -XRCORE_API void __stdcall CLSID2TEXT(CLASS_ID id, LPSTR text) { - text[8]=0; - for (int i=7; i>=0; i--) { text[i]=char(id&0xff); id>>=8; } +XRCORE_API void __stdcall CLSID2TEXT(CLASS_ID id, LPSTR text) +{ + text[8] = 0; + for (int i = 7; i >= 0; i--) { text[i] = char(id & 0xff); id >>= 8; } } -XRCORE_API CLASS_ID __stdcall TEXT2CLSID(LPCSTR text) { - VERIFY3(xr_strlen(text)<=8,"Beer from creator CLASS_ID:",text); - char buf[9]; buf[8] = 0; - strncpy_s(buf,sizeof(buf),text,8); - size_t need = 8-xr_strlen(buf); - while (need) { buf[8-need]=' '; need--; } - return MK_CLSID(buf[0],buf[1],buf[2],buf[3],buf[4],buf[5],buf[6],buf[7]); +XRCORE_API CLASS_ID __stdcall TEXT2CLSID(LPCSTR text) +{ + VERIFY3(xr_strlen(text) <= 8, "Beer from creator CLASS_ID:", text); + char buf[9]; + buf[8] = 0; + strncpy_s(buf, sizeof(buf), text, 8); + size_t need = 8 - xr_strlen(buf); + while (need) { buf[8 - need] = ' '; need--; } + return MK_CLSID(buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6], buf[7]); } diff --git a/src/xrCore/clsid.h b/src/xrCore/clsid.h index 64444e11b29..4b34cd7de35 100644 --- a/src/xrCore/clsid.h +++ b/src/xrCore/clsid.h @@ -4,13 +4,13 @@ #pragma once //***** CLASS ID type -typedef u64 CLASS_ID; +typedef u64 CLASS_ID; #define MK_CLSID(a,b,c,d,e,f,g,h) \ - CLASS_ID((CLASS_ID(a)<= m_buffer); - VERIFY (m_pointer < (m_buffer + m_buffer_size)); - *m_pointer = object; - ++m_pointer; + VERIFY(m_pointer >= m_buffer); + VERIFY(m_pointer < (m_buffer + m_buffer_size)); + *m_pointer = object; + ++m_pointer; } -inline int stream::get_char () +inline int stream::get_char() { - VERIFY (m_pointer >= m_buffer); - if (m_pointer < (m_buffer + m_buffer_size)) - return (*m_pointer++); - return (EOF); + VERIFY(m_pointer >= m_buffer); + if (m_pointer < (m_buffer + m_buffer_size)) + return (*m_pointer++); + return (EOF); } -inline void stream::rewind () +inline void stream::rewind() { - m_pointer = m_buffer; + m_pointer = m_buffer; } -inline u8 *stream::buffer () const +inline u8* stream::buffer() const { - return (m_buffer); + return (m_buffer); } -inline u32 stream::tell () const +inline u32 stream::tell() const { - VERIFY (m_pointer >= m_buffer); - VERIFY2 (m_pointer <= (m_buffer + m_buffer_size),make_string("0x%08x <= 0x%08x + %d",m_pointer,m_buffer,m_buffer_size)); - return (u32(m_pointer - m_buffer)); + VERIFY(m_pointer >= m_buffer); + VERIFY2(m_pointer <= (m_buffer + m_buffer_size), make_string("0x%08x <= 0x%08x + %d", m_pointer, m_buffer, m_buffer_size)); + return (u32(m_pointer - m_buffer)); } } // namespace ppmd diff --git a/src/xrCore/cpuid.h b/src/xrCore/cpuid.h index 4aa191d036e..30f0ecd4b9d 100644 --- a/src/xrCore/cpuid.h +++ b/src/xrCore/cpuid.h @@ -1,38 +1,39 @@ #ifndef _INC_CPUID #define _INC_CPUID -#define _CPU_FEATURE_MMX 0x0001 -#define _CPU_FEATURE_SSE 0x0002 -#define _CPU_FEATURE_SSE2 0x0004 -#define _CPU_FEATURE_3DNOW 0x0008 +#define _CPU_FEATURE_MMX 0x0001 +#define _CPU_FEATURE_SSE 0x0002 +#define _CPU_FEATURE_SSE2 0x0004 +#define _CPU_FEATURE_3DNOW 0x0008 -#define _CPU_FEATURE_SSE3 0x0010 -#define _CPU_FEATURE_SSSE3 0x0020 +#define _CPU_FEATURE_SSE3 0x0010 +#define _CPU_FEATURE_SSSE3 0x0020 #define _CPU_FEATURE_SSE4_1 0x0040 -#define _CPU_FEATURE_SSE4_2 0x0080 - -#define _CPU_FEATURE_MWAIT 0x0100 -#define _CPU_FEATURE_HTT 0x0200 - -struct _processor_info { - char v_name[13]; // vendor name - char model_name[49]; // Name of model eg. Intel_Pentium_Pro - - unsigned char family; // family of the processor, eg. Intel_Pentium_Pro is family 6 processor - unsigned char model; // model of processor, eg. Intel_Pentium_Pro is model 1 of family 6 processor - unsigned char stepping; // Processor revision number - - unsigned int feature; // processor Feature ( same as return value). - - unsigned int n_cores; // number of available physical cores - unsigned int n_threads; // number of available logical threads - - unsigned int affinity_mask; // recommended affinity mask - // all processors available to process - // except 2nd (and upper) logical threads - // of the same physical core +#define _CPU_FEATURE_SSE4_2 0x0080 + +#define _CPU_FEATURE_MWAIT 0x0100 +#define _CPU_FEATURE_HTT 0x0200 + +struct _processor_info +{ + char v_name[13]; // vendor name + char model_name[49]; // Name of model eg. Intel_Pentium_Pro + + unsigned char family; // family of the processor, eg. Intel_Pentium_Pro is family 6 processor + unsigned char model; // model of processor, eg. Intel_Pentium_Pro is model 1 of family 6 processor + unsigned char stepping; // Processor revision number + + unsigned int feature; // processor Feature ( same as return value). + + unsigned int n_cores; // number of available physical cores + unsigned int n_threads; // number of available logical threads + + unsigned int affinity_mask; // recommended affinity mask + // all processors available to process + // except 2nd (and upper) logical threads + // of the same physical core }; -int _cpuid ( _processor_info * ); +int _cpuid(_processor_info*); #endif diff --git a/src/xrCore/crc32.cpp b/src/xrCore/crc32.cpp index b2de7665566..db3dc32a110 100644 --- a/src/xrCore/crc32.cpp +++ b/src/xrCore/crc32.cpp @@ -1,112 +1,112 @@ #include "stdafx.h" #pragma hdrstop -static BOOL crc32_ready = FALSE; -static u32 crc32_table [256]; // Lookup table array +static BOOL crc32_ready = FALSE; +static u32 crc32_table[256]; // Lookup table array -inline u32 Reflect (u32 ref, char ch) // Reflects CRC bits in the lookup table +inline u32 Reflect(u32 ref, char ch) // Reflects CRC bits in the lookup table { - // Used only by Init_CRC32_Table(). - - u32 value(0); - - // Swap bit 0 for bit 7 - // bit 1 for bit 6, etc. - for(int i = 1; i < (ch + 1); i++) - { - if(ref & 1) - value |= 1 << (ch - i); - ref >>= 1; - } - return value; -} - -void crc32_init () + // Used only by Init_CRC32_Table(). + + u32 value(0); + + // Swap bit 0 for bit 7 + // bit 1 for bit 6, etc. + for (int i = 1; i < (ch + 1); i++) + { + if (ref & 1) + value |= 1 << (ch - i); + ref >>= 1; + } + return value; +} + +void crc32_init() { - // Call this function only once to initialize the CRC table. - - // This is the official polynomial used by CRC-32 - // in PKZip, WinZip and Ethernet. - u32 ulPolynomial = 0x04c11db7; - - // 256 values representing ASCII character codes. - for(int i = 0; i <= 0xFF; i++) - { - crc32_table[i]=Reflect(i, 8) << 24; - for (int j = 0; j < 8; j++) - crc32_table[i] = (crc32_table[i] << 1) ^ (crc32_table[i] & (1 << 31) ? ulPolynomial : 0); - crc32_table[i] = Reflect(crc32_table[i], 32); - } -} - -u32 crc32 (const void* P, u32 len) + // Call this function only once to initialize the CRC table. + + // This is the official polynomial used by CRC-32 + // in PKZip, WinZip and Ethernet. + u32 ulPolynomial = 0x04c11db7; + + // 256 values representing ASCII character codes. + for (int i = 0; i <= 0xFF; i++) + { + crc32_table[i] = Reflect(i, 8) << 24; + for (int j = 0; j < 8; j++) + crc32_table[i] = (crc32_table[i] << 1) ^ (crc32_table[i] & (1 << 31) ? ulPolynomial : 0); + crc32_table[i] = Reflect(crc32_table[i], 32); + } +} + +u32 crc32(const void* P, u32 len) { - if (!crc32_ready) - { - crc32_init (); - crc32_ready = TRUE; - } + if (!crc32_ready) + { + crc32_init(); + crc32_ready = TRUE; + } - // Pass a text string to this function and it will return the CRC. + // Pass a text string to this function and it will return the CRC. - // Once the lookup table has been filled in by the two functions above, - // this function creates all CRCs using only the lookup table. + // Once the lookup table has been filled in by the two functions above, + // this function creates all CRCs using only the lookup table. - // Be sure to use unsigned variables, - // because negative values introduce high bits - // where zero bits are required. + // Be sure to use unsigned variables, + // because negative values introduce high bits + // where zero bits are required. - // Start out with all bits set high. - u32 ulCRC = 0xffffffff; - u8* buffer = (u8*)P; + // Start out with all bits set high. + u32 ulCRC = 0xffffffff; + u8* buffer = (u8*)P; - // Perform the algorithm on each character - // in the string, using the lookup table values. - while(len--) - ulCRC = (ulCRC >> 8) ^ crc32_table[(ulCRC & 0xFF) ^ *buffer++]; + // Perform the algorithm on each character + // in the string, using the lookup table values. + while (len--) + ulCRC = (ulCRC >> 8) ^ crc32_table[(ulCRC & 0xFF) ^ *buffer++]; - // Exclusive OR the result with the beginning value. - return ulCRC ^ 0xffffffff; -} + // Exclusive OR the result with the beginning value. + return ulCRC ^ 0xffffffff; +} -u32 crc32 (const void* P, u32 len, u32 starting_crc) +u32 crc32(const void* P, u32 len, u32 starting_crc) { - if (!crc32_ready) - { - crc32_init (); - crc32_ready = TRUE; - } + if (!crc32_ready) + { + crc32_init(); + crc32_ready = TRUE; + } - u32 ulCRC = 0xffffffff ^ starting_crc; - u8* buffer = (u8*)P; + u32 ulCRC = 0xffffffff ^ starting_crc; + u8* buffer = (u8*)P; - while(len--) - ulCRC = (ulCRC >> 8) ^ crc32_table[(ulCRC & 0xFF) ^ *buffer++]; + while (len--) + ulCRC = (ulCRC >> 8) ^ crc32_table[(ulCRC & 0xFF) ^ *buffer++]; - return ulCRC ^ 0xffffffff; -} + return ulCRC ^ 0xffffffff; +} -u32 path_crc32 (const char* path, u32 len) +u32 path_crc32(const char* path, u32 len) { - if (!crc32_ready) - { - crc32_init (); - crc32_ready = TRUE; - } - - u32 ulCRC = 0xffffffff; - u8* buffer = (u8*)path; - - while(len--) - { - const u8 c = *buffer; - if ( c != '/' && c != '\\' ) - { - ulCRC = (ulCRC >> 8) ^ crc32_table[(ulCRC & 0xFF) ^ *buffer]; - } - - ++buffer; - } - - return ulCRC ^ 0xffffffff; -} \ No newline at end of file + if (!crc32_ready) + { + crc32_init(); + crc32_ready = TRUE; + } + + u32 ulCRC = 0xffffffff; + u8* buffer = (u8*)path; + + while (len--) + { + const u8 c = *buffer; + if (c != '/' && c != '\\') + { + ulCRC = (ulCRC >> 8) ^ crc32_table[(ulCRC & 0xFF) ^ *buffer]; + } + + ++buffer; + } + + return ulCRC ^ 0xffffffff; +} \ No newline at end of file diff --git a/src/xrCore/doug_lea_allocator.cpp b/src/xrCore/doug_lea_allocator.cpp index 53cdfe54c8c..c2f7a7732eb 100644 --- a/src/xrCore/doug_lea_allocator.cpp +++ b/src/xrCore/doug_lea_allocator.cpp @@ -1,7 +1,7 @@ //////////////////////////////////////////////////////////////////////////// -// Created : 14.08.2009 -// Author : Armen Abroyan -// Copyright (C) GSC Game World - 2009 +// Created : 14.08.2009 +// Author : Armen Abroyan +// Copyright (C) GSC Game World - 2009 //////////////////////////////////////////////////////////////////////////// #include "stdafx.h" @@ -13,49 +13,49 @@ #define USE_LOCKS 0 #include "ptmalloc3/malloc-2.8.3.h" -static void __stdcall out_of_memory ( mspace const space, void const* const parameter, int const first_time ) +static void __stdcall out_of_memory(mspace const space, void const* const parameter, int const first_time) { - if ( first_time ) - return; + if (first_time) + return; - doug_lea_allocator* const allocator = ( doug_lea_allocator* )parameter; - Debug.fatal ( DEBUG_INFO, "not enough memory for arena [%s]", allocator->get_arena_id( ) ); + doug_lea_allocator* const allocator = (doug_lea_allocator*)parameter; + Debug.fatal(DEBUG_INFO, "not enough memory for arena [%s]", allocator->get_arena_id()); } -doug_lea_allocator::doug_lea_allocator ( void* arena, u32 arena_size, LPCSTR arena_id ) : - m_arena_id ( arena_id ) +doug_lea_allocator::doug_lea_allocator(void* arena, u32 arena_size, LPCSTR arena_id) : +m_arena_id(arena_id) { - VERIFY ( m_arena_id ); + VERIFY(m_arena_id); - if ( arena && arena_size ) - m_dl_arena = create_mspace_with_base( arena, arena_size, 0, &out_of_memory, (void*)this ); - else - m_dl_arena = create_mspace( 0, 0, 0, 0 ); + if (arena && arena_size) + m_dl_arena = create_mspace_with_base(arena, arena_size, 0, &out_of_memory, (void*)this); + else + m_dl_arena = create_mspace(0, 0, 0, 0); } -doug_lea_allocator::~doug_lea_allocator ( ) +doug_lea_allocator::~doug_lea_allocator() { - VERIFY ( m_dl_arena ); - destroy_mspace ( m_dl_arena ); + VERIFY(m_dl_arena); + destroy_mspace(m_dl_arena); } -void* doug_lea_allocator::malloc_impl ( u32 size ) +void* doug_lea_allocator::malloc_impl(u32 size) { - return mspace_malloc( m_dl_arena, size ); + return mspace_malloc(m_dl_arena, size); } -void* doug_lea_allocator::realloc_impl ( void* pointer, u32 new_size ) +void* doug_lea_allocator::realloc_impl(void* pointer, u32 new_size) { - return mspace_realloc( m_dl_arena, pointer, new_size ); + return mspace_realloc(m_dl_arena, pointer, new_size); } -void doug_lea_allocator::free_impl ( void*& pointer ) +void doug_lea_allocator::free_impl(void*& pointer) { - mspace_free ( m_dl_arena, pointer ); - pointer = 0; + mspace_free(m_dl_arena, pointer); + pointer = 0; } -u32 doug_lea_allocator::get_allocated_size ( ) const +u32 doug_lea_allocator::get_allocated_size() const { - return (u32)mspace_mallinfo(m_dl_arena).uordblks; + return (u32)mspace_mallinfo(m_dl_arena).uordblks; } \ No newline at end of file diff --git a/src/xrCore/doug_lea_allocator.h b/src/xrCore/doug_lea_allocator.h index ec8ca640679..6efeee32d91 100644 --- a/src/xrCore/doug_lea_allocator.h +++ b/src/xrCore/doug_lea_allocator.h @@ -1,37 +1,38 @@ //////////////////////////////////////////////////////////////////////////// -// Created : 14.08.2009 -// Author : Armen Abroyan -// Copyright (C) GSC Game World - 2009 +// Created : 14.08.2009 +// Author : Armen Abroyan +// Copyright (C) GSC Game World - 2009 //////////////////////////////////////////////////////////////////////////// #ifndef DOUG_LEA_ALLOCATOR_H_INCLUDED #define DOUG_LEA_ALLOCATOR_H_INCLUDED -class XRCORE_API doug_lea_allocator { +class XRCORE_API doug_lea_allocator +{ public: - doug_lea_allocator ( void* arena, u32 arena_size, LPCSTR arena_id ); - ~doug_lea_allocator ( ); - void* malloc_impl ( u32 size ); - void* realloc_impl ( void* pointer, u32 new_size ); - void free_impl ( void*& pointer ); - u32 get_allocated_size ( ) const; - inline LPCSTR get_arena_id ( ) const { return m_arena_id; } + doug_lea_allocator(void* arena, u32 arena_size, LPCSTR arena_id); + ~doug_lea_allocator(); + void* malloc_impl(u32 size); + void* realloc_impl(void* pointer, u32 new_size); + void free_impl(void*& pointer); + u32 get_allocated_size() const; + inline LPCSTR get_arena_id() const { return m_arena_id; } - template - inline void free_impl ( T*& pointer ) - { - free_impl ( reinterpret_cast(pointer) ); - } + template + inline void free_impl(T*& pointer) + { + free_impl(reinterpret_cast(pointer)); + } - template < typename T > - inline T* alloc_impl ( u32 const count ) - { - return (T*)malloc_impl( count*sizeof(T) ); - } + template < typename T > + inline T* alloc_impl(u32 const count) + { + return (T*)malloc_impl(count*sizeof(T)); + } private: - LPCSTR m_arena_id; - void* m_dl_arena; + LPCSTR m_arena_id; + void* m_dl_arena; }; // class doug_lea_allocator #endif // #ifndef DOUG_LEA_ALLOCATOR_H_INCLUDED \ No newline at end of file diff --git a/src/xrCore/dump_string.cpp b/src/xrCore/dump_string.cpp index d4d209dd4cc..43189fd6e4e 100644 --- a/src/xrCore/dump_string.cpp +++ b/src/xrCore/dump_string.cpp @@ -1,55 +1,55 @@ #include "stdafx.h" -#ifdef DEBUG -std::string get_string( const Fvector& v ) +#ifdef DEBUG +std::string get_string(const Fvector& v) { - return make_string ("( %f, %f, %f )", v.x, v.y, v.z ); + return make_string("( %f, %f, %f )", v.x, v.y, v.z); } -std::string get_string( const Fmatrix& dop ) +std::string get_string(const Fmatrix& dop) { - return make_string ("\n%f,%f,%f,%f\n%f,%f,%f,%f\n%f,%f,%f,%f\n%f,%f,%f,%f\n", - dop.i.x, dop.i.y, dop.i.z, dop._14_, - dop.j.x, dop.j.y, dop.j.z, dop._24_, - dop.k.x, dop.k.y, dop.k.z, dop._34_, - dop.c.x, dop.c.y, dop.c.z, dop._44_ - ); + return make_string("\n%f,%f,%f,%f\n%f,%f,%f,%f\n%f,%f,%f,%f\n%f,%f,%f,%f\n", + dop.i.x, dop.i.y, dop.i.z, dop._14_, + dop.j.x, dop.j.y, dop.j.z, dop._24_, + dop.k.x, dop.k.y, dop.k.z, dop._34_, + dop.c.x, dop.c.y, dop.c.z, dop._44_ + ); } -std::string get_string(const Fbox &box) +std::string get_string(const Fbox& box) { - return make_string( "[ min: %s - max: %s ]", get_string( box.min ).c_str(), get_string( box.max ).c_str() ); + return make_string("[ min: %s - max: %s ]", get_string(box.min).c_str(), get_string(box.max).c_str()); } -std::string get_string( bool v ) +std::string get_string(bool v) { - return v ? std::string( "true" ) : std::string( "false" ); + return v ? std::string("true") : std::string("false"); } -std::string dump_string( LPCSTR name, const Fvector &v ) +std::string dump_string(LPCSTR name, const Fvector& v) { - return make_string( "%s : (%f,%f,%f) ", name, v.x, v.y, v.z ); + return make_string("%s : (%f,%f,%f) ", name, v.x, v.y, v.z); } -void dump( LPCSTR name, const Fvector &v ) +void dump(LPCSTR name, const Fvector& v) { - Msg( "%s", dump_string( name, v ).c_str() ); + Msg("%s", dump_string(name, v).c_str()); } -std::string dump_string( LPCSTR name, const Fmatrix &form ) +std::string dump_string(LPCSTR name, const Fmatrix& form) { - return - make_string( "%s, _14_=%f \n", dump_string( make_string( "%s.i, ", name ).c_str(), form.i ).c_str( ) , form._14_ ) + - make_string( "%s, _24_=%f \n", dump_string( make_string( "%s.j, ", name ).c_str(), form.j ).c_str( ) , form._24_ ) + - make_string( "%s, _34_=%f \n", dump_string( make_string( "%s.k, ", name ).c_str(), form.k ).c_str( ) , form._34_ ) + - make_string( "%s, _44_=%f \n", dump_string( make_string( "%s.c, ", name ).c_str(), form.c ).c_str( ) , form._44_ ); + return + make_string("%s, _14_=%f \n", dump_string(make_string("%s.i, ", name).c_str(), form.i).c_str(), form._14_) + + make_string("%s, _24_=%f \n", dump_string(make_string("%s.j, ", name).c_str(), form.j).c_str(), form._24_) + + make_string("%s, _34_=%f \n", dump_string(make_string("%s.k, ", name).c_str(), form.k).c_str(), form._34_) + + make_string("%s, _44_=%f \n", dump_string(make_string("%s.c, ", name).c_str(), form.c).c_str(), form._44_); } -void dump( LPCSTR name, const Fmatrix &form ) +void dump(LPCSTR name, const Fmatrix& form) { - Msg( "%s", dump_string( name, form ).c_str() ); - //Msg( "%s, _14_=%f ", dump_string( make_string( "%s.i, ", name ).c_str(), form.i ).c_str( ) , form._14_ ); - //Msg( "%s, _24_=%f ", dump_string( make_string( "%s.j, ", name ).c_str(), form.j ).c_str( ) , form._24_ ); - //Msg( "%s, _34_=%f ", dump_string( make_string( "%s.k, ", name ).c_str(), form.k ).c_str( ) , form._34_ ); - //Msg( "%s, _44_=%f ", dump_string( make_string( "%s.c, ", name ).c_str(), form.c ).c_str( ) , form._44_ ); + Msg("%s", dump_string(name, form).c_str()); + //Msg( "%s, _14_=%f ", dump_string( make_string( "%s.i, ", name ).c_str(), form.i ).c_str( ) , form._14_ ); + //Msg( "%s, _24_=%f ", dump_string( make_string( "%s.j, ", name ).c_str(), form.j ).c_str( ) , form._24_ ); + //Msg( "%s, _34_=%f ", dump_string( make_string( "%s.k, ", name ).c_str(), form.k ).c_str( ) , form._34_ ); + //Msg( "%s, _44_=%f ", dump_string( make_string( "%s.c, ", name ).c_str(), form.c ).c_str( ) , form._44_ ); } #endif \ No newline at end of file diff --git a/src/xrCore/dump_string.h b/src/xrCore/dump_string.h index 00b04cb30aa..5e45cbfed7f 100644 --- a/src/xrCore/dump_string.h +++ b/src/xrCore/dump_string.h @@ -1,13 +1,13 @@ #pragma once -#ifdef DEBUG -XRCORE_API std::string get_string( bool v ); -XRCORE_API std::string get_string( const Fvector& v ); -XRCORE_API std::string get_string( const Fmatrix& dop ); -XRCORE_API std::string get_string(const Fbox &box); +#ifdef DEBUG +XRCORE_API std::string get_string(bool v); +XRCORE_API std::string get_string(const Fvector& v); +XRCORE_API std::string get_string(const Fmatrix& dop); +XRCORE_API std::string get_string(const Fbox& box); -XRCORE_API std::string dump_string( LPCSTR name, const Fvector &v ); -XRCORE_API std::string dump_string( LPCSTR name, const Fmatrix &form ); -XRCORE_API void dump( LPCSTR name, const Fmatrix &form ); -XRCORE_API void dump( LPCSTR name, const Fvector &v ); +XRCORE_API std::string dump_string(LPCSTR name, const Fvector& v); +XRCORE_API std::string dump_string(LPCSTR name, const Fmatrix& form); +XRCORE_API void dump(LPCSTR name, const Fmatrix& form); +XRCORE_API void dump(LPCSTR name, const Fvector& v); #endif \ No newline at end of file diff --git a/src/xrCore/fastdelegate.h b/src/xrCore/fastdelegate.h index 9e2cccfadce..3a7b05a10e5 100644 --- a/src/xrCore/fastdelegate.h +++ b/src/xrCore/fastdelegate.h @@ -1,47 +1,47 @@ -// FastDelegate.h -// Efficient delegates in C++ that generate only two lines of asm code! +// FastDelegate.h +// Efficient delegates in C++ that generate only two lines of asm code! // Documentation is found at http://www.codeproject.com/cpp/FastDelegate.asp // -// - Don Clugston, Mar 2004. -// Major contributions were made by Jody Hagins. +// - Don Clugston, Mar 2004. +// Major contributions were made by Jody Hagins. // History: // 24-Apr-04 1.0 * Submitted to CodeProject. // 28-Apr-04 1.1 * Prevent most unsafe uses of evil static function hack. -// * Improved syntax for horrible_cast (thanks Paul Bludov). -// * Tested on Metrowerks MWCC and Intel ICL (IA32) -// * Compiled, but not run, on Comeau C++ and Intel Itanium ICL. -// 27-Jun-04 1.2 * Now works on Borland C++ Builder 5.5 -// * Now works on /clr "managed C++" code on VC7, VC7.1 -// * Comeau C++ now compiles without warnings. -// * Prevent the virtual inheritance case from being used on -// VC6 and earlier, which generate incorrect code. -// * Improved warning and error messages. Non-standard hacks -// now have compile-time checks to make them safer. -// * implicit_cast used instead of static_cast in many cases. -// * If calling a const member function, a const class pointer can be used. -// * MakeDelegate() global helper function added to simplify pass-by-value. -// * Added fastdelegate.clear() +// * Improved syntax for horrible_cast (thanks Paul Bludov). +// * Tested on Metrowerks MWCC and Intel ICL (IA32) +// * Compiled, but not run, on Comeau C++ and Intel Itanium ICL. +// 27-Jun-04 1.2 * Now works on Borland C++ Builder 5.5 +// * Now works on /clr "managed C++" code on VC7, VC7.1 +// * Comeau C++ now compiles without warnings. +// * Prevent the virtual inheritance case from being used on +// VC6 and earlier, which generate incorrect code. +// * Improved warning and error messages. Non-standard hacks +// now have compile-time checks to make them safer. +// * implicit_cast used instead of static_cast in many cases. +// * If calling a const member function, a const class pointer can be used. +// * MakeDelegate() global helper function added to simplify pass-by-value. +// * Added fastdelegate.clear() // 16-Jul-04 1.2.1* Workaround for gcc bug (const member function pointers in templates) // 30-Oct-04 1.3 * Support for (non-void) return values. -// * No more workarounds in client code! -// MSVC and Intel now use a clever hack invented by John Dlugosz: -// - The FASTDELEGATEDECLARE workaround is no longer necessary. -// - No more warning messages for VC6 -// * Less use of macros. Error messages should be more comprehensible. -// * Added include guards -// * Added FastDelegate::empty() to test if invocation is safe (Thanks Neville Franks). -// * Now tested on VS 2005 Express Beta, PGI C++ +// * No more workarounds in client code! +// MSVC and Intel now use a clever hack invented by John Dlugosz: +// - The FASTDELEGATEDECLARE workaround is no longer necessary. +// - No more warning messages for VC6 +// * Less use of macros. Error messages should be more comprehensible. +// * Added include guards +// * Added FastDelegate::empty() to test if invocation is safe (Thanks Neville Franks). +// * Now tested on VS 2005 Express Beta, PGI C++ // 24-Dec-04 1.4 * Added DelegateMemento, to allow collections of disparate delegates. // * <,>,<=,>= comparison operators to allow storage in ordered containers. -// * Substantial reduction of code size, especially the 'Closure' class. -// * Standardised all the compiler-specific workarounds. +// * Substantial reduction of code size, especially the 'Closure' class. +// * Standardised all the compiler-specific workarounds. // * MFP conversion now works for CodePlay (but not yet supported in the full code). // * Now compiles without warnings on _any_ supported compiler, including BCC 5.5.1 -// * New syntax: FastDelegate< int (char *, double) >. +// * New syntax: FastDelegate< int (char *, double) >. // 14-Feb-05 1.4.1* Now treats =0 as equivalent to .clear(), ==0 as equivalent to .empty(). (Thanks elfric). -// * Now tested on Intel ICL for AMD64, VS2005 Beta for AMD64 and Itanium. +// * Now tested on Intel ICL for AMD64, VS2005 Beta for AMD64 and Itanium. // 30-Mar-05 1.5 * Safebool idiom: "if (dg)" is now equivalent to "if (!dg.empty())" -// * Fully supported by CodePlay VectorC +// * Fully supported by CodePlay VectorC // * Bugfix for Metrowerks: empty() was buggy because a valid MFP can be 0 on MWCC! // * More optimal assignment,== and != operators for static function pointers. @@ -58,7 +58,7 @@ /////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -// Configuration options +// Configuration options // //////////////////////////////////////////////////////////////////////////////// @@ -75,7 +75,7 @@ //#define FASTDELEGATE_ALLOW_FUNCTION_TYPE_SYNTAX //////////////////////////////////////////////////////////////////////////////// -// Compiler identification for workarounds +// Compiler identification for workarounds // //////////////////////////////////////////////////////////////////////////////// @@ -120,33 +120,33 @@ #endif #ifdef __GNUC__ // Workaround GCC bug #8271 - // At present, GCC doesn't recognize constness of MFPs in templates + // At present, GCC doesn't recognize constness of MFPs in templates #define FASTDELEGATE_GCC_BUG_8271 #endif //////////////////////////////////////////////////////////////////////////////// -// General tricks used in this code +// General tricks used in this code // // (a) Error messages are generated by typdefing an array of negative size to // generate compile-time errors. // (b) Warning messages on MSVC are generated by declaring unused variables, and -// enabling the "variable XXX is never used" warning. +// enabling the "variable XXX is never used" warning. // (c) Unions are used in a few compiler-specific cases to perform illegal casts. // (d) For Microsoft and Intel, when adjusting the 'this' pointer, it's cast to // (char *) first to ensure that the correct number of *bytes* are added. // //////////////////////////////////////////////////////////////////////////////// -// Helper templates +// Helper templates // //////////////////////////////////////////////////////////////////////////////// namespace fastdelegate { -namespace detail { // we'll hide the implementation details in a nested namespace. +namespace detail { // we'll hide the implementation details in a nested namespace. -// implicit_cast< > +// implicit_cast< > // I believe this was originally going to be in the C++ standard but // was left out by accident. It's even milder than static_cast. // I use it instead of static_cast<> to emphasize that I'm not doing @@ -154,10 +154,10 @@ namespace detail { // we'll hide the implementation details in a nested namespac // Usage is identical to static_cast<> template inline OutputClass implicit_cast(InputClass input){ - return input; + return input; } -// horrible_cast< > +// horrible_cast< > // This is truly evil. It completely subverts C++'s type system, allowing you // to cast from any class to any other class. Technically, using a union // to perform the cast is undefined behaviour (even in C). But we can see if @@ -169,37 +169,37 @@ inline OutputClass implicit_cast(InputClass input){ // can't inline a function with a nested class, and gives a warning. template union horrible_union{ - OutputClass out; - InputClass in; + OutputClass out; + InputClass in; }; template inline OutputClass horrible_cast(const InputClass input){ - horrible_union u; - // Cause a compile-time error if in, out and u are not the same size. - // If the compile fails here, it means the compiler has peculiar - // unions which would prevent the cast from working. - typedef int ERROR_CantUseHorrible_cast[sizeof(InputClass)==sizeof(u) - && sizeof(InputClass)==sizeof(OutputClass) ? 1 : -1]; - u.in = input; - return u.out; + horrible_union u; + // Cause a compile-time error if in, out and u are not the same size. + // If the compile fails here, it means the compiler has peculiar + // unions which would prevent the cast from working. + typedef int ERROR_CantUseHorrible_cast[sizeof(InputClass)==sizeof(u) + && sizeof(InputClass)==sizeof(OutputClass) ? 1 : -1]; + u.in = input; + return u.out; } //////////////////////////////////////////////////////////////////////////////// -// Workarounds +// Workarounds // //////////////////////////////////////////////////////////////////////////////// // Backwards compatibility: This macro used to be necessary in the virtual inheritance // case for Intel and Microsoft. Now it just forward-declares the class. -#define FASTDELEGATEDECLARE(CLASSNAME) class CLASSNAME; +#define FASTDELEGATEDECLARE(CLASSNAME) class CLASSNAME; // Prevent use of the static function hack with the DOS medium model. #ifdef __MEDIUM__ #undef FASTDELEGATE_USESTATICFUNCTIONHACK #endif -// DefaultVoid - a workaround for 'void' templates in VC6. +// DefaultVoid - a workaround for 'void' templates in VC6. // // (1) VC6 and earlier do not allow 'void' as a default template argument. // (2) They also doesn't allow you to return 'void' from a function. @@ -230,7 +230,7 @@ template struct DefaultVoidToVoid { typedef T type; }; template <> -struct DefaultVoidToVoid { typedef void type; }; +struct DefaultVoidToVoid { typedef void type; }; // Translate from 'void' into 'DefaultVoid' // Everything else is unchanged @@ -243,9 +243,9 @@ struct VoidToDefaultVoid { typedef DefaultVoid type; }; //////////////////////////////////////////////////////////////////////////////// -// Fast Delegates, part 1: +// Fast Delegates, part 1: // -// Conversion of member function pointer to a standard form +// Conversion of member function pointer to a standard form // //////////////////////////////////////////////////////////////////////////////// @@ -258,72 +258,72 @@ struct VoidToDefaultVoid { typedef DefaultVoid type; }; #ifdef FASTDLGT_MICROSOFT_MFP #ifdef FASTDLGT_HASINHERITANCE_KEYWORDS - // For Microsoft and Intel, we want to ensure that it's the most efficient type of MFP - // (4 bytes), even when the /vmg option is used. Declaring an empty class - // would give 16 byte pointers in this case.... - class __single_inheritance GenericClass; + // For Microsoft and Intel, we want to ensure that it's the most efficient type of MFP + // (4 bytes), even when the /vmg option is used. Declaring an empty class + // would give 16 byte pointers in this case.... + class __single_inheritance GenericClass; #endif - // ...but for Codeplay, an empty class *always* gives 4 byte pointers. - // If compiled with the /clr option ("managed C++"), the JIT compiler thinks - // it needs to load GenericClass before it can call any of its functions, - // (compiles OK but crashes at runtime!), so we need to declare an - // empty class to make it happy. - // Codeplay and VC4 can't cope with the unknown_inheritance case either. - class GenericClass {}; + // ...but for Codeplay, an empty class *always* gives 4 byte pointers. + // If compiled with the /clr option ("managed C++"), the JIT compiler thinks + // it needs to load GenericClass before it can call any of its functions, + // (compiles OK but crashes at runtime!), so we need to declare an + // empty class to make it happy. + // Codeplay and VC4 can't cope with the unknown_inheritance case either. + class GenericClass {}; #else - class GenericClass; + class GenericClass; #endif // The size of a single inheritance member function pointer. const int SINGLE_MEMFUNCPTR_SIZE = sizeof(void (xr_stdcall GenericClass::*)()); -// SimplifyMemFunc< >::Convert() +// SimplifyMemFunc< >::Convert() // -// A template function that converts an arbitrary member function pointer into the -// simplest possible form of member function pointer, using a supplied 'this' pointer. +// A template function that converts an arbitrary member function pointer into the +// simplest possible form of member function pointer, using a supplied 'this' pointer. // According to the standard, this can be done legally with reinterpret_cast<>. -// For (non-standard) compilers which use member function pointers which vary in size -// depending on the class, we need to use knowledge of the internal structure of a +// For (non-standard) compilers which use member function pointers which vary in size +// depending on the class, we need to use knowledge of the internal structure of a // member function pointer, as used by the compiler. Template specialization is used // to distinguish between the sizes. Because some compilers don't support partial -// template specialisation, I use full specialisation of a wrapper struct. +// template specialisation, I use full specialisation of a wrapper struct. // general case -- don't know how to convert it. Force a compile failure template struct SimplifyMemFunc { - template - inline static GenericClass * xr_stdcall Convert(X *pthis, XFuncType function_to_bind, - GenericMemFuncType &bound_func) { - // Unsupported member function type -- force a compile failure. - // (it's illegal to have a array with negative size). - typedef char ERROR_Unsupported_member_function_pointer_on_this_compiler[N-100]; - return 0; - } + template + inline static GenericClass * xr_stdcall Convert(X *pthis, XFuncType function_to_bind, + GenericMemFuncType &bound_func) { + // Unsupported member function type -- force a compile failure. + // (it's illegal to have a array with negative size). + typedef char ERROR_Unsupported_member_function_pointer_on_this_compiler[N-100]; + return 0; + } }; // For compilers where all member func ptrs are the same size, everything goes here. // For non-standard compilers, only single_inheritance classes go here. template <> -struct SimplifyMemFunc { - template - inline static GenericClass * xr_stdcall Convert(X *pthis, XFuncType function_to_bind, - GenericMemFuncType &bound_func) { +struct SimplifyMemFunc { + template + inline static GenericClass * xr_stdcall Convert(X *pthis, XFuncType function_to_bind, + GenericMemFuncType &bound_func) { #if defined __DMC__ - // Digital Mars doesn't allow you to cast between abitrary PMF's, - // even though the standard says you can. The 32-bit compiler lets you - // static_cast through an int, but the DOS compiler doesn't. - bound_func = horrible_cast(function_to_bind); + // Digital Mars doesn't allow you to cast between abitrary PMF's, + // even though the standard says you can. The 32-bit compiler lets you + // static_cast through an int, but the DOS compiler doesn't. + bound_func = horrible_cast(function_to_bind); #else bound_func = reinterpret_cast(function_to_bind); #endif return reinterpret_cast(pthis); - } + } }; //////////////////////////////////////////////////////////////////////////////// -// Fast Delegates, part 1b: +// Fast Delegates, part 1b: // -// Workarounds for Microsoft and Intel +// Workarounds for Microsoft and Intel // //////////////////////////////////////////////////////////////////////////////// @@ -340,24 +340,24 @@ struct SimplifyMemFunc { // Nasty hack for Microsoft and Intel (IA32 and Itanium) template<> struct SimplifyMemFunc< SINGLE_MEMFUNCPTR_SIZE + sizeof(int) > { - template - inline static GenericClass * xr_stdcall Convert(X *pthis, XFuncType function_to_bind, - GenericMemFuncType &bound_func) { - // We need to use a horrible_cast to do this conversion. - // In MSVC, a multiple inheritance member pointer is internally defined as: + template + inline static GenericClass * xr_stdcall Convert(X *pthis, XFuncType function_to_bind, + GenericMemFuncType &bound_func) { + // We need to use a horrible_cast to do this conversion. + // In MSVC, a multiple inheritance member pointer is internally defined as: union { - XFuncType func; - struct { - GenericMemFuncType funcaddress; // points to the actual member function - int delta; // #BYTES to be added to the 'this' pointer - }s; + XFuncType func; + struct { + GenericMemFuncType funcaddress; // points to the actual member function + int delta; // #BYTES to be added to the 'this' pointer + }s; } u; - // Check that the horrible_cast will work - typedef int ERROR_CantUsehorrible_cast[sizeof(function_to_bind)==sizeof(u.s)? 1 : -1]; + // Check that the horrible_cast will work + typedef int ERROR_CantUsehorrible_cast[sizeof(function_to_bind)==sizeof(u.s)? 1 : -1]; u.func = function_to_bind; - bound_func = u.s.funcaddress; - return reinterpret_cast(reinterpret_cast(pthis) + u.s.delta); - } + bound_func = u.s.funcaddress; + return reinterpret_cast(reinterpret_cast(pthis) + u.s.delta); + } }; // virtual inheritance is a real nuisance. It's inefficient and complicated. @@ -371,9 +371,9 @@ struct SimplifyMemFunc< SINGLE_MEMFUNCPTR_SIZE + sizeof(int) > { // In VC++ and ICL, a virtual_inheritance member pointer // is internally defined as: struct MicrosoftVirtualMFP { - void (GenericClass::*codeptr)(); // points to the actual member function - int delta; // #bytes to be added to the 'this' pointer - int vtable_index; // or 0 if no virtual inheritance + void (GenericClass::*codeptr)(); // points to the actual member function + int delta; // #bytes to be added to the 'this' pointer + int vtable_index; // or 0 if no virtual inheritance }; // The CRUCIAL feature of Microsoft/Intel MFPs which we exploit is that the // m_codeptr member is *always* called, regardless of the values of the other @@ -386,8 +386,8 @@ struct MicrosoftVirtualMFP { // It has a trival member function that returns the value of the 'this' pointer. struct GenericVirtualClass : virtual public GenericClass { - typedef GenericVirtualClass * (GenericVirtualClass::*ProbePtrType)(); - GenericVirtualClass * GetThis() { return this; } + typedef GenericVirtualClass * (GenericVirtualClass::*ProbePtrType)(); + GenericVirtualClass * GetThis() { return this; } }; // __virtual_inheritance classes go here @@ -395,35 +395,35 @@ template <> struct SimplifyMemFunc { - template - inline static GenericClass * xr_stdcall Convert(X *pthis, XFuncType function_to_bind, - GenericMemFuncType &bound_func) { + template + inline static GenericClass * xr_stdcall Convert(X *pthis, XFuncType function_to_bind, + GenericMemFuncType &bound_func) { #pragma pack(push) #pragma pack(1) - union { - XFuncType func; - GenericClass* (X::*ProbeFunc)(); - MicrosoftVirtualMFP s; - } u; + union { + XFuncType func; + GenericClass* (X::*ProbeFunc)(); + MicrosoftVirtualMFP s; + } u; #pragma pack(pop) - u.func = function_to_bind; - bound_func = reinterpret_cast(u.s.codeptr); - union { - GenericVirtualClass::ProbePtrType virtfunc; - MicrosoftVirtualMFP s; - } u2; - // Check that the horrible_cast<>s will work - typedef int ERROR_CantUsehorrible_cast[sizeof(function_to_bind)==sizeof(u.s) - && sizeof(function_to_bind)==sizeof(u.ProbeFunc) - && sizeof(u2.virtfunc)==sizeof(u2.s) ? 1 : -1]; + u.func = function_to_bind; + bound_func = reinterpret_cast(u.s.codeptr); + union { + GenericVirtualClass::ProbePtrType virtfunc; + MicrosoftVirtualMFP s; + } u2; + // Check that the horrible_cast<>s will work + typedef int ERROR_CantUsehorrible_cast[sizeof(function_to_bind)==sizeof(u.s) + && sizeof(function_to_bind)==sizeof(u.ProbeFunc) + && sizeof(u2.virtfunc)==sizeof(u2.s) ? 1 : -1]; // Unfortunately, taking the address of a MF prevents it from being inlined, so // this next line can't be completely optimised away by the compiler. - u2.virtfunc = &GenericVirtualClass::GetThis; - u.s.codeptr = u2.s.codeptr; - return (pthis->*u.ProbeFunc)(); - } + u2.virtfunc = &GenericVirtualClass::GetThis; + u.s.codeptr = u2.s.codeptr; + return (pthis->*u.ProbeFunc)(); + } }; #if (_MSC_VER <1300) @@ -434,36 +434,36 @@ struct SimplifyMemFunc template <> struct SimplifyMemFunc { - template - inline static GenericClass * xr_stdcall Convert(X *pthis, XFuncType function_to_bind, - GenericMemFuncType &bound_func) { - // There is an apalling but obscure compiler bug in MSVC6 and earlier: - // vtable_index and 'vtordisp' are always set to 0 in the - // unknown_inheritance case! - // This means that an incorrect function could be called!!! - // Compiling with the /vmg option leads to potentially incorrect code. - // This is probably the reason that the IDE has a user interface for specifying - // the /vmg option, but it is disabled - you can only specify /vmg on - // the command line. In VC1.5 and earlier, the compiler would ICE if it ever - // encountered this situation. - // It is OK to use the /vmg option if /vmm or /vms is specified. - - // Fortunately, the wrong function is only called in very obscure cases. - // It only occurs when a derived class overrides a virtual function declared - // in a virtual base class, and the member function - // points to the *Derived* version of that function. The problem can be - // completely averted in 100% of cases by using the *Base class* for the - // member fpointer. Ie, if you use the base class as an interface, you'll - // stay out of trouble. - // Occasionally, you might want to point directly to a derived class function - // that isn't an override of a base class. In this case, both vtable_index - // and 'vtordisp' are zero, but a virtual_inheritance pointer will be generated. - // We can generate correct code in this case. To prevent an incorrect call from - // ever being made, on MSVC6 we generate a warning, and call a function to - // make the program crash instantly. - typedef char ERROR_VC6CompilerBug[-100]; - return 0; - } + template + inline static GenericClass * xr_stdcall Convert(X *pthis, XFuncType function_to_bind, + GenericMemFuncType &bound_func) { + // There is an apalling but obscure compiler bug in MSVC6 and earlier: + // vtable_index and 'vtordisp' are always set to 0 in the + // unknown_inheritance case! + // This means that an incorrect function could be called!!! + // Compiling with the /vmg option leads to potentially incorrect code. + // This is probably the reason that the IDE has a user interface for specifying + // the /vmg option, but it is disabled - you can only specify /vmg on + // the command line. In VC1.5 and earlier, the compiler would ICE if it ever + // encountered this situation. + // It is OK to use the /vmg option if /vmm or /vms is specified. + + // Fortunately, the wrong function is only called in very obscure cases. + // It only occurs when a derived class overrides a virtual function declared + // in a virtual base class, and the member function + // points to the *Derived* version of that function. The problem can be + // completely averted in 100% of cases by using the *Base class* for the + // member fpointer. Ie, if you use the base class as an interface, you'll + // stay out of trouble. + // Occasionally, you might want to point directly to a derived class function + // that isn't an override of a base class. In this case, both vtable_index + // and 'vtordisp' are zero, but a virtual_inheritance pointer will be generated. + // We can generate correct code in this case. To prevent an incorrect call from + // ever being made, on MSVC6 we generate a warning, and call a function to + // make the program crash instantly. + typedef char ERROR_VC6CompilerBug[-100]; + return 0; + } }; @@ -476,42 +476,42 @@ struct SimplifyMemFunc template <> struct SimplifyMemFunc { - template - inline static GenericClass * xr_stdcall Convert(X *pthis, XFuncType function_to_bind, - GenericMemFuncType &bound_func) { - // The member function pointer is 16 bytes long. We can't use a normal cast, but - // we can use a union to do the conversion. - union { - XFuncType func; - // In VC++ and ICL, an unknown_inheritance member pointer - // is internally defined as: - struct { - GenericMemFuncType m_funcaddress; // points to the actual member function - int delta; // #bytes to be added to the 'this' pointer - int vtordisp; // #bytes to add to 'this' to find the vtable - int vtable_index; // or 0 if no virtual inheritance - } s; - } u; - // Check that the horrible_cast will work - typedef int ERROR_CantUsehorrible_cast[sizeof(XFuncType)==sizeof(u.s)? 1 : -1]; - u.func = function_to_bind; - bound_func = u.s.funcaddress; - int virtual_delta = 0; - if (u.s.vtable_index) { // Virtual inheritance is used - // First, get to the vtable. - // It is 'vtordisp' bytes from the start of the class. - const int * vtable = *reinterpret_cast( - reinterpret_cast(pthis) + u.s.vtordisp ); - - // 'vtable_index' tells us where in the table we should be looking. - virtual_delta = u.s.vtordisp + *reinterpret_cast( - reinterpret_cast(vtable) + u.s.vtable_index); - } - // The int at 'virtual_delta' gives us the amount to add to 'this'. + template + inline static GenericClass * xr_stdcall Convert(X *pthis, XFuncType function_to_bind, + GenericMemFuncType &bound_func) { + // The member function pointer is 16 bytes long. We can't use a normal cast, but + // we can use a union to do the conversion. + union { + XFuncType func; + // In VC++ and ICL, an unknown_inheritance member pointer + // is internally defined as: + struct { + GenericMemFuncType m_funcaddress; // points to the actual member function + int delta; // #bytes to be added to the 'this' pointer + int vtordisp; // #bytes to add to 'this' to find the vtable + int vtable_index; // or 0 if no virtual inheritance + } s; + } u; + // Check that the horrible_cast will work + typedef int ERROR_CantUsehorrible_cast[sizeof(XFuncType)==sizeof(u.s)? 1 : -1]; + u.func = function_to_bind; + bound_func = u.s.funcaddress; + int virtual_delta = 0; + if (u.s.vtable_index) { // Virtual inheritance is used + // First, get to the vtable. + // It is 'vtordisp' bytes from the start of the class. + const int * vtable = *reinterpret_cast( + reinterpret_cast(pthis) + u.s.vtordisp ); + + // 'vtable_index' tells us where in the table we should be looking. + virtual_delta = u.s.vtordisp + *reinterpret_cast( + reinterpret_cast(vtable) + u.s.vtable_index); + } + // The int at 'virtual_delta' gives us the amount to add to 'this'. // Finally we can add the three components together. Phew! return reinterpret_cast( - reinterpret_cast(pthis) + u.s.delta + virtual_delta); - }; + reinterpret_cast(pthis) + u.s.delta + virtual_delta); + }; }; #endif // MSVC 7 and greater @@ -520,9 +520,9 @@ struct SimplifyMemFunc } // namespace detail //////////////////////////////////////////////////////////////////////////////// -// Fast Delegates, part 2: +// Fast Delegates, part 2: // -// Define the delegate storage, and cope with static functions +// Define the delegate storage, and cope with static functions // //////////////////////////////////////////////////////////////////////////////// @@ -535,13 +535,13 @@ struct SimplifyMemFunc // Implementation: // There are two possible implementations: the Safe method and the Evil method. -// DelegateMemento - Safe version +// DelegateMemento - Safe version // // This implementation is standard-compliant, but a bit tricky. // A static function pointer is stored inside the class. // Here are the valid values: // +-- Static pointer --+--pThis --+-- pMemFunc-+-- Meaning------+ -// | 0 | 0 | 0 | Empty | +// | 0 | 0 | 0 | Empty | // | !=0 |(dontcare)| Invoker | Static function| // | 0 | !=0 | !=0* | Method call | // +--------------------+----------+------------+----------------+ @@ -551,7 +551,7 @@ struct SimplifyMemFunc // with a reference to the delegate itself. This complicates the = and == operators // for the delegate class. -// DelegateMemento - Evil version +// DelegateMemento - Evil version // // For compilers where data pointers are at least as big as code pointers, it is // possible to store the function pointer in the this pointer, using another @@ -567,92 +567,92 @@ struct SimplifyMemFunc class DelegateMemento { protected: - // the data is protected, not private, because many - // compilers have problems with template friends. - typedef void (detail::GenericClass::*GenericMemFuncType)(); // arbitrary MFP. - detail::GenericClass *m_pthis; - GenericMemFuncType m_pFunction; + // the data is protected, not private, because many + // compilers have problems with template friends. + typedef void (detail::GenericClass::*GenericMemFuncType)(); // arbitrary MFP. + detail::GenericClass *m_pthis; + GenericMemFuncType m_pFunction; #if !defined(FASTDELEGATE_USESTATICFUNCTIONHACK) - typedef void (xr_stdcall *GenericFuncPtr)(); // arbitrary code pointer - GenericFuncPtr m_pStaticFunction; + typedef void (xr_stdcall *GenericFuncPtr)(); // arbitrary code pointer + GenericFuncPtr m_pStaticFunction; #endif public: #if !defined(FASTDELEGATE_USESTATICFUNCTIONHACK) - DelegateMemento() : m_pthis(0), m_pFunction(0), m_pStaticFunction(0) {}; - void clear() { - m_pthis=0; m_pFunction=0; m_pStaticFunction=0; - } + DelegateMemento() : m_pthis(0), m_pFunction(0), m_pStaticFunction(0) {}; + void clear() { + m_pthis=0; m_pFunction=0; m_pStaticFunction=0; + } #else - DelegateMemento() : m_pthis(0), m_pFunction(0) {}; - void clear() { m_pthis=0; m_pFunction=0; } + DelegateMemento() : m_pthis(0), m_pFunction(0) {}; + void clear() { m_pthis=0; m_pFunction=0; } #endif public: #if !defined(FASTDELEGATE_USESTATICFUNCTIONHACK) - inline bool IsEqual (const DelegateMemento &x) const{ - // We have to cope with the static function pointers as a special case - if (m_pFunction!=x.m_pFunction) return false; - // the static function ptrs must either both be equal, or both be 0. - if (m_pStaticFunction!=x.m_pStaticFunction) return false; - if (m_pStaticFunction!=0) return m_pthis==x.m_pthis; - else return true; - } + inline bool IsEqual (const DelegateMemento &x) const{ + // We have to cope with the static function pointers as a special case + if (m_pFunction!=x.m_pFunction) return false; + // the static function ptrs must either both be equal, or both be 0. + if (m_pStaticFunction!=x.m_pStaticFunction) return false; + if (m_pStaticFunction!=0) return m_pthis==x.m_pthis; + else return true; + } #else // Evil Method - inline bool IsEqual (const DelegateMemento &x) const{ - return m_pthis==x.m_pthis && m_pFunction==x.m_pFunction; - } + inline bool IsEqual (const DelegateMemento &x) const{ + return m_pthis==x.m_pthis && m_pFunction==x.m_pFunction; + } #endif - // Provide a strict weak ordering for DelegateMementos. - inline bool IsLess(const DelegateMemento &right) const { - // deal with static function pointers first + // Provide a strict weak ordering for DelegateMementos. + inline bool IsLess(const DelegateMemento &right) const { + // deal with static function pointers first #if !defined(FASTDELEGATE_USESTATICFUNCTIONHACK) - if (m_pStaticFunction !=0 || right.m_pStaticFunction!=0) - return m_pStaticFunction < right.m_pStaticFunction; + if (m_pStaticFunction !=0 || right.m_pStaticFunction!=0) + return m_pStaticFunction < right.m_pStaticFunction; #endif - if (m_pthis !=right.m_pthis) return m_pthis < right.m_pthis; - // There are no ordering operators for member function pointers, - // but we can fake one by comparing each byte. The resulting ordering is - // arbitrary (and compiler-dependent), but it permits storage in ordered STL containers. - return memcmp(&m_pFunction, &right.m_pFunction, sizeof(m_pFunction)) < 0; - - } - // BUGFIX (Mar 2005): - // We can't just compare m_pFunction because on Metrowerks, - // m_pFunction can be zero even if the delegate is not empty! - inline bool operator ! () const // Is it bound to anything? - { return m_pthis==0 && m_pFunction==0; } - inline bool empty() const // Is it bound to anything? - { return m_pthis==0 && m_pFunction==0; } + if (m_pthis !=right.m_pthis) return m_pthis < right.m_pthis; + // There are no ordering operators for member function pointers, + // but we can fake one by comparing each byte. The resulting ordering is + // arbitrary (and compiler-dependent), but it permits storage in ordered STL containers. + return memcmp(&m_pFunction, &right.m_pFunction, sizeof(m_pFunction)) < 0; + + } + // BUGFIX (Mar 2005): + // We can't just compare m_pFunction because on Metrowerks, + // m_pFunction can be zero even if the delegate is not empty! + inline bool operator ! () const // Is it bound to anything? + { return m_pthis==0 && m_pFunction==0; } + inline bool empty() const // Is it bound to anything? + { return m_pthis==0 && m_pFunction==0; } public: - DelegateMemento & operator = (const DelegateMemento &right) { - SetMementoFrom(right); - return *this; - } - inline bool operator <(const DelegateMemento &right) { - return IsLess(right); - } - inline bool operator >(const DelegateMemento &right) { - return right.IsLess(*this); - } - DelegateMemento (const DelegateMemento &right) : - m_pFunction(right.m_pFunction), m_pthis(right.m_pthis) + DelegateMemento & operator = (const DelegateMemento &right) { + SetMementoFrom(right); + return *this; + } + inline bool operator <(const DelegateMemento &right) { + return IsLess(right); + } + inline bool operator >(const DelegateMemento &right) { + return right.IsLess(*this); + } + DelegateMemento (const DelegateMemento &right) : + m_pFunction(right.m_pFunction), m_pthis(right.m_pthis) #if !defined(FASTDELEGATE_USESTATICFUNCTIONHACK) - , m_pStaticFunction (right.m_pStaticFunction) + , m_pStaticFunction (right.m_pStaticFunction) #endif - {} + {} protected: - void SetMementoFrom(const DelegateMemento &right) { - m_pFunction = right.m_pFunction; - m_pthis = right.m_pthis; + void SetMementoFrom(const DelegateMemento &right) { + m_pFunction = right.m_pFunction; + m_pthis = right.m_pthis; #if !defined(FASTDELEGATE_USESTATICFUNCTIONHACK) - m_pStaticFunction = right.m_pStaticFunction; + m_pStaticFunction = right.m_pStaticFunction; #endif - } + } }; -// ClosurePtr<> +// ClosurePtr<> // // A private wrapper class that adds function signatures to DelegateMemento. // It's the class that does most of the actual work. @@ -672,43 +672,43 @@ namespace detail { template < class GenericMemFunc, class StaticFuncPtr, class UnvoidStaticFuncPtr> class ClosurePtr : public DelegateMemento { public: - // These functions are for setting the delegate to a member function. - - // Here's the clever bit: we convert an arbitrary member function into a - // standard form. XMemFunc should be a member function of class X, but I can't - // enforce that here. It needs to be enforced by the wrapper class. - template < class X, class XMemFunc > - inline void bindmemfunc(X *pthis, XMemFunc function_to_bind ) { - m_pthis = SimplifyMemFunc< sizeof(function_to_bind) > - ::Convert(pthis, function_to_bind, m_pFunction); + // These functions are for setting the delegate to a member function. + + // Here's the clever bit: we convert an arbitrary member function into a + // standard form. XMemFunc should be a member function of class X, but I can't + // enforce that here. It needs to be enforced by the wrapper class. + template < class X, class XMemFunc > + inline void bindmemfunc(X *pthis, XMemFunc function_to_bind ) { + m_pthis = SimplifyMemFunc< sizeof(function_to_bind) > + ::Convert(pthis, function_to_bind, m_pFunction); #if !defined(FASTDELEGATE_USESTATICFUNCTIONHACK) - m_pStaticFunction = 0; + m_pStaticFunction = 0; #endif - } - // For const member functions, we only need a const class pointer. - // Since we know that the member function is const, it's safe to - // remove the const qualifier from the 'this' pointer with a const_cast. - // VC6 has problems if we just overload 'bindmemfunc', so we give it a different name. - template < class X, class XMemFunc> - inline void bindconstmemfunc(const X *pthis, XMemFunc function_to_bind) { - m_pthis= SimplifyMemFunc< sizeof(function_to_bind) > - ::Convert(const_cast(pthis), function_to_bind, m_pFunction); + } + // For const member functions, we only need a const class pointer. + // Since we know that the member function is const, it's safe to + // remove the const qualifier from the 'this' pointer with a const_cast. + // VC6 has problems if we just overload 'bindmemfunc', so we give it a different name. + template < class X, class XMemFunc> + inline void bindconstmemfunc(const X *pthis, XMemFunc function_to_bind) { + m_pthis= SimplifyMemFunc< sizeof(function_to_bind) > + ::Convert(const_cast(pthis), function_to_bind, m_pFunction); #if !defined(FASTDELEGATE_USESTATICFUNCTIONHACK) - m_pStaticFunction = 0; + m_pStaticFunction = 0; #endif - } -#ifdef FASTDELEGATE_GCC_BUG_8271 // At present, GCC doesn't recognize constness of MFPs in templates - template < class X, class XMemFunc> - inline void bindmemfunc(const X *pthis, XMemFunc function_to_bind) { - bindconstmemfunc(pthis, function_to_bind); + } +#ifdef FASTDELEGATE_GCC_BUG_8271 // At present, GCC doesn't recognize constness of MFPs in templates + template < class X, class XMemFunc> + inline void bindmemfunc(const X *pthis, XMemFunc function_to_bind) { + bindconstmemfunc(pthis, function_to_bind); #if !defined(FASTDELEGATE_USESTATICFUNCTIONHACK) - m_pStaticFunction = 0; + m_pStaticFunction = 0; #endif - } + } #endif - // These functions are required for invoking the stored function - inline GenericClass *GetClosureThis() const { return m_pthis; } - inline GenericMemFunc GetClosureMemPtr() const { return reinterpret_cast(m_pFunction); } + // These functions are required for invoking the stored function + inline GenericClass *GetClosureThis() const { return m_pthis; } + inline GenericMemFunc GetClosureMemPtr() const { return reinterpret_cast(m_pFunction); } // There are a few ways of dealing with static function pointers. // There's a standard-compliant, but tricky method. @@ -718,43 +718,43 @@ class ClosurePtr : public DelegateMemento { #if !defined(FASTDELEGATE_USESTATICFUNCTIONHACK) -// ClosurePtr<> - Safe version +// ClosurePtr<> - Safe version // // This implementation is standard-compliant, but a bit tricky. // I store the function pointer inside the class, and the delegate then // points to itself. Whenever the delegate is copied, these self-references // must be transformed, and this complicates the = and == operators. public: - // The next two functions are for operator ==, =, and the copy constructor. - // We may need to convert the m_pthis pointers, so that - // they remain as self-references. - template< class DerivedClass > - inline void CopyFrom (DerivedClass *pParent, const DelegateMemento &x) { - SetMementoFrom(x); - if (m_pStaticFunction!=0) { - // transform self references... - m_pthis=reinterpret_cast(pParent); - } - } - // For static functions, the 'static_function_invoker' class in the parent - // will be called. The parent then needs to call GetStaticFunction() to find out - // the actual function to invoke. - template < class DerivedClass, class ParentInvokerSig > - inline void bindstaticfunc(DerivedClass *pParent, ParentInvokerSig static_function_invoker, - StaticFuncPtr function_to_bind ) { - if (function_to_bind==0) { // cope with assignment to 0 - m_pFunction=0; - } else { - bindmemfunc(pParent, static_function_invoker); + // The next two functions are for operator ==, =, and the copy constructor. + // We may need to convert the m_pthis pointers, so that + // they remain as self-references. + template< class DerivedClass > + inline void CopyFrom (DerivedClass *pParent, const DelegateMemento &x) { + SetMementoFrom(x); + if (m_pStaticFunction!=0) { + // transform self references... + m_pthis=reinterpret_cast(pParent); + } + } + // For static functions, the 'static_function_invoker' class in the parent + // will be called. The parent then needs to call GetStaticFunction() to find out + // the actual function to invoke. + template < class DerivedClass, class ParentInvokerSig > + inline void bindstaticfunc(DerivedClass *pParent, ParentInvokerSig static_function_invoker, + StaticFuncPtr function_to_bind ) { + if (function_to_bind==0) { // cope with assignment to 0 + m_pFunction=0; + } else { + bindmemfunc(pParent, static_function_invoker); } - m_pStaticFunction=reinterpret_cast(function_to_bind); - } - inline UnvoidStaticFuncPtr GetStaticFunction() const { - return reinterpret_cast(m_pStaticFunction); - } + m_pStaticFunction=reinterpret_cast(function_to_bind); + } + inline UnvoidStaticFuncPtr GetStaticFunction() const { + return reinterpret_cast(m_pStaticFunction); + } #else -// ClosurePtr<> - Evil version +// ClosurePtr<> - Evil version // // For compilers where data pointers are at least as big as code pointers, it is // possible to store the function pointer in the this pointer, using another @@ -764,65 +764,65 @@ class ClosurePtr : public DelegateMemento { // Note that the Sun C++ and MSVC documentation explicitly state that they // support static_cast between void * and function pointers. - template< class DerivedClass > - inline void CopyFrom (DerivedClass *pParent, const DelegateMemento &right) { - SetMementoFrom(right); - } - // For static functions, the 'static_function_invoker' class in the parent - // will be called. The parent then needs to call GetStaticFunction() to find out - // the actual function to invoke. - // ******** EVIL, EVIL CODE! ******* - template < class DerivedClass, class ParentInvokerSig> - inline void bindstaticfunc(DerivedClass *pParent, ParentInvokerSig static_function_invoker, - StaticFuncPtr function_to_bind) { - if (function_to_bind==0) { // cope with assignment to 0 - m_pFunction=0; - } else { - // We'll be ignoring the 'this' pointer, but we need to make sure we pass - // a valid value to bindmemfunc(). - bindmemfunc(pParent, static_function_invoker); + template< class DerivedClass > + inline void CopyFrom (DerivedClass *pParent, const DelegateMemento &right) { + SetMementoFrom(right); + } + // For static functions, the 'static_function_invoker' class in the parent + // will be called. The parent then needs to call GetStaticFunction() to find out + // the actual function to invoke. + // ******** EVIL, EVIL CODE! ******* + template < class DerivedClass, class ParentInvokerSig> + inline void bindstaticfunc(DerivedClass *pParent, ParentInvokerSig static_function_invoker, + StaticFuncPtr function_to_bind) { + if (function_to_bind==0) { // cope with assignment to 0 + m_pFunction=0; + } else { + // We'll be ignoring the 'this' pointer, but we need to make sure we pass + // a valid value to bindmemfunc(). + bindmemfunc(pParent, static_function_invoker); } - // WARNING! Evil hack. We store the function in the 'this' pointer! - // Ensure that there's a compilation failure if function pointers - // and data pointers have different sizes. - // If you get this error, you need to #undef FASTDELEGATE_USESTATICFUNCTIONHACK. - typedef int ERROR_CantUseEvilMethod[sizeof(GenericClass *)==sizeof(function_to_bind) ? 1 : -1]; - m_pthis = horrible_cast(function_to_bind); - // MSVC, SunC++ and DMC accept the following (non-standard) code: -// m_pthis = static_cast(static_cast(function_to_bind)); - // BCC32, Comeau and DMC accept this method. MSVC7.1 needs __int64 instead of long -// m_pthis = reinterpret_cast(reinterpret_cast(function_to_bind)); - } - // ******** EVIL, EVIL CODE! ******* - // This function will be called with an invalid 'this' pointer!! - // We're just returning the 'this' pointer, converted into - // a function pointer! - inline UnvoidStaticFuncPtr GetStaticFunction() const { - // Ensure that there's a compilation failure if function pointers - // and data pointers have different sizes. - // If you get this error, you need to #undef FASTDELEGATE_USESTATICFUNCTIONHACK. - typedef int ERROR_CantUseEvilMethod[sizeof(UnvoidStaticFuncPtr)==sizeof(this) ? 1 : -1]; - return horrible_cast(this); - } + // WARNING! Evil hack. We store the function in the 'this' pointer! + // Ensure that there's a compilation failure if function pointers + // and data pointers have different sizes. + // If you get this error, you need to #undef FASTDELEGATE_USESTATICFUNCTIONHACK. + typedef int ERROR_CantUseEvilMethod[sizeof(GenericClass *)==sizeof(function_to_bind) ? 1 : -1]; + m_pthis = horrible_cast(function_to_bind); + // MSVC, SunC++ and DMC accept the following (non-standard) code: +// m_pthis = static_cast(static_cast(function_to_bind)); + // BCC32, Comeau and DMC accept this method. MSVC7.1 needs __int64 instead of long +// m_pthis = reinterpret_cast(reinterpret_cast(function_to_bind)); + } + // ******** EVIL, EVIL CODE! ******* + // This function will be called with an invalid 'this' pointer!! + // We're just returning the 'this' pointer, converted into + // a function pointer! + inline UnvoidStaticFuncPtr GetStaticFunction() const { + // Ensure that there's a compilation failure if function pointers + // and data pointers have different sizes. + // If you get this error, you need to #undef FASTDELEGATE_USESTATICFUNCTIONHACK. + typedef int ERROR_CantUseEvilMethod[sizeof(UnvoidStaticFuncPtr)==sizeof(this) ? 1 : -1]; + return horrible_cast(this); + } #endif // !defined(FASTDELEGATE_USESTATICFUNCTIONHACK) - // Does the closure contain this static function? - inline bool IsEqualToStaticFuncPtr(StaticFuncPtr funcptr){ - if (funcptr==0) return empty(); - // For the Evil method, if it doesn't actually contain a static function, this will return an arbitrary - // value that is not equal to any valid function pointer. - else return funcptr==reinterpret_cast(GetStaticFunction()); - } + // Does the closure contain this static function? + inline bool IsEqualToStaticFuncPtr(StaticFuncPtr funcptr){ + if (funcptr==0) return empty(); + // For the Evil method, if it doesn't actually contain a static function, this will return an arbitrary + // value that is not equal to any valid function pointer. + else return funcptr==reinterpret_cast(GetStaticFunction()); + } }; } // namespace detail //////////////////////////////////////////////////////////////////////////////// -// Fast Delegates, part 3: +// Fast Delegates, part 3: // -// Wrapper classes to ensure type safety +// Wrapper classes to ensure type safety // //////////////////////////////////////////////////////////////////////////////// @@ -842,9 +842,9 @@ class ClosurePtr : public DelegateMemento { // This is the reason for the use of "implicit_cast(pthis)" in the code below. // If CDerivedClass is derived from CBaseClass, but doesn't override SimpleVirtualFunction, // without this trick you'd need to write: -// MyDelegate(static_cast(&d), &CDerivedClass::SimpleVirtualFunction); +// MyDelegate(static_cast(&d), &CDerivedClass::SimpleVirtualFunction); // but with the trick you can write -// MyDelegate(&d, &CDerivedClass::SimpleVirtualFunction); +// MyDelegate(&d, &CDerivedClass::SimpleVirtualFunction); // RetType is the type the compiler uses in compiling the template. For VC6, // it cannot be void. DesiredRetType is the real type which is returned from @@ -862,778 +862,778 @@ class ClosurePtr : public DelegateMemento { template class FastDelegate0 { private: - typedef typename detail::DefaultVoidToVoid::type DesiredRetType; - typedef DesiredRetType (xr_stdcall *StaticFunctionPtr)(); - typedef RetType (xr_stdcall *UnvoidStaticFunctionPtr)(); - typedef RetType (xr_stdcall detail::GenericClass::*GenericMemFn)(); - typedef detail::ClosurePtr ClosureType; - ClosureType m_Closure; + typedef typename detail::DefaultVoidToVoid::type DesiredRetType; + typedef DesiredRetType (xr_stdcall *StaticFunctionPtr)(); + typedef RetType (xr_stdcall *UnvoidStaticFunctionPtr)(); + typedef RetType (xr_stdcall detail::GenericClass::*GenericMemFn)(); + typedef detail::ClosurePtr ClosureType; + ClosureType m_Closure; public: - // Typedefs to aid generic programming - typedef FastDelegate0 type; - - // Construction and comparison functions - FastDelegate0() { clear(); } - FastDelegate0(const FastDelegate0 &x) { - m_Closure.CopyFrom(this, x.m_Closure); } - void operator = (const FastDelegate0 &x) { - m_Closure.CopyFrom(this, x.m_Closure); } - bool operator ==(const FastDelegate0 &x) const { - return m_Closure.IsEqual(x.m_Closure); } - bool operator !=(const FastDelegate0 &x) const { - return !m_Closure.IsEqual(x.m_Closure); } - bool operator <(const FastDelegate0 &x) const { - return m_Closure.IsLess(x.m_Closure); } - bool operator >(const FastDelegate0 &x) const { - return x.m_Closure.IsLess(m_Closure); } - // Binding to non-const member functions - template < class X, class Y > - FastDelegate0(Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)() ) { - m_Closure.bindmemfunc(detail::implicit_cast(pthis), function_to_bind); } - template < class X, class Y > - inline void bind(Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)()) { - m_Closure.bindmemfunc(detail::implicit_cast(pthis), function_to_bind); } - // Binding to const member functions. - template < class X, class Y > - FastDelegate0(const Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)() const) { - m_Closure.bindconstmemfunc(detail::implicit_cast(pthis), function_to_bind); } - template < class X, class Y > - inline void bind(const Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)() const) { - m_Closure.bindconstmemfunc(detail::implicit_cast(pthis), function_to_bind); } - // Static functions. We convert them into a member function call. - // This constructor also provides implicit conversion - FastDelegate0(DesiredRetType (xr_stdcall *function_to_bind)() ) { - bind(function_to_bind); } - // for efficiency, prevent creation of a temporary - void operator = (DesiredRetType (xr_stdcall *function_to_bind)() ) { - bind(function_to_bind); } - inline void bind(DesiredRetType (xr_stdcall *function_to_bind)()) { - m_Closure.bindstaticfunc(this, &FastDelegate0::InvokeStaticFunction, - function_to_bind); } - // Invoke the delegate - RetType operator() () const { - return (m_Closure.GetClosureThis()->*(m_Closure.GetClosureMemPtr()))(); } - // Implicit conversion to "bool" using the safe_bool idiom + // Typedefs to aid generic programming + typedef FastDelegate0 type; + + // Construction and comparison functions + FastDelegate0() { clear(); } + FastDelegate0(const FastDelegate0 &x) { + m_Closure.CopyFrom(this, x.m_Closure); } + void operator = (const FastDelegate0 &x) { + m_Closure.CopyFrom(this, x.m_Closure); } + bool operator ==(const FastDelegate0 &x) const { + return m_Closure.IsEqual(x.m_Closure); } + bool operator !=(const FastDelegate0 &x) const { + return !m_Closure.IsEqual(x.m_Closure); } + bool operator <(const FastDelegate0 &x) const { + return m_Closure.IsLess(x.m_Closure); } + bool operator >(const FastDelegate0 &x) const { + return x.m_Closure.IsLess(m_Closure); } + // Binding to non-const member functions + template < class X, class Y > + FastDelegate0(Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)() ) { + m_Closure.bindmemfunc(detail::implicit_cast(pthis), function_to_bind); } + template < class X, class Y > + inline void bind(Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)()) { + m_Closure.bindmemfunc(detail::implicit_cast(pthis), function_to_bind); } + // Binding to const member functions. + template < class X, class Y > + FastDelegate0(const Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)() const) { + m_Closure.bindconstmemfunc(detail::implicit_cast(pthis), function_to_bind); } + template < class X, class Y > + inline void bind(const Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)() const) { + m_Closure.bindconstmemfunc(detail::implicit_cast(pthis), function_to_bind); } + // Static functions. We convert them into a member function call. + // This constructor also provides implicit conversion + FastDelegate0(DesiredRetType (xr_stdcall *function_to_bind)() ) { + bind(function_to_bind); } + // for efficiency, prevent creation of a temporary + void operator = (DesiredRetType (xr_stdcall *function_to_bind)() ) { + bind(function_to_bind); } + inline void bind(DesiredRetType (xr_stdcall *function_to_bind)()) { + m_Closure.bindstaticfunc(this, &FastDelegate0::InvokeStaticFunction, + function_to_bind); } + // Invoke the delegate + RetType operator() () const { + return (m_Closure.GetClosureThis()->*(m_Closure.GetClosureMemPtr()))(); } + // Implicit conversion to "bool" using the safe_bool idiom private: - typedef struct SafeBoolStruct { - int a_data_pointer_to_this_is_0_on_buggy_compilers; - StaticFunctionPtr m_nonzero; - } UselessTypedef; - typedef StaticFunctionPtr SafeBoolStruct::*unspecified_bool_type; + typedef struct SafeBoolStruct { + int a_data_pointer_to_this_is_0_on_buggy_compilers; + StaticFunctionPtr m_nonzero; + } UselessTypedef; + typedef StaticFunctionPtr SafeBoolStruct::*unspecified_bool_type; public: - operator unspecified_bool_type() const { - return empty()? 0: &SafeBoolStruct::m_nonzero; - } - // necessary to allow ==0 to work despite the safe_bool idiom - inline bool operator==(StaticFunctionPtr funcptr) { - return m_Closure.IsEqualToStaticFuncPtr(funcptr); } - inline bool operator!=(StaticFunctionPtr funcptr) { - return !m_Closure.IsEqualToStaticFuncPtr(funcptr); } - inline bool operator ! () const { // Is it bound to anything? - return !m_Closure; } - inline bool empty() const { - return !m_Closure; } - void clear() { m_Closure.clear();} - // Conversion to and from the DelegateMemento storage class - const DelegateMemento & GetMemento() { return m_Closure; } - void SetMemento(const DelegateMemento &any) { m_Closure.CopyFrom(this, any); } - -private: // Invoker for static functions - RetType xr_stdcall InvokeStaticFunction() const { - return (*(m_Closure.GetStaticFunction()))(); } + operator unspecified_bool_type() const { + return empty()? 0: &SafeBoolStruct::m_nonzero; + } + // necessary to allow ==0 to work despite the safe_bool idiom + inline bool operator==(StaticFunctionPtr funcptr) { + return m_Closure.IsEqualToStaticFuncPtr(funcptr); } + inline bool operator!=(StaticFunctionPtr funcptr) { + return !m_Closure.IsEqualToStaticFuncPtr(funcptr); } + inline bool operator ! () const { // Is it bound to anything? + return !m_Closure; } + inline bool empty() const { + return !m_Closure; } + void clear() { m_Closure.clear();} + // Conversion to and from the DelegateMemento storage class + const DelegateMemento & GetMemento() { return m_Closure; } + void SetMemento(const DelegateMemento &any) { m_Closure.CopyFrom(this, any); } + +private: // Invoker for static functions + RetType xr_stdcall InvokeStaticFunction() const { + return (*(m_Closure.GetStaticFunction()))(); } }; //N=1 template class FastDelegate1 { private: - typedef typename detail::DefaultVoidToVoid::type DesiredRetType; - typedef DesiredRetType (xr_stdcall *StaticFunctionPtr)(Param1 p1); - typedef RetType (xr_stdcall *UnvoidStaticFunctionPtr)(Param1 p1); - typedef RetType (xr_stdcall detail::GenericClass::*GenericMemFn)(Param1 p1); - typedef detail::ClosurePtr ClosureType; - ClosureType m_Closure; + typedef typename detail::DefaultVoidToVoid::type DesiredRetType; + typedef DesiredRetType (xr_stdcall *StaticFunctionPtr)(Param1 p1); + typedef RetType (xr_stdcall *UnvoidStaticFunctionPtr)(Param1 p1); + typedef RetType (xr_stdcall detail::GenericClass::*GenericMemFn)(Param1 p1); + typedef detail::ClosurePtr ClosureType; + ClosureType m_Closure; public: - // Typedefs to aid generic programming - typedef FastDelegate1 type; - - // Construction and comparison functions - FastDelegate1() { clear(); } - FastDelegate1(const FastDelegate1 &x) { - m_Closure.CopyFrom(this, x.m_Closure); } - void operator = (const FastDelegate1 &x) { - m_Closure.CopyFrom(this, x.m_Closure); } - bool operator ==(const FastDelegate1 &x) const { - return m_Closure.IsEqual(x.m_Closure); } - bool operator !=(const FastDelegate1 &x) const { - return !m_Closure.IsEqual(x.m_Closure); } - bool operator <(const FastDelegate1 &x) const { - return m_Closure.IsLess(x.m_Closure); } - bool operator >(const FastDelegate1 &x) const { - return x.m_Closure.IsLess(m_Closure); } - // Binding to non-const member functions - template < class X, class Y > - FastDelegate1(Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1) ) { - m_Closure.bindmemfunc(detail::implicit_cast(pthis), function_to_bind); } - template < class X, class Y > - inline void bind(Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1)) { - m_Closure.bindmemfunc(detail::implicit_cast(pthis), function_to_bind); } - // Binding to const member functions. - template < class X, class Y > - FastDelegate1(const Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1) const) { - m_Closure.bindconstmemfunc(detail::implicit_cast(pthis), function_to_bind); } - template < class X, class Y > - inline void bind(const Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1) const) { - m_Closure.bindconstmemfunc(detail::implicit_cast(pthis), function_to_bind); } - // Static functions. We convert them into a member function call. - // This constructor also provides implicit conversion - FastDelegate1(DesiredRetType (xr_stdcall *function_to_bind)(Param1 p1) ) { - bind(function_to_bind); } - // for efficiency, prevent creation of a temporary - void operator = (DesiredRetType (xr_stdcall *function_to_bind)(Param1 p1) ) { - bind(function_to_bind); } - inline void bind(DesiredRetType (xr_stdcall *function_to_bind)(Param1 p1)) { - m_Closure.bindstaticfunc(this, &FastDelegate1::InvokeStaticFunction, - function_to_bind); } - // Invoke the delegate - RetType operator() (Param1 p1) const { - return (m_Closure.GetClosureThis()->*(m_Closure.GetClosureMemPtr()))(p1); } - // Implicit conversion to "bool" using the safe_bool idiom + // Typedefs to aid generic programming + typedef FastDelegate1 type; + + // Construction and comparison functions + FastDelegate1() { clear(); } + FastDelegate1(const FastDelegate1 &x) { + m_Closure.CopyFrom(this, x.m_Closure); } + void operator = (const FastDelegate1 &x) { + m_Closure.CopyFrom(this, x.m_Closure); } + bool operator ==(const FastDelegate1 &x) const { + return m_Closure.IsEqual(x.m_Closure); } + bool operator !=(const FastDelegate1 &x) const { + return !m_Closure.IsEqual(x.m_Closure); } + bool operator <(const FastDelegate1 &x) const { + return m_Closure.IsLess(x.m_Closure); } + bool operator >(const FastDelegate1 &x) const { + return x.m_Closure.IsLess(m_Closure); } + // Binding to non-const member functions + template < class X, class Y > + FastDelegate1(Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1) ) { + m_Closure.bindmemfunc(detail::implicit_cast(pthis), function_to_bind); } + template < class X, class Y > + inline void bind(Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1)) { + m_Closure.bindmemfunc(detail::implicit_cast(pthis), function_to_bind); } + // Binding to const member functions. + template < class X, class Y > + FastDelegate1(const Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1) const) { + m_Closure.bindconstmemfunc(detail::implicit_cast(pthis), function_to_bind); } + template < class X, class Y > + inline void bind(const Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1) const) { + m_Closure.bindconstmemfunc(detail::implicit_cast(pthis), function_to_bind); } + // Static functions. We convert them into a member function call. + // This constructor also provides implicit conversion + FastDelegate1(DesiredRetType (xr_stdcall *function_to_bind)(Param1 p1) ) { + bind(function_to_bind); } + // for efficiency, prevent creation of a temporary + void operator = (DesiredRetType (xr_stdcall *function_to_bind)(Param1 p1) ) { + bind(function_to_bind); } + inline void bind(DesiredRetType (xr_stdcall *function_to_bind)(Param1 p1)) { + m_Closure.bindstaticfunc(this, &FastDelegate1::InvokeStaticFunction, + function_to_bind); } + // Invoke the delegate + RetType operator() (Param1 p1) const { + return (m_Closure.GetClosureThis()->*(m_Closure.GetClosureMemPtr()))(p1); } + // Implicit conversion to "bool" using the safe_bool idiom private: - typedef struct SafeBoolStruct { - int a_data_pointer_to_this_is_0_on_buggy_compilers; - StaticFunctionPtr m_nonzero; - } UselessTypedef; - typedef StaticFunctionPtr SafeBoolStruct::*unspecified_bool_type; + typedef struct SafeBoolStruct { + int a_data_pointer_to_this_is_0_on_buggy_compilers; + StaticFunctionPtr m_nonzero; + } UselessTypedef; + typedef StaticFunctionPtr SafeBoolStruct::*unspecified_bool_type; public: - operator unspecified_bool_type() const { - return empty()? 0: &SafeBoolStruct::m_nonzero; - } - // necessary to allow ==0 to work despite the safe_bool idiom - inline bool operator==(StaticFunctionPtr funcptr) { - return m_Closure.IsEqualToStaticFuncPtr(funcptr); } - inline bool operator!=(StaticFunctionPtr funcptr) { - return !m_Closure.IsEqualToStaticFuncPtr(funcptr); } - inline bool operator ! () const { // Is it bound to anything? - return !m_Closure; } - inline bool empty() const { - return !m_Closure; } - void clear() { m_Closure.clear();} - // Conversion to and from the DelegateMemento storage class - const DelegateMemento & GetMemento() { return m_Closure; } - void SetMemento(const DelegateMemento &any) { m_Closure.CopyFrom(this, any); } - -private: // Invoker for static functions - // this -- parameter, function - // p1 - function, parameter - RetType xr_stdcall InvokeStaticFunction(Param1 p1) const { - return (*(m_Closure.GetStaticFunction()))(p1); } + operator unspecified_bool_type() const { + return empty()? 0: &SafeBoolStruct::m_nonzero; + } + // necessary to allow ==0 to work despite the safe_bool idiom + inline bool operator==(StaticFunctionPtr funcptr) { + return m_Closure.IsEqualToStaticFuncPtr(funcptr); } + inline bool operator!=(StaticFunctionPtr funcptr) { + return !m_Closure.IsEqualToStaticFuncPtr(funcptr); } + inline bool operator ! () const { // Is it bound to anything? + return !m_Closure; } + inline bool empty() const { + return !m_Closure; } + void clear() { m_Closure.clear();} + // Conversion to and from the DelegateMemento storage class + const DelegateMemento & GetMemento() { return m_Closure; } + void SetMemento(const DelegateMemento &any) { m_Closure.CopyFrom(this, any); } + +private: // Invoker for static functions + // this -- parameter, function + // p1 - function, parameter + RetType xr_stdcall InvokeStaticFunction(Param1 p1) const { + return (*(m_Closure.GetStaticFunction()))(p1); } }; //N=2 template class FastDelegate2 { private: - typedef typename detail::DefaultVoidToVoid::type DesiredRetType; - typedef DesiredRetType (xr_stdcall *StaticFunctionPtr)(Param1 p1, Param2 p2); - typedef RetType (xr_stdcall *UnvoidStaticFunctionPtr)(Param1 p1, Param2 p2); - typedef RetType (xr_stdcall detail::GenericClass::*GenericMemFn)(Param1 p1, Param2 p2); - typedef detail::ClosurePtr ClosureType; - ClosureType m_Closure; + typedef typename detail::DefaultVoidToVoid::type DesiredRetType; + typedef DesiredRetType (xr_stdcall *StaticFunctionPtr)(Param1 p1, Param2 p2); + typedef RetType (xr_stdcall *UnvoidStaticFunctionPtr)(Param1 p1, Param2 p2); + typedef RetType (xr_stdcall detail::GenericClass::*GenericMemFn)(Param1 p1, Param2 p2); + typedef detail::ClosurePtr ClosureType; + ClosureType m_Closure; public: - // Typedefs to aid generic programming - typedef FastDelegate2 type; - - // Construction and comparison functions - FastDelegate2() { clear(); } - FastDelegate2(const FastDelegate2 &x) { - m_Closure.CopyFrom(this, x.m_Closure); } - void operator = (const FastDelegate2 &x) { - m_Closure.CopyFrom(this, x.m_Closure); } - bool operator ==(const FastDelegate2 &x) const { - return m_Closure.IsEqual(x.m_Closure); } - bool operator !=(const FastDelegate2 &x) const { - return !m_Closure.IsEqual(x.m_Closure); } - bool operator <(const FastDelegate2 &x) const { - return m_Closure.IsLess(x.m_Closure); } - bool operator >(const FastDelegate2 &x) const { - return x.m_Closure.IsLess(m_Closure); } - // Binding to non-const member functions - template < class X, class Y > - FastDelegate2(Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2) ) { - m_Closure.bindmemfunc(detail::implicit_cast(pthis), function_to_bind); } - template < class X, class Y > - inline void bind(Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2)) { - m_Closure.bindmemfunc(detail::implicit_cast(pthis), function_to_bind); } - // Binding to const member functions. - template < class X, class Y > - FastDelegate2(const Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2) const) { - m_Closure.bindconstmemfunc(detail::implicit_cast(pthis), function_to_bind); } - template < class X, class Y > - inline void bind(const Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2) const) { - m_Closure.bindconstmemfunc(detail::implicit_cast(pthis), function_to_bind); } - // Static functions. We convert them into a member function call. - // This constructor also provides implicit conversion - FastDelegate2(DesiredRetType (xr_stdcall *function_to_bind)(Param1 p1, Param2 p2) ) { - bind(function_to_bind); } - // for efficiency, prevent creation of a temporary - void operator = (DesiredRetType (xr_stdcall *function_to_bind)(Param1 p1, Param2 p2) ) { - bind(function_to_bind); } - inline void bind(DesiredRetType (xr_stdcall *function_to_bind)(Param1 p1, Param2 p2)) { - m_Closure.bindstaticfunc(this, &FastDelegate2::InvokeStaticFunction, - function_to_bind); } - // Invoke the delegate - RetType operator() (Param1 p1, Param2 p2) const { - return (m_Closure.GetClosureThis()->*(m_Closure.GetClosureMemPtr()))(p1, p2); } - // Implicit conversion to "bool" using the safe_bool idiom + // Typedefs to aid generic programming + typedef FastDelegate2 type; + + // Construction and comparison functions + FastDelegate2() { clear(); } + FastDelegate2(const FastDelegate2 &x) { + m_Closure.CopyFrom(this, x.m_Closure); } + void operator = (const FastDelegate2 &x) { + m_Closure.CopyFrom(this, x.m_Closure); } + bool operator ==(const FastDelegate2 &x) const { + return m_Closure.IsEqual(x.m_Closure); } + bool operator !=(const FastDelegate2 &x) const { + return !m_Closure.IsEqual(x.m_Closure); } + bool operator <(const FastDelegate2 &x) const { + return m_Closure.IsLess(x.m_Closure); } + bool operator >(const FastDelegate2 &x) const { + return x.m_Closure.IsLess(m_Closure); } + // Binding to non-const member functions + template < class X, class Y > + FastDelegate2(Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2) ) { + m_Closure.bindmemfunc(detail::implicit_cast(pthis), function_to_bind); } + template < class X, class Y > + inline void bind(Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2)) { + m_Closure.bindmemfunc(detail::implicit_cast(pthis), function_to_bind); } + // Binding to const member functions. + template < class X, class Y > + FastDelegate2(const Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2) const) { + m_Closure.bindconstmemfunc(detail::implicit_cast(pthis), function_to_bind); } + template < class X, class Y > + inline void bind(const Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2) const) { + m_Closure.bindconstmemfunc(detail::implicit_cast(pthis), function_to_bind); } + // Static functions. We convert them into a member function call. + // This constructor also provides implicit conversion + FastDelegate2(DesiredRetType (xr_stdcall *function_to_bind)(Param1 p1, Param2 p2) ) { + bind(function_to_bind); } + // for efficiency, prevent creation of a temporary + void operator = (DesiredRetType (xr_stdcall *function_to_bind)(Param1 p1, Param2 p2) ) { + bind(function_to_bind); } + inline void bind(DesiredRetType (xr_stdcall *function_to_bind)(Param1 p1, Param2 p2)) { + m_Closure.bindstaticfunc(this, &FastDelegate2::InvokeStaticFunction, + function_to_bind); } + // Invoke the delegate + RetType operator() (Param1 p1, Param2 p2) const { + return (m_Closure.GetClosureThis()->*(m_Closure.GetClosureMemPtr()))(p1, p2); } + // Implicit conversion to "bool" using the safe_bool idiom private: - typedef struct SafeBoolStruct { - int a_data_pointer_to_this_is_0_on_buggy_compilers; - StaticFunctionPtr m_nonzero; - } UselessTypedef; - typedef StaticFunctionPtr SafeBoolStruct::*unspecified_bool_type; + typedef struct SafeBoolStruct { + int a_data_pointer_to_this_is_0_on_buggy_compilers; + StaticFunctionPtr m_nonzero; + } UselessTypedef; + typedef StaticFunctionPtr SafeBoolStruct::*unspecified_bool_type; public: - operator unspecified_bool_type() const { - return empty()? 0: &SafeBoolStruct::m_nonzero; - } - // necessary to allow ==0 to work despite the safe_bool idiom - inline bool operator==(StaticFunctionPtr funcptr) { - return m_Closure.IsEqualToStaticFuncPtr(funcptr); } - inline bool operator!=(StaticFunctionPtr funcptr) { - return !m_Closure.IsEqualToStaticFuncPtr(funcptr); } - inline bool operator ! () const { // Is it bound to anything? - return !m_Closure; } - inline bool empty() const { - return !m_Closure; } - void clear() { m_Closure.clear();} - // Conversion to and from the DelegateMemento storage class - const DelegateMemento & GetMemento() { return m_Closure; } - void SetMemento(const DelegateMemento &any) { m_Closure.CopyFrom(this, any); } - -private: // Invoker for static functions - RetType xr_stdcall InvokeStaticFunction(Param1 p1, Param2 p2) const { - return (*(m_Closure.GetStaticFunction()))(p1, p2); } + operator unspecified_bool_type() const { + return empty()? 0: &SafeBoolStruct::m_nonzero; + } + // necessary to allow ==0 to work despite the safe_bool idiom + inline bool operator==(StaticFunctionPtr funcptr) { + return m_Closure.IsEqualToStaticFuncPtr(funcptr); } + inline bool operator!=(StaticFunctionPtr funcptr) { + return !m_Closure.IsEqualToStaticFuncPtr(funcptr); } + inline bool operator ! () const { // Is it bound to anything? + return !m_Closure; } + inline bool empty() const { + return !m_Closure; } + void clear() { m_Closure.clear();} + // Conversion to and from the DelegateMemento storage class + const DelegateMemento & GetMemento() { return m_Closure; } + void SetMemento(const DelegateMemento &any) { m_Closure.CopyFrom(this, any); } + +private: // Invoker for static functions + RetType xr_stdcall InvokeStaticFunction(Param1 p1, Param2 p2) const { + return (*(m_Closure.GetStaticFunction()))(p1, p2); } }; //N=3 template class FastDelegate3 { private: - typedef typename detail::DefaultVoidToVoid::type DesiredRetType; - typedef DesiredRetType (xr_stdcall *StaticFunctionPtr)(Param1 p1, Param2 p2, Param3 p3); - typedef RetType (xr_stdcall *UnvoidStaticFunctionPtr)(Param1 p1, Param2 p2, Param3 p3); - typedef RetType (xr_stdcall detail::GenericClass::*GenericMemFn)(Param1 p1, Param2 p2, Param3 p3); - typedef detail::ClosurePtr ClosureType; - ClosureType m_Closure; + typedef typename detail::DefaultVoidToVoid::type DesiredRetType; + typedef DesiredRetType (xr_stdcall *StaticFunctionPtr)(Param1 p1, Param2 p2, Param3 p3); + typedef RetType (xr_stdcall *UnvoidStaticFunctionPtr)(Param1 p1, Param2 p2, Param3 p3); + typedef RetType (xr_stdcall detail::GenericClass::*GenericMemFn)(Param1 p1, Param2 p2, Param3 p3); + typedef detail::ClosurePtr ClosureType; + ClosureType m_Closure; public: - // Typedefs to aid generic programming - typedef FastDelegate3 type; - - // Construction and comparison functions - FastDelegate3() { clear(); } - FastDelegate3(const FastDelegate3 &x) { - m_Closure.CopyFrom(this, x.m_Closure); } - void operator = (const FastDelegate3 &x) { - m_Closure.CopyFrom(this, x.m_Closure); } - bool operator ==(const FastDelegate3 &x) const { - return m_Closure.IsEqual(x.m_Closure); } - bool operator !=(const FastDelegate3 &x) const { - return !m_Closure.IsEqual(x.m_Closure); } - bool operator <(const FastDelegate3 &x) const { - return m_Closure.IsLess(x.m_Closure); } - bool operator >(const FastDelegate3 &x) const { - return x.m_Closure.IsLess(m_Closure); } - // Binding to non-const member functions - template < class X, class Y > - FastDelegate3(Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3) ) { - m_Closure.bindmemfunc(detail::implicit_cast(pthis), function_to_bind); } - template < class X, class Y > - inline void bind(Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3)) { - m_Closure.bindmemfunc(detail::implicit_cast(pthis), function_to_bind); } - // Binding to const member functions. - template < class X, class Y > - FastDelegate3(const Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3) const) { - m_Closure.bindconstmemfunc(detail::implicit_cast(pthis), function_to_bind); } - template < class X, class Y > - inline void bind(const Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3) const) { - m_Closure.bindconstmemfunc(detail::implicit_cast(pthis), function_to_bind); } - // Static functions. We convert them into a member function call. - // This constructor also provides implicit conversion - FastDelegate3(DesiredRetType (xr_stdcall *function_to_bind)(Param1 p1, Param2 p2, Param3 p3) ) { - bind(function_to_bind); } - // for efficiency, prevent creation of a temporary - void operator = (DesiredRetType (xr_stdcall *function_to_bind)(Param1 p1, Param2 p2, Param3 p3) ) { - bind(function_to_bind); } - inline void bind(DesiredRetType (xr_stdcall *function_to_bind)(Param1 p1, Param2 p2, Param3 p3)) { - m_Closure.bindstaticfunc(this, &FastDelegate3::InvokeStaticFunction, - function_to_bind); } - // Invoke the delegate - RetType operator() (Param1 p1, Param2 p2, Param3 p3) const { - return (m_Closure.GetClosureThis()->*(m_Closure.GetClosureMemPtr()))(p1, p2, p3); } - // Implicit conversion to "bool" using the safe_bool idiom + // Typedefs to aid generic programming + typedef FastDelegate3 type; + + // Construction and comparison functions + FastDelegate3() { clear(); } + FastDelegate3(const FastDelegate3 &x) { + m_Closure.CopyFrom(this, x.m_Closure); } + void operator = (const FastDelegate3 &x) { + m_Closure.CopyFrom(this, x.m_Closure); } + bool operator ==(const FastDelegate3 &x) const { + return m_Closure.IsEqual(x.m_Closure); } + bool operator !=(const FastDelegate3 &x) const { + return !m_Closure.IsEqual(x.m_Closure); } + bool operator <(const FastDelegate3 &x) const { + return m_Closure.IsLess(x.m_Closure); } + bool operator >(const FastDelegate3 &x) const { + return x.m_Closure.IsLess(m_Closure); } + // Binding to non-const member functions + template < class X, class Y > + FastDelegate3(Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3) ) { + m_Closure.bindmemfunc(detail::implicit_cast(pthis), function_to_bind); } + template < class X, class Y > + inline void bind(Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3)) { + m_Closure.bindmemfunc(detail::implicit_cast(pthis), function_to_bind); } + // Binding to const member functions. + template < class X, class Y > + FastDelegate3(const Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3) const) { + m_Closure.bindconstmemfunc(detail::implicit_cast(pthis), function_to_bind); } + template < class X, class Y > + inline void bind(const Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3) const) { + m_Closure.bindconstmemfunc(detail::implicit_cast(pthis), function_to_bind); } + // Static functions. We convert them into a member function call. + // This constructor also provides implicit conversion + FastDelegate3(DesiredRetType (xr_stdcall *function_to_bind)(Param1 p1, Param2 p2, Param3 p3) ) { + bind(function_to_bind); } + // for efficiency, prevent creation of a temporary + void operator = (DesiredRetType (xr_stdcall *function_to_bind)(Param1 p1, Param2 p2, Param3 p3) ) { + bind(function_to_bind); } + inline void bind(DesiredRetType (xr_stdcall *function_to_bind)(Param1 p1, Param2 p2, Param3 p3)) { + m_Closure.bindstaticfunc(this, &FastDelegate3::InvokeStaticFunction, + function_to_bind); } + // Invoke the delegate + RetType operator() (Param1 p1, Param2 p2, Param3 p3) const { + return (m_Closure.GetClosureThis()->*(m_Closure.GetClosureMemPtr()))(p1, p2, p3); } + // Implicit conversion to "bool" using the safe_bool idiom private: - typedef struct SafeBoolStruct { - int a_data_pointer_to_this_is_0_on_buggy_compilers; - StaticFunctionPtr m_nonzero; - } UselessTypedef; - typedef StaticFunctionPtr SafeBoolStruct::*unspecified_bool_type; + typedef struct SafeBoolStruct { + int a_data_pointer_to_this_is_0_on_buggy_compilers; + StaticFunctionPtr m_nonzero; + } UselessTypedef; + typedef StaticFunctionPtr SafeBoolStruct::*unspecified_bool_type; public: - operator unspecified_bool_type() const { - return empty()? 0: &SafeBoolStruct::m_nonzero; - } - // necessary to allow ==0 to work despite the safe_bool idiom - inline bool operator==(StaticFunctionPtr funcptr) { - return m_Closure.IsEqualToStaticFuncPtr(funcptr); } - inline bool operator!=(StaticFunctionPtr funcptr) { - return !m_Closure.IsEqualToStaticFuncPtr(funcptr); } - inline bool operator ! () const { // Is it bound to anything? - return !m_Closure; } - inline bool empty() const { - return !m_Closure; } - void clear() { m_Closure.clear();} - // Conversion to and from the DelegateMemento storage class - const DelegateMemento & GetMemento() { return m_Closure; } - void SetMemento(const DelegateMemento &any) { m_Closure.CopyFrom(this, any); } - -private: // Invoker for static functions - RetType xr_stdcall InvokeStaticFunction(Param1 p1, Param2 p2, Param3 p3) const { - return (*(m_Closure.GetStaticFunction()))(p1, p2, p3); } + operator unspecified_bool_type() const { + return empty()? 0: &SafeBoolStruct::m_nonzero; + } + // necessary to allow ==0 to work despite the safe_bool idiom + inline bool operator==(StaticFunctionPtr funcptr) { + return m_Closure.IsEqualToStaticFuncPtr(funcptr); } + inline bool operator!=(StaticFunctionPtr funcptr) { + return !m_Closure.IsEqualToStaticFuncPtr(funcptr); } + inline bool operator ! () const { // Is it bound to anything? + return !m_Closure; } + inline bool empty() const { + return !m_Closure; } + void clear() { m_Closure.clear();} + // Conversion to and from the DelegateMemento storage class + const DelegateMemento & GetMemento() { return m_Closure; } + void SetMemento(const DelegateMemento &any) { m_Closure.CopyFrom(this, any); } + +private: // Invoker for static functions + RetType xr_stdcall InvokeStaticFunction(Param1 p1, Param2 p2, Param3 p3) const { + return (*(m_Closure.GetStaticFunction()))(p1, p2, p3); } }; //N=4 template class FastDelegate4 { private: - typedef typename detail::DefaultVoidToVoid::type DesiredRetType; - typedef DesiredRetType (xr_stdcall *StaticFunctionPtr)(Param1 p1, Param2 p2, Param3 p3, Param4 p4); - typedef RetType (xr_stdcall *UnvoidStaticFunctionPtr)(Param1 p1, Param2 p2, Param3 p3, Param4 p4); - typedef RetType (xr_stdcall detail::GenericClass::*GenericMemFn)(Param1 p1, Param2 p2, Param3 p3, Param4 p4); - typedef detail::ClosurePtr ClosureType; - ClosureType m_Closure; + typedef typename detail::DefaultVoidToVoid::type DesiredRetType; + typedef DesiredRetType (xr_stdcall *StaticFunctionPtr)(Param1 p1, Param2 p2, Param3 p3, Param4 p4); + typedef RetType (xr_stdcall *UnvoidStaticFunctionPtr)(Param1 p1, Param2 p2, Param3 p3, Param4 p4); + typedef RetType (xr_stdcall detail::GenericClass::*GenericMemFn)(Param1 p1, Param2 p2, Param3 p3, Param4 p4); + typedef detail::ClosurePtr ClosureType; + ClosureType m_Closure; public: - // Typedefs to aid generic programming - typedef FastDelegate4 type; - - // Construction and comparison functions - FastDelegate4() { clear(); } - FastDelegate4(const FastDelegate4 &x) { - m_Closure.CopyFrom(this, x.m_Closure); } - void operator = (const FastDelegate4 &x) { - m_Closure.CopyFrom(this, x.m_Closure); } - bool operator ==(const FastDelegate4 &x) const { - return m_Closure.IsEqual(x.m_Closure); } - bool operator !=(const FastDelegate4 &x) const { - return !m_Closure.IsEqual(x.m_Closure); } - bool operator <(const FastDelegate4 &x) const { - return m_Closure.IsLess(x.m_Closure); } - bool operator >(const FastDelegate4 &x) const { - return x.m_Closure.IsLess(m_Closure); } - // Binding to non-const member functions - template < class X, class Y > - FastDelegate4(Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4) ) { - m_Closure.bindmemfunc(detail::implicit_cast(pthis), function_to_bind); } - template < class X, class Y > - inline void bind(Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4)) { - m_Closure.bindmemfunc(detail::implicit_cast(pthis), function_to_bind); } - // Binding to const member functions. - template < class X, class Y > - FastDelegate4(const Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4) const) { - m_Closure.bindconstmemfunc(detail::implicit_cast(pthis), function_to_bind); } - template < class X, class Y > - inline void bind(const Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4) const) { - m_Closure.bindconstmemfunc(detail::implicit_cast(pthis), function_to_bind); } - // Static functions. We convert them into a member function call. - // This constructor also provides implicit conversion - FastDelegate4(DesiredRetType (xr_stdcall *function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4) ) { - bind(function_to_bind); } - // for efficiency, prevent creation of a temporary - void operator = (DesiredRetType (xr_stdcall *function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4) ) { - bind(function_to_bind); } - inline void bind(DesiredRetType (xr_stdcall *function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4)) { - m_Closure.bindstaticfunc(this, &FastDelegate4::InvokeStaticFunction, - function_to_bind); } - // Invoke the delegate - RetType operator() (Param1 p1, Param2 p2, Param3 p3, Param4 p4) const { - return (m_Closure.GetClosureThis()->*(m_Closure.GetClosureMemPtr()))(p1, p2, p3, p4); } - // Implicit conversion to "bool" using the safe_bool idiom + // Typedefs to aid generic programming + typedef FastDelegate4 type; + + // Construction and comparison functions + FastDelegate4() { clear(); } + FastDelegate4(const FastDelegate4 &x) { + m_Closure.CopyFrom(this, x.m_Closure); } + void operator = (const FastDelegate4 &x) { + m_Closure.CopyFrom(this, x.m_Closure); } + bool operator ==(const FastDelegate4 &x) const { + return m_Closure.IsEqual(x.m_Closure); } + bool operator !=(const FastDelegate4 &x) const { + return !m_Closure.IsEqual(x.m_Closure); } + bool operator <(const FastDelegate4 &x) const { + return m_Closure.IsLess(x.m_Closure); } + bool operator >(const FastDelegate4 &x) const { + return x.m_Closure.IsLess(m_Closure); } + // Binding to non-const member functions + template < class X, class Y > + FastDelegate4(Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4) ) { + m_Closure.bindmemfunc(detail::implicit_cast(pthis), function_to_bind); } + template < class X, class Y > + inline void bind(Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4)) { + m_Closure.bindmemfunc(detail::implicit_cast(pthis), function_to_bind); } + // Binding to const member functions. + template < class X, class Y > + FastDelegate4(const Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4) const) { + m_Closure.bindconstmemfunc(detail::implicit_cast(pthis), function_to_bind); } + template < class X, class Y > + inline void bind(const Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4) const) { + m_Closure.bindconstmemfunc(detail::implicit_cast(pthis), function_to_bind); } + // Static functions. We convert them into a member function call. + // This constructor also provides implicit conversion + FastDelegate4(DesiredRetType (xr_stdcall *function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4) ) { + bind(function_to_bind); } + // for efficiency, prevent creation of a temporary + void operator = (DesiredRetType (xr_stdcall *function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4) ) { + bind(function_to_bind); } + inline void bind(DesiredRetType (xr_stdcall *function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4)) { + m_Closure.bindstaticfunc(this, &FastDelegate4::InvokeStaticFunction, + function_to_bind); } + // Invoke the delegate + RetType operator() (Param1 p1, Param2 p2, Param3 p3, Param4 p4) const { + return (m_Closure.GetClosureThis()->*(m_Closure.GetClosureMemPtr()))(p1, p2, p3, p4); } + // Implicit conversion to "bool" using the safe_bool idiom private: - typedef struct SafeBoolStruct { - int a_data_pointer_to_this_is_0_on_buggy_compilers; - StaticFunctionPtr m_nonzero; - } UselessTypedef; - typedef StaticFunctionPtr SafeBoolStruct::*unspecified_bool_type; + typedef struct SafeBoolStruct { + int a_data_pointer_to_this_is_0_on_buggy_compilers; + StaticFunctionPtr m_nonzero; + } UselessTypedef; + typedef StaticFunctionPtr SafeBoolStruct::*unspecified_bool_type; public: - operator unspecified_bool_type() const { - return empty()? 0: &SafeBoolStruct::m_nonzero; - } - // necessary to allow ==0 to work despite the safe_bool idiom - inline bool operator==(StaticFunctionPtr funcptr) { - return m_Closure.IsEqualToStaticFuncPtr(funcptr); } - inline bool operator!=(StaticFunctionPtr funcptr) { - return !m_Closure.IsEqualToStaticFuncPtr(funcptr); } - inline bool operator ! () const { // Is it bound to anything? - return !m_Closure; } - inline bool empty() const { - return !m_Closure; } - void clear() { m_Closure.clear();} - // Conversion to and from the DelegateMemento storage class - const DelegateMemento & GetMemento() { return m_Closure; } - void SetMemento(const DelegateMemento &any) { m_Closure.CopyFrom(this, any); } - -private: // Invoker for static functions - RetType xr_stdcall InvokeStaticFunction(Param1 p1, Param2 p2, Param3 p3, Param4 p4) const { - return (*(m_Closure.GetStaticFunction()))(p1, p2, p3, p4); } + operator unspecified_bool_type() const { + return empty()? 0: &SafeBoolStruct::m_nonzero; + } + // necessary to allow ==0 to work despite the safe_bool idiom + inline bool operator==(StaticFunctionPtr funcptr) { + return m_Closure.IsEqualToStaticFuncPtr(funcptr); } + inline bool operator!=(StaticFunctionPtr funcptr) { + return !m_Closure.IsEqualToStaticFuncPtr(funcptr); } + inline bool operator ! () const { // Is it bound to anything? + return !m_Closure; } + inline bool empty() const { + return !m_Closure; } + void clear() { m_Closure.clear();} + // Conversion to and from the DelegateMemento storage class + const DelegateMemento & GetMemento() { return m_Closure; } + void SetMemento(const DelegateMemento &any) { m_Closure.CopyFrom(this, any); } + +private: // Invoker for static functions + RetType xr_stdcall InvokeStaticFunction(Param1 p1, Param2 p2, Param3 p3, Param4 p4) const { + return (*(m_Closure.GetStaticFunction()))(p1, p2, p3, p4); } }; //N=5 template class FastDelegate5 { private: - typedef typename detail::DefaultVoidToVoid::type DesiredRetType; - typedef DesiredRetType (xr_stdcall *StaticFunctionPtr)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5); - typedef RetType (xr_stdcall *UnvoidStaticFunctionPtr)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5); - typedef RetType (xr_stdcall detail::GenericClass::*GenericMemFn)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5); - typedef detail::ClosurePtr ClosureType; - ClosureType m_Closure; + typedef typename detail::DefaultVoidToVoid::type DesiredRetType; + typedef DesiredRetType (xr_stdcall *StaticFunctionPtr)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5); + typedef RetType (xr_stdcall *UnvoidStaticFunctionPtr)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5); + typedef RetType (xr_stdcall detail::GenericClass::*GenericMemFn)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5); + typedef detail::ClosurePtr ClosureType; + ClosureType m_Closure; public: - // Typedefs to aid generic programming - typedef FastDelegate5 type; - - // Construction and comparison functions - FastDelegate5() { clear(); } - FastDelegate5(const FastDelegate5 &x) { - m_Closure.CopyFrom(this, x.m_Closure); } - void operator = (const FastDelegate5 &x) { - m_Closure.CopyFrom(this, x.m_Closure); } - bool operator ==(const FastDelegate5 &x) const { - return m_Closure.IsEqual(x.m_Closure); } - bool operator !=(const FastDelegate5 &x) const { - return !m_Closure.IsEqual(x.m_Closure); } - bool operator <(const FastDelegate5 &x) const { - return m_Closure.IsLess(x.m_Closure); } - bool operator >(const FastDelegate5 &x) const { - return x.m_Closure.IsLess(m_Closure); } - // Binding to non-const member functions - template < class X, class Y > - FastDelegate5(Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5) ) { - m_Closure.bindmemfunc(detail::implicit_cast(pthis), function_to_bind); } - template < class X, class Y > - inline void bind(Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5)) { - m_Closure.bindmemfunc(detail::implicit_cast(pthis), function_to_bind); } - // Binding to const member functions. - template < class X, class Y > - FastDelegate5(const Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5) const) { - m_Closure.bindconstmemfunc(detail::implicit_cast(pthis), function_to_bind); } - template < class X, class Y > - inline void bind(const Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5) const) { - m_Closure.bindconstmemfunc(detail::implicit_cast(pthis), function_to_bind); } - // Static functions. We convert them into a member function call. - // This constructor also provides implicit conversion - FastDelegate5(DesiredRetType (xr_stdcall *function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5) ) { - bind(function_to_bind); } - // for efficiency, prevent creation of a temporary - void operator = (DesiredRetType (xr_stdcall *function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5) ) { - bind(function_to_bind); } - inline void bind(DesiredRetType (xr_stdcall *function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5)) { - m_Closure.bindstaticfunc(this, &FastDelegate5::InvokeStaticFunction, - function_to_bind); } - // Invoke the delegate - RetType operator() (Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5) const { - return (m_Closure.GetClosureThis()->*(m_Closure.GetClosureMemPtr()))(p1, p2, p3, p4, p5); } - // Implicit conversion to "bool" using the safe_bool idiom + // Typedefs to aid generic programming + typedef FastDelegate5 type; + + // Construction and comparison functions + FastDelegate5() { clear(); } + FastDelegate5(const FastDelegate5 &x) { + m_Closure.CopyFrom(this, x.m_Closure); } + void operator = (const FastDelegate5 &x) { + m_Closure.CopyFrom(this, x.m_Closure); } + bool operator ==(const FastDelegate5 &x) const { + return m_Closure.IsEqual(x.m_Closure); } + bool operator !=(const FastDelegate5 &x) const { + return !m_Closure.IsEqual(x.m_Closure); } + bool operator <(const FastDelegate5 &x) const { + return m_Closure.IsLess(x.m_Closure); } + bool operator >(const FastDelegate5 &x) const { + return x.m_Closure.IsLess(m_Closure); } + // Binding to non-const member functions + template < class X, class Y > + FastDelegate5(Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5) ) { + m_Closure.bindmemfunc(detail::implicit_cast(pthis), function_to_bind); } + template < class X, class Y > + inline void bind(Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5)) { + m_Closure.bindmemfunc(detail::implicit_cast(pthis), function_to_bind); } + // Binding to const member functions. + template < class X, class Y > + FastDelegate5(const Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5) const) { + m_Closure.bindconstmemfunc(detail::implicit_cast(pthis), function_to_bind); } + template < class X, class Y > + inline void bind(const Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5) const) { + m_Closure.bindconstmemfunc(detail::implicit_cast(pthis), function_to_bind); } + // Static functions. We convert them into a member function call. + // This constructor also provides implicit conversion + FastDelegate5(DesiredRetType (xr_stdcall *function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5) ) { + bind(function_to_bind); } + // for efficiency, prevent creation of a temporary + void operator = (DesiredRetType (xr_stdcall *function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5) ) { + bind(function_to_bind); } + inline void bind(DesiredRetType (xr_stdcall *function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5)) { + m_Closure.bindstaticfunc(this, &FastDelegate5::InvokeStaticFunction, + function_to_bind); } + // Invoke the delegate + RetType operator() (Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5) const { + return (m_Closure.GetClosureThis()->*(m_Closure.GetClosureMemPtr()))(p1, p2, p3, p4, p5); } + // Implicit conversion to "bool" using the safe_bool idiom private: - typedef struct SafeBoolStruct { - int a_data_pointer_to_this_is_0_on_buggy_compilers; - StaticFunctionPtr m_nonzero; - } UselessTypedef; - typedef StaticFunctionPtr SafeBoolStruct::*unspecified_bool_type; + typedef struct SafeBoolStruct { + int a_data_pointer_to_this_is_0_on_buggy_compilers; + StaticFunctionPtr m_nonzero; + } UselessTypedef; + typedef StaticFunctionPtr SafeBoolStruct::*unspecified_bool_type; public: - operator unspecified_bool_type() const { - return empty()? 0: &SafeBoolStruct::m_nonzero; - } - // necessary to allow ==0 to work despite the safe_bool idiom - inline bool operator==(StaticFunctionPtr funcptr) { - return m_Closure.IsEqualToStaticFuncPtr(funcptr); } - inline bool operator!=(StaticFunctionPtr funcptr) { - return !m_Closure.IsEqualToStaticFuncPtr(funcptr); } - inline bool operator ! () const { // Is it bound to anything? - return !m_Closure; } - inline bool empty() const { - return !m_Closure; } - void clear() { m_Closure.clear();} - // Conversion to and from the DelegateMemento storage class - const DelegateMemento & GetMemento() { return m_Closure; } - void SetMemento(const DelegateMemento &any) { m_Closure.CopyFrom(this, any); } - -private: // Invoker for static functions - RetType xr_stdcall InvokeStaticFunction(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5) const { - return (*(m_Closure.GetStaticFunction()))(p1, p2, p3, p4, p5); } + operator unspecified_bool_type() const { + return empty()? 0: &SafeBoolStruct::m_nonzero; + } + // necessary to allow ==0 to work despite the safe_bool idiom + inline bool operator==(StaticFunctionPtr funcptr) { + return m_Closure.IsEqualToStaticFuncPtr(funcptr); } + inline bool operator!=(StaticFunctionPtr funcptr) { + return !m_Closure.IsEqualToStaticFuncPtr(funcptr); } + inline bool operator ! () const { // Is it bound to anything? + return !m_Closure; } + inline bool empty() const { + return !m_Closure; } + void clear() { m_Closure.clear();} + // Conversion to and from the DelegateMemento storage class + const DelegateMemento & GetMemento() { return m_Closure; } + void SetMemento(const DelegateMemento &any) { m_Closure.CopyFrom(this, any); } + +private: // Invoker for static functions + RetType xr_stdcall InvokeStaticFunction(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5) const { + return (*(m_Closure.GetStaticFunction()))(p1, p2, p3, p4, p5); } }; //N=6 template class FastDelegate6 { private: - typedef typename detail::DefaultVoidToVoid::type DesiredRetType; - typedef DesiredRetType (xr_stdcall *StaticFunctionPtr)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6); - typedef RetType (xr_stdcall *UnvoidStaticFunctionPtr)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6); - typedef RetType (xr_stdcall detail::GenericClass::*GenericMemFn)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6); - typedef detail::ClosurePtr ClosureType; - ClosureType m_Closure; + typedef typename detail::DefaultVoidToVoid::type DesiredRetType; + typedef DesiredRetType (xr_stdcall *StaticFunctionPtr)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6); + typedef RetType (xr_stdcall *UnvoidStaticFunctionPtr)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6); + typedef RetType (xr_stdcall detail::GenericClass::*GenericMemFn)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6); + typedef detail::ClosurePtr ClosureType; + ClosureType m_Closure; public: - // Typedefs to aid generic programming - typedef FastDelegate6 type; - - // Construction and comparison functions - FastDelegate6() { clear(); } - FastDelegate6(const FastDelegate6 &x) { - m_Closure.CopyFrom(this, x.m_Closure); } - void operator = (const FastDelegate6 &x) { - m_Closure.CopyFrom(this, x.m_Closure); } - bool operator ==(const FastDelegate6 &x) const { - return m_Closure.IsEqual(x.m_Closure); } - bool operator !=(const FastDelegate6 &x) const { - return !m_Closure.IsEqual(x.m_Closure); } - bool operator <(const FastDelegate6 &x) const { - return m_Closure.IsLess(x.m_Closure); } - bool operator >(const FastDelegate6 &x) const { - return x.m_Closure.IsLess(m_Closure); } - // Binding to non-const member functions - template < class X, class Y > - FastDelegate6(Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6) ) { - m_Closure.bindmemfunc(detail::implicit_cast(pthis), function_to_bind); } - template < class X, class Y > - inline void bind(Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6)) { - m_Closure.bindmemfunc(detail::implicit_cast(pthis), function_to_bind); } - // Binding to const member functions. - template < class X, class Y > - FastDelegate6(const Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6) const) { - m_Closure.bindconstmemfunc(detail::implicit_cast(pthis), function_to_bind); } - template < class X, class Y > - inline void bind(const Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6) const) { - m_Closure.bindconstmemfunc(detail::implicit_cast(pthis), function_to_bind); } - // Static functions. We convert them into a member function call. - // This constructor also provides implicit conversion - FastDelegate6(DesiredRetType (xr_stdcall *function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6) ) { - bind(function_to_bind); } - // for efficiency, prevent creation of a temporary - void operator = (DesiredRetType (xr_stdcall *function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6) ) { - bind(function_to_bind); } - inline void bind(DesiredRetType (xr_stdcall *function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6)) { - m_Closure.bindstaticfunc(this, &FastDelegate6::InvokeStaticFunction, - function_to_bind); } - // Invoke the delegate - RetType operator() (Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6) const { - return (m_Closure.GetClosureThis()->*(m_Closure.GetClosureMemPtr()))(p1, p2, p3, p4, p5, p6); } - // Implicit conversion to "bool" using the safe_bool idiom + // Typedefs to aid generic programming + typedef FastDelegate6 type; + + // Construction and comparison functions + FastDelegate6() { clear(); } + FastDelegate6(const FastDelegate6 &x) { + m_Closure.CopyFrom(this, x.m_Closure); } + void operator = (const FastDelegate6 &x) { + m_Closure.CopyFrom(this, x.m_Closure); } + bool operator ==(const FastDelegate6 &x) const { + return m_Closure.IsEqual(x.m_Closure); } + bool operator !=(const FastDelegate6 &x) const { + return !m_Closure.IsEqual(x.m_Closure); } + bool operator <(const FastDelegate6 &x) const { + return m_Closure.IsLess(x.m_Closure); } + bool operator >(const FastDelegate6 &x) const { + return x.m_Closure.IsLess(m_Closure); } + // Binding to non-const member functions + template < class X, class Y > + FastDelegate6(Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6) ) { + m_Closure.bindmemfunc(detail::implicit_cast(pthis), function_to_bind); } + template < class X, class Y > + inline void bind(Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6)) { + m_Closure.bindmemfunc(detail::implicit_cast(pthis), function_to_bind); } + // Binding to const member functions. + template < class X, class Y > + FastDelegate6(const Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6) const) { + m_Closure.bindconstmemfunc(detail::implicit_cast(pthis), function_to_bind); } + template < class X, class Y > + inline void bind(const Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6) const) { + m_Closure.bindconstmemfunc(detail::implicit_cast(pthis), function_to_bind); } + // Static functions. We convert them into a member function call. + // This constructor also provides implicit conversion + FastDelegate6(DesiredRetType (xr_stdcall *function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6) ) { + bind(function_to_bind); } + // for efficiency, prevent creation of a temporary + void operator = (DesiredRetType (xr_stdcall *function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6) ) { + bind(function_to_bind); } + inline void bind(DesiredRetType (xr_stdcall *function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6)) { + m_Closure.bindstaticfunc(this, &FastDelegate6::InvokeStaticFunction, + function_to_bind); } + // Invoke the delegate + RetType operator() (Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6) const { + return (m_Closure.GetClosureThis()->*(m_Closure.GetClosureMemPtr()))(p1, p2, p3, p4, p5, p6); } + // Implicit conversion to "bool" using the safe_bool idiom private: - typedef struct SafeBoolStruct { - int a_data_pointer_to_this_is_0_on_buggy_compilers; - StaticFunctionPtr m_nonzero; - } UselessTypedef; - typedef StaticFunctionPtr SafeBoolStruct::*unspecified_bool_type; + typedef struct SafeBoolStruct { + int a_data_pointer_to_this_is_0_on_buggy_compilers; + StaticFunctionPtr m_nonzero; + } UselessTypedef; + typedef StaticFunctionPtr SafeBoolStruct::*unspecified_bool_type; public: - operator unspecified_bool_type() const { - return empty()? 0: &SafeBoolStruct::m_nonzero; - } - // necessary to allow ==0 to work despite the safe_bool idiom - inline bool operator==(StaticFunctionPtr funcptr) { - return m_Closure.IsEqualToStaticFuncPtr(funcptr); } - inline bool operator!=(StaticFunctionPtr funcptr) { - return !m_Closure.IsEqualToStaticFuncPtr(funcptr); } - inline bool operator ! () const { // Is it bound to anything? - return !m_Closure; } - inline bool empty() const { - return !m_Closure; } - void clear() { m_Closure.clear();} - // Conversion to and from the DelegateMemento storage class - const DelegateMemento & GetMemento() { return m_Closure; } - void SetMemento(const DelegateMemento &any) { m_Closure.CopyFrom(this, any); } - -private: // Invoker for static functions - RetType xr_stdcall InvokeStaticFunction(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6) const { - return (*(m_Closure.GetStaticFunction()))(p1, p2, p3, p4, p5, p6); } + operator unspecified_bool_type() const { + return empty()? 0: &SafeBoolStruct::m_nonzero; + } + // necessary to allow ==0 to work despite the safe_bool idiom + inline bool operator==(StaticFunctionPtr funcptr) { + return m_Closure.IsEqualToStaticFuncPtr(funcptr); } + inline bool operator!=(StaticFunctionPtr funcptr) { + return !m_Closure.IsEqualToStaticFuncPtr(funcptr); } + inline bool operator ! () const { // Is it bound to anything? + return !m_Closure; } + inline bool empty() const { + return !m_Closure; } + void clear() { m_Closure.clear();} + // Conversion to and from the DelegateMemento storage class + const DelegateMemento & GetMemento() { return m_Closure; } + void SetMemento(const DelegateMemento &any) { m_Closure.CopyFrom(this, any); } + +private: // Invoker for static functions + RetType xr_stdcall InvokeStaticFunction(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6) const { + return (*(m_Closure.GetStaticFunction()))(p1, p2, p3, p4, p5, p6); } }; //N=7 template class FastDelegate7 { private: - typedef typename detail::DefaultVoidToVoid::type DesiredRetType; - typedef DesiredRetType (xr_stdcall *StaticFunctionPtr)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7); - typedef RetType (xr_stdcall *UnvoidStaticFunctionPtr)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7); - typedef RetType (xr_stdcall detail::GenericClass::*GenericMemFn)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7); - typedef detail::ClosurePtr ClosureType; - ClosureType m_Closure; + typedef typename detail::DefaultVoidToVoid::type DesiredRetType; + typedef DesiredRetType (xr_stdcall *StaticFunctionPtr)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7); + typedef RetType (xr_stdcall *UnvoidStaticFunctionPtr)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7); + typedef RetType (xr_stdcall detail::GenericClass::*GenericMemFn)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7); + typedef detail::ClosurePtr ClosureType; + ClosureType m_Closure; public: - // Typedefs to aid generic programming - typedef FastDelegate7 type; - - // Construction and comparison functions - FastDelegate7() { clear(); } - FastDelegate7(const FastDelegate7 &x) { - m_Closure.CopyFrom(this, x.m_Closure); } - void operator = (const FastDelegate7 &x) { - m_Closure.CopyFrom(this, x.m_Closure); } - bool operator ==(const FastDelegate7 &x) const { - return m_Closure.IsEqual(x.m_Closure); } - bool operator !=(const FastDelegate7 &x) const { - return !m_Closure.IsEqual(x.m_Closure); } - bool operator <(const FastDelegate7 &x) const { - return m_Closure.IsLess(x.m_Closure); } - bool operator >(const FastDelegate7 &x) const { - return x.m_Closure.IsLess(m_Closure); } - // Binding to non-const member functions - template < class X, class Y > - FastDelegate7(Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7) ) { - m_Closure.bindmemfunc(detail::implicit_cast(pthis), function_to_bind); } - template < class X, class Y > - inline void bind(Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7)) { - m_Closure.bindmemfunc(detail::implicit_cast(pthis), function_to_bind); } - // Binding to const member functions. - template < class X, class Y > - FastDelegate7(const Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7) const) { - m_Closure.bindconstmemfunc(detail::implicit_cast(pthis), function_to_bind); } - template < class X, class Y > - inline void bind(const Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7) const) { - m_Closure.bindconstmemfunc(detail::implicit_cast(pthis), function_to_bind); } - // Static functions. We convert them into a member function call. - // This constructor also provides implicit conversion - FastDelegate7(DesiredRetType (xr_stdcall *function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7) ) { - bind(function_to_bind); } - // for efficiency, prevent creation of a temporary - void operator = (DesiredRetType (xr_stdcall *function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7) ) { - bind(function_to_bind); } - inline void bind(DesiredRetType (xr_stdcall *function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7)) { - m_Closure.bindstaticfunc(this, &FastDelegate7::InvokeStaticFunction, - function_to_bind); } - // Invoke the delegate - RetType operator() (Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7) const { - return (m_Closure.GetClosureThis()->*(m_Closure.GetClosureMemPtr()))(p1, p2, p3, p4, p5, p6, p7); } - // Implicit conversion to "bool" using the safe_bool idiom + // Typedefs to aid generic programming + typedef FastDelegate7 type; + + // Construction and comparison functions + FastDelegate7() { clear(); } + FastDelegate7(const FastDelegate7 &x) { + m_Closure.CopyFrom(this, x.m_Closure); } + void operator = (const FastDelegate7 &x) { + m_Closure.CopyFrom(this, x.m_Closure); } + bool operator ==(const FastDelegate7 &x) const { + return m_Closure.IsEqual(x.m_Closure); } + bool operator !=(const FastDelegate7 &x) const { + return !m_Closure.IsEqual(x.m_Closure); } + bool operator <(const FastDelegate7 &x) const { + return m_Closure.IsLess(x.m_Closure); } + bool operator >(const FastDelegate7 &x) const { + return x.m_Closure.IsLess(m_Closure); } + // Binding to non-const member functions + template < class X, class Y > + FastDelegate7(Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7) ) { + m_Closure.bindmemfunc(detail::implicit_cast(pthis), function_to_bind); } + template < class X, class Y > + inline void bind(Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7)) { + m_Closure.bindmemfunc(detail::implicit_cast(pthis), function_to_bind); } + // Binding to const member functions. + template < class X, class Y > + FastDelegate7(const Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7) const) { + m_Closure.bindconstmemfunc(detail::implicit_cast(pthis), function_to_bind); } + template < class X, class Y > + inline void bind(const Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7) const) { + m_Closure.bindconstmemfunc(detail::implicit_cast(pthis), function_to_bind); } + // Static functions. We convert them into a member function call. + // This constructor also provides implicit conversion + FastDelegate7(DesiredRetType (xr_stdcall *function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7) ) { + bind(function_to_bind); } + // for efficiency, prevent creation of a temporary + void operator = (DesiredRetType (xr_stdcall *function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7) ) { + bind(function_to_bind); } + inline void bind(DesiredRetType (xr_stdcall *function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7)) { + m_Closure.bindstaticfunc(this, &FastDelegate7::InvokeStaticFunction, + function_to_bind); } + // Invoke the delegate + RetType operator() (Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7) const { + return (m_Closure.GetClosureThis()->*(m_Closure.GetClosureMemPtr()))(p1, p2, p3, p4, p5, p6, p7); } + // Implicit conversion to "bool" using the safe_bool idiom private: - typedef struct SafeBoolStruct { - int a_data_pointer_to_this_is_0_on_buggy_compilers; - StaticFunctionPtr m_nonzero; - } UselessTypedef; - typedef StaticFunctionPtr SafeBoolStruct::*unspecified_bool_type; + typedef struct SafeBoolStruct { + int a_data_pointer_to_this_is_0_on_buggy_compilers; + StaticFunctionPtr m_nonzero; + } UselessTypedef; + typedef StaticFunctionPtr SafeBoolStruct::*unspecified_bool_type; public: - operator unspecified_bool_type() const { - return empty()? 0: &SafeBoolStruct::m_nonzero; - } - // necessary to allow ==0 to work despite the safe_bool idiom - inline bool operator==(StaticFunctionPtr funcptr) { - return m_Closure.IsEqualToStaticFuncPtr(funcptr); } - inline bool operator!=(StaticFunctionPtr funcptr) { - return !m_Closure.IsEqualToStaticFuncPtr(funcptr); } - inline bool operator ! () const { // Is it bound to anything? - return !m_Closure; } - inline bool empty() const { - return !m_Closure; } - void clear() { m_Closure.clear();} - // Conversion to and from the DelegateMemento storage class - const DelegateMemento & GetMemento() { return m_Closure; } - void SetMemento(const DelegateMemento &any) { m_Closure.CopyFrom(this, any); } - -private: // Invoker for static functions - RetType xr_stdcall InvokeStaticFunction(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7) const { - return (*(m_Closure.GetStaticFunction()))(p1, p2, p3, p4, p5, p6, p7); } + operator unspecified_bool_type() const { + return empty()? 0: &SafeBoolStruct::m_nonzero; + } + // necessary to allow ==0 to work despite the safe_bool idiom + inline bool operator==(StaticFunctionPtr funcptr) { + return m_Closure.IsEqualToStaticFuncPtr(funcptr); } + inline bool operator!=(StaticFunctionPtr funcptr) { + return !m_Closure.IsEqualToStaticFuncPtr(funcptr); } + inline bool operator ! () const { // Is it bound to anything? + return !m_Closure; } + inline bool empty() const { + return !m_Closure; } + void clear() { m_Closure.clear();} + // Conversion to and from the DelegateMemento storage class + const DelegateMemento & GetMemento() { return m_Closure; } + void SetMemento(const DelegateMemento &any) { m_Closure.CopyFrom(this, any); } + +private: // Invoker for static functions + RetType xr_stdcall InvokeStaticFunction(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7) const { + return (*(m_Closure.GetStaticFunction()))(p1, p2, p3, p4, p5, p6, p7); } }; //N=8 template class FastDelegate8 { private: - typedef typename detail::DefaultVoidToVoid::type DesiredRetType; - typedef DesiredRetType (xr_stdcall *StaticFunctionPtr)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8); - typedef RetType (xr_stdcall *UnvoidStaticFunctionPtr)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8); - typedef RetType (xr_stdcall detail::GenericClass::*GenericMemFn)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8); - typedef detail::ClosurePtr ClosureType; - ClosureType m_Closure; + typedef typename detail::DefaultVoidToVoid::type DesiredRetType; + typedef DesiredRetType (xr_stdcall *StaticFunctionPtr)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8); + typedef RetType (xr_stdcall *UnvoidStaticFunctionPtr)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8); + typedef RetType (xr_stdcall detail::GenericClass::*GenericMemFn)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8); + typedef detail::ClosurePtr ClosureType; + ClosureType m_Closure; public: - // Typedefs to aid generic programming - typedef FastDelegate8 type; - - // Construction and comparison functions - FastDelegate8() { clear(); } - FastDelegate8(const FastDelegate8 &x) { - m_Closure.CopyFrom(this, x.m_Closure); } - void operator = (const FastDelegate8 &x) { - m_Closure.CopyFrom(this, x.m_Closure); } - bool operator ==(const FastDelegate8 &x) const { - return m_Closure.IsEqual(x.m_Closure); } - bool operator !=(const FastDelegate8 &x) const { - return !m_Closure.IsEqual(x.m_Closure); } - bool operator <(const FastDelegate8 &x) const { - return m_Closure.IsLess(x.m_Closure); } - bool operator >(const FastDelegate8 &x) const { - return x.m_Closure.IsLess(m_Closure); } - // Binding to non-const member functions - template < class X, class Y > - FastDelegate8(Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8) ) { - m_Closure.bindmemfunc(detail::implicit_cast(pthis), function_to_bind); } - template < class X, class Y > - inline void bind(Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8)) { - m_Closure.bindmemfunc(detail::implicit_cast(pthis), function_to_bind); } - // Binding to const member functions. - template < class X, class Y > - FastDelegate8(const Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8) const) { - m_Closure.bindconstmemfunc(detail::implicit_cast(pthis), function_to_bind); } - template < class X, class Y > - inline void bind(const Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8) const) { - m_Closure.bindconstmemfunc(detail::implicit_cast(pthis), function_to_bind); } - // Static functions. We convert them into a member function call. - // This constructor also provides implicit conversion - FastDelegate8(DesiredRetType (xr_stdcall *function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8) ) { - bind(function_to_bind); } - // for efficiency, prevent creation of a temporary - void operator = (DesiredRetType (xr_stdcall *function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8) ) { - bind(function_to_bind); } - inline void bind(DesiredRetType (xr_stdcall *function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8)) { - m_Closure.bindstaticfunc(this, &FastDelegate8::InvokeStaticFunction, - function_to_bind); } - // Invoke the delegate - RetType operator() (Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8) const { - return (m_Closure.GetClosureThis()->*(m_Closure.GetClosureMemPtr()))(p1, p2, p3, p4, p5, p6, p7, p8); } - // Implicit conversion to "bool" using the safe_bool idiom + // Typedefs to aid generic programming + typedef FastDelegate8 type; + + // Construction and comparison functions + FastDelegate8() { clear(); } + FastDelegate8(const FastDelegate8 &x) { + m_Closure.CopyFrom(this, x.m_Closure); } + void operator = (const FastDelegate8 &x) { + m_Closure.CopyFrom(this, x.m_Closure); } + bool operator ==(const FastDelegate8 &x) const { + return m_Closure.IsEqual(x.m_Closure); } + bool operator !=(const FastDelegate8 &x) const { + return !m_Closure.IsEqual(x.m_Closure); } + bool operator <(const FastDelegate8 &x) const { + return m_Closure.IsLess(x.m_Closure); } + bool operator >(const FastDelegate8 &x) const { + return x.m_Closure.IsLess(m_Closure); } + // Binding to non-const member functions + template < class X, class Y > + FastDelegate8(Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8) ) { + m_Closure.bindmemfunc(detail::implicit_cast(pthis), function_to_bind); } + template < class X, class Y > + inline void bind(Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8)) { + m_Closure.bindmemfunc(detail::implicit_cast(pthis), function_to_bind); } + // Binding to const member functions. + template < class X, class Y > + FastDelegate8(const Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8) const) { + m_Closure.bindconstmemfunc(detail::implicit_cast(pthis), function_to_bind); } + template < class X, class Y > + inline void bind(const Y *pthis, DesiredRetType (xr_stdcall X::* function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8) const) { + m_Closure.bindconstmemfunc(detail::implicit_cast(pthis), function_to_bind); } + // Static functions. We convert them into a member function call. + // This constructor also provides implicit conversion + FastDelegate8(DesiredRetType (xr_stdcall *function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8) ) { + bind(function_to_bind); } + // for efficiency, prevent creation of a temporary + void operator = (DesiredRetType (xr_stdcall *function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8) ) { + bind(function_to_bind); } + inline void bind(DesiredRetType (xr_stdcall *function_to_bind)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8)) { + m_Closure.bindstaticfunc(this, &FastDelegate8::InvokeStaticFunction, + function_to_bind); } + // Invoke the delegate + RetType operator() (Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8) const { + return (m_Closure.GetClosureThis()->*(m_Closure.GetClosureMemPtr()))(p1, p2, p3, p4, p5, p6, p7, p8); } + // Implicit conversion to "bool" using the safe_bool idiom private: - typedef struct SafeBoolStruct { - int a_data_pointer_to_this_is_0_on_buggy_compilers; - StaticFunctionPtr m_nonzero; - } UselessTypedef; - typedef StaticFunctionPtr SafeBoolStruct::*unspecified_bool_type; + typedef struct SafeBoolStruct { + int a_data_pointer_to_this_is_0_on_buggy_compilers; + StaticFunctionPtr m_nonzero; + } UselessTypedef; + typedef StaticFunctionPtr SafeBoolStruct::*unspecified_bool_type; public: - operator unspecified_bool_type() const { - return empty()? 0: &SafeBoolStruct::m_nonzero; - } - // necessary to allow ==0 to work despite the safe_bool idiom - inline bool operator==(StaticFunctionPtr funcptr) { - return m_Closure.IsEqualToStaticFuncPtr(funcptr); } - inline bool operator!=(StaticFunctionPtr funcptr) { - return !m_Closure.IsEqualToStaticFuncPtr(funcptr); } - inline bool operator ! () const { // Is it bound to anything? - return !m_Closure; } - inline bool empty() const { - return !m_Closure; } - void clear() { m_Closure.clear();} - // Conversion to and from the DelegateMemento storage class - const DelegateMemento & GetMemento() { return m_Closure; } - void SetMemento(const DelegateMemento &any) { m_Closure.CopyFrom(this, any); } - -private: // Invoker for static functions - RetType xr_stdcall InvokeStaticFunction(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8) const { - return (*(m_Closure.GetStaticFunction()))(p1, p2, p3, p4, p5, p6, p7, p8); } + operator unspecified_bool_type() const { + return empty()? 0: &SafeBoolStruct::m_nonzero; + } + // necessary to allow ==0 to work despite the safe_bool idiom + inline bool operator==(StaticFunctionPtr funcptr) { + return m_Closure.IsEqualToStaticFuncPtr(funcptr); } + inline bool operator!=(StaticFunctionPtr funcptr) { + return !m_Closure.IsEqualToStaticFuncPtr(funcptr); } + inline bool operator ! () const { // Is it bound to anything? + return !m_Closure; } + inline bool empty() const { + return !m_Closure; } + void clear() { m_Closure.clear();} + // Conversion to and from the DelegateMemento storage class + const DelegateMemento & GetMemento() { return m_Closure; } + void SetMemento(const DelegateMemento &any) { m_Closure.CopyFrom(this, any); } + +private: // Invoker for static functions + RetType xr_stdcall InvokeStaticFunction(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8) const { + return (*(m_Closure.GetStaticFunction()))(p1, p2, p3, p4, p5, p6, p7, p8); } }; //////////////////////////////////////////////////////////////////////////////// -// Fast Delegates, part 4: +// Fast Delegates, part 4: // -// FastDelegate<> class (Original author: Jody Hagins) -// Allows boost::function style syntax like: -// FastDelegate< double (int, long) > +// FastDelegate<> class (Original author: Jody Hagins) +// Allows boost::function style syntax like: +// FastDelegate< double (int, long) > // instead of: -// FastDelegate2< int, long, double > +// FastDelegate2< int, long, double > // //////////////////////////////////////////////////////////////////////////////// @@ -1651,34 +1651,34 @@ class FastDelegate; // FastDelegate0 < R > template class FastDelegate< R ( ) > - // Inherit from FastDelegate0 so that it can be treated just like a FastDelegate0 - : public FastDelegate0 < R > + // Inherit from FastDelegate0 so that it can be treated just like a FastDelegate0 + : public FastDelegate0 < R > { public: - // Make using the base type a bit easier via typedef. - typedef FastDelegate0 < R > BaseType; - - // Allow users access to the specific type of this delegate. - typedef FastDelegate SelfType; - - // Mimic the base class constructors. - FastDelegate() : BaseType() { } - - template < class X, class Y > - FastDelegate(Y * pthis, - R (xr_stdcall X::* function_to_bind)( )) - : BaseType(pthis, function_to_bind) { } - - template < class X, class Y > - FastDelegate(const Y *pthis, - R (xr_stdcall X::* function_to_bind)( ) const) - : BaseType(pthis, function_to_bind) - { } - - FastDelegate(R (xr_stdcall *function_to_bind)( )) - : BaseType(function_to_bind) { } - void operator = (const BaseType &x) { - *static_cast(this) = x; } + // Make using the base type a bit easier via typedef. + typedef FastDelegate0 < R > BaseType; + + // Allow users access to the specific type of this delegate. + typedef FastDelegate SelfType; + + // Mimic the base class constructors. + FastDelegate() : BaseType() { } + + template < class X, class Y > + FastDelegate(Y * pthis, + R (xr_stdcall X::* function_to_bind)( )) + : BaseType(pthis, function_to_bind) { } + + template < class X, class Y > + FastDelegate(const Y *pthis, + R (xr_stdcall X::* function_to_bind)( ) const) + : BaseType(pthis, function_to_bind) + { } + + FastDelegate(R (xr_stdcall *function_to_bind)( )) + : BaseType(function_to_bind) { } + void operator = (const BaseType &x) { + *static_cast(this) = x; } }; //N=1 @@ -1688,34 +1688,34 @@ class FastDelegate< R ( ) > // FastDelegate1 < Param1, R > template class FastDelegate< R ( Param1 ) > - // Inherit from FastDelegate1 so that it can be treated just like a FastDelegate1 - : public FastDelegate1 < Param1, R > + // Inherit from FastDelegate1 so that it can be treated just like a FastDelegate1 + : public FastDelegate1 < Param1, R > { public: - // Make using the base type a bit easier via typedef. - typedef FastDelegate1 < Param1, R > BaseType; - - // Allow users access to the specific type of this delegate. - typedef FastDelegate SelfType; - - // Mimic the base class constructors. - FastDelegate() : BaseType() { } - - template < class X, class Y > - FastDelegate(Y * pthis, - R (xr_stdcall X::* function_to_bind)( Param1 p1 )) - : BaseType(pthis, function_to_bind) { } - - template < class X, class Y > - FastDelegate(const Y *pthis, - R (xr_stdcall X::* function_to_bind)( Param1 p1 ) const) - : BaseType(pthis, function_to_bind) - { } - - FastDelegate(R (xr_stdcall *function_to_bind)( Param1 p1 )) - : BaseType(function_to_bind) { } - void operator = (const BaseType &x) { - *static_cast(this) = x; } + // Make using the base type a bit easier via typedef. + typedef FastDelegate1 < Param1, R > BaseType; + + // Allow users access to the specific type of this delegate. + typedef FastDelegate SelfType; + + // Mimic the base class constructors. + FastDelegate() : BaseType() { } + + template < class X, class Y > + FastDelegate(Y * pthis, + R (xr_stdcall X::* function_to_bind)( Param1 p1 )) + : BaseType(pthis, function_to_bind) { } + + template < class X, class Y > + FastDelegate(const Y *pthis, + R (xr_stdcall X::* function_to_bind)( Param1 p1 ) const) + : BaseType(pthis, function_to_bind) + { } + + FastDelegate(R (xr_stdcall *function_to_bind)( Param1 p1 )) + : BaseType(function_to_bind) { } + void operator = (const BaseType &x) { + *static_cast(this) = x; } }; //N=2 @@ -1725,34 +1725,34 @@ class FastDelegate< R ( Param1 ) > // FastDelegate2 < Param1, Param2, R > template class FastDelegate< R ( Param1, Param2 ) > - // Inherit from FastDelegate2 so that it can be treated just like a FastDelegate2 - : public FastDelegate2 < Param1, Param2, R > + // Inherit from FastDelegate2 so that it can be treated just like a FastDelegate2 + : public FastDelegate2 < Param1, Param2, R > { public: - // Make using the base type a bit easier via typedef. - typedef FastDelegate2 < Param1, Param2, R > BaseType; - - // Allow users access to the specific type of this delegate. - typedef FastDelegate SelfType; - - // Mimic the base class constructors. - FastDelegate() : BaseType() { } - - template < class X, class Y > - FastDelegate(Y * pthis, - R (xr_stdcall X::* function_to_bind)( Param1 p1, Param2 p2 )) - : BaseType(pthis, function_to_bind) { } - - template < class X, class Y > - FastDelegate(const Y *pthis, - R (xr_stdcall X::* function_to_bind)( Param1 p1, Param2 p2 ) const) - : BaseType(pthis, function_to_bind) - { } - - FastDelegate(R (xr_stdcall *function_to_bind)( Param1 p1, Param2 p2 )) - : BaseType(function_to_bind) { } - void operator = (const BaseType &x) { - *static_cast(this) = x; } + // Make using the base type a bit easier via typedef. + typedef FastDelegate2 < Param1, Param2, R > BaseType; + + // Allow users access to the specific type of this delegate. + typedef FastDelegate SelfType; + + // Mimic the base class constructors. + FastDelegate() : BaseType() { } + + template < class X, class Y > + FastDelegate(Y * pthis, + R (xr_stdcall X::* function_to_bind)( Param1 p1, Param2 p2 )) + : BaseType(pthis, function_to_bind) { } + + template < class X, class Y > + FastDelegate(const Y *pthis, + R (xr_stdcall X::* function_to_bind)( Param1 p1, Param2 p2 ) const) + : BaseType(pthis, function_to_bind) + { } + + FastDelegate(R (xr_stdcall *function_to_bind)( Param1 p1, Param2 p2 )) + : BaseType(function_to_bind) { } + void operator = (const BaseType &x) { + *static_cast(this) = x; } }; //N=3 @@ -1762,34 +1762,34 @@ class FastDelegate< R ( Param1, Param2 ) > // FastDelegate3 < Param1, Param2, Param3, R > template class FastDelegate< R ( Param1, Param2, Param3 ) > - // Inherit from FastDelegate3 so that it can be treated just like a FastDelegate3 - : public FastDelegate3 < Param1, Param2, Param3, R > + // Inherit from FastDelegate3 so that it can be treated just like a FastDelegate3 + : public FastDelegate3 < Param1, Param2, Param3, R > { public: - // Make using the base type a bit easier via typedef. - typedef FastDelegate3 < Param1, Param2, Param3, R > BaseType; - - // Allow users access to the specific type of this delegate. - typedef FastDelegate SelfType; - - // Mimic the base class constructors. - FastDelegate() : BaseType() { } - - template < class X, class Y > - FastDelegate(Y * pthis, - R (xr_stdcall X::* function_to_bind)( Param1 p1, Param2 p2, Param3 p3 )) - : BaseType(pthis, function_to_bind) { } - - template < class X, class Y > - FastDelegate(const Y *pthis, - R (xr_stdcall X::* function_to_bind)( Param1 p1, Param2 p2, Param3 p3 ) const) - : BaseType(pthis, function_to_bind) - { } - - FastDelegate(R (xr_stdcall *function_to_bind)( Param1 p1, Param2 p2, Param3 p3 )) - : BaseType(function_to_bind) { } - void operator = (const BaseType &x) { - *static_cast(this) = x; } + // Make using the base type a bit easier via typedef. + typedef FastDelegate3 < Param1, Param2, Param3, R > BaseType; + + // Allow users access to the specific type of this delegate. + typedef FastDelegate SelfType; + + // Mimic the base class constructors. + FastDelegate() : BaseType() { } + + template < class X, class Y > + FastDelegate(Y * pthis, + R (xr_stdcall X::* function_to_bind)( Param1 p1, Param2 p2, Param3 p3 )) + : BaseType(pthis, function_to_bind) { } + + template < class X, class Y > + FastDelegate(const Y *pthis, + R (xr_stdcall X::* function_to_bind)( Param1 p1, Param2 p2, Param3 p3 ) const) + : BaseType(pthis, function_to_bind) + { } + + FastDelegate(R (xr_stdcall *function_to_bind)( Param1 p1, Param2 p2, Param3 p3 )) + : BaseType(function_to_bind) { } + void operator = (const BaseType &x) { + *static_cast(this) = x; } }; //N=4 @@ -1799,34 +1799,34 @@ class FastDelegate< R ( Param1, Param2, Param3 ) > // FastDelegate4 < Param1, Param2, Param3, Param4, R > template class FastDelegate< R ( Param1, Param2, Param3, Param4 ) > - // Inherit from FastDelegate4 so that it can be treated just like a FastDelegate4 - : public FastDelegate4 < Param1, Param2, Param3, Param4, R > + // Inherit from FastDelegate4 so that it can be treated just like a FastDelegate4 + : public FastDelegate4 < Param1, Param2, Param3, Param4, R > { public: - // Make using the base type a bit easier via typedef. - typedef FastDelegate4 < Param1, Param2, Param3, Param4, R > BaseType; - - // Allow users access to the specific type of this delegate. - typedef FastDelegate SelfType; - - // Mimic the base class constructors. - FastDelegate() : BaseType() { } - - template < class X, class Y > - FastDelegate(Y * pthis, - R (xr_stdcall X::* function_to_bind)( Param1 p1, Param2 p2, Param3 p3, Param4 p4 )) - : BaseType(pthis, function_to_bind) { } - - template < class X, class Y > - FastDelegate(const Y *pthis, - R (xr_stdcall X::* function_to_bind)( Param1 p1, Param2 p2, Param3 p3, Param4 p4 ) const) - : BaseType(pthis, function_to_bind) - { } - - FastDelegate(R (xr_stdcall *function_to_bind)( Param1 p1, Param2 p2, Param3 p3, Param4 p4 )) - : BaseType(function_to_bind) { } - void operator = (const BaseType &x) { - *static_cast(this) = x; } + // Make using the base type a bit easier via typedef. + typedef FastDelegate4 < Param1, Param2, Param3, Param4, R > BaseType; + + // Allow users access to the specific type of this delegate. + typedef FastDelegate SelfType; + + // Mimic the base class constructors. + FastDelegate() : BaseType() { } + + template < class X, class Y > + FastDelegate(Y * pthis, + R (xr_stdcall X::* function_to_bind)( Param1 p1, Param2 p2, Param3 p3, Param4 p4 )) + : BaseType(pthis, function_to_bind) { } + + template < class X, class Y > + FastDelegate(const Y *pthis, + R (xr_stdcall X::* function_to_bind)( Param1 p1, Param2 p2, Param3 p3, Param4 p4 ) const) + : BaseType(pthis, function_to_bind) + { } + + FastDelegate(R (xr_stdcall *function_to_bind)( Param1 p1, Param2 p2, Param3 p3, Param4 p4 )) + : BaseType(function_to_bind) { } + void operator = (const BaseType &x) { + *static_cast(this) = x; } }; //N=5 @@ -1836,34 +1836,34 @@ class FastDelegate< R ( Param1, Param2, Param3, Param4 ) > // FastDelegate5 < Param1, Param2, Param3, Param4, Param5, R > template class FastDelegate< R ( Param1, Param2, Param3, Param4, Param5 ) > - // Inherit from FastDelegate5 so that it can be treated just like a FastDelegate5 - : public FastDelegate5 < Param1, Param2, Param3, Param4, Param5, R > + // Inherit from FastDelegate5 so that it can be treated just like a FastDelegate5 + : public FastDelegate5 < Param1, Param2, Param3, Param4, Param5, R > { public: - // Make using the base type a bit easier via typedef. - typedef FastDelegate5 < Param1, Param2, Param3, Param4, Param5, R > BaseType; - - // Allow users access to the specific type of this delegate. - typedef FastDelegate SelfType; - - // Mimic the base class constructors. - FastDelegate() : BaseType() { } - - template < class X, class Y > - FastDelegate(Y * pthis, - R (xr_stdcall X::* function_to_bind)( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5 )) - : BaseType(pthis, function_to_bind) { } - - template < class X, class Y > - FastDelegate(const Y *pthis, - R (xr_stdcall X::* function_to_bind)( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5 ) const) - : BaseType(pthis, function_to_bind) - { } - - FastDelegate(R (xr_stdcall *function_to_bind)( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5 )) - : BaseType(function_to_bind) { } - void operator = (const BaseType &x) { - *static_cast(this) = x; } + // Make using the base type a bit easier via typedef. + typedef FastDelegate5 < Param1, Param2, Param3, Param4, Param5, R > BaseType; + + // Allow users access to the specific type of this delegate. + typedef FastDelegate SelfType; + + // Mimic the base class constructors. + FastDelegate() : BaseType() { } + + template < class X, class Y > + FastDelegate(Y * pthis, + R (xr_stdcall X::* function_to_bind)( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5 )) + : BaseType(pthis, function_to_bind) { } + + template < class X, class Y > + FastDelegate(const Y *pthis, + R (xr_stdcall X::* function_to_bind)( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5 ) const) + : BaseType(pthis, function_to_bind) + { } + + FastDelegate(R (xr_stdcall *function_to_bind)( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5 )) + : BaseType(function_to_bind) { } + void operator = (const BaseType &x) { + *static_cast(this) = x; } }; //N=6 @@ -1873,34 +1873,34 @@ class FastDelegate< R ( Param1, Param2, Param3, Param4, Param5 ) > // FastDelegate6 < Param1, Param2, Param3, Param4, Param5, Param6, R > template class FastDelegate< R ( Param1, Param2, Param3, Param4, Param5, Param6 ) > - // Inherit from FastDelegate6 so that it can be treated just like a FastDelegate6 - : public FastDelegate6 < Param1, Param2, Param3, Param4, Param5, Param6, R > + // Inherit from FastDelegate6 so that it can be treated just like a FastDelegate6 + : public FastDelegate6 < Param1, Param2, Param3, Param4, Param5, Param6, R > { public: - // Make using the base type a bit easier via typedef. - typedef FastDelegate6 < Param1, Param2, Param3, Param4, Param5, Param6, R > BaseType; - - // Allow users access to the specific type of this delegate. - typedef FastDelegate SelfType; - - // Mimic the base class constructors. - FastDelegate() : BaseType() { } - - template < class X, class Y > - FastDelegate(Y * pthis, - R (xr_stdcall X::* function_to_bind)( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6 )) - : BaseType(pthis, function_to_bind) { } - - template < class X, class Y > - FastDelegate(const Y *pthis, - R (xr_stdcall X::* function_to_bind)( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6 ) const) - : BaseType(pthis, function_to_bind) - { } - - FastDelegate(R (xr_stdcall *function_to_bind)( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6 )) - : BaseType(function_to_bind) { } - void operator = (const BaseType &x) { - *static_cast(this) = x; } + // Make using the base type a bit easier via typedef. + typedef FastDelegate6 < Param1, Param2, Param3, Param4, Param5, Param6, R > BaseType; + + // Allow users access to the specific type of this delegate. + typedef FastDelegate SelfType; + + // Mimic the base class constructors. + FastDelegate() : BaseType() { } + + template < class X, class Y > + FastDelegate(Y * pthis, + R (xr_stdcall X::* function_to_bind)( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6 )) + : BaseType(pthis, function_to_bind) { } + + template < class X, class Y > + FastDelegate(const Y *pthis, + R (xr_stdcall X::* function_to_bind)( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6 ) const) + : BaseType(pthis, function_to_bind) + { } + + FastDelegate(R (xr_stdcall *function_to_bind)( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6 )) + : BaseType(function_to_bind) { } + void operator = (const BaseType &x) { + *static_cast(this) = x; } }; //N=7 @@ -1910,34 +1910,34 @@ class FastDelegate< R ( Param1, Param2, Param3, Param4, Param5, Param6 ) > // FastDelegate7 < Param1, Param2, Param3, Param4, Param5, Param6, Param7, R > template class FastDelegate< R ( Param1, Param2, Param3, Param4, Param5, Param6, Param7 ) > - // Inherit from FastDelegate7 so that it can be treated just like a FastDelegate7 - : public FastDelegate7 < Param1, Param2, Param3, Param4, Param5, Param6, Param7, R > + // Inherit from FastDelegate7 so that it can be treated just like a FastDelegate7 + : public FastDelegate7 < Param1, Param2, Param3, Param4, Param5, Param6, Param7, R > { public: - // Make using the base type a bit easier via typedef. - typedef FastDelegate7 < Param1, Param2, Param3, Param4, Param5, Param6, Param7, R > BaseType; - - // Allow users access to the specific type of this delegate. - typedef FastDelegate SelfType; - - // Mimic the base class constructors. - FastDelegate() : BaseType() { } - - template < class X, class Y > - FastDelegate(Y * pthis, - R (xr_stdcall X::* function_to_bind)( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7 )) - : BaseType(pthis, function_to_bind) { } - - template < class X, class Y > - FastDelegate(const Y *pthis, - R (xr_stdcall X::* function_to_bind)( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7 ) const) - : BaseType(pthis, function_to_bind) - { } - - FastDelegate(R (xr_stdcall *function_to_bind)( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7 )) - : BaseType(function_to_bind) { } - void operator = (const BaseType &x) { - *static_cast(this) = x; } + // Make using the base type a bit easier via typedef. + typedef FastDelegate7 < Param1, Param2, Param3, Param4, Param5, Param6, Param7, R > BaseType; + + // Allow users access to the specific type of this delegate. + typedef FastDelegate SelfType; + + // Mimic the base class constructors. + FastDelegate() : BaseType() { } + + template < class X, class Y > + FastDelegate(Y * pthis, + R (xr_stdcall X::* function_to_bind)( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7 )) + : BaseType(pthis, function_to_bind) { } + + template < class X, class Y > + FastDelegate(const Y *pthis, + R (xr_stdcall X::* function_to_bind)( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7 ) const) + : BaseType(pthis, function_to_bind) + { } + + FastDelegate(R (xr_stdcall *function_to_bind)( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7 )) + : BaseType(function_to_bind) { } + void operator = (const BaseType &x) { + *static_cast(this) = x; } }; //N=8 @@ -1947,47 +1947,47 @@ class FastDelegate< R ( Param1, Param2, Param3, Param4, Param5, Param6, Param7 ) // FastDelegate8 < Param1, Param2, Param3, Param4, Param5, Param6, Param7, Param8, R > template class FastDelegate< R ( Param1, Param2, Param3, Param4, Param5, Param6, Param7, Param8 ) > - // Inherit from FastDelegate8 so that it can be treated just like a FastDelegate8 - : public FastDelegate8 < Param1, Param2, Param3, Param4, Param5, Param6, Param7, Param8, R > + // Inherit from FastDelegate8 so that it can be treated just like a FastDelegate8 + : public FastDelegate8 < Param1, Param2, Param3, Param4, Param5, Param6, Param7, Param8, R > { public: - // Make using the base type a bit easier via typedef. - typedef FastDelegate8 < Param1, Param2, Param3, Param4, Param5, Param6, Param7, Param8, R > BaseType; - - // Allow users access to the specific type of this delegate. - typedef FastDelegate SelfType; - - // Mimic the base class constructors. - FastDelegate() : BaseType() { } - - template < class X, class Y > - FastDelegate(Y * pthis, - R (xr_stdcall X::* function_to_bind)( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8 )) - : BaseType(pthis, function_to_bind) { } - - template < class X, class Y > - FastDelegate(const Y *pthis, - R (xr_stdcall X::* function_to_bind)( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8 ) const) - : BaseType(pthis, function_to_bind) - { } - - FastDelegate(R (xr_stdcall *function_to_bind)( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8 )) - : BaseType(function_to_bind) { } - void operator = (const BaseType &x) { - *static_cast(this) = x; } + // Make using the base type a bit easier via typedef. + typedef FastDelegate8 < Param1, Param2, Param3, Param4, Param5, Param6, Param7, Param8, R > BaseType; + + // Allow users access to the specific type of this delegate. + typedef FastDelegate SelfType; + + // Mimic the base class constructors. + FastDelegate() : BaseType() { } + + template < class X, class Y > + FastDelegate(Y * pthis, + R (xr_stdcall X::* function_to_bind)( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8 )) + : BaseType(pthis, function_to_bind) { } + + template < class X, class Y > + FastDelegate(const Y *pthis, + R (xr_stdcall X::* function_to_bind)( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8 ) const) + : BaseType(pthis, function_to_bind) + { } + + FastDelegate(R (xr_stdcall *function_to_bind)( Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8 )) + : BaseType(function_to_bind) { } + void operator = (const BaseType &x) { + *static_cast(this) = x; } }; #endif //FASTDELEGATE_ALLOW_FUNCTION_TYPE_SYNTAX //////////////////////////////////////////////////////////////////////////////// -// Fast Delegates, part 5: +// Fast Delegates, part 5: // -// MakeDelegate() helper function +// MakeDelegate() helper function // -// MakeDelegate(&x, &X::func) returns a fastdelegate of the type -// necessary for calling x.func() with the correct number of arguments. -// This makes it possible to eliminate many typedefs from user code. +// MakeDelegate(&x, &X::func) returns a fastdelegate of the type +// necessary for calling x.func() with the correct number of arguments. +// This makes it possible to eliminate many typedefs from user code. // //////////////////////////////////////////////////////////////////////////////// @@ -2013,107 +2013,107 @@ class FastDelegate< R ( Param1, Param2, Param3, Param4, Param5, Param6, Param7, //N=0 template FastDelegate0 MakeDelegate(Y* x, RetType (xr_stdcall X::*func)()) { - return FastDelegate0(x, func); + return FastDelegate0(x, func); } template FastDelegate0 MakeDelegate(Y* x, RetType (xr_stdcall X::*func)() const) { - return FastDelegate0(x, func); + return FastDelegate0(x, func); } //N=1 template FastDelegate1 MakeDelegate(Y* x, RetType (xr_stdcall X::*func)(Param1 p1)) { - return FastDelegate1(x, func); + return FastDelegate1(x, func); } template FastDelegate1 MakeDelegate(Y* x, RetType (xr_stdcall X::*func)(Param1 p1) const) { - return FastDelegate1(x, func); + return FastDelegate1(x, func); } //N=2 template FastDelegate2 MakeDelegate(Y* x, RetType (xr_stdcall X::*func)(Param1 p1, Param2 p2)) { - return FastDelegate2(x, func); + return FastDelegate2(x, func); } template FastDelegate2 MakeDelegate(Y* x, RetType (xr_stdcall X::*func)(Param1 p1, Param2 p2) const) { - return FastDelegate2(x, func); + return FastDelegate2(x, func); } //N=3 template FastDelegate3 MakeDelegate(Y* x, RetType (xr_stdcall X::*func)(Param1 p1, Param2 p2, Param3 p3)) { - return FastDelegate3(x, func); + return FastDelegate3(x, func); } template FastDelegate3 MakeDelegate(Y* x, RetType (xr_stdcall X::*func)(Param1 p1, Param2 p2, Param3 p3) const) { - return FastDelegate3(x, func); + return FastDelegate3(x, func); } //N=4 template FastDelegate4 MakeDelegate(Y* x, RetType (xr_stdcall X::*func)(Param1 p1, Param2 p2, Param3 p3, Param4 p4)) { - return FastDelegate4(x, func); + return FastDelegate4(x, func); } template FastDelegate4 MakeDelegate(Y* x, RetType (xr_stdcall X::*func)(Param1 p1, Param2 p2, Param3 p3, Param4 p4) const) { - return FastDelegate4(x, func); + return FastDelegate4(x, func); } //N=5 template FastDelegate5 MakeDelegate(Y* x, RetType (xr_stdcall X::*func)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5)) { - return FastDelegate5(x, func); + return FastDelegate5(x, func); } template FastDelegate5 MakeDelegate(Y* x, RetType (xr_stdcall X::*func)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5) const) { - return FastDelegate5(x, func); + return FastDelegate5(x, func); } //N=6 template FastDelegate6 MakeDelegate(Y* x, RetType (xr_stdcall X::*func)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6)) { - return FastDelegate6(x, func); + return FastDelegate6(x, func); } template FastDelegate6 MakeDelegate(Y* x, RetType (xr_stdcall X::*func)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6) const) { - return FastDelegate6(x, func); + return FastDelegate6(x, func); } //N=7 template FastDelegate7 MakeDelegate(Y* x, RetType (X::*func)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7)) { - return FastDelegate7(x, func); + return FastDelegate7(x, func); } template FastDelegate7 MakeDelegate(Y* x, RetType (X::*func)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7) const) { - return FastDelegate7(x, func); + return FastDelegate7(x, func); } //N=8 template FastDelegate8 MakeDelegate(Y* x, RetType (X::*func)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8)) { - return FastDelegate8(x, func); + return FastDelegate8(x, func); } template FastDelegate8 MakeDelegate(Y* x, RetType (X::*func)(Param1 p1, Param2 p2, Param3 p3, Param4 p4, Param5 p5, Param6 p6, Param7 p7, Param8 p8) const) { - return FastDelegate8(x, func); + return FastDelegate8(x, func); } #ifdef __BORLANDC__ template - A bind(B b) {A a; a.bind(b); return a;} + A bind(B b) {A a; a.bind(b); return a;} template - A bind(B b,C c) {A a; a.bind(b,c); return a;} + A bind(B b,C c) {A a; a.bind(b,c); return a;} #endif // clean up after ourselves... diff --git a/src/xrCore/file_stream_reader.cpp b/src/xrCore/file_stream_reader.cpp index 9226519044f..6883f41f826 100644 --- a/src/xrCore/file_stream_reader.cpp +++ b/src/xrCore/file_stream_reader.cpp @@ -1,40 +1,23 @@ #include "stdafx.h" #include "file_stream_reader.h" -void CFileStreamReader::construct (LPCSTR file_name, const u32 &window_size) +void CFileStreamReader::construct(LPCSTR file_name, const u32& window_size) { - m_file_handle = - CreateFile( - file_name, - GENERIC_READ, - FILE_SHARE_READ, - 0, - OPEN_EXISTING, - 0, - 0 - ); + m_file_handle = CreateFile(file_name, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0); - VERIFY (m_file_handle != INVALID_HANDLE_VALUE); - u32 file_size = (u32)GetFileSize(m_file_handle,NULL); + VERIFY(m_file_handle != INVALID_HANDLE_VALUE); + u32 file_size = (u32)GetFileSize(m_file_handle, NULL); - HANDLE file_mapping_handle = - CreateFileMapping( - m_file_handle, - 0, - PAGE_READONLY, - 0, - 0, - 0 - ); - VERIFY (file_mapping_handle != INVALID_HANDLE_VALUE); + HANDLE file_mapping_handle = CreateFileMapping(m_file_handle, 0, PAGE_READONLY, 0, 0, 0); + VERIFY(file_mapping_handle != INVALID_HANDLE_VALUE); - inherited::construct (file_mapping_handle,0,file_size,file_size,window_size); + inherited::construct(file_mapping_handle, 0, file_size, file_size, window_size); } -void CFileStreamReader::destroy () +void CFileStreamReader::destroy() { - HANDLE file_mapping_handle = this->file_mapping_handle(); - inherited::destroy (); - CloseHandle (file_mapping_handle); - CloseHandle (m_file_handle); + HANDLE file_mapping_handle = this->file_mapping_handle(); + inherited::destroy(); + CloseHandle(file_mapping_handle); + CloseHandle(m_file_handle); } diff --git a/src/xrCore/file_stream_reader.h b/src/xrCore/file_stream_reader.h index d10b12cd926..4342330e315 100644 --- a/src/xrCore/file_stream_reader.h +++ b/src/xrCore/file_stream_reader.h @@ -3,16 +3,17 @@ #include "stream_reader.h" -class CFileStreamReader : public CStreamReader { +class CFileStreamReader : public CStreamReader +{ private: - typedef CStreamReader inherited; + typedef CStreamReader inherited; private: - HANDLE m_file_handle; + HANDLE m_file_handle; public: - virtual void construct (LPCSTR file_name, const u32 &window_size); - virtual void destroy (); + virtual void construct(LPCSTR file_name, const u32& window_size); + virtual void destroy(); }; #endif // FILE_STREAM_READER_H \ No newline at end of file diff --git a/src/xrCore/intrusive_ptr.h b/src/xrCore/intrusive_ptr.h index 40d81b00012..3c95eb48e42 100644 --- a/src/xrCore/intrusive_ptr.h +++ b/src/xrCore/intrusive_ptr.h @@ -1,93 +1,99 @@ //////////////////////////////////////////////////////////////////////////// -// Module : intrusive_ptr.h -// Created : 30.07.2004 -// Modified : 30.07.2004 -// Author : Dmitriy Iassenev -// Description : Intrusive pointer template +// Module : intrusive_ptr.h +// Created : 30.07.2004 +// Modified : 30.07.2004 +// Author : Dmitriy Iassenev +// Description : Intrusive pointer template //////////////////////////////////////////////////////////////////////////// #pragma once #ifdef XRGAME_EXPORTS -# include "object_type_traits.h" +# include "object_type_traits.h" #endif //XRGAME_EXPORTS #pragma pack(push,4) -struct intrusive_base { - u32 m_ref_count; - - IC intrusive_base () : m_ref_count(0) - { - } - - template - IC void _release (T*object) - { - try { - xr_delete (object); - } - catch(...) { - } - } +struct intrusive_base +{ + u32 m_ref_count; + + IC intrusive_base() : m_ref_count(0) + { + } + + template + IC void _release(T* object) + { + try + { + xr_delete(object); + } + catch (...) + { + } + } }; template -class intrusive_ptr { +class intrusive_ptr +{ private: - typedef base_type base_type; - typedef object_type object_type; - typedef intrusive_ptr self_type; - typedef const object_type *(intrusive_ptr::*unspecified_bool_type) () const; + typedef base_type base_type; + typedef object_type object_type; + typedef intrusive_ptr self_type; + typedef const object_type* (intrusive_ptr::*unspecified_bool_type) () const; private: #ifdef XRGAME_EXPORTS - enum {result = - object_type_traits::is_base_and_derived::value || - object_type_traits::is_same::value - }; -#else - enum {result = true }; + enum + { + result = + object_type_traits::is_base_and_derived::value || + object_type_traits::is_same::value + }; +#else + enum { result = true }; #endif private: - object_type *m_object; + object_type* m_object; protected: - IC void dec (); + IC void dec(); public: - IC intrusive_ptr (); - IC intrusive_ptr (object_type *rhs); - IC intrusive_ptr (self_type const &rhs); - IC ~intrusive_ptr (); - IC self_type &operator= (object_type* rhs); - IC self_type &operator= (self_type const &rhs); - IC object_type &operator* () const; - IC object_type *operator-> () const; - IC bool operator! () const; - IC operator unspecified_bool_type () const { return(!m_object? 0: &intrusive_ptr::get);} - IC u32 size (); - IC void swap (self_type &rhs); - IC bool equal (const self_type & rhs) const; - IC void set (object_type* rhs); - IC void set (self_type const &rhs); - IC const object_type *get () const; + IC intrusive_ptr(); + IC intrusive_ptr(object_type* rhs); + IC intrusive_ptr(self_type const& rhs); + IC ~intrusive_ptr(); + IC self_type& operator= (object_type* rhs); + IC self_type& operator= (self_type const& rhs); + IC object_type& operator* () const; + IC object_type* operator-> () const; + IC bool operator! () const; + IC operator unspecified_bool_type () const { return(!m_object ? 0 : &intrusive_ptr::get); } + IC u32 size(); + IC void swap(self_type& rhs); + IC bool equal(const self_type& rhs) const; + IC void set(object_type* rhs); + IC void set(self_type const& rhs); + IC const object_type* get() const; }; template -IC bool operator== (intrusive_ptr const & a, intrusive_ptr const & b); +IC bool operator== (intrusive_ptr const& a, intrusive_ptr const& b); template -IC bool operator!= (intrusive_ptr const & a, intrusive_ptr const & b); +IC bool operator!= (intrusive_ptr const& a, intrusive_ptr const& b); template -IC bool operator< (intrusive_ptr const & a, intrusive_ptr const & b); +IC bool operator< (intrusive_ptr const& a, intrusive_ptr const& b); template -IC bool operator> (intrusive_ptr const & a, intrusive_ptr const & b); +IC bool operator> (intrusive_ptr const& a, intrusive_ptr const& b); template -IC void swap (intrusive_ptr & lhs, intrusive_ptr & rhs); +IC void swap(intrusive_ptr& lhs, intrusive_ptr& rhs); #include "intrusive_ptr_inline.h" diff --git a/src/xrCore/intrusive_ptr_inline.h b/src/xrCore/intrusive_ptr_inline.h index 7825200df6a..65f8133647d 100644 --- a/src/xrCore/intrusive_ptr_inline.h +++ b/src/xrCore/intrusive_ptr_inline.h @@ -1,9 +1,9 @@ //////////////////////////////////////////////////////////////////////////// -// Module : intrusive_ptr_inline.h -// Created : 30.07.2004 -// Modified : 30.07.2004 -// Author : Dmitriy Iassenev -// Description : Intrusive pointer template inline functions +// Module : intrusive_ptr_inline.h +// Created : 30.07.2004 +// Modified : 30.07.2004 +// Author : Dmitriy Iassenev +// Description : Intrusive pointer template inline functions //////////////////////////////////////////////////////////////////////////// #pragma once @@ -12,149 +12,149 @@ #define _intrusive_ptr intrusive_ptr TEMPLATE_SPECIALIZATION -IC _intrusive_ptr::intrusive_ptr () +IC _intrusive_ptr::intrusive_ptr() { - m_object = 0; + m_object = 0; } TEMPLATE_SPECIALIZATION -IC _intrusive_ptr::intrusive_ptr (object_type* rhs) +IC _intrusive_ptr::intrusive_ptr(object_type* rhs) { - m_object = 0; - set (rhs); + m_object = 0; + set(rhs); } TEMPLATE_SPECIALIZATION -IC _intrusive_ptr::intrusive_ptr (self_type const &rhs) +IC _intrusive_ptr::intrusive_ptr(self_type const& rhs) { - m_object = 0; - set (rhs); + m_object = 0; + set(rhs); } TEMPLATE_SPECIALIZATION -IC _intrusive_ptr::~intrusive_ptr () +IC _intrusive_ptr::~intrusive_ptr() { - STATIC_CHECK (result,Class_MUST_Be_Derived_From_The_Base); - dec (); + STATIC_CHECK(result, Class_MUST_Be_Derived_From_The_Base); + dec(); } TEMPLATE_SPECIALIZATION -IC void _intrusive_ptr::dec () +IC void _intrusive_ptr::dec() { - if (!m_object) - return; - - --m_object->base_type::m_ref_count; - if (!m_object->base_type::m_ref_count) - m_object->base_type::_release (m_object); + if (!m_object) + return; + + --m_object->base_type::m_ref_count; + if (!m_object->base_type::m_ref_count) + m_object->base_type::_release(m_object); } TEMPLATE_SPECIALIZATION -IC typename _intrusive_ptr::self_type &_intrusive_ptr::operator= (object_type* rhs) +IC typename _intrusive_ptr::self_type& _intrusive_ptr::operator= (object_type* rhs) { - set (rhs); - return ((self_type&)*this); + set(rhs); + return ((self_type&)*this); } TEMPLATE_SPECIALIZATION -IC typename _intrusive_ptr::self_type &_intrusive_ptr::operator= (self_type const &rhs) +IC typename _intrusive_ptr::self_type& _intrusive_ptr::operator= (self_type const& rhs) { - set (rhs); - return ((self_type&)*this); + set(rhs); + return ((self_type&)*this); } TEMPLATE_SPECIALIZATION -IC typename _intrusive_ptr::object_type &_intrusive_ptr::operator* () const +IC typename _intrusive_ptr::object_type& _intrusive_ptr::operator* () const { - VERIFY (m_object); - return (*m_object); + VERIFY(m_object); + return (*m_object); } TEMPLATE_SPECIALIZATION -IC typename _intrusive_ptr::object_type *_intrusive_ptr::operator->() const +IC typename _intrusive_ptr::object_type* _intrusive_ptr::operator->() const { - VERIFY (m_object); - return (m_object); + VERIFY(m_object); + return (m_object); } TEMPLATE_SPECIALIZATION -IC bool _intrusive_ptr::operator! () const +IC bool _intrusive_ptr::operator! () const { - return (!m_object); + return (!m_object); } TEMPLATE_SPECIALIZATION -IC void _intrusive_ptr::swap (self_type & rhs) +IC void _intrusive_ptr::swap(self_type& rhs) { - object_type *tmp = m_object; - m_object = rhs.m_object; - rhs.m_object = tmp; + object_type* tmp = m_object; + m_object = rhs.m_object; + rhs.m_object = tmp; } TEMPLATE_SPECIALIZATION -IC bool _intrusive_ptr::equal (const self_type & rhs) const +IC bool _intrusive_ptr::equal(const self_type& rhs) const { - return (m_object == rhs.m_object); + return (m_object == rhs.m_object); } TEMPLATE_SPECIALIZATION -IC void _intrusive_ptr::set (object_type* rhs) +IC void _intrusive_ptr::set(object_type* rhs) { - if (m_object == rhs) - return; - dec (); - m_object = rhs; - if (!m_object) - return; - ++m_object->m_ref_count; + if (m_object == rhs) + return; + dec(); + m_object = rhs; + if (!m_object) + return; + ++m_object->m_ref_count; } TEMPLATE_SPECIALIZATION -IC void _intrusive_ptr::set (self_type const &rhs) +IC void _intrusive_ptr::set(self_type const& rhs) { - if (m_object == rhs.m_object) - return; - dec (); - m_object = rhs.m_object; - if (!m_object) - return; - ++m_object->m_ref_count; + if (m_object == rhs.m_object) + return; + dec(); + m_object = rhs.m_object; + if (!m_object) + return; + ++m_object->m_ref_count; } TEMPLATE_SPECIALIZATION -IC const typename _intrusive_ptr::object_type* _intrusive_ptr::get () const +IC const typename _intrusive_ptr::object_type* _intrusive_ptr::get() const { - return (m_object); + return (m_object); } TEMPLATE_SPECIALIZATION -IC bool operator== (_intrusive_ptr const &a, _intrusive_ptr const &b) +IC bool operator== (_intrusive_ptr const& a, _intrusive_ptr const& b) { - return (a.get() == b.get()); + return (a.get() == b.get()); } TEMPLATE_SPECIALIZATION -IC bool operator != (_intrusive_ptr const &a, _intrusive_ptr const &b) +IC bool operator != (_intrusive_ptr const& a, _intrusive_ptr const& b) { - return (a.get() != b.get()); + return (a.get() != b.get()); } TEMPLATE_SPECIALIZATION -IC bool operator< (_intrusive_ptr const &a, _intrusive_ptr const &b) +IC bool operator< (_intrusive_ptr const& a, _intrusive_ptr const& b) { - return (a.get() < b.get()); + return (a.get() < b.get()); } TEMPLATE_SPECIALIZATION -IC bool operator> (_intrusive_ptr const &a, _intrusive_ptr const &b) +IC bool operator> (_intrusive_ptr const& a, _intrusive_ptr const& b) { - return (a.get() > b.get()); + return (a.get() > b.get()); } TEMPLATE_SPECIALIZATION -IC void swap (_intrusive_ptr &lhs, _intrusive_ptr &rhs) +IC void swap(_intrusive_ptr& lhs, _intrusive_ptr& rhs) { - lhs.swap (rhs); + lhs.swap(rhs); } #undef TEMPLATE_SPECIALIZATION diff --git a/src/xrCore/log.cpp b/src/xrCore/log.cpp index 74d270f380f..bf00d58985c 100644 --- a/src/xrCore/log.cpp +++ b/src/xrCore/log.cpp @@ -5,198 +5,216 @@ #include "resource.h" #include "log.h" #ifdef _EDITOR - #include "malloc.h" +#include "malloc.h" #endif -extern BOOL LogExecCB = TRUE; -static string_path logFName = "engine.log"; -static string_path log_file_name = "engine.log"; -static BOOL no_log = TRUE; +extern BOOL LogExecCB = TRUE; +static string_path logFName = "engine.log"; +static string_path log_file_name = "engine.log"; +static BOOL no_log = TRUE; #ifdef PROFILE_CRITICAL_SECTIONS - static xrCriticalSection logCS(MUTEX_PROFILE_ID(log)); +static xrCriticalSection logCS(MUTEX_PROFILE_ID(log)); #else // PROFILE_CRITICAL_SECTIONS - static xrCriticalSection logCS; +static xrCriticalSection logCS; #endif // PROFILE_CRITICAL_SECTIONS -xr_vector* LogFile = NULL; -static LogCallback LogCB = 0; - -void FlushLog () -{ - if (!no_log){ - logCS.Enter (); - IWriter *f = FS.w_open(logFName); - if (f) { - for (u32 it=0; itsize(); it++) { - LPCSTR s = *((*LogFile)[it]); - f->w_string (s?s:""); - } - FS.w_close (f); +xr_vector* LogFile = NULL; +static LogCallback LogCB = 0; + +void FlushLog() +{ + if (!no_log) + { + logCS.Enter(); + IWriter* f = FS.w_open(logFName); + if (f) + { + for (u32 it = 0; it < LogFile->size(); it++) + { + LPCSTR s = *((*LogFile)[it]); + f->w_string(s ? s : ""); + } + FS.w_close(f); } - logCS.Leave (); + logCS.Leave(); } } -void AddOne (const char *split) +void AddOne(const char* split) { - if(!LogFile) - return; + if (!LogFile) + return; - logCS.Enter (); + logCS.Enter(); #ifdef DEBUG - OutputDebugString (split); - OutputDebugString ("\n"); + OutputDebugString(split); + OutputDebugString("\n"); #endif -// DUMP_PHASE; - { - shared_str temp = shared_str(split); -// DUMP_PHASE; - LogFile->push_back (temp); - } + // DUMP_PHASE; + { + shared_str temp = shared_str(split); + // DUMP_PHASE; + LogFile->push_back(temp); + } - //exec CallBack - if (LogExecCB&&LogCB)LogCB(split); + //exec CallBack + if (LogExecCB&&LogCB)LogCB(split); - logCS.Leave (); + logCS.Leave(); } -void Log (const char *s) +void Log(const char* s) { - int i,j; + int i, j; - u32 length = xr_strlen( s ); -#ifndef _EDITOR - PSTR split = (PSTR)_alloca( (length + 1) * sizeof(char) ); + u32 length = xr_strlen(s); +#ifndef _EDITOR + PSTR split = (PSTR)_alloca((length + 1) * sizeof(char)); #else - PSTR split = (PSTR)alloca( (length + 1) * sizeof(char) ); + PSTR split = (PSTR)alloca((length + 1) * sizeof(char)); #endif - for (i=0,j=0; s[i]!=0; i++) { - if (s[i]=='\n') { - split[j]=0; // end of line - if (split[0]==0) { split[0]=' '; split[1]=0; } - AddOne(split); - j=0; - } else { - split[j++]=s[i]; - } - } - split[j]=0; - AddOne(split); + for (i = 0, j = 0; s[i] != 0; i++) + { + if (s[i] == '\n') + { + split[j] = 0; // end of line + if (split[0] == 0) { split[0] = ' '; split[1] = 0; } + AddOne(split); + j = 0; + } + else + { + split[j++] = s[i]; + } + } + split[j] = 0; + AddOne(split); } -void __cdecl Msg ( const char *format, ...) +void __cdecl Msg(const char* format, ...) { - va_list mark; - string2048 buf; - va_start (mark, format ); - int sz = _vsnprintf(buf, sizeof(buf)-1, format, mark ); buf[sizeof(buf)-1]=0; - va_end (mark); - if (sz) Log(buf); + va_list mark; + string2048 buf; + va_start(mark, format); + int sz = _vsnprintf(buf, sizeof(buf) - 1, format, mark); + buf[sizeof(buf) - 1] = 0; + va_end(mark); + if (sz) Log(buf); } -void Log (const char *msg, const char *dop) { - if (!dop) { - Log (msg); - return; - } +void Log(const char* msg, const char* dop) +{ + if (!dop) + { + Log(msg); + return; + } - u32 buffer_size = (xr_strlen(msg) + 1 + xr_strlen(dop) + 1) * sizeof(char); - PSTR buf = (PSTR)_alloca( buffer_size ); - strconcat (buffer_size, buf, msg, " ", dop); - Log (buf); + u32 buffer_size = (xr_strlen(msg) + 1 + xr_strlen(dop) + 1) * sizeof(char); + PSTR buf = (PSTR)_alloca(buffer_size); + strconcat(buffer_size, buf, msg, " ", dop); + Log(buf); } -void Log (const char *msg, u32 dop) { - u32 buffer_size = (xr_strlen(msg) + 1 + 10 + 1) * sizeof(char); - PSTR buf = (PSTR)_alloca( buffer_size ); +void Log(const char* msg, u32 dop) +{ + u32 buffer_size = (xr_strlen(msg) + 1 + 10 + 1) * sizeof(char); + PSTR buf = (PSTR)_alloca(buffer_size); - xr_sprintf (buf, buffer_size, "%s %d", msg, dop); - Log (buf); + xr_sprintf(buf, buffer_size, "%s %d", msg, dop); + Log(buf); } -void Log (const char *msg, int dop) { - u32 buffer_size = (xr_strlen(msg) + 1 + 11 + 1) * sizeof(char); - PSTR buf = (PSTR)_alloca( buffer_size ); +void Log(const char* msg, int dop) +{ + u32 buffer_size = (xr_strlen(msg) + 1 + 11 + 1) * sizeof(char); + PSTR buf = (PSTR)_alloca(buffer_size); - xr_sprintf (buf, buffer_size, "%s %i", msg, dop); - Log (buf); + xr_sprintf(buf, buffer_size, "%s %i", msg, dop); + Log(buf); } -void Log (const char *msg, float dop) { - // actually, float string representation should be no more, than 40 characters, - // but we will count with slight overhead - u32 buffer_size = (xr_strlen(msg) + 1 + 64 + 1) * sizeof(char); - PSTR buf = (PSTR)_alloca( buffer_size ); +void Log(const char* msg, float dop) +{ + // actually, float string representation should be no more, than 40 characters, + // but we will count with slight overhead + u32 buffer_size = (xr_strlen(msg) + 1 + 64 + 1) * sizeof(char); + PSTR buf = (PSTR)_alloca(buffer_size); - xr_sprintf (buf, buffer_size, "%s %f", msg, dop); - Log (buf); + xr_sprintf(buf, buffer_size, "%s %f", msg, dop); + Log(buf); } -void Log (const char *msg, const Fvector &dop) { - u32 buffer_size = (xr_strlen(msg) + 2 + 3*(64 + 1) + 1) * sizeof(char); - PSTR buf = (PSTR)_alloca( buffer_size ); +void Log(const char* msg, const Fvector& dop) +{ + u32 buffer_size = (xr_strlen(msg) + 2 + 3 * (64 + 1) + 1) * sizeof(char); + PSTR buf = (PSTR)_alloca(buffer_size); - xr_sprintf (buf, buffer_size,"%s (%f,%f,%f)",msg, VPUSH(dop) ); - Log (buf); + xr_sprintf(buf, buffer_size, "%s (%f,%f,%f)", msg, VPUSH(dop)); + Log(buf); } -void Log (const char *msg, const Fmatrix &dop) { - u32 buffer_size = (xr_strlen(msg) + 2 + 4*( 4*(64 + 1) + 1 ) + 1) * sizeof(char); - PSTR buf = (PSTR)_alloca( buffer_size ); +void Log(const char* msg, const Fmatrix& dop) +{ + u32 buffer_size = (xr_strlen(msg) + 2 + 4 * (4 * (64 + 1) + 1) + 1) * sizeof(char); + PSTR buf = (PSTR)_alloca(buffer_size); - xr_sprintf (buf, buffer_size,"%s:\n%f,%f,%f,%f\n%f,%f,%f,%f\n%f,%f,%f,%f\n%f,%f,%f,%f\n", - msg, - dop.i.x, dop.i.y, dop.i.z, dop._14_, - dop.j.x, dop.j.y, dop.j.z, dop._24_, - dop.k.x, dop.k.y, dop.k.z, dop._34_, - dop.c.x, dop.c.y, dop.c.z, dop._44_ - ); - Log (buf); + xr_sprintf(buf, buffer_size, "%s:\n%f,%f,%f,%f\n%f,%f,%f,%f\n%f,%f,%f,%f\n%f,%f,%f,%f\n", + msg, + dop.i.x, dop.i.y, dop.i.z, dop._14_, + dop.j.x, dop.j.y, dop.j.z, dop._24_, + dop.k.x, dop.k.y, dop.k.z, dop._34_, + dop.c.x, dop.c.y, dop.c.z, dop._44_ + ); + Log(buf); } -void LogWinErr (const char *msg, long err_code) { - Msg ("%s: %s",msg,Debug.error2string(err_code) ); +void LogWinErr(const char* msg, long err_code) +{ + Msg("%s: %s", msg, Debug.error2string(err_code)); } -LogCallback SetLogCB (LogCallback cb) +LogCallback SetLogCB(LogCallback cb) { - LogCallback result = LogCB; - LogCB = cb; - return (result); + LogCallback result = LogCB; + LogCB = cb; + return (result); } -LPCSTR log_name () +LPCSTR log_name() { - return (log_file_name); + return (log_file_name); } void InitLog() { - R_ASSERT (LogFile==NULL); - LogFile = xr_new< xr_vector >(); - LogFile->reserve (1000); + R_ASSERT(LogFile == NULL); + LogFile = xr_new< xr_vector >(); + LogFile->reserve(1000); } -void CreateLog (BOOL nl) +void CreateLog(BOOL nl) { - no_log = nl; - strconcat (sizeof(log_file_name),log_file_name,Core.ApplicationName,"_",Core.UserName,".log"); - if (FS.path_exist("$logs$")) - FS.update_path (logFName,"$logs$",log_file_name); - if (!no_log){ - IWriter *f = FS.w_open (logFName); - if (f==NULL){ - MessageBox (NULL,"Can't create log file.","Error",MB_ICONERROR); - abort(); + no_log = nl; + strconcat(sizeof(log_file_name), log_file_name, Core.ApplicationName, "_", Core.UserName, ".log"); + if (FS.path_exist("$logs$")) + FS.update_path(logFName, "$logs$", log_file_name); + if (!no_log) + { + IWriter* f = FS.w_open(logFName); + if (f == NULL) + { + MessageBox(NULL, "Can't create log file.", "Error", MB_ICONERROR); + abort(); } - FS.w_close (f); + FS.w_close(f); } } void CloseLog(void) { - FlushLog (); - LogFile->clear (); - xr_delete (LogFile); + FlushLog(); + LogFile->clear(); + xr_delete(LogFile); } diff --git a/src/xrCore/log.h b/src/xrCore/log.h index c15eb537cef..f7545e74de8 100644 --- a/src/xrCore/log.h +++ b/src/xrCore/log.h @@ -1,28 +1,28 @@ #ifndef logH #define logH -#define VPUSH(a) ((a).x), ((a).y), ((a).z) +#define VPUSH(a) ((a).x), ((a).y), ((a).z) -void XRCORE_API __cdecl Msg (LPCSTR format, ...); -void XRCORE_API Log (LPCSTR msg); -void XRCORE_API Log (LPCSTR msg); -void XRCORE_API Log (LPCSTR msg, LPCSTR dop); -void XRCORE_API Log (LPCSTR msg, u32 dop); -void XRCORE_API Log (LPCSTR msg, int dop); -void XRCORE_API Log (LPCSTR msg, float dop); -void XRCORE_API Log (LPCSTR msg, const Fvector& dop); -void XRCORE_API Log (LPCSTR msg, const Fmatrix& dop); -void XRCORE_API LogWinErr (LPCSTR msg, long err_code); +void XRCORE_API __cdecl Msg(LPCSTR format, ...); +void XRCORE_API Log(LPCSTR msg); +void XRCORE_API Log(LPCSTR msg); +void XRCORE_API Log(LPCSTR msg, LPCSTR dop); +void XRCORE_API Log(LPCSTR msg, u32 dop); +void XRCORE_API Log(LPCSTR msg, int dop); +void XRCORE_API Log(LPCSTR msg, float dop); +void XRCORE_API Log(LPCSTR msg, const Fvector& dop); +void XRCORE_API Log(LPCSTR msg, const Fmatrix& dop); +void XRCORE_API LogWinErr(LPCSTR msg, long err_code); -typedef void ( * LogCallback) (LPCSTR string); -LogCallback XRCORE_API SetLogCB (LogCallback cb); -void XRCORE_API CreateLog (BOOL no_log=FALSE); -void InitLog (); -void CloseLog (); -void XRCORE_API FlushLog (); +typedef void(*LogCallback) (LPCSTR string); +LogCallback XRCORE_API SetLogCB(LogCallback cb); +void XRCORE_API CreateLog(BOOL no_log = FALSE); +void InitLog(); +void CloseLog(); +void XRCORE_API FlushLog(); -extern XRCORE_API xr_vector* LogFile; -extern XRCORE_API BOOL LogExecCB; +extern XRCORE_API xr_vector* LogFile; +extern XRCORE_API BOOL LogExecCB; #endif diff --git a/src/xrCore/lzhuf.h b/src/xrCore/lzhuf.h index 7418a4b5800..fe094eef869 100644 --- a/src/xrCore/lzhuf.h +++ b/src/xrCore/lzhuf.h @@ -1,10 +1,10 @@ #ifndef _LZ_H_ #define _LZ_H_ -extern XRCORE_API unsigned _writeLZ (int hf, void* d, unsigned size); -extern XRCORE_API unsigned _readLZ (int hf, void* &d, unsigned size); +extern XRCORE_API unsigned _writeLZ(int hf, void* d, unsigned size); +extern XRCORE_API unsigned _readLZ(int hf, void*& d, unsigned size); -extern XRCORE_API void _compressLZ (u8** dest, unsigned* dest_sz, void* src, unsigned src_sz); -extern XRCORE_API void _decompressLZ (u8** dest, unsigned* dest_sz, void* src, unsigned src_sz); +extern XRCORE_API void _compressLZ(u8** dest, unsigned* dest_sz, void* src, unsigned src_sz); +extern XRCORE_API void _decompressLZ(u8** dest, unsigned* dest_sz, void* src, unsigned src_sz); #endif diff --git a/src/xrCore/lzo_compressor.cpp b/src/xrCore/lzo_compressor.cpp index 14782dd9b4e..9013c6a7613 100644 --- a/src/xrCore/lzo_compressor.cpp +++ b/src/xrCore/lzo_compressor.cpp @@ -1,28 +1,24 @@ #include "stdafx.h" #include "lzo_compressor.h" -int lzo_compress_dict(const lzo_bytep in , lzo_uint in_len, - lzo_bytep out, lzo_uintp out_len, - lzo_voidp wrkmem, - const lzo_bytep dict, lzo_uint dict_len) +int lzo_compress_dict(const lzo_bytep in, lzo_uint in_len, + lzo_bytep out, lzo_uintp out_len, + lzo_voidp wrkmem, + const lzo_bytep dict, lzo_uint dict_len) { - return lzo1x_999_compress_dict( - in, in_len, out, out_len, wrkmem, dict, dict_len - ); + return lzo1x_999_compress_dict(in, in_len, out, out_len, wrkmem, dict, dict_len); } -int lzo_decompress_dict(const lzo_bytep in, lzo_uint in_len, - lzo_bytep out, lzo_uintp out_len, - lzo_voidp wrkmem /* NOT USED */, - const lzo_bytep dict, lzo_uint dict_len) +int lzo_decompress_dict(const lzo_bytep in, lzo_uint in_len, + lzo_bytep out, lzo_uintp out_len, + lzo_voidp wrkmem /* NOT USED */, + const lzo_bytep dict, lzo_uint dict_len) { - return lzo1x_decompress_dict_safe( - in, in_len, out, out_len, wrkmem, dict, dict_len - ); + return lzo1x_decompress_dict_safe(in, in_len, out, out_len, wrkmem, dict, dict_len); } int lzo_initialize() { - return lzo_init(); + return lzo_init(); } diff --git a/src/xrCore/lzo_compressor.h b/src/xrCore/lzo_compressor.h index 0cd83e49df0..2d6acd78f35 100644 --- a/src/xrCore/lzo_compressor.h +++ b/src/xrCore/lzo_compressor.h @@ -4,18 +4,16 @@ #include "rt_lzo1x.h" XRCORE_API int lzo_compress_dict( - const lzo_bytep in , lzo_uint in_len, - lzo_bytep out, lzo_uintp out_len, - lzo_voidp wrkmem, - const lzo_bytep dict, lzo_uint dict_len -); + const lzo_bytep in, lzo_uint in_len, + lzo_bytep out, lzo_uintp out_len, + lzo_voidp wrkmem, + const lzo_bytep dict, lzo_uint dict_len); XRCORE_API int lzo_decompress_dict( - const lzo_bytep in, lzo_uint in_len, - lzo_bytep out, lzo_uintp out_len, - lzo_voidp wrkmem /* NOT USED */, - const lzo_bytep dict, lzo_uint dict_len -); + const lzo_bytep in, lzo_uint in_len, + lzo_bytep out, lzo_uintp out_len, + lzo_voidp wrkmem /* NOT USED */, + const lzo_bytep dict, lzo_uint dict_len); XRCORE_API int lzo_initialize(); diff --git a/src/xrCore/memory_allocation_stats.cpp b/src/xrCore/memory_allocation_stats.cpp index 92ab026beae..3548922a00a 100644 --- a/src/xrCore/memory_allocation_stats.cpp +++ b/src/xrCore/memory_allocation_stats.cpp @@ -1,133 +1,139 @@ #include "stdafx.h" #ifdef DEBUG_MEMORY_MANAGER -# pragma warning(push) -# pragma warning(disable:4995) -# include -# pragma warning(pop) - -# include - - extern void BuildStackTrace (); - - extern char g_stackTrace[100][4096]; - extern int g_stackTraceCount; - - static bool g_mem_alloc_gather_stats = false; - static float g_mem_alloc_gather_stats_frequency = 0.f; - - typedef std::pair STATS_PAIR; - typedef std::multimap STATS; - static STATS stats; - - void mem_alloc_gather_stats (const bool &value) - { - g_mem_alloc_gather_stats = value; - } - - void mem_alloc_gather_stats_frequency (const float &value) - { - g_mem_alloc_gather_stats_frequency = value; - } - - void mem_alloc_show_stats () - { - u32 size = (u32)stats.size(); - STATS_PAIR *strings = (STATS_PAIR*)_alloca(size*sizeof(STATS_PAIR)); - STATS_PAIR *e = strings + size; - STATS_PAIR *i = strings; - - u32 accumulator = 0; - STATS::const_iterator I = stats.begin(); - STATS::const_iterator E = stats.end(); - for ( ; I != E; ++I, ++i) { - *i = (*I).second; - accumulator += (*I).second.second; - } - - struct predicate { - static inline bool compare (const STATS_PAIR &_0, const STATS_PAIR &_1) - { - return (_0.second < _1.second); - } - }; - - std::sort (strings,e,predicate::compare); - - int j = 0; - for (i = strings; i != e; ++i, ++j) { - Msg ("%d(%d)-----------------%d[%d]:%5.2f%%------------------",j,size,(*i).second,accumulator,((*i).second*100)/float(accumulator)); - Log ((*i).first); - } - } - - void mem_alloc_clear_stats () - { - STATS::iterator I = stats.begin(); - STATS::iterator E = stats.end(); - for ( ; I != E; ++I) - free ((*I).second.first); - - stats.clear (); - } - - __declspec(noinline) - void save_stack_trace () - { - if (!g_mem_alloc_gather_stats) - return; - - if (::Random.randF() >= g_mem_alloc_gather_stats_frequency) - return; - -// OutputDebugStackTrace ("----------------------------------------------------"); - - BuildStackTrace (); - - if (g_stackTraceCount <= 2) - return; - - u32 accumulator = 0; - VERIFY (g_stackTraceCount > 2); - int *lengths = (int*)_alloca((g_stackTraceCount - 2)*sizeof(int)); - { - int *I = lengths; - for (int i=2; i 2); - int *I = lengths; - for (int i=2; i +# pragma warning(pop) + +# include + +extern void BuildStackTrace (); + +extern char g_stackTrace[100][4096]; +extern int g_stackTraceCount; + +static bool g_mem_alloc_gather_stats = false; +static float g_mem_alloc_gather_stats_frequency = 0.f; + +typedef std::pair STATS_PAIR; +typedef std::multimap STATS; +static STATS stats; + +void mem_alloc_gather_stats (const bool& value) +{ + g_mem_alloc_gather_stats = value; +} + +void mem_alloc_gather_stats_frequency (const float& value) +{ + g_mem_alloc_gather_stats_frequency = value; +} + +void mem_alloc_show_stats () +{ + u32 size = (u32)stats.size(); + STATS_PAIR* strings = (STATS_PAIR*)_alloca(size*sizeof(STATS_PAIR)); + STATS_PAIR* e = strings + size; + STATS_PAIR* i = strings; + + u32 accumulator = 0; + STATS::const_iterator I = stats.begin(); + STATS::const_iterator E = stats.end(); + for ( ; I != E; ++I, ++i) + { + *i = (*I).second; + accumulator += (*I).second.second; + } + + struct predicate + { + static inline bool compare (const STATS_PAIR& _0, const STATS_PAIR& _1) + { + return (_0.second < _1.second); + } + }; + + std::sort (strings,e,predicate::compare); + + int j = 0; + for (i = strings; i != e; ++i, ++j) + { + Msg ("%d(%d)-----------------%d[%d]:%5.2f%%------------------",j,size,(*i).second,accumulator,((*i).second*100)/float(accumulator)); + Log ((*i).first); + } +} + +void mem_alloc_clear_stats () +{ + STATS::iterator I = stats.begin(); + STATS::iterator E = stats.end(); + for ( ; I != E; ++I) + free ((*I).second.first); + + stats.clear (); +} + +__declspec(noinline) +void save_stack_trace () +{ + if (!g_mem_alloc_gather_stats) + return; + + if (::Random.randF() >= g_mem_alloc_gather_stats_frequency) + return; + + // OutputDebugStackTrace ("----------------------------------------------------"); + + BuildStackTrace (); + + if (g_stackTraceCount <= 2) + return; + + u32 accumulator = 0; + VERIFY (g_stackTraceCount > 2); + int* lengths = (int*)_alloca((g_stackTraceCount - 2)*sizeof(int)); + { + int* I = lengths; + for (int i=2; i 2); + int* I = lengths; + for (int i=2; i -# include +# include +# include #define STATIC -//#define STATIC static +//#define STATIC static // constants -STATIC const u32 buffer_size = 512*1024; -STATIC LPCSTR output_folder = "d:/memory_monitor_stats/"; -STATIC LPCSTR output_extension = ".bin"; +STATIC const u32 buffer_size = 512 * 1024; +STATIC LPCSTR output_folder = "d:/memory_monitor_stats/"; +STATIC LPCSTR output_extension = ".bin"; // for internal use only -STATIC bool detaching = false; -STATIC CRITICAL_SECTION critical_section; +STATIC bool detaching = false; +STATIC CRITICAL_SECTION critical_section; -namespace memory_monitor { +namespace memory_monitor +{ LPCSTR inline file_name() { - static string_path file = " "; - if(file[0]==' '){ - _mkdir (output_folder); - - __time64_t long_time; - _time64 (&long_time); - tm new_time; - new_time = *_localtime64(&long_time); - string256 file_name; - strftime (file_name,sizeof(file_name),"%Y.%m.%d.%H.%M.%S",&new_time); - strconcat (sizeof(file),file,output_folder,file_name,output_extension); - } - return file; + static string_path file = " "; + if (file[0] == ' ') + { + _mkdir(output_folder); + + __time64_t long_time; + _time64(&long_time); + tm new_time; + new_time = *_localtime64(&long_time); + string256 file_name; + strftime(file_name, sizeof(file_name), "%Y.%m.%d.%H.%M.%S", &new_time); + strconcat(sizeof(file), file, output_folder, file_name, output_extension); + } + return file; } -STATIC inline FILE *file() +STATIC inline FILE* file() { - static FILE *m_file = 0; - static char buffer[buffer_size]; - if (!m_file) { - m_file = fopen(file_name(),"wb"); - VERIFY (m_file); - setvbuf (m_file,buffer,_IOFBF,buffer_size); - } - - return (m_file); + static FILE* m_file = 0; + static char buffer[buffer_size]; + if (!m_file) + { + m_file = fopen(file_name(), "wb"); + VERIFY(m_file); + setvbuf(m_file, buffer, _IOFBF, buffer_size); + } + + return (m_file); } -union _allocation_size { - struct { - u32 allocation : 1; - u32 size : 31; - }; - u32 allocation_size; +union _allocation_size +{ + struct + { + u32 allocation : 1; + u32 size : 31; + }; + u32 allocation_size; }; -STATIC bool use_monitor () +STATIC bool use_monitor() { - return (!!strstr(GetCommandLine(),"-memory_monitor")); + return (!!strstr(GetCommandLine(), "-memory_monitor")); } } -void memory_monitor::flush_each_time (const bool &value) +void memory_monitor::flush_each_time(const bool& value) { - if (!use_monitor()) - return; + if (!use_monitor()) + return; - detaching = value; - if (detaching) - fflush (file()); + detaching = value; + if (detaching) + fflush(file()); } -namespace memory_monitor { -STATIC void initialize () +namespace memory_monitor +{ +STATIC void initialize() { - VERIFY (use_monitor()); - InitializeCriticalSection (&critical_section); + VERIFY(use_monitor()); + InitializeCriticalSection(&critical_section); } } XRCORE_API int memory_monitor::counter = 0; XRCORE_API int memory_monitor::counter_alloc = 0; XRCORE_API int memory_monitor::counter_free = 0; -void memory_monitor::monitor_alloc (const void *allocation_address, const u32 &allocation_size, LPCSTR allocation_description) +void memory_monitor::monitor_alloc(const void* allocation_address, const u32& allocation_size, LPCSTR allocation_description) { - counter++; - counter_alloc++; - //if(0==stricmp(allocation_description,"char")) - //{ - // int d = 65+56; - //} - if (!use_monitor()) - return; - static bool initialized = false; - if (!initialized) { - initialized = true; - initialize (); - } - -// if (!detaching) - EnterCriticalSection (&critical_section); - - _allocation_size temp; - temp.allocation = 1; - temp.size = allocation_size; - fwrite (&temp,sizeof(temp),1,file()); - fwrite (&allocation_address,sizeof(allocation_address),1,file()); - fwrite (allocation_description,(xr_strlen(allocation_description) + 1)*sizeof(char),1,file()); - - if (!detaching) - ; - else - fflush (file()); - - LeaveCriticalSection (&critical_section); + counter++; + counter_alloc++; + //if(0==stricmp(allocation_description,"char")) + //{ + // int d = 65+56; + //} + if (!use_monitor()) + return; + static bool initialized = false; + if (!initialized) + { + initialized = true; + initialize(); + } + + // if (!detaching) + EnterCriticalSection(&critical_section); + + _allocation_size temp; + temp.allocation = 1; + temp.size = allocation_size; + fwrite(&temp, sizeof(temp), 1, file()); + fwrite(&allocation_address, sizeof(allocation_address), 1, file()); + fwrite(allocation_description, (xr_strlen(allocation_description) + 1)*sizeof(char), 1, file()); + + if (!detaching) + ; + else + fflush(file()); + + LeaveCriticalSection(&critical_section); } -void memory_monitor::monitor_free (const void *deallocation_address) +void memory_monitor::monitor_free(const void* deallocation_address) { - counter++; - counter_free++; - if (!use_monitor()) - return; - -// if (!detaching) - EnterCriticalSection (&critical_section); - - if (deallocation_address) { - _allocation_size temp; - temp.allocation_size = 0; - fwrite (&temp,sizeof(temp),1,file()); - fwrite (&deallocation_address,sizeof(deallocation_address),1,file()); - } - - if (!detaching) - ; - else - fflush (file()); - - LeaveCriticalSection (&critical_section); + counter++; + counter_free++; + if (!use_monitor()) + return; + + // if (!detaching) + EnterCriticalSection(&critical_section); + + if (deallocation_address) + { + _allocation_size temp; + temp.allocation_size = 0; + fwrite(&temp, sizeof(temp), 1, file()); + fwrite(&deallocation_address, sizeof(deallocation_address), 1, file()); + } + + if (!detaching) + ; + else + fflush(file()); + + LeaveCriticalSection(&critical_section); } -void memory_monitor::make_checkpoint (LPCSTR checkpoint_name) +void memory_monitor::make_checkpoint(LPCSTR checkpoint_name) { - fflush (file()); - string_path fn; - strconcat (sizeof(fn),fn,output_folder,checkpoint_name,output_extension); + fflush(file()); + string_path fn; + strconcat(sizeof(fn), fn, output_folder, checkpoint_name, output_extension); - Msg ("Creating memory checkpoint file[%s]...", fn); - CopyFile (file_name(),fn,FALSE); - Msg ("Done"); + Msg("Creating memory checkpoint file[%s]...", fn); + CopyFile(file_name(), fn, FALSE); + Msg("Done"); } #endif // USE_MEMORY_MONITOR \ No newline at end of file diff --git a/src/xrCore/memory_monitor.h b/src/xrCore/memory_monitor.h index 50bc27bea90..ec89b99b1c6 100644 --- a/src/xrCore/memory_monitor.h +++ b/src/xrCore/memory_monitor.h @@ -2,21 +2,22 @@ #define MEMORY_MONITOR_H #ifdef DEBUG - #ifndef _EDITOR - #define USE_MEMORY_MONITOR - #endif // _EDITOR +#ifndef _EDITOR +#define USE_MEMORY_MONITOR +#endif // _EDITOR #endif // DEBUG #ifdef USE_MEMORY_MONITOR -namespace memory_monitor { - XRCORE_API void flush_each_time (const bool &value); - XRCORE_API void monitor_alloc (const void *pointer, const u32 &size, LPCSTR description); - XRCORE_API void monitor_free (const void *pointer); - XRCORE_API void make_checkpoint (LPCSTR name); - extern XRCORE_API int counter; - extern XRCORE_API int counter_alloc; - extern XRCORE_API int counter_free; +namespace memory_monitor +{ +XRCORE_API void flush_each_time(const bool& value); +XRCORE_API void monitor_alloc(const void* pointer, const u32& size, LPCSTR description); +XRCORE_API void monitor_free(const void* pointer); +XRCORE_API void make_checkpoint(LPCSTR name); +extern XRCORE_API int counter; +extern XRCORE_API int counter_alloc; +extern XRCORE_API int counter_free; } #endif // USE_MEMORY_MONITOR diff --git a/src/xrCore/memory_usage.cpp b/src/xrCore/memory_usage.cpp index 68a49b18cd0..a4663ce985f 100644 --- a/src/xrCore/memory_usage.cpp +++ b/src/xrCore/memory_usage.cpp @@ -2,36 +2,39 @@ #include #include -XRCORE_API void vminfo (size_t *_free, size_t *reserved, size_t *committed) { - MEMORY_BASIC_INFORMATION memory_info; - memory_info.BaseAddress = 0; - *_free = *reserved = *committed = 0; - while (VirtualQuery (memory_info.BaseAddress, &memory_info, sizeof (memory_info))) { - switch (memory_info.State) { - case MEM_FREE: - *_free += memory_info.RegionSize; - break; - case MEM_RESERVE: - *reserved += memory_info.RegionSize; - break; - case MEM_COMMIT: - *committed += memory_info.RegionSize; - break; - } - memory_info.BaseAddress = (char *) memory_info.BaseAddress + memory_info.RegionSize; - } +XRCORE_API void vminfo(size_t* _free, size_t* reserved, size_t* committed) +{ + MEMORY_BASIC_INFORMATION memory_info; + memory_info.BaseAddress = 0; + *_free = *reserved = *committed = 0; + while (VirtualQuery(memory_info.BaseAddress, &memory_info, sizeof(memory_info))) + { + switch (memory_info.State) + { + case MEM_FREE: + *_free += memory_info.RegionSize; + break; + case MEM_RESERVE: + *reserved += memory_info.RegionSize; + break; + case MEM_COMMIT: + *committed += memory_info.RegionSize; + break; + } + memory_info.BaseAddress = (char*)memory_info.BaseAddress + memory_info.RegionSize; + } } -XRCORE_API void log_vminfo () +XRCORE_API void log_vminfo() { - size_t w_free, w_reserved, w_committed; - vminfo (&w_free, &w_reserved, &w_committed); - Msg ( - "* [win32]: free[%d K], reserved[%d K], committed[%d K]", - w_free/1024, - w_reserved/1024, - w_committed/1024 - ); + size_t w_free, w_reserved, w_committed; + vminfo(&w_free, &w_reserved, &w_committed); + Msg( + "* [win32]: free[%d K], reserved[%d K], committed[%d K]", + w_free / 1024, + w_reserved / 1024, + w_committed / 1024 + ); } size_t xrMemory::mem_usage() diff --git a/src/xrCore/net_utils.h b/src/xrCore/net_utils.h index 39177966b27..1e1d1029b32 100644 --- a/src/xrCore/net_utils.h +++ b/src/xrCore/net_utils.h @@ -6,266 +6,272 @@ #pragma pack(push,1) -const u32 NET_PacketSizeLimit = 16*1024; +const u32 NET_PacketSizeLimit = 16 * 1024; struct XRCORE_API IIniFileStream { - virtual void __stdcall move_begin () = 0; - - virtual void __stdcall w_float ( float a) = 0; - virtual void __stdcall w_vec3 ( const Fvector& a) = 0; - virtual void __stdcall w_vec4 ( const Fvector4& a) = 0; - virtual void __stdcall w_u64 ( u64 a) = 0; - virtual void __stdcall w_s64 ( s64 a) = 0; - virtual void __stdcall w_u32 ( u32 a) = 0; - virtual void __stdcall w_s32 ( s32 a) = 0; - virtual void __stdcall w_u16 ( u16 a) = 0; - virtual void __stdcall w_s16 ( s16 a) = 0; - virtual void __stdcall w_u8 ( u8 a) = 0; - virtual void __stdcall w_s8 ( s8 a) = 0; - virtual void __stdcall w_stringZ ( LPCSTR S) = 0; - - virtual void __stdcall r_vec3 (Fvector&) = 0; - virtual void __stdcall r_vec4 (Fvector4&) = 0; - virtual void __stdcall r_float (float&) = 0; - virtual void __stdcall r_u8 (u8&) = 0; - virtual void __stdcall r_u16 (u16&) = 0; - virtual void __stdcall r_u32 (u32&) = 0; - virtual void __stdcall r_u64 (u64&) = 0; - virtual void __stdcall r_s8 (s8&) = 0; - virtual void __stdcall r_s16 (s16&) = 0; - virtual void __stdcall r_s32 (s32&) = 0; - virtual void __stdcall r_s64 (s64&) = 0; - - virtual void __stdcall r_string (LPSTR dest, u32 dest_size) = 0; -// virtual void __stdcall r_tell () = 0; -// virtual void __stdcall r_seek (u32 pos) = 0; - virtual void __stdcall skip_stringZ () = 0; + virtual void __stdcall move_begin() = 0; + + virtual void __stdcall w_float(float a) = 0; + virtual void __stdcall w_vec3(const Fvector& a) = 0; + virtual void __stdcall w_vec4(const Fvector4& a) = 0; + virtual void __stdcall w_u64(u64 a) = 0; + virtual void __stdcall w_s64(s64 a) = 0; + virtual void __stdcall w_u32(u32 a) = 0; + virtual void __stdcall w_s32(s32 a) = 0; + virtual void __stdcall w_u16(u16 a) = 0; + virtual void __stdcall w_s16(s16 a) = 0; + virtual void __stdcall w_u8(u8 a) = 0; + virtual void __stdcall w_s8(s8 a) = 0; + virtual void __stdcall w_stringZ(LPCSTR S) = 0; + + virtual void __stdcall r_vec3(Fvector&) = 0; + virtual void __stdcall r_vec4(Fvector4&) = 0; + virtual void __stdcall r_float(float&) = 0; + virtual void __stdcall r_u8(u8&) = 0; + virtual void __stdcall r_u16(u16&) = 0; + virtual void __stdcall r_u32(u32&) = 0; + virtual void __stdcall r_u64(u64&) = 0; + virtual void __stdcall r_s8(s8&) = 0; + virtual void __stdcall r_s16(s16&) = 0; + virtual void __stdcall r_s32(s32&) = 0; + virtual void __stdcall r_s64(s64&) = 0; + + virtual void __stdcall r_string(LPSTR dest, u32 dest_size) = 0; + // virtual void __stdcall r_tell () = 0; + // virtual void __stdcall r_seek (u32 pos) = 0; + virtual void __stdcall skip_stringZ() = 0; }; #define INI_W(what_to_do)\ if(inistream)\ {\ - inistream->what_to_do;\ + inistream->what_to_do;\ } #define INI_ASSERT(what_to_do)\ {\ if(inistream)\ - R_ASSERT3(0,#what_to_do,"not implemented");\ + R_ASSERT3(0,#what_to_do,"not implemented");\ } -struct NET_Buffer +struct NET_Buffer { - BYTE data [NET_PacketSizeLimit]; - u32 count; + BYTE data[NET_PacketSizeLimit]; + u32 count; }; class XRCORE_API NET_Packet { public: - IIniFileStream* inistream; - - void construct( const void* data, unsigned size ) - { - memcpy( B.data, data, size ); - B.count = size; - } - - NET_Buffer B; - u32 r_pos; - u32 timeReceive; - bool w_allow; + IIniFileStream* inistream; + + void construct(const void* data, unsigned size) + { + memcpy(B.data, data, size); + B.count = size; + } + + NET_Buffer B; + u32 r_pos; + u32 timeReceive; + bool w_allow; public: - NET_Packet ():inistream(NULL),w_allow(true) {} - // writing - main - IC void write_start () { B.count=0; INI_W(move_begin());} - IC void w_begin ( u16 type ) { B.count=0; w_u16(type);} - - struct W_guard{ - bool* guarded; - W_guard(bool* b):guarded(b){*b=true;} - ~W_guard(){*guarded=false;} - }; - IC void w ( const void* p, u32 count ) - { - R_ASSERT (inistream==NULL || w_allow); - VERIFY (p && count); - VERIFY (B.count + count < NET_PacketSizeLimit); - CopyMemory(&B.data[B.count],p,count); - B.count += count; - VERIFY (B.count=min && a<=max); - float q = (a-min)/(max-min); - w_u16( u16(iFloor(q*65535.f+0.5f))); - } - IC void w_float_q8 ( float a, float min, float max) - { - VERIFY (a>=min && a<=max); - float q = (a-min)/(max-min); - w_u8( u8(iFloor(q*255.f+0.5f))); - } - IC void w_angle16 ( float a ) { w_float_q16 (angle_normalize(a),0,PI_MUL_2);} - IC void w_angle8 ( float a ) {w_float_q8 (angle_normalize(a),0,PI_MUL_2); } - IC void w_dir ( const Fvector& D) {w_u16(pvCompress(D)); } - IC void w_sdir ( const Fvector& D) { - Fvector C; - float mag = D.magnitude(); - if (mag>EPS_S) { - C.div (D,mag); - } else { - C.set (0,0,1); - mag = 0; - } - w_dir (C); - w_float (mag); - } - IC void w_stringZ ( LPCSTR S ) { W_guard g(&w_allow); w(S,(u32)xr_strlen(S)+1); INI_W(w_stringZ(S)); } - IC void w_stringZ ( const shared_str& p) - { - W_guard g(&w_allow); - if (*p) - w(*p,p.size()+1); - else{ - IIniFileStream* tmp = inistream; - inistream = NULL; - w_u8(0); - inistream = tmp; //hack -( - } - - INI_W (w_stringZ(p.c_str())); - } - IC void w_matrix (Fmatrix& M) - { - w_vec3 (M.i); - w_vec3 (M.j); - w_vec3 (M.k); - w_vec3 (M.c); - } - - IC void w_clientID (ClientID& C) { w_u32(C.value()); } - - IC void w_chunk_open8 (u32& position) - { - position = w_tell(); - w_u8 (0); - INI_ASSERT (w_chunk_open8) - } - - IC void w_chunk_close8 (u32 position) - { - u32 size = u32(w_tell() - position) - sizeof(u8); - VERIFY (size<256 ); - u8 _size = (u8)size; - w_seek (position,&_size,sizeof(_size)); - INI_ASSERT (w_chunk_close8) - } - - IC void w_chunk_open16 (u32& position) - { - position = w_tell (); - w_u16 (0); - INI_ASSERT (w_chunk_open16) - } - - IC void w_chunk_close16 (u32 position) - { - u32 size = u32(w_tell() - position) - sizeof(u16); - VERIFY (size < 65536); - u16 _size = (u16)size; - w_seek (position,&_size,sizeof(_size)); - INI_ASSERT (w_chunk_close16) - } - - // reading - void read_start (); - u32 r_begin ( u16& type ); - void r_seek (u32 pos); - u32 r_tell (); - - IC void r ( void* p, u32 count) - { - R_ASSERT (inistream==NULL); - VERIFY (p && count); - CopyMemory (p,&B.data[r_pos],count); - r_pos += count; - VERIFY (r_pos<=B.count); - } - BOOL r_eof (); - u32 r_elapsed (); - void r_advance (u32 size); - - // reading - utilities - void r_vec3 (Fvector& A); - void r_vec4 (Fvector4& A); - void r_float (float& A ); - void r_u64 (u64& A); - void r_s64 (s64& A); - void r_u32 (u32& A); - void r_s32 (s32& A); - void r_u16 (u16& A); - void r_s16 (s16& A); - void r_u8 (u8& A); - void r_s8 (s8& A); - - // IReader compatibility - Fvector r_vec3 (); - Fvector4 r_vec4 (); - float r_float_q8 (float min,float max); - float r_float_q16 (float min, float max); - float r_float (); - u64 r_u64 (); - s64 r_s64 (); - u32 r_u32 (); - s32 r_s32 (); - u16 r_u16 (); - s16 r_s16 (); - u8 r_u8 (); - s8 r_s8 (); - - void r_float_q16 (float& A, float min, float max); - void r_float_q8 (float& A, float min, float max); - void r_angle16 (float& A); - void r_angle8 (float& A); - void r_dir (Fvector& A); - - void r_sdir (Fvector& A); - void r_stringZ (LPSTR S ); - void r_stringZ (xr_string& dest ); - void r_stringZ (shared_str& dest); - - void skip_stringZ (); - - void r_stringZ_s (LPSTR string, u32 size); - - template - inline void r_stringZ_s (char (&string)[size]) - { - r_stringZ_s (string, size); - } - - void r_matrix (Fmatrix& M); - void r_clientID (ClientID& C); + NET_Packet() :inistream(NULL), w_allow(true) {} + // writing - main + IC void write_start() { B.count = 0; INI_W(move_begin()); } + IC void w_begin(u16 type) { B.count = 0; w_u16(type); } + + struct W_guard + { + bool* guarded; + W_guard(bool* b) :guarded(b) { *b = true; } + ~W_guard() { *guarded = false; } + }; + IC void w(const void* p, u32 count) + { + R_ASSERT(inistream == NULL || w_allow); + VERIFY(p && count); + VERIFY(B.count + count < NET_PacketSizeLimit); + CopyMemory(&B.data[B.count], p, count); + B.count += count; + VERIFY(B.count < NET_PacketSizeLimit); + } + IC void w_seek(u32 pos, const void* p, u32 count); + IC u32 w_tell() { return B.count; } + + // writing - utilities + IC void w_float(float a) { W_guard g(&w_allow); w(&a, 4); INI_W(w_float(a)); } // float + IC void w_vec3(const Fvector& a) { W_guard g(&w_allow); w(&a, 3 * sizeof(float)); INI_W(w_vec3(a)); } // vec3 + IC void w_vec4(const Fvector4& a) { W_guard g(&w_allow); w(&a, 4 * sizeof(float)); INI_W(w_vec4(a)); } // vec4 + IC void w_u64(u64 a) { W_guard g(&w_allow); w(&a, 8); INI_W(w_u64(a)); } // qword (8b) + IC void w_s64(s64 a) { W_guard g(&w_allow); w(&a, 8); INI_W(w_s64(a)); } // qword (8b) + IC void w_u32(u32 a) { W_guard g(&w_allow); w(&a, 4); INI_W(w_u32(a)); } // dword (4b) + IC void w_s32(s32 a) { W_guard g(&w_allow); w(&a, 4); INI_W(w_s32(a)); } // dword (4b) + IC void w_u16(u16 a) { W_guard g(&w_allow); w(&a, 2); INI_W(w_u16(a)); } // word (2b) + IC void w_s16(s16 a) { W_guard g(&w_allow); w(&a, 2); INI_W(w_s16(a)); } // word (2b) + IC void w_u8(u8 a) { W_guard g(&w_allow); w(&a, 1); INI_W(w_u8(a)); } // byte (1b) + IC void w_s8(s8 a) { W_guard g(&w_allow); w(&a, 1); INI_W(w_s8(a)); } // byte (1b) + + IC void w_float_q16(float a, float min, float max) + { + VERIFY(a >= min && a <= max); + float q = (a - min) / (max - min); + w_u16(u16(iFloor(q*65535.f + 0.5f))); + } + IC void w_float_q8(float a, float min, float max) + { + VERIFY(a >= min && a <= max); + float q = (a - min) / (max - min); + w_u8(u8(iFloor(q*255.f + 0.5f))); + } + IC void w_angle16(float a) { w_float_q16(angle_normalize(a), 0, PI_MUL_2); } + IC void w_angle8(float a) { w_float_q8(angle_normalize(a), 0, PI_MUL_2); } + IC void w_dir(const Fvector& D) { w_u16(pvCompress(D)); } + IC void w_sdir(const Fvector& D) + { + Fvector C; + float mag = D.magnitude(); + if (mag > EPS_S) + { + C.div(D, mag); + } + else + { + C.set(0, 0, 1); + mag = 0; + } + w_dir(C); + w_float(mag); + } + IC void w_stringZ(LPCSTR S) { W_guard g(&w_allow); w(S, (u32)xr_strlen(S) + 1); INI_W(w_stringZ(S)); } + IC void w_stringZ(const shared_str& p) + { + W_guard g(&w_allow); + if (*p) + w(*p, p.size() + 1); + else + { + IIniFileStream* tmp = inistream; + inistream = NULL; + w_u8(0); + inistream = tmp; //hack -( + } + + INI_W(w_stringZ(p.c_str())); + } + IC void w_matrix(Fmatrix& M) + { + w_vec3(M.i); + w_vec3(M.j); + w_vec3(M.k); + w_vec3(M.c); + } + + IC void w_clientID(ClientID& C) { w_u32(C.value()); } + + IC void w_chunk_open8(u32& position) + { + position = w_tell(); + w_u8(0); + INI_ASSERT(w_chunk_open8) + } + + IC void w_chunk_close8(u32 position) + { + u32 size = u32(w_tell() - position) - sizeof(u8); + VERIFY(size < 256); + u8 _size = (u8)size; + w_seek(position, &_size, sizeof(_size)); + INI_ASSERT(w_chunk_close8) + } + + IC void w_chunk_open16(u32& position) + { + position = w_tell(); + w_u16(0); + INI_ASSERT(w_chunk_open16) + } + + IC void w_chunk_close16(u32 position) + { + u32 size = u32(w_tell() - position) - sizeof(u16); + VERIFY(size < 65536); + u16 _size = (u16)size; + w_seek(position, &_size, sizeof(_size)); + INI_ASSERT(w_chunk_close16) + } + + // reading + void read_start(); + u32 r_begin(u16& type); + void r_seek(u32 pos); + u32 r_tell(); + + IC void r(void* p, u32 count) + { + R_ASSERT(inistream == NULL); + VERIFY(p && count); + CopyMemory(p, &B.data[r_pos], count); + r_pos += count; + VERIFY(r_pos <= B.count); + } + BOOL r_eof(); + u32 r_elapsed(); + void r_advance(u32 size); + + // reading - utilities + void r_vec3(Fvector& A); + void r_vec4(Fvector4& A); + void r_float(float& A); + void r_u64(u64& A); + void r_s64(s64& A); + void r_u32(u32& A); + void r_s32(s32& A); + void r_u16(u16& A); + void r_s16(s16& A); + void r_u8(u8& A); + void r_s8(s8& A); + + // IReader compatibility + Fvector r_vec3(); + Fvector4 r_vec4(); + float r_float_q8(float min, float max); + float r_float_q16(float min, float max); + float r_float(); + u64 r_u64(); + s64 r_s64(); + u32 r_u32(); + s32 r_s32(); + u16 r_u16(); + s16 r_s16(); + u8 r_u8(); + s8 r_s8(); + + void r_float_q16(float& A, float min, float max); + void r_float_q8(float& A, float min, float max); + void r_angle16(float& A); + void r_angle8(float& A); + void r_dir(Fvector& A); + + void r_sdir(Fvector& A); + void r_stringZ(LPSTR S); + void r_stringZ(xr_string& dest); + void r_stringZ(shared_str& dest); + + void skip_stringZ(); + + void r_stringZ_s(LPSTR string, u32 size); + + template + inline void r_stringZ_s(char(&string)[size]) + { + r_stringZ_s(string, size); + } + + void r_matrix(Fmatrix& M); + void r_clientID(ClientID& C); }; #pragma pack(pop) diff --git a/src/xrCore/os_clipboard.cpp b/src/xrCore/os_clipboard.cpp index 376af2f6d77..38d4fcb39ac 100644 --- a/src/xrCore/os_clipboard.cpp +++ b/src/xrCore/os_clipboard.cpp @@ -1,90 +1,91 @@ //////////////////////////////////////////////////////////////////////////// -// Module : os_clipboard.cpp -// Created : 21.02.2008 -// Author : Evgeniy Sokolov -// Description : os clipboard class implementation +// Module : os_clipboard.cpp +// Created : 21.02.2008 +// Author : Evgeniy Sokolov +// Description : os clipboard class implementation //////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #pragma hdrstop #include "os_clipboard.h" -void os_clipboard::copy_to_clipboard ( LPCSTR buf ) +void os_clipboard::copy_to_clipboard(LPCSTR buf) { - if ( !OpenClipboard(0) ) - return; - u32 handle_size = ( xr_strlen(buf) + 1 ) * sizeof(char); - HGLOBAL handle = GlobalAlloc( GHND, handle_size ); - if ( !handle ) - { - CloseClipboard (); - return; - } + if (!OpenClipboard(0)) + return; + u32 handle_size = (xr_strlen(buf) + 1) * sizeof(char); + HGLOBAL handle = GlobalAlloc(GHND, handle_size); + if (!handle) + { + CloseClipboard(); + return; + } - char* memory = (char*)GlobalLock( handle ); - xr_strcpy ( memory, handle_size, buf ); - GlobalUnlock ( handle ); - EmptyClipboard (); - SetClipboardData ( CF_TEXT, handle ); - CloseClipboard (); + char* memory = (char*)GlobalLock(handle); + xr_strcpy(memory, handle_size, buf); + GlobalUnlock(handle); + EmptyClipboard(); + SetClipboardData(CF_TEXT, handle); + CloseClipboard(); } -void os_clipboard::paste_from_clipboard ( LPSTR buffer, u32 const& buffer_size ) +void os_clipboard::paste_from_clipboard(LPSTR buffer, u32 const& buffer_size) { - VERIFY (buffer); - VERIFY (buffer_size > 0); + VERIFY(buffer); + VERIFY(buffer_size > 0); - if (!OpenClipboard(0)) - return; + if (!OpenClipboard(0)) + return; - HGLOBAL hmem = GetClipboardData( CF_TEXT ); - if ( !hmem ) - return; + HGLOBAL hmem = GetClipboardData(CF_TEXT); + if (!hmem) + return; - LPCSTR clipdata = (LPCSTR)GlobalLock( hmem ); - strncpy_s ( buffer, buffer_size, clipdata, buffer_size - 1 ); - buffer[buffer_size - 1] = 0; - for ( u32 i = 0; i < strlen( buffer ); ++i ) - { - char c = buffer[i]; - if ( ( (isprint(c) == 0) && (c != char(-1)) ) || c == '\t' || c == '\n' )// "ÿ" = -1 - { - buffer[i] = ' '; - } - } + LPCSTR clipdata = (LPCSTR)GlobalLock(hmem); + strncpy_s(buffer, buffer_size, clipdata, buffer_size - 1); + buffer[buffer_size - 1] = 0; + for (u32 i = 0; i < strlen(buffer); ++i) + { + char c = buffer[i]; + if (((isprint(c) == 0) && (c != char(-1))) || c == '\t' || c == '\n')// "ÿ" = -1 + { + buffer[i] = ' '; + } + } - GlobalUnlock ( hmem ); - CloseClipboard (); + GlobalUnlock(hmem); + CloseClipboard(); } -void os_clipboard::update_clipboard ( LPCSTR string ) +void os_clipboard::update_clipboard(LPCSTR string) { - if ( !OpenClipboard(0) ) - return; + if (!OpenClipboard(0)) + return; - HGLOBAL handle = GetClipboardData(CF_TEXT); - if (!handle) { - CloseClipboard (); - copy_to_clipboard (string); - return; - } + HGLOBAL handle = GetClipboardData(CF_TEXT); + if (!handle) + { + CloseClipboard(); + copy_to_clipboard(string); + return; + } - LPSTR memory = (LPSTR)GlobalLock(handle); - int memory_length = (int)strlen(memory); - int string_length = (int)strlen(string); - int buffer_size = (memory_length + string_length + 1) * sizeof(char); + LPSTR memory = (LPSTR)GlobalLock(handle); + int memory_length = (int)strlen(memory); + int string_length = (int)strlen(string); + int buffer_size = (memory_length + string_length + 1) * sizeof(char); #ifndef _EDITOR - LPSTR buffer = (LPSTR)_alloca( buffer_size ); + LPSTR buffer = (LPSTR)_alloca(buffer_size); #else // #ifndef _EDITOR - LPSTR buffer = (LPSTR)xr_alloc( buffer_size ); + LPSTR buffer = (LPSTR)xr_alloc( buffer_size ); #endif // #ifndef _EDITOR - xr_strcpy (buffer, buffer_size, memory); - GlobalUnlock (handle); + xr_strcpy(buffer, buffer_size, memory); + GlobalUnlock(handle); - xr_strcat (buffer, buffer_size, string); - CloseClipboard (); - copy_to_clipboard (buffer); + xr_strcat(buffer, buffer_size, string); + CloseClipboard(); + copy_to_clipboard(buffer); #ifdef _EDITOR - xr_free (buffer); + xr_free (buffer); #endif // #ifdef _EDITOR } \ No newline at end of file diff --git a/src/xrCore/os_clipboard.h b/src/xrCore/os_clipboard.h index dac121c3513..fb22aa75c47 100644 --- a/src/xrCore/os_clipboard.h +++ b/src/xrCore/os_clipboard.h @@ -1,9 +1,9 @@ //////////////////////////////////////////////////////////////////////////// -// Module : os_clipboard.h -// Created : 21.02.2008 -// Modified : 04.03.2008 -// Author : Evgeniy Sokolov -// Description : os clipboard class +// Module : os_clipboard.h +// Created : 21.02.2008 +// Modified : 04.03.2008 +// Author : Evgeniy Sokolov +// Description : os clipboard class //////////////////////////////////////////////////////////////////////////// #ifndef OS_CLIPBOARD_H_INCLUDED @@ -11,9 +11,9 @@ namespace os_clipboard { - XRCORE_API void copy_to_clipboard ( LPCSTR buf ); - XRCORE_API void paste_from_clipboard ( LPSTR buf, u32 const& buf_size ); - XRCORE_API void update_clipboard ( LPCSTR str ); +XRCORE_API void copy_to_clipboard(LPCSTR buf); +XRCORE_API void paste_from_clipboard(LPSTR buf, u32 const& buf_size); +XRCORE_API void update_clipboard(LPCSTR str); } // namespace os_clipboard #endif // OS_CLIPBOARD_H_INCLUDED \ No newline at end of file diff --git a/src/xrCore/ppmd_compressor.cpp b/src/xrCore/ppmd_compressor.cpp index 6beff10ff05..a442834ab0e 100644 --- a/src/xrCore/ppmd_compressor.cpp +++ b/src/xrCore/ppmd_compressor.cpp @@ -2,15 +2,15 @@ #include "ppmd_compressor.h" #include "ppmd.h" -const u32 suballocator_size = 32; -const u32 order_model = 8; -const MR_METHOD restoration_method_cut_off = MRM_RESTART; +const u32 suballocator_size = 32; +const u32 order_model = 8; +const MR_METHOD restoration_method_cut_off = MRM_RESTART; -typedef compression::ppmd::stream stream; +typedef compression::ppmd::stream stream; -extern compression::ppmd::stream *trained_model; +extern compression::ppmd::stream* trained_model; -void _STDCALL PrintInfo (_PPMD_FILE* DecodedFile,_PPMD_FILE* EncodedFile) +void _STDCALL PrintInfo(_PPMD_FILE* DecodedFile, _PPMD_FILE* EncodedFile) { } @@ -21,178 +21,178 @@ static LONG PPMd_Locked = 0; static inline void PPMd_Lock() { - while( ::InterlockedExchange( &PPMd_Locked, 1 ) ) - ::Sleep( 0 ); + while (::InterlockedExchange(&PPMd_Locked, 1)) + ::Sleep(0); } static inline void PPMd_Unlock() { - ::InterlockedExchange( &PPMd_Locked, 0 ); + ::InterlockedExchange(&PPMd_Locked, 0); } -void ppmd_initialize () +void ppmd_initialize() { - if (trained_model) - trained_model->rewind (); - - static bool initialized = false; - if (initialized) - return; - - initialized = true; - if (StartSubAllocator(suballocator_size)) - return; - - exit (-1); + if (trained_model) + trained_model->rewind(); + + static bool initialized = false; + if (initialized) + return; + + initialized = true; + if (StartSubAllocator(suballocator_size)) + return; + + exit(-1); } -u32 ppmd_compress (void *dest_buffer, const u32 &dest_buffer_size, const void *source_buffer, const u32 &source_buffer_size) +u32 ppmd_compress(void* dest_buffer, const u32& dest_buffer_size, const void* source_buffer, const u32& source_buffer_size) { PPMd_Lock(); - ppmd_initialize (); + ppmd_initialize(); - stream source(source_buffer,source_buffer_size); - stream dest(dest_buffer,dest_buffer_size); - EncodeFile (&dest,&source,order_model,restoration_method_cut_off); + stream source(source_buffer, source_buffer_size); + stream dest(dest_buffer, dest_buffer_size); + EncodeFile(&dest, &source, order_model, restoration_method_cut_off); - PPMd_Unlock(); - return (dest.tell() + 1); + PPMd_Unlock(); + return (dest.tell() + 1); } -u32 ppmd_trained_compress(void *dest_buffer, const u32 &dest_buffer_size, const void *source_buffer, const u32 &source_buffer_size, - compression::ppmd::stream * tmodel) +u32 ppmd_trained_compress(void* dest_buffer, const u32& dest_buffer_size, const void* source_buffer, const u32& source_buffer_size, + compression::ppmd::stream* tmodel) { - PPMd_Lock(); - - stream* old_stream = trained_model; - trained_model = tmodel; + PPMd_Lock(); + + stream* old_stream = trained_model; + trained_model = tmodel; - ppmd_initialize(); + ppmd_initialize(); - stream source(source_buffer,source_buffer_size); - stream dest(dest_buffer,dest_buffer_size); - EncodeFile (&dest,&source,order_model,restoration_method_cut_off); + stream source(source_buffer, source_buffer_size); + stream dest(dest_buffer, dest_buffer_size); + EncodeFile(&dest, &source, order_model, restoration_method_cut_off); - trained_model = old_stream; + trained_model = old_stream; - PPMd_Unlock(); - return (dest.tell() + 1); + PPMd_Unlock(); + return (dest.tell() + 1); } -u32 ppmd_decompress (void *dest_buffer, const u32 &dest_buffer_size, const void *source_buffer, const u32 &source_buffer_size) +u32 ppmd_decompress(void* dest_buffer, const u32& dest_buffer_size, const void* source_buffer, const u32& source_buffer_size) { PPMd_Lock(); - ppmd_initialize (); + ppmd_initialize(); - stream source(source_buffer,source_buffer_size); - stream dest(dest_buffer,dest_buffer_size); - DecodeFile (&dest,&source,order_model,restoration_method_cut_off); + stream source(source_buffer, source_buffer_size); + stream dest(dest_buffer, dest_buffer_size); + DecodeFile(&dest, &source, order_model, restoration_method_cut_off); - PPMd_Unlock(); - return (dest.tell()); + PPMd_Unlock(); + return (dest.tell()); } -u32 ppmd_trained_decompress(void *dest_buffer, const u32 &dest_buffer_size, const void *source_buffer, const u32 &source_buffer_size, - compression::ppmd::stream * tmodel) +u32 ppmd_trained_decompress(void* dest_buffer, const u32& dest_buffer_size, const void* source_buffer, const u32& source_buffer_size, + compression::ppmd::stream* tmodel) { - PPMd_Lock(); - - stream* old_stream = trained_model; - trained_model = tmodel; + PPMd_Lock(); + + stream* old_stream = trained_model; + trained_model = tmodel; + + ppmd_initialize(); - ppmd_initialize (); - - stream source(source_buffer,source_buffer_size); - stream dest(dest_buffer,dest_buffer_size); - DecodeFile (&dest,&source,order_model,restoration_method_cut_off); + stream source(source_buffer, source_buffer_size); + stream dest(dest_buffer, dest_buffer_size); + DecodeFile(&dest, &source, order_model, restoration_method_cut_off); - trained_model = old_stream; + trained_model = old_stream; - PPMd_Unlock(); - return (dest.tell()); + PPMd_Unlock(); + return (dest.tell()); } static const u32 compress_chunk_size = 100 * 1024; //100 kb -u32 ppmd_compress_mt (void *dest_buffer, const u32 &dest_buffer_size, const void *source_buffer, const u32 &source_buffer_size, ppmd_yield_callback_t ycb) +u32 ppmd_compress_mt(void* dest_buffer, const u32& dest_buffer_size, const void* source_buffer, const u32& source_buffer_size, ppmd_yield_callback_t ycb) { - PPMd_Lock(); - ppmd_initialize (); - - u32 rest_src_buff = source_buffer_size; - u8 const * src_buff_chunk = static_cast(source_buffer); - - u8* curr_dst_buff = static_cast(dest_buffer); - u32 dst_buff_size = dest_buffer_size; - - u32 result_size = 0; - - while (rest_src_buff) - { - u32 to_compress = rest_src_buff > compress_chunk_size ? - compress_chunk_size : rest_src_buff; - - stream source(src_buff_chunk, to_compress); - stream dest(curr_dst_buff, dst_buff_size); - EncodeFile (&dest,&source,order_model,restoration_method_cut_off); - - u32 dst_encoded = dest.tell(); - curr_dst_buff += dst_encoded; - R_ASSERT (dest_buffer_size >= dst_encoded); - dst_buff_size -= dst_encoded; - result_size += dst_encoded; - - src_buff_chunk += to_compress; - rest_src_buff -= to_compress; - if (ycb) - ycb(); - } - - PPMd_Unlock(); - return result_size; + PPMd_Lock(); + ppmd_initialize(); + + u32 rest_src_buff = source_buffer_size; + u8 const* src_buff_chunk = static_cast(source_buffer); + + u8* curr_dst_buff = static_cast(dest_buffer); + u32 dst_buff_size = dest_buffer_size; + + u32 result_size = 0; + + while (rest_src_buff) + { + u32 to_compress = rest_src_buff > compress_chunk_size ? + compress_chunk_size : rest_src_buff; + + stream source(src_buff_chunk, to_compress); + stream dest(curr_dst_buff, dst_buff_size); + EncodeFile(&dest, &source, order_model, restoration_method_cut_off); + + u32 dst_encoded = dest.tell(); + curr_dst_buff += dst_encoded; + R_ASSERT(dest_buffer_size >= dst_encoded); + dst_buff_size -= dst_encoded; + result_size += dst_encoded; + + src_buff_chunk += to_compress; + rest_src_buff -= to_compress; + if (ycb) + ycb(); + } + + PPMd_Unlock(); + return result_size; } -u32 ppmd_decompress_mt (void *dest_buffer, const u32 &dest_buffer_size, const void *source_buffer, const u32 &source_buffer_size, ppmd_yield_callback_t ycb) +u32 ppmd_decompress_mt(void* dest_buffer, const u32& dest_buffer_size, const void* source_buffer, const u32& source_buffer_size, ppmd_yield_callback_t ycb) { - PPMd_Lock(); - ppmd_initialize (); + PPMd_Lock(); + ppmd_initialize(); + + u32 rest_src_buff = source_buffer_size; + u8 const* src_buff_chunk = static_cast(source_buffer); - u32 rest_src_buff = source_buffer_size; - u8 const * src_buff_chunk = static_cast(source_buffer); + u8* curr_dst_buff = static_cast(dest_buffer); + u32 dst_buff_size = dest_buffer_size; - u8* curr_dst_buff = static_cast(dest_buffer); - u32 dst_buff_size = dest_buffer_size; + u32 result_size = 0; - u32 result_size = 0; + while (rest_src_buff) + { + stream source(src_buff_chunk, rest_src_buff); + stream dest(curr_dst_buff, dst_buff_size); + DecodeFile(&dest, &source, order_model, restoration_method_cut_off); - while (rest_src_buff) - { - stream source(src_buff_chunk, rest_src_buff); - stream dest(curr_dst_buff, dst_buff_size); - DecodeFile (&dest,&source,order_model,restoration_method_cut_off); + u32 src_decoded = source.tell(); + src_buff_chunk += src_decoded; + R_ASSERT(rest_src_buff >= src_decoded); + rest_src_buff -= src_decoded; - u32 src_decoded = source.tell(); - src_buff_chunk += src_decoded; - R_ASSERT (rest_src_buff >= src_decoded); - rest_src_buff -= src_decoded; + u32 unpacked = dest.tell(); + curr_dst_buff += unpacked; + R_ASSERT(dst_buff_size >= unpacked); + dst_buff_size -= unpacked; - u32 unpacked = dest.tell(); - curr_dst_buff += unpacked; - R_ASSERT (dst_buff_size >= unpacked); - dst_buff_size -= unpacked; + result_size += unpacked; - result_size += unpacked; - - if (ycb) - ycb(); - } + if (ycb) + ycb(); + } - PPMd_Unlock(); - return result_size; + PPMd_Unlock(); + return result_size; } diff --git a/src/xrCore/ppmd_compressor.h b/src/xrCore/ppmd_compressor.h index eca41e96aba..33c76e8ec3a 100644 --- a/src/xrCore/ppmd_compressor.h +++ b/src/xrCore/ppmd_compressor.h @@ -5,20 +5,20 @@ namespace compression { - namespace ppmd - { - class stream; - } +namespace ppmd +{ +class stream; +} } -XRCORE_API u32 ppmd_compress (void *dest_buffer, const u32 &dest_buffer_size, const void *source_buffer, const u32 &source_buffer_size); -XRCORE_API u32 ppmd_trained_compress (void *dest_buffer, const u32 &dest_buffer_size, const void *source_buffer, const u32 &source_buffer_size, compression::ppmd::stream * tmodel); -XRCORE_API u32 ppmd_decompress (void *dest_buffer, const u32 &dest_buffer_size, const void *source_buffer, const u32 &source_buffer_size); -XRCORE_API u32 ppmd_trained_decompress (void *dest_buffer, const u32 &dest_buffer_size, const void *source_buffer, const u32 &source_buffer_size, compression::ppmd::stream * tmodel); +XRCORE_API u32 ppmd_compress(void* dest_buffer, const u32& dest_buffer_size, const void* source_buffer, const u32& source_buffer_size); +XRCORE_API u32 ppmd_trained_compress(void* dest_buffer, const u32& dest_buffer_size, const void* source_buffer, const u32& source_buffer_size, compression::ppmd::stream* tmodel); +XRCORE_API u32 ppmd_decompress(void* dest_buffer, const u32& dest_buffer_size, const void* source_buffer, const u32& source_buffer_size); +XRCORE_API u32 ppmd_trained_decompress(void* dest_buffer, const u32& dest_buffer_size, const void* source_buffer, const u32& source_buffer_size, compression::ppmd::stream* tmodel); -typedef fastdelegate::FastDelegate ppmd_yield_callback_t; -XRCORE_API u32 ppmd_compress_mt (void *dest_buffer, const u32 &dest_buffer_size, const void *source_buffer, const u32 &source_buffer_size, ppmd_yield_callback_t ycb); -XRCORE_API u32 ppmd_decompress_mt (void *dest_buffer, const u32 &dest_buffer_size, const void *source_buffer, const u32 &source_buffer_size, ppmd_yield_callback_t ycb); +typedef fastdelegate::FastDelegate ppmd_yield_callback_t; +XRCORE_API u32 ppmd_compress_mt(void* dest_buffer, const u32& dest_buffer_size, const void* source_buffer, const u32& source_buffer_size, ppmd_yield_callback_t ycb); +XRCORE_API u32 ppmd_decompress_mt(void* dest_buffer, const u32& dest_buffer_size, const void* source_buffer, const u32& source_buffer_size, ppmd_yield_callback_t ycb); #endif // PPMD_COMPRESSOR_H \ No newline at end of file diff --git a/src/xrCore/resource.h b/src/xrCore/resource.h index aa214e677b3..ec9f8db8a09 100644 --- a/src/xrCore/resource.h +++ b/src/xrCore/resource.h @@ -2,21 +2,21 @@ // Microsoft Visual C++ generated include file. // Used by xrCore.rc // -#define IDD_STOP 101 -#define IDC_DESC 1001 -#define IDC_FILE 1002 -#define IDC_LINE 1003 -#define IDC_ABORT 1004 -#define IDC_STOP 1004 -#define IDC_DEBUG 1005 +#define IDD_STOP 101 +#define IDC_DESC 1001 +#define IDC_FILE 1002 +#define IDC_LINE 1003 +#define IDC_ABORT 1004 +#define IDC_STOP 1004 +#define IDC_DEBUG 1005 // Next default values for new objects -// +// #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 102 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 1005 -#define _APS_NEXT_SYMED_VALUE 101 +#define _APS_NEXT_RESOURCE_VALUE 102 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1005 +#define _APS_NEXT_SYMED_VALUE 101 #endif #endif diff --git a/src/xrCore/rt_compressor.cpp b/src/xrCore/rt_compressor.cpp index 6e72a1479e6..c8eaf7f9847 100644 --- a/src/xrCore/rt_compressor.cpp +++ b/src/xrCore/rt_compressor.cpp @@ -7,41 +7,41 @@ #define HEAP_ALLOC(var,size) \ - lzo_align_t __LZO_MMODEL var [ ((size) + (sizeof(lzo_align_t) - 1)) / sizeof(lzo_align_t) ] + lzo_align_t __LZO_MMODEL var [ ((size) + (sizeof(lzo_align_t) - 1)) / sizeof(lzo_align_t) ] -__declspec(thread) HEAP_ALLOC(rtc_wrkmem,LZO1X_1_MEM_COMPRESS); +__declspec(thread) HEAP_ALLOC(rtc_wrkmem, LZO1X_1_MEM_COMPRESS); -void rtc_initialize () +void rtc_initialize() { - VERIFY (lzo_init()==LZO_E_OK); + VERIFY(lzo_init() == LZO_E_OK); } -u32 rtc_csize (u32 in) +u32 rtc_csize(u32 in) { - VERIFY (in); - return in + in/64 + 16 + 3; + VERIFY(in); + return in + in / 64 + 16 + 3; } -u32 rtc_compress (void *dst, u32 dst_len, const void* src, u32 src_len) +u32 rtc_compress(void* dst, u32 dst_len, const void* src, u32 src_len) { - u32 out_size = dst_len; - int r = lzo1x_1_compress ( - (const lzo_byte *) src, (lzo_uint) src_len, - (lzo_byte *) dst, (lzo_uintp) &out_size, - rtc_wrkmem); - VERIFY (r==LZO_E_OK); - return out_size; + u32 out_size = dst_len; + int r = lzo1x_1_compress( + (const lzo_byte*)src, (lzo_uint)src_len, + (lzo_byte*)dst, (lzo_uintp)&out_size, + rtc_wrkmem); + VERIFY(r == LZO_E_OK); + return out_size; } -u32 rtc_decompress (void *dst, u32 dst_len, const void* src, u32 src_len) +u32 rtc_decompress(void* dst, u32 dst_len, const void* src, u32 src_len) { - u32 out_size = dst_len; - int r = lzo1x_decompress ( - (const lzo_byte *) src, (lzo_uint) src_len, - (lzo_byte *) dst, (lzo_uintp) &out_size, - rtc_wrkmem); - VERIFY (r==LZO_E_OK); - return out_size; + u32 out_size = dst_len; + int r = lzo1x_decompress( + (const lzo_byte*)src, (lzo_uint)src_len, + (lzo_byte*)dst, (lzo_uintp)&out_size, + rtc_wrkmem); + VERIFY(r == LZO_E_OK); + return out_size; } diff --git a/src/xrCore/rt_compressor.h b/src/xrCore/rt_compressor.h index 54df3a8188d..13cea4237b5 100644 --- a/src/xrCore/rt_compressor.h +++ b/src/xrCore/rt_compressor.h @@ -2,15 +2,15 @@ #define rt_compressorH #pragma once -extern XRCORE_API void rtc_initialize (); -extern XRCORE_API u32 rtc_compress (void *dst, u32 dst_len, const void* src, u32 src_len); -extern XRCORE_API u32 rtc_decompress (void *dst, u32 dst_len, const void* src, u32 src_len); -extern XRCORE_API u32 rtc_csize (u32 in); +extern XRCORE_API void rtc_initialize(); +extern XRCORE_API u32 rtc_compress(void* dst, u32 dst_len, const void* src, u32 src_len); +extern XRCORE_API u32 rtc_decompress(void* dst, u32 dst_len, const void* src, u32 src_len); +extern XRCORE_API u32 rtc_csize(u32 in); -extern XRCORE_API void rtc9_initialize (); -extern XRCORE_API void rtc9_uninitialize (); -extern XRCORE_API u32 rtc9_compress (void *dst, u32 dst_len, const void* src, u32 src_len); -extern XRCORE_API u32 rtc9_decompress (void *dst, u32 dst_len, const void* src, u32 src_len); -extern XRCORE_API u32 rtc9_csize (u32 in); +extern XRCORE_API void rtc9_initialize(); +extern XRCORE_API void rtc9_uninitialize(); +extern XRCORE_API u32 rtc9_compress(void* dst, u32 dst_len, const void* src, u32 src_len); +extern XRCORE_API u32 rtc9_decompress(void* dst, u32 dst_len, const void* src, u32 src_len); +extern XRCORE_API u32 rtc9_csize(u32 in); #endif diff --git a/src/xrCore/rt_compressor9.cpp b/src/xrCore/rt_compressor9.cpp index 2ba06a254f4..e4bd0cecdc1 100644 --- a/src/xrCore/rt_compressor9.cpp +++ b/src/xrCore/rt_compressor9.cpp @@ -7,13 +7,13 @@ //============================================================================== #define HEAP_ALLOC(var,size) \ - lzo_align_t __LZO_MMODEL var [ ((size) + (sizeof(lzo_align_t) - 1)) / sizeof(lzo_align_t) ] + lzo_align_t __LZO_MMODEL var [ ((size) + (sizeof(lzo_align_t) - 1)) / sizeof(lzo_align_t) ] -__declspec(thread) HEAP_ALLOC(rtc9_wrkmem,LZO1X_999_MEM_COMPRESS); +__declspec(thread) HEAP_ALLOC(rtc9_wrkmem, LZO1X_999_MEM_COMPRESS); -static u8* _LZO_Dictionary = NULL; -static u32 _LZO_DictionarySize = 0; +static u8* _LZO_Dictionary = NULL; +static u32 _LZO_DictionarySize = 0; //------------------------------------------------------------------------------ @@ -23,35 +23,35 @@ rtc9_initialize() { static bool initialized = false; - if( initialized ) + if (initialized) return; - VERIFY(lzo_init()==LZO_E_OK); - - string_path file_name; - - FS.update_path( file_name, "$game_config$","mp\\lzo-dict.bin" ); - - if( FS.exist(file_name)) - { - IReader* reader = FS.r_open( file_name ); - - R_ASSERT(reader); - - _LZO_DictionarySize = reader->length(); - _LZO_Dictionary = (u8*)xr_malloc(_LZO_DictionarySize); - - reader->r( _LZO_Dictionary, _LZO_DictionarySize ); - FS.r_close( reader ); - - Msg( "using LZO-dictionary \"%s\"", file_name ); - } - else - { - Msg( "\"%s\" not found", file_name ); - } - - initialized = true; + VERIFY(lzo_init() == LZO_E_OK); + + string_path file_name; + + FS.update_path(file_name, "$game_config$", "mp\\lzo-dict.bin"); + + if (FS.exist(file_name)) + { + IReader* reader = FS.r_open(file_name); + + R_ASSERT(reader); + + _LZO_DictionarySize = reader->length(); + _LZO_Dictionary = (u8*)xr_malloc(_LZO_DictionarySize); + + reader->r(_LZO_Dictionary, _LZO_DictionarySize); + FS.r_close(reader); + + Msg("using LZO-dictionary \"%s\"", file_name); + } + else + { + Msg("\"%s\" not found", file_name); + } + + initialized = true; } @@ -60,11 +60,11 @@ rtc9_initialize() void rtc9_uninitialize() { - if( _LZO_Dictionary ) + if (_LZO_Dictionary) { - xr_free( _LZO_Dictionary ); - - _LZO_Dictionary = NULL; + xr_free(_LZO_Dictionary); + + _LZO_Dictionary = NULL; _LZO_DictionarySize = 0; } } @@ -72,72 +72,72 @@ rtc9_uninitialize() //------------------------------------------------------------------------------ -u32 -rtc9_csize( u32 in ) +u32 +rtc9_csize(u32 in) { VERIFY(in); - return in + in/64 + 16 + 3; + return in + in / 64 + 16 + 3; } //------------------------------------------------------------------------------ -u32 -rtc9_compress( void* dst, u32 dst_len, const void* src, u32 src_len ) +u32 +rtc9_compress(void* dst, u32 dst_len, const void* src, u32 src_len) { - u32 out_size = dst_len; - int r = LZO_E_ERROR; + u32 out_size = dst_len; + int r = LZO_E_ERROR; rtc9_initialize(); - if( _LZO_Dictionary ) - { - r = lzo1x_999_compress_dict( (const lzo_byte *)src, (lzo_uint)src_len, - (lzo_byte *)dst, (lzo_uintp)&out_size, - rtc9_wrkmem, _LZO_Dictionary, _LZO_DictionarySize + if (_LZO_Dictionary) + { + r = lzo1x_999_compress_dict((const lzo_byte*)src, (lzo_uint)src_len, + (lzo_byte*)dst, (lzo_uintp)&out_size, + rtc9_wrkmem, _LZO_Dictionary, _LZO_DictionarySize ); - } - else - { - r = lzo1x_999_compress( (const lzo_byte *)src, (lzo_uint)src_len, - (lzo_byte *)dst, (lzo_uintp) &out_size, - rtc9_wrkmem - ); } - - VERIFY(r==LZO_E_OK); - - return out_size; + else + { + r = lzo1x_999_compress((const lzo_byte*)src, (lzo_uint)src_len, + (lzo_byte*)dst, (lzo_uintp)&out_size, + rtc9_wrkmem + ); + } + + VERIFY(r == LZO_E_OK); + + return out_size; } //------------------------------------------------------------------------------ -u32 -rtc9_decompress( void* dst, u32 dst_len, const void* src, u32 src_len ) +u32 +rtc9_decompress(void* dst, u32 dst_len, const void* src, u32 src_len) { - u32 out_size = dst_len; - int r = LZO_E_ERROR; - + u32 out_size = dst_len; + int r = LZO_E_ERROR; + rtc9_initialize(); - if( _LZO_Dictionary ) + if (_LZO_Dictionary) { - r = lzo1x_decompress_dict_safe( (const lzo_byte*)src, (lzo_uint)src_len, - (lzo_byte*)dst, (lzo_uintp)&out_size, - NULL, _LZO_Dictionary, _LZO_DictionarySize + r = lzo1x_decompress_dict_safe((const lzo_byte*)src, (lzo_uint)src_len, + (lzo_byte*)dst, (lzo_uintp)&out_size, + NULL, _LZO_Dictionary, _LZO_DictionarySize ); } else { - r = lzo1x_decompress( (const lzo_byte*)src, (lzo_uint)src_len, - (lzo_byte*)dst, (lzo_uintp)&out_size, - NULL - ); + r = lzo1x_decompress((const lzo_byte*)src, (lzo_uint)src_len, + (lzo_byte*)dst, (lzo_uintp)&out_size, + NULL + ); } - VERIFY(r==LZO_E_OK); + VERIFY(r == LZO_E_OK); - return out_size; + return out_size; } diff --git a/src/xrCore/rt_lzo.cpp b/src/xrCore/rt_lzo.cpp index c919aadeb9f..a5034290a8e 100644 --- a/src/xrCore/rt_lzo.cpp +++ b/src/xrCore/rt_lzo.cpp @@ -114,11 +114,11 @@ Markus F.X.J. Oberhumer #if !defined(LZO_COMPILE_TIME_ASSERT) # define LZO_COMPILE_TIME_ASSERT(expr) \ - { typedef int __lzo_compile_time_assert_fail[1 - 2 * !(expr)]; } + { typedef int __lzo_compile_time_assert_fail[1 - 2 * !(expr)]; } #endif # define LZO_UNUSED(var) ((void)&var) -# define __inline__ inline +# define __inline__ inline #if defined(NO_MEMCMP) # undef HAVE_MEMCMP @@ -141,7 +141,7 @@ Markus F.X.J. Oberhumer # define memset lzo_memset #endif -#define LZO_BYTE(x) ((unsigned char) (x & 0xff)) +#define LZO_BYTE(x) ((unsigned char) (x & 0xff)) #define LZO_MAX(a,b) _max(a,b) #define LZO_MIN(a,b) _min(a,b) #define LZO_MAX3(a,b,c) ((a) >= (b) ? LZO_MAX(a,c) : LZO_MAX(b,c)) @@ -163,10 +163,10 @@ Markus F.X.J. Oberhumer #define LZO_STYPE_MAX(b) (((1l << (8*(b)-2)) - 1l) + (1l << (8*(b)-2))) #define LZO_UTYPE_MAX(b) (((1ul << (8*(b)-1)) - 1ul) + (1ul << (8*(b)-1))) -#define SIZEOF_UNSIGNED sizeof(unsigned) +#define SIZEOF_UNSIGNED sizeof(unsigned) #define SIZEOF_UNSIGNED_LONG sizeof(unsigned long) #define SIZEOF_SIZE_T sizeof(size_t) -#define SIZE_T_MAX LZO_UTYPE_MAX(SIZEOF_SIZE_T) +#define SIZE_T_MAX LZO_UTYPE_MAX(SIZEOF_SIZE_T) #if 1 && defined(__LZO_i386) && (UINT_MAX == LZO_0xffffffffL) # if !defined(LZO_UNALIGNED_OK_2) && (USHRT_MAX == 0xffff) @@ -207,7 +207,7 @@ Markus F.X.J. Oberhumer #define LZO_LITTLE_ENDIAN 1234 #define LZO_BIG_ENDIAN 4321 #define LZO_PDP_ENDIAN 3412 -#define LZO_BYTE_ORDER LZO_LITTLE_ENDIAN +#define LZO_BYTE_ORDER LZO_LITTLE_ENDIAN #if defined(LZO_UNALIGNED_OK) && !defined(LZO_BYTE_ORDER) # error "LZO_BYTE_ORDER is not defined" @@ -245,15 +245,15 @@ __LZO_EXTERN_C const lzo_uint32 _lzo_crc32_table[256]; #define __LZO_IS_COMPRESS_QUERY(i,il,o,ol,w) ((lzo_voidp)(o) == (w)) #define __LZO_QUERY_COMPRESS(i,il,o,ol,w,n,s) \ - (*ol = (n)*(s), LZO_E_OK) + (*ol = (n)*(s), LZO_E_OK) #define __LZO_IS_DECOMPRESS_QUERY(i,il,o,ol,w) ((lzo_voidp)(o) == (w)) #define __LZO_QUERY_DECOMPRESS(i,il,o,ol,w,n,s) \ - (*ol = (n)*(s), LZO_E_OK) + (*ol = (n)*(s), LZO_E_OK) #define __LZO_IS_OPTIMIZE_QUERY(i,il,o,ol,w) ((lzo_voidp)(o) == (w)) #define __LZO_QUERY_OPTIMIZE(i,il,o,ol,w,n,s) \ - (*ol = (n)*(s), LZO_E_OK) + (*ol = (n)*(s), LZO_E_OK) #endif @@ -268,10 +268,10 @@ extern "C" { # include # if 1 && defined(__WATCOMC__) # include - __LZO_EXTERN_C unsigned char _HShift; + __LZO_EXTERN_C unsigned char _HShift; # define __LZO_HShift _HShift # elif 1 && defined(_MSC_VER) - __LZO_EXTERN_C unsigned short __near _AHSHIFT; + __LZO_EXTERN_C unsigned short __near _AHSHIFT; # define __LZO_HShift ((unsigned) &_AHSHIFT) # elif defined(__LZO_WIN16) # define __LZO_HShift 3 @@ -288,9 +288,9 @@ extern "C" { #endif // -typedef ptrdiff_t lzo_ptrdiff_t; -typedef intptr_t lzo_sptr_t; -typedef uintptr_t lzo_ptr_t; +typedef ptrdiff_t lzo_ptrdiff_t; +typedef intptr_t lzo_sptr_t; +typedef uintptr_t lzo_ptr_t; #define __LZO_HAVE_PTR_T #if defined(__LZO_DOS16) || defined(__LZO_WIN16) @@ -311,38 +311,38 @@ typedef uintptr_t lzo_ptr_t; #define PTR_DIFF(a,b) ((lzo_ptrdiff_t) (PTR(a) - PTR(b))) #define pd(a,b) ((lzo_uint) ((a)-(b))) - LZO_EXTERN(lzo_ptr_t) - __lzo_ptr_linear(const lzo_voidp ptr); - - typedef union - { - char a_char; - unsigned char a_uchar; - short a_short; - unsigned short a_ushort; - int a_int; - unsigned int a_uint; - long a_long; - unsigned long a_ulong; - lzo_int a_lzo_int; - lzo_uint a_lzo_uint; - lzo_int32 a_lzo_int32; - lzo_uint32 a_lzo_uint32; - ptrdiff_t a_ptrdiff_t; - lzo_ptrdiff_t a_lzo_ptrdiff_t; - lzo_ptr_t a_lzo_ptr_t; - lzo_voidp a_lzo_voidp; - void * a_void_p; - lzo_bytep a_lzo_bytep; - lzo_bytepp a_lzo_bytepp; - lzo_uintp a_lzo_uintp; - lzo_uint * a_lzo_uint_p; - lzo_uint32p a_lzo_uint32p; - lzo_uint32 * a_lzo_uint32_p; - unsigned char * a_uchar_p; - char * a_char_p; - } - lzo_full_align_t; + LZO_EXTERN(lzo_ptr_t) + __lzo_ptr_linear(const lzo_voidp ptr); + + typedef union + { + char a_char; + unsigned char a_uchar; + short a_short; + unsigned short a_ushort; + int a_int; + unsigned int a_uint; + long a_long; + unsigned long a_ulong; + lzo_int a_lzo_int; + lzo_uint a_lzo_uint; + lzo_int32 a_lzo_int32; + lzo_uint32 a_lzo_uint32; + ptrdiff_t a_ptrdiff_t; + lzo_ptrdiff_t a_lzo_ptrdiff_t; + lzo_ptr_t a_lzo_ptr_t; + lzo_voidp a_lzo_voidp; + void * a_void_p; + lzo_bytep a_lzo_bytep; + lzo_bytepp a_lzo_bytepp; + lzo_uintp a_lzo_uintp; + lzo_uint * a_lzo_uint_p; + lzo_uint32p a_lzo_uint32p; + lzo_uint32 * a_lzo_uint32_p; + unsigned char * a_uchar_p; + char * a_char_p; + } + lzo_full_align_t; #ifdef __cplusplus } @@ -374,37 +374,37 @@ typedef uintptr_t lzo_ptr_t; LZO_PUBLIC(lzo_ptr_t) __lzo_ptr_linear(const lzo_voidp ptr) { - lzo_ptr_t p; + lzo_ptr_t p; #if defined(__LZO_DOS16) || defined(__LZO_WIN16) - p = (((lzo_ptr_t)(_FP_SEG(ptr))) << (16 - __LZO_HShift)) + (_FP_OFF(ptr)); + p = (((lzo_ptr_t)(_FP_SEG(ptr))) << (16 - __LZO_HShift)) + (_FP_OFF(ptr)); #else - p = PTR_LINEAR(ptr); + p = PTR_LINEAR(ptr); #endif - return p; + return p; } LZO_PUBLIC(unsigned) __lzo_align_gap(const lzo_voidp ptr, lzo_uint size) { - lzo_ptr_t p, s, n; + lzo_ptr_t p, s, n; - assert(size > 0); + assert(size > 0); - p = __lzo_ptr_linear(ptr); - s = (lzo_ptr_t) (size - 1); + p = __lzo_ptr_linear(ptr); + s = (lzo_ptr_t) (size - 1); #if 0 - assert((size & (size - 1)) == 0); - n = ((p + s) & ~s) - p; + assert((size & (size - 1)) == 0); + n = ((p + s) & ~s) - p; #else - n = (((p + s) / size) * size) - p; + n = (((p + s) / size) * size) - p; #endif - assert((long)n >= 0); - assert(n <= s); + assert((long)n >= 0); + assert(n <= s); - return (unsigned)n; + return (unsigned)n; } #ifndef __LZO_UTIL_H @@ -421,9 +421,9 @@ extern "C" { #if !defined(__LZO_DOS16) && !defined(__LZO_WIN16) #define MEMCPY8_DS(dest,src,len) \ - memcpy(dest,src,len); \ - dest += len; \ - src += len + memcpy(dest,src,len); \ + dest += len; \ + src += len #endif #endif @@ -431,44 +431,44 @@ extern "C" { #if 0 && !defined(MEMCPY8_DS) #define MEMCPY8_DS(dest,src,len) \ - { do { \ - *dest++ = *src++; \ - *dest++ = *src++; \ - *dest++ = *src++; \ - *dest++ = *src++; \ - *dest++ = *src++; \ - *dest++ = *src++; \ - *dest++ = *src++; \ - *dest++ = *src++; \ - len -= 8; \ - } while (len > 0); } + { do { \ + *dest++ = *src++; \ + *dest++ = *src++; \ + *dest++ = *src++; \ + *dest++ = *src++; \ + *dest++ = *src++; \ + *dest++ = *src++; \ + *dest++ = *src++; \ + *dest++ = *src++; \ + len -= 8; \ + } while (len > 0); } #endif #if !defined(MEMCPY8_DS) #define MEMCPY8_DS(dest,src,len) \ - { register lzo_uint __l = (len) / 8; \ - do { \ - *dest++ = *src++; \ - *dest++ = *src++; \ - *dest++ = *src++; \ - *dest++ = *src++; \ - *dest++ = *src++; \ - *dest++ = *src++; \ - *dest++ = *src++; \ - *dest++ = *src++; \ - } while (--__l > 0); } + { register lzo_uint __l = (len) / 8; \ + do { \ + *dest++ = *src++; \ + *dest++ = *src++; \ + *dest++ = *src++; \ + *dest++ = *src++; \ + *dest++ = *src++; \ + *dest++ = *src++; \ + *dest++ = *src++; \ + *dest++ = *src++; \ + } while (--__l > 0); } #endif #define MEMCPY_DS(dest,src,len) \ - do *dest++ = *src++; \ - while (--len > 0) + do *dest++ = *src++; \ + while (--len > 0) #define MEMMOVE_DS(dest,src,len) \ - do *dest++ = *src++; \ - while (--len > 0) + do *dest++ = *src++; \ + while (--len > 0) #if 1 #define BZERO8_PTR(s,l,n) memset((s),0,(lzo_uint)(l)*(n)) @@ -479,25 +479,25 @@ extern "C" { #if 0 #if defined(__GNUC__) && defined(__i386__) - unsigned char lzo_rotr8(unsigned char value, int shift); - extern __inline__ unsigned char lzo_rotr8(unsigned char value, int shift) - { - unsigned char result; + unsigned char lzo_rotr8(unsigned char value, int shift); + extern __inline__ unsigned char lzo_rotr8(unsigned char value, int shift) + { + unsigned char result; - __asm__ __volatile__ ("movb %b1, %b0; rorb %b2, %b0" - : "=a"(result) : "g"(value), "c"(shift)); - return result; - } + __asm__ __volatile__ ("movb %b1, %b0; rorb %b2, %b0" + : "=a"(result) : "g"(value), "c"(shift)); + return result; + } - unsigned short lzo_rotr16(unsigned short value, int shift); - extern __inline__ unsigned short lzo_rotr16(unsigned short value, int shift) - { - unsigned short result; + unsigned short lzo_rotr16(unsigned short value, int shift); + extern __inline__ unsigned short lzo_rotr16(unsigned short value, int shift) + { + unsigned short result; - __asm__ __volatile__ ("movw %b1, %b0; rorw %b2, %b0" - : "=a"(result) : "g"(value), "c"(shift)); - return result; - } + __asm__ __volatile__ ("movw %b1, %b0; rorw %b2, %b0" + : "=a"(result) : "g"(value), "c"(shift)); + return result; + } #endif #endif @@ -511,7 +511,7 @@ extern "C" { LZO_PUBLIC(lzo_bool) lzo_assert(int expr) { - return (expr) ? 1 : 0; + return (expr) ? 1 : 0; } /* If you use the LZO library in a product, you *must* keep this @@ -599,37 +599,37 @@ LZO_VERSION_STRING; LZO_PUBLIC(const lzo_byte *) lzo_copyright(void) { - return __lzo_copyright; + return __lzo_copyright; } LZO_PUBLIC(unsigned) lzo_version(void) { - return LZO_VERSION; + return LZO_VERSION; } LZO_PUBLIC(const char *) lzo_version_string(void) { - return LZO_VERSION_STRING; + return LZO_VERSION_STRING; } LZO_PUBLIC(const char *) lzo_version_date(void) { - return LZO_VERSION_DATE; + return LZO_VERSION_DATE; } LZO_PUBLIC(const lzo_charp) _lzo_version_string(void) { - return LZO_VERSION_STRING; + return LZO_VERSION_STRING; } LZO_PUBLIC(const lzo_charp) _lzo_version_date(void) { - return LZO_VERSION_DATE; + return LZO_VERSION_DATE; } #define LZO_BASE 65521u @@ -644,32 +644,32 @@ _lzo_version_date(void) LZO_PUBLIC(lzo_uint32) lzo_adler32(lzo_uint32 adler, const lzo_byte *buf, lzo_uint len) { - lzo_uint32 s1 = adler & 0xffff; - lzo_uint32 s2 = (adler >> 16) & 0xffff; - int k; - - if (buf == NULL) - return 1; - - while (len > 0) - { - k = len < LZO_NMAX ? (int) len : LZO_NMAX; - len -= k; - if (k >= 16) do - { - LZO_DO16(buf,0); - buf += 16; - k -= 16; - } while (k >= 16); - if (k != 0) do - { - s1 += *buf++; - s2 += s1; - } while (--k > 0); - s1 %= LZO_BASE; - s2 %= LZO_BASE; - } - return (s2 << 16) | s1; + lzo_uint32 s1 = adler & 0xffff; + lzo_uint32 s2 = (adler >> 16) & 0xffff; + int k; + + if (buf == NULL) + return 1; + + while (len > 0) + { + k = len < LZO_NMAX ? (int) len : LZO_NMAX; + len -= k; + if (k >= 16) do + { + LZO_DO16(buf,0); + buf += 16; + k -= 16; + } while (k >= 16); + if (k != 0) do + { + s1 += *buf++; + s2 += s1; + } while (--k > 0); + s1 %= LZO_BASE; + s2 %= LZO_BASE; + } + return (s2 << 16) | s1; } @@ -691,11 +691,11 @@ static lzo_bool strength_reduce_bug(int *); static lzo_bool __lzo_assert_fail(const char *s, unsigned line) { #if defined(__palmos__) - printf("LZO assertion failed in line %u: '%s'\n",line,s); + printf("LZO assertion failed in line %u: '%s'\n",line,s); #else - fprintf(stderr,"LZO assertion failed in line %u: '%s'\n",line,s); + fprintf(stderr,"LZO assertion failed in line %u: '%s'\n",line,s); #endif - return 0; + return 0; } # define __lzo_assert(x) ((x) ? 1 : __lzo_assert_fail(#x,__LINE__)) #else @@ -711,389 +711,389 @@ static lzo_bool __lzo_assert_fail(const char *s, unsigned line) static lzo_bool basic_integral_check(void) { - lzo_bool r = 1; + lzo_bool r = 1; - COMPILE_TIME_ASSERT(CHAR_BIT == 8); - COMPILE_TIME_ASSERT(sizeof(char) == 1); - COMPILE_TIME_ASSERT(sizeof(short) >= 2); - COMPILE_TIME_ASSERT(sizeof(long) >= 4); - COMPILE_TIME_ASSERT(sizeof(int) >= sizeof(short)); - COMPILE_TIME_ASSERT(sizeof(long) >= sizeof(int)); + COMPILE_TIME_ASSERT(CHAR_BIT == 8); + COMPILE_TIME_ASSERT(sizeof(char) == 1); + COMPILE_TIME_ASSERT(sizeof(short) >= 2); + COMPILE_TIME_ASSERT(sizeof(long) >= 4); + COMPILE_TIME_ASSERT(sizeof(int) >= sizeof(short)); + COMPILE_TIME_ASSERT(sizeof(long) >= sizeof(int)); - COMPILE_TIME_ASSERT(sizeof(lzo_uint) == sizeof(lzo_int)); - COMPILE_TIME_ASSERT(sizeof(lzo_uint32) == sizeof(lzo_int32)); + COMPILE_TIME_ASSERT(sizeof(lzo_uint) == sizeof(lzo_int)); + COMPILE_TIME_ASSERT(sizeof(lzo_uint32) == sizeof(lzo_int32)); - COMPILE_TIME_ASSERT(sizeof(lzo_uint32) >= 4); - COMPILE_TIME_ASSERT(sizeof(lzo_uint32) >= sizeof(unsigned)); + COMPILE_TIME_ASSERT(sizeof(lzo_uint32) >= 4); + COMPILE_TIME_ASSERT(sizeof(lzo_uint32) >= sizeof(unsigned)); #if defined(__LZO_STRICT_16BIT) - COMPILE_TIME_ASSERT(sizeof(lzo_uint) == 2); + COMPILE_TIME_ASSERT(sizeof(lzo_uint) == 2); #else - COMPILE_TIME_ASSERT(sizeof(lzo_uint) >= 4); - COMPILE_TIME_ASSERT(sizeof(lzo_uint) >= sizeof(unsigned)); + COMPILE_TIME_ASSERT(sizeof(lzo_uint) >= 4); + COMPILE_TIME_ASSERT(sizeof(lzo_uint) >= sizeof(unsigned)); #endif #if (USHRT_MAX == 65535u) - COMPILE_TIME_ASSERT(sizeof(short) == 2); + COMPILE_TIME_ASSERT(sizeof(short) == 2); #elif (USHRT_MAX == LZO_0xffffffffL) - COMPILE_TIME_ASSERT(sizeof(short) == 4); + COMPILE_TIME_ASSERT(sizeof(short) == 4); #elif (USHRT_MAX >= LZO_0xffffffffL) - COMPILE_TIME_ASSERT(sizeof(short) > 4); + COMPILE_TIME_ASSERT(sizeof(short) > 4); #endif #if (UINT_MAX == 65535u) - COMPILE_TIME_ASSERT(sizeof(int) == 2); + COMPILE_TIME_ASSERT(sizeof(int) == 2); #elif (UINT_MAX == LZO_0xffffffffL) - COMPILE_TIME_ASSERT(sizeof(int) == 4); + COMPILE_TIME_ASSERT(sizeof(int) == 4); #elif (UINT_MAX >= LZO_0xffffffffL) - COMPILE_TIME_ASSERT(sizeof(int) > 4); + COMPILE_TIME_ASSERT(sizeof(int) > 4); #endif #if (ULONG_MAX == 65535ul) - COMPILE_TIME_ASSERT(sizeof(long) == 2); + COMPILE_TIME_ASSERT(sizeof(long) == 2); #elif (ULONG_MAX == LZO_0xffffffffL) - COMPILE_TIME_ASSERT(sizeof(long) == 4); + COMPILE_TIME_ASSERT(sizeof(long) == 4); #elif (ULONG_MAX >= LZO_0xffffffffL) - COMPILE_TIME_ASSERT(sizeof(long) > 4); + COMPILE_TIME_ASSERT(sizeof(long) > 4); #endif #if defined(SIZEOF_UNSIGNED) - COMPILE_TIME_ASSERT(SIZEOF_UNSIGNED == sizeof(unsigned)); + COMPILE_TIME_ASSERT(SIZEOF_UNSIGNED == sizeof(unsigned)); #endif #if defined(SIZEOF_UNSIGNED_LONG) - COMPILE_TIME_ASSERT(SIZEOF_UNSIGNED_LONG == sizeof(unsigned long)); + COMPILE_TIME_ASSERT(SIZEOF_UNSIGNED_LONG == sizeof(unsigned long)); #endif #if defined(SIZEOF_UNSIGNED_SHORT) - COMPILE_TIME_ASSERT(SIZEOF_UNSIGNED_SHORT == sizeof(unsigned short)); + COMPILE_TIME_ASSERT(SIZEOF_UNSIGNED_SHORT == sizeof(unsigned short)); #endif #if !defined(__LZO_IN_MINILZO) #if defined(SIZEOF_SIZE_T) - COMPILE_TIME_ASSERT(SIZEOF_SIZE_T == sizeof(size_t)); -#endif -#endif - - COMPILE_TIME_ASSERT(IS_UNSIGNED(unsigned char)); - COMPILE_TIME_ASSERT(IS_UNSIGNED(unsigned short)); - COMPILE_TIME_ASSERT(IS_UNSIGNED(unsigned)); - COMPILE_TIME_ASSERT(IS_UNSIGNED(unsigned long)); - COMPILE_TIME_ASSERT(IS_SIGNED(short)); - COMPILE_TIME_ASSERT(IS_SIGNED(int)); - COMPILE_TIME_ASSERT(IS_SIGNED(long)); - - COMPILE_TIME_ASSERT(IS_UNSIGNED(lzo_uint32)); - COMPILE_TIME_ASSERT(IS_UNSIGNED(lzo_uint)); - COMPILE_TIME_ASSERT(IS_SIGNED(lzo_int32)); - COMPILE_TIME_ASSERT(IS_SIGNED(lzo_int)); - - COMPILE_TIME_ASSERT(INT_MAX == LZO_STYPE_MAX(sizeof(int))); - COMPILE_TIME_ASSERT(UINT_MAX == LZO_UTYPE_MAX(sizeof(unsigned))); - COMPILE_TIME_ASSERT(LONG_MAX == LZO_STYPE_MAX(sizeof(long))); - COMPILE_TIME_ASSERT(ULONG_MAX == LZO_UTYPE_MAX(sizeof(unsigned long))); - COMPILE_TIME_ASSERT(SHRT_MAX == LZO_STYPE_MAX(sizeof(short))); - COMPILE_TIME_ASSERT(USHRT_MAX == LZO_UTYPE_MAX(sizeof(unsigned short))); - COMPILE_TIME_ASSERT(LZO_UINT32_MAX == LZO_UTYPE_MAX(sizeof(lzo_uint32))); - COMPILE_TIME_ASSERT(LZO_UINT_MAX == LZO_UTYPE_MAX(sizeof(lzo_uint))); + COMPILE_TIME_ASSERT(SIZEOF_SIZE_T == sizeof(size_t)); +#endif +#endif + + COMPILE_TIME_ASSERT(IS_UNSIGNED(unsigned char)); + COMPILE_TIME_ASSERT(IS_UNSIGNED(unsigned short)); + COMPILE_TIME_ASSERT(IS_UNSIGNED(unsigned)); + COMPILE_TIME_ASSERT(IS_UNSIGNED(unsigned long)); + COMPILE_TIME_ASSERT(IS_SIGNED(short)); + COMPILE_TIME_ASSERT(IS_SIGNED(int)); + COMPILE_TIME_ASSERT(IS_SIGNED(long)); + + COMPILE_TIME_ASSERT(IS_UNSIGNED(lzo_uint32)); + COMPILE_TIME_ASSERT(IS_UNSIGNED(lzo_uint)); + COMPILE_TIME_ASSERT(IS_SIGNED(lzo_int32)); + COMPILE_TIME_ASSERT(IS_SIGNED(lzo_int)); + + COMPILE_TIME_ASSERT(INT_MAX == LZO_STYPE_MAX(sizeof(int))); + COMPILE_TIME_ASSERT(UINT_MAX == LZO_UTYPE_MAX(sizeof(unsigned))); + COMPILE_TIME_ASSERT(LONG_MAX == LZO_STYPE_MAX(sizeof(long))); + COMPILE_TIME_ASSERT(ULONG_MAX == LZO_UTYPE_MAX(sizeof(unsigned long))); + COMPILE_TIME_ASSERT(SHRT_MAX == LZO_STYPE_MAX(sizeof(short))); + COMPILE_TIME_ASSERT(USHRT_MAX == LZO_UTYPE_MAX(sizeof(unsigned short))); + COMPILE_TIME_ASSERT(LZO_UINT32_MAX == LZO_UTYPE_MAX(sizeof(lzo_uint32))); + COMPILE_TIME_ASSERT(LZO_UINT_MAX == LZO_UTYPE_MAX(sizeof(lzo_uint))); #if !defined(__LZO_IN_MINILZO) - COMPILE_TIME_ASSERT(SIZE_T_MAX == LZO_UTYPE_MAX(sizeof(size_t))); + COMPILE_TIME_ASSERT(SIZE_T_MAX == LZO_UTYPE_MAX(sizeof(size_t))); #endif - // there is no hardware when following can fail: - // r &= __lzo_assert(LZO_BYTE(257) == 1); + // there is no hardware when following can fail: + // r &= __lzo_assert(LZO_BYTE(257) == 1); - return r; + return r; } static lzo_bool basic_ptr_check(void) { - lzo_bool r = 1; + lzo_bool r = 1; - COMPILE_TIME_ASSERT(sizeof(char *) >= sizeof(int)); - COMPILE_TIME_ASSERT(sizeof(lzo_byte *) >= sizeof(char *)); + COMPILE_TIME_ASSERT(sizeof(char *) >= sizeof(int)); + COMPILE_TIME_ASSERT(sizeof(lzo_byte *) >= sizeof(char *)); - COMPILE_TIME_ASSERT(sizeof(lzo_voidp) == sizeof(lzo_byte *)); - COMPILE_TIME_ASSERT(sizeof(lzo_voidp) == sizeof(lzo_voidpp)); - COMPILE_TIME_ASSERT(sizeof(lzo_voidp) == sizeof(lzo_bytepp)); - COMPILE_TIME_ASSERT(sizeof(lzo_voidp) >= sizeof(lzo_uint)); + COMPILE_TIME_ASSERT(sizeof(lzo_voidp) == sizeof(lzo_byte *)); + COMPILE_TIME_ASSERT(sizeof(lzo_voidp) == sizeof(lzo_voidpp)); + COMPILE_TIME_ASSERT(sizeof(lzo_voidp) == sizeof(lzo_bytepp)); + COMPILE_TIME_ASSERT(sizeof(lzo_voidp) >= sizeof(lzo_uint)); - COMPILE_TIME_ASSERT(sizeof(lzo_ptr_t) == sizeof(lzo_voidp)); - COMPILE_TIME_ASSERT(sizeof(lzo_ptr_t) == sizeof(lzo_sptr_t)); - COMPILE_TIME_ASSERT(sizeof(lzo_ptr_t) >= sizeof(lzo_uint)); + COMPILE_TIME_ASSERT(sizeof(lzo_ptr_t) == sizeof(lzo_voidp)); + COMPILE_TIME_ASSERT(sizeof(lzo_ptr_t) == sizeof(lzo_sptr_t)); + COMPILE_TIME_ASSERT(sizeof(lzo_ptr_t) >= sizeof(lzo_uint)); - COMPILE_TIME_ASSERT(sizeof(lzo_ptrdiff_t) >= 4); - COMPILE_TIME_ASSERT(sizeof(lzo_ptrdiff_t) >= sizeof(ptrdiff_t)); + COMPILE_TIME_ASSERT(sizeof(lzo_ptrdiff_t) >= 4); + COMPILE_TIME_ASSERT(sizeof(lzo_ptrdiff_t) >= sizeof(ptrdiff_t)); - COMPILE_TIME_ASSERT(sizeof(ptrdiff_t) >= sizeof(size_t)); - COMPILE_TIME_ASSERT(sizeof(lzo_ptrdiff_t) >= sizeof(lzo_uint)); + COMPILE_TIME_ASSERT(sizeof(ptrdiff_t) >= sizeof(size_t)); + COMPILE_TIME_ASSERT(sizeof(lzo_ptrdiff_t) >= sizeof(lzo_uint)); #if defined(SIZEOF_CHAR_P) - COMPILE_TIME_ASSERT(SIZEOF_CHAR_P == sizeof(char *)); + COMPILE_TIME_ASSERT(SIZEOF_CHAR_P == sizeof(char *)); #endif #if defined(SIZEOF_PTRDIFF_T) - COMPILE_TIME_ASSERT(SIZEOF_PTRDIFF_T == sizeof(ptrdiff_t)); + COMPILE_TIME_ASSERT(SIZEOF_PTRDIFF_T == sizeof(ptrdiff_t)); #endif - COMPILE_TIME_ASSERT(IS_SIGNED(ptrdiff_t)); - COMPILE_TIME_ASSERT(IS_UNSIGNED(size_t)); - COMPILE_TIME_ASSERT(IS_SIGNED(lzo_ptrdiff_t)); - COMPILE_TIME_ASSERT(IS_SIGNED(lzo_sptr_t)); - COMPILE_TIME_ASSERT(IS_UNSIGNED(lzo_ptr_t)); - COMPILE_TIME_ASSERT(IS_UNSIGNED(lzo_moff_t)); + COMPILE_TIME_ASSERT(IS_SIGNED(ptrdiff_t)); + COMPILE_TIME_ASSERT(IS_UNSIGNED(size_t)); + COMPILE_TIME_ASSERT(IS_SIGNED(lzo_ptrdiff_t)); + COMPILE_TIME_ASSERT(IS_SIGNED(lzo_sptr_t)); + COMPILE_TIME_ASSERT(IS_UNSIGNED(lzo_ptr_t)); + COMPILE_TIME_ASSERT(IS_UNSIGNED(lzo_moff_t)); - return r; + return r; } static lzo_bool ptr_check(void) { - lzo_bool r = 1; - int i; - char _wrkmem[10 * sizeof(lzo_byte *) + sizeof(lzo_full_align_t)]; - lzo_bytep wrkmem; - lzo_bytepp dict; - unsigned char x[4 * sizeof(lzo_full_align_t)]; - long d; - lzo_full_align_t a; - lzo_full_align_t u; + lzo_bool r = 1; + int i; + char _wrkmem[10 * sizeof(lzo_byte *) + sizeof(lzo_full_align_t)]; + lzo_bytep wrkmem; + lzo_bytepp dict; + unsigned char x[4 * sizeof(lzo_full_align_t)]; + long d; + lzo_full_align_t a; + lzo_full_align_t u; - for (i = 0; i < (int) sizeof(x); i++) - x[i] = LZO_BYTE(i); + for (i = 0; i < (int) sizeof(x); i++) + x[i] = LZO_BYTE(i); - wrkmem = LZO_PTR_ALIGN_UP((lzo_byte *)_wrkmem,sizeof(lzo_full_align_t)); + wrkmem = LZO_PTR_ALIGN_UP((lzo_byte *)_wrkmem,sizeof(lzo_full_align_t)); #if 0 - dict = (lzo_bytepp) wrkmem; -#else - - u.a_lzo_bytep = wrkmem; dict = u.a_lzo_bytepp; -#endif - - d = (long) ((const lzo_bytep) dict - (const lzo_bytep) _wrkmem); - r &= __lzo_assert(d >= 0); - r &= __lzo_assert(d < (long) sizeof(lzo_full_align_t)); - - memset(&a,0,sizeof(a)); - r &= __lzo_assert(a.a_lzo_voidp == NULL); - - memset(&a,0xff,sizeof(a)); - r &= __lzo_assert(a.a_ushort == USHRT_MAX); - r &= __lzo_assert(a.a_uint == UINT_MAX); - r &= __lzo_assert(a.a_ulong == ULONG_MAX); - r &= __lzo_assert(a.a_lzo_uint == LZO_UINT_MAX); - r &= __lzo_assert(a.a_lzo_uint32 == LZO_UINT32_MAX); - - if (r == 1) - { - for (i = 0; i < 8; i++) - r &= __lzo_assert((const lzo_voidp) (&dict[i]) == (const lzo_voidp) (&wrkmem[i * sizeof(lzo_byte *)])); - } - - memset(&a,0,sizeof(a)); - r &= __lzo_assert(a.a_char_p == NULL); - r &= __lzo_assert(a.a_lzo_bytep == NULL); - r &= __lzo_assert(NULL == (void *)0); - if (r == 1) - { - for (i = 0; i < 10; i++) - dict[i] = wrkmem; - BZERO8_PTR(dict+1,sizeof(dict[0]),8); - r &= __lzo_assert(dict[0] == wrkmem); - for (i = 1; i < 9; i++) - r &= __lzo_assert(dict[i] == NULL); - r &= __lzo_assert(dict[9] == wrkmem); - } - - if (r == 1) - { - unsigned k = 1; - const unsigned n = (unsigned) sizeof(lzo_uint32); - lzo_byte *p0; - lzo_byte *p1; - - k += __lzo_align_gap(&x[k],n); - p0 = (lzo_bytep) &x[k]; + dict = (lzo_bytepp) wrkmem; +#else + + u.a_lzo_bytep = wrkmem; dict = u.a_lzo_bytepp; +#endif + + d = (long) ((const lzo_bytep) dict - (const lzo_bytep) _wrkmem); + r &= __lzo_assert(d >= 0); + r &= __lzo_assert(d < (long) sizeof(lzo_full_align_t)); + + memset(&a,0,sizeof(a)); + r &= __lzo_assert(a.a_lzo_voidp == NULL); + + memset(&a,0xff,sizeof(a)); + r &= __lzo_assert(a.a_ushort == USHRT_MAX); + r &= __lzo_assert(a.a_uint == UINT_MAX); + r &= __lzo_assert(a.a_ulong == ULONG_MAX); + r &= __lzo_assert(a.a_lzo_uint == LZO_UINT_MAX); + r &= __lzo_assert(a.a_lzo_uint32 == LZO_UINT32_MAX); + + if (r == 1) + { + for (i = 0; i < 8; i++) + r &= __lzo_assert((const lzo_voidp) (&dict[i]) == (const lzo_voidp) (&wrkmem[i * sizeof(lzo_byte *)])); + } + + memset(&a,0,sizeof(a)); + r &= __lzo_assert(a.a_char_p == NULL); + r &= __lzo_assert(a.a_lzo_bytep == NULL); + r &= __lzo_assert(NULL == (void *)0); + if (r == 1) + { + for (i = 0; i < 10; i++) + dict[i] = wrkmem; + BZERO8_PTR(dict+1,sizeof(dict[0]),8); + r &= __lzo_assert(dict[0] == wrkmem); + for (i = 1; i < 9; i++) + r &= __lzo_assert(dict[i] == NULL); + r &= __lzo_assert(dict[9] == wrkmem); + } + + if (r == 1) + { + unsigned k = 1; + const unsigned n = (unsigned) sizeof(lzo_uint32); + lzo_byte *p0; + lzo_byte *p1; + + k += __lzo_align_gap(&x[k],n); + p0 = (lzo_bytep) &x[k]; #if defined(PTR_LINEAR) - r &= __lzo_assert((PTR_LINEAR(p0) & (n-1)) == 0); + r &= __lzo_assert((PTR_LINEAR(p0) & (n-1)) == 0); #else - r &= __lzo_assert(n == 4); - r &= __lzo_assert(PTR_ALIGNED_4(p0)); + r &= __lzo_assert(n == 4); + r &= __lzo_assert(PTR_ALIGNED_4(p0)); #endif - r &= __lzo_assert(k >= 1); - p1 = (lzo_bytep) &x[1]; - r &= __lzo_assert(PTR_GE(p0,p1)); + r &= __lzo_assert(k >= 1); + p1 = (lzo_bytep) &x[1]; + r &= __lzo_assert(PTR_GE(p0,p1)); - r &= __lzo_assert(k < 1+n); - p1 = (lzo_bytep) &x[1+n]; - r &= __lzo_assert(PTR_LT(p0,p1)); + r &= __lzo_assert(k < 1+n); + p1 = (lzo_bytep) &x[1+n]; + r &= __lzo_assert(PTR_LT(p0,p1)); - if (r == 1) - { - lzo_uint32 v0, v1; + if (r == 1) + { + lzo_uint32 v0, v1; #if 0 - v0 = * (lzo_uint32 *) &x[k]; - v1 = * (lzo_uint32 *) &x[k+n]; + v0 = * (lzo_uint32 *) &x[k]; + v1 = * (lzo_uint32 *) &x[k+n]; #else - u.a_uchar_p = &x[k]; - v0 = *u.a_lzo_uint32_p; - u.a_uchar_p = &x[k+n]; - v1 = *u.a_lzo_uint32_p; + u.a_uchar_p = &x[k]; + v0 = *u.a_lzo_uint32_p; + u.a_uchar_p = &x[k+n]; + v1 = *u.a_lzo_uint32_p; #endif - r &= __lzo_assert(v0 > 0); - r &= __lzo_assert(v1 > 0); - } - } + r &= __lzo_assert(v0 > 0); + r &= __lzo_assert(v1 > 0); + } + } - return r; + return r; } LZO_PUBLIC(int) _lzo_config_check(void) { - lzo_bool r = 1; - int i; - union { - lzo_uint32 a; - unsigned short b; - lzo_uint32 aa[4]; - unsigned char x[4*sizeof(lzo_full_align_t)]; - } u; - - COMPILE_TIME_ASSERT( (int) ((unsigned char) ((signed char) -1)) == 255); - COMPILE_TIME_ASSERT( (((unsigned char)128) << (int)(8*sizeof(int)-8)) < 0); + lzo_bool r = 1; + int i; + union { + lzo_uint32 a; + unsigned short b; + lzo_uint32 aa[4]; + unsigned char x[4*sizeof(lzo_full_align_t)]; + } u; + + COMPILE_TIME_ASSERT( (int) ((unsigned char) ((signed char) -1)) == 255); + COMPILE_TIME_ASSERT( (((unsigned char)128) << (int)(8*sizeof(int)-8)) < 0); #if 0 - r &= __lzo_assert((const void *)&u == (const void *)&u.a); - r &= __lzo_assert((const void *)&u == (const void *)&u.b); - r &= __lzo_assert((const void *)&u == (const void *)&u.x[0]); - r &= __lzo_assert((const void *)&u == (const void *)&u.aa[0]); + r &= __lzo_assert((const void *)&u == (const void *)&u.a); + r &= __lzo_assert((const void *)&u == (const void *)&u.b); + r &= __lzo_assert((const void *)&u == (const void *)&u.x[0]); + r &= __lzo_assert((const void *)&u == (const void *)&u.aa[0]); #endif - r &= basic_integral_check(); - r &= basic_ptr_check(); - if (r != 1) - return LZO_E_ERROR; + r &= basic_integral_check(); + r &= basic_ptr_check(); + if (r != 1) + return LZO_E_ERROR; - u.a = 0; u.b = 0; - for (i = 0; i < (int) sizeof(u.x); i++) - u.x[i] = LZO_BYTE(i); + u.a = 0; u.b = 0; + for (i = 0; i < (int) sizeof(u.x); i++) + u.x[i] = LZO_BYTE(i); #if defined(LZO_BYTE_ORDER) - if (r == 1) - { + if (r == 1) + { # if (LZO_BYTE_ORDER == LZO_LITTLE_ENDIAN) - lzo_uint32 a = (lzo_uint32) (u.a & LZO_0xffffffffL); - unsigned short b = (unsigned short) (u.b & 0xffff); - r &= __lzo_assert(a == 0x03020100L); - r &= __lzo_assert(b == 0x0100); + lzo_uint32 a = (lzo_uint32) (u.a & LZO_0xffffffffL); + unsigned short b = (unsigned short) (u.b & 0xffff); + r &= __lzo_assert(a == 0x03020100L); + r &= __lzo_assert(b == 0x0100); # elif (LZO_BYTE_ORDER == LZO_BIG_ENDIAN) - lzo_uint32 a = u.a >> (8 * sizeof(u.a) - 32); - unsigned short b = u.b >> (8 * sizeof(u.b) - 16); - r &= __lzo_assert(a == 0x00010203L); - r &= __lzo_assert(b == 0x0001); + lzo_uint32 a = u.a >> (8 * sizeof(u.a) - 32); + unsigned short b = u.b >> (8 * sizeof(u.b) - 16); + r &= __lzo_assert(a == 0x00010203L); + r &= __lzo_assert(b == 0x0001); # else # error "invalid LZO_BYTE_ORDER" # endif - } + } #endif #if defined(LZO_UNALIGNED_OK_2) - COMPILE_TIME_ASSERT(sizeof(short) == 2); - if (r == 1) - { - unsigned short b[4]; + COMPILE_TIME_ASSERT(sizeof(short) == 2); + if (r == 1) + { + unsigned short b[4]; - for (i = 0; i < 4; i++) - b[i] = * (const unsigned short *) &u.x[i]; + for (i = 0; i < 4; i++) + b[i] = * (const unsigned short *) &u.x[i]; # if (LZO_BYTE_ORDER == LZO_LITTLE_ENDIAN) - r &= __lzo_assert(b[0] == 0x0100); - r &= __lzo_assert(b[1] == 0x0201); - r &= __lzo_assert(b[2] == 0x0302); - r &= __lzo_assert(b[3] == 0x0403); + r &= __lzo_assert(b[0] == 0x0100); + r &= __lzo_assert(b[1] == 0x0201); + r &= __lzo_assert(b[2] == 0x0302); + r &= __lzo_assert(b[3] == 0x0403); # elif (LZO_BYTE_ORDER == LZO_BIG_ENDIAN) - r &= __lzo_assert(b[0] == 0x0001); - r &= __lzo_assert(b[1] == 0x0102); - r &= __lzo_assert(b[2] == 0x0203); - r &= __lzo_assert(b[3] == 0x0304); + r &= __lzo_assert(b[0] == 0x0001); + r &= __lzo_assert(b[1] == 0x0102); + r &= __lzo_assert(b[2] == 0x0203); + r &= __lzo_assert(b[3] == 0x0304); # endif - } + } #endif #if defined(LZO_UNALIGNED_OK_4) - COMPILE_TIME_ASSERT(sizeof(lzo_uint32) == 4); - if (r == 1) - { - lzo_uint32 a[4]; + COMPILE_TIME_ASSERT(sizeof(lzo_uint32) == 4); + if (r == 1) + { + lzo_uint32 a[4]; - for (i = 0; i < 4; i++) - a[i] = * (const lzo_uint32 *) &u.x[i]; + for (i = 0; i < 4; i++) + a[i] = * (const lzo_uint32 *) &u.x[i]; # if (LZO_BYTE_ORDER == LZO_LITTLE_ENDIAN) - r &= __lzo_assert(a[0] == 0x03020100L); - r &= __lzo_assert(a[1] == 0x04030201L); - r &= __lzo_assert(a[2] == 0x05040302L); - r &= __lzo_assert(a[3] == 0x06050403L); + r &= __lzo_assert(a[0] == 0x03020100L); + r &= __lzo_assert(a[1] == 0x04030201L); + r &= __lzo_assert(a[2] == 0x05040302L); + r &= __lzo_assert(a[3] == 0x06050403L); # elif (LZO_BYTE_ORDER == LZO_BIG_ENDIAN) - r &= __lzo_assert(a[0] == 0x00010203L); - r &= __lzo_assert(a[1] == 0x01020304L); - r &= __lzo_assert(a[2] == 0x02030405L); - r &= __lzo_assert(a[3] == 0x03040506L); + r &= __lzo_assert(a[0] == 0x00010203L); + r &= __lzo_assert(a[1] == 0x01020304L); + r &= __lzo_assert(a[2] == 0x02030405L); + r &= __lzo_assert(a[3] == 0x03040506L); # endif - } + } #endif #if defined(LZO_ALIGNED_OK_4) - COMPILE_TIME_ASSERT(sizeof(lzo_uint32) == 4); + COMPILE_TIME_ASSERT(sizeof(lzo_uint32) == 4); #endif - COMPILE_TIME_ASSERT(lzo_sizeof_dict_t == sizeof(lzo_dict_t)); + COMPILE_TIME_ASSERT(lzo_sizeof_dict_t == sizeof(lzo_dict_t)); #if defined(__LZO_IN_MINLZO) - if (r == 1) - { - lzo_uint32 adler; - adler = lzo_adler32(0, NULL, 0); - adler = lzo_adler32(adler, lzo_copyright(), 200); - r &= __lzo_assert(adler == 0xc76f1751L); - } -#endif - - if (r == 1) - { - r &= __lzo_assert(!schedule_insns_bug()); - } - - if (r == 1) - { - static int x[3]; - static unsigned xn = 3; - register unsigned j; - - for (j = 0; j < xn; j++) - x[j] = (int)j - 3; - r &= __lzo_assert(!strength_reduce_bug(x)); - } - - if (r == 1) - { - r &= ptr_check(); - } - - return r == 1 ? LZO_E_OK : LZO_E_ERROR; + if (r == 1) + { + lzo_uint32 adler; + adler = lzo_adler32(0, NULL, 0); + adler = lzo_adler32(adler, lzo_copyright(), 200); + r &= __lzo_assert(adler == 0xc76f1751L); + } +#endif + + if (r == 1) + { + r &= __lzo_assert(!schedule_insns_bug()); + } + + if (r == 1) + { + static int x[3]; + static unsigned xn = 3; + register unsigned j; + + for (j = 0; j < xn; j++) + x[j] = (int)j - 3; + r &= __lzo_assert(!strength_reduce_bug(x)); + } + + if (r == 1) + { + r &= ptr_check(); + } + + return r == 1 ? LZO_E_OK : LZO_E_ERROR; } static lzo_bool schedule_insns_bug(void) { #if defined(__LZO_CHECKER) - return 0; + return 0; #else - const int clone[] = {1, 2, 0}; - const int *q; - q = clone; - return (*q) ? 0 : 1; + const int clone[] = {1, 2, 0}; + const int *q; + q = clone; + return (*q) ? 0 : 1; #endif } static lzo_bool strength_reduce_bug(int *x) { - return x[0] != -3 || x[1] != -2 || x[2] != -1; + return x[0] != -3 || x[1] != -2 || x[2] != -1; } #undef COMPILE_TIME_ASSERT @@ -1102,32 +1102,32 @@ int __lzo_init_done = 0; LZO_PUBLIC(int) __lzo_init2(unsigned v, int s1, int s2, int s3, int s4, int s5, - int s6, int s7, int s8, int s9) + int s6, int s7, int s8, int s9) { - int r; - - __lzo_init_done = 1; - - if (v == 0) - return LZO_E_ERROR; - - r = (s1 == -1 || s1 == (int) sizeof(short)) && - (s2 == -1 || s2 == (int) sizeof(int)) && - (s3 == -1 || s3 == (int) sizeof(long)) && - (s4 == -1 || s4 == (int) sizeof(lzo_uint32)) && - (s5 == -1 || s5 == (int) sizeof(lzo_uint)) && - (s6 == -1 || s6 == (int) lzo_sizeof_dict_t) && - (s7 == -1 || s7 == (int) sizeof(char *)) && - (s8 == -1 || s8 == (int) sizeof(lzo_voidp)) && - (s9 == -1 || s9 == (int) sizeof(lzo_compress_t)); - if (!r) - return LZO_E_ERROR; - - r = _lzo_config_check(); - if (r != LZO_E_OK) - return r; - - return r; + int r; + + __lzo_init_done = 1; + + if (v == 0) + return LZO_E_ERROR; + + r = (s1 == -1 || s1 == (int) sizeof(short)) && + (s2 == -1 || s2 == (int) sizeof(int)) && + (s3 == -1 || s3 == (int) sizeof(long)) && + (s4 == -1 || s4 == (int) sizeof(lzo_uint32)) && + (s5 == -1 || s5 == (int) sizeof(lzo_uint)) && + (s6 == -1 || s6 == (int) lzo_sizeof_dict_t) && + (s7 == -1 || s7 == (int) sizeof(char *)) && + (s8 == -1 || s8 == (int) sizeof(lzo_voidp)) && + (s9 == -1 || s9 == (int) sizeof(lzo_compress_t)); + if (!r) + return LZO_E_ERROR; + + r = _lzo_config_check(); + if (r != LZO_E_OK) + return r; + + return r; } #if !defined(__LZO_IN_MINILZO) @@ -1138,9 +1138,9 @@ __lzo_init(unsigned v,int s1,int s2,int s3,int s4,int s5,int s6,int s7); LZO_PUBLIC(int) __lzo_init(unsigned v,int s1,int s2,int s3,int s4,int s5,int s6,int s7) { - if (v == 0 || v > 0x1010) - return LZO_E_ERROR; - return __lzo_init2(v,s1,s2,s3,s4,s5,-1,-1,s6,s7); + if (v == 0 || v > 0x1010) + return LZO_E_ERROR; + return __lzo_init2(v,s1,s2,s3,s4,s5,-1,-1,s6,s7); } #endif @@ -1272,27 +1272,27 @@ extern "C" { #if (DL_MIN_LEN == 3) # define _DV2_A(p,shift1,shift2) \ - (((( (lzo_uint32)((p)[0]) << shift1) ^ (p)[1]) << shift2) ^ (p)[2]) + (((( (lzo_uint32)((p)[0]) << shift1) ^ (p)[1]) << shift2) ^ (p)[2]) # define _DV2_B(p,shift1,shift2) \ - (((( (lzo_uint32)((p)[2]) << shift1) ^ (p)[1]) << shift2) ^ (p)[0]) + (((( (lzo_uint32)((p)[2]) << shift1) ^ (p)[1]) << shift2) ^ (p)[0]) # define _DV3_B(p,shift1,shift2,shift3) \ - ((_DV2_B((p)+1,shift1,shift2) << (shift3)) ^ (p)[0]) + ((_DV2_B((p)+1,shift1,shift2) << (shift3)) ^ (p)[0]) #elif (DL_MIN_LEN == 2) # define _DV2_A(p,shift1,shift2) \ - (( (lzo_uint32)(p[0]) << shift1) ^ p[1]) + (( (lzo_uint32)(p[0]) << shift1) ^ p[1]) # define _DV2_B(p,shift1,shift2) \ - (( (lzo_uint32)(p[1]) << shift1) ^ p[2]) + (( (lzo_uint32)(p[1]) << shift1) ^ p[2]) #else # error "invalid DL_MIN_LEN" #endif #define _DV_A(p,shift) _DV2_A(p,shift,shift) #define _DV_B(p,shift) _DV2_B(p,shift,shift) #define DA2(p,s1,s2) \ - (((((lzo_uint32)((p)[2]) << (s2)) + (p)[1]) << (s1)) + (p)[0]) + (((((lzo_uint32)((p)[2]) << (s2)) + (p)[1]) << (s1)) + (p)[0]) #define DS2(p,s1,s2) \ - (((((lzo_uint32)((p)[2]) << (s2)) - (p)[1]) << (s1)) - (p)[0]) + (((((lzo_uint32)((p)[2]) << (s2)) - (p)[1]) << (s1)) - (p)[0]) #define DX2(p,s1,s2) \ - (((((lzo_uint32)((p)[2]) << (s2)) ^ (p)[1]) << (s1)) ^ (p)[0]) + (((((lzo_uint32)((p)[2]) << (s2)) ^ (p)[1]) << (s1)) ^ (p)[0]) #define DA3(p,s1,s2,s3) ((DA2((p)+1,s2,s3) << (s1)) + (p)[0]) #define DS3(p,s1,s2,s3) ((DS2((p)+1,s2,s3) << (s1)) - (p)[0]) #define DX3(p,s1,s2,s3) ((DX2((p)+1,s2,s3) << (s1)) ^ (p)[0]) @@ -1313,7 +1313,7 @@ extern "C" { # define __LZO_HASH_INCREMENTAL # define DVAL_FIRST(dv,p) dv = _DV_A((p),5) # define DVAL_NEXT(dv,p) \ - dv ^= (lzo_uint32)(p[-1]) << (2*5); dv = (((dv) << 5) ^ p[2]) + dv ^= (lzo_uint32)(p[-1]) << (2*5); dv = (((dv) << 5) ^ p[2]) # define _DINDEX(dv,p) ((0x9f5f * (dv)) >> 5) # define DVAL_LOOKAHEAD DL_MIN_LEN @@ -1321,7 +1321,7 @@ extern "C" { # define __LZO_HASH_INCREMENTAL # define DVAL_FIRST(dv,p) dv = _DV_B((p),5) # define DVAL_NEXT(dv,p) \ - dv ^= p[-1]; dv = (((dv) >> 5) ^ ((lzo_uint32)(p[2]) << (2*5))) + dv ^= p[-1]; dv = (((dv) >> 5) ^ ((lzo_uint32)(p[2]) << (2*5))) # define _DINDEX(dv,p) ((0x9f5f * (dv)) >> 5) # define DVAL_LOOKAHEAD DL_MIN_LEN @@ -1364,36 +1364,36 @@ extern "C" { #else # define UPDATE_D(dict,drun,dv,p,in) \ - dict[ DINDEX(dv,p) + drun++ ] = DENTRY(p,in); drun &= DD_MASK + dict[ DINDEX(dv,p) + drun++ ] = DENTRY(p,in); drun &= DD_MASK # define UPDATE_I(dict,drun,index,p,in) \ - dict[ (index) + drun++ ] = DENTRY(p,in); drun &= DD_MASK + dict[ (index) + drun++ ] = DENTRY(p,in); drun &= DD_MASK # define UPDATE_P(ptr,drun,p,in) \ - (ptr) [ drun++ ] = DENTRY(p,in); drun &= DD_MASK + (ptr) [ drun++ ] = DENTRY(p,in); drun &= DD_MASK #endif #if defined(LZO_DICT_USE_PTR) #define LZO_CHECK_MPOS_DET(m_pos,m_off,in,ip,max_offset) \ - (m_pos == NULL || (m_off = (lzo_moff_t) (ip - m_pos)) > max_offset) + (m_pos == NULL || (m_off = (lzo_moff_t) (ip - m_pos)) > max_offset) #define LZO_CHECK_MPOS_NON_DET(m_pos,m_off,in,ip,max_offset) \ - (BOUNDS_CHECKING_OFF_IN_EXPR( \ - (PTR_LT(m_pos,in) || \ - (m_off = (lzo_moff_t) PTR_DIFF(ip,m_pos)) <= 0 || \ - m_off > max_offset) )) + (BOUNDS_CHECKING_OFF_IN_EXPR( \ + (PTR_LT(m_pos,in) || \ + (m_off = (lzo_moff_t) PTR_DIFF(ip,m_pos)) <= 0 || \ + m_off > max_offset) )) #else #define LZO_CHECK_MPOS_DET(m_pos,m_off,in,ip,max_offset) \ - (m_off == 0 || \ - ((m_off = (lzo_moff_t) ((ip)-(in)) - m_off) > max_offset) || \ - (m_pos = (ip) - (m_off), 0) ) + (m_off == 0 || \ + ((m_off = (lzo_moff_t) ((ip)-(in)) - m_off) > max_offset) || \ + (m_pos = (ip) - (m_off), 0) ) #define LZO_CHECK_MPOS_NON_DET(m_pos,m_off,in,ip,max_offset) \ - ((lzo_moff_t) ((ip)-(in)) <= m_off || \ - ((m_off = (lzo_moff_t) ((ip)-(in)) - m_off) > max_offset) || \ - (m_pos = (ip) - (m_off), 0) ) + ((lzo_moff_t) ((ip)-(in)) <= m_off || \ + ((m_off = (lzo_moff_t) ((ip)-(in)) - m_off) > max_offset) || \ + (m_pos = (ip) - (m_off), 0) ) #endif @@ -1418,302 +1418,302 @@ extern "C" { static lzo_uint do_compress ( const lzo_byte *in , lzo_uint in_len, - lzo_byte *out, lzo_uintp out_len, - lzo_voidp wrkmem ) + lzo_byte *out, lzo_uintp out_len, + lzo_voidp wrkmem ) { #if 0 && defined(__GNUC__) && defined(__i386__) - register const lzo_byte *ip __asm__("%esi"); + register const lzo_byte *ip __asm__("%esi"); #else - register const lzo_byte *ip; + register const lzo_byte *ip; #endif - lzo_byte *op; - const lzo_byte * const in_end = in + in_len; - const lzo_byte * const ip_end = in + in_len - M2_MAX_LEN - 5; - const lzo_byte *ii; - lzo_dict_p const dict = (lzo_dict_p) wrkmem; + lzo_byte *op; + const lzo_byte * const in_end = in + in_len; + const lzo_byte * const ip_end = in + in_len - M2_MAX_LEN - 5; + const lzo_byte *ii; + lzo_dict_p const dict = (lzo_dict_p) wrkmem; - op = out; - ip = in; - ii = ip; + op = out; + ip = in; + ii = ip; - ip += 4; - for (;;) - { + ip += 4; + for (;;) + { #if 0 && defined(__GNUC__) && defined(__i386__) - register const lzo_byte *m_pos __asm__("%edi"); + register const lzo_byte *m_pos __asm__("%edi"); #else - register const lzo_byte *m_pos; + register const lzo_byte *m_pos; #endif - lzo_moff_t m_off; - lzo_uint m_len; - lzo_uint dindex; + lzo_moff_t m_off; + lzo_uint m_len; + lzo_uint dindex; - DINDEX1(dindex,ip); - GINDEX(m_pos,m_off,dict,dindex,in); - if (LZO_CHECK_MPOS_NON_DET(m_pos,m_off,in,ip,M4_MAX_OFFSET)) - goto literal; + DINDEX1(dindex,ip); + GINDEX(m_pos,m_off,dict,dindex,in); + if (LZO_CHECK_MPOS_NON_DET(m_pos,m_off,in,ip,M4_MAX_OFFSET)) + goto literal; #if 1 - if (m_off <= M2_MAX_OFFSET || m_pos[3] == ip[3]) - goto try_match; - DINDEX2(dindex,ip); + if (m_off <= M2_MAX_OFFSET || m_pos[3] == ip[3]) + goto try_match; + DINDEX2(dindex,ip); #endif - GINDEX(m_pos,m_off,dict,dindex,in); - if (LZO_CHECK_MPOS_NON_DET(m_pos,m_off,in,ip,M4_MAX_OFFSET)) - goto literal; - if (m_off <= M2_MAX_OFFSET || m_pos[3] == ip[3]) - goto try_match; - goto literal; + GINDEX(m_pos,m_off,dict,dindex,in); + if (LZO_CHECK_MPOS_NON_DET(m_pos,m_off,in,ip,M4_MAX_OFFSET)) + goto literal; + if (m_off <= M2_MAX_OFFSET || m_pos[3] == ip[3]) + goto try_match; + goto literal; try_match: #if 1 && defined(LZO_UNALIGNED_OK_2) - if (* (const lzo_ushortp) m_pos != * (const lzo_ushortp) ip) + if (* (const lzo_ushortp) m_pos != * (const lzo_ushortp) ip) #else - if (m_pos[0] != ip[0] || m_pos[1] != ip[1]) + if (m_pos[0] != ip[0] || m_pos[1] != ip[1]) #endif - { - } - else - { - if (m_pos[2] == ip[2]) - { + { + } + else + { + if (m_pos[2] == ip[2]) + { #if 0 - if (m_off <= M2_MAX_OFFSET) - goto match; - if (lit <= 3) - goto match; - if (lit == 3) - { - assert(op - 2 > out); op[-2] |= LZO_BYTE(3); - *op++ = *ii++; *op++ = *ii++; *op++ = *ii++; - goto code_match; - } - if (m_pos[3] == ip[3]) -#endif - goto match; - } - else - { + if (m_off <= M2_MAX_OFFSET) + goto match; + if (lit <= 3) + goto match; + if (lit == 3) + { + assert(op - 2 > out); op[-2] |= LZO_BYTE(3); + *op++ = *ii++; *op++ = *ii++; *op++ = *ii++; + goto code_match; + } + if (m_pos[3] == ip[3]) +#endif + goto match; + } + else + { #if 0 #if 0 - if (m_off <= M1_MAX_OFFSET && lit > 0 && lit <= 3) + if (m_off <= M1_MAX_OFFSET && lit > 0 && lit <= 3) #else - if (m_off <= M1_MAX_OFFSET && lit == 3) + if (m_off <= M1_MAX_OFFSET && lit == 3) #endif - { - register lzo_uint t; + { + register lzo_uint t; - t = lit; - assert(op - 2 > out); op[-2] |= LZO_BYTE(t); - do *op++ = *ii++; while (--t > 0); - assert(ii == ip); - m_off -= 1; - *op++ = LZO_BYTE(M1_MARKER | ((m_off & 3) << 2)); - *op++ = LZO_BYTE(m_off >> 2); - ip += 2; - goto match_done; - } + t = lit; + assert(op - 2 > out); op[-2] |= LZO_BYTE(t); + do *op++ = *ii++; while (--t > 0); + assert(ii == ip); + m_off -= 1; + *op++ = LZO_BYTE(M1_MARKER | ((m_off & 3) << 2)); + *op++ = LZO_BYTE(m_off >> 2); + ip += 2; + goto match_done; + } #endif - } - } + } + } literal: - UPDATE_I(dict,0,dindex,ip,in); - ++ip; - if (ip >= ip_end) - break; - continue; + UPDATE_I(dict,0,dindex,ip,in); + ++ip; + if (ip >= ip_end) + break; + continue; match: - UPDATE_I(dict,0,dindex,ip,in); - if (pd(ip,ii) > 0) - { - register lzo_uint t = pd(ip,ii); - - if (t <= 3) - { - assert(op - 2 > out); - op[-2] |= LZO_BYTE(t); - } - else if (t <= 18) - *op++ = LZO_BYTE(t - 3); - else - { - register lzo_uint tt = t - 18; - - *op++ = 0; - while (tt > 255) - { - tt -= 255; - *op++ = 0; - } - assert(tt > 0); - *op++ = LZO_BYTE(tt); - } - do *op++ = *ii++; while (--t > 0); - } - - assert(ii == ip); - ip += 3; - if (m_pos[3] != *ip++ || m_pos[4] != *ip++ || m_pos[5] != *ip++ || - m_pos[6] != *ip++ || m_pos[7] != *ip++ || m_pos[8] != *ip++ + UPDATE_I(dict,0,dindex,ip,in); + if (pd(ip,ii) > 0) + { + register lzo_uint t = pd(ip,ii); + + if (t <= 3) + { + assert(op - 2 > out); + op[-2] |= LZO_BYTE(t); + } + else if (t <= 18) + *op++ = LZO_BYTE(t - 3); + else + { + register lzo_uint tt = t - 18; + + *op++ = 0; + while (tt > 255) + { + tt -= 255; + *op++ = 0; + } + assert(tt > 0); + *op++ = LZO_BYTE(tt); + } + do *op++ = *ii++; while (--t > 0); + } + + assert(ii == ip); + ip += 3; + if (m_pos[3] != *ip++ || m_pos[4] != *ip++ || m_pos[5] != *ip++ || + m_pos[6] != *ip++ || m_pos[7] != *ip++ || m_pos[8] != *ip++ #ifdef LZO1Y - || m_pos[ 9] != *ip++ || m_pos[10] != *ip++ || m_pos[11] != *ip++ - || m_pos[12] != *ip++ || m_pos[13] != *ip++ || m_pos[14] != *ip++ -#endif - ) - { - --ip; - m_len = ip - ii; - assert(m_len >= 3); assert(m_len <= M2_MAX_LEN); - - if (m_off <= M2_MAX_OFFSET) - { - m_off -= 1; + || m_pos[ 9] != *ip++ || m_pos[10] != *ip++ || m_pos[11] != *ip++ + || m_pos[12] != *ip++ || m_pos[13] != *ip++ || m_pos[14] != *ip++ +#endif + ) + { + --ip; + m_len = ip - ii; + assert(m_len >= 3); assert(m_len <= M2_MAX_LEN); + + if (m_off <= M2_MAX_OFFSET) + { + m_off -= 1; #if defined(LZO1X) - *op++ = LZO_BYTE(((m_len - 1) << 5) | ((m_off & 7) << 2)); - *op++ = LZO_BYTE(m_off >> 3); + *op++ = LZO_BYTE(((m_len - 1) << 5) | ((m_off & 7) << 2)); + *op++ = LZO_BYTE(m_off >> 3); #elif defined(LZO1Y) - *op++ = LZO_BYTE(((m_len + 1) << 4) | ((m_off & 3) << 2)); - *op++ = LZO_BYTE(m_off >> 2); -#endif - } - else if (m_off <= M3_MAX_OFFSET) - { - m_off -= 1; - *op++ = LZO_BYTE(M3_MARKER | (m_len - 2)); - goto m3_m4_offset; - } - else + *op++ = LZO_BYTE(((m_len + 1) << 4) | ((m_off & 3) << 2)); + *op++ = LZO_BYTE(m_off >> 2); +#endif + } + else if (m_off <= M3_MAX_OFFSET) + { + m_off -= 1; + *op++ = LZO_BYTE(M3_MARKER | (m_len - 2)); + goto m3_m4_offset; + } + else #if defined(LZO1X) - { - m_off -= 0x4000; - assert(m_off > 0); assert(m_off <= 0x7fff); - *op++ = LZO_BYTE(M4_MARKER | - ((m_off & 0x4000) >> 11) | (m_len - 2)); - goto m3_m4_offset; - } + { + m_off -= 0x4000; + assert(m_off > 0); assert(m_off <= 0x7fff); + *op++ = LZO_BYTE(M4_MARKER | + ((m_off & 0x4000) >> 11) | (m_len - 2)); + goto m3_m4_offset; + } #elif defined(LZO1Y) - goto m4_match; -#endif - } - else - { - { - const lzo_byte *end = in_end; - const lzo_byte *m = m_pos + M2_MAX_LEN + 1; - while (ip < end && *m == *ip) - m++, ip++; - m_len = (ip - ii); - } - assert(m_len > M2_MAX_LEN); - - if (m_off <= M3_MAX_OFFSET) - { - m_off -= 1; - if (m_len <= 33) - *op++ = LZO_BYTE(M3_MARKER | (m_len - 2)); - else - { - m_len -= 33; - *op++ = M3_MARKER | 0; - goto m3_m4_len; - } - } - else - { + goto m4_match; +#endif + } + else + { + { + const lzo_byte *end = in_end; + const lzo_byte *m = m_pos + M2_MAX_LEN + 1; + while (ip < end && *m == *ip) + m++, ip++; + m_len = (ip - ii); + } + assert(m_len > M2_MAX_LEN); + + if (m_off <= M3_MAX_OFFSET) + { + m_off -= 1; + if (m_len <= 33) + *op++ = LZO_BYTE(M3_MARKER | (m_len - 2)); + else + { + m_len -= 33; + *op++ = M3_MARKER | 0; + goto m3_m4_len; + } + } + else + { #if defined(LZO1Y) m4_match: #endif - m_off -= 0x4000; - assert(m_off > 0); assert(m_off <= 0x7fff); - if (m_len <= M4_MAX_LEN) - *op++ = LZO_BYTE(M4_MARKER | - ((m_off & 0x4000) >> 11) | (m_len - 2)); - else - { - m_len -= M4_MAX_LEN; - *op++ = LZO_BYTE(M4_MARKER | ((m_off & 0x4000) >> 11)); + m_off -= 0x4000; + assert(m_off > 0); assert(m_off <= 0x7fff); + if (m_len <= M4_MAX_LEN) + *op++ = LZO_BYTE(M4_MARKER | + ((m_off & 0x4000) >> 11) | (m_len - 2)); + else + { + m_len -= M4_MAX_LEN; + *op++ = LZO_BYTE(M4_MARKER | ((m_off & 0x4000) >> 11)); m3_m4_len: - while (m_len > 255) - { - m_len -= 255; - *op++ = 0; - } - assert(m_len > 0); - *op++ = LZO_BYTE(m_len); - } - } + while (m_len > 255) + { + m_len -= 255; + *op++ = 0; + } + assert(m_len > 0); + *op++ = LZO_BYTE(m_len); + } + } m3_m4_offset: - *op++ = LZO_BYTE((m_off & 63) << 2); - *op++ = LZO_BYTE(m_off >> 6); - } + *op++ = LZO_BYTE((m_off & 63) << 2); + *op++ = LZO_BYTE(m_off >> 6); + } #if 0 match_done: #endif - ii = ip; - if (ip >= ip_end) - break; - } + ii = ip; + if (ip >= ip_end) + break; + } - *out_len = op - out; - return pd(in_end,ii); + *out_len = op - out; + return pd(in_end,ii); } LZO_PUBLIC(int) DO_COMPRESS ( const lzo_byte *in , lzo_uint in_len, - lzo_byte *out, lzo_uintp out_len, - lzo_voidp wrkmem ) + lzo_byte *out, lzo_uintp out_len, + lzo_voidp wrkmem ) { - lzo_byte *op = out; - lzo_uint t; + lzo_byte *op = out; + lzo_uint t; #if defined(__LZO_QUERY_COMPRESS) - if (__LZO_IS_COMPRESS_QUERY(in,in_len,out,out_len,wrkmem)) - return __LZO_QUERY_COMPRESS(in,in_len,out,out_len,wrkmem,D_SIZE,lzo_sizeof(lzo_dict_t)); -#endif - - if (in_len <= M2_MAX_LEN + 5) - t = in_len; - else - { - t = do_compress(in,in_len,op,out_len,wrkmem); - op += *out_len; - } - - if (t > 0) - { - const lzo_byte *ii = in + in_len - t; - - if (op == out && t <= 238) - *op++ = LZO_BYTE(17 + t); - else if (t <= 3) - op[-2] |= LZO_BYTE(t); - else if (t <= 18) - *op++ = LZO_BYTE(t - 3); - else - { - lzo_uint tt = t - 18; - - *op++ = 0; - while (tt > 255) - { - tt -= 255; - *op++ = 0; - } - assert(tt > 0); - *op++ = LZO_BYTE(tt); - } - do *op++ = *ii++; while (--t > 0); - } - - *op++ = M4_MARKER | 1; - *op++ = 0; - *op++ = 0; - - *out_len = op - out; - return LZO_E_OK; + if (__LZO_IS_COMPRESS_QUERY(in,in_len,out,out_len,wrkmem)) + return __LZO_QUERY_COMPRESS(in,in_len,out,out_len,wrkmem,D_SIZE,lzo_sizeof(lzo_dict_t)); +#endif + + if (in_len <= M2_MAX_LEN + 5) + t = in_len; + else + { + t = do_compress(in,in_len,op,out_len,wrkmem); + op += *out_len; + } + + if (t > 0) + { + const lzo_byte *ii = in + in_len - t; + + if (op == out && t <= 238) + *op++ = LZO_BYTE(17 + t); + else if (t <= 3) + op[-2] |= LZO_BYTE(t); + else if (t <= 18) + *op++ = LZO_BYTE(t - 3); + else + { + lzo_uint tt = t - 18; + + *op++ = 0; + while (tt > 255) + { + tt -= 255; + *op++ = 0; + } + assert(tt > 0); + *op++ = LZO_BYTE(tt); + } + do *op++ = *ii++; while (--t > 0); + } + + *op++ = M4_MARKER | 1; + *op++ = 0; + *op++ = 0; + + *out_len = op - out; + return LZO_E_OK; } #undef do_compress @@ -1757,7 +1757,7 @@ DO_COMPRESS ( const lzo_byte *in , lzo_uint in_len, # endif # if (LZO_TEST_DECOMPRESS_OVERRUN_INPUT >= 2) # define NEED_IP(x) \ - if ((lzo_uint)(ip_end - ip) < (lzo_uint)(x)) goto input_overrun + if ((lzo_uint)(ip_end - ip) < (lzo_uint)(x)) goto input_overrun # endif #endif @@ -1768,7 +1768,7 @@ DO_COMPRESS ( const lzo_byte *in , lzo_uint in_len, # if (LZO_TEST_DECOMPRESS_OVERRUN_OUTPUT >= 2) # undef TEST_OP # define NEED_OP(x) \ - if ((lzo_uint)(op_end - op) < (lzo_uint)(x)) goto output_overrun + if ((lzo_uint)(op_end - op) < (lzo_uint)(x)) goto output_overrun # endif #endif @@ -1824,394 +1824,394 @@ DO_COMPRESS ( const lzo_byte *in , lzo_uint in_len, #if defined(DO_DECOMPRESS) LZO_PUBLIC(int) DO_DECOMPRESS ( const lzo_byte *in , lzo_uint in_len, - lzo_byte *out, lzo_uintp out_len, - lzo_voidp wrkmem ) + lzo_byte *out, lzo_uintp out_len, + lzo_voidp wrkmem ) #endif { - register lzo_byte *op; - register const lzo_byte *ip; - register lzo_uint t; + register lzo_byte *op; + register const lzo_byte *ip; + register lzo_uint t; #if defined(COPY_DICT) - lzo_uint m_off; - const lzo_byte *dict_end; + lzo_uint m_off; + const lzo_byte *dict_end; #else - register const lzo_byte *m_pos; + register const lzo_byte *m_pos; #endif - const lzo_byte * const ip_end = in + in_len; + const lzo_byte * const ip_end = in + in_len; #if defined(HAVE_ANY_OP) - lzo_byte * const op_end = out + *out_len; + lzo_byte * const op_end = out + *out_len; #endif #if defined(LZO1Z) - lzo_uint last_m_off = 0; + lzo_uint last_m_off = 0; #endif - LZO_UNUSED(wrkmem); + LZO_UNUSED(wrkmem); #if defined(__LZO_QUERY_DECOMPRESS) - if (__LZO_IS_DECOMPRESS_QUERY(in,in_len,out,out_len,wrkmem)) - return __LZO_QUERY_DECOMPRESS(in,in_len,out,out_len,wrkmem,0,0); + if (__LZO_IS_DECOMPRESS_QUERY(in,in_len,out,out_len,wrkmem)) + return __LZO_QUERY_DECOMPRESS(in,in_len,out,out_len,wrkmem,0,0); #endif #if defined(COPY_DICT) - if (dict) - { - if (dict_len > M4_MAX_OFFSET) - { - dict += dict_len - M4_MAX_OFFSET; - dict_len = M4_MAX_OFFSET; - } - dict_end = dict + dict_len; - } - else - { - dict_len = 0; - dict_end = NULL; - } -#endif - - *out_len = 0; - - op = out; - ip = in; - - if (*ip > 17) - { - t = *ip++ - 17; - if (t < 4) - goto match_next; - assert(t > 0); NEED_OP(t); NEED_IP(t+1); - do *op++ = *ip++; while (--t > 0); - goto first_literal_run; - } - - while (TEST_IP && TEST_OP) - { - t = *ip++; - if (t >= 16) - goto match; - if (t == 0) - { - NEED_IP(1); - while (*ip == 0) - { - t += 255; - ip++; - NEED_IP(1); - } - t += 15 + *ip++; - } - assert(t > 0); NEED_OP(t+3); NEED_IP(t+4); + if (dict) + { + if (dict_len > M4_MAX_OFFSET) + { + dict += dict_len - M4_MAX_OFFSET; + dict_len = M4_MAX_OFFSET; + } + dict_end = dict + dict_len; + } + else + { + dict_len = 0; + dict_end = NULL; + } +#endif + + *out_len = 0; + + op = out; + ip = in; + + if (*ip > 17) + { + t = *ip++ - 17; + if (t < 4) + goto match_next; + assert(t > 0); NEED_OP(t); NEED_IP(t+1); + do *op++ = *ip++; while (--t > 0); + goto first_literal_run; + } + + while (TEST_IP && TEST_OP) + { + t = *ip++; + if (t >= 16) + goto match; + if (t == 0) + { + NEED_IP(1); + while (*ip == 0) + { + t += 255; + ip++; + NEED_IP(1); + } + t += 15 + *ip++; + } + assert(t > 0); NEED_OP(t+3); NEED_IP(t+4); #if defined(LZO_UNALIGNED_OK_4) || defined(LZO_ALIGNED_OK_4) #if !defined(LZO_UNALIGNED_OK_4) - if (PTR_ALIGNED2_4(op,ip)) - { -#endif - COPY4(op,ip); - op += 4; ip += 4; - if (--t > 0) - { - if (t >= 4) - { - do { - COPY4(op,ip); - op += 4; ip += 4; t -= 4; - } while (t >= 4); - if (t > 0) do *op++ = *ip++; while (--t > 0); - } - else - do *op++ = *ip++; while (--t > 0); - } + if (PTR_ALIGNED2_4(op,ip)) + { +#endif + COPY4(op,ip); + op += 4; ip += 4; + if (--t > 0) + { + if (t >= 4) + { + do { + COPY4(op,ip); + op += 4; ip += 4; t -= 4; + } while (t >= 4); + if (t > 0) do *op++ = *ip++; while (--t > 0); + } + else + do *op++ = *ip++; while (--t > 0); + } #if !defined(LZO_UNALIGNED_OK_4) - } - else + } + else #endif #endif #if !defined(LZO_UNALIGNED_OK_4) - { - *op++ = *ip++; *op++ = *ip++; *op++ = *ip++; - do *op++ = *ip++; while (--t > 0); - } + { + *op++ = *ip++; *op++ = *ip++; *op++ = *ip++; + do *op++ = *ip++; while (--t > 0); + } #endif first_literal_run: - t = *ip++; - if (t >= 16) - goto match; + t = *ip++; + if (t >= 16) + goto match; #if defined(COPY_DICT) #if defined(LZO1Z) - m_off = (1 + M2_MAX_OFFSET) + (t << 6) + (*ip++ >> 2); - last_m_off = m_off; + m_off = (1 + M2_MAX_OFFSET) + (t << 6) + (*ip++ >> 2); + last_m_off = m_off; #else - m_off = (1 + M2_MAX_OFFSET) + (t >> 2) + (*ip++ << 2); + m_off = (1 + M2_MAX_OFFSET) + (t >> 2) + (*ip++ << 2); #endif - NEED_OP(3); - t = 3; COPY_DICT(t,m_off) + NEED_OP(3); + t = 3; COPY_DICT(t,m_off) #else #if defined(LZO1Z) - t = (1 + M2_MAX_OFFSET) + (t << 6) + (*ip++ >> 2); - m_pos = op - t; - last_m_off = t; + t = (1 + M2_MAX_OFFSET) + (t << 6) + (*ip++ >> 2); + m_pos = op - t; + last_m_off = t; #else - m_pos = op - (1 + M2_MAX_OFFSET); - m_pos -= t >> 2; - m_pos -= *ip++ << 2; + m_pos = op - (1 + M2_MAX_OFFSET); + m_pos -= t >> 2; + m_pos -= *ip++ << 2; #endif - TEST_LOOKBEHIND(m_pos,out); NEED_OP(3); - *op++ = *m_pos++; *op++ = *m_pos++; *op++ = *m_pos; + TEST_LOOKBEHIND(m_pos,out); NEED_OP(3); + *op++ = *m_pos++; *op++ = *m_pos++; *op++ = *m_pos; #endif - goto match_done; + goto match_done; - while (TEST_IP && TEST_OP) - { + while (TEST_IP && TEST_OP) + { match: - if (t >= 64) - { + if (t >= 64) + { #if defined(COPY_DICT) #if defined(LZO1X) - m_off = 1 + ((t >> 2) & 7) + (*ip++ << 3); - t = (t >> 5) - 1; + m_off = 1 + ((t >> 2) & 7) + (*ip++ << 3); + t = (t >> 5) - 1; #elif defined(LZO1Y) - m_off = 1 + ((t >> 2) & 3) + (*ip++ << 2); - t = (t >> 4) - 3; + m_off = 1 + ((t >> 2) & 3) + (*ip++ << 2); + t = (t >> 4) - 3; #elif defined(LZO1Z) - m_off = t & 0x1f; - if (m_off >= 0x1c) - m_off = last_m_off; - else - { - m_off = 1 + (m_off << 6) + (*ip++ >> 2); - last_m_off = m_off; - } - t = (t >> 5) - 1; + m_off = t & 0x1f; + if (m_off >= 0x1c) + m_off = last_m_off; + else + { + m_off = 1 + (m_off << 6) + (*ip++ >> 2); + last_m_off = m_off; + } + t = (t >> 5) - 1; #endif #else #if defined(LZO1X) - m_pos = op - 1; - m_pos -= (t >> 2) & 7; - m_pos -= *ip++ << 3; - t = (t >> 5) - 1; + m_pos = op - 1; + m_pos -= (t >> 2) & 7; + m_pos -= *ip++ << 3; + t = (t >> 5) - 1; #elif defined(LZO1Y) - m_pos = op - 1; - m_pos -= (t >> 2) & 3; - m_pos -= *ip++ << 2; - t = (t >> 4) - 3; + m_pos = op - 1; + m_pos -= (t >> 2) & 3; + m_pos -= *ip++ << 2; + t = (t >> 4) - 3; #elif defined(LZO1Z) - { - lzo_uint off = t & 0x1f; - m_pos = op; - if (off >= 0x1c) - { - assert(last_m_off > 0); - m_pos -= last_m_off; - } - else - { - off = 1 + (off << 6) + (*ip++ >> 2); - m_pos -= off; - last_m_off = off; - } - } - t = (t >> 5) - 1; -#endif - TEST_LOOKBEHIND(m_pos,out); assert(t > 0); NEED_OP(t+3-1); - goto copy_match; -#endif - } - else if (t >= 32) - { - t &= 31; - if (t == 0) - { - NEED_IP(1); - while (*ip == 0) - { - t += 255; - ip++; - NEED_IP(1); - } - t += 31 + *ip++; - } + { + lzo_uint off = t & 0x1f; + m_pos = op; + if (off >= 0x1c) + { + assert(last_m_off > 0); + m_pos -= last_m_off; + } + else + { + off = 1 + (off << 6) + (*ip++ >> 2); + m_pos -= off; + last_m_off = off; + } + } + t = (t >> 5) - 1; +#endif + TEST_LOOKBEHIND(m_pos,out); assert(t > 0); NEED_OP(t+3-1); + goto copy_match; +#endif + } + else if (t >= 32) + { + t &= 31; + if (t == 0) + { + NEED_IP(1); + while (*ip == 0) + { + t += 255; + ip++; + NEED_IP(1); + } + t += 31 + *ip++; + } #if defined(COPY_DICT) #if defined(LZO1Z) - m_off = 1 + (ip[0] << 6) + (ip[1] >> 2); - last_m_off = m_off; + m_off = 1 + (ip[0] << 6) + (ip[1] >> 2); + last_m_off = m_off; #else - m_off = 1 + (ip[0] >> 2) + (ip[1] << 6); + m_off = 1 + (ip[0] >> 2) + (ip[1] << 6); #endif #else #if defined(LZO1Z) - { - lzo_uint off = 1 + (ip[0] << 6) + (ip[1] >> 2); - m_pos = op - off; - last_m_off = off; - } + { + lzo_uint off = 1 + (ip[0] << 6) + (ip[1] >> 2); + m_pos = op - off; + last_m_off = off; + } #elif defined(LZO_UNALIGNED_OK_2) && (LZO_BYTE_ORDER == LZO_LITTLE_ENDIAN) - m_pos = op - 1; - m_pos -= (* (const lzo_ushortp) ip) >> 2; + m_pos = op - 1; + m_pos -= (* (const lzo_ushortp) ip) >> 2; #else - m_pos = op - 1; - m_pos -= (ip[0] >> 2) + (ip[1] << 6); + m_pos = op - 1; + m_pos -= (ip[0] >> 2) + (ip[1] << 6); #endif #endif - ip += 2; - } - else if (t >= 16) - { + ip += 2; + } + else if (t >= 16) + { #if defined(COPY_DICT) - m_off = (t & 8) << 11; -#else - m_pos = op; - m_pos -= (t & 8) << 11; -#endif - t &= 7; - if (t == 0) - { - NEED_IP(1); - while (*ip == 0) - { - t += 255; - ip++; - NEED_IP(1); - } - t += 7 + *ip++; - } + m_off = (t & 8) << 11; +#else + m_pos = op; + m_pos -= (t & 8) << 11; +#endif + t &= 7; + if (t == 0) + { + NEED_IP(1); + while (*ip == 0) + { + t += 255; + ip++; + NEED_IP(1); + } + t += 7 + *ip++; + } #if defined(COPY_DICT) #if defined(LZO1Z) - m_off += (ip[0] << 6) + (ip[1] >> 2); + m_off += (ip[0] << 6) + (ip[1] >> 2); #else - m_off += (ip[0] >> 2) + (ip[1] << 6); + m_off += (ip[0] >> 2) + (ip[1] << 6); #endif - ip += 2; - if (m_off == 0) - goto eof_found; - m_off += 0x4000; + ip += 2; + if (m_off == 0) + goto eof_found; + m_off += 0x4000; #if defined(LZO1Z) - last_m_off = m_off; + last_m_off = m_off; #endif #else #if defined(LZO1Z) - m_pos -= (ip[0] << 6) + (ip[1] >> 2); + m_pos -= (ip[0] << 6) + (ip[1] >> 2); #elif defined(LZO_UNALIGNED_OK_2) && (LZO_BYTE_ORDER == LZO_LITTLE_ENDIAN) - m_pos -= (* (const lzo_ushortp) ip) >> 2; + m_pos -= (* (const lzo_ushortp) ip) >> 2; #else - m_pos -= (ip[0] >> 2) + (ip[1] << 6); + m_pos -= (ip[0] >> 2) + (ip[1] << 6); #endif - ip += 2; - if (m_pos == op) - goto eof_found; - m_pos -= 0x4000; + ip += 2; + if (m_pos == op) + goto eof_found; + m_pos -= 0x4000; #if defined(LZO1Z) - last_m_off = op - m_pos; + last_m_off = op - m_pos; #endif #endif - } - else - { + } + else + { #if defined(COPY_DICT) #if defined(LZO1Z) - m_off = 1 + (t << 6) + (*ip++ >> 2); - last_m_off = m_off; + m_off = 1 + (t << 6) + (*ip++ >> 2); + last_m_off = m_off; #else - m_off = 1 + (t >> 2) + (*ip++ << 2); + m_off = 1 + (t >> 2) + (*ip++ << 2); #endif - NEED_OP(2); - t = 2; COPY_DICT(t,m_off) + NEED_OP(2); + t = 2; COPY_DICT(t,m_off) #else #if defined(LZO1Z) - t = 1 + (t << 6) + (*ip++ >> 2); - m_pos = op - t; - last_m_off = t; + t = 1 + (t << 6) + (*ip++ >> 2); + m_pos = op - t; + last_m_off = t; #else - m_pos = op - 1; - m_pos -= t >> 2; - m_pos -= *ip++ << 2; + m_pos = op - 1; + m_pos -= t >> 2; + m_pos -= *ip++ << 2; #endif - TEST_LOOKBEHIND(m_pos,out); NEED_OP(2); - *op++ = *m_pos++; *op++ = *m_pos; + TEST_LOOKBEHIND(m_pos,out); NEED_OP(2); + *op++ = *m_pos++; *op++ = *m_pos; #endif - goto match_done; - } + goto match_done; + } #if defined(COPY_DICT) - NEED_OP(t+3-1); - t += 3-1; COPY_DICT(t,m_off) + NEED_OP(t+3-1); + t += 3-1; COPY_DICT(t,m_off) #else - TEST_LOOKBEHIND(m_pos,out); assert(t > 0); NEED_OP(t+3-1); + TEST_LOOKBEHIND(m_pos,out); assert(t > 0); NEED_OP(t+3-1); #if defined(LZO_UNALIGNED_OK_4) || defined(LZO_ALIGNED_OK_4) #if !defined(LZO_UNALIGNED_OK_4) - if (t >= 2 * 4 - (3 - 1) && PTR_ALIGNED2_4(op,m_pos)) - { - assert((op - m_pos) >= 4); -#else - if (t >= 2 * 4 - (3 - 1) && (op - m_pos) >= 4) - { -#endif - COPY4(op,m_pos); - op += 4; m_pos += 4; t -= 4 - (3 - 1); - do { - COPY4(op,m_pos); - op += 4; m_pos += 4; t -= 4; - } while (t >= 4); - if (t > 0) do *op++ = *m_pos++; while (--t > 0); - } - else -#endif - { + if (t >= 2 * 4 - (3 - 1) && PTR_ALIGNED2_4(op,m_pos)) + { + assert((op - m_pos) >= 4); +#else + if (t >= 2 * 4 - (3 - 1) && (op - m_pos) >= 4) + { +#endif + COPY4(op,m_pos); + op += 4; m_pos += 4; t -= 4 - (3 - 1); + do { + COPY4(op,m_pos); + op += 4; m_pos += 4; t -= 4; + } while (t >= 4); + if (t > 0) do *op++ = *m_pos++; while (--t > 0); + } + else +#endif + { copy_match: - *op++ = *m_pos++; *op++ = *m_pos++; - do *op++ = *m_pos++; while (--t > 0); - } + *op++ = *m_pos++; *op++ = *m_pos++; + do *op++ = *m_pos++; while (--t > 0); + } #endif match_done: #if defined(LZO1Z) - t = ip[-1] & 3; + t = ip[-1] & 3; #else - t = ip[-2] & 3; + t = ip[-2] & 3; #endif - if (t == 0) - break; + if (t == 0) + break; match_next: - assert(t > 0); NEED_OP(t); NEED_IP(t+1); - do *op++ = *ip++; while (--t > 0); - t = *ip++; - } - } + assert(t > 0); NEED_OP(t); NEED_IP(t+1); + do *op++ = *ip++; while (--t > 0); + t = *ip++; + } + } #if defined(HAVE_TEST_IP) || defined(HAVE_TEST_OP) - *out_len = op - out; - return LZO_E_EOF_NOT_FOUND; + *out_len = op - out; + return LZO_E_EOF_NOT_FOUND; #endif eof_found: - assert(t == 1); - *out_len = op - out; - return (ip == ip_end ? LZO_E_OK : - (ip < ip_end ? LZO_E_INPUT_NOT_CONSUMED : LZO_E_INPUT_OVERRUN)); + assert(t == 1); + *out_len = op - out; + return (ip == ip_end ? LZO_E_OK : + (ip < ip_end ? LZO_E_INPUT_NOT_CONSUMED : LZO_E_INPUT_OVERRUN)); #if defined(HAVE_NEED_IP) input_overrun: - *out_len = op - out; - return LZO_E_INPUT_OVERRUN; + *out_len = op - out; + return LZO_E_INPUT_OVERRUN; #endif #if defined(HAVE_NEED_OP) output_overrun: - *out_len = op - out; - return LZO_E_OUTPUT_OVERRUN; + *out_len = op - out; + return LZO_E_OUTPUT_OVERRUN; #endif #if defined(LZO_TEST_DECOMPRESS_OVERRUN_LOOKBEHIND) lookbehind_overrun: - *out_len = op - out; - return LZO_E_LOOKBEHIND_OVERRUN; + *out_len = op - out; + return LZO_E_LOOKBEHIND_OVERRUN; #endif } @@ -2249,7 +2249,7 @@ DO_DECOMPRESS ( const lzo_byte *in , lzo_uint in_len, # endif # if (LZO_TEST_DECOMPRESS_OVERRUN_INPUT >= 2) # define NEED_IP(x) \ - if ((lzo_uint)(ip_end - ip) < (lzo_uint)(x)) goto input_overrun + if ((lzo_uint)(ip_end - ip) < (lzo_uint)(x)) goto input_overrun # endif #endif @@ -2260,7 +2260,7 @@ DO_DECOMPRESS ( const lzo_byte *in , lzo_uint in_len, # if (LZO_TEST_DECOMPRESS_OVERRUN_OUTPUT >= 2) # undef TEST_OP # define NEED_OP(x) \ - if ((lzo_uint)(op_end - op) < (lzo_uint)(x)) goto output_overrun + if ((lzo_uint)(op_end - op) < (lzo_uint)(x)) goto output_overrun # endif #endif @@ -2316,394 +2316,394 @@ DO_DECOMPRESS ( const lzo_byte *in , lzo_uint in_len, #if defined(DO_DECOMPRESS) LZO_PUBLIC(int) DO_DECOMPRESS ( const lzo_byte *in , lzo_uint in_len, - lzo_byte *out, lzo_uintp out_len, - lzo_voidp wrkmem ) + lzo_byte *out, lzo_uintp out_len, + lzo_voidp wrkmem ) #endif { - register lzo_byte *op; - register const lzo_byte *ip; - register lzo_uint t; + register lzo_byte *op; + register const lzo_byte *ip; + register lzo_uint t; #if defined(COPY_DICT) - lzo_uint m_off; - const lzo_byte *dict_end; + lzo_uint m_off; + const lzo_byte *dict_end; #else - register const lzo_byte *m_pos; + register const lzo_byte *m_pos; #endif - const lzo_byte * const ip_end = in + in_len; + const lzo_byte * const ip_end = in + in_len; #if defined(HAVE_ANY_OP) - lzo_byte * const op_end = out + *out_len; + lzo_byte * const op_end = out + *out_len; #endif #if defined(LZO1Z) - lzo_uint last_m_off = 0; + lzo_uint last_m_off = 0; #endif - LZO_UNUSED(wrkmem); + LZO_UNUSED(wrkmem); #if defined(__LZO_QUERY_DECOMPRESS) - if (__LZO_IS_DECOMPRESS_QUERY(in,in_len,out,out_len,wrkmem)) - return __LZO_QUERY_DECOMPRESS(in,in_len,out,out_len,wrkmem,0,0); + if (__LZO_IS_DECOMPRESS_QUERY(in,in_len,out,out_len,wrkmem)) + return __LZO_QUERY_DECOMPRESS(in,in_len,out,out_len,wrkmem,0,0); #endif #if defined(COPY_DICT) - if (dict) - { - if (dict_len > M4_MAX_OFFSET) - { - dict += dict_len - M4_MAX_OFFSET; - dict_len = M4_MAX_OFFSET; - } - dict_end = dict + dict_len; - } - else - { - dict_len = 0; - dict_end = NULL; - } -#endif - - *out_len = 0; - - op = out; - ip = in; - - if (*ip > 17) - { - t = *ip++ - 17; - if (t < 4) - goto match_next; - assert(t > 0); NEED_OP(t); NEED_IP(t+1); - do *op++ = *ip++; while (--t > 0); - goto first_literal_run; - } - - while (TEST_IP && TEST_OP) - { - t = *ip++; - if (t >= 16) - goto match; - if (t == 0) - { - NEED_IP(1); - while (*ip == 0) - { - t += 255; - ip++; - NEED_IP(1); - } - t += 15 + *ip++; - } - assert(t > 0); NEED_OP(t+3); NEED_IP(t+4); + if (dict) + { + if (dict_len > M4_MAX_OFFSET) + { + dict += dict_len - M4_MAX_OFFSET; + dict_len = M4_MAX_OFFSET; + } + dict_end = dict + dict_len; + } + else + { + dict_len = 0; + dict_end = NULL; + } +#endif + + *out_len = 0; + + op = out; + ip = in; + + if (*ip > 17) + { + t = *ip++ - 17; + if (t < 4) + goto match_next; + assert(t > 0); NEED_OP(t); NEED_IP(t+1); + do *op++ = *ip++; while (--t > 0); + goto first_literal_run; + } + + while (TEST_IP && TEST_OP) + { + t = *ip++; + if (t >= 16) + goto match; + if (t == 0) + { + NEED_IP(1); + while (*ip == 0) + { + t += 255; + ip++; + NEED_IP(1); + } + t += 15 + *ip++; + } + assert(t > 0); NEED_OP(t+3); NEED_IP(t+4); #if defined(LZO_UNALIGNED_OK_4) || defined(LZO_ALIGNED_OK_4) #if !defined(LZO_UNALIGNED_OK_4) - if (PTR_ALIGNED2_4(op,ip)) - { -#endif - COPY4(op,ip); - op += 4; ip += 4; - if (--t > 0) - { - if (t >= 4) - { - do { - COPY4(op,ip); - op += 4; ip += 4; t -= 4; - } while (t >= 4); - if (t > 0) do *op++ = *ip++; while (--t > 0); - } - else - do *op++ = *ip++; while (--t > 0); - } + if (PTR_ALIGNED2_4(op,ip)) + { +#endif + COPY4(op,ip); + op += 4; ip += 4; + if (--t > 0) + { + if (t >= 4) + { + do { + COPY4(op,ip); + op += 4; ip += 4; t -= 4; + } while (t >= 4); + if (t > 0) do *op++ = *ip++; while (--t > 0); + } + else + do *op++ = *ip++; while (--t > 0); + } #if !defined(LZO_UNALIGNED_OK_4) - } - else + } + else #endif #endif #if !defined(LZO_UNALIGNED_OK_4) - { - *op++ = *ip++; *op++ = *ip++; *op++ = *ip++; - do *op++ = *ip++; while (--t > 0); - } + { + *op++ = *ip++; *op++ = *ip++; *op++ = *ip++; + do *op++ = *ip++; while (--t > 0); + } #endif first_literal_run: - t = *ip++; - if (t >= 16) - goto match; + t = *ip++; + if (t >= 16) + goto match; #if defined(COPY_DICT) #if defined(LZO1Z) - m_off = (1 + M2_MAX_OFFSET) + (t << 6) + (*ip++ >> 2); - last_m_off = m_off; + m_off = (1 + M2_MAX_OFFSET) + (t << 6) + (*ip++ >> 2); + last_m_off = m_off; #else - m_off = (1 + M2_MAX_OFFSET) + (t >> 2) + (*ip++ << 2); + m_off = (1 + M2_MAX_OFFSET) + (t >> 2) + (*ip++ << 2); #endif - NEED_OP(3); - t = 3; COPY_DICT(t,m_off) + NEED_OP(3); + t = 3; COPY_DICT(t,m_off) #else #if defined(LZO1Z) - t = (1 + M2_MAX_OFFSET) + (t << 6) + (*ip++ >> 2); - m_pos = op - t; - last_m_off = t; + t = (1 + M2_MAX_OFFSET) + (t << 6) + (*ip++ >> 2); + m_pos = op - t; + last_m_off = t; #else - m_pos = op - (1 + M2_MAX_OFFSET); - m_pos -= t >> 2; - m_pos -= *ip++ << 2; + m_pos = op - (1 + M2_MAX_OFFSET); + m_pos -= t >> 2; + m_pos -= *ip++ << 2; #endif - TEST_LOOKBEHIND(m_pos,out); NEED_OP(3); - *op++ = *m_pos++; *op++ = *m_pos++; *op++ = *m_pos; + TEST_LOOKBEHIND(m_pos,out); NEED_OP(3); + *op++ = *m_pos++; *op++ = *m_pos++; *op++ = *m_pos; #endif - goto match_done; + goto match_done; - while (TEST_IP && TEST_OP) - { + while (TEST_IP && TEST_OP) + { match: - if (t >= 64) - { + if (t >= 64) + { #if defined(COPY_DICT) #if defined(LZO1X) - m_off = 1 + ((t >> 2) & 7) + (*ip++ << 3); - t = (t >> 5) - 1; + m_off = 1 + ((t >> 2) & 7) + (*ip++ << 3); + t = (t >> 5) - 1; #elif defined(LZO1Y) - m_off = 1 + ((t >> 2) & 3) + (*ip++ << 2); - t = (t >> 4) - 3; + m_off = 1 + ((t >> 2) & 3) + (*ip++ << 2); + t = (t >> 4) - 3; #elif defined(LZO1Z) - m_off = t & 0x1f; - if (m_off >= 0x1c) - m_off = last_m_off; - else - { - m_off = 1 + (m_off << 6) + (*ip++ >> 2); - last_m_off = m_off; - } - t = (t >> 5) - 1; + m_off = t & 0x1f; + if (m_off >= 0x1c) + m_off = last_m_off; + else + { + m_off = 1 + (m_off << 6) + (*ip++ >> 2); + last_m_off = m_off; + } + t = (t >> 5) - 1; #endif #else #if defined(LZO1X) - m_pos = op - 1; - m_pos -= (t >> 2) & 7; - m_pos -= *ip++ << 3; - t = (t >> 5) - 1; + m_pos = op - 1; + m_pos -= (t >> 2) & 7; + m_pos -= *ip++ << 3; + t = (t >> 5) - 1; #elif defined(LZO1Y) - m_pos = op - 1; - m_pos -= (t >> 2) & 3; - m_pos -= *ip++ << 2; - t = (t >> 4) - 3; + m_pos = op - 1; + m_pos -= (t >> 2) & 3; + m_pos -= *ip++ << 2; + t = (t >> 4) - 3; #elif defined(LZO1Z) - { - lzo_uint off = t & 0x1f; - m_pos = op; - if (off >= 0x1c) - { - assert(last_m_off > 0); - m_pos -= last_m_off; - } - else - { - off = 1 + (off << 6) + (*ip++ >> 2); - m_pos -= off; - last_m_off = off; - } - } - t = (t >> 5) - 1; -#endif - TEST_LOOKBEHIND(m_pos,out); assert(t > 0); NEED_OP(t+3-1); - goto copy_match; -#endif - } - else if (t >= 32) - { - t &= 31; - if (t == 0) - { - NEED_IP(1); - while (*ip == 0) - { - t += 255; - ip++; - NEED_IP(1); - } - t += 31 + *ip++; - } + { + lzo_uint off = t & 0x1f; + m_pos = op; + if (off >= 0x1c) + { + assert(last_m_off > 0); + m_pos -= last_m_off; + } + else + { + off = 1 + (off << 6) + (*ip++ >> 2); + m_pos -= off; + last_m_off = off; + } + } + t = (t >> 5) - 1; +#endif + TEST_LOOKBEHIND(m_pos,out); assert(t > 0); NEED_OP(t+3-1); + goto copy_match; +#endif + } + else if (t >= 32) + { + t &= 31; + if (t == 0) + { + NEED_IP(1); + while (*ip == 0) + { + t += 255; + ip++; + NEED_IP(1); + } + t += 31 + *ip++; + } #if defined(COPY_DICT) #if defined(LZO1Z) - m_off = 1 + (ip[0] << 6) + (ip[1] >> 2); - last_m_off = m_off; + m_off = 1 + (ip[0] << 6) + (ip[1] >> 2); + last_m_off = m_off; #else - m_off = 1 + (ip[0] >> 2) + (ip[1] << 6); + m_off = 1 + (ip[0] >> 2) + (ip[1] << 6); #endif #else #if defined(LZO1Z) - { - lzo_uint off = 1 + (ip[0] << 6) + (ip[1] >> 2); - m_pos = op - off; - last_m_off = off; - } + { + lzo_uint off = 1 + (ip[0] << 6) + (ip[1] >> 2); + m_pos = op - off; + last_m_off = off; + } #elif defined(LZO_UNALIGNED_OK_2) && (LZO_BYTE_ORDER == LZO_LITTLE_ENDIAN) - m_pos = op - 1; - m_pos -= (* (const lzo_ushortp) ip) >> 2; + m_pos = op - 1; + m_pos -= (* (const lzo_ushortp) ip) >> 2; #else - m_pos = op - 1; - m_pos -= (ip[0] >> 2) + (ip[1] << 6); + m_pos = op - 1; + m_pos -= (ip[0] >> 2) + (ip[1] << 6); #endif #endif - ip += 2; - } - else if (t >= 16) - { + ip += 2; + } + else if (t >= 16) + { #if defined(COPY_DICT) - m_off = (t & 8) << 11; -#else - m_pos = op; - m_pos -= (t & 8) << 11; -#endif - t &= 7; - if (t == 0) - { - NEED_IP(1); - while (*ip == 0) - { - t += 255; - ip++; - NEED_IP(1); - } - t += 7 + *ip++; - } + m_off = (t & 8) << 11; +#else + m_pos = op; + m_pos -= (t & 8) << 11; +#endif + t &= 7; + if (t == 0) + { + NEED_IP(1); + while (*ip == 0) + { + t += 255; + ip++; + NEED_IP(1); + } + t += 7 + *ip++; + } #if defined(COPY_DICT) #if defined(LZO1Z) - m_off += (ip[0] << 6) + (ip[1] >> 2); + m_off += (ip[0] << 6) + (ip[1] >> 2); #else - m_off += (ip[0] >> 2) + (ip[1] << 6); + m_off += (ip[0] >> 2) + (ip[1] << 6); #endif - ip += 2; - if (m_off == 0) - goto eof_found; - m_off += 0x4000; + ip += 2; + if (m_off == 0) + goto eof_found; + m_off += 0x4000; #if defined(LZO1Z) - last_m_off = m_off; + last_m_off = m_off; #endif #else #if defined(LZO1Z) - m_pos -= (ip[0] << 6) + (ip[1] >> 2); + m_pos -= (ip[0] << 6) + (ip[1] >> 2); #elif defined(LZO_UNALIGNED_OK_2) && (LZO_BYTE_ORDER == LZO_LITTLE_ENDIAN) - m_pos -= (* (const lzo_ushortp) ip) >> 2; + m_pos -= (* (const lzo_ushortp) ip) >> 2; #else - m_pos -= (ip[0] >> 2) + (ip[1] << 6); + m_pos -= (ip[0] >> 2) + (ip[1] << 6); #endif - ip += 2; - if (m_pos == op) - goto eof_found; - m_pos -= 0x4000; + ip += 2; + if (m_pos == op) + goto eof_found; + m_pos -= 0x4000; #if defined(LZO1Z) - last_m_off = op - m_pos; + last_m_off = op - m_pos; #endif #endif - } - else - { + } + else + { #if defined(COPY_DICT) #if defined(LZO1Z) - m_off = 1 + (t << 6) + (*ip++ >> 2); - last_m_off = m_off; + m_off = 1 + (t << 6) + (*ip++ >> 2); + last_m_off = m_off; #else - m_off = 1 + (t >> 2) + (*ip++ << 2); + m_off = 1 + (t >> 2) + (*ip++ << 2); #endif - NEED_OP(2); - t = 2; COPY_DICT(t,m_off) + NEED_OP(2); + t = 2; COPY_DICT(t,m_off) #else #if defined(LZO1Z) - t = 1 + (t << 6) + (*ip++ >> 2); - m_pos = op - t; - last_m_off = t; + t = 1 + (t << 6) + (*ip++ >> 2); + m_pos = op - t; + last_m_off = t; #else - m_pos = op - 1; - m_pos -= t >> 2; - m_pos -= *ip++ << 2; + m_pos = op - 1; + m_pos -= t >> 2; + m_pos -= *ip++ << 2; #endif - TEST_LOOKBEHIND(m_pos,out); NEED_OP(2); - *op++ = *m_pos++; *op++ = *m_pos; + TEST_LOOKBEHIND(m_pos,out); NEED_OP(2); + *op++ = *m_pos++; *op++ = *m_pos; #endif - goto match_done; - } + goto match_done; + } #if defined(COPY_DICT) - NEED_OP(t+3-1); - t += 3-1; COPY_DICT(t,m_off) + NEED_OP(t+3-1); + t += 3-1; COPY_DICT(t,m_off) #else - TEST_LOOKBEHIND(m_pos,out); assert(t > 0); NEED_OP(t+3-1); + TEST_LOOKBEHIND(m_pos,out); assert(t > 0); NEED_OP(t+3-1); #if defined(LZO_UNALIGNED_OK_4) || defined(LZO_ALIGNED_OK_4) #if !defined(LZO_UNALIGNED_OK_4) - if (t >= 2 * 4 - (3 - 1) && PTR_ALIGNED2_4(op,m_pos)) - { - assert((op - m_pos) >= 4); -#else - if (t >= 2 * 4 - (3 - 1) && (op - m_pos) >= 4) - { -#endif - COPY4(op,m_pos); - op += 4; m_pos += 4; t -= 4 - (3 - 1); - do { - COPY4(op,m_pos); - op += 4; m_pos += 4; t -= 4; - } while (t >= 4); - if (t > 0) do *op++ = *m_pos++; while (--t > 0); - } - else -#endif - { + if (t >= 2 * 4 - (3 - 1) && PTR_ALIGNED2_4(op,m_pos)) + { + assert((op - m_pos) >= 4); +#else + if (t >= 2 * 4 - (3 - 1) && (op - m_pos) >= 4) + { +#endif + COPY4(op,m_pos); + op += 4; m_pos += 4; t -= 4 - (3 - 1); + do { + COPY4(op,m_pos); + op += 4; m_pos += 4; t -= 4; + } while (t >= 4); + if (t > 0) do *op++ = *m_pos++; while (--t > 0); + } + else +#endif + { copy_match: - *op++ = *m_pos++; *op++ = *m_pos++; - do *op++ = *m_pos++; while (--t > 0); - } + *op++ = *m_pos++; *op++ = *m_pos++; + do *op++ = *m_pos++; while (--t > 0); + } #endif match_done: #if defined(LZO1Z) - t = ip[-1] & 3; + t = ip[-1] & 3; #else - t = ip[-2] & 3; + t = ip[-2] & 3; #endif - if (t == 0) - break; + if (t == 0) + break; match_next: - assert(t > 0); NEED_OP(t); NEED_IP(t+1); - do *op++ = *ip++; while (--t > 0); - t = *ip++; - } - } + assert(t > 0); NEED_OP(t); NEED_IP(t+1); + do *op++ = *ip++; while (--t > 0); + t = *ip++; + } + } #if defined(HAVE_TEST_IP) || defined(HAVE_TEST_OP) - *out_len = op - out; - return LZO_E_EOF_NOT_FOUND; + *out_len = op - out; + return LZO_E_EOF_NOT_FOUND; #endif eof_found: - assert(t == 1); - *out_len = op - out; - return (ip == ip_end ? LZO_E_OK : - (ip < ip_end ? LZO_E_INPUT_NOT_CONSUMED : LZO_E_INPUT_OVERRUN)); + assert(t == 1); + *out_len = op - out; + return (ip == ip_end ? LZO_E_OK : + (ip < ip_end ? LZO_E_INPUT_NOT_CONSUMED : LZO_E_INPUT_OVERRUN)); #if defined(HAVE_NEED_IP) input_overrun: - *out_len = op - out; - return LZO_E_INPUT_OVERRUN; + *out_len = op - out; + return LZO_E_INPUT_OVERRUN; #endif #if defined(HAVE_NEED_OP) output_overrun: - *out_len = op - out; - return LZO_E_OUTPUT_OVERRUN; + *out_len = op - out; + return LZO_E_OUTPUT_OVERRUN; #endif #if defined(LZO_TEST_DECOMPRESS_OVERRUN_LOOKBEHIND) lookbehind_overrun: - *out_len = op - out; - return LZO_E_LOOKBEHIND_OVERRUN; + *out_len = op - out; + return LZO_E_LOOKBEHIND_OVERRUN; #endif } diff --git a/src/xrCore/stream_reader.cpp b/src/xrCore/stream_reader.cpp index cc496c016b9..35d594fd5ae 100644 --- a/src/xrCore/stream_reader.cpp +++ b/src/xrCore/stream_reader.cpp @@ -1,165 +1,171 @@ #include "stdafx.h" #include "stream_reader.h" -void CStreamReader::construct ( - const HANDLE &file_mapping_handle, - const u32 &start_offset, - const u32 &file_size, - const u32 &archive_size, - const u32 &window_size - ) +void CStreamReader::construct( + const HANDLE& file_mapping_handle, + const u32& start_offset, + const u32& file_size, + const u32& archive_size, + const u32& window_size +) { - m_file_mapping_handle = file_mapping_handle; - m_start_offset = start_offset; - m_file_size = file_size; - m_archive_size = archive_size; - m_window_size = _max(window_size,FS.dwAllocGranularity); + m_file_mapping_handle = file_mapping_handle; + m_start_offset = start_offset; + m_file_size = file_size; + m_archive_size = archive_size; + m_window_size = _max(window_size, FS.dwAllocGranularity); - map (0); + map(0); } -void CStreamReader::destroy () +void CStreamReader::destroy() { - unmap (); + unmap(); } -void CStreamReader::map (const u32 &new_offset) +void CStreamReader::map(const u32& new_offset) { - VERIFY (new_offset <= m_file_size); - m_current_offset_from_start = new_offset; - - u32 granularity = FS.dwAllocGranularity; - u32 start_offset = m_start_offset + new_offset; - u32 pure_start_offset = start_offset; - start_offset = (start_offset/granularity)*granularity; - - VERIFY (pure_start_offset >= start_offset); - u32 pure_end_offset = m_window_size + pure_start_offset; - u32 end_offset = pure_end_offset/granularity; - if (pure_end_offset%granularity) - ++end_offset; - - end_offset *= granularity; - if (end_offset > m_archive_size) - end_offset = m_archive_size; - - m_current_window_size = end_offset - start_offset; - m_current_map_view_of_file = (u8*) - MapViewOfFile( - m_file_mapping_handle, - FILE_MAP_READ, - 0, - start_offset, - m_current_window_size - ); - m_current_pointer = m_current_map_view_of_file; - - u32 difference = pure_start_offset - start_offset; - m_current_window_size -= difference; - m_current_pointer += difference; - m_start_pointer = m_current_pointer; + VERIFY(new_offset <= m_file_size); + m_current_offset_from_start = new_offset; + + u32 granularity = FS.dwAllocGranularity; + u32 start_offset = m_start_offset + new_offset; + u32 pure_start_offset = start_offset; + start_offset = (start_offset / granularity)*granularity; + + VERIFY(pure_start_offset >= start_offset); + u32 pure_end_offset = m_window_size + pure_start_offset; + u32 end_offset = pure_end_offset / granularity; + if (pure_end_offset%granularity) + ++end_offset; + + end_offset *= granularity; + if (end_offset > m_archive_size) + end_offset = m_archive_size; + + m_current_window_size = end_offset - start_offset; + m_current_map_view_of_file = (u8*) + MapViewOfFile( + m_file_mapping_handle, + FILE_MAP_READ, + 0, + start_offset, + m_current_window_size + ); + m_current_pointer = m_current_map_view_of_file; + + u32 difference = pure_start_offset - start_offset; + m_current_window_size -= difference; + m_current_pointer += difference; + m_start_pointer = m_current_pointer; } -void CStreamReader::advance (const int &offset) +void CStreamReader::advance(const int& offset) { - VERIFY (m_current_pointer >= m_start_pointer); - VERIFY (u32(m_current_pointer - m_start_pointer) <= m_current_window_size); - int offset_inside_window = int(m_current_pointer - m_start_pointer); - if (offset_inside_window + offset >= (int)m_current_window_size) { - remap (m_current_offset_from_start + offset_inside_window + offset); - return; - } - - if (offset_inside_window + offset < 0) { - remap (m_current_offset_from_start + offset_inside_window + offset); - return; - } - - m_current_pointer += offset; + VERIFY(m_current_pointer >= m_start_pointer); + VERIFY(u32(m_current_pointer - m_start_pointer) <= m_current_window_size); + int offset_inside_window = int(m_current_pointer - m_start_pointer); + if (offset_inside_window + offset >= (int)m_current_window_size) + { + remap(m_current_offset_from_start + offset_inside_window + offset); + return; + } + + if (offset_inside_window + offset < 0) + { + remap(m_current_offset_from_start + offset_inside_window + offset); + return; + } + + m_current_pointer += offset; } -void CStreamReader::r (void *_buffer, u32 buffer_size) +void CStreamReader::r(void* _buffer, u32 buffer_size) { - VERIFY (m_current_pointer >= m_start_pointer); - VERIFY (u32(m_current_pointer - m_start_pointer) <= m_current_window_size); - - int offset_inside_window = int(m_current_pointer - m_start_pointer); - if (offset_inside_window + buffer_size < m_current_window_size) { - Memory.mem_copy (_buffer,m_current_pointer,buffer_size); - m_current_pointer += buffer_size; - return; - } - - u8 *buffer = (u8*)_buffer; - u32 elapsed_in_window = m_current_window_size - (m_current_pointer - m_start_pointer); - - do { - Memory.mem_copy (buffer,m_current_pointer,elapsed_in_window); - buffer += elapsed_in_window; - buffer_size -= elapsed_in_window; - advance (elapsed_in_window); - - elapsed_in_window = m_current_window_size; - } - while (m_current_window_size < buffer_size); - - Memory.mem_copy (buffer,m_current_pointer,buffer_size); - advance (buffer_size); + VERIFY(m_current_pointer >= m_start_pointer); + VERIFY(u32(m_current_pointer - m_start_pointer) <= m_current_window_size); + + int offset_inside_window = int(m_current_pointer - m_start_pointer); + if (offset_inside_window + buffer_size < m_current_window_size) + { + Memory.mem_copy(_buffer, m_current_pointer, buffer_size); + m_current_pointer += buffer_size; + return; + } + + u8* buffer = (u8*)_buffer; + u32 elapsed_in_window = m_current_window_size - (m_current_pointer - m_start_pointer); + + do + { + Memory.mem_copy(buffer, m_current_pointer, elapsed_in_window); + buffer += elapsed_in_window; + buffer_size -= elapsed_in_window; + advance(elapsed_in_window); + + elapsed_in_window = m_current_window_size; + } + while (m_current_window_size < buffer_size); + + Memory.mem_copy(buffer, m_current_pointer, buffer_size); + advance(buffer_size); } -CStreamReader *CStreamReader::open_chunk (const u32 &chunk_id) +CStreamReader* CStreamReader::open_chunk(const u32& chunk_id) { - BOOL compressed; - u32 size = find_chunk(chunk_id,&compressed); - if (!size) - return (0); - - R_ASSERT2 (!compressed,"cannot use CStreamReader on compressed chunks"); - CStreamReader *result = xr_new(); - result->construct (file_mapping_handle(),m_start_offset + tell(),size,m_archive_size,m_window_size); - return (result); + BOOL compressed; + u32 size = find_chunk(chunk_id, &compressed); + if (!size) + return (0); + + R_ASSERT2(!compressed, "cannot use CStreamReader on compressed chunks"); + CStreamReader* result = xr_new(); + result->construct(file_mapping_handle(), m_start_offset + tell(), size, m_archive_size, m_window_size); + return (result); } #include "FS_impl.h" -u32 CStreamReader::find_chunk (u32 ID, BOOL* bCompressed) +u32 CStreamReader::find_chunk(u32 ID, BOOL* bCompressed) { - return inherited::find_chunk(ID, bCompressed); + return inherited::find_chunk(ID, bCompressed); } -void CStreamReader::r_stringZ (shared_str& dest) +void CStreamReader::r_stringZ(shared_str& dest) { - char* dest_str = NULL; - u32 current_str_size = 0; - u8* end_str = NULL; - do - { - u8* end_ptr = m_start_pointer + m_current_window_size; - end_str = m_current_pointer; - while (end_str < end_ptr) - { - if ((*end_str == 0) && (!dest_str)) - { - dest = reinterpret_cast(m_current_pointer); - m_current_pointer = ++end_str; - return; - } else if (*end_str == 0) - { - ++end_str; //copying with ending zero - break; - } - ++end_str; - } - if (!dest_str) //first iteration - dest_str = static_cast(_alloca(4096)); - - u32 current_chunk_size = static_cast(end_ptr - m_current_pointer); - R_ASSERT(current_str_size + current_chunk_size <= 4096); - - CopyMemory(dest_str, m_current_pointer, current_chunk_size); - current_str_size += current_chunk_size; - remap(m_current_offset_from_start + current_chunk_size); - VERIFY(m_current_pointer == m_start_pointer); - } while (*(end_str - 1) == 0); - dest = dest_str; - m_current_pointer = end_str; + char* dest_str = NULL; + u32 current_str_size = 0; + u8* end_str = NULL; + do + { + u8* end_ptr = m_start_pointer + m_current_window_size; + end_str = m_current_pointer; + while (end_str < end_ptr) + { + if ((*end_str == 0) && (!dest_str)) + { + dest = reinterpret_cast(m_current_pointer); + m_current_pointer = ++end_str; + return; + } + else if (*end_str == 0) + { + ++end_str; //copying with ending zero + break; + } + ++end_str; + } + if (!dest_str) //first iteration + dest_str = static_cast(_alloca(4096)); + + u32 current_chunk_size = static_cast(end_ptr - m_current_pointer); + R_ASSERT(current_str_size + current_chunk_size <= 4096); + + CopyMemory(dest_str, m_current_pointer, current_chunk_size); + current_str_size += current_chunk_size; + remap(m_current_offset_from_start + current_chunk_size); + VERIFY(m_current_pointer == m_start_pointer); + } + while (*(end_str - 1) == 0); + dest = dest_str; + m_current_pointer = end_str; } \ No newline at end of file diff --git a/src/xrCore/stream_reader.h b/src/xrCore/stream_reader.h index 586b1a9e906..1f17946d64b 100644 --- a/src/xrCore/stream_reader.h +++ b/src/xrCore/stream_reader.h @@ -1,68 +1,69 @@ #ifndef STREAM_READER_H #define STREAM_READER_H -class XRCORE_API CStreamReader : public IReaderBase { +class XRCORE_API CStreamReader : public IReaderBase < CStreamReader > +{ private: - HANDLE m_file_mapping_handle; - u32 m_start_offset; - u32 m_file_size; - u32 m_archive_size; - u32 m_window_size; + HANDLE m_file_mapping_handle; + u32 m_start_offset; + u32 m_file_size; + u32 m_archive_size; + u32 m_window_size; private: - u32 m_current_offset_from_start; - u32 m_current_window_size; - u8 *m_current_map_view_of_file; - u8 *m_start_pointer; - u8 *m_current_pointer; + u32 m_current_offset_from_start; + u32 m_current_window_size; + u8* m_current_map_view_of_file; + u8* m_start_pointer; + u8* m_current_pointer; private: - void map (const u32 &new_offset); - IC void unmap (); - IC void remap (const u32 &new_offset); + void map(const u32& new_offset); + IC void unmap(); + IC void remap(const u32& new_offset); private: - // should not be called - IC CStreamReader (const CStreamReader &object); - IC CStreamReader &operator= (const CStreamReader &); + // should not be called + IC CStreamReader(const CStreamReader& object); + IC CStreamReader& operator= (const CStreamReader&); public: - IC CStreamReader (); + IC CStreamReader(); public: - virtual void construct ( - const HANDLE &file_mapping_handle, - const u32 &start_offset, - const u32 &file_size, - const u32 &archive_size, - const u32 &window_size - ); - virtual void destroy (); + virtual void construct( + const HANDLE& file_mapping_handle, + const u32& start_offset, + const u32& file_size, + const u32& archive_size, + const u32& window_size + ); + virtual void destroy(); public: - IC const HANDLE &file_mapping_handle() const; - IC u32 elapsed () const; - IC const u32 &length () const; - IC void seek (const int &offset); - IC u32 tell () const; - IC void close (); + IC const HANDLE& file_mapping_handle() const; + IC u32 elapsed() const; + IC const u32& length() const; + IC void seek(const int& offset); + IC u32 tell() const; + IC void close(); public: - void advance (const int &offset); - void r (void *buffer, u32 buffer_size); - CStreamReader *open_chunk (const u32 &chunk_id); - u32 find_chunk (u32 ID, BOOL* bCompressed = 0); -//. CStreamReader*open_chunk_iterator(const u32 &chunk_id, CStreamReader *previous = 0); // 0 means first + void advance(const int& offset); + void r(void* buffer, u32 buffer_size); + CStreamReader* open_chunk(const u32& chunk_id); + u32 find_chunk(u32 ID, BOOL* bCompressed = 0); + //. CStreamReader*open_chunk_iterator(const u32 &chunk_id, CStreamReader *previous = 0); // 0 means first public: -//. void r_string (char *dest, u32 tgt_sz); -//. void r_string (xr_string& dest); -//. void skip_stringZ (); -//. void r_stringZ (char *dest, u32 tgt_sz); - void r_stringZ (shared_str& dest); -//. void r_stringZ (xr_string& dest); + //. void r_string (char *dest, u32 tgt_sz); + //. void r_string (xr_string& dest); + //. void skip_stringZ (); + //. void r_stringZ (char *dest, u32 tgt_sz); + void r_stringZ(shared_str& dest); + //. void r_stringZ (xr_string& dest); private: - typedef IReaderBase inherited; + typedef IReaderBase inherited; }; #include "stream_reader_inline.h" diff --git a/src/xrCore/stream_reader_inline.h b/src/xrCore/stream_reader_inline.h index 758218bf1e8..a6edf3e7b12 100644 --- a/src/xrCore/stream_reader_inline.h +++ b/src/xrCore/stream_reader_inline.h @@ -1,70 +1,70 @@ #ifndef STREAM_READER_INLINE_H #define STREAM_READER_INLINE_H -IC CStreamReader::CStreamReader () +IC CStreamReader::CStreamReader() { } -IC CStreamReader::CStreamReader (const CStreamReader &object) : - m_start_offset (object.m_start_offset), - m_file_size (object.m_file_size), - m_archive_size (object.m_archive_size), - m_window_size (object.m_window_size) +IC CStreamReader::CStreamReader(const CStreamReader& object) : + m_start_offset(object.m_start_offset), + m_file_size(object.m_file_size), + m_archive_size(object.m_archive_size), + m_window_size(object.m_window_size) { - // should be never called + // should be never called } -IC CStreamReader &CStreamReader::operator= (const CStreamReader &) +IC CStreamReader& CStreamReader::operator= (const CStreamReader&) { - // should be never called - return (*this); + // should be never called + return (*this); } -IC const HANDLE &CStreamReader::file_mapping_handle () const +IC const HANDLE& CStreamReader::file_mapping_handle() const { - return (m_file_mapping_handle); + return (m_file_mapping_handle); } -IC void CStreamReader::unmap () +IC void CStreamReader::unmap() { - UnmapViewOfFile (m_current_map_view_of_file); + UnmapViewOfFile(m_current_map_view_of_file); } -IC void CStreamReader::remap (const u32 &new_offset) +IC void CStreamReader::remap(const u32& new_offset) { - unmap (); - map (new_offset); + unmap(); + map(new_offset); } -IC u32 CStreamReader::elapsed () const +IC u32 CStreamReader::elapsed() const { - u32 offset_from_file_start = tell(); - VERIFY (m_file_size >= offset_from_file_start); - return (m_file_size - offset_from_file_start); + u32 offset_from_file_start = tell(); + VERIFY(m_file_size >= offset_from_file_start); + return (m_file_size - offset_from_file_start); } -IC const u32 &CStreamReader::length () const +IC const u32& CStreamReader::length() const { - return (m_file_size); + return (m_file_size); } -IC void CStreamReader::seek (const int &offset) +IC void CStreamReader::seek(const int& offset) { - advance (offset - tell()); + advance(offset - tell()); } -IC u32 CStreamReader::tell () const +IC u32 CStreamReader::tell() const { - VERIFY (m_current_pointer >= m_start_pointer); - VERIFY (u32(m_current_pointer - m_start_pointer) <= m_current_window_size); - return (m_current_offset_from_start + (m_current_pointer - m_start_pointer)); + VERIFY(m_current_pointer >= m_start_pointer); + VERIFY(u32(m_current_pointer - m_start_pointer) <= m_current_window_size); + return (m_current_offset_from_start + (m_current_pointer - m_start_pointer)); } -IC void CStreamReader::close () +IC void CStreamReader::close() { - destroy (); - CStreamReader *self = this; - xr_delete (self); + destroy(); + CStreamReader* self = this; + xr_delete(self); } #endif // STREAM_READER_INLINE_H \ No newline at end of file diff --git a/src/xrCore/string_concatenations.cpp b/src/xrCore/string_concatenations.cpp index 07b1dbea4d7..9f03625862c 100644 --- a/src/xrCore/string_concatenations.cpp +++ b/src/xrCore/string_concatenations.cpp @@ -1,314 +1,319 @@ #include "stdafx.h" #include "string_concatenations.h" -namespace xray { - -namespace core { - -namespace detail { - -namespace strconcat_error { - -void process (u32 const index, u32 const count, LPCSTR *strings) +namespace xray { - u32 const max_string_size = 1024; - LPSTR temp = (LPSTR)_alloca((count*(max_string_size + 4) + 1)*sizeof(**strings)); - LPSTR k = temp; - *k++ = '['; - for (u32 i = 0; i= count) - continue; - - *k++ = '['; - *k++ = '\r'; - *k++ = '\n'; - } - *k = 0; - - Debug.fatal ( - DEBUG_INFO, - make_string( - "buffer overflow: cannot concatenate strings(%d):\r\n%s", - index, - temp - ).c_str() - ); + +namespace core +{ + +namespace detail +{ + +namespace strconcat_error +{ + +void process(u32 const index, u32 const count, LPCSTR* strings) +{ + u32 const max_string_size = 1024; + LPSTR temp = (LPSTR)_alloca((count*(max_string_size + 4) + 1)*sizeof(**strings)); + LPSTR k = temp; + *k++ = '['; + for (u32 i = 0; i < count; ++i) + { + for (LPCSTR j = strings[i], e = j + max_string_size; *j && j < e; ++k, ++j) + *k = *j; + + *k++ = ']'; + + if (i + 1 >= count) + continue; + + *k++ = '['; + *k++ = '\r'; + *k++ = '\n'; + } + *k = 0; + + Debug.fatal( + DEBUG_INFO, + make_string( + "buffer overflow: cannot concatenate strings(%d):\r\n%s", + index, + temp + ).c_str() + ); } template -static inline void process (LPSTR& i, LPCSTR e, u32 const index, LPCSTR (&strings)[count]) +static inline void process(LPSTR& i, LPCSTR e, u32 const index, LPCSTR(&strings)[count]) { - VERIFY (i <= e); - VERIFY (index < count); + VERIFY(i <= e); + VERIFY(index < count); - if (i != e) - return; + if (i != e) + return; #ifndef MASTER_GOLD - process (index, count, strings); + process(index, count, strings); #else // #ifndef MASTER_GOLD - --i; + --i; #endif // #ifndef MASTER_GOLD } -} // namespace strconcat_error +} // namespace strconcat_error -int stack_overflow_exception_filter (int exception_code) +int stack_overflow_exception_filter(int exception_code) { - if (exception_code == EXCEPTION_STACK_OVERFLOW) - { - // Do not call _resetstkoflw here, because - // at this point, the stack is not yet unwound. - // Instead, signal that the handler (the __except block) - // is to be executed. - return EXCEPTION_EXECUTE_HANDLER; - } - else - return EXCEPTION_CONTINUE_SEARCH; + if (exception_code == EXCEPTION_STACK_OVERFLOW) + { + // Do not call _resetstkoflw here, because + // at this point, the stack is not yet unwound. + // Instead, signal that the handler (the __except block) + // is to be executed. + return EXCEPTION_EXECUTE_HANDLER; + } + else + return EXCEPTION_CONTINUE_SEARCH; } -void check_stack_overflow (u32 stack_increment) +void check_stack_overflow(u32 stack_increment) { - __try - { - void* p = _alloca(stack_increment); - p; - } - __except ( xray::core::detail::stack_overflow_exception_filter(GetExceptionCode()) ) - { - _resetstkoflw(); - } + __try + { + void* p = _alloca(stack_increment); + p; + } + __except (xray::core::detail::stack_overflow_exception_filter(GetExceptionCode())) + { + _resetstkoflw(); + } } -void string_tupples::error_process () const +void string_tupples::error_process() const { - LPCSTR strings[6]; - - u32 part_size = 0; - u32 overrun_string_index = (u32)-1; - for ( u32 i=0; i max_concat_result_size ) - { - overrun_string_index = i; - } - } - } - VERIFY(overrun_string_index != -1); - - strconcat_error::process(overrun_string_index, m_count, strings); + LPCSTR strings[6]; + + u32 part_size = 0; + u32 overrun_string_index = (u32)-1; + for (u32 i = 0; i < m_count; ++i) + { + strings[i] = m_strings[i].first; + + if (overrun_string_index == (u32)-1) + { + part_size += m_strings[i].second; + if (part_size > max_concat_result_size) + { + overrun_string_index = i; + } + } + } + VERIFY(overrun_string_index != -1); + + strconcat_error::process(overrun_string_index, m_count, strings); } } // namespace detail } // namespace core - + } // namespace xray using namespace xray::core::detail; // dest = S1+S2 -LPSTR strconcat ( int dest_sz, char* dest, const char* S1, const char* S2) +LPSTR strconcat(int dest_sz, char* dest, const char* S1, const char* S2) { - VERIFY (dest); - VERIFY (S1); - VERIFY (S2); + VERIFY(dest); + VERIFY(S1); + VERIFY(S2); - LPCSTR strings[]= { S1, S2 }; + LPCSTR strings[] = {S1, S2}; - LPSTR i = dest; - LPCSTR e = dest + dest_sz; - LPCSTR j; - for (j = S1; *j && i < e; ++i, ++j) - *i = *j; + LPSTR i = dest; + LPCSTR e = dest + dest_sz; + LPCSTR j; + for (j = S1; *j && i < e; ++i, ++j) + *i = *j; - strconcat_error::process ( i, e, 0, strings ); + strconcat_error::process(i, e, 0, strings); - for (j = S2; *j && i < e; ++i, ++j) - *i = *j; + for (j = S2; *j && i < e; ++i, ++j) + *i = *j; - strconcat_error::process ( i, e, 1, strings ); + strconcat_error::process(i, e, 1, strings); - *i = 0; + *i = 0; - return (dest); + return (dest); } // dest = S1+S2+S3 -LPSTR strconcat ( int dest_sz, char* dest, const char* S1, const char* S2, const char* S3) +LPSTR strconcat(int dest_sz, char* dest, const char* S1, const char* S2, const char* S3) { - VERIFY (dest); - VERIFY (S1); - VERIFY (S2); - VERIFY (S3); + VERIFY(dest); + VERIFY(S1); + VERIFY(S2); + VERIFY(S3); - LPCSTR strings[]= { S1, S2, S3 }; + LPCSTR strings[] = {S1, S2, S3}; - LPSTR i = dest; - LPCSTR e = dest + dest_sz; - LPCSTR j; - for (j = S1; *j && i < e; ++i, ++j) - *i = *j; + LPSTR i = dest; + LPCSTR e = dest + dest_sz; + LPCSTR j; + for (j = S1; *j && i < e; ++i, ++j) + *i = *j; - strconcat_error::process ( i, e, 0, strings ); + strconcat_error::process(i, e, 0, strings); - for (j = S2; *j && i < e; ++i, ++j) - *i = *j; + for (j = S2; *j && i < e; ++i, ++j) + *i = *j; - strconcat_error::process ( i, e, 1, strings ); + strconcat_error::process(i, e, 1, strings); - for (j = S3; *j && i < e; ++i, ++j) - *i = *j; + for (j = S3; *j && i < e; ++i, ++j) + *i = *j; - strconcat_error::process ( i, e, 2, strings ); + strconcat_error::process(i, e, 2, strings); - *i = 0; + *i = 0; - return (dest); + return (dest); } // dest = S1+S2+S3+S4 -LPSTR strconcat ( int dest_sz, char* dest, const char* S1, const char* S2, const char* S3, const char* S4) +LPSTR strconcat(int dest_sz, char* dest, const char* S1, const char* S2, const char* S3, const char* S4) { - VERIFY (dest); - VERIFY (S1); - VERIFY (S2); - VERIFY (S3); - VERIFY (S4); + VERIFY(dest); + VERIFY(S1); + VERIFY(S2); + VERIFY(S3); + VERIFY(S4); - LPCSTR strings[]= { S1, S2, S3, S4 }; + LPCSTR strings[] = {S1, S2, S3, S4}; - LPSTR i = dest; - LPCSTR e = dest + dest_sz; - LPCSTR j; - for (j = S1; *j && i < e; ++i, ++j) - *i = *j; + LPSTR i = dest; + LPCSTR e = dest + dest_sz; + LPCSTR j; + for (j = S1; *j && i < e; ++i, ++j) + *i = *j; - strconcat_error::process ( i, e, 0, strings ); + strconcat_error::process(i, e, 0, strings); - for (j = S2; *j && i < e; ++i, ++j) - *i = *j; + for (j = S2; *j && i < e; ++i, ++j) + *i = *j; - strconcat_error::process ( i, e, 1, strings ); + strconcat_error::process(i, e, 1, strings); - for (j = S3; *j && i < e; ++i, ++j) - *i = *j; + for (j = S3; *j && i < e; ++i, ++j) + *i = *j; - strconcat_error::process ( i, e, 2, strings ); + strconcat_error::process(i, e, 2, strings); - for (j = S4; *j && i < e; ++i, ++j) - *i = *j; + for (j = S4; *j && i < e; ++i, ++j) + *i = *j; - strconcat_error::process ( i, e, 3, strings ); + strconcat_error::process(i, e, 3, strings); - *i = 0; + *i = 0; - return (dest); + return (dest); } // dest = S1+S2+S3+S4+S5 -LPSTR strconcat ( int dest_sz, char* dest, const char* S1, const char* S2, const char* S3, const char* S4, const char* S5) +LPSTR strconcat(int dest_sz, char* dest, const char* S1, const char* S2, const char* S3, const char* S4, const char* S5) { - VERIFY (dest); - VERIFY (S1); - VERIFY (S2); - VERIFY (S3); - VERIFY (S4); - VERIFY (S5); + VERIFY(dest); + VERIFY(S1); + VERIFY(S2); + VERIFY(S3); + VERIFY(S4); + VERIFY(S5); - LPCSTR strings[]= { S1, S2, S3, S4, S5 }; + LPCSTR strings[] = {S1, S2, S3, S4, S5}; - LPSTR i = dest; - LPCSTR e = dest + dest_sz; - LPCSTR j; - for (j = S1; *j && i < e; ++i, ++j) - *i = *j; + LPSTR i = dest; + LPCSTR e = dest + dest_sz; + LPCSTR j; + for (j = S1; *j && i < e; ++i, ++j) + *i = *j; - strconcat_error::process ( i, e, 0, strings ); + strconcat_error::process(i, e, 0, strings); - for (j = S2; *j && i < e; ++i, ++j) - *i = *j; + for (j = S2; *j && i < e; ++i, ++j) + *i = *j; - strconcat_error::process ( i, e, 1, strings ); + strconcat_error::process(i, e, 1, strings); - for (j = S3; *j && i < e; ++i, ++j) - *i = *j; + for (j = S3; *j && i < e; ++i, ++j) + *i = *j; - strconcat_error::process ( i, e, 2, strings ); + strconcat_error::process(i, e, 2, strings); - for (j = S4; *j && i < e; ++i, ++j) - *i = *j; + for (j = S4; *j && i < e; ++i, ++j) + *i = *j; - strconcat_error::process ( i, e, 3, strings ); + strconcat_error::process(i, e, 3, strings); - for (j = S5; *j && i < e; ++i, ++j) - *i = *j; + for (j = S5; *j && i < e; ++i, ++j) + *i = *j; - strconcat_error::process ( i, e, 4, strings ); + strconcat_error::process(i, e, 4, strings); - *i = 0; + *i = 0; - return (dest); + return (dest); } // dest = S1+S2+S3+S4+S5+S6 -LPSTR strconcat ( int dest_sz, char* dest, const char* S1, const char* S2, const char* S3, const char* S4, const char* S5, const char* S6) +LPSTR strconcat(int dest_sz, char* dest, const char* S1, const char* S2, const char* S3, const char* S4, const char* S5, const char* S6) { - VERIFY (dest); - VERIFY (S1); - VERIFY (S2); - VERIFY (S3); - VERIFY (S4); - VERIFY (S5); - VERIFY (S6); + VERIFY(dest); + VERIFY(S1); + VERIFY(S2); + VERIFY(S3); + VERIFY(S4); + VERIFY(S5); + VERIFY(S6); - LPCSTR strings[]= { S1, S2, S3, S4, S5, S6 }; + LPCSTR strings[] = {S1, S2, S3, S4, S5, S6}; - LPSTR i = dest; - LPCSTR e = dest + dest_sz; - LPCSTR j; - for (j = S1; *j && i < e; ++i, ++j) - *i = *j; + LPSTR i = dest; + LPCSTR e = dest + dest_sz; + LPCSTR j; + for (j = S1; *j && i < e; ++i, ++j) + *i = *j; - strconcat_error::process ( i, e, 0, strings ); + strconcat_error::process(i, e, 0, strings); - for (j = S2; *j && i < e; ++i, ++j) - *i = *j; + for (j = S2; *j && i < e; ++i, ++j) + *i = *j; - strconcat_error::process ( i, e, 1, strings ); + strconcat_error::process(i, e, 1, strings); - for (j = S3; *j && i < e; ++i, ++j) - *i = *j; + for (j = S3; *j && i < e; ++i, ++j) + *i = *j; - strconcat_error::process ( i, e, 2, strings ); + strconcat_error::process(i, e, 2, strings); - for (j = S4; *j && i < e; ++i, ++j) - *i = *j; + for (j = S4; *j && i < e; ++i, ++j) + *i = *j; - strconcat_error::process ( i, e, 3, strings ); + strconcat_error::process(i, e, 3, strings); - for (j = S5; *j && i < e; ++i, ++j) - *i = *j; + for (j = S5; *j && i < e; ++i, ++j) + *i = *j; - strconcat_error::process ( i, e, 4, strings ); + strconcat_error::process(i, e, 4, strings); - for (j = S6; *j && i < e; ++i, ++j) - *i = *j; + for (j = S6; *j && i < e; ++i, ++j) + *i = *j; - strconcat_error::process ( i, e, 5, strings ); + strconcat_error::process(i, e, 5, strings); - *i = 0; + *i = 0; - return (dest); + return (dest); } diff --git a/src/xrCore/string_concatenations.h b/src/xrCore/string_concatenations.h index 4ff95d7fe2a..12839e06752 100644 --- a/src/xrCore/string_concatenations.h +++ b/src/xrCore/string_concatenations.h @@ -3,41 +3,41 @@ #ifndef _EDITOR -LPSTR XRCORE_API strconcat ( int dest_sz, char* dest, const char* S1, const char* S2); -LPSTR XRCORE_API strconcat ( int dest_sz, char* dest, const char* S1, const char* S2, const char* S3); -LPSTR XRCORE_API strconcat ( int dest_sz, char* dest, const char* S1, const char* S2, const char* S3, const char* S4); -LPSTR XRCORE_API strconcat ( int dest_sz, char* dest, const char* S1, const char* S2, const char* S3, const char* S4, const char* S5); -LPSTR XRCORE_API strconcat ( int dest_sz, char* dest, const char* S1, const char* S2, const char* S3, const char* S4, const char* S5, const char* S6); +LPSTR XRCORE_API strconcat(int dest_sz, char* dest, const char* S1, const char* S2); +LPSTR XRCORE_API strconcat(int dest_sz, char* dest, const char* S1, const char* S2, const char* S3); +LPSTR XRCORE_API strconcat(int dest_sz, char* dest, const char* S1, const char* S2, const char* S3, const char* S4); +LPSTR XRCORE_API strconcat(int dest_sz, char* dest, const char* S1, const char* S2, const char* S3, const char* S4, const char* S5); +LPSTR XRCORE_API strconcat(int dest_sz, char* dest, const char* S1, const char* S2, const char* S3, const char* S4, const char* S5, const char* S6); #else // _EDITOR // obsolete: should be deleted as soon borland work correctly with new strconcats -IC char* strconcat ( int dest_sz, char* dest, const char* S1, const char* S2) +IC char* strconcat(int dest_sz, char* dest, const char* S1, const char* S2) { - return xr_strcat(xr_strcpy(dest,dest_sz, S1),dest_sz, S2); + return xr_strcat(xr_strcpy(dest, dest_sz, S1), dest_sz, S2); } // dest = S1+S2+S3 -IC char* strconcat ( int dest_sz, char* dest, const char* S1, const char* S2, const char* S3) +IC char* strconcat(int dest_sz, char* dest, const char* S1, const char* S2, const char* S3) { - return xr_strcat(xr_strcat(xr_strcpy(dest,dest_sz,S1),dest_sz,S2),dest_sz,S3); + return xr_strcat(xr_strcat(xr_strcpy(dest, dest_sz, S1), dest_sz, S2), dest_sz, S3); } // dest = S1+S2+S3+S4 -IC char* strconcat ( int dest_sz, char* dest, const char* S1, const char* S2, const char* S3, const char* S4) +IC char* strconcat(int dest_sz, char* dest, const char* S1, const char* S2, const char* S3, const char* S4) { - return xr_strcat(xr_strcat(xr_strcat(xr_strcpy(dest,dest_sz,S1),dest_sz,S2),dest_sz,S3),dest_sz,S4); + return xr_strcat(xr_strcat(xr_strcat(xr_strcpy(dest, dest_sz, S1), dest_sz, S2), dest_sz, S3), dest_sz, S4); } // dest = S1+S2+S3+S4+S5 -IC char* strconcat ( int dest_sz, char* dest, const char* S1, const char* S2, const char* S3, const char* S4, const char* S5) +IC char* strconcat(int dest_sz, char* dest, const char* S1, const char* S2, const char* S3, const char* S4, const char* S5) { - return xr_strcat(xr_strcat(xr_strcat(xr_strcat(xr_strcpy(dest,dest_sz,S1),dest_sz,S2),dest_sz,S3),dest_sz,S4),dest_sz,S5); + return xr_strcat(xr_strcat(xr_strcat(xr_strcat(xr_strcpy(dest, dest_sz, S1), dest_sz, S2), dest_sz, S3), dest_sz, S4), dest_sz, S5); } // dest = S1+S2+S3+S4+S5+S6 -IC char* strconcat ( int dest_sz, char* dest, const char* S1, const char* S2, const char* S3, const char* S4, const char* S5, const char* S6) +IC char* strconcat(int dest_sz, char* dest, const char* S1, const char* S2, const char* S3, const char* S4, const char* S5, const char* S6) { - return xr_strcat(xr_strcat(xr_strcat(xr_strcat(xr_strcat(xr_strcpy(dest,dest_sz,S1),dest_sz,S2),dest_sz,S3),dest_sz,S4),dest_sz,S5),dest_sz,S6); + return xr_strcat(xr_strcat(xr_strcat(xr_strcat(xr_strcat(xr_strcpy(dest, dest_sz, S1), dest_sz, S2), dest_sz, S3), dest_sz, S4), dest_sz, S5), dest_sz, S6); } #endif @@ -50,22 +50,22 @@ IC char* strconcat ( int dest_sz, char* dest, const char* S1, const cha #ifdef STRCONCAT_STACKOVERFLOW_CHECK #define STRCONCAT(dest, ...) \ - do { \ - xray::core::detail::string_tupples STRCONCAT_tupples_unique_identifier(__VA_ARGS__); \ - u32 STRCONCAT_buffer_size = STRCONCAT_tupples_unique_identifier.size(); \ - xray::core::detail::check_stack_overflow(STRCONCAT_buffer_size); \ - (dest) = (LPSTR)_alloca(STRCONCAT_buffer_size); \ - STRCONCAT_tupples_unique_identifier.concat (dest); \ - } while (0) + do { \ + xray::core::detail::string_tupples STRCONCAT_tupples_unique_identifier(__VA_ARGS__); \ + u32 STRCONCAT_buffer_size = STRCONCAT_tupples_unique_identifier.size(); \ + xray::core::detail::check_stack_overflow(STRCONCAT_buffer_size); \ + (dest) = (LPSTR)_alloca(STRCONCAT_buffer_size); \ + STRCONCAT_tupples_unique_identifier.concat (dest); \ + } while (0) #else //#ifdef STRCONCAT_STACKOVERFLOW_CHECK #define STRCONCAT(dest, ...) \ - do { \ - xray::core::detail::string_tupples STRCONCAT_tupples_unique_identifier(__VA_ARGS__); \ - (dest) = (LPSTR)_alloca(STRCONCAT_tupples_unique_identifier.size()); \ - STRCONCAT_tupples_unique_identifier.concat (dest); \ - } while (0) + do { \ + xray::core::detail::string_tupples STRCONCAT_tupples_unique_identifier(__VA_ARGS__); \ + (dest) = (LPSTR)_alloca(STRCONCAT_tupples_unique_identifier.size()); \ + STRCONCAT_tupples_unique_identifier.concat (dest); \ + } while (0) #endif //#ifdef STRCONCAT_STACKOVERFLOW_CHECK diff --git a/src/xrCore/string_concatenations_inline.h b/src/xrCore/string_concatenations_inline.h index 291bc72dd38..de9c4dc7534 100644 --- a/src/xrCore/string_concatenations_inline.h +++ b/src/xrCore/string_concatenations_inline.h @@ -1,165 +1,172 @@ -namespace xray { +namespace xray +{ -namespace core { +namespace core +{ -namespace detail { +namespace detail +{ -class XRCORE_API string_tupples { +class XRCORE_API string_tupples +{ public: - template < typename T0 > - inline string_tupples ( T0 p0 ) : - m_count (1) - { - helper<0>::add_string (*this, p0); - } - - template < typename T0, typename T1 > - inline string_tupples ( T0 p0, T1 p1 ) : - m_count (2) - { - helper<0>::add_string (*this, p0); - helper<1>::add_string (*this, p1); - } - - template < typename T0, typename T1, typename T2 > - inline string_tupples ( T0 p0, T1 p1, T2 p2 ) : - m_count (3) - { - helper<0>::add_string (*this, p0); - helper<1>::add_string (*this, p1); - helper<2>::add_string (*this, p2); - } - - template < typename T0, typename T1, typename T2, typename T3 > - inline string_tupples ( T0 p0, T1 p1, T2 p2, T3 p3 ) : - m_count (4) - { - helper<0>::add_string (*this, p0); - helper<1>::add_string (*this, p1); - helper<2>::add_string (*this, p2); - helper<3>::add_string (*this, p3); - } - - template < typename T0, typename T1, typename T2, typename T3, typename T4 > - inline string_tupples ( T0 p0, T1 p1, T2 p2, T3 p3, T4 p4 ) : - m_count (5) - { - helper<0>::add_string (*this, p0); - helper<1>::add_string (*this, p1); - helper<2>::add_string (*this, p2); - helper<3>::add_string (*this, p3); - helper<4>::add_string (*this, p4); - } - - template < typename T0, typename T1, typename T2, typename T3, typename T4, typename T5 > - inline string_tupples ( T0 p0, T1 p1, T2 p2, T3 p3, T4 p4, T5 p5 ) : - m_count (6) - { - helper<0>::add_string (*this, p0); - helper<1>::add_string (*this, p1); - helper<2>::add_string (*this, p2); - helper<3>::add_string (*this, p3); - helper<4>::add_string (*this, p4); - helper<5>::add_string (*this, p5); - } - - void error_process () const; - - inline u32 size () const - { - VERIFY (m_count > 0); - - u32 result = m_strings[0].second; - - for (u32 j = 1; j < m_count; ++j) - result += m_strings[j].second; - - if ( result > max_concat_result_size ) - { - error_process(); - } - - return ((result + 1)*sizeof(*m_strings[0].first)); - } - - inline void concat (LPCSTR const result) const - { - VERIFY (m_count > 0); - - LPSTR i = const_cast(result); - Memory.mem_copy (i, m_strings[0].first, m_strings[0].second*sizeof(*m_strings[0].first)); - i += m_strings[0].second; - - for (u32 j = 1; j < m_count; ++j) { - Memory.mem_copy (i, m_strings[j].first, m_strings[j].second*sizeof(*m_strings[j].first)); - i += m_strings[j].second; - } - - *i = 0; - } + template < typename T0 > + inline string_tupples(T0 p0) : + m_count(1) + { + helper<0>::add_string(*this, p0); + } + + template < typename T0, typename T1 > + inline string_tupples(T0 p0, T1 p1) : + m_count(2) + { + helper<0>::add_string(*this, p0); + helper<1>::add_string(*this, p1); + } + + template < typename T0, typename T1, typename T2 > + inline string_tupples(T0 p0, T1 p1, T2 p2) : + m_count(3) + { + helper<0>::add_string(*this, p0); + helper<1>::add_string(*this, p1); + helper<2>::add_string(*this, p2); + } + + template < typename T0, typename T1, typename T2, typename T3 > + inline string_tupples(T0 p0, T1 p1, T2 p2, T3 p3) : + m_count(4) + { + helper<0>::add_string(*this, p0); + helper<1>::add_string(*this, p1); + helper<2>::add_string(*this, p2); + helper<3>::add_string(*this, p3); + } + + template < typename T0, typename T1, typename T2, typename T3, typename T4 > + inline string_tupples(T0 p0, T1 p1, T2 p2, T3 p3, T4 p4) : + m_count(5) + { + helper<0>::add_string(*this, p0); + helper<1>::add_string(*this, p1); + helper<2>::add_string(*this, p2); + helper<3>::add_string(*this, p3); + helper<4>::add_string(*this, p4); + } + + template < typename T0, typename T1, typename T2, typename T3, typename T4, typename T5 > + inline string_tupples(T0 p0, T1 p1, T2 p2, T3 p3, T4 p4, T5 p5) : + m_count(6) + { + helper<0>::add_string(*this, p0); + helper<1>::add_string(*this, p1); + helper<2>::add_string(*this, p2); + helper<3>::add_string(*this, p3); + helper<4>::add_string(*this, p4); + helper<5>::add_string(*this, p5); + } + + void error_process() const; + + inline u32 size() const + { + VERIFY(m_count > 0); + + u32 result = m_strings[0].second; + + for (u32 j = 1; j < m_count; ++j) + result += m_strings[j].second; + + if (result > max_concat_result_size) + { + error_process(); + } + + return ((result + 1)*sizeof(*m_strings[0].first)); + } + + inline void concat(LPCSTR const result) const + { + VERIFY(m_count > 0); + + LPSTR i = const_cast(result); + Memory.mem_copy(i, m_strings[0].first, m_strings[0].second*sizeof(*m_strings[0].first)); + i += m_strings[0].second; + + for (u32 j = 1; j < m_count; ++j) + { + Memory.mem_copy(i, m_strings[j].first, m_strings[j].second*sizeof(*m_strings[j].first)); + i += m_strings[j].second; + } + + *i = 0; + } private: - enum { - max_concat_result_size = u32(512*1024), - max_item_count = 6, - }; + enum + { + max_concat_result_size = u32(512 * 1024), + max_item_count = 6, + }; private: - template - struct helper { - - static inline u32 length (LPCSTR string) - { - return (string ? (unsigned int)xr_strlen(string) : 0); - } - - static inline LPCSTR string (LPCSTR string) - { - return (string); - } - - static inline u32 length (shared_str const& string) - { - return (string.size()); - } - - static inline LPCSTR string (shared_str const& string) - { - return (string.c_str()); - } - - static inline u32 length (xr_string const& string) - { - return (string.size()); - } - - static inline LPCSTR string (xr_string const& string) - { - return (string.c_str()); - } - - template - static inline void add_string (string_tupples& self, T p) - { - STATIC_CHECK (index < max_item_count, Error_invalid_string_index_specified); - - LPCSTR cstr = string(p); - VERIFY (cstr); - self.m_strings[index] = std::make_pair(cstr, length(p)); - } - }; // struct helper + template + struct helper + { + + static inline u32 length(LPCSTR string) + { + return (string ? (unsigned int)xr_strlen(string) : 0); + } + + static inline LPCSTR string(LPCSTR string) + { + return (string); + } + + static inline u32 length(shared_str const& string) + { + return (string.size()); + } + + static inline LPCSTR string(shared_str const& string) + { + return (string.c_str()); + } + + static inline u32 length(xr_string const& string) + { + return (string.size()); + } + + static inline LPCSTR string(xr_string const& string) + { + return (string.c_str()); + } + + template + static inline void add_string(string_tupples& self, T p) + { + STATIC_CHECK(index < max_item_count, Error_invalid_string_index_specified); + + LPCSTR cstr = string(p); + VERIFY(cstr); + self.m_strings[index] = std::make_pair(cstr, length(p)); + } + }; // struct helper private: - typedef std::pair StringPair; + typedef std::pair StringPair; private: - StringPair m_strings[max_item_count]; - u32 m_count; + StringPair m_strings[max_item_count]; + u32 m_count; }; -void XRCORE_API check_stack_overflow (u32 stack_increment); +void XRCORE_API check_stack_overflow(u32 stack_increment); } // namespace detail diff --git a/src/xrCore/vector.h b/src/xrCore/vector.h index c47ab737e78..b8c8d8a92cb 100644 --- a/src/xrCore/vector.h +++ b/src/xrCore/vector.h @@ -16,96 +16,101 @@ #endif // Select platform -#ifdef _MSC_VER -#define M_VISUAL +#ifdef _MSC_VER +#define M_VISUAL #endif -#ifdef __BORLANDC__ +#ifdef __BORLANDC__ #define M_BORLAND #endif // Constants #ifdef M_VISUAL -const float EPS_S = 0.0000001f; -const float EPS = 0.0000100f; -const float EPS_L = 0.0010000f; +const float EPS_S = 0.0000001f; +const float EPS = 0.0000100f; +const float EPS_L = 0.0010000f; #undef M_SQRT1_2 -const float M_SQRT1_2 = 0.7071067811865475244008443621048f;//490; +const float M_SQRT1_2 = 0.7071067811865475244008443621048f;//490; -const float M_PI = 3.1415926535897932384626433832795f; -const float PI = 3.1415926535897932384626433832795f; -const float PI_MUL_2 = 6.2831853071795864769252867665590f; -const float PI_MUL_3 = 9.4247779607693797153879301498385f; -const float PI_MUL_4 = 12.566370614359172953850573533118f; -const float PI_MUL_6 = 18.849555921538759430775860299677f; -const float PI_MUL_8 = 25.132741228718345907701147066236f; -const float PI_DIV_2 = 1.5707963267948966192313216916398f; -const float PI_DIV_3 = 1.0471975511965977461542144610932f; -const float PI_DIV_4 = 0.7853981633974483096156608458199f; -const float PI_DIV_6 = 0.5235987755982988730771072305466f; -const float PI_DIV_8 = 0.3926990816987241548078304229099f; +const float M_PI = 3.1415926535897932384626433832795f; +const float PI = 3.1415926535897932384626433832795f; +const float PI_MUL_2 = 6.2831853071795864769252867665590f; +const float PI_MUL_3 = 9.4247779607693797153879301498385f; +const float PI_MUL_4 = 12.566370614359172953850573533118f; +const float PI_MUL_6 = 18.849555921538759430775860299677f; +const float PI_MUL_8 = 25.132741228718345907701147066236f; +const float PI_DIV_2 = 1.5707963267948966192313216916398f; +const float PI_DIV_3 = 1.0471975511965977461542144610932f; +const float PI_DIV_4 = 0.7853981633974483096156608458199f; +const float PI_DIV_6 = 0.5235987755982988730771072305466f; +const float PI_DIV_8 = 0.3926990816987241548078304229099f; #endif #ifdef M_BORLAND -#define EPS_S 0.0000001f -#define EPS 0.0000100f -#define EPS_L 0.0010000f - -#define M_PI 3.1415926535897932384626433832795f -#define PI 3.1415926535897932384626433832795f -#define PI_MUL_2 6.2831853071795864769252867665590f -#define PI_MUL_3 9.4247779607693797153879301498385f -#define PI_MUL_4 12.566370614359172953850573533118f -#define PI_DIV_3 1.0471975511965977461542144610932f -#define PI_MUL_6 18.849555921538759430775860299677f -#define PI_MUL_8 25.132741228718345907701147066236f -#define PI_MUL_2 6.2831853071795864769252867665590f -#define PI_DIV_2 1.5707963267948966192313216916398f -#define PI_DIV_4 0.7853981633974483096156608458199f -#define PI_DIV_6 0.5235987755982988730771072305466f -#define PI_DIV_8 0.3926990816987241548078304229099f +#define EPS_S 0.0000001f +#define EPS 0.0000100f +#define EPS_L 0.0010000f + +#define M_PI 3.1415926535897932384626433832795f +#define PI 3.1415926535897932384626433832795f +#define PI_MUL_2 6.2831853071795864769252867665590f +#define PI_MUL_3 9.4247779607693797153879301498385f +#define PI_MUL_4 12.566370614359172953850573533118f +#define PI_DIV_3 1.0471975511965977461542144610932f +#define PI_MUL_6 18.849555921538759430775860299677f +#define PI_MUL_8 25.132741228718345907701147066236f +#define PI_MUL_2 6.2831853071795864769252867665590f +#define PI_DIV_2 1.5707963267948966192313216916398f +#define PI_DIV_4 0.7853981633974483096156608458199f +#define PI_DIV_6 0.5235987755982988730771072305466f +#define PI_DIV_8 0.3926990816987241548078304229099f #endif // Define types and namespaces (CPU & FPU) -#include "_types.h" -#include "_math.h" -#include "_bitwise.h" -#include "_std_extensions.h" +#include "_types.h" +#include "_math.h" +#include "_bitwise.h" +#include "_std_extensions.h" // comparisions -IC BOOL fsimilar ( float a, float b, float cmp=EPS ) { return _abs(a-b) ICF T deg2rad ( T val ) { return (val*T(M_PI)/T(180)); }; - template ICF T rad2deg ( T val ) { return (val*T(180)/T(M_PI)); }; +namespace implement +{ +template ICF T deg2rad(T val) { return (val*T(M_PI) / T(180)); }; +template ICF T rad2deg(T val) { return (val*T(180) / T(M_PI)); }; }; -ICF float deg2rad (float val) {return implement::deg2rad(val);} -ICF double deg2rad (double val) {return implement::deg2rad(val);} -ICF float rad2deg (float val) {return implement::rad2deg(val);} -ICF double rad2deg (double val) {return implement::rad2deg(val);} +ICF float deg2rad(float val) { return implement::deg2rad(val); } +ICF double deg2rad(double val) { return implement::deg2rad(val); } +ICF float rad2deg(float val) { return implement::rad2deg(val); } +ICF double rad2deg(double val) { return implement::rad2deg(val); } // clamping/snapping template -IC void clamp ( T& val, const T& _low, const T& _high ){ - if( val<_low ) val = _low; else if( val>_high ) val = _high; +IC void clamp(T& val, const T& _low, const T& _high) +{ + if (val<_low) val = _low; + else if (val>_high) val = _high; }; template -IC T clampr ( const T& val, const T& _low, const T& _high ){ - if ( val<_low ) return _low; - else if ( val>_high ) return _high; - else return val; +IC T clampr(const T& val, const T& _low, const T& _high) +{ + if (val < _low) return _low; + else if (val > _high) return _high; + else return val; }; -IC float snapto ( float value, float snap ) { - if( snap<=0.f ) return value; - return float(iFloor((value+(snap*0.5f)) / snap )) * snap; +IC float snapto(float value, float snap) +{ + if (snap <= 0.f) return value; + return float(iFloor((value + (snap*0.5f)) / snap)) * snap; }; // pre-definitions @@ -134,296 +139,354 @@ template struct _quaternion; #include "_plane.h" #include "_plane2.h" #include "_flags.h" -#ifdef DEBUG +#ifdef DEBUG #include "dump_string.h" #endif #pragma pack(pop) // normalize angle (0..2PI) -ICF float angle_normalize_always (float a) +ICF float angle_normalize_always(float a) { - float div = a/PI_MUL_2; - int rnd = (div>0)?iFloor(div):iCeil(div); - float frac = div-rnd; - if (frac<0) frac += 1.f; - return frac * PI_MUL_2; + float div = a / PI_MUL_2; + int rnd = (div > 0) ? iFloor(div) : iCeil(div); + float frac = div - rnd; + if (frac < 0) frac += 1.f; + return frac * PI_MUL_2; } // normalize angle (0..2PI) -ICF float angle_normalize (float a) +ICF float angle_normalize(float a) { - if (a>=0 && a<=PI_MUL_2) return a; - else return angle_normalize_always(a); + if (a >= 0 && a <= PI_MUL_2) return a; + else return angle_normalize_always(a); } // -PI .. +PI -ICF float angle_normalize_signed(float a) +ICF float angle_normalize_signed(float a) { - if (a>=(-PI) && a<=PI) return a; - float angle = angle_normalize_always (a); - if (angle>PI) angle-=PI_MUL_2; - return angle; + if (a >= (-PI) && a <= PI) return a; + float angle = angle_normalize_always(a); + if (angle > PI) angle -= PI_MUL_2; + return angle; } // -PI..PI -ICF float angle_difference_signed(float a, float b) +ICF float angle_difference_signed(float a, float b) { - float diff = angle_normalize_signed(a) - angle_normalize_signed(b); - if (diff>0) { - if (diff>PI) - diff -= PI_MUL_2; - } else { - if (diff<-PI) - diff += PI_MUL_2; - } - return diff; + float diff = angle_normalize_signed(a) - angle_normalize_signed(b); + if (diff > 0) + { + if (diff > PI) + diff -= PI_MUL_2; + } + else + { + if (diff < -PI) + diff += PI_MUL_2; + } + return diff; } // 0..PI -ICF float angle_difference(float a, float b) +ICF float angle_difference(float a, float b) { - return _abs (angle_difference_signed(a,b)); + return _abs(angle_difference_signed(a, b)); } -IC bool are_ordered ( float const value0, float const value1, float const value2 ) +IC bool are_ordered(float const value0, float const value1, float const value2) { - if ( (value1 >= value0) && (value1 <= value2) ) - return true; + if ((value1 >= value0) && (value1 <= value2)) + return true; - if ( (value1 <= value0) && (value1 >= value2) ) - return true; + if ((value1 <= value0) && (value1 >= value2)) + return true; - return false; + return false; } -IC bool is_between ( float const value, float const left, float const right ) +IC bool is_between(float const value, float const left, float const right) { - return are_ordered( left, value, right ); + return are_ordered(left, value, right); } // c=current, t=target, s=speed, dt=dt -IC bool angle_lerp (float& c, float t, float s, float dt) +IC bool angle_lerp(float& c, float t, float s, float dt) { - float const before = c; - float diff = t - c; - if (diff>0) { - if (diff>PI) - diff -= PI_MUL_2; - } else { - if (diff<-PI) - diff += PI_MUL_2; - } - float diff_a = _abs(diff); - - if (diff_adiff_a) mot=diff_a; - c += (diff/diff_a)*mot; - - if ( is_between(c,before,t) ) - return false; - - if (c<0) - c+=PI_MUL_2; - else if (c>PI_MUL_2) - c-=PI_MUL_2; - - return false; + float const before = c; + float diff = t - c; + if (diff > 0) + { + if (diff > PI) + diff -= PI_MUL_2; + } + else + { + if (diff < -PI) + diff += PI_MUL_2; + } + float diff_a = _abs(diff); + + if (diff_a < EPS_S) + return true; + + float mot = s*dt; + if (mot > diff_a) mot = diff_a; + c += (diff / diff_a)*mot; + + if (is_between(c, before, t)) + return false; + + if (c < 0) + c += PI_MUL_2; + else if (c > PI_MUL_2) + c -= PI_MUL_2; + + return false; } -// Just lerp :) expects normalized angles in range [0..2PI) -ICF float angle_lerp (float A, float B, float f) +// Just lerp :) expects normalized angles in range [0..2PI) +ICF float angle_lerp(float A, float B, float f) { - float diff = B - A; - if (diff>PI) diff -= PI_MUL_2; - else if (diff<-PI) diff += PI_MUL_2; + float diff = B - A; + if (diff > PI) diff -= PI_MUL_2; + else if (diff < -PI) diff += PI_MUL_2; - return A + diff*f; + return A + diff*f; } -IC float angle_inertion (float src, float tgt, float speed, float clmp, float dt) +IC float angle_inertion(float src, float tgt, float speed, float clmp, float dt) { - float a = angle_normalize_signed (tgt); - angle_lerp (src,a,speed,dt); - src = angle_normalize_signed (src); - float dH = angle_difference_signed (src,a); - float dCH = clampr (dH,-clmp,clmp); - src -= dH-dCH; - return src; + float a = angle_normalize_signed(tgt); + angle_lerp(src, a, speed, dt); + src = angle_normalize_signed(src); + float dH = angle_difference_signed(src, a); + float dCH = clampr(dH, -clmp, clmp); + src -= dH - dCH; + return src; } -IC float angle_inertion_var(float src, float tgt, float min_speed, float max_speed, float clmp, float dt) +IC float angle_inertion_var(float src, float tgt, float min_speed, float max_speed, float clmp, float dt) { - tgt = angle_normalize_signed (tgt); - src = angle_normalize_signed (src); - float speed = _abs((max_speed-min_speed)*angle_difference(tgt,src)/clmp)+min_speed; - angle_lerp (src,tgt,speed,dt); - src = angle_normalize_signed (src); - float dH = angle_difference_signed (src,tgt); - float dCH = clampr (dH,-clmp,clmp); - src -= dH-dCH; - return src; + tgt = angle_normalize_signed(tgt); + src = angle_normalize_signed(src); + float speed = _abs((max_speed - min_speed)*angle_difference(tgt, src) / clmp) + min_speed; + angle_lerp(src, tgt, speed, dt); + src = angle_normalize_signed(src); + float dH = angle_difference_signed(src, tgt); + float dCH = clampr(dH, -clmp, clmp); + src -= dH - dCH; + return src; } template -IC _matrix& _matrix::rotation (const _quaternion &Q) +IC _matrix& _matrix::rotation(const _quaternion& Q) { - T xx = Q.x*Q.x; T yy = Q.y*Q.y; T zz = Q.z*Q.z; - T xy = Q.x*Q.y; T xz = Q.x*Q.z; T yz = Q.y*Q.z; - T wx = Q.w*Q.x; T wy = Q.w*Q.y; T wz = Q.w*Q.z; - - _11 = 1 - 2 * ( yy + zz ); _12 = 2 * ( xy - wz ); _13 = 2 * ( xz + wy ); _14 = 0; - _21 = 2 * ( xy + wz ); _22 = 1 - 2 * ( xx + zz ); _23 = 2 * ( yz - wx ); _24 = 0; - _31 = 2 * ( xz - wy ); _32 = 2 * ( yz + wx ); _33 = 1 - 2 * ( xx + yy ); _34 = 0; - _41 = 0; _42 = 0; _43 = 0; _44 = 1; - return *this; + T xx = Q.x*Q.x; + T yy = Q.y*Q.y; + T zz = Q.z*Q.z; + T xy = Q.x*Q.y; + T xz = Q.x*Q.z; + T yz = Q.y*Q.z; + T wx = Q.w*Q.x; + T wy = Q.w*Q.y; + T wz = Q.w*Q.z; + + _11 = 1 - 2 * (yy + zz); + _12 = 2 * (xy - wz); + _13 = 2 * (xz + wy); + _14 = 0; + _21 = 2 * (xy + wz); + _22 = 1 - 2 * (xx + zz); + _23 = 2 * (yz - wx); + _24 = 0; + _31 = 2 * (xz - wy); + _32 = 2 * (yz + wx); + _33 = 1 - 2 * (xx + yy); + _34 = 0; + _41 = 0; + _42 = 0; + _43 = 0; + _44 = 1; + return *this; } template -IC _matrix& _matrix::mk_xform (const _quaternion &Q, const Tvector &V) +IC _matrix& _matrix::mk_xform(const _quaternion& Q, const Tvector& V) { - T xx = Q.x*Q.x; T yy = Q.y*Q.y; T zz = Q.z*Q.z; - T xy = Q.x*Q.y; T xz = Q.x*Q.z; T yz = Q.y*Q.z; - T wx = Q.w*Q.x; T wy = Q.w*Q.y; T wz = Q.w*Q.z; - - _11 = 1 - 2 * ( yy + zz ); _12 = 2 * ( xy - wz ); _13 = 2 * ( xz + wy ); _14 = 0; - _21 = 2 * ( xy + wz ); _22 = 1 - 2 * ( xx + zz ); _23 = 2 * ( yz - wx ); _24 = 0; - _31 = 2 * ( xz - wy ); _32 = 2 * ( yz + wx ); _33 = 1 - 2 * ( xx + yy ); _34 = 0; - _41 = V.x; _42 = V.y; _43 = V.z; _44 = 1; - return *this; + T xx = Q.x*Q.x; + T yy = Q.y*Q.y; + T zz = Q.z*Q.z; + T xy = Q.x*Q.y; + T xz = Q.x*Q.z; + T yz = Q.y*Q.z; + T wx = Q.w*Q.x; + T wy = Q.w*Q.y; + T wz = Q.w*Q.z; + + _11 = 1 - 2 * (yy + zz); + _12 = 2 * (xy - wz); + _13 = 2 * (xz + wy); + _14 = 0; + _21 = 2 * (xy + wz); + _22 = 1 - 2 * (xx + zz); + _23 = 2 * (yz - wx); + _24 = 0; + _31 = 2 * (xz - wy); + _32 = 2 * (yz + wx); + _33 = 1 - 2 * (xx + yy); + _34 = 0; + _41 = V.x; + _42 = V.y; + _43 = V.z; + _44 = 1; + return *this; } -#define TRACE_QZERO_TOLERANCE 0.1f +#define TRACE_QZERO_TOLERANCE 0.1f template IC _quaternion& _quaternion::set(const _matrix& M) { - float trace,s; - - trace = M._11 + M._22 + M._33; - if (trace > 0.0f){ - s = _sqrt(trace + 1.0f); - w = s * 0.5f; - s = 0.5f / s; - - x = (M._32 - M._23) * s; - y = (M._13 - M._31) * s; - z = (M._21 - M._12) * s; - }else{ - int biggest; - enum {A,E,I}; - if (M._11 > M._22){ - if (M._33 > M._11) - biggest = I; - else - biggest = A; - }else{ - if (M._33 > M._11) - biggest = I; - else - biggest = E; - } - - // in the unusual case the original trace fails to produce a good sqrt, try others... - switch (biggest){ - case A: - s = _sqrt( M._11 - (M._22 + M._33) + 1.0f); - if (s > TRACE_QZERO_TOLERANCE){ - x = s * 0.5f; - s = 0.5f / s; - w = (M._32 - M._23) * s; - y = (M._12 + M._21) * s; - z = (M._13 + M._31) * s; - break; - } - // I - s = _sqrt( M._33 - (M._11 + M._22) + 1.0f); - if (s > TRACE_QZERO_TOLERANCE){ - z = s * 0.5f; - s = 0.5f / s; - w = (M._21 - M._12) * s; - x = (M._31 + M._13) * s; - y = (M._32 + M._23) * s; - break; - } - // E - s = _sqrt( M._22 - (M._33 + M._11) + 1.0f); - if (s > TRACE_QZERO_TOLERANCE){ - y = s * 0.5f; - s = 0.5f / s; - w = (M._13 - M._31) * s; - z = (M._23 + M._32) * s; - x = (M._21 + M._12) * s; - break; - } - break; - case E: - s = _sqrt( M._22 - (M._33 + M._11) + 1.0f); - if (s > TRACE_QZERO_TOLERANCE){ - y = s * 0.5f; - s = 0.5f / s; - w = (M._13 - M._31) * s; - z = (M._23 + M._32) * s; - x = (M._21 + M._12) * s; - break; - } - // I - s = _sqrt( M._33 - (M._11 + M._22) + 1.0f); - if (s > TRACE_QZERO_TOLERANCE){ - z = s * 0.5f; - s = 0.5f / s; - w = (M._21 - M._12) * s; - x = (M._31 + M._13) * s; - y = (M._32 + M._23) * s; - break; - } - // A - s = _sqrt( M._11 - (M._22 + M._33) + 1.0f); - if (s > TRACE_QZERO_TOLERANCE){ - x = s * 0.5f; - s = 0.5f / s; - w = (M._32 - M._23) * s; - y = (M._12 + M._21) * s; - z = (M._13 + M._31) * s; - break; - } - break; - case I: - s = _sqrt( M._33 - (M._11 + M._22) + 1.0f); - if (s > TRACE_QZERO_TOLERANCE){ - z = s * 0.5f; - s = 0.5f / s; - w = (M._21 - M._12) * s; - x = (M._31 + M._13) * s; - y = (M._32 + M._23) * s; - break; - } - // A - s = _sqrt( M._11 - (M._22 + M._33) + 1.0f); - if (s > TRACE_QZERO_TOLERANCE){ - x = s * 0.5f; - s = 0.5f / s; - w = (M._32 - M._23) * s; - y = (M._12 + M._21) * s; - z = (M._13 + M._31) * s; - break; - } - // E - s = _sqrt( M._22 - (M._33 + M._11) + 1.0f); - if (s > TRACE_QZERO_TOLERANCE){ - y = s * 0.5f; - s = 0.5f / s; - w = (M._13 - M._31) * s; - z = (M._23 + M._32) * s; - x = (M._21 + M._12) * s; - break; - } - break; - } - } - return *this; + float trace, s; + + trace = M._11 + M._22 + M._33; + if (trace > 0.0f) + { + s = _sqrt(trace + 1.0f); + w = s * 0.5f; + s = 0.5f / s; + + x = (M._32 - M._23) * s; + y = (M._13 - M._31) * s; + z = (M._21 - M._12) * s; + } + else + { + int biggest; + enum { A, E, I }; + if (M._11 > M._22) + { + if (M._33 > M._11) + biggest = I; + else + biggest = A; + } + else + { + if (M._33 > M._11) + biggest = I; + else + biggest = E; + } + + // in the unusual case the original trace fails to produce a good sqrt, try others... + switch (biggest) + { + case A: + s = _sqrt(M._11 - (M._22 + M._33) + 1.0f); + if (s > TRACE_QZERO_TOLERANCE) + { + x = s * 0.5f; + s = 0.5f / s; + w = (M._32 - M._23) * s; + y = (M._12 + M._21) * s; + z = (M._13 + M._31) * s; + break; + } + // I + s = _sqrt(M._33 - (M._11 + M._22) + 1.0f); + if (s > TRACE_QZERO_TOLERANCE) + { + z = s * 0.5f; + s = 0.5f / s; + w = (M._21 - M._12) * s; + x = (M._31 + M._13) * s; + y = (M._32 + M._23) * s; + break; + } + // E + s = _sqrt(M._22 - (M._33 + M._11) + 1.0f); + if (s > TRACE_QZERO_TOLERANCE) + { + y = s * 0.5f; + s = 0.5f / s; + w = (M._13 - M._31) * s; + z = (M._23 + M._32) * s; + x = (M._21 + M._12) * s; + break; + } + break; + case E: + s = _sqrt(M._22 - (M._33 + M._11) + 1.0f); + if (s > TRACE_QZERO_TOLERANCE) + { + y = s * 0.5f; + s = 0.5f / s; + w = (M._13 - M._31) * s; + z = (M._23 + M._32) * s; + x = (M._21 + M._12) * s; + break; + } + // I + s = _sqrt(M._33 - (M._11 + M._22) + 1.0f); + if (s > TRACE_QZERO_TOLERANCE) + { + z = s * 0.5f; + s = 0.5f / s; + w = (M._21 - M._12) * s; + x = (M._31 + M._13) * s; + y = (M._32 + M._23) * s; + break; + } + // A + s = _sqrt(M._11 - (M._22 + M._33) + 1.0f); + if (s > TRACE_QZERO_TOLERANCE) + { + x = s * 0.5f; + s = 0.5f / s; + w = (M._32 - M._23) * s; + y = (M._12 + M._21) * s; + z = (M._13 + M._31) * s; + break; + } + break; + case I: + s = _sqrt(M._33 - (M._11 + M._22) + 1.0f); + if (s > TRACE_QZERO_TOLERANCE) + { + z = s * 0.5f; + s = 0.5f / s; + w = (M._21 - M._12) * s; + x = (M._31 + M._13) * s; + y = (M._32 + M._23) * s; + break; + } + // A + s = _sqrt(M._11 - (M._22 + M._33) + 1.0f); + if (s > TRACE_QZERO_TOLERANCE) + { + x = s * 0.5f; + s = 0.5f / s; + w = (M._32 - M._23) * s; + y = (M._12 + M._21) * s; + z = (M._13 + M._31) * s; + break; + } + // E + s = _sqrt(M._22 - (M._33 + M._11) + 1.0f); + if (s > TRACE_QZERO_TOLERANCE) + { + y = s * 0.5f; + s = 0.5f / s; + w = (M._13 - M._31) * s; + z = (M._23 + M._32) * s; + x = (M._21 + M._12) * s; + break; + } + break; + } + } + return *this; } //---------------------------------------------------------------------------------------------- diff --git a/src/xrCore/xrCore.cpp b/src/xrCore/xrCore.cpp index 02b26c1916b..6dd7e9e3d63 100644 --- a/src/xrCore/xrCore.cpp +++ b/src/xrCore/xrCore.cpp @@ -6,184 +6,188 @@ #include #include #include "xrCore.h" - + #pragma comment(lib,"winmm.lib") #ifdef DEBUG -# include +# include #endif // DEBUG -XRCORE_API xrCore Core; -XRCORE_API u32 build_id; -XRCORE_API LPCSTR build_date; +XRCORE_API xrCore Core; +XRCORE_API u32 build_id; +XRCORE_API LPCSTR build_date; namespace CPU { - extern void Detect (); +extern void Detect(); }; -static u32 init_counter = 0; +static u32 init_counter = 0; extern char g_application_path[256]; -//. extern xr_vector* LogFile; +//. extern xr_vector* LogFile; -void xrCore::_initialize (LPCSTR _ApplicationName, LogCallback cb, BOOL init_fs, LPCSTR fs_fname) +void xrCore::_initialize(LPCSTR _ApplicationName, LogCallback cb, BOOL init_fs, LPCSTR fs_fname) { - xr_strcpy (ApplicationName,_ApplicationName); - if (0==init_counter) { -#ifdef XRCORE_STATIC - _clear87 (); - _control87 ( _PC_53, MCW_PC ); - _control87 ( _RC_CHOP, MCW_RC ); - _control87 ( _RC_NEAR, MCW_RC ); - _control87 ( _MCW_EM, MCW_EM ); + xr_strcpy(ApplicationName, _ApplicationName); + if (0 == init_counter) + { +#ifdef XRCORE_STATIC + _clear87(); + _control87(_PC_53, MCW_PC); + _control87(_RC_CHOP, MCW_RC); + _control87(_RC_NEAR, MCW_RC); + _control87(_MCW_EM, MCW_EM); #endif - // Init COM so we can use CoCreateInstance -// HRESULT co_res = + // Init COM so we can use CoCreateInstance + // HRESULT co_res = Params = xr_strdup(GetCommandLine()); xr_strlwr(Params); if (!strstr(Params, "-editor")) - CoInitializeEx (NULL, COINIT_MULTITHREADED); + CoInitializeEx(NULL, COINIT_MULTITHREADED); - string_path fn,dr,di; + string_path fn, dr, di; - // application path - GetModuleFileName(GetModuleHandle(MODULE_NAME),fn,sizeof(fn)); - _splitpath (fn,dr,di,0,0); - strconcat (sizeof(ApplicationPath),ApplicationPath,dr,di); + // application path + GetModuleFileName(GetModuleHandle(MODULE_NAME), fn, sizeof(fn)); + _splitpath(fn, dr, di, 0, 0); + strconcat(sizeof(ApplicationPath), ApplicationPath, dr, di); #ifndef _EDITOR - xr_strcpy (g_application_path,sizeof(g_application_path),ApplicationPath); + xr_strcpy(g_application_path, sizeof(g_application_path), ApplicationPath); #endif #ifdef _EDITOR - // working path - if( strstr(Params,"-wf") ) + // working path + if (strstr(Params, "-wf")) { - string_path c_name; - sscanf (strstr(Core.Params,"-wf ")+4,"%[^ ] ",c_name); - SetCurrentDirectory (c_name); + string_path c_name; + sscanf(strstr(Core.Params, "-wf ") + 4, "%[^ ] ", c_name); + SetCurrentDirectory(c_name); } #endif - GetCurrentDirectory(sizeof(WorkingPath),WorkingPath); + GetCurrentDirectory(sizeof(WorkingPath), WorkingPath); + + // User/Comp Name + DWORD sz_user = sizeof(UserName); + GetUserName(UserName, &sz_user); - // User/Comp Name - DWORD sz_user = sizeof(UserName); - GetUserName (UserName,&sz_user); + DWORD sz_comp = sizeof(CompName); + GetComputerName(CompName, &sz_comp); - DWORD sz_comp = sizeof(CompName); - GetComputerName (CompName,&sz_comp); + // Mathematics & PSI detection + CPU::Detect(); - // Mathematics & PSI detection - CPU::Detect (); - - Memory._initialize (strstr(Params,"-mem_debug") ? TRUE : FALSE); + Memory._initialize(strstr(Params, "-mem_debug") ? TRUE : FALSE); - DUMP_PHASE; + DUMP_PHASE; - InitLog (); - _initialize_cpu (); + InitLog(); + _initialize_cpu(); -// Debug._initialize (); + // Debug._initialize (); - rtc_initialize (); + rtc_initialize(); - xr_FS = xr_new (); + xr_FS = xr_new(); - xr_EFS = xr_new (); -//. R_ASSERT (co_res==S_OK); - } - if (init_fs){ - u32 flags = 0; - if (0!=strstr(Params,"-build")) flags |= CLocatorAPI::flBuildCopy; - if (0!=strstr(Params,"-ebuild")) flags |= CLocatorAPI::flBuildCopy|CLocatorAPI::flEBuildCopy; + xr_EFS = xr_new(); + //. R_ASSERT (co_res==S_OK); + } + if (init_fs) + { + u32 flags = 0; + if (0 != strstr(Params, "-build")) flags |= CLocatorAPI::flBuildCopy; + if (0 != strstr(Params, "-ebuild")) flags |= CLocatorAPI::flBuildCopy | CLocatorAPI::flEBuildCopy; #ifdef DEBUG - if (strstr(Params,"-cache")) flags |= CLocatorAPI::flCacheFiles; - else flags &= ~CLocatorAPI::flCacheFiles; + if (strstr(Params, "-cache")) flags |= CLocatorAPI::flCacheFiles; + else flags &= ~CLocatorAPI::flCacheFiles; #endif // DEBUG #ifdef _EDITOR // for EDITORS - no cache - flags &=~ CLocatorAPI::flCacheFiles; + flags &= ~CLocatorAPI::flCacheFiles; #endif // _EDITOR - flags |= CLocatorAPI::flScanAppRoot; + flags |= CLocatorAPI::flScanAppRoot; -#ifndef _EDITOR - #ifndef ELocatorAPIH - if (0!=strstr(Params,"-file_activity")) flags |= CLocatorAPI::flDumpFileActivity; - #endif +#ifndef _EDITOR +#ifndef ELocatorAPIH + if (0 != strstr(Params, "-file_activity")) flags |= CLocatorAPI::flDumpFileActivity; #endif - FS._initialize (flags,0,fs_fname); - Msg ("'%s' build %d, %s\n","xrCore",build_id, build_date); - EFS._initialize (); +#endif + FS._initialize(flags, 0, fs_fname); + Msg("'%s' build %d, %s\n", "xrCore", build_id, build_date); + EFS._initialize(); #ifdef DEBUG - #ifndef _EDITOR - Msg ("Process heap 0x%08x",GetProcessHeap()); - #endif +#ifndef _EDITOR + Msg("Process heap 0x%08x", GetProcessHeap()); +#endif #endif // DEBUG - } - SetLogCB (cb); - init_counter++; + } + SetLogCB(cb); + init_counter++; } -#ifndef _EDITOR +#ifndef _EDITOR #include "compression_ppmd_stream.h" -extern compression::ppmd::stream *trained_model; +extern compression::ppmd::stream* trained_model; #endif -void xrCore::_destroy () +void xrCore::_destroy() { - --init_counter; - if (0==init_counter){ - FS._destroy (); - EFS._destroy (); - xr_delete (xr_FS); - xr_delete (xr_EFS); - -#ifndef _EDITOR - if (trained_model) { - void *buffer = trained_model->buffer(); - xr_free (buffer); - xr_delete (trained_model); - } + --init_counter; + if (0 == init_counter) + { + FS._destroy(); + EFS._destroy(); + xr_delete(xr_FS); + xr_delete(xr_EFS); + +#ifndef _EDITOR + if (trained_model) + { + void* buffer = trained_model->buffer(); + xr_free(buffer); + xr_delete(trained_model); + } #endif xr_free(Params); - Memory._destroy (); - } + Memory._destroy(); + } } #ifndef XRCORE_STATIC -//. why ??? +//. why ??? #ifdef _EDITOR - BOOL WINAPI DllEntryPoint(HINSTANCE hinstDLL, DWORD ul_reason_for_call, LPVOID lpvReserved) +BOOL WINAPI DllEntryPoint(HINSTANCE hinstDLL, DWORD ul_reason_for_call, LPVOID lpvReserved) #else - BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD ul_reason_for_call, LPVOID lpvReserved) +BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD ul_reason_for_call, LPVOID lpvReserved) #endif { - switch (ul_reason_for_call) - { - case DLL_PROCESS_ATTACH: - { - _clear87 (); - _control87 ( _PC_53, MCW_PC ); - _control87 ( _RC_CHOP, MCW_RC ); - _control87 ( _RC_NEAR, MCW_RC ); - _control87 ( _MCW_EM, MCW_EM ); - } -//. LogFile.reserve (256); - break; - case DLL_THREAD_ATTACH: - if (!strstr(GetCommandLine(),"-editor")) - CoInitializeEx (NULL, COINIT_MULTITHREADED); - timeBeginPeriod (1); - break; - case DLL_THREAD_DETACH: - break; - case DLL_PROCESS_DETACH: + switch (ul_reason_for_call) + { + case DLL_PROCESS_ATTACH: + { + _clear87(); + _control87(_PC_53, MCW_PC); + _control87(_RC_CHOP, MCW_RC); + _control87(_RC_NEAR, MCW_RC); + _control87(_MCW_EM, MCW_EM); + } + //. LogFile.reserve (256); + break; + case DLL_THREAD_ATTACH: + if (!strstr(GetCommandLine(), "-editor")) + CoInitializeEx(NULL, COINIT_MULTITHREADED); + timeBeginPeriod(1); + break; + case DLL_THREAD_DETACH: + break; + case DLL_PROCESS_DETACH: #ifdef USE_MEMORY_MONITOR - memory_monitor::flush_each_time (true); + memory_monitor::flush_each_time(true); #endif // USE_MEMORY_MONITOR - break; - } + break; + } return TRUE; } #endif // XRCORE_STATIC \ No newline at end of file diff --git a/src/xrCore/xrCore.h b/src/xrCore/xrCore.h index efdbc3f9bc5..1039cdcdf4c 100644 --- a/src/xrCore/xrCore.h +++ b/src/xrCore/xrCore.h @@ -3,74 +3,74 @@ #pragma once #ifndef DEBUG -# define MASTER_GOLD +# define MASTER_GOLD #endif // DEBUG //#define BENCHMARK_BUILD -#ifdef BENCHMARK_BUILD -# define BENCH_SEC_CALLCONV __stdcall -# define BENCH_SEC_SCRAMBLEVTBL1 virtual int GetFlags() { return 1;} -# define BENCH_SEC_SCRAMBLEVTBL2 virtual void* GetData() { return 0;} -# define BENCH_SEC_SCRAMBLEVTBL3 virtual void* GetCache(){ return 0;} -# define BENCH_SEC_SIGN , void *pBenchScrampleVoid = 0 -# define BENCH_SEC_SCRAMBLEMEMBER1 float m_fSrambleMember1; -# define BENCH_SEC_SCRAMBLEMEMBER2 float m_fSrambleMember2; -#else // BENCHMARK_BUILD -# define BENCH_SEC_CALLCONV -# define BENCH_SEC_SCRAMBLEVTBL1 -# define BENCH_SEC_SCRAMBLEVTBL2 -# define BENCH_SEC_SCRAMBLEVTBL3 -# define BENCH_SEC_SIGN -# define BENCH_SEC_SCRAMBLEMEMBER1 -# define BENCH_SEC_SCRAMBLEMEMBER2 -#endif // BENCHMARK_BUILD +#ifdef BENCHMARK_BUILD +# define BENCH_SEC_CALLCONV __stdcall +# define BENCH_SEC_SCRAMBLEVTBL1 virtual int GetFlags() { return 1;} +# define BENCH_SEC_SCRAMBLEVTBL2 virtual void* GetData() { return 0;} +# define BENCH_SEC_SCRAMBLEVTBL3 virtual void* GetCache(){ return 0;} +# define BENCH_SEC_SIGN , void *pBenchScrampleVoid = 0 +# define BENCH_SEC_SCRAMBLEMEMBER1 float m_fSrambleMember1; +# define BENCH_SEC_SCRAMBLEMEMBER2 float m_fSrambleMember2; +#else // BENCHMARK_BUILD +# define BENCH_SEC_CALLCONV +# define BENCH_SEC_SCRAMBLEVTBL1 +# define BENCH_SEC_SCRAMBLEVTBL2 +# define BENCH_SEC_SCRAMBLEVTBL3 +# define BENCH_SEC_SIGN +# define BENCH_SEC_SCRAMBLEMEMBER1 +# define BENCH_SEC_SCRAMBLEMEMBER2 +#endif // BENCHMARK_BUILD #pragma warning(disable:4996) #if (defined(_DEBUG) || defined(MIXED) || defined(DEBUG)) && !defined(FORCE_NO_EXCEPTIONS) - // "debug" or "mixed" - #if !defined(_CPPUNWIND) - #error Please enable exceptions... - #endif - #define _HAS_EXCEPTIONS 1 // STL - #define XRAY_EXCEPTIONS 1 // XRAY +// "debug" or "mixed" +#if !defined(_CPPUNWIND) +#error Please enable exceptions... +#endif +#define _HAS_EXCEPTIONS 1 // STL +#define XRAY_EXCEPTIONS 1 // XRAY #else - // "release" - #if defined(_CPPUNWIND) && !defined __BORLANDC__ - #error Please disable exceptions... - #endif - #define _HAS_EXCEPTIONS 1 // STL - #define XRAY_EXCEPTIONS 0 // XRAY - #define LUABIND_NO_EXCEPTIONS - #pragma warning(disable:4530) +// "release" +#if defined(_CPPUNWIND) && !defined __BORLANDC__ +#error Please disable exceptions... +#endif +#define _HAS_EXCEPTIONS 1 // STL +#define XRAY_EXCEPTIONS 0 // XRAY +#define LUABIND_NO_EXCEPTIONS +#pragma warning(disable:4530) #endif #if !defined(_MT) - // multithreading disabled - #error Please enable multi-threaded library... +// multithreading disabled +#error Please enable multi-threaded library... #endif -# include "xrCore_platform.h" +# include "xrCore_platform.h" /* // stl-config // *** disable exceptions for both STLport and VC7.1 STL -// #define _STLP_NO_EXCEPTIONS 1 +// #define _STLP_NO_EXCEPTIONS 1 // #if XRAY_EXCEPTIONS - #define _HAS_EXCEPTIONS 1 // force STL again +#define _HAS_EXCEPTIONS 1 // force STL again // #endif */ // *** try to minimize code bloat of STLport #ifdef __BORLANDC__ #else - #ifdef XRCORE_EXPORTS // no exceptions, export allocator and common stuff - #define _STLP_DESIGNATED_DLL 1 - #define _STLP_USE_DECLSPEC 1 - #else - #define _STLP_USE_DECLSPEC 1 // no exceptions, import allocator and common stuff - #endif +#ifdef XRCORE_EXPORTS // no exceptions, export allocator and common stuff +#define _STLP_DESIGNATED_DLL 1 +#define _STLP_USE_DECLSPEC 1 +#else +#define _STLP_USE_DECLSPEC 1 // no exceptions, import allocator and common stuff +#endif #endif // #include @@ -85,100 +85,100 @@ //#include #ifndef DEBUG - #ifdef _DEBUG - #define DEBUG - #endif - #ifdef MIXED - #define DEBUG - #endif +#ifdef _DEBUG +#define DEBUG +#endif +#ifdef MIXED +#define DEBUG +#endif #endif #ifdef XRCORE_STATIC -# define NO_FS_SCAN +# define NO_FS_SCAN #endif #ifdef _EDITOR -# define NO_FS_SCAN +# define NO_FS_SCAN #endif // inline control - redefine to use compiler's heuristics ONLY // it seems "IC" is misused in many places which cause code-bloat // ...and VC7.1 really don't miss opportunities for inline :) #ifdef _EDITOR -# define __forceinline inline +# define __forceinline inline #endif -#define _inline inline -#define __inline inline -#define IC inline -#define ICF __forceinline // !!! this should be used only in critical places found by PROFILER +#define _inline inline +#define __inline inline +#define IC inline +#define ICF __forceinline // !!! this should be used only in critical places found by PROFILER #ifdef _EDITOR -# define ICN +# define ICN #else -# define ICN __declspec (noinline) +# define ICN __declspec (noinline) #endif #ifndef DEBUG - #pragma inline_depth ( 254 ) - #pragma inline_recursion( on ) - #ifndef __BORLANDC__ - #pragma intrinsic (abs, fabs, fmod, sin, cos, tan, asin, acos, atan, sqrt, exp, log, log10, strcat) - #endif +#pragma inline_depth ( 254 ) +#pragma inline_recursion( on ) +#ifndef __BORLANDC__ +#pragma intrinsic (abs, fabs, fmod, sin, cos, tan, asin, acos, atan, sqrt, exp, log, log10, strcat) +#endif #endif #include // work-around dumb borland compiler #ifdef __BORLANDC__ - #define ALIGN(a) - - #include - #include - #define _utimbuf utimbuf - #define MODULE_NAME "xrCoreB.dll" - - // function redefinition - #define fabsf(a) fabs(a) - #define sinf(a) sin(a) - #define asinf(a) asin(a) - #define cosf(a) cos(a) - #define acosf(a) acos(a) - #define tanf(a) tan(a) - #define atanf(a) atan(a) - #define sqrtf(a) sqrt(a) - #define expf(a) ::exp(a) - #define floorf floor - #define atan2f atan2 - #define logf log - // float redefine - #define _PC_24 PC_24 - #define _PC_53 PC_53 - #define _PC_64 PC_64 - #define _RC_CHOP RC_CHOP - #define _RC_NEAR RC_NEAR - #define _MCW_EM MCW_EM +#define ALIGN(a) + +#include +#include +#define _utimbuf utimbuf +#define MODULE_NAME "xrCoreB.dll" + +// function redefinition +#define fabsf(a) fabs(a) +#define sinf(a) sin(a) +#define asinf(a) asin(a) +#define cosf(a) cos(a) +#define acosf(a) acos(a) +#define tanf(a) tan(a) +#define atanf(a) atan(a) +#define sqrtf(a) sqrt(a) +#define expf(a) ::exp(a) +#define floorf floor +#define atan2f atan2 +#define logf log +// float redefine +#define _PC_24 PC_24 +#define _PC_53 PC_53 +#define _PC_64 PC_64 +#define _RC_CHOP RC_CHOP +#define _RC_NEAR RC_NEAR +#define _MCW_EM MCW_EM #else - #define ALIGN(a) __declspec(align(a)) - #include - #define MODULE_NAME "xrCore.dll" +#define ALIGN(a) __declspec(align(a)) +#include +#define MODULE_NAME "xrCore.dll" #endif // Warnings -#pragma warning (disable : 4251 ) // object needs DLL interface -#pragma warning (disable : 4201 ) // nonstandard extension used : nameless struct/union -#pragma warning (disable : 4100 ) // unreferenced formal parameter -#pragma warning (disable : 4127 ) // conditional expression is constant -//#pragma warning (disable : 4530 ) // C++ exception handler used, but unwind semantics are not enabled +#pragma warning (disable : 4251 ) // object needs DLL interface +#pragma warning (disable : 4201 ) // nonstandard extension used : nameless struct/union +#pragma warning (disable : 4100 ) // unreferenced formal parameter +#pragma warning (disable : 4127 ) // conditional expression is constant +//#pragma warning (disable : 4530 ) // C++ exception handler used, but unwind semantics are not enabled #pragma warning (disable : 4345 ) -#pragma warning (disable : 4714 ) // __forceinline not inlined +#pragma warning (disable : 4714 ) // __forceinline not inlined #ifndef DEBUG -#pragma warning (disable : 4189 ) // local variable is initialized but not refenced -#endif // frequently in release code due to large amount of VERIFY +#pragma warning (disable : 4189 ) // local variable is initialized but not refenced +#endif // frequently in release code due to large amount of VERIFY #ifdef _M_AMD64 #pragma warning (disable : 4512 ) #endif - + // stl #pragma warning (push) #pragma warning (disable:4702) @@ -191,23 +191,23 @@ #include #ifndef _EDITOR -# include -# include +# include +# include #endif #include #pragma warning (pop) -#pragma warning (disable : 4100 ) // unreferenced formal parameter +#pragma warning (disable : 4100 ) // unreferenced formal parameter // Our headers #ifdef XRCORE_STATIC -# define XRCORE_API +# define XRCORE_API #else -# ifdef XRCORE_EXPORTS -# define XRCORE_API __declspec(dllexport) -# else -# define XRCORE_API __declspec(dllimport) -# endif +# ifdef XRCORE_EXPORTS +# define XRCORE_API __declspec(dllexport) +# else +# define XRCORE_API __declspec(dllimport) +# endif #endif #include "xrDebug.h" @@ -227,49 +227,54 @@ #include "string_concatenations.h" // stl ext -struct XRCORE_API xr_rtoken{ - shared_str name; - int id; - xr_rtoken (LPCSTR _nm, int _id){name=_nm;id=_id;} +struct XRCORE_API xr_rtoken +{ + shared_str name; + int id; + xr_rtoken(LPCSTR _nm, int _id) { name = _nm; id = _id; } public: - void rename (LPCSTR _nm) {name=_nm;} - bool equal (LPCSTR _nm) {return (0==xr_strcmp(*name,_nm));} + void rename(LPCSTR _nm) { name = _nm; } + bool equal(LPCSTR _nm) { return (0 == xr_strcmp(*name, _nm)); } }; #pragma pack (push,1) -struct XRCORE_API xr_shortcut{ - enum{ - flShift = 0x20, - flCtrl = 0x40, - flAlt = 0x80, +struct XRCORE_API xr_shortcut +{ + enum + { + flShift = 0x20, + flCtrl = 0x40, + flAlt = 0x80, }; - union{ - struct{ - u8 key; - Flags8 ext; + union + { + struct + { + u8 key; + Flags8 ext; }; - u16 hotkey; + u16 hotkey; }; - xr_shortcut (u8 k, BOOL a, BOOL c, BOOL s):key(k){ext.assign(u8((a?flAlt:0)|(c?flCtrl:0)|(s?flShift:0)));} - xr_shortcut (){ext.zero();key=0;} - bool similar (const xr_shortcut& v)const{return ext.equal(v.ext)&&(key==v.key);} + xr_shortcut(u8 k, BOOL a, BOOL c, BOOL s) :key(k) { ext.assign(u8((a ? flAlt : 0) | (c ? flCtrl : 0) | (s ? flShift : 0))); } + xr_shortcut() { ext.zero(); key = 0; } + bool similar(const xr_shortcut& v)const { return ext.equal(v.ext) && (key == v.key); } }; #pragma pack (pop) -DEFINE_VECTOR (shared_str,RStringVec,RStringVecIt); -DEFINE_SET (shared_str,RStringSet,RStringSetIt); -DEFINE_VECTOR (xr_rtoken,RTokenVec,RTokenVecIt); +DEFINE_VECTOR(shared_str, RStringVec, RStringVecIt); +DEFINE_SET(shared_str, RStringSet, RStringSetIt); +DEFINE_VECTOR(xr_rtoken, RTokenVec, RTokenVecIt); -#define xr_pure_interface __interface +#define xr_pure_interface __interface #include "FS.h" #include "log.h" #include "xr_trims.h" #include "xr_ini.h" #ifdef NO_FS_SCAN -# include "ELocatorAPI.h" +# include "ELocatorAPI.h" #else -# include "LocatorAPI.h" +# include "LocatorAPI.h" #endif #include "FileSystem.h" #include "FTimer.h" @@ -282,36 +287,38 @@ DEFINE_VECTOR (xr_rtoken,RTokenVec,RTokenVecIt); template class destructor { - T* ptr; + T* ptr; public: - destructor(T* p) { ptr=p; } - ~destructor() { xr_delete(ptr); } - IC T& operator() () - { return *ptr; } + destructor(T* p) { ptr = p; } + ~destructor() { xr_delete(ptr); } + IC T& operator() () + { + return *ptr; + } }; // ********************************************** The Core definition -class XRCORE_API xrCore +class XRCORE_API xrCore { public: - string64 ApplicationName; - string_path ApplicationPath; - string_path WorkingPath; - string64 UserName; - string64 CompName; + string64 ApplicationName; + string_path ApplicationPath; + string_path WorkingPath; + string64 UserName; + string64 CompName; char* Params; - DWORD dwFrame; + DWORD dwFrame; public: - void _initialize (LPCSTR ApplicationName, LogCallback cb=0, BOOL init_fs=TRUE, LPCSTR fs_fname=0); - void _destroy (); + void _initialize(LPCSTR ApplicationName, LogCallback cb = 0, BOOL init_fs = TRUE, LPCSTR fs_fname = 0); + void _destroy(); }; //Borland class dll interface -#define _BCL __stdcall +#define _BCL __stdcall //Borland global function dll interface -#define _BGCL __stdcall +#define _BGCL __stdcall extern XRCORE_API xrCore Core; diff --git a/src/xrCore/xrCore_platform.h b/src/xrCore/xrCore_platform.h index f54c96cab68..eb015f52488 100644 --- a/src/xrCore/xrCore_platform.h +++ b/src/xrCore/xrCore_platform.h @@ -2,24 +2,24 @@ #define XRCORE_PLATFORM_H #pragma once -#define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers -#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers +#define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers +#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers #ifndef STRICT -# define STRICT // Enable strict syntax +# define STRICT // Enable strict syntax #endif // STRICT -#define IDIRECTPLAY2_OR_GREATER // ? -#define DIRECTINPUT_VERSION 0x0800 // -#define _CRT_SECURE_NO_DEPRECATE // vc8.0 stuff, don't deprecate several ANSI functions +#define IDIRECTPLAY2_OR_GREATER // ? +#define DIRECTINPUT_VERSION 0x0800 // +#define _CRT_SECURE_NO_DEPRECATE // vc8.0 stuff, don't deprecate several ANSI functions // windows.h #ifndef _WIN32_WINNT -# define _WIN32_WINNT 0x0501 +# define _WIN32_WINNT 0x0501 #endif #ifdef __BORLANDC__ - #include - #include - #include +#include +#include +#include #endif #define NOGDICAPMASKS @@ -43,7 +43,7 @@ #pragma warning(disable:4005) #include #ifndef __BORLANDC__ - #include +#include #endif #pragma warning(pop) diff --git a/src/xrCore/xrDebug.cpp b/src/xrCore/xrDebug.cpp index 2f39ec212f1..1fb14f995de 100644 --- a/src/xrCore/xrDebug.cpp +++ b/src/xrCore/xrDebug.cpp @@ -6,344 +6,350 @@ #include "xrdebug.h" #include "resource.h" #include "dbghelp.h" - + #include "dxerr.h" #ifdef __BORLANDC__ - #include "d3d9.h" - #include "d3dx9.h" - #include "D3DX_Wrapper.h" - #pragma comment (lib,"EToolsB.lib") - static BOOL bException = TRUE; +#include "d3d9.h" +#include "d3dx9.h" +#include "D3DX_Wrapper.h" +#pragma comment (lib,"EToolsB.lib") +static BOOL bException = TRUE; #else - static BOOL bException = FALSE; +static BOOL bException = FALSE; #endif #ifdef _M_AMD64 -#define DEBUG_INVOKE DebugBreak () +#define DEBUG_INVOKE DebugBreak () #else -#define DEBUG_INVOKE __asm { int 3 } +#define DEBUG_INVOKE __asm { int 3 } #ifndef __BORLANDC__ - #pragma comment (lib,"dxerr.lib") +#pragma comment (lib,"dxerr.lib") #endif #endif -XRCORE_API xrDebug Debug; +XRCORE_API xrDebug Debug; // Dialog support -static const char * dlgExpr = NULL; -static const char * dlgFile = NULL; -static char dlgLine [16]; +static const char* dlgExpr = NULL; +static const char* dlgFile = NULL; +static char dlgLine[16]; -static INT_PTR CALLBACK DialogProc ( HWND hw, UINT msg, WPARAM wp, LPARAM lp ) +static INT_PTR CALLBACK DialogProc(HWND hw, UINT msg, WPARAM wp, LPARAM lp) { - switch( msg ){ - case WM_INITDIALOG: - { - if (dlgFile) - { - SetWindowText(GetDlgItem(hw,IDC_DESC),dlgExpr); - SetWindowText(GetDlgItem(hw,IDC_FILE),dlgFile); - SetWindowText(GetDlgItem(hw,IDC_LINE),dlgLine); - } else { - SetWindowText(GetDlgItem(hw,IDC_DESC),dlgExpr); - SetWindowText(GetDlgItem(hw,IDC_FILE),""); - SetWindowText(GetDlgItem(hw,IDC_LINE),""); - } - } - break; - case WM_DESTROY: - break; - case WM_CLOSE: - EndDialog (hw, IDC_STOP); - break; - case WM_COMMAND: - if( LOWORD(wp)==IDC_STOP ) { - EndDialog(hw, IDC_STOP); - } - if( LOWORD(wp)==IDC_DEBUG) { - EndDialog(hw, IDC_DEBUG); - } - break; - default: - return FALSE; - } - return TRUE; + switch (msg) + { + case WM_INITDIALOG: + { + if (dlgFile) + { + SetWindowText(GetDlgItem(hw, IDC_DESC), dlgExpr); + SetWindowText(GetDlgItem(hw, IDC_FILE), dlgFile); + SetWindowText(GetDlgItem(hw, IDC_LINE), dlgLine); + } + else + { + SetWindowText(GetDlgItem(hw, IDC_DESC), dlgExpr); + SetWindowText(GetDlgItem(hw, IDC_FILE), ""); + SetWindowText(GetDlgItem(hw, IDC_LINE), ""); + } + } + break; + case WM_DESTROY: + break; + case WM_CLOSE: + EndDialog(hw, IDC_STOP); + break; + case WM_COMMAND: + if (LOWORD(wp) == IDC_STOP) + { + EndDialog(hw, IDC_STOP); + } + if (LOWORD(wp) == IDC_DEBUG) + { + EndDialog(hw, IDC_DEBUG); + } + break; + default: + return FALSE; + } + return TRUE; } -void xrDebug::backend(const char* reason, const char* expression, const char *argument0, const char *argument1, const char* file, int line, const char *function, bool &ignore_always) +void xrDebug::backend(const char* reason, const char* expression, const char* argument0, const char* argument1, const char* file, int line, const char* function, bool& ignore_always) { - static xrCriticalSection CS; - - CS.Enter (); - - // Log - string1024 tmp; - xr_sprintf (tmp,"***STOP*** file '%s', line %d.\n***Reason***: %s\n %s",file,line,reason,expression); - Msg (tmp); - FlushLog (); - if (handler) handler (); - - // Call the dialog - dlgExpr = reason; - xr_sprintf () - dlgFile = file; - xr_sprintf (dlgLine,"%d",line); - INT_PTR res = -1; + static xrCriticalSection CS; + + CS.Enter(); + + // Log + string1024 tmp; + xr_sprintf(tmp, "***STOP*** file '%s', line %d.\n***Reason***: %s\n %s", file, line, reason, expression); + Msg(tmp); + FlushLog(); + if (handler) handler(); + + // Call the dialog + dlgExpr = reason; + xr_sprintf() + dlgFile = file; + xr_sprintf(dlgLine, "%d", line); + INT_PTR res = -1; #ifdef XRCORE_STATIC - MessageBox (NULL,tmp,"X-Ray error",MB_OK|MB_ICONERROR|MB_SYSTEMMODAL); + MessageBox(NULL, tmp, "X-Ray error", MB_OK | MB_ICONERROR | MB_SYSTEMMODAL); #else - res = DialogBox - ( - GetModuleHandle(MODULE_NAME), - MAKEINTRESOURCE(IDD_STOP), - NULL, - DialogProc - ); + res = DialogBox + ( + GetModuleHandle(MODULE_NAME), + MAKEINTRESOURCE(IDD_STOP), + NULL, + DialogProc + ); #endif - switch (res) - { - case -1: - case IDC_STOP: - if (bException) TerminateProcess(GetCurrentProcess(),3); - else RaiseException (0, 0, 0, NULL); - break; - case IDC_DEBUG: - DEBUG_INVOKE; - break; - } - - CS.Leave (); + switch (res) + { + case -1: + case IDC_STOP: + if (bException) TerminateProcess(GetCurrentProcess(), 3); + else RaiseException(0, 0, 0, NULL); + break; + case IDC_DEBUG: + DEBUG_INVOKE; + break; + } + + CS.Leave(); } -LPCSTR xrDebug::error2string (long code) +LPCSTR xrDebug::error2string(long code) { - LPCSTR result = 0; - static string1024 desc_storage; + LPCSTR result = 0; + static string1024 desc_storage; #ifdef _M_AMD64 #else - result = DXGetErrorDescription (code); + result = DXGetErrorDescription(code); #endif - if (0==result) - { - FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM,0,code,0,desc_storage,sizeof(desc_storage)-1,0); - result = desc_storage; - } - return result ; + if (0 == result) + { + FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, 0, code, 0, desc_storage, sizeof(desc_storage) - 1, 0); + result = desc_storage; + } + return result; } -void xrDebug::error (long hr, const char* expr, const char *file, int line, const char *function, bool &ignore_always) +void xrDebug::error(long hr, const char* expr, const char* file, int line, const char* function, bool& ignore_always) { - backend (error2string(hr),expr,0,0,file,line,function,ignore_always); + backend(error2string(hr), expr, 0, 0, file, line, function, ignore_always); } -void xrDebug::error (long hr, const char* expr, const char *e2, const char *file, int line, const char *function, bool &ignore_always) +void xrDebug::error(long hr, const char* expr, const char* e2, const char* file, int line, const char* function, bool& ignore_always) { - backend (error2string(hr),expr,e2,0,file,line,function,ignore_always); + backend(error2string(hr), expr, e2, 0, file, line, function, ignore_always); } -void xrDebug::fail (const char *e1, const char *file, int line, const char *function, bool &ignore_always) +void xrDebug::fail(const char* e1, const char* file, int line, const char* function, bool& ignore_always) { - backend ("assertion failed",e1,0,0,file,line,function,ignore_always); + backend("assertion failed", e1, 0, 0, file, line, function, ignore_always); } -void xrDebug::fail (const char *e1, const char *e2, const char *file, int line, const char *function, bool &ignore_always) +void xrDebug::fail(const char* e1, const char* e2, const char* file, int line, const char* function, bool& ignore_always) { - backend (e1,e2,0,0,file,line,function,ignore_always); + backend(e1, e2, 0, 0, file, line, function, ignore_always); } -void xrDebug::fail (const char *e1, const char *e2, const char *e3, const char *file, int line, const char *function, bool &ignore_always) +void xrDebug::fail(const char* e1, const char* e2, const char* e3, const char* file, int line, const char* function, bool& ignore_always) { - backend (e1,e2,e3,0,file,line,function,ignore_always); + backend(e1, e2, e3, 0, file, line, function, ignore_always); } -void xrDebug::fail (const char *e1, const char *e2, const char *e3, const char *e4, const char *file, int line, const char *function, bool &ignore_always) +void xrDebug::fail(const char* e1, const char* e2, const char* e3, const char* e4, const char* file, int line, const char* function, bool& ignore_always) { - backend (e1,e2,e3,e4,file,line,function,ignore_always); + backend(e1, e2, e3, e4, file, line, function, ignore_always); } -void __cdecl xrDebug::fatal(const char *file, int line, const char *function, const char* F,...) +void __cdecl xrDebug::fatal(const char* file, int line, const char* function, const char* F, ...) { - string1024 buffer; + string1024 buffer; - va_list p; - va_start (p,F); - vsprintf (buffer,F,p); - va_end (p); + va_list p; + va_start(p, F); + vsprintf(buffer, F, p); + va_end(p); - bool ignore_always = true; + bool ignore_always = true; - backend ("fatal error","",buffer,0,file,line,function,ignore_always); + backend("fatal error", "", buffer, 0, file, line, function, ignore_always); } -void xrDebug::do_exit (const std::string &message) +void xrDebug::do_exit(const std::string& message) { - FlushLog (); - MessageBox (NULL,message.c_str(),"Error",MB_OK|MB_ICONERROR|MB_SYSTEMMODAL); - TerminateProcess (GetCurrentProcess(),1); + FlushLog(); + MessageBox(NULL, message.c_str(), "Error", MB_OK | MB_ICONERROR | MB_SYSTEMMODAL); + TerminateProcess(GetCurrentProcess(), 1); } -int __cdecl _out_of_memory (size_t size) +int __cdecl _out_of_memory(size_t size) { - Debug.fatal (DEBUG_INFO,"Out of memory. Memory request: %d K",size/1024); - return 1; + Debug.fatal(DEBUG_INFO, "Out of memory. Memory request: %d K", size / 1024); + return 1; } -void __cdecl _terminate () +void __cdecl _terminate() { - FATAL ("Unexpected application termination"); + FATAL("Unexpected application termination"); } // based on dbghelp.h -typedef BOOL (WINAPI *MINIDUMPWRITEDUMP)(HANDLE hProcess, DWORD dwPid, HANDLE hFile, MINIDUMP_TYPE DumpType, - CONST PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam, - CONST PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam, - CONST PMINIDUMP_CALLBACK_INFORMATION CallbackParam - ); +typedef BOOL(WINAPI* MINIDUMPWRITEDUMP)(HANDLE hProcess, DWORD dwPid, HANDLE hFile, MINIDUMP_TYPE DumpType, + CONST PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam, + CONST PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam, + CONST PMINIDUMP_CALLBACK_INFORMATION CallbackParam + ); -LONG WINAPI UnhandledFilter ( struct _EXCEPTION_POINTERS *pExceptionInfo ) +LONG WINAPI UnhandledFilter(struct _EXCEPTION_POINTERS* pExceptionInfo) { - LONG retval = EXCEPTION_CONTINUE_SEARCH; - bException = TRUE; - - // firstly see if dbghelp.dll is around and has the function we need - // look next to the EXE first, as the one in System32 might be old - // (e.g. Windows 2000) - HMODULE hDll = NULL; - string_path szDbgHelpPath; - - if (GetModuleFileName( NULL, szDbgHelpPath, _MAX_PATH )) - { - char *pSlash = strchr( szDbgHelpPath, '\\' ); - if (pSlash) - { - xr_strcpy (pSlash+1, "DBGHELP.DLL" ); - hDll = ::LoadLibrary( szDbgHelpPath ); - } - } - - if (hDll==NULL) - { - // load any version we can - hDll = ::LoadLibrary( "DBGHELP.DLL" ); - } - - LPCTSTR szResult = NULL; - - if (hDll) - { - MINIDUMPWRITEDUMP pDump = (MINIDUMPWRITEDUMP)::GetProcAddress( hDll, "MiniDumpWriteDump" ); - if (pDump) - { - string_path szDumpPath; - string_path szScratch; - string64 t_stemp; - - // work out a good place for the dump file - timestamp (t_stemp); - xr_strcpy ( szDumpPath, "logs\\" ); - xr_strcat ( szDumpPath, Core.ApplicationName ); - xr_strcat ( szDumpPath, "_" ); - xr_strcat ( szDumpPath, Core.UserName ); - xr_strcat ( szDumpPath, "_" ); - xr_strcat ( szDumpPath, t_stemp ); - xr_strcat ( szDumpPath, ".mdmp" ); - - // create the file - HANDLE hFile = ::CreateFile( szDumpPath, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); - if (INVALID_HANDLE_VALUE==hFile) - { - // try to place into current directory - MoveMemory (szDumpPath,szDumpPath+5,strlen(szDumpPath)); - hFile = ::CreateFile( szDumpPath, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); - } - if (hFile!=INVALID_HANDLE_VALUE) - { - _MINIDUMP_EXCEPTION_INFORMATION ExInfo; - - ExInfo.ThreadId = ::GetCurrentThreadId(); - ExInfo.ExceptionPointers = pExceptionInfo; - ExInfo.ClientPointers = NULL; - - // write the dump - MINIDUMP_TYPE dump_flags = MINIDUMP_TYPE(MiniDumpNormal | MiniDumpFilterMemory | MiniDumpScanMemory ); - - BOOL bOK = pDump( GetCurrentProcess(), GetCurrentProcessId(), hFile, dump_flags, &ExInfo, NULL, NULL ); - if (bOK) - { - xr_sprintf( szScratch, "Saved dump file to '%s'", szDumpPath ); - szResult = szScratch; - retval = EXCEPTION_EXECUTE_HANDLER; - } - else - { - xr_sprintf( szScratch, "Failed to save dump file to '%s' (error %d)", szDumpPath, GetLastError() ); - szResult = szScratch; - } - ::CloseHandle(hFile); - } - else - { - xr_sprintf( szScratch, "Failed to create dump file '%s' (error %d)", szDumpPath, GetLastError() ); - szResult = szScratch; - } - } - else - { - szResult = "DBGHELP.DLL too old"; - } - } - else - { - szResult = "DBGHELP.DLL not found"; - } - - string1024 reason; - xr_sprintf (reason,"*** Internal Error ***\n%s",szResult); - bool ref = false; - Debug.backend (reason,0,0,0,0,0,0,ref); - - return retval; -} + LONG retval = EXCEPTION_CONTINUE_SEARCH; + bException = TRUE; -////////////////////////////////////////////////////////////////////// -#ifdef M_BORLAND -// typedef void ( _RTLENTRY *___new_handler) (); -namespace std{ - extern new_handler _RTLENTRY _EXPFUNC set_new_handler( new_handler new_p ); -}; + // firstly see if dbghelp.dll is around and has the function we need + // look next to the EXE first, as the one in System32 might be old + // (e.g. Windows 2000) + HMODULE hDll = NULL; + string_path szDbgHelpPath; -// typedef int (__stdcall * _PNH)( size_t ); -// _CRTIMP int __cdecl _set_new_mode( int ); -// _PNH __cdecl set_new_handler( _PNH ); -// typedef void (new * new_handler)(); -// new_handler set_new_handler(new_handler my_handler); - static void __cdecl def_new_handler() + if (GetModuleFileName(NULL, szDbgHelpPath, _MAX_PATH)) { - FATAL ("Out of memory."); + char* pSlash = strchr(szDbgHelpPath, '\\'); + if (pSlash) + { + xr_strcpy(pSlash + 1, "DBGHELP.DLL"); + hDll = ::LoadLibrary(szDbgHelpPath); + } } - void xrDebug::_initialize (const bool &dedicated) + if (hDll == NULL) { -// std::set_new_mode (1); // gen exception if can't allocate memory - std::set_new_handler (def_new_handler ); // exception-handler for 'out of memory' condition - ::SetUnhandledExceptionFilter ( UnhandledFilter ); // exception handler to all "unhandled" exceptions + // load any version we can + hDll = ::LoadLibrary("DBGHELP.DLL"); } -#else - typedef int (__cdecl * _PNH)( size_t ); - _CRTIMP int __cdecl _set_new_mode( int ); - _CRTIMP _PNH __cdecl _set_new_handler( _PNH ); - void xrDebug::_initialize (const bool &dedicated) + LPCTSTR szResult = NULL; + + if (hDll) + { + MINIDUMPWRITEDUMP pDump = (MINIDUMPWRITEDUMP)::GetProcAddress(hDll, "MiniDumpWriteDump"); + if (pDump) + { + string_path szDumpPath; + string_path szScratch; + string64 t_stemp; + + // work out a good place for the dump file + timestamp(t_stemp); + xr_strcpy(szDumpPath, "logs\\"); + xr_strcat(szDumpPath, Core.ApplicationName); + xr_strcat(szDumpPath, "_"); + xr_strcat(szDumpPath, Core.UserName); + xr_strcat(szDumpPath, "_"); + xr_strcat(szDumpPath, t_stemp); + xr_strcat(szDumpPath, ".mdmp"); + + // create the file + HANDLE hFile = ::CreateFile(szDumpPath, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + if (INVALID_HANDLE_VALUE == hFile) + { + // try to place into current directory + MoveMemory(szDumpPath, szDumpPath + 5, strlen(szDumpPath)); + hFile = ::CreateFile(szDumpPath, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + } + if (hFile != INVALID_HANDLE_VALUE) + { + _MINIDUMP_EXCEPTION_INFORMATION ExInfo; + + ExInfo.ThreadId = ::GetCurrentThreadId(); + ExInfo.ExceptionPointers = pExceptionInfo; + ExInfo.ClientPointers = NULL; + + // write the dump + MINIDUMP_TYPE dump_flags = MINIDUMP_TYPE(MiniDumpNormal | MiniDumpFilterMemory | MiniDumpScanMemory); + + BOOL bOK = pDump(GetCurrentProcess(), GetCurrentProcessId(), hFile, dump_flags, &ExInfo, NULL, NULL); + if (bOK) + { + xr_sprintf(szScratch, "Saved dump file to '%s'", szDumpPath); + szResult = szScratch; + retval = EXCEPTION_EXECUTE_HANDLER; + } + else + { + xr_sprintf(szScratch, "Failed to save dump file to '%s' (error %d)", szDumpPath, GetLastError()); + szResult = szScratch; + } + ::CloseHandle(hFile); + } + else + { + xr_sprintf(szScratch, "Failed to create dump file '%s' (error %d)", szDumpPath, GetLastError()); + szResult = szScratch; + } + } + else + { + szResult = "DBGHELP.DLL too old"; + } + } + else { - handler = 0; - _set_new_mode (1); // gen exception if can't allocate memory - _set_new_handler (_out_of_memory ); // exception-handler for 'out of memory' condition - std::set_terminate (_terminate); - std::set_unexpected (_terminate); - ::SetUnhandledExceptionFilter ( UnhandledFilter ); // exception handler to all "unhandled" exceptions + szResult = "DBGHELP.DLL not found"; } + string1024 reason; + xr_sprintf(reason, "*** Internal Error ***\n%s", szResult); + bool ref = false; + Debug.backend(reason, 0, 0, 0, 0, 0, 0, ref); + + return retval; +} + +////////////////////////////////////////////////////////////////////// +#ifdef M_BORLAND +// typedef void ( _RTLENTRY *___new_handler) (); +namespace std +{ +extern new_handler _RTLENTRY _EXPFUNC set_new_handler(new_handler new_p); +}; + +// typedef int (__stdcall * _PNH)( size_t ); +// _CRTIMP int __cdecl _set_new_mode( int ); +// _PNH __cdecl set_new_handler( _PNH ); +// typedef void (new * new_handler)(); +// new_handler set_new_handler(new_handler my_handler); +static void __cdecl def_new_handler() +{ + FATAL("Out of memory."); +} + +void xrDebug::_initialize(const bool& dedicated) +{ + // std::set_new_mode (1); // gen exception if can't allocate memory + std::set_new_handler(def_new_handler); // exception-handler for 'out of memory' condition + ::SetUnhandledExceptionFilter(UnhandledFilter); // exception handler to all "unhandled" exceptions +} +#else +typedef int(__cdecl* _PNH)(size_t); +_CRTIMP int __cdecl _set_new_mode(int); +_CRTIMP _PNH __cdecl _set_new_handler(_PNH); + +void xrDebug::_initialize(const bool& dedicated) +{ + handler = 0; + _set_new_mode(1); // gen exception if can't allocate memory + _set_new_handler(_out_of_memory); // exception-handler for 'out of memory' condition + std::set_terminate(_terminate); + std::set_unexpected(_terminate); + ::SetUnhandledExceptionFilter(UnhandledFilter); // exception handler to all "unhandled" exceptions +} + #endif #endif diff --git a/src/xrCore/xrDebug.h b/src/xrCore/xrDebug.h index 7079e8ec95b..c88d326fef0 100644 --- a/src/xrCore/xrDebug.h +++ b/src/xrCore/xrDebug.h @@ -2,63 +2,63 @@ #define xrDebugH #pragma once -typedef void crashhandler (void); -typedef void on_dialog (bool before); +typedef void crashhandler(void); +typedef void on_dialog(bool before); -class XRCORE_API xrDebug +class XRCORE_API xrDebug { private: - crashhandler* handler ; - on_dialog* m_on_dialog; + crashhandler* handler; + on_dialog* m_on_dialog; public: - void _initialize (const bool &dedicated); - void _destroy (); - + void _initialize(const bool& dedicated); + void _destroy(); + public: - crashhandler* get_crashhandler () { return handler; }; - void set_crashhandler (crashhandler* _handler) { handler=_handler; }; + crashhandler* get_crashhandler() { return handler; }; + void set_crashhandler(crashhandler* _handler) { handler = _handler; }; - on_dialog* get_on_dialog () { return m_on_dialog; } - void set_on_dialog (on_dialog* on_dialog) { m_on_dialog = on_dialog; } + on_dialog* get_on_dialog() { return m_on_dialog; } + void set_on_dialog(on_dialog* on_dialog) { m_on_dialog = on_dialog; } - LPCSTR error2string (long code ); + LPCSTR error2string(long code); - void gather_info (const char *expression, const char *description, const char *argument0, const char *argument1, const char *file, int line, const char *function, LPSTR assertion_info, unsigned int assertion_info_size); - template - inline void gather_info (const char *expression, const char *description, const char *argument0, const char *argument1, const char *file, int line, const char *function, char (&assertion_info)[count]) - { - gather_info ( expression, description, argument0, argument1, file, line, function, assertion_info, count); - } + void gather_info(const char* expression, const char* description, const char* argument0, const char* argument1, const char* file, int line, const char* function, LPSTR assertion_info, unsigned int assertion_info_size); + template + inline void gather_info(const char* expression, const char* description, const char* argument0, const char* argument1, const char* file, int line, const char* function, char(&assertion_info)[count]) + { + gather_info(expression, description, argument0, argument1, file, line, function, assertion_info, count); + } - void fail (const char *e1, const char *file, int line, const char *function, bool &ignore_always); - void fail (const char *e1, const std::string &e2, const char *file, int line, const char *function, bool &ignore_always); - void fail (const char *e1, const char *e2, const char *file, int line, const char *function, bool &ignore_always); - void fail (const char *e1, const char *e2, const char *e3, const char *file, int line, const char *function, bool &ignore_always); - void fail (const char *e1, const char *e2, const char *e3, const char *e4, const char *file, int line, const char *function, bool &ignore_always); - void error (long code, const char* e1, const char *file, int line, const char *function, bool &ignore_always); - void error (long code, const char* e1, const char* e2, const char *file, int line, const char *function, bool &ignore_always); - void _cdecl fatal (const char *file, int line, const char *function, const char* F,...); - void backend (const char* reason, const char* expression, const char *argument0, const char *argument1, const char* file, int line, const char *function, bool &ignore_always); - void do_exit (const std::string &message); + void fail(const char* e1, const char* file, int line, const char* function, bool& ignore_always); + void fail(const char* e1, const std::string& e2, const char* file, int line, const char* function, bool& ignore_always); + void fail(const char* e1, const char* e2, const char* file, int line, const char* function, bool& ignore_always); + void fail(const char* e1, const char* e2, const char* e3, const char* file, int line, const char* function, bool& ignore_always); + void fail(const char* e1, const char* e2, const char* e3, const char* e4, const char* file, int line, const char* function, bool& ignore_always); + void error(long code, const char* e1, const char* file, int line, const char* function, bool& ignore_always); + void error(long code, const char* e1, const char* e2, const char* file, int line, const char* function, bool& ignore_always); + void _cdecl fatal(const char* file, int line, const char* function, const char* F, ...); + void backend(const char* reason, const char* expression, const char* argument0, const char* argument1, const char* file, int line, const char* function, bool& ignore_always); + void do_exit(const std::string& message); }; // warning // this function can be used for debug purposes only -IC std::string __cdecl make_string (LPCSTR format,...) +IC std::string __cdecl make_string(LPCSTR format, ...) { - va_list args; - va_start (args,format); + va_list args; + va_start(args, format); - char temp[4096]; - vsprintf (temp,format,args); + char temp[4096]; + vsprintf(temp, format, args); - return std::string(temp); + return std::string(temp); } -extern XRCORE_API xrDebug Debug; +extern XRCORE_API xrDebug Debug; -XRCORE_API void LogStackTrace (LPCSTR header); +XRCORE_API void LogStackTrace(LPCSTR header); #include "xrDebug_macros.h" diff --git a/src/xrCore/xrDebugNew.cpp b/src/xrCore/xrDebugNew.cpp index 125f1dec5a8..580ac517788 100644 --- a/src/xrCore/xrDebugNew.cpp +++ b/src/xrCore/xrDebugNew.cpp @@ -16,904 +16,937 @@ extern bool shared_str_initialized; #ifdef __BORLANDC__ - # include "d3d9.h" - # include "d3dx9.h" - # include "D3DX_Wrapper.h" - # pragma comment(lib,"EToolsB.lib") - # define DEBUG_INVOKE DebugBreak() - static BOOL bException = TRUE; - # define USE_BUG_TRAP +# include "d3d9.h" +# include "d3dx9.h" +# include "D3DX_Wrapper.h" +# pragma comment(lib,"EToolsB.lib") +# define DEBUG_INVOKE DebugBreak() +static BOOL bException = TRUE; +# define USE_BUG_TRAP #else - # define USE_BUG_TRAP - # define DEBUG_INVOKE __asm int 3 - static BOOL bException = FALSE; +# define USE_BUG_TRAP +# define DEBUG_INVOKE __asm int 3 +static BOOL bException = FALSE; #endif #ifndef USE_BUG_TRAP -# include +# include #endif #ifndef _M_AMD64 -# ifndef __BORLANDC__ -# pragma comment(lib,"dxerr.lib") -# endif +# ifndef __BORLANDC__ +# pragma comment(lib,"dxerr.lib") +# endif #endif -#include // MiniDump flags +#include // MiniDump flags #ifdef USE_BUG_TRAP -# include // for BugTrap functionality - #ifndef __BORLANDC__ - # pragma comment(lib,"BugTrap.lib") // Link to ANSI DLL - #else - # pragma comment(lib,"BugTrapB.lib") // Link to ANSI DLL - #endif +# include // for BugTrap functionality +#ifndef __BORLANDC__ +# pragma comment(lib,"BugTrap.lib") // Link to ANSI DLL +#else +# pragma comment(lib,"BugTrapB.lib") // Link to ANSI DLL +#endif #endif // USE_BUG_TRAP -#include // for _set_new_mode -#include // for signals +#include // for _set_new_mode +#include // for signals #ifdef DEBUG -# define USE_OWN_ERROR_MESSAGE_WINDOW +# define USE_OWN_ERROR_MESSAGE_WINDOW #else // DEBUG -# define USE_OWN_MINI_DUMP +# define USE_OWN_MINI_DUMP #endif // DEBUG -XRCORE_API xrDebug Debug; +XRCORE_API xrDebug Debug; -static bool error_after_dialog = false; +static bool error_after_dialog = false; extern void BuildStackTrace(); extern char g_stackTrace[100][4096]; -extern int g_stackTraceCount; - -void LogStackTrace (LPCSTR header) -{ - if (!shared_str_initialized) - return; - - BuildStackTrace (); - - Msg ("%s",header); - - for (int i=1; i",buffer,0,file,line,function,ignore_always); + backend("fatal error", "", buffer, 0, file, line, function, ignore_always); } -typedef void (*full_memory_stats_callback_type) ( ); +typedef void(*full_memory_stats_callback_type) (); XRCORE_API full_memory_stats_callback_type g_full_memory_stats_callback = 0; -int out_of_memory_handler (size_t size) +int out_of_memory_handler(size_t size) { - if ( g_full_memory_stats_callback ) - g_full_memory_stats_callback ( ); - else { - Memory.mem_compact (); - size_t process_heap = Memory.mem_usage(); - int eco_strings = (int)g_pStringContainer->stat_economy (); - int eco_smem = (int)g_pSharedMemoryContainer->stat_economy (); - Msg ("* [x-ray]: process heap[%u K]",process_heap/1024,process_heap/1024); - Msg ("* [x-ray]: economy: strings[%d K], smem[%d K]",eco_strings/1024,eco_smem); - } + if (g_full_memory_stats_callback) + g_full_memory_stats_callback(); + else + { + Memory.mem_compact(); + size_t process_heap = Memory.mem_usage(); + int eco_strings = (int)g_pStringContainer->stat_economy(); + int eco_smem = (int)g_pSharedMemoryContainer->stat_economy(); + Msg("* [x-ray]: process heap[%u K]", process_heap / 1024, process_heap / 1024); + Msg("* [x-ray]: economy: strings[%d K], smem[%d K]", eco_strings / 1024, eco_smem); + } - Debug.fatal (DEBUG_INFO,"Out of memory. Memory request: %d K",size/1024); - return 1; + Debug.fatal(DEBUG_INFO, "Out of memory. Memory request: %d K", size / 1024); + return 1; } extern LPCSTR log_name(); XRCORE_API string_path g_bug_report_file; -void CALLBACK PreErrorHandler (INT_PTR) +void CALLBACK PreErrorHandler(INT_PTR) { #ifdef USE_BUG_TRAP - if (!xr_FS || !FS.m_Flags.test(CLocatorAPI::flReady)) - return; - - string_path log_folder; - - __try { - FS.update_path (log_folder,"$logs$",""); - if ((log_folder[0] != '\\') && (log_folder[1] != ':')) { - string256 current_folder; - _getcwd (current_folder,sizeof(current_folder)); - - string256 relative_path; - xr_strcpy (relative_path,sizeof(relative_path),log_folder); - strconcat (sizeof(log_folder),log_folder,current_folder,"\\",relative_path); - } - } - __except(EXCEPTION_EXECUTE_HANDLER) { - xr_strcpy (log_folder,sizeof(log_folder),"logs"); - } - - string_path temp; - strconcat (sizeof(temp), temp, log_folder, log_name()); - BT_AddLogFile (temp); - - if (*g_bug_report_file) - BT_AddLogFile (g_bug_report_file); - - BT_SaveSnapshot ( 0 ); + if (!xr_FS || !FS.m_Flags.test(CLocatorAPI::flReady)) + return; + + string_path log_folder; + + __try + { + FS.update_path(log_folder, "$logs$", ""); + if ((log_folder[0] != '\\') && (log_folder[1] != ':')) + { + string256 current_folder; + _getcwd(current_folder, sizeof(current_folder)); + + string256 relative_path; + xr_strcpy(relative_path, sizeof(relative_path), log_folder); + strconcat(sizeof(log_folder), log_folder, current_folder, "\\", relative_path); + } + } + __except (EXCEPTION_EXECUTE_HANDLER) + { + xr_strcpy(log_folder, sizeof(log_folder), "logs"); + } + + string_path temp; + strconcat(sizeof(temp), temp, log_folder, log_name()); + BT_AddLogFile(temp); + + if (*g_bug_report_file) + BT_AddLogFile(g_bug_report_file); + + BT_SaveSnapshot(0); #endif // USE_BUG_TRAP } #ifdef USE_BUG_TRAP -void SetupExceptionHandler (const bool &dedicated) +void SetupExceptionHandler(const bool& dedicated) { - BT_InstallSehFilter (); + BT_InstallSehFilter(); #if 1//ndef USE_OWN_ERROR_MESSAGE_WINDOW - if (!dedicated && !strstr(GetCommandLine(),"-silent_error_mode")) - BT_SetActivityType (BTA_SHOWUI); - else - BT_SetActivityType (BTA_SAVEREPORT); + if (!dedicated && !strstr(GetCommandLine(), "-silent_error_mode")) + BT_SetActivityType(BTA_SHOWUI); + else + BT_SetActivityType(BTA_SAVEREPORT); #else // USE_OWN_ERROR_MESSAGE_WINDOW - BT_SetActivityType (BTA_SAVEREPORT); + BT_SetActivityType (BTA_SAVEREPORT); #endif // USE_OWN_ERROR_MESSAGE_WINDOW - BT_SetDialogMessage ( - BTDM_INTRO2, - "\ -This is X-Ray Engine v1.6 crash reporting client. \ -To help the development process, \ -please Submit Bug or save report and email it manually (button More...).\ -\r\nMany thanks in advance and sorry for the inconvenience." - ); - - BT_SetPreErrHandler (PreErrorHandler,0); - BT_SetAppName ("XRay Engine"); - BT_SetReportFormat (BTRF_TEXT); - BT_SetFlags (/**/BTF_DETAILEDMODE | /**BTF_EDIETMAIL | /**/BTF_ATTACHREPORT /**| BTF_LISTPROCESSES /**| BTF_SHOWADVANCEDUI /**| BTF_SCREENCAPTURE/**/); - - u32 const minidump_flags = + BT_SetDialogMessage( + BTDM_INTRO2, + "\ + This is X-Ray Engine v1.6 crash reporting client. \ + To help the development process, \ + please Submit Bug or save report and email it manually (button More...).\ + \r\nMany thanks in advance and sorry for the inconvenience." + ); + + BT_SetPreErrHandler(PreErrorHandler, 0); + BT_SetAppName("XRay Engine"); + BT_SetReportFormat(BTRF_TEXT); + BT_SetFlags(/**/BTF_DETAILEDMODE | /**BTF_EDIETMAIL | /**/BTF_ATTACHREPORT /**| BTF_LISTPROCESSES /**| BTF_SHOWADVANCEDUI /**| BTF_SCREENCAPTURE/**/); + + u32 const minidump_flags = #ifndef MASTER_GOLD - ( - MiniDumpWithDataSegs | -// MiniDumpWithFullMemory | -// MiniDumpWithHandleData | -// MiniDumpFilterMemory | -// MiniDumpScanMemory | -// MiniDumpWithUnloadedModules | -# ifndef _EDITOR - MiniDumpWithIndirectlyReferencedMemory | -# endif // _EDITOR -// MiniDumpFilterModulePaths | -// MiniDumpWithProcessThreadData | -// MiniDumpWithPrivateReadWriteMemory | -// MiniDumpWithoutOptionalData | -// MiniDumpWithFullMemoryInfo | -// MiniDumpWithThreadInfo | -// MiniDumpWithCodeSegs | - 0 - ); + ( + MiniDumpWithDataSegs | + // MiniDumpWithFullMemory | + // MiniDumpWithHandleData | + // MiniDumpFilterMemory | + // MiniDumpScanMemory | + // MiniDumpWithUnloadedModules | +# ifndef _EDITOR + MiniDumpWithIndirectlyReferencedMemory | +# endif // _EDITOR + // MiniDumpFilterModulePaths | + // MiniDumpWithProcessThreadData | + // MiniDumpWithPrivateReadWriteMemory | + // MiniDumpWithoutOptionalData | + // MiniDumpWithFullMemoryInfo | + // MiniDumpWithThreadInfo | + // MiniDumpWithCodeSegs | + 0 + ); #else // #ifndef MASTER_GOLD - dedicated ? - MiniDumpNoDump : - ( - MiniDumpWithDataSegs | -// MiniDumpWithFullMemory | -// MiniDumpWithHandleData | -// MiniDumpFilterMemory | -// MiniDumpScanMemory | -// MiniDumpWithUnloadedModules | -# ifndef _EDITOR - MiniDumpWithIndirectlyReferencedMemory | -# endif // _EDITOR -// MiniDumpFilterModulePaths | -// MiniDumpWithProcessThreadData | -// MiniDumpWithPrivateReadWriteMemory | -// MiniDumpWithoutOptionalData | -// MiniDumpWithFullMemoryInfo | -// MiniDumpWithThreadInfo | -// MiniDumpWithCodeSegs | - 0 - ); + dedicated ? + MiniDumpNoDump : + ( + MiniDumpWithDataSegs | + // MiniDumpWithFullMemory | + // MiniDumpWithHandleData | + // MiniDumpFilterMemory | + // MiniDumpScanMemory | + // MiniDumpWithUnloadedModules | +# ifndef _EDITOR + MiniDumpWithIndirectlyReferencedMemory | +# endif // _EDITOR + // MiniDumpFilterModulePaths | + // MiniDumpWithProcessThreadData | + // MiniDumpWithPrivateReadWriteMemory | + // MiniDumpWithoutOptionalData | + // MiniDumpWithFullMemoryInfo | + // MiniDumpWithThreadInfo | + // MiniDumpWithCodeSegs | + 0 + ); #endif // #ifndef MASTER_GOLD - BT_SetDumpType (minidump_flags); - BT_SetSupportEMail ("cop-crash-report@stalker-game.com"); -// BT_SetSupportServer ("localhost", 9999); -// BT_SetSupportURL ("www.gsc-game.com"); + BT_SetDumpType(minidump_flags); + BT_SetSupportEMail("cop-crash-report@stalker-game.com"); + // BT_SetSupportServer ("localhost", 9999); + // BT_SetSupportURL ("www.gsc-game.com"); } #endif // USE_BUG_TRAP #if 1 -extern void BuildStackTrace(struct _EXCEPTION_POINTERS *pExceptionInfo); -typedef LONG WINAPI UnhandledExceptionFilterType(struct _EXCEPTION_POINTERS *pExceptionInfo); -typedef LONG ( __stdcall *PFNCHFILTFN ) ( EXCEPTION_POINTERS * pExPtrs ) ; -extern "C" BOOL __stdcall SetCrashHandlerFilter ( PFNCHFILTFN pFn ); +extern void BuildStackTrace(struct _EXCEPTION_POINTERS* pExceptionInfo); +typedef LONG WINAPI UnhandledExceptionFilterType(struct _EXCEPTION_POINTERS* pExceptionInfo); +typedef LONG(__stdcall* PFNCHFILTFN) (EXCEPTION_POINTERS* pExPtrs); +extern "C" BOOL __stdcall SetCrashHandlerFilter(PFNCHFILTFN pFn); -static UnhandledExceptionFilterType *previous_filter = 0; +static UnhandledExceptionFilterType* previous_filter = 0; #ifdef USE_OWN_MINI_DUMP -typedef BOOL (WINAPI *MINIDUMPWRITEDUMP)(HANDLE hProcess, DWORD dwPid, HANDLE hFile, MINIDUMP_TYPE DumpType, - CONST PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam, - CONST PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam, - CONST PMINIDUMP_CALLBACK_INFORMATION CallbackParam - ); - -void save_mini_dump (_EXCEPTION_POINTERS *pExceptionInfo) -{ - // firstly see if dbghelp.dll is around and has the function we need - // look next to the EXE first, as the one in System32 might be old - // (e.g. Windows 2000) - HMODULE hDll = NULL; - string_path szDbgHelpPath; - - if (GetModuleFileName( NULL, szDbgHelpPath, _MAX_PATH )) - { - char *pSlash = strchr( szDbgHelpPath, '\\' ); - if (pSlash) - { - xr_strcpy (pSlash+1, sizeof(szDbgHelpPath)-(pSlash - szDbgHelpPath), "DBGHELP.DLL" ); - hDll = ::LoadLibrary( szDbgHelpPath ); - } - } - - if (hDll==NULL) - { - // load any version we can - hDll = ::LoadLibrary( "DBGHELP.DLL" ); - } - - LPCTSTR szResult = NULL; - - if (hDll) - { - MINIDUMPWRITEDUMP pDump = (MINIDUMPWRITEDUMP)::GetProcAddress( hDll, "MiniDumpWriteDump" ); - if (pDump) - { - string_path szDumpPath; - string_path szScratch; - string64 t_stemp; - - timestamp (t_stemp); - xr_strcpy ( szDumpPath, Core.ApplicationName); - xr_strcat ( szDumpPath, "_" ); - xr_strcat ( szDumpPath, Core.UserName ); - xr_strcat ( szDumpPath, "_" ); - xr_strcat ( szDumpPath, t_stemp ); - xr_strcat ( szDumpPath, ".mdmp" ); - - __try { - if (FS.path_exist("$logs$")) - FS.update_path (szDumpPath,"$logs$",szDumpPath); - } - __except( EXCEPTION_EXECUTE_HANDLER ) { - string_path temp; - xr_strcpy (temp,szDumpPath); - xr_strcpy (szDumpPath,"logs/"); - xr_strcat (szDumpPath,temp); +typedef BOOL (WINAPI* MINIDUMPWRITEDUMP)(HANDLE hProcess, DWORD dwPid, HANDLE hFile, MINIDUMP_TYPE DumpType, + CONST PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam, + CONST PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam, + CONST PMINIDUMP_CALLBACK_INFORMATION CallbackParam + ); + +void save_mini_dump (_EXCEPTION_POINTERS* pExceptionInfo) +{ + // firstly see if dbghelp.dll is around and has the function we need + // look next to the EXE first, as the one in System32 might be old + // (e.g. Windows 2000) + HMODULE hDll = NULL; + string_path szDbgHelpPath; + + if (GetModuleFileName( NULL, szDbgHelpPath, _MAX_PATH )) + { + char* pSlash = strchr( szDbgHelpPath, '\\' ); + if (pSlash) + { + xr_strcpy (pSlash+1, sizeof(szDbgHelpPath)-(pSlash - szDbgHelpPath), "DBGHELP.DLL" ); + hDll = ::LoadLibrary( szDbgHelpPath ); + } + } + + if (hDll==NULL) + { + // load any version we can + hDll = ::LoadLibrary( "DBGHELP.DLL" ); + } + + LPCTSTR szResult = NULL; + + if (hDll) + { + MINIDUMPWRITEDUMP pDump = (MINIDUMPWRITEDUMP)::GetProcAddress( hDll, "MiniDumpWriteDump" ); + if (pDump) + { + string_path szDumpPath; + string_path szScratch; + string64 t_stemp; + + timestamp (t_stemp); + xr_strcpy ( szDumpPath, Core.ApplicationName); + xr_strcat ( szDumpPath, "_" ); + xr_strcat ( szDumpPath, Core.UserName ); + xr_strcat ( szDumpPath, "_" ); + xr_strcat ( szDumpPath, t_stemp ); + xr_strcat ( szDumpPath, ".mdmp" ); + + __try + { + if (FS.path_exist("$logs$")) + FS.update_path (szDumpPath,"$logs$",szDumpPath); + } + __except( EXCEPTION_EXECUTE_HANDLER ) + { + string_path temp; + xr_strcpy (temp,szDumpPath); + xr_strcpy (szDumpPath,"logs/"); + xr_strcat (szDumpPath,temp); } - // create the file - HANDLE hFile = ::CreateFile( szDumpPath, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); - if (INVALID_HANDLE_VALUE==hFile) - { - // try to place into current directory - MoveMemory (szDumpPath,szDumpPath+5,strlen(szDumpPath)); - hFile = ::CreateFile( szDumpPath, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); - } - if (hFile!=INVALID_HANDLE_VALUE) - { - _MINIDUMP_EXCEPTION_INFORMATION ExInfo; - - ExInfo.ThreadId = ::GetCurrentThreadId(); - ExInfo.ExceptionPointers = pExceptionInfo; - ExInfo.ClientPointers = NULL; - - // write the dump - MINIDUMP_TYPE dump_flags = MINIDUMP_TYPE(MiniDumpNormal | MiniDumpFilterMemory | MiniDumpScanMemory ); - - BOOL bOK = pDump( GetCurrentProcess(), GetCurrentProcessId(), hFile, dump_flags, &ExInfo, NULL, NULL ); - if (bOK) - { - xr_sprintf( szScratch, "Saved dump file to '%s'", szDumpPath ); - szResult = szScratch; -// retval = EXCEPTION_EXECUTE_HANDLER; - } - else - { - xr_sprintf( szScratch, "Failed to save dump file to '%s' (error %d)", szDumpPath, GetLastError() ); - szResult = szScratch; - } - ::CloseHandle(hFile); - } - else - { - xr_sprintf( szScratch, "Failed to create dump file '%s' (error %d)", szDumpPath, GetLastError() ); - szResult = szScratch; - } - } - else - { - szResult = "DBGHELP.DLL too old"; - } - } - else - { - szResult = "DBGHELP.DLL not found"; - } + // create the file + HANDLE hFile = ::CreateFile( szDumpPath, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); + if (INVALID_HANDLE_VALUE==hFile) + { + // try to place into current directory + MoveMemory (szDumpPath,szDumpPath+5,strlen(szDumpPath)); + hFile = ::CreateFile( szDumpPath, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); + } + if (hFile!=INVALID_HANDLE_VALUE) + { + _MINIDUMP_EXCEPTION_INFORMATION ExInfo; + + ExInfo.ThreadId = ::GetCurrentThreadId(); + ExInfo.ExceptionPointers = pExceptionInfo; + ExInfo.ClientPointers = NULL; + + // write the dump + MINIDUMP_TYPE dump_flags = MINIDUMP_TYPE(MiniDumpNormal | MiniDumpFilterMemory | MiniDumpScanMemory ); + + BOOL bOK = pDump( GetCurrentProcess(), GetCurrentProcessId(), hFile, dump_flags, &ExInfo, NULL, NULL ); + if (bOK) + { + xr_sprintf( szScratch, "Saved dump file to '%s'", szDumpPath ); + szResult = szScratch; + // retval = EXCEPTION_EXECUTE_HANDLER; + } + else + { + xr_sprintf( szScratch, "Failed to save dump file to '%s' (error %d)", szDumpPath, GetLastError() ); + szResult = szScratch; + } + ::CloseHandle(hFile); + } + else + { + xr_sprintf( szScratch, "Failed to create dump file '%s' (error %d)", szDumpPath, GetLastError() ); + szResult = szScratch; + } + } + else + { + szResult = "DBGHELP.DLL too old"; + } + } + else + { + szResult = "DBGHELP.DLL not found"; + } } #endif // USE_OWN_MINI_DUMP -void format_message (LPSTR buffer, const u32 &buffer_size) +void format_message(LPSTR buffer, const u32& buffer_size) { - LPVOID message; - DWORD error_code = GetLastError(); + LPVOID message; + DWORD error_code = GetLastError(); - if (!error_code) { - *buffer = 0; - return; - } + if (!error_code) + { + *buffer = 0; + return; + } FormatMessage( - FORMAT_MESSAGE_ALLOCATE_BUFFER | + FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&message, 0, - NULL - ); + NULL + ); - xr_sprintf (buffer,buffer_size,"[error][%8d] : %s",error_code,message); - LocalFree (message); + xr_sprintf(buffer, buffer_size, "[error][%8d] : %s", error_code, message); + LocalFree(message); } #ifndef _EDITOR - #include - #pragma comment( lib, "faultrep.lib" ) +#include +#pragma comment( lib, "faultrep.lib" ) #endif -LONG WINAPI UnhandledFilter (_EXCEPTION_POINTERS *pExceptionInfo) +LONG WINAPI UnhandledFilter(_EXCEPTION_POINTERS* pExceptionInfo) { - string256 error_message; - format_message (error_message,sizeof(error_message)); - - if (!error_after_dialog && !strstr(GetCommandLine(),"-no_call_stack_assert")) { - CONTEXT save = *pExceptionInfo->ContextRecord; - BuildStackTrace (pExceptionInfo); - *pExceptionInfo->ContextRecord = save; - - if (shared_str_initialized) - Msg ("stack trace:\n"); - - if (!IsDebuggerPresent()) - { - os_clipboard::copy_to_clipboard ("stack trace:\r\n\r\n"); - } + string256 error_message; + format_message(error_message, sizeof(error_message)); - string4096 buffer; - for (int i=0; iContextRecord; + BuildStackTrace(pExceptionInfo); + *pExceptionInfo->ContextRecord = save; + + if (shared_str_initialized) + Msg("stack trace:\n"); + + if (!IsDebuggerPresent()) + { + os_clipboard::copy_to_clipboard("stack trace:\r\n\r\n"); + } + + string4096 buffer; + for (int i = 0; i < g_stackTraceCount; ++i) + { + if (shared_str_initialized) + Msg("%s", g_stackTrace[i]); + xr_sprintf(buffer, sizeof(buffer), "%s\r\n", g_stackTrace[i]); #ifdef DEBUG - if (!IsDebuggerPresent()) - os_clipboard::update_clipboard(buffer); + if (!IsDebuggerPresent()) + os_clipboard::update_clipboard(buffer); #endif // #ifdef DEBUG - } + } - if (*error_message) { - if (shared_str_initialized) - Msg ("\n%s",error_message); + if (*error_message) + { + if (shared_str_initialized) + Msg("\n%s", error_message); - xr_strcat (error_message,sizeof(error_message),"\r\n"); + xr_strcat(error_message, sizeof(error_message), "\r\n"); #ifdef DEBUG - if (!IsDebuggerPresent()) - os_clipboard::update_clipboard(buffer); + if (!IsDebuggerPresent()) + os_clipboard::update_clipboard(buffer); #endif // #ifdef DEBUG - } - } + } + } - if (shared_str_initialized) - FlushLog (); + if (shared_str_initialized) + FlushLog(); #ifndef USE_OWN_ERROR_MESSAGE_WINDOW -# ifdef USE_OWN_MINI_DUMP - save_mini_dump (pExceptionInfo); -# endif // USE_OWN_MINI_DUMP +# ifdef USE_OWN_MINI_DUMP + save_mini_dump (pExceptionInfo); +# endif // USE_OWN_MINI_DUMP #else // USE_OWN_ERROR_MESSAGE_WINDOW - if (!error_after_dialog) { - if (Debug.get_on_dialog()) - Debug.get_on_dialog() (true); + if (!error_after_dialog) + { + if (Debug.get_on_dialog()) + Debug.get_on_dialog() (true); - MessageBox (NULL,"Fatal error occured\n\nPress OK to abort program execution","Fatal error",MB_OK|MB_ICONERROR|MB_SYSTEMMODAL); - } + MessageBox(NULL, "Fatal error occured\n\nPress OK to abort program execution", "Fatal error", MB_OK | MB_ICONERROR | MB_SYSTEMMODAL); + } #endif // USE_OWN_ERROR_MESSAGE_WINDOW #ifndef _EDITOR - ReportFault ( pExceptionInfo, 0 ); + ReportFault(pExceptionInfo, 0); #endif - if (!previous_filter) { + if (!previous_filter) + { #ifdef USE_OWN_ERROR_MESSAGE_WINDOW - if (Debug.get_on_dialog()) - Debug.get_on_dialog() (false); + if (Debug.get_on_dialog()) + Debug.get_on_dialog() (false); #endif // USE_OWN_ERROR_MESSAGE_WINDOW - return (EXCEPTION_CONTINUE_SEARCH) ; - } + return (EXCEPTION_CONTINUE_SEARCH); + } - previous_filter (pExceptionInfo); + previous_filter(pExceptionInfo); #ifdef USE_OWN_ERROR_MESSAGE_WINDOW - if (Debug.get_on_dialog()) - Debug.get_on_dialog() (false); + if (Debug.get_on_dialog()) + Debug.get_on_dialog() (false); #endif // USE_OWN_ERROR_MESSAGE_WINDOW - return (EXCEPTION_CONTINUE_SEARCH) ; + return (EXCEPTION_CONTINUE_SEARCH); } #endif ////////////////////////////////////////////////////////////////////// #ifdef M_BORLAND - namespace std{ - extern new_handler _RTLENTRY _EXPFUNC set_new_handler( new_handler new_p ); - }; +namespace std +{ +extern new_handler _RTLENTRY _EXPFUNC set_new_handler( new_handler new_p ); +}; - static void __cdecl def_new_handler() - { - FATAL ("Out of memory."); - } +static void __cdecl def_new_handler() +{ + FATAL ("Out of memory."); +} - void xrDebug::_initialize (const bool &dedicated) - { - handler = 0; - m_on_dialog = 0; - std::set_new_handler (def_new_handler); // exception-handler for 'out of memory' condition -// ::SetUnhandledExceptionFilter (UnhandledFilter); // exception handler to all "unhandled" exceptions - } +void xrDebug::_initialize (const bool& dedicated) +{ + handler = 0; + m_on_dialog = 0; + std::set_new_handler (def_new_handler); // exception-handler for 'out of memory' condition + // ::SetUnhandledExceptionFilter (UnhandledFilter); // exception handler to all "unhandled" exceptions +} #else - typedef int (__cdecl * _PNH)( size_t ); - _CRTIMP int __cdecl _set_new_mode( int ); - _CRTIMP _PNH __cdecl _set_new_handler( _PNH ); +typedef int(__cdecl* _PNH)(size_t); +_CRTIMP int __cdecl _set_new_mode(int); +_CRTIMP _PNH __cdecl _set_new_handler(_PNH); #ifndef USE_BUG_TRAP - void _terminate () - { - if (strstr(GetCommandLine(),"-silent_error_mode")) - exit (-1); - - string4096 assertion_info; - - Debug.gather_info ( - //gather_info ( - "", - "Unexpected application termination", - 0, - 0, - #ifdef ANONYMOUS_BUILD - "", - 0, - #else - __FILE__, - __LINE__, - #endif - #ifndef _EDITOR - __FUNCTION__, - #else // _EDITOR - "", - #endif // _EDITOR - assertion_info - ); - - LPCSTR endline = "\r\n"; - LPSTR buffer = assertion_info + xr_strlen(assertion_info); - buffer += xr_sprintf(buffer,"Press OK to abort execution%s",endline); - - MessageBox ( - GetTopWindow(NULL), - assertion_info, - "Fatal Error", - MB_OK|MB_ICONERROR|MB_SYSTEMMODAL - ); - - exit (-1); - // FATAL ("Unexpected application termination"); - } +void _terminate () +{ + if (strstr(GetCommandLine(),"-silent_error_mode")) + exit (-1); + + string4096 assertion_info; + + Debug.gather_info ( + //gather_info ( + "", + "Unexpected application termination", + 0, + 0, +#ifdef ANONYMOUS_BUILD + "", + 0, +#else + __FILE__, + __LINE__, +#endif +#ifndef _EDITOR + __FUNCTION__, +#else // _EDITOR + "", +#endif // _EDITOR + assertion_info + ); + + LPCSTR endline = "\r\n"; + LPSTR buffer = assertion_info + xr_strlen(assertion_info); + buffer += xr_sprintf(buffer,"Press OK to abort execution%s",endline); + + MessageBox ( + GetTopWindow(NULL), + assertion_info, + "Fatal Error", + MB_OK|MB_ICONERROR|MB_SYSTEMMODAL + ); + + exit (-1); + // FATAL ("Unexpected application termination"); +} #endif // USE_BUG_TRAP - static void handler_base (LPCSTR reason_string) - { - bool ignore_always = false; - Debug.backend ( - "error handler is invoked!", - reason_string, - 0, - 0, - DEBUG_INFO, - ignore_always - ); - } - - static void invalid_parameter_handler ( - const wchar_t *expression, - const wchar_t *function, - const wchar_t *file, - unsigned int line, - uintptr_t reserved - ) - { - bool ignore_always = false; - - string4096 expression_; - string4096 function_; - string4096 file_; - size_t converted_chars = 0; -// errno_t err = - if (expression) - wcstombs_s ( - &converted_chars, - expression_, - sizeof(expression_), - expression, - (wcslen(expression) + 1)*2*sizeof(char) - ); - else - xr_strcpy (expression_,""); - - if (function) - wcstombs_s ( - &converted_chars, - function_, - sizeof(function_), - function, - (wcslen(function) + 1)*2*sizeof(char) - ); - else - xr_strcpy (function_,__FUNCTION__); - - if (file) - wcstombs_s ( - &converted_chars, - file_, - sizeof(file_), - file, - (wcslen(file) + 1)*2*sizeof(char) - ); - else { - line = __LINE__; - xr_strcpy (file_,__FILE__); - } - - Debug.backend ( - "error handler is invoked!", - expression_, - 0, - 0, - file_, - line, - function_, - ignore_always - ); - } - - static void pure_call_handler () - { - handler_base ("pure virtual function call"); - } +static void handler_base(LPCSTR reason_string) +{ + bool ignore_always = false; + Debug.backend( + "error handler is invoked!", + reason_string, + 0, + 0, + DEBUG_INFO, + ignore_always + ); +} + +static void invalid_parameter_handler( + const wchar_t* expression, + const wchar_t* function, + const wchar_t* file, + unsigned int line, + uintptr_t reserved +) +{ + bool ignore_always = false; + + string4096 expression_; + string4096 function_; + string4096 file_; + size_t converted_chars = 0; + // errno_t err = + if (expression) + wcstombs_s( + &converted_chars, + expression_, + sizeof(expression_), + expression, + (wcslen(expression) + 1) * 2 * sizeof(char) + ); + else + xr_strcpy(expression_, ""); + + if (function) + wcstombs_s( + &converted_chars, + function_, + sizeof(function_), + function, + (wcslen(function) + 1) * 2 * sizeof(char) + ); + else + xr_strcpy(function_, __FUNCTION__); + + if (file) + wcstombs_s( + &converted_chars, + file_, + sizeof(file_), + file, + (wcslen(file) + 1) * 2 * sizeof(char) + ); + else + { + line = __LINE__; + xr_strcpy(file_, __FILE__); + } + + Debug.backend( + "error handler is invoked!", + expression_, + 0, + 0, + file_, + line, + function_, + ignore_always + ); +} + +static void pure_call_handler() +{ + handler_base("pure virtual function call"); +} #ifdef XRAY_USE_EXCEPTIONS - static void unexpected_handler () - { - handler_base ("unexpected program termination"); - } +static void unexpected_handler () +{ + handler_base ("unexpected program termination"); +} #endif // XRAY_USE_EXCEPTIONS - static void abort_handler (int signal) - { - handler_base ("application is aborting"); - } - - static void floating_point_handler (int signal) - { - handler_base ("floating point error"); - } - - static void illegal_instruction_handler (int signal) - { - handler_base ("illegal instruction"); - } - -// static void storage_access_handler (int signal) -// { -// handler_base ("illegal storage access"); -// } - - static void termination_handler (int signal) - { - handler_base ("termination with exit code 3"); - } - - void debug_on_thread_spawn () - { +static void abort_handler(int signal) +{ + handler_base("application is aborting"); +} + +static void floating_point_handler(int signal) +{ + handler_base("floating point error"); +} + +static void illegal_instruction_handler(int signal) +{ + handler_base("illegal instruction"); +} + +// static void storage_access_handler (int signal) +// { +// handler_base ("illegal storage access"); +// } + +static void termination_handler(int signal) +{ + handler_base("termination with exit code 3"); +} + +void debug_on_thread_spawn() +{ #ifdef USE_BUG_TRAP - BT_SetTerminate (); + BT_SetTerminate(); #else // USE_BUG_TRAP - //std::set_terminate (_terminate); + //std::set_terminate (_terminate); #endif // USE_BUG_TRAP - _set_abort_behavior (0,_WRITE_ABORT_MSG | _CALL_REPORTFAULT); - signal (SIGABRT, abort_handler); - signal (SIGABRT_COMPAT,abort_handler); - signal (SIGFPE, floating_point_handler); - signal (SIGILL, illegal_instruction_handler); - signal (SIGINT, 0); -// signal (SIGSEGV, storage_access_handler); - signal (SIGTERM, termination_handler); + _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT); + signal(SIGABRT, abort_handler); + signal(SIGABRT_COMPAT, abort_handler); + signal(SIGFPE, floating_point_handler); + signal(SIGILL, illegal_instruction_handler); + signal(SIGINT, 0); + // signal (SIGSEGV, storage_access_handler); + signal(SIGTERM, termination_handler); - _set_invalid_parameter_handler (&invalid_parameter_handler); + _set_invalid_parameter_handler(&invalid_parameter_handler); - _set_new_mode (1); - _set_new_handler (&out_of_memory_handler); -// std::set_new_handler (&std_out_of_memory_handler); + _set_new_mode(1); + _set_new_handler(&out_of_memory_handler); + // std::set_new_handler (&std_out_of_memory_handler); - _set_purecall_handler (&pure_call_handler); + _set_purecall_handler(&pure_call_handler); #if 0// should be if we use exceptions - std::set_unexpected (_terminate); + std::set_unexpected (_terminate); #endif - } +} - void xrDebug::_initialize (const bool &dedicated) - { - static bool is_dedicated = dedicated; +void xrDebug::_initialize(const bool& dedicated) +{ + static bool is_dedicated = dedicated; - *g_bug_report_file = 0; + *g_bug_report_file = 0; - debug_on_thread_spawn (); + debug_on_thread_spawn(); #ifdef USE_BUG_TRAP - SetupExceptionHandler ( is_dedicated ); + SetupExceptionHandler(is_dedicated); #endif // USE_BUG_TRAP - previous_filter = ::SetUnhandledExceptionFilter(UnhandledFilter); // exception handler to all "unhandled" exceptions + previous_filter = ::SetUnhandledExceptionFilter(UnhandledFilter); // exception handler to all "unhandled" exceptions #if 0 - struct foo {static void recurs (const u32 &count) - { - if (!count) - return; - - _alloca (4096); - recurs (count - 1); - }}; - foo::recurs (u32(-1)); - std::terminate (); + struct foo + { + static void recurs (const u32& count) + { + if (!count) + return; + + _alloca (4096); + recurs (count - 1); + } + }; + foo::recurs (u32(-1)); + std::terminate (); #endif // 0 - } +} #endif diff --git a/src/xrCore/xrDebug_macros.h b/src/xrCore/xrDebug_macros.h index 5ab05deaee1..cf13bd92291 100644 --- a/src/xrCore/xrDebug_macros.h +++ b/src/xrCore/xrDebug_macros.h @@ -5,55 +5,55 @@ //#define ANONYMOUS_BUILD #ifndef __BORLANDC__ -# ifndef ANONYMOUS_BUILD -# define DEBUG_INFO __FILE__,__LINE__,__FUNCTION__ -# else // ANONYMOUS_BUILD -# define DEBUG_INFO "",__LINE__,"" -# endif // ANONYMOUS_BUILD +# ifndef ANONYMOUS_BUILD +# define DEBUG_INFO __FILE__,__LINE__,__FUNCTION__ +# else // ANONYMOUS_BUILD +# define DEBUG_INFO "",__LINE__,"" +# endif // ANONYMOUS_BUILD #else // __BORLANDC__ -# define DEBUG_INFO __FILE__,__LINE__,__FILE__ +# define DEBUG_INFO __FILE__,__LINE__,__FILE__ #endif // __BORLANDC__ #ifdef ANONYMOUS_BUILD - #define _TRE(arg) "" + #define _TRE(arg) "" #else - #define _TRE(arg) arg + #define _TRE(arg) arg #endif -# define CHECK_OR_EXIT(expr,message) do {if (!(expr)) ::Debug.do_exit(message);} while (0) +# define CHECK_OR_EXIT(expr,message) do {if (!(expr)) ::Debug.do_exit(message);} while (0) -# define R_ASSERT(expr) do {static bool ignore_always = false; if (!ignore_always && !(expr)) ::Debug.fail(_TRE(#expr),DEBUG_INFO,ignore_always);} while(0) -# define R_ASSERT2(expr,e2) do {static bool ignore_always = false; if (!ignore_always && !(expr)) ::Debug.fail(_TRE(#expr),_TRE(e2),DEBUG_INFO,ignore_always);} while(0) -# define R_ASSERT3(expr,e2,e3) do {static bool ignore_always = false; if (!ignore_always && !(expr)) ::Debug.fail(_TRE(#expr),_TRE(e2),_TRE(e3),DEBUG_INFO,ignore_always);} while(0) -# define R_ASSERT4(expr,e2,e3,e4) do {static bool ignore_always = false; if (!ignore_always && !(expr)) ::Debug.fail(_TRE(#expr),_TRE(e2),_TRE(e3),_TRE(e4),DEBUG_INFO,ignore_always);} while(0) -# define R_CHK(expr) do {static bool ignore_always = false; HRESULT hr = expr; if (!ignore_always && FAILED(hr)) ::Debug.error(hr,_TRE(#expr),DEBUG_INFO,ignore_always);} while(0) -# define R_CHK2(expr,e2) do {static bool ignore_always = false; HRESULT hr = expr; if (!ignore_always && FAILED(hr)) ::Debug.error(hr,_TRE(#expr),_TRE(e2),DEBUG_INFO,ignore_always);} while(0) -# define FATAL(description) Debug.fatal(DEBUG_INFO,description) +# define R_ASSERT(expr) do {static bool ignore_always = false; if (!ignore_always && !(expr)) ::Debug.fail(_TRE(#expr),DEBUG_INFO,ignore_always);} while(0) +# define R_ASSERT2(expr,e2) do {static bool ignore_always = false; if (!ignore_always && !(expr)) ::Debug.fail(_TRE(#expr),_TRE(e2),DEBUG_INFO,ignore_always);} while(0) +# define R_ASSERT3(expr,e2,e3) do {static bool ignore_always = false; if (!ignore_always && !(expr)) ::Debug.fail(_TRE(#expr),_TRE(e2),_TRE(e3),DEBUG_INFO,ignore_always);} while(0) +# define R_ASSERT4(expr,e2,e3,e4) do {static bool ignore_always = false; if (!ignore_always && !(expr)) ::Debug.fail(_TRE(#expr),_TRE(e2),_TRE(e3),_TRE(e4),DEBUG_INFO,ignore_always);} while(0) +# define R_CHK(expr) do {static bool ignore_always = false; HRESULT hr = expr; if (!ignore_always && FAILED(hr)) ::Debug.error(hr,_TRE(#expr),DEBUG_INFO,ignore_always);} while(0) +# define R_CHK2(expr,e2) do {static bool ignore_always = false; HRESULT hr = expr; if (!ignore_always && FAILED(hr)) ::Debug.error(hr,_TRE(#expr),_TRE(e2),DEBUG_INFO,ignore_always);} while(0) +# define FATAL(description) Debug.fatal(DEBUG_INFO,description) -# ifdef VERIFY -# undef VERIFY -# endif // VERIFY +# ifdef VERIFY +# undef VERIFY +# endif // VERIFY -# ifdef DEBUG -# define NODEFAULT FATAL("nodefault reached") -# define VERIFY(expr) do {static bool ignore_always = false; if (!ignore_always && !(expr)) ::Debug.fail(#expr,DEBUG_INFO,ignore_always);} while(0) -# define VERIFY2(expr,e2) do {static bool ignore_always = false; if (!ignore_always && !(expr)) ::Debug.fail(#expr,e2,DEBUG_INFO,ignore_always);} while(0) -# define VERIFY3(expr,e2,e3) do {static bool ignore_always = false; if (!ignore_always && !(expr)) ::Debug.fail(#expr,e2,e3,DEBUG_INFO,ignore_always);} while(0) -# define VERIFY4(expr,e2,e3,e4)do {static bool ignore_always = false; if (!ignore_always && !(expr)) ::Debug.fail(#expr,e2,e3,e4,DEBUG_INFO,ignore_always);} while(0) -# define CHK_DX(expr) do {static bool ignore_always = false; HRESULT hr = expr; if (!ignore_always && FAILED(hr)) ::Debug.error(hr,#expr,DEBUG_INFO,ignore_always);} while(0) -# else // DEBUG -# ifdef __BORLANDC__ -# define NODEFAULT -# else -# define NODEFAULT __assume(0) -# endif -# define VERIFY(expr) do {} while (0) -# define VERIFY2(expr, e2) do {} while (0) -# define VERIFY3(expr, e2, e3) do {} while (0) -# define VERIFY4(expr, e2, e3, e4)do {} while (0) -# define CHK_DX(a) a -# endif // DEBUG +# ifdef DEBUG +# define NODEFAULT FATAL("nodefault reached") +# define VERIFY(expr) do {static bool ignore_always = false; if (!ignore_always && !(expr)) ::Debug.fail(#expr,DEBUG_INFO,ignore_always);} while(0) +# define VERIFY2(expr,e2) do {static bool ignore_always = false; if (!ignore_always && !(expr)) ::Debug.fail(#expr,e2,DEBUG_INFO,ignore_always);} while(0) +# define VERIFY3(expr,e2,e3) do {static bool ignore_always = false; if (!ignore_always && !(expr)) ::Debug.fail(#expr,e2,e3,DEBUG_INFO,ignore_always);} while(0) +# define VERIFY4(expr,e2,e3,e4)do {static bool ignore_always = false; if (!ignore_always && !(expr)) ::Debug.fail(#expr,e2,e3,e4,DEBUG_INFO,ignore_always);} while(0) +# define CHK_DX(expr) do {static bool ignore_always = false; HRESULT hr = expr; if (!ignore_always && FAILED(hr)) ::Debug.error(hr,#expr,DEBUG_INFO,ignore_always);} while(0) +# else // DEBUG +# ifdef __BORLANDC__ +# define NODEFAULT +# else +# define NODEFAULT __assume(0) +# endif +# define VERIFY(expr) do {} while (0) +# define VERIFY2(expr, e2) do {} while (0) +# define VERIFY3(expr, e2, e3) do {} while (0) +# define VERIFY4(expr, e2, e3, e4)do {} while (0) +# define CHK_DX(a) a +# endif // DEBUG //--------------------------------------------------------------------------------------------- // FIXMEs / TODOs / NOTE macros //--------------------------------------------------------------------------------------------- @@ -61,26 +61,26 @@ #define QUOTE(x) _QUOTE(x) #define __FILE__LINE__ __FILE__ "(" QUOTE(__LINE__) ") : " -#define NOTE( x ) message( x ) -#define FILE_LINE message( __FILE__LINE__ ) +#define NOTE( x ) message( x ) +#define FILE_LINE message( __FILE__LINE__ ) -#define TODO( x ) message( __FILE__LINE__"\n" \ - " ------------------------------------------------\n" \ - "| TODO : " #x "\n" \ - " -------------------------------------------------\n" ) -#define FIXME( x ) message( __FILE__LINE__"\n" \ - " ------------------------------------------------\n" \ - "| FIXME : " #x "\n" \ - " -------------------------------------------------\n" ) -#define todo( x ) message( __FILE__LINE__" TODO : " #x "\n" ) -#define fixme( x ) message( __FILE__LINE__" FIXME: " #x "\n" ) +#define TODO( x ) message( __FILE__LINE__"\n" \ + " ------------------------------------------------\n" \ + "| TODO : " #x "\n" \ + " -------------------------------------------------\n" ) +#define FIXME( x ) message( __FILE__LINE__"\n" \ + " ------------------------------------------------\n" \ + "| FIXME : " #x "\n" \ + " -------------------------------------------------\n" ) +#define todo( x ) message( __FILE__LINE__" TODO : " #x "\n" ) +#define fixme( x ) message( __FILE__LINE__" FIXME: " #x "\n" ) //--------- static assertion -template struct CompileTimeError; -template<> struct CompileTimeError {}; +template struct CompileTimeError; +template<> struct CompileTimeError {}; #define STATIC_CHECK(expr, msg) \ { \ - CompileTimeError<((expr) != 0)> ERROR_##msg; \ - (void)ERROR_##msg; \ + CompileTimeError<((expr) != 0)> ERROR_##msg; \ + (void)ERROR_##msg; \ } #endif // xrDebug_macrosH \ No newline at end of file diff --git a/src/xrCore/xrMEMORY_POOL.h b/src/xrCore/xrMEMORY_POOL.h index 00aa0254362..bd1f5c61cea 100644 --- a/src/xrCore/xrMEMORY_POOL.h +++ b/src/xrCore/xrMEMORY_POOL.h @@ -4,48 +4,48 @@ class xrMemory; -class MEMPOOL +class MEMPOOL { #ifdef DEBUG_MEMORY_MANAGER - friend class xrMemory; + friend class xrMemory; #endif // DEBUG_MEMORY_MANAGER private: - xrCriticalSection cs; - u32 s_sector; // large-memory sector size - u32 s_element; // element size, for example 32 - u32 s_count; // element count = [s_sector/s_element] - u32 s_offset; // header size - u32 block_count; // block count - u8* list; + xrCriticalSection cs; + u32 s_sector; // large-memory sector size + u32 s_element; // element size, for example 32 + u32 s_count; // element count = [s_sector/s_element] + u32 s_offset; // header size + u32 block_count; // block count + u8* list; private: - ICF void** access (void* P) { return (void**) ((void*)(P)); } - void block_create (); + ICF void** access(void* P) { return (void**)((void*)(P)); } + void block_create(); public: - void _initialize (u32 _element, u32 _sector, u32 _header); + void _initialize(u32 _element, u32 _sector, u32 _header); #ifdef PROFILE_CRITICAL_SECTIONS - ICF MEMPOOL (): cs(MUTEX_PROFILE_ID(memory_pool)){} + ICF MEMPOOL() : cs(MUTEX_PROFILE_ID(memory_pool)) {} #endif // PROFILE_CRITICAL_SECTIONS - - ICF u32 get_block_count () { return block_count; } - ICF u32 get_element () { return s_element; } - ICF void* create () - { - cs.Enter (); - if (0==list) block_create(); + ICF u32 get_block_count() { return block_count; } + ICF u32 get_element() { return s_element; } - void* E = list; - list = (u8*)*access(list); - cs.Leave (); - return E; - } - ICF void destroy (void* &P) - { - cs.Enter (); - *access(P) = list; - list = (u8*)P; - cs.Leave (); - } + ICF void* create() + { + cs.Enter(); + if (0 == list) block_create(); + + void* E = list; + list = (u8*)*access(list); + cs.Leave(); + return E; + } + ICF void destroy(void*& P) + { + cs.Enter(); + *access(P) = list; + list = (u8*)P; + cs.Leave(); + } }; #endif diff --git a/src/xrCore/xrMemory.cpp b/src/xrCore/xrMemory.cpp index 15c3704e6a8..fa7dd6516cb 100644 --- a/src/xrCore/xrMemory.cpp +++ b/src/xrCore/xrMemory.cpp @@ -1,285 +1,290 @@ #include "stdafx.h" #pragma hdrstop -#include "xrsharedmem.h" -#include "xrMemory_pure.h" +#include "xrsharedmem.h" +#include "xrMemory_pure.h" -#include +#include -xrMemory Memory; -BOOL mem_initialized = FALSE; -bool shared_str_initialized = false; +xrMemory Memory; +BOOL mem_initialized = FALSE; +bool shared_str_initialized = false; //fake fix of memory corruptions in multiplayer game :( // XXX nitrocaster: to be removed -XRCORE_API bool g_allow_heap_min = true; +XRCORE_API bool g_allow_heap_min = true; // Processor specific implementations -extern pso_MemCopy xrMemCopy_MMX; -extern pso_MemCopy xrMemCopy_x86; -extern pso_MemFill xrMemFill_x86; -extern pso_MemFill32 xrMemFill32_MMX; -extern pso_MemFill32 xrMemFill32_x86; +extern pso_MemCopy xrMemCopy_MMX; +extern pso_MemCopy xrMemCopy_x86; +extern pso_MemFill xrMemFill_x86; +extern pso_MemFill32 xrMemFill32_MMX; +extern pso_MemFill32 xrMemFill32_x86; #ifdef DEBUG_MEMORY_MANAGER -XRCORE_API void dump_phase () +XRCORE_API void dump_phase() { - if (!Memory.debug_mode) - return; + if (!Memory.debug_mode) + return; - static int phase_counter = 0; + static int phase_counter = 0; - string256 temp; - xr_sprintf (temp,sizeof(temp),"x:\\$phase$%d.dump",++phase_counter); - Memory.mem_statistic (temp); + string256 temp; + xr_sprintf(temp, sizeof(temp), "x:\\$phase$%d.dump", ++phase_counter); + Memory.mem_statistic(temp); } #endif // DEBUG_MEMORY_MANAGER xrMemory::xrMemory() #ifdef DEBUG_MEMORY_MANAGER -# ifdef PROFILE_CRITICAL_SECTIONS - :debug_cs(MUTEX_PROFILE_ID(xrMemory)) -# endif // PROFILE_CRITICAL_SECTIONS +# ifdef PROFILE_CRITICAL_SECTIONS + :debug_cs(MUTEX_PROFILE_ID(xrMemory)) +# endif // PROFILE_CRITICAL_SECTIONS #endif // DEBUG_MEMORY_MANAGER { #ifdef DEBUG_MEMORY_MANAGER - debug_mode = FALSE; + debug_mode = FALSE; #endif // DEBUG_MEMORY_MANAGER - mem_copy = xrMemCopy_x86; - mem_fill = xrMemFill_x86; - mem_fill32 = xrMemFill32_x86; + mem_copy = xrMemCopy_x86; + mem_fill = xrMemFill_x86; + mem_fill32 = xrMemFill32_x86; } #ifdef DEBUG_MEMORY_MANAGER - BOOL g_bMEMO = FALSE; +BOOL g_bMEMO = FALSE; #endif // DEBUG_MEMORY_MANAGER -void xrMemory::_initialize (BOOL bDebug) +void xrMemory::_initialize(BOOL bDebug) { #ifdef DEBUG_MEMORY_MANAGER - debug_mode = bDebug; - debug_info_update = 0; + debug_mode = bDebug; + debug_info_update = 0; #endif // DEBUG_MEMORY_MANAGER - stat_calls = 0; - stat_counter = 0; - - u32 features = CPU::ID.feature; - if (features & _CPU_FEATURE_MMX) - { - mem_copy = xrMemCopy_MMX; - mem_fill = xrMemFill_x86; - mem_fill32 = xrMemFill32_MMX; - } else { - mem_copy = xrMemCopy_x86; - mem_fill = xrMemFill_x86; - mem_fill32 = xrMemFill32_x86; - } + stat_calls = 0; + stat_counter = 0; + + u32 features = CPU::ID.feature; + if (features & _CPU_FEATURE_MMX) + { + mem_copy = xrMemCopy_MMX; + mem_fill = xrMemFill_x86; + mem_fill32 = xrMemFill32_MMX; + } + else + { + mem_copy = xrMemCopy_x86; + mem_fill = xrMemFill_x86; + mem_fill32 = xrMemFill32_x86; + } #ifndef M_BORLAND - if (!strstr(Core.Params,"-pure_alloc")) { - // initialize POOLs - u32 element = mem_pools_ebase; - u32 sector = mem_pools_ebase*1024; - for (u32 pid=0; pid (); - shared_str_initialized = true; -// DUMP_PHASE; - g_pSharedMemoryContainer = xr_new (); -// DUMP_PHASE; + // DUMP_PHASE; + g_pStringContainer = xr_new(); + shared_str_initialized = true; + // DUMP_PHASE; + g_pSharedMemoryContainer = xr_new(); + // DUMP_PHASE; } #ifdef DEBUG_MEMORY_MANAGER - extern void dbg_dump_leaks(); - extern void dbg_dump_str_leaks(); +extern void dbg_dump_leaks(); +extern void dbg_dump_str_leaks(); #endif // DEBUG_MEMORY_MANAGER -void xrMemory::_destroy() +void xrMemory::_destroy() { #ifdef DEBUG_MEMORY_MANAGER - mem_alloc_gather_stats (false); - mem_alloc_show_stats (); - mem_alloc_clear_stats (); + mem_alloc_gather_stats(false); + mem_alloc_show_stats(); + mem_alloc_clear_stats(); #endif // DEBUG #ifdef DEBUG_MEMORY_MANAGER - if (debug_mode) dbg_dump_str_leaks (); + if (debug_mode) dbg_dump_str_leaks(); #endif // DEBUG_MEMORY_MANAGER - xr_delete (g_pSharedMemoryContainer); - xr_delete (g_pStringContainer); + xr_delete(g_pSharedMemoryContainer); + xr_delete(g_pStringContainer); #ifndef M_BORLAND -# ifdef DEBUG_MEMORY_MANAGER - if (debug_mode) dbg_dump_leaks (); -# endif // DEBUG_MEMORY_MANAGER +# ifdef DEBUG_MEMORY_MANAGER + if (debug_mode) dbg_dump_leaks(); +# endif // DEBUG_MEMORY_MANAGER #endif // M_BORLAND - mem_initialized = FALSE; + mem_initialized = FALSE; #ifdef DEBUG_MEMORY_MANAGER - debug_mode = FALSE; + debug_mode = FALSE; #endif // DEBUG_MEMORY_MANAGER } -void xrMemory::mem_compact () +void xrMemory::mem_compact() { - RegFlushKey ( HKEY_CLASSES_ROOT ); - RegFlushKey ( HKEY_CURRENT_USER ); - if (g_allow_heap_min) - _heapmin ( ); - HeapCompact (GetProcessHeap(),0); - if (g_pStringContainer) g_pStringContainer->clean (); - if (g_pSharedMemoryContainer) g_pSharedMemoryContainer->clean (); - if (strstr(Core.Params,"-swap_on_compact")) - SetProcessWorkingSetSize (GetCurrentProcess(),size_t(-1),size_t(-1)); + RegFlushKey(HKEY_CLASSES_ROOT); + RegFlushKey(HKEY_CURRENT_USER); + if (g_allow_heap_min) + _heapmin(); + HeapCompact(GetProcessHeap(), 0); + if (g_pStringContainer) g_pStringContainer->clean(); + if (g_pSharedMemoryContainer) g_pSharedMemoryContainer->clean(); + if (strstr(Core.Params, "-swap_on_compact")) + SetProcessWorkingSetSize(GetCurrentProcess(), size_t(-1), size_t(-1)); } #ifdef DEBUG_MEMORY_MANAGER -ICF u8* acc_header (void* P) { u8* _P = (u8*)P; return _P-1; } -ICF u32 get_header (void* P) { return (u32)*acc_header(P); } -void xrMemory::mem_statistic (LPCSTR fn) +ICF u8* acc_header(void* P) { u8* _P = (u8*)P; return _P - 1; } +ICF u32 get_header(void* P) { return (u32)*acc_header(P); } +void xrMemory::mem_statistic(LPCSTR fn) { - if (!debug_mode) return ; - mem_compact () ; - - debug_cs.Enter () ; - debug_mode = FALSE; - - FILE* Fa = fopen (fn,"w"); - fprintf (Fa,"$BEGIN CHUNK #0\n"); - fprintf (Fa,"POOL: %d %dKb\n",mem_pools_count,mem_pools_ebase); - - fprintf (Fa,"$BEGIN CHUNK #1\n"); - for (u32 k=0; kvalue); - }catch(...){ - } - } - */ - - fclose (Fa) ; - - // leave - debug_mode = TRUE; - debug_cs.Leave (); - - /* - mem_compact (); - LPCSTR fn = "$memstat$.tmp"; - xr_map stats; - - if (g_pStringContainer) Msg ("memstat: shared_str: economy: %d bytes",g_pStringContainer->stat_economy()); - if (g_pSharedMemoryContainer) Msg ("memstat: shared_mem: economy: %d bytes",g_pSharedMemoryContainer->stat_economy()); - - // Dump memory stats into file to avoid reallocation while traversing - { - IWriter* F = FS.w_open(fn); - F->w_u32 (0); - _HEAPINFO hinfo; - int heapstatus; - hinfo._pentry = NULL; - while( ( heapstatus = _heapwalk( &hinfo ) ) == _HEAPOK ) - if (hinfo._useflag == _USEDENTRY) F->w_u32 (u32(hinfo._size)); - FS.w_close (F); - } - - // Read back and perform sorting - { - IReader* F = FS.r_open (fn); - u32 size = F->r_u32 (); - while (!F->eof()) - { - size = F->r_u32 (); - xr_map::iterator I = stats.find(size); - if (I!=stats.end()) I->second += 1; - else stats.insert(mk_pair(size,1)); - } - FS.r_close (F); - FS.file_delete (fn); - } - - // Output to log - { - xr_map::iterator I = stats.begin(); - xr_map::iterator E = stats.end(); - for (; I!=E; I++) Msg ("%8d : %-4d [%d]",I->first,I->second,I->first*I->second); - } - */ + if (!debug_mode) return; + mem_compact(); + + debug_cs.Enter(); + debug_mode = FALSE; + + FILE* Fa = fopen(fn, "w"); + fprintf(Fa, "$BEGIN CHUNK #0\n"); + fprintf(Fa, "POOL: %d %dKb\n", mem_pools_count, mem_pools_ebase); + + fprintf(Fa, "$BEGIN CHUNK #1\n"); + for (u32 k = 0; k < mem_pools_count; ++k) + fprintf(Fa, "%2d: %d %db\n", k, mem_pools[k].get_block_count(), (k + 1) * 16); + + fprintf(Fa, "$BEGIN CHUNK #2\n"); + for (u32 it = 0; it < debug_info.size(); it++) + { + if (0 == debug_info[it]._p) continue; + + u32 p_current = get_header(debug_info[it]._p); + int pool_id = (mem_generic == p_current) ? -1 : p_current; + + fprintf(Fa, "0x%08X[%2d]: %8d %s\n", *(u32*)(&debug_info[it]._p), pool_id, debug_info[it]._size, debug_info[it]._name); + } + + { + for (u32 k = 0; k < mem_pools_count; ++k) + { + MEMPOOL& pool = mem_pools[k]; + u8* list = pool.list; + while (list) + { + pool.cs.Enter(); + u32 temp = *(u32*)(&list); + if (!temp) + break; + fprintf(Fa, "0x%08X[%2d]: %8d mempool\n", temp, k, pool.s_element); + list = (u8*)*pool.access(list); + pool.cs.Leave(); + } + } + } + + /* + fprintf (Fa,"$BEGIN CHUNK #3\n"); + for (u32 it=0; itvalue); + }catch(...){ + } + } + */ + + fclose(Fa); + + // leave + debug_mode = TRUE; + debug_cs.Leave(); + + /* + mem_compact (); + LPCSTR fn = "$memstat$.tmp"; + xr_map stats; + + if (g_pStringContainer) Msg ("memstat: shared_str: economy: %d bytes",g_pStringContainer->stat_economy()); + if (g_pSharedMemoryContainer) Msg ("memstat: shared_mem: economy: %d bytes",g_pSharedMemoryContainer->stat_economy()); + + // Dump memory stats into file to avoid reallocation while traversing + { + IWriter* F = FS.w_open(fn); + F->w_u32 (0); + _HEAPINFO hinfo; + int heapstatus; + hinfo._pentry = NULL; + while( ( heapstatus = _heapwalk( &hinfo ) ) == _HEAPOK ) + if (hinfo._useflag == _USEDENTRY) F->w_u32 (u32(hinfo._size)); + FS.w_close (F); + } + + // Read back and perform sorting + { + IReader* F = FS.r_open (fn); + u32 size = F->r_u32 (); + while (!F->eof()) + { + size = F->r_u32 (); + xr_map::iterator I = stats.find(size); + if (I!=stats.end()) I->second += 1; + else stats.insert(mk_pair(size,1)); + } + FS.r_close (F); + FS.file_delete (fn); + } + + // Output to log + { + xr_map::iterator I = stats.begin(); + xr_map::iterator E = stats.end(); + for (; I!=E; I++) Msg ("%8d : %-4d [%d]",I->first,I->second,I->first*I->second); + } + */ } #endif // DEBUG_MEMORY_MANAGER // xr_strdup -char* xr_strdup (const char* string) -{ - VERIFY (string); - u32 len = u32(xr_strlen(string))+1 ; - char * memory = (char*) Memory.mem_alloc( len +char* xr_strdup(const char* string) +{ + VERIFY(string); + u32 len = u32(xr_strlen(string)) + 1; + char* memory = (char*)Memory.mem_alloc(len #ifdef DEBUG_MEMORY_NAME - , "strdup" + , "strdup" #endif // DEBUG_MEMORY_NAME - ); - CopyMemory (memory,string,len); - return memory; + ); + CopyMemory(memory, string, len); + return memory; } -XRCORE_API BOOL is_stack_ptr ( void* _ptr) +XRCORE_API BOOL is_stack_ptr(void* _ptr) { - int local_value = 0; - void* ptr_refsound = _ptr; - void* ptr_local = &local_value; - ptrdiff_t difference = (ptrdiff_t)_abs(s64(ptrdiff_t(ptr_local) - ptrdiff_t(ptr_refsound))); - return (difference < (512*1024)); + int local_value = 0; + void* ptr_refsound = _ptr; + void* ptr_local = &local_value; + ptrdiff_t difference = (ptrdiff_t)_abs(s64(ptrdiff_t(ptr_local) - ptrdiff_t(ptr_refsound))); + return (difference < (512 * 1024)); } diff --git a/src/xrCore/xrMemory.h b/src/xrCore/xrMemory.h index ddf97fc5dfd..60fe58a56b6 100644 --- a/src/xrCore/xrMemory.h +++ b/src/xrCore/xrMemory.h @@ -5,142 +5,143 @@ #include "memory_monitor.h" #ifdef USE_MEMORY_MONITOR -# define DEBUG_MEMORY_NAME +# define DEBUG_MEMORY_NAME #endif // USE_MEMORY_MONITOR #ifndef M_BORLAND -# if 0//def DEBUG -# define DEBUG_MEMORY_MANAGER -# endif // DEBUG +# if 0//def DEBUG +# define DEBUG_MEMORY_MANAGER +# endif // DEBUG #endif // M_BORLAND #ifdef DEBUG_MEMORY_MANAGER - XRCORE_API extern BOOL g_bMEMO; -# ifndef DEBUG_MEMORY_NAME -# define DEBUG_MEMORY_NAME -# endif // DEBUG_MEMORY_NAME - extern XRCORE_API void dump_phase (); -# define DUMP_PHASE do {dump_phase();} while (0) +XRCORE_API extern BOOL g_bMEMO; +# ifndef DEBUG_MEMORY_NAME +# define DEBUG_MEMORY_NAME +# endif // DEBUG_MEMORY_NAME +extern XRCORE_API void dump_phase (); +# define DUMP_PHASE do {dump_phase();} while (0) #else // DEBUG_MEMORY_MANAGER -# define DUMP_PHASE do {} while (0) +# define DUMP_PHASE do {} while (0) #endif // DEBUG_MEMORY_MANAGER #include "xrMemory_pso.h" #include "xrMemory_POOL.h" -class XRCORE_API xrMemory +class XRCORE_API xrMemory { public: - struct mdbg { - void* _p; - size_t _size; - const char* _name; - u32 _dummy; - }; + struct mdbg + { + void* _p; + size_t _size; + const char* _name; + u32 _dummy; + }; public: - xrMemory (); - void _initialize (BOOL _debug_mode=FALSE); - void _destroy (); + xrMemory(); + void _initialize(BOOL _debug_mode = FALSE); + void _destroy(); #ifdef DEBUG_MEMORY_MANAGER - BOOL debug_mode; - xrCriticalSection debug_cs; - std::vector debug_info; - u32 debug_info_update; - u32 stat_strcmp ; - u32 stat_strdock ; + BOOL debug_mode; + xrCriticalSection debug_cs; + std::vector debug_info; + u32 debug_info_update; + u32 stat_strcmp ; + u32 stat_strdock ; #endif // DEBUG_MEMORY_MANAGER - u32 stat_calls; - s32 stat_counter; + u32 stat_calls; + s32 stat_counter; public: - void dbg_register (void* _p, size_t _size, const char* _name); - void dbg_unregister (void* _p); - void dbg_check (); + void dbg_register(void* _p, size_t _size, const char* _name); + void dbg_unregister(void* _p); + void dbg_check(); - size_t mem_usage (); - void mem_compact (); - void mem_counter_set (u32 _val) { stat_counter = _val; } - u32 mem_counter_get () { return stat_counter; } + size_t mem_usage(); + void mem_compact(); + void mem_counter_set(u32 _val) { stat_counter = _val; } + u32 mem_counter_get() { return stat_counter; } #ifdef DEBUG_MEMORY_NAME - void mem_statistic (LPCSTR fn); - void* mem_alloc (size_t size , const char* _name); - void* mem_realloc (void* p, size_t size , const char* _name); + void mem_statistic(LPCSTR fn); + void* mem_alloc(size_t size, const char* _name); + void* mem_realloc(void* p, size_t size, const char* _name); #else // DEBUG_MEMORY_NAME - void* mem_alloc (size_t size ); - void* mem_realloc (void* p, size_t size ); + void* mem_alloc (size_t size ); + void* mem_realloc (void* p, size_t size ); #endif // DEBUG_MEMORY_NAME - void mem_free (void* p ); + void mem_free(void* p); - pso_MemCopy* mem_copy; - pso_MemFill* mem_fill; - pso_MemFill32* mem_fill32; + pso_MemCopy* mem_copy; + pso_MemFill* mem_fill; + pso_MemFill32* mem_fill32; }; -extern XRCORE_API xrMemory Memory; +extern XRCORE_API xrMemory Memory; -#undef ZeroMemory -#undef CopyMemory -#undef FillMemory -#define ZeroMemory(a,b) Memory.mem_fill(a,0,b) -#define CopyMemory(a,b,c) memcpy(a,b,c) //. CopyMemory(a,b,c) -#define FillMemory(a,b,c) Memory.mem_fill(a,c,b) +#undef ZeroMemory +#undef CopyMemory +#undef FillMemory +#define ZeroMemory(a,b) Memory.mem_fill(a,0,b) +#define CopyMemory(a,b,c) memcpy(a,b,c) //. CopyMemory(a,b,c) +#define FillMemory(a,b,c) Memory.mem_fill(a,c,b) // delete #ifdef __BORLANDC__ - #include "xrMemory_subst_borland.h" +#include "xrMemory_subst_borland.h" #else - #include "xrMemory_subst_msvc.h" +#include "xrMemory_subst_msvc.h" #endif // generic "C"-like allocations/deallocations #ifdef DEBUG_MEMORY_NAME - #include "typeinfo.h" - - template - IC T* xr_alloc (u32 count) { return (T*)Memory.mem_alloc(count*sizeof(T),typeid(T).name()); } - template - IC void xr_free (T* &P) { if (P) { Memory.mem_free((void*)P); P=NULL; }; } - IC void* xr_malloc (size_t size) { return Memory.mem_alloc(size,"xr_malloc"); } - IC void* xr_realloc (void* P, size_t size) { return Memory.mem_realloc(P,size,"xr_realloc"); } +#include "typeinfo.h" + +template +IC T* xr_alloc(u32 count) { return (T*)Memory.mem_alloc(count*sizeof(T), typeid(T).name()); } +template +IC void xr_free(T*& P) { if (P) { Memory.mem_free((void*)P); P = NULL; }; } +IC void* xr_malloc(size_t size) { return Memory.mem_alloc(size, "xr_malloc"); } +IC void* xr_realloc(void* P, size_t size) { return Memory.mem_realloc(P, size, "xr_realloc"); } #else // DEBUG_MEMORY_NAME - template - IC T* xr_alloc (u32 count) { return (T*)Memory.mem_alloc(count*sizeof(T)); } - template - IC void xr_free (T* &P) { if (P) { Memory.mem_free((void*)P); P=NULL; }; } - IC void* xr_malloc (size_t size) { return Memory.mem_alloc(size); } - IC void* xr_realloc (void* P, size_t size) { return Memory.mem_realloc(P,size); } +template +IC T* xr_alloc (u32 count) { return (T*)Memory.mem_alloc(count*sizeof(T)); } +template +IC void xr_free (T*& P) { if (P) { Memory.mem_free((void*)P); P=NULL; }; } +IC void* xr_malloc (size_t size) { return Memory.mem_alloc(size); } +IC void* xr_realloc (void* P, size_t size) { return Memory.mem_realloc(P,size); } #endif // DEBUG_MEMORY_NAME -XRCORE_API char* xr_strdup (const char* string); +XRCORE_API char* xr_strdup(const char* string); #ifdef DEBUG_MEMORY_NAME // Global new/delete override -# if !(defined(__BORLANDC__) || defined(NO_XRNEW)) - IC void* operator new (size_t size) { return Memory.mem_alloc(size?size:1, "C++ NEW"); } - IC void operator delete (void *p) { xr_free(p); } - IC void* operator new[] (size_t size) { return Memory.mem_alloc(size?size:1, "C++ NEW"); } - IC void operator delete[] (void* p) { xr_free(p); } -# endif +# if !(defined(__BORLANDC__) || defined(NO_XRNEW)) +IC void* operator new (size_t size) {return Memory.mem_alloc(size ? size : 1, "C++ NEW");} +IC void operator delete (void* p) { xr_free(p); } +IC void* operator new[](size_t size) { return Memory.mem_alloc(size ? size : 1, "C++ NEW"); } +IC void operator delete[](void* p) { xr_free(p); } +# endif #else // DEBUG_MEMORY_NAME -# if !(defined(__BORLANDC__) || defined(NO_XRNEW)) - IC void* operator new (size_t size) { return Memory.mem_alloc(size?size:1); } - IC void operator delete (void *p) { xr_free(p); } - IC void* operator new[] (size_t size) { return Memory.mem_alloc(size?size:1); } - IC void operator delete[] (void* p) { xr_free(p); } -# endif +# if !(defined(__BORLANDC__) || defined(NO_XRNEW)) +IC void* operator new (size_t size) { return Memory.mem_alloc(size?size:1); } +IC void operator delete (void* p) { xr_free(p); } +IC void* operator new[] (size_t size) { return Memory.mem_alloc(size?size:1); } +IC void operator delete[] (void* p) { xr_free(p); } +# endif #endif // DEBUG_MEMORY_MANAGER // POOL-ing -const u32 mem_pools_count = 54; -const u32 mem_pools_ebase = 16; -const u32 mem_generic = mem_pools_count+1; -extern MEMPOOL mem_pools [mem_pools_count]; -extern BOOL mem_initialized; - -XRCORE_API void vminfo (size_t *_free, size_t *reserved, size_t *committed); -XRCORE_API void log_vminfo (); +const u32 mem_pools_count = 54; +const u32 mem_pools_ebase = 16; +const u32 mem_generic = mem_pools_count + 1; +extern MEMPOOL mem_pools[mem_pools_count]; +extern BOOL mem_initialized; + +XRCORE_API void vminfo(size_t* _free, size_t* reserved, size_t* committed); +XRCORE_API void log_vminfo(); #endif // xrMemoryH \ No newline at end of file diff --git a/src/xrCore/xrMemory_POOL.cpp b/src/xrCore/xrMemory_POOL.cpp index ff3252383ea..f88fbbefa9c 100644 --- a/src/xrCore/xrMemory_POOL.cpp +++ b/src/xrCore/xrMemory_POOL.cpp @@ -4,29 +4,29 @@ #include "xrMemory_POOL.h" #include "xrMemory_align.h" -void MEMPOOL::block_create () +void MEMPOOL::block_create() { - // Allocate - R_ASSERT (0==list); - list = (u8*) xr_aligned_offset_malloc (s_sector,16,s_offset); + // Allocate + R_ASSERT(0 == list); + list = (u8*)xr_aligned_offset_malloc(s_sector, 16, s_offset); - // Partition - for (u32 it=0; it<(s_count-1); it++) - { - u8* E = list + it*s_element; - *access(E) = E+s_element; - } - *access (list+(s_count-1)*s_element) = NULL; - block_count ++; + // Partition + for (u32 it = 0; it < (s_count - 1); it++) + { + u8* E = list + it*s_element; + *access(E) = E + s_element; + } + *access(list + (s_count - 1)*s_element) = NULL; + block_count++; } -void MEMPOOL::_initialize (u32 _element, u32 _sector, u32 _header) +void MEMPOOL::_initialize(u32 _element, u32 _sector, u32 _header) { - R_ASSERT (_element < _sector/2); - s_sector = _sector; - s_element = _element; - s_count = s_sector/s_element; - s_offset = _header; - list = NULL; - block_count = 0; + R_ASSERT(_element < _sector / 2); + s_sector = _sector; + s_element = _element; + s_count = s_sector / s_element; + s_offset = _header; + list = NULL; + block_count = 0; } diff --git a/src/xrCore/xrMemory_align.cpp b/src/xrCore/xrMemory_align.cpp index 0488198f3e8..1b97b43cdbd 100644 --- a/src/xrCore/xrMemory_align.cpp +++ b/src/xrCore/xrMemory_align.cpp @@ -20,11 +20,11 @@ * *******************************************************************************/ -#define IS_2_POW_N(X) (((X)&(X-1)) == 0) -#define PTR_SZ sizeof(void *) +#define IS_2_POW_N(X) (((X)&(X-1)) == 0) +#define PTR_SZ sizeof(void *) #ifdef __BORLANDC__ - typedef _W64 unsigned int uintptr_t; +typedef _W64 unsigned int uintptr_t; #endif /*** * @@ -57,12 +57,9 @@ * Faliure: Null *******************************************************************************/ -void * __stdcall xr_aligned_malloc( - size_t size, - size_t alignment - ) +void* __stdcall xr_aligned_malloc(size_t size, size_t alignment) { - return xr_aligned_offset_malloc(size, alignment, 0); + return xr_aligned_offset_malloc(size, alignment, 0); } /*** @@ -85,34 +82,30 @@ void * __stdcall xr_aligned_malloc( *******************************************************************************/ -void * __stdcall xr_aligned_offset_malloc( - size_t size, - size_t align, - size_t offset - ) +void* __stdcall xr_aligned_offset_malloc(size_t size, size_t align, size_t offset) { - uintptr_t ptr, retptr, gap; + uintptr_t ptr, retptr, gap; - if (!IS_2_POW_N(align)) - { - errno = EINVAL; - return NULL; - } - if ( offset >= size && offset != 0) - size = offset+1; + if (!IS_2_POW_N(align)) + { + errno = EINVAL; + return NULL; + } + if (offset >= size && offset != 0) + size = offset + 1; - align = (align > PTR_SZ ? align : PTR_SZ) -1; + align = (align > PTR_SZ ? align : PTR_SZ) - 1; - /* gap = number of bytes needed to round up offset to align with PTR_SZ*/ - gap = (0 - offset)&(PTR_SZ -1); + /* gap = number of bytes needed to round up offset to align with PTR_SZ*/ + gap = (0 - offset)&(PTR_SZ - 1); - if ( (ptr =(uintptr_t)malloc(PTR_SZ +gap +align +size)) == (uintptr_t)NULL) - return NULL; + if ((ptr = (uintptr_t)malloc(PTR_SZ + gap + align + size)) == (uintptr_t)NULL) + return NULL; - retptr =((ptr +PTR_SZ +gap +align +offset)&~align)- offset; - ((uintptr_t *)(retptr - gap))[-1] = ptr; + retptr = ((ptr + PTR_SZ + gap + align + offset)&~align) - offset; + ((uintptr_t*)(retptr - gap))[-1] = ptr; - return (void *)retptr; + return (void*)retptr; } /*** @@ -140,13 +133,9 @@ void * __stdcall xr_aligned_offset_malloc( * *******************************************************************************/ -void * __stdcall xr_aligned_realloc( - void *memblock, - size_t size, - size_t alignment - ) +void* __stdcall xr_aligned_realloc(void* memblock, size_t size, size_t alignment) { - return xr_aligned_offset_realloc(memblock, size, alignment, 0); + return xr_aligned_offset_realloc(memblock, size, alignment, 0); } @@ -176,98 +165,93 @@ void * __stdcall xr_aligned_realloc( * *******************************************************************************/ -void * __stdcall xr_aligned_offset_realloc( - void *memblock, - size_t size, - size_t align, - size_t offset - ) +void* __stdcall xr_aligned_offset_realloc(void* memblock, size_t size, size_t align, size_t offset) { - uintptr_t ptr, retptr, gap, stptr, diff; - uintptr_t movsz, reqsz; - int bFree = 0; - - if (memblock == NULL) - { - return xr_aligned_offset_malloc(size, align, offset); - } - if ( size == 0) - { - xr_aligned_free(memblock); - return NULL; - } - if ( offset >= size && offset != 0) - { - errno = EINVAL; - return NULL; - } - - stptr = (uintptr_t)memblock; - - /* ptr points to the pointer to starting of the memory block */ - stptr = (stptr & ~(PTR_SZ -1)) - PTR_SZ; - - /* ptr is the pointer to the start of memory block*/ - stptr = *((uintptr_t *)stptr); - - if (!IS_2_POW_N(align)) - { - errno = EINVAL; - return NULL; - } - - align = (align > PTR_SZ ? align : PTR_SZ) -1; - /* gap = number of bytes needed to round up offset to align with PTR_SZ*/ - gap = (0 -offset)&(PTR_SZ -1); - - diff = (uintptr_t)memblock - stptr; - /* Mov size is min of the size of data available and sizw requested. - */ - movsz = _msize((void *)stptr) - ((uintptr_t)memblock - stptr); - movsz = movsz > size? size: movsz; - reqsz = PTR_SZ +gap +align +size; - - /* First check if we can expand(reducing or expanding using expand) data - * safely, ie no data is lost. eg, reducing alignment and keeping size - * same might result in loss of data at the tail of data block while - * expanding. - * - * If no, use malloc to allocate the new data and move data. - * - * If yes, expand and then check if we need to move the data. - */ - if ((stptr +align +PTR_SZ +gap)<(uintptr_t)memblock) - { - if ((ptr = (uintptr_t)malloc(reqsz)) == (uintptr_t) NULL) - return NULL; - bFree = 1; - } - else - { - if ((ptr = (uintptr_t)_expand((void *)stptr, reqsz)) == (uintptr_t)NULL) - { - if ((ptr = (uintptr_t)malloc(reqsz)) == (uintptr_t) NULL) - return NULL; - bFree = 1; - } - else - stptr = ptr; - } - - - if ( ptr == ((uintptr_t)memblock - diff) - && !( ((size_t)memblock + gap +offset) & ~(align) )) - { - return memblock; - } - - retptr =((ptr +PTR_SZ +gap +align +offset)&~align)- offset; - memmove((void *)retptr, (void *)(stptr + diff), movsz); - if ( bFree) - free ((void *)stptr); - - ((uintptr_t *)(retptr - gap))[-1] = ptr; - return (void *)retptr; + uintptr_t ptr, retptr, gap, stptr, diff; + uintptr_t movsz, reqsz; + int bFree = 0; + + if (memblock == NULL) + { + return xr_aligned_offset_malloc(size, align, offset); + } + if (size == 0) + { + xr_aligned_free(memblock); + return NULL; + } + if (offset >= size && offset != 0) + { + errno = EINVAL; + return NULL; + } + + stptr = (uintptr_t)memblock; + + /* ptr points to the pointer to starting of the memory block */ + stptr = (stptr & ~(PTR_SZ - 1)) - PTR_SZ; + + /* ptr is the pointer to the start of memory block*/ + stptr = *((uintptr_t*)stptr); + + if (!IS_2_POW_N(align)) + { + errno = EINVAL; + return NULL; + } + + align = (align > PTR_SZ ? align : PTR_SZ) - 1; + /* gap = number of bytes needed to round up offset to align with PTR_SZ*/ + gap = (0 - offset)&(PTR_SZ - 1); + + diff = (uintptr_t)memblock - stptr; + /* Mov size is min of the size of data available and sizw requested. + */ + movsz = _msize((void*)stptr) - ((uintptr_t)memblock - stptr); + movsz = movsz > size ? size : movsz; + reqsz = PTR_SZ + gap + align + size; + + /* First check if we can expand(reducing or expanding using expand) data + * safely, ie no data is lost. eg, reducing alignment and keeping size + * same might result in loss of data at the tail of data block while + * expanding. + * + * If no, use malloc to allocate the new data and move data. + * + * If yes, expand and then check if we need to move the data. + */ + if ((stptr + align + PTR_SZ + gap) < (uintptr_t)memblock) + { + if ((ptr = (uintptr_t)malloc(reqsz)) == (uintptr_t)NULL) + return NULL; + bFree = 1; + } + else + { + if ((ptr = (uintptr_t)_expand((void*)stptr, reqsz)) == (uintptr_t)NULL) + { + if ((ptr = (uintptr_t)malloc(reqsz)) == (uintptr_t)NULL) + return NULL; + bFree = 1; + } + else + stptr = ptr; + } + + + if (ptr == ((uintptr_t)memblock - diff) + && !(((size_t)memblock + gap + offset) & ~(align))) + { + return memblock; + } + + retptr = ((ptr + PTR_SZ + gap + align + offset)&~align) - offset; + memmove((void*)retptr, (void*)(stptr + diff), movsz); + if (bFree) + free((void*)stptr); + + ((uintptr_t*)(retptr - gap))[-1] = ptr; + return (void*)retptr; } @@ -286,36 +270,36 @@ void * __stdcall xr_aligned_offset_realloc( * *******************************************************************************/ -void __stdcall xr_aligned_free(void *memblock) +void __stdcall xr_aligned_free(void* memblock) { - uintptr_t ptr; + uintptr_t ptr; - if (memblock == NULL) - return; + if (memblock == NULL) + return; - ptr = (uintptr_t)memblock; + ptr = (uintptr_t)memblock; - /* ptr points to the pointer to starting of the memory block */ - ptr = (ptr & ~(PTR_SZ -1)) - PTR_SZ; + /* ptr points to the pointer to starting of the memory block */ + ptr = (ptr & ~(PTR_SZ - 1)) - PTR_SZ; - /* ptr is the pointer to the start of memory block*/ - ptr = *((uintptr_t *)ptr); - free((void *)ptr); + /* ptr is the pointer to the start of memory block*/ + ptr = *((uintptr_t*)ptr); + free((void*)ptr); } -u32 __stdcall xr_aligned_msize(void *memblock) +u32 __stdcall xr_aligned_msize(void* memblock) { - uintptr_t ptr; + uintptr_t ptr; - if (memblock == NULL) - return 0; + if (memblock == NULL) + return 0; - ptr = (uintptr_t)memblock; + ptr = (uintptr_t)memblock; - /* ptr points to the pointer to starting of the memory block */ - ptr = (ptr & ~(PTR_SZ -1)) - PTR_SZ; + /* ptr points to the pointer to starting of the memory block */ + ptr = (ptr & ~(PTR_SZ - 1)) - PTR_SZ; - /* ptr is the pointer to the start of memory block*/ - ptr = *((uintptr_t *)ptr); - return (u32) _msize ((void *)ptr); + /* ptr is the pointer to the start of memory block*/ + ptr = *((uintptr_t*)ptr); + return (u32)_msize((void*)ptr); } diff --git a/src/xrCore/xrMemory_align.h b/src/xrCore/xrMemory_align.h index 7a09e3fac9d..918a4d92cf3 100644 --- a/src/xrCore/xrMemory_align.h +++ b/src/xrCore/xrMemory_align.h @@ -2,11 +2,11 @@ #define xrMemory_alignH #pragma once -u32 __stdcall xr_aligned_msize(void *); -void __stdcall xr_aligned_free(void *); -void * __stdcall xr_aligned_malloc(size_t, size_t); -void * __stdcall xr_aligned_offset_malloc(size_t, size_t, size_t); -void * __stdcall xr_aligned_realloc(void *, size_t, size_t); -void * __stdcall xr_aligned_offset_realloc(void *, size_t, size_t, size_t); +u32 __stdcall xr_aligned_msize(void*); +void __stdcall xr_aligned_free(void*); +void* __stdcall xr_aligned_malloc(size_t, size_t); +void* __stdcall xr_aligned_offset_malloc(size_t, size_t, size_t); +void* __stdcall xr_aligned_realloc(void*, size_t, size_t); +void* __stdcall xr_aligned_offset_realloc(void*, size_t, size_t, size_t); #endif \ No newline at end of file diff --git a/src/xrCore/xrMemory_debug.cpp b/src/xrCore/xrMemory_debug.cpp index d65e28b1ae7..855426fed7f 100644 --- a/src/xrCore/xrMemory_debug.cpp +++ b/src/xrCore/xrMemory_debug.cpp @@ -2,174 +2,180 @@ #pragma hdrstop #ifndef DEBUG_MEMORY_MANAGER -void xrMemory::dbg_register (void* _p, size_t _size, const char* _name) { } -void xrMemory::dbg_unregister (void* _p) { } -void xrMemory::dbg_check () { } +void xrMemory::dbg_register(void* _p, size_t _size, const char* _name) { } +void xrMemory::dbg_unregister(void* _p) { } +void xrMemory::dbg_check() { } #else // DEBUG_MEMORY_MANAGER -# if 0 -# define DEBUG_MEMORY_LEAK -# define MEMORY_LEAK_DESCRIPTION "C++ NEW" -//# define MEMORY_LEAK_DESCRIPTION "class luabind::functor" -# define MEMORY_LEAK_SIZE 12 -# endif +# if 0 +# define DEBUG_MEMORY_LEAK +# define MEMORY_LEAK_DESCRIPTION "C++ NEW" +//# define MEMORY_LEAK_DESCRIPTION "class luabind::functor" +# define MEMORY_LEAK_SIZE 12 +# endif #include -bool pred_mdbg (const xrMemory::mdbg& A) { - return (0==A._p && 0==A._size); +bool pred_mdbg(const xrMemory::mdbg& A) +{ + return (0 == A._p && 0 == A._size); } -extern u32 get_header (void* P); -extern u32 get_pool (size_t size); -BOOL g_bDbgFillMemory = true; +extern u32 get_header(void* P); +extern u32 get_pool(size_t size); +BOOL g_bDbgFillMemory = true; -void dbg_header (xrMemory::mdbg& dbg, bool _debug) +void dbg_header(xrMemory::mdbg& dbg, bool _debug) { - //. check header - u32 t1 = get_header (dbg._p); - u32 t2 = get_pool (1+dbg._size+(_debug?4:0)); - R_ASSERT2 (t1==t2,"CorePanic: Memory block header corrupted"); + //. check header + u32 t1 = get_header(dbg._p); + u32 t2 = get_pool(1 + dbg._size + (_debug ? 4 : 0)); + R_ASSERT2(t1 == t2, "CorePanic: Memory block header corrupted"); } -void xrMemory::dbg_register (void* _p, size_t _size, const char* _name) +void xrMemory::dbg_register(void* _p, size_t _size, const char* _name) { #ifdef DEBUG_MEMORY_LEAK - if ((_size == MEMORY_LEAK_SIZE) && _name &&!xr_strcmp(MEMORY_LEAK_DESCRIPTION,_name)) { - static int i = 0; - string2048 temp; - xr_sprintf (temp,sizeof(temp),"____[%s][%d] : 0x%8x [REGISTER][%d]\n",_name,_size,(u32)((size_t)_p),i++); - OutputDebugString (temp); - } + if ((_size == MEMORY_LEAK_SIZE) && _name &&!xr_strcmp(MEMORY_LEAK_DESCRIPTION, _name)) + { + static int i = 0; + string2048 temp; + xr_sprintf(temp, sizeof(temp), "____[%s][%d] : 0x%8x [REGISTER][%d]\n", _name, _size, (u32)((size_t)_p), i++); + OutputDebugString(temp); + } #endif - VERIFY (debug_mode); - debug_cs.Enter (); - debug_mode = FALSE; - - // register + mark - mdbg dbg = { _p,_size,_name, 0 }; - dbg_header (dbg,true); - debug_info.push_back (dbg); - u8* _ptr = (u8*) _p; - u32* _shred = (u32*)(_ptr + _size); - *_shred = u32 (-1); - dbg_header (dbg,true); - - debug_mode = TRUE; - debug_cs.Leave (); + VERIFY(debug_mode); + debug_cs.Enter(); + debug_mode = FALSE; + + // register + mark + mdbg dbg = {_p, _size, _name, 0}; + dbg_header(dbg, true); + debug_info.push_back(dbg); + u8* _ptr = (u8*)_p; + u32* _shred = (u32*)(_ptr + _size); + *_shred = u32(-1); + dbg_header(dbg, true); + + debug_mode = TRUE; + debug_cs.Leave(); } -void xrMemory::dbg_unregister (void* _p) +void xrMemory::dbg_unregister(void* _p) { - VERIFY (debug_mode); - debug_cs.Enter (); - debug_mode = FALSE; - - // search entry - u32 _found = u32(-1); - - if (!debug_info.empty()) - { - for (int it=int(debug_info.size()-1); it>=0; it--) - if (debug_info[it]._p==_p) { _found=it; break; } - } - - // unregister entry - if (u32(-1)==_found) { - FATAL ("Memory allocation error: double free() ?"); - } else { + VERIFY(debug_mode); + debug_cs.Enter(); + debug_mode = FALSE; + + // search entry + u32 _found = u32(-1); + + if (!debug_info.empty()) + { + for (int it = int(debug_info.size() - 1); it >= 0; it--) + if (debug_info[it]._p == _p) { _found = it; break; } + } + + // unregister entry + if (u32(-1) == _found) + { + FATAL("Memory allocation error: double free() ?"); + } + else + { #ifdef DEBUG_MEMORY_LEAK - if ((debug_info[_found]._size == MEMORY_LEAK_SIZE) && debug_info[_found]._name && !xr_strcmp(MEMORY_LEAK_DESCRIPTION,debug_info[_found]._name)) { - string2048 temp; - xr_sprintf (temp,sizeof(temp),"____[%s][%d] : 0x%8x [UNREGISTER]\n",debug_info[_found]._name,debug_info[_found]._size,(u32)((size_t)_p)); - OutputDebugString (temp); - } + if ((debug_info[_found]._size == MEMORY_LEAK_SIZE) && debug_info[_found]._name && !xr_strcmp(MEMORY_LEAK_DESCRIPTION, debug_info[_found]._name)) + { + string2048 temp; + xr_sprintf(temp, sizeof(temp), "____[%s][%d] : 0x%8x [UNREGISTER]\n", debug_info[_found]._name, debug_info[_found]._size, (u32)((size_t)_p)); + OutputDebugString(temp); + } #endif - u8* _ptr = (u8*) debug_info[_found]._p; - u32* _shred = (u32*)(_ptr + debug_info[_found]._size); - R_ASSERT2 (u32(-1)==*_shred, "Memory overrun error"); - - // fill free memory with random data - if (g_bDbgFillMemory) - memset (debug_info[_found]._p,'C',debug_info[_found]._size); - - // clear record - std::swap (debug_info[_found],debug_info.back()); - debug_info.pop_back (); - debug_info_update ++; - } - - // perform cleanup - if (debug_info_update>1024*100) - { - debug_info_update = 0; - debug_info.erase (std::remove_if(debug_info.begin(),debug_info.end(),pred_mdbg),debug_info.end()); - dbg_check (); - } - - debug_mode = TRUE; - debug_cs.Leave (); + u8* _ptr = (u8*)debug_info[_found]._p; + u32* _shred = (u32*)(_ptr + debug_info[_found]._size); + R_ASSERT2(u32(-1) == *_shred, "Memory overrun error"); + + // fill free memory with random data + if (g_bDbgFillMemory) + memset(debug_info[_found]._p, 'C', debug_info[_found]._size); + + // clear record + std::swap(debug_info[_found], debug_info.back()); + debug_info.pop_back(); + debug_info_update++; + } + + // perform cleanup + if (debug_info_update > 1024 * 100) + { + debug_info_update = 0; + debug_info.erase(std::remove_if(debug_info.begin(), debug_info.end(), pred_mdbg), debug_info.end()); + dbg_check(); + } + + debug_mode = TRUE; + debug_cs.Leave(); } -void xrMemory::dbg_check () +void xrMemory::dbg_check() { - if (!debug_mode) return; - - // Check RO strings - if (g_pStringContainer) g_pStringContainer->verify (); - - // Check overrun - debug_cs.Enter (); - debug_mode = FALSE; - for (int it=0; itverify(); + + // Check overrun + debug_cs.Enter(); + debug_mode = FALSE; + for (int it = 0; itdump(); + g_pStringContainer->dump(); } #endif // DEBUG_MEMORY_MANAGER \ No newline at end of file diff --git a/src/xrCore/xrMemory_pso.h b/src/xrCore/xrMemory_pso.h index a883beae22b..d890c7951a8 100644 --- a/src/xrCore/xrMemory_pso.h +++ b/src/xrCore/xrMemory_pso.h @@ -2,7 +2,7 @@ #define xrMemory_psoH #pragma once -typedef void __stdcall pso_MemFill (void* dest, int value, u32 count); -typedef void __stdcall pso_MemFill32 (void* dest, u32 value, u32 count); -typedef void __stdcall pso_MemCopy (void* dest, const void* src, u32 count); +typedef void __stdcall pso_MemFill(void* dest, int value, u32 count); +typedef void __stdcall pso_MemFill32(void* dest, u32 value, u32 count); +typedef void __stdcall pso_MemCopy(void* dest, const void* src, u32 count); #endif diff --git a/src/xrCore/xrMemory_pso_Copy.cpp b/src/xrCore/xrMemory_pso_Copy.cpp index 45ba103d662..4ef93724c28 100644 --- a/src/xrCore/xrMemory_pso_Copy.cpp +++ b/src/xrCore/xrMemory_pso_Copy.cpp @@ -2,223 +2,224 @@ #pragma hdrstop #pragma warning(disable:4995) -void __stdcall xrMemCopy_x86 (LPVOID dest, const void* src, u32 n) +void __stdcall xrMemCopy_x86(LPVOID dest, const void* src, u32 n) { - memcpy (dest,src,n); + memcpy(dest, src, n); } #if defined(M_BORLAND) || defined(_M_AMD64) -void __stdcall xrMemCopy_MMX (LPVOID dest, const void* src, u32 n) +void __stdcall xrMemCopy_MMX (LPVOID dest, const void* src, u32 n) { - memcpy (dest,src,n); + memcpy (dest,src,n); } #else //------------------------------------------------------------------------------------------------- -#define TINY_BLOCK_COPY 64 //upper limit for movsd type copy +#define TINY_BLOCK_COPY 64 //upper limit for movsd type copy //The smallest copy uses the X86 "movsd"instruction,in an optimized //form which is an "unrolled loop". -#define IN_CACHE_COPY 64 *1024 //upper limit for movq/movq copy w/SW prefetch +#define IN_CACHE_COPY 64 *1024 //upper limit for movq/movq copy w/SW prefetch //Next is a copy that uses the MMX registers to copy 8 bytes at a time, //also using the "unrolled loop"optimization.This code uses //the software prefetch instruction to get the data into the cache. -#define UNCACHED_COPY 197 *1024 //upper limit for movq/movntq w/SW prefetch +#define UNCACHED_COPY 197 *1024 //upper limit for movq/movntq w/SW prefetch //For larger blocks,which will spill beyond the cache,it ’s faster to //use the Streaming Store instruction MOVNTQ.This write instruction //bypasses the cache and writes straight to main memory.This code also //uses the software prefetch instruction to pre-read the data. //USE 64 *1024 FOR THIS VALUE IF YOU ’RE ALWAYS FILLING A "CLEAN CACHE" -#define BLOCK_PREFETCH_COPY infinity //no limit for movq/movntq w/block prefetch -#define CACHEBLOCK 80h //#of 64-byte blocks (cache lines)for block prefetch +#define BLOCK_PREFETCH_COPY infinity //no limit for movq/movntq w/block prefetch +#define CACHEBLOCK 80h //#of 64-byte blocks (cache lines)for block prefetch //For the largest size blocks,a special technique called Block Prefetch //can be used to accelerate the read operations.Block Prefetch reads //one address per cache line,for a series of cache lines,in a short loop. //This is faster than using software prefetch.The technique is great for //getting maximum read bandwidth,especially in DDR memory systems. -void __stdcall xrMemCopy_MMX (LPVOID dest, const void* src, u32 n) +void __stdcall xrMemCopy_MMX(LPVOID dest, const void* src, u32 n) { - __asm { - mov ecx,[n ]; // number of bytes to copy - mov edi,[dest ]; // destination - mov esi,[src ]; // source - mov ebx,ecx; // keep a copy of count - cld; - cmp ecx,TINY_BLOCK_COPY; - jb $memcpy_ic_3; // tiny?skip mmx copy - cmp ecx,32*1024; // don ’t align between 32k-64k because - jbe $memcpy_do_align; // it appears to be slower - cmp ecx,64*1024; - jbe $memcpy_align_done; + __asm + { + mov ecx, [n]; // number of bytes to copy + mov edi, [dest]; // destination + mov esi, [src]; // source + mov ebx, ecx; // keep a copy of count + cld; + cmp ecx, TINY_BLOCK_COPY; + jb $memcpy_ic_3; // tiny?skip mmx copy + cmp ecx, 32 * 1024; // don ’t align between 32k-64k because + jbe $memcpy_do_align; // it appears to be slower + cmp ecx, 64 * 1024; + jbe $memcpy_align_done; -$memcpy_do_align: - mov ecx,8; // a trick that ’s faster than rep movsb... - sub ecx,edi; // align destination to qword - and ecx,111b; // get the low bits - sub ebx,ecx; // update copy count - neg ecx; // set up to jump into the array - add ecx,offset $memcpy_align_done; - jmp ecx; // jump to array of movsb ’s - align 4; - movsb; - movsb; - movsb; - movsb; - movsb; - movsb; - movsb; - movsb; -$memcpy_align_done: // destination is dword aligned - mov ecx,ebx; // number of bytes left to copy - shr ecx,6; // get 64-byte block count - jz $memcpy_ic_2; // finish the last few bytes - cmp ecx,IN_CACHE_COPY/64; // too big 4 cache?use uncached copy - jae $memcpy_uc_test; + $memcpy_do_align: + mov ecx, 8; // a trick that ’s faster than rep movsb... + sub ecx, edi; // align destination to qword + and ecx, 111b; // get the low bits + sub ebx, ecx; // update copy count + neg ecx; // set up to jump into the array + add ecx, offset $memcpy_align_done; + jmp ecx; // jump to array of movsb ’s + align 4; + movsb; + movsb; + movsb; + movsb; + movsb; + movsb; + movsb; + movsb; + $memcpy_align_done: // destination is dword aligned + mov ecx, ebx; // number of bytes left to copy + shr ecx, 6; // get 64-byte block count + jz $memcpy_ic_2; // finish the last few bytes + cmp ecx, IN_CACHE_COPY / 64; // too big 4 cache?use uncached copy + jae $memcpy_uc_test; - //This is small block copy that uses the MMX registers to copy 8 bytes - //at a time.It uses the "unrolled loop"optimization,and also uses - //the software prefetch instruction to get the data into the cache. - align 16; -$memcpy_ic_1: // 64-byte block copies, in-cache copy - prefetchnta [esi +(200*64/34+192)]; // start reading ahead - movq mm0,[esi+0 ]; // read 64 bits - movq mm1,[esi+8 ]; - movq [edi+0 ],mm0; // write 64 bits - movq [edi+8 ],mm1; // note:the normal movq writes the - movq mm2,[esi+16 ]; // data to cache;a cache line will be - movq mm3,[esi+24 ]; // allocated as needed,to store the data - movq [edi+16 ],mm2; - movq [edi+24 ],mm3; - movq mm0,[esi+32 ]; - movq mm1,[esi+40 ]; - movq [edi+32 ],mm0; - movq [edi+40 ],mm1; - movq mm2,[esi+48 ]; - movq mm3,[esi+56 ]; - movq [edi+48 ],mm2; - movq [edi+56 ],mm3; - add esi,64 ; // update source pointer - add edi,64 ; // update destination pointer - dec ecx ; // count down - jnz $memcpy_ic_1; // last 64-byte block? + //This is small block copy that uses the MMX registers to copy 8 bytes + //at a time.It uses the "unrolled loop"optimization,and also uses + //the software prefetch instruction to get the data into the cache. + align 16; + $memcpy_ic_1: // 64-byte block copies, in-cache copy + prefetchnta[esi + (200 * 64 / 34 + 192)]; // start reading ahead + movq mm0, [esi + 0]; // read 64 bits + movq mm1, [esi + 8]; + movq[edi + 0], mm0; // write 64 bits + movq[edi + 8], mm1; // note:the normal movq writes the + movq mm2, [esi + 16]; // data to cache;a cache line will be + movq mm3, [esi + 24]; // allocated as needed,to store the data + movq[edi + 16], mm2; + movq[edi + 24], mm3; + movq mm0, [esi + 32]; + movq mm1, [esi + 40]; + movq[edi + 32], mm0; + movq[edi + 40], mm1; + movq mm2, [esi + 48]; + movq mm3, [esi + 56]; + movq[edi + 48], mm2; + movq[edi + 56], mm3; + add esi, 64; // update source pointer + add edi, 64; // update destination pointer + dec ecx; // count down + jnz $memcpy_ic_1; // last 64-byte block? -$memcpy_ic_2: - mov ecx,ebx ; // has valid low 6 bits of the byte count -$memcpy_ic_3: - shr ecx,2 ; // dword count - and ecx,1111b ; // only look at the "remainder"bits - neg ecx ; // set up to jump into the array - add ecx,offset $memcpy_last_few; - jmp ecx ; // jump to array of movsd ’s -$memcpy_uc_test: - cmp ecx,UNCACHED_COPY/64; // big enough?use block prefetch copy - jae $memcpy_bp_1; -$memcpy_64_test: - or ecx,ecx; // tail end of block prefetch will jump here - jz $memcpy_ic_2; // no more 64-byte blocks left + $memcpy_ic_2: + mov ecx, ebx; // has valid low 6 bits of the byte count + $memcpy_ic_3: + shr ecx, 2; // dword count + and ecx, 1111b; // only look at the "remainder"bits + neg ecx; // set up to jump into the array + add ecx, offset $memcpy_last_few; + jmp ecx; // jump to array of movsd ’s + $memcpy_uc_test: + cmp ecx, UNCACHED_COPY / 64; // big enough?use block prefetch copy + jae $memcpy_bp_1; + $memcpy_64_test: + or ecx, ecx; // tail end of block prefetch will jump here + jz $memcpy_ic_2; // no more 64-byte blocks left - //For larger blocks,which will spill beyond the cache,it ’s faster to - //use the Streaming Store instruction MOVNTQ.This write instruction - //bypasses the cache and writes straight to main memory.This code also - //uses the software prefetch instruction to pre-read the data. + //For larger blocks,which will spill beyond the cache,it ’s faster to + //use the Streaming Store instruction MOVNTQ.This write instruction + //bypasses the cache and writes straight to main memory.This code also + //uses the software prefetch instruction to pre-read the data. - align 16 -$memcpy_uc_1: // ;64-byte blocks,uncached copy - prefetchnta [esi +(200*64/34+192)]; // start reading ahead - movq mm0,[esi+0 ]; // read 64 bits - add edi,64 ; // update destination pointer - movq mm1,[esi+8 ]; - add esi,64 ; // update source pointer - movq mm2,[esi-48 ]; - movntq [edi-64 ],mm0; // write 64 bits,bypassing the cache - movq mm0,[esi-40 ]; // note:movntq also prevents the CPU - movntq [edi-56 ],mm1; // from READING the destination address - movq mm1,[esi-32 ]; // into the cache,only to be over-written - movntq [edi-48 ],mm2; // so that also helps performance - movq mm2,[esi-24 ]; - movntq [edi-40 ],mm0; - movq mm0,[esi-16 ]; - movntq [edi-32 ],mm1; - movq mm1,[esi-8 ]; - movntq [edi-24 ],mm2; - movntq [edi-16 ],mm0; - dec ecx - movntq [edi-8 ],mm1; - jnz $memcpy_uc_1; // last 64-byte block? - jmp $memcpy_ic_2; // almost dont + align 16 + $memcpy_uc_1: // ;64-byte blocks,uncached copy + prefetchnta[esi + (200 * 64 / 34 + 192)]; // start reading ahead + movq mm0, [esi + 0]; // read 64 bits + add edi, 64; // update destination pointer + movq mm1, [esi + 8]; + add esi, 64; // update source pointer + movq mm2, [esi - 48]; + movntq[edi - 64], mm0; // write 64 bits,bypassing the cache + movq mm0, [esi - 40]; // note:movntq also prevents the CPU + movntq[edi - 56], mm1; // from READING the destination address + movq mm1, [esi - 32]; // into the cache,only to be over-written + movntq[edi - 48], mm2; // so that also helps performance + movq mm2, [esi - 24]; + movntq[edi - 40], mm0; + movq mm0, [esi - 16]; + movntq[edi - 32], mm1; + movq mm1, [esi - 8]; + movntq[edi - 24], mm2; + movntq[edi - 16], mm0; + dec ecx + movntq[edi - 8], mm1; + jnz $memcpy_uc_1; // last 64-byte block? + jmp $memcpy_ic_2; // almost dont - //For the largest size blocks,a special technique called Block Prefetch - //can be used to accelerate the read operations.Block Prefetch reads - //one address per cache line,for a series of cache lines,in a short loop. - //This is faster than using software prefetch.The technique is great for - //getting maximum read bandwidth,especially in DDR memory systems. + //For the largest size blocks,a special technique called Block Prefetch + //can be used to accelerate the read operations.Block Prefetch reads + //one address per cache line,for a series of cache lines,in a short loop. + //This is faster than using software prefetch.The technique is great for + //getting maximum read bandwidth,especially in DDR memory systems. -$memcpy_bp_1: // large blocks,block prefetch copy - cmp ecx,CACHEBLOCK; // big enough to run another prefetch loop? - jl $memcpy_64_test; // no,back to regular uncached copy - mov eax,CACHEBLOCK /2; // block prefetch loop,unrolled 2X - add esi,CACHEBLOCK *64; // move to the top of the block - align 16; -$memcpy_bp_2: - mov edx,[esi-64 ]; // grab one address per cache line - mov edx,[esi-128 ]; // grab one address per cache line - sub esi,128 ; // go reverse order to suppress HW prefetcher - dec eax ; // count down the cache lines - jnz $memcpy_bp_2; // keep grabbing more lines into cache - mov eax,CACHEBLOCK; // now that it ’s in cache,do the copy - align 16; -$memcpy_bp_3: - movq mm0,[esi ]; // read 64 bits - movq mm1,[esi+8 ]; - movq mm2,[esi+16 ]; - movq mm3,[esi+24 ]; - movq mm4,[esi+32 ]; - movq mm5,[esi+40 ]; - movq mm6,[esi+48 ]; - movq mm7,[esi+56 ]; - add esi,64 ; // update source pointer - movntq [edi ],mm0; // write 64 bits,bypassing cache - movntq [edi+8 ],mm1; // note:movntq also prevents the CPU - movntq [edi+16 ],mm2; // from READING the destination address - movntq [edi+24 ],mm3; // into the cache,only to be over-written, - movntq [edi+32 ],mm4; // so that also helps performance - movntq [edi+40 ],mm5; - movntq [edi+48 ],mm6; - movntq [edi+56 ],mm7; - add edi,64 ; // update dest pointer - dec eax ; // count down - jnz $memcpy_bp_3; // keep copying - sub ecx,CACHEBLOCK; // update the 64-byte block count - jmp $memcpy_bp_1; // keep processing blocks + $memcpy_bp_1: // large blocks,block prefetch copy + cmp ecx, CACHEBLOCK; // big enough to run another prefetch loop? + jl $memcpy_64_test; // no,back to regular uncached copy + mov eax, CACHEBLOCK / 2; // block prefetch loop,unrolled 2X + add esi, CACHEBLOCK * 64; // move to the top of the block + align 16; + $memcpy_bp_2: + mov edx, [esi - 64]; // grab one address per cache line + mov edx, [esi - 128]; // grab one address per cache line + sub esi, 128; // go reverse order to suppress HW prefetcher + dec eax; // count down the cache lines + jnz $memcpy_bp_2; // keep grabbing more lines into cache + mov eax, CACHEBLOCK; // now that it ’s in cache,do the copy + align 16; + $memcpy_bp_3: + movq mm0, [esi]; // read 64 bits + movq mm1, [esi + 8]; + movq mm2, [esi + 16]; + movq mm3, [esi + 24]; + movq mm4, [esi + 32]; + movq mm5, [esi + 40]; + movq mm6, [esi + 48]; + movq mm7, [esi + 56]; + add esi, 64; // update source pointer + movntq[edi], mm0; // write 64 bits,bypassing cache + movntq[edi + 8], mm1; // note:movntq also prevents the CPU + movntq[edi + 16], mm2; // from READING the destination address + movntq[edi + 24], mm3; // into the cache,only to be over-written, + movntq[edi + 32], mm4; // so that also helps performance + movntq[edi + 40], mm5; + movntq[edi + 48], mm6; + movntq[edi + 56], mm7; + add edi, 64; // update dest pointer + dec eax; // count down + jnz $memcpy_bp_3; // keep copying + sub ecx, CACHEBLOCK; // update the 64-byte block count + jmp $memcpy_bp_1; // keep processing blocks - //The smallest copy uses the X86 "movsd"instruction,in an optimized - //form which is an "unrolled loop".Then it handles the last few bytes. - align 4; - movsd; - movsd; // perform last 1-15 dword copies - movsd; - movsd; - movsd; - movsd; - movsd; - movsd; - movsd; - movsd; // perform last 1-7 dword copies - movsd; - movsd; - movsd; - movsd; - movsd; - movsd; + //The smallest copy uses the X86 "movsd"instruction,in an optimized + //form which is an "unrolled loop".Then it handles the last few bytes. + align 4; + movsd; + movsd; // perform last 1-15 dword copies + movsd; + movsd; + movsd; + movsd; + movsd; + movsd; + movsd; + movsd; // perform last 1-7 dword copies + movsd; + movsd; + movsd; + movsd; + movsd; + movsd; -$memcpy_last_few: // dword aligned from before movsd ’s - mov ecx,ebx; // has valid low 2 bits of the byte count - and ecx,11b; // the last few cows must come home - jz $memcpy_final; // no more,let ’s leave - rep movsb; // the last 1,2,or 3 bytes -$memcpy_final: - emms; // clean up the MMX state - sfence; // flush the write buffer - mov eax,[dest ]; // ret value =destination pointer - } + $memcpy_last_few: // dword aligned from before movsd ’s + mov ecx, ebx; // has valid low 2 bits of the byte count + and ecx, 11b; // the last few cows must come home + jz $memcpy_final; // no more,let ’s leave + rep movsb; // the last 1,2,or 3 bytes + $memcpy_final: + emms; // clean up the MMX state + sfence; // flush the write buffer + mov eax, [dest]; // ret value =destination pointer + } } #endif diff --git a/src/xrCore/xrMemory_pso_Fill.cpp b/src/xrCore/xrMemory_pso_Fill.cpp index f649b3a4f70..99b2ebdf24d 100644 --- a/src/xrCore/xrMemory_pso_Fill.cpp +++ b/src/xrCore/xrMemory_pso_Fill.cpp @@ -1,7 +1,7 @@ #include "stdafx.h" #pragma hdrstop -void __stdcall xrMemFill_x86 (void* dest, int value, u32 count) +void __stdcall xrMemFill_x86(void* dest, int value, u32 count) { - memset (dest,int(value),count); + memset(dest, int(value), count); } diff --git a/src/xrCore/xrMemory_pso_Fill32.cpp b/src/xrCore/xrMemory_pso_Fill32.cpp index 5a768c9e11d..88dfcbddac1 100644 --- a/src/xrCore/xrMemory_pso_Fill32.cpp +++ b/src/xrCore/xrMemory_pso_Fill32.cpp @@ -1,78 +1,73 @@ #include "stdafx.h" #pragma hdrstop -void __stdcall xrMemFill32_x86 (LPVOID dest, u32 value, u32 count) +void __stdcall xrMemFill32_x86(LPVOID dest, u32 value, u32 count) { - u32* ptr = (u32*) dest; - u32* end = ptr + count; - for (; ptr!=end; ) *ptr++ = value; + u32* ptr = (u32*)dest; + u32* end = ptr + count; + for (; ptr != end;) *ptr++ = value; } #if defined(M_BORLAND) || defined(_M_AMD64) -void __stdcall xrMemFill32_MMX (LPVOID dest, u32 value, u32 count) +void __stdcall xrMemFill32_MMX(LPVOID dest, u32 value, u32 count) { - u32* ptr = (u32*) dest; - u32* end = ptr + count; - for (; ptr!=end; ) *ptr++ = value; + u32* ptr = (u32*)dest; + u32* end = ptr + count; + for (; ptr != end;) *ptr++ = value; } #else /* block fill:fill a number of DWORDs at DWORD aligned destination with DWORD initializer using cacheable stores */ -void __stdcall xrMemFill32_MMX (LPVOID dest, u32 value, u32 count) +void __stdcall xrMemFill32_MMX(LPVOID dest, u32 value, u32 count) { - __asm { - MOV EDI,[dest]; // pointer to dst,DWORD aligned - MOV ECX,[count ]; // number of DWORDs to copy - MOVD MM0,[value ]; // initialization data - PUNPCKLDQ MM0,MM0; // extend fill data to QWORD - CMP ECX,1; // less than one DWORD to fill ? - JB $filldone2_fc; // yes,must be no DWORDs to fill,done - TEST EDI,7; // dst QWORD aligned? - JZ $dstqaligned2_fc; // yes - MOVD [EDI ],MM0; // store one DWORD to dst - ADD EDI,4 ; // dst++ - DEC ECX ; // number of DWORDs to fill -$dstqaligned2_fc: - MOV EBX,ECX; // number of DWORDs to fill - SHR ECX,4; // number of cache lines to fill - JZ $fillqwords2_fc; // no whole cache lines to fill,maybe QWORDs - ALIGN 16; // align loop for optimal performance -$cloop2_fc: - ADD EDI,64; // dst++ - MOVQ [EDI-64 ],MM0; // store 1st DWORD in cache line to dst - MOVQ [EDI-56 ],MM0; // store 2nd DWORD in cache line to dst - MOVQ [EDI-48 ],MM0; // store 3rd DWORD in cache line to dst - MOVQ [EDI-40 ],MM0; // store 4th DWORD in cache line to dst - MOVQ [EDI-32 ],MM0; // store 5th DWORD in cache line to dst - MOVQ [EDI-24 ],MM0; // store 6th DWORD in cache line to dst - MOVQ [EDI-16 ],MM0; // store 7th DWORD in cache line to dst - DEC ECX; // count-- - MOVQ [EDI -8 ],MM0; // store 8th DWORD in cache line to dst - JNZ $cloop2_fc; // until no more cache lines to copy -$fillqwords2_fc: - MOV ECX,EBX; // number of DWORDs to fill - AND EBX,0xE; // number of QWORDS left to fill *2 - JZ $filldword2_fc; // no QWORDs left,maybe DWORD left - ALIGN 16; // align loop for optimal performance -$qloop2_fc: - MOVQ [EDI ],MM0; // store QWORD to dst - ADD EDI,8; // dst++ - SUB EBX,2; // count-- - JNZ $qloop2_fc; // until no more QWORDs left to copy -$filldword2_fc: - TEST ECX,1; // DWORD left to fill ? - JZ $filldone2_fc; // nope,we ’re done - MOVD [EDI ],MM0; // store last DWORD to dst -$filldone2_fc: - EMMS; // clear MMX state - } + __asm + { + MOV EDI, [dest]; // pointer to dst,DWORD aligned + MOV ECX, [count]; // number of DWORDs to copy + MOVD MM0, [value]; // initialization data + PUNPCKLDQ MM0, MM0; // extend fill data to QWORD + CMP ECX, 1; // less than one DWORD to fill ? + JB $filldone2_fc; // yes,must be no DWORDs to fill,done + TEST EDI, 7; // dst QWORD aligned? + JZ $dstqaligned2_fc; // yes + MOVD [EDI], MM0; // store one DWORD to dst + ADD EDI, 4; // dst++ + DEC ECX; // number of DWORDs to fill + $dstqaligned2_fc: + MOV EBX, ECX; // number of DWORDs to fill + SHR ECX, 4; // number of cache lines to fill + JZ $fillqwords2_fc; // no whole cache lines to fill,maybe QWORDs + ALIGN 16; // align loop for optimal performance + $cloop2_fc: + ADD EDI, 64; // dst++ + MOVQ [EDI - 64], MM0; // store 1st DWORD in cache line to dst + MOVQ [EDI - 56], MM0; // store 2nd DWORD in cache line to dst + MOVQ [EDI - 48], MM0; // store 3rd DWORD in cache line to dst + MOVQ [EDI - 40], MM0; // store 4th DWORD in cache line to dst + MOVQ [EDI - 32], MM0; // store 5th DWORD in cache line to dst + MOVQ [EDI - 24], MM0; // store 6th DWORD in cache line to dst + MOVQ [EDI - 16], MM0; // store 7th DWORD in cache line to dst + DEC ECX; // count-- + MOVQ [EDI - 8], MM0; // store 8th DWORD in cache line to dst + JNZ $cloop2_fc; // until no more cache lines to copy + $fillqwords2_fc: + MOV ECX, EBX; // number of DWORDs to fill + AND EBX, 0xE; // number of QWORDS left to fill *2 + JZ $filldword2_fc; // no QWORDs left,maybe DWORD left + ALIGN 16; // align loop for optimal performance + $qloop2_fc: + MOVQ [EDI], MM0; // store QWORD to dst + ADD EDI, 8; // dst++ + SUB EBX, 2; // count-- + JNZ $qloop2_fc; // until no more QWORDs left to copy + $filldword2_fc: + TEST ECX, 1; // DWORD left to fill ? + JZ $filldone2_fc; // nope,we ’re done + MOVD [EDI], MM0; // store last DWORD to dst + $filldone2_fc: + EMMS; // clear MMX state + } } #endif - - - - - - diff --git a/src/xrCore/xrMemory_pure.h b/src/xrCore/xrMemory_pure.h index 3ce963979f1..8039f8d83ee 100644 --- a/src/xrCore/xrMemory_pure.h +++ b/src/xrCore/xrMemory_pure.h @@ -2,11 +2,11 @@ #define XRMEMORY_PURE_H #ifdef XRCORE_STATIC -# define PURE_ALLOC +#define PURE_ALLOC #else // XRCORE_STATIC -# ifdef DEBUG -# define PURE_ALLOC -# endif // DEBUG +#ifdef DEBUG +#define PURE_ALLOC +#endif // DEBUG #endif // XRCORE_STATIC #endif // XRMEMORY_PURE_H \ No newline at end of file diff --git a/src/xrCore/xrMemory_subst_borland.cpp b/src/xrCore/xrMemory_subst_borland.cpp index b396af71fcd..9f54b84c35c 100644 --- a/src/xrCore/xrMemory_subst_borland.cpp +++ b/src/xrCore/xrMemory_subst_borland.cpp @@ -2,25 +2,25 @@ #pragma hdrstop #ifdef __BORLANDC__ -MEMPOOL mem_pools [mem_pools_count]; +MEMPOOL mem_pools[mem_pools_count]; // Borland doesn't support marked aligned allocs ??? -void* xrMemory::mem_alloc (size_t size) +void* xrMemory::mem_alloc(size_t size) { - if (0==size) size = 1; - void* data = malloc (size); - if(!data) - Debug.fatal (DEBUG_INFO,"Out of memory. Memory request: %d K",size/1024); - return data; + if (0 == size) size = 1; + void* data = malloc(size); + if (!data) + Debug.fatal(DEBUG_INFO, "Out of memory. Memory request: %d K", size / 1024); + return data; } -void xrMemory::mem_free (void* P) +void xrMemory::mem_free(void* P) { - free (P); + free(P); } -void* xrMemory::mem_realloc (void* P, size_t size) -{ - void* data = realloc(P,size); - if(size&&(0==data)) - Debug.fatal(DEBUG_INFO,"Out of memory. Memory request: %d K",size/1024); - return data; +void* xrMemory::mem_realloc(void* P, size_t size) +{ + void* data = realloc(P, size); + if (size && (0 == data)) + Debug.fatal(DEBUG_INFO, "Out of memory. Memory request: %d K", size / 1024); + return data; } #endif diff --git a/src/xrCore/xrMemory_subst_borland.h b/src/xrCore/xrMemory_subst_borland.h index 64204edf393..d035c3df761 100644 --- a/src/xrCore/xrMemory_subst_borland.h +++ b/src/xrCore/xrMemory_subst_borland.h @@ -1,52 +1,59 @@ // new(0) template -IC T* xr_new () +IC T* xr_new() { - return new T(); + return new T(); } // new(1) template -IC T* xr_new (P1 p1) { - return new T(p1); +IC T* xr_new(P1 p1) +{ + return new T(p1); } // new(2) -template -IC T* xr_new (P1 p1, P2 p2) { - return new T(p1,p2); +template +IC T* xr_new(P1 p1, P2 p2) +{ + return new T(p1, p2); } // new(3) template -IC T* xr_new (P1 p1, P2 p2, P3 p3) { - return new T(p1,p2,p3); +IC T* xr_new(P1 p1, P2 p2, P3 p3) +{ + return new T(p1, p2, p3); } // new(4) template -IC T* xr_new (P1 p1, P2 p2, P3 p3, P4 p4) { - return new T(p1,p2,p3,p4); +IC T* xr_new(P1 p1, P2 p2, P3 p3, P4 p4) +{ + return new T(p1, p2, p3, p4); } // new(5) template -IC T* xr_new (P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) { - return new T(p1,p2,p3,p4,p5); +IC T* xr_new(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) +{ + return new T(p1, p2, p3, p4, p5); } // new(6) template -IC T* xr_new (P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6) { - return new T(p1,p2,p3,p4,p5,p6); +IC T* xr_new(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6) +{ + return new T(p1, p2, p3, p4, p5, p6); } // new(7) template -IC T* xr_new (P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7) { - return new T(p1,p2,p3,p4,p5,p6,p7); +IC T* xr_new(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7) +{ + return new T(p1, p2, p3, p4, p5, p6, p7); } -// #define xr_delete(ptr) if (ptr){delete ptr; ptr=0;} +// #define xr_delete(ptr) if (ptr){delete ptr; ptr=0;} template -IC void xr_delete (T* &ptr) +IC void xr_delete(T*& ptr) { - if (ptr) - { - delete ptr; - const_cast(ptr) = NULL; - } + if (ptr) + { + delete ptr; + const_cast(ptr) = NULL; + } } diff --git a/src/xrCore/xrMemory_subst_msvc.cpp b/src/xrCore/xrMemory_subst_msvc.cpp index 9325fdb14a1..4c577bc5cad 100644 --- a/src/xrCore/xrMemory_subst_msvc.cpp +++ b/src/xrCore/xrMemory_subst_msvc.cpp @@ -4,273 +4,291 @@ #include "xrMemory_align.h" #include "xrMemory_pure.h" -#ifndef __BORLANDC__ +#ifndef __BORLANDC__ #ifndef DEBUG_MEMORY_MANAGER -# define debug_mode 0 +# define debug_mode 0 #endif // DEBUG_MEMORY_MANAGER #ifdef DEBUG_MEMORY_MANAGER - XRCORE_API void* g_globalCheckAddr = NULL; +XRCORE_API void* g_globalCheckAddr = NULL; #endif // DEBUG_MEMORY_MANAGER #ifdef DEBUG_MEMORY_MANAGER - extern void save_stack_trace (); +extern void save_stack_trace(); #endif // DEBUG_MEMORY_MANAGER -MEMPOOL mem_pools [mem_pools_count]; +MEMPOOL mem_pools[mem_pools_count]; // MSVC -ICF u8* acc_header (void* P) { u8* _P = (u8*)P; return _P-1; } -ICF u32 get_header (void* P) { return (u32)*acc_header(P); } -ICF u32 get_pool (size_t size) +ICF u8* acc_header(void* P) { u8* _P = (u8*)P; return _P - 1; } +ICF u32 get_header(void* P) { return (u32)*acc_header(P); } +ICF u32 get_pool(size_t size) { - u32 pid = u32(size/mem_pools_ebase); - if (pid>=mem_pools_count) return mem_generic; - else return pid; + u32 pid = u32(size / mem_pools_ebase); + if (pid >= mem_pools_count) return mem_generic; + else return pid; } #ifdef PURE_ALLOC -bool g_use_pure_alloc = false; +bool g_use_pure_alloc = false; #endif // PURE_ALLOC -void* xrMemory::mem_alloc (size_t size -# ifdef DEBUG_MEMORY_NAME - , const char* _name -# endif // DEBUG_MEMORY_NAME - ) +void* xrMemory::mem_alloc(size_t size +# ifdef DEBUG_MEMORY_NAME + , const char* _name +# endif // DEBUG_MEMORY_NAME + ) { - stat_calls++; + stat_calls++; #ifdef PURE_ALLOC - static bool g_use_pure_alloc_initialized = false; - if (!g_use_pure_alloc_initialized) { - g_use_pure_alloc_initialized = true; - g_use_pure_alloc = -# ifdef XRCORE_STATIC - true -# else // XRCORE_STATIC - !!strstr(GetCommandLine(),"-pure_alloc") -# endif // XRCORE_STATIC - ; - } + static bool g_use_pure_alloc_initialized = false; + if (!g_use_pure_alloc_initialized) + { + g_use_pure_alloc_initialized = true; + g_use_pure_alloc = +# ifdef XRCORE_STATIC + true +# else // XRCORE_STATIC + !!strstr(GetCommandLine(), "-pure_alloc") +# endif // XRCORE_STATIC + ; + } - if (g_use_pure_alloc) { - void *result = malloc(size); + if (g_use_pure_alloc) + { + void* result = malloc(size); #ifdef USE_MEMORY_MONITOR - memory_monitor::monitor_alloc (result,size,_name); + memory_monitor::monitor_alloc(result, size, _name); #endif // USE_MEMORY_MONITOR - return (result); - } + return (result); + } #endif // PURE_ALLOC #ifdef DEBUG_MEMORY_MANAGER - if (mem_initialized) debug_cs.Enter (); + if (mem_initialized) debug_cs.Enter(); #endif // DEBUG_MEMORY_MANAGER - u32 _footer = debug_mode?4:0; - void* _ptr = 0; + u32 _footer = debug_mode ? 4 : 0; + void* _ptr = 0; - // - if (!mem_initialized /*|| debug_mode*/) - { - // generic - // Igor: Reserve 1 byte for xrMemory header - void* _real = xr_aligned_offset_malloc (1 + size + _footer, 16, 0x1); - //void* _real = xr_aligned_offset_malloc (size + _footer, 16, 0x1); - _ptr = (void*)(((u8*)_real)+1); - *acc_header(_ptr) = mem_generic; - } else { + // + if (!mem_initialized /*|| debug_mode*/) + { + // generic + // Igor: Reserve 1 byte for xrMemory header + void* _real = xr_aligned_offset_malloc(1 + size + _footer, 16, 0x1); + //void* _real = xr_aligned_offset_malloc (size + _footer, 16, 0x1); + _ptr = (void*)(((u8*)_real) + 1); + *acc_header(_ptr) = mem_generic; + } + else + { #ifdef DEBUG_MEMORY_MANAGER - save_stack_trace (); + save_stack_trace(); #endif // DEBUG - // accelerated - // Igor: Reserve 1 byte for xrMemory header - u32 pool = get_pool (1+size+_footer); - //u32 pool = get_pool (size+_footer); - if (mem_generic==pool) - { - // generic - // Igor: Reserve 1 byte for xrMemory header - void* _real = xr_aligned_offset_malloc (1 + size + _footer,16,0x1); - //void* _real = xr_aligned_offset_malloc (size + _footer,16,0x1); - _ptr = (void*)(((u8*)_real)+1); - *acc_header(_ptr) = mem_generic; - } else { - // pooled - // Igor: Reserve 1 byte for xrMemory header - // Already reserved when getting pool id - void* _real = mem_pools[pool].create(); - _ptr = (void*)(((u8*)_real)+1); - *acc_header(_ptr) = (u8)pool; - } - } + // accelerated + // Igor: Reserve 1 byte for xrMemory header + u32 pool = get_pool(1 + size + _footer); + //u32 pool = get_pool (size+_footer); + if (mem_generic == pool) + { + // generic + // Igor: Reserve 1 byte for xrMemory header + void* _real = xr_aligned_offset_malloc(1 + size + _footer, 16, 0x1); + //void* _real = xr_aligned_offset_malloc (size + _footer,16,0x1); + _ptr = (void*)(((u8*)_real) + 1); + *acc_header(_ptr) = mem_generic; + } + else + { + // pooled + // Igor: Reserve 1 byte for xrMemory header + // Already reserved when getting pool id + void* _real = mem_pools[pool].create(); + _ptr = (void*)(((u8*)_real) + 1); + *acc_header(_ptr) = (u8)pool; + } + } #ifdef DEBUG_MEMORY_MANAGER - if (debug_mode) dbg_register (_ptr,size,_name); - if (mem_initialized) debug_cs.Leave (); - //if(g_globalCheckAddr==_ptr){ - // __asm int 3; - //} - //if (_name && (0==strcmp(_name,"class ISpatial *")) && (size==376)) - //{ - // __asm int 3; - //} + if (debug_mode) dbg_register(_ptr, size, _name); + if (mem_initialized) debug_cs.Leave(); + //if(g_globalCheckAddr==_ptr){ + // __asm int 3; + //} + //if (_name && (0==strcmp(_name,"class ISpatial *")) && (size==376)) + //{ + // __asm int 3; + //} #endif // DEBUG_MEMORY_MANAGER #ifdef USE_MEMORY_MONITOR - memory_monitor::monitor_alloc (_ptr,size,_name); + memory_monitor::monitor_alloc(_ptr, size, _name); #endif // USE_MEMORY_MONITOR - return _ptr; + return _ptr; } -void xrMemory::mem_free (void* P) +void xrMemory::mem_free(void* P) { - stat_calls++; + stat_calls++; #ifdef USE_MEMORY_MONITOR - memory_monitor::monitor_free(P); + memory_monitor::monitor_free(P); #endif // USE_MEMORY_MONITOR #ifdef PURE_ALLOC - if (g_use_pure_alloc) { - free (P); - return; - } + if (g_use_pure_alloc) + { + free(P); + return; + } #endif // PURE_ALLOC #ifdef DEBUG_MEMORY_MANAGER - if(g_globalCheckAddr==P) - __asm int 3; + if (g_globalCheckAddr == P) + __asm int 3; #endif // DEBUG_MEMORY_MANAGER #ifdef DEBUG_MEMORY_MANAGER - if (mem_initialized) debug_cs.Enter (); + if (mem_initialized) debug_cs.Enter(); #endif // DEBUG_MEMORY_MANAGER - if (debug_mode) dbg_unregister (P); - u32 pool = get_header (P); - void* _real = (void*)(((u8*)P)-1); - if (mem_generic==pool) - { - // generic - xr_aligned_free (_real); - } else { - // pooled - VERIFY2 (pool -IC T* xr_new () +IC T* xr_new() { - T* ptr = (T*)Memory.mem_alloc(sizeof(T), typeid(T).name()); - return new (ptr) T(); + T* ptr = (T*)Memory.mem_alloc(sizeof(T), typeid(T).name()); + return new (ptr)T(); } // new(1) template -IC T* xr_new (const P1& p1) { - T* ptr = (T*)Memory.mem_alloc(sizeof(T), typeid(T).name()); - return new (ptr) T(p1); +IC T* xr_new(const P1& p1) +{ + T* ptr = (T*)Memory.mem_alloc(sizeof(T), typeid(T).name()); + return new (ptr)T(p1); } // new(2) -template -IC T* xr_new (const P1& p1, const P2& p2) { - T* ptr = (T*)Memory.mem_alloc(sizeof(T), typeid(T).name()); - return new (ptr) T(p1,p2); +template +IC T* xr_new(const P1& p1, const P2& p2) +{ + T* ptr = (T*)Memory.mem_alloc(sizeof(T), typeid(T).name()); + return new (ptr)T(p1, p2); } // new(3) template -IC T* xr_new (const P1& p1, const P2& p2, const P3& p3) { - T* ptr = (T*)Memory.mem_alloc(sizeof(T), typeid(T).name()); - return new (ptr) T(p1,p2,p3); +IC T* xr_new(const P1& p1, const P2& p2, const P3& p3) +{ + T* ptr = (T*)Memory.mem_alloc(sizeof(T), typeid(T).name()); + return new (ptr)T(p1, p2, p3); } // new(4) template -IC T* xr_new (const P1& p1, const P2& p2, const P3& p3, const P4& p4) { - T* ptr = (T*)Memory.mem_alloc(sizeof(T), typeid(T).name()); - return new (ptr) T(p1,p2,p3,p4); +IC T* xr_new(const P1& p1, const P2& p2, const P3& p3, const P4& p4) +{ + T* ptr = (T*)Memory.mem_alloc(sizeof(T), typeid(T).name()); + return new (ptr)T(p1, p2, p3, p4); } // new(5) template -IC T* xr_new (const P1& p1, const P2& p2, const P3& p3, const P4& p4, const P5& p5) { - T* ptr = (T*)Memory.mem_alloc(sizeof(T), typeid(T).name()); - return new (ptr) T(p1,p2,p3,p4,p5); +IC T* xr_new(const P1& p1, const P2& p2, const P3& p3, const P4& p4, const P5& p5) +{ + T* ptr = (T*)Memory.mem_alloc(sizeof(T), typeid(T).name()); + return new (ptr)T(p1, p2, p3, p4, p5); } // new(6) template -IC T* xr_new (const P1& p1, const P2& p2, const P3& p3, const P4& p4, const P5& p5, const P6& p6) { - T* ptr = (T*)Memory.mem_alloc(sizeof(T), typeid(T).name()); - return new (ptr) T(p1,p2,p3,p4,p5,p6); +IC T* xr_new(const P1& p1, const P2& p2, const P3& p3, const P4& p4, const P5& p5, const P6& p6) +{ + T* ptr = (T*)Memory.mem_alloc(sizeof(T), typeid(T).name()); + return new (ptr)T(p1, p2, p3, p4, p5, p6); } // new(7) template -IC T* xr_new (const P1& p1, const P2& p2, const P3& p3, const P4& p4, const P5& p5, const P6& p6, const P7& p7) { - T* ptr = (T*)Memory.mem_alloc(sizeof(T), typeid(T).name()); - return new (ptr) T(p1,p2,p3,p4,p5,p6,p7); +IC T* xr_new(const P1& p1, const P2& p2, const P3& p3, const P4& p4, const P5& p5, const P6& p6, const P7& p7) +{ + T* ptr = (T*)Memory.mem_alloc(sizeof(T), typeid(T).name()); + return new (ptr)T(p1, p2, p3, p4, p5, p6, p7); } // new(8) template -IC T* xr_new (const P1& p1, const P2& p2, const P3& p3, const P4& p4, const P5& p5, const P6& p6, const P7& p7, const P8& p8) { - T* ptr = (T*)Memory.mem_alloc(sizeof(T), typeid(T).name()); - return new (ptr) T(p1,p2,p3,p4,p5,p6,p7,p8); +IC T* xr_new(const P1& p1, const P2& p2, const P3& p3, const P4& p4, const P5& p5, const P6& p6, const P7& p7, const P8& p8) +{ + T* ptr = (T*)Memory.mem_alloc(sizeof(T), typeid(T).name()); + return new (ptr)T(p1, p2, p3, p4, p5, p6, p7, p8); } // new(9) template -IC T* xr_new (const P1& p1, const P2& p2, const P3& p3, const P4& p4, const P5& p5, const P6& p6, const P7& p7, const P8& p8, const P8& p9) { - T* ptr = (T*)Memory.mem_alloc(sizeof(T), typeid(T).name()); - return new (ptr) T(p1,p2,p3,p4,p5,p6,p7,p8,p9); +IC T* xr_new(const P1& p1, const P2& p2, const P3& p3, const P4& p4, const P5& p5, const P6& p6, const P7& p7, const P8& p8, const P8& p9) +{ + T* ptr = (T*)Memory.mem_alloc(sizeof(T), typeid(T).name()); + return new (ptr)T(p1, p2, p3, p4, p5, p6, p7, p8, p9); } #else // DEBUG_MEMORY_NAME // new(0) template -IC T* xr_new () +IC T* xr_new() { - T* ptr = (T*)Memory.mem_alloc(sizeof(T)); - return new (ptr) T(); + T* ptr = (T*)Memory.mem_alloc(sizeof(T)); + return new (ptr)T(); } // new(1) template -IC T* xr_new (const P1& p1) { - T* ptr = (T*)Memory.mem_alloc(sizeof(T)); - return new (ptr) T(p1); +IC T* xr_new(const P1& p1) +{ + T* ptr = (T*)Memory.mem_alloc(sizeof(T)); + return new (ptr)T(p1); } // new(2) -template -IC T* xr_new (const P1& p1, const P2& p2) { - T* ptr = (T*)Memory.mem_alloc(sizeof(T)); - return new (ptr) T(p1,p2); +template +IC T* xr_new(const P1& p1, const P2& p2) +{ + T* ptr = (T*)Memory.mem_alloc(sizeof(T)); + return new (ptr)T(p1, p2); } // new(3) template -IC T* xr_new (const P1& p1, const P2& p2, const P3& p3) { - T* ptr = (T*)Memory.mem_alloc(sizeof(T)); - return new (ptr) T(p1,p2,p3); +IC T* xr_new(const P1& p1, const P2& p2, const P3& p3) +{ + T* ptr = (T*)Memory.mem_alloc(sizeof(T)); + return new (ptr)T(p1, p2, p3); } // new(4) template -IC T* xr_new (const P1& p1, const P2& p2, const P3& p3, const P4& p4) { - T* ptr = (T*)Memory.mem_alloc(sizeof(T)); - return new (ptr) T(p1,p2,p3,p4); +IC T* xr_new(const P1& p1, const P2& p2, const P3& p3, const P4& p4) +{ + T* ptr = (T*)Memory.mem_alloc(sizeof(T)); + return new (ptr)T(p1, p2, p3, p4); } // new(5) template -IC T* xr_new (const P1& p1, const P2& p2, const P3& p3, const P4& p4, const P5& p5) { - T* ptr = (T*)Memory.mem_alloc(sizeof(T)); - return new (ptr) T(p1,p2,p3,p4,p5); +IC T* xr_new(const P1& p1, const P2& p2, const P3& p3, const P4& p4, const P5& p5) +{ + T* ptr = (T*)Memory.mem_alloc(sizeof(T)); + return new (ptr)T(p1, p2, p3, p4, p5); } // new(6) template -IC T* xr_new (const P1& p1, const P2& p2, const P3& p3, const P4& p4, const P5& p5, const P6& p6) { - T* ptr = (T*)Memory.mem_alloc(sizeof(T)); - return new (ptr) T(p1,p2,p3,p4,p5,p6); +IC T* xr_new(const P1& p1, const P2& p2, const P3& p3, const P4& p4, const P5& p5, const P6& p6) +{ + T* ptr = (T*)Memory.mem_alloc(sizeof(T)); + return new (ptr)T(p1, p2, p3, p4, p5, p6); } // new(7) template -IC T* xr_new (const P1& p1, const P2& p2, const P3& p3, const P4& p4, const P5& p5, const P6& p6, const P7& p7) { - T* ptr = (T*)Memory.mem_alloc(sizeof(T)); - return new (ptr) T(p1,p2,p3,p4,p5,p6,p7); +IC T* xr_new(const P1& p1, const P2& p2, const P3& p3, const P4& p4, const P5& p5, const P6& p6, const P7& p7) +{ + T* ptr = (T*)Memory.mem_alloc(sizeof(T)); + return new (ptr)T(p1, p2, p3, p4, p5, p6, p7); } // new(8) template -IC T* xr_new (const P1& p1, const P2& p2, const P3& p3, const P4& p4, const P5& p5, const P6& p6, const P7& p7, const P8& p8) { - T* ptr = (T*)Memory.mem_alloc(sizeof(T)); - return new (ptr) T(p1,p2,p3,p4,p5,p6,p7,p8); +IC T* xr_new(const P1& p1, const P2& p2, const P3& p3, const P4& p4, const P5& p5, const P6& p6, const P7& p7, const P8& p8) +{ + T* ptr = (T*)Memory.mem_alloc(sizeof(T)); + return new (ptr)T(p1, p2, p3, p4, p5, p6, p7, p8); } // new(9) template -IC T* xr_new (const P1& p1, const P2& p2, const P3& p3, const P4& p4, const P5& p5, const P6& p6, const P7& p7, const P8& p8, const P8& p9) { - T* ptr = (T*)Memory.mem_alloc(sizeof(T)); - return new (ptr) T(p1,p2,p3,p4,p5,p6,p7,p8,p9); +IC T* xr_new(const P1& p1, const P2& p2, const P3& p3, const P4& p4, const P5& p5, const P6& p6, const P7& p7, const P8& p8, const P8& p9) +{ + T* ptr = (T*)Memory.mem_alloc(sizeof(T)); + return new (ptr)T(p1, p2, p3, p4, p5, p6, p7, p8, p9); } #endif // DEBUG_MEMORY_NAME template struct xr_special_free { - IC void operator()(T* &ptr) - { - void* _real_ptr = dynamic_cast(ptr); - ptr->~T (); - Memory.mem_free (_real_ptr); - } + IC void operator()(T*& ptr) + { + void* _real_ptr = dynamic_cast(ptr); + ptr->~T(); + Memory.mem_free(_real_ptr); + } }; template -struct xr_special_free +struct xr_special_free < false, T > { - IC void operator()(T* &ptr) - { - ptr->~T (); - Memory.mem_free (ptr); - } + IC void operator()(T*& ptr) + { + ptr->~T(); + Memory.mem_free(ptr); + } }; template -IC void xr_delete (T* &ptr) +IC void xr_delete(T*& ptr) { - if (ptr) - { - xr_special_free::result,T>()(ptr); - ptr = NULL; - } + if (ptr) + { + xr_special_free::result, T>()(ptr); + ptr = NULL; + } } template -IC void xr_delete (T* const &ptr) +IC void xr_delete(T* const& ptr) { - if (ptr) - { - xr_special_free::result,T>(ptr); - const_cast(ptr) = NULL; - } + if (ptr) + { + xr_special_free::result, T>(ptr); + const_cast(ptr) = NULL; + } } #ifdef DEBUG_MEMORY_MANAGER - void XRCORE_API mem_alloc_gather_stats (const bool &value); - void XRCORE_API mem_alloc_gather_stats_frequency (const float &value); - void XRCORE_API mem_alloc_show_stats (); - void XRCORE_API mem_alloc_clear_stats (); +void XRCORE_API mem_alloc_gather_stats(const bool& value); +void XRCORE_API mem_alloc_gather_stats_frequency(const float& value); +void XRCORE_API mem_alloc_show_stats(); +void XRCORE_API mem_alloc_clear_stats(); #endif // DEBUG_MEMORY_MANAGER \ No newline at end of file diff --git a/src/xrCore/xrPool.h b/src/xrCore/xrPool.h index 4cf9678b68e..5f464fe22e0 100644 --- a/src/xrCore/xrPool.h +++ b/src/xrCore/xrPool.h @@ -3,59 +3,59 @@ //#pragma once template -class poolSS +class poolSS { private: - T* list; - xr_vector blocks; + T* list; + xr_vector blocks; private: - T** access (T* P) { return (T**) LPVOID(P); } - void block_create () - { - // Allocate - VERIFY (0==list); - list = xr_alloc (granularity); - blocks.push_back (list); + T** access(T* P) { return (T**)LPVOID(P); } + void block_create() + { + // Allocate + VERIFY(0 == list); + list = xr_alloc(granularity); + blocks.push_back(list); - // Partition - for (int it=0; it<(granularity-1); it++) - { - T* E = list+it; - *access(E) = E+1; - } - *access(list+granularity-1) = NULL; - } + // Partition + for (int it = 0; it < (granularity - 1); it++) + { + T* E = list + it; + *access(E) = E + 1; + } + *access(list + granularity - 1) = NULL; + } public: - poolSS() - { - list = 0; - } - ~poolSS() - { - for (u32 b=0; b~T (); - *access(P) = list; - list = P; - P = NULL; - } - void clear () + T* E = list; + list = *access(list); + return new (E)T(); + } + void destroy(T*& P) + { + P->~T(); + *access(P) = list; + list = P; + P = NULL; + } + void clear() { - list = 0; - for (u32 b=0; b(1); - InitializeCriticalSection ( (CRITICAL_SECTION*)pmutex ); + pmutex = xr_alloc(1); + InitializeCriticalSection((CRITICAL_SECTION*)pmutex); } -xrCriticalSection::~xrCriticalSection () +xrCriticalSection::~xrCriticalSection() { - DeleteCriticalSection ( (CRITICAL_SECTION*)pmutex ); - xr_free ( pmutex ); + DeleteCriticalSection((CRITICAL_SECTION*)pmutex); + xr_free(pmutex); } #ifdef DEBUG - extern void OutputDebugStackTrace (const char *header); +extern void OutputDebugStackTrace(const char* header); #endif // DEBUG -void xrCriticalSection::Enter () +void xrCriticalSection::Enter() { #ifdef PROFILE_CRITICAL_SECTIONS -# if 0//def DEBUG - static bool show_call_stack = false; - if (show_call_stack) - OutputDebugStackTrace ("----------------------------------------------------"); -# endif // DEBUG - profiler temp(m_id); +# if 0//def DEBUG + static bool show_call_stack = false; + if (show_call_stack) + OutputDebugStackTrace("----------------------------------------------------"); +# endif // DEBUG + profiler temp(m_id); #endif // PROFILE_CRITICAL_SECTIONS - EnterCriticalSection ( (CRITICAL_SECTION*)pmutex ); + EnterCriticalSection((CRITICAL_SECTION*)pmutex); } -void xrCriticalSection::Leave () +void xrCriticalSection::Leave() { - LeaveCriticalSection ( (CRITICAL_SECTION*)pmutex ); + LeaveCriticalSection((CRITICAL_SECTION*)pmutex); } -BOOL xrCriticalSection::TryEnter () +BOOL xrCriticalSection::TryEnter() { - return TryEnterCriticalSection ( (CRITICAL_SECTION*)pmutex ); + return TryEnterCriticalSection((CRITICAL_SECTION*)pmutex); } -xrCriticalSection::raii::raii (xrCriticalSection* critical_section) - : critical_section(critical_section) +xrCriticalSection::raii::raii(xrCriticalSection* critical_section) + : critical_section(critical_section) { - VERIFY(critical_section); - critical_section->Enter(); + VERIFY(critical_section); + critical_section->Enter(); } -xrCriticalSection::raii::~raii () -{ - critical_section->Leave(); +xrCriticalSection::raii::~raii() +{ + critical_section->Leave(); } diff --git a/src/xrCore/xrSyncronize.h b/src/xrCore/xrSyncronize.h index 168134e4a89..aeb3e991f2d 100644 --- a/src/xrCore/xrSyncronize.h +++ b/src/xrCore/xrSyncronize.h @@ -2,53 +2,53 @@ #define xrSyncronizeH #if 0//def DEBUG -# define PROFILE_CRITICAL_SECTIONS +# define PROFILE_CRITICAL_SECTIONS #endif // DEBUG #ifdef PROFILE_CRITICAL_SECTIONS - typedef void (*add_profile_portion_callback) (LPCSTR id, const u64 &time); - void XRCORE_API set_add_profile_portion (add_profile_portion_callback callback); - -# define STRINGIZER_HELPER(a) #a -# define STRINGIZER(a) STRINGIZER_HELPER(a) -# define CONCATENIZE_HELPER(a,b) a##b -# define CONCATENIZE(a,b) CONCATENIZE_HELPER(a,b) -# define MUTEX_PROFILE_PREFIX_ID #mutexes/ -# define MUTEX_PROFILE_ID(a) STRINGIZER(CONCATENIZE(MUTEX_PROFILE_PREFIX_ID,a)) +typedef void(*add_profile_portion_callback) (LPCSTR id, const u64& time); +void XRCORE_API set_add_profile_portion(add_profile_portion_callback callback); + +# define STRINGIZER_HELPER(a) #a +# define STRINGIZER(a) STRINGIZER_HELPER(a) +# define CONCATENIZE_HELPER(a,b) a##b +# define CONCATENIZE(a,b) CONCATENIZE_HELPER(a,b) +# define MUTEX_PROFILE_PREFIX_ID #mutexes/ +# define MUTEX_PROFILE_ID(a) STRINGIZER(CONCATENIZE(MUTEX_PROFILE_PREFIX_ID,a)) #endif // PROFILE_CRITICAL_SECTIONS // Desc: Simple wrapper for critical section class XRCORE_API xrCriticalSection { public: - class XRCORE_API raii - { - public: - raii(xrCriticalSection*); - ~raii(); + class XRCORE_API raii + { + public: + raii(xrCriticalSection*); + ~raii(); - private: - xrCriticalSection* critical_section; - }; + private: + xrCriticalSection* critical_section; + }; private: - xrCriticalSection(xrCriticalSection const & copy) {}; //noncopyable - void* pmutex; + xrCriticalSection(xrCriticalSection const& copy) {}; //noncopyable + void* pmutex; #ifdef PROFILE_CRITICAL_SECTIONS - LPCSTR m_id; + LPCSTR m_id; #endif // PROFILE_CRITICAL_SECTIONS public: #ifdef PROFILE_CRITICAL_SECTIONS - xrCriticalSection (LPCSTR id); + xrCriticalSection(LPCSTR id); #else // PROFILE_CRITICAL_SECTIONS - xrCriticalSection (); + xrCriticalSection(); #endif // PROFILE_CRITICAL_SECTIONS - ~xrCriticalSection (); + ~xrCriticalSection(); - void Enter (); - void Leave (); - BOOL TryEnter(); + void Enter(); + void Leave(); + BOOL TryEnter(); }; #endif // xrSyncronizeH \ No newline at end of file diff --git a/src/xrCore/xr_ini.h b/src/xrCore/xr_ini.h index d523b31f7ac..dccdedf5797 100644 --- a/src/xrCore/xr_ini.h +++ b/src/xrCore/xr_ini.h @@ -4,162 +4,163 @@ #include "fastdelegate.h" // refs -class CInifile; -struct xr_token; +class CInifile; +struct xr_token; class XRCORE_API CInifile { public: - struct XRCORE_API Item - { - shared_str first; - shared_str second; -//#ifdef DEBUG -// shared_str comment; -//#endif - Item() : first(0), second(0) -//#ifdef DEBUG -// , comment(0) -//#endif - {}; - }; - typedef xr_vector Items; - typedef Items::const_iterator SectCIt; - typedef Items::iterator SectIt_; - struct XRCORE_API Sect { - shared_str Name; - Items Data; + struct XRCORE_API Item + { + shared_str first; + shared_str second; + //#ifdef DEBUG + // shared_str comment; + //#endif + Item() : first(0), second(0) + //#ifdef DEBUG + // , comment(0) + //#endif + {}; + }; + typedef xr_vector Items; + typedef Items::const_iterator SectCIt; + typedef Items::iterator SectIt_; + struct XRCORE_API Sect + { + shared_str Name; + Items Data; + + BOOL line_exist(LPCSTR L, LPCSTR* val = 0); + }; + typedef xr_vector Root; + typedef Root::iterator RootIt; + typedef Root::const_iterator RootCIt; - BOOL line_exist (LPCSTR L, LPCSTR* val=0); - }; - typedef xr_vector Root; - typedef Root::iterator RootIt; - typedef Root::const_iterator RootCIt; - #ifndef _EDITOR - typedef fastdelegate::FastDelegate1 allow_include_func_t; + typedef fastdelegate::FastDelegate1 allow_include_func_t; #endif - static CInifile* Create ( LPCSTR szFileName, BOOL ReadOnly=TRUE); - static void Destroy ( CInifile*); - static IC BOOL IsBOOL ( LPCSTR B) { return (xr_strcmp(B,"on")==0 || xr_strcmp(B,"yes")==0 || xr_strcmp(B,"true")==0 || xr_strcmp(B,"1")==0);} + static CInifile* Create(LPCSTR szFileName, BOOL ReadOnly = TRUE); + static void Destroy(CInifile*); + static IC BOOL IsBOOL(LPCSTR B) { return (xr_strcmp(B, "on") == 0 || xr_strcmp(B, "yes") == 0 || xr_strcmp(B, "true") == 0 || xr_strcmp(B, "1") == 0); } private: - enum{eSaveAtEnd = (1<<0), eReadOnly= (1<<1), eOverrideNames=(1<<2),}; - Flags8 m_flags; - string_path m_file_name; - Root DATA; - - void Load (IReader* F, LPCSTR path - #ifndef _EDITOR - , allow_include_func_t allow_include_func = NULL - #endif - ); + enum { eSaveAtEnd = (1 << 0), eReadOnly = (1 << 1), eOverrideNames = (1 << 2), }; + Flags8 m_flags; + string_path m_file_name; + Root DATA; + + void Load(IReader* F, LPCSTR path +#ifndef _EDITOR + , allow_include_func_t allow_include_func = NULL +#endif + ); public: - CInifile ( IReader* F, - LPCSTR path=0 - #ifndef _EDITOR - ,allow_include_func_t allow_include_func = NULL - #endif - ); + CInifile(IReader* F, + LPCSTR path = 0 +#ifndef _EDITOR + , allow_include_func_t allow_include_func = NULL +#endif + ); - CInifile ( LPCSTR szFileName, - BOOL ReadOnly=TRUE, - BOOL bLoadAtStart=TRUE, - BOOL SaveAtEnd=TRUE, - u32 sect_count=0 - #ifndef _EDITOR - ,allow_include_func_t allow_include_func = NULL - #endif - ); + CInifile(LPCSTR szFileName, + BOOL ReadOnly = TRUE, + BOOL bLoadAtStart = TRUE, + BOOL SaveAtEnd = TRUE, + u32 sect_count = 0 +#ifndef _EDITOR + , allow_include_func_t allow_include_func = NULL +#endif + ); - virtual ~CInifile ( ); - bool save_as ( LPCSTR new_fname=0 ); - void save_as (IWriter& writer, bool bcheck=false)const; - void set_override_names(BOOL b){m_flags.set(eOverrideNames,b);} - void save_at_end (BOOL b){m_flags.set(eSaveAtEnd,b);} - LPCSTR fname ( ) const { return m_file_name; }; + virtual ~CInifile(); + bool save_as(LPCSTR new_fname = 0); + void save_as(IWriter& writer, bool bcheck = false)const; + void set_override_names(BOOL b) { m_flags.set(eOverrideNames, b); } + void save_at_end(BOOL b) { m_flags.set(eSaveAtEnd, b); } + LPCSTR fname() const { return m_file_name; }; - Sect& r_section ( LPCSTR S )const; - Sect& r_section ( const shared_str& S )const; - BOOL line_exist ( LPCSTR S, LPCSTR L )const; - BOOL line_exist ( const shared_str& S, const shared_str& L )const; - u32 line_count ( LPCSTR S )const; - u32 line_count ( const shared_str& S )const; - u32 section_count ( )const; - BOOL section_exist ( LPCSTR S )const; - BOOL section_exist ( const shared_str& S )const; - Root& sections ( ){return DATA;} - Root const& sections ( ) const {return DATA;} + Sect& r_section(LPCSTR S)const; + Sect& r_section(const shared_str& S)const; + BOOL line_exist(LPCSTR S, LPCSTR L)const; + BOOL line_exist(const shared_str& S, const shared_str& L)const; + u32 line_count(LPCSTR S)const; + u32 line_count(const shared_str& S)const; + u32 section_count()const; + BOOL section_exist(LPCSTR S)const; + BOOL section_exist(const shared_str& S)const; + Root& sections() { return DATA; } + Root const& sections() const { return DATA; } - CLASS_ID r_clsid ( LPCSTR S, LPCSTR L )const; - CLASS_ID r_clsid ( const shared_str& S, LPCSTR L )const { return r_clsid(*S,L); } - LPCSTR r_string ( LPCSTR S, LPCSTR L)const; // îñòàâëÿåò êàâû÷êè - LPCSTR r_string ( const shared_str& S, LPCSTR L)const { return r_string(*S,L); } // îñòàâëÿåò êàâû÷êè - shared_str r_string_wb ( LPCSTR S, LPCSTR L)const; // óáèðàåò êàâû÷êè - shared_str r_string_wb ( const shared_str& S, LPCSTR L)const { return r_string_wb(*S,L); } // óáèðàåò êàâû÷êè - u8 r_u8 ( LPCSTR S, LPCSTR L ) const; - u8 r_u8 ( const shared_str& S, LPCSTR L )const { return r_u8(*S,L); } - u16 r_u16 ( LPCSTR S, LPCSTR L )const; - u16 r_u16 ( const shared_str& S, LPCSTR L )const { return r_u16(*S,L); } - u32 r_u32 ( LPCSTR S, LPCSTR L )const; - u32 r_u32 ( const shared_str& S, LPCSTR L )const { return r_u32(*S,L); } - u64 r_u64 ( LPCSTR S, LPCSTR L )const; - s8 r_s8 ( LPCSTR S, LPCSTR L )const; - s8 r_s8 ( const shared_str& S, LPCSTR L )const { return r_s8(*S,L); } - s16 r_s16 ( LPCSTR S, LPCSTR L )const; - s16 r_s16 ( const shared_str& S, LPCSTR L )const { return r_s16(*S,L); } - s32 r_s32 ( LPCSTR S, LPCSTR L )const; - s32 r_s32 ( const shared_str& S, LPCSTR L )const { return r_s32(*S,L); } - s64 r_s64 ( LPCSTR S, LPCSTR L )const; - float r_float ( LPCSTR S, LPCSTR L )const; - float r_float ( const shared_str& S, LPCSTR L )const { return r_float(*S,L); } - Fcolor r_fcolor ( LPCSTR S, LPCSTR L )const; - Fcolor r_fcolor ( const shared_str& S, LPCSTR L )const { return r_fcolor(*S,L); } - u32 r_color ( LPCSTR S, LPCSTR L )const; - u32 r_color ( const shared_str& S, LPCSTR L )const { return r_color(*S,L); } - Ivector2 r_ivector2 ( LPCSTR S, LPCSTR L )const; - Ivector2 r_ivector2 ( const shared_str& S, LPCSTR L )const { return r_ivector2(*S,L); } - Ivector3 r_ivector3 ( LPCSTR S, LPCSTR L )const; - Ivector3 r_ivector3 ( const shared_str& S, LPCSTR L )const { return r_ivector3(*S,L); } - Ivector4 r_ivector4 ( LPCSTR S, LPCSTR L )const; - Ivector4 r_ivector4 ( const shared_str& S, LPCSTR L )const { return r_ivector4(*S,L); } - Fvector2 r_fvector2 ( LPCSTR S, LPCSTR L )const; - Fvector2 r_fvector2 ( const shared_str& S, LPCSTR L )const { return r_fvector2(*S,L); } - Fvector3 r_fvector3 ( LPCSTR S, LPCSTR L )const; - Fvector3 r_fvector3 ( const shared_str& S, LPCSTR L )const { return r_fvector3(*S,L); } - Fvector4 r_fvector4 ( LPCSTR S, LPCSTR L )const; - Fvector4 r_fvector4 ( const shared_str& S, LPCSTR L )const { return r_fvector4(*S,L); } - BOOL r_bool ( LPCSTR S, LPCSTR L )const; - BOOL r_bool ( const shared_str& S, LPCSTR L )const { return r_bool(*S,L); } - int r_token ( LPCSTR S, LPCSTR L, const xr_token *token_list)const; - BOOL r_line ( LPCSTR S, int L, LPCSTR* N, LPCSTR* V )const; - BOOL r_line ( const shared_str& S, int L, LPCSTR* N, LPCSTR* V )const; + CLASS_ID r_clsid(LPCSTR S, LPCSTR L)const; + CLASS_ID r_clsid(const shared_str& S, LPCSTR L)const { return r_clsid(*S, L); } + LPCSTR r_string(LPCSTR S, LPCSTR L)const; // îñòàâëÿåò êàâû÷êè + LPCSTR r_string(const shared_str& S, LPCSTR L)const { return r_string(*S, L); } // îñòàâëÿåò êàâû÷êè + shared_str r_string_wb(LPCSTR S, LPCSTR L)const; // óáèðàåò êàâû÷êè + shared_str r_string_wb(const shared_str& S, LPCSTR L)const { return r_string_wb(*S, L); } // óáèðàåò êàâû÷êè + u8 r_u8(LPCSTR S, LPCSTR L) const; + u8 r_u8(const shared_str& S, LPCSTR L)const { return r_u8(*S, L); } + u16 r_u16(LPCSTR S, LPCSTR L)const; + u16 r_u16(const shared_str& S, LPCSTR L)const { return r_u16(*S, L); } + u32 r_u32(LPCSTR S, LPCSTR L)const; + u32 r_u32(const shared_str& S, LPCSTR L)const { return r_u32(*S, L); } + u64 r_u64(LPCSTR S, LPCSTR L)const; + s8 r_s8(LPCSTR S, LPCSTR L)const; + s8 r_s8(const shared_str& S, LPCSTR L)const { return r_s8(*S, L); } + s16 r_s16(LPCSTR S, LPCSTR L)const; + s16 r_s16(const shared_str& S, LPCSTR L)const { return r_s16(*S, L); } + s32 r_s32(LPCSTR S, LPCSTR L)const; + s32 r_s32(const shared_str& S, LPCSTR L)const { return r_s32(*S, L); } + s64 r_s64(LPCSTR S, LPCSTR L)const; + float r_float(LPCSTR S, LPCSTR L)const; + float r_float(const shared_str& S, LPCSTR L)const { return r_float(*S, L); } + Fcolor r_fcolor(LPCSTR S, LPCSTR L)const; + Fcolor r_fcolor(const shared_str& S, LPCSTR L)const { return r_fcolor(*S, L); } + u32 r_color(LPCSTR S, LPCSTR L)const; + u32 r_color(const shared_str& S, LPCSTR L)const { return r_color(*S, L); } + Ivector2 r_ivector2(LPCSTR S, LPCSTR L)const; + Ivector2 r_ivector2(const shared_str& S, LPCSTR L)const { return r_ivector2(*S, L); } + Ivector3 r_ivector3(LPCSTR S, LPCSTR L)const; + Ivector3 r_ivector3(const shared_str& S, LPCSTR L)const { return r_ivector3(*S, L); } + Ivector4 r_ivector4(LPCSTR S, LPCSTR L)const; + Ivector4 r_ivector4(const shared_str& S, LPCSTR L)const { return r_ivector4(*S, L); } + Fvector2 r_fvector2(LPCSTR S, LPCSTR L)const; + Fvector2 r_fvector2(const shared_str& S, LPCSTR L)const { return r_fvector2(*S, L); } + Fvector3 r_fvector3(LPCSTR S, LPCSTR L)const; + Fvector3 r_fvector3(const shared_str& S, LPCSTR L)const { return r_fvector3(*S, L); } + Fvector4 r_fvector4(LPCSTR S, LPCSTR L)const; + Fvector4 r_fvector4(const shared_str& S, LPCSTR L)const { return r_fvector4(*S, L); } + BOOL r_bool(LPCSTR S, LPCSTR L)const; + BOOL r_bool(const shared_str& S, LPCSTR L)const { return r_bool(*S, L); } + int r_token(LPCSTR S, LPCSTR L, const xr_token* token_list)const; + BOOL r_line(LPCSTR S, int L, LPCSTR* N, LPCSTR* V)const; + BOOL r_line(const shared_str& S, int L, LPCSTR* N, LPCSTR* V)const; - void w_string ( LPCSTR S, LPCSTR L, LPCSTR V, LPCSTR comment=0 ); - void w_u8 ( LPCSTR S, LPCSTR L, u8 V, LPCSTR comment=0 ); - void w_u16 ( LPCSTR S, LPCSTR L, u16 V, LPCSTR comment=0 ); - void w_u32 ( LPCSTR S, LPCSTR L, u32 V, LPCSTR comment=0 ); - void w_u64 ( LPCSTR S, LPCSTR L, u64 V, LPCSTR comment=0 ); - void w_s64 ( LPCSTR S, LPCSTR L, s64 V, LPCSTR comment=0 ); - void w_s8 ( LPCSTR S, LPCSTR L, s8 V, LPCSTR comment=0 ); - void w_s16 ( LPCSTR S, LPCSTR L, s16 V, LPCSTR comment=0 ); - void w_s32 ( LPCSTR S, LPCSTR L, s32 V, LPCSTR comment=0 ); - void w_float ( LPCSTR S, LPCSTR L, float V, LPCSTR comment=0 ); - void w_fcolor ( LPCSTR S, LPCSTR L, const Fcolor& V, LPCSTR comment=0 ); - void w_color ( LPCSTR S, LPCSTR L, u32 V, LPCSTR comment=0 ); - void w_ivector2 ( LPCSTR S, LPCSTR L, const Ivector2& V, LPCSTR comment=0 ); - void w_ivector3 ( LPCSTR S, LPCSTR L, const Ivector3& V, LPCSTR comment=0 ); - void w_ivector4 ( LPCSTR S, LPCSTR L, const Ivector4& V, LPCSTR comment=0 ); - void w_fvector2 ( LPCSTR S, LPCSTR L, const Fvector2& V, LPCSTR comment=0 ); - void w_fvector3 ( LPCSTR S, LPCSTR L, const Fvector3& V, LPCSTR comment=0 ); - void w_fvector4 ( LPCSTR S, LPCSTR L, const Fvector4& V, LPCSTR comment=0 ); - void w_bool ( LPCSTR S, LPCSTR L, BOOL V, LPCSTR comment=0 ); + void w_string(LPCSTR S, LPCSTR L, LPCSTR V, LPCSTR comment = 0); + void w_u8(LPCSTR S, LPCSTR L, u8 V, LPCSTR comment = 0); + void w_u16(LPCSTR S, LPCSTR L, u16 V, LPCSTR comment = 0); + void w_u32(LPCSTR S, LPCSTR L, u32 V, LPCSTR comment = 0); + void w_u64(LPCSTR S, LPCSTR L, u64 V, LPCSTR comment = 0); + void w_s64(LPCSTR S, LPCSTR L, s64 V, LPCSTR comment = 0); + void w_s8(LPCSTR S, LPCSTR L, s8 V, LPCSTR comment = 0); + void w_s16(LPCSTR S, LPCSTR L, s16 V, LPCSTR comment = 0); + void w_s32(LPCSTR S, LPCSTR L, s32 V, LPCSTR comment = 0); + void w_float(LPCSTR S, LPCSTR L, float V, LPCSTR comment = 0); + void w_fcolor(LPCSTR S, LPCSTR L, const Fcolor& V, LPCSTR comment = 0); + void w_color(LPCSTR S, LPCSTR L, u32 V, LPCSTR comment = 0); + void w_ivector2(LPCSTR S, LPCSTR L, const Ivector2& V, LPCSTR comment = 0); + void w_ivector3(LPCSTR S, LPCSTR L, const Ivector3& V, LPCSTR comment = 0); + void w_ivector4(LPCSTR S, LPCSTR L, const Ivector4& V, LPCSTR comment = 0); + void w_fvector2(LPCSTR S, LPCSTR L, const Fvector2& V, LPCSTR comment = 0); + void w_fvector3(LPCSTR S, LPCSTR L, const Fvector3& V, LPCSTR comment = 0); + void w_fvector4(LPCSTR S, LPCSTR L, const Fvector4& V, LPCSTR comment = 0); + void w_bool(LPCSTR S, LPCSTR L, BOOL V, LPCSTR comment = 0); - void remove_line ( LPCSTR S, LPCSTR L ); + void remove_line(LPCSTR S, LPCSTR L); }; // Main configuration file -extern XRCORE_API CInifile const * pSettings; -extern XRCORE_API CInifile const * pSettingsAuth; +extern XRCORE_API CInifile const* pSettings; +extern XRCORE_API CInifile const* pSettingsAuth; #endif //__XR_INI_H__ diff --git a/src/xrCore/xr_resource.h b/src/xrCore/xr_resource.h index 74ce157f1b8..38a1b79acec 100644 --- a/src/xrCore/xr_resource.h +++ b/src/xrCore/xr_resource.h @@ -3,33 +3,36 @@ #pragma once // resource itself, the base class for all derived resources -class XRCORE_API xr_resource { +class XRCORE_API xr_resource +{ public: - enum {RF_REGISTERED=1<<0 }; + enum { RF_REGISTERED = 1 << 0 }; public: - u32 dwReference; - xr_resource() : dwReference(0) { } + u32 dwReference; + xr_resource() : dwReference(0) { } }; -class XRCORE_API xr_resource_flagged : public xr_resource { +class XRCORE_API xr_resource_flagged : public xr_resource +{ public: - enum {RF_REGISTERED=1<<0 }; + enum { RF_REGISTERED = 1 << 0 }; public: - u32 dwFlags; - xr_resource_flagged() : dwFlags(0) { } + u32 dwFlags; + xr_resource_flagged() : dwFlags(0) { } }; -class XRCORE_API xr_resource_named : public xr_resource_flagged { +class XRCORE_API xr_resource_named : public xr_resource_flagged +{ public: - shared_str cName; + shared_str cName; - const char * set_name ( const char * name) - { - cName = name; - return *cName; - } - xr_resource_named() : cName(0) { } - ~xr_resource_named() { } + const char* set_name(const char* name) + { + cName = name; + return *cName; + } + xr_resource_named() : cName(0) { } + ~xr_resource_named() { } }; // resptr_BASE @@ -37,46 +40,46 @@ template class resptr_base { protected: - T * p_; + T* p_; protected: - // ref-counting - void _inc () { if (0==p_) return; p_->dwReference++; } - void _dec () { if (0==p_) return; p_->dwReference--; if (0==p_->dwReference) xr_delete(p_); } + // ref-counting + void _inc() { if (0 == p_) return; p_->dwReference++; } + void _dec() { if (0 == p_) return; p_->dwReference--; if (0 == p_->dwReference) xr_delete(p_); } public: - ICF void _set (T * rhs) { if (0!=rhs) rhs->dwReference++; _dec(); p_ = rhs; } - ICF void _set (resptr_base const & rhs) { T* prhs = rhs._get(); _set(prhs); } - ICF T * _get () const { return p_; } - void _clear () { p_ = 0; } + ICF void _set(T* rhs) { if (0 != rhs) rhs->dwReference++; _dec(); p_ = rhs; } + ICF void _set(resptr_base const& rhs) { T* prhs = rhs._get(); _set(prhs); } + ICF T* _get() const { return p_; } + void _clear() { p_ = 0; } }; // resptr_CORE template -class resptr_core : public C +class resptr_core : public C { protected: - typedef resptr_core this_type; - typedef resptr_core self; + typedef resptr_core this_type; + typedef resptr_core self; public: - // construction - resptr_core () { p_ = 0; } - resptr_core (T * p, bool add_ref = true) { p_ = p; if(add_ref) _inc(); } - resptr_core (const self & rhs) { p_ = rhs.p_; _inc(); } - ~resptr_core () { _dec(); } + // construction + resptr_core() { p_ = 0; } + resptr_core(T* p, bool add_ref = true) { p_ = p; if (add_ref) _inc(); } + resptr_core(const self& rhs) { p_ = rhs.p_; _inc(); } + ~resptr_core() { _dec(); } - // assignment - self & operator= (const self & rhs) { _set(rhs); return (self&)*this; } + // assignment + self& operator= (const self& rhs) { _set(rhs); return (self&)*this; } - // accessors - T & operator*() const { return *p_; } - T * operator->() const { return p_; } + // accessors + T& operator*() const { return *p_; } + T* operator->() const { return p_; } - // unspecified bool type - typedef T * (resptr_core::*unspecified_bool_type) () const; - operator unspecified_bool_type () const { return p_ == 0? 0: &resptr_core::_get; } - bool operator! () const { return p_ == 0; } + // unspecified bool type + typedef T* (resptr_core::*unspecified_bool_type) () const; + operator unspecified_bool_type () const { return p_ == 0 ? 0 : &resptr_core::_get; } + bool operator! () const { return p_ == 0; } - // fast swapping - void swap (self & rhs) { T * tmp = p_; p_ = rhs.p_; rhs.p_ = tmp; } + // fast swapping + void swap(self& rhs) { T* tmp = p_; p_ = rhs.p_; rhs.p_ = tmp; } }; // res_ptr == res_ptr @@ -87,23 +90,23 @@ class resptr_core : public C // ptr != const res_ptr // res_ptr < res_ptr // res_ptr > res_ptr -template inline bool operator == (resptr_core const & a, resptr_core const & b) { return a._get() == b._get(); } -template inline bool operator != (resptr_core const & a, resptr_core const & b) { return a._get() != b._get(); } -template inline bool operator == (resptr_core const & a, T * b) { return a._get() == b; } -template inline bool operator != (resptr_core const & a, T * b) { return a._get() != b; } -template inline bool operator == (T * a, resptr_core const & b) { return a == b._get(); } -template inline bool operator != (T * a, resptr_core const & b) { return a != b._get(); } -template inline bool operator < (resptr_core const & a, resptr_core const & b) { return std::less()(a._get(), b._get()); } -template inline bool operator > (resptr_core const & a, resptr_core const & b) { return std::less()(b._get(), a._get()); } +template inline bool operator == (resptr_core const& a, resptr_core const& b) { return a._get() == b._get(); } +template inline bool operator != (resptr_core const& a, resptr_core const& b) { return a._get() != b._get(); } +template inline bool operator == (resptr_core const& a, T* b) { return a._get() == b; } +template inline bool operator != (resptr_core const& a, T* b) { return a._get() != b; } +template inline bool operator == (T* a, resptr_core const& b) { return a == b._get(); } +template inline bool operator != (T* a, resptr_core const& b) { return a != b._get(); } +template inline bool operator < (resptr_core const& a, resptr_core const& b) { return std::less()(a._get(), b._get()); } +template inline bool operator > (resptr_core const& a, resptr_core const& b) { return std::less()(b._get(), a._get()); } // externally visible swap -template void swap (resptr_core & lhs, resptr_core & rhs) { lhs.swap(rhs); } +template void swap(resptr_core& lhs, resptr_core& rhs) { lhs.swap(rhs); } // mem_fn support -template T * get_pointer(resptr_core const & p) { return p.get(); } +template T* get_pointer(resptr_core const& p) { return p.get(); } // casting -template resptr_core static_pointer_cast(resptr_core const & p) { return static_cast(p.get()); } -template resptr_core dynamic_pointer_cast(resptr_core const & p) { return dynamic_cast(p.get()); } +template resptr_core static_pointer_cast(resptr_core const& p) { return static_cast(p.get()); } +template resptr_core dynamic_pointer_cast(resptr_core const& p) { return dynamic_cast(p.get()); } #endif //xr_resourceH diff --git a/src/xrCore/xr_shared.cpp b/src/xrCore/xr_shared.cpp index cde6556a221..e91060f2cdb 100644 --- a/src/xrCore/xr_shared.cpp +++ b/src/xrCore/xr_shared.cpp @@ -10,14 +10,14 @@ shared_container* CCC=0; typedef shared_item shared_aaa; struct zzz{ - float a; - zzz (float _a):a(_a){} - bool operator() (const shared_str& key, aaa* val) const {return true;} +float a; +zzz (float _a):a(_a){} +bool operator() (const shared_str& key, aaa* val) const {return true;} }; void fff() { - shared_aaa xxx; - xxx.create("",CCC,zzz(0)); +shared_aaa xxx; +xxx.create("",CCC,zzz(0)); } */ \ No newline at end of file diff --git a/src/xrCore/xr_shared.h b/src/xrCore/xr_shared.h index e7c23a334a8..e1b36d95e63 100644 --- a/src/xrCore/xr_shared.h +++ b/src/xrCore/xr_shared.h @@ -5,81 +5,90 @@ class XRCORE_API shared_value { public: - int m_ref_cnt; - virtual ~shared_value (){} + int m_ref_cnt; + virtual ~shared_value() {} }; template class shared_container { protected: - typedef xr_map< shared_str,T* > SharedMap; - typedef typename SharedMap::iterator SharedMapIt; - SharedMap container; + typedef xr_map< shared_str, T* > SharedMap; + typedef typename SharedMap::iterator SharedMapIt; + SharedMap container; public: - shared_container (){} - virtual ~shared_container (){VERIFY(container.empty());} - template - T* dock (shared_str key, const _on_new& p) - { - T* result = 0 ; - SharedMapIt I = container.find (key); - if (I!=container.end()) result = I->second; - if (0==result) { - result = xr_new(); - result->m_ref_cnt = 0; - if (p(key,result)) container.insert(mk_pair(key,result)); - else xr_delete (result); - } - return result; - } - virtual void clean (bool force_destroy) - { - SharedMapIt it = container.begin(); - SharedMapIt _E = container.end(); - if (force_destroy){ - for (; it!=_E; it++){ - T* sv = it->second; - xr_delete (sv); - } - container.clear (); - }else{ - for (; it!=_E; ) { - T* sv = it->second; - if (0==sv->m_ref_cnt){ - SharedMapIt i_current = it; - SharedMapIt i_next = ++it; - xr_delete (sv); - container.erase (i_current); - it = i_next; - }else{ - it++; - } - } - } - } + shared_container() {} + virtual ~shared_container() { VERIFY(container.empty()); } + template + T* dock(shared_str key, const _on_new& p) + { + T* result = 0; + SharedMapIt I = container.find(key); + if (I != container.end()) result = I->second; + if (0 == result) + { + result = xr_new(); + result->m_ref_cnt = 0; + if (p(key, result)) container.insert(mk_pair(key, result)); + else xr_delete(result); + } + return result; + } + virtual void clean(bool force_destroy) + { + SharedMapIt it = container.begin(); + SharedMapIt _E = container.end(); + if (force_destroy) + { + for (; it != _E; it++) + { + T* sv = it->second; + xr_delete(sv); + } + container.clear(); + } + else + { + for (; it != _E;) + { + T* sv = it->second; + if (0 == sv->m_ref_cnt) + { + SharedMapIt i_current = it; + SharedMapIt i_next = ++it; + xr_delete(sv); + container.erase(i_current); + it = i_next; + } + else + { + it++; + } + } + } + } }; template class shared_item { protected: - T* p_; + T* p_; protected: - // ref-counting - void destroy () { if (0==p_) return; p_->m_ref_cnt--; if (0==p_->m_ref_cnt) p_=0; } - void create (shared_item const &rhs) { T* v = rhs.p_; if (0!=v) v->m_ref_cnt++; destroy(); p_ = v; } + // ref-counting + void destroy() { if (0 == p_) return; p_->m_ref_cnt--; if (0 == p_->m_ref_cnt) p_ = 0; } + void create(shared_item const& rhs) { T* v = rhs.p_; if (0 != v) v->m_ref_cnt++; destroy(); p_ = v; } public: - // construction - shared_item () { p_ = 0; } - shared_item (shared_item const &rhs) { p_ = 0; create(rhs); } - ~shared_item () { destroy(); } - // assignment & accessors - shared_item& operator= (shared_item const &rhs) { create(rhs);return *this; } - const T* get_value () { return p_; } - // creating - template - void create (shared_str key, shared_container* container, const _on_new& p){ T* v = container->dock(key,p); if (0!=v) v->m_ref_cnt++; destroy(); p_ = v; } + // construction + shared_item() { p_ = 0; } + shared_item(shared_item const& rhs) { p_ = 0; create(rhs); } + ~shared_item() { destroy(); } + // assignment & accessors + shared_item& operator= (shared_item const& rhs) { create(rhs); return *this; } + const T* get_value() { return p_; } + // creating + template + void create(shared_str key, shared_container* container, const _on_new& p) { T* v = container->dock(key, p); if (0 != v) v->m_ref_cnt++; destroy(); p_ = v; } }; #endif diff --git a/src/xrCore/xr_trims.cpp b/src/xrCore/xr_trims.cpp index a2a32500e05..f3b3de14c01 100644 --- a/src/xrCore/xr_trims.cpp +++ b/src/xrCore/xr_trims.cpp @@ -1,423 +1,462 @@ #include "stdafx.h" #pragma hdrstop -LPSTR _TrimLeft( LPSTR str ) +LPSTR _TrimLeft(LPSTR str) { - LPSTR p = str; - while( *p && (u8(*p)<=u8(' ')) ) p++; - if (p!=str){ - for (LPSTR t=str; *p; t++,p++) *t=*p; + LPSTR p = str; + while (*p && (u8(*p) <= u8(' '))) p++; + if (p != str) + { + for (LPSTR t = str; *p; t++, p++) *t = *p; *t = 0; } - return str; + return str; } -LPSTR _TrimRight( LPSTR str ) +LPSTR _TrimRight(LPSTR str) { - LPSTR p = str+xr_strlen(str); - while( (p!=str) && (u8(*p)<=u8(' ')) ) p--; - *(++p) = 0; - return str; + LPSTR p = str + xr_strlen(str); + while ((p != str) && (u8(*p) <= u8(' '))) p--; + *(++p) = 0; + return str; } -LPSTR _Trim( LPSTR str ) +LPSTR _Trim(LPSTR str) { - _TrimLeft( str ); - _TrimRight( str ); - return str; + _TrimLeft(str); + _TrimRight(str); + return str; } -LPCSTR _SetPos (LPCSTR src, u32 pos, char separator ) +LPCSTR _SetPos(LPCSTR src, u32 pos, char separator) { - LPCSTR res = src; - u32 p = 0; - while( (p0) ? (p-src) : xr_strlen(src); - strncpy ( dst, src, n ); - dst[n] = 0; - return dst; + LPCSTR p; + size_t n; + p = strchr(src, separator); + n = (p > 0) ? (p - src) : xr_strlen(src); + strncpy(dst, src, n); + dst[n] = 0; + return dst; } -int _GetItemCount ( LPCSTR src, char separator ) +int _GetItemCount(LPCSTR src, char separator) { - u32 cnt = 0; - if (src&&src[0]){ - LPCSTR res = src; - LPCSTR last_res = res; - while( 0!=(res=strchr(res,separator)) ) - { - res ++; - last_res=res; - cnt ++; - if (res[0]==separator) break; - } - if (xr_strlen(last_res)) cnt++; - } - return cnt; + u32 cnt = 0; + if (src&&src[0]) + { + LPCSTR res = src; + LPCSTR last_res = res; + while (0 != (res = strchr(res, separator))) + { + res++; + last_res = res; + cnt++; + if (res[0] == separator) break; + } + if (xr_strlen(last_res)) cnt++; + } + return cnt; } -LPSTR _GetItem ( LPCSTR src, int index, LPSTR dst, u32 const dst_size, char separator, LPCSTR def, bool trim ) +LPSTR _GetItem(LPCSTR src, int index, LPSTR dst, u32 const dst_size, char separator, LPCSTR def, bool trim) { - LPCSTR ptr; - ptr = _SetPos ( src, index, separator ); - if( ptr ) _CopyVal ( ptr, dst, separator ); - else xr_strcpy ( dst, dst_size, def ); - if (trim) _Trim ( dst ); - return dst; + LPCSTR ptr; + ptr = _SetPos(src, index, separator); + if (ptr) _CopyVal(ptr, dst, separator); + else xr_strcpy(dst, dst_size, def); + if (trim) _Trim(dst); + return dst; } -LPSTR _GetItems ( LPCSTR src, int idx_start, int idx_end, LPSTR dst, char separator ) +LPSTR _GetItems(LPCSTR src, int idx_start, int idx_end, LPSTR dst, char separator) { - LPSTR n = dst; + LPSTR n = dst; int level = 0; - for (LPCSTR p=src; *p!=0; p++){ - if ((level>=idx_start)&&(level=idx_end) break; + for (LPCSTR p = src; *p != 0; p++) + { + if ((level >= idx_start) && (level < idx_end)) + *n++ = *p; + if (*p == separator) level++; + if (level >= idx_end) break; } *n = '\0'; - return dst; + return dst; } -u32 _ParseItem ( LPCSTR src, xr_token* token_list ) +u32 _ParseItem(LPCSTR src, xr_token* token_list) { - for( int i=0; token_list[i].name; i++ ) - if( !stricmp(src,token_list[i].name) ) - return token_list[i].id; - return u32(-1); + for (int i = 0; token_list[i].name; i++) + if (!stricmp(src, token_list[i].name)) + return token_list[i].id; + return u32(-1); } -u32 _ParseItem ( LPSTR src, int ind, xr_token* token_list ) +u32 _ParseItem(LPSTR src, int ind, xr_token* token_list) { - char dst[128]; - _GetItem(src, ind, dst); - return _ParseItem(dst, token_list); + char dst[128]; + _GetItem(src, ind, dst); + return _ParseItem(dst, token_list); } -LPSTR _ReplaceItems( LPCSTR src, int idx_start, int idx_end, LPCSTR new_items, LPSTR dst, char separator ){ - LPSTR n = dst; +LPSTR _ReplaceItems(LPCSTR src, int idx_start, int idx_end, LPCSTR new_items, LPSTR dst, char separator) +{ + LPSTR n = dst; int level = 0; bool bCopy = true; - for (LPCSTR p=src; *p!=0; p++){ - if ((level>=idx_start)&&(level= idx_start) && (level < idx_end)) + { + if (bCopy) + { + for (LPCSTR itm = new_items; *itm != 0;) *n++ = *itm++; + bCopy = false; } - if (*p==separator) *n++ = separator; - }else{ - *n++ = *p; + if (*p == separator) *n++ = separator; + } + else + { + *n++ = *p; } - if (*p==separator) level++; + if (*p == separator) level++; } *n = '\0'; - return dst; + return dst; } -LPSTR _ReplaceItem ( LPCSTR src, int index, LPCSTR new_item, LPSTR dst, char separator ){ - LPSTR n = dst; +LPSTR _ReplaceItem(LPCSTR src, int index, LPCSTR new_item, LPSTR dst, char separator) +{ + LPSTR n = dst; int level = 0; bool bCopy = true; - for (LPCSTR p=src; *p!=0; p++){ - if (level==index){ - if (bCopy){ - for (LPCSTR itm = new_item; *itm!=0;) *n++ = *itm++; - bCopy=false; + for (LPCSTR p = src; *p != 0; p++) + { + if (level == index) + { + if (bCopy) + { + for (LPCSTR itm = new_item; *itm != 0;) *n++ = *itm++; + bCopy = false; } - if (*p==separator) *n++ = separator; - }else{ - *n++ = *p; + if (*p == separator) *n++ = separator; } - if (*p==separator) level++; + else + { + *n++ = *p; + } + if (*p == separator) level++; } *n = '\0'; - return dst; + return dst; } -LPSTR _ChangeSymbol ( LPSTR name, char src, char dest ) +LPSTR _ChangeSymbol(LPSTR name, char src, char dest) { - char *sTmpName = name; - while(sTmpName[0] ){ - if (sTmpName[0] == src) sTmpName[0] = dest; - sTmpName ++; - } - return name; + char* sTmpName = name; + while (sTmpName[0]) + { + if (sTmpName[0] == src) sTmpName[0] = dest; + sTmpName++; + } + return name; } -xr_string& _ChangeSymbol ( xr_string& name, char src, char dest ) +xr_string& _ChangeSymbol(xr_string& name, char src, char dest) { - for (xr_string::iterator it=name.begin(); it!=name.end(); it++) - if (*it==src) *it=xr_string::value_type(dest); - return name; + for (xr_string::iterator it = name.begin(); it != name.end(); it++) + if (*it == src) *it = xr_string::value_type(dest); + return name; } #ifdef M_BORLAND -AnsiString& _ReplaceItem ( LPCSTR src, int index, LPCSTR new_item, AnsiString& dst, char separator ) +AnsiString& _ReplaceItem(LPCSTR src, int index, LPCSTR new_item, AnsiString& dst, char separator) { - dst = ""; + dst = ""; int level = 0; bool bCopy = true; - for (LPCSTR p=src; *p!=0; p++){ - if (level==index){ - if (bCopy){ - for (LPCSTR itm = new_item; *itm!=0;) dst += *itm++; - bCopy=false; + for (LPCSTR p = src; *p != 0; p++) + { + if (level == index) + { + if (bCopy) + { + for (LPCSTR itm = new_item; *itm != 0;) dst += *itm++; + bCopy = false; } - if (*p==separator) dst += separator; - }else{ - dst += *p; + if (*p == separator) dst += separator; + } + else + { + dst += *p; } - if (*p==separator) level++; + if (*p == separator) level++; } - return dst; + return dst; } -AnsiString& _ReplaceItems ( LPCSTR src, int idx_start, int idx_end, LPCSTR new_items, AnsiString& dst, char separator ) +AnsiString& _ReplaceItems(LPCSTR src, int idx_start, int idx_end, LPCSTR new_items, AnsiString& dst, char separator) { - dst = ""; + dst = ""; int level = 0; bool bCopy = true; - for (LPCSTR p=src; *p!=0; p++){ - if ((level>=idx_start)&&(level= idx_start) && (level < idx_end)) + { + if (bCopy) + { + for (LPCSTR itm = new_items; *itm != 0;) dst += *itm++; + bCopy = false; } - if (*p==separator) dst += separator; - }else{ - dst += *p; + if (*p == separator) dst += separator; } - if (*p==separator) level++; + else + { + dst += *p; + } + if (*p == separator) level++; } - return dst; + return dst; } -AnsiString& _Trim( AnsiString& str ) +AnsiString& _Trim(AnsiString& str) { - return str=str.Trim(); + return str = str.Trim(); } -LPCSTR _CopyVal ( LPCSTR src, AnsiString& dst, char separator ) +LPCSTR _CopyVal(LPCSTR src, AnsiString& dst, char separator) { - LPCSTR p; - u32 n; - p = strchr ( src, separator ); - n = (p>0) ? (p-src) : xr_strlen(src); - dst = src; - dst = dst.Delete(n+1,dst.Length()); - return dst.c_str(); + LPCSTR p; + u32 n; + p = strchr(src, separator); + n = (p > 0) ? (p - src) : xr_strlen(src); + dst = src; + dst = dst.Delete(n + 1, dst.Length()); + return dst.c_str(); } -LPCSTR _GetItems ( LPCSTR src, int idx_start, int idx_end, AnsiString& dst, char separator ) +LPCSTR _GetItems(LPCSTR src, int idx_start, int idx_end, AnsiString& dst, char separator) { - int level = 0; - for (LPCSTR p=src; *p!=0; p++){ - if ((level>=idx_start)&&(level=idx_end) break; - } - return dst.c_str(); + int level = 0; + for (LPCSTR p = src; *p != 0; p++) + { + if ((level >= idx_start) && (level < idx_end)) + dst += *p; + if (*p == separator) level++; + if (level >= idx_end) break; + } + return dst.c_str(); } -LPCSTR _GetItem ( LPCSTR src, int index, AnsiString& dst, char separator, LPCSTR def, bool trim ) +LPCSTR _GetItem(LPCSTR src, int index, AnsiString& dst, char separator, LPCSTR def, bool trim) { - LPCSTR ptr; - ptr = _SetPos ( src, index, separator ); - if( ptr ) _CopyVal ( ptr, dst, separator ); - else dst = def; - if (trim) dst = dst.Trim(); - return dst.c_str(); + LPCSTR ptr; + ptr = _SetPos(src, index, separator); + if (ptr) _CopyVal(ptr, dst, separator); + else dst = def; + if (trim) dst = dst.Trim(); + return dst.c_str(); } AnsiString _ListToSequence(const AStringVec& lst) { - AnsiString out; - out = ""; - if (lst.size()){ - out = lst.front(); - for (AStringVec::const_iterator s_it=lst.begin()+1; s_it!=lst.end(); s_it++) - out += AnsiString(",")+(*s_it); - } - return out; + AnsiString out; + out = ""; + if (lst.size()) + { + out = lst.front(); + for (AStringVec::const_iterator s_it = lst.begin() + 1; s_it != lst.end(); s_it++) + out += AnsiString(",") + (*s_it); + } + return out; } AnsiString _ListToSequence2(const AStringVec& lst) { - AnsiString out; - out = ""; - if (lst.size()){ - out = lst.front(); - for (AStringVec::const_iterator s_it=lst.begin()+1; s_it!=lst.end(); s_it++){ - out += AnsiString("\n")+(*s_it); - } - } - return out; + AnsiString out; + out = ""; + if (lst.size()) + { + out = lst.front(); + for (AStringVec::const_iterator s_it = lst.begin() + 1; s_it != lst.end(); s_it++) + { + out += AnsiString("\n") + (*s_it); + } + } + return out; } void _SequenceToList(AStringVec& lst, LPCSTR in, char separator) { - lst.clear(); - int t_cnt=_GetItemCount(in,separator); - AnsiString T; - for (int i=0; i0) ? (p-src) : xr_strlen(src); - dst = src; - dst = dst.erase (n,dst.length()); - return dst.c_str(); + LPCSTR p; + ptrdiff_t n; + p = strchr(src, separator); + n = (p > 0) ? (p - src) : xr_strlen(src); + dst = src; + dst = dst.erase(n, dst.length()); + return dst.c_str(); } -LPCSTR _GetItem ( LPCSTR src, int index, xr_string& dst, char separator, LPCSTR def, bool trim ) +LPCSTR _GetItem(LPCSTR src, int index, xr_string& dst, char separator, LPCSTR def, bool trim) { - LPCSTR ptr; - ptr = _SetPos ( src, index, separator ); - if( ptr ) _CopyVal ( ptr, dst, separator ); - else dst = def; - if (trim) _Trim (dst); - return dst.c_str (); + LPCSTR ptr; + ptr = _SetPos(src, index, separator); + if (ptr) _CopyVal(ptr, dst, separator); + else dst = def; + if (trim) _Trim(dst); + return dst.c_str(); } -shared_str _ListToSequence(const RStringVec& lst) +shared_str _ListToSequence(const RStringVec& lst) { - xr_string out; - if (lst.size()){ - out = *lst.front(); - for (RStringVec::const_iterator s_it=lst.begin()+1; s_it!=lst.end(); s_it++){ - out += ","; - out += **s_it; + xr_string out; + if (lst.size()) + { + out = *lst.front(); + for (RStringVec::const_iterator s_it = lst.begin() + 1; s_it != lst.end(); s_it++) + { + out += ","; + out += **s_it; } - } - return shared_str (out.c_str()); + } + return shared_str(out.c_str()); } diff --git a/src/xrCore/xr_trims.h b/src/xrCore/xr_trims.h index 24364992ebc..08aae9590c4 100644 --- a/src/xrCore/xr_trims.h +++ b/src/xrCore/xr_trims.h @@ -5,50 +5,50 @@ struct xr_token; #ifdef __BORLANDC__ - XRCORE_API AnsiString& _Trim ( AnsiString& str ); - XRCORE_API LPCSTR _GetItem ( LPCSTR src, int, AnsiString& p, char separator=',', LPCSTR ="", bool trim=true); - XRCORE_API LPCSTR _GetItems ( LPCSTR src, int idx_start, int idx_end, AnsiString& dst, char separator ); - XRCORE_API LPCSTR _CopyVal ( LPCSTR src, AnsiString& dst, char separator=',' ); - XRCORE_API AnsiString _ListToSequence ( const AStringVec& lst ); - XRCORE_API AnsiString _ListToSequence2 ( const AStringVec& lst ); - XRCORE_API void _SequenceToList ( AStringVec& lst, LPCSTR in, char separator=',' ); - XRCORE_API AnsiString& _ReplaceItem ( LPCSTR src, int index, LPCSTR new_item, AnsiString& dst, char separator ); - XRCORE_API AnsiString& _ReplaceItems ( LPCSTR src, int idx_start, int idx_end, LPCSTR new_items, AnsiString& dst, char separator ); - XRCORE_API AnsiString FloatTimeToStrTime (float v, bool h=true, bool m=true, bool s=true, bool ms=false); - XRCORE_API float StrTimeToFloatTime (LPCSTR buf, bool h=true, bool m=true, bool s=true, bool ms=false); +XRCORE_API AnsiString& _Trim ( AnsiString& str ); +XRCORE_API LPCSTR _GetItem ( LPCSTR src, int, AnsiString& p, char separator=',', LPCSTR ="", bool trim=true); +XRCORE_API LPCSTR _GetItems ( LPCSTR src, int idx_start, int idx_end, AnsiString& dst, char separator ); +XRCORE_API LPCSTR _CopyVal ( LPCSTR src, AnsiString& dst, char separator=',' ); +XRCORE_API AnsiString _ListToSequence ( const AStringVec& lst ); +XRCORE_API AnsiString _ListToSequence2 ( const AStringVec& lst ); +XRCORE_API void _SequenceToList ( AStringVec& lst, LPCSTR in, char separator=',' ); +XRCORE_API AnsiString& _ReplaceItem ( LPCSTR src, int index, LPCSTR new_item, AnsiString& dst, char separator ); +XRCORE_API AnsiString& _ReplaceItems ( LPCSTR src, int idx_start, int idx_end, LPCSTR new_items, AnsiString& dst, char separator ); +XRCORE_API AnsiString FloatTimeToStrTime (float v, bool h=true, bool m=true, bool s=true, bool ms=false); +XRCORE_API float StrTimeToFloatTime (LPCSTR buf, bool h=true, bool m=true, bool s=true, bool ms=false); #endif -XRCORE_API int _GetItemCount ( LPCSTR , char separator=','); -XRCORE_API LPSTR _GetItem ( LPCSTR, int, LPSTR, u32 const dst_size, char separator=',', LPCSTR ="", bool trim=true ); +XRCORE_API int _GetItemCount(LPCSTR, char separator = ','); +XRCORE_API LPSTR _GetItem(LPCSTR, int, LPSTR, u32 const dst_size, char separator = ',', LPCSTR = "", bool trim = true); template -inline LPSTR _GetItem ( LPCSTR src, int index, char (&dst)[count], char separator=',', LPCSTR def="", bool trim=true ) +inline LPSTR _GetItem(LPCSTR src, int index, char(&dst)[count], char separator = ',', LPCSTR def = "", bool trim = true) { - return _GetItem(src,index,dst,count,separator,def,trim); + return _GetItem(src, index, dst, count, separator, def, trim); } -XRCORE_API LPSTR _GetItems ( LPCSTR, int, int, LPSTR, char separator=','); -XRCORE_API LPCSTR _SetPos ( LPCSTR src, u32 pos, char separator=',' ); -XRCORE_API LPCSTR _CopyVal ( LPCSTR src, LPSTR dst, char separator=',' ); -XRCORE_API LPSTR _Trim ( LPSTR str ); -XRCORE_API LPSTR _TrimLeft ( LPSTR str ); -XRCORE_API LPSTR _TrimRight ( LPSTR str ); -XRCORE_API LPSTR _ChangeSymbol ( LPSTR name, char src, char dest ); -XRCORE_API u32 _ParseItem ( LPCSTR src, xr_token* token_list ); -XRCORE_API u32 _ParseItem ( LPSTR src, int ind, xr_token* token_list ); -XRCORE_API LPSTR _ReplaceItem ( LPCSTR src, int index, LPCSTR new_item, LPSTR dst, char separator ); -XRCORE_API LPSTR _ReplaceItems ( LPCSTR src, int idx_start, int idx_end, LPCSTR new_items, LPSTR dst, char separator ); -XRCORE_API void _SequenceToList ( LPSTRVec& lst, LPCSTR in, char separator=',' ); -XRCORE_API void _SequenceToList ( RStringVec& lst, LPCSTR in, char separator=',' ); -XRCORE_API void _SequenceToList ( SStringVec& lst, LPCSTR in, char separator=',' ); +XRCORE_API LPSTR _GetItems(LPCSTR, int, int, LPSTR, char separator = ','); +XRCORE_API LPCSTR _SetPos(LPCSTR src, u32 pos, char separator = ','); +XRCORE_API LPCSTR _CopyVal(LPCSTR src, LPSTR dst, char separator = ','); +XRCORE_API LPSTR _Trim(LPSTR str); +XRCORE_API LPSTR _TrimLeft(LPSTR str); +XRCORE_API LPSTR _TrimRight(LPSTR str); +XRCORE_API LPSTR _ChangeSymbol(LPSTR name, char src, char dest); +XRCORE_API u32 _ParseItem(LPCSTR src, xr_token* token_list); +XRCORE_API u32 _ParseItem(LPSTR src, int ind, xr_token* token_list); +XRCORE_API LPSTR _ReplaceItem(LPCSTR src, int index, LPCSTR new_item, LPSTR dst, char separator); +XRCORE_API LPSTR _ReplaceItems(LPCSTR src, int idx_start, int idx_end, LPCSTR new_items, LPSTR dst, char separator); +XRCORE_API void _SequenceToList(LPSTRVec& lst, LPCSTR in, char separator = ','); +XRCORE_API void _SequenceToList(RStringVec& lst, LPCSTR in, char separator = ','); +XRCORE_API void _SequenceToList(SStringVec& lst, LPCSTR in, char separator = ','); -XRCORE_API xr_string& _Trim ( xr_string& src ); -XRCORE_API xr_string& _TrimLeft ( xr_string& src ); -XRCORE_API xr_string& _TrimRight ( xr_string& src ); -XRCORE_API xr_string& _ChangeSymbol ( xr_string& name, char src, char dest ); -XRCORE_API LPCSTR _CopyVal ( LPCSTR src, xr_string& dst, char separator=',' ); -XRCORE_API LPCSTR _GetItem ( LPCSTR src, int, xr_string& p, char separator=',', LPCSTR ="", bool trim=true ); -XRCORE_API xr_string _ListToSequence ( const SStringVec& lst ); -XRCORE_API shared_str _ListToSequence ( const RStringVec& lst ); +XRCORE_API xr_string& _Trim(xr_string& src); +XRCORE_API xr_string& _TrimLeft(xr_string& src); +XRCORE_API xr_string& _TrimRight(xr_string& src); +XRCORE_API xr_string& _ChangeSymbol(xr_string& name, char src, char dest); +XRCORE_API LPCSTR _CopyVal(LPCSTR src, xr_string& dst, char separator = ','); +XRCORE_API LPCSTR _GetItem(LPCSTR src, int, xr_string& p, char separator = ',', LPCSTR = "", bool trim = true); +XRCORE_API xr_string _ListToSequence(const SStringVec& lst); +XRCORE_API shared_str _ListToSequence(const RStringVec& lst); #endif \ No newline at end of file diff --git a/src/xrCore/xrsharedmem.cpp b/src/xrCore/xrsharedmem.cpp index a3b2c1c6403..906f80e7f96 100644 --- a/src/xrCore/xrsharedmem.cpp +++ b/src/xrCore/xrsharedmem.cpp @@ -3,101 +3,104 @@ using namespace std; -XRCORE_API smem_container* g_pSharedMemoryContainer = NULL; +XRCORE_API smem_container* g_pSharedMemoryContainer = NULL; -smem_value* smem_container::dock (u32 dwCRC, u32 dwLength, void* ptr) +smem_value* smem_container::dock(u32 dwCRC, u32 dwLength, void* ptr) { - VERIFY (dwCRC && dwLength && ptr); + VERIFY(dwCRC && dwLength && ptr); - cs.Enter (); - smem_value* result = 0; + cs.Enter(); + smem_value* result = 0; - // search a place to insert - u8 storage [4*sizeof(u32)]; - smem_value* value = (smem_value*)storage; - value->dwReference = 0; - value->dwCRC = dwCRC; - value->dwLength = dwLength; - cdb::iterator it = std::lower_bound (container.begin(),container.end(),value,smem_search); - cdb::iterator saved_place = it; - if (container.end() != it) { - // supposedly found - for (;; it++) { - if (it==container.end()) break; - if ((*it)->dwCRC != dwCRC) break; - if ((*it)->dwLength != dwLength) break; - if (0==memcmp((*it)->value,ptr,dwLength)) - { - // really found - result = *it; - break; - } - } - } + // search a place to insert + u8 storage[4 * sizeof(u32)]; + smem_value* value = (smem_value*)storage; + value->dwReference = 0; + value->dwCRC = dwCRC; + value->dwLength = dwLength; + cdb::iterator it = std::lower_bound(container.begin(), container.end(), value, smem_search); + cdb::iterator saved_place = it; + if (container.end() != it) + { + // supposedly found + for (;; it++) + { + if (it == container.end()) break; + if ((*it)->dwCRC != dwCRC) break; + if ((*it)->dwLength != dwLength) break; + if (0 == memcmp((*it)->value, ptr, dwLength)) + { + // really found + result = *it; + break; + } + } + } - // if not found - create new entry - if (0==result) - { - result = (smem_value*) Memory.mem_alloc (4*sizeof(u32) + dwLength + // if not found - create new entry + if (0 == result) + { + result = (smem_value*)Memory.mem_alloc(4 * sizeof(u32) + dwLength #ifdef DEBUG_MEMORY_NAME - , "storage: smem" + , "storage: smem" #endif // DEBUG_MEMORY_NAME - ); - result->dwReference = 0; - result->dwCRC = dwCRC; - result->dwLength = dwLength; - CopyMemory (result->value,ptr,dwLength); - container.insert (saved_place,result); - } + ); + result->dwReference = 0; + result->dwCRC = dwCRC; + result->dwLength = dwLength; + CopyMemory(result->value, ptr, dwLength); + container.insert(saved_place, result); + } - // exit - cs.Leave (); - return result; + // exit + cs.Leave(); + return result; } -void smem_container::clean () +void smem_container::clean() { - cs.Enter (); - cdb::iterator it = container.begin (); - cdb::iterator end = container.end (); - for (; it!=end; it++) if (0==(*it)->dwReference) xr_free (*it); - container.erase (remove(container.begin(),container.end(),(smem_value*)0),container.end()); - if (container.empty()) container.clear (); - cs.Leave (); + cs.Enter(); + cdb::iterator it = container.begin(); + cdb::iterator end = container.end(); + for (; it != end; it++) if (0 == (*it)->dwReference) xr_free(*it); + container.erase(remove(container.begin(), container.end(), (smem_value*)0), container.end()); + if (container.empty()) container.clear(); + cs.Leave(); } -void smem_container::dump () +void smem_container::dump() { - cs.Enter (); - cdb::iterator it = container.begin (); - cdb::iterator end = container.end (); - FILE* F = fopen("x:\\$smem_dump$.txt","w"); - for (; it!=end; it++) - fprintf (F,"%4u : crc[%6x], %u bytes\n",(*it)->dwReference,(*it)->dwCRC,(*it)->dwLength); - fclose (F); - cs.Leave (); + cs.Enter(); + cdb::iterator it = container.begin(); + cdb::iterator end = container.end(); + FILE* F = fopen("x:\\$smem_dump$.txt", "w"); + for (; it != end; it++) + fprintf(F, "%4u : crc[%6x], %u bytes\n", (*it)->dwReference, (*it)->dwCRC, (*it)->dwLength); + fclose(F); + cs.Leave(); } -u32 smem_container::stat_economy () +u32 smem_container::stat_economy() { - cs.Enter (); - cdb::iterator it = container.begin (); - cdb::iterator end = container.end (); - s64 counter = 0; - counter -= sizeof(*this); - counter -= sizeof(cdb::allocator_type); - const int node_size = 20; - for (; it!=end; it++) { - counter -= 16; - counter -= node_size; - counter += s64((s64((*it)->dwReference) - 1)*s64((*it)->dwLength)); - } - cs.Leave (); + cs.Enter(); + cdb::iterator it = container.begin(); + cdb::iterator end = container.end(); + s64 counter = 0; + counter -= sizeof(*this); + counter -= sizeof(cdb::allocator_type); + const int node_size = 20; + for (; it != end; it++) + { + counter -= 16; + counter -= node_size; + counter += s64((s64((*it)->dwReference) - 1)*s64((*it)->dwLength)); + } + cs.Leave(); - return u32(s64(counter)/s64(1024)); + return u32(s64(counter) / s64(1024)); } -smem_container::~smem_container () +smem_container::~smem_container() { - clean (); + clean(); } diff --git a/src/xrCore/xrsharedmem.h b/src/xrCore/xrsharedmem.h index d3f1b0b119b..4912b5beff3 100644 --- a/src/xrCore/xrsharedmem.h +++ b/src/xrCore/xrsharedmem.h @@ -1,97 +1,101 @@ -#ifndef xrsharedmemH +#ifndef xrsharedmemH #define xrsharedmemH #pragma once #pragma pack(push,4) ////////////////////////////////////////////////////////////////////////// #pragma warning(disable : 4200) -struct XRCORE_API smem_value +struct XRCORE_API smem_value { - u32 dwReference ; - u32 dwCRC ; - u32 dwLength ; - u32 _align_16 ; - u8 value [] ; + u32 dwReference; + u32 dwCRC; + u32 dwLength; + u32 _align_16; + u8 value[]; }; // generic predicate for "less" -IC bool smem_sort (const smem_value* A, const smem_value* B) { - if (A->dwCRC < B->dwCRC) return true; - if (A->dwCRC > B->dwCRC) return false; - if (A->dwLength < B->dwLength) return true; - if (A->dwLength > B->dwLength) return false; - return memcmp(A->value,B->value,A->dwLength)<0; +IC bool smem_sort(const smem_value* A, const smem_value* B) +{ + if (A->dwCRC < B->dwCRC) return true; + if (A->dwCRC > B->dwCRC) return false; + if (A->dwLength < B->dwLength) return true; + if (A->dwLength > B->dwLength) return false; + return memcmp(A->value, B->value, A->dwLength) < 0; }; // predicate for insertion - just a quick estimate -IC bool smem_search (const smem_value* A, const smem_value* B) { - if (A->dwCRC < B->dwCRC) return true; - if (A->dwCRC > B->dwCRC) return false; - return A->dwLength < B->dwLength; +IC bool smem_search(const smem_value* A, const smem_value* B) +{ + if (A->dwCRC < B->dwCRC) return true; + if (A->dwCRC > B->dwCRC) return false; + return A->dwLength < B->dwLength; }; // predicate for exact (byte level) comparition -IC bool smem_equal (const smem_value* A, u32 dwCRC, u32 dwLength, u8* ptr) +IC bool smem_equal(const smem_value* A, u32 dwCRC, u32 dwLength, u8* ptr) { - if (A->dwCRC != dwCRC) return false; - if (A->dwLength != dwLength) return false; - return 0==memcmp(A->value,ptr,dwLength); + if (A->dwCRC != dwCRC) return false; + if (A->dwLength != dwLength) return false; + return 0 == memcmp(A->value, ptr, dwLength); }; #pragma warning(default : 4200) ////////////////////////////////////////////////////////////////////////// -class XRCORE_API smem_container +class XRCORE_API smem_container { private: - typedef xr_vector cdb; - xrCriticalSection cs; - cdb container; + typedef xr_vector cdb; + xrCriticalSection cs; + cdb container; public: - smem_value* dock (u32 dwCRC, u32 dwLength, void* ptr); - void clean (); - void dump (); - u32 stat_economy (); + smem_value* dock(u32 dwCRC, u32 dwLength, void* ptr); + void clean(); + void dump(); + u32 stat_economy(); #ifdef PROFILE_CRITICAL_SECTIONS - smem_container ():cs(MUTEX_PROFILE_ID(smem_container)){} + smem_container ():cs(MUTEX_PROFILE_ID(smem_container)) {} #endif // PROFILE_CRITICAL_SECTIONS - ~smem_container (); + ~smem_container(); }; -XRCORE_API extern smem_container* g_pSharedMemoryContainer; +XRCORE_API extern smem_container* g_pSharedMemoryContainer; ////////////////////////////////////////////////////////////////////////// template -class ref_smem +class ref_smem { private: - smem_value* p_; + smem_value* p_; protected: - // ref-counting - void _dec () { if (0==p_) return; p_->dwReference--; if (0==p_->dwReference) p_=0; } + // ref-counting + void _dec() { if (0 == p_) return; p_->dwReference--; if (0 == p_->dwReference) p_ = 0; } public: - void _set (ref_smem const &rhs) { smem_value* v = rhs.p_; if (0!=v) v->dwReference++; _dec(); p_ = v; } - const smem_value* _get () const { return p_; } + void _set(ref_smem const& rhs) { smem_value* v = rhs.p_; if (0 != v) v->dwReference++; _dec(); p_ = v; } + const smem_value* _get() const { return p_; } public: - // construction - ref_smem () { p_ = 0; } - ref_smem (ref_smem const &rhs) { p_ = 0; _set(rhs); } - ~ref_smem () { _dec(); } + // construction + ref_smem() { p_ = 0; } + ref_smem(ref_smem const& rhs) { p_ = 0; _set(rhs); } + ~ref_smem() { _dec(); } - void create (u32 dwCRC, u32 dwLength, T* ptr) - { - smem_value* v = g_pSharedMemoryContainer->dock(dwCRC,dwLength*sizeof(T),ptr); - if (0!=v) v->dwReference++; _dec(); p_ = v; - } + void create(u32 dwCRC, u32 dwLength, T* ptr) + { + smem_value* v = g_pSharedMemoryContainer->dock(dwCRC, dwLength*sizeof(T), ptr); + if (0 != v) v->dwReference++; + _dec(); + p_ = v; + } - // assignment & accessors - ref_smem& operator= (ref_smem const &rhs) { _set(rhs); return (ref_smem&)*this; } - T* operator* () const { return p_?(T*)p_->value:0; } - bool operator! () const { return p_ == 0; } - T& operator[] (size_t id) { return ((T*)(p_->value))[id]; } -const T& operator[] (size_t id) const { return ((T*)(p_->value))[id]; } - // misc func - u32 size () { if (0==p_) return 0; else return p_->dwLength/sizeof(T); } - void swap (ref_smem & rhs) { smem_value* tmp = p_; p_ = rhs.p_; rhs.p_ = tmp; } - bool equal (ref_smem & rhs) { return p_ == rhs.p_; } - u32 ref_count () { if (0==p_) return 0; else return p_->dwReference; } + // assignment & accessors + ref_smem& operator= (ref_smem const& rhs) { _set(rhs); return (ref_smem&)*this; } + T* operator* () const { return p_ ? (T*)p_->value : 0; } + bool operator! () const { return p_ == 0; } + T& operator[] (size_t id) { return ((T*)(p_->value))[id]; } + const T& operator[] (size_t id) const { return ((T*)(p_->value))[id]; } + // misc func + u32 size() { if (0 == p_) return 0; else return p_->dwLength / sizeof(T); } + void swap(ref_smem& rhs) { smem_value* tmp = p_; p_ = rhs.p_; rhs.p_ = tmp; } + bool equal(ref_smem& rhs) { return p_ == rhs.p_; } + u32 ref_count() { if (0 == p_) return 0; else return p_->dwReference; } }; // res_ptr == res_ptr @@ -103,17 +107,17 @@ const T& operator[] (size_t id) const { return ((T*)(p_->value))[id]; // res_ptr < res_ptr // res_ptr > res_ptr template -IC bool operator == (ref_smem const & a, ref_smem const & b) { return a._get() == b._get(); } +IC bool operator == (ref_smem const& a, ref_smem const& b) { return a._get() == b._get(); } template -IC bool operator != (ref_smem const & a, ref_smem const & b) { return a._get() != b._get(); } +IC bool operator != (ref_smem const& a, ref_smem const& b) { return a._get() != b._get(); } template -IC bool operator < (ref_smem const & a, ref_smem const & b) { return a._get() < b._get(); } +IC bool operator < (ref_smem const& a, ref_smem const& b) { return a._get() < b._get(); } template -IC bool operator > (ref_smem const & a, ref_smem const & b) { return a._get() > b._get(); } +IC bool operator > (ref_smem const& a, ref_smem const& b) { return a._get() > b._get(); } // externally visible standart functionality template -IC void swap (ref_smem & lhs, ref_smem & rhs) { lhs.swap(rhs); } +IC void swap(ref_smem& lhs, ref_smem& rhs) { lhs.swap(rhs); } #pragma pack(pop) diff --git a/src/xrCore/xrstring.cpp b/src/xrCore/xrstring.cpp index a3d381f9351..76c2ba93237 100644 --- a/src/xrCore/xrstring.cpp +++ b/src/xrCore/xrstring.cpp @@ -5,429 +5,438 @@ #include "FS_impl.h" -XRCORE_API extern str_container* g_pStringContainer = NULL; -#define HEADER 16 // ref + len + crc + next +XRCORE_API extern str_container* g_pStringContainer = NULL; +#define HEADER 16 // ref + len + crc + next #if 1 struct str_container_impl { - static const u32 buffer_size = 1024*256; - str_value* buffer[buffer_size]; - int num_docs; - - str_container_impl () - { - num_docs = 0; - ZeroMemory(buffer, sizeof(buffer)); - } - - str_value* find (str_value* value, const char* str) - { - str_value* candidate = buffer[ value->dwCRC % buffer_size ]; - while ( candidate ) - { - if ( candidate->dwCRC == value->dwCRC && - candidate->dwLength == value->dwLength && - !memcmp(candidate->value, str, value->dwLength) ) - { - return candidate; - } - - candidate = candidate->next; - } - - return NULL; - } - - void insert (str_value* value) - { - str_value** element = &buffer[ value->dwCRC % buffer_size ]; - value->next = *element; - *element = value; - } - - void clean () - { - for ( u32 i=0; idwReference ) - { - *current = value->next; - xr_free(value); - } - else - { - current = &value->next; - } - } - } - } - - void verify () - { - Msg ("strings verify started"); - for ( u32 i=0; ivalue, value->dwLength); - string32 crc_str; - R_ASSERT3 (crc==value->dwCRC, "CorePanic: read-only memory corruption (shared_strings)", itoa(value->dwCRC,crc_str,16)); - R_ASSERT3 (value->dwLength == xr_strlen(value->value), "CorePanic: read-only memory corruption (shared_strings, internal structures)", value->value); - value = value->next; - } - } - Msg ("strings verify completed"); - } - - void dump (FILE* f) const - { - for ( u32 i=0; idwReference,value->dwLength,value->dwCRC,value->value); - value = value->next; - } - } - } - - void dump (IWriter* f) const - { - for ( u32 i=0; idwReference, value->dwLength, value->dwCRC, value->value); - f->w_string (temp); - value = value->next; - } - } - } - - int stat_economy () - { - int counter = 0; - for ( u32 i=0; idwReference-1)*(value->dwLength+1); - value = value->next; - } - } - - return counter; - } + static const u32 buffer_size = 1024 * 256; + str_value* buffer[buffer_size]; + int num_docs; + + str_container_impl() + { + num_docs = 0; + ZeroMemory(buffer, sizeof(buffer)); + } + + str_value* find(str_value* value, const char* str) + { + str_value* candidate = buffer[value->dwCRC % buffer_size]; + while (candidate) + { + if (candidate->dwCRC == value->dwCRC && + candidate->dwLength == value->dwLength && + !memcmp(candidate->value, str, value->dwLength)) + { + return candidate; + } + + candidate = candidate->next; + } + + return NULL; + } + + void insert(str_value* value) + { + str_value** element = &buffer[value->dwCRC % buffer_size]; + value->next = *element; + *element = value; + } + + void clean() + { + for (u32 i = 0; i < buffer_size; ++i) + { + str_value** current = &buffer[i]; + + while (*current != NULL) + { + str_value* value = *current; + if (!value->dwReference) + { + *current = value->next; + xr_free(value); + } + else + { + current = &value->next; + } + } + } + } + + void verify() + { + Msg("strings verify started"); + for (u32 i = 0; i < buffer_size; ++i) + { + str_value* value = buffer[i]; + while (value) + { + u32 crc = crc32(value->value, value->dwLength); + string32 crc_str; + R_ASSERT3(crc == value->dwCRC, "CorePanic: read-only memory corruption (shared_strings)", itoa(value->dwCRC, crc_str, 16)); + R_ASSERT3(value->dwLength == xr_strlen(value->value), "CorePanic: read-only memory corruption (shared_strings, internal structures)", value->value); + value = value->next; + } + } + Msg("strings verify completed"); + } + + void dump(FILE* f) const + { + for (u32 i = 0; i < buffer_size; ++i) + { + str_value* value = buffer[i]; + while (value) + { + fprintf(f, "ref[%4u]-len[%3u]-crc[%8X] : %s\n", value->dwReference, value->dwLength, value->dwCRC, value->value); + value = value->next; + } + } + } + + void dump(IWriter* f) const + { + for (u32 i = 0; i < buffer_size; ++i) + { + str_value* value = buffer[i]; + string4096 temp; + while (value) + { + xr_sprintf(temp, sizeof(temp), "ref[%4u]-len[%3u]-crc[%8X] : %s\n", value->dwReference, value->dwLength, value->dwCRC, value->value); + f->w_string(temp); + value = value->next; + } + } + } + + int stat_economy() + { + int counter = 0; + for (u32 i = 0; i < buffer_size; ++i) + { + str_value* value = buffer[i]; + while (value) + { + counter -= sizeof(str_value); + counter += (value->dwReference - 1)*(value->dwLength + 1); + value = value->next; + } + } + + return counter; + } }; -str_container::str_container () +str_container::str_container() { - impl = xr_new(); + impl = xr_new(); } -str_value* str_container::dock (str_c value) +str_value* str_container::dock(str_c value) { - if (0==value) return 0; + if (0 == value) return 0; - cs.Enter (); + cs.Enter(); #ifdef DEBUG_MEMORY_MANAGER - Memory.stat_strdock ++ ; + Memory.stat_strdock++; #endif // DEBUG_MEMORY_MANAGER - str_value* result = 0 ; + str_value* result = 0; - // calc len - u32 s_len = xr_strlen(value); - u32 s_len_with_zero = (u32)s_len+1; - VERIFY (HEADER+s_len_with_zero < 4096); + // calc len + u32 s_len = xr_strlen(value); + u32 s_len_with_zero = (u32)s_len + 1; + VERIFY(HEADER + s_len_with_zero < 4096); - // setup find structure - char header[sizeof(str_value)]; - str_value* sv = (str_value*)header; - sv->dwReference = 0; - sv->dwLength = s_len; - sv->dwCRC = crc32 (value,s_len); + // setup find structure + char header[sizeof(str_value)]; + str_value* sv = (str_value*)header; + sv->dwReference = 0; + sv->dwLength = s_len; + sv->dwCRC = crc32(value, s_len); + + // search + result = impl->find(sv, value); - // search - result = impl->find (sv, value); - #ifdef DEBUG - bool is_leaked_string = !xr_strcmp(value, "enter leaked string here"); + bool is_leaked_string = !xr_strcmp(value, "enter leaked string here"); #endif //DEBUG - // it may be the case, string is not found or has "non-exact" match - if (0==result + // it may be the case, string is not found or has "non-exact" match + if (0 == result #ifdef DEBUG - || is_leaked_string + || is_leaked_string #endif //DEBUG - ) { + ) + { - result = (str_value*)Memory.mem_alloc(HEADER+s_len_with_zero + result = (str_value*)Memory.mem_alloc(HEADER + s_len_with_zero #ifdef DEBUG_MEMORY_NAME - , "storage: sstring" + , "storage: sstring" #endif // DEBUG_MEMORY_NAME - ); + ); #ifdef DEBUG - static int num_leaked_string = 0; - if ( is_leaked_string ) - { - ++num_leaked_string; - Msg("leaked_string: %d 0x%08x", num_leaked_string, result); - } + static int num_leaked_string = 0; + if (is_leaked_string) + { + ++num_leaked_string; + Msg("leaked_string: %d 0x%08x", num_leaked_string, result); + } #endif // DEBUG - result->dwReference = 0; - result->dwLength = sv->dwLength; - result->dwCRC = sv->dwCRC; - CopyMemory (result->value,value,s_len_with_zero); + result->dwReference = 0; + result->dwLength = sv->dwLength; + result->dwCRC = sv->dwCRC; + CopyMemory(result->value, value, s_len_with_zero); - impl->insert (result); - } - cs.Leave (); + impl->insert(result); + } + cs.Leave(); - return result; + return result; } -void str_container::clean () +void str_container::clean() { - cs.Enter (); - impl->clean (); - cs.Leave (); + cs.Enter(); + impl->clean(); + cs.Leave(); } -void str_container::verify () +void str_container::verify() { - cs.Enter (); - impl->verify(); - cs.Leave (); + cs.Enter(); + impl->verify(); + cs.Leave(); } -void str_container::dump () +void str_container::dump() { - cs.Enter (); - FILE* F = fopen("d:\\$str_dump$.txt","w"); - impl->dump (F); - fclose (F); - cs.Leave (); + cs.Enter(); + FILE* F = fopen("d:\\$str_dump$.txt", "w"); + impl->dump(F); + fclose(F); + cs.Leave(); } -void str_container::dump (IWriter* W) +void str_container::dump(IWriter* W) { - cs.Enter (); - impl->dump (W); - cs.Leave (); + cs.Enter(); + impl->dump(W); + cs.Leave(); } -u32 str_container::stat_economy () +u32 str_container::stat_economy() { - cs.Enter (); - int counter = 0; - counter -= sizeof(*this); - counter += impl->stat_economy(); - cs.Leave (); - return u32(counter); + cs.Enter(); + int counter = 0; + counter -= sizeof(*this); + counter += impl->stat_economy(); + cs.Leave(); + return u32(counter); } -str_container::~str_container () +str_container::~str_container() { - clean (); - //dump (); - xr_delete(impl); + clean(); + //dump (); + xr_delete(impl); } #else struct str_container_impl { - typedef xr_multiset cdb; - int num_docs; - str_container_impl () {num_docs=0;} + typedef xr_multiset cdb; + int num_docs; + str_container_impl() { num_docs = 0; } - cdb container; + cdb container; }; -str_container::str_container () +str_container::str_container() { - impl = xr_new(); + impl = xr_new(); } -str_value* str_container::dock (str_c value) +str_value* str_container::dock(str_c value) { - if (0==value) return 0; + if (0 == value) return 0; - cs.Enter (); + cs.Enter(); -// ++impl->num_docs; -// if ( impl->num_docs == 10000000 ) -// { -// Msg("shared_strings"); -// g_find_chunk_counter.flush(); -// } -// -// //#ifdef FIND_CHUNK_BENCHMARK_ENABLE -// find_chunk_auto_timer timer; -// //#endif // FIND_CHUNK_BENCHMARK_ENABLE + // ++impl->num_docs; + // if ( impl->num_docs == 10000000 ) + // { + // Msg("shared_strings"); + // g_find_chunk_counter.flush(); + // } + // + // //#ifdef FIND_CHUNK_BENCHMARK_ENABLE + // find_chunk_auto_timer timer; + // //#endif // FIND_CHUNK_BENCHMARK_ENABLE #ifdef DEBUG_MEMORY_MANAGER - Memory.stat_strdock ++ ; + Memory.stat_strdock++; #endif // DEBUG_MEMORY_MANAGER - str_value* result = 0 ; - - // calc len - u32 s_len = xr_strlen(value); - u32 s_len_with_zero = (u32)s_len+1; - VERIFY (HEADER+s_len_with_zero < 4096); - - // setup find structure - char header[sizeof(str_value)]; - str_value* sv = (str_value*)header; - sv->dwReference = 0; - sv->dwLength = s_len; - sv->dwCRC = crc32 (value,s_len); - sv->next = NULL; - - // search - str_container_impl::cdb::iterator I = impl->container.find (sv); // only integer compares :) - if (I!=impl->container.end()) { - // something found - verify, it is exactly our string - str_container_impl::cdb::iterator save = I; - for (; I!=impl->container.end() && (*I)->dwCRC == sv->dwCRC; ++I) { - str_value* V = (*I); - if (V->dwLength!=sv->dwLength) continue; - if (0!=memcmp(V->value,value,s_len)) continue; - result = V; // found - break; - } - } - - bool is_leaked_string = !xr_strcmp(value, "enter leaked string here"); - - // it may be the case, string is not found or has "non-exact" match - if (0==result || is_leaked_string) { - // Insert string -// DUMP_PHASE; - - result = (str_value*)Memory.mem_alloc(HEADER+s_len_with_zero + str_value* result = 0; + + // calc len + u32 s_len = xr_strlen(value); + u32 s_len_with_zero = (u32)s_len + 1; + VERIFY(HEADER + s_len_with_zero < 4096); + + // setup find structure + char header[sizeof(str_value)]; + str_value* sv = (str_value*)header; + sv->dwReference = 0; + sv->dwLength = s_len; + sv->dwCRC = crc32(value, s_len); + sv->next = NULL; + + // search + str_container_impl::cdb::iterator I = impl->container.find(sv); // only integer compares :) + if (I != impl->container.end()) + { + // something found - verify, it is exactly our string + str_container_impl::cdb::iterator save = I; + for (; I != impl->container.end() && (*I)->dwCRC == sv->dwCRC; ++I) + { + str_value* V = (*I); + if (V->dwLength != sv->dwLength) continue; + if (0 != memcmp(V->value, value, s_len)) continue; + result = V; // found + break; + } + } + + bool is_leaked_string = !xr_strcmp(value, "enter leaked string here"); + + // it may be the case, string is not found or has "non-exact" match + if (0 == result || is_leaked_string) + { + // Insert string + // DUMP_PHASE; + + result = (str_value*)Memory.mem_alloc(HEADER + s_len_with_zero #ifdef DEBUG_MEMORY_NAME - , "storage: sstring" + , "storage: sstring" #endif // DEBUG_MEMORY_NAME - ); + ); + + static int num11 = 0; - static int num11 = 0; - - if ( is_leaked_string ) - { - ++num11; - Msg("leaked_string: %d 0x%08x", num11, result); - } + if (is_leaked_string) + { + ++num11; + Msg("leaked_string: %d 0x%08x", num11, result); + } -// DUMP_PHASE; + // DUMP_PHASE; - result->dwReference = 0; - result->dwLength = sv->dwLength; - result->dwCRC = sv->dwCRC; - result->next = NULL; + result->dwReference = 0; + result->dwLength = sv->dwLength; + result->dwCRC = sv->dwCRC; + result->next = NULL; - CopyMemory (result->value,value,s_len_with_zero); + CopyMemory(result->value, value, s_len_with_zero); - impl->container.insert (result); - } + impl->container.insert(result); + } - cs.Leave (); + cs.Leave(); - return result; + return result; } -void str_container::clean () +void str_container::clean() { - cs.Enter (); - str_container_impl::cdb::iterator it = impl->container.begin (); - str_container_impl::cdb::iterator end = impl->container.end (); - for (; it!=end; ) { - str_value* sv = *it; - if (0==sv->dwReference) - { - str_container_impl::cdb::iterator i_current = it; - str_container_impl::cdb::iterator i_next = ++it; - xr_free (sv); - impl->container.erase (i_current); - it = i_next; - } else { - it++; - } - } - if (impl->container.empty()) impl->container.clear (); - cs.Leave (); + cs.Enter(); + str_container_impl::cdb::iterator it = impl->container.begin(); + str_container_impl::cdb::iterator end = impl->container.end(); + for (; it != end;) + { + str_value* sv = *it; + if (0 == sv->dwReference) + { + str_container_impl::cdb::iterator i_current = it; + str_container_impl::cdb::iterator i_next = ++it; + xr_free(sv); + impl->container.erase(i_current); + it = i_next; + } + else + { + it++; + } + } + if (impl->container.empty()) impl->container.clear(); + cs.Leave(); } -void str_container::verify () +void str_container::verify() { - cs.Enter (); - str_container_impl::cdb::iterator it = impl->container.begin (); - str_container_impl::cdb::iterator end = impl->container.end (); - for (; it!=end; ++it) { - str_value* sv = *it; - u32 crc = crc32 (sv->value,sv->dwLength); - string32 crc_str; - R_ASSERT3 (crc==sv->dwCRC, "CorePanic: read-only memory corruption (shared_strings)", itoa(sv->dwCRC,crc_str,16)); - R_ASSERT3 (sv->dwLength == xr_strlen(sv->value), "CorePanic: read-only memory corruption (shared_strings, internal structures)", sv->value); - } - cs.Leave (); + cs.Enter(); + str_container_impl::cdb::iterator it = impl->container.begin(); + str_container_impl::cdb::iterator end = impl->container.end(); + for (; it != end; ++it) + { + str_value* sv = *it; + u32 crc = crc32(sv->value, sv->dwLength); + string32 crc_str; + R_ASSERT3(crc == sv->dwCRC, "CorePanic: read-only memory corruption (shared_strings)", itoa(sv->dwCRC, crc_str, 16)); + R_ASSERT3(sv->dwLength == xr_strlen(sv->value), "CorePanic: read-only memory corruption (shared_strings, internal structures)", sv->value); + } + cs.Leave(); } -void str_container::dump () +void str_container::dump() { - cs.Enter (); - str_container_impl::cdb::iterator it = impl->container.begin (); - str_container_impl::cdb::iterator end = impl->container.end (); - FILE* F = fopen("d:\\$str_dump$.txt","w"); - for (; it!=end; it++) - fprintf (F,"ref[%4d]-len[%3d]-crc[%8X] : %s\n",(*it)->dwReference,(*it)->dwLength,(*it)->dwCRC,(*it)->value); - fclose (F); - cs.Leave (); + cs.Enter(); + str_container_impl::cdb::iterator it = impl->container.begin(); + str_container_impl::cdb::iterator end = impl->container.end(); + FILE* F = fopen("d:\\$str_dump$.txt", "w"); + for (; it != end; it++) + fprintf(F, "ref[%4d]-len[%3d]-crc[%8X] : %s\n", (*it)->dwReference, (*it)->dwLength, (*it)->dwCRC, (*it)->value); + fclose(F); + cs.Leave(); } -u32 str_container::stat_economy () +u32 str_container::stat_economy() { - cs.Enter (); - str_container_impl::cdb::iterator it = impl->container.begin (); - str_container_impl::cdb::iterator end = impl->container.end (); - int counter = 0; - counter -= sizeof(*this); - counter -= sizeof(str_container_impl::cdb::allocator_type); - const int node_size = 20; - for (; it!=end; it++) { - counter -= HEADER; - counter -= node_size; - counter += int((int((*it)->dwReference) - 1)*int((*it)->dwLength + 1)); - } - cs.Leave (); - - return u32(counter); + cs.Enter(); + str_container_impl::cdb::iterator it = impl->container.begin(); + str_container_impl::cdb::iterator end = impl->container.end(); + int counter = 0; + counter -= sizeof(*this); + counter -= sizeof(str_container_impl::cdb::allocator_type); + const int node_size = 20; + for (; it != end; it++) + { + counter -= HEADER; + counter -= node_size; + counter += int((int((*it)->dwReference) - 1)*int((*it)->dwLength + 1)); + } + cs.Leave(); + + return u32(counter); } -str_container::~str_container () +str_container::~str_container() { - clean (); - //dump (); - xr_delete(impl); - //R_ASSERT(impl->container.empty()); + clean(); + //dump (); + xr_delete(impl); + //R_ASSERT(impl->container.empty()); } #endif \ No newline at end of file diff --git a/src/xrCore/xrstring.h b/src/xrCore/xrstring.h index ca867f544ee..c68f42254d8 100644 --- a/src/xrCore/xrstring.h +++ b/src/xrCore/xrstring.h @@ -4,25 +4,28 @@ #pragma pack(push,4) ////////////////////////////////////////////////////////////////////////// -typedef const char* str_c; +typedef const char* str_c; ////////////////////////////////////////////////////////////////////////// #pragma warning(disable : 4200) -struct XRCORE_API str_value +struct XRCORE_API str_value { - u32 dwReference ; - u32 dwLength ; - u32 dwCRC ; - str_value* next ; - char value [] ; + u32 dwReference; + u32 dwLength; + u32 dwCRC; + str_value* next; + char value[]; }; -struct XRCORE_API str_value_cmp { // less - IC bool operator () (const str_value* A, const str_value* B) const { return A->dwCRCdwCRC; }; +struct XRCORE_API str_value_cmp +{ + // less + IC bool operator () (const str_value* A, const str_value* B) const { return A->dwCRC < B->dwCRC; }; }; -struct XRCORE_API str_hash_function { - IC u32 operator () (str_value const* const value) const { return value->dwCRC; }; +struct XRCORE_API str_hash_function +{ + IC u32 operator () (str_value const* const value) const { return value->dwCRC; }; }; #pragma warning(default : 4200) @@ -30,71 +33,73 @@ struct XRCORE_API str_hash_function { struct str_container_impl; class IWriter; ////////////////////////////////////////////////////////////////////////// -class XRCORE_API str_container +class XRCORE_API str_container { private: - xrCriticalSection cs; - str_container_impl* impl; + xrCriticalSection cs; + str_container_impl* impl; public: - str_container (); - ~str_container (); - - str_value* dock (str_c value); - void clean (); - void dump (); - void dump (IWriter* W); - void verify (); - u32 stat_economy (); + str_container(); + ~str_container(); + + str_value* dock(str_c value); + void clean(); + void dump(); + void dump(IWriter* W); + void verify(); + u32 stat_economy(); #ifdef PROFILE_CRITICAL_SECTIONS - str_container ():cs(MUTEX_PROFILE_ID(str_container)){} + str_container ():cs(MUTEX_PROFILE_ID(str_container)) {} #endif // PROFILE_CRITICAL_SECTIONS }; -XRCORE_API extern str_container* g_pStringContainer; +XRCORE_API extern str_container* g_pStringContainer; ////////////////////////////////////////////////////////////////////////// -class shared_str +class shared_str { private: - str_value* p_; + str_value* p_; protected: - // ref-counting - void _dec () { if (0==p_) return; p_->dwReference--; if (0==p_->dwReference) p_=0; } + // ref-counting + void _dec() { if (0 == p_) return; p_->dwReference--; if (0 == p_->dwReference) p_ = 0; } public: - void _set (str_c rhs) { str_value* v = g_pStringContainer->dock(rhs); if (0!=v) v->dwReference++; _dec(); p_ = v; } - void _set (shared_str const &rhs) { str_value* v = rhs.p_; if (0!=v) v->dwReference++; _dec(); p_ = v; } -// void _set (shared_str const &rhs) { str_value* v = g_pStringContainer->dock(rhs.c_str()); if (0!=v) v->dwReference++; _dec(); p_ = v; } - + void _set(str_c rhs) { str_value* v = g_pStringContainer->dock(rhs); if (0 != v) v->dwReference++; _dec(); p_ = v; } + void _set(shared_str const& rhs) { str_value* v = rhs.p_; if (0 != v) v->dwReference++; _dec(); p_ = v; } + // void _set (shared_str const &rhs) { str_value* v = g_pStringContainer->dock(rhs.c_str()); if (0!=v) v->dwReference++; _dec(); p_ = v; } - const str_value* _get () const { return p_; } + + const str_value* _get() const { return p_; } public: - // construction - shared_str () { p_ = 0; } - shared_str (str_c rhs) { p_ = 0; _set(rhs); } - shared_str (shared_str const &rhs) { p_ = 0; _set(rhs); } - ~shared_str () { _dec(); } - - // assignment & accessors - shared_str& operator= (str_c rhs) { _set(rhs); return (shared_str&)*this; } - shared_str& operator= (shared_str const &rhs) { _set(rhs); return (shared_str&)*this; } - str_c operator* () const { return p_?p_->value:0; } - bool operator! () const { return p_ == 0; } - char operator[] (size_t id) { return p_->value[id]; } - str_c c_str () const { return p_?p_->value:0; } - - // misc func - u32 size () const { if (0==p_) return 0; else return p_->dwLength; } - void swap (shared_str & rhs) { str_value* tmp = p_; p_ = rhs.p_; rhs.p_ = tmp; } - bool equal (const shared_str & rhs) const { return (p_ == rhs.p_); } - shared_str& __cdecl printf (const char* format, ...) { - string4096 buf; - va_list p; - va_start (p,format); - int vs_sz = _vsnprintf(buf,sizeof(buf)-1,format,p); buf[sizeof(buf)-1]=0; - va_end (p); - if (vs_sz) _set(buf); - return (shared_str&)*this; - } + // construction + shared_str() { p_ = 0; } + shared_str(str_c rhs) { p_ = 0; _set(rhs); } + shared_str(shared_str const& rhs) { p_ = 0; _set(rhs); } + ~shared_str() { _dec(); } + + // assignment & accessors + shared_str& operator= (str_c rhs) { _set(rhs); return (shared_str&)*this; } + shared_str& operator= (shared_str const& rhs) { _set(rhs); return (shared_str&)*this; } + str_c operator* () const { return p_ ? p_->value : 0; } + bool operator! () const { return p_ == 0; } + char operator[] (size_t id) { return p_->value[id]; } + str_c c_str() const { return p_ ? p_->value : 0; } + + // misc func + u32 size() const { if (0 == p_) return 0; else return p_->dwLength; } + void swap(shared_str& rhs) { str_value* tmp = p_; p_ = rhs.p_; rhs.p_ = tmp; } + bool equal(const shared_str& rhs) const { return (p_ == rhs.p_); } + shared_str& __cdecl printf(const char* format, ...) + { + string4096 buf; + va_list p; + va_start(p, format); + int vs_sz = _vsnprintf(buf, sizeof(buf) - 1, format, p); + buf[sizeof(buf) - 1] = 0; + va_end(p); + if (vs_sz) _set(buf); + return (shared_str&)*this; + } }; // res_ptr == res_ptr @@ -105,22 +110,23 @@ class shared_str // ptr != const res_ptr // res_ptr < res_ptr // res_ptr > res_ptr -IC bool operator == (shared_str const & a, shared_str const & b) { return a._get() == b._get(); } -IC bool operator != (shared_str const & a, shared_str const & b) { return a._get() != b._get(); } -IC bool operator < (shared_str const & a, shared_str const & b) { return a._get() < b._get(); } -IC bool operator > (shared_str const & a, shared_str const & b) { return a._get() > b._get(); } +IC bool operator == (shared_str const& a, shared_str const& b) { return a._get() == b._get(); } +IC bool operator != (shared_str const& a, shared_str const& b) { return a._get() != b._get(); } +IC bool operator < (shared_str const& a, shared_str const& b) { return a._get() < b._get(); } +IC bool operator > (shared_str const& a, shared_str const& b) { return a._get() > b._get(); } // externally visible standart functionality -IC void swap (shared_str & lhs, shared_str & rhs) { lhs.swap(rhs); } -IC u32 xr_strlen (shared_str & a) { return a.size(); } -IC int xr_strcmp (const shared_str & a, const char* b) { return xr_strcmp(*a,b); } -IC int xr_strcmp (const char* a, const shared_str & b) { return xr_strcmp(a,*b); } -IC int xr_strcmp (const shared_str & a, const shared_str & b) { - if (a.equal(b)) return 0; - else return xr_strcmp(*a,*b); +IC void swap(shared_str& lhs, shared_str& rhs) { lhs.swap(rhs); } +IC u32 xr_strlen(shared_str& a) { return a.size(); } +IC int xr_strcmp(const shared_str& a, const char* b) { return xr_strcmp(*a, b); } +IC int xr_strcmp(const char* a, const shared_str& b) { return xr_strcmp(a, *b); } +IC int xr_strcmp(const shared_str& a, const shared_str& b) +{ + if (a.equal(b)) return 0; + else return xr_strcmp(*a, *b); } -IC void xr_strlwr (xr_string& src) { for(xr_string::iterator it=src.begin(); it!=src.end(); it++) *it=xr_string::value_type(tolower(*it));} -IC void xr_strlwr (shared_str& src) { if (*src){LPSTR lp=xr_strdup(*src); xr_strlwr(lp); src=lp; xr_free(lp);} } +IC void xr_strlwr(xr_string& src) { for (xr_string::iterator it = src.begin(); it != src.end(); it++) *it = xr_string::value_type(tolower(*it)); } +IC void xr_strlwr(shared_str& src) { if (*src) { LPSTR lp = xr_strdup(*src); xr_strlwr(lp); src = lp; xr_free(lp); } } #pragma pack(pop)