Merge inbound to mozilla-central a=merge

This commit is contained in:
arthur.iakab 2018-10-31 11:44:44 +02:00
Родитель f6a4b55fda 6aefc4e30e
Коммит eac6295c39
2011 изменённых файлов: 640769 добавлений и 228479 удалений

Просмотреть файл

@ -3,7 +3,6 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
const TP_PB_ENABLED_PREF = "privacy.trackingprotection.pbmode.enabled";
const CB_ENABLED_PREF = "browser.contentblocking.enabled";
/**
* Opens a new private window and loads "about:privatebrowsing" there.

Просмотреть файл

@ -12,6 +12,7 @@
#include "mozilla/ArrayUtils.h"
#include "mozilla/CheckedInt.h"
#include "mozilla/Vector.h"
#include "skia/include/core/SkSurface.h"
#include "skia/include/core/SkTypeface.h"
@ -38,7 +39,6 @@
#ifdef MOZ_WIDGET_COCOA
#include "BorrowedContext.h"
#include <ApplicationServices/ApplicationServices.h>
#include "mozilla/Vector.h"
#include "ScaledFontMac.h"
#include "CGTextDrawing.h"
#endif
@ -1441,16 +1441,6 @@ DrawTargetSkia::DrawGlyphs(ScaledFont* aFont,
paint.mPaint.setHinting(SkPaint::kNo_Hinting);
}
break;
case FontType::GDI:
{
if (!shouldLCDRenderText && aaEnabled) {
// If we have non LCD GDI text, render the fonts as cleartype and convert them
// to grayscale. This seems to be what Chrome and IE are doing on Windows 7.
// This also applies if cleartype is disabled system wide.
paint.mPaint.setFlags(paint.mPaint.getFlags() | SkPaint::kGenA8FromLCD_Flag);
}
break;
}
#ifdef XP_WIN
case FontType::DWRITE:
{
@ -1470,29 +1460,20 @@ DrawTargetSkia::DrawGlyphs(ScaledFont* aFont,
paint.mPaint.setSubpixelText(useSubpixelText);
const uint32_t heapSize = 64;
uint16_t indicesOnStack[heapSize];
SkPoint offsetsOnStack[heapSize];
std::vector<uint16_t> indicesOnHeap;
std::vector<SkPoint> offsetsOnHeap;
uint16_t* indices = indicesOnStack;
SkPoint* offsets = offsetsOnStack;
if (aBuffer.mNumGlyphs > heapSize) {
// Heap allocation/ deallocation is slow, use it only if we need a
// bigger(>heapSize) buffer.
indicesOnHeap.resize(aBuffer.mNumGlyphs);
offsetsOnHeap.resize(aBuffer.mNumGlyphs);
indices = (uint16_t*)&indicesOnHeap.front();
offsets = (SkPoint*)&offsetsOnHeap.front();
Vector<uint16_t, 64> indices;
Vector<SkPoint, 64> offsets;
if (!indices.resizeUninitialized(aBuffer.mNumGlyphs) ||
!offsets.resizeUninitialized(aBuffer.mNumGlyphs)) {
gfxDebug() << "Failed allocating Skia text buffers for GlyphBuffer";
return;
}
for (unsigned int i = 0; i < aBuffer.mNumGlyphs; i++) {
for (uint32_t i = 0; i < aBuffer.mNumGlyphs; i++) {
indices[i] = aBuffer.mGlyphs[i].mIndex;
offsets[i].fX = SkFloatToScalar(aBuffer.mGlyphs[i].mPosition.x);
offsets[i].fY = SkFloatToScalar(aBuffer.mGlyphs[i].mPosition.y);
offsets[i] = PointToSkPoint(aBuffer.mGlyphs[i].mPosition);
}
mCanvas->drawPosText(indices, aBuffer.mNumGlyphs*2, offsets, paint.mPaint);
mCanvas->drawPosText(indices.begin(), indices.length() * sizeof(uint16_t), offsets.begin(), paint.mPaint);
}
void
@ -2037,9 +2018,10 @@ DrawTargetSkia::GetNativeSurface(NativeSurfaceType aType)
{
#ifdef USE_SKIA_GPU
if (aType == NativeSurfaceType::OPENGL_TEXTURE && mSurface) {
GrBackendObject handle = mSurface->getTextureHandle(SkSurface::kFlushRead_BackendHandleAccess);
if (handle) {
return (void*)(uintptr_t)reinterpret_cast<GrGLTextureInfo *>(handle)->fID;
GrBackendTexture tex = mSurface->getBackendTexture(SkSurface::kFlushRead_BackendHandleAccess);
GrGLTextureInfo info;
if (tex.getGLTextureInfo(&info)) {
return (void*)(uintptr_t)info.fID;
}
}
#endif

Просмотреть файл

@ -62,7 +62,18 @@ struct DWRITE_FONT_AXIS_RANGE {
FLOAT maxValue;
};
struct DWRITE_GLYPH_IMAGE_DATA;
struct DWRITE_GLYPH_IMAGE_DATA
{
const void* imageData;
UINT32 imageDataSize;
UINT32 uniqueDataId;
UINT32 pixelsPerEm;
D2D1_SIZE_U pixelSize;
D2D1_POINT_2L horizontalLeftOrigin;
D2D1_POINT_2L horizontalRightOrigin;
D2D1_POINT_2L verticalTopOrigin;
D2D1_POINT_2L verticalBottomOrigin;
};
interface DWRITE_DECLARE_INTERFACE("27F2A904-4EB8-441D-9678-0563F53E3E2F") IDWriteFontFace4
: public IDWriteFontFace3

Просмотреть файл

@ -148,8 +148,8 @@ static GrGLInterface* CreateGrGLInterfaceFromGLContext(GLContext* context)
i->fStandard = kGL_GrGLStandard;
}
GrGLFunction<GrGLGetStringProc> getString = WrapGL(context, &glGetString_mozilla);
GrGLFunction<GrGLGetIntegervProc> getIntegerv = WrapGL(context, &GLContext::fGetIntegerv);
GrGLFunction<GrGLGetStringFn> getString = WrapGL(context, &glGetString_mozilla);
GrGLFunction<GrGLGetIntegervFn> getIntegerv = WrapGL(context, &GLContext::fGetIntegerv);
GrGLExtensions extensions;
if (!extensions.init(i->fStandard, getString, nullptr, getIntegerv)) {
@ -311,7 +311,7 @@ SkiaGLGlue::SkiaGLGlue(GLContext* context)
: mGLContext(context)
{
mGrGLInterface.reset(CreateGrGLInterfaceFromGLContext(mGLContext));
mGrContext.reset(GrContext::Create(kOpenGL_GrBackend, (GrBackendContext)mGrGLInterface.get()));
mGrContext = GrContext::MakeGL(mGrGLInterface);
}
SkiaGLGlue::~SkiaGLGlue()

Просмотреть файл

@ -1,9 +1,9 @@
# The following tests test the async positioning of the scrollbars.
# Basic root-frame scrollbar with async scrolling
fuzzy-if(Android,1-1,2-2) skip-if(!Android) pref(apz.allow_zooming,true) == async-scrollbar-1-v.html async-scrollbar-1-v-ref.html # bug 1392259
fuzzy-if(Android,1-1,1-2) skip-if(!Android) pref(apz.allow_zooming,true) == async-scrollbar-1-v.html async-scrollbar-1-v-ref.html # bug 1392259
fuzzy-if(Android,0-4,0-5) skip-if(!Android) pref(apz.allow_zooming,true) == async-scrollbar-1-h.html async-scrollbar-1-h-ref.html
fuzzy-if(Android,0-3,0-5) skip-if(!Android) pref(apz.allow_zooming,true) == async-scrollbar-1-vh.html async-scrollbar-1-vh-ref.html
fuzzy-if(Android,1-1,2-2) skip-if(!Android) pref(apz.allow_zooming,true) == async-scrollbar-1-v-rtl.html async-scrollbar-1-v-rtl-ref.html # bug 1392259
fuzzy-if(Android,1-1,1-2) skip-if(!Android) pref(apz.allow_zooming,true) == async-scrollbar-1-v-rtl.html async-scrollbar-1-v-rtl-ref.html # bug 1392259
fuzzy-if(Android,0-4,0-5) skip-if(!Android) pref(apz.allow_zooming,true) == async-scrollbar-1-h-rtl.html async-scrollbar-1-h-rtl-ref.html
fuzzy-if(Android,0-3,0-7) skip-if(!Android) pref(apz.allow_zooming,true) == async-scrollbar-1-vh-rtl.html async-scrollbar-1-vh-rtl-ref.html
@ -11,7 +11,7 @@ fuzzy-if(Android,0-3,0-7) skip-if(!Android) pref(apz.allow_zooming,true) == asyn
# compositor, the border-radius ends of the scrollthumb are going to be a little
# off, hence the fuzzy-if clauses.
fuzzy-if(Android,0-54,0-20) skip-if(!Android) pref(apz.allow_zooming,true) == async-scrollbar-zoom-1.html async-scrollbar-zoom-1-ref.html
fuzzy-if(Android,0-45,0-26) skip-if(!Android) pref(apz.allow_zooming,true) == async-scrollbar-zoom-2.html async-scrollbar-zoom-2-ref.html
fuzzy-if(Android,0-45,0-27) skip-if(!Android) pref(apz.allow_zooming,true) == async-scrollbar-zoom-2.html async-scrollbar-zoom-2-ref.html
# Test scrollbars working properly with pinch-zooming, i.e. different document resolutions.
# As above, the end of the scrollthumb won't match perfectly, but the bulk of the scrollbar should be present and identical.

Просмотреть файл

@ -42,6 +42,7 @@ LOCAL_INCLUDES += [
'skia/include/codec',
'skia/include/config',
'skia/include/core',
'skia/include/docs',
'skia/include/effects',
'skia/include/encode',
'skia/include/gpu',
@ -50,7 +51,7 @@ LOCAL_INCLUDES += [
'skia/include/private',
'skia/include/utils',
'skia/include/utils/mac',
'skia/include/views',
'skia/src/codec',
'skia/src/core',
'skia/src/gpu',
'skia/src/gpu/effects',
@ -61,6 +62,7 @@ LOCAL_INCLUDES += [
'skia/src/opts',
'skia/src/sfnt',
'skia/src/shaders',
'skia/src/shaders/gradients',
'skia/src/sksl',
'skia/src/utils',
'skia/src/utils/mac',
@ -68,10 +70,6 @@ LOCAL_INCLUDES += [
]
if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'windows':
if CONFIG['CC_TYPE'] in ('gcc', 'clang'):
DEFINES['SK_JUMPER_USE_ASSEMBLY'] = 0
elif CONFIG['CPU_ARCH'] == 'x86':
SOURCES['skia/src/jumper/SkJumper_generated_win.S'].flags += ['-safeseh']
DEFINES['UNICODE'] = True
DEFINES['_UNICODE'] = True
UNIFIED_SOURCES += [
@ -79,14 +77,6 @@ if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'windows':
'skia/src/fonts/SkRemotableFontMgr.cpp',
]
# Work around a crash when jumping into assembly on platforms where
# Clang has 4-byte stack alignment.
if CONFIG['CPU_ARCH'] == 'x86' and CONFIG['CC_TYPE'] == 'clang':
SOURCES['skia/src/jumper/SkJumper.cpp'].flags += [
'-mstack-alignment=16',
'-mstackrealign'
]
# We should autogenerate these SSE related flags.
if CONFIG['INTEL_ARCHITECTURE'] and (CONFIG['CC_TYPE'] in ('clang', 'clang-cl', 'gcc')):
@ -97,7 +87,7 @@ if CONFIG['INTEL_ARCHITECTURE'] and (CONFIG['CC_TYPE'] in ('clang', 'clang-cl',
SOURCES['skia/src/opts/SkOpts_sse41.cpp'].flags += ['-msse4.1']
SOURCES['skia/src/opts/SkOpts_sse42.cpp'].flags += ['-msse4.2']
SOURCES['skia/src/opts/SkOpts_avx.cpp'].flags += ['-mavx']
SOURCES['skia/src/opts/SkOpts_hsw.cpp'].flags += ['-mavx2']
SOURCES['skia/src/opts/SkOpts_hsw.cpp'].flags += ['-mavx2', '-mf16c', '-mfma']
elif CONFIG['CC_TYPE'] in ('msvc', 'clang-cl') and CONFIG['INTEL_ARCHITECTURE']:
# MSVC doesn't need special compiler flags, but Skia needs to be told that these files should
# be built with the required SSE level or it will simply compile in stubs and cause runtime crashes
@ -212,25 +202,24 @@ def generate_separated_sources(platform_sources):
'skia/src/android/',
'skia/src/atlastext/',
'skia/src/c/',
'skia/src/effects/Gr',
'skia/src/effects/Sk',
'skia/src/effects/',
'skia/src/fonts/',
'skia/src/jumper/SkJumper_generated_win.S',
'skia/src/ports/SkImageEncoder',
'skia/src/ports/SkImageGenerator',
'skia/src/gpu/vk/',
'SkBitmapRegion',
'SkLite',
'SkLight',
'SkNormal',
'codec',
'SkWGL',
'SkMemory_malloc',
'third_party',
'Sk3D',
'SkAnimCodecPlayer',
'SkCamera',
'SkCanvasStack',
'SkCanvasStateUtils',
'SkCurveMeasure',
'SkDeferredCanvas',
'SkDumpCanvas',
'SkFrontBufferedStream',
'SkInterpolator',
'SkMultiPictureDocument',
@ -243,6 +232,7 @@ def generate_separated_sources(platform_sources):
'SkWhitelistTypefaces',
'SkXPS',
'SkCreateCGImageRef',
'skia/src/ports/SkGlobalInitialization',
]
def isblacklisted(value):
@ -254,17 +244,16 @@ def generate_separated_sources(platform_sources):
separated = defaultdict(set, {
'common': {
'skia/src/core/SkBlurImageFilter.cpp',
'skia/src/core/SkGpuBlurUtils.cpp',
'skia/src/effects/GrCircleBlurFragmentProcessor.cpp',
'skia/src/effects/SkBlurMask.cpp',
'skia/src/effects/SkBlurMaskFilter.cpp',
'skia/src/codec/SkMasks.cpp',
'skia/src/effects/imagefilters/SkBlurImageFilter.cpp',
'skia/src/effects/SkDashPathEffect.cpp',
'skia/src/effects/SkImageSource.cpp',
'skia/src/gpu/gl/GrGLMakeNativeInterface_none.cpp',
'skia/src/ports/SkDiscardableMemory_none.cpp',
'skia/src/ports/SkGlobalInitialization_none.cpp',
'skia/src/ports/SkGlobalInitialization_none_imagefilters.cpp',
'skia/src/ports/SkMemory_mozalloc.cpp',
'skia/src/ports/SkImageGenerator_none.cpp',
'skia/third_party/skcms/skcms.cc',
},
'android': {
# 'skia/src/ports/SkDebug_android.cpp',
@ -278,9 +267,6 @@ def generate_separated_sources(platform_sources):
'skia/src/ports/SkFontHost_cairo.cpp',
'skia/src/ports/SkFontHost_FreeType_common.cpp',
},
'no-mingw': {
'skia/src/jumper/SkJumper_generated_win.S',
},
'intel': set(),
'arm': set(),
'arm64': set(),
@ -347,6 +333,7 @@ opt_whitelist = [
'SkJumper',
'SkSpriteBlitter',
'SkMatrix.cpp',
'skcms',
]
# Unfortunately for now the gpu and pathops directories are
@ -366,11 +353,13 @@ unified_blacklist = [
'SkPDFFont.cpp',
'SkPictureData.cpp',
'skia/src/gpu/effects/',
'skia/src/gpu/gradients/',
'GrResourceCache',
'GrResourceProvider',
'GrAA',
'GrGL',
'GrCCPathProcessor',
'GrCCStrokeGeometry',
'GrMSAAPathRenderer.cpp',
'GrNonAAFillRect',
'GrPathUtils',
@ -386,9 +375,9 @@ unified_blacklist = [
'SkRTree.cpp',
'SkVertices.cpp',
'SkJumper',
'SkSLHCodeGenerator.cpp',
'SkSLLexer.cpp',
'SkSLLayoutLexer.cpp',
'SkThreadedBMPDevice.cpp',
] + opt_whitelist
def write_sources(f, values, indent):
@ -456,10 +445,6 @@ def write_mozbuild(sources):
write_sources(f, sources['linux'], 4)
f.write("if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'windows':\n")
f.write(" if CONFIG['CC_TYPE'] not in ('gcc', 'clang') and CONFIG['CPU_ARCH'] != 'aarch64':\n")
write_list(f, "SOURCES", sources['no-mingw'], 8)
# Windows-specific files don't get unification because of nasty headers.
# Luckily there are not many files in this.
write_list(f, "SOURCES", sources['win'], 4)
f.write("if CONFIG['INTEL_ARCHITECTURE']:\n")

Просмотреть файл

@ -23,6 +23,7 @@ if CONFIG['MOZ_OPTIMIZE']:
skia_opt_flags += ['-O3']
UNIFIED_SOURCES += [
'skia/src/codec/SkMasks.cpp',
'skia/src/core/SkAAClip.cpp',
'skia/src/core/SkAlphaRuns.cpp',
'skia/src/core/SkAnalyticEdge.cpp',
@ -39,7 +40,8 @@ UNIFIED_SOURCES += [
'skia/src/core/SkBitmapProvider.cpp',
'skia/src/core/SkBitmapScaler.cpp',
'skia/src/core/SkBlendMode.cpp',
'skia/src/core/SkBlurImageFilter.cpp',
'skia/src/core/SkBlurMask.cpp',
'skia/src/core/SkBlurMF.cpp',
'skia/src/core/SkBuffer.cpp',
'skia/src/core/SkCachedData.cpp',
'skia/src/core/SkCanvas.cpp',
@ -48,9 +50,7 @@ UNIFIED_SOURCES += [
'skia/src/core/SkClipStackDevice.cpp',
'skia/src/core/SkColor.cpp',
'skia/src/core/SkColorFilter.cpp',
'skia/src/core/SkColorLookUpTable.cpp',
'skia/src/core/SkColorMatrixFilterRowMajor255.cpp',
'skia/src/core/SkColorTable.cpp',
'skia/src/core/SkConvertPixels.cpp',
'skia/src/core/SkConvolver.cpp',
'skia/src/core/SkCoverageDelta.cpp',
@ -64,11 +64,10 @@ UNIFIED_SOURCES += [
'skia/src/core/SkDeferredDisplayListRecorder.cpp',
'skia/src/core/SkDeque.cpp',
'skia/src/core/SkDevice.cpp',
'skia/src/core/SkDeviceProfile.cpp',
'skia/src/core/SkDistanceFieldGen.cpp',
'skia/src/core/SkDither.cpp',
'skia/src/core/SkDocument.cpp',
'skia/src/core/SkDraw.cpp',
'skia/src/core/SkDraw_text.cpp',
'skia/src/core/SkDraw_vertices.cpp',
'skia/src/core/SkDrawable.cpp',
'skia/src/core/SkDrawLooper.cpp',
@ -87,7 +86,10 @@ UNIFIED_SOURCES += [
'skia/src/core/SkGaussFilter.cpp',
'skia/src/core/SkGeometry.cpp',
'skia/src/core/SkGlobalInitialization_core.cpp',
'skia/src/core/SkGlyph.cpp',
'skia/src/core/SkGlyphCache.cpp',
'skia/src/core/SkGlyphRun.cpp',
'skia/src/core/SkGlyphRunPainter.cpp',
'skia/src/core/SkGpuBlurUtils.cpp',
'skia/src/core/SkGraphics.cpp',
'skia/src/core/SkHalf.cpp',
@ -113,6 +115,7 @@ UNIFIED_SOURCES += [
'skia/src/core/SkModeColorFilter.cpp',
'skia/src/core/SkMultiPictureDraw.cpp',
'skia/src/core/SkPaint.cpp',
'skia/src/core/SkPaint_text.cpp',
'skia/src/core/SkPaintPriv.cpp',
'skia/src/core/SkPath.cpp',
'skia/src/core/SkPath_serial.cpp',
@ -141,7 +144,6 @@ UNIFIED_SOURCES += [
'skia/src/core/SkRecordOpts.cpp',
'skia/src/core/SkRecords.cpp',
'skia/src/core/SkRect.cpp',
'skia/src/core/SkRefDict.cpp',
'skia/src/core/SkRegion.cpp',
'skia/src/core/SkRegion_path.cpp',
'skia/src/core/SkRemoteGlyphCache.cpp',
@ -159,16 +161,16 @@ UNIFIED_SOURCES += [
'skia/src/core/SkSpecialImage.cpp',
'skia/src/core/SkSpecialSurface.cpp',
'skia/src/core/SkSpinlock.cpp',
'skia/src/core/SkSRGB.cpp',
'skia/src/core/SkStream.cpp',
'skia/src/core/SkStrikeCache.cpp',
'skia/src/core/SkString.cpp',
'skia/src/core/SkStringUtils.cpp',
'skia/src/core/SkStroke.cpp',
'skia/src/core/SkStrokeRec.cpp',
'skia/src/core/SkStrokerPriv.cpp',
'skia/src/core/SkSurfaceCharacterization.cpp',
'skia/src/core/SkSwizzle.cpp',
'skia/src/core/SkTaskGroup.cpp',
'skia/src/core/SkTaskGroup2D.cpp',
'skia/src/core/SkTextBlob.cpp',
'skia/src/core/SkThreadID.cpp',
'skia/src/core/SkTime.cpp',
@ -183,11 +185,8 @@ UNIFIED_SOURCES += [
'skia/src/core/SkWriteBuffer.cpp',
'skia/src/core/SkWriter32.cpp',
'skia/src/core/SkYUVPlanesCache.cpp',
'skia/src/effects/GrCircleBlurFragmentProcessor.cpp',
'skia/src/effects/SkBlurMask.cpp',
'skia/src/effects/SkBlurMaskFilter.cpp',
'skia/src/effects/imagefilters/SkBlurImageFilter.cpp',
'skia/src/effects/SkDashPathEffect.cpp',
'skia/src/effects/SkImageSource.cpp',
'skia/src/image/SkImage.cpp',
'skia/src/image/SkImage_Lazy.cpp',
'skia/src/image/SkImage_Raster.cpp',
@ -210,6 +209,7 @@ UNIFIED_SOURCES += [
'skia/src/pathops/SkOpEdgeBuilder.cpp',
'skia/src/pathops/SkOpSegment.cpp',
'skia/src/pathops/SkOpSpan.cpp',
'skia/src/pathops/SkPathOpsAsWinding.cpp',
'skia/src/pathops/SkPathOpsCommon.cpp',
'skia/src/pathops/SkPathOpsConic.cpp',
'skia/src/pathops/SkPathOpsCubic.cpp',
@ -226,10 +226,9 @@ UNIFIED_SOURCES += [
'skia/src/pathops/SkPathOpsWinding.cpp',
'skia/src/pathops/SkPathWriter.cpp',
'skia/src/pathops/SkReduceOrder.cpp',
'skia/src/pipe/SkPipeCanvas.cpp',
'skia/src/pipe/SkPipeReader.cpp',
'skia/src/ports/SkDiscardableMemory_none.cpp',
'skia/src/ports/SkGlobalInitialization_default.cpp',
'skia/src/ports/SkGlobalInitialization_none.cpp',
'skia/src/ports/SkGlobalInitialization_none_imagefilters.cpp',
'skia/src/ports/SkImageGenerator_none.cpp',
'skia/src/ports/SkMemory_mozalloc.cpp',
'skia/src/ports/SkOSFile_stdio.cpp',
@ -237,13 +236,11 @@ UNIFIED_SOURCES += [
'skia/src/sfnt/SkOTUtils.cpp',
'skia/src/shaders/gradients/Sk4fGradientBase.cpp',
'skia/src/shaders/gradients/Sk4fLinearGradient.cpp',
'skia/src/shaders/gradients/SkGradientBitmapCache.cpp',
'skia/src/shaders/gradients/SkGradientShader.cpp',
'skia/src/shaders/gradients/SkLinearGradient.cpp',
'skia/src/shaders/gradients/SkRadialGradient.cpp',
'skia/src/shaders/gradients/SkSweepGradient.cpp',
'skia/src/shaders/gradients/SkTwoPointConicalGradient.cpp',
'skia/src/shaders/gradients/SkTwoPointConicalGradient_gpu.cpp',
'skia/src/shaders/SkBitmapProcShader.cpp',
'skia/src/shaders/SkColorFilterShader.cpp',
'skia/src/shaders/SkColorShader.cpp',
@ -258,15 +255,17 @@ UNIFIED_SOURCES += [
'skia/src/utils/SkDashPath.cpp',
'skia/src/utils/SkEventTracer.cpp',
'skia/src/utils/SkFloatToDecimal.cpp',
'skia/src/utils/SkInsetConvexPolygon.cpp',
'skia/src/utils/SkJSON.cpp',
'skia/src/utils/SkJSONWriter.cpp',
'skia/src/utils/SkMatrix22.cpp',
'skia/src/utils/SkOSPath.cpp',
'skia/src/utils/SkPatchUtils.cpp',
'skia/src/utils/SkPolyUtils.cpp',
'skia/src/utils/SkShadowTessellator.cpp',
'skia/src/utils/SkShadowUtils.cpp',
'skia/src/utils/SkThreadUtils_pthread.cpp',
'skia/src/utils/SkThreadUtils_win.cpp',
'skia/src/utils/SkUTF.cpp',
'skia/src/utils/win/SkAutoCoInitialize.cpp',
'skia/src/utils/win/SkDWrite.cpp',
'skia/src/utils/win/SkDWriteFontFileStream.cpp',
@ -285,14 +284,9 @@ SOURCES += [
'skia/src/core/SkBlitter_RGB565.cpp',
'skia/src/core/SkBlitter_Sprite.cpp',
'skia/src/core/SkColorSpace.cpp',
'skia/src/core/SkColorSpace_A2B.cpp',
'skia/src/core/SkColorSpace_ICC.cpp',
'skia/src/core/SkColorSpace_New.cpp',
'skia/src/core/SkColorSpace_XYZ.cpp',
'skia/src/core/SkColorSpaceXform.cpp',
'skia/src/core/SkColorSpaceXform_A2B.cpp',
'skia/src/core/SkColorSpaceXformCanvas.cpp',
'skia/src/core/SkColorSpaceXformer.cpp',
'skia/src/core/SkColorSpaceXformSteps.cpp',
'skia/src/core/SkMatrix.cpp',
'skia/src/core/SkMatrix44.cpp',
'skia/src/core/SkMiniRecorder.cpp',
@ -305,17 +299,15 @@ SOURCES += [
'skia/src/core/SkScan_DAAPath.cpp',
'skia/src/core/SkSpriteBlitter_ARGB32.cpp',
'skia/src/core/SkSpriteBlitter_RGB565.cpp',
'skia/src/core/SkThreadedBMPDevice.cpp',
'skia/src/core/SkVertices.cpp',
'skia/src/core/SkXfermode.cpp',
'skia/src/core/SkXfermodeInterpretation.cpp',
'skia/src/gpu/gl/GrGLMakeNativeInterface_none.cpp',
'skia/src/jumper/SkJumper.cpp',
'skia/src/jumper/SkJumper_stages.cpp',
'skia/src/jumper/SkJumper_stages_lowp.cpp',
'skia/src/pathops/SkPathOpsDebug.cpp',
'skia/src/utils/SkParse.cpp',
'skia/src/utils/SkParsePath.cpp',
'skia/third_party/skcms/skcms.cc',
]
SOURCES['skia/src/core/SkBitmapProcState.cpp'].flags += skia_opt_flags
SOURCES['skia/src/core/SkBitmapProcState_matrixProcs.cpp'].flags += skia_opt_flags
@ -331,10 +323,10 @@ SOURCES['skia/src/core/SkOpts.cpp'].flags += skia_opt_flags
SOURCES['skia/src/core/SkSpriteBlitter_ARGB32.cpp'].flags += skia_opt_flags
SOURCES['skia/src/core/SkSpriteBlitter_RGB565.cpp'].flags += skia_opt_flags
SOURCES['skia/src/jumper/SkJumper.cpp'].flags += skia_opt_flags
SOURCES['skia/src/jumper/SkJumper_stages.cpp'].flags += skia_opt_flags
SOURCES['skia/src/jumper/SkJumper_stages_lowp.cpp'].flags += skia_opt_flags
SOURCES['skia/third_party/skcms/skcms.cc'].flags += skia_opt_flags
if CONFIG['MOZ_ENABLE_SKIA_PDF']:
UNIFIED_SOURCES += [
'skia/src/pdf/SkClusterator.cpp',
'skia/src/pdf/SkDeflate.cpp',
'skia/src/pdf/SkJpegInfo.cpp',
'skia/src/pdf/SkKeyedImage.cpp',
@ -351,6 +343,7 @@ if CONFIG['MOZ_ENABLE_SKIA_PDF']:
'skia/src/pdf/SkPDFMetadata.cpp',
'skia/src/pdf/SkPDFResourceDict.cpp',
'skia/src/pdf/SkPDFShader.cpp',
'skia/src/pdf/SkPDFTag.cpp',
'skia/src/pdf/SkPDFTypes.cpp',
'skia/src/pdf/SkPDFUtils.cpp',
]
@ -360,22 +353,26 @@ if CONFIG['MOZ_ENABLE_SKIA_PDF']:
if CONFIG['MOZ_ENABLE_SKIA_GPU']:
UNIFIED_SOURCES += [
'skia/src/gpu/ccpr/GrCCAtlas.cpp',
'skia/src/gpu/ccpr/GrCCClipPath.cpp',
'skia/src/gpu/ccpr/GrCCClipProcessor.cpp',
'skia/src/gpu/ccpr/GrCCConicShader.cpp',
'skia/src/gpu/ccpr/GrCCCoverageProcessor.cpp',
'skia/src/gpu/ccpr/GrCCCoverageProcessor_GSImpl.cpp',
'skia/src/gpu/ccpr/GrCCCoverageProcessor_VSImpl.cpp',
'skia/src/gpu/ccpr/GrCCCubicShader.cpp',
'skia/src/gpu/ccpr/GrCCGeometry.cpp',
'skia/src/gpu/ccpr/GrCCPathParser.cpp',
'skia/src/gpu/ccpr/GrCCDrawPathsOp.cpp',
'skia/src/gpu/ccpr/GrCCFiller.cpp',
'skia/src/gpu/ccpr/GrCCFillGeometry.cpp',
'skia/src/gpu/ccpr/GrCCPathCache.cpp',
'skia/src/gpu/ccpr/GrCCPerFlushResources.cpp',
'skia/src/gpu/ccpr/GrCCQuadraticShader.cpp',
'skia/src/gpu/ccpr/GrCCTriangleShader.cpp',
'skia/src/gpu/ccpr/GrCCStroker.cpp',
'skia/src/gpu/ccpr/GrCoverageCountingPathRenderer.cpp',
'skia/src/gpu/GrAHardwareBufferImageGenerator.cpp',
'skia/src/gpu/GrAuditTrail.cpp',
'skia/src/gpu/GrBackendSurface.cpp',
'skia/src/gpu/GrBackendTextureImageGenerator.cpp',
'skia/src/gpu/GrBitmapTextureMaker.cpp',
'skia/src/gpu/GrBlend.cpp',
'skia/src/gpu/GrBlurUtils.cpp',
'skia/src/gpu/GrBuffer.cpp',
'skia/src/gpu/GrBufferAllocPool.cpp',
@ -384,18 +381,19 @@ if CONFIG['MOZ_ENABLE_SKIA_GPU']:
'skia/src/gpu/GrColorSpaceInfo.cpp',
'skia/src/gpu/GrColorSpaceXform.cpp',
'skia/src/gpu/GrContext.cpp',
'skia/src/gpu/GrDDLContext.cpp',
'skia/src/gpu/GrDefaultGeoProcFactory.cpp',
'skia/src/gpu/GrDirectContext.cpp',
'skia/src/gpu/GrDistanceFieldGenFromVector.cpp',
'skia/src/gpu/GrDrawingManager.cpp',
'skia/src/gpu/GrDrawOpAtlas.cpp',
'skia/src/gpu/GrDrawOpTest.cpp',
'skia/src/gpu/GrDriverBugWorkarounds.cpp',
'skia/src/gpu/GrFixedClip.cpp',
'skia/src/gpu/GrFragmentProcessor.cpp',
'skia/src/gpu/GrGpu.cpp',
'skia/src/gpu/GrGpuCommandBuffer.cpp',
'skia/src/gpu/GrGpuFactory.cpp',
'skia/src/gpu/GrGpuResource.cpp',
'skia/src/gpu/GrGpuResourceRef.cpp',
'skia/src/gpu/GrImageTextureMaker.cpp',
'skia/src/gpu/GrMemoryPool.cpp',
'skia/src/gpu/GrOnFlushResourceProvider.cpp',
@ -404,7 +402,6 @@ if CONFIG['MOZ_ENABLE_SKIA_GPU']:
'skia/src/gpu/GrPaint.cpp',
'skia/src/gpu/GrPath.cpp',
'skia/src/gpu/GrPathProcessor.cpp',
'skia/src/gpu/GrPathRange.cpp',
'skia/src/gpu/GrPathRenderer.cpp',
'skia/src/gpu/GrPathRendererChain.cpp',
'skia/src/gpu/GrPathRendering.cpp',
@ -416,6 +413,7 @@ if CONFIG['MOZ_ENABLE_SKIA_GPU']:
'skia/src/gpu/GrProcessorUnitTest.cpp',
'skia/src/gpu/GrProgramDesc.cpp',
'skia/src/gpu/GrProxyProvider.cpp',
'skia/src/gpu/GrQuad.cpp',
'skia/src/gpu/GrRectanizer_pow2.cpp',
'skia/src/gpu/GrRectanizer_skyline.cpp',
'skia/src/gpu/GrReducedClip.cpp',
@ -435,7 +433,6 @@ if CONFIG['MOZ_ENABLE_SKIA_GPU']:
'skia/src/gpu/GrSurface.cpp',
'skia/src/gpu/GrSurfaceContext.cpp',
'skia/src/gpu/GrSurfaceProxy.cpp',
'skia/src/gpu/GrSurfaceProxyRef.cpp',
'skia/src/gpu/GrSWMaskHelper.cpp',
'skia/src/gpu/GrTessellator.cpp',
'skia/src/gpu/GrTestUtils.cpp',
@ -447,14 +444,17 @@ if CONFIG['MOZ_ENABLE_SKIA_GPU']:
'skia/src/gpu/GrTextureProducer.cpp',
'skia/src/gpu/GrTextureProxy.cpp',
'skia/src/gpu/GrTextureRenderTargetProxy.cpp',
'skia/src/gpu/GrUninstantiateProxyTracker.cpp',
'skia/src/gpu/GrXferProcessor.cpp',
'skia/src/gpu/GrYUVProvider.cpp',
'skia/src/gpu/mock/GrMockGpu.cpp',
'skia/src/gpu/ops/GrAtlasTextOp.cpp',
'skia/src/gpu/ops/GrClearOp.cpp',
'skia/src/gpu/ops/GrClearStencilClipOp.cpp',
'skia/src/gpu/ops/GrCopySurfaceOp.cpp',
'skia/src/gpu/ops/GrDashLinePathRenderer.cpp',
'skia/src/gpu/ops/GrDashOp.cpp',
'skia/src/gpu/ops/GrDebugMarkerOp.cpp',
'skia/src/gpu/ops/GrDefaultPathRenderer.cpp',
'skia/src/gpu/ops/GrDrawAtlasOp.cpp',
'skia/src/gpu/ops/GrDrawPathOp.cpp',
@ -475,37 +475,46 @@ if CONFIG['MOZ_ENABLE_SKIA_GPU']:
'skia/src/gpu/SkGpuDevice.cpp',
'skia/src/gpu/SkGpuDevice_drawTexture.cpp',
'skia/src/gpu/SkGr.cpp',
'skia/src/gpu/text/GrAtlasGlyphCache.cpp',
'skia/src/gpu/text/GrAtlasTextBlob.cpp',
'skia/src/gpu/text/GrAtlasTextBlobVertexRegenerator.cpp',
'skia/src/gpu/text/GrAtlasTextContext.cpp',
'skia/src/gpu/text/GrAtlasManager.cpp',
'skia/src/gpu/text/GrDistanceFieldAdjustTable.cpp',
'skia/src/gpu/text/GrGlyphCache.cpp',
'skia/src/gpu/text/GrSDFMaskFilter.cpp',
'skia/src/gpu/text/GrTextBlob.cpp',
'skia/src/gpu/text/GrTextBlobCache.cpp',
'skia/src/gpu/text/GrTextUtils.cpp',
'skia/src/gpu/text/GrTextBlobVertexRegenerator.cpp',
'skia/src/gpu/text/GrTextContext.cpp',
'skia/src/image/SkImage_GpuBase.cpp',
'skia/src/image/SkImage_GpuYUVA.cpp',
'skia/src/image/SkSurface_Gpu.cpp',
'skia/src/sksl/ir/SkSLSetting.cpp',
'skia/src/sksl/ir/SkSLSymbolTable.cpp',
'skia/src/sksl/ir/SkSLType.cpp',
'skia/src/sksl/ir/SkSLVariableReference.cpp',
'skia/src/sksl/SkSLCFGGenerator.cpp',
'skia/src/sksl/SkSLCompiler.cpp',
'skia/src/sksl/SkSLCPPCodeGenerator.cpp',
'skia/src/sksl/SkSLCPPUniformCTypes.cpp',
'skia/src/sksl/SkSLGLSLCodeGenerator.cpp',
'skia/src/sksl/SkSLHCodeGenerator.cpp',
'skia/src/sksl/SkSLInterpreter.cpp',
'skia/src/sksl/SkSLIRGenerator.cpp',
'skia/src/sksl/SkSLJIT.cpp',
'skia/src/sksl/SkSLMetalCodeGenerator.cpp',
'skia/src/sksl/SkSLParser.cpp',
'skia/src/sksl/SkSLPipelineStageCodeGenerator.cpp',
'skia/src/sksl/SkSLSPIRVCodeGenerator.cpp',
'skia/src/sksl/SkSLString.cpp',
'skia/src/sksl/SkSLUtil.cpp',
]
SOURCES += [
'skia/src/gpu/ccpr/GrCCPathProcessor.cpp',
'skia/src/gpu/ccpr/GrCCStrokeGeometry.cpp',
'skia/src/gpu/effects/GrAARectEffect.cpp',
'skia/src/gpu/effects/GrArithmeticFP.cpp',
'skia/src/gpu/effects/GrAlphaThresholdFragmentProcessor.cpp',
'skia/src/gpu/effects/GrBezierEffect.cpp',
'skia/src/gpu/effects/GrBicubicEffect.cpp',
'skia/src/gpu/effects/GrBitmapTextGeoProc.cpp',
'skia/src/gpu/effects/GrBlurredEdgeFragmentProcessor.cpp',
'skia/src/gpu/effects/GrCircleBlurFragmentProcessor.cpp',
'skia/src/gpu/effects/GrCircleEffect.cpp',
'skia/src/gpu/effects/GrConfigConversionEffect.cpp',
'skia/src/gpu/effects/GrConstColorProcessor.cpp',
@ -514,15 +523,12 @@ if CONFIG['MOZ_ENABLE_SKIA_GPU']:
'skia/src/gpu/effects/GrCustomXfermode.cpp',
'skia/src/gpu/effects/GrDisableColorXP.cpp',
'skia/src/gpu/effects/GrDistanceFieldGeoProc.cpp',
'skia/src/gpu/effects/GrDitherEffect.cpp',
'skia/src/gpu/effects/GrEllipseEffect.cpp',
'skia/src/gpu/effects/GrGaussianConvolutionFragmentProcessor.cpp',
'skia/src/gpu/effects/GrLumaColorFilterEffect.cpp',
'skia/src/gpu/effects/GrMagnifierEffect.cpp',
'skia/src/gpu/effects/GrMatrixConvolutionEffect.cpp',
'skia/src/gpu/effects/GrNonlinearColorSpaceXformEffect.cpp',
'skia/src/gpu/effects/GrOvalEffect.cpp',
'skia/src/gpu/effects/GrOverdrawFragmentProcessor.cpp',
'skia/src/gpu/effects/GrPorterDuffXferProcessor.cpp',
'skia/src/gpu/effects/GrPremulInputFragmentProcessor.cpp',
'skia/src/gpu/effects/GrRectBlurEffect.cpp',
@ -530,10 +536,9 @@ if CONFIG['MOZ_ENABLE_SKIA_GPU']:
'skia/src/gpu/effects/GrRRectEffect.cpp',
'skia/src/gpu/effects/GrShadowGeoProc.cpp',
'skia/src/gpu/effects/GrSimpleTextureEffect.cpp',
'skia/src/gpu/effects/GrSkSLFP.cpp',
'skia/src/gpu/effects/GrSRGBEffect.cpp',
'skia/src/gpu/effects/GrTextureDomain.cpp',
'skia/src/gpu/effects/GrTextureStripAtlas.cpp',
'skia/src/gpu/effects/GrUnpremulInputFragmentProcessor.cpp',
'skia/src/gpu/effects/GrXfermodeFragmentProcessor.cpp',
'skia/src/gpu/effects/GrYUVtoRGBEffect.cpp',
'skia/src/gpu/gl/builders/GrGLProgramBuilder.cpp',
@ -548,7 +553,6 @@ if CONFIG['MOZ_ENABLE_SKIA_GPU']:
'skia/src/gpu/gl/GrGLGpuProgramCache.cpp',
'skia/src/gpu/gl/GrGLInterface.cpp',
'skia/src/gpu/gl/GrGLPath.cpp',
'skia/src/gpu/gl/GrGLPathRange.cpp',
'skia/src/gpu/gl/GrGLPathRendering.cpp',
'skia/src/gpu/gl/GrGLProgram.cpp',
'skia/src/gpu/gl/GrGLProgramDataManager.cpp',
@ -574,6 +578,18 @@ if CONFIG['MOZ_ENABLE_SKIA_GPU']:
'skia/src/gpu/glsl/GrGLSLVarying.cpp',
'skia/src/gpu/glsl/GrGLSLVertexGeoBuilder.cpp',
'skia/src/gpu/glsl/GrGLSLXferProcessor.cpp',
'skia/src/gpu/gradients/GrClampedGradientEffect.cpp',
'skia/src/gpu/gradients/GrDualIntervalGradientColorizer.cpp',
'skia/src/gpu/gradients/GrGradientBitmapCache.cpp',
'skia/src/gpu/gradients/GrGradientShader.cpp',
'skia/src/gpu/gradients/GrLinearGradientLayout.cpp',
'skia/src/gpu/gradients/GrRadialGradientLayout.cpp',
'skia/src/gpu/gradients/GrSingleIntervalGradientColorizer.cpp',
'skia/src/gpu/gradients/GrSweepGradientLayout.cpp',
'skia/src/gpu/gradients/GrTextureGradientColorizer.cpp',
'skia/src/gpu/gradients/GrTiledGradientEffect.cpp',
'skia/src/gpu/gradients/GrTwoPointConicalGradientLayout.cpp',
'skia/src/gpu/gradients/GrUnrolledBinaryGradientColorizer.cpp',
'skia/src/gpu/GrPathUtils.cpp',
'skia/src/gpu/GrResourceCache.cpp',
'skia/src/gpu/GrResourceProvider.cpp',
@ -583,11 +599,10 @@ if CONFIG['MOZ_ENABLE_SKIA_GPU']:
'skia/src/gpu/ops/GrAAHairLinePathRenderer.cpp',
'skia/src/gpu/ops/GrAALinearizingConvexPathRenderer.cpp',
'skia/src/gpu/ops/GrAAStrokeRectOp.cpp',
'skia/src/gpu/ops/GrMSAAPathRenderer.cpp',
'skia/src/gpu/ops/GrNonAAFillRectOp.cpp',
'skia/src/gpu/ops/GrShadowRRectOp.cpp',
'skia/src/image/SkImage_Gpu.cpp',
'skia/src/sksl/SkSLLayoutLexer.cpp',
'skia/src/sksl/SkSLHCodeGenerator.cpp',
'skia/src/sksl/SkSLLexer.cpp',
]
if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'android':
@ -598,7 +613,6 @@ if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'android':
'skia/src/ports/SkTLS_pthread.cpp',
]
SOURCES += [
'skia/src/jumper/SkJumper_generated.S',
'skia/src/ports/SkFontHost_cairo.cpp',
'skia/src/ports/SkFontHost_FreeType_common.cpp',
]
@ -610,7 +624,6 @@ if CONFIG['MOZ_WIDGET_TOOLKIT'] in ('cocoa', 'uikit'):
'skia/src/ports/SkTLS_pthread.cpp',
]
SOURCES += [
'skia/src/jumper/SkJumper_generated.S',
'skia/src/ports/SkFontHost_mac.cpp',
]
if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gtk3':
@ -621,15 +634,10 @@ if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gtk3':
'skia/src/ports/SkTLS_pthread.cpp',
]
SOURCES += [
'skia/src/jumper/SkJumper_generated.S',
'skia/src/ports/SkFontHost_cairo.cpp',
'skia/src/ports/SkFontHost_FreeType_common.cpp',
]
if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'windows':
if CONFIG['CC_TYPE'] not in ('gcc', 'clang') and CONFIG['CPU_ARCH'] != 'aarch64':
SOURCES += [
'skia/src/jumper/SkJumper_generated_win.S',
]
SOURCES += [
'skia/src/ports/SkDebug_win.cpp',
'skia/src/ports/SkFontHost_win.cpp',
@ -716,6 +724,7 @@ LOCAL_INCLUDES += [
'skia/include/codec',
'skia/include/config',
'skia/include/core',
'skia/include/docs',
'skia/include/effects',
'skia/include/encode',
'skia/include/gpu',
@ -724,7 +733,7 @@ LOCAL_INCLUDES += [
'skia/include/private',
'skia/include/utils',
'skia/include/utils/mac',
'skia/include/views',
'skia/src/codec',
'skia/src/core',
'skia/src/gpu',
'skia/src/gpu/effects',
@ -735,6 +744,7 @@ LOCAL_INCLUDES += [
'skia/src/opts',
'skia/src/sfnt',
'skia/src/shaders',
'skia/src/shaders/gradients',
'skia/src/sksl',
'skia/src/utils',
'skia/src/utils/mac',
@ -742,10 +752,6 @@ LOCAL_INCLUDES += [
]
if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'windows':
if CONFIG['CC_TYPE'] in ('gcc', 'clang'):
DEFINES['SK_JUMPER_USE_ASSEMBLY'] = 0
elif CONFIG['CPU_ARCH'] == 'x86':
SOURCES['skia/src/jumper/SkJumper_generated_win.S'].flags += ['-safeseh']
DEFINES['UNICODE'] = True
DEFINES['_UNICODE'] = True
UNIFIED_SOURCES += [
@ -753,14 +759,6 @@ if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'windows':
'skia/src/fonts/SkRemotableFontMgr.cpp',
]
# Work around a crash when jumping into assembly on platforms where
# Clang has 4-byte stack alignment.
if CONFIG['CPU_ARCH'] == 'x86' and CONFIG['CC_TYPE'] == 'clang':
SOURCES['skia/src/jumper/SkJumper.cpp'].flags += [
'-mstack-alignment=16',
'-mstackrealign'
]
# We should autogenerate these SSE related flags.
if CONFIG['INTEL_ARCHITECTURE'] and (CONFIG['CC_TYPE'] in ('clang', 'clang-cl', 'gcc')):
@ -771,7 +769,7 @@ if CONFIG['INTEL_ARCHITECTURE'] and (CONFIG['CC_TYPE'] in ('clang', 'clang-cl',
SOURCES['skia/src/opts/SkOpts_sse41.cpp'].flags += ['-msse4.1']
SOURCES['skia/src/opts/SkOpts_sse42.cpp'].flags += ['-msse4.2']
SOURCES['skia/src/opts/SkOpts_avx.cpp'].flags += ['-mavx']
SOURCES['skia/src/opts/SkOpts_hsw.cpp'].flags += ['-mavx2']
SOURCES['skia/src/opts/SkOpts_hsw.cpp'].flags += ['-mavx2', '-mf16c', '-mfma']
elif CONFIG['CC_TYPE'] in ('msvc', 'clang-cl') and CONFIG['INTEL_ARCHITECTURE']:
# MSVC doesn't need special compiler flags, but Skia needs to be told that these files should
# be built with the required SSE level or it will simply compile in stubs and cause runtime crashes

Просмотреть файл

@ -107,7 +107,20 @@ private:
int fIndex;
SkCodecAnimation::DisposalMethod fDisposalMethod;
// init() may have to create a new SkPixelRef, if the
// current one is already in use by another owner (e.g.
// an SkPicture). This determines whether to copy the
// existing one to the new one.
enum class OnInit {
// Restore the image from the old SkPixelRef to the
// new one.
kRestoreIfNecessary,
// No need to restore.
kNoRestore,
};
Frame();
bool init(const SkImageInfo& info, OnInit);
bool copyTo(Frame*) const;
};
@ -122,7 +135,8 @@ private:
bool fFinished;
int fCurrentFrameDuration;
Frame fActiveFrame;
Frame fDisplayFrame;
Frame fDecodingFrame;
Frame fRestoreFrame;
int fRepetitionCount;
int fRepetitionsCompleted;

Просмотреть файл

@ -30,7 +30,8 @@ public:
/** Color, same value for all four corners of a glyph quad. */
uint32_t fColor;
/** Texture coordinate (in texel units, not normalized). */
SkIPoint16 fTextureCoord;
int16_t fTextureCoordX;
int16_t fTextureCoordY;
};
virtual ~SkAtlasTextRenderer() = default;

Просмотреть файл

@ -8,11 +8,12 @@
#ifndef SkAtlasTextTarget_DEFINED
#define SkAtlasTextTarget_DEFINED
#include <memory>
#include "SkDeque.h"
#include "SkRefCnt.h"
#include "SkScalar.h"
#include <memory>
class SkAtlasTextContext;
class SkAtlasTextFont;
class SkMatrix;
@ -27,7 +28,9 @@ public:
* Creates a text drawing target. handle is used to identify this rendering surface when
* draws are flushed to the SkAtlasTextContext's SkAtlasTextRenderer.
*/
static std::unique_ptr<SkAtlasTextTarget> Make(sk_sp<SkAtlasTextContext>, int width, int height,
static std::unique_ptr<SkAtlasTextTarget> Make(sk_sp<SkAtlasTextContext>,
int width,
int height,
void* handle);
/**

Просмотреть файл

@ -0,0 +1,25 @@
/*
* Copyright 2018 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
// EXPERIMENTAL EXPERIMENTAL EXPERIMENTAL EXPERIMENTAL
// DO NOT USE -- FOR INTERNAL TESTING ONLY
#ifndef sk_imageinfo_DEFINED
#define sk_imageinfo_DEFINED
#include "sk_types.h"
SK_C_PLUS_PLUS_BEGIN_GUARD
sk_colorspace_t* sk_colorspace_new_srgb();
void sk_colorspace_ref(sk_colorspace_t*);
void sk_colorspace_unref(sk_colorspace_t*);
SK_C_PLUS_PLUS_END_GUARD
#endif

Просмотреть файл

@ -0,0 +1,62 @@
/*
* Copyright 2018 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
// EXPERIMENTAL EXPERIMENTAL EXPERIMENTAL EXPERIMENTAL
// DO NOT USE -- FOR INTERNAL TESTING ONLY
#ifndef sk_imageinfo_DEFINED
#define sk_imageinfo_DEFINED
#include "sk_types.h"
SK_C_PLUS_PLUS_BEGIN_GUARD
typedef enum {
UNKNOWN_SK_COLORTYPE,
RGBA_8888_SK_COLORTYPE,
BGRA_8888_SK_COLORTYPE,
ALPHA_8_SK_COLORTYPE,
GRAY_8_SK_COLORTYPE,
RGBA_F16_SK_COLORTYPE,
RGBA_F32_SK_COLORTYPE,
} sk_colortype_t;
typedef enum {
OPAQUE_SK_ALPHATYPE,
PREMUL_SK_ALPHATYPE,
UNPREMUL_SK_ALPHATYPE,
} sk_alphatype_t;
/**
* Allocate a new imageinfo object. If colorspace is not null, it's owner-count will be
* incremented automatically.
*/
sk_imageinfo_t* sk_imageinfo_new(int width, int height, sk_colortype_t ct, sk_alphatype_t at,
sk_colorspace_t* cs);
/**
* Free the imageinfo object. If it contains a reference to a colorspace, its owner-count will
* be decremented automatically.
*/
void sk_imageinfo_delete(sk_imageinfo_t*);
int32_t sk_imageinfo_get_width(sk_imageinfo_t*);
int32_t sk_imageinfo_get_height(sk_imageinfo_t*);
sk_colortype_t sk_imageinfo_get_colortype(sk_imageinfo_t*);
sk_alphatype_t sk_imageinfo_get_alphatype(sk_imageinfo_t*);
/**
* Return the colorspace object reference contained in the imageinfo, or null if there is none.
* Note: this does not modify the owner-count on the colorspace object. If the caller needs to
* use the colorspace beyond the lifetime of the imageinfo, it should manually call
* sk_colorspace_ref() (and then call unref() when it is done).
*/
sk_colorspace_t* sk_imageinfo_get_colorspace(sk_imageinfo_t*);
SK_C_PLUS_PLUS_END_GUARD
#endif

Просмотреть файл

@ -52,19 +52,6 @@ typedef uint32_t sk_color_t;
#define sk_color_get_g(c) (((c) >> 8) & 0xFF)
#define sk_color_get_b(c) (((c) >> 0) & 0xFF)
typedef enum {
UNKNOWN_SK_COLORTYPE,
RGBA_8888_SK_COLORTYPE,
BGRA_8888_SK_COLORTYPE,
ALPHA_8_SK_COLORTYPE,
} sk_colortype_t;
typedef enum {
OPAQUE_SK_ALPHATYPE,
PREMUL_SK_ALPHATYPE,
UNPREMUL_SK_ALPHATYPE,
} sk_alphatype_t;
typedef enum {
INTERSECT_SK_CLIPTYPE,
DIFFERENCE_SK_CLIPTYPE,
@ -78,18 +65,6 @@ typedef enum {
BGR_V_SK_PIXELGEOMETRY,
} sk_pixelgeometry_t;
/**
Return the default sk_colortype_t; this is operating-system dependent.
*/
SK_API sk_colortype_t sk_colortype_get_default_8888(void);
typedef struct {
int32_t width;
int32_t height;
sk_colortype_t colorType;
sk_alphatype_t alphaType;
} sk_imageinfo_t;
typedef struct {
sk_pixelgeometry_t pixelGeometry;
} sk_surfaceprops_t;
@ -187,6 +162,17 @@ typedef struct sk_data_t sk_data_t;
encoded data or other means.
*/
typedef struct sk_image_t sk_image_t;
/**
* Describes the color components. See ICC Profiles.
*/
typedef struct sk_colorspace_t sk_colorspace_t;
/**
* Describes an image buffer : width, height, pixel type, colorspace, etc.
*/
typedef struct sk_imageinfo_t sk_imageinfo_t;
/**
A sk_maskfilter_t is an object that perform transformations on an
alpha-channel mask before drawing it; it may be installed into a

Просмотреть файл

@ -8,11 +8,11 @@
#ifndef SkCodec_DEFINED
#define SkCodec_DEFINED
#include "../private/SkNoncopyable.h"
#include "../private/SkTemplates.h"
#include "../private/SkEncodedInfo.h"
#include "SkCodecAnimation.h"
#include "SkColor.h"
#include "SkColorSpaceXform.h"
#include "SkEncodedImageFormat.h"
#include "SkEncodedOrigin.h"
#include "SkImageInfo.h"
@ -34,7 +34,6 @@ namespace DM {
class CodecSrc;
class ColorCodecSrc;
}
class ColorCodecBench;
/**
* Abstraction layer directly on top of an image codec.
@ -170,9 +169,14 @@ public:
virtual ~SkCodec();
/**
* Return the ImageInfo associated with this codec.
* Return a reasonable SkImageInfo to decode into.
*/
const SkImageInfo& getInfo() const { return fSrcInfo; }
SkImageInfo getInfo() const { return fEncodedInfo.makeImageInfo(); }
SkISize dimensions() const { return {fEncodedInfo.width(), fEncodedInfo.height()}; }
SkIRect bounds() const {
return SkIRect::MakeWH(fEncodedInfo.width(), fEncodedInfo.height());
}
/**
* Returns the image orientation stored in the EXIF data.
@ -197,7 +201,7 @@ public:
// Upscaling is not supported. Return the original size if the client
// requests an upscale.
if (desiredScale >= 1.0f) {
return this->getInfo().dimensions();
return this->dimensions();
}
return this->onGetScaledDimensions(desiredScale);
}
@ -252,8 +256,7 @@ public:
: fZeroInitialized(kNo_ZeroInitialized)
, fSubset(nullptr)
, fFrameIndex(0)
, fPriorFrame(kNone)
, fPremulBehavior(SkTransferFunctionBehavior::kRespect)
, fPriorFrame(kNoFrame)
{}
ZeroInitialized fZeroInitialized;
@ -284,7 +287,7 @@ public:
int fFrameIndex;
/**
* If not kNone, the dst already contains the prior frame at this index.
* If not kNoFrame, the dst already contains the prior frame at this index.
*
* Only meaningful for multi-frame images.
*
@ -294,17 +297,9 @@ public:
* indicate that that frame is already in the dst. Options.fZeroInitialized
* is ignored in this case.
*
* If set to kNone, the codec will decode any necessary required frame(s) first.
* If set to kNoFrame, the codec will decode any necessary required frame(s) first.
*/
int fPriorFrame;
/**
* Indicates whether we should do a linear premultiply or a legacy premultiply.
*
* In the case where the dst SkColorSpace is nullptr, this flag is ignored and
* we will always do a legacy premultiply.
*/
SkTransferFunctionBehavior fPremulBehavior;
};
/**
@ -580,9 +575,17 @@ public:
return this->onGetFrameCount();
}
// The required frame for an independent frame is marked as
// kNone.
static constexpr int kNone = -1;
// Sentinel value used when a frame index implies "no frame":
// - FrameInfo::fRequiredFrame set to this value means the frame
// is independent.
// - Options::fPriorFrame set to this value means no (relevant) prior frame
// is residing in dst's memory.
static constexpr int kNoFrame = -1;
// This transitional definition was added in August 2018, and will eventually be removed.
#ifdef SK_LEGACY_SKCODEC_NONE_ENUM
static constexpr int kNone = kNoFrame;
#endif
/**
* Information about individual frames in a multi-framed image.
@ -590,7 +593,7 @@ public:
struct FrameInfo {
/**
* The frame that this frame needs to be blended with, or
* kNone if this frame is independent.
* kNoFrame if this frame is independent.
*
* Note that this is the *earliest* frame that can be used
* for blending. Any frame from [fRequiredFrame, i) can be
@ -645,20 +648,25 @@ public:
*
* As such, future decoding calls may require a rewind.
*
* For single-frame images, this will return an empty vector.
* For still (non-animated) image codecs, this will return an empty vector.
*/
std::vector<FrameInfo> getFrameInfo();
static constexpr int kRepetitionCountInfinite = -1;
/**
* Return the number of times to repeat, if this image is animated.
* Return the number of times to repeat, if this image is animated. This number does not
* include the first play through of each frame. For example, a repetition count of 4 means
* that each frame is played 5 times and then the animation stops.
*
* It can return kRepetitionCountInfinite, a negative number, meaning that the animation
* should loop forever.
*
* May require reading the stream to find the repetition count.
*
* As such, future decoding calls may require a rewind.
*
* For single-frame images, this will return 0.
* For still (non-animated) image codecs, this will return 0.
*/
int getRepetitionCount() {
return this->onGetRepetitionCount();
@ -667,28 +675,16 @@ public:
protected:
const SkEncodedInfo& getEncodedInfo() const { return fEncodedInfo; }
using XformFormat = SkColorSpaceXform::ColorFormat;
using XformFormat = skcms_PixelFormat;
SkCodec(int width,
int height,
const SkEncodedInfo&,
XformFormat srcFormat,
std::unique_ptr<SkStream>,
sk_sp<SkColorSpace>,
SkEncodedOrigin = kTopLeft_SkEncodedOrigin);
/**
* Allows the subclass to set the recommended SkImageInfo
*/
SkCodec(const SkEncodedInfo&,
const SkImageInfo&,
SkCodec(SkEncodedInfo&&,
XformFormat srcFormat,
std::unique_ptr<SkStream>,
SkEncodedOrigin = kTopLeft_SkEncodedOrigin);
virtual SkISize onGetScaledDimensions(float /*desiredScale*/) const {
// By default, scaling is not supported.
return this->getInfo().dimensions();
return this->dimensions();
}
// FIXME: What to do about subsets??
@ -732,8 +728,8 @@ protected:
* @returns true if the codec is at the right position and can be used.
* false if there was a failure to rewind.
*
* This is called by getPixels() and start(). Subclasses may call if they
* need to rewind at another time.
* This is called by getPixels(), getYUV8Planes(), startIncrementalDecode() and
* startScanlineDecode(). Subclasses may call if they need to rewind at another time.
*/
bool SK_WARN_UNUSED_RESULT rewindIfNeeded();
@ -746,34 +742,6 @@ protected:
return true;
}
/**
* On an incomplete input, getPixels() and getScanlines() will fill any uninitialized
* scanlines. This allows the subclass to indicate what value to fill with.
*
* @param dstInfo Describes the destination.
* @return The value with which to fill uninitialized pixels.
*
* Note that we can interpret the return value as a 64-bit Float16 color, a SkPMColor,
* a 16-bit 565 color, an 8-bit gray color, or an 8-bit index into a color table,
* depending on the color type.
*/
uint64_t getFillValue(const SkImageInfo& dstInfo) const {
return this->onGetFillValue(dstInfo);
}
/**
* Some subclasses will override this function, but this is a useful default for the color
* types that we support. Note that for color types that do not use the full 64-bits,
* we will simply take the low bits of the fill value.
*
* The defaults are:
* kRGBA_F16_SkColorType: Transparent or Black, depending on the src alpha type
* kN32_SkColorType: Transparent or Black, depending on the src alpha type
* kRGB_565_SkColorType: Black
* kGray_8_SkColorType: Black
*/
virtual uint64_t onGetFillValue(const SkImageInfo& dstInfo) const;
/**
* Get method for the input stream
*/
@ -804,17 +772,14 @@ protected:
virtual int onOutputScanline(int inputScanline) const;
bool initializeColorXform(const SkImageInfo& dstInfo, SkEncodedInfo::Alpha,
SkTransferFunctionBehavior premulBehavior);
// Some classes never need a colorXform e.g.
// - ICO uses its embedded codec's colorXform
// - WBMP is just Black/White
virtual bool usesColorXform() const { return true; }
void applyColorXform(void* dst, const void* src, int count, SkAlphaType) const;
void applyColorXform(void* dst, const void* src, int count) const;
SkColorSpaceXform* colorXform() const { return fColorXform.get(); }
bool xformOnDecode() const { return fXformOnDecode; }
bool colorXform() const { return fXformTime != kNo_XformTime; }
bool xformOnDecode() const { return fXformTime == kDecodeRow_XformTime; }
virtual int onGetFrameCount() {
return 1;
@ -830,7 +795,6 @@ protected:
private:
const SkEncodedInfo fEncodedInfo;
const SkImageInfo fSrcInfo;
const XformFormat fSrcXformFormat;
std::unique_ptr<SkStream> fStream;
bool fNeedsRewind;
@ -838,9 +802,16 @@ private:
SkImageInfo fDstInfo;
Options fOptions;
enum XformTime {
kNo_XformTime,
kPalette_XformTime,
kDecodeRow_XformTime,
};
XformTime fXformTime;
XformFormat fDstXformFormat; // Based on fDstInfo.
std::unique_ptr<SkColorSpaceXform> fColorXform;
bool fXformOnDecode;
skcms_ICCProfile fDstProfile;
skcms_AlphaFormat fDstXformAlphaFormat;
// Only meaningful during scanline decodes.
int fCurrScanline;
@ -848,12 +819,15 @@ private:
bool fStartedIncrementalDecode;
/**
* Return whether {srcColor, srcIsOpaque, srcCS} can convert to dst.
* Return whether we can convert to dst.
*
* Will be called for the appropriate frame, prior to initializing the colorXform.
*/
virtual bool conversionSupported(const SkImageInfo& dst, SkColorType srcColor,
bool srcIsOpaque, const SkColorSpace* srcCS) const;
virtual bool conversionSupported(const SkImageInfo& dst, bool srcIsOpaque,
bool needsColorXform);
bool initializeColorXform(const SkImageInfo& dstInfo, SkEncodedInfo::Alpha, bool srcIsOpaque);
/**
* Return whether these dimensions are supported as a scale.
*
@ -864,7 +838,7 @@ private:
* This must return true for a size returned from getScaledDimensions.
*/
bool dimensionsSupported(const SkISize& dim) {
return dim == fSrcInfo.dimensions() || this->onDimensionsSupported(dim);
return dim == this->dimensions() || this->onDimensionsSupported(dim);
}
/**

Просмотреть файл

@ -100,14 +100,6 @@
*/
//#define SK_MAX_SIZE_FOR_LCDTEXT 48
/* If SK_DEBUG is defined, then you can optionally define SK_SUPPORT_UNITTEST
which will run additional self-tests at startup. These can take a long time,
so this flag is optional.
*/
#ifdef SK_DEBUG
//#define SK_SUPPORT_UNITTEST
#endif
/* Change the ordering to work in X windows.
*/
//#ifdef SK_SAMPLES_FOR_X
@ -152,8 +144,6 @@
#define SK_SUPPORT_DEPRECATED_CLIPOPS
#define SK_DISABLE_EXPLICIT_GPU_RESOURCE_ALLOCATION
#ifndef MOZ_IMPLICIT
# ifdef MOZ_CLANG_PLUGIN
# define MOZ_IMPLICIT __attribute__((annotate("moz_implicit")))

Просмотреть файл

@ -5,6 +5,16 @@
* found in the LICENSE file.
*/
/* Generated by tools/bookmaker from include/core/SkBitmap.h and docs/SkBitmap_Reference.bmh
on 2018-09-13 13:59:55. Additional documentation and examples can be found at:
https://skia.org/user/api/SkBitmap_Reference
You may edit either file directly. Structural changes to public interfaces require
editing both files. After editing docs/SkBitmap_Reference.bmh, run:
bookmaker -b docs -i include/core/SkBitmap.h -p
to create an updated version of this file.
*/
#ifndef SkBitmap_DEFINED
#define SkBitmap_DEFINED
@ -29,8 +39,8 @@ class SkString;
SkImageInfo bounds may be located anywhere fully inside SkPixelRef bounds.
SkBitmap can be drawn using SkCanvas. SkBitmap can be a drawing destination for SkCanvas
draw methods. SkBitmap flexibility as a pixel container limits some optimizations
available to the target platform.
draw member functions. SkBitmap flexibility as a pixel container limits some
optimizations available to the target platform.
If pixel array is primarily read-only, use SkImage for better performance.
If pixel array is primarily written to, use SkSurface for better performance.
@ -112,10 +122,10 @@ public:
*/
const SkImageInfo& info() const { return fPixmap.info(); }
/** Returns pixel count in each row. Should be equal or less than:
/** Returns pixel count in each row. Should be equal or less than
rowBytes() / info().bytesPerPixel().
Maybe be less than pixelRef().width(). Will not exceed pixelRef().width() less
May be less than pixelRef().width(). Will not exceed pixelRef().width() less
pixelRefOrigin().fX.
@return pixel width in SkImageInfo
@ -131,16 +141,19 @@ public:
*/
int height() const { return fPixmap.height(); }
/** Returns SkColorType, one of: kUnknown_SkColorType, kAlpha_8_SkColorType,
kRGB_565_SkColorType, kARGB_4444_SkColorType, kRGBA_8888_SkColorType,
kBGRA_8888_SkColorType, kGray_8_SkColorType, kRGBA_F16_SkColorType.
/** Returns SkColorType, one of:
kUnknown_SkColorType, kAlpha_8_SkColorType, kRGB_565_SkColorType,
kARGB_4444_SkColorType, kRGBA_8888_SkColorType, kRGB_888x_SkColorType,
kBGRA_8888_SkColorType, kRGBA_1010102_SkColorType, kRGB_101010x_SkColorType,
kGray_8_SkColorType, kRGBA_F16_SkColorType.
@return SkColorType in SkImageInfo
*/
SkColorType colorType() const { return fPixmap.colorType(); }
/** Returns SkAlphaType, one of: kUnknown_SkAlphaType, kOpaque_SkAlphaType,
kPremul_SkAlphaType, kUnpremul_SkAlphaType.
/** Returns SkAlphaType, one of:
kUnknown_SkAlphaType, kOpaque_SkAlphaType, kPremul_SkAlphaType,
kUnpremul_SkAlphaType.
@return SkAlphaType in SkImageInfo
*/
@ -154,7 +167,7 @@ public:
*/
SkColorSpace* colorSpace() const { return fPixmap.colorSpace(); }
/** Returns a smart pointer to SkColorSpace, the range of colors, associated with
/** Returns smart pointer to SkColorSpace, the range of colors, associated with
SkImageInfo. The smart pointer tracks the number of objects sharing this
SkColorSpace reference so the memory is released when the owners destruct.
@ -194,7 +207,7 @@ public:
*/
bool empty() const { return fPixmap.info().isEmpty(); }
/** Return true if SkPixelRef is nullptr.
/** Returns true if SkPixelRef is nullptr.
Does not check if width() or height() are zero; call drawsNothing() to check
width(), height(), and SkPixelRef.
@ -203,7 +216,7 @@ public:
*/
bool isNull() const { return nullptr == fPixelRef; }
/** Return true if width() or height() are zero, or if SkPixelRef is nullptr.
/** Returns true if width() or height() are zero, or if SkPixelRef is nullptr.
If true, SkBitmap has no effect when drawn or drawn into.
@return true if drawing has no effect
@ -213,7 +226,7 @@ public:
}
/** Returns row bytes, the interval from one pixel row to the next. Row bytes
is at least as large as width() * info().bytesPerPixel().
is at least as large as: width() * info().bytesPerPixel().
Returns zero if colorType() is kUnknown_SkColorType, or if row bytes supplied to
setInfo() is not large enough to hold a row of pixels.
@ -245,8 +258,9 @@ public:
This changes SkAlphaType in SkPixelRef; all bitmaps sharing SkPixelRef
are affected.
@param alphaType one of: kUnknown_SkAlphaType, kOpaque_SkAlphaType,
kPremul_SkAlphaType, kUnpremul_SkAlphaType
@param alphaType one of:
kUnknown_SkAlphaType, kOpaque_SkAlphaType, kPremul_SkAlphaType,
kUnpremul_SkAlphaType
@return true if SkAlphaType is set
*/
bool setAlphaType(SkAlphaType alphaType);
@ -283,18 +297,21 @@ public:
*/
void setImmutable();
/** Returns true if SkAlphaType is kOpaque_SkAlphaType.
/** Returns true if SkAlphaType is set to hint that all pixels are opaque; their
alpha value is implicitly or explicitly 1.0. If true, and all pixels are
not opaque, Skia may draw incorrectly.
Does not check if SkColorType allows alpha, or if any pixel value has
transparency.
@return true if SkImageInfo describes opaque alpha
@return true if SkImageInfo SkAlphaType is kOpaque_SkAlphaType
*/
bool isOpaque() const {
return SkAlphaTypeIsOpaque(this->alphaType());
}
/** If true, provides a hint to caller that pixels should not
be cached. Only true if setIsVolatile() has been called to mark as volatile.
/** Provides a hint to caller that pixels should not be cached. Only true if
setIsVolatile() has been called to mark as volatile.
Volatile state is not shared by other bitmaps sharing the same SkPixelRef.
@ -412,8 +429,7 @@ public:
AllocFlags provides the option to zero pixel memory when allocated.
*/
enum AllocFlags {
/** Instructs tryAllocPixelsFlags() and allocPixelsFlags() to zero pixel memory. */
kZeroPixels_AllocFlag = 1 << 0,
kZeroPixels_AllocFlag = 1 << 0, //!< zero pixel memory
};
/** Sets SkImageInfo to info following the rules in setInfo() and allocates pixel
@ -428,8 +444,8 @@ public:
implementation of malloc(), if flags is zero, and calloc(), if flags is
kZeroPixels_AllocFlag.
Passing kZeroPixels_AllocFlag is usually faster than separately calling
eraseColor(SK_ColorTRANSPARENT).
flags set to kZeroPixels_AllocFlag offers equal or better performance than
subsequently calling eraseColor() with SK_ColorTRANSPARENT.
@param info contains width, height, SkAlphaType, SkColorType, SkColorSpace
@param flags kZeroPixels_AllocFlag, or zero
@ -451,8 +467,8 @@ public:
implementation of malloc(), if flags is zero, and calloc(), if flags is
kZeroPixels_AllocFlag.
Passing kZeroPixels_AllocFlag is usually faster than separately calling
eraseColor(SK_ColorTRANSPARENT).
flags set to kZeroPixels_AllocFlag offers equal or better performance than
subsequently calling eraseColor() with SK_ColorTRANSPARENT.
@param info contains width, height, SkAlphaType, SkColorType, SkColorSpace
@param flags kZeroPixels_AllocFlag, or zero
@ -535,7 +551,7 @@ public:
this->allocPixels(info, info.minRowBytes());
}
/** Sets SkImageInfo to width, height, and native SkColorType; and allocates
/** Sets SkImageInfo to width, height, and native color type; and allocates
pixel memory. If isOpaque is true, sets SkImageInfo to kOpaque_SkAlphaType;
otherwise, sets to kPremul_SkAlphaType.
@ -558,7 +574,7 @@ public:
return this->tryAllocPixels(info);
}
/** Sets SkImageInfo to width, height, and the native SkColorType; and allocates
/** Sets SkImageInfo to width, height, and the native color type; and allocates
pixel memory. If isOpaque is true, sets SkImageInfo to kPremul_SkAlphaType;
otherwise, sets to kOpaque_SkAlphaType.
@ -762,7 +778,7 @@ public:
void notifyPixelsChanged() const;
/** Replaces pixel values with c. All pixels contained by bounds() are affected.
If the colorType() is kGray_8_SkColorType or k565_SkColorType, then color alpha
If the colorType() is kGray_8_SkColorType or k565_SkColorType, then alpha
is ignored; RGB is treated as opaque. If colorType() is kAlpha_8_SkColorType,
then RGB is ignored.
@ -776,30 +792,19 @@ public:
is ignored; r, g, and b are treated as opaque. If colorType() is kAlpha_8_SkColorType,
then r, g, and b are ignored.
@param a amount of color alpha, from fully transparent (0) to fully opaque (255)
@param r amount of color rgb red, from no red (0) to full red (255)
@param g amount of color rgb green, from no green (0) to full green (255)
@param b amount of color rgb blue, from no blue (0) to full blue (255)
@param a amount of alpha, from fully transparent (0) to fully opaque (255)
@param r amount of red, from no red (0) to full red (255)
@param g amount of green, from no green (0) to full green (255)
@param b amount of blue, from no blue (0) to full blue (255)
*/
void eraseARGB(U8CPU a, U8CPU r, U8CPU g, U8CPU b) const {
this->eraseColor(SkColorSetARGB(a, r, g, b));
}
/** Deprecated. Use eraseARGB() or eraseColor().
@param r amount of red
@param g amount of green
@param b amount of blue
*/
SK_ATTR_DEPRECATED("use eraseARGB or eraseColor")
void eraseRGB(U8CPU r, U8CPU g, U8CPU b) const {
this->eraseARGB(0xFF, r, g, b);
}
/** Replaces pixel values inside area with c. If area does not intersect bounds(),
call has no effect.
If the colorType() is kGray_8_SkColorType or k565_SkColorType, then color alpha
If the colorType() is kGray_8_SkColorType or k565_SkColorType, then alpha
is ignored; RGB is treated as opaque. If colorType() is kAlpha_8_SkColorType,
then RGB is ignored.
@ -834,6 +839,18 @@ public:
return this->pixmap().getColor(x, y);
}
/** Look up the pixel at (x,y) and return its alpha component, normalized to [0..1].
This is roughly equivalent to SkGetColorA(getColor()), but can be more efficent
(and more precise if the pixels store more than 8 bits per component).
@param x column index, zero or greater, and less than width()
@param y row index, zero or greater, and less than height()
@return alpha converted to normalized float
*/
float getAlphaf(int x, int y) const {
return this->pixmap().getAlphaf(x, y);
}
/** Returns pixel address at (x, y).
Input is not validated: out of bounds values of x or y, or kUnknown_SkColorType,
@ -911,44 +928,6 @@ public:
*/
bool extractSubset(SkBitmap* dst, const SkIRect& subset) const;
/** Copies SkRect of pixels from SkBitmap pixels to dstPixels. Copy starts at (srcX, srcY),
and does not exceed SkBitmap (width(), height()).
dstInfo specifies width, height, SkColorType, SkAlphaType, and
SkColorSpace of destination. dstRowBytes specifics the gap from one destination
row to the next. Returns true if pixels are copied. Returns false if:
- dstInfo.addr() equals nullptr
- dstRowBytes is less than dstInfo.minRowBytes()
- SkPixelRef is nullptr
Pixels are copied only if pixel conversion is possible. If SkBitmap colorType() is
kGray_8_SkColorType, or kAlpha_8_SkColorType; dstInfo.colorType() must match.
If SkBitmap colorType() is kGray_8_SkColorType, dstInfo.colorSpace() must match.
If SkBitmap alphaType() is kOpaque_SkAlphaType, dstInfo.alphaType() must
match. If SkBitmap colorSpace() is nullptr, dstInfo.colorSpace() must match. Returns
false if pixel conversion is not possible.
srcX and srcY may be negative to copy only top or left of source. Returns
false if width() or height() is zero or negative.
Returns false if abs(srcX) >= Bitmap width(), or if abs(srcY) >= Bitmap height().
If behavior is SkTransferFunctionBehavior::kRespect: converts source
pixels to a linear space before converting to dstInfo.
If behavior is SkTransferFunctionBehavior::kIgnore: source
pixels are treated as if they are linear, regardless of how they are encoded.
@param dstInfo destination width, height, SkColorType, SkAlphaType, SkColorSpace
@param dstPixels destination pixel storage
@param dstRowBytes destination row length
@param srcX column index whose absolute value is less than width()
@param srcY row index whose absolute value is less than height()
@param behavior one of: SkTransferFunctionBehavior::kRespect,
SkTransferFunctionBehavior::kIgnore
@return true if pixels are copied to dstPixels
*/
bool readPixels(const SkImageInfo& dstInfo, void* dstPixels, size_t dstRowBytes,
int srcX, int srcY, SkTransferFunctionBehavior behavior) const;
/** Copies a SkRect of pixels from SkBitmap to dstPixels. Copy starts at (srcX, srcY),
and does not exceed SkBitmap (width(), height()).
@ -978,10 +957,7 @@ public:
@return true if pixels are copied to dstPixels
*/
bool readPixels(const SkImageInfo& dstInfo, void* dstPixels, size_t dstRowBytes,
int srcX, int srcY) const {
return this->readPixels(dstInfo, dstPixels, dstRowBytes, srcX, srcY,
SkTransferFunctionBehavior::kRespect);
}
int srcX, int srcY) const;
/** Copies a SkRect of pixels from SkBitmap to dst. Copy starts at (srcX, srcY), and
does not exceed SkBitmap (width(), height()).
@ -1061,9 +1037,7 @@ public:
@param dstY row index whose absolute value is less than height()
@return true if src pixels are copied to SkBitmap
*/
bool writePixels(const SkPixmap& src, int dstX, int dstY) {
return this->writePixels(src, dstX, dstY, SkTransferFunctionBehavior::kRespect);
}
bool writePixels(const SkPixmap& src, int dstX, int dstY);
/** Copies a SkRect of pixels from src. Copy starts at (0, 0), and does not exceed
(src.width(), src.height()).
@ -1089,40 +1063,8 @@ public:
return this->writePixels(src, 0, 0);
}
/** Copies a SkRect of pixels from src. Copy starts at (0, 0), and does not exceed
(src.width(), src.height()).
src specifies width, height, SkColorType, SkAlphaType, SkColorSpace, pixel storage,
and row bytes of source. src.rowBytes() specifics the gap from one source
row to the next. Returns true if pixels are copied. Returns false if:
- src pixel storage equals nullptr
- src.rowBytes is less than SkImageInfo::minRowBytes
- SkPixelRef is nullptr
Pixels are copied only if pixel conversion is possible. If SkBitmap colorType() is
kGray_8_SkColorType, or kAlpha_8_SkColorType; src SkColorType must match.
If SkBitmap colorType() is kGray_8_SkColorType, src SkColorSpace must match.
If SkBitmap alphaType() is kOpaque_SkAlphaType, src SkAlphaType must
match. If SkBitmap colorSpace() is nullptr, src SkColorSpace must match. Returns
false if pixel conversion is not possible. Returns false if width() or height()
is zero or negative.
If behavior is SkTransferFunctionBehavior::kRespect: converts src
pixels to a linear space before converting to SkImageInfo.
If behavior is SkTransferFunctionBehavior::kIgnore: src
pixels are treated as if they are linear, regardless of how they are encoded.
@param src source SkPixmap: SkImageInfo, pixels, row bytes
@param x column index whose absolute value is less than width()
@param y row index whose absolute value is less than height()
@param behavior one of: SkTransferFunctionBehavior::kRespect,
SkTransferFunctionBehavior::kIgnore
@return true if src pixels are copied to SkBitmap
*/
bool writePixels(const SkPixmap& src, int x, int y, SkTransferFunctionBehavior behavior);
#ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
/** Android framework only.
/** For use by Android framework only.
@return true if setHasHardwareMipMap() has been called with true
*/
@ -1130,7 +1072,7 @@ public:
return (fFlags & kHasHardwareMipMap_Flag) != 0;
}
/** Android framework only.
/** For use by Android framework only.
@param hasHardwareMipMap sets state
*/
@ -1184,7 +1126,7 @@ public:
@param dst holds SkPixelRef to fill with alpha layer
@param paint holds optional SkMaskFilter; may be nullptr
@param allocator method to reserve memory for SkPixelRef; may be nullptr
@param allocator function to reserve memory for SkPixelRef; may be nullptr
@param offset top-left position for dst; may be nullptr
@return true if alpha layer was constructed in dst SkPixelRef
*/
@ -1243,15 +1185,6 @@ public:
bool allocPixelRef(SkBitmap* bitmap) override;
};
/** macro expands to: void toString(SkString* str) const;
Creates string representation of SkBitmap. The representation is read by
internal debugging tools. The interface and implementation may be
suppressed by defining SK_IGNORE_TO_STRING.
@param str storage for string representation
*/
SK_TO_STRING_NONVIRT()
private:
enum Flags {
kImageIsVolatile_Flag = 0x02,

Просмотреть файл

@ -5,54 +5,71 @@
* found in the LICENSE file.
*/
/* Generated by tools/bookmaker from include/core/SkBlendMode.h and docs/SkBlendMode_Reference.bmh
on 2018-07-13 08:15:10. Additional documentation and examples can be found at:
https://skia.org/user/api/SkBlendMode_Reference
You may edit either file directly. Structural changes to public interfaces require
editing both files. After editing docs/SkBlendMode_Reference.bmh, run:
bookmaker -b docs -i include/core/SkBlendMode.h -p
to create an updated version of this file.
*/
#ifndef SkBlendMode_DEFINED
#define SkBlendMode_DEFINED
#include "SkTypes.h"
enum class SkBlendMode {
kClear, //!< [0, 0]
kSrc, //!< [Sa, Sc]
kDst, //!< [Da, Dc]
kSrcOver, //!< [Sa + Da * (1 - Sa), Sc + Dc * (1 - Sa)]
kDstOver, //!< [Da + Sa * (1 - Da), Dc + Sc * (1 - Da)]
kSrcIn, //!< [Sa * Da, Sc * Da]
kDstIn, //!< [Da * Sa, Dc * Sa]
kSrcOut, //!< [Sa * (1 - Da), Sc * (1 - Da)]
kDstOut, //!< [Da * (1 - Sa), Dc * (1 - Sa)]
kSrcATop, //!< [Da, Sc * Da + Dc * (1 - Sa)]
kDstATop, //!< [Sa, Dc * Sa + Sc * (1 - Da)]
kXor, //!< [Sa + Da - 2 * Sa * Da, Sc * (1 - Da) + Dc * (1 - Sa)]
kPlus, //!< [Sa + Da, Sc + Dc]
kModulate, // multiplies all components (= alpha and color)
// Following blend modes are defined in the CSS Compositing standard:
// https://dvcs.w3.org/hg/FXTF/rawfile/tip/compositing/index.html#blending
kScreen,
kLastCoeffMode = kScreen,
kOverlay,
kDarken,
kLighten,
kColorDodge,
kColorBurn,
kHardLight,
kSoftLight,
kDifference,
kExclusion,
kMultiply,
kLastSeparableMode = kMultiply,
kHue,
kSaturation,
kColor,
kLuminosity,
kLastMode = kLuminosity
kClear, //!< replaces destination with zero: fully transparent
kSrc, //!< replaces destination
kDst, //!< preserves destination
kSrcOver, //!< source over destination
kDstOver, //!< destination over source
kSrcIn, //!< source trimmed inside destination
kDstIn, //!< destination trimmed by source
kSrcOut, //!< source trimmed outside destination
kDstOut, //!< destination trimmed outside source
kSrcATop, //!< source inside destination blended with destination
kDstATop, //!< destination inside source blended with source
kXor, //!< each of source and destination trimmed outside the other
kPlus, //!< sum of colors
kModulate, //!< product of premultiplied colors; darkens destination
kScreen, //!< multiply inverse of pixels, inverting result; brightens destination
kLastCoeffMode = kScreen, //!< last porter duff blend mode
kOverlay, //!< multiply or screen, depending on destination
kDarken, //!< darker of source and destination
kLighten, //!< lighter of source and destination
kColorDodge, //!< brighten destination to reflect source
kColorBurn, //!< darken destination to reflect source
kHardLight, //!< multiply or screen, depending on source
kSoftLight, //!< lighten or darken, depending on source
kDifference, //!< subtract darker from lighter with higher contrast
kExclusion, //!< subtract darker from lighter with lower contrast
kMultiply, //!< multiply source with destination, darkening image
kLastSeparableMode = kMultiply, //!< last blend mode operating separately on components
kHue, //!< hue of source with saturation and luminosity of destination
kSaturation, //!< saturation of source with hue and luminosity of destination
kColor, //!< hue and saturation of source with luminosity of destination
kLuminosity, //!< luminosity of source with hue and saturation of destination
kLastMode = kLuminosity, //!< last valid value
};
/**
* Return the (c-string) name of the blendmode.
*/
SK_API const char* SkBlendMode_Name(SkBlendMode);
/** Returns name of blendMode as null-terminated C string.
@param blendMode one of:
SkBlendMode::kClear, SkBlendMode::kSrc, SkBlendMode::kDst, SkBlendMode::kSrcOver,
SkBlendMode::kDstOver, SkBlendMode::kSrcIn, SkBlendMode::kDstIn,
SkBlendMode::kSrcOut, SkBlendMode::kDstOut, SkBlendMode::kSrcATop,
SkBlendMode::kDstATop, SkBlendMode::kXor, SkBlendMode::kPlus,
SkBlendMode::kModulate, SkBlendMode::kScreen, SkBlendMode::kOverlay,
SkBlendMode::kDarken, SkBlendMode::kLighten, SkBlendMode::kColorDodge,
SkBlendMode::kColorBurn, SkBlendMode::kHardLight, SkBlendMode::kSoftLight,
SkBlendMode::kDifference, SkBlendMode::kExclusion, SkBlendMode::kMultiply,
SkBlendMode::kHue, SkBlendMode::kSaturation, SkBlendMode::kColor,
SkBlendMode::kLuminosity
@return C string
*/
SK_API const char* SkBlendMode_Name(SkBlendMode blendMode);
#endif

Просмотреть файл

@ -16,14 +16,7 @@ enum SkBlurStyle {
kOuter_SkBlurStyle, //!< nothing inside, fuzzy outside
kInner_SkBlurStyle, //!< fuzzy inside, nothing outside
kLastEnum_SkBlurStyle = kInner_SkBlurStyle
};
enum SkBlurQuality {
kLow_SkBlurQuality, //!< e.g. box filter
kHigh_SkBlurQuality, //!< e.g. 3-pass similar to gaussian
kLastEnum_SkBlurQuality
kLastEnum_SkBlurStyle = kInner_SkBlurStyle,
};
#endif

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -0,0 +1,83 @@
/*
* Copyright 2018 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef SkCanvasVirtualEnforcer_DEFINED
#define SkCanvasVirtualEnforcer_DEFINED
#include "SkCanvas.h"
// If you would ordinarily want to inherit from Base (eg SkCanvas, SkNWayCanvas), instead
// inherit from SkCanvasVirtualEnforcer<Base>, which will make the build fail if you forget
// to override one of SkCanvas' key virtual hooks.
template <typename Base>
class SkCanvasVirtualEnforcer : public Base {
public:
using Base::Base;
protected:
void onDrawPaint(const SkPaint& paint) override = 0;
void onDrawRect(const SkRect& rect, const SkPaint& paint) override = 0;
void onDrawRRect(const SkRRect& rrect, const SkPaint& paint) override = 0;
void onDrawDRRect(const SkRRect& outer, const SkRRect& inner,
const SkPaint& paint) override = 0;
void onDrawOval(const SkRect& rect, const SkPaint& paint) override = 0;
void onDrawArc(const SkRect& rect, SkScalar startAngle, SkScalar sweepAngle, bool useCenter,
const SkPaint& paint) override = 0;
void onDrawPath(const SkPath& path, const SkPaint& paint) override = 0;
void onDrawRegion(const SkRegion& region, const SkPaint& paint) override = 0;
void onDrawText(const void* text, size_t byteLength, SkScalar x, SkScalar y,
const SkPaint& paint) override = 0;
void onDrawPosText(const void* text, size_t byteLength, const SkPoint pos[],
const SkPaint& paint) override = 0;
void onDrawPosTextH(const void* text, size_t byteLength, const SkScalar xpos[],
SkScalar constY, const SkPaint& paint) override = 0;
void onDrawTextRSXform(const void* text, size_t byteLength, const SkRSXform xform[],
const SkRect* cullRect, const SkPaint& paint) override = 0;
void onDrawTextBlob(const SkTextBlob* blob, SkScalar x, SkScalar y,
const SkPaint& paint) override = 0;
void onDrawPatch(const SkPoint cubics[12], const SkColor colors[4],
const SkPoint texCoords[4], SkBlendMode mode,
const SkPaint& paint) override = 0;
void onDrawPoints(SkCanvas::PointMode mode, size_t count, const SkPoint pts[],
const SkPaint& paint) override = 0;
void onDrawVerticesObject(const SkVertices*, const SkVertices::Bone bones[], int boneCount,
SkBlendMode, const SkPaint&) override = 0;
void onDrawImage(const SkImage* image, SkScalar dx, SkScalar dy,
const SkPaint* paint) override = 0;
void onDrawImageRect(const SkImage* image, const SkRect* src, const SkRect& dst,
const SkPaint* paint, SkCanvas::SrcRectConstraint constraint) override = 0;
void onDrawImageNine(const SkImage* image, const SkIRect& center, const SkRect& dst,
const SkPaint* paint) override = 0;
void onDrawImageLattice(const SkImage* image, const SkCanvas::Lattice& lattice,
const SkRect& dst, const SkPaint* paint) override = 0;
void onDrawBitmap(const SkBitmap& bitmap, SkScalar dx, SkScalar dy,
const SkPaint* paint) override = 0;
void onDrawBitmapRect(const SkBitmap& bitmap, const SkRect* src, const SkRect& dst,
const SkPaint* paint,
SkCanvas::SrcRectConstraint constraint) override = 0;
void onDrawBitmapNine(const SkBitmap& bitmap, const SkIRect& center, const SkRect& dst,
const SkPaint* paint) override = 0;
void onDrawBitmapLattice(const SkBitmap& bitmap, const SkCanvas::Lattice& lattice,
const SkRect& dst, const SkPaint* paint) override = 0;
void onDrawAtlas(const SkImage* atlas, const SkRSXform xform[], const SkRect rect[],
const SkColor colors[], int count, SkBlendMode mode, const SkRect* cull,
const SkPaint* paint) override = 0;
void onDrawAnnotation(const SkRect& rect, const char key[], SkData* value) override = 0;
void onDrawShadowRec(const SkPath&, const SkDrawShadowRec&) override = 0;
void onDrawDrawable(SkDrawable* drawable, const SkMatrix* matrix) override = 0;
void onDrawPicture(const SkPicture* picture, const SkMatrix* matrix,
const SkPaint* paint) override = 0;
};
#endif

Просмотреть файл

@ -5,187 +5,296 @@
* found in the LICENSE file.
*/
/* Generated by tools/bookmaker from include/core/SkColor.h and docs/SkColor_Reference.bmh
on 2018-06-14 13:13:34. Additional documentation and examples can be found at:
https://skia.org/user/api/SkColor_Reference
You may edit either file directly. Structural changes to public interfaces require
editing both files. After editing docs/SkColor_Reference.bmh, run:
bookmaker -b docs -i include/core/SkColor.h -p
to create an updated version of this file.
*/
#ifndef SkColor_DEFINED
#define SkColor_DEFINED
#include "SkImageInfo.h"
#include "SkScalar.h"
#include "SkTypes.h"
/** \file SkColor.h
Types and macros for colors
Types, consts, functions, and macros for colors.
*/
/** 8-bit type for an alpha value. 0xFF is 100% opaque, 0x00 is 100% transparent.
/** 8-bit type for an alpha value. 255 is 100% opaque, zero is 100% transparent.
*/
typedef uint8_t SkAlpha;
/** 32 bit ARGB color value, not premultiplied. The color components are always in
/** 32-bit ARGB color value, unpremultiplied. Color components are always in
a known order. This is different from SkPMColor, which has its bytes in a configuration
dependent order, to match the format of kARGB32 bitmaps. SkColor is the type used to
specify colors in SkPaint and in gradients.
dependent order, to match the format of kBGRA_8888_SkColorType bitmaps. SkColor
is the type used to specify colors in SkPaint and in gradients.
Color that is premultiplied has the same component values as color
that is unpremultiplied if alpha is 255, fully opaque, although may have the
component values in a different order.
*/
typedef uint32_t SkColor;
/** Return a SkColor value from 8 bit component values
/** Returns color value from 8-bit component values. Asserts if SK_DEBUG is defined
if a, r, g, or b exceed 255. Since color is unpremultiplied, a may be smaller
than the largest of r, g, and b.
@param a amount of alpha, from fully transparent (0) to fully opaque (255)
@param r amount of red, from no red (0) to full red (255)
@param g amount of green, from no green (0) to full green (255)
@param b amount of blue, from no blue (0) to full blue (255)
@return color and alpha, unpremultiplied
*/
static constexpr inline SkColor SkColorSetARGB(U8CPU a, U8CPU r, U8CPU g, U8CPU b) {
return SkASSERT(a <= 255 && r <= 255 && g <= 255 && b <= 255),
(a << 24) | (r << 16) | (g << 8) | (b << 0);
}
// Legacy aliases.
#define SkColorSetARGBInline SkColorSetARGB
#define SkColorSetARGBMacro SkColorSetARGB
/** Return a SkColor value from 8 bit component values, with an implied value
of 0xFF for alpha (fully opaque)
/** Returns color value from 8-bit component values, with alpha set
fully opaque to 255.
*/
#define SkColorSetRGB(r, g, b) SkColorSetARGB(0xFF, r, g, b)
/** return the alpha byte from a SkColor value */
/** Returns alpha byte from color value.
*/
#define SkColorGetA(color) (((color) >> 24) & 0xFF)
/** return the red byte from a SkColor value */
/** Returns red component of color, from zero to 255.
*/
#define SkColorGetR(color) (((color) >> 16) & 0xFF)
/** return the green byte from a SkColor value */
/** Returns green component of color, from zero to 255.
*/
#define SkColorGetG(color) (((color) >> 8) & 0xFF)
/** return the blue byte from a SkColor value */
/** Returns blue component of color, from zero to 255.
*/
#define SkColorGetB(color) (((color) >> 0) & 0xFF)
/** Returns unpremultiplied color with red, blue, and green set from c; and alpha set
from a. Alpha component of c is ignored and is replaced by a in result.
@param c packed RGB, eight bits per component
@param a alpha: transparent at zero, fully opaque at 255
@return color with transparency
*/
static constexpr inline SkColor SkColorSetA(SkColor c, U8CPU a) {
return (c & 0x00FFFFFF) | (a << 24);
}
// common colors
/** Represents fully transparent SkAlpha value. SkAlpha ranges from zero,
fully transparent; to 255, fully opaque.
*/
constexpr SkAlpha SK_AlphaTRANSPARENT = 0x00;
/** transparent SkAlpha value */
#define SK_AlphaTRANSPARENT static_cast<SkAlpha>(0x00)
/** opaque SkAlpha value */
#define SK_AlphaOPAQUE static_cast<SkAlpha>(0xFF)
/** Represents fully opaque SkAlpha value. SkAlpha ranges from zero,
fully transparent; to 255, fully opaque.
*/
constexpr SkAlpha SK_AlphaOPAQUE = 0xFF;
/** transparent SkColor value */
#define SK_ColorTRANSPARENT static_cast<SkColor>(0x00000000)
/** Represents fully transparent SkColor. May be used to initialize a destination
containing a mask or a non-rectangular image.
*/
constexpr SkColor SK_ColorTRANSPARENT = SkColorSetARGB(0x00, 0x00, 0x00, 0x00);
/** black SkColor value */
#define SK_ColorBLACK static_cast<SkColor>(0xFF000000)
/** dark gray SkColor value */
#define SK_ColorDKGRAY static_cast<SkColor>(0xFF444444)
/** gray SkColor value */
#define SK_ColorGRAY static_cast<SkColor>(0xFF888888)
/** light gray SkColor value */
#define SK_ColorLTGRAY static_cast<SkColor>(0xFFCCCCCC)
/** white SkColor value */
#define SK_ColorWHITE static_cast<SkColor>(0xFFFFFFFF)
/** Represents fully opaque black.
*/
constexpr SkColor SK_ColorBLACK = SkColorSetARGB(0xFF, 0x00, 0x00, 0x00);
/** red SkColor value */
#define SK_ColorRED static_cast<SkColor>(0xFFFF0000)
/** green SkColor value */
#define SK_ColorGREEN static_cast<SkColor>(0xFF00FF00)
/** blue SkColor value */
#define SK_ColorBLUE static_cast<SkColor>(0xFF0000FF)
/** yellow SkColor value */
#define SK_ColorYELLOW static_cast<SkColor>(0xFFFFFF00)
/** cyan SkColor value */
#define SK_ColorCYAN static_cast<SkColor>(0xFF00FFFF)
/** magenta SkColor value */
#define SK_ColorMAGENTA static_cast<SkColor>(0xFFFF00FF)
/** Represents fully opaque dark gray.
Note that SVG dark gray is equivalent to 0xFFA9A9A9.
*/
constexpr SkColor SK_ColorDKGRAY = SkColorSetARGB(0xFF, 0x44, 0x44, 0x44);
////////////////////////////////////////////////////////////////////////
/** Represents fully opaque gray.
Note that HTML gray is equivalent to 0xFF808080.
*/
constexpr SkColor SK_ColorGRAY = SkColorSetARGB(0xFF, 0x88, 0x88, 0x88);
/** Convert RGB components to HSV.
hsv[0] is Hue [0 .. 360)
hsv[1] is Saturation [0...1]
hsv[2] is Value [0...1]
@param red red component value [0..255]
@param green green component value [0..255]
@param blue blue component value [0..255]
@param hsv 3 element array which holds the resulting HSV components.
/** Represents fully opaque light gray. HTML silver is equivalent to 0xFFC0C0C0.
Note that SVG light gray is equivalent to 0xFFD3D3D3.
*/
constexpr SkColor SK_ColorLTGRAY = SkColorSetARGB(0xFF, 0xCC, 0xCC, 0xCC);
/** Represents fully opaque white.
*/
constexpr SkColor SK_ColorWHITE = SkColorSetARGB(0xFF, 0xFF, 0xFF, 0xFF);
/** Represents fully opaque red.
*/
constexpr SkColor SK_ColorRED = SkColorSetARGB(0xFF, 0xFF, 0x00, 0x00);
/** Represents fully opaque green. HTML lime is equivalent.
Note that HTML green is equivalent to 0xFF008000.
*/
constexpr SkColor SK_ColorGREEN = SkColorSetARGB(0xFF, 0x00, 0xFF, 0x00);
/** Represents fully opaque blue.
*/
constexpr SkColor SK_ColorBLUE = SkColorSetARGB(0xFF, 0x00, 0x00, 0xFF);
/** Represents fully opaque yellow.
*/
constexpr SkColor SK_ColorYELLOW = SkColorSetARGB(0xFF, 0xFF, 0xFF, 0x00);
/** Represents fully opaque cyan. HTML aqua is equivalent.
*/
constexpr SkColor SK_ColorCYAN = SkColorSetARGB(0xFF, 0x00, 0xFF, 0xFF);
/** Represents fully opaque magenta. HTML fuchsia is equivalent.
*/
constexpr SkColor SK_ColorMAGENTA = SkColorSetARGB(0xFF, 0xFF, 0x00, 0xFF);
/** Converts RGB to its HSV components.
hsv[0] contains hsv hue, a value from zero to less than 360.
hsv[1] contains hsv saturation, a value from zero to one.
hsv[2] contains hsv value, a value from zero to one.
@param red red component value from zero to 255
@param green green component value from zero to 255
@param blue blue component value from zero to 255
@param hsv three element array which holds the resulting HSV components
*/
SK_API void SkRGBToHSV(U8CPU red, U8CPU green, U8CPU blue, SkScalar hsv[3]);
/** Convert the argb color to its HSV components.
hsv[0] is Hue [0 .. 360)
hsv[1] is Saturation [0...1]
hsv[2] is Value [0...1]
@param color the argb color to convert. Note: the alpha component is ignored.
@param hsv 3 element array which holds the resulting HSV components.
/** Converts ARGB to its HSV components. Alpha in ARGB is ignored.
hsv[0] contains hsv hue, and is assigned a value from zero to less than 360.
hsv[1] contains hsv saturation, a value from zero to one.
hsv[2] contains hsv value, a value from zero to one.
@param color ARGB color to convert
@param hsv three element array which holds the resulting HSV components
*/
static inline void SkColorToHSV(SkColor color, SkScalar hsv[3]) {
SkRGBToHSV(SkColorGetR(color), SkColorGetG(color), SkColorGetB(color), hsv);
}
/** Convert HSV components to an ARGB color. The alpha component is passed through unchanged.
hsv[0] is Hue [0 .. 360)
hsv[1] is Saturation [0...1]
hsv[2] is Value [0...1]
If hsv values are out of range, they are pinned.
@param alpha the alpha component of the returned argb color.
@param hsv 3 element array which holds the input HSV components.
@return the resulting argb color
/** Converts HSV components to an ARGB color. Alpha is passed through unchanged.
hsv[0] represents hsv hue, an angle from zero to less than 360.
hsv[1] represents hsv saturation, and varies from zero to one.
hsv[2] represents hsv value, and varies from zero to one.
Out of range hsv values are pinned.
@param alpha alpha component of the returned ARGB color
@param hsv three element array which holds the input HSV components
@return ARGB equivalent to HSV
*/
SK_API SkColor SkHSVToColor(U8CPU alpha, const SkScalar hsv[3]);
/** Convert HSV components to an ARGB color. The alpha component set to 0xFF.
hsv[0] is Hue [0 .. 360)
hsv[1] is Saturation [0...1]
hsv[2] is Value [0...1]
If hsv values are out of range, they are pinned.
@param hsv 3 element array which holds the input HSV components.
@return the resulting argb color
/** Converts HSV components to an ARGB color. Alpha is set to 255.
hsv[0] represents hsv hue, an angle from zero to less than 360.
hsv[1] represents hsv saturation, and varies from zero to one.
hsv[2] represents hsv value, and varies from zero to one.
Out of range hsv values are pinned.
@param hsv three element array which holds the input HSV components
@return RGB equivalent to HSV
*/
static inline SkColor SkHSVToColor(const SkScalar hsv[3]) {
return SkHSVToColor(0xFF, hsv);
}
////////////////////////////////////////////////////////////////////////
/** 32 bit ARGB color value, premultiplied. The byte order for this value is
configuration dependent, matching the format of kARGB32 bitmaps. This is different
from SkColor, which is nonpremultiplied, and is always in the same byte order.
/** 32-bit ARGB color value, premultiplied. The byte order for this value is
configuration dependent, matching the format of kBGRA_8888_SkColorType bitmaps.
This is different from SkColor, which is unpremultiplied, and is always in the
same byte order.
*/
typedef uint32_t SkPMColor;
/** Return a SkPMColor value from unpremultiplied 8 bit component values
/** Returns a SkPMColor value from unpremultiplied 8-bit component values.
@param a amount of alpha, from fully transparent (0) to fully opaque (255)
@param r amount of red, from no red (0) to full red (255)
@param g amount of green, from no green (0) to full green (255)
@param b amount of blue, from no blue (0) to full blue (255)
@return premultiplied color
*/
SK_API SkPMColor SkPreMultiplyARGB(U8CPU a, U8CPU r, U8CPU g, U8CPU b);
/** Return a SkPMColor value from a SkColor value. This is done by multiplying the color
components by the color's alpha, and by arranging the bytes in a configuration
dependent order, to match the format of kARGB32 bitmaps.
/** Returns pmcolor closest to color c. Multiplies c RGB components by the c alpha,
and arranges the bytes to match the format of kN32_SkColorType.
@param c unpremultiplied ARGB color
@return premultiplied color
*/
SK_API SkPMColor SkPreMultiplyColor(SkColor c);
///////////////////////////////////////////////////////////////////////////////////////////////////
struct SkPM4f;
/*
* The float values are 0...1 unpremultiplied
*/
struct SK_API SkColor4f {
template <SkAlphaType kAT>
struct SkRGBA4f {
float fR;
float fG;
float fB;
float fA;
bool operator==(const SkColor4f& other) const {
bool operator==(const SkRGBA4f& other) const {
return fA == other.fA && fR == other.fR && fG == other.fG && fB == other.fB;
}
bool operator!=(const SkColor4f& other) const {
bool operator!=(const SkRGBA4f& other) const {
return !(*this == other);
}
const float* vec() const { return &fR; }
float* vec() { return &fR; }
static SkColor4f Pin(float r, float g, float b, float a);
/** Convert to SkColor4f, assuming SkColor is sRGB */
static SkColor4f FromColor(SkColor);
SkColor toSkColor() const;
SkColor4f pin() const {
return Pin(fR, fG, fB, fA);
SkRGBA4f operator*(float scale) const {
return { fR * scale, fG * scale, fB * scale, fA * scale };
}
SkPM4f premul() const;
SkRGBA4f operator*(const SkRGBA4f& scale) const {
return { fR * scale.fR, fG * scale.fG, fB * scale.fB, fA * scale.fA };
}
const float* vec() const { return &fR; }
float* vec() { return &fR; }
float operator[](int index) const {
SkASSERT(index >= 0 && index < 4);
return this->vec()[index];
}
float& operator[](int index) {
SkASSERT(index >= 0 && index < 4);
return this->vec()[index];
}
bool isOpaque() const {
SkASSERT(fA <= 1.0f && fA >= 0.0f);
return fA == 1.0f;
}
static SkRGBA4f Pin(float r, float g, float b, float a); // impl. depends on kAT
SkRGBA4f pin() const { return Pin(fR, fG, fB, fA); }
static SkRGBA4f FromColor(SkColor); // impl. depends on kAT
SkColor toSkColor() const; // impl. depends on kAT
static SkRGBA4f FromPMColor(SkPMColor); // impl. depends on kAT
SkRGBA4f<kPremul_SkAlphaType> premul() const {
static_assert(kAT == kUnpremul_SkAlphaType, "");
return { fR * fA, fG * fA, fB * fA, fA };
}
SkRGBA4f<kUnpremul_SkAlphaType> unpremul() const {
static_assert(kAT == kPremul_SkAlphaType, "");
if (fA == 0.0f) {
return { 0, 0, 0, 0 };
} else {
float invAlpha = 1 / fA;
return { fR * invAlpha, fG * invAlpha, fB * invAlpha, fA };
}
}
};
using SkColor4f = SkRGBA4f<kUnpremul_SkAlphaType>;
template <> SK_API SkColor4f SkColor4f::FromColor(SkColor);
template <> SK_API SkColor SkColor4f::toSkColor() const;
#endif

Просмотреть файл

@ -21,6 +21,7 @@ class SkBitmap;
class SkColorSpace;
class SkColorSpaceXformer;
class SkRasterPipeline;
class SkString;
/**
* ColorFilters are optional objects in the drawing pipeline. When present in
@ -77,7 +78,7 @@ public:
virtual uint32_t getFlags() const { return 0; }
SkColor filterColor(SkColor) const;
SkColor4f filterColor4f(const SkColor4f&) const;
SkColor4f filterColor4f(const SkColor4f&, SkColorSpace*) const;
/** Create a colorfilter that uses the specified color and mode.
If the Mode is DST, this function will return NULL (since that
@ -134,13 +135,25 @@ public:
#endif
bool affectsTransparentBlack() const {
return this->filterColor(0) != 0;
return this->filterColor(SK_ColorTRANSPARENT) != SK_ColorTRANSPARENT;
}
SK_TO_STRING_PUREVIRT()
static void InitializeFlattenables();
SK_DECLARE_FLATTENABLE_REGISTRAR_GROUP()
SK_DEFINE_FLATTENABLE_TYPE(SkColorFilter)
static SkFlattenable::Type GetFlattenableType() {
return kSkColorFilter_Type;
}
SkFlattenable::Type getFlattenableType() const override {
return kSkColorFilter_Type;
}
static sk_sp<SkColorFilter> Deserialize(const void* data, size_t size,
const SkDeserialProcs* procs = nullptr) {
return sk_sp<SkColorFilter>(static_cast<SkColorFilter*>(
SkFlattenable::Deserialize(
kSkColorFilter_Type, data, size, procs).release()));
}
protected:
SkColorFilter() {}

Просмотреть файл

@ -8,6 +8,7 @@
#ifndef SkColorPriv_DEFINED
#define SkColorPriv_DEFINED
#include "../private/SkTo.h"
#include "SkColor.h"
#include "SkMath.h"

Просмотреть файл

@ -8,10 +8,13 @@
#ifndef SkColorSpace_DEFINED
#define SkColorSpace_DEFINED
#include "../private/SkOnce.h"
#include "SkMatrix44.h"
#include "SkRefCnt.h"
#include <memory>
class SkData;
struct skcms_ICCProfile;
enum SkGammaNamed {
kLinear_SkGammaNamed,
@ -24,10 +27,14 @@ enum SkGammaNamed {
* Describes a color gamut with primaries and a white point.
*/
struct SK_API SkColorSpacePrimaries {
float fRX, fRY;
float fGX, fGY;
float fBX, fBY;
float fWX, fWY;
float fRX;
float fRY;
float fGX;
float fGY;
float fBX;
float fBY;
float fWX;
float fWY;
/**
* Convert primaries and a white point to a toXYZD50 matrix, the preferred color gamut
@ -40,11 +47,9 @@ struct SK_API SkColorSpacePrimaries {
* Contains the coefficients for a common transfer function equation, specified as
* a transformation from a curved space to linear.
*
* LinearVal = C*InputVal + F , for 0.0f <= InputVal < D
* LinearVal = (A*InputVal + B)^G + E, for D <= InputVal <= 1.0f
* LinearVal = sign(InputVal) * ( C*|InputVal| + F ), for 0.0f <= |InputVal| < D
* LinearVal = sign(InputVal) * ( (A*|InputVal| + B)^G + E), for D <= |InputVal|
*
* Function is undefined if InputVal is not in [ 0.0f, 1.0f ].
* Resulting LinearVals must be in [ 0.0f, 1.0f ].
* Function must be positive and increasing.
*/
struct SK_API SkColorSpaceTransferFn {
@ -55,29 +60,9 @@ struct SK_API SkColorSpaceTransferFn {
float fD;
float fE;
float fF;
/**
* Produces a new parametric transfer function equation that is the mathematical inverse of
* this one.
*/
SkColorSpaceTransferFn invert() const;
/**
* Transform a single float by this transfer function.
* For negative inputs, returns sign(x) * f(abs(x)).
*/
float operator()(float x) {
SkScalar s = SkScalarSignAsScalar(x);
x = sk_float_abs(x);
if (x >= fD) {
return s * (powf(fA * x + fB, fG) + fE);
} else {
return s * (fC * x + fF);
}
}
};
class SK_API SkColorSpace : public SkRefCnt {
class SK_API SkColorSpace : public SkNVRefCnt<SkColorSpace> {
public:
/**
* Create the sRGB color space.
@ -122,33 +107,26 @@ public:
static sk_sp<SkColorSpace> MakeRGB(SkGammaNamed gammaNamed, const SkMatrix44& toXYZD50);
/**
* Create an SkColorSpace from an ICC profile.
* Create an SkColorSpace from a parsed (skcms) ICC profile.
*/
static sk_sp<SkColorSpace> MakeICC(const void*, size_t);
static sk_sp<SkColorSpace> Make(const skcms_ICCProfile&);
/**
* Types of colorspaces.
* Convert this color space to an skcms ICC profile struct.
*/
enum Type {
kRGB_Type,
kCMYK_Type,
kGray_Type,
};
Type type() const;
void toProfile(skcms_ICCProfile*) const;
SkGammaNamed gammaNamed() const;
SkGammaNamed gammaNamed() const { return fGammaNamed; }
/**
* Returns true if the color space gamma is near enough to be approximated as sRGB.
* This includes the canonical sRGB transfer function as well as a 2.2f exponential
* transfer function.
*/
bool gammaCloseToSRGB() const;
bool gammaCloseToSRGB() const { return kSRGB_SkGammaNamed == fGammaNamed; }
/**
* Returns true if the color space gamma is linear.
*/
bool gammaIsLinear() const;
bool gammaIsLinear() const { return kLinear_SkGammaNamed == fGammaNamed; }
/**
* If the transfer function can be represented as coefficients to the standard
@ -165,37 +143,24 @@ public:
bool toXYZD50(SkMatrix44* toXYZD50) const;
/**
* Describes color space gamut as a transformation to XYZ D50.
* Returns nullptr if color gamut cannot be described in terms of XYZ D50.
*/
const SkMatrix44* toXYZD50() const;
/**
* Describes color space gamut as a transformation from XYZ D50
* Returns nullptr if color gamut cannot be described in terms of XYZ D50.
*/
const SkMatrix44* fromXYZD50() const;
/**
* Returns a hash of the gamut transofmration to XYZ D50. Allows for fast equality checking
* Returns a hash of the gamut transformation to XYZ D50. Allows for fast equality checking
* of gamuts, at the (very small) risk of collision.
* Returns 0 if color gamut cannot be described in terms of XYZ D50.
*/
uint32_t toXYZD50Hash() const;
uint32_t toXYZD50Hash() const { return fToXYZD50Hash; }
/**
* Returns a color space with the same gamut as this one, but with a linear gamma.
* For color spaces whose gamut can not be described in terms of XYZ D50, returns
* linear sRGB.
*/
virtual sk_sp<SkColorSpace> makeLinearGamma() const = 0;
sk_sp<SkColorSpace> makeLinearGamma() const;
/**
* Returns a color space with the same gamut as this one, with with the sRGB transfer
* function. For color spaces whose gamut can not be described in terms of XYZ D50, returns
* sRGB.
*/
virtual sk_sp<SkColorSpace> makeSRGBGamma() const = 0;
sk_sp<SkColorSpace> makeSRGBGamma() const;
/**
* Returns a color space with the same transfer function as this one, but with the primary
@ -205,7 +170,7 @@ public:
*
* This is used for testing, to construct color spaces that have severe and testable behavior.
*/
virtual sk_sp<SkColorSpace> makeColorSpin() const { return nullptr; }
sk_sp<SkColorSpace> makeColorSpin() const;
/**
* Returns true if the color space is sRGB.
@ -239,35 +204,34 @@ public:
* If both are null, we return true. If one is null and the other is not, we return false.
* If both are non-null, we do a deeper compare.
*/
static bool Equals(const SkColorSpace* src, const SkColorSpace* dst);
static bool Equals(const SkColorSpace*, const SkColorSpace*);
void transferFn(float gabcdef[7]) const;
void invTransferFn(float gabcdef[7]) const;
void gamutTransformTo(const SkColorSpace* dst, float src_to_dst_row_major[9]) const;
uint32_t transferFnHash() const { return fTransferFnHash; }
uint64_t hash() const { return (uint64_t)fTransferFnHash << 32 | fToXYZD50Hash; }
private:
virtual const SkMatrix44* onToXYZD50() const = 0;
virtual uint32_t onToXYZD50Hash() const = 0;
virtual const SkMatrix44* onFromXYZD50() const = 0;
friend class SkColorSpaceSingletonFactory;
virtual SkGammaNamed onGammaNamed() const = 0;
virtual bool onGammaCloseToSRGB() const = 0;
virtual bool onGammaIsLinear() const = 0;
virtual bool onIsNumericalTransferFn(SkColorSpaceTransferFn* coeffs) const = 0;
virtual bool onIsCMYK() const { return false; }
SkColorSpace(SkGammaNamed gammaNamed,
const float transferFn[7],
const SkMatrix44& toXYZ);
virtual const SkData* onProfileData() const { return nullptr; }
void computeLazyDstFields() const;
using INHERITED = SkRefCnt;
};
SkGammaNamed fGammaNamed; // TODO: 2-bit, pack tightly? drop?
uint32_t fTransferFnHash;
uint32_t fToXYZD50Hash;
enum class SkTransferFunctionBehavior {
/**
* Converts to a linear space before premultiplying, unpremultiplying, or blending.
*/
kRespect,
float fTransferFn[7];
float fToXYZD50_3x3[9]; // row-major
/**
* Premultiplies, unpremultiplies, and blends ignoring the transfer function. Pixels are
* treated as if they are linear, regardless of their transfer function encoding.
*/
kIgnore,
mutable float fInvTransferFn[7];
mutable float fFromXYZD50_3x3[9]; // row-major
mutable SkOnce fLazyDstFieldsOnce;
};
#endif

Просмотреть файл

@ -1,76 +0,0 @@
/*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef SkColorSpaceXform_DEFINED
#define SkColorSpaceXform_DEFINED
#include "SkImageInfo.h"
class SkColorSpace;
class SK_API SkColorSpaceXform : SkNoncopyable {
public:
/**
* Create an object to handle color space conversions.
*
* @param srcSpace The encoded color space.
* @param dstSpace The destination color space.
*
*/
static std::unique_ptr<SkColorSpaceXform> New(SkColorSpace* srcSpace, SkColorSpace* dstSpace);
enum ColorFormat {
kRGBA_8888_ColorFormat,
kBGRA_8888_ColorFormat,
// Unsigned, big-endian, 16-bit integer
kRGB_U16_BE_ColorFormat, // Src only
kRGBA_U16_BE_ColorFormat, // Src only
kRGBA_F16_ColorFormat,
kRGBA_F32_ColorFormat,
kBGR_565_ColorFormat, // Dst only, kOpaque only
};
/**
* Apply the color conversion to a |src| buffer, storing the output in the |dst| buffer.
*
* F16 and F32 are only supported when the color space is linear. This function will return
* false in unsupported cases.
*
* @param dst Stored in the format described by |dstColorFormat|
* @param src Stored in the format described by |srcColorFormat|
* @param len Number of pixels in the buffers
* @param dstColorFormat Describes color format of |dst|
* @param srcColorFormat Describes color format of |src|
* @param alphaType Describes alpha properties of the |dst| (and |src|)
* kUnpremul preserves input alpha values
* kPremul performs a premultiplication and also preserves alpha values
* kOpaque optimization hint, |dst| alphas set to 1
*
*/
bool apply(ColorFormat dstFormat, void* dst, ColorFormat srcFormat, const void* src, int count,
SkAlphaType alphaType) const;
virtual ~SkColorSpaceXform() {}
enum AlphaOp {
kPreserve_AlphaOp, // just transfer src-alpha to dst-alpha
kPremul_AlphaOp, // like kPreserve, but multiplies RGB by it
kSrcIsOpaque_AlphaOp, // src alphas are all 1, this is a perf hint
};
static bool Apply(SkColorSpace* dstCS, ColorFormat dstFormat, void* dst,
SkColorSpace* srcCS, ColorFormat srcFormat, const void* src,
int count, AlphaOp);
protected:
SkColorSpaceXform() {}
};
#endif

Просмотреть файл

@ -24,7 +24,7 @@ enum class SkCoverageMode {
kReverseDifference, // B - A B*(1-A)
kXor, // A ⊕ B A+B-2*A*B
kLast = kXor
kLast = kXor,
};
#endif

Просмотреть файл

@ -169,10 +169,7 @@ private:
~SkData();
// Ensure the unsized delete is called.
void operator delete(void* p) { ::operator delete(p); }
// Called the first time someone calls NewEmpty to initialize the singleton.
friend SkData* sk_new_empty_data();
void operator delete(void* p);
// shared internal factory
static sk_sp<SkData> PrivateNewWithCopy(const void* srcOrNull, size_t length);

Просмотреть файл

@ -8,15 +8,21 @@
#ifndef SkDeferredDisplayListMaker_DEFINED
#define SkDeferredDisplayListMaker_DEFINED
#include "SkImageInfo.h"
#include "SkRefCnt.h"
#include "SkSurfaceCharacterization.h"
#include "SkTypes.h"
#include "../private/SkDeferredDisplayList.h"
#include "../private/SkSurfaceCharacterization.h"
class GrBackendFormat;
class GrBackendTexture;
class GrContext;
class SkCanvas;
class SkImage;
class SkSurface;
struct SkYUVAIndex;
/*
* This class is intended to be used as:
@ -46,18 +52,98 @@ public:
std::unique_ptr<SkDeferredDisplayList> detach();
// Matches the defines in SkImage_Gpu.h
typedef void* TextureContext;
typedef void (*TextureReleaseProc)(TextureContext textureContext);
typedef void (*TextureFulfillProc)(TextureContext textureContext, GrBackendTexture* outTexture);
typedef void (*PromiseDoneProc)(TextureContext textureContext);
/**
Create a new SkImage that is very similar to an SkImage created by MakeFromTexture. The main
difference is that the client doesn't have the backend texture on the gpu yet but they know
all the properties of the texture. So instead of passing in a GrBackendTexture the client
supplies a GrBackendFormat, width, height, and GrMipMapped state.
When we actually send the draw calls to the GPU, we will call the textureFulfillProc and
the client will return a GrBackendTexture to us. The properties of the GrBackendTexture must
match those set during the SkImage creation, and it must have a valid backend gpu texture.
The gpu texture supplied by the client must stay valid until we call the textureReleaseProc.
When we are done with the texture returned by the textureFulfillProc we will call the
textureReleaseProc passing in the textureContext. This is a signal to the client that they
are free to delete the underlying gpu texture. If future draws also use the same promise
image we will call the textureFulfillProc again if we've already called the
textureReleaseProc. We will always call textureFulfillProc and textureReleaseProc in pairs.
In other words we will never call textureFulfillProc or textureReleaseProc multiple times
for the same textureContext before calling the other.
We call the promiseDoneProc when we will no longer call the textureFulfillProc again. We
pass in the textureContext as a parameter to the promiseDoneProc. We also guarantee that
there will be no outstanding textureReleaseProcs that still need to be called when we call
the textureDoneProc. Thus when the textureDoneProc gets called the client is able to cleanup
all GPU objects and meta data needed for the textureFulfill call.
This call is only valid if the SkDeferredDisplayListRecorder is backed by a gpu context.
@param backendFormat format of promised gpu texture
@param width width of promised gpu texture
@param height height of promised gpu texture
@param mipMapped mip mapped state of promised gpu texture
@param origin one of: kBottomLeft_GrSurfaceOrigin, kTopLeft_GrSurfaceOrigin
@param colorType one of: kUnknown_SkColorType, kAlpha_8_SkColorType,
kRGB_565_SkColorType, kARGB_4444_SkColorType,
kRGBA_8888_SkColorType, kBGRA_8888_SkColorType,
kGray_8_SkColorType, kRGBA_F16_SkColorType
@param alphaType one of: kUnknown_SkAlphaType, kOpaque_SkAlphaType,
kPremul_SkAlphaType, kUnpremul_SkAlphaType
@param colorSpace range of colors; may be nullptr
@param textureFulfillProc function called to get actual gpu texture
@param textureReleaseProc function called when texture can be released
@param promiseDoneProc function called when we will no longer call textureFulfillProc
@param textureContext state passed to textureFulfillProc and textureReleaseProc
@return created SkImage, or nullptr
*/
sk_sp<SkImage> makePromiseTexture(const GrBackendFormat& backendFormat,
int width,
int height,
GrMipMapped mipMapped,
GrSurfaceOrigin origin,
SkColorType colorType,
SkAlphaType alphaType,
sk_sp<SkColorSpace> colorSpace,
TextureFulfillProc textureFulfillProc,
TextureReleaseProc textureReleaseProc,
PromiseDoneProc promiseDoneProc,
TextureContext textureContext);
/**
This entry point operates the same as 'makePromiseTexture' except that its
textureFulfillProc can be called up to four times to fetch the required YUVA
planes (passing a different textureContext to each call). So, if the 'yuvaIndices'
indicate that only the first two backend textures are used, 'textureFulfillProc' will
be called with the first two 'textureContexts'.
*/
sk_sp<SkImage> makeYUVAPromiseTexture(SkYUVColorSpace yuvColorSpace,
const GrBackendFormat yuvaFormats[],
const SkYUVAIndex yuvaIndices[4],
int imageWidth,
int imageHeight,
GrSurfaceOrigin imageOrigin,
sk_sp<SkColorSpace> imageColorSpace,
TextureFulfillProc textureFulfillProc,
TextureReleaseProc textureReleaseProc,
PromiseDoneProc promiseDoneProc,
TextureContext textureContexts[]);
private:
bool init();
const SkSurfaceCharacterization fCharacterization;
#ifndef SK_RASTER_RECORDER_IMPLEMENTATION
#if SK_SUPPORT_GPU
sk_sp<GrContext> fContext;
#endif
sk_sp<SkDeferredDisplayList::LazyProxyData> fLazyProxyData;
#endif
sk_sp<SkSurface> fSurface;
#endif
};
#endif

Просмотреть файл

@ -10,6 +10,7 @@
#ifndef SkDeque_DEFINED
#define SkDeque_DEFINED
#include "../private/SkNoncopyable.h"
#include "SkTypes.h"
/*
@ -66,7 +67,7 @@ public:
public:
enum IterStart {
kFront_IterStart,
kBack_IterStart
kBack_IterStart,
};
/**

Просмотреть файл

@ -8,23 +8,15 @@
#ifndef SkDocument_DEFINED
#define SkDocument_DEFINED
#include "SkBitmap.h"
#include "SkPicture.h"
#include "SkRect.h"
#include "SkRefCnt.h"
#include "SkString.h"
#include "SkTime.h"
#include "SkScalar.h"
class SkCanvas;
class SkWStream;
struct SkRect;
#ifdef SK_BUILD_FOR_WIN
struct IXpsOMObjectFactory;
#endif
/** SK_ScalarDefaultDPI is 72 DPI.
*/
#define SK_ScalarDefaultRasterDPI 72.0f
/** SK_ScalarDefaultDPI is 72 dots per inch. */
static constexpr SkScalar SK_ScalarDefaultRasterDPI = 72.0f;
/**
* High-level API for creating a document-based canvas. To use..
@ -38,122 +30,6 @@ struct IXpsOMObjectFactory;
*/
class SK_API SkDocument : public SkRefCnt {
public:
struct OptionalTimestamp {
SkTime::DateTime fDateTime;
bool fEnabled;
OptionalTimestamp() : fEnabled(false) {}
};
/**
* Optional metadata to be passed into the PDF factory function.
*/
struct PDFMetadata {
/**
* The document's title.
*/
SkString fTitle;
/**
* The name of the person who created the document.
*/
SkString fAuthor;
/**
* The subject of the document.
*/
SkString fSubject;
/**
* Keywords associated with the document. Commas may be used
* to delineate keywords within the string.
*/
SkString fKeywords;
/**
* If the document was converted to PDF from another format,
* the name of the conforming product that created the
* original document from which it was converted.
*/
SkString fCreator;
/**
* The product that is converting this document to PDF.
*
* Leave fProducer empty to get the default, correct value.
*/
SkString fProducer;
/**
* The date and time the document was created.
*/
OptionalTimestamp fCreation;
/**
* The date and time the document was most recently modified.
*/
OptionalTimestamp fModified;
/** The DPI (pixels-per-inch) at which features without
* native PDF support will be rasterized (e.g. draw image
* with perspective, draw text with perspective, ...) A
* larger DPI would create a PDF that reflects the
* original intent with better fidelity, but it can make
* for larger PDF files too, which would use more memory
* while rendering, and it would be slower to be processed
* or sent online or to printer.
*/
SkScalar fRasterDPI = SK_ScalarDefaultRasterDPI;
/** If true, include XMP metadata, a document UUID, and sRGB output intent information.
* This adds length to the document and makes it non-reproducable, but are necessary
* features for PDF/A-2b conformance
*/
bool fPDFA = false;
/**
* Encoding quality controls the trade-off between size and quality. By default this is
* set to 101 percent, which corresponds to lossless encoding. If this value is set to
* a value <= 100, and the image is opaque, it will be encoded (using JPEG) with that
* quality setting.
*/
int fEncodingQuality = 101;
};
/**
* Create a PDF-backed document, writing the results into a
* SkWStream.
*
* PDF pages are sized in point units. 1 pt == 1/72 inch == 127/360 mm.
*
* @param stream A PDF document will be written to this stream. The document may write
* to the stream at anytime during its lifetime, until either close() is
* called or the document is deleted.
* @param metadata a PDFmetadata object. Any fields may be left empty.
*
* @returns NULL if there is an error, otherwise a newly created PDF-backed SkDocument.
*/
static sk_sp<SkDocument> MakePDF(SkWStream* stream, const PDFMetadata& metadata);
static sk_sp<SkDocument> MakePDF(SkWStream* stream);
#ifdef SK_BUILD_FOR_WIN
/**
* Create a XPS-backed document, writing the results into the stream.
*
* @param stream A XPS document will be written to this stream. The
* document may write to the stream at anytime during its
* lifetime, until either close() or abort() are called or
* the document is deleted.
* @param xpsFactory A pointer to a COM XPS factory. Must be non-null.
* The document will take a ref to the factory. See
* dm/DMSrcSink.cpp for an example.
* @param dpi The DPI (pixels-per-inch) at which features without
* native XPS support will be rasterized (e.g. draw image
* with perspective, draw text with perspective, ...) A
* larger DPI would create a XPS that reflects the
* original intent with better fidelity, but it can make
* for larger XPS files too, which would use more memory
* while rendering, and it would be slower to be processed
* or sent online or to printer.
*
* @returns nullptr if XPS is not supported.
*/
static sk_sp<SkDocument> MakeXPS(SkWStream* stream,
IXpsOMObjectFactory* xpsFactory,
SkScalar dpi = SK_ScalarDefaultRasterDPI);
#endif
/**
* Begin a new page for the document, returning the canvas that will draw

Просмотреть файл

@ -1,55 +0,0 @@
/*
* Copyright 2011 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef SkDrawFilter_DEFINED
#define SkDrawFilter_DEFINED
#include "SkRefCnt.h"
class SkCanvas;
class SkPaint;
/**
* DEPRECATED - use SkPaintFilterCanvas instead.
*
* Right before something is being draw, filter() is called with the
* paint. The filter may modify the paint as it wishes, which will then be
* used for the actual drawing. Note: this modification only lasts for the
* current draw, as a temporary copy of the paint is used.
*/
class SK_API SkDrawFilter : public SkRefCnt {
public:
enum Type {
kPaint_Type,
kPoint_Type,
kLine_Type,
kBitmap_Type,
kRect_Type,
kRRect_Type,
kOval_Type,
kPath_Type,
kText_Type,
};
enum {
kTypeCount = kText_Type + 1
};
/**
* Called with the paint that will be used to draw the specified type.
* The implementation may modify the paint as they wish. If filter()
* returns false, the draw will be skipped.
*/
virtual bool filter(SkPaint*, Type) = 0;
private:
typedef SkRefCnt INHERITED;
};
#endif

Просмотреть файл

@ -10,6 +10,7 @@
#ifndef SkDrawLooper_DEFINED
#define SkDrawLooper_DEFINED
#include "../private/SkNoncopyable.h"
#include "SkBlurTypes.h"
#include "SkFlattenable.h"
#include "SkPoint.h"
@ -84,7 +85,6 @@ public:
SkVector fOffset;
SkColor fColor;
SkBlurStyle fStyle;
SkBlurQuality fQuality;
};
/**
* If this looper can be interpreted as having two layers, such that
@ -97,8 +97,20 @@ public:
*/
virtual bool asABlurShadow(BlurShadowRec*) const;
SK_TO_STRING_PUREVIRT()
SK_DEFINE_FLATTENABLE_TYPE(SkDrawLooper)
static SkFlattenable::Type GetFlattenableType() {
return kSkDrawLooper_Type;
}
SkFlattenable::Type getFlattenableType() const override {
return kSkDrawLooper_Type;
}
static sk_sp<SkDrawLooper> Deserialize(const void* data, size_t size,
const SkDeserialProcs* procs = nullptr) {
return sk_sp<SkDrawLooper>(static_cast<SkDrawLooper*>(
SkFlattenable::Deserialize(
kSkDrawLooper_Type, data, size, procs).release()));
}
protected:
sk_sp<SkDrawLooper> makeColorSpace(SkColorSpaceXformer* xformer) const {

Просмотреть файл

@ -60,7 +60,21 @@ public:
*/
void notifyDrawingChanged();
SK_DEFINE_FLATTENABLE_TYPE(SkDrawable)
static SkFlattenable::Type GetFlattenableType() {
return kSkDrawable_Type;
}
SkFlattenable::Type getFlattenableType() const override {
return kSkDrawable_Type;
}
static sk_sp<SkDrawable> Deserialize(const void* data, size_t size,
const SkDeserialProcs* procs = nullptr) {
return sk_sp<SkDrawable>(static_cast<SkDrawable*>(
SkFlattenable::Deserialize(
kSkDrawable_Type, data, size, procs).release()));
}
Factory getFactory() const override { return nullptr; }
protected:

Просмотреть файл

@ -20,7 +20,7 @@ enum SkFilterQuality {
kMedium_SkFilterQuality, //!< typically bilerp + mipmaps for down-scaling
kHigh_SkFilterQuality, //!< slowest but highest quality, typically bicubic or better
kLast_SkFilterQuality = kHigh_SkFilterQuality
kLast_SkFilterQuality = kHigh_SkFilterQuality,
};
#endif

Просмотреть файл

@ -17,61 +17,6 @@ class SkWriteBuffer;
struct SkSerialProcs;
struct SkDeserialProcs;
/*
* Flattening is straight-forward:
* 1. call getFactory() so we have a function-ptr to recreate the subclass
* 2. call flatten(buffer) to write out enough data for the factory to read
*
* Unflattening is easy for the caller: new_instance = factory(buffer)
*
* The complexity of supporting this is as follows.
*
* If your subclass wants to control unflattening, use this macro in your declaration:
* SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS
* This will provide a getFactory(), and require that the subclass implements CreateProc.
*
* For older buffers (before the DEEPFLATTENING change, the macros below declare
* a thin factory DeepCreateProc. It checks the version of the buffer, and if it is pre-deep,
* then it calls through to a (usually protected) constructor, passing the buffer.
* If the buffer is newer, then it directly calls the "real" factory: CreateProc.
*/
#define SK_DECLARE_FLATTENABLE_REGISTRAR_GROUP() static void InitializeFlattenables();
#define SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_START(flattenable) \
void flattenable::InitializeFlattenables() {
#define SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_END \
}
#define SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(flattenable) \
SkFlattenable::Register(#flattenable, flattenable::CreateProc, \
flattenable::GetFlattenableType());
#define SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(flattenable) \
private: \
static sk_sp<SkFlattenable> CreateProc(SkReadBuffer&); \
friend class SkFlattenable::PrivateInitializer; \
public: \
Factory getFactory() const override { return CreateProc; }
/** For SkFlattenable derived objects with a valid type
This macro should only be used in base class objects in core
*/
#define SK_DEFINE_FLATTENABLE_TYPE(flattenable) \
static Type GetFlattenableType() { \
return k##flattenable##_Type; \
} \
Type getFlattenableType() const override { \
return k##flattenable##_Type; \
} \
static sk_sp<flattenable> Deserialize(const void* data, size_t size, \
const SkDeserialProcs* procs = nullptr) { \
return sk_sp<flattenable>(static_cast<flattenable*>( \
SkFlattenable::Deserialize( \
k##flattenable##_Type, data, size, procs).release()));\
}
/** \class SkFlattenable
SkFlattenable is the base class for objects that need to be flattened
@ -92,7 +37,7 @@ public:
kSkShaderBase_Type,
kSkUnused_Type, // used to be SkUnitMapper
kSkUnused_Type2,
kSkUnused_Type3, // used to be SkNormalSource
kSkNormalSource_Type,
};
typedef sk_sp<SkFlattenable> (*Factory)(SkReadBuffer&);
@ -113,7 +58,15 @@ public:
*
* If the flattenable is registered, there is no need to override.
*/
virtual const char* getTypeName() const { return FactoryToName(getFactory()); }
virtual const char* getTypeName() const {
#ifdef SK_DISABLE_READBUFFER
// Should not be reachable by PathKit WebAssembly Code.
SkASSERT(false);
return nullptr;
#else
return FactoryToName(getFactory());
#endif
}
static Factory NameToFactory(const char name[]);
static const char* FactoryToName(Factory);
@ -135,6 +88,8 @@ public:
// public ways to serialize / deserialize
//
sk_sp<SkData> serialize(const SkSerialProcs* = nullptr) const;
size_t serialize(void* memory, size_t memory_size,
const SkSerialProcs* = nullptr) const;
static sk_sp<SkFlattenable> Deserialize(Type, const void* data, size_t length,
const SkDeserialProcs* procs = nullptr);
@ -143,6 +98,7 @@ protected:
public:
static void InitCore();
static void InitEffects();
static void InitImageFilters();
};
private:

Просмотреть файл

@ -29,17 +29,13 @@ enum SkTextEncoding {
enum Flags {
kAntiAlias_Flag = 0x01, //!< mask to enable antialiasing
kDither_Flag = 0x04, //!< mask to enable dithering
kUnderlineText_Flag = 0x08, //!< mask to enable underline text
kStrikeThruText_Flag = 0x10, //!< mask to enable strike-thru text
kFakeBoldText_Flag = 0x20, //!< mask to enable fake-bold text
kLinearText_Flag = 0x40, //!< mask to enable linear-text
kSubpixelText_Flag = 0x80, //!< mask to enable subpixel text positioning
kDevKernText_Flag = 0x100, //!< mask to enable device kerning text
kLCDRenderText_Flag = 0x200, //!< mask to enable subpixel glyph renderering
kEmbeddedBitmapText_Flag = 0x400, //!< mask to enable embedded bitmap strikes
kAutoHinting_Flag = 0x800, //!< mask to force Freetype's autohinter
kVerticalText_Flag = 0x1000,
kGenA8FromLCD_Flag = 0x2000, // hack for GDI -- do not use if you can help it
};
SkFont would absorb these:
@ -47,19 +43,15 @@ enum SkTextEncoding {
kFakeBoldText_Flag = 0x20, //!< mask to enable fake-bold text
kLinearText_Flag = 0x40, //!< mask to enable linear-text
kSubpixelText_Flag = 0x80, //!< mask to enable subpixel text positioning
kDevKernText_Flag = 0x100, //!< mask to enable device kerning text
kLCDRenderText_Flag = 0x200, //!< mask to enable subpixel glyph renderering
kEmbeddedBitmapText_Flag = 0x400, //!< mask to enable embedded bitmap strikes
kAutoHinting_Flag = 0x800, //!< mask to force Freetype's autohinter
kVerticalText_Flag = 0x1000,
kGenA8FromLCD_Flag = 0x2000, // hack for GDI -- do not use if you can help it
leaving these still in paint
kAntiAlias_Flag = 0x01, //!< mask to enable antialiasing
kDither_Flag = 0x04, //!< mask to enable dithering
kUnderlineText_Flag = 0x08, //!< mask to enable underline text
kStrikeThruText_Flag = 0x10, //!< mask to enable strike-thru text
3. Antialiasing
@ -106,9 +98,8 @@ public:
kUseNonlinearMetrics_Flag = 1 << 3,
kVertical_Flag = 1 << 4,
kGenA8FromLCD_Flag = 1 << 5,
kEmbolden_Flag = 1 << 6,
kDevKern_Flag = 1 << 7, // ifdef ANDROID ?
};
enum MaskType {
@ -143,7 +134,6 @@ public:
bool isEnableAutoHints() const { return SkToBool(fFlags & kEnableAutoHints_Flag); }
bool isEnableByteCodeHints() const { return SkToBool(fFlags & kEnableByteCodeHints_Flag); }
bool isUseNonLinearMetrics() const { return SkToBool(fFlags & kUseNonlinearMetrics_Flag); }
bool isDevKern() const { return SkToBool(fFlags & kDevKern_Flag); }
int textToGlyphs(const void* text, size_t byteLength, SkTextEncoding,
SkGlyphID glyphs[], int maxGlyphCount) const;
@ -157,9 +147,7 @@ public:
static sk_sp<SkFont> Testing_CreateFromPaint(const SkPaint&);
private:
enum {
kAllFlags = 0xFF,
};
static constexpr int kAllFlags = 0xFF;
SkFont(sk_sp<SkTypeface>, SkScalar size, SkScalar scaleX, SkScalar skewX, MaskType,
uint32_t flags);

Просмотреть файл

@ -5,8 +5,8 @@
* found in the LICENSE file.
*/
#ifndef SkFontAgruments_DEFINED
#define SkFontAgruments_DEFINED
#ifndef SkFontArguments_DEFINED
#define SkFontArguments_DEFINED
#include "SkScalar.h"
#include "SkTypes.h"
@ -16,15 +16,15 @@ struct SkFontArguments {
struct VariationPosition {
struct Coordinate {
SkFourByteTag axis;
SkScalar value;
float value;
};
const Coordinate* coordinates;
int coordinateCount;
};
// deprecated, use VariationCoordinate instead
// deprecated, use VariationPosition::Coordinate instead
struct Axis {
SkFourByteTag fTag;
SkScalar fStyleValue;
float fStyleValue;
};
SkFontArguments() : fCollectionIndex(0), fVariationDesignPosition{nullptr, 0} {}

Просмотреть файл

@ -23,7 +23,7 @@ public:
*/
enum LCDOrientation {
kHorizontal_LCDOrientation = 0, //!< this is the default
kVertical_LCDOrientation = 1
kVertical_LCDOrientation = 1,
};
/** @deprecated set on Device creation. */
@ -46,7 +46,7 @@ public:
enum LCDOrder {
kRGB_LCDOrder = 0, //!< this is the default
kBGR_LCDOrder = 1,
kNONE_LCDOrder = 2
kNONE_LCDOrder = 2,
};
/** @deprecated set on Device creation. */

Просмотреть файл

@ -57,8 +57,7 @@ public:
/**
* Find the closest matching typeface to the specified familyName and style
* and return a ref to it. The caller must call unref() on the returned
* object. Will never return NULL, as it will return the default font if
* no matching font is found.
* object. Will return nullptr if no 'good' match is found.
*
* Passing |nullptr| as the parameter for |familyName| will return the
* default system font.

Просмотреть файл

@ -0,0 +1,38 @@
/*
* Copyright 2018 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef SkFontParameters_DEFINED
#define SkFontParameters_DEFINED
#include "SkScalar.h"
#include "SkTypes.h"
struct SkFontParameters {
struct Variation {
// Parameters in a variation font axis.
struct Axis {
// Four character identifier of the font axis (weight, width, slant, italic...).
SkFourByteTag tag;
// Minimum value supported by this axis.
float min;
// Default value set by this axis.
float def;
// Maximum value supported by this axis. The maximum can equal the minimum.
float max;
// Return whether this axis is recommended to be remain hidden in user interfaces.
bool isHidden() const { return flags & HIDDEN; }
// Set this axis to be remain hidden in user interfaces.
void setHidden(bool hidden) { flags = hidden ? (flags | HIDDEN) : (flags & ~HIDDEN); }
private:
static constexpr uint16_t HIDDEN = 0x0001;
// Attributes for a font axis.
uint16_t flags;
};
};
};
#endif

Просмотреть файл

@ -161,26 +161,6 @@ public:
*/
static void SetFlags(const char* flags);
/**
* Return the max number of bytes that should be used by the thread-local
* font cache.
* If the cache needs to allocate more, it will purge previous entries.
* This max can be changed by calling SetFontCacheLimit().
*
* If this thread has never called SetTLSFontCacheLimit, or has called it
* with 0, then this thread is using the shared font cache. In that case,
* this function will always return 0, and the caller may want to call
* GetFontCacheLimit.
*/
static size_t GetTLSFontCacheLimit();
/**
* Specify the max number of bytes that should be used by the thread-local
* font cache. If this value is 0, then this thread will use the shared
* global font cache.
*/
static void SetTLSFontCacheLimit(size_t bytes);
typedef std::unique_ptr<SkImageGenerator>
(*ImageGeneratorFromEncodedDataFactory)(sk_sp<SkData>);

Просмотреть файл

@ -9,101 +9,30 @@
#define SkICC_DEFINED
#include "SkData.h"
#include "SkMatrix44.h"
#include "SkRefCnt.h"
struct SkColorSpaceTransferFn;
class SkColorSpace;
class SkData;
class SkMatrix44;
class SK_API SkICC : public SkRefCnt {
public:
SK_API sk_sp<SkData> SkWriteICCProfile(const SkColorSpaceTransferFn&, const float toXYZD50[9]);
/**
* Parse an ICC profile.
*
* Returns nullptr if the data is not a valid ICC profile or if the profile
* input space is not RGB.
*/
static sk_sp<SkICC> Make(const void*, size_t);
namespace SkICC {
static inline sk_sp<SkData> WriteToICC(const SkColorSpaceTransferFn& fn,
const SkMatrix44& toXYZD50) {
if (toXYZD50.get(3,0) == 0 && toXYZD50.get(3,1) == 0 && toXYZD50.get(3,2) == 0 &&
toXYZD50.get(3,3) == 1 &&
toXYZD50.get(0,3) == 0 && toXYZD50.get(1,3) == 0 && toXYZD50.get(2,3) == 0) {
/**
* If the gamut can be represented as transformation into XYZ D50, returns
* true and sets the proper values in |toXYZD50|.
*
* If not, returns false. This indicates that the ICC data is too complex
* to isolate a simple gamut transformation.
*/
bool toXYZD50(SkMatrix44* toXYZD50) const;
float m33[9];
for (int r = 0; r < 3; r++)
for (int c = 0; c < 3; c++) {
m33[3*r+c] = toXYZD50.get(r,c);
}
return SkWriteICCProfile(fn, m33);
/**
* If the transfer function can be represented as coefficients to the standard
* equation, returns true and sets |fn| to the proper values.
*
* If not, returns false. This indicates one of the following:
* (1) The R, G, and B transfer functions are not the same.
* (2) The transfer function is represented as a table that we have not managed
* to match to a standard curve.
* (3) The ICC data is too complex to isolate a single transfer function.
*/
bool isNumericalTransferFn(SkColorSpaceTransferFn* fn) const;
/**
* Please do not call this unless isNumericalTransferFn() has been called and it
* fails. SkColorSpaceTransferFn is the preferred representation.
*
* If it is not possible to represent the R, G, and B transfer functions numerically
* and it is still necessary to get the transfer function, this will return the
* transfer functions as three tables (R, G, and B).
*
* If possible, this will return tables of the same length as they were specified in
* the ICC profile. This means that the lengths of the three tables are not
* guaranteed to be the same. If the ICC representation was not a table, the length
* will be chosen arbitrarily.
*
* The lengths of the tables are all guaranteed to be at least 2. Entries in the
* tables are guaranteed to be in [0, 1].
*
* This API may be deleted in favor of a numerical approximation of the raw data.
*
* This function may fail, indicating that the ICC profile does not have transfer
* functions.
*/
struct Channel {
// Byte offset of the start of the table in |fStorage|
size_t fOffset;
int fCount;
};
struct Tables {
Channel fRed;
Channel fGreen;
Channel fBlue;
const float* red() {
return (const float*) (fStorage->bytes() + fRed.fOffset);
}
const float* green() {
return (const float*) (fStorage->bytes() + fGreen.fOffset);
}
const float* blue() {
return (const float*) (fStorage->bytes() + fBlue.fOffset);
}
return nullptr;
}
}
sk_sp<SkData> fStorage;
};
bool rawTransferFnData(Tables* tables) const;
/**
* Write an ICC profile with transfer function |fn| and gamut |toXYZD50|.
*/
static sk_sp<SkData> WriteToICC(const SkColorSpaceTransferFn& fn, const SkMatrix44& toXYZD50);
private:
SkICC(sk_sp<SkColorSpace> colorSpace);
sk_sp<SkColorSpace> fColorSpace;
friend class ICCTest;
};
#endif
#endif//SkICC_DEFINED

Просмотреть файл

@ -5,6 +5,16 @@
* found in the LICENSE file.
*/
/* Generated by tools/bookmaker from include/core/SkImage.h and docs/SkImage_Reference.bmh
on 2018-09-18 07:26:44. Additional documentation and examples can be found at:
https://skia.org/user/api/SkImage_Reference
You may edit either file directly. Structural changes to public interfaces require
editing both files. After editing docs/SkImage_Reference.bmh, run:
bookmaker -b docs -i include/core/SkImage.h -p
to create an updated version of this file.
*/
#ifndef SkImage_DEFINED
#define SkImage_DEFINED
@ -33,6 +43,8 @@ class GrContext;
class GrContextThreadSafeProxy;
class GrTexture;
struct SkYUVAIndex;
/** \class SkImage
SkImage describes a two dimensional array of pixels to draw. The pixels may be
decoded in a raster bitmap, encoded in a SkPicture or compressed data stream,
@ -51,7 +63,9 @@ class GrTexture;
*/
class SK_API SkImage : public SkRefCnt {
public:
typedef SkImageInfo Info;
/** Caller data passed to RasterReleaseProc; may be nullptr.
*/
typedef void* ReleaseContext;
/** Creates SkImage from SkPixmap and copy of pixels. Since pixels are copied, SkPixmap
@ -83,8 +97,12 @@ public:
@param rowBytes size of pixel row or larger
@return SkImage sharing pixels, or nullptr
*/
static sk_sp<SkImage> MakeRasterData(const Info& info, sk_sp<SkData> pixels, size_t rowBytes);
static sk_sp<SkImage> MakeRasterData(const SkImageInfo& info, sk_sp<SkData> pixels,
size_t rowBytes);
/** Function called when SkImage no longer shares pixels. ReleaseContext is
provided by caller when SkImage is created, and may be nullptr.
*/
typedef void (*RasterReleaseProc)(const void* pixels, ReleaseContext);
/** Creates SkImage from pixmap, sharing SkPixmap pixels. Pixels must remain valid and
@ -158,29 +176,10 @@ public:
*/
static sk_sp<SkImage> MakeFromEncoded(sk_sp<SkData> encoded, const SkIRect* subset = nullptr);
/** User function called when supplied texture may be deleted.
*/
typedef void (*TextureReleaseProc)(ReleaseContext releaseContext);
/** Deprecated.
*/
static sk_sp<SkImage> MakeFromTexture(GrContext* context,
const GrBackendTexture& backendTexture,
GrSurfaceOrigin origin,
SkAlphaType alphaType,
sk_sp<SkColorSpace> colorSpace) {
return MakeFromTexture(context, backendTexture, origin, alphaType, colorSpace, nullptr,
nullptr);
}
/** Deprecated.
*/
static sk_sp<SkImage> MakeFromTexture(GrContext* context,
const GrBackendTexture& backendTexture,
GrSurfaceOrigin origin,
SkAlphaType alphaType,
sk_sp<SkColorSpace> colorSpace,
TextureReleaseProc textureReleaseProc,
ReleaseContext releaseContext);
/** Creates SkImage from GPU texture associated with context. Caller is responsible for
managing the lifetime of GPU texture.
@ -190,12 +189,14 @@ public:
@param context GPU context
@param backendTexture texture residing on GPU
@param origin one of: kBottomLeft_GrSurfaceOrigin, kTopLeft_GrSurfaceOrigin
@param colorType one of: kUnknown_SkColorType, kAlpha_8_SkColorType,
kRGB_565_SkColorType, kARGB_4444_SkColorType,
kRGBA_8888_SkColorType, kBGRA_8888_SkColorType,
@param colorType one of:
kUnknown_SkColorType, kAlpha_8_SkColorType, kRGB_565_SkColorType,
kARGB_4444_SkColorType, kRGBA_8888_SkColorType, kRGB_888x_SkColorType,
kBGRA_8888_SkColorType, kRGBA_1010102_SkColorType, kRGB_101010x_SkColorType,
kGray_8_SkColorType, kRGBA_F16_SkColorType
@param alphaType one of: kUnknown_SkAlphaType, kOpaque_SkAlphaType,
kPremul_SkAlphaType, kUnpremul_SkAlphaType
@param alphaType one of:
kUnknown_SkAlphaType, kOpaque_SkAlphaType, kPremul_SkAlphaType,
kUnpremul_SkAlphaType
@param colorSpace range of colors; may be nullptr
@return created SkImage, or nullptr
*/
@ -219,12 +220,14 @@ public:
@param context GPU context
@param backendTexture texture residing on GPU
@param origin one of: kBottomLeft_GrSurfaceOrigin, kTopLeft_GrSurfaceOrigin
@param colorType one of: kUnknown_SkColorType, kAlpha_8_SkColorType,
kRGB_565_SkColorType, kARGB_4444_SkColorType,
kRGBA_8888_SkColorType, kBGRA_8888_SkColorType,
@param colorType one of:
kUnknown_SkColorType, kAlpha_8_SkColorType, kRGB_565_SkColorType,
kARGB_4444_SkColorType, kRGBA_8888_SkColorType, kRGB_888x_SkColorType,
kBGRA_8888_SkColorType, kRGBA_1010102_SkColorType, kRGB_101010x_SkColorType,
kGray_8_SkColorType, kRGBA_F16_SkColorType
@param alphaType one of: kUnknown_SkAlphaType, kOpaque_SkAlphaType,
kPremul_SkAlphaType, kUnpremul_SkAlphaType
@param alphaType one of:
kUnknown_SkAlphaType, kOpaque_SkAlphaType, kPremul_SkAlphaType,
kUnpremul_SkAlphaType
@param colorSpace range of colors; may be nullptr
@param textureReleaseProc function called when texture can be released
@param releaseContext state passed to textureReleaseProc
@ -242,7 +245,7 @@ public:
/** Creates SkImage from encoded data. SkImage is uploaded to GPU back-end using context.
Created SkImage is available to other GPU contexts, and is available across thread
boundaries. All contexts must be in the same GPU_Share_Group, or otherwise
boundaries. All contexts must be in the same GPU share group, or otherwise
share resources.
When SkImage is no longer referenced, context releases texture memory
@ -257,19 +260,21 @@ public:
SkImage is returned using MakeFromEncoded() if context is nullptr or does not support
moving resources between contexts.
@param context GPU context
@param data SkImage to decode
@param buildMips create SkImage as Mip_Map if true
@param dstColorSpace range of colors of matching SkSurface on GPU
@return created SkImage, or nullptr
@param context GPU context
@param data SkImage to decode
@param buildMips create SkImage as mip map if true
@param dstColorSpace range of colors of matching SkSurface on GPU
@param limitToMaxTextureSize downscale image to GPU maximum texture size, if necessary
@return created SkImage, or nullptr
*/
static sk_sp<SkImage> MakeCrossContextFromEncoded(GrContext* context, sk_sp<SkData> data,
bool buildMips, SkColorSpace* dstColorSpace);
bool buildMips, SkColorSpace* dstColorSpace,
bool limitToMaxTextureSize = false);
/** Creates SkImage from pixmap. SkImage is uploaded to GPU back-end using context.
Created SkImage is available to other GPU contexts, and is available across thread
boundaries. All contexts must be in the same GPU_Share_Group, or otherwise
boundaries. All contexts must be in the same GPU share group, or otherwise
share resources.
When SkImage is no longer referenced, context releases texture memory
@ -284,22 +289,16 @@ public:
as returned in raster format if possible; nullptr may be returned.
Recognized GPU formats vary by platform and GPU back-end.
@param context GPU context
@param pixmap SkImageInfo, pixel address, and row bytes
@param buildMips create SkImage as Mip_Map if true
@param dstColorSpace range of colors of matching SkSurface on GPU
@return created SkImage, or nullptr
@param context GPU context
@param pixmap SkImageInfo, pixel address, and row bytes
@param buildMips create SkImage as mip map if true
@param dstColorSpace range of colors of matching SkSurface on GPU
@param limitToMaxTextureSize downscale image to GPU maximum texture size, if necessary
@return created SkImage, or nullptr
*/
static sk_sp<SkImage> MakeCrossContextFromPixmap(GrContext* context, const SkPixmap& pixmap,
bool buildMips, SkColorSpace* dstColorSpace);
/** Deprecated.
*/
static sk_sp<SkImage> MakeFromAdoptedTexture(GrContext* context,
const GrBackendTexture& backendTexture,
GrSurfaceOrigin surfaceOrigin,
SkAlphaType alphaType = kPremul_SkAlphaType,
sk_sp<SkColorSpace> colorSpace = nullptr);
bool buildMips, SkColorSpace* dstColorSpace,
bool limitToMaxTextureSize = false);
/** Creates SkImage from backendTexture associated with context. backendTexture and
returned SkImage are managed internally, and are released when no longer needed.
@ -310,12 +309,14 @@ public:
@param context GPU context
@param backendTexture texture residing on GPU
@param surfaceOrigin one of: kBottomLeft_GrSurfaceOrigin, kTopLeft_GrSurfaceOrigin
@param colorType one of: kUnknown_SkColorType, kAlpha_8_SkColorType,
kRGB_565_SkColorType, kARGB_4444_SkColorType,
kRGBA_8888_SkColorType, kBGRA_8888_SkColorType,
@param colorType one of:
kUnknown_SkColorType, kAlpha_8_SkColorType, kRGB_565_SkColorType,
kARGB_4444_SkColorType, kRGBA_8888_SkColorType, kRGB_888x_SkColorType,
kBGRA_8888_SkColorType, kRGBA_1010102_SkColorType, kRGB_101010x_SkColorType,
kGray_8_SkColorType, kRGBA_F16_SkColorType
@param alphaType one of: kUnknown_SkAlphaType, kOpaque_SkAlphaType,
kPremul_SkAlphaType, kUnpremul_SkAlphaType
@param alphaType one of:
kUnknown_SkAlphaType, kOpaque_SkAlphaType, kPremul_SkAlphaType,
kUnpremul_SkAlphaType
@param colorSpace range of colors; may be nullptr
@return created SkImage, or nullptr
*/
@ -326,99 +327,143 @@ public:
SkAlphaType alphaType = kPremul_SkAlphaType,
sk_sp<SkColorSpace> colorSpace = nullptr);
/** Creates SkImage from copy of yuvTextureHandles, an array of textures on GPU.
yuvTextureHandles contain pixels for YUV planes of SkImage.
yuvSizes contain dimensions for each pixel plane. Dimensions must be greater than
zero but may differ from plane to plane. Returned SkImage has the dimensions
yuvSizes[0]. yuvColorSpace describes how YUV colors convert to RGB colors.
/** Creates an SkImage by flattening the specified YUVA planes into a single, interleaved RGBA
image.
@param context GPU context
@param yuvColorSpace one of: kJPEG_SkYUVColorSpace, kRec601_SkYUVColorSpace,
kRec709_SkYUVColorSpace
@param yuvTextureHandles array of YUV textures on GPU
@param yuvSizes dimensions of YUV textures
@param surfaceOrigin one of: kBottomLeft_GrSurfaceOrigin, kTopLeft_GrSurfaceOrigin
@param colorSpace range of colors; may be nullptr
@return created SkImage, or nullptr
@param context GPU context
@param yuvColorSpace How the YUV values are converted to RGB. One of:
kJPEG_SkYUVColorSpace, kRec601_SkYUVColorSpace,
kRec709_SkYUVColorSpace
@param yuvTextures array of (up to four) YUVA textures on GPU which contain the,
possibly interleaved, YUVA planes
@param yuvaIndices array indicating which texture (in 'yuvaTextures') and channel
(in the specified texture) maps to each of Y, U, V, and A.
@param imageSize size of the resulting image
@param imageOrigin origin of the resulting image. One of: kBottomLeft_GrSurfaceOrigin,
kTopLeft_GrSurfaceOrigin
@param imageColorSpace range of colors of the resulting image; may be nullptr
@return created SkImage, or nullptr
*/
static sk_sp<SkImage> MakeFromYUVATexturesCopy(GrContext* context,
SkYUVColorSpace yuvColorSpace,
const GrBackendTexture yuvaTextures[],
const SkYUVAIndex yuvaIndices[4],
SkISize imageSize,
GrSurfaceOrigin imageOrigin,
sk_sp<SkColorSpace> imageColorSpace = nullptr);
/** Creates an SkImage by flattening the specified YUVA planes into a single, interleaved RGBA
image. 'backendTexture' is used to store the result of the flattening.
@param context GPU context
@param yuvColorSpace How the YUV values are converted to RGB. One of:
kJPEG_SkYUVColorSpace, kRec601_SkYUVColorSpace,
kRec709_SkYUVColorSpace
@param yuvTextures array of (up to four) YUVA textures on GPU which contain the,
possibly interleaved, YUVA planes
@param yuvaIndices array indicating which texture (in 'yuvaTextures') and channel
(in the specified texture) maps to each of Y, U, V, and A.
@param imageSize size of the resulting image
@param imageOrigin origin of the resulting image. One of: kBottomLeft_GrSurfaceOrigin,
kTopLeft_GrSurfaceOrigin
@param backendTexture the resource that stores the final pixels
@param imageColorSpace range of colors of the resulting image; may be nullptr
@return created SkImage, or nullptr
*/
static sk_sp<SkImage> MakeFromYUVATexturesCopyWithExternalBackend(
GrContext* context,
SkYUVColorSpace yuvColorSpace,
const GrBackendTexture yuvaTextures[],
const SkYUVAIndex yuvaIndices[4],
SkISize imageSize,
GrSurfaceOrigin imageOrigin,
const GrBackendTexture& backendTexture,
sk_sp<SkColorSpace> imageColorSpace = nullptr);
/** Creates SkImage from copy of yuvTextures, an array of textures on GPU.
yuvTextures contain pixels for YUV planes of SkImage. Returned SkImage has the dimensions
yuvTextures[0]. yuvColorSpace describes how YUV colors convert to RGB colors.
@param context GPU context
@param yuvColorSpace one of: kJPEG_SkYUVColorSpace, kRec601_SkYUVColorSpace,
kRec709_SkYUVColorSpace
@param yuvTextures array of YUV textures on GPU
@param imageOrigin one of: kBottomLeft_GrSurfaceOrigin, kTopLeft_GrSurfaceOrigin
@param imageColorSpace range of colors; may be nullptr
@return created SkImage, or nullptr
*/
static sk_sp<SkImage> MakeFromYUVTexturesCopy(GrContext* context, SkYUVColorSpace yuvColorSpace,
const GrBackendObject yuvTextureHandles[3],
const SkISize yuvSizes[3],
GrSurfaceOrigin surfaceOrigin,
sk_sp<SkColorSpace> colorSpace = nullptr);
const GrBackendTexture yuvTextures[3],
GrSurfaceOrigin imageOrigin,
sk_sp<SkColorSpace> imageColorSpace = nullptr);
/** Creates SkImage from copy of nv12TextureHandles, an array of textures on GPU.
nv12TextureHandles[0] contains pixels for YUV_Component_Y plane.
nv12TextureHandles[1] contains pixels for YUV_Component_U plane,
followed by pixels for YUV_Component_V plane.
nv12Sizes contain dimensions for each pixel plane. Dimensions must be greater than
zero but may differ from plane to plane. Returned SkImage has the dimensions
nv12Sizes[0]. yuvColorSpace describes how YUV colors convert to RGB colors.
/** Creates SkImage from copy of yuvTextures, an array of textures on GPU.
yuvTextures contain pixels for YUV planes of SkImage. Returned SkImage has the dimensions
yuvTextures[0] and stores pixels in backendTexture. yuvColorSpace describes how YUV colors
convert to RGB colors.
@param context GPU context
@param yuvColorSpace one of: kJPEG_SkYUVColorSpace, kRec601_SkYUVColorSpace,
kRec709_SkYUVColorSpace
@param nv12TextureHandles array of YUV textures on GPU
@param nv12Sizes dimensions of YUV textures
@param surfaceOrigin one of: kBottomLeft_GrSurfaceOrigin, kTopLeft_GrSurfaceOrigin
@param colorSpace range of colors; may be nullptr
@return created SkImage, or nullptr
@param context GPU context
@param yuvColorSpace one of: kJPEG_SkYUVColorSpace, kRec601_SkYUVColorSpace,
kRec709_SkYUVColorSpace
@param yuvTextures array of YUV textures on GPU
@param imageOrigin one of: kBottomLeft_GrSurfaceOrigin, kTopLeft_GrSurfaceOrigin
@param backendTexture the resource that stores the final pixels
@param imageColorSpace range of colors; may be nullptr
@return created SkImage, or nullptr
*/
static sk_sp<SkImage> MakeFromYUVTexturesCopyWithExternalBackend(
GrContext* context, SkYUVColorSpace yuvColorSpace,
const GrBackendTexture yuvTextures[3], GrSurfaceOrigin imageOrigin,
const GrBackendTexture& backendTexture, sk_sp<SkColorSpace> imageColorSpace = nullptr);
/** Creates SkImage from copy of nv12Textures, an array of textures on GPU.
nv12Textures[0] contains pixels for YUV component y plane.
nv12Textures[1] contains pixels for YUV component u plane,
followed by pixels for YUV component v plane.
Returned SkImage has the dimensions nv12Textures[2].
yuvColorSpace describes how YUV colors convert to RGB colors.
@param context GPU context
@param yuvColorSpace one of: kJPEG_SkYUVColorSpace, kRec601_SkYUVColorSpace,
kRec709_SkYUVColorSpace
@param nv12Textures array of YUV textures on GPU
@param imageOrigin one of: kBottomLeft_GrSurfaceOrigin, kTopLeft_GrSurfaceOrigin
@param imageColorSpace range of colors; may be nullptr
@return created SkImage, or nullptr
*/
static sk_sp<SkImage> MakeFromNV12TexturesCopy(GrContext* context,
SkYUVColorSpace yuvColorSpace,
const GrBackendObject nv12TextureHandles[2],
const SkISize nv12Sizes[2],
GrSurfaceOrigin surfaceOrigin,
sk_sp<SkColorSpace> colorSpace = nullptr);
const GrBackendTexture nv12Textures[2],
GrSurfaceOrigin imageOrigin,
sk_sp<SkColorSpace> imageColorSpace = nullptr);
/** Creates SkImage from copy of yuvTextureHandles, an array of textures on GPU.
yuvTextureHandles contain pixels for YUV planes of SkImage.
yuvSizes contain dimensions for each pixel plane. Dimensions must be greater than
zero but may differ from plane to plane. Returned SkImage has the dimensions
yuvSizes[0]. yuvColorSpace describes how YUV colors convert to RGB colors.
/** Creates SkImage from copy of nv12Textures, an array of textures on GPU.
nv12Textures[0] contains pixels for YUV component y plane.
nv12Textures[1] contains pixels for YUV component u plane,
followed by pixels for YUV component v plane.
Returned SkImage has the dimensions nv12Textures[2] and stores pixels in backendTexture.
yuvColorSpace describes how YUV colors convert to RGB colors.
@param context GPU context
@param yuvColorSpace one of: kJPEG_SkYUVColorSpace, kRec601_SkYUVColorSpace,
kRec709_SkYUVColorSpace
@param yuvTextureHandles array of YUV textures on GPU
@param yuvSizes dimensions of YUV textures
@param surfaceOrigin one of: kBottomLeft_GrSurfaceOrigin, kTopLeft_GrSurfaceOrigin
@param colorSpace range of colors; may be nullptr
@return created SkImage, or nullptr
@param context GPU context
@param yuvColorSpace one of: kJPEG_SkYUVColorSpace, kRec601_SkYUVColorSpace,
kRec709_SkYUVColorSpace
@param nv12Textures array of YUV textures on GPU
@param imageOrigin one of: kBottomLeft_GrSurfaceOrigin, kTopLeft_GrSurfaceOrigin
@param backendTexture the resource that stores the final pixels
@param imageColorSpace range of colors; may be nullptr
@return created SkImage, or nullptr
*/
static sk_sp<SkImage> MakeFromYUVTexturesCopy(GrContext* context, SkYUVColorSpace yuvColorSpace,
const GrBackendTexture yuvTextureHandles[3],
const SkISize yuvSizes[3],
GrSurfaceOrigin surfaceOrigin,
sk_sp<SkColorSpace> colorSpace = nullptr);
/** Creates SkImage from copy of nv12TextureHandles, an array of textures on GPU.
nv12TextureHandles[0] contains pixels for YUV_Component_Y plane.
nv12TextureHandles[1] contains pixels for YUV_Component_U plane,
followed by pixels for YUV_Component_V plane.
nv12Sizes contain dimensions for each pixel plane. Dimensions must be greater than
zero but may differ from plane to plane. Returned SkImage has the dimensions
nv12Sizes[0]. yuvColorSpace describes how YUV colors convert to RGB colors.
@param context GPU context
@param yuvColorSpace one of: kJPEG_SkYUVColorSpace, kRec601_SkYUVColorSpace,
kRec709_SkYUVColorSpace
@param nv12TextureHandles array of YUV textures on GPU
@param nv12Sizes dimensions of YUV textures
@param surfaceOrigin one of: kBottomLeft_GrSurfaceOrigin, kTopLeft_GrSurfaceOrigin
@param colorSpace range of colors; may be nullptr
@return created SkImage, or nullptr
*/
static sk_sp<SkImage> MakeFromNV12TexturesCopy(GrContext* context,
SkYUVColorSpace yuvColorSpace,
const GrBackendTexture nv12TextureHandles[2],
const SkISize nv12Sizes[2],
GrSurfaceOrigin surfaceOrigin,
sk_sp<SkColorSpace> colorSpace = nullptr);
static sk_sp<SkImage> MakeFromNV12TexturesCopyWithExternalBackend(
GrContext* context,
SkYUVColorSpace yuvColorSpace,
const GrBackendTexture nv12Textures[2],
GrSurfaceOrigin imageOrigin,
const GrBackendTexture& backendTexture,
sk_sp<SkColorSpace> imageColorSpace = nullptr);
enum class BitDepth {
kU8, //!< Use 8 bits per ARGB component using unsigned integer format.
kF16, //!< Use 16 bits per ARGB component using half-precision floating point format.
kU8, //!< uses 8-bit unsigned int per color component
kF16, //!< uses 16-bit float per color component
};
/** Creates SkImage from picture. Returned SkImage width and height are set by dimensions.
@ -431,7 +476,7 @@ public:
@param dimensions width and height
@param matrix SkMatrix to rotate, scale, translate, and so on; may be nullptr
@param paint SkPaint to apply transparency, filtering, and so on; may be nullptr
@param bitDepth 8 bit integer or 16 bit float: per component
@param bitDepth 8-bit integer or 16-bit float: per component
@param colorSpace range of colors; may be nullptr
@return created SkImage, or nullptr
*/
@ -448,14 +493,18 @@ public:
Only available on Android, when __ANDROID_API__ is defined to be 26 or greater.
@param hardwareBuffer AHardwareBuffer Android hardware buffer
@param alphaType one of: kUnknown_SkAlphaType, kOpaque_SkAlphaType,
kPremul_SkAlphaType, kUnpremul_SkAlphaType
@param alphaType one of:
kUnknown_SkAlphaType, kOpaque_SkAlphaType, kPremul_SkAlphaType,
kUnpremul_SkAlphaType
@param colorSpace range of colors; may be nullptr
@param surfaceOrigin one of: kBottomLeft_GrSurfaceOrigin, kTopLeft_GrSurfaceOrigin
@return created SkImage, or nullptr
*/
static sk_sp<SkImage> MakeFromAHardwareBuffer(AHardwareBuffer* hardwareBuffer,
SkAlphaType alphaType = kPremul_SkAlphaType,
sk_sp<SkColorSpace> colorSpace = nullptr);
static sk_sp<SkImage> MakeFromAHardwareBuffer(
AHardwareBuffer* hardwareBuffer,
SkAlphaType alphaType = kPremul_SkAlphaType,
sk_sp<SkColorSpace> colorSpace = nullptr,
GrSurfaceOrigin surfaceOrigin = kTopLeft_GrSurfaceOrigin);
#endif
/** Returns pixel count in each row.
@ -490,8 +539,9 @@ public:
*/
uint32_t uniqueID() const { return fUniqueID; }
/** Returns SkAlphaType, one of: kUnknown_SkAlphaType, kOpaque_SkAlphaType,
kPremul_SkAlphaType, kUnpremul_SkAlphaType.
/** Returns SkAlphaType, one of:
kUnknown_SkAlphaType, kOpaque_SkAlphaType, kPremul_SkAlphaType,
kUnpremul_SkAlphaType.
SkAlphaType returned was a parameter to an SkImage constructor,
or was parsed from encoded data.
@ -500,6 +550,12 @@ public:
*/
SkAlphaType alphaType() const;
/** Returns SkColorType if known; otherwise, returns kUnknown_SkColorType.
@return SkColorType of SkImage
*/
SkColorType colorType() const;
/** Returns SkColorSpace, the range of colors, associated with SkImage. The
reference count of SkColorSpace is unchanged. The returned SkColorSpace is
immutable.
@ -543,10 +599,10 @@ public:
SkShader::TileMode rules to fill drawn area outside SkImage. localMatrix permits
transforming SkImage before SkCanvas matrix is applied.
@param tileMode1 tiling in x, one of: SkShader::kClamp_TileMode, SkShader::kRepeat_TileMode,
SkShader::kMirror_TileMode
@param tileMode2 tiling in y, one of: SkShader::kClamp_TileMode, SkShader::kRepeat_TileMode,
SkShader::kMirror_TileMode
@param tileMode1 tiling on x-axis, one of: SkShader::kClamp_TileMode,
SkShader::kRepeat_TileMode, SkShader::kMirror_TileMode
@param tileMode2 tiling on y-axis, one of: SkShader::kClamp_TileMode,
SkShader::kRepeat_TileMode, SkShader::kMirror_TileMode
@param localMatrix SkImage transformation, or nullptr
@return SkShader containing SkImage
*/
@ -597,18 +653,21 @@ public:
*/
bool isValid(GrContext* context) const;
/** Retrieves the back-end API handle of texture. If flushPendingGrContextIO is true,
complete deferred I/O operations.
/** Retrieves the back-end texture. If SkImage has no back-end texture, an invalid
object is returned. Call GrBackendTexture::isValid to determine if the result
is valid.
If flushPendingGrContextIO is true, completes deferred I/O operations.
If origin in not nullptr, copies location of content drawn into SkImage.
@param flushPendingGrContextIO flag to flush outstanding requests
@param origin storage for one of: kTopLeft_GrSurfaceOrigin,
kBottomLeft_GrSurfaceOrigin; or nullptr
@return back-end API texture handle, or nullptr
@return back-end API texture handle; invalid on failure
*/
GrBackendObject getTextureHandle(bool flushPendingGrContextIO,
GrSurfaceOrigin* origin = nullptr) const;
GrBackendTexture getBackendTexture(bool flushPendingGrContextIO,
GrSurfaceOrigin* origin = nullptr) const;
/** \enum SkImage::CachingHint
CachingHint selects whether Skia may internally cache SkBitmap generated by
@ -623,10 +682,8 @@ public:
pixels are not accessible.
*/
enum CachingHint {
kAllow_CachingHint, //!< Allows Skia to internally cache decoded and copied pixels.
/** Disallows Skia from internally caching decoded and copied pixels. */
kDisallow_CachingHint,
kAllow_CachingHint, //!< allows internally caching decoded and copied pixels
kDisallow_CachingHint, //!< disallows internally caching decoded and copied pixels
};
/** Copies SkRect of pixels from SkImage to dstPixels. Copy starts at offset (srcX, srcY),
@ -772,14 +829,6 @@ public:
*/
sk_sp<SkData> refEncodedData() const;
/** Appends SkImage description to string, including unique ID, width, height, and
whether the image is opaque.
@param string storage for description; existing content is preserved
@return string appended with SkImage description
*/
const char* toString(SkString* string) const;
/** Returns subset of SkImage. subset must be fully contained by SkImage dimensions().
The implementation may share pixels, or may copy them.
@ -792,17 +841,21 @@ public:
sk_sp<SkImage> makeSubset(const SkIRect& subset) const;
/** Returns SkImage backed by GPU texture associated with context. Returned SkImage is
compatible with SkSurface created with dstColorSpace. Returns original
SkImage if context and dstColorSpace match.
compatible with SkSurface created with dstColorSpace. The returned SkImage respects
mipMapped setting; if mipMapped equals GrMipMapped::kYes, the backing texture
allocates mip map levels. Returns original SkImage if context
and dstColorSpace match and mipMapped is compatible with backing GPU texture.
Returns nullptr if context is nullptr, or if SkImage was created with another
GrContext.
@param context GPU context
@param dstColorSpace range of colors of matching SkSurface on GPU
@param mipMapped whether created SkImage texture must allocate mip map levels
@return created SkImage, or nullptr
*/
sk_sp<SkImage> makeTextureImage(GrContext* context, SkColorSpace* dstColorSpace) const;
sk_sp<SkImage> makeTextureImage(GrContext* context, SkColorSpace* dstColorSpace,
GrMipMapped mipMapped = GrMipMapped::kNo) const;
/** Returns raster image or lazy image. Copies SkImage backed by GPU texture into
CPU memory if needed. Returns original SkImage if decoded in raster bitmap,
@ -850,6 +903,9 @@ public:
const SkIRect& clipBounds, SkIRect* outSubset,
SkIPoint* offset) const;
/** Defines a callback function, taking one parameter of type GrBackendTexture with
no return value. Function is called when back-end texture is to be released.
*/
typedef std::function<void(GrBackendTexture)> BackendTextureReleaseProc;
/** Creates a GrBackendTexture from the provided SkImage. Returns true and
@ -869,9 +925,9 @@ public:
@param context GPU context
@param image SkImage used for texture
@param backendTexture storage for backend texture
@param backendTexture storage for back-end texture
@param backendTextureReleaseProc storage for clean up function
@return true if backend texture was created
@return true if back-end texture was created
*/
static bool MakeBackendTextureFromSkImage(GrContext* context,
sk_sp<SkImage> image,
@ -879,7 +935,7 @@ public:
BackendTextureReleaseProc* backendTextureReleaseProc);
enum LegacyBitmapMode {
kRO_LegacyBitmapMode, //!< Returned bitmap is read-only and immutable.
kRO_LegacyBitmapMode, //!< returned bitmap is read-only and immutable
};
/** Creates raster SkBitmap with same pixels as SkImage. If legacyBitmapMode is
@ -907,23 +963,10 @@ public:
Otherwise, converts pixels from SkImage SkColorSpace to target SkColorSpace.
If SkImage colorSpace() returns nullptr, SkImage SkColorSpace is assumed to be sRGB.
SkTransferFunctionBehavior is to be deprecated.
Set premulBehavior to SkTransferFunctionBehavior::kRespect to convert SkImage
pixels to a linear space, before converting to destination SkColorType
and SkColorSpace.
Set premulBehavior to SkTransferFunctionBehavior::kIgnore to treat SkImage
pixels as linear, when converting to destination SkColorType
and SkColorSpace, ignoring pixel encoding.
@param target SkColorSpace describing color range of returned SkImage
@param premulBehavior one of: SkTransferFunctionBehavior::kRespect,
SkTransferFunctionBehavior::kIgnore
@return created SkImage in target SkColorSpace
@param target SkColorSpace describing color range of returned SkImage
@return created SkImage in target SkColorSpace
*/
sk_sp<SkImage> makeColorSpace(sk_sp<SkColorSpace> target,
SkTransferFunctionBehavior premulBehavior) const;
sk_sp<SkImage> makeColorSpace(sk_sp<SkColorSpace> target) const;
private:
SkImage(int width, int height, uint32_t uniqueID);

Просмотреть файл

@ -14,6 +14,7 @@
#include "SkColorSpace.h"
#include "SkFilterQuality.h"
#include "SkFlattenable.h"
#include "SkImageInfo.h"
#include "SkMatrix.h"
#include "SkRect.h"
@ -41,11 +42,14 @@ public:
// consumer of the DAG's output.
class OutputProperties {
public:
explicit OutputProperties(SkColorSpace* colorSpace) : fColorSpace(colorSpace) {}
explicit OutputProperties(SkColorType colorType, SkColorSpace* colorSpace)
: fColorType(colorType), fColorSpace(colorSpace) {}
SkColorType colorType() const { return fColorType; }
SkColorSpace* colorSpace() const { return fColorSpace; }
private:
SkColorType fColorType;
// This will be a pointer to the device's color space, and our lifetime is bounded by
// the device, so we can store a bare pointer.
SkColorSpace* fColorSpace;
@ -97,9 +101,6 @@ public:
: fRect(rect), fFlags(flags) {}
uint32_t flags() const { return fFlags; }
const SkRect& rect() const { return fRect; }
#ifndef SK_IGNORE_TO_STRING
void toString(SkString* str) const;
#endif
/**
* Apply this cropRect to the imageBounds. If a given edge of the cropRect is not
@ -157,9 +158,13 @@ public:
* be exact, but should never be smaller than the real answer. The default
* implementation recursively unions all input bounds, or returns the
* source rect if no inputs.
*
* In kReverse mode, 'inputRect' is the device-space bounds of the input pixels. In kForward
* mode it should always be null. If 'inputRect' is null in kReverse mode the resulting
* answer may be incorrect.
*/
SkIRect filterBounds(const SkIRect& src, const SkMatrix& ctm,
MapDirection = kReverse_MapDirection) const;
MapDirection, const SkIRect* inputRect = nullptr) const;
#if SK_SUPPORT_GPU
static sk_sp<SkSpecialImage> DrawWithFP(GrContext* context,
@ -247,9 +252,22 @@ public:
SkFilterQuality quality,
sk_sp<SkImageFilter> input);
SK_TO_STRING_PUREVIRT()
SK_DEFINE_FLATTENABLE_TYPE(SkImageFilter)
SK_DECLARE_FLATTENABLE_REGISTRAR_GROUP()
static void InitializeFlattenables();
static SkFlattenable::Type GetFlattenableType() {
return kSkImageFilter_Type;
}
SkFlattenable::Type getFlattenableType() const override {
return kSkImageFilter_Type;
}
static sk_sp<SkImageFilter> Deserialize(const void* data, size_t size,
const SkDeserialProcs* procs = nullptr) {
return sk_sp<SkImageFilter>(static_cast<SkImageFilter*>(
SkFlattenable::Deserialize(
kSkImageFilter_Type, data, size, procs).release()));
}
protected:
class Common {
@ -266,16 +284,14 @@ protected:
const CropRect& cropRect() const { return fCropRect; }
int inputCount() const { return fInputs.count(); }
sk_sp<SkImageFilter>* inputs() const { return fInputs.get(); }
sk_sp<SkImageFilter>* inputs() { return fInputs.begin(); }
sk_sp<SkImageFilter> getInput(int index) const { return fInputs[index]; }
sk_sp<SkImageFilter> getInput(int index) { return fInputs[index]; }
private:
CropRect fCropRect;
// most filters accept at most 2 input-filters
SkAutoSTArray<2, sk_sp<SkImageFilter>> fInputs;
void allocInputs(int count);
SkSTArray<2, sk_sp<SkImageFilter>, true> fInputs;
};
SkImageFilter(sk_sp<SkImageFilter> const* inputs, int inputCount, const CropRect* cropRect);
@ -325,18 +341,22 @@ protected:
* and returns the union of those results. If a derived class has special
* recursion requirements (e.g., it has an input which does not participate
* in bounds computation), it can be overridden here.
* In kReverse mode, 'inputRect' is the device-space bounds of the input pixels. In kForward
* mode it should always be null. If 'inputRect' is null in kReverse mode the resulting
* answer may be incorrect.
*
* Note that this function is *not* responsible for mapping the rect for
* this node's filter bounds requirements (i.e., calling
* onFilterNodeBounds()); that is handled by filterBounds().
*/
virtual SkIRect onFilterBounds(const SkIRect&, const SkMatrix&, MapDirection) const;
virtual SkIRect onFilterBounds(const SkIRect&, const SkMatrix& ctm,
MapDirection, const SkIRect* inputRect) const;
/**
* Performs a forwards or reverse mapping of the given rect to accommodate
* this filter's margin requirements. kForward_MapDirection is used to
* determine the destination pixels which would be touched by filtering
* the given given source rect (e.g., given source bitmap bounds,
* the given source rect (e.g., given source bitmap bounds,
* determine the optimal bounds of the filtered offscreen bitmap).
* kReverse_MapDirection is used to determine which pixels of the
* input(s) would be required to fill the given destination rect
@ -344,8 +364,12 @@ protected:
* inverse of the other. For example, blurring expands the given rect
* in both forward and reverse directions. Unlike
* onFilterBounds(), this function is non-recursive.
* In kReverse mode, 'inputRect' will be the device space bounds of the input pixels. In
* kForward mode, 'inputRect' should always be null. If 'inputRect' is null in kReverse mode
* the resulting answer may be incorrect.
*/
virtual SkIRect onFilterNodeBounds(const SkIRect&, const SkMatrix&, MapDirection) const;
virtual SkIRect onFilterNodeBounds(const SkIRect&, const SkMatrix& ctm,
MapDirection, const SkIRect* inputRect) const;
// Helper function which invokes filter processing on the input at the
// specified "index". If the input is null, it returns "src" and leaves
@ -389,8 +413,8 @@ protected:
* which are not capable of processing a smaller source bitmap into a
* larger destination.
*/
sk_sp<SkSpecialImage> applyCropRect(const Context&, SkSpecialImage* src, SkIPoint* srcOffset,
SkIRect* bounds) const;
sk_sp<SkSpecialImage> applyCropRectAndPad(const Context&, SkSpecialImage* src,
SkIPoint* srcOffset, SkIRect* bounds) const;
/**
* Creates a modified Context for use when recursing up the image filter DAG.
@ -421,6 +445,15 @@ protected:
return sk_ref_sp(const_cast<SkImageFilter*>(this));
}
// If 'srcBounds' will sample outside the border of 'originalSrcBounds' (i.e., the sample
// will wrap around to the other side) we must preserve the far side of the src along that
// axis (e.g., if we will sample beyond the left edge of the src, the right side must be
// preserved for the repeat sampling to work).
static SkIRect DetermineRepeatedSrcBound(const SkIRect& srcBounds,
const SkIVector& filterOffset,
const SkISize& filterSize,
const SkIRect& originalSrcBounds);
private:
// For makeColorSpace().
friend class SkColorSpaceXformer;
@ -439,8 +472,7 @@ private:
bool fUsesSrcInput;
CropRect fCropRect;
uint32_t fUniqueID; // Globally unique
mutable SkTArray<SkImageFilterCacheKey> fCacheKeys;
mutable SkMutex fMutex;
typedef SkFlattenable INHERITED;
};

Просмотреть файл

@ -24,7 +24,7 @@ class SkMatrix;
class SkPaint;
class SkPicture;
class SK_API SkImageGenerator : public SkNoncopyable {
class SK_API SkImageGenerator {
public:
/**
* The PixelRef which takes ownership of this SkImageGenerator
@ -41,7 +41,7 @@ public:
* If non-NULL is returned, the caller is responsible for calling
* unref() on the data when it is finished.
*/
SkData* refEncodedData() {
sk_sp<SkData> refEncodedData() {
return this->onRefEncodedData();
}
@ -78,22 +78,8 @@ public:
* to scale. If the generator cannot perform this scale,
* it will return false.
*
* kIndex_8_SkColorType is not supported.
*
* @return true on success.
*/
struct Options {
Options()
: fBehavior(SkTransferFunctionBehavior::kIgnore)
{}
SkTransferFunctionBehavior fBehavior;
};
bool getPixels(const SkImageInfo& info, void* pixels, size_t rowBytes, const Options* options);
/**
* Simplified version of getPixels() that uses the default Options.
*/
bool getPixels(const SkImageInfo& info, void* pixels, size_t rowBytes);
/**
@ -148,7 +134,6 @@ public:
*/
sk_sp<GrTextureProxy> generateTexture(GrContext*, const SkImageInfo& info,
const SkIPoint& origin,
SkTransferFunctionBehavior behavior,
bool willNeedMipMaps);
#endif
@ -170,13 +155,12 @@ public:
sk_sp<SkColorSpace>);
protected:
enum {
kNeedNewImageUniqueID = 0
};
static constexpr int kNeedNewImageUniqueID = 0;
SkImageGenerator(const SkImageInfo& info, uint32_t uniqueId = kNeedNewImageUniqueID);
virtual SkData* onRefEncodedData() { return nullptr; }
virtual sk_sp<SkData> onRefEncodedData() { return nullptr; }
struct Options {};
virtual bool onGetPixels(const SkImageInfo&, void*, size_t, const Options&) { return false; }
virtual bool onIsValid(GrContext*) const { return true; }
virtual bool onQueryYUV8(SkYUVSizeInfo*, SkYUVColorSpace*) const { return false; }
@ -191,7 +175,6 @@ protected:
virtual TexGenType onCanGenerateTexture() const { return TexGenType::kNone; }
virtual sk_sp<GrTextureProxy> onGenerateTexture(GrContext*, const SkImageInfo&, const SkIPoint&,
SkTransferFunctionBehavior,
bool willNeedMipMaps); // returns nullptr
#endif
@ -205,6 +188,11 @@ private:
// It is called from NewFromEncoded() after it has checked for any runtime factory.
// The SkData will never be NULL, as that will have been checked by NewFromEncoded.
static std::unique_ptr<SkImageGenerator> MakeFromEncodedImpl(sk_sp<SkData>);
SkImageGenerator(SkImageGenerator&&) = delete;
SkImageGenerator(const SkImageGenerator&) = delete;
SkImageGenerator& operator=(SkImageGenerator&&) = delete;
SkImageGenerator& operator=(const SkImageGenerator&) = delete;
};
#endif // SkImageGenerator_DEFINED

Просмотреть файл

@ -5,6 +5,16 @@
* found in the LICENSE file.
*/
/* Generated by tools/bookmaker from include/core/SkImageInfo.h and docs/SkImageInfo_Reference.bmh
on 2018-07-13 08:15:11. Additional documentation and examples can be found at:
https://skia.org/user/api/SkImageInfo_Reference
You may edit either file directly. Structural changes to public interfaces require
editing both files. After editing docs/SkImageInfo_Reference.bmh, run:
bookmaker -b docs -i include/core/SkImageInfo.h -p
to create an updated version of this file.
*/
#ifndef SkImageInfo_DEFINED
#define SkImageInfo_DEFINED
@ -13,41 +23,46 @@
#include "SkRect.h"
#include "SkSize.h"
#include "../private/SkTFitsIn.h"
#include "../private/SkTo.h"
class SkReadBuffer;
class SkWriteBuffer;
/**
* Describes how to interpret the alpha component of a pixel.
*/
/** \enum SkImageInfo::SkAlphaType
Describes how to interpret the alpha component of a pixel. A pixel may
be opaque, or alpha, describing multiple levels of transparency.
In simple blending, alpha weights the draw color and the destination
color to create a new color. If alpha describes a weight from zero to one:
new color = draw color * alpha + destination color * (1 - alpha)
In practice alpha is encoded in two or more bits, where 1.0 equals all bits set.
RGB may have alpha included in each component value; the stored
value is the original RGB multiplied by alpha. Premultiplied color
components improve performance.
*/
enum SkAlphaType {
kUnknown_SkAlphaType,
/**
* All pixels are stored as opaque. This differs slightly from kIgnore in
* that kOpaque has correct "opaque" values stored in the pixels, while
* kIgnore may not, but in both cases the caller should treat the pixels
* as opaque.
*/
kOpaque_SkAlphaType,
/**
* All pixels have their alpha premultiplied in their color components.
* This is the natural format for the rendering target pixels.
*/
kPremul_SkAlphaType,
/**
* All pixels have their color components stored without any regard to the
* alpha. e.g. this is the default configuration for PNG images.
*
* This alpha-type is ONLY supported for input images. Rendering cannot
* generate this on output.
*/
kUnpremul_SkAlphaType,
kLastEnum_SkAlphaType = kUnpremul_SkAlphaType,
kUnknown_SkAlphaType, //!< uninitialized
kOpaque_SkAlphaType, //!< pixel is opaque
kPremul_SkAlphaType, //!< pixel components are premultiplied by alpha
kUnpremul_SkAlphaType, //!< pixel components are independent of alpha
kLastEnum_SkAlphaType = kUnpremul_SkAlphaType, //!< last valid value
};
/** Returns true if SkAlphaType equals kOpaque_SkAlphaType. kOpaque_SkAlphaType is a
hint that the SkColorType is opaque, or that all alpha values are set to
their 1.0 equivalent. If SkAlphaType is kOpaque_SkAlphaType, and SkColorType is not
opaque, then the result of drawing any pixel with a alpha value less than
1.0 is undefined.
@param at one of:
kUnknown_SkAlphaType, kOpaque_SkAlphaType, kPremul_SkAlphaType,
kUnpremul_SkAlphaType
@return true if at equals kOpaque_SkAlphaType
*/
static inline bool SkAlphaTypeIsOpaque(SkAlphaType at) {
return kOpaque_SkAlphaType == at;
}
@ -57,265 +72,549 @@ static inline bool SkAlphaTypeIsOpaque(SkAlphaType at) {
/** Temporary macro that allows us to add new color types without breaking Chrome compile. */
#define SK_EXTENDED_COLOR_TYPES
/**
* Describes how to interpret the components of a pixel.
*
* kN32_SkColorType is an alias for whichever 32bit ARGB format is the "native"
* form for skia's blitters. Use this if you don't have a swizzle preference
* for 32bit pixels.
*/
enum SkColorType {
kUnknown_SkColorType,
kAlpha_8_SkColorType,
kRGB_565_SkColorType,
kARGB_4444_SkColorType,
kRGBA_8888_SkColorType,
kRGB_888x_SkColorType,
kBGRA_8888_SkColorType,
kRGBA_1010102_SkColorType,
kRGB_101010x_SkColorType,
kGray_8_SkColorType,
kRGBA_F16_SkColorType,
/** \enum SkImageInfo::SkColorType
Describes how pixel bits encode color. A pixel may be an alpha mask, a
grayscale, RGB, or ARGB.
kLastEnum_SkColorType = kRGBA_F16_SkColorType,
kN32_SkColorType selects the native 32-bit ARGB format. On little endian
processors, pixels containing 8-bit ARGB components pack into 32-bit
kBGRA_8888_SkColorType. On big endian processors, pixels pack into 32-bit
kRGBA_8888_SkColorType.
*/
enum SkColorType {
kUnknown_SkColorType, //!< uninitialized
kAlpha_8_SkColorType, //!< pixel with alpha in 8-bit byte
kRGB_565_SkColorType, //!< pixel with 5 bits red, 6 bits green, 5 bits blue, in 16-bit word
kARGB_4444_SkColorType, //!< pixel with 4 bits for alpha, red, green, blue; in 16-bit word
kRGBA_8888_SkColorType, //!< pixel with 8 bits for red, green, blue, alpha; in 32-bit word
kRGB_888x_SkColorType, //!< pixel with 8 bits each for red, green, blue; in 32-bit word
kBGRA_8888_SkColorType, //!< pixel with 8 bits for blue, green, red, alpha; in 32-bit word
kRGBA_1010102_SkColorType, //!< 10 bits for red, green, blue; 2 bits for alpha; in 32-bit word
kRGB_101010x_SkColorType, //!< pixel with 10 bits each for red, green, blue; in 32-bit word
kGray_8_SkColorType, //!< pixel with grayscale level in 8-bit byte
kRGBA_F16_SkColorType, //!< pixel with half floats for red, green, blue, alpha; in 64-bit word
kRGBA_F32_SkColorType, //!< pixel using C float for red, green, blue, alpha; in 128-bit word
kLastEnum_SkColorType = kRGBA_F32_SkColorType,//!< last valid value
#if SK_PMCOLOR_BYTE_ORDER(B,G,R,A)
kN32_SkColorType = kBGRA_8888_SkColorType,
kN32_SkColorType = kBGRA_8888_SkColorType,//!< native ARGB 32-bit encoding
#elif SK_PMCOLOR_BYTE_ORDER(R,G,B,A)
kN32_SkColorType = kRGBA_8888_SkColorType,
kN32_SkColorType = kRGBA_8888_SkColorType,//!< native ARGB 32-bit encoding
#else
kN32_SkColorType = kBGRA_8888_SkColorType,
#endif
};
/**
* Returns the number of bytes-per-pixel for the specified colortype, or 0 if invalid.
*/
/** Returns the number of bytes required to store a pixel, including unused padding.
Returns zero if ct is kUnknown_SkColorType or invalid.
@param ct one of:
kUnknown_SkColorType, kAlpha_8_SkColorType, kRGB_565_SkColorType,
kARGB_4444_SkColorType, kRGBA_8888_SkColorType, kRGB_888x_SkColorType,
kBGRA_8888_SkColorType, kRGBA_1010102_SkColorType, kRGB_101010x_SkColorType,
kGray_8_SkColorType, kRGBA_F16_SkColorType
@return bytes per pixel
*/
SK_API int SkColorTypeBytesPerPixel(SkColorType ct);
/**
* Returns true iff the colortype is always considered opaque (i.e. does not store alpha).
*/
/** Returns true if SkColorType always decodes alpha to 1.0, making the pixel
fully opaque. If true, SkColorType does not reserve bits to encode alpha.
@param ct one of:
kUnknown_SkColorType, kAlpha_8_SkColorType, kRGB_565_SkColorType,
kARGB_4444_SkColorType, kRGBA_8888_SkColorType, kRGB_888x_SkColorType,
kBGRA_8888_SkColorType, kRGBA_1010102_SkColorType, kRGB_101010x_SkColorType,
kGray_8_SkColorType, kRGBA_F16_SkColorType
@return true if alpha is always set to 1.0
*/
SK_API bool SkColorTypeIsAlwaysOpaque(SkColorType ct);
/**
* Tries to validate the colortype, alphatype pair. In all cases if it returns true, it
* will set canonical to the "canonical" answer if it is non-null, and ignore the parameter if
* it is set to null.
*
* If the specified colortype has only 1 valid alphatype (e.g. 565 must always be opaque) then
* canonical will be set to that valid alphatype.
*
* If the specified colortype treats more than one alphatype the same (e.g. Alpha_8 colortype
* treates Premul and Unpremul the same) and the specified alphatype is one of those,
* then canonical will be set to the "canonical" answer (Premul in the case of Alpha_8 colortype).
*
* If the colortype supports multiple alphatypes, and the specified alphatype is one of them,
* then canonical will be set to the specified alphatype. If the specified alphatype is not
* one of them (e.g. kUnknown_SkAlphaType is not valid for any colortype except
* kUnknown_SkColorType), then the function returns false, and canonical's value is undefined.
*/
/** Returns true if canonical can be set to a valid SkAlphaType for colorType. If
there is more than one valid canonical SkAlphaType, set to alphaType, if valid.
If true is returned and canonical is not nullptr, store valid SkAlphaType.
Returns false only if alphaType is kUnknown_SkAlphaType, color type is not
kUnknown_SkColorType, and SkColorType is not always opaque. If false is returned,
canonical is ignored.
For kUnknown_SkColorType: set canonical to kUnknown_SkAlphaType and return true.
For kAlpha_8_SkColorType: set canonical to kPremul_SkAlphaType or
kOpaque_SkAlphaType and return true if alphaType is not kUnknown_SkAlphaType.
For kRGB_565_SkColorType, kRGB_888x_SkColorType, kRGB_101010x_SkColorType, and
kGray_8_SkColorType: set canonical to kOpaque_SkAlphaType and return true.
For kARGB_4444_SkColorType, kRGBA_8888_SkColorType, kBGRA_8888_SkColorType,
kRGBA_1010102_SkColorType, and kRGBA_F16_SkColorType: set canonical to alphaType
and return true if alphaType is not kUnknown_SkAlphaType.
@param colorType one of:
kUnknown_SkColorType, kAlpha_8_SkColorType, kRGB_565_SkColorType,
kARGB_4444_SkColorType, kRGBA_8888_SkColorType, kRGB_888x_SkColorType,
kBGRA_8888_SkColorType, kRGBA_1010102_SkColorType, kRGB_101010x_SkColorType,
kGray_8_SkColorType, kRGBA_F16_SkColorType
@param alphaType one of:
kUnknown_SkAlphaType, kOpaque_SkAlphaType, kPremul_SkAlphaType,
kUnpremul_SkAlphaType
@param canonical storage for SkAlphaType
@return true if valid SkAlphaType can be associated with colorType
*/
SK_API bool SkColorTypeValidateAlphaType(SkColorType colorType, SkAlphaType alphaType,
SkAlphaType* canonical = nullptr);
/** \enum SkImageInfo::SkYUVColorSpace
Describes color range of YUV pixels. The color mapping from YUV to RGB varies
depending on the source. YUV pixels may be generated by JPEG images, standard
video streams, or high definition video streams. Each has its own mapping from
YUV and RGB.
///////////////////////////////////////////////////////////////////////////////
/**
* Describes the color space a YUV pixel.
*/
JPEG YUV values encode the full range of 0 to 255 for all three components.
Video YUV values range from 16 to 235 for all three components. Details of
encoding and conversion to RGB are described in YCbCr color space.
*/
enum SkYUVColorSpace {
/** Standard JPEG color space. */
kJPEG_SkYUVColorSpace,
/** SDTV standard Rec. 601 color space. Uses "studio swing" [16, 235] color
range. See http://en.wikipedia.org/wiki/Rec._601 for details. */
kRec601_SkYUVColorSpace,
/** HDTV standard Rec. 709 color space. Uses "studio swing" [16, 235] color
range. See http://en.wikipedia.org/wiki/Rec._709 for details. */
kRec709_SkYUVColorSpace,
kLastEnum_SkYUVColorSpace = kRec709_SkYUVColorSpace,
kJPEG_SkYUVColorSpace, //!< describes full range
kRec601_SkYUVColorSpace, //!< describes SDTV range
kRec709_SkYUVColorSpace, //!< describes HDTV range
kLastEnum_SkYUVColorSpace = kRec709_SkYUVColorSpace, //!< last valid value
};
///////////////////////////////////////////////////////////////////////////////
/** \struct SkImageInfo
Describes pixel dimensions and encoding. SkBitmap, SkImage, PixMap, and SkSurface
can be created from SkImageInfo. SkImageInfo can be retrieved from SkBitmap and
SkPixmap, but not from SkImage and SkSurface. For example, SkImage and SkSurface
implementations may defer pixel depth, so may not completely specify SkImageInfo.
/**
* Describe an image's dimensions and pixel type.
* Used for both src images and render-targets (surfaces).
*/
SkImageInfo contains dimensions, the pixel integral width and height. It encodes
how pixel bits describe alpha, transparency; color components red, blue,
and green; and SkColorSpace, the range and linearity of colors.
*/
struct SK_API SkImageInfo {
public:
/** Creates an empty SkImageInfo with kUnknown_SkColorType, kUnknown_SkAlphaType,
a width and height of zero, and no SkColorSpace.
@return empty SkImageInfo
*/
SkImageInfo()
: fColorSpace(nullptr)
, fWidth(0)
, fHeight(0)
, fDimensions{0, 0}
, fColorType(kUnknown_SkColorType)
, fAlphaType(kUnknown_SkAlphaType)
{}
/** Creates SkImageInfo from integral dimensions width and height, SkColorType ct,
SkAlphaType at, and optionally SkColorSpace cs.
If SkColorSpace cs is nullptr and SkImageInfo is part of drawing source: SkColorSpace
defaults to sRGB, mapping into SkSurface SkColorSpace.
Parameters are not validated to see if their values are legal, or that the
combination is supported.
@param width pixel column count; must be zero or greater
@param height pixel row count; must be zero or greater
@param ct one of:
kUnknown_SkColorType, kAlpha_8_SkColorType, kRGB_565_SkColorType,
kARGB_4444_SkColorType, kRGBA_8888_SkColorType, kRGB_888x_SkColorType,
kBGRA_8888_SkColorType, kRGBA_1010102_SkColorType, kRGB_101010x_SkColorType,
kGray_8_SkColorType, kRGBA_F16_SkColorType
@param at one of:
kUnknown_SkAlphaType, kOpaque_SkAlphaType, kPremul_SkAlphaType,
kUnpremul_SkAlphaType
@param cs range of colors; may be nullptr
@return created SkImageInfo
*/
static SkImageInfo Make(int width, int height, SkColorType ct, SkAlphaType at,
sk_sp<SkColorSpace> cs = nullptr) {
return SkImageInfo(width, height, ct, at, std::move(cs));
}
/**
* Sets colortype to the native ARGB32 type.
*/
/** Creates SkImageInfo from integral dimensions width and height, kN32_SkColorType,
SkAlphaType at, and optionally SkColorSpace cs. kN32_SkColorType will equal either
kBGRA_8888_SkColorType or kRGBA_8888_SkColorType, whichever is optimal.
If SkColorSpace cs is nullptr and SkImageInfo is part of drawing source: SkColorSpace
defaults to sRGB, mapping into SkSurface SkColorSpace.
Parameters are not validated to see if their values are legal, or that the
combination is supported.
@param width pixel column count; must be zero or greater
@param height pixel row count; must be zero or greater
@param at one of:
kUnknown_SkAlphaType, kOpaque_SkAlphaType, kPremul_SkAlphaType,
kUnpremul_SkAlphaType
@param cs range of colors; may be nullptr
@return created SkImageInfo
*/
static SkImageInfo MakeN32(int width, int height, SkAlphaType at,
sk_sp<SkColorSpace> cs = nullptr) {
return Make(width, height, kN32_SkColorType, at, cs);
return Make(width, height, kN32_SkColorType, at, std::move(cs));
}
/**
* Create an ImageInfo marked as SRGB with N32 swizzle.
*/
/** Creates SkImageInfo from integral dimensions width and height, kN32_SkColorType,
SkAlphaType at, with sRGB SkColorSpace.
Parameters are not validated to see if their values are legal, or that the
combination is supported.
@param width pixel column count; must be zero or greater
@param height pixel row count; must be zero or greater
@param at one of:
kUnknown_SkAlphaType, kOpaque_SkAlphaType, kPremul_SkAlphaType,
kUnpremul_SkAlphaType
@return created SkImageInfo
*/
static SkImageInfo MakeS32(int width, int height, SkAlphaType at);
/**
* Sets colortype to the native ARGB32 type, and the alphatype to premul.
*/
/** Creates SkImageInfo from integral dimensions width and height, kN32_SkColorType,
kPremul_SkAlphaType, with optional SkColorSpace.
If SkColorSpace cs is nullptr and SkImageInfo is part of drawing source: SkColorSpace
defaults to sRGB, mapping into SkSurface SkColorSpace.
Parameters are not validated to see if their values are legal, or that the
combination is supported.
@param width pixel column count; must be zero or greater
@param height pixel row count; must be zero or greater
@param cs range of colors; may be nullptr
@return created SkImageInfo
*/
static SkImageInfo MakeN32Premul(int width, int height, sk_sp<SkColorSpace> cs = nullptr) {
return Make(width, height, kN32_SkColorType, kPremul_SkAlphaType, cs);
return Make(width, height, kN32_SkColorType, kPremul_SkAlphaType, std::move(cs));
}
/** Creates SkImageInfo from integral dimensions width and height, kN32_SkColorType,
kPremul_SkAlphaType, with SkColorSpace set to nullptr.
If SkImageInfo is part of drawing source: SkColorSpace defaults to sRGB, mapping
into SkSurface SkColorSpace.
Parameters are not validated to see if their values are legal, or that the
combination is supported.
@param size width and height, each must be zero or greater
@return created SkImageInfo
*/
static SkImageInfo MakeN32Premul(const SkISize& size) {
return MakeN32Premul(size.width(), size.height());
}
/** Creates SkImageInfo from integral dimensions width and height, kAlpha_8_SkColorType,
kPremul_SkAlphaType, with SkColorSpace set to nullptr.
@param width pixel column count; must be zero or greater
@param height pixel row count; must be zero or greater
@return created SkImageInfo
*/
static SkImageInfo MakeA8(int width, int height) {
return Make(width, height, kAlpha_8_SkColorType, kPremul_SkAlphaType, nullptr);
}
/** Creates SkImageInfo from integral dimensions width and height, kUnknown_SkColorType,
kUnknown_SkAlphaType, with SkColorSpace set to nullptr.
Returned SkImageInfo as part of source does not draw, and as part of destination
can not be drawn to.
@param width pixel column count; must be zero or greater
@param height pixel row count; must be zero or greater
@return created SkImageInfo
*/
static SkImageInfo MakeUnknown(int width, int height) {
return Make(width, height, kUnknown_SkColorType, kUnknown_SkAlphaType, nullptr);
}
/** Creates SkImageInfo from integral dimensions width and height set to zero,
kUnknown_SkColorType, kUnknown_SkAlphaType, with SkColorSpace set to nullptr.
Returned SkImageInfo as part of source does not draw, and as part of destination
can not be drawn to.
@return created SkImageInfo
*/
static SkImageInfo MakeUnknown() {
return MakeUnknown(0, 0);
}
int width() const { return fWidth; }
int height() const { return fHeight; }
/** Returns pixel count in each row.
@return pixel width
*/
int width() const { return fDimensions.width(); }
/** Returns pixel row count.
@return pixel height
*/
int height() const { return fDimensions.height(); }
/** Returns SkColorType, one of:
kUnknown_SkColorType, kAlpha_8_SkColorType, kRGB_565_SkColorType,
kARGB_4444_SkColorType, kRGBA_8888_SkColorType, kRGB_888x_SkColorType,
kBGRA_8888_SkColorType, kRGBA_1010102_SkColorType, kRGB_101010x_SkColorType,
kGray_8_SkColorType, kRGBA_F16_SkColorType.
@return SkColorType
*/
SkColorType colorType() const { return fColorType; }
/** Returns SkAlphaType, one of:
kUnknown_SkAlphaType, kOpaque_SkAlphaType, kPremul_SkAlphaType,
kUnpremul_SkAlphaType.
@return SkAlphaType
*/
SkAlphaType alphaType() const { return fAlphaType; }
/** Returns SkColorSpace, the range of colors. The reference count of
SkColorSpace is unchanged. The returned SkColorSpace is immutable.
@return SkColorSpace, or nullptr
*/
SkColorSpace* colorSpace() const { return fColorSpace.get(); }
/** Returns smart pointer to SkColorSpace, the range of colors. The smart pointer
tracks the number of objects sharing this SkColorSpace reference so the memory
is released when the owners destruct.
The returned SkColorSpace is immutable.
@return SkColorSpace wrapped in a smart pointer
*/
sk_sp<SkColorSpace> refColorSpace() const { return fColorSpace; }
bool isEmpty() const { return fWidth <= 0 || fHeight <= 0; }
/** Returns if SkImageInfo describes an empty area of pixels by checking if either
width or height is zero or smaller.
@return true if either dimension is zero or smaller
*/
bool isEmpty() const { return fDimensions.isEmpty(); }
/** Returns true if SkAlphaType is set to hint that all pixels are opaque; their
alpha value is implicitly or explicitly 1.0. If true, and all pixels are
not opaque, Skia may draw incorrectly.
Does not check if SkColorType allows alpha, or if any pixel value has
transparency.
@return true if SkAlphaType is kOpaque_SkAlphaType
*/
bool isOpaque() const {
return SkAlphaTypeIsOpaque(fAlphaType);
}
SkISize dimensions() const { return SkISize::Make(fWidth, fHeight); }
SkIRect bounds() const { return SkIRect::MakeWH(fWidth, fHeight); }
/** Returns SkISize { width(), height() }.
@return integral size of width() and height()
*/
SkISize dimensions() const { return fDimensions; }
/** Returns SkIRect { 0, 0, width(), height() }.
@return integral rectangle from origin to width() and height()
*/
SkIRect bounds() const { return SkIRect::MakeSize(fDimensions); }
/** Returns true if associated SkColorSpace is not nullptr, and SkColorSpace gamma
is approximately the same as sRGB.
This includes the
@return true if SkColorSpace gamma is approximately the same as sRGB
*/
bool gammaCloseToSRGB() const {
return fColorSpace && fColorSpace->gammaCloseToSRGB();
}
/**
* Return a new ImageInfo with the same colortype and alphatype as this info,
* but with the specified width and height.
*/
/** Creates SkImageInfo with the same SkColorType, SkColorSpace, and SkAlphaType,
with dimensions set to width and height.
@param newWidth pixel column count; must be zero or greater
@param newHeight pixel row count; must be zero or greater
@return created SkImageInfo
*/
SkImageInfo makeWH(int newWidth, int newHeight) const {
return Make(newWidth, newHeight, fColorType, fAlphaType, fColorSpace);
}
/** Creates SkImageInfo with same SkColorType, SkColorSpace, width, and height,
with SkAlphaType set to newAlphaType.
Created SkImageInfo contains newAlphaType even if it is incompatible with
SkColorType, in which case SkAlphaType in SkImageInfo is ignored.
@param newAlphaType one of:
kUnknown_SkAlphaType, kOpaque_SkAlphaType, kPremul_SkAlphaType,
kUnpremul_SkAlphaType
@return created SkImageInfo
*/
SkImageInfo makeAlphaType(SkAlphaType newAlphaType) const {
return Make(fWidth, fHeight, fColorType, newAlphaType, fColorSpace);
return Make(this->width(), this->height(), fColorType, newAlphaType, fColorSpace);
}
/** Creates SkImageInfo with same SkAlphaType, SkColorSpace, width, and height,
with SkColorType set to newColorType.
@param newColorType one of:
kUnknown_SkColorType, kAlpha_8_SkColorType, kRGB_565_SkColorType,
kARGB_4444_SkColorType, kRGBA_8888_SkColorType, kRGB_888x_SkColorType,
kBGRA_8888_SkColorType, kRGBA_1010102_SkColorType, kRGB_101010x_SkColorType,
kGray_8_SkColorType, kRGBA_F16_SkColorType
@return created SkImageInfo
*/
SkImageInfo makeColorType(SkColorType newColorType) const {
return Make(fWidth, fHeight, newColorType, fAlphaType, fColorSpace);
return Make(this->width(), this->height(), newColorType, fAlphaType, fColorSpace);
}
/** Creates SkImageInfo with same SkAlphaType, SkColorType, width, and height,
with SkColorSpace set to cs.
@param cs range of colors; may be nullptr
@return created SkImageInfo
*/
SkImageInfo makeColorSpace(sk_sp<SkColorSpace> cs) const {
return Make(fWidth, fHeight, fColorType, fAlphaType, std::move(cs));
return Make(this->width(), this->height(), fColorType, fAlphaType, std::move(cs));
}
/** Returns number of bytes per pixel required by SkColorType.
Returns zero if colorType( is kUnknown_SkColorType.
@return bytes in pixel
*/
int bytesPerPixel() const;
/** Returns bit shift converting row bytes to row pixels.
Returns zero for kUnknown_SkColorType.
@return one of: 0, 1, 2, 3; left shift to convert pixels to bytes
*/
int shiftPerPixel() const;
uint64_t minRowBytes64() const {
return sk_64_mul(fWidth, this->bytesPerPixel());
}
/** Returns minimum bytes per row, computed from pixel width() and SkColorType, which
specifies bytesPerPixel(). SkBitmap maximum value for row bytes must fit
in 31 bits.
@return width() times bytesPerPixel() as unsigned 64-bit integer
*/
uint64_t minRowBytes64() const { return sk_64_mul(this->width(), this->bytesPerPixel()); }
/** Returns minimum bytes per row, computed from pixel width() and SkColorType, which
specifies bytesPerPixel(). SkBitmap maximum value for row bytes must fit
in 31 bits.
@return width() times bytesPerPixel() as signed 32-bit integer
*/
size_t minRowBytes() const {
uint64_t minRowBytes = this->minRowBytes64();
if (!sk_64_isS32(minRowBytes)) {
if (!SkTFitsIn<int32_t>(minRowBytes)) {
return 0;
}
return sk_64_asS32(minRowBytes);
return SkTo<int32_t>(minRowBytes);
}
/** Returns byte offset of pixel from pixel base address.
Asserts in debug build if x or y is outside of bounds. Does not assert if
rowBytes is smaller than minRowBytes(), even though result may be incorrect.
@param x column index, zero or greater, and less than width()
@param y row index, zero or greater, and less than height()
@param rowBytes size of pixel row or larger
@return offset within pixel array
*/
size_t computeOffset(int x, int y, size_t rowBytes) const;
/** Compares SkImageInfo with other, and returns true if width, height, SkColorType,
SkAlphaType, and SkColorSpace are equivalent.
@param other SkImageInfo to compare
@return true if SkImageInfo equals other
*/
bool operator==(const SkImageInfo& other) const {
return fWidth == other.fWidth && fHeight == other.fHeight &&
return fDimensions == other.fDimensions &&
fColorType == other.fColorType && fAlphaType == other.fAlphaType &&
SkColorSpace::Equals(fColorSpace.get(), other.fColorSpace.get());
}
/** Compares SkImageInfo with other, and returns true if width, height, SkColorType,
SkAlphaType, and SkColorSpace are not equivalent.
@param other SkImageInfo to compare
@return true if SkImageInfo is not equal to other
*/
bool operator!=(const SkImageInfo& other) const {
return !(*this == other);
}
void unflatten(SkReadBuffer& buffer);
void flatten(SkWriteBuffer& buffer) const;
/** Returns storage required by pixel array, given SkImageInfo dimensions, SkColorType,
and rowBytes. rowBytes is assumed to be at least as large as minRowBytes().
/**
* Returns the size (in bytes) of the image buffer that this info needs, given the specified
* rowBytes. The rowBytes must be >= this->minRowBytes().
*
* if (height == 0) {
* return 0;
* } else {
* return (height - 1) * rowBytes + width * bytes_per_pixel;
* }
*
* If the calculation overflows this returns SK_MaxSizeT
*/
Returns zero if height is zero.
Returns SIZE_MAX if answer exceeds the range of size_t.
@param rowBytes size of pixel row or larger
@return memory required by pixel buffer
*/
size_t computeByteSize(size_t rowBytes) const;
/**
* Returns the minimum size (in bytes) of the image buffer that this info needs.
* If the calculation overflows, or if the height is 0, this returns 0.
*/
/** Returns storage required by pixel array, given SkImageInfo dimensions, and
SkColorType. Uses minRowBytes() to compute bytes for pixel row.
Returns zero if height is zero.
Returns SIZE_MAX if answer exceeds the range of size_t.
@return least memory required by pixel buffer
*/
size_t computeMinByteSize() const {
return this->computeByteSize(this->minRowBytes());
}
// Returns true if the result of computeByteSize (or computeMinByteSize) overflowed
/** Returns true if byteSize equals SIZE_MAX. computeByteSize() and
computeMinByteSize() return SIZE_MAX if size_t can not hold buffer size.
@param byteSize result of computeByteSize() or computeMinByteSize()
@return true if computeByteSize() or computeMinByteSize() result exceeds size_t
*/
static bool ByteSizeOverflowed(size_t byteSize) {
return SK_MaxSizeT == byteSize;
return SIZE_MAX == byteSize;
}
/** Returns true if rowBytes is smaller than width times pixel size.
@param rowBytes size of pixel row or larger
@return true if rowBytes is large enough to contain pixel row
*/
bool validRowBytes(size_t rowBytes) const {
uint64_t minRB = sk_64_mul(fWidth, this->bytesPerPixel());
return rowBytes >= minRB;
return rowBytes >= this->minRowBytes64();
}
/** Creates an empty SkImageInfo with kUnknown_SkColorType, kUnknown_SkAlphaType,
a width and height of zero, and no SkColorSpace.
*/
void reset() {
fColorSpace = nullptr;
fWidth = 0;
fHeight = 0;
fDimensions = {0, 0};
fColorType = kUnknown_SkColorType;
fAlphaType = kUnknown_SkAlphaType;
}
/** Asserts if internal values are illegal or inconsistent. Only available if
SK_DEBUG is defined at compile time.
*/
SkDEBUGCODE(void validate() const;)
private:
sk_sp<SkColorSpace> fColorSpace;
int fWidth;
int fHeight;
SkISize fDimensions;
SkColorType fColorType;
SkAlphaType fAlphaType;
SkImageInfo(int width, int height, SkColorType ct, SkAlphaType at, sk_sp<SkColorSpace> cs)
: fColorSpace(std::move(cs))
, fWidth(width)
, fHeight(height)
, fDimensions{width, height}
, fColorType(ct)
, fAlphaType(at)
{}

Просмотреть файл

@ -0,0 +1,195 @@
/*
* Copyright 2015 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef SkLights_DEFINED
#define SkLights_DEFINED
#include "SkPoint3.h"
#include "SkRefCnt.h"
#include "../private/SkTArray.h"
class SkColorSpaceXformer;
class SkReadBuffer;
class SkWriteBuffer;
/** \class SkLights
SkLights encapsulates a set of directional, point and ambient lights for use with the
SkLightingShader.
*/
class SK_API SkLights : public SkRefCnt {
public:
class Light {
public:
enum LightType {
kDirectional_LightType,
kPoint_LightType
};
Light(const Light& other)
: fType(other.fType)
, fColor(other.fColor)
, fDirOrPos(other.fDirOrPos)
, fIntensity(other.fIntensity) {}
Light(Light&& other)
: fType(other.fType)
, fColor(other.fColor)
, fDirOrPos(other.fDirOrPos)
, fIntensity(other.fIntensity) {}
static Light MakeDirectional(const SkColor3f& color, const SkVector3& dir) {
Light light(kDirectional_LightType, color, dir, 0.0f);
if (!light.fDirOrPos.normalize()) {
light.fDirOrPos.set(0.0f, 0.0f, 1.0f);
}
return light;
}
static Light MakePoint(const SkColor3f& color, const SkPoint3& pos, SkScalar intensity) {
return Light(kPoint_LightType, color, pos, intensity);
}
LightType type() const { return fType; }
const SkColor3f& color() const { return fColor; }
const SkVector3& dir() const {
SkASSERT(kDirectional_LightType == fType);
return fDirOrPos;
}
const SkPoint3& pos() const {
SkASSERT(kPoint_LightType == fType);
return fDirOrPos;
}
SkScalar intensity() const {
SkASSERT(kPoint_LightType == fType);
return fIntensity;
}
Light& operator=(const Light& other) {
if (this == &other) {
return *this;
}
fType = other.fType;
fColor = other.fColor;
fDirOrPos = other.fDirOrPos;
fIntensity = other.fIntensity;
return *this;
}
bool operator==(const Light& other) {
return (fType == other.fType) &&
(fColor == other.fColor) &&
(fDirOrPos == other.fDirOrPos) &&
(fIntensity == other.fIntensity);
}
bool operator!=(const Light& other) { return !(this->operator==(other)); }
private:
friend class SkLights;
Light(LightType type, const SkColor3f& color, const SkVector3& dirOrPos,
SkScalar intensity)
: fType(type)
, fColor(color)
, fDirOrPos(dirOrPos)
, fIntensity(intensity) {}
LightType fType;
SkColor3f fColor; // linear (unpremul) color. Range is 0..1 in each channel.
SkVector3 fDirOrPos; // For directional lights, holds the direction towards the
// light (+Z is out of the screen).
// If degenerate, it will be replaced with (0, 0, 1).
// For point lights, holds location of point light
SkScalar fIntensity; // For point lights, dictates the light intensity.
// Simply a multiplier to the final light output value.
};
class Builder {
public:
Builder() : fLights(new SkLights) {}
void add(const Light& light) {
if (fLights) {
fLights->fLights.push_back(light);
}
}
void add(Light&& light) {
if (fLights) {
fLights->fLights.push_back(std::move(light));
}
}
void setAmbientLightColor(const SkColor3f& color) {
if (fLights) {
fLights->fAmbientLightColor = color;
}
}
sk_sp<SkLights> finish() {
return std::move(fLights);
}
private:
sk_sp<SkLights> fLights;
};
/** Returns number of lights not including the ambient light.
@return number of lights not including the ambient light
*/
int numLights() const { return fLights.count(); }
/** Returns the index-th light.
@param index the index of the desired light
@return the index-th light
*/
const Light& light(int index) const { return fLights[index]; }
/** Returns the ambient light.
@return the ambient light
*/
const SkColor3f& ambientLightColor() const {
return fAmbientLightColor;
}
/**
* Recreate an SkLights object that was serialized into a buffer.
*
* @param SkReadBuffer Serialized blob data.
* @return A new SkLights representing the serialized data, or NULL if the buffer is
* invalid.
*/
static sk_sp<SkLights> MakeFromBuffer(SkReadBuffer& buf);
/**
* Serialize to a buffer.
*
* @param buffer the write buffer to write out to
*/
void flatten(SkWriteBuffer& buf) const;
private:
friend class SkLightingShaderImpl;
SkLights() : fAmbientLightColor(SkColor3f::Make(0.0f, 0.0f, 0.0f)) {}
sk_sp<SkLights> makeColorSpace(SkColorSpaceXformer* xformer) const;
SkTArray<Light> fLights;
SkColor3f fAmbientLightColor;
typedef SkRefCnt INHERITED;
};
#endif

Просмотреть файл

@ -9,6 +9,10 @@
#define SkMallocPixelRef_DEFINED
#include "SkPixelRef.h"
#include "SkRefCnt.h"
#include "SkTypes.h"
class SkData;
struct SkImageInfo;
/** We explicitly use the same allocator for our pixels that SkMask does,
so that we can freely assign memory allocated by one class to the other.

Просмотреть файл

@ -8,10 +8,13 @@
#ifndef SkMaskFilter_DEFINED
#define SkMaskFilter_DEFINED
#include "SkBlurTypes.h"
#include "SkCoverageMode.h"
#include "SkFlattenable.h"
#include "SkScalar.h"
class SkMatrix;
struct SkRect;
class SkString;
/** \class SkMaskFilter
@ -21,6 +24,15 @@ class SkString;
*/
class SK_API SkMaskFilter : public SkFlattenable {
public:
/** Create a blur maskfilter.
* @param style The SkBlurStyle to use
* @param sigma Standard deviation of the Gaussian blur to apply. Must be > 0.
* @param respectCTM if true the blur's sigma is modified by the CTM.
* @return The new blur maskfilter
*/
static sk_sp<SkMaskFilter> MakeBlur(SkBlurStyle style, SkScalar sigma,
bool respectCTM = true);
/**
* Construct a maskfilter whose effect is to first apply the inner filter and then apply
* the outer filter to the result of the inner's. Returns nullptr on failure.
@ -33,10 +45,29 @@ public:
static sk_sp<SkMaskFilter> MakeCombine(sk_sp<SkMaskFilter> filterA, sk_sp<SkMaskFilter> filterB,
SkCoverageMode mode);
sk_sp<SkMaskFilter> makeWithLocalMatrix(const SkMatrix&) const;
/**
* Construct a maskfilter with an additional transform.
*
* Note: unlike shader local matrices, this transform composes next to the CTM.
*
* TotalMatrix = CTM x MaskFilterMatrix x (optional/downstream) ShaderLocalMatrix
*/
sk_sp<SkMaskFilter> makeWithMatrix(const SkMatrix&) const;
SK_TO_STRING_PUREVIRT()
SK_DEFINE_FLATTENABLE_TYPE(SkMaskFilter)
static SkFlattenable::Type GetFlattenableType() {
return kSkMaskFilter_Type;
}
SkFlattenable::Type getFlattenableType() const override {
return kSkMaskFilter_Type;
}
static sk_sp<SkMaskFilter> Deserialize(const void* data, size_t size,
const SkDeserialProcs* procs = nullptr) {
return sk_sp<SkMaskFilter>(static_cast<SkMaskFilter*>(
SkFlattenable::Deserialize(
kSkMaskFilter_Type, data, size, procs).release()));
}
private:
static void InitializeFlattenables();

Просмотреть файл

@ -1,4 +1,3 @@
/*
* Copyright 2006 The Android Open Source Project
*
@ -6,7 +5,6 @@
* found in the LICENSE file.
*/
#ifndef SkMath_DEFINED
#define SkMath_DEFINED
@ -14,23 +12,6 @@
// 64bit -> 32bit utilities
/**
* Return true iff the 64bit value can exactly be represented in signed 32bits
*/
static inline bool sk_64_isS32(int64_t value) {
return (int32_t)value == value;
}
/**
* Return the 64bit argument as signed 32bits, asserting in debug that the arg
* exactly fits in signed 32bits. In the release build, no checks are preformed
* and the return value if the arg does not fit is undefined.
*/
static inline int32_t sk_64_asS32(int64_t value) {
SkASSERT(sk_64_isS32(value));
return (int32_t)value;
}
// Handy util that can be passed two ints, and will automatically promote to
// 64bits before the multiply, so the caller doesn't have to remember to cast
// e.g. (int64_t)a * b;
@ -40,34 +21,6 @@ static inline int64_t sk_64_mul(int64_t a, int64_t b) {
///////////////////////////////////////////////////////////////////////////////
/**
* Computes numer1 * numer2 / denom in full 64 intermediate precision.
* It is an error for denom to be 0. There is no special handling if
* the result overflows 32bits.
*/
static inline int32_t SkMulDiv(int32_t numer1, int32_t numer2, int32_t denom) {
SkASSERT(denom);
int64_t tmp = sk_64_mul(numer1, numer2) / denom;
return sk_64_asS32(tmp);
}
/**
* Return the integer square root of value, with a bias of bitBias
*/
int32_t SkSqrtBits(int32_t value, int bitBias);
/** Return the integer square root of n, treated as a SkFixed (16.16)
*/
#define SkSqrt32(n) SkSqrtBits(n, 15)
/**
* Returns (value < 0 ? 0 : value) efficiently (i.e. no compares or branches)
*/
static inline int SkClampPos(int value) {
return value & ~(value >> 31);
}
/** Given an integer and a positive (max) integer, return the value
* pinned against 0 and max, inclusive.
* @param value The value we want returned pinned between [0...max]
@ -119,26 +72,4 @@ static inline U8CPU SkMulDiv255Round(U16CPU a, U16CPU b) {
return (prod + (prod >> 8)) >> 8;
}
/**
* Stores numer/denom and numer%denom into div and mod respectively.
*/
template <typename In, typename Out>
inline void SkTDivMod(In numer, In denom, Out* div, Out* mod) {
#ifdef SK_CPU_ARM32
// If we wrote this as in the else branch, GCC won't fuse the two into one
// divmod call, but rather a div call followed by a divmod. Silly! This
// version is just as fast as calling __aeabi_[u]idivmod manually, but with
// prettier code.
//
// This benches as around 2x faster than the code in the else branch.
const In d = numer/denom;
*div = static_cast<Out>(d);
*mod = static_cast<Out>(numer-d*denom);
#else
// On x86 this will just be a single idiv.
*div = static_cast<Out>(numer/denom);
*mod = static_cast<Out>(numer%denom);
#endif
}
#endif

Просмотреть файл

@ -5,10 +5,21 @@
* found in the LICENSE file.
*/
/* Generated by tools/bookmaker from include/core/SkMatrix.h and docs/SkMatrix_Reference.bmh
on 2018-09-13 13:59:55. Additional documentation and examples can be found at:
https://skia.org/user/api/SkMatrix_Reference
You may edit either file directly. Structural changes to public interfaces require
editing both files. After editing docs/SkMatrix_Reference.bmh, run:
bookmaker -b docs -i include/core/SkMatrix.h -p
to create an updated version of this file.
*/
#ifndef SkMatrix_DEFINED
#define SkMatrix_DEFINED
#include "../private/SkMacros.h"
#include "../private/SkTo.h"
#include "SkRect.h"
struct SkRSXform;
@ -91,8 +102,8 @@ public:
@param skewY vertical skew factor
@param scaleY vertical scale factor
@param transY vertical translation
@param pers0 input x perspective factor
@param pers1 input y perspective factor
@param pers0 input x-axis perspective factor
@param pers1 input y-axis perspective factor
@param pers2 perspective scale factor
@return SkMatrix constructed from parameters
*/
@ -109,11 +120,11 @@ public:
Used to identify the complexity of SkMatrix, to optimize performance.
*/
enum TypeMask {
kIdentity_Mask = 0, //!< all bits clear if SkMatrix is identity
kTranslate_Mask = 0x01, //!< set if SkMatrix has translation
kScale_Mask = 0x02, //!< set if SkMatrix has x or y scale
kAffine_Mask = 0x04, //!< set if SkMatrix skews or rotates
kPerspective_Mask = 0x08, //!< set if SkMatrix has perspective
kIdentity_Mask = 0, //!< identity SkMatrix; all bits clear
kTranslate_Mask = 0x01, //!< translation SkMatrix
kScale_Mask = 0x02, //!< scale SkMatrix
kAffine_Mask = 0x04, //!< skew or rotate SkMatrix
kPerspective_Mask = 0x08, //!< perspective SkMatrix
};
/** Returns a bit field describing the transformations the matrix may
@ -168,7 +179,7 @@ public:
bool isTranslate() const { return !(this->getType() & ~(kTranslate_Mask)); }
/** Returns true SkMatrix maps SkRect to another SkRect. If true, SkMatrix is identity,
or scales, or rotates a multiple of 90 degrees, or mirrors in x or y. In all
or scales, or rotates a multiple of 90 degrees, or mirrors on axes. In all
cases, SkMatrix may also have translation. SkMatrix form is either:
| scale-x 0 translate-x |
@ -196,7 +207,7 @@ public:
}
/** Returns true SkMatrix maps SkRect to another SkRect. If true, SkMatrix is identity,
or scales, or rotates a multiple of 90 degrees, or mirrors in x or y. In all
or scales, or rotates a multiple of 90 degrees, or mirrors on axes. In all
cases, SkMatrix may also have translation. SkMatrix form is either:
| scale-x 0 translate-x |
@ -241,7 +252,7 @@ public:
Describes that the SkMatrix makes rendering with and without the matrix are
visually alike; a transformed circle remains a circle. Mathematically, this is
referred to as similarity of a Euclidean_Space, or a similarity transformation.
referred to as similarity of a Euclidean space, or a similarity transformation.
Preserves right angles, keeping the arms of the angle equal lengths.
@ -263,34 +274,28 @@ public:
*/
bool preservesRightAngles(SkScalar tol = SK_ScalarNearlyZero) const;
/** \enum
SkMatrix organizes its values in row order. These members correspond to
/** SkMatrix organizes its values in row order. These members correspond to
each value in SkMatrix.
*/
enum {
kMScaleX, //!< horizontal scale factor
kMSkewX, //!< horizontal skew factor
kMTransX, //!< horizontal translation
kMSkewY, //!< vertical skew factor
kMScaleY, //!< vertical scale factor
kMTransY, //!< vertical translation
kMPersp0, //!< input x perspective factor
kMPersp1, //!< input y perspective factor
kMPersp2, //!< perspective bias
};
static constexpr int kMScaleX = 0; //!< horizontal scale factor
static constexpr int kMSkewX = 1; //!< horizontal skew factor
static constexpr int kMTransX = 2; //!< horizontal translation
static constexpr int kMSkewY = 3; //!< vertical skew factor
static constexpr int kMScaleY = 4; //!< vertical scale factor
static constexpr int kMTransY = 5; //!< vertical translation
static constexpr int kMPersp0 = 6; //!< input x perspective factor
static constexpr int kMPersp1 = 7; //!< input y perspective factor
static constexpr int kMPersp2 = 8; //!< perspective bias
/** \enum
Affine arrays are in column major order to match the matrix used by
/** Affine arrays are in column major order to match the matrix used by
PDF and XPS.
*/
enum {
kAScaleX, //!< horizontal scale factor
kASkewY, //!< vertical skew factor
kASkewX, //!< horizontal skew factor
kAScaleY, //!< vertical scale factor
kATransX, //!< horizontal translation
kATransY, //!< vertical translation
};
static constexpr int kAScaleX = 0; //!< horizontal scale factor
static constexpr int kASkewY = 1; //!< vertical skew factor
static constexpr int kASkewX = 2; //!< horizontal skew factor
static constexpr int kAScaleY = 3; //!< vertical scale factor
static constexpr int kATransX = 4; //!< horizontal translation
static constexpr int kATransY = 5; //!< vertical translation
/** Returns one matrix value. Asserts if index is out of range and SK_DEBUG is
defined.
@ -316,59 +321,59 @@ public:
return fMat[index];
}
/** Returns scale factor multiplied by x input, contributing to x output.
/** Returns scale factor multiplied by x-axis input, contributing to x-axis output.
With mapPoints(), scales SkPoint along the x-axis.
@return horizontal scale factor
*/
SkScalar getScaleX() const { return fMat[kMScaleX]; }
/** Returns scale factor multiplied by y input, contributing to y output.
/** Returns scale factor multiplied by y-axis input, contributing to y-axis output.
With mapPoints(), scales SkPoint along the y-axis.
@return vertical scale factor
*/
SkScalar getScaleY() const { return fMat[kMScaleY]; }
/** Returns scale factor multiplied by x input, contributing to y output.
/** Returns scale factor multiplied by x-axis input, contributing to y-axis output.
With mapPoints(), skews SkPoint along the y-axis.
Skew x and y together can rotate SkPoint.
Skewing both axes can rotate SkPoint.
@return vertical skew factor
*/
SkScalar getSkewY() const { return fMat[kMSkewY]; }
/** Returns scale factor multiplied by y input, contributing to x output.
/** Returns scale factor multiplied by y-axis input, contributing to x-axis output.
With mapPoints(), skews SkPoint along the x-axis.
Skew x and y together can rotate SkPoint.
Skewing both axes can rotate SkPoint.
@return horizontal scale factor
*/
SkScalar getSkewX() const { return fMat[kMSkewX]; }
/** Returns translation contributing to x output.
/** Returns translation contributing to x-axis output.
With mapPoints(), moves SkPoint along the x-axis.
@return horizontal translation factor
*/
SkScalar getTranslateX() const { return fMat[kMTransX]; }
/** Returns translation contributing to y output.
/** Returns translation contributing to y-axis output.
With mapPoints(), moves SkPoint along the y-axis.
@return vertical translation factor
*/
SkScalar getTranslateY() const { return fMat[kMTransY]; }
/** Returns factor scaling input x relative to input y.
/** Returns factor scaling input x-axis relative to input y-axis.
@return input x perspective factor
@return input x-axis perspective factor
*/
SkScalar getPerspX() const { return fMat[kMPersp0]; }
/** Returns factor scaling input y relative to input x.
/** Returns factor scaling input y-axis relative to input x-axis.
@return input y perspective factor
@return input y-axis perspective factor
*/
SkScalar getPerspY() const { return fMat[kMPersp1]; }
@ -437,15 +442,15 @@ public:
*/
void setTranslateY(SkScalar v) { this->set(kMTransY, v); }
/** Sets input x perspective factor, which causes mapXY() to vary input x inversely
proportional to input y.
/** Sets input x-axis perspective factor, which causes mapXY() to vary input x-axis values
inversely proportional to input y-axis values.
@param v perspective factor
*/
void setPerspX(SkScalar v) { this->set(kMPersp0, v); }
/** Sets input y perspective factor, which causes mapXY() to vary input y inversely
proportional to input x.
/** Sets input y-axis perspective factor, which causes mapXY() to vary input y-axis values
inversely proportional to input x-axis values.
@param v perspective factor
*/
@ -463,8 +468,8 @@ public:
@param skewY vertical skew factor to store
@param scaleY vertical scale factor to store
@param transY vertical translation to store
@param persp0 input x perspective factor to store
@param persp1 input y perspective factor to store
@param persp0 input x-axis values perspective factor to store
@param persp1 input y-axis values perspective factor to store
@param persp2 perspective scale factor to store
*/
void setAll(SkScalar scaleX, SkScalar skewX, SkScalar transX,
@ -586,10 +591,10 @@ public:
Vector (sinValue, cosValue) describes the angle of rotation relative to (0, 1).
Vector length specifies scale.
@param sinValue rotation vector x component
@param cosValue rotation vector y component
@param px pivot x
@param py pivot y
@param sinValue rotation vector x-axis component
@param cosValue rotation vector y-axis component
@param px pivot x-axis
@param py pivot y-axis
*/
void setSinCos(SkScalar sinValue, SkScalar cosValue,
SkScalar px, SkScalar py);
@ -599,8 +604,8 @@ public:
Vector (sinValue, cosValue) describes the angle of rotation relative to (0, 1).
Vector length specifies scale.
@param sinValue rotation vector x component
@param cosValue rotation vector y component
@param sinValue rotation vector x-axis component
@param cosValue rotation vector y-axis component
*/
void setSinCos(SkScalar sinValue, SkScalar cosValue);
@ -666,8 +671,8 @@ public:
Matrix * T(dx, dy) = | D E F | | 0 1 dy | = | D E D*dx+E*dy+F |
| G H I | | 0 0 1 | | G H G*dx+H*dy+I |
@param dx x translation before applying SkMatrix
@param dy y translation before applying SkMatrix
@param dx x-axis translation before applying SkMatrix
@param dy y-axis translation before applying SkMatrix
*/
void preTranslate(SkScalar dx, SkScalar dy);
@ -861,8 +866,8 @@ public:
T(dx, dy) * Matrix = | 0 1 dy | | M N O | = | M+dy*P N+dy*Q O+dy*R |
| 0 0 1 | | P Q R | | P Q R |
@param dx x translation after applying SkMatrix
@param dy y translation after applying SkMatrix
@param dx x-axis translation after applying SkMatrix
@param dy y-axis translation after applying SkMatrix
*/
void postTranslate(SkScalar dx, SkScalar dy);
@ -915,7 +920,8 @@ public:
*/
void postScale(SkScalar sx, SkScalar sy);
/** Sets SkMatrix to SkMatrix constructed from scaling by (1/divx, 1/divy) about pivot point (px, py), multiplied by SkMatrix.
/** Sets SkMatrix to SkMatrix constructed from scaling by (1/divx, 1/divy),
about pivot point (px, py), multiplied by SkMatrix.
Returns false if either divx or divy is zero.
@ -1075,29 +1081,10 @@ public:
how SkMatrix maps to the side or center of the destination SkRect.
*/
enum ScaleToFit {
/** Computes SkMatrix that scales in x and y independently, so that source SkRect is
mapped to completely fill destination SkRect. The aspect ratio of source SkRect
may change.
*/
kFill_ScaleToFit,
/** Computes SkMatrix that maintains source SkRect aspect ratio, mapping source SkRect
width or height to destination SkRect. Aligns mapping to left and top edges
of destination SkRect.
*/
kStart_ScaleToFit,
/** Computes SkMatrix that maintains source SkRect aspect ratio, mapping source SkRect
width or height to destination SkRect. Aligns mapping to center of destination
SkRect.
*/
kCenter_ScaleToFit,
/** Computes SkMatrix that maintains source SkRect aspect ratio, mapping source SkRect
width or height to destination SkRect. Aligns mapping to right and bottom
edges of destination SkRect.
*/
kEnd_ScaleToFit,
kFill_ScaleToFit, //!< scales in x and y to fill destination SkRect
kStart_ScaleToFit, //!< scales and aligns to left and top
kCenter_ScaleToFit, //!< scales and aligns to center
kEnd_ScaleToFit, //!< scales and aligns to right and bottom
};
/** Sets SkMatrix to scale and translate src SkRect to dst SkRect. stf selects whether
@ -1303,8 +1290,8 @@ public:
Matrix * pt = |D E F| |y| = |Ax+By+C Dx+Ey+F Gx+Hy+I| = ------- , -------
|G H I| |1| Gx+Hy+I Gx+Hy+I
@param x x-coordinate of SkPoint to map
@param y y-coordinate of SkPoint to map
@param x x-axis value of SkPoint to map
@param y y-axis value of SkPoint to map
@param result storage for mapped SkPoint
*/
void mapXY(SkScalar x, SkScalar y, SkPoint* result) const {
@ -1324,8 +1311,8 @@ public:
Matrix * pt = |D E F| |y| = |Ax+By+C Dx+Ey+F Gx+Hy+I| = ------- , -------
|G H I| |1| Gx+Hy+I Gx+Hy+I
@param x x-coordinate of SkPoint to map
@param y y-coordinate of SkPoint to map
@param x x-axis value of SkPoint to map
@param y y-axis value of SkPoint to map
@return mapped SkPoint
*/
SkPoint mapXY(SkScalar x, SkScalar y) const {
@ -1403,8 +1390,8 @@ public:
Matrix * vec = |D E 0| |dy| = |A*dx+B*dy D*dx+E*dy G*dx+H*dy+I| = ----------- , -----------
|G H I| | 1| G*dx+H*dy+I G*dx+*dHy+I
@param dx x-coordinate of vector to map
@param dy y-coordinate of vector to map
@param dx x-axis value of vector to map
@param dy y-axis value of vector to map
@param result storage for mapped vector
*/
void mapVector(SkScalar dx, SkScalar dy, SkVector* result) const {
@ -1425,8 +1412,8 @@ public:
Matrix * vec = |D E 0| |dy| = |A*dx+B*dy D*dx+E*dy G*dx+H*dy+I| = ----------- , -----------
|G H I| | 1| G*dx+H*dy+I G*dx+*dHy+I
@param dx x-coordinate of vector to map
@param dy y-coordinate of vector to map
@param dx x-axis value of vector to map
@param dy y-axis value of vector to map
@return mapped vector
*/
SkVector mapVector(SkScalar dx, SkScalar dy) const {
@ -1458,6 +1445,17 @@ public:
return this->mapRect(rect, *rect);
}
/** Returns bounds of src corners mapped by SkMatrix.
@param src rectangle to map
@return mapped bounds
*/
SkRect mapRect(const SkRect& src) const {
SkRect dst;
(void)this->mapRect(&dst, src);
return dst;
}
/** Maps four corners of rect to dst. SkPoint are mapped by multiplying each
rect corner by SkMatrix. rect corner is processed in this order:
(rect.fLeft, rect.fTop), (rect.fRight, rect.fTop), (rect.fRight, rect.fBottom),
@ -1508,9 +1506,9 @@ public:
*/
SkScalar mapRadius(SkScalar radius) const;
/** Returns true if a unit step in x at some y mapped through SkMatrix can be
represented by a constant vector. Returns true if getType() returns kIdentity_Mask,
or combinations of: kTranslate_Mask, kScale_Mask, and kAffine_Mask.
/** Returns true if a unit step on x-axis at some y-axis value mapped through SkMatrix
can be represented by a constant vector. Returns true if getType() returns
kIdentity_Mask, or combinations of: kTranslate_Mask, kScale_Mask, and kAffine_Mask.
May return true if getType() returns kPerspective_Mask, but only when SkMatrix
does not include rotation or skewing along the y-axis.
@ -1519,11 +1517,11 @@ public:
*/
bool isFixedStepInX() const;
/** Returns vector representing a unit step in x at y mapped through SkMatrix.
/** Returns vector representing a unit step on x-axis at y mapped through SkMatrix.
If isFixedStepInX() is false, returned value is undefined.
@param y position of line parallel to x-axis
@return vector advance of mapped unit step in x
@return vector advance of mapped unit step on x-axis
*/
SkVector fixedStepInX(SkScalar y) const;
@ -1572,14 +1570,6 @@ public:
*/
void dump() const;
/** Creates string representation of SkMatrix. Floating point values
are written with limited precision; it may not be possible to reconstruct
original SkMatrix from output.
@param str storage for string representation of SkMatrix
*/
void toString(SkString* str) const;
/** Returns the minimum scaling factor of SkMatrix by decomposing the scaling and
skewing elements.
Returns -1 if scale factor overflows or SkMatrix contains perspective.
@ -1611,18 +1601,17 @@ public:
/** Decomposes SkMatrix into scale components and whatever remains. Returns false if
SkMatrix could not be decomposed.
Sets scale to portion of SkMatrix that scales in x and y. Sets remaining to SkMatrix
with x and y scaling factored out. remaining may be passed as nullptr
Sets scale to portion of SkMatrix that scale axes. Sets remaining to SkMatrix
with scaling factored out. remaining may be passed as nullptr
to determine if SkMatrix can be decomposed without computing remainder.
Returns true if scale components are found. scale and remaining are
unchanged if SkMatrix contains perspective; scale factors are not finite, or
are nearly zero.
On success
Matrix = scale * Remaining
On success: Matrix = scale * Remaining.
@param scale x and y scaling factors; may be nullptr
@param scale axes scaling factors; may be nullptr
@param remaining SkMatrix without scaling; may be nullptr
@return true if scale can be computed
*/
@ -1722,33 +1711,31 @@ public:
bool isFinite() const { return SkScalarsAreFinite(fMat, 9); }
private:
enum {
/** Set if the matrix will map a rectangle to another rectangle. This
can be true if the matrix is scale-only, or rotates a multiple of
90 degrees.
/** Set if the matrix will map a rectangle to another rectangle. This
can be true if the matrix is scale-only, or rotates a multiple of
90 degrees.
This bit will be set on identity matrices
*/
kRectStaysRect_Mask = 0x10,
This bit will be set on identity matrices
*/
static constexpr int kRectStaysRect_Mask = 0x10;
/** Set if the perspective bit is valid even though the rest of
the matrix is Unknown.
*/
kOnlyPerspectiveValid_Mask = 0x40,
/** Set if the perspective bit is valid even though the rest of
the matrix is Unknown.
*/
static constexpr int kOnlyPerspectiveValid_Mask = 0x40;
kUnknown_Mask = 0x80,
static constexpr int kUnknown_Mask = 0x80;
kORableMasks = kTranslate_Mask |
kScale_Mask |
kAffine_Mask |
kPerspective_Mask,
static constexpr int kORableMasks = kTranslate_Mask |
kScale_Mask |
kAffine_Mask |
kPerspective_Mask;
kAllMasks = kTranslate_Mask |
kScale_Mask |
kAffine_Mask |
kPerspective_Mask |
kRectStaysRect_Mask,
};
static constexpr int kAllMasks = kTranslate_Mask |
kScale_Mask |
kAffine_Mask |
kPerspective_Mask |
kRectStaysRect_Mask;
SkScalar fMat[9];
mutable uint32_t fTypeMask;
@ -1829,9 +1816,9 @@ private:
bool SK_WARN_UNUSED_RESULT invertNonIdentity(SkMatrix* inverse) const;
static bool Poly2Proc(const SkPoint[], SkMatrix*, const SkPoint& scale);
static bool Poly3Proc(const SkPoint[], SkMatrix*, const SkPoint& scale);
static bool Poly4Proc(const SkPoint[], SkMatrix*, const SkPoint& scale);
static bool Poly2Proc(const SkPoint[], SkMatrix*);
static bool Poly3Proc(const SkPoint[], SkMatrix*);
static bool Poly4Proc(const SkPoint[], SkMatrix*);
static void Identity_xy(const SkMatrix&, SkScalar, SkScalar, SkPoint*);
static void Trans_xy(const SkMatrix&, SkScalar, SkScalar, SkPoint*);

Просмотреть файл

@ -11,6 +11,9 @@
#include "SkMatrix.h"
#include "SkScalar.h"
#include <atomic>
#include <cstring>
#ifdef SK_MSCALAR_IS_DOUBLE
#ifdef SK_MSCALAR_IS_FLOAT
#error "can't define MSCALAR both as DOUBLE and FLOAT"
@ -142,7 +145,7 @@ public:
kIdentity_Constructor
};
SkMatrix44(Uninitialized_Constructor) {}
SkMatrix44(Uninitialized_Constructor) {} // ironically, cannot be constexpr
constexpr SkMatrix44(Identity_Constructor)
: fMat{{ 1, 0, 0, 0, },
@ -152,12 +155,11 @@ public:
, fTypeMask(kIdentity_Mask)
{}
SK_ATTR_DEPRECATED("use the constructors that take an enum")
SkMatrix44() { this->setIdentity(); }
constexpr SkMatrix44() : SkMatrix44{kIdentity_Constructor} {}
SkMatrix44(const SkMatrix44& src) {
memcpy(fMat, src.fMat, sizeof(fMat));
fTypeMask = src.fTypeMask;
fTypeMask.store(src.fTypeMask, std::memory_order_relaxed);
}
SkMatrix44(const SkMatrix44& a, const SkMatrix44& b) {
@ -167,7 +169,7 @@ public:
SkMatrix44& operator=(const SkMatrix44& src) {
if (&src != this) {
memcpy(fMat, src.fMat, sizeof(fMat));
fTypeMask = src.fTypeMask;
fTypeMask.store(src.fTypeMask, std::memory_order_relaxed);
}
return *this;
}
@ -210,11 +212,11 @@ public:
* transform.
*/
inline TypeMask getType() const {
if (fTypeMask & kUnknown_Mask) {
fTypeMask = this->computeTypeMask();
if (fTypeMask.load(std::memory_order_relaxed) & kUnknown_Mask) {
fTypeMask.store(this->computeTypeMask(), std::memory_order_relaxed);
}
SkASSERT(!(fTypeMask & kUnknown_Mask));
return (TypeMask)fTypeMask;
return (TypeMask)fTypeMask.load(std::memory_order_relaxed);
}
/**
@ -328,11 +330,11 @@ public:
#endif
/* This sets the top-left of the matrix and clears the translation and
* perspective components (with [3][3] set to 1). mXY is interpreted
* as the matrix entry at col = X, row = Y. */
void set3x3(SkMScalar m00, SkMScalar m01, SkMScalar m02,
SkMScalar m10, SkMScalar m11, SkMScalar m12,
SkMScalar m20, SkMScalar m21, SkMScalar m22);
* perspective components (with [3][3] set to 1). m_ij is interpreted
* as the matrix entry at row = i, col = j. */
void set3x3(SkMScalar m_00, SkMScalar m_10, SkMScalar m_20,
SkMScalar m_01, SkMScalar m_11, SkMScalar m_21,
SkMScalar m_02, SkMScalar m_12, SkMScalar m_22);
void set3x3RowMajorf(const float[]);
void setTranslate(SkMScalar dx, SkMScalar dy, SkMScalar dz);
@ -398,16 +400,6 @@ public:
this->mapScalars(vec, vec);
}
SK_ATTR_DEPRECATED("use mapScalars")
void map(const SkScalar src[4], SkScalar dst[4]) const {
this->mapScalars(src, dst);
}
SK_ATTR_DEPRECATED("use mapScalars")
void map(SkScalar vec[4]) const {
this->mapScalars(vec, vec);
}
#ifdef SK_MSCALAR_IS_DOUBLE
void mapMScalars(const SkMScalar src[4], SkMScalar dst[4]) const;
#elif defined SK_MSCALAR_IS_FLOAT
@ -454,14 +446,12 @@ public:
private:
/* This is indexed by [col][row]. */
SkMScalar fMat[4][4];
mutable unsigned fTypeMask;
SkMScalar fMat[4][4];
mutable std::atomic<unsigned> fTypeMask;
enum {
kUnknown_Mask = 0x80,
static constexpr int kUnknown_Mask = 0x80;
kAllPublic_Masks = 0xF
};
static constexpr int kAllPublic_Masks = 0xF;
void as3x4RowMajorf(float[]) const;
void set3x4RowMajorf(const float[]);
@ -481,12 +471,12 @@ private:
int computeTypeMask() const;
inline void dirtyTypeMask() {
fTypeMask = kUnknown_Mask;
fTypeMask.store(kUnknown_Mask, std::memory_order_relaxed);
}
inline void setTypeMask(int mask) {
SkASSERT(0 == (~(kAllPublic_Masks | kUnknown_Mask) & mask));
fTypeMask = mask;
fTypeMask.store(mask, std::memory_order_relaxed);
}
/**
@ -494,13 +484,12 @@ private:
* we already know that this matrix is identity.
*/
inline bool isTriviallyIdentity() const {
return 0 == fTypeMask;
return 0 == fTypeMask.load(std::memory_order_relaxed);
}
inline const SkMScalar* values() const { return &fMat[0][0]; }
friend class SkColorSpace;
friend class SkColorSpace_XYZ;
};
#endif

Просмотреть файл

@ -5,5 +5,5 @@
* found in the LICENSE file.
*/
#ifndef SK_MILESTONE
#define SK_MILESTONE 66
#define SK_MILESTONE 71
#endif

Просмотреть файл

@ -8,6 +8,7 @@
#ifndef SkOverdrawCanvas_DEFINED
#define SkOverdrawCanvas_DEFINED
#include "SkCanvasVirtualEnforcer.h"
#include "SkNWayCanvas.h"
/**
@ -15,7 +16,7 @@
* increments the alpha channel of each pixel every time it would have been touched
* by a draw call. This is useful for detecting overdraw.
*/
class SK_API SkOverdrawCanvas : public SkNWayCanvas {
class SK_API SkOverdrawCanvas : public SkCanvasVirtualEnforcer<SkNWayCanvas> {
public:
/* Does not take ownership of canvas */
SkOverdrawCanvas(SkCanvas*);
@ -23,8 +24,6 @@ public:
void onDrawText(const void*, size_t, SkScalar, SkScalar, const SkPaint&) override;
void onDrawPosText(const void*, size_t, const SkPoint[], const SkPaint&) override;
void onDrawPosTextH(const void*, size_t, const SkScalar[], SkScalar, const SkPaint&) override;
void onDrawTextOnPath(const void*, size_t, const SkPath&, const SkMatrix*,
const SkPaint&) override;
void onDrawTextRSXform(const void*, size_t, const SkRSXform[], const SkRect*,
const SkPaint&) override;
void onDrawTextBlob(const SkTextBlob*, SkScalar, SkScalar, const SkPaint&) override;
@ -38,7 +37,8 @@ public:
void onDrawDRRect(const SkRRect&, const SkRRect&, const SkPaint&) override;
void onDrawRRect(const SkRRect&, const SkPaint&) override;
void onDrawPoints(PointMode, size_t, const SkPoint[], const SkPaint&) override;
void onDrawVerticesObject(const SkVertices*, SkBlendMode, const SkPaint&) override;
void onDrawVerticesObject(const SkVertices*, const SkVertices::Bone bones[], int boneCount,
SkBlendMode, const SkPaint&) override;
void onDrawAtlas(const SkImage*, const SkRSXform[], const SkRect[], const SkColor[],
int, SkBlendMode, const SkRect*, const SkPaint*) override;
void onDrawPath(const SkPath&, const SkPaint&) override;
@ -56,6 +56,9 @@ public:
void onDrawDrawable(SkDrawable*, const SkMatrix*) override;
void onDrawPicture(const SkPicture*, const SkMatrix*, const SkPaint*) override;
void onDrawAnnotation(const SkRect&, const char key[], SkData* value) override;
void onDrawShadowRec(const SkPath&, const SkDrawShadowRec&) override;
private:
void drawPosTextCommon(const void*, size_t, const SkScalar[], int, const SkPoint&,
const SkPaint&);
@ -64,7 +67,7 @@ private:
SkPaint fPaint;
typedef SkNWayCanvas INHERITED;
typedef SkCanvasVirtualEnforcer<SkNWayCanvas> INHERITED;
};
#endif

Просмотреть файл

@ -5,24 +5,37 @@
* found in the LICENSE file.
*/
/* Generated by tools/bookmaker from include/core/SkPaint.h and docs/SkPaint_Reference.bmh
on 2018-08-28 10:32:58. Additional documentation and examples can be found at:
https://skia.org/user/api/SkPaint_Reference
You may edit either file directly. Structural changes to public interfaces require
editing both files. After editing docs/SkPaint_Reference.bmh, run:
bookmaker -b docs -i include/core/SkPaint.h -p
to create an updated version of this file.
*/
#ifndef SkPaint_DEFINED
#define SkPaint_DEFINED
#include "../private/SkTo.h"
#include "SkBlendMode.h"
#include "SkColor.h"
#include "SkFilterQuality.h"
#include "SkMatrix.h"
#include "SkRefCnt.h"
class GrTextBlob;
class SkAutoDescriptor;
class SkAutoGlyphCache;
class SkColorFilter;
class SkColorSpace;
class SkData;
class SkDescriptor;
class SkDrawLooper;
class SkReadBuffer;
class SkWriteBuffer;
class SkGlyph;
class SkGlyphRunBuilder;
class SkGlyphRun;
class SkGlyphRunListPainter;
struct SkRect;
class SkGlyphCache;
class SkImageFilter;
@ -30,9 +43,11 @@ class SkMaskFilter;
class SkPath;
class SkPathEffect;
struct SkPoint;
class SkRunFont;
class SkShader;
class SkSurfaceProps;
class SkTextBlob;
class SkTextBlobRunIterator;
class SkTypeface;
/** \class SkPaint
@ -161,24 +176,6 @@ public:
*/
uint32_t getHash() const;
/** Serializes SkPaint into a buffer. A companion unflatten() call
can reconstitute the paint at a later time.
@param buffer SkWriteBuffer receiving the flattened SkPaint data
*/
void flatten(SkWriteBuffer& buffer) const;
/** Populates SkPaint, typically from a serialized stream, created by calling
flatten() at an earlier time.
SkReadBuffer class is not public, so unflatten() cannot be meaningfully called
by the client.
@param buffer serialized data describing SkPaint content
@return false if the buffer contains invalid data
*/
bool unflatten(SkReadBuffer& buffer);
/** Sets all SkPaint contents to their initial values. This is equivalent to replacing
SkPaint with the result of SkPaint().
*/
@ -193,36 +190,10 @@ public:
as the font engine.
*/
enum Hinting {
/** Leaves glyph outlines unchanged from their native representation.
With FreeType, this is equivalent to the FT_LOAD_NO_HINTING
bit-field constant supplied to FT_Load_Glyph, which indicates that the vector
outline being loaded should not be fitted to the pixel grid but simply scaled
to 26.6 fractional pixels.
*/
kNo_Hinting = 0,
/** Modifies glyph outlines minimally to improve constrast.
With FreeType, this is equivalent in spirit to the
FT_LOAD_TARGET_LIGHT value supplied to FT_Load_Glyph. It chooses a
lighter hinting algorithm for non-monochrome modes.
Generated glyphs may be fuzzy but better resemble their original shape.
*/
kSlight_Hinting = 1,
/** Modifies glyph outlines to improve constrast. This is the default.
With FreeType, this supplies FT_LOAD_TARGET_NORMAL to FT_Load_Glyph,
choosing the default hinting algorithm, which is optimized for standard
gray-level rendering.
*/
kNormal_Hinting = 2,
/** Modifies glyph outlines for maxiumum constrast. With FreeType, this selects
FT_LOAD_TARGET_LCD or FT_LOAD_TARGET_LCD_V if kLCDRenderText_Flag is set.
FT_LOAD_TARGET_LCD is a variant of FT_LOAD_TARGET_NORMAL optimized for
horizontally decimated LCD displays; FT_LOAD_TARGET_LCD_V is a
variant of FT_LOAD_TARGET_NORMAL optimized for vertically decimated LCD displays.
*/
kFull_Hinting = 3,
kNo_Hinting = 0, //!< glyph outlines unchanged
kSlight_Hinting = 1, //!< minimal modification to improve constrast
kNormal_Hinting = 2, //!< glyph outlines modified to improve constrast
kFull_Hinting = 3, //!< modifies glyph outlines for maximum constrast
};
/** Returns level of glyph outline adjustment.
@ -253,23 +224,17 @@ public:
kFakeBoldText_Flag = 0x20, //!< mask for setting fake bold
kLinearText_Flag = 0x40, //!< mask for setting linear text
kSubpixelText_Flag = 0x80, //!< mask for setting subpixel text
kDevKernText_Flag = 0x100, //!< mask for setting full hinting spacing
kLCDRenderText_Flag = 0x200, //!< mask for setting LCD text
kEmbeddedBitmapText_Flag = 0x400, //!< mask for setting font embedded bitmaps
kAutoHinting_Flag = 0x800, //!< mask for setting auto-hinting
kVerticalText_Flag = 0x1000, //!< mask for setting vertical text
/** Hack for GDI -- do not use if you can help it */
kGenA8FromLCD_Flag = 0x2000,
/** mask of all Flags, including private flags and flags reserved for future use */
kAllFlags = 0xFFFF,
kAllFlags = 0xFFFF, //!< mask of all Flags
};
#ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
enum ReserveFlags {
kUnderlineText_ReserveFlag = 0x08, //!< deprecated
kStrikeThruText_ReserveFlag = 0x10, //!< deprecated
kUnderlineText_ReserveFlag = 0x08, //!< to be deprecated soon
kStrikeThruText_ReserveFlag = 0x10, //!< to be deprecated soon
};
#endif
@ -287,7 +252,7 @@ public:
*/
void setFlags(uint32_t flags);
/** If true, pixels on the active edges of SkPath may be drawn with partial transparency.
/** Returns true if pixels on the active edges of SkPath may be drawn with partial transparency.
Equivalent to getFlags() masked with kAntiAlias_Flag.
@ -307,7 +272,7 @@ public:
*/
void setAntiAlias(bool aa);
/** If true, color error may be distributed to smooth color transition.
/** Returns true if color error may be distributed to smooth color transition.
Equivalent to getFlags() masked with kDither_Flag.
@ -326,7 +291,7 @@ public:
*/
void setDither(bool dither);
/** If true, text is converted to SkPath before drawing and measuring.
/** Returns true if text is converted to SkPath before drawing and measuring.
Equivalent to getFlags() masked with kLinearText_Flag.
@ -336,7 +301,7 @@ public:
return SkToBool(this->getFlags() & kLinearText_Flag);
}
/** If true, text is converted to SkPath before drawing and measuring.
/** Returns true if text is converted to SkPath before drawing and measuring.
By default, kLinearText_Flag is clear.
Sets kLinearText_Flag if linearText is true.
@ -346,7 +311,7 @@ public:
*/
void setLinearText(bool linearText);
/** If true, glyphs at different sub-pixel positions may differ on pixel edge coverage.
/** Returns true if glyphs at different sub-pixel positions may differ on pixel edge coverage.
Equivalent to getFlags() masked with kSubpixelText_Flag.
@ -365,7 +330,7 @@ public:
*/
void setSubpixelText(bool subpixelText);
/** If true, glyphs may use LCD striping to improve glyph edges.
/** Returns true if glyphs may use LCD striping to improve glyph edges.
Returns true if SkPaint::Flags kLCDRenderText_Flag is set.
@ -384,7 +349,7 @@ public:
*/
void setLCDRenderText(bool lcdText);
/** If true, font engine may return glyphs from font bitmaps instead of from outlines.
/** Returns true if font engine may return glyphs from font bitmaps instead of from outlines.
Equivalent to getFlags() masked with kEmbeddedBitmapText_Flag.
@ -403,9 +368,9 @@ public:
*/
void setEmbeddedBitmapText(bool useEmbeddedBitmapText);
/** If true, and if SkPaint::Hinting is set to kNormal_Hinting or kFull_Hinting, and if
platform uses FreeType as the font manager, instruct the font manager to always hint
glyphs.
/** Returns true if SkPaint::Hinting is set to kNormal_Hinting or kFull_Hinting, and if
platform uses FreeType as the font manager. If true, instructs
the font manager to always hint glyphs.
Equivalent to getFlags() masked with kAutoHinting_Flag.
@ -415,8 +380,9 @@ public:
return SkToBool(this->getFlags() & kAutoHinting_Flag);
}
/** If SkPaint::Hinting is set to kNormal_Hinting or kFull_Hinting and useAutohinter is set,
instruct the font manager to always hint glyphs.
/** Sets whether to always hint glyphs.
If SkPaint::Hinting is set to kNormal_Hinting or kFull_Hinting and useAutohinter is set,
instructs the font manager to always hint glyphs.
auto-hinting has no effect if SkPaint::Hinting is set to kNo_Hinting or
kSlight_Hinting.
@ -429,7 +395,7 @@ public:
*/
void setAutohinted(bool useAutohinter);
/** If true, glyphs are drawn top to bottom instead of left to right.
/** Returns true if glyphs are drawn top to bottom instead of left to right.
Equivalent to getFlags() masked with kVerticalText_Flag.
@ -439,7 +405,7 @@ public:
return SkToBool(this->getFlags() & kVerticalText_Flag);
}
/** If true, text advance positions the next glyph below the previous glyph instead of to the
/** Returns true if text advance positions the next glyph below the previous glyph instead of to the
right of previous glyph.
Sets kVerticalText_Flag if vertical is true.
@ -449,7 +415,7 @@ public:
*/
void setVerticalText(bool verticalText);
/** If true, approximate bold by increasing the stroke width when creating glyph bitmaps
/** Returns true if approximate bold by increasing the stroke width when creating glyph bitmaps
from outlines.
Equivalent to getFlags() masked with kFakeBoldText_Flag.
@ -460,7 +426,7 @@ public:
return SkToBool(this->getFlags() & kFakeBoldText_Flag);
}
/** Use increased stroke width when creating glyph bitmaps to approximate a bold typeface.
/** Increases stroke width when creating glyph bitmaps to approximate a bold typeface.
Sets kFakeBoldText_Flag if fakeBoldText is true.
Clears kFakeBoldText_Flag if fakeBoldText is false.
@ -469,24 +435,13 @@ public:
*/
void setFakeBoldText(bool fakeBoldText);
/** Returns if character spacing may be adjusted by the hinting difference.
Equivalent to getFlags() masked with kDevKernText_Flag.
@return kDevKernText_Flag state
/** Deprecated.
*/
bool isDevKernText() const {
return SkToBool(this->getFlags() & kDevKernText_Flag);
}
bool isDevKernText() const { return false; }
/** Requests, but does not require, to use hinting to adjust glyph spacing.
Sets kDevKernText_Flag if devKernText is true.
Clears kDevKernText_Flag if devKernText is false.
@param devKernText setting for devKernText
/** Deprecated.
*/
void setDevKernText(bool devKernText);
void setDevKernText(bool) { }
/** Returns SkFilterQuality, the image filtering level. A lower setting
draws faster; a higher setting looks better when the image is scaled.
@ -516,40 +471,16 @@ public:
a fill draw.
*/
enum Style {
/** Set to fill geometry.
Applies to SkRect, SkRegion, SkRRect, circles, ovals, SkPath, and text.
SkBitmap, SkImage, patches, SkRegion, sprites, and vertices are painted as if
kFill_Style is set, and ignore the set Style.
The FillType specifies additional rules to fill the area outside the path edge,
and to create an unfilled hole inside the shape.
Style is set to kFill_Style by default.
*/
kFill_Style,
/** Set to stroke geometry.
Applies to SkRect, SkRegion, SkRRect, arcs, circles, ovals, SkPath, and text.
Arcs, lines, and points, are always drawn as if kStroke_Style is set,
and ignore the set Style.
The stroke construction is unaffected by the FillType.
*/
kStroke_Style,
/** Set to stroke and fill geometry.
Applies to SkRect, SkRegion, SkRRect, circles, ovals, SkPath, and text.
SkPath is treated as if it is set to SkPath::kWinding_FillType,
and the set FillType is ignored.
*/
kStrokeAndFill_Style,
kFill_Style, //!< set to fill geometry
kStroke_Style, //!< set to stroke geometry
kStrokeAndFill_Style, //!< sets to stroke and fill geometry
};
enum {
/** The number of different Style values defined.
May be used to verify that Style is a legal value.
*/
kStyleCount = kStrokeAndFill_Style + 1,
};
/** May be used to verify that SkPaint::Style is a legal value.
*/
static constexpr int kStyleCount = kStrokeAndFill_Style + 1;
/** Whether the geometry is filled, stroked, or filled and stroked.
/** Returns whether the geometry is filled, stroked, or filled and stroked.
@return one of:kFill_Style, kStroke_Style, kStrokeAndFill_Style
*/
@ -568,7 +499,14 @@ public:
@return unpremultiplied ARGB
*/
SkColor getColor() const { return fColor; }
SkColor getColor() const { return fColor4f.toSkColor(); }
/** Retrieves alpha and RGB, unpmreultiplied, as four floating point values. RGB are
are extended sRGB values (sRGB gamut, and encoded with the sRGB transfer function).
@return unpremultiplied RGBA
*/
SkColor4f getColor4f() const { return fColor4f; }
/** Sets alpha and RGB used when stroking and filling. The color is a 32-bit value,
unpremultiplied, packing 8-bit components for alpha, red, blue, and green.
@ -577,11 +515,21 @@ public:
*/
void setColor(SkColor color);
/** Sets alpha and RGB used when stroking and filling. The color is four floating
point values, unpremultiplied. The color values are interpreted as being in
the colorSpace. If colorSpace is nullptr, then color is assumed to be in the
sRGB color space.
@param color unpremultiplied RGBA
@param colorSpace SkColorSpace describing the encoding of color
*/
void setColor4f(const SkColor4f& color, SkColorSpace* colorSpace);
/** Retrieves alpha from the color used when stroking and filling.
@return alpha ranging from zero, fully transparent, to 255, fully opaque
*/
uint8_t getAlpha() const { return SkToU8(SkColorGetA(fColor)); }
uint8_t getAlpha() const { return sk_float_round2int(fColor4f.fA * 255); }
/** Replaces alpha, leaving RGB
unchanged. An out of range value triggers an assert in the debug
@ -596,10 +544,10 @@ public:
/** Sets color used when drawing solid fills. The color components range from 0 to 255.
The color is unpremultiplied; alpha sets the transparency independent of RGB.
@param a amount of color alpha, from fully transparent (0) to fully opaque (255)
@param r amount of color rgb red, from no red (0) to full red (255)
@param g amount of color rgb green, from no green (0) to full green (255)
@param b amount of color rgb blue, from no blue (0) to full blue (255)
@param a amount of alpha, from fully transparent (0) to fully opaque (255)
@param r amount of red, from no red (0) to full red (255)
@param g amount of green, from no green (0) to full green (255)
@param b amount of blue, from no blue (0) to full blue (255)
*/
void setARGB(U8CPU a, U8CPU r, U8CPU g, U8CPU b);
@ -618,13 +566,13 @@ public:
*/
void setStrokeWidth(SkScalar width);
/** The limit at which a sharp corner is drawn beveled.
/** Returns the limit at which a sharp corner is drawn beveled.
@return zero and greater miter limit
*/
SkScalar getStrokeMiter() const { return fMiterLimit; }
/** The limit at which a sharp corner is drawn beveled.
/** Sets the limit at which a sharp corner is drawn beveled.
Valid values are zero and greater.
Has no effect if miter is less than zero.
@ -636,28 +584,15 @@ public:
Cap draws at the beginning and end of an open path contour.
*/
enum Cap {
kButt_Cap, //!< Does not extend the stroke past the beginning or the end.
/** Adds a circle with a diameter equal to stroke width at the beginning
and end.
*/
kRound_Cap,
/** Adds a square with sides equal to stroke width at the beginning
and end. The square sides are parallel to the initial and final direction
of the stroke.
*/
kSquare_Cap,
kLast_Cap = kSquare_Cap, //!< Equivalent to the largest value for Cap.
/** Equivalent to kButt_Cap.
Cap is set to kButt_Cap by default.
*/
kDefault_Cap = kButt_Cap,
kButt_Cap, //!< no stroke extension
kRound_Cap, //!< adds circle
kSquare_Cap, //!< adds square
kLast_Cap = kSquare_Cap, //!< largest Cap value
kDefault_Cap = kButt_Cap, //!< equivalent to kButt_Cap
};
/** The number of different SkPaint::Cap values defined.
May be used to verify that SkPaint::Cap is a legal value.*/
/** May be used to verify that SkPaint::Cap is a legal value.
*/
static constexpr int kCapCount = kLast_Cap + 1;
/** \enum SkPaint::Join
@ -674,53 +609,44 @@ public:
not necessarily include circles at each connected segment.
*/
enum Join {
/** Extends the outside corner to the extent allowed by miter limit.
If the extension exceeds miter limit, kBevel_Join is used instead.
*/
kMiter_Join,
/** Adds a circle with a diameter of stroke width at the sharp corner. */
kRound_Join,
kBevel_Join, //!< Connects the outside edges of the sharp corner.
kLast_Join = kBevel_Join, //!< Equivalent to the largest value for Join.
/** Equivalent to kMiter_Join.
Join is set to kMiter_Join by default.
*/
kDefault_Join = kMiter_Join,
kMiter_Join, //!< extends to miter limit
kRound_Join, //!< adds circle
kBevel_Join, //!< connects outside edges
kLast_Join = kBevel_Join, //!< equivalent to the largest value for Join
kDefault_Join = kMiter_Join, //!< equivalent to kMiter_Join
};
/** The number of different SkPaint::Join values defined.
May be used to verify that SkPaint::Join is a legal value.*/
/** May be used to verify that SkPaint::Join is a legal value.
*/
static constexpr int kJoinCount = kLast_Join + 1;
/** The geometry drawn at the beginning and end of strokes.
/** Returns the geometry drawn at the beginning and end of strokes.
@return one of: kButt_Cap, kRound_Cap, kSquare_Cap
*/
Cap getStrokeCap() const { return (Cap)fBitfields.fCapType; }
/** The geometry drawn at the beginning and end of strokes.
/** Sets the geometry drawn at the beginning and end of strokes.
@param cap one of: kButt_Cap, kRound_Cap, kSquare_Cap;
has no effect if cap is not valid
*/
void setStrokeCap(Cap cap);
/** The geometry drawn at the corners of strokes.
/** Returns the geometry drawn at the corners of strokes.
@return one of: kMiter_Join, kRound_Join, kBevel_Join
*/
Join getStrokeJoin() const { return (Join)fBitfields.fJoinType; }
/** The geometry drawn at the corners of strokes.
/** Sets the geometry drawn at the corners of strokes.
@param join one of: kMiter_Join, kRound_Join, kBevel_Join;
otherwise, has no effect
*/
void setStrokeJoin(Join join);
/** The filled equivalent of the stroked path.
/** Returns the filled equivalent of the stroked path.
@param src SkPath read to create a filled version
@param dst resulting SkPath; may be the same as src, but may not be nullptr
@ -732,7 +658,7 @@ public:
bool getFillPath(const SkPath& src, SkPath* dst, const SkRect* cullRect,
SkScalar resScale = 1) const;
/** The filled equivalent of the stroked path.
/** Returns the filled equivalent of the stroked path.
Replaces dst with the src path modified by SkPathEffect and style stroke.
SkPathEffect, if any, is not culled. stroke width is created with default precision.
@ -745,7 +671,7 @@ public:
return this->getFillPath(src, dst, nullptr, 1);
}
/** Optional colors used when filling a path, such as a gradient.
/** Returns optional colors used when filling a path, such as a gradient.
Does not alter SkShader SkRefCnt.
@ -753,7 +679,7 @@ public:
*/
SkShader* getShader() const { return fShader.get(); }
/** Optional colors used when filling a path, such as a gradient.
/** Returns optional colors used when filling a path, such as a gradient.
Increases SkShader SkRefCnt by one.
@ -761,7 +687,7 @@ public:
*/
sk_sp<SkShader> refShader() const;
/** Optional colors used when filling a path, such as a gradient.
/** Sets optional colors used when filling a path, such as a gradient.
Sets SkShader to shader, decreasing SkRefCnt of the previous SkShader.
Increments shader SkRefCnt by one.
@ -862,7 +788,7 @@ public:
void setMaskFilter(sk_sp<SkMaskFilter> maskFilter);
/** Returns SkTypeface if set, or nullptr.
Increments SkTypeface SkRefCnt by one.
Does not alter SkTypeface SkRefCnt.
@return SkTypeface if previously set, nullptr otherwise
*/
@ -943,8 +869,7 @@ public:
/** \enum SkPaint::Align
Align adjusts the text relative to the text position.
Align affects glyphs drawn with: SkCanvas::drawText, SkCanvas::drawPosText,
SkCanvas::drawPosTextH, SkCanvas::drawTextOnPath,
SkCanvas::drawTextOnPathHV, SkCanvas::drawTextRSXform, SkCanvas::drawTextBlob,
SkCanvas::drawPosTextH, SkCanvas::drawTextRSXform, SkCanvas::drawTextBlob,
and SkCanvas::drawString;
as well as calls that place text glyphs like getTextWidths() and getTextPath().
@ -959,23 +884,14 @@ public:
Align defaults to kLeft_Align.
*/
enum Align {
/** Leaves the glyph at the position computed by the font offset by the text position. */
kLeft_Align,
/** Moves the glyph half its width if Flags has kVerticalText_Flag clear, and
half its height if Flags has kVerticalText_Flag set.
*/
kCenter_Align,
/** Moves the glyph by its width if Flags has kVerticalText_Flag clear,
and by its height if Flags has kVerticalText_Flag set.
*/
kRight_Align,
kLeft_Align, //!< positions glyph by computed font offset
kCenter_Align, //!< centers line of glyphs by its width or height
kRight_Align, //!< moves lines of glyphs by its width or height
};
enum {
kAlignCount = 3, //!< The number of different Align values defined.
};
/** May be used to verify that align is a legal value.
*/
static constexpr int kAlignCount = 3;
/** Returns SkPaint::Align.
Returns kLeft_Align if SkPaint::Align has not been set.
@ -1052,10 +968,10 @@ public:
TextEncoding is set to kUTF8_TextEncoding by default.
*/
enum TextEncoding {
kUTF8_TextEncoding, //!< Uses bytes to represent UTF-8 or ASCII.
kUTF16_TextEncoding, //!< Uses two byte words to represent most of Unicode.
kUTF32_TextEncoding, //!< Uses four byte words to represent all of Unicode.
kGlyphID_TextEncoding, //!< Uses two byte words to represent glyph indices.
kUTF8_TextEncoding, //!< uses bytes to represent UTF-8 or ASCII
kUTF16_TextEncoding, //!< uses two byte words to represent most of Unicode
kUTF32_TextEncoding, //!< uses four byte words to represent all of Unicode
kGlyphID_TextEncoding, //!< uses two byte words to represent glyph indices
};
/** Returns SkPaint::TextEncoding.
@ -1082,9 +998,9 @@ public:
computed by font manager using SkTypeface. Values are set to zero if they are
not available.
All vertical values relative to the baseline are given y-down. As such, zero is on the
baseline, negative values are above the baseline, and positive values are below the
baseline.
All vertical values are relative to the baseline, on a y-axis pointing down.
Zero is on the baseline, negative values are above the baseline, and positive
values are below the baseline.
fUnderlineThickness and fUnderlinePosition have a bit set in fFlags if their values
are valid, since their value may be zero.
@ -1100,97 +1016,30 @@ public:
Fonts with embedded bitmaps may not have valid underline or strikeout metrics.
*/
enum FontMetricsFlags {
kUnderlineThicknessIsValid_Flag = 1 << 0, //!< Set if fUnderlineThickness is valid.
kUnderlinePositionIsValid_Flag = 1 << 1, //!< Set if fUnderlinePosition is valid.
kStrikeoutThicknessIsValid_Flag = 1 << 2, //!< Set if fStrikeoutThickness is valid.
kStrikeoutPositionIsValid_Flag = 1 << 3, //!< Set if fStrikeoutPosition is valid.
kUnderlineThicknessIsValid_Flag = 1 << 0, //!< set if fUnderlineThickness is valid
kUnderlinePositionIsValid_Flag = 1 << 1, //!< set if fUnderlinePosition is valid
kStrikeoutThicknessIsValid_Flag = 1 << 2, //!< set if fStrikeoutThickness is valid
kStrikeoutPositionIsValid_Flag = 1 << 3, //!< set if fStrikeoutPosition is valid
};
uint32_t fFlags; //!< fFlags is set when underline metrics are valid.
uint32_t fFlags; //!< is set to FontMetricsFlags when metrics are valid
SkScalar fTop; //!< extent above baseline
SkScalar fAscent; //!< distance to reserve above baseline
SkScalar fDescent; //!< distance to reserve below baseline
SkScalar fBottom; //!< extent below baseline
SkScalar fLeading; //!< distance to add between lines
SkScalar fAvgCharWidth; //!< average character width
SkScalar fMaxCharWidth; //!< maximum character width
SkScalar fXMin; //!< minimum x
SkScalar fXMax; //!< maximum x
SkScalar fXHeight; //!< height of lower-case 'x'
SkScalar fCapHeight; //!< height of an upper-case letter
SkScalar fUnderlineThickness; //!< underline thickness
SkScalar fUnderlinePosition; //!< underline position relative to baseline
SkScalar fStrikeoutThickness; //!< strikeout thickness
SkScalar fStrikeoutPosition; //!< strikeout position relative to baseline
/** Greatest extent above the baseline for any glyph.
Typically less than zero.
*/
SkScalar fTop;
/** Recommended distance above the baseline to reserve for a line of text.
Typically less than zero.
*/
SkScalar fAscent;
/** Recommended distance below the baseline to reserve for a line of text.
Typically greater than zero.
*/
SkScalar fDescent;
/** Greatest extent below the baseline for any glyph.
Typically greater than zero.
*/
SkScalar fBottom;
/** Recommended distance to add between lines of text.
Typically greater than or equal to zero.
*/
SkScalar fLeading;
/** Average character width, if it is available.
Zero if no average width is stored in the font.
*/
SkScalar fAvgCharWidth;
SkScalar fMaxCharWidth; //!< Maximum character width.
/** Minimum bounding box x value for all glyphs.
Typically less than zero.
*/
SkScalar fXMin;
/** Maximum bounding box x value for all glyphs.
Typically greater than zero.
*/
SkScalar fXMax;
/** Height of a lower-case 'x'.
May be zero if no lower-case height is stored in the font.
*/
SkScalar fXHeight;
/** Height of an upper-case letter.
May be zero if no upper-case height is stored in the font.
*/
SkScalar fCapHeight;
/** Underline thickness.
If the metric is valid, the kUnderlineThicknessIsValid_Flag is set in fFlags.
If kUnderlineThicknessIsValid_Flag is clear, fUnderlineThickness is zero.
*/
SkScalar fUnderlineThickness;
/** Position of the top of the underline stroke relative to the baseline.
Typically positive when valid.
If the metric is valid, the kUnderlinePositionIsValid_Flag is set in fFlags.
If kUnderlinePositionIsValid_Flag is clear, fUnderlinePosition is zero.
*/
SkScalar fUnderlinePosition;
/** Strikeout thickness.
If the metric is valid, the kStrikeoutThicknessIsValid_Flag is set in fFlags.
If kStrikeoutThicknessIsValid_Flag is clear, fStrikeoutThickness is zero.
*/
SkScalar fStrikeoutThickness;
/** Position of the bottom of the strikeout stroke relative to the baseline.
Typically negative when valid.
If the metric is valid, the kStrikeoutPositionIsValid_Flag is set in fFlags.
If kStrikeoutPositionIsValid_Flag is clear, fStrikeoutPosition is zero.
*/
SkScalar fStrikeoutPosition;
/** If SkPaint::FontMetrics has a valid underline thickness, return true, and set
/** Returns true if SkPaint::FontMetrics has a valid underline thickness, and sets
thickness to that value. If the underline thickness is not valid,
return false, and ignore thickness.
@ -1205,7 +1054,7 @@ public:
return false;
}
/** If SkPaint::FontMetrics has a valid underline position, return true, and set
/** Returns true if SkPaint::FontMetrics has a valid underline position, and sets
position to that value. If the underline position is not valid,
return false, and ignore position.
@ -1220,7 +1069,7 @@ public:
return false;
}
/** If SkPaint::FontMetrics has a valid strikeout thickness, return true, and set
/** Returns true if SkPaint::FontMetrics has a valid strikeout thickness, and sets
thickness to that value. If the underline thickness is not valid,
return false, and ignore thickness.
@ -1235,7 +1084,7 @@ public:
return false;
}
/** If SkPaint::FontMetrics has a valid strikeout position, return true, and set
/** Returns true if SkPaint::FontMetrics has a valid strikeout position, and sets
position to that value. If the underline position is not valid,
return false, and ignore position.
@ -1336,9 +1185,7 @@ public:
@param byteLength length of character storage in bytes
@return number of glyphs represented by text of length byteLength
*/
int countText(const void* text, size_t byteLength) const {
return this->textToGlyphs(text, byteLength, nullptr);
}
int countText(const void* text, size_t byteLength) const;
/** Returns the advance width of text if kVerticalText_Flag is clear,
and the height of text if kVerticalText_Flag is set.
@ -1420,8 +1267,8 @@ public:
@param text character codes or glyph indices
@param length number of bytes of text
@param x x-coordinate of the origin of the text
@param y y-coordinate of the origin of the text
@param x x-axis value of the origin of the text
@param y y-axis value of the origin of the text
@param path geometry of the glyphs
*/
void getTextPath(const void* text, size_t length, SkScalar x, SkScalar y,
@ -1456,8 +1303,8 @@ public:
@param text character codes or glyph indices
@param length number of bytes of text
@param x x-coordinate of the origin of the text
@param y y-coordinate of the origin of the text
@param x x-axis value of the origin of the text
@param y y-axis value of the origin of the text
@param bounds lower and upper line parallel to the advance
@param intervals returned intersections; may be nullptr
@return number of intersections; may be zero
@ -1548,7 +1395,7 @@ public:
/** Returns true if SkPaint prevents all drawing;
otherwise, the SkPaint may or may not allow drawing.
Returns true if, for example, SkBlendMode combined with color alpha computes a
Returns true if, for example, SkBlendMode combined with alpha computes a
new alpha of zero.
@return true if SkPaint prevents all drawing
@ -1575,15 +1422,14 @@ public:
should not rely on storage being set to the result, but should always
use the returned value. It is legal for orig and storage to be the same
SkRect.
e.g.
if (paint.canComputeFastBounds()) {
SkRect r, storage;
path.computeBounds(&r, SkPath::kFast_BoundsType);
const SkRect& fastR = paint.computeFastBounds(r, &storage);
if (canvas->quickReject(fastR, ...)) {
// don't draw the path
}
For example:
if (!path.isInverseFillType() && paint.canComputeFastBounds()) {
SkRect storage;
if (canvas->quickReject(paint.computeFastBounds(path.getBounds(), &storage))) {
return; // do not draw the path
}
}
// draw the path
@param orig geometry modified by SkPaint when drawn
@param storage computed bounds of geometry; may not be nullptr
@ -1631,17 +1477,11 @@ public:
const SkRect& doComputeFastBounds(const SkRect& orig, SkRect* storage,
Style style) const;
/** macro expands to: void toString(SkString* str) const;
Creates string representation of SkPaint. The representation is read by
internal debugging tools. The interface and implementation may be
suppressed by defining SK_IGNORE_TO_STRING.
@param str storage for string representation of SkPaint
*/
SK_TO_STRING_NONVIRT()
private:
typedef const SkGlyph& (*GlyphCacheProc)(SkGlyphCache*, const char**);
friend class SkGlyphRun;
friend class SkGlyphRunBuilder;
SkPaint(const SkPaint&, const SkRunFont&);
typedef const SkGlyph& (*GlyphCacheProc)(SkGlyphCache*, const char**, const char*);
sk_sp<SkTypeface> fTypeface;
sk_sp<SkPathEffect> fPathEffect;
@ -1654,7 +1494,7 @@ private:
SkScalar fTextSize;
SkScalar fTextScaleX;
SkScalar fTextSkewX;
SkColor fColor;
SkColor4f fColor4f;
SkScalar fWidth;
SkScalar fMiterLimit;
uint32_t fBlendMode; // just need 5-6 bits
@ -1675,7 +1515,6 @@ private:
};
static GlyphCacheProc GetGlyphCacheProc(TextEncoding encoding,
bool isDevKern,
bool needFullMetrics);
SkScalar measure_text(SkGlyphCache*, const char* text, size_t length,
@ -1688,23 +1527,21 @@ private:
*/
SkColor computeLuminanceColor() const;
enum {
/* This is the size we use when we ask for a glyph's path. We then
* post-transform it as we draw to match the request.
* This is done to try to re-use cache entries for the path.
*
* This value is somewhat arbitrary. In theory, it could be 1, since
* we store paths as floats. However, we get the path from the font
* scaler, and it may represent its paths as fixed-point (or 26.6),
* so we shouldn't ask for something too big (might overflow 16.16)
* or too small (underflow 26.6).
*
* This value could track kMaxSizeForGlyphCache, assuming the above
* constraints, but since we ask for unhinted paths, the two values
* need not match per-se.
*/
kCanonicalTextSizeForPaths = 64,
};
/* This is the size we use when we ask for a glyph's path. We then
* post-transform it as we draw to match the request.
* This is done to try to re-use cache entries for the path.
*
* This value is somewhat arbitrary. In theory, it could be 1, since
* we store paths as floats. However, we get the path from the font
* scaler, and it may represent its paths as fixed-point (or 26.6),
* so we shouldn't ask for something too big (might overflow 16.16)
* or too small (underflow 26.6).
*
* This value could track kMaxSizeForGlyphCache, assuming the above
* constraints, but since we ask for unhinted paths, the two values
* need not match per-se.
*/
static constexpr int kCanonicalTextSizeForPaths = 64;
static bool TooBigToUseCache(const SkMatrix& ctm, const SkMatrix& textM, SkScalar maxLimit);
@ -1715,19 +1552,20 @@ private:
static SkScalar MaxCacheSize2(SkScalar maxLimit);
friend class GrAtlasTextBlob;
friend class GrAtlasTextContext;
friend class GrTextBlob;
friend class GrTextContext;
friend class GrGLPathRendering;
friend class GrPathRendering;
friend class GrTextUtils;
friend class SkAutoGlyphCache;
friend class SkAutoGlyphCacheNoGamma;
friend class SkCanonicalizePaint;
friend class SkCanvas;
friend class SkDraw;
friend class SkGlyphRunListPainter;
friend class SkPaintPriv;
friend class SkPDFDevice;
friend class SkScalerContext; // for computeLuminanceColor()
friend class SkTextBaseIter;
friend class SkTextBlobCacheDiffCanvas;
};
#endif

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -58,14 +58,13 @@ public:
* If this method returns true, the caller will apply (as needed) the
* resulting stroke-rec to dst and then draw.
*/
virtual bool filterPath(SkPath* dst, const SkPath& src,
SkStrokeRec*, const SkRect* cullR) const = 0;
bool filterPath(SkPath* dst, const SkPath& src, SkStrokeRec*, const SkRect* cullR) const;
/**
* Compute a conservative bounds for its effect, given the src bounds.
* The baseline implementation just assigns src to dst.
*/
virtual void computeFastBounds(SkRect* dst, const SkRect& src) const;
void computeFastBounds(SkRect* dst, const SkRect& src) const;
/** \class PointData
@ -112,7 +111,7 @@ public:
* Does applying this path effect to 'src' yield a set of points? If so,
* optionally return the points in 'results'.
*/
virtual bool asPoints(PointData* results, const SkPath& src,
bool asPoints(PointData* results, const SkPath& src,
const SkStrokeRec&, const SkMatrix&,
const SkRect* cullR) const;
@ -143,21 +142,45 @@ public:
// mod the sum of all intervals
};
virtual DashType asADash(DashInfo* info) const;
DashType asADash(DashInfo* info) const;
SK_TO_STRING_PUREVIRT()
SK_DEFINE_FLATTENABLE_TYPE(SkPathEffect)
static void InitializeFlattenables();
static SkFlattenable::Type GetFlattenableType() {
return kSkPathEffect_Type;
}
SkFlattenable::Type getFlattenableType() const override {
return kSkPathEffect_Type;
}
static sk_sp<SkPathEffect> Deserialize(const void* data, size_t size,
const SkDeserialProcs* procs = nullptr) {
return sk_sp<SkPathEffect>(static_cast<SkPathEffect*>(
SkFlattenable::Deserialize(
kSkPathEffect_Type, data, size, procs).release()));
}
#ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
/// Override for subclasses as appropriate.
virtual bool exposedInAndroidJavaAPI() const { return false; }
#endif
SK_DECLARE_FLATTENABLE_REGISTRAR_GROUP()
protected:
SkPathEffect() {}
virtual bool onFilterPath(SkPath*, const SkPath&, SkStrokeRec*, const SkRect*) const = 0;
virtual SkRect onComputeFastBounds(const SkRect& src) const {
return src;
}
virtual bool onAsPoints(PointData*, const SkPath&, const SkStrokeRec&, const SkMatrix&,
const SkRect*) const {
return false;
}
virtual DashType onAsADash(DashInfo*) const {
return kNone_DashType;
}
private:
// illegal
SkPathEffect(const SkPathEffect&);

Просмотреть файл

@ -84,13 +84,15 @@ public:
private:
SkPath::Iter fIter;
const SkPath* fPath;
SkPath fPath;
SkScalar fTolerance;
SkScalar fLength; // relative to the current contour
int fFirstPtIndex; // relative to the current contour
unsigned fFirstPtIndex; // relative to the current contour
bool fIsClosed; // relative to the current contour
bool fForceClosed;
#if defined(IS_FUZZING_WITH_LIBFUZZER)
int fSubdivisionsMax;
#endif
struct Segment {
SkScalar fDistance; // total distance up to this point
unsigned fPtIndex; // index into the fPts array
@ -107,12 +109,12 @@ private:
void buildSegments();
SkScalar compute_quad_segs(const SkPoint pts[3], SkScalar distance,
int mint, int maxt, int ptIndex);
int mint, int maxt, unsigned ptIndex);
SkScalar compute_conic_segs(const SkConic&, SkScalar distance,
int mint, const SkPoint& minPt,
int maxt, const SkPoint& maxPt, int ptIndex);
int maxt, const SkPoint& maxPt, unsigned ptIndex);
SkScalar compute_cubic_segs(const SkPoint pts[3], SkScalar distance,
int mint, int maxt, int ptIndex);
int mint, int maxt, unsigned ptIndex);
const Segment* distanceToSegment(SkScalar distance, SkScalar* t);
bool quad_too_curvy(const SkPoint pts[3]);
bool conic_too_curvy(const SkPoint& firstPt, const SkPoint& midTPt,const SkPoint& lastPt);

Просмотреть файл

@ -5,6 +5,16 @@
* found in the LICENSE file.
*/
/* Generated by tools/bookmaker from include/core/SkPicture.h and docs/SkPicture_Reference.bmh
on 2018-08-10 12:59:44. Additional documentation and examples can be found at:
https://skia.org/user/api/SkPicture_Reference
You may edit either file directly. Structural changes to public interfaces require
editing both files. After editing docs/SkPicture_Reference.bmh, run:
bookmaker -b docs -i include/core/SkPicture.h -p
to create an updated version of this file.
*/
#ifndef SkPicture_DEFINED
#define SkPicture_DEFINED
@ -12,119 +22,198 @@
#include "SkRect.h"
#include "SkTypes.h"
class SkBigPicture;
class SkCanvas;
class SkData;
struct SkDeserialProcs;
class SkImage;
class SkPictureData;
class SkReadBuffer;
class SkRefCntSet;
struct SkSerialProcs;
class SkStream;
class SkTypefacePlayback;
class SkWStream;
class SkWriteBuffer;
struct SkPictInfo;
/** \class SkPicture
SkPicture records drawing commands made to SkCanvas. The command stream may be
played in whole or in part at a later time.
An SkPicture records drawing commands made to a canvas to be played back at a later time.
This base class handles serialization and a few other miscellany.
SkPicture is an abstract class. SkPicture may be generated by SkPictureRecorder
or SkDrawable, or from SkPicture previously saved to SkData or SkStream.
SkPicture may contain any SkCanvas drawing command, as well as one or more
SkCanvas matrix or SkCanvas clip. SkPicture has a cull SkRect, which is used as
a bounding box hint. To limit SkPicture bounds, use SkCanvas clip when
recording or drawing SkPicture.
*/
class SK_API SkPicture : public SkRefCnt {
public:
/**
* Recreate a picture that was serialized into a stream or data.
*/
static sk_sp<SkPicture> MakeFromStream(SkStream*, const SkDeserialProcs* = nullptr);
static sk_sp<SkPicture> MakeFromData(const SkData* data, const SkDeserialProcs* = nullptr);
/** Recreates SkPicture that was serialized into a stream. Returns constructed SkPicture
if successful; otherwise, returns nullptr. Fails if data does not permit
constructing valid SkPicture.
procs.fPictureProc permits supplying a custom function to decode SkPicture.
If procs.fPictureProc is nullptr, default decoding is used. procs.fPictureCtx
may be used to provide user context to procs.fPictureProc; procs.fPictureProc
is called with a pointer to data, data byte length, and user context.
@param stream container for serial data
@param procs custom serial data decoders; may be nullptr
@return SkPicture constructed from stream data
*/
static sk_sp<SkPicture> MakeFromStream(SkStream* stream,
const SkDeserialProcs* procs = nullptr);
/** Recreates SkPicture that was serialized into data. Returns constructed SkPicture
if successful; otherwise, returns nullptr. Fails if data does not permit
constructing valid SkPicture.
procs.fPictureProc permits supplying a custom function to decode SkPicture.
If procs.fPictureProc is nullptr, default decoding is used. procs.fPictureCtx
may be used to provide user context to procs.fPictureProc; procs.fPictureProc
is called with a pointer to data, data byte length, and user context.
@param data container for serial data
@param procs custom serial data decoders; may be nullptr
@return SkPicture constructed from data
*/
static sk_sp<SkPicture> MakeFromData(const SkData* data,
const SkDeserialProcs* procs = nullptr);
/**
@param data pointer to serial data
@param size size of data
@param procs custom serial data decoders; may be nullptr
@return SkPicture constructed from data
*/
static sk_sp<SkPicture> MakeFromData(const void* data, size_t size,
const SkDeserialProcs* = nullptr);
const SkDeserialProcs* procs = nullptr);
/**
* Recreate a picture that was serialized into a buffer. If the creation requires bitmap
* decoding, the decoder must be set on the SkReadBuffer parameter by calling
* SkReadBuffer::setBitmapDecoder() before calling SkPicture::MakeFromBuffer().
* @param SkReadBuffer Serialized picture data.
* @return A new SkPicture representing the serialized data, or NULL if the buffer is
* invalid.
*/
static sk_sp<SkPicture> MakeFromBuffer(SkReadBuffer&);
/** \class SkPicture::AbortCallback
AbortCallback is an abstract class. An implementation of AbortCallback may
passed as a parameter to SkPicture::playback, to stop it before all drawing
commands have been processed.
/**
* Subclasses of this can be passed to playback(). During the playback
* of the picture, this callback will periodically be invoked. If its
* abort() returns true, then picture playback will be interrupted.
*
* The resulting drawing is undefined, as there is no guarantee how often the
* callback will be invoked. If the abort happens inside some level of nested
* calls to save(), restore will automatically be called to return the state
* to the same level it was before the playback call was made.
If AbortCallback::abort returns true, SkPicture::playback is interrupted.
*/
class SK_API AbortCallback {
public:
/** Has no effect.
@return abstract class cannot be instantiated
*/
AbortCallback() {}
/** Has no effect.
*/
virtual ~AbortCallback() {}
/** Stops SkPicture playback when some condition is met. A subclass of
AbortCallback provides an override for abort() that can stop SkPicture::playback.
The part of SkPicture drawn when aborted is undefined. SkPicture instantiations are
free to stop drawing at different points during playback.
If the abort happens inside one or more calls to SkCanvas::save(), stack
of SkCanvas matrix and SkCanvas clip values is restored to its state before
SkPicture::playback was called.
@return true to stop playback
*/
virtual bool abort() = 0;
};
/** Replays the drawing commands on the specified canvas. Note that
this has the effect of unfurling this picture into the destination
canvas. Using the SkCanvas::drawPicture entry point gives the destination
canvas the option of just taking a ref.
@param canvas the canvas receiving the drawing commands.
@param callback a callback that allows interruption of playback
*/
virtual void playback(SkCanvas*, AbortCallback* = nullptr) const = 0;
/** Replays the drawing commands on the specified canvas. In the case that the
commands are recorded, each command in the SkPicture is sent separately to canvas.
/** Return a cull rect for this picture.
Ops recorded into this picture that attempt to draw outside the cull might not be drawn.
*/
To add a single command to draw SkPicture to recording canvas, call
SkCanvas::drawPicture instead.
@param canvas receiver of drawing commands
@param callback allows interruption of playback
*/
virtual void playback(SkCanvas* canvas, AbortCallback* callback = nullptr) const = 0;
/** Returns cull SkRect for this picture, passed in when SkPicture was created.
Returned SkRect does not specify clipping SkRect for SkPicture; cull is hint
of SkPicture bounds.
SkPicture is free to discard recorded drawing commands that fall outside
cull.
@return bounds passed when SkPicture was created
*/
virtual SkRect cullRect() const = 0;
/** Returns a non-zero value unique among all pictures. */
/** Returns a non-zero value unique among SkPicture in Skia process.
@return identifier for SkPicture
*/
uint32_t uniqueID() const;
sk_sp<SkData> serialize(const SkSerialProcs* = nullptr) const;
void serialize(SkWStream*, const SkSerialProcs* = nullptr) const;
/** Returns storage containing SkData describing SkPicture, using optional custom
encoders.
/**
* Return a placeholder SkPicture.
* This placeholder does not draw anything itself. It has a distinct uniqueID()
* (just like all SkPictures) and will always be visible to SkSerialProcs.
* @param cull the placeholder's dimensions
*/
procs.fPictureProc permits supplying a custom function to encode SkPicture.
If procs.fPictureProc is nullptr, default encoding is used. procs.fPictureCtx
may be used to provide user context to procs.fPictureProc; procs.fPictureProc
is called with a pointer to SkPicture and user context.
@param procs custom serial data encoders; may be nullptr
@return storage containing serialized SkPicture
*/
sk_sp<SkData> serialize(const SkSerialProcs* procs = nullptr) const;
/** Writes picture to stream, using optional custom encoders.
procs.fPictureProc permits supplying a custom function to encode SkPicture.
If procs.fPictureProc is nullptr, default encoding is used. procs.fPictureCtx
may be used to provide user context to procs.fPictureProc; procs.fPictureProc
is called with a pointer to SkPicture and user context.
@param stream writable serial data stream
@param procs custom serial data encoders; may be nullptr
*/
void serialize(SkWStream* stream, const SkSerialProcs* procs = nullptr) const;
/** Returns a placeholder SkPicture. Result does not draw, and contains only
cull SkRect, a hint of its bounds. Result is immutable; it cannot be changed
later. Result identifier is unique.
Returned placeholder can be intercepted during playback to insert other
commands into SkCanvas draw stream.
@param cull placeholder dimensions
@return placeholder with unique identifier
*/
static sk_sp<SkPicture> MakePlaceholder(SkRect cull);
/**
* Serialize to a buffer.
*/
void flatten(SkWriteBuffer&) const;
/** Returns the approximate number of operations in SkPicture. Returned value
may be greater or less than the number of SkCanvas calls
recorded: some calls may be recorded as more than one operation, other
calls may be optimized away.
/** Return the approximate number of operations in this picture. This
* number may be greater or less than the number of SkCanvas calls
* recorded: some calls may be recorded as more than one operation, or some
* calls may be optimized away.
*/
@return approximate operation count
*/
virtual int approximateOpCount() const = 0;
/** Returns the approximate byte size of this picture, not including large ref'd objects. */
virtual size_t approximateBytesUsed() const = 0;
/** Returns the approximate byte size of SkPicture. Does not include large objects
referenced by SkPicture.
// Returns NULL if this is not an SkBigPicture.
virtual const SkBigPicture* asSkBigPicture() const { return nullptr; }
@return approximate size
*/
virtual size_t approximateBytesUsed() const = 0;
private:
// Subclass whitelist.
SkPicture();
friend class SkBigPicture;
friend class SkEmptyPicture;
friend class SkPicturePriv;
template <typename> friend class SkMiniPicture;
void serialize(SkWStream*, const SkSerialProcs*, SkRefCntSet* typefaces) const;
static sk_sp<SkPicture> MakeFromStream(SkStream*, const SkDeserialProcs*, SkTypefacePlayback*);
void serialize(SkWStream*, const SkSerialProcs*, class SkRefCntSet* typefaces) const;
static sk_sp<SkPicture> MakeFromStream(SkStream*, const SkDeserialProcs*,
class SkTypefacePlayback*);
friend class SkPictureData;
/** Return true if the SkStream/Buffer represents a serialized picture, and
@ -135,9 +224,12 @@ private:
intended for stand alone tools.
If false is returned, SkPictInfo is unmodified.
*/
static bool StreamIsSKP(SkStream*, SkPictInfo*);
static bool BufferIsSKP(SkReadBuffer*, SkPictInfo*);
friend bool SkPicture_StreamIsSKP(SkStream*, SkPictInfo*);
static bool StreamIsSKP(SkStream*, struct SkPictInfo*);
static bool BufferIsSKP(class SkReadBuffer*, struct SkPictInfo*);
friend bool SkPicture_StreamIsSKP(SkStream*, struct SkPictInfo*);
// Returns NULL if this is not an SkBigPicture.
virtual const class SkBigPicture* asSkBigPicture() const { return nullptr; }
friend struct SkPathCounter;
@ -168,18 +260,23 @@ private:
// V59: No more LocalSpace option on PictureImageFilter
// V60: Remove flags in picture header
// V61: Change SkDrawPictureRec to take two colors rather than two alphas
// V62: Don't negate size of custom encoded images (don't write origin x,y either)
// V63: Store image bounds (including origin) instead of just width/height to support subsets
// V64: Remove occluder feature from blur maskFilter
// Only SKPs within the min/current picture version range (inclusive) can be read.
static const uint32_t MIN_PICTURE_VERSION = 56; // august 2017
static const uint32_t CURRENT_PICTURE_VERSION = 61;
static const uint32_t CURRENT_PICTURE_VERSION = 65;
static bool IsValidPictInfo(const SkPictInfo& info);
static sk_sp<SkPicture> Forwardport(const SkPictInfo&,
const SkPictureData*,
SkReadBuffer* buffer);
static_assert(MIN_PICTURE_VERSION <= 62, "Remove kFontAxes_bad from SkFontDescriptor.cpp");
SkPictInfo createHeader() const;
SkPictureData* backport() const;
static bool IsValidPictInfo(const struct SkPictInfo& info);
static sk_sp<SkPicture> Forwardport(const struct SkPictInfo&,
const class SkPictureData*,
class SkReadBuffer* buffer);
struct SkPictInfo createHeader() const;
class SkPictureData* backport() const;
mutable uint32_t fUniqueID;
};

Просмотреть файл

@ -8,6 +8,7 @@
#ifndef SkPictureRecorder_DEFINED
#define SkPictureRecorder_DEFINED
#include "../private/SkNoncopyable.h"
#include "SkBBHFactory.h"
#include "SkPicture.h"
#include "SkRefCnt.h"

Просмотреть файл

@ -8,7 +8,6 @@
#ifndef SkPixelRef_DEFINED
#define SkPixelRef_DEFINED
#include "../private/SkAtomics.h"
#include "../private/SkMutex.h"
#include "../private/SkTDArray.h"
#include "SkBitmap.h"
@ -19,6 +18,8 @@
#include "SkSize.h"
#include "SkString.h"
#include <atomic>
struct SkIRect;
class GrTexture;
@ -45,18 +46,6 @@ public:
*/
uint32_t getGenerationID() const;
#ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
/** Returns a non-zero, unique value corresponding to this SkPixelRef.
Unlike the generation ID, this ID remains the same even when the pixels
are changed. IDs are not reused (until uint32_t wraps), so it is safe
to consider this ID unique even after this SkPixelRef is deleted.
Can be used as a key which uniquely identifies this SkPixelRef
regardless of changes to its pixels or deletion of this object.
*/
uint32_t getStableID() const { return fStableID; }
#endif
/**
* Call this if you have changed the contents of the pixels. This will in-
* turn cause a different generation ID value to be returned from
@ -88,7 +77,7 @@ public:
virtual void onChange() = 0;
};
// Takes ownership of listener.
// Takes ownership of listener. Threadsafe.
void addGenIDChangeListener(GenIDChangeListener* listener);
// Call when this pixelref is part of the key to a resourcecache entry. This allows the cache
@ -100,9 +89,6 @@ public:
virtual SkDiscardableMemory* diagnostic_only_getDiscardable() const { return nullptr; }
protected:
// default impl does nothing.
virtual void onNotifyPixelsChanged();
void android_only_reset(int width, int height, size_t rowBytes);
private:
@ -113,18 +99,15 @@ private:
// Bottom bit indicates the Gen ID is unique.
bool genIDIsUnique() const { return SkToBool(fTaggedGenID.load() & 1); }
mutable SkAtomic<uint32_t> fTaggedGenID;
#ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
const uint32_t fStableID;
#endif
mutable std::atomic<uint32_t> fTaggedGenID;
SkMutex fGenIDChangeListenersMutex;
SkTDArray<GenIDChangeListener*> fGenIDChangeListeners; // pointers are owned
// Set true by caches when they cache content that's derived from the current pixels.
SkAtomic<bool> fAddedToCache;
std::atomic<bool> fAddedToCache;
enum {
enum Mutability {
kMutable, // PixelRefs begin mutable.
kTemporarilyImmutable, // Considered immutable, but can revert to mutable.
kImmutable, // Once set to this state, it never leaves.

Просмотреть файл

@ -5,6 +5,16 @@
* found in the LICENSE file.
*/
/* Generated by tools/bookmaker from include/core/SkPixmap.h and docs/SkPixmap_Reference.bmh
on 2018-06-08 11:48:28. Additional documentation and examples can be found at:
https://skia.org/user/api/SkPixmap_Reference
You may edit either file directly. Structural changes to public interfaces require
editing both files. After editing docs/SkPixmap_Reference.bmh, run:
bookmaker -b docs -i include/core/SkPixmap.h -p
to create an updated version of this file.
*/
#ifndef SkPixmap_DEFINED
#define SkPixmap_DEFINED
@ -149,27 +159,29 @@ public:
*/
int height() const { return fInfo.height(); }
/** Returns SkColorType, one of: kUnknown_SkColorType, kAlpha_8_SkColorType,
kRGB_565_SkColorType, kARGB_4444_SkColorType, kRGBA_8888_SkColorType,
kRGB_888x_SkColorType, kBGRA_8888_SkColorType, kRGBA_1010102_SkColorType,
kRGB_101010x_SkColorType, kGray_8_SkColorType, kRGBA_F16_SkColorType.
/** Returns SkColorType, one of:
kUnknown_SkColorType, kAlpha_8_SkColorType, kRGB_565_SkColorType,
kARGB_4444_SkColorType, kRGBA_8888_SkColorType, kRGB_888x_SkColorType,
kBGRA_8888_SkColorType, kRGBA_1010102_SkColorType, kRGB_101010x_SkColorType,
kGray_8_SkColorType, kRGBA_F16_SkColorType.
@return SkColorType in SkImageInfo
*/
SkColorType colorType() const { return fInfo.colorType(); }
/** Returns SkAlphaType, one of: kUnknown_SkAlphaType, kOpaque_SkAlphaType,
kPremul_SkAlphaType, kUnpremul_SkAlphaType.
/** Returns SkAlphaType, one of:
kUnknown_SkAlphaType, kOpaque_SkAlphaType, kPremul_SkAlphaType,
kUnpremul_SkAlphaType.
@return SkAlphaType in SkImageInfo
*/
SkAlphaType alphaType() const { return fInfo.alphaType(); }
/** Returns SkColorSpace associated with SkImageInfo. The
/** Returns SkColorSpace, the range of colors, associated with SkImageInfo. The
reference count of SkColorSpace is unchanged. The returned SkColorSpace is
immutable.
@return SkColorSpace, the range of colors, in SkImageInfo
@return SkColorSpace in SkImageInfo, or nullptr
*/
SkColorSpace* colorSpace() const { return fInfo.colorSpace(); }
@ -247,6 +259,16 @@ public:
*/
SkColor getColor(int x, int y) const;
/** Look up the pixel at (x,y) and return its alpha component, normalized to [0..1].
This is roughly equivalent to SkGetColorA(getColor()), but can be more efficent
(and more precise if the pixels store more than 8 bits per component).
@param x column index, zero or greater, and less than width()
@param y row index, zero or greater, and less than height()
@return alpha converted to normalized float
*/
float getAlphaf(int x, int y) const;
/** Returns readable pixel address at (x, y). Returns nullptr if SkPixelRef is nullptr.
Input is not validated: out of bounds values of x or y trigger an assert() if
@ -513,42 +535,6 @@ public:
return reinterpret_cast<uint16_t*>(writable_addr64(x, y));
}
/** Copies a SkRect of pixels to dstPixels. Copy starts at (srcX, srcY), and does not
exceed SkPixmap (width(), height()).
dstInfo specifies width, height, SkColorType, SkAlphaType, and
SkColorSpace of destination. dstRowBytes specifics the gap from one destination
row to the next. Returns true if pixels are copied. Returns false if
dstInfo.addr() equals nullptr, or dstRowBytes is less than dstInfo.minRowBytes().
Pixels are copied only if pixel conversion is possible. If SkPixmap colorType() is
kGray_8_SkColorType, or kAlpha_8_SkColorType; dstInfo.colorType() must match.
If SkPixmap colorType() is kGray_8_SkColorType, dstInfo.colorSpace() must match.
If SkPixmap alphaType() is kOpaque_SkAlphaType, dstInfo.alphaType() must
match. If SkPixmap colorSpace() is nullptr, dstInfo.colorSpace() must match. Returns
false if pixel conversion is not possible.
srcX and srcY may be negative to copy only top or left of source. Returns
false if width() or height() is zero or negative. Returns false if:
abs(srcX) >= Pixmap width(), or if abs(srcY) >= Pixmap height().
If behavior is SkTransferFunctionBehavior::kRespect: converts source
pixels to a linear space before converting to dstInfo.
If behavior is SkTransferFunctionBehavior::kIgnore: source
pixels are treated as if they are linear, regardless of how they are encoded.
@param dstInfo destination width, height, SkColorType, SkAlphaType, SkColorSpace
@param dstPixels destination pixel storage
@param dstRowBytes destination row length
@param srcX column index whose absolute value is less than width()
@param srcY row index whose absolute value is less than height()
@param behavior one of: SkTransferFunctionBehavior::kRespect,
SkTransferFunctionBehavior::kIgnore
@return true if pixels are copied to dstPixels
*/
bool readPixels(const SkImageInfo& dstInfo, void* dstPixels, size_t dstRowBytes,
int srcX, int srcY, SkTransferFunctionBehavior behavior) const;
/** Copies a SkRect of pixels to dstPixels. Copy starts at (0, 0), and does not
exceed SkPixmap (width(), height()).
@ -602,10 +588,7 @@ public:
@return true if pixels are copied to dstPixels
*/
bool readPixels(const SkImageInfo& dstInfo, void* dstPixels, size_t dstRowBytes, int srcX,
int srcY) const {
return this->readPixels(dstInfo, dstPixels, dstRowBytes, srcX, srcY,
SkTransferFunctionBehavior::kRespect);
}
int srcY) const;
/** Copies a SkRect of pixels to dst. Copy starts at (srcX, srcY), and does not
exceed SkPixmap (width(), height()). dst specifies width, height, SkColorType,

Просмотреть файл

@ -5,6 +5,16 @@
* found in the LICENSE file.
*/
/* Generated by tools/bookmaker from include/core/SkPoint.h and docs/SkPoint_Reference.bmh
on 2018-09-13 13:59:55. Additional documentation and examples can be found at:
https://skia.org/user/api/SkPoint_Reference
You may edit either file directly. Structural changes to public interfaces require
editing both files. After editing docs/SkPoint_Reference.bmh, run:
bookmaker -b docs -i include/core/SkPoint.h -p
to create an updated version of this file.
*/
#ifndef SkPoint_DEFINED
#define SkPoint_DEFINED
@ -12,58 +22,19 @@
#include "SkScalar.h"
#include "../private/SkSafe32.h"
/** \struct SkIPoint16
SkIPoint16 holds two 16 bit integer coordinates.
*/
struct SkIPoint16 {
int16_t fX; //!< x-axis value used by SkIPoint16
int16_t fY; //!< y-axis value used by SkIPoint16
/** Sets fX to x, fY to y. If SK_DEBUG is defined, asserts
if x or y does not fit in 16 bits.
@param x integer x-axis value of constructed SkIPoint
@param y integer y-axis value of constructed SkIPoint
@return SkIPoint16 (x, y)
*/
static constexpr SkIPoint16 Make(int x, int y) {
return {SkToS16(x), SkToS16(y)};
}
/** Returns x-axis value of SkIPoint16.
@return fX
*/
int16_t x() const { return fX; }
/** Returns y-axis value of SkIPoint.
@return fY
*/
int16_t y() const { return fY; }
/** Sets fX to x and fY to y.
@param x new value for fX
@param y new value for fY
*/
void set(int x, int y) {
fX = SkToS16(x);
fY = SkToS16(y);
}
};
struct SkIPoint;
/** SkIVector provides an alternative name for SkIPoint. SkIVector and SkIPoint
can be used interchangeably for all purposes.
*/
typedef SkIPoint SkIVector;
/** \struct SkIPoint
SkIPoint holds two 32 bit integer coordinates.
SkIPoint holds two 32-bit integer coordinates.
*/
struct SkIPoint {
int32_t fX; //!< x-axis value used by SkIPoint.
int32_t fY; //!< y-axis value used by SkIPoint.
int32_t fX; //!< x-axis value
int32_t fY; //!< y-axis value
/** Sets fX to x, fY to y.
@ -171,7 +142,8 @@ struct SkIPoint {
return { Sk32_sat_sub(a.fX, b.fX), Sk32_sat_sub(a.fY, b.fY) };
}
/** Returns SkIPoint resulting from SkIPoint a offset by ivector b, computed as: (a.fX + b.fX, a.fY + b.fY).
/** Returns SkIPoint resulting from SkIPoint a offset by ivector b, computed as:
(a.fX + b.fX, a.fY + b.fY).
Can also be used to offset SkIPoint b by ivector a, returning SkIPoint.
Can also be used to add ivector to ivector, returning ivector.
@ -186,22 +158,18 @@ struct SkIPoint {
};
struct SkPoint;
/** SkVector provides an alternative name for SkPoint. SkVector and SkPoint can
be used interchangeably for all purposes.
*/
typedef SkPoint SkVector;
/** \struct SkPoint
SkPoint holds two 32 bit floating point coordinates.
SkPoint holds two 32-bit floating point coordinates.
*/
struct SK_API SkPoint {
/** x-axis value used by both SkPoint and vector. May contain any value, including
infinities and NaN.
*/
SkScalar fX;
/** y-axis value used by both SkPoint and vector. May contain any value, including
infinities and NaN.
*/
SkScalar fY;
SkScalar fX; //!< x-axis value
SkScalar fY; //!< y-axis value
/** Sets fX to x, fY to y. Used both to set SkPoint and vector.
@ -310,7 +278,7 @@ struct SK_API SkPoint {
fY += dy;
}
/** Returns the Euclidean_Distance from origin, computed as:
/** Returns the Euclidean distance from origin, computed as:
sqrt(fX * fX + fY * fY)
@ -320,7 +288,7 @@ struct SK_API SkPoint {
*/
SkScalar length() const { return SkPoint::Length(fX, fY); }
/** Returns the Euclidean_Distance from origin, computed as:
/** Returns the Euclidean distance from origin, computed as:
sqrt(fX * fX + fY * fY)
@ -423,7 +391,7 @@ struct SK_API SkPoint {
return {fX * scale, fY * scale};
}
/** Multiplies SkPoint by scale. Sets SkPoint to: (fX * scale, fY * scale)
/** Multiplies SkPoint by scale. Sets SkPoint to: (fX * scale, fY * scale).
@param scale scalar to multiply by
@return reference to SkPoint
@ -494,7 +462,8 @@ struct SK_API SkPoint {
return {a.fX - b.fX, a.fY - b.fY};
}
/** Returns SkPoint resulting from SkPoint a offset by vector b, computed as: (a.fX + b.fX, a.fY + b.fY).
/** Returns SkPoint resulting from SkPoint a offset by vector b, computed as:
(a.fX + b.fX, a.fY + b.fY).
Can also be used to offset SkPoint b by vector a, returning SkPoint.
Can also be used to add vector to vector, returning vector.
@ -507,7 +476,7 @@ struct SK_API SkPoint {
return {a.fX + b.fX, a.fY + b.fY};
}
/** Returns the Euclidean_Distance from origin, computed as:
/** Returns the Euclidean distance from origin, computed as:
sqrt(x * x + y * y)
@ -532,7 +501,7 @@ struct SK_API SkPoint {
*/
static SkScalar Normalize(SkVector* vec);
/** Returns the Euclidean_Distance between a and b.
/** Returns the Euclidean distance between a and b.
@param a line end point
@param b line end point

Просмотреть файл

@ -134,6 +134,21 @@ struct SK_API SkPoint3 {
SkScalar dot(const SkPoint3& vec) const {
return DotProduct(*this, vec);
}
/** Returns the cross product of a and b, treating them as 3D vectors
*/
static SkPoint3 CrossProduct(const SkPoint3& a, const SkPoint3& b) {
SkPoint3 result;
result.fX = a.fY*b.fZ - a.fZ*b.fY;
result.fY = a.fZ*b.fX - a.fX*b.fZ;
result.fZ = a.fX*b.fY - a.fY*b.fX;
return result;
}
SkPoint3 cross(const SkPoint3& vec) const {
return CrossProduct(*this, vec);
}
};
typedef SkPoint3 SkVector3;

Просмотреть файл

@ -24,10 +24,6 @@
# error "must define either SK_DEBUG or SK_RELEASE"
#endif
#if defined(SK_SUPPORT_UNITTEST) && !defined(SK_DEBUG)
# error "can't have unittests without debug"
#endif
/**
* Matrix calculations may be float or double.
* The default is float, as that's what Chromium's using.
@ -73,14 +69,6 @@
# endif
#endif
#if defined(_MSC_VER) && SK_CPU_SSE_LEVEL >= SK_CPU_SSE_LEVEL_SSE2
#define SK_VECTORCALL __vectorcall
#elif defined(SK_CPU_ARM32) && defined(SK_ARM_HAS_NEON)
#define SK_VECTORCALL __attribute__((pcs("aapcs-vfp")))
#else
#define SK_VECTORCALL
#endif
#if !defined(SK_SUPPORT_GPU)
# define SK_SUPPORT_GPU 1
#endif
@ -107,12 +95,6 @@
# endif
#endif
///////////////////////////////////////////////////////////////////////////////
// TODO(mdempsky): Move elsewhere as appropriate.
#include <new>
///////////////////////////////////////////////////////////////////////////////
#ifdef SK_BUILD_FOR_WIN
@ -204,44 +186,11 @@
//////////////////////////////////////////////////////////////////////////////////////////////
#if defined SK_DEBUG && defined SK_BUILD_FOR_WIN
# ifdef free
# undef free
# endif
# include <crtdbg.h>
# undef free
#
# ifdef SK_DEBUGx
# if defined(SK_SIMULATE_FAILED_MALLOC) && defined(__cplusplus)
void * operator new(
size_t cb,
int nBlockUse,
const char * szFileName,
int nLine,
int foo
);
void * operator new[](
size_t cb,
int nBlockUse,
const char * szFileName,
int nLine,
int foo
);
void operator delete(
void *pUserData,
int, const char*, int, int
);
void operator delete(
void *pUserData
);
void operator delete[]( void * p );
# define DEBUG_CLIENTBLOCK new( _CLIENT_BLOCK, __FILE__, __LINE__, 0)
# else
# define DEBUG_CLIENTBLOCK new( _CLIENT_BLOCK, __FILE__, __LINE__)
# endif
# define new DEBUG_CLIENTBLOCK
# else
# define DEBUG_CLIENTBLOCK
# endif
#ifdef free
#undef free
#endif
#include <crtdbg.h>
#undef free
#endif
//////////////////////////////////////////////////////////////////////
@ -254,11 +203,6 @@
# endif
#endif
#if !defined(SK_ATTR_DEPRECATED)
// FIXME: we ignore msg for now...
# define SK_ATTR_DEPRECATED(msg) SK_ATTRIBUTE(deprecated)
#endif
/**
* If your judgment is better than the compiler's (i.e. you've profiled it),
* you can use SK_ALWAYS_INLINE to force inlining. E.g.
@ -326,16 +270,6 @@
//////////////////////////////////////////////////////////////////////
#ifndef SK_EGL
# if defined(SK_BUILD_FOR_ANDROID)
# define SK_EGL 1
# else
# define SK_EGL 0
# endif
#endif
//////////////////////////////////////////////////////////////////////
#if !defined(SK_GAMMA_EXPONENT)
#define SK_GAMMA_EXPONENT (0.0f) // SRGB
#endif

Просмотреть файл

@ -18,7 +18,8 @@
//////////////////////////////////////////////////////////////////////
#if !defined(SK_BUILD_FOR_ANDROID) && !defined(SK_BUILD_FOR_IOS) && !defined(SK_BUILD_FOR_WIN) && !defined(SK_BUILD_FOR_UNIX) && !defined(SK_BUILD_FOR_MAC)
#if !defined(SK_BUILD_FOR_ANDROID) && !defined(SK_BUILD_FOR_IOS) && !defined(SK_BUILD_FOR_WIN) && \
!defined(SK_BUILD_FOR_UNIX) && !defined(SK_BUILD_FOR_MAC)
#ifdef __APPLE__
#include "TargetConditionals.h"
@ -111,6 +112,7 @@
#define SK_CPU_SSE_LEVEL_SSE42 42
#define SK_CPU_SSE_LEVEL_AVX 51
#define SK_CPU_SSE_LEVEL_AVX2 52
#define SK_CPU_SSE_LEVEL_AVX512 60
// When targetting iOS and using gyp to generate the build files, it is not
// possible to select files to build depending on the architecture (i.e. it
@ -120,11 +122,13 @@
#define SK_CPU_SSE_LEVEL 0
#endif
// Are we in GCC?
// Are we in GCC/Clang?
#ifndef SK_CPU_SSE_LEVEL
// These checks must be done in descending order to ensure we set the highest
// available SSE level.
#if defined(__AVX2__)
#if defined(__AVX512F__)
#define SK_CPU_SSE_LEVEL SK_CPU_SSE_LEVEL_AVX512
#elif defined(__AVX2__)
#define SK_CPU_SSE_LEVEL SK_CPU_SSE_LEVEL_AVX2
#elif defined(__AVX__)
#define SK_CPU_SSE_LEVEL SK_CPU_SSE_LEVEL_AVX
@ -165,35 +169,12 @@
#if defined(__arm__) && (!defined(__APPLE__) || !TARGET_IPHONE_SIMULATOR)
#define SK_CPU_ARM32
#if defined(__GNUC__)
#if defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_7A__) \
|| defined(__ARM_ARCH_7R__) || defined(__ARM_ARCH_7M__) \
|| defined(__ARM_ARCH_7EM__) || defined(_ARM_ARCH_7)
#define SK_ARM_ARCH 7
#elif defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) \
|| defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6Z__) \
|| defined(__ARM_ARCH_6ZK__) || defined(__ARM_ARCH_6T2__) \
|| defined(__ARM_ARCH_6M__) || defined(_ARM_ARCH_6)
#define SK_ARM_ARCH 6
#elif defined(__ARM_ARCH_5__) || defined(__ARM_ARCH_5T__) \
|| defined(__ARM_ARCH_5E__) || defined(__ARM_ARCH_5TE__) \
|| defined(__ARM_ARCH_5TEJ__) || defined(_ARM_ARCH_5)
#define SK_ARM_ARCH 5
#elif defined(__ARM_ARCH_4__) || defined(__ARM_ARCH_4T__) || defined(_ARM_ARCH_4)
#define SK_ARM_ARCH 4
#else
#define SK_ARM_ARCH 3
#endif
#endif
#endif
#if defined(__aarch64__) && !defined(SK_BUILD_NO_OPTS)
#elif defined(__aarch64__) && !defined(SK_BUILD_NO_OPTS)
#define SK_CPU_ARM64
#endif
// All 64-bit ARM chips have NEON. Many 32-bit ARM chips do too.
#if !defined(SK_ARM_HAS_NEON) && !defined(SK_BUILD_NO_OPTS) && (defined(__ARM_NEON__) || defined(__ARM_NEON))
#if !defined(SK_ARM_HAS_NEON) && !defined(SK_BUILD_NO_OPTS) && defined(__ARM_NEON)
#define SK_ARM_HAS_NEON
#endif
@ -225,48 +206,4 @@
#endif
#endif
//////////////////////////////////////////////////////////////////////
/**
* Use SK_PURE_FUNC as an attribute to indicate that a function's
* return value only depends on the value of its parameters. This
* can help the compiler optimize out successive calls.
*
* Usage:
* void function(int params) SK_PURE_FUNC;
*/
#if defined(__GNUC__)
# define SK_PURE_FUNC __attribute__((pure))
#else
# define SK_PURE_FUNC /* nothing */
#endif
//////////////////////////////////////////////////////////////////////
/**
* SK_HAS_ATTRIBUTE(<name>) should return true iff the compiler
* supports __attribute__((<name>)). Mostly important because
* Clang doesn't support all of GCC attributes.
*/
#if defined(__has_attribute)
# define SK_HAS_ATTRIBUTE(x) __has_attribute(x)
#elif defined(__GNUC__)
# define SK_HAS_ATTRIBUTE(x) 1
#else
# define SK_HAS_ATTRIBUTE(x) 0
#endif
/**
* SK_ATTRIBUTE_OPTIMIZE_O1 can be used as a function attribute
* to specify individual optimization level of -O1, if the compiler
* supports it.
*
* NOTE: Clang/ARM (r161757) does not support the 'optimize' attribute.
*/
#if SK_HAS_ATTRIBUTE(optimize)
# define SK_ATTRIBUTE_OPTIMIZE_O1 __attribute__((optimize("O1")))
#else
# define SK_ATTRIBUTE_OPTIMIZE_O1 /* nothing */
#endif
#endif

Просмотреть файл

@ -5,6 +5,16 @@
* found in the LICENSE file.
*/
/* Generated by tools/bookmaker from include/core/SkRRect.h and docs/SkRRect_Reference.bmh
on 2018-08-10 12:59:44. Additional documentation and examples can be found at:
https://skia.org/user/api/SkRRect_Reference
You may edit either file directly. Structural changes to public interfaces require
editing both files. After editing docs/SkRRect_Reference.bmh, run:
bookmaker -b docs -i include/core/SkRRect.h -p
to create an updated version of this file.
*/
#ifndef SkRRect_DEFINED
#define SkRRect_DEFINED
@ -13,92 +23,78 @@
class SkPath;
class SkMatrix;
class SkRBuffer;
class SkWBuffer;
// Path forward:
// core work
// add contains(SkRect&) - for clip stack
// add contains(SkRRect&) - for clip stack
// add heart rect computation (max rect inside RR)
// add 9patch rect computation
// add growToInclude(SkPath&)
// analysis
// use growToInclude to fit skp round rects & generate stats (RRs vs. real paths)
// check on # of rectorus's the RRs could handle
// rendering work
// update SkPath.addRRect() to only use quads
// add GM and bench
// further out
// detect and triangulate RRectorii rather than falling back to SW in Ganesh
//
/** \class SkRRect
SkRRect describes a rounded rectangle with a bounds and a pair of radii for each corner.
The bounds and radii can be set so that SkRRect describes: a rectangle with sharp corners;
a circle; an oval; or a rectangle with one or more rounded corners.
The SkRRect class represents a rounded rect with a potentially different
radii for each corner. It does not have a constructor so must be
initialized with one of the initialization functions (e.g., setEmpty,
setRectRadii, etc.)
SkRRect allows implementing CSS properties that describe rounded corners.
SkRRect may have up to eight different radii, one for each axis on each of its four
corners.
This class is intended to roughly match CSS' border-*-*-radius capabilities.
This means:
If either of a corner's radii are 0 the corner will be square.
Negative radii are not allowed (they are clamped to zero).
If the corner curves overlap they will be proportionally reduced to fit.
SkRRect may modify the provided parameters when initializing bounds and radii.
If either axis radii is zero or less: radii are stored as zero; corner is square.
If corner curves overlap, radii are proportionally reduced to fit within bounds.
*/
class SK_API SkRRect {
public:
/** Default initialized to a rrect at the origin with zero width and height. */
/** Initializes bounds at (0, 0), the origin, with zero width and height.
Initializes corner radii to (0, 0), and sets type of kEmpty_Type.
@return empty SkRRect
*/
SkRRect() = default;
SkRRect(const SkRRect&) = default;
SkRRect& operator=(const SkRRect&) = default;
/** Initializes to copy of rrect bounds and corner radii.
/**
* Enum to capture the various possible subtypes of RR. Accessed
* by type(). The subtypes become progressively less restrictive.
*/
@param rrect bounds and corner to copy
@return copy of rrect
*/
SkRRect(const SkRRect& rrect) = default;
/** Copies rrect bounds and corner radii.
@param rrect bounds and corner to copy
@return copy of rrect
*/
SkRRect& operator=(const SkRRect& rrect) = default;
/** \enum SkRRect::Type
Type describes possible specializations of SkRRect. Each Type is
exclusive; a SkRRect may only have one type.
Type members become progressively less restrictive; larger values of
Type have more degrees of freedom than smaller values.
*/
enum Type {
// !< The RR has zero width and/or zero height. All radii are zero.
kEmpty_Type,
//!< The RR is actually a (non-empty) rect (i.e., at least one radius
//!< at each corner is zero)
kRect_Type,
//!< The RR is actually a (non-empty) oval (i.e., all x radii are equal
//!< and >= width/2 and all the y radii are equal and >= height/2
kOval_Type,
//!< The RR is non-empty and all the x radii are equal & all y radii
//!< are equal but it is not an oval (i.e., there are lines between
//!< the curves) nor a rect (i.e., both radii are non-zero)
kSimple_Type,
//!< The RR is non-empty and the two left x radii are equal, the two top
//!< y radii are equal, and the same for the right and bottom but it is
//!< neither an rect, oval, nor a simple RR. It is called "nine patch"
//!< because the centers of the corner ellipses form an axis aligned
//!< rect with edges that divide the RR into an 9 rectangular patches:
//!< an interior patch, four edge patches, and four corner patches.
kNinePatch_Type,
//!< A fully general (non-empty) RR. Some of the x and/or y radii are
//!< different from the others and there must be one corner where
//!< both radii are non-zero.
kComplex_Type,
kLastType = kComplex_Type,
kEmpty_Type, //!< zero width or height
kRect_Type, //!< non-zero width and height, and zeroed radii
kOval_Type, //!< non-zero width and height filled with radii
kSimple_Type, //!< non-zero width and height with equal radii
kNinePatch_Type, //!< non-zero width and height with axis-aligned radii
kComplex_Type, //!< non-zero width and height with arbitrary radii
kLastType = kComplex_Type, //!< largest Type value
};
/**
* Returns the RR's sub type.
*/
/** Returns SkRRect::Type, one of:
kEmpty_Type, kRect_Type, kOval_Type, kSimple_Type, kNinePatch_Type,
kComplex_Type.
@return SkRRect::Type
*/
Type getType() const {
SkASSERT(this->isValid());
return static_cast<Type>(fType);
}
/** Returns SkRRect::Type, one of:
kEmpty_Type, kRect_Type, kOval_Type, kSimple_Type, kNinePatch_Type,
kComplex_Type.
@return SkRRect::Type
*/
Type type() const { return this->getType(); }
inline bool isEmpty() const { return kEmpty_Type == this->getType(); }
@ -108,26 +104,42 @@ public:
inline bool isNinePatch() const { return kNinePatch_Type == this->getType(); }
inline bool isComplex() const { return kComplex_Type == this->getType(); }
/** Returns span on the x-axis. This does not check if result fits in 32-bit float;
result may be infinity.
@return bounds().fRight minus bounds().fLeft
*/
SkScalar width() const { return fRect.width(); }
/** Returns span on the y-axis. This does not check if result fits in 32-bit float;
result may be infinity.
@return bounds().fBottom minus bounds().fTop
*/
SkScalar height() const { return fRect.height(); }
/**
* kSimple means that all corners have the same x,y radii. This returns the top/left
* corner's radii as representative of all corners. If the RRect is kComplex, then
* this still returns that corner's radii, but it is not indicative of the other corners.
*/
/** Returns top-left corner radii. If type() returns kEmpty_Type, kRect_Type,
kOval_Type, or kSimple_Type, returns a value representative of all corner radii.
If type() returns kNinePatch_Type or kComplex_Type, at least one of the
remaining three corners has a different value.
@return corner radii for simple types
*/
SkVector getSimpleRadii() const {
return fRadii[0];
}
/**
* Same as default initialized - zero width and height at the origin.
*/
/** Sets bounds to zero width and height at (0, 0), the origin. Sets
corner radii to zero and sets type to kEmpty_Type.
*/
void setEmpty() { *this = SkRRect(); }
/**
* Set this RR to match the supplied rect. All radii will be 0.
*/
/** Sets bounds to sorted rect, and sets corner radii to zero.
If set bounds has width and height, and sets type to kRect_Type;
otherwise, sets type to kEmpty_Type.
@param rect bounds to set
*/
void setRect(const SkRect& rect) {
if (!this->initializeRect(rect)) {
return;
@ -139,31 +151,61 @@ public:
SkASSERT(this->isValid());
}
/** Makes an empty rrect at the origin with zero width and height. */
/** Initializes bounds at (0, 0), the origin, with zero width and height.
Initializes corner radii to (0, 0), and sets type of kEmpty_Type.
@return empty SkRRect
*/
static SkRRect MakeEmpty() { return SkRRect(); }
/** Initializes to copy of r bounds and zeroes corner radii.
@param r bounds to copy
@return copy of r
*/
static SkRRect MakeRect(const SkRect& r) {
SkRRect rr;
rr.setRect(r);
return rr;
}
/** Sets bounds to oval, x-axis radii to half oval.width(), and all y-axis radii
to half oval.height(). If oval bounds is empty, sets to kEmpty_Type.
Otherwise, sets to kOval_Type.
@param oval bounds of oval
@return oval
*/
static SkRRect MakeOval(const SkRect& oval) {
SkRRect rr;
rr.setOval(oval);
return rr;
}
/** Sets to rounded rectangle with the same radii for all four corners.
If rect is empty, sets to kEmpty_Type.
Otherwise, if xRad and yRad are zero, sets to kRect_Type.
Otherwise, if xRad is at least half rect.width() and yRad is at least half
rect.height(), sets to kOval_Type.
Otherwise, sets to kSimple_Type.
@param rect bounds of rounded rectangle
@param xRad x-axis radius of corners
@param yRad y-axis radius of corners
@return rounded rectangle
*/
static SkRRect MakeRectXY(const SkRect& rect, SkScalar xRad, SkScalar yRad) {
SkRRect rr;
rr.setRectXY(rect, xRad, yRad);
return rr;
}
/**
* Set this RR to match the supplied oval. All x radii will equal half the
* width and all y radii will equal half the height.
*/
/** Sets bounds to oval, x-axis radii to half oval.width(), and all y-axis radii
to half oval.height(). If oval bounds is empty, sets to kEmpty_Type.
Otherwise, sets to kOval_Type.
@param oval bounds of oval
*/
void setOval(const SkRect& oval) {
if (!this->initializeRect(oval)) {
return;
@ -180,135 +222,278 @@ public:
SkASSERT(this->isValid());
}
/**
* Initialize the RR with the same radii for all four corners.
*/
/** Sets to rounded rectangle with the same radii for all four corners.
If rect is empty, sets to kEmpty_Type.
Otherwise, if xRad or yRad is zero, sets to kRect_Type.
Otherwise, if xRad is at least half rect.width() and yRad is at least half
rect.height(), sets to kOval_Type.
Otherwise, sets to kSimple_Type.
@param rect bounds of rounded rectangle
@param xRad x-axis radius of corners
@param yRad y-axis radius of corners
*/
void setRectXY(const SkRect& rect, SkScalar xRad, SkScalar yRad);
/**
* Initialize the rr with one radius per-side.
*/
/** Sets bounds to rect. Sets radii to (leftRad, topRad), (rightRad, topRad),
(rightRad, bottomRad), (leftRad, bottomRad).
If rect is empty, sets to kEmpty_Type.
Otherwise, if leftRad and rightRad are zero, sets to kRect_Type.
Otherwise, if topRad and bottomRad are zero, sets to kRect_Type.
Otherwise, if leftRad and rightRad are equal and at least half rect.width(), and
topRad and bottomRad are equal at least half rect.height(), sets to kOval_Type.
Otherwise, if leftRad and rightRad are equal, and topRad and bottomRad are equal,
sets to kSimple_Type. Otherwise, sets to kNinePatch_Type.
Nine patch refers to the nine parts defined by the radii: one center rectangle,
four edge patches, and four corner patches.
@param rect bounds of rounded rectangle
@param leftRad left-top and left-bottom x-axis radius
@param topRad left-top and right-top y-axis radius
@param rightRad right-top and right-bottom x-axis radius
@param bottomRad left-bottom and right-bottom y-axis radius
*/
void setNinePatch(const SkRect& rect, SkScalar leftRad, SkScalar topRad,
SkScalar rightRad, SkScalar bottomRad);
/**
* Initialize the RR with potentially different radii for all four corners.
*/
/** Sets bounds to rect. Sets radii array for individual control of all for corners.
If rect is empty, sets to kEmpty_Type.
Otherwise, if one of each corner radii are zero, sets to kRect_Type.
Otherwise, if all x-axis radii are equal and at least half rect.width(), and
all y-axis radii are equal at least half rect.height(), sets to kOval_Type.
Otherwise, if all x-axis radii are equal, and all y-axis radii are equal,
sets to kSimple_Type. Otherwise, sets to kNinePatch_Type.
@param rect bounds of rounded rectangle
@param radii corner x-axis and y-axis radii
*/
void setRectRadii(const SkRect& rect, const SkVector radii[4]);
// The radii are stored in UL, UR, LR, LL order.
/** \enum SkRRect::Corner
The radii are stored: top-left, top-right, bottom-right, bottom-left.
*/
enum Corner {
kUpperLeft_Corner,
kUpperRight_Corner,
kLowerRight_Corner,
kLowerLeft_Corner
kUpperLeft_Corner, //!< index of top-left corner radii
kUpperRight_Corner, //!< index of top-right corner radii
kLowerRight_Corner, //!< index of bottom-right corner radii
kLowerLeft_Corner, //!< index of bottom-left corner radii
};
/** Returns bounds. Bounds may have zero width or zero height. Bounds right is
greater than or equal to left; bounds bottom is greater than or equal to top.
Result is identical to getBounds().
@return bounding box
*/
const SkRect& rect() const { return fRect; }
/** Returns scalar pair for radius of curve on x-axis and y-axis for one corner.
Both radii may be zero. If not zero, both are positive and finite.
@param corner one of: kUpperLeft_Corner, kUpperRight_Corner,
kLowerRight_Corner, kLowerLeft_Corner
@return x-axis and y-axis radii for one corner
*/
SkVector radii(Corner corner) const { return fRadii[corner]; }
/** Returns bounds. Bounds may have zero width or zero height. Bounds right is
greater than or equal to left; bounds bottom is greater than or equal to top.
Result is identical to rect().
@return bounding box
*/
const SkRect& getBounds() const { return fRect; }
/** Returns true if bounds and radii in a are equal to bounds and radii in b.
a and b are not equal if either contain NaN. a and b are equal if members
contain zeroes width different signs.
@param a SkRect bounds and radii to compare
@param b SkRect bounds and radii to compare
@return true if members are equal
*/
friend bool operator==(const SkRRect& a, const SkRRect& b) {
return a.fRect == b.fRect && SkScalarsEqual(&a.fRadii[0].fX, &b.fRadii[0].fX, 8);
}
/** Returns true if bounds and radii in a are not equal to bounds and radii in b.
a and b are not equal if either contain NaN. a and b are equal if members
contain zeroes width different signs.
@param a SkRect bounds and radii to compare
@param b SkRect bounds and radii to compare
@return true if members are not equal
*/
friend bool operator!=(const SkRRect& a, const SkRRect& b) {
return a.fRect != b.fRect || !SkScalarsEqual(&a.fRadii[0].fX, &b.fRadii[0].fX, 8);
}
/**
* Call inset on the bounds, and adjust the radii to reflect what happens
* in stroking: If the corner is sharp (no curvature), leave it alone,
* otherwise we grow/shrink the radii by the amount of the inset. If a
* given radius becomes negative, it is pinned to 0.
*
* If the inset amount is larger than the width/height then the rrect collapses to
* a degenerate line or point.
*
* If the inset is sufficiently negative to cause the bounds to become infinite then
* the result is a default initialized rrect.
*
* It is valid for dst == this.
*/
/** Copies SkRRect to dst, then insets dst bounds by dx and dy, and adjusts dst
radii by dx and dy. dx and dy may be positive, negative, or zero. dst may be
SkRRect.
If either corner radius is zero, the corner has no curvature and is unchanged.
Otherwise, if adjusted radius becomes negative, pins radius to zero.
If dx exceeds half dst bounds width, dst bounds left and right are set to
bounds x-axis center. If dy exceeds half dst bounds height, dst bounds top and
bottom are set to bounds y-axis center.
If dx or dy cause the bounds to become infinite, dst bounds is zeroed.
@param dx added to rect().fLeft, and subtracted from rect().fRight
@param dy added to rect().fTop, and subtracted from rect().fBottom
@param dst insets bounds and radii
*/
void inset(SkScalar dx, SkScalar dy, SkRRect* dst) const;
/** Insets bounds by dx and dy, and adjusts radii by dx and dy. dx and dy may be
positive, negative, or zero.
If either corner radius is zero, the corner has no curvature and is unchanged.
Otherwise, if adjusted radius becomes negative, pins radius to zero.
If dx exceeds half bounds width, bounds left and right are set to
bounds x-axis center. If dy exceeds half bounds height, bounds top and
bottom are set to bounds y-axis center.
If dx or dy cause the bounds to become infinite, bounds is zeroed.
@param dx added to rect().fLeft, and subtracted from rect().fRight
@param dy added to rect().fTop, and subtracted from rect().fBottom
*/
void inset(SkScalar dx, SkScalar dy) {
this->inset(dx, dy, this);
}
/**
* Call outset on the bounds, and adjust the radii to reflect what happens
* in stroking: If the corner is sharp (no curvature), leave it alone,
* otherwise we grow/shrink the radii by the amount of the inset. If a
* given radius becomes negative, it is pinned to 0.
*
* It is valid for dst == this.
*/
/** Outsets dst bounds by dx and dy, and adjusts radii by dx and dy. dx and dy may be
positive, negative, or zero.
If either corner radius is zero, the corner has no curvature and is unchanged.
Otherwise, if adjusted radius becomes negative, pins radius to zero.
If dx exceeds half dst bounds width, dst bounds left and right are set to
bounds x-axis center. If dy exceeds half dst bounds height, dst bounds top and
bottom are set to bounds y-axis center.
If dx or dy cause the bounds to become infinite, dst bounds is zeroed.
@param dx subtracted from rect().fLeft, and added to rect().fRight
@param dy subtracted from rect().fTop, and added to rect().fBottom
@param dst outset bounds and radii
*/
void outset(SkScalar dx, SkScalar dy, SkRRect* dst) const {
this->inset(-dx, -dy, dst);
}
/** Outsets bounds by dx and dy, and adjusts radii by dx and dy. dx and dy may be
positive, negative, or zero.
If either corner radius is zero, the corner has no curvature and is unchanged.
Otherwise, if adjusted radius becomes negative, pins radius to zero.
If dx exceeds half bounds width, bounds left and right are set to
bounds x-axis center. If dy exceeds half bounds height, bounds top and
bottom are set to bounds y-axis center.
If dx or dy cause the bounds to become infinite, bounds is zeroed.
@param dx subtracted from rect().fLeft, and added to rect().fRight
@param dy subtracted from rect().fTop, and added to rect().fBottom
*/
void outset(SkScalar dx, SkScalar dy) {
this->inset(-dx, -dy, this);
}
/**
* Translate the rrect by (dx, dy).
*/
/** Translates SkRRect by (dx, dy).
@param dx offset added to rect().fLeft and rect().fRight
@param dy offset added to rect().fTop and rect().fBottom
*/
void offset(SkScalar dx, SkScalar dy) {
fRect.offset(dx, dy);
}
/** Returns SkRRect translated by (dx, dy).
@param dx offset added to rect().fLeft and rect().fRight
@param dy offset added to rect().fTop and rect().fBottom
@return SkRRect bounds offset by (dx, dy), with unchanged corner radii
*/
SkRRect SK_WARN_UNUSED_RESULT makeOffset(SkScalar dx, SkScalar dy) const {
return SkRRect(fRect.makeOffset(dx, dy), fRadii, fType);
}
/**
* Returns true if 'rect' is wholy inside the RR, and both
* are not empty.
*/
/** Returns true if rect is inside the bounds and corner radii, and if
SkRRect and rect are not empty.
@param rect area tested for containment
@return true if SkRRect contains rect
*/
bool contains(const SkRect& rect) const;
/** Returns true if bounds and radii values are finite and describe a SkRRect
SkRRect::Type that matches getType(). All SkRRect methods construct valid types,
even if the input values are not valid. Invalid SkRRect data can only
be generated by corrupting memory.
@return true if bounds and radii match type()
*/
bool isValid() const;
enum {
kSizeInMemory = 12 * sizeof(SkScalar)
};
static constexpr size_t kSizeInMemory = 12 * sizeof(SkScalar);
/**
* Write the rrect into the specified buffer. This is guaranteed to always
* write kSizeInMemory bytes, and that value is guaranteed to always be
* a multiple of 4. Return kSizeInMemory.
*/
/** Writes SkRRect to buffer. Writes kSizeInMemory bytes, and returns
kSizeInMemory, the number of bytes written.
@param buffer storage for SkRRect
@return bytes written, kSizeInMemory
*/
size_t writeToMemory(void* buffer) const;
void writeToBuffer(SkWBuffer*) const;
/**
* Reads the rrect from the specified buffer
*
* If the specified buffer is large enough, this will read kSizeInMemory bytes,
* and that value is guaranteed to always be a multiple of 4.
*
* @param buffer Memory to read from
* @param length Amount of memory available in the buffer
* @return number of bytes read (must be a multiple of 4) or
* 0 if there was not enough memory available
*/
/** Reads SkRRect from buffer, reading kSizeInMemory bytes.
Returns kSizeInMemory, bytes read if length is at least kSizeInMemory.
Otherwise, returns zero.
@param buffer memory to read from
@param length size of buffer
@return bytes read, or 0 if length is less than kSizeInMemory
*/
size_t readFromMemory(const void* buffer, size_t length);
bool readFromBuffer(SkRBuffer*);
/**
* Transform by the specified matrix, and put the result in dst.
*
* @param matrix SkMatrix specifying the transform. Must only contain
* scale and/or translate, or this call will fail.
* @param dst SkRRect to store the result. It is an error to use this,
* which would make this function no longer const.
* @return true on success, false on failure.
*/
/** Transforms by SkRRect by matrix, storing result in dst.
Returns true if SkRRect transformed can be represented by another SkRRect.
Returns false if matrix contains transformations other than scale and translate.
Asserts in debug builds if SkRRect equals dst.
@param matrix SkMatrix specifying the transform
@param dst SkRRect to store the result
@return true if transformation succeeded.
*/
bool transform(const SkMatrix& matrix, SkRRect* dst) const;
/** Writes text representation of SkRRect to standard output.
Set asHex true to generate exact binary representations
of floating point numbers.
@param asHex true if SkScalar values are written as hexadecimal
*/
void dump(bool asHex) const;
/** Writes text representation of SkRRect to standard output. The representation
may be directly compiled as C++ code. Floating point values are written
with limited precision; it may not be possible to reconstruct original
SkRRect from output.
*/
void dump() const { this->dump(false); }
/** Writes text representation of SkRRect to standard output. The representation
may be directly compiled as C++ code. Floating point values are written
in hexadecimal to preserve their exact bit pattern. The output reconstructs the
original SkRRect.
*/
void dumpHex() const { this->dump(true); }
private:
@ -327,7 +512,7 @@ private:
void computeType();
bool checkCornerContainment(SkScalar x, SkScalar y) const;
void scaleRadii();
void scaleRadii(const SkRect& rect);
SkRect fRect = SkRect::MakeEmpty();
// Radii order is UL, UR, LR, LL. Use Corner enum to index into fRadii[]

Просмотреть файл

@ -5,6 +5,16 @@
* found in the LICENSE file.
*/
/* Generated by tools/bookmaker from include/core/SkRect.h and docs/SkRect_Reference.bmh
on 2018-09-13 13:59:55. Additional documentation and examples can be found at:
https://skia.org/user/api/SkRect_Reference
You may edit either file directly. Structural changes to public interfaces require
editing both files. After editing docs/SkRect_Reference.bmh, run:
bookmaker -b docs -i include/core/SkRect.h -p
to create an updated version of this file.
*/
#ifndef SkRect_DEFINED
#define SkRect_DEFINED
@ -13,36 +23,22 @@
#include "../private/SkSafe32.h"
#include "../private/SkTFitsIn.h"
#include <utility>
struct SkRect;
/** \struct SkIRect
SkIRect holds four 32 bit integer coordinates describing the upper and
SkIRect holds four 32-bit integer coordinates describing the upper and
lower bounds of a rectangle. SkIRect may be created from outer bounds or
from position, width, and height. SkIRect describes an area; if its right
is less than or equal to its left, or if its bottom is less than or equal to
its top, it is considered empty.
*/
struct SK_API SkIRect {
/** May contain any value. The smaller of the horizontal values when sorted.
When equal to or greater than fRight, SkIRect is empty.
*/
int32_t fLeft;
/** May contain any value. The smaller of the horizontal values when sorted.
When equal to or greater than fBottom, SkIRect is empty.
*/
int32_t fTop;
/** May contain any value. The larger of the vertical values when sorted.
When equal to or less than fLeft, SkIRect is empty.
*/
int32_t fRight;
/** May contain any value. The larger of the vertical values when sorted.
When equal to or less than fTop, SkIRect is empty.
*/
int32_t fBottom;
int32_t fLeft; //!< smaller x-axis bounds
int32_t fTop; //!< smaller y-axis bounds
int32_t fRight; //!< larger x-axis bounds
int32_t fBottom; //!< larger y-axis bounds
/** Returns constructed SkIRect set to (0, 0, 0, 0).
Many other rectangles are empty; if left is equal to or greater than right,
@ -98,8 +94,8 @@ struct SK_API SkIRect {
return SkIRect{l, t, r, b};
}
/** Returns constructed SkIRect set to: (x, y, x + w, y + h). Does not validate input;
w or h may be negative.
/** Returns constructed SkIRect set to: (x, y, x + w, y + h).
Does not validate input; w or h may be negative.
@param x stored in fLeft
@param y stored in fTop
@ -175,24 +171,6 @@ struct SK_API SkIRect {
*/
SkISize size() const { return SkISize::Make(this->width(), this->height()); }
/** Returns average of left edge and right edge. Result does not change if SkIRect
is sorted. Result may be incorrect if SkIRect is far from the origin.
Result is rounded down.
@return midpoint in x
*/
int32_t centerX() const { return SkToS32(((int64_t)fRight + fLeft) >> 1); }
/** Returns average of top edge and bottom edge. Result does not change if SkIRect
is sorted. Result may be incorrect if SkIRect is far from the origin.
Result is rounded down.
@return midpoint in y
*/
int32_t centerY() const { return SkToS32(((int64_t)fBottom + fTop) >> 1); }
/** Returns span on the x-axis. This does not check if SkIRect is sorted, so the
result may be negative. This is safer than calling width() since width() might
overflow in its calculation.
@ -217,7 +195,7 @@ struct SK_API SkIRect {
*/
bool isEmpty64() const { return fRight <= fLeft || fBottom <= fTop; }
/** Returns true if width() or height() .
/** Returns true if width() or height() are zero or negative.
@return true if width() or height() are zero or negative
*/
@ -228,7 +206,7 @@ struct SK_API SkIRect {
return true;
}
// Return true if either exceeds int32_t
return !sk_64_isS32(w | h);
return !SkTFitsIn<int32_t>(w | h);
}
/** Returns true if all members in a: fLeft, fTop, fRight, and fBottom; are
@ -253,16 +231,6 @@ struct SK_API SkIRect {
return !(a == b);
}
/** Returns true if all members: fLeft, fTop, fRight, and fBottom; values are
equal to or larger than -32768 and equal to or smaller than 32767.
@return true if members fit in 16-bit word
*/
bool is16Bit() const {
return SkTFitsIn<int16_t>(fLeft) && SkTFitsIn<int16_t>(fTop) &&
SkTFitsIn<int16_t>(fRight) && SkTFitsIn<int16_t>(fBottom);
}
/** Sets SkIRect to (0, 0, 0, 0).
Many other rectangles are empty; if left is equal to or greater than right,
@ -300,8 +268,8 @@ struct SK_API SkIRect {
this->set(left, top, right, bottom);
}
/** Sets SkIRect to: (x, y, x + width, y + height). Does not validate input;
width or height may be negative.
/** Sets SkIRect to: (x, y, x + width, y + height).
Does not validate input; width or height may be negative.
@param x stored in fLeft
@param y stored in fTop
@ -324,7 +292,7 @@ struct SK_API SkIRect {
@param dx offset added to fLeft and fRight
@param dy offset added to fTop and fBottom
@return SkIRect offset in x or y, with original width and height
@return SkIRect offset by dx and dy, with original width and height
*/
SkIRect makeOffset(int32_t dx, int32_t dy) const {
return {
@ -442,20 +410,27 @@ struct SK_API SkIRect {
*/
void outset(int32_t dx, int32_t dy) { this->inset(-dx, -dy); }
/** Constructs SkIRect (l, t, r, b) and returns true if constructed SkIRect does not
intersect SkIRect. Does not check to see if construction or SkIRect is empty.
/** Adjusts SkIRect by adding dL to fLeft, dT to fTop, dR to fRight, and dB to fBottom.
Is implemented with short circuit logic so that true can be returned after
a single compare.
If dL is positive, narrows SkIRect on the left. If negative, widens it on the left.
If dT is positive, shrinks SkIRect on the top. If negative, lengthens it on the top.
If dR is positive, narrows SkIRect on the right. If negative, widens it on the right.
If dB is positive, shrinks SkIRect on the bottom. If negative, lengthens it on the bottom.
@param l x minimum of constructed SkIRect
@param t y minimum of constructed SkIRect
@param r x maximum of constructed SkIRect
@param b y maximum of constructed SkIRect
@return true if construction and SkIRect have no area in common
The resulting SkIRect is not checked for validity. Thus, if the resulting SkIRect left is
greater than right, the SkIRect will be considered empty. Call sort() after this call
if that is not the desired behavior.
@param dL offset added to fLeft
@param dT offset added to fTop
@param dR offset added to fRight
@param dB offset added to fBottom
*/
bool quickReject(int l, int t, int r, int b) const {
return l >= fRight || fLeft >= r || t >= fBottom || fTop >= b;
void adjust(int32_t dL, int32_t dT, int32_t dR, int32_t dB) {
fLeft = Sk32_sat_add(fLeft, dL);
fTop = Sk32_sat_add(fTop, dT);
fRight = Sk32_sat_add(fRight, dR);
fBottom = Sk32_sat_add(fBottom, dB);
}
/** Returns true if: fLeft <= x < fRight && fTop <= y < fBottom.
@ -478,10 +453,10 @@ struct SK_API SkIRect {
Returns true if SkIRect contains construction.
Returns false if SkIRect is empty or construction is empty.
@param left x minimum of constructed SkIRect
@param top y minimum of constructed SkIRect
@param right x maximum of constructed SkIRect
@param bottom y maximum of constructed SkIRect
@param left x-axis minimum of constructed SkIRect
@param top y-axis minimum of constructed SkIRect
@param right x-axis maximum of constructed SkIRect
@param bottom y-axis maximum of constructed SkIRect
@return true if all sides of SkIRect are outside construction
*/
bool contains(int32_t left, int32_t top, int32_t right, int32_t bottom) const {
@ -522,10 +497,10 @@ struct SK_API SkIRect {
Return is undefined if SkIRect is empty or construction is empty.
@param left x minimum of constructed SkIRect
@param top y minimum of constructed SkIRect
@param right x maximum of constructed SkIRect
@param bottom y maximum of constructed SkIRect
@param left x-axis minimum of constructed SkIRect
@param top y-axis minimum of constructed SkIRect
@param right x-axis maximum of constructed SkIRect
@param bottom y-axis maximum of constructed SkIRect
@return true if all sides of SkIRect are outside construction
*/
bool containsNoEmptyCheck(int32_t left, int32_t top,
@ -609,10 +584,10 @@ struct SK_API SkIRect {
Returns false if either construction or SkIRect is empty, leaving SkIRect unchanged.
@param left x minimum of constructed SkIRect
@param top y minimum of constructed SkIRect
@param right x maximum of constructed SkIRect
@param bottom y maximum of constructed SkIRect
@param left x-axis minimum of constructed SkIRect
@param top y-axis minimum of constructed SkIRect
@param right x-axis maximum of constructed SkIRect
@param bottom y-axis maximum of constructed SkIRect
@return true if construction and SkIRect have area in common
*/
bool intersect(int32_t left, int32_t top, int32_t right, int32_t bottom) {
@ -651,10 +626,10 @@ struct SK_API SkIRect {
Has no effect if construction is empty. Otherwise, if SkIRect is empty, sets
SkIRect to construction.
@param left x minimum of constructed SkIRect
@param top y minimum of constructed SkIRect
@param right x maximum of constructed SkIRect
@param bottom y maximum of constructed SkIRect
@param left x-axis minimum of constructed SkIRect
@param top y-axis minimum of constructed SkIRect
@param right x-axis maximum of constructed SkIRect
@param bottom y-axis maximum of constructed SkIRect
*/
void join(int32_t left, int32_t top, int32_t right, int32_t bottom);
@ -673,11 +648,12 @@ struct SK_API SkIRect {
and width() and height() will be zero or positive.
*/
void sort() {
using std::swap;
if (fLeft > fRight) {
SkTSwap<int32_t>(fLeft, fRight);
swap(fLeft, fRight);
}
if (fTop > fBottom) {
SkTSwap<int32_t>(fTop, fBottom);
swap(fTop, fBottom);
}
}
@ -710,26 +686,10 @@ struct SK_API SkIRect {
its top, it is considered empty.
*/
struct SK_API SkRect {
/** May contain any value, including infinities and NaN. The smaller of the
horizontal values when sorted. When equal to or greater than fRight, SkRect is empty.
*/
SkScalar fLeft;
/** May contain any value, including infinities and NaN. The smaller of the
vertical values when sorted. When equal to or greater than fBottom, SkRect is empty.
*/
SkScalar fTop;
/** May contain any value, including infinities and NaN. The larger of the
horizontal values when sorted. When equal to or less than fLeft, SkRect is empty.
*/
SkScalar fRight;
/** May contain any value, including infinities and NaN. The larger of the
vertical values when sorted. When equal to or less than fTop, SkRect is empty.
*/
SkScalar fBottom;
SkScalar fLeft; //!< smaller x-axis bounds
SkScalar fTop; //!< smaller y-axis bounds
SkScalar fRight; //!< larger x-axis bounds
SkScalar fBottom; //!< larger y-axis bounds
/** Returns constructed SkRect set to (0, 0, 0, 0).
Many other rectangles are empty; if left is equal to or greater than right,
@ -804,8 +764,8 @@ struct SK_API SkRect {
return SkRect {l, t, r, b};
}
/** Returns constructed SkRect set to (x, y, x + w, y + h). Does not validate input;
w or h may be negative.
/** Returns constructed SkRect set to (x, y, x + w, y + h).
Does not validate input; w or h may be negative.
@param x stored in fLeft
@param y stored in fTop
@ -813,22 +773,11 @@ struct SK_API SkRect {
@param h added to y and stored in fBottom
@return bounds at (x, y) with width w and height h
*/
static constexpr SkRect SK_WARN_UNUSED_RESULT MakeXYWH(SkScalar x, SkScalar y, SkScalar w, SkScalar h) {
static constexpr SkRect SK_WARN_UNUSED_RESULT MakeXYWH(SkScalar x, SkScalar y, SkScalar w,
SkScalar h) {
return SkRect {x, y, x + w, y + h};
}
/** Deprecated.
*/
SK_ATTR_DEPRECATED("use Make()")
static SkRect SK_WARN_UNUSED_RESULT MakeFromIRect(const SkIRect& irect) {
SkRect r;
r.set(SkIntToScalar(irect.fLeft),
SkIntToScalar(irect.fTop),
SkIntToScalar(irect.fRight),
SkIntToScalar(irect.fBottom));
return r;
}
/** Returns constructed SkIRect set to (0, 0, size.width(), size.height()).
Does not validate input; size.width() or size.height() may be negative.
@ -944,7 +893,7 @@ struct SK_API SkRect {
*/
SkScalar width() const { return fRight - fLeft; }
/** Returns span on the y-axis. This does not check if SkIRect is sorted, or if
/** Returns span on the y-axis. This does not check if SkRect is sorted, or if
result fits in 32-bit float; result may be negative or infinity.
@return fBottom minus fTop
@ -956,14 +905,20 @@ struct SK_API SkRect {
@return midpoint in x
*/
SkScalar centerX() const { return SkScalarHalf(fLeft + fRight); }
SkScalar centerX() const {
// don't use SkScalarHalf(fLeft + fBottom) as that might overflow before the 0.5
return SkScalarHalf(fLeft) + SkScalarHalf(fRight);
}
/** Returns average of top edge and bottom edge. Result does not change if SkRect
is sorted. Result may overflow to infinity if SkRect is far from the origin.
is sorted.
@return midpoint in y
*/
SkScalar centerY() const { return SkScalarHalf(fTop + fBottom); }
SkScalar centerY() const {
// don't use SkScalarHalf(fTop + fBottom) as that might overflow before the 0.5
return SkScalarHalf(fTop) + SkScalarHalf(fBottom);
}
/** Returns true if all members in a: fLeft, fTop, fRight, and fBottom; are
equal to the corresponding members in b.
@ -995,7 +950,7 @@ struct SK_API SkRect {
/** Returns four points in quad that enclose SkRect ordered as: top-left, top-right,
bottom-right, bottom-left.
Consider adding param to control whether quad is CW or CCW.
Consider adding param to control whether quad is clockwise or counterclockwise.
@param quad storage for corners of SkRect
*/
@ -1122,6 +1077,14 @@ struct SK_API SkRect {
*/
bool setBoundsCheck(const SkPoint pts[], int count);
/** Sets to bounds of SkPoint pts array with count entries. If any SkPoint in pts
contains infinity or NaN, all SkRect dimensions are set to NaN.
@param pts SkPoint array
@param count entries in array
*/
void setBoundsNoCheck(const SkPoint pts[], int count);
/** Sets bounds to the smallest SkRect enclosing SkPoint p0 and p1. The result is
sorted and may be empty. Does not check to see if values are finite.
@ -1135,8 +1098,8 @@ struct SK_API SkRect {
fBottom = SkMaxScalar(p0.fY, p1.fY);
}
/** Sets SkRect to (x, y, x + width, y + height). Does not validate input;
width or height may be negative.
/** Sets SkRect to (x, y, x + width, y + height).
Does not validate input; width or height may be negative.
@param x stored in fLeft
@param y stored in fTop
@ -1172,7 +1135,7 @@ struct SK_API SkRect {
@param dx added to fLeft and fRight
@param dy added to fTop and fBottom
@return SkRect offset in x or y, with original width and height
@return SkRect offset on axes, with original width and height
*/
SkRect makeOffset(SkScalar dx, SkScalar dy) const {
return MakeLTRB(fLeft + dx, fTop + dy, fRight + dx, fBottom + dy);
@ -1299,10 +1262,10 @@ struct SK_API SkRect {
Returns false if either construction or SkRect is empty, leaving SkRect unchanged.
@param left x minimum of constructed SkRect
@param top y minimum of constructed SkRect
@param right x maximum of constructed SkRect
@param bottom y maximum of constructed SkRect
@param left x-axis minimum of constructed SkRect
@param top y-axis minimum of constructed SkRect
@param right x-axis maximum of constructed SkRect
@param bottom y-axis maximum of constructed SkRect
@return true if construction and SkRect have area in common
*/
bool intersect(SkScalar left, SkScalar top, SkScalar right, SkScalar bottom);
@ -1337,10 +1300,10 @@ public:
Returns true if SkRect intersects construction.
Returns false if either construction or SkRect is empty, or do not intersect.
@param left x minimum of constructed SkRect
@param top y minimum of constructed SkRect
@param right x maximum of constructed SkRect
@param bottom y maximum of constructed SkRect
@param left x-axis minimum of constructed SkRect
@param top y-axis minimum of constructed SkRect
@param right x-axis maximum of constructed SkRect
@param bottom y-axis maximum of constructed SkRect
@return true if construction and SkRect have area in common
*/
bool intersects(SkScalar left, SkScalar top, SkScalar right, SkScalar bottom) const {
@ -1378,10 +1341,10 @@ public:
Has no effect if construction is empty. Otherwise, if SkRect is empty, sets
SkRect to construction.
@param left x minimum of constructed SkRect
@param top y minimum of constructed SkRect
@param right x maximum of constructed SkRect
@param bottom y maximum of constructed SkRect
@param left x-axis minimum of constructed SkRect
@param top y-axis minimum of constructed SkRect
@param right x-axis maximum of constructed SkRect
@param bottom y-axis maximum of constructed SkRect
*/
void join(SkScalar left, SkScalar top, SkScalar right, SkScalar bottom);
@ -1481,9 +1444,10 @@ public:
SkScalarRoundToInt(fRight), SkScalarRoundToInt(fBottom));
}
/** Sets SkIRect by discarding the fractional portion of fLeft and fTop; and
rounding up fRight and fBottom, using (SkScalarFloorToInt(fLeft), SkScalarFloorToInt(fTop),
SkScalarCeilToInt(fRight), SkScalarCeilToInt(fBottom)).
/** Sets SkIRect by discarding the fractional portion of fLeft and fTop; and rounding
up fRight and fBottom, using
(SkScalarFloorToInt(fLeft), SkScalarFloorToInt(fTop),
SkScalarCeilToInt(fRight), SkScalarCeilToInt(fBottom)).
@param dst storage for SkIRect
*/
@ -1493,9 +1457,10 @@ public:
SkScalarCeilToInt(fRight), SkScalarCeilToInt(fBottom));
}
/** Sets SkRect by discarding the fractional portion of fLeft and fTop; and
rounding up fRight and fBottom, using (SkScalarFloorToInt(fLeft), SkScalarFloorToInt(fTop),
SkScalarCeilToInt(fRight), SkScalarCeilToInt(fBottom)).
/** Sets SkRect by discarding the fractional portion of fLeft and fTop; and rounding
up fRight and fBottom, using
(SkScalarFloorToInt(fLeft), SkScalarFloorToInt(fTop),
SkScalarCeilToInt(fRight), SkScalarCeilToInt(fBottom)).
@param dst storage for SkRect
*/
@ -1506,8 +1471,8 @@ public:
SkScalarCeilToScalar(fBottom));
}
/** Sets SkRect by rounding up fLeft and fTop; and
discarding the fractional portion of fRight and fBottom, using
/** Sets SkRect by rounding up fLeft and fTop; and discarding the fractional portion
of fRight and fBottom, using
(SkScalarCeilToInt(fLeft), SkScalarCeilToInt(fTop),
SkScalarFloorToInt(fRight), SkScalarFloorToInt(fBottom)).
@ -1531,9 +1496,10 @@ public:
return ir;
}
/** Sets SkIRect by discarding the fractional portion of fLeft and fTop; and
rounding up fRight and fBottom, using (SkScalarFloorToInt(fLeft), SkScalarFloorToInt(fTop),
SkScalarCeilToInt(fRight), SkScalarCeilToInt(fBottom)).
/** Sets SkIRect by discarding the fractional portion of fLeft and fTop; and rounding
up fRight and fBottom, using
(SkScalarFloorToInt(fLeft), SkScalarFloorToInt(fTop),
SkScalarCeilToInt(fRight), SkScalarCeilToInt(fBottom)).
@return rounded SkIRect
*/
@ -1548,12 +1514,13 @@ public:
and width() and height() will be zero or positive.
*/
void sort() {
using std::swap;
if (fLeft > fRight) {
SkTSwap<SkScalar>(fLeft, fRight);
swap(fLeft, fRight);
}
if (fTop > fBottom) {
SkTSwap<SkScalar>(fTop, fBottom);
swap(fTop, fBottom);
}
}

Просмотреть файл

@ -8,11 +8,13 @@
#ifndef SkRefCnt_DEFINED
#define SkRefCnt_DEFINED
#include "../private/SkTLogic.h"
#include "SkTypes.h"
#include <atomic>
#include <cstddef>
#include <functional>
#include <memory>
#include <ostream>
#include <type_traits>
#include <utility>
@ -26,7 +28,7 @@
destructor to be called explicitly (or via the object going out of scope on
the stack or calling delete) if getRefCnt() > 1.
*/
class SK_API SkRefCntBase : SkNoncopyable {
class SK_API SkRefCntBase {
public:
/** Default construct, initializing the reference count to 1.
*/
@ -42,12 +44,12 @@ public:
#endif
}
#ifdef SK_DEBUG
/** Return the reference count. Use only for debugging. */
int32_t getRefCnt() const {
return fRefCnt.load(std::memory_order_relaxed);
}
#ifdef SK_DEBUG
void validate() const {
SkASSERT(getRefCnt() > 0);
}
@ -114,7 +116,10 @@ private:
mutable std::atomic<int32_t> fRefCnt;
typedef SkNoncopyable INHERITED;
SkRefCntBase(SkRefCntBase&&) = delete;
SkRefCntBase(const SkRefCntBase&) = delete;
SkRefCntBase& operator=(SkRefCntBase&&) = delete;
SkRefCntBase& operator=(const SkRefCntBase&) = delete;
};
#ifdef SK_REF_CNT_MIXIN_INCLUDE
@ -133,42 +138,6 @@ class SK_API SkRefCnt : public SkRefCntBase {
///////////////////////////////////////////////////////////////////////////////
/** Helper macro to safely assign one SkRefCnt[TS]* to another, checking for
null in on each side of the assignment, and ensuring that ref() is called
before unref(), in case the two pointers point to the same object.
*/
#if defined(SK_BUILD_FOR_ANDROID_FRAMEWORK)
// This version heuristically detects data races, since those otherwise result
// in redundant reference count decrements, which are exceedingly
// difficult to debug.
#define SkRefCnt_SafeAssign(dst, src) \
do { \
typedef typename std::remove_reference<decltype(dst)>::type \
SkRefCntPtrT; \
SkRefCntPtrT old_dst = *const_cast<SkRefCntPtrT volatile *>(&dst); \
if (src) src->ref(); \
if (old_dst) old_dst->unref(); \
if (old_dst != *const_cast<SkRefCntPtrT volatile *>(&dst)) { \
SkDebugf("Detected racing Skia calls at %s:%d\n", \
__FILE__, __LINE__); \
} \
dst = src; \
} while (0)
#else /* !SK_BUILD_FOR_ANDROID_FRAMEWORK */
#define SkRefCnt_SafeAssign(dst, src) \
do { \
if (src) src->ref(); \
if (dst) dst->unref(); \
dst = src; \
} while (0)
#endif
/** Call obj->ref() and return obj. The obj must not be nullptr.
*/
template <typename T> static inline T* SkRef(T* obj) {
@ -194,19 +163,12 @@ template <typename T> static inline void SkSafeUnref(T* obj) {
}
}
template<typename T> static inline void SkSafeSetNull(T*& obj) {
if (obj) {
obj->unref();
obj = nullptr;
}
}
///////////////////////////////////////////////////////////////////////////////
// This is a variant of SkRefCnt that's Not Virtual, so weighs 4 bytes instead of 8 or 16.
// There's only benefit to using this if the deriving class does not otherwise need a vtable.
template <typename Derived>
class SkNVRefCnt : SkNoncopyable {
class SkNVRefCnt {
public:
SkNVRefCnt() : fRefCnt(1) {}
~SkNVRefCnt() { SkASSERTF(1 == getRefCnt(), "NVRefCnt was %d", getRefCnt()); }
@ -232,6 +194,11 @@ private:
int32_t getRefCnt() const {
return fRefCnt.load(std::memory_order_relaxed);
}
SkNVRefCnt(SkNVRefCnt&&) = delete;
SkNVRefCnt(const SkNVRefCnt&) = delete;
SkNVRefCnt& operator=(SkNVRefCnt&&) = delete;
SkNVRefCnt& operator=(const SkNVRefCnt&) = delete;
};
///////////////////////////////////////////////////////////////////////////////////////////////////
@ -244,8 +211,6 @@ private:
* may have its ref/unref be thread-safe, but that is not assumed/imposed by sk_sp.
*/
template <typename T> class sk_sp {
/** Supports safe bool idiom. Obsolete with explicit operator bool. */
using unspecified_bool_type = T* sk_sp::*;
public:
using element_type = T;
@ -257,7 +222,8 @@ public:
* created sk_sp both have a reference to it.
*/
sk_sp(const sk_sp<T>& that) : fPtr(SkSafeRef(that.get())) {}
template <typename U, typename = skstd::enable_if_t<std::is_convertible<U*, T*>::value>>
template <typename U,
typename = typename std::enable_if<std::is_convertible<U*, T*>::value>::type>
sk_sp(const sk_sp<U>& that) : fPtr(SkSafeRef(that.get())) {}
/**
@ -266,7 +232,8 @@ public:
* No call to ref() or unref() will be made.
*/
sk_sp(sk_sp<T>&& that) : fPtr(that.release()) {}
template <typename U, typename = skstd::enable_if_t<std::is_convertible<U*, T*>::value>>
template <typename U,
typename = typename std::enable_if<std::is_convertible<U*, T*>::value>::type>
sk_sp(sk_sp<U>&& that) : fPtr(that.release()) {}
/**
@ -291,10 +258,13 @@ public:
* object.
*/
sk_sp<T>& operator=(const sk_sp<T>& that) {
this->reset(SkSafeRef(that.get()));
if (this != &that) {
this->reset(SkSafeRef(that.get()));
}
return *this;
}
template <typename U, typename = skstd::enable_if_t<std::is_convertible<U*, T*>::value>>
template <typename U,
typename = typename std::enable_if<std::is_convertible<U*, T*>::value>::type>
sk_sp<T>& operator=(const sk_sp<U>& that) {
this->reset(SkSafeRef(that.get()));
return *this;
@ -309,7 +279,8 @@ public:
this->reset(that.release());
return *this;
}
template <typename U, typename = skstd::enable_if_t<std::is_convertible<U*, T*>::value>>
template <typename U,
typename = typename std::enable_if<std::is_convertible<U*, T*>::value>::type>
sk_sp<T>& operator=(sk_sp<U>&& that) {
this->reset(that.release());
return *this;
@ -320,12 +291,7 @@ public:
return *this->get();
}
// MSVC 2013 does not work correctly with explicit operator bool.
// https://chromium-cpp.appspot.com/#core-blacklist
// When explicit operator bool can be used, remove operator! and operator unspecified_bool_type.
//explicit operator bool() const { return this->get() != nullptr; }
operator unspecified_bool_type() const { return this->get() ? &sk_sp::fPtr : nullptr; }
bool operator!() const { return this->get() == nullptr; }
explicit operator bool() const { return this->get() != nullptr; }
T* get() const { return fPtr; }
T* operator->() const { return fPtr; }
@ -391,7 +357,7 @@ template <typename T, typename U> inline bool operator<(const sk_sp<T>& a, const
// Provide defined total order on sk_sp.
// http://wg21.cmeerw.net/lwg/issue1297
// http://wg21.cmeerw.net/lwg/issue1401 .
return std::less<skstd::common_type_t<T*, U*>>()(a.get(), b.get());
return std::less<typename std::common_type<T*, U*>::type>()(a.get(), b.get());
}
template <typename T> inline bool operator<(const sk_sp<T>& a, std::nullptr_t) {
return std::less<T*>()(a.get(), nullptr);
@ -430,6 +396,11 @@ template <typename T> inline bool operator>=(std::nullptr_t, const sk_sp<T>& b)
return !(nullptr < b);
}
template <typename C, typename CT, typename T>
auto operator<<(std::basic_ostream<C, CT>& os, const sk_sp<T>& sp) -> decltype(os << sp.get()) {
return os << sp.get();
}
template <typename T, typename... Args>
sk_sp<T> sk_make_sp(Args&&... args) {
return sk_sp<T>(new T(std::forward<Args>(args)...));

Просмотреть файл

@ -1,4 +1,3 @@
/*
* Copyright 2005 The Android Open Source Project
*
@ -6,6 +5,15 @@
* found in the LICENSE file.
*/
/* Generated by tools/bookmaker from include/core/SkRegion.h and docs/SkRegion_Reference.bmh
on 2018-08-10 12:59:44. Additional documentation and examples can be found at:
https://skia.org/user/api/SkRegion_Reference
You may edit either file directly. Structural changes to public interfaces require
editing both files. After editing docs/SkRegion_Reference.bmh, run:
bookmaker -b docs -i include/core/SkRegion.h -p
to create an updated version of this file.
*/
#ifndef SkRegion_DEFINED
#define SkRegion_DEFINED
@ -15,248 +23,360 @@
class SkPath;
class SkRgnBuilder;
namespace android {
class Region;
}
#define SkRegion_gEmptyRunHeadPtr ((SkRegion::RunHead*)-1)
#define SkRegion_gRectRunHeadPtr nullptr
/** \class SkRegion
The SkRegion class encapsulates the geometric region used to specify
clipping areas for drawing.
SkRegion describes the set of pixels used to clip SkCanvas. SkRegion is compact,
efficiently storing a single integer rectangle, or a run length encoded array
of rectangles. SkRegion may reduce the current SkCanvas clip, or may be drawn as
one or more integer rectangles. SkRegion iterator returns the scan lines or
rectangles contained by it, optionally intersecting a bounding rectangle.
*/
class SK_API SkRegion {
public:
typedef int32_t RunType;
enum {
kRunTypeSentinel = 0x7FFFFFFF
};
public:
/** Constructs an empty SkRegion. SkRegion is set to empty bounds
at (0, 0) with zero width and height.
@return empty SkRegion
*/
SkRegion();
SkRegion(const SkRegion&);
explicit SkRegion(const SkIRect&);
/** Constructs a copy of an existing region.
Copy constructor makes two regions identical by value. Internally, region and
the returned result share pointer values. The underlying SkRect array is
copied when modified.
Creating a SkRegion copy is very efficient and never allocates memory.
SkRegion are always copied by value from the interface; the underlying shared
pointers are not exposed.
@param region SkRegion to copy by value
@return copy of SkRegion
*/
SkRegion(const SkRegion& region);
/** Constructs a rectangular SkRegion matching the bounds of rect.
@param rect bounds of constructed SkRegion
@return rectangular SkRegion
*/
explicit SkRegion(const SkIRect& rect);
/** Releases ownership of any shared data and deletes data if SkRegion is sole owner.
*/
~SkRegion();
SkRegion& operator=(const SkRegion&);
/** Constructs a copy of an existing region.
Makes two regions identical by value. Internally, region and
the returned result share pointer values. The underlying SkRect array is
copied when modified.
/**
* Return true if the two regions are equal. i.e. The enclose exactly
* the same area.
*/
Creating a SkRegion copy is very efficient and never allocates memory.
SkRegion are always copied by value from the interface; the underlying shared
pointers are not exposed.
@param region SkRegion to copy by value
@return SkRegion to copy by value
*/
SkRegion& operator=(const SkRegion& region);
/** Compares SkRegion and other; returns true if they enclose exactly
the same area.
@param other SkRegion to compare
@return true if SkRegion pair are equivalent
*/
bool operator==(const SkRegion& other) const;
/**
* Return true if the two regions are not equal.
*/
/** Compares SkRegion and other; returns true if they do not enclose the same area.
@param other SkRegion to compare
@return true if SkRegion pair are not equivalent
*/
bool operator!=(const SkRegion& other) const {
return !(*this == other);
}
/**
* Replace this region with the specified region, and return true if the
* resulting region is non-empty.
*/
/** Sets SkRegion to src, and returns true if src bounds is not empty.
This makes SkRegion and src identical by value. Internally,
SkRegion and src share pointer values. The underlying SkRect array is
copied when modified.
Creating a SkRegion copy is very efficient and never allocates memory.
SkRegion are always copied by value from the interface; the underlying shared
pointers are not exposed.
@param src SkRegion to copy
@return copy of src
*/
bool set(const SkRegion& src) {
*this = src;
return !this->isEmpty();
}
/**
* Swap the contents of this and the specified region. This operation
* is gauarenteed to never fail.
*/
void swap(SkRegion&);
/** Exchanges SkIRect array of SkRegion and other. swap() internally exchanges pointers,
so it is lightweight and does not allocate memory.
/** Return true if this region is empty */
bool isEmpty() const { return fRunHead == SkRegion_gEmptyRunHeadPtr; }
swap() usage has largely been replaced by operator=(const SkRegion& region).
SkPath do not copy their content on assignment until they are written to,
making assignment as efficient as swap().
/** Return true if this region is a single, non-empty rectangle */
bool isRect() const { return fRunHead == SkRegion_gRectRunHeadPtr; }
@param other operator=(const SkRegion& region) set
*/
void swap(SkRegion& other);
/** Return true if this region consists of more than 1 rectangular area */
/** Returns true if SkRegion is empty.
Empty SkRegion has bounds width or height less than or equal to zero.
SkRegion() constructs empty SkRegion; setEmpty()
and setRect() with dimensionless data make SkRegion empty.
@return true if bounds has no width or height
*/
bool isEmpty() const { return fRunHead == emptyRunHeadPtr(); }
/** Returns true if SkRegion is one SkIRect with positive dimensions.
@return true if SkRegion contains one SkIRect
*/
bool isRect() const { return fRunHead == kRectRunHeadPtr; }
/** Returns true if SkRegion is described by more than one rectangle.
@return true if SkRegion contains more than one SkIRect
*/
bool isComplex() const { return !this->isEmpty() && !this->isRect(); }
/**
* Return the bounds of this region. If the region is empty, returns an
* empty rectangle.
*/
/** Returns minimum and maximum axes values of SkIRect array.
Returns (0, 0, 0, 0) if SkRegion is empty.
@return combined bounds of all SkIRect elements
*/
const SkIRect& getBounds() const { return fBounds; }
/**
* Returns a value that grows approximately linearly with the number of
* intervals comprised in the region. Empty region will return 0, Rect
* will return 1, Complex will return a value > 1.
*
* Use this to compare two regions, where the larger count likely
* indicates a more complex region.
*/
/** Returns a value that increases with the number of
elements in SkRegion. Returns zero if SkRegion is empty.
Returns one if SkRegion equals SkIRect; otherwise, returns
value greater than one indicating that SkRegion is complex.
Call to compare SkRegion for relative complexity.
@return relative complexity
*/
int computeRegionComplexity() const;
/**
* Returns true if the region is non-empty, and if so, appends the
* boundary(s) of the region to the specified path.
* If the region is empty, returns false, and path is left unmodified.
*/
/** Appends outline of SkRegion to path.
Returns true if SkRegion is not empty; otherwise, returns false, and leaves path
unmodified.
@param path SkPath to append to
@return true if path changed
*/
bool getBoundaryPath(SkPath* path) const;
/**
* Set the region to be empty, and return false, since the resulting
* region is empty
*/
/** Constructs an empty SkRegion. SkRegion is set to empty bounds
at (0, 0) with zero width and height. Always returns false.
@return false
*/
bool setEmpty();
/**
* If rect is non-empty, set this region to that rectangle and return true,
* otherwise set this region to empty and return false.
*/
bool setRect(const SkIRect&);
/** Constructs a rectangular SkRegion matching the bounds of rect.
If rect is empty, constructs empty and returns false.
/**
* If left < right and top < bottom, set this region to that rectangle and
* return true, otherwise set this region to empty and return false.
*/
@param rect bounds of constructed SkRegion
@return true if rect is not empty
*/
bool setRect(const SkIRect& rect);
/** Constructs SkRegion with bounds (left, top, right, bottom).
Returns true if left is less than right and top is less than bottom; otherwise,
constructs empty SkRegion and returns false.
@param left edge of bounds on x-axis
@param top edge of bounds on y-axis
@param right edge of bounds on x-axis
@param bottom edge of bounds on y-axis
@return rectangular SkRegion
*/
bool setRect(int32_t left, int32_t top, int32_t right, int32_t bottom) {
return this->setRect({ left, top, right, bottom });
}
/**
* Set this region to the union of an array of rects. This is generally
* faster than calling region.op(rect, kUnion_Op) in a loop. If count is
* 0, then this region is set to the empty region.
* @return true if the resulting region is non-empty
*/
/** Constructs SkRegion as the union of SkIRect in rects array. If count is
zero, constructs empty SkRegion. Returns false if constructed SkRegion is empty.
May be faster than repeated calls to op().
@param rects array of SkIRect
@param count array size
@return true if constructed SkRegion is not empty
*/
bool setRects(const SkIRect rects[], int count);
/**
* Set this region to the specified region, and return true if it is
* non-empty.
*/
bool setRegion(const SkRegion&);
/** Constructs a copy of an existing region.
Makes two regions identical by value. Internally, region and
the returned result share pointer values. The underlying SkRect array is
copied when modified.
/**
* Set this region to the area described by the path, clipped.
* Return true if the resulting region is non-empty.
* This produces a region that is identical to the pixels that would be
* drawn by the path (with no antialiasing) with the specified clip.
*/
bool setPath(const SkPath&, const SkRegion& clip);
Creating a SkRegion copy is very efficient and never allocates memory.
SkRegion are always copied by value from the interface; the underlying shared
pointers are not exposed.
/**
* Returns true if the specified rectangle has a non-empty intersection
* with this region.
*/
bool intersects(const SkIRect&) const;
@param region SkRegion to copy by value
@return SkRegion to copy by value
*/
bool setRegion(const SkRegion& region);
/**
* Returns true if the specified region has a non-empty intersection
* with this region.
*/
bool intersects(const SkRegion&) const;
/** Constructs SkRegion to match outline of path within clip.
Returns false if constructed SkRegion is empty.
/**
* Return true if the specified x,y coordinate is inside the region.
*/
Constructed SkRegion draws the same pixels as path through clip when
anti-aliasing is disabled.
@param path SkPath providing outline
@param clip SkRegion containing path
@return true if constructed SkRegion is not empty
*/
bool setPath(const SkPath& path, const SkRegion& clip);
/** Returns true if SkRegion intersects rect.
Returns false if either rect or SkRegion is empty, or do not intersect.
@param rect SkIRect to intersect
@return true if rect and SkRegion have area in common
*/
bool intersects(const SkIRect& rect) const;
/** Returns true if SkRegion intersects other.
Returns false if either other or SkRegion is empty, or do not intersect.
@param other SkRegion to intersect
@return true if other and SkRegion have area in common
*/
bool intersects(const SkRegion& other) const;
/** Returns true if SkIPoint (x, y) is inside SkRegion.
Returns false if SkRegion is empty.
@param x test SkIPoint x-coordinate
@param y test SkIPoint y-coordinate
@return true if (x, y) is inside SkRegion
*/
bool contains(int32_t x, int32_t y) const;
/**
* Return true if the specified rectangle is completely inside the region.
* This works for simple (rectangular) and complex regions, and always
* returns the correct result. Note: if either this region or the rectangle
* is empty, contains() returns false.
*/
bool contains(const SkIRect&) const;
/** Returns true if other is completely inside SkRegion.
Returns false if SkRegion or other is empty.
/**
* Return true if the specified region is completely inside the region.
* This works for simple (rectangular) and complex regions, and always
* returns the correct result. Note: if either region is empty, contains()
* returns false.
*/
bool contains(const SkRegion&) const;
@param other SkIRect to contain
@return true if other is inside SkRegion
*/
bool contains(const SkIRect& other) const;
/**
* Return true if this region is a single rectangle (not complex) and the
* specified rectangle is contained by this region. Returning false is not
* a guarantee that the rectangle is not contained by this region, but
* return true is a guarantee that the rectangle is contained by this region.
*/
/** Returns true if other is completely inside SkRegion.
Returns false if SkRegion or other is empty.
@param other SkRegion to contain
@return true if other is inside SkRegion
*/
bool contains(const SkRegion& other) const;
/** Returns true if SkRegion is a single rectangle and contains r.
May return false even though SkRegion contains r.
@param r SkIRect to contain
@return true quickly if r points are equal or inside
*/
bool quickContains(const SkIRect& r) const {
return this->quickContains(r.fLeft, r.fTop, r.fRight, r.fBottom);
}
/**
* Return true if this region is a single rectangle (not complex) and the
* specified rectangle is contained by this region. Returning false is not
* a guarantee that the rectangle is not contained by this region, but
* return true is a guarantee that the rectangle is contained by this
* region.
*/
/** Returns true if SkRegion is a single rectangle and contains SkIRect
(left, top, right, bottom).
Returns false if SkRegion is empty or SkIRect (left, top, right, bottom) is empty.
May return false even though SkRegion contains (left, top, right, bottom).
@param left edge of bounds on x-axis
@param top edge of bounds on y-axis
@param right edge of bounds on x-axis
@param bottom edge of bounds on y-axis
@return true quickly if SkIRect are equal or inside
*/
bool quickContains(int32_t left, int32_t top, int32_t right,
int32_t bottom) const {
SkASSERT(this->isEmpty() == fBounds.isEmpty()); // valid region
return left < right && top < bottom &&
fRunHead == SkRegion_gRectRunHeadPtr && // this->isRect()
fRunHead == kRectRunHeadPtr && // this->isRect()
/* fBounds.contains(left, top, right, bottom); */
fBounds.fLeft <= left && fBounds.fTop <= top &&
fBounds.fRight >= right && fBounds.fBottom >= bottom;
}
/**
* Return true if this region is empty, or if the specified rectangle does
* not intersect the region. Returning false is not a guarantee that they
* intersect, but returning true is a guarantee that they do not.
*/
/** Returns true if SkRegion does not intersect rect.
Returns true if rect is empty or SkRegion is empty.
May return false even though SkRegion does not intersect rect.
@param rect SkIRect to intersect
@return true if rect does not intersect
*/
bool quickReject(const SkIRect& rect) const {
return this->isEmpty() || rect.isEmpty() ||
!SkIRect::Intersects(fBounds, rect);
}
/**
* Return true if this region, or rgn, is empty, or if their bounds do not
* intersect. Returning false is not a guarantee that they intersect, but
* returning true is a guarantee that they do not.
*/
/** Returns true if SkRegion does not intersect rgn.
Returns true if rgn is empty or SkRegion is empty.
May return false even though SkRegion does not intersect rgn.
@param rgn SkRegion to intersect
@return true if rgn does not intersect
*/
bool quickReject(const SkRegion& rgn) const {
return this->isEmpty() || rgn.isEmpty() ||
!SkIRect::Intersects(fBounds, rgn.fBounds);
}
/** Translate the region by the specified (dx, dy) amount. */
/** Offsets SkRegion by ivector (dx, dy). Has no effect if SkRegion is empty.
@param dx x-axis offset
@param dy y-axis offset
*/
void translate(int dx, int dy) { this->translate(dx, dy, this); }
/**
* Translate the region by the specified (dx, dy) amount, writing the
* resulting region into dst. Note: it is legal to pass this region as the
* dst parameter, effectively translating the region in place. If dst is
* null, nothing happens.
*/
/** Offsets SkRegion by ivector (dx, dy), writing result to dst. SkRegion may be passed
as dst parameter, translating SkRegion in place. Has no effect if dst is nullptr.
If SkRegion is empty, sets dst to empty.
@param dx x-axis offset
@param dy y-axis offset
@param dst translated result
*/
void translate(int dx, int dy, SkRegion* dst) const;
/**
* The logical operations that can be performed when combining two regions.
*/
/** \enum SkRegion::Op
The logical operations that can be performed when combining two SkRegion.
*/
enum Op {
kDifference_Op, //!< subtract the op region from the first region
kIntersect_Op, //!< intersect the two regions
kUnion_Op, //!< union (inclusive-or) the two regions
kXOR_Op, //!< exclusive-or the two regions
/** subtract the first region from the op region */
kReverseDifference_Op,
kReplace_Op, //!< replace the dst region with the op region
kLastOp = kReplace_Op
kDifference_Op, //!< target minus operand
kIntersect_Op, //!< target intersected with operand
kUnion_Op, //!< target unioned with operand
kXOR_Op, //!< target exclusive or with operand
kReverseDifference_Op, //!< operand minus target
kReplace_Op, //!< replace target with operand
kLastOp = kReplace_Op, //!< last operator
};
static const int kOpCnt = kLastOp + 1;
/**
* Set this region to the result of applying the Op to this region and the
* specified rectangle: this = (this op rect).
* Return true if the resulting region is non-empty.
*/
/** Replaces SkRegion with the result of SkRegion op rect.
Returns true if replaced SkRegion is not empty.
@param rect SkIRect operand
@param op operator, one of:
kDifference_Op, kIntersect_Op, kUnion_Op, kXOR_Op, kReverseDifference_Op,
kReplace_Op
@return false if result is empty
*/
bool op(const SkIRect& rect, Op op) {
if (this->isRect() && kIntersect_Op == op) {
if (!fBounds.intersect(rect)) {
@ -267,101 +387,206 @@ public:
return this->op(*this, rect, op);
}
/**
* Set this region to the result of applying the Op to this region and the
* specified rectangle: this = (this op rect).
* Return true if the resulting region is non-empty.
*/
/** Replaces SkRegion with the result of SkRegion op SkIRect (left, top, right, bottom).
Returns true if replaced SkRegion is not empty.
@param left edge of bounds on x-axis
@param top edge of bounds on y-axis
@param right edge of bounds on x-axis
@param bottom edge of bounds on y-axis
@param op operator, one of:
kDifference_Op, kIntersect_Op, kUnion_Op, kXOR_Op, kReverseDifference_Op,
kReplace_Op
@return false if result is empty
*/
bool op(int left, int top, int right, int bottom, Op op) {
SkIRect rect;
rect.set(left, top, right, bottom);
return this->op(*this, rect, op);
}
/**
* Set this region to the result of applying the Op to this region and the
* specified region: this = (this op rgn).
* Return true if the resulting region is non-empty.
*/
/** Replaces SkRegion with the result of SkRegion op rgn.
Returns true if replaced SkRegion is not empty.
@param rgn SkRegion operand
@param op operator, one of:
kDifference_Op, kIntersect_Op, kUnion_Op, kXOR_Op, kReverseDifference_Op,
kReplace_Op
@return false if result is empty
*/
bool op(const SkRegion& rgn, Op op) { return this->op(*this, rgn, op); }
/**
* Set this region to the result of applying the Op to the specified
* rectangle and region: this = (rect op rgn).
* Return true if the resulting region is non-empty.
*/
bool op(const SkIRect& rect, const SkRegion& rgn, Op);
/** Replaces SkRegion with the result of rect op rgn.
Returns true if replaced SkRegion is not empty.
/**
* Set this region to the result of applying the Op to the specified
* region and rectangle: this = (rgn op rect).
* Return true if the resulting region is non-empty.
*/
bool op(const SkRegion& rgn, const SkIRect& rect, Op);
@param rect SkIRect operand
@param rgn SkRegion operand
@param op operator, one of:
kDifference_Op, kIntersect_Op, kUnion_Op, kXOR_Op, kReverseDifference_Op,
kReplace_Op
@return false if result is empty
*/
bool op(const SkIRect& rect, const SkRegion& rgn, Op op);
/**
* Set this region to the result of applying the Op to the specified
* regions: this = (rgna op rgnb).
* Return true if the resulting region is non-empty.
*/
/** Replaces SkRegion with the result of rgn op rect.
Returns true if replaced SkRegion is not empty.
@param rgn SkRegion operand
@param rect SkIRect operand
@param op operator, one of:
kDifference_Op, kIntersect_Op, kUnion_Op, kXOR_Op, kReverseDifference_Op,
kReplace_Op
@return false if result is empty
*/
bool op(const SkRegion& rgn, const SkIRect& rect, Op op);
/** Replaces SkRegion with the result of rgna op rgnb.
Returns true if replaced SkRegion is not empty.
@param rgna SkRegion operand
@param rgnb SkRegion operand
@param op operator, one of:
kDifference_Op, kIntersect_Op, kUnion_Op, kXOR_Op, kReverseDifference_Op,
kReplace_Op
@return false if result is empty
*/
bool op(const SkRegion& rgna, const SkRegion& rgnb, Op op);
#ifdef SK_BUILD_FOR_ANDROID
/** Returns a new char* containing the list of rectangles in this region
*/
/** Android framework only.
@return string representation of SkRegion
*/
char* toString();
#endif
/**
* Returns the sequence of rectangles, sorted in Y and X, that make up
* this region.
*/
/** \class SkRegion::Iterator
Returns sequence of rectangles, sorted along y-axis, then x-axis, that make
up SkRegion.
*/
class SK_API Iterator {
public:
/** Initializes SkRegion::Iterator with an empty SkRegion. done() on SkRegion::Iterator returns true.
Call reset() to initialized SkRegion::Iterator at a later time.
@return empty SkRegion ierator
*/
Iterator() : fRgn(nullptr), fDone(true) {}
Iterator(const SkRegion&);
// if we have a region, reset to it and return true, else return false
/** Sets SkRegion::Iterator to return elements of SkIRect array in region.
@param region SkRegion to iterate
@return SkRegion iterator
*/
Iterator(const SkRegion& region);
/** SkPoint SkRegion::Iterator to start of SkRegion.
Returns true if SkRegion was set; otherwise, returns false.
@return true if SkRegion was set
*/
bool rewind();
// reset the iterator, using the new region
void reset(const SkRegion&);
/** Resets iterator, using the new SkRegion.
@param region SkRegion to iterate
*/
void reset(const SkRegion& region);
/** Returns true if SkRegion::Iterator is pointing to final SkIRect in SkRegion.
@return true if data parsing is complete
*/
bool done() const { return fDone; }
/** Advances SkRegion::Iterator to next SkIRect in SkRegion if it is not done.
*/
void next();
/** Returns SkIRect element in SkRegion. Does not return predictable results if SkRegion
is empty.
@return part of SkRegion as SkIRect
*/
const SkIRect& rect() const { return fRect; }
// may return null
/** Returns SkRegion if set; otherwise, returns nullptr.
@return iterated SkRegion
*/
const SkRegion* rgn() const { return fRgn; }
private:
const SkRegion* fRgn;
const RunType* fRuns;
SkIRect fRect;
const SkRegion::RunType* fRuns;
SkIRect fRect = {0, 0, 0, 0};
bool fDone;
};
/**
* Returns the sequence of rectangles, sorted in Y and X, that make up
* this region intersected with the specified clip rectangle.
*/
/** \class SkRegion::Cliperator
Returns the sequence of rectangles, sorted along y-axis, then x-axis, that make
up SkRegion intersected with the specified clip rectangle.
*/
class SK_API Cliperator {
public:
Cliperator(const SkRegion&, const SkIRect& clip);
/** Sets SkRegion::Cliperator to return elements of SkIRect array in SkRegion within clip.
@param region SkRegion to iterate
@param clip bounds of iteration
@return SkRegion iterator
*/
Cliperator(const SkRegion& region, const SkIRect& clip);
/** Returns true if SkRegion::Cliperator is pointing to final SkIRect in SkRegion.
@return true if data parsing is complete
*/
bool done() { return fDone; }
/** Advances iterator to next SkIRect in SkRegion contained by clip.
*/
void next();
/** Returns SkIRect element in SkRegion, intersected with clip passed to SkRegion::Cliperator
constructor. Does not return predictable results if SkRegion
is empty.
@return part of SkRegion inside clip as SkIRect
*/
const SkIRect& rect() const { return fRect; }
private:
Iterator fIter;
SkIRect fClip;
SkIRect fRect;
SkIRect fRect = {0, 0, 0, 0};
bool fDone;
};
/**
* Returns the sequence of runs that make up this region for the specified
* Y scanline, clipped to the specified left and right X values.
*/
/** \class SkRegion::Spanerator
Returns the line segment ends within SkRegion that intersect a horizontal line.
*/
class Spanerator {
public:
Spanerator(const SkRegion&, int y, int left, int right);
/** Sets SkRegion::Spanerator to return line segments in SkRegion on scan line.
@param region SkRegion to iterate
@param y horizontal line to intersect
@param left bounds of iteration
@param right bounds of iteration
@return SkRegion iterator
*/
Spanerator(const SkRegion& region, int y, int left, int right);
/** Advances iterator to next span intersecting SkRegion within line segment provided
in constructor. Returns true if interval was found.
@param left pointer to span start; may be nullptr
@param right pointer to span end; may be nullptr
@return true if interval was found
*/
bool next(int* left, int* right);
private:
@ -370,55 +595,43 @@ public:
bool fDone;
};
/**
* Write the region to the buffer, and return the number of bytes written.
* If buffer is NULL, it still returns the number of bytes.
*/
/** Writes SkRegion to buffer, and returns number of bytes written.
If buffer is nullptr, returns number number of bytes that would be written.
@param buffer storage for binary data
@return size of SkRegion
*/
size_t writeToMemory(void* buffer) const;
/**
* Initializes the region from the buffer
*
* @param buffer Memory to read from
* @param length Amount of memory available in the buffer
* @return number of bytes read (must be a multiple of 4) or
* 0 if there was not enough memory available
*/
/** Constructs SkRegion from buffer of size length. Returns bytes read.
Returned value will be multiple of four or zero if length was too small.
@param buffer storage for binary data
@param length size of buffer
@return bytes read
*/
size_t readFromMemory(const void* buffer, size_t length);
/**
* Returns a reference to a global empty region. Just a convenience for
* callers that need a const empty region.
*/
static const SkRegion& GetEmptyRegion();
SkDEBUGCODE(void dump() const;)
SkDEBUGCODE(void validate() const;)
SkDEBUGCODE(static void UnitTest();)
// expose this to allow for regression test on complex regions
SkDEBUGCODE(bool debugSetRuns(const RunType runs[], int count);)
private:
enum {
kOpCount = kReplace_Op + 1
};
static constexpr int kOpCount = kReplace_Op + 1;
enum {
// T
// [B N L R S]
// S
kRectRegionRuns = 7
};
friend class android::Region; // needed for marshalling efficiently
// T
// [B N L R S]
// S
static constexpr int kRectRegionRuns = 7;
struct RunHead;
static RunHead* emptyRunHeadPtr() { return (SkRegion::RunHead*) -1; }
static constexpr RunHead* kRectRunHeadPtr = nullptr;
// allocate space for count runs
void allocateRuns(int count);
void allocateRuns(int count, int ySpanCount, int intervalCount);
void allocateRuns(const RunHead& src);
SkDEBUGCODE(void dump() const;)
SkIRect fBounds;
RunHead* fRunHead;

Просмотреть файл

@ -60,7 +60,7 @@ typedef float SkScalar;
#define SkScalarToFloat(x) static_cast<float>(x)
#define SkFloatToScalar(x) static_cast<SkScalar>(x)
#define SkScalarToDouble(x) static_cast<double>(x)
#define SkDoubleToScalar(x) static_cast<SkScalar>(x)
#define SkDoubleToScalar(x) sk_double_to_float(x)
#define SK_ScalarMin (-SK_ScalarMax)
@ -68,22 +68,10 @@ static inline bool SkScalarIsNaN(SkScalar x) { return x != x; }
/** Returns true if x is not NaN and not infinite
*/
static inline bool SkScalarIsFinite(SkScalar x) {
// We rely on the following behavior of infinities and nans
// 0 * finite --> 0
// 0 * infinity --> NaN
// 0 * NaN --> NaN
SkScalar prod = x * 0;
// At this point, prod will either be NaN or 0
return !SkScalarIsNaN(prod);
}
static inline bool SkScalarIsFinite(SkScalar x) { return sk_float_isfinite(x); }
static inline bool SkScalarsAreFinite(SkScalar a, SkScalar b) {
SkScalar prod = 0;
prod *= a;
prod *= b;
// At this point, prod will either be NaN or 0
return !SkScalarIsNaN(prod);
return sk_float_isfinite(a) && sk_float_isfinite(b);
}
static inline bool SkScalarsAreFinite(const SkScalar array[], int count) {
@ -92,7 +80,7 @@ static inline bool SkScalarsAreFinite(const SkScalar array[], int count) {
prod *= array[i];
}
// At this point, prod will either be NaN or 0
return !SkScalarIsNaN(prod);
return prod == 0; // if prod is NaN, this check will return false
}
/**

Просмотреть файл

@ -18,7 +18,7 @@
* If null is returned, then Skia will take its default action.
*
* The default action for pictures is to use Skia's internal format.
* The default action for images is to encode using PNG.
* The default action for images is to encode either in its native format or PNG.
* The default action for typefaces is to use Skia's internal format.
*/
@ -27,13 +27,24 @@ typedef sk_sp<SkData> (*SkSerialImageProc)(SkImage*, void* ctx);
typedef sk_sp<SkData> (*SkSerialTypefaceProc)(SkTypeface*, void* ctx);
/**
* A deserial-proc is given the serialized form previously returned by the corresponding
* serial-proc, and should return the re-constituted object. In case of an error, the proc
* can return nullptr.
* Called with the encoded form of a picture (previously written with a custom
* SkSerialPictureProc proc). Return a picture object, or nullptr indicating failure.
*/
typedef sk_sp<SkPicture> (*SkDeserialPictureProc)(const void* data, size_t length, void* ctx);
/**
* Called with the encoded from of an image. The proc can return an image object, or if it
* returns nullptr, then Skia will take its default action to try to create an image from the data.
*
* Note that unlike SkDeserialPictureProc and SkDeserialTypefaceProc, return nullptr from this
* does not indicate failure, but is a signal for Skia to take its default action.
*/
typedef sk_sp<SkImage> (*SkDeserialImageProc)(const void* data, size_t length, void* ctx);
/**
* Called with the encoded form of a typeface (previously written with a custom
* SkSerialTypefaceProc proc). Return a typeface object, or nullptr indicating failure.
*/
typedef sk_sp<SkTypeface> (*SkDeserialTypefaceProc)(const void* data, size_t length, void* ctx);
struct SK_API SkSerialProcs {

Просмотреть файл

@ -59,12 +59,10 @@ public:
*/
kDecal_TileMode,
kLast_TileMode = kDecal_TileMode
kLast_TileMode = kDecal_TileMode,
};
enum {
kTileModeCount = kLast_TileMode + 1
};
static constexpr int kTileModeCount = kLast_TileMode + 1;
/**
* Returns the local matrix.
@ -141,7 +139,7 @@ public:
kRadial_GradientType,
kSweep_GradientType,
kConical_GradientType,
kLast_GradientType = kConical_GradientType
kLast_GradientType = kConical_GradientType,
};
struct GradientInfo {

Просмотреть файл

@ -24,7 +24,7 @@ struct SkISize {
*/
bool isZero() const { return 0 == fWidth && 0 == fHeight; }
/** Returns true if either widht or height are <= 0 */
/** Returns true if either width or height are <= 0 */
bool isEmpty() const { return fWidth <= 0 || fHeight <= 0; }
/** Set the width and height to 0 */

Просмотреть файл

@ -8,6 +8,7 @@
#ifndef SkStream_DEFINED
#define SkStream_DEFINED
#include "../private/SkTo.h"
#include "SkData.h"
#include "SkRefCnt.h"
#include "SkScalar.h"
@ -37,9 +38,10 @@ class SkStreamMemory;
* no more data (at EOF or hit an error). The caller should *not* call again
* in hopes of fulfilling more of the request.
*/
class SK_API SkStream : public SkNoncopyable {
class SK_API SkStream {
public:
virtual ~SkStream() {}
SkStream() {}
/**
* Attempts to open the specified file as a stream, returns nullptr on failure.
@ -83,17 +85,22 @@ public:
*/
virtual bool isAtEnd() const = 0;
int8_t readS8();
int16_t readS16();
int32_t readS32();
bool SK_WARN_UNUSED_RESULT readS8(int8_t*);
bool SK_WARN_UNUSED_RESULT readS16(int16_t*);
bool SK_WARN_UNUSED_RESULT readS32(int32_t*);
uint8_t readU8() { return (uint8_t)this->readS8(); }
uint16_t readU16() { return (uint16_t)this->readS16(); }
uint32_t readU32() { return (uint32_t)this->readS32(); }
bool SK_WARN_UNUSED_RESULT readU8(uint8_t* i) { return this->readS8((int8_t*)i); }
bool SK_WARN_UNUSED_RESULT readU16(uint16_t* i) { return this->readS16((int16_t*)i); }
bool SK_WARN_UNUSED_RESULT readU32(uint32_t* i) { return this->readS32((int32_t*)i); }
bool readBool() { return this->readU8() != 0; }
SkScalar readScalar();
size_t readPackedUInt();
bool SK_WARN_UNUSED_RESULT readBool(bool* b) {
uint8_t i;
if (!this->readU8(&i)) { return false; }
*b = (i != 0);
return true;
}
bool SK_WARN_UNUSED_RESULT readScalar(SkScalar*);
bool SK_WARN_UNUSED_RESULT readPackedUInt(size_t*);
//SkStreamRewindable
/** Rewinds to the beginning of the stream. Returns true if the stream is known
@ -146,6 +153,11 @@ public:
private:
virtual SkStream* onDuplicate() const { return nullptr; }
virtual SkStream* onFork() const { return nullptr; }
SkStream(SkStream&&) = delete;
SkStream(const SkStream&) = delete;
SkStream& operator=(SkStream&&) = delete;
SkStream& operator=(const SkStream&) = delete;
};
/** SkStreamRewindable is a SkStream for which rewind and duplicate are required. */
@ -212,9 +224,10 @@ private:
SkStreamMemory* onFork() const override = 0;
};
class SK_API SkWStream : SkNoncopyable {
class SK_API SkWStream {
public:
virtual ~SkWStream();
SkWStream() {}
/** Called to write bytes to a SkWStream. Returns true on success
@param buffer the address of at least size bytes to be written to the stream
@ -247,29 +260,33 @@ public:
bool newline() { return this->write("\n", strlen("\n")); }
bool writeDecAsText(int32_t);
bool writeBigDecAsText(int64_t, int minDigits = 0);
bool writeHexAsText(uint32_t, int minDigits = 0);
bool writeScalarAsText(SkScalar);
bool writeDecAsText(int32_t);
bool writeBigDecAsText(int64_t, int minDigits = 0);
bool writeHexAsText(uint32_t, int minDigits = 0);
bool writeScalarAsText(SkScalar);
bool writeBool(bool v) { return this->write8(v); }
bool writeScalar(SkScalar);
bool writePackedUInt(size_t);
bool writeBool(bool v) { return this->write8(v); }
bool writeScalar(SkScalar);
bool writePackedUInt(size_t);
bool writeStream(SkStream* input, size_t length);
bool writeStream(SkStream* input, size_t length);
/**
* This returns the number of bytes in the stream required to store
* 'value'.
*/
static int SizeOfPackedUInt(size_t value);
private:
SkWStream(const SkWStream&) = delete;
SkWStream& operator=(const SkWStream&) = delete;
};
class SK_API SkNullWStream : public SkWStream {
public:
SkNullWStream() : fBytesWritten(0) {}
bool write(const void*, size_t n) override { fBytesWritten += n; return true; }
bool write(const void* , size_t n) override { fBytesWritten += n; return true; }
void flush() override {}
size_t bytesWritten() const override { return fBytesWritten; }
@ -289,8 +306,10 @@ public:
*/
explicit SkFILEStream(const char path[] = nullptr);
/** Initialize the stream with an existing C file stream.
* The C file stream will be closed in the destructor.
/** Initialize the stream with an existing C FILE stream.
* The current position of the C FILE stream will be considered the
* beginning of the SkFILEStream.
* The C FILE stream will be closed in the destructor.
*/
explicit SkFILEStream(FILE* file);
@ -352,7 +371,7 @@ public:
SkMemoryStream(const void* data, size_t length, bool copyData = false);
/** Creates the stream to read from the specified data */
SkMemoryStream(sk_sp<SkData>);
SkMemoryStream(sk_sp<SkData> data);
/** Returns a stream with a copy of the input data. */
static std::unique_ptr<SkMemoryStream> MakeCopy(const void* data, size_t length);
@ -376,7 +395,7 @@ public:
void setMemoryOwned(const void* data, size_t length);
sk_sp<SkData> asData() const { return fData; }
void setData(sk_sp<SkData>);
void setData(sk_sp<SkData> data);
void skipToAlign4();
const void* getAtPos();
@ -438,7 +457,9 @@ private:
class SK_API SkDynamicMemoryWStream : public SkWStream {
public:
SkDynamicMemoryWStream();
SkDynamicMemoryWStream() = default;
SkDynamicMemoryWStream(SkDynamicMemoryWStream&&);
SkDynamicMemoryWStream& operator=(SkDynamicMemoryWStream&&);
~SkDynamicMemoryWStream() override;
bool write(const void* buffer, size_t size) override;
@ -456,6 +477,13 @@ public:
/** Equivalent to writeToStream() followed by reset(), but may save memory use. */
bool writeToAndReset(SkWStream* dst);
/** Equivalent to writeToStream() followed by reset(), but may save memory use.
When the dst is also a SkDynamicMemoryWStream, the implementation is constant time. */
bool writeToAndReset(SkDynamicMemoryWStream* dst);
/** Prepend this stream to dst, resetting this. */
void prependToAndReset(SkDynamicMemoryWStream* dst);
/** Return the contents as SkData, and then reset the stream. */
sk_sp<SkData> detachAsData();
@ -467,9 +495,9 @@ public:
void padToAlign4();
private:
struct Block;
Block* fHead;
Block* fTail;
size_t fBytesWrittenBeforeTail;
Block* fHead = nullptr;
Block* fTail = nullptr;
size_t fBytesWrittenBeforeTail = 0;
#ifdef SK_DEBUG
void validate() const;

Просмотреть файл

@ -1,4 +1,3 @@
/*
* Copyright 2006 The Android Open Source Project
*
@ -11,8 +10,9 @@
#define SkString_DEFINED
#include "../private/SkTArray.h"
#include "SkScalar.h"
#include "../private/SkTo.h"
#include "SkRefCnt.h"
#include "SkScalar.h"
#include <atomic>
#include <stdarg.h>
@ -186,8 +186,6 @@ public:
void set(const SkString& src) { *this = src; }
void set(const char text[]);
void set(const char text[], size_t len);
void setUTF16(const uint16_t[]);
void setUTF16(const uint16_t[], size_t len);
void insert(size_t offset, const SkString& src) { this->insert(offset, src.c_str(), src.size()); }
void insert(size_t offset, const char text[]);
@ -276,9 +274,7 @@ SkString SkStringPrintf(const char* format, ...);
/// optional.
static inline SkString SkStringPrintf() { return SkString(); }
// Specialized to take advantage of SkString's fast swap path. The unspecialized function is
// declared in SkTypes.h and called by SkTSort.
template <> inline void SkTSwap(SkString& a, SkString& b) {
static inline void swap(SkString& a, SkString& b) {
a.swap(b);
}

Просмотреть файл

@ -8,6 +8,7 @@
#ifndef SkStrokeRec_DEFINED
#define SkStrokeRec_DEFINED
#include "../private/SkMacros.h"
#include "SkPaint.h"
class SkPath;
@ -29,9 +30,8 @@ public:
kStroke_Style,
kStrokeAndFill_Style
};
enum {
kStyleCount = kStrokeAndFill_Style + 1
};
static constexpr int kStyleCount = kStrokeAndFill_Style + 1;
Style getStyle() const;
SkScalar getWidth() const { return fWidth; }
@ -114,6 +114,9 @@ public:
*/
static SkScalar GetInflationRadius(const SkPaint&, SkPaint::Style);
static SkScalar GetInflationRadius(SkPaint::Join, SkScalar miterLimit, SkPaint::Cap,
SkScalar strokeWidth);
/**
* Compare if two SkStrokeRecs have an equal effect on a path.
* Equal SkStrokeRecs produce equal paths. Equality of produced

Просмотреть файл

@ -5,6 +5,16 @@
* found in the LICENSE file.
*/
/* Generated by tools/bookmaker from include/core/SkSurface.h and docs/SkSurface_Reference.bmh
on 2018-09-13 13:59:55. Additional documentation and examples can be found at:
https://skia.org/user/api/SkSurface_Reference
You may edit either file directly. Structural changes to public interfaces require
editing both files. After editing docs/SkSurface_Reference.bmh, run:
bookmaker -b docs -i include/core/SkSurface.h -p
to create an updated version of this file.
*/
#ifndef SkSurface_DEFINED
#define SkSurface_DEFINED
@ -20,6 +30,7 @@ class SkPaint;
class SkSurfaceCharacterization;
class GrBackendRenderTarget;
class GrBackendSemaphore;
class GrBackendTexture;
class GrContext;
class GrRenderTarget;
@ -137,7 +148,7 @@ public:
Allocates and zeroes pixel memory. Pixel memory size is height times width times
four. Pixel memory is deleted when SkSurface is deleted.
Internally, sets SkImageInfo to width, height, native SkColorType, and
Internally, sets SkImageInfo to width, height, native color type, and
kPremul_SkAlphaType.
SkSurface is returned if width and height are greater than zero.
@ -173,39 +184,12 @@ public:
@param backendTexture texture residing on GPU
@param origin one of: kBottomLeft_GrSurfaceOrigin, kTopLeft_GrSurfaceOrigin
@param sampleCnt samples per pixel, or 0 to disable full scene anti-aliasing
@param colorSpace range of colors
@param surfaceProps LCD striping orientation and setting for device independent
fonts; may be nullptr
@return SkSurface if all parameters are valid; otherwise, nullptr
*/
static sk_sp<SkSurface> MakeFromBackendTexture(GrContext* context,
const GrBackendTexture& backendTexture,
GrSurfaceOrigin origin, int sampleCnt,
sk_sp<SkColorSpace> colorSpace,
const SkSurfaceProps* surfaceProps);
/** Wraps a GPU-backed texture into SkSurface. Caller must ensure the texture is
valid for the lifetime of returned SkSurface. If sampleCnt greater than zero,
creates an intermediate MSAA SkSurface which is used for drawing backendTexture.
SkSurface is returned if all parameters are valid. backendTexture is valid if
its pixel configuration agrees with colorSpace and context; for instance, if
backendTexture has an sRGB configuration, then context must support sRGB,
and colorSpace must be present. Further, backendTexture width and height must
not exceed context capabilities, and the context must be able to support
back-end textures.
If SK_SUPPORT_GPU is defined as zero, has no effect and returns nullptr.
@param context GPU context
@param backendTexture texture residing on GPU
@param origin one of: kBottomLeft_GrSurfaceOrigin, kTopLeft_GrSurfaceOrigin
@param sampleCnt samples per pixel, or 0 to disable full scene anti-aliasing
@param colorType one of: kUnknown_SkColorType, kAlpha_8_SkColorType,
kRGB_565_SkColorType, kARGB_4444_SkColorType,
kRGBA_8888_SkColorType, kBGRA_8888_SkColorType,
@param colorType one of:
kUnknown_SkColorType, kAlpha_8_SkColorType, kRGB_565_SkColorType,
kARGB_4444_SkColorType, kRGBA_8888_SkColorType, kRGB_888x_SkColorType,
kBGRA_8888_SkColorType, kRGBA_1010102_SkColorType, kRGB_101010x_SkColorType,
kGray_8_SkColorType, kRGBA_F16_SkColorType
@param colorSpace range of colors
@param colorSpace range of colors; may be nullptr
@param surfaceProps LCD striping orientation and setting for device independent
fonts; may be nullptr
@return SkSurface if all parameters are valid; otherwise, nullptr
@ -217,8 +201,8 @@ public:
sk_sp<SkColorSpace> colorSpace,
const SkSurfaceProps* surfaceProps);
/** Wraps a GPU-backed buffer into SkSurface. Caller must ensure render target is
valid for the lifetime of returned SkSurface.
/** Wraps a GPU-backed buffer into SkSurface. Caller must ensure backendRenderTarget
is valid for the lifetime of returned SkSurface.
SkSurface is returned if all parameters are valid. backendRenderTarget is valid if
its pixel configuration agrees with colorSpace and context; for instance, if
@ -232,35 +216,10 @@ public:
@param context GPU context
@param backendRenderTarget GPU intermediate memory buffer
@param origin one of: kBottomLeft_GrSurfaceOrigin, kTopLeft_GrSurfaceOrigin
@param colorSpace range of colors
@param surfaceProps LCD striping orientation and setting for device independent
fonts; may be nullptr
@return SkSurface if all parameters are valid; otherwise, nullptr
*/
static sk_sp<SkSurface> MakeFromBackendRenderTarget(GrContext* context,
const GrBackendRenderTarget& backendRenderTarget,
GrSurfaceOrigin origin,
sk_sp<SkColorSpace> colorSpace,
const SkSurfaceProps* surfaceProps);
/** Wraps a GPU-backed buffer into SkSurface. Caller must ensure render target is
valid for the lifetime of returned SkSurface.
SkSurface is returned if all parameters are valid. backendRenderTarget is valid if
its pixel configuration agrees with colorSpace and context; for instance, if
backendRenderTarget has an sRGB configuration, then context must support sRGB,
and colorSpace must be present. Further, backendRenderTarget width and height must
not exceed context capabilities, and the context must be able to support
back-end render targets.
If SK_SUPPORT_GPU is defined as zero, has no effect and returns nullptr.
@param context GPU context
@param backendRenderTarget GPU intermediate memory buffer
@param origin one of: kBottomLeft_GrSurfaceOrigin, kTopLeft_GrSurfaceOrigin
@param colorType one of: kUnknown_SkColorType, kAlpha_8_SkColorType,
kRGB_565_SkColorType, kARGB_4444_SkColorType,
kRGBA_8888_SkColorType, kBGRA_8888_SkColorType,
@param colorType one of:
kUnknown_SkColorType, kAlpha_8_SkColorType, kRGB_565_SkColorType,
kARGB_4444_SkColorType, kRGBA_8888_SkColorType, kRGB_888x_SkColorType,
kBGRA_8888_SkColorType, kRGBA_1010102_SkColorType, kRGB_101010x_SkColorType,
kGray_8_SkColorType, kRGBA_F16_SkColorType
@param colorSpace range of colors
@param surfaceProps LCD striping orientation and setting for device independent
@ -274,11 +233,18 @@ public:
sk_sp<SkColorSpace> colorSpace,
const SkSurfaceProps* surfaceProps);
/** Used to wrap a GPU-backed texture as a SkSurface. Skia will treat the texture as
a rendering target only, but unlike NewFromBackendRenderTarget, Skia will manage and own
the associated render target objects (but not the provided texture). Skia will not assume
ownership of the texture and the client must ensure the texture is valid for the lifetime
of the SkSurface.
/** Wraps a GPU-backed texture into SkSurface. Caller must ensure backendTexture is
valid for the lifetime of returned SkSurface. If sampleCnt greater than zero,
creates an intermediate MSAA SkSurface which is used for drawing backendTexture.
SkSurface is returned if all parameters are valid. backendTexture is valid if
its pixel configuration agrees with colorSpace and context; for instance, if
backendTexture has an sRGB configuration, then context must support sRGB,
and colorSpace must be present. Further, backendTexture width and height must
not exceed context capabilities.
Returned SkSurface is available only for drawing into, and cannot generate an
SkImage.
If SK_SUPPORT_GPU is defined as zero, has no effect and returns nullptr.
@ -286,35 +252,12 @@ public:
@param backendTexture texture residing on GPU
@param origin one of: kBottomLeft_GrSurfaceOrigin, kTopLeft_GrSurfaceOrigin
@param sampleCnt samples per pixel, or 0 to disable full scene anti-aliasing
@param colorSpace range of colors
@param surfaceProps LCD striping orientation and setting for device independent
fonts; may be nullptr
@return SkSurface if all parameters are valid; otherwise, nullptr
*/
static sk_sp<SkSurface> MakeFromBackendTextureAsRenderTarget(GrContext* context,
const GrBackendTexture& backendTexture,
GrSurfaceOrigin origin,
int sampleCnt,
sk_sp<SkColorSpace> colorSpace,
const SkSurfaceProps* surfaceProps);
/** Used to wrap a GPU-backed texture as a SkSurface. Skia will treat the texture as
a rendering target only, but unlike NewFromBackendRenderTarget, Skia will manage and own
the associated render target objects (but not the provided texture). Skia will not assume
ownership of the texture and the client must ensure the texture is valid for the lifetime
of the SkSurface.
If SK_SUPPORT_GPU is defined as zero, has no effect and returns nullptr.
@param context GPU context
@param backendTexture texture residing on GPU
@param origin one of: kBottomLeft_GrSurfaceOrigin, kTopLeft_GrSurfaceOrigin
@param sampleCnt samples per pixel, or 0 to disable full scene anti-aliasing
@param colorType one of: kUnknown_SkColorType, kAlpha_8_SkColorType,
kRGB_565_SkColorType, kARGB_4444_SkColorType,
kRGBA_8888_SkColorType, kBGRA_8888_SkColorType,
@param colorType one of:
kUnknown_SkColorType, kAlpha_8_SkColorType, kRGB_565_SkColorType,
kARGB_4444_SkColorType, kRGBA_8888_SkColorType, kRGB_888x_SkColorType,
kBGRA_8888_SkColorType, kRGBA_1010102_SkColorType, kRGB_101010x_SkColorType,
kGray_8_SkColorType, kRGBA_F16_SkColorType
@param colorSpace range of colors
@param colorSpace range of colors; may be nullptr
@param surfaceProps LCD striping orientation and setting for device independent
fonts; may be nullptr
@return SkSurface if all parameters are valid; otherwise, nullptr
@ -334,13 +277,13 @@ public:
SkAlphaType, and color matching in SkColorSpace.
sampleCount requests the number of samples per pixel.
Pass zero to disable Multi_Sample_Anti_Aliasing. The request is rounded
Pass zero to disable multi-sample anti-aliasing. The request is rounded
up to the next supported count, or rounded down if it is larger than the
maximum supported count.
surfaceOrigin pins either the top-left or the bottom-left corner to the origin.
shouldCreateWithMips hints that SkImage returned by makeImageSnapshot() is Mip_Map.
shouldCreateWithMips hints that SkImage returned by makeImageSnapshot() is mip map.
If SK_SUPPORT_GPU is defined as zero, has no effect and returns nullptr.
@ -352,7 +295,7 @@ public:
@param surfaceOrigin one of: kBottomLeft_GrSurfaceOrigin, kTopLeft_GrSurfaceOrigin
@param surfaceProps LCD striping orientation and setting for device independent
fonts; may be nullptr
@param shouldCreateWithMips hint that SkSurface will host Mip_Map images
@param shouldCreateWithMips hint that SkSurface will host mip map images
@return SkSurface if all parameters are valid; otherwise, nullptr
*/
static sk_sp<SkSurface> MakeRenderTarget(GrContext* context, SkBudgeted budgeted,
@ -368,7 +311,7 @@ public:
SkAlphaType, and color matching in SkColorSpace.
sampleCount requests the number of samples per pixel.
Pass zero to disable Multi_Sample_Anti_Aliasing. The request is rounded
Pass zero to disable multi-sample anti-aliasing. The request is rounded
up to the next supported count, or rounded down if it is larger than the
maximum supported count.
@ -378,7 +321,7 @@ public:
@param budgeted one of: SkBudgeted::kNo, SkBudgeted::kYes
@param imageInfo width, height, SkColorType, SkAlphaType, SkColorSpace,
of raster surface; width, or height, or both, may be zero
@param sampleCount samples per pixel, or 0 to disable Multi_Sample_Anti_Aliasing
@param sampleCount samples per pixel, or 0 to disable multi-sample anti-aliasing
@param props LCD striping orientation and setting for device independent
fonts; may be nullptr
@return SkSurface if all parameters are valid; otherwise, nullptr
@ -413,6 +356,18 @@ public:
nullptr);
}
/** Returns SkSurface on GPU indicated by context that is compatible with the provided
characterization. budgeted selects whether allocation for pixels is tracked by context.
@param context GPU context
@param characterization description of the desired SkSurface
@param budgeted one of: SkBudgeted::kNo, SkBudgeted::kYes
@return SkSurface if all parameters are valid; otherwise, nullptr
*/
static sk_sp<SkSurface> MakeRenderTarget(GrContext* context,
const SkSurfaceCharacterization& characterization,
SkBudgeted budgeted);
/** Returns SkSurface without backing pixels. Drawing to SkCanvas returned from SkSurface
has no effect. Calling makeImageSnapshot() on returned SkSurface returns nullptr.
@ -446,26 +401,24 @@ public:
ContentChangeMode members are parameters to notifyContentWillChange().
*/
enum ContentChangeMode {
kDiscard_ContentChangeMode, //!< the surface is cleared or overwritten.
/** If a snapshot has been generated, this copies the SkSurface contents. */
kRetain_ContentChangeMode,
kDiscard_ContentChangeMode, //!< discards surface on change
kRetain_ContentChangeMode, //!< preserves surface on change
};
/** Notifies that SkSurface contents will be changed by code outside of Skia.
Subsequent calls to generationID() return a different value.
mode is normally passed as kRetain_ContentChangeMode.
CAN WE DEPRECATE THIS?
Can we deprecate this?
@param mode one of: kDiscard_ContentChangeMode, kRetain_ContentChangeMode
*/
void notifyContentWillChange(ContentChangeMode mode);
enum BackendHandleAccess {
kFlushRead_BackendHandleAccess, //!< Caller may read from the back-end object.
kFlushWrite_BackendHandleAccess, //!< Caller may write to the back-end object.
kDiscardWrite_BackendHandleAccess, //!< Caller must overwrite the entire back-end object.
kFlushRead_BackendHandleAccess, //!< back-end object is readable
kFlushWrite_BackendHandleAccess, //!< back-end object is writable
kDiscardWrite_BackendHandleAccess, //!< back-end object must be overwritten
};
/** Deprecated.
@ -483,36 +436,30 @@ public:
static const BackendHandleAccess kDiscardWrite_TextureHandleAccess =
kDiscardWrite_BackendHandleAccess;
/** Returns the GPU back-end reference of the texture used by SkSurface, or zero
if SkSurface is not backed by a GPU texture.
/** Retrieves the back-end texture. If SkSurface has no back-end texture, an invalid
object is returned. Call GrBackendTexture::isValid to determine if the result
is valid.
The returned texture handle is only valid until the next draw into SkSurface,
or when SkSurface is deleted.
The returned GrBackendTexture should be discarded if the SkSurface is drawn to or deleted.
@param backendHandleAccess one of: kFlushRead_BackendHandleAccess,
kFlushWrite_BackendHandleAccess, kDiscardWrite_BackendHandleAccess
@return GPU texture reference
@return GPU texture reference; invalid on failure
*/
GrBackendObject getTextureHandle(BackendHandleAccess backendHandleAccess);
GrBackendTexture getBackendTexture(BackendHandleAccess backendHandleAccess);
/** Returns true and stores the GPU back-end reference of the render target used
by SkSurface in backendObject.
/** Retrieves the back-end render target. If SkSurface has no back-end render target, an invalid
object is returned. Call GrBackendRenderTarget::isValid to determine if the result
is valid.
Return false if SkSurface is not backed by a GPU render target, and leaves
backendObject unchanged.
The returned GrBackendRenderTarget should be discarded if the SkSurface is drawn to
or deleted.
The returned render target handle is only valid until the next draw into SkSurface,
or when SkSurface is deleted.
In OpenGL this returns the frame buffer object ID.
@param backendObject GPU intermediate memory buffer
@param backendHandleAccess one of: kFlushRead_BackendHandleAccess,
kFlushWrite_BackendHandleAccess, kDiscardWrite_BackendHandleAccess
@return true if SkSurface is backed by GPU texture
@return GPU render target reference; invalid on failure
*/
bool getRenderTargetHandle(GrBackendObject* backendObject,
BackendHandleAccess backendHandleAccess);
GrBackendRenderTarget getBackendRenderTarget(BackendHandleAccess backendHandleAccess);
/** Returns SkCanvas that draws into SkSurface. Subsequent calls return the same SkCanvas.
SkCanvas returned is managed and owned by SkSurface, and is deleted when SkSurface
@ -545,7 +492,7 @@ public:
/** Draws SkSurface contents to canvas, with its top-left corner at (x, y).
If SkPaint paint is not nullptr, apply SkColorFilter, color alpha, SkImageFilter,
If SkPaint paint is not nullptr, apply SkColorFilter, alpha, SkImageFilter,
SkBlendMode, and SkDrawLooper.
@param canvas SkCanvas drawn into
@ -590,8 +537,8 @@ public:
- dst.rowBytes() is too small to contain one row of pixels.
@param dst storage for pixels copied from SkSurface
@param srcX offset into readable pixels in x; may be negative
@param srcY offset into readable pixels in y; may be negative
@param srcX offset into readable pixels on x-axis; may be negative
@param srcY offset into readable pixels on y-axis; may be negative
@return true if pixels were copied
*/
bool readPixels(const SkPixmap& dst, int srcX, int srcY);
@ -621,8 +568,8 @@ public:
@param dstInfo width, height, SkColorType, and SkAlphaType of dstPixels
@param dstPixels storage for pixels; dstInfo.height() times dstRowBytes, or larger
@param dstRowBytes size of one destination row; dstInfo.width() times pixel size, or larger
@param srcX offset into readable pixels in x; may be negative
@param srcY offset into readable pixels in y; may be negative
@param srcX offset into readable pixels on x-axis; may be negative
@param srcY offset into readable pixels on y-axis; may be negative
@return true if pixels were copied
*/
bool readPixels(const SkImageInfo& dstInfo, void* dstPixels, size_t dstRowBytes,
@ -652,8 +599,8 @@ public:
- dst.rowBytes() is too small to contain one row of pixels.
@param dst storage for pixels copied from SkSurface
@param srcX offset into readable pixels in x; may be negative
@param srcY offset into readable pixels in y; may be negative
@param srcX offset into readable pixels on x-axis; may be negative
@param srcY offset into readable pixels on y-axis; may be negative
@return true if pixels were copied
*/
bool readPixels(const SkBitmap& dst, int srcX, int srcY);
@ -661,26 +608,30 @@ public:
/** Copies SkRect of pixels from the src SkPixmap to the SkSurface.
Source SkRect corners are (0, 0) and (src.width(), src.height()).
Destination SkRect corners are (dstX, dstY) and (dstX + Surface width(), dstY + Surface height()).
Destination SkRect corners are (dstX, dstY) and
(dstX + Surface width(), dstY + Surface height()).
Copies each readable pixel intersecting both rectangles, without scaling,
converting to SkSurface colorType() and SkSurface alphaType() if required.
@param src storage for pixels to copy to SkSurface
@param dstX x position relative to SkSurface to begin copy; may be negative
@param dstY x position relative to SkSurface to begin copy; may be negative
@param dstX x-axis position relative to SkSurface to begin copy; may be negative
@param dstY y-axis position relative to SkSurface to begin copy; may be negative
*/
void writePixels(const SkPixmap& src, int dstX, int dstY);
/** Copies SkRect of pixels from the src SkBitmap to the SkSurface.
Source SkRect corners are (0, 0) and (src.width(), src.height()).
Destination SkRect corners are (dstX, dstY) and (dstX + Surface width(), dstY + Surface height()).
Destination SkRect corners are (dstX, dstY) and
(dstX + Surface width(), dstY + Surface height()).
Copies each readable pixel intersecting both rectangles, without scaling,
converting to SkSurface colorType() and SkSurface alphaType() if required.
@param src storage for pixels to copy to SkSurface
@param dstX x position relative to SkSurface to begin copy; may be negative
@param dstY x position relative to SkSurface to begin copy; may be negative
@param dstX x-axis position relative to SkSurface to begin copy; may be negative
@param dstY y-axis position relative to SkSurface to begin copy; may be negative
*/
void writePixels(const SkBitmap& src, int dstX, int dstY);

Просмотреть файл

@ -16,10 +16,6 @@
class SkColorSpace;
// This define can be used to swap between the default (raster) DDL implementation and the
// gpu implementation.
#define SK_RASTER_RECORDER_IMPLEMENTATION 1
#if SK_SUPPORT_GPU
#include "GrContext.h"
@ -30,21 +26,21 @@ class SkColorSpace;
those objects (the Recorder and the DisplayList) will take a ref on the
GrContextThreadSafeProxy and SkColorSpace objects.
*/
class SkSurfaceCharacterization {
class SK_API SkSurfaceCharacterization {
public:
enum class Textureable : bool { kNo = false, kYes = true };
enum class MipMapped : bool { kNo = false, kYes = true };
enum class UsesGLFBO0 : bool { kNo = false, kYes = true };
SkSurfaceCharacterization()
: fCacheMaxResourceBytes(0)
, fOrigin(kBottomLeft_GrSurfaceOrigin)
, fWidth(0)
, fHeight(0)
, fConfig(kUnknown_GrPixelConfig)
, fFSAAType(GrFSAAType::kNone)
, fStencilCnt(0)
, fIsTextureable(Textureable::kYes)
, fIsMipMapped(MipMapped::kYes)
, fUsesGLFBO0(UsesGLFBO0::kNo)
, fSurfaceProps(0, kUnknown_SkPixelGeometry) {
}
@ -53,115 +49,136 @@ public:
SkSurfaceCharacterization(const SkSurfaceCharacterization&) = default;
SkSurfaceCharacterization& operator=(const SkSurfaceCharacterization& other) = default;
bool operator==(const SkSurfaceCharacterization& other) const;
bool operator!=(const SkSurfaceCharacterization& other) const {
return !(*this == other);
}
SkSurfaceCharacterization createResized(int width, int height) const;
GrContextThreadSafeProxy* contextInfo() const { return fContextInfo.get(); }
sk_sp<GrContextThreadSafeProxy> refContextInfo() const { return fContextInfo; }
size_t cacheMaxResourceBytes() const { return fCacheMaxResourceBytes; }
bool isValid() const { return kUnknown_GrPixelConfig != fConfig; }
bool isValid() const { return kUnknown_SkColorType != fImageInfo.colorType(); }
const SkImageInfo& imageInfo() const { return fImageInfo; }
GrSurfaceOrigin origin() const { return fOrigin; }
int width() const { return fWidth; }
int height() const { return fHeight; }
GrPixelConfig config() const { return fConfig; }
int width() const { return fImageInfo.width(); }
int height() const { return fImageInfo.height(); }
SkColorType colorType() const { return fImageInfo.colorType(); }
GrFSAAType fsaaType() const { return fFSAAType; }
int stencilCount() const { return fStencilCnt; }
bool isTextureable() const { return Textureable::kYes == fIsTextureable; }
bool isMipMapped() const { return MipMapped::kYes == fIsMipMapped; }
SkColorSpace* colorSpace() const { return fColorSpace.get(); }
sk_sp<SkColorSpace> refColorSpace() const { return fColorSpace; }
bool usesGLFBO0() const { return UsesGLFBO0::kYes == fUsesGLFBO0; }
SkColorSpace* colorSpace() const { return fImageInfo.colorSpace(); }
sk_sp<SkColorSpace> refColorSpace() const { return fImageInfo.refColorSpace(); }
const SkSurfaceProps& surfaceProps()const { return fSurfaceProps; }
private:
friend class SkSurface_Gpu; // for 'set'
friend class SkSurface_Gpu; // for 'set' & 'config'
friend class GrContextThreadSafeProxy; // for private ctor
friend class SkDeferredDisplayListRecorder; // for 'config'
friend class SkSurface; // for 'config'
GrPixelConfig config() const { return fConfig; }
SkSurfaceCharacterization(sk_sp<GrContextThreadSafeProxy> contextInfo,
size_t cacheMaxResourceBytes,
GrSurfaceOrigin origin, int width, int height,
GrPixelConfig config, GrFSAAType FSAAType, int stencilCnt,
const SkImageInfo& ii,
GrSurfaceOrigin origin,
GrPixelConfig config,
GrFSAAType FSAAType, int stencilCnt,
Textureable isTextureable, MipMapped isMipMapped,
sk_sp<SkColorSpace> colorSpace,
UsesGLFBO0 usesGLFBO0,
const SkSurfaceProps& surfaceProps)
: fContextInfo(std::move(contextInfo))
, fCacheMaxResourceBytes(cacheMaxResourceBytes)
, fImageInfo(ii)
, fOrigin(origin)
, fWidth(width)
, fHeight(height)
, fConfig(config)
, fFSAAType(FSAAType)
, fStencilCnt(stencilCnt)
, fIsTextureable(isTextureable)
, fIsMipMapped(isMipMapped)
, fColorSpace(std::move(colorSpace))
, fUsesGLFBO0(usesGLFBO0)
, fSurfaceProps(surfaceProps) {
}
void set(sk_sp<GrContextThreadSafeProxy> contextInfo,
size_t cacheMaxResourceBytes,
const SkImageInfo& ii,
GrSurfaceOrigin origin,
int width, int height,
GrPixelConfig config,
GrFSAAType fsaaType,
int stencilCnt,
Textureable isTextureable,
MipMapped isMipMapped,
sk_sp<SkColorSpace> colorSpace,
UsesGLFBO0 usesGLFBO0,
const SkSurfaceProps& surfaceProps) {
SkASSERT(MipMapped::kNo == isMipMapped || Textureable::kYes == isTextureable);
SkASSERT(Textureable::kNo == isTextureable || UsesGLFBO0::kNo == usesGLFBO0);
fContextInfo = contextInfo;
fCacheMaxResourceBytes = cacheMaxResourceBytes;
fImageInfo = ii;
fOrigin = origin;
fWidth = width;
fHeight = height;
fConfig = config;
fFSAAType = fsaaType;
fStencilCnt = stencilCnt;
fIsTextureable = isTextureable;
fIsMipMapped = isMipMapped;
fColorSpace = std::move(colorSpace);
fUsesGLFBO0 = usesGLFBO0;
fSurfaceProps = surfaceProps;
}
sk_sp<GrContextThreadSafeProxy> fContextInfo;
size_t fCacheMaxResourceBytes;
SkImageInfo fImageInfo;
GrSurfaceOrigin fOrigin;
int fWidth;
int fHeight;
GrPixelConfig fConfig;
GrFSAAType fFSAAType;
int fStencilCnt;
Textureable fIsTextureable;
MipMapped fIsMipMapped;
sk_sp<SkColorSpace> fColorSpace;
UsesGLFBO0 fUsesGLFBO0;
SkSurfaceProps fSurfaceProps;
};
#else// !SK_SUPPORT_GPU
class SkSurfaceCharacterization {
class SK_API SkSurfaceCharacterization {
public:
SkSurfaceCharacterization()
: fWidth(0)
, fHeight(0)
, fSurfaceProps(0, kUnknown_SkPixelGeometry) {
SkSurfaceCharacterization() : fSurfaceProps(0, kUnknown_SkPixelGeometry) { }
SkSurfaceCharacterization createResized(int width, int height) const {
return *this;
}
bool operator==(const SkSurfaceCharacterization& other) const { return false; }
bool operator!=(const SkSurfaceCharacterization& other) const {
return !(*this == other);
}
size_t cacheMaxResourceBytes() const { return 0; }
bool isValid() const { return false; }
int width() const { return fWidth; }
int height() const { return fHeight; }
SkColorSpace* colorSpace() const { return fColorSpace.get(); }
sk_sp<SkColorSpace> refColorSpace() const { return fColorSpace; }
int width() const { return 0; }
int height() const { return 0; }
int stencilCount() const { return 0; }
bool isTextureable() const { return false; }
bool isMipMapped() const { return false; }
bool usesGLFBO0() const { return false; }
SkColorSpace* colorSpace() const { return nullptr; }
sk_sp<SkColorSpace> refColorSpace() const { return nullptr; }
const SkSurfaceProps& surfaceProps()const { return fSurfaceProps; }
private:
int fWidth;
int fHeight;
sk_sp<SkColorSpace> fColorSpace;
SkSurfaceProps fSurfaceProps;
SkSurfaceProps fSurfaceProps;
};
#endif

Просмотреть файл

@ -61,7 +61,7 @@ public:
if (this->isValid()) {
fPtr->~T();
}
fPtr = new (SkTCast<T*>(fStorage.get())) T(std::forward<Args>(args)...);
fPtr = new (reinterpret_cast<T*>(fStorage.get())) T(std::forward<Args>(args)...);
return fPtr;
}
@ -75,7 +75,7 @@ public:
if (this->isValid()) {
*fPtr = src;
} else {
fPtr = new (SkTCast<T*>(fStorage.get())) T(src);
fPtr = new (reinterpret_cast<T*>(fStorage.get())) T(src);
}
return fPtr;
}
@ -84,7 +84,7 @@ public:
if (this->isValid()) {
*fPtr = std::move(src);
} else {
fPtr = new (SkTCast<T*>(fStorage.get())) T(std::move(src));
fPtr = new (reinterpret_cast<T*>(fStorage.get())) T(std::move(src));
}
return fPtr;
}
@ -148,13 +148,28 @@ private:
template <typename T>
class SkTCopyOnFirstWrite {
public:
SkTCopyOnFirstWrite(const T& initial) : fObj(&initial) {}
explicit SkTCopyOnFirstWrite(const T& initial) : fObj(&initial) {}
SkTCopyOnFirstWrite(const T* initial) : fObj(initial) {}
explicit SkTCopyOnFirstWrite(const T* initial) : fObj(initial) {}
// Constructor for delayed initialization.
SkTCopyOnFirstWrite() : fObj(nullptr) {}
SkTCopyOnFirstWrite(const SkTCopyOnFirstWrite& that) { *this = that; }
SkTCopyOnFirstWrite( SkTCopyOnFirstWrite&& that) { *this = std::move(that); }
SkTCopyOnFirstWrite& operator=(const SkTCopyOnFirstWrite& that) {
fLazy = that.fLazy;
fObj = fLazy.isValid() ? fLazy.get() : that.fObj;
return *this;
}
SkTCopyOnFirstWrite& operator=(SkTCopyOnFirstWrite&& that) {
fLazy = std::move(that.fLazy);
fObj = fLazy.isValid() ? fLazy.get() : that.fObj;
return *this;
}
// Should only be called once, and only if the default constructor was used.
void init(const T& initial) {
SkASSERT(nullptr == fObj);
@ -174,6 +189,8 @@ public:
return const_cast<T*>(fObj);
}
const T* get() const { return fObj; }
/**
* Operators for treating this as though it were a const pointer.
*/

Просмотреть файл

@ -5,96 +5,150 @@
* found in the LICENSE file.
*/
/* Generated by tools/bookmaker from include/core/SkTextBlob.h and docs/SkTextBlob_Reference.bmh
on 2018-08-10 12:59:44. Additional documentation and examples can be found at:
https://skia.org/user/api/SkTextBlob_Reference
You may edit either file directly. Structural changes to public interfaces require
editing both files. After editing docs/SkTextBlob_Reference.bmh, run:
bookmaker -b docs -i include/core/SkTextBlob.h -p
to create an updated version of this file.
*/
#ifndef SkTextBlob_DEFINED
#define SkTextBlob_DEFINED
#include "../private/SkTemplates.h"
#include "../private/SkAtomics.h"
#include "SkPaint.h"
#include "SkString.h"
#include "SkRefCnt.h"
class SkReadBuffer;
class SkWriteBuffer;
#include <atomic>
struct SkSerialProcs;
struct SkDeserialProcs;
typedef void (*SkTypefaceCatalogerProc)(SkTypeface*, void* ctx);
typedef sk_sp<SkTypeface> (*SkTypefaceResolverProc)(uint32_t id, void* ctx);
/** \class SkTextBlob
SkTextBlob combines multiple text runs into an immutable, ref-counted structure.
SkTextBlob combines multiple text runs into an immutable container. Each text
run consists of glyphs, SkPaint, and position. Only parts of SkPaint related to
fonts and text rendering are used by run.
*/
class SK_API SkTextBlob final : public SkNVRefCnt<SkTextBlob> {
public:
/**
* Returns a conservative blob bounding box.
*/
/** Returns conservative bounding box. Uses SkPaint associated with each glyph to
determine glyph bounds, and unions all bounds. Returned bounds may be
larger than the bounds of all glyphs in runs.
@return conservative bounding box
*/
const SkRect& bounds() const { return fBounds; }
/**
* Return a non-zero, unique value representing the text blob.
*/
/** Returns a non-zero value unique among all text blobs.
@return identifier for SkTextBlob
*/
uint32_t uniqueID() const { return fUniqueID; }
/**
* Serialize to a buffer.
*/
void flatten(SkWriteBuffer&) const;
/** Creates SkTextBlob with a single run. text meaning depends on SkPaint::TextEncoding;
by default, text is encoded as UTF-8.
/**
* Recreate an SkTextBlob that was serialized into a buffer.
*
* @param SkReadBuffer Serialized blob data.
* @return A new SkTextBlob representing the serialized data, or NULL if the buffer is
* invalid.
*/
static sk_sp<SkTextBlob> MakeFromBuffer(SkReadBuffer&);
paint contains attributes used to define the run text:
SkTypeface, SkPaint text size, SkPaint text scale x,
SkPaint text skew x, SkPaint::Align, SkPaint::Hinting, anti-alias, SkPaint fake bold,
SkPaint font embedded bitmaps, SkPaint full hinting spacing, LCD text, SkPaint linear text,
and SkPaint subpixel text.
enum GlyphPositioning : uint8_t {
kDefault_Positioning = 0, // Default glyph advances -- zero scalars per glyph.
kHorizontal_Positioning = 1, // Horizontal positioning -- one scalar per glyph.
kFull_Positioning = 2 // Point positioning -- two scalars per glyph.
};
@param text character code points or glyphs drawn
@param byteLength byte length of text array
@param paint text size, typeface, text scale, and so on, used to draw
@return SkTextBlob constructed from one run
*/
static sk_sp<SkTextBlob> MakeFromText(
const void* text, size_t byteLength, const SkPaint& paint);
/**
* Serialize the typeface into a data blob, storing type uniqueID of each referenced typeface.
* During this process, each time a typeface is encountered, it is passed to the catalog,
* allowing the caller to what typeface IDs will need to be resolved in Deserialize().
*/
sk_sp<SkData> serialize(SkTypefaceCatalogerProc, void* ctx) const;
/** Creates SkTextBlob with a single run. string meaning depends on SkPaint::TextEncoding;
by default, string is encoded as UTF-8.
/**
* Re-create a text blob previously serialized. Since the serialized form records the uniqueIDs
* of its typefaces, deserialization requires that the caller provide the corresponding
* SkTypefaces for those IDs.
*/
paint contains SkPaint::FontMetrics used to define the run text:
SkTypeface, SkPaint text size, SkPaint text scale x,
SkPaint text skew x, SkPaint::Align, SkPaint::Hinting, anti-alias, SkPaint fake bold,
SkPaint font embedded bitmaps, SkPaint full hinting spacing, LCD text, SkPaint linear text,
and SkPaint subpixel text.
@param string character code points or glyphs drawn
@param paint text size, typeface, text scale, and so on, used to draw
@return SkTextBlob constructed from one run
*/
static sk_sp<SkTextBlob> MakeFromString(const char* string, const SkPaint& paint) {
if (!string) {
return nullptr;
}
return MakeFromText(string, strlen(string), paint);
}
/** Writes data to allow later reconstruction of SkTextBlob. memory points to storage
to receive the encoded data, and memory_size describes the size of storage.
Returns bytes used if provided storage is large enough to hold all data;
otherwise, returns zero.
procs.fTypefaceProc permits supplying a custom function to encode SkTypeface.
If procs.fTypefaceProc is nullptr, default encoding is used. procs.fTypefaceCtx
may be used to provide user context to procs.fTypefaceProc; procs.fTypefaceProc
is called with a pointer to SkTypeface and user context.
@param procs custom serial data encoders; may be nullptr
@param memory storage for data
@param size size of storage
@return bytes written, or zero if required storage is larger than memory_size
*/
size_t serialize(const SkSerialProcs& procs, void* memory, size_t memory_size) const;
/** Returns storage containing SkData describing SkTextBlob, using optional custom
encoders.
procs.fTypefaceProc permits supplying a custom function to encode SkTypeface.
If procs.fTypefaceProc is nullptr, default encoding is used. procs.fTypefaceCtx
may be used to provide user context to procs.fTypefaceProc; procs.fTypefaceProc
is called with a pointer to SkTypeface and user context.
@param procs custom serial data encoders; may be nullptr
@return storage containing serialized SkTextBlob
*/
sk_sp<SkData> serialize(const SkSerialProcs& procs) const;
/** Recreates SkTextBlob that was serialized into data. Returns constructed SkTextBlob
if successful; otherwise, returns nullptr. Fails if size is smaller than
required data length, or if data does not permit constructing valid SkTextBlob.
procs.fTypefaceProc permits supplying a custom function to decode SkTypeface.
If procs.fTypefaceProc is nullptr, default decoding is used. procs.fTypefaceCtx
may be used to provide user context to procs.fTypefaceProc; procs.fTypefaceProc
is called with a pointer to SkTypeface data, data byte length, and user context.
@param data pointer for serial data
@param size size of data
@param procs custom serial data decoders; may be nullptr
@return SkTextBlob constructed from data in memory
*/
static sk_sp<SkTextBlob> Deserialize(const void* data, size_t size,
SkTypefaceResolverProc, void* ctx);
sk_sp<SkData> serialize(const SkSerialProcs&) const;
sk_sp<SkData> serialize() const;
static sk_sp<SkTextBlob> Deserialize(const void* data, size_t size, const SkDeserialProcs&);
static sk_sp<SkTextBlob> Deserialize(const void* data, size_t size);
const SkDeserialProcs& procs);
private:
friend class SkNVRefCnt<SkTextBlob>;
class RunRecord;
enum GlyphPositioning : uint8_t;
explicit SkTextBlob(const SkRect& bounds);
~SkTextBlob();
// Memory for objects of this class is created with sk_malloc rather than operator new and must
// be freed with sk_free.
void operator delete(void* p) { sk_free(p); }
void* operator new(size_t) {
SK_ABORT("All blobs are created by placement new.");
return sk_malloc_throw(0);
}
void* operator new(size_t, void* p) { return p; }
void operator delete(void* p);
void* operator new(size_t);
void* operator new(size_t, void* p);
static unsigned ScalarsPerGlyph(GlyphPositioning pos);
@ -104,13 +158,15 @@ private:
fCacheID.store(cacheID);
}
friend class SkGlyphRunList;
friend class GrTextBlobCache;
friend class SkTextBlobBuilder;
friend class SkTextBlobPriv;
friend class SkTextBlobRunIterator;
const SkRect fBounds;
const uint32_t fUniqueID;
mutable SkAtomic<uint32_t> fCacheID;
const SkRect fBounds;
const uint32_t fUniqueID;
mutable std::atomic<uint32_t> fCacheID;
SkDEBUGCODE(size_t fStorageSize;)
@ -121,68 +177,139 @@ private:
};
/** \class SkTextBlobBuilder
Helper class for constructing SkTextBlobs.
*/
Helper class for constructing SkTextBlob.
*/
class SK_API SkTextBlobBuilder {
public:
/** Constructs empty SkTextBlobBuilder. By default, SkTextBlobBuilder has no runs.
@return empty SkTextBlobBuilder
*/
SkTextBlobBuilder();
/** Deletes data allocated internally by SkTextBlobBuilder.
*/
~SkTextBlobBuilder();
/**
* Returns an immutable SkTextBlob for the current runs/glyphs,
* or nullptr if no runs were allocated.
*
* The builder is reset and can be reused.
*/
/** Returns SkTextBlob built from runs of glyphs added by builder. Returned
SkTextBlob is immutable; it may be copied, but its contents may not be altered.
Returns nullptr if no runs of glyphs were added by builder.
Resets SkTextBlobBuilder to its initial empty state, allowing it to be
reused to build a new set of runs.
@return SkTextBlob or nullptr
*/
sk_sp<SkTextBlob> make();
/**
* Glyph and position buffers associated with a run.
*
* A run is a sequence of glyphs sharing the same font metrics
* and positioning mode.
*
* If textByteCount is 0, utf8text and clusters will be NULL (no
* character information will be associated with the glyphs).
*
* utf8text will point to a buffer of size textByteCount bytes.
*
* clusters (if not NULL) will point to an array of size count.
* For each glyph, give the byte-offset into the text for the
* first byte in the first character in that glyph's cluster.
* Each value in the array should be an integer less than
* textByteCount. Values in the array should either be
* monotonically increasing (left-to-right text) or monotonically
* decreasing (right-to-left text). This definiton is conviently
* the same as used by Harfbuzz's hb_glyph_info_t::cluster field,
* except that Harfbuzz interleaves glyphs and clusters.
*/
/** \struct SkTextBlobBuilder::RunBuffer
RunBuffer supplies storage for glyphs and positions within a run.
A run is a sequence of glyphs sharing SkPaint::FontMetrics and positioning.
Each run may position its glyphs in one of three ways:
by specifying where the first glyph is drawn, and allowing SkPaint::FontMetrics to
determine the advance to subsequent glyphs; by specifying a baseline, and
the position on that baseline for each glyph in run; or by providing SkPoint
array, one per glyph.
*/
struct RunBuffer {
SkGlyphID* glyphs;
SkScalar* pos;
char* utf8text;
uint32_t* clusters;
SkGlyphID* glyphs; //!< storage for glyphs in run
SkScalar* pos; //!< storage for positions in run
char* utf8text; //!< reserved for future use
uint32_t* clusters; //!< reserved for future use
};
/**
* Allocates a new default-positioned run and returns its writable glyph buffer
* for direct manipulation.
*
* @param font The font to be used for this run.
* @param count Number of glyphs.
* @param x,y Position within the blob.
* @param textByteCount length of the original UTF-8 text that
* corresponds to this sequence of glyphs. If 0,
* text will not be included in the textblob.
* @param lang Language code, currently unimplemented.
* @param bounds Optional run bounding box. If known in advance (!= NULL), it will
* be used when computing the blob bounds, to avoid re-measuring.
*
* @return A writable glyph buffer, valid until the next allocRun() or
* build() call. The buffer is guaranteed to hold @count@ glyphs.
*/
/** Returns run with storage for glyphs. Caller must write count glyphs to
RunBuffer.glyphs() before next call to FontBlobBuilder.
RunBuffer.utf8text(), and RunBuffer.clusters() should be ignored.
Glyphs share SkPaint::FontMetrics in font, including:
SkTypeface, SkPaint text size, SkPaint text scale x,
SkPaint text skew x, SkPaint::Align, SkPaint::Hinting, anti-alias, SkPaint fake bold,
SkPaint font embedded bitmaps, SkPaint full hinting spacing, LCD text, SkPaint linear text,
and SkPaint subpixel text.
Glyphs are positioned on a baseline at (x, y), using font SkPaint::FontMetrics to
determine their relative placement.
bounds defines an optional bounding box, used to suppress drawing when SkTextBlob
bounds does not intersect SkSurface bounds. If bounds is nullptr, SkTextBlob bounds
is computed from (x, y) and RunBuffer.glyphs() SkPaint::FontMetrics.
@param font SkPaint used for this run
@param count number of glyphs
@param x horizontal offset within the blob
@param y vertical offset within the blob
@param bounds optional run bounding box
@return writable glyph buffer
*/
const RunBuffer& allocRun(const SkPaint& font, int count, SkScalar x, SkScalar y,
const SkRect* bounds = nullptr) {
return this->allocRunText(font, count, x, y, 0, SkString(), bounds);
}
/** Returns run with storage for glyphs and positions along baseline. Caller must
write count glyphs to RunBuffer.glyphs(), and count scalars to RunBuffer.pos();
before next call to FontBlobBuilder.
RunBuffer.utf8text(), and RunBuffer.clusters() should be ignored.
Glyphs share SkPaint::FontMetrics in font, including:
SkTypeface, SkPaint text size, SkPaint text scale x,
SkPaint text skew x, SkPaint::Align, SkPaint::Hinting, anti-alias, SkPaint fake bold,
SkPaint font embedded bitmaps, SkPaint full hinting spacing, LCD text, SkPaint linear text,
and SkPaint subpixel text.
Glyphs are positioned on a baseline at y, using x-axis positions written by
caller to RunBuffer.pos().
bounds defines an optional bounding box, used to suppress drawing when SkTextBlob
bounds does not intersect SkSurface bounds. If bounds is nullptr, SkTextBlob bounds
is computed from y, RunBuffer.pos(), and RunBuffer.glyphs() SkPaint::FontMetrics.
@param font SkPaint used for this run
@param count number of glyphs
@param y vertical offset within the blob
@param bounds optional run bounding box
@return writable glyph buffer and x-axis position buffer
*/
const RunBuffer& allocRunPosH(const SkPaint& font, int count, SkScalar y,
const SkRect* bounds = nullptr) {
return this->allocRunTextPosH(font, count, y, 0, SkString(), bounds);
}
/** Returns run with storage for glyphs and SkPoint positions. Caller must
write count glyphs to RunBuffer.glyphs(), and count SkPoint to RunBuffer.pos();
before next call to FontBlobBuilder.
RunBuffer.utf8text(), and RunBuffer.clusters() should be ignored.
Glyphs share SkPaint::FontMetrics in font, including:
SkTypeface, SkPaint text size, SkPaint text scale x,
SkPaint text skew x, SkPaint::Align, SkPaint::Hinting, anti-alias, SkPaint fake bold,
SkPaint font embedded bitmaps, SkPaint full hinting spacing, LCD text, SkPaint linear text,
and SkPaint subpixel text.
Glyphs are positioned using SkPoint written by caller to RunBuffer.pos(), using
two scalar values for each SkPoint.
bounds defines an optional bounding box, used to suppress drawing when SkTextBlob
bounds does not intersect SkSurface bounds. If bounds is nullptr, SkTextBlob bounds
is computed from RunBuffer.pos(), and RunBuffer.glyphs() SkPaint::FontMetrics.
@param font SkPaint used for this run
@param count number of glyphs
@param bounds optional run bounding box
@return writable glyph buffer and SkPoint buffer
*/
const RunBuffer& allocRunPos(const SkPaint& font, int count,
const SkRect* bounds = nullptr) {
return this->allocRunTextPos(font, count, 0, SkString(), bounds);
}
private:
const RunBuffer& allocRunText(const SkPaint& font,
int count,
SkScalar x,
@ -190,62 +317,12 @@ public:
int textByteCount,
SkString lang,
const SkRect* bounds = nullptr);
const RunBuffer& allocRun(const SkPaint& font, int count, SkScalar x, SkScalar y,
const SkRect* bounds = nullptr) {
return this->allocRunText(font, count, x, y, 0, SkString(), bounds);
}
/**
* Allocates a new horizontally-positioned run and returns its writable glyph and position
* buffers for direct manipulation.
*
* @param font The font to be used for this run.
* @param count Number of glyphs.
* @param y Vertical offset within the blob.
* @param textByteCount length of the original UTF-8 text that
* corresponds to this sequence of glyphs. If 0,
* text will not be included in the textblob.
* @param lang Language code, currently unimplemented.
* @param bounds Optional run bounding box. If known in advance (!= NULL), it will
* be used when computing the blob bounds, to avoid re-measuring.
*
* @return Writable glyph and position buffers, valid until the next allocRun()
* or build() call. The buffers are guaranteed to hold @count@ elements.
*/
const RunBuffer& allocRunTextPosH(const SkPaint& font, int count, SkScalar y,
int textByteCount, SkString lang,
const SkRect* bounds = nullptr);
const RunBuffer& allocRunPosH(const SkPaint& font, int count, SkScalar y,
const SkRect* bounds = nullptr) {
return this->allocRunTextPosH(font, count, y, 0, SkString(), bounds);
}
/**
* Allocates a new fully-positioned run and returns its writable glyph and position
* buffers for direct manipulation.
*
* @param font The font to be used for this run.
* @param count Number of glyphs.
* @param textByteCount length of the original UTF-8 text that
* corresponds to this sequence of glyphs. If 0,
* text will not be included in the textblob.
* @param lang Language code, currently unimplemented.
* @param bounds Optional run bounding box. If known in advance (!= NULL), it will
* be used when computing the blob bounds, to avoid re-measuring.
*
* @return Writable glyph and position buffers, valid until the next allocRun()
* or build() call. The glyph buffer and position buffer are
* guaranteed to hold @count@ and 2 * @count@ elements, respectively.
*/
const RunBuffer& allocRunTextPos(const SkPaint& font, int count,
int textByteCount, SkString lang,
const SkRect* bounds = nullptr);
const RunBuffer& allocRunPos(const SkPaint& font, int count,
const SkRect* bounds = nullptr) {
return this->allocRunTextPos(font, count, 0, SkString(), bounds);
}
private:
void reserve(size_t size);
void allocInternal(const SkPaint& font, SkTextBlob::GlyphPositioning positioning,
int count, int textBytes, SkPoint offset, const SkRect* bounds);
@ -256,6 +333,9 @@ private:
static SkRect ConservativeRunBounds(const SkTextBlob::RunRecord&);
static SkRect TightRunBounds(const SkTextBlob::RunRecord&);
friend class SkTextBlobPriv;
friend class SkTextBlobBuilderPriv;
SkAutoTMalloc<uint8_t> fStorage;
size_t fStorageSize;
size_t fStorageUsed;

Просмотреть файл

@ -10,6 +10,7 @@
#ifndef SkTime_DEFINED
#define SkTime_DEFINED
#include "../private/SkMacros.h"
#include "SkTypes.h"
class SkString;

Просмотреть файл

@ -50,6 +50,10 @@ public:
const char* units,
uint64_t value) = 0;
virtual void dumpStringValue(const char* /*dumpName*/,
const char* /*valueName*/,
const char* /*value*/) { }
/**
* Sets the memory backing for an existing dump.
* backingType and backingObjectId are used by the embedder to associate the memory dumped via
@ -73,6 +77,12 @@ public:
*/
virtual LevelOfDetail getRequestedDetails() const = 0;
/**
* Returns true if we should dump wrapped objects. Wrapped objects come from outside Skia, and
* may be independently tracked there.
*/
virtual bool shouldDumpWrappedObjects() const { return true; }
protected:
virtual ~SkTraceMemoryDump() { }
};

Просмотреть файл

@ -8,14 +8,16 @@
#ifndef SkTypeface_DEFINED
#define SkTypeface_DEFINED
#include "../private/SkBitmaskEnum.h"
#include "../private/SkNoncopyable.h"
#include "../private/SkOnce.h"
#include "../private/SkWeakRefCnt.h"
#include "SkFontArguments.h"
#include "SkFontParameters.h"
#include "SkFontStyle.h"
#include "SkRect.h"
#include "SkString.h"
class SkData;
class SkDescriptor;
class SkFontData;
class SkFontDescriptor;
@ -72,6 +74,20 @@ public:
int getVariationDesignPosition(SkFontArguments::VariationPosition::Coordinate coordinates[],
int coordinateCount) const;
/** Copy into 'parameters' (allocated by the caller) the design variation parameters.
*
* @param parameters the buffer into which to write the design variation parameters.
* @param coordinateCount the number of entries available through 'parameters'.
*
* @return The number of axes, or -1 if there is an error.
* If 'parameters != nullptr' and 'parameterCount >= numAxes' then 'parameters' will be
* filled with the variation parameters describing the position of this typeface in design
* variation space. It is possible the number of axes can be retrieved but actual parameters
* cannot.
*/
int getVariationDesignParameters(SkFontParameters::Variation::Axis parameters[],
int parameterCount) const;
/** Return a 32bit value for this typeface, unique for the underlying font
data. Will never return 0.
*/
@ -111,17 +127,47 @@ public:
not a valid font file, returns nullptr. Ownership of the stream is
transferred, so the caller must not reference it again.
*/
static sk_sp<SkTypeface> MakeFromStream(SkStreamAsset* stream, int index = 0);
static sk_sp<SkTypeface> MakeFromStream(std::unique_ptr<SkStreamAsset> stream, int index = 0);
/** Return a new typeface given a SkData. If the data is null, or is not a valid font file,
* returns nullptr.
*/
static sk_sp<SkTypeface> MakeFromData(sk_sp<SkData>, int index = 0);
/** Return a new typeface given font data and configuration. If the data
is not valid font data, returns nullptr.
*/
static sk_sp<SkTypeface> MakeFromFontData(std::unique_ptr<SkFontData>);
/** Return a new typeface based on this typeface but parameterized as specified in the
SkFontArguments. If the SkFontArguments does not supply an argument for a parameter
in the font then the value from this typeface will be used as the value for that
argument. If the cloned typeface would be exaclty the same as this typeface then
this typeface may be ref'ed and returned. May return nullptr on failure.
*/
sk_sp<SkTypeface> makeClone(const SkFontArguments&) const;
/**
* A typeface can serialize just a descriptor (names, etc.), or it can also include the
* actual font data (which can be large). This enum controls how serialize() decides what
* to serialize.
*/
enum class SerializeBehavior {
kDoIncludeData,
kDontIncludeData,
kIncludeDataIfLocal,
};
/** Write a unique signature to a stream, sufficient to reconstruct a
typeface referencing the same font when Deserialize is called.
*/
void serialize(SkWStream*) const;
void serialize(SkWStream*, SerializeBehavior = SerializeBehavior::kIncludeDataIfLocal) const;
/**
* Same as serialize(SkWStream*, ...) but returns the serialized data in SkData, instead of
* writing it to a stream.
*/
sk_sp<SkData> serialize(SerializeBehavior = SerializeBehavior::kIncludeDataIfLocal) const;
/** Given the data previously written by serialize(), return a new instance
of a typeface referring to the same font. If that font is not available,
@ -308,6 +354,8 @@ protected:
SkTypeface(const SkFontStyle& style, bool isFixedPitch = false);
virtual ~SkTypeface();
virtual sk_sp<SkTypeface> onMakeClone(const SkFontArguments&) const;
/** Sets the fixedPitch bit. If used, must be called in the constructor. */
void setIsFixedPitch(bool isFixedPitch) { fIsFixedPitch = isFixedPitch; }
/** Sets the font style. If used, must be called in the constructor. */
@ -316,9 +364,19 @@ protected:
virtual SkScalerContext* onCreateScalerContext(const SkScalerContextEffects&,
const SkDescriptor*) const = 0;
virtual void onFilterRec(SkScalerContextRec*) const = 0;
friend class SkScalerContext; // onFilterRec
// Subclasses *must* override this method to work with the PDF backend.
virtual std::unique_ptr<SkAdvancedTypefaceMetrics> onGetAdvancedMetrics() const;
// For type1 postscript fonts only, set the glyph names for each glyph.
// destination array is non-null, and points to an array of size this->countGlyphs().
// Backends that do not suport type1 fonts should not override.
virtual void getPostScriptGlyphNames(SkString*) const {}
// The mapping from glyph to Unicode; array indices are glyph ids.
// For each glyph, give the default Unicode value, if it exists.
// dstArray is non-null, and points to an array of size this->countGlyphs().
virtual void getGlyphToUnicodeMap(SkUnichar* dstArray) const;
virtual SkStreamAsset* onOpenStream(int* ttcIndex) const = 0;
// TODO: make pure virtual.
@ -328,6 +386,9 @@ protected:
SkFontArguments::VariationPosition::Coordinate coordinates[],
int coordinateCount) const = 0;
virtual int onGetVariationDesignParameters(
SkFontParameters::Variation::Axis parameters[], int parameterCount) const;
virtual void onGetFontDescriptor(SkFontDescriptor*, bool* isLocal) const = 0;
virtual int onCharsToGlyphs(const void* chars, Encoding, SkGlyphID glyphs[],
@ -371,10 +432,7 @@ private:
};
static SkFontStyle FromOldStyle(Style oldStyle);
static SkTypeface* GetDefaultTypeface(Style style = SkTypeface::kNormal);
friend class GrPathRendering; // GetDefaultTypeface
friend class SkGlyphCache; // GetDefaultTypeface
friend class SkPaint; // GetDefaultTypeface
friend class SkScalerContext; // GetDefaultTypeface
friend class SkPaintPriv; // GetDefaultTypeface
private:
SkFontID fUniqueID;

Просмотреть файл

@ -9,23 +9,6 @@
#define SkTypes_DEFINED
// IWYU pragma: begin_exports
// In at least two known scenarios when using GCC with libc++:
// * GCC 4.8 targeting ARMv7 with NEON
// * GCC 4.9 targeting ARMv8 64 bit
// we need to typedef float float32_t (or include <arm_neon.h> which does that)
// before #including <memory>. This makes no sense. I'm not very interested in
// understanding why... these are old, bizarre platform configuration that we
// should just let die.
// See https://llvm.org/bugs/show_bug.cgi?id=25608 .
#include <ciso646> // Include something innocuous to define _LIBCPP_VERISON if it's libc++.
#if defined(__GNUC__) && __GNUC__ == 4 \
&& ((defined(__arm__) && (defined(__ARM_NEON__) || defined(__ARM_NEON))) || defined(__aarch64__)) \
&& defined(_LIBCPP_VERSION)
typedef float float32_t;
#include <memory>
#endif
#include "SkPreConfig.h"
#include "SkUserConfig.h"
#include "SkPostConfig.h"
@ -33,13 +16,11 @@
#include <stdint.h>
// IWYU pragma: end_exports
#include <string.h>
/** \file SkTypes.h
*/
/** See SkGraphics::GetVersion() to retrieve these at runtime
*/
*/
#define SKIA_VERSION_MAJOR 1
#define SKIA_VERSION_MINOR 0
#define SKIA_VERSION_PATCH 0
@ -51,8 +32,6 @@
*/
SK_API extern void sk_abort_no_print(void);
#define SK_INIT_TO_AVOID_WARNING = 0
#ifndef SkDebugf
SK_API void SkDebugf(const char format[], ...);
#endif
@ -79,7 +58,7 @@ SK_API extern void sk_abort_no_print(void);
#define SkDEBUGFAIL(message) SK_ABORT(message)
#define SkDEBUGFAILF(fmt, ...) SkASSERTF(false, fmt, ##__VA_ARGS__)
#define SkDEBUGCODE(...) __VA_ARGS__
#define SkDEBUGF(args ) SkDebugf args
#define SkDEBUGF(...) SkDebugf(__VA_ARGS__)
#define SkAssertResult(cond) SkASSERT(cond)
#else
#define SkASSERT(cond) static_cast<void>(0)
@ -87,175 +66,77 @@ SK_API extern void sk_abort_no_print(void);
#define SkDEBUGFAIL(message)
#define SkDEBUGFAILF(fmt, ...)
#define SkDEBUGCODE(...)
#define SkDEBUGF(args)
#define SkDEBUGF(...)
// unlike SkASSERT, this guy executes its condition in the non-debug build.
// unlike SkASSERT, this macro executes its condition in the non-debug build.
// The if is present so that this can be used with functions marked SK_WARN_UNUSED_RESULT.
#define SkAssertResult(cond) if (cond) {} do {} while(false)
#endif
#ifdef SK_IGNORE_TO_STRING
#define SK_TO_STRING_NONVIRT()
#define SK_TO_STRING_VIRT()
#define SK_TO_STRING_PUREVIRT()
#define SK_TO_STRING_OVERRIDE()
#else
class SkString;
// the 'toString' helper functions convert Sk* objects to human-readable
// form in developer mode
#define SK_TO_STRING_NONVIRT() void toString(SkString* str) const;
#define SK_TO_STRING_VIRT() virtual void toString(SkString* str) const;
#define SK_TO_STRING_PUREVIRT() virtual void toString(SkString* str) const = 0;
#define SK_TO_STRING_OVERRIDE() void toString(SkString* str) const override;
#endif
////////////////////////////////////////////////////////////////////////////////
/*
* Usage: SK_MACRO_CONCAT(a, b) to construct the symbol ab
*
* SK_MACRO_CONCAT_IMPL_PRIV just exists to make this work. Do not use directly
*
*/
#define SK_MACRO_CONCAT(X, Y) SK_MACRO_CONCAT_IMPL_PRIV(X, Y)
#define SK_MACRO_CONCAT_IMPL_PRIV(X, Y) X ## Y
/*
* Usage: SK_MACRO_APPEND_LINE(foo) to make foo123, where 123 is the current
* line number. Easy way to construct
* unique names for local functions or
* variables.
*/
#define SK_MACRO_APPEND_LINE(name) SK_MACRO_CONCAT(name, __LINE__)
/**
* For some classes, it's almost always an error to instantiate one without a name, e.g.
* {
* SkAutoMutexAcquire(&mutex);
* <some code>
* }
* In this case, the writer meant to hold mutex while the rest of the code in the block runs,
* but instead the mutex is acquired and then immediately released. The correct usage is
* {
* SkAutoMutexAcquire lock(&mutex);
* <some code>
* }
*
* To prevent callers from instantiating your class without a name, use SK_REQUIRE_LOCAL_VAR
* like this:
* class classname {
* <your class>
* };
* #define classname(...) SK_REQUIRE_LOCAL_VAR(classname)
*
* This won't work with templates, and you must inline the class' constructors and destructors.
* Take a look at SkAutoFree and SkAutoMalloc in this file for examples.
*/
#define SK_REQUIRE_LOCAL_VAR(classname) \
static_assert(false, "missing name for " #classname)
///////////////////////////////////////////////////////////////////////
/**
* Fast type for signed 8 bits. Use for parameter passing and local variables,
* not for storage.
*/
typedef int S8CPU;
/**
* Fast type for unsigned 8 bits. Use for parameter passing and local
* variables, not for storage
*/
/** Fast type for unsigned 8 bits. Use for parameter passing and local
variables, not for storage
*/
typedef unsigned U8CPU;
/**
* Fast type for signed 16 bits. Use for parameter passing and local variables,
* not for storage
*/
typedef int S16CPU;
/**
* Fast type for unsigned 16 bits. Use for parameter passing and local
* variables, not for storage
*/
/** Fast type for unsigned 16 bits. Use for parameter passing and local
variables, not for storage
*/
typedef unsigned U16CPU;
/**
* Meant to be a small version of bool, for storage purposes. Will be 0 or 1
*/
typedef uint8_t SkBool8;
#include "../private/SkTFitsIn.h"
template <typename D, typename S> constexpr D SkTo(S s) {
return SkASSERT(SkTFitsIn<D>(s)),
static_cast<D>(s);
}
#define SkToS8(x) SkTo<int8_t>(x)
#define SkToU8(x) SkTo<uint8_t>(x)
#define SkToS16(x) SkTo<int16_t>(x)
#define SkToU16(x) SkTo<uint16_t>(x)
#define SkToS32(x) SkTo<int32_t>(x)
#define SkToU32(x) SkTo<uint32_t>(x)
#define SkToInt(x) SkTo<int>(x)
#define SkToUInt(x) SkTo<unsigned>(x)
#define SkToSizeT(x) SkTo<size_t>(x)
/** Returns 0 or 1 based on the condition
/** @return false or true based on the condition
*/
#define SkToBool(cond) ((cond) != 0)
template <typename T> static constexpr bool SkToBool(const T& x) { return 0 != x; }
#define SK_MaxS16 32767
#define SK_MinS16 -32767
#define SK_MaxU16 0xFFFF
#define SK_MinU16 0
#define SK_MaxS32 0x7FFFFFFF
#define SK_MinS32 -SK_MaxS32
#define SK_MaxU32 0xFFFFFFFF
#define SK_MinU32 0
#define SK_NaN32 ((int) (1U << 31))
#define SK_MaxSizeT SIZE_MAX
static constexpr int64_t SK_MaxS64 = 0x7FFFFFFFFFFFFFFF;
static constexpr int16_t SK_MaxS16 = INT16_MAX;
static constexpr int16_t SK_MinS16 = -SK_MaxS16;
static constexpr int32_t SK_MaxS32 = INT32_MAX;
static constexpr int32_t SK_MinS32 = -SK_MaxS32;
static constexpr int32_t SK_NaN32 = INT32_MIN;
static constexpr int64_t SK_MaxS64 = INT64_MAX;
static constexpr int64_t SK_MinS64 = -SK_MaxS64;
static inline int32_t SkLeftShift(int32_t value, int32_t shift) {
static inline constexpr int32_t SkLeftShift(int32_t value, int32_t shift) {
return (int32_t) ((uint32_t) value << shift);
}
static inline int64_t SkLeftShift(int64_t value, int32_t shift) {
static inline constexpr int64_t SkLeftShift(int64_t value, int32_t shift) {
return (int64_t) ((uint64_t) value << shift);
}
//////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/** Returns the number of entries in an array (not a pointer) */
/** @return the number of entries in an array (not a pointer)
*/
template <typename T, size_t N> char (&SkArrayCountHelper(T (&array)[N]))[N];
#define SK_ARRAY_COUNT(array) (sizeof(SkArrayCountHelper(array)))
// Can be used to bracket data types that must be dense, e.g. hash keys.
#if defined(__clang__) // This should work on GCC too, but GCC diagnostic pop didn't seem to work!
#define SK_BEGIN_REQUIRE_DENSE _Pragma("GCC diagnostic push") \
_Pragma("GCC diagnostic error \"-Wpadded\"")
#define SK_END_REQUIRE_DENSE _Pragma("GCC diagnostic pop")
#else
#define SK_BEGIN_REQUIRE_DENSE
#define SK_END_REQUIRE_DENSE
#endif
////////////////////////////////////////////////////////////////////////////////
#define SkAlign2(x) (((x) + 1) >> 1 << 1)
#define SkIsAlign2(x) (0 == ((x) & 1))
template <typename T> static constexpr T SkAlign2(T x) { return (x + 1) >> 1 << 1; }
template <typename T> static constexpr T SkAlign4(T x) { return (x + 3) >> 2 << 2; }
template <typename T> static constexpr T SkAlign8(T x) { return (x + 7) >> 3 << 3; }
#define SkAlign4(x) (((x) + 3) >> 2 << 2)
#define SkIsAlign4(x) (0 == ((x) & 3))
template <typename T> static constexpr bool SkIsAlign2(T x) { return 0 == (x & 1); }
template <typename T> static constexpr bool SkIsAlign4(T x) { return 0 == (x & 3); }
template <typename T> static constexpr bool SkIsAlign8(T x) { return 0 == (x & 7); }
#define SkAlign8(x) (((x) + 7) >> 3 << 3)
#define SkIsAlign8(x) (0 == ((x) & 7))
#define SkAlign16(x) (((x) + 15) >> 4 << 4)
#define SkIsAlign16(x) (0 == ((x) & 15))
#define SkAlignPtr(x) (sizeof(void*) == 8 ? SkAlign8(x) : SkAlign4(x))
#define SkIsAlignPtr(x) (sizeof(void*) == 8 ? SkIsAlign8(x) : SkIsAlign4(x))
template <typename T> static constexpr T SkAlignPtr(T x) {
return sizeof(void*) == 8 ? SkAlign8(x) : SkAlign4(x);
}
template <typename T> static constexpr bool SkIsAlignPtr(T x) {
return sizeof(void*) == 8 ? SkIsAlign8(x) : SkIsAlign4(x);
}
typedef uint32_t SkFourByteTag;
#define SkSetFourByteTag(a, b, c, d) (((a) << 24) | ((b) << 16) | ((c) << 8) | (d))
static inline constexpr SkFourByteTag SkSetFourByteTag(char a, char b, char c, char d) {
return (((uint8_t)a << 24) | ((uint8_t)b << 16) | ((uint8_t)c << 8) | (uint8_t)d);
}
////////////////////////////////////////////////////////////////////////////////
/** 32 bit integer to hold a unicode value
*/
@ -266,47 +147,21 @@ typedef int32_t SkUnichar;
typedef uint16_t SkGlyphID;
/** 32 bit value to hold a millisecond duration
* Note that SK_MSecMax is about 25 days.
*/
Note that SK_MSecMax is about 25 days.
*/
typedef uint32_t SkMSec;
/** 1 second measured in milliseconds
/** Maximum representable milliseconds; 24d 20h 31m 23.647s.
*/
#define SK_MSec1 1000
/** maximum representable milliseconds; 24d 20h 31m 23.647s.
*/
#define SK_MSecMax 0x7FFFFFFF
/** Returns a < b for milliseconds, correctly handling wrap-around from 0xFFFFFFFF to 0
*/
#define SkMSec_LT(a, b) ((int32_t)(a) - (int32_t)(b) < 0)
/** Returns a <= b for milliseconds, correctly handling wrap-around from 0xFFFFFFFF to 0
*/
#define SkMSec_LE(a, b) ((int32_t)(a) - (int32_t)(b) <= 0)
static constexpr SkMSec SK_MSecMax = INT32_MAX;
/** The generation IDs in Skia reserve 0 has an invalid marker.
*/
#define SK_InvalidGenID 0
*/
static constexpr uint32_t SK_InvalidGenID = 0;
/** The unique IDs in Skia reserve 0 has an invalid marker.
*/
#define SK_InvalidUniqueID 0
/****************************************************************************
The rest of these only build with C++
*/
#ifdef __cplusplus
/** Faster than SkToBool for integral conditions. Returns 0 or 1
*/
static inline constexpr int Sk32ToBool(uint32_t n) {
return (n | (0-n)) >> 31;
}
/** Generic swap function. Classes with efficient swaps should specialize this function to take
their fast path. This function is used by SkTSort. */
template <typename T> static inline void SkTSwap(T& a, T& b) {
T c(std::move(a));
a = std::move(b);
b = std::move(c);
}
static constexpr uint32_t SK_InvalidUniqueID = 0;
static inline int32_t SkAbs32(int32_t value) {
SkASSERT(value != SK_NaN32); // The most negative int32_t can't be negated.
@ -343,81 +198,31 @@ template <typename T> constexpr const T& SkTMax(const T& a, const T& b) {
return (b < a) ? a : b;
}
static inline int32_t SkSign32(int32_t a) {
return (a >> 31) | ((unsigned) -a >> 31);
template <typename T> constexpr const T& SkTClamp(const T& x, const T& lo, const T& hi) {
return (x < lo) ? lo : SkTMin(x, hi);
}
static inline int32_t SkFastMin32(int32_t value, int32_t max) {
if (value > max) {
value = max;
}
return value;
}
/** Returns value pinned between min and max, inclusively. */
/** @return value pinned (clamped) between min and max, inclusively.
*/
template <typename T> static constexpr const T& SkTPin(const T& value, const T& min, const T& max) {
return SkTMax(SkTMin(value, max), min);
}
////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
/**
* Indicates whether an allocation should count against a cache budget.
*/
/** Indicates whether an allocation should count against a cache budget.
*/
enum class SkBudgeted : bool {
kNo = false,
kYes = true
};
/**
* Indicates whether a backing store needs to be an exact match or can be larger
* than is strictly necessary
*/
/** Indicates whether a backing store needs to be an exact match or can be
larger than is strictly necessary
*/
enum class SkBackingFit {
kApprox,
kExact
};
///////////////////////////////////////////////////////////////////////////////
/** Use to combine multiple bits in a bitmask in a type safe way.
*/
template <typename T>
T SkTBitOr(T a, T b) {
return (T)(a | b);
}
/**
* Use to cast a pointer to a different type, and maintaining strict-aliasing
*/
template <typename Dst> Dst SkTCast(const void* ptr) {
union {
const void* src;
Dst dst;
} data;
data.src = ptr;
return data.dst;
}
//////////////////////////////////////////////////////////////////////////////
/** \class SkNoncopyable
SkNoncopyable is the base class for objects that do not want to
be copied. It hides its copy-constructor and its assignment-operator.
*/
class SK_API SkNoncopyable {
public:
SkNoncopyable() = default;
SkNoncopyable(SkNoncopyable&&) = default;
SkNoncopyable& operator =(SkNoncopyable&&) = default;
SkNoncopyable(const SkNoncopyable&) = delete;
SkNoncopyable& operator=(const SkNoncopyable&) = delete;
};
#endif /* C++ */
#endif

Просмотреть файл

@ -19,6 +19,81 @@
*/
class SK_API SkVertices : public SkNVRefCnt<SkVertices> {
public:
// BoneIndices indicates which (of a maximum of 4 bones) a given vertex will interpolate
// between. To indicate that a slot is not used, the convention is to assign the bone index
// to 0.
struct BoneIndices {
uint32_t indices[4];
uint32_t& operator[] (int i) {
SkASSERT(i >= 0);
SkASSERT(i < 4);
return indices[i];
}
const uint32_t& operator[] (int i) const {
SkASSERT(i >= 0);
SkASSERT(i < 4);
return indices[i];
}
};
// BoneWeights stores the interpolation weight for each of the (maximum of 4) bones a given
// vertex interpolates between. To indicate that a slot is not used, the weight for that
// slot should be 0.
struct BoneWeights {
float weights[4];
float& operator[] (int i) {
SkASSERT(i >= 0);
SkASSERT(i < 4);
return weights[i];
}
const float& operator[] (int i) const {
SkASSERT(i >= 0);
SkASSERT(i < 4);
return weights[i];
}
};
// Bone stores a 3x2 transformation matrix in column major order:
// | scaleX skewX transX |
// | skewY scaleY transY |
// SkRSXform is insufficient because bones can have non uniform scale.
struct Bone {
float values[6];
float& operator[] (int i) {
SkASSERT(i >= 0);
SkASSERT(i < 6);
return values[i];
}
const float& operator[] (int i) const {
SkASSERT(i >= 0);
SkASSERT(i < 6);
return values[i];
}
SkPoint mapPoint(const SkPoint& point) const {
float x = values[0] * point.x() + values[2] * point.y() + values[4];
float y = values[1] * point.x() + values[3] * point.y() + values[5];
return SkPoint::Make(x, y);
}
SkRect mapRect(const SkRect& rect) const {
SkRect dst = SkRect::MakeEmpty();
SkPoint quad[4];
rect.toQuad(quad);
for (int i = 0; i < 4; i ++) {
quad[i] = mapPoint(quad[i]);
}
dst.setBoundsNoCheck(quad, 4);
return dst;
}
};
enum VertexMode {
kTriangles_VertexMode,
kTriangleStrip_VertexMode,
@ -28,21 +103,66 @@ public:
};
/**
* Create a vertices by copying the specified arrays. texs and colors may be nullptr,
* and indices is ignored if indexCount == 0.
* Create a vertices by copying the specified arrays. texs, colors, boneIndices, and
* boneWeights may be nullptr, and indices is ignored if indexCount == 0.
*
* boneIndices and boneWeights must either both be nullptr or both point to valid data.
* If specified, they must both contain 'vertexCount' entries.
*/
static sk_sp<SkVertices> MakeCopy(VertexMode mode, int vertexCount,
const SkPoint positions[],
const SkPoint texs[],
const SkColor colors[],
const BoneIndices boneIndices[],
const BoneWeights boneWeights[],
int indexCount,
const uint16_t indices[]);
const uint16_t indices[],
bool isVolatile = true);
static sk_sp<SkVertices> MakeCopy(VertexMode mode, int vertexCount,
const SkPoint positions[],
const SkPoint texs[],
const SkColor colors[]) {
return MakeCopy(mode, vertexCount, positions, texs, colors, 0, nullptr);
const SkColor colors[],
const BoneIndices boneIndices[],
const BoneWeights boneWeights[],
bool isVolatile = true) {
return MakeCopy(mode,
vertexCount,
positions,
texs,
colors,
boneIndices,
boneWeights,
0,
nullptr,
isVolatile);
}
static sk_sp<SkVertices> MakeCopy(VertexMode mode, int vertexCount,
const SkPoint positions[],
const SkPoint texs[],
const SkColor colors[],
int indexCount,
const uint16_t indices[],
bool isVolatile = true) {
return MakeCopy(mode,
vertexCount,
positions,
texs,
colors,
nullptr,
nullptr,
indexCount,
indices,
isVolatile);
}
static sk_sp<SkVertices> MakeCopy(VertexMode mode, int vertexCount,
const SkPoint positions[],
const SkPoint texs[],
const SkColor colors[],
bool isVolatile = true) {
return MakeCopy(mode, vertexCount, positions, texs, colors, nullptr, nullptr, isVolatile);
}
struct Sizes;
@ -50,6 +170,8 @@ public:
enum BuilderFlags {
kHasTexCoords_BuilderFlag = 1 << 0,
kHasColors_BuilderFlag = 1 << 1,
kHasBones_BuilderFlag = 1 << 2,
kIsNonVolatile_BuilderFlag = 1 << 3,
};
class Builder {
public:
@ -60,21 +182,27 @@ public:
// if the builder is invalid, these will return 0
int vertexCount() const;
int indexCount() const;
bool isVolatile() const;
SkPoint* positions();
SkPoint* texCoords(); // returns null if there are no texCoords
SkColor* colors(); // returns null if there are no colors
uint16_t* indices(); // returns null if there are no indices
SkPoint* texCoords(); // returns null if there are no texCoords
SkColor* colors(); // returns null if there are no colors
BoneIndices* boneIndices(); // returns null if there are no bone indices
BoneWeights* boneWeights(); // returns null if there are no bone weights
uint16_t* indices(); // returns null if there are no indices
// Detach the built vertices object. After the first call, this will always return null.
sk_sp<SkVertices> detach();
private:
Builder(VertexMode mode, int vertexCount, int indexCount, const Sizes&);
Builder(VertexMode mode, int vertexCount, int indexCount, bool isVolatile, const Sizes&);
void init(VertexMode mode, int vertexCount, int indexCount, const Sizes&);
void init(VertexMode mode, int vertexCount, int indexCount, bool isVolatile, const Sizes&);
// holds a partially complete object. only completed in detach()
sk_sp<SkVertices> fVertices;
// Extra storage for intermediate vertices in the case where the client specifies indexed
// triangle fans. These get converted to indexed triangles when the Builder is finalized.
std::unique_ptr<uint8_t[]> fIntermediateFanIndices;
friend class SkVertices;
};
@ -85,6 +213,7 @@ public:
bool hasColors() const { return SkToBool(this->colors()); }
bool hasTexCoords() const { return SkToBool(this->texCoords()); }
bool hasBones() const { return SkToBool(this->boneIndices()); }
bool hasIndices() const { return SkToBool(this->indices()); }
int vertexCount() const { return fVertexCnt; }
@ -92,9 +221,16 @@ public:
const SkPoint* texCoords() const { return fTexs; }
const SkColor* colors() const { return fColors; }
const BoneIndices* boneIndices() const { return fBoneIndices; }
const BoneWeights* boneWeights() const { return fBoneWeights; }
int indexCount() const { return fIndexCnt; }
const uint16_t* indices() const { return fIndices; }
bool isVolatile() const { return fIsVolatile; }
sk_sp<SkVertices> applyBones(const Bone bones[], int boneCount) const;
// returns approximate byte size of the vertices object
size_t approximateSize() const;
@ -115,7 +251,7 @@ private:
// these are needed since we've manually sized our allocation (see Builder::init)
friend class SkNVRefCnt<SkVertices>;
void operator delete(void* p) { ::operator delete(p); }
void operator delete(void* p);
static sk_sp<SkVertices> Alloc(int vCount, int iCount, uint32_t builderFlags,
size_t* arraySize);
@ -125,15 +261,19 @@ private:
uint32_t fUniqueID;
// these point inside our allocation, so none of these can be "freed"
SkPoint* fPositions;
SkPoint* fTexs;
SkColor* fColors;
uint16_t* fIndices;
SkPoint* fPositions;
SkPoint* fTexs;
SkColor* fColors;
BoneIndices* fBoneIndices;
BoneWeights* fBoneWeights;
uint16_t* fIndices;
SkRect fBounds; // computed to be the union of the fPositions[]
int fVertexCnt;
int fIndexCnt;
bool fIsVolatile;
VertexMode fMode;
// below here is where the actual array data is stored.
};

Просмотреть файл

@ -0,0 +1,88 @@
/*
* Copyright 2018 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef SkYUVAIndex_DEFINED
#define SkYUVAIndex_DEFINED
#include "SkTypes.h"
/** \enum SkColorChannel
Describes different color channels one can manipulate
*/
enum class SkColorChannel {
kR, // the red channel
kG, // the green channel
kB, // the blue channel
kA, // the alpha channel
kLastEnum = kA,
};
/** \struct SkYUVAIndex
Describes from which image source and which channel to read each individual YUVA plane.
SkYUVAIndex contains a index for which image source to read from and a enum for which channel
to read from.
*/
struct SK_API SkYUVAIndex {
bool operator==(const SkYUVAIndex& that) const {
return this->fIndex == that.fIndex && this->fChannel == that.fChannel;
}
bool operator!=(const SkYUVAIndex& that) const {
return !(*this == that);
}
// Index in the array of SkYUVAIndex
enum Index {
kY_Index = 0,
kU_Index = 1,
kV_Index = 2,
kA_Index = 3
};
/** The index is a number between -1..3 which definies which image source to read from, where -1
* means the image source doesn't exist. The assumption is we will always have image sources for
* each of YUV planes, but optionally have image source for A plane. */
int fIndex;
/** The channel describes from which channel to read the info from. Currently we only deal with
* YUV and NV12 and channel info is ignored. */
SkColorChannel fChannel;
static bool AreValidIndices(const SkYUVAIndex yuvaIndices[4], int* numPlanes) {
// Note that 'numPlanes' is always filled in even if the indices are not valid.
// This means it can always be used to process the backing resources (but be careful
// of empty intervening slots).
int maxSlotUsed = -1;
bool used[4] = { false, false, false, false };
bool valid = true;
for (int i = 0; i < 4; ++i) {
if (yuvaIndices[i].fIndex < 0) {
if (SkYUVAIndex::kA_Index != i) {
valid = false; // only the 'A' plane can be omitted
}
} else if (yuvaIndices[i].fIndex > 3) {
valid = false; // A maximum of four input textures is allowed
} else {
maxSlotUsed = SkTMax(yuvaIndices[i].fIndex, maxSlotUsed);
used[i] = true;
}
}
// All the used slots should be packed starting at 0 with no gaps
for (int i = 0; i <= maxSlotUsed; ++i) {
if (!used[i]) {
valid = false;
}
}
*numPlanes = maxSlotUsed + 1;
return valid;
}
};
#endif

Просмотреть файл

@ -11,7 +11,7 @@
#include "SkSize.h"
struct SkYUVSizeInfo {
enum {
enum YUVIndex {
kY = 0,
kU = 1,
kV = 2,

Просмотреть файл

@ -0,0 +1,176 @@
// Copyright 2018 Google LLC.
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
#ifndef SkPDFDocument_DEFINED
#define SkPDFDocument_DEFINED
#include "SkDocument.h"
#include "SkScalar.h"
#include "SkString.h"
#include "SkTime.h"
namespace SkPDF {
/** Table 333 in PDF 32000-1:2008
*/
enum class DocumentStructureType {
kDocument,
kPart,
kArt, // Article
kSect, // Section
kDiv,
kBlockQuote,
kCaption,
kTOC, // Table of Contents
kTOCI, // Table of Contents Item
kIndex,
kNonStruct,
kPrivate,
kH, // Heading
kH1, // Heading level 1
kH2,
kH3,
kH4,
kH5,
kH6, // Heading level 6
kP, // Paragraph
kL, // List
kLI, // List item
kLbl, // List item label
kLBody, // List item body
kTable,
kTR,
kTH,
kTD,
kTHead,
kTBody,
kTFoot,
kSpan,
kQuote,
kNote,
kReference,
kBibEntry,
kCode,
kLink,
kAnnot,
kRuby,
kWarichu,
kFigure,
kFormula,
kForm, // Form control (not like an HTML FORM element)
};
/**
* A node in a PDF structure tree, giving a semantic representation
* of the content. Each node ID is associated with content
* by passing the SkCanvas and node ID to SkPDF::SetNodeId() when drawing.
*/
struct StructureElementNode {
const StructureElementNode* fChildren = nullptr;
size_t fChildCount;
int fNodeId;
DocumentStructureType fType;
};
/** Optional metadata to be passed into the PDF factory function.
*/
struct Metadata {
/** The document's title.
*/
SkString fTitle;
/** The name of the person who created the document.
*/
SkString fAuthor;
/** The subject of the document.
*/
SkString fSubject;
/** Keywords associated with the document. Commas may be used to delineate
keywords within the string.
*/
SkString fKeywords;
/** If the document was converted to PDF from another format,
the name of the conforming product that created the
original document from which it was converted.
*/
SkString fCreator;
/** The product that is converting this document to PDF.
Leave fProducer empty to get the default, correct value.
*/
SkString fProducer;
/** The date and time the document was created.
The zero default value represents an unknown/unset time.
*/
SkTime::DateTime fCreation = {0, 0, 0, 0, 0, 0, 0, 0};
/** The date and time the document was most recently modified.
The zero default value represents an unknown/unset time.
*/
SkTime::DateTime fModified = {0, 0, 0, 0, 0, 0, 0, 0};
/** The DPI (pixels-per-inch) at which features without native PDF support
will be rasterized (e.g. draw image with perspective, draw text with
perspective, ...) A larger DPI would create a PDF that reflects the
original intent with better fidelity, but it can make for larger PDF
files too, which would use more memory while rendering, and it would be
slower to be processed or sent online or to printer.
*/
SkScalar fRasterDPI = SK_ScalarDefaultRasterDPI;
/** If true, include XMP metadata, a document UUID, and sRGB output intent
information. This adds length to the document and makes it
non-reproducable, but are necessary features for PDF/A-2b conformance
*/
bool fPDFA = false;
/** Encoding quality controls the trade-off between size and quality. By
default this is set to 101 percent, which corresponds to lossless
encoding. If this value is set to a value <= 100, and the image is
opaque, it will be encoded (using JPEG) with that quality setting.
*/
int fEncodingQuality = 101;
/**
* An optional tree of structured document tags that provide
* a semantic representation of the content. The caller
* should retain ownership.
*/
const StructureElementNode* fStructureElementTreeRoot = nullptr;
};
/** Associate a node ID with subsequent drawing commands in an
SkCanvas. The same node ID can appear in a StructureElementNode
in order to associate a document's structure element tree with
its content.
A node ID of zero indicates no node ID.
@param canvas The canvas used to draw to the PDF.
@param nodeId The node ID for subsequent drawing commands.
*/
SK_API void SetNodeId(SkCanvas* dst, int nodeID);
/** Create a PDF-backed document, writing the results into a SkWStream.
PDF pages are sized in point units. 1 pt == 1/72 inch == 127/360 mm.
@param stream A PDF document will be written to this stream. The document may write
to the stream at anytime during its lifetime, until either close() is
called or the document is deleted.
@param metadata a PDFmetadata object. Any fields may be left empty.
@returns NULL if there is an error, otherwise a newly created PDF-backed SkDocument.
*/
SK_API sk_sp<SkDocument> MakeDocument(SkWStream* stream, const Metadata& metadata);
static inline sk_sp<SkDocument> MakeDocument(SkWStream* stream) {
return MakeDocument(stream, Metadata());
}
} // namespace SkPDF
#endif // SkPDFDocument_DEFINED

Просмотреть файл

@ -0,0 +1,27 @@
/*
* Copyright 2017 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef SkXPSDocument_DEFINED
#define SkXPSDocument_DEFINED
#include "SkTypes.h"
#ifdef SK_BUILD_FOR_WIN
#include "SkDocument.h"
struct IXpsOMObjectFactory;
namespace SkXPS {
SK_API sk_sp<SkDocument> MakeDocument(SkWStream* stream,
IXpsOMObjectFactory* xpsFactory,
SkScalar dpi = SK_ScalarDefaultRasterDPI);
} // namespace SkXPS
#endif // SK_BUILD_FOR_WIN
#endif // SkXPSDocument_DEFINED

Просмотреть файл

@ -8,6 +8,7 @@
#ifndef Sk1DPathEffect_DEFINED
#define Sk1DPathEffect_DEFINED
#include "SkFlattenable.h"
#include "SkPathEffect.h"
#include "SkPath.h"
@ -16,10 +17,9 @@ class SkPathMeasure;
// This class is not exported to java.
class SK_API Sk1DPathEffect : public SkPathEffect {
public:
virtual bool filterPath(SkPath* dst, const SkPath& src,
SkStrokeRec*, const SkRect*) const override;
protected:
bool onFilterPath(SkPath* dst, const SkPath& src, SkStrokeRec*, const SkRect*) const override;
/** Called at the start of each contour, returns the initial offset
into that contour.
*/
@ -58,21 +58,21 @@ public:
*/
static sk_sp<SkPathEffect> Make(const SkPath& path, SkScalar advance, SkScalar phase, Style);
virtual bool filterPath(SkPath*, const SkPath&,
SkStrokeRec*, const SkRect*) const override;
SK_TO_STRING_OVERRIDE()
SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(SkPath1DPathEffect)
Factory getFactory() const override { return CreateProc; }
protected:
SkPath1DPathEffect(const SkPath& path, SkScalar advance, SkScalar phase, Style);
void flatten(SkWriteBuffer&) const override;
bool onFilterPath(SkPath*, const SkPath&, SkStrokeRec*, const SkRect*) const override;
// overrides from Sk1DPathEffect
SkScalar begin(SkScalar contourLength) const override;
SkScalar next(SkPath*, SkScalar, SkPathMeasure&) const override;
private:
static sk_sp<SkFlattenable> CreateProc(SkReadBuffer&);
friend class SkFlattenable::PrivateInitializer;
SkPath fPath; // copied from constructor
SkScalar fAdvance; // copied from constructor
SkScalar fInitialOffset; // computed from phase

Просмотреть файл

@ -8,14 +8,12 @@
#ifndef Sk2DPathEffect_DEFINED
#define Sk2DPathEffect_DEFINED
#include "SkFlattenable.h"
#include "SkPath.h"
#include "SkPathEffect.h"
#include "SkMatrix.h"
class SK_API Sk2DPathEffect : public SkPathEffect {
public:
bool filterPath(SkPath*, const SkPath&, SkStrokeRec*, const SkRect*) const override;
protected:
/** New virtual, to be overridden by subclasses.
This is called once from filterPath, and provides the
@ -38,8 +36,7 @@ protected:
// protected so that subclasses can call this during unflattening
explicit Sk2DPathEffect(const SkMatrix& mat);
void flatten(SkWriteBuffer&) const override;
SK_TO_STRING_OVERRIDE()
bool onFilterPath(SkPath*, const SkPath&, SkStrokeRec*, const SkRect*) const override;
private:
SkMatrix fMatrix, fInverse;
@ -56,23 +53,29 @@ private:
class SK_API SkLine2DPathEffect : public Sk2DPathEffect {
public:
static sk_sp<SkPathEffect> Make(SkScalar width, const SkMatrix& matrix) {
if (!(width >= 0)) {
return nullptr;
}
return sk_sp<SkPathEffect>(new SkLine2DPathEffect(width, matrix));
}
virtual bool filterPath(SkPath* dst, const SkPath& src,
SkStrokeRec*, const SkRect*) const override;
SK_TO_STRING_OVERRIDE()
SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(SkLine2DPathEffect)
Factory getFactory() const override { return CreateProc; }
protected:
SkLine2DPathEffect(SkScalar width, const SkMatrix& matrix)
: Sk2DPathEffect(matrix), fWidth(width) {}
: Sk2DPathEffect(matrix), fWidth(width) {
SkASSERT(width >= 0);
}
void flatten(SkWriteBuffer&) const override;
bool onFilterPath(SkPath* dst, const SkPath& src, SkStrokeRec*, const SkRect*) const override;
void nextSpan(int u, int v, int ucount, SkPath*) const override;
private:
static sk_sp<SkFlattenable> CreateProc(SkReadBuffer&);
friend class SkFlattenable::PrivateInitializer;
SkScalar fWidth;
typedef Sk2DPathEffect INHERITED;
@ -88,8 +91,7 @@ public:
return sk_sp<SkPathEffect>(new SkPath2DPathEffect(matrix, path));
}
SK_TO_STRING_OVERRIDE()
SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(SkPath2DPathEffect)
Factory getFactory() const override { return CreateProc; }
protected:
SkPath2DPathEffect(const SkMatrix&, const SkPath&);
@ -98,6 +100,9 @@ protected:
void next(const SkPoint&, int u, int v, SkPath*) const override;
private:
static sk_sp<SkFlattenable> CreateProc(SkReadBuffer&);
friend class SkFlattenable::PrivateInitializer;
SkPath fPath;
typedef Sk2DPathEffect INHERITED;

Просмотреть файл

@ -26,7 +26,7 @@ public:
const SkImageFilter::CropRect* cropRect = nullptr);
SK_DECLARE_FLATTENABLE_REGISTRAR_GROUP();
static void InitializeFlattenables();
};
#endif

Просмотреть файл

@ -10,6 +10,15 @@
#include "SkImageFilter.h"
struct ArithmeticFPInputs {
ArithmeticFPInputs() {
memset(this, 0, sizeof(*this));
}
float k[4];
bool enforcePMColor;
};
class SK_API SkArithmeticImageFilter {
public:
static sk_sp<SkImageFilter> Make(float k1, float k2, float k3, float k4, bool enforcePMColor,
@ -17,7 +26,7 @@ public:
sk_sp<SkImageFilter> foreground,
const SkImageFilter::CropRect* cropRect);
SK_DECLARE_FLATTENABLE_REGISTRAR_GROUP();
static void InitializeFlattenables();
private:
SkArithmeticImageFilter(); // can't instantiate

Просмотреть файл

@ -18,39 +18,6 @@ class SkRRect;
class SK_API SkBlurMaskFilter {
public:
/**
* If radius > 0, return the corresponding sigma, else return 0. Use this to convert from the
* (legacy) idea of specify the blur "radius" to the standard notion of specifying its sigma.
*/
static SkScalar ConvertRadiusToSigma(SkScalar radius);
enum BlurFlags {
kNone_BlurFlag = 0x00,
/** The blur layer's radius is not affected by transforms */
kIgnoreTransform_BlurFlag = 0x01,
/** Use a smother, higher qulity blur algorithm */
kHighQuality_BlurFlag = 0x02,
/** mask for all blur flags */
kAll_BlurFlag = 0x03
};
/** Create a blur maskfilter.
* @param style The SkBlurStyle to use
* @param sigma Standard deviation of the Gaussian blur to apply. Must be > 0.
* @param occluder The rect for which no pixels need be drawn (b.c. it will be overdrawn
* with some opaque object. This is just a hint which backends are free to
* ignore.
* @param flags Flags to use - defaults to none
* @return The new blur maskfilter
*/
static sk_sp<SkMaskFilter> Make(SkBlurStyle style, SkScalar sigma,
const SkRect& occluder, uint32_t flags = kNone_BlurFlag);
static sk_sp<SkMaskFilter> Make(SkBlurStyle style, SkScalar sigma,
uint32_t flags = kNone_BlurFlag) {
return Make(style, sigma, SkRect::MakeEmpty(), flags);
}
#ifdef SK_SUPPORT_LEGACY_EMBOSSMASKFILTER
/** Create an emboss maskfilter
@param blurSigma standard deviation of the Gaussian blur to apply
@ -63,33 +30,6 @@ public:
static sk_sp<SkMaskFilter> MakeEmboss(SkScalar blurSigma, const SkScalar direction[3],
SkScalar ambient, SkScalar specular);
#endif
static const int kMaxDivisions = 6;
// This method computes all the parameters for drawing a partially occluded nine-patched
// blurred rrect mask:
// rrectToDraw - the integerized rrect to draw in the mask
// widthHeight - how large to make the mask (rrectToDraw will be centered in this coord sys)
// rectXs, rectYs - the x & y coordinates of the covering geometry lattice
// texXs, texYs - the texture coordinate at each point in rectXs & rectYs
// numXs, numYs - number of coordinates in the x & y directions
// skipMask - bit mask that contains a 1-bit whenever one of the cells is occluded
// It returns true if 'devRRect' is nine-patchable
static bool ComputeBlurredRRectParams(const SkRRect& srcRRect, const SkRRect& devRRect,
const SkRect& occluder,
SkScalar sigma, SkScalar xformedSigma,
SkRRect* rrectToDraw,
SkISize* widthHeight,
SkScalar rectXs[kMaxDivisions],
SkScalar rectYs[kMaxDivisions],
SkScalar texXs[kMaxDivisions],
SkScalar texYs[kMaxDivisions],
int* numXs, int* numYs, uint32_t* skipMask);
SK_DECLARE_FLATTENABLE_REGISTRAR_GROUP()
private:
SkBlurMaskFilter(); // can't be instantiated
};
#endif

Просмотреть файл

@ -9,8 +9,7 @@
#define SkColorFilterImageFilter_DEFINED
#include "SkImageFilter.h"
class SkColorFilter;
#include "SkColorFilter.h"
class SK_API SkColorFilterImageFilter : public SkImageFilter {
public:
@ -18,8 +17,7 @@ public:
sk_sp<SkImageFilter> input,
const CropRect* cropRect = nullptr);
SK_TO_STRING_OVERRIDE()
SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(SkColorFilterImageFilter)
Factory getFactory() const override { return CreateProc; }
protected:
void flatten(SkWriteBuffer&) const override;
@ -34,6 +32,8 @@ private:
SkColorFilterImageFilter(sk_sp<SkColorFilter> cf,
sk_sp<SkImageFilter> input,
const CropRect* cropRect);
static sk_sp<SkFlattenable> CreateProc(SkReadBuffer&);
friend class SkFlattenable::PrivateInitializer;
sk_sp<SkColorFilter> fColorFilter;

Просмотреть файл

@ -32,10 +32,6 @@ public:
void setIdentity();
void setScale(SkScalar rScale, SkScalar gScale, SkScalar bScale,
SkScalar aScale = SK_Scalar1);
void preScale(SkScalar rScale, SkScalar gScale, SkScalar bScale,
SkScalar aScale = SK_Scalar1);
void postScale(SkScalar rScale, SkScalar gScale, SkScalar bScale,
SkScalar aScale = SK_Scalar1);
void postTranslate(SkScalar rTrans, SkScalar gTrans, SkScalar bTrans,
SkScalar aTrans = 0);

Просмотреть файл

@ -8,6 +8,7 @@
#ifndef SkComposeImageFilter_DEFINED
#define SkComposeImageFilter_DEFINED
#include "SkFlattenable.h"
#include "SkImageFilter.h"
class SK_API SkComposeImageFilter : public SkImageFilter {
@ -16,8 +17,7 @@ public:
SkRect computeFastBounds(const SkRect& src) const override;
SK_TO_STRING_OVERRIDE()
SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(SkComposeImageFilter)
Factory getFactory() const override { return CreateProc; }
protected:
explicit SkComposeImageFilter(sk_sp<SkImageFilter> inputs[2]) : INHERITED(inputs, 2, nullptr) {
@ -27,10 +27,14 @@ protected:
sk_sp<SkSpecialImage> onFilterImage(SkSpecialImage* source, const Context&,
SkIPoint* offset) const override;
sk_sp<SkImageFilter> onMakeColorSpace(SkColorSpaceXformer*) const override;
SkIRect onFilterBounds(const SkIRect&, const SkMatrix&, MapDirection) const override;
SkIRect onFilterBounds(const SkIRect&, const SkMatrix& ctm,
MapDirection, const SkIRect* inputRect) const override;
bool onCanHandleComplexCTM() const override { return true; }
private:
static sk_sp<SkFlattenable> CreateProc(SkReadBuffer&);
friend class SkFlattenable::PrivateInitializer;
typedef SkImageFilter INHERITED;
};

Просмотреть файл

@ -8,6 +8,7 @@
#ifndef SkCornerPathEffect_DEFINED
#define SkCornerPathEffect_DEFINED
#include "SkFlattenable.h"
#include "SkPathEffect.h"
/** \class SkCornerPathEffect
@ -21,14 +22,10 @@ public:
that should be "rounded".
*/
static sk_sp<SkPathEffect> Make(SkScalar radius) {
return sk_sp<SkPathEffect>(new SkCornerPathEffect(radius));
return radius > 0 ? sk_sp<SkPathEffect>(new SkCornerPathEffect(radius)) : nullptr;
}
virtual bool filterPath(SkPath* dst, const SkPath& src,
SkStrokeRec*, const SkRect*) const override;
SK_TO_STRING_OVERRIDE()
SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(SkCornerPathEffect)
Factory getFactory() const override { return CreateProc; }
#ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
bool exposedInAndroidJavaAPI() const override { return true; }
@ -36,9 +33,12 @@ public:
protected:
~SkCornerPathEffect() override;
static sk_sp<SkFlattenable> CreateProc(SkReadBuffer&);
friend class SkFlattenable::PrivateInitializer;
explicit SkCornerPathEffect(SkScalar radius);
void flatten(SkWriteBuffer&) const override;
bool onFilterPath(SkPath* dst, const SkPath& src, SkStrokeRec*, const SkRect*) const override;
private:
SkScalar fRadius;

Просмотреть файл

@ -8,6 +8,7 @@
#ifndef SkDiscretePathEffect_DEFINED
#define SkDiscretePathEffect_DEFINED
#include "SkFlattenable.h"
#include "SkPathEffect.h"
/** \class SkDiscretePathEffect
@ -31,11 +32,7 @@ public:
*/
static sk_sp<SkPathEffect> Make(SkScalar segLength, SkScalar dev, uint32_t seedAssist = 0);
virtual bool filterPath(SkPath* dst, const SkPath& src,
SkStrokeRec*, const SkRect*) const override;
SK_TO_STRING_OVERRIDE()
SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(SkDiscretePathEffect)
Factory getFactory() const override { return CreateProc; }
#ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
bool exposedInAndroidJavaAPI() const override { return true; }
@ -46,8 +43,12 @@ protected:
SkScalar deviation,
uint32_t seedAssist);
void flatten(SkWriteBuffer&) const override;
bool onFilterPath(SkPath* dst, const SkPath& src, SkStrokeRec*, const SkRect*) const override;
private:
static sk_sp<SkFlattenable> CreateProc(SkReadBuffer&);
friend class SkFlattenable::PrivateInitializer;
SkScalar fSegLength, fPerterb;
/* Caller-supplied 32 bit seed assist */

Некоторые файлы не были показаны из-за слишком большого количества измененных файлов Показать больше