godot icon indicating copy to clipboard operation
godot copied to clipboard

Let materials' shaders update happen on loader threads

Open RandomShaper opened this issue 1 year ago • 0 comments

Most important material types feature a dirty list that is processed every frame so those materials generate their internal shader. In the case of ShaderMaterial, its _shader_changed() function is also invoked (if running the editor). During threaded loading, there are some mechanics in place so such those operations don't happen until the load is known to have finished. They eventually happen on the main thread.

The problem in #90565 has to do with that. The resource previewer runs on a thread, from where it loads a material whose preview it wants to generate. Unfortunately, by the time the main thread would have had the chance to run the internal update, the shader is already gone (no error is printed about this). Also, the deferred call to _shader_changed() is attempted there on the already freed shader, which causes the error message.

A possible solution would have been to add some API so the resource previewer can somehow force the flush of the loader thread call queue right there instad of being transferred to the main one. However, after some analysis, I think we can just make those update operations happen on the loader thread organically (with added benefits). My only concern is that there might be some resource types that have a similar mechanism of deferred update in a way that they don't support such a thing happening on the loader thread. I can't think of any, but it's important to bear that in mind. If this is considered too risky for 4.3, I may provide a compromise fix for it and reschedule this PR for 4.4.

Finally, as a bonus, a little cleanup is made in terms of init-term, to make it more consistent across material types.

Fixes #90565.

RandomShaper avatar May 06 '24 18:05 RandomShaper