GrLatticeOp.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. /*
  2. * Copyright 2015 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. #include "include/core/SkBitmap.h"
  8. #include "include/core/SkRect.h"
  9. #include "src/core/SkLatticeIter.h"
  10. #include "src/core/SkMatrixPriv.h"
  11. #include "src/gpu/GrDefaultGeoProcFactory.h"
  12. #include "src/gpu/GrDrawOpTest.h"
  13. #include "src/gpu/GrGpu.h"
  14. #include "src/gpu/GrOpFlushState.h"
  15. #include "src/gpu/GrResourceProvider.h"
  16. #include "src/gpu/GrResourceProviderPriv.h"
  17. #include "src/gpu/GrVertexWriter.h"
  18. #include "src/gpu/SkGr.h"
  19. #include "src/gpu/glsl/GrGLSLColorSpaceXformHelper.h"
  20. #include "src/gpu/glsl/GrGLSLGeometryProcessor.h"
  21. #include "src/gpu/glsl/GrGLSLVarying.h"
  22. #include "src/gpu/ops/GrLatticeOp.h"
  23. #include "src/gpu/ops/GrMeshDrawOp.h"
  24. #include "src/gpu/ops/GrSimpleMeshDrawOpHelper.h"
  25. namespace {
  26. class LatticeGP : public GrGeometryProcessor {
  27. public:
  28. static sk_sp<GrGeometryProcessor> Make(GrGpu* gpu,
  29. const GrTextureProxy* proxy,
  30. sk_sp<GrColorSpaceXform> csxf,
  31. GrSamplerState::Filter filter,
  32. bool wideColor) {
  33. return sk_sp<GrGeometryProcessor>(
  34. new LatticeGP(gpu, proxy, std::move(csxf), filter, wideColor));
  35. }
  36. const char* name() const override { return "LatticeGP"; }
  37. void getGLSLProcessorKey(const GrShaderCaps&, GrProcessorKeyBuilder* b) const override {
  38. b->add32(GrColorSpaceXform::XformKey(fColorSpaceXform.get()));
  39. }
  40. GrGLSLPrimitiveProcessor* createGLSLInstance(const GrShaderCaps& caps) const override {
  41. class GLSLProcessor : public GrGLSLGeometryProcessor {
  42. public:
  43. void setData(const GrGLSLProgramDataManager& pdman, const GrPrimitiveProcessor& proc,
  44. FPCoordTransformIter&& transformIter) override {
  45. const auto& latticeGP = proc.cast<LatticeGP>();
  46. this->setTransformDataHelper(SkMatrix::I(), pdman, &transformIter);
  47. fColorSpaceXformHelper.setData(pdman, latticeGP.fColorSpaceXform.get());
  48. }
  49. private:
  50. void onEmitCode(EmitArgs& args, GrGPArgs* gpArgs) override {
  51. using Interpolation = GrGLSLVaryingHandler::Interpolation;
  52. const auto& latticeGP = args.fGP.cast<LatticeGP>();
  53. fColorSpaceXformHelper.emitCode(args.fUniformHandler,
  54. latticeGP.fColorSpaceXform.get());
  55. args.fVaryingHandler->emitAttributes(latticeGP);
  56. this->writeOutputPosition(args.fVertBuilder, gpArgs, latticeGP.fInPosition.name());
  57. this->emitTransforms(args.fVertBuilder,
  58. args.fVaryingHandler,
  59. args.fUniformHandler,
  60. latticeGP.fInTextureCoords.asShaderVar(),
  61. args.fFPCoordTransformHandler);
  62. args.fFragBuilder->codeAppend("float2 textureCoords;");
  63. args.fVaryingHandler->addPassThroughAttribute(latticeGP.fInTextureCoords,
  64. "textureCoords");
  65. args.fFragBuilder->codeAppend("float4 textureDomain;");
  66. args.fVaryingHandler->addPassThroughAttribute(
  67. latticeGP.fInTextureDomain, "textureDomain", Interpolation::kCanBeFlat);
  68. args.fVaryingHandler->addPassThroughAttribute(latticeGP.fInColor,
  69. args.fOutputColor,
  70. Interpolation::kCanBeFlat);
  71. args.fFragBuilder->codeAppendf("%s = ", args.fOutputColor);
  72. args.fFragBuilder->appendTextureLookupAndModulate(
  73. args.fOutputColor,
  74. args.fTexSamplers[0],
  75. "clamp(textureCoords, textureDomain.xy, textureDomain.zw)",
  76. kFloat2_GrSLType,
  77. &fColorSpaceXformHelper);
  78. args.fFragBuilder->codeAppend(";");
  79. args.fFragBuilder->codeAppendf("%s = half4(1);", args.fOutputCoverage);
  80. }
  81. GrGLSLColorSpaceXformHelper fColorSpaceXformHelper;
  82. };
  83. return new GLSLProcessor;
  84. }
  85. private:
  86. LatticeGP(GrGpu* gpu, const GrTextureProxy* proxy, sk_sp<GrColorSpaceXform> csxf,
  87. GrSamplerState::Filter filter, bool wideColor)
  88. : INHERITED(kLatticeGP_ClassID), fColorSpaceXform(std::move(csxf)) {
  89. GrSamplerState samplerState = GrSamplerState(GrSamplerState::WrapMode::kClamp,
  90. filter);
  91. uint32_t extraSamplerKey = gpu->getExtraSamplerKeyForProgram(samplerState,
  92. proxy->backendFormat());
  93. fSampler.reset(proxy->textureType(), proxy->config(), samplerState, proxy->textureSwizzle(),
  94. extraSamplerKey);
  95. this->setTextureSamplerCnt(1);
  96. fInPosition = {"position", kFloat2_GrVertexAttribType, kFloat2_GrSLType};
  97. fInTextureCoords = {"textureCoords", kFloat2_GrVertexAttribType, kFloat2_GrSLType};
  98. fInTextureDomain = {"textureDomain", kFloat4_GrVertexAttribType, kFloat4_GrSLType};
  99. fInColor = MakeColorAttribute("color", wideColor);
  100. this->setVertexAttributes(&fInPosition, 4);
  101. }
  102. const TextureSampler& onTextureSampler(int) const override { return fSampler; }
  103. Attribute fInPosition;
  104. Attribute fInTextureCoords;
  105. Attribute fInTextureDomain;
  106. Attribute fInColor;
  107. sk_sp<GrColorSpaceXform> fColorSpaceXform;
  108. TextureSampler fSampler;
  109. typedef GrGeometryProcessor INHERITED;
  110. };
  111. class NonAALatticeOp final : public GrMeshDrawOp {
  112. private:
  113. using Helper = GrSimpleMeshDrawOpHelper;
  114. public:
  115. DEFINE_OP_CLASS_ID
  116. static const int kVertsPerRect = 4;
  117. static const int kIndicesPerRect = 6;
  118. static std::unique_ptr<GrDrawOp> Make(GrRecordingContext* context,
  119. GrPaint&& paint,
  120. const SkMatrix& viewMatrix,
  121. sk_sp<GrTextureProxy> proxy,
  122. sk_sp<GrColorSpaceXform> colorSpaceXForm,
  123. GrSamplerState::Filter filter,
  124. std::unique_ptr<SkLatticeIter> iter,
  125. const SkRect& dst) {
  126. SkASSERT(proxy);
  127. return Helper::FactoryHelper<NonAALatticeOp>(context, std::move(paint), viewMatrix,
  128. std::move(proxy),
  129. std::move(colorSpaceXForm), filter,
  130. std::move(iter), dst);
  131. }
  132. NonAALatticeOp(Helper::MakeArgs& helperArgs, const SkPMColor4f& color,
  133. const SkMatrix& viewMatrix, sk_sp<GrTextureProxy> proxy,
  134. sk_sp<GrColorSpaceXform> colorSpaceXform, GrSamplerState::Filter filter,
  135. std::unique_ptr<SkLatticeIter> iter, const SkRect& dst)
  136. : INHERITED(ClassID())
  137. , fHelper(helperArgs, GrAAType::kNone)
  138. , fProxy(std::move(proxy))
  139. , fColorSpaceXform(std::move(colorSpaceXform))
  140. , fFilter(filter) {
  141. Patch& patch = fPatches.push_back();
  142. patch.fViewMatrix = viewMatrix;
  143. patch.fColor = color;
  144. patch.fIter = std::move(iter);
  145. patch.fDst = dst;
  146. // setup bounds
  147. this->setTransformedBounds(patch.fDst, viewMatrix, HasAABloat::kNo, IsZeroArea::kNo);
  148. }
  149. const char* name() const override { return "NonAALatticeOp"; }
  150. void visitProxies(const VisitProxyFunc& func) const override {
  151. bool mipped = (GrSamplerState::Filter::kMipMap == fFilter);
  152. func(fProxy.get(), GrMipMapped(mipped));
  153. fHelper.visitProxies(func);
  154. }
  155. #ifdef SK_DEBUG
  156. SkString dumpInfo() const override {
  157. SkString str;
  158. for (int i = 0; i < fPatches.count(); ++i) {
  159. str.appendf("%d: Color: 0x%08x Dst [L: %.2f, T: %.2f, R: %.2f, B: %.2f]\n", i,
  160. fPatches[i].fColor.toBytes_RGBA(), fPatches[i].fDst.fLeft,
  161. fPatches[i].fDst.fTop, fPatches[i].fDst.fRight, fPatches[i].fDst.fBottom);
  162. }
  163. str += fHelper.dumpInfo();
  164. str += INHERITED::dumpInfo();
  165. return str;
  166. }
  167. #endif
  168. FixedFunctionFlags fixedFunctionFlags() const override { return fHelper.fixedFunctionFlags(); }
  169. GrProcessorSet::Analysis finalize(
  170. const GrCaps& caps, const GrAppliedClip* clip, bool hasMixedSampledCoverage,
  171. GrClampType clampType) override {
  172. auto opaque = fPatches[0].fColor.isOpaque() && GrPixelConfigIsOpaque(fProxy->config())
  173. ? GrProcessorAnalysisColor::Opaque::kYes
  174. : GrProcessorAnalysisColor::Opaque::kNo;
  175. auto analysisColor = GrProcessorAnalysisColor(opaque);
  176. auto result = fHelper.finalizeProcessors(
  177. caps, clip, hasMixedSampledCoverage, clampType, GrProcessorAnalysisCoverage::kNone,
  178. &analysisColor);
  179. analysisColor.isConstant(&fPatches[0].fColor);
  180. fWideColor = SkPMColor4fNeedsWideColor(fPatches[0].fColor, clampType, caps);
  181. return result;
  182. }
  183. private:
  184. void onPrepareDraws(Target* target) override {
  185. GrGpu* gpu = target->resourceProvider()->priv().gpu();
  186. auto gp = LatticeGP::Make(gpu, fProxy.get(), fColorSpaceXform, fFilter, fWideColor);
  187. if (!gp) {
  188. SkDebugf("Couldn't create GrGeometryProcessor\n");
  189. return;
  190. }
  191. int patchCnt = fPatches.count();
  192. int numRects = 0;
  193. for (int i = 0; i < patchCnt; i++) {
  194. numRects += fPatches[i].fIter->numRectsToDraw();
  195. }
  196. if (!numRects) {
  197. return;
  198. }
  199. const size_t kVertexStride = gp->vertexStride();
  200. sk_sp<const GrBuffer> indexBuffer = target->resourceProvider()->refQuadIndexBuffer();
  201. if (!indexBuffer) {
  202. SkDebugf("Could not allocate indices\n");
  203. return;
  204. }
  205. PatternHelper helper(target, GrPrimitiveType::kTriangles, kVertexStride,
  206. std::move(indexBuffer), kVertsPerRect, kIndicesPerRect, numRects);
  207. GrVertexWriter vertices{helper.vertices()};
  208. if (!vertices.fPtr) {
  209. SkDebugf("Could not allocate vertices\n");
  210. return;
  211. }
  212. for (int i = 0; i < patchCnt; i++) {
  213. const Patch& patch = fPatches[i];
  214. GrVertexColor patchColor(patch.fColor, fWideColor);
  215. // Apply the view matrix here if it is scale-translate. Otherwise, we need to
  216. // wait until we've created the dst rects.
  217. bool isScaleTranslate = patch.fViewMatrix.isScaleTranslate();
  218. if (isScaleTranslate) {
  219. patch.fIter->mapDstScaleTranslate(patch.fViewMatrix);
  220. }
  221. SkIRect srcR;
  222. SkRect dstR;
  223. SkPoint* patchPositions = reinterpret_cast<SkPoint*>(vertices.fPtr);
  224. Sk4f scales(1.f / fProxy->width(), 1.f / fProxy->height(),
  225. 1.f / fProxy->width(), 1.f / fProxy->height());
  226. static const Sk4f kDomainOffsets(0.5f, 0.5f, -0.5f, -0.5f);
  227. static const Sk4f kFlipOffsets(0.f, 1.f, 0.f, 1.f);
  228. static const Sk4f kFlipMuls(1.f, -1.f, 1.f, -1.f);
  229. while (patch.fIter->next(&srcR, &dstR)) {
  230. Sk4f coords(SkIntToScalar(srcR.fLeft), SkIntToScalar(srcR.fTop),
  231. SkIntToScalar(srcR.fRight), SkIntToScalar(srcR.fBottom));
  232. Sk4f domain = coords + kDomainOffsets;
  233. coords *= scales;
  234. domain *= scales;
  235. if (fProxy->origin() == kBottomLeft_GrSurfaceOrigin) {
  236. coords = kFlipMuls * coords + kFlipOffsets;
  237. domain = SkNx_shuffle<0, 3, 2, 1>(kFlipMuls * domain + kFlipOffsets);
  238. }
  239. SkRect texDomain;
  240. SkRect texCoords;
  241. domain.store(&texDomain);
  242. coords.store(&texCoords);
  243. vertices.writeQuad(GrVertexWriter::TriStripFromRect(dstR),
  244. GrVertexWriter::TriStripFromRect(texCoords),
  245. texDomain,
  246. patchColor);
  247. }
  248. // If we didn't handle it above, apply the matrix here.
  249. if (!isScaleTranslate) {
  250. SkMatrixPriv::MapPointsWithStride(patch.fViewMatrix, patchPositions, kVertexStride,
  251. kVertsPerRect * patch.fIter->numRectsToDraw());
  252. }
  253. }
  254. auto fixedDynamicState = target->makeFixedDynamicState(1);
  255. fixedDynamicState->fPrimitiveProcessorTextures[0] = fProxy.get();
  256. helper.recordDraw(target, std::move(gp), fixedDynamicState);
  257. }
  258. void onExecute(GrOpFlushState* flushState, const SkRect& chainBounds) override {
  259. fHelper.executeDrawsAndUploads(this, flushState, chainBounds);
  260. }
  261. CombineResult onCombineIfPossible(GrOp* t, const GrCaps& caps) override {
  262. NonAALatticeOp* that = t->cast<NonAALatticeOp>();
  263. if (fProxy != that->fProxy) {
  264. return CombineResult::kCannotCombine;
  265. }
  266. if (fFilter != that->fFilter) {
  267. return CombineResult::kCannotCombine;
  268. }
  269. if (GrColorSpaceXform::Equals(fColorSpaceXform.get(), that->fColorSpaceXform.get())) {
  270. return CombineResult::kCannotCombine;
  271. }
  272. if (!fHelper.isCompatible(that->fHelper, caps, this->bounds(), that->bounds())) {
  273. return CombineResult::kCannotCombine;
  274. }
  275. fPatches.move_back_n(that->fPatches.count(), that->fPatches.begin());
  276. fWideColor |= that->fWideColor;
  277. return CombineResult::kMerged;
  278. }
  279. struct Patch {
  280. SkMatrix fViewMatrix;
  281. std::unique_ptr<SkLatticeIter> fIter;
  282. SkRect fDst;
  283. SkPMColor4f fColor;
  284. };
  285. Helper fHelper;
  286. SkSTArray<1, Patch, true> fPatches;
  287. sk_sp<GrTextureProxy> fProxy;
  288. sk_sp<GrColorSpaceXform> fColorSpaceXform;
  289. GrSamplerState::Filter fFilter;
  290. bool fWideColor;
  291. typedef GrMeshDrawOp INHERITED;
  292. };
  293. } // anonymous namespace
  294. namespace GrLatticeOp {
  295. std::unique_ptr<GrDrawOp> MakeNonAA(GrRecordingContext* context,
  296. GrPaint&& paint,
  297. const SkMatrix& viewMatrix,
  298. sk_sp<GrTextureProxy> proxy,
  299. sk_sp<GrColorSpaceXform> colorSpaceXform,
  300. GrSamplerState::Filter filter,
  301. std::unique_ptr<SkLatticeIter> iter,
  302. const SkRect& dst) {
  303. return NonAALatticeOp::Make(context, std::move(paint), viewMatrix, std::move(proxy),
  304. std::move(colorSpaceXform), filter, std::move(iter), dst);
  305. }
  306. };
  307. #if GR_TEST_UTILS
  308. #include "src/gpu/GrProxyProvider.h"
  309. #include "src/gpu/GrRecordingContextPriv.h"
  310. /** Randomly divides subset into count divs. */
  311. static void init_random_divs(int divs[], int count, int subsetStart, int subsetStop,
  312. SkRandom* random) {
  313. // Rules for lattice divs: Must be strictly increasing and in the range
  314. // [subsetStart, subsetStop).
  315. // Not terribly efficient alg for generating random divs:
  316. // 1) Start with minimum legal pixels between each div.
  317. // 2) Randomly assign the remaining pixels of the subset to divs.
  318. // 3) Convert from pixel counts to div offsets.
  319. // 1) Initially each divs[i] represents the number of pixels between
  320. // div i-1 and i. The initial div is allowed to be at subsetStart. There
  321. // must be one pixel spacing between subsequent divs.
  322. divs[0] = 0;
  323. for (int i = 1; i < count; ++i) {
  324. divs[i] = 1;
  325. }
  326. // 2) Assign the remaining subset pixels to fall
  327. int subsetLength = subsetStop - subsetStart;
  328. for (int i = 0; i < subsetLength - count; ++i) {
  329. // +1 because count divs means count+1 intervals.
  330. int entry = random->nextULessThan(count + 1);
  331. // We don't have an entry to to store the count after the last div
  332. if (entry < count) {
  333. divs[entry]++;
  334. }
  335. }
  336. // 3) Now convert the counts between divs to pixel indices, incorporating the subset's offset.
  337. int offset = subsetStart;
  338. for (int i = 0; i < count; ++i) {
  339. divs[i] += offset;
  340. offset = divs[i];
  341. }
  342. }
  343. GR_DRAW_OP_TEST_DEFINE(NonAALatticeOp) {
  344. SkCanvas::Lattice lattice;
  345. // We loop because our random lattice code can produce an invalid lattice in the case where
  346. // there is a single div separator in both x and y and both are aligned with the left and top
  347. // edge of the image subset, respectively.
  348. std::unique_ptr<int[]> xdivs;
  349. std::unique_ptr<int[]> ydivs;
  350. std::unique_ptr<SkCanvas::Lattice::RectType[]> flags;
  351. std::unique_ptr<SkColor[]> colors;
  352. SkIRect subset;
  353. GrSurfaceDesc desc;
  354. desc.fConfig = kRGBA_8888_GrPixelConfig;
  355. desc.fWidth = random->nextRangeU(1, 1000);
  356. desc.fHeight = random->nextRangeU(1, 1000);
  357. GrSurfaceOrigin origin =
  358. random->nextBool() ? kTopLeft_GrSurfaceOrigin : kBottomLeft_GrSurfaceOrigin;
  359. const GrBackendFormat format =
  360. context->priv().caps()->getBackendFormatFromColorType(GrColorType::kRGBA_8888);
  361. auto proxy = context->priv().proxyProvider()->createProxy(format, desc, GrRenderable::kNo, 1,
  362. origin, SkBackingFit::kExact,
  363. SkBudgeted::kYes, GrProtected::kNo);
  364. do {
  365. if (random->nextBool()) {
  366. subset.fLeft = random->nextULessThan(desc.fWidth);
  367. subset.fRight = random->nextRangeU(subset.fLeft + 1, desc.fWidth);
  368. subset.fTop = random->nextULessThan(desc.fHeight);
  369. subset.fBottom = random->nextRangeU(subset.fTop + 1, desc.fHeight);
  370. } else {
  371. subset.setXYWH(0, 0, desc.fWidth, desc.fHeight);
  372. }
  373. // SkCanvas::Lattice allows bounds to be null. However, SkCanvas creates a temp Lattice with
  374. // a non-null bounds before creating a SkLatticeIter since SkLatticeIter requires a bounds.
  375. lattice.fBounds = &subset;
  376. lattice.fXCount = random->nextRangeU(1, subset.width());
  377. lattice.fYCount = random->nextRangeU(1, subset.height());
  378. xdivs.reset(new int[lattice.fXCount]);
  379. ydivs.reset(new int[lattice.fYCount]);
  380. init_random_divs(xdivs.get(), lattice.fXCount, subset.fLeft, subset.fRight, random);
  381. init_random_divs(ydivs.get(), lattice.fYCount, subset.fTop, subset.fBottom, random);
  382. lattice.fXDivs = xdivs.get();
  383. lattice.fYDivs = ydivs.get();
  384. bool hasFlags = random->nextBool();
  385. if (hasFlags) {
  386. int n = (lattice.fXCount + 1) * (lattice.fYCount + 1);
  387. flags.reset(new SkCanvas::Lattice::RectType[n]);
  388. colors.reset(new SkColor[n]);
  389. for (int i = 0; i < n; ++i) {
  390. flags[i] = random->nextBool() ? SkCanvas::Lattice::kTransparent
  391. : SkCanvas::Lattice::kDefault;
  392. }
  393. lattice.fRectTypes = flags.get();
  394. lattice.fColors = colors.get();
  395. } else {
  396. lattice.fRectTypes = nullptr;
  397. lattice.fColors = nullptr;
  398. }
  399. } while (!SkLatticeIter::Valid(desc.fWidth, desc.fHeight, lattice));
  400. SkRect dst;
  401. dst.fLeft = random->nextRangeScalar(-2000.5f, 1000.f);
  402. dst.fTop = random->nextRangeScalar(-2000.5f, 1000.f);
  403. dst.fRight = dst.fLeft + random->nextRangeScalar(0.5f, 1000.f);
  404. dst.fBottom = dst.fTop + random->nextRangeScalar(0.5f, 1000.f);
  405. std::unique_ptr<SkLatticeIter> iter(new SkLatticeIter(lattice, dst));
  406. SkMatrix viewMatrix = GrTest::TestMatrixPreservesRightAngles(random);
  407. auto csxf = GrTest::TestColorXform(random);
  408. GrSamplerState::Filter filter =
  409. random->nextBool() ? GrSamplerState::Filter::kNearest : GrSamplerState::Filter::kBilerp;
  410. return NonAALatticeOp::Make(context, std::move(paint), viewMatrix, std::move(proxy),
  411. std::move(csxf), filter, std::move(iter), dst);
  412. }
  413. #endif