Zero Hour rebuilt from EA's source: x64, Direct3D 11, VS2022/CMake, ~60 original bugs fixed, an AI that builds a base. Bring your own game.
C++ cmakecnccommand-and-conquercppdirectx11game-enginegame-preservationgeneralsrtssage-enginex64zero-hour
perf: cut redundant device, light, lock and heap work per frame
Olcay Seyganbc3d17af7981
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0ce943104..cd6024b1b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -100,6 +100,7 @@ found and fixed — EA's own, not port damage.**- The command bar stopped throwing its own layout away every frame. The few hundred positions and sizes it hands its page were written into a fresh list each frame, copied twice for the frames in front of the buttons, and thrown out, and every price and build time on a button was looked up by copying the text of every figure the bar was already showing. The list is written over in place now, nothing is copied, and the graphics card settings that did not change between two draws are not looked up again. The same Twilight Flame match from a player's seat went from 2.29ms a frame to 1.96ms, and as an observer from 1.64ms to 1.58ms. The picture is the same one.- Raise the particle limit as far as you like and every puff gets drawn. Past about sixteen thousand smoke and fire sprites on screen the game quietly stopped drawing the rest: a test with 68,000 of them showed barely a fifth. A test with 101,000 now draws all of them at 8.3ms a frame, and in 1,200 frames not one fell below 60 a second. The first version that drew them all took 22.4ms; the rest came from sorting and copying them far less and from sharing the work across every core of the processor.- Big fights no longer drag the picture down into the twenties. Every moving tank and soldier, and every puff of smoke, goes to the graphics card through one shared scratch area, and it was so small that a big fight on Bombardment Beach filled it about fifty times a frame. Each refill made the processor wait for the card, 8 to 12ms of every frame, while the card sat two thirds idle. The area is made full size once now and refills about seven times a frame, in 0.02ms. The same 16,000-frame battle, fast-forwarded, finishes in 226 seconds where it took between 263 and 325, and the seconds that fell under 50 frames a second went from 125 or more to 4.+- Crowded battles run a few frames faster again. Six computer players on one map gain 2.4%, and thirty Inferno Cannons against twenty Crusaders gain 7.3% at 720p and 6.2% at 1080p. The game stopped re-sending lights and materials to the graphics card when nothing about them had changed, stopped relighting the terrain when no light had moved, stopped adding up the glow of every fire particle twice, and widened 16-bit textures with a lookup instead of arithmetic on each pixel. The rules side runs 4% quicker too: locking, the lists of nearby units, the sleeping-unit schedule and text strings all got cheaper. The picture matches the old build to within 0.06% of pixels in all eight test views, and a recorded match plays back to the same checksum.- Every animation runs on a clock instead of counting frames.- Tanks and trucks move the same at any frame rate. Their treads scrolled a fixed step every picture, so at 120 frames a second they ran four times too fast, and a tank turning on the spot rolled both treads forward as if it were driving. Each tread now covers exactly the ground under it. In a tight turn the two run against each other, and backing up runs them backwards. Wheels spin with the distance driven the same way. The hull's springs used to settle four times too fast as well, and every start or stop threw the chassis to its full tilt in a single picture. Now a tank squats as it pulls away and dips its nose when it brakes, easing in over a tenth of a second and settling within half a second. In a corner it leans out, a Crusader up to two and a half degrees. The Humvee, which never moved on its springs at all, rocks too. A run drawing one picture per game tick and one drawing fourteen put every tank in the same pose, to the last digit, for as long as neither skipped a tick.- A scroll that starts after the camera has stood still no longer lurches. The first frame of the move was timed from the last time the camera moved, so after a few seconds of looking at one spot it was worth three frames of scrolling at once. The clock runs while the camera is still now, and the first frame moves one frame's worth.diff --git a/GeneralsMD/Code/GameEngine/Include/Common/CriticalSection.h b/GeneralsMD/Code/GameEngine/Include/Common/CriticalSection.hindex 1dd503e75..85a394e92 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/CriticalSection.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/CriticalSection.h@@ -36,11 +36,19 @@#include <mutex>+#include <atomic>+#include <stdint.h>+#if defined(__APPLE__)#include <os/lock.h>#include <pthread.h>-#include <atomic>-#include <stdint.h>+#else+#include <condition_variable>+#include <cstdlib>+#include <thread>+#if defined(_MSC_VER)+#include <intrin.h> // _mm_pause, __yield+#endif#endif#ifdef PERF_TIMERS@@ -48,44 +56,23 @@ extern PerfGather TheCritSecPerfGather;#endif/*- This was a raw Win32 CRITICAL_SECTION. It is a std::recursive_mutex now (B11), and the- "recursive" is not conservatism - it is required, by one caller, unconditionally:-- UnicodeString::set( const UnicodeString & ) UnicodeString.cpp:155- takes TheUnicodeStringCriticalSection UnicodeString.cpp:157- calls releaseBuffer() UnicodeString.cpp:162- takes TheUnicodeStringCriticalSection UnicodeString.cpp:130 <- again, same lock-- The scoped lock taken at :157 is still in scope when :162 runs, and the branch it sits in is- `if (&stringSrc != this)` - which is the ordinary case, not an edge one. A Win32- CRITICAL_SECTION is recursive, so this has always been well-defined; a std::mutex is not, and- re-locking one you already hold is undefined behaviour rather than a deadlock you would- notice in a debugger. So std::mutex is not available to us here, and a future reader who- thinks the "recursive" looks unnecessary should re-read those four lines before removing it.-- The other three locks this class backs do not recurse - checked, not assumed:-- TheMemoryPoolCriticalSection GameMemory.cpp 1644, 1734, 1793, 1814. The functions reached- under it - createBlob, freeBlob, init, sysAllocateDoNotZero,- sysFree - take no lock of their own.- TheDmaCriticalSection GameMemory.cpp 2182, 2298. Nests into the pool lock, which is- a different object.- TheDebugLogCriticalSection Debug.cpp 451. doLogOutput is a leaf: fprintf and- OutputDebugString, no allocation and no way back into DebugLog.-- They share one class, so they get the recursive one too. The cost of that over a plain mutex- is an owner check on an uncontended acquire, which is also exactly what CRITICAL_SECTION was- doing before - this is the mapping that keeps behaviour identical, not a concession.-- Lock ordering, since three of the four nest: Unicode -> Dma -> Pool, in that direction only.- UnicodeString::releaseBuffer calls TheDynamicMemoryAllocator->freeBytes under the Unicode- lock, and DynamicMemoryAllocator::allocateBytesDoNotZeroImplementation calls into the pool- under the Dma lock. Nothing in GameMemory.cpp takes the Unicode lock, so there is no cycle.- Keep it that way.-- No spin count is lost in the move. InitializeCriticalSectionAndSpinCount,- SetCriticalSectionSpinCount and TryEnterCriticalSection appear nowhere in this tree, so every- one of these locks was already a plain InitializeCriticalSection with the system default.+ This was a raw Win32 CRITICAL_SECTION, then std::recursive_mutex (B11), and is now an owner and+ a count over a platform word: RecursiveUnfairLock on Apple, RecursiveLock everywhere else. It+ stays recursive, as CRITICAL_SECTION was. The one caller that re-entered, UnicodeString::set+ through releaseBuffer, takes no lock since its count went atomic (2026-10-05), so no caller+ needs the recursion now; keeping it costs one compare per enter. TheUnicodeStringCriticalSection+ is still declared because WinMain, PosixMain and the tests assign it. Nothing takes it.++ The three locks in use:++ TheMemoryPoolCriticalSection MemoryPool's allocate, free, releaseEmpties and reset in+ GameMemory.cpp. What they call under it takes no lock.+ TheDmaCriticalSection DynamicMemoryAllocator's allocate and free. Nests into the pool+ lock, a different object.+ TheDebugLogCriticalSection DebugLog in Debug.cpp, under DEBUG_THREADSAFE. A leaf.++ Lock order: Dma -> Pool, that direction only. Nothing in GameMemory.cpp takes the Dma lock+ under the pool lock. Keep it that way.On Apple the lock is os_unfair_lock with an owner and a count (PERF1, 2026-09-27), not libc++'sstd::recursive_mutex, which is a recursive pthread mutex there. The allocator takes these locks@@ -102,10 +89,114 @@ extern PerfGather TheCritSecPerfGather;Without it a non-owner exit at depth above one would quietly count down someone else's depth. Athread that ends while holding the lock is a bug on every platform too; here a later thread giventhe same pthread_t would find itself the owner.- Windows and Linux keep std::recursive_mutex: Linux's glibc mutex is to be measured before it is- replaced, and Windows is not ours to measure.++ Everywhere else (2026-10-05) the lock is RecursiveLock below, the same owner and count over a+ three-state word in place of os_unfair_lock. MSVC's std::recursive_mutex went through+ msvcp140's _Mtx_lock and mtx_do_lock into ntdll's SRW lock on every allocation:+ RtlAcquire/ReleaseSRWLockExclusive were 2.3% and mtx_do_lock 0.6% of the main thread in a+ 530-unit fight. Uncontended, this is one compare-exchange to enter and one exchange to leave,+ inline, the same two locked instructions the SRW lock executes; what goes is the calls around+ them and the second owner check. A thread that finds the lock taken spins on a CPU pause for a+ short while, as SRW does (JobSystem workers hold the pool lock for well under a microsecond),+ then yields a few times, then sleeps on a condition variable until the holder's exit wakes it,+ so a long hold costs a waiter no CPU. The owner tag is the address of a thread_local, which costs no call; as with pthread_t+ on Apple, a later thread can be given the address of one that ended, which matters only if that+ one ended holding the lock. Linux's glibc mutex was never measured against this. It takes the+ same path because nothing in it is Windows.*/-#if defined(__APPLE__)+#if !defined(__APPLE__)+class RecursiveLock+{+ std::atomic<unsigned int> m_state{ 0 }; ///< 0 free, 1 held, 2 held and someone may be asleep+ std::atomic<uintptr_t> m_owner{ 0 }; ///< the holder's tag, 0 when free+ unsigned int m_depth = 0; ///< read and written by the holder only+ std::mutex m_parkMutex; ///< guards the sleep, not the lock+ std::condition_variable m_parkCv;++ static uintptr_t self()+ {+ static thread_local char tag;+ return reinterpret_cast<uintptr_t>( &tag );+ }++ bool tryTake()+ {+ unsigned int expected = 0;+ return m_state.compare_exchange_strong( expected, 1, std::memory_order_acquire, std::memory_order_relaxed );+ }++ static void cpuRelax()+ {+ #if defined(_MSC_VER) && (defined(_M_X64) || defined(_M_IX86))+ _mm_pause();+ #elif defined(_MSC_VER) && defined(_M_ARM64)+ __yield();+ #elif defined(__x86_64__) || defined(__i386__)+ __builtin_ia32_pause();+ #elif defined(__aarch64__)+ __asm__ __volatile__( "yield" );+ #endif+ }++ void lockContended()+ {+ for (int spin = 0; spin < 128; ++spin)+ {+ cpuRelax();+ if (m_state.load( std::memory_order_relaxed ) == 0 && tryTake())+ return;+ }+ for (int spin = 0; spin < 16; ++spin)+ {+ std::this_thread::yield();+ if (m_state.load( std::memory_order_relaxed ) == 0 && tryTake())+ return;+ }+ // Marking the word 2 before sleeping is what makes the holder's exit wake someone. The mark+ // and the check happen under m_parkMutex, and the waker takes m_parkMutex before it notifies,+ // so a wake cannot fall between this thread's check and its wait. Whoever gets the lock out+ // of here leaves it at 2, which at worst costs one wake nobody needed.+ std::unique_lock<std::mutex> park( m_parkMutex );+ while (m_state.exchange( 2, std::memory_order_acquire ) != 0)+ m_parkCv.wait( park );+ }++ void wake()+ {+ { std::lock_guard<std::mutex> park( m_parkMutex ); }+ m_parkCv.notify_all();+ }++public:+ void lock()+ {+ const uintptr_t me = self();+ // Only this thread ever stores its own tag, so a relaxed load that sees it is this thread's own+ // earlier store: the lock is ours already.+ if (m_owner.load( std::memory_order_relaxed ) == me)+ {+ ++m_depth;+ return;+ }+ if (!tryTake())+ lockContended();+ m_owner.store( me, std::memory_order_relaxed );+ m_depth = 1;+ }++ void unlock()+ {+ if (m_owner.load( std::memory_order_relaxed ) != self())+ std::abort(); // CriticalSection::exit by a thread that does not hold it+ if (--m_depth == 0)+ {+ m_owner.store( 0, std::memory_order_relaxed );+ if (m_state.exchange( 0, std::memory_order_release ) == 2)+ wake();+ }+ }+};+#elseclass RecursiveUnfairLock{os_unfair_lock m_lock = OS_UNFAIR_LOCK_INIT;@@ -148,7 +239,7 @@ class CriticalSection#if defined(__APPLE__)RecursiveUnfairLock m_mutex;#else- std::recursive_mutex m_mutex;+ RecursiveLock m_mutex;#endifpublic:@@ -209,9 +300,8 @@ class ScopedCriticalSection// TheAsciiStringCriticalSection used to sit at the top of this list, a FastCriticalSectionClass// from WWVegas' mutex.h rather than one of these. It is gone, and so is the #include of mutex.h// that only it needed: its three uses in AsciiString.h (:378, :389, :450) are all commented out,-// nothing else in the tree named it, and WinMain never assigned it. mutex.h reaches <intrin.h>-// and _interlockedbittestandset, so a dead extern was keeping MSVC intrinsics in the header that-// the allocator and both string classes compile against.+// nothing else in the tree named it, and WinMain never assigned it. The <intrin.h> at the top is+// RecursiveLock's own, for the pause in its contended spin, not a leftover of mutex.h.extern CriticalSection *TheUnicodeStringCriticalSection;extern CriticalSection *TheDmaCriticalSection;extern CriticalSection *TheMemoryPoolCriticalSection;diff --git a/GeneralsMD/Code/GameEngine/Include/Common/UnicodeString.h b/GeneralsMD/Code/GameEngine/Include/Common/UnicodeString.hindex ec9ee7f5d..b6e9e4a17 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/UnicodeString.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/UnicodeString.h@@ -56,6 +56,8 @@#include "Common/Debug.h"#include "Common/Errors.h"#include "Lib/WideCharFns.h" // the engine's own wcs*: WideChar is char16_t, which the C library has no functions for+#include <atomic>+#include <new>class AsciiString;@@ -94,7 +96,7 @@ private:#if defined(_DEBUG) || defined(_INTERNAL)const WideChar* m_debugptr; // just makes it easier to read in the debugger#endif- unsigned short m_refCount; // reference count+ std::atomic<unsigned short> m_refCount; // reference count; atomic as AsciiStringData's, no lockunsigned short m_numCharsAllocated; // length of data allocated// WideChar m_stringdata[];diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/GameLogic.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/GameLogic.hindex 611606ade..bccb8d7ad 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/GameLogic.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/GameLogic.h@@ -111,6 +111,13 @@ typedef void (*GameLogicFuncPtr)( Object *obj, void *userData );typedef std::vector<Object*> ObjectPtrVector;+/// One slot of GameLogic's sleepy-update heap: the module and its friend_getPriority() beside it.+struct SleepyEntry+{+ UnsignedInt priority;+ UpdateModulePtr module;+};+// ------------------------------------------------------------------------------------------------/*** The implementation of GameLogic@@ -379,7 +386,10 @@ private:// never modify it directly; please use the proper access methods.// (for an excellent discussion of priority queues, please see:// http://dogma.net/markn/articles/pq_stl/priority.htm)- std::vector<UpdateModulePtr> m_sleepyUpdates;+ // Each entry carries a copy of its module's friend_getPriority() so the heap compares without+ // touching the pooled module. The copy must equal the module's value whenever a heap operation+ // runs: every friend_setNextCallFrame on a queued module writes the entry at its index too.+ std::vector<SleepyEntry> m_sleepyUpdates;#ifdef ALLOW_NONSLEEPY_UPDATES// this is a plain old list, not a pq.diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/ObjectIter.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/ObjectIter.hindex 8faff0920..25d8a9577 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/ObjectIter.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/ObjectIter.h@@ -93,19 +93,26 @@ class SimpleObjectIterator : public ObjectIteratorMEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(SimpleObjectIterator, "SimpleObjectIteratorPool" )private:- class Clump : public MemoryPoolObject- {- MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(Clump, "SimpleObjectIteratorClumpPool" )- public:+ class PooledClump;- Clump *m_nextClump;- Object *m_obj;- Real m_numeric; // typically, dist-squared+ struct Clump+ {+ Clump *m_nextClump;+ Object *m_obj;+ PooledClump *m_pooled; // NULL when the clump is one of m_inlineClumps+ Real m_numeric; // typically, dist-squared+ };- Clump();- //~Clump();+ // a query that finds more than INLINE_CLUMPS objects takes the rest from the pool+ class PooledClump : public MemoryPoolObject+ {+ MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(PooledClump, "SimpleObjectIteratorClumpPool" )+ public:+ Clump m_clump;};+ enum { INLINE_CLUMPS = 64 };+typedef Real (*ClumpCompareProc)(Clump *a, Clump *b);static ClumpCompareProc theClumpCompareProcs[];@@ -118,6 +125,8 @@ private:Clump *m_firstClump;Clump *m_curClump;Int m_clumpCount;+ Int m_inlineClumpsUsed;+ Clump m_inlineClumps[INLINE_CLUMPS];void reset();diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/AsciiString.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/AsciiString.cppindex 0eb616a1e..31eb3106a 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/System/AsciiString.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/AsciiString.cpp@@ -124,7 +124,7 @@ void AsciiString::ensureUniqueBufferOfSize(int numCharsNeeded, Bool preserveDatavalidate();if (m_data &&- m_data->m_refCount.load(std::memory_order_relaxed) == 1 &&+ m_data->m_refCount.load(std::memory_order_acquire) == 1 && // acquire: the last other holder's reads of the buffer happen before this thread writes itm_data->m_numCharsAllocated >= numCharsNeeded){// no buffer manhandling is needed (it's already large enough, and unique to us)diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/UnicodeString.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/UnicodeString.cppindex de237f912..76aae9598 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/System/UnicodeString.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/UnicodeString.cpp@@ -46,7 +46,6 @@#include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine#include "Lib/WideCharFns.h"-#include "Common/CriticalSection.h"#ifdef _INTERNAL@@ -64,7 +63,7 @@void UnicodeString::validate() const{if (!m_data) return;- DEBUG_ASSERTCRASH(m_data->m_refCount > 0, ("m_refCount is zero"));+ DEBUG_ASSERTCRASH(m_data->m_refCount.load(std::memory_order_relaxed) > 0, ("m_refCount is zero"));DEBUG_ASSERTCRASH(m_data->m_numCharsAllocated > 0, ("m_numCharsAllocated is zero"));DEBUG_ASSERTCRASH(WideCharLen(m_data->peek())+1 <= m_data->m_numCharsAllocated,("str is too long for storage"));}@@ -73,9 +72,12 @@ void UnicodeString::validate() const// -----------------------------------------------------UnicodeString::UnicodeString(const UnicodeString& stringSrc) : m_data(stringSrc.m_data){- ScopedCriticalSection scopedCriticalSection(TheUnicodeStringCriticalSection);+ /* The refcount is atomic, with AsciiString's orderings (AsciiString.h, the copy constructor and+ releaseBuffer), so TheUnicodeStringCriticalSection is no longer taken here or anywhere. That+ lock only ever covered the count: a race on one UnicodeString object itself - one thread+ copying it while another reassigns it - read m_data outside the lock before, and still does. */if (m_data)- ++m_data->m_refCount;+ m_data->m_refCount.fetch_add(1, std::memory_order_relaxed);validate();}@@ -85,7 +87,7 @@ void UnicodeString::ensureUniqueBufferOfSize(int numCharsNeeded, Bool preserveDavalidate();if (m_data &&- m_data->m_refCount == 1 &&+ m_data->m_refCount.load(std::memory_order_acquire) == 1 && // acquire: the last other holder's reads of the buffer happen before this thread writes itm_data->m_numCharsAllocated >= numCharsNeeded){// no buffer manhandling is needed (it's already large enough, and unique to us)@@ -110,7 +112,7 @@ void UnicodeString::ensureUniqueBufferOfSize(int numCharsNeeded, Bool preserveDapreMainInitMemoryManager(); // a string built by a static constructor, before main (GameMemory.h)int actualBytes = TheDynamicMemoryAllocator->getActualAllocationSize(minBytes);UnicodeStringData* newData = (UnicodeStringData*)TheDynamicMemoryAllocator->allocateBytesDoNotZero(actualBytes, "STR_UnicodeString::ensureUniqueBufferOfSize");- newData->m_refCount = 1;+ new (&newData->m_refCount) std::atomic<unsigned short>(1); // raw bytes, no constructor ran: start the atomic's lifetimenewData->m_numCharsAllocated = (actualBytes - sizeof(UnicodeStringData))/sizeof(WideChar);#if defined(_DEBUG) || defined(_INTERNAL)newData->m_debugptr = newData->peek(); // just makes it easier to read in the debugger@@ -138,12 +140,10 @@ void UnicodeString::ensureUniqueBufferOfSize(int numCharsNeeded, Bool preserveDa// -----------------------------------------------------void UnicodeString::releaseBuffer(){- ScopedCriticalSection scopedCriticalSection(TheUnicodeStringCriticalSection);-validate();if (m_data){- if (--m_data->m_refCount == 0)+ if (m_data->m_refCount.fetch_sub(1, std::memory_order_acq_rel) == 1) // exactly one releaser sees 1{TheDynamicMemoryAllocator->freeBytes(m_data);}@@ -165,15 +165,15 @@ UnicodeString::UnicodeString(const WideChar* s) : m_data(0)// -----------------------------------------------------void UnicodeString::set(const UnicodeString& stringSrc){- ScopedCriticalSection scopedCriticalSection(TheUnicodeStringCriticalSection);-validate();if (&stringSrc != this){+ // Release first is safe without the lock: if both share a buffer the count is at least 2,+ // so the release cannot free what stringSrc still holds.releaseBuffer();m_data = stringSrc.m_data;if (m_data)- ++m_data->m_refCount;+ m_data->m_refCount.fetch_add(1, std::memory_order_relaxed);}validate();}diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/SimpleObjectIterator.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/SimpleObjectIterator.cppindex 9f5d884bd..2ff15dce7 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/SimpleObjectIterator.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/Object/SimpleObjectIterator.cpp@@ -46,13 +46,7 @@ SimpleObjectIterator::ClumpCompareProc SimpleObjectIterator::theClumpCompareProc};//=============================================================================-SimpleObjectIterator::Clump::Clump()-{- m_nextClump = NULL;-}--//=============================================================================-SimpleObjectIterator::Clump::~Clump()+SimpleObjectIterator::PooledClump::~PooledClump(){}@@ -62,6 +56,7 @@ SimpleObjectIterator::SimpleObjectIterator()m_firstClump = NULL;m_curClump = NULL;m_clumpCount = 0;+ m_inlineClumpsUsed = 0;}//=============================================================================@@ -71,21 +66,31 @@ SimpleObjectIterator::~SimpleObjectIterator()}//=============================================================================-/* Recycling these through a free list instead of the pool was tried and measured at nothing.-- A gathering range query keeps every object it finds in one of these and an eight-player match- makes 111 such queries a logic frame, so this is thousands of pool allocations and frees a- frame, every one of them taking the global memory lock that THREADING-ROADMAP section 1.1 is- about. Recycling removes all of them, comes back bit-identical over four matches, and moves the- mean logic frame from 1.24ms to 1.26 - which is to say it does nothing. The pool is a free list- already and the lock is uncontended in a single-threaded logic frame, so the 16,523- critical-section operations a frame are cheap operations. Worth knowing before anybody spends a- fortnight on the allocator. */+/* The first INLINE_CLUMPS objects a query finds go into the iterator's own array, and only the+ rest take a pool block each. A gathering range query used to allocate one per object found.+ On an eight-player match (111 such queries a logic frame) recycling them through a free list+ measured at nothing, 1.24ms to 1.26, since the pool is a free list already and its lock is+ uncontended. A dense fight of several hundred units makes far more of these queries, each one+ finding dozens of neighbours, and that is the case this array is for; its gain there has not+ been measured yet. Which slot a clump lives+ in never reaches the order: insert still pushes at the head and sort compares only m_numeric+ or the build cost, so the output is the same object sequence as before. */void SimpleObjectIterator::insert(Object *obj, Real numeric){DEBUG_ASSERTCRASH(obj, ("sorry, no nulls allowed here"));- Clump *clump = newInstance(Clump)();+ Clump *clump;+ if (m_inlineClumpsUsed < INLINE_CLUMPS)+ {+ clump = &m_inlineClumps[m_inlineClumpsUsed++];+ clump->m_pooled = NULL;+ }+ else+ {+ PooledClump *pooled = newInstance(PooledClump);+ clump = &pooled->m_clump;+ clump->m_pooled = pooled;+ }clump->m_nextClump = m_firstClump;m_firstClump = clump;@@ -126,7 +131,8 @@ void SimpleObjectIterator::makeEmpty()while (m_firstClump){Clump *next = m_firstClump->m_nextClump;- m_firstClump->deleteInstance();+ if (m_firstClump->m_pooled)+ m_firstClump->m_pooled->deleteInstance();m_firstClump = next;--m_clumpCount;}@@ -135,6 +141,7 @@ void SimpleObjectIterator::makeEmpty()m_firstClump = NULL;m_curClump = NULL;m_clumpCount = 0;+ m_inlineClumpsUsed = 0;}//=============================================================================diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cppindex aa3c4c033..11983c724 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp@@ -274,9 +274,9 @@ void GameLogic::setDefaults( Bool loadingSaveGame )#ifdef ALLOW_NONSLEEPY_UPDATESm_normalUpdates.clear();#endif- for (std::vector<UpdateModulePtr>::iterator it = m_sleepyUpdates.begin(); it != m_sleepyUpdates.end(); ++it)+ for (std::vector<SleepyEntry>::iterator it = m_sleepyUpdates.begin(); it != m_sleepyUpdates.end(); ++it){- (*it)->friend_setIndexInLogic(-1);+ it->module->friend_setIndexInLogic(-1);}m_sleepyUpdates.clear();m_curUpdateModule = NULL;@@ -2658,9 +2658,9 @@ void GameLogic::processDestroyList( void )UpdateModulePtr sleepyUpdatesForThisObject[MAX_SUO];Int numSUO = 0;- for (std::vector<UpdateModulePtr>::iterator it2 = m_sleepyUpdates.begin(); it2 != m_sleepyUpdates.end(); ++it2)+ for (std::vector<SleepyEntry>::iterator it2 = m_sleepyUpdates.begin(); it2 != m_sleepyUpdates.end(); ++it2){- UpdateModulePtr u = *it2;+ UpdateModulePtr u = it2->module;if (u->friend_getObject() == currentObject && numSUO < MAX_SUO){sleepyUpdatesForThisObject[numSUO++] = u;@@ -2671,7 +2671,7 @@ void GameLogic::processDestroyList( void ){// have to re-get idx each time since each call to erase might change others.Int idx = sleepyUpdatesForThisObject[numSUO]->friend_getIndexInLogic();- DEBUG_ASSERTCRASH(m_sleepyUpdates[idx] == sleepyUpdatesForThisObject[numSUO], ("Hmm, expected update mismatch here"));+ DEBUG_ASSERTCRASH(m_sleepyUpdates[idx].module == sleepyUpdatesForThisObject[numSUO], ("Hmm, expected update mismatch here"));eraseSleepyUpdate(idx);DEBUG_ASSERTCRASH(sleepyUpdatesForThisObject[numSUO]->friend_getIndexInLogic() == -1, ("Hmm, expected index to be -1 here"));}@@ -3020,28 +3020,29 @@ inline void GameLogic::validateSleepyUpdate() const//DEBUG_LOG(("\n\n"));//for (i = 0; i < sz; ++i)//{- // DEBUG_LOG(("u %04d: %08lx %08lx\n",i,m_sleepyUpdates[i],m_sleepyUpdates[i]->friend_getNextCallFrame()));+ // DEBUG_LOG(("u %04d: %08lx %08lx\n",i,m_sleepyUpdates[i].module,m_sleepyUpdates[i].module->friend_getNextCallFrame()));//}for (i = 0; i < sz; ++i){- DEBUG_ASSERTCRASH(m_sleepyUpdates[i]->friend_getIndexInLogic() == i, ("index mismatch: expected %d, got %d\n",i,m_sleepyUpdates[i]->friend_getIndexInLogic()));- UnsignedInt pri = m_sleepyUpdates[i]->friend_getPriority();+ DEBUG_ASSERTCRASH(m_sleepyUpdates[i].module->friend_getIndexInLogic() == i, ("index mismatch: expected %d, got %d\n",i,m_sleepyUpdates[i].module->friend_getIndexInLogic()));+ DEBUG_ASSERTCRASH(m_sleepyUpdates[i].priority == m_sleepyUpdates[i].module->friend_getPriority(), ("sleepy priority copy is stale at %d\n",i));+ UnsignedInt pri = m_sleepyUpdates[i].priority;if (i > 0){Int i0 = (i+1)/2-1;- UnsignedInt pri0 = m_sleepyUpdates[i0]->friend_getPriority();+ UnsignedInt pri0 = m_sleepyUpdates[i0].priority;DEBUG_ASSERTCRASH(pri >= pri0, ("sleepyUpdates are munged (0)"));}Int i1 = 2*(i+1)-1;Int i2 = 2*(i+1);if (i1 < sz){- UnsignedInt pri1 = m_sleepyUpdates[i1]->friend_getPriority();+ UnsignedInt pri1 = m_sleepyUpdates[i1].priority;DEBUG_ASSERTCRASH(pri <= pri1, ("sleepyUpdates are munged (1)"));}if (i2 < sz){- UnsignedInt pri2 = m_sleepyUpdates[i2]->friend_getPriority();+ UnsignedInt pri2 = m_sleepyUpdates[i2].priority;DEBUG_ASSERTCRASH(pri <= pri2, ("sleepyUpdates are munged (2)"));}}@@ -3056,13 +3057,13 @@ void GameLogic::eraseSleepyUpdate(Int i)DEBUG_ASSERTCRASH(i >= 0 && i < m_sleepyUpdates.size(), ("bad sleepy idx"));// swap with the final item, toss the final item, then rebalance- m_sleepyUpdates[i]->friend_setIndexInLogic(-1);+ m_sleepyUpdates[i].module->friend_setIndexInLogic(-1);Int final = m_sleepyUpdates.size() - 1;if (i < final){m_sleepyUpdates[i] = m_sleepyUpdates[final];- m_sleepyUpdates[i]->friend_setIndexInLogic(i);+ m_sleepyUpdates[i].module->friend_setIndexInLogic(i);m_sleepyUpdates.pop_back();rebalanceSleepyUpdate(i);}@@ -3073,15 +3074,12 @@ void GameLogic::eraseSleepyUpdate(Int i)}// -------------------------------------------------------------------------------------------------inline Bool isLowerPriority(const UpdateModulePtr a, const UpdateModulePtr b)+inline Bool isLowerPriority(const SleepyEntry& a, const SleepyEntry& b){// return true iff a is lower pri than b.// remember: lower ordinal value means higher priority.// therefore, higher ordinal value means lower priority.- DEBUG_ASSERTCRASH(a && b, ("these may no longer be null"));- UnsignedInt f1 = a->friend_getPriority();- UnsignedInt f2 = b->friend_getPriority();- return f1 > f2;+ return a.priority > b.priority;}// ------------------------------------------------------------------------------------------------@@ -3094,14 +3092,14 @@ Int GameLogic::rebalanceParentSleepyUpdate(Int i)Int parent = ((i+1)>>1)-1;while (parent >= 0 && isLowerPriority(m_sleepyUpdates[parent], m_sleepyUpdates[i])){- UpdateModulePtr a = m_sleepyUpdates[parent];- UpdateModulePtr b = m_sleepyUpdates[i];+ SleepyEntry a = m_sleepyUpdates[parent];+ SleepyEntry b = m_sleepyUpdates[i];m_sleepyUpdates[i] = a;m_sleepyUpdates[parent] = b;- a->friend_setIndexInLogic(i);- b->friend_setIndexInLogic(parent);+ a.module->friend_setIndexInLogic(i);+ b.module->friend_setIndexInLogic(parent);i = parent;parent = ((parent+1)>>1)-1;@@ -3122,15 +3120,15 @@ Int GameLogic::rebalanceChildSleepyUpdate(Int i)// max efficiency. I have left the pristine non-unrolled// version present for clarity. (Yes, this is worth doing.) (srj)#if 1- UpdateModulePtr* pI = &m_sleepyUpdates[i];+ SleepyEntry* pI = &m_sleepyUpdates[i];// our children are i*2 and i*2+1Int child = ((i+1)<<1)-1;// data() + n, not &m_sleepyUpdates[n]: both are only addresses until the loop below has checked// them against pSZ, and the same addresses in a release build, but a Debug build's checked// operator[] aborts on any n past the end, which child and size() often are (W3).- UpdateModulePtr* pChild = m_sleepyUpdates.data() + child;- UpdateModulePtr* pSZ = m_sleepyUpdates.data() + m_sleepyUpdates.size(); // yes, this is off the end.+ SleepyEntry* pChild = m_sleepyUpdates.data() + child;+ SleepyEntry* pSZ = m_sleepyUpdates.data() + m_sleepyUpdates.size(); // yes, this is off the end.while (pChild < pSZ){@@ -3148,14 +3146,14 @@ Int GameLogic::rebalanceChildSleepyUpdate(Int i)}// doh. swap with the highest-pri child we have.- UpdateModulePtr a = *pChild;- UpdateModulePtr b = *pI;+ SleepyEntry a = *pChild;+ SleepyEntry b = *pI;*pI = a;*pChild = b;- a->friend_setIndexInLogic(i);- b->friend_setIndexInLogic(child);+ a.module->friend_setIndexInLogic(i);+ b.module->friend_setIndexInLogic(child);i = child;pI = pChild;@@ -3180,14 +3178,14 @@ Int GameLogic::rebalanceChildSleepyUpdate(Int i)}// doh. swap with the highest-pri child we have.- UpdateModulePtr a = m_sleepyUpdates[child];- UpdateModulePtr b = m_sleepyUpdates[i];+ SleepyEntry a = m_sleepyUpdates[child];+ SleepyEntry b = m_sleepyUpdates[i];m_sleepyUpdates[i] = a;m_sleepyUpdates[child] = b;- a->friend_setIndexInLogic(i);- b->friend_setIndexInLogic(child);+ a.module->friend_setIndexInLogic(i);+ b.module->friend_setIndexInLogic(child);i = child;child = ((i+1)<<1)-1;}@@ -3228,9 +3226,10 @@ void GameLogic::pushSleepyUpdate(UpdateModulePtr u)DEBUG_ASSERTCRASH(u != NULL, ("You may not pass null for sleepy update info"));- m_sleepyUpdates.push_back(u);+ SleepyEntry e = { u->friend_getPriority(), u };+ m_sleepyUpdates.push_back(e);u->friend_setIndexInLogic(m_sleepyUpdates.size() - 1);-+rebalanceParentSleepyUpdate(m_sleepyUpdates.size()-1);}@@ -3239,7 +3238,7 @@ UpdateModulePtr GameLogic::peekSleepyUpdate() const{USE_PERF_TIMER(SleepyMaintenance)- UpdateModulePtr u = m_sleepyUpdates.front();+ UpdateModulePtr u = m_sleepyUpdates.front().module;DEBUG_ASSERTCRASH(u->friend_getIndexInLogic() == 0, ("index mismatch: expected %d, got %d\n",0,u->friend_getIndexInLogic()));return u;}@@ -3256,11 +3255,11 @@ void GameLogic::popSleepyUpdate()return;}- m_sleepyUpdates[0]->friend_setIndexInLogic(-1);+ m_sleepyUpdates[0].module->friend_setIndexInLogic(-1);if (sz > 1){m_sleepyUpdates[0] = m_sleepyUpdates[sz-1];- m_sleepyUpdates[0]->friend_setIndexInLogic(0);+ m_sleepyUpdates[0].module->friend_setIndexInLogic(0);m_sleepyUpdates.pop_back();rebalanceChildSleepyUpdate(0);}@@ -3308,7 +3307,7 @@ void GameLogic::friend_awakenUpdateModule(Object* obj, UpdateModulePtr u, Unsignreturn;}- if (m_sleepyUpdates[idx] != u)+ if (m_sleepyUpdates[idx].module != u){RELEASE_CRASH("fatal error! sleepy update module index mismatch.\n");return;@@ -3316,6 +3315,7 @@ void GameLogic::friend_awakenUpdateModule(Object* obj, UpdateModulePtr u, Unsign// update the value.u->friend_setNextCallFrame(whenToWakeUp);+ m_sleepyUpdates[idx].priority = u->friend_getPriority();// rebalance.rebalanceSleepyUpdate(idx);@@ -3879,9 +3879,14 @@ static Real logicElapsedMS( const Int64 &from, const Int64 &to )//// Which update module ate the frame. The `objects` figure in the slow-frame line is the whole// sleepy-update sweep, thousands of modules deep, and that alone never says which one. Two-// QueryPerformanceCounter reads per module cost about 0.2ms over a busy frame - they sit inside-// the `objects` window, so the sweep's own total carries that and the per-module figures do not.+// QueryPerformanceCounter reads and a kind lookup per module cost about 0.2ms over a busy frame, so+// they run on one logic frame in MODULE_PROFILE_EVERY and on every frame after a slow one: a fight+// that runs slow is slow for many frames in a row, and from its second frame on every one is timed.+// A lone spike on an untimed frame says so in its line.//+enum { MODULE_PROFILE_EVERY = 8 };+static Bool theModulesTimed = FALSE;+static Bool theLastLogicFrameSlow = FALSE;static Int64 theWorstModuleTicks = 0;static NameKeyType theWorstModuleKey = NAMEKEY_INVALID;static const ThingTemplate *theWorstModuleThing = NULL;@@ -3901,8 +3906,9 @@ static Int theModuleKindCount[ MODULE_PROFILE_MAX ];static Int theModuleKindQueries[ MODULE_PROFILE_MAX ];static Int theModuleKindsUsed = 0;-static void resetModuleProfile( void )+static void resetModuleProfile( UnsignedInt now ){+ theModulesTimed = theLastLogicFrameSlow || ( now % MODULE_PROFILE_EVERY ) == 0;theWorstModuleTicks = 0;theWorstModuleKey = NAMEKEY_INVALID;theWorstModuleThing = NULL;@@ -3945,7 +3951,7 @@ static const char *getModuleQueryReport( void )static char report[ 256 ];Bool taken[ MODULE_PROFILE_MAX ];- Int used = snprintf( report, ARRAY_SIZE(report), "queries by module:" );+ Int used = snprintf( report, ARRAY_SIZE(report), theModulesTimed ? "queries by module:" : "queries by module: not counted this frame" );if( used < 0 || used >= (Int)ARRAY_SIZE(report) )return report;@@ -3983,6 +3989,12 @@ static const char *getModuleProfileReport( void )Int64 freq = 0;freq = Clock_Ticks_Per_Second();+ if( !theModulesTimed )+ {+ snprintf( report, ARRAY_SIZE(report), "%d updates, modules not timed this frame", theModuleUpdateCount );+ return report;+ }+if( theWorstModuleKey == NAMEKEY_INVALID ){snprintf( report, ARRAY_SIZE(report), "%d updates", theModuleUpdateCount );@@ -4518,7 +4530,7 @@ void GameLogic::update( void )AI::resetEnemyScanCount();Pathfinder::resetProfile();#ifdef DEBUG_LOGGING- resetModuleProfile();+ resetModuleProfile( now );#endif// update (execute) scripts@@ -4687,22 +4699,30 @@ void GameLogic::update( void )m_curUpdateModule = u;#ifdef DEBUG_LOGGING- // read the identity before the update - a module may kill its own object- const NameKeyType profModuleKey = u->getModuleNameKey();- const ThingTemplate *profModuleThing = u->friend_getObject() ? u->friend_getObject()->getTemplate() : NULL;- const ObjectID profModuleObjID = u->friend_getObject() ? u->friend_getObject()->getID() : INVALID_ID;- const Int profModuleQueriesBefore = PartitionManager::getQueryCountThisFrame();- Int64 profModuleStart;- profModuleStart = Clock_Ticks();+ theModuleUpdateCount++;+ NameKeyType profModuleKey = NAMEKEY_INVALID;+ const ThingTemplate *profModuleThing = NULL;+ ObjectID profModuleObjID = INVALID_ID;+ Int profModuleQueriesBefore = 0;+ Int64 profModuleStart = 0;+ if( theModulesTimed )+ {+ // read the identity before the update - a module may kill its own object+ profModuleKey = u->getModuleNameKey();+ profModuleThing = u->friend_getObject() ? u->friend_getObject()->getTemplate() : NULL;+ profModuleObjID = u->friend_getObject() ? u->friend_getObject()->getID() : INVALID_ID;+ profModuleQueriesBefore = PartitionManager::getQueryCountThisFrame();+ profModuleStart = Clock_Ticks();+ }#endifsleepLen = u->update();#ifdef DEBUG_LOGGING+ if( theModulesTimed ){Int64 profModuleEnd;profModuleEnd = Clock_Ticks();- theModuleUpdateCount++;const Int64 profModuleTicks = profModuleEnd - profModuleStart;addModuleProfile( profModuleKey, profModuleTicks,PartitionManager::getQueryCountThisFrame() - profModuleQueriesBefore );@@ -4737,6 +4757,9 @@ void GameLogic::update( void )// else defer it till next frame and re-push itu->friend_setNextCallFrame(now + sleepLen);+ // u's own slot, which is not slot 0 when its update pushed or woke a module that sorts ahead+ // of it; the rebalance stays at 0 as it always was.+ m_sleepyUpdates[u->friend_getIndexInLogic()].priority = u->friend_getPriority();rebalanceSleepyUpdate(0);}}@@ -4820,6 +4843,9 @@ void GameLogic::update( void )// the logic gets 1/30th of a second, 33ms, per frame; -slowframe lowers the bar for a huntconst Real SLOW_FRAME_MS = TheGlobalData ? TheGlobalData->m_slowFrameMS : 20.0f;const Real total = logicElapsedMS( tFrameStart, tFrameEnd );+#ifdef DEBUG_LOGGING+ theLastLogicFrameSlow = total > SLOW_FRAME_MS;+#endifif( total > SLOW_FRAME_MS && now > 60 && getGameMode() != GAME_SHELL && getGameMode() != GAME_NONE ){const Real scripts = logicElapsedMS( tFrameStart, tScripts );@@ -6210,9 +6236,9 @@ void GameLogic::loadPostProcess( void )m_nextObjID = (ObjectID)((UnsignedInt)obj->getID() + 1);// blow away the sleepy update and normal update module lists- for (std::vector<UpdateModulePtr>::iterator it = m_sleepyUpdates.begin(); it != m_sleepyUpdates.end(); ++it)+ for (std::vector<SleepyEntry>::iterator it = m_sleepyUpdates.begin(); it != m_sleepyUpdates.end(); ++it){- (*it)->friend_setIndexInLogic(-1);+ it->module->friend_setIndexInLogic(-1);}m_sleepyUpdates.clear();#ifdef ALLOW_NONSLEEPY_UPDATES@@ -6256,7 +6282,8 @@ void GameLogic::loadPostProcess( void )u->friend_setNextCallFrame(now);#endif{- m_sleepyUpdates.push_back(u);+ SleepyEntry e = { u->friend_getPriority(), u };+ m_sleepyUpdates.push_back(e);u->friend_setIndexInLogic(m_sleepyUpdates.size() - 1);}diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/HeightMap.h b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/HeightMap.hindex cb298c91b..5216cf6ab 100644--- a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/HeightMap.h+++ b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/HeightMap.h@@ -111,8 +111,36 @@ protected:Int m_numBlockColumnsInLastVB;///<a VB tile may be partially filled, this indicates how many 2x2 vertex blocks are filled.Int m_numBlockRowsInLastVB;///<a VB tile may be partially filled, this indicates how many 2x2 vertex blocks are filled.-- UnsignedInt doTheDynamicLight(VERTEX_FORMAT *vb, VERTEX_FORMAT *vbMirror, Vector3*light, Vector3*normal, W3DDynamicLight *pLights[], Int numLights);+ /** What doTheDynamicLight reads from one light, taken once per relight instead of once per+ vertex. The relight reads these, the heights and m_vertexBufferBackup, and never the vertex+ buffer it writes, so a pass whose inputs match the last relight's would write the same bytes+ again. Lights change on logic frames and the terrain draws more often than that. */+ struct DynamicLightInputs+ {+ Int type;+ Int enabled;+ Vector3 position;+ Vector3 spotDirection;+ Vector3 diffuse;+ Vector3 ambient;+ double midRange; ///< double, the way Get_Far_Attenuation_Range hands it to the falloff+ double range;+ Int bounds[8]; ///< m_minX, m_minY, m_maxX, m_maxY, then the four m_prev bounds+ };+ struct DynamicLightPass+ {+ WorldHeightMap *map;+ Int drawOrgX;+ Int drawOrgY;+ Int originX;+ Int originY;+ Int numLights;+ DynamicLightInputs lights[MAX_ENABLED_DYNAMIC_LIGHTS];+ };+ DynamicLightPass m_lastRelight; ///< compared with memcmp, so only ever written by memset and memcpy+ Bool m_lastRelightValid; ///< false once anything has rewritten the vertex buffers since that relight++ UnsignedInt doTheDynamicLight(VERTEX_FORMAT *vb, VERTEX_FORMAT *vbMirror, Vector3*light, Vector3*normal, const DynamicLightInputs lights[], Int numLights);//// Gets the index that corresponds to the data. For example, if the columns are shifted by 3,// index 3 is actually the first row of polygons, or 0. Yes it is confusing, but it makesdiff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DParticleSys.h b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DParticleSys.hindex 6e872c938..d75393352 100644--- a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DParticleSys.h+++ b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DParticleSys.h@@ -51,6 +51,7 @@ public:W3DParticleSystemManager();~W3DParticleSystemManager();+ virtual void reset();virtual void doParticles(RenderInfoClass &rinfo);virtual void queueParticleRender();///< returns the number of particles shown on screen per framediff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HeightMap.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HeightMap.cppindex 50f8ec54c..5ffba22e4 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HeightMap.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HeightMap.cpp@@ -177,7 +177,7 @@ Int HeightMapRenderObjClass::freeMapResources(void)//=============================================================================/** Calculates the diffuse lighting as affected by dynamic lighting. *///=============================================================================-UnsignedInt HeightMapRenderObjClass::doTheDynamicLight(VERTEX_FORMAT *vb, VERTEX_FORMAT *vbMirror, Vector3*light, Vector3*normal, W3DDynamicLight *pLights[], Int numLights)+UnsignedInt HeightMapRenderObjClass::doTheDynamicLight(VERTEX_FORMAT *vb, VERTEX_FORMAT *vbMirror, Vector3*light, Vector3*normal, const DynamicLightInputs lights[], Int numLights){#ifdef USE_NORMALSreturn;@@ -197,19 +197,17 @@ UnsignedInt HeightMapRenderObjClass::doTheDynamicLight(VERTEX_FORMAT *vb, VERTEXInt alpha = (diffuse>>24)&0x00FF;Int k;for (k=0; k<numLights; k++) {- W3DDynamicLight *pLight = pLights[k];- if (!pLight->isEnabled()) {+ const DynamicLightInputs &dl = lights[k];+ if (!dl.enabled) {continue; // he is turned off.}Vector3 lightDirection(vbMirror->x, vbMirror->y, vbMirror->z);Real factor = 1.0f;- switch(pLight->Get_Type()) {+ switch(dl.type) {case LightClass::POINT:case LightClass::SPOT: {- Vector3 lightLoc = pLight->Get_Position();- lightDirection -= lightLoc;- double range, midRange;- pLight->Get_Far_Attenuation_Range(midRange, range);+ lightDirection -= dl.position;+ double range = dl.range, midRange = dl.midRange;Real dist = lightDirection.Length();if (dist >= range) continue;if (midRange < 0.1) continue;@@ -221,7 +219,7 @@ UnsignedInt HeightMapRenderObjClass::doTheDynamicLight(VERTEX_FORMAT *vb, VERTEX}break;case LightClass::DIRECTIONAL:- pLight->Get_Spot_Direction(lightDirection);+ lightDirection = dl.spotDirection;factor = 1.0;break;};@@ -232,10 +230,8 @@ UnsignedInt HeightMapRenderObjClass::doTheDynamicLight(VERTEX_FORMAT *vb, VERTEXVector3 lightRay(-lightDirection.X, -lightDirection.Y, -lightDirection.Z);Real shade = Vector3::Dot_Product(lightRay, *normal);shade *= factor;- Vector3 diffuse;- pLight->Get_Diffuse(&diffuse);- Vector3 ambient;- pLight->Get_Ambient(&ambient);+ const Vector3 &diffuse = dl.diffuse;+ const Vector3 &ambient = dl.ambient;if (shade > 1.0) shade = 1.0;if(shade < 0.0f) shade = 0.0f;shadeR += shade*diffuse.X;@@ -288,6 +284,7 @@ Int HeightMapRenderObjClass::updateVB(DX8VertexBufferClass *pVB, char *data, Int}REF_PTR_SET(m_map, pMap); //update our heightmap pointer in case it changed since last call.+ m_lastRelightValid = false; // the tile's diffuse goes back to static lighting, so the dynamic lights must be redoneif (m_vertexBufferTiles && pMap){#ifdef _DEBUG@@ -560,6 +557,7 @@ Int HeightMapRenderObjClass::updateVBForLight(DX8VertexBufferClass *pVB, char *dVERTEX_FORMAT *vBase = (VERTEX_FORMAT*)lockVtxBuffer.Get_Vertex_Array();// a failed lock - a device that has gone away - hands back nothing to lightif (vBase == NULL) {+ m_lastRelightValid = false; // nothing written, so the next pass tries againreturn 0;}VERTEX_FORMAT *vb;@@ -645,7 +643,7 @@ Int HeightMapRenderObjClass::updateVBForLight(DX8VertexBufferClass *pVB, char *dVector3::Normalized_Cross_Product(l2r, n2f, &normalAtTexel);#endif- doTheDynamicLight(vb, vbMirror, &lightRay, &normalAtTexel, pLights, numLights);+ doTheDynamicLight(vb, vbMirror, &lightRay, &normalAtTexel, m_lastRelight.lights, numLights);vb++; vbMirror++;//top-right sample@@ -658,7 +656,7 @@ Int HeightMapRenderObjClass::updateVBForLight(DX8VertexBufferClass *pVB, char *dVector3::Normalized_Cross_Product(l2r, n2f, &normalAtTexel);#endif- doTheDynamicLight(vb, vbMirror, &lightRay, &normalAtTexel, pLights, numLights);+ doTheDynamicLight(vb, vbMirror, &lightRay, &normalAtTexel, m_lastRelight.lights, numLights);vb++; vbMirror++;//bottom-right sample@@ -671,7 +669,7 @@ Int HeightMapRenderObjClass::updateVBForLight(DX8VertexBufferClass *pVB, char *dVector3::Normalized_Cross_Product(l2r, n2f, &normalAtTexel);#endif- doTheDynamicLight(vb, vbMirror, &lightRay, &normalAtTexel, pLights, numLights);+ doTheDynamicLight(vb, vbMirror, &lightRay, &normalAtTexel, m_lastRelight.lights, numLights);vb++; vbMirror++;//bottom-left sample@@ -684,7 +682,7 @@ Int HeightMapRenderObjClass::updateVBForLight(DX8VertexBufferClass *pVB, char *dVector3::Normalized_Cross_Product(l2r, n2f, &normalAtTexel);#endif- doTheDynamicLight(vb, vbMirror, &lightRay, &normalAtTexel, pLights, numLights);+ doTheDynamicLight(vb, vbMirror, &lightRay, &normalAtTexel, m_lastRelight.lights, numLights);vb++; vbMirror++;}}@@ -711,6 +709,7 @@ Int HeightMapRenderObjClass::updateVBForLightOptimized(DX8VertexBufferClass *pVBVERTEX_FORMAT *vBase = (VERTEX_FORMAT*)lockVtxBuffer.Get_Vertex_Array();// a failed lock - a device that has gone away - hands back nothing to lightif (vBase == NULL) {+ m_lastRelightValid = false; // nothing written, so the next pass tries againreturn 0;}VERTEX_FORMAT *vb;@@ -829,7 +828,7 @@ Int HeightMapRenderObjClass::updateVBForLightOptimized(DX8VertexBufferClass *pVBl2r.Set(2*MAP_XY_FACTOR,0,MAP_HEIGHT_SCALE*(m_map->getDisplayHeight(getXWithOrigin(i)+1, getYWithOrigin(j)) - m_map->getDisplayHeight(un0, getYWithOrigin(j))));n2f.Set(0,2*MAP_XY_FACTOR,MAP_HEIGHT_SCALE*(m_map->getDisplayHeight(getXWithOrigin(i), (getYWithOrigin(j)+1)) - m_map->getDisplayHeight(getXWithOrigin(i), vn0)));Vector3::Normalized_Cross_Product(l2r, n2f, &normalAtTexel);- doTheDynamicLight(vb, vbMirror, &lightRay, &normalAtTexel, pLights, numLights);+ doTheDynamicLight(vb, vbMirror, &lightRay, &normalAtTexel, m_lastRelight.lights, numLights);}vb++; vbMirror++;@@ -838,7 +837,7 @@ Int HeightMapRenderObjClass::updateVBForLightOptimized(DX8VertexBufferClass *pVBl2r.Set(2*MAP_XY_FACTOR,0,MAP_HEIGHT_SCALE*(m_map->getDisplayHeight(up1 , getYWithOrigin(j) ) - m_map->getDisplayHeight(getXWithOrigin(i) , getYWithOrigin(j) )));n2f.Set(0,2*MAP_XY_FACTOR,MAP_HEIGHT_SCALE*(m_map->getDisplayHeight(getXWithOrigin(i)+1 , (getYWithOrigin(j)+1) ) - m_map->getDisplayHeight(getXWithOrigin(i)+1 , vn0 )));Vector3::Normalized_Cross_Product(l2r, n2f, &normalAtTexel);- light_copy = doTheDynamicLight(vb, vbMirror, &lightRay, &normalAtTexel, pLights, numLights);+ light_copy = doTheDynamicLight(vb, vbMirror, &lightRay, &normalAtTexel, m_lastRelight.lights, numLights);if (i < x1-1) {// copy light to (right,0)@@ -851,7 +850,7 @@ Int HeightMapRenderObjClass::updateVBForLightOptimized(DX8VertexBufferClass *pVBl2r.Set(2*MAP_XY_FACTOR,0,MAP_HEIGHT_SCALE*(m_map->getDisplayHeight(up1 , (getYWithOrigin(j)+1) ) - m_map->getDisplayHeight(getXWithOrigin(i) , (getYWithOrigin(j)+1) )));n2f.Set(0,2*MAP_XY_FACTOR,MAP_HEIGHT_SCALE*(m_map->getDisplayHeight(getXWithOrigin(i)+1 , vp1 ) - m_map->getDisplayHeight(getXWithOrigin(i)+1 , getYWithOrigin(j) )));Vector3::Normalized_Cross_Product(l2r, n2f, &normalAtTexel);- light_copy = doTheDynamicLight(vb, vbMirror, &lightRay, &normalAtTexel, pLights, numLights);+ light_copy = doTheDynamicLight(vb, vbMirror, &lightRay, &normalAtTexel, m_lastRelight.lights, numLights);if (i < x1-1) {// copy light to (right,3)@@ -875,7 +874,7 @@ Int HeightMapRenderObjClass::updateVBForLightOptimized(DX8VertexBufferClass *pVBl2r.Set(2*MAP_XY_FACTOR,0,MAP_HEIGHT_SCALE*(m_map->getDisplayHeight(getXWithOrigin(i)+1 , (getYWithOrigin(j)+1) ) - m_map->getDisplayHeight(un0 , (getYWithOrigin(j)+1) )));n2f.Set(0,2*MAP_XY_FACTOR,MAP_HEIGHT_SCALE*(m_map->getDisplayHeight(getXWithOrigin(i) , vp1 ) - m_map->getDisplayHeight(getXWithOrigin(i) , getYWithOrigin(j) )));Vector3::Normalized_Cross_Product(l2r, n2f, &normalAtTexel);- light_copy = doTheDynamicLight(vb, vbMirror, &lightRay, &normalAtTexel, pLights, numLights);+ light_copy = doTheDynamicLight(vb, vbMirror, &lightRay, &normalAtTexel, m_lastRelight.lights, numLights);if (j < y1-1) {// copy light to (down,0)@@ -1081,7 +1080,8 @@ m_numVBTilesX(0),m_numVBTilesY(0),m_numVertexBufferTiles(0),m_numBlockColumnsInLastVB(0),-m_numBlockRowsInLastVB(0)+m_numBlockRowsInLastVB(0),+m_lastRelightValid(false){TheHeightMap = this;}@@ -1433,6 +1433,39 @@ void HeightMapRenderObjClass::On_Frame_Update(void)pLight->m_priorEnable = pLight->m_enabled;}if (numDynaLights > 0) {+ DynamicLightPass pass;+ memset((void *)&pass, 0, sizeof(pass));+ pass.map = m_map;+ pass.drawOrgX = m_map->getDrawOrgX();+ pass.drawOrgY = m_map->getDrawOrgY();+ pass.originX = m_originX;+ pass.originY = m_originY;+ pass.numLights = numDynaLights;+ for (k=0; k<numDynaLights; k++) {+ W3DDynamicLight *pLight = enabledLights[k];+ DynamicLightInputs &in = pass.lights[k];+ in.type = pLight->Get_Type();+ in.enabled = pLight->isEnabled();+ in.position = pLight->Get_Position();+ pLight->Get_Spot_Direction(in.spotDirection);+ pLight->Get_Diffuse(&in.diffuse);+ pLight->Get_Ambient(&in.ambient);+ pLight->Get_Far_Attenuation_Range(in.midRange, in.range);+ in.bounds[0] = pLight->m_minX; in.bounds[1] = pLight->m_minY;+ in.bounds[2] = pLight->m_maxX; in.bounds[3] = pLight->m_maxY;+ in.bounds[4] = pLight->m_prevMinX; in.bounds[5] = pLight->m_prevMinY;+ in.bounds[6] = pLight->m_prevMaxX; in.bounds[7] = pLight->m_prevMaxY;+ }+ // Same inputs as the last relight and no vertex buffer rewritten since: the tiles already+ // hold what this pass would write. Ground that moved and is waiting for its rebuild, or a+ // full rebuild pending, changes the normals first, so those passes relight as before.+ if (m_lastRelightValid && !m_hasDirtyRegion && !m_needFullUpdate &&+ memcmp(&pass, &m_lastRelight, sizeof(pass)) == 0) {+ return;+ }+ memcpy((void *)&m_lastRelight, &pass, sizeof(pass));+ m_lastRelightValid = true;+//step through each vertex buffer that needs updatingfor (j=0; j<m_numVBTilesY; j++){diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cppindex d594bf228..f722c1cd6 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cpp@@ -144,9 +144,23 @@ static void addSmokeLight( SmokeLight *lights, Int &count, const SmokeLight &liglights[ slot ] = light;}-/** One additive system as a point light, if it is bright enough and near enough the view box. */-static void gatherFireLight( ParticleSystem *sys, SmokeLight *lights, Int &count,- const AABoxClass &view )+/** An additive system's light before the view box has had its say. It depends on the particles+ * alone, and they only move when ParticleSystemManager::update runs, once a logic frame, so the+ * walk over them is kept for every pass drawn until the next one. */+struct FireLight+{+ SmokeLight light;+ Real reach; ///< the light's reach in any one axis, for the view box test+};++static std::vector<FireLight> s_fireLights; ///< in system list order, as the walk found them+static Bool s_fireLightsValid = FALSE;+static UnsignedInt s_fireLightsFrame; ///< the particle update they were taken after+static UnsignedInt s_fireLightsParticles;+static UnsignedInt s_fireLightsSystems;++/** One additive system as a point light, if it is bright enough. */+static void gatherFireLight( ParticleSystem *sys ){Real w = 0.0f, x = 0.0f, y = 0.0f, z = 0.0f, sq = 0.0f;for (Particle *p = sys->getFirstParticle(); p; p = p->m_systemNext)@@ -165,7 +179,8 @@ static void gatherFireLight( ParticleSystem *sys, SmokeLight *lights, Int &countif (w < FIRE_LIGHT_MIN_WEIGHT)return;- SmokeLight light;+ FireLight fire;+ SmokeLight &light = fire.light;const Real inv = 1.0f / w;light.x = x * inv;light.y = y * inv;@@ -177,10 +192,7 @@ static void gatherFireLight( ParticleSystem *sys, SmokeLight *lights, Int &countconst Real height = FIRE_LIGHT_HEIGHT;const Real reach = radius > height ? radius : height;- if (WWMath::Fabs( light.x - view.Center.X ) > view.Extent.X + reach- || WWMath::Fabs( light.y - view.Center.Y ) > view.Extent.Y + reach- || WWMath::Fabs( light.z - view.Center.Z ) > view.Extent.Z + reach)- return;+ fire.reach = reach;// fire's own colour, and the strength from how much of the flames there islight.strength = w < FIRE_LIGHT_FULL_WEIGHT ? w / FIRE_LIGHT_FULL_WEIGHT : 1.0f;@@ -193,7 +205,7 @@ static void gatherFireLight( ParticleSystem *sys, SmokeLight *lights, Int &countlight.invHeight = 1.0f / height;light.invBelow = 1.0f / (radius * FIRE_LIGHT_BELOW_SHARE);light.reachSq = reach * reach;- addSmokeLight( lights, count, light );+ s_fireLights.push_back( fire );}/** The scene's enabled light pulses, which FX lists put on explosions. */@@ -240,17 +252,20 @@ static void gatherPulseLights( SmokeLight *lights, Int &count, const AABoxClass}}-/** Fills lights[] with this frame's lights, strongest first, and returns how many. */+/** Fills lights[] with this frame's lights, strongest first, and returns how many. The fires are+ * offered in the order the systems walk found them, so the weakest-out list keeps the same ones. */static Int gatherSmokeLights( SmokeLight *lights, const AABoxClass &view ){Int count = 0;- ParticleSystemManager::ParticleSystemList &systems = TheParticleSystemManager->getAllParticleSystems();- for (ParticleSystemManager::ParticleSystemListIt it = systems.begin(); it != systems.end(); ++it)+ for (size_t i = 0; i < s_fireLights.size(); ++i){- ParticleSystem *sys = *it;- if (sys && !sys->isUsingDrawables() && sys->getShaderType() == ParticleSystemInfo::ADDITIVE- && sys->getParticleCount() > 0)- gatherFireLight( sys, lights, count, view );+ const FireLight &fire = s_fireLights[ i ];+ const SmokeLight &light = fire.light;+ if (WWMath::Fabs( light.x - view.Center.X ) > view.Extent.X + fire.reach+ || WWMath::Fabs( light.y - view.Center.Y ) > view.Extent.Y + fire.reach+ || WWMath::Fabs( light.z - view.Center.Z ) > view.Extent.Z + fire.reach)+ continue;+ addSmokeLight( lights, count, light );}gatherPulseLights( lights, count, view );@@ -472,6 +487,14 @@ W3DParticleSystemManager::~W3DParticleSystemManager()REF_PTR_RELEASE(m_angleBuffer);}+/** A reset can be followed by an update on the same logic frame, so the fires' frame alone would+ * not tell the lights taken before it from the ones after. */+void W3DParticleSystemManager::reset()+{+ ParticleSystemManager::reset();+ s_fireLightsValid = FALSE;+}+/*** Hack because DoParticles is called from Flush(), which is called* multiple times per frame. We only want to render once.@@ -586,7 +609,29 @@ void W3DParticleSystemManager::doParticles(RenderInfoClass &rinfo)fillJob.extentX = beX;fillJob.extentY = beY;fillJob.extentZ = beZ;- fillJob.lightCount = TheGlobalData->m_smokeFireLighting ? gatherSmokeLights( fillJob.lights, bbox ) : 0;+ fillJob.lightCount = 0;+ if (TheGlobalData->m_smokeFireLighting)+ {+ // Between two particle updates nothing moves a particle; a system made in between has none+ // yet, and the counts catch a load or anything else that adds or takes some away.+ if (!s_fireLightsValid || s_fireLightsFrame != m_lastLogicFrameUpdate+ || s_fireLightsParticles != m_particleCount || s_fireLightsSystems != m_particleSystemCount)+ {+ s_fireLights.clear();+ for( ParticleSystemManager::ParticleSystemListIt it = particleSysList.begin(); it != particleSysList.end(); ++it)+ {+ ParticleSystem *sys = *it;+ if (sys && !sys->isUsingDrawables() && sys->getShaderType() == ParticleSystemInfo::ADDITIVE+ && sys->getParticleCount() > 0)+ gatherFireLight( sys );+ }+ s_fireLightsValid = TRUE;+ s_fireLightsFrame = m_lastLogicFrameUpdate;+ s_fireLightsParticles = m_particleCount;+ s_fireLightsSystems = m_particleSystemCount;+ }+ fillJob.lightCount = gatherSmokeLights( fillJob.lights, bbox );+ }fillJob.glowAfterShade = Direct3D11_Present_Is_Enabled();JobSystem::parallel_for( (Int)m_billboardFills.size(), BILLBOARD_FILLS_PER_CLAIM, fillBillboards, &fillJob );size_t nextFill = 0;diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cppindex f20f4ff2a..5299849fe 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp@@ -1268,6 +1268,14 @@ void DX11BackendClass::Set_Transform(D3DTRANSFORMSTATETYPE state, const float mavoid DX11BackendClass::Set_Material(const float ambient[4], const float diffuse[4],const float specular[4], const float emissive[4], float power){+ // The wrapper reapplies the material on every mesh whether or not it changed.+ if (memcmp(MaterialAmbient, ambient, sizeof(MaterialAmbient)) == 0+ && memcmp(MaterialDiffuse, diffuse, sizeof(MaterialDiffuse)) == 0+ && memcmp(MaterialSpecular, specular, sizeof(MaterialSpecular)) == 0+ && memcmp(MaterialEmissive, emissive, sizeof(MaterialEmissive)) == 0+ && memcmp(&MaterialPower, &power, sizeof(MaterialPower)) == 0) {+ return;+ }memcpy(MaterialAmbient, ambient, sizeof(MaterialAmbient));memcpy(MaterialDiffuse, diffuse, sizeof(MaterialDiffuse));memcpy(MaterialSpecular, specular, sizeof(MaterialSpecular));@@ -1284,7 +1292,20 @@ void DX11BackendClass::Set_Light(unsigned index, DWORD type, const float positioreturn;}+ // Set_Light_Environment marks all four lights on every object it lights, so most of these+ // arrive unchanged. Only whether a light is on and its type reach the pipeline description.Light & light = Lights[index];+ const bool pipeline_changed = !light.Enabled || light.Type != type;+ if (!pipeline_changed+ && memcmp(light.Position, position, sizeof(light.Position)) == 0+ && memcmp(light.Direction, direction, sizeof(light.Direction)) == 0+ && memcmp(light.Diffuse, diffuse, sizeof(light.Diffuse)) == 0+ && memcmp(light.Specular, specular, sizeof(light.Specular)) == 0+ && memcmp(light.Attenuation, attenuation, sizeof(light.Attenuation)) == 0+ && memcmp(light.Spot, spot, sizeof(light.Spot)) == 0+ && memcmp(light.Ambient, ambient, sizeof(light.Ambient)) == 0) {+ return;+ }light.Enabled = true;light.Type = type;memcpy(light.Position, position, sizeof(light.Position));@@ -1295,7 +1316,9 @@ void DX11BackendClass::Set_Light(unsigned index, DWORD type, const float positiomemcpy(light.Spot, spot, sizeof(light.Spot));memcpy(light.Ambient, ambient, sizeof(light.Ambient));ConstantsChanged = true;- PipelineChanged = true;+ if (pipeline_changed) {+ PipelineChanged = true;+ }}void DX11BackendClass::Disable_Light(unsigned index)diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11texture.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11texture.cppindex 375537f32..5ede941cf 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11texture.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11texture.cpp@@ -134,6 +134,29 @@ static bool is_sixteen_bit_colour(D3DFORMAT format)return format == D3DFMT_A1R5G5B5 || format == D3DFMT_R5G6B5 || format == D3DFMT_A4R4G4B4;}+// Each channel width widened to eight bits as value * 255 / maximum, worked out once rather than a+// divide per channel per pixel.+struct ChannelScale+{+ unsigned char Four[16];+ unsigned char Five[32];+ unsigned char Six[64];++ ChannelScale()+ {+ for (unsigned value = 0; value < 16; ++value) {+ Four[value] = (unsigned char)(value * 255 / 15);+ }+ for (unsigned value = 0; value < 32; ++value) {+ Five[value] = (unsigned char)(value * 255 / 31);+ }+ for (unsigned value = 0; value < 64; ++value) {+ Six[value] = (unsigned char)(value * 255 / 63);+ }+ }+};+static const ChannelScale Scale;+static void expand_sixteen_bit(unsigned char * destination, unsigned destination_pitch,const unsigned char * source, unsigned source_pitch, unsigned width, unsigned height,D3DFORMAT format)@@ -141,32 +164,34 @@ static void expand_sixteen_bit(unsigned char * destination, unsigned destinationfor (unsigned row = 0; row < height; ++row) {const unsigned short * in = (const unsigned short *)(source + row * source_pitch);unsigned char * out = destination + row * destination_pitch;- for (unsigned column = 0; column < width; ++column) {- const unsigned short pixel = in[column];- unsigned blue = 0, green = 0, red = 0, alpha = 0xff;- switch (format) {- case D3DFMT_A1R5G5B5:- blue = ((pixel ) & 0x1f) * 255 / 31;- green = ((pixel >> 5) & 0x1f) * 255 / 31;- red = ((pixel >> 10) & 0x1f) * 255 / 31;- alpha = ((pixel >> 15) & 0x01) * 255;- break;- case D3DFMT_R5G6B5:- blue = ((pixel ) & 0x1f) * 255 / 31;- green = ((pixel >> 5) & 0x3f) * 255 / 63;- red = ((pixel >> 11) & 0x1f) * 255 / 31;- break;- default: // D3DFMT_A4R4G4B4- blue = ((pixel ) & 0x0f) * 255 / 15;- green = ((pixel >> 4) & 0x0f) * 255 / 15;- red = ((pixel >> 8) & 0x0f) * 255 / 15;- alpha = ((pixel >> 12) & 0x0f) * 255 / 15;- break;+ switch (format) {+ case D3DFMT_A1R5G5B5:+ for (unsigned column = 0; column < width; ++column, out += 4) {+ const unsigned pixel = in[column];+ out[0] = Scale.Five[pixel & 0x1f];+ out[1] = Scale.Five[(pixel >> 5) & 0x1f];+ out[2] = Scale.Five[(pixel >> 10) & 0x1f];+ out[3] = (unsigned char)((pixel >> 15) * 255);+ }+ break;+ case D3DFMT_R5G6B5:+ for (unsigned column = 0; column < width; ++column, out += 4) {+ const unsigned pixel = in[column];+ out[0] = Scale.Five[pixel & 0x1f];+ out[1] = Scale.Six[(pixel >> 5) & 0x3f];+ out[2] = Scale.Five[pixel >> 11];+ out[3] = 0xff;+ }+ break;+ default: // D3DFMT_A4R4G4B4+ for (unsigned column = 0; column < width; ++column, out += 4) {+ const unsigned pixel = in[column];+ out[0] = Scale.Four[pixel & 0x0f];+ out[1] = Scale.Four[(pixel >> 4) & 0x0f];+ out[2] = Scale.Four[(pixel >> 8) & 0x0f];+ out[3] = Scale.Four[pixel >> 12];}- out[column * 4 + 0] = (unsigned char)blue;- out[column * 4 + 1] = (unsigned char)green;- out[column * 4 + 2] = (unsigned char)red;- out[column * 4 + 3] = (unsigned char)alpha;+ break;}}}diff --git a/GeneralsMD/Code/Tests/test_dx11texture.cpp b/GeneralsMD/Code/Tests/test_dx11texture.cppindex f3b98b7cf..9c164189a 100644--- a/GeneralsMD/Code/Tests/test_dx11texture.cpp+++ b/GeneralsMD/Code/Tests/test_dx11texture.cpp@@ -396,3 +396,89 @@ TEST(dx11texture_a_repeated_sixteen_bit_copy_carries_only_what_changed)source->Release();texture->Release();}++// The sixty-four pixels of an eight by eight texture, between them holding every value of every+// channel of the format.+static unsigned short every_channel_value(D3DFORMAT format, unsigned index)+{+ switch (format) {+ case D3DFMT_A1R5G5B5:+ return (unsigned short)((index >> 5) << 15 | ((index * 3) & 0x1f) << 10+ | ((index + 7) & 0x1f) << 5 | (index & 0x1f));+ case D3DFMT_R5G6B5:+ return (unsigned short)(((index * 3) & 0x1f) << 11 | index << 5 | ((index + 7) & 0x1f));+ default:+ return (unsigned short)(((index * 5) & 0xf) << 12 | ((index * 3) & 0xf) << 8+ | ((index + 7) & 0xf) << 4 | (index & 0xf));+ }+}++// The widening as it was written before it became lookup tables: a divide per channel.+static void widen_by_divide(D3DFORMAT format, unsigned pixel, unsigned char out[4])+{+ switch (format) {+ case D3DFMT_A1R5G5B5:+ out[0] = (unsigned char)((pixel & 0x1f) * 255 / 31);+ out[1] = (unsigned char)(((pixel >> 5) & 0x1f) * 255 / 31);+ out[2] = (unsigned char)(((pixel >> 10) & 0x1f) * 255 / 31);+ out[3] = (unsigned char)(((pixel >> 15) & 0x01) * 255);+ break;+ case D3DFMT_R5G6B5:+ out[0] = (unsigned char)((pixel & 0x1f) * 255 / 31);+ out[1] = (unsigned char)(((pixel >> 5) & 0x3f) * 255 / 63);+ out[2] = (unsigned char)(((pixel >> 11) & 0x1f) * 255 / 31);+ out[3] = 0xff;+ break;+ default:+ out[0] = (unsigned char)((pixel & 0x0f) * 255 / 15);+ out[1] = (unsigned char)(((pixel >> 4) & 0x0f) * 255 / 15);+ out[2] = (unsigned char)(((pixel >> 8) & 0x0f) * 255 / 15);+ out[3] = (unsigned char)(((pixel >> 12) & 0x0f) * 255 / 15);+ break;+ }+}++TEST(dx11texture_sixteen_bit_formats_widen_as_the_divide_did)+{+ Direct3D9Fixture d3d9;+ if (!d3d9.Create()) {+ printf("skip: no Direct3D 9 device on this machine\n");+ return;+ }++ DX11DeviceClass d3d11;+ CHECK(d3d11.Create_Offscreen());++ const D3DFORMAT formats[] = { D3DFMT_A1R5G5B5, D3DFMT_R5G6B5, D3DFMT_A4R4G4B4 };+ for (unsigned f = 0; f < sizeof(formats) / sizeof(formats[0]); ++f) {+ IDirect3DTexture9 * texture = NULL;+ if (FAILED(d3d9.Get()->CreateTexture(TEXTURE_SIZE, TEXTURE_SIZE, ONE_LEVEL, 0, formats[f],+ D3DPOOL_MANAGED, &texture, NULL))) {+ printf("skip: no managed texture in format %u on this machine\n", (unsigned)formats[f]);+ continue;+ }++ D3DLOCKED_RECT locked;+ CHECK(SUCCEEDED(texture->LockRect(0, &locked, NULL, 0)));+ for (unsigned row = 0; row < TEXTURE_SIZE; ++row) {+ unsigned short * out = (unsigned short *)((unsigned char *)locked.pBits + row * locked.Pitch);+ for (unsigned column = 0; column < TEXTURE_SIZE; ++column) {+ out[column] = every_channel_value(formats[f], row * TEXTURE_SIZE + column);+ }+ }+ texture->UnlockRect(0);++ ID3D11ShaderResourceView * view =+ DX11Texture_Mirror(d3d11.Get_Device(), d3d11.Get_Context(), texture);+ CHECK(view != NULL);+ unsigned char pixels[TEXTURE_SIZE * TEXTURE_SIZE * 4];+ CHECK(read_back(d3d11, view, pixels, TEXTURE_SIZE * 4));+ for (unsigned index = 0; index < TEXTURE_SIZE * TEXTURE_SIZE; ++index) {+ unsigned char expected[4];+ widen_by_divide(formats[f], every_channel_value(formats[f], index), expected);+ CHECK_MEM(pixels + index * 4, expected, 4);+ }++ texture->Release();+ }+}diff --git a/tree-check.ps1 b/tree-check.ps1index 7a3f8ce90..d4d545469 100644--- a/tree-check.ps1+++ b/tree-check.ps1@@ -20,7 +20,7 @@# the run-to-run shimmer does not. Re-measure and move them if the reference machine changes.## Exit code is the number of views over the limit.-param([double]$Limit = 0, [string[]]$Extra = @(), [string[]]$NewEnv = @())+param([double]$Limit = 0, [string[]]$Extra = @(), [string[]]$NewEnv = @(), [string]$Base = 'generals_base.exe')$env:ZH_UNATTENDED = "1" # every game this starts is unattended: no box may wait on a person (EarlyCommandLine.h)Add-Type -AssemblyName System.Drawing@@ -36,10 +36,10 @@ if (-not (Test-Path $tmp)) { $null = New-Item -ItemType Directory $tmp }# -turbo cuts a view from about 90 seconds to about 25, but the cloud shadows scroll on the wall# clock, so a turbo shot and a paced one of the same frame differ on 7% of the pixels. Both builds# have to run the same way: turbo when the reference build knows the switch, paced when it does not.-$baseExe = Join-Path $run 'generals_base.exe'+$baseExe = Join-Path $run $Base$pace = @()if (Select-String -Path $baseExe -Pattern '-turbo' -SimpleMatch -Quiet) { $pace = @('-turbo') }-else { "generals_base.exe predates -turbo: both builds run paced, about 90 seconds a view" }+else { "$Base predates -turbo: both builds run paced, about 90 seconds a view" }$cases = @(@{map='Flash Effect'; x='1200'; y='945'; f=400; lim=1.6}, # noise 0.77@@ -113,7 +113,7 @@ function DiffPct($a, $b) {$fail = 0foreach ($c in $cases) {$tag = ($c.map -replace '[^A-Za-z]','') + "_$($c.x)_$($c.f)"- $a = Shoot 'generals_base.exe' $c "base_$tag"+ $a = Shoot $Base $c "base_$tag"$b = Shoot 'generals.exe' $c "new_$tag"$d = DiffPct $a $b$lim = if ($Limit -gt 0) { $Limit } else { $c.lim }