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.

779 lines
30KB

  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. #include <juce_core/system/juce_TargetPlatform.h>
  19. #if JucePlugin_Build_Unity
  20. #include "../utility/juce_IncludeModuleHeaders.h"
  21. #include <juce_audio_processors/format_types/juce_LegacyAudioParameter.cpp>
  22. #if JUCE_WINDOWS
  23. #include "../utility/juce_IncludeSystemHeaders.h"
  24. #endif
  25. #include "juce_UnityPluginInterface.h"
  26. //==============================================================================
  27. namespace juce
  28. {
  29. typedef ComponentPeer* (*createUnityPeerFunctionType) (Component&);
  30. extern createUnityPeerFunctionType juce_createUnityPeerFn;
  31. //==============================================================================
  32. class UnityPeer : public ComponentPeer,
  33. public AsyncUpdater
  34. {
  35. public:
  36. UnityPeer (Component& ed)
  37. : ComponentPeer (ed, 0),
  38. mouseWatcher (*this)
  39. {
  40. getEditor().setResizable (false, false);
  41. }
  42. //==============================================================================
  43. Rectangle<int> getBounds() const override { return bounds; }
  44. Point<float> localToGlobal (Point<float> relativePosition) override { return relativePosition + getBounds().getPosition().toFloat(); }
  45. Point<float> globalToLocal (Point<float> screenPosition) override { return screenPosition - getBounds().getPosition().toFloat(); }
  46. using ComponentPeer::localToGlobal;
  47. using ComponentPeer::globalToLocal;
  48. StringArray getAvailableRenderingEngines() override { return StringArray ("Software Renderer"); }
  49. void setBounds (const Rectangle<int>& newBounds, bool) override
  50. {
  51. bounds = newBounds;
  52. mouseWatcher.setBoundsToWatch (bounds);
  53. }
  54. bool contains (Point<int> localPos, bool) const override
  55. {
  56. if (isPositiveAndBelow (localPos.getX(), getBounds().getWidth())
  57. && isPositiveAndBelow (localPos.getY(), getBounds().getHeight()))
  58. return true;
  59. return false;
  60. }
  61. void handleAsyncUpdate() override
  62. {
  63. fillPixels();
  64. }
  65. //==============================================================================
  66. AudioProcessorEditor& getEditor() { return *dynamic_cast<AudioProcessorEditor*> (&getComponent()); }
  67. void setPixelDataHandle (uint8* handle, int width, int height)
  68. {
  69. pixelData = handle;
  70. textureWidth = width;
  71. textureHeight = height;
  72. renderImage = Image (new UnityBitmapImage (pixelData, width, height));
  73. }
  74. // N.B. This is NOT an efficient way to do this and you shouldn't use this method in your own code.
  75. // It works for our purposes here but a much more efficient way would be to use a GL texture.
  76. void fillPixels()
  77. {
  78. if (pixelData == nullptr)
  79. return;
  80. LowLevelGraphicsSoftwareRenderer renderer (renderImage);
  81. renderer.addTransform (AffineTransform::verticalFlip ((float) getComponent().getHeight()));
  82. handlePaint (renderer);
  83. for (int i = 0; i < textureWidth * textureHeight * 4; i += 4)
  84. {
  85. auto r = pixelData[i + 2];
  86. auto g = pixelData[i + 1];
  87. auto b = pixelData[i + 0];
  88. pixelData[i + 0] = r;
  89. pixelData[i + 1] = g;
  90. pixelData[i + 2] = b;
  91. }
  92. }
  93. void forwardMouseEvent (Point<float> position, ModifierKeys mods)
  94. {
  95. ModifierKeys::currentModifiers = mods;
  96. handleMouseEvent (juce::MouseInputSource::mouse, position, mods, juce::MouseInputSource::defaultPressure,
  97. juce::MouseInputSource::defaultOrientation, juce::Time::currentTimeMillis());
  98. }
  99. void forwardKeyPress (int code, String name, ModifierKeys mods)
  100. {
  101. ModifierKeys::currentModifiers = mods;
  102. handleKeyPress (getKeyPress (code, name));
  103. }
  104. private:
  105. //==============================================================================
  106. struct UnityBitmapImage : public ImagePixelData
  107. {
  108. UnityBitmapImage (uint8* data, int w, int h)
  109. : ImagePixelData (Image::PixelFormat::ARGB, w, h),
  110. imageData (data),
  111. lineStride (width * pixelStride)
  112. {
  113. }
  114. std::unique_ptr<ImageType> createType() const override
  115. {
  116. return std::make_unique<SoftwareImageType>();
  117. }
  118. std::unique_ptr<LowLevelGraphicsContext> createLowLevelContext() override
  119. {
  120. return std::make_unique<LowLevelGraphicsSoftwareRenderer> (Image (this));
  121. }
  122. void initialiseBitmapData (Image::BitmapData& bitmap, int x, int y, [[maybe_unused]] Image::BitmapData::ReadWriteMode mode) override
  123. {
  124. const auto offset = (size_t) x * (size_t) pixelStride + (size_t) y * (size_t) lineStride;
  125. bitmap.data = imageData + offset;
  126. bitmap.size = (size_t) (lineStride * height) - offset;
  127. bitmap.pixelFormat = pixelFormat;
  128. bitmap.lineStride = lineStride;
  129. bitmap.pixelStride = pixelStride;
  130. }
  131. ImagePixelData::Ptr clone() override
  132. {
  133. auto im = new UnityBitmapImage (imageData, width, height);
  134. for (int i = 0; i < height; ++i)
  135. memcpy (im->imageData + i * lineStride, imageData + i * lineStride, (size_t) lineStride);
  136. return im;
  137. }
  138. uint8* imageData;
  139. int pixelStride = 4, lineStride;
  140. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (UnityBitmapImage)
  141. };
  142. //==============================================================================
  143. struct MouseWatcher : public Timer
  144. {
  145. MouseWatcher (ComponentPeer& o) : owner (o) {}
  146. void timerCallback() override
  147. {
  148. auto pos = Desktop::getMousePosition();
  149. if (boundsToWatch.contains (pos) && pos != lastMousePos)
  150. {
  151. auto ms = Desktop::getInstance().getMainMouseSource();
  152. if (! ms.getCurrentModifiers().isLeftButtonDown())
  153. owner.handleMouseEvent (juce::MouseInputSource::mouse, owner.globalToLocal (pos.toFloat()), {},
  154. juce::MouseInputSource::defaultPressure, juce::MouseInputSource::defaultOrientation, juce::Time::currentTimeMillis());
  155. lastMousePos = pos;
  156. }
  157. }
  158. void setBoundsToWatch (Rectangle<int> b)
  159. {
  160. if (boundsToWatch != b)
  161. boundsToWatch = b;
  162. startTimer (250);
  163. }
  164. ComponentPeer& owner;
  165. Rectangle<int> boundsToWatch;
  166. Point<int> lastMousePos;
  167. };
  168. //==============================================================================
  169. KeyPress getKeyPress (int keyCode, String name)
  170. {
  171. if (keyCode >= 32 && keyCode <= 64)
  172. return { keyCode, ModifierKeys::currentModifiers, juce::juce_wchar (keyCode) };
  173. if (keyCode >= 91 && keyCode <= 122)
  174. return { keyCode, ModifierKeys::currentModifiers, name[0] };
  175. if (keyCode >= 256 && keyCode <= 265)
  176. return { juce::KeyPress::numberPad0 + (keyCode - 256), ModifierKeys::currentModifiers, juce::String (keyCode - 256).getCharPointer()[0] };
  177. if (keyCode == 8) return { juce::KeyPress::backspaceKey, ModifierKeys::currentModifiers, {} };
  178. if (keyCode == 127) return { juce::KeyPress::deleteKey, ModifierKeys::currentModifiers, {} };
  179. if (keyCode == 9) return { juce::KeyPress::tabKey, ModifierKeys::currentModifiers, {} };
  180. if (keyCode == 13) return { juce::KeyPress::returnKey, ModifierKeys::currentModifiers, {} };
  181. if (keyCode == 27) return { juce::KeyPress::escapeKey, ModifierKeys::currentModifiers, {} };
  182. if (keyCode == 32) return { juce::KeyPress::spaceKey, ModifierKeys::currentModifiers, {} };
  183. if (keyCode == 266) return { juce::KeyPress::numberPadDecimalPoint, ModifierKeys::currentModifiers, {} };
  184. if (keyCode == 267) return { juce::KeyPress::numberPadDivide, ModifierKeys::currentModifiers, {} };
  185. if (keyCode == 268) return { juce::KeyPress::numberPadMultiply, ModifierKeys::currentModifiers, {} };
  186. if (keyCode == 269) return { juce::KeyPress::numberPadSubtract, ModifierKeys::currentModifiers, {} };
  187. if (keyCode == 270) return { juce::KeyPress::numberPadAdd, ModifierKeys::currentModifiers, {} };
  188. if (keyCode == 272) return { juce::KeyPress::numberPadEquals, ModifierKeys::currentModifiers, {} };
  189. if (keyCode == 273) return { juce::KeyPress::upKey, ModifierKeys::currentModifiers, {} };
  190. if (keyCode == 274) return { juce::KeyPress::downKey, ModifierKeys::currentModifiers, {} };
  191. if (keyCode == 275) return { juce::KeyPress::rightKey, ModifierKeys::currentModifiers, {} };
  192. if (keyCode == 276) return { juce::KeyPress::leftKey, ModifierKeys::currentModifiers, {} };
  193. return {};
  194. }
  195. //==============================================================================
  196. Rectangle<int> bounds;
  197. MouseWatcher mouseWatcher;
  198. uint8* pixelData = nullptr;
  199. int textureWidth, textureHeight;
  200. Image renderImage;
  201. //==============================================================================
  202. void setMinimised (bool) override {}
  203. bool isMinimised() const override { return false; }
  204. void setFullScreen (bool) override {}
  205. bool isFullScreen() const override { return false; }
  206. bool setAlwaysOnTop (bool) override { return false; }
  207. void toFront (bool) override {}
  208. void toBehind (ComponentPeer*) override {}
  209. bool isFocused() const override { return true; }
  210. void grabFocus() override {}
  211. void* getNativeHandle() const override { return nullptr; }
  212. OptionalBorderSize getFrameSizeIfPresent() const override { return {}; }
  213. BorderSize<int> getFrameSize() const override { return {}; }
  214. void setVisible (bool) override {}
  215. void setTitle (const String&) override {}
  216. void setIcon (const Image&) override {}
  217. void textInputRequired (Point<int>, TextInputTarget&) override {}
  218. void setAlpha (float) override {}
  219. void performAnyPendingRepaintsNow() override {}
  220. void repaint (const Rectangle<int>&) override {}
  221. //==============================================================================
  222. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (UnityPeer)
  223. };
  224. static ComponentPeer* createUnityPeer (Component& c) { return new UnityPeer (c); }
  225. //==============================================================================
  226. class AudioProcessorUnityWrapper
  227. {
  228. public:
  229. AudioProcessorUnityWrapper (bool isTemporary)
  230. {
  231. pluginInstance.reset (createPluginFilterOfType (AudioProcessor::wrapperType_Unity));
  232. if (! isTemporary && pluginInstance->hasEditor())
  233. {
  234. pluginInstanceEditor.reset (pluginInstance->createEditorIfNeeded());
  235. pluginInstanceEditor->setVisible (true);
  236. pluginInstanceEditor->addToDesktop (0);
  237. }
  238. juceParameters.update (*pluginInstance, false);
  239. }
  240. ~AudioProcessorUnityWrapper()
  241. {
  242. if (pluginInstanceEditor != nullptr)
  243. {
  244. pluginInstanceEditor->removeFromDesktop();
  245. PopupMenu::dismissAllActiveMenus();
  246. pluginInstanceEditor->processor.editorBeingDeleted (pluginInstanceEditor.get());
  247. pluginInstanceEditor = nullptr;
  248. }
  249. }
  250. void create (UnityAudioEffectState* state)
  251. {
  252. // only supported in Unity plugin API > 1.0
  253. if (state->structSize >= sizeof (UnityAudioEffectState))
  254. samplesPerBlock = static_cast<int> (state->dspBufferSize);
  255. #ifdef JucePlugin_PreferredChannelConfigurations
  256. short configs[][2] = { JucePlugin_PreferredChannelConfigurations };
  257. const int numConfigs = sizeof (configs) / sizeof (short[2]);
  258. jassertquiet (numConfigs > 0 && (configs[0][0] > 0 || configs[0][1] > 0));
  259. pluginInstance->setPlayConfigDetails (configs[0][0], configs[0][1], state->sampleRate, samplesPerBlock);
  260. #else
  261. pluginInstance->setRateAndBufferSizeDetails (state->sampleRate, samplesPerBlock);
  262. #endif
  263. pluginInstance->prepareToPlay (state->sampleRate, samplesPerBlock);
  264. scratchBuffer.setSize (jmax (pluginInstance->getTotalNumInputChannels(), pluginInstance->getTotalNumOutputChannels()), samplesPerBlock);
  265. }
  266. void release()
  267. {
  268. pluginInstance->releaseResources();
  269. }
  270. void reset()
  271. {
  272. pluginInstance->reset();
  273. }
  274. void process (float* inBuffer, float* outBuffer, int bufferSize, int numInChannels, int numOutChannels, bool isBypassed)
  275. {
  276. // If the plugin has a bypass parameter, set it to the current bypass state
  277. if (auto* param = pluginInstance->getBypassParameter())
  278. if (isBypassed != (param->getValue() >= 0.5f))
  279. param->setValueNotifyingHost (isBypassed ? 1.0f : 0.0f);
  280. for (int pos = 0; pos < bufferSize;)
  281. {
  282. auto max = jmin (bufferSize - pos, samplesPerBlock);
  283. processBuffers (inBuffer + (pos * numInChannels), outBuffer + (pos * numOutChannels), max, numInChannels, numOutChannels, isBypassed);
  284. pos += max;
  285. }
  286. }
  287. void declareParameters (UnityAudioEffectDefinition& definition)
  288. {
  289. static std::unique_ptr<UnityAudioParameterDefinition> parametersPtr;
  290. static int numParams = 0;
  291. if (parametersPtr == nullptr)
  292. {
  293. numParams = (int) juceParameters.size();
  294. parametersPtr.reset (static_cast<UnityAudioParameterDefinition*> (std::calloc (static_cast<size_t> (numParams),
  295. sizeof (UnityAudioParameterDefinition))));
  296. parameterDescriptions.clear();
  297. for (int i = 0; i < numParams; ++i)
  298. {
  299. auto* parameter = juceParameters.getParamForIndex (i);
  300. auto& paramDef = parametersPtr.get()[i];
  301. const auto nameLength = (size_t) numElementsInArray (paramDef.name);
  302. const auto unitLength = (size_t) numElementsInArray (paramDef.unit);
  303. parameter->getName ((int) nameLength - 1).copyToUTF8 (paramDef.name, nameLength);
  304. if (parameter->getLabel().isNotEmpty())
  305. parameter->getLabel().copyToUTF8 (paramDef.unit, unitLength);
  306. parameterDescriptions.add (parameter->getName (15));
  307. paramDef.description = parameterDescriptions[i].toRawUTF8();
  308. paramDef.defaultVal = parameter->getDefaultValue();
  309. paramDef.min = 0.0f;
  310. paramDef.max = 1.0f;
  311. paramDef.displayScale = 1.0f;
  312. paramDef.displayExponent = 1.0f;
  313. }
  314. }
  315. definition.numParameters = static_cast<uint32> (numParams);
  316. definition.parameterDefintions = parametersPtr.get();
  317. }
  318. void setParameter (int index, float value) { juceParameters.getParamForIndex (index)->setValueNotifyingHost (value); }
  319. float getParameter (int index) const noexcept { return juceParameters.getParamForIndex (index)->getValue(); }
  320. String getParameterString (int index) const noexcept
  321. {
  322. auto* param = juceParameters.getParamForIndex (index);
  323. return param->getText (param->getValue(), 16);
  324. }
  325. int getNumInputChannels() const noexcept { return pluginInstance->getTotalNumInputChannels(); }
  326. int getNumOutputChannels() const noexcept { return pluginInstance->getTotalNumOutputChannels(); }
  327. bool hasEditor() const noexcept { return pluginInstance->hasEditor(); }
  328. UnityPeer& getEditorPeer() const
  329. {
  330. auto* peer = dynamic_cast<UnityPeer*> (pluginInstanceEditor->getPeer());
  331. jassert (peer != nullptr);
  332. return *peer;
  333. }
  334. private:
  335. //==============================================================================
  336. void processBuffers (float* inBuffer, float* outBuffer, int bufferSize, int numInChannels, int numOutChannels, bool isBypassed)
  337. {
  338. int ch;
  339. for (ch = 0; ch < numInChannels; ++ch)
  340. {
  341. using DstSampleType = AudioData::Pointer<AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst>;
  342. using SrcSampleType = AudioData::Pointer<AudioData::Float32, AudioData::NativeEndian, AudioData::Interleaved, AudioData::Const>;
  343. DstSampleType dstData (scratchBuffer.getWritePointer (ch));
  344. SrcSampleType srcData (inBuffer + ch, numInChannels);
  345. dstData.convertSamples (srcData, bufferSize);
  346. }
  347. for (; ch < numOutChannels; ++ch)
  348. scratchBuffer.clear (ch, 0, bufferSize);
  349. {
  350. const ScopedLock sl (pluginInstance->getCallbackLock());
  351. if (pluginInstance->isSuspended())
  352. {
  353. scratchBuffer.clear();
  354. }
  355. else
  356. {
  357. MidiBuffer mb;
  358. if (isBypassed && pluginInstance->getBypassParameter() == nullptr)
  359. pluginInstance->processBlockBypassed (scratchBuffer, mb);
  360. else
  361. pluginInstance->processBlock (scratchBuffer, mb);
  362. }
  363. }
  364. for (ch = 0; ch < numOutChannels; ++ch)
  365. {
  366. using DstSampleType = AudioData::Pointer<AudioData::Float32, AudioData::NativeEndian, AudioData::Interleaved, AudioData::NonConst>;
  367. using SrcSampleType = AudioData::Pointer<AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const>;
  368. DstSampleType dstData (outBuffer + ch, numOutChannels);
  369. SrcSampleType srcData (scratchBuffer.getReadPointer (ch));
  370. dstData.convertSamples (srcData, bufferSize);
  371. }
  372. }
  373. //==============================================================================
  374. std::unique_ptr<AudioProcessor> pluginInstance;
  375. std::unique_ptr<AudioProcessorEditor> pluginInstanceEditor;
  376. int samplesPerBlock = 1024;
  377. StringArray parameterDescriptions;
  378. AudioBuffer<float> scratchBuffer;
  379. LegacyAudioParametersWrapper juceParameters;
  380. //==============================================================================
  381. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioProcessorUnityWrapper)
  382. };
  383. //==============================================================================
  384. static HashMap<int, AudioProcessorUnityWrapper*>& getWrapperMap()
  385. {
  386. static HashMap<int, AudioProcessorUnityWrapper*> wrapperMap;
  387. return wrapperMap;
  388. }
  389. static void onWrapperCreation (AudioProcessorUnityWrapper* wrapperToAdd)
  390. {
  391. getWrapperMap().set (std::abs (Random::getSystemRandom().nextInt (65536)), wrapperToAdd);
  392. }
  393. static void onWrapperDeletion (AudioProcessorUnityWrapper* wrapperToRemove)
  394. {
  395. getWrapperMap().removeValue (wrapperToRemove);
  396. }
  397. //==============================================================================
  398. static UnityAudioEffectDefinition getEffectDefinition()
  399. {
  400. const auto wrapper = std::make_unique<AudioProcessorUnityWrapper> (true);
  401. const String originalName { JucePlugin_Name };
  402. const auto name = (! originalName.startsWithIgnoreCase ("audioplugin") ? "audioplugin_" : "") + originalName;
  403. UnityAudioEffectDefinition result{};
  404. name.copyToUTF8 (result.name, (size_t) numElementsInArray (result.name));
  405. result.structSize = sizeof (UnityAudioEffectDefinition);
  406. result.parameterStructSize = sizeof (UnityAudioParameterDefinition);
  407. result.apiVersion = UNITY_AUDIO_PLUGIN_API_VERSION;
  408. result.pluginVersion = JucePlugin_VersionCode;
  409. // effects must set this to 0, generators > 0
  410. result.channels = (wrapper->getNumInputChannels() != 0 ? 0
  411. : static_cast<uint32> (wrapper->getNumOutputChannels()));
  412. wrapper->declareParameters (result);
  413. result.create = [] (UnityAudioEffectState* state)
  414. {
  415. auto* pluginInstance = new AudioProcessorUnityWrapper (false);
  416. pluginInstance->create (state);
  417. state->effectData = pluginInstance;
  418. onWrapperCreation (pluginInstance);
  419. return 0;
  420. };
  421. result.release = [] (UnityAudioEffectState* state)
  422. {
  423. auto* pluginInstance = state->getEffectData<AudioProcessorUnityWrapper>();
  424. pluginInstance->release();
  425. onWrapperDeletion (pluginInstance);
  426. delete pluginInstance;
  427. if (getWrapperMap().size() == 0)
  428. shutdownJuce_GUI();
  429. return 0;
  430. };
  431. result.reset = [] (UnityAudioEffectState* state)
  432. {
  433. auto* pluginInstance = state->getEffectData<AudioProcessorUnityWrapper>();
  434. pluginInstance->reset();
  435. return 0;
  436. };
  437. result.setPosition = [] (UnityAudioEffectState* state, unsigned int pos)
  438. {
  439. ignoreUnused (state, pos);
  440. return 0;
  441. };
  442. result.process = [] (UnityAudioEffectState* state,
  443. float* inBuffer,
  444. float* outBuffer,
  445. unsigned int bufferSize,
  446. int numInChannels,
  447. int numOutChannels)
  448. {
  449. auto* pluginInstance = state->getEffectData<AudioProcessorUnityWrapper>();
  450. if (pluginInstance != nullptr)
  451. {
  452. auto isPlaying = ((state->flags & stateIsPlaying) != 0);
  453. auto isMuted = ((state->flags & stateIsMuted) != 0);
  454. auto isPaused = ((state->flags & stateIsPaused) != 0);
  455. const auto bypassed = ! isPlaying || (isMuted || isPaused);
  456. pluginInstance->process (inBuffer, outBuffer, static_cast<int> (bufferSize), numInChannels, numOutChannels, bypassed);
  457. }
  458. else
  459. {
  460. FloatVectorOperations::clear (outBuffer, static_cast<int> (bufferSize) * numOutChannels);
  461. }
  462. return 0;
  463. };
  464. result.setFloatParameter = [] (UnityAudioEffectState* state, int index, float value)
  465. {
  466. auto* pluginInstance = state->getEffectData<AudioProcessorUnityWrapper>();
  467. pluginInstance->setParameter (index, value);
  468. return 0;
  469. };
  470. result.getFloatParameter = [] (UnityAudioEffectState* state, int index, float* value, char* valueStr)
  471. {
  472. auto* pluginInstance = state->getEffectData<AudioProcessorUnityWrapper>();
  473. *value = pluginInstance->getParameter (index);
  474. pluginInstance->getParameterString (index).copyToUTF8 (valueStr, 15);
  475. return 0;
  476. };
  477. result.getFloatBuffer = [] (UnityAudioEffectState* state, const char* kind, float* buffer, int numSamples)
  478. {
  479. ignoreUnused (numSamples);
  480. const StringRef kindStr { kind };
  481. if (kindStr == StringRef ("Editor"))
  482. {
  483. auto* pluginInstance = state->getEffectData<AudioProcessorUnityWrapper>();
  484. buffer[0] = pluginInstance->hasEditor() ? 1.0f : 0.0f;
  485. }
  486. else if (kindStr == StringRef ("ID"))
  487. {
  488. auto* pluginInstance = state->getEffectData<AudioProcessorUnityWrapper>();
  489. for (HashMap<int, AudioProcessorUnityWrapper*>::Iterator i (getWrapperMap()); i.next();)
  490. {
  491. if (i.getValue() == pluginInstance)
  492. {
  493. buffer[0] = (float) i.getKey();
  494. break;
  495. }
  496. }
  497. return 0;
  498. }
  499. else if (kindStr == StringRef ("Size"))
  500. {
  501. auto* pluginInstance = state->getEffectData<AudioProcessorUnityWrapper>();
  502. auto& editor = pluginInstance->getEditorPeer().getEditor();
  503. buffer[0] = (float) editor.getBounds().getWidth();
  504. buffer[1] = (float) editor.getBounds().getHeight();
  505. buffer[2] = (float) editor.getConstrainer()->getMinimumWidth();
  506. buffer[3] = (float) editor.getConstrainer()->getMinimumHeight();
  507. buffer[4] = (float) editor.getConstrainer()->getMaximumWidth();
  508. buffer[5] = (float) editor.getConstrainer()->getMaximumHeight();
  509. }
  510. return 0;
  511. };
  512. return result;
  513. }
  514. } // namespace juce
  515. // From reading the example code, it seems that the triple indirection indicates
  516. // an out-value of an array of pointers. That is, after calling this function, definitionsPtr
  517. // should point to a pre-existing/static array of pointer-to-effect-definition.
  518. UNITY_INTERFACE_EXPORT int UNITY_INTERFACE_API UnityGetAudioEffectDefinitions (UnityAudioEffectDefinition*** definitionsPtr)
  519. {
  520. if (juce::getWrapperMap().size() == 0)
  521. juce::initialiseJuce_GUI();
  522. static std::once_flag flag;
  523. std::call_once (flag, []
  524. {
  525. juce::PluginHostType::jucePlugInClientCurrentWrapperType = juce::AudioProcessor::wrapperType_Unity;
  526. juce::juce_createUnityPeerFn = juce::createUnityPeer;
  527. });
  528. static auto definition = juce::getEffectDefinition();
  529. static UnityAudioEffectDefinition* definitions[] { &definition };
  530. *definitionsPtr = definitions;
  531. return 1;
  532. }
  533. //==============================================================================
  534. static juce::ModifierKeys unityModifiersToJUCE (UnityEventModifiers mods, bool mouseDown, int mouseButton = -1)
  535. {
  536. int flags = 0;
  537. if (mouseDown)
  538. {
  539. if (mouseButton == 0)
  540. flags |= juce::ModifierKeys::leftButtonModifier;
  541. else if (mouseButton == 1)
  542. flags |= juce::ModifierKeys::rightButtonModifier;
  543. else if (mouseButton == 2)
  544. flags |= juce::ModifierKeys::middleButtonModifier;
  545. }
  546. if (mods == 0)
  547. return flags;
  548. if ((mods & UnityEventModifiers::shift) != 0) flags |= juce::ModifierKeys::shiftModifier;
  549. if ((mods & UnityEventModifiers::control) != 0) flags |= juce::ModifierKeys::ctrlModifier;
  550. if ((mods & UnityEventModifiers::alt) != 0) flags |= juce::ModifierKeys::altModifier;
  551. if ((mods & UnityEventModifiers::command) != 0) flags |= juce::ModifierKeys::commandModifier;
  552. return { flags };
  553. }
  554. //==============================================================================
  555. static juce::AudioProcessorUnityWrapper* getWrapperChecked (int id)
  556. {
  557. auto* wrapper = juce::getWrapperMap()[id];
  558. jassert (wrapper != nullptr);
  559. return wrapper;
  560. }
  561. //==============================================================================
  562. static void UNITY_INTERFACE_API onRenderEvent (int id)
  563. {
  564. getWrapperChecked (id)->getEditorPeer().triggerAsyncUpdate();
  565. }
  566. UNITY_INTERFACE_EXPORT renderCallback UNITY_INTERFACE_API getRenderCallback()
  567. {
  568. return onRenderEvent;
  569. }
  570. UNITY_INTERFACE_EXPORT void UNITY_INTERFACE_API unityInitialiseTexture (int id, void* data, int w, int h)
  571. {
  572. getWrapperChecked (id)->getEditorPeer().setPixelDataHandle (reinterpret_cast<juce::uint8*> (data), w, h);
  573. }
  574. UNITY_INTERFACE_EXPORT void UNITY_INTERFACE_API unityMouseDown (int id, float x, float y, UnityEventModifiers unityMods, int button)
  575. {
  576. getWrapperChecked (id)->getEditorPeer().forwardMouseEvent ({ x, y }, unityModifiersToJUCE (unityMods, true, button));
  577. }
  578. UNITY_INTERFACE_EXPORT void UNITY_INTERFACE_API unityMouseDrag (int id, float x, float y, UnityEventModifiers unityMods, int button)
  579. {
  580. getWrapperChecked (id)->getEditorPeer().forwardMouseEvent ({ x, y }, unityModifiersToJUCE (unityMods, true, button));
  581. }
  582. UNITY_INTERFACE_EXPORT void UNITY_INTERFACE_API unityMouseUp (int id, float x, float y, UnityEventModifiers unityMods)
  583. {
  584. getWrapperChecked (id)->getEditorPeer().forwardMouseEvent ({ x, y }, unityModifiersToJUCE (unityMods, false));
  585. }
  586. UNITY_INTERFACE_EXPORT void UNITY_INTERFACE_API unityKeyEvent (int id, int code, UnityEventModifiers mods, const char* name)
  587. {
  588. getWrapperChecked (id)->getEditorPeer().forwardKeyPress (code, name, unityModifiersToJUCE (mods, false));
  589. }
  590. UNITY_INTERFACE_EXPORT void UNITY_INTERFACE_API unitySetScreenBounds (int id, float x, float y, float w, float h)
  591. {
  592. getWrapperChecked (id)->getEditorPeer().getEditor().setBounds ({ (int) x, (int) y, (int) w, (int) h });
  593. }
  594. //==============================================================================
  595. #if JUCE_WINDOWS
  596. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wmissing-prototypes")
  597. extern "C" BOOL WINAPI DllMain (HINSTANCE instance, DWORD reason, LPVOID)
  598. {
  599. if (reason == DLL_PROCESS_ATTACH)
  600. juce::Process::setCurrentModuleInstanceHandle (instance);
  601. return true;
  602. }
  603. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  604. #endif
  605. #endif