Files
palemoon27/gfx/2d/PathHelpers.h
T
roytam1 e1776c67f8 import changes from `dev' branch of rmottola/Arctic-Fox:
- Bug 1199885 - Part 2: Add AsyncDragMetrics. r=kats (220a4f445e)
- Bug 1149482 - Localize the 'none' string for APZ in about:support. r=dvander (3e0128f62e)
- Bug 1199885 - Part 3: Add 'apz.drag.enabled' preference for async scrollbars. r=kats (5133061d3f)
- Bug 1199885 - Part 4: Let the hit testing tree know about the scroll thumb. r=kats (26a9a69443)
- Bug 1199885 - Part 5: Make mRootLayerTreeID const to prove that there's no data races. r=kats (88e2eb80f1)
- Bug 1199885 - Part 8: Add FindScrollNode to locate the scrollbar thumb. r=kats (a545ec9569)
- Bug 1199885 - Part 9: Let APZC handle the drag events. r=kats (4cc0f88153)
- Bug 1199885 - Part 9.5: Make the mouse events APZC aware. r=kats (69bd4caf94)
- Bug 1199885 - Part 10: Add APZTeeManager API to start an async scroll. r=kats (e212ee2750)
- Bug 1199885 - Part 12: Add StartScrollbarDrag IPC message. r=kats (705af3b233)
- Bug 1199885 - Part 13: Let nsSliderFrame trigger async scrolling via StartScrollbarDrag. r=kats (d31b5a790d)
- put in gstreamer as of 2015-10-05 Bug 1146482 (7cca45858c)
- pointer style (f8041af438)
- Bug 1197097 - Don't use a context-wide cycle-detection mechanism for detecting cycles during JSON.stringify. This prevents nested (yet separate) JSON.stringify, and it causes that algorithm to be affected by specification-unrelated operations like toSource. r=jonco (09652471c1)
- align to ugly grammaer of 1114782 (c760693693)
- remove space (7158a0c2bf)
- align to FF/TFF (27138a55bb)
- Bug 1205887 - Verify that MOZILLA_VERSION was set correctly, r=glandium (2269e8f31b)
- Bug 1205012 - Allow rust source code in SpiderMonkey; r=mshal (9ebca9ed28)
- Bug 1197281 - Use MOZ_FIND_WINSDK_VERSION for MOZ_WINSDK_MAXVER on mingw. r=glandium (2910b2160e)
- Bug 1207893 - Refactor how build backend execution is summarized. r=gps (56d8fecbc2)
- Bug 1207893 - Allow to create multiple build backends at once. r=gps (d8cba87d2b)
- Bug 1207897 - Add a configure option to build multiple build backends. r=gps (f9c7851d02)
- Bug 1188555 - part 1 - remove write-only configure.in variable NO_LD_ARCHIVE_FLAGS; r=mshal (461958b100)
- Bug 1188555 - part 2 - remove write-only configure.in variables MKSHLIB_{UN,}FORCE_ALL; r=mshal (1813210dda)
- Bug 1207882 - Ensure chrome manifests are created in a directory that exists when processing jar manifests. r=gps (59165a64cb)
- Bug 1204712 - Handle wildcards properly for localized content in jar manifests. r=gps (54dfb632c7)
- Bug 1188551: treat assertion failures as bad mozconfig; r=mshal (e307769de7)
- Bug 1181040 - Set ${var}_IS_SET variables for mk_add_options-defined variables. r=gps (19f169556b)
- Bug 1193015 - Require MOZ_GLX_USE_SURFACE_SHARING to enable WebGL surface sharing on GLX. r=jgilbert (9aa4fa8f41)
- Bug 1211324 (part 1) - Remove BILINEAR and GAUSSIAN filter constants. (3d9290ef02)
- Bug 1211324 (part 2) - Make gfx::FILTER::GOOD convert to GraphicsFilter::FILTER_GOOD. r=mattwoodrow. (16e7607c70)
- Bug 1208365 (part 1) - Remove unused EXTEND_PAD_EDGE. r=Bas. (10920e2bb6)
- Bug 1208365 (part 2) - Remove gfxPattern::Extend(). r=bas. (3703b9748a)
- Bug 1208365 (part 3) - Change gfxPattern::mExtend from a GraphicsExtend to a gfx::ExtendMode. r=bas. (b105d06e91)
- Bug 1208365 (part 4) - Remove gfxPattern::GraphicsExtend. r=bas. (7a16d48995)
- Bug 1211324 (part 3) - Remove GraphicsFilter::FILTER_FAST and replace it with FILTER_BEST. r=mattwoodrow. (b5101e049f)
- Bug 1211324 (part 4) - Replace GraphicsFilter constants with gfx::Filter equivalents. r=mattwoodrow. (c19b6b030e)
- Bug 1190117 - Track mLastProducerID and mLastFrameID explicitly in ImageLayerProperties. r=roc (ed9a5c777f)
- Bug 1211324 (part 5) - Remove GraphicsFilter and gfxGraphicsFilter. r=mattwoodrow. (0bd4ce7160)
- Bug 1194954 - Fix -Wunreachable-code warnings in gfx/layers and gfx/thebes. r=BenWa (1a3d68c490)
- Bug 1180509 - Fix judder of icons in Australis doorhanger menu at the end of its scale-in animation. r=roc (9b4df470fa)
- Bug 1206915 - Make paint dumping to a file e10s-friendly. r=mattwoodrow (87d2e12c2b)
- Bug 1206915 - Handle nested PaintFrame() calls correctly during paint dumping. r=mattwoodrow,BenWa (d30f77fbdd)
- Fix max texture size handling in displayport clamping. (bug 1135907 follow-up, r=kats) (a791894332)
- Fix bogus assertion in nsLayoutUtils::SetDisplayPortMargins. (bug 1156409, r=botond, a=philor) (b635b21c34)
- Bug 1169879 - Use only the critical displayport when computing image visibility. r=tn (9ec91c9527)
- Bug 1169881 - Recompute image visibility when display port margins change. r=tn (35a5bd3a51)
- Bug 1197765 - Compare text content inside frame instead of the content node for ruby autohiding. r=dbaron (00cf5b7674)
- Bug 1173580 - Record content descriptions in APZ test data. r=kats (7a72d1ac0a)
- Bug 1178971 - Changed line snapping behaviour depending on even/odd-ness of stroke width. r=mstange (495b32dc23)
- Bug 1208953: [mp3] Don't parse data we've already parsed. r=cpearce (72eed4309f)
- Bug 1137151: Marked destructor of |android::MediaCodecReader| as protected, r=sotaro (0632b34bc5)
- Bug 1205351 - Replace nsBaseHashtable::Enumerate() calls in dom/media/ with iterators r=cpearce (45976c24c0)
- Bug 1133624 - Add lang-specific ruby rules to ua.css. r=dbaron (46788cc220)
- Bug 1133624 - followup add fuzzy maxdiff on CLOSED TREE (1b6b62aded)
- Bug 1180443 - Consider whitespace collapse when calculating intrinsic isize of ruby. r=dbaron (3862184acd)
- Bug 1153764 - Avoid explicitly doing break before when there is ruby span. r=roc (71b4ec7749)
- add gstreamer parts (7e562556be)
- some preferences aligned to FF (b26d0b389c)
- Bug 1166301 - If APZ is enabled, clip fixed background images at the layer level rather than the display item level. r=mattwoodrow (5644e22090)
- Bug 1144990 - Dump display items with class id and name, r=roc (aa2e227e35)
- Bug 1205087 - Remove LayerManager parameter for ShouldFixToViewport. r=roc (00a1f2e36f)
- Bug 1205087 - Make nsSVGIntegrationUtils paint frame continuations manually since combining them meant that our reference frame wasn't an ancestor of all painted frames. r=roc (e40f6b7b81)
- Bug 1195400 - Check ancestor geometry roots when determining scrollability of a layer. r=mattwoodrow (4699b7e935)
- Bug 1205087 - Cache the AnimatedGeometryRoot on DisplayItem. r=roc (06bba311c3)
- Back out the bits of bug 1205087 that cache the AnimatedGeometryRoot on DisplayItem. r=backout (254057a6b6)
- Bug 1203190 - Don't intersect with the visible rect for fixed background images. r=mattwoodrow (1c5a432459)
- Bug 1208438 - Don't allow layers with scrolling clips to occlusion-cull layers behind them. r=mattwoodrow (c3d77a9846)
- Bug 1205630 - Translate a fixed background display item's clip rect correctly when setting it on the layer. r=mstange (49039f0e2d)
- Bug 1205630 - Reftest. r=mstange (a8db59eaee)
- Bug 1105832 - Also dump inactive layer managers when display list dumping is enabled. r=mattwoodrow (564fe5fcbc)
- Bug 1208661 - Move Dump() up from ContentClient to CompositableClient. r=BenWa (37915312b3)
2022-09-22 10:16:52 +08:00

422 lines
16 KiB
C++

/* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifndef MOZILLA_GFX_PATHHELPERS_H_
#define MOZILLA_GFX_PATHHELPERS_H_
#include "2D.h"
#include "mozilla/Constants.h"
#include "UserData.h"
#include <cmath>
namespace mozilla {
namespace gfx {
// Kappa constant for 90-degree angle
const Float kKappaFactor = 0.55191497064665766025f;
// Calculate kappa constant for partial curve. The sign of angle in the
// tangent will actually ensure this is negative for a counter clockwise
// sweep, so changing signs later isn't needed.
inline Float ComputeKappaFactor(Float aAngle)
{
return (4.0f / 3.0f) * tanf(aAngle / 4.0f);
}
/**
* Draws a partial arc <= 90 degrees given exact start and end points.
* Assumes that it is continuing from an already specified start point.
*/
template <typename T>
inline void PartialArcToBezier(T* aSink,
const Point& aStartOffset, const Point& aEndOffset,
const Matrix& aTransform,
Float aKappaFactor = kKappaFactor)
{
Point cp1 =
aStartOffset + Point(-aStartOffset.y, aStartOffset.x) * aKappaFactor;
Point cp2 =
aEndOffset + Point(aEndOffset.y, -aEndOffset.x) * aKappaFactor;
aSink->BezierTo(aTransform * cp1, aTransform * cp2, aTransform * aEndOffset);
}
/**
* Draws an acute arc (<= 90 degrees) given exact start and end points.
* Specialized version avoiding kappa calculation.
*/
template <typename T>
inline void AcuteArcToBezier(T* aSink,
const Point& aOrigin, const Size& aRadius,
const Point& aStartPoint, const Point& aEndPoint,
Float aKappaFactor = kKappaFactor)
{
aSink->LineTo(aStartPoint);
if (!aRadius.IsEmpty()) {
Float kappaX = aKappaFactor * aRadius.width / aRadius.height;
Float kappaY = aKappaFactor * aRadius.height / aRadius.width;
Point startOffset = aStartPoint - aOrigin;
Point endOffset = aEndPoint - aOrigin;
aSink->BezierTo(aStartPoint + Point(-startOffset.y * kappaX, startOffset.x * kappaY),
aEndPoint + Point(endOffset.y * kappaX, -endOffset.x * kappaY),
aEndPoint);
} else if (aEndPoint != aStartPoint) {
aSink->LineTo(aEndPoint);
}
}
/**
* Draws an acute arc (<= 90 degrees) given exact start and end points.
*/
template <typename T>
inline void AcuteArcToBezier(T* aSink,
const Point& aOrigin, const Size& aRadius,
const Point& aStartPoint, const Point& aEndPoint,
Float aStartAngle, Float aEndAngle)
{
AcuteArcToBezier(aSink, aOrigin, aRadius, aStartPoint, aEndPoint,
ComputeKappaFactor(aEndAngle - aStartAngle));
}
template <typename T>
void ArcToBezier(T* aSink, const Point &aOrigin, const Size &aRadius,
float aStartAngle, float aEndAngle, bool aAntiClockwise,
float aRotation = 0.0f)
{
Float sweepDirection = aAntiClockwise ? -1.0f : 1.0f;
// Calculate the total arc we're going to sweep.
Float arcSweepLeft = (aEndAngle - aStartAngle) * sweepDirection;
// Clockwise we always sweep from the smaller to the larger angle, ccw
// it's vice versa.
if (arcSweepLeft < 0) {
// Rerverse sweep is modulo'd into range rather than clamped.
arcSweepLeft = Float(2.0f * M_PI) + fmodf(arcSweepLeft, Float(2.0f * M_PI));
// Recalculate the start angle to land closer to end angle.
aStartAngle = aEndAngle - arcSweepLeft * sweepDirection;
} else if (arcSweepLeft > Float(2.0f * M_PI)) {
// Sweeping more than 2 * pi is a full circle.
arcSweepLeft = Float(2.0f * M_PI);
}
Float currentStartAngle = aStartAngle;
Point currentStartOffset(cosf(aStartAngle), sinf(aStartAngle));
Matrix transform = Matrix::Scaling(aRadius.width, aRadius.height);
if (aRotation != 0.0f) {
transform *= Matrix::Rotation(aRotation);
}
transform.PostTranslate(aOrigin);
aSink->LineTo(transform * currentStartOffset);
while (arcSweepLeft > 0) {
Float currentEndAngle =
currentStartAngle + std::min(arcSweepLeft, Float(M_PI / 2.0f)) * sweepDirection;
Point currentEndOffset(cosf(currentEndAngle), sinf(currentEndAngle));
PartialArcToBezier(aSink, currentStartOffset, currentEndOffset, transform,
ComputeKappaFactor(currentEndAngle - currentStartAngle));
// We guarantee here the current point is the start point of the next
// curve segment.
arcSweepLeft -= Float(M_PI / 2.0f);
currentStartAngle = currentEndAngle;
currentStartOffset = currentEndOffset;
}
}
/* This is basically the ArcToBezier with the parameters for drawing a circle
* inlined which vastly simplifies it and avoids a bunch of transcedental function
* calls which should make it faster. */
template <typename T>
void EllipseToBezier(T* aSink, const Point &aOrigin, const Size &aRadius)
{
Matrix transform(aRadius.width, 0, 0, aRadius.height, aOrigin.x, aOrigin.y);
Point currentStartOffset(1, 0);
aSink->LineTo(transform * currentStartOffset);
for (int i = 0; i < 4; i++) {
// cos(x+pi/2) == -sin(x)
// sin(x+pi/2) == cos(x)
Point currentEndOffset(-currentStartOffset.y, currentStartOffset.x);
PartialArcToBezier(aSink, currentStartOffset, currentEndOffset, transform);
// We guarantee here the current point is the start point of the next
// curve segment.
currentStartOffset = currentEndOffset;
}
}
/**
* Appends a path represending a rectangle to the path being built by
* aPathBuilder.
*
* aRect The rectangle to append.
* aDrawClockwise If set to true, the path will start at the left of the top
* left edge and draw clockwise. If set to false the path will
* start at the right of the top left edge and draw counter-
* clockwise.
*/
GFX2D_API void AppendRectToPath(PathBuilder* aPathBuilder,
const Rect& aRect,
bool aDrawClockwise = true);
inline already_AddRefed<Path> MakePathForRect(const DrawTarget& aDrawTarget,
const Rect& aRect,
bool aDrawClockwise = true)
{
RefPtr<PathBuilder> builder = aDrawTarget.CreatePathBuilder();
AppendRectToPath(builder, aRect, aDrawClockwise);
return builder->Finish();
}
struct RectCornerRadii {
Size radii[RectCorner::Count];
RectCornerRadii() {}
explicit RectCornerRadii(Float radius) {
for (int i = 0; i < RectCorner::Count; i++) {
radii[i].SizeTo(radius, radius);
}
}
explicit RectCornerRadii(Float radiusX, Float radiusY) {
for (int i = 0; i < RectCorner::Count; i++) {
radii[i].SizeTo(radiusX, radiusY);
}
}
RectCornerRadii(Float tl, Float tr, Float br, Float bl) {
radii[RectCorner::TopLeft].SizeTo(tl, tl);
radii[RectCorner::TopRight].SizeTo(tr, tr);
radii[RectCorner::BottomRight].SizeTo(br, br);
radii[RectCorner::BottomLeft].SizeTo(bl, bl);
}
RectCornerRadii(const Size& tl, const Size& tr,
const Size& br, const Size& bl) {
radii[RectCorner::TopLeft] = tl;
radii[RectCorner::TopRight] = tr;
radii[RectCorner::BottomRight] = br;
radii[RectCorner::BottomLeft] = bl;
}
const Size& operator[](size_t aCorner) const {
return radii[aCorner];
}
Size& operator[](size_t aCorner) {
return radii[aCorner];
}
bool operator==(const RectCornerRadii& aOther) const {
for (size_t i = 0; i < RectCorner::Count; i++) {
if (radii[i] != aOther.radii[i]) return false;
}
return true;
}
void Scale(Float aXScale, Float aYScale) {
for (int i = 0; i < RectCorner::Count; i++) {
radii[i].Scale(aXScale, aYScale);
}
}
const Size TopLeft() const { return radii[RectCorner::TopLeft]; }
Size& TopLeft() { return radii[RectCorner::TopLeft]; }
const Size TopRight() const { return radii[RectCorner::TopRight]; }
Size& TopRight() { return radii[RectCorner::TopRight]; }
const Size BottomRight() const { return radii[RectCorner::BottomRight]; }
Size& BottomRight() { return radii[RectCorner::BottomRight]; }
const Size BottomLeft() const { return radii[RectCorner::BottomLeft]; }
Size& BottomLeft() { return radii[RectCorner::BottomLeft]; }
};
/**
* Appends a path represending a rounded rectangle to the path being built by
* aPathBuilder.
*
* aRect The rectangle to append.
* aCornerRadii Contains the radii of the top-left, top-right, bottom-right
* and bottom-left corners, in that order.
* aDrawClockwise If set to true, the path will start at the left of the top
* left edge and draw clockwise. If set to false the path will
* start at the right of the top left edge and draw counter-
* clockwise.
*/
GFX2D_API void AppendRoundedRectToPath(PathBuilder* aPathBuilder,
const Rect& aRect,
const RectCornerRadii& aRadii,
bool aDrawClockwise = true);
inline already_AddRefed<Path> MakePathForRoundedRect(const DrawTarget& aDrawTarget,
const Rect& aRect,
const RectCornerRadii& aRadii,
bool aDrawClockwise = true)
{
RefPtr<PathBuilder> builder = aDrawTarget.CreatePathBuilder();
AppendRoundedRectToPath(builder, aRect, aRadii, aDrawClockwise);
return builder->Finish();
}
/**
* Appends a path represending an ellipse to the path being built by
* aPathBuilder.
*
* The ellipse extends aDimensions.width / 2.0 in the horizontal direction
* from aCenter, and aDimensions.height / 2.0 in the vertical direction.
*/
GFX2D_API void AppendEllipseToPath(PathBuilder* aPathBuilder,
const Point& aCenter,
const Size& aDimensions);
inline already_AddRefed<Path> MakePathForEllipse(const DrawTarget& aDrawTarget,
const Point& aCenter,
const Size& aDimensions)
{
RefPtr<PathBuilder> builder = aDrawTarget.CreatePathBuilder();
AppendEllipseToPath(builder, aCenter, aDimensions);
return builder->Finish();
}
/**
* If aDrawTarget's transform only contains a translation, and if this line is
* a horizontal or vertical line, this function will snap the line's vertices
* to align with the device pixel grid so that stroking the line with a one
* pixel wide stroke will result in a crisp line that is not antialiased over
* two pixels across its width.
*
* @return Returns true if this function snaps aRect's vertices, else returns
* false.
*/
GFX2D_API bool SnapLineToDevicePixelsForStroking(Point& aP1, Point& aP2,
const DrawTarget& aDrawTarget,
Float aLineWidth);
/**
* This function paints each edge of aRect separately, snapping the edges using
* SnapLineToDevicePixelsForStroking. Stroking the edges as separate paths
* helps ensure not only that the stroke spans a single row of device pixels if
* possible, but also that the ends of stroke dashes start and end on device
* pixels too.
*/
GFX2D_API void StrokeSnappedEdgesOfRect(const Rect& aRect,
DrawTarget& aDrawTarget,
const ColorPattern& aColor,
const StrokeOptions& aStrokeOptions);
/**
* Return the margin, in device space, by which a stroke can extend beyond the
* rendered shape.
* @param aStrokeOptions The stroke options that the stroke is drawn with.
* @param aTransform The user space to device space transform.
* @return The stroke margin.
*/
GFX2D_API Margin MaxStrokeExtents(const StrokeOptions& aStrokeOptions,
const Matrix& aTransform);
extern UserDataKey sDisablePixelSnapping;
/**
* If aDrawTarget's transform only contains a translation or, if
* aAllowScaleOr90DegreeRotate is true, and/or a scale/90 degree rotation, this
* function will convert aRect to device space and snap it to device pixels.
* This function returns true if aRect is modified, otherwise it returns false.
*
* Note that the snapping is such that filling the rect using a DrawTarget
* which has the identity matrix as its transform will result in crisp edges.
* (That is, aRect will have integer values, aligning its edges between pixel
* boundaries.) If on the other hand you stroking the rect with an odd valued
* stroke width then the edges of the stroke will be antialiased (assuming an
* AntialiasMode that does antialiasing).
*
* Empty snaps are those which result in a rectangle of 0 area. If they are
* disallowed, an axis is left unsnapped if the rounding process results in a
* length of 0.
*/
inline bool UserToDevicePixelSnapped(Rect& aRect, const DrawTarget& aDrawTarget,
bool aAllowScaleOr90DegreeRotate = false,
bool aAllowEmptySnaps = true)
{
if (aDrawTarget.GetUserData(&sDisablePixelSnapping)) {
return false;
}
Matrix mat = aDrawTarget.GetTransform();
const Float epsilon = 0.0000001f;
#define WITHIN_E(a,b) (fabs((a)-(b)) < epsilon)
if (!aAllowScaleOr90DegreeRotate &&
(!WITHIN_E(mat._11, 1.f) || !WITHIN_E(mat._22, 1.f) ||
!WITHIN_E(mat._12, 0.f) || !WITHIN_E(mat._21, 0.f))) {
// We have non-translation, but only translation is allowed.
return false;
}
#undef WITHIN_E
Point p1 = mat * aRect.TopLeft();
Point p2 = mat * aRect.TopRight();
Point p3 = mat * aRect.BottomRight();
// Check that the rectangle is axis-aligned. For an axis-aligned rectangle,
// two opposite corners define the entire rectangle. So check if
// the axis-aligned rectangle with opposite corners p1 and p3
// define an axis-aligned rectangle whose other corners are p2 and p4.
// We actually only need to check one of p2 and p4, since an affine
// transform maps parallelograms to parallelograms.
if (p2 == Point(p1.x, p3.y) || p2 == Point(p3.x, p1.y)) {
Point p1r = p1;
Point p3r = p3;
p1r.Round();
p3r.Round();
if (aAllowEmptySnaps || p1r.x != p3r.x) {
p1.x = p1r.x;
p3.x = p3r.x;
}
if (aAllowEmptySnaps || p1r.y != p3r.y) {
p1.y = p1r.y;
p3.y = p3r.y;
}
aRect.MoveTo(Point(std::min(p1.x, p3.x), std::min(p1.y, p3.y)));
aRect.SizeTo(Size(std::max(p1.x, p3.x) - aRect.X(),
std::max(p1.y, p3.y) - aRect.Y()));
return true;
}
return false;
}
/**
* This function has the same behavior as UserToDevicePixelSnapped except that
* aRect is not transformed to device space.
*/
inline void MaybeSnapToDevicePixels(Rect& aRect, const DrawTarget& aDrawTarget,
bool aAllowScaleOr90DegreeRotate = false,
bool aAllowEmptySnaps = true)
{
if (UserToDevicePixelSnapped(aRect, aDrawTarget,
aAllowScaleOr90DegreeRotate, aAllowEmptySnaps)) {
// Since UserToDevicePixelSnapped returned true we know there is no
// rotation/skew in 'mat', so we can just use TransformBounds() here.
Matrix mat = aDrawTarget.GetTransform();
mat.Invert();
aRect = mat.TransformBounds(aRect);
}
}
} // namespace gfx
} // namespace mozilla
#endif /* MOZILLA_GFX_PATHHELPERS_H_ */