Advertisement
Guest User

Levelcs

a guest
Dec 21st, 2011
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 12.60 KB | None | 0 0
  1. #region Using
  2.  
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Windows.Forms;
  6. using Microsoft.Xna.Framework;
  7. using Microsoft.Xna.Framework.Content;
  8. using Microsoft.Xna.Framework.Graphics;
  9. using Microsoft.Xna.Framework.Input;
  10. using System.Collections.Generic;
  11. using PolitieNL.Game.Managers;
  12.  
  13. using Pathfinding;
  14. #endregion
  15.  
  16. namespace PolitieNL.Game.Levels
  17. {
  18.     class Level
  19.     {
  20.         #region Members
  21.         /// <summary>
  22.         /// Test model
  23.         /// </summary>
  24.         private Model _level;
  25.         private Model _props;
  26.         KeyboardState currentKeyboardState;
  27.         GamePadState currentGamePadState;
  28.         private Matrix[] _transforms;
  29.         private Matrix[] _porpsTransforms;
  30.         Map _mMap;
  31.         private Effect _eShadowMapEffect;
  32.         SpriteBatch spriteBatch;
  33.         TriangleProcessor _pickingProcessor;
  34.         // The shadow map render target
  35.         RenderTarget2D _shadowRenderTarget;
  36.         const int ShadowMapWidthHeight = 2048;
  37.         // ViewProjection matrix from the lights perspective
  38.         Matrix _lightViewProjection;
  39.         // Transform matrices
  40.         Matrix _world;
  41.         Matrix _view;
  42.         Matrix _projection;
  43.         private Matrix _lightView;
  44.         private float rotate;
  45.         // Light direction
  46.         Vector3 lightPos = new Vector3(10,10,10);
  47.         Vector3 lightDir = new Vector3(-0.3333333f, 0.6666667f, 0.6666667f);
  48.         // Starting position and direction of our camera
  49.         Vector3 cameraPosition = new Vector3(690.0f, 400.0f, 271);
  50.         Vector3 cameraForward = new Vector3(0, -0.4472136f, -0.8944272f);
  51.         BoundingFrustum cameraFrustum = new BoundingFrustum(Matrix.Identity);
  52.  
  53.  
  54.         #endregion
  55.  
  56.         #region Functions
  57.        /// <summary>
  58.         /// Initialize level
  59.         /// </summary>
  60.         /// <param name="content">contentmanager for loading models</param>
  61.         /// <param name="projMat">projection matrix</param>
  62.         public void Initialize(ContentManager content, PolitieNL.Game.CameraClass.Camera cam , GraphicsDevice device)
  63.         {
  64.             spriteBatch = new SpriteBatch(device);
  65.            
  66.  
  67.             //Load test model
  68.             _level = content.Load<Model>("Models/PNTS_Building");
  69.             _props = content.Load<Model>("Models/PNTS_Props");
  70.            
  71.             //_eShadowMapEffect = content.Load<Effect>("Effect/DrawModel");
  72.  
  73.             _view = cam.ViewMatrix;
  74.             _projection = cam.ProjectionMatrix;
  75.  
  76.            
  77.             //Managers.ModelHandler.InitModel(_level, cam.ProjectionMatrix, out _transforms);
  78.             //Managers.ModelHandler.InitModel(_props, cam.ProjectionMatrix, out _porpsTransforms);
  79.            
  80.             var transMat = new Matrix[_level.Bones.Count];
  81.             _pickingProcessor = new TriangleProcessor();
  82.             var lst = new List<string>();
  83.             _pickingProcessor.ExtractData(_level, ref transMat, new Vector3(0, 0, 0), Matrix.Identity, false, lst);
  84.  
  85.             // Create floating point render target
  86.             _shadowRenderTarget = new RenderTarget2D(device,
  87.                                                     ShadowMapWidthHeight,
  88.                                                     ShadowMapWidthHeight,
  89.                                                     true,
  90.                                                     SurfaceFormat.Single,
  91.                                                     DepthFormat.Depth24);
  92.             _mMap = new Map();
  93.             _mMap.LoadContent(content, cam);
  94.         }
  95.         public void Update(GameTime gameTime)
  96.         {
  97.             //HandleInput(gameTime);
  98.  
  99.             //UpdateCamera(gameTime);
  100.  
  101.         }
  102.  
  103.         /// <summary>
  104.         /// Draws the level
  105.         /// </summary>
  106.         public void Draw(Matrix viewMat, Matrix projMat, GraphicsDevice device)
  107.         {
  108.            
  109.             // Create the new view matrix
  110.             _view = viewMat;
  111.             _projection = projMat;
  112.             // Set the new frustum value
  113.             cameraFrustum.Matrix = viewMat * projMat;
  114.             // Update the lights ViewProjection matrix based on the
  115.             // current camera frustum
  116.             _lightViewProjection = CreateLightViewProjectionMatrix();
  117.  
  118.             device.BlendState = BlendState.Opaque;
  119.             device.DepthStencilState = DepthStencilState.Default;
  120.  
  121.  
  122.             // Render the scene to the shadow map
  123.             CreateShadowMap(device);
  124.  
  125.             // Draw the scene using the shadow map
  126.             DrawWithShadowMap(device);
  127.  
  128.             // Display the shadow map to the screen
  129.             DrawShadowMapToScreen(device);
  130.            
  131.            
  132.             //Managers.ModelHandler.DrawModel(_level, viewMat, Matrix.Identity, _transforms);
  133.             //Managers.ModelHandler.DrawModel(_props, viewMat, Matrix.Identity, _transforms);
  134.             //if (m_map.IsMapthere()) m_map.Draw(spriteBatch, viewMat, transforms, projMat);
  135.  
  136.         }
  137.         public float UpdatePicking(ref Ray ray)
  138.         {
  139.             for (int i = 0; i < _pickingProcessor.indexList.Count; ++i)
  140.             {
  141.                 Vector3 vertex1, vertex2, vertex3;
  142.                 vertex1 = vertex2 = vertex3 = Vector3.Zero;
  143.                 float? intersection = null;
  144.  
  145.                 _pickingProcessor.RayIntersectsTriangle(ref ray,
  146.                                                   _pickingProcessor.vertexList[_pickingProcessor.indexList[i].I0],
  147.                                                   _pickingProcessor.vertexList[_pickingProcessor.indexList[i].I1],
  148.                                                   _pickingProcessor.vertexList[_pickingProcessor.indexList[i].I2],
  149.                                                   out intersection);
  150.                 if (intersection != null)
  151.                     return (float)intersection;
  152.             }
  153.             return 0;
  154.         }
  155.  
  156.         public Map GetMap() { return _mMap; }
  157.  
  158.  
  159.  
  160.         #endregion
  161.  
  162.         #region Shadowmap methods
  163.         /// <summary>
  164.         /// Creates the WorldViewProjection matrix from the perspective of the
  165.         /// light using the cameras bounding frustum to determine what is visible
  166.         /// in the scene.
  167.         /// </summary>
  168.         /// <returns>The WorldViewProjection for the light</returns>
  169.         Matrix CreateLightViewProjectionMatrix()
  170.         {
  171.             #region algOne
  172.             // Matrix with that will rotate in points the direction of the light
  173.             Matrix lightRotation = Matrix.CreateLookAt(Vector3.Zero,
  174.                                                        -lightDir,
  175.                                                        Vector3.Up);
  176.  
  177.             // Get the corners of the frustum
  178.             Vector3[] frustumCorners = cameraFrustum.GetCorners();
  179.  
  180.             // Transform the positions of the corners into the direction of the light
  181.             for (int i = 0; i < frustumCorners.Length; i++)
  182.             {
  183.                 frustumCorners[i] = Vector3.Transform(frustumCorners[i], lightRotation);
  184.             }
  185.  
  186.             // Find the smallest box around the points
  187.             BoundingBox lightBox = BoundingBox.CreateFromPoints(frustumCorners);
  188.  
  189.             Vector3 boxSize = lightBox.Max - lightBox.Min;
  190.             Vector3 halfBoxSize = boxSize * 0.5f;
  191.  
  192.             // The position of the light should be in the center of the back
  193.             // pannel of the box.
  194.             Vector3 lightPosition = lightBox.Min + halfBoxSize;
  195.             lightPosition.Z = lightBox.Min.Z;
  196.  
  197.             // We need the position back in world coordinates so we transform
  198.             // the light position by the inverse of the lights rotation
  199.             lightPosition = Vector3.Transform(lightPosition,
  200.                                               Matrix.Invert(lightRotation));
  201.  
  202.             // Create the view matrix for the light
  203.             Matrix lightView = Matrix.CreateLookAt(lightPosition,
  204.                                                    lightPosition - lightDir,
  205.                                                    Vector3.Up);
  206.  
  207.             // Create the projection matrix for the light
  208.             // The projection is orthographic since we are using a directional light
  209.             Matrix lightProjection = Matrix.CreateOrthographic(boxSize.X, boxSize.Y,
  210.                                                                -boxSize.Z, boxSize.Z);
  211.             _lightView = lightView;
  212.             return lightView * lightProjection;
  213.             #endregion
  214.  
  215.         }
  216.  
  217.         /// <summary>
  218.         /// Renders the scene to the floating point render target then
  219.         /// sets the texture for use when drawing the scene.
  220.         /// </summary>
  221.         void CreateShadowMap(GraphicsDevice device)
  222.         {
  223.             // Set our render target to our floating point render target
  224.             device.SetRenderTarget(_shadowRenderTarget);
  225.            
  226.             // Clear the render target to white or all 1's
  227.             // We set the clear to white since that represents the
  228.             // furthest the object could be away
  229.             device.Clear(Color.White);
  230.  
  231.             device.DepthStencilState = DepthStencilState.Default;
  232.             device.BlendState = BlendState.Opaque;
  233.  
  234.             // Draw any occluders in our case that is just the dude model
  235.             _world = Matrix.Identity;
  236.             // Set the models world matrix so it will rotate
  237.             //_world = Matrix.CreateRotationY(MathHelper.ToRadians(rotate));
  238.             // Draw the dude model
  239.             DrawModel(_props, true);
  240.  
  241.             // Set render target back to the back buffer
  242.             device.SetRenderTarget(null);
  243.  
  244.         }
  245.  
  246.         /// <summary>
  247.         /// Renders the scene using the shadow map to darken the shadow areas
  248.         /// </summary>
  249.         void DrawWithShadowMap(GraphicsDevice device)
  250.         {
  251.             device.Clear(Color.Green);
  252.  
  253.              device.DepthStencilState = DepthStencilState.Default;
  254.              device.BlendState = BlendState.Opaque;
  255.  
  256.             device.SamplerStates[1] = SamplerState.PointClamp;
  257.  
  258.             // Draw the grid
  259.             _world = Matrix.Identity;
  260.             DrawModel(_level, false);
  261.  
  262.             _world = Matrix.Identity;
  263.             // Draw the Props model
  264.             //_world = Matrix.CreateRotationY(MathHelper.ToRadians(rotate));
  265.             DrawModel(_props, false);
  266.         }
  267.  
  268.         /// <summary>
  269.         /// Helper function to draw a model
  270.         /// </summary>
  271.         /// <param name="model">The model to draw</param>
  272.         ///<param name="createShadowMap">Draw to Create or not</param>
  273.         void DrawModel(Model model, bool createShadowMap)
  274.         {
  275.             string techniqueName = createShadowMap ? "CreateShadowMap" : "DrawWithShadowMap";
  276.  
  277.              _transforms = new Matrix[model.Bones.Count];
  278.             model.CopyAbsoluteBoneTransformsTo(_transforms);
  279.  
  280.             // Loop over meshs in the model
  281.             foreach (ModelMesh mesh in model.Meshes)
  282.             {
  283.  
  284.                 foreach (Effect effect in mesh.Effects)
  285.                 {
  286.                    
  287.                     // Set the currest values for the effect
  288.                     effect.CurrentTechnique = effect.Techniques[techniqueName];
  289.                     effect.Parameters["World"].SetValue(_transforms[mesh.ParentBone.Index] * _world);
  290.                     effect.Parameters["View"].SetValue(_view);
  291.                     effect.Parameters["Projection"].SetValue(_projection);
  292. //                     effect.Parameters["LightPos"].SetValue(lightPos);
  293. //                     effect.Parameters["mLightView"].SetValue(_lightView);
  294.                     effect.Parameters["LightDirection"].SetValue(lightDir);
  295.                     effect.Parameters["LightViewProj"].SetValue(_lightViewProjection);
  296.  
  297.                     if (!createShadowMap)
  298.                         effect.Parameters["ShadowMap"].SetValue(_shadowRenderTarget);
  299.                 }
  300.  
  301.                 //mesh.Effects = _eShadowMapEffect;
  302.                 // Loop over effects in the mesh
  303.  
  304.                 // Draw the mesh
  305.                 mesh.Draw();
  306.             }
  307.         }
  308.  
  309.         /// <summary>
  310.         /// Render the shadow map texture to the screen
  311.         /// </summary>
  312.         void DrawShadowMapToScreen(GraphicsDevice device)
  313.         {
  314.             spriteBatch.Begin(0, BlendState.Opaque, SamplerState.PointClamp, null, null);
  315.             spriteBatch.Draw(_shadowRenderTarget, new Rectangle(0, 0, 128, 128), Color.White);
  316.             spriteBatch.End();
  317.  
  318.             device.Textures[0] = null;
  319.             device.SamplerStates[0] = SamplerState.LinearWrap;
  320.         }
  321.  
  322.         #endregion
  323.  
  324.     }
  325. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement