SkScalerContext.cpp 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199
  1. /*
  2. * Copyright 2006 The Android Open Source Project
  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/SkPaint.h"
  8. #include "src/core/SkScalerContext.h"
  9. #include "include/core/SkFontMetrics.h"
  10. #include "include/core/SkMaskFilter.h"
  11. #include "include/core/SkPathEffect.h"
  12. #include "include/core/SkStrokeRec.h"
  13. #include "include/private/SkColorData.h"
  14. #include "include/private/SkTo.h"
  15. #include "src/core/SkAutoMalloc.h"
  16. #include "src/core/SkAutoPixmapStorage.h"
  17. #include "src/core/SkDescriptor.h"
  18. #include "src/core/SkDraw.h"
  19. #include "src/core/SkFontPriv.h"
  20. #include "src/core/SkGlyph.h"
  21. #include "src/core/SkMakeUnique.h"
  22. #include "src/core/SkMaskGamma.h"
  23. #include "src/core/SkPaintPriv.h"
  24. #include "src/core/SkPathPriv.h"
  25. #include "src/core/SkRasterClip.h"
  26. #include "src/core/SkReadBuffer.h"
  27. #include "src/core/SkRectPriv.h"
  28. #include "src/core/SkStroke.h"
  29. #include "src/core/SkSurfacePriv.h"
  30. #include "src/core/SkTextFormatParams.h"
  31. #include "src/core/SkWriteBuffer.h"
  32. #include "src/utils/SkMatrix22.h"
  33. #include <new>
  34. ///////////////////////////////////////////////////////////////////////////////
  35. #ifdef SK_DEBUG
  36. #define DUMP_RECx
  37. #endif
  38. SkScalerContextRec SkScalerContext::PreprocessRec(const SkTypeface& typeface,
  39. const SkScalerContextEffects& effects,
  40. const SkDescriptor& desc) {
  41. SkScalerContextRec rec =
  42. *static_cast<const SkScalerContextRec*>(desc.findEntry(kRec_SkDescriptorTag, nullptr));
  43. // Allow the typeface to adjust the rec.
  44. typeface.onFilterRec(&rec);
  45. if (effects.fMaskFilter) {
  46. // Pre-blend is not currently applied to filtered text.
  47. // The primary filter is blur, for which contrast makes no sense,
  48. // and for which the destination guess error is more visible.
  49. // Also, all existing users of blur have calibrated for linear.
  50. rec.ignorePreBlend();
  51. }
  52. SkColor lumColor = rec.getLuminanceColor();
  53. if (rec.fMaskFormat == SkMask::kA8_Format) {
  54. U8CPU lum = SkComputeLuminance(SkColorGetR(lumColor),
  55. SkColorGetG(lumColor),
  56. SkColorGetB(lumColor));
  57. lumColor = SkColorSetRGB(lum, lum, lum);
  58. }
  59. // TODO: remove CanonicalColor when we to fix up Chrome layout tests.
  60. rec.setLuminanceColor(lumColor);
  61. return rec;
  62. }
  63. SkScalerContext::SkScalerContext(sk_sp<SkTypeface> typeface, const SkScalerContextEffects& effects,
  64. const SkDescriptor* desc)
  65. : fRec(PreprocessRec(*typeface, effects, *desc))
  66. , fTypeface(std::move(typeface))
  67. , fPathEffect(sk_ref_sp(effects.fPathEffect))
  68. , fMaskFilter(sk_ref_sp(effects.fMaskFilter))
  69. // Initialize based on our settings. Subclasses can also force this.
  70. , fGenerateImageFromPath(fRec.fFrameWidth > 0 || fPathEffect != nullptr)
  71. , fPreBlend(fMaskFilter ? SkMaskGamma::PreBlend() : SkScalerContext::GetMaskPreBlend(fRec))
  72. {
  73. #ifdef DUMP_REC
  74. SkDebugf("SkScalerContext checksum %x count %d length %d\n",
  75. desc->getChecksum(), desc->getCount(), desc->getLength());
  76. SkDebugf("%s", fRec.dump().c_str());
  77. SkDebugf(" effects %x\n", desc->findEntry(kEffects_SkDescriptorTag, nullptr));
  78. #endif
  79. }
  80. SkScalerContext::~SkScalerContext() {}
  81. /**
  82. * In order to call cachedDeviceLuminance, cachedPaintLuminance, or
  83. * cachedMaskGamma the caller must hold the mask_gamma_cache_mutex and continue
  84. * to hold it until the returned pointer is refed or forgotten.
  85. */
  86. static SkMutex& mask_gamma_cache_mutex() {
  87. static SkMutex& mutex = *(new SkMutex);
  88. return mutex;
  89. }
  90. static SkMaskGamma* gLinearMaskGamma = nullptr;
  91. static SkMaskGamma* gMaskGamma = nullptr;
  92. static SkScalar gContrast = SK_ScalarMin;
  93. static SkScalar gPaintGamma = SK_ScalarMin;
  94. static SkScalar gDeviceGamma = SK_ScalarMin;
  95. /**
  96. * The caller must hold the mask_gamma_cache_mutex() and continue to hold it until
  97. * the returned SkMaskGamma pointer is refed or forgotten.
  98. */
  99. static const SkMaskGamma& cached_mask_gamma(SkScalar contrast, SkScalar paintGamma,
  100. SkScalar deviceGamma) {
  101. mask_gamma_cache_mutex().assertHeld();
  102. if (0 == contrast && SK_Scalar1 == paintGamma && SK_Scalar1 == deviceGamma) {
  103. if (nullptr == gLinearMaskGamma) {
  104. gLinearMaskGamma = new SkMaskGamma;
  105. }
  106. return *gLinearMaskGamma;
  107. }
  108. if (gContrast != contrast || gPaintGamma != paintGamma || gDeviceGamma != deviceGamma) {
  109. SkSafeUnref(gMaskGamma);
  110. gMaskGamma = new SkMaskGamma(contrast, paintGamma, deviceGamma);
  111. gContrast = contrast;
  112. gPaintGamma = paintGamma;
  113. gDeviceGamma = deviceGamma;
  114. }
  115. return *gMaskGamma;
  116. }
  117. /**
  118. * Expands fDeviceGamma, fPaintGamma, fContrast, and fLumBits into a mask pre-blend.
  119. */
  120. SkMaskGamma::PreBlend SkScalerContext::GetMaskPreBlend(const SkScalerContextRec& rec) {
  121. SkAutoMutexExclusive ama(mask_gamma_cache_mutex());
  122. const SkMaskGamma& maskGamma = cached_mask_gamma(rec.getContrast(),
  123. rec.getPaintGamma(),
  124. rec.getDeviceGamma());
  125. // TODO: remove CanonicalColor when we to fix up Chrome layout tests.
  126. return maskGamma.preBlend(rec.getLuminanceColor());
  127. }
  128. size_t SkScalerContext::GetGammaLUTSize(SkScalar contrast, SkScalar paintGamma,
  129. SkScalar deviceGamma, int* width, int* height) {
  130. SkAutoMutexExclusive ama(mask_gamma_cache_mutex());
  131. const SkMaskGamma& maskGamma = cached_mask_gamma(contrast,
  132. paintGamma,
  133. deviceGamma);
  134. maskGamma.getGammaTableDimensions(width, height);
  135. size_t size = (*width)*(*height)*sizeof(uint8_t);
  136. return size;
  137. }
  138. bool SkScalerContext::GetGammaLUTData(SkScalar contrast, SkScalar paintGamma, SkScalar deviceGamma,
  139. uint8_t* data) {
  140. SkAutoMutexExclusive ama(mask_gamma_cache_mutex());
  141. const SkMaskGamma& maskGamma = cached_mask_gamma(contrast,
  142. paintGamma,
  143. deviceGamma);
  144. const uint8_t* gammaTables = maskGamma.getGammaTables();
  145. if (!gammaTables) {
  146. return false;
  147. }
  148. int width, height;
  149. maskGamma.getGammaTableDimensions(&width, &height);
  150. size_t size = width*height * sizeof(uint8_t);
  151. memcpy(data, gammaTables, size);
  152. return true;
  153. }
  154. void SkScalerContext::getAdvance(SkGlyph* glyph) {
  155. if (generateAdvance(glyph)) {
  156. glyph->fMaskFormat = MASK_FORMAT_JUST_ADVANCE;
  157. } else {
  158. this->getMetrics(glyph);
  159. SkASSERT(glyph->fMaskFormat != MASK_FORMAT_UNKNOWN);
  160. }
  161. }
  162. void SkScalerContext::getMetrics(SkGlyph* glyph) {
  163. bool generatingImageFromPath = fGenerateImageFromPath;
  164. if (!generatingImageFromPath) {
  165. generateMetrics(glyph);
  166. SkASSERT(glyph->fMaskFormat != MASK_FORMAT_UNKNOWN);
  167. } else {
  168. SkPath devPath;
  169. generatingImageFromPath = this->internalGetPath(glyph->getPackedID(), &devPath);
  170. if (!generatingImageFromPath) {
  171. generateMetrics(glyph);
  172. SkASSERT(glyph->fMaskFormat != MASK_FORMAT_UNKNOWN);
  173. } else {
  174. uint8_t originMaskFormat = glyph->fMaskFormat;
  175. if (!generateAdvance(glyph)) {
  176. generateMetrics(glyph);
  177. }
  178. if (originMaskFormat != MASK_FORMAT_UNKNOWN) {
  179. glyph->fMaskFormat = originMaskFormat;
  180. } else {
  181. glyph->fMaskFormat = fRec.fMaskFormat;
  182. }
  183. // If we are going to create the mask, then we cannot keep the color
  184. if (SkMask::kARGB32_Format == glyph->fMaskFormat) {
  185. glyph->fMaskFormat = SkMask::kA8_Format;
  186. }
  187. const SkIRect ir = devPath.getBounds().roundOut();
  188. if (ir.isEmpty() || !SkRectPriv::Is16Bit(ir)) {
  189. goto SK_ERROR;
  190. }
  191. glyph->fLeft = ir.fLeft;
  192. glyph->fTop = ir.fTop;
  193. glyph->fWidth = SkToU16(ir.width());
  194. glyph->fHeight = SkToU16(ir.height());
  195. if (glyph->fWidth > 0) {
  196. switch (glyph->fMaskFormat) {
  197. case SkMask::kLCD16_Format:
  198. if (fRec.fFlags & SkScalerContext::kLCD_Vertical_Flag) {
  199. glyph->fHeight += 2;
  200. glyph->fTop -= 1;
  201. } else {
  202. glyph->fWidth += 2;
  203. glyph->fLeft -= 1;
  204. }
  205. break;
  206. default:
  207. break;
  208. }
  209. }
  210. }
  211. }
  212. // if either dimension is empty, zap the image bounds of the glyph
  213. if (0 == glyph->fWidth || 0 == glyph->fHeight) {
  214. glyph->fWidth = 0;
  215. glyph->fHeight = 0;
  216. glyph->fTop = 0;
  217. glyph->fLeft = 0;
  218. glyph->fMaskFormat = 0;
  219. return;
  220. }
  221. if (fMaskFilter) {
  222. SkMask src = glyph->mask(),
  223. dst;
  224. SkMatrix matrix;
  225. fRec.getMatrixFrom2x2(&matrix);
  226. src.fImage = nullptr; // only want the bounds from the filter
  227. if (as_MFB(fMaskFilter)->filterMask(&dst, src, matrix, nullptr)) {
  228. if (dst.fBounds.isEmpty() || !SkRectPriv::Is16Bit(dst.fBounds)) {
  229. goto SK_ERROR;
  230. }
  231. SkASSERT(dst.fImage == nullptr);
  232. glyph->fLeft = dst.fBounds.fLeft;
  233. glyph->fTop = dst.fBounds.fTop;
  234. glyph->fWidth = SkToU16(dst.fBounds.width());
  235. glyph->fHeight = SkToU16(dst.fBounds.height());
  236. glyph->fMaskFormat = dst.fFormat;
  237. }
  238. }
  239. return;
  240. SK_ERROR:
  241. // draw nothing 'cause we failed
  242. glyph->fLeft = 0;
  243. glyph->fTop = 0;
  244. glyph->fWidth = 0;
  245. glyph->fHeight = 0;
  246. // put a valid value here, in case it was earlier set to
  247. // MASK_FORMAT_JUST_ADVANCE
  248. glyph->fMaskFormat = fRec.fMaskFormat;
  249. }
  250. #define SK_SHOW_TEXT_BLIT_COVERAGE 0
  251. static void applyLUTToA8Mask(const SkMask& mask, const uint8_t* lut) {
  252. uint8_t* SK_RESTRICT dst = (uint8_t*)mask.fImage;
  253. unsigned rowBytes = mask.fRowBytes;
  254. for (int y = mask.fBounds.height() - 1; y >= 0; --y) {
  255. for (int x = mask.fBounds.width() - 1; x >= 0; --x) {
  256. dst[x] = lut[dst[x]];
  257. }
  258. dst += rowBytes;
  259. }
  260. }
  261. static void pack4xHToLCD16(const SkPixmap& src, const SkMask& dst,
  262. const SkMaskGamma::PreBlend& maskPreBlend,
  263. const bool doBGR, const bool doVert) {
  264. #define SAMPLES_PER_PIXEL 4
  265. #define LCD_PER_PIXEL 3
  266. SkASSERT(kAlpha_8_SkColorType == src.colorType());
  267. SkASSERT(SkMask::kLCD16_Format == dst.fFormat);
  268. // doVert in this function means swap x and y when writing to dst.
  269. if (doVert) {
  270. SkASSERT(src.width() == (dst.fBounds.height() - 2) * 4);
  271. SkASSERT(src.height() == dst.fBounds.width());
  272. } else {
  273. SkASSERT(src.width() == (dst.fBounds.width() - 2) * 4);
  274. SkASSERT(src.height() == dst.fBounds.height());
  275. }
  276. const int sample_width = src.width();
  277. const int height = src.height();
  278. uint16_t* dstImage = (uint16_t*)dst.fImage;
  279. size_t dstRB = dst.fRowBytes;
  280. // An N tap FIR is defined by
  281. // out[n] = coeff[0]*x[n] + coeff[1]*x[n-1] + ... + coeff[N]*x[n-N]
  282. // or
  283. // out[n] = sum(i, 0, N, coeff[i]*x[n-i])
  284. // The strategy is to use one FIR (different coefficients) for each of r, g, and b.
  285. // This means using every 4th FIR output value of each FIR and discarding the rest.
  286. // The FIRs are aligned, and the coefficients reach 5 samples to each side of their 'center'.
  287. // (For r and b this is technically incorrect, but the coeffs outside round to zero anyway.)
  288. // These are in some fixed point repesentation.
  289. // Adding up to more than one simulates ink spread.
  290. // For implementation reasons, these should never add up to more than two.
  291. // Coefficients determined by a gausian where 5 samples = 3 std deviations (0x110 'contrast').
  292. // Calculated using tools/generate_fir_coeff.py
  293. // With this one almost no fringing is ever seen, but it is imperceptibly blurry.
  294. // The lcd smoothed text is almost imperceptibly different from gray,
  295. // but is still sharper on small stems and small rounded corners than gray.
  296. // This also seems to be about as wide as one can get and only have a three pixel kernel.
  297. // TODO: calculate these at runtime so parameters can be adjusted (esp contrast).
  298. static const unsigned int coefficients[LCD_PER_PIXEL][SAMPLES_PER_PIXEL*3] = {
  299. //The red subpixel is centered inside the first sample (at 1/6 pixel), and is shifted.
  300. { 0x03, 0x0b, 0x1c, 0x33, 0x40, 0x39, 0x24, 0x10, 0x05, 0x01, 0x00, 0x00, },
  301. //The green subpixel is centered between two samples (at 1/2 pixel), so is symetric
  302. { 0x00, 0x02, 0x08, 0x16, 0x2b, 0x3d, 0x3d, 0x2b, 0x16, 0x08, 0x02, 0x00, },
  303. //The blue subpixel is centered inside the last sample (at 5/6 pixel), and is shifted.
  304. { 0x00, 0x00, 0x01, 0x05, 0x10, 0x24, 0x39, 0x40, 0x33, 0x1c, 0x0b, 0x03, },
  305. };
  306. for (int y = 0; y < height; ++y) {
  307. uint16_t* dstP;
  308. size_t dstPDelta;
  309. if (doVert) {
  310. dstP = dstImage + y;
  311. dstPDelta = dstRB;
  312. } else {
  313. dstP = SkTAddOffset<uint16_t>(dstImage, dstRB * y);
  314. dstPDelta = sizeof(uint16_t);
  315. }
  316. const uint8_t* srcP = src.addr8(0, y);
  317. // TODO: this fir filter implementation is straight forward, but slow.
  318. // It should be possible to make it much faster.
  319. for (int sample_x = -4; sample_x < sample_width + 4; sample_x += 4) {
  320. int fir[LCD_PER_PIXEL] = { 0 };
  321. for (int sample_index = SkMax32(0, sample_x - 4), coeff_index = sample_index - (sample_x - 4)
  322. ; sample_index < SkMin32(sample_x + 8, sample_width)
  323. ; ++sample_index, ++coeff_index)
  324. {
  325. int sample_value = srcP[sample_index];
  326. for (int subpxl_index = 0; subpxl_index < LCD_PER_PIXEL; ++subpxl_index) {
  327. fir[subpxl_index] += coefficients[subpxl_index][coeff_index] * sample_value;
  328. }
  329. }
  330. for (int subpxl_index = 0; subpxl_index < LCD_PER_PIXEL; ++subpxl_index) {
  331. fir[subpxl_index] /= 0x100;
  332. fir[subpxl_index] = SkMin32(fir[subpxl_index], 255);
  333. }
  334. U8CPU r, g, b;
  335. if (doBGR) {
  336. r = fir[2];
  337. g = fir[1];
  338. b = fir[0];
  339. } else {
  340. r = fir[0];
  341. g = fir[1];
  342. b = fir[2];
  343. }
  344. if (maskPreBlend.isApplicable()) {
  345. r = maskPreBlend.fR[r];
  346. g = maskPreBlend.fG[g];
  347. b = maskPreBlend.fB[b];
  348. }
  349. #if SK_SHOW_TEXT_BLIT_COVERAGE
  350. r = SkMax32(r, 10); g = SkMax32(g, 10); b = SkMax32(b, 10);
  351. #endif
  352. *dstP = SkPack888ToRGB16(r, g, b);
  353. dstP = SkTAddOffset<uint16_t>(dstP, dstPDelta);
  354. }
  355. }
  356. }
  357. static inline int convert_8_to_1(unsigned byte) {
  358. SkASSERT(byte <= 0xFF);
  359. return byte >> 7;
  360. }
  361. static uint8_t pack_8_to_1(const uint8_t alpha[8]) {
  362. unsigned bits = 0;
  363. for (int i = 0; i < 8; ++i) {
  364. bits <<= 1;
  365. bits |= convert_8_to_1(alpha[i]);
  366. }
  367. return SkToU8(bits);
  368. }
  369. static void packA8ToA1(const SkMask& mask, const uint8_t* src, size_t srcRB) {
  370. const int height = mask.fBounds.height();
  371. const int width = mask.fBounds.width();
  372. const int octs = width >> 3;
  373. const int leftOverBits = width & 7;
  374. uint8_t* dst = mask.fImage;
  375. const int dstPad = mask.fRowBytes - SkAlign8(width)/8;
  376. SkASSERT(dstPad >= 0);
  377. SkASSERT(width >= 0);
  378. SkASSERT(srcRB >= (size_t)width);
  379. const size_t srcPad = srcRB - width;
  380. for (int y = 0; y < height; ++y) {
  381. for (int i = 0; i < octs; ++i) {
  382. *dst++ = pack_8_to_1(src);
  383. src += 8;
  384. }
  385. if (leftOverBits > 0) {
  386. unsigned bits = 0;
  387. int shift = 7;
  388. for (int i = 0; i < leftOverBits; ++i, --shift) {
  389. bits |= convert_8_to_1(*src++) << shift;
  390. }
  391. *dst++ = bits;
  392. }
  393. src += srcPad;
  394. dst += dstPad;
  395. }
  396. }
  397. static void generateMask(const SkMask& mask, const SkPath& path,
  398. const SkMaskGamma::PreBlend& maskPreBlend,
  399. bool doBGR, bool doVert) {
  400. SkPaint paint;
  401. int srcW = mask.fBounds.width();
  402. int srcH = mask.fBounds.height();
  403. int dstW = srcW;
  404. int dstH = srcH;
  405. int dstRB = mask.fRowBytes;
  406. SkMatrix matrix;
  407. matrix.setTranslate(-SkIntToScalar(mask.fBounds.fLeft),
  408. -SkIntToScalar(mask.fBounds.fTop));
  409. paint.setAntiAlias(SkMask::kBW_Format != mask.fFormat);
  410. switch (mask.fFormat) {
  411. case SkMask::kBW_Format:
  412. dstRB = 0; // signals we need a copy
  413. break;
  414. case SkMask::kA8_Format:
  415. break;
  416. case SkMask::kLCD16_Format:
  417. if (doVert) {
  418. dstW = 4*dstH - 8;
  419. dstH = srcW;
  420. matrix.setAll(0, 4, -SkIntToScalar(mask.fBounds.fTop + 1) * 4,
  421. 1, 0, -SkIntToScalar(mask.fBounds.fLeft),
  422. 0, 0, 1);
  423. } else {
  424. dstW = 4*dstW - 8;
  425. matrix.setAll(4, 0, -SkIntToScalar(mask.fBounds.fLeft + 1) * 4,
  426. 0, 1, -SkIntToScalar(mask.fBounds.fTop),
  427. 0, 0, 1);
  428. }
  429. dstRB = 0; // signals we need a copy
  430. break;
  431. default:
  432. SkDEBUGFAIL("unexpected mask format");
  433. }
  434. SkRasterClip clip;
  435. clip.setRect(SkIRect::MakeWH(dstW, dstH));
  436. const SkImageInfo info = SkImageInfo::MakeA8(dstW, dstH);
  437. SkAutoPixmapStorage dst;
  438. if (0 == dstRB) {
  439. if (!dst.tryAlloc(info)) {
  440. // can't allocate offscreen, so empty the mask and return
  441. sk_bzero(mask.fImage, mask.computeImageSize());
  442. return;
  443. }
  444. } else {
  445. dst.reset(info, mask.fImage, dstRB);
  446. }
  447. sk_bzero(dst.writable_addr(), dst.computeByteSize());
  448. SkDraw draw;
  449. draw.fDst = dst;
  450. draw.fRC = &clip;
  451. draw.fMatrix = &matrix;
  452. draw.drawPath(path, paint);
  453. switch (mask.fFormat) {
  454. case SkMask::kBW_Format:
  455. packA8ToA1(mask, dst.addr8(0, 0), dst.rowBytes());
  456. break;
  457. case SkMask::kA8_Format:
  458. if (maskPreBlend.isApplicable()) {
  459. applyLUTToA8Mask(mask, maskPreBlend.fG);
  460. }
  461. break;
  462. case SkMask::kLCD16_Format:
  463. pack4xHToLCD16(dst, mask, maskPreBlend, doBGR, doVert);
  464. break;
  465. default:
  466. break;
  467. }
  468. }
  469. void SkScalerContext::getImage(const SkGlyph& origGlyph) {
  470. const SkGlyph* glyph = &origGlyph;
  471. SkGlyph tmpGlyph{origGlyph.getPackedID()};
  472. // in case we need to call generateImage on a mask-format that is different
  473. // (i.e. larger) than what our caller allocated by looking at origGlyph.
  474. SkAutoMalloc tmpGlyphImageStorage;
  475. if (fMaskFilter) { // restore the prefilter bounds
  476. // need the original bounds, sans our maskfilter
  477. sk_sp<SkMaskFilter> mf = std::move(fMaskFilter);
  478. this->getMetrics(&tmpGlyph);
  479. fMaskFilter = std::move(mf);
  480. // we need the prefilter bounds to be <= filter bounds
  481. SkASSERT(tmpGlyph.fWidth <= origGlyph.fWidth);
  482. SkASSERT(tmpGlyph.fHeight <= origGlyph.fHeight);
  483. if (tmpGlyph.fMaskFormat == origGlyph.fMaskFormat) {
  484. tmpGlyph.fImage = origGlyph.fImage;
  485. } else {
  486. tmpGlyphImageStorage.reset(tmpGlyph.imageSize());
  487. tmpGlyph.fImage = tmpGlyphImageStorage.get();
  488. }
  489. glyph = &tmpGlyph;
  490. }
  491. if (!fGenerateImageFromPath) {
  492. generateImage(*glyph);
  493. } else {
  494. SkPath devPath;
  495. SkMask mask = glyph->mask();
  496. if (!this->internalGetPath(glyph->getPackedID(), &devPath)) {
  497. generateImage(*glyph);
  498. } else {
  499. SkASSERT(SkMask::kARGB32_Format != origGlyph.fMaskFormat);
  500. SkASSERT(SkMask::kARGB32_Format != mask.fFormat);
  501. const bool doBGR = SkToBool(fRec.fFlags & SkScalerContext::kLCD_BGROrder_Flag);
  502. const bool doVert = SkToBool(fRec.fFlags & SkScalerContext::kLCD_Vertical_Flag);
  503. generateMask(mask, devPath, fPreBlend, doBGR, doVert);
  504. }
  505. }
  506. if (fMaskFilter) {
  507. // the src glyph image shouldn't be 3D
  508. SkASSERT(SkMask::k3D_Format != glyph->fMaskFormat);
  509. SkMask srcM = glyph->mask(),
  510. dstM;
  511. SkMatrix matrix;
  512. fRec.getMatrixFrom2x2(&matrix);
  513. if (as_MFB(fMaskFilter)->filterMask(&dstM, srcM, matrix, nullptr)) {
  514. int width = SkMin32(origGlyph.fWidth, dstM.fBounds.width());
  515. int height = SkMin32(origGlyph.fHeight, dstM.fBounds.height());
  516. int dstRB = origGlyph.rowBytes();
  517. int srcRB = dstM.fRowBytes;
  518. const uint8_t* src = (const uint8_t*)dstM.fImage;
  519. uint8_t* dst = (uint8_t*)origGlyph.fImage;
  520. if (SkMask::k3D_Format == dstM.fFormat) {
  521. // we have to copy 3 times as much
  522. height *= 3;
  523. }
  524. // clean out our glyph, since it may be larger than dstM
  525. //sk_bzero(dst, height * dstRB);
  526. while (--height >= 0) {
  527. memcpy(dst, src, width);
  528. src += srcRB;
  529. dst += dstRB;
  530. }
  531. SkMask::FreeImage(dstM.fImage);
  532. }
  533. }
  534. }
  535. bool SkScalerContext::getPath(SkPackedGlyphID glyphID, SkPath* path) {
  536. return this->internalGetPath(glyphID, path);
  537. }
  538. void SkScalerContext::getFontMetrics(SkFontMetrics* fm) {
  539. SkASSERT(fm);
  540. this->generateFontMetrics(fm);
  541. }
  542. ///////////////////////////////////////////////////////////////////////////////
  543. bool SkScalerContext::internalGetPath(SkPackedGlyphID glyphID, SkPath* devPath) {
  544. SkPath path;
  545. if (!generatePath(glyphID.code(), &path)) {
  546. return false;
  547. }
  548. if (fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) {
  549. SkFixed dx = glyphID.getSubXFixed();
  550. SkFixed dy = glyphID.getSubYFixed();
  551. if (dx | dy) {
  552. path.offset(SkFixedToScalar(dx), SkFixedToScalar(dy));
  553. }
  554. }
  555. if (fRec.fFrameWidth > 0 || fPathEffect != nullptr) {
  556. // need the path in user-space, with only the point-size applied
  557. // so that our stroking and effects will operate the same way they
  558. // would if the user had extracted the path themself, and then
  559. // called drawPath
  560. SkPath localPath;
  561. SkMatrix matrix, inverse;
  562. fRec.getMatrixFrom2x2(&matrix);
  563. if (!matrix.invert(&inverse)) {
  564. // assume devPath is already empty.
  565. return true;
  566. }
  567. path.transform(inverse, &localPath);
  568. // now localPath is only affected by the paint settings, and not the canvas matrix
  569. SkStrokeRec rec(SkStrokeRec::kFill_InitStyle);
  570. if (fRec.fFrameWidth > 0) {
  571. rec.setStrokeStyle(fRec.fFrameWidth,
  572. SkToBool(fRec.fFlags & kFrameAndFill_Flag));
  573. // glyphs are always closed contours, so cap type is ignored,
  574. // so we just pass something.
  575. rec.setStrokeParams((SkPaint::Cap)fRec.fStrokeCap,
  576. (SkPaint::Join)fRec.fStrokeJoin,
  577. fRec.fMiterLimit);
  578. }
  579. if (fPathEffect) {
  580. SkPath effectPath;
  581. if (fPathEffect->filterPath(&effectPath, localPath, &rec, nullptr)) {
  582. localPath.swap(effectPath);
  583. }
  584. }
  585. if (rec.needToApply()) {
  586. SkPath strokePath;
  587. if (rec.applyToPath(&strokePath, localPath)) {
  588. localPath.swap(strokePath);
  589. }
  590. }
  591. // now return stuff to the caller
  592. if (devPath) {
  593. localPath.transform(matrix, devPath);
  594. }
  595. } else { // nothing tricky to do
  596. if (devPath) {
  597. devPath->swap(path);
  598. }
  599. }
  600. if (devPath) {
  601. devPath->updateBoundsCache();
  602. }
  603. return true;
  604. }
  605. void SkScalerContextRec::getMatrixFrom2x2(SkMatrix* dst) const {
  606. dst->setAll(fPost2x2[0][0], fPost2x2[0][1], 0,
  607. fPost2x2[1][0], fPost2x2[1][1], 0,
  608. 0, 0, 1);
  609. }
  610. void SkScalerContextRec::getLocalMatrix(SkMatrix* m) const {
  611. *m = SkFontPriv::MakeTextMatrix(fTextSize, fPreScaleX, fPreSkewX);
  612. }
  613. void SkScalerContextRec::getSingleMatrix(SkMatrix* m) const {
  614. this->getLocalMatrix(m);
  615. // now concat the device matrix
  616. SkMatrix deviceMatrix;
  617. this->getMatrixFrom2x2(&deviceMatrix);
  618. m->postConcat(deviceMatrix);
  619. }
  620. bool SkScalerContextRec::computeMatrices(PreMatrixScale preMatrixScale, SkVector* s, SkMatrix* sA,
  621. SkMatrix* GsA, SkMatrix* G_inv, SkMatrix* A_out)
  622. {
  623. // A is the 'total' matrix.
  624. SkMatrix A;
  625. this->getSingleMatrix(&A);
  626. // The caller may find the 'total' matrix useful when dealing directly with EM sizes.
  627. if (A_out) {
  628. *A_out = A;
  629. }
  630. // GA is the matrix A with rotation removed.
  631. SkMatrix GA;
  632. bool skewedOrFlipped = A.getSkewX() || A.getSkewY() || A.getScaleX() < 0 || A.getScaleY() < 0;
  633. if (skewedOrFlipped) {
  634. // QR by Givens rotations. G is Q^T and GA is R. G is rotational (no reflections).
  635. // h is where A maps the horizontal baseline.
  636. SkPoint h = SkPoint::Make(SK_Scalar1, 0);
  637. A.mapPoints(&h, 1);
  638. // G is the Givens Matrix for A (rotational matrix where GA[0][1] == 0).
  639. SkMatrix G;
  640. SkComputeGivensRotation(h, &G);
  641. GA = G;
  642. GA.preConcat(A);
  643. // The 'remainingRotation' is G inverse, which is fairly simple since G is 2x2 rotational.
  644. if (G_inv) {
  645. G_inv->setAll(
  646. G.get(SkMatrix::kMScaleX), -G.get(SkMatrix::kMSkewX), G.get(SkMatrix::kMTransX),
  647. -G.get(SkMatrix::kMSkewY), G.get(SkMatrix::kMScaleY), G.get(SkMatrix::kMTransY),
  648. G.get(SkMatrix::kMPersp0), G.get(SkMatrix::kMPersp1), G.get(SkMatrix::kMPersp2));
  649. }
  650. } else {
  651. GA = A;
  652. if (G_inv) {
  653. G_inv->reset();
  654. }
  655. }
  656. // If the 'total' matrix is singular, set the 'scale' to something finite and zero the matrices.
  657. // All underlying ports have issues with zero text size, so use the matricies to zero.
  658. // If one of the scale factors is less than 1/256 then an EM filling square will
  659. // never affect any pixels.
  660. // If there are any nonfinite numbers in the matrix, bail out and set the matrices to zero.
  661. if (SkScalarAbs(GA.get(SkMatrix::kMScaleX)) <= SK_ScalarNearlyZero ||
  662. SkScalarAbs(GA.get(SkMatrix::kMScaleY)) <= SK_ScalarNearlyZero ||
  663. !GA.isFinite())
  664. {
  665. s->fX = SK_Scalar1;
  666. s->fY = SK_Scalar1;
  667. sA->setScale(0, 0);
  668. if (GsA) {
  669. GsA->setScale(0, 0);
  670. }
  671. if (G_inv) {
  672. G_inv->reset();
  673. }
  674. return false;
  675. }
  676. // At this point, given GA, create s.
  677. switch (preMatrixScale) {
  678. case kFull_PreMatrixScale:
  679. s->fX = SkScalarAbs(GA.get(SkMatrix::kMScaleX));
  680. s->fY = SkScalarAbs(GA.get(SkMatrix::kMScaleY));
  681. break;
  682. case kVertical_PreMatrixScale: {
  683. SkScalar yScale = SkScalarAbs(GA.get(SkMatrix::kMScaleY));
  684. s->fX = yScale;
  685. s->fY = yScale;
  686. break;
  687. }
  688. case kVerticalInteger_PreMatrixScale: {
  689. SkScalar realYScale = SkScalarAbs(GA.get(SkMatrix::kMScaleY));
  690. SkScalar intYScale = SkScalarRoundToScalar(realYScale);
  691. if (intYScale == 0) {
  692. intYScale = SK_Scalar1;
  693. }
  694. s->fX = intYScale;
  695. s->fY = intYScale;
  696. break;
  697. }
  698. }
  699. // The 'remaining' matrix sA is the total matrix A without the scale.
  700. if (!skewedOrFlipped && (
  701. (kFull_PreMatrixScale == preMatrixScale) ||
  702. (kVertical_PreMatrixScale == preMatrixScale && A.getScaleX() == A.getScaleY())))
  703. {
  704. // If GA == A and kFull_PreMatrixScale, sA is identity.
  705. // If GA == A and kVertical_PreMatrixScale and A.scaleX == A.scaleY, sA is identity.
  706. sA->reset();
  707. } else if (!skewedOrFlipped && kVertical_PreMatrixScale == preMatrixScale) {
  708. // If GA == A and kVertical_PreMatrixScale, sA.scaleY is SK_Scalar1.
  709. sA->reset();
  710. sA->setScaleX(A.getScaleX() / s->fY);
  711. } else {
  712. // TODO: like kVertical_PreMatrixScale, kVerticalInteger_PreMatrixScale with int scales.
  713. *sA = A;
  714. sA->preScale(SkScalarInvert(s->fX), SkScalarInvert(s->fY));
  715. }
  716. // The 'remainingWithoutRotation' matrix GsA is the non-rotational part of A without the scale.
  717. if (GsA) {
  718. *GsA = GA;
  719. // G is rotational so reorders with the scale.
  720. GsA->preScale(SkScalarInvert(s->fX), SkScalarInvert(s->fY));
  721. }
  722. return true;
  723. }
  724. SkAxisAlignment SkScalerContext::computeAxisAlignmentForHText() const {
  725. return fRec.computeAxisAlignmentForHText();
  726. }
  727. SkAxisAlignment SkScalerContextRec::computeAxisAlignmentForHText() const {
  728. // Why fPost2x2 can be used here.
  729. // getSingleMatrix multiplies in getLocalMatrix, which consists of
  730. // * fTextSize (a scale, which has no effect)
  731. // * fPreScaleX (a scale in x, which has no effect)
  732. // * fPreSkewX (has no effect, but would on vertical text alignment).
  733. // In other words, making the text bigger, stretching it along the
  734. // horizontal axis, or fake italicizing it does not move the baseline.
  735. if (0 == fPost2x2[1][0]) {
  736. // The x axis is mapped onto the x axis.
  737. return kX_SkAxisAlignment;
  738. }
  739. if (0 == fPost2x2[0][0]) {
  740. // The x axis is mapped onto the y axis.
  741. return kY_SkAxisAlignment;
  742. }
  743. return kNone_SkAxisAlignment;
  744. }
  745. void SkScalerContextRec::setLuminanceColor(SkColor c) {
  746. fLumBits = SkMaskGamma::CanonicalColor(
  747. SkColorSetRGB(SkColorGetR(c), SkColorGetG(c), SkColorGetB(c)));
  748. }
  749. ///////////////////////////////////////////////////////////////////////////////
  750. class SkScalerContext_Empty : public SkScalerContext {
  751. public:
  752. SkScalerContext_Empty(sk_sp<SkTypeface> typeface, const SkScalerContextEffects& effects,
  753. const SkDescriptor* desc)
  754. : SkScalerContext(std::move(typeface), effects, desc) {}
  755. protected:
  756. unsigned generateGlyphCount() override {
  757. return 0;
  758. }
  759. bool generateAdvance(SkGlyph* glyph) override {
  760. glyph->zeroMetrics();
  761. return true;
  762. }
  763. void generateMetrics(SkGlyph* glyph) override {
  764. glyph->fMaskFormat = fRec.fMaskFormat;
  765. glyph->zeroMetrics();
  766. }
  767. void generateImage(const SkGlyph& glyph) override {}
  768. bool generatePath(SkGlyphID glyph, SkPath* path) override {
  769. path->reset();
  770. return false;
  771. }
  772. void generateFontMetrics(SkFontMetrics* metrics) override {
  773. if (metrics) {
  774. sk_bzero(metrics, sizeof(*metrics));
  775. }
  776. }
  777. };
  778. extern SkScalerContext* SkCreateColorScalerContext(const SkDescriptor* desc);
  779. std::unique_ptr<SkScalerContext> SkTypeface::createScalerContext(
  780. const SkScalerContextEffects& effects, const SkDescriptor* desc, bool allowFailure) const
  781. {
  782. std::unique_ptr<SkScalerContext> c(this->onCreateScalerContext(effects, desc));
  783. if (!c && !allowFailure) {
  784. c = skstd::make_unique<SkScalerContext_Empty>(sk_ref_sp(const_cast<SkTypeface*>(this)),
  785. effects, desc);
  786. }
  787. // !allowFailure implies c != nullptr
  788. SkASSERT(c || allowFailure);
  789. return c;
  790. }
  791. /*
  792. * Return the scalar with only limited fractional precision. Used to consolidate matrices
  793. * that vary only slightly when we create our key into the font cache, since the font scaler
  794. * typically returns the same looking resuts for tiny changes in the matrix.
  795. */
  796. static SkScalar sk_relax(SkScalar x) {
  797. SkScalar n = SkScalarRoundToScalar(x * 1024);
  798. return n / 1024.0f;
  799. }
  800. static SkMask::Format compute_mask_format(const SkFont& font) {
  801. switch (font.getEdging()) {
  802. case SkFont::Edging::kAlias:
  803. return SkMask::kBW_Format;
  804. case SkFont::Edging::kAntiAlias:
  805. return SkMask::kA8_Format;
  806. case SkFont::Edging::kSubpixelAntiAlias:
  807. return SkMask::kLCD16_Format;
  808. }
  809. SkASSERT(false);
  810. return SkMask::kA8_Format;
  811. }
  812. // Beyond this size, LCD doesn't appreciably improve quality, but it always
  813. // cost more RAM and draws slower, so we set a cap.
  814. #ifndef SK_MAX_SIZE_FOR_LCDTEXT
  815. #define SK_MAX_SIZE_FOR_LCDTEXT 48
  816. #endif
  817. const SkScalar gMaxSize2ForLCDText = SK_MAX_SIZE_FOR_LCDTEXT * SK_MAX_SIZE_FOR_LCDTEXT;
  818. static bool too_big_for_lcd(const SkScalerContextRec& rec, bool checkPost2x2) {
  819. if (checkPost2x2) {
  820. SkScalar area = rec.fPost2x2[0][0] * rec.fPost2x2[1][1] -
  821. rec.fPost2x2[1][0] * rec.fPost2x2[0][1];
  822. area *= rec.fTextSize * rec.fTextSize;
  823. return area > gMaxSize2ForLCDText;
  824. } else {
  825. return rec.fTextSize > SK_MAX_SIZE_FOR_LCDTEXT;
  826. }
  827. }
  828. // The only reason this is not file static is because it needs the context of SkScalerContext to
  829. // access SkPaint::computeLuminanceColor.
  830. void SkScalerContext::MakeRecAndEffects(const SkFont& font, const SkPaint& paint,
  831. const SkSurfaceProps& surfaceProps,
  832. SkScalerContextFlags scalerContextFlags,
  833. const SkMatrix& deviceMatrix,
  834. SkScalerContextRec* rec,
  835. SkScalerContextEffects* effects) {
  836. SkASSERT(!deviceMatrix.hasPerspective());
  837. sk_bzero(rec, sizeof(SkScalerContextRec));
  838. SkTypeface* typeface = font.getTypefaceOrDefault();
  839. rec->fFontID = typeface->uniqueID();
  840. rec->fTextSize = font.getSize();
  841. rec->fPreScaleX = font.getScaleX();
  842. rec->fPreSkewX = font.getSkewX();
  843. bool checkPost2x2 = false;
  844. const SkMatrix::TypeMask mask = deviceMatrix.getType();
  845. if (mask & SkMatrix::kScale_Mask) {
  846. rec->fPost2x2[0][0] = sk_relax(deviceMatrix.getScaleX());
  847. rec->fPost2x2[1][1] = sk_relax(deviceMatrix.getScaleY());
  848. checkPost2x2 = true;
  849. } else {
  850. rec->fPost2x2[0][0] = rec->fPost2x2[1][1] = SK_Scalar1;
  851. }
  852. if (mask & SkMatrix::kAffine_Mask) {
  853. rec->fPost2x2[0][1] = sk_relax(deviceMatrix.getSkewX());
  854. rec->fPost2x2[1][0] = sk_relax(deviceMatrix.getSkewY());
  855. checkPost2x2 = true;
  856. } else {
  857. rec->fPost2x2[0][1] = rec->fPost2x2[1][0] = 0;
  858. }
  859. SkPaint::Style style = paint.getStyle();
  860. SkScalar strokeWidth = paint.getStrokeWidth();
  861. unsigned flags = 0;
  862. if (font.isEmbolden()) {
  863. #ifdef SK_USE_FREETYPE_EMBOLDEN
  864. flags |= SkScalerContext::kEmbolden_Flag;
  865. #else
  866. SkScalar fakeBoldScale = SkScalarInterpFunc(font.getSize(),
  867. kStdFakeBoldInterpKeys,
  868. kStdFakeBoldInterpValues,
  869. kStdFakeBoldInterpLength);
  870. SkScalar extra = font.getSize() * fakeBoldScale;
  871. if (style == SkPaint::kFill_Style) {
  872. style = SkPaint::kStrokeAndFill_Style;
  873. strokeWidth = extra; // ignore paint's strokeWidth if it was "fill"
  874. } else {
  875. strokeWidth += extra;
  876. }
  877. #endif
  878. }
  879. if (style != SkPaint::kFill_Style && strokeWidth > 0) {
  880. rec->fFrameWidth = strokeWidth;
  881. rec->fMiterLimit = paint.getStrokeMiter();
  882. rec->fStrokeJoin = SkToU8(paint.getStrokeJoin());
  883. rec->fStrokeCap = SkToU8(paint.getStrokeCap());
  884. if (style == SkPaint::kStrokeAndFill_Style) {
  885. flags |= SkScalerContext::kFrameAndFill_Flag;
  886. }
  887. } else {
  888. rec->fFrameWidth = 0;
  889. rec->fMiterLimit = 0;
  890. rec->fStrokeJoin = 0;
  891. rec->fStrokeCap = 0;
  892. }
  893. rec->fMaskFormat = SkToU8(compute_mask_format(font));
  894. if (SkMask::kLCD16_Format == rec->fMaskFormat) {
  895. if (too_big_for_lcd(*rec, checkPost2x2)) {
  896. rec->fMaskFormat = SkMask::kA8_Format;
  897. flags |= SkScalerContext::kGenA8FromLCD_Flag;
  898. } else {
  899. SkPixelGeometry geometry = surfaceProps.pixelGeometry();
  900. switch (geometry) {
  901. case kUnknown_SkPixelGeometry:
  902. // eeek, can't support LCD
  903. rec->fMaskFormat = SkMask::kA8_Format;
  904. flags |= SkScalerContext::kGenA8FromLCD_Flag;
  905. break;
  906. case kRGB_H_SkPixelGeometry:
  907. // our default, do nothing.
  908. break;
  909. case kBGR_H_SkPixelGeometry:
  910. flags |= SkScalerContext::kLCD_BGROrder_Flag;
  911. break;
  912. case kRGB_V_SkPixelGeometry:
  913. flags |= SkScalerContext::kLCD_Vertical_Flag;
  914. break;
  915. case kBGR_V_SkPixelGeometry:
  916. flags |= SkScalerContext::kLCD_Vertical_Flag;
  917. flags |= SkScalerContext::kLCD_BGROrder_Flag;
  918. break;
  919. }
  920. }
  921. }
  922. if (font.isEmbeddedBitmaps()) {
  923. flags |= SkScalerContext::kEmbeddedBitmapText_Flag;
  924. }
  925. if (font.isSubpixel()) {
  926. flags |= SkScalerContext::kSubpixelPositioning_Flag;
  927. }
  928. if (font.isForceAutoHinting()) {
  929. flags |= SkScalerContext::kForceAutohinting_Flag;
  930. }
  931. if (font.isLinearMetrics()) {
  932. flags |= SkScalerContext::kLinearMetrics_Flag;
  933. }
  934. rec->fFlags = SkToU16(flags);
  935. // these modify fFlags, so do them after assigning fFlags
  936. rec->setHinting(font.getHinting());
  937. rec->setLuminanceColor(SkPaintPriv::ComputeLuminanceColor(paint));
  938. // For now always set the paint gamma equal to the device gamma.
  939. // The math in SkMaskGamma can handle them being different,
  940. // but it requires superluminous masks when
  941. // Ex : deviceGamma(x) < paintGamma(x) and x is sufficiently large.
  942. rec->setDeviceGamma(SK_GAMMA_EXPONENT);
  943. rec->setPaintGamma(SK_GAMMA_EXPONENT);
  944. #ifdef SK_GAMMA_CONTRAST
  945. rec->setContrast(SK_GAMMA_CONTRAST);
  946. #else
  947. // A value of 0.5 for SK_GAMMA_CONTRAST appears to be a good compromise.
  948. // With lower values small text appears washed out (though correctly so).
  949. // With higher values lcd fringing is worse and the smoothing effect of
  950. // partial coverage is diminished.
  951. rec->setContrast(0.5f);
  952. #endif
  953. if (!SkToBool(scalerContextFlags & SkScalerContextFlags::kFakeGamma)) {
  954. rec->ignoreGamma();
  955. }
  956. if (!SkToBool(scalerContextFlags & SkScalerContextFlags::kBoostContrast)) {
  957. rec->setContrast(0);
  958. }
  959. new (effects) SkScalerContextEffects{paint};
  960. }
  961. SkDescriptor* SkScalerContext::MakeDescriptorForPaths(SkFontID typefaceID,
  962. SkAutoDescriptor* ad) {
  963. SkScalerContextRec rec;
  964. memset(&rec, 0, sizeof(rec));
  965. rec.fFontID = typefaceID;
  966. rec.fTextSize = SkFontPriv::kCanonicalTextSizeForPaths;
  967. rec.fPreScaleX = rec.fPost2x2[0][0] = rec.fPost2x2[1][1] = SK_Scalar1;
  968. return AutoDescriptorGivenRecAndEffects(rec, SkScalerContextEffects(), ad);
  969. }
  970. SkDescriptor* SkScalerContext::CreateDescriptorAndEffectsUsingPaint(
  971. const SkFont& font, const SkPaint& paint, const SkSurfaceProps& surfaceProps,
  972. SkScalerContextFlags scalerContextFlags, const SkMatrix& deviceMatrix, SkAutoDescriptor* ad,
  973. SkScalerContextEffects* effects)
  974. {
  975. SkScalerContextRec rec;
  976. MakeRecAndEffects(font, paint, surfaceProps, scalerContextFlags, deviceMatrix, &rec, effects);
  977. return AutoDescriptorGivenRecAndEffects(rec, *effects, ad);
  978. }
  979. static size_t calculate_size_and_flatten(const SkScalerContextRec& rec,
  980. const SkScalerContextEffects& effects,
  981. SkBinaryWriteBuffer* effectBuffer) {
  982. size_t descSize = sizeof(rec);
  983. int entryCount = 1;
  984. if (effects.fPathEffect || effects.fMaskFilter) {
  985. if (effects.fPathEffect) { effectBuffer->writeFlattenable(effects.fPathEffect); }
  986. if (effects.fMaskFilter) { effectBuffer->writeFlattenable(effects.fMaskFilter); }
  987. entryCount += 1;
  988. descSize += effectBuffer->bytesWritten();
  989. }
  990. descSize += SkDescriptor::ComputeOverhead(entryCount);
  991. return descSize;
  992. }
  993. static void generate_descriptor(const SkScalerContextRec& rec,
  994. const SkBinaryWriteBuffer& effectBuffer,
  995. SkDescriptor* desc) {
  996. desc->init();
  997. desc->addEntry(kRec_SkDescriptorTag, sizeof(rec), &rec);
  998. if (effectBuffer.bytesWritten() > 0) {
  999. effectBuffer.writeToMemory(desc->addEntry(kEffects_SkDescriptorTag,
  1000. effectBuffer.bytesWritten(),
  1001. nullptr));
  1002. }
  1003. desc->computeChecksum();
  1004. }
  1005. SkDescriptor* SkScalerContext::AutoDescriptorGivenRecAndEffects(
  1006. const SkScalerContextRec& rec,
  1007. const SkScalerContextEffects& effects,
  1008. SkAutoDescriptor* ad)
  1009. {
  1010. SkBinaryWriteBuffer buf;
  1011. ad->reset(calculate_size_and_flatten(rec, effects, &buf));
  1012. generate_descriptor(rec, buf, ad->getDesc());
  1013. return ad->getDesc();
  1014. }
  1015. std::unique_ptr<SkDescriptor> SkScalerContext::DescriptorGivenRecAndEffects(
  1016. const SkScalerContextRec& rec,
  1017. const SkScalerContextEffects& effects)
  1018. {
  1019. SkBinaryWriteBuffer buf;
  1020. auto desc = SkDescriptor::Alloc(calculate_size_and_flatten(rec, effects, &buf));
  1021. generate_descriptor(rec, buf, desc.get());
  1022. return desc;
  1023. }
  1024. void SkScalerContext::DescriptorBufferGiveRec(const SkScalerContextRec& rec, void* buffer) {
  1025. generate_descriptor(rec, SkBinaryWriteBuffer{}, (SkDescriptor*)buffer);
  1026. }
  1027. bool SkScalerContext::CheckBufferSizeForRec(const SkScalerContextRec& rec,
  1028. const SkScalerContextEffects& effects,
  1029. size_t size) {
  1030. SkBinaryWriteBuffer buf;
  1031. return size >= calculate_size_and_flatten(rec, effects, &buf);
  1032. }