/
LevelDesignerState.cs
1324 lines (1181 loc) · 56 KB
/
LevelDesignerState.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
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
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Windows.Forms;
using System.Diagnostics;
using OpenTK;
using OpenTK.Graphics;
using OpenTK.Graphics.OpenGL;
using OpenTK.Audio;
using OpenTK.Audio.OpenAL;
using Engine;
using OpenTK.Input;
using LevelDesignerTool;
// XML parser
using System.Xml;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Drawing;
using System.Threading;
using System.Windows.Markup;
using System.IO;
using QuickFont;
using KeyboardState = OpenTK.Input.KeyboardState;
using Keyboard = OpenTK.Input.Keyboard;
using System.Text;
namespace U5Designs
{
/** Main State of the game that will be active while the player is Playing **/
public class LevelDesignerState : PlayState
{
// Our current selected object for movement
internal GameObject SelectedObject = null;
QFont currentObj, controls, ahSnap, whichList;
bool showUI = true;
double timer = 0;
StringBuilder controlsText;
System.Windows.Application app;
MainWindow window;
bool windowInit;
// Changes ortho projection
double orthoWidth = 192;
double orthoHeight = 108;
List<string> ObstaclesList;
List<string> EnemiesList;
// Number of items and current item in the Obstacles List
int objectIter;
// Number of items and current item in the Enemies List
Dictionary<int, List<string>> ObjectList = new Dictionary<int, List<string>>();
int listKey = 0;
// Switches to control keyboard presses
bool AllowSnapping = false;
KeyboardState Old_Key_State;
float UnitsToMove = 1.0f;
/** These Dictionarys will map Vector3's to different game objects that will then be written out to a level file. When the user adds
* a given object type into the level editor that object will be added to the appropriate Dictionary. When the user deletes an object
* it will be removed from the appropriate list.**/
public struct BackGroundData
{
public Vector3 _scale;
public String _sprite_file;
public float _speed;
public Vector3 _location;
};
Dictionary<int, List<Vector3>> _xml_obstacle_list;
Dictionary<int, List<Vector3>> _xml_enemy_list;
Dictionary<Vector3, int> _xml_dec_list;
Dictionary<String, int> _xml_sound_list;
Dictionary<BackGroundData, int> _xml_bg_list;
Dictionary<Vector3, int> _xml_boss_area_list;
Dictionary<Vector3, int> _xml_boss_bounds_list;
Dictionary<Vector3, int> _xml_boss_center_list;
List<Vector3> _xml_end_region;
#region Constructor
/// <summary>
/// PlayState is the state in which the game is actually playing, this should only be called once when a new game is made.
/// </summary>
/// <param name="engine">Pointer to the game engine</param>
/// <param name="lvl">the level ID</param>
public LevelDesignerState(GameEngine engine, MainMenuState menustate, int lvl)
: base(engine, menustate, lvl)
{
//eng.WindowState = WindowState.Normal;
//eng.WindowBorder = WindowBorder.Fixed;
current_level = lvl;
LoadLevel.Load(lvl, this);
Old_Key_State = Keyboard.GetState();
//Have to load the next few things here for now because they require the GraphicsContext
foreach (RenderObject ro in renderList)
{
if (ro.is3dGeo)
{
ro.texture.init();
}
}
//HUD Health Bar
Assembly assembly = Assembly.GetExecutingAssembly();
eng.StateTextureManager.LoadTexture("Healthbar", assembly.GetManifestResourceStream("U5Designs.Resources.Textures.healthbar_top.png"));
Healthbar = eng.StateTextureManager.GetTexture("Healthbar");
eng.StateTextureManager.LoadTexture("bHealth", assembly.GetManifestResourceStream("U5Designs.Resources.Textures.healthbar_bottom.png"));
bHealth = eng.StateTextureManager.GetTexture("bHealth");
//initialize camera
camera = new Camera(eng.ClientRectangle.Width, eng.ClientRectangle.Height, player, this);
player.cam = camera;
// undo this when done testing ObjList = LoadLevel.Load(current_level);
player.inLevelDesignMode = true;
levelMusic.Stop();
//Thread t = new Thread(new ThreadStart(CreateLevelDesignForm));
//t.ApartmentState = ApartmentState.STA;
//t.Start();
ObstaclesList = GetItemsFromDir("Obstacles.obstacles.txt");
EnemiesList = GetItemsFromDir("Enemies.enemies.txt");
ObjectList.Add(0, ObstaclesList);
ObjectList.Add(1, EnemiesList);
_xml_obstacle_list = new Dictionary<int, List<Vector3>>();
// Add everything from previous list into this list. Problem is we have no idea what the object is.
//foreach (GameObject obj in objList)
//{
// if (obj is Obstacle)
// {
// }
//}
_xml_dec_list = new Dictionary<Vector3, int>();
_xml_enemy_list = new Dictionary<int, List<Vector3>>();
_xml_sound_list = new Dictionary<string, int>();
_xml_bg_list = new Dictionary<BackGroundData, int>();
_xml_boss_area_list = new Dictionary<Vector3, int>();
_xml_boss_bounds_list = new Dictionary<Vector3, int>();
_xml_boss_center_list = new Dictionary<Vector3, int>();
_xml_end_region = new List<Vector3>();
//StartDesignerThread();
currentObj = QFont.FromQFontFile("Fonts/myHappySans.qfont", new QFontLoaderConfiguration(true));
currentObj.Options.DropShadowActive = false;
controls = QFont.FromQFontFile("Fonts/myHappySans.qfont", new QFontLoaderConfiguration(true));
controls.Options.DropShadowActive = false;
ahSnap = QFont.FromQFontFile("Fonts/myHappySans.qfont", new QFontLoaderConfiguration(true));
ahSnap.Options.DropShadowActive = false;
whichList = QFont.FromQFontFile("Fonts/myHappySans.qfont", new QFontLoaderConfiguration(true));
whichList.Options.DropShadowActive = false;
controlsText = new StringBuilder();
controlsText.AppendLine("WASD - Camera/Character Movement");
controlsText.AppendLine("Up,Down,Left,Right - Movement selected object");
controlsText.AppendLine("Mouse Click Left/Right - Select/Add/Remove Objects");
controlsText.AppendLine("[ ] - Switch Objects");
controlsText.AppendLine("; - Switch between different objects");
controlsText.AppendLine("\\ - Switch number of units to move");
}
#endregion
#region WPF Stuff
/// <summary>
/// Opens the secondary tool menu which will be useful for user to choose items
/// </summary>
//private void OpenWindow()
//{
// if (System.Windows.Application.Current == null)
// {
// app = new System.Windows.Application();
// window = new LevelDesignerTool.MainWindow();
// app.Run(window);
// }
//}
///// <summary>
///// Thread for secondary window
///// </summary>
//private void StartDesignerThread()
//{
// var thread = new Thread(() =>
// {
// OpenWindow();
// });
// thread.SetApartmentState(ApartmentState.STA);
// thread.IsBackground = false;
// thread.Start();
//}
// IF WE DECIDE TO GO THE WINDOWS FORM ROUTE
//[STAThread]
//private void CreateLevelDesignForm()
//{
// Application.EnableVisualStyles();
// Application.SetCompatibleTextRenderingDefault(false);
// LevelDesignerForm LDForm = new LevelDesignerForm();
// Application.Run(LDForm);
//}
#endregion
/// <summary>
/// Refreshes graphics when this state becomes active again after being frozen.
/// </summary>
public override void MakeActive()
{
GL.Material(MaterialFace.FrontAndBack, MaterialParameter.Emission, new Vector4(0.0f, 0.0f, 0.0f, 1.0f));
GL.Enable(EnableCap.Blend);
GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha);
GL.ShadeModel(ShadingModel.Smooth);
GL.ClearColor(0.26667f, 0.86667f, 1.0f, 1.0f);
// TO DO: MAKE ORTHOGRAPHIC VIEW FURTHER BACK
if (enable3d)
{
camera.Set3DCamera();
}
else
{
camera.Set2DCamera();
}
if (player.curProjectile.gravity)
{
eng.CursorVisible = false;
}
else
{
eng.CursorVisible = true; //TODO: When we have a crosshair, we'll change this
}
}
/// <summary>
/// Update, this gets called once every update frame
/// </summary>
/// <param name="e">FrameEventArgs from OpenTK's update</param>
public override void Update(FrameEventArgs e)
{
player.cam.trackingPlayer = false;
//First deal with hardware input
DealWithInput();
HandleMouseInput();
//If the camera is transitioning, everything else is paused
if (!camera.isInTransition)
{
//Deal with everyone's acceleration, run AI on enemies
player.updateState(enable3d, eng.Keyboard, e.Time, true);
//Now that everyone's had a chance to accelerate, actually
//translate that into velocity and position
if (enable3d)
{
player.physUpdate3d(e.Time, physList);
foreach (PhysicsObject po in collisionList)
{
po.physUpdate3d(e.Time, physList);
}
}
else
{
player.physUpdate2d(e.Time, physList);
foreach (PhysicsObject po in collisionList)
{
po.physUpdate2d(e.Time, physList);
}
}
//These updates must be last
foreach (Background b in backgroundList)
{
b.UpdatePositionX(player.deltax);
}
}
//Update the camera whether we're transitioning or not
camera.Update(e.Time);
}
//Called by camera for parallaxing
public void updateBackgroundsYPos(float deltay)
{
foreach (Background b in backgroundList)
{
b.UpdatePositionY(deltay);
}
}
public void enterBossMode()
{
bossMode = true;
camera.enterBossMode(bossAreaCenter, bossAreaBounds);
}
/// <summary>
/// The Draw update, happens every frame
/// </summary>
/// <param name="e">FrameEventArgs from OpenTK's update</param>
public override void Draw(FrameEventArgs e)
{
////e = new FrameEventArgs(e.Time * 0.1);
GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
camera.SetModelView();
for (int i = effectsList.Count - 1; i >= 0; i--)
{
effectsList[i].update(e.Time);
}
foreach (RenderObject obj in renderList)
{
if (obj.ScreenRegion == GameObject.ON_SCREEN || obj.drawWhenOffScreen)
{
if ((camera.isInTransition && ((!nowBillboarding && obj.existsIn2d) || (nowBillboarding && obj.existsIn3d))) ||
(!camera.isInTransition && ((enable3d && obj.existsIn3d) || (!enable3d && obj.existsIn2d))))
{
if (obj.is3dGeo)
{
obj.doScaleTranslateAndTexture();
obj.mesh.Render();
}
else
{
obj.doScaleTranslateAndTexture();
if (camera.isInTransition)
{ //Pause all animations in transition
obj.sprite.draw(nowBillboarding, obj.billboards, obj.cycleNumber, obj.frameNumber + obj.animDirection * e.Time);
}
else
{
obj.frameNumber = obj.sprite.draw(nowBillboarding, obj.billboards, obj.cycleNumber, obj.frameNumber + obj.animDirection * e.Time);
}
}
}
}
}
//Draw the parabola if grenade is active
foreach (Decoration m in player.markerList)
{
m.doScaleTranslateAndTexture();
m.frameNumber = m.sprite.draw(nowBillboarding, m.billboards, m.cycleNumber, m.frameNumber + m.animDirection * e.Time);
}
if (showUI)
{
DrawUI();
timer = timer + e.Time;
if (timer > 3.0)
{
showUI = false;
timer = 0;
}
}
}
/// <summary>
/// Switches the sprites and bounding boxes of anything that billboards
/// Called by camera at appropriate time
/// </summary>
new public void doBillboards()
{
if (enable3d)
{
nowBillboarding = true;
}
else
{
nowBillboarding = false;
}
//Temporary hack until we get a setting added to everything that does this
player.cycleNumber += (enable3d ? +1 : -1);
//Switch pboxes and cboxes for things that billboard
foreach (PhysicsObject p in physList)
{
if (p.billboards == Billboarding.Yes)
{
p.swapPBox();
}
}
foreach (CombatObject c in combatList)
{
if (c.billboards == Billboarding.Yes)
{
c.swapCBox();
}
}
//TODO: This if/else block is a hack!
// Implement a flag that controls whether to switch these or not
if (enable3d)
{
foreach (AIObject o in aiList)
{
((RenderObject)o).cycleNumber = 1;
}
}
else
{ //2d
foreach (AIObject o in aiList)
{
((RenderObject)o).cycleNumber = 0;
}
}
}
/// <summary>
/// Deals with Hardware input relivant to the playstate
/// </summary>
private void DealWithInput()
{
KeyboardState New_Key_State = Keyboard.GetState();
// SAVE THE CURRENT LEVEL TO A NEW LEVEL
if (New_Key_State.IsKeyDown(Key.Period) && !Old_Key_State.IsKeyDown(Key.Period) ||
New_Key_State.IsKeyDown(Key.BracketLeft) && !Old_Key_State.IsKeyDown(Key.BracketLeft) ||
New_Key_State.IsKeyDown(Key.BracketRight) && !Old_Key_State.IsKeyDown(Key.BracketRight) ||
New_Key_State.IsKeyDown(Key.Slash) && !Old_Key_State.IsKeyDown(Key.Slash) ||
New_Key_State.IsKeyDown(Key.Semicolon) && !Old_Key_State.IsKeyDown(Key.Semicolon))
showUI = true;
if (New_Key_State.IsKeyDown(Key.Period) && !Old_Key_State.IsKeyDown(Key.Period))
{
_write_level_file("TestLevelWrite", 99);
Console.WriteLine("Level Written");
}
// Allow snapping for movement
if (New_Key_State.IsKeyDown(Key.Slash) && !Old_Key_State.IsKeyDown(Key.Slash))
{
AllowSnapping = !AllowSnapping;
if (AllowSnapping)
{
UnitsToMove = 10.0f;
}
else
{
UnitsToMove = 1.0f;
}
Console.WriteLine("Snapping is: {0}", AllowSnapping.ToString());
}
if (New_Key_State.IsKeyDown(Key.Semicolon) && !Old_Key_State.IsKeyDown(Key.Semicolon))
{
int totalKeys = ObjectList.Keys.Count;
listKey += 1;
objectIter = 0;
if (listKey > totalKeys - 1)
{
listKey = 0;
}
Console.WriteLine(" You are in {0}", listKey);
}
// If we are in 2D View, Allow user to zoom out and in with W and S
if (!enable3d)
{
if (New_Key_State.IsKeyDown(Key.W))
{
orthoWidth = Math.Max(192, orthoWidth - orthoWidth * 0.01);
orthoHeight = Math.Max(108, orthoHeight - orthoHeight * 0.01);
camera.Set2DCamera(orthoWidth, orthoHeight);
}
if (New_Key_State.IsKeyDown(Key.S))
{
orthoWidth = Math.Min(1920, orthoWidth + orthoWidth * 0.01);
orthoHeight = Math.Min(1080, orthoHeight + orthoHeight * 0.01);
camera.Set2DCamera(orthoWidth, orthoHeight);
}
}
// Testing the Level Design feature of re-loading LoadLevel after changing coords for a given game object
if (eng.Keyboard[Key.F5])
{
LevelDesignerState lds = new LevelDesignerState(eng, menustate, current_level);
if (!window.IsActive)
{
window.Show();
}
eng.ChangeState(lds);
//LoadLevel.Load(0, pst);
}
if (eng.Keyboard[Key.Escape] || eng.Keyboard[Key.Tilde])
{
//eng.PushState(menustate);
eng.PushState(pms);
}
//********************** tab
if (!camera.isInTransition && player.onGround)
{
if (eng.Keyboard[Key.Tab] && !tabDown)
{
enable3d = !enable3d;
tabDown = true;
player.velocity.Z = 0;
camera.startTransition(enable3d);
//figure out if the player gets a grace jump
if (enable3d && player.onGround && !VectorUtil.overGround3dLoose(player, physList))
{
player.viewSwitchJumpTimer = 1.0;
}
}
else if (!eng.Keyboard[Key.Tab])
{
tabDown = false;
}
}
// Allow movement of the selected objects
if (!enable3d)
{
if (New_Key_State.IsKeyDown(Key.Up) && !Old_Key_State.IsKeyDown(Key.Up))
{
MoveObjects(SelectedObject, new Vector3(0.0f, UnitsToMove, 0.0f));
}
if (New_Key_State.IsKeyDown(Key.Down) && !Old_Key_State.IsKeyDown(Key.Down))
{
MoveObjects(SelectedObject, new Vector3(0.0f, -UnitsToMove, 0.0f));
}
if (New_Key_State.IsKeyDown(Key.Left) && !Old_Key_State.IsKeyDown(Key.Left))
{
MoveObjects(SelectedObject, new Vector3(-UnitsToMove, 0.0f, 0.0f));
}
if (New_Key_State.IsKeyDown(Key.Right) && !Old_Key_State.IsKeyDown(Key.Right))
{
MoveObjects(SelectedObject, new Vector3(UnitsToMove, 0.0f, 0.0f));
}
// Moving between obstacles
if (New_Key_State.IsKeyDown(Key.BracketLeft) && !Old_Key_State.IsKeyDown(Key.BracketLeft))
{
if (objectIter - 1 < 0)
objectIter = ObjectList[listKey].Count - 1;
else objectIter--;
Console.WriteLine("Using {0}", ObjectList[listKey][objectIter]);
}
if (New_Key_State.IsKeyDown(Key.BracketRight) && !Old_Key_State.IsKeyDown(Key.BracketRight))
{
if (objectIter + 1 > ObjectList[listKey].Count - 1)
objectIter = 0;
else objectIter++;
Console.WriteLine("Using {0}", ObjectList[listKey][objectIter]);
}
}
#region 3D Move Controls
else
{
if (New_Key_State.IsKeyDown(Key.Up) && !Old_Key_State.IsKeyDown(Key.Up) && !eng.Keyboard[Key.ControlLeft])
{
MoveObjects(SelectedObject, new Vector3(UnitsToMove, 0.0f, 0.0f));
}
if (New_Key_State.IsKeyDown(Key.Down) && !Old_Key_State.IsKeyDown(Key.Down) && !eng.Keyboard[Key.ControlLeft])
{
MoveObjects(SelectedObject, new Vector3(-UnitsToMove, 0.0f, 0.0f));
}
if (New_Key_State.IsKeyDown(Key.Left) && !Old_Key_State.IsKeyDown(Key.Left))
{
MoveObjects(SelectedObject, new Vector3(0.0f, 0.0f, -UnitsToMove));
}
if (New_Key_State.IsKeyDown(Key.Right) && !Old_Key_State.IsKeyDown(Key.Right))
{
MoveObjects(SelectedObject, new Vector3(0.0f, 0.0f, UnitsToMove));
}
if (New_Key_State.IsKeyDown(Key.Up) && !Old_Key_State.IsKeyDown(Key.Up) && eng.Keyboard[Key.ControlLeft])
{
MoveObjects(SelectedObject, new Vector3(0.0f, UnitsToMove, 0.0f));
}
if (New_Key_State.IsKeyDown(Key.Down) && !Old_Key_State.IsKeyDown(Key.Down) && eng.Keyboard[Key.ControlLeft])
{
MoveObjects(SelectedObject, new Vector3(0.0f, -UnitsToMove, 0.0f));
}
}
#endregion
Old_Key_State = New_Key_State;
}
private void MoveObjects(GameObject gameObj, Vector3 newLoc)
{
if (gameObj == null) return;
if (gameObj is Obstacle)
{
foreach (var key in _xml_obstacle_list.Keys)
{
int xmlIndex;
if ((xmlIndex = _xml_obstacle_list[key].FindIndex(q => q == gameObj.location)) != -1)
{
_xml_obstacle_list[key][xmlIndex] += newLoc;
}
}
int index = objList.FindIndex(p => p.location == gameObj.location);
if (index == -1) return;
objList[index].location += newLoc;
// Alter the dictionary location when we move objects
}
if (gameObj is Enemy)
{
foreach (var key in _xml_enemy_list.Keys)
{
int xmlIndex;
if ((xmlIndex = _xml_enemy_list[key].FindIndex(q => q == gameObj.location)) != -1)
{
_xml_enemy_list[key][xmlIndex] += newLoc;
}
}
int index = objList.FindIndex(p => p.location == gameObj.location);
if (index == -1) return;
objList[index].location += newLoc;
// Alter the dictionary location when we move objects
}
}
private void HandleMouseInput()
{
if (!eng.ThisMouse.LeftPressed())
{
clickdown = false;
}
// ADDING OBJECTS TO THE LIST
if (eng.ThisMouse.LeftPressed() && !clickdown && !enable3d)
{
clickdown = true;
// Pull the projection and model view matrix from the camera.
Matrix4d project = this.camera.GetProjectionMatrix();
Matrix4d model = this.camera.GetModelViewMatrix();
Vector3d mousecoord = new Vector3d((double)this.eng.Mouse.X, (double)(this.eng.Height - this.eng.Mouse.Y), 1.0);
// Unproject the coordinates to convert from mouse to world coordinates
Vector3d mouseWorld = GameMouse.UnProject(mousecoord, model, project, this.camera.getViewport());
foreach (GameObject obj in objList)
{
if (obj is Obstacle || obj is Enemy)
{
if (eng.ThisMouse.inObjectRegion(obj, mouseWorld, enable3d))
{
SelectedObject = obj;
Console.WriteLine("Selected Object");
return;
}
}
}
Vector3 loc = new Vector3((float)mouseWorld.X, (float)mouseWorld.Y, 50.0f);
// Handle adding enemies
if (listKey == 1)
{
Enemy e = parseEnemy(ObjectList[listKey][objectIter], loc, player);
objList.Add(e);
physList.Add(e);
renderList.Add(e);
clickdown = false;
// Add to obstacle list
if (_xml_enemy_list.ContainsKey(objectIter))
{
_xml_enemy_list[objectIter].Add(e.location);
}
else
{
List<Vector3> locList = new List<Vector3>();
locList.Add(e.location);
_xml_enemy_list.Add(objectIter, locList);
}
}
else
{
Obstacle o = ParseObstacle(ObjectList[listKey][objectIter], loc);
if (o == null)
{
Decoration dec = ParseDecoration(ObjectList[listKey][objectIter], loc);
objList.Add(dec);
renderList.Add(dec);
// Add decoration to decoration list
_xml_dec_list.Add(dec.location, objectIter);
/** TODO !!!! ***/
// Need to parse Enemies, Sound files, boss regions, backgrounds
/// PSEUDO-CODE
// if ( boss region )
// _xml_boss_region.Add(Vector3, index)
// if ( boss bounds )
// _xml_boss_bounds.Add(Vector3, index)
// if ( boss center )
// _xml_boss_center.Add(Vector3, index)
// if ( sound file )
// _xml_sound.Add(object, index)
// if ( end region )
// _xml_end_region.Add(Vector3)
// if ( enemy )
// _xml_enemy.Add(object, index)
// if ( background )
// _xml_bg.Add(BackGroundData, index) /// BackGroundData is a struct to hold the multiple data items needed to create a BG
}
else
{
objList.Add(o);
physList.Add(o);
renderList.Add(o);
clickdown = false;
// Add to obstacle list
if (_xml_obstacle_list.ContainsKey(objectIter))
{
_xml_obstacle_list[objectIter].Add(o.location);
}
else
{
List<Vector3> locList = new List<Vector3>();
locList.Add(o.location);
_xml_obstacle_list.Add(objectIter, locList);
}
}
}
}
else if (eng.ThisMouse.LeftPressed() && !clickdown && enable3d)
{
// TO DO: ALLOW SELECTION AND OF OBJECTS IN 3D
clickdown = true;
// Pull the projection and model view matrix from the camera.
Matrix4d project = this.camera.GetProjectionMatrix();
Matrix4d model = this.camera.GetModelViewMatrix();
float[] t = new float[1];
GL.ReadPixels(this.eng.Mouse.X, this.eng.Height - this.eng.Mouse.Y, 1, 1, PixelFormat.DepthComponent, PixelType.Float, t);
Vector3d mousecoord = new Vector3d((double)this.eng.Mouse.X, (double)(this.eng.Height - this.eng.Mouse.Y), 1.0);
// Unproject the coordinates to convert from mouse to world coordinates
mousecoord.Z = 0.0;
Vector3d near = GameMouse.UnProject(mousecoord, model, project, this.camera.getViewport());
mousecoord.Z = 1.0;
Vector3d far = GameMouse.UnProject(mousecoord, model, project, this.camera.getViewport());
//Interpolate to find coordinates just in front of player
double tA = (player.location.X + (100.0f * t[0]) - near.X) / (far.X - near.X);
Vector3d mouseWorld = new Vector3d(player.location.X + (100.0 * (1 - t[0])), near.Y + (far.Y - near.Y) * tA, near.Z + (far.Z - near.Z) * tA);
Console.WriteLine("{0} \t {1} \t {2}", mouseWorld.X, mouseWorld.Y, mouseWorld.Z);
// Console.WriteLine(t[0]);
clickdown = false;
}
else if (eng.ThisMouse.RightPressed())
{
// Pull the projection and model view matrix from the camera.
Matrix4d project = this.camera.GetProjectionMatrix();
Matrix4d model = this.camera.GetModelViewMatrix();
Vector3d mousecoord = new Vector3d((double)this.eng.Mouse.X, (double)(this.eng.Height - this.eng.Mouse.Y), 1.0);
// Unproject the coordinates to convert from mouse to world coordinates
Vector3d mouseWorld = GameMouse.UnProject(mousecoord, model, project, this.camera.getViewport());
GameObject objToRemove = null;
foreach (GameObject obj in objList)
{
if (obj is Obstacle)
{
if (eng.ThisMouse.inObjectRegion(obj, mouseWorld, enable3d))
{
objToRemove = (Obstacle)obj;
foreach (int key in _xml_obstacle_list.Keys)
{
if (_xml_obstacle_list[key].Contains(objToRemove.location))
{
_xml_obstacle_list[key].Remove(objToRemove.location);
}
}
}
}
// Remove object if it is an enemy
if (obj is Enemy)
{
if (eng.ThisMouse.inObjectRegion(obj, mouseWorld, enable3d))
{
objToRemove = obj;
foreach (int key in _xml_enemy_list.Keys)
{
if (_xml_enemy_list[key].Contains(objToRemove.location))
{
_xml_enemy_list[key].Remove(objToRemove.location);
}
}
}
}
//else if (obj is Enemy)
//{
// _xml_enemy_list.Remove(obj.location);
// break;
//}
//else if (obj is Background)
//{
// // Set temp BGD properties to the currently selected Background object and then search for a match in the Dictionary
// Background b = (Background)obj;
// BackGroundData bgd;
// bgd._location = obj.location;
// bgd._scale = b.scale;
// bgd._speed = b.Speed;
// bgd._sprite_file = b.Path;
// // ?? Not sure this works, hard to test at the moment so be aware this may be a broken hack...sorry coding blind on this one ...
// foreach (KeyValuePair<BackGroundData, int> pair in _xml_bg_list)
// {
// BackGroundData _b = pair.Key;
// if (_b._location == bgd._location && _b._scale == bgd._scale && _b._speed == bgd._speed && _b._sprite_file.CompareTo(bgd._sprite_file) == 0)
// {
// _xml_bg_list.Remove(_b);
// break;
// }
// }
// break;
//}
}
if (objToRemove != null)
{
objList.Remove(objToRemove);
physList.Remove((PhysicsObject)objToRemove);
renderList.Remove((RenderObject)objToRemove);
}
}
}
#region Remove/Add Items to List
private void RemoveItemFromAllLists(Obstacle objToRemove)
{
if (objToRemove != null)
{
objList.Remove(objToRemove);
physList.Remove(objToRemove);
renderList.Remove(objToRemove);
}
}
private void AddItemsToAllLists(Obstacle objToAdd)
{
if (objToAdd != null)
{
objList.Add(objToAdd);
physList.Add(objToAdd);
renderList.Add(objToAdd);
}
}
#endregion
public void DrawUI()
{
float startY = eng.Height * 0.1f;
float startX = eng.Width * 0.3f;
float contrStartX = eng.Width * 0.7f;
string list = "Obstacles";
if (listKey == 1)
{
list = "Enemies";
}
GL.Disable(EnableCap.DepthTest);
GL.MatrixMode(MatrixMode.Projection);
GL.PushMatrix();
GL.LoadIdentity();
GL.Ortho(0, 1280, 0, 720, 0, 1);
GL.MatrixMode(MatrixMode.Modelview);
GL.PushMatrix();
GL.LoadIdentity();
GL.PushMatrix();
QFont.Begin();
currentObj.Print(ObjectList[listKey][objectIter], new Vector2(startX - (currentObj.Measure(ObjectList[listKey][objectIter]).Width / 2), startY - (currentObj.Measure("A").Height + 10)));
ahSnap.Print("Units to Move: " + UnitsToMove.ToString(), new Vector2(eng.Width * 0.1f, eng.Height - (currentObj.Measure("A").Height + 10)));
whichList.Print(list, new Vector2(eng.Width * 0.8f, eng.Height - (currentObj.Measure("A").Height + 10)));
GL.Scale(0.4, 0.4, 0.4);
GL.Translate((double)contrStartX, 0, 0);
controls.Print(controlsText.ToString(), new Vector2(contrStartX, startY - (currentObj.Measure("A").Height + 10)));
QFont.End();
GL.PopMatrix();
GL.PopMatrix();
GL.MatrixMode(MatrixMode.Projection);
GL.PopMatrix();
GL.MatrixMode(MatrixMode.Modelview);
GL.Enable(EnableCap.DepthTest);
}
/*--------------------------------------------------------------------------------------------------------------
*
* LEVEL DESIGNER FILE METHODS
*
* -------------------------------------------------------------------------------------------------------------
* */
#region Parse Level Files
public List<string> GetItemsFromDir(string filename)
{
Assembly assembly = Assembly.GetExecutingAssembly();
string _o_path = "U5Designs.Resources.Data." + filename;
Stream fstream = assembly.GetManifestResourceStream(_o_path);
StreamReader r = new StreamReader(fstream);
List<string> obstacleList = new List<string>();
string obs = r.ReadLine();
while (obs != null)
{
obstacleList.Add(obs);
obs = r.ReadLine();
}
return obstacleList;
}
private Decoration ParseDecoration(string path, Vector3 loc)
{
Decoration dec = null;
// Instantiate the list
Assembly assembly = Assembly.GetExecutingAssembly();
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreComments = true;
string _d_path = "U5Designs.Resources.Data.Decorations." + path;
Stream fstream = assembly.GetManifestResourceStream(_d_path);
XmlDocument doc = new XmlDocument();
XmlReader reader = XmlReader.Create(fstream, settings);
doc.Load(reader);
Vector3 scale = LoadLevel.parseVector3(doc.GetElementsByTagName("scale")[0]);
bool _draw2 = Convert.ToBoolean(doc.GetElementsByTagName("draw2")[0].InnerText);
bool _draw3 = Convert.ToBoolean(doc.GetElementsByTagName("draw3")[0].InnerText);
// Check to see if the current Obstacle is 2D or 3D and handle accordingly
if (Convert.ToBoolean(doc.GetElementsByTagName("is2d")[0].InnerText))
{
// Create the SpriteSheet
SpriteSheet ss = LoadLevel.parseSpriteFile(doc.GetElementsByTagName("sprite")[0].InnerText);
Billboarding bb = Billboarding.Yes; //Have to put something here for it to compile
switch (doc.GetElementsByTagName("billboards")[0].InnerText)
{
case "yes":
case "Yes":
bb = Billboarding.Yes;
break;
case "lock2d":
case "Lock2d":
bb = Billboarding.Lock2d;
break;
case "lock3d":
case "Lock3d":
bb = Billboarding.Lock3d;
break;
default:
Console.WriteLine("Bad obstacle file: " + path);
Environment.Exit(1);
break;
}
dec = new Decoration(loc, scale, _draw2, _draw3, bb, ss);
}
else
{
XmlNodeList _m = doc.GetElementsByTagName("mesh");
ObjMesh _mesh = new ObjMesh(assembly.GetManifestResourceStream("U5Designs.Resources.Geometry." + _m.Item(0).InnerText));
XmlNodeList _b = doc.GetElementsByTagName("bmp");
List<Bitmap> texFrames = new List<Bitmap>();
foreach (XmlNode n in _b)
{
texFrames.Add(new Bitmap(assembly.GetManifestResourceStream("U5Designs.Resources.Textures." + n.InnerText)));
}
MeshTexture _bmp = new MeshTexture(texFrames);
_bmp.init();
dec = new Decoration(loc, scale, _draw2, _draw3, _mesh, _bmp);
}
fstream.Close();
return dec;
}