Skip to content

Commit

Permalink
misc clean up in unity
Browse files Browse the repository at this point in the history
  • Loading branch information
anokta committed Jan 4, 2024
1 parent 53fbf4e commit e8fbe8f
Show file tree
Hide file tree
Showing 8 changed files with 107 additions and 72 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Runtime.InteropServices.ComTypes;
using UnityEngine;

namespace Barely {
Expand All @@ -14,16 +15,18 @@ public enum ArpeggiatorStyle {
[InspectorName("Random")] RANDOM = 8,
}

/// A represantion of a simple arpeggiator hat can be attached to a musical instrument to play
/// A represantion of a simple arpeggiator that can be attached to a musical instrument to play
/// notes in sequence.
[RequireComponent(typeof(Instrument))]
public class Arpeggiator : MonoBehaviour {
public int ProcessOrder = 0;

/// Gate ratio.
[Range(0.0f, 1.0f)]
public double GateRatio = 0.5;

// Instrument.
public Instrument Instrument = null;

/// Rate.
[Range(0.0f, 8.0f)]
public double Rate = 1.0;
Expand Down Expand Up @@ -64,21 +67,53 @@ public class Arpeggiator : MonoBehaviour {
Musician.Internal.Arpeggiator_SetNoteOn(_handle, pitch);
}

protected virtual void Update() {
if (_handle == IntPtr.Zero && GetComponent<Instrument>().enabled) {
Musician.Internal.Component_Create(
this, Instrument.Internal.GetInstrumentHandle(GetComponent<Instrument>()), ref _handle);
private void OnEnable() {
Musician.Internal.Component_Create(this, ref _handle);
UpdateInstrument();
}

private void OnDisable() {
if (_instrument != null) {
_instrument.OnInstrumentCreate -= OnInstrumentCreate;
_instrument.OnInstrumentDestroy -= OnInstrumentDestroy;
}
Musician.Internal.Component_Destroy(this, ref _handle);
}

private void Update() {
Musician.Internal.Arpeggiator_SetGateRatio(_handle, GateRatio);
Musician.Internal.Arpeggiator_SetRate(_handle, Rate);
Musician.Internal.Arpeggiator_SetStyle(_handle, Style);
if (_instrument != Instrument) {
UpdateInstrument();
}
}

protected virtual void OnDisable() {
Musician.Internal.Component_Destroy(this, ref _handle);
private void UpdateInstrument() {
if (_instrument != null) {
_instrument.OnInstrumentCreate -= OnInstrumentCreate;
_instrument.OnInstrumentDestroy -= OnInstrumentDestroy;
}
_instrument = Instrument;
Musician.Internal.Arpeggiator_SetInstrument(_handle, _instrument);
if (_instrument != null) {
_instrument.OnInstrumentCreate += OnInstrumentCreate;
_instrument.OnInstrumentDestroy += OnInstrumentDestroy;
}
}

private void OnInstrumentCreate() {
Musician.Internal.Arpeggiator_SetInstrument(_handle, _instrument);
}

private void OnInstrumentDestroy() {
Musician.Internal.Arpeggiator_SetInstrument(_handle, null);
}

// Handle.
private IntPtr _handle = IntPtr.Zero;

// Current instrument.
private Instrument _instrument = null;
}
} // namespace Barely
Original file line number Diff line number Diff line change
Expand Up @@ -61,17 +61,6 @@ public abstract class CustomEffect<DefinitionType> : Effect,
/// @return Array of control definitions.
protected abstract ControlDefinition[] GetControlDefinitions();

protected override void OnEnable() {
var config = AudioSettings.GetConfiguration();
_outputSamples = new double[config.dspBufferSize * (int)config.speakerMode];
base.OnEnable();
}

protected override void OnDisable() {
base.OnDisable();
_outputSamples = null;
}

// Create callback.
[AOT.MonoPInvokeCallback(typeof(Musician.Internal.EffectDefinition_CreateCallback))]
private static void OnCreate(ref IntPtr state, Int32 frameRate) {
Expand All @@ -93,8 +82,9 @@ public abstract class CustomEffect<DefinitionType> : Effect,
private static void OnProcess(ref IntPtr state, IntPtr outputSamples, Int32 outputChannelCount,
Int32 outputFrameCount) {
(GCHandle.FromIntPtr(state).Target as DefinitionType)
.OnProcess(_outputSamples, outputChannelCount, outputFrameCount);
Marshal.Copy(_outputSamples, 0, outputSamples, outputChannelCount * outputFrameCount);
.OnProcess(Musician.Internal.OutputSamples, outputChannelCount, outputFrameCount);
Marshal.Copy(Musician.Internal.OutputSamples, 0, outputSamples,
outputChannelCount * outputFrameCount);
}

// Set control callback.
Expand Down Expand Up @@ -135,8 +125,5 @@ public abstract class CustomEffect<DefinitionType> : Effect,
}
return definitionsPtr;
}

// Internal output samples.
private static double[] _outputSamples = null;
}
} // namespace Barely
12 changes: 10 additions & 2 deletions platforms/unity/Assets/BarelyMusician/Scripts/Instrument.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,12 @@ public class NoteOffEvent : UnityEngine.Events.UnityEvent<float> {}
public class NoteOnEvent : UnityEngine.Events.UnityEvent<float, float> {}
public NoteOnEvent OnNoteOnEvent;

/// Instrument create callback.
public event Action OnInstrumentCreate;

/// Instrument destroy callback.
public event Action OnInstrumentDestroy;

/// Returns a control value.
///
/// @param index Control index.
Expand Down Expand Up @@ -155,7 +161,7 @@ public class NoteOnEvent : UnityEngine.Events.UnityEvent<float, float> {}
public static class Internal {
/// Returns instrument handle.
public static IntPtr GetInstrumentHandle(Instrument instrument) {
return instrument._handle;
return instrument ? instrument._handle : IntPtr.Zero;
}

/// Internal control event callback.
Expand Down Expand Up @@ -186,7 +192,7 @@ public static class Internal {

protected virtual void Awake() {
Source = GetComponent<AudioSource>();
Source.clip = AudioClip.Create("Ones", 64, 1, AudioSettings.outputSampleRate, false);
Source.clip = AudioClip.Create("[DO NOT EDIT]", 64, 1, AudioSettings.outputSampleRate, false);
float[] ones = new float[64];
for (int i = 0; i < ones.Length; ++i) {
ones[i] = 1.0f;
Expand All @@ -201,6 +207,7 @@ public static class Internal {

protected virtual void OnEnable() {
Musician.Internal.Instrument_Create(this, ref _handle);
OnInstrumentCreate?.Invoke();
foreach (var effect in GetComponents<Effect>()) {
Effect.Internal.ReEnable(_handle, effect);
}
Expand All @@ -212,6 +219,7 @@ public static class Internal {
foreach (var effect in GetComponents<Effect>()) {
Effect.Internal.Disable(effect);
}
OnInstrumentDestroy?.Invoke();
Musician.Internal.Instrument_Destroy(ref _handle);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,17 +92,6 @@ public abstract class CustomInstrument<DefinitionType>
/// @return Array of note control definitions.
protected abstract ControlDefinition[] GetNoteControlDefinitions();

protected override void OnEnable() {
var config = AudioSettings.GetConfiguration();
_outputSamples = new double[config.dspBufferSize * (int)config.speakerMode];
base.OnEnable();
}

protected override void OnDisable() {
base.OnDisable();
_outputSamples = null;
}

// Create callback.
[AOT.MonoPInvokeCallback(typeof(Musician.Internal.InstrumentDefinition_CreateCallback))]
private static void OnCreate(ref IntPtr state, Int32 frameRate) {
Expand All @@ -124,8 +113,9 @@ public abstract class CustomInstrument<DefinitionType>
private static void OnProcess(ref IntPtr state, IntPtr outputSamples, Int32 outputChannelCount,
Int32 outputFrameCount) {
(GCHandle.FromIntPtr(state).Target as DefinitionType)
.OnProcess(_outputSamples, outputChannelCount, outputFrameCount);
Marshal.Copy(_outputSamples, 0, outputSamples, outputChannelCount * outputFrameCount);
.OnProcess(Musician.Internal.OutputSamples, outputChannelCount, outputFrameCount);
Marshal.Copy(Musician.Internal.OutputSamples, 0, outputSamples,
outputChannelCount * outputFrameCount);
}

// Set control callback.
Expand Down Expand Up @@ -186,8 +176,5 @@ public abstract class CustomInstrument<DefinitionType>
}
return definitionsPtr;
}

// Internal output samples.
private static double[] _outputSamples = null;
}
} // namespace Barely
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,9 @@ public class Pad {
private int _padCount = 0;

private void Update() {
UpdatePadData();
if (Pads != null) {
UpdatePadData();
}
SetControl(0, Gain);
SetControl(1, PadRelease);
}
Expand Down
42 changes: 27 additions & 15 deletions platforms/unity/Assets/BarelyMusician/Scripts/Musician.cs
Original file line number Diff line number Diff line change
Expand Up @@ -233,17 +233,14 @@ public interface CustomInstrumentInterface {
/// Creates a new component.
///
/// @param component Component.
/// @param instrumentHandle Instrument handle.
/// @param componentHandle Component handle.
public static void Component_Create(Component component, IntPtr instrumentHandle,
ref IntPtr componentHandle) {
public static void Component_Create(Component component, ref IntPtr componentHandle) {
if (Handle == IntPtr.Zero || componentHandle != IntPtr.Zero) {
return;
}
switch (component) {
case Arpeggiator arpeggiator:
if (BarelyArpeggiator_Create(_handle, arpeggiator.ProcessOrder, ref componentHandle) &&
BarelyArpeggiator_SetInstrument(componentHandle, instrumentHandle)) {
if (BarelyArpeggiator_Create(_handle, arpeggiator.ProcessOrder, ref componentHandle)) {
return;
}
break;
Expand All @@ -262,17 +259,19 @@ public interface CustomInstrumentInterface {
if (Handle == IntPtr.Zero || componentHandle == IntPtr.Zero) {
return;
}
bool success = true;
switch (component) {
case Arpeggiator arpeggiator:
if (BarelyArpeggiator_Destroy(componentHandle)) {
return;
}
success = BarelyArpeggiator_Destroy(componentHandle);
break;
default:
Debug.LogError("Unsupported component type: " + component.GetType());
return;
}
Debug.LogError("Failed to destroy component '" + component.name + "'");
if (!success) {
Debug.LogError("Failed to destroy component '" + component.name + "'");
}
componentHandle = IntPtr.Zero;
}

/// Creates a new effect.
Expand Down Expand Up @@ -535,11 +534,11 @@ public interface CustomInstrumentInterface {
}
return;
}
if (BarelyInstrument_Process(instrumentHandle, _outputSamples, outputChannelCount,
if (BarelyInstrument_Process(instrumentHandle, OutputSamples, outputChannelCount,
outputSamples.Length / outputChannelCount,
AudioSettings.dspTime)) {
for (int i = 0; i < outputSamples.Length; ++i) {
outputSamples[i] *= (float)_outputSamples[i];
outputSamples[i] *= (float)OutputSamples[i];
}
} else {
for (int i = 0; i < outputSamples.Length; ++i) {
Expand Down Expand Up @@ -1027,6 +1026,19 @@ public interface CustomInstrumentInterface {
}
}

/// Sets an arpeggiator instrument.
///
/// @param arpeggiatorHandle Arpeggiator handle.
/// @param instrument Instrument.
public static void Arpeggiator_SetInstrument(IntPtr arpeggiatorHandle,
Instrument instrument) {
if (!BarelyArpeggiator_SetInstrument(arpeggiatorHandle,
Instrument.Internal.GetInstrumentHandle(instrument)) &&
arpeggiatorHandle != IntPtr.Zero) {
Debug.LogError("Failed to set arpeggiator instrument '" + instrument.name + "'");
}
}

/// Sets an arpeggiator note off.
///
/// @param arpeggiatorHandle Arpeggiator handle.
Expand Down Expand Up @@ -1071,6 +1083,9 @@ public interface CustomInstrumentInterface {
}
}

// Internal output samples.
public static double[] OutputSamples { get; private set; } = null;

// Control event definition create callback.
private delegate void ControlEventDefinition_CreateCallback(ref IntPtr state,
IntPtr userData);
Expand Down Expand Up @@ -1352,9 +1367,6 @@ private struct TaskDefinition {
// Latency in seconds.
private static double _latency = 0.0;

// Internal output samples.
private static double[] _outputSamples = null;

// Map of scheduled list of task callbacks by their timestamps.
private static SortedDictionary<double, List<Action>> _scheduledTaskCallbacks = null;

Expand Down Expand Up @@ -1414,7 +1426,7 @@ private class State : MonoBehaviour {
BarelyMusician_SetTempo(_handle, _tempo);
var config = AudioSettings.GetConfiguration();
_latency = (double)(2 * config.dspBufferSize) / (double)config.sampleRate;
_outputSamples = new double[config.dspBufferSize * (int)config.speakerMode];
OutputSamples = new double[config.dspBufferSize * (int)config.speakerMode];
_effects = new Dictionary<IntPtr, Effect>();
_instruments = new Dictionary<IntPtr, Instrument>();
_scheduledTaskCallbacks = new SortedDictionary<double, List<Action>>();
Expand Down
9 changes: 6 additions & 3 deletions platforms/unity/Assets/Examples/Scenes/ArpeggiatorDemo.unity
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ MonoBehaviour:
m_Script: {fileID: 11500000, guid: bf2924acef9d3214e9203ba5ca1f8f38, type: 3}
m_Name:
m_EditorClassIdentifier:
tempo: 200
tempo: 150
--- !u!850595691 &748775628
LightingSettings:
m_ObjectHideFlags: 0
Expand Down Expand Up @@ -418,11 +418,11 @@ GameObject:
- component: {fileID: 1737834382}
- component: {fileID: 1737834381}
- component: {fileID: 1737834380}
- component: {fileID: 1737834384}
- component: {fileID: 1737834379}
- component: {fileID: 1737834383}
- component: {fileID: 1737834384}
m_Layer: 0
m_Name: InstrumentController
m_Name: ArpeggiatorController
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
Expand Down Expand Up @@ -611,4 +611,7 @@ MonoBehaviour:
m_Name:
m_EditorClassIdentifier:
ProcessOrder: 0
GateRatio: 0.5
Instrument: {fileID: 1737834380}
Rate: 2
Style: 0
Loading

0 comments on commit e8fbe8f

Please sign in to comment.