[flutter_tools] add tool support for shader hot reload (#107963)

This commit is contained in:
Jonah Williams
2022-07-26 20:31:06 -07:00
committed by GitHub
parent 0b27bd307b
commit 7e683c023a
26 changed files with 624 additions and 37 deletions

View File

@@ -15,6 +15,7 @@ import '../exceptions.dart';
import 'assets.dart';
import 'common.dart';
import 'icon_tree_shaker.dart';
import 'shader_compiler.dart';
/// Prepares the asset bundle in the format expected by flutter.gradle.
///
@@ -66,6 +67,7 @@ abstract class AndroidAssetBundle extends Target {
outputDirectory,
targetPlatform: TargetPlatform.android,
buildMode: buildMode,
shaderTarget: ShaderTarget.sksl,
);
final DepfileService depfileService = DepfileService(
fileSystem: environment.fileSystem,

View File

@@ -31,6 +31,7 @@ Future<Depfile> copyAssets(
Map<String, DevFSContent>? additionalContent,
required TargetPlatform targetPlatform,
BuildMode? buildMode,
required ShaderTarget shaderTarget,
}) async {
// Check for an SkSL bundle.
final String? shaderBundlePath = environment.defines[kBundleSkSLPath] ?? environment.inputs[kBundleSkSLPath];
@@ -124,6 +125,7 @@ Future<Depfile> copyAssets(
doCopy = !await shaderCompiler.compileShader(
input: content.file as File,
outputPath: file.path,
target: shaderTarget,
);
break;
}
@@ -306,6 +308,7 @@ class CopyAssets extends Target {
environment,
output,
targetPlatform: TargetPlatform.android,
shaderTarget: ShaderTarget.sksl,
);
final DepfileService depfileService = DepfileService(
fileSystem: environment.fileSystem,

View File

@@ -74,6 +74,7 @@ class CopyFlutterBundle extends Target {
environment.outputDir,
targetPlatform: TargetPlatform.android,
buildMode: buildMode,
shaderTarget: ShaderTarget.sksl,
);
final DepfileService depfileService = DepfileService(
fileSystem: environment.fileSystem,

View File

@@ -493,6 +493,7 @@ abstract class IosAssetBundle extends Target {
environment,
assetDirectory,
targetPlatform: TargetPlatform.ios,
shaderTarget: ShaderTarget.sksl,
);
final DepfileService depfileService = DepfileService(
fileSystem: environment.fileSystem,

View File

@@ -15,6 +15,7 @@ import 'assets.dart';
import 'common.dart';
import 'desktop.dart';
import 'icon_tree_shaker.dart';
import 'shader_compiler.dart';
/// The only files/subdirectories we care out.
const List<String> _kLinuxArtifacts = <String>[
@@ -143,7 +144,8 @@ abstract class BundleLinuxAssets extends Target {
targetPlatform: targetPlatform,
additionalContent: <String, DevFSContent>{
'version.json': DevFSStringContent(versionInfo),
}
},
shaderTarget: ShaderTarget.sksl,
);
final DepfileService depfileService = DepfileService(
fileSystem: environment.fileSystem,

View File

@@ -15,6 +15,7 @@ import '../exceptions.dart';
import 'assets.dart';
import 'common.dart';
import 'icon_tree_shaker.dart';
import 'shader_compiler.dart';
/// Copy the macOS framework to the correct copy dir by invoking 'rsync'.
///
@@ -390,6 +391,7 @@ abstract class MacOSBundleFlutterAssets extends Target {
environment,
assetDirectory,
targetPlatform: TargetPlatform.darwin,
shaderTarget: ShaderTarget.sksl,
);
final DepfileService depfileService = DepfileService(
fileSystem: environment.fileSystem,

View File

@@ -2,6 +2,11 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math' as math;
import 'dart:typed_data';
import 'package:meta/meta.dart';
import 'package:pool/pool.dart';
import 'package:process/process.dart';
import '../../artifacts.dart';
@@ -9,9 +14,110 @@ import '../../base/error_handling_io.dart';
import '../../base/file_system.dart';
import '../../base/io.dart';
import '../../base/logger.dart';
import '../../build_info.dart';
import '../../convert.dart';
import '../../devfs.dart';
import '../build_system.dart';
/// The output shader format that should be used by the [ShaderCompiler].
enum ShaderTarget {
impellerAndroid('--opengl-es'),
impelleriOS('--metal-ios'),
sksl('--sksl');
const ShaderTarget(this.target);
final String target;
}
/// A wrapper around [ShaderCompiler] to support hot reload of shader sources.
class DevelopmentShaderCompiler {
DevelopmentShaderCompiler({
required ShaderCompiler shaderCompiler,
required FileSystem fileSystem,
@visibleForTesting math.Random? random,
}) : _shaderCompiler = shaderCompiler,
_fileSystem = fileSystem,
_random = random ?? math.Random();
final ShaderCompiler _shaderCompiler;
final FileSystem _fileSystem;
final Pool _compilationPool = Pool(4);
final math.Random _random;
late ShaderTarget _shaderTarget;
bool _debugConfigured = false;
/// Configure the output format of the shader compiler for a particular
/// flutter device.
void configureCompiler(TargetPlatform? platform, { required bool enableImpeller }) {
switch (platform) {
case TargetPlatform.ios:
_shaderTarget = enableImpeller ? ShaderTarget.impelleriOS : ShaderTarget.sksl;
break;
case TargetPlatform.android_arm64:
case TargetPlatform.android_x64:
case TargetPlatform.android_x86:
case TargetPlatform.android_arm:
case TargetPlatform.android:
_shaderTarget = enableImpeller ? ShaderTarget.impellerAndroid : ShaderTarget.sksl;
break;
case TargetPlatform.darwin:
case TargetPlatform.linux_x64:
case TargetPlatform.linux_arm64:
case TargetPlatform.windows_x64:
case TargetPlatform.fuchsia_arm64:
case TargetPlatform.fuchsia_x64:
case TargetPlatform.tester:
case TargetPlatform.web_javascript:
assert(!enableImpeller);
_shaderTarget = ShaderTarget.sksl;
break;
case null:
return;
}
_debugConfigured = true;
}
/// Recompile the input shader and return a devfs content that should be synced
/// to the attached device in its place.
Future<DevFSContent?> recompileShader(DevFSContent inputShader) async {
assert(_debugConfigured);
final File output = _fileSystem.systemTempDirectory.childFile('${_random.nextDouble()}.temp');
late File inputFile;
bool cleanupInput = false;
Uint8List result;
PoolResource? resource;
try {
resource = await _compilationPool.request();
if (inputShader is DevFSFileContent) {
inputFile = inputShader.file as File;
} else {
inputFile = _fileSystem.systemTempDirectory.childFile('${_random.nextDouble()}.temp');
inputFile.writeAsBytesSync(await inputShader.contentsAsBytes());
cleanupInput = true;
}
final bool success = await _shaderCompiler.compileShader(
input: inputFile,
outputPath: output.path,
target: _shaderTarget,
fatal: false,
);
if (!success) {
return null;
}
result = output.readAsBytesSync();
} finally {
resource?.release();
ErrorHandlingFileSystem.deleteIfExists(output);
if (cleanupInput) {
ErrorHandlingFileSystem.deleteIfExists(inputFile);
}
}
return DevFSByteContent(result);
}
}
/// A class the wraps the functionality of the Impeller shader compiler
/// impellerc.
class ShaderCompiler {
@@ -49,6 +155,8 @@ class ShaderCompiler {
Future<bool> compileShader({
required File input,
required String outputPath,
required ShaderTarget target,
bool fatal = true,
}) async {
final File impellerc = _fs.file(
_artifacts.getHostArtifact(HostArtifact.impellerc),
@@ -62,10 +170,7 @@ class ShaderCompiler {
final List<String> cmd = <String>[
impellerc.path,
// TODO(zanderso): When impeller is enabled, the correct flags for the
// target backend will need to be passed.
// https://github.com/flutter/flutter/issues/102853
'--sksl',
target.target,
'--iplr',
'--sl=$outputPath',
'--spirv=$outputPath.spirv',
@@ -78,12 +183,14 @@ class ShaderCompiler {
if (code != 0) {
_logger.printTrace(await utf8.decodeStream(impellercProcess.stdout));
_logger.printError(await utf8.decodeStream(impellercProcess.stderr));
throw ShaderCompilerException._(
'Shader compilation of "${input.path}" to "$outputPath" '
'failed with exit code $code.',
);
if (fatal) {
throw ShaderCompilerException._(
'Shader compilation of "${input.path}" to "$outputPath" '
'failed with exit code $code.',
);
}
return false;
}
ErrorHandlingFileSystem.deleteIfExists(_fs.file('$outputPath.spirv'));
return true;
}

View File

@@ -26,6 +26,7 @@ import '../depfile.dart';
import '../exceptions.dart';
import 'assets.dart';
import 'localizations.dart';
import 'shader_compiler.dart';
/// Whether the application has web plugins.
const String kHasWebPlugins = 'HasWebPlugins';
@@ -306,6 +307,7 @@ class WebReleaseBundle extends Target {
environment,
environment.outputDir.childDirectory('assets'),
targetPlatform: TargetPlatform.web_javascript,
shaderTarget: ShaderTarget.sksl,
);
final DepfileService depfileService = DepfileService(
fileSystem: globals.fs,

View File

@@ -12,6 +12,7 @@ import 'assets.dart';
import 'common.dart';
import 'desktop.dart';
import 'icon_tree_shaker.dart';
import 'shader_compiler.dart';
/// The only files/subdirectories we care about.
const List<String> _kWindowsArtifacts = <String>[
@@ -142,6 +143,7 @@ abstract class BundleWindowsAssets extends Target {
environment,
outputDirectory,
targetPlatform: TargetPlatform.windows_x64,
shaderTarget: ShaderTarget.sksl,
);
final DepfileService depfileService = DepfileService(
fileSystem: environment.fileSystem,

View File

@@ -184,6 +184,7 @@ Future<void> writeBundle(
doCopy = !await shaderCompiler.compileShader(
input: input,
outputPath: file.path,
target: ShaderTarget.sksl, // TODO(zanderso): configure impeller target when enabled.
);
break;
}

View File

@@ -15,6 +15,7 @@ import 'base/logger.dart';
import 'base/net.dart';
import 'base/os.dart';
import 'build_info.dart';
import 'build_system/targets/shader_compiler.dart';
import 'compile.dart';
import 'convert.dart' show base64, utf8;
import 'vmservice.dart';
@@ -479,6 +480,7 @@ class DevFS {
final String fsName;
final Directory? rootDirectory;
final Set<String> assetPathsToEvict = <String>{};
final Set<String> shaderPathsToEvict = <String>{};
// A flag to indicate whether we have called `setAssetDirectory` on the target device.
bool hasSetAssetDirectory = false;
@@ -574,6 +576,7 @@ class DevFS {
required List<Uri> invalidatedFiles,
required PackageConfig packageConfig,
required String dillOutputPath,
required DevelopmentShaderCompiler shaderCompiler,
DevFSWriter? devFSWriter,
String? target,
AssetBundle? bundle,
@@ -591,6 +594,8 @@ class DevFS {
// Update modified files
final Map<Uri, DevFSContent> dirtyEntries = <Uri, DevFSContent>{};
final List<Future<void>> pendingShaderCompiles = <Future<void>>[];
bool shaderCompilationFailed = false;
int syncedBytes = 0;
if (fullRestart) {
generator.reset();
@@ -634,14 +639,32 @@ class DevFS {
if (!content.isModified || bundleFirstUpload) {
return;
}
// Modified shaders must be recompiled per-target platform.
final Uri deviceUri = _fileSystem.path.toUri(_fileSystem.path.join(assetDirectory, archivePath));
if (deviceUri.path.startsWith(assetBuildDirPrefix)) {
archivePath = deviceUri.path.substring(assetBuildDirPrefix.length);
}
dirtyEntries[deviceUri] = content;
syncedBytes += content.size;
if (archivePath != null && !bundleFirstUpload) {
assetPathsToEvict.add(archivePath);
if (bundle.entryKinds[archivePath] == AssetKind.shader) {
final Future<DevFSContent?> pending = shaderCompiler.recompileShader(content);
pendingShaderCompiles.add(pending);
pending.then((DevFSContent? content) {
if (content == null) {
shaderCompilationFailed = true;
return;
}
dirtyEntries[deviceUri] = content;
syncedBytes += content.size;
if (archivePath != null && !bundleFirstUpload) {
shaderPathsToEvict.add(archivePath);
}
});
} else {
dirtyEntries[deviceUri] = content;
syncedBytes += content.size;
if (archivePath != null && !bundleFirstUpload) {
assetPathsToEvict.add(archivePath);
}
}
});
@@ -672,6 +695,12 @@ class DevFS {
}
_logger.printTrace('Updating files.');
final Stopwatch transferTimer = _stopwatchFactory.createStopwatch('transfer')..start();
await Future.wait(pendingShaderCompiles);
if (shaderCompilationFailed) {
return UpdateFSReport();
}
if (dirtyEntries.isNotEmpty) {
await (devFSWriter ?? _httpWriter).write(dirtyEntries, _baseUri!, _httpWriter);
}

View File

@@ -27,6 +27,7 @@ import '../base/logger.dart';
import '../base/net.dart';
import '../base/platform.dart';
import '../build_info.dart';
import '../build_system/targets/shader_compiler.dart';
import '../build_system/targets/web.dart';
import '../bundle_builder.dart';
import '../cache.dart';
@@ -792,6 +793,7 @@ class WebDevFS implements DevFS {
required List<Uri> invalidatedFiles,
required PackageConfig packageConfig,
required String dillOutputPath,
required DevelopmentShaderCompiler shaderCompiler,
DevFSWriter? devFSWriter,
String? target,
AssetBundle? bundle,
@@ -923,6 +925,9 @@ class WebDevFS implements DevFS {
void resetLastCompiled() {
// Not used for web compilation.
}
@override
Set<String> get shaderPathsToEvict => <String>{};
}
class ReleaseAssetServer {

View File

@@ -502,6 +502,7 @@ class ResidentWebRunner extends ResidentRunner {
invalidatedFiles: invalidationResult.uris!,
packageConfig: invalidationResult.packageConfig!,
trackWidgetCreation: debuggingOptions.buildInfo.trackWidgetCreation,
shaderCompiler: device!.developmentShaderCompiler,
);
devFSStatus.stop();
_logger!.printTrace('Synced ${getSizeAsMB(report.syncedBytes)}.');

View File

@@ -26,6 +26,7 @@ import 'build_info.dart';
import 'build_system/build_system.dart';
import 'build_system/targets/dart_plugin_registrant.dart';
import 'build_system/targets/localizations.dart';
import 'build_system/targets/shader_compiler.dart';
import 'bundle.dart';
import 'cache.dart';
import 'compile.dart';
@@ -49,6 +50,7 @@ class FlutterDevice {
this.targetPlatform,
ResidentCompiler? generator,
this.userIdentifier,
required this.developmentShaderCompiler,
}) : assert(buildInfo.trackWidgetCreation != null),
generator = generator ?? ResidentCompiler(
globals.artifacts!.getArtifactPath(
@@ -87,6 +89,16 @@ class FlutterDevice {
if (device.platformType == PlatformType.fuchsia) {
targetModel = TargetModel.flutterRunner;
}
final DevelopmentShaderCompiler shaderCompiler = DevelopmentShaderCompiler(
shaderCompiler: ShaderCompiler(
artifacts: globals.artifacts!,
logger: globals.logger,
processManager: globals.processManager,
fileSystem: globals.fs,
),
fileSystem: globals.fs,
);
// For both web and non-web platforms we initialize dill to/from
// a shared location for faster bootstrapping. If the compiler fails
// due to a kernel target or version mismatch, no error is reported
@@ -184,6 +196,7 @@ class FlutterDevice {
generator: generator,
buildInfo: buildInfo,
userIdentifier: userIdentifier,
developmentShaderCompiler: shaderCompiler,
);
}
@@ -192,6 +205,7 @@ class FlutterDevice {
final ResidentCompiler? generator;
final BuildInfo buildInfo;
final String? userIdentifier;
final DevelopmentShaderCompiler developmentShaderCompiler;
DevFSWriter? devFSWriter;
Stream<Uri?>? observatoryUris;
@@ -563,6 +577,7 @@ class FlutterDevice {
invalidatedFiles: invalidatedFiles,
packageConfig: packageConfig,
devFSWriter: devFSWriter,
shaderCompiler: developmentShaderCompiler,
dartPluginRegistrant: FlutterProject.current().dartPluginRegistrant,
);
} on DevFSException {

View File

@@ -247,6 +247,9 @@ class HotRunner extends ResidentRunner {
for (final FlutterDevice? device in flutterDevices) {
await device!.initLogReader();
device
.developmentShaderCompiler
.configureCompiler(device.targetPlatform, enableImpeller: debuggingOptions.enableImpeller);
}
try {
final List<Uri?> baseUris = await _initDevFS();
@@ -496,6 +499,7 @@ class HotRunner extends ResidentRunner {
void _resetDirtyAssets() {
for (final FlutterDevice? device in flutterDevices) {
device!.devFS!.assetPathsToEvict.clear();
device.devFS!.shaderPathsToEvict.clear();
}
}
@@ -1027,7 +1031,7 @@ class HotRunner extends ResidentRunner {
Future<void> evictDirtyAssets() async {
final List<Future<Map<String, dynamic>?>> futures = <Future<Map<String, dynamic>>>[];
for (final FlutterDevice? device in flutterDevices) {
if (device!.devFS!.assetPathsToEvict.isEmpty) {
if (device!.devFS!.assetPathsToEvict.isEmpty && device.devFS!.shaderPathsToEvict.isEmpty) {
continue;
}
final List<FlutterView> views = await device.vmService!.getFlutterViews();
@@ -1061,7 +1065,17 @@ class HotRunner extends ResidentRunner {
)
);
}
for (final String assetPath in device.devFS!.shaderPathsToEvict) {
futures.add(
device.vmService!
.flutterEvictShader(
assetPath,
isolateId: views.first.uiIsolate!.id!,
)
);
}
device.devFS!.assetPathsToEvict.clear();
device.devFS!.shaderPathsToEvict.clear();
}
await Future.wait<Map<String, Object?>?>(futures);
}

View File

@@ -727,6 +727,19 @@ class FlutterVmService {
);
}
Future<Map<String, Object?>?> flutterEvictShader(String assetPath, {
required String isolateId,
}) {
return invokeFlutterExtensionRpcRaw(
'ext.ui.window.reinitializeShader',
isolateId: isolateId,
args: <String, Object?>{
'assetKey': assetPath,
},
);
}
/// Exit the application by calling [exit] from `dart:io`.
///
/// This method is only supported by certain embedders. This is