Ejemplo n.º 1
0
    void CreateNormalizedUVMatrix()
    {
        MaterialPropertyBlock mpb = new MaterialPropertyBlock();
        Renderer rend             = GetComponent <Renderer>();

        rend.GetPropertyBlock(mpb);
        Sprite sp = GetComponent <SpriteRenderer>().sprite;

        Rect r = sp.rect;

        r.x      /= sp.texture.width;
        r.y      /= sp.texture.height;
        r.width  /= sp.texture.width;
        r.height /= sp.texture.height;

        Vector3   scale     = new Vector3((1.0f / r.width), 1.0f / r.height - 2, 1);
        Matrix4x4 uv0ToRect =
            Matrix4x4.TRS(new Vector3(-r.x * scale.x, -r.y * scale.y - 1, 0), Quaternion.identity, scale);

        mpb.SetMatrix("_TextureRotation", uv0ToRect);
        rend.SetPropertyBlock(mpb);

        //lightMaterial.SetMatrix("_TextureRotation", uv0ToRect);
    }
Ejemplo n.º 2
0
    // Update is called once per frame
    void Update()
    {
        Lod_0_positionBuffer.SetCounterValue(0);
        Lod_1_positionBuffer.SetCounterValue(0);
        Lod_2_positionBuffer.SetCounterValue(0);
        Lod_3_positionBuffer.SetCounterValue(0);
        Lod_4_positionBuffer.SetCounterValue(0);

        pearlsInstancerCS.SetFloat("_gridSizeURcp", 1.0f / PearlsUResolution);
        pearlsInstancerCS.SetFloat("_gridSizeVRcp", 1.0f / PearlsVResolution);
        pearlsInstancerCS.SetFloat("_pearlScale", PearlScale);
        pearlsInstancerCS.SetFloat("_normalOffset", NormalOffset);
        pearlsInstancerCS.SetFloat("_minU", MinU);
        pearlsInstancerCS.SetFloat("_minV", MinV);
        pearlsInstancerCS.SetFloat("_maxU", MaxU);
        pearlsInstancerCS.SetFloat("_maxV", MaxV);
        pearlsInstancerCS.SetFloat("_time", timelineTime);

        pearlsInstancerCS.SetFloat("_Lod_0_distance", Lod_0_distance);
        pearlsInstancerCS.SetFloat("_Lod_1_distance", Lod_1_distance);
        pearlsInstancerCS.SetFloat("_Lod_2_distance", Lod_2_distance);
        pearlsInstancerCS.SetFloat("_Lod_3_distance", Lod_3_distance);
        pearlsInstancerCS.SetFloat("_Lod_4_distance", Lod_4_distance);

        pearlsInstancerCS.SetVector("_cameraWorldPos", Camera.main.transform.position);

        Matrix4x4 matrix = transform.localToWorldMatrix;

        floatMatrix[0] = matrix[0, 0];
        floatMatrix[1] = matrix[1, 0];
        floatMatrix[2] = matrix[2, 0];
        floatMatrix[3] = matrix[3, 0];

        floatMatrix[4] = matrix[0, 1];
        floatMatrix[5] = matrix[1, 1];
        floatMatrix[6] = matrix[2, 1];
        floatMatrix[7] = matrix[3, 1];

        floatMatrix[8]  = matrix[0, 2];
        floatMatrix[9]  = matrix[1, 2];
        floatMatrix[10] = matrix[2, 2];
        floatMatrix[11] = matrix[3, 2];

        floatMatrix[12] = matrix[0, 3];
        floatMatrix[13] = matrix[1, 3];
        floatMatrix[14] = matrix[2, 3];
        floatMatrix[15] = matrix[3, 3];

        pearlsInstancerCS.SetFloats("_instancerMatrix", floatMatrix);

        if (inMeshTransform)
        {
            matrix = inMeshTransform.localToWorldMatrix;
        }
        else
        {
            matrix = Matrix4x4.identity;
        }

        floatMatrix[0] = matrix[0, 0];
        floatMatrix[1] = matrix[1, 0];
        floatMatrix[2] = matrix[2, 0];
        floatMatrix[3] = matrix[3, 0];

        floatMatrix[4] = matrix[0, 1];
        floatMatrix[5] = matrix[1, 1];
        floatMatrix[6] = matrix[2, 1];
        floatMatrix[7] = matrix[3, 1];

        floatMatrix[8]  = matrix[0, 2];
        floatMatrix[9]  = matrix[1, 2];
        floatMatrix[10] = matrix[2, 2];
        floatMatrix[11] = matrix[3, 2];

        floatMatrix[12] = matrix[0, 3];
        floatMatrix[13] = matrix[1, 3];
        floatMatrix[14] = matrix[2, 3];
        floatMatrix[15] = matrix[3, 3];

        pearlsInstancerCS.SetFloats("_meshMatrix", floatMatrix);

        if (inMesh)
        {
            pearlsInstancerCS.SetBuffer(kernelMainForMesh, "Lod_0_positions", Lod_0_positionBuffer);
            pearlsInstancerCS.SetBuffer(kernelMainForMesh, "Lod_1_positions", Lod_1_positionBuffer);
            pearlsInstancerCS.SetBuffer(kernelMainForMesh, "Lod_2_positions", Lod_2_positionBuffer);
            pearlsInstancerCS.SetBuffer(kernelMainForMesh, "Lod_3_positions", Lod_3_positionBuffer);
            pearlsInstancerCS.SetBuffer(kernelMainForMesh, "Lod_4_positions", Lod_4_positionBuffer);
        }
        else
        {
            pearlsInstancerCS.SetBuffer(kernelMain, "Lod_0_positions", Lod_0_positionBuffer);
            pearlsInstancerCS.SetBuffer(kernelMain, "Lod_1_positions", Lod_1_positionBuffer);
            pearlsInstancerCS.SetBuffer(kernelMain, "Lod_2_positions", Lod_2_positionBuffer);
            pearlsInstancerCS.SetBuffer(kernelMain, "Lod_3_positions", Lod_3_positionBuffer);
            pearlsInstancerCS.SetBuffer(kernelMain, "Lod_4_positions", Lod_4_positionBuffer);
        }

        if (Colliders.Length > 0)
        {
            int i = 0;
            foreach (var go in Colliders)
            {
                if (go.activeInHierarchy)
                {
                    collidersData[i].position  = transform.worldToLocalMatrix.MultiplyPoint(go.transform.position);
                    collidersData[i].influence = 1.0f / ColliderInfluence;
                    i++;
                }
            }
            pearlsInstancerCS.SetInt("_numberOfColliders", i);

            collidersBuffer.SetData(collidersData);
            if (inMesh)
            {
                pearlsInstancerCS.SetBuffer(kernelMainForMesh, "colliders", collidersBuffer);
            }
            else
            {
                pearlsInstancerCS.SetBuffer(kernelMain, "colliders", collidersBuffer);
            }
        }
        else
        {
            pearlsInstancerCS.SetInt("_numberOfColliders", 0);
        }


        if (inMesh)
        {
            pearlsInstancerCS.Dispatch(kernelMainForMesh, inMesh.vertexCount / 64, 1, 1);
        }
        else
        {
            pearlsInstancerCS.Dispatch(kernelMain, PearlsUResolution / 8, PearlsVResolution / 8, 1);
        }

        ComputeBuffer.CopyCount(Lod_0_positionBuffer, Lod_0_instancesArgBuffer, 4);
        ComputeBuffer.CopyCount(Lod_1_positionBuffer, Lod_1_instancesArgBuffer, 4);
        ComputeBuffer.CopyCount(Lod_2_positionBuffer, Lod_2_instancesArgBuffer, 4);
        ComputeBuffer.CopyCount(Lod_3_positionBuffer, Lod_3_instancesArgBuffer, 4);
        ComputeBuffer.CopyCount(Lod_4_positionBuffer, Lod_4_instancesArgBuffer, 4);

        /*        int[] args2 = new int[] { 0, 1, 0, 0, 0 };
         *      Lod_0_instancesArgBuffer.GetData(args2);
         *      Debug.Log("Lod_0_instancesArgBuffer Indices count:" + args2[0] + " Indstances count:" + args2[1]);
         *      Lod_1_instancesArgBuffer.GetData(args2);
         *      Debug.Log("Lod_1_instancesArgBuffer Indices count:" + args2[0] + " Indstances count:" + args2[1]);
         *      Lod_2_instancesArgBuffer.GetData(args2);
         *      Debug.Log("Lod_2_instancesArgBuffer Indices count:" + args2[0] + " Indstances count:" + args2[1]);
         *      Lod_3_instancesArgBuffer.GetData(args2);
         *      Debug.Log("Lod_3_instancesArgBuffer Indices count:" + args2[0] + " Indstances count:" + args2[1]);
         *      Lod_4_instancesArgBuffer.GetData(args2);
         *      Debug.Log("Lod_4_instancesArgBuffer Indices count:" + args2[0] + " Indstances count:" + args2[1]);
         */
        mat.SetPass(0);

        matPropertyBlock_lod0.SetBuffer("positions", Lod_0_positionBuffer);
        matPropertyBlock_lod1.SetBuffer("positions", Lod_1_positionBuffer);
        matPropertyBlock_lod2.SetBuffer("positions", Lod_2_positionBuffer);
        matPropertyBlock_lod3.SetBuffer("positions", Lod_3_positionBuffer);
        matPropertyBlock_lod4.SetBuffer("positions", Lod_4_positionBuffer);

        if (inMesh)
        {
            meshBounds = inMesh.bounds;
            if (inMeshTransform)
            {
                meshBounds.center = inMeshTransform.position;
            }

            Matrix4x4 transformedMatrix = Matrix4x4.Translate(-meshBounds.center) * Matrix4x4.Inverse(transform.localToWorldMatrix) * transform.localToWorldMatrix;

            matPropertyBlock_lod0.SetMatrix("_LocalToWorld", transformedMatrix);
            matPropertyBlock_lod1.SetMatrix("_LocalToWorld", transformedMatrix);
            matPropertyBlock_lod2.SetMatrix("_LocalToWorld", transformedMatrix);
            matPropertyBlock_lod3.SetMatrix("_LocalToWorld", transformedMatrix);
            matPropertyBlock_lod4.SetMatrix("_LocalToWorld", transformedMatrix);
        }
        else
        {
            Matrix4x4 transformedMatrix = Matrix4x4.Translate(-meshBounds.center - transform.position) * transform.localToWorldMatrix;

            matPropertyBlock_lod0.SetMatrix("_LocalToWorld", transformedMatrix);
            matPropertyBlock_lod1.SetMatrix("_LocalToWorld", transformedMatrix);
            matPropertyBlock_lod2.SetMatrix("_LocalToWorld", transformedMatrix);
            matPropertyBlock_lod3.SetMatrix("_LocalToWorld", transformedMatrix);
            matPropertyBlock_lod4.SetMatrix("_LocalToWorld", transformedMatrix);
        }

        bounds.size   = meshBounds.size;
        bounds.center = transform.position + meshBounds.center;

        Graphics.DrawMeshInstancedIndirect(
            Lod_0_mesh, 0, mat,
            bounds,
            Lod_0_instancesArgBuffer, 0, matPropertyBlock_lod0);

        Graphics.DrawMeshInstancedIndirect(
            Lod_1_mesh, 0, mat,
            bounds,
            Lod_1_instancesArgBuffer, 0, matPropertyBlock_lod1);

        Graphics.DrawMeshInstancedIndirect(
            Lod_2_mesh, 0, mat,
            bounds,
            Lod_2_instancesArgBuffer, 0, matPropertyBlock_lod2);

        Graphics.DrawMeshInstancedIndirect(
            Lod_3_mesh, 0, mat,
            bounds,
            Lod_3_instancesArgBuffer, 0, matPropertyBlock_lod3);

        Graphics.DrawMeshInstancedIndirect(
            Lod_4_mesh, 0, mat,
            bounds,
            Lod_4_instancesArgBuffer, 0, matPropertyBlock_lod4);
    }
Ejemplo n.º 3
0
 public override void SetOn(MaterialPropertyBlock block) => block.SetMatrix(id, latestValue);
Ejemplo n.º 4
0
        public void RenderVehicle(VehicleInfo info, Color color, bool useColor = true)
        {
            InfoManager infoManager = Singleton <InfoManager> .instance;

            InfoManager.InfoMode    currentMod    = infoManager.CurrentMode;
            InfoManager.SubInfoMode currentSubMod = infoManager.CurrentSubMode;;
            infoManager.SetCurrentMode(InfoManager.InfoMode.None, InfoManager.SubInfoMode.Default);
            infoManager.UpdateInfoMode();

            Light   sunLight       = DayNightProperties.instance.sunLightSource;
            float   lightIntensity = sunLight.intensity;
            Color   lightColor     = sunLight.color;
            Vector3 lightAngles    = sunLight.transform.eulerAngles;

            sunLight.intensity             = 2f;
            sunLight.color                 = Color.white;
            sunLight.transform.eulerAngles = new Vector3(50, 180, 70);

            Light mainLight = RenderManager.instance.MainLight;

            RenderManager.instance.MainLight = sunLight;

            if (mainLight == DayNightProperties.instance.moonLightSource)
            {
                DayNightProperties.instance.sunLightSource.enabled  = true;
                DayNightProperties.instance.moonLightSource.enabled = false;
            }

            Vector3 one = Vector3.one;

            float magnitude = info.m_mesh.bounds.extents.magnitude;
            float num       = magnitude + 16f;
            float num2      = magnitude * m_zoom;

            m_camera.transform.position = Vector3.forward * num2;
            m_camera.transform.rotation = Quaternion.AngleAxis(180, Vector3.up);
            m_camera.nearClipPlane      = Mathf.Max(num2 - num * 1.5f, 0.01f);
            m_camera.farClipPlane       = num2 + num * 1.5f;

            Quaternion rotation = Quaternion.Euler(20f, 0f, 0f) * Quaternion.Euler(0f, m_rotation, 0f);
            Vector3    position = rotation * -info.m_mesh.bounds.center;

            Vector3 swayPosition = Vector3.zero;

            VehicleManager instance   = Singleton <VehicleManager> .instance;
            Matrix4x4      matrixBody = Matrix4x4.TRS(position, rotation, Vector3.one);
            Matrix4x4      matrixTyre = info.m_vehicleAI.CalculateTyreMatrix(Vehicle.Flags.Created, ref position, ref rotation, ref one, ref matrixBody);

            MaterialPropertyBlock materialBlock = instance.m_materialBlock;

            materialBlock.Clear();
            materialBlock.SetMatrix(instance.ID_TyreMatrix, matrixTyre);
            materialBlock.SetVector(instance.ID_TyrePosition, Vector3.zero);
            materialBlock.SetVector(instance.ID_LightState, Vector3.zero);
            if (useColor)
            {
                materialBlock.SetColor(instance.ID_Color, color);
            }

            instance.m_drawCallData.m_defaultCalls = instance.m_drawCallData.m_defaultCalls + 1;

            info.m_material.SetVectorArray(instance.ID_TyreLocation, info.m_generatedInfo.m_tyres);
            Graphics.DrawMesh(info.m_mesh, matrixBody, info.m_material, 0, m_camera, 0, materialBlock, true, true);

            m_camera.RenderWithShader(info.m_material.shader, "");

            sunLight.intensity             = lightIntensity;
            sunLight.color                 = lightColor;
            sunLight.transform.eulerAngles = lightAngles;

            RenderManager.instance.MainLight = mainLight;

            if (mainLight == DayNightProperties.instance.moonLightSource)
            {
                DayNightProperties.instance.sunLightSource.enabled  = false;
                DayNightProperties.instance.moonLightSource.enabled = true;
            }

            infoManager.SetCurrentMode(currentMod, currentSubMod);
            infoManager.UpdateInfoMode();
        }
Ejemplo n.º 5
0
        protected override Matrix4x4 RenderMesh(VehicleInfo info, BoardTextDescriptorGeneralXml[] textDescriptors, Vector3 position, Quaternion rotation, Vector3 scale, Matrix4x4 sourceMatrix, out Color targetColor, ref int defaultCallsCounter)
        {
            targetColor = WTSDynamicTextRenderingRules.GetPropColor(0, 0, 0, m_defaultInstance, null, out _);
            VehicleManager        instance2     = Singleton <VehicleManager> .instance;
            Matrix4x4             matrix        = Matrix4x4.TRS(position, rotation, scale) * sourceMatrix;
            Matrix4x4             value         = info.m_vehicleAI.CalculateTyreMatrix(Vehicle.Flags.Created, ref position, ref rotation, ref scale, ref matrix);
            MaterialPropertyBlock materialBlock = instance2.m_materialBlock;

            materialBlock.Clear();
            materialBlock.SetMatrix(instance2.ID_TyreMatrix, value);
            materialBlock.SetVector(instance2.ID_TyrePosition, Vector3.zero);
            materialBlock.SetVector(instance2.ID_LightState, Vector3.zero);
            materialBlock.SetColor(instance2.ID_Color, targetColor * new Color(1, 1, 1, 0));
            instance2.m_drawCallData.m_batchedCalls += 1;
            info.m_material.SetVectorArray(instance2.ID_TyreLocation, info.m_generatedInfo.m_tyres);
            defaultCallsCounter++;
            Graphics.DrawMesh(GetMesh(info), matrix, GetMaterial(info), info.m_prefabDataLayer, m_camera, 0, materialBlock, true, true);

            for (int j = 0; j < info.m_subMeshes.Length; j++)
            {
                VehicleInfo.MeshInfo meshInfo = info.m_subMeshes[j];
                var subInfo = meshInfo.m_subInfo as VehicleInfoSub;
                if (subInfo != null && (meshInfo.m_vehicleFlagsRequired & Vehicle.Flags.LeftHandDrive) == 0)
                {
                    VehicleManager.instance.m_drawCallData.m_batchedCalls = VehicleManager.instance.m_drawCallData.m_batchedCalls + 1;

                    subInfo.m_material.SetVectorArray(VehicleManager.instance.ID_TyreLocation, subInfo.m_generatedInfo.m_tyres);
                    defaultCallsCounter++;
                    Graphics.DrawMesh(subInfo.m_mesh, matrix, subInfo.m_material, info.m_prefabDataLayer, null, 0, materialBlock);
                }
            }
            ////Vector3 one = Vector3.one;
            ////float magnitude = info.m_mesh.bounds.extents.magnitude;
            ////float num = magnitude + 16f;
            ////float num2 = magnitude * 3f;
            ////m_camera.transform.position = Vector3.forward * num2;
            ////m_camera.transform.rotation = Quaternion.AngleAxis(180f, Vector3.up);
            ////m_camera.nearClipPlane = Mathf.Max(num2 - num * 1.5f, 0.01f);
            ////m_camera.farClipPlane = num2 + num * 1.5f;
            ////Quaternion quaternion = Quaternion.Euler(20f, 0f, 0f)* rotation;
            ////Vector3 pos = quaternion * -info.m_mesh.bounds.center;
            ////VehicleManager instance2 = Singleton<VehicleManager>.instance;
            ////Matrix4x4 matrix = Matrix4x4.TRS(pos, quaternion, Vector3.one);
            ////Matrix4x4 value = info.m_vehicleAI.CalculateTyreMatrix(Vehicle.Flags.Created, ref pos, ref quaternion, ref one, ref matrix);
            ////MaterialPropertyBlock materialBlock = instance2.m_materialBlock;
            ////materialBlock.Clear();
            ////materialBlock.SetMatrix(instance2.ID_TyreMatrix, value);
            ////materialBlock.SetVector(instance2.ID_TyrePosition, Vector3.zero);
            ////materialBlock.SetVector(instance2.ID_LightState, Vector3.zero);
            ////materialBlock.SetColor(instance2.ID_VehicleColor, targetColor);

            ////instance2.m_drawCallData.m_batchedCalls = instance2.m_drawCallData.m_batchedCalls + 1;
            ////info.m_material.SetVectorArray(instance2.ID_TyreLocation, info.m_generatedInfo.m_tyres);
            ///defaultCallsCounter++;
            ////Graphics.DrawMesh(info.m_mesh, matrix, info.m_material, 0, m_camera, 0, materialBlock, true, true);

            ////m_camera.Render();


            return(matrix);
        }
Ejemplo n.º 6
0
        public void SetupLocalToTerrainMatrix(MaterialPropertyBlock props)
        {
            string localToTerrainPropName = "_LocalToTerrainMatrix";

            props.SetMatrix(localToTerrainPropName, LocalToTerrainMatrix);
        }
 public override void Apply(MaterialPropertyBlock materialPropertyBlock)
 {
     materialPropertyBlock.SetMatrix(PropertyId, Value);
 }
Ejemplo n.º 8
0
 public void SetValueOnMaterialPropertyBlock(MaterialPropertyBlock mat)
 {
     if ((propType == PropertyType.Texture2D || propType == PropertyType.Texture2DArray || propType == PropertyType.Texture3D))
     {
         if (m_ClassData.textureValue == null)
         {
             // there's no way to set the texture back to NULL
             // and no way to delete the property either
             // so instead we set the value to what we know the default will be
             // (all textures in ShaderGraph default to white)
             mat.SetTexture(name, Texture2D.whiteTexture);
         }
         else
         {
             mat.SetTexture(name, m_ClassData.textureValue);
         }
     }
     else if (propType == PropertyType.Cubemap)
     {
         if (m_ClassData.cubemapValue == null)
         {
             // there's no way to set the texture back to NULL
             // and no way to delete the property either
             // so instead we set the value to what we know the default will be
             // (all textures in ShaderGraph default to white)
             // there's no Cubemap.whiteTexture, but this seems to work
             mat.SetTexture(name, Texture2D.whiteTexture);
         }
         else
         {
             mat.SetTexture(name, m_ClassData.cubemapValue);
         }
     }
     else if (propType == PropertyType.Color)
     {
         mat.SetColor(name, m_StructData.colorValue);
     }
     else if (propType == PropertyType.Vector2 || propType == PropertyType.Vector3 || propType == PropertyType.Vector4)
     {
         mat.SetVector(name, m_StructData.vector4Value);
     }
     else if (propType == PropertyType.Vector1)
     {
         mat.SetFloat(name, m_StructData.floatValue);
     }
     else if (propType == PropertyType.Boolean)
     {
         mat.SetFloat(name, m_StructData.booleanValue ? 1 : 0);
     }
     else if (propType == PropertyType.Matrix2 || propType == PropertyType.Matrix3 || propType == PropertyType.Matrix4)
     {
         mat.SetMatrix(name, m_StructData.matrixValue);
     }
     else if (propType == PropertyType.Gradient)
     {
         mat.SetFloat(string.Format("{0}_Type", name), (int)m_ClassData.gradientValue.mode);
         mat.SetFloat(string.Format("{0}_ColorsLength", name), m_ClassData.gradientValue.colorKeys.Length);
         mat.SetFloat(string.Format("{0}_AlphasLength", name), m_ClassData.gradientValue.alphaKeys.Length);
         for (int i = 0; i < 8; i++)
         {
             mat.SetVector(string.Format("{0}_ColorKey{1}", name, i), i < m_ClassData.gradientValue.colorKeys.Length ? GradientUtil.ColorKeyToVector(m_ClassData.gradientValue.colorKeys[i]) : Vector4.zero);
         }
         for (int i = 0; i < 8; i++)
         {
             mat.SetVector(string.Format("{0}_AlphaKey{1}", name, i), i < m_ClassData.gradientValue.alphaKeys.Length ? GradientUtil.AlphaKeyToVector(m_ClassData.gradientValue.alphaKeys[i]) : Vector2.zero);
         }
     }
     else if (propType == PropertyType.VirtualTexture)
     {
         // virtual texture assignments are not supported via the material property block, we must assign them to the materials
     }
 }
Ejemplo n.º 9
0
        public void AttachDeform(Matrix4x4 partixOrientation)
        {
            Assert.IsTrue(nativePartixSoftVolume != IntPtr.Zero);
            foreach (MeshRenderer r in meshRenderers)
            {
                Transform        t        = r.transform;
                List <Matrix4x4> matrices = new List <Matrix4x4>();
                while (t.gameObject != controlTransform.gameObject)
                {
                    Matrix4x4 mm = Matrix4x4.TRS(
                        t.localPosition, t.localRotation, t.localScale);
                    matrices.Add(mm);
                    t = t.parent;
                }

                Matrix4x4 m = controlTransform.localToWorldMatrix;
                m *= partixOrientation;

                for (int i = 0; i < matrices.Count; i++)
                {
                    m *= matrices[matrices.Count - 1 - i];
                }
                Material material = r.sharedMaterial;

                // TODO: 毎回作ってる
                MaterialPropertyBlock props = new MaterialPropertyBlock();
                props.SetMatrix("_Deform", m);
                props.SetMatrix("_ShadowDeform", m);
                r.SetPropertyBlock(props);
            }
            foreach (SkinnedMeshRenderer r in skinnedMeshRenderers)
            {
                List <Matrix4x4> matrices = new List <Matrix4x4>();

                Transform t = r.rootBone;
                {
                    Matrix4x4 mm = Matrix4x4.TRS(
                        t.localPosition, t.localRotation, new Vector3(1, 1, 1));
                    matrices.Add(mm);
                }

                t = r.transform.parent;
                while (t.gameObject != controlTransform.gameObject)
                {
                    // scaleは自動でかかるらしい
                    Matrix4x4 mm = Matrix4x4.TRS(
                        t.localPosition, t.localRotation, new Vector3(1, 1, 1));
                    matrices.Add(mm);
                    t = t.parent;
                }

                Matrix4x4 m = controlTransform.localToWorldMatrix;
                m *= partixOrientation;

                for (int i = 0; i < matrices.Count; i++)
                {
                    m *= matrices[matrices.Count - 1 - i];
                }
                Material material = r.sharedMaterial;

                forDebug = m;

                // TODO: 毎回作ってる
                MaterialPropertyBlock props = new MaterialPropertyBlock();
                props.SetMatrix("_Deform", m);
                props.SetMatrix("_ShadowDeform", m);
                r.SetPropertyBlock(props);
            }
        }
        // 'renderSunDisk' parameter is not supported.
        // Users should instead create an emissive (or lit) mesh for every relevant light source
        // (to support multiple stars in space, moons with moon phases, etc).
        public override void RenderSky(BuiltinSkyParameters builtinParams, bool renderForCubemap, bool renderSunDisk)
        {
            CommandBuffer cmd = builtinParams.commandBuffer;

            UpdateGlobalConstantBuffer(cmd);

            int currentParamHash = m_Settings.GetHashCode();

            if (currentParamHash != m_LastPrecomputationParamHash)
            {
                // Hash does not match, have to restart the precomputation from scratch.
                m_LastPrecomputedBounce = 0;
            }

            // F**k cubemap.
            if (!renderForCubemap)
            {
                if (m_LastPrecomputedBounce == 0)
                {
                    // Allocate temp tables if needed
                    if (m_GroundIrradianceTables[1] == null)
                    {
                        m_GroundIrradianceTables[1] = AllocateGroundIrradianceTable(1);
                    }

                    if (m_InScatteredRadianceTables[3] == null)
                    {
                        m_InScatteredRadianceTables[3] = AllocateInScatteredRadianceTable(3);
                    }

                    if (m_InScatteredRadianceTables[4] == null)
                    {
                        m_InScatteredRadianceTables[4] = AllocateInScatteredRadianceTable(4);
                    }
                }

                if (m_LastPrecomputedBounce == m_Settings.numBounces.value)
                {
                    // Free temp tables.
                    // This is a deferred release (one frame late)!
                    RTHandles.Release(m_GroundIrradianceTables[1]);
                    RTHandles.Release(m_InScatteredRadianceTables[3]);
                    RTHandles.Release(m_InScatteredRadianceTables[4]);
                    m_GroundIrradianceTables[1]    = null;
                    m_InScatteredRadianceTables[3] = null;
                    m_InScatteredRadianceTables[4] = null;
                }

                if (m_LastPrecomputedBounce < m_Settings.numBounces.value)
                {
                    // We precompute one bounce per render call.
                    PrecomputeTables(cmd);
                    m_LastPrecomputedBounce++;

                    // Update the hash for the current bounce.
                    m_LastPrecomputationParamHash = currentParamHash;
                }
            }

            // Precomputation is done, shading is next.
            Quaternion planetRotation = Quaternion.Euler(m_Settings.planetRotation.value.x,
                                                         m_Settings.planetRotation.value.y,
                                                         m_Settings.planetRotation.value.z);

            Quaternion spaceRotation = Quaternion.Euler(m_Settings.spaceRotation.value.x,
                                                        m_Settings.spaceRotation.value.y,
                                                        m_Settings.spaceRotation.value.z);

            // This matrix needs to be updated at the draw call frequency.
            s_PbrSkyMaterialProperties.SetMatrix(HDShaderIDs._PixelCoordToViewDirWS, builtinParams.pixelCoordToViewDirMatrix);
            s_PbrSkyMaterialProperties.SetMatrix(HDShaderIDs._PlanetRotation, Matrix4x4.Rotate(planetRotation));
            s_PbrSkyMaterialProperties.SetMatrix(HDShaderIDs._SpaceRotation, Matrix4x4.Rotate(spaceRotation));

            if (m_LastPrecomputedBounce != 0)
            {
                s_PbrSkyMaterialProperties.SetTexture(HDShaderIDs._OpticalDepthTexture, m_OpticalDepthTable);
                s_PbrSkyMaterialProperties.SetTexture(HDShaderIDs._GroundIrradianceTexture, m_GroundIrradianceTables[0]);
                s_PbrSkyMaterialProperties.SetTexture(HDShaderIDs._AirSingleScatteringTexture, m_InScatteredRadianceTables[0]);
                s_PbrSkyMaterialProperties.SetTexture(HDShaderIDs._AerosolSingleScatteringTexture, m_InScatteredRadianceTables[1]);
                s_PbrSkyMaterialProperties.SetTexture(HDShaderIDs._MultipleScatteringTexture, m_InScatteredRadianceTables[2]);
            }
            else
            {
                s_PbrSkyMaterialProperties.SetTexture(HDShaderIDs._OpticalDepthTexture, Texture2D.blackTexture);
                s_PbrSkyMaterialProperties.SetTexture(HDShaderIDs._GroundIrradianceTexture, Texture2D.blackTexture);
                s_PbrSkyMaterialProperties.SetTexture(HDShaderIDs._AirSingleScatteringTexture, CoreUtils.blackVolumeTexture);
                s_PbrSkyMaterialProperties.SetTexture(HDShaderIDs._AerosolSingleScatteringTexture, CoreUtils.blackVolumeTexture);
                s_PbrSkyMaterialProperties.SetTexture(HDShaderIDs._MultipleScatteringTexture, CoreUtils.blackVolumeTexture);
            }

            int hasGroundAlbedoTexture = 0;

            if (m_Settings.groundAlbedoTexture.value != null)
            {
                hasGroundAlbedoTexture = 1;
                s_PbrSkyMaterialProperties.SetTexture(HDShaderIDs._GroundAlbedoTexture, m_Settings.groundAlbedoTexture.value);
            }
            s_PbrSkyMaterialProperties.SetInt(HDShaderIDs._HasGroundAlbedoTexture, hasGroundAlbedoTexture);

            int hasGroundEmissionTexture = 0;

            if (m_Settings.groundEmissionTexture.value != null)
            {
                hasGroundEmissionTexture = 1;
                s_PbrSkyMaterialProperties.SetTexture(HDShaderIDs._GroundEmissionTexture, m_Settings.groundEmissionTexture.value);
            }
            s_PbrSkyMaterialProperties.SetInt(HDShaderIDs._HasGroundEmissionTexture, hasGroundEmissionTexture);

            int hasSpaceEmissionTexture = 0;

            if (m_Settings.spaceEmissionTexture.value != null)
            {
                hasSpaceEmissionTexture = 1;
                s_PbrSkyMaterialProperties.SetTexture(HDShaderIDs._SpaceEmissionTexture, m_Settings.spaceEmissionTexture.value);
            }
            s_PbrSkyMaterialProperties.SetInt(HDShaderIDs._HasSpaceEmissionTexture, hasSpaceEmissionTexture);

            CoreUtils.DrawFullScreen(builtinParams.commandBuffer, s_PbrSkyMaterial, s_PbrSkyMaterialProperties, renderForCubemap ? 0 : 1);
        }
Ejemplo n.º 11
0
    private void UpdateMaterial(float deltaTime)
    {
        int frameIndex = GetFrameIndex();

        if (lastPlayingClip == playingClip && lastPlayingFrameIndex == frameIndex)
        {
            return;
        }

        lastPlayingClip       = playingClip;
        lastPlayingFrameIndex = frameIndex;

        bool         isCrossBlending      = IsCrossFadeBlending(lastPlayedClip, crossFadeTime, crossFadeProgress);
        int          frameIndexCrossFade  = -1;
        GPUSkinFrame frameCrossFade       = null;
        float        crossFadeBlendFactor = 1;
        bool         isRootMotion         = playingClip.rootMotionEnabled && RootMotionEnabled;
        GPUSkinFrame frame = playingClip.frames[frameIndex];

        if (isCrossBlending)
        {
            frameIndexCrossFade  = GetCrossFadeFrameIndex();
            frameCrossFade       = lastPlayedClip.frames[frameIndexCrossFade];
            crossFadeBlendFactor = Mathf.Clamp01(crossFadeProgress / crossFadeTime);
        }

        //if (Visible || CullingMode == GPUSkinCullingMode.AlwaysAnimate)
        if (CullingMode == GPUSkinCullingMode.AlwaysAnimate)
        {
            mpb.SetVector(shaderPorpID_GPUSkin_FrameIndex_PixelSegmentation, new Vector4(frameIndex, playingClip.pixelSegmentation, 0, 0));
            if (isRootMotion)
            {
                Matrix4x4 rootMotionInv = animData.rootTransformMatrix * frame.RootMotionInv(animData.rootBoneIndex);
                //Matrix4x4 rootMotionInv = frame.RootMotionInv(animData.rootBoneIndex);
                mpb.SetMatrix(shaderPorpID_GPUSkin_RootMotion, rootMotionInv);
            }
            else
            {
                mpb.SetMatrix(shaderPorpID_GPUSkin_RootMotion, Matrix4x4.identity);
            }

            if (isCrossBlending)
            {
                mpb.SetVector(shaderPorpID_GPUSkin_FrameIndex_PixelSegmentation_Blend_CrossFade, new Vector4(frameIndexCrossFade, lastPlayedClip.pixelSegmentation, crossFadeBlendFactor));
            }
            else
            {
                mpb.SetVector(shaderPorpID_GPUSkin_FrameIndex_PixelSegmentation_Blend_CrossFade, new Vector4(0, 0, 1));
            }

            meshRender.SetPropertyBlock(mpb);
        }

        if (isRootMotion && deltaTime > 0)
        {
            if (CullingMode != GPUSkinCullingMode.CullCompletely)
            {
                DoRootMotion(deltaTime);
            }
        }
    }
        // Run before the original method. Skip the original one if the vehicle is a cable car
        public static bool Prefix(RenderManager.CameraInfo cameraInfo, VehicleInfo info, Vector3 position, ref Quaternion rotation, Vector3 swayPosition, Vector4 lightState, Vector4 tyrePosition, Vector3 velocity, float acceleration, Color color, Vehicle.Flags flags, int variationMask, InstanceID id, bool underground, bool overground)
        {
            // if the vehicle is not a cable car, skip and use the original method
            if ((int)info.m_vehicleType != 0x1000)
            {
                return(true);
            }

            // limit rotation along the x and z axes for all meshes except submesh1
            // submesh1 would rotate in the original way(along with the cable)
            Quaternion originalRotation = rotation;

            rotation.x = 0.0f;
            rotation.z = 0.0f;

            // change how cable cars sway
            // so they don't move up and down on the cables as if they're ships moving in sea waves
            swayPosition.y = 0.0f;

            if ((cameraInfo.m_layerMask & (1 << info.m_prefabDataLayer)) == 0)
            {
                // return false to skip the original method
                return(false);
            }
            Vector3 scale = Vector3.one;

            if ((flags & Vehicle.Flags.Inverted) != 0)
            {
                scale = new Vector3(-1f, 1f, -1f);
                Vector4 vector = lightState;
                lightState.x = vector.y;
                lightState.y = vector.x;
                lightState.z = vector.w;
                lightState.w = vector.z;
            }

            info.m_vehicleAI.RenderExtraStuff(id.Vehicle, ref Singleton <VehicleManager> .instance.m_vehicles.m_buffer[id.Vehicle], cameraInfo, id, position, rotation, tyrePosition, lightState, scale, swayPosition, underground, overground);

            if (cameraInfo.CheckRenderDistance(position, info.m_lodRenderDistance))
            {
                VehicleManager instance           = Singleton <VehicleManager> .instance;
                Matrix4x4      bodyMatrix         = info.m_vehicleAI.CalculateBodyMatrix(flags, ref position, ref rotation, ref scale, ref swayPosition);
                Matrix4x4      originalBodyMatrix = info.m_vehicleAI.CalculateBodyMatrix(flags, ref position, ref originalRotation, ref scale, ref swayPosition);
                Matrix4x4      value = info.m_vehicleAI.CalculateTyreMatrix(flags, ref position, ref rotation, ref scale, ref bodyMatrix);
                if (Singleton <InfoManager> .instance.CurrentMode == InfoManager.InfoMode.None)
                {
                    RenderGroup.MeshData effectMeshData = info.m_vehicleAI.GetEffectMeshData();
                    EffectInfo.SpawnArea area           = new EffectInfo.SpawnArea(bodyMatrix, effectMeshData, info.m_generatedInfo.m_tyres, info.m_lightPositions);
                    if (info.m_effects != null)
                    {
                        for (int i = 0; i < info.m_effects.Length; i++)
                        {
                            VehicleInfo.Effect effect = info.m_effects[i];
                            if (((effect.m_vehicleFlagsRequired | effect.m_vehicleFlagsForbidden) & flags) == effect.m_vehicleFlagsRequired && effect.m_parkedFlagsRequired == VehicleParked.Flags.None)
                            {
                                effect.m_effect.RenderEffect(id, area, velocity, acceleration, 1f, -1f, Singleton <SimulationManager> .instance.m_simulationTimeDelta, cameraInfo);
                            }
                        }
                    }
                }
                if ((flags & Vehicle.Flags.Inverted) != 0)
                {
                    tyrePosition.x = 0f - tyrePosition.x;
                    tyrePosition.y = 0f - tyrePosition.y;
                }
                MaterialPropertyBlock materialBlock = instance.m_materialBlock;
                materialBlock.Clear();
                materialBlock.SetMatrix(instance.ID_TyreMatrix, value);
                materialBlock.SetVector(instance.ID_TyrePosition, tyrePosition);
                materialBlock.SetVector(instance.ID_LightState, lightState);
                bool flag = Singleton <ToolManager> .instance.m_properties.m_mode == ItemClass.Availability.AssetEditor;
                if (!flag)
                {
                    materialBlock.SetColor(instance.ID_Color, color);
                }
                bool flag2 = true;
                if (flag)
                {
                    flag2 = BuildingDecoration.IsMainMeshRendered();
                }
                if (info.m_subMeshes != null)
                {
                    for (int j = 0; j < info.m_subMeshes.Length; j++)
                    {
                        VehicleInfo.MeshInfo meshInfo = info.m_subMeshes[j];
                        VehicleInfoBase      subInfo  = meshInfo.m_subInfo;
                        if ((!flag && ((meshInfo.m_vehicleFlagsRequired | meshInfo.m_vehicleFlagsForbidden) & flags) == meshInfo.m_vehicleFlagsRequired && (meshInfo.m_variationMask & variationMask) == 0 && meshInfo.m_parkedFlagsRequired == VehicleParked.Flags.None) || (flag && BuildingDecoration.IsSubMeshRendered(subInfo)))
                        {
                            if (!(subInfo != null))
                            {
                                continue;
                            }
                            instance.m_drawCallData.m_defaultCalls++;
                            if (underground)
                            {
                                if (subInfo.m_undergroundMaterial == null && subInfo.m_material != null)
                                {
                                    VehicleProperties properties = instance.m_properties;
                                    if (properties != null)
                                    {
                                        subInfo.m_undergroundMaterial = new Material(properties.m_undergroundShader);
                                        subInfo.m_undergroundMaterial.CopyPropertiesFromMaterial(subInfo.m_material);
                                    }
                                }
                                subInfo.m_undergroundMaterial.SetVectorArray(instance.ID_TyreLocation, subInfo.m_generatedInfo.m_tyres);
                                if (j == 1)
                                {
                                    Graphics.DrawMesh(subInfo.m_mesh, originalBodyMatrix, subInfo.m_undergroundMaterial, instance.m_undergroundLayer, null, 0, materialBlock);
                                }
                                else
                                {
                                    Graphics.DrawMesh(subInfo.m_mesh, bodyMatrix, subInfo.m_undergroundMaterial, instance.m_undergroundLayer, null, 0, materialBlock);
                                }
                            }
                            if (overground)
                            {
                                subInfo.m_material.SetVectorArray(instance.ID_TyreLocation, subInfo.m_generatedInfo.m_tyres);
                                if (j == 1)
                                {
                                    Graphics.DrawMesh(subInfo.m_mesh, originalBodyMatrix, subInfo.m_material, info.m_prefabDataLayer, null, 0, materialBlock);
                                }
                                else
                                {
                                    Graphics.DrawMesh(subInfo.m_mesh, bodyMatrix, subInfo.m_material, info.m_prefabDataLayer, null, 0, materialBlock);
                                }
                            }
                        }
                        else if (subInfo == null)
                        {
                            flag2 = false;
                        }
                    }
                }
                if (!flag2)
                {
                    // return false to skip the original method
                    return(false);
                }
                instance.m_drawCallData.m_defaultCalls++;
                if (underground)
                {
                    if (info.m_undergroundMaterial == null && info.m_material != null)
                    {
                        VehicleProperties properties2 = instance.m_properties;
                        if (properties2 != null)
                        {
                            info.m_undergroundMaterial = new Material(properties2.m_undergroundShader);
                            info.m_undergroundMaterial.CopyPropertiesFromMaterial(info.m_material);
                        }
                    }
                    info.m_undergroundMaterial.SetVectorArray(instance.ID_TyreLocation, info.m_generatedInfo.m_tyres);
                    Graphics.DrawMesh(info.m_mesh, bodyMatrix, info.m_undergroundMaterial, instance.m_undergroundLayer, null, 0, materialBlock);
                }
                if (overground)
                {
                    info.m_material.SetVectorArray(instance.ID_TyreLocation, info.m_generatedInfo.m_tyres);
                    Graphics.DrawMesh(info.m_mesh, bodyMatrix, info.m_material, info.m_prefabDataLayer, null, 0, materialBlock);
                }
                // return false to skip the original method
                return(false);
            }
            Matrix4x4 bodyMatrix2         = info.m_vehicleAI.CalculateBodyMatrix(flags, ref position, ref rotation, ref scale, ref swayPosition);
            Matrix4x4 originalBodyMatrix2 = info.m_vehicleAI.CalculateBodyMatrix(flags, ref position, ref originalRotation, ref scale, ref swayPosition);

            if (Singleton <ToolManager> .instance.m_properties.m_mode == ItemClass.Availability.AssetEditor)
            {
                Matrix4x4             value2         = info.m_vehicleAI.CalculateTyreMatrix(flags, ref position, ref rotation, ref scale, ref bodyMatrix2);
                VehicleManager        instance2      = Singleton <VehicleManager> .instance;
                MaterialPropertyBlock materialBlock2 = instance2.m_materialBlock;
                materialBlock2.Clear();
                materialBlock2.SetMatrix(instance2.ID_TyreMatrix, value2);
                materialBlock2.SetVector(instance2.ID_TyrePosition, tyrePosition);
                materialBlock2.SetVector(instance2.ID_LightState, lightState);
                Mesh     mesh     = null;
                Material material = null;
                if (info.m_lodObject != null)
                {
                    MeshFilter component = info.m_lodObject.GetComponent <MeshFilter>();
                    if (component != null)
                    {
                        mesh = component.sharedMesh;
                    }
                    Renderer component2 = info.m_lodObject.GetComponent <Renderer>();
                    if (component2 != null)
                    {
                        material = component2.sharedMaterial;
                    }
                }
                if (mesh != null && material != null)
                {
                    materialBlock2.SetVectorArray(instance2.ID_TyreLocation, info.m_generatedInfo.m_tyres);
                    Graphics.DrawMesh(mesh, bodyMatrix2, material, info.m_prefabDataLayer, null, 0, materialBlock2);
                }
            }
            else if (Singleton <InfoManager> .instance.CurrentMode == InfoManager.InfoMode.None)
            {
                RenderGroup.MeshData effectMeshData2 = info.m_vehicleAI.GetEffectMeshData();
                EffectInfo.SpawnArea area2           = new EffectInfo.SpawnArea(bodyMatrix2, effectMeshData2, info.m_generatedInfo.m_tyres, info.m_lightPositions);
                if (info.m_effects != null)
                {
                    for (int k = 0; k < info.m_effects.Length; k++)
                    {
                        VehicleInfo.Effect effect2 = info.m_effects[k];
                        if (((effect2.m_vehicleFlagsRequired | effect2.m_vehicleFlagsForbidden) & flags) == effect2.m_vehicleFlagsRequired && effect2.m_parkedFlagsRequired == VehicleParked.Flags.None)
                        {
                            effect2.m_effect.RenderEffect(id, area2, velocity, acceleration, 1f, -1f, Singleton <SimulationManager> .instance.m_simulationTimeDelta, cameraInfo);
                        }
                    }
                }
            }
            bool flag3 = true;

            if (info.m_subMeshes != null)
            {
                for (int l = 0; l < info.m_subMeshes.Length; l++)
                {
                    VehicleInfo.MeshInfo meshInfo2 = info.m_subMeshes[l];
                    VehicleInfoBase      subInfo2  = meshInfo2.m_subInfo;
                    if (((meshInfo2.m_vehicleFlagsRequired | meshInfo2.m_vehicleFlagsForbidden) & flags) == meshInfo2.m_vehicleFlagsRequired && (meshInfo2.m_variationMask & variationMask) == 0 && meshInfo2.m_parkedFlagsRequired == VehicleParked.Flags.None)
                    {
                        if (!(subInfo2 != null))
                        {
                            continue;
                        }
                        if (underground)
                        {
                            if (l == 1)
                            {
                                subInfo2.m_undergroundLodTransforms[subInfo2.m_undergroundLodCount] = originalBodyMatrix2;
                            }
                            else
                            {
                                subInfo2.m_undergroundLodTransforms[subInfo2.m_undergroundLodCount] = bodyMatrix2;
                            }

                            subInfo2.m_undergroundLodLightStates[subInfo2.m_undergroundLodCount] = lightState;
                            subInfo2.m_undergroundLodColors[subInfo2.m_undergroundLodCount]      = color.linear;
                            subInfo2.m_undergroundLodMin = Vector3.Min(subInfo2.m_undergroundLodMin, position);
                            subInfo2.m_undergroundLodMax = Vector3.Max(subInfo2.m_undergroundLodMax, position);
                            if (++subInfo2.m_undergroundLodCount == subInfo2.m_undergroundLodTransforms.Length)
                            {
                                Vehicle.RenderUndergroundLod(cameraInfo, subInfo2);
                            }
                        }
                        if (overground)
                        {
                            if (l == 1)
                            {
                                subInfo2.m_lodTransforms[subInfo2.m_lodCount] = originalBodyMatrix2;
                            }
                            else
                            {
                                subInfo2.m_lodTransforms[subInfo2.m_lodCount] = bodyMatrix2;
                            }
                            subInfo2.m_lodLightStates[subInfo2.m_lodCount] = lightState;
                            subInfo2.m_lodColors[subInfo2.m_lodCount]      = color.linear;
                            subInfo2.m_lodMin = Vector3.Min(subInfo2.m_lodMin, position);
                            subInfo2.m_lodMax = Vector3.Max(subInfo2.m_lodMax, position);
                            if (++subInfo2.m_lodCount == subInfo2.m_lodTransforms.Length)
                            {
                                Vehicle.RenderLod(cameraInfo, subInfo2);
                            }
                        }
                    }
                    else if (subInfo2 == null)
                    {
                        flag3 = false;
                    }
                }
            }
            if (!flag3)
            {
                return(false);
            }
            if (underground)
            {
                info.m_undergroundLodTransforms[info.m_undergroundLodCount]  = bodyMatrix2;
                info.m_undergroundLodLightStates[info.m_undergroundLodCount] = lightState;
                info.m_undergroundLodColors[info.m_undergroundLodCount]      = color.linear;
                info.m_undergroundLodMin = Vector3.Min(info.m_undergroundLodMin, position);
                info.m_undergroundLodMax = Vector3.Max(info.m_undergroundLodMax, position);
                if (++info.m_undergroundLodCount == info.m_undergroundLodTransforms.Length)
                {
                    Vehicle.RenderUndergroundLod(cameraInfo, info);
                }
            }
            if (overground)
            {
                info.m_lodTransforms[info.m_lodCount]  = bodyMatrix2;
                info.m_lodLightStates[info.m_lodCount] = lightState;
                info.m_lodColors[info.m_lodCount]      = color.linear;
                info.m_lodMin = Vector3.Min(info.m_lodMin, position);
                info.m_lodMax = Vector3.Max(info.m_lodMax, position);
                if (++info.m_lodCount == info.m_lodTransforms.Length)
                {
                    Vehicle.RenderLod(cameraInfo, info);
                }
            }
            // return false to skip the original method
            return(false);
        }
Ejemplo n.º 13
0
 internal void SetWaterMatrix(Matrix4x4 matrix)
 {
     _materialPropertyBlock.SetMatrix(waterMatrixID, matrix);
 }
Ejemplo n.º 14
0
    // Update is called once per frame
    void LateUpdate()
    {
        // FIRST
        // assign all our data from our current bone transforms
        // and push it into a compute buffer
        Matrix4x4[] boneInfo = new Matrix4x4[bones.Length];
        for (int i = 0; i < bones.Length; i++)
        {
            boneInfo[i] = bones[i].localToWorldMatrix;
        }

        boneBuffer.SetData(boneInfo);


        uint y; uint z; uint numThreads; int numGroups;


        /*
         *
         * Skinning Shader
         *
         */

        // Figure out how many times we need to dispatch
        shader.GetKernelThreadGroupSizes(0, out numThreads, out y, out z);
        numGroups = (verts.Length + ((int)numThreads - 1)) / (int)numThreads;

        // bind buffers
        shader.SetBuffer(0, "_VertBuffer", vertBuffer);
        shader.SetBuffer(0, "_BindBuffer", bindBuffer);
        shader.SetBuffer(0, "_BoneBuffer", boneBuffer);

        // Dispatch the shader
        shader.Dispatch(0, numGroups, 1, 1);



        /*
         *
         * Simulation Shader
         *
         */

        shader.SetVector("_Gravity", _Gravity);
        shader.SetVector("_Velocity", _Velocity);
        shader.SetFloat("_Dampening", _Dampening);
        shader.SetFloat("_NoiseSize", _NoiseSize);
        shader.SetFloat("_NoisePower", _NoisePower);
        shader.SetFloat("_NormalPower", _NormalPower);
        shader.SetFloat("_VelocityPower", _VelocityPower);
        shader.SetFloat("_DeathRate", _DeathRate);
        shader.SetFloat("_FlingPower", _FlingPower);

        // Figure out how many times we need to dispatch
        shader.GetKernelThreadGroupSizes(1, out numThreads, out y, out z);
        numGroups = (numParticles + ((int)numThreads - 1)) / (int)numThreads;


        // bind buffers
        shader.SetBuffer(1, "_VertBuffer", vertBuffer);
        shader.SetBuffer(1, "_ParticleBuffer", particleBuffer);


        // Dispatch the shader
        shader.Dispatch(1, numGroups, 1, 1);



        /*
         *
         * Rendering
         *
         */

        if (mpb == null)
        {
            mpb = new MaterialPropertyBlock();
        }

        mpb.SetBuffer("_VertBuffer", vertBuffer);
        mpb.SetBuffer("_ParticleBuffer", particleBuffer);
        mpb.SetBuffer("_BindBuffer", bindBuffer);
        mpb.SetBuffer("_BoneBuffer", boneBuffer);
        mpb.SetMatrix("_InverseWorldMatrix", transform.worldToLocalMatrix);

        Graphics.DrawProcedural(
            particleMaterial,
            new Bounds(transform.position, Vector3.one * 5000),
            MeshTopology.Triangles,
            numParticles * 3 * 2,
            1, null, mpb,
            ShadowCastingMode.On,
            true,
            LayerMask.NameToLayer("Default")
            );
    }
Ejemplo n.º 15
0
 private void UpdateAtmosphere(MaterialPropertyBlock mat)
 {
     mat.SetVector(shaderPropertyAtmCameraPosition, shaderValueAtmCameraPosition);
     mat.SetMatrix(shaderPropertyAtmViewInv, shaderValueAtmViewInv);
 }
        // 'renderSunDisk' parameter is not supported.
        // Users should instead create an emissive (or lit) mesh for every relevant light source
        // (to support multiple stars in space, moons with moon phases, etc).
        public override void RenderSky(BuiltinSkyParameters builtinParams, bool renderForCubemap, bool renderSunDisk)
        {
            var pbrSky = builtinParams.skySettings as PhysicallyBasedSky;

            // TODO: the following expression is somewhat inefficient, but good enough for now.
            Vector3 cameraPos    = builtinParams.worldSpaceCameraPos;
            Vector3 planetCenter = pbrSky.GetPlanetCenterPosition(cameraPos);
            float   R            = pbrSky.GetPlanetaryRadius();

            Vector3 cameraToPlanetCenter = planetCenter - cameraPos;
            float   r = cameraToPlanetCenter.magnitude;

            cameraPos = planetCenter - Mathf.Max(R, r) * cameraToPlanetCenter.normalized;

            CommandBuffer cmd = builtinParams.commandBuffer;

            // Precomputation is done, shading is next.
            Quaternion planetRotation = Quaternion.Euler(pbrSky.planetRotation.value.x,
                                                         pbrSky.planetRotation.value.y,
                                                         pbrSky.planetRotation.value.z);

            Quaternion spaceRotation = Quaternion.Euler(pbrSky.spaceRotation.value.x,
                                                        pbrSky.spaceRotation.value.y,
                                                        pbrSky.spaceRotation.value.z);

            s_PbrSkyMaterialProperties.SetMatrix(HDShaderIDs._PixelCoordToViewDirWS, builtinParams.pixelCoordToViewDirMatrix);
            s_PbrSkyMaterialProperties.SetVector(HDShaderIDs._WorldSpaceCameraPos1, cameraPos);
            s_PbrSkyMaterialProperties.SetMatrix(HDShaderIDs._ViewMatrix1, builtinParams.viewMatrix);
            s_PbrSkyMaterialProperties.SetMatrix(HDShaderIDs._PlanetRotation, Matrix4x4.Rotate(planetRotation));
            s_PbrSkyMaterialProperties.SetMatrix(HDShaderIDs._SpaceRotation, Matrix4x4.Rotate(spaceRotation));

            m_PrecomputedData.BindBuffers(cmd, s_PbrSkyMaterialProperties);

            int hasGroundAlbedoTexture = 0;

            if (pbrSky.groundColorTexture.value != null)
            {
                hasGroundAlbedoTexture = 1;
                s_PbrSkyMaterialProperties.SetTexture(HDShaderIDs._GroundAlbedoTexture, pbrSky.groundColorTexture.value);
            }
            s_PbrSkyMaterialProperties.SetInt(HDShaderIDs._HasGroundAlbedoTexture, hasGroundAlbedoTexture);

            int hasGroundEmissionTexture = 0;

            if (pbrSky.groundEmissionTexture.value != null)
            {
                hasGroundEmissionTexture = 1;
                s_PbrSkyMaterialProperties.SetTexture(HDShaderIDs._GroundEmissionTexture, pbrSky.groundEmissionTexture.value);
                s_PbrSkyMaterialProperties.SetFloat(HDShaderIDs._GroundEmissionMultiplier, pbrSky.groundEmissionMultiplier.value);
            }
            s_PbrSkyMaterialProperties.SetInt(HDShaderIDs._HasGroundEmissionTexture, hasGroundEmissionTexture);

            int hasSpaceEmissionTexture = 0;

            if (pbrSky.spaceEmissionTexture.value != null)
            {
                hasSpaceEmissionTexture = 1;
                s_PbrSkyMaterialProperties.SetTexture(HDShaderIDs._SpaceEmissionTexture, pbrSky.spaceEmissionTexture.value);
                s_PbrSkyMaterialProperties.SetFloat(HDShaderIDs._SpaceEmissionMultiplier, pbrSky.spaceEmissionMultiplier.value);
            }
            s_PbrSkyMaterialProperties.SetInt(HDShaderIDs._HasSpaceEmissionTexture, hasSpaceEmissionTexture);

            s_PbrSkyMaterialProperties.SetInt(HDShaderIDs._RenderSunDisk, renderSunDisk ? 1 : 0);

            int pass = (renderForCubemap ? 0 : 2);

            CloudLayer.Apply(builtinParams.cloudLayer, m_PbrSkyMaterial);

            CoreUtils.DrawFullScreen(builtinParams.commandBuffer, m_PbrSkyMaterial, s_PbrSkyMaterialProperties, pass);
        }
        public static void DrawSubdivLivePreview(GStylizedTerrain t, Camera cam, Texture newHeightMap, Rect dirtyRect, Texture mask, Matrix4x4 worldPointToMaskMatrix)
        {
            if (t.transform.rotation != Quaternion.identity ||
                t.transform.lossyScale != Vector3.one)
            {
                return;
            }

            t.TerrainData.Geometry.Internal_CreateNewSubDivisionMap(newHeightMap);

            GPolygonDistributionMode polygonMode = t.TerrainData.Geometry.PolygonDistribution;
            int baseResolution = polygonMode == GPolygonDistributionMode.Dynamic ?
                                 t.TerrainData.Geometry.MeshBaseResolution :
                                 t.TerrainData.Geometry.MeshResolution;
            int resolution = t.TerrainData.Geometry.MeshResolution;
            int maxLevel   = baseResolution + Mathf.Min(Mathf.FloorToInt(1f / GCommon.SUB_DIV_STEP), resolution - baseResolution);

            Vector3 terrainSize = new Vector3(
                t.TerrainData.Geometry.Width,
                t.TerrainData.Geometry.Height,
                t.TerrainData.Geometry.Length);

            previewPropertyBlock.Clear();
            previewPropertyBlock.SetColor("_Color", new Color(0, 0, 0, 0.6f));
            previewPropertyBlock.SetTexture("_HeightMap", newHeightMap);
            previewPropertyBlock.SetVector("_Dimension", terrainSize);
            previewPropertyBlock.SetVector("_BoundMin", t.transform.position);
            previewPropertyBlock.SetVector("_BoundMax", t.transform.TransformPoint(terrainSize));
            previewPropertyBlock.SetTexture("_SubdivMap", t.TerrainData.Geometry.Internal_SubDivisionMap);
            previewPropertyBlock.SetTexture("_Mask", mask);
            previewPropertyBlock.SetMatrix("_WorldPointToMask", worldPointToMaskMatrix);

            Material mat = GInternalMaterials.SubdivLivePreviewMaterial;

            mat.renderQueue = 4000;
            Mesh previewMesh = null;

            int gridSize = t.TerrainData.Geometry.ChunkGridSize;

            for (int x = 0; x < gridSize; ++x)
            {
                for (int z = 0; z < gridSize; ++z)
                {
                    Rect uvRect = GCommon.GetUvRange(gridSize, x, z);
                    if (!uvRect.Overlaps(dirtyRect))
                    {
                        continue;
                    }
                    Vector3 localPos = new Vector3(
                        terrainSize.x * uvRect.x,
                        0f,
                        terrainSize.z * uvRect.y);
                    Vector3    worldPos = t.transform.TransformPoint(localPos);
                    Quaternion rotation = Quaternion.identity;
                    Vector3    scale    = new Vector3(terrainSize.x * uvRect.width, 1, terrainSize.z * uvRect.height);

                    for (int i = baseResolution; i <= maxLevel; ++i)
                    {
                        previewMesh = GGriffinSettings.Instance.GetLivePreviewWireframeMesh(i);
                        previewPropertyBlock.SetVector("_SubdivRange", new Vector4(
                                                           (i - baseResolution) * GCommon.SUB_DIV_STEP,
                                                           i != maxLevel ? (i - baseResolution + 1) * GCommon.SUB_DIV_STEP : 1f,
                                                           0, 0));

                        Graphics.DrawMesh(
                            previewMesh,
                            Matrix4x4.TRS(worldPos, rotation, scale),
                            mat,
                            LayerMask.NameToLayer("Default"),
                            cam,
                            0,
                            previewPropertyBlock);
                    }
                }
            }
        }
Ejemplo n.º 18
0
    public void Update()
    {
        if (!isDrawing)
        {
            return;
        }

        if (bone == null)
        {
            bone = gpuSkinning.model.GetBoneByHierarchyName(jointPath);
            if (bone != null)
            {
                boneIndex = System.Array.IndexOf(gpuSkinning.model.bones, bone);
            }
        }
        if (bone == null)
        {
            return;
        }

        if (instancingMatrices == null)
        {
            instancingMatrices = new Matrix4x4[gpuSkinning.model.spawnObjects.Length];
            playMode0_mpb      = new MaterialPropertyBlock();

            hierarchyToObjectMatrices = new Matrix4x4[gpuSkinning.model.spawnObjects.Length];
            playMode1_mpb             = new MaterialPropertyBlock();
        }

        if (gpuSkinning.playingMode.IsPlayMode0())
        {
            Matrix4x4 hierarchyToObject = bone.hierarchyMatrix * localMatrix;
            var       spawnObjects      = gpuSkinning.model.spawnObjects;
            int       numSpawnObjects   = spawnObjects == null ? 0 : spawnObjects.Length;


            for (int i = 0; i < numSpawnObjects; ++i)
            {
                var spawnObject = spawnObjects[i];

                // (1)
                // I think "transform.hasChanged" is not a reliable api in a complex case, it would be better to write your own game logic instead.
                if (spawnObject.transform.hasChanged)
                {
                    spawnObject.transform.hasChanged = false;
                    // (2)
                    // Huge amount of accessing "transform.localToWorldMatrix" will spend much cpu time, so cache these in a buffer, updating once data is dirty.
                    instancingMatrices[i] = spawnObject.transform.localToWorldMatrix;
                }

                if (!isBuiltInDrawMeshInstancedSupported || !gpuSkinning.instancing.IsGPUInstancingOn())
                {
                    // (3)
                    // Matrix multiplication is a slow operation. Optimize it.
                    Matrix4x4 hierarchyToWorld = instancingMatrices[i] * hierarchyToObject;
                    // (4)
                    // Invoke many times of "Graphics.DrawMesh" api will cause performance impact.
                    // So "Graphics.DrawMesh" is not better than MeshRenderer in some cases.
                    // Here is just a example for joint. Overhead should be considered in production.
                    Graphics.DrawMesh(mesh, hierarchyToWorld, material, 0);
                }
            }

            if (isBuiltInDrawMeshInstancedSupported && gpuSkinning.instancing.IsGPUInstancingOn())
            {
                playMode0_mpb.SetMatrix(shaderPropId_HierarchyToObjectMat, hierarchyToObject);
#if UNITY_5_5 || UNITY_5_6 || UNITY_5_7 || UNITY_5_8 || UNITY_5_9 || UNITY_6 || UNITY_2017 || UNITY_2018 // etc.
                // (5)
                // https://forum.unity3d.com/threads/graphics-drawmesh-drawmeshinstanced-fundamentally-bottlenecked-by-the-cpu.429120/
                Graphics.DrawMeshInstanced(mesh, 0, material, instancingMatrices, numSpawnObjects, playMode0_mpb);
#endif
            }
        }
        else
        {
            var   spawnObjects    = gpuSkinning.model.spawnObjects;
            int   numSpawnObjects = spawnObjects == null ? 0 : spawnObjects.Length;
            bool  isInstancingOn  = gpuSkinning.instancing.IsGPUInstancingOn();
            int   fps             = gpuSkinning.model.boneAnimations[0].fps;
            float animLength      = gpuSkinning.model.boneAnimations[0].length;

            for (int i = 0; i < numSpawnObjects; ++i)
            {
                var spawnObject = spawnObjects[i];

                // (1)
                if (spawnObject.transform.hasChanged)
                {
                    spawnObject.transform.hasChanged = false;
                    // (2)
                    instancingMatrices[i] = spawnObject.transform.localToWorldMatrix;
                }

                float     timeOffset        = isInstancingOn ? spawnObject.timeOffset_instancingOn : spawnObject.timeOffset_instancingOff;
                int       frameIndex        = (int)(((gpuSkinning.second + timeOffset) * fps) % (animLength * fps));
                int       frameStartIndex   = frameIndex * gpuSkinning.matrixTexture.numHierarchyMatricesPerFrame;
                Matrix4x4 hierarchyToObject = gpuSkinning.matrixTexture.hierarchyMatrices[frameStartIndex + boneIndex];

                if (!isBuiltInDrawMeshInstancedSupported || !gpuSkinning.instancing.IsGPUInstancingOn())
                {
                    // (3)
                    Matrix4x4 hierarchyToWorld = instancingMatrices[i] * hierarchyToObject * localMatrix;
                    // (4)
                    Graphics.DrawMesh(mesh, hierarchyToWorld, material, 0);
                }
                else
                {
                    hierarchyToObjectMatrices[i] = hierarchyToObject;
                }
            }

            if (isBuiltInDrawMeshInstancedSupported && gpuSkinning.instancing.IsGPUInstancingOn())
            {
                playMode1_mpb.SetMatrixArray(shaderPorpId_HierarchyToObjectMats, hierarchyToObjectMatrices);
                playMode1_mpb.SetMatrix(shaderPropId_JointLocalMatrix, localMatrix);
#if UNITY_5_5 || UNITY_5_6 || UNITY_5_7 || UNITY_5_8 || UNITY_5_9 || UNITY_6 || UNITY_2017 || UNITY_2018 // etc.
                // (5)
                Graphics.DrawMeshInstanced(mesh, 0, material, instancingMatrices, numSpawnObjects, playMode1_mpb);
#endif
            }
        }
    }
 /// <inheritdoc />
 protected override void UpdateShaderProperties(MaterialPropertyBlock materialPropertyBlock)
 {
     materialPropertyBlock.SetMatrix(clipSphereInverseTransformID, clipSphereInverseTransform);
 }
        // 'renderSunDisk' parameter is not supported.
        // Users should instead create an emissive (or lit) mesh for every relevant light source
        // (to support multiple stars in space, moons with moon phases, etc).
        public override void RenderSky(BuiltinSkyParameters builtinParams, bool renderForCubemap, bool renderSunDisk)
        {
            var pbrSky = builtinParams.skySettings as PhysicallyBasedSky;

            // TODO: the following expression is somewhat inefficient, but good enough for now.
            Vector3 X = builtinParams.worldSpaceCameraPos;
            float   r = Vector3.Distance(X, pbrSky.GetPlanetCenterPosition(X));
            float   R = pbrSky.GetPlanetaryRadius();

            bool isPbrSkyActive = r > R; // Disable sky rendering below the ground

            CommandBuffer cmd = builtinParams.commandBuffer;

            // Precomputation is done, shading is next.
            Quaternion planetRotation = Quaternion.Euler(pbrSky.planetRotation.value.x,
                                                         pbrSky.planetRotation.value.y,
                                                         pbrSky.planetRotation.value.z);

            Quaternion spaceRotation = Quaternion.Euler(pbrSky.spaceRotation.value.x,
                                                        pbrSky.spaceRotation.value.y,
                                                        pbrSky.spaceRotation.value.z);

            s_PbrSkyMaterialProperties.SetMatrix(HDShaderIDs._PixelCoordToViewDirWS, builtinParams.pixelCoordToViewDirMatrix);
            s_PbrSkyMaterialProperties.SetVector(HDShaderIDs._WorldSpaceCameraPos1, builtinParams.worldSpaceCameraPos);
            s_PbrSkyMaterialProperties.SetMatrix(HDShaderIDs._ViewMatrix1, builtinParams.viewMatrix);
            s_PbrSkyMaterialProperties.SetMatrix(HDShaderIDs._PlanetRotation, Matrix4x4.Rotate(planetRotation));
            s_PbrSkyMaterialProperties.SetMatrix(HDShaderIDs._SpaceRotation, Matrix4x4.Rotate(spaceRotation));

            if (m_LastPrecomputedBounce != 0)
            {
                s_PbrSkyMaterialProperties.SetTexture(HDShaderIDs._GroundIrradianceTexture, m_GroundIrradianceTables[0]);
                s_PbrSkyMaterialProperties.SetTexture(HDShaderIDs._AirSingleScatteringTexture, m_InScatteredRadianceTables[0]);
                s_PbrSkyMaterialProperties.SetTexture(HDShaderIDs._AerosolSingleScatteringTexture, m_InScatteredRadianceTables[1]);
                s_PbrSkyMaterialProperties.SetTexture(HDShaderIDs._MultipleScatteringTexture, m_InScatteredRadianceTables[2]);
            }
            else
            {
                s_PbrSkyMaterialProperties.SetTexture(HDShaderIDs._GroundIrradianceTexture, Texture2D.blackTexture);
                s_PbrSkyMaterialProperties.SetTexture(HDShaderIDs._AirSingleScatteringTexture, CoreUtils.blackVolumeTexture);
                s_PbrSkyMaterialProperties.SetTexture(HDShaderIDs._AerosolSingleScatteringTexture, CoreUtils.blackVolumeTexture);
                s_PbrSkyMaterialProperties.SetTexture(HDShaderIDs._MultipleScatteringTexture, CoreUtils.blackVolumeTexture);
            }

            int hasGroundAlbedoTexture = 0;

            if (pbrSky.groundColorTexture.value != null)
            {
                hasGroundAlbedoTexture = 1;
                s_PbrSkyMaterialProperties.SetTexture(HDShaderIDs._GroundAlbedoTexture, pbrSky.groundColorTexture.value);
            }
            s_PbrSkyMaterialProperties.SetInt(HDShaderIDs._HasGroundAlbedoTexture, hasGroundAlbedoTexture);

            int hasGroundEmissionTexture = 0;

            if (pbrSky.groundEmissionTexture.value != null)
            {
                hasGroundEmissionTexture = 1;
                s_PbrSkyMaterialProperties.SetTexture(HDShaderIDs._GroundEmissionTexture, pbrSky.groundEmissionTexture.value);
                s_PbrSkyMaterialProperties.SetFloat(HDShaderIDs._GroundEmissionMultiplier, pbrSky.groundEmissionMultiplier.value);
            }
            s_PbrSkyMaterialProperties.SetInt(HDShaderIDs._HasGroundEmissionTexture, hasGroundEmissionTexture);

            int hasSpaceEmissionTexture = 0;

            if (pbrSky.spaceEmissionTexture.value != null)
            {
                hasSpaceEmissionTexture = 1;
                s_PbrSkyMaterialProperties.SetTexture(HDShaderIDs._SpaceEmissionTexture, pbrSky.spaceEmissionTexture.value);
                s_PbrSkyMaterialProperties.SetFloat(HDShaderIDs._SpaceEmissionMultiplier, pbrSky.spaceEmissionMultiplier.value);
            }
            s_PbrSkyMaterialProperties.SetInt(HDShaderIDs._HasSpaceEmissionTexture, hasSpaceEmissionTexture);

            s_PbrSkyMaterialProperties.SetInt(HDShaderIDs._RenderSunDisk, renderSunDisk ? 1 : 0);

            int pass = (renderForCubemap ? 0 : 2) + (isPbrSkyActive ? 0 : 1);

            CoreUtils.DrawFullScreen(builtinParams.commandBuffer, s_PbrSkyMaterial, s_PbrSkyMaterialProperties, pass);
        }
Ejemplo n.º 21
0
    void Update()
    {
        registeredTouches = touches.Count;

        //	Reset
        finalMatrix     = Matrix4x4.identity;
        finalRotation   = Quaternion.identity;
        finalTouchForce = Vector4.zero;

        //	Handles touches
        if (registeredTouches > 0)
        {
            resetted = false;
            touch temp;
            for (int i = 0; i < registeredTouches; i++)
            {
                temp = touches[i];
                //	Update Player vars
                touchBendingPlayerListener tempPlayerVars = temp.go.GetComponent <touchBendingPlayerListener>();

                //	Reset Animation if it has ended
                if (temp.timer >= duration)
                {
                    if (temp.left == true)
                    {
                        touchToRemove = i;
                    }
                }

                //	Bounce Animation
                else
                {
                    //temp.easingControl = Mathf.Lerp( Mathf.Sin(temp.timer * 10.0f / duration) / (temp.timer + 1.25f) * 8.0f, target, Mathf.Sqrt( temp.timer / duration ) );
                    temp.easingControl = Mathf.Lerp(Mathf.Sin(temp.timer * 10.0f / duration) / (temp.timer + 1.25f) * 8.0f, 0.0f, Mathf.Clamp01(temp.timer / duration));
                }

                if (temp.left == true)
                {
                    // timerLeft = 0 --> player is outside the trigger
                    temp.timerLeft = Mathf.Clamp01(temp.timerLeft - Time.deltaTime * duration);
                }
                else
                {
                    // timerLeft = 1 --> player is inside the trigger
                    temp.timerLeft = Mathf.Clamp01(temp.timerLeft + Time.deltaTime * duration);
                }

                //	Set timer according to Player_Speed if player is inside the trigger
                temp.timer += Time.deltaTime * Mathf.Lerp(1.0f, tempPlayerVars.Player_Speed, temp.timerLeft);

                touches[i] = temp;
                Quaternion rotation = Quaternion.Euler(temp.axis * (temp.intialTouchForce * bendability * temp.easingControl));
                finalRotation = finalRotation * rotation;

                //	Calculate extra force // faster to do it componentwise istead of new Vector4()
                finalTouchForce.x += temp.playerDirection.x * temp.easingControl;
                finalTouchForce.y += temp.playerDirection.y * temp.easingControl;
                finalTouchForce.z += temp.playerDirection.z * temp.easingControl;
                finalTouchForce.w += tempPlayerVars.Player_Speed * temp.easingControl * disturbance;
                //finalTouchForce.w += temp.playerSpeed * temp.easingControl * disturbance; //temp.playerSpeed
            }

            //	Set rotation and extra force
            finalMatrix.SetTRS(Vector3.zero, finalRotation, Vector3.one);
            TouchMaterialBlock.SetMatrix(RotMatrixPID, finalMatrix);
            TouchMaterialBlock.SetVector(TouchBendingForcePID, finalTouchForce);
            m_Renderer.SetPropertyBlock(TouchMaterialBlock);

            //	Remove touch from list
            if (touchToRemove != -1)
            {
                touches.RemoveAt(touchToRemove);
                touchToRemove = -1;
            }
        }
        else if (!resetted)
        {
            //	Remove PropertyBlock
            resetted = true;
            TouchMaterialBlock.Clear();
            m_Renderer.SetPropertyBlock(TouchMaterialBlock);
        }
    }
Ejemplo n.º 22
0
    void Update()
    {
        if (appendVertexBuffer == null)
        {
            return;
        }
        appendVertexBuffer.SetCounterValue(0);

        OceanOfCubesCS.SetFloat("_gridSizeURcp", 1.0f / CubesUResolution);
        OceanOfCubesCS.SetFloat("_gridSizeVRcp", 1.0f / CubesVResolution);
        OceanOfCubesCS.SetFloat("_cubeScale", CubeScale);
        OceanOfCubesCS.SetFloat("_minU", minU);
        OceanOfCubesCS.SetFloat("_minV", minV);
        OceanOfCubesCS.SetFloat("_maxU", maxU);
        OceanOfCubesCS.SetFloat("_maxV", maxV);
        OceanOfCubesCS.SetFloat("_time", timelineTime);
        OceanOfCubesCS.SetBuffer(kernelMain, "triangleRW", appendVertexBuffer);

        if (Colliders.Length > 0)
        {
            int i = 0;
            foreach (var go in Colliders)
            {
                if (go.activeInHierarchy)
                {
                    collidersData[i].position  = transform.worldToLocalMatrix.MultiplyPoint(go.transform.position);
                    collidersData[i].influence = 1.0f / ColliderInfluence;
                    i++;
                }
            }
            OceanOfCubesCS.SetInt("_numberOfColliders", i);

            collidersBuffer.SetData(collidersData);
            OceanOfCubesCS.SetBuffer(kernelMain, "colliders", collidersBuffer);
        }
        else
        {
            OceanOfCubesCS.SetBuffer(kernelMain, "colliders", collidersBuffer);
            OceanOfCubesCS.SetInt("_numberOfColliders", 0);
        }

        OceanOfCubesCS.Dispatch(kernelMain, CubesUResolution / 8, CubesVResolution / 8, 1);

        //ComputeBuffer.CopyCount(appendVertexBuffer, argBuffer, 0);

        //MarchingCubesCS.SetBuffer(kernelMultiply, "_numVertices", argBuffer);
        //MarchingCubesCS.Dispatch(kernelMultiply, 1, 1, 1);

        //int[] args2 = new int[] { 0, 1, 0, 0 };
        //argBuffer.GetData(args2);
        //args2[0] *= 3;
        //argBuffer.SetData(args);

        //Debug.Log("Vertex count:" + args2[0]);

        ComputeBuffer.CopyCount(appendVertexBuffer, argBuffer, 0);

        //int[] args2 = new int[] { 0, 1, 0, 0, 0 };
        //argBuffer.GetData(args2);
        //Debug.Log("Index count:" + args2[0] + " Instances count:" + args2[1]);

        OceanOfCubesCS.SetBuffer(kernelInstances, "_numVertices", argBuffer);
        OceanOfCubesCS.Dispatch(kernelInstances, 1, 1, 1);

        mat.SetPass(0);
        matPropertyBlock.SetBuffer("triangles", appendVertexBuffer);
        matPropertyBlock.SetBuffer("indexStructure", argBuffer);
        matPropertyBlock.SetMatrix("_LocalToWorld", Matrix4x4.Translate(-transform.position) * transform.localToWorldMatrix);
        matPropertyBlock.SetMatrix("_WorldToLocal", transform.worldToLocalMatrix);

        Graphics.DrawMeshInstancedIndirect(
            emptyMesh, 0, mat,
            new Bounds(transform.position, transform.lossyScale * 10.0f),
            argBuffer, 0, matPropertyBlock);
    }
Ejemplo n.º 23
0
        private void LateUpdate()
        {
            if (window == null)
            {
                return;
            }

            // Update window transformation.
            Transform cameraTransform = CameraCache.Main ? CameraCache.Main.transform : null;

            if (isVisible && cameraTransform != null)
            {
                float t = Time.deltaTime * windowFollowSpeed;
                window.position   = Vector3.Lerp(window.position, CalculateWindowPosition(cameraTransform), t);
                window.rotation   = Quaternion.Slerp(window.rotation, CalculateWindowRotation(cameraTransform), t);
                window.localScale = defaultWindowScale * windowScale;
                CalculateBackgroundSize();
            }

            // Capture frame timings every frame and read from it depending on the frameSampleRate.
            FrameTimingManager.CaptureFrameTimings();

            ++frameCount;
            float elapsedSeconds = stopwatch.ElapsedMilliseconds * 0.001f;

            if (elapsedSeconds >= frameSampleRate)
            {
                int cpuFrameRate = (int)(1.0f / (elapsedSeconds / frameCount));
                int gpuFrameRate = 0;

                // Many platforms do not yet support the FrameTimingManager. When timing data is returned from the FrameTimingManager we will use
                // its timing data, else we will depend on the stopwatch.
                uint frameTimingsCount = FrameTimingManager.GetLatestTimings((uint)Mathf.Min(frameCount, maxFrameTimings), frameTimings);

                if (frameTimingsCount != 0)
                {
                    float cpuFrameTime, gpuFrameTime;
                    AverageFrameTiming(frameTimings, frameTimingsCount, out cpuFrameTime, out gpuFrameTime);
                    cpuFrameRate = (int)(1.0f / (cpuFrameTime / frameCount));
                    gpuFrameRate = (int)(1.0f / (gpuFrameTime / frameCount));
                }

                // Update frame rate text.
                cpuFrameRateText.text = cpuFrameRateStrings[Mathf.Clamp(cpuFrameRate, 0, maxTargetFrameRate)];

                if (gpuFrameRate != 0)
                {
                    gpuFrameRateText.gameObject.SetActive(true);
                    gpuFrameRateText.text = gpuFrameRateStrings[Mathf.Clamp(gpuFrameRate, 0, maxTargetFrameRate)];
                }

                // Update frame colors.
                if (frameInfoVisible)
                {
                    for (int i = frameRange - 1; i > 0; --i)
                    {
                        frameInfoColors[i] = frameInfoColors[i - 1];
                    }

                    frameInfoColors[0] = CalculateFrameColor(cpuFrameRate);
                    frameInfoPropertyBlock.SetVectorArray(colorID, frameInfoColors);
                }

                // Reset timers.
                frameCount = 0;
                stopwatch.Reset();
                stopwatch.Start();
            }

            // Draw frame info.
            if (isVisible && frameInfoVisible)
            {
                Matrix4x4 parentLocalToWorldMatrix = window.localToWorldMatrix;

                if (defaultInstancedMaterial != null)
                {
                    frameInfoPropertyBlock.SetMatrix(parentMatrixID, parentLocalToWorldMatrix);
                    Graphics.DrawMeshInstanced(quadMesh, 0, defaultInstancedMaterial, frameInfoMatrices, frameInfoMatrices.Length, frameInfoPropertyBlock, UnityEngine.Rendering.ShadowCastingMode.Off, false);
                }
                else
                {
                    // If a instanced material is not available, fall back to non-instanced rendering.
                    for (int i = 0; i < frameInfoMatrices.Length; ++i)
                    {
                        frameInfoPropertyBlock.SetColor(colorID, frameInfoColors[i]);
                        Graphics.DrawMesh(quadMesh, parentLocalToWorldMatrix * frameInfoMatrices[i], defaultMaterial, 0, null, 0, frameInfoPropertyBlock, false, false, false);
                    }
                }
            }

            // Update memory statistics.
            if (isVisible && memoryStatsVisible)
            {
                ulong limit = AppMemoryUsageLimit;

                if (limit != limitMemoryUsage)
                {
                    if (WillDisplayedMemoryUsageDiffer(limitMemoryUsage, limit, displayedDecimalDigits))
                    {
                        MemoryUsageToString(stringBuffer, displayedDecimalDigits, limitMemoryText, limitMemoryString, limit);
                    }

                    limitMemoryUsage = limit;
                }

                ulong usage = AppMemoryUsage;

                if (usage != memoryUsage)
                {
                    usedAnchor.localScale = new Vector3((float)usage / limitMemoryUsage, usedAnchor.localScale.y, usedAnchor.localScale.z);

                    if (WillDisplayedMemoryUsageDiffer(memoryUsage, usage, displayedDecimalDigits))
                    {
                        MemoryUsageToString(stringBuffer, displayedDecimalDigits, usedMemoryText, usedMemoryString, usage);
                    }

                    memoryUsage = usage;
                }

                if (memoryUsage > peakMemoryUsage)
                {
                    peakAnchor.localScale = new Vector3((float)memoryUsage / limitMemoryUsage, peakAnchor.localScale.y, peakAnchor.localScale.z);

                    if (WillDisplayedMemoryUsageDiffer(peakMemoryUsage, memoryUsage, displayedDecimalDigits))
                    {
                        MemoryUsageToString(stringBuffer, displayedDecimalDigits, peakMemoryText, peakMemoryString, memoryUsage);
                    }

                    peakMemoryUsage = memoryUsage;
                }
            }

            // Update visibility state.
            window.gameObject.SetActive(isVisible);
            memoryStats.gameObject.SetActive(memoryStatsVisible);
        }
Ejemplo n.º 24
0
                        #pragma warning restore 0649



            public void InitalizeRenderMesh(int x_dim, int y_dim, int z_dim, float size)
            {
                //each dimension must be divisable by 8, densitymap and MC shader must be present
                if (x_dim % 8 != 0 || y_dim % 8 != 0 || z_dim % 8 != 0)
                {
                    throw new System.ArgumentException("x, y or z must be divisible by 8");
                }
                if (m_MCRenderShader == null)
                {
                    throw new System.ArgumentException("Missing MCRenderShader");
                }
                if (m_clearVerticesShader == null)
                {
                    throw new System.ArgumentException("Missing ClearVerticesShader");
                }
                if (m_calculateNormalsShader == null)
                {
                    throw new System.ArgumentException("Missing CalculateNormalsShader");
                }
                if (m_meshMaterial == null)
                {
                    Debug.LogWarning("Missing mesh material");
                }

                m_x_dim = x_dim;
                m_y_dim = y_dim;
                m_z_dim = z_dim;

                m_scale = size;

                //m_meshMaterial.SetVector("_Offset", new Vector4(m_x_dim / 2, m_y_dim / 2, m_z_dim / 2, 0f));
                //m_meshMaterial.SetFloat("_Scale", m_scale);

                m_propertyBlock = new MaterialPropertyBlock();
                m_propertyBlock.SetMatrix("_ObjectToWorld", m_chunkTransform.localToWorldMatrix);
                //m_bounds = new Bounds(m_chunkTransform.position + (new Vector3(m_x_dim / 2, m_y_dim / 2, m_z_dim / 2) * m_scale), new Vector3(m_x_dim, m_y_dim, m_z_dim) * m_scale);
                m_bounds = new Bounds();

                //MarchingCubes
                //tables
                m_cubeEdgeFlags = new ComputeBuffer(256, sizeof(int));
                m_cubeEdgeFlags.SetData(MarchingCubesTables.CubeEdgeFlags);
                m_traingleConnectionTable = new ComputeBuffer(256 * 16, sizeof(int));
                m_traingleConnectionTable.SetData(MarchingCubesTables.TriangleConnectionTable);

                m_densityBuffer         = new ComputeBuffer(m_x_dim * m_y_dim * m_z_dim, sizeof(float));
                m_ChunkXdensityBuffer   = new ComputeBuffer(2 * m_y_dim * m_z_dim, sizeof(float));
                m_ChunkYdensityBuffer   = new ComputeBuffer(2 * m_x_dim * m_z_dim, sizeof(float));
                m_ChunkZdensityBuffer   = new ComputeBuffer(2 * m_x_dim * m_y_dim, sizeof(float));
                m_ChunkXYdensityBuffer  = new ComputeBuffer(3 * m_z_dim, sizeof(float));
                m_ChunkYZdensityBuffer  = new ComputeBuffer(3 * m_x_dim, sizeof(float));
                m_ChunkXZdensityBuffer  = new ComputeBuffer(3 * m_y_dim, sizeof(float));
                m_ChunkXYZdensityBuffer = new ComputeBuffer(4, sizeof(float));

                //normals
                m_normalsTexture = new RenderTexture(m_x_dim + 1, m_y_dim + 1, 0, RenderTextureFormat.ARGBHalf, RenderTextureReadWrite.Linear)
                {
                    dimension         = UnityEngine.Rendering.TextureDimension.Tex3D,
                    volumeDepth       = m_z_dim + 1,
                    enableRandomWrite = true,
                    useMipMap         = false
                };
                m_normalsTexture.Create();

                //initalize variables in MC, ClearVertices, initalize normals shader
                InitRenderMC();
                InitRenderMesh();
                InitNormals();
            }
Ejemplo n.º 25
0
    void SetShaderPropertiesBlock(MaterialPropertyBlock propertyBlock)
    {
        propertyBlock.SetVector(_idNoiseOffset, _angle);
        propertyBlock.SetVector(_idMinBounds, _minBounds);
        propertyBlock.SetVector(_idMaxBounds, _maxBounds);
        propertyBlock.SetMatrix(_idProjection, _projectionMatrixCached);
        propertyBlock.SetMatrix(_idViewWorldLight, _viewWorldLight);
        propertyBlock.SetMatrix(_idLocalRotation, _localRotation);
        propertyBlock.SetMatrix(_idRotation, _rotation);
        propertyBlock.SetColor(_idColorTint, colorTint);
        propertyBlock.SetFloat(_idLightMultiplier, lightMultiplier);
        propertyBlock.SetVector("_WorldPos", (CachedTransform.position + CachedTransform.forward) * worldScrollAmount);

        var lightMaterial = LightMaterial;

        if (useSoftBlend)
        {
            lightMaterial.EnableKeyword("_SOFTBLEND_ON");
        }
        else
        {
            lightMaterial.DisableKeyword("_SOFTBLEND_ON");
        }

        if (useDithering)
        {
            propertyBlock.SetFloat(_idJitterAmount, ditherAmount);
            propertyBlock.SetTexture(_idDitherTex, DitherTexture);
            lightMaterial.EnableKeyword("_DITHER_ON");
        }
        else
        {
            lightMaterial.DisableKeyword("_DITHER_ON");
        }

        if (useCurves)
        {
            propertyBlock.SetTexture(_idFallOffTex, FallOffTexture);
            lightMaterial.EnableKeyword("_CURVE_ON");
        }
        else
        {
            lightMaterial.DisableKeyword("_CURVE_ON");
        }

        switch (lightType)
        {
        case LightTypes.Point:
        case LightTypes.Spot:
        case LightTypes.Orthographic:
            propertyBlock.SetFloat(_idSpotExponent, spotExponent);
            propertyBlock.SetFloat(_idConstantAttenuation, constantAttenuation);
            propertyBlock.SetFloat(_idLinearAttenuation, linearAttenuation);
            propertyBlock.SetFloat(_idQuadraticAttenuation, quadraticAttenuation);
            break;

        case LightTypes.Area:
            Vector4 p = volumeTextureOffset;
            p.w = volumeTextureScale;
            propertyBlock.SetVector(_idVolumeOffset, p);
            propertyBlock.SetFloat(_idVolumeParams, shapeValue);
            switch (volumeShape)
            {
            case VolumeShape.Cube:
                lightMaterial.EnableKeyword("_SHAPE_CUBE");
                lightMaterial.DisableKeyword("_SHAPE_SPHERE");
                lightMaterial.DisableKeyword("_SHAPE_ROUNDED_CUBE");
                lightMaterial.DisableKeyword("_SHAPE_CYLINDER");
                break;

            case VolumeShape.Sphere:
                lightMaterial.EnableKeyword("_SHAPE_SPHERE");
                lightMaterial.DisableKeyword("_SHAPE_CUBE");
                lightMaterial.DisableKeyword("_SHAPE_ROUNDED_CUBE");
                lightMaterial.DisableKeyword("_SHAPE_CYLINDER");
                break;

            case VolumeShape.RoundedCube:
                lightMaterial.EnableKeyword("_SHAPE_ROUNDED_CUBE");
                lightMaterial.DisableKeyword("_SHAPE_CUBE");
                lightMaterial.DisableKeyword("_SHAPE_SPHERE");
                lightMaterial.DisableKeyword("_SHAPE_CYLINDER");
                break;

            case VolumeShape.Cylinder:
                lightMaterial.EnableKeyword("_SHAPE_CYLINDER");
                lightMaterial.DisableKeyword("_SHAPE_CUBE");
                lightMaterial.DisableKeyword("_SHAPE_SPHERE");
                lightMaterial.DisableKeyword("_SHAPE_ROUNDED_CUBE");
                break;
            }
            break;
        }

        switch (lightType)
        {
        case LightTypes.Area:
            propertyBlock.SetTexture("_MainTex", areaVolume != null ? areaVolume : EmptyTexture3D);
            break;

        case LightTypes.Point:
            propertyBlock.SetTexture("_LightColorEmission", pointEmission != null ? pointEmission : EmptyCubemap);
            propertyBlock.SetTexture("_NoiseTex", pointNoise != null ? pointNoise : EmptyCubemap);
            propertyBlock.SetTexture("_ShadowTexture", pointShadow != null ? pointShadow : EmptyCubemap);
            break;

        case LightTypes.Spot:
        case LightTypes.Orthographic:
            propertyBlock.SetTexture("_LightColorEmission", spotEmission != null ? spotEmission : EmptyTexture2D);
            propertyBlock.SetTexture("_NoiseTex", spotNoise != null ? spotNoise : EmptyTexture2D);
            propertyBlock.SetTexture("_ShadowTexture", spotShadow != null ? spotShadow : EmptyTexture2D);
            break;
        }

        var shouldUseCustomShadowMap = false;

        cam.targetTexture = null;
        switch (shadowMode)
        {
        case ShadowMode.Realtime:
            if (_depthTexture == null)
            {
                CreateDepthTexture(lightType);
            }
            propertyBlock.SetTexture("_ShadowTexture", _depthTexture);
            lightMaterial.EnableKeyword("_SHADOW_ON");
            shouldUseCustomShadowMap = renderFullShadows;
            break;

        case ShadowMode.Baked:
            lightMaterial.EnableKeyword("_SHADOW_ON");
            shouldUseCustomShadowMap = false;
            break;

        case ShadowMode.None:
            lightMaterial.DisableKeyword("_SHADOW_ON");
            shouldUseCustomShadowMap = false;
            break;
        }

        if (shouldUseCustomShadowMap)
        {
            lightMaterial.EnableKeyword("_SHADOW_EXP");
        }
        else
        {
            lightMaterial.DisableKeyword("_SHADOW_EXP");
        }

        float far  = cam.farClipPlane;
        float near = cam.nearClipPlane;
        float fov  = cam.fieldOfView;

        far  = spotRange;
        near = Mathf.Max(0.01f, spotNear);
        fov  = spotAngle;

        cam.farClipPlane = far;

        if (lightType == LightTypes.Point || lightType == LightTypes.Area)
        {
            near = -pointLightRadius;
            far  = pointLightRadius;
        }

        switch ((lightType))
        {
        case LightTypes.Point:
        case LightTypes.Area:
            propertyBlock.SetVector(_idLightParams, new Vector4(near, far, aspect, pointLightRadius));
            break;

        case LightTypes.Orthographic:
            propertyBlock.SetVector(_idLightParams, new Vector4(near, far, aspect, orthoSize));
            break;

        default:
            propertyBlock.SetVector(_idLightParams, new Vector4(near, far, aspect, fov * 0.5f * Mathf.Deg2Rad));
            break;
        }
    }
Ejemplo n.º 26
0
        void SetUniforms(BuiltinSkyParameters builtinParams, ProceduralSkySettings param, bool renderForCubemap, ref MaterialPropertyBlock properties)
        {
            properties.SetTexture("_Cubemap", param.skyHDRI);
            properties.SetVector("_SkyParam", new Vector4(param.exposure, param.multiplier, param.rotation, 0.0f));

            properties.SetMatrix("_InvViewProjMatrix", builtinParams.invViewProjMatrix);
            properties.SetVector("_CameraPosWS", builtinParams.cameraPosWS);
            properties.SetVector("_ScreenSize", builtinParams.screenSize);

            m_ProceduralSkyMaterial.SetInt("_AtmosphericsDebugMode", (int)param.debugMode);

            Vector3 sunDirection = (builtinParams.sunLight != null) ? -builtinParams.sunLight.transform.forward : Vector3.zero;

            m_ProceduralSkyMaterial.SetVector("_SunDirection", sunDirection);

            var pixelRect = new Rect(0f, 0f, builtinParams.screenSize.x, builtinParams.screenSize.y);
            var scale     = 1.0f; //(float)(int)occlusionDownscale;
            var depthTextureScaledTexelSize = new Vector4(scale / pixelRect.width,
                                                          scale / pixelRect.height,
                                                          -scale / pixelRect.width,
                                                          -scale / pixelRect.height);

            properties.SetVector("_DepthTextureScaledTexelSize", depthTextureScaledTexelSize);

            /*
             * m_ProceduralSkyMaterial.SetFloat("_ShadowBias", useOcclusion ? occlusionBias : 1f);
             * m_ProceduralSkyMaterial.SetFloat("_ShadowBiasIndirect", useOcclusion ? occlusionBiasIndirect : 1f);
             * m_ProceduralSkyMaterial.SetFloat("_ShadowBiasClouds", useOcclusion ? occlusionBiasClouds : 1f);
             * m_ProceduralSkyMaterial.SetVector("_ShadowBiasSkyRayleighMie", useOcclusion ? new Vector4(occlusionBiasSkyRayleigh, occlusionBiasSkyMie, 0f, 0f) : Vector4.zero);
             * m_ProceduralSkyMaterial.SetFloat("_OcclusionDepthThreshold", occlusionDepthThreshold);
             * m_ProceduralSkyMaterial.SetVector("_OcclusionTexture_TexelSize", ???);
             */

            m_ProceduralSkyMaterial.SetFloat("_WorldScaleExponent", param.worldScaleExponent);
            m_ProceduralSkyMaterial.SetFloat("_WorldNormalDistanceRcp", 1f / param.worldNormalDistance);
            m_ProceduralSkyMaterial.SetFloat("_WorldMieNearScatterPush", -Mathf.Pow(Mathf.Abs(param.worldMieNearScatterPush), param.worldScaleExponent) * Mathf.Sign(param.worldMieNearScatterPush));
            m_ProceduralSkyMaterial.SetFloat("_WorldRayleighNearScatterPush", -Mathf.Pow(Mathf.Abs(param.worldRayleighNearScatterPush), param.worldScaleExponent) * Mathf.Sign(param.worldRayleighNearScatterPush));
            m_ProceduralSkyMaterial.SetFloat("_WorldRayleighDensity", -param.worldRayleighDensity / 100000f);
            m_ProceduralSkyMaterial.SetFloat("_WorldMieDensity", -param.worldMieDensity / 100000f);

            var rayleighColorM20 = param.worldRayleighColorRamp.Evaluate(0.00f);
            var rayleighColorM10 = param.worldRayleighColorRamp.Evaluate(0.25f);
            var rayleighColorO00 = param.worldRayleighColorRamp.Evaluate(0.50f);
            var rayleighColorP10 = param.worldRayleighColorRamp.Evaluate(0.75f);
            var rayleighColorP20 = param.worldRayleighColorRamp.Evaluate(1.00f);

            var mieColorM20 = param.worldMieColorRamp.Evaluate(0.00f);
            var mieColorO00 = param.worldMieColorRamp.Evaluate(0.50f);
            var mieColorP20 = param.worldMieColorRamp.Evaluate(1.00f);

            m_ProceduralSkyMaterial.SetVector("_RayleighColorM20", (Vector4)rayleighColorM20 * param.worldRayleighColorIntensity);
            m_ProceduralSkyMaterial.SetVector("_RayleighColorM10", (Vector4)rayleighColorM10 * param.worldRayleighColorIntensity);
            m_ProceduralSkyMaterial.SetVector("_RayleighColorO00", (Vector4)rayleighColorO00 * param.worldRayleighColorIntensity);
            m_ProceduralSkyMaterial.SetVector("_RayleighColorP10", (Vector4)rayleighColorP10 * param.worldRayleighColorIntensity);
            m_ProceduralSkyMaterial.SetVector("_RayleighColorP20", (Vector4)rayleighColorP20 * param.worldRayleighColorIntensity);

            m_ProceduralSkyMaterial.SetVector("_MieColorM20", (Vector4)mieColorM20 * param.worldMieColorIntensity);
            m_ProceduralSkyMaterial.SetVector("_MieColorO00", (Vector4)mieColorO00 * param.worldMieColorIntensity);
            m_ProceduralSkyMaterial.SetVector("_MieColorP20", (Vector4)mieColorP20 * param.worldMieColorIntensity);

            m_ProceduralSkyMaterial.SetFloat("_HeightNormalDistanceRcp", 1f / param.heightNormalDistance);
            m_ProceduralSkyMaterial.SetFloat("_HeightMieNearScatterPush", -Mathf.Pow(Mathf.Abs(param.heightMieNearScatterPush), param.worldScaleExponent) * Mathf.Sign(param.heightMieNearScatterPush));
            m_ProceduralSkyMaterial.SetFloat("_HeightRayleighNearScatterPush", -Mathf.Pow(Mathf.Abs(param.heightRayleighNearScatterPush), param.worldScaleExponent) * Mathf.Sign(param.heightRayleighNearScatterPush));
            // m_ProceduralSkyMaterial.SetFloat("_HeightRayleighDensity", -param.heightRayleighDensity / 100000f);
            // m_ProceduralSkyMaterial.SetFloat("_HeightMieDensity", -param.heightMieDensity / 100000f);
            m_ProceduralSkyMaterial.SetFloat("_HeightSeaLevel", param.heightSeaLevel);
            m_ProceduralSkyMaterial.SetVector("_HeightPlaneShift", param.heightPlaneShift);
            m_ProceduralSkyMaterial.SetFloat("_HeightDistanceRcp", 1f / param.heightDistance);
            m_ProceduralSkyMaterial.SetVector("_HeightRayleighColor", (Vector4)param.heightRayleighColor * param.heightRayleighIntensity);
            m_ProceduralSkyMaterial.SetFloat("_HeightExtinctionFactor", param.heightExtinctionFactor);

            m_ProceduralSkyMaterial.SetVector("_RayleighInScatterPct", new Vector4(1f - param.worldRayleighIndirectScatter, param.worldRayleighIndirectScatter, 0f, 0f));
            m_ProceduralSkyMaterial.SetFloat("_RayleighExtinctionFactor", param.worldRayleighExtinctionFactor);

            m_ProceduralSkyMaterial.SetFloat("_MiePhaseAnisotropy", param.worldMiePhaseAnisotropy);
            m_ProceduralSkyMaterial.SetFloat("_MieExtinctionFactor", param.worldMieExtinctionFactor);

            // Since we use the material for rendering the sky both into the cubemap, and
            // during the fullscreen pass, setting the 'PERFORM_SKY_OCCLUSION_TEST' keyword has no effect.
            properties.SetFloat("_DisableSkyOcclusionTest", renderForCubemap ? 1.0f : 0.0f);
            // We flip the screens-space Y axis in case we follow the D3D convention.
            properties.SetFloat("_FlipY", renderForCubemap ? 1.0f : 0.0f);
            // We do not render the height fog into the sky IBL cubemap.
            properties.SetFloat("_HeightRayleighDensity", renderForCubemap ? -0.0f : -param.heightRayleighDensity / 100000f);
            properties.SetFloat("_HeightMieDensity", renderForCubemap ? -0.0f : -param.heightMieDensity / 100000f);
        }
Ejemplo n.º 27
0
 public Pair SetMatrix(int name, Matrix4x4 value)
 {
     CheckLoad();
     Block.SetMatrix(name, value);
     return(this);
 }
        public override void RenderSky(BuiltinSkyParameters builtinParams, bool renderForCubemap, bool renderSunDisk)
        {
            CommandBuffer cmd = builtinParams.commandBuffer;

            UpdateGlobalConstantBuffer(cmd);

            int currPrecomputationParamHash = m_Settings.GetPrecomputationHashCode();

            if (currPrecomputationParamHash != m_LastPrecomputationParamHash)
            {
                // Hash does not match, have to restart the precomputation from scratch.
                m_LastPrecomputedBounce = 0;
            }

            if (m_LastPrecomputedBounce == 0)
            {
                // Allocate temp tables if needed
                if (m_GroundIrradianceTables[1] == null)
                {
                    m_GroundIrradianceTables[1] = AllocateGroundIrradianceTable(1);
                }

                if (m_InScatteredRadianceTables[3] == null)
                {
                    m_InScatteredRadianceTables[3] = AllocateInScatteredRadianceTable(3);
                }

                if (m_InScatteredRadianceTables[4] == null)
                {
                    m_InScatteredRadianceTables[4] = AllocateInScatteredRadianceTable(4);
                }
            }

            if (m_LastPrecomputedBounce == m_Settings.numberOfBounces.value && m_LastPrecomputationFrameIndex < builtinParams.frameIndex)
            {
                // Free temp tables.
                // This is a deferred release (one frame late)!
                RTHandles.Release(m_GroundIrradianceTables[1]);
                RTHandles.Release(m_InScatteredRadianceTables[3]);
                RTHandles.Release(m_InScatteredRadianceTables[4]);
                m_GroundIrradianceTables[1]    = null;
                m_InScatteredRadianceTables[3] = null;
                m_InScatteredRadianceTables[4] = null;
            }

            if (m_LastPrecomputedBounce < m_Settings.numberOfBounces.value)
            {
                // When rendering into a cubemap for environment lighting, if the sky is not realtime, then we need to do all the bounces at once
                // It's ok in terms of performance because it's only done once (as long as parameters don't change).
                // However, editing parameters will be very slow.
                if (builtinParams.updateMode != EnvironmentUpdateMode.Realtime)
                {
                    for (int i = m_LastPrecomputedBounce; i < m_Settings.numberOfBounces.value; ++i)
                    {
                        PrecomputeTables(cmd);
                        m_LastPrecomputedBounce++;
                    }

                    // Update the hash for the current bounce.
                    m_LastPrecomputationParamHash  = currPrecomputationParamHash;
                    m_LastPrecomputationFrameIndex = builtinParams.frameIndex;
                }
                // In case of realtime environment lighting, we need to update only one bounce and only once per frame
                // (the same sky can be rendered into a cubemap and in the regular view).
                // Also, we obviously want the precomputation to run at least once.
                else if ((m_LastPrecomputationFrameIndex < builtinParams.frameIndex) || (m_LastPrecomputedBounce == 0))
                {
                    PrecomputeTables(cmd);
                    m_LastPrecomputedBounce++;

                    // Update the hash for the current bounce.
                    m_LastPrecomputationParamHash  = currPrecomputationParamHash;
                    m_LastPrecomputationFrameIndex = builtinParams.frameIndex;
                }
            }

            // Precomputation is done, shading is next.
            Quaternion planetRotation = Quaternion.Euler(m_Settings.planetRotation.value.x,
                                                         m_Settings.planetRotation.value.y,
                                                         m_Settings.planetRotation.value.z);

            Quaternion spaceRotation = Quaternion.Euler(m_Settings.spaceRotation.value.x,
                                                        m_Settings.spaceRotation.value.y,
                                                        m_Settings.spaceRotation.value.z);

            s_PbrSkyMaterialProperties.SetMatrix(HDShaderIDs._PixelCoordToViewDirWS, builtinParams.pixelCoordToViewDirMatrix);
            s_PbrSkyMaterialProperties.SetVector(HDShaderIDs._WorldSpaceCameraPos1, builtinParams.worldSpaceCameraPos);
            s_PbrSkyMaterialProperties.SetMatrix(HDShaderIDs._ViewMatrix1, builtinParams.viewMatrix);
            s_PbrSkyMaterialProperties.SetMatrix(HDShaderIDs._PlanetRotation, Matrix4x4.Rotate(planetRotation));
            s_PbrSkyMaterialProperties.SetMatrix(HDShaderIDs._SpaceRotation, Matrix4x4.Rotate(spaceRotation));

            if (m_LastPrecomputedBounce != 0)
            {
                s_PbrSkyMaterialProperties.SetTexture(HDShaderIDs._GroundIrradianceTexture, m_GroundIrradianceTables[0]);
                s_PbrSkyMaterialProperties.SetTexture(HDShaderIDs._AirSingleScatteringTexture, m_InScatteredRadianceTables[0]);
                s_PbrSkyMaterialProperties.SetTexture(HDShaderIDs._AerosolSingleScatteringTexture, m_InScatteredRadianceTables[1]);
                s_PbrSkyMaterialProperties.SetTexture(HDShaderIDs._MultipleScatteringTexture, m_InScatteredRadianceTables[2]);
            }
            else
            {
                s_PbrSkyMaterialProperties.SetTexture(HDShaderIDs._GroundIrradianceTexture, Texture2D.blackTexture);
                s_PbrSkyMaterialProperties.SetTexture(HDShaderIDs._AirSingleScatteringTexture, CoreUtils.blackVolumeTexture);
                s_PbrSkyMaterialProperties.SetTexture(HDShaderIDs._AerosolSingleScatteringTexture, CoreUtils.blackVolumeTexture);
                s_PbrSkyMaterialProperties.SetTexture(HDShaderIDs._MultipleScatteringTexture, CoreUtils.blackVolumeTexture);
            }

            int hasGroundAlbedoTexture = 0;

            if (m_Settings.groundAlbedoTexture.value != null)
            {
                hasGroundAlbedoTexture = 1;
                s_PbrSkyMaterialProperties.SetTexture(HDShaderIDs._GroundAlbedoTexture, m_Settings.groundAlbedoTexture.value);
            }
            s_PbrSkyMaterialProperties.SetInt(HDShaderIDs._HasGroundAlbedoTexture, hasGroundAlbedoTexture);

            int hasGroundEmissionTexture = 0;

            if (m_Settings.groundEmissionTexture.value != null)
            {
                hasGroundEmissionTexture = 1;
                s_PbrSkyMaterialProperties.SetTexture(HDShaderIDs._GroundEmissionTexture, m_Settings.groundEmissionTexture.value);
            }
            s_PbrSkyMaterialProperties.SetInt(HDShaderIDs._HasGroundEmissionTexture, hasGroundEmissionTexture);

            int hasSpaceEmissionTexture = 0;

            if (m_Settings.spaceEmissionTexture.value != null)
            {
                hasSpaceEmissionTexture = 1;
                s_PbrSkyMaterialProperties.SetTexture(HDShaderIDs._SpaceEmissionTexture, m_Settings.spaceEmissionTexture.value);
            }
            s_PbrSkyMaterialProperties.SetInt(HDShaderIDs._HasSpaceEmissionTexture, hasSpaceEmissionTexture);

            s_PbrSkyMaterialProperties.SetInt(HDShaderIDs._RenderSunDisk, renderSunDisk ? 1 : 0);

            CoreUtils.DrawFullScreen(builtinParams.commandBuffer, s_PbrSkyMaterial, s_PbrSkyMaterialProperties, renderForCubemap ? 0 : 1);
        }
Ejemplo n.º 29
0
        static void _getShaderPassAndProps(
            PictureFlusher.RenderLayer layer, Paint paint, MeshMesh mesh, float alpha,
            out int pass, out MaterialPropertyBlock props)
        {
            Vector4 viewport = layer.viewport;

            props = new MaterialPropertyBlock();
            props.SetVector("_viewport", viewport);
            props.SetFloat("_alpha", alpha);

            switch (paint.shader)
            {
            case null:
                pass = 0;
                props.SetVector("_color", _colorToVector4(paint.color));
                return;

            case _LinearGradient linear:
                pass = 1;
                props.SetMatrix("_shaderMat", linear.getGradientMat(
                                    _getShaderMatBase(layer.currentState, mesh.matrix)).toMatrix4x4());
                props.SetTexture("_shaderTex", linear.gradientTex.texture);
                props.SetVector("_leftColor", _colorToVector4(linear.leftColor));
                props.SetVector("_rightColor", _colorToVector4(linear.rightColor));
                props.SetInt("_tileMode", (int)linear.tileMode);
                return;

            case _RadialGradient radial:
                pass = 2;
                props.SetMatrix("_shaderMat", radial.getGradientMat(
                                    _getShaderMatBase(layer.currentState, mesh.matrix)).toMatrix4x4());
                props.SetTexture("_shaderTex", radial.gradientTex.texture);
                props.SetVector("_leftColor", _colorToVector4(radial.leftColor));
                props.SetVector("_rightColor", _colorToVector4(radial.rightColor));
                props.SetInt("_tileMode", (int)radial.tileMode);
                return;

            case _SweepGradient sweep:
                pass = 3;
                props.SetMatrix("_shaderMat", sweep.getGradientMat(
                                    _getShaderMatBase(layer.currentState, mesh.matrix)).toMatrix4x4());
                props.SetTexture("_shaderTex", sweep.gradientTex.texture);
                props.SetVector("_leftColor", _colorToVector4(sweep.leftColor));
                props.SetVector("_rightColor", _colorToVector4(sweep.rightColor));
                props.SetInt("_tileMode", (int)sweep.tileMode);
                props.SetFloat("_bias", sweep.bias);
                props.SetFloat("_scale", sweep.scale);
                return;

            case ImageShader image:
                pass = 4;
                props.SetMatrix("_shaderMat", image.getShaderMat(
                                    _getShaderMatBase(layer.currentState, mesh.matrix)).toMatrix4x4());
                props.SetTexture("_shaderTex", image.image.texture);
                props.SetInt("_tileMode", (int)image.tileMode);
                return;

            default:
                throw new Exception("Unknown paint.shader: " + paint.shader);
            }
        }
 private void Update()
 {
     block.SetMatrix(ShaderIDs._LastFrameModel, lastLocalToWorld);
     rend.SetPropertyBlock(block);
     lastLocalToWorld = transform.localToWorldMatrix;
 }