-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
633 lines (515 loc) · 22.8 KB
/
Program.cs
File metadata and controls
633 lines (515 loc) · 22.8 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
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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
using System.Numerics;
using ImGuiNET;
using Silk.NET.Input;
using Silk.NET.Maths;
using Silk.NET.OpenGL;
using Silk.NET.OpenGL.Extensions.ImGui;
using Silk.NET.Windowing;
namespace hijacking
{
internal static class Program
{
private static CameraDescriptor cameraDescriptor = new();
private static ArrangementModel arrangementModel = new();
private static IWindow window;
private static IInputContext inputContext;
private static GL Gl;
private static ImGuiController controller;
private static uint program;
private static GlObject airbus;
private static GlObject[] fighterJets = new GlObject[4];
private static GlObject road;
private static GlCube skyBox;
private static float Shininess = 50;
private static float movementSpeed = 2.0f;
private static Dictionary<Key, bool> keyStates = new Dictionary<Key, bool>
{
{ Key.Left, false },
{ Key.Right, false },
{ Key.Down, false },
{ Key.Up, false },
{ Key.A, false },
{ Key.D, false },
{ Key.Space, false }
};
private static float viewerPositionSpeed = 0.09f;
private static float rotationAngle = 0f;
private static bool isColidingWithRoad = false;
private static bool isColidingWithFighterJets = false;
private static bool planeMiss = false;
private const string ModelMatrixVariableName = "uModel";
private const string NormalMatrixVariableName = "uNormal";
private const string ViewMatrixVariableName = "uView";
private const string ProjectionMatrixVariableName = "uProjection";
private const string TextureUniformVariableName = "uTexture";
private const string LightColorVariableName = "lightColor";
private const string LightPositionVariableName = "lightPos";
private const string ViewPosVariableName = "viewPos";
private const string ShininessVariableName = "shininess";
private static bool pov = false;
static void Main(string[] args)
{
WindowOptions windowOptions = WindowOptions.Default;
windowOptions.Title = "Hijacking";
windowOptions.Size = new Vector2D<int>(1000, 1000);
// on some systems there is no depth buffer by default, so we need to make sure one is created
windowOptions.PreferredDepthBufferBits = 24;
window = Window.Create(windowOptions);
window.Load += Window_Load;
window.Update += Window_Update;
window.Render += Window_Render;
window.Closing += Window_Closing;
window.Run();
}
private static void Window_Load()
{
//Console.WriteLine("Load");
// set up input handling
inputContext = window.CreateInput();
foreach (var keyboard in inputContext.Keyboards)
{
keyboard.KeyDown += Keyboard_KeyDown;
keyboard.KeyUp += Keyboard_KeyUp;
}
Gl = window.CreateOpenGL();
controller = new ImGuiController(Gl, window, inputContext);
// Handle resizes
window.FramebufferResize += s =>
{
// Adjust the viewport to the new window size
Gl.Viewport(s);
};
Gl.ClearColor(System.Drawing.Color.Black);
SetUpObjects();
LinkProgram();
cameraDescriptor.setMovementSpeed(arrangementModel.getMovementSpeed());
cameraDescriptor.setTurningSpeed(arrangementModel.getTurningSpeed());
//Gl.Enable(EnableCap.CullFace);
Gl.Enable(EnableCap.DepthTest);
Gl.DepthFunc(DepthFunction.Lequal);
}
private static void LinkProgram()
{
uint vshader = Gl.CreateShader(ShaderType.VertexShader);
uint fshader = Gl.CreateShader(ShaderType.FragmentShader);
Gl.ShaderSource(vshader, ReadShader("VertexShader.vert"));
Gl.CompileShader(vshader);
Gl.GetShader(vshader, ShaderParameterName.CompileStatus, out int vStatus);
if (vStatus != (int)GLEnum.True)
throw new Exception("Vertex shader failed to compile: " + Gl.GetShaderInfoLog(vshader));
Gl.ShaderSource(fshader, ReadShader("FragmentShader.frag"));
Gl.CompileShader(fshader);
program = Gl.CreateProgram();
Gl.AttachShader(program, vshader);
Gl.AttachShader(program, fshader);
Gl.LinkProgram(program);
Gl.GetProgram(program, GLEnum.LinkStatus, out var status);
if (status == 0)
{
Console.WriteLine($"Error linking shader {Gl.GetProgramInfoLog(program)}");
}
Gl.DetachShader(program, vshader);
Gl.DetachShader(program, fshader);
Gl.DeleteShader(vshader);
Gl.DeleteShader(fshader);
}
private static string ReadShader(string shaderFileName)
{
using (Stream shaderStream = typeof(Program).Assembly.GetManifestResourceStream("hijacking.Shaders." + shaderFileName))
using (StreamReader shaderReader = new StreamReader(shaderStream))
return shaderReader.ReadToEnd();
}
private static void Keyboard_KeyDown(IKeyboard keyboard, Key key, int arg3)
{
if (keyStates.ContainsKey(key))
{
keyStates[key] = true;
}
}
private static void Keyboard_KeyUp(IKeyboard keyboard, Key key, int arg3)
{
if (keyStates.ContainsKey(key))
{
keyStates[key] = false;
}
}
private static void Window_Update(double deltaTime)
{
// multithreaded
// make sure it is threadsafe
// NO GL calls
PilotControl();
arrangementModel.AdvanceTime();
cameraDescriptor.MoveForward();
Vector3D<float> airbusPosition = arrangementModel.airplaneTranslation;
Hitbox airbusHitbox = airbus.Hitbox.Translated(airbusPosition);
if (arrangementModel.getColifingWithFighterJet() == -1)
{
Vector3D<float> roadPosition = arrangementModel.roadPosition;
Hitbox roadHitbox = road.Hitbox.Translated(roadPosition);
if (airbusHitbox.IsColliding(roadHitbox))
{
isColidingWithRoad = true;
arrangementModel.setColidingWithRoad();
cameraDescriptor.SetColidingWithRoad();
}
}
for (int i = 0; i < 4; i++)
{
Vector3D<float> jetPosition = arrangementModel.aircraftPosition[i];
Hitbox jetHitbox = fighterJets[i].Hitbox.Translated(jetPosition);
if (airbusHitbox.IsColliding(jetHitbox))
{
isColidingWithFighterJets = true;
arrangementModel.setColidingWithFighterJet(i);
cameraDescriptor.SetColidingWithFighterJets();
}
}
if (airbusPosition.Y < arrangementModel.roadPosition.Y && !planeMiss)
{
planeMiss = true;
}
controller.Update((float)deltaTime);
}
private static unsafe void Window_Render(double deltaTime)
{
//Console.WriteLine($"Render after {deltaTime} [s].");
// GL here
Gl.Clear(ClearBufferMask.ColorBufferBit);
Gl.Clear(ClearBufferMask.DepthBufferBit);
Gl.UseProgram(program);
SetViewMatrix();
SetProjectionMatrix();
SetLightColor();
SetLightPosition();
SetViewerPosition();
SetShininess();
DrawAirbus();
DrawSkyBox();
DrawRoad();
DrawFighter();
if (isColidingWithFighterJets)
{
ImGui.SetNextWindowPos(new Vector2(window.Size.X / 2 - 100, window.Size.Y / 2 - 50));
ImGui.Begin("Game Over");
ImGui.Text("You have crashed into a fighter jet");
ImGui.End();
}
if (isColidingWithRoad)
{
ImGui.SetNextWindowPos(new Vector2(window.Size.X / 2 - 100, window.Size.Y / 2 - 50));
ImGui.Begin("Game Over");
ImGui.Text("Congratulations you have landed safely!");
ImGui.End();
}
if (planeMiss)
{
ImGui.SetNextWindowPos(new Vector2(window.Size.X / 2 - 100, window.Size.Y / 2 - 50));
ImGui.Begin("Game Over");
ImGui.Text("You have missed the road");
ImGui.End();
}
//ImGuiNET.ImGui.ShowDemoWindow();
ImGui.SetNextWindowPos(new Vector2(0,0));
ImGuiNET.ImGui.Begin("Pilot Position",
ImGuiWindowFlags.AlwaysAutoResize | ImGuiWindowFlags.NoTitleBar);
if (ImGui.RadioButton("FPV", pov))
{
if (!pov)
{
cameraDescriptor.SetFPV();
}
pov = true;
Console.WriteLine("POV selected");
}
ImGui.SameLine();
if (ImGui.RadioButton("TPV", !pov))
{
if (pov)
{
cameraDescriptor.SetTPV();
}
pov = false;
Console.WriteLine("TPV selected");
}
ImGuiNET.ImGui.End();
ImGui.SetNextWindowPos(new Vector2(0, 50));
// set a bar for setting the movementSpeed min speed is 1.5 and max speed is 6.0
ImGui.Begin("Movement Speed");
ImGui.SliderFloat("Movement Speed", ref movementSpeed, 1.5f, 6.0f);
arrangementModel.setMovementSpeed(movementSpeed);
cameraDescriptor.setMovementSpeed(movementSpeed);
controller.Render();
}
private static unsafe void SetLightColor()
{
int location = Gl.GetUniformLocation(program, LightColorVariableName);
if (location == -1)
{
throw new Exception($"{LightColorVariableName} uniform not found on shader.");
}
Gl.Uniform3(location, 1f, 1f, 1f);
CheckError();
}
private static unsafe void SetLightPosition()
{
int location = Gl.GetUniformLocation(program, LightPositionVariableName);
if (location == -1)
{
throw new Exception($"{LightPositionVariableName} uniform not found on shader.");
}
Gl.Uniform3(location, 0f, 200f, 0f);
CheckError();
}
private static unsafe void SetViewerPosition()
{
int location = Gl.GetUniformLocation(program, ViewPosVariableName);
if (location == -1)
{
throw new Exception($"{ViewPosVariableName} uniform not found on shader.");
}
Gl.Uniform3(location, cameraDescriptor.Position.X, cameraDescriptor.Position.Y, cameraDescriptor.Position.Z);
CheckError();
}
private static unsafe void SetShininess()
{
int location = Gl.GetUniformLocation(program, ShininessVariableName);
if (location == -1)
{
throw new Exception($"{ShininessVariableName} uniform not found on shader.");
}
Gl.Uniform1(location, Shininess);
CheckError();
}
private static unsafe void DrawSkyBox()
{
Matrix4X4<float> modelMatrix = Matrix4X4.CreateScale(40000f);
SetModelMatrix(modelMatrix);
Gl.BindVertexArray(skyBox.Vao);
int textureLocation = Gl.GetUniformLocation(program, TextureUniformVariableName);
if (textureLocation == -1)
{
throw new Exception($"{TextureUniformVariableName} uniform not found on shader.");
}
// set texture 0
Gl.Uniform1(textureLocation, 0);
Gl.ActiveTexture(TextureUnit.Texture0);
Gl.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (float)GLEnum.Linear);
Gl.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (float)GLEnum.Linear);
Gl.BindTexture(TextureTarget.Texture2D, skyBox.Texture.Value);
Gl.DrawElements(GLEnum.Triangles, skyBox.IndexArrayLength, GLEnum.UnsignedInt, null);
Gl.BindVertexArray(0);
CheckError();
Gl.BindTexture(TextureTarget.Texture2D, 0);
CheckError();
}
private static unsafe void DrawRoad()
{
var translationMatrix = Matrix4X4.CreateTranslation(arrangementModel.roadPosition);
var modelMatrix = translationMatrix;
SetModelMatrix(modelMatrix);
Gl.BindVertexArray(road.Vao);
int textureLocation = Gl.GetUniformLocation(program, TextureUniformVariableName);
if (textureLocation == -1)
{
throw new Exception($"{TextureUniformVariableName} uniform not found on shader.");
}
// set texture 0
Gl.Uniform1(textureLocation, 0);
Gl.ActiveTexture(TextureUnit.Texture0);
Gl.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (float)GLEnum.Linear);
Gl.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (float)GLEnum.Linear);
Gl.BindTexture(TextureTarget.Texture2D, road.Texture.Value);
Gl.DrawElements(GLEnum.Triangles, road.IndexArrayLength, GLEnum.UnsignedInt, null);
Gl.BindVertexArray(0);
CheckError();
Gl.BindTexture(TextureTarget.Texture2D, 0);
CheckError();
}
private static unsafe void DrawAirbus()
{
if (arrangementModel.getColifingWithFighterJet() == -1)
{
var translationMatrix = Matrix4X4.CreateTranslation(arrangementModel.airplaneTranslation);
//var rotationMatrix = Matrix4X4.CreateRotationX((float)-Math.PI/2);
var modelMatrixForCenterCube = translationMatrix;
//var modelMatrixForCenterCube = translationMatrix;
SetModelMatrix(modelMatrixForCenterCube);
Gl.BindVertexArray(airbus.Vao);
}
else if (arrangementModel.getColifingWithFighterJet() != -1)
{
var lookDownRotationMatrix = Matrix4X4.CreateRotationX((float)-Math.PI / 2);
var translationMatrix = Matrix4X4.CreateTranslation(arrangementModel.airplaneTranslation);
var rotationMatrix = Matrix4X4.CreateRotationZ(rotationAngle);
var modelMatrixForCenterCube = rotationMatrix * lookDownRotationMatrix * translationMatrix;
SetModelMatrix(modelMatrixForCenterCube);
Gl.BindVertexArray(airbus.Vao);
}
int textureLocation = Gl.GetUniformLocation(program, TextureUniformVariableName);
if (textureLocation == -1)
{
throw new Exception($"{TextureUniformVariableName} uniform not found on shader.");
}
// set texture 0
Gl.Uniform1(textureLocation, 0);
Gl.ActiveTexture(TextureUnit.Texture0);
Gl.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (float)GLEnum.Linear);
Gl.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (float)GLEnum.Linear);
Gl.BindTexture(TextureTarget.Texture2D, airbus.Texture.Value);
Gl.DrawElements(GLEnum.Triangles, airbus.IndexArrayLength, GLEnum.UnsignedInt, null);
Gl.BindVertexArray(0);
CheckError();
Gl.BindTexture(TextureTarget.Texture2D, 0);
CheckError();
}
private static unsafe void DrawFighter()
{
rotationAngle += 0.02f;
// set material uniform to rubber
for (int i = 0; i < fighterJets.Length; i++)
{
var translationMatrix = Matrix4X4.CreateTranslation(arrangementModel.aircraftPosition[i]);
if (i == arrangementModel.getColifingWithFighterJet())
{
// Apply rotation to the specific fighter jet
var lookDownRotationMatrix = Matrix4X4.CreateRotationX((float)-Math.PI / 2);
var rotationMatrix = Matrix4X4.CreateRotationZ(rotationAngle);
var modelMatrixForCenterCube = rotationMatrix * lookDownRotationMatrix * translationMatrix;
SetModelMatrix(modelMatrixForCenterCube);
Gl.BindVertexArray(fighterJets[i].Vao);
}
else
{
var modelMatrixForCenterCube = translationMatrix;
SetModelMatrix(modelMatrixForCenterCube);
Gl.BindVertexArray(fighterJets[i].Vao);
}
int textureLocation = Gl.GetUniformLocation(program, TextureUniformVariableName);
if (textureLocation == -1)
{
throw new Exception($"{TextureUniformVariableName} uniform not found on shader.");
}
// set texture 0
Gl.Uniform1(textureLocation, 0);
Gl.ActiveTexture(TextureUnit.Texture0);
Gl.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (float)GLEnum.Linear);
Gl.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (float)GLEnum.Linear);
Gl.BindTexture(TextureTarget.Texture2D, fighterJets[i].Texture.Value);
Gl.DrawElements(GLEnum.Triangles, fighterJets[i].IndexArrayLength, GLEnum.UnsignedInt, null);
Gl.BindVertexArray(0);
CheckError();
Gl.BindTexture(TextureTarget.Texture2D, 0);
CheckError();
}
}
private static unsafe void SetModelMatrix(Matrix4X4<float> modelMatrix)
{
int location = Gl.GetUniformLocation(program, ModelMatrixVariableName);
if (location == -1)
{
throw new Exception($"{ModelMatrixVariableName} uniform not found on shader.");
}
Gl.UniformMatrix4(location, 1, false, (float*)&modelMatrix);
CheckError();
var modelMatrixWithoutTranslation = new Matrix4X4<float>(modelMatrix.Row1, modelMatrix.Row2, modelMatrix.Row3, modelMatrix.Row4);
modelMatrixWithoutTranslation.M41 = 0;
modelMatrixWithoutTranslation.M42 = 0;
modelMatrixWithoutTranslation.M43 = 0;
modelMatrixWithoutTranslation.M44 = 1;
Matrix4X4<float> modelInvers;
Matrix4X4.Invert<float>(modelMatrixWithoutTranslation, out modelInvers);
Matrix3X3<float> normalMatrix = new Matrix3X3<float>(Matrix4X4.Transpose(modelInvers));
location = Gl.GetUniformLocation(program, NormalMatrixVariableName);
if (location == -1)
{
throw new Exception($"{NormalMatrixVariableName} uniform not found on shader.");
}
Gl.UniformMatrix3(location, 1, false, (float*)&normalMatrix);
CheckError();
}
private static unsafe void SetUpObjects()
{
airbus = ObjResourceReader.CreateAirbus(Gl);
skyBox = GlCube.CreateInteriorCube(Gl);
road = ObjResourceReader.CreateRoad(Gl);
arrangementModel = new();
for (int i = 0; i < fighterJets.Length; i++)
{
fighterJets[i] = ObjResourceReader.CreateFighterJet(Gl);
}
}
private static void Window_Closing()
{
airbus.ReleaseGlObject();
skyBox.ReleaseGlObject();
road.ReleaseGlObject();
for (int i = 0; i < fighterJets.Length; i++)
{
fighterJets[i].ReleaseGlObject();
}
}
private static unsafe void SetProjectionMatrix()
{
var projectionMatrix = Matrix4X4.CreatePerspectiveFieldOfView<float>((float)Math.PI / 4f, 1024f / 768f, 0.1f, 100000);
int location = Gl.GetUniformLocation(program, ProjectionMatrixVariableName);
if (location == -1)
{
throw new Exception($"{ViewMatrixVariableName} uniform not found on shader.");
}
Gl.UniformMatrix4(location, 1, false, (float*)&projectionMatrix);
CheckError();
}
private static unsafe void SetViewMatrix()
{
var viewMatrix = Matrix4X4.CreateLookAt(cameraDescriptor.Position, cameraDescriptor.Target, cameraDescriptor.UpVector);
int location = Gl.GetUniformLocation(program, ViewMatrixVariableName);
if (location == -1)
{
throw new Exception($"{ViewMatrixVariableName} uniform not found on shader.");
}
Gl.UniformMatrix4(location, 1, false, (float*)&viewMatrix);
CheckError();
}
public static void CheckError()
{
var error = (ErrorCode)Gl.GetError();
if (error != ErrorCode.NoError)
throw new Exception("GL.GetError() returned " + error.ToString());
}
private static void PilotControl()
{
if (keyStates[Key.Left])
{
cameraDescriptor.RotateLeft();
}
if (keyStates[Key.Right])
{
cameraDescriptor.RotateRight();
}
if (keyStates[Key.Down])
{
cameraDescriptor.RotateDown();
}
if (keyStates[Key.Up])
{
cameraDescriptor.RotateUp();
}
if (keyStates[Key.A])
{
arrangementModel.TurnLeft();
cameraDescriptor.MoveLeft();
}
if (keyStates[Key.D])
{
arrangementModel.TurnRight();
cameraDescriptor.MoveRight();
}
if (keyStates[Key.Space])
{
cameraDescriptor.SetLanding();
arrangementModel.setLand();
}
}
}
}