Newer
Older
EARS-LINUX / program / RegionSound.cs
using System;
using System.Runtime.InteropServices;

public class RegionSound : IDisposable
{
    public int    Index;              // 0,1 = heart; 2..6 = breath
    public string Name;
    public Gdk.Pixbuf Map;            // raw, NOT black-keyed — audio reference
    public AudioEngine.Voice Voice;   // owned by AudioEngine's cache
    public float  Volume;
    public bool   Enabled = true;

    private byte[] _px;
    private int _w, _h, _stride, _ch;

    public bool IsHeart { get { return Index <= 1; } }

    public void CachePixels()
    {
        if (Map == null) return;
        _w = Map.Width; _h = Map.Height;
        _stride = Map.Rowstride; _ch = Map.NChannels;

        int len = _stride * (_h - 1) + _w * _ch;    // last row is short — don't overrun
        _px = new byte[len];
        Marshal.Copy(Map.Pixels, _px, 0, len);
    }

    /// u,v are 0..1 across the map, from MapWindow.BodyToMapUV.
    public int IntensityAt(double u, double v)
    {
        if (_px == null) return 0;
        int x = (int)(u * _w), y = (int)(v * _h);
        if (x < 0 || y < 0 || x >= _w || y >= _h) return 0;

        int i = y * _stride + x * _ch;
        if (i + 2 >= _px.Length) return 0;

        byte r = _px[i], b = _px[i + 2];
        return r != 0 ? r : b;                      // Python: R if R != 0 else B
    }

    /// Python EarsSound.volume_change: non-linear curve, breath halved.
    public float VolumeAt(double u, double v)
    {
        if (!Enabled) return 0f;
        int val = IntensityAt(u, v);
        if (val == 0) return 0f;

        float vol = (float)Math.Pow(val / 255.0, 1.0 / 9.5);
        if (!IsHeart) vol *= 0.5f;
        return Math.Max(0f, Math.Min(1f, vol));
    }

    public void Dispose()
    {
        if (Map != null) { Map.Dispose(); Map = null; }
        _px = null;
        Voice = null;                               // engine keeps and reuses it
    }
}