Esempio n. 1
0
        //  Draw muzzle flash not matter if in frustum (it's because it's above the frustum)
        public override bool Draw(MyRenderObject renderObject)
        {
            if (base.Draw(renderObject) == false)
            {
                return(false);
            }

            m_barrel.Draw();

            if (MyMinerGame.IsPaused())
            {
                return(false);
            }

            //  Draw muzzle flash
            int deltaTime = MyMinerGame.TotalGamePlayTimeInMilliseconds - m_lastTimeShoot;

            if (deltaTime <= MyMachineGunConstants.MUZZLE_FLASH_MACHINE_GUN_LIFESPAN)
            {
                MyParticleEffects.GenerateMuzzleFlash(m_positionMuzzleInWorldSpace, WorldMatrix.Forward, m_muzzleFlashRadius, m_muzzleFlashLength, MyRender.GetCurrentLodDrawPass() == MyLodTypeEnum.LOD_NEAR);
            }

            if (m_smokeEffect != null)
            {
                m_smokeEffect.Near = MyRender.GetCurrentLodDrawPass() == MyLodTypeEnum.LOD_NEAR;
            }

            return(true);
        }
Esempio n. 2
0
 private static void TryPause()
 {
     if (!MyMinerGame.IsPaused() && MyGuiScreenGamePlay.Static != null)
     {
         MyMinerGame.SwitchPause();
     }
 }
Esempio n. 3
0
        /// <summary>
        /// Render method is called directly by renderer. Depending on stage, post process can do various things
        /// </summary>
        /// <param name="postProcessStage">Stage indicating in which part renderer currently is.</param>public override void RenderAfterBlendLights()
        public override Texture Render(PostProcessStage postProcessStage, Texture source, Texture availableRenderTarget)
        {
            switch (postProcessStage)
            {
            case PostProcessStage.HDR:
            {
                MyMinerGame.SetRenderTarget(availableRenderTarget, null);
                MyEffectContrast effectContrast = MyRender.GetEffect(MyEffects.Contrast) as MyEffectContrast;


                effectContrast.SetDiffuseTexture(source);
                effectContrast.SetHalfPixel(MyUtils.GetHalfPixel(source.GetLevelDescription(0).Width, source.GetLevelDescription(0).Height));
                effectContrast.SetContrast(Contrast);
                effectContrast.SetHue(Hue);
                effectContrast.SetSaturation(Saturation);

                MyGuiManager.GetFullscreenQuad().Draw(effectContrast);

                return(availableRenderTarget);
            }
            break;
            }

            return(source);
        }
        public static void UpdateScreenSize()
        {
            MyMwcLog.WriteLine("MyVideoModeManager.UpdateScreenSize - START");
            MyMwcLog.IncreaseIndent();

            //  Update or reload everything that depends on screen resolution
            MyMinerGame.UpdateScreenSize();
            MyGuiManager.UpdateScreenSize();
            MyGuiManager.RecreateMainMenuControls();


            MyCamera.UpdateScreenSize();
            MyHud.UpdateScreenSize();
            MySunGlare.UpdateScreenSize();

            if (MyGuiScreenGamePlay.Static != null)
            {
                MyGuiScreenGamePlay.Static.UpdateScreenSize();
            }

            CenterizeWindowPosition();

            /*
             * MyRender.CreateRenderTargets();
             * MyRender.CreateEnvironmentMapsRT(MyRenderConstants.ENVIRONMENT_MAP_SIZE);
             */
            MyMwcLog.DecreaseIndent();
            MyMwcLog.WriteLine("MyVideoModeManager.UpdateScreenSize - END");
        }
        /// <summary>
        /// Render method is called directly by renderer. Depending on stage, post process can do various things
        /// </summary>
        /// <param name="postProcessStage">Stage indicating in which part renderer currently is.</param>public override void RenderAfterBlendLights()
        public override Texture Render(PostProcessStage postProcessStage, Texture source, Texture availableRenderTarget)
        {
            switch (postProcessStage)
            {
            case PostProcessStage.AlphaBlended:
            {
                BlendState.Opaque.Apply();
                DepthStencilState.None.Apply();
                RasterizerState.CullCounterClockwise.Apply();

                MyMinerGame.SetRenderTarget(availableRenderTarget, null);

                MyEffectAntiAlias effectAntiAlias = MyRender.GetEffect(MyEffects.AntiAlias) as MyEffectAntiAlias;
                effectAntiAlias.SetDiffuseTexture(source);
                effectAntiAlias.SetHalfPixel(source.GetLevelDescription(0).Width, source.GetLevelDescription(0).Height);

                if (MyMwcFinalBuildConstants.EnableFxaa && MyRenderConstants.RenderQualityProfile.EnableFXAA)
                {
                    effectAntiAlias.ApplyFxaa();
                }
                else
                {
                    return(source);        // Nothing to do, return source
                }
                MyGuiManager.GetFullscreenQuad().Draw(effectAntiAlias);
                return(availableRenderTarget);
            }
            break;
            }
            return(source);
        }
        private void Blur(Texture sourceAndDestination, Texture aux, MyEffectGaussianBlur effect, float verticalBlurAmount, float horizontalBlurAmount)
        {
            effect.SetHalfPixel(sourceAndDestination.GetLevelDescription(0).Width, sourceAndDestination.GetLevelDescription(0).Height);

            int numberOfBlurPasses = Convert.ToInt32(Math.Floor(NumberOfBlurPasses));

            for (int i = 0; i < numberOfBlurPasses; i++)
            {
                // Apply vertical gaussian blur
                MyMinerGame.SetRenderTarget(aux, null);
                effect.BlurAmount = verticalBlurAmount;
                effect.SetSourceTexture(sourceAndDestination);
                //effect.SetWidthForHorisontalPass(sourceAndDestination.Width);
                effect.SetHeightForVerticalPass(sourceAndDestination.GetLevelDescription(0).Height);
                MyGuiManager.GetFullscreenQuad().Draw(effect);

                // Apply horizontal gaussian blur
                MyMinerGame.SetRenderTarget(sourceAndDestination, null);
                effect.BlurAmount = horizontalBlurAmount;
                effect.SetSourceTexture(aux);
                //effect.SetHeightForVerticalPass(sourceAndDestination.Height);
                effect.SetWidthForHorisontalPass(aux.GetLevelDescription(0).Width);
                MyGuiManager.GetFullscreenQuad().Draw(effect);
            }
        }
        protected void PostProcess(Texture source, Texture destination, MyEffectHDRBase effect)
        {
            MyMinerGame.SetRenderTarget(destination, null);

            effect.SetHalfPixel(source.GetLevelDescription(0).Width, source.GetLevelDescription(0).Height);
            effect.SetSourceTextureMod(source);

            MyGuiManager.GetFullscreenQuad().Draw(effect);
        }
        /// <summary>
        /// Renders a list of models to the shadow map, and returns a surface
        /// containing the shadow occlusion factor
        /// </summary>
        public void Render()
        {
            int shadowBlock = -1;

            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartProfilingBlock("MyShadowRenderer::Render", ref shadowBlock);

            if (MultiThreaded)
            {
                WaitUntilPrepareForDrawCompleted();
            }
            else
            {
                //PrepareFrame();
                PrepareCascadesForDraw();
            }

            IssueQueriesForCascades();

            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartProfilingBlock("Set & Clear RT");

            // Set our targets
            MyMinerGame.SetRenderTarget(MyRender.GetRenderTarget(m_shadowRenderTarget), MyRender.GetRenderTarget(m_shadowDepthTarget));
            //MyMinerGameDX.Static.GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.White, 1.0f, 0);
            MyMinerGame.Static.GraphicsDevice.Clear(ClearFlags.ZBuffer, new ColorBGRA(1.0f), 1.0f, 0);

            DepthStencilState.Default.Apply();
            RasterizerState.CullCounterClockwise.Apply();
            BlendState.Opaque.Apply();

            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock();

            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartProfilingBlock("Render 4 ShadowMaps");

            // Render our scene geometry to each split of the cascade
            for (int i = 0; i < NumSplits; i++)
            {
                if (m_skip[i])
                {
                    continue;
                }
                if (!m_visibility[i])
                {
                    continue;
                }

                RenderShadowMap(i);
                //IssueQueriesForShadowMap(i);
            }

            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock();

            //   MyGuiManager.TakeScreenshot();
            MyRender.TakeScreenshot("ShadowMap", MyRender.GetRenderTarget(m_shadowRenderTarget), MyEffectScreenshot.ScreenshotTechniqueEnum.Color);

            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock(shadowBlock);
        }
Esempio n. 9
0
 public override void ChangeValueDown()
 {
     System.Diagnostics.Debug.Assert(!MyMinerGame.IsPaused());
     if (MyMinerGame.TotalGamePlayTimeInMilliseconds > m_lastTimeChanged + m_minChangeThreshold)
     {
         m_value = !m_value;
         base.ChangeValueDown();
         m_lastTimeChanged = MyMinerGame.TotalGamePlayTimeInMilliseconds;
     }
 }
Esempio n. 10
0
        public void Run(ServiceContainer services)
        {
            //MyMinerGame.OnGameInit += new OnInitEvent(Initialize);
            //MyMinerGame.OnGameUpdate += new OnDrawEvent(Update);
            //MyMinerGame.OnGameDraw += new OnDrawEvent(Draw);
            MyGuiScreenGamePlay.OnGameLoaded += new EventHandler(GameLoaded);
            MyParticlesManager.OnDraw        += new EventHandler(EffectsDraw);

            Static = new MyMinerGame(services);
            Static.Run();
        }
Esempio n. 11
0
        protected override void OnClosed()
        {
            if (MyGuiScreenGamePlay.Static != null)
            {
                MyGuiScreenGamePlay.Static.DrawHud = true;
            }

            MyMinerGame.SetPause(m_wasPause);

            base.OnClosed();
        }
        public void PrepareForDraw(MyEffectDistantImpostors effect)
        {
            RasterizerState.CullClockwise.Apply();
            BlendState.Opaque.Apply();
            MyMinerGame.SetRenderTarget(MyRender.GetRenderTarget(MyRenderTargets.AuxiliaryHalf0), null);

            foreach (MyVoxelMapImpostorGroup group in m_voxelMapImpostorGroups)
            {
                group.PrepareForDraw(effect);
            }
        }
Esempio n. 13
0
        /// <summary>
        /// Downscales the source to 1/4th size, using mipmaps
        /// !! IMPORTANT !! you cannot just switch function call. Also changing RTs is necessary.
        /// </summary>
        protected void GenerateDownscale4(Texture sourceMod, Texture sourceDiv, Texture destination, MyEffectScale effect)
        {
            effect.SetTechnique(MyEffectScale.Technique.Downscale4);

            MyMinerGame.SetRenderTarget(destination, null);

            effect.SetSourceTextureMod(sourceMod);
            effect.SetSourceTextureDiv(sourceDiv);
            //effect.SetLumTexture(currentFrameAdaptedLuminance);
            effect.SetHalfPixel(sourceMod.GetLevelDescription(0).Width, sourceMod.GetLevelDescription(0).Height);

            MyGuiManager.GetFullscreenQuad().Draw(effect);
        }
Esempio n. 14
0
        private void BlitToThumbnail(Device device, Texture renderTarget)
        {
            MyMinerGame.SetRenderTarget(renderTarget, null);
            var screenEffect = MyRender.GetEffect(MyEffects.Scale) as MyEffectScale;

            Debug.Assert(screenEffect != null);
            screenEffect.SetTechnique(MyEffectScale.Technique.HWScalePrefabPreviews);
            screenEffect.SetSourceTextureMod(m_fullSizeRT);
            //screenEffect.SetScale(2f * new Vector2(renderTarget.Width / (float)m_fullSizeRT.Width, renderTarget.Height / (float)m_fullSizeRT.Height));
            screenEffect.SetScale(2f * new Vector2((renderTarget.GetLevelDescription(0).Width - 1) / (float)m_fullSizeRT.GetLevelDescription(0).Width, (renderTarget.GetLevelDescription(0).Height - 1) / (float)m_fullSizeRT.GetLevelDescription(0).Height));
            MyGuiManager.GetFullscreenQuad().Draw(screenEffect);
            MyMinerGame.SetRenderTarget(null, null);
        }
Esempio n. 15
0
        private void GenerateThreshold(Texture sourceMod, Texture sourceDiv, Texture[] destination, MyEffectThreshold effect, float threshold, float bloomIntensity, float bloomIntensityBackground, float exposure)
        {
            MyMinerGame.SetRenderTargets(destination, null);

            effect.SetSourceTextureMod(sourceMod);
            effect.SetSourceTextureDiv(sourceDiv);
            //effect.SetLumTexture(currentFrameAdaptedLuminance);
            effect.SetHalfPixel(sourceMod.GetLevelDescription(0).Width, sourceMod.GetLevelDescription(0).Height);
            effect.SetThreshold(threshold);
            effect.SetBloomIntensity(bloomIntensity);
            effect.SetBloomIntensityBackground(bloomIntensityBackground);
            effect.SetExposure(exposure);

            MyGuiManager.GetFullscreenQuad().Draw(effect);
        }
Esempio n. 16
0
        private void DrawControls()
        {
            //  Then draw all screen controls, except opened combobox and drag and drop - must be drawn as last
            // foreach (MyGuiControlBase control in Controls.GetVisibleControls())  //dont use this - allocations
            List <MyGuiControlBase> visibleControls = Controls.GetVisibleControls();

            for (int i = 0; i < visibleControls.Count; i++)
            {
                MyGuiControlBase control = visibleControls[i];
                if (control != m_comboboxHandlingNow && control != m_listboxDragAndDropHandlingNow)
                {
                    if (MyMinerGame.IsPaused() && !control.DrawWhilePaused)
                    {
                        continue;
                    }
                    control.Draw();
                }
            }

            //  Finaly draw opened combobox and dragAndDrop, so it will overdraw all other controls

            if (m_comboboxHandlingNow != null)
            {
                m_comboboxHandlingNow.Draw();
            }

            if (m_listboxDragAndDropHandlingNow != null)
            {
                m_listboxDragAndDropHandlingNow.Draw();
            }

            // draw tooltips only when screen has focus
            if (this == MyGuiManager.GetScreenWithFocus())
            {
                //  Draw tooltips
                for (int i = 0; i < m_controlsVisible.Count; i++)
                {
                    MyGuiControlBase control = m_controlsVisible[i];
                    control.ShowToolTip();
                    if (MyFakes.CONTROLS_MOVE_ENABLED && MyGuiManager.GetInput().IsKeyPress(Keys.M))
                    {
                        DrawControlDebugPosition(control);
                    }
                }
            }
        }
        public void RenderForLight(Matrix lightViewProjection, ref BoundingBox lightBoundingBox, Texture shadowRenderTarget, Texture shadowDepth, int spotIndex)
        {
            m_renderElementsForShadows.Clear();
            m_castingRenderObjectsUnique.Clear();

            m_spotFrustum.Matrix = lightViewProjection;

            //MyRender.GetEntitiesFromPrunningStructure(ref lightBoundingBox, m_castingRenderObjects);
            MyRender.GetEntitiesFromShadowStructure(ref lightBoundingBox, m_castingRenderObjects);

            foreach (MyElement element in m_castingRenderObjects)
            {
                MyRenderObject renderObject = (MyRenderObject)element;
                MyEntity       entity       = ((MyRenderObject)element).Entity;

                if (entity != null)
                {
                    if (entity is MyVoxelMap)
                    {
                        // Changed m_castersBox to lightBoundingBox, should work
                        //(entity as MyVoxelMap).GetRenderElementsForShadowmap(m_renderElementsForShadows, ref lightBoundingBox, m_spotFrustum, MyLodTypeEnum.LOD0, false);
                        (entity as MyVoxelMap).GetRenderElementsForShadowmap(m_renderElementsForShadows, renderObject.RenderCellCoord.Value, MyLodTypeEnum.LOD0, false);
                    }
                    else
                    {
                        if (entity.ModelLod0 != null)
                        {
                            MyRender.CollectRenderElementsForShadowmap(m_renderElementsForShadows, m_transparentRenderElementsForShadows, entity, entity.ModelLod0);
                        }
                    }
                }
            }

            // Set our targets
            MyMinerGame.SetRenderTarget(shadowRenderTarget, shadowDepth);
            MyMinerGame.Static.GraphicsDevice.Clear(ClearFlags.All, new ColorBGRA(1.0f), 1.0f, 0);

            DepthStencilState.Default.Apply();
            RasterizerState.CullNone.Apply();
            BlendState.Opaque.Apply();

            RenderShadowMap(lightViewProjection);

            MyRender.TakeScreenshot("ShadowMapSpot", shadowRenderTarget, MyEffectScreenshot.ScreenshotTechniqueEnum.Color);
        }
Esempio n. 18
0
        public void UpdateAmbient(int index)
        {
            CubeMapFace face        = (CubeMapFace)index;
            Surface     cubeSurface = m_ambientRT.GetCubeMapSurface(face, 0);

            MyMinerGame.Static.GraphicsDevice.SetRenderTarget(0, cubeSurface);
            BlendState.Opaque.Apply();

            MyEffectAmbientPrecalculation precalc = MyRender.GetEffect(MyEffects.AmbientMapPrecalculation) as MyEffectAmbientPrecalculation;

            precalc.SetEnvironmentMap(this.m_environmentRT);
            precalc.SetFaceMatrix(CreateViewMatrix(face, Vector3.Zero));
            precalc.SetRandomTexture(MyRender.GetRandomTexture());
            precalc.SetIterationCount(14);
            precalc.SetMainVectorWeight(1.0f);
            precalc.SetBacklightColorAndIntensity(new Vector3(MyRender.Sun.BackColor.X, MyRender.Sun.BackColor.Y, MyRender.Sun.BackColor.Z), MyRender.Sun.BackIntensity);
            MyGuiManager.GetFullscreenQuad().Draw(precalc);

            MyMinerGame.SetRenderTarget(null, null);
            cubeSurface.Dispose();
        }
        void ValidateAllMissionsStartingFrom(int index)
        {
            var allMissions = MyMissions.Missions.Values.OfType <MyMission>().ToList();

            if (index >= allMissions.Count)
            {
                return;
            }

            var         mission   = allMissions[index];
            MyMissionID missionId = mission.ID;

            // each mission is automatically validated after start
            MyGuiManager.CloseAllScreensExcept(MyGuiScreenGamePlay.Static);

            var startSessionScreen = new MyGuiScreenStartSessionProgress(MyMwcStartSessionRequestTypeEnum.NEW_STORY,
                                                                         MyTextsWrapperEnum.StartGameInProgressPleaseWait, null, MyGameplayDifficultyEnum.EASY, null, null);

            startSessionScreen.OnSuccessEnter = new Action <MyGuiScreenGamePlayType, MyMwcStartSessionRequestTypeEnum, MyMwcObjectBuilder_Checkpoint>((screenType, sessionType, checkpoint) =>
            {
                Action <MyMwcObjectBuilder_Sector, Vector3> enterSuccessAction = new Action <MyMwcObjectBuilder_Sector, Vector3>((sector, newPosition) =>
                {
                    MyMwcVector3Int sectorPosition;
                    sectorPosition = sector.Position;

                    MyMwcSectorIdentifier newSectorIdentifier = new MyMwcSectorIdentifier(MyMwcSectorTypeEnum.STORY, MyClientServer.LoggedPlayer.GetUserId(), sectorPosition, null);
                    var newScreen          = new MyGuiScreenGamePlay(MyGuiScreenGamePlayType.GAME_STORY, null, newSectorIdentifier, sector.Version, MyMwcStartSessionRequestTypeEnum.LOAD_CHECKPOINT);
                    var loadScreen         = new MyGuiScreenLoading(newScreen, MyGuiScreenGamePlay.Static);
                    newScreen.OnGameReady += new ScreenHandler((screen) =>
                    {
                        ((MyMission)MyMissions.GetMissionByID(missionId)).Accept();
                        ValidateAllMissionsStartingFrom(index + 1);  // validate the next mission
                    });

                    loadScreen.AnnounceLeaveToServer = true;
                    loadScreen.LeaveSectorReason     = MyMwcLeaveSectorReasonEnum.TRAVEL;

                    // Current sector and sector object builder has changed
                    checkpoint.ActiveMissionID = -1;          // Manually deactivate mission
                    checkpoint.PlayerObjectBuilder.ShipObjectBuilder.PositionAndOrientation.Position = newPosition;
                    checkpoint.EventLogObjectBuilder.Clear(); // Or just clear mission start/finish

                    // Make prereq missions completed
                    foreach (var prereq in mission.RequiredMissions)
                    {
                        var start = new MyEventLogEntry()
                        {
                            EventType = EventTypeEnum.MissionStarted, EventTypeID = (int)prereq
                        }.GetObjectBuilder();
                        var end = new MyEventLogEntry()
                        {
                            EventType = EventTypeEnum.MissionFinished, EventTypeID = (int)prereq
                        }.GetObjectBuilder();
                        checkpoint.EventLogObjectBuilder.Add(start);
                        checkpoint.EventLogObjectBuilder.Add(end);
                    }

                    checkpoint.SectorObjectBuilder    = sector;
                    checkpoint.CurrentSector.Position = sector.Position;
                    loadScreen.AddEnterSectorResponse(checkpoint, missionId);

                    MyGuiManager.AddScreen(loadScreen);

                    if (MyMinerGame.IsPaused())
                    {
                        MyMinerGame.SwitchPause();
                    }
                });

                //  Load neighbouring sector
                MyGuiManager.AddScreen(new MyGuiScreenEnterSectorProgress(MyMwcTravelTypeEnum.SOLAR, mission.Location.Sector, Vector3.Zero, enterSuccessAction));

                //var newGameplayScreen = new MyGuiScreenGamePlay(screenType, null, checkpoint.CurrentSector, sessionType);
                //var loadScreen = new MyGuiScreenLoading(newGameplayScreen, MyGuiScreenGamePlay.Static);

                //loadScreen.AddEnterSectorResponse(checkpoint);
                //MyGuiManager.AddScreen(loadScreen);
            });

            MyGuiManager.AddScreen(startSessionScreen);
        }
Esempio n. 20
0
        public static void Update()
        {
            if (CurrentSentence == null)
            {
                return;
            }

            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartProfilingBlock("MyDialogues.Update");

            if ((m_currentCue == null && MyMinerGame.TotalGamePlayTimeInMilliseconds - CurrentSentenceStarted_ms > CurrentSentence.SentenceTime_ms) ||
                (m_currentCue != null && (!m_currentCue.Value.IsValid || m_currentCue.Value.IsStopped))
                )
            {
                // advance to next sentence or unload
                m_currentSentenceIndex++;
                if (m_currentDialogueId != MyDialogueEnum.NONE && m_currentSentenceIndex == CurrentDialogue.Sentences.Length)
                {
                    if (OnDialogueFinished != null)
                    {
                        OnDialogueFinished(m_currentDialogueId, false);
                    }
                }

                PlayCurrentSentence();
            }

            if (m_currentCue != null && CurrentSentence.PauseBefore_ms != 0 && m_currentCue.Value.IsValid && m_currentCue.Value.IsPaused && MyMinerGame.TotalGamePlayTimeInMilliseconds - CurrentSentenceStarted_ms > CurrentSentence.PauseBefore_ms && !MyMinerGame.IsPaused())
            {
                m_currentCue.Value.Resume();
            }

            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock();
        }
Esempio n. 21
0
        public MyGuiScreenHelp()
            : base(new Vector2(0.5f, 0.5f), MyGuiConstants.SCREEN_BACKGROUND_COLOR, new Vector2(1f, 0.98f))
        {
            m_enableBackgroundFade = true;

            AddCaption(MyTextsWrapperEnum.HelpCaption, captionScale: 1.35f);

            if (MyGuiScreenGamePlay.Static != null)
            {
                MyGuiScreenGamePlay.Static.DrawHud = false;
            }

            List <ControlWithDescription> left  = new List <ControlWithDescription>();
            List <ControlWithDescription> right = new List <ControlWithDescription>();

//            left.Add(new ControlWithDescription(MyGameControlEnums.FORWARD, MyGameControlEnums.REVERSE));
//            left.Add(new ControlWithDescription(MyGameControlEnums.STRAFE_LEFT, MyGameControlEnums.STRAFE_RIGHT));
//            left.Add(new ControlWithDescription(MyGameControlEnums.UP_THRUST, MyGameControlEnums.DOWN_THRUST));
//            left.Add(new ControlWithDescription(MyGameControlEnums.ROLL_LEFT, MyGameControlEnums.ROLL_RIGHT));
            left.Add(new ControlWithDescription(MyGameControlEnums.FORWARD));
            left.Add(new ControlWithDescription(MyGameControlEnums.REVERSE));
            left.Add(new ControlWithDescription(MyGameControlEnums.STRAFE_LEFT));
            left.Add(new ControlWithDescription(MyGameControlEnums.STRAFE_RIGHT));
            left.Add(new ControlWithDescription(MyGameControlEnums.UP_THRUST));
            left.Add(new ControlWithDescription(MyGameControlEnums.DOWN_THRUST));
            left.Add(new ControlWithDescription(MyGameControlEnums.ROLL_LEFT));
            left.Add(new ControlWithDescription(MyGameControlEnums.ROLL_RIGHT));
            left.Add(new ControlWithDescription(MyGameControlEnums.AFTERBURNER));
            left.Add(new ControlWithDescription(MyGameControlEnums.MOVEMENT_SLOWDOWN));
            left.Add(new ControlWithDescription(MyGameControlEnums.AUTO_LEVEL));

            left.Add(new ControlWithDescription("", ""));

            left.Add(new ControlWithDescription(
                         new StringBuilder().
                         Append(MyGuiManager.GetInput().GetGameControlTextEnum(MyGameControlEnums.FIRE_PRIMARY)).
                         Append(", ").
                         Append(MyGuiManager.GetInput().GetGameControl(MyGameControlEnums.FIRE_PRIMARY).GetControlButtonName(MyGuiInputDeviceEnum.Mouse)),
                         MyGameControlEnums.FIRE_PRIMARY
                         ));
            left.Add(new ControlWithDescription(
                         new StringBuilder().
                         Append(MyGuiManager.GetInput().GetGameControlTextEnum(MyGameControlEnums.FIRE_SECONDARY)).
                         Append(", ").
                         Append(MyGuiManager.GetInput().GetGameControl(MyGameControlEnums.FIRE_SECONDARY).GetControlButtonName(MyGuiInputDeviceEnum.Mouse)),
                         MyGameControlEnums.FIRE_SECONDARY
                         ));
            left.Add(new ControlWithDescription(
                         new StringBuilder().
                         Append(MyGuiManager.GetInput().GetGameControlTextEnum(MyGameControlEnums.SELECT_AMMO_BULLET)).
                         Append(",").
                         Append(MyGuiManager.GetInput().GetGameControlTextEnum(MyGameControlEnums.SELECT_AMMO_MISSILE)).
                         Append(",").
                         Append(MyGuiManager.GetInput().GetGameControlTextEnum(MyGameControlEnums.SELECT_AMMO_CANNON)).
                         Append(",").
                         Append(MyGuiManager.GetInput().GetGameControlTextEnum(MyGameControlEnums.SELECT_AMMO_UNIVERSAL_LAUNCHER_FRONT)).
                         Append(",").
                         Append(MyGuiManager.GetInput().GetGameControlTextEnum(MyGameControlEnums.SELECT_AMMO_UNIVERSAL_LAUNCHER_BACK)),
                         MyTextsWrapper.Get(MyTextsWrapperEnum.SelectAmmo)
                         ));
            left.Add(new ControlWithDescription(MyGameControlEnums.WEAPON_SPECIAL));
            left.Add(new ControlWithDescription(MyGameControlEnums.PREV_TARGET));
            left.Add(new ControlWithDescription(MyGameControlEnums.NEXT_TARGET));

            for (int i = 0; i < specTexts.Length; i++)
            {
                StringBuilder specControl = new StringBuilder();
                if (MyGuiManager.GetInput().GetGameControl(specFront[i]).IsControlAssigned(MyGuiInputDeviceEnum.Keyboard))
                {
                    specControl.Append(MyGuiManager.GetInput().GetGameControlTextEnum(specFront[i]));
                }
                if (MyGuiManager.GetInput().GetGameControl(specBack[i]).IsControlAssigned(MyGuiInputDeviceEnum.Keyboard))
                {
                    if (specControl.Length != 0)
                    {
                        specControl.Append(", ");
                    }
                    specControl.Append(MyGuiManager.GetInput().GetGameControlTextEnum(specBack[i]));
                }
                left.Add(new ControlWithDescription(specControl, MyTextsWrapper.Get(specTexts[i])));
            }

            left.Add(new ControlWithDescription("", ""));

            left.Add(new ControlWithDescription(MyGameControlEnums.USE));
            left.Add(new ControlWithDescription(MyGameControlEnums.GPS));
            //Journal removed
            //left.Add(new ControlWithDescription(MyGameControlEnums.MISSION_DIALOG));
            left.Add(new ControlWithDescription(MyGameControlEnums.INVENTORY));
            left.Add(new ControlWithDescription(MyGameControlEnums.TRAVEL));

            right.Add(new ControlWithDescription(MyGameControlEnums.DRILL));
            right.Add(new ControlWithDescription(MyGameControlEnums.HARVEST));
            right.Add(new ControlWithDescription(MyGameControlEnums.DRONE_DEPLOY));
            right.Add(new ControlWithDescription(MyGameControlEnums.DRONE_CONTROL));
            right.Add(new ControlWithDescription(MyGameControlEnums.CHANGE_DRONE_MODE));
            right.Add(new ControlWithDescription(MyTextsWrapper.Get(MyTextsWrapperEnum.LeftMouseButton), MyTextsWrapper.Get(MyTextsWrapperEnum.DetonateDrone)));
            right.Add(new ControlWithDescription(
                          new StringBuilder().
                          Append(MyGuiManager.GetInput().GetGameControlTextEnum(MyGameControlEnums.PREVIOUS_CAMERA)).
                          Append(", ").
                          Append(MyGuiManager.GetInput().GetGameControlTextEnum(MyGameControlEnums.NEXT_CAMERA)),
                          MyTextsWrapper.Get(MyTextsWrapperEnum.CycleSecondaryCamera)
                          ));
            right.Add(new ControlWithDescription(MyGameControlEnums.CONTROL_SECONDARY_CAMERA));

            right.Add(new ControlWithDescription("", ""));

            right.Add(new ControlWithDescription(MyGameControlEnums.QUICK_ZOOM));
            right.Add(new ControlWithDescription(MyGameControlEnums.ZOOM_IN, MyGameControlEnums.ZOOM_OUT));
            right.Add(new ControlWithDescription(MyGameControlEnums.REAR_CAM));
            right.Add(new ControlWithDescription(MyGameControlEnums.HEADLIGHTS));
            right.Add(new ControlWithDescription(MyGameControlEnums.HEADLIGTHS_DISTANCE));
            right.Add(new ControlWithDescription(MyGameControlEnums.VIEW_MODE));
            right.Add(new ControlWithDescription(MyGameControlEnums.WHEEL_CONTROL));
            right.Add(new ControlWithDescription(MyGameControlEnums.CHAT));
            right.Add(new ControlWithDescription(MyGameControlEnums.SCORE));

            right.Add(new ControlWithDescription("", ""));

            right.Add(new ControlWithDescription(new StringBuilder("F1"), MyTextsWrapper.Get(MyTextsWrapperEnum.OpenHelpScreen)));
            right.Add(new ControlWithDescription(
                          new StringBuilder().
                          Append(MyTextsWrapper.Get(MyTextsWrapperEnum.Ctrl)).
                          Append("+F1"),
                          MyTextsWrapper.Get(MyTextsWrapperEnum.OpenCheats)
                          ));
            right.Add(new ControlWithDescription(new StringBuilder("F4"), MyTextsWrapper.Get(MyTextsWrapperEnum.SaveScreenshotToUserFolder)));

            //These keys are to be used just for developers or testing
            if (!SysUtils.MyMwcFinalBuildConstants.IS_PUBLIC)
            {
                right.Add(new ControlWithDescription("", ""));
                //Programmers
                right.Add(new ControlWithDescription("F6", "Switch to player"));
                right.Add(new ControlWithDescription("F7", "Switch to following 3rd person"));
                right.Add(new ControlWithDescription("F9", "Switch to static 3rd person"));
                right.Add(new ControlWithDescription("F8, Ctrl+F8", "Switch to / reset spectator"));
                right.Add(new ControlWithDescription("Ctrl+Space", "Move ship to spectator"));
                right.Add(new ControlWithDescription("F11, Shift+F11", "Game statistics / FPS"));
                right.Add(new ControlWithDescription("F12", "Debug screen (jump to mission)"));
                right.Add(new ControlWithDescription("Ctrl+Del", "Skip current objective"));
                right.Add(new ControlWithDescription("Shift+\\", "Teleport to next obstacle"));
            }

            /*
             * right.Add(new ControlWithDescription("F5","Ship customization screen"));
             * right.Add(new ControlWithDescription("F9","restart current game and reload sounds"));
             * right.Add(new ControlWithDescription("F3","start sun wind"));
             * right.Add(new ControlWithDescription("F8","save all voxel maps into USER FOLDER - only for programmers"));
             * right.Add(new ControlWithDescription("F10","switch camera - only for programmers"));
             * right.Add(new ControlWithDescription("F11","save screenshot(s) into USER FOLDER"));
             * right.Add(new ControlWithDescription("F12","cycle through debug screens - only for programmers"));
             */

#if RENDER_PROFILING
            right.Add(new ControlWithDescription("Alt + Num0", "Enable/Disable render profiler or leave current child node."));
            right.Add(new ControlWithDescription("Alt + Num1-Num9", "Enter child node in render profiler"));
            right.Add(new ControlWithDescription("Alt + Enter", "Pause/Unpause profiler"));
#endif //RENDER_PROFILER

            Vector2 controlPosition     = -m_size.Value / 2.0f + new Vector2(0.06f, 0.125f);
            Vector2 descriptionPosition = -m_size.Value / 2.0f + new Vector2(0.18f, 0.125f);
            foreach (var line in left)
            {
                Controls.Add(new MyGuiControlLabel(this, controlPosition, null, line.Control, MyGuiConstants.LABEL_TEXT_COLOR, MyGuiConstants.LABEL_TEXT_SCALE, MyGuiDrawAlignEnum.HORISONTAL_LEFT_AND_VERTICAL_CENTER, MyGuiManager.GetFontMinerWarsRed()));
                Controls.Add(new MyGuiControlLabel(this, descriptionPosition, null, line.Description, MyGuiConstants.LABEL_TEXT_COLOR, MyGuiConstants.LABEL_TEXT_SCALE, MyGuiDrawAlignEnum.HORISONTAL_LEFT_AND_VERTICAL_CENTER));
                controlPosition.Y     += 0.023f;
                descriptionPosition.Y += 0.023f;
            }

            controlPosition     = new Vector2(0.03f, 0.125f - m_size.Value.Y / 2.0f);
            descriptionPosition = new Vector2(0.15f, 0.125f - m_size.Value.Y / 2.0f);

            foreach (var line in right)
            {
                Controls.Add(new MyGuiControlLabel(this, controlPosition, null, line.Control, MyGuiConstants.LABEL_TEXT_COLOR, MyGuiConstants.LABEL_TEXT_SCALE, MyGuiDrawAlignEnum.HORISONTAL_LEFT_AND_VERTICAL_CENTER, MyGuiManager.GetFontMinerWarsRed()));
                Controls.Add(new MyGuiControlLabel(this, descriptionPosition, null, line.Description, MyGuiConstants.LABEL_TEXT_COLOR, MyGuiConstants.LABEL_TEXT_SCALE, MyGuiDrawAlignEnum.HORISONTAL_LEFT_AND_VERTICAL_CENTER));
                controlPosition.Y     += 0.023f;
                descriptionPosition.Y += 0.023f;
            }

            Controls.Add(new MyGuiControlLabel(this, new Vector2(0.06f - m_size.Value.X / 2.0f, -0.085f + m_size.Value.Y / 2.0f), null, new StringBuilder().Append(MyTextsWrapper.Get(MyTextsWrapperEnum.UserFolder)).Append(": ").Append(MyFileSystemUtils.GetApplicationUserDataFolder()), MyGuiConstants.LABEL_TEXT_COLOR, MyGuiConstants.LABEL_TEXT_SCALE, MyGuiDrawAlignEnum.HORISONTAL_LEFT_AND_VERTICAL_CENTER));

            Controls.Add(new MyGuiControlButton(this, 0.5f * m_size.Value + new Vector2(-0.14f, -0.085f), MyGuiConstants.BACK_BUTTON_SIZE,
                                                MyGuiConstants.BACK_BUTTON_BACKGROUND_COLOR, MyTextsWrapperEnum.Back, MyGuiConstants.BACK_BUTTON_TEXT_COLOR,
                                                MyGuiConstants.BACK_BUTTON_TEXT_SCALE, OnBackClick, MyGuiControlButtonTextAlignment.CENTERED, true, MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER, true));

            if (MyMultiplayerPeers.Static.Players.Count == 0)
            {
                m_wasPause = MyMinerGame.IsPaused();
                MyMinerGame.SetPause(true);
            }
        }
        public override bool Draw(float backgroundFadeAlpha)
        {
            if (base.Draw(backgroundFadeAlpha) == false)
            {
                return(false);
            }

            float rowDistance = MyGuiConstants.DEBUG_STATISTICS_ROW_DISTANCE;
            float textScale   = MyGuiConstants.DEBUG_STATISTICS_TEXT_SCALE;

            m_stringIndex = 0;
            m_texts.Clear();
            m_rightAlignedtexts.Clear();


            m_texts.Add(StringBuilderCache.GetFormatedFloat("FPS: ", MyFpsManager.GetFps()));

            m_texts.Add(MyGuiManager.GetGuiScreensForDebug());

            m_texts.Add(StringBuilderCache.GetFormatedBool("Paused: ", MyMinerGame.IsPaused()));
            m_texts.Add(StringBuilderCache.GetFormatedDateTimeOffset("System Time: ", TimeUtil.LocalTime));
            m_texts.Add(StringBuilderCache.GetFormatedTimeSpan("Total MISSION Time: ", MyMissions.ActiveMission == null ? TimeSpan.Zero : MyMissions.ActiveMission.MissionTimer.GetElapsedTime()));
            m_texts.Add(StringBuilderCache.GetFormatedTimeSpan("Total GAME-PLAY Time: ", TimeSpan.FromMilliseconds(MyMinerGame.TotalGamePlayTimeInMilliseconds)));
            m_texts.Add(StringBuilderCache.GetFormatedTimeSpan("Total Time: ", TimeSpan.FromMilliseconds(MyMinerGame.TotalTimeInMilliseconds)));

            m_texts.Add(StringBuilderCache.GetFormatedLong("GC.GetTotalMemory: ", GC.GetTotalMemory(false), " bytes"));

//#if MEMORY_PROFILING
            //TODO: I am unable to show this without allocations
            m_texts.Add(StringBuilderCache.GetFormatedLong("Environment.WorkingSet: ", MyWindowsAPIWrapper.WorkingSet, " bytes"));

            m_texts.Add(StringBuilderCache.GetFormatedFloat("Available videomemory: ", MyMinerGame.Static.GraphicsDevice.AvailableTextureMemory / (1024.0f * 1024.0f), " MB"));
            // TODO: Videomem
            //m_texts.Add(StringBuilderCache.GetFormatedFloat("Allocated videomemory: ", MyProgram.GetResourcesSizeInMB(), " MB"));
//#endif

#if PHYSICS_SENSORS_PROFILING
            if (MinerWars.AppCode.Physics.MyPhysics.physicsSystem != null)
            {
                m_texts.Add(StringBuilderCache.GetFormatedInt("Physics sensor - new allocated interactions: ", MinerWars.AppCode.Physics.MyPhysics.physicsSystem.GetSensorInteractionModule().GetNewAllocatedInteractionsCount()));
                m_texts.Add(StringBuilderCache.GetFormatedInt("Physics sensor - interactions in use: ", MinerWars.AppCode.Physics.MyPhysics.physicsSystem.GetSensorInteractionModule().GetInteractionsInUseCount()));
                m_texts.Add(StringBuilderCache.GetFormatedInt("Physics sensor - interactions in use MAX: ", MinerWars.AppCode.Physics.MyPhysics.physicsSystem.GetSensorInteractionModule().GetInteractionsInUseCountMax()));
                m_texts.Add(StringBuilderCache.GetFormatedInt("Physics sensor - all sensors: ", MinerWars.AppCode.Physics.MyPhysics.physicsSystem.GetSensorModule().SensorsCount()));
                m_texts.Add(StringBuilderCache.GetFormatedInt("Physics sensor - active sensors: ", MinerWars.AppCode.Physics.MyPhysics.physicsSystem.GetSensorModule().ActiveSensors.Count));
            }
#endif

            m_texts.Add(StringBuilderCache.GetFormatedInt("Sound Instances Total 2D: ", MyAudio.GetSoundInstancesTotal2D()));
            m_texts.Add(StringBuilderCache.GetFormatedInt("Sound Instances Total 3D: ", MyAudio.GetSoundInstancesTotal3D()));
            m_texts.Add(MyAudio.GetCurrentTransitionForDebug());
            if (MyAudio.GetMusicCue() != null)
            {
                //m_texts.Add(StringBuilderCache.GetStrings("Currently Playing Music Cue: ", MyAudio.GetMusicCue().Value.GetCue().Name));
            }

            m_texts.Add(StringBuilderCache.Clear());
            m_texts.Add(StringBuilderCache.GetFormatedInt("Textures 2D Count: ", MyPerformanceCounter.PerAppLifetime.Textures2DCount));
            m_texts.Add(StringBuilderCache.GetFormatedInt("Textures 2D Size In Pixels: ", MyPerformanceCounter.PerAppLifetime.Textures2DSizeInPixels));
            m_texts.Add(StringBuilderCache.GetFormatedDecimal("Textures 2D Size In Mb: ", MyPerformanceCounter.PerAppLifetime.Textures2DSizeInMb, 3));
            m_texts.Add(StringBuilderCache.GetFormatedInt("Dxt Compressed Textures Count: ", MyPerformanceCounter.PerAppLifetime.DxtCompressedTexturesCount));
            m_texts.Add(StringBuilderCache.GetFormatedInt("Non Dxt Compressed Textures Count: ", MyPerformanceCounter.PerAppLifetime.NonDxtCompressedTexturesCount));
            m_texts.Add(StringBuilderCache.GetFormatedInt("Non Mip Mapped Textures Count: ", MyPerformanceCounter.PerAppLifetime.NonMipMappedTexturesCount));
            m_texts.Add(StringBuilderCache.GetFormatedInt("Texture Cubes Count: ", MyPerformanceCounter.PerAppLifetime.TextureCubesCount));
            m_texts.Add(StringBuilderCache.GetFormatedInt("Texture Cubes Size In Pixels: ", MyPerformanceCounter.PerAppLifetime.TextureCubesSizeInPixels));
            m_texts.Add(StringBuilderCache.GetFormatedDecimal("Texture Cubes Size In Mb: ", MyPerformanceCounter.PerAppLifetime.TextureCubesSizeInMb, 3));
            m_texts.Add(StringBuilderCache.GetFormatedInt("Non MyModels Count: ", MyPerformanceCounter.PerAppLifetime.ModelsCount));
            m_texts.Add(StringBuilderCache.GetFormatedInt("MyModels Count: ", MyPerformanceCounter.PerAppLifetime.MyModelsCount));
            m_texts.Add(StringBuilderCache.GetFormatedInt("MyModels Meshes Count: ", MyPerformanceCounter.PerAppLifetime.MyModelsMeshesCount));
            m_texts.Add(StringBuilderCache.GetFormatedInt("MyModels Vertexes Count: ", MyPerformanceCounter.PerAppLifetime.MyModelsVertexesCount));
            m_texts.Add(StringBuilderCache.GetFormatedInt("MyModels Triangles Count: ", MyPerformanceCounter.PerAppLifetime.MyModelsTrianglesCount));
            m_texts.Add(StringBuilderCache.GetFormatedInt("Size of Model Vertex Buffers in Mb: ", MyPerformanceCounter.PerAppLifetime.ModelVertexBuffersSize / 1024 / 1024));
            m_texts.Add(StringBuilderCache.GetFormatedInt("Size of Model Index Buffers in Mb: ", MyPerformanceCounter.PerAppLifetime.ModelIndexBuffersSize / 1024 / 1024));
            m_texts.Add(StringBuilderCache.GetFormatedInt("Size of Voxel Vertex Buffers in Mb: ", MyPerformanceCounter.PerAppLifetime.VoxelVertexBuffersSize / 1024 / 1024));
            m_texts.Add(StringBuilderCache.GetFormatedInt("Size of Voxel Index Buffers in Mb: ", MyPerformanceCounter.PerAppLifetime.VoxelIndexBuffersSize / 1024 / 1024));
            m_texts.Add(StringBuilderCache.GetFormatedBool("Paused: ", MyMinerGame.IsPaused()));
            MyGuiManager.GetInput().GetPressedKeys(m_pressedKeys);
            AddPressedKeys("Current keys              : ", m_pressedKeys);

            m_texts.Add(StringBuilderCache.Clear());
            m_texts.Add(m_frameDebugText);


            //This ensures constant max length of right block to avoid flickering when correct max line is changing too often
            m_frameDebugTextRA.AppendLine();
            m_frameDebugTextRA.Append("                                                                  ");
            ////

            m_rightAlignedtexts.Add(m_frameDebugTextRA);

            Vector2 origin             = GetScreenLeftTopPosition();
            Vector2 rightAlignedOrigin = GetScreenRightTopPosition();

            for (int i = 0; i < m_texts.Count; i++)
            {
                MyGuiManager.DrawString(MyGuiManager.GetFontMinerWarsWhite(), m_texts[i], origin + new Vector2(0, i * rowDistance), textScale,
                                        Color.Yellow, MyGuiDrawAlignEnum.HORISONTAL_LEFT_AND_VERTICAL_TOP);
            }
            for (int i = 0; i < m_rightAlignedtexts.Count; i++)
            {
                MyGuiManager.DrawString(MyGuiManager.GetFontMinerWarsWhite(), m_rightAlignedtexts[i], rightAlignedOrigin + new Vector2(0.0f, i * rowDistance), textScale,
                                        Color.Yellow, MyGuiDrawAlignEnum.HORISONTAL_RIGHT_AND_VERTICAL_TOP);
            }

            ClearFrameDebugText();

            return(true);
        }
Esempio n. 23
0
        /// <summary>
        /// Render method is called directly by renderer. Depending on stage, post process can do various things
        /// </summary>
        /// <param name="postProcessStage">Stage indicating in which part renderer currently is.</param>public override void RenderAfterBlendLights()
        public override Texture Render(PostProcessStage postProcessStage, Texture source, Texture availableRenderTarget)
        {
            switch (postProcessStage)
            {
            case PostProcessStage.LODBlend:
            {
                MyEffectVolumetricSSAO2 volumetricSsao = MyRender.GetEffect(MyEffects.VolumetricSSAO) as MyEffectVolumetricSSAO2;

                int width      = MyRender.GetRenderTarget(MyRenderTargets.Normals).GetLevelDescription(0).Width;
                int height     = MyRender.GetRenderTarget(MyRenderTargets.Normals).GetLevelDescription(0).Height;
                int halfWidth  = width / 2;
                int halfHeight = height / 2;

                //Render SSAO
                MyMinerGame.SetRenderTarget(MyRender.GetRenderTarget(MyRenderTargets.SSAO), null);

                MyMinerGame.Static.GraphicsDevice.Clear(ClearFlags.Target, new SharpDX.ColorBGRA(0), 1, 0);
                DepthStencilState.None.Apply();
                BlendState.Opaque.Apply();

                Vector4 ssaoParams  = new Vector4(MinRadius, MaxRadius, RadiusGrowZScale, CameraZFar);
                Vector4 ssaoParams2 = new Vector4(Bias, Falloff, NormValue, 0);

                volumetricSsao.SetDepthsRT(MyRender.GetRenderTarget(MyRenderTargets.Depth));
                volumetricSsao.SetNormalsTexture(MyRender.GetRenderTarget(MyRenderTargets.Normals));
                volumetricSsao.SetHalfPixel(width, height);

                volumetricSsao.SetFrustumCorners(MyRender.GetShadowRenderer().GetFrustumCorners());

                volumetricSsao.SetViewMatrix(MyCamera.ViewMatrixAtZero);

                volumetricSsao.SetParams1(ssaoParams);
                volumetricSsao.SetParams2(ssaoParams2);

                volumetricSsao.SetProjectionMatrix(MyCamera.ProjectionMatrix);

                volumetricSsao.SetContrast(Contrast);


                MyGuiManager.GetFullscreenQuad().Draw(volumetricSsao);

                if (volumetricSsao.UseBlur)
                {
                    //SSAO Blur
                    MyMinerGame.SetRenderTarget(availableRenderTarget, null);
                    MyEffectSSAOBlur2 effectSsaoBlur = MyRender.GetEffect(MyEffects.SSAOBlur) as MyEffectSSAOBlur2;
                    effectSsaoBlur.SetDepthsRT(MyRender.GetRenderTarget(MyRenderTargets.Depth));
                    //effectSsaoBlur.SetNormalsRT(MyRender.GetRenderTarget(MyRenderTargets.Normals));
                    effectSsaoBlur.SetHalfPixel(width, height);
                    effectSsaoBlur.SetSSAOHalfPixel(halfWidth, halfHeight);
                    effectSsaoBlur.SetSsaoRT(MyRender.GetRenderTarget(MyRenderTargets.SSAO));
                    effectSsaoBlur.SetBlurDirection(new Vector2(0, 1f / (float)halfHeight));
                    //effectSsaoBlur.SetBlurDirection(new Vector2(1 / (float)halfWidth, 1f / (float)halfHeight));

                    MyGuiManager.GetFullscreenQuad().Draw(effectSsaoBlur);

                    MyMinerGame.SetRenderTarget(MyRender.GetRenderTarget(MyRenderTargets.SSAOBlur), null);
                    effectSsaoBlur.SetSsaoRT(availableRenderTarget);
                    effectSsaoBlur.SetBlurDirection(new Vector2(1f / (float)halfWidth, 0));
                    MyGuiManager.GetFullscreenQuad().Draw(effectSsaoBlur);
                }

                //Bake it into diffuse

                /*
                 * MyEffectScreenshot ssEffect = MyRender.GetEffect(MyEffects.Screenshot) as MyEffectScreenshot;
                 * MyMinerGame.SetRenderTarget(availableRenderTarget, null);
                 * ssEffect.SetSourceTexture(MyRender.GetRenderTarget(MyRenderTargets.Diffuse));
                 * ssEffect.SetScale(Vector2.One);
                 * ssEffect.SetTechnique(MyEffectScreenshot.ScreenshotTechniqueEnum.Default);
                 *
                 * MyGuiManager.GetFullscreenQuad().Draw(ssEffect);
                 *
                 */
                MyMinerGame.SetRenderTarget(MyRender.GetRenderTarget(MyRenderTargets.Diffuse), null);

                /*
                 * ssEffect.SetSourceTexture(availableRenderTarget);
                 * ssEffect.SetTechnique(MyEffectScreenshot.ScreenshotTechniqueEnum.Default);
                 * ssEffect.SetScale(Vector2.One);
                 * MyGuiManager.GetFullscreenQuad().Draw(ssEffect);
                 */
                MyEffectVolumetricSSAO2 effectVolumetricSsao = MyRender.GetEffect(MyEffects.VolumetricSSAO) as MyEffectVolumetricSSAO2;

                //Blend with SSAO together
                DepthStencilState.None.Apply();

                if (!effectVolumetricSsao.ShowOnlySSAO)
                {
                    MyStateObjects.SSAO_BlendState.Apply();
                }
                else
                {
                    MyRender.CurrentRenderSetup.EnableLights = false;
                    MyMinerGame.Static.GraphicsDevice.Clear(ClearFlags.Target, new SharpDX.ColorBGRA(1.0f), 1, 0);
                    MyStateObjects.SSAO_BlendState.Apply();
                }


                if (effectVolumetricSsao.UseBlur)
                {
                    MyGuiManager.DrawSpriteFast(MyRender.GetRenderTarget(MyRenderTargets.SSAOBlur), 0, 0, MyCamera.Viewport.Width, MyCamera.Viewport.Height, Color.White);
                }
                else
                {
                    MyGuiManager.DrawSpriteFast(MyRender.GetRenderTarget(MyRenderTargets.SSAO), 0, 0, MyCamera.Viewport.Width, MyCamera.Viewport.Height, Color.White);
                }
            }
            break;
            }
            return(source);
        }
        /// <summary>
        /// Render method is called directly by renderer. Depending on stage, post process can do various things
        /// </summary>
        /// <param name="postProcessStage">Stage indicating in which part renderer currently is.</param>public override void RenderAfterBlendLights()
        public override Texture Render(PostProcessStage postProcessStage, Texture source, Texture availableRenderTarget)
        {
            switch (postProcessStage)
            {
            case PostProcessStage.AlphaBlended:
            {
                Density    = MySector.GodRaysProperties.Density;
                Weight     = MySector.GodRaysProperties.Weight;
                Decay      = MySector.GodRaysProperties.Decay;
                Exposition = MySector.GodRaysProperties.Exposition;


                var halfRT = MyRender.GetRenderTarget(MyRenderTargets.AuxiliaryHalf0);

                MyMinerGame.SetRenderTarget(halfRT, null);
                BlendState.Opaque.Apply();
                RasterizerState.CullNone.Apply();
                DepthStencilState.None.Apply();

                MyEffectGodRays effectGodRays = MyRender.GetEffect(MyEffects.GodRays) as MyEffectGodRays;

                effectGodRays.SetDiffuseTexture(source);
                effectGodRays.SetDepthTexture(MyRender.GetRenderTarget(MyRenderTargets.Depth));
                effectGodRays.SetFrustumCorners(MyRender.GetShadowRenderer().GetFrustumCorners());
                effectGodRays.SetView(MyCamera.ViewMatrix);
                effectGodRays.SetWorldViewProjection(MyCamera.ViewProjectionMatrix);
                effectGodRays.SetDensity(Density);
                effectGodRays.SetDecay(Decay);
                effectGodRays.SetWeight(Weight * (1 - MySector.FogProperties.FogMultiplier));
                effectGodRays.SetExposition(Exposition);
                //effectGodRays.LightPosition.SetValue(1500f * -MySunGlare.GetSunDirection() * MySunConstants.RENDER_SUN_DISTANCE);
                effectGodRays.SetLightPosition(1500f * -MyRender.Sun.Direction * MySunConstants.RENDER_SUN_DISTANCE);
                effectGodRays.SetLightDirection(MyRender.Sun.Direction);
                effectGodRays.SetCameraPos(MyCamera.Position);

                MyGuiManager.GetFullscreenQuad().Draw(effectGodRays);

                if (ApplyBlur)
                {
                    var auxTarget = MyRender.GetRenderTarget(MyRenderTargets.AuxiliaryHalf1010102);

                    var blurEffect = MyRender.GetEffect(MyEffects.GaussianBlur) as MyEffectGaussianBlur;
                    blurEffect.SetHalfPixel(halfRT.GetLevelDescription(0).Width, halfRT.GetLevelDescription(0).Height);

                    // Apply vertical gaussian blur
                    MyMinerGame.SetRenderTarget(auxTarget, null);
                    blurEffect.BlurAmount = 1;
                    blurEffect.SetSourceTexture(halfRT);
                    blurEffect.SetHeightForVerticalPass(halfRT.GetLevelDescription(0).Height);
                    MyGuiManager.GetFullscreenQuad().Draw(blurEffect);

                    // Apply horizontal gaussian blur
                    MyMinerGame.SetRenderTarget(halfRT, null);
                    blurEffect.BlurAmount = 1;
                    blurEffect.SetSourceTexture(auxTarget);
                    blurEffect.SetWidthForHorisontalPass(auxTarget.GetLevelDescription(0).Width);
                    MyGuiManager.GetFullscreenQuad().Draw(blurEffect);
                }

                // Additive
                MyMinerGame.SetRenderTarget(availableRenderTarget, null);
                //MyMinerGame.Static.GraphicsDevice.Clear(ClearFlags.All, new SharpDX.ColorBGRA(0), 1, 0);
                BlendState.Opaque.Apply();
                MyRender.Blit(source, true);

                var upscaleEffect = MyRender.GetEffect(MyEffects.Scale) as MyEffectScale;
                upscaleEffect.SetScale(new Vector2(2));
                upscaleEffect.SetTechnique(MyEffectScale.Technique.HWScale);
                MyStateObjects.Additive_NoAlphaWrite_BlendState.Apply();

                upscaleEffect.SetSourceTextureMod(halfRT);
                MyGuiManager.GetFullscreenQuad().Draw(upscaleEffect);

                /*
                 * MyMinerGame.SetRenderTarget(availableRenderTarget, null);
                 * var upscaleEffect = MyRender.GetEffect(MyEffects.Scale) as MyEffectScale;
                 * upscaleEffect.SetScale(new Vector2(2));
                 * upscaleEffect.SetTechnique(MyEffectScale.Technique.HWScale);
                 * //MyStateObjects.Additive_NoAlphaWrite_BlendState.Apply();
                 * BlendState.Opaque.Apply();
                 *
                 * upscaleEffect.SetSourceTextureMod(halfRT);
                 * MyGuiManager.GetFullscreenQuad().Draw(upscaleEffect);
                 */
                return(availableRenderTarget);
            }
            break;
            }

            return(source);
        }
Esempio n. 25
0
        static MyGlobalEvents()
        {
            m_globalEvents[(int)MyGlobalEventEnum.SunWind] =
                new MyGlobalEvent(
                    Type : MyGlobalEventEnum.SunWind,
                    Name : MyTextsWrapperEnum.GlobalEventSunWindName,
                    Description : MyTextsWrapperEnum.GlobalEventSunWindDescription,
                    RatePerHour : 12.0f,
                    Icon : null,
                    Enabled : true,
                    Action : delegate(object o, EventArgs e)
            {
                //dont allow sunwind in god editor on or when the game is paused
                if (!MySunWind.IsActive && !(MyGuiScreenGamePlay.Static.IsEditorActive() && !MyGuiScreenGamePlay.Static.IsIngameEditorActive()) && !MyMinerGame.IsPaused())
                {
                    //MyHudNotification.AddNotification(new MyHudNotification.MyNotification(MyTextsWrapperEnum.GlobalEventSunWindDescription, 5000));
                    MySunWind.Start();
                    //MyAudio.AddCue2D(MySoundCuesEnum.HudSolarFlareWarning);
                }
            },
                    WriteToEventLog: false
                    );

            m_globalEvents[(int)MyGlobalEventEnum.FractionStatusChange] =
                new MyGlobalEvent(
                    Type : MyGlobalEventEnum.FractionStatusChange,
                    Name : MyTextsWrapperEnum.GlobalEventFactionChangeName,
                    Description : MyTextsWrapperEnum.GlobalEventFactionChangeDescription,
                    RatePerHour : 10.0f,
                    Icon : null,
                    Enabled : false,
                    Action : delegate(object o, EventArgs e)
            {
                float statusChange = MyMwcUtils.GetRandomFloat(MyFactions.RELATION_WORST, MyFactions.RELATION_BEST) / 10.0f;

                int[] enumValues = MyMwcFactionsByIndex.GetFactionsIndexes();
                System.Diagnostics.Debug.Assert(enumValues.Length > 3);

                MyMwcObjectBuilder_FactionEnum faction1;
                do
                {
                    faction1 = MyMwcFactionsByIndex.GetFaction(MyMwcUtils.GetRandomInt(enumValues.Length));
                }while (faction1 == MyMwcObjectBuilder_FactionEnum.None);

                MyMwcObjectBuilder_FactionEnum faction2;
                do
                {
                    faction2 = MyMwcFactionsByIndex.GetFaction(MyMwcUtils.GetRandomInt(enumValues.Length));
                }while ((faction1 == faction2) || (faction2 == MyMwcObjectBuilder_FactionEnum.None));

                MyFactions.ChangeFactionStatus(faction1, faction2, statusChange);
            },
                    WriteToEventLog: false
                    );

            m_globalEvents[(int)MyGlobalEventEnum.MeteorWind] =
                new MyGlobalEvent(
                    Type : MyGlobalEventEnum.SunWind,
                    Name : MyTextsWrapperEnum.GlobalEventMeteorWindName,
                    Description : MyTextsWrapperEnum.GlobalEventSunWindDescription,
                    RatePerHour : MyFakes.ENABLE_RANDOM_METEOR_SHOWER ? 1.0f : 0.0f,
                    Icon : null,
                    Enabled : false,
                    Action : delegate(object o, EventArgs e)
            {
                //dont allow sunwind in god editor on or when the game is paused
                if (!(MyGuiScreenGamePlay.Static.IsEditorActive() && !MyGuiScreenGamePlay.Static.IsIngameEditorActive()) && !MyMinerGame.IsPaused())
                {
                    //MyHudNotification.AddNotification(new MyHudNotification.MyNotification(MyTextsWrapperEnum.GlobalEventSunWindDescription, 5000));
                    MyMeteorWind.Start();
                    //MyAudio.AddCue2D(MySoundCuesEnum.SfxSolarFlareWarning);
                }
            },
                    WriteToEventLog: false
                    );


            // todo implement localization strings
            m_globalEvents[(int)MyGlobalEventEnum.IceStorm] =
                new MyGlobalEvent(
                    Type : MyGlobalEventEnum.IceStorm,
                    Name : MyTextsWrapperEnum.GlobalEventIceStormName,              //Name: MyTextsWrapperEnum.GlobalEvent_IceStorm_Name,
                    Description : MyTextsWrapperEnum.GlobalEventSunWindDescription, //IceStorm_Description,
                    RatePerHour : MyFakes.ENABLE_RANDOM_ICE_STORM ? 1.0f : 0.0f,
                    Icon : null,
                    Enabled : false,
                    Action : delegate(object o, EventArgs e)
            {
                //dont allow sunwind in god editor on or when the game is paused
                if (!(MyGuiScreenGamePlay.Static.IsEditorActive() && !MyGuiScreenGamePlay.Static.IsIngameEditorActive()) && !MyMinerGame.IsPaused())
                {
                    MyHudNotification.AddNotification(new MyHudNotification.MyNotification(MyTextsWrapperEnum.GlobalEventSunWindDescription, 5000, null));        // MyHudNotification.AddNotification(new MyHudNotification.MyNotification(MyTextsWrapperEnum.GlobalEvent_IceStorm_Description, 5000));
                    MyIceStorm.Start();
                    MyAudio.AddCue2D(MySoundCuesEnum.HudSolarFlareWarning);
                }
            },
                    WriteToEventLog: false
                    );

            m_globalEvents[(int)MyGlobalEventEnum.IceComet] =
                new MyGlobalEvent(
                    Type : MyGlobalEventEnum.IceComet,
                    Name : MyTextsWrapperEnum.GlobalEventIceCometName,
                    Description : MyTextsWrapperEnum.GlobalEventIceCometDescription,
                    RatePerHour : 0.0f,
                    Icon : null,
                    Enabled : false,
                    Action : delegate(object o, EventArgs e)
            {
                if (!(MyGuiScreenGamePlay.Static.IsEditorActive() && !MyGuiScreenGamePlay.Static.IsIngameEditorActive()) && !MyMinerGame.IsPaused())
                {
                    MyHudNotification.AddNotification(new MyHudNotification.MyNotification(MyTextsWrapperEnum.GlobalEventSunWindDescription, 5000));
                    MyIceComet.Start();
                    MyAudio.AddCue2D(MySoundCuesEnum.HudSolarFlareWarning);
                }
            },
                    WriteToEventLog: false
                    );

            foreach (MyGlobalEvent e in m_globalEvents)
            {
                System.Diagnostics.Debug.Assert(e != null);
            }

            MyFactions.OnFactionStatusChanged += new MyFactionStatusChangeHandler(MyFactions_OnFactionStatusChanged);
        }
Esempio n. 26
0
        /// <summary>
        /// Render method is called directly by renderer. Depending on stage, post process can do various things
        /// </summary>
        /// <param name="postProcessStage">Stage indicating in which part renderer currently is.</param>public override void RenderAfterBlendLights()
        public override Texture Render(PostProcessStage postProcessStage, Texture source, Texture availableRenderTarget)
        {
            switch (postProcessStage)
            {
            case PostProcessStage.LODBlend:
            {
                //if (RenderHDRThisFrame())
                //{
                //    (MyRender.GetEffect(MyEffects.BlendLights) as MyEffectBlendLights).CopyEmissivityTechnique = MyEffectBlendLights.Technique.CopyEmissivityHDR;
                //    (MyRender.GetEffect(MyEffects.BlendLights) as MyEffectBlendLights).DefaultTechnique = MyEffectBlendLights.Technique.HDR;
                //    (MyRender.GetEffect(MyEffects.DirectionalLight) as MyEffectDirectionalLight).DefaultTechnique = MyEffectDirectionalLight.Technique.DefaultHDR;
                //    (MyRender.GetEffect(MyEffects.DirectionalLight) as MyEffectDirectionalLight).DefaultWithoutShadowsTechnique = MyEffectDirectionalLight.Technique.WithoutShadowsHDR;
                //    (MyRender.GetEffect(MyEffects.DirectionalLight) as MyEffectDirectionalLight).DefaultNoLightingTechnique = MyEffectDirectionalLight.Technique.NoLightingHDR;

                //    (MyRender.GetEffect(MyEffects.PointLight) as MyEffectPointLight).DefaultTechnique = MyEffectPointLight.MyEffectPointLightTechnique.DefaultHDR;
                //    (MyRender.GetEffect(MyEffects.PointLight) as MyEffectPointLight).DefaultPointTechnique = MyEffectPointLight.MyEffectPointLightTechnique.DefaultHDR;
                //    (MyRender.GetEffect(MyEffects.PointLight) as MyEffectPointLight).DefaultHemisphereTechnique = MyEffectPointLight.MyEffectPointLightTechnique.DefaultHDR;
                //    (MyRender.GetEffect(MyEffects.PointLight) as MyEffectPointLight).DefaultReflectorTechnique = MyEffectPointLight.MyEffectPointLightTechnique.ReflectorHDR; // unused, dont have instancing
                //    (MyRender.GetEffect(MyEffects.PointLight) as MyEffectPointLight).DefaultSpotTechnique = MyEffectPointLight.MyEffectPointLightTechnique.SpotHDR;
                //    (MyRender.GetEffect(MyEffects.PointLight) as MyEffectPointLight).DefaultSpotShadowTechnique = MyEffectPointLight.MyEffectPointLightTechnique.SpotShadowsHDR;

                //    (MyRender.GetEffect(MyEffects.PointLight) as MyEffectPointLight).DefaultPointInstancedTechnique = MyEffectPointLight.MyEffectPointLightTechnique.PointHDR_Instanced;
                //    (MyRender.GetEffect(MyEffects.PointLight) as MyEffectPointLight).DefaultHemisphereInstancedTechnique = MyEffectPointLight.MyEffectPointLightTechnique.HemisphereHDR_Instanced;
                //    (MyRender.GetEffect(MyEffects.PointLight) as MyEffectPointLight).DefaultSpotInstancedTechnique = MyEffectPointLight.MyEffectPointLightTechnique.SpotHDR_Instanced;
                //}
                break;
            }

            case PostProcessStage.HDR:
            {
                // if HDR is disabled or some debug rendering display
                // is enabled then skip HDR post process
                if (!RenderHDRThisFrame())
                {
                    return(source);
                }

                BlendState.Opaque.Apply();
                DepthStencilState.None.Apply();
                // RasterizerState.CullNone.Apply(MyMinerGameDX.Static.GraphicsDevice);

                m_thresholdTargets[0] = MyRender.GetRenderTarget(MyRenderTargets.Normals);
                m_thresholdTargets[1] = availableRenderTarget;

                // 1. threshold
                GenerateThreshold(
                    source,
                    MyRender.GetRenderTarget(MyRenderTargets.Diffuse),
                    m_thresholdTargets,
                    MyRender.GetEffect(MyEffects.Threshold) as MyEffectThreshold,
                    Threshold, BloomIntensity, BloomIntensityBackground, Exposure);

                /*
                 * MyMinerGame.SetRenderTarget(null, null,  SetDepthTargetEnum.RestoreDefault);
                 * MyMinerGame.SetRenderTarget(availableRenderTarget, null, SetDepthTargetEnum.RestoreDefault);
                 * MyEffectScreenshot ssEffect = MyRender.GetEffect(MyEffects.Screenshot) as MyEffectScreenshot;
                 * ssEffect.SetSourceTexture(m_thresholdTargets[0]);
                 * ssEffect.SetScale(MinerWarsMath.Vector2.One);
                 * ssEffect.SetTechnique(MyEffectScreenshot.ScreenshotTechniqueEnum.Default);
                 * MyGuiManager.GetFullscreenQuad().Draw(ssEffect);
                 * return availableRenderTarget;
                 */


                // 2. downscale HDR1 -> Downscaled8
                // !! IMPORTANT !! you cannot just switch the function call if you want different downscale
                // Also changing the RTs is necessary (they have fixed dimensions).
                GenerateDownscale4(
                    MyRender.GetRenderTarget(MyRenderTargets.Normals),
                    MyRender.GetRenderTarget(MyRenderTargets.Depth),
                    MyRender.GetRenderTarget(MyRenderTargets.HDR4Threshold),
                    MyRender.GetEffect(MyEffects.Scale) as MyEffectScale);

                /*
                 * // 3?. avg luminance
                 * float dt = (MyMinerGame.TotalGamePlayTimeInMilliseconds - lastTime) / 1000.0f;
                 * lastTime = MyMinerGame.TotalGamePlayTimeInMilliseconds;
                 * CalculateAverageLuminance(
                 *  MyRender.GetRenderTarget(MyRenderTargets.Downscaled8),
                 *  MyRender.GetRenderTarget(MyRenderTargets.Downscaled8Threshold),
                 *  MyRender.GetEffect(MyEffects.Luminance) as MyEffectLuminance,
                 *  MyRender.GetEffect(MyEffects.Scale) as MyEffectScale,
                 *  dt, 0.5f);
                 */

                // 4. blur
                Blur(MyRender.GetRenderTarget(MyRenderTargets.HDR4Threshold),
                     MyRender.GetRenderTarget(MyRenderTargets.HDR4),
                     MyRender.GetEffect(MyEffects.GaussianBlur) as MyEffectGaussianBlur,
                     VerticalBlurAmount, HorizontalBlurAmount);

                // 5. scale blurred to halfsize
                Upscale4To2(
                    MyRender.GetRenderTarget(MyRenderTargets.HDR4Threshold),
                    MyRender.GetRenderTarget(MyRenderTargets.AuxiliaryHalf1010102),
                    MyRender.GetEffect(MyEffects.Scale) as MyEffectScale);

                MyMinerGame.SetRenderTarget(availableRenderTarget, null, SetDepthTargetEnum.RestoreDefault);

                // 6. tonemap + apply bloom
                HDR(
                    source,
                    MyRender.GetRenderTarget(MyRenderTargets.Diffuse),
                    MyRender.GetRenderTarget(MyRenderTargets.AuxiliaryHalf1010102),
                    MyRender.GetEffect(MyEffects.HDR) as MyEffectHDR,
                    0.6f, Exposure);

                return(availableRenderTarget);

                //RenderTarget2D temp = currentFrameAdaptedLuminance;
                //currentFrameAdaptedLuminance = lastFrameAdaptedLuminance;
                //lastFrameAdaptedLuminance = temp;
            }
            }
            return(source);
        }
Esempio n. 27
0
        public static void Update()
        {
            //  Update only if sun wind is active
            if (IsActive == false)
            {
                return;
            }

            //?
            float dT = ((float)MyMinerGame.TotalGamePlayTimeInMilliseconds - (float)m_timeLastUpdate) / 1000.0f;

            m_timeLastUpdate = MyMinerGame.TotalGamePlayTimeInMilliseconds;

            if ((MyGuiScreenGamePlay.Static.IsEditorActive() && !MyGuiScreenGamePlay.Static.IsIngameEditorActive()) || MyMinerGame.IsPaused())
            {
                return;
            }

            m_deltaTime += dT;

            float traveledDistance = m_speed * m_deltaTime;

            //  If sun wind finished its way, we will turn it off
            if (traveledDistance >= MySunWindConstants.SUN_WIND_LENGTH_TOTAL)
            {
                IsActive = false;
                StopCue();
                return;
            }

            Vector3 campos = MyCamera.Position;

            //  This is plane that goes through sun wind, it's in its middle
            m_planeMiddle       = new MyPlane(m_initialSunWindPosition + m_directionFromSunNormalized * traveledDistance, m_directionFromSunNormalized);
            m_distanceToSunWind = MyUtils.GetDistanceFromPointToPlane(ref campos, ref m_planeMiddle);

            //  We make sure that sound moves always on line that goes through camera. So it's not in the middle of sun wind, more like middle where is camera.
            //  Reason is that I want the sound always go through camera.
            m_positionOnCameraLine = MyCamera.Position - m_directionFromSunNormalized * m_distanceToSunWind;

            Vector3 positionFront = m_positionOnCameraLine + m_directionFromSunNormalized * 5000;
            Vector3 positionBack  = m_positionOnCameraLine + m_directionFromSunNormalized * -5000;

            m_planeFront = new MyPlane(ref positionFront, ref m_directionFromSunNormalized);
            m_planeBack  = new MyPlane(ref positionBack, ref m_directionFromSunNormalized);

            float distanceToFrontPlane = MyUtils.GetDistanceFromPointToPlane(ref campos, ref m_planeFront);
            float distanceToBackPlane  = MyUtils.GetDistanceFromPointToPlane(ref campos, ref m_planeBack);


            Vector3 positionOfSound;

            if ((distanceToFrontPlane <= 0) && (distanceToBackPlane >= 0))
            {
                positionOfSound = MyCamera.Position;
            }
            else if (distanceToFrontPlane > 0)
            {
                positionOfSound = positionFront;
            }
            else
            {
                positionOfSound = positionBack;
            }

            //  Update position of sound. It works like this: we hear coming sound, then we are in the sound and then we hear it coming out.
            MyAudio.UpdateCuePosition(m_burningCue, positionOfSound, m_directionFromSunNormalized, -m_downVector, m_directionFromSunNormalized * m_speed);
            //MySounds.UpdateCuePosition(m_burningCue, positionOfSound, m_directionFromSunNormalized, Vector3.Up, Vector3.Zero);

            //MyLogManager.WriteLine("positionOfSound: " + MyUtils.GetFormatedVector3(positionOfSound, 3));
            //MyLogManager.WriteLine("m_directionFromSunNormalized: " + MyUtils.GetFormatedVector3(m_directionFromSunNormalized, 3));
            //MyLogManager.WriteLine("m_downVector: " + MyUtils.GetFormatedVector3(m_downVector, 3));

            Position = positionOfSound;

            //  Shake player's head
            float distanceToSound;

            Vector3.Distance(ref positionOfSound, ref campos, out distanceToSound);
            float shake = 1 - MathHelper.Clamp(distanceToSound / 1000, 0, 1);

            if (MySession.PlayerShip != null)
            {
                MySession.PlayerShip.IncreaseHeadShake(
                    MathHelper.Lerp(MyHeadShakeConstants.HEAD_SHAKE_AMOUNT_DURING_SUN_WIND_MIN,
                                    MyHeadShakeConstants.HEAD_SHAKE_AMOUNT_DURING_SUN_WIND_MAX, shake));
            }

            for (int i = 0; i < m_sunwindEntities.Count;)
            {
                if (m_sunwindEntities[i].Closed)
                {
                    m_sunwindEntities.RemoveAtFast(i);
                }
                else
                {
                    i++;
                }
            }

            //  Apply force to all objects that aren't static and are hit by sun wind (ignoring voxels and large ships)
            MyEntities.ApplySunWindForce(m_sunwindEntities, ref m_planeFront, ref m_planeBack, DoNotIgnoreTheseTypes, ref m_directionFromSunNormalized);

            //  Start small billboards
            if (m_distanceToSunWind <= MySunWindConstants.SWITCH_LARGE_AND_SMALL_BILLBOARD_DISTANCE)
            {
                Debug.Assert(m_computedMaxDistances == MySunWindConstants.SMALL_BILLBOARDS_SIZE.X * MySunWindConstants.SMALL_BILLBOARDS_SIZE.Y, "Not all small billboard MaxDistances are computed!");
                m_smallBillboardsStarted = true;
            }

            ComputeMaxDistances();
        }
Esempio n. 28
0
        internal static void RenderLights()
        {
            PrepareLights();

            RenderSpotShadows();

            m_renderProfiler.StartProfilingBlock("Render lights");
            MyMinerGame.SetRenderTarget(GetRenderTarget(MyRenderTargets.Auxiliary1), null, SetDepthTargetEnum.RestoreDefault);
            MyMinerGame.Static.GraphicsDevice.Clear(ClearFlags.Target, new ColorBGRA(0.0f), 1, 0);

            SetCorrectViewportSize();

            if (MyRender.CurrentRenderSetup.EnableSmallLights.Value)
            {
                MyEffectPointLight effectPointLight = (MyEffectPointLight)MyRender.GetEffect(MyEffects.PointLight);
                Texture            diffuseRT        = MyRender.GetRenderTarget(MyRenderTargets.Diffuse);
                effectPointLight.SetNormalsRT(MyRender.GetRenderTarget(MyRenderTargets.Normals));
                effectPointLight.SetDiffuseRT(diffuseRT);
                effectPointLight.SetDepthsRT(MyRender.GetRenderTarget(MyRenderTargets.Depth));
                effectPointLight.SetHalfPixel(diffuseRT.GetLevelDescription(0).Width, diffuseRT.GetLevelDescription(0).Height);
                effectPointLight.SetScale(GetScaleForViewport(diffuseRT));

                Matrix invViewProjMatrix = Matrix.Invert(MyCamera.ViewProjectionMatrix);
                Matrix invViewMatrix     = Matrix.Invert(MyCamera.ViewMatrix);

                effectPointLight.SetCameraPosition(MyCamera.Position);
                effectPointLight.SetViewMatrix(MyCamera.ViewMatrix);
                effectPointLight.SetInvViewMatrix(invViewMatrix);

                DepthStencilState.None.Apply();
                MyStateObjects.Light_Combination_BlendState.Apply();

                //Render each light with a model specific to the light
                m_renderProfiler.StartProfilingBlock("PointLight");

                var cullRationSq = MyRenderConstants.DISTANCE_LIGHT_CULL_RATIO * MyRenderConstants.DISTANCE_LIGHT_CULL_RATIO;

                effectPointLight.SetTechnique(effectPointLight.DefaultTechnique);
                foreach (MyLight light in m_pointLights)
                {
                    float distanceSq         = Vector3.DistanceSquared(MyCamera.Position, light.PositionWithOffset);
                    var   hasVolumetricGlare = light.GlareOn && light.Glare.Type == MyLightGlare.GlareTypeEnum.Distant;
                    var   isTooFarAway       = (light.Range * light.Range) < (distanceSq / cullRationSq);

                    if (!isTooFarAway)
                    {
                        // Always cull clockwise (render inner parts of object), depth test is done is PS using light radius
                        RasterizerState.CullClockwise.Apply();

                        effectPointLight.SetLightPosition(light.PositionWithOffset);
                        effectPointLight.SetLightIntensity(light.Intensity);
                        effectPointLight.SetSpecularLightColor(light.SpecularColor);
                        effectPointLight.SetFalloff(light.Falloff);

                        effectPointLight.SetLightRadius(light.Range);
                        effectPointLight.SetReflectorTexture(light.ReflectorTexture);
                        effectPointLight.SetLightColor(new Vector3(light.Color.X, light.Color.Y, light.Color.Z));
                        effectPointLight.SetTechnique(effectPointLight.DefaultTechnique);
                        MySimpleObjectDraw.DrawSphereForLight(effectPointLight, ref light.PositionWithOffset, light.Range, ref MyMath.Vector3One, 1);
                        MyPerformanceCounter.PerCameraDraw.LightsCount++;
                    }
                    if (!isTooFarAway || hasVolumetricGlare)
                    {
                        light.Draw();
                    }
                }


                m_renderProfiler.EndProfilingBlock();


                m_renderProfiler.StartProfilingBlock("Hemisphere");

                foreach (MyLight light in m_hemiLights)
                {
                    // compute bounding box
                    //Vector3 center = light.Position;// - light.Range * new Vector3(0,1,0);
                    //Vector3 extend = new Vector3(light.Range, light.Range, light.Range);
                    //m_lightBoundingBox.Min = center - extend;
                    //m_lightBoundingBox.Max = center + extend;
                    // Always cull clockwise (render inner parts of object), depth test is done is PS using light radius
                    if (Vector3.Dot(light.ReflectorDirection, MyCamera.Position - light.Position) > 0 && light.PointBoundingSphere.Contains(MyCamera.Position) == MinerWarsMath.ContainmentType.Contains)
                    {
                        RasterizerState.CullNone.Apply(); //zevnitr
                    }
                    else
                    {
                        RasterizerState.CullCounterClockwise.Apply(); //zvenku
                    }

                    effectPointLight.SetLightPosition(light.Position);
                    effectPointLight.SetLightIntensity(light.Intensity);
                    effectPointLight.SetSpecularLightColor(light.SpecularColor);
                    effectPointLight.SetFalloff(light.Falloff);

                    effectPointLight.SetLightRadius(light.Range);
                    effectPointLight.SetReflectorTexture(light.ReflectorTexture);
                    effectPointLight.SetLightColor(new Vector3(light.Color.X, light.Color.Y, light.Color.Z));
                    effectPointLight.SetTechnique(effectPointLight.DefaultHemisphereTechnique);

                    Matrix world = Matrix.CreateScale(light.Range) * Matrix.CreateWorld(light.Position, light.ReflectorDirection, light.ReflectorUp);
                    MySimpleObjectDraw.DrawHemisphereForLight(effectPointLight, ref world, ref MyMath.Vector3One, 1);
                    light.Draw();

                    MyPerformanceCounter.PerCameraDraw.LightsCount++;
                }
                m_renderProfiler.EndProfilingBlock();


                m_renderProfiler.StartProfilingBlock("Spotlight");
                RenderSpotLights(m_spotLightRenderElements, effectPointLight);

                m_renderProfiler.EndProfilingBlock();

                if (EnableSpectatorReflector && DrawSpectatorReflector && SpectatorReflector != null && SpectatorReflector.LightOn && SpectatorReflector.ReflectorOn)
                {
                    SpectatorReflector.ReflectorDirection = MyCamera.ForwardVector;
                    SpectatorReflector.ReflectorUp        = MyCamera.UpVector;
                    SpectatorReflector.SetPosition(MyCamera.Position);

                    effectPointLight.SetLightPosition(SpectatorReflector.Position);
                    effectPointLight.SetReflectorTexture(null);
                    effectPointLight.SetReflectorDirection(SpectatorReflector.ReflectorDirection);
                    effectPointLight.SetReflectorConeMaxAngleCos(1 - SpectatorReflector.ReflectorConeMaxAngleCos);
                    effectPointLight.SetReflectorColor(SpectatorReflector.ReflectorColor);
                    effectPointLight.SetReflectorRange(SpectatorReflector.ReflectorRange);
                    effectPointLight.SetCameraPosition(MyCamera.Position);

                    // Special case, for camera reflector
                    effectPointLight.SetReflectorIntensity(MyMinerShipConstants.MINER_SHIP_NEAR_REFLECTOR_INTENSITY * MySmallShip.ReflectorIntensityMultiplier);
                    effectPointLight.SetReflectorFalloff(MyMinerShipConstants.MINER_SHIP_NEAR_REFLECTOR_FALLOFF);

                    effectPointLight.SetTechnique(effectPointLight.DefaultSpotTechnique);
                    MySimpleObjectDraw.DrawConeForLight(effectPointLight, SpectatorReflector.SpotWorld);


                    // Always cull clockwise (render inner parts of object), depth test is done is PS using light radius
                    RasterizerState.CullClockwise.Apply();

                    effectPointLight.SetLightIntensity(MyMinerShipConstants.MINER_SHIP_NEAR_LIGHT_INTENSITY);
                    effectPointLight.SetSpecularLightColor(Color.White.ToVector3());
                    effectPointLight.SetFalloff(1.0f);

                    effectPointLight.SetLightRadius(MyMinerShipConstants.MINER_SHIP_NEAR_LIGHT_RANGE);
                    effectPointLight.SetLightColor(new Color(MyReflectorConstants.SHORT_REFLECTOR_LIGHT_COLOR).ToVector3());
                    effectPointLight.SetTechnique(effectPointLight.DefaultSpotTechnique);

                    MySimpleObjectDraw.DrawSphereForLight(effectPointLight, ref MyCamera.Position, MyMinerShipConstants.MINER_SHIP_NEAR_LIGHT_RANGE, ref MyMath.Vector3One, 1);
                    MyPerformanceCounter.PerCameraDraw.LightsCount++;
                }
            }

            DepthStencilState.None.Apply();
            RasterizerState.CullCounterClockwise.Apply();

            MyStateObjects.Sun_Combination_BlendState.Apply();

            m_renderProfiler.StartProfilingBlock("Sun light");

            if (EnableSun && CurrentRenderSetup.EnableSun.Value)
            {
                //Sun light
                MyEffectDirectionalLight effectDirectionalLight = MyRender.GetEffect(MyEffects.DirectionalLight) as MyEffectDirectionalLight;
                Texture diffuseRTSun = MyRender.GetRenderTarget(MyRenderTargets.Diffuse);
                effectDirectionalLight.SetNormalsRT(MyRender.GetRenderTarget(MyRenderTargets.Normals));
                effectDirectionalLight.SetDiffuseRT(diffuseRTSun);
                effectDirectionalLight.SetDepthsRT(MyRender.GetRenderTarget(MyRenderTargets.Depth));
                effectDirectionalLight.SetHalfPixelAndScale(diffuseRTSun.GetLevelDescription(0).Width, diffuseRTSun.GetLevelDescription(0).Height, GetScaleForViewport(diffuseRTSun));

                effectDirectionalLight.SetCameraMatrix(Matrix.Invert(MyCamera.ViewMatrix));

                effectDirectionalLight.SetAmbientMinimumAndIntensity(new Vector4(AmbientColor * AmbientMultiplier, EnvAmbientIntensity));
                effectDirectionalLight.SetTextureEnvironmentMain(MyEnvironmentMap.EnvironmentMainMap);
                effectDirectionalLight.SetTextureEnvironmentAux(MyEnvironmentMap.EnvironmentAuxMap);
                effectDirectionalLight.SetTextureAmbientMain(MyEnvironmentMap.AmbientMainMap);
                effectDirectionalLight.SetTextureAmbientAux(MyEnvironmentMap.AmbientAuxMap);
                effectDirectionalLight.SetTextureEnvironmentBlendFactor(MyEnvironmentMap.BlendFactor);
                effectDirectionalLight.SetCameraPosition(MyCamera.Position);

                //Set distance where no slope bias will be applied (because of cockpit artifacts)
                effectDirectionalLight.SetNearSlopeBiasDistance(3);

                effectDirectionalLight.ShowSplitColors(ShowCascadeSplits);
                effectDirectionalLight.SetShadowBias(0.0001f * MyRenderConstants.RenderQualityProfile.ShadowBiasMultiplier);
                effectDirectionalLight.SetSlopeBias(0.00002f);
                effectDirectionalLight.SetSlopeCascadeMultiplier(20.0f); //100 makes artifacts in prefabs

                MyRender.GetShadowRenderer().SetupShadowBaseEffect(effectDirectionalLight);

                effectDirectionalLight.SetLightDirection(-m_sun.Direction); //*-1 because of shader opts
                effectDirectionalLight.SetLightColorAndIntensity(new Vector3(m_sun.Color.X, m_sun.Color.Y, m_sun.Color.Z), m_sun.Intensity);
                effectDirectionalLight.SetBacklightColorAndIntensity(new Vector3(m_sun.BackColor.X, m_sun.BackColor.Y, m_sun.BackColor.Z), m_sun.BackIntensity);
                //m_sun.SpecularColor = {X:0,9137255 Y:0,6078432 Z:0,2078431} //nice yellow
                effectDirectionalLight.SetSpecularLightColor(m_sun.SpecularColor);
                effectDirectionalLight.EnableCascadeBlending(MyRenderConstants.RenderQualityProfile.EnableCascadeBlending);

                effectDirectionalLight.SetFrustumCorners(MyRender.GetShadowRenderer().GetFrustumCorners());

                effectDirectionalLight.SetEnableAmbientEnvironment(EnableEnvironmentMapAmbient && MyRenderConstants.RenderQualityProfile.EnableEnvironmentals && CurrentRenderSetup.EnableEnvironmentMapping.Value);
                effectDirectionalLight.SetEnableReflectionEnvironment(EnableEnvironmentMapReflection && MyRenderConstants.RenderQualityProfile.EnableEnvironmentals && CurrentRenderSetup.EnableEnvironmentMapping.Value);

                if (EnableShadows && MyRender.CurrentRenderSetup.ShadowRenderer != null)
                {
                    effectDirectionalLight.SetTechnique(effectDirectionalLight.DefaultTechnique);
                }
                else
                {
                    effectDirectionalLight.SetTechnique(effectDirectionalLight.DefaultWithoutShadowsTechnique);
                }

                MyGuiManager.GetFullscreenQuad().Draw(effectDirectionalLight);
            }
            m_renderProfiler.EndProfilingBlock();

            // Blend in background
            if (true) // blend background
            {
                m_renderProfiler.StartProfilingBlock("Blend background");
                if (MyFakes.RENDER_PREVIEWS_WITH_CORRECT_ALPHA)
                {
                    // for some reason the other option does not give 0 alpha for the background when rendering gui preview images
                    MyStateObjects.Additive_NoAlphaWrite_BlendState.Apply();
                }
                else
                {
                    MyStateObjects.NonPremultiplied_NoAlphaWrite_BlendState.Apply();
                    //BlendState.NonPremultiplied.Apply();
                }
                DepthStencilState.None.Apply();
                RasterizerState.CullCounterClockwise.Apply();

                MyEffectBlendLights effectBlendLights = MyRender.GetEffect(MyEffects.BlendLights) as MyEffectBlendLights;
                Texture             diffuseRT         = GetRenderTarget(MyRenderTargets.Diffuse);
                MyCamera.SetupBaseEffect(effectBlendLights, m_currentSetup.FogMultiplierMult);
                effectBlendLights.SetDiffuseTexture(diffuseRT);
                effectBlendLights.SetNormalTexture(GetRenderTarget(MyRenderTargets.Normals));
                effectBlendLights.SetDepthTexture(GetRenderTarget(MyRenderTargets.Depth));
                effectBlendLights.SetHalfPixel(diffuseRT.GetLevelDescription(0).Width, diffuseRT.GetLevelDescription(0).Height);
                effectBlendLights.SetScale(GetScaleForViewport(diffuseRT));
                effectBlendLights.SetBackgroundTexture(GetRenderTarget(MyRenderTargets.Auxiliary0));

                effectBlendLights.SetTechnique(effectBlendLights.DefaultTechnique);

                MyGuiManager.GetFullscreenQuad().Draw(effectBlendLights);
                m_renderProfiler.EndProfilingBlock();

                // Blend in emissive light, overwrite emissivity (alpha)
                m_renderProfiler.StartProfilingBlock("Copy emisivity");

                if (MyPostProcessHDR.RenderHDRThisFrame())
                {
                    MyStateObjects.AddEmissiveLight_BlendState.Apply();
                }
                else
                {
                    MyStateObjects.AddEmissiveLight_NoAlphaWrite_BlendState.Apply();
                }

                effectBlendLights.SetTechnique(effectBlendLights.CopyEmissivityTechnique);
                MyGuiManager.GetFullscreenQuad().Draw(effectBlendLights);


                bool showDebugLighting = false;

                if (ShowSpecularIntensity)
                {
                    effectBlendLights.SetTechnique(MyEffectBlendLights.Technique.OnlySpecularIntensity);
                    showDebugLighting = true;
                }
                else
                if (ShowSpecularPower)
                {
                    effectBlendLights.SetTechnique(MyEffectBlendLights.Technique.OnlySpecularPower);
                    showDebugLighting = true;
                }
                else
                if (ShowEmissivity)
                {
                    effectBlendLights.SetTechnique(MyEffectBlendLights.Technique.OnlyEmissivity);
                    showDebugLighting = true;
                }
                else
                if (ShowReflectivity)
                {
                    effectBlendLights.SetTechnique(MyEffectBlendLights.Technique.OnlyReflectivity);
                    showDebugLighting = true;
                }

                if (showDebugLighting)
                {
                    BlendState.Opaque.Apply();
                    MyGuiManager.GetFullscreenQuad().Draw(effectBlendLights);
                }

                m_renderProfiler.EndProfilingBlock();
            }

            //TakeScreenshot("Accumulated_lights", GetRenderTarget(MyRenderTargets.Lod0Depth), MyEffectScreenshot.ScreenshotTechniqueEnum.Default);

            /*TakeScreenshot("EnvironmentMap_1", GetRenderTargetCube(MyRenderTargets.EnvironmentCube), MyEffectScreenshot.ScreenshotTechniqueEnum.Default);
             * TakeScreenshot("EnvironmentMap_2", GetRenderTargetCube(MyRenderTargets.EnvironmentCubeAux), MyEffectScreenshot.ScreenshotTechniqueEnum.Default);
             * TakeScreenshot("AmbientMap_1", GetRenderTargetCube(MyRenderTargets.AmbientCube), MyEffectScreenshot.ScreenshotTechniqueEnum.Default);
             * TakeScreenshot("AmbientMap_2", GetRenderTargetCube(MyRenderTargets.AmbientCubeAux), MyEffectScreenshot.ScreenshotTechniqueEnum.Default);
             */
            m_renderProfiler.EndProfilingBlock();
        }