Skip to content

Commit c2d4958

Browse files
arosolinoviniciusjarina
authored andcommitted
Improved shader cache hash key to not cause collisions (MonoGame#8557)
Fix for the following issue MonoGame#8555 I made the key used for the shader program cache use a value tuple so it can avoid potential hash key collisions. Also made use of `TryGetValue` so it only has to check the key in the dictionary once.
1 parent e12ad11 commit c2d4958

File tree

1 file changed

+8
-6
lines changed

1 file changed

+8
-6
lines changed

MonoGame.Framework/Platform/Graphics/Shader/ShaderProgramCache.cs

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ public int GetUniformLocation(string name)
3737
/// </summary>
3838
internal class ShaderProgramCache : IDisposable
3939
{
40-
private readonly Dictionary<int, ShaderProgram> _programCache = new Dictionary<int, ShaderProgram>();
40+
private readonly Dictionary<ulong, ShaderProgram> _programCache = new Dictionary<ulong, ShaderProgram>();
4141
GraphicsDevice _graphicsDevice;
4242
bool disposed;
4343

@@ -69,14 +69,16 @@ public ShaderProgram GetProgram(Shader vertexShader, Shader pixelShader)
6969
// buffers here as well. This would allow us to optimize
7070
// setting uniforms to only when a constant buffer changes.
7171

72-
var key = vertexShader.HashKey | pixelShader.HashKey;
73-
if (!_programCache.ContainsKey(key))
72+
var key = ((ulong)(uint)vertexShader.HashKey << 32) | (uint)pixelShader.HashKey;
73+
74+
if(!_programCache.TryGetValue(key, out var shaderProgram))
7475
{
7576
// the key does not exist so we need to link the programs
76-
_programCache.Add(key, Link(vertexShader, pixelShader));
77+
shaderProgram = Link(vertexShader, pixelShader);
78+
_programCache.Add(key, shaderProgram);
7779
}
7880

79-
return _programCache[key];
81+
return shaderProgram;
8082
}
8183

8284
private ShaderProgram Link(Shader vertexShader, Shader pixelShader)
@@ -141,4 +143,4 @@ protected virtual void Dispose(bool disposing)
141143
}
142144
}
143145

144-
#endif // OPENGL
146+
#endif // OPENGL

0 commit comments

Comments
 (0)