[ui] hold a strong reference to fragment program objects. (flutter/engine#49868)

The native engine needs to hold a strong reference to fragment programs. So the dart side holding a weak ref is more or less pointless
This commit is contained in:
Jonah Williams
2024-01-23 16:08:24 -08:00
committed by GitHub
parent db041900f3
commit 6f0249a062
2 changed files with 21 additions and 14 deletions

View File

@@ -4465,35 +4465,31 @@ base class FragmentProgram extends NativeFieldWrapperClass1 {
// the same encoding here so that users can load assets with the same
// key they have written in the pubspec.
final String encodedKey = Uri(path: Uri.encodeFull(assetKey)).path;
final FragmentProgram? program = _shaderRegistry[encodedKey]?.target;
final FragmentProgram? program = _shaderRegistry[encodedKey];
if (program != null) {
return Future<FragmentProgram>.value(program);
}
return Future<FragmentProgram>.microtask(() {
final FragmentProgram program = FragmentProgram._fromAsset(encodedKey);
_shaderRegistry[encodedKey] = WeakReference<FragmentProgram>(program);
_shaderRegistry[encodedKey] = program;
return program;
});
}
// This is a cache of shaders that have been loaded by
// FragmentProgram.fromAsset. It holds weak references to the FragmentPrograms
// so that the case where an in-use program is requested again can be fast,
// but programs that are no longer referenced are not retained because of the
// cache.
static final Map<String, WeakReference<FragmentProgram>> _shaderRegistry =
<String, WeakReference<FragmentProgram>>{};
// FragmentProgram.fromAsset. It holds a strong reference to theFragmentPrograms
// The native engine will retain the resources associated with this shader
// program (PSO variants) until shutdown, so maintaining a strong reference
// here ensures we do not perform extra work if the dart object is continually
// re-initialized.
static final Map<String, FragmentProgram> _shaderRegistry =
<String, FragmentProgram>{};
static void _reinitializeShader(String assetKey) {
// If a shader for the asset isn't already registered, then there's no
// need to reinitialize it. The new shader will be loaded and initialized
// the next time the program access it.
final WeakReference<FragmentProgram>? programRef = _shaderRegistry[assetKey];
if (programRef == null) {
return;
}
final FragmentProgram? program = programRef.target;
final FragmentProgram? program = _shaderRegistry[assetKey];
if (program == null) {
return;
}

View File

@@ -50,6 +50,17 @@ void main() async {
return;
}
test('FragmentProgram objects are cached.', () async {
final FragmentProgram programA = await FragmentProgram.fromAsset(
'blue_green_sampler.frag.iplr',
);
final FragmentProgram programB = await FragmentProgram.fromAsset(
'blue_green_sampler.frag.iplr',
);
expect(identical(programA, programB), true);
});
test('FragmentShader setSampler throws with out-of-bounds index', () async {
final FragmentProgram program = await FragmentProgram.fromAsset(
'blue_green_sampler.frag.iplr',