Skip to content

Commit

Permalink
dispose old Gamepads
Browse files Browse the repository at this point in the history
  • Loading branch information
nkast committed Sep 14, 2024
1 parent 40ab96b commit ea68b6f
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 25 deletions.
44 changes: 19 additions & 25 deletions Wasm.Dom/Dom/Navigator.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using Microsoft.JSInterop.WebAssembly;
using nkast.Wasm.Input;
Expand All @@ -11,8 +12,7 @@ public class Navigator : JSObject
{
private readonly Window _window;
static Gamepad[] _emptyGamepadArray = new Gamepad[0];

private Dictionary<int,Gamepad> _gamepadMap = new Dictionary<int, Gamepad>();
Dictionary<int,Gamepad> _prevGamepads = new Dictionary<int,Gamepad>();

public string UserAgent
{
Expand Down Expand Up @@ -41,36 +41,30 @@ public Gamepad[] GetGamepads()

for (int index = 0; index < strs.Length; index++)
{
int gpuid = int.Parse(strs[index]);
if (gpuid == 0)
int uid = int.Parse(strs[index]);
if (Gamepad._uidMap.TryGetValue(uid, out WeakReference<JSObject> jsObjRef))
{
gamepads[index] = null;
if (jsObjRef.TryGetTarget(out JSObject jsObj))
{
gamepads[index] = (Gamepad)jsObj;
continue;
}
else
Gamepad._uidMap.Remove(uid);
}
else
{
if (!_gamepadMap.ContainsKey(gpuid))
_gamepadMap[gpuid] = new Gamepad(gpuid);

gamepads[index] = _gamepadMap[gpuid];
}
if (uid != 0)
gamepads[index] = new Gamepad(uid);
}

List<int> keys = new List<int>(_gamepadMap.Keys);
for (int index = 0; index < keys.Count; index++)
foreach(int key in _prevGamepads.Keys)
{
bool found = false;
for (int k = 0; k < strs.Length; k++)
{
int gpuid = int.Parse(strs[k]);
if (keys[index] == gpuid)
{
found = true;
break;
}
}
if (!found)
_gamepadMap.Remove(keys[index]);
if (!gamepads.Contains(_prevGamepads[key]))
_prevGamepads[key].Dispose();
}
_prevGamepads.Clear();
for (int index = 0; index < gamepads.Length; index++)
_prevGamepads.Add(index, gamepads[index]);

return gamepads;
}
Expand Down
14 changes: 14 additions & 0 deletions Wasm.Dom/Input/Gamepad.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ namespace nkast.Wasm.Input
{
public class Gamepad : JSObject
{
static internal Dictionary<int, WeakReference<JSObject>> _uidMap = new Dictionary<int, WeakReference<JSObject>>();

public bool Connected
{
get { return InvokeRet<bool>("nkGamepad.GetConnected"); }
Expand Down Expand Up @@ -99,8 +101,20 @@ public GamepadHapticActuator VibrationActuator

internal Gamepad(int uid) : base(uid)
{
_uidMap.Add(Uid, new WeakReference<JSObject>(this));
}

protected override void Dispose(bool disposing)
{
if (disposing)
{

}

_uidMap.Remove(Uid);

base.Dispose(disposing);
}
}

public struct GamepadButton
Expand Down

0 comments on commit ea68b6f

Please sign in to comment.