• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2013 Google Inc.
3  *
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the LICENSE file.
6  */
7 
8 #include "include/core/SkCanvas.h"
9 #include "include/core/SkData.h"
10 #include "include/core/SkOverdrawCanvas.h"
11 #include "include/core/SkPath.h"
12 #include "include/core/SkRRect.h"
13 #include "include/core/SkRegion.h"
14 #include "include/core/SkSurface.h"
15 #include "include/gpu/GrBackendSurface.h"
16 #include "include/gpu/GrDirectContext.h"
17 #include "src/core/SkAutoPixmapStorage.h"
18 #include "src/core/SkCanvasPriv.h"
19 #include "src/core/SkDevice.h"
20 #include "src/core/SkUtils.h"
21 #include "src/gpu/BaseDevice.h"
22 #include "src/gpu/GrDirectContextPriv.h"
23 #include "src/gpu/GrGpu.h"
24 #include "src/gpu/GrGpuResourcePriv.h"
25 #include "src/gpu/GrImageInfo.h"
26 #include "src/gpu/GrRenderTarget.h"
27 #include "src/gpu/GrResourceProvider.h"
28 #include "src/gpu/SurfaceFillContext.h"
29 #include "src/image/SkImage_Base.h"
30 #include "src/image/SkImage_Gpu.h"
31 #include "src/image/SkSurface_Gpu.h"
32 #include "tests/Test.h"
33 #include "tools/ToolUtils.h"
34 #include "tools/gpu/BackendSurfaceFactory.h"
35 #include "tools/gpu/ManagedBackendTexture.h"
36 #include "tools/gpu/ProxyUtils.h"
37 
38 #include <functional>
39 #include <initializer_list>
40 #include <vector>
41 
release_direct_surface_storage(void * pixels,void * context)42 static void release_direct_surface_storage(void* pixels, void* context) {
43     SkASSERT(pixels == context);
44     sk_free(pixels);
45 }
create_surface(SkAlphaType at=kPremul_SkAlphaType,SkImageInfo * requestedInfo=nullptr)46 static sk_sp<SkSurface> create_surface(SkAlphaType at = kPremul_SkAlphaType,
47                                        SkImageInfo* requestedInfo = nullptr) {
48     const SkImageInfo info = SkImageInfo::MakeN32(10, 10, at);
49     if (requestedInfo) {
50         *requestedInfo = info;
51     }
52     return SkSurface::MakeRaster(info);
53 }
create_direct_surface(SkAlphaType at=kPremul_SkAlphaType,SkImageInfo * requestedInfo=nullptr)54 static sk_sp<SkSurface> create_direct_surface(SkAlphaType at = kPremul_SkAlphaType,
55                                               SkImageInfo* requestedInfo = nullptr) {
56     const SkImageInfo info = SkImageInfo::MakeN32(10, 10, at);
57     if (requestedInfo) {
58         *requestedInfo = info;
59     }
60     const size_t rowBytes = info.minRowBytes();
61     void* storage = sk_malloc_throw(info.computeByteSize(rowBytes));
62     return SkSurface::MakeRasterDirectReleaseProc(info, storage, rowBytes,
63                                                   release_direct_surface_storage,
64                                                   storage);
65 }
create_gpu_surface(GrRecordingContext * rContext,SkAlphaType at=kPremul_SkAlphaType,SkImageInfo * requestedInfo=nullptr)66 static sk_sp<SkSurface> create_gpu_surface(GrRecordingContext* rContext,
67                                            SkAlphaType at = kPremul_SkAlphaType,
68                                            SkImageInfo* requestedInfo = nullptr) {
69     const SkImageInfo info = SkImageInfo::MakeN32(10, 10, at);
70     if (requestedInfo) {
71         *requestedInfo = info;
72     }
73     return SkSurface::MakeRenderTarget(rContext, SkBudgeted::kNo, info);
74 }
create_gpu_scratch_surface(GrRecordingContext * rContext,SkAlphaType at=kPremul_SkAlphaType,SkImageInfo * requestedInfo=nullptr)75 static sk_sp<SkSurface> create_gpu_scratch_surface(GrRecordingContext* rContext,
76                                                    SkAlphaType at = kPremul_SkAlphaType,
77                                                    SkImageInfo* requestedInfo = nullptr) {
78     const SkImageInfo info = SkImageInfo::MakeN32(10, 10, at);
79     if (requestedInfo) {
80         *requestedInfo = info;
81     }
82     return SkSurface::MakeRenderTarget(rContext, SkBudgeted::kYes, info);
83 }
84 
DEF_TEST(SurfaceEmpty,reporter)85 DEF_TEST(SurfaceEmpty, reporter) {
86     const SkImageInfo info = SkImageInfo::Make(0, 0, kN32_SkColorType, kPremul_SkAlphaType);
87     REPORTER_ASSERT(reporter, nullptr == SkSurface::MakeRaster(info));
88     REPORTER_ASSERT(reporter, nullptr == SkSurface::MakeRasterDirect(info, nullptr, 0));
89 
90 }
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceEmpty_Gpu,reporter,ctxInfo)91 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceEmpty_Gpu, reporter, ctxInfo) {
92     const SkImageInfo info = SkImageInfo::Make(0, 0, kN32_SkColorType, kPremul_SkAlphaType);
93     REPORTER_ASSERT(reporter, nullptr ==
94                     SkSurface::MakeRenderTarget(ctxInfo.directContext(), SkBudgeted::kNo, info));
95 }
96 
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(GrContext_colorTypeSupportedAsSurface,reporter,ctxInfo)97 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(GrContext_colorTypeSupportedAsSurface, reporter, ctxInfo) {
98     auto context = ctxInfo.directContext();
99 
100     for (int ct = 0; ct < kLastEnum_SkColorType; ++ct) {
101         static constexpr int kSize = 10;
102 
103         SkColorType colorType = static_cast<SkColorType>(ct);
104         auto info = SkImageInfo::Make(kSize, kSize, colorType, kOpaque_SkAlphaType, nullptr);
105 
106         {
107             bool can = context->colorTypeSupportedAsSurface(colorType);
108             auto surf = SkSurface::MakeRenderTarget(context, SkBudgeted::kYes, info, 1, nullptr);
109             REPORTER_ASSERT(reporter, can == SkToBool(surf), "ct: %d, can: %d, surf: %d",
110                             colorType, can, SkToBool(surf));
111 
112             surf = sk_gpu_test::MakeBackendTextureSurface(context,
113                                                           {kSize, kSize},
114                                                           kTopLeft_GrSurfaceOrigin,
115                                                           /*sample cnt*/ 1,
116                                                           colorType);
117             REPORTER_ASSERT(reporter, can == SkToBool(surf), "ct: %d, can: %d, surf: %d",
118                             colorType, can, SkToBool(surf));
119         }
120 
121         // The MSAA test only makes sense if the colorType is renderable to begin with.
122         if (context->colorTypeSupportedAsSurface(colorType)) {
123             static constexpr int kSampleCnt = 2;
124 
125             bool can = context->maxSurfaceSampleCountForColorType(colorType) >= kSampleCnt;
126             auto surf = SkSurface::MakeRenderTarget(context, SkBudgeted::kYes, info, kSampleCnt,
127                                                     nullptr);
128             REPORTER_ASSERT(reporter, can == SkToBool(surf), "ct: %d, can: %d, surf: %d",
129                             colorType, can, SkToBool(surf));
130 
131             surf = sk_gpu_test::MakeBackendTextureSurface(
132                     context, {kSize, kSize}, kTopLeft_GrSurfaceOrigin, kSampleCnt, colorType);
133             REPORTER_ASSERT(reporter, can == SkToBool(surf),
134                             "colorTypeSupportedAsSurface:%d, surf:%d, ct:%d", can, SkToBool(surf),
135                             colorType);
136             // Ensure that the sample count stored on the resulting SkSurface is a valid value.
137             if (surf) {
138                 auto rtp = SkCanvasPriv::TopDeviceTargetProxy(surf->getCanvas());
139                 int storedCnt = rtp->numSamples();
140                 const GrBackendFormat& format = rtp->backendFormat();
141                 int allowedCnt =
142                         context->priv().caps()->getRenderTargetSampleCount(storedCnt, format);
143                 REPORTER_ASSERT(reporter, storedCnt == allowedCnt,
144                                 "Should store an allowed sample count (%d vs %d)", allowedCnt,
145                                 storedCnt);
146             }
147         }
148 
149         for (int sampleCnt : {1, 2}) {
150             auto surf = sk_gpu_test::MakeBackendRenderTargetSurface(context,
151                                                                     {16, 16},
152                                                                     kTopLeft_GrSurfaceOrigin,
153                                                                     sampleCnt,
154                                                                     colorType);
155             bool can = context->colorTypeSupportedAsSurface(colorType) &&
156                        context->maxSurfaceSampleCountForColorType(colorType) >= sampleCnt;
157             if (!surf && can && colorType == kBGRA_8888_SkColorType && sampleCnt > 1 &&
158                 context->backend() == GrBackendApi::kOpenGL) {
159                 // This is an execeptional case. On iOS GLES we support MSAA BGRA for internally-
160                 // created render targets by using a MSAA RGBA8 renderbuffer that resolves to a
161                 // BGRA8 texture. However, the GL_APPLE_texture_format_BGRA8888 extension does not
162                 // allow creation of BGRA8 renderbuffers and we don't support multisampled textures.
163                 // So this is expected to fail. As of 10/5/2020 it actually seems to work to create
164                 // a MSAA BGRA8 renderbuffer (at least in the simulator) but we don't want to rely
165                 // on this undocumented behavior.
166                 continue;
167             }
168             REPORTER_ASSERT(reporter, can == SkToBool(surf), "ct: %d, sc: %d, can: %d, surf: %d",
169                             colorType, sampleCnt, can, SkToBool(surf));
170             if (surf) {
171                 auto rtp = SkCanvasPriv::TopDeviceTargetProxy(surf->getCanvas());
172                 int storedCnt = rtp->numSamples();
173                 const GrBackendFormat& backendFormat = rtp->backendFormat();
174                 int allowedCnt = context->priv().caps()->getRenderTargetSampleCount(storedCnt,
175                                                                                     backendFormat);
176                 REPORTER_ASSERT(reporter, storedCnt == allowedCnt,
177                                 "Should store an allowed sample count (%d vs %d)", allowedCnt,
178                                 storedCnt);
179             }
180         }
181     }
182 }
183 
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(GrContext_maxSurfaceSamplesForColorType,reporter,ctxInfo)184 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(GrContext_maxSurfaceSamplesForColorType, reporter, ctxInfo) {
185     auto context = ctxInfo.directContext();
186 
187     static constexpr int kSize = 10;
188 
189     for (int ct = 0; ct < kLastEnum_SkColorType; ++ct) {
190 
191         SkColorType colorType = static_cast<SkColorType>(ct);
192         int maxSampleCnt = context->maxSurfaceSampleCountForColorType(colorType);
193         if (!maxSampleCnt) {
194             continue;
195         }
196         if (!context->colorTypeSupportedAsSurface(colorType)) {
197             continue;
198         }
199 
200         auto info = SkImageInfo::Make(kSize, kSize, colorType, kOpaque_SkAlphaType, nullptr);
201         auto surf = sk_gpu_test::MakeBackendTextureSurface(
202                 context, info, kTopLeft_GrSurfaceOrigin, maxSampleCnt);
203         if (!surf) {
204             ERRORF(reporter, "Could not make surface of color type %d.", colorType);
205             continue;
206         }
207         int sampleCnt =
208             ((SkSurface_Gpu*)(surf.get()))->getDevice()->targetProxy()->numSamples();
209         REPORTER_ASSERT(reporter, sampleCnt == maxSampleCnt, "Exected: %d, actual: %d",
210                         maxSampleCnt, sampleCnt);
211     }
212 }
213 
test_canvas_peek(skiatest::Reporter * reporter,sk_sp<SkSurface> & surface,const SkImageInfo & requestInfo,bool expectPeekSuccess)214 static void test_canvas_peek(skiatest::Reporter* reporter,
215                              sk_sp<SkSurface>& surface,
216                              const SkImageInfo& requestInfo,
217                              bool expectPeekSuccess) {
218     const SkColor color = SK_ColorRED;
219     const SkPMColor pmcolor = SkPreMultiplyColor(color);
220     surface->getCanvas()->clear(color);
221 
222     SkPixmap pmap;
223     bool success = surface->getCanvas()->peekPixels(&pmap);
224     REPORTER_ASSERT(reporter, expectPeekSuccess == success);
225 
226     SkPixmap pmap2;
227     const void* addr2 = surface->peekPixels(&pmap2) ? pmap2.addr() : nullptr;
228 
229     if (success) {
230         REPORTER_ASSERT(reporter, requestInfo == pmap.info());
231         REPORTER_ASSERT(reporter, requestInfo.minRowBytes() <= pmap.rowBytes());
232         REPORTER_ASSERT(reporter, pmcolor == *pmap.addr32());
233 
234         REPORTER_ASSERT(reporter, pmap.addr() == pmap2.addr());
235         REPORTER_ASSERT(reporter, pmap.info() == pmap2.info());
236         REPORTER_ASSERT(reporter, pmap.rowBytes() == pmap2.rowBytes());
237     } else {
238         REPORTER_ASSERT(reporter, nullptr == addr2);
239     }
240 }
DEF_TEST(SurfaceCanvasPeek,reporter)241 DEF_TEST(SurfaceCanvasPeek, reporter) {
242     for (auto& surface_func : { &create_surface, &create_direct_surface }) {
243         SkImageInfo requestInfo;
244         auto surface(surface_func(kPremul_SkAlphaType, &requestInfo));
245         test_canvas_peek(reporter, surface, requestInfo, true);
246     }
247 }
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceCanvasPeek_Gpu,reporter,ctxInfo)248 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceCanvasPeek_Gpu, reporter, ctxInfo) {
249     for (auto& surface_func : { &create_gpu_surface, &create_gpu_scratch_surface }) {
250         SkImageInfo requestInfo;
251         auto surface(surface_func(ctxInfo.directContext(), kPremul_SkAlphaType, &requestInfo));
252         test_canvas_peek(reporter, surface, requestInfo, false);
253     }
254 }
255 
test_snapshot_alphatype(skiatest::Reporter * reporter,const sk_sp<SkSurface> & surface,SkAlphaType expectedAlphaType)256 static void test_snapshot_alphatype(skiatest::Reporter* reporter, const sk_sp<SkSurface>& surface,
257                                     SkAlphaType expectedAlphaType) {
258     REPORTER_ASSERT(reporter, surface);
259     if (surface) {
260         sk_sp<SkImage> image(surface->makeImageSnapshot());
261         REPORTER_ASSERT(reporter, image);
262         if (image) {
263             REPORTER_ASSERT(reporter, image->alphaType() == expectedAlphaType);
264         }
265     }
266 }
DEF_TEST(SurfaceSnapshotAlphaType,reporter)267 DEF_TEST(SurfaceSnapshotAlphaType, reporter) {
268     for (auto& surface_func : { &create_surface, &create_direct_surface }) {
269         for (auto& at: { kOpaque_SkAlphaType, kPremul_SkAlphaType, kUnpremul_SkAlphaType }) {
270             auto surface(surface_func(at, nullptr));
271             test_snapshot_alphatype(reporter, surface, at);
272         }
273     }
274 }
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceSnapshotAlphaType_Gpu,reporter,ctxInfo)275 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceSnapshotAlphaType_Gpu, reporter, ctxInfo) {
276     for (auto& surface_func : { &create_gpu_surface, &create_gpu_scratch_surface }) {
277         // GPU doesn't support creating unpremul surfaces, so only test opaque + premul
278         for (auto& at : { kOpaque_SkAlphaType, kPremul_SkAlphaType }) {
279             auto surface(surface_func(ctxInfo.directContext(), at, nullptr));
280             test_snapshot_alphatype(reporter, surface, at);
281         }
282     }
283 }
284 
test_backend_texture_access_copy_on_write(skiatest::Reporter * reporter,SkSurface * surface,SkSurface::BackendHandleAccess access)285 static void test_backend_texture_access_copy_on_write(
286     skiatest::Reporter* reporter, SkSurface* surface, SkSurface::BackendHandleAccess access) {
287     GrBackendTexture tex1 = surface->getBackendTexture(access);
288     sk_sp<SkImage> snap1(surface->makeImageSnapshot());
289 
290     GrBackendTexture tex2 = surface->getBackendTexture(access);
291     sk_sp<SkImage> snap2(surface->makeImageSnapshot());
292 
293     // If the access mode triggers CoW, then the backend objects should reflect it.
294     REPORTER_ASSERT(reporter, GrBackendTexture::TestingOnly_Equals(tex1, tex2) == (snap1 == snap2));
295 }
296 
test_backend_rendertarget_access_copy_on_write(skiatest::Reporter * reporter,SkSurface * surface,SkSurface::BackendHandleAccess access)297 static void test_backend_rendertarget_access_copy_on_write(
298     skiatest::Reporter* reporter, SkSurface* surface, SkSurface::BackendHandleAccess access) {
299     GrBackendRenderTarget rt1 = surface->getBackendRenderTarget(access);
300     sk_sp<SkImage> snap1(surface->makeImageSnapshot());
301 
302     GrBackendRenderTarget rt2 = surface->getBackendRenderTarget(access);
303     sk_sp<SkImage> snap2(surface->makeImageSnapshot());
304 
305     // If the access mode triggers CoW, then the backend objects should reflect it.
306     REPORTER_ASSERT(reporter, GrBackendRenderTarget::TestingOnly_Equals(rt1, rt2) ==
307                               (snap1 == snap2));
308 }
309 
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceBackendSurfaceAccessCopyOnWrite_Gpu,reporter,ctxInfo)310 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceBackendSurfaceAccessCopyOnWrite_Gpu, reporter, ctxInfo) {
311     const SkSurface::BackendHandleAccess accessModes[] = {
312         SkSurface::kFlushRead_BackendHandleAccess,
313         SkSurface::kFlushWrite_BackendHandleAccess,
314         SkSurface::kDiscardWrite_BackendHandleAccess,
315     };
316 
317     for (auto& surface_func : { &create_gpu_surface, &create_gpu_scratch_surface }) {
318         for (auto& accessMode : accessModes) {
319             {
320                 auto surface(surface_func(ctxInfo.directContext(), kPremul_SkAlphaType, nullptr));
321                 test_backend_texture_access_copy_on_write(reporter, surface.get(), accessMode);
322             }
323             {
324                 auto surface(surface_func(ctxInfo.directContext(), kPremul_SkAlphaType, nullptr));
325                 test_backend_rendertarget_access_copy_on_write(reporter, surface.get(), accessMode);
326             }
327         }
328     }
329 }
330 
331 template<typename Type, Type(SkSurface::*func)(SkSurface::BackendHandleAccess)>
test_backend_unique_id(skiatest::Reporter * reporter,SkSurface * surface)332 static void test_backend_unique_id(skiatest::Reporter* reporter, SkSurface* surface) {
333     sk_sp<SkImage> image0(surface->makeImageSnapshot());
334 
335     Type obj = (surface->*func)(SkSurface::kFlushRead_BackendHandleAccess);
336     REPORTER_ASSERT(reporter, obj.isValid());
337     sk_sp<SkImage> image1(surface->makeImageSnapshot());
338     // just read access should not affect the snapshot
339     REPORTER_ASSERT(reporter, image0->uniqueID() == image1->uniqueID());
340 
341     obj = (surface->*func)(SkSurface::kFlushWrite_BackendHandleAccess);
342     REPORTER_ASSERT(reporter, obj.isValid());
343     sk_sp<SkImage> image2(surface->makeImageSnapshot());
344     // expect a new image, since we claimed we would write
345     REPORTER_ASSERT(reporter, image0->uniqueID() != image2->uniqueID());
346 
347     obj = (surface->*func)(SkSurface::kDiscardWrite_BackendHandleAccess);
348     REPORTER_ASSERT(reporter, obj.isValid());
349     sk_sp<SkImage> image3(surface->makeImageSnapshot());
350     // expect a new(er) image, since we claimed we would write
351     REPORTER_ASSERT(reporter, image0->uniqueID() != image3->uniqueID());
352     REPORTER_ASSERT(reporter, image2->uniqueID() != image3->uniqueID());
353 }
354 
355 // No CPU test.
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceBackendHandleAccessIDs_Gpu,reporter,ctxInfo)356 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceBackendHandleAccessIDs_Gpu, reporter, ctxInfo) {
357     for (auto& surface_func : { &create_gpu_surface, &create_gpu_scratch_surface }) {
358         {
359             auto surface(surface_func(ctxInfo.directContext(), kPremul_SkAlphaType, nullptr));
360             test_backend_unique_id<GrBackendTexture, &SkSurface::getBackendTexture>(reporter,
361                                                                                     surface.get());
362         }
363         {
364             auto surface(surface_func(ctxInfo.directContext(), kPremul_SkAlphaType, nullptr));
365             test_backend_unique_id<GrBackendRenderTarget, &SkSurface::getBackendRenderTarget>(
366                                                                 reporter, surface.get());
367         }
368     }
369 }
370 
371 // No CPU test.
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceAbandonPostFlush_Gpu,reporter,ctxInfo)372 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceAbandonPostFlush_Gpu, reporter, ctxInfo) {
373     auto direct = ctxInfo.directContext();
374     sk_sp<SkSurface> surface = create_gpu_surface(direct, kPremul_SkAlphaType, nullptr);
375     if (!surface) {
376         return;
377     }
378     // This flush can put command buffer refs on the GrGpuResource for the surface.
379     surface->flush();
380     direct->abandonContext();
381     // We pass the test if we don't hit any asserts or crashes when the ref on the surface goes away
382     // after we abanonded the context. One thing specifically this checks is to make sure we're
383     // correctly handling the mix of normal refs and command buffer refs, and correctly deleting
384     // the object at the right time.
385 }
386 
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceBackendAccessAbandoned_Gpu,reporter,ctxInfo)387 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceBackendAccessAbandoned_Gpu, reporter, ctxInfo) {
388     auto dContext = ctxInfo.directContext();
389     sk_sp<SkSurface> surface = create_gpu_surface(dContext, kPremul_SkAlphaType, nullptr);
390     if (!surface) {
391         return;
392     }
393 
394     GrBackendRenderTarget beRT =
395             surface->getBackendRenderTarget(SkSurface::kFlushRead_BackendHandleAccess);
396     REPORTER_ASSERT(reporter, beRT.isValid());
397     GrBackendTexture beTex =
398             surface->getBackendTexture(SkSurface::kFlushRead_BackendHandleAccess);
399     REPORTER_ASSERT(reporter, beTex.isValid());
400 
401     surface->flush();
402     dContext->abandonContext();
403 
404     // After abandoning the context none of the backend surfaces should be valid.
405     beRT = surface->getBackendRenderTarget(SkSurface::kFlushRead_BackendHandleAccess);
406     REPORTER_ASSERT(reporter, !beRT.isValid());
407     beTex = surface->getBackendTexture(SkSurface::kFlushRead_BackendHandleAccess);
408     REPORTER_ASSERT(reporter, !beTex.isValid());
409 }
410 
411 // Verify that the right canvas commands trigger a copy on write.
test_copy_on_write(skiatest::Reporter * reporter,SkSurface * surface)412 static void test_copy_on_write(skiatest::Reporter* reporter, SkSurface* surface) {
413     SkCanvas* canvas = surface->getCanvas();
414 
415     const SkRect testRect =
416         SkRect::MakeXYWH(SkIntToScalar(0), SkIntToScalar(0),
417                          SkIntToScalar(4), SkIntToScalar(5));
418     SkPath testPath;
419     testPath.addRect(SkRect::MakeXYWH(SkIntToScalar(0), SkIntToScalar(0),
420                                       SkIntToScalar(2), SkIntToScalar(1)));
421 
422     const SkIRect testIRect = SkIRect::MakeXYWH(0, 0, 2, 1);
423 
424     SkRegion testRegion;
425     testRegion.setRect(testIRect);
426 
427 
428     const SkColor testColor = 0x01020304;
429     const SkPaint testPaint;
430     const SkPoint testPoints[3] = {
431         {SkIntToScalar(0), SkIntToScalar(0)},
432         {SkIntToScalar(2), SkIntToScalar(1)},
433         {SkIntToScalar(0), SkIntToScalar(2)}
434     };
435     const size_t testPointCount = 3;
436 
437     SkBitmap testBitmap;
438     testBitmap.allocN32Pixels(10, 10);
439     testBitmap.eraseColor(0);
440 
441     SkRRect testRRect;
442     testRRect.setRectXY(testRect, SK_Scalar1, SK_Scalar1);
443 
444     SkString testText("Hello World");
445 
446 #define EXPECT_COPY_ON_WRITE(command)                               \
447     {                                                               \
448         sk_sp<SkImage> imageBefore = surface->makeImageSnapshot();  \
449         sk_sp<SkImage> aur_before(imageBefore);  /*NOLINT*/         \
450         canvas-> command ;                                          \
451         sk_sp<SkImage> imageAfter = surface->makeImageSnapshot();   \
452         sk_sp<SkImage> aur_after(imageAfter);  /*NOLINT*/           \
453         REPORTER_ASSERT(reporter, imageBefore != imageAfter);       \
454     }
455 
456     EXPECT_COPY_ON_WRITE(clear(testColor))
457     EXPECT_COPY_ON_WRITE(drawPaint(testPaint))
458     EXPECT_COPY_ON_WRITE(drawPoints(SkCanvas::kPoints_PointMode, testPointCount, testPoints, \
459         testPaint))
460     EXPECT_COPY_ON_WRITE(drawOval(testRect, testPaint))
461     EXPECT_COPY_ON_WRITE(drawRect(testRect, testPaint))
462     EXPECT_COPY_ON_WRITE(drawRRect(testRRect, testPaint))
463     EXPECT_COPY_ON_WRITE(drawPath(testPath, testPaint))
464     EXPECT_COPY_ON_WRITE(drawImage(testBitmap.asImage(), 0, 0))
465     EXPECT_COPY_ON_WRITE(drawImageRect(testBitmap.asImage(), testRect, SkSamplingOptions()))
466     EXPECT_COPY_ON_WRITE(drawString(testText, 0, 1, SkFont(), testPaint))
467 }
DEF_TEST(SurfaceCopyOnWrite,reporter)468 DEF_TEST(SurfaceCopyOnWrite, reporter) {
469     test_copy_on_write(reporter, create_surface().get());
470 }
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceCopyOnWrite_Gpu,reporter,ctxInfo)471 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceCopyOnWrite_Gpu, reporter, ctxInfo) {
472     for (auto& surface_func : { &create_gpu_surface, &create_gpu_scratch_surface }) {
473         auto surface(surface_func(ctxInfo.directContext(), kPremul_SkAlphaType, nullptr));
474         test_copy_on_write(reporter, surface.get());
475     }
476 }
477 
test_writable_after_snapshot_release(skiatest::Reporter * reporter,SkSurface * surface)478 static void test_writable_after_snapshot_release(skiatest::Reporter* reporter,
479                                                  SkSurface* surface) {
480     // This test succeeds by not triggering an assertion.
481     // The test verifies that the surface remains writable (usable) after
482     // acquiring and releasing a snapshot without triggering a copy on write.
483     SkCanvas* canvas = surface->getCanvas();
484     canvas->clear(1);
485     surface->makeImageSnapshot();  // Create and destroy SkImage
486     canvas->clear(2);  // Must not assert internally
487 }
DEF_TEST(SurfaceWriteableAfterSnapshotRelease,reporter)488 DEF_TEST(SurfaceWriteableAfterSnapshotRelease, reporter) {
489     test_writable_after_snapshot_release(reporter, create_surface().get());
490 }
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceWriteableAfterSnapshotRelease_Gpu,reporter,ctxInfo)491 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceWriteableAfterSnapshotRelease_Gpu, reporter, ctxInfo) {
492     for (auto& surface_func : { &create_gpu_surface, &create_gpu_scratch_surface }) {
493         auto surface(surface_func(ctxInfo.directContext(), kPremul_SkAlphaType, nullptr));
494         test_writable_after_snapshot_release(reporter, surface.get());
495     }
496 }
497 
test_crbug263329(skiatest::Reporter * reporter,SkSurface * surface1,SkSurface * surface2)498 static void test_crbug263329(skiatest::Reporter* reporter,
499                              SkSurface* surface1,
500                              SkSurface* surface2) {
501     // This is a regression test for crbug.com/263329
502     // Bug was caused by onCopyOnWrite releasing the old surface texture
503     // back to the scratch texture pool even though the texture is used
504     // by and active SkImage_Gpu.
505     SkCanvas* canvas1 = surface1->getCanvas();
506     SkCanvas* canvas2 = surface2->getCanvas();
507     canvas1->clear(1);
508     sk_sp<SkImage> image1(surface1->makeImageSnapshot());
509     // Trigger copy on write, new backing is a scratch texture
510     canvas1->clear(2);
511     sk_sp<SkImage> image2(surface1->makeImageSnapshot());
512     // Trigger copy on write, old backing should not be returned to scratch
513     // pool because it is held by image2
514     canvas1->clear(3);
515 
516     canvas2->clear(4);
517     sk_sp<SkImage> image3(surface2->makeImageSnapshot());
518     // Trigger copy on write on surface2. The new backing store should not
519     // be recycling a texture that is held by an existing image.
520     canvas2->clear(5);
521     sk_sp<SkImage> image4(surface2->makeImageSnapshot());
522 
523     auto imageProxy = [ctx = surface1->recordingContext()](SkImage* img) {
524         GrTextureProxy* proxy = sk_gpu_test::GetTextureImageProxy(img, ctx);
525         SkASSERT(proxy);
526         return proxy;
527     };
528 
529     REPORTER_ASSERT(reporter, imageProxy(image4.get()) != imageProxy(image3.get()));
530     // The following assertion checks crbug.com/263329
531     REPORTER_ASSERT(reporter, imageProxy(image4.get()) != imageProxy(image2.get()));
532     REPORTER_ASSERT(reporter, imageProxy(image4.get()) != imageProxy(image1.get()));
533     REPORTER_ASSERT(reporter, imageProxy(image3.get()) != imageProxy(image2.get()));
534     REPORTER_ASSERT(reporter, imageProxy(image3.get()) != imageProxy(image1.get()));
535     REPORTER_ASSERT(reporter, imageProxy(image2.get()) != imageProxy(image1.get()));
536 }
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceCRBug263329_Gpu,reporter,ctxInfo)537 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceCRBug263329_Gpu, reporter, ctxInfo) {
538     for (auto& surface_func : { &create_gpu_surface, &create_gpu_scratch_surface }) {
539         auto surface1(surface_func(ctxInfo.directContext(), kPremul_SkAlphaType, nullptr));
540         auto surface2(surface_func(ctxInfo.directContext(), kPremul_SkAlphaType, nullptr));
541         test_crbug263329(reporter, surface1.get(), surface2.get());
542     }
543 }
544 
DEF_TEST(SurfaceGetTexture,reporter)545 DEF_TEST(SurfaceGetTexture, reporter) {
546     auto surface(create_surface());
547     sk_sp<SkImage> image(surface->makeImageSnapshot());
548     REPORTER_ASSERT(reporter, !as_IB(image)->isTextureBacked());
549     surface->notifyContentWillChange(SkSurface::kDiscard_ContentChangeMode);
550     REPORTER_ASSERT(reporter, !as_IB(image)->isTextureBacked());
551 }
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfacepeekTexture_Gpu,reporter,ctxInfo)552 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfacepeekTexture_Gpu, reporter, ctxInfo) {
553     for (auto& surface_func : { &create_gpu_surface, &create_gpu_scratch_surface }) {
554         auto surface(surface_func(ctxInfo.directContext(), kPremul_SkAlphaType, nullptr));
555         sk_sp<SkImage> image(surface->makeImageSnapshot());
556 
557         REPORTER_ASSERT(reporter, as_IB(image)->isTextureBacked());
558         GrBackendTexture backendTex = image->getBackendTexture(false);
559         REPORTER_ASSERT(reporter, backendTex.isValid());
560         surface->notifyContentWillChange(SkSurface::kDiscard_ContentChangeMode);
561         REPORTER_ASSERT(reporter, as_IB(image)->isTextureBacked());
562         GrBackendTexture backendTex2 = image->getBackendTexture(false);
563         REPORTER_ASSERT(reporter, GrBackendTexture::TestingOnly_Equals(backendTex, backendTex2));
564     }
565 }
566 
is_budgeted(const sk_sp<SkSurface> & surf)567 static SkBudgeted is_budgeted(const sk_sp<SkSurface>& surf) {
568     SkSurface_Gpu* gsurf = (SkSurface_Gpu*)surf.get();
569 
570     GrRenderTargetProxy* proxy = gsurf->getDevice()->targetProxy();
571     return proxy->isBudgeted();
572 }
573 
is_budgeted(SkImage * image,GrRecordingContext * rc)574 static SkBudgeted is_budgeted(SkImage* image, GrRecordingContext* rc) {
575     return sk_gpu_test::GetTextureImageProxy(image, rc)->isBudgeted();
576 }
577 
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceBudget,reporter,ctxInfo)578 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceBudget, reporter, ctxInfo) {
579     SkImageInfo info = SkImageInfo::MakeN32Premul(8,8);
580     GrDirectContext* dContext = ctxInfo.directContext();
581     for (auto budgeted : { SkBudgeted::kNo, SkBudgeted::kYes }) {
582         auto surface(SkSurface::MakeRenderTarget(dContext, budgeted, info));
583         SkASSERT(surface);
584         REPORTER_ASSERT(reporter, budgeted == is_budgeted(surface));
585 
586         sk_sp<SkImage> image(surface->makeImageSnapshot());
587 
588         // Initially the image shares a texture with the surface, and the
589         // the budgets should always match.
590         REPORTER_ASSERT(reporter, budgeted == is_budgeted(surface));
591         REPORTER_ASSERT(reporter, budgeted == is_budgeted(image.get(), dContext));
592 
593         // Now trigger copy-on-write
594         surface->getCanvas()->clear(SK_ColorBLUE);
595 
596         // They don't share a texture anymore but the budgets should still match.
597         REPORTER_ASSERT(reporter, budgeted == is_budgeted(surface));
598         REPORTER_ASSERT(reporter, budgeted == is_budgeted(image.get(), dContext));
599     }
600 }
601 
test_no_canvas1(skiatest::Reporter * reporter,SkSurface * surface,SkSurface::ContentChangeMode mode)602 static void test_no_canvas1(skiatest::Reporter* reporter,
603                             SkSurface* surface,
604                             SkSurface::ContentChangeMode mode) {
605     // Test passes by not asserting
606     surface->notifyContentWillChange(mode);
607 }
test_no_canvas2(skiatest::Reporter * reporter,SkSurface * surface,SkSurface::ContentChangeMode mode)608 static void test_no_canvas2(skiatest::Reporter* reporter,
609                             SkSurface* surface,
610                             SkSurface::ContentChangeMode mode) {
611     // Verifies the robustness of SkSurface for handling use cases where calls
612     // are made before a canvas is created.
613     sk_sp<SkImage> image1 = surface->makeImageSnapshot();
614     sk_sp<SkImage> aur_image1(image1);  // NOLINT(performance-unnecessary-copy-initialization)
615     surface->notifyContentWillChange(mode);
616     sk_sp<SkImage> image2 = surface->makeImageSnapshot();
617     sk_sp<SkImage> aur_image2(image2);  // NOLINT(performance-unnecessary-copy-initialization)
618     REPORTER_ASSERT(reporter, image1 != image2);
619 }
DEF_TEST(SurfaceNoCanvas,reporter)620 DEF_TEST(SurfaceNoCanvas, reporter) {
621     SkSurface::ContentChangeMode modes[] =
622             { SkSurface::kDiscard_ContentChangeMode, SkSurface::kRetain_ContentChangeMode};
623     for (auto& test_func : { &test_no_canvas1, &test_no_canvas2 }) {
624         for (auto& mode : modes) {
625             test_func(reporter, create_surface().get(), mode);
626         }
627     }
628 }
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceNoCanvas_Gpu,reporter,ctxInfo)629 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceNoCanvas_Gpu, reporter, ctxInfo) {
630     SkSurface::ContentChangeMode modes[] =
631             { SkSurface::kDiscard_ContentChangeMode, SkSurface::kRetain_ContentChangeMode};
632     for (auto& surface_func : { &create_gpu_surface, &create_gpu_scratch_surface }) {
633         for (auto& test_func : { &test_no_canvas1, &test_no_canvas2 }) {
634             for (auto& mode : modes) {
635                 auto surface(surface_func(ctxInfo.directContext(), kPremul_SkAlphaType, nullptr));
636                 test_func(reporter, surface.get(), mode);
637             }
638         }
639     }
640 }
641 
check_rowbytes_remain_consistent(SkSurface * surface,skiatest::Reporter * reporter)642 static void check_rowbytes_remain_consistent(SkSurface* surface, skiatest::Reporter* reporter) {
643     SkPixmap surfacePM;
644     REPORTER_ASSERT(reporter, surface->peekPixels(&surfacePM));
645 
646     sk_sp<SkImage> image(surface->makeImageSnapshot());
647     SkPixmap pm;
648     REPORTER_ASSERT(reporter, image->peekPixels(&pm));
649 
650     REPORTER_ASSERT(reporter, surfacePM.rowBytes() == pm.rowBytes());
651 
652     // trigger a copy-on-write
653     surface->getCanvas()->drawPaint(SkPaint());
654     sk_sp<SkImage> image2(surface->makeImageSnapshot());
655     REPORTER_ASSERT(reporter, image->uniqueID() != image2->uniqueID());
656 
657     SkPixmap pm2;
658     REPORTER_ASSERT(reporter, image2->peekPixels(&pm2));
659     REPORTER_ASSERT(reporter, pm2.rowBytes() == pm.rowBytes());
660 }
661 
DEF_TEST(surface_rowbytes,reporter)662 DEF_TEST(surface_rowbytes, reporter) {
663     const SkImageInfo info = SkImageInfo::MakeN32Premul(100, 100);
664 
665     auto surf0(SkSurface::MakeRaster(info));
666     check_rowbytes_remain_consistent(surf0.get(), reporter);
667 
668     // specify a larger rowbytes
669     auto surf1(SkSurface::MakeRaster(info, 500, nullptr));
670     check_rowbytes_remain_consistent(surf1.get(), reporter);
671 
672     // Try some illegal rowByte values
673     auto s = SkSurface::MakeRaster(info, 396, nullptr);    // needs to be at least 400
674     REPORTER_ASSERT(reporter, nullptr == s);
675     s = SkSurface::MakeRaster(info, std::numeric_limits<size_t>::max(), nullptr);
676     REPORTER_ASSERT(reporter, nullptr == s);
677 }
678 
DEF_TEST(surface_raster_zeroinitialized,reporter)679 DEF_TEST(surface_raster_zeroinitialized, reporter) {
680     sk_sp<SkSurface> s(SkSurface::MakeRasterN32Premul(100, 100));
681     SkPixmap pixmap;
682     REPORTER_ASSERT(reporter, s->peekPixels(&pixmap));
683 
684     for (int i = 0; i < pixmap.info().width(); ++i) {
685         for (int j = 0; j < pixmap.info().height(); ++j) {
686             REPORTER_ASSERT(reporter, *pixmap.addr32(i, j) == 0);
687         }
688     }
689 }
690 
create_gpu_surface_backend_texture(GrDirectContext * dContext,int sampleCnt,const SkColor4f & color)691 static sk_sp<SkSurface> create_gpu_surface_backend_texture(GrDirectContext* dContext,
692                                                            int sampleCnt,
693                                                            const SkColor4f& color) {
694     // On Pixel and Pixel2XL's with Adreno 530 and 540s, setting width and height to 10s reliably
695     // triggers what appears to be a driver race condition where the 10x10 surface from the
696     // OverdrawSurface_gpu test is reused(?) for this surface created by the SurfacePartialDraw_gpu
697     // test.
698     //
699     // Immediately after creation of this surface, readback shows the correct initial solid color.
700     // However, sometime before content is rendered into the upper half of the surface, the driver
701     // presumably cleans up the OverdrawSurface_gpu's memory which corrupts this color buffer. The
702     // top half of the surface is fine after the partially-covering rectangle is drawn, but the
703     // untouched bottom half contains random pixel values that trigger asserts in the
704     // SurfacePartialDraw_gpu test for no longer matching the initial color. Running the
705     // SurfacePartialDraw_gpu test without the OverdrawSurface_gpu test completes successfully.
706     //
707     // Requesting a much larger backend texture size seems to prevent it from reusing the same
708     // memory and avoids the issue.
709 #if defined(SK_BUILD_FOR_SKQP)
710     const int kWidth = 10;
711     const int kHeight = 10;
712 #else
713     const int kWidth = 100;
714     const int kHeight = 100;
715 #endif
716 
717     auto surf = sk_gpu_test::MakeBackendTextureSurface(dContext,
718                                                        {kWidth, kHeight},
719                                                        kTopLeft_GrSurfaceOrigin,
720                                                        sampleCnt,
721                                                        kRGBA_8888_SkColorType);
722     if (!surf) {
723         return nullptr;
724     }
725     surf->getCanvas()->clear(color);
726     return surf;
727 }
728 
supports_readpixels(const GrCaps * caps,SkSurface * surface)729 static bool supports_readpixels(const GrCaps* caps, SkSurface* surface) {
730     auto surfaceGpu = static_cast<SkSurface_Gpu*>(surface);
731     GrRenderTarget* rt = surfaceGpu->getDevice()->targetProxy()->peekRenderTarget();
732     if (!rt) {
733         return false;
734     }
735     return caps->surfaceSupportsReadPixels(rt) == GrCaps::SurfaceReadPixelsSupport::kSupported;
736 }
737 
create_gpu_surface_backend_render_target(GrDirectContext * dContext,int sampleCnt,const SkColor4f & color)738 static sk_sp<SkSurface> create_gpu_surface_backend_render_target(GrDirectContext* dContext,
739                                                                  int sampleCnt,
740                                                                  const SkColor4f& color) {
741     const int kWidth = 10;
742     const int kHeight = 10;
743 
744     auto surf = sk_gpu_test::MakeBackendRenderTargetSurface(dContext,
745                                                             {kWidth, kHeight},
746                                                             kTopLeft_GrSurfaceOrigin,
747                                                             sampleCnt,
748                                                             kRGBA_8888_SkColorType);
749     if (!surf) {
750         return nullptr;
751     }
752     surf->getCanvas()->clear(color);
753     return surf;
754 }
755 
test_surface_context_clear(skiatest::Reporter * reporter,GrDirectContext * dContext,skgpu::SurfaceContext * surfaceContext,uint32_t expectedValue)756 static void test_surface_context_clear(skiatest::Reporter* reporter,
757                                        GrDirectContext* dContext,
758                                        skgpu::SurfaceContext* surfaceContext,
759                                        uint32_t expectedValue) {
760     int w = surfaceContext->width();
761     int h = surfaceContext->height();
762 
763     SkImageInfo ii = SkImageInfo::Make(w, h, kRGBA_8888_SkColorType, kPremul_SkAlphaType);
764 
765     SkAutoPixmapStorage readback;
766     readback.alloc(ii);
767 
768     readback.erase(~expectedValue);
769     surfaceContext->readPixels(dContext, readback, {0, 0});
770     for (int y = 0; y < h; ++y) {
771         for (int x = 0; x < w; ++x) {
772             uint32_t pixel = readback.addr32()[y * w + x];
773             if (pixel != expectedValue) {
774                 SkString msg;
775                 if (expectedValue) {
776                     msg = "SkSurface should have left render target unmodified";
777                 } else {
778                     msg = "SkSurface should have cleared the render target";
779                 }
780                 ERRORF(reporter,
781                        "%s but read 0x%08x (instead of 0x%08x) at %x,%d", msg.c_str(), pixel,
782                        expectedValue, x, y);
783                 return;
784             }
785         }
786     }
787 }
788 
DEF_GPUTEST_FOR_GL_RENDERING_CONTEXTS(SurfaceClear_Gpu,reporter,ctxInfo)789 DEF_GPUTEST_FOR_GL_RENDERING_CONTEXTS(SurfaceClear_Gpu, reporter, ctxInfo) {
790     auto dContext = ctxInfo.directContext();
791     // Snaps an image from a surface and then makes a SurfaceContext from the image's texture.
792     auto makeImageSurfaceContext = [dContext](SkSurface* surface) {
793         sk_sp<SkImage> i(surface->makeImageSnapshot());
794         auto gpuImage = static_cast<SkImage_Gpu*>(as_IB(i));
795         auto [view, ct] = gpuImage->asView(dContext, GrMipmapped::kNo);
796         GrColorInfo colorInfo(ct, i->alphaType(), i->refColorSpace());
797         return dContext->priv().makeSC(view, std::move(colorInfo));
798     };
799 
800     // Test that non-wrapped RTs are created clear.
801     for (auto& surface_func : {&create_gpu_surface, &create_gpu_scratch_surface}) {
802         auto surface = surface_func(dContext, kPremul_SkAlphaType, nullptr);
803         if (!surface) {
804             ERRORF(reporter, "Could not create GPU SkSurface.");
805             return;
806         }
807         auto sfc = SkCanvasPriv::TopDeviceSurfaceFillContext(surface->getCanvas());
808         if (!sfc) {
809             ERRORF(reporter, "Could access surface context of GPU SkSurface.");
810             return;
811         }
812         test_surface_context_clear(reporter, dContext, sfc, 0x0);
813         auto imageSurfaceCtx = makeImageSurfaceContext(surface.get());
814         test_surface_context_clear(reporter, dContext, imageSurfaceCtx.get(), 0x0);
815     }
816 
817     // Wrapped RTs are *not* supposed to clear (to allow client to partially update a surface).
818     const SkColor4f kOrigColor{.67f, .67f, .67f, 1};
819     for (auto& surfaceFunc :
820          {&create_gpu_surface_backend_texture, &create_gpu_surface_backend_render_target}) {
821         auto surface = surfaceFunc(dContext, 1, kOrigColor);
822         if (!surface) {
823             ERRORF(reporter, "Could not create GPU SkSurface.");
824             return;
825         }
826         auto sfc = SkCanvasPriv::TopDeviceSurfaceFillContext(surface->getCanvas());
827         if (!sfc) {
828             ERRORF(reporter, "Could access surface context of GPU SkSurface.");
829             return;
830         }
831         test_surface_context_clear(reporter, dContext, sfc, kOrigColor.toSkColor());
832         auto imageSurfaceCtx = makeImageSurfaceContext(surface.get());
833         test_surface_context_clear(reporter, dContext, imageSurfaceCtx.get(),
834                                    kOrigColor.toSkColor());
835     }
836 }
837 
test_surface_draw_partially(skiatest::Reporter * reporter,sk_sp<SkSurface> surface,SkColor origColor)838 static void test_surface_draw_partially(
839     skiatest::Reporter* reporter, sk_sp<SkSurface> surface, SkColor origColor) {
840     const int kW = surface->width();
841     const int kH = surface->height();
842     SkPaint paint;
843     const SkColor kRectColor = ~origColor | 0xFF000000;
844     paint.setColor(kRectColor);
845     surface->getCanvas()->drawRect(SkRect::MakeIWH(kW, kH/2), paint);
846 
847     // Read back RGBA to avoid format conversions that may not be supported on all platforms.
848     SkImageInfo readInfo = SkImageInfo::Make(kW, kH, kRGBA_8888_SkColorType, kPremul_SkAlphaType);
849 
850     SkAutoPixmapStorage readback;
851     readback.alloc(readInfo);
852 
853     readback.erase(~origColor);
854     REPORTER_ASSERT(reporter, surface->readPixels(readback.info(), readback.writable_addr(),
855                                                   readback.rowBytes(), 0, 0));
856     bool stop = false;
857 
858     SkPMColor origColorPM = SkPackARGB_as_RGBA(SkColorGetA(origColor),
859                                                SkColorGetR(origColor),
860                                                SkColorGetG(origColor),
861                                                SkColorGetB(origColor));
862     SkPMColor rectColorPM = SkPackARGB_as_RGBA(SkColorGetA(kRectColor),
863                                                SkColorGetR(kRectColor),
864                                                SkColorGetG(kRectColor),
865                                                SkColorGetB(kRectColor));
866 
867     for (int y = 0; y < kH/2 && !stop; ++y) {
868        for (int x = 0; x < kW && !stop; ++x) {
869             REPORTER_ASSERT(reporter, rectColorPM == readback.addr32()[x + y * kW]);
870             if (rectColorPM != readback.addr32()[x + y * kW]) {
871                 SkDebugf("--- got [%x] expected [%x], x = %d, y = %d\n",
872                          readback.addr32()[x + y * kW], rectColorPM, x, y);
873                 stop = true;
874             }
875         }
876     }
877     stop = false;
878     for (int y = kH/2; y < kH && !stop; ++y) {
879         for (int x = 0; x < kW && !stop; ++x) {
880             REPORTER_ASSERT(reporter, origColorPM == readback.addr32()[x + y * kW]);
881             if (origColorPM != readback.addr32()[x + y * kW]) {
882                 SkDebugf("--- got [%x] expected [%x], x = %d, y = %d\n",
883                          readback.addr32()[x + y * kW], origColorPM, x, y);
884                 stop = true;
885             }
886         }
887     }
888 }
889 
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfacePartialDraw_Gpu,reporter,ctxInfo)890 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfacePartialDraw_Gpu, reporter, ctxInfo) {
891     auto context = ctxInfo.directContext();
892 
893     static const SkColor4f kOrigColor { 0.667f, 0.733f, 0.8f, 1 };
894 
895     for (auto& surfaceFunc :
896          {&create_gpu_surface_backend_texture, &create_gpu_surface_backend_render_target}) {
897         // Validate that we can draw to the canvas and that the original texture color is
898         // preserved in pixels that aren't rendered to via the surface.
899         // This works only for non-multisampled case.
900         auto surface = surfaceFunc(context, 1, kOrigColor);
901         if (surface && supports_readpixels(context->priv().caps(), surface.get())) {
902             test_surface_draw_partially(reporter, surface, kOrigColor.toSkColor());
903         }
904     }
905 }
906 
907 struct ReleaseChecker {
ReleaseCheckerReleaseChecker908     ReleaseChecker() : fReleaseCount(0) {}
909     int fReleaseCount;
ReleaseReleaseChecker910     static void Release(void* self) {
911         static_cast<ReleaseChecker*>(self)->fReleaseCount++;
912     }
913 };
914 
915 
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceWrappedWithRelease_Gpu,reporter,ctxInfo)916 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceWrappedWithRelease_Gpu, reporter, ctxInfo) {
917     const int kWidth = 10;
918     const int kHeight = 10;
919 
920     auto ctx = ctxInfo.directContext();
921     GrGpu* gpu = ctx->priv().getGpu();
922 
923     for (bool useTexture : {false, true}) {
924         sk_sp<sk_gpu_test::ManagedBackendTexture> mbet;
925         GrBackendRenderTarget backendRT;
926         sk_sp<SkSurface> surface;
927 
928         ReleaseChecker releaseChecker;
929         GrSurfaceOrigin texOrigin = kBottomLeft_GrSurfaceOrigin;
930 
931         if (useTexture) {
932             SkImageInfo ii = SkImageInfo::Make(kWidth, kHeight, SkColorType::kRGBA_8888_SkColorType,
933                                                kPremul_SkAlphaType);
934             mbet = sk_gpu_test::ManagedBackendTexture::MakeFromInfo(ctx, ii, GrMipmapped::kNo,
935                                                                     GrRenderable::kYes);
936             if (!mbet) {
937                 continue;
938             }
939 
940             surface = SkSurface::MakeFromBackendTexture(
941                     ctx,
942                     mbet->texture(),
943                     texOrigin,
944                     /*sample count*/ 1,
945                     kRGBA_8888_SkColorType,
946                     /*color space*/ nullptr,
947                     /*surface props*/ nullptr,
948                     sk_gpu_test::ManagedBackendTexture::ReleaseProc,
949                     mbet->releaseContext(ReleaseChecker::Release, &releaseChecker));
950         } else {
951             backendRT = gpu->createTestingOnlyBackendRenderTarget({kWidth, kHeight},
952                                                                   GrColorType::kRGBA_8888);
953             if (!backendRT.isValid()) {
954                 continue;
955             }
956             surface = SkSurface::MakeFromBackendRenderTarget(ctx, backendRT, texOrigin,
957                                                              kRGBA_8888_SkColorType,
958                                                              nullptr, nullptr,
959                                                              ReleaseChecker::Release,
960                                                              &releaseChecker);
961         }
962         if (!surface) {
963             ERRORF(reporter, "Failed to create surface");
964             continue;
965         }
966 
967         surface->getCanvas()->clear(SK_ColorRED);
968         surface->flush();
969         ctx->submit(true);
970 
971         // Now exercise the release proc
972         REPORTER_ASSERT(reporter, 0 == releaseChecker.fReleaseCount);
973         surface.reset(nullptr); // force a release of the surface
974         REPORTER_ASSERT(reporter, 1 == releaseChecker.fReleaseCount);
975 
976         if (!useTexture) {
977             gpu->deleteTestingOnlyBackendRenderTarget(backendRT);
978         }
979     }
980 }
981 
DEF_GPUTEST_FOR_GL_RENDERING_CONTEXTS(SurfaceAttachStencil_Gpu,reporter,ctxInfo)982 DEF_GPUTEST_FOR_GL_RENDERING_CONTEXTS(SurfaceAttachStencil_Gpu, reporter, ctxInfo) {
983     auto context = ctxInfo.directContext();
984     const GrCaps* caps = context->priv().caps();
985 
986     if (caps->avoidStencilBuffers()) {
987         return;
988     }
989 
990     static const SkColor4f kOrigColor { 0.667f, 0.733f, 0.8f, 1 };
991 
992     auto resourceProvider = context->priv().resourceProvider();
993 
994     for (auto& surfaceFunc :
995          {&create_gpu_surface_backend_texture, &create_gpu_surface_backend_render_target}) {
996         for (int sampleCnt : {1, 4, 8}) {
997             auto surface = surfaceFunc(context, sampleCnt, kOrigColor);
998 
999             if (!surface && sampleCnt > 1) {
1000                 // Certain platforms don't support MSAA, skip these.
1001                 continue;
1002             }
1003 
1004             // Validate that we can attach a stencil buffer to an SkSurface created by either of
1005             // our surface functions.
1006             auto rtp = SkCanvasPriv::TopDeviceTargetProxy(surface->getCanvas());
1007             GrRenderTarget* rt = rtp->peekRenderTarget();
1008             REPORTER_ASSERT(reporter,
1009                             resourceProvider->attachStencilAttachment(rt, rt->numSamples() > 1));
1010         }
1011     }
1012 }
1013 
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(ReplaceSurfaceBackendTexture,reporter,ctxInfo)1014 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(ReplaceSurfaceBackendTexture, reporter, ctxInfo) {
1015     auto context = ctxInfo.directContext();
1016 
1017     for (int sampleCnt : {1, 2}) {
1018         auto ii = SkImageInfo::Make(10, 10, kRGBA_8888_SkColorType, kPremul_SkAlphaType, nullptr);
1019         auto mbet1 = sk_gpu_test::ManagedBackendTexture::MakeFromInfo(
1020                 context, ii, GrMipmapped::kNo, GrRenderable::kYes);
1021         if (!mbet1) {
1022             continue;
1023         }
1024         auto mbet2 = sk_gpu_test::ManagedBackendTexture::MakeFromInfo(
1025                 context, ii, GrMipmapped::kNo, GrRenderable::kYes);
1026         if (!mbet2) {
1027             ERRORF(reporter, "Expected to be able to make second texture");
1028             continue;
1029         }
1030         auto ii2 = ii.makeWH(8, 8);
1031         auto mbet3 = sk_gpu_test::ManagedBackendTexture::MakeFromInfo(
1032                 context, ii2, GrMipmapped::kNo, GrRenderable::kYes);
1033         GrBackendTexture backendTexture3;
1034         if (!mbet3) {
1035             ERRORF(reporter, "Couldn't create different sized texture.");
1036             continue;
1037         }
1038 
1039         auto surf = SkSurface::MakeFromBackendTexture(
1040                 context, mbet1->texture(), kTopLeft_GrSurfaceOrigin, sampleCnt,
1041                 kRGBA_8888_SkColorType, ii.refColorSpace(), nullptr);
1042         if (!surf) {
1043             continue;
1044         }
1045         surf->getCanvas()->clear(SK_ColorBLUE);
1046         // Change matrix, layer, and clip state before swapping out the backing texture.
1047         surf->getCanvas()->translate(5, 5);
1048         surf->getCanvas()->saveLayer(nullptr, nullptr);
1049         surf->getCanvas()->clipRect(SkRect::MakeXYWH(0, 0, 1, 1));
1050         // switch origin while we're at it.
1051         bool replaced = surf->replaceBackendTexture(mbet2->texture(), kBottomLeft_GrSurfaceOrigin);
1052         REPORTER_ASSERT(reporter, replaced);
1053         SkPaint paint;
1054         paint.setColor(SK_ColorRED);
1055         surf->getCanvas()->drawRect(SkRect::MakeWH(5, 5), paint);
1056         surf->getCanvas()->restore();
1057 
1058         // Check that the replacement texture got the right color values.
1059         SkAutoPixmapStorage pm;
1060         pm.alloc(ii);
1061         bool bad = !surf->readPixels(pm, 0, 0);
1062         REPORTER_ASSERT(reporter, !bad, "Could not read surface.");
1063         for (int y = 0; y < ii.height() && !bad; ++y) {
1064             for (int x = 0; x < ii.width() && !bad; ++x) {
1065                 auto expected = (x == 5 && y == 5) ? 0xFF0000FF : 0xFFFF0000;
1066                 auto found = *pm.addr32(x, y);
1067                 if (found != expected) {
1068                     bad = true;
1069                     ERRORF(reporter, "Expected color 0x%08x, found color 0x%08x at %d, %d.",
1070                            expected, found, x, y);
1071                 }
1072             }
1073         }
1074         // The original texture should still be all blue.
1075         surf = SkSurface::MakeFromBackendTexture(
1076                 context, mbet1->texture(), kBottomLeft_GrSurfaceOrigin, sampleCnt,
1077                 kRGBA_8888_SkColorType, ii.refColorSpace(), nullptr);
1078         if (!surf) {
1079             ERRORF(reporter, "Could not create second surface.");
1080             continue;
1081         }
1082         bad = !surf->readPixels(pm, 0, 0);
1083         REPORTER_ASSERT(reporter, !bad, "Could not read second surface.");
1084         for (int y = 0; y < ii.height() && !bad; ++y) {
1085             for (int x = 0; x < ii.width() && !bad; ++x) {
1086                 auto expected = 0xFFFF0000;
1087                 auto found = *pm.addr32(x, y);
1088                 if (found != expected) {
1089                     bad = true;
1090                     ERRORF(reporter, "Expected color 0x%08x, found color 0x%08x at %d, %d.",
1091                            expected, found, x, y);
1092                 }
1093             }
1094         }
1095 
1096         // Can't replace with the same texture
1097         REPORTER_ASSERT(reporter,
1098                         !surf->replaceBackendTexture(mbet1->texture(), kTopLeft_GrSurfaceOrigin));
1099         // Can't replace with invalid texture
1100         REPORTER_ASSERT(reporter, !surf->replaceBackendTexture({}, kTopLeft_GrSurfaceOrigin));
1101         // Can't replace with different size texture.
1102         REPORTER_ASSERT(reporter,
1103                         !surf->replaceBackendTexture(mbet3->texture(), kTopLeft_GrSurfaceOrigin));
1104         // Can't replace texture of non-wrapped SkSurface.
1105         surf = SkSurface::MakeRenderTarget(context, SkBudgeted::kYes, ii, sampleCnt, nullptr);
1106         REPORTER_ASSERT(reporter, surf);
1107         if (surf) {
1108             REPORTER_ASSERT(reporter, !surf->replaceBackendTexture(mbet1->texture(),
1109                                                                    kTopLeft_GrSurfaceOrigin));
1110         }
1111     }
1112 }
1113 
test_overdraw_surface(skiatest::Reporter * r,SkSurface * surface)1114 static void test_overdraw_surface(skiatest::Reporter* r, SkSurface* surface) {
1115     SkOverdrawCanvas canvas(surface->getCanvas());
1116     canvas.drawPaint(SkPaint());
1117     sk_sp<SkImage> image = surface->makeImageSnapshot();
1118 
1119     SkBitmap bitmap;
1120     image->asLegacyBitmap(&bitmap);
1121     for (int y = 0; y < 10; y++) {
1122         for (int x = 0; x < 10; x++) {
1123             REPORTER_ASSERT(r, 1 == SkGetPackedA32(*bitmap.getAddr32(x, y)));
1124         }
1125     }
1126 }
1127 
DEF_TEST(OverdrawSurface_Raster,r)1128 DEF_TEST(OverdrawSurface_Raster, r) {
1129     sk_sp<SkSurface> surface = create_surface();
1130     test_overdraw_surface(r, surface.get());
1131 }
1132 
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(OverdrawSurface_Gpu,r,ctxInfo)1133 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(OverdrawSurface_Gpu, r, ctxInfo) {
1134     auto context = ctxInfo.directContext();
1135     sk_sp<SkSurface> surface = create_gpu_surface(context);
1136     test_overdraw_surface(r, surface.get());
1137 }
1138 
DEF_TEST(Surface_null,r)1139 DEF_TEST(Surface_null, r) {
1140     REPORTER_ASSERT(r, SkSurface::MakeNull(0, 0) == nullptr);
1141 
1142     const int w = 37;
1143     const int h = 1000;
1144     auto surf = SkSurface::MakeNull(w, h);
1145     auto canvas = surf->getCanvas();
1146 
1147     canvas->drawPaint(SkPaint());   // should not crash, but don't expect anything to draw
1148     REPORTER_ASSERT(r, surf->makeImageSnapshot() == nullptr);
1149 }
1150 
1151 // assert: if a given imageinfo is valid for a surface, then it must be valid for an image
1152 //         (so the snapshot can succeed)
DEF_TEST(surface_image_unity,reporter)1153 DEF_TEST(surface_image_unity, reporter) {
1154     auto do_test = [reporter](const SkImageInfo& info) {
1155         size_t rowBytes = info.minRowBytes();
1156         auto surf = SkSurface::MakeRaster(info, rowBytes, nullptr);
1157         if (surf) {
1158             auto img = surf->makeImageSnapshot();
1159             if (!img && false) {    // change to true to document the differences
1160                 SkDebugf("image failed: [%08X %08X] %14s %s\n",
1161                          info.width(),
1162                          info.height(),
1163                          ToolUtils::colortype_name(info.colorType()),
1164                          ToolUtils::alphatype_name(info.alphaType()));
1165                 return;
1166             }
1167             REPORTER_ASSERT(reporter, img != nullptr);
1168 
1169             char tempPixel = 0;    // just need a valid address (not a valid size)
1170             SkPixmap pmap = { info, &tempPixel, rowBytes };
1171             img = SkImage::MakeFromRaster(pmap, nullptr, nullptr);
1172             REPORTER_ASSERT(reporter, img != nullptr);
1173         }
1174     };
1175 
1176     const int32_t sizes[] = { -1, 0, 1, 1 << 18 };
1177     for (int cti = 0; cti <= kLastEnum_SkColorType; ++cti) {
1178         SkColorType ct = static_cast<SkColorType>(cti);
1179         for (int ati = 0; ati <= kLastEnum_SkAlphaType; ++ati) {
1180             SkAlphaType at = static_cast<SkAlphaType>(ati);
1181             for (int32_t size : sizes) {
1182                 do_test(SkImageInfo::Make(1, size, ct, at));
1183                 do_test(SkImageInfo::Make(size, 1, ct, at));
1184             }
1185         }
1186     }
1187 }
1188