-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
333 lines (292 loc) · 12.6 KB
/
Program.cs
File metadata and controls
333 lines (292 loc) · 12.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
using NAudio.Mixer;
using NAudio.Wave;
using NAudio.Wave.SampleProviders;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Timers;
using VRChatOSCLib;
namespace WoojerOSC
{
internal class Program
{
static VRChatOSC osc = new VRChatOSC();
public static int sampleRate = 48000;
static float hapticDuration = 0.1f;
public static WaveOutEvent waveOut;
public static MixingSampleProvider mixer;
static SinePool pool;
static string PersistentDataPath;
static Dictionary<int, Dictionary<int, float>> currentHapticsF = new(); //x, y - top left > bottom right
static bool allowSelfInflicted = true;
static bool singleIntensityMode = false;
static float singleIntensityValue = 1f;
static async Task Main(string[] args)
{
// Get Unity PersistentDataPath equivalent for log-based haptics
PersistentDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "AppData", "LocalLow");
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
string xdgConfig = Environment.GetEnvironmentVariable("XDG_CONFIG_HOME");
if (!string.IsNullOrWhiteSpace(xdgConfig))
PersistentDataPath = xdgConfig;
string home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
PersistentDataPath = Path.Combine(home, ".config");
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
PersistentDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
// List devices that I totally didn't have to port over due to NAudio only supporting WaveOut.DeviceCount on WinForms
for (int idx = 0; idx < WaveOut.DeviceCount; ++idx)
{
string devName = NAudio.Wave.WaveOut.GetCapabilities(idx).ProductName;
Console.WriteLine($"{idx}: {devName}");
}
Console.Write("Index of Woojer device: ");
// Initialize Output, dont use an invalid int or you DIE
waveOut = new WaveOutEvent
{
DeviceNumber = int.Parse(Console.ReadLine()),
};
mixer = new MixingSampleProvider(WaveFormat.CreateIeeeFloatWaveFormat(sampleRate, 2))
{
ReadFully = true
};
waveOut.Init(mixer);
waveOut.Play();
Console.WriteLine();
pool = new(sampleRate);
for (var x = 0; x < 5; x++)
{
for (var y = 0; y < 4; y++)
{
if (!currentHapticsF.ContainsKey(x))
currentHapticsF[x] = new();
currentHapticsF[x][y] = 0f;
}
}
// Connect to vrchat itself cuz how else are you gonna get data from the obfuscated game
osc.Listen();
osc.OnMessage += HandleOSCMessage;
// okay well maybe this is how
string logDir = Path.Combine(PersistentDataPath, "VRChat", "VRChat");
string logPrefix = "output_log_";
string logExt = ".txt";
string outputHeader = "Debug - ";
string bHapticsHeader = "[bLog] ";
string previousLogFile = "";
long previousLogLength = 0;
while (true)
{
var newestLog = Directory.EnumerateFiles(logDir, $"{logPrefix}*{logExt}")
.Select(path => new
{
Path = path,
Timestamp = TryParseTimestamp(Path.GetFileNameWithoutExtension(path), logPrefix)
})
.Where(x => x.Timestamp.HasValue)
.OrderByDescending(x => x.Timestamp!.Value)
.FirstOrDefault();
if (newestLog == null)
continue;
if (newestLog.Path != previousLogFile)
{
previousLogFile = newestLog.Path;
previousLogLength = new FileInfo(previousLogFile).Length;
}
using (var fs = new FileStream(
previousLogFile,
FileMode.Open,
FileAccess.Read,
FileShare.ReadWrite))
{
fs.Seek(previousLogLength, SeekOrigin.Begin);
using (var reader = new StreamReader(fs, Encoding.UTF8))
{
string? line;
while ((line = reader.ReadLine()) != null)
{
if (!line.Contains(outputHeader))
continue;
line = line.Substring(line.IndexOf(outputHeader)+outputHeader.Length);
if (!line.StartsWith(bHapticsHeader))
continue;
line = line.Substring(bHapticsHeader.Length);
HandleLogMessage(line);
}
previousLogLength = fs.Position;
}
}
}
}
static DateTime? TryParseTimestamp(string fileName, string prefix)
{
var timestampPart = fileName.Substring(prefix.Length);
if (DateTime.TryParseExact(
timestampPart,
"yyyy-MM-dd_HH-mm-ss",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out var timestamp))
{
return timestamp;
}
return null;
}
static Dictionary<int, SineProvider>? directionalSines = null;
static void ForcedSide()
{
if (directionalSines == null)
{
directionalSines = new Dictionary<int, SineProvider>
{
{
-1,
new SineProvider
{
Frequency = 0f,
Pan = -1f,
Volume = 0f
}
},
{
1,
new SineProvider
{
Frequency = 0f,
Pan = 1f,
Volume = 0f
}
}
};
mixer.AddMixerInput(directionalSines[-1]);
mixer.AddMixerInput(directionalSines[1]);
}
Dictionary<int, float> directionalPower = new Dictionary<int, float>
{
{ -1, 0f },
{ 1, 0f }
};
for (int x = 0; x < currentHapticsF.Count; x++)
{
for (int y = 0; y < currentHapticsF[x].Count; y++)
{
if (currentHapticsF[x][y] > 0f)
{
//float bodyPos = 1f-(3f - x)/3f*2f;
//float bodyPos = x == 0 ? -1f : x == 1 ? -0.8f : x == 2 ? 0.8f : 1f;
int bodyPos = x <= 1 ? -1 : 1;
directionalPower[bodyPos] += currentHapticsF[x][y] / 10f;
}
}
}
foreach (KeyValuePair<int, float> side in directionalPower)
{
directionalSines[side.Key].Volume = side.Value > 0f ? 1f : 0f;
float modifiedValue = 1f - MathF.Pow(1f - side.Value, 5f); // Quintic ease out - First few touches will make much more of a difference than later ones
directionalSines[side.Key].Frequency = 250f + (50f - 250f) * modifiedValue;
Console.WriteLine(directionalSines[side.Key].Frequency);
}
}
static void HandleOSCMessage(object? source, VRCMessage message)
{
if (!message.IsParameter)
return;
VRCMessage.MessageType messageType = message.Type;
if (messageType != VRCMessage.MessageType.AvatarParameter)
return;
string address = message.Address.Replace("/avatar/parameters/", "");
string[] AddressParts = address.Split('/');
if (AddressParts.Length == 1) // bOSC v1
AddressParts = address.Split('_');
if (AddressParts[0] == "")
AddressParts = AddressParts.Skip(1).ToArray();
if (AddressParts[0] != "bOSC")
return;
if (AddressParts[2] != "VestFront")/* &&
AddressParts[2] != "VestBack")*/
return;
bool isSelfInflicted = false;
if (AddressParts[1] == "v2" ||
AddressParts[1] == "v2m") //mobile
{
isSelfInflicted = (AddressParts[4] == "self");
if (!isSelfInflicted && AddressParts[4] != "others")
Console.WriteLine("WARNING: Using bHaptics v2 but couldn't determine whether the haptic was self-inflicted for some reason. Assuming it wasn't");
}
if (isSelfInflicted && !allowSelfInflicted)
return;
if (!int.TryParse(AddressParts[3], out int hapticPoint))
return; // idek
int x = hapticPoint % 4; // 0-3 (4 possible)
int y = (int)Math.Floor(hapticPoint / 4f); // 0-4 (5 possible)
currentHapticsF[x][y] = singleIntensityMode ? singleIntensityValue : message.GetValue<float>();
if (mixer.MixerInputs.Count() >= 1024)
return;
ForcedSide();
}
public static Dictionary<string, System.Timers.Timer> loops = new();
static void HandleLogMessage(string message)
{
Console.WriteLine(message);
string[] parts = message.Split(' ');
if (parts[0] == "PlayLoop") parts[0] = "Play";
switch (parts[0])
{
case "Play":
if (Presets.PresetHaptics.ContainsKey(parts[1]))
Presets.PresetHaptics[parts[1]].Invoke(1, 1, 0);
else
Console.WriteLine($"World attempted to call unknown preset: {parts[1]}");
break;
case "PlayLoop":
if (Presets.PresetHaptics.ContainsKey(parts[1]))
{
float intensity = 1f;
float duration = 1f;
float angleX = 0f;
float offsetY = 0f;
int interval = 200;
int maxCount = 999999;
float.TryParse(parts[2], out intensity);
float.TryParse(parts[3], out duration);
float.TryParse(parts[4], out angleX);
float.TryParse(parts[5], out offsetY);
int.TryParse(parts[6], out interval);
int.TryParse(parts[7], out maxCount);
loops[parts[1]] = new(Math.Max(interval,1));
var startTime = DateTime.Now;
int currentCount = 0;
loops[parts[1]].Elapsed += (s, e) =>
{
if (currentCount >= maxCount)
{
loops[parts[1]].Stop();
loops[parts[1]].Dispose();
return;
}
Console.WriteLine("{0}, {1}, {2}", intensity, duration, angleX);
Presets.PresetHaptics[parts[1]].Invoke(intensity, duration, angleX);
currentCount++;
};
loops[parts[1]].Start();
}
else
Console.WriteLine($"World attempted to call unknown preset: {parts[1]}");
break;
case "Stop":
if (loops.ContainsKey(parts[1]))
{
loops[parts[1]].Stop();
loops[parts[1]].Dispose();
loops.Remove(parts[1]);
}
Presets.StopMixer(parts[1]);
break;
}
}
}
}