text
stringlengths 6
13.6M
| id
stringlengths 13
176
| metadata
dict | __index_level_0__
int64 0
1.69k
|
---|---|---|---|
> [!NOTE]
> There are parts of this release process that can only be completed by Googlers
on the Dash team. If you are not a Googler on the Dash team, please reach out on the
[#hackers-devtools](https://discord.com/channels/608014603317936148/1106667330093723668)
Discord channel before trying to create a DevTools release.
# DevTools release process
A new minor version of DevTools should be released into the Dart SDK **monthly**.
This release should be timed with the Dart / Flutter release code cutoff dates so
that we can ensure it is included with the next Flutter beta (see the
[Dash release schedule](http://go/dash-team-releases)). The minor DevTools releases
must be submitted to the Dart SDK before the Beta release cutoff date. Dev or patch
releases of DevTools may occur as needed between minor or major releases.
Before each minor or major DevTools release, the DevTools team will perform a bug
bash for quality assurance and to prevent regressions from slipping into the release.
# How to release Dart DevTools
1. [Release into the Dart SDK master branch](#release-into-the-dart-sdk-master-branch)
2. [Cherry-pick releases into the Dart SDK stable / beta branches](#cherry-pick-releases)
## Release into the Dart SDK master branch
### Configure/Refresh environment
Make sure:
1. Your Dart SDK is configured:
a. You have a local checkout of the Dart SDK
- (for getting started instructions, see
[sdk/CONTRIBUTING.md](https://github.com/dart-lang/sdk/blob/main/CONTRIBUTING.md)).
b. Ensure your `.bashrc` sets `$LOCAL_DART_SDK`
```shell
DART_SDK_REPO_DIR=<Path to cloned dart sdk>
export LOCAL_DART_SDK=$DART_SDK_REPO_DIR/sdk
```
c. The local checkout is at `main` branch: `git rebase-update`
2. Your Flutter SDK in `tool/flutter-sdk` and the one on PATH are updated to the latest candidate release branch:
- Run `devtools_tool update-flutter-sdk --update-on-path`
3. You have goma [configured](http://go/ma-mac-setup)
### Prepare the release
#### Create a release PR
> [!NOTE]
> If you need to install the [Github CLI](https://cli.github.com/manual/installation) you
can run: `brew install gh`
1. Ensure that you have access to `devtools_tool` by adding the `tool/bin` folder to your
`PATH` environment variable
- **MacOS Users**
- add the following to your `~/.bashrc` file.
- `export PATH=$PATH:<DEVTOOLS_DIR>/tool/bin`
> [!NOTE]
> Replace `<DEVTOOLS_DIR>` with the local path to your DevTools
> repo path.
- **Windows Users**
- Open "Edit environment variables for your account" from Control Panel
- Locate the `Path` variable and click **Edit**
- Click the **New** button and paste in `<DEVTOOLS_DIR>/tool/bin`
> [!NOTE]
> Replace `<DEVTOOLS_DIR>` with the local path to your DevTools
> repo path.
2. Run `devtools_tool release-helper` in order to:
- create a new branch using the tip of master and check out locally
- create a PR for the branch
- update your local version of flutter to the latest flutter candidate
- This is to facilitate testing in the next steps
NOTE: Run the script from `/devtools/tool` while [the issue](https://github.com/dart-lang/sdk/issues/54493) is not adderessed.
#### Verify the version changes for the Release PR
Verify the code on the release PR:
1. updated the `devtools_app` and `devtools_test` pubspec versions
2. updated all references to those packages in other `pubspec.yaml` files
3. updated the version constant in `packages/devtools_app/lib/devtools.dart`
`devtools_app` and `devtools_test` versions are updated in lock, so we don't
have to worry about versioning between these two packages. The other DevTools
packages, however, are not updated in lock and each have their own versioning.
For `devtools_app_shared`, `devtools_extensions`, and `devtools_shared`, we
adhere to semantic versioning strategy where breaking changes should be versioned
with a major version bump, and all other changes should be minor or patch version
bumps.
### Test the release PR
1. Build DevTools in release mode and serve it from a locally running DevTools
server instance:
```shell
devtools_tool serve
```
2. Launch DevTools and verify that everything generally works.
- open the page in a browser (http://localhost:53432)
- `flutter run` an application
- connect to the running app from DevTools
- verify:
- pages generally work
- there are no exceptions in the chrome devtools log
- If you find any release blocking issues:
- fix them before releasing.
- Then grab the latest commit hash that includes
- the release prep commit
- the bug fixes,
- use this commit hash for the following steps.
3. Once the build is in good shape,
- revert any local changes.
```shell
git checkout . && \
git clean -f -d;
```
#### Submit the Release PR
Receive an LGTM for the PR, squash and commit.
### Tag the release
1. Checkout the commit from which you want to release DevTools
- This is likely the commit, on `master`, for the PR you just landed
- You can run `git log -v` to see the commits.
2. Run `devtools_tool tag-version`
- this creates a tag on the `flutter/devtools` repo for this release.
- This script will automatically determine the version from
`packages/devtools/pubspec.yaml` so there is no need to manually enter the version.
### Wait for the binary to be uploaded CIPD
On each DevTools commit, DevTools is built and uploaded to CIPD. You can check the
status of the builds on this
[dashboard](https://ci.chromium.org/ui/p/dart-internal/builders/flutter/devtools).
Within minutes, a build should be uploaded for the commit you just merged and tagged.
> [!NOTE]
> If the CIPD build times out, instructions for re-triggering can be found at
[go/dart-engprod/release.md](go/dart-engprod/release.md)
### Update the DevTools hash in the Dart SDK
Run the tool script with the commit hash you just merged and tagged:
```shell
devtools_tool update-sdk-deps -c <commit-hash>
```
This automatically creates a Gerrit CL with the DEPS update for DevTools.
Quickly test the build and then add a reviewer:
1. Build the dart sdk locally
```shell
cd $LOCAL_DART_SDK && \
gclient sync -D && \
./tools/build.py -mrelease -ax64 create_sdk;
```
2. Verify that running `dart devtools` launches the version of DevTools you just released.
- for OSX
```shell
xcodebuild/ReleaseX64/dart-sdk/bin/dart devtools
```
- For non-OSX
```shell
out/ReleaseX64/dart-sdk/bin/dart devtools
```
3. If the version of DevTools you just published to CIPD does not load properly,
you may need to hard reload and clear your browser cache.
4. Add a reviewer and submit once approved.
### Publish DevTools pub packages
If `package:devtools_app_shared`, `package:devtools_extensions`, or
`package:devtools_shared` have unreleased changes, these packages may need to be
published to pub.
**Before publishing these packages, please message the DevTools Team chat room to ask if there
are any reasons why we should wait.** Since these packages follow their own release schedules,
it is possible that there are changes that are not ready to publish.
From the respective `devtools/packages/devtools_*` directories, run:
```shell
flutter pub publish
```
### Update to the next version
1. `gh workflow run daily-dev-bump.yaml -f updateType=minor+dev`
This will kick off a workflow that will automatically create a PR with a
`minor` + `dev` version bump. That PR should then be auto-submitted.
2. Make sure that the release PR goes through without issue:
- See the workflow run [here](https://github.com/flutter/devtools/actions/workflows/daily-dev-bump.yaml)
- Go to https://github.com/flutter/devtools/pulls to see the pull request that
ends up being created
### Verify and Submit the release notes
1. Follow the instructions outlined in the release notes
[README.md](https://github.com/flutter/devtools/blob/master/packages/devtools_app/release_notes/README.md)
to add DevTools release notes to Flutter website and test them in DevTools.
2. Once release notes are submitted to the Flutter website, send an announcement to
[g/flutter-internal-announce](http://g/flutter-internal-announce) with a link to
the new release notes.
## Cherry-pick releases
### Prepare the release in the `flutter/devtools` repo
1. Find the [DevTools tag](https://github.com/flutter/devtools/tags) that you want
to perform the cherry-pick release on top of. Then checkout that tag locally. For this
example, we'll use `v2.29.0` as the base branch and `2.29.1` as the cherry-pick branch.
```
git checkout v2.29.0
```
2. Create a new branch for your cherry pick release.
```
git checkout -b 2.29.1
```
3. Cherry pick the commit(s) you want in this cherry-pick release, and bump the
DevTools version number:
```
git cherry-pick <commit>
devtools_tool update-version auto -t patch
```
4. Commit your changes and push to the `upstream` remote.
```
git add .
git commit -m "Prepare cherry-pick release - DevTools 2.29.1"
git push upstream 2.29.1
```
**To move on to the next step, you will need to take note of two values:**
1) The name of the DevTools branch you just created (e.g. `2.29.1`)
2) The commit hash that is at the tip of this branch
(see https://github.com/flutter/devtools/branches).
### Manually run the DevTools Builder
Follow the instructions at
[go/dart-engprod/devtools.md#cherry-picks](go/dart-engprod/devtools.md#cherry-picks)
to trigger the DevTools builder.
### Create the cherry-pick CL in the Dart SDK
Checkout the Dart SDK branch you want to perform the cherry-pick on top of
(e.g. `stable` or `beta`), and create a new branch:
```
git new-branch --upstream origin/<stable or beta> cherry-pick-devtools
```
From this branch:
1. Edit the `"devtools_rev"` entry in the Dart SDK
[DEPS](https://github.com/dart-lang/sdk/blob/main/DEPS#L104) file to point to the
cherry-pick release hash (the commit at the tip of the cherry-pick branch you created
above).
2. **[Only if cherry-picking to `stable`]** add a
[CHANGELOG entry](https://github.com/dart-lang/sdk/wiki/Cherry-picks-to-a-release-channel#changelog).
3. Commit your changes and upload your CL:
```
git add .
git commit -m "Cherry-pick DevTools 2.29.1"
git cl upload -s
```
Once your CL is uploaded to Gerrit, modify your changelist commit message to meet
the cherry-pick
[requirements](https://github.com/dart-lang/sdk/wiki/Cherry-picks-to-a-release-channel#how-to-cherry-pick-a-changelist).
Then trigger a CQ Dry Run, add reviewers, and wait for approval. **DO NOT** merge
the CL yet.
### Create the cherry-pick issue in the Dart SDK
Follow the [Request cherry-pick approval](https://github.com/dart-lang/sdk/wiki/Cherry-picks-to-a-release-channel#request-cherry-pick-approval) instructions to
create a cherry-pick request against the Dart SDK.
Once the Dart release engineers approve both your cherry-pick issue and your
cherry-pick CL, you can merge the CL you created above.
**Do not move on to the next steps unless your cherry-pick CL has been approved
and merged.**
### Create a DevTools tag for the cherry-pick release
> **If your cherry-pick CL has not been approved and merged, wait.**
Once your cherry pick has been approved and merged, create a tag for this cherry-pick
release. This will ensure that we have a tag we can branch from if we need to
create another DevTools cherry-pick release from the tip of the one we just created.
Check out the cherry-pick branch you created earlier, and create a git tag:
```sh
git checkout upstream/2.29.1
devtools_tool tag-version
```
### Create the merge commit in the `flutter/devtools` repo
> **If your cherry-pick CL has not been approved and merged, wait.**
In order to ensure that the cherry-picked DevTools commit does not get GC'ed, we
need to perform a merge commit from the branch we just created (e.g. `2.29.1`)
onto the `flutter/devtools` protected branch (`master`).
1. Create a pull request in the GitHub UI from the cherry-pick branch to the
`master` branch.
- Navigate to `https://github.com/flutter/devtools/compare/<cherry-pick-branch>`,
where `<cherry-pick-branch>` is the branch you pushed up to the `upstream`
remote with the cherry-picked commit(s) (e.g. `2.29.1`).
- Click "Create pull request", and then create a PR with a descriptive title:
"Merge commit for cherry-pick release 2.29.1"
- Once created, you should see several merge conflicts at the bottom of the PR.
Click "Resolve conflicts" in the GitHub UI, and resolve any merge conflicts by
**accepting whatever is on master**. Once you do this, the PR should show changes
in **zero** lines of code.
- Ask a member of the DevTools team for review, but **DO NOT** squash and merge yet.
2. Contact a member of the Dash team who has Admin access to the `flutter/devtools`
repository settings (@godofredoc or @devoncarew). Ask them to:
- temporarily modify the `flutter/devtools` repository settings to "allow merge
commits at the repo level and remove `require linear history`".
Provide them with a link to your PR for context.
3. Once merge commits have been enabled for the repository, land your PR by
selecting "Create a merge commit" from the merge dropdown options at the bottom
of the PR.
4. Once you have successfully merged your PR, reach back out to the person who
modified the `flutter/devtools` repository settings for you and ask them to revert
the settings change.
### Additional resources
- `dart-lang/sdk` cherry-pick [Wiki](https://github.com/dart-lang/sdk/wiki/Cherry-picks-to-a-release-channel)
- Flutter cherry-pick [Wiki](https://github.com/flutter/flutter/wiki/Flutter-Cherrypick-Process)
- Example cherry-pick cl: https://dart-review.googlesource.com/c/sdk/+/336827
- Example cherry-pick issue: https://github.com/dart-lang/sdk/issues/54085
- Example merge commit on `flutter/devtools`: https://github.com/flutter/devtools/pull/6812
| devtools/tool/RELEASE_INSTRUCTIONS.md/0 | {
"file_path": "devtools/tool/RELEASE_INSTRUCTIONS.md",
"repo_id": "devtools",
"token_count": 4429
} | 150 |
# Script to execute smoke tests for the flutter/tests registry
# https://github.com/flutter/tests
# This is executed as a pre-submit check for every PR in flutter/flutter
# At this point we can expect that mocks have already been generated
# from the setup steps in
# https://github.com/flutter/tests/blob/main/registry/flutter_devtools.test
# Test all tests in devtools_app_shared
cd packages/devtools_app_shared
flutter pub get
flutter test test/
cd ../devtools_app
flutter pub get
flutter test --exclude-tags=skip-for-flutter-customer-tests test/
| devtools/tool/flutter_customer_tests/test.sh/0 | {
"file_path": "devtools/tool/flutter_customer_tests/test.sh",
"repo_id": "devtools",
"token_count": 168
} | 151 |
// Copyright 2023 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:io';
import 'package:args/command_runner.dart';
import 'package:io/io.dart';
import 'package:path/path.dart' as path;
import '../utils.dart';
const _argCommit = 'commit';
/// This command updates the "devtools_rev" hash in the Dart SDK DEPS file with
/// the provided commit hash, and creates a Gerrit CL for review.
///
/// This hash is the ID for a DevTools build stored in CIPD, which is
/// automatically built and uploaded to CIPD on each DevTools commit.
///
/// To run this script:
/// `devtools_tool update-sdk-deps -c <commit-hash>`
class UpdateDartSdkDepsCommand extends Command {
UpdateDartSdkDepsCommand() {
argParser.addOption(
_argCommit,
abbr: 'c',
help: 'The DevTools commit hash to release into the Dart SDK.',
mandatory: true,
);
}
@override
String get name => 'update-sdk-deps';
@override
String get description =>
'Updates the "devtools_rev" hash in the Dart SDK DEPS file with the '
'provided commit hash, and creates a Gerrit CL for review';
@override
Future run() async {
final commit = argResults![_argCommit] as String;
final dartSdkLocation = localDartSdkLocation();
final processManager = ProcessManager();
print('Preparing a local Dart SDK branch...');
await DartSdkHelper.fetchAndCheckoutMaster(processManager);
await processManager.runAll(
workingDirectory: dartSdkLocation,
additionalErrorMessage: DartSdkHelper.commandDebugMessage,
commands: [
CliCommand.git(
['branch', '-D', 'devtools-$commit'],
throwOnException: false,
),
CliCommand.git(['new-branch', 'devtools-$commit']),
],
);
print('Updating the DEPS file with the new DevTools hash...');
_writeToDepsFile(commit, dartSdkLocation);
print('Committing the changes and creating a Gerrit CL...');
await processManager.runAll(
workingDirectory: dartSdkLocation,
additionalErrorMessage: DartSdkHelper.commandDebugMessage,
commands: [
CliCommand.git(['add', 'DEPS']),
CliCommand.git(
[
'commit',
'-m',
'Update DevTools rev to $commit',
],
),
CliCommand.git(['cl', 'upload', '-s', '-f']),
],
);
}
void _writeToDepsFile(String commit, String localDartSdkLocation) {
final depsFilePath = path.join(localDartSdkLocation, 'DEPS');
final depsFile = File(depsFilePath);
if (!depsFile.existsSync()) {
throw Exception('Count not find SDK DEPS file at: $depsFilePath');
}
final devToolsRevMarker = ' "devtools_rev":';
final newFileContent = StringBuffer();
final lines = depsFile.readAsLinesSync();
for (final line in lines) {
if (line.startsWith(devToolsRevMarker)) {
newFileContent.writeln('$devToolsRevMarker "$commit",');
} else {
newFileContent.writeln(line);
}
}
depsFile.writeAsStringSync(newFileContent.toString());
}
}
| devtools/tool/lib/commands/update_dart_sdk_deps.dart/0 | {
"file_path": "devtools/tool/lib/commands/update_dart_sdk_deps.dart",
"repo_id": "devtools",
"token_count": 1195
} | 152 |
[MASTER]
# Specify a configuration file.
#rcfile=
# Python code to execute, usually for sys.path manipulation such as
# pygtk.require().
#init-hook=
# Add files or directories to the blocklist. They should be base names, not
# paths.
ignore=CVS,.git,out
# Pickle collected data for later comparisons.
persistent=yes
# List of plugins (as comma separated values of python modules names) to load,
# usually to register additional checkers.
load-plugins=
pylint_quotes
# Configure quote preferences.
string-quote = single-avoid-escape
triple-quote = double
docstring-quote = double
[MESSAGES CONTROL]
# Enable the message, report, category or checker with the given id(s). You can
# either give multiple identifier separated by comma (,) or put this option
# multiple time.
#enable=
# Disable the message, report, category or checker with the given id(s). You
# can either give multiple identifier separated by comma (,) or put this option
# multiple time (only on the command line, not in the configuration file where
# it should appear only once).
disable=
duplicate-code,
exec-used,
fixme,
missing-class-docstring,
missing-function-docstring,
missing-module-docstring,
too-few-public-methods,
too-many-branches,
too-many-lines,
too-many-return-statements,
too-many-statements,
[REPORTS]
# Set the output format. Available formats are text, parseable, colorized, msvs
# (visual studio) and html
output-format=text
# Put messages in a separate file for each module / package specified on the
# command line instead of printing them on stdout. Reports (if any) will be
# written in a file name "pylint_global.[txt|html]".
files-output=no
# Tells whether to display a full report or only the messages
# CHANGED:
reports=no
# Activate the evaluation score.
score=no
# Python expression which should return a note less than 10 (10 is the highest
# note). You have access to the variables errors warning, statement which
# respectively contain the number of errors / warnings messages and the total
# number of statements analyzed. This is used by the global evaluation report
# (RP0004).
evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)
[VARIABLES]
# Tells whether we should check for unused import in __init__ files.
init-import=no
# A regular expression matching the beginning of the name of dummy variables
# (i.e. not used).
dummy-variables-rgx=_|dummy
# List of additional names supposed to be defined in builtins. Remember that
# you should avoid to define new builtins when possible.
additional-builtins=
[TYPECHECK]
# Tells whether missing members accessed in mixin class should be ignored. A
# mixin class is detected if its name ends with "mixin" (case insensitive).
ignore-mixin-members=yes
# List of classes names for which member attributes should not be checked
# (useful for classes with attributes dynamically set).
ignored-classes=SQLObject,twisted.internet.reactor,hashlib,google.appengine.api.memcache
# List of members which are set dynamically and missed by pylint inference
# system, and so shouldn't trigger E0201 when accessed. Python regular
# expressions are accepted.
generated-members=REQUEST,acl_users,aq_parent,multiprocessing.managers.SyncManager
[MISCELLANEOUS]
# List of note tags to take in consideration, separated by a comma.
notes=FIXME,XXX,TODO
[SIMILARITIES]
# Minimum lines number of a similarity.
min-similarity-lines=10
# Ignore comments when computing similarities.
ignore-comments=yes
# Ignore docstrings when computing similarities.
ignore-docstrings=yes
[FORMAT]
# Maximum number of characters on a single line.
# yapf is configured (in .style.yapf) to format to a line length of 80, but
# sometimes it is not successful if a comment or string literal isn't already
# well-formatted. Therefore, we use pylint to put a hard limit somewhere
# further out at a point where manual formatting should be done.
max-line-length=100
# Maximum number of lines in a module
max-module-lines=1000
# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1
# tab).
# CHANGED:
indent-string=' '
[BASIC]
# List of builtins function names that should not be used, separated by a comma
bad-functions=map,filter,apply,input
# Regular expression which should only match correct module names
module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$
# Regular expression which should only match correct module level names
const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$
# Regular expression which should only match correct class names
class-rgx=[A-Z_][a-zA-Z0-9]+$
# Regular expression which should only match correct function names
function-rgx=[a-z_][a-z0-9_]{2,60}$
# Regular expression which should only match correct method names
method-rgx=[a-z_][a-z0-9_]{2,60}$
# Regular expression which should only match correct instance attribute names
attr-rgx=[a-z_][a-z0-9_]{2,30}$
# Regular expression which should only match correct argument names
argument-rgx=[a-z_][a-z0-9_]{2,30}$
# Regular expression which should only match correct variable names
variable-rgx=[a-z_][a-z0-9_]{2,30}$
# Regular expression which should only match correct list comprehension /
# generator expression variable names
inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$
# Good variable names which should always be accepted, separated by a comma
good-names=i,j,k,ex,Run,_
# Bad variable names which should always be refused, separated by a comma
bad-names=foo,bar,baz,toto,tutu,tata
# Regular expression which should only match functions or classes name which do
# not require a docstring
no-docstring-rgx=__.*__
[DESIGN]
# Maximum number of arguments for function / method
max-args=5
# Argument names that match this expression will be ignored. Default to name
# with leading underscore
ignored-argument-names=_.*
# Maximum number of locals for function / method body
max-locals=25
# Maximum number of return / yield for function / method body
max-returns=6
# Maximum number of branch for function / method body
max-branchs=12
# Maximum number of statements in function / method body
max-statements=50
# Maximum number of parents for a class (see R0901).
max-parents=7
# Maximum number of attributes for a class (see R0902).
max-attributes=7
# Minimum number of public methods for a class (see R0903).
min-public-methods=2
# Maximum number of public methods for a class (see R0904).
max-public-methods=20
[CLASSES]
# List of method names used to declare (i.e. assign) instance attributes.
defining-attr-methods=__init__,__new__,setUp
# List of valid names for the first argument in a class method.
valid-classmethod-first-arg=cls
[IMPORTS]
# Deprecated modules which should not be used, separated by a comma
deprecated-modules=regsub,string,TERMIOS,Bastion,rexec
# Create a graph of every (i.e. internal and external) dependencies in the
# given file (report RP0402 must not be disabled)
import-graph=
# Create a graph of external dependencies in the given file (report RP0402 must
# not be disabled)
ext-import-graph=
# Create a graph of internal dependencies in the given file (report RP0402 must
# not be disabled)
int-import-graph=
[EXCEPTIONS]
# Exceptions that will emit a warning when being caught. Defaults to
# "Exception"
overgeneral-exceptions=Exception
| engine/.pylintrc/0 | {
"file_path": "engine/.pylintrc",
"repo_id": "engine",
"token_count": 2176
} | 153 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_ASSETS_DIRECTORY_ASSET_BUNDLE_H_
#define FLUTTER_ASSETS_DIRECTORY_ASSET_BUNDLE_H_
#include <optional>
#include "flutter/assets/asset_resolver.h"
#include "flutter/fml/macros.h"
#include "flutter/fml/memory/ref_counted.h"
#include "flutter/fml/unique_fd.h"
namespace flutter {
class DirectoryAssetBundle : public AssetResolver {
public:
DirectoryAssetBundle(fml::UniqueFD descriptor,
bool is_valid_after_asset_manager_change);
~DirectoryAssetBundle() override;
private:
const fml::UniqueFD descriptor_;
bool is_valid_ = false;
bool is_valid_after_asset_manager_change_ = false;
// |AssetResolver|
bool IsValid() const override;
// |AssetResolver|
bool IsValidAfterAssetManagerChange() const override;
// |AssetResolver|
AssetResolver::AssetResolverType GetType() const override;
// |AssetResolver|
std::unique_ptr<fml::Mapping> GetAsMapping(
const std::string& asset_name) const override;
// |AssetResolver|
std::vector<std::unique_ptr<fml::Mapping>> GetAsMappings(
const std::string& asset_pattern,
const std::optional<std::string>& subdir) const override;
// |AssetResolver|
bool operator==(const AssetResolver& other) const override;
// |AssetResolver|
const DirectoryAssetBundle* as_directory_asset_bundle() const override {
return this;
}
FML_DISALLOW_COPY_AND_ASSIGN(DirectoryAssetBundle);
};
} // namespace flutter
#endif // FLUTTER_ASSETS_DIRECTORY_ASSET_BUNDLE_H_
| engine/assets/directory_asset_bundle.h/0 | {
"file_path": "engine/assets/directory_asset_bundle.h",
"repo_id": "engine",
"token_count": 584
} | 154 |
#!/usr/bin/env python3
#
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Utility for dart_pkg and dart_pkg_app rules"""
import argparse
import errno
import json
import os
import shutil
import subprocess
import sys
USE_LINKS = sys.platform != 'win32'
DART_ANALYZE = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'dart_analyze.py')
def dart_filter(path):
if os.path.isdir(path):
return True
_, ext = os.path.splitext(path)
# .dart includes '.mojom.dart'
return ext == '.dart'
def ensure_dir_exists(path):
abspath = os.path.abspath(path)
if not os.path.exists(abspath):
os.makedirs(abspath)
def has_pubspec_yaml(paths):
for path in paths:
_, filename = os.path.split(path)
if filename == 'pubspec.yaml':
return True
return False
def link(from_root, to_root):
ensure_dir_exists(os.path.dirname(to_root))
try:
os.unlink(to_root)
except OSError as err:
if err.errno == errno.ENOENT:
pass
try:
os.symlink(from_root, to_root)
except OSError as err:
if err.errno == errno.EEXIST:
pass
def copy(from_root, to_root, filter_func=None):
if not os.path.exists(from_root):
return
if os.path.isfile(from_root):
ensure_dir_exists(os.path.dirname(to_root))
shutil.copy(from_root, to_root)
return
ensure_dir_exists(to_root)
for root, dirs, files in os.walk(from_root):
# filter_func expects paths not names, so wrap it to make them absolute.
wrapped_filter = None
if filter_func:
wrapped_filter = lambda name, rt=root: filter_func(os.path.join(rt, name))
for name in filter(wrapped_filter, files):
from_path = os.path.join(root, name)
root_rel_path = os.path.relpath(from_path, from_root)
to_path = os.path.join(to_root, root_rel_path)
to_dir = os.path.dirname(to_path)
if not os.path.exists(to_dir):
os.makedirs(to_dir)
shutil.copy(from_path, to_path)
dirs[:] = list(filter(wrapped_filter, dirs))
def copy_or_link(from_root, to_root, filter_func=None):
if USE_LINKS:
link(from_root, to_root)
else:
copy(from_root, to_root, filter_func)
def link_if_possible(from_root, to_root):
if USE_LINKS:
link(from_root, to_root)
def remove_if_exists(path):
try:
os.remove(path)
except OSError as err:
if err.errno != errno.ENOENT:
raise
def list_files(from_root, filter_func=None):
file_list = []
for root, dirs, files in os.walk(from_root):
# filter_func expects paths not names, so wrap it to make them absolute.
wrapped_filter = None
if filter_func:
wrapped_filter = lambda name, rt=root: filter_func(os.path.join(rt, name))
for name in filter(wrapped_filter, files):
path = os.path.join(root, name)
file_list.append(path)
dirs[:] = list(filter(wrapped_filter, dirs))
return file_list
def remove_broken_symlink(path):
if not USE_LINKS:
return
try:
link_path = os.readlink(path)
except OSError as err:
# Path was not a symlink.
if err.errno == errno.EINVAL:
pass
else:
if not os.path.exists(link_path):
remove_if_exists(path)
def remove_broken_symlinks(root_dir):
if not USE_LINKS:
return
for current_dir, _, child_files in os.walk(root_dir):
for filename in child_files:
path = os.path.join(current_dir, filename)
remove_broken_symlink(path)
def analyze_entrypoints(dart_sdk, package_root, entrypoints):
cmd = ['python', DART_ANALYZE]
cmd.append('--dart-sdk')
cmd.append(dart_sdk)
cmd.append('--entrypoints')
cmd.extend(entrypoints)
cmd.append('--package-root')
cmd.append(package_root)
cmd.append('--no-hints')
try:
subprocess.check_output(cmd, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as err:
print('Failed analyzing %s' % entrypoints)
print(err.output)
return err.returncode
return 0
def main():
parser = argparse.ArgumentParser(description='Generate a dart-pkg')
parser.add_argument(
'--dart-sdk', action='store', metavar='dart_sdk', help='Path to the Dart SDK.'
)
parser.add_argument(
'--package-name',
action='store',
metavar='package_name',
help='Name of package',
required=True
)
parser.add_argument(
'--pkg-directory',
metavar='pkg_directory',
help='Directory where dart_pkg should go',
required=True
)
parser.add_argument(
'--package-root', metavar='package_root', help='packages/ directory', required=True
)
parser.add_argument('--stamp-file', metavar='stamp_file', help='timestamp file', required=True)
parser.add_argument(
'--entries-file', metavar='entries_file', help='script entries file', required=True
)
parser.add_argument(
'--package-sources', metavar='package_sources', help='Package sources', nargs='+'
)
parser.add_argument(
'--package-entrypoints',
metavar='package_entrypoints',
help='Package entry points for analyzer',
nargs='*',
default=[]
)
parser.add_argument(
'--sdk-ext-directories',
metavar='sdk_ext_directories',
help='Directory containing .dart sources',
nargs='*',
default=[]
)
parser.add_argument(
'--sdk-ext-files',
metavar='sdk_ext_files',
help='List of .dart files that are part of sdk_ext.',
nargs='*',
default=[]
)
parser.add_argument(
'--sdk-ext-mappings',
metavar='sdk_ext_mappings',
help='Mappings for SDK extension libraries.',
nargs='*',
default=[]
)
parser.add_argument(
'--read_only',
action='store_true',
dest='read_only',
help='Package is a read only package.',
default=False
)
args = parser.parse_args()
# We must have a pubspec.yaml.
assert has_pubspec_yaml(args.package_sources)
target_dir = os.path.join(args.pkg_directory, args.package_name)
target_packages_dir = os.path.join(target_dir, 'packages')
lib_path = os.path.join(target_dir, 'lib')
ensure_dir_exists(lib_path)
mappings = {}
for mapping in args.sdk_ext_mappings:
library, path = mapping.split(',', 1)
mappings[library] = '../sdk_ext/%s' % path
sdkext_path = os.path.join(lib_path, '_sdkext')
if mappings:
with open(sdkext_path, 'w') as stream:
json.dump(mappings, stream, sort_keys=True, indent=2, separators=(',', ': '))
else:
remove_if_exists(sdkext_path)
# Copy or symlink package sources into pkg directory.
common_source_prefix = os.path.dirname(os.path.commonprefix(args.package_sources))
for source in args.package_sources:
relative_source = os.path.relpath(source, common_source_prefix)
target = os.path.join(target_dir, relative_source)
copy_or_link(source, target)
entrypoint_targets = []
for source in args.package_entrypoints:
relative_source = os.path.relpath(source, common_source_prefix)
target = os.path.join(target_dir, relative_source)
copy_or_link(source, target)
entrypoint_targets.append(target)
# Copy sdk-ext sources into pkg directory
sdk_ext_dir = os.path.join(target_dir, 'sdk_ext')
for directory in args.sdk_ext_directories:
sdk_ext_sources = list_files(directory, dart_filter)
common_prefix = os.path.commonprefix(sdk_ext_sources)
for source in sdk_ext_sources:
relative_source = os.path.relpath(source, common_prefix)
target = os.path.join(sdk_ext_dir, relative_source)
copy_or_link(source, target)
common_source_prefix = os.path.dirname(os.path.commonprefix(args.sdk_ext_files))
for source in args.sdk_ext_files:
relative_source = os.path.relpath(source, common_source_prefix)
target = os.path.join(sdk_ext_dir, relative_source)
copy_or_link(source, target)
# Symlink packages/
package_path = os.path.join(args.package_root, args.package_name)
copy_or_link(lib_path, package_path)
# Link dart-pkg/$package/packages to dart-pkg/packages
link_if_possible(args.package_root, target_packages_dir)
# Remove any broken symlinks in target_dir and package root.
remove_broken_symlinks(target_dir)
remove_broken_symlinks(args.package_root)
# If any entrypoints are defined, write them to disk so that the analyzer
# test can find them.
with open(args.entries_file, 'w') as file:
for entrypoint in entrypoint_targets:
file.write(entrypoint + '\n')
# Write stamp file.
with open(args.stamp_file, 'w'):
pass
return 0
if __name__ == '__main__':
sys.exit(main())
| engine/build/dart/tools/dart_pkg.py/0 | {
"file_path": "engine/build/dart/tools/dart_pkg.py",
"repo_id": "engine",
"token_count": 3427
} | 155 |
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# This file is based on:
# https://skia.googlesource.com/skia/+/main/third_party/libwebp/BUILD.gn
config("libwebp_config") {
include_dirs = [
"//flutter/third_party/libwebp/src",
"//flutter/third_party/libwebp",
]
}
config("libwebp_defines") {
defines = [
# WebP naturally decodes to RGB_565, Skia with BGR_565.
# This makes WebP decode to BGR_565 when we ask for RGB_565.
# (It also swaps the color order for 4444, but we don't care today.)
"WEBP_SWAP_16BIT_CSP",
# Prevent WebP symbols from being exposed.
"WEBP_EXTERN=extern",
]
}
source_set("libwebp_sse41") {
include_dirs = [
"//flutter/third_party/libwebp/src",
"//flutter/third_party/libwebp",
]
configs += [ ":libwebp_defines" ]
sources = [
"//flutter/third_party/libwebp/src/dsp/alpha_processing_sse41.c",
"//flutter/third_party/libwebp/src/dsp/dec_sse41.c",
"//flutter/third_party/libwebp/src/dsp/enc_sse41.c",
"//flutter/third_party/libwebp/src/dsp/lossless_enc_sse41.c",
"//flutter/third_party/libwebp/src/dsp/lossless_sse41.c",
"//flutter/third_party/libwebp/src/dsp/upsampling_sse41.c",
"//flutter/third_party/libwebp/src/dsp/yuv_sse41.c",
]
if ((current_cpu == "x86" || current_cpu == "x64") && (!is_win || is_clang)) {
cflags_c = [ "-msse4.1" ]
}
}
source_set("libwebp") {
public_configs = [ ":libwebp_config" ]
include_dirs = [
"//flutter/third_party/libwebp/src",
"//flutter/third_party/libwebp",
]
deps = [ ":libwebp_sse41" ]
if (is_android) {
deps += [ "//third_party/cpu-features" ]
}
configs += [ ":libwebp_defines" ]
sources = [
"//flutter/third_party/libwebp/sharpyuv/sharpyuv.c",
"//flutter/third_party/libwebp/sharpyuv/sharpyuv_cpu.c",
"//flutter/third_party/libwebp/sharpyuv/sharpyuv_csp.c",
"//flutter/third_party/libwebp/sharpyuv/sharpyuv_dsp.c",
"//flutter/third_party/libwebp/sharpyuv/sharpyuv_gamma.c",
"//flutter/third_party/libwebp/sharpyuv/sharpyuv_neon.c",
"//flutter/third_party/libwebp/sharpyuv/sharpyuv_sse2.c",
"//flutter/third_party/libwebp/src/dec/alpha_dec.c",
"//flutter/third_party/libwebp/src/dec/buffer_dec.c",
"//flutter/third_party/libwebp/src/dec/frame_dec.c",
"//flutter/third_party/libwebp/src/dec/idec_dec.c",
"//flutter/third_party/libwebp/src/dec/io_dec.c",
"//flutter/third_party/libwebp/src/dec/quant_dec.c",
"//flutter/third_party/libwebp/src/dec/tree_dec.c",
"//flutter/third_party/libwebp/src/dec/vp8_dec.c",
"//flutter/third_party/libwebp/src/dec/vp8l_dec.c",
"//flutter/third_party/libwebp/src/dec/webp_dec.c",
"//flutter/third_party/libwebp/src/demux/anim_decode.c",
"//flutter/third_party/libwebp/src/demux/demux.c",
"//flutter/third_party/libwebp/src/dsp/alpha_processing.c",
"//flutter/third_party/libwebp/src/dsp/alpha_processing_mips_dsp_r2.c",
"//flutter/third_party/libwebp/src/dsp/alpha_processing_neon.c",
"//flutter/third_party/libwebp/src/dsp/alpha_processing_sse2.c",
"//flutter/third_party/libwebp/src/dsp/cost.c",
"//flutter/third_party/libwebp/src/dsp/cost_mips32.c",
"//flutter/third_party/libwebp/src/dsp/cost_mips_dsp_r2.c",
"//flutter/third_party/libwebp/src/dsp/cost_neon.c",
"//flutter/third_party/libwebp/src/dsp/cost_sse2.c",
"//flutter/third_party/libwebp/src/dsp/cpu.c",
"//flutter/third_party/libwebp/src/dsp/dec.c",
"//flutter/third_party/libwebp/src/dsp/dec_clip_tables.c",
"//flutter/third_party/libwebp/src/dsp/dec_mips32.c",
"//flutter/third_party/libwebp/src/dsp/dec_mips_dsp_r2.c",
"//flutter/third_party/libwebp/src/dsp/dec_msa.c",
"//flutter/third_party/libwebp/src/dsp/dec_neon.c",
"//flutter/third_party/libwebp/src/dsp/dec_sse2.c",
"//flutter/third_party/libwebp/src/dsp/enc.c",
"//flutter/third_party/libwebp/src/dsp/enc_mips32.c",
"//flutter/third_party/libwebp/src/dsp/enc_mips_dsp_r2.c",
"//flutter/third_party/libwebp/src/dsp/enc_msa.c",
"//flutter/third_party/libwebp/src/dsp/enc_neon.c",
"//flutter/third_party/libwebp/src/dsp/enc_sse2.c",
"//flutter/third_party/libwebp/src/dsp/filters.c",
"//flutter/third_party/libwebp/src/dsp/filters_mips_dsp_r2.c",
"//flutter/third_party/libwebp/src/dsp/filters_msa.c",
"//flutter/third_party/libwebp/src/dsp/filters_neon.c",
"//flutter/third_party/libwebp/src/dsp/filters_sse2.c",
"//flutter/third_party/libwebp/src/dsp/lossless.c",
"//flutter/third_party/libwebp/src/dsp/lossless_enc.c",
"//flutter/third_party/libwebp/src/dsp/lossless_enc_mips32.c",
"//flutter/third_party/libwebp/src/dsp/lossless_enc_mips_dsp_r2.c",
"//flutter/third_party/libwebp/src/dsp/lossless_enc_msa.c",
"//flutter/third_party/libwebp/src/dsp/lossless_enc_neon.c",
"//flutter/third_party/libwebp/src/dsp/lossless_enc_sse2.c",
"//flutter/third_party/libwebp/src/dsp/lossless_mips_dsp_r2.c",
"//flutter/third_party/libwebp/src/dsp/lossless_msa.c",
"//flutter/third_party/libwebp/src/dsp/lossless_neon.c",
"//flutter/third_party/libwebp/src/dsp/lossless_sse2.c",
"//flutter/third_party/libwebp/src/dsp/rescaler.c",
"//flutter/third_party/libwebp/src/dsp/rescaler_mips32.c",
"//flutter/third_party/libwebp/src/dsp/rescaler_mips_dsp_r2.c",
"//flutter/third_party/libwebp/src/dsp/rescaler_msa.c",
"//flutter/third_party/libwebp/src/dsp/rescaler_neon.c",
"//flutter/third_party/libwebp/src/dsp/rescaler_sse2.c",
"//flutter/third_party/libwebp/src/dsp/ssim.c",
"//flutter/third_party/libwebp/src/dsp/ssim_sse2.c",
"//flutter/third_party/libwebp/src/dsp/upsampling.c",
"//flutter/third_party/libwebp/src/dsp/upsampling_mips_dsp_r2.c",
"//flutter/third_party/libwebp/src/dsp/upsampling_msa.c",
"//flutter/third_party/libwebp/src/dsp/upsampling_neon.c",
"//flutter/third_party/libwebp/src/dsp/upsampling_sse2.c",
"//flutter/third_party/libwebp/src/dsp/yuv.c",
"//flutter/third_party/libwebp/src/dsp/yuv_mips32.c",
"//flutter/third_party/libwebp/src/dsp/yuv_mips_dsp_r2.c",
"//flutter/third_party/libwebp/src/dsp/yuv_neon.c",
"//flutter/third_party/libwebp/src/dsp/yuv_sse2.c",
"//flutter/third_party/libwebp/src/enc/alpha_enc.c",
"//flutter/third_party/libwebp/src/enc/analysis_enc.c",
"//flutter/third_party/libwebp/src/enc/backward_references_cost_enc.c",
"//flutter/third_party/libwebp/src/enc/backward_references_enc.c",
"//flutter/third_party/libwebp/src/enc/config_enc.c",
"//flutter/third_party/libwebp/src/enc/cost_enc.c",
"//flutter/third_party/libwebp/src/enc/filter_enc.c",
"//flutter/third_party/libwebp/src/enc/frame_enc.c",
"//flutter/third_party/libwebp/src/enc/histogram_enc.c",
"//flutter/third_party/libwebp/src/enc/iterator_enc.c",
"//flutter/third_party/libwebp/src/enc/near_lossless_enc.c",
"//flutter/third_party/libwebp/src/enc/picture_csp_enc.c",
"//flutter/third_party/libwebp/src/enc/picture_enc.c",
"//flutter/third_party/libwebp/src/enc/picture_psnr_enc.c",
"//flutter/third_party/libwebp/src/enc/picture_rescale_enc.c",
"//flutter/third_party/libwebp/src/enc/picture_tools_enc.c",
"//flutter/third_party/libwebp/src/enc/predictor_enc.c",
"//flutter/third_party/libwebp/src/enc/quant_enc.c",
"//flutter/third_party/libwebp/src/enc/syntax_enc.c",
"//flutter/third_party/libwebp/src/enc/token_enc.c",
"//flutter/third_party/libwebp/src/enc/tree_enc.c",
"//flutter/third_party/libwebp/src/enc/vp8l_enc.c",
"//flutter/third_party/libwebp/src/enc/webp_enc.c",
"//flutter/third_party/libwebp/src/mux/anim_encode.c",
"//flutter/third_party/libwebp/src/mux/muxedit.c",
"//flutter/third_party/libwebp/src/mux/muxinternal.c",
"//flutter/third_party/libwebp/src/mux/muxread.c",
"//flutter/third_party/libwebp/src/utils/bit_reader_utils.c",
"//flutter/third_party/libwebp/src/utils/bit_writer_utils.c",
"//flutter/third_party/libwebp/src/utils/color_cache_utils.c",
"//flutter/third_party/libwebp/src/utils/filters_utils.c",
"//flutter/third_party/libwebp/src/utils/huffman_encode_utils.c",
"//flutter/third_party/libwebp/src/utils/huffman_utils.c",
"//flutter/third_party/libwebp/src/utils/quant_levels_dec_utils.c",
"//flutter/third_party/libwebp/src/utils/quant_levels_utils.c",
"//flutter/third_party/libwebp/src/utils/random_utils.c",
"//flutter/third_party/libwebp/src/utils/rescaler_utils.c",
"//flutter/third_party/libwebp/src/utils/thread_utils.c",
"//flutter/third_party/libwebp/src/utils/utils.c",
]
}
| engine/build/secondary/flutter/third_party/libwebp/BUILD.gn/0 | {
"file_path": "engine/build/secondary/flutter/third_party/libwebp/BUILD.gn",
"repo_id": "engine",
"token_count": 4194
} | 156 |
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
config("libcxxabi_config") {
common_cc_flags = [
"-nostdinc++",
"-fvisibility=hidden",
]
cflags_cc = common_cc_flags
cflags_objcc = common_cc_flags
include_dirs = [ "include" ]
if (is_ios) {
ldflags = [ "-Wl,-unexported_symbols_list," +
rebase_path("lib/new-delete.exp", root_build_dir) ]
}
}
source_set("libcxxabi") {
visibility = [ "../libcxx:*" ]
public_configs = [ ":libcxxabi_config" ]
defines = [
"_LIBCPP_BUILDING_LIBRARY",
"_LIBCXXABI_BUILDING_LIBRARY",
"LIBCXXABI_SILENT_TERMINATE",
"_LIBCXXABI_DISABLE_VISIBILITY_ANNOTATIONS",
]
sources = []
# Compile libcxx ABI using C++11. This replicates the rule in the
# CMakeLists on the "cxx_abiobjects" target.
configs -= [ "//build/config/compiler:cxx_version_default" ]
configs += [ "//build/config/compiler:cxx_version_20" ]
configs += [ "//third_party/libcxx:src_include" ]
# No translation units in the engine are built with exceptions. But, using
# Objective-C exceptions requires some infrastructure setup for exceptions.
# Build support for the same in cxxabi on Darwin.
if (is_mac || is_ios) {
configs -= [ "//build/config/gcc:no_exceptions" ]
sources += [
"src/cxa_exception.cpp",
"src/cxa_personality.cpp",
]
} else {
if (!is_tsan) {
sources += [ "src/cxa_noexception.cpp" ]
}
}
# Third party dependencies may depend on RTTI. Add support for the same in
# cxxabi.
configs -= [ "//build/config/compiler:no_rtti" ]
configs += [ "//build/config/compiler:rtti" ]
sources += [
"src/abort_message.cpp",
"src/cxa_aux_runtime.cpp",
"src/cxa_default_handlers.cpp",
"src/cxa_demangle.cpp",
"src/cxa_exception_storage.cpp",
"src/cxa_handlers.cpp",
"src/cxa_vector.cpp",
"src/cxa_virtual.cpp",
"src/fallback_malloc.cpp",
"src/private_typeinfo.cpp",
"src/stdlib_exception.cpp",
"src/stdlib_stdexcept.cpp",
"src/stdlib_typeinfo.cpp",
]
if (!(is_tsan && is_linux)) {
sources += [ "src/cxa_guard.cpp" ]
}
if (is_fuchsia || (is_posix && !is_apple)) {
sources += [ "src/cxa_thread_atexit.cpp" ]
}
}
| engine/build/secondary/third_party/libcxxabi/BUILD.gn/0 | {
"file_path": "engine/build/secondary/third_party/libcxxabi/BUILD.gn",
"repo_id": "engine",
"token_count": 967
} | 157 |
#!/usr/bin/env python3.8
# Copyright 2012 Google Inc. All Rights Reserved.
"""
A simple wrapper for protoc.
Script for //third_party/protobuf/proto_library.gni .
Features:
- Inserts #include for extra header automatically.
- Prevents bad proto names.
"""
from __future__ import print_function
import argparse
import os
import os.path
import re
import subprocess
import sys
import tempfile
PROTOC_INCLUDE_POINT = "// @@protoc_insertion_point(includes)"
def FormatGeneratorOptions(options):
if not options:
return ""
if options.endswith(":"):
return options
return options + ":"
def VerifyProtoNames(protos):
for filename in protos:
if "-" in filename:
raise RuntimeError("Proto file names must not contain hyphens "
"(see http://crbug.com/386125 for more information).")
def StripProtoExtension(filename):
if not filename.endswith(".proto"):
raise RuntimeError("Invalid proto filename extension: "
"{0} .".format(filename))
return filename.rsplit(".", 1)[0]
def WriteIncludes(headers, include):
for filename in headers:
include_point_found = False
contents = []
with open(filename) as f:
for line in f:
stripped_line = line.strip()
contents.append(stripped_line)
if stripped_line == PROTOC_INCLUDE_POINT:
if include_point_found:
raise RuntimeError("Multiple include points found.")
include_point_found = True
extra_statement = "#include \"{0}\"".format(include)
contents.append(extra_statement)
if not include_point_found:
raise RuntimeError("Include point not found in header: "
"{0} .".format(filename))
with open(filename, "w") as f:
for line in contents:
print(line, file=f)
def WriteDepfile(depfile, out_list, dep_list):
os.makedirs(os.path.dirname(depfile), exist_ok=True)
with open(depfile, 'w') as f:
print("{0}: {1}".format(" ".join(out_list), " ".join(dep_list)), file=f)
def WritePluginDepfile(depfile, outputs, dependencies):
with open(outputs) as f:
outs = [line.strip() for line in f]
with open(dependencies) as f:
deps = [line.strip() for line in f]
WriteDepfile(depfile, outs, deps)
def WriteProtocDepfile(depfile, outputs, deps_list):
with open(outputs) as f:
outs = [line.strip() for line in f]
WriteDepfile(depfile, outs, deps_list)
def ExtractImports(proto, proto_dir, import_dirs):
filename = os.path.join(proto_dir, proto)
imports = set()
with open(filename) as f:
# Search the file for import.
for line in f:
match = re.match(r'^\s*import(?:\s+public)?\s+"([^"]+)"\s*;\s*$', line)
if match:
imported = match[1]
# Check import directories to find the imported file.
for candidate_dir in [proto_dir] + import_dirs:
candidate_path = os.path.join(candidate_dir, imported)
if os.path.exists(candidate_path):
imports.add(candidate_path)
# Transitively check imports.
imports.update(ExtractImports(imported, candidate_dir, import_dirs))
break
return imports
def main(argv):
parser = argparse.ArgumentParser()
parser.add_argument("--protoc",
help="Relative path to compiler.")
parser.add_argument("--proto-in-dir",
help="Base directory with source protos.")
parser.add_argument("--cc-out-dir",
help="Output directory for standard C++ generator.")
parser.add_argument("--py-out-dir",
help="Output directory for standard Python generator.")
parser.add_argument("--plugin-out-dir",
help="Output directory for custom generator plugin.")
parser.add_argument("--depfile",
help="Output location for the protoc depfile.")
parser.add_argument("--depfile-outputs",
help="File containing a list of files to be generated.")
parser.add_argument("--plugin",
help="Relative path to custom generator plugin.")
parser.add_argument("--plugin-depfile",
help="Output location for the plugin depfile.")
parser.add_argument("--plugin-depfile-deps",
help="File containing plugin deps not set as other input.")
parser.add_argument("--plugin-depfile-outputs",
help="File containing a list of files that will be generated.")
parser.add_argument("--plugin-options",
help="Custom generator plugin options.")
parser.add_argument("--cc-options",
help="Standard C++ generator options.")
parser.add_argument("--include",
help="Name of include to insert into generated headers.")
parser.add_argument("--import-dir", action="append", default=[],
help="Extra import directory for protos, can be repeated."
)
parser.add_argument("--descriptor-set-out",
help="Passed through to protoc as --descriptor_set_out")
parser.add_argument("protos", nargs="+",
help="Input protobuf definition file(s).")
options = parser.parse_args()
proto_dir = os.path.relpath(options.proto_in_dir)
protoc_cmd = [os.path.realpath(options.protoc)]
protos = options.protos
headers = []
VerifyProtoNames(protos)
if options.descriptor_set_out:
protoc_cmd += ["--descriptor_set_out", options.descriptor_set_out]
if options.py_out_dir:
protoc_cmd += ["--python_out", options.py_out_dir]
if options.cc_out_dir:
cc_out_dir = options.cc_out_dir
cc_options = FormatGeneratorOptions(options.cc_options)
protoc_cmd += ["--cpp_out", cc_options + cc_out_dir]
for filename in protos:
stripped_name = StripProtoExtension(filename)
headers.append(os.path.join(cc_out_dir, stripped_name + ".pb.h"))
if options.plugin_out_dir:
plugin_options = FormatGeneratorOptions(options.plugin_options)
protoc_cmd += [
"--plugin", "protoc-gen-plugin=" + os.path.relpath(options.plugin),
"--plugin_out", plugin_options + options.plugin_out_dir
]
if options.plugin_depfile:
if not options.plugin_depfile_deps or not options.plugin_depfile_outputs:
raise RuntimeError("If plugin depfile is supplied, then the plugin "
"depfile deps and outputs must be set.")
depfile = options.plugin_depfile
dep_info = options.plugin_depfile_deps
outputs = options.plugin_depfile_outputs
WritePluginDepfile(depfile, outputs, dep_info)
if options.depfile:
if not options.depfile_outputs:
raise RuntimeError("If depfile is supplied, depfile outputs must also"
"be supplied.")
depfile = options.depfile
outputs = options.depfile_outputs
deps = set()
for proto in protos:
deps.update(ExtractImports(proto, proto_dir, options.import_dir))
WriteProtocDepfile(depfile, outputs, deps)
protoc_cmd += ["--proto_path", proto_dir]
for path in options.import_dir:
protoc_cmd += ["--proto_path", path]
protoc_cmd += [os.path.join(proto_dir, name) for name in protos]
ret = subprocess.call(protoc_cmd)
if ret != 0:
raise RuntimeError("Protoc has returned non-zero status: "
"{0} .".format(ret))
if options.include:
WriteIncludes(headers, options.include)
if __name__ == "__main__":
try:
main(sys.argv)
except RuntimeError as e:
print(e, file=sys.stderr)
sys.exit(1)
| engine/build/secondary/third_party/protobuf/protoc_wrapper.py/0 | {
"file_path": "engine/build/secondary/third_party/protobuf/protoc_wrapper.py",
"repo_id": "engine",
"token_count": 3006
} | 158 |
# Copyright 2019 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# ANGLE expects this to be here.
# Flutter has no wayland third-party dir
wayland_gn_dir = ""
| engine/build_overrides/wayland.gni/0 | {
"file_path": "engine/build_overrides/wayland.gni",
"repo_id": "engine",
"token_count": 74
} | 159 |
{
"builds": [
{
"archives": [
{
"name": "host_debug",
"base_path": "out/host_debug_desktop/zip_archives/",
"type": "gcs",
"include_paths": [
"out/host_debug_desktop/zip_archives/linux-x64-debug/linux-x64-flutter-gtk.zip"
],
"realm": "production"
}
],
"drone_dimensions": [
"device_type=none",
"os=Linux"
],
"gclient_variables": {
"download_android_deps": false,
"use_rbe": true
},
"gn": [
"--runtime-mode",
"debug",
"--enable-fontconfig",
"--prebuilt-dart-sdk",
"--rbe",
"--no-goma",
"--target-dir",
"host_debug_desktop"
],
"name": "host_debug_desktop",
"ninja": {
"config": "host_debug_desktop",
"targets": [
"flutter/shell/platform/linux:flutter_gtk"
]
}
},
{
"archives": [
{
"name": "host_profile",
"base_path": "out/host_profile_desktop/zip_archives/",
"type": "gcs",
"include_paths": [
"out/host_profile_desktop/zip_archives/linux-x64-profile/linux-x64-flutter-gtk.zip"
],
"realm": "production"
}
],
"drone_dimensions": [
"device_type=none",
"os=Linux"
],
"gclient_variables": {
"download_android_deps": false,
"use_rbe": true
},
"gn": [
"--runtime-mode",
"profile",
"--no-lto",
"--enable-fontconfig",
"--prebuilt-dart-sdk",
"--rbe",
"--no-goma",
"--target-dir",
"host_profile_desktop"
],
"name": "host_profile_desktop",
"ninja": {
"config": "host_profile_desktop",
"targets": [
"flutter/shell/platform/linux:flutter_gtk"
]
}
},
{
"archives": [
{
"name": "host_release",
"base_path": "out/host_release_desktop/zip_archives/",
"type": "gcs",
"include_paths": [
"out/host_release_desktop/zip_archives/linux-x64-release/linux-x64-flutter-gtk.zip"
],
"realm": "production"
}
],
"drone_dimensions": [
"device_type=none",
"os=Linux"
],
"gclient_variables": {
"download_android_deps": false,
"use_rbe": true
},
"gn": [
"--runtime-mode",
"release",
"--enable-fontconfig",
"--prebuilt-dart-sdk",
"--rbe",
"--no-goma",
"--target-dir",
"host_release_desktop"
],
"name": "host_release_desktop",
"ninja": {
"config": "host_release_desktop",
"targets": [
"flutter/shell/platform/linux:flutter_gtk"
]
}
}
]
}
| engine/ci/builders/linux_host_desktop_engine.json/0 | {
"file_path": "engine/ci/builders/linux_host_desktop_engine.json",
"repo_id": "engine",
"token_count": 2525
} | 160 |
{
"builds": [
{
"archives": [
{
"base_path": "out/host_debug/zip_archives/",
"type": "gcs",
"include_paths": [
"out/host_debug/zip_archives/windows-x64/artifacts.zip",
"out/host_debug/zip_archives/windows-x64/windows-x64-embedder.zip",
"out/host_debug/zip_archives/windows-x64/font-subset.zip",
"out/host_debug/zip_archives/dart-sdk-windows-x64.zip",
"out/host_debug/zip_archives/windows-x64-debug/windows-x64-flutter.zip",
"out/host_debug/zip_archives/windows-x64/flutter-cpp-client-wrapper.zip"
],
"name": "host_debug",
"realm": "production"
}
],
"drone_dimensions": [
"device_type=none",
"os=Windows-10"
],
"gclient_variables": {
"download_android_deps": false,
"use_rbe": true
},
"gn": [
"--runtime-mode",
"debug",
"--no-lto",
"--no-goma",
"--rbe"
],
"name": "host_debug",
"ninja": {
"config": "host_debug",
"targets": [
"flutter:unittests",
"flutter/build/archives:artifacts",
"flutter/build/archives:embedder",
"flutter/tools/font_subset",
"flutter/build/archives:dart_sdk_archive",
"flutter/shell/platform/windows/client_wrapper:client_wrapper_archive",
"flutter/build/archives:windows_flutter"
]
},
"tests": [
{
"language": "python3",
"name": "Host Tests for host_debug",
"script": "flutter/testing/run_tests.py",
"parameters": [
"--variant",
"host_debug",
"--type",
"engine"
]
}
]
},
{
"archives": [
{
"base_path": "out/host_profile/zip_archives/",
"type": "gcs",
"include_paths": [
"out/host_profile/zip_archives/windows-x64-profile/windows-x64-flutter.zip"
],
"name": "host_profile",
"realm": "production"
}
],
"drone_dimensions": [
"device_type=none",
"os=Windows-10"
],
"gclient_variables": {
"download_android_deps": false,
"use_rbe": true
},
"gn": [
"--runtime-mode",
"profile",
"--no-lto",
"--no-goma",
"--rbe"
],
"name": "host_profile",
"ninja": {
"config": "host_profile",
"targets": [
"windows",
"gen_snapshot",
"flutter/build/archives:windows_flutter"
]
}
},
{
"archives": [
{
"base_path": "out/host_release/zip_archives/",
"type": "gcs",
"include_paths": [
"out/host_release/zip_archives/windows-x64-release/windows-x64-flutter.zip"
],
"name": "host_release",
"realm": "production"
}
],
"drone_dimensions": [
"device_type=none",
"os=Windows-10"
],
"gclient_variables": {
"download_android_deps": false,
"use_rbe": true
},
"generators": {},
"gn": [
"--runtime-mode",
"release",
"--no-lto",
"--no-goma",
"--rbe"
],
"name": "host_release",
"ninja": {
"config": "host_release",
"targets": [
"windows",
"gen_snapshot",
"flutter/build/archives:windows_flutter"
]
}
}
]
}
| engine/ci/builders/windows_host_engine.json/0 | {
"file_path": "engine/ci/builders/windows_host_engine.json",
"repo_id": "engine",
"token_count": 3117
} | 161 |
Signature: 10ea95d73c5e8a92240f014b15634a8c
| engine/ci/licenses_golden/tool_signature/0 | {
"file_path": "engine/ci/licenses_golden/tool_signature",
"repo_id": "engine",
"token_count": 24
} | 162 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/common/graphics/gl_context_switch.h"
namespace flutter {
SwitchableGLContext::SwitchableGLContext() = default;
SwitchableGLContext::~SwitchableGLContext() = default;
GLContextResult::GLContextResult() = default;
GLContextResult::~GLContextResult() = default;
GLContextResult::GLContextResult(bool static_result) : result_(static_result){};
bool GLContextResult::GetResult() {
return result_;
};
GLContextDefaultResult::GLContextDefaultResult(bool static_result)
: GLContextResult(static_result){};
GLContextDefaultResult::~GLContextDefaultResult() = default;
GLContextSwitch::GLContextSwitch(std::unique_ptr<SwitchableGLContext> context)
: context_(std::move(context)) {
FML_CHECK(context_ != nullptr);
result_ = context_->SetCurrent();
};
GLContextSwitch::~GLContextSwitch() {
context_->RemoveCurrent();
};
} // namespace flutter
| engine/common/graphics/gl_context_switch.cc/0 | {
"file_path": "engine/common/graphics/gl_context_switch.cc",
"repo_id": "engine",
"token_count": 308
} | 163 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_DISPLAY_LIST_BENCHMARKING_DL_COMPLEXITY_H_
#define FLUTTER_DISPLAY_LIST_BENCHMARKING_DL_COMPLEXITY_H_
#include "flutter/display_list/display_list.h"
#include "third_party/skia/include/gpu/GrTypes.h"
namespace flutter {
class DisplayListComplexityCalculator {
public:
static DisplayListComplexityCalculator* GetForSoftware();
static DisplayListComplexityCalculator* GetForBackend(GrBackendApi backend);
virtual ~DisplayListComplexityCalculator() = default;
// Returns a calculated complexity score for a given DisplayList object
virtual unsigned int Compute(const DisplayList* display_list) = 0;
// Returns whether a given complexity score meets the threshold for
// cacheability for this particular ComplexityCalculator
virtual bool ShouldBeCached(unsigned int complexity_score) = 0;
// Sets a ceiling for the complexity score being calculated. By default
// this is the largest number representable by an unsigned int.
//
// This setting has no effect on non-accumulator based scorers such as
// the Naive calculator.
virtual void SetComplexityCeiling(unsigned int ceiling) = 0;
};
class DisplayListNaiveComplexityCalculator
: public DisplayListComplexityCalculator {
public:
static DisplayListComplexityCalculator* GetInstance();
unsigned int Compute(const DisplayList* display_list) override {
return display_list->op_count(true);
}
bool ShouldBeCached(unsigned int complexity_score) override {
return complexity_score > 5u;
}
void SetComplexityCeiling(unsigned int ceiling) override {}
private:
DisplayListNaiveComplexityCalculator() {}
static DisplayListNaiveComplexityCalculator* instance_;
};
} // namespace flutter
#endif // FLUTTER_DISPLAY_LIST_BENCHMARKING_DL_COMPLEXITY_H_
| engine/display_list/benchmarking/dl_complexity.h/0 | {
"file_path": "engine/display_list/benchmarking/dl_complexity.h",
"repo_id": "engine",
"token_count": 576
} | 164 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_DISPLAY_LIST_DL_BUILDER_H_
#define FLUTTER_DISPLAY_LIST_DL_BUILDER_H_
#include "flutter/display_list/display_list.h"
#include "flutter/display_list/dl_blend_mode.h"
#include "flutter/display_list/dl_canvas.h"
#include "flutter/display_list/dl_op_flags.h"
#include "flutter/display_list/dl_op_receiver.h"
#include "flutter/display_list/dl_paint.h"
#include "flutter/display_list/dl_sampling_options.h"
#include "flutter/display_list/effects/dl_path_effect.h"
#include "flutter/display_list/image/dl_image.h"
#include "flutter/display_list/utils/dl_bounds_accumulator.h"
#include "flutter/display_list/utils/dl_comparable.h"
#include "flutter/display_list/utils/dl_matrix_clip_tracker.h"
#include "flutter/fml/macros.h"
namespace flutter {
// The primary class used to build a display list. The list of methods
// here matches the list of methods invoked on a |DlOpReceiver| combined
// with the list of methods invoked on a |DlCanvas|.
class DisplayListBuilder final : public virtual DlCanvas,
public SkRefCnt,
virtual DlOpReceiver,
DisplayListOpFlags {
public:
static constexpr SkRect kMaxCullRect =
SkRect::MakeLTRB(-1E9F, -1E9F, 1E9F, 1E9F);
explicit DisplayListBuilder(bool prepare_rtree)
: DisplayListBuilder(kMaxCullRect, prepare_rtree) {}
explicit DisplayListBuilder(const SkRect& cull_rect = kMaxCullRect,
bool prepare_rtree = false);
~DisplayListBuilder();
// |DlCanvas|
SkISize GetBaseLayerSize() const override;
// |DlCanvas|
SkImageInfo GetImageInfo() const override;
// |DlCanvas|
void Save() override;
// |DlCanvas|
void SaveLayer(const SkRect* bounds,
const DlPaint* paint = nullptr,
const DlImageFilter* backdrop = nullptr) override;
// |DlCanvas|
void Restore() override;
// |DlCanvas|
int GetSaveCount() const override { return layer_stack_.size(); }
// |DlCanvas|
void RestoreToCount(int restore_count) override;
// |DlCanvas|
void Translate(SkScalar tx, SkScalar ty) override;
// |DlCanvas|
void Scale(SkScalar sx, SkScalar sy) override;
// |DlCanvas|
void Rotate(SkScalar degrees) override;
// |DlCanvas|
void Skew(SkScalar sx, SkScalar sy) override;
// clang-format off
// 2x3 2D affine subset of a 4x4 transform in row major order
// |DlCanvas|
void Transform2DAffine(SkScalar mxx, SkScalar mxy, SkScalar mxt,
SkScalar myx, SkScalar myy, SkScalar myt) override;
// full 4x4 transform in row major order
// |DlCanvas|
void TransformFullPerspective(
SkScalar mxx, SkScalar mxy, SkScalar mxz, SkScalar mxt,
SkScalar myx, SkScalar myy, SkScalar myz, SkScalar myt,
SkScalar mzx, SkScalar mzy, SkScalar mzz, SkScalar mzt,
SkScalar mwx, SkScalar mwy, SkScalar mwz, SkScalar mwt) override;
// clang-format on
// |DlCanvas|
void TransformReset() override;
// |DlCanvas|
void Transform(const SkMatrix* matrix) override;
// |DlCanvas|
void Transform(const SkM44* matrix44) override;
// |DlCanvas|
void SetTransform(const SkMatrix* matrix) override {
TransformReset();
Transform(matrix);
}
// |DlCanvas|
void SetTransform(const SkM44* matrix44) override {
TransformReset();
Transform(matrix44);
}
using DlCanvas::Transform;
/// Returns the 4x4 full perspective transform representing all transform
/// operations executed so far in this DisplayList within the enclosing
/// save stack.
// |DlCanvas|
SkM44 GetTransformFullPerspective() const override {
return tracker_.matrix_4x4();
}
/// Returns the 3x3 partial perspective transform representing all transform
/// operations executed so far in this DisplayList within the enclosing
/// save stack.
// |DlCanvas|
SkMatrix GetTransform() const override { return tracker_.matrix_3x3(); }
// |DlCanvas|
void ClipRect(const SkRect& rect,
ClipOp clip_op = ClipOp::kIntersect,
bool is_aa = false) override;
// |DlCanvas|
void ClipRRect(const SkRRect& rrect,
ClipOp clip_op = ClipOp::kIntersect,
bool is_aa = false) override;
// |DlCanvas|
void ClipPath(const SkPath& path,
ClipOp clip_op = ClipOp::kIntersect,
bool is_aa = false) override;
/// Conservative estimate of the bounds of all outstanding clip operations
/// measured in the coordinate space within which this DisplayList will
/// be rendered.
// |DlCanvas|
SkRect GetDestinationClipBounds() const override {
return tracker_.device_cull_rect();
}
/// Conservative estimate of the bounds of all outstanding clip operations
/// transformed into the local coordinate space in which currently
/// recorded rendering operations are interpreted.
// |DlCanvas|
SkRect GetLocalClipBounds() const override {
return tracker_.local_cull_rect();
}
/// Return true iff the supplied bounds are easily shown to be outside
/// of the current clip bounds. This method may conservatively return
/// false if it cannot make the determination.
// |DlCanvas|
bool QuickReject(const SkRect& bounds) const override;
// |DlCanvas|
void DrawPaint(const DlPaint& paint) override;
// |DlCanvas|
void DrawColor(DlColor color, DlBlendMode mode) override;
// |DlCanvas|
void DrawLine(const SkPoint& p0,
const SkPoint& p1,
const DlPaint& paint) override;
// |DlCanvas|
void DrawRect(const SkRect& rect, const DlPaint& paint) override;
// |DlCanvas|
void DrawOval(const SkRect& bounds, const DlPaint& paint) override;
// |DlCanvas|
void DrawCircle(const SkPoint& center,
SkScalar radius,
const DlPaint& paint) override;
// |DlCanvas|
void DrawRRect(const SkRRect& rrect, const DlPaint& paint) override;
// |DlCanvas|
void DrawDRRect(const SkRRect& outer,
const SkRRect& inner,
const DlPaint& paint) override;
// |DlCanvas|
void DrawPath(const SkPath& path, const DlPaint& paint) override;
// |DlCanvas|
void DrawArc(const SkRect& bounds,
SkScalar start,
SkScalar sweep,
bool useCenter,
const DlPaint& paint) override;
// |DlCanvas|
void DrawPoints(PointMode mode,
uint32_t count,
const SkPoint pts[],
const DlPaint& paint) override;
// |DlCanvas|
void DrawVertices(const DlVertices* vertices,
DlBlendMode mode,
const DlPaint& paint) override;
using DlCanvas::DrawVertices;
// |DlCanvas|
void DrawImage(const sk_sp<DlImage>& image,
const SkPoint point,
DlImageSampling sampling,
const DlPaint* paint = nullptr) override;
// |DlCanvas|
void DrawImageRect(
const sk_sp<DlImage>& image,
const SkRect& src,
const SkRect& dst,
DlImageSampling sampling,
const DlPaint* paint = nullptr,
SrcRectConstraint constraint = SrcRectConstraint::kFast) override;
using DlCanvas::DrawImageRect;
// |DlCanvas|
void DrawImageNine(const sk_sp<DlImage>& image,
const SkIRect& center,
const SkRect& dst,
DlFilterMode filter,
const DlPaint* paint = nullptr) override;
// |DlCanvas|
void DrawAtlas(const sk_sp<DlImage>& atlas,
const SkRSXform xform[],
const SkRect tex[],
const DlColor colors[],
int count,
DlBlendMode mode,
DlImageSampling sampling,
const SkRect* cullRect,
const DlPaint* paint = nullptr) override;
// |DlCanvas|
void DrawDisplayList(const sk_sp<DisplayList> display_list,
SkScalar opacity = SK_Scalar1) override;
// |DlCanvas|
void DrawTextBlob(const sk_sp<SkTextBlob>& blob,
SkScalar x,
SkScalar y,
const DlPaint& paint) override;
void drawTextFrame(const std::shared_ptr<impeller::TextFrame>& text_frame,
SkScalar x,
SkScalar y) override;
void DrawTextFrame(const std::shared_ptr<impeller::TextFrame>& text_frame,
SkScalar x,
SkScalar y,
const DlPaint& paint) override;
// |DlCanvas|
void DrawShadow(const SkPath& path,
const DlColor color,
const SkScalar elevation,
bool transparent_occluder,
SkScalar dpr) override;
// |DlCanvas|
void Flush() override {}
sk_sp<DisplayList> Build();
private:
// This method exposes the internal stateful DlOpReceiver implementation
// of the DisplayListBuilder, primarily for testing purposes. Its use
// is obsolete and forbidden in every other case and is only shared to a
// pair of "friend" accessors in the benchmark/unittest files.
DlOpReceiver& asReceiver() { return *this; }
friend DlOpReceiver& DisplayListBuilderBenchmarkAccessor(
DisplayListBuilder& builder);
friend DlOpReceiver& DisplayListBuilderTestingAccessor(
DisplayListBuilder& builder);
friend DlPaint DisplayListBuilderTestingAttributes(
DisplayListBuilder& builder);
void SetAttributesFromPaint(const DlPaint& paint,
const DisplayListAttributeFlags flags);
// |DlOpReceiver|
void setAntiAlias(bool aa) override {
if (current_.isAntiAlias() != aa) {
onSetAntiAlias(aa);
}
}
// |DlOpReceiver|
void setInvertColors(bool invert) override {
if (current_.isInvertColors() != invert) {
onSetInvertColors(invert);
}
}
// |DlOpReceiver|
void setStrokeCap(DlStrokeCap cap) override {
if (current_.getStrokeCap() != cap) {
onSetStrokeCap(cap);
}
}
// |DlOpReceiver|
void setStrokeJoin(DlStrokeJoin join) override {
if (current_.getStrokeJoin() != join) {
onSetStrokeJoin(join);
}
}
// |DlOpReceiver|
void setDrawStyle(DlDrawStyle style) override {
if (current_.getDrawStyle() != style) {
onSetDrawStyle(style);
}
}
// |DlOpReceiver|
void setStrokeWidth(float width) override {
if (current_.getStrokeWidth() != width) {
onSetStrokeWidth(width);
}
}
// |DlOpReceiver|
void setStrokeMiter(float limit) override {
if (current_.getStrokeMiter() != limit) {
onSetStrokeMiter(limit);
}
}
// |DlOpReceiver|
void setColor(DlColor color) override {
if (current_.getColor() != color) {
onSetColor(color);
}
}
// |DlOpReceiver|
void setBlendMode(DlBlendMode mode) override {
if (current_.getBlendMode() != mode) {
onSetBlendMode(mode);
}
}
// |DlOpReceiver|
void setColorSource(const DlColorSource* source) override {
if (NotEquals(current_.getColorSource(), source)) {
onSetColorSource(source);
}
}
// |DlOpReceiver|
void setImageFilter(const DlImageFilter* filter) override {
if (NotEquals(current_.getImageFilter(), filter)) {
onSetImageFilter(filter);
}
}
// |DlOpReceiver|
void setColorFilter(const DlColorFilter* filter) override {
if (NotEquals(current_.getColorFilter(), filter)) {
onSetColorFilter(filter);
}
}
// |DlOpReceiver|
void setPathEffect(const DlPathEffect* effect) override {
if (NotEquals(current_.getPathEffect(), effect)) {
onSetPathEffect(effect);
}
}
// |DlOpReceiver|
void setMaskFilter(const DlMaskFilter* filter) override {
if (NotEquals(current_.getMaskFilter(), filter)) {
onSetMaskFilter(filter);
}
}
DlPaint CurrentAttributes() const { return current_; }
// |DlOpReceiver|
void save() override { Save(); }
// Only the |renders_with_attributes()| option will be accepted here. Any
// other flags will be ignored and calculated anew as the DisplayList is
// built. Alternatively, use the |saveLayer(SkRect, bool)| method.
// |DlOpReceiver|
void saveLayer(const SkRect& bounds,
const SaveLayerOptions options,
const DlImageFilter* backdrop) override;
// |DlOpReceiver|
void restore() override { Restore(); }
// |DlOpReceiver|
void translate(SkScalar tx, SkScalar ty) override { Translate(tx, ty); }
// |DlOpReceiver|
void scale(SkScalar sx, SkScalar sy) override { Scale(sx, sy); }
// |DlOpReceiver|
void rotate(SkScalar degrees) override { Rotate(degrees); }
// |DlOpReceiver|
void skew(SkScalar sx, SkScalar sy) override { Skew(sx, sy); }
// clang-format off
// |DlOpReceiver|
void transform2DAffine(SkScalar mxx, SkScalar mxy, SkScalar mxt,
SkScalar myx, SkScalar myy, SkScalar myt) override {
Transform2DAffine(mxx, mxy, mxt, myx, myy, myt);
}
// |DlOpReceiver|
void transformFullPerspective(
SkScalar mxx, SkScalar mxy, SkScalar mxz, SkScalar mxt,
SkScalar myx, SkScalar myy, SkScalar myz, SkScalar myt,
SkScalar mzx, SkScalar mzy, SkScalar mzz, SkScalar mzt,
SkScalar mwx, SkScalar mwy, SkScalar mwz, SkScalar mwt) override {
TransformFullPerspective(mxx, mxy, mxz, mxt,
myx, myy, myz, myt,
mzx, mzy, mzz, mzt,
mwx, mwy, mwz, mwt);
}
// clang-format off
// |DlOpReceiver|
void transformReset() override { TransformReset(); }
// |DlOpReceiver|
void clipRect(const SkRect& rect, ClipOp clip_op, bool is_aa) override {
ClipRect(rect, clip_op, is_aa);
}
// |DlOpReceiver|
void clipRRect(const SkRRect& rrect, ClipOp clip_op, bool is_aa) override {
ClipRRect(rrect, clip_op, is_aa);
}
// |DlOpReceiver|
void clipPath(const SkPath& path, ClipOp clip_op, bool is_aa) override {
ClipPath(path, clip_op, is_aa);
}
// |DlOpReceiver|
void drawPaint() override;
// |DlOpReceiver|
void drawColor(DlColor color, DlBlendMode mode) override {
DrawColor(color, mode);
}
// |DlOpReceiver|
void drawLine(const SkPoint& p0, const SkPoint& p1) override;
// |DlOpReceiver|
void drawRect(const SkRect& rect) override;
// |DlOpReceiver|
void drawOval(const SkRect& bounds) override;
// |DlOpReceiver|
void drawCircle(const SkPoint& center, SkScalar radius) override;
// |DlOpReceiver|
void drawRRect(const SkRRect& rrect) override;
// |DlOpReceiver|
void drawDRRect(const SkRRect& outer, const SkRRect& inner) override;
// |DlOpReceiver|
void drawPath(const SkPath& path) override;
// |DlOpReceiver|
void drawArc(const SkRect& bounds,
SkScalar start,
SkScalar sweep,
bool useCenter) override;
// |DlOpReceiver|
void drawPoints(PointMode mode, uint32_t count, const SkPoint pts[]) override;
// |DlOpReceiver|
void drawVertices(const DlVertices* vertices, DlBlendMode mode) override;
// |DlOpReceiver|
void drawImage(const sk_sp<DlImage> image,
const SkPoint point,
DlImageSampling sampling,
bool render_with_attributes) override;
// |DlOpReceiver|
void drawImageRect(
const sk_sp<DlImage> image,
const SkRect& src,
const SkRect& dst,
DlImageSampling sampling,
bool render_with_attributes,
SrcRectConstraint constraint = SrcRectConstraint::kFast) override;
// |DlOpReceiver|
void drawImageNine(const sk_sp<DlImage> image,
const SkIRect& center,
const SkRect& dst,
DlFilterMode filter,
bool render_with_attributes) override;
// |DlOpReceiver|
void drawAtlas(const sk_sp<DlImage> atlas,
const SkRSXform xform[],
const SkRect tex[],
const DlColor colors[],
int count,
DlBlendMode mode,
DlImageSampling sampling,
const SkRect* cullRect,
bool render_with_attributes) override;
// |DlOpReceiver|
void drawDisplayList(const sk_sp<DisplayList> display_list,
SkScalar opacity) override {
DrawDisplayList(display_list, opacity);
}
// |DlOpReceiver|
void drawTextBlob(const sk_sp<SkTextBlob> blob,
SkScalar x,
SkScalar y) override;
// |DlOpReceiver|
void drawShadow(const SkPath& path,
const DlColor color,
const SkScalar elevation,
bool transparent_occluder,
SkScalar dpr) override {
DrawShadow(path, color, elevation, transparent_occluder, dpr);
}
void checkForDeferredSave();
DisplayListStorage storage_;
size_t used_ = 0;
size_t allocated_ = 0;
int render_op_count_ = 0;
int op_index_ = 0;
// bytes and ops from |drawPicture| and |drawDisplayList|
size_t nested_bytes_ = 0;
int nested_op_count_ = 0;
bool is_ui_thread_safe_ = true;
template <typename T, typename... Args>
void* Push(size_t extra, int op_inc, Args&&... args);
void intersect(const SkRect& rect);
// kInvalidSigma is used to indicate that no MaskBlur is currently set.
static constexpr SkScalar kInvalidSigma = 0.0;
static bool mask_sigma_valid(SkScalar sigma) {
return SkScalarIsFinite(sigma) && sigma > 0.0;
}
class SaveInfo {
public:
explicit SaveInfo(size_t save_offset = 0) : save_offset_(save_offset) {}
// The offset into the memory buffer where the save DLOp record
// for this save() call is placed. This may be needed if the
// eventual restore() call has discovered important information about
// the records inside the saveLayer that may impact how the saveLayer
// is handled (e.g., |cannot_inherit_opacity| == false).
// This offset is only valid if |has_layer| is true.
size_t save_offset() const { return save_offset_; }
bool is_save_layer() const { return is_save_layer_; }
bool cannot_inherit_opacity() const { return cannot_inherit_opacity_; }
bool has_compatible_op() const { return has_compatible_op_; }
bool affects_transparent_layer() const {
return affects_transparent_layer_;
}
bool is_group_opacity_compatible() const {
return !cannot_inherit_opacity_;
}
void mark_incompatible() { cannot_inherit_opacity_ = true; }
// For now this only allows a single compatible op to mark the
// layer as being compatible with group opacity. If we start
// computing bounds of ops in the Builder methods then we
// can upgrade this to checking for overlapping ops.
// See https://github.com/flutter/flutter/issues/93899
void add_compatible_op() {
if (!cannot_inherit_opacity_) {
if (has_compatible_op_) {
cannot_inherit_opacity_ = true;
} else {
has_compatible_op_ = true;
}
}
}
// Records that the current layer contains an op that produces visible
// output on a transparent surface.
void add_visible_op() {
affects_transparent_layer_ = true;
}
// The filter to apply to the layer bounds when it is restored
std::shared_ptr<const DlImageFilter> filter() { return filter_; }
// is_unbounded should be set to true if we ever encounter an operation
// on a layer that either is unrestricted (|drawColor| or |drawPaint|)
// or cannot compute its bounds (some effects and filters) and there
// was no outstanding clip op at the time.
// When the layer is restored, the outer layer may then process this
// unbounded state by accumulating its own clip or transferring the
// unbounded state to its own outer layer.
// Typically the DisplayList will have been constructed with a cull
// rect which will act as a default clip for the outermost layer and
// the unbounded state of all sub layers will eventually be caught by
// that cull rect so that the overall unbounded state of the entire
// DisplayList will never be true.
//
// For historical consistency it is worth noting that SkPicture used
// to treat these same conditions as a Nop (they accumulate the
// SkPicture cull rect, but if no cull rect was specified then it is
// an empty Rect and so has no effect on the bounds).
//
// Flutter is unlikely to ever run into this as the Dart mechanisms
// all supply a non-null cull rect for all Dart Picture objects,
// even if that cull rect is kGiantRect.
void set_unbounded() { is_unbounded_ = true; }
// |is_unbounded| should be called after |getLayerBounds| in case
// a problem was found during the computation of those bounds,
// the layer will have one last chance to flag an unbounded state.
bool is_unbounded() const { return is_unbounded_; }
private:
size_t save_offset_;
bool is_save_layer_ = false;
bool cannot_inherit_opacity_ = false;
bool has_compatible_op_ = false;
std::shared_ptr<const DlImageFilter> filter_;
bool is_unbounded_ = false;
bool has_deferred_save_op_ = false;
bool is_nop_ = false;
bool affects_transparent_layer_ = false;
std::shared_ptr<BoundsAccumulator> layer_accumulator_;
friend class DisplayListBuilder;
};
std::vector<SaveInfo> layer_stack_;
SaveInfo* current_layer_;
DisplayListMatrixClipTracker tracker_;
std::unique_ptr<DisplayListMatrixClipTracker> layer_tracker_;
std::unique_ptr<BoundsAccumulator> accumulator_;
BoundsAccumulator* accumulator() { return accumulator_.get(); }
// This flag indicates whether or not the current rendering attributes
// are compatible with rendering ops applying an inherited opacity.
bool current_opacity_compatibility_ = true;
// Returns the compatibility of a given blend mode for applying an
// inherited opacity value to modulate the visibility of the op.
// For now we only accept SrcOver blend modes but this could be expanded
// in the future to include other (rarely used) modes that also modulate
// the opacity of a rendering operation at the cost of a switch statement
// or lookup table.
static bool IsOpacityCompatible(DlBlendMode mode) {
return (mode == DlBlendMode::kSrcOver);
}
void UpdateCurrentOpacityCompatibility() {
current_opacity_compatibility_ = //
current_.getColorFilter() == nullptr && //
!current_.isInvertColors() && //
IsOpacityCompatible(current_.getBlendMode());
}
// Update the opacity compatibility flags of the current layer for an op
// that has determined its compatibility as indicated by |compatible|.
void UpdateLayerOpacityCompatibility(bool compatible) {
if (compatible) {
current_layer_->add_compatible_op();
} else {
current_layer_->mark_incompatible();
}
}
// Check for opacity compatibility for an op that may or may not use the
// current rendering attributes as indicated by |uses_blend_attribute|.
// If the flag is false then the rendering op will be able to substitute
// a default Paint object with the opacity applied using the default SrcOver
// blend mode which is always compatible with applying an inherited opacity.
void CheckLayerOpacityCompatibility(bool uses_blend_attribute = true) {
UpdateLayerOpacityCompatibility(!uses_blend_attribute ||
current_opacity_compatibility_);
}
void CheckLayerOpacityHairlineCompatibility() {
UpdateLayerOpacityCompatibility(
current_opacity_compatibility_ &&
(current_.getDrawStyle() == DlDrawStyle::kFill ||
current_.getStrokeWidth() > 0));
}
// Check for opacity compatibility for an op that ignores the current
// attributes and uses the indicated blend |mode| to render to the layer.
// This is only used by |drawColor| currently.
void CheckLayerOpacityCompatibility(DlBlendMode mode) {
UpdateLayerOpacityCompatibility(IsOpacityCompatible(mode));
}
void onSetAntiAlias(bool aa);
void onSetInvertColors(bool invert);
void onSetStrokeCap(DlStrokeCap cap);
void onSetStrokeJoin(DlStrokeJoin join);
void onSetDrawStyle(DlDrawStyle style);
void onSetStrokeWidth(SkScalar width);
void onSetStrokeMiter(SkScalar limit);
void onSetColor(DlColor color);
void onSetBlendMode(DlBlendMode mode);
void onSetColorSource(const DlColorSource* source);
void onSetImageFilter(const DlImageFilter* filter);
void onSetColorFilter(const DlColorFilter* filter);
void onSetPathEffect(const DlPathEffect* effect);
void onSetMaskFilter(const DlMaskFilter* filter);
// The DisplayList had an unbounded call with no cull rect or clip
// to contain it. Should only be called after the stream is fully
// built.
// Unbounded operations are calls like |drawColor| which are defined
// to flood the entire surface, or calls that relied on a rendering
// attribute which is unable to compute bounds (should be rare).
// In those cases the bounds will represent only the accumulation
// of the bounded calls and this flag will be set to indicate that
// condition.
bool is_unbounded() const {
FML_DCHECK(layer_stack_.size() == 1);
return layer_stack_.front().is_unbounded();
}
SkRect bounds() const {
FML_DCHECK(layer_stack_.size() == 1);
if (is_unbounded()) {
FML_LOG(INFO) << "returning partial bounds for unbounded DisplayList";
}
return accumulator_->bounds();
}
sk_sp<DlRTree> rtree() {
FML_DCHECK(layer_stack_.size() == 1);
if (is_unbounded()) {
FML_LOG(INFO) << "returning partial rtree for unbounded DisplayList";
}
return accumulator_->rtree();
}
static DisplayListAttributeFlags FlagsForPointMode(PointMode mode);
enum class OpResult {
kNoEffect,
kPreservesTransparency,
kAffectsAll,
};
bool paint_nops_on_transparency();
OpResult PaintResult(const DlPaint& paint,
DisplayListAttributeFlags flags = kDrawPaintFlags);
void UpdateLayerResult(OpResult result) {
switch (result) {
case OpResult::kNoEffect:
case OpResult::kPreservesTransparency:
break;
case OpResult::kAffectsAll:
current_layer_->add_visible_op();
break;
}
}
// kAnyColor is a non-opaque and non-transparent color that will not
// trigger any short-circuit tests about the results of a blend.
static constexpr DlColor kAnyColor = DlColor::kMidGrey().withAlpha(0x80);
static_assert(!kAnyColor.isOpaque());
static_assert(!kAnyColor.isTransparent());
static DlColor GetEffectiveColor(const DlPaint& paint,
DisplayListAttributeFlags flags);
// Adjusts the indicated bounds for the given flags and returns true if
// the calculation was possible, or false if it could not be estimated.
bool AdjustBoundsForPaint(SkRect& bounds, DisplayListAttributeFlags flags);
// Records the fact that we encountered an op that either could not
// estimate its bounds or that fills all of the destination space.
bool AccumulateUnbounded();
// Records the bounds for an op after modifying them according to the
// supplied attribute flags and transforming by the current matrix.
bool AccumulateOpBounds(const SkRect& bounds,
DisplayListAttributeFlags flags) {
SkRect safe_bounds = bounds;
return AccumulateOpBounds(safe_bounds, flags);
}
// Records the bounds for an op after modifying them according to the
// supplied attribute flags and transforming by the current matrix
// and clipping against the current clip.
bool AccumulateOpBounds(SkRect& bounds, DisplayListAttributeFlags flags);
// Records the given bounds after transforming by the current matrix
// and clipping against the current clip.
bool AccumulateBounds(SkRect& bounds);
DlPaint current_;
};
} // namespace flutter
#endif // FLUTTER_DISPLAY_LIST_DL_BUILDER_H_
| engine/display_list/dl_builder.h/0 | {
"file_path": "engine/display_list/dl_builder.h",
"repo_id": "engine",
"token_count": 10901
} | 165 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/display_list/dl_vertices.h"
#include "flutter/display_list/utils/dl_bounds_accumulator.h"
#include "flutter/fml/logging.h"
namespace flutter {
using Flags = DlVertices::Builder::Flags;
static void DlVerticesDeleter(void* p) {
// Some of our target environments would prefer a sized delete,
// but other target environments do not have that operator.
// Use an unsized delete until we get better agreement in the
// environments.
// See https://github.com/flutter/flutter/issues/100327
::operator delete(p);
}
static size_t bytes_needed(int vertex_count, Flags flags, int index_count) {
int needed = sizeof(DlVertices);
// We always have vertices
needed += vertex_count * sizeof(SkPoint);
if (flags.has_texture_coordinates) {
needed += vertex_count * sizeof(SkPoint);
}
if (flags.has_colors) {
needed += vertex_count * sizeof(DlColor);
}
if (index_count > 0) {
needed += index_count * sizeof(uint16_t);
}
return needed;
}
std::shared_ptr<DlVertices> DlVertices::Make(
DlVertexMode mode,
int vertex_count,
const SkPoint vertices[],
const SkPoint texture_coordinates[],
const DlColor colors[],
int index_count,
const uint16_t indices[]) {
if (!vertices || vertex_count <= 0) {
vertex_count = 0;
texture_coordinates = nullptr;
colors = nullptr;
}
if (!indices || index_count <= 0) {
index_count = 0;
indices = nullptr;
}
Flags flags;
FML_DCHECK(!flags.has_texture_coordinates);
FML_DCHECK(!flags.has_colors);
if (texture_coordinates) {
flags |= Builder::kHasTextureCoordinates;
}
if (colors) {
flags |= Builder::kHasColors;
}
Builder builder(mode, vertex_count, flags, index_count);
builder.store_vertices(vertices);
if (texture_coordinates) {
builder.store_texture_coordinates(texture_coordinates);
}
if (colors) {
builder.store_colors(colors);
}
if (indices) {
builder.store_indices(indices);
}
return builder.build();
}
size_t DlVertices::size() const {
return bytes_needed(vertex_count_,
{{texture_coordinates_offset_ > 0, colors_offset_ > 0}},
index_count_);
}
static SkRect compute_bounds(const SkPoint* points, int count) {
RectBoundsAccumulator accumulator;
for (int i = 0; i < count; i++) {
accumulator.accumulate(points[i]);
}
return accumulator.bounds();
}
DlVertices::DlVertices(DlVertexMode mode,
int unchecked_vertex_count,
const SkPoint* vertices,
const SkPoint* texture_coordinates,
const DlColor* colors,
int unchecked_index_count,
const uint16_t* indices,
const SkRect* bounds)
: mode_(mode),
vertex_count_(std::max(unchecked_vertex_count, 0)),
index_count_(indices ? std::max(unchecked_index_count, 0) : 0) {
bounds_ = bounds ? *bounds : compute_bounds(vertices, vertex_count_);
char* pod = reinterpret_cast<char*>(this);
size_t offset = sizeof(DlVertices);
auto advance = [pod, &offset](auto* src, int count) {
if (src != nullptr && count > 0) {
size_t bytes = count * sizeof(*src);
memcpy(pod + offset, src, bytes);
size_t ret = offset;
offset += bytes;
return ret;
} else {
return static_cast<size_t>(0);
}
};
vertices_offset_ = advance(vertices, vertex_count_);
texture_coordinates_offset_ = advance(texture_coordinates, vertex_count_);
colors_offset_ = advance(colors, vertex_count_);
indices_offset_ = advance(indices, index_count_);
FML_DCHECK(offset == bytes_needed(vertex_count_,
{{!!texture_coordinates, !!colors}},
index_count_));
}
DlVertices::DlVertices(const DlVertices* other)
: DlVertices(other->mode_,
other->vertex_count_,
other->vertices(),
other->texture_coordinates(),
other->colors(),
other->index_count_,
other->indices(),
&other->bounds_) {}
DlVertices::DlVertices(DlVertexMode mode,
int unchecked_vertex_count,
Flags flags,
int unchecked_index_count)
: mode_(mode),
vertex_count_(std::max(unchecked_vertex_count, 0)),
index_count_(std::max(unchecked_index_count, 0)) {
char* pod = reinterpret_cast<char*>(this);
size_t offset = sizeof(DlVertices);
auto advance = [pod, &offset](size_t size, int count) {
if (count > 0) {
size_t bytes = count * size;
memset(pod + offset, 0, bytes);
size_t ret = offset;
offset += bytes;
return ret;
} else {
return static_cast<size_t>(0);
}
};
vertices_offset_ = advance(sizeof(SkPoint), vertex_count_);
texture_coordinates_offset_ = advance(
sizeof(SkPoint), flags.has_texture_coordinates ? vertex_count_ : 0);
colors_offset_ =
advance(sizeof(DlColor), flags.has_colors ? vertex_count_ : 0);
indices_offset_ = advance(sizeof(uint16_t), index_count_);
FML_DCHECK(offset == bytes_needed(vertex_count_, flags, index_count_));
FML_DCHECK((vertex_count_ != 0) == (vertices() != nullptr));
FML_DCHECK((vertex_count_ != 0 && flags.has_texture_coordinates) ==
(texture_coordinates() != nullptr));
FML_DCHECK((vertex_count_ != 0 && flags.has_colors) == (colors() != nullptr));
FML_DCHECK((index_count_ != 0) == (indices() != nullptr));
}
bool DlVertices::operator==(DlVertices const& other) const {
auto lists_equal = [](auto* a, auto* b, int count) {
if (a == nullptr || b == nullptr) {
return a == b;
}
for (int i = 0; i < count; i++) {
if (a[i] != b[i]) {
return false;
}
}
return true;
};
return //
mode_ == other.mode_ && //
vertex_count_ == other.vertex_count_ && //
lists_equal(vertices(), other.vertices(), vertex_count_) && //
lists_equal(texture_coordinates(), other.texture_coordinates(), //
vertex_count_) && //
lists_equal(colors(), other.colors(), vertex_count_) && //
index_count_ == other.index_count_ && //
lists_equal(indices(), other.indices(), index_count_);
}
DlVertices::Builder::Builder(DlVertexMode mode,
int vertex_count,
Flags flags,
int index_count)
: needs_texture_coords_(flags.has_texture_coordinates),
needs_colors_(flags.has_colors),
needs_indices_(index_count > 0) {
vertex_count = std::max(vertex_count, 0);
index_count = std::max(index_count, 0);
void* storage =
::operator new(bytes_needed(vertex_count, flags, index_count));
vertices_.reset(new (storage)
DlVertices(mode, vertex_count, flags, index_count),
DlVerticesDeleter);
}
static void store_points(char* dst, int offset, const float* src, int count) {
SkPoint* points = reinterpret_cast<SkPoint*>(dst + offset);
for (int i = 0; i < count; i++) {
points[i] = SkPoint::Make(src[i * 2], src[i * 2 + 1]);
}
}
void DlVertices::Builder::store_vertices(const SkPoint vertices[]) {
FML_CHECK(is_valid());
FML_CHECK(needs_vertices_);
char* pod = reinterpret_cast<char*>(vertices_.get());
size_t bytes = vertices_->vertex_count_ * sizeof(vertices[0]);
memcpy(pod + vertices_->vertices_offset_, vertices, bytes);
needs_vertices_ = false;
}
void DlVertices::Builder::store_vertices(const float vertices[]) {
FML_CHECK(is_valid());
FML_CHECK(needs_vertices_);
char* pod = reinterpret_cast<char*>(vertices_.get());
store_points(pod, vertices_->vertices_offset_, vertices,
vertices_->vertex_count_);
needs_vertices_ = false;
}
void DlVertices::Builder::store_texture_coordinates(const SkPoint coords[]) {
FML_CHECK(is_valid());
FML_CHECK(needs_texture_coords_);
char* pod = reinterpret_cast<char*>(vertices_.get());
size_t bytes = vertices_->vertex_count_ * sizeof(coords[0]);
memcpy(pod + vertices_->texture_coordinates_offset_, coords, bytes);
needs_texture_coords_ = false;
}
void DlVertices::Builder::store_texture_coordinates(const float coords[]) {
FML_CHECK(is_valid());
FML_CHECK(needs_texture_coords_);
char* pod = reinterpret_cast<char*>(vertices_.get());
store_points(pod, vertices_->texture_coordinates_offset_, coords,
vertices_->vertex_count_);
needs_texture_coords_ = false;
}
void DlVertices::Builder::store_colors(const DlColor colors[]) {
FML_CHECK(is_valid());
FML_CHECK(needs_colors_);
char* pod = reinterpret_cast<char*>(vertices_.get());
size_t bytes = vertices_->vertex_count_ * sizeof(colors[0]);
memcpy(pod + vertices_->colors_offset_, colors, bytes);
needs_colors_ = false;
}
void DlVertices::Builder::store_indices(const uint16_t indices[]) {
FML_CHECK(is_valid());
FML_CHECK(needs_indices_);
char* pod = reinterpret_cast<char*>(vertices_.get());
size_t bytes = vertices_->index_count_ * sizeof(indices[0]);
memcpy(pod + vertices_->indices_offset_, indices, bytes);
needs_indices_ = false;
}
std::shared_ptr<DlVertices> DlVertices::Builder::build() {
FML_CHECK(is_valid());
if (vertices_->vertex_count() <= 0) {
// We set this to true in the constructor to make sure that they
// call store_vertices() only once, but if there are no vertices
// then we will not object to them never having stored any vertices
needs_vertices_ = false;
}
FML_CHECK(!needs_vertices_);
FML_CHECK(!needs_texture_coords_);
FML_CHECK(!needs_colors_);
FML_CHECK(!needs_indices_);
vertices_->bounds_ =
compute_bounds(vertices_->vertices(), vertices_->vertex_count_);
return std::move(vertices_);
}
} // namespace flutter
| engine/display_list/dl_vertices.cc/0 | {
"file_path": "engine/display_list/dl_vertices.cc",
"repo_id": "engine",
"token_count": 4318
} | 166 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_DISPLAY_LIST_EFFECTS_DL_PATH_EFFECT_H_
#define FLUTTER_DISPLAY_LIST_EFFECTS_DL_PATH_EFFECT_H_
#include <optional>
#include "flutter/display_list/dl_attributes.h"
#include "flutter/fml/logging.h"
#include "third_party/skia/include/core/SkRect.h"
namespace flutter {
class DlDashPathEffect;
// The DisplayList PathEffect class. This class implements all of the
// facilities and adheres to the design goals of the |DlAttribute| base
// class.
// An enumerated type for the supported PathEffect operations.
enum class DlPathEffectType {
kDash,
};
class DlPathEffect : public DlAttribute<DlPathEffect, DlPathEffectType> {
public:
virtual const DlDashPathEffect* asDash() const { return nullptr; }
virtual std::optional<SkRect> effect_bounds(SkRect&) const = 0;
protected:
DlPathEffect() = default;
private:
FML_DISALLOW_COPY_ASSIGN_AND_MOVE(DlPathEffect);
};
/// The DashPathEffect which breaks a path up into dash segments, and it
/// only affects stroked paths.
/// intervals: array containing an even number of entries (>=2), with
/// the even indices specifying the length of "on" intervals, and the odd
/// indices specifying the length of "off" intervals. This array will be
/// copied in Make, and can be disposed of freely after.
/// count: number of elements in the intervals array.
/// phase: initial distance into the intervals at which to start the dashing
/// effect for the path.
///
/// For example: if intervals[] = {10, 20}, count = 2, and phase = 25,
/// this will set up a dashed path like so:
/// 5 pixels off
/// 10 pixels on
/// 20 pixels off
/// 10 pixels on
/// 20 pixels off
/// ...
/// A phase of -5, 25, 55, 85, etc. would all result in the same path,
/// because the sum of all the intervals is 30.
///
class DlDashPathEffect final : public DlPathEffect {
public:
static std::shared_ptr<DlPathEffect> Make(const SkScalar intervals[],
int count,
SkScalar phase);
DlPathEffectType type() const override { return DlPathEffectType::kDash; }
size_t size() const override {
return sizeof(*this) + sizeof(SkScalar) * count_;
}
std::shared_ptr<DlPathEffect> shared() const override {
return Make(intervals(), count_, phase_);
}
const DlDashPathEffect* asDash() const override { return this; }
const SkScalar* intervals() const {
return reinterpret_cast<const SkScalar*>(this + 1);
}
int count() const { return count_; }
SkScalar phase() const { return phase_; }
std::optional<SkRect> effect_bounds(SkRect& rect) const override;
protected:
bool equals_(DlPathEffect const& other) const override {
FML_DCHECK(other.type() == DlPathEffectType::kDash);
auto that = static_cast<DlDashPathEffect const*>(&other);
return count_ == that->count_ && phase_ == that->phase_ &&
memcmp(intervals(), that->intervals(), sizeof(SkScalar) * count_) ==
0;
}
private:
// DlDashPathEffect constructor assumes the caller has prealloced storage for
// the intervals. If the intervals is nullptr the intervals will
// uninitialized.
DlDashPathEffect(const SkScalar intervals[], int count, SkScalar phase)
: count_(count), phase_(phase) {
if (intervals != nullptr) {
SkScalar* intervals_ = reinterpret_cast<SkScalar*>(this + 1);
memcpy(intervals_, intervals, sizeof(SkScalar) * count);
}
}
explicit DlDashPathEffect(const DlDashPathEffect* dash_effect)
: DlDashPathEffect(dash_effect->intervals(),
dash_effect->count_,
dash_effect->phase_) {}
SkScalar* intervals_unsafe() { return reinterpret_cast<SkScalar*>(this + 1); }
int count_;
SkScalar phase_;
friend class DisplayListBuilder;
friend class DlPathEffect;
FML_DISALLOW_COPY_ASSIGN_AND_MOVE(DlDashPathEffect);
};
} // namespace flutter
#endif // FLUTTER_DISPLAY_LIST_EFFECTS_DL_PATH_EFFECT_H_
| engine/display_list/effects/dl_path_effect.h/0 | {
"file_path": "engine/display_list/effects/dl_path_effect.h",
"repo_id": "engine",
"token_count": 1445
} | 167 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/display_list/skia/dl_sk_conversions.h"
#include "third_party/skia/include/core/SkColorFilter.h"
#include "third_party/skia/include/effects/SkGradientShader.h"
#include "third_party/skia/include/effects/SkImageFilters.h"
namespace flutter {
// clang-format off
constexpr float kInvertColorMatrix[20] = {
-1.0, 0, 0, 1.0, 0,
0, -1.0, 0, 1.0, 0,
0, 0, -1.0, 1.0, 0,
1.0, 1.0, 1.0, 1.0, 0
};
// clang-format on
SkPaint ToSk(const DlPaint& paint) {
SkPaint sk_paint;
sk_paint.setAntiAlias(paint.isAntiAlias());
sk_paint.setColor(ToSk(paint.getColor()));
sk_paint.setBlendMode(ToSk(paint.getBlendMode()));
sk_paint.setStyle(ToSk(paint.getDrawStyle()));
sk_paint.setStrokeWidth(paint.getStrokeWidth());
sk_paint.setStrokeMiter(paint.getStrokeMiter());
sk_paint.setStrokeCap(ToSk(paint.getStrokeCap()));
sk_paint.setStrokeJoin(ToSk(paint.getStrokeJoin()));
sk_paint.setImageFilter(ToSk(paint.getImageFilterPtr()));
auto color_filter = ToSk(paint.getColorFilterPtr());
if (paint.isInvertColors()) {
auto invert_filter = SkColorFilters::Matrix(kInvertColorMatrix);
if (color_filter) {
invert_filter = invert_filter->makeComposed(color_filter);
}
color_filter = invert_filter;
}
sk_paint.setColorFilter(color_filter);
auto color_source = paint.getColorSourcePtr();
if (color_source) {
// Unconditionally set dither to true for gradient shaders.
sk_paint.setDither(color_source->isGradient());
sk_paint.setShader(ToSk(color_source));
}
sk_paint.setMaskFilter(ToSk(paint.getMaskFilterPtr()));
sk_paint.setPathEffect(ToSk(paint.getPathEffectPtr()));
return sk_paint;
}
SkPaint ToStrokedSk(const DlPaint& paint) {
DlPaint stroked_paint = paint;
stroked_paint.setDrawStyle(DlDrawStyle::kStroke);
return ToSk(stroked_paint);
}
SkPaint ToNonShaderSk(const DlPaint& paint) {
DlPaint non_shader_paint = paint;
non_shader_paint.setColorSource(nullptr);
return ToSk(non_shader_paint);
}
sk_sp<SkShader> ToSk(const DlColorSource* source) {
if (!source) {
return nullptr;
}
static auto ToSkColors = [](const DlGradientColorSourceBase* gradient) {
return reinterpret_cast<const SkColor*>(gradient->colors());
};
switch (source->type()) {
case DlColorSourceType::kColor: {
const DlColorColorSource* color_source = source->asColor();
FML_DCHECK(color_source != nullptr);
return SkShaders::Color(ToSk(color_source->color()));
}
case DlColorSourceType::kImage: {
const DlImageColorSource* image_source = source->asImage();
FML_DCHECK(image_source != nullptr);
auto image = image_source->image();
if (!image || !image->skia_image()) {
return nullptr;
}
return image->skia_image()->makeShader(
ToSk(image_source->horizontal_tile_mode()),
ToSk(image_source->vertical_tile_mode()),
ToSk(image_source->sampling()), image_source->matrix_ptr());
}
case DlColorSourceType::kLinearGradient: {
const DlLinearGradientColorSource* linear_source =
source->asLinearGradient();
FML_DCHECK(linear_source != nullptr);
SkPoint pts[] = {linear_source->start_point(),
linear_source->end_point()};
return SkGradientShader::MakeLinear(
pts, ToSkColors(linear_source), linear_source->stops(),
linear_source->stop_count(), ToSk(linear_source->tile_mode()), 0,
linear_source->matrix_ptr());
}
case DlColorSourceType::kRadialGradient: {
const DlRadialGradientColorSource* radial_source =
source->asRadialGradient();
FML_DCHECK(radial_source != nullptr);
return SkGradientShader::MakeRadial(
radial_source->center(), radial_source->radius(),
ToSkColors(radial_source), radial_source->stops(),
radial_source->stop_count(), ToSk(radial_source->tile_mode()), 0,
radial_source->matrix_ptr());
}
case DlColorSourceType::kConicalGradient: {
const DlConicalGradientColorSource* conical_source =
source->asConicalGradient();
FML_DCHECK(conical_source != nullptr);
return SkGradientShader::MakeTwoPointConical(
conical_source->start_center(), conical_source->start_radius(),
conical_source->end_center(), conical_source->end_radius(),
ToSkColors(conical_source), conical_source->stops(),
conical_source->stop_count(), ToSk(conical_source->tile_mode()), 0,
conical_source->matrix_ptr());
}
case DlColorSourceType::kSweepGradient: {
const DlSweepGradientColorSource* sweep_source =
source->asSweepGradient();
FML_DCHECK(sweep_source != nullptr);
return SkGradientShader::MakeSweep(
sweep_source->center().x(), sweep_source->center().y(),
ToSkColors(sweep_source), sweep_source->stops(),
sweep_source->stop_count(), ToSk(sweep_source->tile_mode()),
sweep_source->start(), sweep_source->end(), 0,
sweep_source->matrix_ptr());
}
case DlColorSourceType::kRuntimeEffect: {
const DlRuntimeEffectColorSource* runtime_source =
source->asRuntimeEffect();
FML_DCHECK(runtime_source != nullptr);
auto runtime_effect = runtime_source->runtime_effect();
if (!runtime_effect || !runtime_effect->skia_runtime_effect()) {
return nullptr;
}
auto samplers = runtime_source->samplers();
std::vector<sk_sp<SkShader>> sk_samplers(samplers.size());
for (size_t i = 0; i < samplers.size(); i++) {
auto sampler = samplers[i];
if (sampler == nullptr) {
return nullptr;
}
sk_samplers[i] = ToSk(sampler);
}
auto uniform_data = runtime_source->uniform_data();
auto ref = new std::shared_ptr<std::vector<uint8_t>>(uniform_data);
auto sk_uniform_data = SkData::MakeWithProc(
uniform_data->data(), uniform_data->size(),
[](const void* ptr, void* context) {
delete reinterpret_cast<std::shared_ptr<std::vector<uint8_t>>*>(
context);
},
ref);
return runtime_effect->skia_runtime_effect()->makeShader(
sk_uniform_data, sk_samplers.data(), sk_samplers.size());
}
#ifdef IMPELLER_ENABLE_3D
case DlColorSourceType::kScene: {
return nullptr;
}
#endif // IMPELLER_ENABLE_3D
}
}
sk_sp<SkImageFilter> ToSk(const DlImageFilter* filter) {
if (!filter) {
return nullptr;
}
switch (filter->type()) {
case DlImageFilterType::kBlur: {
const DlBlurImageFilter* blur_filter = filter->asBlur();
FML_DCHECK(blur_filter != nullptr);
return SkImageFilters::Blur(blur_filter->sigma_x(),
blur_filter->sigma_y(),
ToSk(blur_filter->tile_mode()), nullptr);
}
case DlImageFilterType::kDilate: {
const DlDilateImageFilter* dilate_filter = filter->asDilate();
FML_DCHECK(dilate_filter != nullptr);
return SkImageFilters::Dilate(dilate_filter->radius_x(),
dilate_filter->radius_y(), nullptr);
}
case DlImageFilterType::kErode: {
const DlErodeImageFilter* erode_filter = filter->asErode();
FML_DCHECK(erode_filter != nullptr);
return SkImageFilters::Erode(erode_filter->radius_x(),
erode_filter->radius_y(), nullptr);
}
case DlImageFilterType::kMatrix: {
const DlMatrixImageFilter* matrix_filter = filter->asMatrix();
FML_DCHECK(matrix_filter != nullptr);
return SkImageFilters::MatrixTransform(
matrix_filter->matrix(), ToSk(matrix_filter->sampling()), nullptr);
}
case DlImageFilterType::kCompose: {
const DlComposeImageFilter* compose_filter = filter->asCompose();
FML_DCHECK(compose_filter != nullptr);
return SkImageFilters::Compose(ToSk(compose_filter->outer()),
ToSk(compose_filter->inner()));
}
case DlImageFilterType::kColorFilter: {
const DlColorFilterImageFilter* cf_filter = filter->asColorFilter();
FML_DCHECK(cf_filter != nullptr);
return SkImageFilters::ColorFilter(ToSk(cf_filter->color_filter()),
nullptr);
}
case DlImageFilterType::kLocalMatrix: {
const DlLocalMatrixImageFilter* lm_filter = filter->asLocalMatrix();
FML_DCHECK(lm_filter != nullptr);
sk_sp<SkImageFilter> skia_filter = ToSk(lm_filter->image_filter());
// The image_filter property itself might have been null, or the
// construction of the SkImageFilter might be optimized to null
// for any number of reasons. In any case, if the filter is null
// or optimizaed away, let's then optimize away this local matrix
// case by returning null.
if (!skia_filter) {
return nullptr;
}
return skia_filter->makeWithLocalMatrix(lm_filter->matrix());
}
}
}
sk_sp<SkColorFilter> ToSk(const DlColorFilter* filter) {
if (!filter) {
return nullptr;
}
switch (filter->type()) {
case DlColorFilterType::kBlend: {
const DlBlendColorFilter* blend_filter = filter->asBlend();
FML_DCHECK(blend_filter != nullptr);
return SkColorFilters::Blend(ToSk(blend_filter->color()),
ToSk(blend_filter->mode()));
}
case DlColorFilterType::kMatrix: {
const DlMatrixColorFilter* matrix_filter = filter->asMatrix();
FML_DCHECK(matrix_filter != nullptr);
float matrix[20];
matrix_filter->get_matrix(matrix);
return SkColorFilters::Matrix(matrix);
}
case DlColorFilterType::kSrgbToLinearGamma: {
return SkColorFilters::SRGBToLinearGamma();
}
case DlColorFilterType::kLinearToSrgbGamma: {
return SkColorFilters::LinearToSRGBGamma();
}
}
}
sk_sp<SkMaskFilter> ToSk(const DlMaskFilter* filter) {
if (!filter) {
return nullptr;
}
switch (filter->type()) {
case DlMaskFilterType::kBlur: {
const DlBlurMaskFilter* blur_filter = filter->asBlur();
FML_DCHECK(blur_filter != nullptr);
return SkMaskFilter::MakeBlur(ToSk(blur_filter->style()),
blur_filter->sigma(),
blur_filter->respectCTM());
}
}
}
sk_sp<SkPathEffect> ToSk(const DlPathEffect* effect) {
if (!effect) {
return nullptr;
}
switch (effect->type()) {
case DlPathEffectType::kDash: {
const DlDashPathEffect* dash_effect = effect->asDash();
FML_DCHECK(dash_effect != nullptr);
return SkDashPathEffect::Make(dash_effect->intervals(),
dash_effect->count(), dash_effect->phase());
}
}
}
sk_sp<SkVertices> ToSk(const DlVertices* vertices) {
const SkColor* sk_colors =
reinterpret_cast<const SkColor*>(vertices->colors());
return SkVertices::MakeCopy(ToSk(vertices->mode()), vertices->vertex_count(),
vertices->vertices(),
vertices->texture_coordinates(), sk_colors,
vertices->index_count(), vertices->indices());
}
} // namespace flutter
| engine/display_list/skia/dl_sk_conversions.cc/0 | {
"file_path": "engine/display_list/skia/dl_sk_conversions.cc",
"repo_id": "engine",
"token_count": 4951
} | 168 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/display_list/testing/dl_test_surface_metal.h"
#include "flutter/impeller/display_list/dl_dispatcher.h"
#include "flutter/impeller/display_list/dl_image_impeller.h"
#include "flutter/impeller/typographer/backends/skia/typographer_context_skia.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkSurface.h"
namespace flutter {
namespace testing {
class DlMetalSurfaceInstance : public DlSurfaceInstance {
public:
explicit DlMetalSurfaceInstance(
std::unique_ptr<TestMetalSurface> metal_surface)
: metal_surface_(std::move(metal_surface)) {}
~DlMetalSurfaceInstance() = default;
sk_sp<SkSurface> sk_surface() const override {
return metal_surface_->GetSurface();
}
private:
std::unique_ptr<TestMetalSurface> metal_surface_;
};
bool DlMetalSurfaceProvider::InitializeSurface(size_t width,
size_t height,
PixelFormat format) {
if (format != kN32PremulPixelFormat) {
return false;
}
metal_context_ = std::make_unique<TestMetalContext>();
metal_surface_ = MakeOffscreenSurface(width, height, format);
return true;
}
std::shared_ptr<DlSurfaceInstance> DlMetalSurfaceProvider::GetPrimarySurface()
const {
if (!metal_surface_) {
return nullptr;
}
return metal_surface_;
}
std::shared_ptr<DlSurfaceInstance> DlMetalSurfaceProvider::MakeOffscreenSurface(
size_t width,
size_t height,
PixelFormat format) const {
auto surface =
TestMetalSurface::Create(*metal_context_, SkISize::Make(width, height));
surface->GetSurface()->getCanvas()->clear(SK_ColorTRANSPARENT);
return std::make_shared<DlMetalSurfaceInstance>(std::move(surface));
}
class DlMetalPixelData : public DlPixelData {
public:
explicit DlMetalPixelData(
std::unique_ptr<impeller::testing::Screenshot> screenshot)
: screenshot_(std::move(screenshot)),
addr_(reinterpret_cast<const uint32_t*>(screenshot_->GetBytes())),
ints_per_row_(screenshot_->GetBytesPerRow() / 4) {
FML_DCHECK(screenshot_->GetBytesPerRow() == ints_per_row_ * 4);
}
~DlMetalPixelData() override = default;
const uint32_t* addr32(int x, int y) const override {
return addr_ + (y * ints_per_row_) + x;
}
size_t width() const override { return screenshot_->GetWidth(); }
size_t height() const override { return screenshot_->GetHeight(); }
void write(const std::string& path) const override {
screenshot_->WriteToPNG(path);
}
private:
std::unique_ptr<impeller::testing::Screenshot> screenshot_;
const uint32_t* addr_;
const uint32_t ints_per_row_;
};
sk_sp<DlPixelData> DlMetalSurfaceProvider::ImpellerSnapshot(
const sk_sp<DisplayList>& list,
int width,
int height) const {
InitScreenShotter();
impeller::DlDispatcher dispatcher;
dispatcher.drawColor(flutter::DlColor::kTransparent(),
flutter::DlBlendMode::kSrc);
list->Dispatch(dispatcher);
auto picture = dispatcher.EndRecordingAsPicture();
return sk_make_sp<DlMetalPixelData>(snapshotter_->MakeScreenshot(
*aiks_context_, picture, {width, height}, false));
}
sk_sp<DlImage> DlMetalSurfaceProvider::MakeImpellerImage(
const sk_sp<DisplayList>& list,
int width,
int height) const {
InitScreenShotter();
impeller::DlDispatcher dispatcher;
dispatcher.drawColor(flutter::DlColor::kTransparent(),
flutter::DlBlendMode::kSrc);
list->Dispatch(dispatcher);
auto picture = dispatcher.EndRecordingAsPicture();
std::shared_ptr<impeller::Image> image =
picture.ToImage(*aiks_context_, {width, height});
std::shared_ptr<impeller::Texture> texture = image->GetTexture();
return impeller::DlImageImpeller::Make(texture);
}
void DlMetalSurfaceProvider::InitScreenShotter() const {
if (!snapshotter_) {
snapshotter_.reset(new MetalScreenshotter());
auto typographer = impeller::TypographerContextSkia::Make();
aiks_context_.reset(new impeller::AiksContext(
snapshotter_->GetPlayground().GetContext(), typographer));
}
}
} // namespace testing
} // namespace flutter
| engine/display_list/testing/dl_test_surface_metal.cc/0 | {
"file_path": "engine/display_list/testing/dl_test_surface_metal.cc",
"repo_id": "engine",
"token_count": 1611
} | 169 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <cassert>
#include <chrono>
#include <iostream>
#define GLFW_EXPOSE_NATIVE_EGL
#define GLFW_INCLUDE_GLEXT
#include <EGL/egl.h>
#include <EGL/eglext.h>
#include <array>
#include <cstring>
#include <list>
#include <unordered_map>
#include "GLFW/glfw3.h"
#include "GLFW/glfw3native.h"
#include "embedder.h"
// This value is calculated after the window is created.
static double g_pixelRatio = 1.0;
static const size_t kInitialWindowWidth = 800;
static const size_t kInitialWindowHeight = 600;
// Maximum damage history - for triple buffering we need to store damage for
// last two frames; Some Android devices (Pixel 4) use quad buffering.
static const int kMaxHistorySize = 10;
static constexpr FlutterViewId kImplicitViewId = 0;
// Keeps track of the most recent frame damages so that existing damage can
// be easily computed.
std::list<FlutterRect> damage_history_;
// Keeps track of the existing damage associated with each FBO ID
std::unordered_map<intptr_t, FlutterRect*> existing_damage_map_;
EGLDisplay display_;
EGLSurface surface_;
static_assert(FLUTTER_ENGINE_VERSION == 1,
"This Flutter Embedder was authored against the stable Flutter "
"API at version 1. There has been a serious breakage in the "
"API. Please read the ChangeLog and take appropriate action "
"before updating this assertion");
void GLFWcursorPositionCallbackAtPhase(GLFWwindow* window,
FlutterPointerPhase phase,
double x,
double y) {
FlutterPointerEvent event = {};
event.struct_size = sizeof(event);
event.phase = phase;
event.x = x * g_pixelRatio;
event.y = y * g_pixelRatio;
event.timestamp =
std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::high_resolution_clock::now().time_since_epoch())
.count();
// This example only supports a single window, therefore we assume the pointer
// event occurred in the only view, the implicit view.
event.view_id = kImplicitViewId;
FlutterEngineSendPointerEvent(
reinterpret_cast<FlutterEngine>(glfwGetWindowUserPointer(window)), &event,
1);
}
void GLFWcursorPositionCallback(GLFWwindow* window, double x, double y) {
GLFWcursorPositionCallbackAtPhase(window, FlutterPointerPhase::kMove, x, y);
}
void GLFWmouseButtonCallback(GLFWwindow* window,
int key,
int action,
int mods) {
if (key == GLFW_MOUSE_BUTTON_1 && action == GLFW_PRESS) {
double x, y;
glfwGetCursorPos(window, &x, &y);
GLFWcursorPositionCallbackAtPhase(window, FlutterPointerPhase::kDown, x, y);
glfwSetCursorPosCallback(window, GLFWcursorPositionCallback);
}
if (key == GLFW_MOUSE_BUTTON_1 && action == GLFW_RELEASE) {
double x, y;
glfwGetCursorPos(window, &x, &y);
GLFWcursorPositionCallbackAtPhase(window, FlutterPointerPhase::kUp, x, y);
glfwSetCursorPosCallback(window, nullptr);
}
}
static void GLFWKeyCallback(GLFWwindow* window,
int key,
int scancode,
int action,
int mods) {
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) {
glfwSetWindowShouldClose(window, GLFW_TRUE);
}
}
void GLFWwindowSizeCallback(GLFWwindow* window, int width, int height) {
FlutterWindowMetricsEvent event = {};
event.struct_size = sizeof(event);
event.width = width * g_pixelRatio;
event.height = height * g_pixelRatio;
event.pixel_ratio = g_pixelRatio;
// This example only supports a single window, therefore we assume the event
// occurred in the only view, the implicit view.
event.view_id = kImplicitViewId;
FlutterEngineSendWindowMetricsEvent(
reinterpret_cast<FlutterEngine>(glfwGetWindowUserPointer(window)),
&event);
}
// Auxiliary function used to transform a FlutterRect into the format that is
// expected by the EGL functions (i.e. array of EGLint).
static std::array<EGLint, 4> RectToInts(const FlutterRect rect) {
EGLint height;
eglQuerySurface(display_, surface_, EGL_HEIGHT, &height);
std::array<EGLint, 4> res{
static_cast<int>(rect.left), height - static_cast<int>(rect.bottom),
static_cast<int>(rect.right) - static_cast<int>(rect.left),
static_cast<int>(rect.bottom) - static_cast<int>(rect.top)};
return res;
}
// Auxiliary function to union the damage regions comprised by two FlutterRect
// element. It saves the result of this join in the rect variable.
static void JoinFlutterRect(FlutterRect* rect, FlutterRect additional_rect) {
rect->left = std::min(rect->left, additional_rect.left);
rect->top = std::min(rect->top, additional_rect.top);
rect->right = std::max(rect->right, additional_rect.right);
rect->bottom = std::max(rect->bottom, additional_rect.bottom);
}
// Auxiliary function used to check if the given list of extensions contains the
// requested extension name.
static bool HasExtension(const char* extensions, const char* name) {
const char* r = strstr(extensions, name);
auto len = strlen(name);
// check that the extension name is terminated by space or null terminator
return r != nullptr && (r[len] == ' ' || r[len] == 0);
}
bool RunFlutter(GLFWwindow* window,
const std::string& project_path,
const std::string& icudtl_path) {
FlutterRendererConfig config = {};
config.type = kOpenGL;
config.open_gl.struct_size = sizeof(config.open_gl);
config.open_gl.make_current = [](void* userdata) -> bool {
glfwMakeContextCurrent(static_cast<GLFWwindow*>(userdata));
return true;
};
config.open_gl.clear_current = [](void*) -> bool {
glfwMakeContextCurrent(nullptr); // is this even a thing?
return true;
};
config.open_gl.present_with_info =
[](void* userdata, const FlutterPresentInfo* info) -> bool {
// Free the existing damage that was allocated to this frame.
if (existing_damage_map_[info->fbo_id] != nullptr) {
free(existing_damage_map_[info->fbo_id]);
existing_damage_map_[info->fbo_id] = nullptr;
}
// Get list of extensions.
const char* extensions = eglQueryString(display_, EGL_EXTENSIONS);
// Retrieve the set damage region function.
PFNEGLSETDAMAGEREGIONKHRPROC set_damage_region_ = nullptr;
if (HasExtension(extensions, "EGL_KHR_partial_update")) {
set_damage_region_ = reinterpret_cast<PFNEGLSETDAMAGEREGIONKHRPROC>(
eglGetProcAddress("eglSetDamageRegionKHR"));
}
// Retrieve the swap buffers with damage function.
PFNEGLSWAPBUFFERSWITHDAMAGEEXTPROC swap_buffers_with_damage_ = nullptr;
if (HasExtension(extensions, "EGL_EXT_swap_buffers_with_damage")) {
swap_buffers_with_damage_ =
reinterpret_cast<PFNEGLSWAPBUFFERSWITHDAMAGEEXTPROC>(
eglGetProcAddress("eglSwapBuffersWithDamageEXT"));
} else if (HasExtension(extensions, "EGL_KHR_swap_buffers_with_damage")) {
swap_buffers_with_damage_ =
reinterpret_cast<PFNEGLSWAPBUFFERSWITHDAMAGEEXTPROC>(
eglGetProcAddress("eglSwapBuffersWithDamageKHR"));
}
if (set_damage_region_) {
// Set the buffer damage as the damage region.
auto buffer_rects = RectToInts(info->buffer_damage.damage[0]);
set_damage_region_(display_, surface_, buffer_rects.data(), 1);
}
// Add frame damage to damage history
damage_history_.push_back(info->frame_damage.damage[0]);
if (damage_history_.size() > kMaxHistorySize) {
damage_history_.pop_front();
}
if (swap_buffers_with_damage_) {
// Swap buffers with frame damage.
auto frame_rects = RectToInts(info->frame_damage.damage[0]);
return swap_buffers_with_damage_(display_, surface_, frame_rects.data(),
1);
} else {
// If the required extensions for partial repaint were not provided, do
// full repaint.
return eglSwapBuffers(display_, surface_);
}
};
config.open_gl.fbo_callback = [](void*) -> uint32_t {
return 0; // FBO0
};
config.open_gl.populate_existing_damage =
[](void* userdata, intptr_t fbo_id,
FlutterDamage* existing_damage) -> void {
// Given the FBO age, create existing damage region by joining all frame
// damages since FBO was last used
EGLint age;
if (glfwExtensionSupported("GL_EXT_buffer_age") == GLFW_TRUE) {
eglQuerySurface(display_, surface_, EGL_BUFFER_AGE_EXT, &age);
} else {
age = 4; // Virtually no driver should have a swapchain length > 4.
}
existing_damage->num_rects = 1;
// Allocate the array of rectangles for the existing damage.
existing_damage_map_[fbo_id] = static_cast<FlutterRect*>(
malloc(sizeof(FlutterRect) * existing_damage->num_rects));
existing_damage_map_[fbo_id][0] =
FlutterRect{0, 0, kInitialWindowWidth, kInitialWindowHeight};
existing_damage->damage = existing_damage_map_[fbo_id];
if (age > 1) {
--age;
// join up to (age - 1) last rects from damage history
for (auto i = damage_history_.rbegin();
i != damage_history_.rend() && age > 0; ++i, --age) {
if (i == damage_history_.rbegin()) {
if (i != damage_history_.rend()) {
existing_damage->damage[0] = {i->left, i->top, i->right, i->bottom};
}
} else {
JoinFlutterRect(&(existing_damage->damage[0]), *i);
}
}
}
};
config.open_gl.gl_proc_resolver = [](void*, const char* name) -> void* {
return reinterpret_cast<void*>(glfwGetProcAddress(name));
};
config.open_gl.fbo_reset_after_present = true;
// This directory is generated by `flutter build bundle`.
std::string assets_path = project_path + "/build/flutter_assets";
FlutterProjectArgs args = {
.struct_size = sizeof(FlutterProjectArgs),
.assets_path = assets_path.c_str(),
.icu_data_path =
icudtl_path.c_str(), // Find this in your bin/cache directory.
};
FlutterEngine engine = nullptr;
FlutterEngineResult result =
FlutterEngineRun(FLUTTER_ENGINE_VERSION, &config, // renderer
&args, window, &engine);
if (result != kSuccess || engine == nullptr) {
std::cout << "Could not run the Flutter Engine." << std::endl;
return false;
}
glfwSetWindowUserPointer(window, engine);
GLFWwindowSizeCallback(window, kInitialWindowWidth, kInitialWindowHeight);
return true;
}
void printUsage() {
std::cout
<< "usage: embedder_example_drm <path to project> <path to icudtl.dat>"
<< std::endl;
}
void GLFW_ErrorCallback(int error, const char* description) {
std::cout << "GLFW Error: (" << error << ") " << description << std::endl;
}
int main(int argc, const char* argv[]) {
if (argc != 3) {
printUsage();
return 1;
}
std::string project_path = argv[1];
std::string icudtl_path = argv[2];
glfwSetErrorCallback(GLFW_ErrorCallback);
int result = glfwInit();
if (result != GLFW_TRUE) {
std::cout << "Could not initialize GLFW." << std::endl;
return EXIT_FAILURE;
}
#if defined(__linux__)
glfwWindowHint(GLFW_CONTEXT_CREATION_API, GLFW_EGL_CONTEXT_API);
#endif
GLFWwindow* window = glfwCreateWindow(
kInitialWindowWidth, kInitialWindowHeight, "Flutter", NULL, NULL);
if (window == nullptr) {
std::cout << "Could not create GLFW window." << std::endl;
return EXIT_FAILURE;
}
int framebuffer_width, framebuffer_height;
glfwGetFramebufferSize(window, &framebuffer_width, &framebuffer_height);
g_pixelRatio = framebuffer_width / kInitialWindowWidth;
// Get the display and surface variables.
display_ = glfwGetEGLDisplay();
surface_ = glfwGetEGLSurface(window);
bool run_result = RunFlutter(window, project_path, icudtl_path);
if (!run_result) {
std::cout << "Could not run the Flutter engine." << std::endl;
return EXIT_FAILURE;
}
glfwSetKeyCallback(window, GLFWKeyCallback);
glfwSetWindowSizeCallback(window, GLFWwindowSizeCallback);
glfwSetMouseButtonCallback(window, GLFWmouseButtonCallback);
while (!glfwWindowShouldClose(window)) {
glfwWaitEvents();
}
glfwDestroyWindow(window);
glfwTerminate();
return EXIT_SUCCESS;
}
| engine/examples/glfw_drm/FlutterEmbedderGLFW.cc/0 | {
"file_path": "engine/examples/glfw_drm/FlutterEmbedderGLFW.cc",
"repo_id": "engine",
"token_count": 4852
} | 170 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/flow/embedded_views.h"
#include "flutter/fml/logging.h"
#include "gtest/gtest.h"
namespace flutter {
namespace testing {
TEST(EmbeddedViewParams, GetBoundingRectAfterMutationsWithNoMutations) {
MutatorsStack stack;
SkMatrix matrix;
EmbeddedViewParams params(matrix, SkSize::Make(1, 1), stack);
const SkRect& rect = params.finalBoundingRect();
ASSERT_TRUE(SkScalarNearlyEqual(rect.x(), 0));
ASSERT_TRUE(SkScalarNearlyEqual(rect.y(), 0));
ASSERT_TRUE(SkScalarNearlyEqual(rect.width(), 1));
ASSERT_TRUE(SkScalarNearlyEqual(rect.height(), 1));
}
TEST(EmbeddedViewParams, GetBoundingRectAfterMutationsWithScale) {
MutatorsStack stack;
SkMatrix matrix = SkMatrix::Scale(2, 2);
stack.PushTransform(matrix);
EmbeddedViewParams params(matrix, SkSize::Make(1, 1), stack);
const SkRect& rect = params.finalBoundingRect();
ASSERT_TRUE(SkScalarNearlyEqual(rect.x(), 0));
ASSERT_TRUE(SkScalarNearlyEqual(rect.y(), 0));
ASSERT_TRUE(SkScalarNearlyEqual(rect.width(), 2));
ASSERT_TRUE(SkScalarNearlyEqual(rect.height(), 2));
}
TEST(EmbeddedViewParams, GetBoundingRectAfterMutationsWithTranslate) {
MutatorsStack stack;
SkMatrix matrix = SkMatrix::Translate(1, 1);
stack.PushTransform(matrix);
EmbeddedViewParams params(matrix, SkSize::Make(1, 1), stack);
const SkRect& rect = params.finalBoundingRect();
ASSERT_TRUE(SkScalarNearlyEqual(rect.x(), 1));
ASSERT_TRUE(SkScalarNearlyEqual(rect.y(), 1));
ASSERT_TRUE(SkScalarNearlyEqual(rect.width(), 1));
ASSERT_TRUE(SkScalarNearlyEqual(rect.height(), 1));
}
TEST(EmbeddedViewParams, GetBoundingRectAfterMutationsWithRotation90) {
MutatorsStack stack;
SkMatrix matrix;
matrix.setRotate(90);
stack.PushTransform(matrix);
EmbeddedViewParams params(matrix, SkSize::Make(1, 1), stack);
const SkRect& rect = params.finalBoundingRect();
ASSERT_TRUE(SkScalarNearlyEqual(rect.x(), -1));
ASSERT_TRUE(SkScalarNearlyEqual(rect.y(), 0));
ASSERT_TRUE(SkScalarNearlyEqual(rect.width(), 1));
ASSERT_TRUE(SkScalarNearlyEqual(rect.height(), 1));
}
TEST(EmbeddedViewParams, GetBoundingRectAfterMutationsWithRotation45) {
MutatorsStack stack;
SkMatrix matrix;
matrix.setRotate(45);
stack.PushTransform(matrix);
EmbeddedViewParams params(matrix, SkSize::Make(1, 1), stack);
const SkRect& rect = params.finalBoundingRect();
ASSERT_TRUE(SkScalarNearlyEqual(rect.x(), -sqrt(2) / 2));
ASSERT_TRUE(SkScalarNearlyEqual(rect.y(), 0));
ASSERT_TRUE(SkScalarNearlyEqual(rect.width(), sqrt(2)));
ASSERT_TRUE(SkScalarNearlyEqual(rect.height(), sqrt(2)));
}
TEST(EmbeddedViewParams,
GetBoundingRectAfterMutationsWithTranslateScaleAndRotation) {
SkMatrix matrix = SkMatrix::Translate(2, 2);
matrix.preScale(3, 3);
matrix.preRotate(90);
MutatorsStack stack;
stack.PushTransform(matrix);
EmbeddedViewParams params(matrix, SkSize::Make(1, 1), stack);
const SkRect& rect = params.finalBoundingRect();
ASSERT_TRUE(SkScalarNearlyEqual(rect.x(), -1));
ASSERT_TRUE(SkScalarNearlyEqual(rect.y(), 2));
ASSERT_TRUE(SkScalarNearlyEqual(rect.width(), 3));
ASSERT_TRUE(SkScalarNearlyEqual(rect.height(), 3));
}
} // namespace testing
} // namespace flutter
| engine/flow/embedded_view_params_unittests.cc/0 | {
"file_path": "engine/flow/embedded_view_params_unittests.cc",
"repo_id": "engine",
"token_count": 1241
} | 171 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_FLOW_LAYERS_CACHEABLE_LAYER_H_
#define FLUTTER_FLOW_LAYERS_CACHEABLE_LAYER_H_
#include <memory>
#include "flutter/flow/layers/container_layer.h"
#include "flutter/flow/layers/layer_raster_cache_item.h"
namespace flutter {
class AutoCache {
public:
AutoCache(RasterCacheItem* raster_cache_item,
PrerollContext* context,
const SkMatrix& matrix);
void ShouldNotBeCached() { raster_cache_item_ = nullptr; }
~AutoCache();
private:
inline bool IsCacheEnabled();
RasterCacheItem* raster_cache_item_ = nullptr;
PrerollContext* context_ = nullptr;
const SkMatrix matrix_;
};
class CacheableContainerLayer : public ContainerLayer {
public:
explicit CacheableContainerLayer(
int layer_cached_threshold =
RasterCacheUtil::kMinimumRendersBeforeCachingFilterLayer,
bool can_cache_children = false);
const LayerRasterCacheItem* raster_cache_item() const {
return layer_raster_cache_item_.get();
}
protected:
std::unique_ptr<LayerRasterCacheItem> layer_raster_cache_item_;
};
} // namespace flutter
#endif // FLUTTER_FLOW_LAYERS_CACHEABLE_LAYER_H_
| engine/flow/layers/cacheable_layer.h/0 | {
"file_path": "engine/flow/layers/cacheable_layer.h",
"repo_id": "engine",
"token_count": 472
} | 172 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_FLOW_LAYERS_CONTAINER_LAYER_H_
#define FLUTTER_FLOW_LAYERS_CONTAINER_LAYER_H_
#include <vector>
#include "flutter/flow/layers/layer.h"
namespace flutter {
class ContainerLayer : public Layer {
public:
ContainerLayer();
void Diff(DiffContext* context, const Layer* old_layer) override;
void PreservePaintRegion(DiffContext* context) override;
virtual void Add(std::shared_ptr<Layer> layer);
void Preroll(PrerollContext* context) override;
void Paint(PaintContext& context) const override;
const std::vector<std::shared_ptr<Layer>>& layers() const { return layers_; }
virtual void DiffChildren(DiffContext* context,
const ContainerLayer* old_layer);
void PaintChildren(PaintContext& context) const override;
const ContainerLayer* as_container_layer() const override { return this; }
const SkRect& child_paint_bounds() const { return child_paint_bounds_; }
void set_child_paint_bounds(const SkRect& bounds) {
child_paint_bounds_ = bounds;
}
int children_renderable_state_flags() const {
return children_renderable_state_flags_;
}
void set_children_renderable_state_flags(int flags) {
children_renderable_state_flags_ = flags;
}
protected:
void PrerollChildren(PrerollContext* context, SkRect* child_paint_bounds);
private:
std::vector<std::shared_ptr<Layer>> layers_;
SkRect child_paint_bounds_;
int children_renderable_state_flags_ = 0;
FML_DISALLOW_COPY_AND_ASSIGN(ContainerLayer);
};
} // namespace flutter
#endif // FLUTTER_FLOW_LAYERS_CONTAINER_LAYER_H_
| engine/flow/layers/container_layer.h/0 | {
"file_path": "engine/flow/layers/container_layer.h",
"repo_id": "engine",
"token_count": 592
} | 173 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "gtest/gtest.h"
#include "flutter/display_list/effects/dl_color_filter.h"
#include "flutter/display_list/effects/dl_image_filter.h"
#include "flutter/flow/layers/layer.h"
#include "flutter/flow/layers/layer_state_stack.h"
#include "flutter/testing/display_list_testing.h"
namespace flutter {
namespace testing {
#ifndef NDEBUG
TEST(LayerStateStack, AccessorsDieWithoutDelegate) {
LayerStateStack state_stack;
EXPECT_DEATH_IF_SUPPORTED(state_stack.device_cull_rect(),
"LayerStateStack state queried without a delegate");
EXPECT_DEATH_IF_SUPPORTED(state_stack.local_cull_rect(),
"LayerStateStack state queried without a delegate");
EXPECT_DEATH_IF_SUPPORTED(state_stack.transform_3x3(),
"LayerStateStack state queried without a delegate");
EXPECT_DEATH_IF_SUPPORTED(state_stack.transform_4x4(),
"LayerStateStack state queried without a delegate");
EXPECT_DEATH_IF_SUPPORTED(state_stack.content_culled({}),
"LayerStateStack state queried without a delegate");
{
// state_stack.set_preroll_delegate(kGiantRect, SkMatrix::I());
auto mutator = state_stack.save();
mutator.applyOpacity({}, 0.5);
state_stack.clear_delegate();
auto restore = state_stack.applyState({}, 0);
}
}
#endif
TEST(LayerStateStack, Defaults) {
LayerStateStack state_stack;
ASSERT_EQ(state_stack.canvas_delegate(), nullptr);
ASSERT_EQ(state_stack.checkerboard_func(), nullptr);
ASSERT_EQ(state_stack.outstanding_opacity(), SK_Scalar1);
ASSERT_EQ(state_stack.outstanding_color_filter(), nullptr);
ASSERT_EQ(state_stack.outstanding_image_filter(), nullptr);
ASSERT_EQ(state_stack.outstanding_bounds(), SkRect());
state_stack.set_preroll_delegate(kGiantRect, SkMatrix::I());
ASSERT_EQ(state_stack.device_cull_rect(), kGiantRect);
ASSERT_EQ(state_stack.local_cull_rect(), kGiantRect);
ASSERT_EQ(state_stack.transform_3x3(), SkMatrix::I());
ASSERT_EQ(state_stack.transform_4x4(), SkM44());
DlPaint dl_paint;
state_stack.fill(dl_paint);
ASSERT_EQ(dl_paint, DlPaint());
}
TEST(LayerStateStack, SingularDelegate) {
LayerStateStack state_stack;
ASSERT_EQ(state_stack.canvas_delegate(), nullptr);
// Two different DlCanvas implementators
DisplayListBuilder builder;
DisplayListBuilder builder2;
DlCanvas& canvas = builder2;
// no delegate -> builder delegate
state_stack.set_delegate(&builder);
ASSERT_EQ(state_stack.canvas_delegate(), &builder);
// builder delegate -> DlCanvas delegate
state_stack.set_delegate(&canvas);
ASSERT_EQ(state_stack.canvas_delegate(), &canvas);
// DlCanvas delegate -> builder delegate
state_stack.set_delegate(&builder);
ASSERT_EQ(state_stack.canvas_delegate(), &builder);
// builder delegate -> no delegate
state_stack.clear_delegate();
ASSERT_EQ(state_stack.canvas_delegate(), nullptr);
// DlCanvas delegate -> no delegate
state_stack.set_delegate(&canvas);
state_stack.clear_delegate();
ASSERT_EQ(state_stack.canvas_delegate(), nullptr);
}
TEST(LayerStateStack, OldDelegateIsRolledBack) {
LayerStateStack state_stack;
DisplayListBuilder builder;
DisplayListBuilder builder2;
DlCanvas& canvas = builder2;
ASSERT_TRUE(builder.GetTransform().isIdentity());
ASSERT_TRUE(canvas.GetTransform().isIdentity());
state_stack.set_delegate(&builder);
ASSERT_TRUE(builder.GetTransform().isIdentity());
ASSERT_TRUE(canvas.GetTransform().isIdentity());
auto mutator = state_stack.save();
mutator.translate({10, 10});
ASSERT_EQ(builder.GetTransform(), SkMatrix::Translate(10, 10));
ASSERT_TRUE(canvas.GetTransform().isIdentity());
state_stack.set_delegate(&canvas);
ASSERT_TRUE(builder.GetTransform().isIdentity());
ASSERT_EQ(canvas.GetTransform(), SkMatrix::Translate(10, 10));
state_stack.set_preroll_delegate(SkRect::MakeWH(100, 100));
ASSERT_TRUE(builder.GetTransform().isIdentity());
ASSERT_TRUE(canvas.GetTransform().isIdentity());
state_stack.set_delegate(&builder);
state_stack.clear_delegate();
ASSERT_TRUE(builder.GetTransform().isIdentity());
ASSERT_TRUE(canvas.GetTransform().isIdentity());
state_stack.set_delegate(&canvas);
state_stack.clear_delegate();
ASSERT_TRUE(builder.GetTransform().isIdentity());
ASSERT_TRUE(canvas.GetTransform().isIdentity());
}
TEST(LayerStateStack, Opacity) {
SkRect rect = {10, 10, 20, 20};
LayerStateStack state_stack;
state_stack.set_preroll_delegate(SkRect::MakeLTRB(0, 0, 50, 50));
{
auto mutator = state_stack.save();
mutator.applyOpacity(rect, 0.5f);
ASSERT_EQ(state_stack.outstanding_opacity(), 0.5f);
ASSERT_EQ(state_stack.outstanding_bounds(), rect);
// Check nested opacities multiply with each other
{
auto mutator2 = state_stack.save();
mutator.applyOpacity(rect, 0.5f);
ASSERT_EQ(state_stack.outstanding_opacity(), 0.25f);
ASSERT_EQ(state_stack.outstanding_bounds(), rect);
// Verify output with applyState that does not accept opacity
{
DisplayListBuilder builder;
state_stack.set_delegate(&builder);
{
auto restore = state_stack.applyState(rect, 0);
ASSERT_EQ(state_stack.outstanding_opacity(), SK_Scalar1);
ASSERT_EQ(state_stack.outstanding_bounds(), SkRect());
DlPaint paint;
state_stack.fill(paint);
builder.DrawRect(rect, paint);
}
state_stack.clear_delegate();
DisplayListBuilder expected;
DlPaint save_paint =
DlPaint().setOpacity(state_stack.outstanding_opacity());
expected.SaveLayer(&rect, &save_paint);
expected.DrawRect(rect, DlPaint());
expected.Restore();
ASSERT_TRUE(DisplayListsEQ_Verbose(builder.Build(), expected.Build()));
}
// Verify output with applyState that accepts opacity
{
DisplayListBuilder builder;
state_stack.set_delegate(&builder);
{
auto restore = state_stack.applyState(
rect, LayerStateStack::kCallerCanApplyOpacity);
ASSERT_EQ(state_stack.outstanding_opacity(), 0.25f);
ASSERT_EQ(state_stack.outstanding_bounds(), rect);
DlPaint paint;
state_stack.fill(paint);
builder.DrawRect(rect, paint);
}
state_stack.clear_delegate();
DisplayListBuilder expected;
expected.DrawRect(rect, DlPaint().setOpacity(0.25f));
ASSERT_TRUE(DisplayListsEQ_Verbose(builder.Build(), expected.Build()));
}
}
ASSERT_EQ(state_stack.outstanding_opacity(), 0.5f);
ASSERT_EQ(state_stack.outstanding_bounds(), rect);
}
ASSERT_EQ(state_stack.outstanding_opacity(), SK_Scalar1);
ASSERT_EQ(state_stack.outstanding_bounds(), SkRect());
}
TEST(LayerStateStack, ColorFilter) {
SkRect rect = {10, 10, 20, 20};
std::shared_ptr<DlBlendColorFilter> outer_filter =
std::make_shared<DlBlendColorFilter>(DlColor::kYellow(),
DlBlendMode::kColorBurn);
std::shared_ptr<DlBlendColorFilter> inner_filter =
std::make_shared<DlBlendColorFilter>(DlColor::kRed(),
DlBlendMode::kColorBurn);
LayerStateStack state_stack;
state_stack.set_preroll_delegate(SkRect::MakeLTRB(0, 0, 50, 50));
{
auto mutator = state_stack.save();
mutator.applyColorFilter(rect, outer_filter);
ASSERT_EQ(state_stack.outstanding_color_filter(), outer_filter);
// Check nested color filters result in nested saveLayers
{
auto mutator2 = state_stack.save();
mutator.applyColorFilter(rect, inner_filter);
ASSERT_EQ(state_stack.outstanding_color_filter(), inner_filter);
// Verify output with applyState that does not accept color filters
{
DisplayListBuilder builder;
state_stack.set_delegate(&builder);
{
auto restore = state_stack.applyState(rect, 0);
ASSERT_EQ(state_stack.outstanding_color_filter(), nullptr);
DlPaint paint;
state_stack.fill(paint);
builder.DrawRect(rect, paint);
}
state_stack.clear_delegate();
DisplayListBuilder expected;
DlPaint outer_save_paint = DlPaint().setColorFilter(outer_filter);
DlPaint inner_save_paint = DlPaint().setColorFilter(inner_filter);
expected.SaveLayer(&rect, &outer_save_paint);
expected.SaveLayer(&rect, &inner_save_paint);
expected.DrawRect(rect, DlPaint());
expected.Restore();
expected.Restore();
ASSERT_TRUE(DisplayListsEQ_Verbose(builder.Build(), expected.Build()));
}
// Verify output with applyState that accepts color filters
{
SkRect rect = {10, 10, 20, 20};
DisplayListBuilder builder;
state_stack.set_delegate(&builder);
{
auto restore = state_stack.applyState(
rect, LayerStateStack::kCallerCanApplyColorFilter);
ASSERT_EQ(state_stack.outstanding_color_filter(), inner_filter);
DlPaint paint;
state_stack.fill(paint);
builder.DrawRect(rect, paint);
}
state_stack.clear_delegate();
DisplayListBuilder expected;
DlPaint save_paint = DlPaint().setColorFilter(outer_filter);
DlPaint draw_paint = DlPaint().setColorFilter(inner_filter);
expected.SaveLayer(&rect, &save_paint);
expected.DrawRect(rect, draw_paint);
ASSERT_TRUE(DisplayListsEQ_Verbose(builder.Build(), expected.Build()));
}
}
ASSERT_EQ(state_stack.outstanding_color_filter(), outer_filter);
}
ASSERT_EQ(state_stack.outstanding_color_filter(), nullptr);
}
TEST(LayerStateStack, ImageFilter) {
SkRect rect = {10, 10, 20, 20};
std::shared_ptr<DlBlurImageFilter> outer_filter =
std::make_shared<DlBlurImageFilter>(2.0f, 2.0f, DlTileMode::kClamp);
std::shared_ptr<DlBlurImageFilter> inner_filter =
std::make_shared<DlBlurImageFilter>(3.0f, 3.0f, DlTileMode::kClamp);
SkRect inner_src_rect = rect;
SkRect outer_src_rect;
ASSERT_EQ(inner_filter->map_local_bounds(rect, outer_src_rect),
&outer_src_rect);
LayerStateStack state_stack;
state_stack.set_preroll_delegate(SkRect::MakeLTRB(0, 0, 50, 50));
{
auto mutator = state_stack.save();
mutator.applyImageFilter(outer_src_rect, outer_filter);
ASSERT_EQ(state_stack.outstanding_image_filter(), outer_filter);
// Check nested color filters result in nested saveLayers
{
auto mutator2 = state_stack.save();
mutator.applyImageFilter(rect, inner_filter);
ASSERT_EQ(state_stack.outstanding_image_filter(), inner_filter);
// Verify output with applyState that does not accept color filters
{
DisplayListBuilder builder;
state_stack.set_delegate(&builder);
{
auto restore = state_stack.applyState(rect, 0);
ASSERT_EQ(state_stack.outstanding_image_filter(), nullptr);
DlPaint paint;
state_stack.fill(paint);
builder.DrawRect(rect, paint);
}
state_stack.clear_delegate();
DisplayListBuilder expected;
DlPaint outer_save_paint = DlPaint().setImageFilter(outer_filter);
DlPaint inner_save_paint = DlPaint().setImageFilter(inner_filter);
expected.SaveLayer(&outer_src_rect, &outer_save_paint);
expected.SaveLayer(&inner_src_rect, &inner_save_paint);
expected.DrawRect(rect, DlPaint());
expected.Restore();
expected.Restore();
ASSERT_TRUE(DisplayListsEQ_Verbose(builder.Build(), expected.Build()));
}
// Verify output with applyState that accepts color filters
{
SkRect rect = {10, 10, 20, 20};
DisplayListBuilder builder;
state_stack.set_delegate(&builder);
{
auto restore = state_stack.applyState(
rect, LayerStateStack::kCallerCanApplyImageFilter);
ASSERT_EQ(state_stack.outstanding_image_filter(), inner_filter);
DlPaint paint;
state_stack.fill(paint);
builder.DrawRect(rect, paint);
}
state_stack.clear_delegate();
DisplayListBuilder expected;
DlPaint save_paint = DlPaint().setImageFilter(outer_filter);
DlPaint draw_paint = DlPaint().setImageFilter(inner_filter);
expected.SaveLayer(&outer_src_rect, &save_paint);
expected.DrawRect(rect, draw_paint);
ASSERT_TRUE(DisplayListsEQ_Verbose(builder.Build(), expected.Build()));
}
}
ASSERT_EQ(state_stack.outstanding_image_filter(), outer_filter);
}
ASSERT_EQ(state_stack.outstanding_image_filter(), nullptr);
}
TEST(LayerStateStack, OpacityAndColorFilterInteraction) {
SkRect rect = {10, 10, 20, 20};
std::shared_ptr<DlBlendColorFilter> color_filter =
std::make_shared<DlBlendColorFilter>(DlColor::kYellow(),
DlBlendMode::kColorBurn);
DisplayListBuilder builder;
LayerStateStack state_stack;
state_stack.set_delegate(&builder);
ASSERT_EQ(builder.GetSaveCount(), 1);
{
auto mutator1 = state_stack.save();
ASSERT_EQ(builder.GetSaveCount(), 1);
mutator1.applyOpacity(rect, 0.5f);
ASSERT_EQ(builder.GetSaveCount(), 1);
{
auto mutator2 = state_stack.save();
ASSERT_EQ(builder.GetSaveCount(), 1);
mutator2.applyColorFilter(rect, color_filter);
// The opacity will have been resolved by a saveLayer
ASSERT_EQ(builder.GetSaveCount(), 2);
ASSERT_EQ(state_stack.outstanding_color_filter(), color_filter);
ASSERT_EQ(state_stack.outstanding_opacity(), SK_Scalar1);
}
ASSERT_EQ(builder.GetSaveCount(), 1);
ASSERT_EQ(state_stack.outstanding_color_filter(), nullptr);
ASSERT_EQ(state_stack.outstanding_opacity(), 0.5f);
}
ASSERT_EQ(builder.GetSaveCount(), 1);
ASSERT_EQ(state_stack.outstanding_color_filter(), nullptr);
ASSERT_EQ(state_stack.outstanding_opacity(), SK_Scalar1);
{
auto mutator1 = state_stack.save();
ASSERT_EQ(builder.GetSaveCount(), 1);
mutator1.applyColorFilter(rect, color_filter);
ASSERT_EQ(builder.GetSaveCount(), 1);
{
auto mutator2 = state_stack.save();
ASSERT_EQ(builder.GetSaveCount(), 1);
mutator2.applyOpacity(rect, 0.5f);
// color filter applied to opacity can be applied together
ASSERT_EQ(builder.GetSaveCount(), 1);
ASSERT_EQ(state_stack.outstanding_color_filter(), color_filter);
ASSERT_EQ(state_stack.outstanding_opacity(), 0.5f);
}
ASSERT_EQ(builder.GetSaveCount(), 1);
ASSERT_EQ(state_stack.outstanding_color_filter(), color_filter);
ASSERT_EQ(state_stack.outstanding_opacity(), SK_Scalar1);
}
ASSERT_EQ(builder.GetSaveCount(), 1);
ASSERT_EQ(state_stack.outstanding_color_filter(), nullptr);
ASSERT_EQ(state_stack.outstanding_opacity(), SK_Scalar1);
}
TEST(LayerStateStack, OpacityAndImageFilterInteraction) {
SkRect rect = {10, 10, 20, 20};
std::shared_ptr<DlBlurImageFilter> image_filter =
std::make_shared<DlBlurImageFilter>(2.0f, 2.0f, DlTileMode::kClamp);
DisplayListBuilder builder;
LayerStateStack state_stack;
state_stack.set_delegate(&builder);
ASSERT_EQ(builder.GetSaveCount(), 1);
{
auto mutator1 = state_stack.save();
ASSERT_EQ(builder.GetSaveCount(), 1);
mutator1.applyOpacity(rect, 0.5f);
ASSERT_EQ(builder.GetSaveCount(), 1);
{
auto mutator2 = state_stack.save();
ASSERT_EQ(builder.GetSaveCount(), 1);
mutator2.applyImageFilter(rect, image_filter);
// opacity applied to image filter can be applied together
ASSERT_EQ(builder.GetSaveCount(), 1);
ASSERT_EQ(state_stack.outstanding_image_filter(), image_filter);
ASSERT_EQ(state_stack.outstanding_opacity(), 0.5f);
}
ASSERT_EQ(builder.GetSaveCount(), 1);
ASSERT_EQ(state_stack.outstanding_image_filter(), nullptr);
ASSERT_EQ(state_stack.outstanding_opacity(), 0.5f);
}
ASSERT_EQ(builder.GetSaveCount(), 1);
ASSERT_EQ(state_stack.outstanding_image_filter(), nullptr);
ASSERT_EQ(state_stack.outstanding_opacity(), SK_Scalar1);
{
auto mutator1 = state_stack.save();
ASSERT_EQ(builder.GetSaveCount(), 1);
mutator1.applyImageFilter(rect, image_filter);
ASSERT_EQ(builder.GetSaveCount(), 1);
{
auto mutator2 = state_stack.save();
ASSERT_EQ(builder.GetSaveCount(), 1);
mutator2.applyOpacity(rect, 0.5f);
// The image filter will have been resolved by a saveLayer
ASSERT_EQ(builder.GetSaveCount(), 2);
ASSERT_EQ(state_stack.outstanding_image_filter(), nullptr);
ASSERT_EQ(state_stack.outstanding_opacity(), 0.5f);
}
ASSERT_EQ(builder.GetSaveCount(), 1);
ASSERT_EQ(state_stack.outstanding_image_filter(), image_filter);
ASSERT_EQ(state_stack.outstanding_opacity(), SK_Scalar1);
}
ASSERT_EQ(builder.GetSaveCount(), 1);
ASSERT_EQ(state_stack.outstanding_image_filter(), nullptr);
ASSERT_EQ(state_stack.outstanding_opacity(), SK_Scalar1);
}
TEST(LayerStateStack, ColorFilterAndImageFilterInteraction) {
SkRect rect = {10, 10, 20, 20};
std::shared_ptr<DlBlendColorFilter> color_filter =
std::make_shared<DlBlendColorFilter>(DlColor::kYellow(),
DlBlendMode::kColorBurn);
std::shared_ptr<DlBlurImageFilter> image_filter =
std::make_shared<DlBlurImageFilter>(2.0f, 2.0f, DlTileMode::kClamp);
DisplayListBuilder builder;
LayerStateStack state_stack;
state_stack.set_delegate(&builder);
ASSERT_EQ(builder.GetSaveCount(), 1);
{
auto mutator1 = state_stack.save();
ASSERT_EQ(builder.GetSaveCount(), 1);
mutator1.applyColorFilter(rect, color_filter);
ASSERT_EQ(builder.GetSaveCount(), 1);
{
auto mutator2 = state_stack.save();
ASSERT_EQ(builder.GetSaveCount(), 1);
mutator2.applyImageFilter(rect, image_filter);
// color filter applied to image filter can be applied together
ASSERT_EQ(builder.GetSaveCount(), 1);
ASSERT_EQ(state_stack.outstanding_image_filter(), image_filter);
ASSERT_EQ(state_stack.outstanding_color_filter(), color_filter);
}
ASSERT_EQ(builder.GetSaveCount(), 1);
ASSERT_EQ(state_stack.outstanding_image_filter(), nullptr);
ASSERT_EQ(state_stack.outstanding_color_filter(), color_filter);
}
ASSERT_EQ(builder.GetSaveCount(), 1);
ASSERT_EQ(state_stack.outstanding_image_filter(), nullptr);
ASSERT_EQ(state_stack.outstanding_color_filter(), nullptr);
{
auto mutator1 = state_stack.save();
ASSERT_EQ(builder.GetSaveCount(), 1);
mutator1.applyImageFilter(rect, image_filter);
ASSERT_EQ(builder.GetSaveCount(), 1);
{
auto mutator2 = state_stack.save();
ASSERT_EQ(builder.GetSaveCount(), 1);
mutator2.applyColorFilter(rect, color_filter);
// The image filter will have been resolved by a saveLayer
ASSERT_EQ(builder.GetSaveCount(), 2);
ASSERT_EQ(state_stack.outstanding_image_filter(), nullptr);
ASSERT_EQ(state_stack.outstanding_color_filter(), color_filter);
}
ASSERT_EQ(builder.GetSaveCount(), 1);
ASSERT_EQ(state_stack.outstanding_image_filter(), image_filter);
ASSERT_EQ(state_stack.outstanding_color_filter(), nullptr);
}
ASSERT_EQ(builder.GetSaveCount(), 1);
ASSERT_EQ(state_stack.outstanding_image_filter(), nullptr);
ASSERT_EQ(state_stack.outstanding_color_filter(), nullptr);
}
} // namespace testing
} // namespace flutter
| engine/flow/layers/layer_state_stack_unittests.cc/0 | {
"file_path": "engine/flow/layers/layer_state_stack_unittests.cc",
"repo_id": "engine",
"token_count": 8044
} | 174 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/flow/layers/shader_mask_layer.h"
#include "flutter/flow/raster_cache_util.h"
namespace flutter {
ShaderMaskLayer::ShaderMaskLayer(std::shared_ptr<DlColorSource> color_source,
const SkRect& mask_rect,
DlBlendMode blend_mode)
: CacheableContainerLayer(
RasterCacheUtil::kMinimumRendersBeforeCachingFilterLayer),
color_source_(std::move(color_source)),
mask_rect_(mask_rect),
blend_mode_(blend_mode) {}
void ShaderMaskLayer::Diff(DiffContext* context, const Layer* old_layer) {
DiffContext::AutoSubtreeRestore subtree(context);
auto* prev = static_cast<const ShaderMaskLayer*>(old_layer);
if (!context->IsSubtreeDirty()) {
FML_DCHECK(prev);
if (color_source_ != prev->color_source_ ||
mask_rect_ != prev->mask_rect_ || blend_mode_ != prev->blend_mode_) {
context->MarkSubtreeDirty(context->GetOldLayerPaintRegion(old_layer));
}
}
if (context->has_raster_cache()) {
context->WillPaintWithIntegralTransform();
}
DiffChildren(context, prev);
context->SetLayerPaintRegion(this, context->CurrentSubtreeRegion());
}
void ShaderMaskLayer::Preroll(PrerollContext* context) {
Layer::AutoPrerollSaveLayerState save =
Layer::AutoPrerollSaveLayerState::Create(context);
AutoCache cache = AutoCache(layer_raster_cache_item_.get(), context,
context->state_stack.transform_3x3());
ContainerLayer::Preroll(context);
// We always paint with a saveLayer (or a cached rendering),
// so we can always apply opacity in any of those cases.
context->renderable_state_flags = kSaveLayerRenderFlags;
}
void ShaderMaskLayer::Paint(PaintContext& context) const {
FML_DCHECK(needs_painting(context));
auto mutator = context.state_stack.save();
if (context.raster_cache) {
mutator.integralTransform();
DlPaint paint;
if (layer_raster_cache_item_->Draw(context,
context.state_stack.fill(paint))) {
return;
}
}
auto shader_rect = SkRect::MakeWH(mask_rect_.width(), mask_rect_.height());
mutator.saveLayer(paint_bounds());
PaintChildren(context);
DlPaint dl_paint;
dl_paint.setBlendMode(blend_mode_);
if (color_source_) {
dl_paint.setColorSource(color_source_.get());
}
context.canvas->Translate(mask_rect_.left(), mask_rect_.top());
context.canvas->DrawRect(shader_rect, dl_paint);
}
} // namespace flutter
| engine/flow/layers/shader_mask_layer.cc/0 | {
"file_path": "engine/flow/layers/shader_mask_layer.cc",
"repo_id": "engine",
"token_count": 1016
} | 175 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_FLOW_RASTER_CACHE_ITEM_H_
#define FLUTTER_FLOW_RASTER_CACHE_ITEM_H_
#include <memory>
#include <optional>
#include <utility>
#include "flutter/display_list/dl_canvas.h"
#include "flutter/flow/raster_cache_key.h"
namespace flutter {
struct PrerollContext;
struct PaintContext;
class DisplayList;
class RasterCache;
class LayerRasterCacheItem;
class DisplayListRasterCacheItem;
class RasterCacheItem {
public:
enum CacheState {
kNone = 0,
kCurrent,
kChildren,
};
explicit RasterCacheItem(RasterCacheKeyID key_id,
CacheState cache_state = CacheState::kNone,
unsigned child_entries = 0)
: key_id_(std::move(key_id)),
cache_state_(cache_state),
child_items_(child_entries) {}
virtual void PrerollSetup(PrerollContext* context,
const SkMatrix& matrix) = 0;
virtual void PrerollFinalize(PrerollContext* context,
const SkMatrix& matrix) = 0;
virtual bool Draw(const PaintContext& context,
const DlPaint* paint) const = 0;
virtual bool Draw(const PaintContext& context,
DlCanvas* canvas,
const DlPaint* paint) const = 0;
virtual std::optional<RasterCacheKeyID> GetId() const { return key_id_; }
virtual bool TryToPrepareRasterCache(const PaintContext& context,
bool parent_cached = false) const = 0;
unsigned child_items() const { return child_items_; }
void set_matrix(const SkMatrix& matrix) { matrix_ = matrix; }
CacheState cache_state() const { return cache_state_; }
bool need_caching() const { return cache_state_ != CacheState::kNone; }
virtual ~RasterCacheItem() = default;
protected:
// The id for cache the layer self.
RasterCacheKeyID key_id_;
CacheState cache_state_ = CacheState::kNone;
mutable SkMatrix matrix_;
unsigned child_items_;
};
} // namespace flutter
#endif // FLUTTER_FLOW_RASTER_CACHE_ITEM_H_
| engine/flow/raster_cache_item.h/0 | {
"file_path": "engine/flow/raster_cache_item.h",
"repo_id": "engine",
"token_count": 879
} | 176 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/flow/surface.h"
namespace flutter {
Surface::Surface() = default;
Surface::~Surface() = default;
std::unique_ptr<GLContextResult> Surface::MakeRenderContextCurrent() {
return std::make_unique<GLContextDefaultResult>(true);
}
bool Surface::ClearRenderContext() {
return false;
}
bool Surface::AllowsDrawingWhenGpuDisabled() const {
return true;
}
bool Surface::EnableRasterCache() const {
return true;
}
std::shared_ptr<impeller::AiksContext> Surface::GetAiksContext() const {
return nullptr;
}
Surface::SurfaceData Surface::GetSurfaceData() const {
return {};
}
} // namespace flutter
| engine/flow/surface.cc/0 | {
"file_path": "engine/flow/surface.cc",
"repo_id": "engine",
"token_count": 249
} | 177 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_FLOW_TESTING_MOCK_RASTER_CACHE_H_
#define FLUTTER_FLOW_TESTING_MOCK_RASTER_CACHE_H_
#include <vector>
#include "flutter/flow/layers/layer.h"
#include "flutter/flow/raster_cache.h"
#include "flutter/flow/raster_cache_item.h"
#include "flutter/flow/testing/mock_layer.h"
#include "flutter/testing/mock_canvas.h"
#include "third_party/skia/include/core/SkColorSpace.h"
#include "third_party/skia/include/core/SkRefCnt.h"
#include "third_party/skia/include/core/SkSize.h"
namespace flutter {
namespace testing {
/**
* @brief A RasterCacheResult implementation that represents a cached Layer or
* DisplayList without the overhead of storage.
*
* This implementation is used by MockRasterCache only for testing proper usage
* of the RasterCache in layer unit tests.
*/
class MockRasterCacheResult : public RasterCacheResult {
public:
explicit MockRasterCacheResult(SkRect device_rect);
void draw(DlCanvas& canvas,
const DlPaint* paint = nullptr,
bool preserve_rtree = false) const override {};
SkISize image_dimensions() const override {
return SkSize::Make(device_rect_.width(), device_rect_.height()).toCeil();
};
int64_t image_bytes() const override {
return image_dimensions().area() *
SkColorTypeBytesPerPixel(kBGRA_8888_SkColorType);
}
private:
SkRect device_rect_;
};
static std::vector<RasterCacheItem*> raster_cache_items_;
/**
* @brief A RasterCache implementation that simulates the act of rendering a
* Layer or DisplayList without the overhead of rasterization or pixel storage.
* This implementation is used only for testing proper usage of the RasterCache
* in layer unit tests.
*/
class MockRasterCache : public RasterCache {
public:
explicit MockRasterCache(
size_t access_threshold = 3,
size_t picture_and_display_list_cache_limit_per_frame =
RasterCacheUtil::kDefaultPictureAndDisplayListCacheLimitPerFrame)
: RasterCache(access_threshold,
picture_and_display_list_cache_limit_per_frame) {
preroll_state_stack_.set_preroll_delegate(SkMatrix::I());
paint_state_stack_.set_delegate(&mock_canvas_);
}
void AddMockLayer(int width, int height);
void AddMockPicture(int width, int height);
private:
LayerStateStack preroll_state_stack_;
LayerStateStack paint_state_stack_;
MockCanvas mock_canvas_;
sk_sp<SkColorSpace> color_space_ = SkColorSpace::MakeSRGB();
MutatorsStack mutators_stack_;
FixedRefreshRateStopwatch raster_time_;
FixedRefreshRateStopwatch ui_time_;
std::shared_ptr<TextureRegistry> texture_registry_;
PrerollContext preroll_context_ = {
// clang-format off
.raster_cache = this,
.gr_context = nullptr,
.view_embedder = nullptr,
.state_stack = preroll_state_stack_,
.dst_color_space = color_space_,
.surface_needs_readback = false,
.raster_time = raster_time_,
.ui_time = ui_time_,
.texture_registry = texture_registry_,
.has_platform_view = false,
.has_texture_layer = false,
.raster_cached_entries = &raster_cache_items_
// clang-format on
};
PaintContext paint_context_ = {
// clang-format off
.state_stack = paint_state_stack_,
.canvas = nullptr,
.gr_context = nullptr,
.dst_color_space = color_space_,
.view_embedder = nullptr,
.raster_time = raster_time_,
.ui_time = ui_time_,
.texture_registry = texture_registry_,
.raster_cache = nullptr,
// clang-format on
};
};
struct PrerollContextHolder {
PrerollContext preroll_context;
sk_sp<SkColorSpace> srgb;
};
struct PaintContextHolder {
PaintContext paint_context;
sk_sp<SkColorSpace> srgb;
};
PrerollContextHolder GetSamplePrerollContextHolder(
LayerStateStack& state_stack,
RasterCache* raster_cache,
FixedRefreshRateStopwatch* raster_time,
FixedRefreshRateStopwatch* ui_time);
PaintContextHolder GetSamplePaintContextHolder(
LayerStateStack& state_stack,
RasterCache* raster_cache,
FixedRefreshRateStopwatch* raster_time,
FixedRefreshRateStopwatch* ui_time);
bool RasterCacheItemPrerollAndTryToRasterCache(
DisplayListRasterCacheItem& display_list_item,
PrerollContext& context,
PaintContext& paint_context,
const SkMatrix& matrix);
void RasterCacheItemPreroll(DisplayListRasterCacheItem& display_list_item,
PrerollContext& context,
const SkMatrix& matrix);
bool RasterCacheItemTryToRasterCache(
DisplayListRasterCacheItem& display_list_item,
PaintContext& paint_context);
} // namespace testing
} // namespace flutter
#endif // FLUTTER_FLOW_TESTING_MOCK_RASTER_CACHE_H_
| engine/flow/testing/mock_raster_cache.h/0 | {
"file_path": "engine/flow/testing/mock_raster_cache.h",
"repo_id": "engine",
"token_count": 2172
} | 178 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifdef VMA_STATIC_VULKAN_FUNCTIONS
#undef VMA_STATIC_VULKAN_FUNCTIONS
#endif // VMA_STATIC_VULKAN_FUNCTIONS
#ifdef VMA_DYNAMIC_VULKAN_FUNCTIONS
#undef VMA_DYNAMIC_VULKAN_FUNCTIONS
#endif // VMA_DYNAMIC_VULKAN_FUNCTIONS
// We use our own functions pointers
#define VMA_STATIC_VULKAN_FUNCTIONS 0
#define VMA_DYNAMIC_VULKAN_FUNCTIONS 0
#define VMA_IMPLEMENTATION
// Enable this to dump a list of all pending allocations to the log. This comes
// in handy if you are tracking a leak of a resource after context shutdown.
#if 0
#include "flutter/fml/logging.h" // nogncheck
#define VMA_DEBUG_LOG VMADebugPrint
void VMADebugPrint(const char* message, ...) {
va_list args;
va_start(args, message);
char buffer[256];
vsnprintf(buffer, sizeof(buffer) - 1, message, args);
va_end(args);
FML_DLOG(INFO) << buffer;
}
#endif
#include "flutter/fml/logging.h"
#define VMA_ASSERT(expr) \
FML_DCHECK((expr)) << "Vulkan Memory Allocator Failure!"
#define VMA_HEAVY_ASSERT(expr) \
FML_DCHECK((expr)) << "Vulkan Memory Allocator Failure!"
#include "flutter/flutter_vma/flutter_vma.h"
| engine/flutter_vma/flutter_vma.cc/0 | {
"file_path": "engine/flutter_vma/flutter_vma.cc",
"repo_id": "engine",
"token_count": 478
} | 179 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/fml/command_line.h"
namespace fml {
// CommandLine -----------------------------------------------------------------
CommandLine::Option::Option(const std::string& name) : name(name) {}
CommandLine::Option::Option(const std::string& name, const std::string& value)
: name(name), value(value) {}
CommandLine::CommandLine() = default;
CommandLine::CommandLine(const CommandLine& from) = default;
CommandLine::CommandLine(CommandLine&& from) = default;
CommandLine::CommandLine(const std::string& argv0,
const std::vector<Option>& options,
const std::vector<std::string>& positional_args)
: has_argv0_(true),
argv0_(argv0),
options_(options),
positional_args_(positional_args) {
for (size_t i = 0; i < options_.size(); i++) {
option_index_[options_[i].name] = i;
}
}
CommandLine::~CommandLine() = default;
CommandLine& CommandLine::operator=(const CommandLine& from) = default;
CommandLine& CommandLine::operator=(CommandLine&& from) = default;
bool CommandLine::HasOption(std::string_view name, size_t* index) const {
auto it = option_index_.find(name.data());
if (it == option_index_.end()) {
return false;
}
if (index) {
*index = it->second;
}
return true;
}
bool CommandLine::GetOptionValue(std::string_view name,
std::string* value) const {
size_t index;
if (!HasOption(name, &index)) {
return false;
}
*value = options_[index].value;
return true;
}
std::vector<std::string_view> CommandLine::GetOptionValues(
std::string_view name) const {
std::vector<std::string_view> ret;
for (const auto& option : options_) {
if (option.name == name) {
ret.push_back(option.value);
}
}
return ret;
}
std::string CommandLine::GetOptionValueWithDefault(
std::string_view name,
std::string_view default_value) const {
size_t index;
if (!HasOption(name, &index)) {
return {default_value.data(), default_value.size()};
}
return options_[index].value;
}
// Factory functions (etc.) ----------------------------------------------------
namespace internal {
CommandLineBuilder::CommandLineBuilder() {}
CommandLineBuilder::~CommandLineBuilder() {}
bool CommandLineBuilder::ProcessArg(const std::string& arg) {
if (!has_argv0_) {
has_argv0_ = true;
argv0_ = arg;
return false;
}
// If we've seen a positional argument, then the remaining arguments are also
// positional.
if (started_positional_args_) {
bool rv = positional_args_.empty();
positional_args_.push_back(arg);
return rv;
}
// Anything that doesn't start with "--" is a positional argument.
if (arg.size() < 2u || arg[0] != '-' || arg[1] != '-') {
bool rv = positional_args_.empty();
started_positional_args_ = true;
positional_args_.push_back(arg);
return rv;
}
// "--" ends option processing, but isn't stored as a positional argument.
if (arg.size() == 2u) {
started_positional_args_ = true;
return false;
}
// Note: The option name *must* be at least one character, so start at
// position 3 -- "--=foo" will yield a name of "=foo" and no value. (Passing a
// starting |pos| that's "too big" is OK.)
size_t equals_pos = arg.find('=', 3u);
if (equals_pos == std::string::npos) {
options_.push_back(CommandLine::Option(arg.substr(2u)));
return false;
}
options_.push_back(CommandLine::Option(arg.substr(2u, equals_pos - 2u),
arg.substr(equals_pos + 1u)));
return false;
}
CommandLine CommandLineBuilder::Build() const {
if (!has_argv0_) {
return CommandLine();
}
return CommandLine(argv0_, options_, positional_args_);
}
} // namespace internal
std::vector<std::string> CommandLineToArgv(const CommandLine& command_line) {
if (!command_line.has_argv0()) {
return std::vector<std::string>();
}
std::vector<std::string> argv;
const std::vector<CommandLine::Option>& options = command_line.options();
const std::vector<std::string>& positional_args =
command_line.positional_args();
// Reserve space for argv[0], options, maybe a "--" (if needed), and the
// positional arguments.
argv.reserve(1u + options.size() + 1u + positional_args.size());
argv.push_back(command_line.argv0());
for (const auto& option : options) {
if (option.value.empty()) {
argv.push_back("--" + option.name);
} else {
argv.push_back("--" + option.name + "=" + option.value);
}
}
if (!positional_args.empty()) {
// Insert a "--" if necessary.
if (positional_args[0].size() >= 2u && positional_args[0][0] == '-' &&
positional_args[0][1] == '-') {
argv.push_back("--");
}
argv.insert(argv.end(), positional_args.begin(), positional_args.end());
}
return argv;
}
} // namespace fml
| engine/fml/command_line.cc/0 | {
"file_path": "engine/fml/command_line.cc",
"repo_id": "engine",
"token_count": 1845
} | 180 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_FML_ENDIANNESS_H_
#define FLUTTER_FML_ENDIANNESS_H_
#include <cstdint>
#include <type_traits>
#if defined(_MSC_VER)
#include "intrin.h"
#endif
#include "flutter/fml/build_config.h"
// Compiler intrinsics for flipping endianness.
#if defined(_MSC_VER)
#define FML_BYTESWAP_16(n) _byteswap_ushort(n)
#define FML_BYTESWAP_32(n) _byteswap_ulong(n)
#define FML_BYTESWAP_64(n) _byteswap_uint64(n)
#else
#define FML_BYTESWAP_16(n) __builtin_bswap16(n)
#define FML_BYTESWAP_32(n) __builtin_bswap32(n)
#define FML_BYTESWAP_64(n) __builtin_bswap64(n)
#endif
namespace fml {
template <typename T>
struct IsByteSwappable
: public std::
integral_constant<bool, std::is_integral_v<T> || std::is_enum_v<T>> {
};
template <typename T>
constexpr bool kIsByteSwappableV = IsByteSwappable<T>::value;
/// @brief Flips the endianness of the given value.
/// The given value must be an integral type of size 1, 2, 4, or 8.
template <typename T, class = std::enable_if_t<kIsByteSwappableV<T>>>
constexpr T ByteSwap(T n) {
if constexpr (sizeof(T) == 1) {
return n;
} else if constexpr (sizeof(T) == 2) {
return (T)FML_BYTESWAP_16((uint16_t)n);
} else if constexpr (sizeof(T) == 4) {
return (T)FML_BYTESWAP_32((uint32_t)n);
} else if constexpr (sizeof(T) == 8) {
return (T)FML_BYTESWAP_64((uint64_t)n);
} else {
static_assert(!sizeof(T), "Unsupported size");
}
}
/// @brief Convert a known big endian value to match the endianness of the
/// current architecture. This is effectively a cross platform
/// ntohl/ntohs (as network byte order is always Big Endian).
/// The given value must be an integral type of size 1, 2, 4, or 8.
template <typename T, class = std::enable_if_t<kIsByteSwappableV<T>>>
constexpr T BigEndianToArch(T n) {
#if FML_ARCH_CPU_LITTLE_ENDIAN
return ByteSwap<T>(n);
#else
return n;
#endif
}
/// @brief Convert a known little endian value to match the endianness of the
/// current architecture.
/// The given value must be an integral type of size 1, 2, 4, or 8.
template <typename T, class = std::enable_if_t<kIsByteSwappableV<T>>>
constexpr T LittleEndianToArch(T n) {
#if !FML_ARCH_CPU_LITTLE_ENDIAN
return ByteSwap<T>(n);
#else
return n;
#endif
}
} // namespace fml
#endif // FLUTTER_FML_ENDIANNESS_H_
| engine/fml/endianness.h/0 | {
"file_path": "engine/fml/endianness.h",
"repo_id": "engine",
"token_count": 1031
} | 181 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <algorithm>
#include <cstring>
#include <iostream>
#include "flutter/fml/build_config.h"
#include "flutter/fml/log_level.h"
#include "flutter/fml/log_settings.h"
#include "flutter/fml/logging.h"
#if defined(FML_OS_ANDROID)
#include <android/log.h>
#elif defined(FML_OS_IOS)
#include <syslog.h>
#elif defined(OS_FUCHSIA)
#include <lib/syslog/structured_backend/cpp/fuchsia_syslog.h>
#include <lib/syslog/structured_backend/fuchsia_syslog.h>
#include <zircon/process.h>
#include "flutter/fml/platform/fuchsia/log_state.h"
#endif
namespace fml {
namespace {
#if !defined(OS_FUCHSIA)
const char* const kLogSeverityNames[kLogNumSeverities] = {
"INFO", "WARNING", "ERROR", "IMPORTANT", "FATAL"};
const char* GetNameForLogSeverity(LogSeverity severity) {
if (severity >= kLogInfo && severity < kLogNumSeverities) {
return kLogSeverityNames[severity];
}
return "UNKNOWN";
}
#endif
const char* StripDots(const char* path) {
while (strncmp(path, "../", 3) == 0) {
path += 3;
}
return path;
}
#if defined(OS_FUCHSIA)
zx_koid_t GetKoid(zx_handle_t handle) {
zx_info_handle_basic_t info;
zx_status_t status = zx_object_get_info(handle, ZX_INFO_HANDLE_BASIC, &info,
sizeof(info), nullptr, nullptr);
return status == ZX_OK ? info.koid : ZX_KOID_INVALID;
}
thread_local zx_koid_t tls_thread_koid{ZX_KOID_INVALID};
zx_koid_t GetCurrentThreadKoid() {
if (unlikely(tls_thread_koid == ZX_KOID_INVALID)) {
tls_thread_koid = GetKoid(zx_thread_self());
}
ZX_DEBUG_ASSERT(tls_thread_koid != ZX_KOID_INVALID);
return tls_thread_koid;
}
static zx_koid_t pid = GetKoid(zx_process_self());
static thread_local zx_koid_t tid = GetCurrentThreadKoid();
std::string GetProcessName(zx_handle_t handle) {
char process_name[ZX_MAX_NAME_LEN];
zx_status_t status = zx_object_get_property(
handle, ZX_PROP_NAME, &process_name, sizeof(process_name));
if (status != ZX_OK) {
process_name[0] = '\0';
}
return process_name;
}
static std::string process_name = GetProcessName(zx_process_self());
static const zx::socket& socket = LogState::Default().socket();
#endif
} // namespace
LogMessage::LogMessage(LogSeverity severity,
const char* file,
int line,
const char* condition)
: severity_(severity), file_(StripDots(file)), line_(line) {
#if !defined(OS_FUCHSIA)
stream_ << "[";
if (severity >= kLogInfo) {
stream_ << GetNameForLogSeverity(severity);
} else {
stream_ << "VERBOSE" << -severity;
}
stream_ << ":" << file_ << "(" << line_ << ")] ";
#endif
if (condition) {
stream_ << "Check failed: " << condition << ". ";
}
}
// static
thread_local std::ostringstream* LogMessage::capture_next_log_stream_ = nullptr;
namespace testing {
LogCapture::LogCapture() {
fml::LogMessage::CaptureNextLog(&stream_);
}
LogCapture::~LogCapture() {
fml::LogMessage::CaptureNextLog(nullptr);
}
std::string LogCapture::str() const {
return stream_.str();
}
} // namespace testing
// static
void LogMessage::CaptureNextLog(std::ostringstream* stream) {
LogMessage::capture_next_log_stream_ = stream;
}
LogMessage::~LogMessage() {
#if !defined(OS_FUCHSIA)
stream_ << std::endl;
#endif
if (capture_next_log_stream_) {
*capture_next_log_stream_ << stream_.str();
capture_next_log_stream_ = nullptr;
} else {
#if defined(FML_OS_ANDROID)
android_LogPriority priority =
(severity_ < 0) ? ANDROID_LOG_VERBOSE : ANDROID_LOG_UNKNOWN;
switch (severity_) {
case kLogImportant:
case kLogInfo:
priority = ANDROID_LOG_INFO;
break;
case kLogWarning:
priority = ANDROID_LOG_WARN;
break;
case kLogError:
priority = ANDROID_LOG_ERROR;
break;
case kLogFatal:
priority = ANDROID_LOG_FATAL;
break;
}
__android_log_write(priority, "flutter", stream_.str().c_str());
#elif defined(FML_OS_IOS)
syslog(LOG_ALERT, "%s", stream_.str().c_str());
#elif defined(OS_FUCHSIA)
FuchsiaLogSeverity severity;
switch (severity_) {
case kLogImportant:
case kLogInfo:
severity = FUCHSIA_LOG_INFO;
break;
case kLogWarning:
severity = FUCHSIA_LOG_WARNING;
break;
case kLogError:
severity = FUCHSIA_LOG_ERROR;
break;
case kLogFatal:
severity = FUCHSIA_LOG_FATAL;
break;
default:
if (severity_ < 0) {
severity = FUCHSIA_LOG_DEBUG;
} else {
// Unknown severity. Use INFO.
severity = FUCHSIA_LOG_INFO;
}
break;
}
fuchsia_syslog::LogBuffer buffer;
buffer.BeginRecord(severity, std::string_view(file_), line_,
std::string_view(stream_.str()), socket.borrow(), 0, pid,
tid);
if (!process_name.empty()) {
buffer.WriteKeyValue("tag", process_name);
}
if (auto tags_ptr = LogState::Default().tags()) {
for (auto& tag : *tags_ptr) {
buffer.WriteKeyValue("tag", tag);
}
}
buffer.FlushRecord();
#else
// Don't use std::cerr here, because it may not be initialized properly yet.
fprintf(stderr, "%s", stream_.str().c_str());
fflush(stderr);
#endif
}
if (severity_ >= kLogFatal) {
KillProcess();
}
}
int GetVlogVerbosity() {
return std::max(-1, kLogInfo - GetMinLogLevel());
}
bool ShouldCreateLogMessage(LogSeverity severity) {
return severity >= GetMinLogLevel();
}
void KillProcess() {
abort();
}
} // namespace fml
| engine/fml/logging.cc/0 | {
"file_path": "engine/fml/logging.cc",
"repo_id": "engine",
"token_count": 2501
} | 182 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_FML_MEMORY_TASK_RUNNER_CHECKER_H_
#define FLUTTER_FML_MEMORY_TASK_RUNNER_CHECKER_H_
#include "flutter/fml/message_loop.h"
#include "flutter/fml/task_runner.h"
namespace fml {
class TaskRunnerChecker final {
public:
TaskRunnerChecker();
~TaskRunnerChecker();
bool RunsOnCreationTaskRunner() const;
static bool RunsOnTheSameThread(TaskQueueId queue_a, TaskQueueId queue_b);
private:
TaskQueueId initialized_queue_id_;
std::set<TaskQueueId> subsumed_queue_ids_;
TaskQueueId InitTaskQueueId();
};
#if !defined(NDEBUG)
#define FML_DECLARE_TASK_RUNNER_CHECKER(c) fml::TaskRunnerChecker c
#define FML_DCHECK_TASK_RUNNER_IS_CURRENT(c) \
FML_DCHECK((c).RunsOnCreationTaskRunner())
#else
#define FML_DECLARE_TASK_RUNNER_CHECKER(c)
#define FML_DCHECK_TASK_RUNNER_IS_CURRENT(c) ((void)0)
#endif
} // namespace fml
#endif // FLUTTER_FML_MEMORY_TASK_RUNNER_CHECKER_H_
| engine/fml/memory/task_runner_checker.h/0 | {
"file_path": "engine/fml/memory/task_runner_checker.h",
"repo_id": "engine",
"token_count": 416
} | 183 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#define FML_USED_ON_EMBEDDER
#include "flutter/fml/message_loop_task_queues.h"
#include <algorithm>
#include <cstdlib>
#include <thread>
#include <utility>
#include "flutter/fml/synchronization/count_down_latch.h"
#include "flutter/fml/synchronization/waitable_event.h"
#include "flutter/fml/time/chrono_timestamp_provider.h"
#include "gtest/gtest.h"
namespace fml {
namespace testing {
class TestWakeable : public fml::Wakeable {
public:
using WakeUpCall = std::function<void(const fml::TimePoint)>;
explicit TestWakeable(WakeUpCall call) : wake_up_call_(std::move(call)) {}
void WakeUp(fml::TimePoint time_point) override { wake_up_call_(time_point); }
private:
WakeUpCall wake_up_call_;
};
TEST(MessageLoopTaskQueue, StartsWithNoPendingTasks) {
auto task_queue = fml::MessageLoopTaskQueues::GetInstance();
auto queue_id = task_queue->CreateTaskQueue();
ASSERT_FALSE(task_queue->HasPendingTasks(queue_id));
}
TEST(MessageLoopTaskQueue, RegisterOneTask) {
const auto time = fml::TimePoint::Max();
auto task_queue = fml::MessageLoopTaskQueues::GetInstance();
auto queue_id = task_queue->CreateTaskQueue();
auto wakeable = std::make_unique<TestWakeable>(
[&time](fml::TimePoint wake_time) { ASSERT_TRUE(wake_time == time); });
task_queue->SetWakeable(queue_id, wakeable.get());
task_queue->RegisterTask(queue_id, [] {}, time);
ASSERT_TRUE(task_queue->HasPendingTasks(queue_id));
ASSERT_TRUE(task_queue->GetNumPendingTasks(queue_id) == 1);
}
TEST(MessageLoopTaskQueue, RegisterTwoTasksAndCount) {
auto task_queue = fml::MessageLoopTaskQueues::GetInstance();
auto queue_id = task_queue->CreateTaskQueue();
task_queue->RegisterTask(queue_id, [] {}, ChronoTicksSinceEpoch());
task_queue->RegisterTask(queue_id, [] {}, fml::TimePoint::Max());
ASSERT_TRUE(task_queue->HasPendingTasks(queue_id));
ASSERT_TRUE(task_queue->GetNumPendingTasks(queue_id) == 2);
}
TEST(MessageLoopTaskQueue, RegisterTasksOnMergedQueuesAndCount) {
auto task_queue = fml::MessageLoopTaskQueues::GetInstance();
auto platform_queue = task_queue->CreateTaskQueue();
auto raster_queue = task_queue->CreateTaskQueue();
// A task in platform_queue
task_queue->RegisterTask(platform_queue, []() {}, fml::TimePoint::Now());
// A task in raster_queue
task_queue->RegisterTask(raster_queue, []() {}, fml::TimePoint::Now());
ASSERT_TRUE(task_queue->GetNumPendingTasks(platform_queue) == 1);
ASSERT_TRUE(task_queue->GetNumPendingTasks(raster_queue) == 1);
ASSERT_FALSE(task_queue->Owns(platform_queue, raster_queue));
task_queue->Merge(platform_queue, raster_queue);
ASSERT_TRUE(task_queue->Owns(platform_queue, raster_queue));
ASSERT_TRUE(task_queue->HasPendingTasks(platform_queue));
ASSERT_TRUE(task_queue->GetNumPendingTasks(platform_queue) == 2);
// The task count of subsumed queue is 0
ASSERT_FALSE(task_queue->HasPendingTasks(raster_queue));
ASSERT_TRUE(task_queue->GetNumPendingTasks(raster_queue) == 0);
task_queue->Unmerge(platform_queue, raster_queue);
ASSERT_FALSE(task_queue->Owns(platform_queue, raster_queue));
ASSERT_TRUE(task_queue->GetNumPendingTasks(platform_queue) == 1);
ASSERT_TRUE(task_queue->GetNumPendingTasks(raster_queue) == 1);
}
TEST(MessageLoopTaskQueue, PreserveTaskOrdering) {
auto task_queue = fml::MessageLoopTaskQueues::GetInstance();
auto queue_id = task_queue->CreateTaskQueue();
int test_val = 0;
// order: 0
task_queue->RegisterTask(
queue_id, [&test_val]() { test_val = 1; }, ChronoTicksSinceEpoch());
// order: 1
task_queue->RegisterTask(
queue_id, [&test_val]() { test_val = 2; }, ChronoTicksSinceEpoch());
const auto now = ChronoTicksSinceEpoch();
int expected_value = 1;
while (true) {
fml::closure invocation = task_queue->GetNextTaskToRun(queue_id, now);
if (!invocation) {
break;
}
invocation();
ASSERT_TRUE(test_val == expected_value);
expected_value++;
}
}
TEST(MessageLoopTaskQueue, RegisterTasksOnMergedQueuesPreserveTaskOrdering) {
auto task_queue = fml::MessageLoopTaskQueues::GetInstance();
auto platform_queue = task_queue->CreateTaskQueue();
auto raster1_queue = task_queue->CreateTaskQueue();
auto raster2_queue = task_queue->CreateTaskQueue();
int test_val = 0;
// order 0 in raster1_queue
task_queue->RegisterTask(
raster1_queue, [&test_val]() { test_val = 0; }, fml::TimePoint::Now());
// order 1 in platform_queue
task_queue->RegisterTask(
platform_queue, [&test_val]() { test_val = 1; }, fml::TimePoint::Now());
// order 2 in raster2_queue
task_queue->RegisterTask(
raster2_queue, [&test_val]() { test_val = 2; }, fml::TimePoint::Now());
task_queue->Merge(platform_queue, raster1_queue);
ASSERT_TRUE(task_queue->Owns(platform_queue, raster1_queue));
task_queue->Merge(platform_queue, raster2_queue);
ASSERT_TRUE(task_queue->Owns(platform_queue, raster2_queue));
const auto now = fml::TimePoint::Now();
int expected_value = 0;
// Right order:
// "test_val = 0" in raster1_queue
// "test_val = 1" in platform_queue
// "test_val = 2" in raster2_queue
while (true) {
fml::closure invocation = task_queue->GetNextTaskToRun(platform_queue, now);
if (!invocation) {
break;
}
invocation();
ASSERT_TRUE(test_val == expected_value);
expected_value++;
}
}
TEST(MessageLoopTaskQueue, UnmergeRespectTheOriginalTaskOrderingInQueues) {
auto task_queue = fml::MessageLoopTaskQueues::GetInstance();
auto platform_queue = task_queue->CreateTaskQueue();
auto raster_queue = task_queue->CreateTaskQueue();
int test_val = 0;
// order 0 in platform_queue
task_queue->RegisterTask(
platform_queue, [&test_val]() { test_val = 0; }, fml::TimePoint::Now());
// order 1 in platform_queue
task_queue->RegisterTask(
platform_queue, [&test_val]() { test_val = 1; }, fml::TimePoint::Now());
// order 2 in raster_queue
task_queue->RegisterTask(
raster_queue, [&test_val]() { test_val = 2; }, fml::TimePoint::Now());
// order 3 in raster_queue
task_queue->RegisterTask(
raster_queue, [&test_val]() { test_val = 3; }, fml::TimePoint::Now());
// order 4 in platform_queue
task_queue->RegisterTask(
platform_queue, [&test_val]() { test_val = 4; }, fml::TimePoint::Now());
// order 5 in raster_queue
task_queue->RegisterTask(
raster_queue, [&test_val]() { test_val = 5; }, fml::TimePoint::Now());
ASSERT_TRUE(task_queue->Merge(platform_queue, raster_queue));
ASSERT_TRUE(task_queue->Owns(platform_queue, raster_queue));
const auto now = fml::TimePoint::Now();
// The right order after merged and consumed 3 tasks:
// "test_val = 0" in platform_queue
// "test_val = 1" in platform_queue
// "test_val = 2" in raster_queue (running on platform)
for (int i = 0; i < 3; i++) {
fml::closure invocation = task_queue->GetNextTaskToRun(platform_queue, now);
ASSERT_FALSE(!invocation);
invocation();
ASSERT_TRUE(test_val == i);
}
ASSERT_TRUE(task_queue->GetNumPendingTasks(platform_queue) == 3);
ASSERT_TRUE(task_queue->GetNumPendingTasks(raster_queue) == 0);
ASSERT_TRUE(task_queue->Unmerge(platform_queue, raster_queue));
ASSERT_FALSE(task_queue->Owns(platform_queue, raster_queue));
// The right order after unmerged and left 3 tasks:
// "test_val = 3" in raster_queue
// "test_val = 4" in platform_queue
// "test_val = 5" in raster_queue
// platform_queue has 1 task left: "test_val = 4"
{
ASSERT_TRUE(task_queue->GetNumPendingTasks(platform_queue) == 1);
fml::closure invocation = task_queue->GetNextTaskToRun(platform_queue, now);
ASSERT_FALSE(!invocation);
invocation();
ASSERT_TRUE(test_val == 4);
ASSERT_TRUE(task_queue->GetNumPendingTasks(platform_queue) == 0);
}
// raster_queue has 2 tasks left: "test_val = 3" and "test_val = 5"
{
ASSERT_TRUE(task_queue->GetNumPendingTasks(raster_queue) == 2);
fml::closure invocation = task_queue->GetNextTaskToRun(raster_queue, now);
ASSERT_FALSE(!invocation);
invocation();
ASSERT_TRUE(test_val == 3);
}
{
ASSERT_TRUE(task_queue->GetNumPendingTasks(raster_queue) == 1);
fml::closure invocation = task_queue->GetNextTaskToRun(raster_queue, now);
ASSERT_FALSE(!invocation);
invocation();
ASSERT_TRUE(test_val == 5);
ASSERT_TRUE(task_queue->GetNumPendingTasks(raster_queue) == 0);
}
}
void TestNotifyObservers(fml::TaskQueueId queue_id) {
auto task_queue = fml::MessageLoopTaskQueues::GetInstance();
std::vector<fml::closure> observers =
task_queue->GetObserversToNotify(queue_id);
for (const auto& observer : observers) {
observer();
}
}
TEST(MessageLoopTaskQueue, AddRemoveNotifyObservers) {
auto task_queue = fml::MessageLoopTaskQueues::GetInstance();
auto queue_id = task_queue->CreateTaskQueue();
int test_val = 0;
intptr_t key = 123;
task_queue->AddTaskObserver(queue_id, key, [&test_val]() { test_val = 1; });
TestNotifyObservers(queue_id);
ASSERT_TRUE(test_val == 1);
test_val = 0;
task_queue->RemoveTaskObserver(queue_id, key);
TestNotifyObservers(queue_id);
ASSERT_TRUE(test_val == 0);
}
TEST(MessageLoopTaskQueue, WakeUpIndependentOfTime) {
auto task_queue = fml::MessageLoopTaskQueues::GetInstance();
auto queue_id = task_queue->CreateTaskQueue();
int num_wakes = 0;
auto wakeable = std::make_unique<TestWakeable>(
[&num_wakes](fml::TimePoint wake_time) { ++num_wakes; });
task_queue->SetWakeable(queue_id, wakeable.get());
task_queue->RegisterTask(queue_id, []() {}, ChronoTicksSinceEpoch());
task_queue->RegisterTask(queue_id, []() {}, fml::TimePoint::Max());
ASSERT_TRUE(num_wakes == 2);
}
TEST(MessageLoopTaskQueue, WokenUpWithNewerTime) {
auto task_queue = fml::MessageLoopTaskQueues::GetInstance();
auto queue_id = task_queue->CreateTaskQueue();
fml::CountDownLatch latch(2);
fml::TimePoint expected = fml::TimePoint::Max();
auto wakeable = std::make_unique<TestWakeable>(
[&latch, &expected](fml::TimePoint wake_time) {
ASSERT_TRUE(wake_time == expected);
latch.CountDown();
});
task_queue->SetWakeable(queue_id, wakeable.get());
task_queue->RegisterTask(queue_id, []() {}, fml::TimePoint::Max());
const auto now = ChronoTicksSinceEpoch();
expected = now;
task_queue->RegisterTask(queue_id, []() {}, now);
latch.Wait();
}
TEST(MessageLoopTaskQueue, NotifyObserversWhileCreatingQueues) {
auto task_queues = fml::MessageLoopTaskQueues::GetInstance();
fml::TaskQueueId queue_id = task_queues->CreateTaskQueue();
fml::AutoResetWaitableEvent first_observer_executing, before_second_observer;
task_queues->AddTaskObserver(queue_id, queue_id + 1, [&]() {
first_observer_executing.Signal();
before_second_observer.Wait();
});
for (int i = 0; i < 100; i++) {
task_queues->AddTaskObserver(queue_id, queue_id + i + 2, [] {});
}
std::thread notify_observers([&]() { TestNotifyObservers(queue_id); });
first_observer_executing.Wait();
for (int i = 0; i < 100; i++) {
task_queues->CreateTaskQueue();
}
before_second_observer.Signal();
notify_observers.join();
}
TEST(MessageLoopTaskQueue, QueueDoNotOwnItself) {
auto task_queue = fml::MessageLoopTaskQueues::GetInstance();
auto queue_id = task_queue->CreateTaskQueue();
ASSERT_FALSE(task_queue->Owns(queue_id, queue_id));
}
TEST(MessageLoopTaskQueue, QueueDoNotOwnUnmergedTaskQueueId) {
auto task_queue = fml::MessageLoopTaskQueues::GetInstance();
ASSERT_FALSE(task_queue->Owns(task_queue->CreateTaskQueue(), kUnmerged));
ASSERT_FALSE(task_queue->Owns(kUnmerged, task_queue->CreateTaskQueue()));
ASSERT_FALSE(task_queue->Owns(kUnmerged, kUnmerged));
}
TEST(MessageLoopTaskQueue, QueueOwnsMergedTaskQueueId) {
auto task_queue = fml::MessageLoopTaskQueues::GetInstance();
auto platform_queue = task_queue->CreateTaskQueue();
auto raster_queue = task_queue->CreateTaskQueue();
ASSERT_FALSE(task_queue->Owns(platform_queue, raster_queue));
ASSERT_FALSE(task_queue->Owns(raster_queue, platform_queue));
task_queue->Merge(platform_queue, raster_queue);
ASSERT_TRUE(task_queue->Owns(platform_queue, raster_queue));
ASSERT_FALSE(task_queue->Owns(raster_queue, platform_queue));
}
//------------------------------------------------------------------------------
/// Verifies that tasks can be added to task queues concurrently.
///
TEST(MessageLoopTaskQueue, ConcurrentQueueAndTaskCreatingCounts) {
auto task_queues = fml::MessageLoopTaskQueues::GetInstance();
// kThreadCount threads post kThreadTaskCount tasks each to kTaskQueuesCount
// task queues. Each thread picks a task queue randomly for each task.
constexpr size_t kThreadCount = 4;
constexpr size_t kTaskQueuesCount = 2;
constexpr size_t kThreadTaskCount = 500;
std::vector<TaskQueueId> task_queue_ids;
for (size_t i = 0; i < kTaskQueuesCount; ++i) {
task_queue_ids.emplace_back(task_queues->CreateTaskQueue());
}
ASSERT_EQ(task_queue_ids.size(), kTaskQueuesCount);
fml::CountDownLatch tasks_posted_latch(kThreadCount);
auto thread_main = [&]() {
for (size_t i = 0; i < kThreadTaskCount; i++) {
const auto current_task_queue_id =
task_queue_ids[std::rand() % kTaskQueuesCount];
const auto empty_task = []() {};
// The timepoint doesn't matter as the queue is never going to be drained.
const auto task_timepoint = ChronoTicksSinceEpoch();
task_queues->RegisterTask(current_task_queue_id, empty_task,
task_timepoint);
}
tasks_posted_latch.CountDown();
};
std::vector<std::thread> threads;
for (size_t i = 0; i < kThreadCount; i++) {
threads.emplace_back(std::thread{thread_main});
}
ASSERT_EQ(threads.size(), kThreadCount);
for (size_t i = 0; i < kThreadCount; i++) {
threads[i].join();
}
// All tasks have been posted by now. Check that they are all pending.
size_t pending_tasks = 0u;
std::for_each(task_queue_ids.begin(), task_queue_ids.end(),
[&](const auto& queue) {
pending_tasks += task_queues->GetNumPendingTasks(queue);
});
ASSERT_EQ(pending_tasks, kThreadCount * kThreadTaskCount);
}
TEST(MessageLoopTaskQueue, RegisterTaskWakesUpOwnerQueue) {
auto task_queue = fml::MessageLoopTaskQueues::GetInstance();
auto platform_queue = task_queue->CreateTaskQueue();
auto raster_queue = task_queue->CreateTaskQueue();
std::vector<fml::TimePoint> wakes;
auto wakeable1 = std::make_unique<TestWakeable>(
[&wakes](fml::TimePoint wake_time) { wakes.push_back(wake_time); });
auto wakeable2 = std::make_unique<TestWakeable>([](fml::TimePoint wake_time) {
// The raster queue is owned by the platform queue.
ASSERT_FALSE(true);
});
task_queue->SetWakeable(platform_queue, wakeable1.get());
task_queue->SetWakeable(raster_queue, wakeable2.get());
auto time1 = ChronoTicksSinceEpoch() + fml::TimeDelta::FromMilliseconds(1);
auto time2 = ChronoTicksSinceEpoch() + fml::TimeDelta::FromMilliseconds(2);
ASSERT_EQ(0UL, wakes.size());
task_queue->RegisterTask(platform_queue, []() {}, time1);
ASSERT_EQ(1UL, wakes.size());
ASSERT_EQ(time1, wakes[0]);
task_queue->Merge(platform_queue, raster_queue);
task_queue->RegisterTask(raster_queue, []() {}, time2);
ASSERT_EQ(3UL, wakes.size());
ASSERT_EQ(time1, wakes[1]);
ASSERT_EQ(time1, wakes[2]);
}
} // namespace testing
} // namespace fml
| engine/fml/message_loop_task_queues_unittests.cc/0 | {
"file_path": "engine/fml/message_loop_task_queues_unittests.cc",
"repo_id": "engine",
"token_count": 5730
} | 184 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/fml/platform/android/scoped_java_ref.h"
#include "flutter/fml/logging.h"
#include "flutter/fml/platform/android/jni_util.h"
namespace fml {
namespace jni {
static const int kDefaultLocalFrameCapacity = 16;
ScopedJavaLocalFrame::ScopedJavaLocalFrame(JNIEnv* env) : env_(env) {
[[maybe_unused]] int failed =
env_->PushLocalFrame(kDefaultLocalFrameCapacity);
FML_DCHECK(!failed);
}
ScopedJavaLocalFrame::ScopedJavaLocalFrame(JNIEnv* env, int capacity)
: env_(env) {
[[maybe_unused]] int failed = env_->PushLocalFrame(capacity);
FML_DCHECK(!failed);
}
ScopedJavaLocalFrame::~ScopedJavaLocalFrame() {
env_->PopLocalFrame(NULL);
}
JavaRef<jobject>::JavaRef() : obj_(NULL) {}
JavaRef<jobject>::JavaRef(JNIEnv* env, jobject obj) : obj_(obj) {
if (obj) {
FML_DCHECK(env && env->GetObjectRefType(obj) == JNILocalRefType);
}
}
JavaRef<jobject>::~JavaRef() = default;
JNIEnv* JavaRef<jobject>::SetNewLocalRef(JNIEnv* env, jobject obj) {
if (!env) {
env = AttachCurrentThread();
} else {
FML_DCHECK(env == AttachCurrentThread()); // Is |env| on correct thread.
}
if (obj) {
obj = env->NewLocalRef(obj);
}
if (obj_) {
env->DeleteLocalRef(obj_);
}
obj_ = obj;
return env;
}
void JavaRef<jobject>::SetNewGlobalRef(JNIEnv* env, jobject obj) {
if (!env) {
env = AttachCurrentThread();
} else {
FML_DCHECK(env == AttachCurrentThread()); // Is |env| on correct thread.
}
if (obj) {
obj = env->NewGlobalRef(obj);
}
if (obj_) {
env->DeleteGlobalRef(obj_);
}
obj_ = obj;
}
void JavaRef<jobject>::ResetLocalRef(JNIEnv* env) {
if (obj_) {
FML_DCHECK(env == AttachCurrentThread()); // Is |env| on correct thread.
env->DeleteLocalRef(obj_);
obj_ = NULL;
}
}
void JavaRef<jobject>::ResetGlobalRef() {
if (obj_) {
AttachCurrentThread()->DeleteGlobalRef(obj_);
obj_ = NULL;
}
}
jobject JavaRef<jobject>::ReleaseInternal() {
jobject obj = obj_;
obj_ = NULL;
return obj;
}
} // namespace jni
} // namespace fml
| engine/fml/platform/android/scoped_java_ref.cc/0 | {
"file_path": "engine/fml/platform/android/scoped_java_ref.cc",
"repo_id": "engine",
"token_count": 867
} | 185 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/fml/platform/darwin/scoped_nsobject.h"
namespace fml {
namespace internal {
id ScopedNSProtocolTraitsRetain(id obj) {
return [obj retain];
}
id ScopedNSProtocolTraitsAutoRelease(id obj) {
return [obj autorelease];
}
void ScopedNSProtocolTraitsRelease(id obj) {
return [obj release];
}
} // namespace internal
} // namespace fml
| engine/fml/platform/darwin/scoped_nsobject.mm/0 | {
"file_path": "engine/fml/platform/darwin/scoped_nsobject.mm",
"repo_id": "engine",
"token_count": 172
} | 186 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_FML_PLATFORM_FUCHSIA_LOG_STATE_H_
#define FLUTTER_FML_PLATFORM_FUCHSIA_LOG_STATE_H_
#include <fidl/fuchsia.logger/cpp/fidl.h>
#include <lib/fidl/cpp/wire/internal/transport_channel.h>
#include <lib/zx/socket.h>
#include <atomic>
#include <initializer_list>
#include <memory>
#include <mutex>
#include <string>
#include <vector>
namespace fml {
// Class for holding the global connection to the Fuchsia LogSink service.
class LogState {
public:
// Connects to the Fuchsia LogSink service.
LogState();
// Get the socket for sending log messages.
const zx::socket& socket() const { return socket_; }
// Get the current list of tags.
std::shared_ptr<const std::vector<std::string>> tags() const {
return std::atomic_load(&tags_);
}
// Take ownership of the log sink channel (e.g. for LogInterestListener).
// This is thread-safe.
fidl::ClientEnd<::fuchsia_logger::LogSink> TakeClientEnd();
// Updates the default tags.
// This is thread-safe.
void SetTags(const std::initializer_list<std::string>& tags);
// Get the default instance of LogState.
static LogState& Default();
private:
std::mutex mutex_;
fidl::ClientEnd<::fuchsia_logger::LogSink> client_end_;
zx::socket socket_;
std::shared_ptr<const std::vector<std::string>> tags_;
};
} // namespace fml
#endif // FLUTTER_FML_PLATFORM_FUCHSIA_LOG_STATE_H_
| engine/fml/platform/fuchsia/log_state.h/0 | {
"file_path": "engine/fml/platform/fuchsia/log_state.h",
"repo_id": "engine",
"token_count": 536
} | 187 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/fml/platform/win/wstring_conversion.h"
#include <codecvt>
#include <locale>
#include <string>
namespace fml {
using WideStringConverter =
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t>;
std::string WideStringToUtf8(const std::wstring_view str) {
WideStringConverter converter;
return converter.to_bytes(str.data());
}
std::wstring Utf8ToWideString(const std::string_view str) {
WideStringConverter converter;
return converter.from_bytes(str.data());
}
std::u16string WideStringToUtf16(const std::wstring_view str) {
static_assert(sizeof(std::wstring::value_type) ==
sizeof(std::u16string::value_type));
return {begin(str), end(str)};
}
std::wstring Utf16ToWideString(const std::u16string_view str) {
static_assert(sizeof(std::wstring::value_type) ==
sizeof(std::u16string::value_type));
return {begin(str), end(str)};
}
} // namespace fml
| engine/fml/platform/win/wstring_conversion.cc/0 | {
"file_path": "engine/fml/platform/win/wstring_conversion.cc",
"repo_id": "engine",
"token_count": 408
} | 188 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_FML_SYNCHRONIZATION_ATOMIC_OBJECT_H_
#define FLUTTER_FML_SYNCHRONIZATION_ATOMIC_OBJECT_H_
#include <mutex>
namespace fml {
// A wrapper for an object instance that can be read or written atomically.
template <typename T>
class AtomicObject {
public:
AtomicObject() = default;
explicit AtomicObject(T object) : object_(object) {}
T Load() const {
std::scoped_lock lock(mutex_);
return object_;
}
void Store(const T& object) {
std::scoped_lock lock(mutex_);
object_ = object;
}
private:
mutable std::mutex mutex_;
T object_;
};
} // namespace fml
#endif // FLUTTER_FML_SYNCHRONIZATION_ATOMIC_OBJECT_H_
| engine/fml/synchronization/atomic_object.h/0 | {
"file_path": "engine/fml/synchronization/atomic_object.h",
"repo_id": "engine",
"token_count": 298
} | 189 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_FML_TASK_QUEUE_ID_H_
#define FLUTTER_FML_TASK_QUEUE_ID_H_
#include "flutter/fml/logging.h"
namespace fml {
/**
* `MessageLoopTaskQueues` task dispatcher's internal task queue identifier.
*/
class TaskQueueId {
public:
/// This constant indicates whether a task queue has been subsumed by a task
/// runner.
static const size_t kUnmerged;
/// Intializes a task queue with the given value as it's ID.
explicit TaskQueueId(size_t value) : value_(value) {}
operator size_t() const { // NOLINT(google-explicit-constructor)
return value_;
}
private:
size_t value_ = kUnmerged;
};
} // namespace fml
#endif // FLUTTER_FML_TASK_QUEUE_ID_H_
| engine/fml/task_queue_id.h/0 | {
"file_path": "engine/fml/task_queue_id.h",
"repo_id": "engine",
"token_count": 293
} | 190 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/fml/time/chrono_timestamp_provider.h"
#include "flutter/runtime/dart_timestamp_provider.h"
#include <thread>
#include "gtest/gtest.h"
namespace fml {
namespace {
TEST(TimePoint, Control) {
EXPECT_LT(TimePoint::Min(), ChronoTicksSinceEpoch());
EXPECT_GT(TimePoint::Max(), ChronoTicksSinceEpoch());
}
TEST(TimePoint, DartClockIsMonotonic) {
using namespace std::chrono_literals;
const auto t1 = flutter::DartTimelineTicksSinceEpoch();
std::this_thread::sleep_for(1us);
const auto t2 = flutter::DartTimelineTicksSinceEpoch();
std::this_thread::sleep_for(1us);
const auto t3 = flutter::DartTimelineTicksSinceEpoch();
EXPECT_LT(TimePoint::Min(), t1);
EXPECT_LE(t1, t2);
EXPECT_LE(t2, t3);
EXPECT_LT(t3, TimePoint::Max());
}
} // namespace
} // namespace fml
| engine/fml/time/time_point_unittest.cc/0 | {
"file_path": "engine/fml/time/time_point_unittest.cc",
"repo_id": "engine",
"token_count": 358
} | 191 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_AIKS_AIKS_CONTEXT_H_
#define FLUTTER_IMPELLER_AIKS_AIKS_CONTEXT_H_
#include <memory>
#include "flutter/fml/macros.h"
#include "impeller/entity/contents/content_context.h"
#include "impeller/renderer/context.h"
#include "impeller/renderer/render_target.h"
#include "impeller/typographer/typographer_context.h"
namespace impeller {
struct Picture;
class AiksContext {
public:
/// Construct a new AiksContext.
///
/// @param context The Impeller context that Aiks should use for
/// allocating resources and executing device
/// commands. Required.
/// @param typographer_context The text backend to use for rendering text. If
/// `nullptr` is supplied, then attempting to draw
/// text with Aiks will result in validation
/// errors.
/// @param render_target_allocator Injects a render target allocator or
/// allocates its own if none is supplied.
AiksContext(std::shared_ptr<Context> context,
std::shared_ptr<TypographerContext> typographer_context,
std::optional<std::shared_ptr<RenderTargetAllocator>>
render_target_allocator = std::nullopt);
~AiksContext();
bool IsValid() const;
std::shared_ptr<Context> GetContext() const;
ContentContext& GetContentContext() const;
bool Render(const Picture& picture,
RenderTarget& render_target,
bool reset_host_buffer);
private:
std::shared_ptr<Context> context_;
std::unique_ptr<ContentContext> content_context_;
bool is_valid_ = false;
AiksContext(const AiksContext&) = delete;
AiksContext& operator=(const AiksContext&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_AIKS_AIKS_CONTEXT_H_
| engine/impeller/aiks/aiks_context.h/0 | {
"file_path": "engine/impeller/aiks/aiks_context.h",
"repo_id": "engine",
"token_count": 830
} | 192 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/aiks/color_filter.h"
#include <utility>
#include "impeller/entity/contents/filters/color_filter_contents.h"
#include "impeller/entity/contents/filters/filter_contents.h"
#include "impeller/entity/contents/filters/inputs/filter_input.h"
#include "impeller/geometry/color.h"
namespace impeller {
/*******************************************************************************
******* ColorFilter
******************************************************************************/
ColorFilter::ColorFilter() = default;
ColorFilter::~ColorFilter() = default;
std::shared_ptr<ColorFilter> ColorFilter::MakeBlend(BlendMode blend_mode,
Color color) {
return std::make_shared<BlendColorFilter>(blend_mode, color);
}
std::shared_ptr<ColorFilter> ColorFilter::MakeMatrix(ColorMatrix color_matrix) {
return std::make_shared<MatrixColorFilter>(color_matrix);
}
std::shared_ptr<ColorFilter> ColorFilter::MakeSrgbToLinear() {
return std::make_shared<SrgbToLinearColorFilter>();
}
std::shared_ptr<ColorFilter> ColorFilter::MakeLinearToSrgb() {
return std::make_shared<LinearToSrgbColorFilter>();
}
std::shared_ptr<ColorFilter> ColorFilter::MakeComposed(
const std::shared_ptr<ColorFilter>& outer,
const std::shared_ptr<ColorFilter>& inner) {
return std::make_shared<ComposedColorFilter>(outer, inner);
}
/*******************************************************************************
******* BlendColorFilter
******************************************************************************/
BlendColorFilter::BlendColorFilter(BlendMode blend_mode, Color color)
: blend_mode_(blend_mode), color_(color) {}
BlendColorFilter::~BlendColorFilter() = default;
std::shared_ptr<ColorFilterContents> BlendColorFilter::WrapWithGPUColorFilter(
std::shared_ptr<FilterInput> input,
ColorFilterContents::AbsorbOpacity absorb_opacity) const {
auto filter =
ColorFilterContents::MakeBlend(blend_mode_, {std::move(input)}, color_);
filter->SetAbsorbOpacity(absorb_opacity);
return filter;
}
ColorFilter::ColorFilterProc BlendColorFilter::GetCPUColorFilterProc() const {
return [filter_blend_mode = blend_mode_, filter_color = color_](Color color) {
return color.Blend(filter_color, filter_blend_mode);
};
}
std::shared_ptr<ColorFilter> BlendColorFilter::Clone() const {
return std::make_shared<BlendColorFilter>(*this);
}
/*******************************************************************************
******* MatrixColorFilter
******************************************************************************/
MatrixColorFilter::MatrixColorFilter(ColorMatrix color_matrix)
: color_matrix_(color_matrix) {}
MatrixColorFilter::~MatrixColorFilter() = default;
std::shared_ptr<ColorFilterContents> MatrixColorFilter::WrapWithGPUColorFilter(
std::shared_ptr<FilterInput> input,
ColorFilterContents::AbsorbOpacity absorb_opacity) const {
auto filter =
ColorFilterContents::MakeColorMatrix({std::move(input)}, color_matrix_);
filter->SetAbsorbOpacity(absorb_opacity);
return filter;
}
ColorFilter::ColorFilterProc MatrixColorFilter::GetCPUColorFilterProc() const {
return [color_matrix = color_matrix_](Color color) {
return color.ApplyColorMatrix(color_matrix);
};
}
std::shared_ptr<ColorFilter> MatrixColorFilter::Clone() const {
return std::make_shared<MatrixColorFilter>(*this);
}
/*******************************************************************************
******* SrgbToLinearColorFilter
******************************************************************************/
SrgbToLinearColorFilter::SrgbToLinearColorFilter() = default;
SrgbToLinearColorFilter::~SrgbToLinearColorFilter() = default;
std::shared_ptr<ColorFilterContents>
SrgbToLinearColorFilter::WrapWithGPUColorFilter(
std::shared_ptr<FilterInput> input,
ColorFilterContents::AbsorbOpacity absorb_opacity) const {
auto filter = ColorFilterContents::MakeSrgbToLinearFilter({std::move(input)});
filter->SetAbsorbOpacity(absorb_opacity);
return filter;
}
ColorFilter::ColorFilterProc SrgbToLinearColorFilter::GetCPUColorFilterProc()
const {
return [](Color color) { return color.SRGBToLinear(); };
}
std::shared_ptr<ColorFilter> SrgbToLinearColorFilter::Clone() const {
return std::make_shared<SrgbToLinearColorFilter>(*this);
}
/*******************************************************************************
******* LinearToSrgbColorFilter
******************************************************************************/
LinearToSrgbColorFilter::LinearToSrgbColorFilter() = default;
LinearToSrgbColorFilter::~LinearToSrgbColorFilter() = default;
std::shared_ptr<ColorFilterContents>
LinearToSrgbColorFilter::WrapWithGPUColorFilter(
std::shared_ptr<FilterInput> input,
ColorFilterContents::AbsorbOpacity absorb_opacity) const {
auto filter = ColorFilterContents::MakeSrgbToLinearFilter({std::move(input)});
filter->SetAbsorbOpacity(absorb_opacity);
return filter;
}
ColorFilter::ColorFilterProc LinearToSrgbColorFilter::GetCPUColorFilterProc()
const {
return [](Color color) { return color.LinearToSRGB(); };
}
std::shared_ptr<ColorFilter> LinearToSrgbColorFilter::Clone() const {
return std::make_shared<LinearToSrgbColorFilter>(*this);
}
/*******************************************************************************
******* ComposedColorFilter
******************************************************************************/
ComposedColorFilter::ComposedColorFilter(
const std::shared_ptr<ColorFilter>& outer,
const std::shared_ptr<ColorFilter>& inner)
: outer_(outer), inner_(inner) {}
ComposedColorFilter::~ComposedColorFilter() = default;
std::shared_ptr<ColorFilterContents>
ComposedColorFilter::WrapWithGPUColorFilter(
std::shared_ptr<FilterInput> input,
ColorFilterContents::AbsorbOpacity absorb_opacity) const {
std::shared_ptr<FilterContents> inner = inner_->WrapWithGPUColorFilter(
input, ColorFilterContents::AbsorbOpacity::kNo);
return outer_->WrapWithGPUColorFilter(FilterInput::Make(inner),
absorb_opacity);
}
// |ColorFilter|
ColorFilter::ColorFilterProc ComposedColorFilter::GetCPUColorFilterProc()
const {
return [inner = inner_, outer = outer_](Color color) {
auto inner_proc = inner->GetCPUColorFilterProc();
auto outer_proc = outer->GetCPUColorFilterProc();
return outer_proc(inner_proc(color));
};
}
// |ColorFilter|
std::shared_ptr<ColorFilter> ComposedColorFilter::Clone() const {
return std::make_shared<ComposedColorFilter>(outer_, inner_);
}
} // namespace impeller
| engine/impeller/aiks/color_filter.cc/0 | {
"file_path": "engine/impeller/aiks/color_filter.cc",
"repo_id": "engine",
"token_count": 2084
} | 193 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_AIKS_TESTING_CONTEXT_MOCK_H_
#define FLUTTER_IMPELLER_AIKS_TESTING_CONTEXT_MOCK_H_
#include <string>
#include <utility>
#include <vector>
#include "gmock/gmock-function-mocker.h"
#include "gmock/gmock.h"
#include "impeller/renderer/command_buffer.h"
#include "impeller/renderer/context.h"
#include "impeller/renderer/render_target.h"
namespace impeller {
namespace testing {
class CommandBufferMock : public CommandBuffer {
public:
explicit CommandBufferMock(std::weak_ptr<const Context> context)
: CommandBuffer(std::move(context)) {}
MOCK_METHOD(bool, IsValid, (), (const, override));
MOCK_METHOD(void, SetLabel, (const std::string& label), (const, override));
MOCK_METHOD(std::shared_ptr<RenderPass>,
OnCreateRenderPass,
(RenderTarget render_target),
(override));
static std::shared_ptr<RenderPass> ForwardOnCreateRenderPass(
CommandBuffer* command_buffer,
const RenderTarget& render_target) {
return command_buffer->OnCreateRenderPass(render_target);
}
MOCK_METHOD(std::shared_ptr<BlitPass>, OnCreateBlitPass, (), (override));
static std::shared_ptr<BlitPass> ForwardOnCreateBlitPass(
CommandBuffer* command_buffer) {
return command_buffer->OnCreateBlitPass();
}
MOCK_METHOD(bool,
OnSubmitCommands,
(CompletionCallback callback),
(override));
static bool ForwardOnSubmitCommands(CommandBuffer* command_buffer,
CompletionCallback callback) {
return command_buffer->OnSubmitCommands(std::move(callback));
}
MOCK_METHOD(void, OnWaitUntilScheduled, (), (override));
static void ForwardOnWaitUntilScheduled(CommandBuffer* command_buffer) {
return command_buffer->OnWaitUntilScheduled();
}
MOCK_METHOD(std::shared_ptr<ComputePass>,
OnCreateComputePass,
(),
(override));
static std::shared_ptr<ComputePass> ForwardOnCreateComputePass(
CommandBuffer* command_buffer) {
return command_buffer->OnCreateComputePass();
}
};
class ContextMock : public Context {
public:
MOCK_METHOD(std::string, DescribeGpuModel, (), (const, override));
MOCK_METHOD(Context::BackendType, GetBackendType, (), (const, override));
MOCK_METHOD(bool, IsValid, (), (const, override));
MOCK_METHOD(const std::shared_ptr<const Capabilities>&,
GetCapabilities,
(),
(const, override));
MOCK_METHOD(bool,
UpdateOffscreenLayerPixelFormat,
(PixelFormat format),
(override));
MOCK_METHOD(std::shared_ptr<Allocator>,
GetResourceAllocator,
(),
(const, override));
MOCK_METHOD(std::shared_ptr<ShaderLibrary>,
GetShaderLibrary,
(),
(const, override));
MOCK_METHOD(std::shared_ptr<SamplerLibrary>,
GetSamplerLibrary,
(),
(const, override));
MOCK_METHOD(std::shared_ptr<PipelineLibrary>,
GetPipelineLibrary,
(),
(const, override));
MOCK_METHOD(std::shared_ptr<CommandBuffer>,
CreateCommandBuffer,
(),
(const, override));
MOCK_METHOD(std::shared_ptr<CommandQueue>,
GetCommandQueue,
(),
(const override));
MOCK_METHOD(void, Shutdown, (), (override));
MOCK_METHOD(void,
InitializeCommonlyUsedShadersIfNeeded,
(),
(const, override));
};
} // namespace testing
} // namespace impeller
#endif // FLUTTER_IMPELLER_AIKS_TESTING_CONTEXT_MOCK_H_
| engine/impeller/aiks/testing/context_mock.h/0 | {
"file_path": "engine/impeller/aiks/testing/context_mock.h",
"repo_id": "engine",
"token_count": 1626
} | 194 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/compiler/compiler.h"
#include <cstdint>
#include <filesystem>
#include <memory>
#include <optional>
#include <sstream>
#include <string>
#include <utility>
#include "flutter/fml/paths.h"
#include "impeller/base/allocation.h"
#include "impeller/compiler/compiler_backend.h"
#include "impeller/compiler/constants.h"
#include "impeller/compiler/includer.h"
#include "impeller/compiler/logger.h"
#include "impeller/compiler/spirv_compiler.h"
#include "impeller/compiler/types.h"
#include "impeller/compiler/uniform_sorter.h"
#include "impeller/compiler/utilities.h"
namespace impeller {
namespace compiler {
static uint32_t ParseMSLVersion(const std::string& msl_version) {
std::stringstream sstream(msl_version);
std::string version_part;
uint32_t major = 1;
uint32_t minor = 2;
uint32_t patch = 0;
if (std::getline(sstream, version_part, '.')) {
major = std::stoi(version_part);
if (std::getline(sstream, version_part, '.')) {
minor = std::stoi(version_part);
if (std::getline(sstream, version_part, '.')) {
patch = std::stoi(version_part);
}
}
}
if (major < 1 || (major == 1 && minor < 2)) {
std::cerr << "--metal-version version must be at least 1.2. Have "
<< msl_version << std::endl;
}
return spirv_cross::CompilerMSL::Options::make_msl_version(major, minor,
patch);
}
static CompilerBackend CreateMSLCompiler(
const spirv_cross::ParsedIR& ir,
const SourceOptions& source_options,
std::optional<uint32_t> msl_version_override = {}) {
auto sl_compiler = std::make_shared<spirv_cross::CompilerMSL>(ir);
spirv_cross::CompilerMSL::Options sl_options;
sl_options.platform =
TargetPlatformToMSLPlatform(source_options.target_platform);
sl_options.msl_version = msl_version_override.value_or(
ParseMSLVersion(source_options.metal_version));
sl_options.ios_use_simdgroup_functions =
sl_options.is_ios() &&
sl_options.msl_version >=
spirv_cross::CompilerMSL::Options::make_msl_version(2, 4, 0);
sl_options.use_framebuffer_fetch_subpasses = true;
sl_compiler->set_msl_options(sl_options);
// Sort the float and sampler uniforms according to their declared/decorated
// order. For user authored fragment shaders, the API for setting uniform
// values uses the index of the uniform in the declared order. By default, the
// metal backend of spirv-cross will order uniforms according to usage. To fix
// this, we use the sorted order and the add_msl_resource_binding API to force
// the ordering to match the declared order. Note that while this code runs
// for all compiled shaders, it will only affect vertex and fragment shaders
// due to the specified stage.
auto floats =
SortUniforms(&ir, sl_compiler.get(), spirv_cross::SPIRType::Float);
auto images =
SortUniforms(&ir, sl_compiler.get(), spirv_cross::SPIRType::SampledImage);
spv::ExecutionModel execution_model =
spv::ExecutionModel::ExecutionModelFragment;
if (source_options.type == SourceType::kVertexShader) {
execution_model = spv::ExecutionModel::ExecutionModelVertex;
}
uint32_t buffer_offset = 0;
uint32_t sampler_offset = 0;
for (auto& float_id : floats) {
sl_compiler->add_msl_resource_binding(
{.stage = execution_model,
.basetype = spirv_cross::SPIRType::BaseType::Float,
.desc_set = sl_compiler->get_decoration(float_id,
spv::DecorationDescriptorSet),
.binding =
sl_compiler->get_decoration(float_id, spv::DecorationBinding),
.count = 1u,
.msl_buffer = buffer_offset});
buffer_offset++;
}
for (auto& image_id : images) {
sl_compiler->add_msl_resource_binding({
.stage = execution_model,
.basetype = spirv_cross::SPIRType::BaseType::SampledImage,
.desc_set =
sl_compiler->get_decoration(image_id, spv::DecorationDescriptorSet),
.binding =
sl_compiler->get_decoration(image_id, spv::DecorationBinding),
.count = 1u,
// A sampled image is both an image and a sampler, so both
// offsets need to be set or depending on the partiular shader
// the bindings may be incorrect.
.msl_texture = sampler_offset,
.msl_sampler = sampler_offset,
});
sampler_offset++;
}
return CompilerBackend(sl_compiler);
}
static CompilerBackend CreateVulkanCompiler(
const spirv_cross::ParsedIR& ir,
const SourceOptions& source_options) {
auto gl_compiler = std::make_shared<spirv_cross::CompilerGLSL>(ir);
spirv_cross::CompilerGLSL::Options sl_options;
sl_options.force_zero_initialized_variables = true;
sl_options.vertex.fixup_clipspace = true;
sl_options.vulkan_semantics = true;
gl_compiler->set_common_options(sl_options);
return CompilerBackend(gl_compiler);
}
static CompilerBackend CreateGLSLCompiler(const spirv_cross::ParsedIR& ir,
const SourceOptions& source_options) {
auto gl_compiler = std::make_shared<spirv_cross::CompilerGLSL>(ir);
// Walk the variables and insert the external image extension if any of them
// begins with the external texture prefix. Unfortunately, we can't walk
// `gl_compiler->get_shader_resources().separate_samplers` until the compiler
// is further along.
//
// Unfortunately, we can't just let the shader author add this extension and
// use `samplerExternalOES` directly because compiling to spirv requires the
// source language profile to be at least 310 ES, but this extension is
// incompatible with ES 310+.
for (auto& id : ir.ids_for_constant_or_variable) {
if (StringStartsWith(ir.get_name(id), kExternalTexturePrefix)) {
gl_compiler->require_extension("GL_OES_EGL_image_external");
break;
}
}
spirv_cross::CompilerGLSL::Options sl_options;
sl_options.force_zero_initialized_variables = true;
sl_options.vertex.fixup_clipspace = true;
if (source_options.target_platform == TargetPlatform::kOpenGLES ||
source_options.target_platform == TargetPlatform::kRuntimeStageGLES) {
sl_options.version = source_options.gles_language_version > 0
? source_options.gles_language_version
: 100;
sl_options.es = true;
if (source_options.require_framebuffer_fetch &&
source_options.type == SourceType::kFragmentShader) {
gl_compiler->remap_ext_framebuffer_fetch(0, 0, true);
}
gl_compiler->set_variable_type_remap_callback(
[&](const spirv_cross::SPIRType& type, const std::string& var_name,
std::string& name_of_type) {
if (StringStartsWith(var_name, kExternalTexturePrefix)) {
name_of_type = "samplerExternalOES";
}
});
} else {
sl_options.version = source_options.gles_language_version > 0
? source_options.gles_language_version
: 120;
sl_options.es = false;
}
gl_compiler->set_common_options(sl_options);
return CompilerBackend(gl_compiler);
}
static CompilerBackend CreateSkSLCompiler(const spirv_cross::ParsedIR& ir,
const SourceOptions& source_options) {
auto sksl_compiler = std::make_shared<CompilerSkSL>(ir);
return CompilerBackend(sksl_compiler);
}
static bool EntryPointMustBeNamedMain(TargetPlatform platform) {
switch (platform) {
case TargetPlatform::kUnknown:
FML_UNREACHABLE();
case TargetPlatform::kMetalDesktop:
case TargetPlatform::kMetalIOS:
case TargetPlatform::kVulkan:
case TargetPlatform::kRuntimeStageMetal:
case TargetPlatform::kRuntimeStageVulkan:
return false;
case TargetPlatform::kSkSL:
case TargetPlatform::kOpenGLES:
case TargetPlatform::kOpenGLDesktop:
case TargetPlatform::kRuntimeStageGLES:
return true;
}
FML_UNREACHABLE();
}
static CompilerBackend CreateCompiler(const spirv_cross::ParsedIR& ir,
const SourceOptions& source_options) {
CompilerBackend compiler;
switch (source_options.target_platform) {
case TargetPlatform::kMetalDesktop:
case TargetPlatform::kMetalIOS:
case TargetPlatform::kRuntimeStageMetal:
compiler = CreateMSLCompiler(ir, source_options);
break;
case TargetPlatform::kVulkan:
case TargetPlatform::kRuntimeStageVulkan:
compiler = CreateVulkanCompiler(ir, source_options);
break;
case TargetPlatform::kUnknown:
case TargetPlatform::kOpenGLES:
case TargetPlatform::kOpenGLDesktop:
case TargetPlatform::kRuntimeStageGLES:
compiler = CreateGLSLCompiler(ir, source_options);
break;
case TargetPlatform::kSkSL:
compiler = CreateSkSLCompiler(ir, source_options);
}
if (!compiler) {
return {};
}
auto* backend = compiler.GetCompiler();
if (!EntryPointMustBeNamedMain(source_options.target_platform) &&
source_options.source_language == SourceLanguage::kGLSL) {
backend->rename_entry_point("main", source_options.entry_point_name,
ToExecutionModel(source_options.type));
}
return compiler;
}
Compiler::Compiler(const std::shared_ptr<const fml::Mapping>& source_mapping,
const SourceOptions& source_options,
Reflector::Options reflector_options)
: options_(source_options) {
if (!source_mapping || source_mapping->GetMapping() == nullptr) {
COMPILER_ERROR(error_stream_)
<< "Could not read shader source or shader source was empty.";
return;
}
if (source_options.target_platform == TargetPlatform::kUnknown) {
COMPILER_ERROR(error_stream_) << "Target platform not specified.";
return;
}
SPIRVCompilerOptions spirv_options;
// Make sure reflection is as effective as possible. The generated shaders
// will be processed later by backend specific compilers.
spirv_options.generate_debug_info = true;
switch (options_.source_language) {
case SourceLanguage::kGLSL:
// Expects GLSL 4.60 (Core Profile).
// https://www.khronos.org/registry/OpenGL/specs/gl/GLSLangSpec.4.60.pdf
spirv_options.source_langauge =
shaderc_source_language::shaderc_source_language_glsl;
spirv_options.source_profile = SPIRVCompilerSourceProfile{
shaderc_profile::shaderc_profile_core, //
460, //
};
break;
case SourceLanguage::kHLSL:
spirv_options.source_langauge =
shaderc_source_language::shaderc_source_language_hlsl;
break;
case SourceLanguage::kUnknown:
COMPILER_ERROR(error_stream_) << "Source language invalid.";
return;
}
switch (source_options.target_platform) {
case TargetPlatform::kMetalDesktop:
case TargetPlatform::kMetalIOS: {
SPIRVCompilerTargetEnv target;
if (source_options.use_half_textures) {
target.env = shaderc_target_env::shaderc_target_env_opengl;
target.version = shaderc_env_version::shaderc_env_version_opengl_4_5;
target.spirv_version = shaderc_spirv_version::shaderc_spirv_version_1_0;
} else {
target.env = shaderc_target_env::shaderc_target_env_vulkan;
target.version = shaderc_env_version::shaderc_env_version_vulkan_1_1;
target.spirv_version = shaderc_spirv_version::shaderc_spirv_version_1_3;
}
spirv_options.target = target;
} break;
case TargetPlatform::kOpenGLES:
case TargetPlatform::kOpenGLDesktop:
case TargetPlatform::kVulkan:
case TargetPlatform::kRuntimeStageVulkan: {
SPIRVCompilerTargetEnv target;
target.env = shaderc_target_env::shaderc_target_env_vulkan;
target.version = shaderc_env_version::shaderc_env_version_vulkan_1_1;
target.spirv_version = shaderc_spirv_version::shaderc_spirv_version_1_3;
if (source_options.target_platform ==
TargetPlatform::kRuntimeStageVulkan) {
spirv_options.macro_definitions.push_back("IMPELLER_GRAPHICS_BACKEND");
spirv_options.relaxed_vulkan_rules = true;
}
spirv_options.target = target;
} break;
case TargetPlatform::kRuntimeStageMetal:
case TargetPlatform::kRuntimeStageGLES: {
SPIRVCompilerTargetEnv target;
target.env = shaderc_target_env::shaderc_target_env_opengl;
target.version = shaderc_env_version::shaderc_env_version_opengl_4_5;
target.spirv_version = shaderc_spirv_version::shaderc_spirv_version_1_0;
spirv_options.target = target;
spirv_options.macro_definitions.push_back("IMPELLER_GRAPHICS_BACKEND");
} break;
case TargetPlatform::kSkSL: {
SPIRVCompilerTargetEnv target;
target.env = shaderc_target_env::shaderc_target_env_opengl;
target.version = shaderc_env_version::shaderc_env_version_opengl_4_5;
target.spirv_version = shaderc_spirv_version::shaderc_spirv_version_1_0;
// When any optimization level above 'zero' is enabled, the phi merges at
// loop continue blocks are rendered using syntax that is supported in
// GLSL, but not in SkSL.
// https://bugs.chromium.org/p/skia/issues/detail?id=13518.
spirv_options.optimization_level =
shaderc_optimization_level::shaderc_optimization_level_zero;
spirv_options.target = target;
spirv_options.macro_definitions.push_back("SKIA_GRAPHICS_BACKEND");
} break;
case TargetPlatform::kUnknown:
COMPILER_ERROR(error_stream_) << "Target platform invalid.";
return;
}
// Implicit definition that indicates that this compilation is for the device
// (instead of the host).
spirv_options.macro_definitions.push_back("IMPELLER_DEVICE");
for (const auto& define : source_options.defines) {
spirv_options.macro_definitions.push_back(define);
}
std::vector<std::string> included_file_names;
spirv_options.includer = std::make_shared<Includer>(
options_.working_directory, options_.include_dirs,
[&included_file_names](auto included_name) {
included_file_names.emplace_back(std::move(included_name));
});
// SPIRV Generation.
SPIRVCompiler spv_compiler(source_options, source_mapping);
spirv_assembly_ = spv_compiler.CompileToSPV(
error_stream_, spirv_options.BuildShadercOptions());
if (!spirv_assembly_) {
return;
} else {
included_file_names_ = std::move(included_file_names);
}
// SL Generation.
spirv_cross::Parser parser(
reinterpret_cast<const uint32_t*>(spirv_assembly_->GetMapping()),
spirv_assembly_->GetSize() / sizeof(uint32_t));
// The parser and compiler must be run separately because the parser contains
// meta information (like type member names) that are useful for reflection.
parser.parse();
const auto parsed_ir =
std::make_shared<spirv_cross::ParsedIR>(parser.get_parsed_ir());
auto sl_compiler = CreateCompiler(*parsed_ir, options_);
if (!sl_compiler) {
COMPILER_ERROR(error_stream_)
<< "Could not create compiler for target platform.";
return;
}
// We need to invoke the compiler even if we don't use the SL mapping later
// for Vulkan. The reflector needs information that is only valid after a
// successful compilation call.
auto sl_compilation_result =
CreateMappingWithString(sl_compiler.GetCompiler()->compile());
// If the target is Vulkan, our shading language is SPIRV which we already
// have. We just need to strip it of debug information. If it isn't, we need
// to invoke the appropriate compiler to compile the SPIRV to the target SL.
if (source_options.target_platform == TargetPlatform::kVulkan ||
source_options.target_platform == TargetPlatform::kRuntimeStageVulkan) {
auto stripped_spirv_options = spirv_options;
stripped_spirv_options.generate_debug_info = false;
sl_mapping_ = spv_compiler.CompileToSPV(
error_stream_, stripped_spirv_options.BuildShadercOptions());
} else {
sl_mapping_ = sl_compilation_result;
}
if (!sl_mapping_) {
COMPILER_ERROR(error_stream_) << "Could not generate SL from SPIRV";
return;
}
reflector_ = std::make_unique<Reflector>(std::move(reflector_options), //
parsed_ir, //
GetSLShaderSource(), //
sl_compiler //
);
if (!reflector_->IsValid()) {
COMPILER_ERROR(error_stream_)
<< "Could not complete reflection on generated shader.";
return;
}
is_valid_ = true;
}
Compiler::~Compiler() = default;
std::shared_ptr<fml::Mapping> Compiler::GetSPIRVAssembly() const {
return spirv_assembly_;
}
std::shared_ptr<fml::Mapping> Compiler::GetSLShaderSource() const {
return sl_mapping_;
}
bool Compiler::IsValid() const {
return is_valid_;
}
std::string Compiler::GetSourcePrefix() const {
std::stringstream stream;
stream << options_.file_name << ": ";
return stream.str();
}
std::string Compiler::GetErrorMessages() const {
return error_stream_.str();
}
const std::vector<std::string>& Compiler::GetIncludedFileNames() const {
return included_file_names_;
}
static std::string JoinStrings(std::vector<std::string> items,
const std::string& separator) {
std::stringstream stream;
for (size_t i = 0, count = items.size(); i < count; i++) {
const auto is_last = (i == count - 1);
stream << items[i];
if (!is_last) {
stream << separator;
}
}
return stream.str();
}
std::string Compiler::GetDependencyNames(const std::string& separator) const {
std::vector<std::string> dependencies = included_file_names_;
dependencies.push_back(options_.file_name);
return JoinStrings(dependencies, separator);
}
std::unique_ptr<fml::Mapping> Compiler::CreateDepfileContents(
std::initializer_list<std::string> targets_names) const {
// https://github.com/ninja-build/ninja/blob/master/src/depfile_parser.cc#L28
const auto targets = JoinStrings(targets_names, " ");
const auto dependencies = GetDependencyNames(" ");
std::stringstream stream;
stream << targets << ": " << dependencies << "\n";
auto contents = std::make_shared<std::string>(stream.str());
return std::make_unique<fml::NonOwnedMapping>(
reinterpret_cast<const uint8_t*>(contents->data()), contents->size(),
[contents](auto, auto) {});
}
const Reflector* Compiler::GetReflector() const {
return reflector_.get();
}
} // namespace compiler
} // namespace impeller
| engine/impeller/compiler/compiler.cc/0 | {
"file_path": "engine/impeller/compiler/compiler.cc",
"repo_id": "engine",
"token_count": 7355
} | 195 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/compiler/runtime_stage_data.h"
#include <array>
#include <cstdint>
#include <memory>
#include <optional>
#include "fml/backtrace.h"
#include "impeller/core/runtime_types.h"
#include "inja/inja.hpp"
#include "impeller/base/validation.h"
#include "impeller/runtime_stage/runtime_stage_flatbuffers.h"
#include "runtime_stage_types_flatbuffers.h"
namespace impeller {
namespace compiler {
RuntimeStageData::RuntimeStageData() = default;
RuntimeStageData::~RuntimeStageData() = default;
void RuntimeStageData::AddShader(const std::shared_ptr<Shader>& data) {
FML_DCHECK(data);
FML_DCHECK(data_.find(data->backend) == data_.end());
data_[data->backend] = data;
}
static std::optional<fb::Stage> ToStage(spv::ExecutionModel stage) {
switch (stage) {
case spv::ExecutionModel::ExecutionModelVertex:
return fb::Stage::kVertex;
case spv::ExecutionModel::ExecutionModelFragment:
return fb::Stage::kFragment;
case spv::ExecutionModel::ExecutionModelGLCompute:
return fb::Stage::kCompute;
default:
return std::nullopt;
}
FML_UNREACHABLE();
}
static std::optional<fb::Stage> ToJsonStage(spv::ExecutionModel stage) {
switch (stage) {
case spv::ExecutionModel::ExecutionModelVertex:
return fb::Stage::kVertex;
case spv::ExecutionModel::ExecutionModelFragment:
return fb::Stage::kFragment;
case spv::ExecutionModel::ExecutionModelGLCompute:
return fb::Stage::kCompute;
default:
return std::nullopt;
}
FML_UNREACHABLE();
}
static std::optional<fb::UniformDataType> ToUniformType(
spirv_cross::SPIRType::BaseType type) {
switch (type) {
case spirv_cross::SPIRType::Float:
return fb::UniformDataType::kFloat;
case spirv_cross::SPIRType::SampledImage:
return fb::UniformDataType::kSampledImage;
case spirv_cross::SPIRType::Struct:
return fb::UniformDataType::kStruct;
case spirv_cross::SPIRType::Boolean:
case spirv_cross::SPIRType::SByte:
case spirv_cross::SPIRType::UByte:
case spirv_cross::SPIRType::Short:
case spirv_cross::SPIRType::UShort:
case spirv_cross::SPIRType::Int:
case spirv_cross::SPIRType::UInt:
case spirv_cross::SPIRType::Int64:
case spirv_cross::SPIRType::UInt64:
case spirv_cross::SPIRType::Half:
case spirv_cross::SPIRType::Double:
case spirv_cross::SPIRType::AccelerationStructure:
case spirv_cross::SPIRType::AtomicCounter:
case spirv_cross::SPIRType::Char:
case spirv_cross::SPIRType::ControlPointArray:
case spirv_cross::SPIRType::Image:
case spirv_cross::SPIRType::Interpolant:
case spirv_cross::SPIRType::RayQuery:
case spirv_cross::SPIRType::Sampler:
case spirv_cross::SPIRType::Unknown:
case spirv_cross::SPIRType::Void:
return std::nullopt;
}
FML_UNREACHABLE();
}
static std::optional<fb::InputDataType> ToInputType(
spirv_cross::SPIRType::BaseType type) {
switch (type) {
case spirv_cross::SPIRType::Boolean:
return fb::InputDataType::kBoolean;
case spirv_cross::SPIRType::SByte:
return fb::InputDataType::kSignedByte;
case spirv_cross::SPIRType::UByte:
return fb::InputDataType::kUnsignedByte;
case spirv_cross::SPIRType::Short:
return fb::InputDataType::kSignedShort;
case spirv_cross::SPIRType::UShort:
return fb::InputDataType::kUnsignedShort;
case spirv_cross::SPIRType::Int:
return fb::InputDataType::kSignedInt;
case spirv_cross::SPIRType::UInt:
return fb::InputDataType::kUnsignedInt;
case spirv_cross::SPIRType::Int64:
return fb::InputDataType::kSignedInt64;
case spirv_cross::SPIRType::UInt64:
return fb::InputDataType::kUnsignedInt64;
case spirv_cross::SPIRType::Float:
return fb::InputDataType::kFloat;
case spirv_cross::SPIRType::Double:
return fb::InputDataType::kDouble;
case spirv_cross::SPIRType::Unknown:
case spirv_cross::SPIRType::Void:
case spirv_cross::SPIRType::Half:
case spirv_cross::SPIRType::AtomicCounter:
case spirv_cross::SPIRType::Struct:
case spirv_cross::SPIRType::Image:
case spirv_cross::SPIRType::SampledImage:
case spirv_cross::SPIRType::Sampler:
case spirv_cross::SPIRType::AccelerationStructure:
case spirv_cross::SPIRType::RayQuery:
case spirv_cross::SPIRType::ControlPointArray:
case spirv_cross::SPIRType::Interpolant:
case spirv_cross::SPIRType::Char:
return std::nullopt;
}
FML_UNREACHABLE();
}
static std::optional<uint32_t> ToJsonType(
spirv_cross::SPIRType::BaseType type) {
switch (type) {
case spirv_cross::SPIRType::Boolean:
return 0; // fb::UniformDataType::kBoolean;
case spirv_cross::SPIRType::SByte:
return 1; // fb::UniformDataType::kSignedByte;
case spirv_cross::SPIRType::UByte:
return 2; // fb::UniformDataType::kUnsignedByte;
case spirv_cross::SPIRType::Short:
return 3; // fb::UniformDataType::kSignedShort;
case spirv_cross::SPIRType::UShort:
return 4; // fb::UniformDataType::kUnsignedShort;
case spirv_cross::SPIRType::Int:
return 5; // fb::UniformDataType::kSignedInt;
case spirv_cross::SPIRType::UInt:
return 6; // fb::UniformDataType::kUnsignedInt;
case spirv_cross::SPIRType::Int64:
return 7; // fb::UniformDataType::kSignedInt64;
case spirv_cross::SPIRType::UInt64:
return 8; // fb::UniformDataType::kUnsignedInt64;
case spirv_cross::SPIRType::Half:
return 9; // b::UniformDataType::kHalfFloat;
case spirv_cross::SPIRType::Float:
return 10; // fb::UniformDataType::kFloat;
case spirv_cross::SPIRType::Double:
return 11; // fb::UniformDataType::kDouble;
case spirv_cross::SPIRType::SampledImage:
return 12; // fb::UniformDataType::kSampledImage;
case spirv_cross::SPIRType::Struct:
return 13;
case spirv_cross::SPIRType::AccelerationStructure:
case spirv_cross::SPIRType::AtomicCounter:
case spirv_cross::SPIRType::Char:
case spirv_cross::SPIRType::ControlPointArray:
case spirv_cross::SPIRType::Image:
case spirv_cross::SPIRType::Interpolant:
case spirv_cross::SPIRType::RayQuery:
case spirv_cross::SPIRType::Sampler:
case spirv_cross::SPIRType::Unknown:
case spirv_cross::SPIRType::Void:
return std::nullopt;
}
FML_UNREACHABLE();
}
static const char* kStageKey = "stage";
static const char* kTargetPlatformKey = "target_platform";
static const char* kEntrypointKey = "entrypoint";
static const char* kUniformsKey = "uniforms";
static const char* kShaderKey = "shader";
static const char* kUniformNameKey = "name";
static const char* kUniformLocationKey = "location";
static const char* kUniformTypeKey = "type";
static const char* kUniformRowsKey = "rows";
static const char* kUniformColumnsKey = "columns";
static const char* kUniformBitWidthKey = "bit_width";
static const char* kUniformArrayElementsKey = "array_elements";
static std::string RuntimeStageBackendToString(RuntimeStageBackend backend) {
switch (backend) {
case RuntimeStageBackend::kSkSL:
return "sksl";
case RuntimeStageBackend::kMetal:
return "metal";
case RuntimeStageBackend::kOpenGLES:
return "opengles";
case RuntimeStageBackend::kVulkan:
return "vulkan";
}
}
std::shared_ptr<fml::Mapping> RuntimeStageData::CreateJsonMapping() const {
// Runtime Stage Data JSON format
// {
// "sksl": {
// "stage": 0,
// "entrypoint": "",
// "shader": "",
// "uniforms": [
// {
// "name": "..",
// "location": 0,
// "type": 0,
// "rows": 0,
// "columns": 0,
// "bit_width": 0,
// "array_elements": 0,
// }
// ]
// },
// "metal": ...
// },
nlohmann::json root;
for (const auto& kvp : data_) {
nlohmann::json platform_object;
const auto stage = ToJsonStage(kvp.second->stage);
if (!stage.has_value()) {
VALIDATION_LOG << "Invalid runtime stage.";
return nullptr;
}
platform_object[kStageKey] = static_cast<uint32_t>(stage.value());
platform_object[kEntrypointKey] = kvp.second->entrypoint;
if (kvp.second->shader->GetSize() > 0u) {
std::string shader(
reinterpret_cast<const char*>(kvp.second->shader->GetMapping()),
kvp.second->shader->GetSize());
platform_object[kShaderKey] = shader.c_str();
}
auto& uniforms = platform_object[kUniformsKey] = nlohmann::json::array_t{};
for (const auto& uniform : kvp.second->uniforms) {
nlohmann::json uniform_object;
uniform_object[kUniformNameKey] = uniform.name.c_str();
uniform_object[kUniformLocationKey] = uniform.location;
uniform_object[kUniformRowsKey] = uniform.rows;
uniform_object[kUniformColumnsKey] = uniform.columns;
auto uniform_type = ToJsonType(uniform.type);
if (!uniform_type.has_value()) {
VALIDATION_LOG << "Invalid uniform type for runtime stage.";
return nullptr;
}
uniform_object[kUniformTypeKey] = uniform_type.value();
uniform_object[kUniformBitWidthKey] = uniform.bit_width;
uniform_object[kUniformArrayElementsKey] =
uniform.array_elements.value_or(0);
uniforms.push_back(uniform_object);
}
root[RuntimeStageBackendToString(kvp.first)] = platform_object;
}
auto json_string = std::make_shared<std::string>(root.dump(2u));
return std::make_shared<fml::NonOwnedMapping>(
reinterpret_cast<const uint8_t*>(json_string->data()),
json_string->size(), [json_string](auto, auto) {});
}
std::unique_ptr<fb::RuntimeStageT> RuntimeStageData::CreateStageFlatbuffer(
impeller::RuntimeStageBackend backend) const {
auto kvp = data_.find(backend);
if (kvp == data_.end()) {
return nullptr;
}
auto runtime_stage = std::make_unique<fb::RuntimeStageT>();
runtime_stage->entrypoint = kvp->second->entrypoint;
const auto stage = ToStage(kvp->second->stage);
if (!stage.has_value()) {
VALIDATION_LOG << "Invalid runtime stage.";
return nullptr;
}
runtime_stage->stage = stage.value();
if (!kvp->second->shader) {
VALIDATION_LOG << "No shader specified for runtime stage.";
return nullptr;
}
if (kvp->second->shader->GetSize() > 0u) {
runtime_stage->shader = {
kvp->second->shader->GetMapping(),
kvp->second->shader->GetMapping() + kvp->second->shader->GetSize()};
}
for (const auto& uniform : kvp->second->uniforms) {
auto desc = std::make_unique<fb::UniformDescriptionT>();
desc->name = uniform.name;
if (desc->name.empty()) {
VALIDATION_LOG << "Uniform name cannot be empty.";
return nullptr;
}
desc->location = uniform.location;
desc->rows = uniform.rows;
desc->columns = uniform.columns;
auto uniform_type = ToUniformType(uniform.type);
if (!uniform_type.has_value()) {
VALIDATION_LOG << "Invalid uniform type for runtime stage.";
return nullptr;
}
desc->type = uniform_type.value();
desc->bit_width = uniform.bit_width;
if (uniform.array_elements.has_value()) {
desc->array_elements = uniform.array_elements.value();
}
for (const auto& byte_type : uniform.struct_layout) {
desc->struct_layout.push_back(static_cast<fb::StructByteType>(byte_type));
}
desc->struct_float_count = uniform.struct_float_count;
runtime_stage->uniforms.emplace_back(std::move(desc));
}
for (const auto& input : kvp->second->inputs) {
auto desc = std::make_unique<fb::StageInputT>();
desc->name = input.name;
if (desc->name.empty()) {
VALIDATION_LOG << "Stage input name cannot be empty.";
return nullptr;
}
desc->location = input.location;
desc->set = input.set;
desc->binding = input.binding;
auto input_type = ToInputType(input.type);
if (!input_type.has_value()) {
VALIDATION_LOG << "Invalid uniform type for runtime stage.";
return nullptr;
}
desc->type = input_type.value();
desc->bit_width = input.bit_width;
desc->vec_size = input.vec_size;
desc->columns = input.columns;
desc->offset = input.offset;
runtime_stage->inputs.emplace_back(std::move(desc));
}
return runtime_stage;
}
std::unique_ptr<fb::RuntimeStagesT>
RuntimeStageData::CreateMultiStageFlatbuffer() const {
// The high level object API is used here for writing to the buffer. This is
// just a convenience.
auto runtime_stages = std::make_unique<fb::RuntimeStagesT>();
for (const auto& kvp : data_) {
auto runtime_stage = CreateStageFlatbuffer(kvp.first);
switch (kvp.first) {
case RuntimeStageBackend::kSkSL:
runtime_stages->sksl = std::move(runtime_stage);
break;
case RuntimeStageBackend::kMetal:
runtime_stages->metal = std::move(runtime_stage);
break;
case RuntimeStageBackend::kOpenGLES:
runtime_stages->opengles = std::move(runtime_stage);
break;
case RuntimeStageBackend::kVulkan:
runtime_stages->vulkan = std::move(runtime_stage);
break;
}
}
return runtime_stages;
}
std::shared_ptr<fml::Mapping> RuntimeStageData::CreateMapping() const {
auto runtime_stages = CreateMultiStageFlatbuffer();
if (!runtime_stages) {
return nullptr;
}
auto builder = std::make_shared<flatbuffers::FlatBufferBuilder>();
builder->Finish(fb::RuntimeStages::Pack(*builder.get(), runtime_stages.get()),
fb::RuntimeStagesIdentifier());
return std::make_shared<fml::NonOwnedMapping>(builder->GetBufferPointer(),
builder->GetSize(),
[builder](auto, auto) {});
}
} // namespace compiler
} // namespace impeller
| engine/impeller/compiler/runtime_stage_data.cc/0 | {
"file_path": "engine/impeller/compiler/runtime_stage_data.cc",
"repo_id": "engine",
"token_count": 5635
} | 196 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef DITHERING_GLSL_
#define DITHERING_GLSL_
#include <impeller/types.glsl>
/// The dithering rate, which is 1.0 / 64.0, or 0.015625.
const float kDitherRate = 1.0 / 64.0;
/// Returns the closest color to the input color using 8x8 ordered dithering.
///
/// Ordered dithering divides the output into a grid of cells, and then assigns
/// a different threshold to each cell. The threshold is used to determine if
/// the color should be rounded up (white) or down (black).
//
/// This technique was chosen mostly because Skia also uses it:
/// https://github.com/google/skia/blob/f9de059517a6f58951510fc7af0cba21e13dd1a8/src/opts/SkRasterPipeline_opts.h#L1717
///
/// See also:
/// - https://en.wikipedia.org/wiki/Ordered_dithering
/// - https://surma.dev/things/ditherpunk/
/// - https://shader-tutorial.dev/advanced/color-banding-dithering/
vec4 IPOrderedDither8x8(vec4 color, vec2 dest) {
// Get the x and y coordinates of the pixel in the 8x8 grid.
uint x = uint(dest.x) % 8;
uint y = uint(dest.y);
y ^= x;
// Get the dither value from the matrix.
uint m = (y & 1) << 5 | //
(x & 1) << 4 | //
(y & 2) << 2 | //
(x & 2) << 1 | //
(y & 4) >> 1 | //
(x & 4) >> 2; //
// Scale that dither to [0,1), then (-0.5,+0.5), here using 63/128 = 0.4921875
// as 0.5-epsilon. We want to make sure our dither is less than 0.5 in either
// direction to keep exact values like 0 and 1 unchanged after rounding.
float dither = float(m) * (2.0 / 128.0) - (63.0 / 128.0);
// Apply the dither to the color.
color.rgb += dither * kDitherRate;
// Clamp the color values to [0,1].
color.rgb = clamp(color.rgb, 0.0, 1.0);
return color;
}
#endif
| engine/impeller/compiler/shader_lib/impeller/dithering.glsl/0 | {
"file_path": "engine/impeller/compiler/shader_lib/impeller/dithering.glsl",
"repo_id": "engine",
"token_count": 725
} | 197 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/compiler/switches.h"
#include <algorithm>
#include <cctype>
#include <filesystem>
#include <map>
#include "flutter/fml/file.h"
#include "fml/command_line.h"
#include "impeller/compiler/types.h"
#include "impeller/compiler/utilities.h"
namespace impeller {
namespace compiler {
static const std::map<std::string, TargetPlatform> kKnownPlatforms = {
{"metal-desktop", TargetPlatform::kMetalDesktop},
{"metal-ios", TargetPlatform::kMetalIOS},
{"vulkan", TargetPlatform::kVulkan},
{"opengl-es", TargetPlatform::kOpenGLES},
{"opengl-desktop", TargetPlatform::kOpenGLDesktop},
};
static const std::map<std::string, TargetPlatform> kKnownRuntimeStages = {
{"sksl", TargetPlatform::kSkSL},
{"runtime-stage-metal", TargetPlatform::kRuntimeStageMetal},
{"runtime-stage-gles", TargetPlatform::kRuntimeStageGLES},
{"runtime-stage-vulkan", TargetPlatform::kRuntimeStageVulkan},
};
static const std::map<std::string, SourceType> kKnownSourceTypes = {
{"vert", SourceType::kVertexShader},
{"frag", SourceType::kFragmentShader},
{"comp", SourceType::kComputeShader},
};
void Switches::PrintHelp(std::ostream& stream) {
// clang-format off
const std::string optional_prefix = "[optional] ";
const std::string optional_multiple_prefix = "[optional,multiple] ";
// clang-format on
stream << std::endl;
stream << "ImpellerC is an offline shader processor and reflection engine."
<< std::endl;
stream << "---------------------------------------------------------------"
<< std::endl;
stream << "Expected invocation is:" << std::endl << std::endl;
stream << "./impellerc <One platform or multiple runtime stages> "
"--input=<source_file> --sl=<sl_output_file> <optional arguments>"
<< std::endl
<< std::endl;
stream << "Valid platforms are:" << std::endl << std::endl;
stream << "One of [";
for (const auto& platform : kKnownPlatforms) {
stream << " --" << platform.first;
}
stream << " ]" << std::endl << std::endl;
stream << "Valid runtime stages are:" << std::endl << std::endl;
stream << "At least one of [";
for (const auto& platform : kKnownRuntimeStages) {
stream << " --" << platform.first;
}
stream << " ]" << std::endl << std::endl;
stream << "Optional arguments:" << std::endl << std::endl;
stream << optional_prefix
<< "--spirv=<spirv_output_file> (ignored for --shader-bundle)"
<< std::endl;
stream << optional_prefix << "--input-type={";
for (const auto& source_type : kKnownSourceTypes) {
stream << source_type.first << ", ";
}
stream << "}" << std::endl;
stream << optional_prefix << "--source-language=glsl|hlsl (default: glsl)"
<< std::endl;
stream << optional_prefix
<< "--entry-point=<entry_point_name> (default: main; "
"ignored for glsl)"
<< std::endl;
stream << optional_prefix
<< "--iplr (causes --sl file to be emitted in "
"iplr format)"
<< std::endl;
stream << optional_prefix
<< "--shader-bundle=<bundle_spec> (causes --sl "
"file to be "
"emitted in Flutter GPU's shader bundle format)"
<< std::endl;
stream << optional_prefix << "--reflection-json=<reflection_json_file>"
<< std::endl;
stream << optional_prefix << "--reflection-header=<reflection_header_file>"
<< std::endl;
stream << optional_prefix << "--reflection-cc=<reflection_cc_file>"
<< std::endl;
stream << optional_multiple_prefix << "--include=<include_directory>"
<< std::endl;
stream << optional_multiple_prefix << "--define=<define>" << std::endl;
stream << optional_prefix << "--depfile=<depfile_path>" << std::endl;
stream << optional_prefix << "--gles-language-version=<number>" << std::endl;
stream << optional_prefix << "--json" << std::endl;
stream << optional_prefix
<< "--use-half-textures (force openGL semantics when "
"targeting metal)"
<< std::endl;
stream << optional_prefix << "--require-framebuffer-fetch" << std::endl;
}
Switches::Switches() = default;
Switches::~Switches() = default;
static TargetPlatform TargetPlatformFromCommandLine(
const fml::CommandLine& command_line) {
auto target = TargetPlatform::kUnknown;
for (const auto& platform : kKnownPlatforms) {
if (command_line.HasOption(platform.first)) {
// If the platform has already been determined, the caller may have
// specified multiple platforms. This is an error and only one must be
// selected.
if (target != TargetPlatform::kUnknown) {
return TargetPlatform::kUnknown;
}
target = platform.second;
// Keep going to detect duplicates.
}
}
return target;
}
static std::vector<TargetPlatform> RuntimeStagesFromCommandLine(
const fml::CommandLine& command_line) {
std::vector<TargetPlatform> stages;
for (const auto& platform : kKnownRuntimeStages) {
if (command_line.HasOption(platform.first)) {
stages.push_back(platform.second);
}
}
return stages;
}
static SourceType SourceTypeFromCommandLine(
const fml::CommandLine& command_line) {
auto source_type_option =
command_line.GetOptionValueWithDefault("input-type", "");
auto source_type_search = kKnownSourceTypes.find(source_type_option);
if (source_type_search == kKnownSourceTypes.end()) {
return SourceType::kUnknown;
}
return source_type_search->second;
}
Switches::Switches(const fml::CommandLine& command_line)
: working_directory(std::make_shared<fml::UniqueFD>(fml::OpenDirectory(
Utf8FromPath(std::filesystem::current_path()).c_str(),
false, // create if necessary,
fml::FilePermission::kRead))),
source_file_name(command_line.GetOptionValueWithDefault("input", "")),
input_type(SourceTypeFromCommandLine(command_line)),
sl_file_name(command_line.GetOptionValueWithDefault("sl", "")),
iplr(command_line.HasOption("iplr")),
shader_bundle(
command_line.GetOptionValueWithDefault("shader-bundle", "")),
spirv_file_name(command_line.GetOptionValueWithDefault("spirv", "")),
reflection_json_name(
command_line.GetOptionValueWithDefault("reflection-json", "")),
reflection_header_name(
command_line.GetOptionValueWithDefault("reflection-header", "")),
reflection_cc_name(
command_line.GetOptionValueWithDefault("reflection-cc", "")),
depfile_path(command_line.GetOptionValueWithDefault("depfile", "")),
json_format(command_line.HasOption("json")),
gles_language_version(
stoi(command_line.GetOptionValueWithDefault("gles-language-version",
"0"))),
metal_version(
command_line.GetOptionValueWithDefault("metal-version", "1.2")),
entry_point(
command_line.GetOptionValueWithDefault("entry-point", "main")),
use_half_textures(command_line.HasOption("use-half-textures")),
require_framebuffer_fetch(
command_line.HasOption("require-framebuffer-fetch")),
target_platform_(TargetPlatformFromCommandLine(command_line)),
runtime_stages_(RuntimeStagesFromCommandLine(command_line)) {
auto language = ToLowerCase(
command_line.GetOptionValueWithDefault("source-language", "glsl"));
source_language = ToSourceLanguage(language);
if (!working_directory || !working_directory->is_valid()) {
return;
}
for (const auto& include_dir_path : command_line.GetOptionValues("include")) {
if (!include_dir_path.data()) {
continue;
}
// fml::OpenDirectoryReadOnly for Windows doesn't handle relative paths
// beginning with `../` well, so we build an absolute path.
// Get the current working directory as a utf8 encoded string.
// Note that the `include_dir_path` is already utf8 encoded, and so we
// mustn't attempt to double-convert it to utf8 lest multi-byte characters
// will become mangled.
std::filesystem::path include_dir_absolute;
if (std::filesystem::path(include_dir_path).is_absolute()) {
include_dir_absolute = std::filesystem::path(include_dir_path);
} else {
auto cwd = Utf8FromPath(std::filesystem::current_path());
include_dir_absolute = std::filesystem::absolute(
std::filesystem::path(cwd) / include_dir_path);
}
auto dir = std::make_shared<fml::UniqueFD>(fml::OpenDirectoryReadOnly(
*working_directory, include_dir_absolute.string().c_str()));
if (!dir || !dir->is_valid()) {
continue;
}
IncludeDir dir_entry;
dir_entry.name = include_dir_path;
dir_entry.dir = std::move(dir);
include_directories.emplace_back(std::move(dir_entry));
}
for (const auto& define : command_line.GetOptionValues("define")) {
defines.emplace_back(define);
}
}
bool Switches::AreValid(std::ostream& explain) const {
// When producing a shader bundle, all flags related to single shader inputs
// and outputs such as `--input` and `--spirv-file-name` are ignored. Instead,
// input files are read from the shader bundle spec and a single flatbuffer
// containing all compiled shaders and reflection state is output to `--sl`.
const bool shader_bundle_mode = !shader_bundle.empty();
bool valid = true;
if (target_platform_ == TargetPlatform::kUnknown && runtime_stages_.empty() &&
!shader_bundle_mode) {
explain << "Either a target platform was not specified, or no runtime "
"stages were specified."
<< std::endl;
valid = false;
}
if (source_language == SourceLanguage::kUnknown && !shader_bundle_mode) {
explain << "Invalid source language type." << std::endl;
valid = false;
}
if (!working_directory || !working_directory->is_valid()) {
explain << "Could not open the working directory: \""
<< Utf8FromPath(std::filesystem::current_path()).c_str() << "\""
<< std::endl;
valid = false;
}
if (source_file_name.empty() && !shader_bundle_mode) {
explain << "Input file name was empty." << std::endl;
valid = false;
}
if (sl_file_name.empty()) {
explain << "Target shading language file name was empty." << std::endl;
valid = false;
}
if (spirv_file_name.empty() && !shader_bundle_mode) {
explain << "Spirv file name was empty." << std::endl;
valid = false;
}
if (iplr && shader_bundle_mode) {
explain << "--iplr and --shader-bundle flag cannot be specified at the "
"same time"
<< std::endl;
valid = false;
}
return valid;
}
std::vector<TargetPlatform> Switches::PlatformsToCompile() const {
if (target_platform_ == TargetPlatform::kUnknown) {
return runtime_stages_;
}
return {target_platform_};
}
TargetPlatform Switches::SelectDefaultTargetPlatform() const {
if (target_platform_ == TargetPlatform::kUnknown &&
!runtime_stages_.empty()) {
return runtime_stages_.front();
}
return target_platform_;
}
SourceOptions Switches::CreateSourceOptions(
std::optional<TargetPlatform> target_platform) const {
SourceOptions options;
options.target_platform =
target_platform.value_or(SelectDefaultTargetPlatform());
options.source_language = source_language;
if (input_type == SourceType::kUnknown) {
options.type = SourceTypeFromFileName(source_file_name);
} else {
options.type = input_type;
}
options.working_directory = working_directory;
options.file_name = source_file_name;
options.include_dirs = include_directories;
options.defines = defines;
options.entry_point_name = EntryPointFunctionNameFromSourceName(
source_file_name, options.type, options.source_language, entry_point);
options.json_format = json_format;
options.gles_language_version = gles_language_version;
options.metal_version = metal_version;
options.use_half_textures = use_half_textures;
options.require_framebuffer_fetch = require_framebuffer_fetch;
return options;
}
} // namespace compiler
} // namespace impeller
| engine/impeller/compiler/switches.cc/0 | {
"file_path": "engine/impeller/compiler/switches.cc",
"repo_id": "engine",
"token_count": 4434
} | 198 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_CORE_CAPTURE_H_
#define FLUTTER_IMPELLER_CORE_CAPTURE_H_
#include <functional>
#include <initializer_list>
#include <memory>
#include <string>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include "flutter/fml/logging.h"
#include "flutter/fml/macros.h"
#include "impeller/geometry/color.h"
#include "impeller/geometry/matrix.h"
#include "impeller/geometry/point.h"
#include "impeller/geometry/rect.h"
#include "impeller/geometry/scalar.h"
#include "impeller/geometry/vector.h"
namespace impeller {
struct CaptureProcTable;
#define _FOR_EACH_CAPTURE_PROPERTY(PROPERTY_V) \
PROPERTY_V(bool, Boolean, boolean) \
PROPERTY_V(int, Integer, integer) \
PROPERTY_V(Scalar, Scalar, scalar) \
PROPERTY_V(Point, Point, point) \
PROPERTY_V(Vector3, Vector3, vector3) \
PROPERTY_V(Rect, Rect, rect) \
PROPERTY_V(Color, Color, color) \
PROPERTY_V(Matrix, Matrix, matrix) \
PROPERTY_V(std::string, String, string)
template <typename Type>
struct CaptureCursorListElement {
std::string label;
explicit CaptureCursorListElement(const std::string& label) : label(label){};
virtual ~CaptureCursorListElement() = default;
//----------------------------------------------------------------------------
/// @brief Determines if previously captured data matches closely enough with
/// newly recorded data to safely emitted in its place. If this
/// returns `false`, then the remaining elements in the capture list
/// are discarded and re-recorded.
///
/// This mechanism ensures that the UI of an interactive inspector can
/// never deviate from reality, even if the schema of the captured
/// data were to significantly deviate.
///
virtual bool MatchesCloselyEnough(const Type& other) const = 0;
};
#define _CAPTURE_TYPE(type_name, pascal_name, lower_name) k##pascal_name,
#define _CAPTURE_PROPERTY_CAST_DECLARATION(type_name, pascal_name, lower_name) \
std::optional<type_name> As##pascal_name() const;
/// A capturable property type
struct CaptureProperty : public CaptureCursorListElement<CaptureProperty> {
enum class Type { _FOR_EACH_CAPTURE_PROPERTY(_CAPTURE_TYPE) };
struct Options {
struct Range {
Scalar min;
Scalar max;
};
/// Readonly properties are always re-recorded during capture. Any edits
/// made to readonly values in-between captures are overwritten during the
/// next capture.
bool readonly = false;
/// An inspector hint that can be used for displaying sliders. Only used for
/// numeric types. Rounded down for integer types.
std::optional<Range> range;
};
Options options;
CaptureProperty(const std::string& label, Options options);
virtual ~CaptureProperty();
virtual Type GetType() const = 0;
virtual void Invoke(const CaptureProcTable& proc_table) = 0;
bool MatchesCloselyEnough(const CaptureProperty& other) const override;
_FOR_EACH_CAPTURE_PROPERTY(_CAPTURE_PROPERTY_CAST_DECLARATION)
};
#define _CAPTURE_PROPERTY_DECLARATION(type_name, pascal_name, lower_name) \
struct Capture##pascal_name##Property final : public CaptureProperty { \
type_name value; \
\
static std::shared_ptr<Capture##pascal_name##Property> \
Make(const std::string& label, type_name value, Options options); \
\
/* |CaptureProperty| */ \
Type GetType() const override; \
\
/* |CaptureProperty| */ \
void Invoke(const CaptureProcTable& proc_table) override; \
\
private: \
Capture##pascal_name##Property(const std::string& label, \
type_name value, \
Options options); \
\
FML_DISALLOW_COPY_AND_ASSIGN(Capture##pascal_name##Property); \
};
_FOR_EACH_CAPTURE_PROPERTY(_CAPTURE_PROPERTY_DECLARATION);
#define _CAPTURE_PROC(type_name, pascal_name, lower_name) \
std::function<void(Capture##pascal_name##Property&)> lower_name = \
[](Capture##pascal_name##Property& value) {};
struct CaptureProcTable {
_FOR_EACH_CAPTURE_PROPERTY(_CAPTURE_PROC)
};
template <typename Type>
class CapturePlaybackList {
public:
CapturePlaybackList() = default;
~CapturePlaybackList() {
// Force the list element type to inherit the CRTP type. We can't enforce
// this as a template requirement directly because `CaptureElement` has a
// recursive `CaptureCursorList<CaptureElement>` property, and so the
// compiler fails the check due to the type being incomplete.
static_assert(std::is_base_of_v<CaptureCursorListElement<Type>, Type>);
}
void Rewind() { cursor_ = 0; }
size_t Count() { return values_.size(); }
std::shared_ptr<Type> GetNext(std::shared_ptr<Type> captured,
bool force_overwrite) {
if (cursor_ < values_.size()) {
std::shared_ptr<Type>& result = values_[cursor_];
if (result->MatchesCloselyEnough(*captured)) {
if (force_overwrite) {
values_[cursor_] = captured;
}
// Safe playback is possible.
++cursor_;
return result;
}
// The data has changed too much from the last capture to safely continue
// playback. Discard this and all subsequent elements to re-record.
values_.resize(cursor_);
}
++cursor_;
values_.push_back(captured);
return captured;
}
std::shared_ptr<Type> FindFirstByLabel(const std::string& label) {
for (std::shared_ptr<Type>& value : values_) {
if (value->label == label) {
return value;
}
}
return nullptr;
}
void Iterate(std::function<void(Type&)> iterator) const {
for (auto& value : values_) {
iterator(*value);
}
}
private:
size_t cursor_ = 0;
std::vector<std::shared_ptr<Type>> values_;
CapturePlaybackList(const CapturePlaybackList&) = delete;
CapturePlaybackList& operator=(const CapturePlaybackList&) = delete;
};
/// A document of capture data, containing a list of properties and a list
/// of subdocuments.
struct CaptureElement final : public CaptureCursorListElement<CaptureElement> {
CapturePlaybackList<CaptureProperty> properties;
CapturePlaybackList<CaptureElement> children;
static std::shared_ptr<CaptureElement> Make(const std::string& label);
void Rewind();
bool MatchesCloselyEnough(const CaptureElement& other) const override;
private:
explicit CaptureElement(const std::string& label);
CaptureElement(const CaptureElement&) = delete;
CaptureElement& operator=(const CaptureElement&) = delete;
};
#ifdef IMPELLER_ENABLE_CAPTURE
#define _CAPTURE_PROPERTY_RECORDER_DECLARATION(type_name, pascal_name, \
lower_name) \
type_name Add##pascal_name(std::string_view label, type_name value, \
CaptureProperty::Options options = {});
#else
#define _CAPTURE_PROPERTY_RECORDER_DECLARATION(type_name, pascal_name, \
lower_name) \
inline type_name Add##pascal_name(std::string_view label, type_name value, \
CaptureProperty::Options options = {}) { \
return value; \
}
#endif
class Capture {
public:
explicit Capture(const std::string& label);
Capture();
static Capture MakeInactive();
inline Capture CreateChild(std::string_view label) {
#ifdef IMPELLER_ENABLE_CAPTURE
if (!active_) {
return Capture();
}
std::string label_copy = std::string(label);
auto new_capture = Capture(label_copy);
new_capture.element_ =
element_->children.GetNext(new_capture.element_, false);
new_capture.element_->Rewind();
return new_capture;
#else
return Capture();
#endif
}
std::shared_ptr<CaptureElement> GetElement() const;
void Rewind();
_FOR_EACH_CAPTURE_PROPERTY(_CAPTURE_PROPERTY_RECORDER_DECLARATION)
private:
#ifdef IMPELLER_ENABLE_CAPTURE
std::shared_ptr<CaptureElement> element_;
bool active_ = false;
#endif
};
class CaptureContext {
public:
CaptureContext();
static CaptureContext MakeInactive();
static CaptureContext MakeAllowlist(
std::initializer_list<std::string> allowlist);
bool IsActive() const;
void Rewind();
Capture GetDocument(const std::string& label);
bool DoesDocumentExist(const std::string& label) const;
private:
struct InactiveFlag {};
explicit CaptureContext(InactiveFlag);
CaptureContext(std::initializer_list<std::string> allowlist);
#ifdef IMPELLER_ENABLE_CAPTURE
bool active_ = false;
std::optional<std::unordered_set<std::string>> allowlist_;
std::unordered_map<std::string, Capture> documents_;
#endif
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_CORE_CAPTURE_H_
| engine/impeller/core/capture.h/0 | {
"file_path": "engine/impeller/core/capture.h",
"repo_id": "engine",
"token_count": 4127
} | 199 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_CORE_RUNTIME_TYPES_H_
#define FLUTTER_IMPELLER_CORE_RUNTIME_TYPES_H_
#include <cstddef>
#include <optional>
#include <string>
#include <vector>
namespace impeller {
enum class RuntimeStageBackend {
kSkSL,
kMetal,
kOpenGLES,
kVulkan,
};
enum RuntimeUniformType {
kFloat,
kSampledImage,
kStruct,
};
enum class RuntimeShaderStage {
kVertex,
kFragment,
kCompute,
};
struct RuntimeUniformDimensions {
size_t rows = 0;
size_t cols = 0;
};
struct RuntimeUniformDescription {
std::string name;
size_t location = 0u;
RuntimeUniformType type = RuntimeUniformType::kFloat;
RuntimeUniformDimensions dimensions = {};
size_t bit_width = 0u;
std::optional<size_t> array_elements;
std::vector<uint8_t> struct_layout = {};
size_t struct_float_count = 0u;
/// @brief Computes the total number of bytes that this uniform requires.
size_t GetSize() const;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_CORE_RUNTIME_TYPES_H_
| engine/impeller/core/runtime_types.h/0 | {
"file_path": "engine/impeller/core/runtime_types.h",
"repo_id": "engine",
"token_count": 427
} | 200 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/display_list/dl_image_impeller.h"
#include "impeller/aiks/aiks_context.h"
#include "impeller/entity/contents/filters/filter_contents.h"
namespace impeller {
sk_sp<DlImageImpeller> DlImageImpeller::Make(std::shared_ptr<Texture> texture,
OwningContext owning_context) {
if (!texture) {
return nullptr;
}
return sk_sp<DlImageImpeller>(
new DlImageImpeller(std::move(texture), owning_context));
}
sk_sp<DlImageImpeller> DlImageImpeller::MakeFromYUVTextures(
AiksContext* aiks_context,
std::shared_ptr<Texture> y_texture,
std::shared_ptr<Texture> uv_texture,
YUVColorSpace yuv_color_space) {
if (!aiks_context || !y_texture || !uv_texture) {
return nullptr;
}
auto yuv_to_rgb_filter_contents = FilterContents::MakeYUVToRGBFilter(
std::move(y_texture), std::move(uv_texture), yuv_color_space);
impeller::Entity entity;
entity.SetBlendMode(impeller::BlendMode::kSource);
auto snapshot = yuv_to_rgb_filter_contents->RenderToSnapshot(
aiks_context->GetContentContext(), // renderer
entity, // entity
std::nullopt, // coverage_limit
std::nullopt, // sampler_descriptor
true, // msaa_enabled
/*mip_count=*/1,
"MakeYUVToRGBFilter Snapshot"); // label
if (!snapshot.has_value()) {
return nullptr;
}
return impeller::DlImageImpeller::Make(snapshot->texture);
}
DlImageImpeller::DlImageImpeller(std::shared_ptr<Texture> texture,
OwningContext owning_context)
: texture_(std::move(texture)), owning_context_(owning_context) {}
// |DlImage|
DlImageImpeller::~DlImageImpeller() = default;
// |DlImage|
sk_sp<SkImage> DlImageImpeller::skia_image() const {
return nullptr;
};
// |DlImage|
std::shared_ptr<impeller::Texture> DlImageImpeller::impeller_texture() const {
return texture_;
}
// |DlImage|
bool DlImageImpeller::isOpaque() const {
// Impeller doesn't currently implement opaque alpha types.
return false;
}
// |DlImage|
bool DlImageImpeller::isTextureBacked() const {
// Impeller textures are always ... textures :/
return true;
}
// |DlImage|
bool DlImageImpeller::isUIThreadSafe() const {
// Impeller textures are always thread-safe
return true;
}
// |DlImage|
SkISize DlImageImpeller::dimensions() const {
const auto size = texture_ ? texture_->GetSize() : ISize{};
return SkISize::Make(size.width, size.height);
}
// |DlImage|
size_t DlImageImpeller::GetApproximateByteSize() const {
auto size = sizeof(*this);
if (texture_) {
size += texture_->GetTextureDescriptor().GetByteSizeOfBaseMipLevel();
}
return size;
}
} // namespace impeller
| engine/impeller/display_list/dl_image_impeller.cc/0 | {
"file_path": "engine/impeller/display_list/dl_image_impeller.cc",
"repo_id": "engine",
"token_count": 1219
} | 201 |
# Enable Metal Validation without Xcode.
Metal validation can be enabled for command-line application using environment
variables.
Apple [documents these environment variables on their developer site](https://developer.apple.com/documentation/xcode/validating-your-apps-metal-api-usage#Enable-API-Validation-with-environment-variables).
More documentation about these environment variables is also available via a man
page entry: `man MetalValidation`
To enable all relevant Metal API and shader validation without using Xcode, add
the following to your `.rc` file.
``` sh
# Metal Validation Defaults
export MTL_DEBUG_LAYER=1
export MTL_DEBUG_LAYER_ERROR_MODE=assert
# Set this to assert for stricter runtime checks. Set to "ignore" if too chatty.
export MTL_DEBUG_LAYER_WARNING_MODE=nslog
export MTL_SHADER_VALIDATION=1
```
These environment variable are good defaults but there are more validation
related knobs and dials to turn. See `man MetalValidation`.
# Enable Metal Profiling HUD without Xcode
Applications can optionally display a HUD that displays real-time information
about Metal related performance.

More documentation about the specific elements of the HUD is present on the
[Apple developer site](https://developer.apple.com/documentation/xcode/monitoring-your-metal-apps-graphics-performance).
The Profiling HUD is separate from Metal Validation and can be enabled for apps
that are launched from the command like (like Impeller Playgrounds) using
environment variables. Add the following to your `.rc` file.
```sh
export MTL_HUD_ENABLED=1
```
| engine/impeller/docs/metal_validation.md/0 | {
"file_path": "engine/impeller/docs/metal_validation.md",
"repo_id": "engine",
"token_count": 433
} | 202 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <optional>
#include "fml/logging.h"
#include "impeller/core/formats.h"
#include "impeller/entity/contents/clip_contents.h"
#include "impeller/entity/contents/content_context.h"
#include "impeller/entity/entity.h"
#include "impeller/renderer/render_pass.h"
#include "impeller/renderer/vertex_buffer_builder.h"
namespace impeller {
/*******************************************************************************
******* ClipContents
******************************************************************************/
ClipContents::ClipContents() = default;
ClipContents::~ClipContents() = default;
void ClipContents::SetGeometry(const std::shared_ptr<Geometry>& geometry) {
geometry_ = geometry;
}
void ClipContents::SetClipOperation(Entity::ClipOperation clip_op) {
clip_op_ = clip_op;
}
std::optional<Rect> ClipContents::GetCoverage(const Entity& entity) const {
return std::nullopt;
};
Contents::ClipCoverage ClipContents::GetClipCoverage(
const Entity& entity,
const std::optional<Rect>& current_clip_coverage) const {
if (!current_clip_coverage.has_value()) {
return {.type = ClipCoverage::Type::kAppend, .coverage = std::nullopt};
}
switch (clip_op_) {
case Entity::ClipOperation::kDifference:
// This can be optimized further by considering cases when the bounds of
// the current stencil will shrink.
return {.type = ClipCoverage::Type::kAppend,
.coverage = current_clip_coverage};
case Entity::ClipOperation::kIntersect:
if (!geometry_) {
return {.type = ClipCoverage::Type::kAppend, .coverage = std::nullopt};
}
auto coverage = geometry_->GetCoverage(entity.GetTransform());
if (!coverage.has_value() || !current_clip_coverage.has_value()) {
return {.type = ClipCoverage::Type::kAppend, .coverage = std::nullopt};
}
return {
.type = ClipCoverage::Type::kAppend,
.coverage = current_clip_coverage->Intersection(coverage.value()),
};
}
FML_UNREACHABLE();
}
bool ClipContents::ShouldRender(const Entity& entity,
const std::optional<Rect> clip_coverage) const {
return true;
}
bool ClipContents::CanInheritOpacity(const Entity& entity) const {
return true;
}
void ClipContents::SetInheritedOpacity(Scalar opacity) {}
bool ClipContents::RenderDepthClip(const ContentContext& renderer,
const Entity& entity,
RenderPass& pass,
Entity::ClipOperation clip_op,
const Geometry& geometry) const {
using VS = ClipPipeline::VertexShader;
VS::FrameInfo info;
info.depth = entity.GetShaderClipDepth();
auto geometry_result = geometry.GetPositionBuffer(renderer, entity, pass);
auto options = OptionsFromPass(pass);
options.blend_mode = BlendMode::kDestination;
pass.SetStencilReference(0);
/// Stencil preparation draw.
options.depth_write_enabled = false;
options.primitive_type = geometry_result.type;
pass.SetVertexBuffer(std::move(geometry_result.vertex_buffer));
switch (geometry_result.mode) {
case GeometryResult::Mode::kNonZero:
pass.SetCommandLabel("Clip stencil preparation (NonZero)");
options.stencil_mode =
ContentContextOptions::StencilMode::kStencilNonZeroFill;
break;
case GeometryResult::Mode::kEvenOdd:
pass.SetCommandLabel("Clip stencil preparation (EvenOdd)");
options.stencil_mode =
ContentContextOptions::StencilMode::kStencilEvenOddFill;
break;
case GeometryResult::Mode::kNormal:
case GeometryResult::Mode::kPreventOverdraw:
pass.SetCommandLabel("Clip stencil preparation (Increment)");
options.stencil_mode =
ContentContextOptions::StencilMode::kLegacyClipIncrement;
break;
}
pass.SetPipeline(renderer.GetClipPipeline(options));
info.mvp = geometry_result.transform;
VS::BindFrameInfo(pass, renderer.GetTransientsBuffer().EmplaceUniform(info));
if (!pass.Draw().ok()) {
return false;
}
/// Write depth.
options.depth_write_enabled = true;
options.primitive_type = PrimitiveType::kTriangleStrip;
Rect cover_area;
switch (clip_op) {
case Entity::ClipOperation::kIntersect:
pass.SetCommandLabel("Intersect Clip");
options.stencil_mode =
ContentContextOptions::StencilMode::kCoverCompareInverted;
cover_area = Rect::MakeSize(pass.GetRenderTargetSize());
break;
case Entity::ClipOperation::kDifference:
pass.SetCommandLabel("Difference Clip");
options.stencil_mode = ContentContextOptions::StencilMode::kCoverCompare;
std::optional<Rect> maybe_cover_area =
geometry.GetCoverage(entity.GetTransform());
if (!maybe_cover_area.has_value()) {
return true;
}
cover_area = maybe_cover_area.value();
break;
}
auto points = cover_area.GetPoints();
auto vertices =
VertexBufferBuilder<VS::PerVertexData>{}
.AddVertices({{points[0]}, {points[1]}, {points[2]}, {points[3]}})
.CreateVertexBuffer(renderer.GetTransientsBuffer());
pass.SetVertexBuffer(std::move(vertices));
pass.SetPipeline(renderer.GetClipPipeline(options));
info.mvp = pass.GetOrthographicTransform();
VS::BindFrameInfo(pass, renderer.GetTransientsBuffer().EmplaceUniform(info));
return pass.Draw().ok();
}
bool ClipContents::RenderStencilClip(const ContentContext& renderer,
const Entity& entity,
RenderPass& pass,
Entity::ClipOperation clip_op,
const Geometry& geometry) const {
using VS = ClipPipeline::VertexShader;
VS::FrameInfo info;
info.depth = entity.GetShaderClipDepth();
auto options = OptionsFromPass(pass);
options.blend_mode = BlendMode::kDestination;
pass.SetStencilReference(entity.GetClipDepth());
if (clip_op == Entity::ClipOperation::kDifference) {
{
pass.SetCommandLabel("Difference Clip (Increment)");
options.stencil_mode =
ContentContextOptions::StencilMode::kLegacyClipIncrement;
auto points = Rect::MakeSize(pass.GetRenderTargetSize()).GetPoints();
auto vertices =
VertexBufferBuilder<VS::PerVertexData>{}
.AddVertices({{points[0]}, {points[1]}, {points[2]}, {points[3]}})
.CreateVertexBuffer(renderer.GetTransientsBuffer());
pass.SetVertexBuffer(std::move(vertices));
info.mvp = pass.GetOrthographicTransform();
VS::BindFrameInfo(pass,
renderer.GetTransientsBuffer().EmplaceUniform(info));
options.primitive_type = PrimitiveType::kTriangleStrip;
pass.SetPipeline(renderer.GetClipPipeline(options));
pass.Draw();
}
{
pass.SetCommandLabel("Difference Clip (Punch)");
pass.SetStencilReference(entity.GetClipDepth() + 1);
options.stencil_mode =
ContentContextOptions::StencilMode::kLegacyClipDecrement;
}
} else {
pass.SetCommandLabel("Intersect Clip");
options.stencil_mode =
ContentContextOptions::StencilMode::kLegacyClipIncrement;
}
auto geometry_result = geometry.GetPositionBuffer(renderer, entity, pass);
options.primitive_type = geometry_result.type;
pass.SetPipeline(renderer.GetClipPipeline(options));
pass.SetVertexBuffer(std::move(geometry_result.vertex_buffer));
info.mvp = geometry_result.transform;
VS::BindFrameInfo(pass, renderer.GetTransientsBuffer().EmplaceUniform(info));
return pass.Draw().ok();
}
bool ClipContents::Render(const ContentContext& renderer,
const Entity& entity,
RenderPass& pass) const {
if (!geometry_) {
return true;
}
if constexpr (ContentContext::kEnableStencilThenCover) {
return RenderDepthClip(renderer, entity, pass, clip_op_, *geometry_);
} else {
return RenderStencilClip(renderer, entity, pass, clip_op_, *geometry_);
}
}
/*******************************************************************************
******* ClipRestoreContents
******************************************************************************/
ClipRestoreContents::ClipRestoreContents() = default;
ClipRestoreContents::~ClipRestoreContents() = default;
void ClipRestoreContents::SetRestoreCoverage(
std::optional<Rect> restore_coverage) {
restore_coverage_ = restore_coverage;
}
std::optional<Rect> ClipRestoreContents::GetCoverage(
const Entity& entity) const {
return std::nullopt;
};
Contents::ClipCoverage ClipRestoreContents::GetClipCoverage(
const Entity& entity,
const std::optional<Rect>& current_clip_coverage) const {
return {.type = ClipCoverage::Type::kRestore, .coverage = std::nullopt};
}
bool ClipRestoreContents::ShouldRender(
const Entity& entity,
const std::optional<Rect> clip_coverage) const {
return true;
}
bool ClipRestoreContents::CanInheritOpacity(const Entity& entity) const {
return true;
}
void ClipRestoreContents::SetInheritedOpacity(Scalar opacity) {}
bool ClipRestoreContents::Render(const ContentContext& renderer,
const Entity& entity,
RenderPass& pass) const {
using VS = ClipPipeline::VertexShader;
pass.SetCommandLabel("Restore Clip");
auto options = OptionsFromPass(pass);
options.blend_mode = BlendMode::kDestination;
options.stencil_mode = ContentContextOptions::StencilMode::kLegacyClipRestore;
options.primitive_type = PrimitiveType::kTriangleStrip;
pass.SetPipeline(renderer.GetClipPipeline(options));
pass.SetStencilReference(entity.GetClipDepth());
// Create a rect that covers either the given restore area, or the whole
// render target texture.
auto ltrb =
restore_coverage_.value_or(Rect::MakeSize(pass.GetRenderTargetSize()))
.GetLTRB();
VertexBufferBuilder<VS::PerVertexData> vtx_builder;
vtx_builder.AddVertices({
{Point(ltrb[0], ltrb[1])},
{Point(ltrb[2], ltrb[1])},
{Point(ltrb[0], ltrb[3])},
{Point(ltrb[2], ltrb[3])},
});
pass.SetVertexBuffer(
vtx_builder.CreateVertexBuffer(renderer.GetTransientsBuffer()));
VS::FrameInfo info;
info.depth = entity.GetShaderClipDepth();
info.mvp = pass.GetOrthographicTransform();
VS::BindFrameInfo(pass, renderer.GetTransientsBuffer().EmplaceUniform(info));
return pass.Draw().ok();
}
}; // namespace impeller
| engine/impeller/entity/contents/clip_contents.cc/0 | {
"file_path": "engine/impeller/entity/contents/clip_contents.cc",
"repo_id": "engine",
"token_count": 4042
} | 203 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_COLOR_FILTER_CONTENTS_H_
#define FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_COLOR_FILTER_CONTENTS_H_
#include "impeller/entity/contents/filters/filter_contents.h"
namespace impeller {
class ColorFilterContents : public FilterContents {
public:
enum class AbsorbOpacity {
kYes,
kNo,
};
/// @brief the [inputs] are expected to be in the order of dst, src.
static std::shared_ptr<ColorFilterContents> MakeBlend(
BlendMode blend_mode,
FilterInput::Vector inputs,
std::optional<Color> foreground_color = std::nullopt);
static std::shared_ptr<ColorFilterContents> MakeColorMatrix(
FilterInput::Ref input,
const ColorMatrix& color_matrix);
static std::shared_ptr<ColorFilterContents> MakeLinearToSrgbFilter(
FilterInput::Ref input);
static std::shared_ptr<ColorFilterContents> MakeSrgbToLinearFilter(
FilterInput::Ref input);
ColorFilterContents();
~ColorFilterContents() override;
void SetAbsorbOpacity(AbsorbOpacity absorb_opacity);
AbsorbOpacity GetAbsorbOpacity() const;
/// @brief Sets an alpha that is applied to the final blended result.
void SetAlpha(Scalar alpha);
std::optional<Scalar> GetAlpha() const;
// |FilterContents|
std::optional<Rect> GetFilterSourceCoverage(
const Matrix& effect_transform,
const Rect& output_limit) const override;
private:
AbsorbOpacity absorb_opacity_ = AbsorbOpacity::kNo;
std::optional<Scalar> alpha_;
ColorFilterContents(const ColorFilterContents&) = delete;
ColorFilterContents& operator=(const ColorFilterContents&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_COLOR_FILTER_CONTENTS_H_
| engine/impeller/entity/contents/filters/color_filter_contents.h/0 | {
"file_path": "engine/impeller/entity/contents/filters/color_filter_contents.h",
"repo_id": "engine",
"token_count": 630
} | 204 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_INPUTS_PLACEHOLDER_FILTER_INPUT_H_
#define FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_INPUTS_PLACEHOLDER_FILTER_INPUT_H_
#include "impeller/entity/contents/filters/inputs/filter_input.h"
namespace impeller {
class PlaceholderFilterInput final : public FilterInput {
public:
explicit PlaceholderFilterInput(Rect coverage);
~PlaceholderFilterInput() override;
// |FilterInput|
Variant GetInput() const override;
// |FilterInput|
std::optional<Snapshot> GetSnapshot(const std::string& label,
const ContentContext& renderer,
const Entity& entity,
std::optional<Rect> coverage_limit,
int32_t mip_count = 1) const override;
// |FilterInput|
std::optional<Rect> GetCoverage(const Entity& entity) const override;
// |FilterInput|
void PopulateGlyphAtlas(
const std::shared_ptr<LazyGlyphAtlas>& lazy_glyph_atlas,
Scalar scale) override;
private:
Rect coverage_rect_;
friend FilterInput;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_INPUTS_PLACEHOLDER_FILTER_INPUT_H_
| engine/impeller/entity/contents/filters/inputs/placeholder_filter_input.h/0 | {
"file_path": "engine/impeller/entity/contents/filters/inputs/placeholder_filter_input.h",
"repo_id": "engine",
"token_count": 582
} | 205 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_FRAMEBUFFER_BLEND_CONTENTS_H_
#define FLUTTER_IMPELLER_ENTITY_CONTENTS_FRAMEBUFFER_BLEND_CONTENTS_H_
#include <memory>
#include "impeller/entity/contents/color_source_contents.h"
#include "impeller/entity/entity.h"
namespace impeller {
enum class BlendSelectValues {
kScreen = 0,
kOverlay,
kDarken,
kLighten,
kColorDodge,
kColorBurn,
kHardLight,
kSoftLight,
kDifference,
kExclusion,
kMultiply,
kHue,
kSaturation,
kColor,
kLuminosity,
};
class FramebufferBlendContents final : public ColorSourceContents {
public:
FramebufferBlendContents();
~FramebufferBlendContents() override;
void SetBlendMode(BlendMode blend_mode);
void SetChildContents(std::shared_ptr<Contents> child_contents);
private:
// |Contents|
std::optional<Rect> GetCoverage(const Entity& entity) const override;
// |Contents|
bool Render(const ContentContext& renderer,
const Entity& entity,
RenderPass& pass) const override;
BlendMode blend_mode_;
std::shared_ptr<Contents> child_contents_;
FramebufferBlendContents(const FramebufferBlendContents&) = delete;
FramebufferBlendContents& operator=(const FramebufferBlendContents&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_FRAMEBUFFER_BLEND_CONTENTS_H_
| engine/impeller/entity/contents/framebuffer_blend_contents.h/0 | {
"file_path": "engine/impeller/entity/contents/framebuffer_blend_contents.h",
"repo_id": "engine",
"token_count": 529
} | 206 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "sweep_gradient_contents.h"
#include "flutter/fml/logging.h"
#include "impeller/entity/contents/clip_contents.h"
#include "impeller/entity/contents/content_context.h"
#include "impeller/entity/contents/gradient_generator.h"
#include "impeller/entity/entity.h"
#include "impeller/geometry/gradient.h"
#include "impeller/renderer/render_pass.h"
namespace impeller {
SweepGradientContents::SweepGradientContents() = default;
SweepGradientContents::~SweepGradientContents() = default;
void SweepGradientContents::SetCenterAndAngles(Point center,
Degrees start_angle,
Degrees end_angle) {
center_ = center;
Scalar t0 = start_angle.degrees / 360;
Scalar t1 = end_angle.degrees / 360;
FML_DCHECK(t0 < t1);
bias_ = -t0;
scale_ = 1 / (t1 - t0);
}
void SweepGradientContents::SetColors(std::vector<Color> colors) {
colors_ = std::move(colors);
}
void SweepGradientContents::SetStops(std::vector<Scalar> stops) {
stops_ = std::move(stops);
}
void SweepGradientContents::SetTileMode(Entity::TileMode tile_mode) {
tile_mode_ = tile_mode;
}
const std::vector<Color>& SweepGradientContents::GetColors() const {
return colors_;
}
const std::vector<Scalar>& SweepGradientContents::GetStops() const {
return stops_;
}
bool SweepGradientContents::IsOpaque() const {
if (GetOpacityFactor() < 1 || tile_mode_ == Entity::TileMode::kDecal) {
return false;
}
for (auto color : colors_) {
if (!color.IsOpaque()) {
return false;
}
}
return true;
}
bool SweepGradientContents::Render(const ContentContext& renderer,
const Entity& entity,
RenderPass& pass) const {
if (renderer.GetDeviceCapabilities().SupportsSSBO()) {
return RenderSSBO(renderer, entity, pass);
}
return RenderTexture(renderer, entity, pass);
}
bool SweepGradientContents::RenderSSBO(const ContentContext& renderer,
const Entity& entity,
RenderPass& pass) const {
using VS = SweepGradientSSBOFillPipeline::VertexShader;
using FS = SweepGradientSSBOFillPipeline::FragmentShader;
VS::FrameInfo frame_info;
frame_info.matrix = GetInverseEffectTransform();
VS::BindFrameInfo(pass,
renderer.GetTransientsBuffer().EmplaceUniform(frame_info));
PipelineBuilderCallback pipeline_callback =
[&renderer](ContentContextOptions options) {
return renderer.GetSweepGradientSSBOFillPipeline(options);
};
return ColorSourceContents::DrawGeometry<VS>(
renderer, entity, pass, pipeline_callback, frame_info,
[this, &renderer](RenderPass& pass) {
FS::FragInfo frag_info;
frag_info.center = center_;
frag_info.bias = bias_;
frag_info.scale = scale_;
frag_info.tile_mode = static_cast<Scalar>(tile_mode_);
frag_info.decal_border_color = decal_border_color_;
frag_info.alpha = GetOpacityFactor();
auto& host_buffer = renderer.GetTransientsBuffer();
auto colors = CreateGradientColors(colors_, stops_);
frag_info.colors_length = colors.size();
auto color_buffer =
host_buffer.Emplace(colors.data(), colors.size() * sizeof(StopData),
DefaultUniformAlignment());
pass.SetCommandLabel("SweepGradientSSBOFill");
FS::BindFragInfo(
pass, renderer.GetTransientsBuffer().EmplaceUniform(frag_info));
FS::BindColorData(pass, color_buffer);
return true;
});
}
bool SweepGradientContents::RenderTexture(const ContentContext& renderer,
const Entity& entity,
RenderPass& pass) const {
using VS = SweepGradientFillPipeline::VertexShader;
using FS = SweepGradientFillPipeline::FragmentShader;
auto gradient_data = CreateGradientBuffer(colors_, stops_);
auto gradient_texture =
CreateGradientTexture(gradient_data, renderer.GetContext());
if (gradient_texture == nullptr) {
return false;
}
VS::FrameInfo frame_info;
frame_info.matrix = GetInverseEffectTransform();
PipelineBuilderCallback pipeline_callback =
[&renderer](ContentContextOptions options) {
return renderer.GetSweepGradientFillPipeline(options);
};
return ColorSourceContents::DrawGeometry<VS>(
renderer, entity, pass, pipeline_callback, frame_info,
[this, &renderer, &gradient_texture](RenderPass& pass) {
FS::FragInfo frag_info;
frag_info.center = center_;
frag_info.bias = bias_;
frag_info.scale = scale_;
frag_info.texture_sampler_y_coord_scale =
gradient_texture->GetYCoordScale();
frag_info.tile_mode = static_cast<Scalar>(tile_mode_);
frag_info.decal_border_color = decal_border_color_;
frag_info.alpha = GetOpacityFactor();
frag_info.half_texel =
Vector2(0.5 / gradient_texture->GetSize().width,
0.5 / gradient_texture->GetSize().height);
SamplerDescriptor sampler_desc;
sampler_desc.min_filter = MinMagFilter::kLinear;
sampler_desc.mag_filter = MinMagFilter::kLinear;
pass.SetCommandLabel("SweepGradientFill");
FS::BindFragInfo(
pass, renderer.GetTransientsBuffer().EmplaceUniform(frag_info));
FS::BindTextureSampler(
pass, gradient_texture,
renderer.GetContext()->GetSamplerLibrary()->GetSampler(
sampler_desc));
return true;
});
}
bool SweepGradientContents::ApplyColorFilter(
const ColorFilterProc& color_filter_proc) {
for (Color& color : colors_) {
color = color_filter_proc(color);
}
decal_border_color_ = color_filter_proc(decal_border_color_);
return true;
}
} // namespace impeller
| engine/impeller/entity/contents/sweep_gradient_contents.cc/0 | {
"file_path": "engine/impeller/entity/contents/sweep_gradient_contents.cc",
"repo_id": "engine",
"token_count": 2530
} | 207 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/entity/entity.h"
#include <algorithm>
#include <limits>
#include <optional>
#include "impeller/base/validation.h"
#include "impeller/entity/contents/content_context.h"
#include "impeller/entity/contents/filters/filter_contents.h"
#include "impeller/entity/contents/texture_contents.h"
#include "impeller/entity/entity_pass.h"
#include "impeller/geometry/color.h"
#include "impeller/geometry/vector.h"
#include "impeller/renderer/render_pass.h"
namespace impeller {
Entity Entity::FromSnapshot(const Snapshot& snapshot,
BlendMode blend_mode,
uint32_t clip_depth) {
auto texture_rect = Rect::MakeSize(snapshot.texture->GetSize());
auto contents = TextureContents::MakeRect(texture_rect);
contents->SetTexture(snapshot.texture);
contents->SetSamplerDescriptor(snapshot.sampler_descriptor);
contents->SetSourceRect(texture_rect);
contents->SetOpacity(snapshot.opacity);
Entity entity;
entity.SetBlendMode(blend_mode);
entity.SetClipDepth(clip_depth);
entity.SetTransform(snapshot.transform);
entity.SetContents(contents);
return entity;
}
Entity::Entity() = default;
Entity::~Entity() = default;
Entity::Entity(Entity&&) = default;
Entity::Entity(const Entity&) = default;
const Matrix& Entity::GetTransform() const {
return transform_;
}
void Entity::SetTransform(const Matrix& transform) {
transform_ = transform;
}
std::optional<Rect> Entity::GetCoverage() const {
if (!contents_) {
return std::nullopt;
}
return contents_->GetCoverage(*this);
}
Contents::ClipCoverage Entity::GetClipCoverage(
const std::optional<Rect>& current_clip_coverage) const {
if (!contents_) {
return {};
}
return contents_->GetClipCoverage(*this, current_clip_coverage);
}
bool Entity::ShouldRender(const std::optional<Rect>& clip_coverage) const {
#ifdef IMPELLER_CONTENT_CULLING
return contents_->ShouldRender(*this, clip_coverage);
#else
return true;
#endif // IMPELLER_CONTENT_CULLING
}
void Entity::SetContents(std::shared_ptr<Contents> contents) {
contents_ = std::move(contents);
}
const std::shared_ptr<Contents>& Entity::GetContents() const {
return contents_;
}
void Entity::SetClipDepth(uint32_t clip_depth) {
clip_depth_ = clip_depth;
}
uint32_t Entity::GetClipDepth() const {
return clip_depth_;
}
void Entity::SetNewClipDepth(uint32_t clip_depth) {
new_clip_depth_ = clip_depth;
}
uint32_t Entity::GetNewClipDepth() const {
return new_clip_depth_;
}
static const Scalar kDepthEpsilon = 1.0f / std::pow(2, 18);
float Entity::GetShaderClipDepth() const {
return std::clamp(new_clip_depth_ * kDepthEpsilon, 0.0f, 1.0f);
}
void Entity::IncrementStencilDepth(uint32_t increment) {
clip_depth_ += increment;
}
void Entity::SetBlendMode(BlendMode blend_mode) {
blend_mode_ = blend_mode;
}
BlendMode Entity::GetBlendMode() const {
return blend_mode_;
}
bool Entity::CanInheritOpacity() const {
if (!contents_) {
return false;
}
if (!((blend_mode_ == BlendMode::kSource && contents_->IsOpaque()) ||
blend_mode_ == BlendMode::kSourceOver)) {
return false;
}
return contents_->CanInheritOpacity(*this);
}
bool Entity::SetInheritedOpacity(Scalar alpha) {
if (!CanInheritOpacity()) {
return false;
}
if (blend_mode_ == BlendMode::kSource && contents_->IsOpaque()) {
blend_mode_ = BlendMode::kSourceOver;
}
contents_->SetInheritedOpacity(alpha);
return true;
}
std::optional<Color> Entity::AsBackgroundColor(ISize target_size) const {
return contents_->AsBackgroundColor(*this, target_size);
}
/// @brief Returns true if the blend mode is "destructive", meaning that even
/// fully transparent source colors would result in the destination
/// getting changed.
///
/// This is useful for determining if EntityPass textures can be
/// shrinkwrapped to their Entities' coverage; they can be shrinkwrapped
/// if all of the contained Entities have non-destructive blends.
bool Entity::IsBlendModeDestructive(BlendMode blend_mode) {
switch (blend_mode) {
case BlendMode::kClear:
case BlendMode::kSource:
case BlendMode::kSourceIn:
case BlendMode::kDestinationIn:
case BlendMode::kSourceOut:
case BlendMode::kDestinationOut:
case BlendMode::kDestinationATop:
case BlendMode::kXor:
case BlendMode::kModulate:
return true;
default:
return false;
}
}
bool Entity::Render(const ContentContext& renderer,
RenderPass& parent_pass) const {
if (!contents_) {
return true;
}
if (!contents_->GetCoverageHint().has_value()) {
contents_->SetCoverageHint(
Rect::MakeSize(parent_pass.GetRenderTargetSize()));
}
return contents_->Render(renderer, *this, parent_pass);
}
Scalar Entity::DeriveTextScale() const {
return GetTransform().GetMaxBasisLengthXY();
}
Capture& Entity::GetCapture() const {
return capture_;
}
Entity Entity::Clone() const {
return Entity(*this);
}
void Entity::SetCapture(Capture capture) const {
capture_ = std::move(capture);
}
} // namespace impeller
| engine/impeller/entity/entity.cc/0 | {
"file_path": "engine/impeller/entity/entity.cc",
"repo_id": "engine",
"token_count": 1888
} | 208 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <algorithm>
#include "flutter/impeller/entity/geometry/ellipse_geometry.h"
#include "flutter/impeller/entity/geometry/line_geometry.h"
namespace impeller {
EllipseGeometry::EllipseGeometry(Rect bounds) : bounds_(bounds) {}
GeometryResult EllipseGeometry::GetPositionBuffer(
const ContentContext& renderer,
const Entity& entity,
RenderPass& pass) const {
return ComputePositionGeometry(
renderer,
renderer.GetTessellator()->FilledEllipse(entity.GetTransform(), bounds_),
entity, pass);
}
// |Geometry|
GeometryResult EllipseGeometry::GetPositionUVBuffer(
Rect texture_coverage,
Matrix effect_transform,
const ContentContext& renderer,
const Entity& entity,
RenderPass& pass) const {
return ComputePositionUVGeometry(
renderer,
renderer.GetTessellator()->FilledEllipse(entity.GetTransform(), bounds_),
texture_coverage.GetNormalizingTransform() * effect_transform, entity,
pass);
}
GeometryVertexType EllipseGeometry::GetVertexType() const {
return GeometryVertexType::kPosition;
}
std::optional<Rect> EllipseGeometry::GetCoverage(
const Matrix& transform) const {
return bounds_.TransformBounds(transform);
}
bool EllipseGeometry::CoversArea(const Matrix& transform,
const Rect& rect) const {
return false;
}
bool EllipseGeometry::IsAxisAlignedRect() const {
return false;
}
} // namespace impeller
| engine/impeller/entity/geometry/ellipse_geometry.cc/0 | {
"file_path": "engine/impeller/entity/geometry/ellipse_geometry.cc",
"repo_id": "engine",
"token_count": 562
} | 209 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_ENTITY_GEOMETRY_STROKE_PATH_GEOMETRY_H_
#define FLUTTER_IMPELLER_ENTITY_GEOMETRY_STROKE_PATH_GEOMETRY_H_
#include "impeller/entity/geometry/geometry.h"
namespace impeller {
/// @brief A geometry that is created from a stroked path object.
class StrokePathGeometry final : public Geometry {
public:
StrokePathGeometry(const Path& path,
Scalar stroke_width,
Scalar miter_limit,
Cap stroke_cap,
Join stroke_join);
~StrokePathGeometry();
Scalar GetStrokeWidth() const;
Scalar GetMiterLimit() const;
Cap GetStrokeCap() const;
Join GetStrokeJoin() const;
private:
// |Geometry|
GeometryResult GetPositionBuffer(const ContentContext& renderer,
const Entity& entity,
RenderPass& pass) const override;
// |Geometry|
GeometryResult GetPositionUVBuffer(Rect texture_coverage,
Matrix effect_transform,
const ContentContext& renderer,
const Entity& entity,
RenderPass& pass) const override;
// |Geometry|
GeometryResult::Mode GetResultMode() const override;
// |Geometry|
GeometryVertexType GetVertexType() const override;
// |Geometry|
std::optional<Rect> GetCoverage(const Matrix& transform) const override;
// Private for benchmarking and debugging
static std::vector<SolidFillVertexShader::PerVertexData>
GenerateSolidStrokeVertices(const Path::Polyline& polyline,
Scalar stroke_width,
Scalar miter_limit,
Join stroke_join,
Cap stroke_cap,
Scalar scale);
static std::vector<TextureFillVertexShader::PerVertexData>
GenerateSolidStrokeVerticesUV(const Path::Polyline& polyline,
Scalar stroke_width,
Scalar miter_limit,
Join stroke_join,
Cap stroke_cap,
Scalar scale,
Point texture_origin,
Size texture_size,
const Matrix& effect_transform);
friend class ImpellerBenchmarkAccessor;
friend class ImpellerEntityUnitTestAccessor;
bool SkipRendering() const;
Path path_;
Scalar stroke_width_;
Scalar miter_limit_;
Cap stroke_cap_;
Join stroke_join_;
StrokePathGeometry(const StrokePathGeometry&) = delete;
StrokePathGeometry& operator=(const StrokePathGeometry&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_ENTITY_GEOMETRY_STROKE_PATH_GEOMETRY_H_
| engine/impeller/entity/geometry/stroke_path_geometry.h/0 | {
"file_path": "engine/impeller/entity/geometry/stroke_path_geometry.h",
"repo_id": "engine",
"token_count": 1447
} | 210 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <impeller/conversions.glsl>
#include <impeller/types.glsl>
uniform FrameInfo {
mat4 mvp;
float depth;
float texture_sampler_y_coord_scale;
}
frame_info;
in vec2 vertices;
in vec2 texture_coords;
in vec4 color;
out vec2 v_texture_coords;
out f16vec4 v_color;
void main() {
gl_Position = frame_info.mvp * vec4(vertices, 0.0, 1.0);
gl_Position /= gl_Position.w;
gl_Position.z = frame_info.depth;
v_color = f16vec4(color);
v_texture_coords =
IPRemapCoords(texture_coords, frame_info.texture_sampler_y_coord_scale);
}
| engine/impeller/entity/shaders/blending/porter_duff_blend.vert/0 | {
"file_path": "engine/impeller/entity/shaders/blending/porter_duff_blend.vert",
"repo_id": "engine",
"token_count": 271
} | 211 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
precision mediump float;
#include <impeller/color.glsl>
#include <impeller/dithering.glsl>
#include <impeller/gradient.glsl>
#include <impeller/texture.glsl>
#include <impeller/types.glsl>
struct ColorPoint {
vec4 color;
float stop;
};
layout(std140) readonly buffer ColorData {
ColorPoint colors[];
}
color_data;
uniform FragInfo {
highp vec2 center;
float radius;
float tile_mode;
vec4 decal_border_color;
float alpha;
int colors_length;
}
frag_info;
highp in vec2 v_position;
out vec4 frag_color;
void main() {
float len = length(v_position - frag_info.center);
float t = len / frag_info.radius;
vec4 result_color = vec4(0);
if ((t < 0.0 || t > 1.0) && frag_info.tile_mode == kTileModeDecal) {
result_color = frag_info.decal_border_color;
} else {
t = IPFloatTile(t, frag_info.tile_mode);
for (int i = 1; i < frag_info.colors_length; i++) {
ColorPoint prev_point = color_data.colors[i - 1];
ColorPoint current_point = color_data.colors[i];
if (t >= prev_point.stop && t <= current_point.stop) {
float delta = (current_point.stop - prev_point.stop);
if (delta < 0.001) {
result_color = current_point.color;
} else {
float ratio = (t - prev_point.stop) / delta;
result_color = mix(prev_point.color, current_point.color, ratio);
}
break;
}
}
}
frag_color = IPPremultiply(result_color) * frag_info.alpha;
frag_color = IPOrderedDither8x8(frag_color, v_position);
}
| engine/impeller/entity/shaders/radial_gradient_ssbo_fill.frag/0 | {
"file_path": "engine/impeller/entity/shaders/radial_gradient_ssbo_fill.frag",
"repo_id": "engine",
"token_count": 670
} | 212 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
precision mediump float;
#include <impeller/types.glsl>
uniform FragInfo {
float16_t alpha;
}
frag_info;
in f16vec4 v_color;
out f16vec4 frag_color;
void main() {
frag_color = v_color * frag_info.alpha;
}
| engine/impeller/entity/shaders/vertices.frag/0 | {
"file_path": "engine/impeller/entity/shaders/vertices.frag",
"repo_id": "engine",
"token_count": 132
} | 213 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
uniform UniformBuffer {
mat4 mvp;
}
uniform_buffer;
in vec3 position;
in vec4 color;
out vec4 v_color;
void main() {
gl_Position = uniform_buffer.mvp * vec4(position, 1.0);
v_color = color;
}
| engine/impeller/fixtures/colors.vert/0 | {
"file_path": "engine/impeller/fixtures/colors.vert",
"repo_id": "engine",
"token_count": 123
} | 214 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
out vec4 frag_color;
layout(input_attachment_index = 0) uniform subpassInputMS subpass_input;
void main() {
// https://github.com/chinmaygarde/merle/blob/3eecb311ac8862c41f0c53a5d9b360be923142bb/src/texture.cc#L195
const mat4 sepia_matrix = mat4(0.3588, 0.2990, 0.2392, 0.0000, //
0.7044, 0.5870, 0.4696, 0.0000, //
0.1368, 0.1140, 0.0912, 0.0000, //
0.0000, 0.0000, 0.0000, 1.0000 //
);
frag_color = sepia_matrix * subpassLoad(subpass_input, 0);
}
| engine/impeller/fixtures/sepia.frag/0 | {
"file_path": "engine/impeller/fixtures/sepia.frag",
"repo_id": "engine",
"token_count": 355
} | 215 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
uniform FrameInfo {
mat4 mvp;
}
frame_info;
in vec2 vtx;
void main() {
gl_Position = frame_info.mvp * vec4(vtx, 0.0, 1.0);
}
| engine/impeller/fixtures/test_texture.vert/0 | {
"file_path": "engine/impeller/fixtures/test_texture.vert",
"repo_id": "engine",
"token_count": 105
} | 216 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <algorithm>
#include "flutter/fml/logging.h"
#include "impeller/geometry/gradient.h"
namespace impeller {
static void AppendColor(const Color& color, GradientData* data) {
auto converted = color.ToR8G8B8A8();
data->color_bytes.push_back(converted[0]);
data->color_bytes.push_back(converted[1]);
data->color_bytes.push_back(converted[2]);
data->color_bytes.push_back(converted[3]);
}
GradientData CreateGradientBuffer(const std::vector<Color>& colors,
const std::vector<Scalar>& stops) {
FML_DCHECK(stops.size() == colors.size());
uint32_t texture_size;
if (stops.size() == 2) {
texture_size = colors.size();
} else {
auto minimum_delta = 1.0;
for (size_t i = 1; i < stops.size(); i++) {
auto value = stops[i] - stops[i - 1];
// Smaller than kEhCloseEnough
if (value < 0.0001) {
continue;
}
if (value < minimum_delta) {
minimum_delta = value;
}
}
// Avoid creating textures that are absurdly large due to stops that are
// very close together.
// TODO(jonahwilliams): this should use a platform specific max texture
// size.
texture_size = std::min(
static_cast<uint32_t>(std::round(1.0 / minimum_delta)) + 1, 1024u);
}
GradientData data = {
.color_bytes = {},
.texture_size = texture_size,
};
data.color_bytes.reserve(texture_size * 4);
if (texture_size == colors.size() && colors.size() <= 1024) {
for (auto i = 0u; i < colors.size(); i++) {
AppendColor(colors[i], &data);
}
} else {
Color previous_color = colors[0];
auto previous_stop = 0.0;
auto previous_color_index = 0;
// The first index is always equal to the first color, exactly.
AppendColor(previous_color, &data);
for (auto i = 1u; i < texture_size - 1; i++) {
auto scaled_i = i / (texture_size - 1.0);
Color next_color = colors[previous_color_index + 1];
auto next_stop = stops[previous_color_index + 1];
// We're almost exactly equal to the next stop.
if (ScalarNearlyEqual(scaled_i, next_stop)) {
AppendColor(next_color, &data);
previous_color = next_color;
previous_stop = next_stop;
previous_color_index += 1;
} else if (scaled_i < next_stop) {
// We're still between the current stop and the next stop.
auto t = (scaled_i - previous_stop) / (next_stop - previous_stop);
auto mixed_color = Color::Lerp(previous_color, next_color, t);
AppendColor(mixed_color, &data);
} else {
// We've slightly overshot the previous stop.
previous_color = next_color;
previous_stop = next_stop;
previous_color_index += 1;
next_color = colors[previous_color_index + 1];
auto next_stop = stops[previous_color_index + 1];
auto t = (scaled_i - previous_stop) / (next_stop - previous_stop);
auto mixed_color = Color::Lerp(previous_color, next_color, t);
AppendColor(mixed_color, &data);
}
}
// The last index is always equal to the last color, exactly.
AppendColor(colors.back(), &data);
}
return data;
}
} // namespace impeller
| engine/impeller/geometry/gradient.cc/0 | {
"file_path": "engine/impeller/geometry/gradient.cc",
"repo_id": "engine",
"token_count": 1355
} | 217 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_GEOMETRY_POINT_H_
#define FLUTTER_IMPELLER_GEOMETRY_POINT_H_
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <ostream>
#include <string>
#include <type_traits>
#include "impeller/geometry/scalar.h"
#include "impeller/geometry/size.h"
#include "impeller/geometry/type_traits.h"
namespace impeller {
#define ONLY_ON_FLOAT_M(Modifiers, Return) \
template <typename U = T> \
Modifiers std::enable_if_t<std::is_floating_point_v<U>, Return>
#define ONLY_ON_FLOAT(Return) DL_ONLY_ON_FLOAT_M(, Return)
template <class T>
struct TPoint {
using Type = T;
Type x = {};
Type y = {};
constexpr TPoint() = default;
template <class U>
explicit constexpr TPoint(const TPoint<U>& other)
: TPoint(static_cast<Type>(other.x), static_cast<Type>(other.y)) {}
template <class U>
explicit constexpr TPoint(const TSize<U>& other)
: TPoint(static_cast<Type>(other.width),
static_cast<Type>(other.height)) {}
constexpr TPoint(Type x, Type y) : x(x), y(y) {}
static constexpr TPoint<Type> MakeXY(Type x, Type y) { return {x, y}; }
template <class U>
static constexpr TPoint Round(const TPoint<U>& other) {
return TPoint{static_cast<Type>(std::round(other.x)),
static_cast<Type>(std::round(other.y))};
}
constexpr bool operator==(const TPoint& p) const {
return p.x == x && p.y == y;
}
constexpr bool operator!=(const TPoint& p) const {
return p.x != x || p.y != y;
}
template <class U>
inline TPoint operator+=(const TPoint<U>& p) {
x += static_cast<Type>(p.x);
y += static_cast<Type>(p.y);
return *this;
}
template <class U>
inline TPoint operator+=(const TSize<U>& s) {
x += static_cast<Type>(s.width);
y += static_cast<Type>(s.height);
return *this;
}
template <class U>
inline TPoint operator-=(const TPoint<U>& p) {
x -= static_cast<Type>(p.x);
y -= static_cast<Type>(p.y);
return *this;
}
template <class U>
inline TPoint operator-=(const TSize<U>& s) {
x -= static_cast<Type>(s.width);
y -= static_cast<Type>(s.height);
return *this;
}
template <class U>
inline TPoint operator*=(const TPoint<U>& p) {
x *= static_cast<Type>(p.x);
y *= static_cast<Type>(p.y);
return *this;
}
template <class U>
inline TPoint operator*=(const TSize<U>& s) {
x *= static_cast<Type>(s.width);
y *= static_cast<Type>(s.height);
return *this;
}
template <class U, class = std::enable_if_t<std::is_arithmetic_v<U>>>
inline TPoint operator*=(U scale) {
x *= static_cast<Type>(scale);
y *= static_cast<Type>(scale);
return *this;
}
template <class U>
inline TPoint operator/=(const TPoint<U>& p) {
x /= static_cast<Type>(p.x);
y /= static_cast<Type>(p.y);
return *this;
}
template <class U>
inline TPoint operator/=(const TSize<U>& s) {
x /= static_cast<Type>(s.width);
y /= static_cast<Type>(s.height);
return *this;
}
template <class U, class = std::enable_if_t<std::is_arithmetic_v<U>>>
inline TPoint operator/=(U scale) {
x /= static_cast<Type>(scale);
y /= static_cast<Type>(scale);
return *this;
}
constexpr TPoint operator-() const { return {-x, -y}; }
constexpr TPoint operator+(const TPoint& p) const {
return {x + p.x, y + p.y};
}
template <class U>
constexpr TPoint operator+(const TSize<U>& s) const {
return {x + static_cast<Type>(s.width), y + static_cast<Type>(s.height)};
}
constexpr TPoint operator-(const TPoint& p) const {
return {x - p.x, y - p.y};
}
template <class U>
constexpr TPoint operator-(const TSize<U>& s) const {
return {x - static_cast<Type>(s.width), y - static_cast<Type>(s.height)};
}
template <class U, class = std::enable_if_t<std::is_arithmetic_v<U>>>
constexpr TPoint operator*(U scale) const {
return {static_cast<Type>(x * scale), static_cast<Type>(y * scale)};
}
constexpr TPoint operator*(const TPoint& p) const {
return {x * p.x, y * p.y};
}
template <class U>
constexpr TPoint operator*(const TSize<U>& s) const {
return {x * static_cast<Type>(s.width), y * static_cast<Type>(s.height)};
}
template <class U, class = std::enable_if_t<std::is_arithmetic_v<U>>>
constexpr TPoint operator/(U d) const {
return {static_cast<Type>(x / d), static_cast<Type>(y / d)};
}
constexpr TPoint operator/(const TPoint& p) const {
return {x / p.x, y / p.y};
}
template <class U>
constexpr TPoint operator/(const TSize<U>& s) const {
return {x / static_cast<Type>(s.width), y / static_cast<Type>(s.height)};
}
constexpr Type GetDistanceSquared(const TPoint& p) const {
double dx = p.x - x;
double dy = p.y - y;
return dx * dx + dy * dy;
}
constexpr TPoint Min(const TPoint& p) const {
return {std::min<Type>(x, p.x), std::min<Type>(y, p.y)};
}
constexpr TPoint Max(const TPoint& p) const {
return {std::max<Type>(x, p.x), std::max<Type>(y, p.y)};
}
constexpr TPoint Floor() const { return {std::floor(x), std::floor(y)}; }
constexpr TPoint Ceil() const { return {std::ceil(x), std::ceil(y)}; }
constexpr TPoint Round() const { return {std::round(x), std::round(y)}; }
constexpr Type GetDistance(const TPoint& p) const {
return sqrt(GetDistanceSquared(p));
}
constexpr Type GetLengthSquared() const { return GetDistanceSquared({}); }
constexpr Type GetLength() const { return GetDistance({}); }
constexpr TPoint Normalize() const {
const auto length = GetLength();
if (length == 0) {
return {1, 0};
}
return {x / length, y / length};
}
constexpr TPoint Abs() const { return {std::fabs(x), std::fabs(y)}; }
constexpr Type Cross(const TPoint& p) const { return (x * p.y) - (y * p.x); }
constexpr Type Dot(const TPoint& p) const { return (x * p.x) + (y * p.y); }
constexpr TPoint Reflect(const TPoint& axis) const {
return *this - axis * this->Dot(axis) * 2;
}
constexpr Radians AngleTo(const TPoint& p) const {
return Radians{std::atan2(this->Cross(p), this->Dot(p))};
}
constexpr TPoint Lerp(const TPoint& p, Scalar t) const {
return *this + (p - *this) * t;
}
constexpr bool IsZero() const { return x == 0 && y == 0; }
ONLY_ON_FLOAT_M(constexpr, bool)
IsFinite() const { return std::isfinite(x) && std::isfinite(y); }
};
// Specializations for mixed (float & integer) algebraic operations.
template <class F, class I, class = MixedOp<F, I>>
constexpr TPoint<F> operator+(const TPoint<F>& p1, const TPoint<I>& p2) {
return {p1.x + static_cast<F>(p2.x), p1.y + static_cast<F>(p2.y)};
}
template <class F, class I, class = MixedOp<F, I>>
constexpr TPoint<F> operator+(const TPoint<I>& p1, const TPoint<F>& p2) {
return p2 + p1;
}
template <class F, class I, class = MixedOp<F, I>>
constexpr TPoint<F> operator-(const TPoint<F>& p1, const TPoint<I>& p2) {
return {p1.x - static_cast<F>(p2.x), p1.y - static_cast<F>(p2.y)};
}
template <class F, class I, class = MixedOp<F, I>>
constexpr TPoint<F> operator-(const TPoint<I>& p1, const TPoint<F>& p2) {
return {static_cast<F>(p1.x) - p2.x, static_cast<F>(p1.y) - p2.y};
}
template <class F, class I, class = MixedOp<F, I>>
constexpr TPoint<F> operator*(const TPoint<F>& p1, const TPoint<I>& p2) {
return {p1.x * static_cast<F>(p2.x), p1.y * static_cast<F>(p2.y)};
}
template <class F, class I, class = MixedOp<F, I>>
constexpr TPoint<F> operator*(const TPoint<I>& p1, const TPoint<F>& p2) {
return p2 * p1;
}
template <class F, class I, class = MixedOp<F, I>>
constexpr TPoint<F> operator/(const TPoint<F>& p1, const TPoint<I>& p2) {
return {p1.x / static_cast<F>(p2.x), p1.y / static_cast<F>(p2.y)};
}
template <class F, class I, class = MixedOp<F, I>>
constexpr TPoint<F> operator/(const TPoint<I>& p1, const TPoint<F>& p2) {
return {static_cast<F>(p1.x) / p2.x, static_cast<F>(p1.y) / p2.y};
}
// RHS algebraic operations with arithmetic types.
template <class T, class U, class = std::enable_if_t<std::is_arithmetic_v<U>>>
constexpr TPoint<T> operator*(U s, const TPoint<T>& p) {
return p * s;
}
template <class T, class U, class = std::enable_if_t<std::is_arithmetic_v<U>>>
constexpr TPoint<T> operator/(U s, const TPoint<T>& p) {
return {static_cast<T>(s) / p.x, static_cast<T>(s) / p.y};
}
// RHS algebraic operations with TSize.
template <class T, class U>
constexpr TPoint<T> operator+(const TSize<U>& s, const TPoint<T>& p) {
return p + s;
}
template <class T, class U>
constexpr TPoint<T> operator-(const TSize<U>& s, const TPoint<T>& p) {
return {static_cast<T>(s.width) - p.x, static_cast<T>(s.height) - p.y};
}
template <class T, class U>
constexpr TPoint<T> operator*(const TSize<U>& s, const TPoint<T>& p) {
return p * s;
}
template <class T, class U>
constexpr TPoint<T> operator/(const TSize<U>& s, const TPoint<T>& p) {
return {static_cast<T>(s.width) / p.x, static_cast<T>(s.height) / p.y};
}
using Point = TPoint<Scalar>;
using IPoint = TPoint<int64_t>;
using IPoint32 = TPoint<int32_t>;
using UintPoint32 = TPoint<uint32_t>;
using Vector2 = Point;
using Quad = std::array<Point, 4>;
#undef ONLY_ON_FLOAT
#undef ONLY_ON_FLOAT_M
} // namespace impeller
namespace std {
template <class T>
inline std::ostream& operator<<(std::ostream& out,
const impeller::TPoint<T>& p) {
out << "(" << p.x << ", " << p.y << ")";
return out;
}
} // namespace std
#endif // FLUTTER_IMPELLER_GEOMETRY_POINT_H_
| engine/impeller/geometry/point.h/0 | {
"file_path": "engine/impeller/geometry/point.h",
"repo_id": "engine",
"token_count": 3939
} | 218 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_GOLDEN_TESTS_METAL_SCREENSHOT_H_
#define FLUTTER_IMPELLER_GOLDEN_TESTS_METAL_SCREENSHOT_H_
#include "flutter/impeller/golden_tests/screenshot.h"
#include <CoreFoundation/CoreFoundation.h>
#include <CoreImage/CoreImage.h>
#include <string>
#include "flutter/fml/macros.h"
namespace impeller {
namespace testing {
/// A screenshot that was produced from `MetalScreenshotter`.
class MetalScreenshot : public Screenshot {
public:
explicit MetalScreenshot(CGImageRef cgImage);
~MetalScreenshot();
const uint8_t* GetBytes() const override;
size_t GetHeight() const override;
size_t GetWidth() const override;
size_t GetBytesPerRow() const override;
bool WriteToPNG(const std::string& path) const override;
private:
MetalScreenshot(const MetalScreenshot&) = delete;
MetalScreenshot& operator=(const MetalScreenshot&) = delete;
CGImageRef cg_image_;
CFDataRef pixel_data_;
};
} // namespace testing
} // namespace impeller
#endif // FLUTTER_IMPELLER_GOLDEN_TESTS_METAL_SCREENSHOT_H_
| engine/impeller/golden_tests/metal_screenshot.h/0 | {
"file_path": "engine/impeller/golden_tests/metal_screenshot.h",
"repo_id": "engine",
"token_count": 401
} | 219 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/playground/backend/vulkan/playground_impl_vk.h"
#include "flutter/fml/paths.h"
#include "impeller/renderer/backend/vulkan/vk.h"
#define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h>
#include "flutter/fml/logging.h"
#include "flutter/fml/mapping.h"
#include "impeller/entity/vk/entity_shaders_vk.h"
#include "impeller/entity/vk/framebuffer_blend_shaders_vk.h"
#include "impeller/entity/vk/modern_shaders_vk.h"
#include "impeller/fixtures/vk/fixtures_shaders_vk.h"
#include "impeller/playground/imgui/vk/imgui_shaders_vk.h"
#include "impeller/renderer/backend/vulkan/context_vk.h"
#include "impeller/renderer/backend/vulkan/formats_vk.h"
#include "impeller/renderer/backend/vulkan/surface_context_vk.h"
#include "impeller/renderer/backend/vulkan/swapchain/khr/khr_surface_vk.h"
#include "impeller/renderer/backend/vulkan/texture_vk.h"
#include "impeller/renderer/vk/compute_shaders_vk.h"
#include "impeller/scene/shaders/vk/scene_shaders_vk.h"
namespace impeller {
static std::vector<std::shared_ptr<fml::Mapping>>
ShaderLibraryMappingsForPlayground() {
return {
std::make_shared<fml::NonOwnedMapping>(impeller_entity_shaders_vk_data,
impeller_entity_shaders_vk_length),
std::make_shared<fml::NonOwnedMapping>(impeller_modern_shaders_vk_data,
impeller_modern_shaders_vk_length),
std::make_shared<fml::NonOwnedMapping>(
impeller_framebuffer_blend_shaders_vk_data,
impeller_framebuffer_blend_shaders_vk_length),
std::make_shared<fml::NonOwnedMapping>(
impeller_fixtures_shaders_vk_data,
impeller_fixtures_shaders_vk_length),
std::make_shared<fml::NonOwnedMapping>(impeller_imgui_shaders_vk_data,
impeller_imgui_shaders_vk_length),
std::make_shared<fml::NonOwnedMapping>(impeller_scene_shaders_vk_data,
impeller_scene_shaders_vk_length),
std::make_shared<fml::NonOwnedMapping>(
impeller_compute_shaders_vk_data, impeller_compute_shaders_vk_length),
};
}
vk::UniqueInstance PlaygroundImplVK::global_instance_;
void PlaygroundImplVK::DestroyWindowHandle(WindowHandle handle) {
if (!handle) {
return;
}
::glfwDestroyWindow(reinterpret_cast<GLFWwindow*>(handle));
}
PlaygroundImplVK::PlaygroundImplVK(PlaygroundSwitches switches)
: PlaygroundImpl(switches), handle_(nullptr, &DestroyWindowHandle) {
FML_CHECK(IsVulkanDriverPresent());
InitGlobalVulkanInstance();
::glfwDefaultWindowHints();
::glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
::glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);
auto window = ::glfwCreateWindow(1, 1, "Test", nullptr, nullptr);
if (!window) {
VALIDATION_LOG << "Unable to create glfw window";
return;
}
int width = 0;
int height = 0;
::glfwGetWindowSize(window, &width, &height);
size_ = ISize{width, height};
handle_.reset(window);
ContextVK::Settings context_settings;
context_settings.proc_address_callback =
reinterpret_cast<PFN_vkGetInstanceProcAddr>(
&::glfwGetInstanceProcAddress);
context_settings.shader_libraries_data = ShaderLibraryMappingsForPlayground();
context_settings.cache_directory = fml::paths::GetCachesDirectory();
context_settings.enable_validation = switches_.enable_vulkan_validation;
auto context_vk = ContextVK::Create(std::move(context_settings));
if (!context_vk || !context_vk->IsValid()) {
VALIDATION_LOG << "Could not create Vulkan context in the playground.";
return;
}
VkSurfaceKHR vk_surface;
auto res = vk::Result{::glfwCreateWindowSurface(
context_vk->GetInstance(), // instance
window, // window
nullptr, // allocator
&vk_surface // surface
)};
if (res != vk::Result::eSuccess) {
VALIDATION_LOG << "Could not create surface for GLFW window: "
<< vk::to_string(res);
return;
}
vk::UniqueSurfaceKHR surface{vk_surface, context_vk->GetInstance()};
auto context = context_vk->CreateSurfaceContext();
if (!context->SetWindowSurface(std::move(surface), size_)) {
VALIDATION_LOG << "Could not set up surface for context.";
return;
}
context_ = std::move(context);
}
PlaygroundImplVK::~PlaygroundImplVK() = default;
// |PlaygroundImpl|
std::shared_ptr<Context> PlaygroundImplVK::GetContext() const {
return context_;
}
// |PlaygroundImpl|
PlaygroundImpl::WindowHandle PlaygroundImplVK::GetWindowHandle() const {
return handle_.get();
}
// |PlaygroundImpl|
std::unique_ptr<Surface> PlaygroundImplVK::AcquireSurfaceFrame(
std::shared_ptr<Context> context) {
SurfaceContextVK* surface_context_vk =
reinterpret_cast<SurfaceContextVK*>(context_.get());
int width = 0;
int height = 0;
::glfwGetFramebufferSize(reinterpret_cast<GLFWwindow*>(handle_.get()), &width,
&height);
size_ = ISize{width, height};
surface_context_vk->UpdateSurfaceSize(ISize{width, height});
return surface_context_vk->AcquireNextSurface();
}
// Create a global instance of Vulkan in order to prevent unloading of the
// Vulkan library.
// A test suite may repeatedly create and destroy PlaygroundImplVK instances,
// and if the PlaygroundImplVK's Vulkan instance is the only one in the
// process then the Vulkan library will be unloaded when the instance is
// destroyed. Repeated loading and unloading of SwiftShader was leaking
// resources, so this will work around that leak.
// (see https://github.com/flutter/flutter/issues/138028)
void PlaygroundImplVK::InitGlobalVulkanInstance() {
if (global_instance_) {
return;
}
VULKAN_HPP_DEFAULT_DISPATCHER.init(::glfwGetInstanceProcAddress);
vk::ApplicationInfo application_info;
application_info.setApplicationVersion(VK_API_VERSION_1_0);
application_info.setApiVersion(VK_API_VERSION_1_1);
application_info.setEngineVersion(VK_API_VERSION_1_0);
application_info.setPEngineName("PlaygroundImplVK");
application_info.setPApplicationName("PlaygroundImplVK");
auto caps = std::shared_ptr<CapabilitiesVK>(
new CapabilitiesVK(/*enable_validations=*/true));
FML_DCHECK(caps->IsValid());
std::optional<std::vector<std::string>> enabled_layers =
caps->GetEnabledLayers();
std::optional<std::vector<std::string>> enabled_extensions =
caps->GetEnabledInstanceExtensions();
FML_DCHECK(enabled_layers.has_value() && enabled_extensions.has_value());
std::vector<const char*> enabled_layers_c;
std::vector<const char*> enabled_extensions_c;
if (enabled_layers.has_value()) {
for (const auto& layer : enabled_layers.value()) {
enabled_layers_c.push_back(layer.c_str());
}
}
if (enabled_extensions.has_value()) {
for (const auto& ext : enabled_extensions.value()) {
enabled_extensions_c.push_back(ext.c_str());
}
}
vk::InstanceCreateFlags instance_flags = {};
instance_flags |= vk::InstanceCreateFlagBits::eEnumeratePortabilityKHR;
vk::InstanceCreateInfo instance_info;
instance_info.setPEnabledLayerNames(enabled_layers_c);
instance_info.setPEnabledExtensionNames(enabled_extensions_c);
instance_info.setPApplicationInfo(&application_info);
instance_info.setFlags(instance_flags);
auto instance_result = vk::createInstanceUnique(instance_info);
FML_CHECK(instance_result.result == vk::Result::eSuccess)
<< "Unable to initialize global Vulkan instance";
global_instance_ = std::move(instance_result.value);
}
fml::Status PlaygroundImplVK::SetCapabilities(
const std::shared_ptr<Capabilities>& capabilities) {
return fml::Status(
fml::StatusCode::kUnimplemented,
"PlaygroundImplVK doesn't support setting the capabilities.");
}
bool PlaygroundImplVK::IsVulkanDriverPresent() {
if (::glfwVulkanSupported()) {
return true;
}
#ifdef TARGET_OS_MAC
FML_LOG(ERROR) << "Attempting to initialize a Vulkan playground on macOS "
"where Vulkan cannot be found. It can be installed via "
"MoltenVK and make sure to install it globally so "
"dlopen can find it.";
#else // TARGET_OS_MAC
FML_LOG(ERROR) << "Attempting to initialize a Vulkan playground on a system "
"that does not support Vulkan.";
#endif // TARGET_OS_MAC
return false;
}
} // namespace impeller
| engine/impeller/playground/backend/vulkan/playground_impl_vk.cc/0 | {
"file_path": "engine/impeller/playground/backend/vulkan/playground_impl_vk.cc",
"repo_id": "engine",
"token_count": 3318
} | 220 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_PLAYGROUND_IMGUI_IMGUI_IMPL_IMPELLER_H_
#define FLUTTER_IMPELLER_PLAYGROUND_IMGUI_IMGUI_IMPL_IMPELLER_H_
#include <memory>
#include "third_party/imgui/imgui.h"
namespace impeller {
class Context;
class RenderPass;
} // namespace impeller
IMGUI_IMPL_API bool ImGui_ImplImpeller_Init(
const std::shared_ptr<impeller::Context>& context);
IMGUI_IMPL_API void ImGui_ImplImpeller_Shutdown();
IMGUI_IMPL_API void ImGui_ImplImpeller_RenderDrawData(
ImDrawData* draw_data,
impeller::RenderPass& renderpass);
#endif // FLUTTER_IMPELLER_PLAYGROUND_IMGUI_IMGUI_IMPL_IMPELLER_H_
| engine/impeller/playground/imgui/imgui_impl_impeller.h/0 | {
"file_path": "engine/impeller/playground/imgui/imgui_impl_impeller.h",
"repo_id": "engine",
"token_count": 300
} | 221 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/renderer/backend/gles/allocator_gles.h"
#include <memory>
#include "impeller/base/allocation.h"
#include "impeller/base/config.h"
#include "impeller/renderer/backend/gles/device_buffer_gles.h"
#include "impeller/renderer/backend/gles/texture_gles.h"
namespace impeller {
AllocatorGLES::AllocatorGLES(ReactorGLES::Ref reactor)
: reactor_(std::move(reactor)), is_valid_(true) {}
// |Allocator|
AllocatorGLES::~AllocatorGLES() = default;
// |Allocator|
bool AllocatorGLES::IsValid() const {
return is_valid_;
}
// |Allocator|
std::shared_ptr<DeviceBuffer> AllocatorGLES::OnCreateBuffer(
const DeviceBufferDescriptor& desc) {
auto backing_store = std::make_shared<Allocation>();
if (!backing_store->Truncate(desc.size)) {
return nullptr;
}
return std::make_shared<DeviceBufferGLES>(desc, //
reactor_, //
std::move(backing_store) //
);
}
// |Allocator|
std::shared_ptr<Texture> AllocatorGLES::OnCreateTexture(
const TextureDescriptor& desc) {
return std::make_shared<TextureGLES>(reactor_, desc);
}
// |Allocator|
ISize AllocatorGLES::GetMaxTextureSizeSupported() const {
return reactor_->GetProcTable().GetCapabilities()->max_texture_size;
}
} // namespace impeller
| engine/impeller/renderer/backend/gles/allocator_gles.cc/0 | {
"file_path": "engine/impeller/renderer/backend/gles/allocator_gles.cc",
"repo_id": "engine",
"token_count": 627
} | 222 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/renderer/backend/gles/device_buffer_gles.h"
#include <cstring>
#include <memory>
#include "flutter/fml/trace_event.h"
#include "impeller/base/allocation.h"
#include "impeller/base/config.h"
#include "impeller/base/validation.h"
namespace impeller {
DeviceBufferGLES::DeviceBufferGLES(DeviceBufferDescriptor desc,
ReactorGLES::Ref reactor,
std::shared_ptr<Allocation> backing_store)
: DeviceBuffer(desc),
reactor_(std::move(reactor)),
handle_(reactor_ ? reactor_->CreateHandle(HandleType::kBuffer)
: HandleGLES::DeadHandle()),
backing_store_(std::move(backing_store)) {}
// |DeviceBuffer|
DeviceBufferGLES::~DeviceBufferGLES() {
if (!handle_.IsDead()) {
reactor_->CollectHandle(handle_);
}
}
// |DeviceBuffer|
uint8_t* DeviceBufferGLES::OnGetContents() const {
if (!reactor_) {
return nullptr;
}
return backing_store_->GetBuffer();
}
// |DeviceBuffer|
bool DeviceBufferGLES::OnCopyHostBuffer(const uint8_t* source,
Range source_range,
size_t offset) {
if (!reactor_) {
return false;
}
if (offset + source_range.length > backing_store_->GetLength()) {
return false;
}
std::memmove(backing_store_->GetBuffer() + offset,
source + source_range.offset, source_range.length);
++generation_;
return true;
}
void DeviceBufferGLES::Flush(std::optional<Range> range) const {
generation_++;
}
static GLenum ToTarget(DeviceBufferGLES::BindingType type) {
switch (type) {
case DeviceBufferGLES::BindingType::kArrayBuffer:
return GL_ARRAY_BUFFER;
case DeviceBufferGLES::BindingType::kElementArrayBuffer:
return GL_ELEMENT_ARRAY_BUFFER;
}
FML_UNREACHABLE();
}
bool DeviceBufferGLES::BindAndUploadDataIfNecessary(BindingType type) const {
if (!reactor_) {
return false;
}
auto buffer = reactor_->GetGLHandle(handle_);
if (!buffer.has_value()) {
return false;
}
const auto target_type = ToTarget(type);
const auto& gl = reactor_->GetProcTable();
gl.BindBuffer(target_type, buffer.value());
if (upload_generation_ != generation_) {
TRACE_EVENT1("impeller", "BufferData", "Bytes",
std::to_string(backing_store_->GetLength()).c_str());
gl.BufferData(target_type, backing_store_->GetLength(),
backing_store_->GetBuffer(), GL_STATIC_DRAW);
upload_generation_ = generation_;
}
return true;
}
// |DeviceBuffer|
bool DeviceBufferGLES::SetLabel(const std::string& label) {
reactor_->SetDebugLabel(handle_, label);
return true;
}
// |DeviceBuffer|
bool DeviceBufferGLES::SetLabel(const std::string& label, Range range) {
// Cannot support debug label on the range. Set the label for the entire
// range.
return SetLabel(label);
}
const uint8_t* DeviceBufferGLES::GetBufferData() const {
return backing_store_->GetBuffer();
}
void DeviceBufferGLES::UpdateBufferData(
const std::function<void(uint8_t* data, size_t length)>&
update_buffer_data) {
if (update_buffer_data) {
update_buffer_data(backing_store_->GetBuffer(),
backing_store_->GetLength());
++generation_;
}
}
} // namespace impeller
| engine/impeller/renderer/backend/gles/device_buffer_gles.cc/0 | {
"file_path": "engine/impeller/renderer/backend/gles/device_buffer_gles.cc",
"repo_id": "engine",
"token_count": 1377
} | 223 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_REACTOR_GLES_H_
#define FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_REACTOR_GLES_H_
#include <functional>
#include <memory>
#include <vector>
#include "flutter/fml/macros.h"
#include "impeller/base/thread.h"
#include "impeller/renderer/backend/gles/handle_gles.h"
#include "impeller/renderer/backend/gles/proc_table_gles.h"
namespace impeller {
//------------------------------------------------------------------------------
/// @brief The reactor attempts to make thread-safe usage of OpenGL ES
/// easier to reason about.
///
/// In the other Impeller backends (like Metal and Vulkan),
/// resources can be created, used, and deleted on any thread with
/// relatively few restrictions. However, OpenGL resources can only
/// be created, used, and deleted on a thread on which an OpenGL
/// context (or one in the same sharegroup) is current.
///
/// There aren't too many OpenGL contexts to go around and making
/// the caller reason about the timing and threading requirement
/// only when the OpenGL backend is in use is tedious. To work
/// around this tedium, there is an abstraction between the
/// resources and their handles in OpenGL. The reactor is this
/// abstraction.
///
/// The reactor is thread-safe and can created, used, and collected
/// on any thread.
///
/// Reactor handles `HandleGLES` can be created, used, and collected
/// on any thread. These handles can be to textures, buffers, etc..
///
/// Operations added to the reactor are guaranteed to run on a
/// worker within a finite amount of time unless the reactor itself
/// is torn down or there are no workers. These operations may run
/// on the calling thread immediately if a worker is active on the
/// current thread and can perform reactions. The operations are
/// guaranteed to run with an OpenGL context current and all reactor
/// handles having live OpenGL handle counterparts.
///
/// Creating a handle in the reactor doesn't mean an OpenGL handle
/// is created immediately. OpenGL handles become live before the
/// next reaction. Similarly, dropping the last reference to a
/// reactor handle means that the OpenGL handle will be deleted at
/// some point in the near future.
///
class ReactorGLES {
public:
using WorkerID = UniqueID;
//----------------------------------------------------------------------------
/// @brief A delegate implemented by a thread on which an OpenGL context
/// is current. There may be multiple workers for the reactor to
/// perform reactions on. In that case, it is the workers
/// responsibility to ensure that all of them use either the same
/// OpenGL context or multiple OpenGL contexts in the same
/// sharegroup.
///
class Worker {
public:
virtual ~Worker() = default;
//--------------------------------------------------------------------------
/// @brief Determines the ability of the worker to service a reaction
/// on the current thread. The OpenGL context must be current on
/// the thread if the worker says it is able to service a
/// reaction.
///
/// @param[in] reactor The reactor
///
/// @return If the worker is able to service a reaction. The reactor
/// assumes the context is already current if true.
///
virtual bool CanReactorReactOnCurrentThreadNow(
const ReactorGLES& reactor) const = 0;
};
using Ref = std::shared_ptr<ReactorGLES>;
//----------------------------------------------------------------------------
/// @brief Create a new reactor. There are expensive and only one per
/// application instance is necessary.
///
/// @param[in] gl The proc table for GL access. This is necessary for the
/// reactor to be able to create and collect OpenGL handles.
///
explicit ReactorGLES(std::unique_ptr<ProcTableGLES> gl);
//----------------------------------------------------------------------------
/// @brief Destroy a reactor.
///
~ReactorGLES();
//----------------------------------------------------------------------------
/// @brief If this is a valid reactor. Invalid reactors must be discarded
/// immediately.
///
/// @return If this reactor is valid.
///
bool IsValid() const;
//----------------------------------------------------------------------------
/// @brief Adds a worker to the reactor. Each new worker must ensure that
/// the context it manages is the same as the other workers in the
/// reactor or in the same sharegroup.
///
/// @param[in] worker The worker
///
/// @return The worker identifier. This identifier can be used to remove
/// the worker from the reactor later.
///
WorkerID AddWorker(std::weak_ptr<Worker> worker);
//----------------------------------------------------------------------------
/// @brief Remove a previously added worker from the reactor. If the
/// reactor has no workers, pending added operations will never
/// run.
///
/// @param[in] id The worker identifier previously returned by `AddWorker`.
///
/// @return If a worker with the given identifer was successfully removed
/// from the reactor.
///
bool RemoveWorker(WorkerID id);
//----------------------------------------------------------------------------
/// @brief Get the OpenGL proc. table the reactor uses to manage handles.
///
/// @return The proc table.
///
const ProcTableGLES& GetProcTable() const;
//----------------------------------------------------------------------------
/// @brief Returns the OpenGL handle for a reactor handle if one is
/// available. This is typically only safe to call within a
/// reaction. That is, within a `ReactorGLES::Operation`.
///
/// Asking for the OpenGL handle before the reactor has a chance
/// to reactor will return `std::nullopt`.
///
/// This can be called on any thread but is typically useless
/// outside of a reaction since the handle is useless outside of a
/// reactor operation.
///
/// @param[in] handle The reactor handle.
///
/// @return The OpenGL handle if the reactor has had a chance to react.
/// `std::nullopt` otherwise.
///
std::optional<GLuint> GetGLHandle(const HandleGLES& handle) const;
//----------------------------------------------------------------------------
/// @brief Create a reactor handle.
///
/// This can be called on any thread. Even one that doesn't have
/// an OpenGL context.
///
/// @param[in] type The type of handle to create.
///
/// @return The reactor handle.
///
HandleGLES CreateHandle(HandleType type);
//----------------------------------------------------------------------------
/// @brief Collect a reactor handle.
///
/// This can be called on any thread. Even one that doesn't have
/// an OpenGL context.
///
/// @param[in] handle The reactor handle handle
///
void CollectHandle(HandleGLES handle);
//----------------------------------------------------------------------------
/// @brief Set the debug label on a reactor handle.
///
/// This call ensures that the OpenGL debug label is propagated to
/// even the OpenGL handle hasn't been created at the time the
/// caller sets the label.
///
/// @param[in] handle The handle
/// @param[in] label The label
///
void SetDebugLabel(const HandleGLES& handle, std::string label);
using Operation = std::function<void(const ReactorGLES& reactor)>;
//----------------------------------------------------------------------------
/// @brief Adds an operation that the reactor runs on a worker that
/// ensures that an OpenGL context is current.
///
/// This operation is not guaranteed to run immediately. It will
/// complete in a finite amount of time on any thread as long as
/// there is a reactor worker and the reactor itself is not being
/// torn down.
///
/// @param[in] operation The operation
///
/// @return If the operation was successfully queued for completion.
///
[[nodiscard]] bool AddOperation(Operation operation);
//----------------------------------------------------------------------------
/// @brief Perform a reaction on the current thread if able.
///
/// It is safe to call this simultaneously from multiple threads
/// at the same time.
///
/// @return If a reaction was performed on the calling thread.
///
[[nodiscard]] bool React();
private:
struct LiveHandle {
std::optional<GLuint> name;
std::optional<std::string> pending_debug_label;
bool pending_collection = false;
LiveHandle() = default;
explicit LiveHandle(std::optional<GLuint> p_name) : name(p_name) {}
constexpr bool IsLive() const { return name.has_value(); }
};
std::unique_ptr<ProcTableGLES> proc_table_;
Mutex ops_execution_mutex_;
mutable Mutex ops_mutex_;
std::vector<Operation> ops_ IPLR_GUARDED_BY(ops_mutex_);
// Make sure the container is one where erasing items during iteration doesn't
// invalidate other iterators.
using LiveHandles = std::unordered_map<HandleGLES,
LiveHandle,
HandleGLES::Hash,
HandleGLES::Equal>;
mutable RWMutex handles_mutex_;
LiveHandles handles_ IPLR_GUARDED_BY(handles_mutex_);
mutable Mutex workers_mutex_;
mutable std::map<WorkerID, std::weak_ptr<Worker>> workers_ IPLR_GUARDED_BY(
workers_mutex_);
bool can_set_debug_labels_ = false;
bool is_valid_ = false;
bool ReactOnce() IPLR_REQUIRES(ops_execution_mutex_);
bool HasPendingOperations() const;
bool CanReactOnCurrentThread() const;
bool ConsolidateHandles();
bool FlushOps();
void SetupDebugGroups();
ReactorGLES(const ReactorGLES&) = delete;
ReactorGLES& operator=(const ReactorGLES&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_REACTOR_GLES_H_
| engine/impeller/renderer/backend/gles/reactor_gles.h/0 | {
"file_path": "engine/impeller/renderer/backend/gles/reactor_gles.h",
"repo_id": "engine",
"token_count": 3657
} | 224 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/testing/testing.h" // IWYU pragma: keep
#include "gtest/gtest.h"
#include "impeller/renderer/backend/gles/gpu_tracer_gles.h"
#include "impeller/renderer/backend/gles/test/mock_gles.h"
namespace impeller {
namespace testing {
#ifdef IMPELLER_DEBUG
TEST(GPUTracerGLES, CanFormatFramebufferErrorMessage) {
auto const extensions = std::vector<const unsigned char*>{
reinterpret_cast<const unsigned char*>("GL_KHR_debug"), //
reinterpret_cast<const unsigned char*>("GL_EXT_disjoint_timer_query"), //
};
auto mock_gles = MockGLES::Init(extensions);
auto tracer =
std::make_shared<GPUTracerGLES>(mock_gles->GetProcTable(), true);
tracer->RecordRasterThread();
tracer->MarkFrameStart(mock_gles->GetProcTable());
tracer->MarkFrameEnd(mock_gles->GetProcTable());
auto calls = mock_gles->GetCapturedCalls();
std::vector<std::string> expected = {"glGenQueriesEXT", "glBeginQueryEXT",
"glEndQueryEXT"};
for (auto i = 0; i < 3; i++) {
EXPECT_EQ(calls[i], expected[i]);
}
// Begin second frame, which prompts the tracer to query the result
// from the previous frame.
tracer->MarkFrameStart(mock_gles->GetProcTable());
calls = mock_gles->GetCapturedCalls();
std::vector<std::string> expected_b = {"glGetQueryObjectuivEXT",
"glGetQueryObjectui64vEXT",
"glDeleteQueriesEXT"};
for (auto i = 0; i < 3; i++) {
EXPECT_EQ(calls[i], expected_b[i]);
}
}
#endif // IMPELLER_DEBUG
} // namespace testing
} // namespace impeller
| engine/impeller/renderer/backend/gles/test/gpu_tracer_gles_unittests.cc/0 | {
"file_path": "engine/impeller/renderer/backend/gles/test/gpu_tracer_gles_unittests.cc",
"repo_id": "engine",
"token_count": 740
} | 225 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/renderer/backend/metal/command_buffer_mtl.h"
#include "flutter/fml/make_copyable.h"
#include "flutter/fml/synchronization/semaphore.h"
#include "impeller/renderer/backend/metal/blit_pass_mtl.h"
#include "impeller/renderer/backend/metal/compute_pass_mtl.h"
#include "impeller/renderer/backend/metal/context_mtl.h"
#include "impeller/renderer/backend/metal/render_pass_mtl.h"
namespace impeller {
API_AVAILABLE(ios(14.0), macos(11.0))
static NSString* MTLCommandEncoderErrorStateToString(
MTLCommandEncoderErrorState state) {
switch (state) {
case MTLCommandEncoderErrorStateUnknown:
return @"unknown";
case MTLCommandEncoderErrorStateCompleted:
return @"completed";
case MTLCommandEncoderErrorStateAffected:
return @"affected";
case MTLCommandEncoderErrorStatePending:
return @"pending";
case MTLCommandEncoderErrorStateFaulted:
return @"faulted";
}
return @"unknown";
}
static NSString* MTLCommandBufferErrorToString(MTLCommandBufferError code) {
switch (code) {
case MTLCommandBufferErrorNone:
return @"none";
case MTLCommandBufferErrorInternal:
return @"internal";
case MTLCommandBufferErrorTimeout:
return @"timeout";
case MTLCommandBufferErrorPageFault:
return @"page fault";
case MTLCommandBufferErrorNotPermitted:
return @"not permitted";
case MTLCommandBufferErrorOutOfMemory:
return @"out of memory";
case MTLCommandBufferErrorInvalidResource:
return @"invalid resource";
case MTLCommandBufferErrorMemoryless:
return @"memory-less";
default:
break;
}
return [NSString stringWithFormat:@"<unknown> %zu", code];
}
static bool LogMTLCommandBufferErrorIfPresent(id<MTLCommandBuffer> buffer) {
if (!buffer) {
return true;
}
if (buffer.status == MTLCommandBufferStatusCompleted) {
return true;
}
std::stringstream stream;
stream << ">>>>>>>" << std::endl;
stream << "Impeller command buffer could not be committed!" << std::endl;
if (auto desc = buffer.error.localizedDescription) {
stream << desc.UTF8String << std::endl;
}
if (buffer.error) {
stream << "Domain: "
<< (buffer.error.domain.length > 0u ? buffer.error.domain.UTF8String
: "<unknown>")
<< " Code: "
<< MTLCommandBufferErrorToString(
static_cast<MTLCommandBufferError>(buffer.error.code))
.UTF8String
<< std::endl;
}
if (@available(iOS 14.0, macOS 11.0, *)) {
NSArray<id<MTLCommandBufferEncoderInfo>>* infos =
buffer.error.userInfo[MTLCommandBufferEncoderInfoErrorKey];
for (id<MTLCommandBufferEncoderInfo> info in infos) {
stream << (info.label.length > 0u ? info.label.UTF8String
: "<Unlabelled Render Pass>")
<< ": "
<< MTLCommandEncoderErrorStateToString(info.errorState).UTF8String
<< std::endl;
auto signposts = [info.debugSignposts componentsJoinedByString:@", "];
if (signposts.length > 0u) {
stream << signposts.UTF8String << std::endl;
}
}
for (id<MTLFunctionLog> log in buffer.logs) {
auto desc = log.description;
if (desc.length > 0u) {
stream << desc.UTF8String << std::endl;
}
}
}
stream << "<<<<<<<";
VALIDATION_LOG << stream.str();
return false;
}
static id<MTLCommandBuffer> CreateCommandBuffer(id<MTLCommandQueue> queue) {
#ifndef FLUTTER_RELEASE
if (@available(iOS 14.0, macOS 11.0, *)) {
auto desc = [[MTLCommandBufferDescriptor alloc] init];
// Degrades CPU performance slightly but is well worth the cost for typical
// Impeller workloads.
desc.errorOptions = MTLCommandBufferErrorOptionEncoderExecutionStatus;
return [queue commandBufferWithDescriptor:desc];
}
#endif // FLUTTER_RELEASE
return [queue commandBuffer];
}
CommandBufferMTL::CommandBufferMTL(const std::weak_ptr<const Context>& context,
id<MTLCommandQueue> queue)
: CommandBuffer(context), buffer_(CreateCommandBuffer(queue)) {}
CommandBufferMTL::~CommandBufferMTL() = default;
bool CommandBufferMTL::IsValid() const {
return buffer_ != nil;
}
void CommandBufferMTL::SetLabel(const std::string& label) const {
if (label.empty()) {
return;
}
[buffer_ setLabel:@(label.data())];
}
static CommandBuffer::Status ToCommitResult(MTLCommandBufferStatus status) {
switch (status) {
case MTLCommandBufferStatusCompleted:
return CommandBufferMTL::Status::kCompleted;
case MTLCommandBufferStatusEnqueued:
return CommandBufferMTL::Status::kPending;
default:
break;
}
return CommandBufferMTL::Status::kError;
}
bool CommandBufferMTL::OnSubmitCommands(CompletionCallback callback) {
auto context = context_.lock();
if (!context) {
return false;
}
#ifdef IMPELLER_DEBUG
ContextMTL::Cast(*context).GetGPUTracer()->RecordCmdBuffer(buffer_);
#endif // IMPELLER_DEBUG
if (callback) {
[buffer_
addCompletedHandler:^(id<MTLCommandBuffer> buffer) {
[[maybe_unused]] auto result =
LogMTLCommandBufferErrorIfPresent(buffer);
FML_DCHECK(result)
<< "Must not have errors during command buffer submission.";
callback(ToCommitResult(buffer.status));
}];
}
[buffer_ commit];
buffer_ = nil;
return true;
}
void CommandBufferMTL::OnWaitUntilScheduled() {}
std::shared_ptr<RenderPass> CommandBufferMTL::OnCreateRenderPass(
RenderTarget target) {
if (!buffer_) {
return nullptr;
}
auto context = context_.lock();
if (!context) {
return nullptr;
}
auto pass = std::shared_ptr<RenderPassMTL>(
new RenderPassMTL(context, target, buffer_));
if (!pass->IsValid()) {
return nullptr;
}
return pass;
}
std::shared_ptr<BlitPass> CommandBufferMTL::OnCreateBlitPass() {
if (!buffer_) {
return nullptr;
}
auto pass = std::shared_ptr<BlitPassMTL>(new BlitPassMTL(buffer_));
if (!pass->IsValid()) {
return nullptr;
}
return pass;
}
std::shared_ptr<ComputePass> CommandBufferMTL::OnCreateComputePass() {
if (!buffer_) {
return nullptr;
}
auto context = context_.lock();
if (!context) {
return nullptr;
}
auto pass =
std::shared_ptr<ComputePassMTL>(new ComputePassMTL(context, buffer_));
if (!pass->IsValid()) {
return nullptr;
}
return pass;
}
} // namespace impeller
| engine/impeller/renderer/backend/metal/command_buffer_mtl.mm/0 | {
"file_path": "engine/impeller/renderer/backend/metal/command_buffer_mtl.mm",
"repo_id": "engine",
"token_count": 2626
} | 226 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/renderer/backend/metal/lazy_drawable_holder.h"
#include <QuartzCore/CAMetalLayer.h>
#include <future>
#include <memory>
#include "flutter/fml/trace_event.h"
#include "impeller/base/validation.h"
namespace impeller {
#pragma GCC diagnostic push
// Disable the diagnostic for iOS Simulators. Metal without emulation isn't
// available prior to iOS 13 and that's what the simulator headers say when
// support for CAMetalLayer begins. CAMetalLayer is available on iOS 8.0 and
// above which is well below Flutters support level.
#pragma GCC diagnostic ignored "-Wunguarded-availability-new"
std::shared_future<id<CAMetalDrawable>> GetDrawableDeferred(
CAMetalLayer* layer) {
auto future =
std::async(std::launch::deferred, [layer]() -> id<CAMetalDrawable> {
id<CAMetalDrawable> current_drawable = nil;
{
TRACE_EVENT0("impeller", "WaitForNextDrawable");
current_drawable = [layer nextDrawable];
}
if (!current_drawable) {
VALIDATION_LOG << "Could not acquire current drawable.";
return nullptr;
}
return current_drawable;
});
return std::shared_future<id<CAMetalDrawable>>(std::move(future));
}
std::shared_ptr<TextureMTL> CreateTextureFromDrawableFuture(
TextureDescriptor desc,
const std::shared_future<id<CAMetalDrawable>>& drawble_future) {
return std::make_shared<TextureMTL>(
desc, [drawble_future]() { return drawble_future.get().texture; },
/*wrapped=*/false, /*drawable=*/true);
}
#pragma GCC diagnostic pop
} // namespace impeller
| engine/impeller/renderer/backend/metal/lazy_drawable_holder.mm/0 | {
"file_path": "engine/impeller/renderer/backend/metal/lazy_drawable_holder.mm",
"repo_id": "engine",
"token_count": 638
} | 227 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/renderer/backend/metal/shader_library_mtl.h"
#include "flutter/fml/closure.h"
#include "impeller/base/validation.h"
#include "impeller/renderer/backend/metal/shader_function_mtl.h"
namespace impeller {
ShaderLibraryMTL::ShaderLibraryMTL(NSArray<id<MTLLibrary>>* libraries)
: libraries_([libraries mutableCopy]) {
if (libraries_ == nil || libraries_.count == 0) {
return;
}
is_valid_ = true;
}
ShaderLibraryMTL::~ShaderLibraryMTL() = default;
bool ShaderLibraryMTL::IsValid() const {
return is_valid_;
}
static MTLFunctionType ToMTLFunctionType(ShaderStage stage) {
switch (stage) {
case ShaderStage::kVertex:
return MTLFunctionTypeVertex;
case ShaderStage::kFragment:
return MTLFunctionTypeFragment;
case ShaderStage::kUnknown:
case ShaderStage::kCompute:
return MTLFunctionTypeKernel;
}
FML_UNREACHABLE();
}
std::shared_ptr<const ShaderFunction> ShaderLibraryMTL::GetFunction(
std::string_view name,
ShaderStage stage) {
if (!IsValid()) {
return nullptr;
}
if (name.empty()) {
VALIDATION_LOG << "Library function name was empty.";
return nullptr;
}
ShaderKey key(name, stage);
id<MTLFunction> function = nil;
id<MTLLibrary> library = nil;
{
ReaderLock lock(libraries_mutex_);
if (auto found = functions_.find(key); found != functions_.end()) {
return found->second;
}
for (size_t i = 0, count = [libraries_ count]; i < count; i++) {
library = libraries_[i];
function = [library newFunctionWithName:@(name.data())];
if (function) {
break;
}
}
if (function == nil) {
return nullptr;
}
if (function.functionType != ToMTLFunctionType(stage)) {
VALIDATION_LOG << "Library function named " << name
<< " was for an unexpected shader stage.";
return nullptr;
}
auto func = std::shared_ptr<ShaderFunctionMTL>(new ShaderFunctionMTL(
library_id_, function, library, {name.data(), name.size()}, stage));
functions_[key] = func;
return func;
}
}
id<MTLDevice> ShaderLibraryMTL::GetDevice() const {
ReaderLock lock(libraries_mutex_);
if (libraries_.count > 0u) {
return libraries_[0].device;
}
return nil;
}
// |ShaderLibrary|
void ShaderLibraryMTL::RegisterFunction(std::string name, // unused
ShaderStage stage, // unused
std::shared_ptr<fml::Mapping> code,
RegistrationCallback callback) {
if (!callback) {
callback = [](auto) {};
}
auto failure_callback = std::make_shared<fml::ScopedCleanupClosure>(
[callback]() { callback(false); });
if (!IsValid()) {
return;
}
if (code == nullptr || code->GetMapping() == nullptr) {
return;
}
auto device = GetDevice();
if (device == nil) {
return;
}
auto source = [[NSString alloc] initWithBytes:code->GetMapping()
length:code->GetSize()
encoding:NSUTF8StringEncoding];
auto weak_this = weak_from_this();
[device newLibraryWithSource:source
options:NULL
completionHandler:^(id<MTLLibrary> library, NSError* error) {
auto strong_this = weak_this.lock();
if (!strong_this) {
VALIDATION_LOG << "Shader library was collected before "
"dynamic shader stage could be registered.";
return;
}
if (!library) {
VALIDATION_LOG << "Could not register dynamic stage library: "
<< error.localizedDescription.UTF8String;
return;
}
reinterpret_cast<ShaderLibraryMTL*>(strong_this.get())
->RegisterLibrary(library);
failure_callback->Release();
callback(true);
}];
}
// |ShaderLibrary|
void ShaderLibraryMTL::UnregisterFunction(std::string name, ShaderStage stage) {
ReaderLock lock(libraries_mutex_);
// Find the shader library containing this function name and remove it.
bool found_library = false;
for (size_t i = [libraries_ count] - 1; i >= 0; i--) {
id<MTLFunction> function =
[libraries_[i] newFunctionWithName:@(name.data())];
if (function) {
[libraries_ removeObjectAtIndex:i];
found_library = true;
break;
}
}
if (!found_library) {
VALIDATION_LOG << "Library containing function " << name
<< " was not found, so it couldn't be unregistered.";
}
// Remove the shader from the function cache.
ShaderKey key(name, stage);
auto found = functions_.find(key);
if (found == functions_.end()) {
VALIDATION_LOG << "Library function named " << name
<< " was not found, so it couldn't be unregistered.";
return;
}
functions_.erase(found);
}
void ShaderLibraryMTL::RegisterLibrary(id<MTLLibrary> library) {
WriterLock lock(libraries_mutex_);
[libraries_ addObject:library];
}
} // namespace impeller
| engine/impeller/renderer/backend/metal/shader_library_mtl.mm/0 | {
"file_path": "engine/impeller/renderer/backend/metal/shader_library_mtl.mm",
"repo_id": "engine",
"token_count": 2256
} | 228 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/testing/testing.h" // IWYU pragma: keep.
#include "fml/synchronization/waitable_event.h"
#include "impeller/renderer/backend/vulkan/command_pool_vk.h"
#include "impeller/renderer/backend/vulkan/resource_manager_vk.h"
#include "impeller/renderer/backend/vulkan/test/mock_vulkan.h"
namespace impeller {
namespace testing {
TEST(CommandPoolRecyclerVKTest, GetsACommandPoolPerThread) {
auto const context = MockVulkanContextBuilder().Build();
{
// Record the memory location of each pointer to a command pool.
//
// These pools have to be held at this context, otherwise they will be
// dropped and recycled and potentially reused by another thread, causing
// flaky tests.
std::shared_ptr<CommandPoolVK> pool1;
std::shared_ptr<CommandPoolVK> pool2;
// Create a command pool in two threads and record the memory location.
std::thread thread1(
[&]() { pool1 = context->GetCommandPoolRecycler()->Get(); });
std::thread thread2(
[&]() { pool2 = context->GetCommandPoolRecycler()->Get(); });
thread1.join();
thread2.join();
// The two command pools should be different.
EXPECT_NE(pool1, pool2);
}
context->Shutdown();
}
TEST(CommandPoolRecyclerVKTest, GetsTheSameCommandPoolOnSameThread) {
auto const context = MockVulkanContextBuilder().Build();
auto const pool1 = context->GetCommandPoolRecycler()->Get();
auto const pool2 = context->GetCommandPoolRecycler()->Get();
// The two command pools should be the same.
EXPECT_EQ(pool1.get(), pool2.get());
context->Shutdown();
}
namespace {
// Invokes the provided callback when the destructor is called.
//
// Can be moved, but not copied.
class DeathRattle final {
public:
explicit DeathRattle(std::function<void()> callback)
: callback_(std::move(callback)) {}
DeathRattle(DeathRattle&&) = default;
DeathRattle& operator=(DeathRattle&&) = default;
~DeathRattle() { callback_(); }
private:
std::function<void()> callback_;
};
} // namespace
TEST(CommandPoolRecyclerVKTest, ReclaimMakesCommandPoolAvailable) {
auto const context = MockVulkanContextBuilder().Build();
{
// Fetch a pool (which will be created).
auto const recycler = context->GetCommandPoolRecycler();
auto const pool = recycler->Get();
// This normally is called at the end of a frame.
recycler->Dispose();
}
// Add something to the resource manager and have it notify us when it's
// destroyed. That should give us a non-flaky signal that the pool has been
// reclaimed as well.
auto waiter = fml::AutoResetWaitableEvent();
auto rattle = DeathRattle([&waiter]() { waiter.Signal(); });
{
UniqueResourceVKT<DeathRattle> resource(context->GetResourceManager(),
std::move(rattle));
}
waiter.Wait();
// On another thread explicitly, request a new pool.
std::thread thread([&]() {
auto const pool = context->GetCommandPoolRecycler()->Get();
EXPECT_NE(pool.get(), nullptr);
});
thread.join();
// Now check that we only ever created one pool.
auto const called = GetMockVulkanFunctions(context->GetDevice());
EXPECT_EQ(std::count(called->begin(), called->end(), "vkCreateCommandPool"),
1u);
context->Shutdown();
}
TEST(CommandPoolRecyclerVKTest, CommandBuffersAreRecycled) {
auto const context = MockVulkanContextBuilder().Build();
{
// Fetch a pool (which will be created).
auto const recycler = context->GetCommandPoolRecycler();
auto pool = recycler->Get();
auto buffer = pool->CreateCommandBuffer();
pool->CollectCommandBuffer(std::move(buffer));
// This normally is called at the end of a frame.
recycler->Dispose();
}
// Wait for the pool to be reclaimed.
for (auto i = 0u; i < 2u; i++) {
auto waiter = fml::AutoResetWaitableEvent();
auto rattle = DeathRattle([&waiter]() { waiter.Signal(); });
{
UniqueResourceVKT<DeathRattle> resource(context->GetResourceManager(),
std::move(rattle));
}
waiter.Wait();
}
{
// Create a second pool and command buffer, which should reused the existing
// pool and cmd buffer.
auto const recycler = context->GetCommandPoolRecycler();
auto pool = recycler->Get();
auto buffer = pool->CreateCommandBuffer();
pool->CollectCommandBuffer(std::move(buffer));
// This normally is called at the end of a frame.
recycler->Dispose();
}
// Now check that we only ever created one pool and one command buffer.
auto const called = GetMockVulkanFunctions(context->GetDevice());
EXPECT_EQ(std::count(called->begin(), called->end(), "vkCreateCommandPool"),
1u);
EXPECT_EQ(
std::count(called->begin(), called->end(), "vkAllocateCommandBuffers"),
1u);
context->Shutdown();
}
} // namespace testing
} // namespace impeller
| engine/impeller/renderer/backend/vulkan/command_pool_vk_unittests.cc/0 | {
"file_path": "engine/impeller/renderer/backend/vulkan/command_pool_vk_unittests.cc",
"repo_id": "engine",
"token_count": 1722
} | 229 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_DEVICE_BUFFER_VK_H_
#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_DEVICE_BUFFER_VK_H_
#include <memory>
#include "impeller/base/backend_cast.h"
#include "impeller/core/device_buffer.h"
#include "impeller/renderer/backend/vulkan/resource_manager_vk.h"
#include "impeller/renderer/backend/vulkan/vma.h"
namespace impeller {
class DeviceBufferVK final : public DeviceBuffer,
public BackendCast<DeviceBufferVK, DeviceBuffer> {
public:
DeviceBufferVK(DeviceBufferDescriptor desc,
std::weak_ptr<Context> context,
UniqueBufferVMA buffer,
VmaAllocationInfo info);
// |DeviceBuffer|
~DeviceBufferVK() override;
vk::Buffer GetBuffer() const;
private:
friend class AllocatorVK;
struct BufferResource {
UniqueBufferVMA buffer;
VmaAllocationInfo info = {};
BufferResource() = default;
BufferResource(UniqueBufferVMA p_buffer, VmaAllocationInfo p_info)
: buffer(std::move(p_buffer)), info(p_info) {}
BufferResource(BufferResource&& o) {
std::swap(o.buffer, buffer);
std::swap(o.info, info);
}
BufferResource(const BufferResource&) = delete;
BufferResource& operator=(const BufferResource&) = delete;
};
std::weak_ptr<Context> context_;
UniqueResourceVKT<BufferResource> resource_;
// |DeviceBuffer|
uint8_t* OnGetContents() const override;
// |DeviceBuffer|
bool OnCopyHostBuffer(const uint8_t* source,
Range source_range,
size_t offset) override;
// |DeviceBuffer|
bool SetLabel(const std::string& label) override;
// |DeviceBuffer|
bool SetLabel(const std::string& label, Range range) override;
// |DeviceBuffer|
void Flush(std::optional<Range> range) const override;
// |DeviceBuffer|
void Invalidate(std::optional<Range> range) const override;
DeviceBufferVK(const DeviceBufferVK&) = delete;
DeviceBufferVK& operator=(const DeviceBufferVK&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_DEVICE_BUFFER_VK_H_
| engine/impeller/renderer/backend/vulkan/device_buffer_vk.h/0 | {
"file_path": "engine/impeller/renderer/backend/vulkan/device_buffer_vk.h",
"repo_id": "engine",
"token_count": 874
} | 230 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_PIPELINE_LIBRARY_VK_H_
#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_PIPELINE_LIBRARY_VK_H_
#include <atomic>
#include "flutter/fml/concurrent_message_loop.h"
#include "flutter/fml/macros.h"
#include "flutter/fml/mapping.h"
#include "flutter/fml/unique_fd.h"
#include "impeller/base/backend_cast.h"
#include "impeller/base/thread.h"
#include "impeller/renderer/backend/vulkan/compute_pipeline_vk.h"
#include "impeller/renderer/backend/vulkan/pipeline_cache_vk.h"
#include "impeller/renderer/backend/vulkan/pipeline_vk.h"
#include "impeller/renderer/backend/vulkan/vk.h"
#include "impeller/renderer/pipeline_library.h"
namespace impeller {
class ContextVK;
class PipelineLibraryVK final
: public PipelineLibrary,
public BackendCast<PipelineLibraryVK, PipelineLibrary> {
public:
// |PipelineLibrary|
~PipelineLibraryVK() override;
void DidAcquireSurfaceFrame();
const std::shared_ptr<PipelineCacheVK>& GetPSOCache() const;
const std::shared_ptr<fml::ConcurrentTaskRunner>& GetWorkerTaskRunner() const;
private:
friend ContextVK;
std::weak_ptr<DeviceHolderVK> device_holder_;
std::shared_ptr<PipelineCacheVK> pso_cache_;
std::shared_ptr<fml::ConcurrentTaskRunner> worker_task_runner_;
Mutex pipelines_mutex_;
PipelineMap pipelines_ IPLR_GUARDED_BY(pipelines_mutex_);
Mutex compute_pipelines_mutex_;
ComputePipelineMap compute_pipelines_ IPLR_GUARDED_BY(
compute_pipelines_mutex_);
std::atomic_size_t frames_acquired_ = 0u;
bool is_valid_ = false;
PipelineLibraryVK(
const std::shared_ptr<DeviceHolderVK>& device_holder,
std::shared_ptr<const Capabilities> caps,
fml::UniqueFD cache_directory,
std::shared_ptr<fml::ConcurrentTaskRunner> worker_task_runner);
// |PipelineLibrary|
bool IsValid() const override;
// |PipelineLibrary|
PipelineFuture<PipelineDescriptor> GetPipeline(
PipelineDescriptor descriptor) override;
// |PipelineLibrary|
PipelineFuture<ComputePipelineDescriptor> GetPipeline(
ComputePipelineDescriptor descriptor) override;
// |PipelineLibrary|
void RemovePipelinesWithEntryPoint(
std::shared_ptr<const ShaderFunction> function) override;
std::unique_ptr<ComputePipelineVK> CreateComputePipeline(
const ComputePipelineDescriptor& desc);
void PersistPipelineCacheToDisk();
PipelineLibraryVK(const PipelineLibraryVK&) = delete;
PipelineLibraryVK& operator=(const PipelineLibraryVK&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_PIPELINE_LIBRARY_VK_H_
| engine/impeller/renderer/backend/vulkan/pipeline_library_vk.h/0 | {
"file_path": "engine/impeller/renderer/backend/vulkan/pipeline_library_vk.h",
"repo_id": "engine",
"token_count": 1025
} | 231 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SAMPLER_VK_H_
#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SAMPLER_VK_H_
#include "flutter/fml/macros.h"
#include "impeller/base/backend_cast.h"
#include "impeller/core/sampler.h"
#include "impeller/renderer/backend/vulkan/shared_object_vk.h"
#include "impeller/renderer/backend/vulkan/vk.h"
namespace impeller {
class SamplerLibraryVK;
class YUVConversionVK;
class SamplerVK final : public Sampler, public BackendCast<SamplerVK, Sampler> {
public:
SamplerVK(const vk::Device& device,
SamplerDescriptor desc,
std::shared_ptr<YUVConversionVK> yuv_conversion = {});
// |Sampler|
~SamplerVK() override;
vk::Sampler GetSampler() const;
std::shared_ptr<SamplerVK> CreateVariantForConversion(
std::shared_ptr<YUVConversionVK> conversion) const;
const std::shared_ptr<YUVConversionVK>& GetYUVConversion() const;
private:
friend SamplerLibraryVK;
const vk::Device device_;
SharedHandleVK<vk::Sampler> sampler_;
std::shared_ptr<YUVConversionVK> yuv_conversion_;
bool is_valid_ = false;
SamplerVK(const SamplerVK&) = delete;
SamplerVK& operator=(const SamplerVK&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SAMPLER_VK_H_
| engine/impeller/renderer/backend/vulkan/sampler_vk.h/0 | {
"file_path": "engine/impeller/renderer/backend/vulkan/sampler_vk.h",
"repo_id": "engine",
"token_count": 561
} | 232 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SWAPCHAIN_KHR_KHR_SWAPCHAIN_IMPL_VK_H_
#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SWAPCHAIN_KHR_KHR_SWAPCHAIN_IMPL_VK_H_
#include <cstdint>
#include <memory>
#include <variant>
#include "impeller/geometry/size.h"
#include "impeller/renderer/backend/vulkan/vk.h"
#include "vulkan/vulkan_enums.hpp"
namespace impeller {
class Context;
class KHRSwapchainImageVK;
class Surface;
struct KHRFrameSynchronizerVK;
//------------------------------------------------------------------------------
/// @brief An instance of a swapchain that does NOT adapt to going out of
/// date with the underlying surface. Errors will be indicated when
/// the next drawable is acquired from this implementation of the
/// swapchain. If the error is due the swapchain going out of date,
/// the caller must recreate another instance by optionally
/// stealing this implementations guts.
///
class KHRSwapchainImplVK final
: public std::enable_shared_from_this<KHRSwapchainImplVK> {
public:
static std::shared_ptr<KHRSwapchainImplVK> Create(
const std::shared_ptr<Context>& context,
vk::UniqueSurfaceKHR surface,
const ISize& size,
bool enable_msaa = true,
vk::SwapchainKHR old_swapchain = VK_NULL_HANDLE);
~KHRSwapchainImplVK();
bool IsValid() const;
struct AcquireResult {
std::unique_ptr<Surface> surface;
bool out_of_date = false;
explicit AcquireResult(bool p_out_of_date = false)
: out_of_date(p_out_of_date) {}
explicit AcquireResult(std::unique_ptr<Surface> p_surface)
: surface(std::move(p_surface)) {}
};
AcquireResult AcquireNextDrawable();
vk::Format GetSurfaceFormat() const;
std::shared_ptr<Context> GetContext() const;
std::pair<vk::UniqueSurfaceKHR, vk::UniqueSwapchainKHR> DestroySwapchain();
const ISize& GetSize() const;
private:
std::weak_ptr<Context> context_;
vk::UniqueSurfaceKHR surface_;
vk::Format surface_format_ = vk::Format::eUndefined;
vk::UniqueSwapchainKHR swapchain_;
std::vector<std::shared_ptr<KHRSwapchainImageVK>> images_;
std::vector<std::unique_ptr<KHRFrameSynchronizerVK>> synchronizers_;
size_t current_frame_ = 0u;
ISize size_;
bool enable_msaa_ = true;
bool is_valid_ = false;
KHRSwapchainImplVK(const std::shared_ptr<Context>& context,
vk::UniqueSurfaceKHR surface,
const ISize& size,
bool enable_msaa,
vk::SwapchainKHR old_swapchain);
bool Present(const std::shared_ptr<KHRSwapchainImageVK>& image,
uint32_t index);
void WaitIdle() const;
KHRSwapchainImplVK(const KHRSwapchainImplVK&) = delete;
KHRSwapchainImplVK& operator=(const KHRSwapchainImplVK&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SWAPCHAIN_KHR_KHR_SWAPCHAIN_IMPL_VK_H_
| engine/impeller/renderer/backend/vulkan/swapchain/khr/khr_swapchain_impl_vk.h/0 | {
"file_path": "engine/impeller/renderer/backend/vulkan/swapchain/khr/khr_swapchain_impl_vk.h",
"repo_id": "engine",
"token_count": 1233
} | 233 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_VK_H_
#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_VK_H_
#include "flutter/fml/build_config.h"
#include "flutter/fml/logging.h"
#define VK_NO_PROTOTYPES
#if FML_OS_IOS
// #ifndef VK_USE_PLATFORM_IOS_MVK
// #define VK_USE_PLATFORM_IOS_MVK
// #endif // VK_USE_PLATFORM_IOS_MVK
#ifndef VK_USE_PLATFORM_METAL_EXT
#define VK_USE_PLATFORM_METAL_EXT
#endif // VK_USE_PLATFORM_METAL_EXT
#elif FML_OS_MACOSX
// #ifndef VK_USE_PLATFORM_MACOS_MVK
// #define VK_USE_PLATFORM_MACOS_MVK
// #endif // VK_USE_PLATFORM_MACOS_MVK
#ifndef VK_USE_PLATFORM_METAL_EXT
#define VK_USE_PLATFORM_METAL_EXT
#endif // VK_USE_PLATFORM_METAL_EXT
#elif FML_OS_ANDROID
#ifndef VK_USE_PLATFORM_ANDROID_KHR
#define VK_USE_PLATFORM_ANDROID_KHR
#endif // VK_USE_PLATFORM_ANDROID_KHR
#elif FML_OS_LINUX
// Nothing for now.
#elif FML_OS_WIN
#ifndef VK_USE_PLATFORM_WIN32_KHR
#define VK_USE_PLATFORM_WIN32_KHR
#endif // VK_USE_PLATFORM_WIN32_KHR
#elif OS_FUCHSIA
#ifndef VK_USE_PLATFORM_ANDROID_KHR
#define VK_USE_PLATFORM_ANDROID_KHR
#endif // VK_USE_PLATFORM_ANDROID_KHR
#endif // FML_OS
#if !defined(NDEBUG)
#define VULKAN_HPP_ASSERT FML_CHECK
#else
#define VULKAN_HPP_ASSERT(ignored) \
{}
#endif
#define VULKAN_HPP_NAMESPACE impeller::vk
#define VULKAN_HPP_ASSERT_ON_RESULT(ignored) \
{ [[maybe_unused]] auto res = (ignored); }
#define VULKAN_HPP_NO_EXCEPTIONS
#include "vulkan/vulkan.hpp" // IWYU pragma: keep.
static_assert(VK_HEADER_VERSION >= 215, "Vulkan headers must not be too old.");
#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_VK_H_
| engine/impeller/renderer/backend/vulkan/vk.h/0 | {
"file_path": "engine/impeller/renderer/backend/vulkan/vk.h",
"repo_id": "engine",
"token_count": 817
} | 234 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_RENDERER_COMMAND_H_
#define FLUTTER_IMPELLER_RENDERER_COMMAND_H_
#include <cstdint>
#include <memory>
#include <optional>
#include <string>
#include "impeller/core/buffer_view.h"
#include "impeller/core/formats.h"
#include "impeller/core/resource_binder.h"
#include "impeller/core/sampler.h"
#include "impeller/core/shader_types.h"
#include "impeller/core/texture.h"
#include "impeller/core/vertex_buffer.h"
#include "impeller/geometry/rect.h"
#include "impeller/renderer/pipeline.h"
namespace impeller {
#ifdef IMPELLER_DEBUG
#define DEBUG_COMMAND_INFO(obj, arg) obj.label = arg;
#else
#define DEBUG_COMMAND_INFO(obj, arg)
#endif // IMPELLER_DEBUG
template <class T>
struct Resource {
using ResourceType = T;
ResourceType resource;
Resource() {}
Resource(const ShaderMetadata* metadata, ResourceType p_resource)
: resource(p_resource), metadata_(metadata) {}
Resource(std::shared_ptr<const ShaderMetadata>& metadata,
ResourceType p_resource)
: resource(p_resource), dynamic_metadata_(metadata) {}
const ShaderMetadata* GetMetadata() const {
return dynamic_metadata_ ? dynamic_metadata_.get() : metadata_;
}
private:
// Static shader metadata (typically generated by ImpellerC).
const ShaderMetadata* metadata_ = nullptr;
// Dynamically generated shader metadata.
std::shared_ptr<const ShaderMetadata> dynamic_metadata_;
};
using BufferResource = Resource<BufferView>;
using TextureResource = Resource<std::shared_ptr<const Texture>>;
/// @brief combines the texture, sampler and sampler slot information.
struct TextureAndSampler {
SampledImageSlot slot;
TextureResource texture;
const std::unique_ptr<const Sampler>& sampler;
};
/// @brief combines the buffer resource and its uniform slot information.
struct BufferAndUniformSlot {
ShaderUniformSlot slot;
BufferResource view;
};
struct Bindings {
std::vector<TextureAndSampler> sampled_images;
std::vector<BufferAndUniformSlot> buffers;
};
//------------------------------------------------------------------------------
/// @brief An object used to specify work to the GPU along with references
/// to resources the GPU will used when doing said work.
///
/// To construct a valid command, follow these steps:
/// * Specify a valid pipeline.
/// * Specify vertex information via a call `BindVertices`
/// * Specify any stage bindings.
/// * (Optional) Specify a debug label.
///
/// Command can be created frequently and on demand. The resources
/// referenced in commands views into buffers managed by other
/// allocators and resource managers.
///
struct Command : public ResourceBinder {
//----------------------------------------------------------------------------
/// The pipeline to use for this command.
///
std::shared_ptr<Pipeline<PipelineDescriptor>> pipeline;
//----------------------------------------------------------------------------
/// The buffer, texture, and sampler bindings used by the vertex pipeline
/// stage.
///
Bindings vertex_bindings;
//----------------------------------------------------------------------------
/// The buffer, texture, and sampler bindings used by the fragment pipeline
/// stage.
///
Bindings fragment_bindings;
#ifdef IMPELLER_DEBUG
//----------------------------------------------------------------------------
/// The debugging label to use for the command.
///
std::string label;
#endif // IMPELLER_DEBUG
//----------------------------------------------------------------------------
/// The reference value to use in stenciling operations. Stencil configuration
/// is part of pipeline setup and can be read from the pipelines descriptor.
///
/// @see `Pipeline`
/// @see `PipelineDescriptor`
///
uint32_t stencil_reference = 0u;
//----------------------------------------------------------------------------
/// The offset used when indexing into the vertex buffer.
///
uint64_t base_vertex = 0u;
//----------------------------------------------------------------------------
/// The viewport coordinates that the rasterizer linearly maps normalized
/// device coordinates to.
/// If unset, the viewport is the size of the render target with a zero
/// origin, znear=0, and zfar=1.
///
std::optional<Viewport> viewport;
//----------------------------------------------------------------------------
/// The scissor rect to use for clipping writes to the render target. The
/// scissor rect must lie entirely within the render target.
/// If unset, no scissor is applied.
///
std::optional<IRect> scissor;
//----------------------------------------------------------------------------
/// The number of instances of the given set of vertices to render. Not all
/// backends support rendering more than one instance at a time.
///
/// @warning Setting this to more than one will limit the availability of
/// backends to use with this command.
///
size_t instance_count = 1u;
//----------------------------------------------------------------------------
/// The bound per-vertex data and optional index buffer.
VertexBuffer vertex_buffer;
//----------------------------------------------------------------------------
/// @brief Specify the vertex and index buffer to use for this command.
///
/// @param[in] buffer The vertex and index buffer definition. If possible,
/// this value should be moved and not copied.
///
/// @return returns if the binding was updated.
///
bool BindVertices(VertexBuffer buffer);
// |ResourceBinder|
bool BindResource(ShaderStage stage,
DescriptorType type,
const ShaderUniformSlot& slot,
const ShaderMetadata& metadata,
BufferView view) override;
bool BindResource(ShaderStage stage,
DescriptorType type,
const ShaderUniformSlot& slot,
const std::shared_ptr<const ShaderMetadata>& metadata,
BufferView view);
// |ResourceBinder|
bool BindResource(ShaderStage stage,
DescriptorType type,
const SampledImageSlot& slot,
const ShaderMetadata& metadata,
std::shared_ptr<const Texture> texture,
const std::unique_ptr<const Sampler>& sampler) override;
bool IsValid() const { return pipeline && pipeline->IsValid(); }
private:
template <class T>
bool DoBindResource(ShaderStage stage,
const ShaderUniformSlot& slot,
T metadata,
BufferView view);
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_RENDERER_COMMAND_H_
| engine/impeller/renderer/command.h/0 | {
"file_path": "engine/impeller/renderer/command.h",
"repo_id": "engine",
"token_count": 2236
} | 235 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_RENDERER_CONTEXT_H_
#define FLUTTER_IMPELLER_RENDERER_CONTEXT_H_
#include <memory>
#include <string>
#include "impeller/core/allocator.h"
#include "impeller/core/capture.h"
#include "impeller/core/formats.h"
#include "impeller/renderer/capabilities.h"
#include "impeller/renderer/command_queue.h"
#include "impeller/renderer/sampler_library.h"
namespace impeller {
class ShaderLibrary;
class CommandBuffer;
class PipelineLibrary;
//------------------------------------------------------------------------------
/// @brief To do anything rendering related with Impeller, you need a
/// context.
///
/// Contexts are expensive to construct and typically you only need
/// one in the process. The context represents a connection to a
/// graphics or compute accelerator on the device.
///
/// If there are multiple context in a process, it would typically
/// be for separation of concerns (say, use with multiple engines in
/// Flutter), talking to multiple accelerators, or talking to the
/// same accelerator using different client APIs (Metal, Vulkan,
/// OpenGL ES, etc..).
///
/// Contexts are thread-safe. They may be created, used, and
/// collected (though not from a thread used by an internal pool) on
/// any thread. They may also be accessed simultaneously from
/// multiple threads.
///
/// Contexts are abstract and a concrete instance must be created
/// using one of the subclasses of `Context` in
/// `//impeller/renderer/backend`.
class Context {
public:
enum class BackendType {
kMetal,
kOpenGLES,
kVulkan,
};
/// The maximum number of tasks that should ever be stored for
/// `StoreTaskForGPU`.
///
/// This number was arbitrarily chosen. The idea is that this is a somewhat
/// rare situation where tasks happen to get executed in that tiny amount of
/// time while an app is being backgrounded but still executing.
static constexpr int32_t kMaxTasksAwaitingGPU = 10;
//----------------------------------------------------------------------------
/// @brief Destroys an Impeller context.
///
virtual ~Context();
//----------------------------------------------------------------------------
/// @brief Get the graphics backend of an Impeller context.
///
/// This is useful for cases where a renderer needs to track and
/// lookup backend-specific resources, like shaders or uniform
/// layout information.
///
/// It's not recommended to use this as a substitute for
/// per-backend capability checking. Instead, check for specific
/// capabilities via `GetCapabilities()`.
///
/// @return The graphics backend of the `Context`.
///
virtual BackendType GetBackendType() const = 0;
// TODO(129920): Refactor and move to capabilities.
virtual std::string DescribeGpuModel() const = 0;
//----------------------------------------------------------------------------
/// @brief Determines if a context is valid. If the caller ever receives
/// an invalid context, they must discard it and construct a new
/// context. There is no recovery mechanism to repair a bad
/// context.
///
/// It is convention in Impeller to never return an invalid
/// context from a call that returns an pointer to a context. The
/// call implementation performs validity checks itself and return
/// a null context instead of a pointer to an invalid context.
///
/// How a context goes invalid is backend specific. It could
/// happen due to device loss, or any other unrecoverable error.
///
/// @return If the context is valid.
///
virtual bool IsValid() const = 0;
//----------------------------------------------------------------------------
/// @brief Get the capabilities of Impeller context. All optionally
/// supported feature of the platform, client-rendering API, and
/// device can be queried using the `Capabilities`.
///
/// @return The capabilities. Can never be `nullptr` for a valid context.
///
virtual const std::shared_ptr<const Capabilities>& GetCapabilities()
const = 0;
// TODO(129920): Refactor and move to capabilities.
virtual bool UpdateOffscreenLayerPixelFormat(PixelFormat format);
//----------------------------------------------------------------------------
/// @brief Returns the allocator used to create textures and buffers on
/// the device.
///
/// @return The resource allocator. Can never be `nullptr` for a valid
/// context.
///
virtual std::shared_ptr<Allocator> GetResourceAllocator() const = 0;
//----------------------------------------------------------------------------
/// @brief Returns the library of shaders used to specify the
/// programmable stages of a pipeline.
///
/// @return The shader library. Can never be `nullptr` for a valid
/// context.
///
virtual std::shared_ptr<ShaderLibrary> GetShaderLibrary() const = 0;
//----------------------------------------------------------------------------
/// @brief Returns the library of combined image samplers used in
/// shaders.
///
/// @return The sampler library. Can never be `nullptr` for a valid
/// context.
///
virtual std::shared_ptr<SamplerLibrary> GetSamplerLibrary() const = 0;
//----------------------------------------------------------------------------
/// @brief Returns the library of pipelines used by render or compute
/// commands.
///
/// @return The pipeline library. Can never be `nullptr` for a valid
/// context.
///
virtual std::shared_ptr<PipelineLibrary> GetPipelineLibrary() const = 0;
//----------------------------------------------------------------------------
/// @brief Create a new command buffer. Command buffers can be used to
/// encode graphics, blit, or compute commands to be submitted to
/// the device.
///
/// A command buffer can only be used on a single thread.
/// Multi-threaded render, blit, or compute passes must create a
/// new command buffer on each thread.
///
/// @return A new command buffer.
///
virtual std::shared_ptr<CommandBuffer> CreateCommandBuffer() const = 0;
/// @brief Return the graphics queue for submitting command buffers.
virtual std::shared_ptr<CommandQueue> GetCommandQueue() const = 0;
//----------------------------------------------------------------------------
/// @brief Force all pending asynchronous work to finish. This is
/// achieved by deleting all owned concurrent message loops.
///
virtual void Shutdown() = 0;
CaptureContext capture;
/// Stores a task on the `ContextMTL` that is awaiting access for the GPU.
///
/// The task will be executed in the event that the GPU access has changed to
/// being available or that the task has been canceled. The task should
/// operate with the `SyncSwitch` to make sure the GPU is accessible.
///
/// Threadsafe.
///
/// `task` will be executed on the platform thread.
virtual void StoreTaskForGPU(const std::function<void()>& task) {
FML_CHECK(false && "not supported in this context");
}
/// Run backend specific additional setup and create common shader variants.
///
/// This bootstrap is intended to improve the performance of several
/// first frame benchmarks that are tracked in the flutter device lab.
/// The workload includes initializing commonly used but not default
/// shader variants, as well as forcing driver initialization.
virtual void InitializeCommonlyUsedShadersIfNeeded() const {}
protected:
Context();
std::vector<std::function<void()>> per_frame_task_;
private:
Context(const Context&) = delete;
Context& operator=(const Context&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_RENDERER_CONTEXT_H_
| engine/impeller/renderer/context.h/0 | {
"file_path": "engine/impeller/renderer/context.h",
"repo_id": "engine",
"token_count": 2617
} | 236 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_RENDERER_RENDER_PASS_H_
#define FLUTTER_IMPELLER_RENDERER_RENDER_PASS_H_
#include <string>
#include "fml/status.h"
#include "impeller/core/formats.h"
#include "impeller/core/resource_binder.h"
#include "impeller/core/shader_types.h"
#include "impeller/core/vertex_buffer.h"
#include "impeller/renderer/command.h"
#include "impeller/renderer/command_buffer.h"
#include "impeller/renderer/render_target.h"
namespace impeller {
class HostBuffer;
class Allocator;
//------------------------------------------------------------------------------
/// @brief Render passes encode render commands directed as one specific
/// render target into an underlying command buffer.
///
/// Render passes can be obtained from the command buffer in which
/// the pass is meant to encode commands into.
///
/// @see `CommandBuffer`
///
class RenderPass : public ResourceBinder {
public:
virtual ~RenderPass();
const std::shared_ptr<const Context>& GetContext() const;
const RenderTarget& GetRenderTarget() const;
ISize GetRenderTargetSize() const;
const Matrix& GetOrthographicTransform() const;
virtual bool IsValid() const = 0;
void SetLabel(std::string label);
/// @brief Reserve [command_count] commands in the HAL command buffer.
///
/// Note: this is not the native command buffer.
virtual void ReserveCommands(size_t command_count) {
commands_.reserve(command_count);
}
//----------------------------------------------------------------------------
/// The pipeline to use for this command.
virtual void SetPipeline(
const std::shared_ptr<Pipeline<PipelineDescriptor>>& pipeline);
//----------------------------------------------------------------------------
/// The debugging label to use for the command.
virtual void SetCommandLabel(std::string_view label);
//----------------------------------------------------------------------------
/// The reference value to use in stenciling operations. Stencil configuration
/// is part of pipeline setup and can be read from the pipelines descriptor.
///
/// @see `Pipeline`
/// @see `PipelineDescriptor`
///
virtual void SetStencilReference(uint32_t value);
virtual void SetBaseVertex(uint64_t value);
//----------------------------------------------------------------------------
/// The viewport coordinates that the rasterizer linearly maps normalized
/// device coordinates to.
/// If unset, the viewport is the size of the render target with a zero
/// origin, znear=0, and zfar=1.
///
virtual void SetViewport(Viewport viewport);
//----------------------------------------------------------------------------
/// The scissor rect to use for clipping writes to the render target. The
/// scissor rect must lie entirely within the render target.
/// If unset, no scissor is applied.
///
virtual void SetScissor(IRect scissor);
//----------------------------------------------------------------------------
/// The number of instances of the given set of vertices to render. Not all
/// backends support rendering more than one instance at a time.
///
/// @warning Setting this to more than one will limit the availability of
/// backends to use with this command.
///
virtual void SetInstanceCount(size_t count);
//----------------------------------------------------------------------------
/// @brief Specify the vertex and index buffer to use for this command.
///
/// @param[in] buffer The vertex and index buffer definition. If possible,
/// this value should be moved and not copied.
///
/// @return returns if the binding was updated.
///
virtual bool SetVertexBuffer(VertexBuffer buffer);
/// Record the currently pending command.
virtual fml::Status Draw();
// |ResourceBinder|
virtual bool BindResource(ShaderStage stage,
DescriptorType type,
const ShaderUniformSlot& slot,
const ShaderMetadata& metadata,
BufferView view) override;
virtual bool BindResource(
ShaderStage stage,
DescriptorType type,
const ShaderUniformSlot& slot,
const std::shared_ptr<const ShaderMetadata>& metadata,
BufferView view);
// |ResourceBinder|
virtual bool BindResource(
ShaderStage stage,
DescriptorType type,
const SampledImageSlot& slot,
const ShaderMetadata& metadata,
std::shared_ptr<const Texture> texture,
const std::unique_ptr<const Sampler>& sampler) override;
//----------------------------------------------------------------------------
/// @brief Encode the recorded commands to the underlying command buffer.
///
/// @return If the commands were encoded to the underlying command
/// buffer.
///
bool EncodeCommands() const;
//----------------------------------------------------------------------------
/// @brief Accessor for the current Commands.
///
/// @details Visible for testing.
///
virtual const std::vector<Command>& GetCommands() const { return commands_; }
//----------------------------------------------------------------------------
/// @brief The sample count of the attached render target.
SampleCount GetSampleCount() const;
//----------------------------------------------------------------------------
/// @brief The pixel format of the attached render target.
PixelFormat GetRenderTargetPixelFormat() const;
//----------------------------------------------------------------------------
/// @brief Whether the render target has a depth attachment.
bool HasDepthAttachment() const;
//----------------------------------------------------------------------------
/// @brief Whether the render target has an stencil attachment.
bool HasStencilAttachment() const;
protected:
const std::shared_ptr<const Context> context_;
// The following properties: sample_count, pixel_format,
// has_stencil_attachment, and render_target_size are cached on the
// RenderTarget to speed up numerous lookups during rendering. This is safe as
// the RenderTarget itself is copied into the RenderTarget and only exposed as
// a const reference.
const SampleCount sample_count_;
const PixelFormat pixel_format_;
const bool has_depth_attachment_;
const bool has_stencil_attachment_;
const ISize render_target_size_;
const RenderTarget render_target_;
std::vector<Command> commands_;
const Matrix orthographic_;
//----------------------------------------------------------------------------
/// @brief Record a command for subsequent encoding to the underlying
/// command buffer. No work is encoded into the command buffer at
/// this time.
///
/// @param[in] command The command
///
/// @return If the command was valid for subsequent commitment.
///
bool AddCommand(Command&& command);
RenderPass(std::shared_ptr<const Context> context,
const RenderTarget& target);
virtual void OnSetLabel(std::string label) = 0;
virtual bool OnEncodeCommands(const Context& context) const = 0;
private:
RenderPass(const RenderPass&) = delete;
RenderPass& operator=(const RenderPass&) = delete;
Command pending_;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_RENDERER_RENDER_PASS_H_
| engine/impeller/renderer/render_pass.h/0 | {
"file_path": "engine/impeller/renderer/render_pass.h",
"repo_id": "engine",
"token_count": 2188
} | 237 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_RENDERER_SNAPSHOT_H_
#define FLUTTER_IMPELLER_RENDERER_SNAPSHOT_H_
#include <functional>
#include <memory>
#include <vector>
#include "flutter/fml/macros.h"
#include "impeller/core/formats.h"
#include "impeller/core/sampler_descriptor.h"
#include "impeller/core/texture.h"
#include "impeller/geometry/matrix.h"
#include "impeller/geometry/rect.h"
namespace impeller {
class ContentContext;
class Entity;
/// Represents a texture and its intended draw transform/sampler configuration.
struct Snapshot {
std::shared_ptr<Texture> texture;
/// The transform that should be applied to this texture for rendering.
Matrix transform;
SamplerDescriptor sampler_descriptor =
SamplerDescriptor("Default Snapshot Sampler",
MinMagFilter::kLinear,
MinMagFilter::kLinear,
MipFilter::kNearest);
Scalar opacity = 1.0f;
std::optional<Rect> GetCoverage() const;
/// @brief Get the transform that converts screen space coordinates to the UV
/// space of this snapshot.
std::optional<Matrix> GetUVTransform() const;
/// @brief Map a coverage rect to this filter input's UV space.
/// Result order: Top left, top right, bottom left, bottom right.
std::optional<std::array<Point, 4>> GetCoverageUVs(
const Rect& coverage) const;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_RENDERER_SNAPSHOT_H_
| engine/impeller/renderer/snapshot.h/0 | {
"file_path": "engine/impeller/renderer/snapshot.h",
"repo_id": "engine",
"token_count": 592
} | 238 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/impeller/runtime_stage/runtime_stage_playground.h"
#include <future>
#include "flutter/fml/make_copyable.h"
#include "flutter/testing/testing.h"
#include "impeller/core/shader_types.h"
#include "impeller/renderer/shader_library.h"
namespace impeller {
RuntimeStagePlayground::RuntimeStagePlayground() = default;
RuntimeStagePlayground::~RuntimeStagePlayground() = default;
bool RuntimeStagePlayground::RegisterStage(const RuntimeStage& stage) {
std::promise<bool> registration;
auto future = registration.get_future();
const std::shared_ptr<ShaderLibrary>& library =
GetContext()->GetShaderLibrary();
GetContext()->GetShaderLibrary()->RegisterFunction(
stage.GetEntrypoint(), ToShaderStage(stage.GetShaderStage()),
stage.GetCodeMapping(),
fml::MakeCopyable([reg = std::move(registration)](bool result) mutable {
reg.set_value(result);
}));
return future.get();
}
} // namespace impeller
| engine/impeller/runtime_stage/runtime_stage_playground.cc/0 | {
"file_path": "engine/impeller/runtime_stage/runtime_stage_playground.cc",
"repo_id": "engine",
"token_count": 370
} | 239 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_IMPELLER_SCENE_CAMERA_H_
#define FLUTTER_IMPELLER_SCENE_CAMERA_H_
#include <optional>
#include "impeller/geometry/matrix.h"
namespace impeller {
namespace scene {
class Camera {
public:
static Camera MakePerspective(Radians fov_y, Vector3 position);
Camera LookAt(Vector3 target, Vector3 up = Vector3(0, -1, 0)) const;
Matrix GetTransform(ISize target_size) const;
private:
Radians fov_y_ = Degrees(60);
Vector3 position_ = Vector3();
Vector3 target_ = Vector3(0, 0, -1);
Vector3 up_ = Vector3(0, -1, 0);
Scalar z_near_ = 0.1f;
Scalar z_far_ = 1000.0f;
mutable std::optional<Matrix> transform_;
};
} // namespace scene
} // namespace impeller
#endif // FLUTTER_IMPELLER_SCENE_CAMERA_H_
| engine/impeller/scene/camera.h/0 | {
"file_path": "engine/impeller/scene/camera.h",
"repo_id": "engine",
"token_count": 333
} | 240 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/scene/material.h"
#include "impeller/base/validation.h"
#include "impeller/core/formats.h"
#include "impeller/core/sampler_descriptor.h"
#include "impeller/renderer/render_pass.h"
#include "impeller/scene/importer/conversions.h"
#include "impeller/scene/importer/scene_flatbuffers.h"
#include "impeller/scene/pipeline_key.h"
#include "impeller/scene/scene_context.h"
#include "impeller/scene/shaders/unlit.frag.h"
#include <memory>
namespace impeller {
namespace scene {
//------------------------------------------------------------------------------
/// Material
///
Material::~Material() = default;
std::unique_ptr<Material> Material::MakeFromFlatbuffer(
const fb::Material& material,
const std::vector<std::shared_ptr<Texture>>& textures) {
switch (material.type()) {
case fb::MaterialType::kUnlit:
return UnlitMaterial::MakeFromFlatbuffer(material, textures);
case fb::MaterialType::kPhysicallyBased:
return PhysicallyBasedMaterial::MakeFromFlatbuffer(material, textures);
}
}
std::unique_ptr<UnlitMaterial> Material::MakeUnlit() {
return std::make_unique<UnlitMaterial>();
}
std::unique_ptr<PhysicallyBasedMaterial> Material::MakePhysicallyBased() {
return std::make_unique<PhysicallyBasedMaterial>();
}
void Material::SetVertexColorWeight(Scalar weight) {
vertex_color_weight_ = weight;
}
void Material::SetBlendConfig(BlendConfig blend_config) {
blend_config_ = blend_config;
}
void Material::SetStencilConfig(StencilConfig stencil_config) {
stencil_config_ = stencil_config;
}
void Material::SetTranslucent(bool is_translucent) {
is_translucent_ = is_translucent;
}
SceneContextOptions Material::GetContextOptions(const RenderPass& pass) const {
// TODO(bdero): Pipeline blend and stencil config.
return {.sample_count = pass.GetRenderTarget().GetSampleCount()};
}
//------------------------------------------------------------------------------
/// UnlitMaterial
///
std::unique_ptr<UnlitMaterial> UnlitMaterial::MakeFromFlatbuffer(
const fb::Material& material,
const std::vector<std::shared_ptr<Texture>>& textures) {
if (material.type() != fb::MaterialType::kUnlit) {
VALIDATION_LOG << "Cannot unpack unlit material because the ipscene "
"material type is not unlit.";
return nullptr;
}
auto result = Material::MakeUnlit();
if (material.base_color_factor()) {
result->SetColor(importer::ToColor(*material.base_color_factor()));
}
if (material.base_color_texture() >= 0 &&
material.base_color_texture() < static_cast<int32_t>(textures.size())) {
result->SetColorTexture(textures[material.base_color_texture()]);
}
return result;
}
UnlitMaterial::~UnlitMaterial() = default;
void UnlitMaterial::SetColor(Color color) {
color_ = color;
}
void UnlitMaterial::SetColorTexture(std::shared_ptr<Texture> color_texture) {
color_texture_ = std::move(color_texture);
}
// |Material|
MaterialType UnlitMaterial::GetMaterialType() const {
return MaterialType::kUnlit;
}
// |Material|
void UnlitMaterial::BindToCommand(const SceneContext& scene_context,
HostBuffer& buffer,
RenderPass& pass) const {
// Uniform buffer.
UnlitFragmentShader::FragInfo info;
info.color = color_;
info.vertex_color_weight = vertex_color_weight_;
UnlitFragmentShader::BindFragInfo(pass, buffer.EmplaceUniform(info));
// Textures.
SamplerDescriptor sampler_descriptor;
sampler_descriptor.label = "Trilinear";
sampler_descriptor.min_filter = MinMagFilter::kLinear;
sampler_descriptor.mag_filter = MinMagFilter::kLinear;
sampler_descriptor.mip_filter = MipFilter::kLinear;
UnlitFragmentShader::BindBaseColorTexture(
pass,
color_texture_ ? color_texture_ : scene_context.GetPlaceholderTexture(),
scene_context.GetContext()->GetSamplerLibrary()->GetSampler(
sampler_descriptor));
}
//------------------------------------------------------------------------------
/// StandardMaterial
///
std::unique_ptr<PhysicallyBasedMaterial>
PhysicallyBasedMaterial::MakeFromFlatbuffer(
const fb::Material& material,
const std::vector<std::shared_ptr<Texture>>& textures) {
if (material.type() != fb::MaterialType::kPhysicallyBased) {
VALIDATION_LOG << "Cannot unpack unlit material because the ipscene "
"material type is not unlit.";
return nullptr;
}
auto result = Material::MakePhysicallyBased();
result->SetAlbedo(material.base_color_factor()
? importer::ToColor(*material.base_color_factor())
: Color::White());
result->SetRoughness(material.roughness_factor());
result->SetMetallic(material.metallic_factor());
if (material.base_color_texture() >= 0 &&
material.base_color_texture() < static_cast<int32_t>(textures.size())) {
result->SetAlbedoTexture(textures[material.base_color_texture()]);
result->SetVertexColorWeight(0);
}
if (material.metallic_roughness_texture() >= 0 &&
material.metallic_roughness_texture() <
static_cast<int32_t>(textures.size())) {
result->SetMetallicRoughnessTexture(
textures[material.metallic_roughness_texture()]);
}
if (material.normal_texture() >= 0 &&
material.normal_texture() < static_cast<int32_t>(textures.size())) {
result->SetNormalTexture(textures[material.normal_texture()]);
}
if (material.occlusion_texture() >= 0 &&
material.occlusion_texture() < static_cast<int32_t>(textures.size())) {
result->SetOcclusionTexture(textures[material.occlusion_texture()]);
}
return result;
}
PhysicallyBasedMaterial::~PhysicallyBasedMaterial() = default;
void PhysicallyBasedMaterial::SetAlbedo(Color albedo) {
albedo_ = albedo;
}
void PhysicallyBasedMaterial::SetRoughness(Scalar roughness) {
roughness_ = roughness;
}
void PhysicallyBasedMaterial::SetMetallic(Scalar metallic) {
metallic_ = metallic;
}
void PhysicallyBasedMaterial::SetAlbedoTexture(
std::shared_ptr<Texture> albedo_texture) {
albedo_texture_ = std::move(albedo_texture);
}
void PhysicallyBasedMaterial::SetMetallicRoughnessTexture(
std::shared_ptr<Texture> metallic_roughness_texture) {
metallic_roughness_texture_ = std::move(metallic_roughness_texture);
}
void PhysicallyBasedMaterial::SetNormalTexture(
std::shared_ptr<Texture> normal_texture) {
normal_texture_ = std::move(normal_texture);
}
void PhysicallyBasedMaterial::SetOcclusionTexture(
std::shared_ptr<Texture> occlusion_texture) {
occlusion_texture_ = std::move(occlusion_texture);
}
void PhysicallyBasedMaterial::SetEnvironmentMap(
std::shared_ptr<Texture> environment_map) {
environment_map_ = std::move(environment_map);
}
// |Material|
MaterialType PhysicallyBasedMaterial::GetMaterialType() const {
// TODO(bdero): Replace this once a PBR shader has landed.
return MaterialType::kUnlit;
}
// |Material|
void PhysicallyBasedMaterial::BindToCommand(const SceneContext& scene_context,
HostBuffer& buffer,
RenderPass& pass) const {}
} // namespace scene
} // namespace impeller
| engine/impeller/scene/material.cc/0 | {
"file_path": "engine/impeller/scene/material.cc",
"repo_id": "engine",
"token_count": 2574
} | 241 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
uniform FragInfo {
vec4 color;
float vertex_color_weight;
}
frag_info;
uniform sampler2D base_color_texture;
in vec3 v_position;
in mat3 v_tangent_space;
in vec2 v_texture_coords;
in vec4 v_color;
out vec4 frag_color;
void main() {
vec4 vertex_color = mix(vec4(1), v_color, frag_info.vertex_color_weight);
frag_color = texture(base_color_texture, v_texture_coords) * vertex_color *
frag_info.color;
}
| engine/impeller/scene/shaders/unlit.frag/0 | {
"file_path": "engine/impeller/scene/shaders/unlit.frag",
"repo_id": "engine",
"token_count": 219
} | 242 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/shader_archive/shader_archive_writer.h"
#include <array>
#include <filesystem>
#include <optional>
#include "impeller/shader_archive/shader_archive_flatbuffers.h"
namespace impeller {
ShaderArchiveWriter::ShaderArchiveWriter() = default;
ShaderArchiveWriter::~ShaderArchiveWriter() = default;
std::optional<ArchiveShaderType> InferShaderTypefromFileExtension(
const std::filesystem::path& path) {
if (path == ".vert") {
return ArchiveShaderType::kVertex;
} else if (path == ".frag") {
return ArchiveShaderType::kFragment;
} else if (path == ".comp") {
return ArchiveShaderType::kCompute;
}
return std::nullopt;
}
bool ShaderArchiveWriter::AddShaderAtPath(const std::string& std_path) {
std::filesystem::path path(std_path);
if (path.stem().empty()) {
FML_LOG(ERROR) << "File path stem was empty for " << path;
return false;
}
if (path.extension() != ".gles" && path.extension() != ".vkspv") {
FML_LOG(ERROR) << "File path doesn't have a known shader extension "
<< path;
return false;
}
// Get rid of .gles
path = path.replace_extension();
auto shader_type = InferShaderTypefromFileExtension(path.extension());
if (!shader_type.has_value()) {
FML_LOG(ERROR) << "Could not infer shader type from file extension: "
<< path.extension().string();
return false;
}
// Get rid of the shader type extension (.vert, .frag, etc..).
path = path.replace_extension();
const auto shader_name = path.stem().string();
if (shader_name.empty()) {
FML_LOG(ERROR) << "Shader name was empty.";
return false;
}
auto file_mapping = fml::FileMapping::CreateReadOnly(std_path);
if (!file_mapping) {
FML_LOG(ERROR) << "File doesn't exist at path: " << path;
return false;
}
return AddShader(shader_type.value(), shader_name, std::move(file_mapping));
}
bool ShaderArchiveWriter::AddShader(ArchiveShaderType type,
std::string name,
std::shared_ptr<fml::Mapping> mapping) {
if (name.empty() || !mapping || mapping->GetMapping() == nullptr) {
return false;
}
shader_descriptions_.emplace_back(
ShaderDescription{type, std::move(name), std::move(mapping)});
return true;
}
constexpr fb::Stage ToStage(ArchiveShaderType type) {
switch (type) {
case ArchiveShaderType::kVertex:
return fb::Stage::kVertex;
case ArchiveShaderType::kFragment:
return fb::Stage::kFragment;
case ArchiveShaderType::kCompute:
return fb::Stage::kCompute;
}
FML_UNREACHABLE();
}
std::shared_ptr<fml::Mapping> ShaderArchiveWriter::CreateMapping() const {
fb::ShaderArchiveT shader_archive;
for (const auto& shader_description : shader_descriptions_) {
auto mapping = shader_description.mapping;
if (!mapping) {
return nullptr;
}
auto desc = std::make_unique<fb::ShaderBlobT>();
desc->name = shader_description.name;
desc->stage = ToStage(shader_description.type);
desc->mapping = {mapping->GetMapping(),
mapping->GetMapping() + mapping->GetSize()};
shader_archive.items.emplace_back(std::move(desc));
}
auto builder = std::make_shared<flatbuffers::FlatBufferBuilder>();
builder->Finish(fb::ShaderArchive::Pack(*builder.get(), &shader_archive),
fb::ShaderArchiveIdentifier());
return std::make_shared<fml::NonOwnedMapping>(builder->GetBufferPointer(),
builder->GetSize(),
[builder](auto, auto) {});
}
} // namespace impeller
| engine/impeller/shader_archive/shader_archive_writer.cc/0 | {
"file_path": "engine/impeller/shader_archive/shader_archive_writer.cc",
"repo_id": "engine",
"token_count": 1503
} | 243 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/toolkit/android/hardware_buffer.h"
#include "impeller/base/validation.h"
namespace impeller::android {
static AHardwareBuffer_Format ToAHardwareBufferFormat(
HardwareBufferFormat format) {
switch (format) {
case HardwareBufferFormat::kR8G8B8A8UNormInt:
return AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM;
}
FML_UNREACHABLE();
}
static AHardwareBuffer_Desc ToAHardwareBufferDesc(
const HardwareBufferDescriptor& desc) {
AHardwareBuffer_Desc ahb_desc = {};
ahb_desc.width = desc.size.width;
ahb_desc.height = desc.size.height;
ahb_desc.format = ToAHardwareBufferFormat(desc.format);
ahb_desc.layers = 1u;
if (desc.usage & static_cast<HardwareBufferUsage>(
HardwareBufferUsageFlags::kFrameBufferAttachment)) {
ahb_desc.usage |= AHARDWAREBUFFER_USAGE_GPU_FRAMEBUFFER;
}
if (desc.usage & static_cast<HardwareBufferUsage>(
HardwareBufferUsageFlags::kCompositorOverlay)) {
ahb_desc.usage |= AHARDWAREBUFFER_USAGE_COMPOSER_OVERLAY;
}
if (desc.usage & static_cast<HardwareBufferUsage>(
HardwareBufferUsageFlags::kSampledImage)) {
ahb_desc.usage |= AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE;
}
return ahb_desc;
}
bool HardwareBufferDescriptor::IsAllocatable() const {
const auto desc = ToAHardwareBufferDesc(*this);
return GetProcTable().AHardwareBuffer_isSupported(&desc) != 0u;
}
HardwareBuffer::HardwareBuffer(HardwareBufferDescriptor descriptor)
: descriptor_(descriptor),
android_descriptor_(ToAHardwareBufferDesc(descriptor_)) {
if (!descriptor_.IsAllocatable()) {
VALIDATION_LOG << "The hardware buffer descriptor is not allocatable.";
return;
}
const auto& proc_table = GetProcTable();
AHardwareBuffer* buffer = nullptr;
if (auto result =
proc_table.AHardwareBuffer_allocate(&android_descriptor_, &buffer);
result != 0 || buffer == nullptr) {
VALIDATION_LOG << "Could not allocate hardware buffer. Error: " << result;
return;
}
buffer_.reset(buffer);
is_valid_ = true;
}
HardwareBuffer::~HardwareBuffer() = default;
bool HardwareBuffer::IsValid() const {
return is_valid_;
}
AHardwareBuffer* HardwareBuffer::GetHandle() const {
return buffer_.get();
}
HardwareBufferDescriptor HardwareBufferDescriptor::MakeForSwapchainImage(
const ISize& size) {
HardwareBufferDescriptor desc;
desc.format = HardwareBufferFormat::kR8G8B8A8UNormInt;
// Zero sized hardware buffers cannot be allocated.
desc.size = size.Max(ISize{1u, 1u});
desc.usage =
static_cast<HardwareBufferUsage>(
HardwareBufferUsageFlags::kFrameBufferAttachment) |
static_cast<HardwareBufferUsage>(
HardwareBufferUsageFlags::kCompositorOverlay) |
static_cast<HardwareBufferUsage>(HardwareBufferUsageFlags::kSampledImage);
return desc;
}
const HardwareBufferDescriptor& HardwareBuffer::GetDescriptor() const {
return descriptor_;
}
const AHardwareBuffer_Desc& HardwareBuffer::GetAndroidDescriptor() const {
return android_descriptor_;
}
bool HardwareBuffer::IsAvailableOnPlatform() {
return GetProcTable().IsValid() && GetProcTable().AHardwareBuffer_isSupported;
}
std::optional<uint64_t> HardwareBuffer::GetSystemUniqueID() const {
return GetSystemUniqueID(GetHandle());
}
std::optional<uint64_t> HardwareBuffer::GetSystemUniqueID(
AHardwareBuffer* buffer) {
if (!GetProcTable().AHardwareBuffer_getId) {
return false;
}
uint64_t out_id = 0u;
if (GetProcTable().AHardwareBuffer_getId(buffer, &out_id) != 0) {
return std::nullopt;
}
return out_id;
}
std::optional<AHardwareBuffer_Desc> HardwareBuffer::Describe(
AHardwareBuffer* buffer) {
if (!buffer || !GetProcTable().AHardwareBuffer_describe) {
return std::nullopt;
}
AHardwareBuffer_Desc desc = {};
GetProcTable().AHardwareBuffer_describe(buffer, &desc);
return desc;
}
} // namespace impeller::android
| engine/impeller/toolkit/android/hardware_buffer.cc/0 | {
"file_path": "engine/impeller/toolkit/android/hardware_buffer.cc",
"repo_id": "engine",
"token_count": 1441
} | 244 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/toolkit/egl/display.h"
#include <vector>
#include "impeller/toolkit/egl/context.h"
#include "impeller/toolkit/egl/surface.h"
namespace impeller {
namespace egl {
Display::Display() {
EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
if (::eglInitialize(display, nullptr, nullptr) != EGL_TRUE) {
IMPELLER_LOG_EGL_ERROR;
return;
}
display_ = display;
}
Display::~Display() {
if (display_ != EGL_NO_DISPLAY) {
if (::eglTerminate(display_) != EGL_TRUE) {
IMPELLER_LOG_EGL_ERROR;
}
}
}
bool Display::IsValid() const {
return display_ != EGL_NO_DISPLAY;
}
std::unique_ptr<Context> Display::CreateContext(const Config& config,
const Context* share_context) {
const auto& desc = config.GetDescriptor();
std::vector<EGLint> attributes;
switch (desc.api) {
case API::kOpenGL:
break;
case API::kOpenGLES2:
attributes.push_back(EGL_CONTEXT_CLIENT_VERSION);
attributes.push_back(2);
break;
case API::kOpenGLES3:
attributes.push_back(EGL_CONTEXT_CLIENT_VERSION);
attributes.push_back(3);
break;
}
// Termination sentinel must be present.
attributes.push_back(EGL_NONE);
auto context = ::eglCreateContext(
display_, // display
config.GetHandle(), // config
share_context != nullptr ? share_context->GetHandle() : nullptr, // share
attributes.data() // attributes
);
if (context == EGL_NO_CONTEXT) {
IMPELLER_LOG_EGL_ERROR;
return nullptr;
}
return std::make_unique<Context>(display_, context);
}
std::unique_ptr<Config> Display::ChooseConfig(ConfigDescriptor config) const {
if (!display_) {
return nullptr;
}
std::vector<EGLint> attributes;
{
attributes.push_back(EGL_RENDERABLE_TYPE);
switch (config.api) {
case API::kOpenGL:
attributes.push_back(EGL_OPENGL_BIT);
break;
case API::kOpenGLES2:
attributes.push_back(EGL_OPENGL_ES2_BIT);
break;
case API::kOpenGLES3:
attributes.push_back(EGL_OPENGL_ES3_BIT);
break;
}
}
{
attributes.push_back(EGL_SURFACE_TYPE);
switch (config.surface_type) {
case SurfaceType::kWindow:
attributes.push_back(EGL_WINDOW_BIT);
break;
case SurfaceType::kPBuffer:
attributes.push_back(EGL_PBUFFER_BIT);
break;
}
}
{
switch (config.color_format) {
case ColorFormat::kRGBA8888:
attributes.push_back(EGL_RED_SIZE);
attributes.push_back(8);
attributes.push_back(EGL_GREEN_SIZE);
attributes.push_back(8);
attributes.push_back(EGL_BLUE_SIZE);
attributes.push_back(8);
attributes.push_back(EGL_ALPHA_SIZE);
attributes.push_back(8);
break;
case ColorFormat::kRGB565:
attributes.push_back(EGL_RED_SIZE);
attributes.push_back(5);
attributes.push_back(EGL_GREEN_SIZE);
attributes.push_back(6);
attributes.push_back(EGL_BLUE_SIZE);
attributes.push_back(5);
break;
}
}
{
attributes.push_back(EGL_DEPTH_SIZE);
attributes.push_back(static_cast<EGLint>(config.depth_bits));
}
{
attributes.push_back(EGL_STENCIL_SIZE);
attributes.push_back(static_cast<EGLint>(config.stencil_bits));
}
{
const auto sample_count = static_cast<EGLint>(config.samples);
if (sample_count > 1) {
attributes.push_back(EGL_SAMPLE_BUFFERS);
attributes.push_back(1);
attributes.push_back(EGL_SAMPLES);
attributes.push_back(sample_count);
}
}
// termination sentinel must be present.
attributes.push_back(EGL_NONE);
EGLConfig config_out = nullptr;
EGLint config_count_out = 0;
if (::eglChooseConfig(display_, // display
attributes.data(), // attributes (null terminated)
&config_out, // matched configs
1, // configs array size
&config_count_out // match configs count
) != EGL_TRUE) {
IMPELLER_LOG_EGL_ERROR;
return nullptr;
}
if (config_count_out != 1u) {
IMPELLER_LOG_EGL_ERROR;
return nullptr;
}
return std::make_unique<Config>(config, config_out);
}
std::unique_ptr<Surface> Display::CreateWindowSurface(
const Config& config,
EGLNativeWindowType window) {
const EGLint attribs[] = {EGL_NONE};
auto surface = ::eglCreateWindowSurface(display_, // display
config.GetHandle(), // config
window, // window
attribs // attrib_list
);
if (surface == EGL_NO_SURFACE) {
IMPELLER_LOG_EGL_ERROR;
return nullptr;
}
return std::make_unique<Surface>(display_, surface);
}
std::unique_ptr<Surface> Display::CreatePixelBufferSurface(const Config& config,
size_t width,
size_t height) {
// clang-format off
const EGLint attribs[] = {
EGL_WIDTH, static_cast<EGLint>(width),
EGL_HEIGHT, static_cast<EGLint>(height),
EGL_NONE
};
// clang-format on
auto surface = ::eglCreatePbufferSurface(display_, // display
config.GetHandle(), // config
attribs // attrib_list
);
if (surface == EGL_NO_SURFACE) {
IMPELLER_LOG_EGL_ERROR;
return nullptr;
}
return std::make_unique<Surface>(display_, surface);
}
} // namespace egl
} // namespace impeller
| engine/impeller/toolkit/egl/display.cc/0 | {
"file_path": "engine/impeller/toolkit/egl/display.cc",
"repo_id": "engine",
"token_count": 2804
} | 245 |
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import("//build/compiled_action.gni")
import("//flutter/common/config.gni")
import("//flutter/testing/testing.gni")
declare_args() {
# Path to the Mali offline compiler tool 'malioc'.
impeller_malioc_path = ""
impeller_malioc_core_filter = [
"Mali-G78",
"Mali-T880",
]
}
if (impeller_malioc_path != "") {
_core_list_file = "$root_build_dir/mali_core_list.json"
exec_script("//flutter/impeller/tools/malioc_cores.py",
[
"--malioc",
rebase_path(impeller_malioc_path, root_build_dir),
"--output",
rebase_path(_core_list_file),
])
_impeller_malioc_cores = read_file(_core_list_file, "json")
}
template("malioc_analyze_shaders") {
if (impeller_malioc_path == "") {
group(target_name) {
not_needed(invoker, "*")
}
} else {
target_deps = []
foreach(core, _impeller_malioc_cores) {
foreach(filter_core, impeller_malioc_core_filter) {
if (core.core == filter_core) {
foreach(source, invoker.shaders) {
# Should be "gles" or "vkspv"
backend_ext = get_path_info(source, "extension")
assert(
backend_ext == "gles" || backend_ext == "vkspv",
"Shader for unsupported backend passed to malioc: {{source}}")
shader_file_name = get_path_info(source, "name")
analysis_target =
"${target_name}_${shader_file_name}_${core.core}_malioc"
if ((backend_ext == "gles" &&
defined(invoker.gles_language_version) &&
core.opengles_max_version < invoker.gles_language_version) ||
(backend_ext == "vkspv" &&
defined(invoker.vulkan_language_version) &&
core.vulkan_max_version < invoker.vulkan_language_version)) {
group(analysis_target) {
not_needed(invoker, "*")
}
} else {
target_deps += [ ":$analysis_target" ]
action(analysis_target) {
forward_variables_from(invoker,
"*",
[
"args",
"depfile",
"inputs",
"outputs",
"pool",
"script",
])
script = "//build/gn_run_malioc.py"
pool = "//flutter/impeller/tools:malioc_pool"
# Nest all malioc output under its own subdirectory of root_gen_dir
# so that it's easier to diff it against the state before any changes.
subdir = rebase_path(target_gen_dir, root_gen_dir)
output_file = "$root_gen_dir/malioc/$subdir/${shader_file_name}.${backend_ext}.${core.core}.json"
outputs = [ output_file ]
# Determine the kind of the shader from the file name
name = get_path_info(source, "name")
shader_kind_ext = get_path_info(name, "extension")
if (shader_kind_ext == "comp") {
shader_kind_flag = "--compute"
} else if (shader_kind_ext == "frag") {
shader_kind_flag = "--fragment"
} else if (shader_kind_ext == "geom") {
shader_kind_flag = "--geometry"
} else if (shader_kind_ext == "tesc") {
shader_kind_flag = "--tessellation_control"
} else if (shader_kind_ext == "tese") {
shader_kind_flag = "--tessellation_evaluation"
} else if (shader_kind_ext == "vert") {
shader_kind_flag = "--vertex"
} else {
assert(false, "Unknown shader kind: {{source}}")
}
args = [
rebase_path(impeller_malioc_path, root_build_dir),
rebase_path(output_file),
"--format",
"json",
shader_kind_flag,
"--core",
core.core,
]
if (backend_ext == "vkspv") {
args += [ "--vulkan" ]
}
args += [ rebase_path(source) ]
}
}
}
}
}
}
group(target_name) {
deps = target_deps
}
}
}
| engine/impeller/tools/malioc.gni/0 | {
"file_path": "engine/impeller/tools/malioc.gni",
"repo_id": "engine",
"token_count": 2693
} | 246 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/typographer/backends/stb/glyph_atlas_context_stb.h"
namespace impeller {
BitmapSTB::BitmapSTB() = default;
BitmapSTB::~BitmapSTB() = default;
BitmapSTB::BitmapSTB(size_t width, size_t height, size_t bytes_per_pixel)
: width_(width),
height_(height),
bytes_per_pixel_(bytes_per_pixel),
pixels_(std::vector<uint8_t>(width * height * bytes_per_pixel, 0)) {}
uint8_t* BitmapSTB::GetPixels() {
return pixels_.data();
}
uint8_t* BitmapSTB::GetPixelAddress(TPoint<size_t> coords) {
FML_DCHECK(coords.x < width_);
FML_DCHECK(coords.x < height_);
return &pixels_.data()[(coords.x + width_ * coords.y) * bytes_per_pixel_];
}
size_t BitmapSTB::GetRowBytes() const {
return width_ * bytes_per_pixel_;
}
size_t BitmapSTB::GetWidth() const {
return width_;
}
size_t BitmapSTB::GetHeight() const {
return height_;
}
size_t BitmapSTB::GetSize() const {
return width_ * height_ * bytes_per_pixel_;
}
GlyphAtlasContextSTB::GlyphAtlasContextSTB() = default;
GlyphAtlasContextSTB::~GlyphAtlasContextSTB() = default;
std::shared_ptr<BitmapSTB> GlyphAtlasContextSTB::GetBitmap() const {
return bitmap_;
}
void GlyphAtlasContextSTB::UpdateBitmap(std::shared_ptr<BitmapSTB> bitmap) {
bitmap_ = std::move(bitmap);
}
} // namespace impeller
| engine/impeller/typographer/backends/stb/glyph_atlas_context_stb.cc/0 | {
"file_path": "engine/impeller/typographer/backends/stb/glyph_atlas_context_stb.cc",
"repo_id": "engine",
"token_count": 571
} | 247 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/typographer/lazy_glyph_atlas.h"
#include "fml/logging.h"
#include "impeller/base/validation.h"
#include "impeller/typographer/glyph_atlas.h"
#include "impeller/typographer/typographer_context.h"
#include <memory>
#include <utility>
namespace impeller {
static const std::shared_ptr<GlyphAtlas> kNullGlyphAtlas = nullptr;
LazyGlyphAtlas::LazyGlyphAtlas(
std::shared_ptr<TypographerContext> typographer_context)
: typographer_context_(std::move(typographer_context)),
alpha_context_(typographer_context_
? typographer_context_->CreateGlyphAtlasContext()
: nullptr),
color_context_(typographer_context_
? typographer_context_->CreateGlyphAtlasContext()
: nullptr) {}
LazyGlyphAtlas::~LazyGlyphAtlas() = default;
void LazyGlyphAtlas::AddTextFrame(const TextFrame& frame, Scalar scale) {
FML_DCHECK(alpha_atlas_ == nullptr && color_atlas_ == nullptr);
if (frame.GetAtlasType() == GlyphAtlas::Type::kAlphaBitmap) {
frame.CollectUniqueFontGlyphPairs(alpha_glyph_map_, scale);
} else {
frame.CollectUniqueFontGlyphPairs(color_glyph_map_, scale);
}
}
void LazyGlyphAtlas::ResetTextFrames() {
alpha_glyph_map_.clear();
color_glyph_map_.clear();
alpha_atlas_.reset();
color_atlas_.reset();
}
const std::shared_ptr<GlyphAtlas>& LazyGlyphAtlas::CreateOrGetGlyphAtlas(
Context& context,
GlyphAtlas::Type type) const {
{
if (type == GlyphAtlas::Type::kAlphaBitmap && alpha_atlas_) {
return alpha_atlas_;
}
if (type == GlyphAtlas::Type::kColorBitmap && color_atlas_) {
return color_atlas_;
}
}
if (!typographer_context_) {
VALIDATION_LOG << "Unable to render text because a TypographerContext has "
"not been set.";
return kNullGlyphAtlas;
}
if (!typographer_context_->IsValid()) {
VALIDATION_LOG
<< "Unable to render text because the TypographerContext is invalid.";
return kNullGlyphAtlas;
}
auto& glyph_map = type == GlyphAtlas::Type::kAlphaBitmap ? alpha_glyph_map_
: color_glyph_map_;
const std::shared_ptr<GlyphAtlasContext>& atlas_context =
type == GlyphAtlas::Type::kAlphaBitmap ? alpha_context_ : color_context_;
std::shared_ptr<GlyphAtlas> atlas = typographer_context_->CreateGlyphAtlas(
context, type, atlas_context, glyph_map);
if (!atlas || !atlas->IsValid()) {
VALIDATION_LOG << "Could not create valid atlas.";
return kNullGlyphAtlas;
}
if (type == GlyphAtlas::Type::kAlphaBitmap) {
alpha_atlas_ = std::move(atlas);
return alpha_atlas_;
}
if (type == GlyphAtlas::Type::kColorBitmap) {
color_atlas_ = std::move(atlas);
return color_atlas_;
}
FML_UNREACHABLE();
}
} // namespace impeller
| engine/impeller/typographer/lazy_glyph_atlas.cc/0 | {
"file_path": "engine/impeller/typographer/lazy_glyph_atlas.cc",
"repo_id": "engine",
"token_count": 1277
} | 248 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_LIB_GPU_COMMAND_BUFFER_H_
#define FLUTTER_LIB_GPU_COMMAND_BUFFER_H_
#include "flutter/lib/gpu/context.h"
#include "flutter/lib/gpu/export.h"
#include "flutter/lib/ui/dart_wrapper.h"
#include "impeller/renderer/command_buffer.h"
namespace flutter {
namespace gpu {
class CommandBuffer : public RefCountedDartWrappable<CommandBuffer> {
DEFINE_WRAPPERTYPEINFO();
FML_FRIEND_MAKE_REF_COUNTED(CommandBuffer);
public:
CommandBuffer(std::shared_ptr<impeller::Context> context,
std::shared_ptr<impeller::CommandBuffer> command_buffer);
std::shared_ptr<impeller::CommandBuffer> GetCommandBuffer();
void AddRenderPass(std::shared_ptr<impeller::RenderPass> render_pass);
bool Submit();
bool Submit(
const impeller::CommandBuffer::CompletionCallback& completion_callback);
~CommandBuffer() override;
private:
std::shared_ptr<impeller::Context> context_;
std::shared_ptr<impeller::CommandBuffer> command_buffer_;
std::vector<std::shared_ptr<impeller::RenderPass>> encodables_;
FML_DISALLOW_COPY_AND_ASSIGN(CommandBuffer);
};
} // namespace gpu
} // namespace flutter
//----------------------------------------------------------------------------
/// Exports
///
extern "C" {
FLUTTER_GPU_EXPORT
extern bool InternalFlutterGpu_CommandBuffer_Initialize(
Dart_Handle wrapper,
flutter::gpu::Context* contextWrapper);
FLUTTER_GPU_EXPORT
extern Dart_Handle InternalFlutterGpu_CommandBuffer_Submit(
flutter::gpu::CommandBuffer* wrapper,
Dart_Handle completion_callback);
} // extern "C"
#endif // FLUTTER_LIB_GPU_COMMAND_BUFFER_H_
| engine/lib/gpu/command_buffer.h/0 | {
"file_path": "engine/lib/gpu/command_buffer.h",
"repo_id": "engine",
"token_count": 606
} | 249 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.