88 lines
2.5 KiB
C#
88 lines
2.5 KiB
C#
using UnityEngine;
|
|
using System.Collections.Generic;
|
|
using Assets.WasapiAudio.Scripts.Unity;
|
|
|
|
// only slightly different from the SpectrumMaterialBinder
|
|
// in that it modifies a single material for a shader
|
|
// instead of the renderer's instance of that material
|
|
|
|
[RequireComponent(typeof(Material))]
|
|
public class SpectrumShaderBinder : MonoBehaviour
|
|
{
|
|
public WasapiAudioSource source;
|
|
public Material material;
|
|
|
|
private Texture2D _texture;
|
|
private Color[] _colorCache;
|
|
|
|
[SerializeReference]
|
|
[SerializeReferenceButton]
|
|
public List<SpectrumTransformer> Transformers = new List<SpectrumTransformer>();
|
|
|
|
[SpectrumDataPreview]
|
|
public SpectrumData Preview;
|
|
|
|
private void Start() {
|
|
if (source == null) {
|
|
Debug.Log("Material Binder needs WASAPI Source.");
|
|
gameObject.SetActive(false);
|
|
}
|
|
}
|
|
|
|
private void Update() {
|
|
UpdateTexture();
|
|
UpdateBinding();
|
|
}
|
|
|
|
private void InitialiseTexture() {
|
|
Debug.Log("Reinitialising spectrum texture...");
|
|
_texture = new Texture2D(source.SpectrumSize, 1, TextureFormat.RFloat, false);
|
|
_colorCache = new Color[source.SpectrumSize];
|
|
_texture.name = $"AudioSpectrum{source.SpectrumSize}";
|
|
}
|
|
|
|
private float[] GetSpectrumData() {
|
|
// Get raw / unmodified spectrum data
|
|
var spectrumData = source.GetSpectrumData();
|
|
|
|
// Run spectrum data through all configured transformers
|
|
if (Transformers != null && Transformers.Count > 0) {
|
|
foreach (var transformer in Transformers) {
|
|
spectrumData = transformer.Transform(spectrumData);
|
|
}
|
|
}
|
|
|
|
Preview.Values = spectrumData;
|
|
|
|
return spectrumData;
|
|
}
|
|
|
|
private void UpdateTexture() {
|
|
// init
|
|
if (_texture == null) InitialiseTexture();
|
|
|
|
var spectrumData = GetSpectrumData();
|
|
|
|
for (int i = 0; i < source.SpectrumSize; i++) {
|
|
_colorCache[i] = new Color(spectrumData[i], 0, 0, 0);
|
|
}
|
|
|
|
_texture.SetPixels(_colorCache);
|
|
_texture.Apply();
|
|
}
|
|
|
|
public void UpdateBinding() {
|
|
UpdateTexture();
|
|
|
|
// !!!!
|
|
// you must set these via a literal string for some raeson
|
|
// having them as a public property didn't work
|
|
material.SetFloat("_SpectrumSize", source.SpectrumSize);
|
|
material.SetTexture("_SpectrumTexture", _texture);
|
|
}
|
|
|
|
public string ToString() {
|
|
return "Spectrum Material Binder";
|
|
}
|
|
}
|