-
Notifications
You must be signed in to change notification settings - Fork 47
/
Cockpit.cs
521 lines (416 loc) · 18 KB
/
Cockpit.cs
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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
using System;
using System.Collections.Generic;
using System.Diagnostics;
using g3;
namespace f3
{
public interface ICockpitViewTracker
{
void UpdateTracking(Cockpit cockpit, fCamera camera);
}
public class Cockpit : SceneUIParent
{
FContext context;
fGameObject gameobject;
fGameObject onCameraGO;
// additional UI behavior attached to this cockpit
public InputBehaviorSet InputBehaviors { get; set; }
// special behaviors that are not part of regular capture-device handling
public InputBehaviorSet OverrideBehaviors { get; set; }
public GenericAnimator HUDAnimator { get; set; }
List<SceneUIElement> vUIElements;
public int UIElementLayer { get; set; } // Layer that UIElements will be placed in. default is FPlatform.HUDLayer
List<IShortcutKeyHandler> vKeyHandlers;
Dictionary<string, ICockpitLayout> Layouts;
ICockpitLayout defaultLayout;
public enum MovementMode
{
Static = 0,
TrackPosition = 1,
TrackOrientation = 2,
CustomTracking = 3
}
public MovementMode PositionMode { get; set; }
public ICockpitViewTracker CustomTracker { get; set; }
bool bStaticUpdated;
// [TODO] should be using this to restrict input but nobody respects it...
public bool GrabFocus { get; set; }
// this is up/down angle from straight-forward, that we apply after any tracking rotation
public float TiltAngle { get; set; }
// this is l/r angle from straight-forward, that we apply after any tracking rotation
public float ShiftAngle { get; set; }
// use to control depth of no-hit cursor (ie control focal plane)
// default is -1, ie ignore this value
public float DefaultCursorDepth { get; set; }
public Cockpit(FContext context)
{
PositionMode = MovementMode.TrackPosition;
GrabFocus = false;
bStaticUpdated = false;
this.context = context;
vUIElements = new List<SceneUIElement> ();
UIElementLayer = FPlatform.HUDLayer;
Layouts = new Dictionary<string, ICockpitLayout>();
defaultLayout = null;
vKeyHandlers = new List<IShortcutKeyHandler>();
InputBehaviors = new InputBehaviorSet() { DefaultSource = this };
OverrideBehaviors = new InputBehaviorSet() { DefaultSource = this };
HUDAnimator = new GenericAnimator();
TiltAngle = ShiftAngle = 0.0f;
DefaultCursorDepth = -1;
}
public void Destroy()
{
while (vUIElements.Count > 0)
RemoveUIElement(vUIElements[0], true);
RootGameObject.SetParent(null);
RootGameObject.Destroy();
}
public string Name
{
get { return RootGameObject.GetName(); }
set { RootGameObject.SetName(value); }
}
public FContext Context {
get { return context; }
}
public FScene Scene {
get { return Context.Scene; }
}
public fCamera ActiveCamera {
get { return Context.ActiveCamera; }
}
public fGameObject RootGameObject {
get { return gameobject; }
}
public fGameObject FixedCameraTrackingGO {
get { return onCameraGO; }
}
public bool IsActive {
get { return Context.ActiveCockpit == this; }
}
// cockpit frame is oriented such that
// +X is right
// +Y is up
// +Z is into scene
// note that for most unity mesh objects are created on the XZ plane, and so you
// need to rotate world_y to point to -cockpit_z, ie Quaternion.FromToRotation (Vector3.up, -cockpitF.Z)
public virtual Frame3f GetLocalFrame(CoordSpace eSpace)
{
return UnityUtil.GetGameObjectFrame (gameobject, eSpace);
}
public virtual void SetLocalFrame(Frame3f newFrame, CoordSpace eSpace)
{
UnityUtil.SetGameObjectFrame (gameobject, newFrame, eSpace);
}
// same as LocalFrame, but LocalFrame may be tilted up/down, which we want to undo
public virtual Frame3f GetLevelViewFrame(CoordSpace eSpace)
{
// otherwise we can't just set y to 0...
Debug.Assert(eSpace == CoordSpace.WorldCoords);
Frame3f viewF = UnityUtil.GetGameObjectFrame(ActiveCamera.GameObject(), eSpace);
float fAngle = VRUtil.PlaneAngleSigned(Vector3f.AxisZ, viewF.Z, 1);
return new Frame3f(viewF.Origin, Quaternionf.AxisAngleD(Vector3f.AxisY, fAngle));
}
// frame centered at cockpit location and aligned with camera direction
public virtual Frame3f GetViewFrame2D()
{
return new Frame3f(Vector3f.Zero, ActiveCamera.GetRotation());
}
/*
* 2D UI sizing.
*
*/
public virtual void OnWindowResized()
{
if (use_constant_scale)
constant_size_update();
}
bool use_constant_scale = false;
Vector2f start_pixel_scale = Vector2f.One;
Vector2f cur_pixel_scale = Vector2f.One;
Vector2f const_scale = Vector2f.One;
/// <summary>
/// Call this to turn on constant-size 2D cockpit scaling. This is a bit tricky.
/// The orthographic size of the camera stays at height=1, width = aspect*height, regardless
/// of the screen size. So, we have to keep track of the scaling between ortho and pixel dims.
/// Then if the window size changes, the relative x/y initial/cur scalings give us a scaling factor that
/// we can apply to the cockpit itself. This maintains fixed size, but the 2D view bounds will stay
/// fixed, unless we also scale them up - this is what GetConstantSizeOrthoViewBounds() is for.
/// 2D layout containers use this function and then the 2D box gets bigger/smaller with the screen size.
/// </summary>
public virtual void EnableConstantSize2DCockpit()
{
AxisAlignedBox2f uiBounds = GetOrthoViewBounds();
AxisAlignedBox2f pixelBounds = GetPixelViewBounds_DpiIndependent();
start_pixel_scale = new Vector2f(
uiBounds.Width / pixelBounds.Width,
uiBounds.Height / pixelBounds.Height);
use_constant_scale = true;
}
// updates cockpit scaling to maintain constant size - call in OnWindowResized()
protected virtual void constant_size_update()
{
AxisAlignedBox2f uiBounds = GetOrthoViewBounds();
AxisAlignedBox2f pixelBounds = GetPixelViewBounds_DpiIndependent();
cur_pixel_scale = new Vector2f(
uiBounds.Width / pixelBounds.Width,
uiBounds.Height / pixelBounds.Height);
const_scale = cur_pixel_scale / start_pixel_scale;
this.RootGameObject.SetLocalScale(new Vector3f(const_scale.x, const_scale.y, 1));
}
/// <summary>
/// get bounds of current orthographic camera view, in world coordinates
/// (ie box.Min is bottom-left corner of screen and box.Max is top-right
/// </summary>
public virtual AxisAlignedBox2f GetOrthoViewBounds()
{
if (context.OrthoUICamera == null)
return AxisAlignedBox2f.Empty;
float verticalSize = context.OrthoUICamera.OrthoHeight;
float aspect = (float)FPlatform.ScreenWidth / (float)FPlatform.ScreenHeight;
float horizontalSize = verticalSize * aspect;
return new AxisAlignedBox2f(-horizontalSize / 2, -verticalSize / 2, horizontalSize / 2, verticalSize / 2);
}
/// <summary>
/// GetOrthoViewBounds() inverse scaled by constant-size scaling factor,
/// so corners stay at corners of screen as cockpit is scaled
/// </summary>
public virtual AxisAlignedBox2f GetConstantSizeOrthoViewBounds()
{
AxisAlignedBox2f bounds = GetOrthoViewBounds();
return new AxisAlignedBox2f(bounds.Center, bounds.Width * 0.5f / const_scale.x, bounds.Height * 0.5f / const_scale.y);
}
/// <summary>
/// Pixel bounding box of 2D ortho viewport
/// </summary>
public virtual AxisAlignedBox2f GetPixelViewBounds_Absolute()
{
if (context.OrthoUICamera == null)
return AxisAlignedBox2f.Empty;
return new AxisAlignedBox2f(0, 0, FPlatform.ScreenWidth, FPlatform.ScreenHeight);
}
/// <summary>
/// DPI-normalized "Pixel" bounding-box of 2D ortho viewport,
/// (ie bounds will change depending on dpi)
/// </summary>
public virtual AxisAlignedBox2f GetPixelViewBounds_DpiIndependent()
{
if (context.OrthoUICamera == null)
return AxisAlignedBox2f.Empty;
float dpi_scale = GetDpiIndependentScale();
return new AxisAlignedBox2f(0, 0, FPlatform.ScreenWidth*dpi_scale, FPlatform.ScreenHeight*dpi_scale);
}
/// <summary>
/// scaling factor that normalizes for screen DPI (default is 96 DPI)
/// </summary>
public virtual float GetDpiIndependentScale() {
return 96.0f / FPlatform.ScreenDPI;
}
/// <summary>
/// Returns dpi-independent pixel scaling factor. Mainly intended to be used
/// for sizing UI elements.
/// This function multiplies by FPlatform.PixelScaleFactor.
/// </summary>
public float GetPixelScale(bool bDpiIndependent = true)
{
AxisAlignedBox2f uiBounds = GetOrthoViewBounds();
AxisAlignedBox2f pixelBounds =
(bDpiIndependent) ? GetPixelViewBounds_DpiIndependent() : GetPixelViewBounds_Absolute();
float fScale = uiBounds.Height / pixelBounds.Height;
// use ValidScreenDimensionRange to manipulate scale here?
if (FPlatform.InUnityEditor())
fScale *= FPlatform.EditorPixelScaleFactor;
else
fScale *= FPlatform.PixelScaleFactor;
return fScale;
}
/// <summary>
/// If cockpit is scaled (ie to maintain constant-pixel-size elements),
/// then we need a way to get 'scaled' dimensions of things
/// (what about positions...?)
/// </summary>
public Vector2f GetScaledDimensions(Vector2f v)
{
return v * const_scale;
}
// called by FContext.PushCockpit()
public void Start( ICockpitInitializer setup )
{
// create invisible plane for cockpit
gameobject = GameObjectFactory.CreateParentGO("cockpit");
onCameraGO = GameObjectFactory.CreateParentGO("cockpit_camera");
gameobject.AddChild(onCameraGO, false);
// add hud animation controller
gameobject.AddComponent<UnityPerFrameAnimationBehavior>().Animator = HUDAnimator;
// create HUD
try {
setup.Initialize(this);
} catch ( Exception e ) {
// if hud setup fails we still want to keep going
DebugUtil.Log(2, "[Cockpit.Start] exception in initializer: {0}\nTrace:\n{1}", e.Message, e.StackTrace);
if (FPlatform.InUnityEditor())
throw;
}
// position in front of camera
UpdateTracking(true);
}
public void Update()
{
UpdateTracking(false);
}
public void PreRender()
{
foreach (SceneUIElement ui in vUIElements)
ui.PreRender();
}
public void InitializeTracking(Cockpit fromExisting)
{
RootGameObject.SetPosition(fromExisting.RootGameObject.GetPosition());
RootGameObject.SetRotation(fromExisting.RootGameObject.GetRotation());
//RootGameObject.transform.position = fromExisting.RootGameObject.transform.position;
//RootGameObject.transform.rotation = fromExisting.RootGameObject.transform.rotation;
}
void UpdateTracking(bool bSetInitial)
{
if (bSetInitial || PositionMode == MovementMode.Static) {
// [TODO] should damp out jitter while allowing larger moves
if (bStaticUpdated == false) {
RootGameObject.SetPosition(ActiveCamera.GetPosition());
RootGameObject.SetRotation(Quaternionf.Identity);
bStaticUpdated = true;
}
} else if (PositionMode == MovementMode.TrackOrientation) {
RootGameObject.SetPosition(ActiveCamera.GetPosition());
RootGameObject.SetRotation(ActiveCamera.GetRotation());
} else if (PositionMode == MovementMode.CustomTracking && CustomTracker != null ) {
CustomTracker.UpdateTracking(this, ActiveCamera);
} else {
// MovemementMode.TrackPosition
RootGameObject.SetPosition(ActiveCamera.GetPosition());
RootGameObject.SetRotation(Quaternionf.Identity);
}
// apply post-rotations
Frame3f frame = RootGameObject.GetWorldFrame();
Quaternionf rotateLR = Quaternionf.AxisAngleD(frame.Y, ShiftAngle);
Quaternionf rotateUp = Quaternionf.AxisAngleD(rotateLR * frame.X, TiltAngle);
RootGameObject.SetRotation(rotateLR * rotateUp * RootGameObject.GetRotation());
// camera-tracking GO always tracks camera
onCameraGO.SetPosition(ActiveCamera.GetPosition());
onCameraGO.SetRotation(ActiveCamera.GetRotation());
}
public void InvalidateStaticPosition()
{
bStaticUpdated = false;
}
public void AddUIElement(SceneUIElement e, bool bIsInLocalFrame = true) {
vUIElements.Add (e);
e.Parent = this;
if (e.RootGameObject != null) {
// assume element transform is set to a local transform, so we want to apply current scene transform?
e.RootGameObject.SetParent(RootGameObject, (bIsInLocalFrame == false) );
}
e.SetLayer(UIElementLayer);
}
public void RemoveUIElement(SceneUIElement e, bool bDestroy) {
e.Disconnect();
vUIElements.Remove(e);
e.Parent = null;
if ( e.RootGameObject != null && bDestroy) {
e.RootGameObject.SetParent(null);
e.RootGameObject.Destroy();
}
}
public bool FindUIRayIntersection(Ray3f ray, out UIRayHit hit) {
return HUDUtil.FindNearestRayIntersection(vUIElements, ray, out hit);
}
public bool FindUIHoverRayIntersection(Ray3f ray, out UIRayHit hit) {
return HUDUtil.FindNearestHoverRayIntersection(vUIElements, ray, out hit);
}
public bool FindAnyRayIntersection(Ray3f ray, out AnyRayHit hit) {
hit = null;
UIRayHit bestUIHit = null;
if (FindUIRayIntersection (ray, out bestUIHit)) {
hit = new AnyRayHit (bestUIHit);
}
return (hit != null);
}
/// <summary>
/// Register a layout
/// </summary>
public void AddLayout(ICockpitLayout e, string name, bool bSetAsDefault = false)
{
if (Layouts.ContainsKey(name))
throw new Exception("Cockpit.AddLayout: tried to register duplicate name " + name);
// always set first layout as default, until another default comes along
if (Layouts.Count == 0)
bSetAsDefault = true;
Layouts[name] = e;
if (bSetAsDefault)
defaultLayout = e;
}
public void SetDefaultLayout(string name)
{
ICockpitLayout setdefault = null;
if (Layouts.TryGetValue(name, out setdefault) == false)
throw new Exception("Cockpit.SetDefaultLayout: could not find layout named " + name);
defaultLayout = setdefault;
}
/// <summary>
/// Remove named layout.
/// If bRemoveAllElements, then layout.RemoveAll() is called to clean up contents
/// (otherwise you must do yourself).
/// Note: if default layout is removed, we set default to null. You need to call SetDefaultLayout in this case.
/// </summary>
public void RemoveLayout(string name, bool bRemoveAllElements = true)
{
ICockpitLayout remove = null;
if (Layouts.TryGetValue(name, out remove) == false)
throw new Exception("Cockpit.RemoveLayout: could not find layout named " + name);
Layouts.Remove(name);
if ( bRemoveAllElements )
remove.RemoveAll(true);
if ( defaultLayout == remove )
defaultLayout = null;
// [TODO] can we auto-update default layout??
}
/// <summary>
/// get default Layout
/// </summary>
public ICockpitLayout DefaultLayout
{
get { return defaultLayout; }
}
/// <summary>
/// Find Layout with given name, or default layout if no argument
/// </summary>
public ICockpitLayout Layout(string name = "") {
if (name == "")
return defaultLayout;
ICockpitLayout r = null;
if (Layouts.TryGetValue(name, out r) == false)
throw new Exception("Cockpit.Layout: could not find layout named " + name);
return r;
}
public void AddKeyHandler(IShortcutKeyHandler h)
{
vKeyHandlers.Add(h);
}
public void RemoveKeyHandler(IShortcutKeyHandler h)
{
vKeyHandlers.Remove(h);
}
public bool HandleShortcutKeys()
{
//if (FPlatformUI.IsConsumingMouseInput())
// return false;
if (FPlatformUI.TextEntryFieldHasFocus())
return false;
foreach ( IShortcutKeyHandler h in vKeyHandlers ) {
if (h.HandleShortcuts())
return true;
}
return false;
}
}
}