BlueGit

blue-star ggj-2020

Files

ggj-2020 / Assets / Oculus / VoiceMod / Scripts / Helpers / OVRMessenger.cs

OVRMessenger.cs

Project Import
timfa Tim Falken · pushed by timfa · 6 years ago
b77834a1 History
OVRMessenger.cs 15.4 KiB Download Raw
1/************************************************************************************
2Filename : OVRMessenger.cs
3Content : Base component OVR class
4Created : January 8, 2013
5Authors : Peter Giokaris
6Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved.
7
8Use of this software is subject to the terms of the Oculus LLC license
9agreement provided at the time of installation or download, or which
10otherwise accompanies this software in either electronic or hard copy form.
11
12 Messenger.cs from Unity3d: http://wiki.unity3d.com/index.php/Advanced_CSharp_Messenger
13
14 Renamed to OVRMessenger
15
16 * Advanced C# messenger by Ilya Suzdalnitski. V1.0
17 *
18 * Based on Rod Hyde's "CSharpMessenger" and Magnus Wolffelt's "CSharpMessenger Extended".
19 *
20 * Features:
21 * Prevents a MissingReferenceException because of a reference to a destroyed message handler.
22 * Option to log all messages
23 * Extensive error detection, preventing silent bugs
24 *
25 * Usage examples:
26 1. Messenger.AddListener<GameObject>("prop collected", PropCollected);
27 Messenger.Broadcast<GameObject>("prop collected", prop);
28 2. Messenger.AddListener<float>("speed changed", SpeedChanged);
29 Messenger.Broadcast<float>("speed changed", 0.5f);
30 *
31 * Messenger cleans up its evenTable automatically upon loading of a new level.
32 *
33 * Don't forget that the messages that should survive the cleanup, should be marked with Messenger.MarkAsPermanent(string)
34 *
35
36************************************************************************************/
37//#define LOG_ALL_MESSAGES
38//#define LOG_ADD_LISTENER
39//#define LOG_BROADCAST_MESSAGE
40//#define REQUIRE_LISTENER
41
42using System;
43using System.Collections.Generic;
44using UnityEngine;
45
46 // Add more delegate types here and implement them the same way below..
47public delegate void OVRCallback();
48public delegate void OVRCallback<T>(T arg1);
49public delegate void OVRCallback<T, U>(T arg1, U arg2);
50public delegate void OVRCallback<T, U, V>(T arg1, U arg2, V arg3);
51
52static internal class OVRMessenger {
53
54#region Internal variables
55 //Disable the unused variable warning
56#pragma warning disable 0414
57 //Ensures that the MessengerHelper will be created automatically upon start of the game.
58 static private MessengerHelper messengerHelper = ( new GameObject("MessengerHelper") ).AddComponent< MessengerHelper >();
59#pragma warning restore 0414
60
61 static public Dictionary<string, Delegate> eventTable = new Dictionary<string, Delegate>();
62
63 //Message handlers that should never be removed, regardless of calling Cleanup
64 static public List< string > permanentMessages = new List< string > ();
65#endregion
66
67#region Helper methods
68
69 /// <summary>
70 /// Marks a certain message as permanent.
71 /// </summary>
72 /// <param name="eventType">Event type.</param>
73 static public void MarkAsPermanent(string eventType)
74 {
75#if LOG_ALL_MESSAGES
76 Debug.Log("Messenger MarkAsPermanent \t\"" + eventType + "\"");
77#endif
78 permanentMessages.Add( eventType );
79 }
80
81 /// <summary>
82 /// Cleanup this instance.
83 /// </summary>
84 static public void Cleanup()
85 {
86#if LOG_ALL_MESSAGES
87 Debug.Log("MESSENGER Cleanup. Make sure that none of necessary listeners are removed.");
88#endif
89 List< string > messagesToRemove = new List<string>();
90
91 foreach (KeyValuePair<string, Delegate> pair in eventTable) {
92 bool wasFound = false;
93
94 foreach (string message in permanentMessages) {
95
96 if (pair.Key == message) {
97 wasFound = true;
98 break;
99 }
100 }
101
102 if (!wasFound)
103 messagesToRemove.Add( pair.Key );
104 }
105
106
107 foreach (string message in messagesToRemove) {
108 eventTable.Remove( message );
109 }
110 }
111
112 /// <summary>
113 /// Prints the event table.
114 /// </summary>
115 static public void PrintEventTable()
116 {
117 Debug.Log("\t\t\t=== MESSENGER PrintEventTable ===");
118
119 foreach (KeyValuePair<string, Delegate> pair in eventTable) {
120 Debug.Log("\t\t\t" + pair.Key + "\t\t" + pair.Value);
121 }
122
123 Debug.Log("\n");
124 }
125#endregion
126
127 #region Message logging and exception throwing
128 /// <summary>
129 /// Raises the listener adding event.
130 /// </summary>
131 /// <param name="eventType">Event type.</param>
132 /// <param name="listenerBeingAdded">Listener being added.</param>
133 static public void OnListenerAdding(string eventType, Delegate listenerBeingAdded)
134 {
135#if LOG_ALL_MESSAGES || LOG_ADD_LISTENER
136 Debug.Log("MESSENGER OnListenerAdding \t\"" + eventType + "\"\t{" + listenerBeingAdded.Target + " -> " + listenerBeingAdded.Method + "}");
137#endif
138
139 if (!eventTable.ContainsKey(eventType)) {
140 eventTable.Add(eventType, null );
141 }
142
143 Delegate d = eventTable[eventType];
144
145 if (d != null && d.GetType() != listenerBeingAdded.GetType()) {
146 throw new ListenerException(string.Format("Attempting to add listener with inconsistent signature for event type {0}. Current listeners have type {1} and listener being added has type {2}", eventType, d.GetType().Name, listenerBeingAdded.GetType().Name));
147 }
148 }
149
150 /// <summary>
151 /// Raises the listener removing event.
152 /// </summary>
153 /// <param name="eventType">Event type.</param>
154 /// <param name="listenerBeingRemoved">Listener being removed.</param>
155 static public void OnListenerRemoving(string eventType, Delegate listenerBeingRemoved)
156 {
157
158#if LOG_ALL_MESSAGES
159 Debug.Log("MESSENGER OnListenerRemoving \t\"" + eventType + "\"\t{" + listenerBeingRemoved.Target + " -> " + listenerBeingRemoved.Method + "}");
160#endif
161
162 if (eventTable.ContainsKey(eventType))
163 {
164 Delegate d = eventTable[eventType];
165
166 if (d == null)
167 {
168 throw new ListenerException(string.Format("Attempting to remove listener with for event type \"{0}\" but current listener is null.", eventType));
169 } else if (d.GetType() != listenerBeingRemoved.GetType())
170 {
171 throw new ListenerException(string.Format("Attempting to remove listener with inconsistent signature for event type {0}. Current listeners have type {1} and listener being removed has type {2}", eventType, d.GetType().Name, listenerBeingRemoved.GetType().Name));
172 }
173 }
174 else
175 {
176 throw new ListenerException(string.Format("Attempting to remove listener for type \"{0}\" but Messenger doesn't know about this event type.", eventType));
177 }
178 }
179
180 /// <summary>
181 /// Raises the listener removed event.
182 /// </summary>
183 /// <param name="eventType">Event type.</param>
184 static public void OnListenerRemoved(string eventType) {
185
186 if (eventTable[eventType] == null) {
187 eventTable.Remove(eventType);
188 }
189 }
190
191 /// <summary>
192 /// Raises the broadcasting event.
193 /// </summary>
194 /// <param name="eventType">Event type.</param>
195 static public void OnBroadcasting(string eventType)
196 {
197
198#if REQUIRE_LISTENER
199 if (!eventTable.ContainsKey(eventType)) {
200 throw new BroadcastException(string.Format("Broadcasting message \"{0}\" but no listener found. Try marking the message with Messenger.MarkAsPermanent.", eventType));
201 }
202#endif
203 }
204
205 /// <summary>
206 /// Creates the broadcast signature exception.
207 /// </summary>
208 /// <returns>The broadcast signature exception.</returns>
209 /// <param name="eventType">Event type.</param>
210 static public BroadcastException CreateBroadcastSignatureException(string eventType)
211 {
212 return new BroadcastException(string.Format("Broadcasting message \"{0}\" but listeners have a different signature than the broadcaster.", eventType));
213 }
214
215 public class BroadcastException : Exception
216 {
217 public BroadcastException(string msg)
218 : base(msg)
219 {
220 }
221 }
222
223 public class ListenerException : Exception
224 {
225 public ListenerException(string msg)
226 : base(msg)
227 {
228 }
229 }
230#endregion
231
232#region AddListener
233 /// <summary>
234 /// No parameters.
235 /// </summary>
236 /// <param name="eventType">Event type.</param>
237 /// <param name="handler">Handler.</param>
238 static public void AddListener(string eventType, OVRCallback handler)
239 {
240 OnListenerAdding(eventType, handler);
241 eventTable[eventType] = (OVRCallback)eventTable[eventType] + handler;
242 }
243
244 /// <summary>
245 /// Single parameter.
246 /// </summary>
247 /// <param name="eventType">Event type.</param>
248 /// <param name="handler">Handler.</param>
249 /// <typeparam name="T">The 1st type parameter.</typeparam>
250 static public void AddListener<T>(string eventType, OVRCallback<T> handler)
251 {
252 OnListenerAdding(eventType, handler);
253 eventTable[eventType] = (OVRCallback<T>)eventTable[eventType] + handler;
254 }
255
256 /// <summary>
257 /// Two parameters.
258 /// </summary>
259 /// <param name="eventType">Event type.</param>
260 /// <param name="handler">Handler.</param>
261 /// <typeparam name="T">The 1st type parameter.</typeparam>
262 /// <typeparam name="U">The 2nd type parameter.</typeparam>
263 static public void AddListener<T, U>(string eventType, OVRCallback<T, U> handler)
264 {
265 OnListenerAdding(eventType, handler);
266 eventTable[eventType] = (OVRCallback<T, U>)eventTable[eventType] + handler;
267 }
268
269 /// <summary>
270 /// Three parameters
271 /// </summary
272 /// <param name="eventType">Event type.</param>
273 /// <param name="handler">Handler.</param>
274 /// <typeparam name="T">The 1st type parameter.</typeparam>
275 /// <typeparam name="U">The 2nd type parameter.</typeparam>
276 /// <typeparam name="V">The 3rd type parameter.</typeparam>
277 static public void AddListener<T, U, V>(string eventType, OVRCallback<T, U, V> handler)
278 {
279 OnListenerAdding(eventType, handler);
280 eventTable[eventType] = (OVRCallback<T, U, V>)eventTable[eventType] + handler;
281 }
282#endregion
283
284#region RemoveListener
285 /// <summary>
286 /// No parameters
287 /// </summary>
288 /// <param name="eventType">Event type.</param>
289 /// <param name="handler">Handler.</param>
290 static public void RemoveListener(string eventType, OVRCallback handler)
291 {
292 OnListenerRemoving(eventType, handler);
293 eventTable[eventType] = (OVRCallback)eventTable[eventType] - handler;
294 OnListenerRemoved(eventType);
295 }
296
297 /// <summary>
298 /// Single parameter
299 /// </summary>
300 /// <param name="eventType">Event type.</param>
301 /// <param name="handler">Handler.</param>
302 /// <typeparam name="T">The 1st type parameter.</typeparam>
303 static public void RemoveListener<T>(string eventType, OVRCallback<T> handler)
304 {
305 OnListenerRemoving(eventType, handler);
306 eventTable[eventType] = (OVRCallback<T>)eventTable[eventType] - handler;
307 OnListenerRemoved(eventType);
308 }
309
310 /// <summary>
311 /// Two parameters
312 /// </summary>
313 /// <param name="eventType">Event type.</param>
314 /// <param name="handler">Handler.</param>
315 /// <typeparam name="T">The 1st type parameter.</typeparam>
316 /// <typeparam name="U">The 2nd type parameter.</typeparam>
317 static public void RemoveListener<T, U>(string eventType, OVRCallback<T, U> handler)
318 {
319 OnListenerRemoving(eventType, handler);
320 eventTable[eventType] = (OVRCallback<T, U>)eventTable[eventType] - handler;
321 OnListenerRemoved(eventType);
322 }
323
324 /// <summary>
325 //Three parameters.
326 /// </summary>
327 /// <param name="eventType">Event type.</param>
328 /// <param name="handler">Handler.</param>
329 /// <typeparam name="T">The 1st type parameter.</typeparam>
330 /// <typeparam name="U">The 2nd type parameter.</typeparam>
331 /// <typeparam name="V">The 3rd type parameter.</typeparam>
332 static public void RemoveListener<T, U, V>(string eventType, OVRCallback<T, U, V> handler)
333 {
334 OnListenerRemoving(eventType, handler);
335 eventTable[eventType] = (OVRCallback<T, U, V>)eventTable[eventType] - handler;
336 OnListenerRemoved(eventType);
337 }
338
339#endregion
340
341#region Broadcast
342 /// <summary>
343 /// Broadcast the specified eventType.
344 /// </summary>
345 /// <param name="eventType">Event type.</param>
346 static public void Broadcast(string eventType)
347 {
348#if LOG_ALL_MESSAGES || LOG_BROADCAST_MESSAGE
349 Debug.Log("MESSENGER\t" + System.DateTime.Now.ToString("hh:mm:ss.fff") + "\t\t\tInvoking \t\"" + eventType + "\"");
350#endif
351 OnBroadcasting(eventType);
352
353 Delegate d;
354 if (eventTable.TryGetValue(eventType, out d)) {
355 OVRCallback callback = d as OVRCallback;
356
357 if (callback != null) {
358 callback();
359 } else {
360 throw CreateBroadcastSignatureException(eventType);
361 }
362 }
363 }
364
365 /// <summary>
366 /// Broadcast the specified eventType and arg1.
367 /// </summary>
368 /// <param name="eventType">Event type.</param>
369 /// <param name="arg1">Arg1.</param>
370 /// <typeparam name="T">The 1st type parameter.</typeparam>
371 static public void Broadcast<T>(string eventType, T arg1) {
372#if LOG_ALL_MESSAGES || LOG_BROADCAST_MESSAGE
373 Debug.Log("MESSENGER\t" + System.DateTime.Now.ToString("hh:mm:ss.fff") + "\t\t\tInvoking \t\"" + eventType + "\"");
374#endif
375 OnBroadcasting(eventType);
376
377 Delegate d;
378
379 if (eventTable.TryGetValue(eventType, out d)) {
380 OVRCallback<T> callback = d as OVRCallback<T>;
381
382 if (callback != null) {
383 callback(arg1);
384 } else {
385 throw CreateBroadcastSignatureException(eventType);
386 }
387 }
388 }
389
390 /// <summary>
391 /// Broadcast the specified eventType, arg1 and arg2.
392 /// </summary>
393 /// <param name="eventType">Event type.</param>
394 /// <param name="arg1">Arg1.</param>
395 /// <param name="arg2">Arg2.</param>
396 /// <typeparam name="T">The 1st type parameter.</typeparam>
397 /// <typeparam name="U">The 2nd type parameter.</typeparam>
398 static public void Broadcast<T, U>(string eventType, T arg1, U arg2)
399 {
400#if LOG_ALL_MESSAGES || LOG_BROADCAST_MESSAGE
401 Debug.Log("MESSENGER\t" + System.DateTime.Now.ToString("hh:mm:ss.fff") + "\t\t\tInvoking \t\"" + eventType + "\"");
402#endif
403 OnBroadcasting(eventType);
404
405 Delegate d;
406
407 if (eventTable.TryGetValue(eventType, out d)) {
408 OVRCallback<T, U> callback = d as OVRCallback<T, U>;
409
410 if (callback != null) {
411 callback(arg1, arg2);
412 } else {
413 throw CreateBroadcastSignatureException(eventType);
414 }
415 }
416 }
417
418 /// <summary>
419 /// Broadcast the specified eventType, arg1, arg2 and arg3.
420 /// </summary>
421 /// <param name="eventType">Event type.</param>
422 /// <param name="arg1">Arg1.</param>
423 /// <param name="arg2">Arg2.</param>
424 /// <param name="arg3">Arg3.</param>
425 /// <typeparam name="T">The 1st type parameter.</typeparam>
426 /// <typeparam name="U">The 2nd type parameter.</typeparam>
427 /// <typeparam name="V">The 3rd type parameter.</typeparam>
428 static public void Broadcast<T, U, V>(string eventType, T arg1, U arg2, V arg3)
429 {
430#if LOG_ALL_MESSAGES || LOG_BROADCAST_MESSAGE
431 Debug.Log("MESSENGER\t" + System.DateTime.Now.ToString("hh:mm:ss.fff") + "\t\t\tInvoking \t\"" + eventType + "\"");
432#endif
433 OnBroadcasting(eventType);
434
435 Delegate d;
436 if (eventTable.TryGetValue(eventType, out d)) {
437 OVRCallback<T, U, V> callback = d as OVRCallback<T, U, V>;
438
439 if (callback != null) {
440 callback(arg1, arg2, arg3);
441 } else {
442 throw CreateBroadcastSignatureException(eventType);
443 }
444 }
445 }
446#endregion
447}
448
449/// <summary>
450/// Messenger helper.
451/// This manager will ensure that the messenger's eventTable will be cleaned up upon loading of a new level.
452/// </summary>
453public sealed class MessengerHelper : MonoBehaviour
454{
455 /// <summary>
456 /// Awake this instance.
457 /// </summary>
458 void Awake ()
459 {
460 DontDestroyOnLoad(gameObject);
461 }
462
463 /// <summary>
464 /// Raises the disable event.
465 /// </summary>
466 public void OnDisable()
467 {
468 OVRMessenger.Cleanup();
469 }
470}