Exemplo n.º 1
0
 public void Draw(Scene scene, Matrix world, Matrix view, Matrix projection, TextureCube reflectionTexture, Vector3 cameraPosition, RenderPass pass)
 {
     foreach (AbstractEntity entity in scene.Entities)
     {
         entity.Draw(world, view, projection, reflectionTexture, cameraPosition, pass);
     }
 }
Exemplo n.º 2
0
 public override void Render(RenderPass pass)
 {
     foreach(Emblem emblem in emblems)
     {
         emblem.Render(pass);
     }
     base.Render (pass);
 }
Exemplo n.º 3
0
        public override void Initialize()
        {
            base.Initialize();

            boundingBoxPass = new RenderPass("BoundingBoxPass").KeepAliveBy(this);
            heatShimmerPass = new RenderPass("HeatShimmerPass").KeepAliveBy(this);
            heatShimmerComposePass = new RenderPass("HeatShimmerComposePass").KeepAliveBy(this);
        }
Exemplo n.º 4
0
        public override void Load()
        {
            base.Load();

            Parameters.AddSources(GBufferPlugin.MainPlugin.ViewParameters);

            Lights = this.EffectSystemOld.BuildEffect("Lights").Using(new LightPlugin()).InstantiatePermutation();

            // TODO: Check if released properly.
            for (int i = 0; i < 2; ++i)
            {
                if (i == 1)
                {
                    if (!Debug)
                        continue;

                    // Add the debug as an overlay on the main pass
                    debugRenderPass = new RenderPass("LightPrePassDebug").KeepAliveBy(ActiveObjects);
                    GBufferPlugin.MainPlugin.RenderPass.AddPass(debugRenderPass);
                }

                var debug = i == 1;
                var renderPass = i == 1 ? debugRenderPass : RenderPass;

                var lightDeferredEffectBuilder = this.EffectSystemOld.BuildEffect("LightPrePass" + (debug ? "Debug" : string.Empty)).KeepAliveBy(ActiveObjects);
                foreach (var effectPlugin in BasePlugins)
                {
                    lightDeferredEffectBuilder.Using(new BasicShaderPlugin(effectPlugin) { Services = Services, RenderPassPlugin = this, RenderPass = renderPass });
                }
                lightDeferredEffectBuilder.Using(new LightingPrepassShaderPlugin("LightPreShaderPass" + (debug ? "Debug" : string.Empty)) { Services = Services, RenderPassPlugin = this, RenderPass = renderPass, Debug = debug });

                lightDeferredEffects[i] = lightDeferredEffectBuilder.InstantiatePermutation().KeepAliveBy(ActiveObjects);
            }

            if (OfflineCompilation)
                return;

            // Create lighting accumulation texture (that LightPlugin will use)
            var mainBackBuffer = graphicsDeviceService.GraphicsDevice.BackBuffer;
            var lightTexture = Texture.New2D(GraphicsDevice, mainBackBuffer.Width, mainBackBuffer.Height, PixelFormat.R16G16B16A16_Float, TextureFlags.ShaderResource | TextureFlags.RenderTarget);
            lightTexture.Name = "LightTexture";
            LightTexture = lightTexture.ToRenderTarget();

            // Set Parameters for this plugin
            Parameters.Set(LightDeferredShadingKeys.LightTexture, lightTexture);

            // Set GBuffer Texture0
            Parameters.Set(GBufferBaseKeys.GBufferTexture, (Texture2D)GBufferPlugin.RenderTarget.Texture);

            // Set parameters for MainPlugin
            GBufferPlugin.MainTargetPlugin.Parameters.Set(LightDeferredShadingKeys.LightTexture, lightTexture);

            CreatePrePassMesh(RenderPass, false);
            if (Debug)
                CreatePrePassMesh(debugRenderPass, true);
        }
Exemplo n.º 5
0
        public SceneNode(int actor_id, String name, RenderPass pass, Matrix? to_world, Matrix? from_world)
        {
            _properties = new SceneNodeProperties();
            _properties.ActorId = actor_id;
            _properties.Name = name;
            _properties.RenderPass = pass;
            _properties.Alphatype = AlphaType.AlphaOpaque;

            SetTransform(to_world, from_world);
            SetRadius(0);
        }
Exemplo n.º 6
0
 public override void Render(RenderPass pass)
 {
     if(pass == RenderPass.Shadow )
     {
         if(CastShadows)
         {
             SetUpShadowCastMaterial();
             Render(SceneManager.ShadowPassShader);
         }
     }
     else if(pass == RenderPass.Render)
     {
         SetUpMaterial();
         Render();
     }
 }
Exemplo n.º 7
0
 public virtual void Draw(Matrix world, Matrix view, Matrix projection, TextureCube reflectionTexture, Vector3 cameraPosition, RenderPass pass)
 {
     if (_visible)
     {
         if (_effect != null)
         {
             if (cameraPosition != null)
             {
                 DrawModelWithEffect(world, view, projection, reflectionTexture, cameraPosition);
             }
         }
         else
         {
             DrawModel(world, view, projection, pass);
         }
     }
 }
Exemplo n.º 8
0
        public override void DrawModel(Matrix world, Matrix view, Matrix projection, RenderPass pass)
        {
            if (_visible)
            {
                if(pass == RenderPass.Opaque) {
                    //Draw all opaque
                    _device.BlendState = BlendState.Opaque;
                    _device.DepthStencilState = DepthStencilState.Default;
                    this.DrawMeshes(_opaqueMeshes, view, projection);
                }
                else {
                    //Draw all translucent
                    _device.BlendState = BlendState.AlphaBlend;
                    _device.DepthStencilState = DepthStencilState.DepthRead;
                    this.DrawMeshes(_translucentMeshes, view, projection);
                }
                //For future object
                _device.BlendState = BlendState.Opaque;
                _device.DepthStencilState = DepthStencilState.Default;
                _device.RasterizerState = RasterizerState.CullNone;

            }
        }
Exemplo n.º 9
0
        public override void Load()
        {
            base.Load();

            if (OfflineCompilation)
                return;

            var renderTargets = new RenderTarget[2];
            DepthStencilBuffer depthStencilBuffer = null;
            Texture2D depthStencilTexture = null;

            Parameters.AddSources(MainPlugin.ViewParameters);

            Parameters.RegisterParameter(EffectPlugin.BlendStateKey);

            var filteredPasses = new FastList<RenderPass>();

            RenderPass.UpdatePasses += updatePassesAction = (RenderPass currentRenderPass, ref FastList<RenderPass> currentPasses) =>
                {
                    var originalPasses = currentPasses;
                    filteredPasses.Clear();
                    currentPasses = filteredPasses;

                    Parameters.Set(PickingFrameIndex, ++currentPickingFrameIndex);
                    Request[] requests;

                    lock (pendingRequests)
                    {
                        // No picking request or no mesh to pick?
                        if (pendingRequests.Count == 0)
                            return;

                        requests = pendingRequests.ToArray();
                        pendingRequests.Clear();
                    }

                    foreach (var request in requests)
                    {
                        requestResults.Add(request);
                    }

                    if (originalPasses == null)
                        return;

                    // Count mesh passes
                    int meshIndex = 0;
                    foreach (var pass in originalPasses)
                    {
                        meshIndex += pass.Passes.Count;
                    }

                    // No mesh to pick?
                    if (meshIndex == 0)
                        return;

                    // Copy mesh passes and assign indices
                    var meshPasses = new EffectMesh[meshIndex];
                    meshIndex = 0;
                    foreach (var pass in RenderPass.Passes)
                    {
                        throw new NotImplementedException();
                        //foreach (var effectMeshPass in pass.Meshes)
                        //{
                        //    meshPasses[meshIndex] = (EffectMesh)effectMeshPass;
                        //    // Prefix increment so that 0 means no rendering.
                        //    effectMeshPass.Parameters.Set(PickingMeshIndex, ++meshIndex);
                        //}
                    }

                    // For now, it generates one rendering per picking.
                    // It would be quite easy to optimize it by make Picking shader works on multiple picking points at a time.
                    foreach (var request in requests)
                    {
                        var pickingRenderPass = new RenderPass("Picking");

                        pickingRenderPass.StartPass.AddFirst = (threadContext) =>
                            {
                                threadContext.GraphicsDevice.Clear(renderTargets[0], Color.Black);
                                threadContext.GraphicsDevice.Clear(renderTargets[1], Color.Black);
                                threadContext.Parameters.Set(PickingScreenPosition, request.Location);
                                threadContext.GraphicsDevice.SetViewport(new Viewport(0, 0, renderTargets[0].Description.Width, renderTargets[0].Description.Height));

                                threadContext.GraphicsDevice.Clear(depthStencilBuffer, DepthStencilClearOptions.DepthBuffer);
                                threadContext.GraphicsDevice.SetRenderTargets(depthStencilBuffer, renderTargets);
                            };
                        pickingRenderPass.EndPass.AddLast = (threadContext) =>
                            {
                                threadContext.Parameters.Reset(PickingScreenPosition);
                                threadContext.GraphicsDevice.Copy(renderTargets[0].Texture, request.ResultTextures[0]);
                                threadContext.GraphicsDevice.Copy(renderTargets[1].Texture, request.ResultTextures[1]);
                            };
                        //pickingRenderPass.PassesInternal = originalPasses;
                        throw new NotImplementedException();

                        request.MeshPasses = meshPasses;

                        currentPasses.Add(pickingRenderPass);

                        request.HasResults = true;

                        // Wait 2 frames before pulling the results.
                        request.FrameCounter = 2;
                    }
                };

            RenderSystem.GlobalPass.EndPass.AddLast = CheckPickingResults;

            var backBuffer = GraphicsDevice.BackBuffer; 

            int pickingArea = 1 + PickingDistance * 2;
            renderTargets[0] = Texture.New2D(GraphicsDevice, pickingArea, pickingArea, PixelFormat.R32_UInt, TextureFlags.ShaderResource | TextureFlags.RenderTarget).ToRenderTarget().KeepAliveBy(ActiveObjects);
            renderTargets[1] = Texture.New2D(GraphicsDevice, pickingArea, pickingArea, PixelFormat.R32G32B32A32_Float, TextureFlags.ShaderResource | TextureFlags.RenderTarget).ToRenderTarget().KeepAliveBy(ActiveObjects);

            depthStencilTexture = Texture.New2D(GraphicsDevice, pickingArea, pickingArea, PixelFormat.D32_Float, TextureFlags.ShaderResource | TextureFlags.DepthStencil).KeepAliveBy(ActiveObjects);
            depthStencilBuffer = depthStencilTexture.ToDepthStencilBuffer(false);

            Parameters.AddDynamic(PickingMatrix, ParameterDynamicValue.New(PickingScreenPosition, (ref Vector2 pickingPosition, ref Matrix picking) =>
                {
                    // Move center to picked position, and zoom (it is supposed to stay per-pixel according to render target size)
                    picking = Matrix.Translation(1.0f - (pickingPosition.X) / backBuffer.Width * 2.0f, -1.0f + (pickingPosition.Y) / backBuffer.Height * 2.0f, 0.0f)
                        * Matrix.Scaling((float)backBuffer.Width / (float)pickingArea, (float)backBuffer.Height / (float)pickingArea, 1.0f);
                }));
        }
Exemplo n.º 10
0
 protected override void OnDraw(ModelEffectInstance modelEffect, RenderPass pass)
 {
     m_model.Draw(modelEffect);
 }
Exemplo n.º 11
0
        public override void Load()
        {
            base.Load();

            RenderPass.AddPass(boundingBoxPass, heatShimmerPass, heatShimmerComposePass);

            // Use MinMax Plugin
            var bbRenderTargetPlugin = new RenderTargetsPlugin("BoundingBoxRenderTargetPlugin")
            {
                EnableSetTargets  = true,
                EnableClearTarget = true,
                RenderTarget      = null,
                RenderPass        = boundingBoxPass,
                Services          = Services
            };

            bbRenderTargetPlugin.Apply();

            Parameters.AddSources(ViewParameters);
            Parameters.SetDefault(RenderTargetKeys.DepthStencilSource);
            Parameters.SetDefault(TexturingKeys.Sampler);
            bbRenderTargetPlugin.Parameters.AddSources(Parameters);

            EffectOld minMaxEffect = this.EffectSystemOld.BuildEffect("MinMax")
                                     .Using(new MinMaxShaderPlugin("MinMaxShaderPlugin")
            {
                RenderPassPlugin = bbRenderTargetPlugin
            })
                                     .Using(new BasicShaderPlugin("TransformationWVP")
            {
                RenderPassPlugin = bbRenderTargetPlugin
            })
                                     .KeepAliveBy(ActiveObjects)
                                     .InstantiatePermutation()
                                     .KeepAliveBy(ActiveObjects);

            heatShimmerPass.Parameters = new ParameterCollection();
            heatShimmerPass.Parameters.AddSources(Parameters);
            heatShimmerPass.Parameters.AddSources(NoisePlugin.Parameters);

            EffectOld heatShimmerEffect = this.EffectSystemOld.BuildEffect("HeatShimmer")
                                          .Using(new PostEffectSeparateShaderPlugin()
            {
                RenderPass = heatShimmerPass
            })
                                          .Using(
                new BasicShaderPlugin(
                    new ShaderMixinSource()
            {
                Mixins = new List <ShaderClassSource>()
                {
                    // TODO add support for IsZReverse
                    //new ShaderClassSource("PostEffectHeatShimmer", Debug ? 1 : 0, effectSystemOld.IsZReverse ? 1 : 0, 3),
                    new ShaderClassSource("PostEffectHeatShimmer", Debug ? 1 : 0, false ? 1 : 0, 3)
                },
                Compositions = new Dictionary <string, ShaderSource>()
                {
                    { "NoiseSource", new ShaderClassSource("SimplexNoise") }
                },
            }
                    )
            {
                RenderPass = heatShimmerPass
            })
                                          .KeepAliveBy(ActiveObjects)
                                          .InstantiatePermutation()
                                          .KeepAliveBy(ActiveObjects);

            EffectOld heatShimmerDisplayEffect = this.EffectSystemOld.BuildEffect("HeatShimmer")
                                                 .Using(new PostEffectSeparateShaderPlugin()
            {
                RenderPass = heatShimmerComposePass
            })
                                                 .Using(new BasicShaderPlugin(new ShaderClassSource("PostEffectHeatShimmerDisplay", Debug ? 1 : 0))
            {
                RenderPass = heatShimmerComposePass
            })
                                                 .KeepAliveBy(ActiveObjects)
                                                 .InstantiatePermutation()
                                                 .KeepAliveBy(ActiveObjects);

            if (OfflineCompilation)
            {
                return;
            }

            Parameters.Set(RenderTargetKeys.DepthStencilSource, DepthStencil.Texture);
            Parameters.Set(TexturingKeys.Sampler, GraphicsDevice.SamplerStates.PointClamp);

            // ------------------------------------------
            // BoundingBox prepass
            // ------------------------------------------
            var renderTargetDesc = RenderSource.Description;
            var bbRenderTarget   = Texture.New2D(GraphicsDevice, renderTargetDesc.Width, renderTargetDesc.Height, PixelFormat.R32G32_Float, TextureFlags.ShaderResource | TextureFlags.RenderTarget).KeepAliveBy(ActiveObjects);

            bbRenderTargetPlugin.RenderTarget = bbRenderTarget.ToRenderTarget();

            // Add meshes
            foreach (var bbMeshData in BoundingBoxes)
            {
                // Mesh for MinPass
                var bbMesh = new EffectMesh(minMaxEffect, bbMeshData).KeepAliveBy(ActiveObjects);
                // Add mesh
                // boundingBoxPass.AddPass(bbMesh.EffectMeshPasses[0].EffectPass);
                effectMeshes.Add(bbMesh);
                RenderSystem.GlobalMeshes.AddMesh(bbMesh);
            }

            // ------------------------------------------
            // Heat Compute
            // ------------------------------------------
            var shimmerTexture      = Texture.New2D(GraphicsDevice, renderTargetDesc.Width, renderTargetDesc.Height, PixelFormat.R8_UNorm, TextureFlags.ShaderResource | TextureFlags.RenderTarget);
            var shimmerRenderTarget = shimmerTexture.ToRenderTarget();

            heatShimmerPass.StartPass += context => context.GraphicsDevice.Clear(shimmerRenderTarget, Color.Black);

            var quadMesh = new EffectMesh(heatShimmerEffect).KeepAliveBy(ActiveObjects);

            quadMesh.Parameters.Set(TexturingKeys.Texture1, bbRenderTarget);
            quadMesh.Parameters.Set(RenderTargetKeys.RenderTarget, shimmerRenderTarget);

            effectMeshes.Add(quadMesh);
            RenderSystem.GlobalMeshes.AddMesh(quadMesh);

            // ------------------------------------------
            // Heat display
            // ------------------------------------------
            quadMesh = new EffectMesh(heatShimmerDisplayEffect).KeepAliveBy(ActiveObjects);
            quadMesh.Parameters.Set(TexturingKeys.Texture0, RenderSource);
            quadMesh.Parameters.Set(TexturingKeys.Texture1, shimmerTexture);
            quadMesh.Parameters.Set(RenderTargetKeys.RenderTarget, RenderTarget);

            effectMeshes.Add(quadMesh);
            RenderSystem.GlobalMeshes.AddMesh(quadMesh);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Render Primitive
        /// </summary>
        /// <param name="pass">Which pass are we currently in</param>
        /// <param name="pickingID">ID used to identify which object was picked</param>
        /// <param name="scene">Main scene renderer</param>
        /// <param name="time">Time it took to render the last frame</param>
        public override void Render(RenderPass pass, int pickingID, SceneWindow scene, float time)
        {
            //if (!RenderSettings.AvatarRenderingEnabled && Attached) return;//hack

            // Individual prim matrix
            GL.PushMatrix();

            // Prim roation and position and scale
            GL.MultMatrix(Math3D.CreateSRTMatrix(Prim.Scale, RenderRotation, RenderPosition));

            // Do we have animated texture on this face
            bool animatedTexture = false;

            // Initialise flags tracking what type of faces this prim has
            if (pass == RenderPass.Simple)
            {
                HasSimpleFaces = false;
            }
            else if (pass == RenderPass.Alpha)
            {
                HasAlphaFaces = false;
            }
            else if (pass == RenderPass.Invisible)
            {
                HasInvisibleFaces = false;
            }

            // Draw the prim faces
            for (int j = 0; j < Faces.Count; j++)
            {
                Primitive.TextureEntryFace teFace = Prim.Textures.GetFace((uint)j);
                Face     face = Faces[j];
                FaceData data = (FaceData)face.UserData;

                if (data == null)
                {
                    continue;
                }

                if (teFace == null)
                {
                    continue;
                }

                // Don't render transparent faces
                Color4 RGBA = teFace.RGBA;

                if (data.TextureInfo.FullAlpha || RGBA.A <= 0.01f)
                {
                    continue;
                }

                bool switchedLightsOff = false;

                if (pass == RenderPass.Picking)
                {
                    data.PickingID = pickingID;
                    var primNrBytes = Utils.UInt16ToBytes((ushort)pickingID);
                    var faceColor   = new byte[] { primNrBytes[0], primNrBytes[1], (byte)j, 255 };
                    GL.Color4(faceColor);
                }
                else if (pass == RenderPass.Invisible)
                {
                    if (!data.TextureInfo.IsInvisible)
                    {
                        continue;
                    }
                    HasInvisibleFaces = true;
                }
                else
                {
                    if (data.TextureInfo.IsInvisible)
                    {
                        continue;
                    }
                    bool belongToAlphaPass = (RGBA.A < 0.99f) || (data.TextureInfo.HasAlpha && !data.TextureInfo.IsMask);

                    if (belongToAlphaPass && pass != RenderPass.Alpha)
                    {
                        continue;
                    }
                    if (!belongToAlphaPass && pass == RenderPass.Alpha)
                    {
                        continue;
                    }

                    if (pass == RenderPass.Simple)
                    {
                        HasSimpleFaces = true;
                    }
                    else if (pass == RenderPass.Alpha)
                    {
                        HasAlphaFaces = true;
                    }

                    if (teFace.Fullbright)
                    {
                        GL.Disable(EnableCap.Lighting);
                        switchedLightsOff = true;
                    }

                    float shiny = 0f;
                    switch (teFace.Shiny)
                    {
                    case Shininess.High:
                        shiny = 0.96f;
                        break;

                    case Shininess.Medium:
                        shiny = 0.64f;
                        break;

                    case Shininess.Low:
                        shiny = 0.24f;
                        break;
                    }

                    if (shiny > 0f)
                    {
                        scene.StartShiny();
                    }
                    GL.Material(MaterialFace.Front, MaterialParameter.Shininess, shiny);
                    var faceColor = new float[] { RGBA.R, RGBA.G, RGBA.B, RGBA.A };
                    GL.Color4(faceColor);

                    GL.Material(MaterialFace.Front, MaterialParameter.Specular, new float[] { 0.5f, 0.5f, 0.5f, 1f });

                    if (data.TextureInfo.TexturePointer == 0)
                    {
                        TextureInfo teInfo;
                        if (scene.TryGetTextureInfo(teFace.TextureID, out teInfo))
                        {
                            data.TextureInfo = teInfo;
                        }
                    }

                    if (data.TextureInfo.TexturePointer == 0)
                    {
                        GL.Disable(EnableCap.Texture2D);
                        if (!data.TextureInfo.FetchFailed)
                        {
                            scene.DownloadTexture(new TextureLoadItem()
                            {
                                Prim   = this.Prim,
                                TeFace = teFace,
                                Data   = data
                            }, false);
                        }
                    }
                    else
                    {
                        // Is this face using texture animation
                        if ((Prim.TextureAnim.Flags & Primitive.TextureAnimMode.ANIM_ON) != 0 &&
                            (Prim.TextureAnim.Face == j || Prim.TextureAnim.Face == 255))
                        {
                            if (data.AnimInfo == null)
                            {
                                data.AnimInfo = new TextureAnimationInfo();
                            }
                            data.AnimInfo.PrimAnimInfo = Prim.TextureAnim;
                            data.AnimInfo.Step(time);
                            animatedTexture = true;
                        }
                        else if (data.AnimInfo != null) // Face texture not animated. Do we have previous anim setting?
                        {
                            data.AnimInfo = null;
                        }

                        GL.Enable(EnableCap.Texture2D);
                        GL.BindTexture(TextureTarget.Texture2D, data.TextureInfo.TexturePointer);
                    }
                }
                //hack

                /*
                 * if (!RenderSettings.UseVBO || data.VBOFailed)
                 * {
                 * Vertex[] verts = face.Vertices.ToArray();
                 * ushort[] indices = face.Indices.ToArray();
                 *
                 * unsafe
                 * {
                 * fixed (float* normalPtr = &verts[0].Normal.X)
                 * fixed (float* texPtr = &verts[0].TexCoord.X)
                 * {
                 * GL.NormalPointer(NormalPointerType.Float, FaceData.VertexSize, (IntPtr)normalPtr);
                 * GL.TexCoordPointer(2, TexCoordPointerType.Float, FaceData.VertexSize, (IntPtr)texPtr);
                 * GL.VertexPointer(3, VertexPointerType.Float, FaceData.VertexSize, verts);
                 * GL.DrawElements(BeginMode.Triangles, indices.Length, DrawElementsType.UnsignedShort, indices);
                 * }
                 * }
                 * }
                 * else
                 * {
                 * if (data.CheckVBO(face))
                 * {
                 * Compat.BindBuffer(BufferTarget.ArrayBuffer, data.VertexVBO);
                 * Compat.BindBuffer(BufferTarget.ElementArrayBuffer, data.IndexVBO);
                 * GL.NormalPointer(NormalPointerType.Float, FaceData.VertexSize, (IntPtr)12);
                 * GL.TexCoordPointer(2, TexCoordPointerType.Float, FaceData.VertexSize, (IntPtr)(24));
                 * GL.VertexPointer(3, VertexPointerType.Float, FaceData.VertexSize, (IntPtr)(0));
                 *
                 * GL.DrawElements(BeginMode.Triangles, face.Indices.Count, DrawElementsType.UnsignedShort, IntPtr.Zero);
                 * }
                 * Compat.BindBuffer(BufferTarget.ArrayBuffer, 0);
                 * Compat.BindBuffer(BufferTarget.ElementArrayBuffer, 0);
                 *
                 * }
                 */
                if (switchedLightsOff)
                {
                    GL.Enable(EnableCap.Lighting);
                    switchedLightsOff = false;
                }
            }

            GL.BindTexture(TextureTarget.Texture2D, 0);
            RHelp.ResetMaterial();

            // Reset texture coordinates if we modified them in texture animation
            if (animatedTexture)
            {
                GL.MatrixMode(MatrixMode.Texture);
                GL.LoadIdentity();
                GL.MatrixMode(MatrixMode.Modelview);
            }

            // Pop the prim matrix
            GL.PopMatrix();

            base.Render(pass, pickingID, scene, time);
        }
Exemplo n.º 13
0
 public RenderContext(Camera camera, RenderPass renderPass)
 {
     Camera     = camera;
     RenderPass = renderPass;
 }
Exemplo n.º 14
0
        public void Render(RenderPass pass)
        {
            switch(pass)
            {
            case RenderPass.Render : SceneManager.DefaultFramebuffer.enable(true); break;
            case RenderPass.Shadow : SceneManager.LightFramebuffer.enable(true); break;
            }

            foreach(VTKObject obj in objects)
            {
                obj.Render(pass);
            }
        }
Exemplo n.º 15
0
        private void RenderTerrain(RenderPass pass)
        {
            terrainTimeSinceUpdate += lastFrameTime;

            if (terrainModified && terrainTimeSinceUpdate > RenderSettings.MinimumTimeBetweenTerrainUpdated)
            {
                if (!terrainInProgress)
                {
                    terrainInProgress = true;
                    ResetTerrain(false);
                    UpdateTerrain();
                }
            }

            if (terrainTextureNeedsUpdate)
            {
                UpdateTerrainTexture();
            }

            if (terrainIndices == null || terrainVertices == null) return;

            GL.Color3(1f, 1f, 1f);
            GL.EnableClientState(ArrayCap.VertexArray);
            GL.EnableClientState(ArrayCap.TextureCoordArray);
            GL.EnableClientState(ArrayCap.NormalArray);
            if (pass == RenderPass.Picking)
            {
                GL.EnableClientState(ArrayCap.ColorArray);
                GL.ShadeModel(ShadingModel.Flat);
            }

            if (terrainImage != null)
            {
                if (terrainTexture != -1)
                {
                    GL.DeleteTexture(terrainTexture);
                }

                terrainTexture = RHelp.GLLoadImage(terrainImage, false);
                terrainImage.Dispose();
                terrainImage = null;
            }

            if (pass != RenderPass.Picking && terrainTexture != -1)
            {
                GL.Enable(EnableCap.Texture2D);
                GL.BindTexture(TextureTarget.Texture2D, terrainTexture);
            }

            if (!RenderSettings.UseVBO || terrainVBOFailed)
            {
                unsafe
                {
                    fixed (float* normalPtr = &terrainVertices[0].Vertex.Normal.X)
                    fixed (float* texPtr = &terrainVertices[0].Vertex.TexCoord.X)
                    fixed (byte* colorPtr = &terrainVertices[0].Color.R)
                    {
                        GL.NormalPointer(NormalPointerType.Float, ColorVertex.Size, (IntPtr)normalPtr);
                        GL.TexCoordPointer(2, TexCoordPointerType.Float, ColorVertex.Size, (IntPtr)texPtr);
                        GL.VertexPointer(3, VertexPointerType.Float, ColorVertex.Size, terrainVertices);
                        if (pass == RenderPass.Picking)
                        {
                            GL.ColorPointer(4, ColorPointerType.UnsignedByte, ColorVertex.Size, (IntPtr)colorPtr);
                        }
                        GL.DrawElements(BeginMode.Triangles, terrainIndices.Length, DrawElementsType.UnsignedShort, terrainIndices);
                    }
                }
            }
            else
            {
                if (terrainVBO == -1)
                {
                    Compat.GenBuffers(out terrainVBO);
                    Compat.BindBuffer(BufferTarget.ArrayBuffer, terrainVBO);
                    Compat.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(terrainVertices.Length * ColorVertex.Size), terrainVertices, BufferUsageHint.StaticDraw);
                    if (Compat.BufferSize(BufferTarget.ArrayBuffer) != terrainVertices.Length * ColorVertex.Size)
                    {
                        terrainVBOFailed = true;
                        Compat.BindBuffer(BufferTarget.ArrayBuffer, 0);
                        terrainVBO = -1;
                    }
                }
                else
                {
                    Compat.BindBuffer(BufferTarget.ArrayBuffer, terrainVBO);
                }

                if (terrainIndexVBO == -1)
                {
                    Compat.GenBuffers(out terrainIndexVBO);
                    Compat.BindBuffer(BufferTarget.ElementArrayBuffer, terrainIndexVBO);
                    Compat.BufferData(BufferTarget.ElementArrayBuffer, (IntPtr)(terrainIndices.Length * sizeof(ushort)), terrainIndices, BufferUsageHint.StaticDraw);
                    if (Compat.BufferSize(BufferTarget.ElementArrayBuffer) != terrainIndices.Length * sizeof(ushort))
                    {
                        terrainVBOFailed = true;
                        Compat.BindBuffer(BufferTarget.ElementArrayBuffer, 0);
                        terrainIndexVBO = -1;
                    }
                }
                else
                {
                    Compat.BindBuffer(BufferTarget.ElementArrayBuffer, terrainIndexVBO);
                }

                if (!terrainVBOFailed)
                {
                    GL.NormalPointer(NormalPointerType.Float, ColorVertex.Size, (IntPtr)12);
                    GL.TexCoordPointer(2, TexCoordPointerType.Float, ColorVertex.Size, (IntPtr)(24));
                    if (pass == RenderPass.Picking)
                    {
                        GL.ColorPointer(4, ColorPointerType.UnsignedByte, ColorVertex.Size, (IntPtr)32);
                    }
                    GL.VertexPointer(3, VertexPointerType.Float, ColorVertex.Size, (IntPtr)(0));

                    GL.DrawElements(BeginMode.Triangles, terrainIndices.Length, DrawElementsType.UnsignedShort, IntPtr.Zero);
                }

                Compat.BindBuffer(BufferTarget.ArrayBuffer, 0);
                Compat.BindBuffer(BufferTarget.ElementArrayBuffer, 0);
            }

            if (pass == RenderPass.Picking)
            {
                GL.DisableClientState(ArrayCap.ColorArray);
                GL.ShadeModel(ShadingModel.Smooth);
            }
            else
            {
                GL.BindTexture(TextureTarget.Texture2D, 0);
            }
            GL.DisableClientState(ArrayCap.VertexArray);
            GL.DisableClientState(ArrayCap.TextureCoordArray);
            GL.DisableClientState(ArrayCap.NormalArray);
        }
Exemplo n.º 16
0
        void Render(Queue queue, CommandPool cmdPool, VertexData vertexData, ImageData imageData, Buffer imageBuffer, RenderPass renderPass, Pipeline pipeline, Framebuffer framebuffer)
        {
            uint width  = imageData.Width;
            uint height = imageData.Height;

            var cmdBuffers = AllocateCommandBuffers(cmdPool, 1);
            var cmdBuffer  = cmdBuffers[0];

            var beginInfo = new CommandBufferBeginInfo();

            cmdBuffer.Begin(beginInfo);  // CommandBuffer Begin

            PipelineBarrierSetLayout(cmdBuffer, imageData.Image, ImageLayout.Preinitialized, ImageLayout.ColorAttachmentOptimal, AccessFlags.HostWrite, AccessFlags.ColorAttachmentWrite);

            var clearRange = new ImageSubresourceRange(ImageAspectFlags.Color, 0, 1, 0, 1);

            cmdBuffer.ClearColorImage(imageData.Image, ImageLayout.TransferDstOptimal, new ClearColorValue(), new[] { clearRange });

            RenderTriangle(cmdBuffer, vertexData, renderPass, pipeline, framebuffer, width, height);

            // Prepare the render target for copying
            PipelineBarrierSetLayout(cmdBuffer, imageData.Image, ImageLayout.ColorAttachmentOptimal, ImageLayout.TransferSrcOptimal, AccessFlags.ColorAttachmentWrite, AccessFlags.TransferRead);

            // Copy the render target image to a buffer
            CopyImageToBuffer(cmdBuffer, imageData, imageBuffer, width, height);

            // End recording commands to the buffer
            cmdBuffer.End();

            SubmitForExecution(queue, cmdBuffer);

            queue.WaitIdle(); // wait for execution to finish

            device.FreeCommandBuffers(cmdPool, new[] { cmdBuffer });
        }
Exemplo n.º 17
0
 public DisposableRenderPass(Vk api, Device device, RenderPass renderPass)
 {
     _api    = api;
     _device = device;
     Value   = renderPass;
 }
Exemplo n.º 18
0
        public EnvironmentCube(string cubemapPath, PipelineLayout plLayout, Queue staggingQ, RenderPass renderPass, PipelineCache cache = null)
            : base(renderPass, cache, "EnvCube pipeline")
        {
            using (GraphicPipelineConfig cfg = GraphicPipelineConfig.CreateDefault(VkPrimitiveTopology.TriangleList, renderPass.Samples, false)) {
                cfg.RenderPass = renderPass;
                cfg.Layout     = plLayout;
                cfg.AddVertexBinding(0, 3 * sizeof(float));
                cfg.AddVertexAttributes(0, VkFormat.R32g32b32Sfloat);
                cfg.AddShaders(
                    new ShaderInfo(Dev, VkShaderStageFlags.Vertex, "#EnvironmentPipeline.skybox.vert.spv"),
                    new ShaderInfo(Dev, VkShaderStageFlags.Fragment, STR_FRAG_PATH)
                    );

                cfg.multisampleState.rasterizationSamples = Samples;

                layout = cfg.Layout;

                init(cfg);
            }

            using (CommandPool cmdPool = new CommandPool(staggingQ.Dev, staggingQ.index)) {
                vboSkybox = new GPUBuffer <float> (staggingQ, cmdPool, VkBufferUsageFlags.VertexBuffer, box_vertices);

                cubemap = KTX.KTX.Load(staggingQ, cmdPool, cubemapPath,
                                       VkImageUsageFlags.Sampled, VkMemoryPropertyFlags.DeviceLocal, true);
                cubemap.CreateView(VkImageViewType.Cube, VkImageAspectFlags.Color);
                cubemap.CreateSampler(VkSamplerAddressMode.ClampToEdge);
                cubemap.SetName("skybox Texture");
                cubemap.Descriptor.imageLayout = VkImageLayout.ShaderReadOnlyOptimal;

                generateBRDFLUT(staggingQ, cmdPool);
                generateCubemaps(staggingQ, cmdPool);
            }
        }
Exemplo n.º 19
0
 public override bool NeedsRenderPass(RenderPass pass)
 {
     return(true);
 }
Exemplo n.º 20
0
 protected override void InitializePermanent()
 {
     _renderPass     = ToDispose(CreateRenderPass());
     _pipelineLayout = ToDispose(CreatePipelineLayout());
 }
        public override void Render(RenderPass pass, int pickingID, SceneWindow scene, float time)
        {
            terrainTimeSinceUpdate += time;

            if (Modified && terrainTimeSinceUpdate > RenderSettings.MinimumTimeBetweenTerrainUpdated)
            {
                if (!terrainInProgress)
                {
                    terrainInProgress = true;
                    ResetTerrain(false);
                    UpdateTerrain();
                }
            }

            if (terrainTextureNeedsUpdate)
            {
                UpdateTerrainTexture();
            }

            if (terrainIndices == null || terrainVertices == null)
            {
                return;
            }

            GL.Color3(1f, 1f, 1f);
            GL.EnableClientState(ArrayCap.VertexArray);
            GL.EnableClientState(ArrayCap.TextureCoordArray);
            GL.EnableClientState(ArrayCap.NormalArray);
            if (pass == RenderPass.Picking)
            {
                GL.EnableClientState(ArrayCap.ColorArray);
                GL.ShadeModel(ShadingModel.Flat);
            }

            if (terrainImage != null)
            {
                if (terrainTexture != -1)
                {
                    GL.DeleteTexture(terrainTexture);
                }

                terrainTexture = RHelp.GLLoadImage(terrainImage, false);
                terrainImage.Dispose();
                terrainImage = null;
            }

            if (pass != RenderPass.Picking && terrainTexture != -1)
            {
                GL.Enable(EnableCap.Texture2D);
                GL.BindTexture(TextureTarget.Texture2D, terrainTexture);
            }

            if (!RenderSettings.UseVBO || terrainVBOFailed)
            {
                unsafe
                {
                    fixed(float *normalPtr = &terrainVertices[0].Vertex.Normal.X)
                    fixed(float *texPtr  = &terrainVertices[0].Vertex.TexCoord.X)
                    fixed(byte *colorPtr = &terrainVertices[0].Color.R)
                    {
                        GL.NormalPointer(NormalPointerType.Float, ColorVertex.Size, (IntPtr)normalPtr);
                        GL.TexCoordPointer(2, TexCoordPointerType.Float, ColorVertex.Size, (IntPtr)texPtr);
                        GL.VertexPointer(3, VertexPointerType.Float, ColorVertex.Size, terrainVertices);
                        if (pass == RenderPass.Picking)
                        {
                            GL.ColorPointer(4, ColorPointerType.UnsignedByte, ColorVertex.Size, (IntPtr)colorPtr);
                        }
                        GL.DrawElements(PrimitiveType.Triangles, terrainIndices.Length, DrawElementsType.UnsignedInt, terrainIndices);
                    }
                }
            }
            else
            {
                if (terrainVBO == -1)
                {
                    Compat.GenBuffers(out terrainVBO);
                    Compat.BindBuffer(BufferTarget.ArrayBuffer, terrainVBO);
                    Compat.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(terrainVertices.Length * ColorVertex.Size), terrainVertices, BufferUsageHint.StaticDraw);
                    if (Compat.BufferSize(BufferTarget.ArrayBuffer) != terrainVertices.Length * ColorVertex.Size)
                    {
                        terrainVBOFailed = true;
                        Compat.BindBuffer(BufferTarget.ArrayBuffer, 0);
                        terrainVBO = -1;
                    }
                }
                else
                {
                    Compat.BindBuffer(BufferTarget.ArrayBuffer, terrainVBO);
                }

                if (terrainIndexVBO == -1)
                {
                    Compat.GenBuffers(out terrainIndexVBO);
                    Compat.BindBuffer(BufferTarget.ElementArrayBuffer, terrainIndexVBO);
                    Compat.BufferData(BufferTarget.ElementArrayBuffer, (IntPtr)(terrainIndices.Length * sizeof(uint)), terrainIndices, BufferUsageHint.StaticDraw);
                    if (Compat.BufferSize(BufferTarget.ElementArrayBuffer) != terrainIndices.Length * sizeof(uint))
                    {
                        terrainVBOFailed = true;
                        Compat.BindBuffer(BufferTarget.ElementArrayBuffer, 0);
                        terrainIndexVBO = -1;
                    }
                }
                else
                {
                    Compat.BindBuffer(BufferTarget.ElementArrayBuffer, terrainIndexVBO);
                }

                if (!terrainVBOFailed)
                {
                    GL.NormalPointer(NormalPointerType.Float, ColorVertex.Size, (IntPtr)12);
                    GL.TexCoordPointer(2, TexCoordPointerType.Float, ColorVertex.Size, (IntPtr)(24));
                    if (pass == RenderPass.Picking)
                    {
                        GL.ColorPointer(4, ColorPointerType.UnsignedByte, ColorVertex.Size, (IntPtr)32);
                    }
                    GL.VertexPointer(3, VertexPointerType.Float, ColorVertex.Size, (IntPtr)(0));

                    GL.DrawElements(PrimitiveType.Triangles, terrainIndices.Length, DrawElementsType.UnsignedInt, IntPtr.Zero);
                }

                Compat.BindBuffer(BufferTarget.ArrayBuffer, 0);
                Compat.BindBuffer(BufferTarget.ElementArrayBuffer, 0);
            }

            if (pass == RenderPass.Picking)
            {
                GL.DisableClientState(ArrayCap.ColorArray);
                GL.ShadeModel(ShadingModel.Smooth);
            }
            else
            {
                GL.BindTexture(TextureTarget.Texture2D, 0);
            }
            GL.DisableClientState(ArrayCap.VertexArray);
            GL.DisableClientState(ArrayCap.TextureCoordArray);
            GL.DisableClientState(ArrayCap.NormalArray);
        }
Exemplo n.º 22
0
 /// <summary>
 /// Render scene object
 /// </summary>
 /// <param name="pass">Which pass are we currently in</param>
 /// <param name="pickingID">ID used to identify which object was picked</param>
 /// <param name="scene">Main scene renderer</param>
 /// <param name="time">Time it took to render the last frame</param>
 public virtual void Render(RenderPass pass, int pickingID, SceneWindow scene, float time)
 {
 }
Exemplo n.º 23
0
        private void RenderObjects(RenderPass pass)
        {
            if (!PrimitiveRenderingEnabled) return;

            GL.EnableClientState(ArrayCap.VertexArray);
            GL.EnableClientState(ArrayCap.TextureCoordArray);
            GL.EnableClientState(ArrayCap.NormalArray);

            Vector3 myPos = Vector3.Zero;
            RenderAvatar me;
            if (Avatars.TryGetValue(Client.Self.LocalID, out me))
            {
                myPos = me.RenderPosition;
            }
            else
            {
                myPos = Client.Self.SimPosition;
            }

            int nrPrims = SortedObjects.Count;
            for (int i = 0; i < nrPrims; i++)
            {
                //RenderBoundingBox(SortedPrims[i]);

                // When rendering alpha faces, draw from back towards the camers
                // otherwise from those closest to camera, to the farthest
                int ix = pass == RenderPass.Alpha ? nrPrims - i - 1 : i;
                SceneObject obj = SortedObjects[ix];

                if (obj is RenderPrimitive)
                {
                    // Don't render objects that are outside the draw distane
                    if (Vector3.DistanceSquared(myPos, obj.RenderPosition) > drawDistanceSquared) continue;
                    obj.StartQuery(pass);
                    RenderPrim((RenderPrimitive)obj, pass, ix);
                    obj.EndQuery(pass);
                }
            }

            GL.Disable(EnableCap.Texture2D);
            GL.DisableClientState(ArrayCap.VertexArray);
            GL.DisableClientState(ArrayCap.TextureCoordArray);
            GL.DisableClientState(ArrayCap.NormalArray);
        }
Exemplo n.º 24
0
        private void RenderObjects(RenderPass pass)
        {
            lock (Prims)
            {
                int primNr = 0;
                foreach (FacetedMesh mesh in Prims.Values)
                {
                    primNr++;
                    Primitive prim = mesh.Prim;
                    // Individual prim matrix
                    GL.PushMatrix();

                    if (prim.ParentID == RootPrimLocalID)
                    {
                        FacetedMesh parent = null;
                        if (Prims.TryGetValue(prim.ParentID, out parent))
                        {
                            // Apply prim translation and rotation relative to the root prim
                            GL.MultMatrix(Math3D.CreateRotationMatrix(parent.Prim.Rotation));
                            //GL.MultMatrixf(Math3D.CreateTranslationMatrix(parent.Prim.Position));
                        }

                        // Prim roation relative to root
                        GL.MultMatrix(Math3D.CreateTranslationMatrix(prim.Position));
                    }

                    // Prim roation
                    GL.MultMatrix(Math3D.CreateRotationMatrix(prim.Rotation));

                    // Prim scaling
                    GL.Scale(prim.Scale.X, prim.Scale.Y, prim.Scale.Z);

                    // Draw the prim faces
                    for (int j = 0; j < mesh.Faces.Count; j++)
                    {
                        Primitive.TextureEntryFace teFace = mesh.Prim.Textures.FaceTextures[j];
                        Face     face = mesh.Faces[j];
                        FaceData data = (FaceData)face.UserData;

                        if (teFace == null)
                        {
                            teFace = mesh.Prim.Textures.DefaultTexture;
                        }

                        if (pass == RenderPass.Picking)
                        {
                            data.PickingID = primNr;
                            var primNrBytes = Utils.Int16ToBytes((short)primNr);
                            var faceColor   = new byte[] { primNrBytes[0], primNrBytes[1], (byte)j, 255 };

                            GL.Color4(faceColor);
                        }
                        else
                        {
                            bool belongToAlphaPass = (teFace.RGBA.A < 0.99) || data.TextureInfo.HasAlpha;

                            if (belongToAlphaPass && pass != RenderPass.Alpha)
                            {
                                continue;
                            }
                            if (!belongToAlphaPass && pass == RenderPass.Alpha)
                            {
                                continue;
                            }

                            // Don't render transparent faces
                            if (teFace.RGBA.A <= 0.01f)
                            {
                                continue;
                            }

                            switch (teFace.Shiny)
                            {
                            case Shininess.High:
                                GL.Material(MaterialFace.Front, MaterialParameter.Shininess, 94f);
                                break;

                            case Shininess.Medium:
                                GL.Material(MaterialFace.Front, MaterialParameter.Shininess, 64f);
                                break;

                            case Shininess.Low:
                                GL.Material(MaterialFace.Front, MaterialParameter.Shininess, 24f);
                                break;

                            case Shininess.None:
                            default:
                                GL.Material(MaterialFace.Front, MaterialParameter.Shininess, 0f);
                                break;
                            }

                            var faceColor = new float[] { teFace.RGBA.R, teFace.RGBA.G, teFace.RGBA.B, teFace.RGBA.A };

                            GL.Color4(faceColor);
                            GL.Material(MaterialFace.Front, MaterialParameter.AmbientAndDiffuse, faceColor);
                            GL.Material(MaterialFace.Front, MaterialParameter.Specular, faceColor);

                            if (data.TextureInfo.TexturePointer != 0)
                            {
                                GL.Enable(EnableCap.Texture2D);
                            }
                            else
                            {
                                GL.Disable(EnableCap.Texture2D);
                            }

                            // Bind the texture
                            GL.BindTexture(TextureTarget.Texture2D, data.TextureInfo.TexturePointer);
                        }

                        GL.TexCoordPointer(2, TexCoordPointerType.Float, 0, data.TexCoords);
                        GL.VertexPointer(3, VertexPointerType.Float, 0, data.Vertices);
                        GL.NormalPointer(NormalPointerType.Float, 0, data.Normals);
                        GL.DrawElements(PrimitiveType.Triangles, data.Indices.Length, DrawElementsType.UnsignedShort, data.Indices);
                    }

                    // Pop the prim matrix
                    GL.PopMatrix();
                }
            }
        }
Exemplo n.º 25
0
        /// <summary>
        /// Executes the draw calls.
        /// </summary>
        /// <param name="context">The GPU command context.</param>
        /// <param name="task">The render task.</param>
        /// <param name="output">The output texture.</param>
        /// <param name="pass">The rendering pass mode.</param>
        public void ExecuteDrawCalls(GPUContext context, RenderTask task, RenderTarget output, RenderPass pass)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            if (task == null)
            {
                throw new ArgumentNullException(nameof(task));
            }
            if (output == null)
            {
                throw new ArgumentNullException(nameof(output));
            }

            GPUContext.Internal_ExecuteDrawCalls(context.unmanagedPtr, task.unmanagedPtr, output.unmanagedPtr, DrawCalls, pass);
        }
Exemplo n.º 26
0
 protected abstract void Render(T scene, RenderPass pass);
Exemplo n.º 27
0
        private void RenderAvatarsSkeleton(RenderPass pass)
        {
            if (!RenderSettings.RenderAvatarSkeleton) return;

            lock (Avatars)
            {
                foreach (RenderAvatar av in Avatars.Values)
                {
                    // Individual prim matrix
                    GL.PushMatrix();

                    // Prim roation and position
                    Vector3 pos = av.avatar.Position;

                    Vector3 avataroffset = av.glavatar.skel.getOffset("mPelvis");

                    GL.MultMatrix(Math3D.CreateSRTMatrix(new Vector3(1, 1, 1), av.RenderRotation, av.RenderPosition - avataroffset * av.RenderRotation));

                    GL.Begin(BeginMode.Lines);

                    GL.Color3(1.0, 0.0, 0.0);

                    foreach (Bone b in av.glavatar.skel.mBones.Values)
                    {
                        Vector3 newpos = b.getTotalOffset();

                        if (b.parent != null)
                        {
                            Vector3 parentpos = b.parent.getTotalOffset();
                            GL.Vertex3(parentpos.X, parentpos.Y, parentpos.Z);
                        }
                        else
                        {
                            GL.Vertex3(newpos.X, newpos.Y, newpos.Z);
                        }

                        GL.Vertex3(newpos.X, newpos.Y, newpos.Z);

                        //Mark the joints


                        newpos.X += 0.01f;
                        newpos.Y += 0.01f;
                        newpos.Z += 0.01f;
                        GL.Vertex3(newpos.X, newpos.Y, newpos.Z);

                        newpos.X -= 0.02f;
                        GL.Vertex3(newpos.X, newpos.Y, newpos.Z);
                        GL.Vertex3(newpos.X, newpos.Y, newpos.Z);

                        newpos.Y -= 0.02f;
                        GL.Vertex3(newpos.X, newpos.Y, newpos.Z);
                        GL.Vertex3(newpos.X, newpos.Y, newpos.Z);

                        newpos.X += 0.02f;
                        GL.Vertex3(newpos.X, newpos.Y, newpos.Z);
                        GL.Vertex3(newpos.X, newpos.Y, newpos.Z);

                        newpos.Y += 0.02f;
                        GL.Vertex3(newpos.X, newpos.Y, newpos.Z);
                        GL.Vertex3(newpos.X, newpos.Y, newpos.Z);

                        newpos.Z -= 0.02f;
                        GL.Vertex3(newpos.X, newpos.Y, newpos.Z);
                        GL.Vertex3(newpos.X, newpos.Y, newpos.Z);

                        newpos.Y -= 0.02f;
                        GL.Vertex3(newpos.X, newpos.Y, newpos.Z);
                        GL.Vertex3(newpos.X, newpos.Y, newpos.Z);

                        newpos.X -= 0.02f;
                        GL.Vertex3(newpos.X, newpos.Y, newpos.Z);
                        GL.Vertex3(newpos.X, newpos.Y, newpos.Z);

                        newpos.Y += 0.02f;
                        GL.Vertex3(newpos.X, newpos.Y, newpos.Z);
                        GL.Vertex3(newpos.X, newpos.Y, newpos.Z);

                        newpos.X += 0.02f;
                        GL.Vertex3(newpos.X, newpos.Y, newpos.Z);
                        GL.Vertex3(newpos.X, newpos.Y, newpos.Z);

                        newpos.Y -= 0.01f;
                        newpos.Z += 0.01f;
                        newpos.X -= 0.01f;
                        GL.Vertex3(newpos.X, newpos.Y, newpos.Z);



                    }



                    GL.Color3(0.0, 1.0, 0.0);

                    GL.End();

                    GL.PopMatrix();
                }
            }
        }
Exemplo n.º 28
0
 public LightShaftsProcessor(MainPlugin mainPlugin, RenderTargetsPlugin mainTargetPlugin, RenderPass lightShaftsPass)
     : base(new PropertyKey[] { LightShaftsComponent.Key, LightComponent.Key })
 {
     this.mainPlugin       = mainPlugin;
     this.mainTargetPlugin = mainTargetPlugin;
     this.lightShaftsPass  = lightShaftsPass;
 }
Exemplo n.º 29
0
 internal void addPass(RenderPass renderModel)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 30
0
        public void Draw(ModelEffectInstance modelEffect, RenderPass pass)
        {
            // Draw the geometry for the current pass
            var geometry = m_geometry[(int)pass];

            if (geometry.IndexCount > 0)
            {
                modelEffect.ModelMatrix     = Matrix4.Identity;
                modelEffect.UVOffset        = Vector2.Zero;
                modelEffect.UVScale         = Vector2.One;
                modelEffect.DiffuseColour   = Vector4.One;
                modelEffect.DiffuseTexture  = m_atlas;
                modelEffect.SpecularColour  = Vector3.One;
                modelEffect.SpecularTexture = m_atlas;
                modelEffect.NormalTexture   = m_atlas;
                modelEffect.EmissiveColour  = Vector3.One;
                modelEffect.EmissiveTexture = m_atlas;
                modelEffect.Bind();
                geometry.Draw();

                /*
                 * // Wireframe test code
                 * modelEffect.ModelMatrix = Matrix4.Identity;
                 * modelEffect.DiffuseColour = Vector4.One;
                 * modelEffect.DiffuseTexture = Texture.White;
                 * modelEffect.SpecularColour = Vector3.One;
                 * modelEffect.SpecularTexture = Texture.White;
                 * modelEffect.NormalTexture = Texture.Flat;
                 * modelEffect.Bind();
                 * using( var wireframe = geometry.ToWireframe( lines:false, normals:true, tangents:true, binormals:true ) )
                 * {
                 *  wireframe.Draw();
                 * }
                 */
            }

            foreach (var pair in m_liquidGeometry)
            {
                var behaviour      = pair.Key;
                var liquidGeometry = pair.Value;
                if (liquidGeometry.IndexCount > 0 && behaviour.Tile.RenderPass == pass)
                {
                    bool    visible;
                    Matrix4 modelMatrix;
                    Vector2 uvOffset, uvScale;
                    Vector4 colour;
                    if (behaviour.Animation != null)
                    {
                        float cameraFOV;
                        var   anim = LuaAnimation.Get(behaviour.Animation);
                        anim.Animate("Liquid", m_level.TimeMachine.RealTime, out visible, out modelMatrix, out uvOffset, out uvScale, out colour, out cameraFOV);
                    }
                    else
                    {
                        visible     = true;
                        modelMatrix = Matrix4.Identity;
                        uvOffset    = Vector2.Zero;
                        uvScale     = Vector2.One;
                        colour      = Vector4.One;
                    }
                    if (visible)
                    {
                        var surface = Texture.Get(behaviour.Texture, false);
                        surface.Wrap = true;

                        modelEffect.ModelMatrix     = modelMatrix;
                        modelEffect.UVOffset        = uvOffset;
                        modelEffect.UVScale         = uvScale;
                        modelEffect.DiffuseColour   = colour;
                        modelEffect.DiffuseTexture  = surface;
                        modelEffect.SpecularColour  = Vector3.One;
                        modelEffect.SpecularTexture = Texture.Black;
                        modelEffect.NormalTexture   = Texture.Flat;
                        modelEffect.EmissiveColour  = Vector3.One;
                        modelEffect.EmissiveTexture = Texture.Black;
                        modelEffect.Bind();
                        liquidGeometry.Draw();
                    }
                }
            }
        }
Exemplo n.º 31
0
        public override void Render(Shader shader, RenderPass pass, bool frontPass)
        {
            bool alphaPass = pass == RenderPass.Alpha;

            // Set global uniforms
            if (!pass.HasFlag(RenderPass.Shadow))
            {
                shader.LoadFloat("specularPower", 0);
                shader.LoadFloat("specularIntensity", 0);
            }

            // Render Entities
            if (!frontPass)
            {
                foreach (BatchGroup <VoxelObject, BatchedEntity> pair in entityBatch)
                {
                    RenderEntityList(shader, pass, pair.List, pair.Key);
                }
            }
            else
            {
                RenderEntityList(shader, pass, entityBatch.UnoptimizedBatch);
            }

            if (!pass.HasFlag(RenderPass.Shadow))
            {
                shader.LoadBool("skipLight", false);
                shader.LoadColor4("colorOverlay", Color.White);
                shader.LoadFloat("entityLighting", 1f);
            }

            StateManager.DepthFunc(DepthFunction.Less);
            StateManager.DisableWireframe();

            // Render raw voxel objects
            if (!frontPass)
            {
                foreach (BatchGroup <VoxelObject, Matrix4> pair in rawBatch)
                {
                    if (alphaPass && pair.Key.AlphaMesh == null)
                    {
                        continue;
                    }

                    Mesh mesh = alphaPass ? pair.Key.AlphaMesh : pair.Key.Mesh;
                    Master.PrepareMesh(mesh, pass);

                    foreach (Matrix4 transMatrix in pair.List)
                    {
                        // Load the transformation matrix
                        shader.LoadMatrix4("transformationMatrix", transMatrix);

                        // Draw
                        GL.DrawElements(mesh.BeginMode, mesh.VertexCount, DrawElementsType.UnsignedInt, IntPtr.Zero);
                    }

                    Master.EndMesh();
                }
            }
            else
            {
                //StateManager.DepthFunc(DepthFunction.Always);

                foreach (BatchGroup <VoxelObject, Matrix4> pair in rawBatchFront)
                {
                    if (alphaPass && pair.Key.AlphaMesh == null)
                    {
                        continue;
                    }

                    Mesh mesh = alphaPass ? pair.Key.AlphaMesh : pair.Key.Mesh;
                    Master.PrepareMesh(mesh, pass);

                    foreach (Matrix4 transMatrix in pair.List)
                    {
                        // Load the transformation matrix
                        shader.LoadMatrix4("transformationMatrix", transMatrix);

                        // Draw
                        GL.DrawElements(mesh.BeginMode, mesh.VertexCount, DrawElementsType.UnsignedInt, IntPtr.Zero);
                    }

                    Master.EndMesh();
                }

                // StateManager.DepthFunc(DepthFunction.Less);
            }
        }
Exemplo n.º 32
0
        public void StartQuery(RenderPass pass)
        {
            if (!RenderSettings.OcclusionCullingEnabled) return;

            if (pass == RenderPass.Simple)
            {
                StartSimpleQuery();
            }
            else if (pass == RenderPass.Alpha)
            {
                StartAlphaQuery();
            }
        }
Exemplo n.º 33
0
 public override bool NeedsRenderPass(RenderPass pass)
 {
     return(pass == m_renderPass);
 }
Exemplo n.º 34
0
        public override void Load()
        {
            base.Load();

            if (string.IsNullOrEmpty(StructureName) || StructureSize == 0)
                throw new InvalidOperationException("StructureName and StructureSize must be setup on ParticlePlugin");

            // Add passes to the render pass
            RenderPass.AddPass(updatePasses, copyPass, sortPass, renderPass);

            // Create effect to copy from particle buffer to sort buffer
            effectCopyToSortBuffer = this.EffectSystemOld.BuildEffect("CopyToSortBuffer").Using(
                new ComputeShaderPlugin(new ShaderClassSource("ParticleSortInitializer"), MaximumThreadPerGroup, 1, 1)
                    {
                        RenderPass = copyPass,
                        Macros = { new ShaderMacro("PARTICLE_STRUCT", StructureName) }
                    });
            effectCopyToSortBuffer.KeepAliveBy(ActiveObjects);
            effectCopyToSortBuffer.Parameters.AddSources(MainPlugin.ViewParameters);
            effectMeshCopyToSortBuffer = new EffectMesh(effectCopyToSortBuffer);

            // Clear the sort buffer
            copyPass.StartPass.AddFirst = (context) =>
                {
                    if (CapacityCount > 0)
                    {
                        // TODO handle progressive sorting
                        context.GraphicsDevice.ClearReadWrite(sortBuffer, new UInt4(0xFF7FFFFF)); // 0xFF7FFFFF = - float.MaxValue
                    }
                };

            // Create effect for bitonic sort 1 - pass 1
            effectBitonicSort1Pass1 = this.EffectSystemOld.BuildEffect("ParticleBitonicSort1-Pass1").Using(
                new ComputeShaderPlugin(new ShaderClassSource("ParticleBitonicSort1"), MaximumThreadPerGroup, 1, 1)
                {
                    RenderPass = bitonicSort1Pass1,
                    Macros = { new ShaderMacro("PARTICLE_STRUCT", StructureName),
                                new ShaderMacro("PARTICLE_SORT_PASS", 0)
                    }
                });
            effectBitonicSort1Pass1.KeepAliveBy(this);
            effectMeshSort1Pass1 = new EffectMesh(effectBitonicSort1Pass1);

            // Create effect for bitonic sort 1 - pass 2
            effectBitonicSort1Pass2 = this.EffectSystemOld.BuildEffect("ParticleBitonicSort1-Pass2").Using(
                new ComputeShaderPlugin(new ShaderClassSource("ParticleBitonicSort1"), MaximumThreadPerGroup, 1, 1)
                {
                    RenderPass = bitonicSort1Pass2,
                    Macros = { new ShaderMacro("PARTICLE_STRUCT", StructureName),
                                new ShaderMacro("PARTICLE_SORT_PASS", 1)
                    }
                });
            effectBitonicSort1Pass2.KeepAliveBy(this);
            effectMeshSort1Pass2 = new EffectMesh(effectBitonicSort1Pass2);

            // Creates Effect for bitonic sort 2
            var currentDepth = MaximumDepthLevel;
            for (int i = 0; i < bitonicSort2Passes.Length; i++)
            {
                var bitonicShader = new RenderPass(string.Format("Bitonic-{0}", currentDepth));
                bitonicSort2Passes[i] = bitonicShader;

                // Compile the new shader for this count
                effectBitonicSort2[i] = this.EffectSystemOld.BuildEffect("ParticleBitonicSort2-" + currentDepth).Using(
                    new ComputeShaderPlugin(new ShaderClassSource("ParticleBitonicSort2", currentDepth), MaximumThreadPerGroup, 1, 1)
                        {
                            RenderPass = bitonicShader,
                            Macros = { new ShaderMacro("PARTICLE_STRUCT", StructureName) }
                        });
                effectBitonicSort2[i].KeepAliveBy(this);

                currentDepth /= 2;
            }
            effectMeshBitonicSort2 = new EffectMesh[bitonicSort2Passes.Length];
            for (int i = 0; i < effectMeshBitonicSort2.Length; i++)
                effectMeshBitonicSort2[i] = new EffectMesh(effectBitonicSort2[i]);

            // Creates Effect for rendering
            EffectOld particleRenderEffect = this.EffectSystemOld.BuildEffect("ParticleRender")
                .Using(new StateShaderPlugin() { UseBlendState = true, UseDepthStencilState = true, RenderPass = renderPass })
                .Using(new BasicShaderPlugin(RenderShader)
                        {
                            RenderPass = renderPass,
                            Macros = { new ShaderMacro("PARTICLE_STRUCT", StructureName) }
                        });
            particleRenderEffect.KeepAliveBy(this);

            particleRenderEffect.Parameters.AddSources(this.Parameters);
            particleRenderEffect.Parameters.AddSources(MainPlugin.ViewParameters);
            particleRenderEffect.Parameters.Set(EffectPlugin.BlendStateKey, graphicsDeviceService.GraphicsDevice.BlendStates.AlphaBlend);
            particleRenderEffect.Parameters.Set(EffectPlugin.DepthStencilStateKey, MainTargetPlugin.DepthStencilState);
            particleRenderEffect.Parameters.Set(RenderTargetKeys.DepthStencilSource, MainTargetPlugin.DepthStencil.Texture);

            effectMeshRender = new EffectMesh(particleRenderEffect);

            effectMeshRender.Render += (context) =>
            {
                if (currentParticleCount > 0)
                {
                    context.GraphicsDevice.SetVertexArrayObject(null);
                    context.GraphicsDevice.SetViewport(MainTargetPlugin.Viewport);
                    //context.GraphicsDevice.SetRenderTargets(MainTargetPlugin.DepthStencil, 0, MainTargetPlugin.RenderTarget);
                    
                    context.GraphicsDevice.SetRenderTargets((MainTargetPlugin.DepthStencilReadOnly != null) ? MainTargetPlugin.DepthStencilReadOnly : MainTargetPlugin.DepthStencil, RenderTarget);

                    // TODO HANDLE dynamic count
                    //context.GraphicsDevice.Draw(PrimitiveType.PointList, CapacityCount);
                    context.GraphicsDevice.Draw(PrimitiveType.PointList, currentParticleCount);
                }
                //context.GraphicsDevice.SetRenderTargets(null, 0, new ITexture2D[] { null } );
            };

            if (OfflineCompilation)
                return;

            // Allocate global buffers at register time
            // Buffers can also be reallocated at runtime
            OnCapacityCountChange();

            // Add our local meshes to render RenderContext.RenderPassEnumerators
            RenderSystem.RenderPassEnumerators.Add(meshesToRender);

            // Register update per frame
            RenderSystem.GlobalPass.StartPass += OnFrameUpdate;

            // Register sort pass
            sortPass.EndPass.Set = ComputeBitonicSort;
        }
Exemplo n.º 35
0
        public void CmdDraw()
        {
            var renderPassCreateInfo = new RenderPassCreateInfo(
                new[] { new SubpassDescription(new[] { new AttachmentReference(0, ImageLayout.ColorAttachmentOptimal) }) },
                new[]
            {
                new AttachmentDescription
                {
                    Format      = Format.B8G8R8A8UNorm,
                    Samples     = SampleCounts.Count1,
                    FinalLayout = ImageLayout.ColorAttachmentOptimal,
                    LoadOp      = AttachmentLoadOp.DontCare
                }
            });
            var imageCreateInfo = new ImageCreateInfo
            {
                Usage       = ImageUsages.ColorAttachment,
                Format      = Format.B8G8R8A8UNorm,
                Extent      = new Extent3D(2, 2, 1),
                ImageType   = ImageType.Image2D,
                MipLevels   = 1,
                ArrayLayers = 1,
                Samples     = SampleCounts.Count1
            };
            var imageViewCreateInfo = new ImageViewCreateInfo(
                Format.B8G8R8A8UNorm,
                new ImageSubresourceRange(ImageAspects.Color, 0, 1, 0, 1));

            using (ShaderModule vertexShader = Device.CreateShaderModule(new ShaderModuleCreateInfo(ReadAllBytes("Shader.vert.spv"))))
                using (ShaderModule fragmentShader = Device.CreateShaderModule(new ShaderModuleCreateInfo(ReadAllBytes("Shader.frag.spv"))))
                    using (PipelineLayout pipelineLayout = Device.CreatePipelineLayout())
                        using (RenderPass renderPass = Device.CreateRenderPass(renderPassCreateInfo))
                            using (Image image = Device.CreateImage(imageCreateInfo))
                            {
                                MemoryRequirements imageMemReq = image.GetMemoryRequirements();
                                int memTypeIndex = PhysicalDeviceMemoryProperties.MemoryTypes.IndexOf(imageMemReq.MemoryTypeBits, MemoryProperties.DeviceLocal);
                                using (DeviceMemory imageMemory = Device.AllocateMemory(new MemoryAllocateInfo(imageMemReq.Size, memTypeIndex)))
                                {
                                    image.BindMemory(imageMemory);
                                    using (ImageView imageView = image.CreateView(imageViewCreateInfo))
                                        using (Framebuffer framebuffer = renderPass.CreateFramebuffer(new FramebufferCreateInfo(new[] { imageView }, 2, 2)))
                                            using (Pipeline pipeline = Device.CreateGraphicsPipeline(new GraphicsPipelineCreateInfo(
                                                                                                         pipelineLayout,
                                                                                                         renderPass,
                                                                                                         0,
                                                                                                         new[]
                                            {
                                                new PipelineShaderStageCreateInfo(ShaderStages.Vertex, vertexShader, "main"),
                                                new PipelineShaderStageCreateInfo(ShaderStages.Fragment, fragmentShader, "main")
                                            },
                                                                                                         new PipelineInputAssemblyStateCreateInfo(),
                                                                                                         new PipelineVertexInputStateCreateInfo(),
                                                                                                         new PipelineRasterizationStateCreateInfo {
                                                RasterizerDiscardEnable = true, LineWidth = 1.0f
                                            })))
                                            {
                                                CommandBuffer.Begin();
                                                CommandBuffer.CmdBeginRenderPass(new RenderPassBeginInfo(framebuffer, new Rect2D(0, 0, 2, 2)));
                                                CommandBuffer.CmdBindPipeline(PipelineBindPoint.Graphics, pipeline);
                                                CommandBuffer.CmdDraw(3);
                                                CommandBuffer.CmdEndRenderPass();
                                                CommandBuffer.End();
                                            }
                                }
                            }
        }
Exemplo n.º 36
0
        public override void Unload()
        {
            GBufferPlugin.MainPlugin.RenderPass.RemovePass(debugRenderPass);
            debugRenderPass = null;

            base.Unload();
        }
Exemplo n.º 37
0
            public void Initialize(EngineContext engineContext)
            {
                var renderContext = engineContext.RenderContext;
                var rootRenderPass = renderContext.RootRenderPass;

                var linearColorPass = new RenderPass("LinearColor");
                var reinhardColorPass = new RenderPass("ReinhardColor");
                var yebisPass = new RenderPass("YebisColor");
                var filmicColorPass = new RenderPass("FilmicColor");
                var composeColorPass = new RenderPass("ComposeColor");

                rootRenderPass.AddPass(linearColorPass);
                rootRenderPass.AddPass(reinhardColorPass);
                rootRenderPass.AddPass(yebisPass);
                rootRenderPass.AddPass(filmicColorPass);
                rootRenderPass.AddPass(composeColorPass);

                LinearColorPlugin = new PostEffectPlugin("LinearColor") { RenderPass = linearColorPass };

                ReinhardColorPlugin = new PostEffectPlugin("ReinhardColor") { RenderPass = reinhardColorPass };

#if PARADOX_YEBIS
                YebisPlugin = new YebisPlugin("ReinhardColor") { RenderPass = yebisPass };
#endif

                FilmicColorPlugin = new PostEffectPlugin("FilmicColor") { RenderPass = filmicColorPass };

                MainPlugin = new PostEffectPlugin("MainColor") { RenderPass = composeColorPass };

                //MainDepthReadOnlyPlugin

                // YebisPlugin = new YebisPlugin() { RenderPass = yebisColorPass, MainDepthReadOnlyPlugin = null };

                //renderContext.Register(MainDepthReadOnlyPlugin);
                //renderContext.Register(SkyBoxPlugin);
                //renderContext.Register(PostEffectPlugin);

                //// Create and bind depth stencil buffer
                //renderContext.GraphicsResizeContext.SetupResize(
                //    (resizeContext) =>
                //    {
                //        MainDepthReadOnlyPlugin.DepthStencil = renderContext.GraphicsDevice.DepthStencilBuffer.New(DepthFormat.Depth32, renderContext.Width, renderContext.Height, true, "MainDepthBuffer");
                //        // Bind render target - comment when Yebis is off
                //        MainDepthReadOnlyPlugin.RenderTarget = renderContext.GraphicsDevice.RenderTarget2D.New(renderContext.Width, renderContext.Height, PixelFormat.HalfVector4, name: "MainRenderTarget");

                //        // Comment - when Yebis is on
                //        //MainDepthReadOnlyPlugin.RenderTarget = renderContext.GraphicsDevice.RenderTarget2D.New(renderContext.Width, renderContext.Height, PixelFormat.R8G8B8A8, name: "MainRenderTarget");
                //        //renderContext.GlobalPass.EndPass.AddFirst = threadContext => threadContext.GraphicsDevice.Copy(MainDepthReadOnlyPlugin.RenderTarget, engineContext.RenderContext.RenderTarget);
                //    });

                //// Yebis plugin must be initialized after creating MainDepthReadOnlyPlugin.RenderTarget
                //renderContext.Register(YebisPlugin);

                //YebisPlugin.ToneMap.Gamma = 1.0f;
                //YebisPlugin.ToneMap.Type = ToneMapType.Auto;
                //YebisPlugin.ToneMap.AutoExposure.MiddleGray = 0.25f;
                //YebisPlugin.ToneMap.AutoExposure.AdaptationSensitivity = 0.5f;
                //YebisPlugin.ToneMap.AutoExposure.AdaptationScale = 0.8f;
                //YebisPlugin.ToneMap.AutoExposure.AdaptationSpeedLimit = 4.0f;
                //YebisPlugin.ToneMap.AutoExposure.DarkAdaptationSensitivity = 0.9f;
                //YebisPlugin.ToneMap.AutoExposure.DarkAdaptationScale = 0.6f;
                //YebisPlugin.ToneMap.AutoExposure.DarkAdaptationSpeedLimit = 4.0f;
                //YebisPlugin.ToneMap.AutoExposure.LightDarkExposureBorder = 1.0f;

                //YebisPlugin.Glare.Enable = true;
                //YebisPlugin.Glare.RemapFactor = 1f;
                //YebisPlugin.Glare.Threshold = 0f;

                //YebisPlugin.Lens.Vignette.Enable = true;

                //YebisPlugin.ColorCorrection.ColorTemperature = 3500;
            }
Exemplo n.º 38
0
        void init_renderpass()
        {
            renderPass = new RenderPass(dev, NUM_SAMPLES);

            renderPass.AddAttachment(HDR_FORMAT, VkImageLayout.ShaderReadOnlyOptimal, NUM_SAMPLES);                                                                      //final outpout
            renderPass.AddAttachment(dev.GetSuitableDepthFormat(), VkImageLayout.DepthStencilAttachmentOptimal, NUM_SAMPLES);
            renderPass.AddAttachment(VkFormat.R8g8b8a8Unorm, VkImageLayout.ColorAttachmentOptimal, NUM_SAMPLES, VkAttachmentLoadOp.Clear, VkAttachmentStoreOp.DontCare); //GBuff0 (color + roughness) and final color before resolve
            renderPass.AddAttachment(VkFormat.R8g8b8a8Unorm, VkImageLayout.ColorAttachmentOptimal, NUM_SAMPLES, VkAttachmentLoadOp.Clear, VkAttachmentStoreOp.DontCare); //GBuff1 (emit + metal)
            renderPass.AddAttachment(MRT_FORMAT, VkImageLayout.ColorAttachmentOptimal, NUM_SAMPLES, VkAttachmentLoadOp.Clear, VkAttachmentStoreOp.DontCare);             //GBuff2 (normals + AO)
            renderPass.AddAttachment(MRT_FORMAT, VkImageLayout.ColorAttachmentOptimal, NUM_SAMPLES, VkAttachmentLoadOp.Clear, VkAttachmentStoreOp.DontCare);             //GBuff3 (Pos + depth)

            renderPass.ClearValues.Add(new VkClearValue {
                color = new VkClearColorValue(0.0f, 0.0f, 0.0f)
            });
            renderPass.ClearValues.Add(new VkClearValue {
                depthStencil = new VkClearDepthStencilValue(1.0f, 0)
            });
            renderPass.ClearValues.Add(new VkClearValue {
                color = new VkClearColorValue(0.0f, 0.0f, 0.0f)
            });
            renderPass.ClearValues.Add(new VkClearValue {
                color = new VkClearColorValue(0.0f, 0.0f, 0.0f)
            });
            renderPass.ClearValues.Add(new VkClearValue {
                color = new VkClearColorValue(0.0f, 0.0f, 0.0f)
            });
            renderPass.ClearValues.Add(new VkClearValue {
                color = new VkClearColorValue(0.0f, 0.0f, 0.0f)
            });

            SubPass[] subpass = { new SubPass(), new SubPass(), new SubPass() };
            //skybox
            subpass[SP_SKYBOX].AddColorReference(0, VkImageLayout.ColorAttachmentOptimal);
            //models
            subpass[SP_MODELS].AddColorReference(new VkAttachmentReference(2, VkImageLayout.ColorAttachmentOptimal),
                                                 new VkAttachmentReference(3, VkImageLayout.ColorAttachmentOptimal),
                                                 new VkAttachmentReference(4, VkImageLayout.ColorAttachmentOptimal),
                                                 new VkAttachmentReference(5, VkImageLayout.ColorAttachmentOptimal));
            subpass[SP_MODELS].SetDepthReference(1, VkImageLayout.DepthStencilAttachmentOptimal);
            subpass[SP_MODELS].AddPreservedReference(0);

            //compose
            subpass[SP_COMPOSE].AddColorReference(0, VkImageLayout.ColorAttachmentOptimal);
            subpass[SP_COMPOSE].AddInputReference(new VkAttachmentReference(2, VkImageLayout.ShaderReadOnlyOptimal),
                                                  new VkAttachmentReference(3, VkImageLayout.ShaderReadOnlyOptimal),
                                                  new VkAttachmentReference(4, VkImageLayout.ShaderReadOnlyOptimal),
                                                  new VkAttachmentReference(5, VkImageLayout.ShaderReadOnlyOptimal));
            //tone mapping
            //subpass[SP_TONE_MAPPING].AddColorReference ((NUM_SAMPLES == VkSampleCountFlags.SampleCount1) ? 0u : 2u, VkImageLayout.ColorAttachmentOptimal);
            //subpass[SP_TONE_MAPPING].AddInputReference (new VkAttachmentReference (6, VkImageLayout.ShaderReadOnlyOptimal));
            //if (NUM_SAMPLES != VkSampleCountFlags.SampleCount1)
            //subpass[SP_TONE_MAPPING].AddResolveReference (0, VkImageLayout.ColorAttachmentOptimal);

            renderPass.AddSubpass(subpass);

            renderPass.AddDependency(Vk.SubpassExternal, SP_SKYBOX,
                                     VkPipelineStageFlags.BottomOfPipe, VkPipelineStageFlags.ColorAttachmentOutput,
                                     VkAccessFlags.MemoryRead, VkAccessFlags.ColorAttachmentRead | VkAccessFlags.ColorAttachmentWrite);
            renderPass.AddDependency(SP_SKYBOX, SP_MODELS,
                                     VkPipelineStageFlags.ColorAttachmentOutput, VkPipelineStageFlags.FragmentShader,
                                     VkAccessFlags.ColorAttachmentWrite, VkAccessFlags.ShaderRead);
            renderPass.AddDependency(SP_MODELS, SP_COMPOSE,
                                     VkPipelineStageFlags.ColorAttachmentOutput, VkPipelineStageFlags.FragmentShader,
                                     VkAccessFlags.ColorAttachmentWrite, VkAccessFlags.ShaderRead);
            //renderPass.AddDependency (SP_COMPOSE, Vk.SubpassExternal,
            //VkPipelineStageFlags.ColorAttachmentOutput, VkPipelineStageFlags.Transfer,
            //VkAccessFlags.ColorAttachmentWrite, VkAccessFlags.TransferRead);
            //renderPass.AddDependency (SP_COMPOSE, SP_COMPOSE,
            //VkPipelineStageFlags.Transfer, VkPipelineStageFlags.ComputeShader,
            //VkAccessFlags.TransferWrite, VkAccessFlags.ShaderRead);
            //renderPass.AddDependency (Vk.SubpassExternal, SP_TONE_MAPPING,
            //	VkPipelineStageFlags.ComputeShader, VkPipelineStageFlags.FragmentShader,
            //	VkAccessFlags.ShaderWrite, VkAccessFlags.ShaderRead);
            //renderPass.AddDependency (SP_SKYBOX, SP_TONE_MAPPING,
            //VkPipelineStageFlags.ColorAttachmentOutput, VkPipelineStageFlags.FragmentShader,
            //VkAccessFlags.ColorAttachmentWrite, VkAccessFlags.ShaderRead);
            renderPass.AddDependency(SP_COMPOSE, Vk.SubpassExternal,
                                     VkPipelineStageFlags.ColorAttachmentOutput, VkPipelineStageFlags.Transfer,
                                     VkAccessFlags.ColorAttachmentRead | VkAccessFlags.ColorAttachmentWrite, VkAccessFlags.TransferRead);
            //renderPass.AddDependency (SP_TONE_MAPPING, Vk.SubpassExternal,
            //VkPipelineStageFlags.ColorAttachmentOutput, VkPipelineStageFlags.BottomOfPipe,
            //VkAccessFlags.ColorAttachmentRead | VkAccessFlags.ColorAttachmentWrite, VkAccessFlags.MemoryRead);
        }
Exemplo n.º 39
0
        void RenderPrim(RenderPrimitive mesh, RenderPass pass, int primNr)
        {
            if (!AvatarRenderingEnabled && mesh.Attached) return;

            Primitive prim = mesh.Prim;

            // Individual prim matrix
            GL.PushMatrix();

            // Prim roation and position and scale
            GL.MultMatrix(Math3D.CreateSRTMatrix(prim.Scale, mesh.RenderRotation, mesh.RenderPosition));

            // Do we have animated texture on this face
            bool animatedTexture = false;

            // Initialise flags tracking what type of faces this prim has
            if (pass == RenderPass.Simple)
            {
                mesh.HasSimpleFaces = false;
            }
            else if (pass == RenderPass.Alpha)
            {
                mesh.HasAlphaFaces = false;
            }

            // Draw the prim faces
            for (int j = 0; j < mesh.Faces.Count; j++)
            {
                Primitive.TextureEntryFace teFace = mesh.Prim.Textures.GetFace((uint)j);
                Face face = mesh.Faces[j];
                FaceData data = (FaceData)mesh.Faces[j].UserData;

                if (data == null)
                    continue;

                if (teFace == null)
                    continue;

                // Don't render transparent faces
                if (data.TextureInfo.FullAlpha || teFace.RGBA.A <= 0.01f) continue;

                bool switchedLightsOff = false;

                if (pass != RenderPass.Picking)
                {
                    bool belongToAlphaPass = (teFace.RGBA.A < 0.99f) || (data.TextureInfo.HasAlpha && !data.TextureInfo.IsMask);

                    if (belongToAlphaPass && pass != RenderPass.Alpha) continue;
                    if (!belongToAlphaPass && pass == RenderPass.Alpha) continue;

                    if (pass == RenderPass.Simple)
                    {
                        mesh.HasSimpleFaces = true;
                    }
                    else if (pass == RenderPass.Alpha)
                    {
                        mesh.HasAlphaFaces = true;
                    }

                    if (teFace.Fullbright)
                    {
                        GL.Disable(EnableCap.Lighting);
                        switchedLightsOff = true;
                    }

                    switch (teFace.Shiny)
                    {
                        case Shininess.High:
                            GL.Material(MaterialFace.Front, MaterialParameter.Shininess, 0.94f);
                            break;

                        case Shininess.Medium:
                            GL.Material(MaterialFace.Front, MaterialParameter.Shininess, 0.64f);
                            break;

                        case Shininess.Low:
                            GL.Material(MaterialFace.Front, MaterialParameter.Shininess, 0.24f);
                            break;


                        case Shininess.None:
                        default:
                            GL.Material(MaterialFace.Front, MaterialParameter.Shininess, 0f);
                            break;
                    }

                    var faceColor = new float[] { teFace.RGBA.R, teFace.RGBA.G, teFace.RGBA.B, teFace.RGBA.A };
                    GL.Color4(faceColor);

                    GL.Material(MaterialFace.Front, MaterialParameter.Specular, new float[] { 0.5f, 0.5f, 0.5f, 1f });

                    if (data.TextureInfo.TexturePointer == 0 && TexturesPtrMap.ContainsKey(teFace.TextureID))
                    {
                        data.TextureInfo = TexturesPtrMap[teFace.TextureID];
                    }

                    if (data.TextureInfo.TexturePointer == 0)
                    {
                        GL.Disable(EnableCap.Texture2D);
                        if (texturesRequestedThisFrame < 2 && !data.TextureInfo.FetchFailed)
                        {
                            texturesRequestedThisFrame++;

                            DownloadTexture(new TextureLoadItem()
                            {
                                Prim = prim,
                                TeFace = teFace,
                                Data = data
                            });
                        }
                    }
                    else
                    {
                        // Is this face using texture animation
                        if ((prim.TextureAnim.Flags & Primitive.TextureAnimMode.ANIM_ON) != 0
                            && (prim.TextureAnim.Face == j || prim.TextureAnim.Face == 255))
                        {
                            if (data.AnimInfo == null)
                            {
                                data.AnimInfo = new TextureAnimationInfo();
                            }
                            data.AnimInfo.PrimAnimInfo = prim.TextureAnim;
                            data.AnimInfo.Step(lastFrameTime);
                            animatedTexture = true;
                        }
                        else if (data.AnimInfo != null) // Face texture not animated. Do we have previous anim setting?
                        {
                            data.AnimInfo = null;
                        }

                        GL.Enable(EnableCap.Texture2D);
                        GL.BindTexture(TextureTarget.Texture2D, data.TextureInfo.TexturePointer);
                    }

                }
                else
                {
                    data.PickingID = primNr;
                    var primNrBytes = Utils.UInt16ToBytes((ushort)primNr);
                    var faceColor = new byte[] { primNrBytes[0], primNrBytes[1], (byte)j, 255 };
                    GL.Color4(faceColor);
                }

                if (!RenderSettings.UseVBO)
                {
                    Vertex[] verts = face.Vertices.ToArray();
                    ushort[] indices = face.Indices.ToArray();

                    unsafe
                    {
                        fixed (float* normalPtr = &verts[0].Normal.X)
                        fixed (float* texPtr = &verts[0].TexCoord.X)
                        {
                            GL.NormalPointer(NormalPointerType.Float, FaceData.VertexSize, (IntPtr)normalPtr);
                            GL.TexCoordPointer(2, TexCoordPointerType.Float, FaceData.VertexSize, (IntPtr)texPtr);
                            GL.VertexPointer(3, VertexPointerType.Float, FaceData.VertexSize, verts);
                            GL.DrawElements(BeginMode.Triangles, indices.Length, DrawElementsType.UnsignedShort, indices);
                        }
                    }
                }
                else
                {
                    data.CheckVBO(face);
                    GL.BindBuffer(BufferTarget.ArrayBuffer, data.VertexVBO);
                    GL.BindBuffer(BufferTarget.ElementArrayBuffer, data.IndexVBO);
                    GL.NormalPointer(NormalPointerType.Float, FaceData.VertexSize, (IntPtr)12);
                    GL.TexCoordPointer(2, TexCoordPointerType.Float, FaceData.VertexSize, (IntPtr)(24));
                    GL.VertexPointer(3, VertexPointerType.Float, FaceData.VertexSize, (IntPtr)(0));

                    GL.DrawElements(BeginMode.Triangles, face.Indices.Count, DrawElementsType.UnsignedShort, IntPtr.Zero);

                    GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
                    GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0);

                }

                if (switchedLightsOff)
                {
                    GL.Enable(EnableCap.Lighting);
                    switchedLightsOff = false;
                }
            }

            GL.BindTexture(TextureTarget.Texture2D, 0);
            ResetMaterial();

            // Reset texture coordinates if we modified them in texture animation
            if (animatedTexture)
            {
                GL.MatrixMode(MatrixMode.Texture);
                GL.LoadIdentity();
                GL.MatrixMode(MatrixMode.Modelview);
            }

            // Pop the prim matrix
            GL.PopMatrix();
        }
Exemplo n.º 40
0
        /// <summary>
        /// Render Primitive
        /// </summary>
        /// <param name="pass">Which pass are we currently in</param>
        /// <param name="pickingID">ID used to identify which object was picked</param>
        /// <param name="scene">Main scene renderer</param>
        /// <param name="time">Time it took to render the last frame</param>
        public override void Render(RenderPass pass, int pickingID, SceneWindow scene, float time)
        {
            if (!RenderSettings.AvatarRenderingEnabled && Attached) return;

            // Individual prim matrix
            GL.PushMatrix();

            // Prim roation and position and scale
            GL.MultMatrix(Math3D.CreateSRTMatrix(Prim.Scale, RenderRotation, RenderPosition));

            // Do we have animated texture on this face
            bool animatedTexture = false;

            // Initialise flags tracking what type of faces this prim has
            if (pass == RenderPass.Simple)
            {
                HasSimpleFaces = false;
            }
            else if (pass == RenderPass.Alpha)
            {
                HasAlphaFaces = false;
            }
            else if (pass == RenderPass.Invisible)
            {
                HasInvisibleFaces = false;
            }

            // Draw the prim faces
            for (int j = 0; j < Faces.Count; j++)
            {
                Primitive.TextureEntryFace teFace = Prim.Textures.GetFace((uint)j);
                Face face = Faces[j];
                FaceData data = (FaceData)face.UserData;

                if (data == null)
                    continue;

                if (teFace == null)
                    continue;

                // Don't render transparent faces
                Color4 RGBA = teFace.RGBA;

                if (data.TextureInfo.FullAlpha || RGBA.A <= 0.01f) continue;

                bool switchedLightsOff = false;

                if (pass == RenderPass.Picking)
                {
                    data.PickingID = pickingID;
                    var primNrBytes = Utils.UInt16ToBytes((ushort)pickingID);
                    var faceColor = new byte[] { primNrBytes[0], primNrBytes[1], (byte)j, 255 };
                    GL.Color4(faceColor);
                }
                else if (pass == RenderPass.Invisible)
                {
                    if (!data.TextureInfo.IsInvisible) continue;
                    HasInvisibleFaces = true;
                }
                else
                {
                    if (data.TextureInfo.IsInvisible) continue;
                    bool belongToAlphaPass = (RGBA.A < 0.99f) || (data.TextureInfo.HasAlpha && !data.TextureInfo.IsMask);

                    if (belongToAlphaPass && pass != RenderPass.Alpha) continue;
                    if (!belongToAlphaPass && pass == RenderPass.Alpha) continue;

                    if (pass == RenderPass.Simple)
                    {
                        HasSimpleFaces = true;
                    }
                    else if (pass == RenderPass.Alpha)
                    {
                        HasAlphaFaces = true;
                    }

                    if (teFace.Fullbright)
                    {
                        GL.Disable(EnableCap.Lighting);
                        switchedLightsOff = true;
                    }

                    float shiny = 0f;
                    switch (teFace.Shiny)
                    {
                        case Shininess.High:
                            shiny = 0.96f;
                            break;

                        case Shininess.Medium:
                            shiny = 0.64f;
                            break;

                        case Shininess.Low:
                            shiny = 0.24f;
                            break;
                    }

                    if (shiny > 0f)
                    {
                        scene.StartShiny();
                    }
                    GL.Material(MaterialFace.Front, MaterialParameter.Shininess, shiny);
                    var faceColor = new float[] { RGBA.R, RGBA.G, RGBA.B, RGBA.A };
                    GL.Color4(faceColor);

                    GL.Material(MaterialFace.Front, MaterialParameter.Specular, new float[] { 0.5f, 0.5f, 0.5f, 1f });

                    if (data.TextureInfo.TexturePointer == 0)
                    {
                        TextureInfo teInfo;
                        if (scene.TryGetTextureInfo(teFace.TextureID, out teInfo))
                        {
                            data.TextureInfo = teInfo;
                        }
                    }

                    if (data.TextureInfo.TexturePointer == 0)
                    {
                        GL.Disable(EnableCap.Texture2D);
                        if (!data.TextureInfo.FetchFailed)
                        {
                            scene.DownloadTexture(new TextureLoadItem()
                            {
                                Prim = this.Prim,
                                TeFace = teFace,
                                Data = data
                            }, false);
                        }
                    }
                    else
                    {
                        // Is this face using texture animation
                        if ((Prim.TextureAnim.Flags & Primitive.TextureAnimMode.ANIM_ON) != 0
                            && (Prim.TextureAnim.Face == j || Prim.TextureAnim.Face == 255))
                        {
                            if (data.AnimInfo == null)
                            {
                                data.AnimInfo = new TextureAnimationInfo();
                            }
                            data.AnimInfo.PrimAnimInfo = Prim.TextureAnim;
                            data.AnimInfo.Step(time);
                            animatedTexture = true;
                        }
                        else if (data.AnimInfo != null) // Face texture not animated. Do we have previous anim setting?
                        {
                            data.AnimInfo = null;
                        }

                        GL.Enable(EnableCap.Texture2D);
                        GL.BindTexture(TextureTarget.Texture2D, data.TextureInfo.TexturePointer);
                    }
                }

                if (!RenderSettings.UseVBO || data.VBOFailed)
                {
                    Vertex[] verts = face.Vertices.ToArray();
                    ushort[] indices = face.Indices.ToArray();

                    unsafe
                    {
                        fixed (float* normalPtr = &verts[0].Normal.X)
                        fixed (float* texPtr = &verts[0].TexCoord.X)
                        {
                            GL.NormalPointer(NormalPointerType.Float, FaceData.VertexSize, (IntPtr)normalPtr);
                            GL.TexCoordPointer(2, TexCoordPointerType.Float, FaceData.VertexSize, (IntPtr)texPtr);
                            GL.VertexPointer(3, VertexPointerType.Float, FaceData.VertexSize, verts);
                            GL.DrawElements(BeginMode.Triangles, indices.Length, DrawElementsType.UnsignedShort, indices);
                        }
                    }
                }
                else
                {
                    if (data.CheckVBO(face))
                    {
                        Compat.BindBuffer(BufferTarget.ArrayBuffer, data.VertexVBO);
                        Compat.BindBuffer(BufferTarget.ElementArrayBuffer, data.IndexVBO);
                        GL.NormalPointer(NormalPointerType.Float, FaceData.VertexSize, (IntPtr)12);
                        GL.TexCoordPointer(2, TexCoordPointerType.Float, FaceData.VertexSize, (IntPtr)(24));
                        GL.VertexPointer(3, VertexPointerType.Float, FaceData.VertexSize, (IntPtr)(0));

                        GL.DrawElements(BeginMode.Triangles, face.Indices.Count, DrawElementsType.UnsignedShort, IntPtr.Zero);
                    }
                    Compat.BindBuffer(BufferTarget.ArrayBuffer, 0);
                    Compat.BindBuffer(BufferTarget.ElementArrayBuffer, 0);

                }

                if (switchedLightsOff)
                {
                    GL.Enable(EnableCap.Lighting);
                    switchedLightsOff = false;
                }

            }

            GL.BindTexture(TextureTarget.Texture2D, 0);
            RHelp.ResetMaterial();

            // Reset texture coordinates if we modified them in texture animation
            if (animatedTexture)
            {
                GL.MatrixMode(MatrixMode.Texture);
                GL.LoadIdentity();
                GL.MatrixMode(MatrixMode.Modelview);
            }

            // Pop the prim matrix
            GL.PopMatrix();

            base.Render(pass, pickingID, scene, time);
        }
Exemplo n.º 41
0
 /// <summary>
 /// Render scene object
 /// </summary>
 /// <param name="pass">Which pass are we currently in</param>
 /// <param name="pickingID">ID used to identify which object was picked</param>
 /// <param name="scene">Main scene renderer</param>
 /// <param name="time">Time it took to render the last frame</param>
 public virtual void Render(RenderPass pass, int pickingID, SceneWindow scene, float time)
 {
 }
Exemplo n.º 42
0
 internal static extern void Internal_ExecuteDrawCalls(IntPtr obj, IntPtr task, IntPtr output, RenderTask.DrawCall[] drawCalls, RenderPass pass);
Exemplo n.º 43
0
        public override void Initialize()
        {
            base.Initialize();

            graphicsDeviceService = Services.GetSafeServiceAs<IGraphicsDeviceService>();

            // Create and register render passes
            updatePasses = new RenderPass("Update");
            copyPass = new RenderPass("Copy");
            sortPass = new RenderPass("Sort");

            bitonicSort1Pass1 = new RenderPass("BitonicSort1Pass1");
            bitonicSort1Pass2 = new RenderPass("BitonicSort1Pass2");
            bitonicSort2Passes = new RenderPass[(int)Math.Log(MaximumDepthLevel, 2) - 1];
            effectBitonicSort2 = new EffectOld[bitonicSort2Passes.Length];

            renderPass = new RenderPass("Render");
        }
Exemplo n.º 44
0
        public override void Bind(Device device, RenderPass renderPass, CommandBuffer commandBuffer, Extent2D targetExtent)
        {
            this.aspectRatio = (float)targetExtent.Width / (float)targetExtent.Height;

            this.pipeline = device.CreateGraphicsPipelines(null, new[]
            {
                new GraphicsPipelineCreateInfo
                {
                    Layout           = this.pipelineLayout,
                    RenderPass       = renderPass,
                    Subpass          = 0,
                    VertexInputState = new PipelineVertexInputStateCreateInfo()
                    {
                        VertexBindingDescriptions   = new [] { Vertex.GetBindingDescription() },
                        VertexAttributeDescriptions = Vertex.GetAttributeDescriptions()
                    },
                    InputAssemblyState = new PipelineInputAssemblyStateCreateInfo
                    {
                        PrimitiveRestartEnable = false,
                        Topology = PrimitiveTopology.TriangleList
                    },
                    ViewportState = new PipelineViewportStateCreateInfo
                    {
                        Viewports = new[]
                        {
                            new Viewport
                            {
                                X        = 0f,
                                Y        = 0f,
                                Width    = targetExtent.Width,
                                Height   = targetExtent.Height,
                                MaxDepth = 1,
                                MinDepth = 0
                            }
                        },
                        Scissors = new[]
                        {
                            new Rect2D
                            {
                                Offset = new Offset2D(),
                                Extent = targetExtent
                            }
                        }
                    },
                    RasterizationState = new PipelineRasterizationStateCreateInfo
                    {
                        DepthClampEnable        = false,
                        RasterizerDiscardEnable = false,
                        PolygonMode             = PolygonMode.Fill,
                        LineWidth       = 1,
                        CullMode        = CullModeFlags.Back,
                        FrontFace       = FrontFace.CounterClockwise,
                        DepthBiasEnable = false
                    },
                    MultisampleState = new PipelineMultisampleStateCreateInfo
                    {
                        SampleShadingEnable  = false,
                        RasterizationSamples = SampleCountFlags.SampleCount1,
                        MinSampleShading     = 1
                    },
                    ColorBlendState = new PipelineColorBlendStateCreateInfo
                    {
                        Attachments = new[]
                        {
                            new PipelineColorBlendAttachmentState
                            {
                                ColorWriteMask = ColorComponentFlags.R
                                                 | ColorComponentFlags.G
                                                 | ColorComponentFlags.B
                                                 | ColorComponentFlags.A,
                                BlendEnable                 = false,
                                SourceColorBlendFactor      = BlendFactor.One,
                                DestinationColorBlendFactor = BlendFactor.Zero,
                                ColorBlendOp                = BlendOp.Add,
                                SourceAlphaBlendFactor      = BlendFactor.One,
                                DestinationAlphaBlendFactor = BlendFactor.Zero,
                                AlphaBlendOp                = BlendOp.Add
                            }
                        },
                        LogicOpEnable  = false,
                        LogicOp        = LogicOp.Copy,
                        BlendConstants = new float[] { 0, 0, 0, 0 }
                    },
                    DepthStencilState = new PipelineDepthStencilStateCreateInfo
                    {
                        DepthTestEnable       = true,
                        DepthWriteEnable      = true,
                        DepthCompareOp        = CompareOp.Less,
                        DepthBoundsTestEnable = false,
                        MinDepthBounds        = 0,
                        MaxDepthBounds        = 1,
                        StencilTestEnable     = false
                    },
                    Stages = new[]
                    {
                        new PipelineShaderStageCreateInfo
                        {
                            Stage  = ShaderStageFlags.Vertex,
                            Module = this.vertexShader,
                            Name   = "main"
                        },
                        new PipelineShaderStageCreateInfo
                        {
                            Stage  = ShaderStageFlags.Fragment,
                            Module = this.fragmentShader,
                            Name   = "main"
                        }
                    }
                }
            }).Single();

            commandBuffer.BindPipeline(PipelineBindPoint.Graphics, this.pipeline);

            commandBuffer.BindVertexBuffers(0, this.vertexBuffer.Buffer, (DeviceSize)0);

            commandBuffer.BindIndexBuffer(this.indexBuffer.Buffer, 0, IndexType.UInt32);

            commandBuffer.BindDescriptorSets(PipelineBindPoint.Graphics, pipelineLayout, 0, descriptorSet, null);

            commandBuffer.DrawIndexed((uint)indexCount, 1, 0, 0, 0);
        }
Exemplo n.º 45
0
        private void RenderObjects(RenderPass pass)
        {
            lock (Prims)
            {
                int primNr = 0;
                foreach (FacetedMesh mesh in Prims.Values)
                {
                    primNr++;
                    Primitive prim = mesh.Prim;
                    // Individual prim matrix
                    GL.PushMatrix();

                    if (prim.ParentID == RootPrimLocalID)
                    {
                        FacetedMesh parent = null;
                        if (Prims.TryGetValue(prim.ParentID, out parent))
                        {
                            // Apply prim translation and rotation relative to the root prim
                            GL.MultMatrix(Math3D.CreateRotationMatrix(parent.Prim.Rotation));
                            //GL.MultMatrixf(Math3D.CreateTranslationMatrix(parent.Prim.Position));
                        }

                        // Prim roation relative to root
                        GL.MultMatrix(Math3D.CreateTranslationMatrix(prim.Position));
                    }

                    // Prim roation
                    GL.MultMatrix(Math3D.CreateRotationMatrix(prim.Rotation));

                    // Prim scaling
                    GL.Scale(prim.Scale.X, prim.Scale.Y, prim.Scale.Z);

                    // Draw the prim faces
                    for (int j = 0; j < mesh.Faces.Count; j++)
                    {
                        Primitive.TextureEntryFace teFace = mesh.Prim.Textures.FaceTextures[j];
                        Face face = mesh.Faces[j];
                        FaceData data = (FaceData)face.UserData;

                        if (teFace == null)
                            teFace = mesh.Prim.Textures.DefaultTexture;

                        if (pass == RenderPass.Picking)
                        {
                            data.PickingID = primNr;
                            var primNrBytes = Utils.Int16ToBytes((short)primNr);
                            var faceColor = new byte[] { primNrBytes[0], primNrBytes[1], (byte)j, 255 };

                            GL.Color4(faceColor);
                        }
                        else
                        {
                            bool belongToAlphaPass = (teFace.RGBA.A < 0.99) || data.TextureInfo.HasAlpha;

                            if (belongToAlphaPass && pass != RenderPass.Alpha) continue;
                            if (!belongToAlphaPass && pass == RenderPass.Alpha) continue;

                            // Don't render transparent faces
                            if (teFace.RGBA.A <= 0.01f) continue;

                            switch (teFace.Shiny)
                            {
                                case Shininess.High:
                                    GL.Material(MaterialFace.Front, MaterialParameter.Shininess, 94f);
                                    break;

                                case Shininess.Medium:
                                    GL.Material(MaterialFace.Front, MaterialParameter.Shininess, 64f);
                                    break;

                                case Shininess.Low:
                                    GL.Material(MaterialFace.Front, MaterialParameter.Shininess, 24f);
                                    break;

                                case Shininess.None:
                                default:
                                    GL.Material(MaterialFace.Front, MaterialParameter.Shininess, 0f);
                                    break;
                            }

                            var faceColor = new float[] { teFace.RGBA.R, teFace.RGBA.G, teFace.RGBA.B, teFace.RGBA.A };

                            GL.Color4(faceColor);
                            GL.Material(MaterialFace.Front, MaterialParameter.AmbientAndDiffuse, faceColor);
                            GL.Material(MaterialFace.Front, MaterialParameter.Specular, faceColor);

                            if (data.TextureInfo.TexturePointer != 0)
                            {
                                GL.Enable(EnableCap.Texture2D);
                            }
                            else
                            {
                                GL.Disable(EnableCap.Texture2D);
                            }

                            // Bind the texture
                            GL.BindTexture(TextureTarget.Texture2D, data.TextureInfo.TexturePointer);
                        }

                        GL.TexCoordPointer(2, TexCoordPointerType.Float, 0, data.TexCoords);
                        GL.VertexPointer(3, VertexPointerType.Float, 0, data.Vertices);
                        GL.NormalPointer(NormalPointerType.Float, 0, data.Normals);
                        GL.DrawElements(BeginMode.Triangles, data.Indices.Length, DrawElementsType.UnsignedShort, data.Indices);

                    }

                    // Pop the prim matrix
                    GL.PopMatrix();
                }
            }
        }
Exemplo n.º 46
0
        void init()
        {
            renderPass = new RenderPass(dev);
            renderPass.AddAttachment(swapChain.ColorFormat, VkImageLayout.ColorAttachmentOptimal, VkSampleCountFlags.SampleCount1);
            renderPass.AddAttachment(dev.GetSuitableDepthFormat(), VkImageLayout.DepthStencilAttachmentOptimal, samples);
            renderPass.AddAttachment(VkFormat.R8g8b8a8Unorm, VkImageLayout.ColorAttachmentOptimal);
            renderPass.AddAttachment(VkFormat.R8g8b8a8Unorm, VkImageLayout.ColorAttachmentOptimal);
            renderPass.AddAttachment(VkFormat.R16g16b16a16Sfloat, VkImageLayout.ColorAttachmentOptimal);
            renderPass.AddAttachment(VkFormat.R16g16b16a16Sfloat, VkImageLayout.ColorAttachmentOptimal);

            renderPass.ClearValues.Add(new VkClearValue {
                color = new VkClearColorValue(0.0f, 0.0f, 0.0f)
            });
            renderPass.ClearValues.Add(new VkClearValue {
                depthStencil = new VkClearDepthStencilValue(1.0f, 0)
            });
            renderPass.ClearValues.Add(new VkClearValue {
                color = new VkClearColorValue(0.0f, 0.0f, 0.0f)
            });
            renderPass.ClearValues.Add(new VkClearValue {
                color = new VkClearColorValue(0.0f, 0.0f, 0.0f)
            });
            renderPass.ClearValues.Add(new VkClearValue {
                color = new VkClearColorValue(0.0f, 0.0f, 0.0f)
            });
            renderPass.ClearValues.Add(new VkClearValue {
                color = new VkClearColorValue(0.0f, 0.0f, 0.0f)
            });

            SubPass[] subpass = { new SubPass(), new SubPass() };
            subpass[0].AddColorReference(new VkAttachmentReference(2, VkImageLayout.ColorAttachmentOptimal),
                                         new VkAttachmentReference(3, VkImageLayout.ColorAttachmentOptimal),
                                         new VkAttachmentReference(4, VkImageLayout.ColorAttachmentOptimal),
                                         new VkAttachmentReference(5, VkImageLayout.ColorAttachmentOptimal));
            subpass[0].SetDepthReference(1, VkImageLayout.DepthStencilAttachmentOptimal);

            subpass[1].AddColorReference(0, VkImageLayout.ColorAttachmentOptimal);
            subpass[1].AddInputReference(new VkAttachmentReference(2, VkImageLayout.ShaderReadOnlyOptimal),
                                         new VkAttachmentReference(3, VkImageLayout.ShaderReadOnlyOptimal),
                                         new VkAttachmentReference(4, VkImageLayout.ShaderReadOnlyOptimal),
                                         new VkAttachmentReference(5, VkImageLayout.ShaderReadOnlyOptimal));
            renderPass.AddSubpass(subpass);

            renderPass.AddDependency(Vk.SubpassExternal, 0,
                                     VkPipelineStageFlags.BottomOfPipe, VkPipelineStageFlags.ColorAttachmentOutput,
                                     VkAccessFlags.MemoryRead, VkAccessFlags.ColorAttachmentRead | VkAccessFlags.ColorAttachmentWrite);
            renderPass.AddDependency(0, 1,
                                     VkPipelineStageFlags.ColorAttachmentOutput, VkPipelineStageFlags.FragmentShader,
                                     VkAccessFlags.ColorAttachmentWrite, VkAccessFlags.ShaderRead);
            renderPass.AddDependency(1, Vk.SubpassExternal,
                                     VkPipelineStageFlags.ColorAttachmentOutput, VkPipelineStageFlags.BottomOfPipe,
                                     VkAccessFlags.ColorAttachmentRead | VkAccessFlags.ColorAttachmentWrite, VkAccessFlags.MemoryRead);


            descriptorPool = new DescriptorPool(dev, 3,
                                                new VkDescriptorPoolSize(VkDescriptorType.UniformBuffer, 2),
                                                new VkDescriptorPoolSize(VkDescriptorType.CombinedImageSampler, 3),
                                                new VkDescriptorPoolSize(VkDescriptorType.InputAttachment, 4)
                                                );

            descLayoutMain = new DescriptorSetLayout(dev,
                                                     new VkDescriptorSetLayoutBinding(0, VkShaderStageFlags.Vertex | VkShaderStageFlags.Fragment, VkDescriptorType.UniformBuffer),
                                                     new VkDescriptorSetLayoutBinding(1, VkShaderStageFlags.Fragment, VkDescriptorType.CombinedImageSampler),
                                                     new VkDescriptorSetLayoutBinding(2, VkShaderStageFlags.Fragment, VkDescriptorType.CombinedImageSampler),
                                                     new VkDescriptorSetLayoutBinding(3, VkShaderStageFlags.Fragment, VkDescriptorType.CombinedImageSampler));

            descLayoutModelTextures = new DescriptorSetLayout(dev,
                                                              new VkDescriptorSetLayoutBinding(0, VkShaderStageFlags.Fragment, VkDescriptorType.CombinedImageSampler),
                                                              new VkDescriptorSetLayoutBinding(1, VkShaderStageFlags.Fragment, VkDescriptorType.CombinedImageSampler),
                                                              new VkDescriptorSetLayoutBinding(2, VkShaderStageFlags.Fragment, VkDescriptorType.CombinedImageSampler),
                                                              new VkDescriptorSetLayoutBinding(3, VkShaderStageFlags.Fragment, VkDescriptorType.CombinedImageSampler),
                                                              new VkDescriptorSetLayoutBinding(4, VkShaderStageFlags.Fragment, VkDescriptorType.CombinedImageSampler)
                                                              );

            descLayoutGBuff = new DescriptorSetLayout(dev,
                                                      new VkDescriptorSetLayoutBinding(0, VkShaderStageFlags.Fragment, VkDescriptorType.InputAttachment),
                                                      new VkDescriptorSetLayoutBinding(1, VkShaderStageFlags.Fragment, VkDescriptorType.InputAttachment),
                                                      new VkDescriptorSetLayoutBinding(2, VkShaderStageFlags.Fragment, VkDescriptorType.InputAttachment),
                                                      new VkDescriptorSetLayoutBinding(3, VkShaderStageFlags.Fragment, VkDescriptorType.InputAttachment));

            dsMain  = descriptorPool.Allocate(descLayoutMain);
            dsGBuff = descriptorPool.Allocate(descLayoutGBuff);

            GraphicPipelineConfig cfg = GraphicPipelineConfig.CreateDefault(VkPrimitiveTopology.TriangleList, samples);

            cfg.Layout = new PipelineLayout(dev, descLayoutMain, descLayoutModelTextures, descLayoutGBuff);
            cfg.Layout.AddPushConstants(
                new VkPushConstantRange(VkShaderStageFlags.Vertex, (uint)Marshal.SizeOf <Matrix4x4> ()),
                new VkPushConstantRange(VkShaderStageFlags.Fragment, sizeof(int), 64)
                );
            cfg.RenderPass = renderPass;
            cfg.blendAttachments.Add(new VkPipelineColorBlendAttachmentState(false));
            cfg.blendAttachments.Add(new VkPipelineColorBlendAttachmentState(false));
            cfg.blendAttachments.Add(new VkPipelineColorBlendAttachmentState(false));

            cfg.AddVertexBinding <Model.Vertex> (0);
            cfg.SetVertexAttributes(0, VkFormat.R32g32b32Sfloat, VkFormat.R32g32b32Sfloat, VkFormat.R32g32Sfloat);
            cfg.AddShader(VkShaderStageFlags.Vertex, "shaders/pbrtest.vert.spv");
            cfg.AddShader(VkShaderStageFlags.Fragment, "shaders/GBuffPbr.frag.spv");

            gBuffPipeline = new GraphicPipeline(cfg);
            cfg.blendAttachments.Clear();
            cfg.blendAttachments.Add(new VkPipelineColorBlendAttachmentState(false));
            cfg.ResetShadersAndVerticesInfos();
            cfg.SubpassIndex = 1;
            cfg.Layout       = gBuffPipeline.Layout;
            cfg.depthStencilState.depthTestEnable  = false;
            cfg.depthStencilState.depthWriteEnable = false;
            cfg.AddShader(VkShaderStageFlags.Vertex, "shaders/FullScreenQuad.vert.spv");
            cfg.AddShader(VkShaderStageFlags.Fragment, "shaders/pbrtest.frag.spv");
            composePipeline = new GraphicPipeline(cfg);

            envCube = new EnvironmentCube(presentQueue, renderPass);

            uboMats = new HostBuffer(dev, VkBufferUsageFlags.UniformBuffer, (ulong)Marshal.SizeOf <Matrices> () * 2);
            uboMats.Map();             //permanent map

            DescriptorSetWrites uboUpdate = new DescriptorSetWrites(descLayoutMain);

            uboUpdate.Write(dev, dsMain, uboMats.Descriptor,
                            envCube.lutBrdf.Descriptor,
                            envCube.irradianceCube.Descriptor,
                            envCube.prefilterCube.Descriptor);
            uboMats.Descriptor.offset = (ulong)Marshal.SizeOf <Matrices> ();
            envCube.WriteDesc(uboMats.Descriptor);
#if DEBUG
            debugDraw = new DebugDrawPipeline(dev, descLayoutMain, swapChain.ColorFormat);
            debugDraw.AddLine(Vector3.Zero, new Vector3(matrices.lightPos.X, matrices.lightPos.Y, matrices.lightPos.Z) * 3, 1, 1, 1);
            debugDraw.AddLine(Vector3.Zero, Vector3.UnitX, 1, 0, 0);
            debugDraw.AddLine(Vector3.Zero, Vector3.UnitY, 0, 1, 0);
            debugDraw.AddLine(Vector3.Zero, Vector3.UnitZ, 0, 0, 1);
#endif


            model = new Model(presentQueue, "../data/models/DamagedHelmet/glTF/DamagedHelmet.gltf");
            //model = new Model (presentQueue, "../data/models/chess.gltf");
            //model = new Model (presentQueue, "../data/models/Sponza/glTF/Sponza.gltf");
            //model = new Model (dev, presentQueue, "../data/models/icosphere.gltf");
            //model = new Model (dev, presentQueue, cmdPool, "../data/models/cube.gltf");
            model.WriteMaterialsDescriptorSets(descLayoutModelTextures,
                                               VK.AttachmentType.Color,
                                               VK.AttachmentType.Normal,
                                               VK.AttachmentType.AmbientOcclusion,
                                               VK.AttachmentType.PhysicalProps,
                                               VK.AttachmentType.Emissive);
        }
Exemplo n.º 47
0
        private void CreatePrePassMesh(RenderPass renderPass, bool debug)
        {
            var lightDeferredEffect = lightDeferredEffects[debug ? 1 : 0];

            Tiles = new List<LightingPrepassShaderPlugin.LightData>[TileCountX * TileCountY];
            for (int i = 0; i < Tiles.Length; ++i)
            {
                Tiles[i] = new List<LightingPrepassShaderPlugin.LightData>();
            }

            renderPass.StartPass.AddLast = (threadContext) =>
            {
                // TODO THIS IS NOT ACCURATE TO TAKE THE CURRENT BACKBUFFER
                var mainBackBuffer = graphicsDeviceService.GraphicsDevice.BackBuffer;
                threadContext.GraphicsDevice.SetViewport(new Viewport(0, 0, mainBackBuffer.Width, mainBackBuffer.Height));
                if (threadContext.FirstContext)
                {
                    if (debug)
                    {
                        threadContext.GraphicsDevice.SetRenderTarget(GBufferPlugin.MainTargetPlugin.RenderTarget);
                    }
                    else
                    {
                        threadContext.GraphicsDevice.Clear(LightTexture, new Color(0.0f, 0.0f, 0.0f, 0.0f));
                        threadContext.GraphicsDevice.SetRenderTarget(LightTexture);
                    }
                }

                for (int i = 0; i < Tiles.Length; ++i)
                    Tiles[i].Clear();

                var lights = Lights;
                var lightAttenuationCutoff = 0.1f;

                Matrix viewMatrix;
                var mainParameters = GBufferPlugin.MainPlugin.ViewParameters;
                mainParameters.Get(TransformationKeys.View, out viewMatrix);
                Matrix projMatrix;
                mainParameters.Get(TransformationKeys.Projection, out projMatrix);

                for (int index = 0; index < lights.Meshes.Count; index++)
                {
                    LightingPrepassShaderPlugin.LightData lightData;

                    var lightMesh = lights.Meshes[index];
                    Vector3 lightPos;
                    lightMesh.Parameters.TryGet(LightKeys.LightPosition, out lightPos);
                    Vector3.TransformCoordinate(ref lightPos, ref viewMatrix, out lightData.LightPosVS);
                    lightMesh.Parameters.TryGet(LightKeys.LightColor, out lightData.DiffuseColor);
                    lightMesh.Parameters.TryGet(LightKeys.LightIntensity, out lightData.LightIntensity);
                    lightMesh.Parameters.TryGet(LightKeys.LightRadius, out lightData.LightRadius);

                    // ------------------------------------------------------------------------------------------
                    // TEMPORARY FIX FOR DEFERRED LIGHTS
                    // ------------------------------------------------------------------------------------------
                    //lightData2[index].DiffuseColor.Pow(1 / 4.0f);
                    //lightData2[index].LightIntensity = (float)Math.Pow(lightData2[index].LightIntensity, 1.0f / 2.2f);
                    // ------------------------------------------------------------------------------------------

                    // Linearize color
                    lightData.DiffuseColor.Pow(Color.DefaultGamma);
                    lightData.LightIntensity = (float)Math.Pow(lightData.LightIntensity, Color.DefaultGamma);

                    float lightDistanceMax = CalculateMaxDistance(lightData.LightIntensity, lightData.LightRadius, lightAttenuationCutoff);
                    var clipRegion = ComputeClipRegion(lightData.LightPosVS, lightDistanceMax, ref projMatrix);

                    var tileStartX = (int)((clipRegion.X * 0.5f + 0.5f) * TileCountX);
                    var tileEndX = (int)((clipRegion.Z * 0.5f + 0.5f) * TileCountX);
                    var tileStartY = (int)((clipRegion.Y * 0.5f + 0.5f) * TileCountY);
                    var tileEndY = (int)((clipRegion.W * 0.5f + 0.5f) * TileCountY);

                    // Check if this light is really visible (not behind us)
                    if (lightData.LightPosVS.Z + lightDistanceMax < 0.0f)
                        continue;

                    for (int y = tileStartY; y <= tileEndY; ++y)
                    {
                        if (y < 0 || y >= TileCountY)
                            continue;
                        for (int x = tileStartX; x <= tileEndX; ++x)
                        {
                            if (x < 0 || x >= TileCountX)
                                continue;
                            Tiles[y * TileCountX + x].Add(lightData);
                        }
                    }
                }
            };

            var lightDeferredMesh = new EffectMesh(lightDeferredEffect).KeepAliveBy(ActiveObjects);
            RenderSystem.GlobalMeshes.AddMesh(lightDeferredMesh);

            renderPass.EndPass.AddLast = (context) =>
                {
                    // Clear thread context overridden variables.
                    context.Parameters.Reset(LightingPrepassShaderPlugin.LightCount);
                    context.Parameters.Reset(LightingPrepassShaderPlugin.LightInfos);
                    context.Parameters.Reset(LightingPrepassShaderPlugin.TileIndex);
                    context.Parameters.Reset(TransformationKeys.Projection);
                    context.Parameters.Reset(RenderTargetKeys.DepthStencilSource);
                };

            var tileRenderPasses = new RenderPass[TileCountX * TileCountY];
            for (int i = 0; i < tileRenderPasses.Length; ++i)
            {
                int tileIndex = i;
                tileRenderPasses[i] = new RenderPass("Lighting Tile");
                tileRenderPasses[i].StartPass.AddLast = (context) => { context.Parameters.Set(LightingPrepassShaderPlugin.TileIndex, tileIndex); };
                throw new NotImplementedException();
                //tileRenderPasses[i].Meshes.Add(lightDeferredMesh);
            }

            throw new NotImplementedException();
            //renderPass.UpdatePasses += (RenderPass currentRenderPass, ref FastList<RenderPass> currentPasses) =>
            //    {
            //        lightDeferredEffect.Passes[0].Passes.Clear();
            //        lightDeferredEffect.Passes[0].Passes.AddRange(tileRenderPasses);
            //    };
        }
Exemplo n.º 48
0
 public virtual void AcceptPass(RenderPass pass)
 {
     pass.Visit(this);
 }
Exemplo n.º 49
0
        private void CreateRenderPass()
        {
            var colorAttachmentReference = new AttachmentReference { Attachment = 0, Layout = ImageLayout.ColorAttachmentOptimal };
            var depthStencilAttachmentReference = new AttachmentReference { Attachment = 1, Layout = ImageLayout.DepthStencilAttachmentOptimal };

            var subpass = new SubpassDescription
            {
                PipelineBindPoint = PipelineBindPoint.Graphics,
                ColorAttachmentCount = 1,
                ColorAttachments = new IntPtr(&colorAttachmentReference),
            };

            var attachments = new[]
            {
                new AttachmentDescription
                {
                    Format = backBufferFormat,
                    Samples = SampleCountFlags.Sample1,
                    LoadOperation = AttachmentLoadOperation.Load,
                    StoreOperation = AttachmentStoreOperation.Store,
                    StencilLoadOperation = AttachmentLoadOperation.DontCare,
                    StencilStoreOperation = AttachmentStoreOperation.DontCare,
                    InitialLayout = ImageLayout.ColorAttachmentOptimal,
                    FinalLayout = ImageLayout.ColorAttachmentOptimal
                },
            };

            fixed (AttachmentDescription* attachmentsPointer = &attachments[0])
            {
                var createInfo = new RenderPassCreateInfo
                {
                    StructureType = StructureType.RenderPassCreateInfo,
                    AttachmentCount = (uint)attachments.Length,
                    Attachments = new IntPtr(attachmentsPointer),
                    SubpassCount = 1,
                    Subpasses = new IntPtr(&subpass)
                };

                renderPass = device.CreateRenderPass(ref createInfo);
            }
        }
Exemplo n.º 50
0
        Framebuffer [] CreateFramebuffers(Image[] images, SurfaceFormatKhr surfaceFormat, SurfaceCapabilitiesKhr surfaceCapabilities, RenderPass renderPass)
        {
            var displayViews = new ImageView [images.Length];

            for (int i = 0; i < images.Length; i++)
            {
                var viewCreateInfo = new ImageViewCreateInfo {
                    Image      = images [i],
                    ViewType   = ImageViewType.View2D,
                    Format     = surfaceFormat.Format,
                    Components = new ComponentMapping {
                        R = ComponentSwizzle.R,
                        G = ComponentSwizzle.G,
                        B = ComponentSwizzle.B,
                        A = ComponentSwizzle.A
                    },
                    SubresourceRange = new ImageSubresourceRange {
                        AspectMask = ImageAspectFlags.Color,
                        LevelCount = 1,
                        LayerCount = 1
                    }
                };
                displayViews [i] = device.CreateImageView(viewCreateInfo);
            }
            var framebuffers = new Framebuffer [images.Length];

            for (int i = 0; i < images.Length; i++)
            {
                var frameBufferCreateInfo = new FramebufferCreateInfo {
                    Layers      = 1,
                    RenderPass  = renderPass,
                    Attachments = new ImageView [] { displayViews [i] },
                    Width       = surfaceCapabilities.CurrentExtent.Width,
                    Height      = surfaceCapabilities.CurrentExtent.Height
                };
                framebuffers [i] = device.CreateFramebuffer(frameBufferCreateInfo);
            }
            return(framebuffers);
        }
Exemplo n.º 51
0
        private void RenderAvatars(RenderPass pass)
        {
            if (!RenderSettings.AvatarRenderingEnabled) return;

            lock (Avatars)
            {
                GL.EnableClientState(ArrayCap.VertexArray);
                GL.EnableClientState(ArrayCap.TextureCoordArray);
                GL.EnableClientState(ArrayCap.NormalArray);

                int avatarNr = 0;
                foreach (RenderAvatar av in VisibleAvatars)
                {
                    avatarNr++;

                    // Whole avatar position
                    GL.PushMatrix();

                    // Prim roation and position
                    av.UpdateSize();
                    GL.MultMatrix(Math3D.CreateSRTMatrix(Vector3.One, av.RenderRotation, av.AdjustedPosition(av.RenderPosition)));

                    if (av.glavatar._meshes.Count > 0)
                    {
                        int faceNr = 0;
                        foreach (GLMesh mesh in av.glavatar._meshes.Values)
                        {
                            if (av.glavatar.skel.mNeedsMeshRebuild)
                            {
                                mesh.applyjointweights();
                            }

                            faceNr++;
                            if (!av.glavatar._showSkirt && mesh.Name == "skirtMesh")
                                continue;

                            // If we don't have a hair bake OR the hair bake is invisible don't render it
                            if (mesh.Name == "hairMesh" && (av.data[(int)AvatarTextureIndex.HairBaked] == null || av.data[(int)AvatarTextureIndex.HairBaked].TextureInfo.IsInvisible))
                                continue;

                            GL.Color3(1f, 1f, 1f);

                            if (pass == RenderPass.Picking)
                            {
                                GL.Disable(EnableCap.Texture2D);

                                for (int i = 0; i < av.data.Length; i++)
                                {
                                    if (av.data[i] != null)
                                    {
                                        av.data[i].PickingID = avatarNr;
                                    }
                                }
                                byte[] primNrBytes = Utils.Int16ToBytes((short)avatarNr);
                                byte[] faceColor = new byte[] { primNrBytes[0], primNrBytes[1], (byte)faceNr, 254 };
                                GL.Color4(faceColor);
                            }
                            else
                            {
                                if (av.data[mesh.teFaceID] == null)
                                {
                                    GL.Disable(EnableCap.Texture2D);
                                }
                                else
                                {
                                    if (mesh.teFaceID != 0)
                                    {
                                        GL.Enable(EnableCap.Texture2D);
                                        GL.BindTexture(TextureTarget.Texture2D, av.data[mesh.teFaceID].TextureInfo.TexturePointer);
                                    }
                                    else
                                    {
                                        GL.Disable(EnableCap.Texture2D);
                                    }
                                }
                            }

                            GL.TexCoordPointer(2, TexCoordPointerType.Float, 0, mesh.RenderData.TexCoords);
                            GL.VertexPointer(3, VertexPointerType.Float, 0, mesh.RenderData.Vertices);
                            GL.NormalPointer(NormalPointerType.Float, 0, mesh.MorphRenderData.Normals);

                            GL.DrawElements(BeginMode.Triangles, mesh.RenderData.Indices.Length, DrawElementsType.UnsignedShort, mesh.RenderData.Indices);

                            GL.BindTexture(TextureTarget.Texture2D, 0);

                        }

                        av.glavatar.skel.mNeedsMeshRebuild = false;
                    }

                    // Whole avatar position
                    GL.PopMatrix();
                }

                GL.Disable(EnableCap.Texture2D);
                GL.DisableClientState(ArrayCap.NormalArray);
                GL.DisableClientState(ArrayCap.VertexArray);
                GL.DisableClientState(ArrayCap.TextureCoordArray);

            }
        }
Exemplo n.º 52
0
        CommandBuffer[] CreateCommandBuffers(Image[] images, Framebuffer[] framebuffers, RenderPass renderPass, SurfaceCapabilitiesKhr surfaceCapabilities)
        {
            var createPoolInfo = new CommandPoolCreateInfo {
                Flags = CommandPoolCreateFlags.ResetCommandBuffer
            };
            var commandPool = device.CreateCommandPool(createPoolInfo);
            var commandBufferAllocateInfo = new CommandBufferAllocateInfo {
                Level              = CommandBufferLevel.Primary,
                CommandPool        = commandPool,
                CommandBufferCount = (uint)images.Length
            };
            var buffers = device.AllocateCommandBuffers(commandBufferAllocateInfo);

            for (int i = 0; i < images.Length; i++)
            {
                var commandBufferBeginInfo = new CommandBufferBeginInfo();
                buffers [i].Begin(commandBufferBeginInfo);
                var renderPassBeginInfo = new RenderPassBeginInfo {
                    Framebuffer = framebuffers [i],
                    RenderPass  = renderPass,
                    ClearValues = new ClearValue [] { new ClearValue {
                                                          Color = new ClearColorValue(new float [] { 0.9f, 0.7f, 0.0f, 1.0f })
                                                      } },
                    RenderArea = new Rect2D {
                        Extent = surfaceCapabilities.CurrentExtent
                    }
                };
                buffers [i].CmdBeginRenderPass(renderPassBeginInfo, SubpassContents.Inline);
                buffers [i].CmdEndRenderPass();
                buffers [i].End();
            }
            return(buffers);
        }
Exemplo n.º 53
0
        private void RenderText(RenderPass pass)
        {
            lock (VisibleAvatars)
            {
                GL.Color4(0f, 0f, 0f, 0.4f);
                foreach (RenderAvatar av in VisibleAvatars)
                {
                    Vector3 avPos = av.RenderPosition;
                    if (av.DistanceSquared > 400f) continue;

                    byte[] faceColor = null;

                    OpenTK.Vector3 tagPos = RHelp.TKVector3(avPos);
                    tagPos.Z += 1.2f;
                    OpenTK.Vector3 screenPos;
                    if (!Math3D.GluProject(tagPos, ModelMatrix, ProjectionMatrix, Viewport, out screenPos)) continue;

                    string tagText = instance.Names.Get(av.avatar.ID, av.avatar.Name);
                    if (!string.IsNullOrEmpty(av.avatar.GroupName))
                        tagText = av.avatar.GroupName + "\n" + tagText;

                    var tSize = Printer.Measure(tagText, AvatarTagFont);
                    if (pass == RenderPass.Picking)
                    {
                        //Send avatar anyway, we're attached to it
                        int faceID = 0;
                        foreach (FaceData f in av.data)
                        {
                            if (f != null)
                            {
                                byte[] primNrBytes = Utils.Int16ToBytes((short)f.PickingID);
                                faceColor = new byte[] { primNrBytes[0], primNrBytes[1], (byte)faceID, 254 };
                                GL.Color4(faceColor);
                                break;
                            }
                            faceID++;
                        }
                    }

                    OpenTK.Vector3 quadPos = screenPos;
                    screenPos.Y = glControl.Height - screenPos.Y;
                    screenPos.X -= tSize.BoundingBox.Width / 2;
                    screenPos.Y -= tSize.BoundingBox.Height / 2 + 2;

                    if (screenPos.Y > 0)
                    {
                        // Render tag backround
                        float halfWidth = tSize.BoundingBox.Width / 2 + 12;
                        float halfHeight = tSize.BoundingBox.Height / 2 + 5;
                        RHelp.Draw2DBox(quadPos.X - halfWidth, quadPos.Y - halfHeight, halfWidth * 2, halfHeight * 2, screenPos.Z);

                        if (pass == RenderPass.Simple)
                        {
                            Printer.Begin();
                            Color textColor = pass == RenderPass.Simple ?
                                Color.Orange :
                                Color.FromArgb(faceColor[3], faceColor[0], faceColor[1], faceColor[2]);
                            Printer.Print(tagText, AvatarTagFont, textColor,
                                new RectangleF(screenPos.X, screenPos.Y, tSize.BoundingBox.Width + 2, tSize.BoundingBox.Height + 2),
                                OpenTK.Graphics.TextPrinterOptions.Default, OpenTK.Graphics.TextAlignment.Center);
                            Printer.End();
                        }
                    }
                }
            }

            lock (SortedObjects)
            {
                int primNr = 0;
                foreach (SceneObject obj in SortedObjects)
                {
                    if (!(obj is RenderPrimitive)) continue;

                    RenderPrimitive prim = (RenderPrimitive)obj;
                    primNr++;

                    if (!string.IsNullOrEmpty(prim.BasePrim.Text))
                    {
                        string text = System.Text.RegularExpressions.Regex.Replace(prim.BasePrim.Text, "(\r?\n)+", "\n");
                        OpenTK.Vector3 primPos = RHelp.TKVector3(prim.RenderPosition);

                        // Display hovertext only on objects that are withing 12m of the camera
                        if (prim.DistanceSquared > (12 * 12)) continue;

                        primPos.Z += prim.BasePrim.Scale.Z * 0.8f;

                        // Convert objects world position to 2D screen position in pixels
                        OpenTK.Vector3 screenPos;
                        if (!Math3D.GluProject(primPos, ModelMatrix, ProjectionMatrix, Viewport, out screenPos)) continue;
                        screenPos.Y = glControl.Height - screenPos.Y;

                        Printer.Begin();

                        Color color = Color.FromArgb((int)(prim.BasePrim.TextColor.A * 255), (int)(prim.BasePrim.TextColor.R * 255), (int)(prim.BasePrim.TextColor.G * 255), (int)(prim.BasePrim.TextColor.B * 255));

                        var size = Printer.Measure(text, HoverTextFont);
                        screenPos.X -= size.BoundingBox.Width / 2;
                        screenPos.Y -= size.BoundingBox.Height;

                        if (screenPos.Y > 0)
                        {
                            if (pass == RenderPass.Picking)
                            {
                                //Send the prim anyway, we're attached to it
                                int faceID = 0;
                                foreach (Face f in prim.Faces)
                                {
                                    if (f.UserData != null)
                                    {
                                        byte[] primNrBytes = Utils.Int16ToBytes((short)((FaceData)f.UserData).PickingID);
                                        byte[] faceColor = new byte[] { primNrBytes[0], primNrBytes[1], (byte)faceID, 255 };
                                        Printer.Print(text, HoverTextFont, Color.FromArgb(faceColor[3], faceColor[0], faceColor[1], faceColor[2]), new RectangleF(screenPos.X, screenPos.Y, size.BoundingBox.Width + 2, size.BoundingBox.Height + 2), OpenTK.Graphics.TextPrinterOptions.Default, OpenTK.Graphics.TextAlignment.Center);
                                        break;
                                    }
                                    faceID++;
                                }
                            }
                            else
                            {
                                // Shadow
                                if (color != Color.Black)
                                    Printer.Print(text, HoverTextFont, Color.Black, new RectangleF(screenPos.X + 1, screenPos.Y + 1, size.BoundingBox.Width + 2, size.BoundingBox.Height + 2), OpenTK.Graphics.TextPrinterOptions.Default, OpenTK.Graphics.TextAlignment.Center);

                                // Text
                                Printer.Print(text, HoverTextFont, color, new RectangleF(screenPos.X, screenPos.Y, size.BoundingBox.Width + 2, size.BoundingBox.Height + 2), OpenTK.Graphics.TextPrinterOptions.Default, OpenTK.Graphics.TextAlignment.Center);
                            }
                        }

                        Printer.End();
                    }
                }
            }
        }
        internal static Pipeline CreatePipeline(
            Device logicalDevice,
            RenderPass renderpass,
            PipelineLayout layout,
            ShaderModule vertModule,
            ShaderModule fragModule,
            SpecializationContainer specializationContainer,
            bool depthClamp,
            bool depthBias,
            ReadOnlySpan <DeviceTexture> targets,
            IInternalRenderObject renderObject)
        {
            if (logicalDevice == null)
            {
                throw new ArgumentNullException(nameof(logicalDevice));
            }
            if (renderpass == null)
            {
                throw new ArgumentNullException(nameof(renderpass));
            }

            var shaderStages = new []
            {
                new PipelineShaderStageCreateInfo(
                    stage: ShaderStages.Vertex, module: vertModule, name: "main",
                    specializationInfo: specializationContainer?.GetInfo()),
                new PipelineShaderStageCreateInfo(
                    stage: ShaderStages.Fragment,
                    module: fragModule, name: "main",
                    specializationInfo: specializationContainer?.GetInfo())
            };
            var depthTest = new PipelineDepthStencilStateCreateInfo {
                DepthTestEnable       = true,
                DepthWriteEnable      = true,
                DepthCompareOp        = CompareOp.LessOrEqual,
                DepthBoundsTestEnable = false,
                StencilTestEnable     = false
            };
            var rasterizer = new PipelineRasterizationStateCreateInfo(
                depthClampEnable: depthClamp,
                rasterizerDiscardEnable: false,
                polygonMode: PolygonMode.Fill,
                cullMode: CullModes.Back,
                frontFace: renderObject.GetFrontFace(),
                depthBiasEnable: depthBias,
                depthBiasConstantFactor: .1f,
                depthBiasSlopeFactor: 1.75f,
                lineWidth: 1f
                );

            //Gather all the color targets and setup a blend-state for them
            ResizeArray <PipelineColorBlendAttachmentState> blendAttachments =
                new ResizeArray <PipelineColorBlendAttachmentState>();

            for (int i = 0; i < targets.Length; i++)
            {
                if (!targets[i].DepthTexture)
                {
                    blendAttachments.Add(new PipelineColorBlendAttachmentState(
                                             colorWriteMask: ColorComponents.All, blendEnable: false));
                }
            }

            var blending = new PipelineColorBlendStateCreateInfo(
                attachments: blendAttachments.ToArray(),
                logicOpEnable: false
                );
            var multisampleState = new PipelineMultisampleStateCreateInfo(
                rasterizationSamples: SampleCounts.Count1,
                sampleShadingEnable: false
                );
            //Pass the viewport and scissor-rect as dynamic so we are not tied to swapchain size
            //the advantage is this is that we don't need to recreate the pipeline on swapchain
            //resize
            var dynamicState = new PipelineDynamicStateCreateInfo(
                DynamicState.Viewport,
                DynamicState.Scissor
                );

            return(logicalDevice.CreateGraphicsPipeline(new GraphicsPipelineCreateInfo(
                                                            layout: layout,
                                                            renderPass: renderpass,
                                                            subpass: 0,
                                                            stages: shaderStages,
                                                            inputAssemblyState: renderObject.GetInputAssemblyStateInfo(),
                                                            vertexInputState: renderObject.GetVertexInputState(),
                                                            rasterizationState: rasterizer,
                                                            tessellationState: null,
                                                            //Pass empty viewport and scissor-rect as we set them dynamically
                                                            viewportState: new PipelineViewportStateCreateInfo(new Viewport(), new Rect2D()),
                                                            multisampleState: multisampleState,
                                                            depthStencilState: depthTest,
                                                            colorBlendState: blending,
                                                            dynamicState: dynamicState,
                                                            flags: PipelineCreateFlags.None
                                                            )));
        }
Exemplo n.º 55
0
        private void RenderAvatars(RenderPass pass)
        {
            if (!RenderSettings.AvatarRenderingEnabled) return;

            lock (Avatars)
            {
                GL.EnableClientState(ArrayCap.VertexArray);
                GL.EnableClientState(ArrayCap.TextureCoordArray);
                GL.EnableClientState(ArrayCap.NormalArray);

                int avatarNr = 0;
                foreach (RenderAvatar av in VisibleAvatars)
                {
                    avatarNr++;

                    // Whole avatar position
                    GL.PushMatrix();

                    Vector3 avataroffset = av.glavatar.skel.getOffset("mPelvis");

                    // Prim roation and position
                    GL.MultMatrix(Math3D.CreateSRTMatrix(Vector3.One, av.RenderRotation, av.RenderPosition - avataroffset * av.RenderRotation));

                    if (av.glavatar._meshes.Count > 0)
                    {
                        int faceNr = 0;
                        foreach (GLMesh mesh in av.glavatar._meshes.Values)
                        {
                            if (av.glavatar.skel.mNeedsMeshRebuild)
                            {
                                mesh.applyjointweights();
                            }

                            faceNr++;
                            if (!av.glavatar._showSkirt && mesh.Name == "skirtMesh")
                                continue;

                            if (mesh.Name == "hairMesh") // Don't render the hair mesh for the moment
                                continue;

                            GL.Color3(1f, 1f, 1f);

                            // Individual part mesh matrix
                            GL.PushMatrix();

                            // Special case for eyeballs we need to offset the mesh to the correct position
                            // We have manually added the eyeball offset based on the headbone when we
                            // constructed the meshes, but why are the position offsets we got when loading
                            // the other meshes <0,7,0> ?
                            if (mesh.Name == "eyeBallLeftMesh")
                            {
                                // Mesh roation and position
                                GL.MultMatrix(Math3D.CreateSRTMatrix(Vector3.One, av.glavatar.skel.mLeftEye.getTotalRotation(), av.glavatar.skel.mLeftEye.getTotalOffset()));
                            }
                            if (mesh.Name == "eyeBallRightMesh")
                            {
                                // Mesh roation and position
                                GL.MultMatrix(Math3D.CreateSRTMatrix(Vector3.One, av.glavatar.skel.mRightEye.getTotalRotation(), av.glavatar.skel.mRightEye.getTotalOffset()));
                            }

                            //Should we be offsetting the base meshs at all?
                            //if (mesh.Name == "headMesh")
                            //{
                            //    GL.MultMatrix(Math3D.CreateTranslationMatrix(av.glavatar.skel.getDeltaOffset("mHead")));
                            //}


                            if (pass == RenderPass.Picking)
                            {
                                GL.Disable(EnableCap.Texture2D);

                                for (int i = 0; i < av.data.Length; i++)
                                {
                                    if (av.data[i] != null)
                                    {
                                        av.data[i].PickingID = avatarNr;
                                    }
                                }
                                byte[] primNrBytes = Utils.Int16ToBytes((short)avatarNr);
                                byte[] faceColor = new byte[] { primNrBytes[0], primNrBytes[1], (byte)faceNr, 254 };
                                GL.Color4(faceColor);
                            }
                            else
                            {
                                if (av.data[mesh.teFaceID] == null)
                                {
                                    GL.Disable(EnableCap.Texture2D);
                                }
                                else
                                {
                                    if (mesh.teFaceID != 0)
                                    {
                                        GL.Enable(EnableCap.Texture2D);
                                        GL.BindTexture(TextureTarget.Texture2D, av.data[mesh.teFaceID].TextureInfo.TexturePointer);
                                    }
                                    else
                                    {
                                        GL.Disable(EnableCap.Texture2D);
                                    }
                                }
                            }

                            GL.TexCoordPointer(2, TexCoordPointerType.Float, 0, mesh.RenderData.TexCoords);
                            GL.VertexPointer(3, VertexPointerType.Float, 0, mesh.RenderData.Vertices);
                            GL.NormalPointer(NormalPointerType.Float, 0, mesh.RenderData.Normals);

                            GL.DrawElements(BeginMode.Triangles, mesh.RenderData.Indices.Length, DrawElementsType.UnsignedShort, mesh.RenderData.Indices);

                            GL.BindTexture(TextureTarget.Texture2D, 0);

                            GL.PopMatrix();

                        }

                        av.glavatar.skel.mNeedsMeshRebuild = false;
                    }

                    // Whole avatar position
                    GL.PopMatrix();
                }

                GL.Disable(EnableCap.Texture2D);
                GL.DisableClientState(ArrayCap.NormalArray);
                GL.DisableClientState(ArrayCap.VertexArray);
                GL.DisableClientState(ArrayCap.TextureCoordArray);

            }
        }
Exemplo n.º 56
0
        public override void Load()
        {
            base.Load();

            if (OfflineCompilation)
            {
                return;
            }

            var renderTargets = new RenderTarget[2];
            DepthStencilBuffer depthStencilBuffer  = null;
            Texture2D          depthStencilTexture = null;

            Parameters.AddSources(MainPlugin.ViewParameters);

            Parameters.RegisterParameter(EffectPlugin.BlendStateKey);

            var filteredPasses = new FastList <RenderPass>();

            RenderPass.UpdatePasses += updatePassesAction = (RenderPass currentRenderPass, ref FastList <RenderPass> currentPasses) =>
            {
                var originalPasses = currentPasses;
                filteredPasses.Clear();
                currentPasses = filteredPasses;

                Parameters.Set(PickingFrameIndex, ++currentPickingFrameIndex);
                Request[] requests;

                lock (pendingRequests)
                {
                    // No picking request or no mesh to pick?
                    if (pendingRequests.Count == 0)
                    {
                        return;
                    }

                    requests = pendingRequests.ToArray();
                    pendingRequests.Clear();
                }

                foreach (var request in requests)
                {
                    requestResults.Add(request);
                }

                if (originalPasses == null)
                {
                    return;
                }

                // Count mesh passes
                int meshIndex = 0;
                foreach (var pass in originalPasses)
                {
                    meshIndex += pass.Passes.Count;
                }

                // No mesh to pick?
                if (meshIndex == 0)
                {
                    return;
                }

                // Copy mesh passes and assign indices
                var meshPasses = new EffectMesh[meshIndex];
                meshIndex = 0;
                foreach (var pass in RenderPass.Passes)
                {
                    throw new NotImplementedException();
                    //foreach (var effectMeshPass in pass.Meshes)
                    //{
                    //    meshPasses[meshIndex] = (EffectMesh)effectMeshPass;
                    //    // Prefix increment so that 0 means no rendering.
                    //    effectMeshPass.Parameters.Set(PickingMeshIndex, ++meshIndex);
                    //}
                }

                // For now, it generates one rendering per picking.
                // It would be quite easy to optimize it by make Picking shader works on multiple picking points at a time.
                foreach (var request in requests)
                {
                    var pickingRenderPass = new RenderPass("Picking");

                    pickingRenderPass.StartPass.AddFirst = (threadContext) =>
                    {
                        threadContext.GraphicsDevice.Clear(renderTargets[0], Color.Black);
                        threadContext.GraphicsDevice.Clear(renderTargets[1], Color.Black);
                        threadContext.Parameters.Set(PickingScreenPosition, request.Location);
                        threadContext.GraphicsDevice.SetViewport(new Viewport(0, 0, renderTargets[0].Description.Width, renderTargets[0].Description.Height));

                        threadContext.GraphicsDevice.Clear(depthStencilBuffer, DepthStencilClearOptions.DepthBuffer);
                        threadContext.GraphicsDevice.SetRenderTargets(depthStencilBuffer, renderTargets);
                    };
                    pickingRenderPass.EndPass.AddLast = (threadContext) =>
                    {
                        threadContext.Parameters.Reset(PickingScreenPosition);
                        threadContext.GraphicsDevice.Copy(renderTargets[0].Texture, request.ResultTextures[0]);
                        threadContext.GraphicsDevice.Copy(renderTargets[1].Texture, request.ResultTextures[1]);
                    };
                    //pickingRenderPass.PassesInternal = originalPasses;
                    throw new NotImplementedException();

                    request.MeshPasses = meshPasses;

                    currentPasses.Add(pickingRenderPass);

                    request.HasResults = true;

                    // Wait 2 frames before pulling the results.
                    request.FrameCounter = 2;
                }
            };

            RenderSystem.GlobalPass.EndPass.AddLast = CheckPickingResults;

            var backBuffer = GraphicsDevice.BackBuffer;

            int pickingArea = 1 + PickingDistance * 2;

            renderTargets[0] = Texture.New2D(GraphicsDevice, pickingArea, pickingArea, PixelFormat.R32_UInt, TextureFlags.ShaderResource | TextureFlags.RenderTarget).ToRenderTarget().KeepAliveBy(ActiveObjects);
            renderTargets[1] = Texture.New2D(GraphicsDevice, pickingArea, pickingArea, PixelFormat.R32G32B32A32_Float, TextureFlags.ShaderResource | TextureFlags.RenderTarget).ToRenderTarget().KeepAliveBy(ActiveObjects);

            depthStencilTexture = Texture.New2D(GraphicsDevice, pickingArea, pickingArea, PixelFormat.D32_Float, TextureFlags.ShaderResource | TextureFlags.DepthStencil).KeepAliveBy(ActiveObjects);
            depthStencilBuffer  = depthStencilTexture.ToDepthStencilBuffer(false);

            Parameters.AddDynamic(PickingMatrix, ParameterDynamicValue.New(PickingScreenPosition, (ref Vector2 pickingPosition, ref Matrix picking) =>
            {
                // Move center to picked position, and zoom (it is supposed to stay per-pixel according to render target size)
                picking = Matrix.Translation(1.0f - (pickingPosition.X) / backBuffer.Width * 2.0f, -1.0f + (pickingPosition.Y) / backBuffer.Height * 2.0f, 0.0f)
                          * Matrix.Scaling((float)backBuffer.Width / (float)pickingArea, (float)backBuffer.Height / (float)pickingArea, 1.0f);
            }));
        }
Exemplo n.º 57
0
        private void RenderObjects(RenderPass pass)
        {
            if (!RenderSettings.PrimitiveRenderingEnabled) return;

            GL.EnableClientState(ArrayCap.VertexArray);
            GL.EnableClientState(ArrayCap.TextureCoordArray);
            GL.EnableClientState(ArrayCap.NormalArray);

            Vector3 myPos = Vector3.Zero;
            if (myself != null)
            {
                myPos = myself.RenderPosition;
            }
            else
            {
                myPos = Client.Self.SimPosition;
            }

            if (pass == RenderPass.Invisible)
            {
                GL.Disable(EnableCap.Texture2D);
                GL.StencilFunc(StencilFunction.Always, 1, 1);
                GL.StencilOp(StencilOp.Keep, StencilOp.Keep, StencilOp.Replace);
                GL.ColorMask(false, false, false, false);
                GL.StencilMask(0);
            }

            int nrPrims = SortedObjects.Count;
            for (int i = 0; i < nrPrims; i++)
            {
                //RenderBoundingBox(SortedPrims[i]);

                // When rendering alpha faces, draw from back towards the camers
                // otherwise from those closest to camera, to the farthest
                int ix = pass == RenderPass.Alpha ? nrPrims - i - 1 : i;
                SceneObject obj = SortedObjects[ix];

                if (obj is RenderPrimitive)
                {
                    // Don't render objects that are outside the draw distane
                    if (FindClosestDistanceSquared(myPos, obj) > drawDistanceSquared) continue;
                    if (pass == RenderPass.Simple || pass == RenderPass.Alpha)
                    {
                        obj.StartQuery(pass);
                        obj.Render(pass, ix, this, lastFrameTime);
                        obj.EndQuery(pass);
                    }
                    else
                    {
                        obj.Render(pass, ix, this, lastFrameTime);
                    }
                }
            }

            if (pass == RenderPass.Invisible)
            {
                GL.StencilOp(StencilOp.Keep, StencilOp.Keep, StencilOp.Keep);
                GL.ColorMask(true, true, true, true);
                GL.StencilFunc(StencilFunction.Notequal, 1, 1);
                GL.StencilMask(uint.MaxValue);
            }

            GL.Disable(EnableCap.Texture2D);
            GL.DisableClientState(ArrayCap.VertexArray);
            GL.DisableClientState(ArrayCap.TextureCoordArray);
            GL.DisableClientState(ArrayCap.NormalArray);
        }
Exemplo n.º 58
0
            public void Initialize(EngineContext engineContext)
            {
                var renderContext  = engineContext.RenderContext;
                var rootRenderPass = renderContext.RootRenderPass;

                var linearColorPass   = new RenderPass("LinearColor");
                var reinhardColorPass = new RenderPass("ReinhardColor");
                var yebisPass         = new RenderPass("YebisColor");
                var filmicColorPass   = new RenderPass("FilmicColor");
                var composeColorPass  = new RenderPass("ComposeColor");

                rootRenderPass.AddPass(linearColorPass);
                rootRenderPass.AddPass(reinhardColorPass);
                rootRenderPass.AddPass(yebisPass);
                rootRenderPass.AddPass(filmicColorPass);
                rootRenderPass.AddPass(composeColorPass);

                LinearColorPlugin = new PostEffectPlugin("LinearColor")
                {
                    RenderPass = linearColorPass
                };

                ReinhardColorPlugin = new PostEffectPlugin("ReinhardColor")
                {
                    RenderPass = reinhardColorPass
                };

#if XENKO_YEBIS
                YebisPlugin = new YebisPlugin("ReinhardColor")
                {
                    RenderPass = yebisPass
                };
#endif

                FilmicColorPlugin = new PostEffectPlugin("FilmicColor")
                {
                    RenderPass = filmicColorPass
                };

                MainPlugin = new PostEffectPlugin("MainColor")
                {
                    RenderPass = composeColorPass
                };

                //MainDepthReadOnlyPlugin

                // YebisPlugin = new YebisPlugin() { RenderPass = yebisColorPass, MainDepthReadOnlyPlugin = null };

                //renderContext.Register(MainDepthReadOnlyPlugin);
                //renderContext.Register(SkyBoxPlugin);
                //renderContext.Register(PostEffectPlugin);

                //// Create and bind depth stencil buffer
                //renderContext.GraphicsResizeContext.SetupResize(
                //    (resizeContext) =>
                //    {
                //        MainDepthReadOnlyPlugin.DepthStencil = renderContext.GraphicsDevice.DepthStencilBuffer.New(DepthFormat.Depth32, renderContext.Width, renderContext.Height, true, "MainDepthBuffer");
                //        // Bind render target - comment when Yebis is off
                //        MainDepthReadOnlyPlugin.RenderTarget = renderContext.GraphicsDevice.RenderTarget2D.New(renderContext.Width, renderContext.Height, PixelFormat.HalfVector4, name: "MainRenderTarget");

                //        // Comment - when Yebis is on
                //        //MainDepthReadOnlyPlugin.RenderTarget = renderContext.GraphicsDevice.RenderTarget2D.New(renderContext.Width, renderContext.Height, PixelFormat.R8G8B8A8, name: "MainRenderTarget");
                //        //renderContext.GlobalPass.EndPass.AddFirst = threadContext => threadContext.GraphicsDevice.Copy(MainDepthReadOnlyPlugin.RenderTarget, engineContext.RenderContext.RenderTarget);
                //    });

                //// Yebis plugin must be initialized after creating MainDepthReadOnlyPlugin.RenderTarget
                //renderContext.Register(YebisPlugin);

                //YebisPlugin.ToneMap.Gamma = 1.0f;
                //YebisPlugin.ToneMap.Type = ToneMapType.Auto;
                //YebisPlugin.ToneMap.AutoExposure.MiddleGray = 0.25f;
                //YebisPlugin.ToneMap.AutoExposure.AdaptationSensitivity = 0.5f;
                //YebisPlugin.ToneMap.AutoExposure.AdaptationScale = 0.8f;
                //YebisPlugin.ToneMap.AutoExposure.AdaptationSpeedLimit = 4.0f;
                //YebisPlugin.ToneMap.AutoExposure.DarkAdaptationSensitivity = 0.9f;
                //YebisPlugin.ToneMap.AutoExposure.DarkAdaptationScale = 0.6f;
                //YebisPlugin.ToneMap.AutoExposure.DarkAdaptationSpeedLimit = 4.0f;
                //YebisPlugin.ToneMap.AutoExposure.LightDarkExposureBorder = 1.0f;

                //YebisPlugin.Glare.Enable = true;
                //YebisPlugin.Glare.RemapFactor = 1f;
                //YebisPlugin.Glare.Threshold = 0f;

                //YebisPlugin.Lens.Vignette.Enable = true;

                //YebisPlugin.ColorCorrection.ColorTemperature = 3500;
            }
Exemplo n.º 59
0
        public override void Load()
        {
            base.Load();

            if (OfflineCompilation)
                return;

            // Declare post render pass
            PostPass = new RenderPass("PostPass").KeepAliveBy(ActiveObjects);
            RenderPass.AddPass(PostPass);


            var depthStencilTexture = Texture.New2D(GraphicsDevice, AtlasSize, AtlasSize, PixelFormat.D32_Float, TextureFlags.DepthStencil | TextureFlags.ShaderResource).KeepAliveBy(ActiveObjects);
            var depthStencilBuffer = depthStencilTexture.ToDepthStencilBuffer(false);
            ShadowMapDepth = depthStencilBuffer;

            //MainTargetPlugin.Parameters.Set(ShadowMapKeys.Texture0, ShadowMapDepth);

            // Setup clear of this target
            var renderTargetPlugin = new RenderTargetsPlugin
                {
                    Services = Services,
                    EnableClearDepth = true,
                    EnableSetTargets = false,
                    RenderPass = RenderPass,
                    RenderTarget = null,
                    DepthStencil = depthStencilBuffer,
                };
            renderTargetPlugin.Apply();

            // Use Default ZTest for GBuffer
            depthStencilStateZStandard = DepthStencilState.New(GraphicsDevice, new DepthStencilStateDescription().Default()).KeepAliveBy(ActiveObjects);
            depthStencilStateZStandard.Name = "ZStandard";

            Parameters.Set(EffectPlugin.DepthStencilStateKey, depthStencilStateZStandard);

            casterRasterizerState = RasterizerState.New(GraphicsDevice, new RasterizerStateDescription(CullMode.Back)).KeepAliveBy(ActiveObjects);

            // Variance Shadow Mapping
            // Create the blur temporary texture
            var shadowMapTextureDesc = ShadowMapDepth.Description;
            var shadowMapBlurH = Texture.New2D(GraphicsDevice, shadowMapTextureDesc.Width, shadowMapTextureDesc.Height, PixelFormat.R32G32_Float, TextureFlags.ShaderResource | TextureFlags.RenderTarget).KeepAliveBy(ActiveObjects);
            var shadowMapBlurV = Texture.New2D(GraphicsDevice, shadowMapTextureDesc.Width, shadowMapTextureDesc.Height, PixelFormat.R32G32_Float, TextureFlags.ShaderResource | TextureFlags.RenderTarget).KeepAliveBy(ActiveObjects);

            Texture2D textureSourceH = ShadowMapDepth.Texture;
            Texture2D textureSourceV = shadowMapBlurH;
            RenderTarget renderTargetH = shadowMapBlurH.ToRenderTarget();
            RenderTarget renderTargetV = shadowMapBlurV.ToRenderTarget();

            var blurQuadMesh = new EffectMesh[2];
            for (int j = 0; j < BlurCount; j++)
            {
                for (int i = 0; i < 2; ++i)
                {
                    blurQuadMesh[i] = new EffectMesh(j > 0 ? blurEffects[1] : blurEffects[i]).KeepAliveBy(ActiveObjects);
                    blurQuadMesh[i].Parameters.Set(PostEffectBlurKeys.Coefficients, new[] { 0.2270270270f, 0.3162162162f, 0.3162162162f, 0.0702702703f, 0.0702702703f });
                    var unit = i == 0 ? Vector2.UnitX : Vector2.UnitY;
                    blurQuadMesh[i].Parameters.Set(PostEffectBlurKeys.Offsets, new[] { Vector2.Zero, unit * -1.3846153846f, unit * +1.3846153846f, unit * -3.2307692308f, unit * +3.2307692308f });

                    PostPass.AddPass(blurQuadMesh[i].EffectPass);

                    RenderSystem.GlobalMeshes.AddMesh(blurQuadMesh[i]);
                }

                blurQuadMesh[0].Parameters.Set(TexturingKeys.Texture0, textureSourceH);
                blurQuadMesh[1].Parameters.Set(TexturingKeys.Texture0, textureSourceV);
                blurQuadMesh[0].Parameters.Set(RenderTargetKeys.RenderTarget, renderTargetH);
                blurQuadMesh[1].Parameters.Set(RenderTargetKeys.RenderTarget, renderTargetV);

                textureSourceH = shadowMapBlurV;
                textureSourceV = shadowMapBlurH;
            }

            ShadowMapVsm = shadowMapBlurV;

            // Final texture for VSM is result of blur
            //MainTargetPlugin.Parameters.Set(ShadowMapKeys.Texture0, shadowMapBlurV);
        }
Exemplo n.º 60
0
        void RenderEntityList(Shader shader, RenderPass pass, List <BatchedEntity> list, VoxelObject commonVO = null)
        {
            // Pre-load mesh
            Mesh mesh = null;

            if (commonVO != null)
            {
                mesh = PrepareVO(commonVO, pass);
                if (mesh == null)
                {
                    return;
                }
            }

            // Go through batch
            foreach (BatchedEntity ent in list)
            {
                if (ent.OnlyRenderFor.HasValue && !ent.OnlyRenderFor.Value.HasFlag(pass))
                {
                    continue;
                }

                // Load mesh if were not using a common vo
                if (commonVO == null)
                {
                    mesh = PrepareVO(ent.VoxelObject, pass);
                    if (mesh == null)
                    {
                        continue;
                    }
                }

                // Determine the world matrix
                Matrix4 worldMatrix = ent.CustomMatrix
                                      ?? Maths.CreateTransformationMatrix(ent.Position, ent.MeshRotation, ent.VoxelObject.MeshScale);
                shader.LoadMatrix4("transformationMatrix", worldMatrix);

                // Prepare the entity
                //if (ent.RenderFront && pass != RenderPass.Shadow) StateManager.DepthFunc(DepthFunction.Always);
                //else StateManager.DepthFunc(DepthFunction.Less);

                StateManager.ToggleWireframe(ent.RenderAsWireframe);

                if (!pass.HasFlag(RenderPass.Shadow))
                {
                    shader.LoadBool("skipLight", ent.ApplyNoLighting);
                    shader.LoadColor4("colorOverlay", ent.ColorOverlay);
                    shader.LoadFloat("entityLighting", 1f);
                }

                // Render the entity
                GL.DrawElements(mesh.BeginMode, mesh.VertexCount, DrawElementsType.UnsignedInt, IntPtr.Zero);

                // If we're not using a common vo, end it's mesh
                if (commonVO == null)
                {
                    Master.EndMesh();
                }
            }

            // If we are using a common vo, end it's mesh last
            if (commonVO != null)
            {
                Master.EndMesh();
            }
        }