Expose SkPathOps in a standalone library. (flutter/engine#34267)

This commit is contained in:
Dan Field
2022-07-11 10:11:03 -07:00
committed by GitHub
parent 0e6fb5e6dc
commit 6dd8d32f31
10 changed files with 702 additions and 0 deletions

View File

@@ -103,6 +103,9 @@ group("flutter") {
# Impeller artifacts - compiler and libtessellator
"//flutter/impeller/compiler:impellerc",
"//flutter/impeller/tessellator:tessellator_shared",
# path_ops
"//flutter/tools/path_ops",
]
if (full_dart_sdk) {

View File

@@ -39,6 +39,14 @@ def PrintDivider(char='='):
print('\n')
def IsAsan(build_dir):
with open(os.path.join(build_dir, 'args.gn')) as args:
if 'is_asan = true' in args.read():
return True
return False
def RunCmd(cmd, forbidden_output=[], expect_failure=False, env=None, **kwargs):
command_string = ' '.join(cmd)
@@ -769,6 +777,24 @@ def GatherFrontEndServerTests(build_dir):
)
def GatherPathOpsTests(build_dir):
# TODO(dnfield): https://github.com/flutter/flutter/issues/107321
if IsAsan(build_dir):
return
test_dir = os.path.join(
buildroot_dir, 'flutter', 'tools', 'path_ops', 'dart', 'test'
)
opts = ['--disable-dart-dev', os.path.join(test_dir, 'path_ops_test.dart')]
yield EngineExecutableTask(
build_dir,
os.path.join('dart-sdk', 'bin', 'dart'),
None,
flags=opts,
cwd=test_dir
)
def GatherConstFinderTests(build_dir):
test_dir = os.path.join(
buildroot_dir, 'flutter', 'tools', 'const_finder', 'test'
@@ -1031,6 +1057,7 @@ def main():
tasks += list(GatherGithooksTests(build_dir))
tasks += list(GatherClangTidyTests(build_dir))
tasks += list(GatherApiConsistencyTests(build_dir))
tasks += list(GatherPathOpsTests(build_dir))
tasks += list(GatherConstFinderTests(build_dir))
tasks += list(GatherFrontEndServerTests(build_dir))
tasks += list(

View File

@@ -0,0 +1,39 @@
# 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/shell/version/version.gni")
generated_file("path_ops_license") {
source_path = rebase_path(".", "//flutter")
git_url = "https://github.com/flutter/engine/tree/$engine_version"
outputs = [ "$target_gen_dir/LICENSE.path_ops.md" ]
contents = [
"# path_ops",
"",
"This tool is used by the vector_graphics library to calculate path intersections.",
"",
"Source code for this tool: [flutter/engine/$source_path]($git_url/$source_path).",
"",
"## Licenses",
"",
read_file("//flutter/sky/packages/sky_engine/LICENSE", "string"),
"",
"## Additional open source licenses",
"",
"### Skia",
"",
read_file("//third_party/skia/LICENSE", "string"),
]
}
shared_library("path_ops") {
sources = [
"path_ops.cc",
"path_ops.h",
]
deps = [
":path_ops_license",
"//third_party/skia",
]
}

View File

@@ -0,0 +1,12 @@
# path_ops
A small library that exposes C bindings for Skia's SkPathOps, with a minimal
interface for SkPath.
This library only supports four commands from SkPath: `moveTo`, `lineTo`,
`cubicTo`, and `close`.
This library is a subset of the functionality provided by Skia's `PathKit`
library. It is primarily intended for use with the `vector_graphics` optimizing
compiler. That library uses this one to optimize certain masking and clipping
operations at compile time.

View File

@@ -0,0 +1,390 @@
// 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: camel_case_types, non_constant_identifier_names
import 'dart:ffi' as ffi;
import 'dart:io';
import 'dart:typed_data';
/// Determines the winding rule that decides how the interior of a Path is
/// calculated.
///
/// This enum is used by the [Path] constructor
// must match ordering in //third_party/skia/include/core/SkPathTypes.h
enum FillType {
/// The interior is defined by a non-zero sum of signed edge crossings.
nonZero,
/// The interior is defined by an odd number of edge crossings.
evenOdd,
}
/// A set of operations applied to two paths.
// Sync with //third_party/skia/include/pathops/SkPathOps.h
enum PathOp {
/// Subtracts the second path from the first.
difference,
/// Creates a new path representing the intersection of the first and second.
intersect,
/// Creates a new path representing the union of the first and second
/// (includive-or).
union,
/// Creates a new path representing the exclusive-or of two paths.
xor,
/// Creates a new path that subtracts the first path from the second.s
reversedDifference,
}
/// The commands used in a [Path] object.
///
/// This enumeration is a subset of the commands that SkPath supports.
// Sync with //third_party/skia/include/core/SkPathTypes.h
enum PathVerb {
/// Picks up the pen and moves it without drawing. Uses two point values.
moveTo,
/// A straight line from the current point to the specified point.
lineTo,
_quadTo,
_conicTo,
/// A cubic bezier curve from the current point.
///
/// The next two points are used as the first control point. The next two
/// points form the second control point. The next two points form the
/// target point.
cubicTo,
/// A straight line from the current point to the last [moveTo] point.
close,
}
/// A proxy class for [Path.replay].
///
/// Allows implementations to easily inspect the contents of a [Path].
abstract class PathProxy {
/// Picks up the pen and moves to absolute coordinates x,y.
void moveTo(double x, double y);
/// Draws a straight line from the current point to absolute coordinates x,y.
void lineTo(double x, double y);
/// Creates a cubic Bezier curve from the current point to point x3,y3 using
/// x1,y1 as the first control point and x2,y2 as the second.
void cubicTo(
double x1, double y1, double x2, double y2, double x3, double y3);
/// Draws a straight line from the current point to the last [moveTo] point.
void close();
/// Called by [Path.replay] to indicate that a new path is being played.
void reset() {}
}
/// A path proxy that can print the SVG path-data representation of this path.
class SvgPathProxy implements PathProxy {
final StringBuffer _buffer = StringBuffer();
@override
void reset() {
_buffer.clear();
}
@override
void close() {
_buffer.write('Z');
}
@override
void cubicTo(
double x1, double y1, double x2, double y2, double x3, double y3) {
_buffer.write('C$x1,$y1 $x2,$y2 $x3,$y3');
}
@override
void lineTo(double x, double y) {
_buffer.write('L$x,$y');
}
@override
void moveTo(double x, double y) {
_buffer.write('M$x,$y');
}
@override
String toString() => _buffer.toString();
}
/// Creates a path object to operate on.
///
/// First, build up the path contours with the [moveTo], [lineTo], [cubicTo],
/// and [close] methods. All methods expect absolute coordinates.
///
/// Finally, use the [dispose] method to clean up native resources. After
/// [dispose] has been called, this class must not be used again.
class Path implements PathProxy {
/// Creates an empty path object with the specified fill type.
Path([this.fillType = FillType.nonZero])
: _path = _createPathFn(fillType.index);
/// Creates a copy of this path.
factory Path.from(Path other) {
final Path result = Path(other.fillType);
other.replay(result);
return result;
}
/// The [FillType] of this path.
final FillType fillType;
ffi.Pointer<_SkPath>? _path;
ffi.Pointer<_PathData>? _pathData;
/// The number of points used by each [PathVerb].
static const Map<PathVerb, int> pointsPerVerb = <PathVerb, int>{
PathVerb.moveTo: 2,
PathVerb.lineTo: 2,
PathVerb.cubicTo: 6,
PathVerb.close: 0,
};
/// Makes the appropriate calls using [verbs] and [points] to replay this path
/// on [proxy].
///
/// Calls [PathProxy.reset] first if [reset] is true.
void replay(PathProxy proxy, {bool reset = true}) {
if (reset) {
proxy.reset();
}
int index = 0;
for (final PathVerb verb in verbs.toList()) {
switch (verb) {
case PathVerb.moveTo:
proxy.moveTo(points[index++], points[index++]);
break;
case PathVerb.lineTo:
proxy.lineTo(points[index++], points[index++]);
break;
case PathVerb._quadTo:
assert(false);
break;
case PathVerb._conicTo:
assert(false);
break;
case PathVerb.cubicTo:
proxy.cubicTo(
points[index++],
points[index++],
points[index++],
points[index++],
points[index++],
points[index++],
);
break;
case PathVerb.close:
proxy.close();
break;
}
}
assert(index == points.length);
}
/// The list of path verbs in this path.
///
/// This may not match the verbs supplied by calls to [moveTo], [lineTo],
/// [cubicTo], and [close] after [applyOp] is invoked.
///
/// This list determines the meaning of the [points] array.
Iterable<PathVerb> get verbs {
_updatePathData();
final int count = _pathData!.ref.verb_count;
return List<PathVerb>.generate(count, (int index) {
return PathVerb.values[_pathData!.ref.verbs.elementAt(index).value];
}, growable: false);
}
/// The list of points to use with [verbs].
///
/// Each verb uses a specific number of points, specified by the
/// [pointsPerVerb] map.
Float32List get points {
_updatePathData();
return _pathData!.ref.points.asTypedList(_pathData!.ref.point_count);
}
void _updatePathData() {
assert(_path != null);
_pathData ??= _dataFn(_path!);
}
void _resetPathData() {
if (_pathData != null) {
_destroyDataFn(_pathData!);
}
_pathData = null;
}
@override
void moveTo(double x, double y) {
assert(_path != null);
_resetPathData();
_moveToFn(_path!, x, y);
}
@override
void lineTo(double x, double y) {
assert(_path != null);
_resetPathData();
_lineToFn(_path!, x, y);
}
@override
void cubicTo(
double x1,
double y1,
double x2,
double y2,
double x3,
double y3,
) {
assert(_path != null);
_resetPathData();
_cubicToFn(_path!, x1, y1, x2, y2, x3, y3);
}
@override
void close() {
assert(_path != null);
_resetPathData();
_closeFn(_path!, true);
}
@override
void reset() {
assert(_path != null);
_resetPathData();
_resetFn(_path!);
}
/// Releases native resources.
///
/// After calling dispose, this class must not be used again.
void dispose() {
assert(_path != null);
_resetPathData();
_destroyFn(_path!);
_path = null;
}
/// Applies the operation described by [op] to this path using [other].
Path applyOp(Path other, PathOp op) {
assert(_path != null);
assert(other._path != null);
final Path result = Path.from(this);
_opFn(result._path!, other._path!, op.index);
return result;
}
}
// TODO(dnfield): Figure out where to put this.
// https://github.com/flutter/flutter/issues/99563
final ffi.DynamicLibrary _dylib = () {
if (Platform.isWindows) {
return ffi.DynamicLibrary.open('path_ops.dll');
} else if (Platform.isIOS || Platform.isMacOS) {
return ffi.DynamicLibrary.open('libpath_ops.dylib');
} else if (Platform.isAndroid || Platform.isLinux) {
return ffi.DynamicLibrary.open('libpath_ops.so');
}
throw UnsupportedError('Unknown platform: ${Platform.operatingSystem}');
}();
class _SkPath extends ffi.Opaque {}
class _PathData extends ffi.Struct {
external ffi.Pointer<ffi.Uint8> verbs;
@ffi.Size()
external int verb_count;
external ffi.Pointer<ffi.Float> points;
@ffi.Size()
external int point_count;
}
typedef _CreatePathType = ffi.Pointer<_SkPath> Function(int);
typedef _create_path_type = ffi.Pointer<_SkPath> Function(ffi.Int);
final _CreatePathType _createPathFn =
_dylib.lookupFunction<_create_path_type, _CreatePathType>(
'CreatePath',
);
typedef _MoveToType = void Function(ffi.Pointer<_SkPath>, double, double);
typedef _move_to_type = ffi.Void Function(
ffi.Pointer<_SkPath>, ffi.Float, ffi.Float);
final _MoveToType _moveToFn = _dylib.lookupFunction<_move_to_type, _MoveToType>(
'MoveTo',
);
typedef _LineToType = void Function(ffi.Pointer<_SkPath>, double, double);
typedef _line_to_type = ffi.Void Function(
ffi.Pointer<_SkPath>, ffi.Float, ffi.Float);
final _LineToType _lineToFn = _dylib.lookupFunction<_line_to_type, _LineToType>(
'LineTo',
);
typedef _CubicToType = void Function(
ffi.Pointer<_SkPath>, double, double, double, double, double, double);
typedef _cubic_to_type = ffi.Void Function(ffi.Pointer<_SkPath>, ffi.Float,
ffi.Float, ffi.Float, ffi.Float, ffi.Float, ffi.Float);
final _CubicToType _cubicToFn =
_dylib.lookupFunction<_cubic_to_type, _CubicToType>('CubicTo');
typedef _CloseType = void Function(ffi.Pointer<_SkPath>, bool);
typedef _close_type = ffi.Void Function(ffi.Pointer<_SkPath>, ffi.Bool);
final _CloseType _closeFn =
_dylib.lookupFunction<_close_type, _CloseType>('Close');
typedef _ResetType = void Function(ffi.Pointer<_SkPath>);
typedef _reset_type = ffi.Void Function(ffi.Pointer<_SkPath>);
final _ResetType _resetFn =
_dylib.lookupFunction<_reset_type, _ResetType>('Reset');
typedef _DestroyType = void Function(ffi.Pointer<_SkPath>);
typedef _destroy_type = ffi.Void Function(ffi.Pointer<_SkPath>);
final _DestroyType _destroyFn =
_dylib.lookupFunction<_destroy_type, _DestroyType>('DestroyPath');
typedef _OpType = void Function(
ffi.Pointer<_SkPath>, ffi.Pointer<_SkPath>, int);
typedef _op_type = ffi.Void Function(
ffi.Pointer<_SkPath>, ffi.Pointer<_SkPath>, ffi.Int);
final _OpType _opFn = _dylib.lookupFunction<_op_type, _OpType>('Op');
typedef _PathDataType = ffi.Pointer<_PathData> Function(ffi.Pointer<_SkPath>);
typedef _path_data_type = ffi.Pointer<_PathData> Function(ffi.Pointer<_SkPath>);
final _PathDataType _dataFn =
_dylib.lookupFunction<_path_data_type, _PathDataType>('Data');
typedef _DestroyDataType = void Function(ffi.Pointer<_PathData>);
typedef _destroy_data_type = ffi.Void Function(ffi.Pointer<_PathData>);
final _DestroyDataType _destroyDataFn =
_dylib.lookupFunction<_destroy_data_type, _DestroyDataType>('DestroyData');

View File

@@ -0,0 +1,26 @@
# 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.
name: path_ops
description: A Dart FFI wrapper for Skia PathKit.
version: 0.0.0
publish_to: none
homepage: https://github.com/flutter/engine/tree/main/tools/path_ops
environment:
sdk: '>=2.12.0 <3.0.0'
dev_dependencies:
litetest: any
dependency_overrides:
async_helper:
path: ../../../../third_party/dart/pkg/async_helper
expect:
path: ../../../../third_party/dart/pkg/expect
litetest:
path: ../../../testing/litetest
meta:
path: ../../../../third_party/dart/pkg/meta
smith:
path: ../../../../third_party/dart/pkg/smith

View File

@@ -0,0 +1,77 @@
// 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:litetest/litetest.dart';
import 'package:path_ops/path_ops.dart';
void main() {
test('Path tests', () {
final Path path = Path()
..lineTo(10, 0)
..lineTo(10, 10)
..lineTo(0, 10)
..close()
..cubicTo(30, 30, 40, 40, 50, 50);
expect(path.fillType, FillType.nonZero);
expect(path.verbs.toList(), <PathVerb>[
PathVerb.moveTo, // Skia inserts a moveTo here.
PathVerb.lineTo,
PathVerb.lineTo,
PathVerb.lineTo,
PathVerb.close,
PathVerb.moveTo, // Skia inserts a moveTo here.
PathVerb.cubicTo,
]);
expect(path.points, <double>[0, 0, 10, 0, 10, 10, 0, 10, 0, 0, 30, 30, 40, 40, 50, 50]);
final SvgPathProxy proxy = SvgPathProxy();
path.replay(proxy);
expect(proxy.toString(), 'M0.0,0.0L10.0,0.0L10.0,10.0L0.0,10.0ZM0.0,0.0C30.0,30.0 40.0,40.0 50.0,50.0');
path.dispose();
});
test('Ops test', () {
final Path cubics = Path()
..moveTo(16, 128)
..cubicTo(16, 66, 66, 16, 128, 16)
..cubicTo(240, 66, 16, 66, 240, 128)
..close();
final Path quad = Path()
..moveTo(55, 16)
..lineTo(200, 80)
..lineTo(198, 230)
..lineTo(15, 230)
..close();
final Path intersection = cubics.applyOp(quad, PathOp.intersect);
expect(intersection.verbs, <PathVerb>[
PathVerb.moveTo,
PathVerb.lineTo,
PathVerb.cubicTo,
PathVerb.lineTo,
PathVerb.cubicTo,
PathVerb.cubicTo,
PathVerb.lineTo,
PathVerb.lineTo,
PathVerb.close
]);
expect(intersection.points, <double>[
34.06542205810547, 128.0, // move
48.90797424316406, 48.59233856201172, // line
57.80497360229492, 39.73065185546875, 68.189697265625, 32.3614387512207, 79.66168212890625, 26.885154724121094, // cubic
151.7936248779297, 58.72270584106445, // line
150.66123962402344, 59.74142837524414, 149.49365234375, 60.752471923828125, 148.32867431640625, 61.76123809814453, // cubic
132.3506317138672, 75.59684753417969, 116.86703491210938, 89.0042953491211, 199.52090454101562, 115.93260192871094, // cubic
199.36000061035156, 128.0, // line
34.06542205810547, 128.0, // line
// close
]);
cubics.dispose();
quad.dispose();
intersection.dispose();
});
}

View File

@@ -0,0 +1,69 @@
// 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 "path_ops.h"
namespace flutter {
SkPath* CreatePath(SkPathFillType fill_type) {
auto* path = new SkPath();
path->setFillType(fill_type);
return path;
}
void DestroyPath(SkPath* path) {
delete path;
}
void MoveTo(SkPath* path, SkScalar x, SkScalar y) {
path->moveTo(x, y);
}
void LineTo(SkPath* path, SkScalar x, SkScalar y) {
path->lineTo(x, y);
}
void CubicTo(SkPath* path,
SkScalar x1,
SkScalar y1,
SkScalar x2,
SkScalar y2,
SkScalar x3,
SkScalar y3) {
path->cubicTo(x1, y1, x2, y2, x3, y3);
}
void Close(SkPath* path) {
path->close();
}
void Reset(SkPath* path) {
path->reset();
}
void Op(SkPath* one, SkPath* two, SkPathOp op) {
Op(*one, *two, op, one);
}
struct PathData* Data(SkPath* path) {
int point_count = path->countPoints();
int verb_count = path->countVerbs();
auto data = new PathData();
data->points = new float[point_count * 2];
data->point_count = point_count * 2;
data->verbs = new uint8_t[verb_count];
data->verb_count = verb_count;
path->getVerbs(data->verbs, verb_count);
path->getPoints(reinterpret_cast<SkPoint*>(data->points), point_count);
return data;
}
void DestroyData(PathData* data) {
delete[] data->points;
delete[] data->verbs;
delete data;
}
} // namespace flutter

View File

@@ -0,0 +1,58 @@
// 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.
#pragma once
#include "third_party/skia/include/core/SkPath.h"
#include "third_party/skia/include/core/SkPathBuilder.h"
#include "third_party/skia/include/core/SkPathTypes.h"
#include "third_party/skia/include/pathops/SkPathOps.h"
#ifdef _WIN32
#define API __declspec(dllexport)
#else
#define API __attribute__((visibility("default")))
#endif
extern "C" {
namespace flutter {
API SkPath* CreatePath(SkPathFillType fill_type);
API void DestroyPathBuilder(SkPath* path);
API void MoveTo(SkPath* path, SkScalar x, SkScalar y);
API void LineTo(SkPath* path, SkScalar x, SkScalar y);
API void CubicTo(SkPath* path,
SkScalar x1,
SkScalar y1,
SkScalar x2,
SkScalar y2,
SkScalar x3,
SkScalar y3);
API void Close(SkPath* path);
API void Reset(SkPath* path);
API void DestroyPath(SkPath* path);
API void Op(SkPath* one, SkPath* two, SkPathOp op);
struct API PathData {
uint8_t* verbs;
size_t verb_count;
float* points;
size_t point_count;
};
API struct PathData* Data(SkPath* path);
API void DestroyData(PathData* data);
} // namespace flutter
}

View File

@@ -36,6 +36,7 @@ ALL_PACKAGES = [
os.path.join(ENGINE_DIR, "tools", "const_finder"),
os.path.join(ENGINE_DIR, "tools", "githooks"),
os.path.join(ENGINE_DIR, "tools", "licenses"),
os.path.join(ENGINE_DIR, "tools", "path_ops", "dart")
]