/// <summary>
        /// Loads the height data.
        /// </summary>
        private void LoadHeightData()
        {
            this.tm = new TerrainModel();

            DateTime dtStart = DateTime.Now;

            //tm.LoadXYZFile(@"D:\BigData\SRTM Tiles Germany\srtm_38_03.xyz");
            this.tm.LoadXYZFile(@"C:\Lanser\BigData\SRTM Tiles Germany\srtm_38_03.xyz");
            DateTime dtStop = DateTime.Now;

            GMapPolygon polygon = new GMapPolygon(new List <PointLatLng>
            {
                new PointLatLng(this.tm.YMin, this.tm.XMin),
                new PointLatLng(this.tm.YMax, this.tm.XMin),
                new PointLatLng(this.tm.YMax, this.tm.XMax),
                new PointLatLng(this.tm.YMin, this.tm.XMax)
            });

            this.mcMapControl.Markers.Add(polygon);

            MB.Information($"Time: {( dtStop - dtStart ).ToHHMMSSString()} / Points: {this.tm.PointCount}");

            GC.WaitForPendingFinalizers();
            GC.Collect();
        }
        /// <summary>
        /// Updates the light and ambient variables which can then be used to update the shader.
        /// </summary>
        public void UpdateVars()
        {
            switch (type)
            {
            case RenderedObjectType.Terrain:
                TerrainModel terrain = (TerrainModel)modelObject.model;
                light          = ShaderIDTable.ALLOCATED_LIGHTS;
                renderDistance = float.MaxValue;
                break;

            case RenderedObjectType.Moby:
                Moby mob = (Moby)modelObject;
                light          = Math.Max(0, Math.Min(ShaderIDTable.ALLOCATED_LIGHTS, mob.light));
                ambient        = mob.color;
                renderDistance = mob.drawDistance;
                break;

            case RenderedObjectType.Tie:
                Tie tie = (Tie)modelObject;
                light          = Math.Max(0, Math.Min(ShaderIDTable.ALLOCATED_LIGHTS, tie.light));
                renderDistance = float.MaxValue;
                break;

            case RenderedObjectType.Shrub:
                Shrub shrub = (Shrub)modelObject;
                light          = Math.Max(0, Math.Min(ShaderIDTable.ALLOCATED_LIGHTS, shrub.light));
                ambient        = shrub.color;
                renderDistance = shrub.drawDistance;
                break;
            }
        }
        public void Shutdown()
        {
            // Release the position object.
            Position = null;
            // Release the light object.
            Light = null;
            // Release the fps object.
            FPS = null;
            // Release the camera object.
            Camera = null;

            // Release the text object.
            Text?.Shutdown();
            Text = null;
            // Release the cpu object.
            CPU?.Shutdown();
            CPU = null;
            // Release the terrain shader object.
            TerrainBumpMapShader?.ShutDown();
            TerrainBumpMapShader = null;
            // Release the tree object.
            TerrainModel?.ShutDown();
            TerrainModel = null;
            // Release the input object.
            Input?.Shutdown();
            Input = null;
            // Release the Direct3D object.
            D3D?.ShutDown();
            D3D = null;
        }
Exemple #4
0
        }                                   // Always 0


        public TerrainFragment(FileStream fs, TerrainHead head, byte[] tfragBlock, int num)
        {
            int offset = num * 0x30;

            float cullingX = ReadFloat(tfragBlock, offset + 0x00);
            float cullingY = ReadFloat(tfragBlock, offset + 0x04);
            float cullingZ = ReadFloat(tfragBlock, offset + 0x08);

            cullingSize = ReadFloat(tfragBlock, offset + 0x0C);

            off1C = ReadUshort(tfragBlock, offset + 0x1C);
            off1E = ReadUshort(tfragBlock, offset + 0x1E);

            off20 = ReadUshort(tfragBlock, offset + 0x20);
            off24 = ReadUint(tfragBlock, offset + 0x24);
            off28 = ReadUint(tfragBlock, offset + 0x28);
            off2C = ReadUint(tfragBlock, offset + 0x2C);

            model = new TerrainModel(fs, head, tfragBlock, num);

            modelID = model.id;

            modelMatrix = Matrix4.Identity;

            cullingCenter = new Vector3(cullingX, cullingY, cullingZ);
        }
Exemple #5
0
        private bool RenderSceneToTexture()
        {
            // Set the render target to be the render to texture.
            RenderTexture.SetRenderTarget(D3D.DeviceContext);

            // Clear the render to texture.
            RenderTexture.ClearRenderTarget(D3D.DeviceContext, 0.0f, 0.0f, 0.0f, 1.0f);

            // Generate the view matrix based on the camera's position.
            Camera.Render();

            // Get the world, view, projection, ortho, and base view matrices from the camera and Direct3D objects.
            Matrix worldMatrix      = D3D.WorldMatrix;
            Matrix viewMatrix       = Camera.ViewMatrix;
            Matrix projectionMatrix = D3D.ProjectionMatrix;

            // Render the terrain using the depth shader.
            TerrainModel.Render(D3D.DeviceContext);
            if (!DepthShader.Render(D3D.DeviceContext, TerrainModel.IndexCount, worldMatrix, viewMatrix, projectionMatrix))
            {
                return(false);
            }

            // Reset the render target back to the original back buffer and not the render to texture anymore.
            D3D.SetBackBufferRenderTarget();

            // Reset the viewport back to the original.
            D3D.ResetViewPort();

            return(true);
        }
        private bool Render()
        {
            // Clear the scene.
            D3D.BeginScene(0.0f, 0.0f, 0.0f, 1.0f);

            // Generate the view matrix based on the camera's position.
            Camera.Render();

            // Get the world, view, projection, ortho, and base view matrices from the camera and Direct3D objects.
            Matrix worldMatrix      = D3D.WorldMatrix;
            Matrix viewCameraMatrix = Camera.ViewMatrix;
            Matrix projectionMatrix = D3D.ProjectionMatrix;
            Matrix orthoMatrix      = D3D.OrthoMatrix;

            // Render the terrain using the terrain shader.
            TerrainModel.Render(D3D.DeviceContext);
            if (!TerrainShader.Render(D3D.DeviceContext, TerrainModel.IndexCount, worldMatrix, viewCameraMatrix, projectionMatrix, Light.Direction, ColourTexture1.TextureResource, ColourTexture2.TextureResource, ColourTexture3.TextureResource, ColourTexture4.TextureResource, AlphaTexture1.TextureResource, NormalTexture1.TextureResource, NormalTexture2.TextureResource))
            {
                return(false);
            }

            // Present the rendered scene to the screen.
            D3D.EndScene();

            return(true);
        }
 public TerrainEngine(TerrainModel terrainModel)
 {
     this.terrainModel      = terrainModel;
     requestedLayerPosition = 0;
     TerrainSize            = 512;
     FlattenTerrain();
 }
Exemple #8
0
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            player = new Player();
            objects.Add(player);

            world = new World();

            ballModel = new BallModel();

            gameState = new MyGameState();
            gameState.CameraMatrix = Matrix.CreateTranslation((_graphics.PreferredBackBufferWidth / 2) - (Player.PlayerSpriteSize / 2), 0, 0);
            gameState.WorldSize    = WorldSize;

            terrainModel = new TerrainModel();

            for (int i = -20; i < 20; i++)
            {
                TerrainTile t = new TerrainTile(terrainModel, i, r.Next() % 4);
                objects.Add(t);
            }

            base.Initialize();
        }
Exemple #9
0
 IEnumerator DoThings()
 {
     Vector3[] initialVerts = new Vector3[_verticies.Length];
     while (true)
     {
         Vector3[] newVerts       = Grid2D.CreateVertices(GridSizeX, GridSizeY, cellSize.x, cellSize.y);
         float     time           = 0;
         float     lerpTimeLength = 1f;
         TerrainModel.JumbleVertz(newVerts, _terrainModel.jumbleAmount);
         float t = 0;
         System.Array.Copy(_verticies, initialVerts, _verticies.Length);
         do
         {
             time += Time.deltaTime;
             t     = time / lerpTimeLength;
             for (int i = 0; i < newVerts.Length; ++i)
             {
                 _verticies[i] = Vector3.Lerp(initialVerts[i], newVerts[i], t);
             }
             Render.DrawVerts(_meshFilter.mesh, _verticies, _tris, _uvs);
             yield return(null);
         } while (time <= lerpTimeLength);
         Render.DrawVerts(_meshFilter.mesh, newVerts, _tris, _uvs);
         yield return(new WaitForSeconds(2.0f));
     }
 }
Exemple #10
0
        private static double GetElevation(TerrainModel model, double x, double y)
        {
            double colWidth = (model.Right - model.Left) / (model.Width - 1);
            int    col      = (int)((x - model.Left) / colWidth);
            double rowWidth = (model.Top - model.Bottom) / (model.Height - 1);
            int    row      = (int)(model.Height - 1 - (y - model.Bottom) / rowWidth);

            if (row == model.Height - 1)
            {
                row--;
            }
            if (col == model.Width - 1)
            {
                col--;
            }

            double lbElevation = model.Data[model.Width * row + col];
            double ltElevation = model.Data[model.Width * (row + 1) + col];
            double rtElevation = model.Data[model.Width * (row + 1) + col + 1];
            double rbElevation = model.Data[model.Width * row + col + 1];
            double u           = (x - model.Left) / colWidth - col;
            double v           = model.Height - 1 - (y - model.Bottom) / rowWidth - row;

            return((1 - u) * (1 - v) * lbElevation + (1 - u) * v * ltElevation + u * (1 - v) * rbElevation + u * v * rtElevation);
        }
        void createterrain(int height = 5)
        {
            ///Create the Terrain Object
            ///Controls how the heigh map is loaded
            TerrainObject to = new TerrainObject(GraphicFactory, "..\\Content\\Textures\\hmap", new Vector3(0, -30, 0), Matrix.Identity, MaterialDescription.DefaultBepuMaterial(), 3, 3, height);

            ///Create the Model using the Terrain Object. Here we pass the textures used
            TerrainModel stm = new TerrainModel(GraphicFactory, to, "TerrainName", "..\\Content\\Textures\\Terraingrass");

            stm.SetTexture("..\\Content\\Textures\\Terraingrass", TextureType.DIFFUSE);
            ForwardXNABasicShader shader    = new ForwardXNABasicShader();
            ForwardMaterial       fmaterial = new ForwardMaterial(shader);

            ///The object itself
            obj = new IObject(fmaterial, stm, to);
            ///Add to the world
            this.World.AddObject(obj);

            ///light =p
            shader.BasicEffect.EnableDefaultLighting();
            shader.BasicEffect.SpecularPower          = 250;
            shader.BasicEffect.PreferPerPixelLighting = true;


            //Fog =P
            shader.BasicEffect.FogEnabled = true;
            shader.BasicEffect.FogColor   = new Vector3(0.1f, 0.1f, 0.1f); // Dark grey
            shader.BasicEffect.FogStart   = 30;
            shader.BasicEffect.FogEnd     = 300;
        }
        protected override void LoadContent(GraphicInfo GraphicInfo, GraphicFactory factory, IContentManager contentManager)
        {
            base.LoadContent(GraphicInfo, factory, contentManager);

            ///Create the Terrain Object
            ///Controls how the heigh map is loaded
            TerrainObject to = new TerrainObject(factory, "..\\Content\\Textures\\Untitled", Vector3.Zero, Matrix.Identity, MaterialDescription.DefaultBepuMaterial(), 1, 1, 10);
            ///Create the Model using the Terrain Object. Here we pass the textures used, in our case we are using MultiTextured Terrain so we pass lots of textures
            TerrainModel stm = new TerrainModel(factory, to, "TerrainName", "..\\Content\\Textures\\Terraingrass");

            stm.SetTexture(factory.CreateTexture2DColor(1, 1, Color.Green), TextureType.DIFFUSE);
            ///Create the shader
            ///In this sample we passed lots of textures, each one describe a level in the terrain, the ground is the sand and grass. the hills are rocks and the "mountains" are snow
            ///They are interpolated in the shader, you can control how using the shader parameters exposed in the DeferredTerrainShader
            ForwardXNABasicShader shader = new ForwardXNABasicShader();
            ///Deferred material
            ForwardMaterial fmaterial = new ForwardMaterial(shader);
            ///The object itself
            IObject obj = new IObject(fmaterial, stm, to);

            ///Add to the world
            this.World.AddObject(obj);

            shader.BasicEffect.EnableDefaultLighting();

            CameraFirstPerson cam = new CameraFirstPerson(GraphicInfo.Viewport);

            this.World.CameraManager.AddCamera(cam);
        }
        /// <summary>
        /// Calculates the texture for the specified model.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <param name="mesh">
        /// The mesh.
        /// </param>
        public override void Calculate(TerrainModel model, MeshGeometry3D mesh)
        {
            var normals = MeshGeometryHelper.CalculateNormals(mesh);
            var texcoords = new PointCollection();
            var up = new Vector3D(0, 0, 1);
            for (int i = 0; i < normals.Count; i++)
            {
                double slope = Math.Acos(Vector3D.DotProduct(normals[i], up)) * 180 / Math.PI;
                double u = slope / 40;
                if (u > 1)
                {
                    u = 1;
                }

                if (u < 0)
                {
                    u = 0;
                }

                texcoords.Add(new Point(u, u));
            }

            this.TextureCoordinates = texcoords;
            this.Material = MaterialHelper.CreateMaterial(this.Brush);
        }
        private bool RenderRefractionToTexture()
        {
            // Setup a clipping plane based on the height of the water to clip everything above it to create a refraction.
            Vector4 clipPlane = new Vector4(0.0f, -1.0f, 0.0f, WaterModel.WaterHeight + 0.1f);

            // Set the render target to be the refraction render to texture.
            RefractionTexture.SetRenderTarget(D3D.DeviceContext);

            // Clear the refraction render to texture.
            RefractionTexture.ClearRenderTarget(D3D.DeviceContext, 0.0f, 0.0f, 0.0f, 1.0f);

            // Generate the view matrix based on the camera's position.
            Camera.Render();

            // Get the matrices from the camera and d3d objects.
            Matrix worldMatrix      = D3D.WorldMatrix;
            Matrix viewMatrix       = Camera.ViewMatrix;
            Matrix projectionMatrix = D3D.ProjectionMatrix;

            // Render the terrain using the reflection shader and the refraction clip plane to produce the refraction effect.
            TerrainModel.Render(D3D.DeviceContext);
            if (!ReflectionShader.Render(D3D.DeviceContext, TerrainModel.IndexCount, worldMatrix, viewMatrix, projectionMatrix, TerrainModel.ColorTexture.TextureResource, TerrainModel.NormalMapTexture.TextureResource, Light.DiffuseColour, Light.Direction, 2.0f, clipPlane))
            {
                return(false);
            }

            // Reset the render target back to the original back buffer and not the render to texture anymore.
            D3D.SetBackBufferRenderTarget();

            // Reset the viewport back to the original.
            D3D.ResetViewPort();

            return(true);
        }
 private void InitLogic()
 {
     TerrainModel   = new TerrainModel();
     TerrainEngine  = new TerrainEngine(TerrainModel);
     ViewportCamera = new ViewportCamera();
     Viewport       = new Viewport(TerrainEngine, ViewportCamera, TerrainModel);
     LayerManager   = new LayerManager(TerrainEngine);
     TerrainEngine.InitLogic(LayerManager, this);
 }
        public void Shutdown()
        {
            // Release the position object.
            Position = null;
            // Release the light object.
            Light = null;
            // Release the fps object.
            FPS = null;
            // Release the camera object.
            Camera = null;

            // Release the text object.
            Text?.Shutdown();
            Text = null;
            // Release the cpu object.
            CPU?.Shutdown();
            CPU = null;
            // Release the water shader object.
            WaterShader?.ShutDown();
            WaterShader = null;
            // Release the water object.
            WaterModel?.ShutDown();
            WaterModel = null;
            // Release the reflection shader object.
            ReflectionShader?.ShutDown();
            ReflectionShader = null;
            // Release the reflection render to texture object.
            ReflectionTexture?.Shutdown();
            ReflectionTexture = null;
            // Release the refraction render to texture object.
            RefractionTexture?.Shutdown();
            RefractionTexture = null;
            // Release the sky plane shader object.
            SkyPlaneShader?.ShutDown();
            SkyPlaneShader = null;
            // Release the sky plane object.
            SkyPlane?.ShurDown();
            SkyPlane = null;
            // Release the sky dome shader object.
            SkyDomeShader?.ShutDown();
            SkyDomeShader = null;
            // Release the sky dome object.
            SkyDome?.ShutDown();
            SkyDome = null;
            // Release the terrain shader object.
            TerrainShader?.ShutDown();
            TerrainShader = null;
            // Release the tree object.
            TerrainModel?.ShutDown();
            TerrainModel = null;
            // Release the input object.
            Input?.Shutdown();
            Input = null;
            // Release the Direct3D object.
            D3D?.ShutDown();
            D3D = null;
        }
Exemple #17
0
 public CustomTerrain(TerrainModel terrainModel)
 {
     this.ID          = terrainModel.terrainID;
     this.name        = terrainModel.terrainName;
     this.population  = terrainModel.population;
     this.gold        = terrainModel.gold;
     this.food        = terrainModel.food;
     this.description = terrainModel.description;
     this.tile        = Resources.Load <Tile>(terrainModel.tilePath) as Tile;
 }
 public CustomTerrain(TerrainModel terrainModel)
 {
     this.ID   = terrainModel.terrainID;
     this.name = terrainModel.terrainName;
     this.initialPopulation = terrainModel.initialPopulation;
     this.initalGold        = terrainModel.initalGold;
     this.growPopulation    = terrainModel.growPopulation;
     this.growGold          = terrainModel.growGold;
     this.description       = terrainModel.description;
     this.tile = Resources.Load <Tile>(terrainModel.tilePath) as Tile;
 }
Exemple #19
0
 public void LoadData(double[] elevations, int width, double left, double right, double top, double bottom)
 {
     _model        = new TerrainModel();
     _data         = elevations.ToArray();
     _model.Width  = width;
     _model.Height = elevations.Length / _model.Width;
     _model.Left   = left;
     _model.Right  = right;
     _model.Top    = top;
     _model.Bottom = bottom;
 }
Exemple #20
0
    private void ReadSettings(TerrainModel tModel)
    {
        _verticies = tModel.vertices;
        _tris      = tModel.tris;
        _uvs       = tModel.uvs;

        GridSizeX    = tModel.GridSizeX;
        GridSizeY    = tModel.GridSizeY;
        cellSize     = tModel.cellSize;
        jumbleAmount = tModel.jumbleAmount;
        _meshFilter  = tModel.meshFilter;
    }
        private bool RenderGraphics()
        {
            // Clear the scene.
            D3D.BeginScene(0.0f, 0.0f, 0.0f, 1.0f);

            // Generate the view matrix based on the camera's position.
            Camera.Render();

            // Get the world, view, projection, and ortho matrices from the camera and Direct3D objects.
            Matrix worldMatrix      = D3D.WorldMatrix;
            Matrix cameraViewMatrix = Camera.ViewMatrix;
            Matrix projectionMatrix = D3D.ProjectionMatrix;
            Matrix orthoD3DMatrix   = D3D.OrthoMatrix;

            // Render the terrain buffers.
            TerrainModel.Render(D3D.DeviceContext);

            // Render the model using the color shader.
            if (!TerrainShader.Render(D3D.DeviceContext, TerrainModel.IndexCount, worldMatrix, cameraViewMatrix, projectionMatrix, Light.AmbientColor, Light.DiffuseColour, Light.Direction, TerrainModel.Texture.TextureResource))
            {
                return(false);
            }

            // Turn off the Z buffer to begin all 2D rendering.
            D3D.TurnZBufferOff();

            // Render the mini map.
            if (!MiniMap.Render(D3D.DeviceContext, worldMatrix, orthoD3DMatrix, TextureShader))
            {
                return(false);
            }

            // Turn on the alpha blending before rendering the text.
            D3D.TurnOnAlphaBlending();

            // Render the text user interface elements.
            if (!Text.Render(D3D.DeviceContext, worldMatrix, orthoD3DMatrix))
            {
                return(false);
            }

            // Turn off alpha blending after rendering the text.
            D3D.TurnOffAlphaBlending();

            // Turn the Z buffer back on now that all 2D rendering has completed.
            D3D.TurnZBufferOn();

            // Present the rendered scene to the screen.
            D3D.EndScene();

            return(true);
        }
        public Viewport(TerrainEngine terrainSettings, ViewportCamera viewportCamera, TerrainModel terrainModel)
        {
            this.terrainModel   = terrainModel;
            EffectsManager      = new DefaultEffectsManager();
            this.terrainEngine  = terrainSettings;
            this.viewportCamera = viewportCamera;

            InitProperties();
            InitCommands();
            InitModel();
            InitDefaultViewportSettings();
            ChangeViewMode(0);
        }
        protected override void LoadContent(GraphicInfo GraphicInfo, GraphicFactory factory, IContentManager contentManager)
        {
            base.LoadContent(GraphicInfo, factory, contentManager);


            Picking picking = new Picking(this);

            this.AddScreenUpdateable(picking);

            perlim = factory.CreateTexture2DPerlinNoise(512, 512, 0.03f, 3f, 0.5f, 1);
            to     = new TerrainObject(factory, perlim, Vector3.Zero, Matrix.Identity, MaterialDescription.DefaultBepuMaterial(), 2, 2);
            //TerrainObject to = new TerrainObject(factory,"..\\Content\\Textures\\Untitled",Vector3.Zero,Matrix.Identity,MaterialDescription.DefaultBepuMaterial(),2,1);
            TerrainModel          stm    = new TerrainModel(factory, to, "TerrainName", "..\\Content\\Textures\\Terraingrass", "..\\Content\\Textures\\rock", "..\\Content\\Textures\\sand", "..\\Content\\Textures\\snow");
            DeferredTerrainShader shader = new DeferredTerrainShader(TerrainType.MULTITEXTURE);
            DeferredMaterial      mat    = new DeferredMaterial(shader);
            IObject obj3 = new IObject(mat, stm, to);

            this.World.AddObject(obj3);



            #region NormalLight
            DirectionalLightPE ld1 = new DirectionalLightPE(Vector3.Left, Color.White);
            DirectionalLightPE ld2 = new DirectionalLightPE(Vector3.Right, Color.White);
            DirectionalLightPE ld3 = new DirectionalLightPE(Vector3.Backward, Color.White);
            DirectionalLightPE ld4 = new DirectionalLightPE(Vector3.Forward, Color.White);
            DirectionalLightPE ld5 = new DirectionalLightPE(Vector3.Down, Color.White);
            float li = 0.5f;
            ld1.LightIntensity = li;
            ld2.LightIntensity = li;
            ld3.LightIntensity = li;
            ld4.LightIntensity = li;
            ld5.LightIntensity = li;
            this.World.AddLight(ld1);
            this.World.AddLight(ld2);
            this.World.AddLight(ld3);
            this.World.AddLight(ld4);
            this.World.AddLight(ld5);
            #endregion

            this.World.CameraManager.AddCamera(new CameraFirstPerson(true, GraphicInfo));

            SkyBoxSetTextureCube stc = new SkyBoxSetTextureCube("Textures//cubemap");
            CommandProcessor.getCommandProcessor().SendCommandAssyncronous(stc);

            ///O PICKING FUNCIONA APENAS COM OBJETOS QUE TENHAM CORPO FISICO REAL !!!
            ///OS GHOST E OS DUMMY NUNCA SERAO SELECIONADOS
            ///Para ser informado a todo frame sobre as colisoes do raio, basta utilizar o outro construtor
            picking.OnPickedLeftButton += new OnPicked(onPick);
        }
Exemple #24
0
        public override void Calculate(TerrainModel model, MeshGeometry3D mesh)
        {
            base.TextureCoordinates = new PointCollection(mesh.Positions
                                                          .Select(p =>
            {
                double x = p.X + model.Offset.X;
                double y = p.Y + model.Offset.Y;
                double u = (GetElevation(model, x, y) - model.MinimumZ) / (model.MaximumZ - model.MinimumZ);
                u        = u > 1 ? 1 : u < 0 ? 0 : u;
                return(new Point(u, u));
            }));

            base.Material = MaterialHelper.CreateMaterial(Brush);
        }
Exemple #25
0
        protected override void LoadContent(GraphicInfo GraphicInfo, GraphicFactory factory, IContentManager contentManager)
        {
            base.LoadContent(GraphicInfo, factory, contentManager);

            ///Create the Terrain Object
            ///Controls how the heigh map is loaded
            TerrainObject to = new TerrainObject(factory, "..\\Content\\Textures\\Untitled", Vector3.Zero, Matrix.Identity, MaterialDescription.DefaultBepuMaterial(), 2, 1);
            ///Create the Model using the Terrain Object. Here we pass the textures used, in our case we are using MultiTextured Terrain so we pass lots of textures
            TerrainModel stm = new TerrainModel(factory, to, "TerrainName", "..\\Content\\Textures\\Terraingrass", "..\\Content\\Textures\\rock", "..\\Content\\Textures\\sand", "..\\Content\\Textures\\snow");
            ///Create the shader
            ///In this sample we passed lots of textures, each one describe a level in the terrain, the ground is the sand and grass. the hills are rocks and the "mountains" are snow
            ///They are interpolated in the shader, you can control how using the shader parameters exposed in the DeferredTerrainShader
            DeferredTerrainShader shader = new DeferredTerrainShader(TerrainType.MULTITEXTURE);
            ///the classic material
            DeferredMaterial mat  = new DeferredMaterial(shader);
            IObject          obj3 = new IObject(mat, stm, to);

            this.World.AddObject(obj3);

            lt = new LightThrowBepu(this.World, factory);

            #region NormalLight
            DirectionalLightPE ld1 = new DirectionalLightPE(Vector3.Left, Color.White);
            DirectionalLightPE ld2 = new DirectionalLightPE(Vector3.Right, Color.White);
            DirectionalLightPE ld3 = new DirectionalLightPE(Vector3.Backward, Color.White);
            DirectionalLightPE ld4 = new DirectionalLightPE(Vector3.Forward, Color.White);
            DirectionalLightPE ld5 = new DirectionalLightPE(Vector3.Down, Color.White);
            float li = 0.5f;
            ld1.LightIntensity = li;
            ld2.LightIntensity = li;
            ld3.LightIntensity = li;
            ld4.LightIntensity = li;
            ld5.LightIntensity = li;
            this.World.AddLight(ld1);
            this.World.AddLight(ld2);
            this.World.AddLight(ld3);
            this.World.AddLight(ld4);
            this.World.AddLight(ld5);
            #endregion

            CameraFirstPerson cam = new CameraFirstPerson(MathHelper.ToRadians(30), MathHelper.ToRadians(-10), new Vector3(200, 150, 250), GraphicInfo);
            this.World.CameraManager.AddCamera(cam);

            SkyBoxSetTextureCube stc = new SkyBoxSetTextureCube("Textures//grassCube");
            CommandProcessor.getCommandProcessor().SendCommandAssyncronous(stc);

            this.RenderTechnic.AddPostEffect(new AntiAliasingPostEffectStalker());
        }
Exemple #26
0
    void Awake()
    {
        InitializeModel();

        //int resolution = 256;
        //Texture2D texture = new Texture2D(resolution, resolution, TextureFormat.RGB24, true);
        //texture.name = "Procedural Texture";
        //GetComponent<MeshRenderer>().material.mainTexture = texture;
        //Render.FillTexture(resolution, texture);

        TerrainModel.JumbleVertz(_verticies, jumbleAmount);

        Render.DrawVerts(_meshFilter.mesh, _verticies, _tris, _uvs);

        StartCoroutine(DoThings());
    }
        private void OnShowTerrainModel(TerrainModel terrainModel)
        {
            if (!terrainModel)
            {
                _currentTerrainModelType = null;
                _animationProgress       = 1f;
                return;
            }
            Type modelType = terrainModel.GetType();

            if (_currentTerrainModelType != modelType)
            {
                _currentTerrainModelType = modelType;
                _animationProgress       = 0f;
                _startPosition           = transform.localPosition;
            }
        }
        /// <summary>
        /// Calculates the texture of the specified model.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <param name="mesh">
        /// The mesh.
        /// </param>
        public override void Calculate(TerrainModel model, MeshGeometry3D mesh)
        {
            var normals = MeshGeometryHelper.CalculateNormals(mesh);
            var texcoords = new PointCollection();
            for (int i = 0; i < normals.Count; i++)
            {
                double slopedir = Math.Atan2(normals[i].Y, normals[i].X) * 180 / Math.PI;
                if (slopedir < 0)
                {
                    slopedir += 360;
                }

                double u = slopedir / 360;
                texcoords.Add(new Point(u, u));
            }

            this.TextureCoordinates = texcoords;
            this.Material = MaterialHelper.CreateMaterial(this.Brush);
        }
Exemple #29
0
        public void Shutdown()
        {
            // Release the position object.
            Position = null;
            // Release the light object.
            Light = null;
            // Release the fps object.
            FPS = null;
            // Release the camera object.
            Camera = null;

            // Release the depth shader object.
            DepthShader?.ShutDown();
            DepthShader = null;
            // Release the render to texture object.
            RenderTexture?.Shutdown();
            RenderTexture = null;
            // Release the texture shader object.
            TextureShader?.ShutDown();
            TextureShader = null;
            // Release the debug window bitmap object.
            DebugWindow?.Shutdown();
            DebugWindow = null;
            // Release the text object.
            Text?.Shutdown();
            Text = null;
            // Release the cpu object.
            CPU?.Shutdown();
            CPU = null;
            // Release the terrain shader object.
            TerrainShader?.ShutDown();
            TerrainShader = null;
            // Release the tree object.
            TerrainModel?.ShutDown();
            TerrainModel = null;
            // Release the input object.
            Input?.Shutdown();
            Input = null;
            // Release the Direct3D object.
            D3D?.ShutDown();
            D3D = null;
        }
Exemple #30
0
        public uint off_2C;     // Always 0


        public TerrainFragment(FileStream fs, TerrainHead head, byte[] tfragBlock, int num)
        {
            int offset = num * 0x30;

            off_00 = ReadFloat(tfragBlock, offset + 0x00);
            off_04 = ReadFloat(tfragBlock, offset + 0x04);
            off_08 = ReadFloat(tfragBlock, offset + 0x08);
            off_0C = ReadFloat(tfragBlock, offset + 0x0C);


            off_1C = ReadUshort(tfragBlock, offset + 0x1C);
            off_1E = ReadUshort(tfragBlock, offset + 0x1E);
            off_20 = ReadUshort(tfragBlock, offset + 0x20);

            off_24 = ReadUint(tfragBlock, offset + 0x24);
            off_28 = ReadUint(tfragBlock, offset + 0x28);
            off_2C = ReadUint(tfragBlock, offset + 0x2C);

            model       = new TerrainModel(fs, head, tfragBlock, num);
            modelMatrix = Matrix4.Identity;
        }
Exemple #31
0
    /// <summary>
    /// 根据地图规模,阵营数量和地形字典初始化地图数据
    /// </summary>
    public void InitialMap()
    {
        Map = new Land[MapSize.Height, MapSize.Width];
        if (terrianDic != null)
        {
            terrianDic.Clear();
        }
        //地形表
        Dictionary <int, TerrainModel> terrainModelDic = GameDataSet.Instance.terrainModelDic;
        //地图大小-地形数量表
        Terrain_MapModel             curTerrain_Map       = GameDataSet.Instance.terrain_MapModelDic[MapSize.Height];
        List <Terrain_MapModel.Pair> terrainID_AmountList = curTerrain_Map.terrainID_AmountList;

        foreach (Terrain_MapModel.Pair ID_Amount in terrainID_AmountList)
        {
            int          terrainID = ID_Amount.key;
            TerrainModel model     = terrainModelDic[terrainID];
            terrianDic.Add(new CustomTerrain(model), ID_Amount.value);
            Debug.Log(string.Format("{0}号地形,有{1}个", model.terrainName, ID_Amount.value));
        }
    }
Exemple #32
0
        protected override void LoadContent(GraphicInfo GraphicInfo, GraphicFactory factory, IContentManager contentManager)
        {
            base.LoadContent(GraphicInfo, factory, contentManager);

            TerrainObject         to     = new TerrainObject(factory, "..\\Content\\Textures\\Untitled", Vector3.Zero, Matrix.Identity, MaterialDescription.DefaultBepuMaterial(), 2, 1);
            TerrainModel          stm    = new TerrainModel(factory, to, "TerrainName", "..\\Content\\Textures\\Terraingrass", "..\\Content\\Textures\\rock", "..\\Content\\Textures\\sand", "..\\Content\\Textures\\snow");
            DeferredTerrainShader shader = new DeferredTerrainShader(TerrainType.MULTITEXTURE);
            DeferredMaterial      mat    = new DeferredMaterial(shader);
            IObject obj3 = new IObject(mat, stm, to);

            this.World.AddObject(obj3);

            LightThrowBepu lt = new LightThrowBepu(this.World, factory);

            #region NormalLight
            DirectionalLightPE ld1 = new DirectionalLightPE(Vector3.Left, Color.White);
            DirectionalLightPE ld2 = new DirectionalLightPE(Vector3.Right, Color.White);
            DirectionalLightPE ld3 = new DirectionalLightPE(Vector3.Backward, Color.White);
            DirectionalLightPE ld4 = new DirectionalLightPE(Vector3.Forward, Color.White);
            DirectionalLightPE ld5 = new DirectionalLightPE(Vector3.Down, Color.White);
            float li = 0.5f;
            ld1.LightIntensity = li;
            ld2.LightIntensity = li;
            ld3.LightIntensity = li;
            ld4.LightIntensity = li;
            ld5.LightIntensity = li;
            this.World.AddLight(ld1);
            this.World.AddLight(ld2);
            this.World.AddLight(ld3);
            this.World.AddLight(ld4);
            this.World.AddLight(ld5);
            #endregion

            this.World.CameraManager.AddCamera(new CameraFirstPerson(true, GraphicInfo));

            SkyBoxSetTextureCube stc = new SkyBoxSetTextureCube("Textures//cubemap");
            CommandProcessor.getCommandProcessor().SendCommandAssyncronous(stc);
        }
 /// <summary>
 /// Calculates the texture of the specified model.
 /// </summary>
 /// <param name="model">
 /// The model.
 /// </param>
 /// <param name="mesh">
 /// The mesh.
 /// </param>
 public virtual void Calculate(TerrainModel model, MeshGeometry3D mesh)
 {
 }
        /// <summary>
        /// Updates the model.
        /// </summary>
        private void UpdateModel()
        {
            var r = new TerrainModel();
            r.Load(this.Source);

            // r.Texture = new SlopeDirectionTexture(0);
            r.Texture = new SlopeTexture(8);

            // r.Texture = new MapTexture(@"D:\tmp\CraterLake.png") { Left = r.Left, Right = r.Right, Top = r.Top, Bottom = r.Bottom };
            this.visualChild.Content = r.CreateModel(2);
        }
Exemple #35
0
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            // Overlay component, used to draw the pause menu and game over menu
            overlayComponent = new OverlayComponent(Game, spriteBatch);
            Game.Components.Add(overlayComponent);

            projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4,
                GraphicsDevice.Viewport.AspectRatio, 0.1f, 50000);

            directionalLight = new DirectionalLight(
                new Vector3(-1.25f, -2f, 5.0f), // Direction
                new Vector3(.1f, .1f, .1f),//new Vector3(.15f, .14f, .29f), // Ambient
                new Vector3(.46f, .33f, .75f)); // Diffuse

            Game.AddService(typeof(DirectionalLight), directionalLight);

            #region Level terrain generation

            int heightMapSize = terrainSegmentsCount * terrainSegmentSize + 1;
            float halfHeightMapSize = heightMapSize / 2f;
            HeightMap heightmapGenerator = new HeightMap(heightMapSize);
            var heightMap = heightmapGenerator.Generate();

            var roadMap = new float[heightMapSize, heightMapSize];
            raceTrack = new RaceTrack(heightMapSize, terrainScale);

            navMesh = new NavMesh(GraphicsDevice, raceTrack.Curve, //1500, roadWidth, terrainScale);
                750, roadWidth, terrainScale);

            Vector3 lastPosition = raceTrack.Curve.GetPoint(.01f) / terrainScale;

            for (float t = 0; t < 1; t += .0002f)
            {
                var e = raceTrack.Curve.GetPoint(t) / terrainScale;

                for (float j = -roadFalloff; j <= roadFalloff; j++)
                {
                    var pos = e + j * Vector3.Normalize(Vector3.Cross(lastPosition - e, Vector3.Up));

                    // Indices
                    int x = (int)(pos.X + halfHeightMapSize),
                        z = (int)(pos.Z + halfHeightMapSize);

                    float height = e.Y;

                    if (Math.Abs(j) <= roadWidth)
                    {
                        heightMap[x, z] = height;
                        roadMap[x, z] = 1;
                    }
                    else
                    {
                        float amount = (Math.Abs(j) - roadWidth) / (roadFalloff - roadWidth);
                        heightMap[x, z] = MathHelper.Lerp(height,
                            heightMap[x, z], amount);
                        roadMap[x, z] = amount / 10f;
                    }
                }
                lastPosition = e;
            }

            heightmapGenerator.Smoothen();
            heightmapGenerator.Perturb(30f);

            for (int i = 0; i < 5; i++)
            {
                heightmapGenerator.Smoothen();
            }

            terrainEffect = content.Load<Effect>(@"Effects\TerrainShading");

            //terrainEffect.Parameters["TextureMap0"].SetValue(content.Load<Texture2D>(@"Terrain\sand"));
            #region TEXTURE RENDERING

            //var unprocessedGrassTexture = content.Load<Texture2D>(@"Terrain\grass");
            //var grassTexture = new RenderTarget2D(GraphicsDevice, unprocessedGrassTexture.Width, unprocessedGrassTexture.Height);

            //GraphicsDevice.SetRenderTarget(grassTexture);
            //spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);
            //spriteBatch.Draw(unprocessedGrassTexture, new Rectangle(0, 0, unprocessedGrassTexture.Width, unprocessedGrassTexture.Height), Color.White);
            //spriteBatch.Draw(content.Load<Texture2D>(@"Particles\fire"), new Rectangle(0, 0, unprocessedGrassTexture.Width, unprocessedGrassTexture.Height), Color.White);
            //spriteBatch.End();
            //GraphicsDevice.SetRenderTarget(null);

            //terrainEffect.Parameters["TextureMap1"].SetValue(grassTexture);

            #endregion
            terrainEffect.Parameters["TextureMap0"].SetValue(content.Load<Texture2D>(@"Terrain\road"));
            terrainEffect.Parameters["TextureMap1"].SetValue(content.Load<Texture2D>(@"Terrain\grass"));
            terrainEffect.Parameters["TextureMap2"].SetValue(content.Load<Texture2D>(@"Terrain\rock"));
            terrainEffect.Parameters["TextureMap3"].SetValue(content.Load<Texture2D>(@"Terrain\snow"));
            terrainEffect.Parameters["RoadNormalMap"].SetValue(content.Load<Texture2D>(@"Terrain\road_n"));
            terrainEffect.Parameters["Projection"].SetValue(projectionMatrix);

            // Creates a terrainmodel around Vector3.Zero
            terrainSegments = new TerrainModel[terrainSegmentsCount, terrainSegmentsCount];

            float terrainStart = -.5f * heightMapSize;

            for (int z = 0; z < terrainSegmentsCount; z++)
            {
                for (int x = 0; x < terrainSegmentsCount; x++)
                {
                    terrainSegments[x, z] = new TerrainModel(GraphicsDevice,
                        terrainSegmentSize, terrainSegmentsCount, terrainStart,
                        x * terrainSegmentSize, z * terrainSegmentSize,
                        terrainScale, heightMap, roadMap, terrainEffect, directionalLight);
                }
            }

            #endregion

            #region Car

            Car = MakeCar();
            gameInstance.AddService(typeof(Car), Car);
            Player localPlayer = gameInstance.GetService<ServerClient>().LocalPlayer;
            gameInstance.GetService<CarControlComponent>().Cars[localPlayer] = Car;
            gameInstance.AddService(typeof(Player), localPlayer);

            #endregion

            #region Lights

            // Load model to represent our lightsources
            var pointLightModel = content.Load<Model>(@"Models\light");

            //spotLightModel = content.Load<Model>(@"Models\Cone");

            Vector3 pointLightOffset = new Vector3(0, 250, 0);

            var cr = new CurveRasterization(raceTrack.Curve, 50);

            float colorOffset = 0f;

            foreach (var point in cr.Points)
            {
                Random r = UniversalRandom.GetInstance();

                Vector3 color = new Vector3(0f,0f,0f);
                PointLight pl = new PointLight(point.Position + pointLightOffset +
                    Vector3.Transform(50 * Vector3.Up, Matrix.CreateRotationZ(MathHelper.TwoPi * (float)UniversalRandom.GetInstance().NextDouble())),
                    color, 450)
                {
                    Model = pointLightModel,
                    ColorTimeOffset = colorOffset
                };

                pointLights.Add(pl);
                GraphicalObjects.Add(pl);

                colorOffset += 100 / cr.Points.Count;
            }

            #endregion

            dustEmitter = new ParticleEmitter(dustSystem, 150, Car.Position);

            #region SkySphere

            skyBoxModel = content.Load<Model>(@"Models/skybox");
            skyBoxEffect = content.Load<Effect>(@"Effects/SkyBox");

            skyMap = new TextureCube(GraphicsDevice, 2048, false, SurfaceFormat.Color);
            string[] cubemapfaces = { @"SkyBoxes/PurpleSky/skybox_right1",
                @"SkyBoxes/PurpleSky/skybox_left2",
                @"SkyBoxes/PurpleSky/skybox_top3",
                @"SkyBoxes/PurpleSky/skybox_bottom4",
                @"SkyBoxes/PurpleSky/skybox_front5",
                @"SkyBoxes/PurpleSky/skybox_back6_2"
            };

            //cubeMap = new TextureCube(GraphicsDevice, 1024, false, SurfaceFormat.Color);
            //string[] cubemapfaces = {
            //    @"SkyBoxes/StormyDays/stormydays_ft",
            //    @"SkyBoxes/StormyDays/stormydays_bk",
            //    @"SkyBoxes/StormyDays/stormydays_up",
            //    @"SkyBoxes/StormyDays/stormydays_dn",
            //    @"SkyBoxes/StormyDays/stormydays_rt",
            //    @"SkyBoxes/StormyDays/stormydays_lf"
            //};

            //cubeMap = new TextureCube(GraphicsDevice, 1024, false, SurfaceFormat.Color);
            //string[] cubemapfaces = {
            //    @"SkyBoxes/Miramar/miramar_ft",
            //    @"SkyBoxes/Miramar/miramar_bk",
            //    @"SkyBoxes/Miramar/miramar_up",
            //    @"SkyBoxes/Miramar/miramar_dn",
            //    @"SkyBoxes/Miramar/miramar_rt",
            //    @"SkyBoxes/Miramar/miramar_lf"
            //};

            for (int i = 0; i < cubemapfaces.Length; i++)
                LoadCubemapFace(skyMap, cubemapfaces[i], (CubeMapFace)i);

            skyBoxEffect.Parameters["SkyboxTexture"].SetValue(skyMap);

            foreach (var mesh in skyBoxModel.Meshes)
                foreach (var part in mesh.MeshParts)
                    part.Effect = skyBoxEffect;

            #endregion

            #region Weather

            thunderBoltGenerator = new ThunderBoltGenerator(gameInstance, thunderParticleSystem);
            gameInstance.Components.Add(thunderBoltGenerator);

            #endregion

            #region GameObjects

            OakTree.LoadMaterial(content);
            BirchTree.LoadMaterial(content);
            Stone.LoadMaterial(content);

            int numObjects = 75;

            for (int i = 0; i < numObjects; i++)
            {

                var t = navMesh.triangles[UniversalRandom.GetInstance().Next(navMesh.triangles.Length)];
                float v = (float)UniversalRandom.GetInstance().NextDouble();

                //float u = (float) (UniversalRandom.GetInstance().NextDouble() - 1/2f);
                //if (u < 0)
                //    u -= .5f;
                //else
                //    u += 1.5f;

                float u = 0;
                if (UniversalRandom.GetInstance().NextDouble() <= .5)
                    u = -.5f - .3f * (float)(-UniversalRandom.GetInstance().NextDouble());
                else
                    u = (float)(1.5f + .3f * UniversalRandom.GetInstance().NextDouble());

                var pos = (t.vertices[0] + u * t.ab + v * t.ac) / terrainScale;
                //var treePos = new Vector3(-halfHeightMapSize + (float)UniversalRandom.GetInstance().NextDouble() * (heightMapSize-50), 0,
                //    -halfHeightMapSize + (float)UniversalRandom.GetInstance().NextDouble() * (heightMapSize-50));

                float X = pos.X + heightMapSize / 2f,
                    Z = pos.Z +heightMapSize / 2f;

                float Xlerp = X % 1f,
                    Zlerp = Z % 1f;

                int x0 = (int)X,
                    z0 = (int)Z,
                    x1 = x0 + 1,
                    z1 = z0 + 1;

                float height;
                float k;
                if (Xlerp + Zlerp > 1)
                {
                    float h1 = MathHelper.Lerp(heightMap[x0, z1], heightMap[x1, z1], Xlerp);
                    float h2 = MathHelper.Lerp(heightMap[x1, z0], heightMap[x1, z1], Zlerp);
                    k = h2 / h1;
                    height = MathHelper.Lerp(h1, h2, .5f);
                }
                else
                {
                    float h1 = MathHelper.Lerp(heightMap[x0, z0], heightMap[x1, z0], Xlerp),
                        h2 = MathHelper.Lerp(heightMap[x0, z0], heightMap[x0, z1], Zlerp);
                    k = h2 / h1;
                    height = MathHelper.Lerp(h1, h2, .5f);
                }
                pos.Y = height - 0.002f;

                if (k > 1.02 ) continue;

                GameObject obj;
                switch(UniversalRandom.GetInstance().Next(0, 3))
                {
                case 0:
                    obj = new OakTree(gameInstance);
                    obj.Scale = 3 + 3 * (float)UniversalRandom.GetInstance().NextDouble();
                    FireflyCandidates.Add(obj);
                    break;
                case 1:
                    obj = new BirchTree(gameInstance);
                    obj.Scale = 3 + 3 * (float)UniversalRandom.GetInstance().NextDouble();
                    FireflyCandidates.Add(obj);
                    break;
                default:
                    obj = new Stone(gameInstance);
                    obj.Scale = 0.5f + (float)(.25 * UniversalRandom.GetInstance().NextDouble());
                    break;
                }

                obj.Position = terrainScale * pos;
                obj.Rotation = new Vector3(0, MathHelper.Lerp(0, MathHelper.Pi * 2, (float)UniversalRandom.GetInstance().NextDouble()), 0);

                GraphicalObjects.Add(obj);
                ShadowCasterObjects.Add(obj);
            }

            for (int i = 0; i < FireflyCandidates.Count; i+=5)
            {
                ParticleEmitter emitter = new ParticleEmitter(fireflySystem, 80, FireflyCandidates[i].Position);
                emitter.Origin = FireflyCandidates[i].Position + Vector3.Up * 500;
                fireflyEmitter.Add(emitter);
            }

            #endregion

            //foreach (GameObject obj in GraphicalObjects)
            //{
            //    pointLights.Add(new PointLight(obj.Position + Vector3.Up * 500, new Vector3(0.7f, 0.7f, 0.7f), 450)
            //    {
            //        Model = pointLightModel
            //    });
            //}
            //GraphicalObjects.AddRange(pointLights);

            //List<FireObject> list = new List<FireObject>();
            //foreach (PointLight p in pointLights)
            //{
            //    FireObject obj = new FireObject(gameInstance, content, p.Position, p.Position + Vector3.Up * 10);
            //    list.Add(obj);

            //}
            //pointLights.AddRange(list);
            //GraphicalObjects.AddRange(list);

            #region Cameras

            var input = gameInstance.GetService<InputComponent>();

            gameInstance.GetService<CameraComponent>().AddCamera(new DebugCamera(new Vector3(-11800, 3000, -8200), input));
            Camera c;
            gameInstance.GetService<CameraComponent>().AddCamera(c = new ThirdPersonCamera(Car, input));
            gameInstance.GetService<CameraComponent>().CurrentCamera = c;

            #endregion

            #region DynamicEnvironment

            // TODO: CARMOVE
            environmentCubeMap = new RenderTargetCube(this.GraphicsDevice, 256, true, SurfaceFormat.Color, DepthFormat.Depth16);
            Car.EnvironmentMap = skyMap;

            #endregion

            #region PostProcess

            postProcessingComponent = new PostProcessingComponent(Game);
            Game.Components.Add(postProcessingComponent);

            postProcessTexture = new RenderTarget2D(GraphicsDevice,
                GraphicsDevice.Viewport.Width,
                GraphicsDevice.Viewport.Height,
                true, SurfaceFormat.Color, DepthFormat.Depth24);

            #endregion

            // Adding a prelighingrenderer as a service
            prelightingRenderer = new PrelightingRenderer(GraphicsDevice, content);
            Game.AddService(typeof(PrelightingRenderer), prelightingRenderer);

            #region ShadowMapEffect

            shadowMapEffect = content.Load<Effect>(@"Effects\ShadowMap");

            #endregion

            #region Gameplay Trigger Manager (with sample)

            /// <summary>
            /// Gets the triggermanager
            /// Add new PositionTrigger
            /// Hook up to listener => when hit, use the thunderBoltGenerator and spawn a flash
            /// Adds it to triggers.
            /// </summary>

            //var triggerManager = gameInstance.GetService<TriggerManager>();

            //int noOfCheckpoints = 10;
            //for (int i = 0; i < noOfCheckpoints; i++)
            //{
            //    var trigger = new PositionTrigger(raceTrack.CurveRasterization, (int)(((float)i / noOfCheckpoints) * raceTrack.CurveRasterization.Points.Count), true, true);
            //    string cp = "Checkpoint " + i;
            //    trigger.Triggered += (sender, e) =>
            //    {
            //        Console.WriteLine(cp);
            //    };
            //    triggerManager.Triggers.Add("checkpoint"+i, trigger);
            //}

            #endregion

            #region Game Mode
            if (gameInstance.GetService<ServerClient>().connected)
            {
                foreach (var player in gameInstance.GetService<ServerClient>().Players.Values)
                {
                    gameInstance.GetService<CarControlComponent>().AddCar(player, null, this);
                }
                var carList = gameInstance.GetService<CarControlComponent>().Cars.OrderBy(pc => pc.Key.ID).Select(pc => pc.Value).ToList();
                SetCarsAtStart(carList);
            }

            int cp = 6;
            if (gameModeChoice == GameModeChoice.SimpleRace)
                this.mode = new SimpleRaceMode(gameInstance, 3, cp, raceTrack, Car);
            else if (gameModeChoice == GameModeChoice.Multiplayer)
                this.mode = new MultiplayerRaceMode(gameInstance, 3, cp, raceTrack, Car);
            else
                throw new Exception("Stop choosing weird game modes");

            gameInstance.AddService(typeof(GameplayMode), mode);

            #endregion

            #region Checkpoint lights
            for (int i=0; i<cp; i++) {
                var point = raceTrack.GetCurveRasterization(cp).Points[i];

                var pl = new CheckpointLight(point.Position + 500 * Vector3.Up)
                {
                    Model = pointLightModel
                };
                pointLights.Add(pl);
                GraphicalObjects.Add(pl);

                #region Fire
                int halfnumberoffire = 5;

                for (int o = -halfnumberoffire + 1; o < halfnumberoffire; o++)
                {
                    Vector3 side = Vector3.Cross(Vector3.Normalize(raceTrack.Curve.GetPoint((i) / (float)cp + .001f) - point.Position), Vector3.Up);

                    var fire = new FireObject(content, fireSystem, fireSmokeSystem, point.Position + side * 100 * o -
                        Vector3.Up * 400 +
                        Vector3.Up * 650 * (float)Math.Cos(o/(float)halfnumberoffire), Vector3.Up * 10);
                    pointLights.Add(fire);
                    GraphicalObjects.Add(fire);
                }
                #endregion
            }
            #endregion

            #region BackgroundSound
            loopSoundManager.AddNewSound("forestambient");
            #endregion

            prelightingRenderer.GameObjects = GraphicalObjects;

            init = true;
        }