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.

782 lines
30KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2020 - 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 6 End-User License
  8. Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
  9. End User License Agreement: www.juce.com/juce-6-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::invalidPressure,
  97. juce::MouseInputSource::invalidOrientation, 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, Image::BitmapData::ReadWriteMode mode) override
  123. {
  124. ignoreUnused (mode);
  125. bitmap.data = imageData + x * pixelStride + y * lineStride;
  126. bitmap.pixelFormat = pixelFormat;
  127. bitmap.lineStride = lineStride;
  128. bitmap.pixelStride = pixelStride;
  129. }
  130. ImagePixelData::Ptr clone() override
  131. {
  132. auto im = new UnityBitmapImage (imageData, width, height);
  133. for (int i = 0; i < height; ++i)
  134. memcpy (im->imageData + i * lineStride, imageData + i * lineStride, (size_t) lineStride);
  135. return im;
  136. }
  137. uint8* imageData;
  138. int pixelStride = 4, lineStride;
  139. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (UnityBitmapImage)
  140. };
  141. //==============================================================================
  142. struct MouseWatcher : public Timer
  143. {
  144. MouseWatcher (ComponentPeer& o) : owner (o) {}
  145. void timerCallback() override
  146. {
  147. auto pos = Desktop::getMousePosition();
  148. if (boundsToWatch.contains (pos) && pos != lastMousePos)
  149. {
  150. auto ms = Desktop::getInstance().getMainMouseSource();
  151. if (! ms.getCurrentModifiers().isLeftButtonDown())
  152. owner.handleMouseEvent (juce::MouseInputSource::mouse, owner.globalToLocal (pos.toFloat()), {},
  153. juce::MouseInputSource::invalidPressure, juce::MouseInputSource::invalidOrientation, juce::Time::currentTimeMillis());
  154. lastMousePos = pos;
  155. }
  156. }
  157. void setBoundsToWatch (Rectangle<int> b)
  158. {
  159. if (boundsToWatch != b)
  160. boundsToWatch = b;
  161. startTimer (250);
  162. }
  163. ComponentPeer& owner;
  164. Rectangle<int> boundsToWatch;
  165. Point<int> lastMousePos;
  166. };
  167. //==============================================================================
  168. KeyPress getKeyPress (int keyCode, String name)
  169. {
  170. if (keyCode >= 32 && keyCode <= 64)
  171. return { keyCode, ModifierKeys::currentModifiers, juce::juce_wchar (keyCode) };
  172. if (keyCode >= 91 && keyCode <= 122)
  173. return { keyCode, ModifierKeys::currentModifiers, name[0] };
  174. if (keyCode >= 256 && keyCode <= 265)
  175. return { juce::KeyPress::numberPad0 + (keyCode - 256), ModifierKeys::currentModifiers, juce::String (keyCode - 256).getCharPointer()[0] };
  176. if (keyCode == 8) return { juce::KeyPress::backspaceKey, ModifierKeys::currentModifiers, {} };
  177. if (keyCode == 127) return { juce::KeyPress::deleteKey, ModifierKeys::currentModifiers, {} };
  178. if (keyCode == 9) return { juce::KeyPress::tabKey, ModifierKeys::currentModifiers, {} };
  179. if (keyCode == 13) return { juce::KeyPress::returnKey, ModifierKeys::currentModifiers, {} };
  180. if (keyCode == 27) return { juce::KeyPress::escapeKey, ModifierKeys::currentModifiers, {} };
  181. if (keyCode == 32) return { juce::KeyPress::spaceKey, ModifierKeys::currentModifiers, {} };
  182. if (keyCode == 266) return { juce::KeyPress::numberPadDecimalPoint, ModifierKeys::currentModifiers, {} };
  183. if (keyCode == 267) return { juce::KeyPress::numberPadDivide, ModifierKeys::currentModifiers, {} };
  184. if (keyCode == 268) return { juce::KeyPress::numberPadMultiply, ModifierKeys::currentModifiers, {} };
  185. if (keyCode == 269) return { juce::KeyPress::numberPadSubtract, ModifierKeys::currentModifiers, {} };
  186. if (keyCode == 270) return { juce::KeyPress::numberPadAdd, ModifierKeys::currentModifiers, {} };
  187. if (keyCode == 272) return { juce::KeyPress::numberPadEquals, ModifierKeys::currentModifiers, {} };
  188. if (keyCode == 273) return { juce::KeyPress::upKey, ModifierKeys::currentModifiers, {} };
  189. if (keyCode == 274) return { juce::KeyPress::downKey, ModifierKeys::currentModifiers, {} };
  190. if (keyCode == 275) return { juce::KeyPress::rightKey, ModifierKeys::currentModifiers, {} };
  191. if (keyCode == 276) return { juce::KeyPress::leftKey, ModifierKeys::currentModifiers, {} };
  192. return {};
  193. }
  194. //==============================================================================
  195. Rectangle<int> bounds;
  196. MouseWatcher mouseWatcher;
  197. uint8* pixelData = nullptr;
  198. int textureWidth, textureHeight;
  199. Image renderImage;
  200. //==============================================================================
  201. void setMinimised (bool) override {}
  202. bool isMinimised() const override { return false; }
  203. void setFullScreen (bool) override {}
  204. bool isFullScreen() const override { return false; }
  205. bool setAlwaysOnTop (bool) override { return false; }
  206. void toFront (bool) override {}
  207. void toBehind (ComponentPeer*) override {}
  208. bool isFocused() const override { return true; }
  209. void grabFocus() override {}
  210. void* getNativeHandle() const override { return nullptr; }
  211. BorderSize<int> getFrameSize() const override { return {}; }
  212. void setVisible (bool) override {}
  213. void setTitle (const String&) override {}
  214. void setIcon (const Image&) override {}
  215. void textInputRequired (Point<int>, TextInputTarget&) override {}
  216. void setAlpha (float) override {}
  217. void performAnyPendingRepaintsNow() override {}
  218. void repaint (const Rectangle<int>&) override {}
  219. //==============================================================================
  220. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (UnityPeer)
  221. };
  222. ComponentPeer* createUnityPeer (Component& c) { return new UnityPeer (c); }
  223. //==============================================================================
  224. class AudioProcessorUnityWrapper
  225. {
  226. public:
  227. AudioProcessorUnityWrapper (bool isTemporary)
  228. {
  229. pluginInstance.reset (createPluginFilterOfType (AudioProcessor::wrapperType_Unity));
  230. if (! isTemporary && pluginInstance->hasEditor())
  231. {
  232. pluginInstanceEditor.reset (pluginInstance->createEditorIfNeeded());
  233. pluginInstanceEditor->setVisible (true);
  234. pluginInstanceEditor->addToDesktop (0);
  235. }
  236. juceParameters.update (*pluginInstance, false);
  237. }
  238. ~AudioProcessorUnityWrapper()
  239. {
  240. if (pluginInstanceEditor != nullptr)
  241. {
  242. pluginInstanceEditor->removeFromDesktop();
  243. PopupMenu::dismissAllActiveMenus();
  244. pluginInstanceEditor->processor.editorBeingDeleted (pluginInstanceEditor.get());
  245. pluginInstanceEditor = nullptr;
  246. }
  247. }
  248. void create (UnityAudioEffectState* state)
  249. {
  250. // only supported in Unity plugin API > 1.0
  251. if (state->structSize >= sizeof (UnityAudioEffectState))
  252. samplesPerBlock = static_cast<int> (state->dspBufferSize);
  253. #ifdef JucePlugin_PreferredChannelConfigurations
  254. short configs[][2] = { JucePlugin_PreferredChannelConfigurations };
  255. const int numConfigs = sizeof (configs) / sizeof (short[2]);
  256. jassertquiet (numConfigs > 0 && (configs[0][0] > 0 || configs[0][1] > 0));
  257. pluginInstance->setPlayConfigDetails (configs[0][0], configs[0][1], state->sampleRate, samplesPerBlock);
  258. #else
  259. pluginInstance->setRateAndBufferSizeDetails (state->sampleRate, samplesPerBlock);
  260. #endif
  261. pluginInstance->prepareToPlay (state->sampleRate, samplesPerBlock);
  262. scratchBuffer.setSize (jmax (pluginInstance->getTotalNumInputChannels(), pluginInstance->getTotalNumOutputChannels()), samplesPerBlock);
  263. }
  264. void release()
  265. {
  266. pluginInstance->releaseResources();
  267. }
  268. void reset()
  269. {
  270. pluginInstance->reset();
  271. }
  272. void process (float* inBuffer, float* outBuffer, int bufferSize, int numInChannels, int numOutChannels, bool isBypassed)
  273. {
  274. for (int pos = 0; pos < bufferSize;)
  275. {
  276. auto max = jmin (bufferSize - pos, samplesPerBlock);
  277. processBuffers (inBuffer + (pos * numInChannels), outBuffer + (pos * numOutChannels), max, numInChannels, numOutChannels, isBypassed);
  278. pos += max;
  279. }
  280. }
  281. void declareParameters (UnityAudioEffectDefinition& definition)
  282. {
  283. static std::unique_ptr<UnityAudioParameterDefinition> parametersPtr;
  284. static int numParams = 0;
  285. if (parametersPtr == nullptr)
  286. {
  287. numParams = juceParameters.params.size();
  288. parametersPtr.reset (static_cast<UnityAudioParameterDefinition*> (std::calloc (static_cast<size_t> (numParams),
  289. sizeof (UnityAudioParameterDefinition))));
  290. parameterDescriptions.clear();
  291. for (int i = 0; i < numParams; ++i)
  292. {
  293. auto* parameter = juceParameters.params[i];
  294. auto& paramDef = parametersPtr.get()[i];
  295. const auto nameLength = (size_t) numElementsInArray (paramDef.name);
  296. const auto unitLength = (size_t) numElementsInArray (paramDef.unit);
  297. parameter->getName ((int) nameLength - 1).copyToUTF8 (paramDef.name, nameLength);
  298. if (parameter->getLabel().isNotEmpty())
  299. parameter->getLabel().copyToUTF8 (paramDef.unit, unitLength);
  300. parameterDescriptions.add (parameter->getName (15));
  301. paramDef.description = parameterDescriptions[i].toRawUTF8();
  302. paramDef.defaultVal = parameter->getDefaultValue();
  303. paramDef.min = 0.0f;
  304. paramDef.max = 1.0f;
  305. paramDef.displayScale = 1.0f;
  306. paramDef.displayExponent = 1.0f;
  307. }
  308. }
  309. definition.numParameters = static_cast<uint32> (numParams);
  310. definition.parameterDefintions = parametersPtr.get();
  311. }
  312. void setParameter (int index, float value) { juceParameters.getParamForIndex (index)->setValueNotifyingHost (value); }
  313. float getParameter (int index) const noexcept { return juceParameters.getParamForIndex (index)->getValue(); }
  314. String getParameterString (int index) const noexcept
  315. {
  316. auto* param = juceParameters.getParamForIndex (index);
  317. return param->getText (param->getValue(), 16);
  318. }
  319. int getNumInputChannels() const noexcept { return pluginInstance->getTotalNumInputChannels(); }
  320. int getNumOutputChannels() const noexcept { return pluginInstance->getTotalNumOutputChannels(); }
  321. bool hasEditor() const noexcept { return pluginInstance->hasEditor(); }
  322. UnityPeer& getEditorPeer() const
  323. {
  324. auto* peer = dynamic_cast<UnityPeer*> (pluginInstanceEditor->getPeer());
  325. jassert (peer != nullptr);
  326. return *peer;
  327. }
  328. private:
  329. //==============================================================================
  330. void processBuffers (float* inBuffer, float* outBuffer, int bufferSize, int numInChannels, int numOutChannels, bool isBypassed)
  331. {
  332. int ch;
  333. for (ch = 0; ch < numInChannels; ++ch)
  334. {
  335. using DstSampleType = AudioData::Pointer<AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst>;
  336. using SrcSampleType = AudioData::Pointer<AudioData::Float32, AudioData::NativeEndian, AudioData::Interleaved, AudioData::Const>;
  337. DstSampleType dstData (scratchBuffer.getWritePointer (ch));
  338. SrcSampleType srcData (inBuffer + ch, numInChannels);
  339. dstData.convertSamples (srcData, bufferSize);
  340. }
  341. for (; ch < numOutChannels; ++ch)
  342. scratchBuffer.clear (ch, 0, bufferSize);
  343. {
  344. const ScopedLock sl (pluginInstance->getCallbackLock());
  345. if (pluginInstance->isSuspended())
  346. {
  347. scratchBuffer.clear();
  348. }
  349. else
  350. {
  351. MidiBuffer mb;
  352. if (isBypassed)
  353. pluginInstance->processBlockBypassed (scratchBuffer, mb);
  354. else
  355. pluginInstance->processBlock (scratchBuffer, mb);
  356. }
  357. }
  358. for (ch = 0; ch < numOutChannels; ++ch)
  359. {
  360. using DstSampleType = AudioData::Pointer<AudioData::Float32, AudioData::NativeEndian, AudioData::Interleaved, AudioData::NonConst>;
  361. using SrcSampleType = AudioData::Pointer<AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const>;
  362. DstSampleType dstData (outBuffer + ch, numOutChannels);
  363. SrcSampleType srcData (scratchBuffer.getReadPointer (ch));
  364. dstData.convertSamples (srcData, bufferSize);
  365. }
  366. }
  367. //==============================================================================
  368. std::unique_ptr<AudioProcessor> pluginInstance;
  369. std::unique_ptr<AudioProcessorEditor> pluginInstanceEditor;
  370. int samplesPerBlock = 1024;
  371. StringArray parameterDescriptions;
  372. AudioBuffer<float> scratchBuffer;
  373. LegacyAudioParametersWrapper juceParameters;
  374. //==============================================================================
  375. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioProcessorUnityWrapper)
  376. };
  377. //==============================================================================
  378. HashMap<int, AudioProcessorUnityWrapper*>& getWrapperMap()
  379. {
  380. static HashMap<int, AudioProcessorUnityWrapper*> wrapperMap;
  381. return wrapperMap;
  382. }
  383. static void onWrapperCreation (AudioProcessorUnityWrapper* wrapperToAdd)
  384. {
  385. getWrapperMap().set (std::abs (Random::getSystemRandom().nextInt (65536)), wrapperToAdd);
  386. }
  387. static void onWrapperDeletion (AudioProcessorUnityWrapper* wrapperToRemove)
  388. {
  389. getWrapperMap().removeValue (wrapperToRemove);
  390. }
  391. //==============================================================================
  392. namespace UnityCallbacks
  393. {
  394. int UNITY_INTERFACE_API createCallback (UnityAudioEffectState* state)
  395. {
  396. auto* pluginInstance = new AudioProcessorUnityWrapper (false);
  397. pluginInstance->create (state);
  398. state->effectData = pluginInstance;
  399. onWrapperCreation (pluginInstance);
  400. return 0;
  401. }
  402. int UNITY_INTERFACE_API releaseCallback (UnityAudioEffectState* state)
  403. {
  404. auto* pluginInstance = state->getEffectData<AudioProcessorUnityWrapper>();
  405. pluginInstance->release();
  406. onWrapperDeletion (pluginInstance);
  407. delete pluginInstance;
  408. if (getWrapperMap().size() == 0)
  409. shutdownJuce_GUI();
  410. return 0;
  411. }
  412. int UNITY_INTERFACE_API resetCallback (UnityAudioEffectState* state)
  413. {
  414. auto* pluginInstance = state->getEffectData<AudioProcessorUnityWrapper>();
  415. pluginInstance->reset();
  416. return 0;
  417. }
  418. int UNITY_INTERFACE_API setPositionCallback (UnityAudioEffectState* state, unsigned int pos)
  419. {
  420. ignoreUnused (state, pos);
  421. return 0;
  422. }
  423. int UNITY_INTERFACE_API setFloatParameterCallback (UnityAudioEffectState* state, int index, float value)
  424. {
  425. auto* pluginInstance = state->getEffectData<AudioProcessorUnityWrapper>();
  426. pluginInstance->setParameter (index, value);
  427. return 0;
  428. }
  429. int UNITY_INTERFACE_API getFloatParameterCallback (UnityAudioEffectState* state, int index, float* value, char* valueStr)
  430. {
  431. auto* pluginInstance = state->getEffectData<AudioProcessorUnityWrapper>();
  432. *value = pluginInstance->getParameter (index);
  433. pluginInstance->getParameterString (index).copyToUTF8 (valueStr, 15);
  434. return 0;
  435. }
  436. int UNITY_INTERFACE_API getFloatBufferCallback (UnityAudioEffectState* state, const char* name, float* buffer, int numSamples)
  437. {
  438. ignoreUnused (numSamples);
  439. auto nameStr = String (name);
  440. if (nameStr == "Editor")
  441. {
  442. auto* pluginInstance = state->getEffectData<AudioProcessorUnityWrapper>();
  443. buffer[0] = pluginInstance->hasEditor() ? 1.0f : 0.0f;
  444. }
  445. else if (nameStr == "ID")
  446. {
  447. auto* pluginInstance = state->getEffectData<AudioProcessorUnityWrapper>();
  448. for (HashMap<int, AudioProcessorUnityWrapper*>::Iterator i (getWrapperMap()); i.next();)
  449. {
  450. if (i.getValue() == pluginInstance)
  451. {
  452. buffer[0] = (float) i.getKey();
  453. break;
  454. }
  455. }
  456. return 0;
  457. }
  458. else if (nameStr == "Size")
  459. {
  460. auto* pluginInstance = state->getEffectData<AudioProcessorUnityWrapper>();
  461. auto& editor = pluginInstance->getEditorPeer().getEditor();
  462. buffer[0] = (float) editor.getBounds().getWidth();
  463. buffer[1] = (float) editor.getBounds().getHeight();
  464. buffer[2] = (float) editor.getConstrainer()->getMinimumWidth();
  465. buffer[3] = (float) editor.getConstrainer()->getMinimumHeight();
  466. buffer[4] = (float) editor.getConstrainer()->getMaximumWidth();
  467. buffer[5] = (float) editor.getConstrainer()->getMaximumHeight();
  468. }
  469. return 0;
  470. }
  471. int UNITY_INTERFACE_API processCallback (UnityAudioEffectState* state, float* inBuffer, float* outBuffer,
  472. unsigned int bufferSize, int numInChannels, int numOutChannels)
  473. {
  474. auto* pluginInstance = state->getEffectData<AudioProcessorUnityWrapper>();
  475. if (pluginInstance != nullptr)
  476. {
  477. auto isPlaying = ((state->flags & stateIsPlaying) != 0);
  478. auto isMuted = ((state->flags & stateIsMuted) != 0);
  479. auto isPaused = ((state->flags & stateIsPaused) != 0);
  480. auto bypassed = ! isPlaying || (isMuted || isPaused);
  481. pluginInstance->process (inBuffer, outBuffer, static_cast<int> (bufferSize), numInChannels, numOutChannels, bypassed);
  482. }
  483. else
  484. {
  485. FloatVectorOperations::clear (outBuffer, static_cast<int> (bufferSize) * numOutChannels);
  486. }
  487. return 0;
  488. }
  489. }
  490. //==============================================================================
  491. static void declareEffect (UnityAudioEffectDefinition& definition)
  492. {
  493. memset (&definition, 0, sizeof (definition));
  494. std::unique_ptr<AudioProcessorUnityWrapper> wrapper = std::make_unique<AudioProcessorUnityWrapper> (true);
  495. String name (JucePlugin_Name);
  496. if (! name.startsWithIgnoreCase ("audioplugin"))
  497. name = "audioplugin_" + name;
  498. name.copyToUTF8 (definition.name, (size_t) numElementsInArray (definition.name));
  499. definition.structSize = sizeof (UnityAudioEffectDefinition);
  500. definition.parameterStructSize = sizeof (UnityAudioParameterDefinition);
  501. definition.apiVersion = UNITY_AUDIO_PLUGIN_API_VERSION;
  502. definition.pluginVersion = JucePlugin_VersionCode;
  503. // effects must set this to 0, generators > 0
  504. definition.channels = (wrapper->getNumInputChannels() != 0 ? 0
  505. : static_cast<uint32> (wrapper->getNumOutputChannels()));
  506. wrapper->declareParameters (definition);
  507. definition.create = UnityCallbacks::createCallback;
  508. definition.release = UnityCallbacks::releaseCallback;
  509. definition.reset = UnityCallbacks::resetCallback;
  510. definition.setPosition = UnityCallbacks::setPositionCallback;
  511. definition.process = UnityCallbacks::processCallback;
  512. definition.setFloatParameter = UnityCallbacks::setFloatParameterCallback;
  513. definition.getFloatParameter = UnityCallbacks::getFloatParameterCallback;
  514. definition.getFloatBuffer = UnityCallbacks::getFloatBufferCallback;
  515. }
  516. } // namespace juce
  517. UNITY_INTERFACE_EXPORT int UNITY_INTERFACE_API UnityGetAudioEffectDefinitions (UnityAudioEffectDefinition*** definitionsPtr)
  518. {
  519. if (juce::getWrapperMap().size() == 0)
  520. juce::initialiseJuce_GUI();
  521. static bool hasInitialised = false;
  522. if (! hasInitialised)
  523. {
  524. juce::PluginHostType::jucePlugInClientCurrentWrapperType = juce::AudioProcessor::wrapperType_Unity;
  525. juce::juce_createUnityPeerFn = juce::createUnityPeer;
  526. hasInitialised = true;
  527. }
  528. auto* definition = new UnityAudioEffectDefinition();
  529. juce::declareEffect (*definition);
  530. *definitionsPtr = &definition;
  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. extern "C" BOOL WINAPI DllMain (HINSTANCE instance, DWORD reason, LPVOID)
  597. {
  598. if (reason == DLL_PROCESS_ATTACH)
  599. juce::Process::setCurrentModuleInstanceHandle (instance);
  600. return true;
  601. }
  602. #endif
  603. #endif