Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2742 lines
103KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2022 - Raw Material Software Limited
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 7 End-User License
  8. Agreement and JUCE Privacy Policy.
  9. End User License Agreement: www.juce.com/juce-7-licence
  10. Privacy Policy: www.juce.com/juce-privacy-policy
  11. Or: You may also use this code under the terms of the GPL v3 (see
  12. www.gnu.org/licenses).
  13. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  14. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  15. DISCLAIMED.
  16. ==============================================================================
  17. */
  18. namespace juce
  19. {
  20. JUCE_BEGIN_IGNORE_WARNINGS_MSVC (4127)
  21. namespace RenderingHelpers
  22. {
  23. //==============================================================================
  24. /** Holds either a simple integer translation, or an affine transform.
  25. @tags{Graphics}
  26. */
  27. class TranslationOrTransform
  28. {
  29. public:
  30. TranslationOrTransform() = default;
  31. TranslationOrTransform (Point<int> origin) noexcept : offset (origin) {}
  32. TranslationOrTransform (const TranslationOrTransform& other) = default;
  33. AffineTransform getTransform() const noexcept
  34. {
  35. return isOnlyTranslated ? AffineTransform::translation (offset)
  36. : complexTransform;
  37. }
  38. AffineTransform getTransformWith (const AffineTransform& userTransform) const noexcept
  39. {
  40. return isOnlyTranslated ? userTransform.translated (offset)
  41. : userTransform.followedBy (complexTransform);
  42. }
  43. bool isIdentity() const noexcept
  44. {
  45. return isOnlyTranslated && offset.isOrigin();
  46. }
  47. void setOrigin (Point<int> delta) noexcept
  48. {
  49. if (isOnlyTranslated)
  50. offset += delta;
  51. else
  52. complexTransform = AffineTransform::translation (delta)
  53. .followedBy (complexTransform);
  54. }
  55. void addTransform (const AffineTransform& t) noexcept
  56. {
  57. if (isOnlyTranslated && t.isOnlyTranslation())
  58. {
  59. auto tx = (int) (t.getTranslationX() * 256.0f);
  60. auto ty = (int) (t.getTranslationY() * 256.0f);
  61. if (((tx | ty) & 0xf8) == 0)
  62. {
  63. offset += Point<int> (tx >> 8, ty >> 8);
  64. return;
  65. }
  66. }
  67. complexTransform = getTransformWith (t);
  68. isOnlyTranslated = false;
  69. isRotated = (complexTransform.mat01 != 0.0f || complexTransform.mat10 != 0.0f
  70. || complexTransform.mat00 < 0 || complexTransform.mat11 < 0);
  71. }
  72. float getPhysicalPixelScaleFactor() const noexcept
  73. {
  74. return isOnlyTranslated ? 1.0f : std::sqrt (std::abs (complexTransform.getDeterminant()));
  75. }
  76. void moveOriginInDeviceSpace (Point<int> delta) noexcept
  77. {
  78. if (isOnlyTranslated)
  79. offset += delta;
  80. else
  81. complexTransform = complexTransform.translated (delta);
  82. }
  83. Rectangle<int> translated (Rectangle<int> r) const noexcept
  84. {
  85. jassert (isOnlyTranslated);
  86. return r + offset;
  87. }
  88. Rectangle<float> translated (Rectangle<float> r) const noexcept
  89. {
  90. jassert (isOnlyTranslated);
  91. return r + offset.toFloat();
  92. }
  93. template <typename RectangleOrPoint>
  94. RectangleOrPoint transformed (RectangleOrPoint r) const noexcept
  95. {
  96. jassert (! isOnlyTranslated);
  97. return r.transformedBy (complexTransform);
  98. }
  99. template <typename Type>
  100. Rectangle<Type> deviceSpaceToUserSpace (Rectangle<Type> r) const noexcept
  101. {
  102. return isOnlyTranslated ? r - offset
  103. : r.transformedBy (complexTransform.inverted());
  104. }
  105. AffineTransform complexTransform;
  106. Point<int> offset;
  107. bool isOnlyTranslated = true, isRotated = false;
  108. };
  109. //==============================================================================
  110. /** Holds a cache of recently-used glyph objects of some type.
  111. @tags{Graphics}
  112. */
  113. template <class CachedGlyphType, class RenderTargetType>
  114. class GlyphCache : private DeletedAtShutdown
  115. {
  116. public:
  117. GlyphCache()
  118. {
  119. reset();
  120. }
  121. ~GlyphCache() override
  122. {
  123. getSingletonPointer() = nullptr;
  124. }
  125. static GlyphCache& getInstance()
  126. {
  127. auto& g = getSingletonPointer();
  128. if (g == nullptr)
  129. g = new GlyphCache();
  130. return *g;
  131. }
  132. //==============================================================================
  133. void reset()
  134. {
  135. const ScopedLock sl (lock);
  136. glyphs.clear();
  137. addNewGlyphSlots (120);
  138. hits = 0;
  139. misses = 0;
  140. }
  141. void drawGlyph (RenderTargetType& target, const Font& font, const int glyphNumber, Point<float> pos)
  142. {
  143. if (auto glyph = findOrCreateGlyph (font, glyphNumber))
  144. {
  145. glyph->lastAccessCount = ++accessCounter;
  146. glyph->draw (target, pos);
  147. }
  148. }
  149. ReferenceCountedObjectPtr<CachedGlyphType> findOrCreateGlyph (const Font& font, int glyphNumber)
  150. {
  151. const ScopedLock sl (lock);
  152. if (auto g = findExistingGlyph (font, glyphNumber))
  153. {
  154. ++hits;
  155. return g;
  156. }
  157. ++misses;
  158. auto g = getGlyphForReuse();
  159. jassert (g != nullptr);
  160. g->generate (font, glyphNumber);
  161. return g;
  162. }
  163. private:
  164. ReferenceCountedArray<CachedGlyphType> glyphs;
  165. Atomic<int> accessCounter, hits, misses;
  166. CriticalSection lock;
  167. ReferenceCountedObjectPtr<CachedGlyphType> findExistingGlyph (const Font& font, int glyphNumber) const noexcept
  168. {
  169. for (auto g : glyphs)
  170. if (g->glyph == glyphNumber && g->font == font)
  171. return *g;
  172. return {};
  173. }
  174. ReferenceCountedObjectPtr<CachedGlyphType> getGlyphForReuse()
  175. {
  176. if (hits.get() + misses.get() > glyphs.size() * 16)
  177. {
  178. if (misses.get() * 2 > hits.get())
  179. addNewGlyphSlots (32);
  180. hits = 0;
  181. misses = 0;
  182. }
  183. if (auto g = findLeastRecentlyUsedGlyph())
  184. return *g;
  185. addNewGlyphSlots (32);
  186. return glyphs.getLast();
  187. }
  188. void addNewGlyphSlots (int num)
  189. {
  190. glyphs.ensureStorageAllocated (glyphs.size() + num);
  191. while (--num >= 0)
  192. glyphs.add (new CachedGlyphType());
  193. }
  194. CachedGlyphType* findLeastRecentlyUsedGlyph() const noexcept
  195. {
  196. CachedGlyphType* oldest = nullptr;
  197. auto oldestCounter = std::numeric_limits<int>::max();
  198. for (auto* g : glyphs)
  199. {
  200. if (g->lastAccessCount <= oldestCounter
  201. && g->getReferenceCount() == 1)
  202. {
  203. oldestCounter = g->lastAccessCount;
  204. oldest = g;
  205. }
  206. }
  207. return oldest;
  208. }
  209. static GlyphCache*& getSingletonPointer() noexcept
  210. {
  211. static GlyphCache* g = nullptr;
  212. return g;
  213. }
  214. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GlyphCache)
  215. };
  216. //==============================================================================
  217. /** Caches a glyph as an edge-table.
  218. @tags{Graphics}
  219. */
  220. template <class RendererType>
  221. class CachedGlyphEdgeTable : public ReferenceCountedObject
  222. {
  223. public:
  224. CachedGlyphEdgeTable() = default;
  225. void draw (RendererType& state, Point<float> pos) const
  226. {
  227. if (snapToIntegerCoordinate)
  228. pos.x = std::floor (pos.x + 0.5f);
  229. if (edgeTable != nullptr)
  230. state.fillEdgeTable (*edgeTable, pos.x, roundToInt (pos.y));
  231. }
  232. void generate (const Font& newFont, int glyphNumber)
  233. {
  234. font = newFont;
  235. auto typeface = newFont.getTypefacePtr();
  236. snapToIntegerCoordinate = typeface->isHinted();
  237. glyph = glyphNumber;
  238. auto fontHeight = font.getHeight();
  239. edgeTable.reset (typeface->getEdgeTableForGlyph (glyphNumber,
  240. AffineTransform::scale (fontHeight * font.getHorizontalScale(),
  241. fontHeight), fontHeight));
  242. }
  243. Font font;
  244. std::unique_ptr<EdgeTable> edgeTable;
  245. int glyph = 0, lastAccessCount = 0;
  246. bool snapToIntegerCoordinate = false;
  247. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CachedGlyphEdgeTable)
  248. };
  249. //==============================================================================
  250. /** Calculates the alpha values and positions for rendering the edges of a
  251. non-pixel-aligned rectangle.
  252. @tags{Graphics}
  253. */
  254. struct FloatRectangleRasterisingInfo
  255. {
  256. FloatRectangleRasterisingInfo (Rectangle<float> area)
  257. : left (roundToInt (256.0f * area.getX())),
  258. top (roundToInt (256.0f * area.getY())),
  259. right (roundToInt (256.0f * area.getRight())),
  260. bottom (roundToInt (256.0f * area.getBottom()))
  261. {
  262. if ((top >> 8) == (bottom >> 8))
  263. {
  264. topAlpha = bottom - top;
  265. bottomAlpha = 0;
  266. totalTop = top >> 8;
  267. totalBottom = bottom = top = totalTop + 1;
  268. }
  269. else
  270. {
  271. if ((top & 255) == 0)
  272. {
  273. topAlpha = 0;
  274. top = totalTop = (top >> 8);
  275. }
  276. else
  277. {
  278. topAlpha = 255 - (top & 255);
  279. totalTop = (top >> 8);
  280. top = totalTop + 1;
  281. }
  282. bottomAlpha = bottom & 255;
  283. bottom >>= 8;
  284. totalBottom = bottom + (bottomAlpha != 0 ? 1 : 0);
  285. }
  286. if ((left >> 8) == (right >> 8))
  287. {
  288. leftAlpha = right - left;
  289. rightAlpha = 0;
  290. totalLeft = (left >> 8);
  291. totalRight = right = left = totalLeft + 1;
  292. }
  293. else
  294. {
  295. if ((left & 255) == 0)
  296. {
  297. leftAlpha = 0;
  298. left = totalLeft = (left >> 8);
  299. }
  300. else
  301. {
  302. leftAlpha = 255 - (left & 255);
  303. totalLeft = (left >> 8);
  304. left = totalLeft + 1;
  305. }
  306. rightAlpha = right & 255;
  307. right >>= 8;
  308. totalRight = right + (rightAlpha != 0 ? 1 : 0);
  309. }
  310. }
  311. template <class Callback>
  312. void iterate (Callback& callback) const
  313. {
  314. if (topAlpha != 0) callback (totalLeft, totalTop, totalRight - totalLeft, 1, topAlpha);
  315. if (bottomAlpha != 0) callback (totalLeft, bottom, totalRight - totalLeft, 1, bottomAlpha);
  316. if (leftAlpha != 0) callback (totalLeft, totalTop, 1, totalBottom - totalTop, leftAlpha);
  317. if (rightAlpha != 0) callback (right, totalTop, 1, totalBottom - totalTop, rightAlpha);
  318. callback (left, top, right - left, bottom - top, 255);
  319. }
  320. inline bool isOnePixelWide() const noexcept { return right - left == 1 && leftAlpha + rightAlpha == 0; }
  321. inline int getTopLeftCornerAlpha() const noexcept { return (topAlpha * leftAlpha) >> 8; }
  322. inline int getTopRightCornerAlpha() const noexcept { return (topAlpha * rightAlpha) >> 8; }
  323. inline int getBottomLeftCornerAlpha() const noexcept { return (bottomAlpha * leftAlpha) >> 8; }
  324. inline int getBottomRightCornerAlpha() const noexcept { return (bottomAlpha * rightAlpha) >> 8; }
  325. //==============================================================================
  326. int left, top, right, bottom; // bounds of the solid central area, excluding anti-aliased edges
  327. int totalTop, totalLeft, totalBottom, totalRight; // bounds of the total area, including edges
  328. int topAlpha, leftAlpha, bottomAlpha, rightAlpha; // alpha of each anti-aliased edge
  329. };
  330. //==============================================================================
  331. /** Contains classes for calculating the colour of pixels within various types of gradient. */
  332. namespace GradientPixelIterators
  333. {
  334. /** Iterates the colour of pixels in a linear gradient */
  335. struct Linear
  336. {
  337. Linear (const ColourGradient& gradient, const AffineTransform& transform,
  338. const PixelARGB* colours, int numColours)
  339. : lookupTable (colours),
  340. numEntries (numColours)
  341. {
  342. jassert (numColours >= 0);
  343. auto p1 = gradient.point1;
  344. auto p2 = gradient.point2;
  345. if (! transform.isIdentity())
  346. {
  347. auto p3 = Line<float> (p2, p1).getPointAlongLine (0.0f, 100.0f);
  348. p1.applyTransform (transform);
  349. p2.applyTransform (transform);
  350. p3.applyTransform (transform);
  351. p2 = Line<float> (p2, p3).findNearestPointTo (p1);
  352. }
  353. vertical = std::abs (p1.x - p2.x) < 0.001f;
  354. horizontal = std::abs (p1.y - p2.y) < 0.001f;
  355. if (vertical)
  356. {
  357. scale = roundToInt ((double) ((int64_t) numEntries << (int) numScaleBits) / (double) (p2.y - p1.y));
  358. start = roundToInt (p1.y * (float) scale);
  359. }
  360. else if (horizontal)
  361. {
  362. scale = roundToInt ((double) ((int64_t) numEntries << (int) numScaleBits) / (double) (p2.x - p1.x));
  363. start = roundToInt (p1.x * (float) scale);
  364. }
  365. else
  366. {
  367. grad = (p2.getY() - p1.y) / (double) (p1.x - p2.x);
  368. yTerm = p1.getY() - p1.x / grad;
  369. scale = roundToInt ((double) ((int64_t) numEntries << (int) numScaleBits) / (yTerm * grad - (p2.y * grad - p2.x)));
  370. grad *= scale;
  371. }
  372. }
  373. forcedinline void setY (int y) noexcept
  374. {
  375. if (vertical)
  376. linePix = lookupTable[jlimit (0, numEntries, (y * scale - start) >> (int) numScaleBits)];
  377. else if (! horizontal)
  378. start = roundToInt ((y - yTerm) * grad);
  379. }
  380. inline PixelARGB getPixel (int x) const noexcept
  381. {
  382. return vertical ? linePix
  383. : lookupTable[jlimit (0, numEntries, (x * scale - start) >> (int) numScaleBits)];
  384. }
  385. const PixelARGB* const lookupTable;
  386. const int numEntries;
  387. PixelARGB linePix;
  388. int start, scale;
  389. double grad, yTerm;
  390. bool vertical, horizontal;
  391. enum { numScaleBits = 12 };
  392. JUCE_DECLARE_NON_COPYABLE (Linear)
  393. };
  394. //==============================================================================
  395. /** Iterates the colour of pixels in a circular radial gradient */
  396. struct Radial
  397. {
  398. Radial (const ColourGradient& gradient, const AffineTransform&,
  399. const PixelARGB* colours, int numColours)
  400. : lookupTable (colours),
  401. numEntries (numColours),
  402. gx1 (gradient.point1.x),
  403. gy1 (gradient.point1.y)
  404. {
  405. jassert (numColours >= 0);
  406. auto diff = gradient.point1 - gradient.point2;
  407. maxDist = diff.x * diff.x + diff.y * diff.y;
  408. invScale = numEntries / std::sqrt (maxDist);
  409. jassert (roundToInt (std::sqrt (maxDist) * invScale) <= numEntries);
  410. }
  411. forcedinline void setY (int y) noexcept
  412. {
  413. dy = y - gy1;
  414. dy *= dy;
  415. }
  416. inline PixelARGB getPixel (int px) const noexcept
  417. {
  418. auto x = px - gx1;
  419. x *= x;
  420. x += dy;
  421. return lookupTable[x >= maxDist ? numEntries : roundToInt (std::sqrt (x) * invScale)];
  422. }
  423. const PixelARGB* const lookupTable;
  424. const int numEntries;
  425. const double gx1, gy1;
  426. double maxDist, invScale, dy;
  427. JUCE_DECLARE_NON_COPYABLE (Radial)
  428. };
  429. //==============================================================================
  430. /** Iterates the colour of pixels in a skewed radial gradient */
  431. struct TransformedRadial : public Radial
  432. {
  433. TransformedRadial (const ColourGradient& gradient, const AffineTransform& transform,
  434. const PixelARGB* colours, int numColours)
  435. : Radial (gradient, transform, colours, numColours),
  436. inverseTransform (transform.inverted())
  437. {
  438. tM10 = inverseTransform.mat10;
  439. tM00 = inverseTransform.mat00;
  440. }
  441. forcedinline void setY (int y) noexcept
  442. {
  443. auto floatY = (float) y;
  444. lineYM01 = inverseTransform.mat01 * floatY + inverseTransform.mat02 - gx1;
  445. lineYM11 = inverseTransform.mat11 * floatY + inverseTransform.mat12 - gy1;
  446. }
  447. inline PixelARGB getPixel (int px) const noexcept
  448. {
  449. double x = px;
  450. auto y = tM10 * x + lineYM11;
  451. x = tM00 * x + lineYM01;
  452. x *= x;
  453. x += y * y;
  454. if (x >= maxDist)
  455. return lookupTable[numEntries];
  456. return lookupTable[jmin (numEntries, roundToInt (std::sqrt (x) * invScale))];
  457. }
  458. private:
  459. double tM10, tM00, lineYM01, lineYM11;
  460. const AffineTransform inverseTransform;
  461. JUCE_DECLARE_NON_COPYABLE (TransformedRadial)
  462. };
  463. }
  464. #define JUCE_PERFORM_PIXEL_OP_LOOP(op) \
  465. { \
  466. const int destStride = destData.pixelStride; \
  467. do { dest->op; dest = addBytesToPointer (dest, destStride); } while (--width > 0); \
  468. }
  469. //==============================================================================
  470. /** Contains classes for filling edge tables with various fill types. */
  471. namespace EdgeTableFillers
  472. {
  473. /** Fills an edge-table with a solid colour. */
  474. template <class PixelType, bool replaceExisting = false>
  475. struct SolidColour
  476. {
  477. SolidColour (const Image::BitmapData& image, PixelARGB colour)
  478. : destData (image), sourceColour (colour)
  479. {
  480. if (sizeof (PixelType) == 3 && (size_t) destData.pixelStride == sizeof (PixelType))
  481. areRGBComponentsEqual = sourceColour.getRed() == sourceColour.getGreen()
  482. && sourceColour.getGreen() == sourceColour.getBlue();
  483. else
  484. areRGBComponentsEqual = false;
  485. }
  486. forcedinline void setEdgeTableYPos (int y) noexcept
  487. {
  488. linePixels = (PixelType*) destData.getLinePointer (y);
  489. }
  490. forcedinline void handleEdgeTablePixel (int x, int alphaLevel) const noexcept
  491. {
  492. if (replaceExisting)
  493. getPixel (x)->set (sourceColour);
  494. else
  495. getPixel (x)->blend (sourceColour, (uint32) alphaLevel);
  496. }
  497. forcedinline void handleEdgeTablePixelFull (int x) const noexcept
  498. {
  499. if (replaceExisting)
  500. getPixel (x)->set (sourceColour);
  501. else
  502. getPixel (x)->blend (sourceColour);
  503. }
  504. forcedinline void handleEdgeTableLine (int x, int width, int alphaLevel) const noexcept
  505. {
  506. auto p = sourceColour;
  507. p.multiplyAlpha (alphaLevel);
  508. auto* dest = getPixel (x);
  509. if (replaceExisting || p.getAlpha() >= 0xff)
  510. replaceLine (dest, p, width);
  511. else
  512. blendLine (dest, p, width);
  513. }
  514. forcedinline void handleEdgeTableLineFull (int x, int width) const noexcept
  515. {
  516. auto* dest = getPixel (x);
  517. if (replaceExisting || sourceColour.getAlpha() >= 0xff)
  518. replaceLine (dest, sourceColour, width);
  519. else
  520. blendLine (dest, sourceColour, width);
  521. }
  522. void handleEdgeTableRectangle (int x, int y, int width, int height, int alphaLevel) noexcept
  523. {
  524. auto p = sourceColour;
  525. p.multiplyAlpha (alphaLevel);
  526. setEdgeTableYPos (y);
  527. auto* dest = getPixel (x);
  528. if (replaceExisting || p.getAlpha() >= 0xff)
  529. {
  530. while (--height >= 0)
  531. {
  532. replaceLine (dest, p, width);
  533. dest = addBytesToPointer (dest, destData.lineStride);
  534. }
  535. }
  536. else
  537. {
  538. while (--height >= 0)
  539. {
  540. blendLine (dest, p, width);
  541. dest = addBytesToPointer (dest, destData.lineStride);
  542. }
  543. }
  544. }
  545. void handleEdgeTableRectangleFull (int x, int y, int width, int height) noexcept
  546. {
  547. handleEdgeTableRectangle (x, y, width, height, 255);
  548. }
  549. private:
  550. const Image::BitmapData& destData;
  551. PixelType* linePixels;
  552. PixelARGB sourceColour;
  553. bool areRGBComponentsEqual;
  554. forcedinline PixelType* getPixel (int x) const noexcept
  555. {
  556. return addBytesToPointer (linePixels, x * destData.pixelStride);
  557. }
  558. inline void blendLine (PixelType* dest, PixelARGB colour, int width) const noexcept
  559. {
  560. JUCE_PERFORM_PIXEL_OP_LOOP (blend (colour))
  561. }
  562. forcedinline void replaceLine (PixelRGB* dest, PixelARGB colour, int width) const noexcept
  563. {
  564. if ((size_t) destData.pixelStride == sizeof (*dest) && areRGBComponentsEqual)
  565. memset ((void*) dest, colour.getRed(), (size_t) width * 3); // if all the component values are the same, we can cheat..
  566. else
  567. JUCE_PERFORM_PIXEL_OP_LOOP (set (colour));
  568. }
  569. forcedinline void replaceLine (PixelAlpha* dest, const PixelARGB colour, int width) const noexcept
  570. {
  571. if ((size_t) destData.pixelStride == sizeof (*dest))
  572. memset ((void*) dest, colour.getAlpha(), (size_t) width);
  573. else
  574. JUCE_PERFORM_PIXEL_OP_LOOP (setAlpha (colour.getAlpha()))
  575. }
  576. forcedinline void replaceLine (PixelARGB* dest, const PixelARGB colour, int width) const noexcept
  577. {
  578. JUCE_PERFORM_PIXEL_OP_LOOP (set (colour))
  579. }
  580. JUCE_DECLARE_NON_COPYABLE (SolidColour)
  581. };
  582. //==============================================================================
  583. /** Fills an edge-table with a gradient. */
  584. template <class PixelType, class GradientType>
  585. struct Gradient : public GradientType
  586. {
  587. Gradient (const Image::BitmapData& dest, const ColourGradient& gradient, const AffineTransform& transform,
  588. const PixelARGB* colours, int numColours)
  589. : GradientType (gradient, transform, colours, numColours - 1),
  590. destData (dest)
  591. {
  592. }
  593. forcedinline void setEdgeTableYPos (int y) noexcept
  594. {
  595. linePixels = (PixelType*) destData.getLinePointer (y);
  596. GradientType::setY (y);
  597. }
  598. forcedinline void handleEdgeTablePixel (int x, int alphaLevel) const noexcept
  599. {
  600. getPixel (x)->blend (GradientType::getPixel (x), (uint32) alphaLevel);
  601. }
  602. forcedinline void handleEdgeTablePixelFull (int x) const noexcept
  603. {
  604. getPixel (x)->blend (GradientType::getPixel (x));
  605. }
  606. void handleEdgeTableLine (int x, int width, int alphaLevel) const noexcept
  607. {
  608. auto* dest = getPixel (x);
  609. if (alphaLevel < 0xff)
  610. JUCE_PERFORM_PIXEL_OP_LOOP (blend (GradientType::getPixel (x++), (uint32) alphaLevel))
  611. else
  612. JUCE_PERFORM_PIXEL_OP_LOOP (blend (GradientType::getPixel (x++)))
  613. }
  614. void handleEdgeTableLineFull (int x, int width) const noexcept
  615. {
  616. auto* dest = getPixel (x);
  617. JUCE_PERFORM_PIXEL_OP_LOOP (blend (GradientType::getPixel (x++)))
  618. }
  619. void handleEdgeTableRectangle (int x, int y, int width, int height, int alphaLevel) noexcept
  620. {
  621. while (--height >= 0)
  622. {
  623. setEdgeTableYPos (y++);
  624. handleEdgeTableLine (x, width, alphaLevel);
  625. }
  626. }
  627. void handleEdgeTableRectangleFull (int x, int y, int width, int height) noexcept
  628. {
  629. while (--height >= 0)
  630. {
  631. setEdgeTableYPos (y++);
  632. handleEdgeTableLineFull (x, width);
  633. }
  634. }
  635. private:
  636. const Image::BitmapData& destData;
  637. PixelType* linePixels;
  638. forcedinline PixelType* getPixel (int x) const noexcept
  639. {
  640. return addBytesToPointer (linePixels, x * destData.pixelStride);
  641. }
  642. JUCE_DECLARE_NON_COPYABLE (Gradient)
  643. };
  644. //==============================================================================
  645. /** Fills an edge-table with a non-transformed image. */
  646. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  647. struct ImageFill
  648. {
  649. ImageFill (const Image::BitmapData& dest, const Image::BitmapData& src, int alpha, int x, int y)
  650. : destData (dest),
  651. srcData (src),
  652. extraAlpha (alpha + 1),
  653. xOffset (repeatPattern ? negativeAwareModulo (x, src.width) - src.width : x),
  654. yOffset (repeatPattern ? negativeAwareModulo (y, src.height) - src.height : y)
  655. {
  656. }
  657. forcedinline void setEdgeTableYPos (int y) noexcept
  658. {
  659. linePixels = (DestPixelType*) destData.getLinePointer (y);
  660. y -= yOffset;
  661. if (repeatPattern)
  662. {
  663. jassert (y >= 0);
  664. y %= srcData.height;
  665. }
  666. sourceLineStart = (SrcPixelType*) srcData.getLinePointer (y);
  667. }
  668. forcedinline void handleEdgeTablePixel (int x, int alphaLevel) const noexcept
  669. {
  670. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  671. getDestPixel (x)->blend (*getSrcPixel (repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)), (uint32) alphaLevel);
  672. }
  673. forcedinline void handleEdgeTablePixelFull (int x) const noexcept
  674. {
  675. getDestPixel (x)->blend (*getSrcPixel (repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)), (uint32) extraAlpha);
  676. }
  677. void handleEdgeTableLine (int x, int width, int alphaLevel) const noexcept
  678. {
  679. auto* dest = getDestPixel (x);
  680. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  681. x -= xOffset;
  682. if (repeatPattern)
  683. {
  684. if (alphaLevel < 0xfe)
  685. JUCE_PERFORM_PIXEL_OP_LOOP (blend (*getSrcPixel (x++ % srcData.width), (uint32) alphaLevel))
  686. else
  687. JUCE_PERFORM_PIXEL_OP_LOOP (blend (*getSrcPixel (x++ % srcData.width)))
  688. }
  689. else
  690. {
  691. jassert (x >= 0 && x + width <= srcData.width);
  692. if (alphaLevel < 0xfe)
  693. JUCE_PERFORM_PIXEL_OP_LOOP (blend (*getSrcPixel (x++), (uint32) alphaLevel))
  694. else
  695. copyRow (dest, getSrcPixel (x), width);
  696. }
  697. }
  698. void handleEdgeTableLineFull (int x, int width) const noexcept
  699. {
  700. auto* dest = getDestPixel (x);
  701. x -= xOffset;
  702. if (repeatPattern)
  703. {
  704. if (extraAlpha < 0xfe)
  705. JUCE_PERFORM_PIXEL_OP_LOOP (blend (*getSrcPixel (x++ % srcData.width), (uint32) extraAlpha))
  706. else
  707. JUCE_PERFORM_PIXEL_OP_LOOP (blend (*getSrcPixel (x++ % srcData.width)))
  708. }
  709. else
  710. {
  711. jassert (x >= 0 && x + width <= srcData.width);
  712. if (extraAlpha < 0xfe)
  713. JUCE_PERFORM_PIXEL_OP_LOOP (blend (*getSrcPixel (x++), (uint32) extraAlpha))
  714. else
  715. copyRow (dest, getSrcPixel (x), width);
  716. }
  717. }
  718. void handleEdgeTableRectangle (int x, int y, int width, int height, int alphaLevel) noexcept
  719. {
  720. while (--height >= 0)
  721. {
  722. setEdgeTableYPos (y++);
  723. handleEdgeTableLine (x, width, alphaLevel);
  724. }
  725. }
  726. void handleEdgeTableRectangleFull (int x, int y, int width, int height) noexcept
  727. {
  728. while (--height >= 0)
  729. {
  730. setEdgeTableYPos (y++);
  731. handleEdgeTableLineFull (x, width);
  732. }
  733. }
  734. void clipEdgeTableLine (EdgeTable& et, int x, int y, int width)
  735. {
  736. jassert (x - xOffset >= 0 && x + width - xOffset <= srcData.width);
  737. auto* s = (SrcPixelType*) srcData.getLinePointer (y - yOffset);
  738. auto* mask = (uint8*) (s + x - xOffset);
  739. if (sizeof (SrcPixelType) == sizeof (PixelARGB))
  740. mask += PixelARGB::indexA;
  741. et.clipLineToMask (x, y, mask, sizeof (SrcPixelType), width);
  742. }
  743. private:
  744. const Image::BitmapData& destData;
  745. const Image::BitmapData& srcData;
  746. const int extraAlpha, xOffset, yOffset;
  747. DestPixelType* linePixels;
  748. SrcPixelType* sourceLineStart;
  749. forcedinline DestPixelType* getDestPixel (int x) const noexcept
  750. {
  751. return addBytesToPointer (linePixels, x * destData.pixelStride);
  752. }
  753. forcedinline SrcPixelType const* getSrcPixel (int x) const noexcept
  754. {
  755. return addBytesToPointer (sourceLineStart, x * srcData.pixelStride);
  756. }
  757. forcedinline void copyRow (DestPixelType* dest, SrcPixelType const* src, int width) const noexcept
  758. {
  759. auto destStride = destData.pixelStride;
  760. auto srcStride = srcData.pixelStride;
  761. if (destStride == srcStride
  762. && srcData.pixelFormat == Image::RGB
  763. && destData.pixelFormat == Image::RGB)
  764. {
  765. memcpy ((void*) dest, src, (size_t) (width * srcStride));
  766. }
  767. else
  768. {
  769. do
  770. {
  771. dest->blend (*src);
  772. dest = addBytesToPointer (dest, destStride);
  773. src = addBytesToPointer (src, srcStride);
  774. } while (--width > 0);
  775. }
  776. }
  777. JUCE_DECLARE_NON_COPYABLE (ImageFill)
  778. };
  779. //==============================================================================
  780. /** Fills an edge-table with a transformed image. */
  781. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  782. struct TransformedImageFill
  783. {
  784. TransformedImageFill (const Image::BitmapData& dest, const Image::BitmapData& src,
  785. const AffineTransform& transform, int alpha, Graphics::ResamplingQuality q)
  786. : interpolator (transform,
  787. q != Graphics::lowResamplingQuality ? 0.5f : 0.0f,
  788. q != Graphics::lowResamplingQuality ? -128 : 0),
  789. destData (dest),
  790. srcData (src),
  791. extraAlpha (alpha + 1),
  792. quality (q),
  793. maxX (src.width - 1),
  794. maxY (src.height - 1)
  795. {
  796. scratchBuffer.malloc (scratchSize);
  797. }
  798. forcedinline void setEdgeTableYPos (int newY) noexcept
  799. {
  800. currentY = newY;
  801. linePixels = (DestPixelType*) destData.getLinePointer (newY);
  802. }
  803. forcedinline void handleEdgeTablePixel (int x, int alphaLevel) noexcept
  804. {
  805. SrcPixelType p;
  806. generate (&p, x, 1);
  807. getDestPixel (x)->blend (p, (uint32) (alphaLevel * extraAlpha) >> 8);
  808. }
  809. forcedinline void handleEdgeTablePixelFull (int x) noexcept
  810. {
  811. SrcPixelType p;
  812. generate (&p, x, 1);
  813. getDestPixel (x)->blend (p, (uint32) extraAlpha);
  814. }
  815. void handleEdgeTableLine (int x, int width, int alphaLevel) noexcept
  816. {
  817. if (width > (int) scratchSize)
  818. {
  819. scratchSize = (size_t) width;
  820. scratchBuffer.malloc (scratchSize);
  821. }
  822. SrcPixelType* span = scratchBuffer;
  823. generate (span, x, width);
  824. auto* dest = getDestPixel (x);
  825. alphaLevel *= extraAlpha;
  826. alphaLevel >>= 8;
  827. if (alphaLevel < 0xfe)
  828. JUCE_PERFORM_PIXEL_OP_LOOP (blend (*span++, (uint32) alphaLevel))
  829. else
  830. JUCE_PERFORM_PIXEL_OP_LOOP (blend (*span++))
  831. }
  832. forcedinline void handleEdgeTableLineFull (int x, int width) noexcept
  833. {
  834. handleEdgeTableLine (x, width, 255);
  835. }
  836. void handleEdgeTableRectangle (int x, int y, int width, int height, int alphaLevel) noexcept
  837. {
  838. while (--height >= 0)
  839. {
  840. setEdgeTableYPos (y++);
  841. handleEdgeTableLine (x, width, alphaLevel);
  842. }
  843. }
  844. void handleEdgeTableRectangleFull (int x, int y, int width, int height) noexcept
  845. {
  846. while (--height >= 0)
  847. {
  848. setEdgeTableYPos (y++);
  849. handleEdgeTableLineFull (x, width);
  850. }
  851. }
  852. void clipEdgeTableLine (EdgeTable& et, int x, int y, int width)
  853. {
  854. if (width > (int) scratchSize)
  855. {
  856. scratchSize = (size_t) width;
  857. scratchBuffer.malloc (scratchSize);
  858. }
  859. currentY = y;
  860. generate (scratchBuffer.get(), x, width);
  861. et.clipLineToMask (x, y,
  862. reinterpret_cast<uint8*> (scratchBuffer.get()) + SrcPixelType::indexA,
  863. sizeof (SrcPixelType), width);
  864. }
  865. private:
  866. forcedinline DestPixelType* getDestPixel (int x) const noexcept
  867. {
  868. return addBytesToPointer (linePixels, x * destData.pixelStride);
  869. }
  870. //==============================================================================
  871. template <class PixelType>
  872. void generate (PixelType* dest, int x, int numPixels) noexcept
  873. {
  874. this->interpolator.setStartOfLine ((float) x, (float) currentY, numPixels);
  875. do
  876. {
  877. int hiResX, hiResY;
  878. this->interpolator.next (hiResX, hiResY);
  879. int loResX = hiResX >> 8;
  880. int loResY = hiResY >> 8;
  881. if (repeatPattern)
  882. {
  883. loResX = negativeAwareModulo (loResX, srcData.width);
  884. loResY = negativeAwareModulo (loResY, srcData.height);
  885. }
  886. if (quality != Graphics::lowResamplingQuality)
  887. {
  888. if (isPositiveAndBelow (loResX, maxX))
  889. {
  890. if (isPositiveAndBelow (loResY, maxY))
  891. {
  892. // In the centre of the image..
  893. render4PixelAverage (dest, this->srcData.getPixelPointer (loResX, loResY),
  894. hiResX & 255, hiResY & 255);
  895. ++dest;
  896. continue;
  897. }
  898. if (! repeatPattern)
  899. {
  900. // At a top or bottom edge..
  901. if (loResY < 0)
  902. render2PixelAverageX (dest, this->srcData.getPixelPointer (loResX, 0), hiResX & 255);
  903. else
  904. render2PixelAverageX (dest, this->srcData.getPixelPointer (loResX, maxY), hiResX & 255);
  905. ++dest;
  906. continue;
  907. }
  908. }
  909. else
  910. {
  911. if (isPositiveAndBelow (loResY, maxY) && ! repeatPattern)
  912. {
  913. // At a left or right hand edge..
  914. if (loResX < 0)
  915. render2PixelAverageY (dest, this->srcData.getPixelPointer (0, loResY), hiResY & 255);
  916. else
  917. render2PixelAverageY (dest, this->srcData.getPixelPointer (maxX, loResY), hiResY & 255);
  918. ++dest;
  919. continue;
  920. }
  921. }
  922. }
  923. if (! repeatPattern)
  924. {
  925. if (loResX < 0) loResX = 0;
  926. if (loResY < 0) loResY = 0;
  927. if (loResX > maxX) loResX = maxX;
  928. if (loResY > maxY) loResY = maxY;
  929. }
  930. dest->set (*(const PixelType*) this->srcData.getPixelPointer (loResX, loResY));
  931. ++dest;
  932. } while (--numPixels > 0);
  933. }
  934. //==============================================================================
  935. void render4PixelAverage (PixelARGB* dest, const uint8* src, int subPixelX, int subPixelY) noexcept
  936. {
  937. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  938. auto weight = (uint32) ((256 - subPixelX) * (256 - subPixelY));
  939. c[0] += weight * src[0];
  940. c[1] += weight * src[1];
  941. c[2] += weight * src[2];
  942. c[3] += weight * src[3];
  943. src += this->srcData.pixelStride;
  944. weight = (uint32) (subPixelX * (256 - subPixelY));
  945. c[0] += weight * src[0];
  946. c[1] += weight * src[1];
  947. c[2] += weight * src[2];
  948. c[3] += weight * src[3];
  949. src += this->srcData.lineStride;
  950. weight = (uint32) (subPixelX * subPixelY);
  951. c[0] += weight * src[0];
  952. c[1] += weight * src[1];
  953. c[2] += weight * src[2];
  954. c[3] += weight * src[3];
  955. src -= this->srcData.pixelStride;
  956. weight = (uint32) ((256 - subPixelX) * subPixelY);
  957. c[0] += weight * src[0];
  958. c[1] += weight * src[1];
  959. c[2] += weight * src[2];
  960. c[3] += weight * src[3];
  961. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  962. (uint8) (c[PixelARGB::indexR] >> 16),
  963. (uint8) (c[PixelARGB::indexG] >> 16),
  964. (uint8) (c[PixelARGB::indexB] >> 16));
  965. }
  966. void render2PixelAverageX (PixelARGB* dest, const uint8* src, uint32 subPixelX) noexcept
  967. {
  968. uint32 c[4] = { 128, 128, 128, 128 };
  969. uint32 weight = 256 - subPixelX;
  970. c[0] += weight * src[0];
  971. c[1] += weight * src[1];
  972. c[2] += weight * src[2];
  973. c[3] += weight * src[3];
  974. src += this->srcData.pixelStride;
  975. weight = subPixelX;
  976. c[0] += weight * src[0];
  977. c[1] += weight * src[1];
  978. c[2] += weight * src[2];
  979. c[3] += weight * src[3];
  980. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 8),
  981. (uint8) (c[PixelARGB::indexR] >> 8),
  982. (uint8) (c[PixelARGB::indexG] >> 8),
  983. (uint8) (c[PixelARGB::indexB] >> 8));
  984. }
  985. void render2PixelAverageY (PixelARGB* dest, const uint8* src, uint32 subPixelY) noexcept
  986. {
  987. uint32 c[4] = { 128, 128, 128, 128 };
  988. uint32 weight = 256 - subPixelY;
  989. c[0] += weight * src[0];
  990. c[1] += weight * src[1];
  991. c[2] += weight * src[2];
  992. c[3] += weight * src[3];
  993. src += this->srcData.lineStride;
  994. weight = subPixelY;
  995. c[0] += weight * src[0];
  996. c[1] += weight * src[1];
  997. c[2] += weight * src[2];
  998. c[3] += weight * src[3];
  999. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 8),
  1000. (uint8) (c[PixelARGB::indexR] >> 8),
  1001. (uint8) (c[PixelARGB::indexG] >> 8),
  1002. (uint8) (c[PixelARGB::indexB] >> 8));
  1003. }
  1004. //==============================================================================
  1005. void render4PixelAverage (PixelRGB* dest, const uint8* src, uint32 subPixelX, uint32 subPixelY) noexcept
  1006. {
  1007. uint32 c[3] = { 256 * 128, 256 * 128, 256 * 128 };
  1008. uint32 weight = (256 - subPixelX) * (256 - subPixelY);
  1009. c[0] += weight * src[0];
  1010. c[1] += weight * src[1];
  1011. c[2] += weight * src[2];
  1012. src += this->srcData.pixelStride;
  1013. weight = subPixelX * (256 - subPixelY);
  1014. c[0] += weight * src[0];
  1015. c[1] += weight * src[1];
  1016. c[2] += weight * src[2];
  1017. src += this->srcData.lineStride;
  1018. weight = subPixelX * subPixelY;
  1019. c[0] += weight * src[0];
  1020. c[1] += weight * src[1];
  1021. c[2] += weight * src[2];
  1022. src -= this->srcData.pixelStride;
  1023. weight = (256 - subPixelX) * subPixelY;
  1024. c[0] += weight * src[0];
  1025. c[1] += weight * src[1];
  1026. c[2] += weight * src[2];
  1027. dest->setARGB ((uint8) 255,
  1028. (uint8) (c[PixelRGB::indexR] >> 16),
  1029. (uint8) (c[PixelRGB::indexG] >> 16),
  1030. (uint8) (c[PixelRGB::indexB] >> 16));
  1031. }
  1032. void render2PixelAverageX (PixelRGB* dest, const uint8* src, uint32 subPixelX) noexcept
  1033. {
  1034. uint32 c[3] = { 128, 128, 128 };
  1035. const uint32 weight = 256 - subPixelX;
  1036. c[0] += weight * src[0];
  1037. c[1] += weight * src[1];
  1038. c[2] += weight * src[2];
  1039. src += this->srcData.pixelStride;
  1040. c[0] += subPixelX * src[0];
  1041. c[1] += subPixelX * src[1];
  1042. c[2] += subPixelX * src[2];
  1043. dest->setARGB ((uint8) 255,
  1044. (uint8) (c[PixelRGB::indexR] >> 8),
  1045. (uint8) (c[PixelRGB::indexG] >> 8),
  1046. (uint8) (c[PixelRGB::indexB] >> 8));
  1047. }
  1048. void render2PixelAverageY (PixelRGB* dest, const uint8* src, uint32 subPixelY) noexcept
  1049. {
  1050. uint32 c[3] = { 128, 128, 128 };
  1051. const uint32 weight = 256 - subPixelY;
  1052. c[0] += weight * src[0];
  1053. c[1] += weight * src[1];
  1054. c[2] += weight * src[2];
  1055. src += this->srcData.lineStride;
  1056. c[0] += subPixelY * src[0];
  1057. c[1] += subPixelY * src[1];
  1058. c[2] += subPixelY * src[2];
  1059. dest->setARGB ((uint8) 255,
  1060. (uint8) (c[PixelRGB::indexR] >> 8),
  1061. (uint8) (c[PixelRGB::indexG] >> 8),
  1062. (uint8) (c[PixelRGB::indexB] >> 8));
  1063. }
  1064. //==============================================================================
  1065. void render4PixelAverage (PixelAlpha* dest, const uint8* src, uint32 subPixelX, uint32 subPixelY) noexcept
  1066. {
  1067. uint32 c = 256 * 128;
  1068. c += src[0] * ((256 - subPixelX) * (256 - subPixelY));
  1069. src += this->srcData.pixelStride;
  1070. c += src[0] * (subPixelX * (256 - subPixelY));
  1071. src += this->srcData.lineStride;
  1072. c += src[0] * (subPixelX * subPixelY);
  1073. src -= this->srcData.pixelStride;
  1074. c += src[0] * ((256 - subPixelX) * subPixelY);
  1075. *((uint8*) dest) = (uint8) (c >> 16);
  1076. }
  1077. void render2PixelAverageX (PixelAlpha* dest, const uint8* src, uint32 subPixelX) noexcept
  1078. {
  1079. uint32 c = 128;
  1080. c += src[0] * (256 - subPixelX);
  1081. src += this->srcData.pixelStride;
  1082. c += src[0] * subPixelX;
  1083. *((uint8*) dest) = (uint8) (c >> 8);
  1084. }
  1085. void render2PixelAverageY (PixelAlpha* dest, const uint8* src, uint32 subPixelY) noexcept
  1086. {
  1087. uint32 c = 128;
  1088. c += src[0] * (256 - subPixelY);
  1089. src += this->srcData.lineStride;
  1090. c += src[0] * subPixelY;
  1091. *((uint8*) dest) = (uint8) (c >> 8);
  1092. }
  1093. //==============================================================================
  1094. struct TransformedImageSpanInterpolator
  1095. {
  1096. TransformedImageSpanInterpolator (const AffineTransform& transform, float offsetFloat, int offsetInt) noexcept
  1097. : inverseTransform (transform.inverted()),
  1098. pixelOffset (offsetFloat), pixelOffsetInt (offsetInt)
  1099. {}
  1100. void setStartOfLine (float sx, float sy, int numPixels) noexcept
  1101. {
  1102. jassert (numPixels > 0);
  1103. sx += pixelOffset;
  1104. sy += pixelOffset;
  1105. auto x1 = sx, y1 = sy;
  1106. sx += (float) numPixels;
  1107. inverseTransform.transformPoints (x1, y1, sx, sy);
  1108. xBresenham.set ((int) (x1 * 256.0f), (int) (sx * 256.0f), numPixels, pixelOffsetInt);
  1109. yBresenham.set ((int) (y1 * 256.0f), (int) (sy * 256.0f), numPixels, pixelOffsetInt);
  1110. }
  1111. void next (int& px, int& py) noexcept
  1112. {
  1113. px = xBresenham.n; xBresenham.stepToNext();
  1114. py = yBresenham.n; yBresenham.stepToNext();
  1115. }
  1116. private:
  1117. struct BresenhamInterpolator
  1118. {
  1119. BresenhamInterpolator() = default;
  1120. void set (int n1, int n2, int steps, int offsetInt) noexcept
  1121. {
  1122. numSteps = steps;
  1123. step = (n2 - n1) / numSteps;
  1124. remainder = modulo = (n2 - n1) % numSteps;
  1125. n = n1 + offsetInt;
  1126. if (modulo <= 0)
  1127. {
  1128. modulo += numSteps;
  1129. remainder += numSteps;
  1130. --step;
  1131. }
  1132. modulo -= numSteps;
  1133. }
  1134. forcedinline void stepToNext() noexcept
  1135. {
  1136. modulo += remainder;
  1137. n += step;
  1138. if (modulo > 0)
  1139. {
  1140. modulo -= numSteps;
  1141. ++n;
  1142. }
  1143. }
  1144. int n;
  1145. private:
  1146. int numSteps, step, modulo, remainder;
  1147. };
  1148. const AffineTransform inverseTransform;
  1149. BresenhamInterpolator xBresenham, yBresenham;
  1150. const float pixelOffset;
  1151. const int pixelOffsetInt;
  1152. JUCE_DECLARE_NON_COPYABLE (TransformedImageSpanInterpolator)
  1153. };
  1154. //==============================================================================
  1155. TransformedImageSpanInterpolator interpolator;
  1156. const Image::BitmapData& destData;
  1157. const Image::BitmapData& srcData;
  1158. const int extraAlpha;
  1159. const Graphics::ResamplingQuality quality;
  1160. const int maxX, maxY;
  1161. int currentY;
  1162. DestPixelType* linePixels;
  1163. HeapBlock<SrcPixelType> scratchBuffer;
  1164. size_t scratchSize = 2048;
  1165. JUCE_DECLARE_NON_COPYABLE (TransformedImageFill)
  1166. };
  1167. //==============================================================================
  1168. template <class Iterator>
  1169. void renderImageTransformed (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData,
  1170. int alpha, const AffineTransform& transform, Graphics::ResamplingQuality quality, bool tiledFill)
  1171. {
  1172. switch (destData.pixelFormat)
  1173. {
  1174. case Image::ARGB:
  1175. switch (srcData.pixelFormat)
  1176. {
  1177. case Image::ARGB:
  1178. if (tiledFill) { TransformedImageFill<PixelARGB, PixelARGB, true> r (destData, srcData, transform, alpha, quality); iter.iterate (r); }
  1179. else { TransformedImageFill<PixelARGB, PixelARGB, false> r (destData, srcData, transform, alpha, quality); iter.iterate (r); }
  1180. break;
  1181. case Image::RGB:
  1182. if (tiledFill) { TransformedImageFill<PixelARGB, PixelRGB, true> r (destData, srcData, transform, alpha, quality); iter.iterate (r); }
  1183. else { TransformedImageFill<PixelARGB, PixelRGB, false> r (destData, srcData, transform, alpha, quality); iter.iterate (r); }
  1184. break;
  1185. case Image::SingleChannel:
  1186. case Image::UnknownFormat:
  1187. default:
  1188. if (tiledFill) { TransformedImageFill<PixelARGB, PixelAlpha, true> r (destData, srcData, transform, alpha, quality); iter.iterate (r); }
  1189. else { TransformedImageFill<PixelARGB, PixelAlpha, false> r (destData, srcData, transform, alpha, quality); iter.iterate (r); }
  1190. break;
  1191. }
  1192. break;
  1193. case Image::RGB:
  1194. {
  1195. switch (srcData.pixelFormat)
  1196. {
  1197. case Image::ARGB:
  1198. if (tiledFill) { TransformedImageFill<PixelRGB, PixelARGB, true> r (destData, srcData, transform, alpha, quality); iter.iterate (r); }
  1199. else { TransformedImageFill<PixelRGB, PixelARGB, false> r (destData, srcData, transform, alpha, quality); iter.iterate (r); }
  1200. break;
  1201. case Image::RGB:
  1202. if (tiledFill) { TransformedImageFill<PixelRGB, PixelRGB, true> r (destData, srcData, transform, alpha, quality); iter.iterate (r); }
  1203. else { TransformedImageFill<PixelRGB, PixelRGB, false> r (destData, srcData, transform, alpha, quality); iter.iterate (r); }
  1204. break;
  1205. case Image::SingleChannel:
  1206. case Image::UnknownFormat:
  1207. default:
  1208. if (tiledFill) { TransformedImageFill<PixelRGB, PixelAlpha, true> r (destData, srcData, transform, alpha, quality); iter.iterate (r); }
  1209. else { TransformedImageFill<PixelRGB, PixelAlpha, false> r (destData, srcData, transform, alpha, quality); iter.iterate (r); }
  1210. break;
  1211. }
  1212. break;
  1213. }
  1214. case Image::SingleChannel:
  1215. case Image::UnknownFormat:
  1216. default:
  1217. switch (srcData.pixelFormat)
  1218. {
  1219. case Image::ARGB:
  1220. if (tiledFill) { TransformedImageFill<PixelAlpha, PixelARGB, true> r (destData, srcData, transform, alpha, quality); iter.iterate (r); }
  1221. else { TransformedImageFill<PixelAlpha, PixelARGB, false> r (destData, srcData, transform, alpha, quality); iter.iterate (r); }
  1222. break;
  1223. case Image::RGB:
  1224. if (tiledFill) { TransformedImageFill<PixelAlpha, PixelRGB, true> r (destData, srcData, transform, alpha, quality); iter.iterate (r); }
  1225. else { TransformedImageFill<PixelAlpha, PixelRGB, false> r (destData, srcData, transform, alpha, quality); iter.iterate (r); }
  1226. break;
  1227. case Image::SingleChannel:
  1228. case Image::UnknownFormat:
  1229. default:
  1230. if (tiledFill) { TransformedImageFill<PixelAlpha, PixelAlpha, true> r (destData, srcData, transform, alpha, quality); iter.iterate (r); }
  1231. else { TransformedImageFill<PixelAlpha, PixelAlpha, false> r (destData, srcData, transform, alpha, quality); iter.iterate (r); }
  1232. break;
  1233. }
  1234. break;
  1235. }
  1236. }
  1237. template <class Iterator>
  1238. void renderImageUntransformed (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData, int alpha, int x, int y, bool tiledFill)
  1239. {
  1240. switch (destData.pixelFormat)
  1241. {
  1242. case Image::ARGB:
  1243. switch (srcData.pixelFormat)
  1244. {
  1245. case Image::ARGB:
  1246. if (tiledFill) { ImageFill<PixelARGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  1247. else { ImageFill<PixelARGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  1248. break;
  1249. case Image::RGB:
  1250. if (tiledFill) { ImageFill<PixelARGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  1251. else { ImageFill<PixelARGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  1252. break;
  1253. case Image::SingleChannel:
  1254. case Image::UnknownFormat:
  1255. default:
  1256. if (tiledFill) { ImageFill<PixelARGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  1257. else { ImageFill<PixelARGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  1258. break;
  1259. }
  1260. break;
  1261. case Image::RGB:
  1262. switch (srcData.pixelFormat)
  1263. {
  1264. case Image::ARGB:
  1265. if (tiledFill) { ImageFill<PixelRGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  1266. else { ImageFill<PixelRGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  1267. break;
  1268. case Image::RGB:
  1269. if (tiledFill) { ImageFill<PixelRGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  1270. else { ImageFill<PixelRGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  1271. break;
  1272. case Image::SingleChannel:
  1273. case Image::UnknownFormat:
  1274. default:
  1275. if (tiledFill) { ImageFill<PixelRGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  1276. else { ImageFill<PixelRGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  1277. break;
  1278. }
  1279. break;
  1280. case Image::SingleChannel:
  1281. case Image::UnknownFormat:
  1282. default:
  1283. switch (srcData.pixelFormat)
  1284. {
  1285. case Image::ARGB:
  1286. if (tiledFill) { ImageFill<PixelAlpha, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  1287. else { ImageFill<PixelAlpha, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  1288. break;
  1289. case Image::RGB:
  1290. if (tiledFill) { ImageFill<PixelAlpha, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  1291. else { ImageFill<PixelAlpha, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  1292. break;
  1293. case Image::SingleChannel:
  1294. case Image::UnknownFormat:
  1295. default:
  1296. if (tiledFill) { ImageFill<PixelAlpha, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  1297. else { ImageFill<PixelAlpha, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  1298. break;
  1299. }
  1300. break;
  1301. }
  1302. }
  1303. template <class Iterator, class DestPixelType>
  1304. void renderSolidFill (Iterator& iter, const Image::BitmapData& destData, PixelARGB fillColour, bool replaceContents, DestPixelType*)
  1305. {
  1306. if (replaceContents)
  1307. {
  1308. EdgeTableFillers::SolidColour<DestPixelType, true> r (destData, fillColour);
  1309. iter.iterate (r);
  1310. }
  1311. else
  1312. {
  1313. EdgeTableFillers::SolidColour<DestPixelType, false> r (destData, fillColour);
  1314. iter.iterate (r);
  1315. }
  1316. }
  1317. template <class Iterator, class DestPixelType>
  1318. void renderGradient (Iterator& iter, const Image::BitmapData& destData, const ColourGradient& g, const AffineTransform& transform,
  1319. const PixelARGB* lookupTable, int numLookupEntries, bool isIdentity, DestPixelType*)
  1320. {
  1321. if (g.isRadial)
  1322. {
  1323. if (isIdentity)
  1324. {
  1325. EdgeTableFillers::Gradient<DestPixelType, GradientPixelIterators::Radial> renderer (destData, g, transform, lookupTable, numLookupEntries);
  1326. iter.iterate (renderer);
  1327. }
  1328. else
  1329. {
  1330. EdgeTableFillers::Gradient<DestPixelType, GradientPixelIterators::TransformedRadial> renderer (destData, g, transform, lookupTable, numLookupEntries);
  1331. iter.iterate (renderer);
  1332. }
  1333. }
  1334. else
  1335. {
  1336. EdgeTableFillers::Gradient<DestPixelType, GradientPixelIterators::Linear> renderer (destData, g, transform, lookupTable, numLookupEntries);
  1337. iter.iterate (renderer);
  1338. }
  1339. }
  1340. }
  1341. //==============================================================================
  1342. template <class SavedStateType>
  1343. struct ClipRegions
  1344. {
  1345. struct Base : public SingleThreadedReferenceCountedObject
  1346. {
  1347. Base() = default;
  1348. ~Base() override = default;
  1349. using Ptr = ReferenceCountedObjectPtr<Base>;
  1350. virtual Ptr clone() const = 0;
  1351. virtual Ptr applyClipTo (const Ptr& target) const = 0;
  1352. virtual Ptr clipToRectangle (Rectangle<int>) = 0;
  1353. virtual Ptr clipToRectangleList (const RectangleList<int>&) = 0;
  1354. virtual Ptr excludeClipRectangle (Rectangle<int>) = 0;
  1355. virtual Ptr clipToPath (const Path&, const AffineTransform&) = 0;
  1356. virtual Ptr clipToEdgeTable (const EdgeTable&) = 0;
  1357. virtual Ptr clipToImageAlpha (const Image&, const AffineTransform&, Graphics::ResamplingQuality) = 0;
  1358. virtual void translate (Point<int> delta) = 0;
  1359. virtual bool clipRegionIntersects (Rectangle<int>) const = 0;
  1360. virtual Rectangle<int> getClipBounds() const = 0;
  1361. virtual void fillRectWithColour (SavedStateType&, Rectangle<int>, PixelARGB colour, bool replaceContents) const = 0;
  1362. virtual void fillRectWithColour (SavedStateType&, Rectangle<float>, PixelARGB colour) const = 0;
  1363. virtual void fillAllWithColour (SavedStateType&, PixelARGB colour, bool replaceContents) const = 0;
  1364. virtual void fillAllWithGradient (SavedStateType&, ColourGradient&, const AffineTransform&, bool isIdentity) const = 0;
  1365. virtual void renderImageTransformed (SavedStateType&, const Image&, int alpha, const AffineTransform&, Graphics::ResamplingQuality, bool tiledFill) const = 0;
  1366. virtual void renderImageUntransformed (SavedStateType&, const Image&, int alpha, int x, int y, bool tiledFill) const = 0;
  1367. };
  1368. //==============================================================================
  1369. struct EdgeTableRegion : public Base
  1370. {
  1371. EdgeTableRegion (const EdgeTable& e) : edgeTable (e) {}
  1372. EdgeTableRegion (Rectangle<int> r) : edgeTable (r) {}
  1373. EdgeTableRegion (Rectangle<float> r) : edgeTable (r) {}
  1374. EdgeTableRegion (const RectangleList<int>& r) : edgeTable (r) {}
  1375. EdgeTableRegion (const RectangleList<float>& r) : edgeTable (r) {}
  1376. EdgeTableRegion (Rectangle<int> bounds, const Path& p, const AffineTransform& t) : edgeTable (bounds, p, t) {}
  1377. EdgeTableRegion (const EdgeTableRegion& other) : Base(), edgeTable (other.edgeTable) {}
  1378. EdgeTableRegion& operator= (const EdgeTableRegion&) = delete;
  1379. using Ptr = typename Base::Ptr;
  1380. Ptr clone() const override { return *new EdgeTableRegion (*this); }
  1381. Ptr applyClipTo (const Ptr& target) const override { return target->clipToEdgeTable (edgeTable); }
  1382. Ptr clipToRectangle (Rectangle<int> r) override
  1383. {
  1384. edgeTable.clipToRectangle (r);
  1385. return edgeTable.isEmpty() ? Ptr() : Ptr (*this);
  1386. }
  1387. Ptr clipToRectangleList (const RectangleList<int>& r) override
  1388. {
  1389. RectangleList<int> inverse (edgeTable.getMaximumBounds());
  1390. if (inverse.subtract (r))
  1391. for (auto& i : inverse)
  1392. edgeTable.excludeRectangle (i);
  1393. return edgeTable.isEmpty() ? Ptr() : Ptr (*this);
  1394. }
  1395. Ptr excludeClipRectangle (Rectangle<int> r) override
  1396. {
  1397. edgeTable.excludeRectangle (r);
  1398. return edgeTable.isEmpty() ? Ptr() : Ptr (*this);
  1399. }
  1400. Ptr clipToPath (const Path& p, const AffineTransform& transform) override
  1401. {
  1402. EdgeTable et (edgeTable.getMaximumBounds(), p, transform);
  1403. edgeTable.clipToEdgeTable (et);
  1404. return edgeTable.isEmpty() ? Ptr() : Ptr (*this);
  1405. }
  1406. Ptr clipToEdgeTable (const EdgeTable& et) override
  1407. {
  1408. edgeTable.clipToEdgeTable (et);
  1409. return edgeTable.isEmpty() ? Ptr() : Ptr (*this);
  1410. }
  1411. Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, Graphics::ResamplingQuality quality) override
  1412. {
  1413. const Image::BitmapData srcData (image, Image::BitmapData::readOnly);
  1414. if (transform.isOnlyTranslation())
  1415. {
  1416. // If our translation doesn't involve any distortion, just use a simple blit..
  1417. auto tx = (int) (transform.getTranslationX() * 256.0f);
  1418. auto ty = (int) (transform.getTranslationY() * 256.0f);
  1419. if (quality == Graphics::lowResamplingQuality || ((tx | ty) & 224) == 0)
  1420. {
  1421. auto imageX = ((tx + 128) >> 8);
  1422. auto imageY = ((ty + 128) >> 8);
  1423. if (image.getFormat() == Image::ARGB)
  1424. straightClipImage (srcData, imageX, imageY, (PixelARGB*) nullptr);
  1425. else
  1426. straightClipImage (srcData, imageX, imageY, (PixelAlpha*) nullptr);
  1427. return edgeTable.isEmpty() ? Ptr() : Ptr (*this);
  1428. }
  1429. }
  1430. if (transform.isSingularity())
  1431. return Ptr();
  1432. {
  1433. Path p;
  1434. p.addRectangle (0, 0, (float) srcData.width, (float) srcData.height);
  1435. EdgeTable et2 (edgeTable.getMaximumBounds(), p, transform);
  1436. edgeTable.clipToEdgeTable (et2);
  1437. }
  1438. if (! edgeTable.isEmpty())
  1439. {
  1440. if (image.getFormat() == Image::ARGB)
  1441. transformedClipImage (srcData, transform, quality, (PixelARGB*) nullptr);
  1442. else
  1443. transformedClipImage (srcData, transform, quality, (PixelAlpha*) nullptr);
  1444. }
  1445. return edgeTable.isEmpty() ? Ptr() : Ptr (*this);
  1446. }
  1447. void translate (Point<int> delta) override
  1448. {
  1449. edgeTable.translate ((float) delta.x, delta.y);
  1450. }
  1451. bool clipRegionIntersects (Rectangle<int> r) const override
  1452. {
  1453. return edgeTable.getMaximumBounds().intersects (r);
  1454. }
  1455. Rectangle<int> getClipBounds() const override
  1456. {
  1457. return edgeTable.getMaximumBounds();
  1458. }
  1459. void fillRectWithColour (SavedStateType& state, Rectangle<int> area, PixelARGB colour, bool replaceContents) const override
  1460. {
  1461. auto totalClip = edgeTable.getMaximumBounds();
  1462. auto clipped = totalClip.getIntersection (area);
  1463. if (! clipped.isEmpty())
  1464. {
  1465. EdgeTableRegion et (clipped);
  1466. et.edgeTable.clipToEdgeTable (edgeTable);
  1467. state.fillWithSolidColour (et.edgeTable, colour, replaceContents);
  1468. }
  1469. }
  1470. void fillRectWithColour (SavedStateType& state, Rectangle<float> area, PixelARGB colour) const override
  1471. {
  1472. auto totalClip = edgeTable.getMaximumBounds().toFloat();
  1473. auto clipped = totalClip.getIntersection (area);
  1474. if (! clipped.isEmpty())
  1475. {
  1476. EdgeTableRegion et (clipped);
  1477. et.edgeTable.clipToEdgeTable (edgeTable);
  1478. state.fillWithSolidColour (et.edgeTable, colour, false);
  1479. }
  1480. }
  1481. void fillAllWithColour (SavedStateType& state, PixelARGB colour, bool replaceContents) const override
  1482. {
  1483. state.fillWithSolidColour (edgeTable, colour, replaceContents);
  1484. }
  1485. void fillAllWithGradient (SavedStateType& state, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const override
  1486. {
  1487. state.fillWithGradient (edgeTable, gradient, transform, isIdentity);
  1488. }
  1489. void renderImageTransformed (SavedStateType& state, const Image& src, int alpha, const AffineTransform& transform, Graphics::ResamplingQuality quality, bool tiledFill) const override
  1490. {
  1491. state.renderImageTransformed (edgeTable, src, alpha, transform, quality, tiledFill);
  1492. }
  1493. void renderImageUntransformed (SavedStateType& state, const Image& src, int alpha, int x, int y, bool tiledFill) const override
  1494. {
  1495. state.renderImageUntransformed (edgeTable, src, alpha, x, y, tiledFill);
  1496. }
  1497. EdgeTable edgeTable;
  1498. private:
  1499. template <class SrcPixelType>
  1500. void transformedClipImage (const Image::BitmapData& srcData, const AffineTransform& transform, Graphics::ResamplingQuality quality, const SrcPixelType*)
  1501. {
  1502. EdgeTableFillers::TransformedImageFill<SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, transform, 255, quality);
  1503. for (int y = 0; y < edgeTable.getMaximumBounds().getHeight(); ++y)
  1504. renderer.clipEdgeTableLine (edgeTable, edgeTable.getMaximumBounds().getX(), y + edgeTable.getMaximumBounds().getY(),
  1505. edgeTable.getMaximumBounds().getWidth());
  1506. }
  1507. template <class SrcPixelType>
  1508. void straightClipImage (const Image::BitmapData& srcData, int imageX, int imageY, const SrcPixelType*)
  1509. {
  1510. Rectangle<int> r (imageX, imageY, srcData.width, srcData.height);
  1511. edgeTable.clipToRectangle (r);
  1512. EdgeTableFillers::ImageFill<SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, 255, imageX, imageY);
  1513. for (int y = 0; y < r.getHeight(); ++y)
  1514. renderer.clipEdgeTableLine (edgeTable, r.getX(), y + r.getY(), r.getWidth());
  1515. }
  1516. };
  1517. //==============================================================================
  1518. class RectangleListRegion : public Base
  1519. {
  1520. public:
  1521. RectangleListRegion (Rectangle<int> r) : clip (r) {}
  1522. RectangleListRegion (const RectangleList<int>& r) : clip (r) {}
  1523. RectangleListRegion (const RectangleListRegion& other) : Base(), clip (other.clip) {}
  1524. using Ptr = typename Base::Ptr;
  1525. Ptr clone() const override { return *new RectangleListRegion (*this); }
  1526. Ptr applyClipTo (const Ptr& target) const override { return target->clipToRectangleList (clip); }
  1527. Ptr clipToRectangle (Rectangle<int> r) override
  1528. {
  1529. clip.clipTo (r);
  1530. return clip.isEmpty() ? Ptr() : Ptr (*this);
  1531. }
  1532. Ptr clipToRectangleList (const RectangleList<int>& r) override
  1533. {
  1534. clip.clipTo (r);
  1535. return clip.isEmpty() ? Ptr() : Ptr (*this);
  1536. }
  1537. Ptr excludeClipRectangle (Rectangle<int> r) override
  1538. {
  1539. clip.subtract (r);
  1540. return clip.isEmpty() ? Ptr() : Ptr (*this);
  1541. }
  1542. Ptr clipToPath (const Path& p, const AffineTransform& transform) override { return toEdgeTable()->clipToPath (p, transform); }
  1543. Ptr clipToEdgeTable (const EdgeTable& et) override { return toEdgeTable()->clipToEdgeTable (et); }
  1544. Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, Graphics::ResamplingQuality quality) override
  1545. {
  1546. return toEdgeTable()->clipToImageAlpha (image, transform, quality);
  1547. }
  1548. void translate (Point<int> delta) override { clip.offsetAll (delta); }
  1549. bool clipRegionIntersects (Rectangle<int> r) const override { return clip.intersects (r); }
  1550. Rectangle<int> getClipBounds() const override { return clip.getBounds(); }
  1551. void fillRectWithColour (SavedStateType& state, Rectangle<int> area, PixelARGB colour, bool replaceContents) const override
  1552. {
  1553. SubRectangleIterator iter (clip, area);
  1554. state.fillWithSolidColour (iter, colour, replaceContents);
  1555. }
  1556. void fillRectWithColour (SavedStateType& state, Rectangle<float> area, PixelARGB colour) const override
  1557. {
  1558. SubRectangleIteratorFloat iter (clip, area);
  1559. state.fillWithSolidColour (iter, colour, false);
  1560. }
  1561. void fillAllWithColour (SavedStateType& state, PixelARGB colour, bool replaceContents) const override
  1562. {
  1563. state.fillWithSolidColour (*this, colour, replaceContents);
  1564. }
  1565. void fillAllWithGradient (SavedStateType& state, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const override
  1566. {
  1567. state.fillWithGradient (*this, gradient, transform, isIdentity);
  1568. }
  1569. void renderImageTransformed (SavedStateType& state, const Image& src, int alpha, const AffineTransform& transform, Graphics::ResamplingQuality quality, bool tiledFill) const override
  1570. {
  1571. state.renderImageTransformed (*this, src, alpha, transform, quality, tiledFill);
  1572. }
  1573. void renderImageUntransformed (SavedStateType& state, const Image& src, int alpha, int x, int y, bool tiledFill) const override
  1574. {
  1575. state.renderImageUntransformed (*this, src, alpha, x, y, tiledFill);
  1576. }
  1577. RectangleList<int> clip;
  1578. //==============================================================================
  1579. template <class Renderer>
  1580. void iterate (Renderer& r) const noexcept
  1581. {
  1582. for (auto& i : clip)
  1583. {
  1584. auto x = i.getX();
  1585. auto w = i.getWidth();
  1586. jassert (w > 0);
  1587. auto bottom = i.getBottom();
  1588. for (int y = i.getY(); y < bottom; ++y)
  1589. {
  1590. r.setEdgeTableYPos (y);
  1591. r.handleEdgeTableLineFull (x, w);
  1592. }
  1593. }
  1594. }
  1595. private:
  1596. //==============================================================================
  1597. class SubRectangleIterator
  1598. {
  1599. public:
  1600. SubRectangleIterator (const RectangleList<int>& clipList, Rectangle<int> clipBounds)
  1601. : clip (clipList), area (clipBounds)
  1602. {}
  1603. template <class Renderer>
  1604. void iterate (Renderer& r) const noexcept
  1605. {
  1606. for (auto& i : clip)
  1607. {
  1608. auto rect = i.getIntersection (area);
  1609. if (! rect.isEmpty())
  1610. r.handleEdgeTableRectangleFull (rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight());
  1611. }
  1612. }
  1613. private:
  1614. const RectangleList<int>& clip;
  1615. const Rectangle<int> area;
  1616. JUCE_DECLARE_NON_COPYABLE (SubRectangleIterator)
  1617. };
  1618. //==============================================================================
  1619. class SubRectangleIteratorFloat
  1620. {
  1621. public:
  1622. SubRectangleIteratorFloat (const RectangleList<int>& clipList, Rectangle<float> clipBounds) noexcept
  1623. : clip (clipList), area (clipBounds)
  1624. {
  1625. }
  1626. template <class Renderer>
  1627. void iterate (Renderer& r) const noexcept
  1628. {
  1629. const RenderingHelpers::FloatRectangleRasterisingInfo f (area);
  1630. for (auto& i : clip)
  1631. {
  1632. auto clipLeft = i.getX();
  1633. auto clipRight = i.getRight();
  1634. auto clipTop = i.getY();
  1635. auto clipBottom = i.getBottom();
  1636. if (f.totalBottom > clipTop && f.totalTop < clipBottom
  1637. && f.totalRight > clipLeft && f.totalLeft < clipRight)
  1638. {
  1639. if (f.isOnePixelWide())
  1640. {
  1641. if (f.topAlpha != 0 && f.totalTop >= clipTop)
  1642. {
  1643. r.setEdgeTableYPos (f.totalTop);
  1644. r.handleEdgeTablePixel (f.left, f.topAlpha);
  1645. }
  1646. auto y1 = jmax (clipTop, f.top);
  1647. auto y2 = jmin (f.bottom, clipBottom);
  1648. auto h = y2 - y1;
  1649. if (h > 0)
  1650. r.handleEdgeTableRectangleFull (f.left, y1, 1, h);
  1651. if (f.bottomAlpha != 0 && f.bottom < clipBottom)
  1652. {
  1653. r.setEdgeTableYPos (f.bottom);
  1654. r.handleEdgeTablePixel (f.left, f.bottomAlpha);
  1655. }
  1656. }
  1657. else
  1658. {
  1659. auto clippedLeft = jmax (f.left, clipLeft);
  1660. auto clippedWidth = jmin (f.right, clipRight) - clippedLeft;
  1661. bool doLeftAlpha = f.leftAlpha != 0 && f.totalLeft >= clipLeft;
  1662. bool doRightAlpha = f.rightAlpha != 0 && f.right < clipRight;
  1663. if (f.topAlpha != 0 && f.totalTop >= clipTop)
  1664. {
  1665. r.setEdgeTableYPos (f.totalTop);
  1666. if (doLeftAlpha) r.handleEdgeTablePixel (f.totalLeft, f.getTopLeftCornerAlpha());
  1667. if (clippedWidth > 0) r.handleEdgeTableLine (clippedLeft, clippedWidth, f.topAlpha);
  1668. if (doRightAlpha) r.handleEdgeTablePixel (f.right, f.getTopRightCornerAlpha());
  1669. }
  1670. auto y1 = jmax (clipTop, f.top);
  1671. auto y2 = jmin (f.bottom, clipBottom);
  1672. auto h = y2 - y1;
  1673. if (h > 0)
  1674. {
  1675. if (h == 1)
  1676. {
  1677. r.setEdgeTableYPos (y1);
  1678. if (doLeftAlpha) r.handleEdgeTablePixel (f.totalLeft, f.leftAlpha);
  1679. if (clippedWidth > 0) r.handleEdgeTableLineFull (clippedLeft, clippedWidth);
  1680. if (doRightAlpha) r.handleEdgeTablePixel (f.right, f.rightAlpha);
  1681. }
  1682. else
  1683. {
  1684. if (doLeftAlpha) r.handleEdgeTableRectangle (f.totalLeft, y1, 1, h, f.leftAlpha);
  1685. if (clippedWidth > 0) r.handleEdgeTableRectangleFull (clippedLeft, y1, clippedWidth, h);
  1686. if (doRightAlpha) r.handleEdgeTableRectangle (f.right, y1, 1, h, f.rightAlpha);
  1687. }
  1688. }
  1689. if (f.bottomAlpha != 0 && f.bottom < clipBottom)
  1690. {
  1691. r.setEdgeTableYPos (f.bottom);
  1692. if (doLeftAlpha) r.handleEdgeTablePixel (f.totalLeft, f.getBottomLeftCornerAlpha());
  1693. if (clippedWidth > 0) r.handleEdgeTableLine (clippedLeft, clippedWidth, f.bottomAlpha);
  1694. if (doRightAlpha) r.handleEdgeTablePixel (f.right, f.getBottomRightCornerAlpha());
  1695. }
  1696. }
  1697. }
  1698. }
  1699. }
  1700. private:
  1701. const RectangleList<int>& clip;
  1702. Rectangle<float> area;
  1703. JUCE_DECLARE_NON_COPYABLE (SubRectangleIteratorFloat)
  1704. };
  1705. Ptr toEdgeTable() const { return *new EdgeTableRegion (clip); }
  1706. RectangleListRegion& operator= (const RectangleListRegion&) = delete;
  1707. };
  1708. };
  1709. //==============================================================================
  1710. template <class SavedStateType>
  1711. class SavedStateBase
  1712. {
  1713. public:
  1714. using BaseRegionType = typename ClipRegions<SavedStateType>::Base;
  1715. using EdgeTableRegionType = typename ClipRegions<SavedStateType>::EdgeTableRegion;
  1716. using RectangleListRegionType = typename ClipRegions<SavedStateType>::RectangleListRegion;
  1717. SavedStateBase (Rectangle<int> initialClip)
  1718. : clip (new RectangleListRegionType (initialClip)),
  1719. interpolationQuality (Graphics::mediumResamplingQuality), transparencyLayerAlpha (1.0f)
  1720. {
  1721. }
  1722. SavedStateBase (const RectangleList<int>& clipList, Point<int> origin)
  1723. : clip (new RectangleListRegionType (clipList)), transform (origin),
  1724. interpolationQuality (Graphics::mediumResamplingQuality), transparencyLayerAlpha (1.0f)
  1725. {
  1726. }
  1727. SavedStateBase (const SavedStateBase& other)
  1728. : clip (other.clip), transform (other.transform), fillType (other.fillType),
  1729. interpolationQuality (other.interpolationQuality),
  1730. transparencyLayerAlpha (other.transparencyLayerAlpha)
  1731. {
  1732. }
  1733. SavedStateType& getThis() noexcept { return *static_cast<SavedStateType*> (this); }
  1734. bool clipToRectangle (Rectangle<int> r)
  1735. {
  1736. if (clip != nullptr)
  1737. {
  1738. if (transform.isOnlyTranslated)
  1739. {
  1740. cloneClipIfMultiplyReferenced();
  1741. clip = clip->clipToRectangle (transform.translated (r));
  1742. }
  1743. else if (! transform.isRotated)
  1744. {
  1745. cloneClipIfMultiplyReferenced();
  1746. clip = clip->clipToRectangle (transform.transformed (r));
  1747. }
  1748. else
  1749. {
  1750. Path p;
  1751. p.addRectangle (r);
  1752. clipToPath (p, {});
  1753. }
  1754. }
  1755. return clip != nullptr;
  1756. }
  1757. bool clipToRectangleList (const RectangleList<int>& r)
  1758. {
  1759. if (clip != nullptr)
  1760. {
  1761. if (transform.isOnlyTranslated)
  1762. {
  1763. cloneClipIfMultiplyReferenced();
  1764. if (transform.isIdentity())
  1765. {
  1766. clip = clip->clipToRectangleList (r);
  1767. }
  1768. else
  1769. {
  1770. RectangleList<int> offsetList (r);
  1771. offsetList.offsetAll (transform.offset);
  1772. clip = clip->clipToRectangleList (offsetList);
  1773. }
  1774. }
  1775. else if (! transform.isRotated)
  1776. {
  1777. cloneClipIfMultiplyReferenced();
  1778. RectangleList<int> scaledList;
  1779. for (auto& i : r)
  1780. scaledList.add (transform.transformed (i));
  1781. clip = clip->clipToRectangleList (scaledList);
  1782. }
  1783. else
  1784. {
  1785. clipToPath (r.toPath(), {});
  1786. }
  1787. }
  1788. return clip != nullptr;
  1789. }
  1790. static Rectangle<int> getLargestIntegerWithin (Rectangle<float> r)
  1791. {
  1792. auto x1 = (int) std::ceil (r.getX());
  1793. auto y1 = (int) std::ceil (r.getY());
  1794. auto x2 = (int) std::floor (r.getRight());
  1795. auto y2 = (int) std::floor (r.getBottom());
  1796. return { x1, y1, x2 - x1, y2 - y1 };
  1797. }
  1798. bool excludeClipRectangle (Rectangle<int> r)
  1799. {
  1800. if (clip != nullptr)
  1801. {
  1802. cloneClipIfMultiplyReferenced();
  1803. if (transform.isOnlyTranslated)
  1804. {
  1805. clip = clip->excludeClipRectangle (getLargestIntegerWithin (transform.translated (r.toFloat())));
  1806. }
  1807. else if (! transform.isRotated)
  1808. {
  1809. clip = clip->excludeClipRectangle (getLargestIntegerWithin (transform.transformed (r.toFloat())));
  1810. }
  1811. else
  1812. {
  1813. Path p;
  1814. p.addRectangle (r.toFloat());
  1815. p.applyTransform (transform.complexTransform);
  1816. p.addRectangle (clip->getClipBounds().toFloat());
  1817. p.setUsingNonZeroWinding (false);
  1818. clip = clip->clipToPath (p, {});
  1819. }
  1820. }
  1821. return clip != nullptr;
  1822. }
  1823. void clipToPath (const Path& p, const AffineTransform& t)
  1824. {
  1825. if (clip != nullptr)
  1826. {
  1827. cloneClipIfMultiplyReferenced();
  1828. clip = clip->clipToPath (p, transform.getTransformWith (t));
  1829. }
  1830. }
  1831. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& t)
  1832. {
  1833. if (clip != nullptr)
  1834. {
  1835. if (sourceImage.hasAlphaChannel())
  1836. {
  1837. cloneClipIfMultiplyReferenced();
  1838. clip = clip->clipToImageAlpha (sourceImage, transform.getTransformWith (t), interpolationQuality);
  1839. }
  1840. else
  1841. {
  1842. Path p;
  1843. p.addRectangle (sourceImage.getBounds());
  1844. clipToPath (p, t);
  1845. }
  1846. }
  1847. }
  1848. bool clipRegionIntersects (Rectangle<int> r) const
  1849. {
  1850. if (clip != nullptr)
  1851. {
  1852. if (transform.isOnlyTranslated)
  1853. return clip->clipRegionIntersects (transform.translated (r));
  1854. return getClipBounds().intersects (r);
  1855. }
  1856. return false;
  1857. }
  1858. Rectangle<int> getClipBounds() const
  1859. {
  1860. return clip != nullptr ? transform.deviceSpaceToUserSpace (clip->getClipBounds())
  1861. : Rectangle<int>();
  1862. }
  1863. void setFillType (const FillType& newFill)
  1864. {
  1865. fillType = newFill;
  1866. }
  1867. void fillTargetRect (Rectangle<int> r, bool replaceContents)
  1868. {
  1869. if (fillType.isColour())
  1870. {
  1871. clip->fillRectWithColour (getThis(), r, fillType.colour.getPixelARGB(), replaceContents);
  1872. }
  1873. else
  1874. {
  1875. auto clipped = clip->getClipBounds().getIntersection (r);
  1876. if (! clipped.isEmpty())
  1877. fillShape (*new RectangleListRegionType (clipped), false);
  1878. }
  1879. }
  1880. void fillTargetRect (Rectangle<float> r)
  1881. {
  1882. if (fillType.isColour())
  1883. {
  1884. clip->fillRectWithColour (getThis(), r, fillType.colour.getPixelARGB());
  1885. }
  1886. else
  1887. {
  1888. auto clipped = clip->getClipBounds().toFloat().getIntersection (r);
  1889. if (! clipped.isEmpty())
  1890. fillShape (*new EdgeTableRegionType (clipped), false);
  1891. }
  1892. }
  1893. template <typename CoordType>
  1894. void fillRectAsPath (Rectangle<CoordType> r)
  1895. {
  1896. Path p;
  1897. p.addRectangle (r);
  1898. fillPath (p, {});
  1899. }
  1900. void fillRect (Rectangle<int> r, bool replaceContents)
  1901. {
  1902. if (clip != nullptr)
  1903. {
  1904. if (transform.isOnlyTranslated)
  1905. {
  1906. fillTargetRect (transform.translated (r), replaceContents);
  1907. }
  1908. else if (! transform.isRotated)
  1909. {
  1910. fillTargetRect (transform.transformed (r), replaceContents);
  1911. }
  1912. else
  1913. {
  1914. jassert (! replaceContents); // not implemented..
  1915. fillRectAsPath (r);
  1916. }
  1917. }
  1918. }
  1919. void fillRect (Rectangle<float> r)
  1920. {
  1921. if (clip != nullptr)
  1922. {
  1923. if (transform.isOnlyTranslated)
  1924. fillTargetRect (transform.translated (r));
  1925. else if (! transform.isRotated)
  1926. fillTargetRect (transform.transformed (r));
  1927. else
  1928. fillRectAsPath (r);
  1929. }
  1930. }
  1931. void fillRectList (const RectangleList<float>& list)
  1932. {
  1933. if (clip != nullptr)
  1934. {
  1935. if (list.getNumRectangles() == 1)
  1936. return fillRect (*list.begin());
  1937. if (transform.isIdentity())
  1938. {
  1939. fillShape (*new EdgeTableRegionType (list), false);
  1940. }
  1941. else if (! transform.isRotated)
  1942. {
  1943. RectangleList<float> transformed (list);
  1944. if (transform.isOnlyTranslated)
  1945. transformed.offsetAll (transform.offset.toFloat());
  1946. else
  1947. transformed.transformAll (transform.getTransform());
  1948. fillShape (*new EdgeTableRegionType (transformed), false);
  1949. }
  1950. else
  1951. {
  1952. fillPath (list.toPath(), {});
  1953. }
  1954. }
  1955. }
  1956. void fillPath (const Path& path, const AffineTransform& t)
  1957. {
  1958. if (clip != nullptr)
  1959. {
  1960. auto trans = transform.getTransformWith (t);
  1961. auto clipRect = clip->getClipBounds();
  1962. if (path.getBoundsTransformed (trans).getSmallestIntegerContainer().intersects (clipRect))
  1963. fillShape (*new EdgeTableRegionType (clipRect, path, trans), false);
  1964. }
  1965. }
  1966. void fillEdgeTable (const EdgeTable& edgeTable, float x, int y)
  1967. {
  1968. if (clip != nullptr)
  1969. {
  1970. auto* edgeTableClip = new EdgeTableRegionType (edgeTable);
  1971. edgeTableClip->edgeTable.translate (x, y);
  1972. if (fillType.isColour())
  1973. {
  1974. auto brightness = fillType.colour.getBrightness() - 0.5f;
  1975. if (brightness > 0.0f)
  1976. edgeTableClip->edgeTable.multiplyLevels (1.0f + 1.6f * brightness);
  1977. }
  1978. fillShape (*edgeTableClip, false);
  1979. }
  1980. }
  1981. void drawLine (Line<float> line)
  1982. {
  1983. Path p;
  1984. p.addLineSegment (line, 1.0f);
  1985. fillPath (p, {});
  1986. }
  1987. void drawImage (const Image& sourceImage, const AffineTransform& trans)
  1988. {
  1989. if (clip != nullptr && ! fillType.colour.isTransparent())
  1990. renderImage (sourceImage, trans, {});
  1991. }
  1992. static bool isOnlyTranslationAllowingError (const AffineTransform& t, float tolerance) noexcept
  1993. {
  1994. return std::abs (t.mat01) < tolerance
  1995. && std::abs (t.mat10) < tolerance
  1996. && std::abs (t.mat00 - 1.0f) < tolerance
  1997. && std::abs (t.mat11 - 1.0f) < tolerance;
  1998. }
  1999. void renderImage (const Image& sourceImage, const AffineTransform& trans, const BaseRegionType* tiledFillClipRegion)
  2000. {
  2001. auto t = transform.getTransformWith (trans);
  2002. auto alpha = fillType.colour.getAlpha();
  2003. if (isOnlyTranslationAllowingError (t, 0.002f))
  2004. {
  2005. // If our translation doesn't involve any distortion, just use a simple blit..
  2006. auto tx = (int) (t.getTranslationX() * 256.0f);
  2007. auto ty = (int) (t.getTranslationY() * 256.0f);
  2008. if (interpolationQuality == Graphics::lowResamplingQuality || ((tx | ty) & 224) == 0)
  2009. {
  2010. tx = ((tx + 128) >> 8);
  2011. ty = ((ty + 128) >> 8);
  2012. if (tiledFillClipRegion != nullptr)
  2013. {
  2014. tiledFillClipRegion->renderImageUntransformed (getThis(), sourceImage, alpha, tx, ty, true);
  2015. }
  2016. else
  2017. {
  2018. Rectangle<int> area (tx, ty, sourceImage.getWidth(), sourceImage.getHeight());
  2019. area = area.getIntersection (getThis().getMaximumBounds());
  2020. if (! area.isEmpty())
  2021. if (auto c = clip->applyClipTo (*new EdgeTableRegionType (area)))
  2022. c->renderImageUntransformed (getThis(), sourceImage, alpha, tx, ty, false);
  2023. }
  2024. return;
  2025. }
  2026. }
  2027. if (! t.isSingularity())
  2028. {
  2029. if (tiledFillClipRegion != nullptr)
  2030. {
  2031. tiledFillClipRegion->renderImageTransformed (getThis(), sourceImage, alpha,
  2032. t, interpolationQuality, true);
  2033. }
  2034. else
  2035. {
  2036. Path p;
  2037. p.addRectangle (sourceImage.getBounds());
  2038. if (auto c = clip->clone()->clipToPath (p, t))
  2039. c->renderImageTransformed (getThis(), sourceImage, alpha,
  2040. t, interpolationQuality, false);
  2041. }
  2042. }
  2043. }
  2044. void fillShape (typename BaseRegionType::Ptr shapeToFill, bool replaceContents)
  2045. {
  2046. jassert (clip != nullptr);
  2047. shapeToFill = clip->applyClipTo (shapeToFill);
  2048. if (shapeToFill != nullptr)
  2049. {
  2050. if (fillType.isGradient())
  2051. {
  2052. jassert (! replaceContents); // that option is just for solid colours
  2053. auto g2 = *(fillType.gradient);
  2054. g2.multiplyOpacity (fillType.getOpacity());
  2055. auto t = transform.getTransformWith (fillType.transform).translated (-0.5f, -0.5f);
  2056. bool isIdentity = t.isOnlyTranslation();
  2057. if (isIdentity)
  2058. {
  2059. // If our translation doesn't involve any distortion, we can speed it up..
  2060. g2.point1.applyTransform (t);
  2061. g2.point2.applyTransform (t);
  2062. t = {};
  2063. }
  2064. shapeToFill->fillAllWithGradient (getThis(), g2, t, isIdentity);
  2065. }
  2066. else if (fillType.isTiledImage())
  2067. {
  2068. renderImage (fillType.image, fillType.transform, shapeToFill.get());
  2069. }
  2070. else
  2071. {
  2072. shapeToFill->fillAllWithColour (getThis(), fillType.colour.getPixelARGB(), replaceContents);
  2073. }
  2074. }
  2075. }
  2076. void cloneClipIfMultiplyReferenced()
  2077. {
  2078. if (clip->getReferenceCount() > 1)
  2079. clip = clip->clone();
  2080. }
  2081. typename BaseRegionType::Ptr clip;
  2082. RenderingHelpers::TranslationOrTransform transform;
  2083. FillType fillType;
  2084. Graphics::ResamplingQuality interpolationQuality;
  2085. float transparencyLayerAlpha;
  2086. };
  2087. //==============================================================================
  2088. class SoftwareRendererSavedState : public SavedStateBase<SoftwareRendererSavedState>
  2089. {
  2090. using BaseClass = SavedStateBase<SoftwareRendererSavedState>;
  2091. public:
  2092. SoftwareRendererSavedState (const Image& im, Rectangle<int> clipBounds)
  2093. : BaseClass (clipBounds), image (im)
  2094. {
  2095. }
  2096. SoftwareRendererSavedState (const Image& im, const RectangleList<int>& clipList, Point<int> origin)
  2097. : BaseClass (clipList, origin), image (im)
  2098. {
  2099. }
  2100. SoftwareRendererSavedState (const SoftwareRendererSavedState& other) = default;
  2101. SoftwareRendererSavedState* beginTransparencyLayer (float opacity)
  2102. {
  2103. auto* s = new SoftwareRendererSavedState (*this);
  2104. if (clip != nullptr)
  2105. {
  2106. auto layerBounds = clip->getClipBounds();
  2107. s->image = Image (Image::ARGB, layerBounds.getWidth(), layerBounds.getHeight(), true);
  2108. s->transparencyLayerAlpha = opacity;
  2109. s->transform.moveOriginInDeviceSpace (-layerBounds.getPosition());
  2110. s->cloneClipIfMultiplyReferenced();
  2111. s->clip->translate (-layerBounds.getPosition());
  2112. }
  2113. return s;
  2114. }
  2115. void endTransparencyLayer (SoftwareRendererSavedState& finishedLayerState)
  2116. {
  2117. if (clip != nullptr)
  2118. {
  2119. auto layerBounds = clip->getClipBounds();
  2120. auto g = image.createLowLevelContext();
  2121. g->setOpacity (finishedLayerState.transparencyLayerAlpha);
  2122. g->drawImage (finishedLayerState.image, AffineTransform::translation (layerBounds.getPosition()));
  2123. }
  2124. }
  2125. using GlyphCacheType = GlyphCache<CachedGlyphEdgeTable<SoftwareRendererSavedState>, SoftwareRendererSavedState>;
  2126. static void clearGlyphCache()
  2127. {
  2128. GlyphCacheType::getInstance().reset();
  2129. }
  2130. //==============================================================================
  2131. void drawGlyph (int glyphNumber, const AffineTransform& trans)
  2132. {
  2133. if (clip != nullptr)
  2134. {
  2135. if (trans.isOnlyTranslation() && ! transform.isRotated)
  2136. {
  2137. auto& cache = GlyphCacheType::getInstance();
  2138. Point<float> pos (trans.getTranslationX(), trans.getTranslationY());
  2139. if (transform.isOnlyTranslated)
  2140. {
  2141. cache.drawGlyph (*this, font, glyphNumber, pos + transform.offset.toFloat());
  2142. }
  2143. else
  2144. {
  2145. pos = transform.transformed (pos);
  2146. Font f (font);
  2147. f.setHeight (font.getHeight() * transform.complexTransform.mat11);
  2148. auto xScale = transform.complexTransform.mat00 / transform.complexTransform.mat11;
  2149. if (std::abs (xScale - 1.0f) > 0.01f)
  2150. f.setHorizontalScale (xScale);
  2151. cache.drawGlyph (*this, f, glyphNumber, pos);
  2152. }
  2153. }
  2154. else
  2155. {
  2156. auto fontHeight = font.getHeight();
  2157. auto t = transform.getTransformWith (AffineTransform::scale (fontHeight * font.getHorizontalScale(), fontHeight)
  2158. .followedBy (trans));
  2159. std::unique_ptr<EdgeTable> et (font.getTypefacePtr()->getEdgeTableForGlyph (glyphNumber, t, fontHeight));
  2160. if (et != nullptr)
  2161. fillShape (*new EdgeTableRegionType (*et), false);
  2162. }
  2163. }
  2164. }
  2165. Rectangle<int> getMaximumBounds() const { return image.getBounds(); }
  2166. //==============================================================================
  2167. template <typename IteratorType>
  2168. void renderImageTransformed (IteratorType& iter, const Image& src, int alpha, const AffineTransform& trans, Graphics::ResamplingQuality quality, bool tiledFill) const
  2169. {
  2170. Image::BitmapData destData (image, Image::BitmapData::readWrite);
  2171. const Image::BitmapData srcData (src, Image::BitmapData::readOnly);
  2172. EdgeTableFillers::renderImageTransformed (iter, destData, srcData, alpha, trans, quality, tiledFill);
  2173. }
  2174. template <typename IteratorType>
  2175. void renderImageUntransformed (IteratorType& iter, const Image& src, int alpha, int x, int y, bool tiledFill) const
  2176. {
  2177. Image::BitmapData destData (image, Image::BitmapData::readWrite);
  2178. const Image::BitmapData srcData (src, Image::BitmapData::readOnly);
  2179. EdgeTableFillers::renderImageUntransformed (iter, destData, srcData, alpha, x, y, tiledFill);
  2180. }
  2181. template <typename IteratorType>
  2182. void fillWithSolidColour (IteratorType& iter, PixelARGB colour, bool replaceContents) const
  2183. {
  2184. Image::BitmapData destData (image, Image::BitmapData::readWrite);
  2185. switch (destData.pixelFormat)
  2186. {
  2187. case Image::ARGB: EdgeTableFillers::renderSolidFill (iter, destData, colour, replaceContents, (PixelARGB*) nullptr); break;
  2188. case Image::RGB: EdgeTableFillers::renderSolidFill (iter, destData, colour, replaceContents, (PixelRGB*) nullptr); break;
  2189. case Image::SingleChannel:
  2190. case Image::UnknownFormat:
  2191. default: EdgeTableFillers::renderSolidFill (iter, destData, colour, replaceContents, (PixelAlpha*) nullptr); break;
  2192. }
  2193. }
  2194. template <typename IteratorType>
  2195. void fillWithGradient (IteratorType& iter, ColourGradient& gradient, const AffineTransform& trans, bool isIdentity) const
  2196. {
  2197. HeapBlock<PixelARGB> lookupTable;
  2198. auto numLookupEntries = gradient.createLookupTable (trans, lookupTable);
  2199. jassert (numLookupEntries > 0);
  2200. Image::BitmapData destData (image, Image::BitmapData::readWrite);
  2201. switch (destData.pixelFormat)
  2202. {
  2203. case Image::ARGB: EdgeTableFillers::renderGradient (iter, destData, gradient, trans, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) nullptr); break;
  2204. case Image::RGB: EdgeTableFillers::renderGradient (iter, destData, gradient, trans, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) nullptr); break;
  2205. case Image::SingleChannel:
  2206. case Image::UnknownFormat:
  2207. default: EdgeTableFillers::renderGradient (iter, destData, gradient, trans, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) nullptr); break;
  2208. }
  2209. }
  2210. //==============================================================================
  2211. Image image;
  2212. Font font;
  2213. private:
  2214. SoftwareRendererSavedState& operator= (const SoftwareRendererSavedState&) = delete;
  2215. };
  2216. //==============================================================================
  2217. template <class StateObjectType>
  2218. class SavedStateStack
  2219. {
  2220. public:
  2221. SavedStateStack (StateObjectType* initialState) noexcept
  2222. : currentState (initialState)
  2223. {}
  2224. SavedStateStack() = default;
  2225. void initialise (StateObjectType* state)
  2226. {
  2227. currentState.reset (state);
  2228. }
  2229. inline StateObjectType* operator->() const noexcept { return currentState.get(); }
  2230. inline StateObjectType& operator*() const noexcept { return *currentState; }
  2231. void save()
  2232. {
  2233. stack.add (new StateObjectType (*currentState));
  2234. }
  2235. void restore()
  2236. {
  2237. if (auto* top = stack.getLast())
  2238. {
  2239. currentState.reset (top);
  2240. stack.removeLast (1, false);
  2241. }
  2242. else
  2243. {
  2244. jassertfalse; // trying to pop with an empty stack!
  2245. }
  2246. }
  2247. void beginTransparencyLayer (float opacity)
  2248. {
  2249. save();
  2250. currentState.reset (currentState->beginTransparencyLayer (opacity));
  2251. }
  2252. void endTransparencyLayer()
  2253. {
  2254. std::unique_ptr<StateObjectType> finishedTransparencyLayer (currentState.release());
  2255. restore();
  2256. currentState->endTransparencyLayer (*finishedTransparencyLayer);
  2257. }
  2258. private:
  2259. std::unique_ptr<StateObjectType> currentState;
  2260. OwnedArray<StateObjectType> stack;
  2261. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SavedStateStack)
  2262. };
  2263. //==============================================================================
  2264. template <class SavedStateType>
  2265. class StackBasedLowLevelGraphicsContext : public LowLevelGraphicsContext
  2266. {
  2267. public:
  2268. bool isVectorDevice() const override { return false; }
  2269. void setOrigin (Point<int> o) override { stack->transform.setOrigin (o); }
  2270. void addTransform (const AffineTransform& t) override { stack->transform.addTransform (t); }
  2271. float getPhysicalPixelScaleFactor() override { return stack->transform.getPhysicalPixelScaleFactor(); }
  2272. Rectangle<int> getClipBounds() const override { return stack->getClipBounds(); }
  2273. bool isClipEmpty() const override { return stack->clip == nullptr; }
  2274. bool clipRegionIntersects (const Rectangle<int>& r) override { return stack->clipRegionIntersects (r); }
  2275. bool clipToRectangle (const Rectangle<int>& r) override { return stack->clipToRectangle (r); }
  2276. bool clipToRectangleList (const RectangleList<int>& r) override { return stack->clipToRectangleList (r); }
  2277. void excludeClipRectangle (const Rectangle<int>& r) override { stack->excludeClipRectangle (r); }
  2278. void clipToPath (const Path& path, const AffineTransform& t) override { stack->clipToPath (path, t); }
  2279. void clipToImageAlpha (const Image& im, const AffineTransform& t) override { stack->clipToImageAlpha (im, t); }
  2280. void saveState() override { stack.save(); }
  2281. void restoreState() override { stack.restore(); }
  2282. void beginTransparencyLayer (float opacity) override { stack.beginTransparencyLayer (opacity); }
  2283. void endTransparencyLayer() override { stack.endTransparencyLayer(); }
  2284. void setFill (const FillType& fillType) override { stack->setFillType (fillType); }
  2285. void setOpacity (float newOpacity) override { stack->fillType.setOpacity (newOpacity); }
  2286. void setInterpolationQuality (Graphics::ResamplingQuality quality) override { stack->interpolationQuality = quality; }
  2287. void fillRect (const Rectangle<int>& r, bool replace) override { stack->fillRect (r, replace); }
  2288. void fillRect (const Rectangle<float>& r) override { stack->fillRect (r); }
  2289. void fillRectList (const RectangleList<float>& list) override { stack->fillRectList (list); }
  2290. void fillPath (const Path& path, const AffineTransform& t) override { stack->fillPath (path, t); }
  2291. void drawImage (const Image& im, const AffineTransform& t) override { stack->drawImage (im, t); }
  2292. void drawGlyph (int glyphNumber, const AffineTransform& t) override { stack->drawGlyph (glyphNumber, t); }
  2293. void drawLine (const Line<float>& line) override { stack->drawLine (line); }
  2294. void setFont (const Font& newFont) override { stack->font = newFont; }
  2295. const Font& getFont() override { return stack->font; }
  2296. protected:
  2297. StackBasedLowLevelGraphicsContext (SavedStateType* initialState) : stack (initialState) {}
  2298. StackBasedLowLevelGraphicsContext() = default;
  2299. RenderingHelpers::SavedStateStack<SavedStateType> stack;
  2300. };
  2301. }
  2302. JUCE_END_IGNORE_WARNINGS_MSVC
  2303. } // namespace juce