Mass Effect 的 3D 場景黑塊問題一路追到 Intel/AMD 的 SSE2 指令集...

Mass Effect 是個 2007 在 Xbox 上推出的遊戲,並且在 2008 推出 Windows 版,這個遊戲在 2011 年 AMD 推出的 CPU 上 (Bulldozer),某些場景會產生人物黑塊的 bug,社群有些猜測但一直都沒被證實,作者一路追出不少問題,並且給了一個還算乾淨的 workaround:「Fixing Mass Effect black blobs on modern AMD CPUs」,另外在 Hacker News 上有很精彩的討論:「Fixing Mass Effect black blobs on modern AMD CPUs (cookieplmonster.github.io)」。

這篇主要是看趣味的,裡面的狀況有點複雜。

社群有一些 workaround 可以避開這個問題,作者後來是從關閉 PSGP (Processor Specific Graphics Pipeline) 的方法找問題,然後發現在計算時會產生出 NaN 的問題,所以導致貼出來的圖就變成黑塊了...

一路追下去,發現遊戲本身好像沒什麼大問題,但跟 Direct3D 裡面的 D3DXMatrixInverse 有關,會依照 CPU 的支援度決定怎麼跑:

  • Disabling PSGP makes both Intel and AMD take a regular x86 code path.
  • Intel CPUs always take an intelsse2 code path.
  • AMD CPUs supporting 3DNow! take a amd_mmx_3dnow or amd3dnow_amdmmx code path, while CPUs without 3DNow take an intelsse2 code path.

會有這些邏輯是因為 AMD 在 2010 後決定放生 3DNow!,所以會需要這樣判斷。

接著寫了一隻小程式測試,用 memcmp() 判斷是不是一樣,結果發現 AMD 的 SSE2 跑出來的程式不被遊戲接受:(不一樣是正常的,因為這些指令本來就沒有要求完全正確,是可以接受誤差的)

接著就是翻資料,可以知道 XMMatrixInverse 算是接班人:

I figured that since we were to replace that matrix function anyway, I could try replacing it with XMMatrixInverse being a “modern” replacement for D3DXMatrixInverse. XMMatrixInverse also uses SSE2 instructions so it should be equally optimal to the D3DX function, but I was nearly sure it would break the same way.

所以就弄個一個 DLL,把本來呼叫 D3DXMatrixInverse 的部份用 XMMatrixInverse 改寫換掉:「SilentPatchME/source/D3DXMatrix.cpp」,這個方式算是乾淨的 workaround 掉,保持 API 相容性,以及該有的加速能力 (由 XMMatrixInverse 提供)。

Hacker News 上有討論到 Intel 與 AMD 這些指令在 SSE2 上的誤差值,都是在規格要求的範圍內:

Const-me 14 hours ago [–]

Here’s Intel versus AMD relative error of RCPPS instruction: http://const.me/tmp/vrcpps-errors-chart.png AMD is Ryzen 5 3600, Intel is Core i3 6157U.
Over the complete range of floats, AMD is more precise on average, 0.000078 versus 0.000095 relative error. However, Intel has 0.000300 maximum relative error, AMD 0.000315.

Both are well within the spec. The documentation says “maximum relative error for this approximation is less than 1.5*2^-12”, in human language that would be 3.6621E-4.

Source code that compares them by creating 16GB binary files with the complete range of floats: https://gist.github.com/Const-me/a6d36f70a3a77de00c61cf4f6c17c7ac

至於為什麼會生出 NaN 的原因,沒找出來還是有點可惜,不過這個解法還行,就是「新版的 library 既然沒問題,就大家也不要太計較舊版的問題」的概念...