Пример #1
0
        private void DrawCharGlyph(ref Vector2 vAtOriginal, float scale, ref Color currentColor, ref Vector2 vOrigin, ref float pxWidth, ref char cLast, ref Vector2 vAt, int line, char c)
        {
            MyGlyphInfo ginfo = m_glyphInfoByChar[c];

            //  If kerning is enabled, get the kern adjustment for this char pair
            if (KernEnabled)
            {
                int pxKern = CalcKern(cLast, c);
                vAt.X   += pxKern * scale;
                pxWidth += pxKern * scale;
                cLast    = c;
            }

            //  This will fix vertical coordinate in case we use "gpad" - left/top blank space in every character
            vAt.Y = vAtOriginal.Y + (ginfo.pxLeftSideBearing + MyRenderGuiConstants.FONT_TOP_SIDE_BEARING + line * LineHeight) * scale;

            //  Draw the glyph
            vAt.X += ginfo.pxLeftSideBearing * scale;
            if (ginfo.pxWidth != 0 && ginfo.pxHeight != 0)
            {
                Rectangle rSource = new Rectangle(ginfo.pxLocX, ginfo.pxLocY, ginfo.pxWidth, ginfo.pxHeight);
                Color     color   = currentColor;
                MySpritesRenderer.AddSingleSprite(m_bitmapTextureById[ginfo.nBitmapID], color, Vector2.Zero, Vector2.UnitX,
                                                  rSource, new RectangleF(vAt.X, vAt.Y, scale * rSource.Width, scale * rSource.Height));
            }

            // update the string width and advance the pen to the next drawing position
            pxWidth += ginfo.pxAdvanceWidth * scale;
            vAt.X   += (ginfo.pxAdvanceWidth - ginfo.pxLeftSideBearing) * scale;
        }
Пример #2
0
        internal void Draw(Rectangle rect, Color color, MyVideoRectangleFitMode fitMode)
        {
            Rectangle dst         = rect;
            Rectangle src         = new Rectangle(0, 0, VideoWidth, VideoHeight);
            var       videoSize   = new Vector2(VideoWidth, VideoHeight);
            float     videoAspect = videoSize.X / videoSize.Y;
            float     rectAspect  = (float)rect.Width / (float)rect.Height;

            // Automatic decision based on ratios.
            if (fitMode == MyVideoRectangleFitMode.AutoFit)
            {
                fitMode = (videoAspect > rectAspect) ? MyVideoRectangleFitMode.FitHeight : MyVideoRectangleFitMode.FitWidth;
            }

            float scaleRatio = 0.0f;

            switch (fitMode)
            {
            case MyVideoRectangleFitMode.None:
                break;

            case MyVideoRectangleFitMode.FitWidth:
                scaleRatio = (float)dst.Width / videoSize.X;
                dst.Height = (int)(scaleRatio * videoSize.Y);
                if (dst.Height > rect.Height)
                {
                    var diff = dst.Height - rect.Height;
                    dst.Height  = rect.Height;
                    diff        = (int)(diff / scaleRatio);
                    src.Y      += (int)(diff * 0.5f);
                    src.Height -= diff;
                }
                break;

            case MyVideoRectangleFitMode.FitHeight:
                scaleRatio = (float)dst.Height / videoSize.Y;
                dst.Width  = (int)(scaleRatio * videoSize.X);
                if (dst.Width > rect.Width)
                {
                    var diff = dst.Width - rect.Width;
                    dst.Width  = rect.Width;
                    diff       = (int)(diff / scaleRatio);
                    src.X     += (int)(diff * 0.5f);
                    src.Width -= diff;
                }
                break;
            }
            dst.X = rect.Left + (rect.Width - dst.Width) / 2;
            dst.Y = rect.Top + (rect.Height - dst.Height) / 2;


            VRageMath.RectangleF destination = new VRageMath.RectangleF(dst.X, dst.Y, dst.Width, -dst.Height);
            VRageMath.Rectangle? source      = src;
            Vector2 origin = new Vector2(src.Width / 2 * 0, src.Height);

            MySpritesRenderer.AddSingleSprite(m_texture.ShaderView, videoSize, color, origin, Vector2.UnitX, source, destination);
        }
Пример #3
0
 internal void AddSprite(Vector2 clipOffset, Vector2 clipScale, Vector2 texOffset, Vector2 texScale,
                         Vector2 origin, Vector2 tangent, Byte4 color)
 {
     MySpritesRenderer.StackTop().m_instances.Add(new MyVertexFormatSpritePositionTextureRotationColor(
                                                      new HalfVector4(clipOffset.X, clipOffset.Y, clipScale.X, clipScale.Y),
                                                      new HalfVector4(texOffset.X, texOffset.Y, texScale.X, texScale.Y),
                                                      new HalfVector4(origin.X, origin.Y, tangent.X, tangent.Y),
                                                      color));
 }
Пример #4
0
        internal static void Draw(bool draw = true)
        {
            try
            {
                MyGpuProfiler.IC_BeginBlock("Draw");
                GetRenderProfiler().StartProfilingBlock("ProcessMessages");
                MyGpuProfiler.IC_BeginBlock("ProcessMessageQueue");
                TransferLocalMessages();
                ProcessMessageQueue();
                MyGpuProfiler.IC_EndBlock();
                GetRenderProfiler().EndProfilingBlock();

                if (draw)
                {
                    m_drawScene = false;
                    DispatchDrawQueue();

                    if (m_drawScene)
                    {
                        DrawScene();
                    }

                    if (!(MyRender11.Settings.OffscreenSpritesRendering && m_drawScene))
                    {
                        ProcessDrawQueue();
                        DrawSprites(MyRender11.Backbuffer);
                    }

                    MyFileTextureManager texManager = MyManagers.FileTextures;
                    texManager.LoadAllRequested();

                    if (m_texturesToRender.Count > 0)
                    {
                        VRage.Render11.PostprocessStage.MySaveExportedTextures.RenderColoredTextures(m_texturesToRender);
                    }
                }

                MyLinesRenderer.Clear();
                MySpritesRenderer.Clear();

                m_drawQueue.Clear();
                MyGpuProfiler.IC_EndBlock();
            }
            catch (SharpDXException e)
            {
                MyRender11.Log.IncreaseIndent();
                MyRender11.Log.WriteLine(" " + e);
                if (e.Descriptor == SharpDX.DXGI.ResultCode.DeviceRemoved)
                {
                    MyRender11.Log.WriteLine("Reason: " + Device.DeviceRemovedReason);
                }
                MyRender11.Log.DecreaseIndent();

                throw;
            }
        }
Пример #5
0
 private static void DrawSprites(IRtvBindable texture)
 {
     GetRenderProfiler().StartProfilingBlock("MySpritesRenderer.Draw");
     MyStatsUpdater.Timestamps.Update(ref MyStatsUpdater.Timestamps.PreDrawSprites_Draw);
     MyGpuProfiler.IC_BeginBlock("SpriteRenderer");
     MySpritesRenderer.Draw(texture, new MyViewport(MyRender11.ViewportResolution.X, MyRender11.ViewportResolution.Y));
     MyGpuProfiler.IC_EndBlock();
     MyStatsUpdater.Timestamps.Update(ref MyStatsUpdater.Timestamps.PostDrawSprites_Draw);
     GetRenderProfiler().EndProfilingBlock();
 }
Пример #6
0
        internal static void Draw(bool draw = true)
        {
            //if (false) Debug.Assert(MyClipmap.LodLevel.DrewLastFrame);
            //MyClipmap.LodLevel.DrewLastFrame = false;

            try
            {
                GetRenderProfiler().StartProfilingBlock("ProcessMessages");
                TransferLocalMessages();
                ProcessMessageQueue();
                GetRenderProfiler().EndProfilingBlock();

                if (draw)
                {
                    MyImmediateRC.RC.Clear();
                    GetRenderProfiler().StartProfilingBlock("ProcessDrawQueue");
                    ProcessDrawQueue();
                    GetRenderProfiler().EndProfilingBlock();

                    /*GetRenderProfiler().StartProfilingBlock("ProcessDebugMessages");
                     * ProcessDebugMessages();
                     * GetRenderProfiler().EndProfilingBlock();*/

                    GetRenderProfiler().StartProfilingBlock("MySpritesRenderer.Draw");
                    //MyCommon.UpdateFrameConstants();
                    MySpritesRenderer.Draw(MyRender11.Backbuffer.m_RTV, new MyViewport(MyRender11.ViewportResolution.X, MyRender11.ViewportResolution.Y));
                    GetRenderProfiler().EndProfilingBlock();

                    MyTextures.Load();
                }

                if (m_profilingStarted)
                {
                    MyGpuProfiler.IC_BeginBlock("Waiting for present");
                }

                MyLinesRenderer.Clear();
                MySpritesRenderer.Clear();

                m_drawQueue.Clear();
                m_debugDrawMessages.Clear();
            }
            catch (SharpDXException e)
            {
                MyRender11.Log.IncreaseIndent();
                MyRender11.Log.WriteLine(" " + e);
                if (e.Descriptor == SharpDX.DXGI.ResultCode.DeviceRemoved)
                {
                    MyRender11.Log.WriteLine("Reason: " + Device.DeviceRemovedReason);
                }
                MyRender11.Log.DecreaseIndent();

                throw;
            }
        }
Пример #7
0
        internal static unsafe void InitSubsystems()
        {
            InitializeBlendStates();
            InitializeRasterizerStates();
            InitilizeSamplerStates();

            MyCommon.Init();
            MyPipelineStates.Init();
            MyTextures.Init();
            MyVertexLayouts.Init();
            MyShaders.Init();
            MyRwTextures.Init();
            MyHwBuffers.Init();
            MyMeshes.Init();
            MyMeshTableSRV.Init();
            MyMergeInstancing.Init();
            MyGeometryRenderer.Init();
            MyLightRendering.Init();
            MyShadows.Init();
            MyLinesRenderer.Init();
            MySpritesRenderer.Init();
            MyPrimitivesRenderer.Init();
            MyFoliageRenderer.Init();
            MyOutline.Init();

            MyComponents.Init();

            MyBillboardRenderer.Init(); // hardcoded limits
            MyDebugRenderer.Init();
            MyGPUFoliageGenerating.Init();

            MyScreenDecals.Init();
            MyEnvProbeProcessing.Init();
            MyShadowsResolve.Init();
            MyAtmosphereRenderer.Init();
            MyAAEdgeMarking.Init();
            MyScreenPass.Init();
            MyCopyToRT.Init();
            MyBlendTargets.Init();
            MyFXAA.Init();
            MyDepthResolve.Init();
            MyBloom.Init();
            MyLuminanceAverage.Init();
            MyToneMapping.Init();
            MySSAO.Init();
            MyHdrDebugTools.Init();

            MySceneMaterials.Init();
            MyMaterials1.Init();
            MyVoxelMaterials1.Init();
            MyMeshMaterials1.Init();

            //MyShaderFactory.RunCompilation(); // rebuild
        }
Пример #8
0
        internal static unsafe void InitSubsystems()
        {
            MyRwTextures.Init();
            MyHwBuffers.Init();
            MyPipelineStates.Init();
            ResetShadows(MyRenderProxy.Settings.ShadowCascadeCount, RenderSettings.ShadowQuality.ShadowCascadeResolution());
            MyRender11.Init();
            MyCommon.Init();
            SamplerStates.Init();
            MyDepthStencilState.Init();
            MyTextures.Init();
            MyVertexLayouts.Init();
            MyShaders.Init();
            MyMeshes.Init();
            MyMeshTableSRV.Init();
            MyLightRendering.Init();
            MyLinesRenderer.Init();
            MySpritesRenderer.Init();
            MyPrimitivesRenderer.Init();
            MyOutline.Init();
            MyBlur.Init();
            MyTransparentRendering.Init();

            MyFoliageComponents.Init();

            MyBillboardRenderer.Init(); // hardcoded limits
            MyDebugRenderer.Init();

            MyScreenDecals.Init();
            MyEnvProbeProcessing.Init();
            MyAtmosphereRenderer.Init();
            MyCloudRenderer.Init();
            MyAAEdgeMarking.Init();
            MyScreenPass.Init();
            MyCopyToRT.Init();
            MyBlendTargets.Init();
            MyFXAA.Init();
            MyDepthResolve.Init();
            MyBloom.Init();
            MyLuminanceAverage.Init();
            MyToneMapping.Init();
            MySSAO.Init();
            MyPlanetBlur.Init();
            MyHdrDebugTools.Init();

            MySceneMaterials.Init();
            MyMaterials1.Init();
            MyVoxelMaterials1.Init();
            MyMeshMaterials1.Init();
        }
Пример #9
0
        public static void Draw(Dictionary <VRageRender.MyRenderStats.ColumnEnum, List <MyStats> > m_stats, float scale, Color color)
        {
            foreach (var pair in m_stats)
            {
                try
                {
                    foreach (var s in pair.Value)
                    {
                        s.WriteTo(m_tmpDrawText);
                        m_tmpDrawText.AppendLine(); // Newline between each group
                    }

                    Vector2 pos = new Vector2(0, 0);

                    if (pair.Key == VRageRender.MyRenderStats.ColumnEnum.Right)
                    {
                        Vector2 size = MyRender11.GetDebugFont().MeasureString(m_tmpDrawText, scale);
                        if (m_rightColumnWidth < size.X)
                        {
                            m_rightColumnWidth      = size.X * m_rightGapSizeRatio; // Add some gap
                            m_rightColumnChangeTime = MyRender11.CurrentDrawTime;
                        }
                        else if (m_rightColumnWidth > size.X * m_rightGapSizeRatio && (MyRender11.CurrentDrawTime - m_rightColumnChangeTime).Seconds > 3)
                        {
                            m_rightColumnWidth      = size.X * m_rightGapSizeRatio;
                            m_rightColumnChangeTime = MyRender11.CurrentDrawTime;
                        }
                        pos = new Vector2(MyRender11.ViewportResolution.X - m_rightColumnWidth, 0);
                    }

                    MySpritesRenderer.DrawText(pos, m_tmpDrawText, color, scale);
                }
                finally
                {
                    m_tmpDrawText.Clear();
                }
            }
        }
Пример #10
0
        public static IBorrowedRtvTexture DrawSpritesOffscreen(string textureName, int widht, int height,
                                                               Format format = Format.B8G8R8A8_UNorm, Color?clearColor = null)
        {
            if (String.IsNullOrEmpty(textureName))
            {
                textureName = DEFAULT_TEXTURE_TARGET;
            }

            if (widht == -1)
            {
                widht = MyRender11.ViewportResolution.X;
            }

            if (height == -1)
            {
                height = MyRender11.ViewportResolution.Y;
            }

            var texture = MyManagers.RwTexturesPool.BorrowRtv(textureName, widht, height, format);

            MyImmediateRC.RC.ClearRtv(texture, clearColor == null ? Color.Zero : clearColor.Value);
            DispatchDrawQueue(true);

            MySpritesRenderer.PushState(new Vector2(widht, height));
            bool processed = ProcessDrawSpritesQueue(textureName);

            if (!processed)
            {
                MySpritesRenderer.PopState();
                return(texture);
            }

            DrawSprites(texture, new MyViewport(widht, height));
            MySpritesRenderer.PopState();
            return(texture);
        }
Пример #11
0
 internal void Commit()
 {
     MySpritesRenderer.Commit(this);
 }
Пример #12
0
 internal void AddSprite(MyVertexFormatSpritePositionTextureRotationColor sprite)
 {
     MySpritesRenderer.StackTop().m_instances.Add(sprite);
     Count++;
 }
Пример #13
0
        public static void Draw(Dictionary <MyRenderStats.ColumnEnum, List <MyStats> > m_stats, float scale, Color color)
        {
            foreach (var pair in m_stats)
            {
                try
                {
                    foreach (var s in pair.Value)
                    {
                        s.WriteTo(m_tmpDrawText);
                        m_tmpDrawText.AppendLine(); // Newline between each group
                    }

                    Vector2 pos = new Vector2(10, 10);

                    if (pair.Key == MyRenderStats.ColumnEnum.Right)
                    {
                        Vector2 size = MyRender11.GetDebugFont().MeasureString(m_tmpDrawText, scale);
                        if (m_rightColumnWidth < size.X)
                        {
                            m_rightColumnWidth      = size.X * m_rightGapSizeRatio; // Add some gap
                            m_rightColumnChangeTime = MyRender11.CurrentDrawTime;
                        }
                        else if (m_rightColumnWidth > size.X * m_rightGapSizeRatio && (MyRender11.CurrentDrawTime - m_rightColumnChangeTime).Seconds > 3)
                        {
                            m_rightColumnWidth      = size.X * m_rightGapSizeRatio;
                            m_rightColumnChangeTime = MyRender11.CurrentDrawTime;
                        }
                        pos = new Vector2(MyRender11.ViewportResolution.X - m_rightColumnWidth, 0);
                    }

                    /* Add info about render buffers */
                    m_tmpDrawText.Append("Hardware Buffers (count/bytes):\n");

                    MyBufferStats stats, total = new MyBufferStats();

                    MyHwBuffers.GetConstantBufferStats(out stats);
                    m_tmpDrawText.AppendFormat("   Constant: {0:N0}/{1:N0}\n", stats.TotalBuffers, stats.TotalBytes);
                    total.TotalBytes += stats.TotalBytes; total.TotalBuffers += stats.TotalBuffers;

                    MyHwBuffers.GetVertexBufferStats(out stats);
                    m_tmpDrawText.AppendFormat("   Vertex: {0:N0}/{1:N0}\n", stats.TotalBuffers, stats.TotalBytes);
                    total.TotalBytes += stats.TotalBytes; total.TotalBuffers += stats.TotalBuffers;

                    MyHwBuffers.GetIndexBufferStats(out stats);
                    m_tmpDrawText.AppendFormat("   Index: {0:N0}/{1:N0}\n", stats.TotalBuffers, stats.TotalBytes);
                    total.TotalBytes += stats.TotalBytes; total.TotalBuffers += stats.TotalBuffers;

                    MyHwBuffers.GetStructuredBufferStats(out stats);
                    m_tmpDrawText.AppendFormat("   Structured: {0:N0}/{1:N0}\n", stats.TotalBuffers, stats.TotalBytes);
                    total.TotalBytes += stats.TotalBytes; total.TotalBuffers += stats.TotalBuffers;

                    m_tmpDrawText.AppendFormat("   Total: {0:N0}/{1:N0}\n", total.TotalBuffers, total.TotalBytes);


                    m_tmpDrawText.Append("Textures:\n");
                    MyFileTextureUsageReport report = MyManagers.FileTextures.GetReport();

                    m_tmpDrawText.AppendFormat("   Total: {0}\n", report.TexturesTotal);
                    m_tmpDrawText.AppendFormat("   Loaded: {0}\n", report.TexturesLoaded);
                    m_tmpDrawText.AppendFormat("   Memory: {0:N0}\n", report.TotalTextureMemory);

                    MySpritesRenderer.DrawText(pos, m_tmpDrawText, color, scale);
                }
                finally
                {
                    m_tmpDrawText.Clear();
                }
            }
        }
Пример #14
0
        internal static void DrawHierarchyDebug()
        {
            var worldToClip   = MyEnvironment.ViewProjection;
            var displayString = new StringBuilder();

            var batch = MyLinesRenderer.CreateBatch();

            if (MyRender11.Settings.DisplayIDs)
            {
                foreach (var actor in MyActorFactory.GetAll())
                {
                    var h = actor.GetGroupLeaf();
                    var r = actor.GetRenderable();

                    Vector3 position;
                    uint    ID;

                    if (r != null)
                    {
                        position = r.Owner.WorldMatrix.Translation;
                        ID       = r.Owner.ID;
                    }
                    else if (h != null)
                    {
                        position = h.Owner.WorldMatrix.Translation;
                        ID       = h.Owner.ID;
                    }
                    else
                    {
                        continue;
                    }

                    var clipPosition = Vector3.Transform(position, ref worldToClip);
                    clipPosition.X = clipPosition.X * 0.5f + 0.5f;
                    clipPosition.Y = clipPosition.Y * -0.5f + 0.5f;

                    if (clipPosition.Z > 0 && clipPosition.Z < 1)
                    {
                        displayString.AppendFormat("{0}", ID);
                        MySpritesRenderer.DrawText(new Vector2(clipPosition.X, clipPosition.Y) * MyRender11.ViewportResolution,
                                                   displayString, Color.DarkCyan, 0.5f);
                    }

                    displayString.Clear();
                }
            }

            if (MyRender11.Settings.DisplayAabbs)
            {
                foreach (var actor in MyActorFactory.GetAll())
                {
                    var h = actor.GetGroupRoot();
                    var r = actor.GetRenderable();

                    if (h != null)
                    {
                        var bb = BoundingBoxD.CreateInvalid();

                        foreach (var child in h.m_children)
                        {
                            if (child.IsVisible)
                            {
                                bb.Include(child.Aabb);
                            }
                        }

                        batch.AddBoundingBox((BoundingBox)bb, Color.Red);
                        MyPrimitivesRenderer.Draw6FacedConvexZ(bb.GetCorners().Select(x => (Vector3)x).ToArray(), Color.Red, 0.1f);
                    }
                    else if (r != null && actor.GetGroupLeaf() == null)
                    {
                        batch.AddBoundingBox((BoundingBox)r.Owner.Aabb, Color.Green);
                    }
                }
            }

            batch.Commit();
        }
Пример #15
0
        internal static unsafe void InitSubsystems()
        {
            MyManagers.OnDeviceInit();
            //MyRwTextures.Init();
            MyHwBuffers.Init();
            ResetShadows(MyShadowCascades.Settings.NewData.CascadesCount, RenderSettings.ShadowQuality.ShadowCascadeResolution());
            MyRender11.Init();
            MyCommon.Init();
            MyVertexLayouts.Init();
            MyShaders.Init();
            MyMeshes.Init();
            MyMeshTableSrv.Init();
            MyLightRendering.Init();
            MyLinesRenderer.Init();
            MySpritesRenderer.Init();
            MyPrimitivesRenderer.Init();
            MyOutline.Init();
            MyBlur.Init();
            MyTransparentRendering.Init();

            MyFoliageComponents.Init();

            MyBillboardRenderer.Init(); // hardcoded limits
            MyDebugRenderer.Init();

            MyScreenDecals.Init();
            MyEnvProbeProcessing.Init();
            MyAtmosphereRenderer.Init();
            MyCloudRenderer.Init();
            MyAAEdgeMarking.Init();
            MyScreenPass.Init();
            MyCopyToRT.Init();
            MyBlendTargets.Init();
            MyFXAA.Init();
            MyDepthResolve.Init();
            MyBloom.Init();
            MyLuminanceAverage.Init();
            MyToneMapping.Init();
            MySSAO.Init();
            MyHdrDebugTools.Init();

            MySceneMaterials.Init();
            MyMaterials1.Init();
            MyVoxelMaterials1.Init();
            MyMeshMaterials1.Init();

            MyHBAO.Init();

            try
            {
                if (m_settings.UseStereoRendering)
                {
                    var openVR = new MyOpenVR();
                    MyStereoStencilMask.InitUsingOpenVR();
                }
            }
            catch (System.Exception e)
            {
                if (!VRage.MyCompilationSymbols.DX11ForceStereo)
                {
                    throw;
                }
                MyStereoStencilMask.InitUsingUndefinedMask();
            }
        }
Пример #16
0
        static void ProcessDebugMessages()
        {
            bool clearPersistent = false;

            m_persistentDebugMessagesTemp.Clear();
            var linesBatch        = MyLinesRenderer.CreateBatch();
            var noDepthLinesBatch = MyLinesRenderer.CreateBatch();

            noDepthLinesBatch.IgnoreDepth = true;
            var lines2D = MyLinesRenderer.CreateBatch();

            lines2D.IgnoreDepth = true;

            while (m_debugDrawMessages.Count > 0)
            {
                MyRenderMessageBase debugDrawMessage = m_debugDrawMessages.Dequeue();
                if (debugDrawMessage.IsPersistent)
                {
                    m_persistentDebugMessagesTemp.Add(debugDrawMessage);
                }

                MyRenderMessageEnum messageType = debugDrawMessage.MessageType;

                switch (messageType)
                {
                case MyRenderMessageEnum.DebugDrawLine3D:
                {
                    MyRenderMessageDebugDrawLine3D message = (MyRenderMessageDebugDrawLine3D)debugDrawMessage;

                    if (message.DepthRead)
                    {
                        linesBatch.Add(message.PointFrom - MyRender11.Environment.Matrices.CameraPosition, message.PointTo - MyRender11.Environment.Matrices.CameraPosition, message.ColorFrom, message.ColorTo);
                    }
                    else
                    {
                        noDepthLinesBatch.Add(message.PointFrom - MyRender11.Environment.Matrices.CameraPosition, message.PointTo - MyRender11.Environment.Matrices.CameraPosition, message.ColorFrom, message.ColorTo);
                    }

                    break;
                }

                case MyRenderMessageEnum.DebugDrawLine2D:
                {
                    MyRenderMessageDebugDrawLine2D message = (MyRenderMessageDebugDrawLine2D)debugDrawMessage;

                    var matrix = message.Projection ?? Matrix.CreateOrthographicOffCenter(0, MyRender11.ViewportResolution.X, MyRender11.ViewportResolution.Y, 0, 0, -1);

                    if (!lines2D.CustomViewProjection.HasValue || (lines2D.CustomViewProjection.HasValue && lines2D.CustomViewProjection.Value != matrix))
                    {
                        lines2D.Commit();
                        lines2D                      = MyLinesRenderer.CreateBatch();
                        lines2D.IgnoreDepth          = true;
                        lines2D.CustomViewProjection = matrix;
                    }

                    var p0 = new Vector3(message.PointFrom.X, message.PointFrom.Y, 0);
                    var p1 = new Vector3(message.PointTo.X, message.PointTo.Y, 0);
                    lines2D.Add(p0, p1, message.ColorFrom, message.ColorTo);

                    break;
                }

                case MyRenderMessageEnum.DebugDrawPoint:
                {
                    MyRenderMessageDebugDrawPoint message = (MyRenderMessageDebugDrawPoint)debugDrawMessage;

                    var batch = message.DepthRead ? linesBatch : noDepthLinesBatch;

                    var scale = 0.125f;

                    var borderDepth = MyRender11.UseComplementaryDepthBuffer ? 0.0f : 1.0f;
                    borderDepth = message.ClipDistance.HasValue ? Vector3.Transform(new Vector3(0, 0, -message.ClipDistance.Value), MyRender11.Environment.Matrices.Projection).Z : borderDepth;

                    var clipPosition = Vector3D.Transform(message.Position, MyRender11.Environment.Matrices.ViewProjectionAt0);
                    clipPosition.X = clipPosition.X * 0.5f + 0.5f;
                    clipPosition.Y = clipPosition.Y * -0.5f + 0.5f;

                    //Debug.Assert(MyRender11.UseComplementaryDepthBuffer);

                    Vector3 position = (Vector3)(message.Position - MyRender11.Environment.Matrices.CameraPosition);

                    bool drawCondition =
                        MyRender11.UseComplementaryDepthBuffer
                                ? clipPosition.Z > borderDepth && clipPosition.Z < 1
                                : clipPosition.Z < borderDepth && clipPosition.Z > 0;

                    if (drawCondition)
                    {
                        batch.Add(position + Vector3.UnitX * scale, position - Vector3.UnitX * scale, message.Color);
                        batch.Add(position + Vector3.UnitY * scale, position - Vector3.UnitY * scale, message.Color);
                        batch.Add(position + Vector3.UnitZ * scale, position - Vector3.UnitZ * scale, message.Color);
                    }

                    break;
                }

                case MyRenderMessageEnum.DebugDrawSphere:
                {
                    MyRenderMessageDebugDrawSphere message = (MyRenderMessageDebugDrawSphere)debugDrawMessage;

                    var borderDepth = MyRender11.UseComplementaryDepthBuffer ? 0.0f : 1.0f;
                    borderDepth = message.ClipDistance.HasValue ? Vector3.Transform(new Vector3(0, 0, -message.ClipDistance.Value), MyRender11.Environment.Matrices.Projection).Z : borderDepth;

                    Vector3D position = message.Position - MyRender11.Environment.Matrices.CameraPosition;

                    var clipPosition = Vector3D.Transform(position, MyRender11.Environment.Matrices.ViewProjectionAt0);
                    clipPosition.X = clipPosition.X * 0.5f + 0.5f;
                    clipPosition.Y = clipPosition.Y * -0.5f + 0.5f;

                    bool drawCondition =
                        MyRender11.UseComplementaryDepthBuffer
                                ? clipPosition.Z > borderDepth && clipPosition.Z < 1
                                : clipPosition.Z < borderDepth && clipPosition.Z > 0;

                    if (drawCondition)
                    {
                        var batch = message.DepthRead ? linesBatch : noDepthLinesBatch;

                        batch.AddSphereRing(new BoundingSphere(position, message.Radius), message.Color, Matrix.Identity);
                        batch.AddSphereRing(new BoundingSphere(position, message.Radius), message.Color, Matrix.CreateRotationX(MathHelper.PiOver2));
                        batch.AddSphereRing(new BoundingSphere(position, message.Radius), message.Color, Matrix.CreateRotationZ(MathHelper.PiOver2));
                    }

                    break;
                }

                case MyRenderMessageEnum.DebugDrawAABB:
                {
                    MyRenderMessageDebugDrawAABB message = (MyRenderMessageDebugDrawAABB)debugDrawMessage;

                    BoundingBox aabb = (BoundingBox)message.AABB;
                    aabb.Translate(-MyRender11.Environment.Matrices.CameraPosition);

                    if (message.DepthRead)
                    {
                        linesBatch.AddBoundingBox(aabb, message.Color);
                    }
                    else
                    {
                        noDepthLinesBatch.AddBoundingBox(aabb, message.Color);
                    }

                    if (message.Shaded)
                    {
                        unsafe
                        {
                            Vector3 *points = stackalloc Vector3[8];

                            aabb.GetCornersUnsafe(points);

                            MyPrimitivesRenderer.Draw6FacedConvexZ(points, message.Color, message.Alpha);
                        }
                    }

                    break;
                }

                case MyRenderMessageEnum.DebugDraw6FaceConvex:
                {
                    MyRenderMessageDebugDraw6FaceConvex convex = (MyRenderMessageDebugDraw6FaceConvex)debugDrawMessage;

                    if (convex.Fill)
                    {
                        MyPrimitivesRenderer.Draw6FacedConvex(convex.Vertices, convex.Color, convex.Alpha);
                    }
                    else
                    {
                        if (convex.DepthRead)
                        {
                            linesBatch.Add6FacedConvexWorld(convex.Vertices, convex.Color);
                        }
                        else
                        {
                            noDepthLinesBatch.Add6FacedConvexWorld(convex.Vertices, convex.Color);
                        }
                    }
                    break;
                }


                case MyRenderMessageEnum.DebugDrawCone:
                {
                    MyRenderMessageDebugDrawCone message = (MyRenderMessageDebugDrawCone)debugDrawMessage;

                    var batch = message.DepthRead ? linesBatch : noDepthLinesBatch;

                    var axis = message.DirectionVector;
                    axis.Normalize();

                    var apex = message.Translation + message.DirectionVector;

                    var steps    = 32;
                    var stepsRcp = (float)(Math.PI * 2 / steps);
                    for (int i = 0; i < 32; i++)
                    {
                        float a0 = i * stepsRcp;
                        float a1 = (i + 1) * stepsRcp;

                        var A = message.Translation + Vector3D.Transform(message.BaseVector, MatrixD.CreateFromAxisAngle(axis, a0)) - MyRender11.Environment.Matrices.CameraPosition;
                        var B = message.Translation + Vector3D.Transform(message.BaseVector, MatrixD.CreateFromAxisAngle(axis, a1)) - MyRender11.Environment.Matrices.CameraPosition;

                        batch.Add(A, B, message.Color);
                        batch.Add(A, apex, message.Color);
                    }

                    break;
                }

                case MyRenderMessageEnum.DebugDrawAxis:
                {
                    MyRenderMessageDebugDrawAxis message = (MyRenderMessageDebugDrawAxis)debugDrawMessage;

                    var batch = message.DepthRead ? linesBatch : noDepthLinesBatch;

                    Vector3 position = message.Matrix.Translation - MyRender11.Environment.Matrices.CameraPosition;

                    if (message.SkipScale)
                    {
                        batch.Add(position, position + Vector3.Normalize(message.Matrix.Right) * message.AxisLength, Color.Red);
                        batch.Add(position, position + Vector3.Normalize(message.Matrix.Up) * message.AxisLength, Color.Green);
                        batch.Add(position, position + Vector3.Normalize(message.Matrix.Forward) * message.AxisLength, Color.Blue);
                    }
                    else
                    {
                        batch.Add(position, position + message.Matrix.Right * message.AxisLength, Color.Red);
                        batch.Add(position, position + message.Matrix.Up * message.AxisLength, Color.Green);
                        batch.Add(position, position + message.Matrix.Forward * message.AxisLength, Color.Blue);
                    }

                    break;
                }

                case MyRenderMessageEnum.DebugDrawOBB:
                {
                    MyRenderMessageDebugDrawOBB message = (MyRenderMessageDebugDrawOBB)debugDrawMessage;

                    Vector3D[] cornersD = new Vector3D[8];
                    MatrixD    matrix   = (MatrixD)message.Matrix;
                    new MyOrientedBoundingBoxD(matrix).GetCorners(cornersD, 0);

                    Vector3[] corners = new Vector3[8];
                    for (int i = 0; i < 8; i++)
                    {
                        corners[i] = (cornersD[i] - MyRender11.Environment.Matrices.CameraPosition);
                    }

                    if (message.DepthRead)
                    {
                        linesBatch.Add6FacedConvex(corners, message.Color);
                    }
                    else
                    {
                        noDepthLinesBatch.Add6FacedConvex(corners, message.Color);
                    }

                    MyPrimitivesRenderer.Draw6FacedConvexZ(corners, message.Color, message.Alpha);

                    break;
                }

                case MyRenderMessageEnum.DebugDrawFrustrum:
                {
                    MyRenderMessageDebugDrawFrustrum message = (MyRenderMessageDebugDrawFrustrum)debugDrawMessage;

                    Vector3[] corners = new Vector3[8];

                    Matrix m = message.Frustrum.Matrix;

                    m.Translation -= MyRender11.Environment.Matrices.CameraPosition;

                    message.Frustrum.Matrix = m;

                    message.Frustrum.GetCorners(corners);

                    if (message.DepthRead)
                    {
                        linesBatch.Add6FacedConvex(corners, message.Color);
                    }
                    else
                    {
                        noDepthLinesBatch.Add6FacedConvex(corners, message.Color);
                    }

                    MyPrimitivesRenderer.Draw6FacedConvexZ(corners, message.Color, message.Alpha);

                    break;
                }

                case MyRenderMessageEnum.DebugDrawCylinder:
                {
                    MyRenderMessageDebugDrawCylinder message = (MyRenderMessageDebugDrawCylinder)debugDrawMessage;

                    var batch = message.DepthRead ? linesBatch : noDepthLinesBatch;

                    var steps    = 32;
                    var stepsRcp = (float)(Math.PI * 2 / steps);
                    for (int i = 0; i < 32; i++)
                    {
                        float a0 = i * stepsRcp;
                        float a1 = (i + 1) * stepsRcp;

                        Vector3D A = new Vector3D(Math.Cos(a0), 1.0f, Math.Sin(a0)) * 0.5f;
                        Vector3D B = new Vector3D(Math.Cos(a1), 1.0f, Math.Sin(a1)) * 0.5f;
                        Vector3D C = A - Vector3D.UnitY;
                        Vector3D D = B - Vector3D.UnitY;

                        A = Vector3D.Transform(A, message.Matrix);
                        B = Vector3D.Transform(B, message.Matrix);
                        C = Vector3D.Transform(C, message.Matrix);
                        D = Vector3D.Transform(D, message.Matrix);

                        A -= MyRender11.Environment.Matrices.CameraPosition;
                        B -= MyRender11.Environment.Matrices.CameraPosition;
                        C -= MyRender11.Environment.Matrices.CameraPosition;
                        D -= MyRender11.Environment.Matrices.CameraPosition;

                        batch.Add(A, B, message.Color);
                        batch.Add(A, C, message.Color);
                        batch.Add(C, D, message.Color);
                    }

                    break;
                }

                case MyRenderMessageEnum.DebugDrawTriangle:
                {
                    MyRenderMessageDebugDrawTriangle message = (MyRenderMessageDebugDrawTriangle)debugDrawMessage;

                    MyPrimitivesRenderer.DrawTriangle(message.Vertex0 - MyRender11.Environment.Matrices.CameraPosition,
                                                      message.Vertex1 - MyRender11.Environment.Matrices.CameraPosition,
                                                      message.Vertex2 - MyRender11.Environment.Matrices.CameraPosition, message.Color);

                    break;
                }

                case MyRenderMessageEnum.DebugDrawTriangles:
                {
                    MyRenderMessageDebugDrawTriangles message = (MyRenderMessageDebugDrawTriangles)debugDrawMessage;

                    for (int i = 0; i < message.Indices.Count; i += 3)
                    {
                        var v0 = Vector3D.Transform(message.Vertices[message.Indices[i + 0]], message.WorldMatrix) - MyRender11.Environment.Matrices.CameraPosition;
                        var v1 = Vector3D.Transform(message.Vertices[message.Indices[i + 1]], message.WorldMatrix) - MyRender11.Environment.Matrices.CameraPosition;
                        var v2 = Vector3D.Transform(message.Vertices[message.Indices[i + 2]], message.WorldMatrix) - MyRender11.Environment.Matrices.CameraPosition;

                        MyPrimitivesRenderer.DrawTriangle(v0, v1, v2, message.Color);
                    }

                    break;
                }

                case MyRenderMessageEnum.DebugDrawMesh:
                {
                    MyPrimitivesRenderer.DebugMesh(debugDrawMessage as MyRenderMessageDebugDrawMesh);

                    break;
                }

                case MyRenderMessageEnum.DebugDrawCapsule:
                {
                    MyRenderMessageDebugDrawCapsule message = (MyRenderMessageDebugDrawCapsule)debugDrawMessage;

                    var batch = message.DepthRead ? linesBatch : noDepthLinesBatch;

                    batch.AddSphereRing(new BoundingSphere(message.P0 - MyRender11.Environment.Matrices.CameraPosition, message.Radius), message.Color, Matrix.Identity);
                    batch.AddSphereRing(new BoundingSphere(message.P0 - MyRender11.Environment.Matrices.CameraPosition, message.Radius), message.Color, Matrix.CreateRotationX(MathHelper.PiOver2));
                    batch.AddSphereRing(new BoundingSphere(message.P1 - MyRender11.Environment.Matrices.CameraPosition, message.Radius), message.Color, Matrix.Identity);
                    batch.AddSphereRing(new BoundingSphere(message.P1 - MyRender11.Environment.Matrices.CameraPosition, message.Radius), message.Color, Matrix.CreateRotationX(MathHelper.PiOver2));

                    batch.Add(message.P0 - MyRender11.Environment.Matrices.CameraPosition, message.P1 - MyRender11.Environment.Matrices.CameraPosition, message.Color);


                    break;
                }

                case MyRenderMessageEnum.DebugDrawText2D:
                {
                    MyRenderMessageDebugDrawText2D message = (MyRenderMessageDebugDrawText2D)debugDrawMessage;

                    var text = new StringBuilder(message.Text);

                    MySpritesRenderer.DrawText(message.Coord, text, message.Color, message.Scale, message.Align);

                    break;
                }

                case MyRenderMessageEnum.DebugDrawText3D:
                {
                    MyRenderMessageDebugDrawText3D message = (MyRenderMessageDebugDrawText3D)debugDrawMessage;

                    Vector3D position = message.Coord;

                    var worldToClip = MyRender11.Environment.Matrices.ViewProjectionD;
                    if (message.CustomViewProjection != -1)
                    {
                        if (!MyRenderProxy.BillboardsViewProjectionRead.ContainsKey(message.CustomViewProjection))
                        {
                            break;
                        }

                        var i = message.CustomViewProjection;

                        var scaleX  = MyRenderProxy.BillboardsViewProjectionRead[i].Viewport.Width / (float)MyRender11.ViewportResolution.X;
                        var scaleY  = MyRenderProxy.BillboardsViewProjectionRead[i].Viewport.Height / (float)MyRender11.ViewportResolution.Y;
                        var offsetX = MyRenderProxy.BillboardsViewProjectionRead[i].Viewport.OffsetX / (float)MyRender11.ViewportResolution.X;
                        var offsetY = (MyRender11.ViewportResolution.Y - MyRenderProxy.BillboardsViewProjectionRead[i].Viewport.OffsetY - MyRenderProxy.BillboardsViewProjectionRead[i].Viewport.Height)
                                      / (float)MyRender11.ViewportResolution.Y;

                        var viewportTransformation = new Matrix(
                            scaleX, 0, 0, 0,
                            0, scaleY, 0, 0,
                            0, 0, 1, 0,
                            offsetX, offsetY, 0, 1
                            );

                        worldToClip = MyRenderProxy.BillboardsViewProjectionRead[message.CustomViewProjection].ViewAtZero * MyRenderProxy.BillboardsViewProjectionRead[message.CustomViewProjection].Projection * viewportTransformation;
                    }

                    var clipPosition = Vector3D.Transform(position, ref worldToClip);
                    clipPosition.X = clipPosition.X * 0.5f + 0.5f;
                    clipPosition.Y = clipPosition.Y * -0.5f + 0.5f;

                    var borderDepth = MyRender11.UseComplementaryDepthBuffer ? 0.0f : 1.0f;
                    borderDepth = message.ClipDistance.HasValue ? Vector3.Transform(new Vector3(0, 0, -message.ClipDistance.Value), MyRender11.Environment.Matrices.Projection).Z : borderDepth;

                    bool drawCondition =
                        MyRender11.UseComplementaryDepthBuffer
                                ? clipPosition.Z > borderDepth && clipPosition.Z < 1
                                : clipPosition.Z < borderDepth && clipPosition.Z > 0;

                    if (drawCondition)
                    {
                        MySpritesRenderer.DrawText(new Vector2((float)clipPosition.X, (float)clipPosition.Y) * MyRender11.ViewportResolution,
                                                   new StringBuilder(message.Text), message.Color, message.Scale, message.Align);
                    }

                    break;
                }

                case MyRenderMessageEnum.DebugDrawModel:
                {
                    MyRenderMessageDebugDrawModel message = (MyRenderMessageDebugDrawModel)debugDrawMessage;


                    break;
                }

                case MyRenderMessageEnum.DebugDrawPlane:
                {
                    MyRenderMessageDebugDrawPlane message = (MyRenderMessageDebugDrawPlane)debugDrawMessage;


                    break;
                }

                case MyRenderMessageEnum.DebugWaitForPresent:
                {
                    MyRenderMessageDebugWaitForPresent rMessage = (MyRenderMessageDebugWaitForPresent)debugDrawMessage;
                    MyRenderProxy.RenderThread.DebugAddWaitingForPresent(rMessage.WaitHandle);
                    break;
                }

                case MyRenderMessageEnum.DebugClearPersistentMessages:
                {
                    MyRenderMessageDebugClearPersistentMessages rMessage = (MyRenderMessageDebugClearPersistentMessages)debugDrawMessage;
                    clearPersistent = true;
                    break;
                }

                default:
                {
                    break;
                }
                }
            }

            linesBatch.Commit();
            noDepthLinesBatch.Commit();
            lines2D.Commit();

            foreach (var message in m_persistentDebugMessagesTemp)
            {
                if (clearPersistent && m_currentPersistentDebugMessages.Remove(message))
                {
                    continue;
                }

                m_debugDrawMessages.Enqueue(message);
                m_currentPersistentDebugMessages.Add(message);
            }
        }
Пример #17
0
        internal static void DrawSceneDebug()
        {
            //ImmediateContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
            //ImmediateContext.Rasterizer.SetViewport(0, 0, m_settings.BackBufferWidth, m_settings.BackBufferHeight);
            //ImmediateContext.OutputMerger.ResetTargets();
            //ShaderResourceView[] shaderViews = m_gbuffer.ShaderViews;
            //ImmediateContext.OutputMerger.SetTargets(Backbuffer.RenderTarget);
            //ImmediateContext.PixelShader.SetConstantBuffer(0, m_frameCB.Buffer);
            //ImmediateContext.PixelShader.SetConstantBuffer(2, m_shadowsCB.Buffer);
            //ImmediateContext.PixelShader.SetShaderResources(0, shaderViews);

            //if (Settings.ShowGbufferDepth)
            //{
            //    ImmediateContext.PixelShader.Set(m_debugGbufferDepth.GetShader());
            //    DrawFullscreen();
            //}
            //else if (Settings.ShowGbufferAlbedo)
            //{
            //    ImmediateContext.PixelShader.Set(m_debugGbufferAlbedo.GetShader());
            //    DrawFullscreen();
            //}
            //else if (Settings.ShowGbufferNormals)
            //{
            //    ImmediateContext.PixelShader.Set(m_debugGbufferNormals.GetShader());
            //    DrawFullscreen();
            //}
            //else if (Settings.ShowCascadesRange)
            //{
            //    ImmediateContext.PixelShader.Set(m_debugContainingCascade.GetShader());
            //    DrawFullscreen();
            //}
            //if (Settings.ShowCascadesDepth)
            //{
            //    /*
            //    SetupSpritePipeline();
            //    ImmediateContext.PixelShader.Set(m_debugCascadeDepth.GetShader());
            //    ImmediateContext.PixelShader.SetConstantBuffer(3, m_debugCB.Buffer);
            //    ImmediateContext.PixelShader.SetShaderResource(7, m_cascadesTexture.ShaderView);

            //    const int horizontalCutoff = (MyRenderConstants.CASCADES_NUM + 1) / 2;
            //    var size = Math.Min(ViewportResolution.X / horizontalCutoff, ViewportResolution.Y / 2) - 3;

            //    for (int i = 0; i < MyRenderConstants.CASCADES_NUM; i++)
            //    {
            //        var stream = MapCB(m_debugCB);
            //        stream.Write(i);
            //        UnmapCB(m_debugCB);

            //        var gridX = i % horizontalCutoff;
            //        var gridY = i / horizontalCutoff;

            //        Vector2 csScale;
            //        Vector2 csOffset;
            //        CalculateSpriteClipspace(new RectangleF(new Vector2I(gridX * size + gridX, gridY * size + gridY), new Vector2I(size, size)), ViewportResolution, out csOffset, out csScale);

            //        DrawSprite(null, csOffset, csScale, Vector2.Zero, Vector2.One);
            //    }
            //     * */
            //}
            if (false)
            {
                /*
                 * var linesBatch = CreateLinesBatch();
                 *
                 * int objectsNum = MyRenderObjectPool.Size();
                 * for (int i = 0; i < objectsNum; i++)
                 * {
                 *  var bb = MyRenderObjectPool.m_cullinfos[i].worldAABB;
                 *
                 *  var v0 = bb.Center - bb.HalfExtents;
                 *  var v1 = v0 + new Vector3(bb.HalfExtents.X *2, 0, 0);
                 *  var v2 = v0 + new Vector3(bb.HalfExtents.X * 2, bb.HalfExtents.Y * 2, 0);
                 *  var v3 = v0 + new Vector3(0, bb.HalfExtents.Y * 2, 0);
                 *
                 *  var v4 = v0 + new Vector3(0, 0, bb.HalfExtents.Z * 2);
                 *  var v5 = v4 + new Vector3(bb.HalfExtents.X * 2, 0, 0);
                 *  var v6 = v4 + new Vector3(bb.HalfExtents.X * 2, bb.HalfExtents.Y * 2, 0);
                 *  var v7 = v4 + new Vector3(0, bb.HalfExtents.Y * 2, 0);
                 *
                 *  var color = new Byte4(255, 255, 255, 0);
                 *
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v0, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v1, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v1, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v2, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v2, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v3, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v0, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v3, color));
                 *
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v4, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v5, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v5, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v6, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v6, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v7, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v4, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v7, color));
                 *
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v0, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v4, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v1, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v5, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v2, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v6, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v3, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v7, color));
                 * }
                 *
                 * linesBatch.Commit();
                 * */
                /*
                 * var linesBatch = CreateLinesBatch();
                 *
                 * int objectsNum = MyRenderObjectPool.Size();
                 * for (int i = 0; i < objectsNum; i++)
                 * {
                 *  var bb = MyRenderObjectPool.m_cullinfos[i].worldAABB;
                 *
                 *  var v0 = bb.Center - bb.HalfExtents;
                 *  var v1 = v0 + new Vector3(bb.HalfExtents.X *2, 0, 0);
                 *  var v2 = v0 + new Vector3(bb.HalfExtents.X * 2, bb.HalfExtents.Y * 2, 0);
                 *  var v3 = v0 + new Vector3(0, bb.HalfExtents.Y * 2, 0);
                 *
                 *  var v4 = v0 + new Vector3(0, 0, bb.HalfExtents.Z * 2);
                 *  var v5 = v4 + new Vector3(bb.HalfExtents.X * 2, 0, 0);
                 *  var v6 = v4 + new Vector3(bb.HalfExtents.X * 2, bb.HalfExtents.Y * 2, 0);
                 *  var v7 = v4 + new Vector3(0, bb.HalfExtents.Y * 2, 0);
                 *
                 *  var color = new Byte4(255, 255, 255, 0);
                 *
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v0, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v1, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v1, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v2, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v2, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v3, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v0, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v3, color));
                 *
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v4, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v5, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v5, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v6, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v6, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v7, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v4, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v7, color));
                 *
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v0, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v4, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v1, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v5, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v2, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v6, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v3, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v7, color));
                 * }
                 *
                 * linesBatch.Commit();
                 * */
                /*
                 * var linesBatch = CreateLinesBatch();
                 *
                 * int objectsNum = MyRenderObjectPool.Size();
                 * for (int i = 0; i < objectsNum; i++)
                 * {
                 *  var bb = MyRenderObjectPool.m_cullinfos[i].worldAABB;
                 *
                 *  var v0 = bb.Center - bb.HalfExtents;
                 *  var v1 = v0 + new Vector3(bb.HalfExtents.X *2, 0, 0);
                 *  var v2 = v0 + new Vector3(bb.HalfExtents.X * 2, bb.HalfExtents.Y * 2, 0);
                 *  var v3 = v0 + new Vector3(0, bb.HalfExtents.Y * 2, 0);
                 *
                 *  var v4 = v0 + new Vector3(0, 0, bb.HalfExtents.Z * 2);
                 *  var v5 = v4 + new Vector3(bb.HalfExtents.X * 2, 0, 0);
                 *  var v6 = v4 + new Vector3(bb.HalfExtents.X * 2, bb.HalfExtents.Y * 2, 0);
                 *  var v7 = v4 + new Vector3(0, bb.HalfExtents.Y * 2, 0);
                 *
                 *  var color = new Byte4(255, 255, 255, 0);
                 *
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v0, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v1, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v1, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v2, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v2, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v3, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v0, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v3, color));
                 *
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v4, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v5, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v5, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v6, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v6, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v7, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v4, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v7, color));
                 *
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v0, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v4, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v1, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v5, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v2, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v6, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v3, color));
                 *  linesBatch.Add(new MyVertexFormatPositionColor(v7, color));
                 * }
                 *
                 * linesBatch.Commit();
                 * */
            }

            //if(true)
            //{
            //    /*
            //    var linesBatch = MyRender.CreateLinesBatch();

            //    var list = new List<MySpatialObject>();
            //    var bsphere = new BoundingSphere(Vector3.Zero, 25.0f);
            //    MySpatialManager.Tree.OverlapAllBoundingSphere<MySpatialObject>(ref bsphere, list);
            //    var inIDs = new Dictionary<uint, object>();
            //    foreach(var item in list)
            //    {
            //        inIDs[item.ID] = null;
            //    }

            //    foreach (var item in MySpatialManager.AllValues())
            //    {
            //        var bb = item.m_aabb;

            //        var v0 = bb.Center - bb.HalfExtents;
            //        var v1 = v0 + new Vector3(bb.HalfExtents.X * 2, 0, 0);
            //        var v2 = v0 + new Vector3(bb.HalfExtents.X * 2, bb.HalfExtents.Y * 2, 0);
            //        var v3 = v0 + new Vector3(0, bb.HalfExtents.Y * 2, 0);

            //        var v4 = v0 + new Vector3(0, 0, bb.HalfExtents.Z * 2);
            //        var v5 = v4 + new Vector3(bb.HalfExtents.X * 2, 0, 0);
            //        var v6 = v4 + new Vector3(bb.HalfExtents.X * 2, bb.HalfExtents.Y * 2, 0);
            //        var v7 = v4 + new Vector3(0, bb.HalfExtents.Y * 2, 0);

            //        var color = new Byte4(255, 0, 0, 0);
            //        if (inIDs.ContainsKey(item.ID))
            //        {
            //            color = new Byte4(0, 255, 0, 0);
            //        }

            //        linesBatch.Add(new MyVertexFormatPositionColor(v0, color));
            //        linesBatch.Add(new MyVertexFormatPositionColor(v1, color));
            //        linesBatch.Add(new MyVertexFormatPositionColor(v1, color));
            //        linesBatch.Add(new MyVertexFormatPositionColor(v2, color));
            //        linesBatch.Add(new MyVertexFormatPositionColor(v2, color));
            //        linesBatch.Add(new MyVertexFormatPositionColor(v3, color));
            //        linesBatch.Add(new MyVertexFormatPositionColor(v0, color));
            //        linesBatch.Add(new MyVertexFormatPositionColor(v3, color));

            //        linesBatch.Add(new MyVertexFormatPositionColor(v4, color));
            //        linesBatch.Add(new MyVertexFormatPositionColor(v5, color));
            //        linesBatch.Add(new MyVertexFormatPositionColor(v5, color));
            //        linesBatch.Add(new MyVertexFormatPositionColor(v6, color));
            //        linesBatch.Add(new MyVertexFormatPositionColor(v6, color));
            //        linesBatch.Add(new MyVertexFormatPositionColor(v7, color));
            //        linesBatch.Add(new MyVertexFormatPositionColor(v4, color));
            //        linesBatch.Add(new MyVertexFormatPositionColor(v7, color));

            //        linesBatch.Add(new MyVertexFormatPositionColor(v0, color));
            //        linesBatch.Add(new MyVertexFormatPositionColor(v4, color));
            //        linesBatch.Add(new MyVertexFormatPositionColor(v1, color));
            //        linesBatch.Add(new MyVertexFormatPositionColor(v5, color));
            //        linesBatch.Add(new MyVertexFormatPositionColor(v2, color));
            //        linesBatch.Add(new MyVertexFormatPositionColor(v6, color));
            //        linesBatch.Add(new MyVertexFormatPositionColor(v3, color));
            //        linesBatch.Add(new MyVertexFormatPositionColor(v7, color));
            //    }

            //    linesBatch.Commit();
            //     * */
            //}

            // draw culling structure
            if (false)
            {
                var linesBatch = MyLinesRenderer.CreateLinesBatch();

                List <MyRenderObjectProxy> list = new List <MyRenderObjectProxy>();

                foreach (var obj in MySceneObject.Collection)
                {
                    linesBatch.AddBoundingBox(obj.AABB, Color.AntiqueWhite);
                }



                linesBatch.Commit();
            }

            if (false)
            {
                var linesBatch = MyLinesRenderer.CreateLinesBatch();

                var worldToClip = m_viewMatrix * m_projectionMatrix;

                var displayString = new StringBuilder();

                var screenPositions = new List <Vector2>(10000);
                var display         = new List <bool>(10000);
                foreach (var obj in MySceneObject.Collection)
                {
                    var position     = obj.m_spatial.m_worldMatrix.Translation;
                    var clipPosition = Vector3.Transform(position, ref worldToClip);
                    clipPosition.X = clipPosition.X * 0.5f + 0.5f;
                    clipPosition.Y = clipPosition.Y * -0.5f + 0.5f;
                    screenPositions.Add(new Vector2(clipPosition.X, clipPosition.Y) * ViewportResolution);
                    display.Add(clipPosition.Z > 0 && clipPosition.Z < 1);
                }

                int i = 0;
                foreach (var obj in MySceneObject.Collection)
                {
                    if (display[i])
                    {
                        //displayString.AppendFormat("ID: {0}, proxy ID: {1}", obj.ID, obj.m_spatial.proxyID);

                        var v  = obj.m_spatial.m_aabb.Center;
                        var vv = obj.m_spatial.m_aabb.HalfExtents;

                        //var vv = obj.m_spatial.m_localAabb.HasValue ? obj.m_spatial.m_localAabb.Value.Center : Vector3.Zero;
                        displayString.AppendFormat("<{0}, {1}, {2}> <{3}, {4}, {5}>", v.X, v.Y, v.Z, vv.X, vv.Y, vv.Z);
                        if (obj.m_spatial.m_localAabb.HasValue)
                        {
                            v  = obj.m_spatial.m_localAabb.Value.Center;
                            vv = obj.m_spatial.m_localAabb.Value.HalfExtents;
                            displayString.AppendFormat("local: <{0}, {1}, {2}> <{3}, {4}, {5}>", v.X, v.Y, v.Z, vv.X, vv.Y, vv.Z);
                        }

                        //if (v.X != 0 && v.Y != 0 && v.Z != 0)
                        {
                            if (obj.m_spatial.m_parent != null)
                            {
                                MySpritesRenderer.DrawText(screenPositions[i], displayString, Color.DarkCyan, 0.5f);
                            }
                            else
                            {
                                MySpritesRenderer.DrawText(screenPositions[i] + new Vector2(0, -25.0f), displayString, Color.LightSkyBlue, 1);
                            }
                        }
                    }

                    if (obj.m_spatial.m_parent != null)
                    {
                        linesBatch.Add(new MyVertexFormatPositionColor(obj.m_spatial.m_parent.m_worldMatrix.Translation, new Byte4(0, 0, 128, 25)));
                        linesBatch.Add(new MyVertexFormatPositionColor(obj.m_spatial.m_worldMatrix.Translation, new Byte4(0, 0, 128, 25)));
                    }

                    displayString.Clear();

                    i++;
                }

                linesBatch.Commit();
            }

            //UpdateDepthBias();

            //ImmediateContext.ClearState();
        }
Пример #18
0
        internal static void Draw(bool draw = true)
        {
            //if (false) Debug.Assert(MyClipmap.LodLevel.DrewLastFrame);
            //MyClipmap.LodLevel.DrewLastFrame = false;

            try
            {
                MyGpuProfiler.IC_BeginBlock("Draw");
                GetRenderProfiler().StartProfilingBlock("ProcessMessages");
                MyGpuProfiler.IC_BeginBlock("ProcessMessageQueue");
                TransferLocalMessages();
                ProcessMessageQueue();
                MyGpuProfiler.IC_EndBlock();
                GetRenderProfiler().EndProfilingBlock();

                if (draw)
                {
                    //MyLog.Default.WriteLine("Draw");
                    //MyOpenVR.ReadPoses();
                    MyRender11.ClearBackbuffer(MyRender11.Environment.BackgroundColor);
                    MyImmediateRC.RC.Clear();

                    GetRenderProfiler().StartProfilingBlock("ProcessDrawQueue");
                    ProcessDrawQueue();
                    GetRenderProfiler().EndProfilingBlock();

                    /*GetRenderProfiler().StartProfilingBlock("ProcessDebugMessages");
                     * ProcessDebugMessages();
                     * GetRenderProfiler().EndProfilingBlock();*/

                    GetRenderProfiler().StartProfilingBlock("MySpritesRenderer.Draw");
                    MyGpuProfiler.IC_BeginBlock("SpriteRenderer");
                    //MyCommon.UpdateFrameConstants();
                    MySpritesRenderer.Draw(MyRender11.Backbuffer.m_RTV, new MyViewport(MyRender11.ViewportResolution.X, MyRender11.ViewportResolution.Y));
                    MyGpuProfiler.IC_EndBlock();

                    GetRenderProfiler().EndProfilingBlock();

                    MyTextures.Load();

                    if (m_texturesToRender.Count > 0)
                    {
                        VRage.Render11.PostprocessStage.MySaveExportedTextures.RenderColoredTextures(m_texturesToRender);
                    }
                }

                MyLinesRenderer.Clear();
                MySpritesRenderer.Clear();

                m_drawQueue.Clear();
                MyGpuProfiler.IC_EndBlock();
            }
            catch (SharpDXException e)
            {
                MyRender11.Log.IncreaseIndent();
                MyRender11.Log.WriteLine(" " + e);
                if (e.Descriptor == SharpDX.DXGI.ResultCode.DeviceRemoved)
                {
                    MyRender11.Log.WriteLine("Reason: " + Device.DeviceRemovedReason);
                }
                MyRender11.Log.DecreaseIndent();

                throw;
            }
        }
        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
            }
        }
Пример #20
0
        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;

                MyFileTextureManager texManager = MyManagers.FileTextures;
                MySpritesRenderer.AddSingleSprite(texManager.GetTexture(sprite.Texture, MyFileTextureEnum.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 = MyManagers.FileTextures.GetTexture(sprite.Texture, MyFileTextureEnum.GUI, true);

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

                Vector2 sizeInPixels       = tex.Size;
                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);

                MyFileTextureManager texManager = MyManagers.FileTextures;
                MySpritesRenderer.AddSingleSprite(texManager.GetTexture(sprite.Texture, MyFileTextureEnum.GUI, waitTillLoaded: sprite.WaitTillLoaded), sprite.Color, origin, rightVector, null, rect);

                break;
            }


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

                MyFileTextureManager texManager = MyManagers.FileTextures;
                var tex         = texManager.GetTexture(sprite.Texture, MyFileTextureEnum.GUI, true);
                var textureSize = tex.Size;

                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(texManager.GetTexture(sprite.Texture, MyFileTextureEnum.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;
            }

            default:
                throw new Exception();
            }
        }
Пример #21
0
        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;
            }
            }
        }
Пример #22
0
        internal static void Draw(bool draw = true)
        {
            try
            {
                GetRenderProfiler().StartProfilingBlock("ProcessMessages");
                ProcessMessageQueue();
                GetRenderProfiler().EndProfilingBlock();


                GetRenderProfiler().StartProfilingBlock("RebuildShaders");

                //

                //MyShaderCache.CompilePending();
                //MyShaderFactory.RunCompilation();

                GetRenderProfiler().EndProfilingBlock();

                if (draw)
                {
                    MyImmediateRC.RC.Clear();
                    GetRenderProfiler().StartProfilingBlock("ProcessDrawQueue");
                    ProcessDrawQueue();
                    GetRenderProfiler().EndProfilingBlock();

                    GetRenderProfiler().StartProfilingBlock("ProcessDebugMessages");
                    ProcessDebugMessages();
                    GetRenderProfiler().EndProfilingBlock();

                    GetRenderProfiler().StartProfilingBlock("MySpritesRenderer.Draw");
                    MyCommon.UpdateFrameConstants();
                    MySpritesRenderer.Draw(MyRender11.Backbuffer.m_RTV, new MyViewport(MyRender11.ViewportResolution.X, MyRender11.ViewportResolution.Y));
                    GetRenderProfiler().EndProfilingBlock();

                    MyTextures.Load();
                }

                if (m_profilingStarted)
                {
                    MyGpuProfiler.IC_BeginBlock("Waiting for present");
                }

                MyLinesRenderer.Clear();
                MySpritesRenderer.Clear();

                m_drawQueue.Clear();
                m_debugDrawMessages.Clear();
            }
            catch (SharpDXException e)
            {
                MyRender11.Log.IncreaseIndent();
                MyRender11.Log.WriteLine(" " + e);
                if (e.Descriptor == SharpDX.DXGI.ResultCode.DeviceRemoved)
                {
                    MyRender11.Log.WriteLine("Reason: " + Device.DeviceRemovedReason);
                }
                MyRender11.Log.DecreaseIndent();

                throw e;
            }
        }
        static void ProcessDebugMessages()
        {
            var linesBatch        = MyLinesRenderer.CreateBatch();
            var noDepthLinesBatch = MyLinesRenderer.CreateBatch();

            noDepthLinesBatch.IgnoreDepth = true;
            var lines2D = MyLinesRenderer.CreateBatch();

            lines2D.IgnoreDepth = true;


            while (m_debugDrawMessages.Count > 0)
            {
                IMyRenderMessage debugDrawMessage = m_debugDrawMessages.Dequeue();

                MyRenderMessageEnum messageType = debugDrawMessage.MessageType;

                switch (messageType)
                {
                case MyRenderMessageEnum.DebugDrawLine3D:
                {
                    MyRenderMessageDebugDrawLine3D message = (MyRenderMessageDebugDrawLine3D)debugDrawMessage;

                    if (message.DepthRead)
                    {
                        linesBatch.Add(message.PointFrom, message.PointTo, message.ColorFrom, message.ColorTo);
                    }
                    else
                    {
                        noDepthLinesBatch.Add(message.PointFrom, message.PointTo, message.ColorFrom, message.ColorTo);
                    }

                    break;
                }

                case MyRenderMessageEnum.DebugDrawLine2D:
                {
                    MyRenderMessageDebugDrawLine2D message = (MyRenderMessageDebugDrawLine2D)debugDrawMessage;

                    var matrix = message.Projection ?? Matrix.CreateOrthographicOffCenter(0, MyRender11.ViewportResolution.X, MyRender11.ViewportResolution.Y, 0, 0, -1);

                    if (!lines2D.CustomViewProjection.HasValue || (lines2D.CustomViewProjection.HasValue && lines2D.CustomViewProjection.Value != matrix))
                    {
                        lines2D.Commit();
                        lines2D                      = MyLinesRenderer.CreateBatch();
                        lines2D.IgnoreDepth          = true;
                        lines2D.CustomViewProjection = matrix;
                    }

                    var p0 = new Vector3(message.PointFrom.X, message.PointFrom.Y, 0);
                    var p1 = new Vector3(message.PointTo.X, message.PointTo.Y, 0);
                    lines2D.Add(p0, p1, message.ColorFrom, message.ColorTo);

                    break;
                }

                case MyRenderMessageEnum.DebugDrawPoint:
                {
                    MyRenderMessageDebugDrawPoint message = (MyRenderMessageDebugDrawPoint)debugDrawMessage;

                    var batch = message.DepthRead ? linesBatch : noDepthLinesBatch;

                    var scale = 0.125f;

                    var borderDepth = MyRender11.UseComplementaryDepthBuffer ? 0.0f : 1.0f;
                    borderDepth = message.ClipDistance.HasValue ? Vector3.Transform(new Vector3(0, 0, -message.ClipDistance.Value), MyEnvironment.Projection).Z : borderDepth;

                    var clipPosition = Vector3.Transform((Vector3)message.Position, ref MyEnvironment.ViewProjection);
                    clipPosition.X = clipPosition.X * 0.5f + 0.5f;
                    clipPosition.Y = clipPosition.Y * -0.5f + 0.5f;

                    //Debug.Assert(MyRender11.UseComplementaryDepthBuffer);

                    bool drawCondition =
                        MyRender11.UseComplementaryDepthBuffer
                                ? clipPosition.Z > borderDepth && clipPosition.Z < 1
                                : clipPosition.Z < borderDepth && clipPosition.Z > 0;

                    if (drawCondition)
                    {
                        batch.Add(message.Position + Vector3.UnitX * scale, message.Position - Vector3.UnitX * scale, message.Color);
                        batch.Add(message.Position + Vector3.UnitY * scale, message.Position - Vector3.UnitY * scale, message.Color);
                        batch.Add(message.Position + Vector3.UnitZ * scale, message.Position - Vector3.UnitZ * scale, message.Color);
                    }

                    break;
                }

                case MyRenderMessageEnum.DebugDrawSphere:
                {
                    MyRenderMessageDebugDrawSphere message = (MyRenderMessageDebugDrawSphere)debugDrawMessage;

                    var borderDepth = MyRender11.UseComplementaryDepthBuffer ? 0.0f : 1.0f;
                    borderDepth = message.ClipDistance.HasValue ? Vector3.Transform(new Vector3(0, 0, -message.ClipDistance.Value), MyEnvironment.Projection).Z : borderDepth;

                    var clipPosition = Vector3.Transform((Vector3)message.Position, ref MyEnvironment.ViewProjection);
                    clipPosition.X = clipPosition.X * 0.5f + 0.5f;
                    clipPosition.Y = clipPosition.Y * -0.5f + 0.5f;

                    bool drawCondition =
                        MyRender11.UseComplementaryDepthBuffer
                                ? clipPosition.Z > borderDepth && clipPosition.Z < 1
                                : clipPosition.Z < borderDepth && clipPosition.Z > 0;

                    if (drawCondition)
                    {
                        var batch = message.DepthRead ? linesBatch : noDepthLinesBatch;

                        batch.AddSphereRing(new BoundingSphere(message.Position, message.Radius), message.Color, Matrix.Identity);
                        batch.AddSphereRing(new BoundingSphere(message.Position, message.Radius), message.Color, Matrix.CreateRotationX(MathHelper.PiOver2));
                        batch.AddSphereRing(new BoundingSphere(message.Position, message.Radius), message.Color, Matrix.CreateRotationZ(MathHelper.PiOver2));
                    }

                    break;
                }

                case MyRenderMessageEnum.DebugDrawAABB:
                {
                    MyRenderMessageDebugDrawAABB message = (MyRenderMessageDebugDrawAABB)debugDrawMessage;

                    if (message.DepthRead)
                    {
                        linesBatch.AddBoundingBox((BoundingBox)message.AABB, message.Color);
                    }
                    else
                    {
                        noDepthLinesBatch.AddBoundingBox((BoundingBox)message.AABB, message.Color);
                    }

                    break;
                }

                case MyRenderMessageEnum.DebugDrawCone:
                {
                    MyRenderMessageDebugDrawCone message = (MyRenderMessageDebugDrawCone)debugDrawMessage;

                    var batch = message.DepthRead ? linesBatch : noDepthLinesBatch;

                    var axis = message.DirectionVector;
                    axis.Normalize();

                    var apex = message.Translation + message.DirectionVector;

                    var steps    = 32;
                    var stepsRcp = (float)(Math.PI * 2 / steps);
                    for (int i = 0; i < 32; i++)
                    {
                        float a0 = i * stepsRcp;
                        float a1 = (i + 1) * stepsRcp;

                        var A = message.Translation + Vector3.Transform(message.BaseVector, Matrix.CreateFromAxisAngle(axis, a0));
                        var B = message.Translation + Vector3.Transform(message.BaseVector, Matrix.CreateFromAxisAngle(axis, a1));

                        batch.Add(A, B, message.Color);
                        batch.Add(A, apex, message.Color);
                    }

                    break;
                }

                case MyRenderMessageEnum.DebugDrawAxis:
                {
                    MyRenderMessageDebugDrawAxis message = (MyRenderMessageDebugDrawAxis)debugDrawMessage;

                    var batch = message.DepthRead ? linesBatch : noDepthLinesBatch;

                    batch.Add(message.Matrix.Translation, message.Matrix.Translation + message.Matrix.Right * message.AxisLength, Color.Red);
                    batch.Add(message.Matrix.Translation, message.Matrix.Translation + message.Matrix.Up * message.AxisLength, Color.Green);
                    batch.Add(message.Matrix.Translation, message.Matrix.Translation + message.Matrix.Forward * message.AxisLength, Color.Blue);

                    break;
                }

                case MyRenderMessageEnum.DebugDrawOBB:
                {
                    MyRenderMessageDebugDrawOBB message = (MyRenderMessageDebugDrawOBB)debugDrawMessage;

                    Vector3 [] corners = new Vector3[8];
                    Matrix     matrix  = (Matrix)message.Matrix;
                    new MyOrientedBoundingBox(ref matrix).GetCorners(corners, 0);

                    if (message.DepthRead)
                    {
                        linesBatch.Add6FacedConvex(corners, message.Color);
                    }
                    else
                    {
                        noDepthLinesBatch.Add6FacedConvex(corners, message.Color);
                    }

                    MyPrimitivesRenderer.Draw6FacedConvex(corners, message.Color, message.Alpha);

                    break;
                }

                case MyRenderMessageEnum.DebugDrawCylinder:
                {
                    MyRenderMessageDebugDrawCylinder message = (MyRenderMessageDebugDrawCylinder)debugDrawMessage;

                    var steps    = 32;
                    var stepsRcp = (float)(Math.PI * 2 / steps);
                    for (int i = 0; i < 32; i++)
                    {
                        float a0 = i * stepsRcp;
                        float a1 = (i + 1) * stepsRcp;

                        Vector3 A = new Vector3(Math.Cos(a0), 1.0f, Math.Sin(a0)) * 0.5f;
                        Vector3 B = new Vector3(Math.Cos(a1), 1.0f, Math.Sin(a1)) * 0.5f;
                        Vector3 C = A - Vector3.UnitY;
                        Vector3 D = B - Vector3.UnitY;

                        A = Vector3.Transform(A, message.Matrix);
                        B = Vector3.Transform(B, message.Matrix);
                        C = Vector3.Transform(C, message.Matrix);
                        D = Vector3.Transform(D, message.Matrix);

                        linesBatch.Add(A, B, message.Color);
                        linesBatch.Add(A, C, message.Color);
                        linesBatch.Add(C, D, message.Color);
                    }

                    break;
                }

                case MyRenderMessageEnum.DebugDrawTriangle:
                {
                    MyRenderMessageDebugDrawTriangle message = (MyRenderMessageDebugDrawTriangle)debugDrawMessage;

                    MyPrimitivesRenderer.DrawTriangle(message.Vertex0, message.Vertex1, message.Vertex2, message.Color);

                    break;
                }

                case MyRenderMessageEnum.DebugDrawTriangles:
                {
                    MyRenderMessageDebugDrawTriangles message = (MyRenderMessageDebugDrawTriangles)debugDrawMessage;

                    for (int i = 0; i < message.Indices.Count; i += 3)
                    {
                        var v0 = Vector3.Transform(message.Vertices[message.Indices[i + 0]], message.WorldMatrix);
                        var v1 = Vector3.Transform(message.Vertices[message.Indices[i + 1]], message.WorldMatrix);
                        var v2 = Vector3.Transform(message.Vertices[message.Indices[i + 2]], message.WorldMatrix);

                        MyPrimitivesRenderer.DrawTriangle(v0, v1, v2, message.Color);
                    }

                    break;
                }

                case MyRenderMessageEnum.DebugDrawCapsule:
                {
                    MyRenderMessageDebugDrawCapsule message = (MyRenderMessageDebugDrawCapsule)debugDrawMessage;

                    var batch = message.DepthRead ? linesBatch : noDepthLinesBatch;

                    batch.AddSphereRing(new BoundingSphere(message.P0, message.Radius), message.Color, Matrix.Identity);
                    batch.AddSphereRing(new BoundingSphere(message.P0, message.Radius), message.Color, Matrix.CreateRotationX(MathHelper.PiOver2));
                    batch.AddSphereRing(new BoundingSphere(message.P1, message.Radius), message.Color, Matrix.Identity);
                    batch.AddSphereRing(new BoundingSphere(message.P1, message.Radius), message.Color, Matrix.CreateRotationX(MathHelper.PiOver2));

                    batch.Add(message.P0, message.P1, message.Color);


                    break;
                }

                case MyRenderMessageEnum.DebugDrawText2D:
                {
                    MyRenderMessageDebugDrawText2D message = (MyRenderMessageDebugDrawText2D)debugDrawMessage;

                    var text = new StringBuilder(message.Text);

                    MySpritesRenderer.DrawText(message.Coord, text, message.Color, message.Scale, message.Align);

                    break;
                }

                case MyRenderMessageEnum.DebugDrawText3D:
                {
                    MyRenderMessageDebugDrawText3D message = (MyRenderMessageDebugDrawText3D)debugDrawMessage;

                    Vector3 position = (Vector3)message.Coord;

                    var worldToClip = MyEnvironment.ViewProjection;
                    if (message.CustomViewProjection != -1)
                    {
                        if (!MyRenderProxy.BillboardsViewProjectionRead.ContainsKey(message.CustomViewProjection))
                        {
                            break;
                        }

                        var i = message.CustomViewProjection;

                        var scaleX  = MyRenderProxy.BillboardsViewProjectionRead[i].Viewport.Width / (float)MyRender11.ViewportResolution.X;
                        var scaleY  = MyRenderProxy.BillboardsViewProjectionRead[i].Viewport.Height / (float)MyRender11.ViewportResolution.Y;
                        var offsetX = MyRenderProxy.BillboardsViewProjectionRead[i].Viewport.OffsetX / (float)MyRender11.ViewportResolution.X;
                        var offsetY = (MyRender11.ViewportResolution.Y - MyRenderProxy.BillboardsViewProjectionRead[i].Viewport.OffsetY - MyRenderProxy.BillboardsViewProjectionRead[i].Viewport.Height)
                                      / (float)MyRender11.ViewportResolution.Y;

                        var viewportTransformation = new Matrix(
                            scaleX, 0, 0, 0,
                            0, scaleY, 0, 0,
                            0, 0, 1, 0,
                            offsetX, offsetY, 0, 1
                            );

                        worldToClip = MyRenderProxy.BillboardsViewProjectionRead[message.CustomViewProjection].View * MyRenderProxy.BillboardsViewProjectionRead[message.CustomViewProjection].Projection * viewportTransformation;
                    }

                    var clipPosition = Vector3.Transform(position, ref worldToClip);
                    clipPosition.X = clipPosition.X * 0.5f + 0.5f;
                    clipPosition.Y = clipPosition.Y * -0.5f + 0.5f;

                    var borderDepth = MyRender11.UseComplementaryDepthBuffer ? 0.0f : 1.0f;
                    borderDepth = message.ClipDistance.HasValue ? Vector3.Transform(new Vector3(0, 0, -message.ClipDistance.Value), MyEnvironment.Projection).Z : borderDepth;

                    bool drawCondition =
                        MyRender11.UseComplementaryDepthBuffer
                                ? clipPosition.Z > borderDepth && clipPosition.Z < 1
                                : clipPosition.Z < borderDepth && clipPosition.Z > 0;

                    if (drawCondition)
                    {
                        MySpritesRenderer.DrawText(new Vector2(clipPosition.X, clipPosition.Y) * MyRender11.ViewportResolution,
                                                   new StringBuilder(message.Text), message.Color, message.Scale, message.Align);
                    }

                    break;
                }

                case MyRenderMessageEnum.DebugDrawModel:
                {
                    MyRenderMessageDebugDrawModel message = (MyRenderMessageDebugDrawModel)debugDrawMessage;


                    break;
                }

                case MyRenderMessageEnum.DebugDrawPlane:
                {
                    MyRenderMessageDebugDrawPlane message = (MyRenderMessageDebugDrawPlane)debugDrawMessage;


                    break;
                }

                default:
                {
                    break;
                }
                }
            }

            linesBatch.Commit();
            noDepthLinesBatch.Commit();
            lines2D.Commit();
        }