The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
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.

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