Index: ps/trunk/source/lib/app_hooks.cpp =================================================================== --- ps/trunk/source/lib/app_hooks.cpp (revision 26023) +++ ps/trunk/source/lib/app_hooks.cpp (revision 26024) @@ -1,180 +1,118 @@ -/* Copyright (C) 2015 Wildfire Games. +/* Copyright (C) 2021 Wildfire Games. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/* - * hooks to allow customization / app-specific behavior. - */ - #include "precompiled.h" + #include "lib/app_hooks.h" #include "lib/sysdep/sysdep.h" #include //----------------------------------------------------------------------------- // default implementations //----------------------------------------------------------------------------- -static void def_override_gl_upload_caps() -{ -} - - static const OsPath& def_get_log_dir() { static OsPath logDir; if(logDir.empty()) logDir = sys_ExecutablePathname().Parent(); return logDir; } static void def_bundle_logs(FILE* UNUSED(f)) { } -static const wchar_t* def_translate(const wchar_t* text) -{ - return text; -} - - -static void def_translate_free(const wchar_t* UNUSED(text)) -{ - // no-op - translate() doesn't own the pointer. -} - - -static void def_log(const wchar_t* text) -{ -#if ICC_VERSION -#pragma warning(push) -#pragma warning(disable:181) // "invalid printf conversion" - but wchar_t* and %ls are legit -#endif - printf("%ls", text); // must not use wprintf, since stdout on Unix is byte-oriented -#if ICC_VERSION -#pragma warning(pop) -#endif -} - - static ErrorReactionInternal def_display_error(const wchar_t* UNUSED(text), size_t UNUSED(flags)) { return ERI_NOT_IMPLEMENTED; } //----------------------------------------------------------------------------- // contains the current set of hooks. starts with the default values and // may be changed via app_hooks_update. // // rationale: we don't ever need to switch "hook sets", so one global struct // is fine. by always having one defined, we also avoid the trampolines // having to check whether their function pointer is valid. static AppHooks ah = { - def_override_gl_upload_caps, def_get_log_dir, def_bundle_logs, - def_translate, - def_translate_free, - def_log, def_display_error }; // separate copy of ah; used to determine if a particular hook has been // redefined. the additional storage needed is negligible and this is // easier than comparing each value against its corresponding def_ value. static AppHooks default_ah = ah; // register the specified hook function pointers. any of them that // are non-zero override the previous function pointer value // (these default to the stub hooks which are functional but basic). void app_hooks_update(AppHooks* new_ah) { ENSURE(new_ah); #define OVERRIDE_IF_NONZERO(HOOKNAME) if(new_ah->HOOKNAME) ah.HOOKNAME = new_ah->HOOKNAME; - OVERRIDE_IF_NONZERO(override_gl_upload_caps) OVERRIDE_IF_NONZERO(get_log_dir) OVERRIDE_IF_NONZERO(bundle_logs) - OVERRIDE_IF_NONZERO(translate) - OVERRIDE_IF_NONZERO(translate_free) - OVERRIDE_IF_NONZERO(log) OVERRIDE_IF_NONZERO(display_error) #undef OVERRIDE_IF_NONZERO } bool app_hook_was_redefined(size_t offset_in_struct) { const u8* ah_bytes = (const u8*)&ah; const u8* default_ah_bytes = (const u8*)&default_ah; typedef void(*FP)(); // a bit safer than comparing void* pointers if(*(FP)(ah_bytes+offset_in_struct) != *(FP)(default_ah_bytes+offset_in_struct)) return true; return false; } //----------------------------------------------------------------------------- // trampoline implementations // (boilerplate code; hides details of how to call the app hook) //----------------------------------------------------------------------------- -void ah_override_gl_upload_caps() -{ - if(ah.override_gl_upload_caps) - ah.override_gl_upload_caps(); -} - const OsPath& ah_get_log_dir() { return ah.get_log_dir(); } void ah_bundle_logs(FILE* f) { ah.bundle_logs(f); } -const wchar_t* ah_translate(const wchar_t* text) -{ - return ah.translate(text); -} - -void ah_translate_free(const wchar_t* text) -{ - ah.translate_free(text); -} - -void ah_log(const wchar_t* text) -{ - ah.log(text); -} - ErrorReactionInternal ah_display_error(const wchar_t* text, size_t flags) { return ah.display_error(text, flags); } Index: ps/trunk/source/lib/app_hooks.h =================================================================== --- ps/trunk/source/lib/app_hooks.h (revision 26023) +++ ps/trunk/source/lib/app_hooks.h (revision 26024) @@ -1,209 +1,164 @@ -/* Copyright (C) 2010 Wildfire Games. +/* Copyright (C) 2021 Wildfire Games. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* * hooks to allow customization / app-specific behavior. */ /* Background ---------- This codebase is shared between several projects, each with differing needs. Some of them have e.g. complicated i18n/translation facilities and require all text output to go through it; others strive to minimize size and therefore do not want to include that. Since commenting things out isn't an option with shared source and conditional compilation is ugly, we bridge the differences via "hooks". These are functions whose behavior is expected to differ between projects; they are defined by the app, registered here and called from lib code via our trampolines. Introduction ------------ This module provides a clean interface for other code to call hooks and allows the app to register them. It also defines default stub implementations. Usage ----- In the simplest case, the stubs are already acceptable. Otherwise, you need to implement a new version of some hooks, fill an AppHooks struct with pointers to those functions (zero the rest), and call app_hooks_update. Adding New Functions -------------------- Several steps are needed (see below for rationale): 0) HOOKNAME is the name of the desired procedure (e.g. "bundle_logs") 1) add a 'trampoline' (user visible function) declaration to this header (typically named ah_HOOKNAME) 2) add the corresponding implementation, i.e. call to ah.HOOKNAME 3) add a default implementation of the new functionality (typically named def_HOOKNAME) 4) add HOOKNAME member to struct AppHooks declaration 5) set HOOKNAME member to def_HOOKNAME in initialization of 'struct AppHooks ah' 6) add HOOKNAME to list in app_hooks_update code Rationale --------- While X-Macros would reduce the amount of work needed when adding new functions, they confuse static code analysis and VisualAssist X (the function definitions are not visible to them). We prefer convenience during usage instead of in the rare cases where new app hook functions are defined. note: an X-Macro would define the app hook as such: extern const wchar_t*, translate, (const wchar_t* text), (text), return) .. and in its various invocations perform the above steps automatically. */ #ifndef INCLUDED_APP_HOOKS #define INCLUDED_APP_HOOKS #include "lib/os_path.h" // trampolines for user code to call the hooks. they encapsulate // the details of how exactly to do this. /** - * override default decision on using OpenGL extensions relating to - * texture upload. - * - * this should call ogl_tex_override to disable/force their use if the - * current card/driver combo respectively crashes or - * supports it even though the extension isn't advertised. - * - * the default implementation works but is hardwired in code and therefore - * not expandable. - **/ -extern void ah_override_gl_upload_caps(); - -/** * return path to directory into which crash dumps should be written. * * must be callable at any time - in particular, before VFS init. * paths are typically relative to sys_ExecutablePathname. * * @return path ending with directory separator (e.g. '/'). **/ extern const OsPath& ah_get_log_dir(); /** * gather all app-related logs/information and write it to file. * * used when writing a crash log so that all relevant info is in one file. * * the default implementation attempts to gather 0ad data, but is * fail-safe (doesn't complain if file not found). * * @param f file into which to write. **/ extern void ah_bundle_logs(FILE* f); /** - * translate text to the current locale. - * - * @param text to translate. - * @return pointer to localized text; must be freed via translate_free. - * - * the default implementation just returns the pointer unchanged. - **/ -extern const wchar_t* ah_translate(const wchar_t* text); - -/** - * free text that was returned by translate. - * - * @param text to free. - * - * the default implementation does nothing. - **/ -extern void ah_translate_free(const wchar_t* text); - -/** - * write text to the app's log. - * - * @param text to write. - * - * the default implementation uses stdout. - **/ -extern void ah_log(const wchar_t* text); - -/** * display an error dialog, thus overriding sys_display_error. * * @param text error message. * @param flags see DebugDisplayErrorFlags. * @return ErrorReactionInternal. * * the default implementation just returns ERI_NOT_IMPLEMENTED, which * causes the normal sys_display_error to be used. **/ extern ErrorReactionInternal ah_display_error(const wchar_t* text, size_t flags); /** * holds a function pointer (allowed to be NULL) for each hook. * passed to app_hooks_update. **/ struct AppHooks { - void (*override_gl_upload_caps)(); const OsPath& (*get_log_dir)(); void (*bundle_logs)(FILE* f); - const wchar_t* (*translate)(const wchar_t* text); - void (*translate_free)(const wchar_t* text); - void (*log)(const wchar_t* text); ErrorReactionInternal (*display_error)(const wchar_t* text, size_t flags); }; /** * update the app hook function pointers. * * @param ah AppHooks struct. any of its function pointers that are non-zero * override the previous function pointer value * (these default to the stub hooks which are functional but basic). **/ LIB_API void app_hooks_update(AppHooks* ah); /** * was the app hook changed via app_hooks_update from its default value? * * @param offset_in_struct byte offset within AppHooks (determined via * offsetof) of the app hook function pointer. **/ extern bool app_hook_was_redefined(size_t offset_in_struct); // name is identifier of the function pointer within AppHooks to test. #define AH_IS_DEFINED(name) app_hook_was_redefined(offsetof(AppHooks, name)) -#endif // #ifndef INCLUDED_APP_HOOKS +#endif // INCLUDED_APP_HOOKS Index: ps/trunk/source/lib/debug.cpp =================================================================== --- ps/trunk/source/lib/debug.cpp (revision 26023) +++ ps/trunk/source/lib/debug.cpp (revision 26024) @@ -1,550 +1,548 @@ /* Copyright (C) 2021 Wildfire Games. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "precompiled.h" #include "lib/debug.h" #include "lib/alignment.h" #include "lib/app_hooks.h" #include "lib/fnv_hash.h" #include "lib/sysdep/cpu.h" // cpu_CAS #include "lib/sysdep/sysdep.h" #include "lib/sysdep/vm.h" #if OS_WIN # include "lib/sysdep/os/win/wdbg_heap.h" #endif #include #include #include namespace { // (NB: this may appear obscene, but deep stack traces have been // observed to take up > 256 KiB) constexpr std::size_t MESSAGE_SIZE = 512 * KiB / sizeof(wchar_t); wchar_t g_MessageBuffer[MESSAGE_SIZE]; } // anonymous namespace static const StatusDefinition debugStatusDefinitions[] = { { ERR::SYM_NO_STACK_FRAMES_FOUND, L"No stack frames found" }, { ERR::SYM_UNRETRIEVABLE_STATIC, L"Value unretrievable (stored in external module)" }, { ERR::SYM_UNRETRIEVABLE, L"Value unretrievable" }, { ERR::SYM_TYPE_INFO_UNAVAILABLE, L"Error getting type_info" }, { ERR::SYM_INTERNAL_ERROR, L"Exception raised while processing a symbol" }, { ERR::SYM_UNSUPPORTED, L"Symbol type not (fully) supported" }, { ERR::SYM_CHILD_NOT_FOUND, L"Symbol does not have the given child" }, { ERR::SYM_NESTING_LIMIT, L"Symbol nesting too deep or infinite recursion" }, { ERR::SYM_SINGLE_SYMBOL_LIMIT, L"Symbol has produced too much output" }, { INFO::SYM_SUPPRESS_OUTPUT, L"Symbol was suppressed" } }; STATUS_ADD_DEFINITIONS(debugStatusDefinitions); // need to shoehorn printf-style variable params into // the OutputDebugString call. // - don't want to split into multiple calls - would add newlines to output. // - fixing Win32 _vsnprintf to return # characters that would be written, // as required by C99, looks difficult and unnecessary. if any other code // needs that, implement GNU vasprintf. // - fixed size buffers aren't nice, but much simpler than vasprintf-style // allocate+expand_until_it_fits. these calls are for quick debug output, // not loads of data, anyway. // rationale: static data instead of std::set to allow setting at any time. // we store FNV hash of tag strings for fast comparison; collisions are // extremely unlikely and can only result in displaying more/less text. static const size_t MAX_TAGS = 20; static u32 tags[MAX_TAGS]; static size_t num_tags; void debug_filter_add(const char* tag) { const u32 hash = fnv_hash(tag, strlen(tag)*sizeof(tag[0])); // make sure it isn't already in the list for(size_t i = 0; i < MAX_TAGS; i++) if(tags[i] == hash) return; // too many already? if(num_tags == MAX_TAGS) { DEBUG_WARN_ERR(ERR::LOGIC); // increase MAX_TAGS return; } tags[num_tags++] = hash; } void debug_filter_remove(const char* tag) { const u32 hash = fnv_hash(tag, strlen(tag)*sizeof(tag[0])); for(size_t i = 0; i < MAX_TAGS; i++) { if(tags[i] == hash) // found it { // replace with last element (avoid holes) tags[i] = tags[MAX_TAGS-1]; num_tags--; // can only happen once, so we're done. return; } } } void debug_filter_clear() { std::fill(tags, tags+MAX_TAGS, 0); } bool debug_filter_allows(const char* text) { size_t i; for(i = 0; ; i++) { // no | found => no tag => should always be displayed if(text[i] == ' ' || text[i] == '\0') return true; if(text[i] == '|' && i != 0) break; } const u32 hash = fnv_hash(text, i*sizeof(text[0])); // check if entry allowing this tag is found for(i = 0; i < MAX_TAGS; i++) if(tags[i] == hash) return true; return false; } #undef debug_printf // allowing #defining it out void debug_printf(const char* fmt, ...) { char buf[16384]; va_list ap; va_start(ap, fmt); const int numChars = vsprintf_s(buf, ARRAY_SIZE(buf), fmt, ap); if (numChars < 0) debug_break(); // poor man's assert - avoid infinite loop because ENSURE also uses debug_printf va_end(ap); debug_puts_filtered(buf); } void debug_puts_filtered(const char* text) { if(debug_filter_allows(text)) debug_puts(text); } //----------------------------------------------------------------------------- Status debug_WriteCrashlog(const wchar_t* text) { // (avoid infinite recursion and/or reentering this function if it // fails/reports an error) enum State { IDLE, BUSY, FAILED }; // note: the initial state is IDLE. we rely on zero-init because // initializing local static objects from constants may happen when // this is first called, which isn't thread-safe. (see C++ 6.7.4) cassert(IDLE == 0); static volatile intptr_t state; if(!cpu_CAS(&state, IDLE, BUSY)) return ERR::REENTERED; // NOWARN OsPath pathname = ah_get_log_dir()/"crashlog.txt"; FILE* f = sys_OpenFile(pathname, "w"); if(!f) { state = FAILED; // must come before DEBUG_DISPLAY_ERROR DEBUG_DISPLAY_ERROR(L"Unable to open crashlog.txt for writing (please ensure the log directory is writable)"); return ERR::FAIL; // NOWARN (the above text is more helpful than a generic error code) } fputwc(0xFEFF, f); // BOM fwprintf(f, L"%ls\n", text); fwprintf(f, L"\n\n====================================\n\n"); // allow user to bundle whatever information they want ah_bundle_logs(f); fclose(f); state = IDLE; return INFO::OK; } //----------------------------------------------------------------------------- // error message //----------------------------------------------------------------------------- // a stream with printf-style varargs and the possibility of // writing directly to the output buffer. class PrintfWriter { public: PrintfWriter(wchar_t* buf, size_t maxChars) : m_pos(buf), m_charsLeft(maxChars) { } bool operator()(const wchar_t* fmt, ...) WPRINTF_ARGS(2) { va_list ap; va_start(ap, fmt); const int len = vswprintf(m_pos, m_charsLeft, fmt, ap); va_end(ap); if(len < 0) return false; m_pos += len; m_charsLeft -= len; return true; } wchar_t* Position() const { return m_pos; } size_t CharsLeft() const { return m_charsLeft; } void CountAddedChars() { const size_t len = wcslen(m_pos); m_pos += len; m_charsLeft -= len; } private: wchar_t* m_pos; size_t m_charsLeft; }; // split out of debug_DisplayError because it's used by the self-test. const wchar_t* debug_BuildErrorMessage( const wchar_t* description, const wchar_t* filename, int line, const char* func, void* context, const wchar_t* lastFuncToSkip) { // retrieve errno (might be relevant) before doing anything else // that might overwrite it. wchar_t description_buf[100] = L"?"; wchar_t os_error[100] = L"?"; Status errno_equiv = StatusFromErrno(); // NOWARN if(errno_equiv != ERR::FAIL) // meaningful translation StatusDescription(errno_equiv, description_buf, ARRAY_SIZE(description_buf)); sys_StatusDescription(0, os_error, ARRAY_SIZE(os_error)); PrintfWriter writer(g_MessageBuffer, MESSAGE_SIZE); // header if(!writer( L"%ls\r\n" L"Location: %ls:%d (%hs)\r\n" L"\r\n" L"Call stack:\r\n" L"\r\n", description, filename, line, func )) { fail: return L"(error while formatting error message)"; } // append stack trace Status ret = debug_DumpStack(writer.Position(), writer.CharsLeft(), context, lastFuncToSkip); if(ret == ERR::REENTERED) { if(!writer( L"While generating an error report, we encountered a second " L"problem. Please be sure to report both this and the subsequent " L"error messages." )) goto fail; } else if(ret != INFO::OK) { wchar_t error_buf[100] = {'?'}; if(!writer( L"(error while dumping stack: %ls)", StatusDescription(ret, error_buf, ARRAY_SIZE(error_buf)) )) goto fail; } else // success { writer.CountAddedChars(); } // append errno if(!writer( L"\r\n" L"errno = %d (%ls)\r\n" L"OS error = %ls\r\n", errno, description_buf, os_error )) goto fail; return g_MessageBuffer; } //----------------------------------------------------------------------------- // display error messages //----------------------------------------------------------------------------- // translates and displays the given strings in a dialog. // this is typically only used when debug_DisplayError has failed or // is unavailable because that function is much more capable. // implemented via sys_display_msg; see documentation there. void debug_DisplayMessage(const wchar_t* caption, const wchar_t* msg) { - sys_display_msg(ah_translate(caption), ah_translate(msg)); + sys_display_msg(caption, msg); } // when an error has come up and user clicks Exit, we don't want any further // errors (e.g. caused by atexit handlers) to come up, possibly causing an // infinite loop. hiding errors isn't good, but we assume that whoever clicked // exit really doesn't want to see any more messages. static atomic_bool isExiting; // this logic is applicable to any type of error. special cases such as // suppressing certain expected WARN_ERRs are done there. static bool ShouldSuppressError(atomic_bool* suppress) { if(isExiting) return true; if(!suppress) return false; if(*suppress == DEBUG_SUPPRESS) return true; return false; } static ErrorReactionInternal CallDisplayError(const wchar_t* text, size_t flags) { // first try app hook implementation ErrorReactionInternal er = ah_display_error(text, flags); // .. it's only a stub: default to normal implementation if(er == ERI_NOT_IMPLEMENTED) er = sys_display_error(text, flags); return er; } static ErrorReaction PerformErrorReaction(ErrorReactionInternal er, size_t flags, atomic_bool* suppress) { const bool shouldHandleBreak = (flags & DE_MANUAL_BREAK) == 0; switch(er) { case ERI_CONTINUE: return ER_CONTINUE; case ERI_BREAK: // handle "break" request unless the caller wants to (doing so here // instead of within the dlgproc yields a correct call stack) if(shouldHandleBreak) { debug_break(); return ER_CONTINUE; } else return ER_BREAK; case ERI_SUPPRESS: (void)cpu_CAS(suppress, 0, DEBUG_SUPPRESS); return ER_CONTINUE; case ERI_EXIT: isExiting = 1; // see declaration COMPILER_FENCE; #if OS_WIN // prevent (slow) heap reporting since we're exiting abnormally and // thus probably leaking like a sieve. wdbg_heap_Enable(false); #endif exit(EXIT_FAILURE); case ERI_NOT_IMPLEMENTED: default: debug_break(); // not expected to be reached return ER_CONTINUE; } } ErrorReaction debug_DisplayError(const wchar_t* description, size_t flags, void* context, const wchar_t* lastFuncToSkip, const wchar_t* pathname, int line, const char* func, atomic_bool* suppress) { // "suppressing" this error means doing nothing and returning ER_CONTINUE. if(ShouldSuppressError(suppress)) return ER_CONTINUE; // fix up params - // .. translate - description = ah_translate(description); // .. caller supports a suppress flag; set the corresponding flag so that // the error display implementation enables the Suppress option. if(suppress) flags |= DE_ALLOW_SUPPRESS; if(flags & DE_NO_DEBUG_INFO) { // in non-debug-info mode, simply display the given description // and then return immediately ErrorReactionInternal er = CallDisplayError(description, flags); return PerformErrorReaction(er, flags, suppress); } // .. deal with incomplete file/line info if(!pathname || pathname[0] == '\0') pathname = L"unknown"; if(line <= 0) line = 0; if(!func || func[0] == '\0') func = "?"; // .. _FILE__ evaluates to the full path (albeit without drive letter) // which is rather long. we only display the base name for clarity. const wchar_t* filename = path_name_only(pathname); // display in output window; double-click will navigate to error location. const wchar_t* text = debug_BuildErrorMessage(description, filename, line, func, context, lastFuncToSkip); (void)debug_WriteCrashlog(text); ErrorReactionInternal er = CallDisplayError(text, flags); // TODO: use utf8 conversion without internal allocations. debug_printf("%s(%d): %s\n", utf8_from_wstring(filename).c_str(), line, utf8_from_wstring(description).c_str()); // note: debug_break-ing here to make sure the app doesn't continue // running is no longer necessary. debug_DisplayError now determines our // window handle and is modal. return PerformErrorReaction(er, flags, suppress); } // is errorToSkip valid? (also guarantees mutual exclusion) enum SkipStatus { INVALID, VALID, BUSY }; static intptr_t skipStatus = INVALID; static Status errorToSkip; static size_t numSkipped; void debug_SkipErrors(Status err) { if(cpu_CAS(&skipStatus, INVALID, BUSY)) { errorToSkip = err; numSkipped = 0; COMPILER_FENCE; skipStatus = VALID; // linearization point } else DEBUG_WARN_ERR(ERR::REENTERED); } size_t debug_StopSkippingErrors() { if(cpu_CAS(&skipStatus, VALID, BUSY)) { const size_t ret = numSkipped; COMPILER_FENCE; skipStatus = INVALID; // linearization point return ret; } else { DEBUG_WARN_ERR(ERR::REENTERED); return 0; } } static bool ShouldSkipError(Status err) { if(cpu_CAS(&skipStatus, VALID, BUSY)) { numSkipped++; const bool ret = (err == errorToSkip); COMPILER_FENCE; skipStatus = VALID; return ret; } return false; } ErrorReaction debug_OnError(Status err, atomic_bool* suppress, const wchar_t* file, int line, const char* func) { CACHE_ALIGNED(u8) context[DEBUG_CONTEXT_SIZE]; (void)debug_CaptureContext(context); if(ShouldSkipError(err)) return ER_CONTINUE; const wchar_t* lastFuncToSkip = L"debug_OnError"; wchar_t buf[400]; wchar_t err_buf[200]; StatusDescription(err, err_buf, ARRAY_SIZE(err_buf)); swprintf_s(buf, ARRAY_SIZE(buf), L"Function call failed: return value was %lld (%ls)", (long long)err, err_buf); return debug_DisplayError(buf, DE_MANUAL_BREAK, context, lastFuncToSkip, file,line,func, suppress); } ErrorReaction debug_OnAssertionFailure(const wchar_t* expr, atomic_bool* suppress, const wchar_t* file, int line, const char* func) { CACHE_ALIGNED(u8) context[DEBUG_CONTEXT_SIZE]; (void)debug_CaptureContext(context); const wchar_t* lastFuncToSkip = L"debug_OnAssertionFailure"; wchar_t buf[400]; swprintf_s(buf, ARRAY_SIZE(buf), L"Assertion failed: \"%ls\"", expr); return debug_DisplayError(buf, DE_MANUAL_BREAK, context, lastFuncToSkip, file,line,func, suppress); } Index: ps/trunk/source/lib/res/graphics/ogl_tex.cpp =================================================================== --- ps/trunk/source/lib/res/graphics/ogl_tex.cpp (revision 26023) +++ ps/trunk/source/lib/res/graphics/ogl_tex.cpp (revision 26024) @@ -1,1117 +1,1108 @@ /* Copyright (C) 2021 Wildfire Games. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "precompiled.h" #include "ogl_tex.h" #include "lib/app_hooks.h" #include "lib/bits.h" #include "lib/ogl.h" #include "lib/res/h_mgr.h" #include "lib/sysdep/gfx.h" #include "lib/tex/tex.h" #include //---------------------------------------------------------------------------- // OpenGL helper routines //---------------------------------------------------------------------------- static bool filter_valid(GLint filter) { switch(filter) { case GL_NEAREST: case GL_LINEAR: case GL_NEAREST_MIPMAP_NEAREST: case GL_LINEAR_MIPMAP_NEAREST: case GL_NEAREST_MIPMAP_LINEAR: case GL_LINEAR_MIPMAP_LINEAR: return true; default: return false; } } static bool wrap_valid(GLint wrap) { switch(wrap) { #if !CONFIG2_GLES case GL_CLAMP: case GL_CLAMP_TO_BORDER: #endif case GL_CLAMP_TO_EDGE: case GL_REPEAT: case GL_MIRRORED_REPEAT: return true; default: return false; } } static bool are_mipmaps_needed(size_t width, size_t height, GLint filter) { // can't upload the entire texture; we're going to skip some // levels until it no longer exceeds the OpenGL dimension limit. if((GLint)width > ogl_max_tex_size || (GLint)height > ogl_max_tex_size) return true; switch(filter) { case GL_NEAREST_MIPMAP_NEAREST: case GL_LINEAR_MIPMAP_NEAREST: case GL_NEAREST_MIPMAP_LINEAR: case GL_LINEAR_MIPMAP_LINEAR: return true; default: return false; } } static bool fmt_is_s3tc(GLenum fmt) { switch(fmt) { case GL_COMPRESSED_RGB_S3TC_DXT1_EXT: case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT: case GL_COMPRESSED_RGBA_S3TC_DXT3_EXT: case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT: return true; default: return false; } } // determine OpenGL texture format, given and Tex . static GLint choose_fmt(size_t bpp, size_t flags) { const bool alpha = (flags & TEX_ALPHA) != 0; const bool bgr = (flags & TEX_BGR ) != 0; const bool grey = (flags & TEX_GREY ) != 0; const size_t dxt = flags & TEX_DXT; // S3TC if(dxt != 0) { switch(dxt) { case DXT1A: return GL_COMPRESSED_RGBA_S3TC_DXT1_EXT; case 1: return GL_COMPRESSED_RGB_S3TC_DXT1_EXT; case 3: return GL_COMPRESSED_RGBA_S3TC_DXT3_EXT; case 5: return GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; default: DEBUG_WARN_ERR(ERR::LOGIC); // invalid DXT value return 0; } } // uncompressed switch(bpp) { case 8: ENSURE(grey); return GL_LUMINANCE; case 16: return GL_LUMINANCE_ALPHA; case 24: ENSURE(!alpha); #if CONFIG2_GLES // GLES never supports BGR ENSURE(!bgr); return GL_RGB; #else return bgr? GL_BGR : GL_RGB; #endif case 32: ENSURE(alpha); // GLES can support BGRA via GL_EXT_texture_format_BGRA8888 // (TODO: can we rely on support for that extension?) return bgr? GL_BGRA_EXT : GL_RGBA; default: DEBUG_WARN_ERR(ERR::LOGIC); // invalid bpp return 0; } UNREACHABLE; } //---------------------------------------------------------------------------- // quality mechanism //---------------------------------------------------------------------------- static GLint default_filter = GL_LINEAR; // one of the GL *minify* filters static int default_q_flags = OGL_TEX_FULL_QUALITY; // OglTexQualityFlags static bool q_flags_valid(int q_flags) { const size_t bits = OGL_TEX_FULL_QUALITY|OGL_TEX_HALF_BPP|OGL_TEX_HALF_RES; // unrecognized bits are set - invalid if((q_flags & ~bits) != 0) return false; // "full quality" but other reduction bits are set - invalid if(q_flags & OGL_TEX_FULL_QUALITY && q_flags & ~OGL_TEX_FULL_QUALITY) return false; return true; } // change default settings - these affect performance vs. quality. // may be overridden for individual textures via parameter to // ogl_tex_upload or ogl_tex_set_filter, respectively. // // pass 0 to keep the current setting; defaults and legal values are: // - q_flags: OGL_TEX_FULL_QUALITY; combination of OglTexQualityFlags // - filter: GL_LINEAR; any valid OpenGL minification filter void ogl_tex_set_defaults(int q_flags, GLint filter) { if(q_flags) { ENSURE(q_flags_valid(q_flags)); default_q_flags = q_flags; } if(filter) { ENSURE(filter_valid(filter)); default_filter = filter; } } // choose an internal format for based on the given q_flags. static GLint choose_int_fmt(GLenum fmt, int q_flags) { // true => 4 bits per component; otherwise, 8 const bool half_bpp = (q_flags & OGL_TEX_HALF_BPP) != 0; // early-out for S3TC textures: they don't need an internal format // (because upload is via glCompressedTexImage2DARB), but we must avoid // triggering the default case below. we might as well return a // meaningful value (i.e. int_fmt = fmt). if(fmt_is_s3tc(fmt)) return fmt; #if CONFIG2_GLES UNUSED2(half_bpp); // GLES only supports internal format == external format return fmt; #else switch(fmt) { // 8bpp case GL_LUMINANCE: return half_bpp? GL_LUMINANCE4 : GL_LUMINANCE8; case GL_INTENSITY: return half_bpp? GL_INTENSITY4 : GL_INTENSITY8; case GL_ALPHA: return half_bpp? GL_ALPHA4 : GL_ALPHA8; // 16bpp case GL_LUMINANCE_ALPHA: return half_bpp? GL_LUMINANCE4_ALPHA4 : GL_LUMINANCE8_ALPHA8; // 24bpp case GL_RGB: case GL_BGR: // note: BGR can't be used as internal format return half_bpp? GL_RGB4 : GL_RGB8; // 32bpp case GL_RGBA: case GL_BGRA: // note: BGRA can't be used as internal format return half_bpp? GL_RGBA4 : GL_RGBA8; default: { wchar_t buf[100]; swprintf_s(buf, ARRAY_SIZE(buf), L"choose_int_fmt: fmt 0x%x isn't covered! please add it", fmt); DEBUG_DISPLAY_ERROR(buf); DEBUG_WARN_ERR(ERR::LOGIC); // given fmt isn't covered! please add it. // fall back to a reasonable default return half_bpp? GL_RGB4 : GL_RGB8; } } UNREACHABLE; #endif // #if CONFIG2_GLES } //---------------------------------------------------------------------------- // texture state to allow seamless reload //---------------------------------------------------------------------------- // see "Texture Parameters" in docs. // all GL state tied to the texture that must be reapplied after reload. // (this mustn't get too big, as it's stored in the already sizeable OglTex) struct OglTexState { // glTexParameter // note: there are more options, but they do not look to // be important and will not be applied after a reload! // in particular, LOD_BIAS isn't needed because that is set for // the entire texturing unit via glTexEnv. // .. texture filter // note: this is the minification filter value; magnification filter // is GL_NEAREST if it's GL_NEAREST, otherwise GL_LINEAR. // we don't store mag_filter explicitly because it // doesn't appear useful - either apps can tolerate LINEAR, or // mipmaps aren't called for and filter could be NEAREST anyway). GLint filter; // .. wrap mode GLint wrap_s; GLint wrap_t; // .. anisotropy // note: ignored unless EXT_texture_filter_anisotropic is supported. GLfloat anisotropy; }; // fill the given state object with default values. static void state_set_to_defaults(OglTexState* ots) { ots->filter = default_filter; ots->wrap_s = GL_REPEAT; ots->wrap_t = GL_REPEAT; ots->anisotropy = 1.0f; } // send all state to OpenGL (actually the currently bound texture). // called from ogl_tex_upload. static void state_latch(OglTexState* ots) { // filter const GLint filter = ots->filter; glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filter); const GLint mag_filter = (filter == GL_NEAREST)? GL_NEAREST : GL_LINEAR; glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, mag_filter); // wrap const GLint wrap_s = ots->wrap_s; const GLint wrap_t = ots->wrap_t; glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrap_s); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrap_t); // .. only CLAMP and REPEAT are guaranteed to be available. // if we're using one of the others, we squelch the error that // may have resulted if this GL implementation is old. #if !CONFIG2_GLES if((wrap_s != GL_CLAMP && wrap_s != GL_REPEAT) || (wrap_t != GL_CLAMP && wrap_t != GL_REPEAT)) ogl_SquelchError(GL_INVALID_ENUM); #endif // anisotropy const GLfloat anisotropy = ots->anisotropy; if (anisotropy != 1.0f && ogl_tex_has_anisotropy()) { glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, anisotropy); } } //---------------------------------------------------------------------------- // texture resource object //---------------------------------------------------------------------------- // ideally we would split OglTex into data and state objects as in // SndData / VSrc. this gives us the benefits of caching while still // leaving each "instance" (state object, which owns a data reference) // free to change its state. however, unlike in OpenAL, there is no state // independent of the data object - all parameters are directly tied to the // GL texture object. therefore, splitting them up is impossible. // (we shouldn't even keep the texel data in memory since that's already // covered by the FS cache). // // given that multiple "instances" share the state stored here, we conclude: // - a refcount is necessary to prevent ogl_tex_upload from freeing // as long as other instances are active. // - concurrent use risks cross-talk (if the 2nd "instance" changes state and // the first is reloaded, its state may change to that of the 2nd) // // as bad as it sounds, the latter issue isn't a problem: we do not expect // multiple instances of the same texture where someone changes its filter. // even if it is reloaded, the differing state is not critical. // the alternative is even worse: disabling *all* caching/reuse would // really hurt performance and h_mgr doesn't support only disallowing // reuse of active objects (this would break the index lookup code, since // multiple instances may then exist). // note: make sure these values fit inside OglTex.flags (only 16 bits) enum OglTexFlags { // "the texture is currently uploaded"; reset in dtor. OT_IS_UPLOADED = 1, // "the enclosed Tex object is valid and holds a texture"; // reset in dtor and after ogl_tex_upload's tex_free. OT_TEX_VALID = 2, //size_t tex_valid : 1; // "reload() should automatically re-upload the texture" (because // it had been uploaded before the reload); never reset. OT_NEED_AUTO_UPLOAD = 4, // (used for validating flags) OT_ALL_FLAGS = OT_IS_UPLOADED|OT_TEX_VALID|OT_NEED_AUTO_UPLOAD }; struct OglTex { Tex t; // allocated by OglTex_reload; indicates the texture is currently uploaded. GLuint id; // ogl_tex_upload calls choose_fmt to determine these from . // however, its caller may override those values via parameters. // note: these are stored here to allow retrieving via ogl_tex_get_format; // they are only used within ogl_tex_upload. GLenum fmt; GLint int_fmt; OglTexState state; // OglTexQualityFlags u8 q_flags; // to which Texture Mapping Unit was this bound? u8 tmu; u16 flags; u32 uploaded_size; }; H_TYPE_DEFINE(OglTex); static void OglTex_init(OglTex* ot, va_list args) { Tex* wrapped_tex = va_arg(args, Tex*); if(wrapped_tex) { ot->t = *wrapped_tex; // indicate ot->t is now valid, thus skipping loading from file. // note: ogl_tex_wrap prevents actual reloads from happening. ot->flags |= OT_TEX_VALID; } state_set_to_defaults(&ot->state); ot->q_flags = default_q_flags; } static void OglTex_dtor(OglTex* ot) { if(ot->flags & OT_TEX_VALID) { ot->t.free(); ot->flags &= ~OT_TEX_VALID; } // note: do not check if OT_IS_UPLOADED is set, because we allocate // OglTex.id without necessarily having done an upload. glDeleteTextures(1, &ot->id); ot->id = 0; ot->flags &= ~OT_IS_UPLOADED; ot->uploaded_size = 0; } static Status OglTex_reload(OglTex* ot, const PIVFS& vfs, const VfsPath& pathname, Handle h) { // we're reusing a freed but still in-memory OglTex object if(ot->flags & OT_IS_UPLOADED) return INFO::OK; // if we don't already have the texture in memory (*), load from file. // * this happens if the texture is "wrapped". if(!(ot->flags & OT_TEX_VALID)) { std::shared_ptr file; size_t fileSize; RETURN_STATUS_IF_ERR(vfs->LoadFile(pathname, file, fileSize)); if(ot->t.decode(file, fileSize) >= 0) ot->flags |= OT_TEX_VALID; } glGenTextures(1, &ot->id); // if it had already been uploaded before this reload, // re-upload it (this also does state_latch). if(ot->flags & OT_NEED_AUTO_UPLOAD) (void)ogl_tex_upload(h); return INFO::OK; } static Status OglTex_validate(const OglTex* ot) { if(ot->flags & OT_TEX_VALID) { RETURN_STATUS_IF_ERR(ot->t.validate()); // width, height // (note: this is done here because tex.cpp doesn't impose any // restrictions on dimensions, while OpenGL does). size_t w = ot->t.m_Width; size_t h = ot->t.m_Height; // .. == 0; texture file probably not loaded successfully. if(w == 0 || h == 0) WARN_RETURN(ERR::_11); // .. not power-of-2. // note: we can't work around this because both NV_texture_rectangle // and subtexture require work for the client (changing tex coords). // TODO: ARB_texture_non_power_of_two if(!is_pow2(w) || !is_pow2(h)) WARN_RETURN(ERR::_13); // no longer verify dimensions are less than ogl_max_tex_size, // because we just use the higher mip levels in that case. } // texture state if(!filter_valid(ot->state.filter)) WARN_RETURN(ERR::_14); if(!wrap_valid(ot->state.wrap_s)) WARN_RETURN(ERR::_15); if(!wrap_valid(ot->state.wrap_t)) WARN_RETURN(ERR::_16); // misc if(!q_flags_valid(ot->q_flags)) WARN_RETURN(ERR::_17); if(ot->tmu >= 128) // unexpected that there will ever be this many WARN_RETURN(ERR::_18); if(ot->flags > OT_ALL_FLAGS) WARN_RETURN(ERR::_19); // .. note: don't check ot->fmt and ot->int_fmt - they aren't set // until during ogl_tex_upload. return INFO::OK; } static Status OglTex_to_string(const OglTex* ot, wchar_t* buf) { swprintf_s(buf, H_STRING_LEN, L"OglTex id=%u flags=%x", ot->id, (unsigned int)ot->flags); return INFO::OK; } // load and return a handle to the texture given in . // for a list of supported formats, see tex.h's tex_load. Handle ogl_tex_load(const PIVFS& vfs, const VfsPath& pathname, size_t flags) { Tex* wrapped_tex = 0; // we're loading from file return h_alloc(H_OglTex, vfs, pathname, flags, wrapped_tex); } // make the given Tex object ready for use as an OpenGL texture // and return a handle to it. this will be as if its contents // had been loaded by ogl_tex_load. // // we need only add bookkeeping information and "wrap" it in // a resource object (accessed via Handle), hence the name. // // isn't strictly needed but should describe the texture so that // h_filename will return a meaningful comment for debug purposes. // note: because we cannot guarantee that callers will pass distinct // "filenames", caching is disabled for the created object. this avoids // mistakenly reusing previous objects that share the same comment. Handle ogl_tex_wrap(Tex* t, const PIVFS& vfs, const VfsPath& pathname, size_t flags) { // this object may not be backed by a file ("may", because // someone could do tex_load and then ogl_tex_wrap). // if h_mgr asks for a reload, the dtor will be called but // we won't be able to reconstruct it. therefore, disallow reloads. // (they are improbable anyway since caller is supposed to pass a // 'descriptive comment' instead of filename, but don't rely on that) // also disable caching as explained above. flags |= RES_DISALLOW_RELOAD|RES_NO_CACHE; return h_alloc(H_OglTex, vfs, pathname, flags, t); } // free all resources associated with the texture and make further // use of it impossible. (subject to refcount) Status ogl_tex_free(Handle& ht) { return h_free(ht, H_OglTex); } //---------------------------------------------------------------------------- // state setters (see "Texture Parameters" in docs) //---------------------------------------------------------------------------- // we require the below functions be called before uploading; this avoids // potentially redundant glTexParameter calls (we'd otherwise need to always // set defaults because we don't know if an override is forthcoming). // raise a debug warning if the texture has already been uploaded // (except in the few cases where this is allowed; see below). // this is so that you will notice incorrect usage - only one instance of a // texture should be active at a time, because otherwise they vie for // control of one shared OglTexState. static void warn_if_uploaded(Handle ht, const OglTex* ot) { #ifndef NDEBUG // we do not require users of this module to remember if they've // already uploaded a texture (inconvenient). since they also can't // tell if the texture was newly loaded (due to h_alloc interface), // we have to squelch this warning in 2 cases: // - it's ogl_tex_loaded several times (i.e. refcount > 1) and the // caller (typically a higher-level LoadTexture) is setting filter etc. // - caller is using our Handle as a caching mechanism, and calls // ogl_tex_set_* before every use of the texture. note: this // need not fall under the above check, e.g. if freed but cached. // workaround is that ogl_tex_set_* won't call us if the // same state values are being set (harmless anyway). intptr_t refs = h_get_refcnt(ht); if(refs > 1) return; // don't complain if(ot->flags & OT_IS_UPLOADED) DEBUG_WARN_ERR(ERR::LOGIC); // ogl_tex_set_*: texture already uploaded and shouldn't be changed #else // (prevent warnings; the alternative of wrapping all call sites in // #ifndef is worse) UNUSED2(ht); UNUSED2(ot); #endif } // override default filter (as set above) for this texture. // must be called before uploading (raises a warning if called afterwards). // filter is as defined by OpenGL; it is applied for both minification and // magnification (for rationale and details, see OglTexState) Status ogl_tex_set_filter(Handle ht, GLint filter) { H_DEREF(ht, OglTex, ot); if(!filter_valid(filter)) WARN_RETURN(ERR::INVALID_PARAM); if(ot->state.filter != filter) { warn_if_uploaded(ht, ot); ot->state.filter = filter; } return INFO::OK; } // override default wrap mode (GL_REPEAT) for this texture. // must be called before uploading (raises a warning if called afterwards). // wrap is as defined by OpenGL. Status ogl_tex_set_wrap(Handle ht, GLint wrap_s, GLint wrap_t) { H_DEREF(ht, OglTex, ot); if(!wrap_valid(wrap_s)) WARN_RETURN(ERR::INVALID_PARAM); if(!wrap_valid(wrap_t)) WARN_RETURN(ERR::INVALID_PARAM); if(ot->state.wrap_s != wrap_s || ot->state.wrap_t != wrap_t) { warn_if_uploaded(ht, ot); ot->state.wrap_s = wrap_s; ot->state.wrap_t = wrap_t; } return INFO::OK; } // override default anisotropy for this texture. // must be called before uploading (raises a warning if called afterwards). Status ogl_tex_set_anisotropy(Handle ht, GLfloat anisotropy) { H_DEREF(ht, OglTex, ot); if(anisotropy < 1.0f) WARN_RETURN(ERR::INVALID_PARAM); if(ot->state.anisotropy != anisotropy) { warn_if_uploaded(ht, ot); ot->state.anisotropy = anisotropy; } return INFO::OK; } //---------------------------------------------------------------------------- // upload //---------------------------------------------------------------------------- // OpenGL has several features that are helpful for uploading but not // available in all implementations. we check for their presence but // provide for user override (in case they don't work on a card/driver // combo we didn't test). // tristate; -1 is undecided static int have_auto_mipmap_gen = -1; static int have_s3tc = -1; static int have_anistropy = -1; // override the default decision and force/disallow use of the -// given feature. should be called from ah_override_gl_upload_caps. +// given feature. void ogl_tex_override(OglTexOverrides what, OglTexAllow allow) { ENSURE(allow == OGL_TEX_ENABLE || allow == OGL_TEX_DISABLE); const bool enable = (allow == OGL_TEX_ENABLE); switch(what) { case OGL_TEX_S3TC: have_s3tc = enable; break; case OGL_TEX_AUTO_MIPMAP_GEN: have_auto_mipmap_gen = enable; break; case OGL_TEX_ANISOTROPY: have_anistropy = enable; break; default: DEBUG_WARN_ERR(ERR::LOGIC); // invalid break; } } // detect caps (via OpenGL extension list) and give an app_hook the chance to // override this (e.g. via list of card/driver combos on which S3TC breaks). // called once from the first ogl_tex_upload. static void detect_gl_upload_caps() { // note: gfx_card will be empty if running in quickstart mode; // in that case, we won't be able to check for known faulty cards. // detect features, but only change the variables if they were at // "undecided" (if overrides were set before this, they must remain). if(have_auto_mipmap_gen == -1) { have_auto_mipmap_gen = ogl_HaveExtension("GL_SGIS_generate_mipmap"); } if(have_s3tc == -1) { #if CONFIG2_GLES // some GLES implementations have GL_EXT_texture_compression_dxt1 // but that only supports DXT1 so we can't use it. have_s3tc = ogl_HaveExtensions(0, "GL_EXT_texture_compression_s3tc", NULL) == 0; #else // note: we don't bother checking for GL_S3_s3tc - it is incompatible // and irrelevant (was never widespread). have_s3tc = ogl_HaveExtensions(0, "GL_ARB_texture_compression", "GL_EXT_texture_compression_s3tc", NULL) == 0; #endif } if(have_anistropy == -1) { have_anistropy = ogl_HaveExtension("GL_EXT_texture_filter_anisotropic"); } - // allow app hook to make ogl_tex_override calls - if(AH_IS_DEFINED(override_gl_upload_caps)) - { - ah_override_gl_upload_caps(); - } - // no app hook defined - have our own crack at blacklisting some hardware. - else - { - const std::wstring cardName = gfx::CardName(); - // rationale: janwas's laptop's S3 card blows up if S3TC is used - // (oh, the irony). it'd be annoying to have to share this between all - // projects, hence this default implementation here. - if(cardName == L"S3 SuperSavage/IXC 1014") - ogl_tex_override(OGL_TEX_S3TC, OGL_TEX_DISABLE); - } + const std::wstring cardName = gfx::CardName(); + // rationale: janwas's laptop's S3 card blows up if S3TC is used + // (oh, the irony). it'd be annoying to have to share this between all + // projects, hence this default implementation here. + if(cardName == L"S3 SuperSavage/IXC 1014") + ogl_tex_override(OGL_TEX_S3TC, OGL_TEX_DISABLE); } // take care of mipmaps. if they are called for by , either // arrange for OpenGL to create them, or see to it that the Tex object // contains them (if need be, creating them in software). // sets *plevels_to_skip to influence upload behavior (depending on // whether mipmaps are needed and the quality settings). // returns 0 to indicate success; otherwise, caller must disable // mipmapping by switching filter to e.g. GL_LINEAR. static Status get_mipmaps(Tex* t, GLint filter, int q_flags, int* plevels_to_skip) { // decisions: // .. does filter call for uploading mipmaps? const bool need_mipmaps = are_mipmaps_needed(t->m_Width, t->m_Height, filter); // .. does the image data include mipmaps? (stored as separate // images after the regular texels) const bool includes_mipmaps = (t->m_Flags & TEX_MIPMAPS) != 0; // .. is this texture in S3TC format? (more generally, "compressed") const bool is_s3tc = (t->m_Flags & TEX_DXT) != 0; *plevels_to_skip = TEX_BASE_LEVEL_ONLY; if(!need_mipmaps) return INFO::OK; // image already contains pregenerated mipmaps; we need do nothing. // this is the nicest case, because they are fastest to load // (no extra processing needed) and typically filtered better than // if automatically generated. if(includes_mipmaps) *plevels_to_skip = 0; // t contains mipmaps // OpenGL supports automatic generation; we need only // activate that and upload the base image. #if !CONFIG2_GLES else if(have_auto_mipmap_gen) { // note: we assume GL_GENERATE_MIPMAP and GL_GENERATE_MIPMAP_SGIS // have the same values - it's heavily implied by the spec // governing 'promoted' ARB extensions and just plain makes sense. glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE); } #endif // image is S3TC-compressed and the previous 2 alternatives weren't // available; we're going to cheat and just disable mipmapping. // rationale: having tex_transform add mipmaps would be slow (since // all<->all transforms aren't implemented, it'd have to decompress // from S3TC first), and DDS images ought to include mipmaps! else if(is_s3tc) return ERR::FAIL; // NOWARN // image is uncompressed and we're on an old OpenGL implementation; // we will generate mipmaps in software. else { RETURN_STATUS_IF_ERR(t->transform_to(t->m_Flags|TEX_MIPMAPS)); *plevels_to_skip = 0; // t contains mipmaps } // t contains mipmaps; we can apply our resolution reduction trick: if(*plevels_to_skip == 0) { // if OpenGL's texture dimension limit is too small, use the // higher mipmap levels. NB: the minimum guaranteed size is // far too low, and menu background textures may be large. GLint w = (GLint)t->m_Width, h = (GLint)t->m_Height; while(w > ogl_max_tex_size || h > ogl_max_tex_size) { (*plevels_to_skip)++; w /= 2; h /= 2; // doesn't matter if either dimension drops to 0 } // this saves texture memory by skipping some of the lower // (high-resolution) mip levels. // // note: we don't just use GL_TEXTURE_BASE_LEVEL because it would // require uploading unused levels, which is wasteful. // .. can be expanded to reduce to 1/4, 1/8 by encoding factor in q_flags. if(q_flags & OGL_TEX_HALF_RES) (*plevels_to_skip)++; } return INFO::OK; } // tex_util_foreach_mipmap callbacks: upload the given level to OpenGL. struct UploadParams { GLenum fmt; GLint int_fmt; u32* uploaded_size; }; static void upload_level(size_t level, size_t level_w, size_t level_h, const u8* RESTRICT level_data, size_t level_data_size, void* RESTRICT cbData) { const UploadParams* up = (const UploadParams*)cbData; glTexImage2D(GL_TEXTURE_2D, (GLint)level, up->int_fmt, (GLsizei)level_w, (GLsizei)level_h, 0, up->fmt, GL_UNSIGNED_BYTE, level_data); *up->uploaded_size += (u32)level_data_size; } static void upload_compressed_level(size_t level, size_t level_w, size_t level_h, const u8* RESTRICT level_data, size_t level_data_size, void* RESTRICT cbData) { const UploadParams* up = (const UploadParams*)cbData; pglCompressedTexImage2DARB(GL_TEXTURE_2D, (GLint)level, up->fmt, (GLsizei)level_w, (GLsizei)level_h, 0, (GLsizei)level_data_size, level_data); *up->uploaded_size += (u32)level_data_size; } // upload the texture in the specified (internal) format. // split out of ogl_tex_upload because it was too big. // // pre: is valid for OpenGL use; texture is bound. static void upload_impl(Tex* t, GLenum fmt, GLint int_fmt, int levels_to_skip, u32* uploaded_size) { const GLsizei w = (GLsizei)t->m_Width; const GLsizei h = (GLsizei)t->m_Height; const size_t bpp = t->m_Bpp; const u8* data = (const u8*)t->get_data(); const UploadParams up = { fmt, int_fmt, uploaded_size }; if(t->m_Flags & TEX_DXT) tex_util_foreach_mipmap(w, h, bpp, data, levels_to_skip, 4, upload_compressed_level, (void*)&up); else tex_util_foreach_mipmap(w, h, bpp, data, levels_to_skip, 1, upload_level, (void*)&up); } // upload the texture to OpenGL. // if not 0, parameters override the following: // fmt_ovr : OpenGL format (e.g. GL_RGB) decided from bpp / Tex flags; // q_flags_ovr : global default "quality vs. performance" flags; // int_fmt_ovr : internal format (e.g. GL_RGB8) decided from fmt / q_flags. // // side effects: // - enables texturing on TMU 0 and binds the texture to it; // - frees the texel data! see ogl_tex_get_data. Status ogl_tex_upload(const Handle ht, GLenum fmt_ovr, int q_flags_ovr, GLint int_fmt_ovr) { ONCE(detect_gl_upload_caps()); H_DEREF(ht, OglTex, ot); Tex* t = &ot->t; ENSURE(q_flags_valid(q_flags_ovr)); // we don't bother verifying *fmt_ovr - there are too many values // upload already happened; no work to do. // (this also happens if a cached texture is "loaded") if(ot->flags & OT_IS_UPLOADED) return INFO::OK; if(ot->flags & OT_TEX_VALID) { // decompress S3TC if that's not supported by OpenGL. if((t->m_Flags & TEX_DXT) && !have_s3tc) (void)t->transform_to(t->m_Flags & ~TEX_DXT); // determine fmt and int_fmt, allowing for user override. ot->fmt = choose_fmt(t->m_Bpp, t->m_Flags); if(fmt_ovr) ot->fmt = fmt_ovr; if(q_flags_ovr) ot->q_flags = q_flags_ovr; ot->int_fmt = choose_int_fmt(ot->fmt, ot->q_flags); if(int_fmt_ovr) ot->int_fmt = int_fmt_ovr; ot->uploaded_size = 0; // now actually send to OpenGL: ogl_WarnIfError(); { // (note: we know ht is valid due to H_DEREF, but ogl_tex_bind can // fail in debug builds if OglTex.id isn't a valid texture name) RETURN_STATUS_IF_ERR(ogl_tex_bind(ht, ot->tmu)); int levels_to_skip; if(get_mipmaps(t, ot->state.filter, ot->q_flags, &levels_to_skip) < 0) // error => disable mipmapping ot->state.filter = GL_LINEAR; // (note: if first time, applies our defaults/previous overrides; // otherwise, replays all state changes) state_latch(&ot->state); upload_impl(t, ot->fmt, ot->int_fmt, levels_to_skip, &ot->uploaded_size); } ogl_WarnIfError(); ot->flags |= OT_IS_UPLOADED; // see rationale for at declaration of OglTex. intptr_t refs = h_get_refcnt(ht); if(refs == 1) { // note: we verify above that OT_TEX_VALID is set ot->flags &= ~OT_TEX_VALID; } } ot->flags |= OT_NEED_AUTO_UPLOAD; return INFO::OK; } //---------------------------------------------------------------------------- // getters //---------------------------------------------------------------------------- // retrieve texture dimensions and bits per pixel. // all params are optional and filled if non-NULL. Status ogl_tex_get_size(Handle ht, size_t* w, size_t* h, size_t* bpp) { H_DEREF(ht, OglTex, ot); if(w) *w = ot->t.m_Width; if(h) *h = ot->t.m_Height; if(bpp) *bpp = ot->t.m_Bpp; return INFO::OK; } // retrieve TexFlags and the corresponding OpenGL format. // the latter is determined during ogl_tex_upload and is 0 before that. // all params are optional and filled if non-NULL. Status ogl_tex_get_format(Handle ht, size_t* flags, GLenum* fmt) { H_DEREF(ht, OglTex, ot); if(flags) *flags = ot->t.m_Flags; if(fmt) { ENSURE(ot->flags & OT_IS_UPLOADED); *fmt = ot->fmt; } return INFO::OK; } // retrieve pointer to texel data. // // note: this memory is freed after a successful ogl_tex_upload for // this texture. after that, the pointer we retrieve is NULL but // the function doesn't fail (negative return value) by design. // if you still need to get at the data, add a reference before // uploading it or read directly from OpenGL (discouraged). Status ogl_tex_get_data(Handle ht, u8** p) { H_DEREF(ht, OglTex, ot); *p = ot->t.get_data(); return INFO::OK; } Status ogl_tex_get_uploaded_size(Handle ht, size_t* size) { H_DEREF(ht, OglTex, ot); *size = ot->uploaded_size; return INFO::OK; } // retrieve color of 1x1 mipmap level extern Status ogl_tex_get_average_color(Handle ht, u32* p) { H_DEREF(ht, OglTex, ot); warn_if_uploaded(ht, ot); *p = ot->t.get_average_color(); return INFO::OK; } //---------------------------------------------------------------------------- // misc API //---------------------------------------------------------------------------- // bind the texture to the specified unit [number] in preparation for // using it in rendering. if is 0, texturing is disabled instead. // // side effects: // - changes the active texture unit; // - (if return value is 0:) texturing was enabled/disabled on that unit. // // notes: // - assumes multitexturing is available. // - not necessary before calling ogl_tex_upload! // - on error, the unit's texture state is unchanged; see implementation. Status ogl_tex_bind(Handle ht, size_t unit) { // note: there are many call sites of glActiveTextureARB, so caching // those and ignoring redundant sets isn't feasible. pglActiveTextureARB((int)(GL_TEXTURE0+unit)); // special case: resets the active texture. if(ht == 0) { glBindTexture(GL_TEXTURE_2D, 0); return INFO::OK; } // if this fails, the texture unit's state remains unchanged. // we don't bother catching that and disabling texturing because a // debug warning is raised anyway, and it's quite unlikely. H_DEREF(ht, OglTex, ot); ot->tmu = (u8)unit; // if 0, there's a problem in the OglTex reload/dtor logic. // binding it results in whiteness, which can have many causes; // we therefore complain so this one can be ruled out. ENSURE(ot->id != 0); glBindTexture(GL_TEXTURE_2D, ot->id); return INFO::OK; } Status ogl_tex_get_texture_id(Handle ht, GLuint* id) { *id = 0; H_DEREF(ht, OglTex, ot); *id = ot->id; return INFO::OK; } // apply the specified transforms (as in tex_transform) to the image. // must be called before uploading (raises a warning if called afterwards). Status ogl_tex_transform(Handle ht, size_t transforms) { H_DEREF(ht, OglTex, ot); Status ret = ot->t.transform(transforms); return ret; } // change the pixel format to that specified by . // (note: this is equivalent to ogl_tex_transform(ht, ht_flags^new_flags). Status ogl_tex_transform_to(Handle ht, size_t new_flags) { H_DEREF(ht, OglTex, ot); Status ret = ot->t.transform_to(new_flags); return ret; } // return whether native S3TC support is available bool ogl_tex_has_s3tc() { // ogl_tex_upload must be called before this ENSURE(have_s3tc != -1); return (have_s3tc != 0); } // return whether anisotropic filtering support is available bool ogl_tex_has_anisotropy() { // ogl_tex_upload must be called before this ENSURE(have_anistropy != -1); return (have_anistropy != 0); } Index: ps/trunk/source/lib/res/graphics/ogl_tex.h =================================================================== --- ps/trunk/source/lib/res/graphics/ogl_tex.h (revision 26023) +++ ps/trunk/source/lib/res/graphics/ogl_tex.h (revision 26024) @@ -1,488 +1,488 @@ /* Copyright (C) 2021 Wildfire Games. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* * wrapper for all OpenGL texturing calls. provides caching, hotloading * and lifetime management. */ /* [KEEP IN SYNC WITH WIKI!] Introduction ------------ This module simplifies use of textures in OpenGL. An easy-to-use load/upload/bind/free API is provided, which completely replaces direct access to OpenGL's texturing calls. It basically wraps tex.cpp's texture info in a resource object (see h_mgr.h) that maintains associated GL state and provides for reference counting, caching, hotloading and safe access. Additionally, the upload step provides for trading quality vs. speed and works around older hardware/drivers. Texture Parameters ------------------ OpenGL textures are conditioned on several parameters including filter and wrap mode. These are typically set once when the texture is created, but must survive reloads (1). To that end, all state (2) is set via ogl_tex_set_* (instead of direct glTexParameter calls) and re-applied after a reload. (1) the purpose of hotloading is to permit artists to see their changes in-game without having to restart the map. reloads where the texture looks different due to changed state are useless. (2) currently only filter and wrap mode. no other glTexParameter settings are used ATM; if that changes, add to OglTexState. Uploading to OpenGL ------------------- .. deserves some clarification. This entails calling glTexImage2D (or its variants for mipmaps/compressed textures) and transfers texture parameters and data from system memory to OpenGL (and thereby usually video memory). In so doing, choices are made as to the texture's internal representation (how it is stored in vmem) - in particular, the bit depth. This can trade performance (more/less data to copy) for quality (fidelity to original). We provide a mechanism that applies defaults to all uploads; this allows a global "quality" setting that can boost performance on older graphics cards without requiring anything else to be changed. Textures with specific quality needs can override this via ogl_tex_set_* or ogl_tex_upload parameters. Finally, provision is made for coping with hardware/drivers lacking support for S3TC decompression or mipmap generation: that can be done in software, if necessary. This avoids the need for alternate asset formats and lowers hardware requirements. While such cards probably won't run the app very well (due to their age and lack of other capabilities), this does make possible developing/testing on older machines/laptops. Caching and Texture Instances ----------------------------- Caching is both an advantage and drawback. When opening the same texture twice without previously freeing it, a reference to the first instance is returned. Therefore, be advised that concurrent use of the same texture but with differing parameters (e.g. upload quality) followed by a reload of the first instance will result in using the wrong parameters. For background and rationale why this is acceptable, see struct OglTex. Example Usage ------------- Note: to keep the examples simple, we leave out error handling by ignoring all return values. Each function will still raise a warning (assert) if it fails and passing e.g. invalid Handles will only cause the next function to fail, but real apps should check and report errors. 1) Basic usage: load texture from file. Handle hTexture = ogl_tex_load("filename.dds"); (void)ogl_tex_upload(hTexture); [when rendering:] (void)ogl_tex_bind(hTexture); [.. do something with OpenGL that uses the currently bound texture] [at exit:] * (done automatically, but this avoids it showing up as a leak) (void)ogl_tex_free(hTexture); 2) Advanced usage: wrap existing texture data, override filter, specify internal_format and use multitexturing. Tex t; const size_t flags = 0; * image is plain RGB, default orientation void* data = [pre-existing image] (void)tex_wrap(w, h, 24, flags, data, &t); Handle hCompositeAlphaMap = ogl_tex_wrap(&t, "(alpha map composite)"); (void)ogl_tex_set_filter(hCompositeAlphaMap, GL_LINEAR); (void)ogl_tex_upload(hCompositeAlphaMap, 0, 0, GL_INTENSITY); * (your responsibility! tex_wrap attaches a reference but it is * removed by ogl_tex_upload.) free(data); [when rendering:] (void)ogl_tex_bind(hCompositeAlphaMap, 1); [.. do something with OpenGL that uses the currently bound texture] [at exit:] * (done automatically, but this avoids it showing up as a leak) (void)ogl_tex_free(hCompositeAlphaMap); */ #ifndef INCLUDED_OGL_TEX #define INCLUDED_OGL_TEX #include "lib/res/handle.h" #include "lib/file/vfs/vfs.h" #include "lib/ogl.h" #include "lib/tex/tex.h" // // quality mechanism // /** * Quality flags for texture uploads. * Specify any of them to override certain aspects of the default. */ enum OglTexQualityFlags { /** * emphatically require full quality for this texture. * (q_flags are invalid if this is set together with any other bit) * rationale: the value 0 is used to indicate "use default flags" in * ogl_tex_upload and ogl_tex_set_defaults, so this is the only * way we can say "disregard default and do not reduce anything". */ OGL_TEX_FULL_QUALITY = 0x20, /** * store the texture at half the normal bit depth * (4 bits per pixel component, as opposed to 8). * this increases performance on older graphics cards due to * decreased size in vmem. it has no effect on * compressed textures because they have a fixed internal format. */ OGL_TEX_HALF_BPP = 0x10, /** * store the texture at half its original resolution. * this increases performance on older graphics cards due to * decreased size in vmem. * this is useful for also reducing quality of compressed textures, * which are not affected by OGL_TEX_HALF_BPP. * currently only implemented for images that contain mipmaps * (otherwise, we'd have to resample, which is slow). * note: scaling down to 1/4, 1/8, .. is easily possible without * extra work, so we leave some bits free for that. */ OGL_TEX_HALF_RES = 0x01 }; /** * Change default settings - these affect performance vs. quality. * May be overridden for individual textures via parameter to * ogl_tex_upload or ogl_tex_set_filter, respectively. * * @param q_flags quality flags. Pass 0 to keep the current setting * (initially OGL_TEX_FULL_QUALITY), or any combination of * OglTexQualityFlags. * @param filter mag/minification filter. Pass 0 to keep the current setting * (initially GL_LINEAR), or any valid OpenGL minification filter. */ extern void ogl_tex_set_defaults(int q_flags, GLint filter); // // open/close // /** * Load and return a handle to the texture. * * @param vfs * @param pathname * @param flags h_alloc flags. * @return Handle to texture or negative Status * for a list of supported formats, see tex.h's tex_load. */ extern Handle ogl_tex_load(const PIVFS& vfs, const VfsPath& pathname, size_t flags = 0); /** * Make the Tex object ready for use as an OpenGL texture * and return a handle to it. This will be as if its contents * had been loaded by ogl_tex_load. * * @param t Texture object. * @param vfs * @param pathname filename or description of texture. not strictly needed, * but would allow h_filename to return meaningful info for * purposes of debugging. * @param flags * @return Handle to texture or negative Status * * note: because we cannot guarantee that callers will pass distinct * "filenames", caching is disabled for the created object. this avoids * mistakenly reusing previous objects that share the same comment. * * we need only add bookkeeping information and "wrap" it in * a resource object (accessed via Handle), hence the name. */ extern Handle ogl_tex_wrap(Tex* t, const PIVFS& vfs, const VfsPath& pathname, size_t flags = 0); /** * Release this texture reference. When the count reaches zero, all of * its associated resources are freed and further use made impossible. * * @param ht Texture handle. * @return Status */ extern Status ogl_tex_free(Handle& ht); // // set texture parameters // // these must be called before uploading; this simplifies // things and avoids calling glTexParameter twice. /** * Override default filter (see {@link #ogl_tex_set_defaults}) for * this texture. * * @param ht Texture handle * @param filter OpenGL minification and magnification filter * (rationale: see {@link OglTexState}) * @return Status * * Must be called before uploading (raises a warning if called afterwards). */ extern Status ogl_tex_set_filter(Handle ht, GLint filter); /** * Override default wrap mode (GL_REPEAT) for this texture. * * @param ht Texture handle * @param wrap_s OpenGL wrap mode for S coordinates * @param wrap_t OpenGL wrap mode for T coordinates * @return Status * * Must be called before uploading (raises a warning if called afterwards). */ extern Status ogl_tex_set_wrap(Handle ht, GLint wrap_s, GLint wrap_t); /** * Override default maximum anisotropic filtering for this texture. * * @param ht Texture handle * @param anisotropy Anisotropy value (must not be less than 1.0; should * usually be a power of two) * @return Status * * Must be called before uploading (raises a warning if called afterwards). */ extern Status ogl_tex_set_anisotropy(Handle ht, GLfloat anisotropy); // // upload // enum OglTexOverrides { OGL_TEX_S3TC, OGL_TEX_AUTO_MIPMAP_GEN, OGL_TEX_ANISOTROPY }; enum OglTexAllow { OGL_TEX_DISABLE, OGL_TEX_ENABLE }; /** * Override the default decision and force/disallow use of the -* given feature. Typically called from ah_override_gl_upload_caps. +* given feature. * * @param what Feature to influence. * @param allow Disable/enable flag. */ extern void ogl_tex_override(OglTexOverrides what, OglTexAllow allow); /** * Upload texture to OpenGL. * * @param ht Texture handle * @param fmt_ovr optional override for OpenGL format (e.g. GL_RGB), * which is decided from bpp / Tex flags * @param q_flags_ovr optional override for global default * OglTexQualityFlags * @param int_fmt_ovr optional override for OpenGL internal format * (e.g. GL_RGB8), which is decided from fmt / q_flags. * @return Status. * * Side Effects: * - enables texturing on TMU 0 and binds the texture to it; * - frees the texel data! see ogl_tex_get_data. */ extern Status ogl_tex_upload(const Handle ht, GLenum fmt_ovr = 0, int q_flags_ovr = 0, GLint int_fmt_ovr = 0); // // return information about the texture // /** * Retrieve dimensions and bit depth of the texture. * * @param ht Texture handle * @param w optional; will be filled with width * @param h optional; will be filled with height * @param bpp optional; will be filled with bits per pixel * @return Status */ extern Status ogl_tex_get_size(Handle ht, size_t* w, size_t* h, size_t* bpp); /** * Retrieve pixel format of the texture. * * @param ht Texture handle * @param flags optional; will be filled with TexFlags * @param fmt optional; will be filled with GL format * (it is determined during ogl_tex_upload and 0 before then) * @return Status */ extern Status ogl_tex_get_format(Handle ht, size_t* flags, GLenum* fmt); /** * Retrieve pixel data of the texture. * * @param ht Texture handle * @param p will be filled with pointer to texels. * @return Status * * Note: this memory is freed after a successful ogl_tex_upload for * this texture. After that, the pointer we retrieve is NULL but * the function doesn't fail (negative return value) by design. * If you still need to get at the data, add a reference before * uploading it or read directly from OpenGL (discouraged). */ extern Status ogl_tex_get_data(Handle ht, u8** p); /** * Retrieve number of bytes uploaded for the texture, including mipmaps. * size will be 0 if the texture has not been uploaded yet. * * @param ht Texture handle * @param size Will be filled with size in bytes * @return Status */ extern Status ogl_tex_get_uploaded_size(Handle ht, size_t* size); /** * Retrieve ARGB value of 1x1 mipmap level of the texture, * i.e. the average color of the whole texture. * * @param ht Texture handle * @param p will be filled with ARGB value (or 0 if texture does not have mipmaps) * @return Status * * Must be called before uploading (raises a warning if called afterwards). */ extern Status ogl_tex_get_average_color(Handle ht, u32* p); // // misc // /** * Bind texture to the specified unit in preparation for using it in * rendering. * * @param ht Texture handle. If 0, texturing is disabled on this unit. * @param unit Texture Mapping Unit number, typically 0 for the first. * @return Status * * Side Effects: * - changes the active texture unit; * - (if successful) texturing was enabled/disabled on that unit. * * Notes: * - assumes multitexturing is available. * - not necessary before calling ogl_tex_upload! * - on error, the unit's texture state is unchanged; see implementation. */ extern Status ogl_tex_bind(Handle ht, size_t unit = 0); /** * Return the GL handle of the loaded texture in *id, or 0 on failure. */ extern Status ogl_tex_get_texture_id(Handle ht, GLuint* id); /** * (partially) Transform pixel format of the texture. * * @param ht Texture handle. * @param flags the TexFlags that are to be @em changed. * @return Status * @see tex_transform * * Must be called before uploading (raises a warning if called afterwards). */ extern Status ogl_tex_transform(Handle ht, size_t flags); /** * Transform pixel format of the texture. * * @param ht Texture handle. * @param new_flags Flags desired new TexFlags indicating pixel format. * @return Status * @see tex_transform * * Must be called before uploading (raises a warning if called afterwards). * * Note: this is equivalent to ogl_tex_transform(ht, ht_flags^new_flags). */ extern Status ogl_tex_transform_to(Handle ht, size_t new_flags); /** * Return whether native S3TC texture compression support is available. * If not, textures will be decompressed automatically, hurting performance. * * @return true if native S3TC supported. * * ogl_tex_upload must be called at least once before this. */ extern bool ogl_tex_has_s3tc(); /** * Return whether anisotropic filtering support is available. * (The anisotropy might still be disabled or overridden by the driver * configuration.) * * @return true if anisotropic filtering supported. * * ogl_tex_upload must be called at least once before this. */ extern bool ogl_tex_has_anisotropy(); #endif // #ifndef INCLUDED_OGL_TEX Index: ps/trunk/source/tools/atlas/GameInterface/Handlers/GraphicsSetupHandlers.cpp =================================================================== --- ps/trunk/source/tools/atlas/GameInterface/Handlers/GraphicsSetupHandlers.cpp (revision 26023) +++ ps/trunk/source/tools/atlas/GameInterface/Handlers/GraphicsSetupHandlers.cpp (revision 26024) @@ -1,272 +1,272 @@ /* Copyright (C) 2021 Wildfire Games. * This file is part of 0 A.D. * * 0 A.D. is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * 0 A.D. is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with 0 A.D. If not, see . */ #include "precompiled.h" #include "MessageHandler.h" #include "../GameLoop.h" #include "../CommandProc.h" #include "../ActorViewer.h" #include "../View.h" #include "../InputProcessor.h" #include "graphics/GameView.h" #include "graphics/ObjectManager.h" #include "gui/GUIManager.h" #include "lib/external_libraries/libsdl.h" #include "lib/ogl.h" #include "lib/timer.h" #include "maths/MathUtil.h" #include "ps/CConsole.h" #include "ps/Filesystem.h" #include "ps/Profile.h" #include "ps/Profiler2.h" #include "ps/Game.h" #include "ps/VideoMode.h" #include "ps/GameSetup/Config.h" #include "ps/GameSetup/GameSetup.h" #include "renderer/Renderer.h" #if OS_WIN // We don't include wutil header directly to prevent including Windows headers. extern void wutil_SetAppWindow(void* hwnd); #endif namespace AtlasMessage { InputProcessor g_Input; // This keeps track of the last in-game user input. // It is used to throttle FPS to save CPU & GPU. double last_user_activity; // see comment in GameLoop.cpp about ah_display_error before using INIT_HAVE_DISPLAY_ERROR -const int g_InitFlags = INIT_HAVE_VMODE|INIT_NO_GUI; +const int g_InitFlags = INIT_HAVE_VMODE | INIT_NO_GUI; MESSAGEHANDLER(Init) { UNUSED2(msg); g_Quickstart = true; // Mount mods if there are any specified as command line parameters - if (!Init(g_AtlasGameLoop->args, g_InitFlags | INIT_MODS|INIT_MODS_PUBLIC)) + if (!Init(g_AtlasGameLoop->args, g_InitFlags | INIT_MODS| INIT_MODS_PUBLIC)) { // There are no mods specified on the command line, // but there are in the config file, so mount those. Shutdown(SHUTDOWN_FROM_CONFIG); ENSURE(Init(g_AtlasGameLoop->args, g_InitFlags)); } // Initialise some graphics state for Atlas. // (This must be done after Init loads the config DB, // but before the UI constructs its GL canvases.) g_VideoMode.InitNonSDL(); } MESSAGEHANDLER(InitAppWindow) { #if OS_WIN wutil_SetAppWindow(msg->handle); #else UNUSED2(msg); #endif } MESSAGEHANDLER(InitSDL) { UNUSED2(msg); // When using GLX (Linux), SDL has to load the GL library to find // glXGetProcAddressARB before it can load any extensions. // When running in Atlas, we skip the SDL video initialisation code // which loads the library, and so SDL_GL_GetProcAddress fails (in // ogl.cpp importExtensionFunctions). // (TODO: I think this is meant to be context-independent, i.e. it // doesn't matter that we're getting extensions from SDL-initialised // GL stuff instead of from the wxWidgets-initialised GL stuff, but that // should be checked.) // So, make sure it's loaded: SDL_InitSubSystem(SDL_INIT_VIDEO); SDL_GL_LoadLibrary(NULL); // NULL = use default // (it shouldn't hurt if this is called multiple times, I think) } MESSAGEHANDLER(InitGraphics) { UNUSED2(msg); ogl_Init(); InitGraphics(g_AtlasGameLoop->args, g_InitFlags, {}); #if OS_WIN // HACK (to stop things looking very ugly when scrolling) - should // use proper config system. if(ogl_HaveExtension("WGL_EXT_swap_control")) pwglSwapIntervalEXT(1); #endif } MESSAGEHANDLER(Shutdown) { UNUSED2(msg); // Empty the CommandProc, to get rid of its references to entities before // we kill the EntityManager GetCommandProc().Destroy(); AtlasView::DestroyViews(); g_AtlasGameLoop->view = AtlasView::GetView_None(); int flags = 0; Shutdown(flags); } QUERYHANDLER(Exit) { UNUSED2(msg); g_AtlasGameLoop->running = false; } MESSAGEHANDLER(RenderEnable) { g_AtlasGameLoop->view->SetEnabled(false); g_AtlasGameLoop->view = AtlasView::GetView(msg->view); g_AtlasGameLoop->view->SetEnabled(true); } MESSAGEHANDLER(SetViewParamB) { AtlasView* view = AtlasView::GetView(msg->view); view->SetParam(*msg->name, msg->value); } MESSAGEHANDLER(SetViewParamI) { AtlasView* view = AtlasView::GetView(msg->view); view->SetParam(*msg->name, msg->value); } MESSAGEHANDLER(SetViewParamC) { AtlasView* view = AtlasView::GetView(msg->view); view->SetParam(*msg->name, msg->value); } MESSAGEHANDLER(SetViewParamS) { AtlasView* view = AtlasView::GetView(msg->view); view->SetParam(*msg->name, *msg->value); } MESSAGEHANDLER(SetActorViewer) { if (msg->flushcache) { // TODO EXTREME DANGER: this'll break horribly if any units remain // in existence and use their actors after we've deleted all the actors. // (The actor viewer currently only has one unit at a time, so it's // alright.) // Should replace this with proper actor hot-loading system, or something. AtlasView::GetView_Actor()->GetActorViewer().SetActor(L"", "", -1); AtlasView::GetView_Actor()->GetActorViewer().UnloadObjects(); // vfs_reload_changed_files(); } AtlasView::GetView_Actor()->SetSpeedMultiplier(msg->speed); AtlasView::GetView_Actor()->GetActorViewer().SetActor(*msg->id, *msg->animation, msg->playerID); } ////////////////////////////////////////////////////////////////////////// MESSAGEHANDLER(SetCanvas) { // Need to set the canvas size before possibly doing any rendering, // else we'll get GL errors when trying to render to 0x0 CVideoMode::UpdateRenderer(msg->width, msg->height); g_AtlasGameLoop->glCanvas = msg->canvas; Atlas_GLSetCurrent(const_cast(g_AtlasGameLoop->glCanvas)); } MESSAGEHANDLER(ResizeScreen) { CVideoMode::UpdateRenderer(msg->width, msg->height); #if OS_MACOSX // OS X seems to require this to update the GL canvas Atlas_GLSetCurrent(const_cast(g_AtlasGameLoop->glCanvas)); #endif } QUERYHANDLER(RenderLoop) { { const double time = timer_Time(); static double last_time = time; const double realFrameLength = time-last_time; last_time = time; ENSURE(realFrameLength >= 0.0); // TODO: filter out big jumps, e.g. when having done a lot of slow // processing in the last frame g_AtlasGameLoop->realFrameLength = realFrameLength; } if (g_Input.ProcessInput(g_AtlasGameLoop)) last_user_activity = timer_Time(); msg->timeSinceActivity = timer_Time() - last_user_activity; ReloadChangedFiles(); RendererIncrementalLoad(); // Pump SDL events (e.g. hotkeys) SDL_Event_ ev; while (in_poll_priority_event(&ev)) in_dispatch_event(&ev); if (g_GUI) g_GUI->TickObjects(); g_AtlasGameLoop->view->Update(g_AtlasGameLoop->realFrameLength); g_AtlasGameLoop->view->Render(); if (CProfileManager::IsInitialised()) g_Profiler.Frame(); msg->wantHighFPS = g_AtlasGameLoop->view->WantsHighFramerate(); } ////////////////////////////////////////////////////////////////////////// MESSAGEHANDLER(RenderStyle) { g_Renderer.SetTerrainRenderMode(msg->wireframe ? EDGED_FACES : SOLID); g_Renderer.SetWaterRenderMode(msg->wireframe ? EDGED_FACES : SOLID); g_Renderer.SetModelRenderMode(msg->wireframe ? EDGED_FACES : SOLID); g_Renderer.SetOverlayRenderMode(msg->wireframe ? EDGED_FACES : SOLID); } } // namespace AtlasMessage