internal void LoadContent()
 {
     foreach (var entry in m_bitmapInfoByID)
     {
         m_bitmapTextureById[entry.Key] = MyTextures.GetTexture(Path.Combine(m_fontDirectory, entry.Value.strFilename), MyTextureEnum.GUI, true);
     }
 }
        internal unsafe void RecordCommands(MyRenderableProxy proxy, VertexBufferId stream, int voxelMatId)
        {
            if (stream == VertexBufferId.NULL)
            {
                return;
            }

            var foliageType = MyVoxelMaterials1.Table[voxelMatId].FoliageType;

            MyMapping mapping = MyMapping.MapDiscard(RC.DeviceContext, proxy.ObjectBuffer);

            mapping.WriteAndPosition(ref proxy.NonVoxelObjectData);
            mapping.WriteAndPosition(ref proxy.CommonObjectData);
            mapping.Unmap();

            RC.SetCB(MyCommon.OBJECT_SLOT, proxy.ObjectBuffer);

            RC.SetGS(m_GS[foliageType]);
            RC.SetPS(m_PS[foliageType]);

            if (MyVoxelMaterials1.Table[voxelMatId].FoliageColorTextureArray != null)
            {
                RC.BindRawSRV(0, MyVoxelMaterials1.Table[voxelMatId].FoliageColorTextureArray.ShaderView);
                RC.BindRawSRV(1, MyVoxelMaterials1.Table[voxelMatId].FoliageNormalTextureArray.ShaderView);
            }
            else
            {
                RC.BindRawSRV(0, MyTextures.GetView(MyTextures.GetTexture(MyVoxelMaterials1.Table[voxelMatId].FoliageArray_Texture, MyTextureEnum.COLOR_METAL, true)));
                RC.BindRawSRV(1, MyTextures.GetView(MyTextures.GetTexture(MyVoxelMaterials1.Table[voxelMatId].FoliageArray_NormalTexture, MyTextureEnum.NORMALMAP_GLOSS, true)));
            }

            RC.SetVB(0, stream.Buffer, stream.Stride);
            Context.DrawAuto();
            RC.Stats.DrawAuto++;
        }
        static void BindResourcesCommon()
        {
            RC.SetRS(MyRender11.m_nocullRasterizerState);
            RC.BindRawSRV(104, m_SB);
            RC.SetCB(2, m_cbCustomProjections);
            if (MyStereoRender.Enable && MyStereoRender.EnableUsingStencilMask)
            {
                RC.SetDS(MyDepthStencilState.StereoDefaultDepthState);
            }
            else
            {
                RC.SetDS(MyDepthStencilState.DefaultDepthState);
            }

            RC.SetCB(4, MyRender11.DynamicShadows.ShadowCascades.CascadeConstantBuffer);
            RC.DeviceContext.VertexShader.SetSampler(MyCommon.SHADOW_SAMPLER_SLOT, SamplerStates.m_shadowmap);
            RC.DeviceContext.VertexShader.SetShaderResource(MyCommon.CASCADES_SM_SLOT, MyRender11.DynamicShadows.ShadowCascades.CascadeShadowmapArray.SRV);
            RC.DeviceContext.VertexShader.SetSamplers(0, SamplerStates.StandardSamplers);

            RC.DeviceContext.VertexShader.SetShaderResource(MyCommon.SKYBOX_IBL_SLOT,
                                                            MyRender11.IsIntelBrokenCubemapsWorkaround ? MyTextures.GetView(MyTextures.IntelFallbackCubeTexId) : MyEnvironmentProbe.Instance.cubemapPrefiltered.SRV);
            RC.DeviceContext.VertexShader.SetShaderResource(MyCommon.SKYBOX2_IBL_SLOT,
                                                            MyTextures.GetView(MyTextures.GetTexture(MyRender11.Environment.NightSkyboxPrefiltered, MyTextureEnum.CUBEMAP, true)));

            RC.SetVB(0, m_VB.Buffer, m_VB.Stride);
            RC.SetIB(m_IB.Buffer, m_IB.Format);
            RC.SetIL(m_inputLayout);
        }
 internal static void RequestResources(ref MyMeshMaterialInfo info)
 {
     MyTextures.GetTexture(info.ColorMetal_Texture, info.ContentPath, MyTextureEnum.COLOR_METAL);
     MyTextures.GetTexture(info.NormalGloss_Texture, info.ContentPath, MyTextureEnum.NORMALMAP_GLOSS);
     MyTextures.GetTexture(info.Extensions_Texture, info.ContentPath, MyTextureEnum.EXTENSIONS);
     MyTextures.GetTexture(info.Alphamask_Texture, info.ContentPath, MyTextureEnum.ALPHAMASK);
 }
        internal unsafe static void RebuildMaterialFoliageTable()
        {
            var array = stackalloc MaterialFoliageConstantsElem[256];
            int N     = Table.Length;

            for (int i = 0; i < N; i++)
            {
                uint arraySize = 0;

                if (Table[i].FoliageColorTextureArray != null)
                {
                    arraySize = (uint)Table[i].FoliageColorTextureArray.ArrayLen;
                }
                else
                {
                    var arrayTexId = MyTextures.GetTexture(Table[i].FoliageArray_Texture, MyTextureEnum.COLOR_METAL, true);
                    arraySize = (uint)((Texture2D)MyTextures.Textures.Data[arrayTexId.Index].Resource).Description.ArraySize;
                }

                array[i] = new MaterialFoliageConstantsElem {
                    Scale       = Table[i].FoliageScale,
                    ScaleVar    = Table[i].FoliageScaleVariation,
                    TexturesNum = arraySize
                };
            }
            var mapping = MyMapping.MapDiscard(MyCommon.MaterialFoliageTableConstants);

            for (int arrayIndex = 0; arrayIndex < N; ++arrayIndex)
            {
                mapping.WriteAndPosition(ref array[arrayIndex]);
            }
            mapping.Unmap();
        }
        internal unsafe void RecordCommands(MyRenderableProxy proxy, VertexBufferId stream, int voxelMatId)
        {
            //var worldMat = proxy.WorldMatrix;
            //worldMat.Translation -= MyEnvironment.CameraPosition;
            //proxy.ObjectData.LocalMatrix = worldMat;

            //var worldMatrix = Matrix.CreateTranslation(-MyEnvironment.CameraPosition);
            MyObjectData objectData = proxy.ObjectData;
            //objectData.LocalMatrix = worldMat;

            MyMapping mapping;

            mapping = MyMapping.MapDiscard(RC.Context, proxy.objectBuffer);
            void *ptr = &objectData;

            mapping.stream.Write(new IntPtr(ptr), 0, sizeof(MyObjectData));
            mapping.Unmap();

            RC.SetCB(MyCommon.OBJECT_SLOT, proxy.objectBuffer);

            RC.BindRawSRV(0, MyTextures.GetView(MyTextures.GetTexture(MyVoxelMaterials1.Table[voxelMatId].FoliageArray_Texture, MyTextureEnum.COLOR_METAL, true)));

            RC.SetVB(0, stream.Buffer, stream.Stride);
            Context.DrawAuto();
            RC.Stats.DrawAuto++;
        }
        internal static void CreateCloudLayer(
            uint ID,
            Vector3D centerPoint,
            double altitude,
            double minScaledAltitude,
            bool scalingEnabled,
            double fadeOutRelativeAltitudeStart,
            double fadeOutRelativeAltitudeEnd,
            float applyFogRelativeDistance,
            double maxPlanetHillRadius,
            string model,
            List <string> textures,
            Vector3D rotationAxis,
            float angularVelocity,
            float radiansAroundAxis)
        {
            MeshId mesh = MyMeshes.GetMeshId(X.TEXT(model));

            MyCloudLayer.MyCloudTextureInfo textureInfo;
            if (textures != null && textures.Count > 0) // TODO: Multiple textures
            {
                var cmTexture          = textures[0].Insert(textures[0].LastIndexOf('.'), "_cm");
                var alphaTexture       = textures[0].Insert(textures[0].LastIndexOf('.'), "_alphamask");
                var normalGlossTexture = textures[0].Insert(textures[0].LastIndexOf('.'), "_ng");
                textureInfo = new MyCloudLayer.MyCloudTextureInfo
                {
                    ColorMetalTexture  = MyTextures.GetTexture(cmTexture, MyTextureEnum.COLOR_METAL),
                    AlphaTexture       = MyTextures.GetTexture(alphaTexture, MyTextureEnum.ALPHAMASK),
                    NormalGlossTexture = MyTextures.GetTexture(normalGlossTexture, MyTextureEnum.NORMALMAP_GLOSS),
                };
            }
            else
            {
                textureInfo = new MyCloudLayer.MyCloudTextureInfo
                {
                    ColorMetalTexture  = MyTextures.GetTexture(MyMeshes.GetMeshPart(mesh, 0, 0).Info.Material.Info.ColorMetal_Texture.ToString(), MyTextureEnum.COLOR_METAL),
                    AlphaTexture       = MyTextures.GetTexture(MyMeshes.GetMeshPart(mesh, 0, 0).Info.Material.Info.Alphamask_Texture.ToString(), MyTextureEnum.ALPHAMASK),
                    NormalGlossTexture = MyTextures.GetTexture(MyMeshes.GetMeshPart(mesh, 0, 0).Info.Material.Info.NormalGloss_Texture.ToString(), MyTextureEnum.NORMALMAP_GLOSS),
                }
            };

            m_cloudLayers.Add(ID, new MyCloudLayer
            {
                CenterPoint                  = centerPoint,
                Altitude                     = altitude,
                MinScaledAltitude            = minScaledAltitude,
                ScalingEnabled               = scalingEnabled,
                FadeOutRelativeAltitudeStart = fadeOutRelativeAltitudeStart,
                FadeOutRelativeAltitudeEnd   = fadeOutRelativeAltitudeEnd,
                ApplyFogRelativeDistance     = applyFogRelativeDistance,
                MaxPlanetHillRadius          = maxPlanetHillRadius,
                Mesh            = mesh,
                TextureInfo     = textureInfo,
                RotationAxis    = rotationAxis,
                AngularVelocity = angularVelocity,
            });
            m_modifiableCloudLayerData.Add(ID, new MyModifiableCloudLayerData {
                RadiansAroundAxis = radiansAroundAxis, LastGameplayFrameUpdate = MyRender11.Settings.GameplayFrame
            });
        }
        internal unsafe void RecordCommands(MyRenderableProxy proxy, VertexBufferId stream, int voxelMatId)
        {
            MyObjectData objectData = proxy.ObjectData;

            var foliageType = MyVoxelMaterials1.Table[voxelMatId].FoliageType;

            MyMapping mapping;

            mapping = MyMapping.MapDiscard(RC.Context, proxy.ObjectBuffer);
            void *ptr = &objectData;

            mapping.stream.Write(new IntPtr(ptr), 0, sizeof(MyObjectData));
            mapping.Unmap();

            RC.SetCB(MyCommon.OBJECT_SLOT, proxy.ObjectBuffer);

            RC.SetGS(m_GS[foliageType]);
            RC.SetPS(m_PS[foliageType]);

            if (MyVoxelMaterials1.Table[voxelMatId].FoliageColorTextureArray != null)
            {
                RC.BindRawSRV(0, MyVoxelMaterials1.Table[voxelMatId].FoliageColorTextureArray.ShaderView);
                RC.BindRawSRV(1, MyVoxelMaterials1.Table[voxelMatId].FoliageNormalTextureArray.ShaderView);
            }
            else
            {
                RC.BindRawSRV(0, MyTextures.GetView(MyTextures.GetTexture(MyVoxelMaterials1.Table[voxelMatId].FoliageArray_Texture, MyTextureEnum.COLOR_METAL, true)));
                RC.BindRawSRV(1, MyTextures.GetView(MyTextures.GetTexture(MyVoxelMaterials1.Table[voxelMatId].FoliageArray_NormalTexture, MyTextureEnum.NORMALMAP_GLOSS, true)));
            }

            RC.SetVB(0, stream.Buffer, stream.Stride);
            Context.DrawAuto();
            RC.Stats.DrawAuto++;
        }
 internal static void PreloadTexture(string texture)
 {
     if (!m_preloaded.Contains(texture))
     {
         m_preloaded.Add(texture);
         //MyTextureManager.GetTexture(texture);
         MyTextures.GetTexture(texture, MyTextureEnum.GUI, true);
     }
 }
Exemple #10
0
 internal static void OnResourcesRequesting()
 {
     Materials[MyStringId.NullOrEmpty] = new MyDecalMaterial
     {
         DecalType = MyScreenDecalType.ScreenDecalColor,
         //NormalmapTexture = MyTextures.GetTexture("Textures/decals/impact_1x5_ng.dds", MyTextureEnum.NORMALMAP_GLOSS),
         NormalmapTexture  = TexId.NULL,
         ColorMetalTexture = MyTextures.GetTexture("Textures/decals/impact_1_cm.dds", MyTextureEnum.COLOR_METAL),
         AlphamaskTexture  = MyTextures.GetTexture("Textures/decals/impact_1_alphamask.dds", MyTextureEnum.ALPHAMASK),
     };
 }
        internal static void RequestResources(ref MyVoxelMaterialDetailSet set)
        {
            MyTextures.GetTexture(set.ColorMetalXZnY_Texture, null, MyTextureEnum.COLOR_METAL);
            MyTextures.GetTexture(set.ColorMetalpY_Texture, null, MyTextureEnum.COLOR_METAL);

            MyTextures.GetTexture(set.NormalGlossXZnY_Texture, null, MyTextureEnum.NORMALMAP_GLOSS);
            MyTextures.GetTexture(set.NormalGlosspY_Texture, null, MyTextureEnum.NORMALMAP_GLOSS);

            MyTextures.GetTexture(set.ExtXZnY_Texture, null, MyTextureEnum.EXTENSIONS);
            MyTextures.GetTexture(set.ExtpY_Texture, null, MyTextureEnum.EXTENSIONS);
        }
 internal static void OnResourcesRequesting()
 {
     foreach (var id in MaterialQueryResourcesTable)
     {
         // query all textures
         MyVoxelMaterialDetailSet.RequestResources(ref Table[id].Near);
         MyVoxelMaterialDetailSet.RequestResources(ref Table[id].Far1);
         MyVoxelMaterialDetailSet.RequestResources(ref Table[id].Far2);
         //MyTextureManager.GetTexture(Table[id].FoliageArray_Texture);
         MyTextures.GetTexture(Table[id].FoliageArray_Texture, MyTextureEnum.COLOR_METAL);
     }
 }
Exemple #13
0
        internal static void RegisterMaterials(List <string> names, List <MyDecalMaterialDesc> descriptions)
        {
            Debug.Assert(names.Count == descriptions.Count);

            for (int i = 0; i < names.Count; ++i)
            {
                Materials[MyStringId.GetOrCompute(names[i])] = new MyDecalMaterial {
                    DecalType         = descriptions[i].DecalType,
                    NormalmapTexture  = MyTextures.GetTexture(descriptions[i].NormalmapTexture, MyTextureEnum.NORMALMAP_GLOSS),
                    ColorMetalTexture = MyTextures.GetTexture(descriptions[i].ColorMetalTexture, MyTextureEnum.COLOR_METAL),
                    AlphamaskTexture  = MyTextures.GetTexture(descriptions[i].AlphamaskTexture, MyTextureEnum.ALPHAMASK),
                };
            }
        }
Exemple #14
0
        private static void ParseAtlasDescription(string textureDir, string atlasFile, out Dictionary <string, Element> atlasDict)
        {
            atlasDict = new Dictionary <string, Element>();
            try
            {
                //var atlas = new MyTextureAtlas(64);
                var fsPath = Path.Combine(MyFileSystem.ContentPath, atlasFile);
                using (var file = MyFileSystem.OpenRead(fsPath))
                    using (StreamReader sr = new StreamReader(file))
                    {
                        while (!sr.EndOfStream)
                        {
                            string line = sr.ReadLine();

                            if (line.StartsWith("#"))
                            {
                                continue;
                            }
                            if (line.Trim(' ').Length == 0)
                            {
                                continue;
                            }

                            string[] parts = line.Split(new char[] { ' ', '\t', ',' }, StringSplitOptions.RemoveEmptyEntries);

                            string name      = parts[0];
                            string atlasName = parts[1];

                            Vector4 uv = new Vector4(
                                Convert.ToSingle(parts[4], System.Globalization.CultureInfo.InvariantCulture),
                                Convert.ToSingle(parts[5], System.Globalization.CultureInfo.InvariantCulture),
                                Convert.ToSingle(parts[7], System.Globalization.CultureInfo.InvariantCulture),
                                Convert.ToSingle(parts[8], System.Globalization.CultureInfo.InvariantCulture));

                            name = textureDir + System.IO.Path.GetFileName(name);
                            var atlasTexture = textureDir + atlasName;

                            var element = new Element();
                            element.TextureId     = MyTextures.GetTexture(atlasTexture, MyTextureEnum.GUI, true);
                            element.UvOffsetScale = uv;
                            atlasDict[name]       = element;
                        }
                    }
            }
            catch (Exception e)
            {
                MyLog.Default.WriteLine("Warning: " + e.ToString());
            }
        }
Exemple #15
0
        internal static MyTextureArray FromStringArray(string[] mergeList, MyTextureEnum type, string debugName)
        {
            if (mergeList == null)
            {
                return(null);
            }

            TexId[] ids = new TexId[mergeList.Length];
            for (int i = 0; i < ids.Length; i++)
            {
                ids[i] = MyTextures.GetTexture(mergeList[i], type, true);
            }

            return(new MyTextureArray(ids, debugName));
        }
 internal static void PrepareArrays(ref MyVoxelMaterialDetailSet set)
 {
     set.ColorMetalArray = new MyTextureArray(
         new[] {
         MyTextures.GetTexture(set.ColorMetalXZnY_Texture, null, MyTextureEnum.COLOR_METAL),
         MyTextures.GetTexture(set.ColorMetalpY_Texture, null, MyTextureEnum.COLOR_METAL)
     });
     set.NormalGlossArray = new MyTextureArray(
         new[] {
         MyTextures.GetTexture(set.NormalGlossXZnY_Texture, null, MyTextureEnum.NORMALMAP_GLOSS),
         MyTextures.GetTexture(set.NormalGlosspY_Texture, null, MyTextureEnum.NORMALMAP_GLOSS)
     });
     set.ExtArray = new MyTextureArray(
         new[] {
         MyTextures.GetTexture(set.ExtXZnY_Texture, null, MyTextureEnum.EXTENSIONS),
         MyTextures.GetTexture(set.ExtpY_Texture, null, MyTextureEnum.EXTENSIONS)
     });
 }
        internal static MyMaterialProxy_2 CreateProxy(ref MyMeshMaterialInfo info)
        {
            var A = MyTextures.GetTexture(info.ColorMetal_Texture, info.ContentPath, MyTextureEnum.COLOR_METAL);
            var B = MyTextures.GetTexture(info.NormalGloss_Texture, info.ContentPath, MyTextureEnum.NORMALMAP_GLOSS);
            var C = MyTextures.GetTexture(info.Extensions_Texture, info.ContentPath, MyTextureEnum.EXTENSIONS);
            var D = MyTextures.GetTexture(info.Alphamask_Texture, info.ContentPath, MyTextureEnum.ALPHAMASK);

            var materialSrvs = new MySrvTable
            {
                BindFlag  = MyBindFlag.BIND_PS,
                StartSlot = 0,
                SRVs      = new IShaderResourceBindable[] { A, B, C, D },
                Version   = info.Id.GetHashCode()
            };

            return
                (new MyMaterialProxy_2 {
                MaterialSRVs = materialSrvs
            });
        }
        internal static void RebuildMaterialFoliageTable()
        {
            var array = new MaterialFoliageConstantsElem[256];
            int N     = Table.Length;

            for (int i = 0; i < N; i++)
            {
                var arrayTexId = MyTextures.GetTexture(Table[i].FoliageArray_Texture, MyTextureEnum.COLOR_METAL, true);

                array[i] = new MaterialFoliageConstantsElem {
                    Scale       = Table[i].FoliageScale,
                    ScaleVar    = Table[i].FoliageScaleVariation,
                    TexturesNum = (uint)((Texture2D)MyTextures.Textures.Data[arrayTexId.Index].Resource).Description.ArraySize
                };
            }
            var mapping = MyMapping.MapDiscard(MyCommon.MaterialFoliageTableConstants);

            mapping.stream.WriteRange(array, 0, N);
            mapping.Unmap();
        }
        public static void RegisterMaterials(Dictionary <string, List <MyDecalMaterialDesc> > descriptions)
        {
            m_materials.Clear();
            foreach (var pair in descriptions)
            {
                List <MyDecalTextures> list = new List <MyDecalTextures>();
                foreach (var desc in pair.Value)
                {
                    list.Add(new MyDecalTextures()
                    {
                        DecalType         = desc.DecalType,
                        NormalmapTexture  = MyTextures.GetTexture(desc.NormalmapTexture, MyTextureEnum.NORMALMAP_GLOSS),
                        ColorMetalTexture = MyTextures.GetTexture(desc.ColorMetalTexture, MyTextureEnum.COLOR_METAL),
                        AlphamaskTexture  = MyTextures.GetTexture(desc.AlphamaskTexture, MyTextureEnum.ALPHAMASK),
                        ExtensionsTexture = MyTextures.GetTexture(desc.ExtensionsTexture, MyTextureEnum.EXTENSIONS),
                    });
                }

                m_materials[X.TEXT_(pair.Key)] = list;
            }
        }
        internal static MyMaterialProxy_2 CreateProxy(ref MyMeshMaterialInfo info)
        {
            var A = MyTextures.GetTexture(info.ColorMetal_Texture, info.ContentPath, MyTextureEnum.COLOR_METAL);
            var B = MyTextures.GetTexture(info.NormalGloss_Texture, info.ContentPath, MyTextureEnum.NORMALMAP_GLOSS);
            var C = MyTextures.GetTexture(info.Extensions_Texture, info.ContentPath, MyTextureEnum.EXTENSIONS);
            var D = MyTextures.GetTexture(info.Alphamask_Texture, info.ContentPath, MyTextureEnum.ALPHAMASK);

            return
                (new MyMaterialProxy_2 {
                MaterialSRVs =
                {
                    BindFlag  = MyBindFlag.BIND_PS,
                    StartSlot =                  0,
                    SRVs      = new ShaderResourceView[] {
                        MyTextures.Views[A.Index],
                        MyTextures.Views[B.Index],
                        MyTextures.Views[C.Index],
                        MyTextures.Views[D.Index]
                    },
                    Version   = info.Id.GetHashCode()
                }
            });
        }
Exemple #21
0
        internal unsafe static void RunForwardPostprocess(RenderTargetView rt, ShaderResourceView depth, ref Matrix viewMatrix, uint?atmosphereId)
        {
            var transpose = Matrix.Transpose(viewMatrix);
            var mapping   = MyMapping.MapDiscard(RC.DeviceContext, MyCommon.ProjectionConstants);

            mapping.WriteAndPosition(ref transpose);
            mapping.Unmap();

            RC.SetCB(MyCommon.FRAME_SLOT, MyCommon.FrameConstants);
            RC.SetCB(MyCommon.PROJECTION_SLOT, MyCommon.ProjectionConstants);

            RC.DeviceContext.OutputMerger.SetTargets(rt);
            RC.DeviceContext.PixelShader.SetShaderResource(0, depth);
            RC.DeviceContext.PixelShader.SetShaderResource(MyCommon.SKYBOX_SLOT, MyTextures.GetView(MyTextures.GetTexture(MyEnvironment.DaySkybox, MyTextureEnum.CUBEMAP, true)));
            RC.DeviceContext.PixelShader.SetShaderResource(MyCommon.SKYBOX2_SLOT, MyTextures.GetView(MyTextures.GetTexture(MyEnvironment.NightSkybox, MyTextureEnum.CUBEMAP, true)));
            RC.DeviceContext.PixelShader.SetSamplers(0, MyRender11.StandardSamplers);
            RC.DeviceContext.PixelShader.Set(m_ps);

            MyScreenPass.DrawFullscreenQuad(new MyViewport(256, 256));

            if (atmosphereId != null)
            {
                var atmosphere = MyAtmosphereRenderer.GetAtmosphere(atmosphereId.Value);
                var constants  = new AtmosphereConstants();
                //TODO(AF) These values are computed in MyAtmosphere as well. Find a way to remove the duplication
                var worldMatrix = atmosphere.WorldMatrix;
                worldMatrix.Translation -= MyEnvironment.CameraPosition;

                double distance       = worldMatrix.Translation.Length();
                double atmosphereTop  = atmosphere.AtmosphereRadius * atmosphere.Settings.AtmosphereTopModifier * atmosphere.PlanetScaleFactor * atmosphere.Settings.RayleighTransitionModifier;
                float  rayleighHeight = atmosphere.Settings.RayleighHeight;
                float  t = 0.0f;
                if (distance > atmosphereTop)
                {
                    if (distance > atmosphereTop * 2.0f)
                    {
                        t = 1.0f;
                    }
                    else
                    {
                        t = (float)((distance - atmosphereTop) / atmosphereTop);
                    }
                }
                rayleighHeight = MathHelper.Lerp(atmosphere.Settings.RayleighHeight, atmosphere.Settings.RayleighHeightSpace, t);


                constants.PlanetCentre           = (Vector3)worldMatrix.Translation;
                constants.AtmosphereRadius       = atmosphere.AtmosphereRadius * atmosphere.Settings.AtmosphereTopModifier;
                constants.GroundRadius           = atmosphere.PlanetRadius * 1.01f * atmosphere.Settings.SeaLevelModifier;
                constants.BetaRayleighScattering = atmosphere.BetaRayleighScattering / atmosphere.Settings.RayleighScattering;
                constants.BetaMieScattering      = atmosphere.BetaMieScattering / atmosphere.Settings.MieColorScattering;
                constants.HeightScaleRayleighMie = atmosphere.HeightScaleRayleighMie * new Vector2(rayleighHeight, atmosphere.Settings.MieHeight);
                constants.MieG = atmosphere.Settings.MieG;
                constants.PlanetScaleFactor     = atmosphere.PlanetScaleFactor;
                constants.AtmosphereScaleFactor = atmosphere.AtmosphereScaleFactor;
                constants.Intensity             = atmosphere.Settings.Intensity;
                constants.FogIntensity          = atmosphere.Settings.FogIntensity;

                var cb = MyCommon.GetObjectCB(sizeof(AtmosphereConstants));

                mapping = MyMapping.MapDiscard(RC.DeviceContext, cb);
                mapping.WriteAndPosition(ref constants);
                mapping.Unmap();

                RC.SetBS(MyRender11.BlendAdditive);
                RC.SetCB(2, cb);
                RC.DeviceContext.PixelShader.SetShaderResource(2, MyAtmosphereRenderer.GetAtmosphereLuts(atmosphereId.Value).TransmittanceLut.ShaderView);
                RC.DeviceContext.PixelShader.Set(m_atmosphere);

                MyScreenPass.DrawFullscreenQuad(new MyViewport(MyEnvironmentProbe.CubeMapResolution, MyEnvironmentProbe.CubeMapResolution));
            }

            RC.DeviceContext.OutputMerger.SetTargets(null as RenderTargetView);
        }
        internal unsafe static void Render(MyBindableResource dst, MyBindableResource depth, MyBindableResource depthRead)
        {
            MyRender11.GetRenderProfiler().StartProfilingBlock("Gather");
            Gather();
            MyRender11.GetRenderProfiler().EndProfilingBlock();


            MyRender11.GetRenderProfiler().StartProfilingBlock("Draw");
            TransferData();

            RC.SetupScreenViewport();
            RC.BindDepthRT(depth, DepthStencilAccess.ReadOnly, dst);
            RC.SetBS(MyRender11.BlendAlphaPremult);
            RC.SetRS(MyRender11.m_nocullRasterizerState);
            RC.BindRawSRV(104, m_SB.Srv);
            RC.BindSRV(1, depthRead);
            RC.SetCB(2, MyCommon.GetObjectCB(sizeof(Matrix) * MaxCustomProjections));
            RC.SetDS(MyDepthStencilState.DefaultDepthState);

            RC.SetCB(4, MyShadows.m_csmConstants);
            RC.Context.VertexShader.SetSampler(MyCommon.SHADOW_SAMPLER_SLOT, MyRender11.m_shadowmapSamplerState);
            RC.Context.VertexShader.SetShaderResource(MyCommon.CASCADES_SM_SLOT, MyShadows.m_cascadeShadowmapArray.ShaderView);
            RC.Context.VertexShader.SetSamplers(0, MyRender11.StandardSamplers);


            RC.Context.VertexShader.SetShaderResource(MyCommon.SKYBOX_IBL_SLOT, MyTextures.GetView(MyTextures.GetTexture(MyEnvironment.DaySkyboxPrefiltered, MyTextureEnum.CUBEMAP, true)));
            RC.Context.PixelShader.SetShaderResource(MyCommon.SKYBOX2_IBL_SLOT, MyTextures.GetView(MyTextures.GetTexture(MyEnvironment.NightSkyboxPrefiltered, MyTextureEnum.CUBEMAP, true)));

            RC.SetVB(0, m_VB.Buffer, m_VB.Stride);
            RC.SetIB(m_IB.Buffer, m_IB.Format);

            RC.SetIL(m_inputLayout);

            for (int i = 0; i < m_batches.Count; i++)
            {
                // first part of batches contain sorted billboards and they read depth
                // second part of batches contain unsorted billboards and they ignore depth
                // switch here:
                if (m_batches[i].Offset == m_sortedBillboardsNum)
                {
                    //RC.BindDepthRT(null, DepthStencilAccess.ReadOnly, dst);
                }

                if (m_batches[i].Lit)
                {
                    RC.SetVS(m_vsLit);
                    RC.SetPS(m_psLit);
                }
                else
                {
                    RC.SetVS(m_vs);
                    RC.SetPS(m_ps);
                }

                RC.BindRawSRV(0, m_batches[i].Texture);
                RC.Context.DrawIndexed(m_batches[i].Num * 6, m_batches[i].Offset * 6, 0);
            }

            RC.SetRS(null);
            m_batches.Clear();
            MyRender11.GetRenderProfiler().EndProfilingBlock();
        }
        private static void ProcessDrawMessage(MyRenderMessageBase drawMessage)
        {
            switch (drawMessage.MessageType)
            {
            case MyRenderMessageEnum.SpriteScissorPush:
            {
                var msg = drawMessage as MyRenderMessageSpriteScissorPush;

                MySpritesRenderer.ScissorStackPush(msg.ScreenRectangle);

                break;
            }

            case MyRenderMessageEnum.SpriteScissorPop:
            {
                MySpritesRenderer.ScissorStackPop();

                break;
            }

            case MyRenderMessageEnum.DrawSprite:
            {
                MyRenderMessageDrawSprite sprite = (MyRenderMessageDrawSprite)drawMessage;

                MySpritesRenderer.AddSingleSprite(MyTextures.GetTexture(sprite.Texture, MyTextureEnum.GUI, waitTillLoaded: sprite.WaitTillLoaded), sprite.Color, sprite.Origin, sprite.RightVector, sprite.SourceRectangle, sprite.DestinationRectangle);

                break;
            }

            case MyRenderMessageEnum.DrawSpriteNormalized:
            {
                MyRenderMessageDrawSpriteNormalized sprite = (MyRenderMessageDrawSpriteNormalized)drawMessage;

                var rotation = sprite.Rotation;
                if (sprite.RotationSpeed != 0)
                {
                    rotation += sprite.RotationSpeed * (float)(MyRender11.CurrentDrawTime - MyRender11.CurrentUpdateTime).Seconds;
                }

                Vector2 rightVector = rotation != 0f ? new Vector2((float)Math.Cos(rotation), (float)Math.Sin(rotation)) : sprite.RightVector;

                int safeGuiSizeY = MyRender11.ResolutionI.Y;
                int safeGuiSizeX = (int)(safeGuiSizeY * 1.3333f);             //  This will mantain same aspect ratio for GUI elements

                var   safeGuiRectangle = new VRageMath.Rectangle(MyRender11.ResolutionI.X / 2 - safeGuiSizeX / 2, 0, safeGuiSizeX, safeGuiSizeY);
                var   safeScreenScale  = (float)safeGuiSizeY / MyRenderGuiConstants.REFERENCE_SCREEN_HEIGHT;
                float fixedScale       = sprite.Scale * safeScreenScale;

                var tex = MyTextures.GetTexture(sprite.Texture, MyTextureEnum.GUI, true);

                var normalizedCoord = sprite.NormalizedCoord;
                var screenCoord     = new Vector2(safeGuiRectangle.Left + safeGuiRectangle.Width * normalizedCoord.X,
                                                  safeGuiRectangle.Top + safeGuiRectangle.Height * normalizedCoord.Y);

                var sizeInPixels       = MyTextures.GetSize(tex);
                var sizeInPixelsScaled = sizeInPixels * fixedScale;

                Vector2 alignedScreenCoord = screenCoord;
                var     drawAlign          = sprite.DrawAlign;

                if (drawAlign == MyGuiDrawAlignEnum.HORISONTAL_LEFT_AND_VERTICAL_TOP)
                {
                    //  Nothing to do as position is already at this point
                }
                else if (drawAlign == MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER)
                {
                    //  Move position to the texture center
                    alignedScreenCoord -= sizeInPixelsScaled / 2.0f;
                }
                else if (drawAlign == MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_TOP)
                {
                    alignedScreenCoord.X -= sizeInPixelsScaled.X / 2.0f;
                }
                else if (drawAlign == MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_BOTTOM)
                {
                    alignedScreenCoord.X -= sizeInPixelsScaled.X / 2.0f;
                    alignedScreenCoord.Y -= sizeInPixelsScaled.Y;
                }
                else if (drawAlign == MyGuiDrawAlignEnum.HORISONTAL_RIGHT_AND_VERTICAL_BOTTOM)
                {
                    alignedScreenCoord -= sizeInPixelsScaled;
                }
                else if (drawAlign == MyGuiDrawAlignEnum.HORISONTAL_LEFT_AND_VERTICAL_CENTER)
                {
                    alignedScreenCoord.Y -= sizeInPixelsScaled.Y / 2.0f;
                }
                else if (drawAlign == MyGuiDrawAlignEnum.HORISONTAL_RIGHT_AND_VERTICAL_CENTER)
                {
                    alignedScreenCoord.X -= sizeInPixelsScaled.X;
                    alignedScreenCoord.Y -= sizeInPixelsScaled.Y / 2.0f;
                }
                else if (drawAlign == MyGuiDrawAlignEnum.HORISONTAL_LEFT_AND_VERTICAL_BOTTOM)
                {
                    alignedScreenCoord.Y -= sizeInPixelsScaled.Y;        // *0.75f;
                }
                else if (drawAlign == MyGuiDrawAlignEnum.HORISONTAL_RIGHT_AND_VERTICAL_TOP)
                {
                    alignedScreenCoord.X -= sizeInPixelsScaled.X;
                }

                screenCoord = alignedScreenCoord;

                var     rect = new RectangleF(screenCoord.X, screenCoord.Y, fixedScale * sizeInPixels.X, fixedScale * sizeInPixels.Y);
                Vector2 origin;
                if (sprite.OriginNormalized.HasValue)
                {
                    origin = sprite.OriginNormalized.Value * sizeInPixels;
                }
                else
                {
                    origin = sizeInPixels / 2;
                }

                sprite.OriginNormalized = sprite.OriginNormalized ?? new Vector2(0.5f);

                MySpritesRenderer.AddSingleSprite(MyTextures.GetTexture(sprite.Texture, MyTextureEnum.GUI, waitTillLoaded: sprite.WaitTillLoaded), sprite.Color, origin, rightVector, null, rect);

                break;
            }


            case MyRenderMessageEnum.DrawSpriteAtlas:
            {
                MyRenderMessageDrawSpriteAtlas sprite = (MyRenderMessageDrawSpriteAtlas)drawMessage;

                var tex         = MyTextures.GetTexture(sprite.Texture, MyTextureEnum.GUI, true);
                var textureSize = MyTextures.GetSize(tex);

                Rectangle?sourceRect = new Rectangle(
                    (int)(textureSize.X * sprite.TextureOffset.X),
                    (int)(textureSize.Y * sprite.TextureOffset.Y),
                    (int)(textureSize.X * sprite.TextureSize.X),
                    (int)(textureSize.Y * sprite.TextureSize.Y));

                VRageMath.RectangleF destRect = new VRageMath.RectangleF(
                    (sprite.Position.X) * sprite.Scale.X,
                    (sprite.Position.Y) * sprite.Scale.Y,
                    sprite.HalfSize.X * sprite.Scale.X * 2,
                    sprite.HalfSize.Y * sprite.Scale.Y * 2);

                Vector2 origin = new Vector2(textureSize.X * sprite.TextureSize.X * 0.5f, textureSize.Y * sprite.TextureSize.Y * 0.5f);

                MySpritesRenderer.AddSingleSprite(MyTextures.GetTexture(sprite.Texture, MyTextureEnum.GUI, true), sprite.Color, origin, sprite.RightVector, sourceRect, destRect);

                break;
            }

            case MyRenderMessageEnum.DrawString:
            {
                var message = drawMessage as MyRenderMessageDrawString;

                var font = MyRender11.GetFont(message.FontIndex);
                font.DrawString(
                    message.ScreenCoord,
                    message.ColorMask,
                    message.Text,
                    message.ScreenScale,
                    message.ScreenMaxWidth);

                break;
            }

            case MyRenderMessageEnum.DrawScene:
            {
                UpdateSceneFrame();

                ProfilerShort.Begin("DrawScene");
                DrawGameScene(Backbuffer);
                ProfilerShort.Begin("TransferPerformanceStats");
                TransferPerformanceStats();
                ProfilerShort.End();
                ProfilerShort.End();

                ProfilerShort.Begin("Draw scene debug");
                MyGpuProfiler.IC_BeginBlock("Draw scene debug");
                DrawSceneDebug();
                MyGpuProfiler.IC_EndBlock();
                ProfilerShort.End();

                ProfilerShort.Begin("ProcessDebugMessages");
                ProcessDebugMessages();
                ProfilerShort.End();

                ProfilerShort.Begin("MyDebugRenderer.Draw");
                MyGpuProfiler.IC_BeginBlock("MyDebugRenderer.Draw");
                MyDebugRenderer.Draw(MyRender11.Backbuffer);
                MyGpuProfiler.IC_EndBlock();
                ProfilerShort.End();

                var testingDepth = MyRender11.MultisamplingEnabled ? MyScreenDependants.m_resolvedDepth : MyGBuffer.Main.DepthStencil;

                ProfilerShort.Begin("MyPrimitivesRenderer.Draw");
                MyGpuProfiler.IC_BeginBlock("MyPrimitivesRenderer.Draw");
                MyPrimitivesRenderer.Draw(MyRender11.Backbuffer, testingDepth);
                MyGpuProfiler.IC_EndBlock();
                ProfilerShort.End();

                ProfilerShort.Begin("MyLinesRenderer.Draw");
                MyGpuProfiler.IC_BeginBlock("MyLinesRenderer.Draw");
                MyLinesRenderer.Draw(MyRender11.Backbuffer, testingDepth);
                MyGpuProfiler.IC_EndBlock();
                ProfilerShort.End();

                if (m_screenshot.HasValue && m_screenshot.Value.IgnoreSprites)
                {
                    if (m_screenshot.Value.SizeMult == Vector2.One)
                    {
                        SaveScreenshotFromResource(Backbuffer.m_resource);
                    }
                    else
                    {
                        TakeCustomSizedScreenshot(m_screenshot.Value.SizeMult);
                    }
                }

                ProfilerShort.Begin("MySpritesRenderer.Draw");
                MyGpuProfiler.IC_BeginBlock("MySpritesRenderer.Draw");
                MySpritesRenderer.Draw(MyRender11.Backbuffer.m_RTV, new MyViewport(MyRender11.ViewportResolution.X, MyRender11.ViewportResolution.Y));
                MyGpuProfiler.IC_EndBlock();
                ProfilerShort.End();

                if (MyRenderProxy.DRAW_RENDER_STATS)
                {
                    MyRender11.GetRenderProfiler().StartProfilingBlock("MyRenderStatsDraw.Draw");
                    MyRenderStatsDraw.Draw(MyRenderStats.m_stats, 0.6f, VRageMath.Color.Yellow);
                    ProfilerShort.End();
                }

                break;
            }
            }
        }
        static void Gather()
        {
            // counting sorted billboards
            m_batches.Clear();
            m_sortedNum = 0;

            PreGatherList(MyRenderProxy.BillboardsRead);
            PreGatherList(m_billboardsOnce);

            m_sortedBillboardsNum = m_sortedNum;

            m_unsorted = 0;
            m_sorted   = 0;

            GatherList(MyRenderProxy.BillboardsRead);
            GatherList(m_billboardsOnce);

            Array.Sort(m_sortBuffer, 0, m_sortedNum);
            //Array.Reverse(m_sortBuffer, 0, m_sortedNum);
            //Array.Sort(m_sortBuffer, m_sortedNum, m_unsorted);

            var N = m_sorted + m_unsorted;

            var batch = new MyBillboardBatch();
            //MyAssetTexture prevTexture = null;
            var prevTexId     = TexId.NULL;
            int currentOffset = 0;

            if (N > 0)
            {
                var material = MyTransparentMaterials.GetMaterial(m_sortBuffer[0].Material);

                if (material.UseAtlas)
                {
                    var item = m_atlasedTextures[material.Texture];
                    prevTexId = item.TextureId;
                }
                else
                {
                    PreloadTexture(material.Texture);
                    //prevTexture = MyTextureManager.GetTextureFast(material.Texture);
                    prevTexId = MyTextures.GetTexture(material.Texture, MyTextureEnum.GUI, true);
                }
            }

            TexId batchTexId = TexId.NULL;
            MyTransparentMaterial prevMaterial = null;

            for (int i = 0; i < N; i++)
            {
                var billboard = m_sortBuffer[i];
                var material  = MyTransparentMaterials.GetMaterial(billboard.Material);

                var billboardData = new MyBillboardData();

                billboardData.CustomProjectionID = billboard.CustomViewProjection;
                billboardData.Color = billboard.Color;
                if (material.UseAtlas)
                {
                    var atlasItem = m_atlasedTextures[material.Texture];
                    //billboardData.UvModifiers = new HalfVector4(atlasItem.UvOffsetScale);
                    batchTexId = atlasItem.TextureId;
                }
                else
                {
                    batchTexId = MyTextures.GetTexture(material.Texture, MyTextureEnum.GUI, true);
                }

                billboardData.Reflective = billboard.Reflectivity;
                Vector3D pos0 = billboard.Position0;
                Vector3D pos1 = billboard.Position1;
                Vector3D pos2 = billboard.Position2;
                Vector3D pos3 = billboard.Position3;

                if (billboard.ParentID != -1)
                {
                    if (MyIDTracker <MyActor> .FindByID((uint)billboard.ParentID) != null)
                    {
                        var matrix = MyIDTracker <MyActor> .FindByID((uint)billboard.ParentID).WorldMatrix;

                        Vector3D.Transform(ref pos0, ref matrix, out pos0);
                        Vector3D.Transform(ref pos1, ref matrix, out pos1);
                        Vector3D.Transform(ref pos2, ref matrix, out pos2);
                        Vector3D.Transform(ref pos3, ref matrix, out pos3);
                    }
                }

                if (billboard.CustomViewProjection != -1)
                {
                    var billboardViewProjection = MyRenderProxy.BillboardsViewProjectionRead[billboard.CustomViewProjection];

                    //pos0 -= MyEnvironment.CameraPosition;
                    //pos1 -= MyEnvironment.CameraPosition;
                    //pos2 -= MyEnvironment.CameraPosition;
                    //pos3 -= MyEnvironment.CameraPosition;
                }
                else
                {
                    pos0 -= MyEnvironment.CameraPosition;
                    pos1 -= MyEnvironment.CameraPosition;
                    pos2 -= MyEnvironment.CameraPosition;
                    pos3 -= MyEnvironment.CameraPosition;
                }

                var normal = Vector3.Cross(pos1 - pos0, pos2 - pos0);
                normal.Normalize();

                billboardData.Normal = normal;

                m_vertexData[i * 4 + 0].Position = pos0;
                m_vertexData[i * 4 + 1].Position = pos1;
                m_vertexData[i * 4 + 2].Position = pos2;
                m_vertexData[i * 4 + 3].Position = pos3;

                var uv0 = new Vector2(material.UVOffset.X + billboard.UVOffset.X, material.UVOffset.Y + billboard.UVOffset.Y);
                var uv1 = new Vector2(material.UVOffset.X + material.UVSize.X + billboard.UVOffset.X, material.UVOffset.Y + billboard.UVOffset.Y);
                var uv2 = new Vector2(material.UVOffset.X + material.UVSize.X + billboard.UVOffset.X, material.UVOffset.Y + material.UVSize.Y + billboard.UVOffset.Y);
                var uv3 = new Vector2(material.UVOffset.X + billboard.UVOffset.X, material.UVOffset.Y + material.UVSize.Y + billboard.UVOffset.Y);

                if (material.UseAtlas)
                {
                    var atlasItem = m_atlasedTextures[material.Texture];

                    uv0 = uv0 * new Vector2(atlasItem.UvOffsetScale.Z, atlasItem.UvOffsetScale.W) + new Vector2(atlasItem.UvOffsetScale.X, atlasItem.UvOffsetScale.Y);
                    uv1 = uv1 * new Vector2(atlasItem.UvOffsetScale.Z, atlasItem.UvOffsetScale.W) + new Vector2(atlasItem.UvOffsetScale.X, atlasItem.UvOffsetScale.Y);
                    uv2 = uv2 * new Vector2(atlasItem.UvOffsetScale.Z, atlasItem.UvOffsetScale.W) + new Vector2(atlasItem.UvOffsetScale.X, atlasItem.UvOffsetScale.Y);
                    uv3 = uv3 * new Vector2(atlasItem.UvOffsetScale.Z, atlasItem.UvOffsetScale.W) + new Vector2(atlasItem.UvOffsetScale.X, atlasItem.UvOffsetScale.Y);
                }

                m_vertexData[i * 4 + 0].Texcoord = new HalfVector2(uv0);
                m_vertexData[i * 4 + 1].Texcoord = new HalfVector2(uv1);
                m_vertexData[i * 4 + 2].Texcoord = new HalfVector2(uv2);
                m_vertexData[i * 4 + 3].Texcoord = new HalfVector2(uv3);

                pos0.AssertIsValid();
                pos1.AssertIsValid();
                pos2.AssertIsValid();
                pos3.AssertIsValid();


                MyTriangleBillboard triBillboard = billboard as MyTriangleBillboard;
                if (triBillboard != null)
                {
                    m_vertexData[i * 4 + 3].Position = pos2; // second triangle will die in rasterizer

                    m_vertexData[i * 4 + 0].Texcoord = new HalfVector2(triBillboard.UV0);
                    m_vertexData[i * 4 + 1].Texcoord = new HalfVector2(triBillboard.UV1);
                    m_vertexData[i * 4 + 2].Texcoord = new HalfVector2(triBillboard.UV2);

                    billboardData.Normal = triBillboard.Normal0; // pew pew pew :O
                }

                m_billboardData[i] = billboardData;

                bool closeBatch = (batchTexId != prevTexId) || ((i == m_sortedNum) && (i > 0));

                if (closeBatch)
                {
                    batch = new MyBillboardBatch();

                    batch.Offset  = currentOffset;
                    batch.Num     = i - currentOffset;
                    batch.Texture = prevTexId != TexId.NULL ? MyTextures.Views[prevTexId.Index] : null;

                    batch.Lit = prevMaterial.CanBeAffectedByOtherLights;

                    m_batches.Add(batch);
                    currentOffset = i;
                }

                prevTexId    = batchTexId;
                prevMaterial = material;
            }

            if (N > 0)
            {
                batch         = new MyBillboardBatch();
                batch.Offset  = currentOffset;
                batch.Num     = N - currentOffset;
                batch.Texture = prevTexId != TexId.NULL ? MyTextures.GetView(prevTexId) : null;

                batch.Lit = prevMaterial.CanBeAffectedByOtherLights;

                m_batches.Add(batch);
            }
        }
        static void RenderDirectionalEnvironmentLight()
        {
            MySunlightConstantsLayout constants;

            constants.Direction = MyEnvironment.DirectionalLightDir;
            constants.Color     = MyEnvironment.DirectionalLightIntensity;

            var mapping = MyMapping.MapDiscard(m_sunlightConstants);

            mapping.stream.Write(constants);
            mapping.Unmap();

            //context.VertexShader.Set(MyCommon.FullscreenShader.VertexShader);
            RC.SetPS(DirectionalEnvironmentLight_Pixel);
            RC.SetCB(1, m_sunlightConstants);
            RC.SetCB(4, MyShadows.m_csmConstants);
            RC.Context.PixelShader.SetSamplers(0, MyRender11.StandardSamplers);
            RC.Context.PixelShader.SetSampler(MyCommon.SHADOW_SAMPLER_SLOT, MyRender11.m_shadowmapSamplerState);
            RC.Context.PixelShader.SetShaderResource(MyCommon.CASCADES_SM_SLOT, MyShadows.m_cascadeShadowmapArray.ShaderView);

            var z = Vector4.Transform(new Vector4(0.5f, 0.5f, -MyEnvironment.FarClipping, 1), MyEnvironment.Projection);


            RC.Context.PixelShader.SetShaderResource(MyCommon.SKYBOX_SLOT, MyTextures.GetView(MyTextures.GetTexture(MyEnvironment.DaySkybox, MyTextureEnum.CUBEMAP, true)));
            //RC.Context.PixelShader.SetShaderResource(MyCommon.SKYBOX_IBL_SLOT, MyTextures.GetView(MyTextures.GetTexture(MyEnvironment.DaySkyboxPrefiltered, MyTextureEnum.CUBEMAP, true)));

            RC.Context.PixelShader.SetShaderResource(MyCommon.SKYBOX_IBL_SLOT,
                                                     MyRender11.IsIntelBrokenCubemapsWorkaround ? MyTextures.GetView(MyTextures.IntelFallbackCubeTexId) : MyGeometryRenderer.m_envProbe.cubemapPrefiltered.ShaderView);
            RC.Context.PixelShader.SetShaderResource(MyCommon.SKYBOX2_SLOT, MyTextures.GetView(MyTextures.GetTexture(MyEnvironment.NightSkybox, MyTextureEnum.CUBEMAP, true)));
            RC.Context.PixelShader.SetShaderResource(MyCommon.SKYBOX2_IBL_SLOT, MyTextures.GetView(MyTextures.GetTexture(MyEnvironment.NightSkyboxPrefiltered, MyTextureEnum.CUBEMAP, true)));

            RC.Context.PixelShader.SetShaderResource(MyCommon.SHADOW_SLOT, MyRender11.m_shadowsHelper.ShaderView);

            RC.Context.PixelShader.SetShaderResource(MyCommon.AMBIENT_BRDF_LUT_SLOT,
                                                     MyCommon.GetAmbientBrdfLut());

            RC.BindSRV(MyCommon.AO_SLOT, MyScreenDependants.m_ambientOcclusion);

            MyScreenPass.RunFullscreenPixelFreq(MyGBuffer.Main.Get(MyGbufferSlot.LBuffer));
            if (MyRender11.MultisamplingEnabled)
            {
                RC.SetPS(DirectionalEnvironmentLight_Sample);
                MyScreenPass.RunFullscreenSampleFreq(MyGBuffer.Main.Get(MyGbufferSlot.LBuffer));
            }
        }
Exemple #26
0
 internal static ShaderResourceView GetAmbientBrdfLut()
 {
     return(MyTextures.GetView(MyTextures.GetTexture("Textures/Miscellaneous/ambient_brdf.dds", MyTextureEnum.CUSTOM, true)));
 }
        internal static void RenderColoredTextures(List <renderColoredTextureProperties> texturesToRender)
        {
            if (texturesToRender.Count == 0)
            {
                return;
            }

            if (!m_initialized)
            {
                Init();
            }

            const int RENDER_TEXTURE_RESOLUTION = 512;

            RC.DeviceContext.OutputMerger.BlendState = null;
            RC.SetIL(null);

            RC.SetPS(m_ps);
            RC.SetCB(0, MyCommon.FrameConstants);
            RC.SetCB(1, m_cb);

            Dictionary <Vector2I, MyRenderTarget> createdRenderTextureTargets = new Dictionary <Vector2I, MyRenderTarget>();

            foreach (var texture in texturesToRender)
            {
                TexId texId = MyTextures.GetTexture(texture.TextureName, MyTextureEnum.COLOR_METAL, true);
                if (texId == TexId.NULL)
                {
                    continue;
                }

                Vector2  texSize = MyTextures.GetSize(texId);
                Vector2I renderTargetResolution = new Vector2I(RENDER_TEXTURE_RESOLUTION, RENDER_TEXTURE_RESOLUTION);
                if (texSize.Y > 0)
                {
                    if (texSize.Y < RENDER_TEXTURE_RESOLUTION)
                    {
                        renderTargetResolution.X = (int)texSize.X;
                        renderTargetResolution.Y = (int)texSize.Y;
                    }
                    else
                    {
                        renderTargetResolution.X *= (int)(texSize.X / texSize.Y);
                    }
                }

                MyViewport viewport = new MyViewport(renderTargetResolution.X, renderTargetResolution.Y);

                MyRenderTarget renderTexture = null;
                if (!createdRenderTextureTargets.TryGetValue(renderTargetResolution, out renderTexture))
                {
                    renderTexture = new MyRenderTarget(renderTargetResolution.X, renderTargetResolution.Y, SharpDX.DXGI.Format.R8G8B8A8_UNorm_SRgb, 1, 0);
                    createdRenderTextureTargets[renderTargetResolution] = renderTexture;
                }

                RC.BindDepthRT(null, DepthStencilAccess.ReadWrite, renderTexture);

                // Set color
                var     mapping = MyMapping.MapDiscard(m_cb);
                Vector4 color   = new Vector4(texture.ColorMaskHSV, 1);
                mapping.WriteAndPosition(ref color);
                mapping.Unmap();

                // Set texture
                RC.DeviceContext.PixelShader.SetShaderResource(0, MyTextures.GetView(texId));

                // Draw
                MyScreenPass.DrawFullscreenQuad(viewport);

                // Save to file
                MyTextureData.ToFile(renderTexture.GetHWResource(), texture.PathToSave, ImageFileFormat.Png);
            }

            texturesToRender.Clear();

            foreach (var texture in createdRenderTextureTargets)
            {
                texture.Value.Release();
            }
            createdRenderTextureTargets.Clear();

            RC.BindDepthRT(null, DepthStencilAccess.ReadWrite, null);
            RC.BindGBufferForRead(0, MyGBuffer.Main);
        }
        private static void ProcessMessageInternal(IMyRenderMessage message)
        {
            switch (message.MessageType)
            {
            case MyRenderMessageEnum.SetCameraViewMatrix:
            {
                var rMessage = (MyRenderMessageSetCameraViewMatrix)message;

                SetupCameraMatrices(rMessage);

                break;
            }

            case MyRenderMessageEnum.DrawScene:
            {
                var rMessage = (IMyRenderMessage)message;

                m_drawQueue.Enqueue(rMessage);

                m_messageTracker.Clear();

                break;
            }

            case MyRenderMessageEnum.RebuildCullingStructure:
            {
                break;
            }

                #region Profiler

            case MyRenderMessageEnum.RenderProfiler:
            {
                var profMessage = (MyRenderMessageRenderProfiler)message;

                MyRenderProfiler.HandleInput(profMessage.Command, profMessage.Index);

                break;
            }

                #endregion

                #region Characters

            case MyRenderMessageEnum.CreateRenderCharacter:
            {
                var rMessage = (MyRenderMessageCreateRenderCharacter)message;

                var    actor        = MyActorFactory.CreateCharacter();
                Matrix worldMatrixF = rMessage.WorldMatrix;
                //actor.GetRenderable().SetModel(MyAssetsLoader.GetModel(rMessage.Model));
                actor.GetRenderable().SetModel(MyMeshes.GetMeshId(X.TEXT(rMessage.Model)));
                actor.SetMatrix(ref worldMatrixF);

                if (rMessage.ColorMaskHSV.HasValue)
                {
                    var color = ColorFromMask(rMessage.ColorMaskHSV.Value);
                    actor.GetRenderable().SetKeyColor(new Vector4(color, 1));
                }

                actor.SetID(rMessage.ID);

                //var entity = MyComponents.CreateEntity(rMessage.ID);
                //MyComponents.CreateRenderable(
                //    entity,
                //    MyMeshes.GetMeshId(X.TEXT(rMessage.Model)),
                //    rMessage.ColorMaskHSV.HasValue ? rMessage.ColorMaskHSV.Value : Vector3.One);
                //MyComponents.SetMatrix(entity, ref rMessage.WorldMatrix);

                break;
            }

            case MyRenderMessageEnum.SetCharacterSkeleton:
            {
                var rMessage = (MyRenderMessageSetCharacterSkeleton)message;

                var actor = MyIDTracker <MyActor> .FindByID(rMessage.CharacterID);

                if (actor != null)
                {
                    actor.GetSkinning().SetSkeleton(rMessage.SkeletonBones, rMessage.SkeletonIndices);
                }

                //var entity = MyComponents.GetEntity(rMessage.CharacterID);
                //MyComponents.SetSkeleton(entity, rMessage.SkeletonBones, rMessage.SkeletonIndices);

                break;
            };

            case MyRenderMessageEnum.SetCharacterTransforms:
            {
                var rMessage = (MyRenderMessageSetCharacterTransforms)message;

                var actor = MyIDTracker <MyActor> .FindByID(rMessage.CharacterID);

                if (actor != null)
                {
                    actor.GetSkinning().SetAnimationBones(rMessage.RelativeBoneTransforms);
                }
                //var entity = MyComponents.GetEntity(rMessage.CharacterID);
                //MyComponents.SetAnimation(entity, rMessage.RelativeBoneTransforms);

                break;
            }

            case MyRenderMessageEnum.UpdateRenderEntity:
            {
                var rMessage = (MyRenderMessageUpdateRenderEntity)message;

                var actor = MyIDTracker <MyActor> .FindByID(rMessage.ID);

                if (actor != null && actor.GetRenderable() != null)
                {
                    if (rMessage.ColorMaskHSV.HasValue)
                    {
                        actor.GetRenderable().SetKeyColor(new Vector4(ColorFromMask(rMessage.ColorMaskHSV.Value), 1));
                    }
                    actor.GetRenderable().SetDithering(rMessage.Dithering);

                    if (rMessage.Dithering < 0)
                    {
                    }
                }

                break;
            }

            case MyRenderMessageEnum.ChangeModelMaterial:
            {
                var rMessage = (MyRenderMessageChangeModelMaterial)message;



                //var matId = MyMeshMaterialId.NULL;
                //if (rMessage.Material.ToLower().Contains("debug"))
                //{
                //    matId = MyMeshMaterials1.DebugMaterialId;
                //}
                //else
                //{
                //    matId = MyMeshMaterials1.GetMaterialId(rMessage.Material);
                //}

                //MyAssetsLoader.GetModel(rMessage.Model).SetMaterial_SLOW(MyMeshMaterials1.GetProxyId(matId));

                break;
            }

                #endregion

                #region Render objects

            case MyRenderMessageEnum.CreateRenderEntity:
            {
                var rMessage = (MyRenderMessageCreateRenderEntity)message;

                Matrix m = (Matrix)rMessage.WorldMatrix;

                var actor = MyActorFactory.CreateSceneObject();
                if (rMessage.Model != null)
                {
                    var model = MyAssetsLoader.ModelRemap.Get(rMessage.Model, rMessage.Model);

                    actor.GetRenderable().SetModel(MyMeshes.GetMeshId(X.TEXT(model)));
                    //if (MyDestructionMesh.ModelsDictionary.ContainsKey(model))
                    //{
                    //    //actor.GetRenderable().SetModel(MyDestructionMesh.ModelsDictionary.Get(model));
                    //    actor.GetRenderable().SetModel(MyMeshes.GetMeshId(X.TEXT(model)));
                    //}
                    //else
                    //{
                    //    //actor.GetRenderable().SetModel(MyAssetsLoader.GetModel(model));
                    //    actor.GetRenderable().SetModel(MyMeshes.GetMeshId(X.TEXT(model)));
                    //}
                }

                actor.SetID(rMessage.ID);
                actor.SetMatrix(ref m);

                break;
            }

            case MyRenderMessageEnum.CreateRenderVoxelDebris:
            {
                var rMessage = (MyRenderMessageCreateRenderVoxelDebris)message;

                Matrix m = (Matrix)rMessage.WorldMatrix;

                var actor = MyActorFactory.CreateSceneObject();
                if (rMessage.Model != null)
                {
                    actor.GetRenderable().SetModel(MyMeshes.GetMeshId(X.TEXT(rMessage.Model)));
                }

                actor.SetID(rMessage.ID);
                actor.SetMatrix(ref m);

                MyRenderableComponent.DebrisEntityVoxelMaterial[rMessage.ID] = rMessage.VoxelMaterialIndex;

                break;
            }

            case MyRenderMessageEnum.UpdateRenderObject:
            {
                var rMessage = (MyRenderMessageUpdateRenderObject)message;

                var actor = MyIDTracker <MyActor> .FindByID(rMessage.ID);

                if (actor != null)
                {
                    Matrix m = (Matrix)rMessage.WorldMatrix;
                    actor.SetMatrix(ref m);
                    if (rMessage.AABB.HasValue)
                    {
                        actor.SetAabb((BoundingBox)rMessage.AABB.Value);
                    }
                }

                var entity = MyComponents.GetEntity(rMessage.ID);
                if (entity != EntityId.NULL)
                {
                    MyComponents.SetMatrix(entity, ref rMessage.WorldMatrix);
                    if (rMessage.AABB.HasValue)
                    {
                        var aabb = rMessage.AABB.Value;
                        MyComponents.SetAabb(entity, ref aabb);
                    }
                }

                break;
            }

            case MyRenderMessageEnum.RemoveRenderObject:
            {
                var rMessage = (MyRenderMessageRemoveRenderObject)message;

                var actor = MyIDTracker <MyActor> .FindByID(rMessage.ID);

                if (actor != null)
                {
                    if (actor.GetRenderable() != null && actor.GetRenderable().GetModel().Info.Dynamic)
                    {
                        MyMeshes.RemoveMesh(actor.GetRenderable().GetModel());
                    }

                    actor.Destruct();
                }

                var instancing = MyInstancing.Get(rMessage.ID);
                if (instancing != InstancingId.NULL)
                {
                    MyInstancing.Remove(rMessage.ID, instancing);
                }

                var light = MyLights.Get(rMessage.ID);
                if (light != LightId.NULL)
                {
                    MyLights.Remove(rMessage.ID, light);
                }

                var clipmap = MyClipmapFactory.ClipmapByID.Get(rMessage.ID);
                if (clipmap != null)
                {
                    clipmap.RemoveFromUpdate();
                }

                break;
            }

            case MyRenderMessageEnum.UpdateRenderObjectVisibility:
            {
                var rMessage = (MyRenderMessageUpdateRenderObjectVisibility)message;

                var actor = MyIDTracker <MyActor> .FindByID(rMessage.ID);

                if (actor != null)
                {
                    actor.SetVisibility(rMessage.Visible);
                }

                break;
            }


            case MyRenderMessageEnum.CreateRenderInstanceBuffer:
            {
                var rMessage = (MyRenderMessageCreateRenderInstanceBuffer)message;

                //var instancing = MyComponentFactory<MyInstancingComponent>.Create();
                //instancing.SetID(rMessage.ID);
                //instancing.Init(rMessage.Type);
                //instancing.SetDebugName(rMessage.DebugName);

                MyInstancing.Create(rMessage.ID, rMessage.Type, rMessage.DebugName);

                break;
            }

            case MyRenderMessageEnum.UpdateRenderInstanceBuffer:
            {
                var rMessage = (MyRenderMessageUpdateRenderInstanceBuffer)message;

                //var instancing = MyIDTracker<MyInstancingComponent>.FindByID(rMessage.ID);
                //if(instancing != null)
                //{
                //    instancing.UpdateGeneric(rMessage.InstanceData, rMessage.Capacity);
                //}

                MyInstancing.UpdateGeneric(MyInstancing.Get(rMessage.ID), rMessage.InstanceData, rMessage.Capacity);

                rMessage.InstanceData.Clear();

                break;
            }

            case MyRenderMessageEnum.UpdateRenderCubeInstanceBuffer:
            {
                var rMessage = (MyRenderMessageUpdateRenderCubeInstanceBuffer)message;

                //var instancing = MyIDTracker<MyInstancingComponent>.FindByID(rMessage.ID);
                //if (instancing != null)
                //{
                //    instancing.UpdateCube(rMessage.InstanceData, rMessage.Capacity);
                //}
                MyInstancing.UpdateCube(MyInstancing.Get(rMessage.ID), rMessage.InstanceData, rMessage.Capacity);

                rMessage.InstanceData.Clear();

                break;
            }

            case MyRenderMessageEnum.SetInstanceBuffer:
            {
                var rMessage = (MyRenderMessageSetInstanceBuffer)message;

                var actor = MyIDTracker <MyActor> .FindByID(rMessage.ID);

                //var instancing = MyIDTracker<MyInstancingComponent>.FindByID(rMessage.InstanceBufferId);

                if (actor != null)
                {
                    //if (actor.GetComponent(MyActorComponentEnum.Instancing) != instancing)
                    //{
                    //    actor.AddComponent(instancing);
                    //}
                    //actor.SetLocalAabb(rMessage.LocalAabb);
                    //actor.GetRenderable().SetInstancingCounters(rMessage.InstanceCount, rMessage.InstanceStart);

                    actor.GetRenderable().SetInstancing(MyInstancing.Get(rMessage.InstanceBufferId));
                    actor.SetLocalAabb(rMessage.LocalAabb);
                    actor.GetRenderable().SetInstancingCounters(rMessage.InstanceCount, rMessage.InstanceStart);
                }

                break;
            }

            case MyRenderMessageEnum.CreateManualCullObject:
            {
                var rMessage = (MyRenderMessageCreateManualCullObject)message;

                var actor = MyActorFactory.CreateGroup();
                actor.SetID(rMessage.ID);
                Matrix m = (Matrix)rMessage.WorldMatrix;
                actor.SetMatrix(ref m);

                break;
            }

            case MyRenderMessageEnum.SetParentCullObject:
            {
                var rMessage = (MyRenderMessageSetParentCullObject)message;

                var child = MyIDTracker <MyActor> .FindByID(rMessage.ID);

                var parent = MyIDTracker <MyActor> .FindByID(rMessage.CullObjectID);

                if (child != null && parent != null && parent.GetGroupRoot() != null && child.GetGroupLeaf() == null)
                {
                    child.SetRelativeTransform(rMessage.ChildToParent);
                    parent.GetGroupRoot().Add(child);
                }

                break;
            }

            case MyRenderMessageEnum.CreateLineBasedObject:
            {
                var rMessage = (MyRenderMessageCreateLineBasedObject)message;

                var actor = MyActorFactory.CreateSceneObject();
                //actor.GetRenderable().SetModel(new MyDynamicMesh());

                actor.SetID(rMessage.ID);
                actor.SetMatrix(ref Matrix.Identity);

                MyMeshMaterials1.GetMaterialId("__ROPE_MATERIAL", null, "Textures/rope_cm.dds", "Textures/rope_ng.dds", "Textures/rope_add.dds", MyMesh.DEFAULT_MESH_TECHNIQUE);
                actor.GetRenderable().SetModel(MyMeshes.CreateRuntimeMesh(X.TEXT("LINE" + rMessage.ID), 1, true));

                break;
            }

            case MyRenderMessageEnum.UpdateLineBasedObject:
            {
                var rMessage = (MyRenderMessageUpdateLineBasedObject)message;

                var actor = MyIDTracker <MyActor> .FindByID(rMessage.ID);

                if (actor != null)
                {
                    //var mesh = actor.GetRenderable().GetMesh() as MyDynamicMesh;

                    MyVertexFormatPositionH4 []            stream0;
                    MyVertexFormatTexcoordNormalTangent [] stream1;

                    MyLineHelpers.GenerateVertexData(ref rMessage.WorldPointA, ref rMessage.WorldPointB,
                                                     out stream0, out stream1);

                    var indices  = MyLineHelpers.GenerateIndices(stream0.Length);
                    var sections = new MySectionInfo[]
                    {
                        new MySectionInfo {
                            TriCount = indices.Length / 3, IndexStart = 0, MaterialName = "__ROPE_MATERIAL"
                        }
                    };

                    MyMeshes.UpdateRuntimeMesh(MyMeshes.GetMeshId(X.TEXT("LINE" + rMessage.ID)),
                                               indices,
                                               stream0,
                                               stream1,
                                               sections,
                                               (BoundingBox)MyLineHelpers.GetBoundingBox(ref rMessage.WorldPointA, ref rMessage.WorldPointB));

                    //actor.SetAabb((BoundingBox)MyLineHelpers.GetBoundingBox(ref rMessage.WorldPointA, ref rMessage.WorldPointB));
                    actor.MarkRenderDirty();

                    var matrix = Matrix.CreateTranslation((Vector3)(rMessage.WorldPointA + rMessage.WorldPointB) * 0.5f);
                    actor.SetMatrix(ref matrix);
                }

                break;
            }

            case MyRenderMessageEnum.SetRenderEntityData:
            {
                var rMessage = (MyRenderMessageSetRenderEntityData)message;

                Debug.Assert(false, "MyRenderMessageSetRenderEntityData is deprecated!");

                break;
            }

            case MyRenderMessageEnum.AddRuntimeModel:
            {
                var rMessage = (MyRenderMessageAddRuntimeModel)message;

                //MyDestructionMesh mesh = MyDestructionMesh.ModelsDictionary.Get(rMessage.Name);
                //if (mesh == null)
                //{
                //mesh = new MyDestructionMesh(rMessage.Name);

                //ProfilerShort.Begin("LoadBuffers");
                //mesh.Fill(rMessage.ModelData.Indices, rMessage.ModelData.Positions, rMessage.ModelData.Normals, rMessage.ModelData.Tangents, rMessage.ModelData.TexCoords, rMessage.ModelData.Sections, rMessage.ModelData.AABB);
                //ProfilerShort.End();

                if (!MyMeshes.Exists(rMessage.Name))
                {
                    {
                        ushort[] indices = new ushort[rMessage.ModelData.Indices.Count];
                        for (int i = 0; i < rMessage.ModelData.Indices.Count; i++)
                        {
                            indices[i] = (ushort)rMessage.ModelData.Indices[i];
                        }
                        var verticesNum = rMessage.ModelData.Positions.Count;
                        MyVertexFormatPositionH4[]            stream0 = new MyVertexFormatPositionH4[verticesNum];
                        MyVertexFormatTexcoordNormalTangent[] stream1 = new MyVertexFormatTexcoordNormalTangent[verticesNum];
                        for (int i = 0; i < verticesNum; i++)
                        {
                            stream0[i] = new MyVertexFormatPositionH4(rMessage.ModelData.Positions[i]);
                            stream1[i] = new MyVertexFormatTexcoordNormalTangent(
                                rMessage.ModelData.TexCoords[i], rMessage.ModelData.Normals[i], rMessage.ModelData.Tangents[i]);
                        }
                        var id = MyMeshes.CreateRuntimeMesh(X.TEXT(rMessage.Name), rMessage.ModelData.Sections.Count, false);
                        MyMeshes.UpdateRuntimeMesh(id, indices, stream0, stream1, rMessage.ModelData.Sections.ToArray(), rMessage.ModelData.AABB);
                    }

                    if (rMessage.ReplacedModel != null)
                    {
                        //MyAssetsLoader.ModelRemap[rMessage.ReplacedModel] = rMessage.Name;
                        MyAssetsLoader.ModelRemap[rMessage.Name] = rMessage.ReplacedModel;
                    }

                    //if (MyAssetsLoader.LOG_MESH_STATISTICS)
                    //{
                    //    mesh.DebugWriteInfo();
                    //}
                }

                break;
            }

            case MyRenderMessageEnum.UpdateModelProperties:
            {
                var rMessage = (MyRenderMessageUpdateModelProperties)message;

                var actor = MyIDTracker <MyActor> .FindByID(rMessage.ID);

                if (actor != null)
                {
                    var key = new MyEntityMaterialKey {
                        LOD = rMessage.LOD, Material = X.TEXT(rMessage.MaterialName)
                    };

                    if (rMessage.Enabled.HasValue)
                    {
                        if (!MyScene.EntityDisabledMaterials.ContainsKey(rMessage.ID))
                        {
                            MyScene.EntityDisabledMaterials.Add(rMessage.ID, new HashSet <MyEntityMaterialKey>());
                        }

                        if (!rMessage.Enabled.Value)
                        {
                            MyScene.EntityDisabledMaterials[rMessage.ID].Add(key);
                        }
                        else
                        {
                            MyScene.EntityDisabledMaterials[rMessage.ID].Remove(key);
                        }
                    }

                    var r = actor.GetRenderable();

                    if ((rMessage.Emissivity.HasValue || rMessage.DiffuseColor.HasValue) && !r.ModelProperties.ContainsKey(key))
                    {
                        r.ModelProperties[key] = new MyModelProperties();
                    }

                    if (rMessage.Emissivity.HasValue)
                    {
                        r.ModelProperties[key].Emissivity = rMessage.Emissivity.Value;
                    }

                    if (rMessage.DiffuseColor.HasValue)
                    {
                        r.ModelProperties[key].ColorMul = rMessage.DiffuseColor.Value;
                    }

                    actor.MarkRenderDirty();
                }

                break;
            }

            case MyRenderMessageEnum.PreloadModel:
            {
                var rMessage = (MyRenderMessagePreloadModel)message;

                //MyAssetsLoader.GetModel(rMessage.Name);
                MyMeshes.GetMeshId(X.TEXT(rMessage.Name));

                break;
            }

            case MyRenderMessageEnum.ChangeMaterialTexture:
            {
                var rMessage = (MyRenderMessageChangeMaterialTexture)message;

                var actor = MyIDTracker <MyActor> .FindByID(rMessage.RenderObjectID);

                if (actor != null)
                {
                    var r   = actor.GetRenderable();
                    var key = new MyEntityMaterialKey {
                        LOD = 0, Material = X.TEXT(rMessage.MaterialName)
                    };

                    if (!r.ModelProperties.ContainsKey(key))
                    {
                        r.ModelProperties[key] = new MyModelProperties();
                    }
                    r.ModelProperties[key].TextureSwap = new MyMaterialTextureSwap {
                        TextureName = X.TEXT(rMessage.TextureName)
                    };

                    r.FreeCustomRenderTextures(key);

                    actor.MarkRenderDirty();
                }

                break;
            }

            case MyRenderMessageEnum.DrawTextToMaterial:
            {
                var rMessage = (MyRenderMessageDrawTextToMaterial)message;

                //rMessage.EntityId
                //rMessage.FontColor
                //rMessage.MaterialName
                //rMessage.Text;
                //rMessage.TextScale;

                var actor = MyIDTracker <MyActor> .FindByID(rMessage.RenderObjectID);

                if (actor != null)
                {
                    var r   = actor.GetRenderable();
                    var key = new MyEntityMaterialKey {
                        LOD = 0, Material = X.TEXT(rMessage.MaterialName)
                    };

                    if (!r.ModelProperties.ContainsKey(key))
                    {
                        r.ModelProperties[key] = new MyModelProperties();
                    }
                    else
                    {
                        r.ModelProperties[key].TextureSwap = null;
                    }

                    RwTexId handle = r.ModelProperties[key].CustomRenderedTexture;
                    if (handle == RwTexId.NULL && MyModelProperties.CustomTextures < MyModelProperties.MaxCustomTextures)
                    {
                        handle = MyRwTextures.CreateRenderTarget(rMessage.TextureResolution * rMessage.TextureAspectRatio, rMessage.TextureResolution, SharpDX.DXGI.Format.R8G8B8A8_UNorm_SRgb, true);
                        r.ModelProperties[key].CustomRenderedTexture = handle;
                        ++MyModelProperties.CustomTextures;
                    }

                    if (handle != RwTexId.NULL)
                    {
                        var clearColor = new SharpDX.Color4(rMessage.BackgroundColor.PackedValue);
                        clearColor.Alpha = 0;
                        MyRender11.ImmediateContext.ClearRenderTargetView(handle.Rtv, clearColor);

                        // my sprites renderer -> push state
                        MySpritesRenderer.PushState(new Vector2(rMessage.TextureResolution * rMessage.TextureAspectRatio, rMessage.TextureResolution));


                        MySpritesRenderer.DrawText(Vector2.Zero, new StringBuilder(rMessage.Text), rMessage.FontColor, rMessage.TextScale);
                        // render text with fonts to rt
                        // update texture of proxy
                        MySpritesRenderer.Draw(handle.Rtv, new MyViewport(rMessage.TextureResolution * rMessage.TextureAspectRatio, rMessage.TextureResolution));

                        // render to rt
                        // my sprites renderer -> pop state
                        MySpritesRenderer.PopState();


                        MyRender11.ImmediateContext.GenerateMips(handle.ShaderView);

                        actor.MarkRenderDirty();
                    }
                    else
                    {
                        MyRenderProxy.TextNotDrawnToTexture(rMessage.EntityId);
                    }
                }
                else
                {
                    MyRenderProxy.TextNotDrawnToTexture(rMessage.EntityId);
                }

                break;
            }

            case MyRenderMessageEnum.PreloadMaterials:
            {
                var rMessage = (MyRenderMessagePreloadMaterials)message;

                //MyAssetsLoader.GetMaterials(rMessage.Name);
                MyMeshes.GetMeshId(X.TEXT(rMessage.Name));

                break;
            }

                #endregion

                #region Voxels

            case MyRenderMessageEnum.CreateClipmap:
            {
                var rMessage = (MyRenderMessageCreateClipmap)message;

                var clipmap = new MyClipmapHandler(rMessage.ClipmapId, rMessage.ScaleGroup, rMessage.WorldMatrix, rMessage.SizeLod0);
                MyClipmapFactory.ClipmapByID[rMessage.ClipmapId] = clipmap;
                clipmap.Base.LoadContent();


                break;
            }

            case MyRenderMessageEnum.UpdateClipmapCell:
            {
                var rMessage = (MyRenderMessageUpdateClipmapCell)message;

                var clipmap = MyClipmapFactory.ClipmapByID.Get(rMessage.ClipmapId);
                if (clipmap != null)
                {
                    clipmap.Base.UpdateCell(rMessage);
                }

                rMessage.Batches.Clear();
                break;
            }

            case MyRenderMessageEnum.InvalidateClipmapRange:
            {
                var rMessage = (MyRenderMessageInvalidateClipmapRange)message;

                var clipmap = MyClipmapFactory.ClipmapByID.Get(rMessage.ClipmapId);
                if (clipmap != null)
                {
                    clipmap.Base.InvalidateRange(rMessage.MinCellLod0, rMessage.MaxCellLod0);
                }

                break;
            }

            case MyRenderMessageEnum.CreateRenderVoxelMaterials:
            {
                var rMessage = (MyRenderMessageCreateRenderVoxelMaterials)message;

                Debug.Assert(MyVoxelMaterials1.CheckIndices(rMessage.Materials));
                MyVoxelMaterials1.Set(rMessage.Materials);

                rMessage.Materials = null;

                break;
            }


                #endregion

                #region Lights

            case MyRenderMessageEnum.CreateRenderLight:
            {
                var rMessage = (MyRenderMessageCreateRenderLight)message;

                //MyLight.Create(rMessage.ID);

                MyLights.Create(rMessage.ID);

                break;
            }

            case MyRenderMessageEnum.UpdateRenderLight:
            {
                var rMessage = (MyRenderMessageUpdateRenderLight)message;


                var light = MyLights.Get(rMessage.ID);

                if (light != LightId.NULL)
                {
                    var lightInfo = new MyLightInfo
                    {
                        Position           = rMessage.Position,
                        PositionWithOffset = rMessage.Position + rMessage.Offset * rMessage.Range * rMessage.ReflectorDirection,
                        CastsShadows       = rMessage.CastShadows,
                        ShadowsDistance    = rMessage.ShadowDistance,
                        ParentGID          = rMessage.ParentID,
                        UsedInForward      = rMessage.UseInForwardRender
                    };

                    MyLights.UpdateEntity(light, ref lightInfo);

                    if ((rMessage.Type & LightTypeEnum.PointLight) > 0)
                    {
                        MyLights.UpdatePointlight(light, rMessage.LightOn, rMessage.Range, new Vector3(rMessage.Color.R, rMessage.Color.G, rMessage.Color.B) / 255.0f * rMessage.Intensity, rMessage.Falloff);
                    }
                    if ((rMessage.Type & LightTypeEnum.Hemisphere) > 0)
                    {
                        //rMessage.Color;
                        //rMessage.Falloff;
                        //rMessage.Intensity;
                        //rMessage.LightOn;
                        //rMessage.ReflectorDirection;
                        //rMessage.ReflectorUp;
                    }
                    if ((rMessage.Type & LightTypeEnum.Spotlight) > 0)
                    {
                        // because it's so in dx9...
                        float coneMaxAngleCos = 1 - rMessage.ReflectorConeMaxAngleCos;
                        coneMaxAngleCos = (float)Math.Min(Math.Max(coneMaxAngleCos, 0.01), 0.99f);
                        MyLights.UpdateSpotlight(light, rMessage.ReflectorOn,
                                                 rMessage.ReflectorDirection, rMessage.ReflectorRange, coneMaxAngleCos, rMessage.ReflectorUp,
                                                 new Vector3(rMessage.ReflectorColor.R, rMessage.ReflectorColor.G, rMessage.ReflectorColor.B) / 255.0f * rMessage.Intensity, rMessage.ReflectorFalloff,
                                                 MyTextures.GetTexture(rMessage.ReflectorTexture, MyTextureEnum.CUSTOM));
                    }

                    if (rMessage.GlareOn)
                    {
                        MyLights.UpdateGlare(light, new MyGlareDesc
                            {
                                Enabled     = rMessage.GlareOn,
                                Material    = X.TEXT(rMessage.GlareMaterial),
                                Intensity   = rMessage.GlareIntensity,
                                QuerySize   = rMessage.GlareQuerySize,
                                Type        = rMessage.GlareType,
                                Size        = rMessage.GlareSize,
                                MaxDistance = rMessage.GlareMaxDistance,
                                Color       = rMessage.Color,
                                Direction   = rMessage.ReflectorDirection,
                                Range       = rMessage.Range
                            });
                    }
                }

                break;
            }

            case MyRenderMessageEnum.SetLightShadowIgnore:
            {
                var rMessage = (MyRenderMessageSetLightShadowIgnore)message;

                var light = MyLights.Get(rMessage.ID);
                var actor = MyIDTracker <MyActor> .FindByID(rMessage.ID2);

                if (light != LightId.NULL && actor != null)
                {
                    if (!MyLights.IgnoredEntitites.ContainsKey(light))
                    {
                        MyLights.IgnoredEntitites[light] = new HashSet <uint>();
                    }
                    MyLights.IgnoredEntitites[light].Add(rMessage.ID2);
                }

                break;
            }


            case MyRenderMessageEnum.ClearLightShadowIgnore:
            {
                var rMessage = (MyRenderMessageClearLightShadowIgnore)message;

                var light = MyLights.Get(rMessage.ID);
                if (light != LightId.NULL)
                {
                    MyLights.IgnoredEntitites.Remove(light);
                }

                break;
            }

            case MyRenderMessageEnum.UpdateFogSettings:
            {
                var rMessage = (MyRenderMessageUpdateFogSettings)message;

                MyEnvironment.FogSettings = rMessage.Settings;

                break;
            }

            case MyRenderMessageEnum.UpdateRenderEnvironment:
            {
                var rMessage = (MyRenderMessageUpdateRenderEnvironment)message;

                MyEnvironment.DirectionalLightDir       = VRageMath.Vector3.Normalize(rMessage.SunDirection);
                MyEnvironment.DirectionalLightIntensity = rMessage.SunIntensity * rMessage.SunColor.ToVector3();
                MyEnvironment.DirectionalLightEnabled   = rMessage.SunLightOn;
                MyEnvironment.DayTime           = (float)(rMessage.DayTime - Math.Truncate(rMessage.DayTime));
                MyEnvironment.SunDistance       = rMessage.DistanceToSun;
                MyEnvironment.SunColor          = rMessage.SunColor;
                MyEnvironment.SunMaterial       = rMessage.SunMaterial;
                MyEnvironment.SunSizeMultiplier = rMessage.SunSizeMultiplier;

                var skybox = rMessage.BackgroundTexture;

                m_resetEyeAdaptation = m_resetEyeAdaptation || rMessage.ResetEyeAdaptation;

                break;
            }

            case MyRenderMessageEnum.UpdateEnvironmentMap:
            {
                break;
            }

            case MyRenderMessageEnum.UpdatePostprocessSettings:
            {
                var rMessage = (MyRenderMessageUpdatePostprocessSettings)message;

                m_postprocessSettings = rMessage.Settings;

                break;
            }

            case MyRenderMessageEnum.UpdateSSAOSettings:
            {
                var rMessage = (MyRenderMessageUpdateSSAOSettings)message;


                MySSAO.Params.MinRadius  = rMessage.MinRadius;
                MySSAO.Params.MaxRadius  = rMessage.MaxRadius;
                MySSAO.Params.RadiusGrow = rMessage.RadiusGrowZScale;

                MySSAO.Params.RadiusBias    = rMessage.Bias;
                MySSAO.Params.Falloff       = rMessage.Falloff;
                MySSAO.Params.Normalization = rMessage.NormValue;
                MySSAO.Params.Contrast      = rMessage.Contrast;

                break;
            }

                #endregion

                #region Sprites
            case MyRenderMessageEnum.DrawSprite:
            case MyRenderMessageEnum.DrawSpriteNormalized:
            case MyRenderMessageEnum.DrawSpriteAtlas:
            case MyRenderMessageEnum.SpriteScissorPush:
            case MyRenderMessageEnum.SpriteScissorPop:
            {
                m_drawQueue.Enqueue(message);
                break;
            }

                #endregion

                #region Fonts and text

            case MyRenderMessageEnum.CreateFont:
            {
                var createFontMessage = message as MyRenderMessageCreateFont;
                Debug.Assert(createFontMessage != null);

                var renderFont = new MyRenderFont(createFontMessage.FontPath);
                renderFont.LoadContent();
                AddFont(createFontMessage.FontId, renderFont, createFontMessage.IsDebugFont);

                break;
            }

            case MyRenderMessageEnum.DrawString:
            {
                m_drawQueue.Enqueue(message);
                break;
            }

                #endregion

                #region Textures

            case MyRenderMessageEnum.PreloadTextures:
            {
                var preloadMsg = message as MyRenderMessagePreloadTextures;

                //MyTextureManager.PreloadTextures(preloadMsg.InDirectory, preloadMsg.Recursive);
                //MyTextures.UnloadTexture(texMessage.Texture);

                break;
            }

            case MyRenderMessageEnum.UnloadTexture:
            {
                var texMessage = (MyRenderMessageUnloadTexture)message;

                //MyTextureManager.UnloadTexture(texMessage.Texture);
                MyTextures.UnloadTexture(texMessage.Texture);

                break;
            }

            case MyRenderMessageEnum.ReloadTextures:
            {
                var reloadMsg = (MyRenderMessageReloadTextures)message;

                MyVoxelMaterials1.InvalidateMaterials();
                MyMeshMaterials1.InvalidateMaterials();
                MyTextures.ReloadAssetTextures();

                //MyTextureManager.UnloadTextures();
                //MyMaterialProxyFactory.ReloadTextures();

                break;
            }

            case MyRenderMessageEnum.ReloadModels:
            {
                var reloadMsg = (MyRenderMessageReloadModels)message;

                //MyMaterials.Clear();
                MyAssetsLoader.ReloadMeshes();
                MyRenderableComponent.MarkAllDirty();

                break;
            }

                #endregion

            case MyRenderMessageEnum.TakeScreenshot:
            {
                var rMessage = (MyRenderMessageTakeScreenshot)message;

                m_screenshot = new MyScreenshot(rMessage.PathToSave, rMessage.SizeMultiplier, rMessage.IgnoreSprites);

                break;
            }

            case MyRenderMessageEnum.ReloadEffects:
            {
                m_reloadShaders = true;

                //MyShaderBundleFactory.ClearCache();
                //MyShaderMaterial.ClearCache();
                //MyShaderPass.ClearCache();

                MyShaders.Recompile();
                MyMaterialShaders.Recompile();

                MyRenderableComponent.MarkAllDirty();

                foreach (var f in MyComponentFactory <MyFoliageComponent> .GetAll())
                {
                    f.Dispose();
                }

                break;
            }

            case MyRenderMessageEnum.PlayVideo:
            {
                var rMessage = (MyRenderMessagePlayVideo)message;

                MyVideoFactory.Create(rMessage.ID, rMessage.VideoFile);
                var video = MyVideoFactory.Videos.Get(rMessage.ID);
                if (video != null)
                {
                    video.Volume = rMessage.Volume;
                }

                break;
            }

            case MyRenderMessageEnum.CloseVideo:
            {
                var rMessage = (MyRenderMessageCloseVideo)message;

                var video = MyVideoFactory.Videos.Get(rMessage.ID);
                if (video != null)
                {
                    video.Stop();
                    video.Dispose();
                    MyVideoFactory.Videos.Remove(rMessage.ID);
                }

                break;
            }

            case MyRenderMessageEnum.DrawVideo:
            {
                var rMessage = (MyRenderMessageDrawVideo)message;

                var video = MyVideoFactory.Videos.Get(rMessage.ID);
                if (video != null)
                {
                    video.Draw(rMessage.Rectangle, rMessage.Color, rMessage.FitMode);
                }

                break;
            }

            case MyRenderMessageEnum.UpdateVideo:
            {
                var rMessage = (MyRenderMessageUpdateVideo)message;

                var video = MyVideoFactory.Videos.Get(rMessage.ID);
                if (video != null)
                {
                    video.Update();
                }

                break;
            }

            case MyRenderMessageEnum.SetVideoVolume:
            {
                var rMessage = (MyRenderMessageSetVideoVolume)message;

                var video = MyVideoFactory.Videos.Get(rMessage.ID);
                if (video != null)
                {
                    video.Volume = rMessage.Volume;
                }

                break;
            }

            case MyRenderMessageEnum.VideoAdaptersRequest:
            {
                MyRenderProxy.SendVideoAdapters(GetAdaptersList());
                break;
            }

            case MyRenderMessageEnum.SwitchDeviceSettings:
            {
                MyRenderProxy.RenderThread.SwitchSettings((message as MyRenderMessageSwitchDeviceSettings).Settings);
                break;
            }

            case MyRenderMessageEnum.SwitchRenderSettings:
                break;         // Can be ignored as we're handling newer version of the message.

            case MyRenderMessageEnum.SwitchRenderSettings1:
            {
                UpdateRenderSettings((message as MyRenderMessageSwitchRenderSettings1).Settings);
                break;
            }

            case MyRenderMessageEnum.UnloadData:
            {
                MyRender11.UnloadData();
                break;
            }

            case MyRenderMessageEnum.CollectGarbage:
            {
                GC.Collect();
                break;
            }

                #region Debug draw

            case MyRenderMessageEnum.DebugDrawPoint:
            case MyRenderMessageEnum.DebugDrawLine3D:
            case MyRenderMessageEnum.DebugDrawLine2D:
            case MyRenderMessageEnum.DebugDrawSphere:
            case MyRenderMessageEnum.DebugDrawAABB:
            case MyRenderMessageEnum.DebugDrawAxis:
            case MyRenderMessageEnum.DebugDrawOBB:
            case MyRenderMessageEnum.DebugDrawCone:
            case MyRenderMessageEnum.DebugDrawTriangle:
            case MyRenderMessageEnum.DebugDrawCapsule:
            case MyRenderMessageEnum.DebugDrawText2D:
            case MyRenderMessageEnum.DebugDrawText3D:
            case MyRenderMessageEnum.DebugDrawModel:
            case MyRenderMessageEnum.DebugDrawTriangles:
            case MyRenderMessageEnum.DebugDrawPlane:
            case MyRenderMessageEnum.DebugDrawCylinder:
            {
                m_debugDrawMessages.Enqueue(message);
            }
            break;

            case MyRenderMessageEnum.DebugCrashRenderThread:
            {
                throw new InvalidOperationException("Forced exception");
            }
                #endregion
            }
        }
Exemple #29
0
        static void RenderDirectionalEnvironmentLight()
        {
            PixelShaderId directionalPixelShader;

            if (!MyRenderProxy.Settings.EnableShadows)
            {
                if (DirectionalEnvironmentLight_NoShadow == PixelShaderId.NULL)
                {
                    DirectionalEnvironmentLight_NoShadow = MyShaders.CreatePs("light_dir.hlsl", new[] { new ShaderMacro("NO_SHADOWS", null) });
                }

                directionalPixelShader = DirectionalEnvironmentLight_NoShadow;
            }
            else
            {
                directionalPixelShader = DirectionalEnvironmentLight_Pixel;
            }
            MySunlightConstantsLayout constants;

            constants.Direction = MyEnvironment.DirectionalLightDir;
            constants.Color     = MyEnvironment.DirectionalLightIntensity;

            var mapping = MyMapping.MapDiscard(m_sunlightConstants);

            mapping.WriteAndPosition(ref constants);
            mapping.Unmap();

            //context.VertexShader.Set(MyCommon.FullscreenShader.VertexShader);
            RC.SetPS(directionalPixelShader);
            RC.SetCB(1, m_sunlightConstants);
            RC.SetCB(4, MyRender11.DynamicShadows.ShadowCascades.CascadeConstantBuffer);
            RC.DeviceContext.PixelShader.SetSampler(MyCommon.SHADOW_SAMPLER_SLOT, MyRender11.m_shadowmapSamplerState);

            RC.DeviceContext.PixelShader.SetShaderResource(MyCommon.SKYBOX_SLOT, MyTextures.GetView(MyTextures.GetTexture(MyEnvironment.DaySkybox, MyTextureEnum.CUBEMAP, true)));

            RC.DeviceContext.PixelShader.SetShaderResource(MyCommon.SKYBOX_IBL_SLOT,
                                                           MyRender11.IsIntelBrokenCubemapsWorkaround ? MyTextures.GetView(MyTextures.IntelFallbackCubeTexId) : MyEnvironmentProbe.Instance.cubemapPrefiltered.ShaderView);
            RC.DeviceContext.PixelShader.SetShaderResource(MyCommon.SKYBOX2_SLOT, MyTextures.GetView(MyTextures.GetTexture(MyEnvironment.NightSkybox, MyTextureEnum.CUBEMAP, true)));
            RC.DeviceContext.PixelShader.SetShaderResource(MyCommon.SKYBOX2_IBL_SLOT, MyTextures.GetView(MyTextures.GetTexture(MyEnvironment.NightSkyboxPrefiltered, MyTextureEnum.CUBEMAP, true)));

            RC.DeviceContext.PixelShader.SetShaderResource(MyCommon.CASCADES_SM_SLOT, MyRender11.DynamicShadows.ShadowCascades.CascadeShadowmapArray.ShaderView);
            RC.DeviceContext.PixelShader.SetShaderResource(MyCommon.SHADOW_SLOT, MyRender11.PostProcessedShadows.ShaderView);

            RC.DeviceContext.PixelShader.SetShaderResource(MyCommon.AMBIENT_BRDF_LUT_SLOT,
                                                           MyCommon.GetAmbientBrdfLut());

            RC.BindSRV(MyCommon.AO_SLOT, MyScreenDependants.m_ambientOcclusion);

            MyScreenPass.RunFullscreenPixelFreq(MyGBuffer.Main.Get(MyGbufferSlot.LBuffer));
            if (MyRender11.MultisamplingEnabled)
            {
                RC.SetPS(DirectionalEnvironmentLight_Sample);
                MyScreenPass.RunFullscreenSampleFreq(MyGBuffer.Main.Get(MyGbufferSlot.LBuffer));
            }
        }
        internal unsafe static void RunForwardPostprocess(RenderTargetView rt, ShaderResourceView depth, ref Matrix viewMatrix, uint?atmosphereId)
        {
            var mapping = MyMapping.MapDiscard(RC.Context, MyCommon.ProjectionConstants);

            mapping.stream.Write(Matrix.Transpose(viewMatrix));
            mapping.Unmap();

            RC.SetCB(MyCommon.FRAME_SLOT, MyCommon.FrameConstants);
            RC.SetCB(MyCommon.PROJECTION_SLOT, MyCommon.ProjectionConstants);

            RC.Context.OutputMerger.SetTargets(rt);
            RC.Context.PixelShader.SetShaderResource(0, depth);
            RC.Context.PixelShader.SetShaderResource(MyCommon.SKYBOX_SLOT, MyTextures.GetView(MyTextures.GetTexture(MyEnvironment.DaySkybox, MyTextureEnum.CUBEMAP, true)));
            RC.Context.PixelShader.SetShaderResource(MyCommon.SKYBOX2_SLOT, MyTextures.GetView(MyTextures.GetTexture(MyEnvironment.NightSkybox, MyTextureEnum.CUBEMAP, true)));
            RC.Context.PixelShader.SetSamplers(0, MyRender11.StandardSamplers);
            RC.Context.PixelShader.Set(m_ps);

            MyScreenPass.DrawFullscreenQuad(new MyViewport(256, 256));

            RC.Context.OutputMerger.SetTargets(null as RenderTargetView);
        }