Don't like ads? PRO users don't see any ads ;-)
Guest

My great coding standards

By: a guest on May 23rd, 2012  |  syntax: C#  |  size: 16.27 KB  |  hits: 26  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.IO;
  5. using Microsoft.Xna.Framework;
  6. using Microsoft.Xna.Framework.Audio;
  7. using Microsoft.Xna.Framework.Content;
  8. using Microsoft.Xna.Framework.GamerServices;
  9. using Microsoft.Xna.Framework.Graphics;
  10. using Microsoft.Xna.Framework.Input;
  11. using Microsoft.Xna.Framework.Media;
  12. using Newtonsoft.Json;
  13.  
  14. namespace Serious
  15. {
  16.     public class Game1 : Game
  17.     {
  18.         string game_data_dname = "Serious";
  19.         string persistent_fname = "persistent.json";
  20.  
  21.         string game_data_directory;
  22.         string persistent_fpath
  23.         {
  24.             get
  25.             {
  26.                 return Path.Combine(game_data_directory, persistent_fname);
  27.             }
  28.         }
  29.  
  30.         GraphicsDeviceManager graphics;
  31.         SpriteBatch spriteBatch;
  32.         Effect effect;
  33.         CullMode cull_mode = CullMode.CullCounterClockwiseFace;
  34.         FillMode fill_mode = FillMode.Solid;
  35.         FillMode other_fill_mode = FillMode.WireFrame;
  36.  
  37.         KeyboardState prevKs;
  38.  
  39.         Terrain earth;
  40.         Cylinder player;
  41.  
  42.         IEnumerable<Cylinder> all_game_cylinders
  43.         {
  44.             get
  45.             {
  46.                 return new Cylinder[] { player };
  47.             }
  48.         }
  49.  
  50.         Camera3D player_camera;
  51.  
  52.         public Game1 ()
  53.         {
  54.             graphics = new GraphicsDeviceManager(this);
  55.             Content.RootDirectory = "Content";
  56.         }
  57.  
  58.         protected override void Initialize ()
  59.         {
  60.             Console.SetOut(new StreamWriter("console.log"));
  61.             string app_data_dir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
  62.             try
  63.             {
  64.                 game_data_directory = Path.Combine(app_data_dir, game_data_dname);
  65.                 Directory.CreateDirectory(game_data_directory);
  66.             }
  67.             catch (IOException ex)
  68.             {
  69.                 Logger.Log(ex.ToString());
  70.             }
  71.  
  72.  
  73.  
  74.             int w = 2;
  75.             if (w == 0)
  76.             {
  77.                 graphics.PreferredBackBufferWidth = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width;
  78.                 graphics.PreferredBackBufferHeight = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height;
  79.                 graphics.IsFullScreen = true;
  80.             }
  81.             else if (w == 1)
  82.             {
  83.                 graphics.PreferredBackBufferWidth = 1024;
  84.                 graphics.PreferredBackBufferHeight = 768;
  85.                 graphics.IsFullScreen = false;
  86.             }
  87.             else if (w == 2)
  88.             {
  89.                 graphics.PreferredBackBufferWidth = 1600;
  90.                 graphics.PreferredBackBufferHeight = 900;
  91.                 graphics.IsFullScreen = false;
  92.             }
  93.  
  94.             IsMouseVisible = false;
  95.             graphics.ApplyChanges();
  96.  
  97.             Window.Title = "3D Terrain or whatever";
  98.  
  99.             prevKs = new KeyboardState();
  100.  
  101.             base.Initialize();
  102.         }
  103.        
  104.         protected override void LoadContent()
  105.         {
  106.             spriteBatch = new SpriteBatch(GraphicsDevice);
  107.  
  108.             effect = Content.Load<Effect>("effects");
  109.  
  110.             startup persistent;
  111.             try
  112.             {
  113.                 string json = File.ReadAllText(persistent_fpath);
  114.                 persistent = JsonConvert.DeserializeObject<startup>(json);
  115.             }
  116.             catch (FileNotFoundException)
  117.             {
  118.                 persistent = default_persistent;
  119.             }
  120.  
  121.             SetUpTerrain();
  122.             SetUpCylinders(persistent);
  123.             SetUpCamera(persistent);
  124.         }
  125.  
  126.         protected override void UnloadContent ()
  127.         {
  128.             startup persistent;
  129.             persistent.player.location.x = player.position.X;
  130.             persistent.player.location.y = player.position.Y;
  131.             persistent.player.angle = player.angle;
  132.             persistent.player.go_fast = player.go_fast;
  133.  
  134.             persistent.camera.vertical_delta.x = player_camera.vertical_delta.X;
  135.             persistent.camera.vertical_delta.y = player_camera.vertical_delta.Y;
  136.             persistent.camera.dist = player_camera.dist;
  137.             persistent.camera.z_offset = player_camera.z_offset;
  138.  
  139.             string json = JsonConvert.SerializeObject(persistent);
  140.             File.WriteAllText(persistent_fpath, json);
  141.         }
  142.  
  143.         private startup default_persistent
  144.         {
  145.             get
  146.             {
  147.                 startup persistent;
  148.  
  149.                 persistent.player.location.x = 16.0f;
  150.                 persistent.player.location.y = 16.0f;
  151.                 persistent.player.angle = 90.0f;
  152.                 persistent.player.go_fast = false;
  153.  
  154.                 Vector2 vdelta = Vector2.Normalize(new Vector2(1.0f, 0.25f));
  155.                 persistent.camera.vertical_delta.x = vdelta.X;
  156.                 persistent.camera.vertical_delta.y = vdelta.Y;
  157.                 persistent.camera.dist = 19.0f;
  158.                 persistent.camera.z_offset = 4.0f;
  159.  
  160.                 return persistent;
  161.             }
  162.         }
  163.  
  164.         private BasicModel player_normal_model { get { return BasicModel.Cylinder; } }
  165.         private BasicModel player_fast_model { get { return BasicModel.Sphere; } }
  166.         private Cylinder startup_2_cylinder(startup persistent)
  167.         {
  168.             startup.guy player = persistent.player;
  169.             return new Cylinder(new Vector3(player.location.as_vector2(), 0.0f), player.angle, player.go_fast, player_normal_model, player_fast_model);
  170.         }
  171.  
  172.         private Camera3D startup_2_camera(startup persistent)
  173.         {
  174.             startup.cam camera = persistent.camera;
  175.             return new Camera3D(player, camera.vertical_delta.as_vector2(), camera.dist, camera.z_offset);
  176.         }
  177.  
  178.         private void SetUpTerrain ()
  179.         {
  180.             using (Texture2D heightmap_bmp = Content.Load<Texture2D>("heightmap4"))
  181.             {
  182.                 earth = new Terrain(heightmap_bmp, Vector3.Zero, 2.0f);
  183.             }
  184.         }
  185.  
  186.         private void SetUpCylinders(startup persistent)
  187.         {
  188.             player = startup_2_cylinder(persistent);
  189.         }
  190.  
  191.         private void SetUpCamera(startup persistent)
  192.         {
  193.             player_camera = startup_2_camera(persistent);
  194.         }
  195.  
  196.         private Single get_floor_at(Vector2 v)
  197.         {
  198.             try
  199.             {
  200.                 return earth.z_at(v);
  201.             }
  202.             catch (ArgumentOutOfRangeException)
  203.             {
  204.                 return 0.0f;
  205.             }
  206.         }
  207.  
  208.         protected override void Update(GameTime gameTime)
  209.         {
  210.             KeyboardEvent kev = new KeyboardEvent(Keyboard.GetState(), prevKs);
  211.             prevKs = kev.Current;
  212.             // Allows the game to exit
  213.             if (kev.IsKeyDown(Keys.Escape))
  214.             {
  215.                 Exit();
  216.                 return;
  217.             }
  218.  
  219.  
  220.  
  221.             {
  222.                 if (kev.WasKeyPressed(Keys.Enter))
  223.                 {
  224.                     startup persistent = default_persistent;
  225.                     player = startup_2_cylinder(persistent);
  226.                     player_camera = startup_2_camera(persistent);
  227.                 }
  228.             }
  229.  
  230.             Index2 input_vecdir = Index2.Zero;
  231.             int input_deltang = 0;
  232.             if (kev.IsKeyDown(Keys.D)) input_vecdir.Y -= 1;
  233.             if (kev.IsKeyDown(Keys.A)) input_vecdir.Y += 1;
  234.             if (kev.IsKeyDown(Keys.W)) input_vecdir.X += 1;
  235.             if (kev.IsKeyDown(Keys.S)) input_vecdir.X -= 1;
  236.  
  237.             if (kev.IsKeyDown(Keys.Left)) input_deltang += 1;
  238.             if (kev.IsKeyDown(Keys.Right)) input_deltang -= 1;
  239.             bool player_is_do_jump = (/*player.on_floor && */(kev.WasKeyPressed(Keys.Up) || kev.WasKeyPressed(Keys.Space)));
  240.  
  241.             /*
  242.             if (kev.WasKeyPressed(Keys.Home))
  243.             {
  244.                 player.is_floating = !player.is_floating;
  245.             }
  246.             */
  247.  
  248.             Single s = Cylinder.move_spd;
  249.             Single a = Cylinder.turn_spd;
  250.             Single j = player_is_do_jump ? Cylinder.jump_mag : 0.0f;
  251.             if (kev.WasKeyPressed(Keys.Down))
  252.             {
  253.                 player.go_fast = !player.go_fast;
  254.             }
  255.             if (player.go_fast)
  256.             {
  257.                 s *= 5.0f;
  258.                 a *= 3.0f;
  259.                 j *= 2.0f;
  260.             }
  261.  
  262.             player.angle += input_deltang * a;
  263.             if (input_vecdir)
  264.             {
  265.                 Vector2 player_angdir = Vector2Ext.FromDirectionDeg(player.angle);
  266.                 Vector2 move_vec = Vector2.Normalize(input_vecdir).Rotated(player_angdir);
  267.  
  268.                 player.position += new Vector3(move_vec, 0.0f) * s;
  269.             }
  270.  
  271.             if (player_is_do_jump)
  272.             {
  273.                 player.velocity.Z = j;
  274.                 player.on_floor = false;
  275.             }
  276.             else
  277.             {
  278.                 player.velocity.Z -= Cylinder.gravity;
  279.             }
  280.  
  281.             player.position += player.velocity;
  282.  
  283.             Single floor = this.get_floor_at(new Vector2(player.position.X, player.position.Y));
  284.             if (player.position.Z <= floor || player.on_floor)
  285.             {
  286.                 if (player.velocity.Z < 0.0f)
  287.                 {
  288.                     Single minminmin = 1.5f;
  289.                     player.velocity.Z *= 0.86f;
  290.                     if (Math.Abs(player.velocity.Z) <= 0.125f)
  291.                     {
  292.                         player.velocity.Z = 0.0f;
  293.                     }
  294.                     if (player.position.Z <= floor && Math.Abs(player.velocity.Z) >= minminmin)
  295.                     {
  296.                         int n = (int)MathHelper.Lerp(5, 15, Math.Abs(player.velocity.Z) - minminmin);
  297.                         Func<Vector3, Single> modifier = delegate(Vector3 v)
  298.                         {
  299.                             Single dist = Vector2.Distance(v.AsXY(), player.position.AsXY());
  300.                             Single nn = (Single)n;
  301.                             if (dist > nn)
  302.                             {
  303.                                 return v.Z;
  304.                             }
  305.                             Single zoff = (MathExt.Cos(dist / nn * MathHelper.Pi) + 1.0f) / 2.0f;
  306.                             zoff *= (floor - player.position.Z);
  307.                             return v.Z - zoff;
  308.                         };
  309.                         Vector3 p = player.position;
  310.                         p -= earth.position;
  311.                         p /= earth.scale;
  312.                         Index2 ii = new Index2((int)Math.Floor(p.X), (int)Math.Floor(p.Y)) - Index2.One * ((n - 1) / 2);
  313.                         earth.set_model(ii, new Index2(n, n), modifier);
  314.                     }
  315.                     player.on_floor = true;
  316.                 }
  317.                 player.position.Z = floor;
  318.             }
  319.  
  320.             {
  321.                 if (kev.WasKeyPressed(Keys.NumPad5))
  322.                 {
  323.                     Common.Swap(ref fill_mode, ref other_fill_mode);
  324.                 }
  325.                 if (kev.WasKeyPressed(Keys.NumPad7))
  326.                 {
  327.                     cull_mode = CullMode.CullCounterClockwiseFace;
  328.                 }
  329.                 if (kev.WasKeyPressed(Keys.NumPad8))
  330.                 {
  331.                     cull_mode = CullMode.CullClockwiseFace;
  332.                 }
  333.                 if (kev.WasKeyPressed(Keys.NumPad9))
  334.                 {
  335.                     cull_mode = CullMode.None;
  336.                 }
  337.             }
  338.  
  339.             {
  340.                 if (kev.IsKeyDown(Keys.PageUp))
  341.                 {
  342.                     player_camera.vertical_delta = player_camera.vertical_delta.Rotated(Vector2Ext.FromDirectionDeg(1.0f));
  343.                 }
  344.                 if (kev.IsKeyDown(Keys.PageDown))
  345.                 {
  346.                     player_camera.vertical_delta = player_camera.vertical_delta.Rotated(Vector2Ext.FromDirectionDeg(-1.0f));
  347.                 }
  348.  
  349.                 if (kev.IsKeyDown(Keys.Home))
  350.                 {
  351.                     player_camera.dist -= 0.75f;
  352.                 }
  353.                 if (kev.IsKeyDown(Keys.End))
  354.                 {
  355.                     player_camera.dist += 0.75f;
  356.                 }
  357.  
  358.                 if (kev.IsKeyDown(Keys.Insert))
  359.                 {
  360.                     player_camera.z_offset += 0.25f;
  361.                 }
  362.                 if (kev.IsKeyDown(Keys.Delete))
  363.                 {
  364.                     player_camera.z_offset -= 0.25f;
  365.                 }
  366.             }
  367.  
  368.             base.Update(gameTime);
  369.         }
  370.  
  371.         protected override void Draw(GameTime gameTime)
  372.         {
  373.             GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.Black, 1.0f, 0);
  374.  
  375.             RasterizerState rs = new RasterizerState();
  376.             rs.CullMode = cull_mode;
  377.             rs.FillMode = fill_mode;
  378.             GraphicsDevice.RasterizerState = rs;
  379.             GraphicsDevice.BlendState = BlendState.AlphaBlend;
  380.             GraphicsDevice.BlendFactor = Color.Red;
  381.  
  382.             effect.CurrentTechnique = effect.Techniques["Colored"];
  383.  
  384.             Matrix proj_matrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, GraphicsDevice.Viewport.AspectRatio, 0.0625f, 10000.0f);
  385.             effect.Parameters["xView"].SetValue(player_camera.ViewMatrix);
  386.             effect.Parameters["xProjection"].SetValue(proj_matrix);
  387.  
  388.             Vector3 lightDirection = player_camera.to - player_camera.from;
  389.             effect.Parameters["xLightDirection"].SetValue(Vector3.Normalize(lightDirection));
  390.             effect.Parameters["xAmbient"].SetValue(0.25f);
  391.             effect.Parameters["xEnableLighting"].SetValue(true);
  392.  
  393.             effect.Parameters["xWorld"].SetValue(Matrix.CreateScale(earth.scale) * Matrix.CreateTranslation(earth.position));
  394.             foreach (EffectPass pass in effect.CurrentTechnique.Passes)
  395.             {
  396.                 pass.Apply();
  397.  
  398.                 earth.Draw(GraphicsDevice);
  399.             }
  400.  
  401.             foreach (Cylinder c in all_game_cylinders)
  402.             {
  403.                 Matrix world_matrix = Matrix.CreateRotationZ(MathHelper.ToRadians(c.angle)) *
  404.                                       Matrix.CreateScale(new Vector3(new Vector2(c.radius), c.height)) *
  405.                                       Matrix.CreateTranslation(c.position + new Vector3(0.0f, 0.0f, c.height));
  406.                 effect.Parameters["xWorld"].SetValue(world_matrix);
  407.  
  408.                 foreach (EffectPass pass in effect.CurrentTechnique.Passes)
  409.                 {
  410.                     pass.Apply();
  411.  
  412.                     player.Draw(gameTime, GraphicsDevice);
  413.                 }
  414.             }
  415.  
  416.             Func<int, int> flat_index = delegate(int i)
  417.             {
  418.                 return 1 + i;
  419.             };
  420.             Color shadow_color = Color.Black;
  421.             int n = 24;
  422.             VertexPositionColorNormal[] vertices = new VertexPositionColorNormal[1 + n];
  423.             {
  424.                 Vector2 v2 = new Vector2(player.position.X, player.position.Y);
  425.  
  426.                 vertices[0] = new VertexPositionColorNormal(new Vector3(v2, get_floor_at(v2)), shadow_color, Vector3.UnitZ);
  427.             }
  428.             shadow_color.A = 0;
  429.             for (int k = 0; k < n; k++)
  430.             {
  431.                 Single angle = ((Single)k / (Single)n) * MathHelper.TwoPi;
  432.                 Vector2 v2 = Vector2Ext.FromDirection(angle);
  433.  
  434.                 v2 *= player.radius * 1.125f;
  435.                 v2 += new Vector2(player.position.X, player.position.Y);
  436.  
  437.                 vertices[flat_index(k)] = new VertexPositionColorNormal(new Vector3(v2, get_floor_at(v2)), shadow_color, Vector3.UnitZ);
  438.             }
  439.             int[] indeces = new int[(n+1) * 3];
  440.             int index = 0;
  441.             for (int k = 0; k < n; k++)
  442.             {
  443.                 indeces[index++] = 0;
  444.                 indeces[index++] = flat_index((k + 1)%n);
  445.                 indeces[index++] = flat_index(k);
  446.             }
  447.  
  448.             effect.Parameters["xWorld"].SetValue(Matrix.CreateTranslation(0.0f, 0.0f, 0.0625f));
  449.             foreach (EffectPass pass in effect.CurrentTechnique.Passes)
  450.             {
  451.                 pass.Apply();
  452.                 GraphicsDevice.DrawUserIndexedPrimitives(PrimitiveType.TriangleList, vertices, 0, vertices.Length, indeces, 0, indeces.Length / 3);
  453.             }
  454.  
  455.  
  456.             base.Draw(gameTime);
  457.         }
  458.     }
  459. }