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.

2772 lines
104KB

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