C for Graphic:遮罩显示(一)

news2024/11/20 18:34:26

      模板缓冲一般用于遮罩渲染的功能,其原理很以前聊过(模板缓冲原理),就不再啰嗦了。
      现在实现一个功能:使用一个长方体(或任意物体)遮罩渲染对象(比如一个球)。
      首先在官网下载内置着色器,找到DefaultResourcesExtra中的Standard.shader,改造一下支持stencil操作,如下:

Shader "Standard-Stencil"
{
    Properties
    {
        _StencilVal("Stencil Value", int) = 1
        _StencilComp("Stencil CompFunction (Disable,0,Never,1,Less,2,Equal,3,LessEqual,4,Greater,5,NotEqual,6,GreaterEqual,7,Always,8)", int) = 3
        _StencilPass("StencilPassFunciton(Keep,0,Zero,1,Replace,2,IncrSat,3,DecrSat,4,Invert,5,IncrWrap,6,DecrWrap,7)", int) = 0

        [Enum(Less,0,Greater,1,LEqual,2,GEqual,3,Equal,4,NotEqual,5,Always,6)]_ZTest("ZTest",int) = 0
        [Enum(Off,0,Front,1,Back,2)]_Cull("Cull", int) = 2

        _Color("Color", Color) = (1,1,1,1)
        _MainTex("Albedo", 2D) = "white" {}

        _Cutoff("Alpha Cutoff", Range(0.0, 1.0)) = 0.5

        _Glossiness("Smoothness", Range(0.0, 1.0)) = 0.5
        _GlossMapScale("Smoothness Scale", Range(0.0, 1.0)) = 1.0
        [Enum(Metallic Alpha,0,Albedo Alpha,1)] _SmoothnessTextureChannel ("Smoothness texture channel", Float) = 0

        [Gamma] _Metallic("Metallic", Range(0.0, 1.0)) = 0.0
        _MetallicGlossMap("Metallic", 2D) = "white" {}

        [ToggleOff] _SpecularHighlights("Specular Highlights", Float) = 1.0
        [ToggleOff] _GlossyReflections("Glossy Reflections", Float) = 1.0

        _BumpScale("Scale", Float) = 1.0
        _BumpMap("Normal Map", 2D) = "bump" {}

        _Parallax ("Height Scale", Range (0.005, 0.08)) = 0.02
        _ParallaxMap ("Height Map", 2D) = "black" {}

        _OcclusionStrength("Strength", Range(0.0, 1.0)) = 1.0
        _OcclusionMap("Occlusion", 2D) = "white" {}

        _EmissionColor("Color", Color) = (0,0,0)
        _EmissionMap("Emission", 2D) = "white" {}

        _DetailMask("Detail Mask", 2D) = "white" {}

        _DetailAlbedoMap("Detail Albedo x2", 2D) = "grey" {}
        _DetailNormalMapScale("Scale", Float) = 1.0
        _DetailNormalMap("Normal Map", 2D) = "bump" {}

        [Enum(UV0,0,UV1,1)] _UVSec ("UV Set for secondary textures", Float) = 0

        // Blending state
        [HideInInspector] _Mode ("__mode", Float) = 0.0
        [HideInInspector] _SrcBlend ("__src", Float) = 1.0
        [HideInInspector] _DstBlend ("__dst", Float) = 0.0
        [HideInInspector] _ZWrite ("__zw", Float) = 1.0
    }

    CGINCLUDE
        #define UNITY_SETUP_BRDF_INPUT MetallicSetup
    ENDCG

    SubShader
    {
        Tags { "RenderType"="Opaque" "PerformanceChecks"="False" }
        LOD 300


        // ------------------------------------------------------------------
        //  Base forward pass (directional light, emission, lightmaps, ...)
        Pass
        {
            Name "FORWARD"
            Tags { "LightMode" = "ForwardBase" }

            Blend [_SrcBlend] [_DstBlend]
            ZWrite [_ZWrite]
            ZWrite [_ZTest]

            Stencil
            {
                Ref [_StencilVal]
                Comp [_StencilComp]
                Pass [_StencilPass]
            }

            Cull [_Cull]

            CGPROGRAM
            #pragma target 3.0

            // -------------------------------------

            #pragma shader_feature _NORMALMAP
            #pragma shader_feature _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
            #pragma shader_feature _EMISSION
            #pragma shader_feature _METALLICGLOSSMAP
            #pragma shader_feature ___ _DETAIL_MULX2
            #pragma shader_feature _ _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
            #pragma shader_feature _ _SPECULARHIGHLIGHTS_OFF
            #pragma shader_feature _ _GLOSSYREFLECTIONS_OFF
            #pragma shader_feature _PARALLAXMAP

            #pragma multi_compile_fwdbase
            #pragma multi_compile_fog
            #pragma multi_compile_instancing
            // Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
            //#pragma multi_compile _ LOD_FADE_CROSSFADE

            #pragma vertex vertBase
            #pragma fragment fragBase
            #include "UnityStandardCoreForward.cginc"

            ENDCG
        }
        // ------------------------------------------------------------------
        //  Additive forward pass (one light per pass)
        Pass
        {
            Name "FORWARD_DELTA"
            Tags { "LightMode" = "ForwardAdd" }
            Blend [_SrcBlend] One
            Fog { Color (0,0,0,0) } // in additive pass fog should be black
            ZWrite Off
            ZTest LEqual

            CGPROGRAM
            #pragma target 3.0

            // -------------------------------------


            #pragma shader_feature _NORMALMAP
            #pragma shader_feature _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
            #pragma shader_feature _METALLICGLOSSMAP
            #pragma shader_feature _ _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
            #pragma shader_feature _ _SPECULARHIGHLIGHTS_OFF
            #pragma shader_feature ___ _DETAIL_MULX2
            #pragma shader_feature _PARALLAXMAP

            #pragma multi_compile_fwdadd_fullshadows
            #pragma multi_compile_fog
            // Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
            //#pragma multi_compile _ LOD_FADE_CROSSFADE

            #pragma vertex vertAdd
            #pragma fragment fragAdd
            #include "UnityStandardCoreForward.cginc"

            ENDCG
        }
        // ------------------------------------------------------------------
        //  Shadow rendering pass
        Pass {
            Name "ShadowCaster"
            Tags { "LightMode" = "ShadowCaster" }

            ZWrite On ZTest LEqual

            CGPROGRAM
            #pragma target 3.0

            // -------------------------------------


            #pragma shader_feature _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
            #pragma shader_feature _METALLICGLOSSMAP
            #pragma shader_feature _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
            #pragma shader_feature _PARALLAXMAP
            #pragma multi_compile_shadowcaster
            #pragma multi_compile_instancing
            // Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
            //#pragma multi_compile _ LOD_FADE_CROSSFADE

            #pragma vertex vertShadowCaster
            #pragma fragment fragShadowCaster

            #include "UnityStandardShadow.cginc"

            ENDCG
        }
        // ------------------------------------------------------------------
        //  Deferred pass
        Pass
        {
            Name "DEFERRED"
            Tags { "LightMode" = "Deferred" }

            CGPROGRAM
            #pragma target 3.0
            #pragma exclude_renderers nomrt


            // -------------------------------------

            #pragma shader_feature _NORMALMAP
            #pragma shader_feature _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
            #pragma shader_feature _EMISSION
            #pragma shader_feature _METALLICGLOSSMAP
            #pragma shader_feature _ _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
            #pragma shader_feature _ _SPECULARHIGHLIGHTS_OFF
            #pragma shader_feature ___ _DETAIL_MULX2
            #pragma shader_feature _PARALLAXMAP

            #pragma multi_compile_prepassfinal
            #pragma multi_compile_instancing
            // Uncomment the following line to enable dithering LOD crossfade. Note: there are more in the file to uncomment for other passes.
            //#pragma multi_compile _ LOD_FADE_CROSSFADE

            #pragma vertex vertDeferred
            #pragma fragment fragDeferred

            #include "UnityStandardCore.cginc"

            ENDCG
        }

        // ------------------------------------------------------------------
        // Extracts information for lightmapping, GI (emission, albedo, ...)
        // This pass it not used during regular rendering.
        Pass
        {
            Name "META"
            Tags { "LightMode"="Meta" }

            Cull Off

            CGPROGRAM
            #pragma vertex vert_meta
            #pragma fragment frag_meta

            #pragma shader_feature _EMISSION
            #pragma shader_feature _METALLICGLOSSMAP
            #pragma shader_feature _ _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
            #pragma shader_feature ___ _DETAIL_MULX2
            #pragma shader_feature EDITOR_VISUALIZATION

            #include "UnityStandardMeta.cginc"
            ENDCG
        }
    }

    SubShader
    {
        Tags { "RenderType"="Opaque" "PerformanceChecks"="False" }
        LOD 150

        // ------------------------------------------------------------------
        //  Base forward pass (directional light, emission, lightmaps, ...)
        Pass
        {
            Name "FORWARD"
            Tags { "LightMode" = "ForwardBase" }

            Blend [_SrcBlend] [_DstBlend]
            ZWrite [_ZWrite]

            CGPROGRAM
            #pragma target 2.0

            #pragma shader_feature _NORMALMAP
            #pragma shader_feature _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
            #pragma shader_feature _EMISSION
            #pragma shader_feature _METALLICGLOSSMAP
            #pragma shader_feature _ _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
            #pragma shader_feature _ _SPECULARHIGHLIGHTS_OFF
            #pragma shader_feature _ _GLOSSYREFLECTIONS_OFF
            // SM2.0: NOT SUPPORTED shader_feature ___ _DETAIL_MULX2
            // SM2.0: NOT SUPPORTED shader_feature _PARALLAXMAP

            #pragma skip_variants SHADOWS_SOFT DIRLIGHTMAP_COMBINED

            #pragma multi_compile_fwdbase
            #pragma multi_compile_fog

            #pragma vertex vertBase
            #pragma fragment fragBase
            #include "UnityStandardCoreForward.cginc"

            ENDCG
        }
        // ------------------------------------------------------------------
        //  Additive forward pass (one light per pass)
        Pass
        {
            Name "FORWARD_DELTA"
            Tags { "LightMode" = "ForwardAdd" }
            Blend [_SrcBlend] One
            Fog { Color (0,0,0,0) } // in additive pass fog should be black
            ZWrite Off
            ZTest LEqual

            CGPROGRAM
            #pragma target 2.0

            #pragma shader_feature _NORMALMAP
            #pragma shader_feature _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
            #pragma shader_feature _METALLICGLOSSMAP
            #pragma shader_feature _ _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
            #pragma shader_feature _ _SPECULARHIGHLIGHTS_OFF
            #pragma shader_feature ___ _DETAIL_MULX2
            // SM2.0: NOT SUPPORTED shader_feature _PARALLAXMAP
            #pragma skip_variants SHADOWS_SOFT

            #pragma multi_compile_fwdadd_fullshadows
            #pragma multi_compile_fog

            #pragma vertex vertAdd
            #pragma fragment fragAdd
            #include "UnityStandardCoreForward.cginc"

            ENDCG
        }
        // ------------------------------------------------------------------
        //  Shadow rendering pass
        Pass {
            Name "ShadowCaster"
            Tags { "LightMode" = "ShadowCaster" }

            ZWrite On ZTest LEqual

            CGPROGRAM
            #pragma target 2.0

            #pragma shader_feature _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
            #pragma shader_feature _METALLICGLOSSMAP
            #pragma shader_feature _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
            #pragma skip_variants SHADOWS_SOFT
            #pragma multi_compile_shadowcaster

            #pragma vertex vertShadowCaster
            #pragma fragment fragShadowCaster

            #include "UnityStandardShadow.cginc"

            ENDCG
        }

        // ------------------------------------------------------------------
        // Extracts information for lightmapping, GI (emission, albedo, ...)
        // This pass it not used during regular rendering.
        Pass
        {
            Name "META"
            Tags { "LightMode"="Meta" }

            Cull Off

            CGPROGRAM
            #pragma vertex vert_meta
            #pragma fragment frag_meta

            #pragma shader_feature _EMISSION
            #pragma shader_feature _METALLICGLOSSMAP
            #pragma shader_feature _ _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
            #pragma shader_feature ___ _DETAIL_MULX2
            #pragma shader_feature EDITOR_VISUALIZATION

            #include "UnityStandardMeta.cginc"
            ENDCG
        }
    }


    FallBack "VertexLit"
    //CustomEditor "StandardShaderGUI"
}

      PS:本来想把CompareFunction和PassFunction做成Enum标签,结果发现shader的Enum标签不支持超过7个,算是新发现。
      一般情况standard材质够场景制作了,这个材质赋予球体。
      接下来按照以前的做法写一个StencilMaskShader

Shader "StencilDemo/StencilMaskShader"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
    }

    SubShader
    {
        LOD 100

        Pass
        {
            Tags { "RenderType"="Opaque" }

            ColorMask 0

            Stencil
			{
				Ref 1
				Comp Always    //(Disable,0,Never,1,Less,2,Equal,3,LessEqual,4,Greater,5,NotEqual,6,GreaterEqual,7,Always,8)
				Pass Replace   //(Keep,0,Zero,1,Replace,2,IncrSat,3,DecrSat,4,Invert,5,IncrWrap,6,DecrWrap,7)
			}

            ZWrite Off
            ZTest Off
        }
    }
}

      这个用于立方体,置换立方体蒙版区域的stencilvalue,用于显示球体。设置好球体的renderqueue>立方体的renderqueue。效果如下:
在这里插入图片描述

      因为模板测试位于图形流水线片段处理阶段,所以看到的效果就如同球体投影到平面上遮罩显示一样,我们想要立体感的话可以用两种方案。

      一.填充立方体剖面

Shader "StencilDemo/ZTestUnlitShader"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
    }
    SubShader
    {
        Tags { "RenderType"="Opaque+20" }
        LOD 100

        Pass
        {
            ZTest Greater
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
            };

            sampler2D _MainTex;
            float4 _MainTex_ST;

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = TRANSFORM_TEX(v.uv, _MainTex);
                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                fixed4 col = tex2D(_MainTex, i.uv);
                return col;
            }
            ENDCG
        }
    }
}

      这里设置渲染立方体剖面材质的renderqueue>球体renderqueue,同时设定ZTest Greater,这样就能显示出立方体被球体遮挡的区域,就能形成填充剖面。效果如下:
在这里插入图片描述

      这个技术和以前切水果游戏一样,无非切水果的剖面纹理使用了相应的水果内部纹理。
      PS:当然用Texture3D来进行填充剖面,也是很好的想法。
      第二种方法性能要求高一点,但是也有很多应用的地方,后面有时间再写。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1675061.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

好用无广的桌面便签app 能管理待办事项的便签软件

在忙碌的工作和生活中,我们每天都面临着大量的待办事项。这些琐碎却重要的事务很容易混淆或遗忘,给我们带来不必要的麻烦和压力。幸运的是,选择一款优秀的便签app,可以有效地帮助我们管理这些待办事项,让工作和生活更加…

CVE-2024-4761 Chrome 的 JavaScript 引擎 V8 中的“越界写入”缺陷

分析 CVE-2024-4761 和 POC 代码 CVE-2024-4761 描述 CVE-2024-4761 是一个在 V8 引擎中发现的越界写漏洞,报告日期为 2024-05-09。这个漏洞可能允许攻击者通过特制的代码执行任意代码或者造成内存破坏,进而导致程序崩溃或其他不安全行为。 POC 代码解…

干部管理系统的功能解析

在日益复杂的组织运营环境中,干部管理系统已成为组织人事部门不可或缺的得力助手。该系统集成了多项先进功能,极大地提升了干部信息的全面管理、选拔任用、培训发展等工作的便捷性和效率。以下是对干部管理系统主要功能的深入解析。 一、信息管理功能 …

CH340 RTS DTR引脚编程驱动OLED

运行结果 硬件连接(在连接线上串接300R电阻) 下面是c#实现代码 using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks;using uint8 System.Byt…

小米、西圣、罗马仕充电宝怎么选?哪个牌子好?一篇教会你选!

随着移动设备的普及,充电宝已经成为现代人生活中不可或缺的便携式充电解决方案。在诸多品牌中,小米、西圣、罗马仕等充电宝备受消费者喜爱,各具特色。今天将为大家带来这三款充电宝的一个详细测评对比,方便大家在选购时能够提供有…

生产环境磁盘变更方案

datanode磁盘扩容(1人天) 扩容磁盘 1.1 扩容前检查、新盘初始化 确定block副本统计正常,无丢块,无under-replicated 块 后台执行命令检查 hdfs dfs fsck / 无异常可进行以下步骤进行磁盘扩容 新盘初始化 ##格式化新盘,命令示例: mkfs.xfs /dev/sdc##挂载新盘,命令示…

在 CSS 中使用 text-emphasis 来增强文本的趣味性

在CSS中设置文本样式的方法有很多。您可以更改颜色、大小、字体,甚至添加阴影和轮廓等效果。但最近,我了解到一个我以前没有听说过的时尚 CSS 属性,它非常棒! 它被称为文本强调(text-emphasis)&#xff0c…

Cartographer前后端梳理

0. 简介 最近在研究整个SLAM框架的改进处,想着能不能从Cartographer中找到一些亮点可以用于参考。所以这一篇博客希望能够梳理好Cartographer前后端优化,并从中得到一些启发。carto整体是graph-based框架,前端是scan-map匹配,后端…

安卓APP+TCP+服务器端

1、在.xml文件中添加权限 <uses-permission android:name"android.permission.ACCESS_WIFI_STATE"/><uses-permission android:name"android.permission.INTERNET"/>2、修改显示界面 <?xml version"1.0" encoding"utf-8&…

C++11续——智能指针(出现原因至源码模拟)

前言&#xff1a;在C11里面提出了一个新的语法 try catch用来捕捉异常&#xff0c;这样子能不使用return和exit的前提下退出程序就得到错误信息&#xff0c;但是随之而来的就是一个新的问题&#xff0c;try catch退出程序之后可能带来了无法释放的内存泄露问题&#xff0c;原因…

资料同化 | 搭建docker环境-1

Community Gridpoint Statistical Interpolation (GSI) system DTC 是一个分布式设施&#xff0c;NWP 社区可以在这里测试和评估用于研究和操作的新模型和技术。 DTC的目标包括&#xff1a; 链接研究和操作社区 研究成果转化为实际操作的速度 加快改善天气预报 开发和测试有…

NSSCTF | [SWPUCTF 2021 新生赛]babyrce

打开题目&#xff0c;显示了一个php脚本 我们来分析一下这个脚本是什么意思 <?php error_reporting(0); header("Content-Type:text/html;charsetutf-8"); highlight_file(__FILE__); if($_COOKIE[admin]1) {include "../next.php"; } elseecho &quo…

深入解析RedisJSON:在Redis中直接处理JSON数据

码到三十五 &#xff1a; 个人主页 JSON已经成为现代应用程序之间数据传输的通用格式。然而&#xff0c;传统的关系型数据库在处理JSON数据时可能会遇到性能瓶颈。为了解决这一问题&#xff0c;Redis推出了RedisJSON模块&#xff0c;它允许开发者在Redis数据库中直接存储、查询…

Ceph集群扩容及数据再均衡原理分析

用户文件在Ceph RADOS中存储、定位过程大概包括&#xff1a;用户文件切割成对象、对象映射到PG、PG分组PGP、PG映射到OSD。这些过程中&#xff0c;可能涉及了大量概念和变量&#xff0c;而其实它们大部分是通过HASH、CRUSH等算法计算出来的&#xff0c;初始参数可能也就只有这么…

号卡极团分销管理系统 ue_serve.php 任意文件上传漏洞复现

0x01 产品简介 号卡极团分销管理系统,同步对接多平台,同步订单信息,支持敢探号一键上架,首页多套UI+商品下单页多套模板,订单查询支持实时物流信息、支持代理商自定义域名、泛域名绑定,内置敢探号、172平台、号氪云平台第三方接口以及号卡网同系统对接! 0x02 漏洞概述…

caj文件是什么?caj是什么文件?考研学生赶紧收藏!

在学术研究的广阔领域中&#xff0c;尤其是对于那些致力于深入研究、不断拓宽知识边界的考研学子们来说&#xff0c;了解并掌握各种学术资源的获取与利用方法显得尤为重要。其中&#xff0c;CAJ文件作为一种常见的学术文件格式&#xff0c;其重要性和使用频率不容忽视。那么&am…

在Linux上安装并启动Redis

目录 安装gcc环境 上传redis文件 启动redis-server 后台启动redis-server 查看redis启动状态 参考文章&#xff1a;Linux 安装 Redis 及踩坑 - 敲代码的阿磊 - 博客园 (cnblogs.com) 准备&#xff1a;打开VMware Workstation&#xff0c;创建一个虚拟机&#xff0c;进入管…

FinnConverter格式转换工具

FinnConverter简介 1. 简洁的操作界面 2. 支持多种格式相互转换 支持word转pdf&#xff1b;ppt转pdf&#xff1b;raw格式转png/jpng…&#xff1b;其他格式相互转换 2.1 输入格式支持 bmp、cr2、cr3、crw、cur、dcr、dng、doc、docx、gif、ico、jpeg、jpg、kdc、mos、nef、…

具身智能论文(四)

目录 1. Alexa Arena: A User-Centric Interactive Platform for Embodied AI2. EDGI: Equivariant Diffusion for Planning with Embodied Agents3. Efficient Policy Adaptation with Contrastive Prompt Ensemble for Embodied Agents4. Egocentric Planning for Scalable E…

ICode国际青少年编程竞赛- Python-5级训练场-综合练习5

ICode国际青少年编程竞赛- Python-5级训练场-综合练习5 1、 a 16 for i in range(6):Dev.step(1)Dev.turnLeft()Dev.step(a)Dev.step(-a)Dev.turnRight()while Dev.energy < 100:wait()Dev.step(1)a a - 5 i2、 for i in range(5):Dev.step(11 - i * 2)Dev.turnRight()wh…