예제 #1
0
    private void SetupComputeShaderParameters()
    {
        int emtype = (int)emitter;

        particleComputeShader.SetInt("_EmitterType", emtype);
        particleComputeShader.SetFloat("_EmitterSize", emitterSize);
        particleComputeShader.SetBool("_UseVertexAnimation", useVertexAnimation);

        if (noises.Count > 0)
        {
            NoiseToComputeBuffer(noises);
            int nn = noises.Count > 10 ? 10 : noises.Count;
            particleComputeShader.SetInt("_NoiseCount", nn);
        }

        particleComputeShader.SetFloat("_Time", Time.timeSinceLevelLoad);
        particleComputeShader.SetFloat("_TimeStep", Time.deltaTime);
        startMinLifespan = startMinLifespan <= 0 ? 0.1f : startMinLifespan;
        startMaxLifespan = startMaxLifespan <= startMinLifespan ? startMinLifespan + 0.1f : startMaxLifespan;
        particleComputeShader.SetFloat("_MaxLifeSpan", startMaxLifespan);
        particleComputeShader.SetFloat("_MinLifeSpan", startMinLifespan);
        particleComputeShader.SetVector("_Gravity", gravity);
        particleComputeShader.SetFloat("_Drag", drag);
        particleComputeShader.SetFloat("_Vorticity", vortcity);
        particleComputeShader.SetBool("_UseFluidVelocity", useFluidVelocity);
        particleComputeShader.SetFloat("_FluidWeight", fluidWeight);
        particleComputeShader.SetVector("_FluidOffset", fluidOffset);
        particleComputeShader.SetVector("_FluidDirection", fluidDirection);
        particleComputeShader.SetVector("_FluidSize", fluidSize);
        particleComputeShader.SetFloat("_Speed", speed);
        particleComputeShader.SetVector("_CharPosition", characterPosition);
        particleComputeShader.SetVector("_CharDirection", characterDirection);
        //cs.SetFloats("_AreaSize", new float[3] { areaSize.x, areaSize.y, areaSize.z });
    }
예제 #2
0
    void ComputeDualParaboloid(ComputeShader _cs, int _kanel, int _mipmapLevel, out Color[] _cols)
    {
        int texSize = mTexSize >> _mipmapLevel;

        var buffer = new ComputeBuffer(texSize * texSize * 2, sizeof(float) * 4);

        _cs.SetTexture(_kanel, "cubemap", cubeEnvironment);
        _cs.SetBuffer(_kanel, "Result", buffer);

        _cs.SetInt("mipmapLevel", _mipmapLevel);
        _cs.SetInt("texSize", texSize);
        _cs.SetBool("applyReinhard", mApplyReinhard);
        _cs.SetBool("applyUnityDecoder", mUnityDecoder);

        SetHDRDecode(_cs);
        SetColorSpace(_cs);

        uint sizeX, sizeY, sizeZ;

        _cs.GetKernelThreadGroupSizes(
            _kanel,
            out sizeX,
            out sizeY,
            out sizeZ
            );

        _cs.Dispatch(_kanel, (texSize * 2) / (int)sizeX, texSize / (int)sizeY, 1);

        _cols = new Color[texSize * texSize * 2];

        buffer.GetData(_cols);
        buffer.Release();
    }
 public virtual void SetDynamicShaderParameters()
 {
     rayMarchingShader.SetMatrix("cameraToWorld", _camera.cameraToWorldMatrix);
     rayMarchingShader.SetMatrix("cameraInverseProjection", _camera.projectionMatrix.inverse);
     float[] light = new float[3];
     if (lighting != null)
     {
         if (lighting.type == LightType.Directional)
         {
             light[0] = lighting.transform.forward.x;
             light[1] = lighting.transform.forward.y;
             light[2] = lighting.transform.forward.z;
             rayMarchingShader.SetBool("lightIsPoint", false);
         }
         else
         {
             light[0] = lighting.transform.position.x;
             light[1] = lighting.transform.position.y;
             light[2] = lighting.transform.position.z;
             rayMarchingShader.SetBool("lightIsPoint", true);
         }
     }
     else
     {
         light[0] = -1;
         light[1] = 0;
         light[2] = 0;
         rayMarchingShader.SetBool("lightIsPoint", false);
     }
     rayMarchingShader.SetFloats("light", light);
 }
예제 #4
0
        // シミュレーション
        void Simulation()
        {
            ComputeShader cs = KernelCS;
            // CSSimulationの計算1回あたりのタイムステップの値の計算
            float timestep = (float)TimeStep / VerletIterationNum;
            // カーネルIDを取得
            int kernelId = cs.FindKernel("CSSimulation");
            // ComputeShaderカーネルの実行スレッドグループの数を計算
            int groupThreadsX =
                Mathf.CeilToInt((float)ClothResolution.x / numThreadsXY);
            int groupThreadsY =
                Mathf.CeilToInt((float)ClothResolution.y / numThreadsXY);

            // パラメータをセット
            cs.SetVector("_Gravity", Gravity);
            cs.SetFloat("_Stiffness", Stiffness);
            cs.SetFloat("_Damp", Damp);
            cs.SetFloat("_InverseMass", (float)1.0f / Mass);
            cs.SetFloat("_TimeStep", timestep);
            cs.SetFloat("_RestLength", RestLength);
            cs.SetInts("_ClothResolution",
                       new int[2] {
                ClothResolution.x, ClothResolution.y
            });

            // 衝突用球のパラメータをセット
            if (CollisionSphereTransform != null)
            {
                Vector3 collisionSpherePos = CollisionSphereTransform.position;
                float   collisionSphereRad =
                    CollisionSphereTransform.localScale.x * 0.5f + 0.01f;
                cs.SetBool("_EnableCollideSphere", true);
                cs.SetFloats("_CollideSphereParams",
                             new float[4] {
                    collisionSpherePos.x,
                    collisionSpherePos.y,
                    collisionSpherePos.z,
                    collisionSphereRad
                });
            }
            else
            {
                cs.SetBool("_EnableCollideSphere", false);
            }

            for (var i = 0; i < VerletIterationNum; i++)
            {
                // バッファをセット
                cs.SetTexture(kernelId, "_PositionBufferRO", _posBuff[0]);
                cs.SetTexture(kernelId, "_PositionPrevBufferRO", _posPrevBuff[0]);
                cs.SetTexture(kernelId, "_PositionBufferRW", _posBuff[1]);
                cs.SetTexture(kernelId, "_PositionPrevBufferRW", _posPrevBuff[1]);
                cs.SetTexture(kernelId, "_NormalBufferRW", _normBuff);
                // スレッドを実行
                cs.Dispatch(kernelId, groupThreadsX, groupThreadsY, 1);
                // 読み込み用バッファ, 書き込み用バッファを入れ替え
                SwapBuffer(ref _posBuff[0], ref _posBuff[1]);
                SwapBuffer(ref _posPrevBuff[0], ref _posPrevBuff[1]);
            }
        }
    private void updateAudioEvent()
    {
        AudioAnalyzer aa      = GetComponent <AudioAnalyzer>();
        float         bass    = aa.bass;
        float         treb    = aa.treb;
        float         vol     = aa.vol;
        bool          bassHit = aa.bassHit;
        bool          trebHit = aa.trebHit;
        bool          volHit  = aa.volHit;

        mCs.SetFloat("uBass", bass);
        mCs.SetFloat("uTreb", treb);
        mCs.SetFloat("uVol", vol);
        mCs.SetBool("uBassHit", bassHit);
        mCs.SetBool("uTrebHit", trebHit);
        mCs.SetBool("uVolHit", volHit);

        mSurfaceMat.SetFloat("uVol", vol);

        // normal event
        shuffleNormal(bassHit);

        // rotation event
        shuffleRot(bassHit);
    }
예제 #6
0
 public override void Set(ComputeShader cs, string kernel = null)
 {
     if (this.propertyID != -1)
     {
         cs.SetBool(this.propertyID, this.data);
     }
     else
     {
         cs.SetBool(this.VariableName, this.data);
     }
 }
예제 #7
0
        public void Add(Chunk chunk, Vector3 position, float radius)
        {
            //Sphere variables
            SphereComputeShader.SetBuffer(0, "Voxels", chunk.ComputeBuffer);
            SphereComputeShader.SetVector("Position", position);
            SphereComputeShader.SetFloat("Radius", radius);
            SphereComputeShader.SetBool("Populated", chunk.Populated);

            //Chunk variables
            SphereComputeShader.SetVector("Size", chunk.Size);

            SphereComputeShader.Dispatch(0, (int)chunk.Size.x / 8, (int)chunk.Size.y / 8, (int)chunk.Size.z / 8);
            chunk.Populated = true;
        }
예제 #8
0
    /// <summary>
    /// Update 1 step
    /// </summary>
    /// <param name="deltaTime">(seconds)</param>
    /// <param name="resetCollision">reset collision buffers</param>
    public static void UpdateSimulation(float deltaTime, bool resetCollision = true)
    {
        int  kernel = simShader.FindKernel("Cal");
        uint kernelX, kernelY, kernelZ;

        simShader.GetKernelThreadGroupSizes(kernel, out kernelX, out kernelY, out kernelZ);
        simShader.SetBool("reversed", reversed);
        simShader.SetBool("resetCollision", resetCollision);
        simShader.SetFloat("dt", deltaTime);
        simShader.Dispatch(kernel, buffer1.count / (int)kernelX + 1, 1, 1);

        dataChanged = true;
        reversed   ^= true;
    }
    private void InitShader()
    {
        kernelHandle = shader.FindKernel("CSMain");

        shader.SetInt("texResolution", texResolution);
        shader.SetTexture(kernelHandle, "Result", outputTexture);

        rend.material.SetTexture("_MainTex", outputTexture);

        shader.SetBool("marble", marble);
        marble = !marble;

        DispatchShader(texResolution / 8, texResolution / 8);
    }
예제 #10
0
    public void SimulateStep()
    {
        //Debug.Log("step");
        int  kernel = shader.FindKernel("CSMain");
        uint x, y, z;

        shader.GetKernelThreadGroupSizes(kernel, out x, out y, out z);
        shader.SetFloat("seed", UnityEngine.Random.value);
        shader.SetFloat("intensity", intensity);
        shader.SetBool("back", false);
        shader.Dispatch(kernel, width / (int)x + 1, width / (int)y + 1, 1);
        shader.SetBool("back", true);
        shader.Dispatch(kernel, width / (int)x + 1, width / (int)y + 1, 1);
    }
    private void AudioEvent()
    {
        AudioAnalyzer aa      = GetComponent <AudioAnalyzer>();
        float         bass    = aa.bass;
        float         treb    = aa.treb;
        bool          bassHit = aa.bassHit;
        bool          trebHit = aa.trebHit;

        mBgExposure_target = Mathf.Pow(1f - bass, 3f);

        if (bassHit && bass > .5f)
        {
            // jump scale
            triggerScaleJump = (Random.Range(0f, 1f) > 0.5f);

            //
            //if (Random.Range(0f, 1f) > 0.8f)
            //    ShuffleCage();

            //
            isCenterAttracted = (Random.Range(0f, 1f) > 0.75f);

            // texture
            // update pattern id
            if (Random.Range(0f, 1f) > 0.75f)
            {
                int patternId = (int)Random.Range(0f, 3f);
                GetComponent <TextureBendingMachine>().setPatternId(patternId);

                triggerUvMode = patternId == 0 ? true : false;
            }

            // dice to trigger texture mode
            if (Random.Range(0f, 1f) > 0.9f)
            {
                triggerTexMode = !triggerTexMode;
            }
        }

        if (trebHit && treb > .5f)
        {
        }

        mCsParticleCtrl.SetFloat("uTreb", treb);
        mCsParticleCtrl.SetFloat("uBass", bass);
        mCsParticleCtrl.SetBool("uTrebHit", trebHit);
        mCsParticleCtrl.SetBool("uBassHit", bassHit);
    }
예제 #12
0
        // Set all values from settings object on the shader. Note, variable names must be an exact match in the shader.
        // Settings object can be any class/struct containing vectors/ints/floats/bools
        public static void SetParams(System.Object settings, ComputeShader shader, string variableNamePrefix = "", string variableNameSuffix = "")
        {
            var fields = settings.GetType().GetFields();

            foreach (var field in fields)
            {
                var    fieldType          = field.FieldType;
                string shaderVariableName = variableNamePrefix + field.Name + variableNameSuffix;

                if (fieldType == typeof(UnityEngine.Vector4) || fieldType == typeof(Vector3) || fieldType == typeof(Vector2))
                {
                    shader.SetVector(shaderVariableName, (Vector4)field.GetValue(settings));
                }
                else if (fieldType == typeof(int))
                {
                    shader.SetInt(shaderVariableName, (int)field.GetValue(settings));
                }
                else if (fieldType == typeof(float))
                {
                    shader.SetFloat(shaderVariableName, (float)field.GetValue(settings));
                }
                else if (fieldType == typeof(bool))
                {
                    shader.SetBool(shaderVariableName, (bool)field.GetValue(settings));
                }
                else
                {
                    Debug.Log($"Type {fieldType} not implemented");
                }
            }
        }
예제 #13
0
    private void OnRenderImage(RenderTexture source, RenderTexture destination)
    {
        RenderBackface();
        mat.SetTexture("_BackfaceTex", GetBackfaceTexture());
        mat.SetMatrix("_WorldToView", GetComponent <Camera>().worldToCameraMatrix);

        mat.SetInt("_Debug", dbg);
        mat.SetVector("_RayPar", rayPar);
        mat.SetVector("_nfplane", new Vector4(Camera.main.nearClipPlane, Camera.main.farClipPlane, pixelThickness, reflectionDecay));

        blur.SetBool("dbg", dbg != 0);

        if (mid == null || mid2 == null || mid.width != ScreenWidth || mid.height != ScreenHeight || mid2.width != ScreenWidth || mid2.height != ScreenHeight)
        {
            mid = new RenderTexture(ScreenWidth, ScreenHeight, 0);
            mid.enableRandomWrite = true;
            mid.Create();
            mid2 = new RenderTexture(ScreenWidth, ScreenHeight, 0);
            mid2.enableRandomWrite = true;
            mid2.Create();
        }
        Graphics.Blit(source, mid, mat, 0);
        //Graphics.Blit(mid, destination);

        int kernel = blur.FindKernel("CSMain");

        blur.SetTexture(kernel, "Source", source);
        blur.SetTexture(kernel, "Input", mid);
        blur.SetTexture(kernel, "Result", mid2);
        blur.Dispatch(kernel, Mathf.CeilToInt(ScreenWidth / 8f), Mathf.CeilToInt(ScreenHeight / 8f), 1);

        Graphics.Blit(mid2, destination);
    }
 /// <summary>
 /// Set the terrain settings to a compute shader. Used for Terrain generation on the GPU and for
 /// Collision calculations on the GPU.
 /// </summary>
 /// <param name="shader">The ComputeShader to set the values for.</param>
 /// <param name="settings">The settings where the values come from</param>
 public static void TransferTerrainGeneratorSettingsToComputeShader(ComputeShader shader, TerrainGeneratorSettings settings)
 {
     shader.SetFloat("_gridSize", settings.gridSize);
     shader.SetFloat("_pow1", settings.pow1);
     shader.SetFloat("_pow2", settings.pow2);
     shader.SetFloat("_pow3", settings.pow3);
     shader.SetFloat("_pow4", settings.pow4);
     shader.SetFloat("_pow5", settings.pow5);
     shader.SetFloat("_pow6", settings.pow6);
     shader.SetFloat("_pow7", settings.pow7);
     shader.SetFloat("_scale1", settings.scale1);
     shader.SetFloat("_scale2", settings.scale2);
     shader.SetFloat("_scale3", settings.scale3);
     shader.SetFloat("_scale4", settings.scale4);
     shader.SetFloat("_scale5", settings.scale5);
     shader.SetFloat("_scale6", settings.scale6);
     shader.SetFloat("_scale7", settings.scale7);
     shader.SetFloat("_height1", settings.height1);
     shader.SetFloat("_height3", settings.height3);
     shader.SetFloat("_height4", settings.height4);
     shader.SetFloat("_height5", settings.height5);
     shader.SetFloat("_scaleMultiplier", settings.multiplierScale);
     shader.SetFloat("_weightMultiplier", settings.weightMultiplier2);
     shader.SetFloat("_temperatureScale", settings.temperatureScale);
     shader.SetFloat("_temperatureBlend", settings.temperatureBlend);
     shader.SetFloat("_temperatureRandom", settings.temperatureRandom);
     shader.SetFloat("_snowRandom", settings.snowRandom);
     shader.SetFloat("_sandRandom", settings.sandRandom);
     shader.SetFloat("_snowBlend", settings.snowBlend);
     shader.SetFloat("_sandBlend", settings.sandBlend);
     shader.SetVector("_offset", settings.offset);
     shader.SetBool("_splat", settings.splat);
 }
예제 #15
0
    private void SetShaderParameters()
    {
        // Set the target and dispatch the compute shader
        RaymarchingShader.SetTexture(0, "Result", _target);

        RaymarchingShader.SetMatrix("_CameraToWorld", _camera.cameraToWorldMatrix);                // _CameraToWorld declared in compute shader
        RaymarchingShader.SetMatrix("_CameraInverseProjection", _camera.projectionMatrix.inverse); // _CameraInverseProjection declared in compute shader
        RaymarchingShader.SetTexture(0, "_SkyboxTexture", SkyboxTexture);
        Vector3 l = DirectionalLight.transform.forward;

        RaymarchingShader.SetVector("_DirectionalLight", new Vector4(l.x, l.y, l.z, DirectionalLight.intensity));
        RaymarchingShader.SetVector("_PixelOffset", new Vector2(Random.value, Random.value));
        RaymarchingShader.SetVector("_Albedo", new Vector3(color.r, color.g, color.b));
        RaymarchingShader.SetInt("_NumberOfReflections", numberOfReflections);
        RaymarchingShader.SetBool("_SmoothBlend", smoothBlend);
        RaymarchingShader.SetFloat("_BlendCoefficient", blendCoefficient);
        RaymarchingShader.SetVector("_Ground", ground.transform.position);
        RaymarchingShader.SetVector("_GroundScale", ground.transform.localScale);
        RaymarchingShader.SetVector("_Sphere", new Vector4(sphere.transform.position.x, sphere.transform.position.y, sphere.transform.position.z, sphereRadius));
        RaymarchingShader.SetVector("_Box", box.transform.position);
        RaymarchingShader.SetVector("_BoxScale", box.transform.localScale);
        RaymarchingShader.SetVector("_Prism", prism.transform.position);
        RaymarchingShader.SetVector("_PrismSize", new Vector2(prism.transform.localScale.x, prism.transform.localScale.y));
        RaymarchingShader.SetVector("_Torus", torus.transform.position);
        RaymarchingShader.SetVector("_TorusSize", new Vector2(torus.transform.localScale.x, torus.transform.localScale.y));

        RaymarchingShader.SetVector("_Mandelbulb", mandelbulb.transform.position);
        RaymarchingShader.SetVector("_Tetrahedron", tetrahedron.transform.position);
    }
예제 #16
0
    public static void SetProperty(this ComputeShader shader, ShaderProperty property)
    {
        switch (property.Type)
        {
        case ShaderProperty.PropertyType.Float:
            shader.SetFloat(property.Id, property.FloatValue);
            break;

        case ShaderProperty.PropertyType.Int:
            shader.SetInt(property.Id, property.IntValue);
            break;

        case ShaderProperty.PropertyType.Vector:
            shader.SetVector(property.Id, property.VectorValue);
            break;

        case ShaderProperty.PropertyType.Bool:
            shader.SetBool(property.Id, property.BoolValue);
            break;

        case ShaderProperty.PropertyType.Matrix:
            shader.SetMatrix(property.Id, property.MatrixValue);
            break;

        case ShaderProperty.PropertyType.Texture:
            shader.SetTexture(property.KernelIndex, property.Id, property.TextureValue);
            break;

        default:
            throw new ArgumentOutOfRangeException();
        }
    }
예제 #17
0
        protected void ApplyBuildGenericTrianglesForChunkProperties(ComputeShader forShader, CompressedMarchingCubeChunk chunk, int numTris)
        {
            bool storeMinDegree = chunk.MinDegreeBuffer != null;

            forShader.SetBool("storeMinDegrees", storeMinDegree);

            if (storeMinDegree)
            {
                forShader.SetBuffer(0, "minDegreeAtCoord", chunk.MinDegreeBuffer);
            }
            else
            {
                forShader.SetBuffer(0, "minDegreeAtCoord", ChunkGPUDataRequest.emptyMinDegreeBuffer);
            }

            Vector4 anchor        = VectorExtension.ToVector4(chunk.AnchorPos);
            int     pointsPerAxis = chunk.NoisePointsPerAxis;

            forShader.SetVector("anchor", anchor);
            forShader.SetFloat("spacing", chunk.LOD);
            forShader.SetInt("numPointsPerAxis", pointsPerAxis);
            forShader.SetInt("length", numTris);

            forShader.SetInt("pointSpacing", chunk.PointSpacing);
        }
        public RenderTexture CreatePartitionTexture(RenderTexture muRenderTexture, RenderingSettings renderingSettings)
        {
            _renderingSettings = renderingSettings;

            _partitionDrawingShader.SetBool("DrawGrayscale", _renderingSettings.DrawGrayscale);
            _partitionDrawingShader.SetInts("ImageSize", _settings.SpaceSettings.GridSize[0], _settings.SpaceSettings.GridSize[1]);
            _partitionDrawingShader.SetInt("BorderWidth", _renderingSettings.BorderWidth);

            _partitionDrawingShader.SetTexture(_partitionDrawingKernel, "MuGrids", muRenderTexture);
            _partitionDrawingShader.SetBool("DrawThresholdValue", _renderingSettings.DrawWithMistrustCoefficient);
            _partitionDrawingShader.SetFloat("MuThresholdValue", (float)_renderingSettings.MistrustCoefficient);

            _partitionDrawingShader.Dispatch(_partitionDrawingKernel, _settings.SpaceSettings.GridSize[0] / _shaderNumThreads.x, _settings.SpaceSettings.GridSize[1] / _shaderNumThreads.y, 1);

            return(_partitionRenderTexture);
        }
예제 #19
0
    private void SetShaderParameters()
    {
        RayMarchingShader.SetFloat("_MinimumDistance", MinimumDistance);
        RayMarchingShader.SetFloat("_BreakeOffDistance", BreakeOffDistance);
        RayMarchingShader.SetInt("_ItterationLimit", ItterationLimit);
        RayMarchingShader.SetVector("_DirectionalLight", DirectionalLight.transform.forward * DirectionalLight.intensity);
        RayMarchingShader.SetFloat("_DirectionalLightAngle", DirectionalLightAngle);
        RayMarchingShader.SetFloat("_Blendingcoefficient", Blendingcoefficient);


        //RayMarchingShader.SetFloat("_RecursionDistance", RecursionDistance);
        UpdateBuffers();
        //RayMarchingShader.SetBuffer(0, "_Spheres", _SphereBuffer);
        //RayMarchingShader.SetBuffer(0, "_Boxes", _BoxBuffer);
        RayMarchingShader.SetBuffer(0, "_Sponges", _BoxBuffer);
        RayMarchingShader.SetBuffer(0, "_DistanceBuffer", _DistanceBuffer);

        RayMarchingShader.SetMatrix("_CameraToWorld", cam.cameraToWorldMatrix);
        RayMarchingShader.SetMatrix("_CameraInverseProjection", cam.projectionMatrix.inverse);
        RayMarchingShader.SetTexture(0, "_SkyboxTexture", SkyboxTexture);
        if (pass == 0)
        {
            RayMarchingShader.SetVector("_PixelOffset", new Vector2(0.5f, 0.5f));
        }
        else
        {
            RayMarchingShader.SetVector("_PixelOffset", new Vector2(Random.value, Random.value));
        }
        RayMarchingShader.SetBool("_DynamicShadows", DynamicShadows);
    }
예제 #20
0
    public void CreateNoiseVolume(RenderTexture volume, Vector3 pos, int iSize = 32)
    {
        float startTime = Time.realtimeSinceStartup;

        int mgenId = _CShaderGenerator.FindKernel("Simplex3d");

        _CShaderGenerator.SetTexture(mgenId, "Result", volume);

        Vector3 tpos = pos + Translate * Time.time * Speed;

        _CShaderGenerator.SetVector("_StartPos", new Vector4(tpos.x, tpos.y, tpos.z, 0.0f));
        //_CShaderGenerator.SetFloat("_MyTime",Time.time*Speed);
        _CShaderGenerator.SetFloat("_Str", NoiseStr);
        _CShaderGenerator.SetBool("_Cap", Cap);

        _CShaderGenerator.SetFloat("_Density", Density);
        _CShaderGenerator.SetFloat("_Contrast", Contrast);

        _CShaderGenerator.SetFloat("_NoiseA", Noise.x * 0.0001f);
        _CShaderGenerator.SetFloat("_NoiseB", Noise.y * 0.0001f);
        _CShaderGenerator.SetFloat("_NoiseC", Noise.z * 0.0001f);

        _CShaderGenerator.SetFloat("_NoiseX", Time.time * 40f + 2.0f);
        _CShaderGenerator.SetFloat("_NoiseY", Time.time * 50f + 4.0f);
        _CShaderGenerator.SetFloat("_NoiseZ", Time.time * 60f + 8.0f);

        _CShaderGenerator.Dispatch(mgenId, 1, 1, iSize);
        //Debug.Log("Noise generation time:  " + (1000.0f*(Time.realtimeSinceStartup-startTime)).ToString()+"ms");
    }
예제 #21
0
    private void UpdateParticles(RenderingData data)
    {
        Camera    mainCamera = data.cameraData.camera;
        Matrix4x4 p          = GL.GetGPUProjectionMatrix(mainCamera.projectionMatrix, false);
        float     HCot       = p.m00;
        float     VCot       = p.m11;
        Matrix4x4 vp         = p * mainCamera.worldToCameraMatrix;
        float     time_delta = Time.deltaTime;

        timer += time_delta;

        computeShader.SetVector("time", new Vector2(time_delta, timer));
        computeShader.SetVector("transportPosition", transform.position);
        computeShader.SetVector("transportForward", transform.forward);
        computeShader.SetFloat("maxCount", particleCount);
        computeShader.SetVector("seeds", new Vector3(Random.Range(1f, 10000f), Random.Range(1f, 10000f), Random.Range(1f, 10000f)));
        computeShader.SetVector("lifeRange", new Vector2(minLifetime, maxLifetime));
        computeShader.SetVector("sizeRange", new Vector2(minSize, maxSize));
        computeShader.SetMatrix("gViewProj", vp);
        computeShader.SetBool("enableSorting", enableSorting);
        computeShader.SetFloat("velocity", velocity);
        particleSortCS.SetMatrix("gViewProj", vp);

        particleSortCS.SetFloat("cotangent", VCot);
        particleSortCS.SetFloat("aspect", HCot / VCot);
        particleSortCS.SetInt("depthTexture_size", hizBuffer.Size);
        DispatchUpdate();
        EmitParticles(Mathf.RoundToInt(Time.deltaTime * emissionRate));
        CopyIndirectArgs();
        if (enableSorting) // after buffer swap,
        {
            SortParticles();
        }
        SwapBuffer();
    }
    private void updateInstance()
    {
        int kernel_id = mCs.FindKernel("CsPopUpdate");

        mCs.SetTexture(kernel_id, "out_posLife", mCsBuf_posLife[curFrame]);
        mCs.SetTexture(kernel_id, "out_velScale", mCsBuf_velScale[curFrame]);
        mCs.SetTexture(kernel_id, "out_collision", mCsBuf_collision[curFrame]);

        mCs.SetTexture(kernel_id, "pPosLife", mCsBuf_posLife[curFrame ^ 1]);
        mCs.SetTexture(kernel_id, "pVelScale", mCsBuf_velScale[curFrame ^ 1]);
        mCs.SetTexture(kernel_id, "pCollision", mCsBuf_collision[curFrame ^ 1]);

        mCs.SetTexture(kernel_id, "uBlobNormal", GetComponent <RayMarchCtrl_ComputeShader>().blobNormalBuf);
        mCs.SetTexture(kernel_id, "uBlobSurface", GetComponent <RayMarchCtrl_ComputeShader>().blobSurfaceBuf);

        mCs.SetVector("uTranslate", transform.position);
        mCs.SetVector("_WorldSpaceCameraPos", mCam.transform.position);

        mCs.SetFloat("uExposure", 1.0f - GetComponent <RayMarchCtrl_ComputeShader>().bgExposure);

        if (isInit)
        {
            mCs.SetTexture(kernel_id, "uPosLifeData",
                           GetComponent <RayMarchCtrl_ComputeShader>().posLifeBuf);
            mCs.SetTexture(kernel_id, "uVelScaleData",
                           GetComponent <RayMarchCtrl_ComputeShader>().velScaleBuf);
        }

        mCs.SetBool("isInit", isInit);

        mCs.Dispatch(
            kernel_id, bufSizeSqrt / 8, bufSizeSqrt / 8, 1);
    }
예제 #23
0
 protected void ApplyShaderProperties(int numPointsPerAxis, Vector3 anchor, float spacing, bool tryLoad)
 {
     densityShader.SetBool("tryLoadData", tryLoad);
     densityShader.SetInt("numPointsPerAxis", numPointsPerAxis);
     densityShader.SetFloat("spacing", spacing);
     densityShader.SetVector("anchor", new Vector4(anchor.x, anchor.y, anchor.z));
 }
    private void InitializeComputeShader()
    {
        m_VertexFromDepthHandle  = DepthProcessingCS.FindKernel("VertexFromDepth");
        m_NormalFromVertexHandle = DepthProcessingCS.FindKernel("NormalFromVertex");

        m_VertexBuffer = new ComputeBuffer(m_NumElements, sizeof(float) * 3);
        m_NormalBuffer = new ComputeBuffer(m_NumElements, sizeof(float) * 3);

        Texture2D depthTexture =
            DepthSource.DepthTexture;

        // Sets general compute shader variables.
        DepthProcessingCS.SetInt("DepthWidth", DepthSource.ImageDimensions.x);
        DepthProcessingCS.SetInt("DepthHeight", DepthSource.ImageDimensions.y);
        DepthProcessingCS.SetFloat("PrincipalX", DepthSource.PrincipalPoint.x);
        DepthProcessingCS.SetFloat("PrincipalY", DepthSource.PrincipalPoint.y);
        DepthProcessingCS.SetFloat("FocalLengthX", DepthSource.FocalLength.x);
        DepthProcessingCS.SetFloat("FocalLengthY", DepthSource.FocalLength.y);
        DepthProcessingCS.SetInt("NormalSamplingOffset", k_NormalSamplingOffset);
        DepthProcessingCS.SetInt("DepthPixelSkippingX", m_DepthPixelSkippingX);
        DepthProcessingCS.SetInt("DepthPixelSkippingY", m_DepthPixelSkippingY);
        DepthProcessingCS.SetInt("MeshWidth", m_MeshWidth);
        DepthProcessingCS.SetInt("MeshHeight", m_MeshHeight);
        DepthProcessingCS.SetBool("ExtendEdges", ExtendMeshEdges);
        DepthProcessingCS.SetFloat("EdgeExtensionOffset", k_EdgeExtensionOffset);
        DepthProcessingCS.SetFloat("EdgeExtensionDepthOffset", k_EdgeExtensionDepthOffset);

        // Sets shader resources for the vertex function.
        DepthProcessingCS.SetTexture(m_VertexFromDepthHandle, "depthTex", depthTexture);
        DepthProcessingCS.SetBuffer(m_VertexFromDepthHandle, "vertexBuffer", m_VertexBuffer);

        // Sets shader resources for the normal function.
        DepthProcessingCS.SetBuffer(m_NormalFromVertexHandle, "vertexBuffer", m_VertexBuffer);
        DepthProcessingCS.SetBuffer(m_NormalFromVertexHandle, "normalBuffer", m_NormalBuffer);
    }
예제 #25
0
    private void LateUpdate()
    {
        cs.SetFloat("dt", Time.deltaTime);
        cs.SetFloat("time", Time.realtimeSinceStartup);
        cs.SetBool("isCollision", bakeBeamTop.IsCollision);
        var cp = bakeBeamTop.CollisionPos;

        cs.SetVector("collisionPos", new Vector4(cp.x, cp.y, cp.z, 0));

        cs.SetBuffer(kernelID, "positionBuffer", positionBuffer);
        cs.SetBuffer(kernelID, "velocityBuffer", velocityBuffer);
        cs.SetBuffer(kernelID, "accelerateBuffer", accelerateBuffer);
        cs.SetBuffer(kernelID, "lifeBuffer", lifeBuffer);
        uint threadX, threadY, threadZ;

        cs.GetKernelThreadGroupSizes(kernelID, out threadX, out threadY, out threadZ);
        cs.Dispatch(kernelID, (int)((instancingCount) / threadX), (int)threadY, (int)threadZ);


        instancingMat.SetBuffer("positionBuffer", positionBuffer);
        instancingMat.SetBuffer("velocityBuffer", velocityBuffer);

        instancingMat.SetBuffer("lifeBuffer", lifeBuffer);
        Graphics.DrawMeshInstancedIndirect(srcMesh, 0, instancingMat,
                                           new Bounds(Vector3.zero, Vector3.one * 100.0f), argsBuffer);
    }
예제 #26
0
    public static Vector4[] GenerateExpierementalTerrainValues(Vector3Int size, float gridSize, Vector3 center, float scale, int octaves, float persistance, float lacunarity, int seed, float amplitude, float floorHeight, float floorStrength, bool useTerracing, float terraceHeight)
    {
        SetupGeneration(expierementalTerrainShader, size, gridSize, center);

        expierementalTerrainShader.SetFloat("scale", scale);
        expierementalTerrainShader.SetFloat("baseAmplitude", amplitude);
        expierementalTerrainShader.SetFloat("floorHeight", floorHeight);
        expierementalTerrainShader.SetFloat("floorStrength", floorStrength);
        expierementalTerrainShader.SetBool("useTerracing", useTerracing);
        expierementalTerrainShader.SetFloat("terraceHeight", terraceHeight);

        Vector4[] octaveOffsets = new Vector4[octaves];

        System.Random rand = new System.Random(seed);

        for (int i = 0; i < octaves; i++)
        {
            octaveOffsets[i].x = (float)rand.NextDouble() * 200000 - 100000;
            octaveOffsets[i].y = (float)rand.NextDouble() * 200000 - 100000;
            octaveOffsets[i].z = (float)rand.NextDouble() * 200000 - 100000;
        }

        SetPerlinNoiseValues(expierementalTerrainShader, octaves, persistance, lacunarity, octaveOffsets);

        DispatchShader(expierementalTerrainShader, size);

        if (!Application.isPlaying)
        {
            DestroyBuffer();
        }

        return(values);
    }
예제 #27
0
    void UpdateBuffer()
    {
        cs.SetInt("_TexWidth", texWidth);
        cs.SetInt("_TexHeight", texHeight);
        cs.SetFloat("_DA", da);
        cs.SetFloat("_DB", db);

        cs.SetFloat("_Feed", feed);
        cs.SetFloat("_K", kill);

        cs.SetFloat("_FeedMin", minf);
        cs.SetFloat("_FeedMax", maxf);
        cs.SetFloat("_KMin", mink);
        cs.SetFloat("_KMax", maxk);

        cs.SetBool("_IsFeedMap", isFeedMap);
        if (feedMap != null)
        {
            cs.SetTexture(kernelUpdate, "_FeedMap", feedMap);
        }
        cs.SetBuffer(kernelUpdate, "_BufferRead", buffers[0]);
        cs.SetBuffer(kernelUpdate, "_BufferWrite", buffers[1]);
        cs.Dispatch(kernelUpdate, Mathf.CeilToInt((float)texWidth / THREAD_NUM_X), Mathf.CeilToInt((float)texHeight / THREAD_NUM_X), 1);

        SwapBuffer();
    }
예제 #28
0
    public void createWeatherMap()
    {
        prepForNewRenderTexture(false); // no need to initialize the worley points buffer here

        // create new texture as weather map
        weatherMap = new RenderTexture(weatherMapResolution, weatherMapResolution, 0);
        weatherMap.enableRandomWrite = true;
        weatherMap.dimension         = TextureDimension.Tex2D;
        weatherMap.Create();

        NoiseTextureGenerator.SetTexture(weatherMapKernel, "ResultWeatherMap", weatherMap);

        // set perlin properties if perlin noise is going to be used
        NoiseTextureGenerator.SetInt("coveragePerlinOctaves", coveragePerlinOctaves);
        NoiseTextureGenerator.SetInt("coveragePerlinTextureResolution", coveragePerlinTextureResolution);
        NoiseTextureGenerator.SetFloat("coveragePerlinPersistence", coveragePerlinPersistence);
        NoiseTextureGenerator.SetInt("coveragePerlinLacunarity", coveragePerlinLacunarity);
        NoiseTextureGenerator.SetFloat("coveragePerlinFrequency", coveragePerlinFrequency);

        // set other weather map properties
        NoiseTextureGenerator.SetBool("coverageOption", (coverageOption == 0) ? false : true);
        NoiseTextureGenerator.SetFloat("coverageConstant", coverageConstant);
        NoiseTextureGenerator.SetFloat("cloudHeight", cloudHeight);
        NoiseTextureGenerator.SetFloat("cloudType", cloudType);

        int threadGroups = weatherMapResolution / 8;

        NoiseTextureGenerator.Dispatch(weatherMapKernel, threadGroups, threadGroups, 1); // dispatch the shader

        // save the texture as a 2D asset
        Texture2D weatherMapAs2D = RenderTextureToTexture2D(weatherMap, weatherMapResolution);

        AssetDatabase.CreateAsset(weatherMapAs2D, "Assets/Resources/WeatherMap.asset");
    }
예제 #29
0
    public void SetChunkSettings(double voxelsPerMeter, Vector3Int chunkSizes, Vector3Int chunkMeterSize, int skipDist, float half, Vector3 sideLength)
    {
        if (SurfaceSet)
        {
            return;
        }

        VoxelsPerMeter = voxelsPerMeter;
        ChunkSizeX     = chunkSizes.x;
        ChunkSizeY     = chunkSizes.y;
        ChunkSizeZ     = chunkSizes.z;

        SurfaceData = new float[(ChunkSizeX + 2) * (ChunkSizeZ + 2)];
        plantMap    = new int[ChunkSizeX * ChunkSizeZ];

        shader.SetInt("ChunkSizeX", ChunkSizeX);
        shader.SetInt("ChunkSizeY", ChunkSizeY);
        shader.SetInt("ChunkSizeZ", ChunkSizeZ);

        shader.SetFloat("VoxelsPerMeter", (float)VoxelsPerMeter);
        shader.SetInt("quality", 2);
        shader.SetInt("seed", seed);
        shader.SetBool("enableCaves", enableCaves);
        shader.SetFloat("amp", amp);
        shader.SetFloat("caveDensity", caveDensity);
        shader.SetFloat("grassOffset", grassOffset);



        //height_buffer = new ComputeBuffer(SurfaceData.Length, sizeof(float));
        //iso_buffer = new ComputeBuffer(ChunkSizeX * ChunkSizeY * ChunkSizeZ, sizeof(float));
    }
예제 #30
0
    private void UpdateRaytracerParams()
    {
        // Textures.
        int height = Mathf.Clamp(maxResolution, 1, cachedCamera.pixelHeight);

        if (height > 1 && Mathf.IsPowerOfTwo(height))
        {
            height++; // Weird black screen bug that happens when setting resolution to a power of 2...
        }
        int width = Mathf.CeilToInt(height * cachedCamera.aspect);

        CreateRenderBufferIfNeeded(width, height);
        raytracer.SetTexture(0, _Skybox, skybox);

        // Camera.
        raytracer.SetMatrix(_CameraToWorld, cachedCamera.cameraToWorldMatrix);
        raytracer.SetMatrix(_CameraInvProjection, cachedCamera.projectionMatrix.inverse);
        raytracer.SetVector(_CameraPosition, cachedTrans.position);
        raytracer.SetInt(_MaxBounces, Mathf.Max(0, maxRayBounces) + 1);

        // Other rendering.
        raytracer.SetBool(_HighQuality, highQuality);
        raytracer.SetFloat(_NoiseTime, (Time.unscaledTime * 1000f) % height);

        // Environment.
        raytracer.SetVector(_AmbientColor, ColorToVector(ambientColor, 1f));
        raytracer.SetVector(_FogParams, ColorToVector(fogColor, fogDensity));
        raytracer.SetVector(_LightDirection, dirLightTransform.forward);
        raytracer.SetVector(_LightColor, ColorToVector(dirLight.color, dirLight.intensity));
    }