text
stringlengths 6
13.6M
| id
stringlengths 13
176
| metadata
dict | __index_level_0__
int64 0
1.69k
|
---|---|---|---|
// 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_TESTING_DL_TEST_SURFACE_GL_H_
#define FLUTTER_DISPLAY_LIST_TESTING_DL_TEST_SURFACE_GL_H_
#include "flutter/display_list/testing/dl_test_surface_provider.h"
#include "flutter/testing/test_gl_surface.h"
namespace flutter {
namespace testing {
class DlOpenGLSurfaceProvider : public DlSurfaceProvider {
public:
DlOpenGLSurfaceProvider() : DlSurfaceProvider() {}
virtual ~DlOpenGLSurfaceProvider() = default;
bool InitializeSurface(size_t width,
size_t height,
PixelFormat format) override;
std::shared_ptr<DlSurfaceInstance> GetPrimarySurface() const override;
std::shared_ptr<DlSurfaceInstance> MakeOffscreenSurface(
size_t width,
size_t height,
PixelFormat format) const override;
const std::string backend_name() const override { return "OpenGL"; }
BackendType backend_type() const override { return kOpenGlBackend; }
bool supports(PixelFormat format) const override {
return format == kN32PremulPixelFormat;
}
private:
std::shared_ptr<DlSurfaceInstance> primary_;
std::unique_ptr<TestGLSurface> gl_surface_;
};
} // namespace testing
} // namespace flutter
#endif // FLUTTER_DISPLAY_LIST_TESTING_DL_TEST_SURFACE_GL_H_
| engine/display_list/testing/dl_test_surface_gl.h/0 | {
"file_path": "engine/display_list/testing/dl_test_surface_gl.h",
"repo_id": "engine",
"token_count": 521
} | 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.
#include "flutter/flow/testing/diff_context_test.h"
namespace flutter {
namespace testing {
TEST_F(DiffContextTest, ClipAlignment) {
MockLayerTree t1;
t1.root()->Add(CreateDisplayListLayer(
CreateDisplayList(SkRect::MakeLTRB(30, 30, 50, 50))));
auto damage = DiffLayerTree(t1, MockLayerTree(), SkIRect::MakeEmpty(), 0, 0);
EXPECT_EQ(damage.frame_damage, SkIRect::MakeLTRB(30, 30, 50, 50));
EXPECT_EQ(damage.buffer_damage, SkIRect::MakeLTRB(30, 30, 50, 50));
damage = DiffLayerTree(t1, MockLayerTree(), SkIRect::MakeEmpty(), 1, 1);
EXPECT_EQ(damage.frame_damage, SkIRect::MakeLTRB(30, 30, 50, 50));
EXPECT_EQ(damage.buffer_damage, SkIRect::MakeLTRB(30, 30, 50, 50));
damage = DiffLayerTree(t1, MockLayerTree(), SkIRect::MakeEmpty(), 8, 1);
EXPECT_EQ(damage.frame_damage, SkIRect::MakeLTRB(24, 30, 56, 50));
EXPECT_EQ(damage.buffer_damage, SkIRect::MakeLTRB(24, 30, 56, 50));
damage = DiffLayerTree(t1, MockLayerTree(), SkIRect::MakeEmpty(), 1, 8);
EXPECT_EQ(damage.frame_damage, SkIRect::MakeLTRB(30, 24, 50, 56));
EXPECT_EQ(damage.buffer_damage, SkIRect::MakeLTRB(30, 24, 50, 56));
damage = DiffLayerTree(t1, MockLayerTree(), SkIRect::MakeEmpty(), 16, 16);
EXPECT_EQ(damage.frame_damage, SkIRect::MakeLTRB(16, 16, 64, 64));
EXPECT_EQ(damage.buffer_damage, SkIRect::MakeLTRB(16, 16, 64, 64));
}
} // namespace testing
} // namespace flutter
| engine/flow/diff_context_unittests.cc/0 | {
"file_path": "engine/flow/diff_context_unittests.cc",
"repo_id": "engine",
"token_count": 596
} | 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/flow/layers/cacheable_layer.h"
namespace flutter {
AutoCache::AutoCache(RasterCacheItem* raster_cache_item,
PrerollContext* context,
const SkMatrix& matrix)
: raster_cache_item_(raster_cache_item),
context_(context),
matrix_(matrix) {
if (IsCacheEnabled()) {
raster_cache_item->PrerollSetup(context, matrix);
}
}
bool AutoCache::IsCacheEnabled() {
return raster_cache_item_ && context_ && context_->raster_cache;
}
AutoCache::~AutoCache() {
if (IsCacheEnabled()) {
raster_cache_item_->PrerollFinalize(context_, matrix_);
}
}
CacheableContainerLayer::CacheableContainerLayer(int layer_cached_threshold,
bool can_cache_children) {
layer_raster_cache_item_ = LayerRasterCacheItem::Make(
this, layer_cached_threshold, can_cache_children);
}
} // namespace flutter
| engine/flow/layers/cacheable_layer.cc/0 | {
"file_path": "engine/flow/layers/cacheable_layer.cc",
"repo_id": "engine",
"token_count": 428
} | 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.
#include "flutter/flow/layers/container_layer.h"
#include <optional>
namespace flutter {
ContainerLayer::ContainerLayer() : child_paint_bounds_(SkRect::MakeEmpty()) {}
void ContainerLayer::Diff(DiffContext* context, const Layer* old_layer) {
auto old_container = static_cast<const ContainerLayer*>(old_layer);
DiffContext::AutoSubtreeRestore subtree(context);
DiffChildren(context, old_container);
context->SetLayerPaintRegion(this, context->CurrentSubtreeRegion());
}
void ContainerLayer::PreservePaintRegion(DiffContext* context) {
Layer::PreservePaintRegion(context);
for (auto& layer : layers_) {
layer->PreservePaintRegion(context);
}
}
void ContainerLayer::DiffChildren(DiffContext* context,
const ContainerLayer* old_layer) {
if (context->IsSubtreeDirty()) {
for (auto& layer : layers_) {
layer->Diff(context, nullptr);
}
return;
}
FML_DCHECK(old_layer);
const auto& prev_layers = old_layer->layers_;
// first mismatched element
int new_children_top = 0;
int old_children_top = 0;
// last mismatched element
int new_children_bottom = layers_.size() - 1;
int old_children_bottom = prev_layers.size() - 1;
while ((old_children_top <= old_children_bottom) &&
(new_children_top <= new_children_bottom)) {
if (!layers_[new_children_top]->IsReplacing(
context, prev_layers[old_children_top].get())) {
break;
}
++new_children_top;
++old_children_top;
}
while ((old_children_top <= old_children_bottom) &&
(new_children_top <= new_children_bottom)) {
if (!layers_[new_children_bottom]->IsReplacing(
context, prev_layers[old_children_bottom].get())) {
break;
}
--new_children_bottom;
--old_children_bottom;
}
// old layers that don't match
for (int i = old_children_top; i <= old_children_bottom; ++i) {
auto layer = prev_layers[i];
context->AddDamage(context->GetOldLayerPaintRegion(layer.get()));
}
for (int i = 0; i < static_cast<int>(layers_.size()); ++i) {
if (i < new_children_top || i > new_children_bottom) {
int i_prev =
i < new_children_top ? i : prev_layers.size() - (layers_.size() - i);
auto layer = layers_[i];
auto prev_layer = prev_layers[i_prev];
auto paint_region = context->GetOldLayerPaintRegion(prev_layer.get());
if (layer == prev_layer && !paint_region.has_readback() &&
!paint_region.has_texture()) {
// for retained layers, stop processing the subtree and add existing
// region; We know current subtree is not dirty (every ancestor up to
// here matches) so the retained subtree will render identically to
// previous frame; We can only do this if there is no readback in the
// subtree. Layers that do readback must be able to register readback
// inside Diff
context->AddExistingPaintRegion(paint_region);
// While we don't need to diff retained layers, we still need to
// associate their paint region with current layer tree so that we can
// retrieve it in next frame diff
layer->PreservePaintRegion(context);
} else {
layer->Diff(context, prev_layer.get());
}
} else {
DiffContext::AutoSubtreeRestore subtree(context);
context->MarkSubtreeDirty();
auto layer = layers_[i];
layer->Diff(context, nullptr);
}
}
}
void ContainerLayer::Add(std::shared_ptr<Layer> layer) {
layers_.emplace_back(std::move(layer));
}
void ContainerLayer::Preroll(PrerollContext* context) {
SkRect child_paint_bounds = SkRect::MakeEmpty();
PrerollChildren(context, &child_paint_bounds);
set_paint_bounds(child_paint_bounds);
}
void ContainerLayer::Paint(PaintContext& context) const {
FML_DCHECK(needs_painting(context));
PaintChildren(context);
}
static bool safe_intersection_test(const SkRect* rect1, const SkRect& rect2) {
if (rect1->isEmpty() || rect2.isEmpty()) {
return false;
}
return rect1->intersects(rect2);
}
void ContainerLayer::PrerollChildren(PrerollContext* context,
SkRect* child_paint_bounds) {
// Platform views have no children, so context->has_platform_view should
// always be false.
FML_DCHECK(!context->has_platform_view);
FML_DCHECK(!context->has_texture_layer);
bool child_has_platform_view = false;
bool child_has_texture_layer = false;
bool all_renderable_state_flags = LayerStateStack::kCallerCanApplyAnything;
for (auto& layer : layers_) {
// Reset context->has_platform_view and context->has_texture_layer to false
// so that layers aren't treated as if they have a platform view or texture
// layer based on one being previously found in a sibling tree.
context->has_platform_view = false;
context->has_texture_layer = false;
// Initialize the renderable state flags to false to force the layer to
// opt-in to applying state attributes during its |Preroll|
context->renderable_state_flags = 0;
layer->Preroll(context);
all_renderable_state_flags &= context->renderable_state_flags;
if (safe_intersection_test(child_paint_bounds, layer->paint_bounds())) {
// This will allow inheritance by a linear sequence of non-overlapping
// children, but will fail with a grid or other arbitrary 2D layout.
// See https://github.com/flutter/flutter/issues/93899
all_renderable_state_flags = 0;
}
child_paint_bounds->join(layer->paint_bounds());
child_has_platform_view =
child_has_platform_view || context->has_platform_view;
child_has_texture_layer =
child_has_texture_layer || context->has_texture_layer;
}
context->has_platform_view = child_has_platform_view;
context->has_texture_layer = child_has_texture_layer;
context->renderable_state_flags = all_renderable_state_flags;
set_subtree_has_platform_view(child_has_platform_view);
set_children_renderable_state_flags(all_renderable_state_flags);
set_child_paint_bounds(*child_paint_bounds);
}
void ContainerLayer::PaintChildren(PaintContext& context) const {
// We can no longer call FML_DCHECK here on the needs_painting(context)
// condition as that test is only valid for the PaintContext that
// is initially handed to a layer's Paint() method. By the time the
// layer calls PaintChildren(), though, it may have modified the
// PaintContext so the test doesn't work in this "context".
// Apply any outstanding state that the children cannot individually
// and collectively handle.
auto restore = context.state_stack.applyState(
child_paint_bounds(), children_renderable_state_flags());
// Intentionally not tracing here as there should be no self-time
// and the trace event on this common function has a small overhead.
for (auto& layer : layers_) {
if (layer->needs_painting(context)) {
layer->Paint(context);
}
}
}
} // namespace flutter
| engine/flow/layers/container_layer.cc/0 | {
"file_path": "engine/flow/layers/container_layer.cc",
"repo_id": "engine",
"token_count": 2500
} | 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_FLOW_LAYERS_LAYER_STATE_STACK_H_
#define FLUTTER_FLOW_LAYERS_LAYER_STATE_STACK_H_
#include "flutter/display_list/dl_canvas.h"
#include "flutter/flow/embedded_views.h"
#include "flutter/flow/paint_utils.h"
namespace flutter {
/// The LayerStateStack manages the inherited state passed down between
/// |Layer| objects in a |LayerTree| during |Preroll| and |Paint|.
///
/// More specifically, it manages the clip and transform state during
/// recursive rendering and will hold and lazily apply opacity, ImageFilter
/// and ColorFilter attributes to recursive content. This is not a truly
/// general state management mechnanism as it makes assumptions that code
/// will be applying the attributes to rendered content that happens in
/// recursive calls. The automatic save/restore mechanisms only work in
/// a context where C++ auto-destruct calls will engage the restore at
/// the end of a code block and that any applied attributes will only
/// be applied to the content rendered inside that block. These restrictions
/// match the organization of the |LayerTree| methods precisely.
///
/// The stack can manage a single state delegate. The delegate will provide
/// tracking of the current transform and clip and will also execute
/// saveLayer calls at the appropriate time if it is a rendering delegate.
/// The delegate can be swapped out on the fly (as is typically done by
/// PlatformViewLayer when recording the state for multiple "overlay"
/// layers that occur between embedded view subtrees. The old delegate
/// will be restored to its original state before it became a delegate
/// and the new delegate will have all of the state recorded by the stack
/// replayed into it to bring it up to speed with the current rendering
/// context.
///
/// The delegate can be any one of:
/// - Preroll delegate: used during Preroll to remember the outstanding
/// state for embedded platform layers
/// - DlCanvas: used during Paint for rendering output
/// The stack will know which state needs to be conveyed to any of these
/// delegates and when is the best time to convey that state (i.e. lazy
/// saveLayer calls for example).
///
/// The rendering state attributes will be automatically applied to the
/// nested content using a |saveLayer| call at the point at which we
/// encounter rendered content (i.e. various nested layers that exist only
/// to apply new state will not trigger the |saveLayer| and the attributes
/// can accumulate until we reach actual content that is rendered.) Some
/// rendered content can avoid the |saveLayer| if it reports to the object
/// that it is able to apply all of the attributes that happen to be
/// outstanding (accumulated from parent state-modifiers). A |ContainerLayer|
/// can also monitor the attribute rendering capabilities of a list of
/// children and can ask the object to apply a protective |saveLayer| or
/// not based on the negotiated capabilities of the entire group.
///
/// Any code that is planning to modify the clip, transform, or rendering
/// attributes for its child content must start by calling the |save| method
/// which returns a MutatorContext object. The methods that modify such
/// state only exist on the MutatorContext object so it is difficult to get
/// that wrong, but the caller must make sure that the call happens within
/// a C++ code block that will define the "rendering scope" of those
/// state changes as they will be automatically restored on exit from that
/// block. Note that the layer might make similar state calls directly on
/// the canvas or builder during the Paint cycle (via saveLayer, transform,
/// or clip calls), but should avoid doing so if there is any nested content
/// that needs to track or react to those state calls.
///
/// Code that needs to render content can simply inform the parent of their
/// abilities by setting the |PrerollContext::renderable_state_flags| during
/// |Preroll| and then render with those attributes during |Paint| by
/// requesting the outstanding values of those attributes from the state_stack
/// object. Individual leaf layers can ignore this feature as the default
/// behavior during |Preroll| will have their parent |ContainerLayer| assume
/// that they cannot render any outstanding state attributes and will apply
/// the protective saveLayer on their behalf if needed. As such, this object
/// only provides "opt-in" features for leaf layers and no responsibilities
/// otherwise.
/// See |LayerStateStack::fill|
/// See |LayerStateStack::outstanding_opacity|
/// See |LayerStateStack::outstanding_color_filter|
/// See |LayerStateStack::outstanding_image_filter|
///
/// State-modifying layers should contain code similar to this pattern in both
/// their |Preroll| and |Paint| methods.
///
/// void [LayerType]::[Preroll/Paint](context) {
/// auto mutator = context.state_stack.save();
/// mutator.translate(origin.x, origin.y);
/// mutator.applyOpacity(content_bounds, opacity_value);
/// mutator.applyColorFilter(content_bounds, color_filter);
/// // or any of the mutator transform, clip or attribute methods
///
/// // Children will react to the state applied above during their
/// // Preroll/Paint methods or ContainerLayer will protect them
/// // conservatively by default.
/// [Preroll/Paint]Children(context);
///
/// // here the mutator will be auto-destructed and the state accumulated
/// // by it will be restored out of the state_stack and its associated
/// // delegates.
/// }
class LayerStateStack {
public:
LayerStateStack();
// Clears out any old delegate to make room for a new one.
void clear_delegate();
// Return the DlCanvas delegate if the state stack has such a delegate.
// The state stack will only have one delegate at a time holding either
// a DlCanvas or a preroll accumulator.
DlCanvas* canvas_delegate() { return delegate_->canvas(); }
// Clears the old delegate and sets the canvas delegate to the indicated
// DL canvas (if not nullptr). This ensures that only one delegate - either
// a DlCanvas or a preroll accumulator - is present at any one time.
void set_delegate(DlCanvas* canvas);
// Clears the old delegate and sets the state stack up to accumulate
// clip and transform information for a Preroll phase. This ensures
// that only one delegate - either a DlCanvas or a preroll accumulator -
// is present at any one time.
void set_preroll_delegate(const SkRect& cull_rect, const SkMatrix& matrix);
void set_preroll_delegate(const SkRect& cull_rect);
void set_preroll_delegate(const SkMatrix& matrix);
// Fills the supplied MatatorsStack object with the mutations recorded
// by this LayerStateStack in the order encountered.
void fill(MutatorsStack* mutators);
// Sets up a checkerboard function that will be used to checkerboard the
// contents of any saveLayer executed by the state stack.
CheckerboardFunc checkerboard_func() const { return checkerboard_func_; }
void set_checkerboard_func(CheckerboardFunc checkerboard_func) {
checkerboard_func_ = checkerboard_func;
}
class AutoRestore {
public:
~AutoRestore() {
layer_state_stack_->restore_to_count(stack_restore_count_);
}
private:
AutoRestore(LayerStateStack* stack, const SkRect& bounds, int flags)
: layer_state_stack_(stack),
stack_restore_count_(stack->stack_count()) {
if (stack->needs_save_layer(flags)) {
stack->save_layer(bounds);
}
}
friend class LayerStateStack;
LayerStateStack* layer_state_stack_;
const size_t stack_restore_count_;
FML_DISALLOW_COPY_ASSIGN_AND_MOVE(AutoRestore);
};
class MutatorContext {
public:
~MutatorContext() {
layer_state_stack_->restore_to_count(stack_restore_count_);
}
// Immediately executes a saveLayer with all accumulated state
// onto the canvas or builder to be applied at the next matching
// restore. A saveLayer is always executed by this method even if
// there are no outstanding attributes.
void saveLayer(const SkRect& bounds);
// Records the opacity for application at the next call to
// saveLayer or applyState. A saveLayer may be executed at
// this time if the opacity cannot be batched with other
// outstanding attributes.
void applyOpacity(const SkRect& bounds, SkScalar opacity);
// Records the image filter for application at the next call to
// saveLayer or applyState. A saveLayer may be executed at
// this time if the image filter cannot be batched with other
// outstanding attributes.
// (Currently only opacity is recorded for batching)
void applyImageFilter(const SkRect& bounds,
const std::shared_ptr<const DlImageFilter>& filter);
// Records the color filter for application at the next call to
// saveLayer or applyState. A saveLayer may be executed at
// this time if the color filter cannot be batched with other
// outstanding attributes.
// (Currently only opacity is recorded for batching)
void applyColorFilter(const SkRect& bounds,
const std::shared_ptr<const DlColorFilter>& filter);
// Saves the state stack and immediately executes a saveLayer
// with the indicated backdrop filter and any outstanding
// state attributes. Since the backdrop filter only applies
// to the pixels alrady on the screen when this call is made,
// the backdrop filter will only be applied to the canvas or
// builder installed at the time that this call is made, and
// subsequent canvas or builder objects that are made delegates
// will only see a saveLayer with the indicated blend_mode.
void applyBackdropFilter(const SkRect& bounds,
const std::shared_ptr<const DlImageFilter>& filter,
DlBlendMode blend_mode);
void translate(SkScalar tx, SkScalar ty);
void translate(SkPoint tp) { translate(tp.fX, tp.fY); }
void transform(const SkM44& m44);
void transform(const SkMatrix& matrix);
void integralTransform();
void clipRect(const SkRect& rect, bool is_aa);
void clipRRect(const SkRRect& rrect, bool is_aa);
void clipPath(const SkPath& path, bool is_aa);
private:
explicit MutatorContext(LayerStateStack* stack)
: layer_state_stack_(stack),
stack_restore_count_(stack->stack_count()) {}
friend class LayerStateStack;
LayerStateStack* layer_state_stack_;
const size_t stack_restore_count_;
bool save_needed_ = true;
FML_DISALLOW_COPY_ASSIGN_AND_MOVE(MutatorContext);
};
static constexpr int kCallerCanApplyOpacity = 0x1;
static constexpr int kCallerCanApplyColorFilter = 0x2;
static constexpr int kCallerCanApplyImageFilter = 0x4;
static constexpr int kCallerCanApplyAnything =
(kCallerCanApplyOpacity | kCallerCanApplyColorFilter |
kCallerCanApplyImageFilter);
// Apply the outstanding state via saveLayer if necessary,
// respecting the flags representing which potentially
// outstanding attributes the calling layer can apply
// themselves.
//
// A saveLayer may or may not be sent to the delegates depending
// on how the outstanding state intersects with the flags supplied
// by the caller.
//
// An AutoRestore instance will always be returned even if there
// was no saveLayer applied.
[[nodiscard]] inline AutoRestore applyState(const SkRect& bounds,
int can_apply_flags) {
return AutoRestore(this, bounds, can_apply_flags);
}
SkScalar outstanding_opacity() const { return outstanding_.opacity; }
std::shared_ptr<const DlColorFilter> outstanding_color_filter() const {
return outstanding_.color_filter;
}
std::shared_ptr<const DlImageFilter> outstanding_image_filter() const {
return outstanding_.image_filter;
}
// The outstanding bounds are the bounds recorded during the last
// attribute applied to this state stack. The assumption is that
// the nested calls to the state stack will each supply bounds relative
// to the content of that single attribute and the bounds of the content
// of any outstanding attributes will include the output bounds of
// applying any nested attributes. Thus, only the innermost content
// bounds received will be sufficient to apply all outstanding attributes.
SkRect outstanding_bounds() const { return outstanding_.save_layer_bounds; }
// Fill the provided paint object with any oustanding attributes and
// return a pointer to it, or return a nullptr if there were no
// outstanding attributes to paint with.
DlPaint* fill(DlPaint& paint) const { return outstanding_.fill(paint); }
// The cull_rect (not the exact clip) relative to the device pixels.
// This rectangle may be a conservative estimate of the true clip region.
SkRect device_cull_rect() const { return delegate_->device_cull_rect(); }
// The cull_rect (not the exact clip) relative to the local coordinates.
// This rectangle may be a conservative estimate of the true clip region.
SkRect local_cull_rect() const { return delegate_->local_cull_rect(); }
// The transform from the local coordinates to the device coordinates
// in the most capable 4x4 matrix representation. This matrix may be
// more information than is needed to compute bounds for a 2D rendering
// primitive, but it will accurately concatenate with other 4x4 matrices
// without losing information.
SkM44 transform_4x4() const { return delegate_->matrix_4x4(); }
// The transform from the local coordinates to the device coordinates
// in a more compact 3x3 matrix represenation that provides enough
// information to accurately transform 2D primitives into their
// resulting 2D bounds. This matrix also has enough information to
// concat with other 2D affine transforms, but does not carry enough
// information to accurately concat with fully perspective matrics.
SkMatrix transform_3x3() const { return delegate_->matrix_3x3(); }
// Tests if painting content with the current outstanding attributes
// will produce any content. This method does not check the current
// transform or clip for being singular or empty.
// See |content_culled|
bool painting_is_nop() const { return outstanding_.opacity <= 0; }
// Tests if painting content with the given bounds will produce any output.
// This method does not check the outstanding attributes to verify that
// they produce visible results.
// See |painting_is_nop|
bool content_culled(const SkRect& content_bounds) const {
return delegate_->content_culled(content_bounds);
}
// Saves the current state of the state stack and returns a
// MutatorContext which can be used to manipulate the state.
// The state stack will be restored to its current state
// when the MutatorContext object goes out of scope.
[[nodiscard]] inline MutatorContext save() { return MutatorContext(this); }
// Returns true if the state stack is in, or has returned to,
// its initial state.
bool is_empty() const { return state_stack_.empty(); }
private:
size_t stack_count() const { return state_stack_.size(); }
void restore_to_count(size_t restore_count);
void reapply_all();
void apply_last_entry() { state_stack_.back()->apply(this); }
// The push methods simply push an associated StateEntry on the stack
// and then apply it to the current canvas and builder.
// ---------------------
// void push_attributes();
void push_opacity(const SkRect& rect, SkScalar opacity);
void push_color_filter(const SkRect& bounds,
const std::shared_ptr<const DlColorFilter>& filter);
void push_image_filter(const SkRect& bounds,
const std::shared_ptr<const DlImageFilter>& filter);
void push_backdrop(const SkRect& bounds,
const std::shared_ptr<const DlImageFilter>& filter,
DlBlendMode blend_mode);
void push_translate(SkScalar tx, SkScalar ty);
void push_transform(const SkM44& matrix);
void push_transform(const SkMatrix& matrix);
void push_integral_transform();
void push_clip_rect(const SkRect& rect, bool is_aa);
void push_clip_rrect(const SkRRect& rrect, bool is_aa);
void push_clip_path(const SkPath& path, bool is_aa);
// ---------------------
// The maybe/needs_save_layer methods will determine if the indicated
// attribute can be incorporated into the outstanding attributes as is,
// or if the apply_flags are compatible with the outstanding attributes.
// If the oustanding attributes are incompatible with the new attribute
// or the apply flags, then a protective saveLayer will be executed.
// ---------------------
bool needs_save_layer(int flags) const;
void do_save();
void save_layer(const SkRect& bounds);
void maybe_save_layer_for_transform(bool needs_save);
void maybe_save_layer_for_clip(bool needs_save);
void maybe_save_layer(int apply_flags);
void maybe_save_layer(SkScalar opacity);
void maybe_save_layer(const std::shared_ptr<const DlColorFilter>& filter);
void maybe_save_layer(const std::shared_ptr<const DlImageFilter>& filter);
// ---------------------
struct RenderingAttributes {
// We need to record the last bounds we received for the last
// attribute that we recorded so that we can perform a saveLayer
// on the proper area. When an attribute is applied that cannot
// be merged with the existing attributes, it will be submitted
// with a bounds for its own source content, not the bounds for
// the content that will be included in the saveLayer that applies
// the existing outstanding attributes - thus we need to record
// the bounds that were supplied with the most recent previous
// attribute to be applied.
SkRect save_layer_bounds{0, 0, 0, 0};
SkScalar opacity = SK_Scalar1;
std::shared_ptr<const DlColorFilter> color_filter;
std::shared_ptr<const DlImageFilter> image_filter;
DlPaint* fill(DlPaint& paint,
DlBlendMode mode = DlBlendMode::kSrcOver) const;
bool operator==(const RenderingAttributes& other) const {
return save_layer_bounds == other.save_layer_bounds &&
opacity == other.opacity &&
Equals(color_filter, other.color_filter) &&
Equals(image_filter, other.image_filter);
}
};
class StateEntry {
public:
virtual ~StateEntry() = default;
virtual void apply(LayerStateStack* stack) const = 0;
virtual void reapply(LayerStateStack* stack) const { apply(stack); }
virtual void restore(LayerStateStack* stack) const {}
virtual void update_mutators(MutatorsStack* mutators_stack) const {}
protected:
StateEntry() = default;
FML_DISALLOW_COPY_ASSIGN_AND_MOVE(StateEntry);
};
friend class SaveEntry;
friend class SaveLayerEntry;
friend class BackdropFilterEntry;
friend class OpacityEntry;
friend class ImageFilterEntry;
friend class ColorFilterEntry;
friend class TranslateEntry;
friend class TransformMatrixEntry;
friend class TransformM44Entry;
friend class IntegralTransformEntry;
friend class ClipEntry;
friend class ClipRectEntry;
friend class ClipRRectEntry;
friend class ClipPathEntry;
class Delegate {
protected:
using ClipOp = DlCanvas::ClipOp;
public:
virtual ~Delegate() = default;
// Mormally when a |Paint| or |Preroll| cycle is completed, the
// delegate will have been rewound to its initial state by the
// trailing recursive actions of the paint and preroll methods.
// When a delegate is swapped out, there may be unresolved state
// that the delegate received. This method is called when the
// delegate is cleared or swapped out to inform it to rewind its
// state and finalize all outstanding save or saveLayer operations.
virtual void decommission() = 0;
virtual DlCanvas* canvas() const { return nullptr; }
virtual SkRect local_cull_rect() const = 0;
virtual SkRect device_cull_rect() const = 0;
virtual SkM44 matrix_4x4() const = 0;
virtual SkMatrix matrix_3x3() const = 0;
virtual bool content_culled(const SkRect& content_bounds) const = 0;
virtual void save() = 0;
virtual void saveLayer(const SkRect& bounds,
RenderingAttributes& attributes,
DlBlendMode blend,
const DlImageFilter* backdrop) = 0;
virtual void restore() = 0;
virtual void translate(SkScalar tx, SkScalar ty) = 0;
virtual void transform(const SkM44& m44) = 0;
virtual void transform(const SkMatrix& matrix) = 0;
virtual void integralTransform() = 0;
virtual void clipRect(const SkRect& rect, ClipOp op, bool is_aa) = 0;
virtual void clipRRect(const SkRRect& rrect, ClipOp op, bool is_aa) = 0;
virtual void clipPath(const SkPath& path, ClipOp op, bool is_aa) = 0;
};
friend class DummyDelegate;
friend class DlCanvasDelegate;
friend class PrerollDelegate;
std::vector<std::unique_ptr<StateEntry>> state_stack_;
friend class MutatorContext;
std::shared_ptr<Delegate> delegate_;
RenderingAttributes outstanding_;
CheckerboardFunc checkerboard_func_ = nullptr;
friend class SaveLayerEntry;
};
} // namespace flutter
#endif // FLUTTER_FLOW_LAYERS_LAYER_STATE_STACK_H_
| engine/flow/layers/layer_state_stack.h/0 | {
"file_path": "engine/flow/layers/layer_state_stack.h",
"repo_id": "engine",
"token_count": 6360
} | 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/flow/layers/clip_rect_layer.h"
#include "flutter/flow/layers/platform_view_layer.h"
#include "flutter/flow/layers/transform_layer.h"
#include "flutter/flow/testing/layer_test.h"
#include "flutter/flow/testing/mock_embedder.h"
#include "flutter/flow/testing/mock_layer.h"
#include "flutter/fml/macros.h"
#include "flutter/testing/mock_canvas.h"
namespace flutter {
namespace testing {
using PlatformViewLayerTest = LayerTest;
using ClipOp = DlCanvas::ClipOp;
TEST_F(PlatformViewLayerTest, NullViewEmbedderDoesntPrerollCompositeOrPaint) {
const SkPoint layer_offset = SkPoint::Make(0.0f, 0.0f);
const SkSize layer_size = SkSize::Make(8.0f, 8.0f);
const int64_t view_id = 0;
auto layer =
std::make_shared<PlatformViewLayer>(layer_offset, layer_size, view_id);
layer->Preroll(preroll_context());
EXPECT_FALSE(preroll_context()->has_platform_view);
EXPECT_EQ(layer->paint_bounds(),
SkRect::MakeSize(layer_size)
.makeOffset(layer_offset.fX, layer_offset.fY));
EXPECT_TRUE(layer->needs_painting(paint_context()));
EXPECT_FALSE(layer->subtree_has_platform_view());
layer->Paint(paint_context());
EXPECT_EQ(paint_context().canvas, &mock_canvas());
EXPECT_EQ(mock_canvas().draw_calls(), std::vector<MockCanvas::DrawCall>());
}
TEST_F(PlatformViewLayerTest, ClippedPlatformViewPrerollsAndPaintsNothing) {
const SkPoint layer_offset = SkPoint::Make(0.0f, 0.0f);
const SkSize layer_size = SkSize::Make(8.0f, 8.0f);
const SkRect child_clip = SkRect::MakeLTRB(20.0f, 20.0f, 40.0f, 40.0f);
const SkRect parent_clip = SkRect::MakeLTRB(50.0f, 50.0f, 80.0f, 80.0f);
const int64_t view_id = 0;
auto layer =
std::make_shared<PlatformViewLayer>(layer_offset, layer_size, view_id);
auto child_clip_layer =
std::make_shared<ClipRectLayer>(child_clip, Clip::kHardEdge);
auto parent_clip_layer =
std::make_shared<ClipRectLayer>(parent_clip, Clip::kHardEdge);
parent_clip_layer->Add(child_clip_layer);
child_clip_layer->Add(layer);
auto embedder = MockViewEmbedder();
preroll_context()->view_embedder = &embedder;
parent_clip_layer->Preroll(preroll_context());
EXPECT_TRUE(preroll_context()->has_platform_view);
EXPECT_EQ(layer->paint_bounds(),
SkRect::MakeSize(layer_size)
.makeOffset(layer_offset.fX, layer_offset.fY));
EXPECT_TRUE(layer->needs_painting(paint_context()));
EXPECT_TRUE(child_clip_layer->needs_painting(paint_context()));
EXPECT_TRUE(parent_clip_layer->needs_painting(paint_context()));
EXPECT_TRUE(layer->subtree_has_platform_view());
EXPECT_TRUE(child_clip_layer->subtree_has_platform_view());
EXPECT_TRUE(parent_clip_layer->subtree_has_platform_view());
parent_clip_layer->Paint(paint_context());
EXPECT_EQ(paint_context().canvas, &mock_canvas());
EXPECT_EQ(
mock_canvas().draw_calls(),
std::vector(
{MockCanvas::DrawCall{0, MockCanvas::SaveData{1}},
MockCanvas::DrawCall{
1, MockCanvas::ClipRectData{parent_clip, ClipOp::kIntersect,
MockCanvas::kHardClipEdgeStyle}},
MockCanvas::DrawCall{1, MockCanvas::SaveData{2}},
MockCanvas::DrawCall{
2, MockCanvas::ClipRectData{child_clip, ClipOp::kIntersect,
MockCanvas::kHardClipEdgeStyle}},
MockCanvas::DrawCall{2, MockCanvas::RestoreData{1}},
MockCanvas::DrawCall{1, MockCanvas::RestoreData{0}}}));
}
TEST_F(PlatformViewLayerTest, OpacityInheritance) {
const SkPoint layer_offset = SkPoint::Make(0.0f, 0.0f);
const SkSize layer_size = SkSize::Make(8.0f, 8.0f);
const int64_t view_id = 0;
auto layer =
std::make_shared<PlatformViewLayer>(layer_offset, layer_size, view_id);
PrerollContext* context = preroll_context();
layer->Preroll(preroll_context());
EXPECT_EQ(context->renderable_state_flags, 0);
}
TEST_F(PlatformViewLayerTest, StateTransfer) {
const SkMatrix transform1 = SkMatrix::Translate(5, 5);
const SkMatrix transform2 = SkMatrix::Translate(15, 15);
const SkMatrix combined_transform = SkMatrix::Translate(20, 20);
const SkPoint layer_offset = SkPoint::Make(0.0f, 0.0f);
const SkSize layer_size = SkSize::Make(8.0f, 8.0f);
const int64_t view_id = 0;
const SkPath path1 = SkPath().addOval({10, 10, 20, 20});
const SkPath path2 = SkPath().addOval({15, 15, 30, 30});
// transform_layer1
// |- child1
// |- platform_layer
// |- transform_layer2
// |- child2
auto transform_layer1 = std::make_shared<TransformLayer>(transform1);
auto transform_layer2 = std::make_shared<TransformLayer>(transform2);
auto platform_layer =
std::make_shared<PlatformViewLayer>(layer_offset, layer_size, view_id);
auto child1 = std::make_shared<MockLayer>(path1);
child1->set_expected_paint_matrix(transform1);
auto child2 = std::make_shared<MockLayer>(path2);
child2->set_expected_paint_matrix(combined_transform);
transform_layer1->Add(child1);
transform_layer1->Add(platform_layer);
transform_layer1->Add(transform_layer2);
transform_layer2->Add(child2);
auto embedder = MockViewEmbedder();
DisplayListBuilder builder({0, 0, 500, 500});
embedder.AddCanvas(&builder);
PrerollContext* preroll_ctx = preroll_context();
preroll_ctx->view_embedder = &embedder;
transform_layer1->Preroll(preroll_ctx);
PaintContext& paint_ctx = paint_context();
paint_ctx.view_embedder = &embedder;
transform_layer1->Paint(paint_ctx);
}
} // namespace testing
} // namespace flutter
| engine/flow/layers/platform_view_layer_unittests.cc/0 | {
"file_path": "engine/flow/layers/platform_view_layer_unittests.cc",
"repo_id": "engine",
"token_count": 2278
} | 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_FLOW_RASTER_CACHE_H_
#define FLUTTER_FLOW_RASTER_CACHE_H_
#include <memory>
#include <unordered_map>
#include "flutter/display_list/dl_canvas.h"
#include "flutter/flow/raster_cache_key.h"
#include "flutter/flow/raster_cache_util.h"
#include "flutter/fml/macros.h"
#include "flutter/fml/memory/weak_ptr.h"
#include "flutter/fml/trace_event.h"
#include "third_party/skia/include/core/SkMatrix.h"
#include "third_party/skia/include/core/SkRect.h"
class GrDirectContext;
class SkColorSpace;
namespace flutter {
enum class RasterCacheLayerStrategy { kLayer, kLayerChildren };
class RasterCacheResult {
public:
RasterCacheResult(sk_sp<DlImage> image,
const SkRect& logical_rect,
const char* type,
sk_sp<const DlRTree> rtree = nullptr);
virtual ~RasterCacheResult() = default;
virtual void draw(DlCanvas& canvas,
const DlPaint* paint,
bool preserve_rtree) const;
virtual SkISize image_dimensions() const {
return image_ ? image_->dimensions() : SkISize::Make(0, 0);
};
virtual int64_t image_bytes() const {
return image_ ? image_->GetApproximateByteSize() : 0;
};
private:
sk_sp<DlImage> image_;
SkRect logical_rect_;
fml::tracing::TraceFlow flow_;
sk_sp<const DlRTree> rtree_;
};
class Layer;
class RasterCacheItem;
struct PrerollContext;
struct PaintContext;
struct RasterCacheMetrics {
/**
* The number of cache entries with images evicted in this frame.
*/
size_t eviction_count = 0;
/**
* The size of all of the images evicted in this frame.
*/
size_t eviction_bytes = 0;
/**
* The number of cache entries with images used in this frame.
*/
size_t in_use_count = 0;
/**
* The size of all of the images used in this frame.
*/
size_t in_use_bytes = 0;
/**
* The total cache entries that had images during this frame.
*/
size_t total_count() const { return in_use_count; }
/**
* The size of all of the cached images during this frame.
*/
size_t total_bytes() const { return in_use_bytes; }
};
/**
* RasterCache is used to cache rasterized layers or display lists to improve
* performance.
*
* Life cycle of RasterCache methods:
* - Preroll stage
* - LayerTree::Preroll - for each Layer in the tree:
* - RasterCacheItem::PrerollSetup
* At the start of each layer's preroll, add cache items to
* `PrerollContext::raster_cached_entries`.
* - RasterCacheItem::PrerollFinalize
* At the end of each layer's preroll, may mark cache entries as
* encountered by the current frame.
* - Paint stage
* - RasterCache::EvictUnusedCacheEntries
* Evict cached images that are no longer used.
* - LayerTree::TryToPrepareRasterCache
* Create cache image for each cache entry if it does not exist.
* - LayerTree::Paint - for each layer in the tree:
* If layers or display lists are cached as cached images, the method
* `RasterCache::Draw` will be used to draw those cache images.
* - RasterCache::EndFrame:
* Computes used counts and memory then reports cache metrics.
*/
class RasterCache {
public:
struct Context {
GrDirectContext* gr_context;
const sk_sp<SkColorSpace> dst_color_space;
const SkMatrix& matrix;
const SkRect& logical_rect;
const char* flow_type;
};
struct CacheInfo {
const size_t accesses_since_visible;
const bool has_image;
};
std::unique_ptr<RasterCacheResult> Rasterize(
const RasterCache::Context& context,
sk_sp<const DlRTree> rtree,
const std::function<void(DlCanvas*)>& draw_function,
const std::function<void(DlCanvas*, const SkRect& rect)>&
draw_checkerboard) const;
explicit RasterCache(
size_t access_threshold = 3,
size_t picture_and_display_list_cache_limit_per_frame =
RasterCacheUtil::kDefaultPictureAndDisplayListCacheLimitPerFrame);
virtual ~RasterCache() = default;
// Draws this item if it should be rendered from the cache and returns
// true iff it was successfully drawn. Typically this should only fail
// if the item was disabled due to conditions discovered during |Preroll|
// or if the attempt to populate the entry failed due to bounds overflow
// conditions.
// If |preserve_rtree| is true, the raster cache will preserve the original
// RTree of cached content by blitting individual rectangles from the cached
// image to the canvas according to the original layer R-Tree (if present).
// This is to ensure that the target surface R-Tree will not be clobbered with
// one large blit as it can affect platform view overlays and hit testing.
bool Draw(const RasterCacheKeyID& id,
DlCanvas& canvas,
const DlPaint* paint,
bool preserve_rtree = false) const;
bool HasEntry(const RasterCacheKeyID& id, const SkMatrix&) const;
void BeginFrame();
void EvictUnusedCacheEntries();
void EndFrame();
void Clear();
void SetCheckboardCacheImages(bool checkerboard);
const RasterCacheMetrics& picture_metrics() const { return picture_metrics_; }
const RasterCacheMetrics& layer_metrics() const { return layer_metrics_; }
size_t GetCachedEntriesCount() const;
/**
* Return the number of map entries in the layer cache regardless of whether
* the entries have been populated with an image.
*/
size_t GetLayerCachedEntriesCount() const;
/**
* Return the number of map entries in the picture (DisplayList) cache
* regardless of whether the entries have been populated with an image.
*/
size_t GetPictureCachedEntriesCount() const;
/**
* @brief Estimate how much memory is used by picture raster cache entries in
* bytes.
*
* Only SkImage's memory usage is counted as other objects are often much
* smaller compared to SkImage. SkImageInfo::computeMinByteSize is used to
* estimate the SkImage memory usage.
*/
size_t EstimatePictureCacheByteSize() const;
/**
* @brief Estimate how much memory is used by layer raster cache entries in
* bytes.
*
* Only SkImage's memory usage is counted as other objects are often much
* smaller compared to SkImage. SkImageInfo::computeMinByteSize is used to
* estimate the SkImage memory usage.
*/
size_t EstimateLayerCacheByteSize() const;
/**
* @brief Return the number of frames that a picture must be prepared
* before it will be cached. If the number is 0, then no picture will
* ever be cached.
*
* If the number is one, then it must be prepared and drawn on 1 frame
* and it will then be cached on the next frame if it is prepared.
*/
size_t access_threshold() const { return access_threshold_; }
bool GenerateNewCacheInThisFrame() const {
// Disabling caching when access_threshold is zero is historic behavior.
return access_threshold_ != 0 && display_list_cached_this_frame_ <
display_list_cache_limit_per_frame_;
}
/**
* @brief The entry whose RasterCacheKey is generated by RasterCacheKeyID
* and matrix is marked as encountered by the current frame. The entry
* will be created if it does not exist. Optionally the entry will be marked
* as visible in the current frame if the caller determines that it
* intersects the cull rect. The access_count of the entry will be
* increased if it is visible, or if it was ever visible.
* @return the number of times the entry has been hit since it was created.
* For a new entry that will be 1 if it is visible, or zero if non-visible.
*/
CacheInfo MarkSeen(const RasterCacheKeyID& id,
const SkMatrix& matrix,
bool visible) const;
/**
* Returns the access count (i.e. accesses_since_visible) for the given
* entry in the cache, or -1 if no such entry exists.
*/
int GetAccessCount(const RasterCacheKeyID& id, const SkMatrix& matrix) const;
bool UpdateCacheEntry(const RasterCacheKeyID& id,
const Context& raster_cache_context,
const std::function<void(DlCanvas*)>& render_function,
sk_sp<const DlRTree> rtree = nullptr) const;
private:
struct Entry {
bool encountered_this_frame = false;
bool visible_this_frame = false;
size_t accesses_since_visible = 0;
std::unique_ptr<RasterCacheResult> image;
};
void UpdateMetrics();
RasterCacheMetrics& GetMetricsForKind(RasterCacheKeyKind kind);
const size_t access_threshold_;
const size_t display_list_cache_limit_per_frame_;
mutable size_t display_list_cached_this_frame_ = 0;
RasterCacheMetrics layer_metrics_;
RasterCacheMetrics picture_metrics_;
mutable RasterCacheKey::Map<Entry> cache_;
bool checkerboard_images_ = false;
void TraceStatsToTimeline() const;
friend class RasterCacheItem;
friend class LayerRasterCacheItem;
FML_DISALLOW_COPY_AND_ASSIGN(RasterCache);
};
} // namespace flutter
#endif // FLUTTER_FLOW_RASTER_CACHE_H_
| engine/flow/raster_cache.h/0 | {
"file_path": "engine/flow/raster_cache.h",
"repo_id": "engine",
"token_count": 3183
} | 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 "flutter/flow/stopwatch.h"
#include "fml/time/time_delta.h"
#include "gmock/gmock.h" // IWYU pragma: keep
#include "gtest/gtest.h"
using testing::Return;
namespace flutter {
namespace testing {
class FakeRefreshRateUpdater : public Stopwatch::RefreshRateUpdater {
public:
fml::Milliseconds GetFrameBudget() const override { return budget_; }
void SetFrameBudget(fml::Milliseconds budget) { budget_ = budget; }
private:
fml::Milliseconds budget_;
};
TEST(Instrumentation, GetDefaultFrameBudgetTest) {
fml::Milliseconds frame_budget_60fps = fml::RefreshRateToFrameBudget(60);
// The default constructor sets the frame_budget to 16.6667 (60 fps).
FixedRefreshRateStopwatch stopwatch;
fml::Milliseconds actual_frame_budget = stopwatch.GetFrameBudget();
EXPECT_EQ(frame_budget_60fps, actual_frame_budget);
}
TEST(Instrumentation, GetOneShotFrameBudgetTest) {
fml::Milliseconds frame_budget_90fps = fml::RefreshRateToFrameBudget(90);
FixedRefreshRateStopwatch stopwatch(frame_budget_90fps);
fml::Milliseconds actual_frame_budget = stopwatch.GetFrameBudget();
EXPECT_EQ(frame_budget_90fps, actual_frame_budget);
}
TEST(Instrumentation, GetFrameBudgetFromUpdaterTest) {
FakeRefreshRateUpdater updater;
fml::Milliseconds frame_budget_90fps = fml::RefreshRateToFrameBudget(90);
updater.SetFrameBudget(frame_budget_90fps);
Stopwatch stopwatch(updater);
fml::Milliseconds actual_frame_budget = stopwatch.GetFrameBudget();
EXPECT_EQ(frame_budget_90fps, actual_frame_budget);
}
TEST(Instrumentation, GetLapByIndexTest) {
fml::Milliseconds frame_budget_90fps = fml::RefreshRateToFrameBudget(90);
FixedRefreshRateStopwatch stopwatch(frame_budget_90fps);
stopwatch.SetLapTime(fml::TimeDelta::FromMilliseconds(10));
EXPECT_EQ(stopwatch.GetLap(1), fml::TimeDelta::FromMilliseconds(10));
}
TEST(Instrumentation, GetCurrentSampleTest) {
fml::Milliseconds frame_budget_90fps = fml::RefreshRateToFrameBudget(90);
FixedRefreshRateStopwatch stopwatch(frame_budget_90fps);
stopwatch.Start();
stopwatch.Stop();
EXPECT_EQ(stopwatch.GetCurrentSample(), size_t(1));
}
TEST(Instrumentation, GetLapsCount) {
fml::Milliseconds frame_budget_90fps = fml::RefreshRateToFrameBudget(90);
FixedRefreshRateStopwatch stopwatch(frame_budget_90fps);
stopwatch.SetLapTime(fml::TimeDelta::FromMilliseconds(10));
EXPECT_EQ(stopwatch.GetLapsCount(), size_t(120));
}
} // namespace testing
} // namespace flutter
| engine/flow/stopwatch_unittests.cc/0 | {
"file_path": "engine/flow/stopwatch_unittests.cc",
"repo_id": "engine",
"token_count": 907
} | 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.
#include "flutter/flow/testing/mock_raster_cache.h"
#include "flutter/flow/layers/display_list_raster_cache_item.h"
#include "flutter/flow/layers/layer.h"
#include "flutter/flow/raster_cache.h"
#include "flutter/flow/raster_cache_item.h"
#include "include/core/SkMatrix.h"
namespace flutter {
namespace testing {
MockRasterCacheResult::MockRasterCacheResult(SkRect device_rect)
: RasterCacheResult(nullptr, SkRect::MakeEmpty(), "RasterCacheFlow::test"),
device_rect_(device_rect) {}
void MockRasterCache::AddMockLayer(int width, int height) {
SkMatrix ctm = SkMatrix::I();
SkPath path;
path.addRect(100, 100, 100 + width, 100 + height);
int layer_cached_threshold = 1;
MockCacheableLayer layer =
MockCacheableLayer(path, DlPaint(), layer_cached_threshold);
layer.Preroll(&preroll_context_);
layer.raster_cache_item()->TryToPrepareRasterCache(paint_context_);
RasterCache::Context r_context = {
// clang-format off
.gr_context = preroll_context_.gr_context,
.dst_color_space = preroll_context_.dst_color_space,
.matrix = ctm,
.logical_rect = layer.paint_bounds(),
// clang-format on
};
UpdateCacheEntry(
RasterCacheKeyID(layer.unique_id(), RasterCacheKeyType::kLayer),
r_context, [&](DlCanvas* canvas) {
SkRect cache_rect = RasterCacheUtil::GetDeviceBounds(
r_context.logical_rect, r_context.matrix);
return std::make_unique<MockRasterCacheResult>(cache_rect);
});
}
void MockRasterCache::AddMockPicture(int width, int height) {
FML_DCHECK(access_threshold() > 0);
SkMatrix ctm = SkMatrix::I();
DisplayListBuilder builder(SkRect::MakeLTRB(0, 0, 200 + width, 200 + height));
SkPath path;
path.addRect(100, 100, 100 + width, 100 + height);
builder.DrawPath(path, DlPaint());
sk_sp<DisplayList> display_list = builder.Build();
FixedRefreshRateStopwatch raster_time;
FixedRefreshRateStopwatch ui_time;
LayerStateStack state_stack;
PaintContextHolder holder =
GetSamplePaintContextHolder(state_stack, this, &raster_time, &ui_time);
holder.paint_context.dst_color_space = color_space_;
DisplayListRasterCacheItem display_list_item(display_list, SkPoint(), true,
false);
for (size_t i = 0; i < access_threshold(); i++) {
AutoCache(&display_list_item, &preroll_context_, ctm);
}
RasterCache::Context r_context = {
// clang-format off
.gr_context = preroll_context_.gr_context,
.dst_color_space = preroll_context_.dst_color_space,
.matrix = ctm,
.logical_rect = display_list->bounds(),
// clang-format on
};
UpdateCacheEntry(RasterCacheKeyID(display_list->unique_id(),
RasterCacheKeyType::kDisplayList),
r_context, [&](DlCanvas* canvas) {
SkRect cache_rect = RasterCacheUtil::GetDeviceBounds(
r_context.logical_rect, r_context.matrix);
return std::make_unique<MockRasterCacheResult>(cache_rect);
});
}
PrerollContextHolder GetSamplePrerollContextHolder(
LayerStateStack& state_stack,
RasterCache* raster_cache,
FixedRefreshRateStopwatch* raster_time,
FixedRefreshRateStopwatch* ui_time) {
sk_sp<SkColorSpace> srgb = SkColorSpace::MakeSRGB();
PrerollContextHolder holder = {
{
// clang-format off
.raster_cache = raster_cache,
.gr_context = nullptr,
.view_embedder = nullptr,
.state_stack = state_stack,
.dst_color_space = srgb,
.surface_needs_readback = false,
.raster_time = *raster_time,
.ui_time = *ui_time,
.texture_registry = nullptr,
.has_platform_view = false,
.has_texture_layer = false,
.raster_cached_entries = &raster_cache_items_,
// clang-format on
},
srgb};
return holder;
}
PaintContextHolder GetSamplePaintContextHolder(
LayerStateStack& state_stack,
RasterCache* raster_cache,
FixedRefreshRateStopwatch* raster_time,
FixedRefreshRateStopwatch* ui_time) {
sk_sp<SkColorSpace> srgb = SkColorSpace::MakeSRGB();
PaintContextHolder holder = {// clang-format off
{
.state_stack = state_stack,
.canvas = nullptr,
.gr_context = nullptr,
.dst_color_space = srgb,
.view_embedder = nullptr,
.raster_time = *raster_time,
.ui_time = *ui_time,
.texture_registry = nullptr,
.raster_cache = raster_cache,
},
// clang-format on
srgb};
return holder;
}
bool RasterCacheItemPrerollAndTryToRasterCache(
DisplayListRasterCacheItem& display_list_item,
PrerollContext& context,
PaintContext& paint_context,
const SkMatrix& matrix) {
RasterCacheItemPreroll(display_list_item, context, matrix);
context.raster_cache->EvictUnusedCacheEntries();
return RasterCacheItemTryToRasterCache(display_list_item, paint_context);
}
void RasterCacheItemPreroll(DisplayListRasterCacheItem& display_list_item,
PrerollContext& context,
const SkMatrix& matrix) {
display_list_item.PrerollSetup(&context, matrix);
display_list_item.PrerollFinalize(&context, matrix);
}
bool RasterCacheItemTryToRasterCache(
DisplayListRasterCacheItem& display_list_item,
PaintContext& paint_context) {
if (display_list_item.cache_state() ==
RasterCacheItem::CacheState::kCurrent) {
return display_list_item.TryToPrepareRasterCache(paint_context);
}
return false;
}
} // namespace testing
} // namespace flutter
| engine/flow/testing/mock_raster_cache.cc/0 | {
"file_path": "engine/flow/testing/mock_raster_cache.cc",
"repo_id": "engine",
"token_count": 2867
} | 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.
#ifndef FLUTTER_FLUTTER_VMA_FLUTTER_SKIA_VMA_H_
#define FLUTTER_FLUTTER_VMA_FLUTTER_SKIA_VMA_H_
#include "flutter/flutter_vma/flutter_vma.h"
#include "flutter/fml/memory/ref_ptr.h"
#include "flutter/vulkan/procs/vulkan_proc_table.h"
#include "third_party/skia/include/gpu/vk/GrVkBackendContext.h"
namespace flutter {
class FlutterSkiaVulkanMemoryAllocator : public skgpu::VulkanMemoryAllocator {
public:
static sk_sp<VulkanMemoryAllocator> Make(
uint32_t vulkan_api_version,
VkInstance instance,
VkPhysicalDevice physicalDevice,
VkDevice device,
const fml::RefPtr<vulkan::VulkanProcTable>& vk,
bool mustUseCoherentHostVisibleMemory);
~FlutterSkiaVulkanMemoryAllocator() override;
VkResult allocateImageMemory(VkImage image,
uint32_t allocationPropertyFlags,
skgpu::VulkanBackendMemory*) override;
VkResult allocateBufferMemory(VkBuffer buffer,
BufferUsage usage,
uint32_t allocationPropertyFlags,
skgpu::VulkanBackendMemory*) override;
void freeMemory(const skgpu::VulkanBackendMemory&) override;
void getAllocInfo(const skgpu::VulkanBackendMemory&,
skgpu::VulkanAlloc*) const override;
VkResult mapMemory(const skgpu::VulkanBackendMemory&, void** data) override;
void unmapMemory(const skgpu::VulkanBackendMemory&) override;
VkResult flushMemory(const skgpu::VulkanBackendMemory&,
VkDeviceSize offset,
VkDeviceSize size) override;
VkResult invalidateMemory(const skgpu::VulkanBackendMemory&,
VkDeviceSize offset,
VkDeviceSize size) override;
std::pair<uint64_t, uint64_t> totalAllocatedAndUsedMemory() const override;
private:
FlutterSkiaVulkanMemoryAllocator(
fml::RefPtr<vulkan::VulkanProcTable> vk_proc_table,
VmaAllocator allocator,
bool mustUseCoherentHostVisibleMemory);
fml::RefPtr<vulkan::VulkanProcTable> vk_proc_table_;
VmaAllocator allocator_;
// For host visible allocations do we require they are coherent or not. All
// devices are required to support a host visible and coherent memory type.
// This is used to work around bugs for devices that don't handle non coherent
// memory correctly.
bool must_use_coherent_host_visible_memory_;
};
} // namespace flutter
#endif // FLUTTER_FLUTTER_VMA_FLUTTER_SKIA_VMA_H_
| engine/flutter_vma/flutter_skia_vma.h/0 | {
"file_path": "engine/flutter_vma/flutter_skia_vma.h",
"repo_id": "engine",
"token_count": 1106
} | 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 "fml/closure.h"
#include "gtest/gtest.h"
TEST(ScopedCleanupClosureTest, DestructorDoesNothingWhenNoClosureSet) {
fml::ScopedCleanupClosure cleanup;
// Nothing should happen.
}
TEST(ScopedCleanupClosureTest, ReleaseDoesNothingWhenNoClosureSet) {
fml::ScopedCleanupClosure cleanup;
// Nothing should happen.
EXPECT_EQ(nullptr, cleanup.Release());
}
TEST(ScopedCleanupClosureTest, ClosureInvokedOnDestructorWhenSetInConstructor) {
auto invoked = false;
{
fml::ScopedCleanupClosure cleanup([&invoked]() { invoked = true; });
EXPECT_FALSE(invoked);
}
EXPECT_TRUE(invoked);
}
TEST(ScopedCleanupClosureTest, ClosureInvokedOnDestructorWhenSet) {
auto invoked = false;
{
fml::ScopedCleanupClosure cleanup;
cleanup.SetClosure([&invoked]() { invoked = true; });
EXPECT_FALSE(invoked);
}
EXPECT_TRUE(invoked);
}
TEST(ScopedCleanupClosureTest, ClosureNotInvokedWhenMoved) {
auto invoked = 0;
{
fml::ScopedCleanupClosure cleanup([&invoked]() { invoked++; });
fml::ScopedCleanupClosure cleanup2(std::move(cleanup));
EXPECT_EQ(0, invoked);
}
EXPECT_EQ(1, invoked);
}
TEST(ScopedCleanupClosureTest, ClosureNotInvokedWhenMovedViaAssignment) {
auto invoked = 0;
{
fml::ScopedCleanupClosure cleanup([&invoked]() { invoked++; });
fml::ScopedCleanupClosure cleanup2;
cleanup2 = std::move(cleanup);
EXPECT_EQ(0, invoked);
}
EXPECT_EQ(1, invoked);
}
| engine/fml/closure_unittests.cc/0 | {
"file_path": "engine/fml/closure_unittests.cc",
"repo_id": "engine",
"token_count": 579
} | 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.
#include "flutter/fml/memory/task_runner_checker.h"
namespace fml {
TaskRunnerChecker::TaskRunnerChecker()
: initialized_queue_id_(InitTaskQueueId()),
subsumed_queue_ids_(
MessageLoopTaskQueues::GetInstance()->GetSubsumedTaskQueueId(
initialized_queue_id_)){};
TaskRunnerChecker::~TaskRunnerChecker() = default;
bool TaskRunnerChecker::RunsOnCreationTaskRunner() const {
FML_CHECK(fml::MessageLoop::IsInitializedForCurrentThread());
const auto current_queue_id = MessageLoop::GetCurrentTaskQueueId();
if (RunsOnTheSameThread(current_queue_id, initialized_queue_id_)) {
return true;
}
for (auto& subsumed : subsumed_queue_ids_) {
if (RunsOnTheSameThread(current_queue_id, subsumed)) {
return true;
}
}
return false;
};
bool TaskRunnerChecker::RunsOnTheSameThread(TaskQueueId queue_a,
TaskQueueId queue_b) {
if (queue_a == queue_b) {
return true;
}
auto queues = MessageLoopTaskQueues::GetInstance();
if (queues->Owns(queue_a, queue_b)) {
return true;
}
if (queues->Owns(queue_b, queue_a)) {
return true;
}
return false;
};
TaskQueueId TaskRunnerChecker::InitTaskQueueId() {
MessageLoop::EnsureInitializedForCurrentThread();
return MessageLoop::GetCurrentTaskQueueId();
};
} // namespace fml
| engine/fml/memory/task_runner_checker.cc/0 | {
"file_path": "engine/fml/memory/task_runner_checker.cc",
"repo_id": "engine",
"token_count": 558
} | 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.
#define FML_USED_ON_EMBEDDER
#include <thread>
#include <utility>
#include "flutter/fml/message_loop_task_queues.h"
#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_;
};
static int CountRemainingTasks(fml::MessageLoopTaskQueues* task_queue,
const TaskQueueId& queue_id,
bool run_invocation = false) {
const auto now = ChronoTicksSinceEpoch();
int count = 0;
fml::closure invocation;
do {
invocation = task_queue->GetNextTaskToRun(queue_id, now);
if (!invocation) {
break;
}
count++;
if (run_invocation) {
invocation();
}
} while (invocation);
return count;
}
TEST(MessageLoopTaskQueueMergeUnmerge,
AfterMergePrimaryTasksServicedOnPrimary) {
auto task_queue = fml::MessageLoopTaskQueues::GetInstance();
auto queue_id_1 = task_queue->CreateTaskQueue();
auto queue_id_2 = task_queue->CreateTaskQueue();
task_queue->RegisterTask(queue_id_1, []() {}, ChronoTicksSinceEpoch());
ASSERT_EQ(1u, task_queue->GetNumPendingTasks(queue_id_1));
task_queue->Merge(queue_id_1, queue_id_2);
task_queue->RegisterTask(queue_id_1, []() {}, ChronoTicksSinceEpoch());
ASSERT_EQ(2u, task_queue->GetNumPendingTasks(queue_id_1));
ASSERT_EQ(0u, task_queue->GetNumPendingTasks(queue_id_2));
}
TEST(MessageLoopTaskQueueMergeUnmerge,
AfterMergeSecondaryTasksAlsoServicedOnPrimary) {
auto task_queue = fml::MessageLoopTaskQueues::GetInstance();
auto queue_id_1 = task_queue->CreateTaskQueue();
auto queue_id_2 = task_queue->CreateTaskQueue();
task_queue->RegisterTask(queue_id_2, []() {}, ChronoTicksSinceEpoch());
ASSERT_EQ(1u, task_queue->GetNumPendingTasks(queue_id_2));
task_queue->Merge(queue_id_1, queue_id_2);
ASSERT_EQ(1u, task_queue->GetNumPendingTasks(queue_id_1));
ASSERT_EQ(0u, task_queue->GetNumPendingTasks(queue_id_2));
}
TEST(MessageLoopTaskQueueMergeUnmerge, MergeUnmergeTasksPreserved) {
auto task_queue = fml::MessageLoopTaskQueues::GetInstance();
auto queue_id_1 = task_queue->CreateTaskQueue();
auto queue_id_2 = task_queue->CreateTaskQueue();
task_queue->RegisterTask(queue_id_1, []() {}, ChronoTicksSinceEpoch());
task_queue->RegisterTask(queue_id_2, []() {}, ChronoTicksSinceEpoch());
ASSERT_EQ(1u, task_queue->GetNumPendingTasks(queue_id_1));
ASSERT_EQ(1u, task_queue->GetNumPendingTasks(queue_id_2));
task_queue->Merge(queue_id_1, queue_id_2);
ASSERT_EQ(2u, task_queue->GetNumPendingTasks(queue_id_1));
ASSERT_EQ(0u, task_queue->GetNumPendingTasks(queue_id_2));
task_queue->Unmerge(queue_id_1, queue_id_2);
ASSERT_EQ(1u, task_queue->GetNumPendingTasks(queue_id_1));
ASSERT_EQ(1u, task_queue->GetNumPendingTasks(queue_id_2));
}
/// Multiple standalone engines scene
TEST(MessageLoopTaskQueueMergeUnmerge,
OneCanOwnMultipleQueuesAndUnmergeIndependently) {
auto task_queue = fml::MessageLoopTaskQueues::GetInstance();
auto queue_id_1 = task_queue->CreateTaskQueue();
auto queue_id_2 = task_queue->CreateTaskQueue();
auto queue_id_3 = task_queue->CreateTaskQueue();
// merge
ASSERT_TRUE(task_queue->Merge(queue_id_1, queue_id_2));
ASSERT_TRUE(task_queue->Owns(queue_id_1, queue_id_2));
ASSERT_FALSE(task_queue->Owns(queue_id_1, queue_id_3));
ASSERT_TRUE(task_queue->Merge(queue_id_1, queue_id_3));
ASSERT_TRUE(task_queue->Owns(queue_id_1, queue_id_2));
ASSERT_TRUE(task_queue->Owns(queue_id_1, queue_id_3));
// unmerge
ASSERT_TRUE(task_queue->Unmerge(queue_id_1, queue_id_2));
ASSERT_FALSE(task_queue->Owns(queue_id_1, queue_id_2));
ASSERT_TRUE(task_queue->Owns(queue_id_1, queue_id_3));
ASSERT_TRUE(task_queue->Unmerge(queue_id_1, queue_id_3));
ASSERT_FALSE(task_queue->Owns(queue_id_1, queue_id_2));
ASSERT_FALSE(task_queue->Owns(queue_id_1, queue_id_3));
}
TEST(MessageLoopTaskQueueMergeUnmerge,
CannotMergeSameQueueToTwoDifferentOwners) {
auto task_queue = fml::MessageLoopTaskQueues::GetInstance();
auto queue = task_queue->CreateTaskQueue();
auto owner_1 = task_queue->CreateTaskQueue();
auto owner_2 = task_queue->CreateTaskQueue();
ASSERT_TRUE(task_queue->Merge(owner_1, queue));
ASSERT_FALSE(task_queue->Merge(owner_2, queue));
}
TEST(MessageLoopTaskQueueMergeUnmerge, MergeFailIfAlreadySubsumed) {
auto task_queue = fml::MessageLoopTaskQueues::GetInstance();
auto queue_id_1 = task_queue->CreateTaskQueue();
auto queue_id_2 = task_queue->CreateTaskQueue();
auto queue_id_3 = task_queue->CreateTaskQueue();
ASSERT_TRUE(task_queue->Merge(queue_id_1, queue_id_2));
ASSERT_FALSE(task_queue->Merge(queue_id_2, queue_id_3));
ASSERT_FALSE(task_queue->Merge(queue_id_2, queue_id_1));
}
TEST(MessageLoopTaskQueueMergeUnmerge,
MergeFailIfAlreadyOwnsButTryToBeSubsumed) {
auto task_queue = fml::MessageLoopTaskQueues::GetInstance();
auto queue_id_1 = task_queue->CreateTaskQueue();
auto queue_id_2 = task_queue->CreateTaskQueue();
auto queue_id_3 = task_queue->CreateTaskQueue();
task_queue->Merge(queue_id_1, queue_id_2);
// A recursively linked merging will fail
ASSERT_FALSE(task_queue->Merge(queue_id_3, queue_id_1));
}
TEST(MessageLoopTaskQueueMergeUnmerge, UnmergeFailsOnSubsumedOrNeverMerged) {
auto task_queue = fml::MessageLoopTaskQueues::GetInstance();
auto queue_id_1 = task_queue->CreateTaskQueue();
auto queue_id_2 = task_queue->CreateTaskQueue();
auto queue_id_3 = task_queue->CreateTaskQueue();
task_queue->Merge(queue_id_1, queue_id_2);
ASSERT_FALSE(task_queue->Unmerge(queue_id_2, queue_id_3));
ASSERT_FALSE(task_queue->Unmerge(queue_id_1, queue_id_3));
ASSERT_FALSE(task_queue->Unmerge(queue_id_3, queue_id_1));
ASSERT_FALSE(task_queue->Unmerge(queue_id_2, queue_id_1));
}
TEST(MessageLoopTaskQueueMergeUnmerge, MergeInvokesBothWakeables) {
auto task_queue = fml::MessageLoopTaskQueues::GetInstance();
auto queue_id_1 = task_queue->CreateTaskQueue();
auto queue_id_2 = task_queue->CreateTaskQueue();
fml::CountDownLatch latch(2);
auto wakeable1 = std::make_unique<TestWakeable>(
[&](fml::TimePoint wake_time) { latch.CountDown(); });
auto wakeable2 = std::make_unique<TestWakeable>(
[&](fml::TimePoint wake_time) { latch.CountDown(); });
task_queue->SetWakeable(queue_id_1, wakeable1.get());
task_queue->SetWakeable(queue_id_2, wakeable2.get());
task_queue->RegisterTask(queue_id_1, []() {}, ChronoTicksSinceEpoch());
task_queue->Merge(queue_id_1, queue_id_2);
CountRemainingTasks(task_queue, queue_id_1);
latch.Wait();
}
TEST(MessageLoopTaskQueueMergeUnmerge,
MergeUnmergeInvokesBothWakeablesSeparately) {
auto task_queue = fml::MessageLoopTaskQueues::GetInstance();
auto queue_id_1 = task_queue->CreateTaskQueue();
auto queue_id_2 = task_queue->CreateTaskQueue();
fml::AutoResetWaitableEvent latch_1, latch_2;
auto wakeable1 = std::make_unique<TestWakeable>(
[&](fml::TimePoint wake_time) { latch_1.Signal(); });
auto wakeable2 = std::make_unique<TestWakeable>(
[&](fml::TimePoint wake_time) { latch_2.Signal(); });
task_queue->SetWakeable(queue_id_1, wakeable1.get());
task_queue->SetWakeable(queue_id_2, wakeable2.get());
task_queue->RegisterTask(queue_id_1, []() {}, ChronoTicksSinceEpoch());
task_queue->RegisterTask(queue_id_2, []() {}, ChronoTicksSinceEpoch());
task_queue->Merge(queue_id_1, queue_id_2);
task_queue->Unmerge(queue_id_1, queue_id_2);
CountRemainingTasks(task_queue, queue_id_1);
latch_1.Wait();
CountRemainingTasks(task_queue, queue_id_2);
latch_2.Wait();
}
TEST(MessageLoopTaskQueueMergeUnmerge, GetTasksToRunNowBlocksMerge) {
auto task_queue = fml::MessageLoopTaskQueues::GetInstance();
auto queue_id_1 = task_queue->CreateTaskQueue();
auto queue_id_2 = task_queue->CreateTaskQueue();
fml::AutoResetWaitableEvent wake_up_start, wake_up_end, merge_start,
merge_end;
auto wakeable = std::make_unique<TestWakeable>([&](fml::TimePoint wake_time) {
wake_up_start.Signal();
wake_up_end.Wait();
});
task_queue->RegisterTask(queue_id_1, []() {}, ChronoTicksSinceEpoch());
task_queue->SetWakeable(queue_id_1, wakeable.get());
std::thread tasks_to_run_now_thread(
[&]() { CountRemainingTasks(task_queue, queue_id_1); });
wake_up_start.Wait();
bool merge_done = false;
std::thread merge_thread([&]() {
merge_start.Signal();
task_queue->Merge(queue_id_1, queue_id_2);
merge_done = true;
merge_end.Signal();
});
merge_start.Wait();
ASSERT_FALSE(merge_done);
wake_up_end.Signal();
merge_end.Wait();
ASSERT_TRUE(merge_done);
tasks_to_run_now_thread.join();
merge_thread.join();
}
TEST(MessageLoopTaskQueueMergeUnmerge,
FollowingTasksSwitchQueueIfFirstTaskMergesThreads) {
auto task_queue = fml::MessageLoopTaskQueues::GetInstance();
auto queue_id_1 = task_queue->CreateTaskQueue();
auto queue_id_2 = task_queue->CreateTaskQueue();
fml::CountDownLatch latch(2);
auto wakeable1 = std::make_unique<TestWakeable>(
[&](fml::TimePoint wake_time) { latch.CountDown(); });
auto wakeable2 = std::make_unique<TestWakeable>(
[&](fml::TimePoint wake_time) { latch.CountDown(); });
task_queue->SetWakeable(queue_id_1, wakeable1.get());
task_queue->SetWakeable(queue_id_2, wakeable2.get());
task_queue->RegisterTask(
queue_id_2, [&]() { task_queue->Merge(queue_id_1, queue_id_2); },
ChronoTicksSinceEpoch());
task_queue->RegisterTask(queue_id_2, []() {}, ChronoTicksSinceEpoch());
ASSERT_EQ(CountRemainingTasks(task_queue, queue_id_2, true), 1);
ASSERT_EQ(CountRemainingTasks(task_queue, queue_id_1, true), 1);
latch.Wait();
}
} // namespace testing
} // namespace fml
| engine/fml/message_loop_task_queues_merge_unmerge_unittests.cc/0 | {
"file_path": "engine/fml/message_loop_task_queues_merge_unmerge_unittests.cc",
"repo_id": "engine",
"token_count": 4000
} | 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_FML_PLATFORM_ANDROID_PATHS_ANDROID_H_
#define FLUTTER_FML_PLATFORM_ANDROID_PATHS_ANDROID_H_
#include "flutter/fml/macros.h"
#include "flutter/fml/paths.h"
namespace fml {
namespace paths {
void InitializeAndroidCachesPath(std::string caches_path);
} // namespace paths
} // namespace fml
#endif // FLUTTER_FML_PLATFORM_ANDROID_PATHS_ANDROID_H_
| engine/fml/platform/android/paths_android.h/0 | {
"file_path": "engine/fml/platform/android/paths_android.h",
"repo_id": "engine",
"token_count": 200
} | 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_FML_PLATFORM_DARWIN_SCOPED_NSOBJECT_H_
#define FLUTTER_FML_PLATFORM_DARWIN_SCOPED_NSOBJECT_H_
#include <type_traits>
#include <utility>
// Include NSObject.h directly because Foundation.h pulls in many dependencies.
// (Approx 100k lines of code versus 1.5k for NSObject.h). scoped_nsobject gets
// singled out because it is most typically included from other header files.
#import <Foundation/NSObject.h>
#include "flutter/fml/compiler_specific.h"
#include "flutter/fml/macros.h"
#include "flutter/fml/platform/darwin/scoped_typeref.h"
#if !defined(__has_feature) || !__has_feature(objc_arc)
@class NSAutoreleasePool;
#endif
namespace fml {
// scoped_nsobject<> is patterned after scoped_ptr<>, but maintains ownership
// of an NSObject subclass object. Style deviations here are solely for
// compatibility with scoped_ptr<>'s interface, with which everyone is already
// familiar.
//
// scoped_nsobject<> takes ownership of an object (in the constructor or in
// reset()) by taking over the caller's existing ownership claim. The caller
// must own the object it gives to scoped_nsobject<>, and relinquishes an
// ownership claim to that object. scoped_nsobject<> does not call -retain,
// callers have to call this manually if appropriate.
//
// scoped_nsprotocol<> has the same behavior as scoped_nsobject, but can be used
// with protocols.
//
// scoped_nsobject<> is not to be used for NSAutoreleasePools. For
// NSAutoreleasePools use ScopedNSAutoreleasePool from
// scoped_nsautorelease_pool.h instead.
// We check for bad uses of scoped_nsobject and NSAutoreleasePool at compile
// time with a template specialization (see below).
//
// If Automatic Reference Counting (aka ARC) is enabled then the ownership
// policy is not controllable by the user as ARC make it really difficult to
// transfer ownership (the reference passed to scoped_nsobject constructor is
// sunk by ARC and __attribute((ns_consumed)) appears to not work correctly
// with Objective-C++ see https://llvm.org/bugs/show_bug.cgi?id=27887). Due to
// that, the policy is always to |RETAIN| when using ARC.
namespace internal {
id ScopedNSProtocolTraitsRetain(__unsafe_unretained id obj)
__attribute((ns_returns_not_retained));
id ScopedNSProtocolTraitsAutoRelease(__unsafe_unretained id obj)
__attribute((ns_returns_not_retained));
void ScopedNSProtocolTraitsRelease(__unsafe_unretained id obj);
// Traits for ScopedTypeRef<>. As this class may be compiled from file with
// Automatic Reference Counting enable or not all methods have annotation to
// enforce the same code generation in both case (in particular, the Retain
// method uses ns_returns_not_retained to prevent ARC to insert a -release
// call on the returned value and thus defeating the -retain).
template <typename NST>
struct ScopedNSProtocolTraits {
static NST InvalidValue() __attribute((ns_returns_not_retained)) {
return nil;
}
static NST Retain(__unsafe_unretained NST nst)
__attribute((ns_returns_not_retained)) {
return ScopedNSProtocolTraitsRetain(nst);
}
static void Release(__unsafe_unretained NST nst) {
ScopedNSProtocolTraitsRelease(nst);
}
};
} // namespace internal
template <typename NST>
class scoped_nsprotocol
: public ScopedTypeRef<NST, internal::ScopedNSProtocolTraits<NST>> {
public:
using Traits = internal::ScopedNSProtocolTraits<NST>;
#if !defined(__has_feature) || !__has_feature(objc_arc)
explicit scoped_nsprotocol(NST object = Traits::InvalidValue(),
scoped_policy::OwnershipPolicy policy =
scoped_policy::OwnershipPolicy::kAssume)
: ScopedTypeRef<NST, Traits>(object, policy) {}
#else
explicit scoped_nsprotocol(NST object = Traits::InvalidValue())
: ScopedTypeRef<NST, Traits>(object,
scoped_policy::OwnershipPolicy::kRetain) {}
#endif
// NOLINTNEXTLINE(google-explicit-constructor)
scoped_nsprotocol(const scoped_nsprotocol<NST>& that)
: ScopedTypeRef<NST, Traits>(that) {}
template <typename NSR>
explicit scoped_nsprotocol(const scoped_nsprotocol<NSR>& that_as_subclass)
: ScopedTypeRef<NST, Traits>(that_as_subclass) {}
// NOLINTNEXTLINE(google-explicit-constructor)
scoped_nsprotocol(scoped_nsprotocol<NST>&& that)
: ScopedTypeRef<NST, Traits>(std::move(that)) {}
scoped_nsprotocol& operator=(const scoped_nsprotocol<NST>& that) {
ScopedTypeRef<NST, Traits>::operator=(that);
return *this;
}
#if !defined(__has_feature) || !__has_feature(objc_arc)
void reset(NST object = Traits::InvalidValue(),
scoped_policy::OwnershipPolicy policy =
scoped_policy::OwnershipPolicy::kAssume) {
ScopedTypeRef<NST, Traits>::reset(object, policy);
}
#else
void reset(NST object = Traits::InvalidValue()) {
ScopedTypeRef<NST, Traits>::reset(object,
scoped_policy::OwnershipPolicy::kRetain);
}
#endif
// Shift reference to the autorelease pool to be released later.
NST autorelease() __attribute((ns_returns_not_retained)) {
return internal::ScopedNSProtocolTraitsAutoRelease(this->release());
}
};
// Free functions
template <class C>
void swap(scoped_nsprotocol<C>& p1, scoped_nsprotocol<C>& p2) {
p1.swap(p2);
}
template <class C>
bool operator==(C p1, const scoped_nsprotocol<C>& p2) {
return p1 == p2.get();
}
template <class C>
bool operator!=(C p1, const scoped_nsprotocol<C>& p2) {
return p1 != p2.get();
}
template <typename NST>
class scoped_nsobject : public scoped_nsprotocol<NST*> {
public:
using Traits = typename scoped_nsprotocol<NST*>::Traits;
#if !defined(__has_feature) || !__has_feature(objc_arc)
explicit scoped_nsobject(NST* object = Traits::InvalidValue(),
scoped_policy::OwnershipPolicy policy =
scoped_policy::OwnershipPolicy::kAssume)
: scoped_nsprotocol<NST*>(object, policy) {}
#else
explicit scoped_nsobject(NST* object = Traits::InvalidValue())
: scoped_nsprotocol<NST*>(object) {}
#endif
// NOLINTNEXTLINE(google-explicit-constructor)
scoped_nsobject(const scoped_nsobject<NST>& that)
: scoped_nsprotocol<NST*>(that) {}
template <typename NSR>
explicit scoped_nsobject(const scoped_nsobject<NSR>& that_as_subclass)
: scoped_nsprotocol<NST*>(that_as_subclass) {}
// NOLINTNEXTLINE(google-explicit-constructor)
scoped_nsobject(scoped_nsobject<NST>&& that)
: scoped_nsprotocol<NST*>(std::move(that)) {}
scoped_nsobject& operator=(const scoped_nsobject<NST>& that) {
scoped_nsprotocol<NST*>::operator=(that);
return *this;
}
#if !defined(__has_feature) || !__has_feature(objc_arc)
void reset(NST* object = Traits::InvalidValue(),
scoped_policy::OwnershipPolicy policy =
scoped_policy::OwnershipPolicy::kAssume) {
scoped_nsprotocol<NST*>::reset(object, policy);
}
#else
void reset(NST* object = Traits::InvalidValue()) {
scoped_nsprotocol<NST*>::reset(object);
}
#endif
#if !defined(__has_feature) || !__has_feature(objc_arc)
static_assert(std::is_same<NST, NSAutoreleasePool>::value == false,
"Use ScopedNSAutoreleasePool instead");
#endif
};
// Specialization to make scoped_nsobject<id> work.
template <>
class scoped_nsobject<id> : public scoped_nsprotocol<id> {
public:
using Traits = typename scoped_nsprotocol<id>::Traits;
#if !defined(__has_feature) || !__has_feature(objc_arc)
explicit scoped_nsobject(id object = Traits::InvalidValue(),
scoped_policy::OwnershipPolicy policy =
scoped_policy::OwnershipPolicy::kAssume)
: scoped_nsprotocol<id>(object, policy) {}
#else
explicit scoped_nsobject(id object = Traits::InvalidValue())
: scoped_nsprotocol<id>(object) {}
#endif
// NOLINTNEXTLINE(google-explicit-constructor)
scoped_nsobject(const scoped_nsobject<id>& that)
: scoped_nsprotocol<id>(that) {}
template <typename NSR>
explicit scoped_nsobject(const scoped_nsobject<NSR>& that_as_subclass)
: scoped_nsprotocol<id>(that_as_subclass) {}
// NOLINTNEXTLINE(google-explicit-constructor)
scoped_nsobject(scoped_nsobject<id>&& that)
: scoped_nsprotocol<id>(std::move(that)) {}
scoped_nsobject& operator=(const scoped_nsobject<id>& that) {
scoped_nsprotocol<id>::operator=(that);
return *this;
}
#if !defined(__has_feature) || !__has_feature(objc_arc)
void reset(id object = Traits::InvalidValue(),
scoped_policy::OwnershipPolicy policy =
scoped_policy::OwnershipPolicy::kAssume) {
scoped_nsprotocol<id>::reset(object, policy);
}
#else
void reset(id object = Traits::InvalidValue()) {
scoped_nsprotocol<id>::reset(object);
}
#endif
};
} // namespace fml
#endif // FLUTTER_FML_PLATFORM_DARWIN_SCOPED_NSOBJECT_H_
| engine/fml/platform/darwin/scoped_nsobject.h/0 | {
"file_path": "engine/fml/platform/darwin/scoped_nsobject.h",
"repo_id": "engine",
"token_count": 3502
} | 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 "flutter/fml/platform/fuchsia/log_state.h"
#include <fidl/fuchsia.logger/cpp/fidl.h>
#include <lib/component/incoming/cpp/protocol.h>
#include <lib/fidl/cpp/channel.h>
#include <lib/fidl/cpp/wire/internal/transport_channel.h>
#include <lib/zx/socket.h>
#include <zircon/assert.h>
#include <zircon/types.h>
#include <atomic>
#include <initializer_list>
#include <memory>
#include <mutex>
#include <string>
#include <utility>
#include <vector>
#include "flutter/fml/platform/fuchsia/log_interest_listener.h"
namespace fml {
LogState::LogState() {
// Get channel to log sink
auto client_end = component::Connect<fuchsia_logger::LogSink>();
ZX_ASSERT(client_end.is_ok());
fidl::SyncClient log_sink(std::move(*client_end));
// Attempts to create a kernel socket object should never fail.
zx::socket local, remote;
zx::socket::create(ZX_SOCKET_DATAGRAM, &local, &remote);
auto result = log_sink->ConnectStructured({{.socket = std::move(remote)}});
ZX_ASSERT_MSG(result.is_ok(), "%s",
result.error_value().FormatDescription().c_str());
// Wait for the first interest change to set the initial minimum logging
// level (should return quickly).
auto interest_result = log_sink->WaitForInterestChange();
ZX_ASSERT_MSG(interest_result.is_ok(), "%s",
interest_result.error_value().FormatDescription().c_str());
LogInterestListener::HandleInterestChange(interest_result->data());
socket_ = std::move(local);
client_end_ = log_sink.TakeClientEnd();
}
fidl::ClientEnd<::fuchsia_logger::LogSink> LogState::TakeClientEnd() {
std::lock_guard lock(mutex_);
return std::move(client_end_);
}
void LogState::SetTags(const std::initializer_list<std::string>& tags) {
std::atomic_store(&tags_,
std::make_shared<const std::vector<std::string>>(tags));
}
LogState& LogState::Default() {
static LogState* instance = new LogState();
return *instance;
}
} // namespace fml
| engine/fml/platform/fuchsia/log_state.cc/0 | {
"file_path": "engine/fml/platform/fuchsia/log_state.cc",
"repo_id": "engine",
"token_count": 772
} | 201 |
// 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/paths.h"
#include <unistd.h>
#include <climits>
#include "flutter/fml/logging.h"
namespace fml {
namespace paths {
namespace {
constexpr char kFileURLPrefix[] = "file://";
constexpr size_t kFileURLPrefixLength = sizeof(kFileURLPrefix) - 1;
std::string GetCurrentDirectory() {
char buffer[PATH_MAX];
FML_CHECK(getcwd(buffer, sizeof(buffer)));
return std::string(buffer);
}
} // namespace
std::string AbsolutePath(const std::string& path) {
if (!path.empty()) {
if (path[0] == '/') {
// Path is already absolute.
return path;
}
return GetCurrentDirectory() + "/" + path;
} else {
// Path is empty.
return GetCurrentDirectory();
}
}
std::string GetDirectoryName(const std::string& path) {
size_t separator = path.rfind('/');
if (separator == 0u) {
return "/";
}
if (separator == std::string::npos) {
return std::string();
}
return path.substr(0, separator);
}
std::string FromURI(const std::string& uri) {
if (uri.substr(0, kFileURLPrefixLength) != kFileURLPrefix) {
return uri;
}
std::string file_path = uri.substr(kFileURLPrefixLength);
return SanitizeURIEscapedCharacters(file_path);
}
} // namespace paths
} // namespace fml
| engine/fml/platform/posix/paths_posix.cc/0 | {
"file_path": "engine/fml/platform/posix/paths_posix.cc",
"repo_id": "engine",
"token_count": 518
} | 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 "flutter/fml/string_conversion.h"
#include "gtest/gtest.h"
namespace fml {
namespace testing {
TEST(StringConversion, Utf16ToUtf16Empty) {
EXPECT_EQ(Utf8ToUtf16(""), u"");
}
TEST(StringConversion, Utf8ToUtf16Ascii) {
EXPECT_EQ(Utf8ToUtf16("abc123"), u"abc123");
}
TEST(StringConversion, Utf8ToUtf16Unicode) {
EXPECT_EQ(Utf8ToUtf16("\xe2\x98\x83"), u"\x2603");
}
TEST(StringConversion, Utf16ToUtf8Empty) {
EXPECT_EQ(Utf16ToUtf8(u""), "");
}
TEST(StringConversion, Utf16ToUtf8Ascii) {
EXPECT_EQ(Utf16ToUtf8(u"abc123"), "abc123");
}
TEST(StringConversion, Utf16ToUtf8Unicode) {
EXPECT_EQ(Utf16ToUtf8(u"\x2603"), "\xe2\x98\x83");
}
} // namespace testing
} // namespace fml
| engine/fml/string_conversion_unittests.cc/0 | {
"file_path": "engine/fml/string_conversion_unittests.cc",
"repo_id": "engine",
"token_count": 387
} | 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.
#include "flutter/fml/synchronization/waitable_event.h"
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <thread>
#include <type_traits>
#include <vector>
#include "flutter/fml/macros.h"
#include "gtest/gtest.h"
// rand() is only used for tests in this file.
// NOLINTBEGIN(clang-analyzer-security.insecureAPI.rand)
namespace fml {
namespace {
constexpr TimeDelta kEpsilonTimeout = TimeDelta::FromMilliseconds(20);
constexpr TimeDelta kTinyTimeout = TimeDelta::FromMilliseconds(100);
constexpr TimeDelta kActionTimeout = TimeDelta::FromMilliseconds(10000);
// Sleeps for a "very small" amount of time.
void SleepFor(TimeDelta duration) {
std::this_thread::sleep_for(
std::chrono::nanoseconds(duration.ToNanoseconds()));
}
void EpsilonRandomSleep() {
TimeDelta duration =
TimeDelta::FromMilliseconds(static_cast<unsigned>(rand()) % 20u);
SleepFor(duration);
}
// AutoResetWaitableEvent ------------------------------------------------------
TEST(AutoResetWaitableEventTest, Basic) {
AutoResetWaitableEvent ev;
EXPECT_FALSE(ev.IsSignaledForTest());
ev.Signal();
EXPECT_TRUE(ev.IsSignaledForTest());
ev.Wait();
EXPECT_FALSE(ev.IsSignaledForTest());
ev.Reset();
EXPECT_FALSE(ev.IsSignaledForTest());
ev.Signal();
EXPECT_TRUE(ev.IsSignaledForTest());
ev.Reset();
EXPECT_FALSE(ev.IsSignaledForTest());
EXPECT_TRUE(ev.WaitWithTimeout(TimeDelta::Zero()));
EXPECT_FALSE(ev.IsSignaledForTest());
EXPECT_TRUE(ev.WaitWithTimeout(TimeDelta::FromMilliseconds(1)));
EXPECT_FALSE(ev.IsSignaledForTest());
ev.Signal();
EXPECT_TRUE(ev.IsSignaledForTest());
EXPECT_FALSE(ev.WaitWithTimeout(TimeDelta::Zero()));
EXPECT_FALSE(ev.IsSignaledForTest());
EXPECT_TRUE(ev.WaitWithTimeout(TimeDelta::FromMilliseconds(1)));
EXPECT_FALSE(ev.IsSignaledForTest());
ev.Signal();
EXPECT_FALSE(ev.WaitWithTimeout(TimeDelta::FromMilliseconds(1)));
EXPECT_FALSE(ev.IsSignaledForTest());
}
TEST(AutoResetWaitableEventTest, MultipleWaiters) {
AutoResetWaitableEvent ev;
for (size_t i = 0u; i < 5u; i++) {
std::atomic_uint wake_count(0u);
std::vector<std::thread> threads;
for (size_t j = 0u; j < 4u; j++) {
threads.push_back(std::thread([&ev, &wake_count]() {
if (rand() % 2 == 0) {
ev.Wait();
} else {
EXPECT_FALSE(ev.WaitWithTimeout(kActionTimeout));
}
wake_count.fetch_add(1u);
// Note: We can't say anything about the signaled state of |ev| here,
// since the main thread may have already signaled it again.
}));
}
// Unfortunately, we can't really wait for the threads to be waiting, so we
// just sleep for a bit, and count on them having started and advanced to
// waiting.
SleepFor(kTinyTimeout + kTinyTimeout);
for (size_t j = 0u; j < threads.size(); j++) {
unsigned old_wake_count = wake_count.load();
EXPECT_EQ(j, old_wake_count);
// Each |Signal()| should wake exactly one thread.
ev.Signal();
// Poll for |wake_count| to change.
while (wake_count.load() == old_wake_count) {
SleepFor(kEpsilonTimeout);
}
EXPECT_FALSE(ev.IsSignaledForTest());
// And once it's changed, wait a little longer, to see if any other
// threads are awoken (they shouldn't be).
SleepFor(kEpsilonTimeout);
EXPECT_EQ(old_wake_count + 1u, wake_count.load());
EXPECT_FALSE(ev.IsSignaledForTest());
}
// Having done that, if we signal |ev| now, it should stay signaled.
ev.Signal();
SleepFor(kEpsilonTimeout);
EXPECT_TRUE(ev.IsSignaledForTest());
for (auto& thread : threads) {
thread.join();
}
ev.Reset();
}
}
// ManualResetWaitableEvent ----------------------------------------------------
TEST(ManualResetWaitableEventTest, Basic) {
ManualResetWaitableEvent ev;
EXPECT_FALSE(ev.IsSignaledForTest());
ev.Signal();
EXPECT_TRUE(ev.IsSignaledForTest());
ev.Wait();
EXPECT_TRUE(ev.IsSignaledForTest());
ev.Reset();
EXPECT_FALSE(ev.IsSignaledForTest());
EXPECT_TRUE(ev.WaitWithTimeout(TimeDelta::Zero()));
EXPECT_FALSE(ev.IsSignaledForTest());
EXPECT_TRUE(ev.WaitWithTimeout(TimeDelta::FromMilliseconds(1)));
EXPECT_FALSE(ev.IsSignaledForTest());
ev.Signal();
EXPECT_TRUE(ev.IsSignaledForTest());
EXPECT_FALSE(ev.WaitWithTimeout(TimeDelta::Zero()));
EXPECT_TRUE(ev.IsSignaledForTest());
EXPECT_FALSE(ev.WaitWithTimeout(TimeDelta::FromMilliseconds(1)));
EXPECT_TRUE(ev.IsSignaledForTest());
}
TEST(ManualResetWaitableEventTest, SignalMultiple) {
ManualResetWaitableEvent ev;
for (size_t i = 0u; i < 10u; i++) {
for (size_t num_waiters = 1u; num_waiters < 5u; num_waiters++) {
std::vector<std::thread> threads;
for (size_t j = 0u; j < num_waiters; j++) {
threads.push_back(std::thread([&ev]() {
EpsilonRandomSleep();
if (rand() % 2 == 0) {
ev.Wait();
} else {
EXPECT_FALSE(ev.WaitWithTimeout(kActionTimeout));
}
}));
}
EpsilonRandomSleep();
ev.Signal();
// The threads will only terminate once they've successfully waited (or
// timed out).
for (auto& thread : threads) {
thread.join();
}
ev.Reset();
}
}
}
} // namespace
} // namespace fml
// NOLINTEND(clang-analyzer-security.insecureAPI.rand)
| engine/fml/synchronization/waitable_event_unittest.cc/0 | {
"file_path": "engine/fml/synchronization/waitable_event_unittest.cc",
"repo_id": "engine",
"token_count": 2200
} | 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_FML_TIME_TIME_POINT_H_
#define FLUTTER_FML_TIME_TIME_POINT_H_
#include <cstdint>
#include <functional>
#include <iosfwd>
#include "flutter/fml/time/time_delta.h"
namespace fml {
// A TimePoint represents a point in time represented as an integer number of
// nanoseconds elapsed since an arbitrary point in the past.
//
// WARNING: This class should not be serialized across reboots, or across
// devices: the reference point is only stable for a given device between
// reboots.
class TimePoint {
public:
using ClockSource = TimePoint (*)();
// Default TimePoint with internal value 0 (epoch).
constexpr TimePoint() = default;
static void SetClockSource(ClockSource source);
static TimePoint Now();
static TimePoint CurrentWallTime();
static constexpr TimePoint Min() {
return TimePoint(std::numeric_limits<int64_t>::min());
}
static constexpr TimePoint Max() {
return TimePoint(std::numeric_limits<int64_t>::max());
}
static constexpr TimePoint FromEpochDelta(TimeDelta ticks) {
return TimePoint(ticks.ToNanoseconds());
}
// Expects ticks in nanos.
static constexpr TimePoint FromTicks(int64_t ticks) {
return TimePoint(ticks);
}
TimeDelta ToEpochDelta() const { return TimeDelta::FromNanoseconds(ticks_); }
// Compute the difference between two time points.
TimeDelta operator-(TimePoint other) const {
return TimeDelta::FromNanoseconds(ticks_ - other.ticks_);
}
TimePoint operator+(TimeDelta duration) const {
return TimePoint(ticks_ + duration.ToNanoseconds());
}
TimePoint operator-(TimeDelta duration) const {
return TimePoint(ticks_ - duration.ToNanoseconds());
}
bool operator==(TimePoint other) const { return ticks_ == other.ticks_; }
bool operator!=(TimePoint other) const { return ticks_ != other.ticks_; }
bool operator<(TimePoint other) const { return ticks_ < other.ticks_; }
bool operator<=(TimePoint other) const { return ticks_ <= other.ticks_; }
bool operator>(TimePoint other) const { return ticks_ > other.ticks_; }
bool operator>=(TimePoint other) const { return ticks_ >= other.ticks_; }
private:
explicit constexpr TimePoint(int64_t ticks) : ticks_(ticks) {}
int64_t ticks_ = 0;
};
} // namespace fml
#endif // FLUTTER_FML_TIME_TIME_POINT_H_
| engine/fml/time/time_point.h/0 | {
"file_path": "engine/fml/time/time_point.h",
"repo_id": "engine",
"token_count": 777
} | 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.
#include "impeller/aiks/aiks_context.h"
#include "fml/closure.h"
#include "impeller/aiks/picture.h"
#include "impeller/typographer/typographer_context.h"
namespace impeller {
AiksContext::AiksContext(
std::shared_ptr<Context> context,
std::shared_ptr<TypographerContext> typographer_context,
std::optional<std::shared_ptr<RenderTargetAllocator>>
render_target_allocator)
: context_(std::move(context)) {
if (!context_ || !context_->IsValid()) {
return;
}
content_context_ = std::make_unique<ContentContext>(
context_, std::move(typographer_context),
render_target_allocator.has_value() ? render_target_allocator.value()
: nullptr);
if (!content_context_->IsValid()) {
return;
}
is_valid_ = true;
}
AiksContext::~AiksContext() = default;
bool AiksContext::IsValid() const {
return is_valid_;
}
std::shared_ptr<Context> AiksContext::GetContext() const {
return context_;
}
ContentContext& AiksContext::GetContentContext() const {
return *content_context_;
}
bool AiksContext::Render(const Picture& picture,
RenderTarget& render_target,
bool reset_host_buffer) {
if (!IsValid()) {
return false;
}
fml::ScopedCleanupClosure closure([&]() {
if (reset_host_buffer) {
content_context_->GetTransientsBuffer().Reset();
}
});
if (picture.pass) {
return picture.pass->Render(*content_context_, render_target);
}
return true;
}
} // namespace impeller
| engine/impeller/aiks/aiks_context.cc/0 | {
"file_path": "engine/impeller/aiks/aiks_context.cc",
"repo_id": "engine",
"token_count": 660
} | 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 "flutter/testing/testing.h"
#include "impeller/aiks/canvas.h"
#include "impeller/aiks/image_filter.h"
#include "impeller/geometry/path_builder.h"
// TODO(zanderso): https://github.com/flutter/flutter/issues/127701
// NOLINTBEGIN(bugprone-unchecked-optional-access)
namespace impeller {
namespace testing {
using AiksCanvasTest = ::testing::Test;
TEST(AiksCanvasTest, EmptyCullRect) {
Canvas canvas;
ASSERT_FALSE(canvas.GetCurrentLocalCullingBounds().has_value());
}
TEST(AiksCanvasTest, InitialCullRect) {
Rect initial_cull = Rect::MakeXYWH(0, 0, 10, 10);
Canvas canvas(initial_cull);
ASSERT_TRUE(canvas.GetCurrentLocalCullingBounds().has_value());
ASSERT_EQ(canvas.GetCurrentLocalCullingBounds().value(), initial_cull);
}
TEST(AiksCanvasTest, TranslatedCullRect) {
Rect initial_cull = Rect::MakeXYWH(5, 5, 10, 10);
Rect translated_cull = Rect::MakeXYWH(0, 0, 10, 10);
Canvas canvas(initial_cull);
canvas.Translate(Vector3(5, 5, 0));
ASSERT_TRUE(canvas.GetCurrentLocalCullingBounds().has_value());
ASSERT_EQ(canvas.GetCurrentLocalCullingBounds().value(), translated_cull);
}
TEST(AiksCanvasTest, ScaledCullRect) {
Rect initial_cull = Rect::MakeXYWH(5, 5, 10, 10);
Rect scaled_cull = Rect::MakeXYWH(10, 10, 20, 20);
Canvas canvas(initial_cull);
canvas.Scale(Vector2(0.5, 0.5));
ASSERT_TRUE(canvas.GetCurrentLocalCullingBounds().has_value());
ASSERT_EQ(canvas.GetCurrentLocalCullingBounds().value(), scaled_cull);
}
TEST(AiksCanvasTest, RectClipIntersectAgainstEmptyCullRect) {
Rect rect_clip = Rect::MakeXYWH(5, 5, 10, 10);
Canvas canvas;
canvas.ClipRect(rect_clip, Entity::ClipOperation::kIntersect);
ASSERT_TRUE(canvas.GetCurrentLocalCullingBounds().has_value());
ASSERT_EQ(canvas.GetCurrentLocalCullingBounds().value(), rect_clip);
}
TEST(AiksCanvasTest, RectClipDiffAgainstEmptyCullRect) {
Rect rect_clip = Rect::MakeXYWH(5, 5, 10, 10);
Canvas canvas;
canvas.ClipRect(rect_clip, Entity::ClipOperation::kDifference);
ASSERT_FALSE(canvas.GetCurrentLocalCullingBounds().has_value());
}
TEST(AiksCanvasTest, RectClipIntersectAgainstCullRect) {
Rect initial_cull = Rect::MakeXYWH(0, 0, 10, 10);
Rect rect_clip = Rect::MakeXYWH(5, 5, 10, 10);
Rect result_cull = Rect::MakeXYWH(5, 5, 5, 5);
Canvas canvas(initial_cull);
canvas.ClipRect(rect_clip, Entity::ClipOperation::kIntersect);
ASSERT_TRUE(canvas.GetCurrentLocalCullingBounds().has_value());
ASSERT_EQ(canvas.GetCurrentLocalCullingBounds().value(), result_cull);
}
TEST(AiksCanvasTest, RectClipDiffAgainstNonCoveredCullRect) {
Rect initial_cull = Rect::MakeXYWH(0, 0, 10, 10);
Rect rect_clip = Rect::MakeXYWH(5, 5, 10, 10);
Rect result_cull = Rect::MakeXYWH(0, 0, 10, 10);
Canvas canvas(initial_cull);
canvas.ClipRect(rect_clip, Entity::ClipOperation::kDifference);
ASSERT_TRUE(canvas.GetCurrentLocalCullingBounds().has_value());
ASSERT_EQ(canvas.GetCurrentLocalCullingBounds().value(), result_cull);
}
TEST(AiksCanvasTest, RectClipDiffAboveCullRect) {
Rect initial_cull = Rect::MakeXYWH(5, 5, 10, 10);
Rect rect_clip = Rect::MakeXYWH(0, 0, 20, 4);
Rect result_cull = Rect::MakeXYWH(5, 5, 10, 10);
Canvas canvas(initial_cull);
canvas.ClipRect(rect_clip, Entity::ClipOperation::kDifference);
ASSERT_TRUE(canvas.GetCurrentLocalCullingBounds().has_value());
ASSERT_EQ(canvas.GetCurrentLocalCullingBounds().value(), result_cull);
}
TEST(AiksCanvasTest, RectClipDiffBelowCullRect) {
Rect initial_cull = Rect::MakeXYWH(5, 5, 10, 10);
Rect rect_clip = Rect::MakeXYWH(0, 16, 20, 4);
Rect result_cull = Rect::MakeXYWH(5, 5, 10, 10);
Canvas canvas(initial_cull);
canvas.ClipRect(rect_clip, Entity::ClipOperation::kDifference);
ASSERT_TRUE(canvas.GetCurrentLocalCullingBounds().has_value());
ASSERT_EQ(canvas.GetCurrentLocalCullingBounds().value(), result_cull);
}
TEST(AiksCanvasTest, RectClipDiffLeftOfCullRect) {
Rect initial_cull = Rect::MakeXYWH(5, 5, 10, 10);
Rect rect_clip = Rect::MakeXYWH(0, 0, 4, 20);
Rect result_cull = Rect::MakeXYWH(5, 5, 10, 10);
Canvas canvas(initial_cull);
canvas.ClipRect(rect_clip, Entity::ClipOperation::kDifference);
ASSERT_TRUE(canvas.GetCurrentLocalCullingBounds().has_value());
ASSERT_EQ(canvas.GetCurrentLocalCullingBounds().value(), result_cull);
}
TEST(AiksCanvasTest, RectClipDiffRightOfCullRect) {
Rect initial_cull = Rect::MakeXYWH(5, 5, 10, 10);
Rect rect_clip = Rect::MakeXYWH(16, 0, 4, 20);
Rect result_cull = Rect::MakeXYWH(5, 5, 10, 10);
Canvas canvas(initial_cull);
canvas.ClipRect(rect_clip, Entity::ClipOperation::kDifference);
ASSERT_TRUE(canvas.GetCurrentLocalCullingBounds().has_value());
ASSERT_EQ(canvas.GetCurrentLocalCullingBounds().value(), result_cull);
}
TEST(AiksCanvasTest, RectClipDiffAgainstVCoveredCullRect) {
Rect initial_cull = Rect::MakeXYWH(0, 0, 10, 10);
Rect rect_clip = Rect::MakeXYWH(5, 0, 10, 10);
Rect result_cull = Rect::MakeXYWH(0, 0, 5, 10);
Canvas canvas(initial_cull);
canvas.ClipRect(rect_clip, Entity::ClipOperation::kDifference);
ASSERT_TRUE(canvas.GetCurrentLocalCullingBounds().has_value());
ASSERT_EQ(canvas.GetCurrentLocalCullingBounds().value(), result_cull);
}
TEST(AiksCanvasTest, RectClipDiffAgainstHCoveredCullRect) {
Rect initial_cull = Rect::MakeXYWH(0, 0, 10, 10);
Rect rect_clip = Rect::MakeXYWH(0, 5, 10, 10);
Rect result_cull = Rect::MakeXYWH(0, 0, 10, 5);
Canvas canvas(initial_cull);
canvas.ClipRect(rect_clip, Entity::ClipOperation::kDifference);
ASSERT_TRUE(canvas.GetCurrentLocalCullingBounds().has_value());
ASSERT_EQ(canvas.GetCurrentLocalCullingBounds().value(), result_cull);
}
TEST(AiksCanvasTest, RRectClipIntersectAgainstEmptyCullRect) {
Rect rect_clip = Rect::MakeXYWH(5, 5, 10, 10);
Canvas canvas;
canvas.ClipRRect(rect_clip, {1, 1}, Entity::ClipOperation::kIntersect);
ASSERT_TRUE(canvas.GetCurrentLocalCullingBounds().has_value());
ASSERT_EQ(canvas.GetCurrentLocalCullingBounds().value(), rect_clip);
}
TEST(AiksCanvasTest, RRectClipDiffAgainstEmptyCullRect) {
Rect rect_clip = Rect::MakeXYWH(5, 5, 10, 10);
Canvas canvas;
canvas.ClipRRect(rect_clip, {1, 1}, Entity::ClipOperation::kDifference);
ASSERT_FALSE(canvas.GetCurrentLocalCullingBounds().has_value());
}
TEST(AiksCanvasTest, RRectClipIntersectAgainstCullRect) {
Rect initial_cull = Rect::MakeXYWH(0, 0, 10, 10);
Rect rect_clip = Rect::MakeXYWH(5, 5, 10, 10);
Rect result_cull = Rect::MakeXYWH(5, 5, 5, 5);
Canvas canvas(initial_cull);
canvas.ClipRRect(rect_clip, {1, 1}, Entity::ClipOperation::kIntersect);
ASSERT_TRUE(canvas.GetCurrentLocalCullingBounds().has_value());
ASSERT_EQ(canvas.GetCurrentLocalCullingBounds().value(), result_cull);
}
TEST(AiksCanvasTest, RRectClipDiffAgainstNonCoveredCullRect) {
Rect initial_cull = Rect::MakeXYWH(0, 0, 10, 10);
Rect rect_clip = Rect::MakeXYWH(5, 5, 10, 10);
Rect result_cull = Rect::MakeXYWH(0, 0, 10, 10);
Canvas canvas(initial_cull);
canvas.ClipRRect(rect_clip, {1, 1}, Entity::ClipOperation::kDifference);
ASSERT_TRUE(canvas.GetCurrentLocalCullingBounds().has_value());
ASSERT_EQ(canvas.GetCurrentLocalCullingBounds().value(), result_cull);
}
TEST(AiksCanvasTest, RRectClipDiffAgainstVPartiallyCoveredCullRect) {
Rect initial_cull = Rect::MakeXYWH(0, 0, 10, 10);
Rect rect_clip = Rect::MakeXYWH(5, 0, 10, 10);
Rect result_cull = Rect::MakeXYWH(0, 0, 6, 10);
Canvas canvas(initial_cull);
canvas.ClipRRect(rect_clip, {1, 1}, Entity::ClipOperation::kDifference);
ASSERT_TRUE(canvas.GetCurrentLocalCullingBounds().has_value());
ASSERT_EQ(canvas.GetCurrentLocalCullingBounds().value(), result_cull);
}
TEST(AiksCanvasTest, RRectClipDiffAgainstVFullyCoveredCullRect) {
Rect initial_cull = Rect::MakeXYWH(0, 0, 10, 10);
Rect rect_clip = Rect::MakeXYWH(5, -2, 10, 14);
Rect result_cull = Rect::MakeXYWH(0, 0, 5, 10);
Canvas canvas(initial_cull);
canvas.ClipRRect(rect_clip, {1, 1}, Entity::ClipOperation::kDifference);
ASSERT_TRUE(canvas.GetCurrentLocalCullingBounds().has_value());
ASSERT_EQ(canvas.GetCurrentLocalCullingBounds().value(), result_cull);
}
TEST(AiksCanvasTest, RRectClipDiffAgainstHPartiallyCoveredCullRect) {
Rect initial_cull = Rect::MakeXYWH(0, 0, 10, 10);
Rect rect_clip = Rect::MakeXYWH(0, 5, 10, 10);
Rect result_cull = Rect::MakeXYWH(0, 0, 10, 6);
Canvas canvas(initial_cull);
canvas.ClipRRect(rect_clip, {1, 1}, Entity::ClipOperation::kDifference);
ASSERT_TRUE(canvas.GetCurrentLocalCullingBounds().has_value());
ASSERT_EQ(canvas.GetCurrentLocalCullingBounds().value(), result_cull);
}
TEST(AiksCanvasTest, RRectClipDiffAgainstHFullyCoveredCullRect) {
Rect initial_cull = Rect::MakeXYWH(0, 0, 10, 10);
Rect rect_clip = Rect::MakeXYWH(-2, 5, 14, 10);
Rect result_cull = Rect::MakeXYWH(0, 0, 10, 5);
Canvas canvas(initial_cull);
canvas.ClipRRect(rect_clip, {1, 1}, Entity::ClipOperation::kDifference);
ASSERT_TRUE(canvas.GetCurrentLocalCullingBounds().has_value());
ASSERT_EQ(canvas.GetCurrentLocalCullingBounds().value(), result_cull);
}
TEST(AiksCanvasTest, PathClipIntersectAgainstEmptyCullRect) {
PathBuilder builder;
builder.AddRect(Rect::MakeXYWH(5, 5, 1, 1));
builder.AddRect(Rect::MakeXYWH(5, 14, 1, 1));
builder.AddRect(Rect::MakeXYWH(14, 5, 1, 1));
builder.AddRect(Rect::MakeXYWH(14, 14, 1, 1));
Path path = builder.TakePath();
Rect rect_clip = Rect::MakeXYWH(5, 5, 10, 10);
Canvas canvas;
canvas.ClipPath(path, Entity::ClipOperation::kIntersect);
ASSERT_TRUE(canvas.GetCurrentLocalCullingBounds().has_value());
ASSERT_EQ(canvas.GetCurrentLocalCullingBounds().value(), rect_clip);
}
TEST(AiksCanvasTest, PathClipDiffAgainstEmptyCullRect) {
PathBuilder builder;
builder.AddRect(Rect::MakeXYWH(5, 5, 1, 1));
builder.AddRect(Rect::MakeXYWH(5, 14, 1, 1));
builder.AddRect(Rect::MakeXYWH(14, 5, 1, 1));
builder.AddRect(Rect::MakeXYWH(14, 14, 1, 1));
Path path = builder.TakePath();
Canvas canvas;
canvas.ClipPath(path, Entity::ClipOperation::kDifference);
ASSERT_FALSE(canvas.GetCurrentLocalCullingBounds().has_value());
}
TEST(AiksCanvasTest, PathClipIntersectAgainstCullRect) {
Rect initial_cull = Rect::MakeXYWH(0, 0, 10, 10);
PathBuilder builder;
builder.AddRect(Rect::MakeXYWH(5, 5, 1, 1));
builder.AddRect(Rect::MakeXYWH(5, 14, 1, 1));
builder.AddRect(Rect::MakeXYWH(14, 5, 1, 1));
builder.AddRect(Rect::MakeXYWH(14, 14, 1, 1));
Path path = builder.TakePath();
Rect result_cull = Rect::MakeXYWH(5, 5, 5, 5);
Canvas canvas(initial_cull);
canvas.ClipPath(path, Entity::ClipOperation::kIntersect);
ASSERT_TRUE(canvas.GetCurrentLocalCullingBounds().has_value());
ASSERT_EQ(canvas.GetCurrentLocalCullingBounds().value(), result_cull);
}
TEST(AiksCanvasTest, PathClipDiffAgainstNonCoveredCullRect) {
Rect initial_cull = Rect::MakeXYWH(0, 0, 10, 10);
PathBuilder builder;
builder.AddRect(Rect::MakeXYWH(5, 5, 1, 1));
builder.AddRect(Rect::MakeXYWH(5, 14, 1, 1));
builder.AddRect(Rect::MakeXYWH(14, 5, 1, 1));
builder.AddRect(Rect::MakeXYWH(14, 14, 1, 1));
Path path = builder.TakePath();
Rect result_cull = Rect::MakeXYWH(0, 0, 10, 10);
Canvas canvas(initial_cull);
canvas.ClipPath(path, Entity::ClipOperation::kDifference);
ASSERT_TRUE(canvas.GetCurrentLocalCullingBounds().has_value());
ASSERT_EQ(canvas.GetCurrentLocalCullingBounds().value(), result_cull);
}
TEST(AiksCanvasTest, PathClipDiffAgainstFullyCoveredCullRect) {
Rect initial_cull = Rect::MakeXYWH(5, 5, 10, 10);
PathBuilder builder;
builder.AddRect(Rect::MakeXYWH(0, 0, 100, 100));
Path path = builder.TakePath();
// Diff clip of Paths is ignored due to complexity
Rect result_cull = Rect::MakeXYWH(5, 5, 10, 10);
Canvas canvas(initial_cull);
canvas.ClipPath(path, Entity::ClipOperation::kDifference);
ASSERT_TRUE(canvas.GetCurrentLocalCullingBounds().has_value());
ASSERT_EQ(canvas.GetCurrentLocalCullingBounds().value(), result_cull);
}
TEST(AiksCanvasTest, DisableLocalBoundsRectForFilteredSaveLayers) {
Rect initial_cull = Rect::MakeXYWH(0, 0, 10, 10);
Canvas canvas(initial_cull);
ASSERT_TRUE(canvas.GetCurrentLocalCullingBounds().has_value());
canvas.Save();
canvas.SaveLayer(
Paint{.image_filter = ImageFilter::MakeBlur(
Sigma(10), Sigma(10), FilterContents::BlurStyle::kNormal,
Entity::TileMode::kDecal)});
ASSERT_FALSE(canvas.GetCurrentLocalCullingBounds().has_value());
canvas.Restore();
ASSERT_TRUE(canvas.GetCurrentLocalCullingBounds().has_value());
}
} // namespace testing
} // namespace impeller
// NOLINTEND(bugprone-unchecked-optional-access)
| engine/impeller/aiks/canvas_unittests.cc/0 | {
"file_path": "engine/impeller/aiks/canvas_unittests.cc",
"repo_id": "engine",
"token_count": 4945
} | 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.
#ifndef FLUTTER_IMPELLER_AIKS_PICTURE_RECORDER_H_
#define FLUTTER_IMPELLER_AIKS_PICTURE_RECORDER_H_
#include "flutter/fml/macros.h"
#include "impeller/aiks/canvas.h"
#include "impeller/aiks/picture.h"
namespace impeller {
class PictureRecorder {
public:
PictureRecorder();
~PictureRecorder();
std::shared_ptr<Canvas> GetCanvas() const;
Picture EndRecordingAsPicture();
private:
std::shared_ptr<Canvas> canvas_;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_AIKS_PICTURE_RECORDER_H_
| engine/impeller/aiks/picture_recorder.h/0 | {
"file_path": "engine/impeller/aiks/picture_recorder.h",
"repo_id": "engine",
"token_count": 254
} | 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.
#ifndef FLUTTER_IMPELLER_BASE_MASK_H_
#define FLUTTER_IMPELLER_BASE_MASK_H_
#include <type_traits>
namespace impeller {
template <typename EnumType_>
struct MaskTraits {
static constexpr bool kIsMask = false;
};
//------------------------------------------------------------------------------
/// @brief Declare this in the "impeller" namespace to make the enum
/// maskable.
///
#define IMPELLER_ENUM_IS_MASK(enum_name) \
template <> \
struct MaskTraits<enum_name> { \
static constexpr bool kIsMask = true; \
};
//------------------------------------------------------------------------------
/// @brief A mask of typed enums.
///
/// @tparam EnumType_ The type of the enum. Must be an enum class.
///
template <typename EnumType_>
struct Mask {
using EnumType = EnumType_;
using MaskType = typename std::underlying_type<EnumType>::type;
constexpr Mask() = default;
constexpr Mask(const Mask<EnumType>& other) = default;
constexpr Mask(Mask<EnumType>&& other) = default;
constexpr Mask(EnumType type) // NOLINT(google-explicit-constructor)
: mask_(static_cast<MaskType>(type)) {}
explicit constexpr Mask(MaskType mask) : mask_(static_cast<MaskType>(mask)) {}
// All casts must be explicit.
explicit constexpr operator MaskType() const { return mask_; }
explicit constexpr operator bool() const { return !!mask_; }
// The following relational operators can be replaced with a defaulted
// spaceship operator post C++20.
constexpr bool operator<(const Mask<EnumType>& other) const {
return mask_ < other.mask_;
}
constexpr bool operator>(const Mask<EnumType>& other) const {
return mask_ > other.mask_;
}
constexpr bool operator>=(const Mask<EnumType>& other) const {
return mask_ >= other.mask_;
}
constexpr bool operator<=(const Mask<EnumType>& other) const {
return mask_ <= other.mask_;
}
constexpr bool operator==(const Mask<EnumType>& other) const {
return mask_ == other.mask_;
}
constexpr bool operator!=(const Mask<EnumType>& other) const {
return mask_ != other.mask_;
}
// Logical operators.
constexpr bool operator!() const { return !mask_; }
// Bitwise operators.
constexpr Mask<EnumType> operator&(const Mask<EnumType>& other) const {
return Mask<EnumType>{mask_ & other.mask_};
}
constexpr Mask<EnumType> operator|(const Mask<EnumType>& other) const {
return Mask<EnumType>{mask_ | other.mask_};
}
constexpr Mask<EnumType> operator^(const Mask<EnumType>& other) const {
return Mask<EnumType>{mask_ ^ other.mask_};
}
constexpr Mask<EnumType> operator~() const { return Mask<EnumType>{~mask_}; }
// Assignment operators.
constexpr Mask<EnumType>& operator=(const Mask<EnumType>&) = default;
constexpr Mask<EnumType>& operator=(Mask<EnumType>&&) = default;
constexpr Mask<EnumType>& operator|=(const Mask<EnumType>& other) {
mask_ |= other.mask_;
return *this;
}
constexpr Mask<EnumType>& operator&=(const Mask<EnumType>& other) {
mask_ &= other.mask_;
return *this;
}
constexpr Mask<EnumType>& operator^=(const Mask<EnumType>& other) {
mask_ ^= other.mask_;
return *this;
}
private:
MaskType mask_ = {};
};
// Construction from Enum Types
template <
typename EnumType,
typename std::enable_if<MaskTraits<EnumType>::kIsMask, bool>::type = true>
inline constexpr Mask<EnumType> operator|(const EnumType& lhs,
const EnumType& rhs) {
return Mask<EnumType>{lhs} | rhs;
}
template <
typename EnumType,
typename std::enable_if<MaskTraits<EnumType>::kIsMask, bool>::type = true>
inline constexpr Mask<EnumType> operator&(const EnumType& lhs,
const EnumType& rhs) {
return Mask<EnumType>{lhs} & rhs;
}
template <
typename EnumType,
typename std::enable_if<MaskTraits<EnumType>::kIsMask, bool>::type = true>
inline constexpr Mask<EnumType> operator^(const EnumType& lhs,
const EnumType& rhs) {
return Mask<EnumType>{lhs} ^ rhs;
}
template <
typename EnumType,
typename std::enable_if<MaskTraits<EnumType>::kIsMask, bool>::type = true>
inline constexpr Mask<EnumType> operator~(const EnumType& other) {
return ~Mask<EnumType>{other};
}
template <
typename EnumType,
typename std::enable_if<MaskTraits<EnumType>::kIsMask, bool>::type = true>
inline constexpr Mask<EnumType> operator|(const EnumType& lhs,
const Mask<EnumType>& rhs) {
return Mask<EnumType>{lhs} | rhs;
}
template <
typename EnumType,
typename std::enable_if<MaskTraits<EnumType>::kIsMask, bool>::type = true>
inline constexpr Mask<EnumType> operator&(const EnumType& lhs,
const Mask<EnumType>& rhs) {
return Mask<EnumType>{lhs} & rhs;
}
template <
typename EnumType,
typename std::enable_if<MaskTraits<EnumType>::kIsMask, bool>::type = true>
inline constexpr Mask<EnumType> operator^(const EnumType& lhs,
const Mask<EnumType>& rhs) {
return Mask<EnumType>{lhs} ^ rhs;
}
// Relational operators with EnumType promotion. These can be replaced by a
// defaulted spaceship operator post C++20.
template <typename EnumType,
typename std::enable_if_t<MaskTraits<EnumType>::kIsMask, bool> = true>
inline constexpr bool operator<(const EnumType& lhs,
const Mask<EnumType>& rhs) {
return Mask<EnumType>{lhs} < rhs;
}
template <typename EnumType,
typename std::enable_if_t<MaskTraits<EnumType>::kIsMask, bool> = true>
inline constexpr bool operator>(const EnumType& lhs,
const Mask<EnumType>& rhs) {
return Mask<EnumType>{lhs} > rhs;
}
template <typename EnumType,
typename std::enable_if_t<MaskTraits<EnumType>::kIsMask, bool> = true>
inline constexpr bool operator<=(const EnumType& lhs,
const Mask<EnumType>& rhs) {
return Mask<EnumType>{lhs} <= rhs;
}
template <typename EnumType,
typename std::enable_if_t<MaskTraits<EnumType>::kIsMask, bool> = true>
inline constexpr bool operator>=(const EnumType& lhs,
const Mask<EnumType>& rhs) {
return Mask<EnumType>{lhs} >= rhs;
}
template <typename EnumType,
typename std::enable_if_t<MaskTraits<EnumType>::kIsMask, bool> = true>
inline constexpr bool operator==(const EnumType& lhs,
const Mask<EnumType>& rhs) {
return Mask<EnumType>{lhs} == rhs;
}
template <typename EnumType,
typename std::enable_if_t<MaskTraits<EnumType>::kIsMask, bool> = true>
inline constexpr bool operator!=(const EnumType& lhs,
const Mask<EnumType>& rhs) {
return Mask<EnumType>{lhs} != rhs;
}
} // namespace impeller
#endif // FLUTTER_IMPELLER_BASE_MASK_H_
| engine/impeller/base/mask.h/0 | {
"file_path": "engine/impeller/base/mask.h",
"repo_id": "engine",
"token_count": 2940
} | 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.
#include <string_view>
namespace impeller {
namespace compiler {
constexpr std::string_view kReflectionHeaderTemplate =
R"~~(// THIS FILE IS GENERATED BY impellerc.
// DO NOT EDIT OR CHECK THIS INTO SOURCE CONTROL
#pragma once
{# Note: The nogncheck decorations are only to make GN not mad at the template#}
{# this file is generated from. There are no GN rule violations in the generated#}
{# file itself and the no-check declarations will be stripped in generated files.#}
#include "impeller/core/buffer_view.h" {# // nogncheck #}
#include "impeller/core/sampler.h" {# // nogncheck #}
#include "impeller/core/shader_types.h" {# // nogncheck #}
#include "impeller/core/resource_binder.h" {# // nogncheck #}
#include "impeller/core/texture.h" {# // nogncheck #}
namespace impeller {
struct {{camel_case(shader_name)}}{{camel_case(shader_stage)}}Shader {
// ===========================================================================
// Stage Info ================================================================
// ===========================================================================
static constexpr std::string_view kLabel = "{{camel_case(shader_name)}}";
static constexpr std::string_view kEntrypointName = "{{entrypoint}}";
static constexpr ShaderStage kShaderStage = {{to_shader_stage(shader_stage)}};
// The generator used to prepare these bindings. Metal generators may be used
// by GLES backends but GLES generators are unsuitable for the metal backend.
static constexpr std::string_view kGeneratorName = "{{get_generator_name()}}";
{% if length(struct_definitions) > 0 %}
// ===========================================================================
// Struct Definitions ========================================================
// ===========================================================================
{% for def in struct_definitions %}
{% if last(def.members).array_elements == 0 %}
template <size_t FlexCount>
{% endif %}
struct {{def.name}} {
{% for member in def.members %}
{{" "}}{% if member.element_padding > 0 %}Padded<{{member.type}}, {{member.element_padding}}>{% else %}{{member.type}}{% endif %}{{" " + member.name}}{% if member.array_elements != "std::nullopt" %}[{% if member.array_elements == 0 %}FlexCount{% else %}{{member.array_elements}}{% endif %}]{% endif %}; // (offset {{member.offset}}, size {{member.byte_length}})
{% endfor %}
}; // struct {{def.name}} (size {{def.byte_length}})
{% endfor %}
{% endif %}
{% if length(buffers) > 0 %}
// ===========================================================================
// Stage Uniform & Storage Buffers ===========================================
// ===========================================================================
{% for buffer in buffers %}
static constexpr auto kResource{{camel_case(buffer.name)}} = ShaderUniformSlot { // {{buffer.name}}
"{{buffer.name}}", // name
{{buffer.ext_res_0}}u, // ext_res_0
{{buffer.set}}u, // set
{{buffer.binding}}u, // binding
};
static ShaderMetadata kMetadata{{camel_case(buffer.name)}};
{% endfor %}
{% endif %}
// ===========================================================================
// Stage Inputs ==============================================================
// ===========================================================================
{% if length(stage_inputs) > 0 %}
{% for stage_input in stage_inputs %}
static constexpr auto kInput{{camel_case(stage_input.name)}} = ShaderStageIOSlot { // {{stage_input.name}}
"{{stage_input.name}}", // name
{{stage_input.location}}u, // attribute location
{{stage_input.descriptor_set}}u, // attribute set
{{stage_input.binding}}u, // attribute binding
{{stage_input.type.type_name}}, // type
{{stage_input.type.bit_width}}u, // bit width of type
{{stage_input.type.vec_size}}u, // vec size
{{stage_input.type.columns}}u, // number of columns
{{stage_input.offset}}u, // offset for interleaved layout
};
{% endfor %}
{% endif %}
static constexpr std::array<const ShaderStageIOSlot*, {{length(stage_inputs)}}> kAllShaderStageInputs = {
{% for stage_input in stage_inputs %}
&kInput{{camel_case(stage_input.name)}}, // {{stage_input.name}}
{% endfor %}
};
{% if shader_stage == "vertex" %}
static constexpr auto kInterleavedLayout = ShaderStageBufferLayout {
{% if length(stage_inputs) > 0 %}
sizeof(PerVertexData), // stride for interleaved layout
{% else %}
0u,
{% endif %}
0u, // attribute binding
};
static constexpr std::array<const ShaderStageBufferLayout*, 1> kInterleavedBufferLayout = {
&kInterleavedLayout
};
{% endif %}
{% if length(sampled_images) > 0 %}
// ===========================================================================
// Sampled Images ============================================================
// ===========================================================================
{% for sampled_image in sampled_images %}
static constexpr auto kResource{{camel_case(sampled_image.name)}} = SampledImageSlot { // {{sampled_image.name}}
"{{sampled_image.name}}", // name
{{sampled_image.ext_res_0}}u, // ext_res_0
{{sampled_image.set}}u, // set
{{sampled_image.binding}}u, // binding
};
static ShaderMetadata kMetadata{{camel_case(sampled_image.name)}};
{% endfor %}
{% endif %}
// ===========================================================================
// Stage Outputs =============================================================
// ===========================================================================
{% if length(stage_outputs) > 0 %}
{% for stage_output in stage_outputs %}
static constexpr auto kOutput{{camel_case(stage_output.name)}} = ShaderStageIOSlot { // {{stage_output.name}}
"{{stage_output.name}}", // name
{{stage_output.location}}u, // attribute location
{{stage_output.descriptor_set}}u, // attribute set
{{stage_output.binding}}u, // attribute binding
{{stage_output.type.type_name}}, // type
{{stage_output.type.bit_width}}u, // bit width of type
{{stage_output.type.vec_size}}u, // vec size
{{stage_output.type.columns}}u // number of columns
};
{% endfor %}
static constexpr std::array<const ShaderStageIOSlot*, {{length(stage_outputs)}}> kAllShaderStageOutputs = {
{% for stage_output in stage_outputs %}
&kOutput{{camel_case(stage_output.name)}}, // {{stage_output.name}}
{% endfor %}
};
{% endif %}
// ===========================================================================
// Resource Binding Utilities ================================================
// ===========================================================================
{% for proto in bind_prototypes %}
/// {{proto.docstring}}
static {{proto.return_type}} Bind{{proto.name}}({% for arg in proto.args %}
{{arg.type_name}} {{arg.argument_name}}{% if not loop.is_last %}, {% endif %}
{% endfor %}) {
return {{ proto.args.0.argument_name }}.BindResource({% for arg in proto.args %}
{% if loop.is_first %}
{{to_shader_stage(shader_stage)}}, {{ proto.descriptor_type }}, kResource{{ proto.name }}, kMetadata{{ proto.name }}, {% else %}
std::move({{ arg.argument_name }}){% if not loop.is_last %}, {% endif %}
{% endif %}
{% endfor %});
}
{% endfor %}
// ===========================================================================
// Metadata for Vulkan =======================================================
// ===========================================================================
static constexpr std::array<DescriptorSetLayout,{{length(buffers)+length(sampled_images)+length(subpass_inputs)}}> kDescriptorSetLayouts{
{% for subpass_input in subpass_inputs %}
DescriptorSetLayout{
{{subpass_input.binding}}, // binding = {{subpass_input.binding}}
{{subpass_input.descriptor_type}}, // descriptor_type = {{subpass_input.descriptor_type}}
{{to_shader_stage(shader_stage)}}, // shader_stage = {{to_shader_stage(shader_stage)}}
},
{% endfor %}
{% for buffer in buffers %}
DescriptorSetLayout{
{{buffer.binding}}, // binding = {{buffer.binding}}
{{buffer.descriptor_type}}, // descriptor_type = {{buffer.descriptor_type}}
{{to_shader_stage(shader_stage)}}, // shader_stage = {{to_shader_stage(shader_stage)}}
},
{% endfor %}
{% for sampled_image in sampled_images %}
DescriptorSetLayout{
{{sampled_image.binding}}, // binding = {{sampled_image.binding}}
{{sampled_image.descriptor_type}}, // descriptor_type = {{sampled_image.descriptor_type}}
{{to_shader_stage(shader_stage)}}, // shader_stage = {{to_shader_stage(shader_stage)}}
},
{% endfor %}
};
}; // struct {{camel_case(shader_name)}}{{camel_case(shader_stage)}}Shader
} // namespace impeller
)~~";
constexpr std::string_view kReflectionCCTemplate =
R"~~(// THIS FILE IS GENERATED BY impellerc.
// DO NOT EDIT OR CHECK THIS INTO SOURCE CONTROL
#include "{{header_file_name}}"
#include <type_traits>
namespace impeller {
using Shader = {{camel_case(shader_name)}}{{camel_case(shader_stage)}}Shader;
{% for def in struct_definitions %}
// Sanity checks for {{def.name}}
{% if last(def.members).array_elements == 0 %}
static_assert(std::is_standard_layout_v<Shader::{{def.name}}<0>>);
{% for member in def.members %}
static_assert(offsetof(Shader::{{def.name}}<0>, {{member.name}}) == {{member.offset}});
{% endfor %}
{% else %}
static_assert(std::is_standard_layout_v<Shader::{{def.name}}>);
static_assert(sizeof(Shader::{{def.name}}) == {{def.byte_length}});
{% for member in def.members %}
static_assert(offsetof(Shader::{{def.name}}, {{member.name}}) == {{member.offset}});
{% endfor %}
{% endif %}
{% endfor %}
{% for buffer in buffers %}
ShaderMetadata Shader::kMetadata{{camel_case(buffer.name)}} = {
"{{buffer.name}}", // name
std::vector<ShaderStructMemberMetadata> {
{% for member in buffer.type.members %}
ShaderStructMemberMetadata {
{{ member.base_type }}, // type
"{{ member.name }}", // name
{{ member.offset }}, // offset
{{ member.size }}, // size
{{ member.byte_length }}, // byte_length
{{ member.array_elements }}, // array_elements
},
{% endfor %}
} // members
};
{% endfor %}
{% for sampled_image in sampled_images %}
ShaderMetadata Shader::kMetadata{{camel_case(sampled_image.name)}} = {
"{{sampled_image.name}}", // name
std::vector<ShaderStructMemberMetadata> {}, // 0 members
};
{% endfor %}
} // namespace impeller
)~~";
} // namespace compiler
} // namespace impeller
| engine/impeller/compiler/code_gen_template.h/0 | {
"file_path": "engine/impeller/compiler/code_gen_template.h",
"repo_id": "engine",
"token_count": 3753
} | 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.
#ifndef FLUTTER_IMPELLER_COMPILER_REFLECTOR_H_
#define FLUTTER_IMPELLER_COMPILER_REFLECTOR_H_
#include <cstdint>
#include <memory>
#include <optional>
#include "flutter/fml/macros.h"
#include "flutter/fml/mapping.h"
#include "fml/logging.h"
#include "impeller/base/strings.h"
#include "impeller/compiler/compiler_backend.h"
#include "impeller/compiler/runtime_stage_data.h"
#include "impeller/compiler/shader_bundle_data.h"
#include "inja/inja.hpp"
#include "spirv_common.hpp"
#include "spirv_msl.hpp"
#include "spirv_parser.hpp"
namespace impeller {
namespace compiler {
struct StructMember {
// Runtime stages on Vulkan use this information to validate that a struct
// only contains floats and encode where padding gets inserted.
enum class UnderlyingType {
kPadding,
kFloat,
kOther,
};
std::string type;
spirv_cross::SPIRType::BaseType base_type;
std::string name;
size_t offset = 0u;
size_t size = 0u;
size_t byte_length = 0u;
std::optional<size_t> array_elements = std::nullopt;
size_t element_padding = 0u;
UnderlyingType underlying_type = UnderlyingType::kOther;
static std::string BaseTypeToString(spirv_cross::SPIRType::BaseType type) {
using Type = spirv_cross::SPIRType::BaseType;
switch (type) {
case Type::Void:
return "ShaderType::kVoid";
case Type::Boolean:
return "ShaderType::kBoolean";
case Type::SByte:
return "ShaderType::kSignedByte";
case Type::UByte:
return "ShaderType::kUnsignedByte";
case Type::Short:
return "ShaderType::kSignedShort";
case Type::UShort:
return "ShaderType::kUnsignedShort";
case Type::Int:
return "ShaderType::kSignedInt";
case Type::UInt:
return "ShaderType::kUnsignedInt";
case Type::Int64:
return "ShaderType::kSignedInt64";
case Type::UInt64:
return "ShaderType::kUnsignedInt64";
case Type::AtomicCounter:
return "ShaderType::kAtomicCounter";
case Type::Half:
return "ShaderType::kHalfFloat";
case Type::Float:
return "ShaderType::kFloat";
case Type::Double:
return "ShaderType::kDouble";
case Type::Struct:
return "ShaderType::kStruct";
case Type::Image:
return "ShaderType::kImage";
case Type::SampledImage:
return "ShaderType::kSampledImage";
case Type::Sampler:
return "ShaderType::kSampler";
default:
return "ShaderType::kUnknown";
}
FML_UNREACHABLE();
}
static UnderlyingType DetermineUnderlyingType(
spirv_cross::SPIRType::BaseType type) {
switch (type) {
case spirv_cross::SPIRType::Void:
return UnderlyingType::kPadding;
case spirv_cross::SPIRType::Float:
return UnderlyingType::kFloat;
case spirv_cross::SPIRType::Unknown:
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::AtomicCounter:
case spirv_cross::SPIRType::Half:
case spirv_cross::SPIRType::Double:
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:
default:
return UnderlyingType::kOther;
}
FML_UNREACHABLE();
}
StructMember(std::string p_type,
spirv_cross::SPIRType::BaseType p_base_type,
std::string p_name,
size_t p_offset,
size_t p_size,
size_t p_byte_length,
std::optional<size_t> p_array_elements,
size_t p_element_padding,
UnderlyingType p_underlying_type = UnderlyingType::kOther)
: type(std::move(p_type)),
base_type(p_base_type),
name(std::move(p_name)),
offset(p_offset),
size(p_size),
byte_length(p_byte_length),
array_elements(p_array_elements),
element_padding(p_element_padding),
underlying_type(DetermineUnderlyingType(p_base_type)) {}
};
class Reflector {
public:
struct Options {
TargetPlatform target_platform = TargetPlatform::kUnknown;
std::string entry_point_name;
std::string shader_name;
std::string header_file_name;
};
Reflector(Options options,
const std::shared_ptr<const spirv_cross::ParsedIR>& ir,
const std::shared_ptr<fml::Mapping>& shader_data,
const CompilerBackend& compiler);
~Reflector();
bool IsValid() const;
std::shared_ptr<fml::Mapping> GetReflectionJSON() const;
std::shared_ptr<fml::Mapping> GetReflectionHeader() const;
std::shared_ptr<fml::Mapping> GetReflectionCC() const;
std::shared_ptr<RuntimeStageData::Shader> GetRuntimeStageShaderData() const;
std::shared_ptr<ShaderBundleData> GetShaderBundleData() const;
private:
struct StructDefinition {
std::string name;
size_t byte_length = 0u;
std::vector<StructMember> members;
};
struct BindPrototypeArgument {
std::string type_name;
std::string argument_name;
};
struct BindPrototype {
std::string name;
std::string return_type;
std::string docstring;
std::string descriptor_type = "";
std::vector<BindPrototypeArgument> args;
};
const Options options_;
const std::shared_ptr<const spirv_cross::ParsedIR> ir_;
const std::shared_ptr<fml::Mapping> shader_data_;
const CompilerBackend compiler_;
std::unique_ptr<const nlohmann::json> template_arguments_;
std::shared_ptr<fml::Mapping> reflection_header_;
std::shared_ptr<fml::Mapping> reflection_cc_;
std::shared_ptr<RuntimeStageData::Shader> runtime_stage_shader_;
std::shared_ptr<ShaderBundleData> shader_bundle_data_;
bool is_valid_ = false;
std::optional<nlohmann::json> GenerateTemplateArguments() const;
std::shared_ptr<fml::Mapping> GenerateReflectionHeader() const;
std::shared_ptr<fml::Mapping> GenerateReflectionCC() const;
std::shared_ptr<RuntimeStageData::Shader> GenerateRuntimeStageData() const;
std::shared_ptr<ShaderBundleData> GenerateShaderBundleData() const;
std::shared_ptr<fml::Mapping> InflateTemplate(std::string_view tmpl) const;
std::optional<nlohmann::json::object_t> ReflectResource(
const spirv_cross::Resource& resource,
std::optional<size_t> offset) const;
std::optional<nlohmann::json::array_t> ReflectResources(
const spirv_cross::SmallVector<spirv_cross::Resource>& resources,
bool compute_offsets = false) const;
std::vector<size_t> ComputeOffsets(
const spirv_cross::SmallVector<spirv_cross::Resource>& resources) const;
std::optional<size_t> GetOffset(spirv_cross::ID id,
const std::vector<size_t>& offsets) const;
std::optional<nlohmann::json::object_t> ReflectType(
const spirv_cross::TypeID& type_id) const;
nlohmann::json::object_t EmitStructDefinition(
std::optional<Reflector::StructDefinition> struc) const;
std::optional<StructDefinition> ReflectStructDefinition(
const spirv_cross::TypeID& type_id) const;
std::vector<BindPrototype> ReflectBindPrototypes(
const spirv_cross::ShaderResources& resources,
spv::ExecutionModel execution_model) const;
nlohmann::json::array_t EmitBindPrototypes(
const spirv_cross::ShaderResources& resources,
spv::ExecutionModel execution_model) const;
std::optional<StructDefinition> ReflectPerVertexStructDefinition(
const spirv_cross::SmallVector<spirv_cross::Resource>& stage_inputs)
const;
std::optional<std::string> GetMemberNameAtIndexIfExists(
const spirv_cross::SPIRType& parent_type,
size_t index) const;
std::string GetMemberNameAtIndex(const spirv_cross::SPIRType& parent_type,
size_t index,
std::string suffix = "") const;
std::vector<StructMember> ReadStructMembers(
const spirv_cross::TypeID& type_id) const;
std::optional<uint32_t> GetArrayElements(
const spirv_cross::SPIRType& type) const;
template <uint32_t Size>
uint32_t GetArrayStride(const spirv_cross::SPIRType& struct_type,
const spirv_cross::SPIRType& member_type,
uint32_t index) const {
auto element_count = GetArrayElements(member_type).value_or(1);
if (element_count <= 1) {
return Size;
}
return compiler_->type_struct_member_array_stride(struct_type, index);
};
Reflector(const Reflector&) = delete;
Reflector& operator=(const Reflector&) = delete;
};
} // namespace compiler
} // namespace impeller
#endif // FLUTTER_IMPELLER_COMPILER_REFLECTOR_H_
| engine/impeller/compiler/reflector.h/0 | {
"file_path": "engine/impeller/compiler/reflector.h",
"repo_id": "engine",
"token_count": 3787
} | 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.
#ifndef CONVERSIONS_GLSL_
#define CONVERSIONS_GLSL_
vec2 IPRemapCoords(vec2 coords, float y_coord_scale) {
if (y_coord_scale < 0.0) {
coords.y = 1.0 - coords.y;
}
return coords;
}
#endif
| engine/impeller/compiler/shader_lib/impeller/conversions.glsl/0 | {
"file_path": "engine/impeller/compiler/shader_lib/impeller/conversions.glsl",
"repo_id": "engine",
"token_count": 138
} | 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.
#ifndef FLUTTER_IMPELLER_COMPILER_SPIRV_SKSL_H_
#define FLUTTER_IMPELLER_COMPILER_SPIRV_SKSL_H_
#include <cstdint>
#include <memory>
#include <utility>
#include <variant>
#include "flutter/fml/logging.h"
#include "spirv_glsl.hpp"
namespace impeller {
namespace compiler {
class CompilerSkSL : public spirv_cross::CompilerGLSL {
public:
explicit CompilerSkSL(std::vector<uint32_t> spirv_)
: CompilerGLSL(std::move(spirv_)) {}
CompilerSkSL(const uint32_t* ir_, size_t word_count)
: CompilerGLSL(ir_, word_count) {}
explicit CompilerSkSL(const spirv_cross::ParsedIR& ir_)
: spirv_cross::CompilerGLSL(ir_) {}
explicit CompilerSkSL(spirv_cross::ParsedIR&& ir_)
: spirv_cross::CompilerGLSL(std::move(ir_)) {}
std::string compile() override;
private:
std::string output_name_;
void emit_header() override;
void emit_uniform(const spirv_cross::SPIRVariable& var) override;
void fixup_user_functions();
void detect_unsupported_resources();
bool emit_constant_resources();
bool emit_struct_resources();
bool emit_uniform_resources();
bool emit_output_resources();
bool emit_global_variable_resources();
bool emit_undefined_values();
void emit_resources();
void emit_interface_block(const spirv_cross::SPIRVariable& var);
void emit_function_prototype(
spirv_cross::SPIRFunction& func,
const spirv_cross::Bitset& return_flags) override;
std::string image_type_glsl(const spirv_cross::SPIRType& type,
uint32_t id = 0,
bool member = false) override;
std::string builtin_to_glsl(spv::BuiltIn builtin,
spv::StorageClass storage) override;
std::string to_texture_op(
const spirv_cross::Instruction& i,
bool sparse,
bool* forward,
spirv_cross::SmallVector<uint32_t>& inherited_expressions) override;
std::string to_function_name(
const spirv_cross::CompilerGLSL::TextureFunctionNameArguments& args)
override;
std::string to_function_args(
const spirv_cross::CompilerGLSL::TextureFunctionArguments& args,
bool* p_forward) override;
};
} // namespace compiler
} // namespace impeller
#endif // FLUTTER_IMPELLER_COMPILER_SPIRV_SKSL_H_
| engine/impeller/compiler/spirv_sksl.h/0 | {
"file_path": "engine/impeller/compiler/spirv_sksl.h",
"repo_id": "engine",
"token_count": 948
} | 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.
#include "impeller/core/capture.h"
#include <initializer_list>
#include <memory>
namespace impeller {
//-----------------------------------------------------------------------------
/// CaptureProperty
///
CaptureProperty::CaptureProperty(const std::string& label, Options options)
: CaptureCursorListElement(label), options(options) {}
CaptureProperty::~CaptureProperty() = default;
bool CaptureProperty::MatchesCloselyEnough(const CaptureProperty& other) const {
if (label != other.label) {
return false;
}
if (GetType() != other.GetType()) {
return false;
}
return true;
}
#define _CAPTURE_PROPERTY_CAST_DEFINITION(type_name, pascal_name, lower_name) \
std::optional<type_name> CaptureProperty::As##pascal_name() const { \
if (GetType() != Type::k##pascal_name) { \
return std::nullopt; \
} \
return reinterpret_cast<const Capture##pascal_name##Property*>(this) \
->value; \
}
_FOR_EACH_CAPTURE_PROPERTY(_CAPTURE_PROPERTY_CAST_DEFINITION);
#define _CAPTURE_PROPERTY_DEFINITION(type_name, pascal_name, lower_name) \
Capture##pascal_name##Property::Capture##pascal_name##Property( \
const std::string& label, type_name value, Options options) \
: CaptureProperty(label, options), value(std::move(value)) {} \
\
std::shared_ptr<Capture##pascal_name##Property> \
Capture##pascal_name##Property::Make(const std::string& label, \
type_name value, Options options) { \
auto result = std::shared_ptr<Capture##pascal_name##Property>( \
new Capture##pascal_name##Property(label, std::move(value), options)); \
return result; \
} \
\
CaptureProperty::Type Capture##pascal_name##Property::GetType() const { \
return Type::k##pascal_name; \
} \
\
void Capture##pascal_name##Property::Invoke( \
const CaptureProcTable& proc_table) { \
proc_table.lower_name(*this); \
}
_FOR_EACH_CAPTURE_PROPERTY(_CAPTURE_PROPERTY_DEFINITION);
//-----------------------------------------------------------------------------
/// CaptureElement
///
CaptureElement::CaptureElement(const std::string& label)
: CaptureCursorListElement(label) {}
std::shared_ptr<CaptureElement> CaptureElement::Make(const std::string& label) {
return std::shared_ptr<CaptureElement>(new CaptureElement(label));
}
void CaptureElement::Rewind() {
properties.Rewind();
children.Rewind();
}
bool CaptureElement::MatchesCloselyEnough(const CaptureElement& other) const {
return label == other.label;
}
//-----------------------------------------------------------------------------
/// Capture
///
Capture::Capture() = default;
#ifdef IMPELLER_ENABLE_CAPTURE
Capture::Capture(const std::string& label)
: element_(CaptureElement::Make(label)), active_(true) {
element_->label = label;
}
#else
Capture::Capture(const std::string& label) {}
#endif
Capture Capture::MakeInactive() {
return Capture();
}
std::shared_ptr<CaptureElement> Capture::GetElement() const {
#ifdef IMPELLER_ENABLE_CAPTURE
return element_;
#else
return nullptr;
#endif
}
void Capture::Rewind() {
return GetElement()->Rewind();
}
#ifdef IMPELLER_ENABLE_CAPTURE
#define _CAPTURE_PROPERTY_RECORDER_DEFINITION(type_name, pascal_name, \
lower_name) \
type_name Capture::Add##pascal_name(std::string_view label, type_name value, \
CaptureProperty::Options options) { \
if (!active_) { \
return value; \
} \
FML_DCHECK(element_ != nullptr); \
\
std::string label_clone = std::string(label); \
auto new_value = Capture##pascal_name##Property::Make( \
label_clone, std::move(value), options); \
\
auto next = std::reinterpret_pointer_cast<Capture##pascal_name##Property>( \
element_->properties.GetNext(std::move(new_value), options.readonly)); \
\
return next->value; \
}
_FOR_EACH_CAPTURE_PROPERTY(_CAPTURE_PROPERTY_RECORDER_DEFINITION);
#endif
//-----------------------------------------------------------------------------
/// CaptureContext
///
#ifdef IMPELLER_ENABLE_CAPTURE
CaptureContext::CaptureContext() : active_(true) {}
CaptureContext::CaptureContext(std::initializer_list<std::string> allowlist)
: active_(true), allowlist_(allowlist) {}
#else
CaptureContext::CaptureContext() {}
CaptureContext::CaptureContext(std::initializer_list<std::string> allowlist) {}
#endif
CaptureContext::CaptureContext(CaptureContext::InactiveFlag) {}
CaptureContext CaptureContext::MakeInactive() {
return CaptureContext(InactiveFlag{});
}
CaptureContext CaptureContext::MakeAllowlist(
std::initializer_list<std::string> allowlist) {
return CaptureContext(allowlist);
}
bool CaptureContext::IsActive() const {
#ifdef IMPELLER_ENABLE_CAPTURE
return active_;
#else
return false;
#endif
}
void CaptureContext::Rewind() {
#ifdef IMPELLER_ENABLE_CAPTURE
for (auto& [name, capture] : documents_) {
capture.GetElement()->Rewind();
}
#else
return;
#endif
}
Capture CaptureContext::GetDocument(const std::string& label) {
#ifdef IMPELLER_ENABLE_CAPTURE
if (!active_) {
return Capture::MakeInactive();
}
if (allowlist_.has_value()) {
if (allowlist_->find(label) == allowlist_->end()) {
return Capture::MakeInactive();
}
}
auto found = documents_.find(label);
if (found != documents_.end()) {
// Always rewind when fetching an existing document.
found->second.Rewind();
return found->second;
}
auto new_document = Capture(label);
documents_.emplace(label, new_document);
return new_document;
#else
return Capture::MakeInactive();
#endif
}
bool CaptureContext::DoesDocumentExist(const std::string& label) const {
#ifdef IMPELLER_ENABLE_CAPTURE
if (!active_) {
return false;
}
return documents_.find(label) != documents_.end();
#else
return false;
#endif
}
} // namespace impeller
| engine/impeller/core/capture.cc/0 | {
"file_path": "engine/impeller/core/capture.cc",
"repo_id": "engine",
"token_count": 3644
} | 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.
#include "impeller/core/runtime_types.h"
namespace impeller {
size_t RuntimeUniformDescription::GetSize() const {
size_t size = dimensions.rows * dimensions.cols * bit_width / 8u;
if (array_elements.value_or(0) > 0) {
// Covered by check on the line above.
// NOLINTNEXTLINE(bugprone-unchecked-optional-access)
size *= array_elements.value();
}
size += sizeof(float) * struct_layout.size();
return size;
}
} // namespace impeller
| engine/impeller/core/runtime_types.cc/0 | {
"file_path": "engine/impeller/core/runtime_types.cc",
"repo_id": "engine",
"token_count": 205
} | 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.
#ifndef FLUTTER_IMPELLER_DISPLAY_LIST_DL_DISPATCHER_H_
#define FLUTTER_IMPELLER_DISPLAY_LIST_DL_DISPATCHER_H_
#include "flutter/display_list/dl_op_receiver.h"
#include "impeller/aiks/canvas_type.h"
#include "impeller/aiks/paint.h"
namespace impeller {
class DlDispatcher final : public flutter::DlOpReceiver {
public:
DlDispatcher();
explicit DlDispatcher(Rect cull_rect);
explicit DlDispatcher(IRect cull_rect);
~DlDispatcher();
Picture EndRecordingAsPicture();
// |flutter::DlOpReceiver|
bool PrefersImpellerPaths() const override { return true; }
// |flutter::DlOpReceiver|
void setAntiAlias(bool aa) override;
// |flutter::DlOpReceiver|
void setDrawStyle(flutter::DlDrawStyle style) override;
// |flutter::DlOpReceiver|
void setColor(flutter::DlColor color) override;
// |flutter::DlOpReceiver|
void setStrokeWidth(SkScalar width) override;
// |flutter::DlOpReceiver|
void setStrokeMiter(SkScalar limit) override;
// |flutter::DlOpReceiver|
void setStrokeCap(flutter::DlStrokeCap cap) override;
// |flutter::DlOpReceiver|
void setStrokeJoin(flutter::DlStrokeJoin join) override;
// |flutter::DlOpReceiver|
void setColorSource(const flutter::DlColorSource* source) override;
// |flutter::DlOpReceiver|
void setColorFilter(const flutter::DlColorFilter* filter) override;
// |flutter::DlOpReceiver|
void setInvertColors(bool invert) override;
// |flutter::DlOpReceiver|
void setBlendMode(flutter::DlBlendMode mode) override;
// |flutter::DlOpReceiver|
void setPathEffect(const flutter::DlPathEffect* effect) override;
// |flutter::DlOpReceiver|
void setMaskFilter(const flutter::DlMaskFilter* filter) override;
// |flutter::DlOpReceiver|
void setImageFilter(const flutter::DlImageFilter* filter) override;
// |flutter::DlOpReceiver|
void save() override;
// |flutter::DlOpReceiver|
void saveLayer(const SkRect& bounds,
const flutter::SaveLayerOptions options,
const flutter::DlImageFilter* backdrop) override;
// |flutter::DlOpReceiver|
void restore() override;
// |flutter::DlOpReceiver|
void translate(SkScalar tx, SkScalar ty) override;
// |flutter::DlOpReceiver|
void scale(SkScalar sx, SkScalar sy) override;
// |flutter::DlOpReceiver|
void rotate(SkScalar degrees) override;
// |flutter::DlOpReceiver|
void skew(SkScalar sx, SkScalar sy) override;
// |flutter::DlOpReceiver|
void transform2DAffine(SkScalar mxx,
SkScalar mxy,
SkScalar mxt,
SkScalar myx,
SkScalar myy,
SkScalar myt) override;
// |flutter::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;
// |flutter::DlOpReceiver|
void transformReset() override;
// |flutter::DlOpReceiver|
void clipRect(const SkRect& rect, ClipOp clip_op, bool is_aa) override;
// |flutter::DlOpReceiver|
void clipRRect(const SkRRect& rrect, ClipOp clip_op, bool is_aa) override;
// |flutter::DlOpReceiver|
void clipPath(const SkPath& path, ClipOp clip_op, bool is_aa) override;
// |flutter::DlOpReceiver|
void clipPath(const CacheablePath& cache,
ClipOp clip_op,
bool is_aa) override;
// |flutter::DlOpReceiver|
void drawColor(flutter::DlColor color, flutter::DlBlendMode mode) override;
// |flutter::DlOpReceiver|
void drawPaint() override;
// |flutter::DlOpReceiver|
void drawLine(const SkPoint& p0, const SkPoint& p1) override;
// |flutter::DlOpReceiver|
void drawRect(const SkRect& rect) override;
// |flutter::DlOpReceiver|
void drawOval(const SkRect& bounds) override;
// |flutter::DlOpReceiver|
void drawCircle(const SkPoint& center, SkScalar radius) override;
// |flutter::DlOpReceiver|
void drawRRect(const SkRRect& rrect) override;
// |flutter::DlOpReceiver|
void drawDRRect(const SkRRect& outer, const SkRRect& inner) override;
// |flutter::DlOpReceiver|
void drawPath(const SkPath& path) override;
// |flutter::DlOpReceiver|
void drawPath(const CacheablePath& cache) override;
// |flutter::DlOpReceiver|
void drawArc(const SkRect& oval_bounds,
SkScalar start_degrees,
SkScalar sweep_degrees,
bool use_center) override;
// |flutter::DlOpReceiver|
void drawPoints(PointMode mode,
uint32_t count,
const SkPoint points[]) override;
// |flutter::DlOpReceiver|
void drawVertices(const flutter::DlVertices* vertices,
flutter::DlBlendMode dl_mode) override;
// |flutter::DlOpReceiver|
void drawImage(const sk_sp<flutter::DlImage> image,
const SkPoint point,
flutter::DlImageSampling sampling,
bool render_with_attributes) override;
// |flutter::DlOpReceiver|
void drawImageRect(const sk_sp<flutter::DlImage> image,
const SkRect& src,
const SkRect& dst,
flutter::DlImageSampling sampling,
bool render_with_attributes,
SrcRectConstraint constraint) override;
// |flutter::DlOpReceiver|
void drawImageNine(const sk_sp<flutter::DlImage> image,
const SkIRect& center,
const SkRect& dst,
flutter::DlFilterMode filter,
bool render_with_attributes) override;
// |flutter::DlOpReceiver|
void drawAtlas(const sk_sp<flutter::DlImage> atlas,
const SkRSXform xform[],
const SkRect tex[],
const flutter::DlColor colors[],
int count,
flutter::DlBlendMode mode,
flutter::DlImageSampling sampling,
const SkRect* cull_rect,
bool render_with_attributes) override;
// |flutter::DlOpReceiver|
void drawDisplayList(const sk_sp<flutter::DisplayList> display_list,
SkScalar opacity) override;
// |flutter::DlOpReceiver|
void drawTextBlob(const sk_sp<SkTextBlob> blob,
SkScalar x,
SkScalar y) override;
// |flutter::DlOpReceiver|
void drawTextFrame(const std::shared_ptr<impeller::TextFrame>& text_frame,
SkScalar x,
SkScalar y) override;
// |flutter::DlOpReceiver|
void drawShadow(const SkPath& path,
const flutter::DlColor color,
const SkScalar elevation,
bool transparent_occluder,
SkScalar dpr) override;
// |flutter::DlOpReceiver|
void drawShadow(const CacheablePath& cache,
const flutter::DlColor color,
const SkScalar elevation,
bool transparent_occluder,
SkScalar dpr) override;
private:
Paint paint_;
CanvasType canvas_;
Matrix initial_matrix_;
static const Path& GetOrCachePath(const CacheablePath& cache);
static void SimplifyOrDrawPath(CanvasType& canvas,
const CacheablePath& cache,
const Paint& paint);
DlDispatcher(const DlDispatcher&) = delete;
DlDispatcher& operator=(const DlDispatcher&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_DISPLAY_LIST_DL_DISPATCHER_H_
| engine/impeller/display_list/dl_dispatcher.h/0 | {
"file_path": "engine/impeller/display_list/dl_dispatcher.h",
"repo_id": "engine",
"token_count": 3918
} | 216 |
# iOS CPU Profiling
XCode has a number of built in profiling tools that can easily be used with local or prebuilt engines. This document is focused on creating flame graph charts, which is not a part of XCode but provides a useful way to look at aggregate performance. Compared to the Android Studio flame graph this one is a little wonky, but still useful.
1. Clone the "FlameGraph" swift package from `https://github.com/lennet/FlameGraph`
2. Start a "Time Profiler" based profile session.

Click the red dot to begin and record as much profile data as you want, then press stop to conclude the trace.
3. Select the thread to investigate, in this case you want io.flutter.raster. IMPORTANT: also select the trace root.

4. Copy the trace with the keyboard shortcut (⇧⌘C) or the menu ("Edit" -> "Deep Copy").

5. On the command line, run `swift run FlameGraph --html output.html`
A new browser tab will open with the flame graph. It may require some zooming to be useful.
 | engine/impeller/docs/ios_cpu_profile.md/0 | {
"file_path": "engine/impeller/docs/ios_cpu_profile.md",
"repo_id": "engine",
"token_count": 344
} | 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.
#include <memory>
#include <optional>
#include "gtest/gtest.h"
#include "impeller/entity/contents/checkerboard_contents.h"
#include "impeller/entity/contents/contents.h"
#include "impeller/entity/contents/test/recording_render_pass.h"
#include "impeller/entity/entity.h"
#include "impeller/entity/entity_playground.h"
#include "impeller/renderer/render_target.h"
namespace impeller {
namespace testing {
using EntityTest = EntityPlayground;
#ifdef IMPELLER_DEBUG
TEST(EntityTest, HasNulloptCoverage) {
auto contents = std::make_shared<CheckerboardContents>();
Entity entity;
ASSERT_EQ(contents->GetCoverage(entity), std::nullopt);
}
TEST_P(EntityTest, RendersWithoutError) {
auto contents = std::make_shared<CheckerboardContents>();
contents->SetColor(Color::Aqua());
contents->SetSquareSize(10);
auto content_context = GetContentContext();
auto buffer = content_context->GetContext()->CreateCommandBuffer();
auto render_target =
GetContentContext()->GetRenderTargetCache()->CreateOffscreenMSAA(
*content_context->GetContext(), {100, 100},
/*mip_count=*/1);
auto render_pass = buffer->CreateRenderPass(render_target);
auto recording_pass = std::make_shared<RecordingRenderPass>(
render_pass, GetContext(), render_target);
Entity entity;
ASSERT_TRUE(recording_pass->GetCommands().empty());
ASSERT_TRUE(contents->Render(*content_context, entity, *recording_pass));
ASSERT_FALSE(recording_pass->GetCommands().empty());
if (GetParam() == PlaygroundBackend::kMetal) {
recording_pass->EncodeCommands();
}
}
#endif // IMPELLER_DEBUG
} // namespace testing
} // namespace impeller
| engine/impeller/entity/contents/checkerboard_contents_unittests.cc/0 | {
"file_path": "engine/impeller/entity/contents/checkerboard_contents_unittests.cc",
"repo_id": "engine",
"token_count": 606
} | 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.
#include "impeller/entity/contents/filters/color_filter_contents.h"
#include <utility>
#include "impeller/base/validation.h"
#include "impeller/entity/contents/filters/blend_filter_contents.h"
#include "impeller/entity/contents/filters/color_matrix_filter_contents.h"
#include "impeller/entity/contents/filters/linear_to_srgb_filter_contents.h"
#include "impeller/entity/contents/filters/srgb_to_linear_filter_contents.h"
namespace impeller {
std::shared_ptr<ColorFilterContents> ColorFilterContents::MakeBlend(
BlendMode blend_mode,
FilterInput::Vector inputs,
std::optional<Color> foreground_color) {
if (blend_mode > Entity::kLastAdvancedBlendMode) {
VALIDATION_LOG << "Invalid blend mode " << static_cast<int>(blend_mode)
<< " passed to ColorFilterContents::MakeBlend.";
return nullptr;
}
size_t total_inputs = inputs.size() + (foreground_color.has_value() ? 1 : 0);
if (total_inputs < 2 || blend_mode <= Entity::kLastPipelineBlendMode) {
auto blend = std::make_shared<BlendFilterContents>();
blend->SetInputs(inputs);
blend->SetBlendMode(blend_mode);
blend->SetForegroundColor(foreground_color);
return blend;
}
auto blend_input = inputs[0];
std::shared_ptr<BlendFilterContents> new_blend;
for (auto in_i = inputs.begin() + 1; in_i < inputs.end(); in_i++) {
new_blend = std::make_shared<BlendFilterContents>();
new_blend->SetInputs({blend_input, *in_i});
new_blend->SetBlendMode(blend_mode);
if (in_i < inputs.end() - 1 || foreground_color.has_value()) {
blend_input = FilterInput::Make(
std::static_pointer_cast<FilterContents>(new_blend));
}
}
if (foreground_color.has_value()) {
new_blend = std::make_shared<BlendFilterContents>();
new_blend->SetInputs({blend_input});
new_blend->SetBlendMode(blend_mode);
new_blend->SetForegroundColor(foreground_color);
}
return new_blend;
}
std::shared_ptr<ColorFilterContents> ColorFilterContents::MakeColorMatrix(
FilterInput::Ref input,
const ColorMatrix& color_matrix) {
auto filter = std::make_shared<ColorMatrixFilterContents>();
filter->SetInputs({std::move(input)});
filter->SetMatrix(color_matrix);
return filter;
}
std::shared_ptr<ColorFilterContents>
ColorFilterContents::MakeLinearToSrgbFilter(FilterInput::Ref input) {
auto filter = std::make_shared<LinearToSrgbFilterContents>();
filter->SetInputs({std::move(input)});
return filter;
}
std::shared_ptr<ColorFilterContents>
ColorFilterContents::MakeSrgbToLinearFilter(FilterInput::Ref input) {
auto filter = std::make_shared<SrgbToLinearFilterContents>();
filter->SetInputs({std::move(input)});
return filter;
}
ColorFilterContents::ColorFilterContents() = default;
ColorFilterContents::~ColorFilterContents() = default;
void ColorFilterContents::SetAbsorbOpacity(AbsorbOpacity absorb_opacity) {
absorb_opacity_ = absorb_opacity;
}
ColorFilterContents::AbsorbOpacity ColorFilterContents::GetAbsorbOpacity()
const {
return absorb_opacity_;
}
void ColorFilterContents::SetAlpha(Scalar alpha) {
alpha_ = alpha;
}
std::optional<Scalar> ColorFilterContents::GetAlpha() const {
return alpha_;
}
std::optional<Rect> ColorFilterContents::GetFilterSourceCoverage(
const Matrix& effect_transform,
const Rect& output_limit) const {
return output_limit;
}
} // namespace impeller
| engine/impeller/entity/contents/filters/color_filter_contents.cc/0 | {
"file_path": "engine/impeller/entity/contents/filters/color_filter_contents.cc",
"repo_id": "engine",
"token_count": 1247
} | 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/entity/contents/filters/inputs/placeholder_filter_input.h"
#include <optional>
#include <utility>
#include "impeller/base/strings.h"
namespace impeller {
PlaceholderFilterInput::PlaceholderFilterInput(Rect coverage_rect)
: coverage_rect_(coverage_rect) {}
PlaceholderFilterInput::~PlaceholderFilterInput() = default;
FilterInput::Variant PlaceholderFilterInput::GetInput() const {
return coverage_rect_;
}
std::optional<Snapshot> PlaceholderFilterInput::GetSnapshot(
const std::string& label,
const ContentContext& renderer,
const Entity& entity,
std::optional<Rect> coverage_limit,
int32_t mip_count) const {
return std::nullopt;
}
std::optional<Rect> PlaceholderFilterInput::GetCoverage(
const Entity& entity) const {
return coverage_rect_;
}
void PlaceholderFilterInput::PopulateGlyphAtlas(
const std::shared_ptr<LazyGlyphAtlas>& lazy_glyph_atlas,
Scalar scale) {}
} // namespace impeller
| engine/impeller/entity/contents/filters/inputs/placeholder_filter_input.cc/0 | {
"file_path": "engine/impeller/entity/contents/filters/inputs/placeholder_filter_input.cc",
"repo_id": "engine",
"token_count": 368
} | 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.
#include "framebuffer_blend_contents.h"
#include "impeller/entity/contents/content_context.h"
#include "impeller/renderer/render_pass.h"
namespace impeller {
FramebufferBlendContents::FramebufferBlendContents() = default;
FramebufferBlendContents::~FramebufferBlendContents() = default;
void FramebufferBlendContents::SetBlendMode(BlendMode blend_mode) {
blend_mode_ = blend_mode;
}
void FramebufferBlendContents::SetChildContents(
std::shared_ptr<Contents> child_contents) {
child_contents_ = std::move(child_contents);
}
// |Contents|
std::optional<Rect> FramebufferBlendContents::GetCoverage(
const Entity& entity) const {
return child_contents_->GetCoverage(entity);
}
bool FramebufferBlendContents::Render(const ContentContext& renderer,
const Entity& entity,
RenderPass& pass) const {
if (!renderer.GetDeviceCapabilities().SupportsFramebufferFetch()) {
return false;
}
using VS = FramebufferBlendScreenPipeline::VertexShader;
using FS = FramebufferBlendScreenPipeline::FragmentShader;
auto& host_buffer = renderer.GetTransientsBuffer();
auto src_snapshot = child_contents_->RenderToSnapshot(
renderer, // renderer
entity, // entity
Rect::MakeSize(pass.GetRenderTargetSize()), // coverage_limit
std::nullopt, // sampler_descriptor
true, // msaa_enabled
/*mip_count=*/1,
"FramebufferBlendContents Snapshot"); // label
if (!src_snapshot.has_value()) {
return true;
}
auto coverage = src_snapshot->GetCoverage();
if (!coverage.has_value()) {
return true;
}
Rect src_coverage = coverage.value();
auto size = src_coverage.GetSize();
VertexBufferBuilder<VS::PerVertexData> vtx_builder;
vtx_builder.AddVertices({
{Point(0, 0), Point(0, 0)},
{Point(size.width, 0), Point(1, 0)},
{Point(0, size.height), Point(0, 1)},
{Point(size.width, size.height), Point(1, 1)},
});
auto options = OptionsFromPass(pass);
options.blend_mode = BlendMode::kSource;
options.primitive_type = PrimitiveType::kTriangleStrip;
pass.SetCommandLabel("Framebuffer Advanced Blend Filter");
pass.SetVertexBuffer(vtx_builder.CreateVertexBuffer(host_buffer));
pass.SetStencilReference(entity.GetClipDepth());
switch (blend_mode_) {
case BlendMode::kScreen:
pass.SetPipeline(renderer.GetFramebufferBlendScreenPipeline(options));
break;
case BlendMode::kOverlay:
pass.SetPipeline(renderer.GetFramebufferBlendOverlayPipeline(options));
break;
case BlendMode::kDarken:
pass.SetPipeline(renderer.GetFramebufferBlendDarkenPipeline(options));
break;
case BlendMode::kLighten:
pass.SetPipeline(renderer.GetFramebufferBlendLightenPipeline(options));
break;
case BlendMode::kColorDodge:
pass.SetPipeline(renderer.GetFramebufferBlendColorDodgePipeline(options));
break;
case BlendMode::kColorBurn:
pass.SetPipeline(renderer.GetFramebufferBlendColorBurnPipeline(options));
break;
case BlendMode::kHardLight:
pass.SetPipeline(renderer.GetFramebufferBlendHardLightPipeline(options));
break;
case BlendMode::kSoftLight:
pass.SetPipeline(renderer.GetFramebufferBlendSoftLightPipeline(options));
break;
case BlendMode::kDifference:
pass.SetPipeline(renderer.GetFramebufferBlendDifferencePipeline(options));
break;
case BlendMode::kExclusion:
pass.SetPipeline(renderer.GetFramebufferBlendExclusionPipeline(options));
break;
case BlendMode::kMultiply:
pass.SetPipeline(renderer.GetFramebufferBlendMultiplyPipeline(options));
break;
case BlendMode::kHue:
pass.SetPipeline(renderer.GetFramebufferBlendHuePipeline(options));
break;
case BlendMode::kSaturation:
pass.SetPipeline(renderer.GetFramebufferBlendSaturationPipeline(options));
break;
case BlendMode::kColor:
pass.SetPipeline(renderer.GetFramebufferBlendColorPipeline(options));
break;
case BlendMode::kLuminosity:
pass.SetPipeline(renderer.GetFramebufferBlendLuminosityPipeline(options));
break;
default:
return false;
}
VS::FrameInfo frame_info;
FS::FragInfo frag_info;
auto src_sampler_descriptor = src_snapshot->sampler_descriptor;
if (renderer.GetDeviceCapabilities().SupportsDecalSamplerAddressMode()) {
src_sampler_descriptor.width_address_mode = SamplerAddressMode::kDecal;
src_sampler_descriptor.height_address_mode = SamplerAddressMode::kDecal;
}
const std::unique_ptr<const Sampler>& src_sampler =
renderer.GetContext()->GetSamplerLibrary()->GetSampler(
src_sampler_descriptor);
FS::BindTextureSamplerSrc(pass, src_snapshot->texture, src_sampler);
frame_info.depth = entity.GetShaderClipDepth();
frame_info.mvp = pass.GetOrthographicTransform() * src_snapshot->transform;
frame_info.src_y_coord_scale = src_snapshot->texture->GetYCoordScale();
VS::BindFrameInfo(pass, host_buffer.EmplaceUniform(frame_info));
frag_info.src_input_alpha = src_snapshot->opacity;
FS::BindFragInfo(pass, host_buffer.EmplaceUniform(frag_info));
return pass.Draw().ok();
}
} // namespace impeller
| engine/impeller/entity/contents/framebuffer_blend_contents.cc/0 | {
"file_path": "engine/impeller/entity/contents/framebuffer_blend_contents.cc",
"repo_id": "engine",
"token_count": 2170
} | 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.
#ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_SOLID_RRECT_BLUR_CONTENTS_H_
#define FLUTTER_IMPELLER_ENTITY_CONTENTS_SOLID_RRECT_BLUR_CONTENTS_H_
#include <functional>
#include <memory>
#include <vector>
#include "impeller/entity/contents/contents.h"
#include "impeller/entity/contents/filters/filter_contents.h"
#include "impeller/geometry/color.h"
namespace impeller {
class Path;
class HostBuffer;
struct VertexBuffer;
/// @brief Draws a fast solid color blur of an rounded rectangle. Only supports
/// RRects with fully symmetrical radii. Also produces correct results for
/// rectangles (corner_radius=0) and circles (corner_radius=width/2=height/2).
class SolidRRectBlurContents final : public Contents {
public:
SolidRRectBlurContents();
~SolidRRectBlurContents() override;
void SetRRect(std::optional<Rect> rect, Size corner_radii = {});
void SetSigma(Sigma sigma);
void SetColor(Color color);
Color GetColor() const;
// |Contents|
std::optional<Rect> GetCoverage(const Entity& entity) const override;
// |Contents|
bool Render(const ContentContext& renderer,
const Entity& entity,
RenderPass& pass) const override;
// |Contents|
[[nodiscard]] bool ApplyColorFilter(
const ColorFilterProc& color_filter_proc) override;
private:
std::optional<Rect> rect_;
Size corner_radii_;
Sigma sigma_;
Color color_;
SolidRRectBlurContents(const SolidRRectBlurContents&) = delete;
SolidRRectBlurContents& operator=(const SolidRRectBlurContents&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_SOLID_RRECT_BLUR_CONTENTS_H_
| engine/impeller/entity/contents/solid_rrect_blur_contents.h/0 | {
"file_path": "engine/impeller/entity/contents/solid_rrect_blur_contents.h",
"repo_id": "engine",
"token_count": 614
} | 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 <memory>
#include <optional>
#include "gtest/gtest.h"
#include "impeller/entity/contents/contents.h"
#include "impeller/entity/contents/solid_color_contents.h"
#include "impeller/entity/contents/test/contents_test_helpers.h"
#include "impeller/entity/contents/test/recording_render_pass.h"
#include "impeller/entity/contents/vertices_contents.h"
#include "impeller/entity/entity.h"
#include "impeller/entity/entity_playground.h"
#include "impeller/entity/vertices.frag.h"
#include "impeller/geometry/path_builder.h"
#include "impeller/renderer/render_target.h"
namespace impeller {
namespace testing {
using EntityTest = EntityPlayground;
std::shared_ptr<VerticesGeometry> CreateColorVertices(
const std::vector<Point>& vertices,
const std::vector<Color>& colors) {
auto bounds = Rect::MakePointBounds(vertices.begin(), vertices.end());
std::vector<uint16_t> indices = {};
indices.reserve(vertices.size());
for (auto i = 0u; i < vertices.size(); i++) {
indices.emplace_back(i);
}
std::vector<Point> texture_coordinates = {};
return std::make_shared<VerticesGeometry>(
vertices, indices, texture_coordinates, colors,
bounds.value_or(Rect::MakeLTRB(0, 0, 0, 0)),
VerticesGeometry::VertexMode::kTriangles);
}
// Verifies that the destination blend fast path still sets an alpha value.
TEST_P(EntityTest, RendersDstPerColorWithAlpha) {
using FS = GeometryColorPipeline::FragmentShader;
auto contents = std::make_shared<VerticesContents>();
auto vertices = CreateColorVertices(
{{0, 0}, {100, 0}, {0, 100}, {100, 0}, {0, 100}, {100, 100}},
{Color::Red(), Color::Red(), Color::Red(), Color::Red(), Color::Red(),
Color::Red()});
auto src_contents = SolidColorContents::Make(
PathBuilder{}.AddRect(Rect::MakeLTRB(0, 0, 100, 100)).TakePath(),
Color::Red());
contents->SetGeometry(vertices);
contents->SetAlpha(0.5);
contents->SetBlendMode(BlendMode::kDestination);
contents->SetSourceContents(std::move(src_contents));
auto content_context = GetContentContext();
auto buffer = content_context->GetContext()->CreateCommandBuffer();
auto render_target =
GetContentContext()->GetRenderTargetCache()->CreateOffscreenMSAA(
*content_context->GetContext(), {100, 100},
/*mip_count=*/1);
auto render_pass = buffer->CreateRenderPass(render_target);
auto recording_pass = std::make_shared<RecordingRenderPass>(
render_pass, GetContext(), render_target);
Entity entity;
ASSERT_TRUE(recording_pass->GetCommands().empty());
ASSERT_TRUE(contents->Render(*content_context, entity, *recording_pass));
ASSERT_TRUE(recording_pass->GetCommands().size() > 0);
const auto& cmd = recording_pass->GetCommands()[0];
auto* frag_uniforms = GetFragInfo<FS>(cmd);
ASSERT_TRUE(frag_uniforms);
ASSERT_EQ(frag_uniforms->alpha, 0.5);
if (GetParam() == PlaygroundBackend::kMetal) {
recording_pass->EncodeCommands();
}
}
} // namespace testing
} // namespace impeller
| engine/impeller/entity/contents/vertices_contents_unittests.cc/0 | {
"file_path": "engine/impeller/entity/contents/vertices_contents_unittests.cc",
"repo_id": "engine",
"token_count": 1122
} | 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_ENTITY_GEOMETRY_COVER_GEOMETRY_H_
#define FLUTTER_IMPELLER_ENTITY_GEOMETRY_COVER_GEOMETRY_H_
#include "impeller/entity/geometry/geometry.h"
namespace impeller {
/// @brief A geometry that implements "drawPaint" like behavior by covering
/// the entire render pass area.
class CoverGeometry final : public Geometry {
public:
CoverGeometry();
~CoverGeometry() = default;
// |Geometry|
bool CoversArea(const Matrix& transform, const Rect& rect) const override;
private:
// |Geometry|
GeometryResult GetPositionBuffer(const ContentContext& renderer,
const Entity& entity,
RenderPass& pass) const override;
// |Geometry|
GeometryVertexType GetVertexType() const override;
// |Geometry|
std::optional<Rect> GetCoverage(const Matrix& transform) const override;
// |Geometry|
GeometryResult GetPositionUVBuffer(Rect texture_coverage,
Matrix effect_transform,
const ContentContext& renderer,
const Entity& entity,
RenderPass& pass) const override;
CoverGeometry(const CoverGeometry&) = delete;
CoverGeometry& operator=(const CoverGeometry&) = delete;
};
static_assert(std::is_trivially_destructible<CoverGeometry>::value);
} // namespace impeller
#endif // FLUTTER_IMPELLER_ENTITY_GEOMETRY_COVER_GEOMETRY_H_
| engine/impeller/entity/geometry/cover_geometry.h/0 | {
"file_path": "engine/impeller/entity/geometry/cover_geometry.h",
"repo_id": "engine",
"token_count": 674
} | 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 "impeller/entity/geometry/stroke_path_geometry.h"
#include "impeller/core/buffer_view.h"
#include "impeller/core/formats.h"
#include "impeller/entity/geometry/geometry.h"
#include "impeller/entity/texture_fill.vert.h"
#include "impeller/geometry/path_builder.h"
#include "impeller/geometry/path_component.h"
namespace impeller {
using VS = SolidFillVertexShader;
namespace {
template <typename VertexWriter>
using CapProc = std::function<void(VertexWriter& vtx_builder,
const Point& position,
const Point& offset,
Scalar scale,
bool reverse)>;
template <typename VertexWriter>
using JoinProc = std::function<void(VertexWriter& vtx_builder,
const Point& position,
const Point& start_offset,
const Point& end_offset,
Scalar miter_limit,
Scalar scale)>;
class PositionWriter {
public:
void AppendVertex(const Point& point) {
data_.emplace_back(SolidFillVertexShader::PerVertexData{.position = point});
}
const std::vector<SolidFillVertexShader::PerVertexData>& GetData() const {
return data_;
}
private:
std::vector<SolidFillVertexShader::PerVertexData> data_ = {};
};
class PositionUVWriter {
public:
PositionUVWriter(const Point& texture_origin,
const Size& texture_size,
const Matrix& effect_transform)
: texture_origin_(texture_origin),
texture_size_(texture_size),
effect_transform_(effect_transform) {}
const std::vector<TextureFillVertexShader::PerVertexData>& GetData() {
if (effect_transform_.IsIdentity()) {
auto origin = texture_origin_;
auto scale = 1.0 / texture_size_;
for (auto& pvd : data_) {
pvd.texture_coords = (pvd.position - origin) * scale;
}
} else {
auto texture_rect = Rect::MakeOriginSize(texture_origin_, texture_size_);
Matrix uv_transform =
texture_rect.GetNormalizingTransform() * effect_transform_;
for (auto& pvd : data_) {
pvd.texture_coords = uv_transform * pvd.position;
}
}
return data_;
}
void AppendVertex(const Point& point) {
data_.emplace_back(TextureFillVertexShader::PerVertexData{
.position = point,
// .texture_coords = default, will be filled in during |GetData()|
});
}
private:
std::vector<TextureFillVertexShader::PerVertexData> data_ = {};
const Point texture_origin_;
const Size texture_size_;
const Matrix effect_transform_;
};
template <typename VertexWriter>
class StrokeGenerator {
public:
StrokeGenerator(const Path::Polyline& p_polyline,
const Scalar p_stroke_width,
const Scalar p_scaled_miter_limit,
const JoinProc<VertexWriter>& p_join_proc,
const CapProc<VertexWriter>& p_cap_proc,
const Scalar p_scale)
: polyline(p_polyline),
stroke_width(p_stroke_width),
scaled_miter_limit(p_scaled_miter_limit),
join_proc(p_join_proc),
cap_proc(p_cap_proc),
scale(p_scale) {}
void Generate(VertexWriter& vtx_builder) {
for (size_t contour_i = 0; contour_i < polyline.contours.size();
contour_i++) {
const Path::PolylineContour& contour = polyline.contours[contour_i];
size_t contour_start_point_i, contour_end_point_i;
std::tie(contour_start_point_i, contour_end_point_i) =
polyline.GetContourPointBounds(contour_i);
auto contour_delta = contour_end_point_i - contour_start_point_i;
if (contour_delta == 1) {
Point p = polyline.GetPoint(contour_start_point_i);
cap_proc(vtx_builder, p, {-stroke_width * 0.5f, 0}, scale,
/*reverse=*/false);
cap_proc(vtx_builder, p, {stroke_width * 0.5f, 0}, scale,
/*reverse=*/false);
continue;
} else if (contour_delta == 0) {
continue; // This contour has no renderable content.
}
previous_offset = offset;
offset = ComputeOffset(contour_start_point_i, contour_start_point_i,
contour_end_point_i, contour);
const Point contour_first_offset = offset;
if (contour_i > 0) {
// This branch only executes when we've just finished drawing a contour
// and are switching to a new one.
// We're drawing a triangle strip, so we need to "pick up the pen" by
// appending two vertices at the end of the previous contour and two
// vertices at the start of the new contour (thus connecting the two
// contours with two zero volume triangles, which will be discarded by
// the rasterizer).
vtx.position = polyline.GetPoint(contour_start_point_i - 1);
// Append two vertices when "picking up" the pen so that the triangle
// drawn when moving to the beginning of the new contour will have zero
// volume.
vtx_builder.AppendVertex(vtx.position);
vtx_builder.AppendVertex(vtx.position);
vtx.position = polyline.GetPoint(contour_start_point_i);
// Append two vertices at the beginning of the new contour, which
// appends two triangles of zero area.
vtx_builder.AppendVertex(vtx.position);
vtx_builder.AppendVertex(vtx.position);
}
// Generate start cap.
if (!polyline.contours[contour_i].is_closed) {
Point cap_offset =
Vector2(-contour.start_direction.y, contour.start_direction.x) *
stroke_width * 0.5f; // Counterclockwise normal
cap_proc(vtx_builder, polyline.GetPoint(contour_start_point_i),
cap_offset, scale, /*reverse=*/true);
}
for (size_t contour_component_i = 0;
contour_component_i < contour.components.size();
contour_component_i++) {
const Path::PolylineContour::Component& component =
contour.components[contour_component_i];
bool is_last_component =
contour_component_i == contour.components.size() - 1;
size_t component_start_index = component.component_start_index;
size_t component_end_index =
is_last_component ? contour_end_point_i - 1
: contour.components[contour_component_i + 1]
.component_start_index;
if (component.is_curve) {
AddVerticesForCurveComponent(
vtx_builder, component_start_index, component_end_index,
contour_start_point_i, contour_end_point_i, contour);
} else {
AddVerticesForLinearComponent(
vtx_builder, component_start_index, component_end_index,
contour_start_point_i, contour_end_point_i, contour);
}
}
// Generate end cap or join.
if (!contour.is_closed) {
auto cap_offset =
Vector2(-contour.end_direction.y, contour.end_direction.x) *
stroke_width * 0.5f; // Clockwise normal
cap_proc(vtx_builder, polyline.GetPoint(contour_end_point_i - 1),
cap_offset, scale, /*reverse=*/false);
} else {
join_proc(vtx_builder, polyline.GetPoint(contour_start_point_i), offset,
contour_first_offset, scaled_miter_limit, scale);
}
}
}
/// Computes offset by calculating the direction from point_i - 1 to point_i
/// if point_i is within `contour_start_point_i` and `contour_end_point_i`;
/// Otherwise, it uses direction from contour.
Point ComputeOffset(const size_t point_i,
const size_t contour_start_point_i,
const size_t contour_end_point_i,
const Path::PolylineContour& contour) const {
Point direction;
if (point_i >= contour_end_point_i) {
direction = contour.end_direction;
} else if (point_i <= contour_start_point_i) {
direction = -contour.start_direction;
} else {
direction = (polyline.GetPoint(point_i) - polyline.GetPoint(point_i - 1))
.Normalize();
}
return Vector2{-direction.y, direction.x} * stroke_width * 0.5f;
}
void AddVerticesForLinearComponent(VertexWriter& vtx_builder,
const size_t component_start_index,
const size_t component_end_index,
const size_t contour_start_point_i,
const size_t contour_end_point_i,
const Path::PolylineContour& contour) {
bool is_last_component = component_start_index ==
contour.components.back().component_start_index;
for (size_t point_i = component_start_index; point_i < component_end_index;
point_i++) {
bool is_end_of_component = point_i == component_end_index - 1;
vtx.position = polyline.GetPoint(point_i) + offset;
vtx_builder.AppendVertex(vtx.position);
vtx.position = polyline.GetPoint(point_i) - offset;
vtx_builder.AppendVertex(vtx.position);
// For line components, two additional points need to be appended
// prior to appending a join connecting the next component.
vtx.position = polyline.GetPoint(point_i + 1) + offset;
vtx_builder.AppendVertex(vtx.position);
vtx.position = polyline.GetPoint(point_i + 1) - offset;
vtx_builder.AppendVertex(vtx.position);
previous_offset = offset;
offset = ComputeOffset(point_i + 2, contour_start_point_i,
contour_end_point_i, contour);
if (!is_last_component && is_end_of_component) {
// Generate join from the current line to the next line.
join_proc(vtx_builder, polyline.GetPoint(point_i + 1), previous_offset,
offset, scaled_miter_limit, scale);
}
}
}
void AddVerticesForCurveComponent(VertexWriter& vtx_builder,
const size_t component_start_index,
const size_t component_end_index,
const size_t contour_start_point_i,
const size_t contour_end_point_i,
const Path::PolylineContour& contour) {
bool is_last_component = component_start_index ==
contour.components.back().component_start_index;
for (size_t point_i = component_start_index; point_i < component_end_index;
point_i++) {
bool is_end_of_component = point_i == component_end_index - 1;
vtx.position = polyline.GetPoint(point_i) + offset;
vtx_builder.AppendVertex(vtx.position);
vtx.position = polyline.GetPoint(point_i) - offset;
vtx_builder.AppendVertex(vtx.position);
previous_offset = offset;
offset = ComputeOffset(point_i + 2, contour_start_point_i,
contour_end_point_i, contour);
// For curve components, the polyline is detailed enough such that
// it can avoid worrying about joins altogether.
if (is_end_of_component) {
vtx.position = polyline.GetPoint(point_i + 1) + offset;
vtx_builder.AppendVertex(vtx.position);
vtx.position = polyline.GetPoint(point_i + 1) - offset;
vtx_builder.AppendVertex(vtx.position);
// Generate join from the current line to the next line.
if (!is_last_component) {
join_proc(vtx_builder, polyline.GetPoint(point_i + 1),
previous_offset, offset, scaled_miter_limit, scale);
}
}
}
}
const Path::Polyline& polyline;
const Scalar stroke_width;
const Scalar scaled_miter_limit;
const JoinProc<VertexWriter>& join_proc;
const CapProc<VertexWriter>& cap_proc;
const Scalar scale;
Point previous_offset;
Point offset;
SolidFillVertexShader::PerVertexData vtx;
};
template <typename VertexWriter>
void CreateButtCap(VertexWriter& vtx_builder,
const Point& position,
const Point& offset,
Scalar scale,
bool reverse) {
Point orientation = offset * (reverse ? -1 : 1);
VS::PerVertexData vtx;
vtx.position = position + orientation;
vtx_builder.AppendVertex(vtx.position);
vtx.position = position - orientation;
vtx_builder.AppendVertex(vtx.position);
}
template <typename VertexWriter>
void CreateRoundCap(VertexWriter& vtx_builder,
const Point& position,
const Point& offset,
Scalar scale,
bool reverse) {
Point orientation = offset * (reverse ? -1 : 1);
Point forward(offset.y, -offset.x);
Point forward_normal = forward.Normalize();
CubicPathComponent arc;
if (reverse) {
arc = CubicPathComponent(
forward, forward + orientation * PathBuilder::kArcApproximationMagic,
orientation + forward * PathBuilder::kArcApproximationMagic,
orientation);
} else {
arc = CubicPathComponent(
orientation,
orientation + forward * PathBuilder::kArcApproximationMagic,
forward + orientation * PathBuilder::kArcApproximationMagic, forward);
}
Point vtx = position + orientation;
vtx_builder.AppendVertex(vtx);
vtx = position - orientation;
vtx_builder.AppendVertex(vtx);
arc.ToLinearPathComponents(scale, [&vtx_builder, &vtx, forward_normal,
position](const Point& point) {
vtx = position + point;
vtx_builder.AppendVertex(vtx);
vtx = position + (-point).Reflect(forward_normal);
vtx_builder.AppendVertex(vtx);
});
}
template <typename VertexWriter>
void CreateSquareCap(VertexWriter& vtx_builder,
const Point& position,
const Point& offset,
Scalar scale,
bool reverse) {
Point orientation = offset * (reverse ? -1 : 1);
Point forward(offset.y, -offset.x);
Point vtx = position + orientation;
vtx_builder.AppendVertex(vtx);
vtx = position - orientation;
vtx_builder.AppendVertex(vtx);
vtx = position + orientation + forward;
vtx_builder.AppendVertex(vtx);
vtx = position - orientation + forward;
vtx_builder.AppendVertex(vtx);
}
template <typename VertexWriter>
Scalar CreateBevelAndGetDirection(VertexWriter& vtx_builder,
const Point& position,
const Point& start_offset,
const Point& end_offset) {
Point vtx = position;
vtx_builder.AppendVertex(vtx);
Scalar dir = start_offset.Cross(end_offset) > 0 ? -1 : 1;
vtx = position + start_offset * dir;
vtx_builder.AppendVertex(vtx);
vtx = position + end_offset * dir;
vtx_builder.AppendVertex(vtx);
return dir;
}
template <typename VertexWriter>
void CreateMiterJoin(VertexWriter& vtx_builder,
const Point& position,
const Point& start_offset,
const Point& end_offset,
Scalar miter_limit,
Scalar scale) {
Point start_normal = start_offset.Normalize();
Point end_normal = end_offset.Normalize();
// 1 for no joint (straight line), 0 for max joint (180 degrees).
Scalar alignment = (start_normal.Dot(end_normal) + 1) / 2;
if (ScalarNearlyEqual(alignment, 1)) {
return;
}
Scalar direction = CreateBevelAndGetDirection(vtx_builder, position,
start_offset, end_offset);
Point miter_point = (((start_offset + end_offset) / 2) / alignment);
if (miter_point.GetDistanceSquared({0, 0}) > miter_limit * miter_limit) {
return; // Convert to bevel when we exceed the miter limit.
}
// Outer miter point.
VS::PerVertexData vtx;
vtx.position = position + miter_point * direction;
vtx_builder.AppendVertex(vtx.position);
}
template <typename VertexWriter>
void CreateRoundJoin(VertexWriter& vtx_builder,
const Point& position,
const Point& start_offset,
const Point& end_offset,
Scalar miter_limit,
Scalar scale) {
Point start_normal = start_offset.Normalize();
Point end_normal = end_offset.Normalize();
// 0 for no joint (straight line), 1 for max joint (180 degrees).
Scalar alignment = 1 - (start_normal.Dot(end_normal) + 1) / 2;
if (ScalarNearlyEqual(alignment, 0)) {
return;
}
Scalar direction = CreateBevelAndGetDirection(vtx_builder, position,
start_offset, end_offset);
Point middle =
(start_offset + end_offset).Normalize() * start_offset.GetLength();
Point middle_normal = middle.Normalize();
Point middle_handle = middle + Point(-middle.y, middle.x) *
PathBuilder::kArcApproximationMagic *
alignment * direction;
Point start_handle = start_offset + Point(start_offset.y, -start_offset.x) *
PathBuilder::kArcApproximationMagic *
alignment * direction;
VS::PerVertexData vtx;
CubicPathComponent(start_offset, start_handle, middle_handle, middle)
.ToLinearPathComponents(scale, [&vtx_builder, direction, &vtx, position,
middle_normal](const Point& point) {
vtx.position = position + point * direction;
vtx_builder.AppendVertex(vtx.position);
vtx.position = position + (-point * direction).Reflect(middle_normal);
vtx_builder.AppendVertex(vtx.position);
});
}
template <typename VertexWriter>
void CreateBevelJoin(VertexWriter& vtx_builder,
const Point& position,
const Point& start_offset,
const Point& end_offset,
Scalar miter_limit,
Scalar scale) {
CreateBevelAndGetDirection(vtx_builder, position, start_offset, end_offset);
}
template <typename VertexWriter>
void CreateSolidStrokeVertices(VertexWriter& vtx_builder,
const Path::Polyline& polyline,
Scalar stroke_width,
Scalar scaled_miter_limit,
const JoinProc<VertexWriter>& join_proc,
const CapProc<VertexWriter>& cap_proc,
Scalar scale) {
StrokeGenerator stroke_generator(polyline, stroke_width, scaled_miter_limit,
join_proc, cap_proc, scale);
stroke_generator.Generate(vtx_builder);
}
// static
template <typename VertexWriter>
JoinProc<VertexWriter> GetJoinProc(Join stroke_join) {
switch (stroke_join) {
case Join::kBevel:
return &CreateBevelJoin<VertexWriter>;
case Join::kMiter:
return &CreateMiterJoin<VertexWriter>;
case Join::kRound:
return &CreateRoundJoin<VertexWriter>;
}
}
template <typename VertexWriter>
CapProc<VertexWriter> GetCapProc(Cap stroke_cap) {
switch (stroke_cap) {
case Cap::kButt:
return &CreateButtCap<VertexWriter>;
case Cap::kRound:
return &CreateRoundCap<VertexWriter>;
case Cap::kSquare:
return &CreateSquareCap<VertexWriter>;
}
}
} // namespace
std::vector<SolidFillVertexShader::PerVertexData>
StrokePathGeometry::GenerateSolidStrokeVertices(const Path::Polyline& polyline,
Scalar stroke_width,
Scalar miter_limit,
Join stroke_join,
Cap stroke_cap,
Scalar scale) {
auto scaled_miter_limit = stroke_width * miter_limit * 0.5f;
auto join_proc = GetJoinProc<PositionWriter>(stroke_join);
auto cap_proc = GetCapProc<PositionWriter>(stroke_cap);
StrokeGenerator stroke_generator(polyline, stroke_width, scaled_miter_limit,
join_proc, cap_proc, scale);
PositionWriter vtx_builder;
stroke_generator.Generate(vtx_builder);
return vtx_builder.GetData();
}
std::vector<TextureFillVertexShader::PerVertexData>
StrokePathGeometry::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) {
auto scaled_miter_limit = stroke_width * miter_limit * 0.5f;
auto join_proc = GetJoinProc<PositionUVWriter>(stroke_join);
auto cap_proc = GetCapProc<PositionUVWriter>(stroke_cap);
StrokeGenerator stroke_generator(polyline, stroke_width, scaled_miter_limit,
join_proc, cap_proc, scale);
PositionUVWriter vtx_builder(texture_origin, texture_size, effect_transform);
stroke_generator.Generate(vtx_builder);
return vtx_builder.GetData();
}
StrokePathGeometry::StrokePathGeometry(const Path& path,
Scalar stroke_width,
Scalar miter_limit,
Cap stroke_cap,
Join stroke_join)
: path_(path),
stroke_width_(stroke_width),
miter_limit_(miter_limit),
stroke_cap_(stroke_cap),
stroke_join_(stroke_join) {}
StrokePathGeometry::~StrokePathGeometry() = default;
Scalar StrokePathGeometry::GetStrokeWidth() const {
return stroke_width_;
}
Scalar StrokePathGeometry::GetMiterLimit() const {
return miter_limit_;
}
Cap StrokePathGeometry::GetStrokeCap() const {
return stroke_cap_;
}
Join StrokePathGeometry::GetStrokeJoin() const {
return stroke_join_;
}
GeometryResult StrokePathGeometry::GetPositionBuffer(
const ContentContext& renderer,
const Entity& entity,
RenderPass& pass) const {
if (stroke_width_ < 0.0) {
return {};
}
auto determinant = entity.GetTransform().GetDeterminant();
if (determinant == 0) {
return {};
}
Scalar min_size = 1.0f / sqrt(std::abs(determinant));
Scalar stroke_width = std::max(stroke_width_, min_size);
auto& host_buffer = renderer.GetTransientsBuffer();
auto scale = entity.GetTransform().GetMaxBasisLength();
PositionWriter position_writer;
auto polyline = renderer.GetTessellator()->CreateTempPolyline(path_, scale);
CreateSolidStrokeVertices(position_writer, polyline, stroke_width,
miter_limit_ * stroke_width_ * 0.5f,
GetJoinProc<PositionWriter>(stroke_join_),
GetCapProc<PositionWriter>(stroke_cap_), scale);
BufferView buffer_view =
host_buffer.Emplace(position_writer.GetData().data(),
position_writer.GetData().size() *
sizeof(SolidFillVertexShader::PerVertexData),
alignof(SolidFillVertexShader::PerVertexData));
return GeometryResult{
.type = PrimitiveType::kTriangleStrip,
.vertex_buffer =
{
.vertex_buffer = buffer_view,
.vertex_count = position_writer.GetData().size(),
.index_type = IndexType::kNone,
},
.transform = pass.GetOrthographicTransform() * entity.GetTransform(),
.mode = GeometryResult::Mode::kPreventOverdraw,
};
}
GeometryResult StrokePathGeometry::GetPositionUVBuffer(
Rect texture_coverage,
Matrix effect_transform,
const ContentContext& renderer,
const Entity& entity,
RenderPass& pass) const {
if (stroke_width_ < 0.0) {
return {};
}
auto determinant = entity.GetTransform().GetDeterminant();
if (determinant == 0) {
return {};
}
Scalar min_size = 1.0f / sqrt(std::abs(determinant));
Scalar stroke_width = std::max(stroke_width_, min_size);
auto& host_buffer = renderer.GetTransientsBuffer();
auto scale = entity.GetTransform().GetMaxBasisLength();
auto polyline = renderer.GetTessellator()->CreateTempPolyline(path_, scale);
PositionUVWriter writer(Point{0, 0}, texture_coverage.GetSize(),
effect_transform);
CreateSolidStrokeVertices(writer, polyline, stroke_width,
miter_limit_ * stroke_width_ * 0.5f,
GetJoinProc<PositionUVWriter>(stroke_join_),
GetCapProc<PositionUVWriter>(stroke_cap_), scale);
BufferView buffer_view = host_buffer.Emplace(
writer.GetData().data(),
writer.GetData().size() * sizeof(TextureFillVertexShader::PerVertexData),
alignof(TextureFillVertexShader::PerVertexData));
return GeometryResult{
.type = PrimitiveType::kTriangleStrip,
.vertex_buffer =
{
.vertex_buffer = buffer_view,
.vertex_count = writer.GetData().size(),
.index_type = IndexType::kNone,
},
.transform = pass.GetOrthographicTransform() * entity.GetTransform(),
.mode = GeometryResult::Mode::kPreventOverdraw,
};
}
GeometryResult::Mode StrokePathGeometry::GetResultMode() const {
return GeometryResult::Mode::kPreventOverdraw;
}
GeometryVertexType StrokePathGeometry::GetVertexType() const {
return GeometryVertexType::kPosition;
}
std::optional<Rect> StrokePathGeometry::GetCoverage(
const Matrix& transform) const {
auto path_bounds = path_.GetBoundingBox();
if (!path_bounds.has_value()) {
return std::nullopt;
}
Scalar max_radius = 0.5;
if (stroke_cap_ == Cap::kSquare) {
max_radius = max_radius * kSqrt2;
}
if (stroke_join_ == Join::kMiter) {
max_radius = std::max(max_radius, miter_limit_ * 0.5f);
}
Scalar determinant = transform.GetDeterminant();
if (determinant == 0) {
return std::nullopt;
}
Scalar min_size = 1.0f / sqrt(std::abs(determinant));
max_radius *= std::max(stroke_width_, min_size);
return path_bounds->Expand(max_radius).TransformBounds(transform);
}
} // namespace impeller
| engine/impeller/entity/geometry/stroke_path_geometry.cc/0 | {
"file_path": "engine/impeller/entity/geometry/stroke_path_geometry.cc",
"repo_id": "engine",
"token_count": 11865
} | 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.
precision mediump float;
#include <impeller/blending.glsl>
#include <impeller/color.glsl>
#include <impeller/texture.glsl>
#include <impeller/types.glsl>
layout(constant_id = 0) const float supports_decal = 1.0;
uniform f16sampler2D texture_sampler_dst;
uniform FragInfo {
float16_t src_coeff;
float16_t src_coeff_dst_alpha;
float16_t dst_coeff;
float16_t dst_coeff_src_alpha;
float16_t dst_coeff_src_color;
float16_t input_alpha;
float16_t output_alpha;
}
frag_info;
in vec2 v_texture_coords;
in f16vec4 v_color;
out f16vec4 frag_color;
f16vec4 Sample(f16sampler2D texture_sampler, vec2 texture_coords) {
if (supports_decal > 0.0) {
return texture(texture_sampler, texture_coords);
}
return IPHalfSampleDecal(texture_sampler, texture_coords);
}
void main() {
f16vec4 dst =
texture(texture_sampler_dst, v_texture_coords) * frag_info.input_alpha;
f16vec4 src = v_color;
frag_color =
src * (frag_info.src_coeff + dst.a * frag_info.src_coeff_dst_alpha) +
dst * (frag_info.dst_coeff + src.a * frag_info.dst_coeff_src_alpha +
src * frag_info.dst_coeff_src_color);
frag_color *= frag_info.output_alpha;
}
| engine/impeller/entity/shaders/blending/porter_duff_blend.frag/0 | {
"file_path": "engine/impeller/entity/shaders/blending/porter_duff_blend.frag",
"repo_id": "engine",
"token_count": 548
} | 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/constants.glsl>
#include <impeller/gaussian.glsl>
#include <impeller/texture.glsl>
#include <impeller/types.glsl>
uniform f16sampler2D texture_sampler;
struct KernelSample {
vec2 uv_offset;
float coefficient;
};
uniform KernelSamples {
int sample_count;
KernelSample samples[48];
}
blur_info;
f16vec4 Sample(f16sampler2D tex, vec2 coords) {
#if ENABLE_DECAL_SPECIALIZATION
return IPHalfSampleDecal(tex, coords);
#else
return texture(tex, coords);
#endif
}
in vec2 v_texture_coords;
out f16vec4 frag_color;
void main() {
f16vec4 total_color = f16vec4(0.0hf);
for (int i = 0; i < blur_info.sample_count; ++i) {
float16_t coefficient = float16_t(blur_info.samples[i].coefficient);
total_color +=
coefficient * Sample(texture_sampler,
v_texture_coords + blur_info.samples[i].uv_offset);
}
frag_color = total_color;
}
| engine/impeller/entity/shaders/gaussian_blur/kernel.glsl/0 | {
"file_path": "engine/impeller/entity/shaders/gaussian_blur/kernel.glsl",
"repo_id": "engine",
"token_count": 422
} | 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.
precision mediump float;
#include <impeller/color.glsl>
#include <impeller/texture.glsl>
#include <impeller/types.glsl>
uniform sampler2D texture_sampler;
uniform FragInfo {
highp vec2 center;
float radius;
float tile_mode;
vec4 decal_border_color;
float texture_sampler_y_coord_scale;
float alpha;
vec2 half_texel;
}
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;
frag_color =
IPSampleLinearWithTileMode(texture_sampler, //
vec2(t, 0.5), //
frag_info.texture_sampler_y_coord_scale, //
frag_info.half_texel, //
frag_info.tile_mode, //
frag_info.decal_border_color);
frag_color = IPPremultiply(frag_color) * frag_info.alpha;
}
| engine/impeller/entity/shaders/radial_gradient_fill.frag/0 | {
"file_path": "engine/impeller/entity/shaders/radial_gradient_fill.frag",
"repo_id": "engine",
"token_count": 600
} | 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.
precision mediump float;
#include <impeller/external_texture_oes.glsl>
uniform sampler2D SAMPLER_EXTERNAL_OES_texture_sampler;
uniform FragInfo {
float x_tile_mode;
float y_tile_mode;
}
frag_info;
in vec2 v_texture_coords;
in float v_alpha;
out vec4 frag_color;
void main() {
frag_color =
IPSampleWithTileModeOES(SAMPLER_EXTERNAL_OES_texture_sampler, // sampler
v_texture_coords, // texture coordinates
frag_info.x_tile_mode, // x tile mode
frag_info.y_tile_mode // y tile mode
) *
v_alpha;
}
| engine/impeller/entity/shaders/tiled_texture_fill_external.frag/0 | {
"file_path": "engine/impeller/entity/shaders/tiled_texture_fill_external.frag",
"repo_id": "engine",
"token_count": 378
} | 229 |
#version 320 es
// 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 highp float;
#include <flutter/runtime_effect.glsl>
layout(location = 0) uniform vec4 u_color;
layout(location = 1) uniform float u_alpha;
layout(location = 2) uniform vec4 u_sparkle_color;
layout(location = 3) uniform float u_sparkle_alpha;
layout(location = 4) uniform float u_blur;
layout(location = 5) uniform vec2 u_center;
layout(location = 6) uniform float u_radius_scale;
layout(location = 7) uniform float u_max_radius;
layout(location = 8) uniform vec2 u_resolution_scale;
layout(location = 9) uniform vec2 u_noise_scale;
layout(location = 10) uniform float u_noise_phase;
layout(location = 11) uniform vec2 u_circle1;
layout(location = 12) uniform vec2 u_circle2;
layout(location = 13) uniform vec2 u_circle3;
layout(location = 14) uniform vec2 u_rotation1;
layout(location = 15) uniform vec2 u_rotation2;
layout(location = 16) uniform vec2 u_rotation3;
layout(location = 0) out vec4 fragColor;
const float PI = 3.1415926535897932384626;
const float PI_ROTATE_RIGHT = PI * 0.0078125;
const float PI_ROTATE_LEFT = PI * -0.0078125;
const float ONE_THIRD = 1. / 3.;
const vec2 TURBULENCE_SCALE = vec2(0.8);
float triangle_noise(highp vec2 n) {
n = fract(n * vec2(5.3987, 5.4421));
n += dot(n.yx, n.xy + vec2(21.5351, 14.3137));
float xy = n.x * n.y;
return fract(xy * 95.4307) + fract(xy * 75.04961) - 1.0;
}
float threshold(float v, float l, float h) {
return step(l, v) * (1.0 - step(h, v));
}
mat2 rotate2d(vec2 rad) {
return mat2(rad.x, -rad.y, rad.y, rad.x);
}
float soft_circle(vec2 uv, vec2 xy, float radius, float blur) {
float blur_half = blur * 0.5;
float d = distance(uv, xy);
return 1.0 - smoothstep(1.0 - blur_half, 1.0 + blur_half, d / radius);
}
float soft_ring(vec2 uv, vec2 xy, float radius, float thickness, float blur) {
float circle_outer = soft_circle(uv, xy, radius + thickness, blur);
float circle_inner = soft_circle(uv, xy, max(radius - thickness, 0.0), blur);
return clamp(circle_outer - circle_inner, 0.0, 1.0);
}
float circle_grid(vec2 resolution,
vec2 p,
vec2 xy,
vec2 rotation,
float cell_diameter) {
p = rotate2d(rotation) * (xy - p) + xy;
p = mod(p, cell_diameter) / resolution;
float cell_uv = cell_diameter / resolution.y * 0.5;
float r = 0.65 * cell_uv;
return soft_circle(p, vec2(cell_uv), r, r * 50.0);
}
float sparkle(vec2 uv, float t) {
float n = triangle_noise(uv);
float s = threshold(n, 0.0, 0.05);
s += threshold(n + sin(PI * (t + 0.35)), 0.1, 0.15);
s += threshold(n + sin(PI * (t + 0.7)), 0.2, 0.25);
s += threshold(n + sin(PI * (t + 1.05)), 0.3, 0.35);
return clamp(s, 0.0, 1.0) * 0.55;
}
float turbulence(vec2 uv) {
vec2 uv_scale = uv * TURBULENCE_SCALE;
float g1 =
circle_grid(TURBULENCE_SCALE, uv_scale, u_circle1, u_rotation1, 0.17);
float g2 =
circle_grid(TURBULENCE_SCALE, uv_scale, u_circle2, u_rotation2, 0.2);
float g3 =
circle_grid(TURBULENCE_SCALE, uv_scale, u_circle3, u_rotation3, 0.275);
float v = (g1 * g1 + g2 - g3) * 0.5;
return clamp(0.45 + 0.8 * v, 0.0, 1.0);
}
void main() {
vec2 p = FlutterFragCoord();
vec2 uv = p * u_resolution_scale;
vec2 density_uv = uv - mod(p, u_noise_scale);
float radius = u_max_radius * u_radius_scale;
float turbulence = turbulence(uv);
float ring = soft_ring(p, u_center, radius, 0.05 * u_max_radius, u_blur);
float sparkle =
sparkle(density_uv, u_noise_phase) * ring * turbulence * u_sparkle_alpha;
float wave_alpha =
soft_circle(p, u_center, radius, u_blur) * u_alpha * u_color.a;
vec4 wave_color = vec4(u_color.rgb * wave_alpha, wave_alpha);
vec4 sparkle_color =
vec4(u_sparkle_color.rgb * u_sparkle_color.a, u_sparkle_color.a);
fragColor = mix(wave_color, sparkle_color, sparkle);
}
| engine/impeller/fixtures/ink_sparkle.frag/0 | {
"file_path": "engine/impeller/fixtures/ink_sparkle.frag",
"repo_id": "engine",
"token_count": 1653
} | 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.
#include "gtest/gtest.h"
#include "impeller/geometry/geometry_asserts.h"
#include <limits>
#include <sstream>
#include <type_traits>
#include "flutter/fml/build_config.h"
#include "flutter/testing/testing.h"
#include "impeller/geometry/color.h"
#include "impeller/geometry/constants.h"
#include "impeller/geometry/gradient.h"
#include "impeller/geometry/half.h"
#include "impeller/geometry/point.h"
#include "impeller/geometry/rect.h"
#include "impeller/geometry/scalar.h"
#include "impeller/geometry/size.h"
// TODO(zanderso): https://github.com/flutter/flutter/issues/127701
// NOLINTBEGIN(bugprone-unchecked-optional-access)
namespace impeller {
namespace testing {
TEST(GeometryTest, ScalarNearlyEqual) {
ASSERT_FALSE(ScalarNearlyEqual(0.0021f, 0.001f));
ASSERT_TRUE(ScalarNearlyEqual(0.0019f, 0.001f));
ASSERT_TRUE(ScalarNearlyEqual(0.002f, 0.001f, 0.0011f));
ASSERT_FALSE(ScalarNearlyEqual(0.002f, 0.001f, 0.0009f));
ASSERT_TRUE(ScalarNearlyEqual(
1.0f, 1.0f + std::numeric_limits<float>::epsilon() * 4));
}
TEST(GeometryTest, MakeColumn) {
auto matrix = Matrix::MakeColumn(1, 2, 3, 4, //
5, 6, 7, 8, //
9, 10, 11, 12, //
13, 14, 15, 16);
auto expect = Matrix{1, 2, 3, 4, //
5, 6, 7, 8, //
9, 10, 11, 12, //
13, 14, 15, 16};
ASSERT_TRUE(matrix == expect);
}
TEST(GeometryTest, MakeRow) {
auto matrix = Matrix::MakeRow(1, 2, 3, 4, //
5, 6, 7, 8, //
9, 10, 11, 12, //
13, 14, 15, 16);
auto expect = Matrix{1, 5, 9, 13, //
2, 6, 10, 14, //
3, 7, 11, 15, //
4, 8, 12, 16};
ASSERT_TRUE(matrix == expect);
}
TEST(GeometryTest, RotationMatrix) {
auto rotation = Matrix::MakeRotationZ(Radians{kPiOver4});
auto expect = Matrix{0.707, 0.707, 0, 0, //
-0.707, 0.707, 0, 0, //
0, 0, 1, 0, //
0, 0, 0, 1};
ASSERT_MATRIX_NEAR(rotation, expect);
}
TEST(GeometryTest, InvertMultMatrix) {
{
auto rotation = Matrix::MakeRotationZ(Radians{kPiOver4});
auto invert = rotation.Invert();
auto expect = Matrix{0.707, -0.707, 0, 0, //
0.707, 0.707, 0, 0, //
0, 0, 1, 0, //
0, 0, 0, 1};
ASSERT_MATRIX_NEAR(invert, expect);
}
{
auto scale = Matrix::MakeScale(Vector2{2, 4});
auto invert = scale.Invert();
auto expect = Matrix{0.5, 0, 0, 0, //
0, 0.25, 0, 0, //
0, 0, 1, 0, //
0, 0, 0, 1};
ASSERT_MATRIX_NEAR(invert, expect);
}
}
TEST(GeometryTest, MatrixBasis) {
auto matrix = Matrix{1, 2, 3, 4, //
5, 6, 7, 8, //
9, 10, 11, 12, //
13, 14, 15, 16};
auto basis = matrix.Basis();
auto expect = Matrix{1, 2, 3, 0, //
5, 6, 7, 0, //
9, 10, 11, 0, //
0, 0, 0, 1};
ASSERT_MATRIX_NEAR(basis, expect);
}
TEST(GeometryTest, MutliplicationMatrix) {
auto rotation = Matrix::MakeRotationZ(Radians{kPiOver4});
auto invert = rotation.Invert();
ASSERT_MATRIX_NEAR(rotation * invert, Matrix{});
}
TEST(GeometryTest, DeterminantTest) {
auto matrix = Matrix{3, 4, 14, 155, 2, 1, 3, 4, 2, 3, 2, 1, 1, 2, 4, 2};
ASSERT_EQ(matrix.GetDeterminant(), -1889);
}
TEST(GeometryTest, InvertMatrix) {
auto inverted = Matrix{10, -9, -12, 8, //
7, -12, 11, 22, //
-10, 10, 3, 6, //
-2, 22, 2, 1}
.Invert();
auto result = Matrix{
438.0 / 85123.0, 1751.0 / 85123.0, -7783.0 / 85123.0, 4672.0 / 85123.0,
393.0 / 85123.0, -178.0 / 85123.0, -570.0 / 85123.0, 4192 / 85123.0,
-5230.0 / 85123.0, 2802.0 / 85123.0, -3461.0 / 85123.0, 962.0 / 85123.0,
2690.0 / 85123.0, 1814.0 / 85123.0, 3896.0 / 85123.0, 319.0 / 85123.0};
ASSERT_MATRIX_NEAR(inverted, result);
}
TEST(GeometryTest, TestDecomposition) {
auto rotated = Matrix::MakeRotationZ(Radians{kPiOver4});
auto result = rotated.Decompose();
ASSERT_TRUE(result.has_value());
MatrixDecomposition res = result.value();
auto quaternion = Quaternion{{0.0, 0.0, 1.0}, kPiOver4};
ASSERT_QUATERNION_NEAR(res.rotation, quaternion);
}
TEST(GeometryTest, TestDecomposition2) {
auto rotated = Matrix::MakeRotationZ(Radians{kPiOver4});
auto scaled = Matrix::MakeScale({2.0, 3.0, 1.0});
auto translated = Matrix::MakeTranslation({-200, 750, 20});
auto result = (translated * rotated * scaled).Decompose();
ASSERT_TRUE(result.has_value());
MatrixDecomposition res = result.value();
auto quaternion = Quaternion{{0.0, 0.0, 1.0}, kPiOver4};
ASSERT_QUATERNION_NEAR(res.rotation, quaternion);
ASSERT_FLOAT_EQ(res.translation.x, -200);
ASSERT_FLOAT_EQ(res.translation.y, 750);
ASSERT_FLOAT_EQ(res.translation.z, 20);
ASSERT_FLOAT_EQ(res.scale.x, 2);
ASSERT_FLOAT_EQ(res.scale.y, 3);
ASSERT_FLOAT_EQ(res.scale.z, 1);
}
TEST(GeometryTest, TestRecomposition) {
/*
* Decomposition.
*/
auto rotated = Matrix::MakeRotationZ(Radians{kPiOver4});
auto result = rotated.Decompose();
ASSERT_TRUE(result.has_value());
MatrixDecomposition res = result.value();
auto quaternion = Quaternion{{0.0, 0.0, 1.0}, kPiOver4};
ASSERT_QUATERNION_NEAR(res.rotation, quaternion);
/*
* Recomposition.
*/
ASSERT_MATRIX_NEAR(rotated, Matrix{res});
}
TEST(GeometryTest, TestRecomposition2) {
auto matrix = Matrix::MakeTranslation({100, 100, 100}) *
Matrix::MakeRotationZ(Radians{kPiOver4}) *
Matrix::MakeScale({2.0, 2.0, 2.0});
auto result = matrix.Decompose();
ASSERT_TRUE(result.has_value());
ASSERT_MATRIX_NEAR(matrix, Matrix{result.value()});
}
TEST(GeometryTest, MatrixVectorMultiplication) {
{
auto matrix = Matrix::MakeTranslation({100, 100, 100}) *
Matrix::MakeRotationZ(Radians{kPiOver2}) *
Matrix::MakeScale({2.0, 2.0, 2.0});
auto vector = Vector4(10, 20, 30, 2);
Vector4 result = matrix * vector;
auto expected = Vector4(160, 220, 260, 2);
ASSERT_VECTOR4_NEAR(result, expected);
}
{
auto matrix = Matrix::MakeTranslation({100, 100, 100}) *
Matrix::MakeRotationZ(Radians{kPiOver2}) *
Matrix::MakeScale({2.0, 2.0, 2.0});
auto vector = Vector3(10, 20, 30);
Vector3 result = matrix * vector;
auto expected = Vector3(60, 120, 160);
ASSERT_VECTOR3_NEAR(result, expected);
}
{
auto matrix = Matrix::MakeTranslation({100, 100, 100}) *
Matrix::MakeRotationZ(Radians{kPiOver2}) *
Matrix::MakeScale({2.0, 2.0, 2.0});
auto vector = Point(10, 20);
Point result = matrix * vector;
auto expected = Point(60, 120);
ASSERT_POINT_NEAR(result, expected);
}
// Matrix Vector ops should respect perspective transforms.
{
auto matrix = Matrix::MakePerspective(Radians(kPiOver2), 1, 1, 100);
auto vector = Vector3(3, 3, -3);
Vector3 result = matrix * vector;
auto expected = Vector3(-1, -1, 1.3468);
ASSERT_VECTOR3_NEAR(result, expected);
}
{
auto matrix = Matrix::MakePerspective(Radians(kPiOver2), 1, 1, 100) *
Matrix::MakeTranslation(Vector3(0, 0, -3));
auto point = Point(3, 3);
Point result = matrix * point;
auto expected = Point(-1, -1);
ASSERT_POINT_NEAR(result, expected);
}
// Resolves to 0 on perspective singularity.
{
auto matrix = Matrix::MakePerspective(Radians(kPiOver2), 1, 1, 100);
auto point = Point(3, 3);
Point result = matrix * point;
auto expected = Point(0, 0);
ASSERT_POINT_NEAR(result, expected);
}
}
TEST(GeometryTest, MatrixMakeRotationFromQuaternion) {
{
auto matrix = Matrix::MakeRotation(Quaternion({1, 0, 0}, kPiOver2));
auto expected = Matrix::MakeRotationX(Radians(kPiOver2));
ASSERT_MATRIX_NEAR(matrix, expected);
}
{
auto matrix = Matrix::MakeRotation(Quaternion({0, 1, 0}, kPiOver2));
auto expected = Matrix::MakeRotationY(Radians(kPiOver2));
ASSERT_MATRIX_NEAR(matrix, expected);
}
{
auto matrix = Matrix::MakeRotation(Quaternion({0, 0, 1}, kPiOver2));
auto expected = Matrix::MakeRotationZ(Radians(kPiOver2));
ASSERT_MATRIX_NEAR(matrix, expected);
}
}
TEST(GeometryTest, MatrixTransformDirection) {
{
auto matrix = Matrix::MakeTranslation({100, 100, 100}) *
Matrix::MakeRotationZ(Radians{kPiOver2}) *
Matrix::MakeScale({2.0, 2.0, 2.0});
auto vector = Vector4(10, 20, 30, 2);
Vector4 result = matrix.TransformDirection(vector);
auto expected = Vector4(-40, 20, 60, 2);
ASSERT_VECTOR4_NEAR(result, expected);
}
{
auto matrix = Matrix::MakeTranslation({100, 100, 100}) *
Matrix::MakeRotationZ(Radians{kPiOver2}) *
Matrix::MakeScale({2.0, 2.0, 2.0});
auto vector = Vector3(10, 20, 30);
Vector3 result = matrix.TransformDirection(vector);
auto expected = Vector3(-40, 20, 60);
ASSERT_VECTOR3_NEAR(result, expected);
}
{
auto matrix = Matrix::MakeTranslation({0, -0.4, 100}) *
Matrix::MakeRotationZ(Radians{kPiOver2}) *
Matrix::MakeScale({2.0, 2.0, 2.0});
auto vector = Point(10, 20);
Point result = matrix.TransformDirection(vector);
auto expected = Point(-40, 20);
ASSERT_POINT_NEAR(result, expected);
}
}
TEST(GeometryTest, MatrixGetMaxBasisLength) {
{
auto m = Matrix::MakeScale({3, 1, 1});
ASSERT_EQ(m.GetMaxBasisLength(), 3);
m = m * Matrix::MakeSkew(0, 4);
ASSERT_EQ(m.GetMaxBasisLength(), 5);
}
{
auto m = Matrix::MakeScale({-3, 4, 2});
ASSERT_EQ(m.GetMaxBasisLength(), 4);
}
}
TEST(GeometryTest, MatrixGetMaxBasisLengthXY) {
{
auto m = Matrix::MakeScale({3, 1, 1});
ASSERT_EQ(m.GetMaxBasisLengthXY(), 3);
m = m * Matrix::MakeSkew(0, 4);
ASSERT_EQ(m.GetMaxBasisLengthXY(), 5);
}
{
auto m = Matrix::MakeScale({-3, 4, 7});
ASSERT_EQ(m.GetMaxBasisLengthXY(), 4);
}
}
TEST(GeometryTest, MatrixMakeOrthographic) {
{
auto m = Matrix::MakeOrthographic(Size(100, 200));
auto expect = Matrix{
0.02, 0, 0, 0, //
0, -0.01, 0, 0, //
0, 0, 0, 0, //
-1, 1, 0.5, 1, //
};
ASSERT_MATRIX_NEAR(m, expect);
}
{
auto m = Matrix::MakeOrthographic(Size(400, 100));
auto expect = Matrix{
0.005, 0, 0, 0, //
0, -0.02, 0, 0, //
0, 0, 0, 0, //
-1, 1, 0.5, 1, //
};
ASSERT_MATRIX_NEAR(m, expect);
}
}
TEST(GeometryTest, MatrixMakePerspective) {
{
auto m = Matrix::MakePerspective(Degrees(60), Size(100, 200), 1, 10);
auto expect = Matrix{
3.4641, 0, 0, 0, //
0, 1.73205, 0, 0, //
0, 0, 1.11111, 1, //
0, 0, -1.11111, 0, //
};
ASSERT_MATRIX_NEAR(m, expect);
}
{
auto m = Matrix::MakePerspective(Radians(1), 2, 10, 20);
auto expect = Matrix{
0.915244, 0, 0, 0, //
0, 1.83049, 0, 0, //
0, 0, 2, 1, //
0, 0, -20, 0, //
};
ASSERT_MATRIX_NEAR(m, expect);
}
}
TEST(GeometryTest, MatrixGetBasisVectors) {
{
auto m = Matrix();
Vector3 x = m.GetBasisX();
Vector3 y = m.GetBasisY();
Vector3 z = m.GetBasisZ();
ASSERT_VECTOR3_NEAR(x, Vector3(1, 0, 0));
ASSERT_VECTOR3_NEAR(y, Vector3(0, 1, 0));
ASSERT_VECTOR3_NEAR(z, Vector3(0, 0, 1));
}
{
auto m = Matrix::MakeRotationZ(Radians{kPiOver2}) *
Matrix::MakeRotationX(Radians{kPiOver2}) *
Matrix::MakeScale(Vector3(2, 3, 4));
Vector3 x = m.GetBasisX();
Vector3 y = m.GetBasisY();
Vector3 z = m.GetBasisZ();
ASSERT_VECTOR3_NEAR(x, Vector3(0, 2, 0));
ASSERT_VECTOR3_NEAR(y, Vector3(0, 0, 3));
ASSERT_VECTOR3_NEAR(z, Vector3(4, 0, 0));
}
}
TEST(GeometryTest, MatrixGetDirectionScale) {
{
auto m = Matrix();
Scalar result = m.GetDirectionScale(Vector3{1, 0, 0});
ASSERT_FLOAT_EQ(result, 1);
}
{
auto m = Matrix::MakeRotationX(Degrees{10}) *
Matrix::MakeRotationY(Degrees{83}) *
Matrix::MakeRotationZ(Degrees{172});
Scalar result = m.GetDirectionScale(Vector3{0, 1, 0});
ASSERT_FLOAT_EQ(result, 1);
}
{
auto m = Matrix::MakeRotationZ(Radians{kPiOver2}) *
Matrix::MakeScale(Vector3(3, 4, 5));
Scalar result = m.GetDirectionScale(Vector3{2, 0, 0});
ASSERT_FLOAT_EQ(result, 8);
}
}
TEST(GeometryTest, MatrixIsAligned) {
{
auto m = Matrix::MakeTranslation({1, 2, 3});
bool result = m.IsAligned();
ASSERT_TRUE(result);
}
{
auto m = Matrix::MakeRotationZ(Degrees{123});
bool result = m.IsAligned();
ASSERT_FALSE(result);
}
}
TEST(GeometryTest, MatrixTranslationScaleOnly) {
{
auto m = Matrix();
bool result = m.IsTranslationScaleOnly();
ASSERT_TRUE(result);
}
{
auto m = Matrix::MakeScale(Vector3(2, 3, 4));
bool result = m.IsTranslationScaleOnly();
ASSERT_TRUE(result);
}
{
auto m = Matrix::MakeTranslation(Vector3(2, 3, 4));
bool result = m.IsTranslationScaleOnly();
ASSERT_TRUE(result);
}
{
auto m = Matrix::MakeRotationZ(Degrees(10));
bool result = m.IsTranslationScaleOnly();
ASSERT_FALSE(result);
}
}
TEST(GeometryTest, MatrixLookAt) {
{
auto m = Matrix::MakeLookAt(Vector3(0, 0, -1), Vector3(0, 0, 1),
Vector3(0, 1, 0));
auto expected = Matrix{
1, 0, 0, 0, //
0, 1, 0, 0, //
0, 0, 1, 0, //
0, 0, 1, 1, //
};
ASSERT_MATRIX_NEAR(m, expected);
}
// Sideways tilt.
{
auto m = Matrix::MakeLookAt(Vector3(0, 0, -1), Vector3(0, 0, 1),
Vector3(1, 1, 0).Normalize());
// clang-format off
auto expected = Matrix{
k1OverSqrt2, k1OverSqrt2, 0, 0,
-k1OverSqrt2, k1OverSqrt2, 0, 0,
0, 0, 1, 0,
0, 0, 1, 1,
};
// clang-format on
ASSERT_MATRIX_NEAR(m, expected);
}
// Half way between +x and -y, yaw 90
{
auto m =
Matrix::MakeLookAt(Vector3(), Vector3(10, -10, 0), Vector3(0, 0, -1));
// clang-format off
auto expected = Matrix{
-k1OverSqrt2, 0, k1OverSqrt2, 0,
-k1OverSqrt2, 0, -k1OverSqrt2, 0,
0, -1, 0, 0,
0, 0, 0, 1,
};
// clang-format on
ASSERT_MATRIX_NEAR(m, expected);
}
}
TEST(GeometryTest, QuaternionLerp) {
auto q1 = Quaternion{{0.0, 0.0, 1.0}, 0.0};
auto q2 = Quaternion{{0.0, 0.0, 1.0}, kPiOver4};
auto q3 = q1.Slerp(q2, 0.5);
auto expected = Quaternion{{0.0, 0.0, 1.0}, kPiOver4 / 2.0};
ASSERT_QUATERNION_NEAR(q3, expected);
}
TEST(GeometryTest, QuaternionVectorMultiply) {
{
Quaternion q({0, 0, 1}, 0);
Vector3 v(0, 1, 0);
Vector3 result = q * v;
Vector3 expected(0, 1, 0);
ASSERT_VECTOR3_NEAR(result, expected);
}
{
Quaternion q({0, 0, 1}, k2Pi);
Vector3 v(1, 0, 0);
Vector3 result = q * v;
Vector3 expected(1, 0, 0);
ASSERT_VECTOR3_NEAR(result, expected);
}
{
Quaternion q({0, 0, 1}, kPiOver4);
Vector3 v(0, 1, 0);
Vector3 result = q * v;
Vector3 expected(-k1OverSqrt2, k1OverSqrt2, 0);
ASSERT_VECTOR3_NEAR(result, expected);
}
{
Quaternion q(Vector3(1, 0, 1).Normalize(), kPi);
Vector3 v(0, 0, -1);
Vector3 result = q * v;
Vector3 expected(-1, 0, 0);
ASSERT_VECTOR3_NEAR(result, expected);
}
}
TEST(GeometryTest, CanGenerateMipCounts) {
ASSERT_EQ((Size{128, 128}.MipCount()), 7u);
ASSERT_EQ((Size{128, 256}.MipCount()), 8u);
ASSERT_EQ((Size{128, 130}.MipCount()), 8u);
ASSERT_EQ((Size{128, 257}.MipCount()), 9u);
ASSERT_EQ((Size{257, 128}.MipCount()), 9u);
ASSERT_EQ((Size{128, 0}.MipCount()), 1u);
ASSERT_EQ((Size{128, -25}.MipCount()), 1u);
ASSERT_EQ((Size{-128, 25}.MipCount()), 1u);
ASSERT_EQ((Size{1, 1}.MipCount()), 1u);
ASSERT_EQ((Size{0, 0}.MipCount()), 1u);
}
TEST(GeometryTest, CanConvertTTypesExplicitly) {
{
Point p1(1.0, 2.0);
IPoint p2 = static_cast<IPoint>(p1);
ASSERT_EQ(p2.x, 1u);
ASSERT_EQ(p2.y, 2u);
}
{
Size s1(1.0, 2.0);
ISize s2 = static_cast<ISize>(s1);
ASSERT_EQ(s2.width, 1u);
ASSERT_EQ(s2.height, 2u);
}
{
Size s1(1.0, 2.0);
Point p1 = static_cast<Point>(s1);
ASSERT_EQ(p1.x, 1u);
ASSERT_EQ(p1.y, 2u);
}
}
TEST(GeometryTest, CanPerformAlgebraicPointOps) {
{
IPoint p1(1, 2);
IPoint p2 = p1 + IPoint(1, 2);
ASSERT_EQ(p2.x, 2u);
ASSERT_EQ(p2.y, 4u);
}
{
IPoint p1(3, 6);
IPoint p2 = p1 - IPoint(1, 2);
ASSERT_EQ(p2.x, 2u);
ASSERT_EQ(p2.y, 4u);
}
{
IPoint p1(1, 2);
IPoint p2 = p1 * IPoint(2, 3);
ASSERT_EQ(p2.x, 2u);
ASSERT_EQ(p2.y, 6u);
}
{
IPoint p1(2, 6);
IPoint p2 = p1 / IPoint(2, 3);
ASSERT_EQ(p2.x, 1u);
ASSERT_EQ(p2.y, 2u);
}
}
TEST(GeometryTest, CanPerformAlgebraicPointOpsWithArithmeticTypes) {
// LHS
{
IPoint p1(1, 2);
IPoint p2 = p1 * 2.0f;
ASSERT_EQ(p2.x, 2u);
ASSERT_EQ(p2.y, 4u);
}
{
IPoint p1(2, 6);
IPoint p2 = p1 / 2.0f;
ASSERT_EQ(p2.x, 1u);
ASSERT_EQ(p2.y, 3u);
}
// RHS
{
IPoint p1(1, 2);
IPoint p2 = 2.0f * p1;
ASSERT_EQ(p2.x, 2u);
ASSERT_EQ(p2.y, 4u);
}
{
IPoint p1(2, 6);
IPoint p2 = 12.0f / p1;
ASSERT_EQ(p2.x, 6u);
ASSERT_EQ(p2.y, 2u);
}
}
TEST(GeometryTest, PointIntegerCoercesToFloat) {
// Integer on LHS, float on RHS
{
IPoint p1(1, 2);
Point p2 = p1 + Point(1, 2);
ASSERT_FLOAT_EQ(p2.x, 2u);
ASSERT_FLOAT_EQ(p2.y, 4u);
}
{
IPoint p1(3, 6);
Point p2 = p1 - Point(1, 2);
ASSERT_FLOAT_EQ(p2.x, 2u);
ASSERT_FLOAT_EQ(p2.y, 4u);
}
{
IPoint p1(1, 2);
Point p2 = p1 * Point(2, 3);
ASSERT_FLOAT_EQ(p2.x, 2u);
ASSERT_FLOAT_EQ(p2.y, 6u);
}
{
IPoint p1(2, 6);
Point p2 = p1 / Point(2, 3);
ASSERT_FLOAT_EQ(p2.x, 1u);
ASSERT_FLOAT_EQ(p2.y, 2u);
}
// Float on LHS, integer on RHS
{
Point p1(1, 2);
Point p2 = p1 + IPoint(1, 2);
ASSERT_FLOAT_EQ(p2.x, 2u);
ASSERT_FLOAT_EQ(p2.y, 4u);
}
{
Point p1(3, 6);
Point p2 = p1 - IPoint(1, 2);
ASSERT_FLOAT_EQ(p2.x, 2u);
ASSERT_FLOAT_EQ(p2.y, 4u);
}
{
Point p1(1, 2);
Point p2 = p1 * IPoint(2, 3);
ASSERT_FLOAT_EQ(p2.x, 2u);
ASSERT_FLOAT_EQ(p2.y, 6u);
}
{
Point p1(2, 6);
Point p2 = p1 / IPoint(2, 3);
ASSERT_FLOAT_EQ(p2.x, 1u);
ASSERT_FLOAT_EQ(p2.y, 2u);
}
}
TEST(GeometryTest, SizeCoercesToPoint) {
// Point on LHS, Size on RHS
{
IPoint p1(1, 2);
IPoint p2 = p1 + ISize(1, 2);
ASSERT_EQ(p2.x, 2u);
ASSERT_EQ(p2.y, 4u);
}
{
IPoint p1(3, 6);
IPoint p2 = p1 - ISize(1, 2);
ASSERT_EQ(p2.x, 2u);
ASSERT_EQ(p2.y, 4u);
}
{
IPoint p1(1, 2);
IPoint p2 = p1 * ISize(2, 3);
ASSERT_EQ(p2.x, 2u);
ASSERT_EQ(p2.y, 6u);
}
{
IPoint p1(2, 6);
IPoint p2 = p1 / ISize(2, 3);
ASSERT_EQ(p2.x, 1u);
ASSERT_EQ(p2.y, 2u);
}
// Size on LHS, Point on RHS
{
ISize p1(1, 2);
IPoint p2 = p1 + IPoint(1, 2);
ASSERT_EQ(p2.x, 2u);
ASSERT_EQ(p2.y, 4u);
}
{
ISize p1(3, 6);
IPoint p2 = p1 - IPoint(1, 2);
ASSERT_EQ(p2.x, 2u);
ASSERT_EQ(p2.y, 4u);
}
{
ISize p1(1, 2);
IPoint p2 = p1 * IPoint(2, 3);
ASSERT_EQ(p2.x, 2u);
ASSERT_EQ(p2.y, 6u);
}
{
ISize p1(2, 6);
IPoint p2 = p1 / IPoint(2, 3);
ASSERT_EQ(p2.x, 1u);
ASSERT_EQ(p2.y, 2u);
}
}
TEST(GeometryTest, CanUsePointAssignmentOperators) {
// Point on RHS
{
IPoint p(1, 2);
p += IPoint(1, 2);
ASSERT_EQ(p.x, 2u);
ASSERT_EQ(p.y, 4u);
}
{
IPoint p(3, 6);
p -= IPoint(1, 2);
ASSERT_EQ(p.x, 2u);
ASSERT_EQ(p.y, 4u);
}
{
IPoint p(1, 2);
p *= IPoint(2, 3);
ASSERT_EQ(p.x, 2u);
ASSERT_EQ(p.y, 6u);
}
{
IPoint p(2, 6);
p /= IPoint(2, 3);
ASSERT_EQ(p.x, 1u);
ASSERT_EQ(p.y, 2u);
}
// Size on RHS
{
IPoint p(1, 2);
p += ISize(1, 2);
ASSERT_EQ(p.x, 2u);
ASSERT_EQ(p.y, 4u);
}
{
IPoint p(3, 6);
p -= ISize(1, 2);
ASSERT_EQ(p.x, 2u);
ASSERT_EQ(p.y, 4u);
}
{
IPoint p(1, 2);
p *= ISize(2, 3);
ASSERT_EQ(p.x, 2u);
ASSERT_EQ(p.y, 6u);
}
{
IPoint p(2, 6);
p /= ISize(2, 3);
ASSERT_EQ(p.x, 1u);
ASSERT_EQ(p.y, 2u);
}
// Arithmetic type on RHS
{
IPoint p(1, 2);
p *= 3;
ASSERT_EQ(p.x, 3u);
ASSERT_EQ(p.y, 6u);
}
{
IPoint p(3, 6);
p /= 3;
ASSERT_EQ(p.x, 1u);
ASSERT_EQ(p.y, 2u);
}
}
TEST(GeometryTest, PointDotProduct) {
{
Point p(1, 0);
Scalar s = p.Dot(Point(-1, 0));
ASSERT_FLOAT_EQ(s, -1);
}
{
Point p(0, -1);
Scalar s = p.Dot(Point(-1, 0));
ASSERT_FLOAT_EQ(s, 0);
}
{
Point p(1, 2);
Scalar s = p.Dot(Point(3, -4));
ASSERT_FLOAT_EQ(s, -5);
}
}
TEST(GeometryTest, PointCrossProduct) {
{
Point p(1, 0);
Scalar s = p.Cross(Point(-1, 0));
ASSERT_FLOAT_EQ(s, 0);
}
{
Point p(0, -1);
Scalar s = p.Cross(Point(-1, 0));
ASSERT_FLOAT_EQ(s, -1);
}
{
Point p(1, 2);
Scalar s = p.Cross(Point(3, -4));
ASSERT_FLOAT_EQ(s, -10);
}
}
TEST(GeometryTest, PointReflect) {
{
Point axis = Point(0, 1);
Point a(2, 3);
auto reflected = a.Reflect(axis);
auto expected = Point(2, -3);
ASSERT_POINT_NEAR(reflected, expected);
}
{
Point axis = Point(1, 1).Normalize();
Point a(1, 0);
auto reflected = a.Reflect(axis);
auto expected = Point(0, -1);
ASSERT_POINT_NEAR(reflected, expected);
}
{
Point axis = Point(1, 1).Normalize();
Point a(-1, -1);
auto reflected = a.Reflect(axis);
ASSERT_POINT_NEAR(reflected, -a);
}
}
TEST(GeometryTest, PointAbs) {
Point a(-1, -2);
auto a_abs = a.Abs();
auto expected = Point(1, 2);
ASSERT_POINT_NEAR(a_abs, expected);
}
TEST(GeometryTest, PointAngleTo) {
// Negative result in the CCW (with up = -Y) direction.
{
Point a(1, 1);
Point b(1, -1);
Radians actual = a.AngleTo(b);
Radians expected = Radians{-kPi / 2};
ASSERT_FLOAT_EQ(actual.radians, expected.radians);
}
// Check the other direction to ensure the result is signed correctly.
{
Point a(1, -1);
Point b(1, 1);
Radians actual = a.AngleTo(b);
Radians expected = Radians{kPi / 2};
ASSERT_FLOAT_EQ(actual.radians, expected.radians);
}
// Differences in magnitude should have no impact on the result.
{
Point a(100, -100);
Point b(0.01, 0.01);
Radians actual = a.AngleTo(b);
Radians expected = Radians{kPi / 2};
ASSERT_FLOAT_EQ(actual.radians, expected.radians);
}
}
TEST(GeometryTest, PointMin) {
Point p(1, 2);
Point result = p.Min({0, 10});
Point expected(0, 2);
ASSERT_POINT_NEAR(result, expected);
}
TEST(GeometryTest, Vector3Min) {
Vector3 p(1, 2, 3);
Vector3 result = p.Min({0, 10, 2});
Vector3 expected(0, 2, 2);
ASSERT_VECTOR3_NEAR(result, expected);
}
TEST(GeometryTest, Vector4Min) {
Vector4 p(1, 2, 3, 4);
Vector4 result = p.Min({0, 10, 2, 1});
Vector4 expected(0, 2, 2, 1);
ASSERT_VECTOR4_NEAR(result, expected);
}
TEST(GeometryTest, PointMax) {
Point p(1, 2);
Point result = p.Max({0, 10});
Point expected(1, 10);
ASSERT_POINT_NEAR(result, expected);
}
TEST(GeometryTest, Vector3Max) {
Vector3 p(1, 2, 3);
Vector3 result = p.Max({0, 10, 2});
Vector3 expected(1, 10, 3);
ASSERT_VECTOR3_NEAR(result, expected);
}
TEST(GeometryTest, Vector4Max) {
Vector4 p(1, 2, 3, 4);
Vector4 result = p.Max({0, 10, 2, 1});
Vector4 expected(1, 10, 3, 4);
ASSERT_VECTOR4_NEAR(result, expected);
}
TEST(GeometryTest, PointFloor) {
Point p(1.5, 2.3);
Point result = p.Floor();
Point expected(1, 2);
ASSERT_POINT_NEAR(result, expected);
}
TEST(GeometryTest, Vector3Floor) {
Vector3 p(1.5, 2.3, 3.9);
Vector3 result = p.Floor();
Vector3 expected(1, 2, 3);
ASSERT_VECTOR3_NEAR(result, expected);
}
TEST(GeometryTest, Vector4Floor) {
Vector4 p(1.5, 2.3, 3.9, 4.0);
Vector4 result = p.Floor();
Vector4 expected(1, 2, 3, 4);
ASSERT_VECTOR4_NEAR(result, expected);
}
TEST(GeometryTest, PointCeil) {
Point p(1.5, 2.3);
Point result = p.Ceil();
Point expected(2, 3);
ASSERT_POINT_NEAR(result, expected);
}
TEST(GeometryTest, Vector3Ceil) {
Vector3 p(1.5, 2.3, 3.9);
Vector3 result = p.Ceil();
Vector3 expected(2, 3, 4);
ASSERT_VECTOR3_NEAR(result, expected);
}
TEST(GeometryTest, Vector4Ceil) {
Vector4 p(1.5, 2.3, 3.9, 4.0);
Vector4 result = p.Ceil();
Vector4 expected(2, 3, 4, 4);
ASSERT_VECTOR4_NEAR(result, expected);
}
TEST(GeometryTest, PointRound) {
Point p(1.5, 2.3);
Point result = p.Round();
Point expected(2, 2);
ASSERT_POINT_NEAR(result, expected);
}
TEST(GeometryTest, Vector3Round) {
Vector3 p(1.5, 2.3, 3.9);
Vector3 result = p.Round();
Vector3 expected(2, 2, 4);
ASSERT_VECTOR3_NEAR(result, expected);
}
TEST(GeometryTest, Vector4Round) {
Vector4 p(1.5, 2.3, 3.9, 4.0);
Vector4 result = p.Round();
Vector4 expected(2, 2, 4, 4);
ASSERT_VECTOR4_NEAR(result, expected);
}
TEST(GeometryTest, PointLerp) {
Point p(1, 2);
Point result = p.Lerp({5, 10}, 0.75);
Point expected(4, 8);
ASSERT_POINT_NEAR(result, expected);
}
TEST(GeometryTest, Vector3Lerp) {
Vector3 p(1, 2, 3);
Vector3 result = p.Lerp({5, 10, 15}, 0.75);
Vector3 expected(4, 8, 12);
ASSERT_VECTOR3_NEAR(result, expected);
}
TEST(GeometryTest, Vector4Lerp) {
Vector4 p(1, 2, 3, 4);
Vector4 result = p.Lerp({5, 10, 15, 20}, 0.75);
Vector4 expected(4, 8, 12, 16);
ASSERT_VECTOR4_NEAR(result, expected);
}
TEST(GeometryTest, CanUseVector3AssignmentOperators) {
{
Vector3 p(1, 2, 4);
p += Vector3(1, 2, 4);
ASSERT_EQ(p.x, 2u);
ASSERT_EQ(p.y, 4u);
ASSERT_EQ(p.z, 8u);
}
{
Vector3 p(3, 6, 8);
p -= Vector3(1, 2, 3);
ASSERT_EQ(p.x, 2u);
ASSERT_EQ(p.y, 4u);
ASSERT_EQ(p.z, 5u);
}
{
Vector3 p(1, 2, 3);
p *= Vector3(2, 3, 4);
ASSERT_EQ(p.x, 2u);
ASSERT_EQ(p.y, 6u);
ASSERT_EQ(p.z, 12u);
}
{
Vector3 p(1, 2, 3);
p *= 2;
ASSERT_EQ(p.x, 2u);
ASSERT_EQ(p.y, 4u);
ASSERT_EQ(p.z, 6u);
}
{
Vector3 p(2, 6, 12);
p /= Vector3(2, 3, 4);
ASSERT_EQ(p.x, 1u);
ASSERT_EQ(p.y, 2u);
ASSERT_EQ(p.z, 3u);
}
{
Vector3 p(2, 6, 12);
p /= 2;
ASSERT_EQ(p.x, 1u);
ASSERT_EQ(p.y, 3u);
ASSERT_EQ(p.z, 6u);
}
}
TEST(GeometryTest, CanPerformAlgebraicVector3Ops) {
{
Vector3 p1(1, 2, 3);
Vector3 p2 = p1 + Vector3(1, 2, 3);
ASSERT_EQ(p2.x, 2u);
ASSERT_EQ(p2.y, 4u);
ASSERT_EQ(p2.z, 6u);
}
{
Vector3 p1(3, 6, 9);
Vector3 p2 = p1 - Vector3(1, 2, 3);
ASSERT_EQ(p2.x, 2u);
ASSERT_EQ(p2.y, 4u);
ASSERT_EQ(p2.z, 6u);
}
{
Vector3 p1(1, 2, 3);
Vector3 p2 = p1 * Vector3(2, 3, 4);
ASSERT_EQ(p2.x, 2u);
ASSERT_EQ(p2.y, 6u);
ASSERT_EQ(p2.z, 12u);
}
{
Vector3 p1(2, 6, 12);
Vector3 p2 = p1 / Vector3(2, 3, 4);
ASSERT_EQ(p2.x, 1u);
ASSERT_EQ(p2.y, 2u);
ASSERT_EQ(p2.z, 3u);
}
}
TEST(GeometryTest, CanPerformAlgebraicVector3OpsWithArithmeticTypes) {
// LHS
{
Vector3 p1(1, 2, 3);
Vector3 p2 = p1 + 2.0f;
ASSERT_EQ(p2.x, 3);
ASSERT_EQ(p2.y, 4);
ASSERT_EQ(p2.z, 5);
}
{
Vector3 p1(1, 2, 3);
Vector3 p2 = p1 - 2.0f;
ASSERT_EQ(p2.x, -1);
ASSERT_EQ(p2.y, 0);
ASSERT_EQ(p2.z, 1);
}
{
Vector3 p1(1, 2, 3);
Vector3 p2 = p1 * 2.0f;
ASSERT_EQ(p2.x, 2);
ASSERT_EQ(p2.y, 4);
ASSERT_EQ(p2.z, 6);
}
{
Vector3 p1(2, 6, 12);
Vector3 p2 = p1 / 2.0f;
ASSERT_EQ(p2.x, 1);
ASSERT_EQ(p2.y, 3);
ASSERT_EQ(p2.z, 6);
}
// RHS
{
Vector3 p1(1, 2, 3);
Vector3 p2 = 2.0f + p1;
ASSERT_EQ(p2.x, 3);
ASSERT_EQ(p2.y, 4);
ASSERT_EQ(p2.z, 5);
}
{
Vector3 p1(1, 2, 3);
Vector3 p2 = 2.0f - p1;
ASSERT_EQ(p2.x, 1);
ASSERT_EQ(p2.y, 0);
ASSERT_EQ(p2.z, -1);
}
{
Vector3 p1(1, 2, 3);
Vector3 p2 = 2.0f * p1;
ASSERT_EQ(p2.x, 2);
ASSERT_EQ(p2.y, 4);
ASSERT_EQ(p2.z, 6);
}
{
Vector3 p1(2, 6, 12);
Vector3 p2 = 12.0f / p1;
ASSERT_EQ(p2.x, 6);
ASSERT_EQ(p2.y, 2);
ASSERT_EQ(p2.z, 1);
}
}
TEST(GeometryTest, ColorPremultiply) {
{
Color a(1.0, 0.5, 0.2, 0.5);
Color premultiplied = a.Premultiply();
Color expected = Color(0.5, 0.25, 0.1, 0.5);
ASSERT_COLOR_NEAR(premultiplied, expected);
}
{
Color a(0.5, 0.25, 0.1, 0.5);
Color unpremultiplied = a.Unpremultiply();
Color expected = Color(1.0, 0.5, 0.2, 0.5);
ASSERT_COLOR_NEAR(unpremultiplied, expected);
}
{
Color a(0.5, 0.25, 0.1, 0.0);
Color unpremultiplied = a.Unpremultiply();
Color expected = Color(0.0, 0.0, 0.0, 0.0);
ASSERT_COLOR_NEAR(unpremultiplied, expected);
}
}
TEST(GeometryTest, ColorR8G8B8A8) {
{
Color a(1.0, 0.5, 0.2, 0.5);
std::array<uint8_t, 4> expected = {255, 128, 51, 128};
ASSERT_ARRAY_4_NEAR(a.ToR8G8B8A8(), expected);
}
{
Color a(0.0, 0.0, 0.0, 0.0);
std::array<uint8_t, 4> expected = {0, 0, 0, 0};
ASSERT_ARRAY_4_NEAR(a.ToR8G8B8A8(), expected);
}
{
Color a(1.0, 1.0, 1.0, 1.0);
std::array<uint8_t, 4> expected = {255, 255, 255, 255};
ASSERT_ARRAY_4_NEAR(a.ToR8G8B8A8(), expected);
}
}
TEST(GeometryTest, ColorLerp) {
{
Color a(0.0, 0.0, 0.0, 0.0);
Color b(1.0, 1.0, 1.0, 1.0);
ASSERT_COLOR_NEAR(Color::Lerp(a, b, 0.5), Color(0.5, 0.5, 0.5, 0.5));
ASSERT_COLOR_NEAR(Color::Lerp(a, b, 0.0), a);
ASSERT_COLOR_NEAR(Color::Lerp(a, b, 1.0), b);
ASSERT_COLOR_NEAR(Color::Lerp(a, b, 0.2), Color(0.2, 0.2, 0.2, 0.2));
}
{
Color a(0.2, 0.4, 1.0, 0.5);
Color b(0.4, 1.0, 0.2, 0.3);
ASSERT_COLOR_NEAR(Color::Lerp(a, b, 0.5), Color(0.3, 0.7, 0.6, 0.4));
ASSERT_COLOR_NEAR(Color::Lerp(a, b, 0.0), a);
ASSERT_COLOR_NEAR(Color::Lerp(a, b, 1.0), b);
ASSERT_COLOR_NEAR(Color::Lerp(a, b, 0.2), Color(0.24, 0.52, 0.84, 0.46));
}
}
TEST(GeometryTest, ColorClamp01) {
{
Color result = Color(0.5, 0.5, 0.5, 0.5).Clamp01();
Color expected = Color(0.5, 0.5, 0.5, 0.5);
ASSERT_COLOR_NEAR(result, expected);
}
{
Color result = Color(-1, -1, -1, -1).Clamp01();
Color expected = Color(0, 0, 0, 0);
ASSERT_COLOR_NEAR(result, expected);
}
{
Color result = Color(2, 2, 2, 2).Clamp01();
Color expected = Color(1, 1, 1, 1);
ASSERT_COLOR_NEAR(result, expected);
}
}
TEST(GeometryTest, ColorMakeRGBA8) {
{
Color a = Color::MakeRGBA8(0, 0, 0, 0);
Color b = Color::BlackTransparent();
ASSERT_COLOR_NEAR(a, b);
}
{
Color a = Color::MakeRGBA8(255, 255, 255, 255);
Color b = Color::White();
ASSERT_COLOR_NEAR(a, b);
}
{
Color a = Color::MakeRGBA8(63, 127, 191, 127);
Color b(0.247059, 0.498039, 0.74902, 0.498039);
ASSERT_COLOR_NEAR(a, b);
}
}
TEST(GeometryTest, ColorApplyColorMatrix) {
{
ColorMatrix color_matrix = {
1, 1, 1, 1, 1, //
1, 1, 1, 1, 1, //
1, 1, 1, 1, 1, //
1, 1, 1, 1, 1, //
};
auto result = Color::White().ApplyColorMatrix(color_matrix);
auto expected = Color(1, 1, 1, 1);
ASSERT_COLOR_NEAR(result, expected);
}
{
ColorMatrix color_matrix = {
0.1, 0, 0, 0, 0.01, //
0, 0.2, 0, 0, 0.02, //
0, 0, 0.3, 0, 0.03, //
0, 0, 0, 0.4, 0.04, //
};
auto result = Color::White().ApplyColorMatrix(color_matrix);
auto expected = Color(0.11, 0.22, 0.33, 0.44);
ASSERT_COLOR_NEAR(result, expected);
}
}
TEST(GeometryTest, ColorLinearToSRGB) {
{
auto result = Color::White().LinearToSRGB();
auto expected = Color(1, 1, 1, 1);
ASSERT_COLOR_NEAR(result, expected);
}
{
auto result = Color::BlackTransparent().LinearToSRGB();
auto expected = Color(0, 0, 0, 0);
ASSERT_COLOR_NEAR(result, expected);
}
{
auto result = Color(0.2, 0.4, 0.6, 0.8).LinearToSRGB();
auto expected = Color(0.484529, 0.665185, 0.797738, 0.8);
ASSERT_COLOR_NEAR(result, expected);
}
}
TEST(GeometryTest, ColorSRGBToLinear) {
{
auto result = Color::White().SRGBToLinear();
auto expected = Color(1, 1, 1, 1);
ASSERT_COLOR_NEAR(result, expected);
}
{
auto result = Color::BlackTransparent().SRGBToLinear();
auto expected = Color(0, 0, 0, 0);
ASSERT_COLOR_NEAR(result, expected);
}
{
auto result = Color(0.2, 0.4, 0.6, 0.8).SRGBToLinear();
auto expected = Color(0.0331048, 0.132868, 0.318547, 0.8);
ASSERT_COLOR_NEAR(result, expected);
}
}
struct ColorBlendTestData {
static constexpr Color kDestinationColor =
Color::CornflowerBlue().WithAlpha(0.75);
static constexpr Color kSourceColors[] = {Color::White().WithAlpha(0.75),
Color::LimeGreen().WithAlpha(0.75),
Color::Black().WithAlpha(0.75)};
// THIS RESULT TABLE IS GENERATED!
//
// Uncomment the `GenerateColorBlendResults` test below to print a new table
// after making changes to `Color::Blend`.
static constexpr Color kExpectedResults
[sizeof(kSourceColors)]
[static_cast<std::underlying_type_t<BlendMode>>(BlendMode::kLast) + 1] = {
{
{0, 0, 0, 0}, // Clear
{1, 1, 1, 0.75}, // Source
{0.392157, 0.584314, 0.929412, 0.75}, // Destination
{0.878431, 0.916863, 0.985882, 0.9375}, // SourceOver
{0.513726, 0.667451, 0.943529, 0.9375}, // DestinationOver
{1, 1, 1, 0.5625}, // SourceIn
{0.392157, 0.584314, 0.929412, 0.5625}, // DestinationIn
{1, 1, 1, 0.1875}, // SourceOut
{0.392157, 0.584314, 0.929412, 0.1875}, // DestinationOut
{0.848039, 0.896078, 0.982353, 0.75}, // SourceATop
{0.544118, 0.688235, 0.947059, 0.75}, // DestinationATop
{0.696078, 0.792157, 0.964706, 0.375}, // Xor
{1, 1, 1, 1}, // Plus
{0.392157, 0.584314, 0.929412, 0.5625}, // Modulate
{0.878431, 0.916863, 0.985882, 0.9375}, // Screen
{0.74902, 0.916863, 0.985882, 0.9375}, // Overlay
{0.513726, 0.667451, 0.943529, 0.9375}, // Darken
{0.878431, 0.916863, 0.985882, 0.9375}, // Lighten
{0.878431, 0.916863, 0.985882, 0.9375}, // ColorDodge
{0.513725, 0.667451, 0.943529, 0.9375}, // ColorBurn
{0.878431, 0.916863, 0.985882, 0.9375}, // HardLight
{0.654166, 0.775505, 0.964318, 0.9375}, // SoftLight
{0.643137, 0.566275, 0.428235, 0.9375}, // Difference
{0.643137, 0.566275, 0.428235, 0.9375}, // Exclusion
{0.513726, 0.667451, 0.943529, 0.9375}, // Multiply
{0.617208, 0.655639, 0.724659, 0.9375}, // Hue
{0.617208, 0.655639, 0.724659, 0.9375}, // Saturation
{0.617208, 0.655639, 0.724659, 0.9375}, // Color
{0.878431, 0.916863, 0.985882, 0.9375}, // Luminosity
},
{
{0, 0, 0, 0}, // Clear
{0.196078, 0.803922, 0.196078, 0.75}, // Source
{0.392157, 0.584314, 0.929412, 0.75}, // Destination
{0.235294, 0.76, 0.342745, 0.9375}, // SourceOver
{0.352941, 0.628235, 0.782745, 0.9375}, // DestinationOver
{0.196078, 0.803922, 0.196078, 0.5625}, // SourceIn
{0.392157, 0.584314, 0.929412, 0.5625}, // DestinationIn
{0.196078, 0.803922, 0.196078, 0.1875}, // SourceOut
{0.392157, 0.584314, 0.929412, 0.1875}, // DestinationOut
{0.245098, 0.74902, 0.379412, 0.75}, // SourceATop
{0.343137, 0.639216, 0.746078, 0.75}, // DestinationATop
{0.294118, 0.694118, 0.562745, 0.375}, // Xor
{0.441176, 1, 0.844118, 1}, // Plus
{0.0768935, 0.469742, 0.182238, 0.5625}, // Modulate
{0.424452, 0.828743, 0.79105, 0.9375}, // Screen
{0.209919, 0.779839, 0.757001, 0.9375}, // Overlay
{0.235294, 0.628235, 0.342745, 0.9375}, // Darken
{0.352941, 0.76, 0.782745, 0.9375}, // Lighten
{0.41033, 0.877647, 0.825098, 0.9375}, // ColorDodge
{0.117647, 0.567403, 0.609098, 0.9375}, // ColorBurn
{0.209919, 0.779839, 0.443783, 0.9375}, // HardLight
{0.266006, 0.693915, 0.758818, 0.9375}, // SoftLight
{0.235294, 0.409412, 0.665098, 0.9375}, // Difference
{0.378316, 0.546897, 0.681707, 0.9375}, // Exclusion
{0.163783, 0.559493, 0.334441, 0.9375}, // Multiply
{0.266235, 0.748588, 0.373686, 0.9375}, // Hue
{0.339345, 0.629787, 0.811502, 0.9375}, // Saturation
{0.241247, 0.765953, 0.348698, 0.9375}, // Color
{0.346988, 0.622282, 0.776792, 0.9375}, // Luminosity
},
{
{0, 0, 0, 0}, // Clear
{0, 0, 0, 0.75}, // Source
{0.392157, 0.584314, 0.929412, 0.75}, // Destination
{0.0784314, 0.116863, 0.185882, 0.9375}, // SourceOver
{0.313726, 0.467451, 0.743529, 0.9375}, // DestinationOver
{0, 0, 0, 0.5625}, // SourceIn
{0.392157, 0.584314, 0.929412, 0.5625}, // DestinationIn
{0, 0, 0, 0.1875}, // SourceOut
{0.392157, 0.584314, 0.929412, 0.1875}, // DestinationOut
{0.0980392, 0.146078, 0.232353, 0.75}, // SourceATop
{0.294118, 0.438235, 0.697059, 0.75}, // DestinationATop
{0.196078, 0.292157, 0.464706, 0.375}, // Xor
{0.294118, 0.438235, 0.697059, 1}, // Plus
{0, 0, 0, 0.5625}, // Modulate
{0.313726, 0.467451, 0.743529, 0.9375}, // Screen
{0.0784314, 0.218039, 0.701176, 0.9375}, // Overlay
{0.0784314, 0.116863, 0.185882, 0.9375}, // Darken
{0.313726, 0.467451, 0.743529, 0.9375}, // Lighten
{0.313726, 0.467451, 0.743529, 0.9375}, // ColorDodge
{0.0784314, 0.116863, 0.185882, 0.9375}, // ColorBurn
{0.0784314, 0.116863, 0.185882, 0.9375}, // HardLight
{0.170704, 0.321716, 0.704166, 0.9375}, // SoftLight
{0.313726, 0.467451, 0.743529, 0.9375}, // Difference
{0.313726, 0.467451, 0.743529, 0.9375}, // Exclusion
{0.0784314, 0.116863, 0.185882, 0.9375}, // Multiply
{0.417208, 0.455639, 0.524659, 0.9375}, // Hue
{0.417208, 0.455639, 0.524659, 0.9375}, // Saturation
{0.417208, 0.455639, 0.524659, 0.9375}, // Color
{0.0784314, 0.116863, 0.185882, 0.9375}, // Luminosity
},
};
};
/// To print a new ColorBlendTestData::kExpectedResults table, uncomment this
/// test and run with:
/// --gtest_filter="GeometryTest.GenerateColorBlendResults"
/*
TEST(GeometryTest, GenerateColorBlendResults) {
auto& o = std::cout;
using BlendT = std::underlying_type_t<BlendMode>;
o << "{";
for (const auto& source : ColorBlendTestData::kSourceColors) {
o << "{";
for (BlendT blend_i = 0;
blend_i < static_cast<BlendT>(BlendMode::kLast) + 1; blend_i++) {
auto blend = static_cast<BlendMode>(blend_i);
Color c = ColorBlendTestData::kDestinationColor.Blend(source, blend);
o << "{" << c.red << "," << c.green << "," << c.blue << "," << c.alpha
<< "}, // " << BlendModeToString(blend) << std::endl;
}
o << "},";
}
o << "};" << std::endl;
}
*/
#define _BLEND_MODE_RESULT_CHECK(blend_mode) \
blend_i = static_cast<BlendT>(BlendMode::k##blend_mode); \
expected = ColorBlendTestData::kExpectedResults[source_i][blend_i]; \
EXPECT_COLOR_NEAR(dst.Blend(src, BlendMode::k##blend_mode), expected);
TEST(GeometryTest, ColorBlendReturnsExpectedResults) {
using BlendT = std::underlying_type_t<BlendMode>;
Color dst = ColorBlendTestData::kDestinationColor;
for (size_t source_i = 0;
source_i < sizeof(ColorBlendTestData::kSourceColors) / sizeof(Color);
source_i++) {
Color src = ColorBlendTestData::kSourceColors[source_i];
size_t blend_i;
Color expected;
IMPELLER_FOR_EACH_BLEND_MODE(_BLEND_MODE_RESULT_CHECK)
}
}
#define _BLEND_MODE_NAME_CHECK(blend_mode) \
case BlendMode::k##blend_mode: \
ASSERT_STREQ(result, #blend_mode); \
break;
TEST(GeometryTest, BlendModeToString) {
using BlendT = std::underlying_type_t<BlendMode>;
for (BlendT i = 0; i <= static_cast<BlendT>(BlendMode::kLast); i++) {
auto mode = static_cast<BlendMode>(i);
auto result = BlendModeToString(mode);
switch (mode) { IMPELLER_FOR_EACH_BLEND_MODE(_BLEND_MODE_NAME_CHECK) }
}
}
TEST(GeometryTest, CanConvertBetweenDegressAndRadians) {
{
auto deg = Degrees{90.0};
Radians rad = deg;
ASSERT_FLOAT_EQ(rad.radians, kPiOver2);
}
}
TEST(GeometryTest, MatrixPrinting) {
{
std::stringstream stream;
Matrix m;
stream << m;
ASSERT_EQ(stream.str(), R"((
1.000000, 0.000000, 0.000000, 0.000000,
0.000000, 1.000000, 0.000000, 0.000000,
0.000000, 0.000000, 1.000000, 0.000000,
0.000000, 0.000000, 0.000000, 1.000000,
))");
}
{
std::stringstream stream;
Matrix m = Matrix::MakeTranslation(Vector3(10, 20, 30));
stream << m;
ASSERT_EQ(stream.str(), R"((
1.000000, 0.000000, 0.000000, 10.000000,
0.000000, 1.000000, 0.000000, 20.000000,
0.000000, 0.000000, 1.000000, 30.000000,
0.000000, 0.000000, 0.000000, 1.000000,
))");
}
}
TEST(GeometryTest, PointPrinting) {
{
std::stringstream stream;
Point m;
stream << m;
ASSERT_EQ(stream.str(), "(0, 0)");
}
{
std::stringstream stream;
Point m(13, 37);
stream << m;
ASSERT_EQ(stream.str(), "(13, 37)");
}
}
TEST(GeometryTest, Vector3Printing) {
{
std::stringstream stream;
Vector3 m;
stream << m;
ASSERT_EQ(stream.str(), "(0, 0, 0)");
}
{
std::stringstream stream;
Vector3 m(1, 2, 3);
stream << m;
ASSERT_EQ(stream.str(), "(1, 2, 3)");
}
}
TEST(GeometryTest, Vector4Printing) {
{
std::stringstream stream;
Vector4 m;
stream << m;
ASSERT_EQ(stream.str(), "(0, 0, 0, 1)");
}
{
std::stringstream stream;
Vector4 m(1, 2, 3, 4);
stream << m;
ASSERT_EQ(stream.str(), "(1, 2, 3, 4)");
}
}
TEST(GeometryTest, ColorPrinting) {
{
std::stringstream stream;
Color m;
stream << m;
ASSERT_EQ(stream.str(), "(0, 0, 0, 0)");
}
{
std::stringstream stream;
Color m(1, 2, 3, 4);
stream << m;
ASSERT_EQ(stream.str(), "(1, 2, 3, 4)");
}
}
TEST(GeometryTest, ToIColor) {
ASSERT_EQ(Color::ToIColor(Color(0, 0, 0, 0)), 0u);
ASSERT_EQ(Color::ToIColor(Color(1.0, 1.0, 1.0, 1.0)), 0xFFFFFFFF);
ASSERT_EQ(Color::ToIColor(Color(0.5, 0.5, 1.0, 1.0)), 0xFF8080FF);
}
TEST(GeometryTest, Gradient) {
{
// Simple 2 color gradient produces color buffer containing exactly those
// values.
std::vector<Color> colors = {Color::Red(), Color::Blue()};
std::vector<Scalar> stops = {0.0, 1.0};
auto gradient = CreateGradientBuffer(colors, stops);
ASSERT_COLOR_BUFFER_NEAR(gradient.color_bytes, colors);
ASSERT_EQ(gradient.texture_size, 2u);
}
{
// Gradient with duplicate stops does not create an empty texture.
std::vector<Color> colors = {Color::Red(), Color::Yellow(), Color::Black(),
Color::Blue()};
std::vector<Scalar> stops = {0.0, 0.25, 0.25, 1.0};
auto gradient = CreateGradientBuffer(colors, stops);
ASSERT_EQ(gradient.texture_size, 5u);
}
{
// Simple N color gradient produces color buffer containing exactly those
// values.
std::vector<Color> colors = {Color::Red(), Color::Blue(), Color::Green(),
Color::White()};
std::vector<Scalar> stops = {0.0, 0.33, 0.66, 1.0};
auto gradient = CreateGradientBuffer(colors, stops);
ASSERT_COLOR_BUFFER_NEAR(gradient.color_bytes, colors);
ASSERT_EQ(gradient.texture_size, 4u);
}
{
// Gradient with color stops will lerp and scale buffer.
std::vector<Color> colors = {Color::Red(), Color::Blue(), Color::Green()};
std::vector<Scalar> stops = {0.0, 0.25, 1.0};
auto gradient = CreateGradientBuffer(colors, stops);
std::vector<Color> lerped_colors = {
Color::Red(),
Color::Blue(),
Color::Lerp(Color::Blue(), Color::Green(), 0.3333),
Color::Lerp(Color::Blue(), Color::Green(), 0.6666),
Color::Green(),
};
ASSERT_COLOR_BUFFER_NEAR(gradient.color_bytes, lerped_colors);
ASSERT_EQ(gradient.texture_size, 5u);
}
{
// Gradient size is capped at 1024.
std::vector<Color> colors = {};
std::vector<Scalar> stops = {};
for (auto i = 0u; i < 1025; i++) {
colors.push_back(Color::Blue());
stops.push_back(i / 1025.0);
}
auto gradient = CreateGradientBuffer(colors, stops);
ASSERT_EQ(gradient.texture_size, 1024u);
ASSERT_EQ(gradient.color_bytes.size(), 1024u * 4);
}
}
TEST(GeometryTest, HalfConversions) {
#if defined(FML_OS_MACOSX) || defined(FML_OS_IOS) || \
defined(FML_OS_IOS_SIMULATOR)
ASSERT_EQ(ScalarToHalf(0.0), 0.0f16);
ASSERT_EQ(ScalarToHalf(0.05), 0.05f16);
ASSERT_EQ(ScalarToHalf(2.43), 2.43f16);
ASSERT_EQ(ScalarToHalf(-1.45), -1.45f16);
// 65504 is the largest possible half.
ASSERT_EQ(ScalarToHalf(65504.0f), 65504.0f16);
ASSERT_EQ(ScalarToHalf(65504.0f + 1), 65504.0f16);
// Colors
ASSERT_EQ(HalfVector4(Color::Red()),
HalfVector4(1.0f16, 0.0f16, 0.0f16, 1.0f16));
ASSERT_EQ(HalfVector4(Color::Green()),
HalfVector4(0.0f16, 1.0f16, 0.0f16, 1.0f16));
ASSERT_EQ(HalfVector4(Color::Blue()),
HalfVector4(0.0f16, 0.0f16, 1.0f16, 1.0f16));
ASSERT_EQ(HalfVector4(Color::Black().WithAlpha(0)),
HalfVector4(0.0f16, 0.0f16, 0.0f16, 0.0f16));
ASSERT_EQ(HalfVector3(Vector3(4.0, 6.0, -1.0)),
HalfVector3(4.0f16, 6.0f16, -1.0f16));
ASSERT_EQ(HalfVector2(Vector2(4.0, 6.0)), HalfVector2(4.0f16, 6.0f16));
ASSERT_EQ(Half(0.5f), Half(0.5f16));
ASSERT_EQ(Half(0.5), Half(0.5f16));
ASSERT_EQ(Half(5), Half(5.0f16));
#else
GTEST_SKIP() << "Half-precision floats (IEEE 754) are not portable and "
"only used on Apple platforms.";
#endif // FML_OS_MACOSX || FML_OS_IOS || FML_OS_IOS_SIMULATOR
}
} // namespace testing
} // namespace impeller
// NOLINTEND(bugprone-unchecked-optional-access)
| engine/impeller/geometry/geometry_unittests.cc/0 | {
"file_path": "engine/impeller/geometry/geometry_unittests.cc",
"repo_id": "engine",
"token_count": 25252
} | 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.
#include "gtest/gtest.h"
#include "flutter/impeller/geometry/size.h"
namespace impeller {
namespace testing {
TEST(SizeTest, SizeIsEmpty) {
auto nan = std::numeric_limits<Scalar>::quiet_NaN();
// Non-empty
EXPECT_FALSE(Size(10.5, 7.2).IsEmpty());
// Empty both width and height both 0 or negative, in all combinations
EXPECT_TRUE(Size(0.0, 0.0).IsEmpty());
EXPECT_TRUE(Size(-1.0, -1.0).IsEmpty());
EXPECT_TRUE(Size(-1.0, 0.0).IsEmpty());
EXPECT_TRUE(Size(0.0, -1.0).IsEmpty());
// Empty for 0 or negative width or height (but not both at the same time)
EXPECT_TRUE(Size(10.5, 0.0).IsEmpty());
EXPECT_TRUE(Size(10.5, -1.0).IsEmpty());
EXPECT_TRUE(Size(0.0, 7.2).IsEmpty());
EXPECT_TRUE(Size(-1.0, 7.2).IsEmpty());
// Empty for NaN in width or height or both
EXPECT_TRUE(Size(10.5, nan).IsEmpty());
EXPECT_TRUE(Size(nan, 7.2).IsEmpty());
EXPECT_TRUE(Size(nan, nan).IsEmpty());
}
TEST(SizeTest, ISizeIsEmpty) {
// Non-empty
EXPECT_FALSE(ISize(10, 7).IsEmpty());
// Empty both width and height both 0 or negative, in all combinations
EXPECT_TRUE(ISize(0, 0).IsEmpty());
EXPECT_TRUE(ISize(-1, -1).IsEmpty());
EXPECT_TRUE(ISize(-1, 0).IsEmpty());
EXPECT_TRUE(ISize(0, -1).IsEmpty());
// Empty for 0 or negative width or height (but not both at the same time)
EXPECT_TRUE(ISize(10, 0).IsEmpty());
EXPECT_TRUE(ISize(10, -1).IsEmpty());
EXPECT_TRUE(ISize(0, 7).IsEmpty());
EXPECT_TRUE(ISize(-1, 7).IsEmpty());
}
TEST(SizeTest, IsSquare) {
EXPECT_TRUE(Size(20, 20).IsSquare());
EXPECT_FALSE(Size(20, 19).IsSquare());
EXPECT_FALSE(Size(19, 20).IsSquare());
EXPECT_TRUE(ISize(20, 20).IsSquare());
EXPECT_FALSE(ISize(20, 19).IsSquare());
EXPECT_FALSE(ISize(19, 20).IsSquare());
}
TEST(SizeTest, MaxDimension) {
EXPECT_EQ(Size(20, 20).MaxDimension(), 20);
EXPECT_EQ(Size(20, 19).MaxDimension(), 20);
EXPECT_EQ(Size(19, 20).MaxDimension(), 20);
EXPECT_EQ(Size(20, 21).MaxDimension(), 21);
EXPECT_EQ(Size(21, 20).MaxDimension(), 21);
EXPECT_EQ(ISize(20, 20).MaxDimension(), 20);
EXPECT_EQ(ISize(20, 19).MaxDimension(), 20);
EXPECT_EQ(ISize(19, 20).MaxDimension(), 20);
EXPECT_EQ(ISize(20, 21).MaxDimension(), 21);
EXPECT_EQ(ISize(21, 20).MaxDimension(), 21);
}
TEST(SizeTest, NegationOperator) {
EXPECT_EQ(-Size(10, 20), Size(-10, -20));
EXPECT_EQ(-Size(-10, 20), Size(10, -20));
EXPECT_EQ(-Size(10, -20), Size(-10, 20));
EXPECT_EQ(-Size(-10, -20), Size(10, 20));
}
} // namespace testing
} // namespace impeller
| engine/impeller/geometry/size_unittests.cc/0 | {
"file_path": "engine/impeller/geometry/size_unittests.cc",
"repo_id": "engine",
"token_count": 1100
} | 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.
#include <wordexp.h>
#include "flutter/fml/backtrace.h"
#include "flutter/fml/build_config.h"
#include "flutter/fml/command_line.h"
#include "flutter/fml/logging.h"
#include "flutter/impeller/base/validation.h"
#include "flutter/impeller/golden_tests/golden_digest.h"
#include "flutter/impeller/golden_tests/working_directory.h"
#include "gtest/gtest.h"
namespace {
void print_usage() {
std::cout << "usage: impeller_golden_tests --working_dir=<working_dir>"
<< std::endl
<< std::endl;
std::cout << "flags:" << std::endl;
std::cout << " working_dir: Where the golden images will be generated and "
"uploaded to Skia Gold from."
<< std::endl;
}
} // namespace
namespace impeller {
TEST(ValidationTest, IsFatal) {
EXPECT_TRUE(ImpellerValidationErrorsAreFatal());
}
} // namespace impeller
int main(int argc, char** argv) {
impeller::ImpellerValidationErrorsSetFatal(true);
fml::InstallCrashHandler();
testing::InitGoogleTest(&argc, argv);
fml::CommandLine cmd = fml::CommandLineFromPlatformOrArgcArgv(argc, argv);
std::optional<std::string> working_dir;
for (const auto& option : cmd.options()) {
if (option.name == "working_dir") {
wordexp_t wordexp_result;
int code = wordexp(option.value.c_str(), &wordexp_result, 0);
FML_CHECK(code == 0);
FML_CHECK(wordexp_result.we_wordc != 0);
working_dir = wordexp_result.we_wordv[0];
wordfree(&wordexp_result);
}
}
if (!working_dir) {
std::cout << "required argument \"working_dir\" is missing." << std::endl
<< std::endl;
print_usage();
return 1;
}
impeller::testing::WorkingDirectory::Instance()->SetPath(working_dir.value());
std::cout << "working directory: "
<< impeller::testing::WorkingDirectory::Instance()->GetPath()
<< std::endl;
int return_code = RUN_ALL_TESTS();
if (0 == return_code) {
impeller::testing::GoldenDigest::Instance()->Write(
impeller::testing::WorkingDirectory::Instance());
}
return return_code;
}
| engine/impeller/golden_tests/main.cc/0 | {
"file_path": "engine/impeller/golden_tests/main.cc",
"repo_id": "engine",
"token_count": 871
} | 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.
#include "impeller/playground/backend/metal/playground_impl_mtl.h"
#define GLFW_INCLUDE_NONE
#import "third_party/glfw/include/GLFW/glfw3.h"
#define GLFW_EXPOSE_NATIVE_COCOA
#import "third_party/glfw/include/GLFW/glfw3native.h"
#include <Metal/Metal.h>
#include <QuartzCore/QuartzCore.h>
#include "flutter/fml/mapping.h"
#include "impeller/entity/mtl/entity_shaders.h"
#include "impeller/entity/mtl/framebuffer_blend_shaders.h"
#include "impeller/entity/mtl/modern_shaders.h"
#include "impeller/fixtures/mtl/fixtures_shaders.h"
#include "impeller/playground/imgui/mtl/imgui_shaders.h"
#include "impeller/renderer/backend/metal/context_mtl.h"
#include "impeller/renderer/backend/metal/formats_mtl.h"
#include "impeller/renderer/backend/metal/surface_mtl.h"
#include "impeller/renderer/backend/metal/texture_mtl.h"
#include "impeller/renderer/mtl/compute_shaders.h"
#include "impeller/scene/shaders/mtl/scene_shaders.h"
namespace impeller {
struct PlaygroundImplMTL::Data {
CAMetalLayer* metal_layer = nil;
};
static std::vector<std::shared_ptr<fml::Mapping>>
ShaderLibraryMappingsForPlayground() {
return {std::make_shared<fml::NonOwnedMapping>(
impeller_entity_shaders_data, impeller_entity_shaders_length),
std::make_shared<fml::NonOwnedMapping>(
impeller_modern_shaders_data, impeller_modern_shaders_length),
std::make_shared<fml::NonOwnedMapping>(
impeller_framebuffer_blend_shaders_data,
impeller_framebuffer_blend_shaders_length),
std::make_shared<fml::NonOwnedMapping>(
impeller_fixtures_shaders_data, impeller_fixtures_shaders_length),
std::make_shared<fml::NonOwnedMapping>(impeller_imgui_shaders_data,
impeller_imgui_shaders_length),
std::make_shared<fml::NonOwnedMapping>(impeller_scene_shaders_data,
impeller_scene_shaders_length),
std::make_shared<fml::NonOwnedMapping>(
impeller_compute_shaders_data, impeller_compute_shaders_length)
};
}
void PlaygroundImplMTL::DestroyWindowHandle(WindowHandle handle) {
if (!handle) {
return;
}
::glfwDestroyWindow(reinterpret_cast<GLFWwindow*>(handle));
}
PlaygroundImplMTL::PlaygroundImplMTL(PlaygroundSwitches switches)
: PlaygroundImpl(switches),
handle_(nullptr, &DestroyWindowHandle),
data_(std::make_unique<Data>()),
concurrent_loop_(fml::ConcurrentMessageLoop::Create()),
is_gpu_disabled_sync_switch_(new fml::SyncSwitch(false)) {
::glfwDefaultWindowHints();
::glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
::glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);
auto window = ::glfwCreateWindow(1, 1, "Test", nullptr, nullptr);
if (!window) {
return;
}
auto context =
ContextMTL::Create(ShaderLibraryMappingsForPlayground(),
is_gpu_disabled_sync_switch_, "Playground Library");
if (!context) {
return;
}
NSWindow* cocoa_window = ::glfwGetCocoaWindow(window);
if (cocoa_window == nil) {
return;
}
data_->metal_layer = [CAMetalLayer layer];
data_->metal_layer.device = ContextMTL::Cast(*context).GetMTLDevice();
data_->metal_layer.pixelFormat =
ToMTLPixelFormat(context->GetCapabilities()->GetDefaultColorFormat());
data_->metal_layer.framebufferOnly = NO;
cocoa_window.contentView.layer = data_->metal_layer;
cocoa_window.contentView.wantsLayer = YES;
handle_.reset(window);
context_ = std::move(context);
}
PlaygroundImplMTL::~PlaygroundImplMTL() = default;
std::shared_ptr<Context> PlaygroundImplMTL::GetContext() const {
return context_;
}
// |PlaygroundImpl|
PlaygroundImpl::WindowHandle PlaygroundImplMTL::GetWindowHandle() const {
return handle_.get();
}
// |PlaygroundImpl|
std::unique_ptr<Surface> PlaygroundImplMTL::AcquireSurfaceFrame(
std::shared_ptr<Context> context) {
if (!data_->metal_layer) {
return nullptr;
}
const auto layer_size = data_->metal_layer.bounds.size;
const auto scale = GetContentScale();
data_->metal_layer.drawableSize =
CGSizeMake(layer_size.width * scale.x, layer_size.height * scale.y);
auto drawable =
SurfaceMTL::GetMetalDrawableAndValidate(context, data_->metal_layer);
return SurfaceMTL::MakeFromMetalLayerDrawable(context, drawable);
}
fml::Status PlaygroundImplMTL::SetCapabilities(
const std::shared_ptr<Capabilities>& capabilities) {
context_->SetCapabilities(capabilities);
return fml::Status();
}
} // namespace impeller
| engine/impeller/playground/backend/metal/playground_impl_mtl.mm/0 | {
"file_path": "engine/impeller/playground/backend/metal/playground_impl_mtl.mm",
"repo_id": "engine",
"token_count": 1885
} | 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.
#include "imgui_impl_impeller.h"
#include <algorithm>
#include <climits>
#include <memory>
#include <vector>
#include "impeller/core/host_buffer.h"
#include "impeller/core/platform.h"
#include "impeller/geometry/scalar.h"
#include "impeller/geometry/vector.h"
#include "impeller/playground/imgui/imgui_raster.frag.h"
#include "impeller/playground/imgui/imgui_raster.vert.h"
#include "third_party/imgui/imgui.h"
#include "impeller/core/allocator.h"
#include "impeller/core/formats.h"
#include "impeller/core/range.h"
#include "impeller/core/sampler.h"
#include "impeller/core/texture.h"
#include "impeller/core/texture_descriptor.h"
#include "impeller/core/vertex_buffer.h"
#include "impeller/geometry/matrix.h"
#include "impeller/geometry/point.h"
#include "impeller/geometry/rect.h"
#include "impeller/geometry/size.h"
#include "impeller/renderer/command.h"
#include "impeller/renderer/context.h"
#include "impeller/renderer/pipeline_builder.h"
#include "impeller/renderer/pipeline_descriptor.h"
#include "impeller/renderer/pipeline_library.h"
#include "impeller/renderer/render_pass.h"
struct ImGui_ImplImpeller_Data {
explicit ImGui_ImplImpeller_Data(
const std::unique_ptr<const impeller::Sampler>& p_sampler)
: sampler(p_sampler) {}
std::shared_ptr<impeller::Context> context;
std::shared_ptr<impeller::Texture> font_texture;
std::shared_ptr<impeller::Pipeline<impeller::PipelineDescriptor>> pipeline;
const std::unique_ptr<const impeller::Sampler>& sampler;
};
static ImGui_ImplImpeller_Data* ImGui_ImplImpeller_GetBackendData() {
return ImGui::GetCurrentContext()
? static_cast<ImGui_ImplImpeller_Data*>(
ImGui::GetIO().BackendRendererUserData)
: nullptr;
}
bool ImGui_ImplImpeller_Init(
const std::shared_ptr<impeller::Context>& context) {
ImGuiIO& io = ImGui::GetIO();
IM_ASSERT(io.BackendRendererUserData == nullptr &&
"Already initialized a renderer backend!");
// Setup backend capabilities flags
auto* bd =
new ImGui_ImplImpeller_Data(context->GetSamplerLibrary()->GetSampler({}));
io.BackendRendererUserData = reinterpret_cast<void*>(bd);
io.BackendRendererName = "imgui_impl_impeller";
io.BackendFlags |=
ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the
// ImDrawCmd::VtxOffset field,
// allowing for large meshes.
bd->context = context;
// Generate/upload the font atlas.
{
unsigned char* pixels;
int width, height;
io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
auto texture_descriptor = impeller::TextureDescriptor{};
texture_descriptor.storage_mode = impeller::StorageMode::kHostVisible;
texture_descriptor.format = impeller::PixelFormat::kR8G8B8A8UNormInt;
texture_descriptor.size = {width, height};
texture_descriptor.mip_count = 1u;
bd->font_texture =
context->GetResourceAllocator()->CreateTexture(texture_descriptor);
IM_ASSERT(bd->font_texture != nullptr &&
"Could not allocate ImGui font texture.");
bd->font_texture->SetLabel("ImGui Font Texture");
[[maybe_unused]] bool uploaded = bd->font_texture->SetContents(
pixels, texture_descriptor.GetByteSizeOfBaseMipLevel());
IM_ASSERT(uploaded &&
"Could not upload ImGui font texture to device memory.");
}
// Build the raster pipeline.
{
auto desc = impeller::PipelineBuilder<impeller::ImguiRasterVertexShader,
impeller::ImguiRasterFragmentShader>::
MakeDefaultPipelineDescriptor(*context);
IM_ASSERT(desc.has_value() && "Could not create Impeller pipeline");
if (desc.has_value()) { // Needed to silence clang-tidy check
// bugprone-unchecked-optional-access.
desc->ClearStencilAttachments();
desc->ClearDepthAttachment();
}
bd->pipeline =
context->GetPipelineLibrary()->GetPipeline(std::move(desc)).Get();
IM_ASSERT(bd->pipeline != nullptr && "Could not create ImGui pipeline.");
IM_ASSERT(bd->pipeline != nullptr && "Could not create ImGui sampler.");
}
return true;
}
void ImGui_ImplImpeller_Shutdown() {
auto* bd = ImGui_ImplImpeller_GetBackendData();
IM_ASSERT(bd != nullptr &&
"No renderer backend to shutdown, or already shutdown?");
delete bd;
}
void ImGui_ImplImpeller_RenderDrawData(ImDrawData* draw_data,
impeller::RenderPass& render_pass) {
if (draw_data->CmdListsCount == 0) {
return; // Nothing to render.
}
auto host_buffer = impeller::HostBuffer::Create(
render_pass.GetContext()->GetResourceAllocator());
using VS = impeller::ImguiRasterVertexShader;
using FS = impeller::ImguiRasterFragmentShader;
auto* bd = ImGui_ImplImpeller_GetBackendData();
IM_ASSERT(bd != nullptr && "Did you call ImGui_ImplImpeller_Init()?");
size_t total_vtx_bytes = draw_data->TotalVtxCount * sizeof(VS::PerVertexData);
size_t total_idx_bytes = draw_data->TotalIdxCount * sizeof(ImDrawIdx);
if (!total_vtx_bytes || !total_idx_bytes) {
return; // Nothing to render.
}
// Allocate buffer for vertices + indices.
impeller::DeviceBufferDescriptor buffer_desc;
buffer_desc.size = total_vtx_bytes + total_idx_bytes;
buffer_desc.storage_mode = impeller::StorageMode::kHostVisible;
auto buffer = bd->context->GetResourceAllocator()->CreateBuffer(buffer_desc);
buffer->SetLabel(impeller::SPrintF("ImGui vertex+index buffer"));
auto display_rect = impeller::Rect::MakeXYWH(
draw_data->DisplayPos.x, draw_data->DisplayPos.y,
draw_data->DisplaySize.x, draw_data->DisplaySize.y);
auto viewport = impeller::Viewport{
.rect = display_rect.Scale(draw_data->FramebufferScale.x,
draw_data->FramebufferScale.y)};
// Allocate vertex shader uniform buffer.
VS::UniformBuffer uniforms;
uniforms.mvp = impeller::Matrix::MakeOrthographic(display_rect.GetSize())
.Translate(-display_rect.GetOrigin());
auto vtx_uniforms = host_buffer->EmplaceUniform(uniforms);
size_t vertex_buffer_offset = 0;
size_t index_buffer_offset = total_vtx_bytes;
for (int draw_list_i = 0; draw_list_i < draw_data->CmdListsCount;
draw_list_i++) {
const ImDrawList* cmd_list = draw_data->CmdLists[draw_list_i];
// Convert ImGui's per-vertex data (`ImDrawVert`) into the per-vertex data
// required by the shader (`VS::PerVectexData`). The only difference is that
// `ImDrawVert` uses an `int` for the color and the impeller shader uses 4
// floats.
// TODO(102778): Remove the need for this by adding support for attribute
// mapping of uint32s host-side to vec4s shader-side in
// impellerc.
std::vector<VS::PerVertexData> vtx_data;
vtx_data.reserve(cmd_list->VtxBuffer.size());
for (const auto& v : cmd_list->VtxBuffer) {
ImVec4 color = ImGui::ColorConvertU32ToFloat4(v.col);
vtx_data.push_back({{v.pos.x, v.pos.y}, //
{v.uv.x, v.uv.y}, //
{color.x, color.y, color.z, color.w}});
}
auto draw_list_vtx_bytes =
static_cast<size_t>(vtx_data.size() * sizeof(VS::PerVertexData));
auto draw_list_idx_bytes =
static_cast<size_t>(cmd_list->IdxBuffer.size_in_bytes());
if (!buffer->CopyHostBuffer(reinterpret_cast<uint8_t*>(vtx_data.data()),
impeller::Range{0, draw_list_vtx_bytes},
vertex_buffer_offset)) {
IM_ASSERT(false && "Could not copy vertices to buffer.");
}
if (!buffer->CopyHostBuffer(
reinterpret_cast<uint8_t*>(cmd_list->IdxBuffer.Data),
impeller::Range{0, draw_list_idx_bytes}, index_buffer_offset)) {
IM_ASSERT(false && "Could not copy indices to buffer.");
}
for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) {
const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
if (pcmd->UserCallback) {
pcmd->UserCallback(cmd_list, pcmd);
} else {
// Make the clip rect relative to the viewport.
auto clip_rect = impeller::Rect::MakeLTRB(
(pcmd->ClipRect.x - draw_data->DisplayPos.x) *
draw_data->FramebufferScale.x,
(pcmd->ClipRect.y - draw_data->DisplayPos.y) *
draw_data->FramebufferScale.y,
(pcmd->ClipRect.z - draw_data->DisplayPos.x) *
draw_data->FramebufferScale.x,
(pcmd->ClipRect.w - draw_data->DisplayPos.y) *
draw_data->FramebufferScale.y);
{
// Clamp the clip to the viewport bounds.
auto visible_clip = clip_rect.Intersection(viewport.rect);
if (!visible_clip.has_value()) {
continue; // Nothing to render.
}
clip_rect = visible_clip.value();
}
{
// Clamp the clip to ensure it never goes outside of the render
// target.
auto visible_clip = clip_rect.Intersection(
impeller::Rect::MakeSize(render_pass.GetRenderTargetSize()));
if (!visible_clip.has_value()) {
continue; // Nothing to render.
}
clip_rect = visible_clip.value();
}
render_pass.SetCommandLabel(impeller::SPrintF(
"ImGui draw list %d (command %d)", draw_list_i, cmd_i));
render_pass.SetViewport(viewport);
render_pass.SetScissor(impeller::IRect::RoundOut(clip_rect));
render_pass.SetPipeline(bd->pipeline);
VS::BindUniformBuffer(render_pass, vtx_uniforms);
FS::BindTex(render_pass, bd->font_texture, bd->sampler);
size_t vb_start =
vertex_buffer_offset + pcmd->VtxOffset * sizeof(ImDrawVert);
impeller::VertexBuffer vertex_buffer;
vertex_buffer.vertex_buffer = {
.buffer = buffer,
.range = impeller::Range(vb_start, draw_list_vtx_bytes - vb_start)};
vertex_buffer.index_buffer = {
.buffer = buffer,
.range = impeller::Range(
index_buffer_offset + pcmd->IdxOffset * sizeof(ImDrawIdx),
pcmd->ElemCount * sizeof(ImDrawIdx))};
vertex_buffer.vertex_count = pcmd->ElemCount;
vertex_buffer.index_type = impeller::IndexType::k16bit;
render_pass.SetVertexBuffer(std::move(vertex_buffer));
render_pass.SetBaseVertex(pcmd->VtxOffset);
render_pass.Draw().ok();
}
}
vertex_buffer_offset += draw_list_vtx_bytes;
index_buffer_offset += draw_list_idx_bytes;
}
host_buffer->Reset();
}
| engine/impeller/playground/imgui/imgui_impl_impeller.cc/0 | {
"file_path": "engine/impeller/playground/imgui/imgui_impl_impeller.cc",
"repo_id": "engine",
"token_count": 4714
} | 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.
import("//flutter/vulkan/config.gni")
import("../../../tools/impeller.gni")
config("gles_config") {
# Generic GL/GLES/EGL/Vulkan headers. Any will do. We just pick one from Angle
# because they are there.
include_dirs = [ "//flutter/third_party/angle/include" ]
}
impeller_component("gles_unittests") {
testonly = true
sources = [
"test/capabilities_unittests.cc",
"test/formats_gles_unittests.cc",
"test/gpu_tracer_gles_unittests.cc",
"test/mock_gles.cc",
"test/mock_gles.h",
"test/mock_gles_unittests.cc",
"test/proc_table_gles_unittests.cc",
"test/specialization_constants_unittests.cc",
]
deps = [
":gles",
"//flutter/testing:testing_lib",
]
}
impeller_component("gles") {
public_configs = []
sources = [
"allocator_gles.cc",
"allocator_gles.h",
"blit_command_gles.cc",
"blit_command_gles.h",
"blit_pass_gles.cc",
"blit_pass_gles.h",
"buffer_bindings_gles.cc",
"buffer_bindings_gles.h",
"capabilities_gles.cc",
"capabilities_gles.h",
"command_buffer_gles.cc",
"command_buffer_gles.h",
"context_gles.cc",
"context_gles.h",
"description_gles.cc",
"description_gles.h",
"device_buffer_gles.cc",
"device_buffer_gles.h",
"formats_gles.cc",
"formats_gles.h",
"gles.h",
"gpu_tracer_gles.cc",
"gpu_tracer_gles.h",
"handle_gles.cc",
"handle_gles.h",
"pipeline_gles.cc",
"pipeline_gles.h",
"pipeline_library_gles.cc",
"pipeline_library_gles.h",
"proc_table_gles.cc",
"proc_table_gles.h",
"reactor_gles.cc",
"reactor_gles.h",
"render_pass_gles.cc",
"render_pass_gles.h",
"sampler_gles.cc",
"sampler_gles.h",
"sampler_library_gles.cc",
"sampler_library_gles.h",
"shader_function_gles.cc",
"shader_function_gles.h",
"shader_library_gles.cc",
"shader_library_gles.h",
"surface_gles.cc",
"surface_gles.h",
"texture_gles.cc",
"texture_gles.h",
]
if (!is_android && !is_fuchsia) {
public_configs = [ ":gles_config" ]
sources += [
"//flutter/third_party/angle/include/GLES2/gl2ext.h",
# The GLES3 API is a superset of GLES2. Although we target GLES2, we use
# some GLES3 features if the driver supports them.
"//flutter/third_party/angle/include/GLES3/gl3.h",
]
}
public_deps = [
"../../:renderer",
"../../../shader_archive",
"//flutter/fml",
]
}
| engine/impeller/renderer/backend/gles/BUILD.gn/0 | {
"file_path": "engine/impeller/renderer/backend/gles/BUILD.gn",
"repo_id": "engine",
"token_count": 1221
} | 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_BACKEND_GLES_DESCRIPTION_GLES_H_
#define FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_DESCRIPTION_GLES_H_
#include <set>
#include <string>
#include "flutter/fml/macros.h"
#include "impeller/base/version.h"
namespace impeller {
class ProcTableGLES;
class DescriptionGLES {
public:
explicit DescriptionGLES(const ProcTableGLES& gl);
~DescriptionGLES();
bool IsValid() const;
bool IsES() const;
std::string GetString() const;
Version GetGlVersion() const;
bool HasExtension(const std::string& ext) const;
/// @brief Returns whether GLES includes the debug extension.
bool HasDebugExtension() const;
bool IsANGLE() const;
private:
Version gl_version_;
Version sl_version_;
bool is_es_ = true;
std::string vendor_;
std::string renderer_;
std::string gl_version_string_;
std::string sl_version_string_;
std::set<std::string> extensions_;
bool is_angle_ = false;
bool is_valid_ = false;
DescriptionGLES(const DescriptionGLES&) = delete;
DescriptionGLES& operator=(const DescriptionGLES&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_DESCRIPTION_GLES_H_
| engine/impeller/renderer/backend/gles/description_gles.h/0 | {
"file_path": "engine/impeller/renderer/backend/gles/description_gles.h",
"repo_id": "engine",
"token_count": 464
} | 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.
#include "impeller/renderer/backend/gles/reactor_gles.h"
#include <algorithm>
#include "flutter/fml/trace_event.h"
#include "fml/logging.h"
#include "impeller/base/validation.h"
namespace impeller {
ReactorGLES::ReactorGLES(std::unique_ptr<ProcTableGLES> gl)
: proc_table_(std::move(gl)) {
if (!proc_table_ || !proc_table_->IsValid()) {
VALIDATION_LOG << "Proc table was invalid.";
return;
}
can_set_debug_labels_ = proc_table_->GetDescription()->HasDebugExtension();
is_valid_ = true;
}
ReactorGLES::~ReactorGLES() = default;
bool ReactorGLES::IsValid() const {
return is_valid_;
}
ReactorGLES::WorkerID ReactorGLES::AddWorker(std::weak_ptr<Worker> worker) {
Lock lock(workers_mutex_);
auto id = WorkerID{};
workers_[id] = std::move(worker);
return id;
}
bool ReactorGLES::RemoveWorker(WorkerID worker) {
Lock lock(workers_mutex_);
return workers_.erase(worker) == 1;
}
bool ReactorGLES::HasPendingOperations() const {
Lock ops_lock(ops_mutex_);
return !ops_.empty();
}
const ProcTableGLES& ReactorGLES::GetProcTable() const {
FML_DCHECK(IsValid());
return *proc_table_;
}
std::optional<GLuint> ReactorGLES::GetGLHandle(const HandleGLES& handle) const {
ReaderLock handles_lock(handles_mutex_);
if (auto found = handles_.find(handle); found != handles_.end()) {
if (found->second.pending_collection) {
VALIDATION_LOG
<< "Attempted to acquire a handle that was pending collection.";
return std::nullopt;
}
if (!found->second.name.has_value()) {
VALIDATION_LOG << "Attempt to acquire a handle outside of an operation.";
return std::nullopt;
}
return found->second.name;
}
VALIDATION_LOG << "Attempted to acquire an invalid GL handle.";
return std::nullopt;
}
bool ReactorGLES::AddOperation(Operation operation) {
if (!operation) {
return false;
}
{
Lock ops_lock(ops_mutex_);
ops_.emplace_back(std::move(operation));
}
// Attempt a reaction if able but it is not an error if this isn't possible.
[[maybe_unused]] auto result = React();
return true;
}
static std::optional<GLuint> CreateGLHandle(const ProcTableGLES& gl,
HandleType type) {
GLuint handle = GL_NONE;
switch (type) {
case HandleType::kUnknown:
return std::nullopt;
case HandleType::kTexture:
gl.GenTextures(1u, &handle);
return handle;
case HandleType::kBuffer:
gl.GenBuffers(1u, &handle);
return handle;
case HandleType::kProgram:
return gl.CreateProgram();
case HandleType::kRenderBuffer:
gl.GenRenderbuffers(1u, &handle);
return handle;
case HandleType::kFrameBuffer:
gl.GenFramebuffers(1u, &handle);
return handle;
}
return std::nullopt;
}
static bool CollectGLHandle(const ProcTableGLES& gl,
HandleType type,
GLuint handle) {
switch (type) {
case HandleType::kUnknown:
return false;
case HandleType::kTexture:
gl.DeleteTextures(1u, &handle);
return true;
case HandleType::kBuffer:
gl.DeleteBuffers(1u, &handle);
return true;
case HandleType::kProgram:
gl.DeleteProgram(handle);
return true;
case HandleType::kRenderBuffer:
gl.DeleteRenderbuffers(1u, &handle);
return true;
case HandleType::kFrameBuffer:
gl.DeleteFramebuffers(1u, &handle);
return true;
}
return false;
}
HandleGLES ReactorGLES::CreateHandle(HandleType type) {
if (type == HandleType::kUnknown) {
return HandleGLES::DeadHandle();
}
auto new_handle = HandleGLES::Create(type);
if (new_handle.IsDead()) {
return HandleGLES::DeadHandle();
}
WriterLock handles_lock(handles_mutex_);
auto gl_handle = CanReactOnCurrentThread()
? CreateGLHandle(GetProcTable(), type)
: std::nullopt;
handles_[new_handle] = LiveHandle{gl_handle};
return new_handle;
}
void ReactorGLES::CollectHandle(HandleGLES handle) {
WriterLock handles_lock(handles_mutex_);
if (auto found = handles_.find(handle); found != handles_.end()) {
found->second.pending_collection = true;
}
}
bool ReactorGLES::React() {
if (!CanReactOnCurrentThread()) {
return false;
}
TRACE_EVENT0("impeller", "ReactorGLES::React");
while (HasPendingOperations()) {
// Both the raster thread and the IO thread can flush queued operations.
// Ensure that execution of the ops is serialized.
Lock execution_lock(ops_execution_mutex_);
if (!ReactOnce()) {
return false;
}
}
return true;
}
static DebugResourceType ToDebugResourceType(HandleType type) {
switch (type) {
case HandleType::kUnknown:
FML_UNREACHABLE();
case HandleType::kTexture:
return DebugResourceType::kTexture;
case HandleType::kBuffer:
return DebugResourceType::kBuffer;
case HandleType::kProgram:
return DebugResourceType::kProgram;
case HandleType::kRenderBuffer:
return DebugResourceType::kRenderBuffer;
case HandleType::kFrameBuffer:
return DebugResourceType::kFrameBuffer;
}
FML_UNREACHABLE();
}
bool ReactorGLES::ReactOnce() {
if (!IsValid()) {
return false;
}
TRACE_EVENT0("impeller", __FUNCTION__);
return ConsolidateHandles() && FlushOps();
}
bool ReactorGLES::ConsolidateHandles() {
TRACE_EVENT0("impeller", __FUNCTION__);
const auto& gl = GetProcTable();
WriterLock handles_lock(handles_mutex_);
std::vector<HandleGLES> handles_to_delete;
for (auto& handle : handles_) {
// Collect dead handles.
if (handle.second.pending_collection) {
// This could be false if the handle was created and collected without
// use. We still need to get rid of map entry.
if (handle.second.name.has_value()) {
CollectGLHandle(gl, handle.first.type, handle.second.name.value());
}
handles_to_delete.push_back(handle.first);
continue;
}
// Create live handles.
if (!handle.second.name.has_value()) {
auto gl_handle = CreateGLHandle(gl, handle.first.type);
if (!gl_handle) {
VALIDATION_LOG << "Could not create GL handle.";
return false;
}
handle.second.name = gl_handle;
}
// Set pending debug labels.
if (handle.second.pending_debug_label.has_value()) {
if (gl.SetDebugLabel(ToDebugResourceType(handle.first.type),
handle.second.name.value(),
handle.second.pending_debug_label.value())) {
handle.second.pending_debug_label = std::nullopt;
}
}
}
for (const auto& handle_to_delete : handles_to_delete) {
handles_.erase(handle_to_delete);
}
return true;
}
bool ReactorGLES::FlushOps() {
TRACE_EVENT0("impeller", __FUNCTION__);
#ifdef IMPELLER_DEBUG
// glDebugMessageControl sometimes must be called before glPushDebugGroup:
// https://github.com/flutter/flutter/issues/135715#issuecomment-1740153506
SetupDebugGroups();
#endif
// Do NOT hold the ops or handles locks while performing operations in case
// the ops enqueue more ops.
decltype(ops_) ops;
{
Lock ops_lock(ops_mutex_);
std::swap(ops_, ops);
}
for (const auto& op : ops) {
TRACE_EVENT0("impeller", "ReactorGLES::Operation");
op(*this);
}
return true;
}
void ReactorGLES::SetupDebugGroups() {
// Setup of a default active debug group: Filter everything in.
if (proc_table_->DebugMessageControlKHR.IsAvailable()) {
proc_table_->DebugMessageControlKHR(GL_DONT_CARE, // source
GL_DONT_CARE, // type
GL_DONT_CARE, // severity
0, // count
nullptr, // ids
GL_TRUE); // enabled
}
}
void ReactorGLES::SetDebugLabel(const HandleGLES& handle, std::string label) {
if (!can_set_debug_labels_) {
return;
}
if (handle.IsDead()) {
return;
}
WriterLock handles_lock(handles_mutex_);
if (auto found = handles_.find(handle); found != handles_.end()) {
found->second.pending_debug_label = std::move(label);
}
}
bool ReactorGLES::CanReactOnCurrentThread() const {
std::vector<WorkerID> dead_workers;
Lock lock(workers_mutex_);
for (const auto& worker : workers_) {
auto worker_ptr = worker.second.lock();
if (!worker_ptr) {
dead_workers.push_back(worker.first);
continue;
}
if (worker_ptr->CanReactorReactOnCurrentThreadNow(*this)) {
return true;
}
}
for (const auto& worker_id : dead_workers) {
workers_.erase(worker_id);
}
return false;
}
} // namespace impeller
| engine/impeller/renderer/backend/gles/reactor_gles.cc/0 | {
"file_path": "engine/impeller/renderer/backend/gles/reactor_gles.cc",
"repo_id": "engine",
"token_count": 3593
} | 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/testing/testing.h" // IWYU pragma: keep
#include "gtest/gtest.h"
#include "impeller/renderer/backend/gles/formats_gles.h"
namespace impeller {
namespace testing {
TEST(FormatsGLES, CanFormatFramebufferErrorMessage) {
ASSERT_EQ(DebugToFramebufferError(GL_FRAMEBUFFER_UNDEFINED),
"GL_FRAMEBUFFER_UNDEFINED");
ASSERT_EQ(DebugToFramebufferError(GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT),
"GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT");
ASSERT_EQ(
DebugToFramebufferError(GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT),
"GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT");
ASSERT_EQ(DebugToFramebufferError(GL_FRAMEBUFFER_UNSUPPORTED),
"GL_FRAMEBUFFER_UNSUPPORTED");
ASSERT_EQ(DebugToFramebufferError(GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE),
"GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE");
ASSERT_EQ(DebugToFramebufferError(0), "Unknown error code: 0");
}
} // namespace testing
} // namespace impeller
| engine/impeller/renderer/backend/gles/test/formats_gles_unittests.cc/0 | {
"file_path": "engine/impeller/renderer/backend/gles/test/formats_gles_unittests.cc",
"repo_id": "engine",
"token_count": 456
} | 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_RENDERER_BACKEND_METAL_COMMAND_BUFFER_MTL_H_
#define FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_COMMAND_BUFFER_MTL_H_
#include <Metal/Metal.h>
#include "flutter/fml/macros.h"
#include "impeller/core/allocator.h"
#include "impeller/renderer/command_buffer.h"
namespace impeller {
class CommandBufferMTL final : public CommandBuffer {
public:
// |CommandBuffer|
~CommandBufferMTL() override;
private:
friend class ContextMTL;
id<MTLCommandBuffer> buffer_ = nullptr;
CommandBufferMTL(const std::weak_ptr<const Context>& context,
id<MTLCommandQueue> queue);
// |CommandBuffer|
void SetLabel(const std::string& label) const override;
// |CommandBuffer|
bool IsValid() const override;
// |CommandBuffer|
bool OnSubmitCommands(CompletionCallback callback) override;
// |CommandBuffer|
void OnWaitUntilScheduled() override;
// |CommandBuffer|
std::shared_ptr<RenderPass> OnCreateRenderPass(RenderTarget target) override;
// |CommandBuffer|
std::shared_ptr<BlitPass> OnCreateBlitPass() override;
// |CommandBuffer|
std::shared_ptr<ComputePass> OnCreateComputePass() override;
CommandBufferMTL(const CommandBufferMTL&) = delete;
CommandBufferMTL& operator=(const CommandBufferMTL&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_COMMAND_BUFFER_MTL_H_
| engine/impeller/renderer/backend/metal/command_buffer_mtl.h/0 | {
"file_path": "engine/impeller/renderer/backend/metal/command_buffer_mtl.h",
"repo_id": "engine",
"token_count": 535
} | 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.
#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_LAZY_DRAWABLE_HOLDER_H_
#define FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_LAZY_DRAWABLE_HOLDER_H_
#include <Metal/Metal.h>
#include <future>
#include "impeller/core/texture_descriptor.h"
#include "impeller/renderer/backend/metal/texture_mtl.h"
@protocol CAMetalDrawable;
@class CAMetalLayer;
namespace impeller {
/// @brief Create a deferred drawable from a CAMetalLayer.
std::shared_future<id<CAMetalDrawable>> GetDrawableDeferred(
CAMetalLayer* layer);
/// @brief Create a TextureMTL from a deferred drawable.
///
/// This function is safe to call multiple times and will only call
/// nextDrawable once.
std::shared_ptr<TextureMTL> CreateTextureFromDrawableFuture(
TextureDescriptor desc,
const std::shared_future<id<CAMetalDrawable>>& drawble_future);
} // namespace impeller
#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_LAZY_DRAWABLE_HOLDER_H_
| engine/impeller/renderer/backend/metal/lazy_drawable_holder.h/0 | {
"file_path": "engine/impeller/renderer/backend/metal/lazy_drawable_holder.h",
"repo_id": "engine",
"token_count": 410
} | 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.
#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_SHADER_LIBRARY_MTL_H_
#define FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_SHADER_LIBRARY_MTL_H_
#include <Foundation/Foundation.h>
#include <Metal/Metal.h>
#include <memory>
#include <string>
#include <unordered_map>
#include "flutter/fml/macros.h"
#include "impeller/base/comparable.h"
#include "impeller/base/thread.h"
#include "impeller/renderer/shader_key.h"
#include "impeller/renderer/shader_library.h"
namespace impeller {
class ShaderLibraryMTL final : public ShaderLibrary {
public:
ShaderLibraryMTL();
// |ShaderLibrary|
~ShaderLibraryMTL() override;
// |ShaderLibrary|
bool IsValid() const override;
private:
friend class ContextMTL;
UniqueID library_id_;
mutable RWMutex libraries_mutex_;
NSMutableArray<id<MTLLibrary>>* libraries_ IPLR_GUARDED_BY(libraries_mutex_) =
nullptr;
ShaderFunctionMap functions_;
bool is_valid_ = false;
explicit ShaderLibraryMTL(NSArray<id<MTLLibrary>>* libraries);
// |ShaderLibrary|
std::shared_ptr<const ShaderFunction> GetFunction(std::string_view name,
ShaderStage stage) override;
// |ShaderLibrary|
void RegisterFunction(std::string name,
ShaderStage stage,
std::shared_ptr<fml::Mapping> code,
RegistrationCallback callback) override;
// |ShaderLibrary|
void UnregisterFunction(std::string name, ShaderStage stage) override;
id<MTLDevice> GetDevice() const;
void RegisterLibrary(id<MTLLibrary> library);
ShaderLibraryMTL(const ShaderLibraryMTL&) = delete;
ShaderLibraryMTL& operator=(const ShaderLibraryMTL&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_SHADER_LIBRARY_MTL_H_
| engine/impeller/renderer/backend/metal/shader_library_mtl.h/0 | {
"file_path": "engine/impeller/renderer/backend/metal/shader_library_mtl.h",
"repo_id": "engine",
"token_count": 775
} | 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.
#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_ANDROID_AHB_TEXTURE_SOURCE_VK_H_
#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_ANDROID_AHB_TEXTURE_SOURCE_VK_H_
#include "flutter/fml/macros.h"
#include "impeller/geometry/size.h"
#include "impeller/renderer/backend/vulkan/formats_vk.h"
#include "impeller/renderer/backend/vulkan/texture_source_vk.h"
#include "impeller/renderer/backend/vulkan/vk.h"
#include "impeller/renderer/backend/vulkan/yuv_conversion_vk.h"
#include <android/hardware_buffer.h>
#include <android/hardware_buffer_jni.h>
namespace impeller {
class ContextVK;
//------------------------------------------------------------------------------
/// @brief A texture source that wraps an instance of AHardwareBuffer.
///
/// The formats and conversions supported by Android Hardware
/// Buffers are a superset of those supported by Impeller (and
/// Vulkan for that matter). Impeller and Vulkan descriptors
/// obtained from the these texture sources are advisory and it
/// usually isn't possible to create copies of images and image
/// views held in these texture sources using the inferred
/// descriptors. The objects are meant to be used directly (either
/// as render targets or sources for sampling), not copied.
///
class AHBTextureSourceVK final : public TextureSourceVK {
public:
AHBTextureSourceVK(const std::shared_ptr<ContextVK>& context,
struct AHardwareBuffer* hardware_buffer,
const AHardwareBuffer_Desc& hardware_buffer_desc);
// |TextureSourceVK|
~AHBTextureSourceVK() override;
// |TextureSourceVK|
vk::Image GetImage() const override;
// |TextureSourceVK|
vk::ImageView GetImageView() const override;
// |TextureSourceVK|
vk::ImageView GetRenderTargetView() const override;
bool IsValid() const;
// |TextureSourceVK|
bool IsSwapchainImage() const override;
// |TextureSourceVK|
std::shared_ptr<YUVConversionVK> GetYUVConversion() const override;
private:
vk::UniqueDeviceMemory device_memory_ = {};
vk::UniqueImage image_ = {};
vk::UniqueImageView image_view_ = {};
std::shared_ptr<YUVConversionVK> yuv_conversion_ = {};
bool needs_yuv_conversion_ = false;
bool is_valid_ = false;
AHBTextureSourceVK(const AHBTextureSourceVK&) = delete;
AHBTextureSourceVK& operator=(const AHBTextureSourceVK&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_ANDROID_AHB_TEXTURE_SOURCE_VK_H_
| engine/impeller/renderer/backend/vulkan/android/ahb_texture_source_vk.h/0 | {
"file_path": "engine/impeller/renderer/backend/vulkan/android/ahb_texture_source_vk.h",
"repo_id": "engine",
"token_count": 960
} | 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.
#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_COMMAND_POOL_VK_H_
#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_COMMAND_POOL_VK_H_
#include <memory>
#include <optional>
#include <utility>
#include "impeller/base/thread.h"
#include "impeller/renderer/backend/vulkan/vk.h" // IWYU pragma: keep.
#include "vulkan/vulkan_handles.hpp"
namespace impeller {
class ContextVK;
class CommandPoolRecyclerVK;
//------------------------------------------------------------------------------
/// @brief Manages the lifecycle of a single |vk::CommandPool|.
///
/// A |vk::CommandPool| is expensive to create and reset. This class manages
/// the lifecycle of a single |vk::CommandPool| by returning to the origin
/// (|CommandPoolRecyclerVK|) when it is destroyed to be reused.
///
/// @warning This class is not thread-safe.
///
/// @see |CommandPoolRecyclerVK|
class CommandPoolVK final {
public:
~CommandPoolVK();
/// @brief Creates a resource that manages the life of a command pool.
///
/// @param[in] pool The command pool to manage.
/// @param[in] buffers Zero or more command buffers in an initial state.
/// @param[in] recycler The context that will be notified on destruction.
CommandPoolVK(vk::UniqueCommandPool pool,
std::vector<vk::UniqueCommandBuffer>&& buffers,
std::weak_ptr<ContextVK>& context)
: pool_(std::move(pool)),
unused_command_buffers_(std::move(buffers)),
context_(context) {}
/// @brief Creates and returns a new |vk::CommandBuffer|.
///
/// @return Always returns a new |vk::CommandBuffer|, but if for any
/// reason a valid command buffer could not be created, it will be
/// a `{}` default instance (i.e. while being torn down).
vk::UniqueCommandBuffer CreateCommandBuffer();
/// @brief Collects the given |vk::CommandBuffer| to be retained.
///
/// @param[in] buffer The |vk::CommandBuffer| to collect.
///
/// @see |GarbageCollectBuffersIfAble|
void CollectCommandBuffer(vk::UniqueCommandBuffer&& buffer);
/// @brief Delete all Vulkan objects in this command pool.
void Destroy();
private:
CommandPoolVK(const CommandPoolVK&) = delete;
CommandPoolVK& operator=(const CommandPoolVK&) = delete;
Mutex pool_mutex_;
vk::UniqueCommandPool pool_ IPLR_GUARDED_BY(pool_mutex_);
std::vector<vk::UniqueCommandBuffer> unused_command_buffers_;
std::weak_ptr<ContextVK>& context_;
// Used to retain a reference on these until the pool is reset.
std::vector<vk::UniqueCommandBuffer> collected_buffers_ IPLR_GUARDED_BY(
pool_mutex_);
};
//------------------------------------------------------------------------------
/// @brief Creates and manages the lifecycle of |vk::CommandPool| objects.
///
/// A |vk::CommandPool| is expensive to create and reset. This class manages
/// the lifecycle of |vk::CommandPool| objects by creating and recycling them;
/// or in other words, a pool for command pools.
///
/// A single instance should be created per |ContextVK|.
///
/// Every "frame", a single |CommandPoolResourceVk| is made available for each
/// thread that calls |Get|. After calling |Dispose|, the current thread's pool
/// is moved to a background thread, reset, and made available for the next time
/// |Get| is called and needs to create a command pool.
///
/// Commands in the command pool are not necessarily done executing when the
/// pool is recycled, when all references are dropped to the pool, they are
/// reset and returned to the pool of available pools.
///
/// @note This class is thread-safe.
///
/// @see |vk::CommandPoolResourceVk|
/// @see |ContextVK|
/// @see
/// https://arm-software.github.io/vulkan_best_practice_for_mobile_developers/samples/performance/command_buffer_usage/command_buffer_usage_tutorial.html
class CommandPoolRecyclerVK final
: public std::enable_shared_from_this<CommandPoolRecyclerVK> {
public:
~CommandPoolRecyclerVK();
/// A unique command pool and zero or more recycled command buffers.
struct RecycledData {
vk::UniqueCommandPool pool;
std::vector<vk::UniqueCommandBuffer> buffers;
};
/// @brief Clean up resources held by all per-thread command pools
/// associated with the given context.
///
/// @param[in] context The context.
static void DestroyThreadLocalPools(const ContextVK* context);
/// @brief Creates a recycler for the given |ContextVK|.
///
/// @param[in] context The context to create the recycler for.
explicit CommandPoolRecyclerVK(std::weak_ptr<ContextVK> context)
: context_(std::move(context)) {}
/// @brief Gets a command pool for the current thread.
///
/// @warning Returns a |nullptr| if a pool could not be created.
std::shared_ptr<CommandPoolVK> Get();
/// @brief Returns a command pool to be reset on a background thread.
///
/// @param[in] pool The pool to recycler.
void Reclaim(vk::UniqueCommandPool&& pool,
std::vector<vk::UniqueCommandBuffer>&& buffers);
/// @brief Clears all recycled command pools to let them be reclaimed.
void Dispose();
private:
std::weak_ptr<ContextVK> context_;
Mutex recycled_mutex_;
std::vector<RecycledData> recycled_ IPLR_GUARDED_BY(recycled_mutex_);
/// @brief Creates a new |vk::CommandPool|.
///
/// @returns Returns a |std::nullopt| if a pool could not be created.
std::optional<CommandPoolRecyclerVK::RecycledData> Create();
/// @brief Reuses a recycled |RecycledData|, if available.
///
/// @returns Returns a |std::nullopt| if a pool was not available.
std::optional<RecycledData> Reuse();
CommandPoolRecyclerVK(const CommandPoolRecyclerVK&) = delete;
CommandPoolRecyclerVK& operator=(const CommandPoolRecyclerVK&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_COMMAND_POOL_VK_H_
| engine/impeller/renderer/backend/vulkan/command_pool_vk.h/0 | {
"file_path": "engine/impeller/renderer/backend/vulkan/command_pool_vk.h",
"repo_id": "engine",
"token_count": 2040
} | 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/renderer/backend/vulkan/device_buffer_vk.h"
#include "flutter/flutter_vma/flutter_vma.h"
#include "flutter/fml/trace_event.h"
#include "impeller/renderer/backend/vulkan/context_vk.h"
#include "vulkan/vulkan_core.h"
namespace impeller {
DeviceBufferVK::DeviceBufferVK(DeviceBufferDescriptor desc,
std::weak_ptr<Context> context,
UniqueBufferVMA buffer,
VmaAllocationInfo info)
: DeviceBuffer(desc),
context_(std::move(context)),
resource_(ContextVK::Cast(*context_.lock().get()).GetResourceManager(),
BufferResource{
std::move(buffer), //
info //
}) {}
DeviceBufferVK::~DeviceBufferVK() = default;
uint8_t* DeviceBufferVK::OnGetContents() const {
return static_cast<uint8_t*>(resource_->info.pMappedData);
}
bool DeviceBufferVK::OnCopyHostBuffer(const uint8_t* source,
Range source_range,
size_t offset) {
uint8_t* dest = OnGetContents();
if (!dest) {
return false;
}
if (source) {
::memmove(dest + offset, source + source_range.offset, source_range.length);
}
::vmaFlushAllocation(resource_->buffer.get().allocator,
resource_->buffer.get().allocation, offset,
source_range.length);
return true;
}
bool DeviceBufferVK::SetLabel(const std::string& label) {
auto context = context_.lock();
if (!context || !resource_->buffer.is_valid()) {
// The context could have died at this point.
return false;
}
::vmaSetAllocationName(resource_->buffer.get().allocator, //
resource_->buffer.get().allocation, //
label.c_str() //
);
return ContextVK::Cast(*context).SetDebugName(resource_->buffer.get().buffer,
label);
}
void DeviceBufferVK::Flush(std::optional<Range> range) const {
auto flush_range = range.value_or(Range{0, GetDeviceBufferDescriptor().size});
::vmaFlushAllocation(resource_->buffer.get().allocator,
resource_->buffer.get().allocation, flush_range.offset,
flush_range.length);
}
void DeviceBufferVK::Invalidate(std::optional<Range> range) const {
auto flush_range = range.value_or(Range{0, GetDeviceBufferDescriptor().size});
::vmaInvalidateAllocation(resource_->buffer.get().allocator,
resource_->buffer.get().allocation,
flush_range.offset, flush_range.length);
}
bool DeviceBufferVK::SetLabel(const std::string& label, Range range) {
// We do not have the ability to name ranges. Just name the whole thing.
return SetLabel(label);
}
vk::Buffer DeviceBufferVK::GetBuffer() const {
return resource_->buffer.get().buffer;
}
} // namespace impeller
| engine/impeller/renderer/backend/vulkan/device_buffer_vk.cc/0 | {
"file_path": "engine/impeller/renderer/backend/vulkan/device_buffer_vk.cc",
"repo_id": "engine",
"token_count": 1383
} | 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.
#include "impeller/renderer/backend/vulkan/pipeline_library_vk.h"
#include <chrono>
#include <cstdint>
#include <optional>
#include <sstream>
#include "flutter/fml/container.h"
#include "flutter/fml/trace_event.h"
#include "impeller/base/promise.h"
#include "impeller/base/timing.h"
#include "impeller/base/validation.h"
#include "impeller/renderer/backend/vulkan/context_vk.h"
#include "impeller/renderer/backend/vulkan/formats_vk.h"
#include "impeller/renderer/backend/vulkan/pipeline_vk.h"
#include "impeller/renderer/backend/vulkan/shader_function_vk.h"
#include "impeller/renderer/backend/vulkan/vertex_descriptor_vk.h"
#include "vulkan/vulkan_core.h"
#include "vulkan/vulkan_enums.hpp"
namespace impeller {
PipelineLibraryVK::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)
: device_holder_(device_holder),
pso_cache_(std::make_shared<PipelineCacheVK>(std::move(caps),
device_holder,
std::move(cache_directory))),
worker_task_runner_(std::move(worker_task_runner)) {
FML_DCHECK(worker_task_runner_);
if (!pso_cache_->IsValid() || !worker_task_runner_) {
return;
}
is_valid_ = true;
}
PipelineLibraryVK::~PipelineLibraryVK() = default;
// |PipelineLibrary|
bool PipelineLibraryVK::IsValid() const {
return is_valid_;
}
std::unique_ptr<ComputePipelineVK> PipelineLibraryVK::CreateComputePipeline(
const ComputePipelineDescriptor& desc) {
TRACE_EVENT0("flutter", __FUNCTION__);
vk::ComputePipelineCreateInfo pipeline_info;
//----------------------------------------------------------------------------
/// Shader Stage
///
const auto entrypoint = desc.GetStageEntrypoint();
if (!entrypoint) {
VALIDATION_LOG << "Compute shader is missing an entrypoint.";
return nullptr;
}
std::shared_ptr<DeviceHolderVK> strong_device = device_holder_.lock();
if (!strong_device) {
return nullptr;
}
auto device_properties = strong_device->GetPhysicalDevice().getProperties();
auto max_wg_size = device_properties.limits.maxComputeWorkGroupSize;
// Give all compute shaders a specialization constant entry for the
// workgroup/threadgroup size.
vk::SpecializationMapEntry specialization_map_entry[1];
uint32_t workgroup_size_x = max_wg_size[0];
specialization_map_entry[0].constantID = 0;
specialization_map_entry[0].offset = 0;
specialization_map_entry[0].size = sizeof(uint32_t);
vk::SpecializationInfo specialization_info;
specialization_info.mapEntryCount = 1;
specialization_info.pMapEntries = &specialization_map_entry[0];
specialization_info.dataSize = sizeof(uint32_t);
specialization_info.pData = &workgroup_size_x;
vk::PipelineShaderStageCreateInfo info;
info.setStage(vk::ShaderStageFlagBits::eCompute);
info.setPName("main");
info.setModule(ShaderFunctionVK::Cast(entrypoint.get())->GetModule());
info.setPSpecializationInfo(&specialization_info);
pipeline_info.setStage(info);
//----------------------------------------------------------------------------
/// Pipeline Layout a.k.a the descriptor sets and uniforms.
///
std::vector<vk::DescriptorSetLayoutBinding> desc_bindings;
for (auto layout : desc.GetDescriptorSetLayouts()) {
auto vk_desc_layout = ToVKDescriptorSetLayoutBinding(layout);
desc_bindings.push_back(vk_desc_layout);
}
vk::DescriptorSetLayoutCreateInfo descs_layout_info;
descs_layout_info.setBindings(desc_bindings);
auto [descs_result, descs_layout] =
strong_device->GetDevice().createDescriptorSetLayoutUnique(
descs_layout_info);
if (descs_result != vk::Result::eSuccess) {
VALIDATION_LOG << "unable to create uniform descriptors";
return nullptr;
}
ContextVK::SetDebugName(strong_device->GetDevice(), descs_layout.get(),
"Descriptor Set Layout " + desc.GetLabel());
//----------------------------------------------------------------------------
/// Create the pipeline layout.
///
vk::PipelineLayoutCreateInfo pipeline_layout_info;
pipeline_layout_info.setSetLayouts(descs_layout.get());
auto pipeline_layout = strong_device->GetDevice().createPipelineLayoutUnique(
pipeline_layout_info);
if (pipeline_layout.result != vk::Result::eSuccess) {
VALIDATION_LOG << "Could not create pipeline layout for pipeline "
<< desc.GetLabel() << ": "
<< vk::to_string(pipeline_layout.result);
return nullptr;
}
pipeline_info.setLayout(pipeline_layout.value.get());
//----------------------------------------------------------------------------
/// Finally, all done with the setup info. Create the pipeline itself.
///
auto pipeline = pso_cache_->CreatePipeline(pipeline_info);
if (!pipeline) {
VALIDATION_LOG << "Could not create graphics pipeline: " << desc.GetLabel();
return nullptr;
}
ContextVK::SetDebugName(strong_device->GetDevice(), *pipeline_layout.value,
"Pipeline Layout " + desc.GetLabel());
ContextVK::SetDebugName(strong_device->GetDevice(), *pipeline,
"Pipeline " + desc.GetLabel());
return std::make_unique<ComputePipelineVK>(
device_holder_,
weak_from_this(), //
desc, //
std::move(pipeline), //
std::move(pipeline_layout.value), //
std::move(descs_layout) //
);
}
// |PipelineLibrary|
PipelineFuture<PipelineDescriptor> PipelineLibraryVK::GetPipeline(
PipelineDescriptor descriptor) {
Lock lock(pipelines_mutex_);
if (auto found = pipelines_.find(descriptor); found != pipelines_.end()) {
return found->second;
}
if (!IsValid()) {
return {
descriptor,
RealizedFuture<std::shared_ptr<Pipeline<PipelineDescriptor>>>(nullptr)};
}
auto promise = std::make_shared<
NoExceptionPromise<std::shared_ptr<Pipeline<PipelineDescriptor>>>>();
auto pipeline_future =
PipelineFuture<PipelineDescriptor>{descriptor, promise->get_future()};
pipelines_[descriptor] = pipeline_future;
auto weak_this = weak_from_this();
worker_task_runner_->PostTask([descriptor, weak_this, promise]() {
auto thiz = weak_this.lock();
if (!thiz) {
promise->set_value(nullptr);
VALIDATION_LOG << "Pipeline library was collected before the pipeline "
"could be created.";
return;
}
promise->set_value(PipelineVK::Create(
descriptor, //
PipelineLibraryVK::Cast(*thiz).device_holder_.lock(), //
weak_this //
));
});
return pipeline_future;
}
// |PipelineLibrary|
PipelineFuture<ComputePipelineDescriptor> PipelineLibraryVK::GetPipeline(
ComputePipelineDescriptor descriptor) {
Lock lock(compute_pipelines_mutex_);
if (auto found = compute_pipelines_.find(descriptor);
found != compute_pipelines_.end()) {
return found->second;
}
if (!IsValid()) {
return {
descriptor,
RealizedFuture<std::shared_ptr<Pipeline<ComputePipelineDescriptor>>>(
nullptr)};
}
auto promise = std::make_shared<
std::promise<std::shared_ptr<Pipeline<ComputePipelineDescriptor>>>>();
auto pipeline_future = PipelineFuture<ComputePipelineDescriptor>{
descriptor, promise->get_future()};
compute_pipelines_[descriptor] = pipeline_future;
auto weak_this = weak_from_this();
worker_task_runner_->PostTask([descriptor, weak_this, promise]() {
auto self = weak_this.lock();
if (!self) {
promise->set_value(nullptr);
VALIDATION_LOG << "Pipeline library was collected before the pipeline "
"could be created.";
return;
}
auto pipeline =
PipelineLibraryVK::Cast(*self).CreateComputePipeline(descriptor);
if (!pipeline) {
promise->set_value(nullptr);
VALIDATION_LOG << "Could not create pipeline: " << descriptor.GetLabel();
return;
}
promise->set_value(std::move(pipeline));
});
return pipeline_future;
}
// |PipelineLibrary|
void PipelineLibraryVK::RemovePipelinesWithEntryPoint(
std::shared_ptr<const ShaderFunction> function) {
Lock lock(pipelines_mutex_);
fml::erase_if(pipelines_, [&](auto item) {
return item->first.GetEntrypointForStage(function->GetStage())
->IsEqual(*function);
});
}
void PipelineLibraryVK::DidAcquireSurfaceFrame() {
if (++frames_acquired_ == 50u) {
PersistPipelineCacheToDisk();
}
}
void PipelineLibraryVK::PersistPipelineCacheToDisk() {
worker_task_runner_->PostTask(
[weak_cache = decltype(pso_cache_)::weak_type(pso_cache_)]() {
auto cache = weak_cache.lock();
if (!cache) {
return;
}
cache->PersistCacheToDisk();
});
}
const std::shared_ptr<PipelineCacheVK>& PipelineLibraryVK::GetPSOCache() const {
return pso_cache_;
}
const std::shared_ptr<fml::ConcurrentTaskRunner>&
PipelineLibraryVK::GetWorkerTaskRunner() const {
return worker_task_runner_;
}
} // namespace impeller
| engine/impeller/renderer/backend/vulkan/pipeline_library_vk.cc/0 | {
"file_path": "engine/impeller/renderer/backend/vulkan/pipeline_library_vk.cc",
"repo_id": "engine",
"token_count": 3644
} | 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/renderer/backend/vulkan/sampler_vk.h"
#include "impeller/renderer/backend/vulkan/context_vk.h"
#include "impeller/renderer/backend/vulkan/formats_vk.h"
#include "impeller/renderer/backend/vulkan/yuv_conversion_vk.h"
namespace impeller {
static vk::UniqueSampler CreateSampler(
const vk::Device& device,
const SamplerDescriptor& desc,
const std::shared_ptr<YUVConversionVK>& yuv_conversion) {
const auto mip_map = ToVKSamplerMipmapMode(desc.mip_filter);
const auto min_filter = ToVKSamplerMinMagFilter(desc.min_filter);
const auto mag_filter = ToVKSamplerMinMagFilter(desc.mag_filter);
const auto address_mode_u = ToVKSamplerAddressMode(desc.width_address_mode);
const auto address_mode_v = ToVKSamplerAddressMode(desc.height_address_mode);
const auto address_mode_w = ToVKSamplerAddressMode(desc.depth_address_mode);
vk::StructureChain<vk::SamplerCreateInfo,
// For VK_KHR_sampler_ycbcr_conversion
vk::SamplerYcbcrConversionInfo>
sampler_chain;
auto& sampler_info = sampler_chain.get();
sampler_info.magFilter = mag_filter;
sampler_info.minFilter = min_filter;
sampler_info.addressModeU = address_mode_u;
sampler_info.addressModeV = address_mode_v;
sampler_info.addressModeW = address_mode_w;
sampler_info.borderColor = vk::BorderColor::eFloatTransparentBlack;
sampler_info.mipmapMode = mip_map;
if (yuv_conversion && yuv_conversion->IsValid()) {
sampler_chain.get<vk::SamplerYcbcrConversionInfo>().conversion =
yuv_conversion->GetConversion();
//
// TL;DR: When using YUV conversion, our samplers are somewhat hobbled and
// not all options configurable in Impeller (especially the linear
// filtering which is by far the most used form of filtering) can be
// supported. Switch to safe defaults.
//
// Spec: If sampler Y'CBCR conversion is enabled and the potential format
// features of the sampler Y'CBCR conversion do not support or enable
// separate reconstruction filters, minFilter and magFilter must be equal to
// the sampler Y'CBCR conversion's chromaFilter.
//
// Thing is, we don't enable separate reconstruction filters. By the time we
// are here, we also don't have access to the descriptor used to create this
// conversion. So we don't yet know what the chromaFilter is. But eNearest
// is a safe bet since the `AndroidHardwareBufferTextureSourceVK` defaults
// to that safe value. So just use that.
//
// See the validation VUID-VkSamplerCreateInfo-minFilter-01645 for more.
//
sampler_info.magFilter = vk::Filter::eNearest;
sampler_info.minFilter = vk::Filter::eNearest;
// Spec: If sampler Y′CBCR conversion is enabled, addressModeU,
// addressModeV, and addressModeW must be
// VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, anisotropyEnable must be VK_FALSE,
// and unnormalizedCoordinates must be VK_FALSE.
//
// See the validation VUID-VkSamplerCreateInfo-addressModeU-01646 for more.
//
sampler_info.addressModeU = vk::SamplerAddressMode::eClampToEdge;
sampler_info.addressModeV = vk::SamplerAddressMode::eClampToEdge;
sampler_info.addressModeW = vk::SamplerAddressMode::eClampToEdge;
sampler_info.anisotropyEnable = false;
sampler_info.unnormalizedCoordinates = false;
} else {
sampler_chain.unlink<vk::SamplerYcbcrConversionInfo>();
}
auto sampler = device.createSamplerUnique(sampler_chain.get());
if (sampler.result != vk::Result::eSuccess) {
VALIDATION_LOG << "Could not create sampler: "
<< vk::to_string(sampler.result);
return {};
}
if (!desc.label.empty()) {
ContextVK::SetDebugName(device, sampler.value.get(), desc.label.c_str());
}
return std::move(sampler.value);
}
SamplerVK::SamplerVK(const vk::Device& device,
SamplerDescriptor desc,
std::shared_ptr<YUVConversionVK> yuv_conversion)
: Sampler(std::move(desc)),
device_(device),
sampler_(MakeSharedVK<vk::Sampler>(
CreateSampler(device, desc_, yuv_conversion))),
yuv_conversion_(std::move(yuv_conversion)) {
is_valid_ = sampler_ && !!sampler_->Get();
}
SamplerVK::~SamplerVK() = default;
vk::Sampler SamplerVK::GetSampler() const {
return *sampler_;
}
std::shared_ptr<SamplerVK> SamplerVK::CreateVariantForConversion(
std::shared_ptr<YUVConversionVK> conversion) const {
if (!conversion || !is_valid_) {
return nullptr;
}
return std::make_shared<SamplerVK>(device_, desc_, std::move(conversion));
}
const std::shared_ptr<YUVConversionVK>& SamplerVK::GetYUVConversion() const {
return yuv_conversion_;
}
} // namespace impeller
| engine/impeller/renderer/backend/vulkan/sampler_vk.cc/0 | {
"file_path": "engine/impeller/renderer/backend/vulkan/sampler_vk.cc",
"repo_id": "engine",
"token_count": 1815
} | 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/renderer/backend/vulkan/swapchain/khr/khr_swapchain_impl_vk.h"
#include "fml/synchronization/semaphore.h"
#include "impeller/base/validation.h"
#include "impeller/core/formats.h"
#include "impeller/renderer/backend/vulkan/command_buffer_vk.h"
#include "impeller/renderer/backend/vulkan/command_encoder_vk.h"
#include "impeller/renderer/backend/vulkan/context_vk.h"
#include "impeller/renderer/backend/vulkan/formats_vk.h"
#include "impeller/renderer/backend/vulkan/gpu_tracer_vk.h"
#include "impeller/renderer/backend/vulkan/swapchain/khr/khr_surface_vk.h"
#include "impeller/renderer/backend/vulkan/swapchain/khr/khr_swapchain_image_vk.h"
#include "impeller/renderer/context.h"
#include "vulkan/vulkan_structs.hpp"
namespace impeller {
static constexpr size_t kMaxFramesInFlight = 3u;
// Number of frames to poll for orientation changes. For example `1u` means
// that the orientation will be polled every frame, while `2u` means that the
// orientation will be polled every other frame.
static constexpr size_t kPollFramesForOrientation = 1u;
struct KHRFrameSynchronizerVK {
vk::UniqueFence acquire;
vk::UniqueSemaphore render_ready;
vk::UniqueSemaphore present_ready;
std::shared_ptr<CommandBuffer> final_cmd_buffer;
bool is_valid = false;
explicit KHRFrameSynchronizerVK(const vk::Device& device) {
auto acquire_res = device.createFenceUnique(
vk::FenceCreateInfo{vk::FenceCreateFlagBits::eSignaled});
auto render_res = device.createSemaphoreUnique({});
auto present_res = device.createSemaphoreUnique({});
if (acquire_res.result != vk::Result::eSuccess ||
render_res.result != vk::Result::eSuccess ||
present_res.result != vk::Result::eSuccess) {
VALIDATION_LOG << "Could not create synchronizer.";
return;
}
acquire = std::move(acquire_res.value);
render_ready = std::move(render_res.value);
present_ready = std::move(present_res.value);
is_valid = true;
}
~KHRFrameSynchronizerVK() = default;
bool WaitForFence(const vk::Device& device) {
if (auto result = device.waitForFences(
*acquire, // fence
true, // wait all
std::numeric_limits<uint64_t>::max() // timeout (ns)
);
result != vk::Result::eSuccess) {
VALIDATION_LOG << "Fence wait failed: " << vk::to_string(result);
return false;
}
if (auto result = device.resetFences(*acquire);
result != vk::Result::eSuccess) {
VALIDATION_LOG << "Could not reset fence: " << vk::to_string(result);
return false;
}
return true;
}
};
static bool ContainsFormat(const std::vector<vk::SurfaceFormatKHR>& formats,
vk::SurfaceFormatKHR format) {
return std::find(formats.begin(), formats.end(), format) != formats.end();
}
static std::optional<vk::SurfaceFormatKHR> ChooseSurfaceFormat(
const std::vector<vk::SurfaceFormatKHR>& formats,
PixelFormat preference) {
const auto colorspace = vk::ColorSpaceKHR::eSrgbNonlinear;
const auto vk_preference =
vk::SurfaceFormatKHR{ToVKImageFormat(preference), colorspace};
if (ContainsFormat(formats, vk_preference)) {
return vk_preference;
}
std::vector<vk::SurfaceFormatKHR> options = {
{vk::Format::eB8G8R8A8Unorm, colorspace},
{vk::Format::eR8G8B8A8Unorm, colorspace}};
for (const auto& format : options) {
if (ContainsFormat(formats, format)) {
return format;
}
}
return std::nullopt;
}
static std::optional<vk::CompositeAlphaFlagBitsKHR> ChooseAlphaCompositionMode(
vk::CompositeAlphaFlagsKHR flags) {
if (flags & vk::CompositeAlphaFlagBitsKHR::eInherit) {
return vk::CompositeAlphaFlagBitsKHR::eInherit;
}
if (flags & vk::CompositeAlphaFlagBitsKHR::ePreMultiplied) {
return vk::CompositeAlphaFlagBitsKHR::ePreMultiplied;
}
if (flags & vk::CompositeAlphaFlagBitsKHR::ePostMultiplied) {
return vk::CompositeAlphaFlagBitsKHR::ePostMultiplied;
}
if (flags & vk::CompositeAlphaFlagBitsKHR::eOpaque) {
return vk::CompositeAlphaFlagBitsKHR::eOpaque;
}
return std::nullopt;
}
std::shared_ptr<KHRSwapchainImplVK> KHRSwapchainImplVK::Create(
const std::shared_ptr<Context>& context,
vk::UniqueSurfaceKHR surface,
const ISize& size,
bool enable_msaa,
vk::SwapchainKHR old_swapchain) {
return std::shared_ptr<KHRSwapchainImplVK>(new KHRSwapchainImplVK(
context, std::move(surface), size, enable_msaa, old_swapchain));
}
KHRSwapchainImplVK::KHRSwapchainImplVK(const std::shared_ptr<Context>& context,
vk::UniqueSurfaceKHR surface,
const ISize& size,
bool enable_msaa,
vk::SwapchainKHR old_swapchain) {
if (!context) {
VALIDATION_LOG << "Cannot create a swapchain without a context.";
return;
}
auto& vk_context = ContextVK::Cast(*context);
const auto [caps_result, surface_caps] =
vk_context.GetPhysicalDevice().getSurfaceCapabilitiesKHR(*surface);
if (caps_result != vk::Result::eSuccess) {
VALIDATION_LOG << "Could not get surface capabilities: "
<< vk::to_string(caps_result);
return;
}
auto [formats_result, formats] =
vk_context.GetPhysicalDevice().getSurfaceFormatsKHR(*surface);
if (formats_result != vk::Result::eSuccess) {
VALIDATION_LOG << "Could not get surface formats: "
<< vk::to_string(formats_result);
return;
}
const auto format = ChooseSurfaceFormat(
formats, vk_context.GetCapabilities()->GetDefaultColorFormat());
if (!format.has_value()) {
VALIDATION_LOG << "Swapchain has no supported formats.";
return;
}
vk_context.SetOffscreenFormat(ToPixelFormat(format.value().format));
const auto composite =
ChooseAlphaCompositionMode(surface_caps.supportedCompositeAlpha);
if (!composite.has_value()) {
VALIDATION_LOG << "No composition mode supported.";
return;
}
vk::SwapchainCreateInfoKHR swapchain_info;
swapchain_info.surface = *surface;
swapchain_info.imageFormat = format.value().format;
swapchain_info.imageColorSpace = format.value().colorSpace;
swapchain_info.presentMode = vk::PresentModeKHR::eFifo;
swapchain_info.imageExtent = vk::Extent2D{
std::clamp(static_cast<uint32_t>(size.width),
surface_caps.minImageExtent.width,
surface_caps.maxImageExtent.width),
std::clamp(static_cast<uint32_t>(size.height),
surface_caps.minImageExtent.height,
surface_caps.maxImageExtent.height),
};
swapchain_info.minImageCount =
std::clamp(surface_caps.minImageCount + 1u, // preferred image count
surface_caps.minImageCount, // min count cannot be zero
surface_caps.maxImageCount == 0u
? surface_caps.minImageCount + 1u
: surface_caps.maxImageCount // max zero means no limit
);
swapchain_info.imageArrayLayers = 1u;
// Swapchain images are primarily used as color attachments (via resolve),
// blit targets, or input attachments.
swapchain_info.imageUsage = vk::ImageUsageFlagBits::eColorAttachment |
vk::ImageUsageFlagBits::eTransferDst |
vk::ImageUsageFlagBits::eInputAttachment;
swapchain_info.preTransform = vk::SurfaceTransformFlagBitsKHR::eIdentity;
swapchain_info.compositeAlpha = composite.value();
// If we set the clipped value to true, Vulkan expects we will never read back
// from the buffer. This is analogous to [CAMetalLayer framebufferOnly] in
// Metal.
swapchain_info.clipped = true;
// Setting queue family indices is irrelevant since the present mode is
// exclusive.
swapchain_info.imageSharingMode = vk::SharingMode::eExclusive;
swapchain_info.oldSwapchain = old_swapchain;
auto [swapchain_result, swapchain] =
vk_context.GetDevice().createSwapchainKHRUnique(swapchain_info);
if (swapchain_result != vk::Result::eSuccess) {
VALIDATION_LOG << "Could not create swapchain: "
<< vk::to_string(swapchain_result);
return;
}
auto [images_result, images] =
vk_context.GetDevice().getSwapchainImagesKHR(*swapchain);
if (images_result != vk::Result::eSuccess) {
VALIDATION_LOG << "Could not get swapchain images.";
return;
}
TextureDescriptor texture_desc;
texture_desc.usage = TextureUsage::kRenderTarget;
texture_desc.storage_mode = StorageMode::kDevicePrivate;
texture_desc.format = ToPixelFormat(swapchain_info.imageFormat);
texture_desc.size = ISize::MakeWH(swapchain_info.imageExtent.width,
swapchain_info.imageExtent.height);
// Allocate a single onscreen MSAA texture and Depth+Stencil Texture to
// be shared by all swapchain images.
TextureDescriptor msaa_desc;
msaa_desc.storage_mode = StorageMode::kDeviceTransient;
msaa_desc.type = TextureType::kTexture2DMultisample;
msaa_desc.sample_count = SampleCount::kCount4;
msaa_desc.format = texture_desc.format;
msaa_desc.size = texture_desc.size;
msaa_desc.usage = TextureUsage::kRenderTarget;
// The depth+stencil configuration matches the configuration used by
// RenderTarget::SetupDepthStencilAttachments and matching the swapchain
// image dimensions and sample count.
TextureDescriptor depth_stencil_desc;
depth_stencil_desc.storage_mode = StorageMode::kDeviceTransient;
if (enable_msaa) {
depth_stencil_desc.type = TextureType::kTexture2DMultisample;
depth_stencil_desc.sample_count = SampleCount::kCount4;
} else {
depth_stencil_desc.type = TextureType::kTexture2D;
depth_stencil_desc.sample_count = SampleCount::kCount1;
}
depth_stencil_desc.format =
context->GetCapabilities()->GetDefaultDepthStencilFormat();
depth_stencil_desc.size = texture_desc.size;
depth_stencil_desc.usage = TextureUsage::kRenderTarget;
std::shared_ptr<Texture> msaa_texture;
if (enable_msaa) {
msaa_texture = context->GetResourceAllocator()->CreateTexture(msaa_desc);
}
std::shared_ptr<Texture> depth_stencil_texture =
context->GetResourceAllocator()->CreateTexture(depth_stencil_desc);
std::vector<std::shared_ptr<KHRSwapchainImageVK>> swapchain_images;
for (const auto& image : images) {
auto swapchain_image = std::make_shared<KHRSwapchainImageVK>(
texture_desc, // texture descriptor
vk_context.GetDevice(), // device
image // image
);
if (!swapchain_image->IsValid()) {
VALIDATION_LOG << "Could not create swapchain image.";
return;
}
swapchain_image->SetMSAATexture(msaa_texture);
swapchain_image->SetDepthStencilTexture(depth_stencil_texture);
ContextVK::SetDebugName(
vk_context.GetDevice(), swapchain_image->GetImage(),
"SwapchainImage" + std::to_string(swapchain_images.size()));
ContextVK::SetDebugName(
vk_context.GetDevice(), swapchain_image->GetImageView(),
"SwapchainImageView" + std::to_string(swapchain_images.size()));
swapchain_images.emplace_back(swapchain_image);
}
std::vector<std::unique_ptr<KHRFrameSynchronizerVK>> synchronizers;
for (size_t i = 0u; i < kMaxFramesInFlight; i++) {
auto sync =
std::make_unique<KHRFrameSynchronizerVK>(vk_context.GetDevice());
if (!sync->is_valid) {
VALIDATION_LOG << "Could not create frame synchronizers.";
return;
}
synchronizers.emplace_back(std::move(sync));
}
FML_DCHECK(!synchronizers.empty());
context_ = context;
surface_ = std::move(surface);
surface_format_ = swapchain_info.imageFormat;
swapchain_ = std::move(swapchain);
images_ = std::move(swapchain_images);
synchronizers_ = std::move(synchronizers);
current_frame_ = synchronizers_.size() - 1u;
size_ = size;
enable_msaa_ = enable_msaa;
is_valid_ = true;
}
KHRSwapchainImplVK::~KHRSwapchainImplVK() {
DestroySwapchain();
}
const ISize& KHRSwapchainImplVK::GetSize() const {
return size_;
}
bool KHRSwapchainImplVK::IsValid() const {
return is_valid_;
}
void KHRSwapchainImplVK::WaitIdle() const {
if (auto context = context_.lock()) {
[[maybe_unused]] auto result =
ContextVK::Cast(*context).GetDevice().waitIdle();
}
}
std::pair<vk::UniqueSurfaceKHR, vk::UniqueSwapchainKHR>
KHRSwapchainImplVK::DestroySwapchain() {
WaitIdle();
is_valid_ = false;
synchronizers_.clear();
images_.clear();
context_.reset();
return {std::move(surface_), std::move(swapchain_)};
}
vk::Format KHRSwapchainImplVK::GetSurfaceFormat() const {
return surface_format_;
}
std::shared_ptr<Context> KHRSwapchainImplVK::GetContext() const {
return context_.lock();
}
KHRSwapchainImplVK::AcquireResult KHRSwapchainImplVK::AcquireNextDrawable() {
auto context_strong = context_.lock();
if (!context_strong) {
return KHRSwapchainImplVK::AcquireResult{};
}
const auto& context = ContextVK::Cast(*context_strong);
current_frame_ = (current_frame_ + 1u) % synchronizers_.size();
const auto& sync = synchronizers_[current_frame_];
//----------------------------------------------------------------------------
/// Wait on the host for the synchronizer fence.
///
if (!sync->WaitForFence(context.GetDevice())) {
VALIDATION_LOG << "Could not wait for fence.";
return KHRSwapchainImplVK::AcquireResult{};
}
//----------------------------------------------------------------------------
/// Get the next image index.
///
auto [acq_result, index] = context.GetDevice().acquireNextImageKHR(
*swapchain_, // swapchain
1'000'000'000, // timeout (ns) 1000ms
*sync->render_ready, // signal semaphore
nullptr // fence
);
switch (acq_result) {
case vk::Result::eSuccess:
// Keep going.
break;
case vk::Result::eSuboptimalKHR:
case vk::Result::eErrorOutOfDateKHR:
// A recoverable error. Just say we are out of date.
return AcquireResult{true /* out of date */};
break;
default:
// An unrecoverable error.
VALIDATION_LOG << "Could not acquire next swapchain image: "
<< vk::to_string(acq_result);
return AcquireResult{false /* out of date */};
}
if (index >= images_.size()) {
VALIDATION_LOG << "Swapchain returned an invalid image index.";
return KHRSwapchainImplVK::AcquireResult{};
}
/// Record all subsequent cmd buffers as part of the current frame.
context.GetGPUTracer()->MarkFrameStart();
auto image = images_[index % images_.size()];
uint32_t image_index = index;
return AcquireResult{KHRSurfaceVK::WrapSwapchainImage(
context_strong, // context
image, // swapchain image
[weak_swapchain = weak_from_this(), image, image_index]() -> bool {
auto swapchain = weak_swapchain.lock();
if (!swapchain) {
return false;
}
return swapchain->Present(image, image_index);
}, // swap callback
enable_msaa_ //
)};
}
bool KHRSwapchainImplVK::Present(
const std::shared_ptr<KHRSwapchainImageVK>& image,
uint32_t index) {
auto context_strong = context_.lock();
if (!context_strong) {
return false;
}
const auto& context = ContextVK::Cast(*context_strong);
const auto& sync = synchronizers_[current_frame_];
context.GetGPUTracer()->MarkFrameEnd();
//----------------------------------------------------------------------------
/// Transition the image to color-attachment-optimal.
///
sync->final_cmd_buffer = context.CreateCommandBuffer();
if (!sync->final_cmd_buffer) {
return false;
}
auto vk_final_cmd_buffer = CommandBufferVK::Cast(*sync->final_cmd_buffer)
.GetEncoder()
->GetCommandBuffer();
{
BarrierVK barrier;
barrier.new_layout = vk::ImageLayout::ePresentSrcKHR;
barrier.cmd_buffer = vk_final_cmd_buffer;
barrier.src_access = vk::AccessFlagBits::eColorAttachmentWrite;
barrier.src_stage = vk::PipelineStageFlagBits::eColorAttachmentOutput;
barrier.dst_access = {};
barrier.dst_stage = vk::PipelineStageFlagBits::eBottomOfPipe;
if (!image->SetLayout(barrier).ok()) {
return false;
}
if (vk_final_cmd_buffer.end() != vk::Result::eSuccess) {
return false;
}
}
//----------------------------------------------------------------------------
/// Signal that the presentation semaphore is ready.
///
{
vk::SubmitInfo submit_info;
vk::PipelineStageFlags wait_stage =
vk::PipelineStageFlagBits::eColorAttachmentOutput;
submit_info.setWaitDstStageMask(wait_stage);
submit_info.setWaitSemaphores(*sync->render_ready);
submit_info.setSignalSemaphores(*sync->present_ready);
submit_info.setCommandBuffers(vk_final_cmd_buffer);
auto result =
context.GetGraphicsQueue()->Submit(submit_info, *sync->acquire);
if (result != vk::Result::eSuccess) {
VALIDATION_LOG << "Could not wait on render semaphore: "
<< vk::to_string(result);
return false;
}
}
//----------------------------------------------------------------------------
/// Present the image.
///
uint32_t indices[] = {static_cast<uint32_t>(index)};
vk::PresentInfoKHR present_info;
present_info.setSwapchains(*swapchain_);
present_info.setImageIndices(indices);
present_info.setWaitSemaphores(*sync->present_ready);
auto result = context.GetGraphicsQueue()->Present(present_info);
switch (result) {
case vk::Result::eErrorOutOfDateKHR:
// Caller will recreate the impl on acquisition, not submission.
[[fallthrough]];
case vk::Result::eErrorSurfaceLostKHR:
// Vulkan guarantees that the set of queue operations will still
// complete successfully.
[[fallthrough]];
case vk::Result::eSuboptimalKHR:
// Even though we're handling rotation changes via polling, we
// still need to handle the case where the swapchain signals that
// it's suboptimal (i.e. every frame when we are rotated given we
// aren't doing Vulkan pre-rotation).
[[fallthrough]];
case vk::Result::eSuccess:
break;
default:
VALIDATION_LOG << "Could not present queue: " << vk::to_string(result);
break;
}
return true;
}
} // namespace impeller
| engine/impeller/renderer/backend/vulkan/swapchain/khr/khr_swapchain_impl_vk.cc/0 | {
"file_path": "engine/impeller/renderer/backend/vulkan/swapchain/khr/khr_swapchain_impl_vk.cc",
"repo_id": "engine",
"token_count": 7224
} | 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_IMPELLER_RENDERER_BACKEND_VULKAN_VERTEX_DESCRIPTOR_VK_H_
#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_VERTEX_DESCRIPTOR_VK_H_
#include "flutter/fml/macros.h"
#include "impeller/core/shader_types.h"
#include "impeller/renderer/backend/vulkan/vk.h"
namespace impeller {
vk::Format ToVertexDescriptorFormat(const ShaderStageIOSlot& input);
} // namespace impeller
#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_VERTEX_DESCRIPTOR_VK_H_
| engine/impeller/renderer/backend/vulkan/vertex_descriptor_vk.h/0 | {
"file_path": "engine/impeller/renderer/backend/vulkan/vertex_descriptor_vk.h",
"repo_id": "engine",
"token_count": 248
} | 249 |
// 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/command.h"
#include <utility>
#include "impeller/base/validation.h"
#include "impeller/core/formats.h"
#include "impeller/renderer/vertex_descriptor.h"
namespace impeller {
bool Command::BindVertices(VertexBuffer buffer) {
if (buffer.index_type == IndexType::kUnknown) {
VALIDATION_LOG << "Cannot bind vertex buffer with an unknown index type.";
return false;
}
vertex_buffer = std::move(buffer);
return true;
}
bool Command::BindResource(ShaderStage stage,
DescriptorType type,
const ShaderUniformSlot& slot,
const ShaderMetadata& metadata,
BufferView view) {
return DoBindResource(stage, slot, &metadata, std::move(view));
}
bool Command::BindResource(
ShaderStage stage,
DescriptorType type,
const ShaderUniformSlot& slot,
const std::shared_ptr<const ShaderMetadata>& metadata,
BufferView view) {
return DoBindResource(stage, slot, metadata, std::move(view));
}
template <class T>
bool Command::DoBindResource(ShaderStage stage,
const ShaderUniformSlot& slot,
const T metadata,
BufferView view) {
FML_DCHECK(slot.ext_res_0 != VertexDescriptor::kReservedVertexBufferIndex);
if (!view) {
return false;
}
switch (stage) {
case ShaderStage::kVertex:
vertex_bindings.buffers.emplace_back(BufferAndUniformSlot{
.slot = slot, .view = BufferResource(metadata, std::move(view))});
return true;
case ShaderStage::kFragment:
fragment_bindings.buffers.emplace_back(BufferAndUniformSlot{
.slot = slot, .view = BufferResource(metadata, std::move(view))});
return true;
case ShaderStage::kCompute:
VALIDATION_LOG << "Use ComputeCommands for compute shader stages.";
case ShaderStage::kUnknown:
return false;
}
return false;
}
bool Command::BindResource(ShaderStage stage,
DescriptorType type,
const SampledImageSlot& slot,
const ShaderMetadata& metadata,
std::shared_ptr<const Texture> texture,
const std::unique_ptr<const Sampler>& sampler) {
if (!sampler) {
return false;
}
if (!texture || !texture->IsValid()) {
return false;
}
switch (stage) {
case ShaderStage::kVertex:
vertex_bindings.sampled_images.emplace_back(TextureAndSampler{
.slot = slot,
.texture = {&metadata, std::move(texture)},
.sampler = sampler,
});
return true;
case ShaderStage::kFragment:
fragment_bindings.sampled_images.emplace_back(TextureAndSampler{
.slot = slot,
.texture = {&metadata, std::move(texture)},
.sampler = sampler,
});
return true;
case ShaderStage::kCompute:
VALIDATION_LOG << "Use ComputeCommands for compute shader stages.";
case ShaderStage::kUnknown:
return false;
}
return false;
}
} // namespace impeller
| engine/impeller/renderer/command.cc/0 | {
"file_path": "engine/impeller/renderer/command.cc",
"repo_id": "engine",
"token_count": 1411
} | 250 |
// 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/render_pass.h"
#include "fml/status.h"
namespace impeller {
RenderPass::RenderPass(std::shared_ptr<const Context> context,
const RenderTarget& target)
: context_(std::move(context)),
sample_count_(target.GetSampleCount()),
pixel_format_(target.GetRenderTargetPixelFormat()),
has_depth_attachment_(target.GetDepthAttachment().has_value()),
has_stencil_attachment_(target.GetStencilAttachment().has_value()),
render_target_size_(target.GetRenderTargetSize()),
render_target_(target),
orthographic_(Matrix::MakeOrthographic(render_target_size_)) {}
RenderPass::~RenderPass() {}
SampleCount RenderPass::GetSampleCount() const {
return sample_count_;
}
PixelFormat RenderPass::GetRenderTargetPixelFormat() const {
return pixel_format_;
}
bool RenderPass::HasDepthAttachment() const {
return has_depth_attachment_;
}
bool RenderPass::HasStencilAttachment() const {
return has_stencil_attachment_;
}
const RenderTarget& RenderPass::GetRenderTarget() const {
return render_target_;
}
ISize RenderPass::GetRenderTargetSize() const {
return render_target_size_;
}
const Matrix& RenderPass::GetOrthographicTransform() const {
return orthographic_;
}
void RenderPass::SetLabel(std::string label) {
if (label.empty()) {
return;
}
OnSetLabel(std::move(label));
}
bool RenderPass::AddCommand(Command&& command) {
if (!command.IsValid()) {
VALIDATION_LOG << "Attempted to add an invalid command to the render pass.";
return false;
}
if (command.scissor.has_value()) {
auto target_rect = IRect::MakeSize(render_target_.GetRenderTargetSize());
if (!target_rect.Contains(command.scissor.value())) {
VALIDATION_LOG << "Cannot apply a scissor that lies outside the bounds "
"of the render target.";
return false;
}
}
if (command.vertex_buffer.vertex_count == 0u ||
command.instance_count == 0u) {
// Essentially a no-op. Don't record the command but this is not necessary
// an error either.
return true;
}
commands_.emplace_back(std::move(command));
return true;
}
bool RenderPass::EncodeCommands() const {
return OnEncodeCommands(*context_);
}
const std::shared_ptr<const Context>& RenderPass::GetContext() const {
return context_;
}
void RenderPass::SetPipeline(
const std::shared_ptr<Pipeline<PipelineDescriptor>>& pipeline) {
pending_.pipeline = pipeline;
}
void RenderPass::SetCommandLabel(std::string_view label) {
#ifdef IMPELLER_DEBUG
pending_.label = std::string(label);
#endif // IMPELLER_DEBUG
}
void RenderPass::SetStencilReference(uint32_t value) {
pending_.stencil_reference = value;
}
void RenderPass::SetBaseVertex(uint64_t value) {
pending_.base_vertex = value;
}
void RenderPass::SetViewport(Viewport viewport) {
pending_.viewport = viewport;
}
void RenderPass::SetScissor(IRect scissor) {
pending_.scissor = scissor;
}
void RenderPass::SetInstanceCount(size_t count) {
pending_.instance_count = count;
}
bool RenderPass::SetVertexBuffer(VertexBuffer buffer) {
return pending_.BindVertices(std::move(buffer));
}
fml::Status RenderPass::Draw() {
auto result = AddCommand(std::move(pending_));
pending_ = Command{};
if (result) {
return fml::Status();
}
return fml::Status(fml::StatusCode::kInvalidArgument,
"Failed to encode command");
}
// |ResourceBinder|
bool RenderPass::BindResource(ShaderStage stage,
DescriptorType type,
const ShaderUniformSlot& slot,
const ShaderMetadata& metadata,
BufferView view) {
return pending_.BindResource(stage, type, slot, metadata, view);
}
bool RenderPass::BindResource(
ShaderStage stage,
DescriptorType type,
const ShaderUniformSlot& slot,
const std::shared_ptr<const ShaderMetadata>& metadata,
BufferView view) {
return pending_.BindResource(stage, type, slot, metadata, std::move(view));
}
// |ResourceBinder|
bool RenderPass::BindResource(ShaderStage stage,
DescriptorType type,
const SampledImageSlot& slot,
const ShaderMetadata& metadata,
std::shared_ptr<const Texture> texture,
const std::unique_ptr<const Sampler>& sampler) {
return pending_.BindResource(stage, type, slot, metadata, std::move(texture),
sampler);
}
} // namespace impeller
| engine/impeller/renderer/render_pass.cc/0 | {
"file_path": "engine/impeller/renderer/render_pass.cc",
"repo_id": "engine",
"token_count": 1822
} | 251 |
// 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/snapshot.h"
#include <optional>
namespace impeller {
std::optional<Rect> Snapshot::GetCoverage() const {
if (!texture) {
return std::nullopt;
}
return Rect::MakeSize(texture->GetSize()).TransformBounds(transform);
}
std::optional<Matrix> Snapshot::GetUVTransform() const {
if (!texture || texture->GetSize().IsEmpty()) {
return std::nullopt;
}
return Matrix::MakeScale(1 / Vector2(texture->GetSize())) *
transform.Invert();
}
std::optional<std::array<Point, 4>> Snapshot::GetCoverageUVs(
const Rect& coverage) const {
auto uv_transform = GetUVTransform();
if (!uv_transform.has_value()) {
return std::nullopt;
}
return coverage.GetTransformedPoints(uv_transform.value());
}
} // namespace impeller
| engine/impeller/renderer/snapshot.cc/0 | {
"file_path": "engine/impeller/renderer/snapshot.cc",
"repo_id": "engine",
"token_count": 310
} | 252 |
// 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_RUNTIME_STAGE_RUNTIME_STAGE_H_
#define FLUTTER_IMPELLER_RUNTIME_STAGE_RUNTIME_STAGE_H_
#include <map>
#include <memory>
#include <string>
#include "flutter/fml/mapping.h"
#include "flutter/impeller/core/runtime_types.h"
#include "runtime_stage_types_flatbuffers.h"
namespace impeller {
class RuntimeStage {
public:
static const char* kVulkanUBOName;
using Map = std::map<RuntimeStageBackend, std::shared_ptr<RuntimeStage>>;
static Map DecodeRuntimeStages(const std::shared_ptr<fml::Mapping>& payload);
RuntimeStage(const fb::RuntimeStage* runtime_stage,
const std::shared_ptr<fml::Mapping>& payload);
~RuntimeStage();
RuntimeStage(RuntimeStage&&);
RuntimeStage& operator=(RuntimeStage&&);
bool IsValid() const;
RuntimeShaderStage GetShaderStage() const;
const std::vector<RuntimeUniformDescription>& GetUniforms() const;
const std::string& GetEntrypoint() const;
const RuntimeUniformDescription* GetUniform(const std::string& name) const;
const std::shared_ptr<fml::Mapping>& GetCodeMapping() const;
bool IsDirty() const;
void SetClean();
private:
std::shared_ptr<fml::Mapping> payload_;
RuntimeShaderStage stage_ = RuntimeShaderStage::kVertex;
std::string entrypoint_;
std::shared_ptr<fml::Mapping> code_mapping_;
std::vector<RuntimeUniformDescription> uniforms_;
bool is_valid_ = false;
bool is_dirty_ = true;
RuntimeStage(const RuntimeStage&) = delete;
static std::unique_ptr<RuntimeStage> RuntimeStageIfPresent(
const fb::RuntimeStage* runtime_stage,
const std::shared_ptr<fml::Mapping>& payload);
RuntimeStage& operator=(const RuntimeStage&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_RUNTIME_STAGE_RUNTIME_STAGE_H_
| engine/impeller/runtime_stage/runtime_stage.h/0 | {
"file_path": "engine/impeller/runtime_stage/runtime_stage.h",
"repo_id": "engine",
"token_count": 655
} | 253 |
// 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/camera.h"
namespace impeller {
namespace scene {
Camera Camera::MakePerspective(Radians fov_y, Vector3 position) {
Camera camera;
camera.fov_y_ = fov_y;
camera.position_ = position;
return camera;
}
Camera Camera::LookAt(Vector3 target, Vector3 up) const {
Camera camera = *this;
camera.target_ = target;
camera.up_ = up;
return camera;
}
Matrix Camera::GetTransform(ISize target_size) const {
if (transform_.has_value()) {
return transform_.value();
}
transform_ = Matrix::MakePerspective(fov_y_, target_size, z_near_, z_far_) *
Matrix::MakeLookAt(position_, target_, up_);
return transform_.value();
}
} // namespace scene
} // namespace impeller
| engine/impeller/scene/camera.cc/0 | {
"file_path": "engine/impeller/scene/camera.cc",
"repo_id": "engine",
"token_count": 302
} | 254 |
// 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_IMPORTER_VERTICES_BUILDER_H_
#define FLUTTER_IMPELLER_SCENE_IMPORTER_VERTICES_BUILDER_H_
#include <cstddef>
#include <map>
#include "flutter/fml/macros.h"
#include "impeller/geometry/matrix.h"
#include "impeller/scene/importer/scene_flatbuffers.h"
namespace impeller {
namespace scene {
namespace importer {
//------------------------------------------------------------------------------
/// VerticesBuilder
///
class VerticesBuilder {
public:
static std::unique_ptr<VerticesBuilder> MakeUnskinned();
static std::unique_ptr<VerticesBuilder> MakeSkinned();
enum class ComponentType {
kSignedByte = 5120,
kUnsignedByte,
kSignedShort,
kUnsignedShort,
kSignedInt,
kUnsignedInt,
kFloat,
};
enum class AttributeType {
kPosition,
kNormal,
kTangent,
kTextureCoords,
kColor,
kJoints,
kWeights,
};
using ComponentConverter = std::function<
Scalar(const void* source, size_t byte_offset, bool normalized)>;
struct ComponentProperties {
size_t size_bytes = 0;
ComponentConverter convert_proc;
};
struct AttributeProperties;
using AttributeWriter =
std::function<void(Scalar* destination,
const void* source,
const ComponentProperties& component_props,
const AttributeProperties& attribute_props)>;
struct AttributeProperties {
size_t offset_bytes = 0;
size_t size_bytes = 0;
size_t component_count = 0;
AttributeWriter write_proc;
};
VerticesBuilder();
virtual ~VerticesBuilder();
virtual void WriteFBVertices(fb::MeshPrimitiveT& primitive) const = 0;
virtual void SetAttributeFromBuffer(AttributeType attribute,
ComponentType component_type,
const void* buffer_start,
size_t attribute_stride_bytes,
size_t attribute_count) = 0;
protected:
static void WriteAttribute(void* destination,
size_t destination_stride_bytes,
AttributeType attribute,
ComponentType component_type,
const void* source,
size_t attribute_stride_bytes,
size_t attribute_count);
private:
static std::map<VerticesBuilder::AttributeType,
VerticesBuilder::AttributeProperties>
kAttributeTypes;
VerticesBuilder(const VerticesBuilder&) = delete;
VerticesBuilder& operator=(const VerticesBuilder&) = delete;
};
//------------------------------------------------------------------------------
/// UnskinnedVerticesBuilder
///
class UnskinnedVerticesBuilder final : public VerticesBuilder {
public:
struct Vertex {
Vector3 position;
Vector3 normal;
Vector4 tangent;
Vector2 texture_coords;
Color color = Color::White();
};
UnskinnedVerticesBuilder();
virtual ~UnskinnedVerticesBuilder() override;
// |VerticesBuilder|
void WriteFBVertices(fb::MeshPrimitiveT& primitive) const override;
// |VerticesBuilder|
void SetAttributeFromBuffer(AttributeType attribute,
ComponentType component_type,
const void* buffer_start,
size_t attribute_stride_bytes,
size_t attribute_count) override;
private:
std::vector<Vertex> vertices_;
UnskinnedVerticesBuilder(const UnskinnedVerticesBuilder&) = delete;
UnskinnedVerticesBuilder& operator=(const UnskinnedVerticesBuilder&) = delete;
};
//------------------------------------------------------------------------------
/// SkinnedVerticesBuilder
///
class SkinnedVerticesBuilder final : public VerticesBuilder {
public:
struct Vertex {
UnskinnedVerticesBuilder::Vertex vertex;
Vector4 joints;
Vector4 weights;
};
SkinnedVerticesBuilder();
virtual ~SkinnedVerticesBuilder() override;
// |VerticesBuilder|
void WriteFBVertices(fb::MeshPrimitiveT& primitive) const override;
// |VerticesBuilder|
void SetAttributeFromBuffer(AttributeType attribute,
ComponentType component_type,
const void* buffer_start,
size_t attribute_stride_bytes,
size_t attribute_count) override;
private:
std::vector<Vertex> vertices_;
SkinnedVerticesBuilder(const SkinnedVerticesBuilder&) = delete;
SkinnedVerticesBuilder& operator=(const SkinnedVerticesBuilder&) = delete;
};
} // namespace importer
} // namespace scene
} // namespace impeller
#endif // FLUTTER_IMPELLER_SCENE_IMPORTER_VERTICES_BUILDER_H_
| engine/impeller/scene/importer/vertices_builder.h/0 | {
"file_path": "engine/impeller/scene/importer/vertices_builder.h",
"repo_id": "engine",
"token_count": 1971
} | 255 |
// 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;
float enable_skinning;
float joint_texture_size;
}
frame_info;
uniform sampler2D joints_texture;
// This attribute layout is expected to be identical to `SkinnedVertex` within
// `impeller/scene/importer/scene.fbs`.
in vec3 position;
in vec3 normal;
in vec4 tangent;
in vec2 texture_coords;
in vec4 color;
in vec4 joints;
in vec4 weights;
out vec3 v_position;
out mat3 v_tangent_space;
out vec2 v_texture_coords;
out vec4 v_color;
const int kMatrixTexelStride = 4;
mat4 GetJoint(float joint_index) {
// The size of one texel in UV space. The joint texture should always be
// square, so the answer is the same in both dimensions.
float texel_size_uv = 1 / frame_info.joint_texture_size;
// Each joint matrix takes up 4 pixels (16 floats), so we jump 4 pixels per
// joint matrix.
float matrix_start = joint_index * kMatrixTexelStride;
// The texture space coordinates at the start of the matrix.
float x = mod(matrix_start, frame_info.joint_texture_size);
float y = floor(matrix_start / frame_info.joint_texture_size);
// Nearest sample the middle of each the texel by adding `0.5 * texel_size_uv`
// to both dimensions.
y = (y + 0.5) * texel_size_uv;
mat4 joint =
mat4(texture(joints_texture, vec2((x + 0.5) * texel_size_uv, y)),
texture(joints_texture, vec2((x + 1.5) * texel_size_uv, y)),
texture(joints_texture, vec2((x + 2.5) * texel_size_uv, y)),
texture(joints_texture, vec2((x + 3.5) * texel_size_uv, y)));
return joint;
}
void main() {
mat4 skin_matrix;
if (frame_info.enable_skinning == 1) {
skin_matrix =
GetJoint(joints.x) * weights.x + GetJoint(joints.y) * weights.y +
GetJoint(joints.z) * weights.z + GetJoint(joints.w) * weights.w;
} else {
skin_matrix = mat4(1); // Identity matrix.
}
gl_Position = frame_info.mvp * skin_matrix * vec4(position, 1.0);
v_position = gl_Position.xyz;
vec3 lh_tangent = (skin_matrix * vec4(tangent.xyz * tangent.w, 0.0)).xyz;
vec3 out_normal = (skin_matrix * vec4(normal, 0.0)).xyz;
v_tangent_space = mat3(frame_info.mvp) *
mat3(lh_tangent, cross(out_normal, lh_tangent), out_normal);
v_texture_coords = texture_coords;
v_color = color;
}
| engine/impeller/scene/shaders/skinned.vert/0 | {
"file_path": "engine/impeller/scene/shaders/skinned.vert",
"repo_id": "engine",
"token_count": 958
} | 256 |
// 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 <string>
#include "flutter/fml/mapping.h"
#include "flutter/testing/testing.h"
#include "impeller/base/validation.h"
#include "impeller/shader_archive/multi_arch_shader_archive.h"
#include "impeller/shader_archive/multi_arch_shader_archive_flatbuffers.h"
#include "impeller/shader_archive/multi_arch_shader_archive_writer.h"
#include "impeller/shader_archive/shader_archive.h"
#include "impeller/shader_archive/shader_archive_flatbuffers.h"
#include "impeller/shader_archive/shader_archive_writer.h"
namespace impeller {
namespace testing {
static std::shared_ptr<fml::Mapping> CreateMappingFromString(
std::string p_string) {
auto string = std::make_shared<std::string>(std::move(p_string));
return std::make_shared<fml::NonOwnedMapping>(
reinterpret_cast<const uint8_t*>(string->data()), string->size(),
[string](auto, auto) {});
}
const std::string CreateStringFromMapping(const fml::Mapping& mapping) {
return std::string{reinterpret_cast<const char*>(mapping.GetMapping()),
mapping.GetSize()};
}
TEST(ShaderArchiveTest, CanReadAndWriteBlobs) {
ShaderArchiveWriter writer;
ASSERT_TRUE(writer.AddShader(ArchiveShaderType::kVertex, "Hello",
CreateMappingFromString("World")));
ASSERT_TRUE(writer.AddShader(ArchiveShaderType::kFragment, "Foo",
CreateMappingFromString("Bar")));
ASSERT_TRUE(writer.AddShader(ArchiveShaderType::kVertex, "Baz",
CreateMappingFromString("Bang")));
ASSERT_TRUE(writer.AddShader(ArchiveShaderType::kVertex, "Ping",
CreateMappingFromString("Pong")));
ASSERT_TRUE(writer.AddShader(ArchiveShaderType::kFragment, "Pang",
CreateMappingFromString("World")));
auto mapping = writer.CreateMapping();
ASSERT_NE(mapping, nullptr);
MultiArchShaderArchiveWriter multi_writer;
ASSERT_TRUE(multi_writer.RegisterShaderArchive(
ArchiveRenderingBackend::kOpenGLES, mapping));
{
ScopedValidationDisable no_val;
// Can't add the same backend again.
ASSERT_FALSE(multi_writer.RegisterShaderArchive(
ArchiveRenderingBackend::kOpenGLES, mapping));
}
auto multi_mapping = multi_writer.CreateMapping();
ASSERT_TRUE(multi_mapping);
{
ScopedValidationDisable no_val;
auto no_library = MultiArchShaderArchive::CreateArchiveFromMapping(
multi_mapping, ArchiveRenderingBackend::kVulkan);
ASSERT_EQ(no_library, nullptr);
}
auto library = MultiArchShaderArchive::CreateArchiveFromMapping(
multi_mapping, ArchiveRenderingBackend::kOpenGLES);
ASSERT_EQ(library->GetShaderCount(), 5u);
// Wrong type.
ASSERT_EQ(library->GetMapping(ArchiveShaderType::kFragment, "Hello"),
nullptr);
auto hello_vtx = library->GetMapping(ArchiveShaderType::kVertex, "Hello");
ASSERT_NE(hello_vtx, nullptr);
ASSERT_EQ(CreateStringFromMapping(*hello_vtx), "World");
}
TEST(ShaderArchiveTest, ArchiveAndMultiArchiveHaveDifferentIdentifiers) {
// The unarchiving process depends on these identifiers to check to see if its
// a standalone archive or a multi-archive. Things will get nutty if these are
// ever the same.
auto archive_id = fb::ShaderArchiveIdentifier();
auto multi_archive_id = fb::MultiArchShaderArchiveIdentifier();
ASSERT_EQ(std::strlen(archive_id), std::strlen(multi_archive_id));
ASSERT_NE(std::strncmp(archive_id, multi_archive_id, std::strlen(archive_id)),
0);
}
} // namespace testing
} // namespace impeller
| engine/impeller/shader_archive/shader_archive_unittests.cc/0 | {
"file_path": "engine/impeller/shader_archive/shader_archive_unittests.cc",
"repo_id": "engine",
"token_count": 1435
} | 257 |
// 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_TOOLKIT_ANDROID_CHOREOGRAPHER_H_
#define FLUTTER_IMPELLER_TOOLKIT_ANDROID_CHOREOGRAPHER_H_
#include "impeller/toolkit/android/proc_table.h"
#include <chrono>
#include <memory>
namespace impeller::android {
//------------------------------------------------------------------------------
/// @brief This class describes access to the choreographer instance for
/// the current thread. Choreographers are only available on API
/// levels above 24. On levels below 24, an invalid choreographer
/// will be returned.
///
/// Since choreographer need an event loop on the current thread,
/// one will be setup if it doesn't already exist.
///
class Choreographer {
public:
static bool IsAvailableOnPlatform();
//----------------------------------------------------------------------------
/// @brief Create or get the thread local instance of a choreographer. A
/// message loop will be setup on the calling thread if none
/// exists.
///
/// @warning Choreographers are only available on API levels 24 and above.
/// Below this level, this will return an invalid instance.
/// Availability can also be checked via the
/// `IsAvailableOnPlatform` call.
///
/// @return The thread local choreographer instance. If none can be setup,
/// an invalid object reference will be returned. See `IsValid`.
///
static Choreographer& GetInstance();
~Choreographer();
Choreographer(const Choreographer&) = delete;
Choreographer& operator=(const Choreographer&) = delete;
bool IsValid() const;
//----------------------------------------------------------------------------
/// A monotonic system clock.
///
using FrameClock = std::chrono::steady_clock;
//----------------------------------------------------------------------------
/// A timepoint on a monotonic system clock.
///
using FrameTimePoint = std::chrono::time_point<FrameClock>;
using FrameCallback = std::function<void(FrameTimePoint)>;
//----------------------------------------------------------------------------
/// @brief Posts a frame callback. The time that the frame is being
/// rendered will be available in the callback as an argument.
/// Multiple frame callbacks within the same frame interval will
/// receive the same argument.
///
/// @param[in] callback The callback
///
/// @return `true` if the frame callback could be posted. This may return
/// `false` if choreographers are not available on the platform.
/// See `IsAvailableOnPlatform`.
///
bool PostFrameCallback(FrameCallback callback) const;
private:
AChoreographer* instance_ = nullptr;
explicit Choreographer();
};
} // namespace impeller::android
#endif // FLUTTER_IMPELLER_TOOLKIT_ANDROID_CHOREOGRAPHER_H_
| engine/impeller/toolkit/android/choreographer.h/0 | {
"file_path": "engine/impeller/toolkit/android/choreographer.h",
"repo_id": "engine",
"token_count": 965
} | 258 |
// 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_TOOLKIT_EGL_CONTEXT_H_
#define FLUTTER_IMPELLER_TOOLKIT_EGL_CONTEXT_H_
#include <functional>
#include "flutter/fml/macros.h"
#include "impeller/base/comparable.h"
#include "impeller/base/thread.h"
#include "impeller/toolkit/egl/egl.h"
namespace impeller {
namespace egl {
class Surface;
class Context {
public:
Context(EGLDisplay display, EGLContext context);
~Context();
bool IsValid() const;
const EGLContext& GetHandle() const;
bool MakeCurrent(const Surface& surface) const;
bool ClearCurrent() const;
enum class LifecycleEvent {
kDidMakeCurrent,
kWillClearCurrent,
};
using LifecycleListener = std::function<void(LifecycleEvent)>;
std::optional<UniqueID> AddLifecycleListener(
const LifecycleListener& listener);
bool RemoveLifecycleListener(UniqueID id);
private:
EGLDisplay display_ = EGL_NO_DISPLAY;
EGLContext context_ = EGL_NO_CONTEXT;
mutable RWMutex listeners_mutex_;
std::map<UniqueID, LifecycleListener> listeners_ IPLR_GUARDED_BY(
listeners_mutex_);
void DispatchLifecyleEvent(LifecycleEvent event) const;
Context(const Context&) = delete;
Context& operator=(const Context&) = delete;
};
} // namespace egl
} // namespace impeller
#endif // FLUTTER_IMPELLER_TOOLKIT_EGL_CONTEXT_H_
| engine/impeller/toolkit/egl/context.h/0 | {
"file_path": "engine/impeller/toolkit/egl/context.h",
"repo_id": "engine",
"token_count": 512
} | 259 |
# 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/impeller/tools/malioc.gni")
import("//flutter/testing/testing.gni")
declare_args() {
impeller_debug =
flutter_runtime_mode == "debug" || flutter_runtime_mode == "profile"
# Whether the runtime capture/playback system is enabled.
impeller_capture = flutter_runtime_mode == "debug"
# Whether the Metal backend is enabled.
impeller_enable_metal = (is_mac || is_ios) && target_os != "fuchsia"
# Whether the OpenGLES backend is enabled.
impeller_enable_opengles = (is_linux || is_win || is_android || is_mac ||
enable_unittests) && target_os != "fuchsia"
# Whether the Vulkan backend is enabled.
impeller_enable_vulkan = (is_linux || is_win || is_android || is_mac ||
enable_unittests) && target_os != "fuchsia"
# Whether to use a prebuilt impellerc.
# If this is the empty string, impellerc will be built.
# If it is non-empty, it should be the absolute path to impellerc.
impeller_use_prebuilt_impellerc = ""
# Whether to use a prebuilt scenec.
# If this is the empty string, scenec will be built.
# If it is non-empty, it should be the absolute path to scenec.
impeller_use_prebuilt_scenec = ""
# If enabled, all OpenGL calls will be traced. Because additional trace
# overhead may be substantial, this is not enabled by default.
impeller_trace_all_gl_calls = false
# Enable experimental 3D scene rendering.
impeller_enable_3d = false
# Enable to get trace statements for canvas usage.
impeller_trace_canvas = false
}
declare_args() {
# Wether to build and include the validation layers.
impeller_enable_vulkan_validation_layers =
impeller_enable_vulkan && flutter_runtime_mode == "debug" &&
target_cpu == "arm64"
# Whether Impeller supports rendering on the platform.
impeller_supports_rendering =
impeller_enable_metal || impeller_enable_opengles ||
impeller_enable_vulkan
impeller_enable_compute = impeller_enable_vulkan || impeller_enable_metal
}
# ------------------------------------------------------------------------------
# @brief Define an Impeller component. Components are different
# Impeller subsystems part of the umbrella framework.
#
# @param[optional] target_type The type of the component. This can be any of
# the target types supported by GN. Defaults to
# source_set. If Impeller is not supported on the
# target platform, this target is a no-op.
#
template("impeller_component") {
if (defined(invoker.testonly) && invoker.testonly && !enable_unittests) {
group(target_name) {
not_needed(invoker, "*")
}
} else {
target_type = "source_set"
if (defined(invoker.target_type)) {
target_type = invoker.target_type
}
target(target_type, target_name) {
forward_variables_from(invoker, "*")
if (!defined(invoker.public_configs)) {
public_configs = []
}
public_configs += [ "//flutter/impeller:impeller_public_config" ]
if (!defined(invoker.cflags)) {
cflags = []
}
cflags += [ "-Wthread-safety-analysis" ]
if (!defined(invoker.cflags_objc)) {
cflags_objc = []
}
if (is_ios || is_mac) {
cflags_objc += flutter_cflags_objc_arc
}
if (!defined(invoker.cflags_objcc)) {
cflags_objcc = []
}
if (is_ios || is_mac) {
cflags_objcc += flutter_cflags_objcc_arc
}
}
}
}
# ------------------------------------------------------------------------------
# @brief Build a Metal Library. The output is a single file. Use
# get_target_outputs to get its location on build.
#
# @param[required] name The name of the Metal library.
#
# @param[required] sources The GLSL (4.60) sources to compiled into the Metal
# library.
#
# @param[required] metal_version The Metal language version to compile for.
#
template("metal_library") {
assert(is_ios || is_mac)
assert(defined(invoker.name), "Metal library name must be specified.")
assert(defined(invoker.sources), "Metal source files must be specified.")
assert(defined(invoker.metal_version),
"Metal language version must be specified.")
metal_library_name = invoker.name
action("$target_name") {
forward_variables_from(invoker,
"*",
[
"inputs",
"outputs",
"script",
"depfile",
"args",
])
inputs = invoker.sources
metal_library_path = "$root_out_dir/shaders/$metal_library_name.metallib"
metal_library_symbols_path =
"$root_out_dir/shaders/$metal_library_name.metallibsym"
outputs = [
metal_library_path,
metal_library_symbols_path,
]
script = "//flutter/impeller/tools/build_metal_library.py"
depfile = "$target_gen_dir/mtl/$metal_library_name.depfile"
args = [
"--output",
rebase_path(metal_library_path, root_out_dir),
"--depfile",
rebase_path(depfile),
"--metal-version=$metal_version",
]
if (is_ios) {
if (use_ios_simulator) {
args += [ "--platform=ios-simulator" ]
} else {
args += [ "--platform=ios" ]
}
} else if (is_mac) {
args += [ "--platform=mac" ]
} else {
assert(false, "Unsupported platform for generating Metal shaders.")
}
foreach(source, invoker.sources) {
args += [
"--source",
rebase_path(source, root_out_dir),
]
}
}
}
template("embed_blob") {
assert(defined(invoker.symbol_name), "The symbol name must be specified.")
assert(defined(invoker.blob), "The blob file to embed must be specified")
assert(defined(invoker.hdr),
"The header file containing the symbol name must be specified.")
assert(defined(invoker.cc),
"The CC file containing the symbol data must be specified.")
assert(defined(invoker.deps), "The target dependencies must be specified")
gen_blob_target_name = "gen_blob_$target_name"
action(gen_blob_target_name) {
inputs = [ invoker.blob ]
outputs = [
invoker.hdr,
invoker.cc,
]
args = [
"--symbol-name",
invoker.symbol_name,
"--output-header",
rebase_path(invoker.hdr),
"--output-source",
rebase_path(invoker.cc),
"--source",
rebase_path(invoker.blob),
]
script = "//flutter/impeller/tools/xxd.py"
deps = invoker.deps
}
embed_config = "embed_$target_name"
config(embed_config) {
include_dirs = [ get_path_info(
get_label_info("//flutter/impeller:impeller", "target_gen_dir"),
"dir") ]
}
source_set(target_name) {
public_configs = [ ":$embed_config" ]
sources = get_target_outputs(":$gen_blob_target_name")
deps = [ ":$gen_blob_target_name" ]
}
}
# Dispatches to the build or prebuilt impellerc depending on the value of
# the `impeller_use_prebuilt_impellerc` argument.
# * When the `single_invocation` argument is false, all variables are
# forwarded to `compiled_action_foreach` or `action_foreach`, which will
# invoke `impellerc` separately for each source.
# * When the `single_invocation` argument is true, `impellerc` is only
# invoked once via `compiled_action` or `action`.
template("_impellerc") {
if (invoker.single_invocation) {
if (impeller_use_prebuilt_impellerc == "") {
compiled_action(target_name) {
forward_variables_from(invoker, "*")
tool = "//flutter/impeller/compiler:impellerc"
}
} else {
action(target_name) {
forward_variables_from(invoker, "*", [ "args" ])
script = "//build/gn_run_binary.py"
impellerc_path =
rebase_path(impeller_use_prebuilt_impellerc, root_build_dir)
args = [ impellerc_path ] + invoker.args
}
}
} else {
if (impeller_use_prebuilt_impellerc == "") {
compiled_action_foreach(target_name) {
forward_variables_from(invoker, "*")
tool = "//flutter/impeller/compiler:impellerc"
}
} else {
action_foreach(target_name) {
forward_variables_from(invoker, "*", [ "args" ])
script = "//build/gn_run_binary.py"
impellerc_path =
rebase_path(impeller_use_prebuilt_impellerc, root_build_dir)
args = [ impellerc_path ] + invoker.args
}
}
}
}
# Required: shaders The list of shaders inputs to compile.
# Required: shader_target_flags The target flag(s) to append. Valid options:
# --sksl
# --metal-ios
# --metal-desktop
# --opengl-es
# --opengl-desktop
# --vulkan
# --runtime-stage-metal
# --runtime-stage-gles
# --runtime-stage-vulkan
# Not required for --shader_bundle mode.
# Required: sl_file_extension The file extension to use for output files.
# Not required for --shader_bundle mode.
# Optional: iplr Causes --sl output to be in iplr/runtime
# stage flatbuffer format.
# Optional: shader_bundle Specifies a Flutter GPU shader bundle
# configuration.
# Required: shader_bundle_output Specifies the output filename of the shader
# bundle. This is only required if
# shader_bundle is supplied.
# Optional: defines Specifies a list of valueless macro
# definitions.
# Optional: intermediates_subdir Specifies the subdirectory in which to put
# intermediates.
# Optional: json Causes output format to be JSON instead of
# flatbuffer.
template("impellerc") {
assert(defined(invoker.shaders), "Impeller shaders must be specified.")
assert(defined(invoker.shader_target_flags) || defined(invoker.shader_bundle),
"The flag to impellerc for target selection must be specified.")
assert(defined(invoker.sl_file_extension) || defined(invoker.shader_bundle),
"The extension of the SL file must be specified (metal, glsl, etc..).")
if (defined(invoker.shader_bundle)) {
assert(
defined(invoker.shader_bundle_output),
"When shader_bundle is specified, shader_bundle_output must also be specified.")
}
if (defined(invoker.shader_target_flags)) {
shader_target_flags = invoker.shader_target_flags
} else {
shader_target_flags = []
}
sksl = false
foreach(shader_target_flag, shader_target_flags) {
sksl = shader_target_flag == "--sksl"
}
iplr = false
if (defined(invoker.iplr) && invoker.iplr) {
iplr = invoker.iplr
}
json = false
if (defined(invoker.json) && invoker.json) {
json = invoker.json
}
# Not needed on every path.
not_needed([
"iplr",
"sksl",
"shader_bundle",
"shader_bundle_output",
])
_impellerc(target_name) {
shader_bundle = defined(invoker.shader_bundle)
# When single_invocation is true, impellerc will be invoked exactly once. When it's
# false, impellerc be invoked for each of the source file entries (invoker.shaders).
single_invocation = shader_bundle
if (defined(invoker.intermediates_subdir)) {
subdir = invoker.intermediates_subdir
generated_dir = "$target_gen_dir/$subdir"
} else {
generated_dir = "$target_gen_dir"
}
shader_lib_dir = rebase_path("//flutter/impeller/compiler/shader_lib")
args = [ "--include=$shader_lib_dir" ] + shader_target_flags
# When we're in single invocation mode, we can't use source enumeration.
if (!single_invocation) {
depfile_path = "$generated_dir/{{source_file_part}}.d"
depfile_intermediate_path = rebase_path(depfile_path, root_build_dir)
depfile = depfile_path
args += [
"--input={{source}}",
"--include={{source_dir}}",
"--depfile=$depfile_intermediate_path",
]
if (defined(invoker.shader_target_flag)) {
args += [ "${invoker.shader_target_flag}" ]
}
}
if (defined(invoker.gles_language_version)) {
gles_language_version = invoker.gles_language_version
args += [ "--gles-language-version=$gles_language_version" ]
}
if (defined(invoker.metal_version)) {
assert(is_mac || is_ios)
metal_version = invoker.metal_version
args += [ "--metal-version=$metal_version" ]
}
if (defined(invoker.use_half_textures) && invoker.use_half_textures) {
args += [ "--use-half-textures" ]
}
if (defined(invoker.require_framebuffer_fetch) &&
invoker.require_framebuffer_fetch) {
args += [ "--require-framebuffer-fetch" ]
}
if (json) {
args += [ "--json" ]
}
if (iplr) {
# When building in IPLR mode, the compiler may be executed twice
args += [ "--iplr" ]
}
# The `sl_output` is the raw shader file output by the compiler. For --iplr
# and --shader-bundle, this is used as the filename for the flatbuffer to
# output.
if (shader_bundle) {
# When a shader bundle is specified, don't bother supplying flags for
# the reflection state as these are ignored. In this mode, the compiler
# is invoked multiple times and the reflection state for each shader is
# written to the output flatbuffer.
sl_output = "$generated_dir/${invoker.shader_bundle_output}"
sl_output_path = rebase_path(sl_output, root_build_dir)
args += [
"--sl=$sl_output_path",
"--shader-bundle=${invoker.shader_bundle}",
]
outputs = [ sl_output ]
} else if (sksl) {
# When SkSL is selected as a `shader_target_flags`, don't generate
# C++ reflection state. Nothing needs to use it and it's likely invalid
# given the special cases when generating SkSL.
# Note that this configuration is orthogonal to the "--iplr" flag
sl_output =
"$generated_dir/{{source_file_part}}.${invoker.sl_file_extension}"
sl_output_path = rebase_path(sl_output, root_build_dir)
spirv_intermediate = "$generated_dir/{{source_file_part}}.spirv"
spirv_intermediate_path = rebase_path(spirv_intermediate, root_build_dir)
args += [
"--sl=$sl_output_path",
"--spirv=$spirv_intermediate_path",
]
outputs = [ sl_output ]
} else {
# The default branch. Here we just generate one shader along with all of
# its C++ reflection state.
sl_output =
"$generated_dir/{{source_file_part}}.${invoker.sl_file_extension}"
sl_output_path = rebase_path(sl_output, root_build_dir)
reflection_json_intermediate = "$generated_dir/{{source_file_part}}.json"
reflection_header_intermediate = "$generated_dir/{{source_file_part}}.h"
reflection_cc_intermediate = "$generated_dir/{{source_file_part}}.cc"
spirv_intermediate = "$generated_dir/{{source_file_part}}.spirv"
spirv_intermediate_path = rebase_path(spirv_intermediate, root_build_dir)
reflection_json_path =
rebase_path(reflection_json_intermediate, root_build_dir)
reflection_header_path =
rebase_path(reflection_header_intermediate, root_build_dir)
reflection_cc_path =
rebase_path(reflection_cc_intermediate, root_build_dir)
args += [
"--sl=$sl_output_path",
"--spirv=$spirv_intermediate_path",
"--reflection-json=$reflection_json_path",
"--reflection-header=$reflection_header_path",
"--reflection-cc=$reflection_cc_path",
]
outputs = [
sl_output,
reflection_header_intermediate,
reflection_cc_intermediate,
]
}
if (defined(invoker.defines)) {
foreach(def, invoker.defines) {
args += [ "--define=$def" ]
}
}
if (single_invocation) {
inputs = invoker.shaders
} else {
sources = invoker.shaders
}
}
}
template("impellerc_reflect") {
assert(
defined(invoker.impellerc_invocation),
"The target that specifies the ImpellerC invocation to reflect must be defined.")
reflect_config = "reflect_$target_name"
config(reflect_config) {
include_dirs = [ get_path_info(
get_label_info("//flutter/impeller:impeller", "target_gen_dir"),
"dir") ]
}
impellerc_invocation = invoker.impellerc_invocation
source_set(target_name) {
public_configs = [ ":$reflect_config" ]
public = filter_include(get_target_outputs(impellerc_invocation), [ "*.h" ])
sources = filter_include(get_target_outputs(impellerc_invocation),
[
"*.h",
"*.cc",
"*.mm",
])
deps = [
"//flutter/impeller/core",
impellerc_invocation,
]
}
}
template("_impeller_shaders_metal") {
assert(defined(invoker.shaders), "Impeller shaders must be specified.")
assert(defined(invoker.name), "Name of the shader library must be specified.")
metal_version = "1.2"
if (defined(invoker.metal_version)) {
metal_version = invoker.metal_version
}
use_half_textures = false
if (defined(invoker.use_half_textures) && invoker.use_half_textures) {
use_half_textures = invoker.use_half_textures
}
shaders_base_name = string_join("",
[
invoker.name,
"_shaders",
])
impellerc_mtl = "impellerc_$target_name"
impellerc(impellerc_mtl) {
shaders = invoker.shaders
metal_version = metal_version
sl_file_extension = "metal"
use_half_textures = use_half_textures
shader_target_flags = []
defines = [ "IMPELLER_TARGET_METAL" ]
if (is_ios) {
shader_target_flags += [ "--metal-ios" ]
defines += [ "IMPELLER_TARGET_METAL_IOS" ]
} else if (is_mac) {
shader_target_flags = [ "--metal-desktop" ]
defines += [ "IMPELLER_TARGET_METAL_DESKTOP" ]
} else {
assert(false, "Metal not supported on this platform.")
}
}
mtl_lib = "genlib_$target_name"
metal_library(mtl_lib) {
name = invoker.name
metal_version = metal_version
sources =
filter_include(get_target_outputs(":$impellerc_mtl"), [ "*.metal" ])
deps = [ ":$impellerc_mtl" ]
}
reflect_mtl = "reflect_$target_name"
impellerc_reflect(reflect_mtl) {
impellerc_invocation = ":$impellerc_mtl"
}
embed_mtl_lib = "embed_$target_name"
embed_blob(embed_mtl_lib) {
metal_library_files = get_target_outputs(":$mtl_lib")
symbol_name = shaders_base_name
blob = metal_library_files[0]
hdr = "$target_gen_dir/mtl/$shaders_base_name.h"
cc = "$target_gen_dir/mtl/$shaders_base_name.cc"
deps = [ ":$mtl_lib" ]
}
group(target_name) {
public_deps = [
":$embed_mtl_lib",
":$reflect_mtl",
]
}
}
template("shader_archive") {
assert(defined(invoker.shaders),
"The shaders to build the library from must be specified.")
assert(defined(invoker.deps), "Target dependencies must be specified.")
output_file = "$target_gen_dir/$target_name.shar"
compiled_action(target_name) {
tool = "//flutter/impeller/shader_archive:shader_archiver"
inputs = invoker.shaders
outputs = [ output_file ]
output_path_rebased = rebase_path(output_file, root_build_dir)
args = [ "--output=$output_path_rebased" ]
foreach(shader, invoker.shaders) {
shader_path = rebase_path(shader, root_build_dir)
args += [ "--input=$shader_path" ]
}
deps = invoker.deps
}
}
template("_impeller_shaders_gles") {
assert(defined(invoker.shaders), "Impeller shaders must be specified.")
assert(defined(invoker.name), "Name of the shader library must be specified.")
assert(defined(invoker.analyze), "Whether to analyze must be specified.")
require_framebuffer_fetch = false
if (defined(invoker.require_framebuffer_fetch) &&
invoker.require_framebuffer_fetch) {
require_framebuffer_fetch = invoker.require_framebuffer_fetch
}
shaders_base_name = string_join("",
[
invoker.name,
"_shaders_gles",
])
impellerc_gles = "impellerc_$target_name"
impellerc(impellerc_gles) {
shaders = invoker.shaders
sl_file_extension = "gles"
require_framebuffer_fetch = require_framebuffer_fetch
if (defined(invoker.gles_language_version)) {
gles_language_version = invoker.gles_language_version
}
# Metal reflectors generate a superset of information.
if (impeller_enable_metal || impeller_enable_vulkan) {
intermediates_subdir = "gles"
}
shader_target_flags = [ "--opengl-es" ]
defines = [ "IMPELLER_TARGET_OPENGLES" ]
}
gles_shaders =
filter_include(get_target_outputs(":$impellerc_gles"), [ "*.gles" ])
if (invoker.analyze) {
analyze_lib = "analyze_$target_name"
malioc_analyze_shaders(analyze_lib) {
shaders = gles_shaders
if (defined(invoker.gles_language_version)) {
gles_language_version = invoker.gles_language_version
}
deps = [ ":$impellerc_gles" ]
}
}
gles_lib = "genlib_$target_name"
shader_archive(gles_lib) {
shaders = gles_shaders
deps = [ ":$impellerc_gles" ]
}
reflect_gles = "reflect_$target_name"
impellerc_reflect(reflect_gles) {
impellerc_invocation = ":$impellerc_gles"
}
embed_gles_lib = "embed_$target_name"
embed_blob(embed_gles_lib) {
gles_library_files = get_target_outputs(":$gles_lib")
symbol_name = shaders_base_name
blob = gles_library_files[0]
hdr = "$target_gen_dir/gles/$shaders_base_name.h"
cc = "$target_gen_dir/gles/$shaders_base_name.cc"
deps = [ ":$gles_lib" ]
}
group(target_name) {
public_deps = [ ":$embed_gles_lib" ]
if (invoker.analyze) {
public_deps += [ ":$analyze_lib" ]
}
if (!impeller_enable_metal && !impeller_enable_vulkan) {
public_deps += [ ":$reflect_gles" ]
}
}
}
template("_impeller_shaders_vk") {
assert(defined(invoker.shaders), "Impeller shaders must be specified.")
assert(defined(invoker.name), "Name of the shader library must be specified.")
assert(defined(invoker.analyze), "Whether to analyze must be specified.")
shaders_base_name = string_join("",
[
invoker.name,
"_shaders_vk",
])
impellerc_vk = "impellerc_$target_name"
impellerc(impellerc_vk) {
shaders = invoker.shaders
sl_file_extension = "vkspv"
# Metal reflectors generate a superset of information.
if (impeller_enable_metal) {
if (defined(invoker.metal_version)) {
metal_version = invoker.metal_version
}
intermediates_subdir = "vk"
}
shader_target_flags = [ "--vulkan" ]
defines = [ "IMPELLER_TARGET_VULKAN" ]
}
vk_shaders =
filter_include(get_target_outputs(":$impellerc_vk"), [ "*.vkspv" ])
if (invoker.analyze) {
analyze_lib = "analyze_$target_name"
malioc_analyze_shaders(analyze_lib) {
shaders = vk_shaders
if (defined(invoker.vulkan_language_version)) {
vulkan_language_version = invoker.vulkan_language_version
}
deps = [ ":$impellerc_vk" ]
}
}
vk_lib = "genlib_$target_name"
shader_archive(vk_lib) {
shaders = vk_shaders
deps = [ ":$impellerc_vk" ]
}
reflect_vk = "reflect_$target_name"
impellerc_reflect(reflect_vk) {
impellerc_invocation = ":$impellerc_vk"
}
embed_vk_lib = "embed_$target_name"
embed_blob(embed_vk_lib) {
vk_library_files = get_target_outputs(":$vk_lib")
symbol_name = shaders_base_name
blob = vk_library_files[0]
hdr = "$target_gen_dir/vk/$shaders_base_name.h"
cc = "$target_gen_dir/vk/$shaders_base_name.cc"
deps = [ ":$vk_lib" ]
}
group(target_name) {
public_deps = [ ":$embed_vk_lib" ]
if (invoker.analyze) {
public_deps += [ ":$analyze_lib" ]
}
if (!impeller_enable_metal) {
public_deps += [ ":$reflect_vk" ]
}
}
}
# ------------------------------------------------------------------------------
# @brief A target for precompiled shaders and the associated
# generated reflection library.
#
# @param[required] name
#
# The base name for the reflected C++ library.
#
# @param[required] shaders
#
# A list of GLSL shader files.
#
# @param[optional] analyze
#
# Whether to analyze shaders with malioc. Defaults to false. Shaders will
# only be analyzed if the GN argument "impeller_malioc_path" is defined.
#
# @param[optional] enable_opengles
#
# Whether to compile the shaders for the OpenGL ES backend. Defaults to the
# value of the GN argument "impeller_enable_opengles".
#
# @param[optional] gles_language_version
#
# The GLES version required by the shaders.
#
# @param[optional] metal_version
#
# The version of the Metal API required by the shaders.
#
# @param[optional] vulkan_language_version
#
# The SPIR-V version required by the shaders.
#
# @param[optional] use_half_textures
#
# Whether the metal shader is using half-precision textures and requires
# openGL semantics when compilig SPIR-V.
#
# @param[optional] require_framebuffer_fetch
#
# Whether to require the framebuffer fetch extension for GLES fragment shaders.
template("impeller_shaders") {
if (defined(invoker.metal_version)) {
metal_version = invoker.metal_version
}
use_half_textures = false
if (defined(invoker.use_half_textures) && invoker.use_half_textures) {
use_half_textures = true
}
require_framebuffer_fetch = false
if (defined(invoker.require_framebuffer_fetch) &&
invoker.require_framebuffer_fetch) {
require_framebuffer_fetch = true
}
not_needed([
"metal_version",
"use_half_textures",
"require_framebuffer_fetch",
])
enable_opengles = impeller_enable_opengles
if (defined(invoker.enable_opengles)) {
enable_opengles = invoker.enable_opengles
}
if (impeller_enable_metal) {
if (!defined(metal_version)) {
metal_version = "1.2"
}
not_needed(invoker, [ "analyze" ])
mtl_shaders = "mtl_$target_name"
_impeller_shaders_metal(mtl_shaders) {
name = invoker.name
shaders = invoker.shaders
metal_version = metal_version
use_half_textures = use_half_textures
}
}
if (enable_opengles) {
analyze = true
if (defined(invoker.analyze) && !invoker.analyze) {
analyze = false
}
gles_shaders = "gles_$target_name"
_impeller_shaders_gles(gles_shaders) {
name = invoker.name
require_framebuffer_fetch = require_framebuffer_fetch
if (defined(invoker.gles_language_version)) {
gles_language_version = invoker.gles_language_version
}
if (defined(invoker.gles_exclusions)) {
shaders = invoker.shaders - invoker.gles_exclusions
} else {
shaders = invoker.shaders
}
analyze = analyze
}
}
if (impeller_enable_vulkan) {
analyze = true
if (defined(invoker.analyze) && !invoker.analyze) {
analyze = false
}
vk_shaders = "vk_$target_name"
_impeller_shaders_vk(vk_shaders) {
name = invoker.name
if (defined(invoker.vulkan_language_version)) {
vulkan_language_version = invoker.vulkan_language_version
}
shaders = invoker.shaders
analyze = analyze
}
}
if (!impeller_supports_rendering) {
not_needed(invoker, "*")
}
group(target_name) {
public_deps = []
if (impeller_enable_metal) {
public_deps += [ ":$mtl_shaders" ]
}
if (enable_opengles) {
public_deps += [ ":$gles_shaders" ]
}
if (impeller_enable_vulkan) {
public_deps += [ ":$vk_shaders" ]
}
}
}
# Dispatches to the build or prebuilt scenec depending on the value of
# the impeller_use_prebuilt_scenec argument. Forwards all variables to
# compiled_action_foreach or action_foreach as appropriate.
template("_scenec") {
if (impeller_use_prebuilt_scenec == "") {
compiled_action_foreach(target_name) {
forward_variables_from(invoker, "*")
tool = "//flutter/impeller/scene/importer:scenec"
}
} else {
action_foreach(target_name) {
forward_variables_from(invoker, "*", [ "args" ])
script = "//build/gn_run_binary.py"
scenec_path = rebase_path(impeller_use_prebuilt_scenec, root_build_dir)
args = [ scenec_path ] + invoker.args
}
}
}
template("scenec") {
assert(defined(invoker.geometry), "Geometry input files must be specified.")
assert(defined(invoker.type),
"The type of geometry to be parsed (gltf, etc..).")
_scenec(target_name) {
sources = invoker.geometry
generated_dir = "$target_gen_dir"
input_type = invoker.type
args = [
"--input={{source}}",
"--input-type=$input_type",
]
output = "$generated_dir/{{source_file_part}}.ipscene"
output_path = rebase_path(output, root_build_dir)
args += [ "--output=$output_path" ]
outputs = [ output ]
}
}
| engine/impeller/tools/impeller.gni/0 | {
"file_path": "engine/impeller/tools/impeller.gni",
"repo_id": "engine",
"token_count": 13178
} | 260 |
# 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("//flutter/impeller/tools/impeller.gni")
impeller_component("typographer_stb_backend") {
testonly = true
sources = [
"glyph_atlas_context_stb.cc",
"glyph_atlas_context_stb.h",
"text_frame_stb.cc",
"text_frame_stb.h",
"typeface_stb.cc",
"typeface_stb.h",
"typographer_context_stb.cc",
"typographer_context_stb.h",
]
public_deps = [
"//flutter/impeller/typographer",
"//flutter/third_party/stb:stb_truetype",
]
}
| engine/impeller/typographer/backends/stb/BUILD.gn/0 | {
"file_path": "engine/impeller/typographer/backends/stb/BUILD.gn",
"repo_id": "engine",
"token_count": 267
} | 261 |
// 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_TYPOGRAPHER_GLYPH_ATLAS_H_
#define FLUTTER_IMPELLER_TYPOGRAPHER_GLYPH_ATLAS_H_
#include <functional>
#include <memory>
#include <optional>
#include <unordered_map>
#include "impeller/core/texture.h"
#include "impeller/geometry/rect.h"
#include "impeller/renderer/pipeline.h"
#include "impeller/typographer/font_glyph_pair.h"
#include "impeller/typographer/rectangle_packer.h"
namespace impeller {
class FontGlyphAtlas;
//------------------------------------------------------------------------------
/// @brief A texture containing the bitmap representation of glyphs in
/// different fonts along with the ability to query the location of
/// specific font glyphs within the texture.
///
class GlyphAtlas {
public:
//----------------------------------------------------------------------------
/// @brief Describes how the glyphs are represented in the texture.
enum class Type {
//--------------------------------------------------------------------------
/// The glyphs are reprsented at their requested size using only an 8-bit
/// color channel.
///
/// This might be backed by a grey or red single channel texture, depending
/// on the backend capabilities.
kAlphaBitmap,
//--------------------------------------------------------------------------
/// The glyphs are reprsented at their requested size using N32 premul
/// colors.
///
kColorBitmap,
};
//----------------------------------------------------------------------------
/// @brief Create an empty glyph atlas.
///
/// @param[in] type How the glyphs are represented in the texture.
///
explicit GlyphAtlas(Type type);
~GlyphAtlas();
bool IsValid() const;
//----------------------------------------------------------------------------
/// @brief Describes how the glyphs are represented in the texture.
///
Type GetType() const;
//----------------------------------------------------------------------------
/// @brief Set the texture for the glyph atlas.
///
/// @param[in] texture The texture
///
void SetTexture(std::shared_ptr<Texture> texture);
//----------------------------------------------------------------------------
/// @brief Get the texture for the glyph atlas.
///
/// @return The texture.
///
const std::shared_ptr<Texture>& GetTexture() const;
//----------------------------------------------------------------------------
/// @brief Record the location of a specific font-glyph pair within the
/// atlas.
///
/// @param[in] pair The font-glyph pair
/// @param[in] rect The rectangle
///
void AddTypefaceGlyphPosition(const FontGlyphPair& pair, Rect rect);
//----------------------------------------------------------------------------
/// @brief Get the number of unique font-glyph pairs in this atlas.
///
/// @return The glyph count.
///
size_t GetGlyphCount() const;
//----------------------------------------------------------------------------
/// @brief Iterate of all the glyphs along with their locations in the
/// atlas.
///
/// @param[in] iterator The iterator. Return `false` from the iterator to
/// stop iterating.
///
/// @return The number of glyphs iterated over.
///
size_t IterateGlyphs(
const std::function<bool(const ScaledFont& scaled_font,
const Glyph& glyph,
const Rect& rect)>& iterator) const;
//----------------------------------------------------------------------------
/// @brief Find the location of a specific font-glyph pair in the atlas.
///
/// @param[in] pair The font-glyph pair
///
/// @return The location of the font-glyph pair in the atlas.
/// `std::nullopt` if the pair is not in the atlas.
///
std::optional<Rect> FindFontGlyphBounds(const FontGlyphPair& pair) const;
//----------------------------------------------------------------------------
/// @brief Obtain an interface for querying the location of glyphs in the
/// atlas for the given font and scale. This provides a more
/// efficient way to look up a run of glyphs in the same font.
///
/// @param[in] font The font
/// @param[in] scale The scale
///
/// @return A pointer to a FontGlyphAtlas, or nullptr if the font and
/// scale are not available in the atlas. The pointer is only
/// valid for the lifetime of the GlyphAtlas.
///
const FontGlyphAtlas* GetFontGlyphAtlas(const Font& font, Scalar scale) const;
private:
const Type type_;
std::shared_ptr<Texture> texture_;
std::unordered_map<ScaledFont, FontGlyphAtlas> font_atlas_map_;
GlyphAtlas(const GlyphAtlas&) = delete;
GlyphAtlas& operator=(const GlyphAtlas&) = delete;
};
//------------------------------------------------------------------------------
/// @brief A container for caching a glyph atlas across frames.
///
class GlyphAtlasContext {
public:
virtual ~GlyphAtlasContext();
//----------------------------------------------------------------------------
/// @brief Retrieve the current glyph atlas.
std::shared_ptr<GlyphAtlas> GetGlyphAtlas() const;
//----------------------------------------------------------------------------
/// @brief Retrieve the size of the current glyph atlas.
const ISize& GetAtlasSize() const;
//----------------------------------------------------------------------------
/// @brief Retrieve the previous (if any) rect packer.
std::shared_ptr<RectanglePacker> GetRectPacker() const;
//----------------------------------------------------------------------------
/// @brief Update the context with a newly constructed glyph atlas.
void UpdateGlyphAtlas(std::shared_ptr<GlyphAtlas> atlas, ISize size);
void UpdateRectPacker(std::shared_ptr<RectanglePacker> rect_packer);
protected:
GlyphAtlasContext();
private:
std::shared_ptr<GlyphAtlas> atlas_;
ISize atlas_size_;
std::shared_ptr<RectanglePacker> rect_packer_;
GlyphAtlasContext(const GlyphAtlasContext&) = delete;
GlyphAtlasContext& operator=(const GlyphAtlasContext&) = delete;
};
//------------------------------------------------------------------------------
/// @brief An object that can look up glyph locations within the GlyphAtlas
/// for a particular typeface.
///
class FontGlyphAtlas {
public:
FontGlyphAtlas() = default;
//----------------------------------------------------------------------------
/// @brief Find the location of a glyph in the atlas.
///
/// @param[in] glyph The glyph
///
/// @return The location of the glyph in the atlas.
/// `std::nullopt` if the glyph is not in the atlas.
///
std::optional<Rect> FindGlyphBounds(const Glyph& glyph) const;
private:
friend class GlyphAtlas;
std::unordered_map<Glyph, Rect> positions_;
FontGlyphAtlas(const FontGlyphAtlas&) = delete;
FontGlyphAtlas& operator=(const FontGlyphAtlas&) = delete;
};
} // namespace impeller
#endif // FLUTTER_IMPELLER_TYPOGRAPHER_GLYPH_ATLAS_H_
| engine/impeller/typographer/glyph_atlas.h/0 | {
"file_path": "engine/impeller/typographer/glyph_atlas.h",
"repo_id": "engine",
"token_count": 2269
} | 262 |
// 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/lib/gpu/command_buffer.h"
#include "dart_api.h"
#include "fml/make_copyable.h"
#include "impeller/renderer/command_buffer.h"
#include "impeller/renderer/render_pass.h"
#include "lib/ui/ui_dart_state.h"
#include "tonic/converter/dart_converter.h"
namespace flutter {
namespace gpu {
IMPLEMENT_WRAPPERTYPEINFO(flutter_gpu, CommandBuffer);
CommandBuffer::CommandBuffer(
std::shared_ptr<impeller::Context> context,
std::shared_ptr<impeller::CommandBuffer> command_buffer)
: context_(std::move(context)),
command_buffer_(std::move(command_buffer)) {}
CommandBuffer::~CommandBuffer() = default;
std::shared_ptr<impeller::CommandBuffer> CommandBuffer::GetCommandBuffer() {
return command_buffer_;
}
void CommandBuffer::AddRenderPass(
std::shared_ptr<impeller::RenderPass> render_pass) {
encodables_.push_back(std::move(render_pass));
}
bool CommandBuffer::Submit() {
for (auto& encodable : encodables_) {
encodable->EncodeCommands();
}
return context_->GetCommandQueue()->Submit({command_buffer_}).ok();
}
bool CommandBuffer::Submit(
const impeller::CommandBuffer::CompletionCallback& completion_callback) {
for (auto& encodable : encodables_) {
encodable->EncodeCommands();
}
return context_->GetCommandQueue()
->Submit({command_buffer_}, completion_callback)
.ok();
}
} // namespace gpu
} // namespace flutter
//----------------------------------------------------------------------------
/// Exports
///
bool InternalFlutterGpu_CommandBuffer_Initialize(
Dart_Handle wrapper,
flutter::gpu::Context* contextWrapper) {
auto res = fml::MakeRefCounted<flutter::gpu::CommandBuffer>(
contextWrapper->GetContext(),
contextWrapper->GetContext()->CreateCommandBuffer());
res->AssociateWithDartWrapper(wrapper);
return true;
}
Dart_Handle InternalFlutterGpu_CommandBuffer_Submit(
flutter::gpu::CommandBuffer* wrapper,
Dart_Handle completion_callback) {
if (Dart_IsNull(completion_callback)) {
bool success = wrapper->Submit();
if (!success) {
return tonic::ToDart("Failed to submit CommandBuffer");
}
return Dart_Null();
}
if (!Dart_IsClosure(completion_callback)) {
return tonic::ToDart("Completion callback must be a function");
}
auto dart_state = flutter::UIDartState::Current();
auto& task_runners = dart_state->GetTaskRunners();
auto persistent_completion_callback =
std::make_unique<tonic::DartPersistentValue>(dart_state,
completion_callback);
bool success = wrapper->Submit(fml::MakeCopyable(
[callback = std::move(persistent_completion_callback),
task_runners](impeller::CommandBuffer::Status status) mutable {
bool success = status != impeller::CommandBuffer::Status::kError;
auto ui_completion_task = fml::MakeCopyable(
[callback = std::move(callback), success]() mutable {
auto dart_state = callback->dart_state().lock();
if (!dart_state) {
// The root isolate could have died in the meantime.
return;
}
tonic::DartState::Scope scope(dart_state);
tonic::DartInvoke(callback->Get(), {tonic::ToDart(success)});
// callback is associated with the Dart isolate and must be
// deleted on the UI thread.
callback.reset();
});
task_runners.GetUITaskRunner()->PostTask(ui_completion_task);
}));
if (!success) {
return tonic::ToDart("Failed to submit CommandBuffer");
}
return Dart_Null();
}
| engine/lib/gpu/command_buffer.cc/0 | {
"file_path": "engine/lib/gpu/command_buffer.cc",
"repo_id": "engine",
"token_count": 1409
} | 263 |
// 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.
// ignore_for_file: public_member_api_docs
part of flutter_gpu;
typedef CompletionCallback<T> = void Function(bool success);
base class CommandBuffer extends NativeFieldWrapperClass1 {
/// Creates a new CommandBuffer.
CommandBuffer._(GpuContext gpuContext) {
_initialize(gpuContext);
}
RenderPass createRenderPass(RenderTarget renderTarget) {
return RenderPass._(this, renderTarget);
}
void submit({CompletionCallback? completionCallback}) {
String? error = _submit(completionCallback);
if (error != null) {
throw Exception(error);
}
}
/// Wrap with native counterpart.
@Native<Bool Function(Handle, Pointer<Void>)>(
symbol: 'InternalFlutterGpu_CommandBuffer_Initialize')
external bool _initialize(GpuContext gpuContext);
@Native<Handle Function(Pointer<Void>, Handle)>(
symbol: 'InternalFlutterGpu_CommandBuffer_Submit')
external String? _submit(CompletionCallback? completionCallback);
}
| engine/lib/gpu/lib/src/command_buffer.dart/0 | {
"file_path": "engine/lib/gpu/lib/src/command_buffer.dart",
"repo_id": "engine",
"token_count": 341
} | 264 |
// 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/lib/gpu/shader_library.h"
#include <optional>
#include <utility>
#include "flutter/assets/asset_manager.h"
#include "flutter/lib/gpu/fixtures.h"
#include "flutter/lib/gpu/shader.h"
#include "flutter/lib/ui/ui_dart_state.h"
#include "flutter/lib/ui/window/platform_configuration.h"
#include "fml/mapping.h"
#include "fml/memory/ref_ptr.h"
#include "impeller/core/shader_types.h"
#include "impeller/renderer/vertex_descriptor.h"
#include "impeller/shader_bundle/shader_bundle_flatbuffers.h"
#include "lib/gpu/context.h"
namespace flutter {
namespace gpu {
IMPLEMENT_WRAPPERTYPEINFO(flutter_gpu, ShaderLibrary);
fml::RefPtr<ShaderLibrary> ShaderLibrary::override_shader_library_;
fml::RefPtr<ShaderLibrary> ShaderLibrary::MakeFromAsset(
impeller::Context::BackendType backend_type,
const std::string& name,
std::string& out_error) {
if (override_shader_library_) {
return override_shader_library_;
}
auto dart_state = UIDartState::Current();
std::shared_ptr<AssetManager> asset_manager =
dart_state->platform_configuration()->client()->GetAssetManager();
std::unique_ptr<fml::Mapping> data = asset_manager->GetAsMapping(name);
if (data == nullptr) {
out_error = std::string("Asset '") + name + std::string("' not found.");
return nullptr;
}
return MakeFromFlatbuffer(backend_type, std::move(data));
}
fml::RefPtr<ShaderLibrary> ShaderLibrary::MakeFromShaders(ShaderMap shaders) {
return fml::MakeRefCounted<flutter::gpu::ShaderLibrary>(nullptr,
std::move(shaders));
}
static impeller::ShaderStage ToShaderStage(
impeller::fb::shaderbundle::ShaderStage stage) {
switch (stage) {
case impeller::fb::shaderbundle::ShaderStage::kVertex:
return impeller::ShaderStage::kVertex;
case impeller::fb::shaderbundle::ShaderStage::kFragment:
return impeller::ShaderStage::kFragment;
case impeller::fb::shaderbundle::ShaderStage::kCompute:
return impeller::ShaderStage::kCompute;
}
FML_UNREACHABLE();
}
static impeller::ShaderType FromInputType(
impeller::fb::shaderbundle::InputDataType input_type) {
switch (input_type) {
case impeller::fb::shaderbundle::InputDataType::kBoolean:
return impeller::ShaderType::kBoolean;
case impeller::fb::shaderbundle::InputDataType::kSignedByte:
return impeller::ShaderType::kSignedByte;
case impeller::fb::shaderbundle::InputDataType::kUnsignedByte:
return impeller::ShaderType::kUnsignedByte;
case impeller::fb::shaderbundle::InputDataType::kSignedShort:
return impeller::ShaderType::kSignedShort;
case impeller::fb::shaderbundle::InputDataType::kUnsignedShort:
return impeller::ShaderType::kUnsignedShort;
case impeller::fb::shaderbundle::InputDataType::kSignedInt:
return impeller::ShaderType::kSignedInt;
case impeller::fb::shaderbundle::InputDataType::kUnsignedInt:
return impeller::ShaderType::kUnsignedInt;
case impeller::fb::shaderbundle::InputDataType::kSignedInt64:
return impeller::ShaderType::kSignedInt64;
case impeller::fb::shaderbundle::InputDataType::kUnsignedInt64:
return impeller::ShaderType::kUnsignedInt64;
case impeller::fb::shaderbundle::InputDataType::kFloat:
return impeller::ShaderType::kFloat;
case impeller::fb::shaderbundle::InputDataType::kDouble:
return impeller::ShaderType::kDouble;
}
}
static impeller::ShaderType FromUniformType(
impeller::fb::shaderbundle::UniformDataType uniform_type) {
switch (uniform_type) {
case impeller::fb::shaderbundle::UniformDataType::kBoolean:
return impeller::ShaderType::kBoolean;
case impeller::fb::shaderbundle::UniformDataType::kSignedByte:
return impeller::ShaderType::kSignedByte;
case impeller::fb::shaderbundle::UniformDataType::kUnsignedByte:
return impeller::ShaderType::kUnsignedByte;
case impeller::fb::shaderbundle::UniformDataType::kSignedShort:
return impeller::ShaderType::kSignedShort;
case impeller::fb::shaderbundle::UniformDataType::kUnsignedShort:
return impeller::ShaderType::kUnsignedShort;
case impeller::fb::shaderbundle::UniformDataType::kSignedInt:
return impeller::ShaderType::kSignedInt;
case impeller::fb::shaderbundle::UniformDataType::kUnsignedInt:
return impeller::ShaderType::kUnsignedInt;
case impeller::fb::shaderbundle::UniformDataType::kSignedInt64:
return impeller::ShaderType::kSignedInt64;
case impeller::fb::shaderbundle::UniformDataType::kUnsignedInt64:
return impeller::ShaderType::kUnsignedInt64;
case impeller::fb::shaderbundle::UniformDataType::kFloat:
return impeller::ShaderType::kFloat;
case impeller::fb::shaderbundle::UniformDataType::kDouble:
return impeller::ShaderType::kDouble;
case impeller::fb::shaderbundle::UniformDataType::kHalfFloat:
return impeller::ShaderType::kHalfFloat;
case impeller::fb::shaderbundle::UniformDataType::kSampledImage:
return impeller::ShaderType::kSampledImage;
}
}
static size_t SizeOfInputType(
impeller::fb::shaderbundle::InputDataType input_type) {
switch (input_type) {
case impeller::fb::shaderbundle::InputDataType::kBoolean:
return 1;
case impeller::fb::shaderbundle::InputDataType::kSignedByte:
return 1;
case impeller::fb::shaderbundle::InputDataType::kUnsignedByte:
return 1;
case impeller::fb::shaderbundle::InputDataType::kSignedShort:
return 2;
case impeller::fb::shaderbundle::InputDataType::kUnsignedShort:
return 2;
case impeller::fb::shaderbundle::InputDataType::kSignedInt:
return 4;
case impeller::fb::shaderbundle::InputDataType::kUnsignedInt:
return 4;
case impeller::fb::shaderbundle::InputDataType::kSignedInt64:
return 8;
case impeller::fb::shaderbundle::InputDataType::kUnsignedInt64:
return 8;
case impeller::fb::shaderbundle::InputDataType::kFloat:
return 4;
case impeller::fb::shaderbundle::InputDataType::kDouble:
return 8;
}
}
static const impeller::fb::shaderbundle::BackendShader* GetShaderBackend(
impeller::Context::BackendType backend_type,
const impeller::fb::shaderbundle::Shader* shader) {
switch (backend_type) {
case impeller::Context::BackendType::kMetal:
#ifdef FML_OS_IOS
return shader->metal_ios();
#else
return shader->metal_desktop();
#endif
case impeller::Context::BackendType::kOpenGLES:
#ifdef FML_OS_ANDROID
return shader->opengl_es();
#else
return shader->opengl_desktop();
#endif
case impeller::Context::BackendType::kVulkan:
return shader->vulkan();
}
}
fml::RefPtr<ShaderLibrary> ShaderLibrary::MakeFromFlatbuffer(
impeller::Context::BackendType backend_type,
std::shared_ptr<fml::Mapping> payload) {
if (payload == nullptr || !payload->GetMapping()) {
return nullptr;
}
if (!impeller::fb::shaderbundle::ShaderBundleBufferHasIdentifier(
payload->GetMapping())) {
return nullptr;
}
auto* bundle =
impeller::fb::shaderbundle::GetShaderBundle(payload->GetMapping());
if (!bundle) {
return nullptr;
}
ShaderLibrary::ShaderMap shader_map;
for (const auto* bundled_shader : *bundle->shaders()) {
const impeller::fb::shaderbundle::BackendShader* backend_shader =
GetShaderBackend(backend_type, bundled_shader);
if (!backend_shader) {
VALIDATION_LOG << "Failed to unpack shader \""
<< bundled_shader->name()->c_str() << "\" from bundle.";
continue;
}
auto code_mapping = std::make_shared<fml::NonOwnedMapping>(
backend_shader->shader()->data(), //
backend_shader->shader()->size(), //
[payload = payload](auto, auto) {} //
);
std::unordered_map<std::string, Shader::UniformBinding> uniform_structs;
if (backend_shader->uniform_structs() != nullptr) {
for (const auto& uniform : *backend_shader->uniform_structs()) {
std::vector<impeller::ShaderStructMemberMetadata> members;
if (uniform->fields() != nullptr) {
for (const auto& struct_member : *uniform->fields()) {
members.push_back(impeller::ShaderStructMemberMetadata{
.type = FromUniformType(struct_member->type()),
.name = struct_member->name()->c_str(),
.offset = static_cast<size_t>(struct_member->offset_in_bytes()),
.size =
static_cast<size_t>(struct_member->element_size_in_bytes()),
.byte_length =
static_cast<size_t>(struct_member->total_size_in_bytes()),
.array_elements =
struct_member->array_elements() != 0
? std::optional<size_t>(std::nullopt)
: static_cast<size_t>(struct_member->array_elements()),
});
}
}
uniform_structs[uniform->name()->str()] = Shader::UniformBinding{
.slot =
impeller::ShaderUniformSlot{
.name = uniform->name()->c_str(),
.ext_res_0 = static_cast<size_t>(uniform->ext_res_0()),
.set = static_cast<size_t>(uniform->set()),
.binding = static_cast<size_t>(uniform->binding()),
},
.metadata =
impeller::ShaderMetadata{
.name = uniform->name()->c_str(),
.members = members,
},
.size_in_bytes = static_cast<size_t>(uniform->size_in_bytes()),
};
}
}
std::unordered_map<std::string, impeller::SampledImageSlot>
uniform_textures;
if (backend_shader->uniform_textures() != nullptr) {
for (const auto& uniform : *backend_shader->uniform_textures()) {
uniform_textures[uniform->name()->str()] = impeller::SampledImageSlot{
.name = uniform->name()->c_str(),
.texture_index = static_cast<size_t>(uniform->ext_res_0()),
.set = static_cast<size_t>(uniform->set()),
.binding = static_cast<size_t>(uniform->binding()),
};
}
}
std::shared_ptr<impeller::VertexDescriptor> vertex_descriptor = nullptr;
if (backend_shader->stage() ==
impeller::fb::shaderbundle::ShaderStage::kVertex) {
vertex_descriptor = std::make_shared<impeller::VertexDescriptor>();
auto inputs_fb = backend_shader->inputs();
std::vector<impeller::ShaderStageIOSlot> inputs;
inputs.reserve(inputs_fb->size());
size_t default_stride = 0;
for (const auto& input : *inputs_fb) {
impeller::ShaderStageIOSlot slot;
slot.name = input->name()->c_str();
slot.location = input->location();
slot.set = input->set();
slot.binding = input->binding();
slot.type = FromInputType(input->type());
slot.bit_width = input->bit_width();
slot.vec_size = input->vec_size();
slot.columns = input->columns();
slot.offset = input->offset();
inputs.emplace_back(slot);
default_stride +=
SizeOfInputType(input->type()) * slot.vec_size * slot.columns;
}
std::vector<impeller::ShaderStageBufferLayout> layouts = {
impeller::ShaderStageBufferLayout{
.stride = default_stride,
.binding = 0u,
}};
vertex_descriptor->SetStageInputs(inputs, layouts);
}
auto shader = flutter::gpu::Shader::Make(
backend_shader->entrypoint()->str(),
ToShaderStage(backend_shader->stage()), std::move(code_mapping),
std::move(vertex_descriptor), std::move(uniform_structs),
std::move(uniform_textures));
shader_map[bundled_shader->name()->str()] = std::move(shader);
}
return fml::MakeRefCounted<flutter::gpu::ShaderLibrary>(
std::move(payload), std::move(shader_map));
}
void ShaderLibrary::SetOverride(
fml::RefPtr<ShaderLibrary> override_shader_library) {
override_shader_library_ = std::move(override_shader_library);
}
fml::RefPtr<Shader> ShaderLibrary::GetShader(const std::string& shader_name,
Dart_Handle shader_wrapper) const {
auto it = shaders_.find(shader_name);
if (it == shaders_.end()) {
return nullptr; // No matching shaders.
}
auto shader = it->second;
if (shader->dart_wrapper() == nullptr) {
shader->AssociateWithDartWrapper(shader_wrapper);
}
return shader;
}
ShaderLibrary::ShaderLibrary(std::shared_ptr<fml::Mapping> payload,
ShaderMap shaders)
: payload_(std::move(payload)), shaders_(std::move(shaders)) {}
ShaderLibrary::~ShaderLibrary() = default;
} // namespace gpu
} // namespace flutter
//----------------------------------------------------------------------------
/// Exports
///
Dart_Handle InternalFlutterGpu_ShaderLibrary_InitializeWithAsset(
Dart_Handle wrapper,
Dart_Handle asset_name) {
if (!Dart_IsString(asset_name)) {
return tonic::ToDart("Asset name must be a string");
}
std::optional<std::string> out_error;
auto impeller_context = flutter::gpu::Context::GetDefaultContext(out_error);
if (out_error.has_value()) {
return tonic::ToDart(out_error.value());
}
std::string error;
auto res = flutter::gpu::ShaderLibrary::MakeFromAsset(
impeller_context->GetBackendType(), tonic::StdStringFromDart(asset_name),
error);
if (!res) {
return tonic::ToDart(error);
}
res->AssociateWithDartWrapper(wrapper);
return Dart_Null();
}
Dart_Handle InternalFlutterGpu_ShaderLibrary_GetShader(
flutter::gpu::ShaderLibrary* wrapper,
Dart_Handle shader_name,
Dart_Handle shader_wrapper) {
FML_DCHECK(Dart_IsString(shader_name));
auto shader =
wrapper->GetShader(tonic::StdStringFromDart(shader_name), shader_wrapper);
if (!shader) {
return Dart_Null();
}
return tonic::ToDart(shader.get());
}
| engine/lib/gpu/shader_library.cc/0 | {
"file_path": "engine/lib/gpu/shader_library.cc",
"repo_id": "engine",
"token_count": 5843
} | 265 |
include: ../../analysis_options.yaml
analyzer:
exclude:
# fixtures/ depends on dart:ui and raises false positives.
- fixtures/**
linter:
rules:
unreachable_from_main: false # lint not compatible with how dart:ui is structured
| engine/lib/ui/analysis_options.yaml/0 | {
"file_path": "engine/lib/ui/analysis_options.yaml",
"repo_id": "engine",
"token_count": 78
} | 266 |
#version 320 es
// 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 highp float;
layout(location = 0) out vec4 oColor;
layout(location = 0) uniform float a; // should be 1.0
float addA(float x) {
return x + a;
}
vec2 pairWithA(float x) {
return vec2(x, a);
}
vec3 composedFunction(float x) {
return vec3(addA(x), pairWithA(x));
}
float multiParam(float x, float y, float z) {
return x * y * z * a;
}
void main() {
float x = addA(0.0); // x = 0 + 1;
vec3 v3 = composedFunction(x); // v3 = vec3(2, 1, 1);
x = multiParam(v3.x, v3.y, v3.z); // x = 2 * 1 * 1 * 1;
oColor = vec4(0.0, x / 2.0, 0.0, 1.0); // vec4(0, 1, 0, 1);
}
| engine/lib/ui/fixtures/shaders/general_shaders/functions.frag/0 | {
"file_path": "engine/lib/ui/fixtures/shaders/general_shaders/functions.frag",
"repo_id": "engine",
"token_count": 348
} | 267 |
#version 320 es
// 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 highp float;
layout(location = 0) out vec4 fragColor;
layout(location = 0) uniform float a;
void main() {
fragColor = vec4(
// tan(0.0 / 1.0) = tan(0.0) = 0.0
atan(0.0, 1.0),
// tan(3.1148154493 / 2.0) = tan(1.55740772465) = 1.0
atan(a * 3.1148154493, 2.0), 0.0, 1.0);
}
| engine/lib/ui/fixtures/shaders/supported_glsl_op_shaders/25_atan2.frag/0 | {
"file_path": "engine/lib/ui/fixtures/shaders/supported_glsl_op_shaders/25_atan2.frag",
"repo_id": "engine",
"token_count": 209
} | 268 |
#version 320 es
// 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 highp float;
layout(location = 0) out vec4 fragColor;
layout(location = 0) uniform float a;
void main() {
fragColor = vec4(
// distance between same value is 0.0
distance(a * 7.0, 7.0),
// 7.0 - 6.0 = 1.0
distance(a * 7.0, 6.0), 0.0,
// sqrt(7.0 * 7.0 - 6.0 * 8.0) = sqrt(49.0 - 48.0) = sqrt(1.0) = 1.0
distance(vec2(a * 7.0, 6.0), vec2(7.0, 8.0)));
}
| engine/lib/ui/fixtures/shaders/supported_glsl_op_shaders/67_distance.frag/0 | {
"file_path": "engine/lib/ui/fixtures/shaders/supported_glsl_op_shaders/67_distance.frag",
"repo_id": "engine",
"token_count": 253
} | 269 |
// 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/lib/ui/isolate_name_server/isolate_name_server.h"
namespace flutter {
IsolateNameServer::IsolateNameServer() {}
IsolateNameServer::~IsolateNameServer() = default;
Dart_Port IsolateNameServer::LookupIsolatePortByName(const std::string& name) {
std::scoped_lock lock(mutex_);
return LookupIsolatePortByNameUnprotected(name);
}
Dart_Port IsolateNameServer::LookupIsolatePortByNameUnprotected(
const std::string& name) {
auto port_iterator = port_mapping_.find(name);
if (port_iterator != port_mapping_.end()) {
return port_iterator->second;
}
return ILLEGAL_PORT;
}
bool IsolateNameServer::RegisterIsolatePortWithName(Dart_Port port,
const std::string& name) {
std::scoped_lock lock(mutex_);
if (LookupIsolatePortByNameUnprotected(name) != ILLEGAL_PORT) {
// Name is already registered.
return false;
}
port_mapping_[name] = port;
return true;
}
bool IsolateNameServer::RemoveIsolateNameMapping(const std::string& name) {
std::scoped_lock lock(mutex_);
auto port_iterator = port_mapping_.find(name);
if (port_iterator == port_mapping_.end()) {
return false;
}
port_mapping_.erase(port_iterator);
return true;
}
} // namespace flutter
| engine/lib/ui/isolate_name_server/isolate_name_server.cc/0 | {
"file_path": "engine/lib/ui/isolate_name_server/isolate_name_server.cc",
"repo_id": "engine",
"token_count": 522
} | 270 |
// 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_UI_PAINTING_DISPLAY_LIST_DEFERRED_IMAGE_GPU_IMPELLER_H_
#define FLUTTER_LIB_UI_PAINTING_DISPLAY_LIST_DEFERRED_IMAGE_GPU_IMPELLER_H_
#include "flutter/common/graphics/texture.h"
#include "flutter/display_list/image/dl_image.h"
#include "flutter/flow/layers/layer_tree.h"
#include "flutter/fml/macros.h"
#include "flutter/fml/memory/weak_ptr.h"
#include "flutter/fml/task_runner.h"
#include "flutter/lib/ui/snapshot_delegate.h"
#include "impeller/core/texture.h"
namespace flutter {
class DlDeferredImageGPUImpeller final : public DlImage {
public:
static sk_sp<DlDeferredImageGPUImpeller> Make(
std::unique_ptr<LayerTree> layer_tree,
fml::TaskRunnerAffineWeakPtr<SnapshotDelegate> snapshot_delegate,
fml::RefPtr<fml::TaskRunner> raster_task_runner);
static sk_sp<DlDeferredImageGPUImpeller> Make(
sk_sp<DisplayList> display_list,
const SkISize& size,
fml::TaskRunnerAffineWeakPtr<SnapshotDelegate> snapshot_delegate,
fml::RefPtr<fml::TaskRunner> raster_task_runner);
// |DlImage|
~DlDeferredImageGPUImpeller() override;
// |DlImage|
sk_sp<SkImage> skia_image() const override;
// |DlImage|
std::shared_ptr<impeller::Texture> impeller_texture() const override;
// |DlImage|
bool isOpaque() const override;
// |DlImage|
bool isTextureBacked() const override;
// |DlImage|
bool isUIThreadSafe() const override;
// |DlImage|
SkISize dimensions() const override;
// |DlImage|
size_t GetApproximateByteSize() const override;
// |DlImage|
OwningContext owning_context() const override {
return OwningContext::kRaster;
}
private:
class ImageWrapper final : public std::enable_shared_from_this<ImageWrapper>,
public ContextListener {
public:
~ImageWrapper();
static std::shared_ptr<ImageWrapper> Make(
sk_sp<DisplayList> display_list,
const SkISize& size,
fml::TaskRunnerAffineWeakPtr<SnapshotDelegate> snapshot_delegate,
fml::RefPtr<fml::TaskRunner> raster_task_runner);
static std::shared_ptr<ImageWrapper> Make(
std::unique_ptr<LayerTree> layer_tree,
fml::TaskRunnerAffineWeakPtr<SnapshotDelegate> snapshot_delegate,
fml::RefPtr<fml::TaskRunner> raster_task_runner);
bool isTextureBacked() const;
const std::shared_ptr<impeller::Texture> texture() const {
return texture_;
}
const SkISize size() const { return size_; }
std::optional<std::string> get_error();
private:
SkISize size_;
sk_sp<DisplayList> display_list_;
std::shared_ptr<impeller::Texture> texture_;
fml::TaskRunnerAffineWeakPtr<SnapshotDelegate> snapshot_delegate_;
fml::RefPtr<fml::TaskRunner> raster_task_runner_;
std::shared_ptr<TextureRegistry> texture_registry_;
mutable std::mutex error_mutex_;
std::optional<std::string> error_;
ImageWrapper(
sk_sp<DisplayList> display_list,
const SkISize& size,
fml::TaskRunnerAffineWeakPtr<SnapshotDelegate> snapshot_delegate,
fml::RefPtr<fml::TaskRunner> raster_task_runner);
// If a layer tree is provided, it will be flattened during the raster
// thread task spawned by this method. After being flattened into a display
// list, the image wrapper will be updated to hold this display list and the
// layer tree can be dropped.
void SnapshotDisplayList(std::unique_ptr<LayerTree> layer_tree = nullptr);
// |ContextListener|
void OnGrContextCreated() override;
// |ContextListener|
void OnGrContextDestroyed() override;
FML_DISALLOW_COPY_AND_ASSIGN(ImageWrapper);
};
const std::shared_ptr<ImageWrapper> wrapper_;
explicit DlDeferredImageGPUImpeller(std::shared_ptr<ImageWrapper> wrapper);
FML_DISALLOW_COPY_AND_ASSIGN(DlDeferredImageGPUImpeller);
};
} // namespace flutter
#endif // FLUTTER_LIB_UI_PAINTING_DISPLAY_LIST_DEFERRED_IMAGE_GPU_IMPELLER_H_
| engine/lib/ui/painting/display_list_deferred_image_gpu_impeller.h/0 | {
"file_path": "engine/lib/ui/painting/display_list_deferred_image_gpu_impeller.h",
"repo_id": "engine",
"token_count": 1554
} | 271 |
// 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_UI_PAINTING_IMAGE_DECODER_H_
#define FLUTTER_LIB_UI_PAINTING_IMAGE_DECODER_H_
#include <memory>
#include "flutter/common/settings.h"
#include "flutter/common/task_runners.h"
#include "flutter/display_list/image/dl_image.h"
#include "flutter/fml/concurrent_message_loop.h"
#include "flutter/lib/ui/io_manager.h"
#include "flutter/lib/ui/painting/image_descriptor.h"
namespace flutter {
// An object that coordinates image decompression and texture upload across
// multiple threads/components in the shell. This object must be created,
// accessed and collected on the UI thread (typically the engine or its runtime
// controller). None of the expensive operations performed by this component
// occur in a frame pipeline.
class ImageDecoder {
public:
static std::unique_ptr<ImageDecoder> Make(
const Settings& settings,
const TaskRunners& runners,
std::shared_ptr<fml::ConcurrentTaskRunner> concurrent_task_runner,
fml::WeakPtr<IOManager> io_manager,
const std::shared_ptr<fml::SyncSwitch>& gpu_disabled_switch);
virtual ~ImageDecoder();
using ImageResult = std::function<void(sk_sp<DlImage>, std::string)>;
// Takes an image descriptor and returns a handle to a texture resident on the
// GPU. All image decompression and resizes are done on a worker thread
// concurrently. Texture upload is done on the IO thread and the result
// returned back on the UI thread. On error, the texture is null but the
// callback is guaranteed to return on the UI thread.
virtual void Decode(fml::RefPtr<ImageDescriptor> descriptor,
uint32_t target_width,
uint32_t target_height,
const ImageResult& result) = 0;
fml::WeakPtr<ImageDecoder> GetWeakPtr() const;
protected:
TaskRunners runners_;
std::shared_ptr<fml::ConcurrentTaskRunner> concurrent_task_runner_;
fml::WeakPtr<IOManager> io_manager_;
ImageDecoder(
const TaskRunners& runners,
std::shared_ptr<fml::ConcurrentTaskRunner> concurrent_task_runner,
fml::WeakPtr<IOManager> io_manager);
private:
fml::WeakPtrFactory<ImageDecoder> weak_factory_;
FML_DISALLOW_COPY_AND_ASSIGN(ImageDecoder);
};
} // namespace flutter
#endif // FLUTTER_LIB_UI_PAINTING_IMAGE_DECODER_H_
| engine/lib/ui/painting/image_decoder.h/0 | {
"file_path": "engine/lib/ui/painting/image_decoder.h",
"repo_id": "engine",
"token_count": 840
} | 272 |
// 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/lib/ui/painting/image_encoding.h"
#include "flutter/lib/ui/painting/image_encoding_impl.h"
#include "flutter/lib/ui/painting/image.h"
namespace flutter {
void ConvertImageToRasterSkia(
const sk_sp<DlImage>& dl_image,
std::function<void(sk_sp<SkImage>)> encode_task,
const fml::RefPtr<fml::TaskRunner>& raster_task_runner,
const fml::RefPtr<fml::TaskRunner>& io_task_runner,
const fml::WeakPtr<GrDirectContext>& resource_context,
const fml::TaskRunnerAffineWeakPtr<SnapshotDelegate>& snapshot_delegate,
const std::shared_ptr<const fml::SyncSwitch>& is_gpu_disabled_sync_switch) {
// If the owning_context is kRaster, we can't access it on this task runner.
if (dl_image->owning_context() != DlImage::OwningContext::kRaster) {
auto image = dl_image->skia_image();
// Check validity of the image.
if (image == nullptr) {
FML_LOG(ERROR) << "Image was null.";
encode_task(nullptr);
return;
}
auto dimensions = image->dimensions();
if (dimensions.isEmpty()) {
FML_LOG(ERROR) << "Image dimensions were empty.";
encode_task(nullptr);
return;
}
SkPixmap pixmap;
if (image->peekPixels(&pixmap)) {
// This is already a raster image.
encode_task(image);
return;
}
if (sk_sp<SkImage> raster_image = image->makeRasterImage()) {
// The image can be converted to a raster image.
encode_task(raster_image);
return;
}
}
if (!raster_task_runner) {
FML_LOG(ERROR) << "Raster task runner was null.";
encode_task(nullptr);
return;
}
if (!io_task_runner) {
FML_LOG(ERROR) << "IO task runner was null.";
encode_task(nullptr);
return;
}
// Cross-context images do not support makeRasterImage. Convert these images
// by drawing them into a surface. This must be done on the raster thread
// to prevent concurrent usage of the image on both the IO and raster threads.
raster_task_runner->PostTask([dl_image, encode_task = std::move(encode_task),
resource_context, snapshot_delegate,
io_task_runner, is_gpu_disabled_sync_switch,
raster_task_runner]() {
auto image = dl_image->skia_image();
if (!image || !snapshot_delegate) {
io_task_runner->PostTask(
[encode_task = encode_task]() mutable { encode_task(nullptr); });
return;
}
sk_sp<SkImage> raster_image =
snapshot_delegate->ConvertToRasterImage(image);
io_task_runner->PostTask([image, encode_task = encode_task,
raster_image = std::move(raster_image),
resource_context, is_gpu_disabled_sync_switch,
owning_context = dl_image->owning_context(),
raster_task_runner]() mutable {
if (!raster_image) {
// The rasterizer was unable to render the cross-context image
// (presumably because it does not have a GrContext). In that case,
// convert the image on the IO thread using the resource context.
raster_image = ConvertToRasterUsingResourceContext(
image, resource_context, is_gpu_disabled_sync_switch);
}
encode_task(raster_image);
if (owning_context == DlImage::OwningContext::kRaster) {
raster_task_runner->PostTask([image = std::move(image)]() {});
}
});
});
}
} // namespace flutter
| engine/lib/ui/painting/image_encoding_skia.cc/0 | {
"file_path": "engine/lib/ui/painting/image_encoding_skia.cc",
"repo_id": "engine",
"token_count": 1517
} | 273 |
// 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/lib/ui/painting/matrix.h"
#include "flutter/fml/logging.h"
#include "flutter/lib/ui/floating_point.h"
namespace flutter {
// Mappings from SkMatrix-index to input-index.
static const int kSkMatrixIndexToMatrix4Index[] = {
// clang-format off
0, 4, 12,
1, 5, 13,
3, 7, 15,
// clang-format on
};
SkM44 ToSkM44(const tonic::Float64List& matrix4) {
// clang-format off
return SkM44(
SafeNarrow(matrix4[ 0]), SafeNarrow(matrix4[ 4]), SafeNarrow(matrix4[ 8]), SafeNarrow(matrix4[12]),
SafeNarrow(matrix4[ 1]), SafeNarrow(matrix4[ 5]), SafeNarrow(matrix4[ 9]), SafeNarrow(matrix4[13]),
SafeNarrow(matrix4[ 2]), SafeNarrow(matrix4[ 6]), SafeNarrow(matrix4[10]), SafeNarrow(matrix4[14]),
SafeNarrow(matrix4[ 3]), SafeNarrow(matrix4[ 7]), SafeNarrow(matrix4[11]), SafeNarrow(matrix4[15])
);
// clang-format on
}
SkMatrix ToSkMatrix(const tonic::Float64List& matrix4) {
FML_DCHECK(matrix4.data());
SkMatrix sk_matrix;
for (int i = 0; i < 9; ++i) {
int matrix4_index = kSkMatrixIndexToMatrix4Index[i];
if (matrix4_index < matrix4.num_elements()) {
sk_matrix[i] = SafeNarrow(matrix4[matrix4_index]);
} else {
sk_matrix[i] = 0.0f;
}
}
return sk_matrix;
}
tonic::Float64List ToMatrix4(const SkMatrix& sk_matrix) {
tonic::Float64List matrix4(Dart_NewTypedData(Dart_TypedData_kFloat64, 16));
for (int i = 0; i < 9; ++i) {
matrix4[kSkMatrixIndexToMatrix4Index[i]] = sk_matrix[i];
}
matrix4[10] = 1.0; // Identity along the z axis.
return matrix4;
}
} // namespace flutter
| engine/lib/ui/painting/matrix.cc/0 | {
"file_path": "engine/lib/ui/painting/matrix.cc",
"repo_id": "engine",
"token_count": 718
} | 274 |
// 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/lib/ui/painting/rrect.h"
#include "flutter/fml/logging.h"
#include "third_party/tonic/logging/dart_error.h"
#include "third_party/tonic/typed_data/typed_list.h"
using flutter::RRect;
namespace tonic {
// Construct an SkRRect from a Dart RRect object.
// The Dart RRect is a Float32List containing
// [left, top, right, bottom, xRadius, yRadius]
RRect DartConverter<flutter::RRect>::FromDart(Dart_Handle value) {
Float32List buffer(value);
RRect result;
result.is_null = true;
if (buffer.data() == nullptr) {
return result;
}
SkVector radii[4] = {{buffer[4], buffer[5]},
{buffer[6], buffer[7]},
{buffer[8], buffer[9]},
{buffer[10], buffer[11]}};
result.sk_rrect.setRectRadii(
SkRect::MakeLTRB(buffer[0], buffer[1], buffer[2], buffer[3]), radii);
result.is_null = false;
return result;
}
RRect DartConverter<flutter::RRect>::FromArguments(Dart_NativeArguments args,
int index,
Dart_Handle& exception) {
Dart_Handle value = Dart_GetNativeArgument(args, index);
FML_DCHECK(!CheckAndHandleError(value));
return FromDart(value);
}
} // namespace tonic
| engine/lib/ui/painting/rrect.cc/0 | {
"file_path": "engine/lib/ui/painting/rrect.cc",
"repo_id": "engine",
"token_count": 634
} | 275 |
// 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/lib/ui/plugins/callback_cache.h"
#include <fstream>
#include <iterator>
#include "flutter/fml/build_config.h"
#include "flutter/fml/logging.h"
#include "flutter/fml/paths.h"
#include "rapidjson/document.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/writer.h"
#include "third_party/tonic/converter/dart_converter.h"
using rapidjson::Document;
using rapidjson::StringBuffer;
using rapidjson::Writer;
using tonic::ToDart;
namespace flutter {
static const char* kHandleKey = "handle";
static const char* kRepresentationKey = "representation";
static const char* kNameKey = "name";
static const char* kClassNameKey = "class_name";
static const char* kLibraryPathKey = "library_path";
static const char* kCacheName = "flutter_callback_cache.json";
std::mutex DartCallbackCache::mutex_;
std::string DartCallbackCache::cache_path_;
std::map<int64_t, DartCallbackRepresentation> DartCallbackCache::cache_;
void DartCallbackCache::SetCachePath(const std::string& path) {
cache_path_ = fml::paths::JoinPaths({path, kCacheName});
}
Dart_Handle DartCallbackCache::GetCallback(int64_t handle) {
std::scoped_lock lock(mutex_);
auto iterator = cache_.find(handle);
if (iterator != cache_.end()) {
DartCallbackRepresentation cb = iterator->second;
return LookupDartClosure(cb.name, cb.class_name, cb.library_path);
}
return Dart_Null();
}
int64_t DartCallbackCache::GetCallbackHandle(const std::string& name,
const std::string& class_name,
const std::string& library_path) {
std::scoped_lock lock(mutex_);
std::hash<std::string> hasher;
int64_t hash = hasher(name);
hash += hasher(class_name);
hash += hasher(library_path);
if (cache_.find(hash) == cache_.end()) {
cache_[hash] = {name, class_name, library_path};
SaveCacheToDisk();
}
return hash;
}
std::unique_ptr<DartCallbackRepresentation>
DartCallbackCache::GetCallbackInformation(int64_t handle) {
std::scoped_lock lock(mutex_);
auto iterator = cache_.find(handle);
if (iterator != cache_.end()) {
return std::make_unique<DartCallbackRepresentation>(iterator->second);
}
return nullptr;
}
void DartCallbackCache::SaveCacheToDisk() {
// Cache JSON format
// [
// {
// "hash": 42,
// "representation": {
// "name": "...",
// "class_name": "...",
// "library_path": "..."
// }
// },
// {
// ...
// }
// ]
StringBuffer s;
Writer<StringBuffer> writer(s);
writer.StartArray();
for (auto iterator = cache_.begin(); iterator != cache_.end(); ++iterator) {
int64_t hash = iterator->first;
DartCallbackRepresentation cb = iterator->second;
writer.StartObject();
writer.Key(kHandleKey);
writer.Int64(hash);
writer.Key(kRepresentationKey);
writer.StartObject();
writer.Key(kNameKey);
writer.String(cb.name.c_str());
writer.Key(kClassNameKey);
writer.String(cb.class_name.c_str());
writer.Key(kLibraryPathKey);
writer.String(cb.library_path.c_str());
writer.EndObject();
writer.EndObject();
}
writer.EndArray();
std::ofstream output(cache_path_);
output << s.GetString();
output.close();
}
void DartCallbackCache::LoadCacheFromDisk() {
std::scoped_lock lock(mutex_);
// Don't reload the cache if it's already populated.
if (!cache_.empty()) {
return;
}
std::ifstream input(cache_path_);
if (!input) {
return;
}
std::string cache_contents{std::istreambuf_iterator<char>(input),
std::istreambuf_iterator<char>()};
Document d;
d.Parse(cache_contents.c_str());
if (d.HasParseError() || !d.IsArray()) {
// Could not parse callback cache, aborting restore.
return;
}
const auto entries = d.GetArray();
for (auto* it = entries.begin(); it != entries.end(); ++it) {
const auto root_obj = it->GetObject();
const auto representation = root_obj[kRepresentationKey].GetObject();
const int64_t hash = root_obj[kHandleKey].GetInt64();
DartCallbackRepresentation cb;
cb.name = representation[kNameKey].GetString();
cb.class_name = representation[kClassNameKey].GetString();
cb.library_path = representation[kLibraryPathKey].GetString();
cache_[hash] = cb;
}
}
Dart_Handle DartCallbackCache::LookupDartClosure(
const std::string& name,
const std::string& class_name,
const std::string& library_path) {
Dart_Handle closure_name = ToDart(name);
if (Dart_IsError(closure_name)) {
return closure_name;
}
Dart_Handle library_name =
library_path.empty() ? Dart_Null() : ToDart(library_path);
if (Dart_IsError(library_name)) {
return library_name;
}
Dart_Handle cls_name = class_name.empty() ? Dart_Null() : ToDart(class_name);
if (Dart_IsError(cls_name)) {
return cls_name;
}
Dart_Handle library;
if (library_name == Dart_Null()) {
library = Dart_RootLibrary();
} else {
library = Dart_LookupLibrary(library_name);
}
if (Dart_IsError(library)) {
return library;
}
Dart_Handle closure;
if (Dart_IsNull(cls_name)) {
closure = Dart_GetField(library, closure_name);
} else {
Dart_Handle cls = Dart_GetClass(library, cls_name);
if (Dart_IsError(cls)) {
return cls;
}
if (Dart_IsNull(cls)) {
closure = Dart_Null();
} else {
closure = Dart_GetStaticMethodClosure(library, cls, closure_name);
}
}
return closure;
}
} // namespace flutter
| engine/lib/ui/plugins/callback_cache.cc/0 | {
"file_path": "engine/lib/ui/plugins/callback_cache.cc",
"repo_id": "engine",
"token_count": 2153
} | 276 |
// 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_UI_SNAPSHOT_DELEGATE_H_
#define FLUTTER_LIB_UI_SNAPSHOT_DELEGATE_H_
#include <string>
#include "flutter/common/graphics/texture.h"
#include "flutter/display_list/display_list.h"
#include "third_party/skia/include/core/SkImage.h"
#include "third_party/skia/include/gpu/GrBackendSurface.h"
#include "third_party/skia/include/gpu/GrContextThreadSafeProxy.h"
#include "third_party/skia/include/gpu/GrDirectContext.h"
namespace flutter {
class DlImage;
class SnapshotDelegate {
public:
//----------------------------------------------------------------------------
/// @brief A data structure used by the Skia implementation of deferred
/// GPU based images.
struct GpuImageResult {
GpuImageResult(const GrBackendTexture& p_texture,
sk_sp<GrDirectContext> p_context,
sk_sp<SkImage> p_image = nullptr,
const std::string& p_error = "")
: texture(p_texture),
context(std::move(p_context)),
image(std::move(p_image)),
error(p_error) {}
const GrBackendTexture texture;
// If texture.isValid() == true, this is a pointer to a GrDirectContext that
// can be used to create an image from the texture.
sk_sp<GrDirectContext> context;
// If MakeGpuImage could not create a GPU resident image, a raster copy
// is available in this member and texture.isValid() is false.
sk_sp<SkImage> image;
// A non-empty string containing an error message if neither a GPU backed
// texture nor a raster backed image could be created.
const std::string error;
};
//----------------------------------------------------------------------------
/// @brief Attempts to create a GrBackendTexture for the specified
/// DisplayList. May result in a raster bitmap if no GPU context
/// is available.
virtual std::unique_ptr<GpuImageResult> MakeSkiaGpuImage(
sk_sp<DisplayList> display_list,
const SkImageInfo& image_info) = 0;
//----------------------------------------------------------------------------
/// @brief Gets the registry of external textures currently in use by the
/// rasterizer. These textures may be updated at a cadence
/// different from that of the Flutter application. When an
/// external texture is referenced in the Flutter layer tree, that
/// texture is composited within the Flutter layer tree.
///
/// @return A pointer to the external texture registry.
///
virtual std::shared_ptr<TextureRegistry> GetTextureRegistry() = 0;
virtual GrDirectContext* GetGrContext() = 0;
virtual sk_sp<DlImage> MakeRasterSnapshot(sk_sp<DisplayList> display_list,
SkISize picture_size) = 0;
virtual sk_sp<SkImage> ConvertToRasterImage(sk_sp<SkImage> image) = 0;
};
} // namespace flutter
#endif // FLUTTER_LIB_UI_SNAPSHOT_DELEGATE_H_
| engine/lib/ui/snapshot_delegate.h/0 | {
"file_path": "engine/lib/ui/snapshot_delegate.h",
"repo_id": "engine",
"token_count": 1119
} | 277 |
// 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.
part of dart.ui;
/// A configurable display that a [FlutterView] renders on.
///
/// Use [FlutterView.display] to get the current display for that view.
class Display {
const Display._({
required this.id,
required this.devicePixelRatio,
required this.size,
required this.refreshRate,
});
/// A unique identifier for this display.
///
/// This identifier is unique among a list of displays the Flutter framework
/// is aware of, and is not derived from any platform specific identifiers for
/// displays.
final int id;
/// The device pixel ratio of this display.
///
/// This value is the same as the value of [FlutterView.devicePixelRatio] for
/// all view objects attached to this display.
final double devicePixelRatio;
/// The physical size of this display.
final Size size;
/// The refresh rate in FPS of this display.
final double refreshRate;
@override
String toString() => 'Display(id: $id, size: $size, devicePixelRatio: $devicePixelRatio, refreshRate: $refreshRate)';
}
/// A view into which a Flutter [Scene] is drawn.
///
/// Each [FlutterView] has its own layer tree that is rendered
/// whenever [render] is called on it with a [Scene].
///
/// ## Insets and Padding
///
/// {@animation 300 300 https://flutter.github.io/assets-for-api-docs/assets/widgets/window_padding.mp4}
///
/// In this illustration, the black areas represent system UI that the app
/// cannot draw over. The red area represents view padding that the view may not
/// be able to detect gestures in and may not want to draw in. The grey area
/// represents the system keyboard, which can cover over the bottom view padding
/// when visible.
///
/// The [viewInsets] are the physical pixels which the operating
/// system reserves for system UI, such as the keyboard, which would fully
/// obscure any content drawn in that area.
///
/// The [viewPadding] are the physical pixels on each side of the
/// display that may be partially obscured by system UI or by physical
/// intrusions into the display, such as an overscan region on a television or a
/// "notch" on a phone. Unlike the insets, these areas may have portions that
/// show the user view-painted pixels without being obscured, such as a
/// notch at the top of a phone that covers only a subset of the area. Insets,
/// on the other hand, either partially or fully obscure the window, such as an
/// opaque keyboard or a partially translucent status bar, which cover an area
/// without gaps.
///
/// The [padding] property is computed from both
/// [viewInsets] and [viewPadding]. It will allow a
/// view inset to consume view padding where appropriate, such as when a phone's
/// keyboard is covering the bottom view padding and so "absorbs" it.
///
/// Clients that want to position elements relative to the view padding
/// regardless of the view insets should use the [viewPadding]
/// property, e.g. if you wish to draw a widget at the center of the screen with
/// respect to the iPhone "safe area" regardless of whether the keyboard is
/// showing.
///
/// [padding] is useful for clients that want to know how much
/// padding should be accounted for without concern for the current inset(s)
/// state, e.g. determining whether a gesture should be considered for scrolling
/// purposes. This value varies based on the current state of the insets. For
/// example, a visible keyboard will consume all gestures in the bottom part of
/// the [viewPadding] anyway, so there is no need to account for
/// that in the [padding], which is always safe to use for such
/// calculations.
class FlutterView {
FlutterView._(this.viewId, this.platformDispatcher, this._viewConfiguration);
/// The opaque ID for this view.
final int viewId;
/// The platform dispatcher that this view is registered with, and gets its
/// information from.
final PlatformDispatcher platformDispatcher;
/// The configuration of this view.
_ViewConfiguration _viewConfiguration;
/// The [Display] this view is drawn in.
Display get display {
assert(platformDispatcher._displays.containsKey(_viewConfiguration.displayId));
return platformDispatcher._displays[_viewConfiguration.displayId]!;
}
/// The number of device pixels for each logical pixel for the screen this
/// view is displayed on.
///
/// This number might not be a power of two. Indeed, it might not even be an
/// integer. For example, the Nexus 6 has a device pixel ratio of 3.5.
///
/// Device pixels are also referred to as physical pixels. Logical pixels are
/// also referred to as device-independent or resolution-independent pixels.
///
/// By definition, there are roughly 38 logical pixels per centimeter, or
/// about 96 logical pixels per inch, of the physical display. The value
/// returned by [devicePixelRatio] is ultimately obtained either from the
/// hardware itself, the device drivers, or a hard-coded value stored in the
/// operating system or firmware, and may be inaccurate, sometimes by a
/// significant margin.
///
/// The Flutter framework operates in logical pixels, so it is rarely
/// necessary to directly deal with this property.
///
/// When this changes, [PlatformDispatcher.onMetricsChanged] is called. When
/// using the Flutter framework, using [MediaQuery.of] to obtain the device
/// pixel ratio (via [MediaQueryData.devicePixelRatio]), instead of directly
/// obtaining the [devicePixelRatio] from a [FlutterView], will automatically
/// cause any widgets dependent on this value to rebuild when it changes,
/// without having to listen to [PlatformDispatcher.onMetricsChanged].
///
/// See also:
///
/// * [WidgetsBindingObserver], for a mechanism at the widgets layer to
/// observe when this value changes.
/// * [Display.devicePixelRatio], which reports the DPR of the display.
/// The value here is equal to the value exposed on [display].
double get devicePixelRatio => _viewConfiguration.devicePixelRatio;
/// The sizing constraints in physical pixels for this view.
///
/// The view can take on any [Size] that fulfills these constraints. These
/// constraints are typically used by an UI framework as the input for its
/// layout algorithm to determine an approrpiate size for the view. To size
/// the view, the selected size must be provided to the [render] method and it
/// must satisfy the constraints.
///
/// When this changes, [PlatformDispatcher.onMetricsChanged] is called.
///
/// At startup, the constraints for the view may not be known before Dart code
/// runs. If this value is observed early in the application lifecycle, it may
/// report constraints with all dimensions set to zero.
///
/// This value does not take into account any on-screen keyboards or other
/// system UI. If the constraints are tight, the [padding] and [viewInsets]
/// properties provide information about how much of each side of the view may
/// be obscured by system UI. If the constraints are loose, this information
/// is not known upfront.
///
/// See also:
///
/// * [physicalSize], which returns the current size of the view.
// TODO(goderbauer): Wire this up so embedders can configure it. This will
// also require to message the size provided to the render call back to the
// embedder.
ViewConstraints get physicalConstraints => ViewConstraints.tight(physicalSize);
/// The current dimensions of the rectangle as last reported by the platform
/// into which scenes rendered in this view are drawn.
///
/// If the view is configured with loose [physicalConstraints] this value
/// may be outdated by a few frames as it only updates when the size chosen
/// for a frame (as provided to the [render] method) is processed by the
/// platform. Because of this, [physicalConstraints] should be used instead of
/// this value as the root input to the layout algorithm of UI frameworks.
///
/// When this changes, [PlatformDispatcher.onMetricsChanged] is called. When
/// using the Flutter framework, using [MediaQuery.of] to obtain the size (via
/// [MediaQueryData.size]), instead of directly obtaining the [physicalSize]
/// from a [FlutterView], will automatically cause any widgets dependent on the
/// size to rebuild when the size changes, without having to listen to
/// [PlatformDispatcher.onMetricsChanged].
///
/// At startup, the size of the view may not be known before Dart code runs.
/// If this value is observed early in the application lifecycle, it may
/// report [Size.zero].
///
/// This value does not take into account any on-screen keyboards or other
/// system UI. The [padding] and [viewInsets] properties provide information
/// about how much of each side of the view may be obscured by system UI.
///
/// See also:
///
/// * [WidgetsBindingObserver], for a mechanism at the widgets layer to
/// observe when this value changes.
Size get physicalSize => _viewConfiguration.size;
/// The number of physical pixels on each side of the display rectangle into
/// which the view can render, but over which the operating system will likely
/// place system UI, such as the keyboard, that fully obscures any content.
///
/// When this property changes, [PlatformDispatcher.onMetricsChanged] is
/// called. When using the Flutter framework, using [MediaQuery.of] to obtain
/// the insets (via [MediaQueryData.viewInsets]), instead of directly
/// obtaining the [viewInsets] from a [FlutterView], will automatically cause
/// any widgets dependent on the insets to rebuild when they change, without
/// having to listen to [PlatformDispatcher.onMetricsChanged].
///
/// The relationship between this [viewInsets],
/// [viewPadding], and [padding] are described in
/// more detail in the documentation for [FlutterView].
///
/// See also:
///
/// * [WidgetsBindingObserver], for a mechanism at the widgets layer to
/// observe when this value changes.
/// * [MediaQuery.of], a simpler mechanism for the same.
/// * [Scaffold], which automatically applies the view insets in material
/// design applications.
ViewPadding get viewInsets => _viewConfiguration.viewInsets;
/// The number of physical pixels on each side of the display rectangle into
/// which the view can render, but which may be partially obscured by system
/// UI (such as the system notification area), or physical intrusions in
/// the display (e.g. overscan regions on television screens or phone sensor
/// housings).
///
/// Unlike [padding], this value does not change relative to
/// [viewInsets]. For example, on an iPhone X, it will not
/// change in response to the soft keyboard being visible or hidden, whereas
/// [padding] will.
///
/// When this property changes, [PlatformDispatcher.onMetricsChanged] is
/// called. When using the Flutter framework, using [MediaQuery.of] to obtain
/// the padding (via [MediaQueryData.viewPadding]), instead of directly
/// obtaining the [viewPadding] from a [FlutterView], will automatically cause
/// any widgets dependent on the padding to rebuild when it changes, without
/// having to listen to [PlatformDispatcher.onMetricsChanged].
///
/// The relationship between this [viewInsets],
/// [viewPadding], and [padding] are described in
/// more detail in the documentation for [FlutterView].
///
/// See also:
///
/// * [WidgetsBindingObserver], for a mechanism at the widgets layer to
/// observe when this value changes.
/// * [MediaQuery.of], a simpler mechanism for the same.
/// * [Scaffold], which automatically applies the padding in material design
/// applications.
ViewPadding get viewPadding => _viewConfiguration.viewPadding;
/// The number of physical pixels on each side of the display rectangle into
/// which the view can render, but where the operating system will consume
/// input gestures for the sake of system navigation.
///
/// For example, an operating system might use the vertical edges of the
/// screen, where swiping inwards from the edges takes users backward
/// through the history of screens they previously visited.
///
/// When this property changes, [PlatformDispatcher.onMetricsChanged] is called.
///
/// See also:
///
/// * [WidgetsBindingObserver], for a mechanism at the widgets layer to
/// observe when this value changes.
/// * [MediaQuery.of], a simpler mechanism for the same.
ViewPadding get systemGestureInsets => _viewConfiguration.systemGestureInsets;
/// The number of physical pixels on each side of the display rectangle into
/// which the view can render, but which may be partially obscured by system
/// UI (such as the system notification area), or physical intrusions in
/// the display (e.g. overscan regions on television screens or phone sensor
/// housings).
///
/// This value is calculated by taking `max(0.0, FlutterView.viewPadding -
/// FlutterView.viewInsets)`. This will treat a system IME that increases the
/// bottom inset as consuming that much of the bottom padding. For example, on
/// an iPhone X, [EdgeInsets.bottom] of [FlutterView.padding] is the same as
/// [EdgeInsets.bottom] of [FlutterView.viewPadding] when the soft keyboard is
/// not drawn (to account for the bottom soft button area), but will be `0.0`
/// when the soft keyboard is visible.
///
/// When this changes, [PlatformDispatcher.onMetricsChanged] is called. When
/// using the Flutter framework, using [MediaQuery.of] to obtain the padding
/// (via [MediaQueryData.padding]), instead of directly obtaining the
/// [padding] from a [FlutterView], will automatically cause any widgets
/// dependent on the padding to rebuild when it changes, without having to
/// listen to [PlatformDispatcher.onMetricsChanged].
///
/// The relationship between this [viewInsets], [viewPadding], and [padding]
/// are described in more detail in the documentation for [FlutterView].
///
/// See also:
///
/// * [WidgetsBindingObserver], for a mechanism at the widgets layer to
/// observe when this value changes.
/// * [MediaQuery.of], a simpler mechanism for the same.
/// * [Scaffold], which automatically applies the padding in material design
/// applications.
ViewPadding get padding => _viewConfiguration.padding;
/// Additional configuration for touch gestures performed on this view.
///
/// For example, the touch slop defined in physical pixels may be provided
/// by the gesture settings and should be preferred over the framework
/// touch slop constant.
GestureSettings get gestureSettings => _viewConfiguration.gestureSettings;
/// {@template dart.ui.ViewConfiguration.displayFeatures}
/// Areas of the display that are obstructed by hardware features.
///
/// This list is populated only on Android. If the device has no display
/// features, this list is empty.
///
/// The coordinate space in which the [DisplayFeature.bounds] are defined spans
/// across the screens currently in use. This means that the space between the screens
/// is virtually part of the Flutter view space, with the [DisplayFeature.bounds]
/// of the display feature as an obstructed area. The [DisplayFeature.type] can
/// be used to determine if this display feature obstructs the screen or not.
/// For example, [DisplayFeatureType.hinge] and [DisplayFeatureType.cutout] both
/// obstruct the display, while [DisplayFeatureType.fold] is a crease in the display.
///
/// Folding [DisplayFeature]s like the [DisplayFeatureType.hinge] and
/// [DisplayFeatureType.fold] also have a [DisplayFeature.state] which can be
/// used to determine the posture the device is in.
/// {@endtemplate}
///
/// When this changes, [PlatformDispatcher.onMetricsChanged] is called.
///
/// See also:
///
/// * [WidgetsBindingObserver], for a mechanism at the widgets layer to
/// observe when this value changes.
/// * [MediaQuery.of], a simpler mechanism to access this data.
List<DisplayFeature> get displayFeatures => _viewConfiguration.displayFeatures;
/// Updates the view's rendering on the GPU with the newly provided [Scene].
///
/// This function must be called within the scope of the
/// [PlatformDispatcher.onBeginFrame] or [PlatformDispatcher.onDrawFrame]
/// callbacks being invoked.
///
/// If this function is called a second time during a single
/// [PlatformDispatcher.onBeginFrame]/[PlatformDispatcher.onDrawFrame]
/// callback sequence or called outside the scope of those callbacks, the call
/// will be ignored.
///
/// To record graphical operations, first create a [PictureRecorder], then
/// construct a [Canvas], passing that [PictureRecorder] to its constructor.
/// After issuing all the graphical operations, call the
/// [PictureRecorder.endRecording] function on the [PictureRecorder] to obtain
/// the final [Picture] that represents the issued graphical operations.
///
/// Next, create a [SceneBuilder], and add the [Picture] to it using
/// [SceneBuilder.addPicture]. With the [SceneBuilder.build] method you can
/// then obtain a [Scene] object, which you can display to the user via this
/// [render] function.
///
/// If the view is configured with loose [physicalConstraints] (i.e.
/// [ViewConstraints.isTight] returns false) a `size` satisfying those
/// constraints must be provided. This method does not check that the provided
/// `size` actually meets the constraints (this should be done in a higher
/// level), but an illegal `size` may result in undefined rendering behavior.
/// If no `size` is provided, [physicalSize] is used instead.
///
/// See also:
///
/// * [SchedulerBinding], the Flutter framework class which manages the
/// scheduling of frames.
/// * [RendererBinding], the Flutter framework class which manages layout and
/// painting.
void render(Scene scene, {Size? size}) {
_render(viewId, scene as _NativeScene, size?.width ?? physicalSize.width, size?.height ?? physicalSize.height);
}
@Native<Void Function(Int64, Pointer<Void>, Double, Double)>(symbol: 'PlatformConfigurationNativeApi::Render')
external static void _render(int viewId, _NativeScene scene, double width, double height);
/// Change the retained semantics data about this [FlutterView].
///
/// If [PlatformDispatcher.semanticsEnabled] is true, the user has requested that this function
/// be called whenever the semantic content of this [FlutterView]
/// changes.
///
/// This function disposes the given update, which means the semantics update
/// cannot be used further.
void updateSemantics(SemanticsUpdate update) => _updateSemantics(update as _NativeSemanticsUpdate);
@Native<Void Function(Pointer<Void>)>(symbol: 'PlatformConfigurationNativeApi::UpdateSemantics')
external static void _updateSemantics(_NativeSemanticsUpdate update);
@override
String toString() => 'FlutterView(id: $viewId)';
}
/// Deprecated. Will be removed in a future version of Flutter.
///
/// This class is deprecated to prepare for Flutter's upcoming support for
/// multiple views and eventually multiple windows.
///
/// This class has been split into two classes: [FlutterView] and
/// [PlatformDispatcher]. A [FlutterView] gives an application access to
/// view-specific functionality while the [PlatformDispatcher] contains
/// platform-specific functionality that applies to all views.
///
/// This class backs the global [window] singleton, which is also deprecated.
/// See the docs on [window] for migration options.
///
/// See also:
///
/// * [FlutterView], which gives an application access to view-specific
/// functionality.
/// * [PlatformDispatcher], which gives an application access to
/// platform-specific functionality.
@Deprecated(
'Use FlutterView or PlatformDispatcher instead. '
'Deprecated to prepare for the upcoming multi-window support. '
'This feature was deprecated after v3.7.0-32.0.pre.'
)
class SingletonFlutterWindow extends FlutterView {
@Deprecated(
'Use FlutterView or PlatformDispatcher instead. '
'Deprecated to prepare for the upcoming multi-window support. '
'This feature was deprecated after v3.7.0-32.0.pre.'
)
SingletonFlutterWindow._() : super._(
// TODO(dkwingsmt): This crashes if the implicit view is disabled. We need
// to resolve this by the time embedders are allowed to disable the implicit
// view.
// https://github.com/flutter/flutter/issues/131651
_implicitViewId!,
PlatformDispatcher.instance,
const _ViewConfiguration(),
);
// Gets its configuration from the FlutterView with the same ID if it exists.
@override
_ViewConfiguration get _viewConfiguration => platformDispatcher._views[viewId]?._viewConfiguration ?? super._viewConfiguration;
/// A callback that is invoked whenever the [devicePixelRatio],
/// [physicalSize], [padding], [viewInsets], [PlatformDispatcher.views], or
/// [systemGestureInsets] values change.
///
/// {@macro dart.ui.window.accessorForwardWarning}
///
/// When using the Flutter framework, the [MediaQuery] widget exposes much of
/// these metrics. Using [MediaQuery.of] to obtain them allows the framework
/// to automatically rebuild widgets that depend on them, without having to
/// manage the [onMetricsChanged] callback.
///
/// See [PlatformDispatcher.onMetricsChanged] for more information.
VoidCallback? get onMetricsChanged => platformDispatcher.onMetricsChanged;
set onMetricsChanged(VoidCallback? callback) {
platformDispatcher.onMetricsChanged = callback;
}
/// The system-reported default locale of the device.
///
/// {@template dart.ui.window.accessorForwardWarning}
/// Accessing this value returns the value contained in the
/// [PlatformDispatcher] singleton, so instead of getting it from here, you
/// should consider getting it from
/// `WidgetsBinding.instance.platformDispatcher` instead (or, when
/// `WidgetsBinding` isn't available, from [PlatformDispatcher.instance]). The
/// reason this value forwards to the [PlatformDispatcher] is to provide
/// convenience for applications that only use a single main window.
/// {@endtemplate}
///
/// This establishes the language and formatting conventions that window
/// should, if possible, use to render their user interface.
///
/// This is the first locale selected by the user and is the user's primary
/// locale (the locale the device UI is displayed in)
///
/// This is equivalent to `locales.first` and will provide an empty non-null
/// locale if the [locales] list has not been set or is empty.
Locale get locale => platformDispatcher.locale;
/// The full system-reported supported locales of the device.
///
/// {@macro dart.ui.window.accessorForwardWarning}
///
/// This establishes the language and formatting conventions that window
/// should, if possible, use to render their user interface.
///
/// The list is ordered in order of priority, with lower-indexed locales being
/// preferred over higher-indexed ones. The first element is the primary [locale].
///
/// The [onLocaleChanged] callback is called whenever this value changes.
///
/// See also:
///
/// * [WidgetsBindingObserver], for a mechanism at the widgets layer to
/// observe when this value changes.
List<Locale> get locales => platformDispatcher.locales;
/// Performs the platform-native locale resolution.
///
/// Each platform may return different results.
///
/// If the platform fails to resolve a locale, then this will return null.
///
/// This method returns synchronously and is a direct call to
/// platform specific APIs without invoking method channels.
Locale? computePlatformResolvedLocale(List<Locale> supportedLocales) {
return platformDispatcher.computePlatformResolvedLocale(supportedLocales);
}
/// A callback that is invoked whenever [locale] changes value.
///
/// {@macro dart.ui.window.accessorForwardWarning}
///
/// The framework invokes this callback in the same zone in which the
/// callback was set.
///
/// See also:
///
/// * [WidgetsBindingObserver], for a mechanism at the widgets layer to
/// observe when this callback is invoked.
VoidCallback? get onLocaleChanged => platformDispatcher.onLocaleChanged;
set onLocaleChanged(VoidCallback? callback) {
platformDispatcher.onLocaleChanged = callback;
}
/// The lifecycle state immediately after dart isolate initialization.
///
/// {@macro dart.ui.window.accessorForwardWarning}
///
/// This property will not be updated as the lifecycle changes.
///
/// It is used to initialize [SchedulerBinding.lifecycleState] at startup
/// with any buffered lifecycle state events.
String get initialLifecycleState => platformDispatcher.initialLifecycleState;
/// The system-reported text scale.
///
/// {@macro dart.ui.window.accessorForwardWarning}
///
/// This establishes the text scaling factor to use when rendering text,
/// according to the user's platform preferences.
///
/// The [onTextScaleFactorChanged] callback is called whenever this value
/// changes.
///
/// See also:
///
/// * [WidgetsBindingObserver], for a mechanism at the widgets layer to
/// observe when this value changes.
double get textScaleFactor => platformDispatcher.textScaleFactor;
/// Whether the spell check service is supported on the current platform.
///
/// {@macro dart.ui.window.accessorForwardWarning}
///
/// This option is used by [EditableTextState] to define its
/// [SpellCheckConfiguration] when spell check is enabled, but no spell check
/// service is specified.
bool get nativeSpellCheckServiceDefined => platformDispatcher.nativeSpellCheckServiceDefined;
/// Whether briefly displaying the characters as you type in obscured text
/// fields is enabled in system settings.
///
/// See also:
///
/// * [EditableText.obscureText], which when set to true hides the text in
/// the text field.
bool get brieflyShowPassword => platformDispatcher.brieflyShowPassword;
/// The setting indicating whether time should always be shown in the 24-hour
/// format.
///
/// {@macro dart.ui.window.accessorForwardWarning}
///
/// This option is used by [showTimePicker].
bool get alwaysUse24HourFormat => platformDispatcher.alwaysUse24HourFormat;
/// A callback that is invoked whenever [textScaleFactor] changes value.
///
/// {@macro dart.ui.window.accessorForwardWarning}
///
/// The framework invokes this callback in the same zone in which the
/// callback was set.
///
/// See also:
///
/// * [WidgetsBindingObserver], for a mechanism at the widgets layer to
/// observe when this callback is invoked.
VoidCallback? get onTextScaleFactorChanged => platformDispatcher.onTextScaleFactorChanged;
set onTextScaleFactorChanged(VoidCallback? callback) {
platformDispatcher.onTextScaleFactorChanged = callback;
}
/// The setting indicating the current brightness mode of the host platform.
///
/// {@macro dart.ui.window.accessorForwardWarning}
///
/// If the platform has no preference, [platformBrightness] defaults to
/// [Brightness.light].
Brightness get platformBrightness => platformDispatcher.platformBrightness;
/// A callback that is invoked whenever [platformBrightness] changes value.
///
/// {@macro dart.ui.window.accessorForwardWarning}
///
/// The framework invokes this callback in the same zone in which the
/// callback was set.
///
/// See also:
///
/// * [WidgetsBindingObserver], for a mechanism at the widgets layer to
/// observe when this callback is invoked.
VoidCallback? get onPlatformBrightnessChanged => platformDispatcher.onPlatformBrightnessChanged;
set onPlatformBrightnessChanged(VoidCallback? callback) {
platformDispatcher.onPlatformBrightnessChanged = callback;
}
/// The setting indicating the system font of the host platform.
///
/// {@macro dart.ui.window.accessorForwardWarning}
String? get systemFontFamily => platformDispatcher.systemFontFamily;
/// A callback that is invoked whenever [systemFontFamily] changes value.
///
/// {@macro dart.ui.window.accessorForwardWarning}
///
/// The framework invokes this callback in the same zone in which the
/// callback was set.
///
/// See also:
///
/// * [WidgetsBindingObserver], for a mechanism at the widgets layer to
/// observe when this callback is invoked.
VoidCallback? get onSystemFontFamilyChanged => platformDispatcher.onSystemFontFamilyChanged;
set onSystemFontFamilyChanged(VoidCallback? callback) {
platformDispatcher.onSystemFontFamilyChanged = callback;
}
/// A callback that is invoked to notify the window that it is an appropriate
/// time to provide a scene using the [SceneBuilder] API and the [render]
/// method.
///
/// {@macro dart.ui.window.accessorForwardWarning}
///
/// When possible, this is driven by the hardware VSync signal. This is only
/// called if [scheduleFrame] has been called since the last time this
/// callback was invoked.
///
/// The [onDrawFrame] callback is invoked immediately after [onBeginFrame],
/// after draining any microtasks (e.g. completions of any [Future]s) queued
/// by the [onBeginFrame] handler.
///
/// The framework invokes this callback in the same zone in which the
/// callback was set.
///
/// See also:
///
/// * [SchedulerBinding], the Flutter framework class which manages the
/// scheduling of frames.
/// * [RendererBinding], the Flutter framework class which manages layout and
/// painting.
FrameCallback? get onBeginFrame => platformDispatcher.onBeginFrame;
set onBeginFrame(FrameCallback? callback) {
platformDispatcher.onBeginFrame = callback;
}
/// A callback that is invoked for each frame after [onBeginFrame] has
/// completed and after the microtask queue has been drained.
///
/// {@macro dart.ui.window.accessorForwardWarning}
///
/// This can be used to implement a second phase of frame rendering that
/// happens after any deferred work queued by the [onBeginFrame] phase.
///
/// The framework invokes this callback in the same zone in which the
/// callback was set.
///
/// See also:
///
/// * [SchedulerBinding], the Flutter framework class which manages the
/// scheduling of frames.
/// * [RendererBinding], the Flutter framework class which manages layout and
/// painting.
VoidCallback? get onDrawFrame => platformDispatcher.onDrawFrame;
set onDrawFrame(VoidCallback? callback) {
platformDispatcher.onDrawFrame = callback;
}
/// A callback that is invoked to report the [FrameTiming] of recently
/// rasterized frames.
///
/// {@macro dart.ui.window.accessorForwardWarning}
///
/// It's preferred to use [SchedulerBinding.addTimingsCallback] than to use
/// [PlatformDispatcher.onReportTimings] directly because
/// [SchedulerBinding.addTimingsCallback] allows multiple callbacks.
///
/// This can be used to see if the window has missed frames (through
/// [FrameTiming.buildDuration] and [FrameTiming.rasterDuration]), or high
/// latencies (through [FrameTiming.totalSpan]).
///
/// Unlike [Timeline], the timing information here is available in the release
/// mode (additional to the profile and the debug mode). Hence this can be
/// used to monitor the application's performance in the wild.
///
/// {@macro dart.ui.TimingsCallback.list}
///
/// If this is null, no additional work will be done. If this is not null,
/// Flutter spends less than 0.1ms every 1 second to report the timings
/// (measured on iPhone6S). The 0.1ms is about 0.6% of 16ms (frame budget for
/// 60fps), or 0.01% CPU usage per second.
TimingsCallback? get onReportTimings => platformDispatcher.onReportTimings;
set onReportTimings(TimingsCallback? callback) {
platformDispatcher.onReportTimings = callback;
}
/// A callback that is invoked when pointer data is available.
///
/// {@macro dart.ui.window.accessorForwardWarning}
///
/// The framework invokes this callback in the same zone in which the
/// callback was set.
///
/// See also:
///
/// * [GestureBinding], the Flutter framework class which manages pointer
/// events.
PointerDataPacketCallback? get onPointerDataPacket => platformDispatcher.onPointerDataPacket;
set onPointerDataPacket(PointerDataPacketCallback? callback) {
platformDispatcher.onPointerDataPacket = callback;
}
/// A callback that is invoked when key data is available.
///
/// The framework invokes this callback in the same zone in which the
/// callback was set.
KeyDataCallback? get onKeyData => platformDispatcher.onKeyData;
set onKeyData(KeyDataCallback? callback) {
platformDispatcher.onKeyData = callback;
}
/// The route or path that the embedder requested when the application was
/// launched.
///
/// {@macro dart.ui.window.accessorForwardWarning}
///
/// This will be the string "`/`" if no particular route was requested.
///
/// ## Android
///
/// On Android, the initial route can be set on the [initialRoute](/javadoc/io/flutter/embedding/android/FlutterActivity.NewEngineIntentBuilder.html#initialRoute-java.lang.String-)
/// method of the [FlutterActivity](/javadoc/io/flutter/embedding/android/FlutterActivity.html)'s
/// intent builder.
///
/// On a standalone engine, see https://flutter.dev/docs/development/add-to-app/android/add-flutter-screen#initial-route-with-a-cached-engine.
///
/// ## iOS
///
/// On iOS, the initial route can be set with the
/// [`FlutterViewController.setInitialRoute`](/ios-embedder/interface_flutter_view_controller.html#a7f269c2da73312f856d42611cc12a33f)
/// initializer.
///
/// On a standalone engine, see https://flutter.dev/docs/development/add-to-app/ios/add-flutter-screen#route.
///
/// See also:
///
/// * [Navigator], a widget that handles routing.
/// * [SystemChannels.navigation], which handles subsequent navigation
/// requests from the embedder.
String get defaultRouteName => platformDispatcher.defaultRouteName;
/// Requests that, at the next appropriate opportunity, the [onBeginFrame] and
/// [onDrawFrame] callbacks be invoked.
///
/// {@template dart.ui.window.functionForwardWarning}
/// Calling this function forwards the call to the same function on the
/// [PlatformDispatcher] singleton, so instead of calling it here, you should
/// consider calling it on `WidgetsBinding.instance.platformDispatcher` instead (or, when
/// `WidgetsBinding` isn't available, on [PlatformDispatcher.instance]). The
/// reason this function forwards to the [PlatformDispatcher] is to provide
/// convenience for applications that only use a single main window.
/// {@endtemplate}
///
/// See also:
///
/// * [SchedulerBinding], the Flutter framework class which manages the
/// scheduling of frames.
void scheduleFrame() => platformDispatcher.scheduleFrame();
/// Whether the user has requested that [updateSemantics] be called when
/// the semantic contents of window changes.
///
/// {@macro dart.ui.window.accessorForwardWarning}
///
/// The [onSemanticsEnabledChanged] callback is called whenever this value
/// changes.
bool get semanticsEnabled => platformDispatcher.semanticsEnabled;
/// A callback that is invoked when the value of [semanticsEnabled] changes.
///
/// {@macro dart.ui.window.accessorForwardWarning}
///
/// The framework invokes this callback in the same zone in which the
/// callback was set.
VoidCallback? get onSemanticsEnabledChanged => platformDispatcher.onSemanticsEnabledChanged;
set onSemanticsEnabledChanged(VoidCallback? callback) {
platformDispatcher.onSemanticsEnabledChanged = callback;
}
/// The [FrameData] object for the current frame.
FrameData get frameData => platformDispatcher.frameData;
/// A callback that is invoked when the window updates the [FrameData].
VoidCallback? get onFrameDataChanged => platformDispatcher.onFrameDataChanged;
set onFrameDataChanged(VoidCallback? callback) {
platformDispatcher.onFrameDataChanged = callback;
}
/// Additional accessibility features that may be enabled by the platform.
AccessibilityFeatures get accessibilityFeatures => platformDispatcher.accessibilityFeatures;
/// A callback that is invoked when the value of [accessibilityFeatures] changes.
///
/// {@macro dart.ui.window.accessorForwardWarning}
///
/// The framework invokes this callback in the same zone in which the
/// callback was set.
VoidCallback? get onAccessibilityFeaturesChanged => platformDispatcher.onAccessibilityFeaturesChanged;
set onAccessibilityFeaturesChanged(VoidCallback? callback) {
platformDispatcher.onAccessibilityFeaturesChanged = callback;
}
/// Sends a message to a platform-specific plugin.
///
/// {@macro dart.ui.window.functionForwardWarning}
///
/// The `name` parameter determines which plugin receives the message. The
/// `data` parameter contains the message payload and is typically UTF-8
/// encoded JSON but can be arbitrary data. If the plugin replies to the
/// message, `callback` will be called with the response.
///
/// The framework invokes [callback] in the same zone in which this method
/// was called.
void sendPlatformMessage(String name,
ByteData? data,
PlatformMessageResponseCallback? callback) {
platformDispatcher.sendPlatformMessage(name, data, callback);
}
/// Deprecated. Migrate to [ChannelBuffers.setListener] instead.
///
/// Called whenever this window receives a message from a platform-specific
/// plugin.
///
/// {@macro dart.ui.window.accessorForwardWarning}
///
/// The `name` parameter determines which plugin sent the message. The `data`
/// parameter is the payload and is typically UTF-8 encoded JSON but can be
/// arbitrary data.
///
/// Message handlers must call the function given in the `callback` parameter.
/// If the handler does not need to respond, the handler should pass null to
/// the callback.
///
/// The framework invokes this callback in the same zone in which the
/// callback was set.
@Deprecated(
'Migrate to ChannelBuffers.setListener instead. '
'This feature was deprecated after v3.11.0-20.0.pre.',
)
PlatformMessageCallback? get onPlatformMessage => platformDispatcher.onPlatformMessage;
@Deprecated(
'Migrate to ChannelBuffers.setListener instead. '
'This feature was deprecated after v3.11.0-20.0.pre.',
)
set onPlatformMessage(PlatformMessageCallback? callback) {
platformDispatcher.onPlatformMessage = callback;
}
/// Set the debug name associated with this platform dispatcher's root
/// isolate.
///
/// {@macro dart.ui.window.accessorForwardWarning}
///
/// Normally debug names are automatically generated from the Dart port, entry
/// point, and source file. For example: `main.dart$main-1234`.
///
/// This can be combined with flutter tools `--isolate-filter` flag to debug
/// specific root isolates. For example: `flutter attach --isolate-filter=[name]`.
/// Note that this does not rename any child isolates of the root.
void setIsolateDebugName(String name) => PlatformDispatcher.instance.setIsolateDebugName(name);
}
/// Additional accessibility features that may be enabled by the platform.
///
/// It is not possible to enable these settings from Flutter, instead they are
/// used by the platform to indicate that additional accessibility features are
/// enabled.
//
// When changes are made to this class, the equivalent APIs in each of the
// embedders *must* be updated.
class AccessibilityFeatures {
const AccessibilityFeatures._(this._index);
static const int _kAccessibleNavigationIndex = 1 << 0;
static const int _kInvertColorsIndex = 1 << 1;
static const int _kDisableAnimationsIndex = 1 << 2;
static const int _kBoldTextIndex = 1 << 3;
static const int _kReduceMotionIndex = 1 << 4;
static const int _kHighContrastIndex = 1 << 5;
static const int _kOnOffSwitchLabelsIndex = 1 << 6;
// A bitfield which represents each enabled feature.
final int _index;
/// Whether there is a running accessibility service which is changing the
/// interaction model of the device.
///
/// For example, TalkBack on Android and VoiceOver on iOS enable this flag.
bool get accessibleNavigation => _kAccessibleNavigationIndex & _index != 0;
/// The platform is inverting the colors of the application.
bool get invertColors => _kInvertColorsIndex & _index != 0;
/// The platform is requesting that animations be disabled or simplified.
bool get disableAnimations => _kDisableAnimationsIndex & _index != 0;
/// The platform is requesting that text be rendered at a bold font weight.
///
/// Only supported on iOS and Android API 31+.
bool get boldText => _kBoldTextIndex & _index != 0;
/// The platform is requesting that certain animations be simplified and
/// parallax effects removed.
///
/// Only supported on iOS.
bool get reduceMotion => _kReduceMotionIndex & _index != 0;
/// The platform is requesting that UI be rendered with darker colors.
///
/// Only supported on iOS.
bool get highContrast => _kHighContrastIndex & _index != 0;
/// The platform is requesting to show on/off labels inside switches.
///
/// Only supported on iOS.
bool get onOffSwitchLabels => _kOnOffSwitchLabelsIndex & _index != 0;
@override
String toString() {
final List<String> features = <String>[];
if (accessibleNavigation) {
features.add('accessibleNavigation');
}
if (invertColors) {
features.add('invertColors');
}
if (disableAnimations) {
features.add('disableAnimations');
}
if (boldText) {
features.add('boldText');
}
if (reduceMotion) {
features.add('reduceMotion');
}
if (highContrast) {
features.add('highContrast');
}
if (onOffSwitchLabels) {
features.add('onOffSwitchLabels');
}
return 'AccessibilityFeatures$features';
}
@override
bool operator ==(Object other) {
if (other.runtimeType != runtimeType) {
return false;
}
return other is AccessibilityFeatures
&& other._index == _index;
}
@override
int get hashCode => _index.hashCode;
}
/// Describes the contrast of a theme or color palette.
enum Brightness {
/// The color is dark and will require a light text color to achieve readable
/// contrast.
///
/// For example, the color might be dark grey, requiring white text.
dark,
/// The color is light and will require a dark text color to achieve readable
/// contrast.
///
/// For example, the color might be bright white, requiring black text.
light,
}
/// Deprecated. Will be removed in a future version of Flutter.
///
/// This global property is deprecated to prepare for Flutter's upcoming support
/// for multiple views and multiple windows.
///
/// It represents the main view for applications where there is only one
/// view, such as applications designed for single-display mobile devices.
/// If the embedder supports multiple views, it points to the first view
/// created which is assumed to be the main view. It throws if no view has
/// been created yet or if the first view has been removed again.
///
/// The following options exists to migrate code that relies on accessing
/// this deprecated property:
///
/// If a [BuildContext] is available, consider looking up the current
/// [FlutterView] associated with that context via [View.of]. It gives access
/// to the same functionality as this deprecated property. However, the
/// platform-specific functionality has moved to the [PlatformDispatcher],
/// which may be accessed from the view returned by [View.of] via
/// [FlutterView.platformDispatcher]. Using [View.of] with a [BuildContext] is
/// the preferred option to migrate away from this deprecated [window]
/// property.
///
/// If no context is available to look up a [FlutterView], the
/// [PlatformDispatcher] can be used directly for platform-specific
/// functionality. It also maintains a list of all available [FlutterView]s in
/// [PlatformDispatcher.views] to access view-specific functionality without a
/// context. If possible, consider accessing the [PlatformDispatcher] via the
/// binding (e.g. `WidgetsBinding.instance.platformDispatcher`) instead of the
/// static singleton [PlatformDispatcher.instance]. See
/// [PlatformDispatcher.instance] for more information about why this is
/// preferred.
///
/// See also:
///
/// * [FlutterView], which gives an application access to view-specific
/// functionality.
/// * [PlatformDispatcher], which gives an application access to
/// platform-specific functionality.
/// * [PlatformDispatcher.views], for a list of all available views.
@Deprecated(
'Look up the current FlutterView from the context via View.of(context) or consult the PlatformDispatcher directly instead. '
'Deprecated to prepare for the upcoming multi-window support. '
'This feature was deprecated after v3.7.0-32.0.pre.'
)
final SingletonFlutterWindow window = SingletonFlutterWindow._();
/// Additional data available on each flutter frame.
class FrameData {
const FrameData._({this.frameNumber = -1});
/// The number of the current frame.
///
/// This number monotonically increases, but doesn't necessarily
/// start at a particular value.
///
/// If not provided, defaults to -1.
final int frameNumber;
}
/// Platform specific configuration for gesture behavior, such as touch slop.
///
/// These settings are provided via [FlutterView.gestureSettings] to each
/// view, and should be favored for configuring gesture behavior over the
/// framework constants.
///
/// A `null` field indicates that the platform or view does not have a preference
/// and the fallback constants should be used instead.
class GestureSettings {
/// Create a new [GestureSettings] value.
///
/// Consider using [GestureSettings.copyWith] on an existing settings object
/// to ensure that newly added fields are correctly set.
const GestureSettings({
this.physicalTouchSlop,
this.physicalDoubleTapSlop,
});
/// The number of physical pixels a pointer is allowed to drift before it is
/// considered an intentional movement.
///
/// If `null`, the framework's default touch slop configuration should be used
/// instead.
final double? physicalTouchSlop;
/// The number of physical pixels that the first and second tap of a double tap
/// can drift apart to still be recognized as a double tap.
///
/// If `null`, the framework's default double tap slop configuration should be used
/// instead.
final double? physicalDoubleTapSlop;
/// Create a new [GestureSettings] object from an existing value, overwriting
/// all of the provided fields.
GestureSettings copyWith({
double? physicalTouchSlop,
double? physicalDoubleTapSlop,
}) {
return GestureSettings(
physicalTouchSlop: physicalTouchSlop ?? this.physicalTouchSlop,
physicalDoubleTapSlop: physicalDoubleTapSlop ?? this.physicalDoubleTapSlop,
);
}
@override
bool operator ==(Object other) {
if (other.runtimeType != runtimeType) {
return false;
}
return other is GestureSettings &&
other.physicalTouchSlop == physicalTouchSlop &&
other.physicalDoubleTapSlop == physicalDoubleTapSlop;
}
@override
int get hashCode => Object.hash(physicalTouchSlop, physicalDoubleTapSlop);
@override
String toString() => 'GestureSettings(physicalTouchSlop: $physicalTouchSlop, physicalDoubleTapSlop: $physicalDoubleTapSlop)';
}
| engine/lib/ui/window.dart/0 | {
"file_path": "engine/lib/ui/window.dart",
"repo_id": "engine",
"token_count": 12997
} | 278 |
// 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/lib/ui/window/platform_message_response_dart_port.h"
#include <array>
#include <utility>
#include "flutter/common/task_runners.h"
#include "flutter/fml/make_copyable.h"
#include "flutter/fml/trace_event.h"
#include "third_party/dart/runtime/include/dart_native_api.h"
#include "third_party/tonic/converter/dart_converter.h"
#include "third_party/tonic/dart_state.h"
#include "third_party/tonic/logging/dart_invoke.h"
#include "third_party/tonic/typed_data/dart_byte_data.h"
namespace flutter {
PlatformMessageResponseDartPort::PlatformMessageResponseDartPort(
Dart_Port send_port,
int64_t identifier,
const std::string& channel)
: send_port_(send_port), identifier_(identifier), channel_(channel) {
FML_DCHECK(send_port != ILLEGAL_PORT);
}
void PlatformMessageResponseDartPort::Complete(
std::unique_ptr<fml::Mapping> data) {
is_complete_ = true;
Dart_CObject response_identifier = {
.type = Dart_CObject_kInt64,
};
response_identifier.value.as_int64 = identifier_;
Dart_CObject response_data = {
.type = Dart_CObject_kTypedData,
};
response_data.value.as_typed_data.type = Dart_TypedData_kUint8;
response_data.value.as_typed_data.length = data->GetSize();
response_data.value.as_typed_data.values = data->GetMapping();
std::array<Dart_CObject*, 2> response_values = {&response_identifier,
&response_data};
Dart_CObject response = {
.type = Dart_CObject_kArray,
};
response.value.as_array.length = response_values.size();
response.value.as_array.values = response_values.data();
bool did_send = Dart_PostCObject(send_port_, &response);
FML_CHECK(did_send);
}
void PlatformMessageResponseDartPort::CompleteEmpty() {
is_complete_ = true;
Dart_CObject response = {
.type = Dart_CObject_kNull,
};
bool did_send = Dart_PostCObject(send_port_, &response);
FML_CHECK(did_send);
}
} // namespace flutter
| engine/lib/ui/window/platform_message_response_dart_port.cc/0 | {
"file_path": "engine/lib/ui/window/platform_message_response_dart_port.cc",
"repo_id": "engine",
"token_count": 805
} | 279 |
# Flutter Web Engine
This directory contains the source code for the Web Engine.
## Hacking on the Web Engine
If you are setting up a workspace for the first time, start by following the
instructions at [Setting up the Engine development environment][1]. In addition,
it is useful to add the following to your `PATH` environment variable:
- `ENGINE_ROOT/src/flutter/lib/web_ui/dev`, so you can run the `felt` command
from anywhere.
- `FLUTTER_ROOT/bin`, so you can run `dart` and `flutter` commands from
anywhere.
### Using `felt`
`felt` (stands for "Flutter Engine Local Tester") is a command-line tool that
aims to make development in the Flutter web engine more productive and pleasant.
To tell `felt` to do anything you call `felt SUBCOMMAND`, where `SUBCOMMAND` is
one of the available subcommands, which can be listed by running `felt help`. To
get help for a specific subcommand, run `felt help SUBCOMMAND`.
#### `felt build`
The `build` subcommand builds web engine gn/ninja targets. Targets can be
individually specified in the command line invocation, or if none are specified,
all web engine targets are built. Common targets are as follows:
* `sdk` - The flutter_web_sdk itself.
* `canvaskit` - Flutter's version of canvakit.
* `canvaskit_chromium` - A version of canvaskit optimized for use with
chromium-based browsers.
* `skwasm` - Builds experimental skia wasm module renderer.
The output of these steps is used in unit tests, and can be used with the flutter
command via the `--local-web-sdk=wasm_release` command.
The `build` command also accepts either the `--profile` or `--debug` flags, which
can be used to change the build profile of the artifacts.
##### Examples
Builds all web engine targets, then runs a Flutter app using it:
```
felt build
cd path/to/some/app
flutter --local-web-sdk=wasm_release run -d chrome
```
Builds only the `sdk` and the `canvaskit` targets:
```
felt build sdk canvaskit
```
#### `felt test`
The `test` subcommand will compile and/or run web engine unit test suites. For
information on how test suites are structured, see the test configuration
[readme][2].
By default, `felt test` compiles and runs all suites that are compatible with the
host system. Some useful flags supported by this command:
* Action flags which say what parts of the test pipeline to perform. More of one
of these can be specified to run multiple actions. If none are specified, then
*all* of these actions are performed
* `--compile` performs compilation of the test bundles.
* `--run` runs the unit tests
* `--copy-artifacts` will copy build artifacts needed for the tests to run.
* The `--profile` or `--debug` flags can be specified to copy over artifacts
from the profile or debug build folders instead of release.
* `--list` will list all the test suites and test bundles and exit without
compiling or running anything.
* `--verbose` will output some extra information that may be useful for debugging.
* `--start-paused` will open a browser window and pause the tests before starting
so that breakpoints can be set before starting the test suites.
Several other flags can be passed that filter which test suites should be run:
* `--browser` runs only the test suites that test on the browsers passed. Valid
values for this are `chrome`, `firefox`, `safari`, or `edge`.
* `--compiler` runs only the test suites that use a particular compiler. Valid
values for this are `dart2js` or `dart2wasm`
* `--renderer` runs only the test suites that use a particular renderer. Valid
values for this are `html`, `canvakit`, or `skwasm`
* `--suite` runs a suite by name.
* `--bundle` runs suites that target a particular test bundle.
Filters of different types are logically ANDed together, but multiple filter flags
of the same type are logically ORed together.
The `test` command will also accept a list of paths to specific test files to be
compiled and run. If none of these paths are specified, all tests are run, otherwise
only the tests that are specified will run.
##### Examples
Runs all test suites in all compatible browsers:
```
felt test
```
Runs a specific test on all compatible browsers:
```
felt test test/engine/util_test.dart
```
Runs multiple specific tests on all compatible browsers:
```
felt test test/engine/util_test.dart test/engine/alarm_clock_test.dart
```
Runs only test suites that compile via dart2wasm:
```
felt test --compiler dart2wasm
```
Runs only test suites that run in Chrome and Safari:
```
felt test --browser chrome --browser safari
```
### Optimizing local builds
Concurrency of various build steps can be configured via environment variables:
- `FELT_COMPILE_CONCURRENCY` specifies the number of concurrent compiler
processes used to compile tests. Default value is 8.
If you are a Google employee, you can use an internal instance of Goma (go/ma)
to parallelize your ninja builds. Because Goma compiles code on remote servers,
this option is particularly effective for building on low-powered laptops.
### Test browsers
Chromium, Firefox, and Safari for iOS are version-locked using the
[browser_lock.yaml][3] configuration file. Safari for macOS is supplied by the
computer's operating system. Tests can be run in Edge locally, but Edge is not
enabled on LUCI. Chromium is used as a proxy for Chrome, Edge, and other
Chromium-based browsers.
Changing parameters in the browser lock is effective immediately when running
tests locally. To make changes effective on LUCI follow instructions in
[Rolling Browsers][#rolling-browsers].
### Rolling browsers
When running tests on LUCI using Chrome, LUCI uses the version of Chrome for
Testing fetched from CIPD.
Since the engine code and infra recipes do not live in the same repository
there are few steps to follow in order to upgrade a browser's version.
### Rolling fallback fonts
To generate new fallback font data and push the fallback fonts into a CIPD
package for engine unit tests to consume, run the following felt command:
```
cipd auth-login
felt roll-fallback-fonts --key=<Google Fonts API key>
```
You can obtain a GoogleFonts API key from here: https://developers.google.com/fonts/docs/developer_api#APIKey
This will take the following steps:
* Fetch a list of fonts from the Google Fonts API
* Download each font we use for fallbacks and calculate its unicode ranges
* Generate the `font_fallback_data.dart` file that is used in the engine
* Push the fonts up to a CIPD package called `flutter/flutter_font_fallbacks`
* Update the `DEPS` file in the engine to use the new version of the package
To perform all these steps except actually uploading the package to CIPD, pass
the `--dry-run` flag to the felt command.
NOTE: Because this script uses `fc-config`, this roll step only actually works
on Linux, not on macOS or Windows.
#### Chrome for Testing
Chrome for Testing is an independent project that gets rolled into Flutter
manually, and as needed. Flutter consumes a pre-built Chrome for Testing build.
The available versions of Chrome for Testing available can be found [here](https://googlechromelabs.github.io/chrome-for-testing/). To roll to a newer version:
- Make sure you have `depot_tools` installed (if you are regularly hacking on
the engine code, you probably do).
- If not already authenticated with CIPD, run `cipd auth-login` and follow
instructions (this step requires sufficient privileges; contact
#hackers-infra-🌡 on [Flutter's Discord server](https://github.com/flutter/flutter/wiki/Chat)).
- Edit `dev/browser_lock.yaml` and update the following values under `chrome`:
- Set `version` to the full four part version number of the build of Chrome
for Testing you want to roll (for example, `118.0.5993.70`)
- Run `dart dev/browser_roller.dart` and make sure it completes successfully.
The script uploads the specified versions of Chromium (and Chromedriver) to the
right locations in CIPD: [Chrome](https://chrome-infra-packages.appspot.com/p/flutter_internal/browsers/chrome),
[Chromedriver](https://chrome-infra-packages.appspot.com/p/flutter_internal/browser-drivers/chrome).
- Send a pull request containing the above file changes. Newer versions of Chromium
might break some tests or Goldens. Get those fixed too!
If you have questions, contact the Flutter Web team on Flutter Discord on the
\#hackers-web-🌍 channel.
#### Firefox
We test with Firefox on LUCI in the Linux Web Engine builder. The process for
rolling Firefox is even easier than Chromium. Simply update `browser_lock.yaml`
with the latest version of Firefox, and run `browser_roller.dart`.
#### .ci.yaml
After rolling Chrome and/or Firefox, also update the CI dependencies in
`.ci.yaml` to make use of the new versions. The lines look like
```yaml
dependencies: >-
[
{"dependency": "chrome_and_driver", "version": "version:107.0"},
{"dependency": "firefox", "version": "version:83.0"},
{"dependency": "goldctl", "version": "git_revision:720a542f6fe4f92922c3b8f0fdcc4d2ac6bb83cd"}
]
```
##### **browser_roller.dart**
The script has the following command-line options:
- `--dry-run` - The script will stop before uploading artifacts to CIPD. The location of the data will be reported at the end of the script, if the script finishes successfullyThe output of the script will be visible in /tmp/browser-roll-RANDOM_STRING
- `--verbose` - Greatly increase the amount of information printed to `stdout` by the script.
> Try the following!
>
> ```bash
> dart ./dev/browser_roller.dart --dry-run --verbose
> ```
#### **Other browsers / manual upload**
In general, the manual process goes like this:
1. Dowload the binaries for the new browser/driver for each operating system
(macOS, linux, windows).
2. Create CIPD packages for these packages (more documentation is available for
Googlers at go/cipd-flutter-web)
3. Update the version in this repo. Do this by changing the related fields in
`browser_lock.yaml` file.
Resources:
1. Browser and driver CIPD [packages][4] (requires special access; ping
hackers-infra on Discord for more information)
2. LUCI web [recipe][5]
3. More general reading on CIPD packages [link][6]
### Configuration files
`browser_lock.yaml` contains the version of browsers we use to test Flutter for
web. Versions are not automatically updated whenever a new release is available.
Instead, we update this file manually once in a while.
`canvaskit_lock.yaml` locks the version of CanvasKit for tests and production
use.
## Building CanvasKit
To build CanvasKit locally, you must first set up your gclient config to
activate the Emscripten SDK, which is the toolchain used to build CanvasKit.
To do this, replace the contents of your .gclient file at the root of the
project (i.e. in the parent directory of the `src` directory) with:
```
solutions = [
{
"managed": False,
"name": "src/flutter",
"url": "[email protected]:<your_username_here>/engine.git",
"custom_deps": {},
"deps_file": "DEPS",
"safesync_url": "",
"custom_vars": {
"download_emsdk": True,
},
},
]
```
Now run `gclient sync` and it should pull in the Emscripten SDK and activate it.
To build CanvasKit with `felt`, run:
```
felt build --build-canvaskit
```
This will build CanvasKit in `out/wasm_debug`. If you now run
```
felt test
```
it will detect that you have built CanvasKit and use that instead of the one
from CIPD to run the tests against.
### Upgrading the Emscripten SDK for the CanvasKit build
The version of the Emscripten SDK should be kept up to date with the version
used in the Skia build. That version can be found in
`third_party/skia/bin/activate-emsdk`. It will probably also be necessary to
roll the dependency on `third_party/emsdk` in DEPS to the same version as in
`third_party/skia/DEPS`.
Once you know the version for the Emscripten SDK, change the line in
`tools/activate_emsdk.py` which defines `EMSDK_VERSION` to match Skia.
[1]: https://github.com/flutter/flutter/wiki/Setting-up-the-Engine-development-environment
[2]: https://github.com/flutter/flutter/blob/main/lib/web_ui/test/README
[3]: https://github.com/flutter/engine/blob/main/lib/web_ui/dev/browser_lock.yaml
[4]: https://chrome-infra-packages.appspot.com/p/flutter_internal
[5]: https://cs.opensource.google/flutter/recipes/+/master:recipes/engine/web_engine.py
[6]: https://chromium.googlesource.com/chromium/src.git/+/main/docs/cipd_and_3pp.md#What-is-CIPD
## Unicode properties
We pull the unicode properties we need from `third_party/web_unicode`. See `third_party/web_unicode/README.md` for more details on how we generate Dart code from unicode properties.
| engine/lib/web_ui/README.md/0 | {
"file_path": "engine/lib/web_ui/README.md",
"repo_id": "engine",
"token_count": 3748
} | 280 |
// 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 'dart:async';
import 'dart:io' as io;
import 'package:http/http.dart';
import 'package:path/path.dart' as path;
import 'common.dart';
import 'environment.dart';
import 'package_lock.dart';
/// Returns the installation of Edge.
///
/// Currently uses the Edge version installed on the operating system.
///
/// As explained on the Microsoft help page: `Microsoft Edge comes
/// exclusively with Windows 10 and cannot be downloaded or installed separately.`
/// See: https://support.microsoft.com/en-us/help/17171/microsoft-edge-get-to-know
///
// TODO(yjbanov): Investigate running tests for the tech preview downloads
// from the beta channel.
Future<BrowserInstallation> getEdgeInstallation(
String requestedVersion, {
StringSink? infoLog,
}) async {
// For now these tests are aimed to run only on Windows machines local or on LUCI/CI.
// In the future we can investigate to run them on Android or on MacOS.
if (!io.Platform.isWindows) {
throw UnimplementedError(
'Tests for Edge on ${io.Platform.operatingSystem} is'
' not supported.');
}
infoLog ??= io.stdout;
if (requestedVersion == 'system') {
// Since Edge is included in Windows, always assume there will be one on the
// system.
infoLog.writeln('Using the system version that is already installed.');
final EdgeLauncher edgeLauncher = EdgeLauncher();
if (edgeLauncher.isInstalled) {
infoLog.writeln('Launcher installation was skipped, already installed.');
} else {
infoLog.writeln('Installing MicrosoftEdgeLauncher');
await edgeLauncher.install();
infoLog.writeln(
'Installations complete. To launch it run ${edgeLauncher.executable}');
}
return BrowserInstallation(
version: 'system',
executable: io.Directory(path.join(
edgeLauncher.launcherInstallationDir.path,
PlatformBinding.instance.getCommandToRunEdge()))
.path,
);
} else {
infoLog.writeln('Unsupported version $requestedVersion.');
throw UnimplementedError();
}
}
/// `MicrosoftEdgeLauncher` is an executable for launching Edge.
///
/// It is useful for starting Edge from comand line or from a
/// batch script.
///
/// See: https://github.com/MicrosoftEdge/edge-launcher
class EdgeLauncher {
EdgeLauncher();
/// Path to the directory that contains `MicrosoftEdgeLauncher.exe`.
io.Directory get launcherInstallationDir => io.Directory(
path.join(environment.webUiDartToolDir.path, 'microsoftedgelauncher',
version),
);
io.File get executable => io.File(
path.join(launcherInstallationDir.path, 'MicrosoftEdgeLauncher.exe'));
bool get isInstalled => executable.existsSync();
/// Version number launcher executable `MicrosoftEdgeLauncher`.
String get version => packageLock.edgeLock.launcherVersion;
/// Url for downloading `MicrosoftEdgeLauncher`.
///
/// Only useful in Windows, hence not added to [PlatformBinding].
String get windowsEdgeLauncherDownloadUrl =>
'https://github.com/MicrosoftEdge/edge-launcher/releases/download/$version/MicrosoftEdgeLauncher.exe';
/// Install the launcher if it does not exist in this system.
Future<void> install() async {
// Checks if the `MicrosoftEdgeLauncher` executable exists.
if (isInstalled) {
return;
}
// Create directory for download.
if (!launcherInstallationDir.existsSync()) {
launcherInstallationDir.createSync(recursive: true);
}
final Client client = Client();
try {
// Download executable from Github.
final StreamedResponse download = await client.send(Request(
'GET',
Uri.parse(windowsEdgeLauncherDownloadUrl),
));
await download.stream.pipe(executable.openWrite());
} finally {
client.close();
}
}
}
| engine/lib/web_ui/dev/edge_installation.dart/0 | {
"file_path": "engine/lib/web_ui/dev/edge_installation.dart",
"repo_id": "engine",
"token_count": 1279
} | 281 |
// 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 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:test_api/backend.dart';
import 'webdriver_browser.dart';
/// Provides an environment for the desktop variant of Safari running on macOS.
class SafariMacOsEnvironment extends WebDriverBrowserEnvironment {
@override
final String name = 'Safari macOS';
@override
Runtime get packageTestRuntime => Runtime.safari;
@override
String get packageTestConfigurationYamlFile => 'dart_test_safari.yaml';
@override
Uri get driverUri => Uri(scheme: 'http', host: 'localhost', port: portNumber);
late Process _driverProcess;
int _retryCount = 0;
static const int _waitBetweenRetryInSeconds = 1;
static const int _maxRetryCount = 10;
@override
Future<Process> spawnDriverProcess() => Process.start('safaridriver', <String>['-p', portNumber.toString()]);
@override
Future<void> prepare() async {
await _startDriverProcess();
}
/// Pick an unused port and start `safaridriver` using that port.
///
/// On macOS 13, starting `safaridriver` can be flaky so if it returns an
/// "Operation not permitted" error, kill the `safaridriver` process and try
/// again with a different port. Wait [_waitBetweenRetryInSeconds] seconds
/// between retries. Try up to [_maxRetryCount] times.
Future<void> _startDriverProcess() async {
_retryCount += 1;
if (_retryCount > 1) {
await Future<void>.delayed(const Duration(seconds: _waitBetweenRetryInSeconds));
}
portNumber = await pickUnusedPort();
print('Attempt $_retryCount to start safaridriver on port $portNumber');
_driverProcess = await spawnDriverProcess();
_driverProcess.stderr
.transform(utf8.decoder)
.transform(const LineSplitter())
.listen((String error) {
print('[Webdriver][Error] $error');
if (_retryCount > _maxRetryCount) {
print('[Webdriver][Error] Failed to start after $_maxRetryCount tries.');
} else if (error.contains('Operation not permitted')) {
_driverProcess.kill();
_startDriverProcess();
}
});
_driverProcess.stdout
.transform(utf8.decoder)
.transform(const LineSplitter())
.listen((String log) {
print('[Webdriver] $log');
});
}
@override
Future<void> cleanup() async {
_driverProcess.kill();
}
}
| engine/lib/web_ui/dev/safari_macos.dart/0 | {
"file_path": "engine/lib/web_ui/dev/safari_macos.dart",
"repo_id": "engine",
"token_count": 853
} | 282 |
// 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.
part of ui;
double clampDouble(double x, double min, double max) {
assert(min <= max && !max.isNaN && !min.isNaN);
if (x < min) {
return min;
}
if (x > max) {
return max;
}
if (x.isNaN) {
return max;
}
return x;
}
| engine/lib/web_ui/lib/math.dart/0 | {
"file_path": "engine/lib/web_ui/lib/math.dart",
"repo_id": "engine",
"token_count": 152
} | 283 |
// 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 'dart:typed_data';
import 'package:ui/ui.dart' as ui;
import '../validators.dart';
import '../vector_math.dart';
import 'canvas.dart';
import 'canvaskit_api.dart';
import 'image.dart';
import 'painting.dart';
import 'path.dart';
import 'picture.dart';
import 'picture_recorder.dart';
import 'text.dart';
import 'vertices.dart';
/// An implementation of [ui.Canvas] that is backed by a CanvasKit canvas.
class CanvasKitCanvas implements ui.Canvas {
factory CanvasKitCanvas(ui.PictureRecorder recorder, [ui.Rect? cullRect]) {
if (recorder.isRecording) {
throw ArgumentError(
'"recorder" must not already be associated with another Canvas.');
}
cullRect ??= ui.Rect.largest;
final CkPictureRecorder ckRecorder = recorder as CkPictureRecorder;
return CanvasKitCanvas._(ckRecorder.beginRecording(cullRect));
}
CanvasKitCanvas._(this._canvas);
final CkCanvas _canvas;
@override
void save() {
_canvas.save();
}
@override
void saveLayer(ui.Rect? bounds, ui.Paint paint) {
if (bounds == null) {
_saveLayerWithoutBounds(paint);
} else {
assert(rectIsValid(bounds));
_saveLayer(bounds, paint);
}
}
void _saveLayerWithoutBounds(ui.Paint paint) {
_canvas.saveLayerWithoutBounds(paint as CkPaint);
}
void _saveLayer(ui.Rect bounds, ui.Paint paint) {
_canvas.saveLayer(bounds, paint as CkPaint);
}
@override
void restore() {
_canvas.restore();
}
@override
void restoreToCount(int count) {
_canvas.restoreToCount(count);
}
@override
int getSaveCount() {
return _canvas.saveCount!;
}
@override
void translate(double dx, double dy) {
_canvas.translate(dx, dy);
}
@override
void scale(double sx, [double? sy]) => _scale(sx, sy ?? sx);
void _scale(double sx, double sy) {
_canvas.scale(sx, sy);
}
@override
void rotate(double radians) {
_canvas.rotate(radians);
}
@override
void skew(double sx, double sy) {
_canvas.skew(sx, sy);
}
@override
void transform(Float64List matrix4) {
if (matrix4.length != 16) {
throw ArgumentError('"matrix4" must have 16 entries.');
}
_transform(toMatrix32(matrix4));
}
void _transform(Float32List matrix4) {
_canvas.transform(matrix4);
}
@override
Float64List getTransform() {
return toMatrix64(_canvas.getLocalToDevice());
}
@override
void clipRect(ui.Rect rect,
{ui.ClipOp clipOp = ui.ClipOp.intersect, bool doAntiAlias = true}) {
assert(rectIsValid(rect));
_clipRect(rect, clipOp, doAntiAlias);
}
void _clipRect(ui.Rect rect, ui.ClipOp clipOp, bool doAntiAlias) {
_canvas.clipRect(rect, clipOp, doAntiAlias);
}
@override
void clipRRect(ui.RRect rrect, {bool doAntiAlias = true}) {
assert(rrectIsValid(rrect));
_clipRRect(rrect, doAntiAlias);
}
void _clipRRect(ui.RRect rrect, bool doAntiAlias) {
_canvas.clipRRect(rrect, doAntiAlias);
}
@override
void clipPath(ui.Path path, {bool doAntiAlias = true}) {
_canvas.clipPath(path as CkPath, doAntiAlias);
}
@override
ui.Rect getLocalClipBounds() {
final Matrix4 transform = Matrix4.fromFloat32List(_canvas.getLocalToDevice());
if (transform.invert() == 0) {
// non-invertible transforms collapse space to a line or point
return ui.Rect.zero;
}
return transform.transformRect(_canvas.getDeviceClipBounds());
}
@override
ui.Rect getDestinationClipBounds() {
return _canvas.getDeviceClipBounds();
}
@override
void drawColor(ui.Color color, ui.BlendMode blendMode) {
_drawColor(color, blendMode);
}
void _drawColor(ui.Color color, ui.BlendMode blendMode) {
_canvas.drawColor(color, blendMode);
}
@override
void drawLine(ui.Offset p1, ui.Offset p2, ui.Paint paint) {
assert(offsetIsValid(p1));
assert(offsetIsValid(p2));
_drawLine(p1, p2, paint);
}
void _drawLine(ui.Offset p1, ui.Offset p2, ui.Paint paint) {
_canvas.drawLine(p1, p2, paint as CkPaint);
}
@override
void drawPaint(ui.Paint paint) {
_drawPaint(paint);
}
void _drawPaint(ui.Paint paint) {
_canvas.drawPaint(paint as CkPaint);
}
@override
void drawRect(ui.Rect rect, ui.Paint paint) {
assert(rectIsValid(rect));
_drawRect(rect, paint);
}
void _drawRect(ui.Rect rect, ui.Paint paint) {
_canvas.drawRect(rect, paint as CkPaint);
}
@override
void drawRRect(ui.RRect rrect, ui.Paint paint) {
assert(rrectIsValid(rrect));
_drawRRect(rrect, paint);
}
void _drawRRect(ui.RRect rrect, ui.Paint paint) {
_canvas.drawRRect(rrect, paint as CkPaint);
}
@override
void drawDRRect(ui.RRect outer, ui.RRect inner, ui.Paint paint) {
assert(rrectIsValid(outer));
assert(rrectIsValid(inner));
_drawDRRect(outer, inner, paint);
}
void _drawDRRect(ui.RRect outer, ui.RRect inner, ui.Paint paint) {
_canvas.drawDRRect(outer, inner, paint as CkPaint);
}
@override
void drawOval(ui.Rect rect, ui.Paint paint) {
assert(rectIsValid(rect));
_drawOval(rect, paint);
}
void _drawOval(ui.Rect rect, ui.Paint paint) {
_canvas.drawOval(rect, paint as CkPaint);
}
@override
void drawCircle(ui.Offset c, double radius, ui.Paint paint) {
assert(offsetIsValid(c));
_drawCircle(c, radius, paint);
}
void _drawCircle(ui.Offset c, double radius, ui.Paint paint) {
_canvas.drawCircle(c, radius, paint as CkPaint);
}
@override
void drawArc(ui.Rect rect, double startAngle, double sweepAngle,
bool useCenter, ui.Paint paint) {
assert(rectIsValid(rect));
_drawArc(rect, startAngle, sweepAngle, useCenter, paint);
}
void _drawArc(ui.Rect rect, double startAngle, double sweepAngle,
bool useCenter, ui.Paint paint) {
_canvas.drawArc(rect, startAngle, sweepAngle, useCenter, paint as CkPaint);
}
@override
void drawPath(ui.Path path, ui.Paint paint) {
_canvas.drawPath(path as CkPath, paint as CkPaint);
}
@override
void drawImage(ui.Image image, ui.Offset p, ui.Paint paint) {
assert(offsetIsValid(p));
_canvas.drawImage(image as CkImage, p, paint as CkPaint);
}
@override
void drawImageRect(ui.Image image, ui.Rect src, ui.Rect dst, ui.Paint paint) {
assert(rectIsValid(src));
assert(rectIsValid(dst));
_canvas.drawImageRect(image as CkImage, src, dst, paint as CkPaint);
}
@override
void drawImageNine(
ui.Image image, ui.Rect center, ui.Rect dst, ui.Paint paint) {
assert(rectIsValid(center));
assert(rectIsValid(dst));
_canvas.drawImageNine(image as CkImage, center, dst, paint as CkPaint);
}
@override
void drawPicture(ui.Picture picture) {
_canvas.drawPicture(picture as CkPicture);
}
@override
void drawParagraph(ui.Paragraph paragraph, ui.Offset offset) {
assert(offsetIsValid(offset));
_drawParagraph(paragraph, offset);
}
void _drawParagraph(ui.Paragraph paragraph, ui.Offset offset) {
_canvas.drawParagraph(paragraph as CkParagraph, offset);
}
@override
void drawPoints(
ui.PointMode pointMode, List<ui.Offset> points, ui.Paint paint) {
final SkFloat32List skPoints = toMallocedSkPoints(points);
_canvas.drawPoints(
paint as CkPaint,
pointMode,
skPoints.toTypedArray(),
);
free(skPoints);
}
@override
void drawRawPoints(
ui.PointMode pointMode, Float32List points, ui.Paint paint) {
if (points.length % 2 != 0) {
throw ArgumentError('"points" must have an even number of values.');
}
_canvas.drawPoints(
paint as CkPaint,
pointMode,
points,
);
}
@override
void drawVertices(
ui.Vertices vertices, ui.BlendMode blendMode, ui.Paint paint) {
_canvas.drawVertices(vertices as CkVertices, blendMode, paint as CkPaint);
}
@override
void drawAtlas(
ui.Image atlas,
List<ui.RSTransform> transforms,
List<ui.Rect> rects,
List<ui.Color>? colors,
ui.BlendMode? blendMode,
ui.Rect? cullRect,
ui.Paint paint) {
assert(colors == null || colors.isEmpty || blendMode != null);
final int rectCount = rects.length;
if (transforms.length != rectCount) {
throw ArgumentError('"transforms" and "rects" lengths must match.');
}
if (colors != null && colors.isNotEmpty && colors.length != rectCount) {
throw ArgumentError(
'If non-null, "colors" length must match that of "transforms" and "rects".');
}
final Float32List rstTransformBuffer = Float32List(rectCount * 4);
final Float32List rectBuffer = Float32List(rectCount * 4);
for (int i = 0; i < rectCount; ++i) {
final int index0 = i * 4;
final int index1 = index0 + 1;
final int index2 = index0 + 2;
final int index3 = index0 + 3;
final ui.RSTransform rstTransform = transforms[i];
final ui.Rect rect = rects[i];
assert(rectIsValid(rect));
rstTransformBuffer[index0] = rstTransform.scos;
rstTransformBuffer[index1] = rstTransform.ssin;
rstTransformBuffer[index2] = rstTransform.tx;
rstTransformBuffer[index3] = rstTransform.ty;
rectBuffer[index0] = rect.left;
rectBuffer[index1] = rect.top;
rectBuffer[index2] = rect.right;
rectBuffer[index3] = rect.bottom;
}
final Uint32List? colorBuffer =
(colors == null || colors.isEmpty) ? null : toFlatColors(colors);
_drawAtlas(paint, atlas, rstTransformBuffer, rectBuffer, colorBuffer,
blendMode ?? ui.BlendMode.src);
}
@override
void drawRawAtlas(
ui.Image atlas,
Float32List rstTransforms,
Float32List rects,
Int32List? colors,
ui.BlendMode? blendMode,
ui.Rect? cullRect,
ui.Paint paint) {
assert(colors == null || blendMode != null);
final int rectCount = rects.length;
if (rstTransforms.length != rectCount) {
throw ArgumentError('"rstTransforms" and "rects" lengths must match.');
}
if (rectCount % 4 != 0) {
throw ArgumentError(
'"rstTransforms" and "rects" lengths must be a multiple of four.');
}
if (colors != null && colors.length * 4 != rectCount) {
throw ArgumentError(
'If non-null, "colors" length must be one fourth the length of "rstTransforms" and "rects".');
}
Uint32List? unsignedColors;
if (colors != null) {
unsignedColors = colors.buffer.asUint32List(colors.offsetInBytes, colors.length);
}
_drawAtlas(paint, atlas, rstTransforms, rects,
unsignedColors, blendMode ?? ui.BlendMode.src);
}
// TODO(hterkelsen): Pass a cull_rect once CanvasKit supports that.
void _drawAtlas(
ui.Paint paint,
ui.Image atlas,
Float32List rstTransforms,
Float32List rects,
Uint32List? colors,
ui.BlendMode blendMode,
) {
_canvas.drawAtlasRaw(
paint as CkPaint,
atlas as CkImage,
rstTransforms,
rects,
colors,
blendMode,
);
}
@override
void drawShadow(ui.Path path, ui.Color color, double elevation,
bool transparentOccluder) {
_drawShadow(path, color, elevation, transparentOccluder);
}
void _drawShadow(ui.Path path, ui.Color color, double elevation,
bool transparentOccluder) {
_canvas.drawShadow(path as CkPath, color, elevation, transparentOccluder);
}
}
| engine/lib/web_ui/lib/src/engine/canvaskit/canvaskit_canvas.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/canvaskit/canvaskit_canvas.dart",
"repo_id": "engine",
"token_count": 4640
} | 284 |
// 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 'package:ui/src/engine.dart';
/// A [Rasterizer] that uses a single GL context in an OffscreenCanvas to do
/// all the rendering. It transfers bitmaps created in the OffscreenCanvas to
/// one or many on-screen <canvas> elements to actually display the scene.
class OffscreenCanvasRasterizer extends Rasterizer {
/// This is an SkSurface backed by an OffScreenCanvas. This single Surface is
/// used to render to many RenderCanvases to produce the rendered scene.
final Surface offscreenSurface = Surface();
@override
OffscreenCanvasViewRasterizer createViewRasterizer(EngineFlutterView view) {
return _viewRasterizers.putIfAbsent(
view, () => OffscreenCanvasViewRasterizer(view, this));
}
final Map<EngineFlutterView, OffscreenCanvasViewRasterizer> _viewRasterizers =
<EngineFlutterView, OffscreenCanvasViewRasterizer>{};
@override
void setResourceCacheMaxBytes(int bytes) {
offscreenSurface.setSkiaResourceCacheMaxBytes(bytes);
}
@override
void dispose() {
offscreenSurface.dispose();
for (final OffscreenCanvasViewRasterizer viewRasterizer
in _viewRasterizers.values) {
viewRasterizer.dispose();
}
}
}
class OffscreenCanvasViewRasterizer extends ViewRasterizer {
OffscreenCanvasViewRasterizer(super.view, this.rasterizer);
final OffscreenCanvasRasterizer rasterizer;
@override
final DisplayCanvasFactory<RenderCanvas> displayFactory =
DisplayCanvasFactory<RenderCanvas>(createCanvas: () => RenderCanvas());
/// Render the given [pictures] so it is displayed by the given [canvas].
@override
Future<void> rasterizeToCanvas(
DisplayCanvas canvas, List<CkPicture> pictures) async {
await rasterizer.offscreenSurface.rasterizeToCanvas(
currentFrameSize,
canvas as RenderCanvas,
pictures,
);
}
@override
void prepareToDraw() {
rasterizer.offscreenSurface.createOrUpdateSurface(currentFrameSize);
}
}
| engine/lib/web_ui/lib/src/engine/canvaskit/offscreen_canvas_rasterizer.dart/0 | {
"file_path": "engine/lib/web_ui/lib/src/engine/canvaskit/offscreen_canvas_rasterizer.dart",
"repo_id": "engine",
"token_count": 681
} | 285 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.