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.

528 lines
16KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2022 - Raw Material Software Limited
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 7 End-User License
  8. Agreement and JUCE Privacy Policy.
  9. End User License Agreement: www.juce.com/juce-7-licence
  10. Privacy Policy: www.juce.com/juce-privacy-policy
  11. Or: You may also use this code under the terms of the GPL v3 (see
  12. www.gnu.org/licenses).
  13. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  14. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  15. DISCLAIMED.
  16. ==============================================================================
  17. */
  18. /**
  19. This scene description is broadcast to all the clients, and contains a list of all
  20. the clients involved, as well as the set of shapes to be drawn.
  21. Each client will draw the part of the path that lies within its own area. It can
  22. find its area by looking at the list of clients contained in this structure.
  23. All the path coordinates are roughly in units of inches, and devices will convert
  24. this to pixels based on their screen size and DPI
  25. */
  26. struct SharedCanvasDescription
  27. {
  28. SharedCanvasDescription() {}
  29. Colour backgroundColour = Colours::black;
  30. struct ColouredPath
  31. {
  32. Path path;
  33. FillType fill;
  34. };
  35. Array<ColouredPath> paths;
  36. struct ClientArea
  37. {
  38. String name;
  39. Point<float> centre; // in inches
  40. float scaleFactor; // extra scaling
  41. };
  42. Array<ClientArea> clients;
  43. //==============================================================================
  44. void reset()
  45. {
  46. paths.clearQuick();
  47. clients.clearQuick();
  48. }
  49. void swapWith (SharedCanvasDescription& other)
  50. {
  51. std::swap (backgroundColour, other.backgroundColour);
  52. paths.swapWith (other.paths);
  53. clients.swapWith (other.clients);
  54. }
  55. // This is a fixed size that represents the overall canvas limits that
  56. // content should lie within
  57. Rectangle<float> getLimits() const
  58. {
  59. float inchesX = 60.0f;
  60. float inchesY = 30.0f;
  61. return { inchesX * -0.5f, inchesY * -0.5f, inchesX, inchesY };
  62. }
  63. //==============================================================================
  64. void draw (Graphics& g, Rectangle<float> targetArea, Rectangle<float> clientArea) const
  65. {
  66. draw (g, clientArea,
  67. AffineTransform::fromTargetPoints (clientArea.getX(), clientArea.getY(),
  68. targetArea.getX(), targetArea.getY(),
  69. clientArea.getRight(), clientArea.getY(),
  70. targetArea.getRight(), targetArea.getY(),
  71. clientArea.getRight(), clientArea.getBottom(),
  72. targetArea.getRight(), targetArea.getBottom()));
  73. }
  74. void draw (Graphics& g, Rectangle<float> clientArea, AffineTransform t) const
  75. {
  76. g.saveState();
  77. g.addTransform (t);
  78. for (const auto& p : paths)
  79. {
  80. if (p.path.getBounds().intersects (clientArea))
  81. {
  82. g.setFillType (p.fill);
  83. g.fillPath (p.path);
  84. }
  85. }
  86. g.restoreState();
  87. }
  88. const ClientArea* findClient (const String& clientName) const
  89. {
  90. for (const auto& c : clients)
  91. if (c.name == clientName)
  92. return &c;
  93. return nullptr;
  94. }
  95. //==============================================================================
  96. // Serialisation...
  97. void save (OutputStream& out) const
  98. {
  99. out.writeInt (magic);
  100. out.writeInt ((int) backgroundColour.getARGB());
  101. out.writeInt (clients.size());
  102. for (const auto& c : clients)
  103. {
  104. out.writeString (c.name);
  105. writePoint (out, c.centre);
  106. out.writeFloat (c.scaleFactor);
  107. }
  108. out.writeInt (paths.size());
  109. for (const auto& p : paths)
  110. {
  111. writeFill (out, p.fill);
  112. p.path.writePathToStream (out);
  113. }
  114. }
  115. void load (InputStream& in)
  116. {
  117. if (in.readInt() != magic)
  118. return;
  119. backgroundColour = Colour ((uint32) in.readInt());
  120. {
  121. const int numClients = in.readInt();
  122. clients.clearQuick();
  123. for (int i = 0; i < numClients; ++i)
  124. {
  125. ClientArea c;
  126. c.name = in.readString();
  127. c.centre = readPoint (in);
  128. c.scaleFactor = in.readFloat();
  129. clients.add (c);
  130. }
  131. }
  132. {
  133. const int numPaths = in.readInt();
  134. paths.clearQuick();
  135. for (int i = 0; i < numPaths; ++i)
  136. {
  137. ColouredPath p;
  138. p.fill = readFill (in);
  139. p.path.loadPathFromStream (in);
  140. paths.add (std::move (p));
  141. }
  142. }
  143. }
  144. MemoryBlock toMemoryBlock() const
  145. {
  146. MemoryOutputStream o;
  147. save (o);
  148. return o.getMemoryBlock();
  149. }
  150. private:
  151. //==============================================================================
  152. static void writePoint (OutputStream& out, Point<float> p)
  153. {
  154. out.writeFloat (p.x);
  155. out.writeFloat (p.y);
  156. }
  157. static void writeRect (OutputStream& out, Rectangle<float> r)
  158. {
  159. writePoint (out, r.getPosition());
  160. out.writeFloat (r.getWidth());
  161. out.writeFloat (r.getHeight());
  162. }
  163. static Point<float> readPoint (InputStream& in)
  164. {
  165. Point<float> p;
  166. p.x = in.readFloat();
  167. p.y = in.readFloat();
  168. return p;
  169. }
  170. static Rectangle<float> readRect (InputStream& in)
  171. {
  172. Rectangle<float> r;
  173. r.setPosition (readPoint (in));
  174. r.setWidth (in.readFloat());
  175. r.setHeight (in.readFloat());
  176. return r;
  177. }
  178. static void writeFill (OutputStream& out, const FillType& f)
  179. {
  180. if (f.isColour())
  181. {
  182. out.writeByte (0);
  183. out.writeInt ((int) f.colour.getARGB());
  184. }
  185. else if (f.isGradient())
  186. {
  187. const ColourGradient& cg = *f.gradient;
  188. jassert (cg.getNumColours() >= 2);
  189. out.writeByte (cg.isRadial ? 2 : 1);
  190. writePoint (out, cg.point1);
  191. writePoint (out, cg.point2);
  192. out.writeCompressedInt (cg.getNumColours());
  193. for (int i = 0; i < cg.getNumColours(); ++i)
  194. {
  195. out.writeDouble (cg.getColourPosition (i));
  196. out.writeInt ((int) cg.getColour(i).getARGB());
  197. }
  198. }
  199. else
  200. {
  201. jassertfalse;
  202. }
  203. }
  204. static FillType readFill (InputStream& in)
  205. {
  206. int type = in.readByte();
  207. if (type == 0)
  208. return FillType (Colour ((uint32) in.readInt()));
  209. if (type > 2)
  210. {
  211. jassertfalse;
  212. return FillType();
  213. }
  214. ColourGradient cg;
  215. cg.point1 = readPoint (in);
  216. cg.point2 = readPoint (in);
  217. cg.clearColours();
  218. int numColours = in.readCompressedInt();
  219. for (int i = 0; i < numColours; ++i)
  220. {
  221. const double pos = in.readDouble();
  222. cg.addColour (pos, Colour ((uint32) in.readInt()));
  223. }
  224. jassert (cg.getNumColours() >= 2);
  225. return FillType (cg);
  226. }
  227. const int magic = 0x2381239a;
  228. JUCE_DECLARE_NON_COPYABLE (SharedCanvasDescription)
  229. };
  230. //==============================================================================
  231. class CanvasGeneratingContext : public LowLevelGraphicsContext
  232. {
  233. public:
  234. CanvasGeneratingContext (SharedCanvasDescription& c) : canvas (c)
  235. {
  236. stateStack.add (new SavedState());
  237. }
  238. //==============================================================================
  239. bool isVectorDevice() const override { return true; }
  240. float getPhysicalPixelScaleFactor() override { return 1.0f; }
  241. void setOrigin (Point<int> o) override { addTransform (AffineTransform::translation ((float) o.x, (float) o.y)); }
  242. void addTransform (const AffineTransform& t) override
  243. {
  244. getState().transform = t.followedBy (getState().transform);
  245. }
  246. bool clipToRectangle (const Rectangle<int>&) override { return true; }
  247. bool clipToRectangleList (const RectangleList<int>&) override { return true; }
  248. void excludeClipRectangle (const Rectangle<int>&) override {}
  249. void clipToPath (const Path&, const AffineTransform&) override {}
  250. void clipToImageAlpha (const Image&, const AffineTransform&) override {}
  251. void saveState() override
  252. {
  253. stateStack.add (new SavedState (getState()));
  254. }
  255. void restoreState() override
  256. {
  257. jassert (stateStack.size() > 0);
  258. if (stateStack.size() > 0)
  259. stateStack.removeLast();
  260. }
  261. void beginTransparencyLayer (float alpha) override
  262. {
  263. saveState();
  264. getState().transparencyLayer = new SharedCanvasHolder();
  265. getState().transparencyOpacity = alpha;
  266. }
  267. void endTransparencyLayer() override
  268. {
  269. const ReferenceCountedObjectPtr<SharedCanvasHolder> finishedTransparencyLayer (getState().transparencyLayer);
  270. float alpha = getState().transparencyOpacity;
  271. restoreState();
  272. if (SharedCanvasHolder* c = finishedTransparencyLayer)
  273. {
  274. for (auto& path : c->canvas.paths)
  275. {
  276. path.fill.setOpacity (path.fill.getOpacity() * alpha);
  277. getTargetCanvas().paths.add (path);
  278. }
  279. }
  280. }
  281. Rectangle<int> getClipBounds() const override
  282. {
  283. return canvas.getLimits().getSmallestIntegerContainer()
  284. .transformedBy (getState().transform.inverted());
  285. }
  286. bool clipRegionIntersects (const Rectangle<int>&) override { return true; }
  287. bool isClipEmpty() const override { return false; }
  288. //==============================================================================
  289. void setFill (const FillType& fillType) override { getState().fillType = fillType; }
  290. void setOpacity (float op) override { getState().fillType.setOpacity (op); }
  291. void setInterpolationQuality (Graphics::ResamplingQuality) override {}
  292. //==============================================================================
  293. void fillRect (const Rectangle<int>& r, bool) override { fillRect (r.toFloat()); }
  294. void fillRectList (const RectangleList<float>& list) override { fillPath (list.toPath(), AffineTransform()); }
  295. void fillRect (const Rectangle<float>& r) override
  296. {
  297. Path p;
  298. p.addRectangle (r.toFloat());
  299. fillPath (p, AffineTransform());
  300. }
  301. void fillPath (const Path& p, const AffineTransform& t) override
  302. {
  303. Path p2 (p);
  304. p2.applyTransform (t.followedBy (getState().transform));
  305. getTargetCanvas().paths.add ({ std::move (p2), getState().fillType });
  306. }
  307. void drawImage (const Image&, const AffineTransform&) override {}
  308. void drawLine (const Line<float>& line) override
  309. {
  310. Path p;
  311. p.addLineSegment (line, 1.0f);
  312. fillPath (p, AffineTransform());
  313. }
  314. //==============================================================================
  315. const Font& getFont() override { return getState().font; }
  316. void setFont (const Font& newFont) override { getState().font = newFont; }
  317. void drawGlyph (int glyphNumber, const AffineTransform& transform) override
  318. {
  319. Path p;
  320. Font& font = getState().font;
  321. font.getTypefacePtr()->getOutlineForGlyph (glyphNumber, p);
  322. fillPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight()).followedBy (transform));
  323. }
  324. private:
  325. //==============================================================================
  326. struct SharedCanvasHolder : public ReferenceCountedObject
  327. {
  328. SharedCanvasDescription canvas;
  329. };
  330. struct SavedState
  331. {
  332. FillType fillType;
  333. AffineTransform transform;
  334. Font font;
  335. ReferenceCountedObjectPtr<SharedCanvasHolder> transparencyLayer;
  336. float transparencyOpacity = 1.0f;
  337. };
  338. SharedCanvasDescription& getTargetCanvas() const
  339. {
  340. if (SharedCanvasHolder* c = getState().transparencyLayer)
  341. return c->canvas;
  342. return canvas;
  343. }
  344. SavedState& getState() const noexcept
  345. {
  346. jassert (stateStack.size() > 0);
  347. return *stateStack.getLast();
  348. }
  349. SharedCanvasDescription& canvas;
  350. OwnedArray<SavedState> stateStack;
  351. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CanvasGeneratingContext)
  352. };
  353. //==============================================================================
  354. /** Helper for breaking and reassembling a memory block into smaller checksummed
  355. blocks that will fit inside UDP packets
  356. */
  357. struct BlockPacketiser
  358. {
  359. void createBlocksFromData (const MemoryBlock& data, size_t maxBlockSize)
  360. {
  361. jassert (blocks.size() == 0);
  362. int offset = 0;
  363. size_t remaining = data.getSize();
  364. while (remaining > 0)
  365. {
  366. auto num = (size_t) jmin (maxBlockSize, remaining);
  367. blocks.add (MemoryBlock (addBytesToPointer (data.getData(), offset), num));
  368. offset += (int) num;
  369. remaining -= num;
  370. }
  371. MemoryOutputStream checksumBlock;
  372. checksumBlock << getLastPacketPrefix() << MD5 (data).toHexString() << (char) 0 << (char) 0;
  373. blocks.add (checksumBlock.getMemoryBlock());
  374. for (int i = 0; i < blocks.size(); ++i)
  375. {
  376. auto index = (uint32) ByteOrder::swapIfBigEndian (i);
  377. blocks.getReference(i).append (&index, sizeof (index));
  378. }
  379. }
  380. // returns true if this is an end-of-sequence block
  381. bool appendIncomingBlock (MemoryBlock data)
  382. {
  383. if (data.getSize() > 4)
  384. blocks.addSorted (*this, data);
  385. return String (CharPointer_ASCII ((const char*) data.getData())).startsWith (getLastPacketPrefix());
  386. }
  387. bool reassemble (MemoryBlock& result)
  388. {
  389. result.reset();
  390. if (blocks.size() > 1)
  391. {
  392. for (int i = 0; i < blocks.size() - 1; ++i)
  393. result.append (blocks.getReference(i).getData(), blocks.getReference(i).getSize() - 4);
  394. String storedMD5 (String (CharPointer_ASCII ((const char*) blocks.getLast().getData()))
  395. .fromFirstOccurrenceOf (getLastPacketPrefix(), false, false));
  396. blocks.clearQuick();
  397. if (MD5 (result).toHexString().trim().equalsIgnoreCase (storedMD5.trim()))
  398. return true;
  399. }
  400. result.reset();
  401. return false;
  402. }
  403. static int compareElements (const MemoryBlock& b1, const MemoryBlock& b2)
  404. {
  405. auto i1 = ByteOrder::littleEndianInt (addBytesToPointer (b1.getData(), b1.getSize() - 4));
  406. auto i2 = ByteOrder::littleEndianInt (addBytesToPointer (b2.getData(), b2.getSize() - 4));
  407. return (int) (i1 - i2);
  408. }
  409. static const char* getLastPacketPrefix() { return "**END_OF_PACKET_LIST** "; }
  410. Array<MemoryBlock> blocks;
  411. };
  412. //==============================================================================
  413. struct AnimatedContent
  414. {
  415. virtual ~AnimatedContent() {}
  416. virtual String getName() const = 0;
  417. virtual void reset() = 0;
  418. virtual void generateCanvas (Graphics&, SharedCanvasDescription& canvas, Rectangle<float> activeArea) = 0;
  419. virtual void handleTouch (Point<float> position) = 0;
  420. };