public Color Evaluate(float time)
        {
            switch (mode)
            {
            default:
            case ColorGradientMode.Color:
                return(color);

            case ColorGradientMode.Gradient:
                return(gradient?.Evaluate(time) ?? new Color());
            }
        }
Esempio n. 2
0
 public void SetMaxHealth(int health)
 {
     slider.maxValue = health;
     slider.value    = health;
     fill.color      = sliderColor.Evaluate(1f);
 }
Esempio n. 3
0
 private void Start()
 {
     scaleSlider     = GetComponent <Slider>();
     fillImage.color = gradient.Evaluate(0f);
 }
    public void Refresh()
    {
        if (resolution != currentResolution)
        {
            CreateGrid();
        }

        Quaternion q       = Quaternion.Euler(rotation);
        Quaternion qInv    = Quaternion.Inverse(q);
        Vector3    point00 = q * new Vector3(-0.5f, -0.5f) + offset;
        Vector3    point10 = q * new Vector3(0.5f, -0.5f) + offset;
        Vector3    point01 = q * new Vector3(-0.5f, 0.5f) + offset;
        Vector3    point11 = q * new Vector3(0.5f, 0.5f) + offset;

        NoiseMethod method    = Noise.methods[(int)type][dimensions - 1];
        float       stepSize  = 1f / resolution;
        float       amplitude = damping ? strength / frequency : strength;

        for (int v = 0, y = 0; y <= resolution; y++)
        {
            Vector3 point0 = Vector3.Lerp(point00, point01, y * stepSize);
            Vector3 point1 = Vector3.Lerp(point10, point11, y * stepSize);

            for (int x = 0; x <= resolution; x++, v++)
            {
                Vector3     point  = Vector3.Lerp(point0, point1, x * stepSize);
                NoiseSample sample = Noise.Sum(method, point, frequency, octaves, lacunarity, persistence);
                sample = sample * 0.5f;
                if (type != NoiseMethodType.Value)
                {
                    sample = sample * 0.5f + 0.5f;
                }

                sample = type == NoiseMethodType.Value ? (sample - 0.5f) : (sample * 0.5f);
                if (coloringForStrength)
                {
                    colors[v] = coloring.Evaluate(sample.value + 0.5f);
                    sample   *= amplitude;
                }
                else
                {
                    sample   *= amplitude;
                    colors[v] = coloring.Evaluate(sample.value + 0.5f);
                }

                vertices[v].y     = sample.value;
                sample.derivative = qInv * sample.derivative;
                if (analyticalDerivatives)
                {
                    normals[v] =
                        new Vector3(-sample.derivative.x, 1f, -sample.derivative.y).normalized;
                }
                colors[v] = coloring.Evaluate(vertices[v].y + 0.5f);
            }
        }

        mesh.vertices = vertices;
        mesh.colors   = colors;
        if (!analyticalDerivatives)
        {
            CalculateNormals();
        }
        mesh.normals = normals;
    }
Esempio n. 5
0
    void DrawLine()
    {
        height           = 1.0f;
        radius           = 0.09f;
        colorChangeSpeed = 0.1f;

        InitKernelIndex();

        totalSegmentNum = (count * (maxSegmentNum + 1));
        totalVertexNum  = count * (numOfSides * maxSegmentNum + numOfSides);
        indices         = new int[3 * 2 * numOfSides * maxSegmentNum];

        Debug.Log("totalVertexNum : " + totalVertexNum);
        Debug.Log("totalSegmentNum : " + totalSegmentNum);
        Debug.Log("indexNum : " + indices.Length);

        vertices            = new TorusVertex[totalVertexNum];
        segments            = new Segment[totalSegmentNum];
        links               = new Link[count];
        initTargetPositions = new Vector3[count];
        spherePositions     = new Vector3[count * 2];

        for (int i = 0; i < totalSegmentNum; i++)
        {
            segments[i] = new Segment();
        }

        for (int i = 0; i < totalVertexNum; i++)
        {
            vertices[i] = new TorusVertex();
        }

        for (int i = 0; i < count; i++)
        {
            var fromPos = arrivePoints[i];
            var toPos   = destPoints[i];

            links[i].fromPos = fromPos;
            links[i].toPos   = toPos;

            initTargetPositions[i] = toPos;

            spherePositions[i * 2]     = fromPos;
            spherePositions[i * 2 + 1] = toPos;
        }

        SetIndices();
        InitBuffer();
        UpdateSegments();

        colorsArr = new List <Color[]>();

        for (int i = 0; i < gradientColors.Length; i++)
        {
            Gradient gradient = gradientColors[i];

            var colors = new Color[100];
            for (int j = 0; j < 100; j++)
            {
                colors[j] = gradient.Evaluate(j / 100f);
            }

            colorsArr.Add(colors);
        }
    }
 public void SetColor(float value)
 {
     image.color = gradient.Evaluate(value);
 }
Esempio n. 7
0
    public Color GetColor(float tileHeight)
    {
        Color color = colorGradient.Evaluate(Mathf.InverseLerp(height.x, height.y, tileHeight));

        return(color);
    }
Esempio n. 8
0
        IEnumerator AnimateTextComponent()
        {
            //Increase timer over Time to Evaluate Animation Curve and Color Gradient
            m_timer = 0;
            this.Text.gameObject.SetActive(true);
            //Time factor for Lerping
            float curveTimerX = 0;
            float curveTimerY = 0;
            float x;
            float y;
            //Time factor forLerpin
            float fontSizeCurveAnim = 0;
            //Animation Length
            float animationTime = m_animDuration;
            //change Icon Alpha with Text Alpahe
            var tempColor            = IconLeft.isActiveAndEnabled ? IconLeft.color : IconRight.color;
            var backgroundColorCache = Background.color;

            //as long as timer is not bigger than the Animation Length
            while (m_timer < animationTime)
            {
                //Evaluate  Timer with the Curve
                curveTimerX = m_animCurveX.Evaluate(m_timer);
                curveTimerY = m_animCurveY.Evaluate(m_timer);

                //if amount == 0 no Size Animation
                if (m_amount != 0)
                {
                    fontSizeCurveAnim = m_fontSizeAnimCurve.Evaluate(m_timer);
                    Text.fontSize     = (int)Mathf.Lerp(this.m_fontSize, m_amount, fontSizeCurveAnim);
                }

                this.Text.color        = m_colorGradient.Evaluate(m_timer);
                tempColor.a            = Text.color.a;
                backgroundColorCache.a = Text.color.a;


                if (IconLeft.isActiveAndEnabled)
                {
                    IconLeft.color = tempColor;
                }
                else
                {
                    IconRight.color = tempColor;
                }

                if (Background.isActiveAndEnabled)
                {
                    //Text.color;
                    Background.color = backgroundColorCache;
                }

                //Based on the Transform Z-Axis, disable if less than 0
                bool isInView = m_rectTransform.position.z < 0;
                this.gameObject.SetActive(!isInView);
                if (m_stack && m_onScreen == false)
                {
                    //m_startPosition = Vector3.Lerp(m_startPosition, m_currentPosition, m_timer / animationTime);
                }

                //ternary position = If(onScreen ==false)cam.WorldToScreenPoint(startPosition) else startPosition
                this.transform.position =
                    m_onScreen == false?m_cam.WorldToScreenPoint(m_startPosition) : m_startPosition;

                //Lerp the Text GameObject in localSpace
                x = Mathf.Lerp(0, m_animationDirection.x, curveTimerX);
                y = Mathf.Lerp(0, m_animationDirection.y, curveTimerY);
                this.SctBox.localPosition = new Vector3(x, y, 0);

                m_timer += Time.deltaTime;

                yield return(null);
            }

            //disable Text Component to avoid weird jump behaviour
            this.Text.gameObject.SetActive(false);
            this.IconRight.enabled    = false;
            this.IconLeft.enabled     = false;
            Background.enabled        = false;
            this.SctBox.localPosition = Vector3.zero;
            //deactivate this Object -> back to Pool
            this.gameObject.SetActive(false);
        }
Esempio n. 9
0
    // Start Coroutine of reading the points from the XYZ file and creating the meshes
    IEnumerator loadXYZ(string dPath)
    {
        // Read file
        numPoints = File.ReadAllLines(Application.dataPath + dPath).Length;

        StreamReader sr = new StreamReader(Application.dataPath + dPath);

        points   = new Vector3[numPoints];
        colors   = new Color[numPoints];
        minValue = new Vector3();

        for (int i = 0; i < numPoints; i++)
        {
            string[] buffer = sr.ReadLine().Split(',');

            if (!invertYZ)
            {
                points[i] = new Vector3(float.Parse(buffer[0]) * scale, float.Parse(buffer[1]) * scale, float.Parse(buffer[2]) * scale);
            }
            else
            {
                points[i] = new Vector3(float.Parse(buffer[0]) * scale, float.Parse(buffer[2]) * scale, float.Parse(buffer[1]) * scale);
            }

            // Test enum for technique to colour points
            // Apply default point colour
            if (colourPointsBy == cpb.Default)
            {
                colors[i] = defaultPointColour;
            }

            // Colour points by RGB values
            if (colourPointsBy == cpb.RGB)
            {
                if (buffer.Length >= 5)
                {
                    colors[i] = new Color(int.Parse(buffer[3]) / 255.0f, int.Parse(buffer[4]) / 255.0f, int.Parse(buffer[5]) / 255.0f);
                }
                else
                {
                    colors[i] = defaultPointColour;
                }
            }

            // TO DO - Automate calculation of minHeight and maxHeight
            // Colour points by Height
            else if (colourPointsBy == cpb.Height)
            {
                if (!invertYZ)
                {
                    localDiff = float.Parse(buffer[1]) - minHeight;
                }
                else
                {
                    localDiff = float.Parse(buffer[2]) - minHeight;
                }
                colors[i] = colourGradient.Evaluate(localDiff / heightDiff);
            }

            //TO DO - Automate calculation of minIntensity and maxIntensity
            // Colour points by intensity
            else if (colourPointsBy == cpb.Intensity)
            {
                relativeDiff = float.Parse(buffer[6]) - minIntensity;
                colors[i]    = colourGradient.Evaluate(relativeDiff / intensityDiff);
            }

            // Relocate points near the origin
            if (relocateToOrigin == true)
            {
                calculateMin(points[i]);
            }

            // Processing GUI
            progress = i * 1.0f / (numPoints - 1) * 1.0f;
            if (i % Mathf.FloorToInt(numPoints / 20) == 0)
            {
                guiText = i.ToString() + " out of " + numPoints.ToString() + " loaded";
                yield return(null);
            }
        }

        // Instantiate Point Groups
        numPointGroups = Mathf.CeilToInt(numPoints * 1.0f / limitPoints * 1.0f);

        pointCloud = new GameObject(filename);

        for (int i = 0; i < numPointGroups - 1; i++)
        {
            InstantiateMesh(i, limitPoints);
            if (i % 10 == 0)
            {
                guiText = i.ToString() + " out of " + numPointGroups.ToString() + " PointGroups loaded";
                yield return(null);
            }
        }
        InstantiateMesh(numPointGroups - 1, numPoints - (numPointGroups - 1) * limitPoints);

        //Store PointCloud
        UnityEditor.PrefabUtility.SaveAsPrefabAsset(pointCloud, "Assets/Resources/PointCloudMeshes/" + filename + ".prefab");

        loaded = true;
    }
Esempio n. 10
0
 public void SetMaxHealth(float health)
 {
     slider.maxValue = health;
     slider.value    = health;
     fill.color      = gradient.Evaluate(1f);
 }
 public void ApplyLocalWindZoneColor(float windForce01)
 {
     localWindZoneMaterial.color = localWindZoneGradient.Evaluate(windForce01);
 }
Esempio n. 12
0
 protected Color getColor()
 {
     return(color.Evaluate(curve.Evaluate(timeKeeper)));
 }
Esempio n. 13
0
 void SetStressBarColor(float value)
 {
     rageImageBar.color = gradient.Evaluate(rageSlider.normalizedValue);
 }
Esempio n. 14
0
 public static Color Eval(float val)
 {
     return(InfluenceGradient.Evaluate(Mathf.Sign(val) * Mathf.Pow(Mathf.Abs(val), .5f) / 2 + .5f));
 }
Esempio n. 15
0
        public string GetChargeValueText()
        {
            int   numShots = Mathf.FloorToInt(this._charge / JuicePerDischarge);
            int   maxShots = Mathf.FloorToInt(this.capacity / JuicePerDischarge);
            float num      = numShots / maxShots;

            //return Language.main.GetFormat<string, float, int, float>("BatteryCharge", ColorUtility.ToHtmlStringRGBA(gradient.Evaluate(num)), num, numShots, maxShots);
            return(Language.main.GetFormat <string, float, int, int>("<color=#{0}>{1,4}u ({2}/{3})</color>", ColorUtility.ToHtmlStringRGBA(gradient.Evaluate(num)), Mathf.Floor(this.charge), numShots, maxShots));
        }
Esempio n. 16
0
    // Update is called once per frame
    void Update()
    {
        float key = image.fillAmount;

        image.color = gradient.Evaluate(key);
    }
Esempio n. 17
0
    private void Update()
    {
        float deltaTime = Time.deltaTime;

        FractalPart rootPart = parts[0][0];

        rootPart.spinAngle    += rootPart.spinVelocity * deltaTime;
        rootPart.worldRotation =
            mul(transform.rotation,
                mul(rootPart.rotation, quaternion.RotateY(rootPart.spinAngle)));
        rootPart.worldPosition = transform.position;
        parts[0][0]            = rootPart;
        float    objectScale = transform.lossyScale.x;
        float3x3 r           = float3x3(rootPart.worldRotation) * objectScale;

        matrices[0][0] = float3x4(r.c0, r.c1, r.c2, rootPart.worldPosition);

        float scale = objectScale;

        JobHandle jobHandle = default;

        for (int li = 1; li < parts.Length; li++)
        {
            scale    *= 0.5f;
            jobHandle = new UpdateFractalLevelJob
            {
                deltaTime = deltaTime,
                scale     = scale,
                parents   = parts[li - 1],
                parts     = parts[li],
                matrices  = matrices[li]
            }.ScheduleParallel(parts[li].Length, 5, jobHandle);
        }
        jobHandle.Complete();

        Bounds bounds    = new Bounds(rootPart.worldPosition, 3f * objectScale * Vector3.one);
        int    leafIndex = matricesBuffers.Length - 1;

        for (int i = 0; i < matricesBuffers.Length; i++)
        {
            ComputeBuffer buffer = matricesBuffers[i];

            Mesh  instanceMesh;
            Color colorA, colorB;
            if (i == leafIndex)
            {
                colorA       = leafColorA;
                colorB       = leafColorB;
                instanceMesh = leafMesh;
            }
            else
            {
                float gradientInterpolator = i / (matricesBuffers.Length - 1f);
                colorA       = gradientA.Evaluate(gradientInterpolator);
                colorB       = gradientB.Evaluate(gradientInterpolator);
                instanceMesh = mesh;
            }

            propertyBlock.SetColor(colorAID, colorA);
            propertyBlock.SetColor(colorBID, colorB);
            buffer.SetData(matrices[i]);
            propertyBlock.SetBuffer(matricesID, buffer);
            propertyBlock.SetVector(sequenceNumbersID, sequenceNumbers[i]);
            Graphics.DrawMeshInstancedProcedural(instanceMesh, 0, material, bounds, buffer.count, propertyBlock);
        }
    }
Esempio n. 18
0
 private void Update()
 {
     spriteRenderer.color = gradient.Evaluate(Mathf.PingPong(Time.time * speedMultiplier, 1f));
 }
Esempio n. 19
0
 public IEnumerator ColorHeight(Gradient gradient, float min = 0.0f, float max = 1.0f)
 {
     //Color vertices according to height
     //Values are normalized to enable a min max
     Color[] vertex_colors = new Color[mesh_deforming.vertices.Length];
     for (int y = 0; y < mesh_size.y; y++)
     {
         //yield return null;
         for (int x = 0; x < mesh_size.x; x++)
         {
             int      i = (int)(y * mesh_size.x) + x;
             Triangle current_triangle = triangles[i];
             //float lerp = Mathf.InverseLerp(minmax_Y.x, minmax_Y.y, current_triangle.value);
             float lerp = Mathf.InverseLerp(min, 1.0f, current_triangle.value);
             vertex_colors[current_triangle.i1] = vertex_colors[current_triangle.i2] = vertex_colors[current_triangle.i3] = gradient.Evaluate(lerp);
             mesh_deforming.colors = vertex_colors;
         }
     }
     mesh_deforming.colors = vertex_colors;
     Debug.Log("Applied color height.");
     yield break;
 }
Esempio n. 20
0
 void UpdateSlider()
 {
     fill.color = gradient.Evaluate(1 / ((slider.maxValue - slider.minValue) / slider.value));
 }
Esempio n. 21
0
 private void Update()
 {
     renderer.material.color = colorGradient.Evaluate(value);
     value = Mathf.Lerp(value, 0f, lerpVelocity * Time.deltaTime);
 }
        private void GenerateMesh()
        {
            DeleteGrid();

            var   verticesList     = new List <Vector3>();
            var   trianglesList    = new List <int>();
            var   colorList        = new List <Color>();
            float minTerrainHeight = 0;
            float maxTerrainHeight = 0;

            #region New
            int scale = 0;
            for (int depth = 0; depth < _mapSize - 1; depth++)
            {
                for (int width = 0; width < _mapSize - 1; width++)
                {
                    for (int z = depth; z < depth + 2; z++)
                    {
                        for (int x = width; x < width + 2; x++)
                        {
                            float y = _heightMap[x, z];
                            verticesList.Add(new Vector3(x, y, z));

                            // For gradients min and max value
                            if (y > maxTerrainHeight)
                            {
                                maxTerrainHeight = y;
                            }
                            if (y < minTerrainHeight)
                            {
                                minTerrainHeight = y;
                            }
                        }
                    }

                    trianglesList.Add(0 + scale);
                    trianglesList.Add(2 + scale);
                    trianglesList.Add(3 + scale);
                    trianglesList.Add(0 + scale);
                    trianglesList.Add(3 + scale);
                    trianglesList.Add(1 + scale);

                    scale += 4;
                }
            }
            #endregion

            foreach (Vector3 vertex in verticesList)
            {
                float height = Mathf.InverseLerp(minTerrainHeight, maxTerrainHeight, vertex.y);
                colorList.Add(_gradient.Evaluate(height));
            }

            #region Old
            // for (int z = 0, i = 0; z <= _mapSize; z++) {
            //     for (int x = 0; x <= _mapSize; x++) {
            //         verticesList[i] = new Vector3(x, _heightMap[x, z], z);
            //         i++;
            //     }
            // }
            //
            // int vert = 0;
            // int tris = 0;
            // for (int z = 0; z < _mapSize; z++) {
            //     for (int i = 0; i < _mapSize; i++) {
            //         trianglesList[tris + 0] = vert + 0;
            //         trianglesList[tris + 1] = vert + _mapSize + 1;
            //         trianglesList[tris + 2] = vert + 1;
            //         trianglesList[tris + 3] = vert + 1;
            //         trianglesList[tris + 4] = vert + _mapSize + 1;
            //         trianglesList[tris + 5] = vert + _mapSize + 2;
            //
            //         vert++;
            //         tris += 6;
            //     }
            //     vert++;
            // }
            #endregion

            _mesh.Clear();
            _mesh.indexFormat = UnityEngine.Rendering.IndexFormat.UInt32;
            _mesh.vertices    = verticesList.ToArray();
            _mesh.triangles   = trianglesList.ToArray();
            _mesh.colors      = colorList.ToArray();

            _mesh.RecalculateNormals();
            _mesh.RecalculateBounds();
            _mesh.RecalculateTangents();

            _parent = Instantiate(_parentPrefab);
        }
Esempio n. 23
0
 private void UpdateColor()
 {
     m_Renderer.GetPropertyBlock(m_MPB);
     m_MPB.SetColor("_Color", m_Gradient.Evaluate(m_Energy));
     m_Renderer.SetPropertyBlock(m_MPB);
 }
 public void SetHealth(int health)
 {
     slider.value = health;
     fill.color   = gradient.Evaluate(slider.normalizedValue);
 }
    void MakeSomeNoise()
    {
        perlin1 = new Vector2(perlinStartX, perlinStartY);
        var  perlin2      = new Vector2(Random.Range(0f, 100f), Random.Range(0f, 100f));
        var  perlinOffset = Random.value;
        Mesh sm           = originalMesh;
        Mesh lm           = new Mesh();

        Vector3[] vertices         = sm.vertices;
        Vector3[] normals          = sm.normals;
        int[]     tris             = sm.triangles;
        Vector3[] originalVertices = null;
        if (originalMesh != null)
        {
            originalVertices = originalMesh.vertices;
        }
        Color[] colors = new Color[vertices.Length];

        for (int i = 0; i < vertices.Length; i++)
        {
            float xCoord = perlin1.x + vertices[i].x * scale;
            float yCoord = perlin1.y + vertices[i].z * scale;


            var y = (Mathf.PerlinNoise(xCoord, yCoord) - 0.5f);

            vertices[i].y = (y * power);

            if (originalVertices != null)
            {
                vertices[i].y += originalVertices[i].y;
                if (flatBottom && originalVertices[i].y < 0)
                {
                    vertices[i].y = originalVertices[i].y;
                }
            }

            colors[i] = gradient.Evaluate(y + perlinOffset * Mathf.PerlinNoise(perlin2.x, perlin2.y));
        }

        for (int i = 0; i < normals.Length; i++)
        {
            if (normals[i].y < 0.1f)
            {
                colors[i] = sideColor;
            }
        }

        lm.vertices  = vertices;
        lm.triangles = tris;

        lm.colors = colors;
        lm.RecalculateBounds();
        lm.RecalculateNormals();

        MeshFilter mf = GetComponent <MeshFilter>();

        mf.mesh = lm;

        MeshCollider mc = GetComponent <MeshCollider>();

        if (mc != null)
        {
            mc.sharedMesh = lm;
        }
    }
Esempio n. 26
0
    private static MeshDraft TerrainDraft(Vector3 terrainSize, float cellSize, Vector2 noiseOffset, float noiseScale, Gradient gradient, float uvScale)  //change in this script
    {
        int xSegments = Mathf.FloorToInt(terrainSize.x / cellSize);
        int zSegments = Mathf.FloorToInt(terrainSize.z / cellSize);

        float     xStep       = terrainSize.x / xSegments;
        float     zStep       = terrainSize.z / zSegments;
        int       vertexCount = 6 * xSegments * zSegments;
        MeshDraft draft       = new MeshDraft {
            name      = "Terrain",
            vertices  = new List <Vector3>(vertexCount),
            triangles = new List <int>(vertexCount),
            normals   = new List <Vector3>(vertexCount),
            colors    = new List <Color>(vertexCount),
            uv        = new List <Vector2>(vertexCount)//addition in this script
        };

        for (int i = 0; i < vertexCount; i++)
        {
            draft.vertices.Add(Vector3.zero);
            draft.triangles.Add(0);
            draft.normals.Add(Vector3.zero);
            draft.colors.Add(Color.black);
            draft.uv.Add(Vector2.zero);//addition in this script
        }

        for (int x = 0; x < xSegments; x++)
        {
            for (int z = 0; z < zSegments; z++)
            {
                int index0 = 6 * (x + z * xSegments);
                int index1 = index0 + 1;
                int index2 = index0 + 2;
                int index3 = index0 + 3;
                int index4 = index0 + 4;
                int index5 = index0 + 5;

                float height00 = GetHeight(x + 0, z + 0, xSegments, zSegments, noiseOffset, noiseScale);
                float height01 = GetHeight(x + 0, z + 1, xSegments, zSegments, noiseOffset, noiseScale);
                float height10 = GetHeight(x + 1, z + 0, xSegments, zSegments, noiseOffset, noiseScale);
                float height11 = GetHeight(x + 1, z + 1, xSegments, zSegments, noiseOffset, noiseScale);

                Vector3 vertex00 = new Vector3((x + 0) * xStep, height00 * terrainSize.y, (z + 0) * zStep);
                Vector3 vertex01 = new Vector3((x + 0) * xStep, height01 * terrainSize.y, (z + 1) * zStep);
                Vector3 vertex10 = new Vector3((x + 1) * xStep, height10 * terrainSize.y, (z + 0) * zStep);
                Vector3 vertex11 = new Vector3((x + 1) * xStep, height11 * terrainSize.y, (z + 1) * zStep);

                draft.vertices[index0] = vertex00;
                draft.vertices[index1] = vertex01;
                draft.vertices[index2] = vertex11;
                draft.vertices[index3] = vertex00;
                draft.vertices[index4] = vertex11;
                draft.vertices[index5] = vertex10;

                draft.colors[index0] = gradient.Evaluate(height00);
                draft.colors[index1] = gradient.Evaluate(height01);
                draft.colors[index2] = gradient.Evaluate(height11);
                draft.colors[index3] = gradient.Evaluate(height00);
                draft.colors[index4] = gradient.Evaluate(height11);
                draft.colors[index5] = gradient.Evaluate(height10);

                Vector3 normal000111 = Vector3.Cross(vertex01 - vertex00, vertex11 - vertex00).normalized;
                Vector3 normal001011 = Vector3.Cross(vertex11 - vertex00, vertex10 - vertex00).normalized;

                draft.normals[index0] = normal000111;
                draft.normals[index1] = normal000111;
                draft.normals[index2] = normal000111;
                draft.normals[index3] = normal001011;
                draft.normals[index4] = normal001011;
                draft.normals[index5] = normal001011;

                draft.triangles[index0] = index0;
                draft.triangles[index1] = index1;
                draft.triangles[index2] = index2;
                draft.triangles[index3] = index3;
                draft.triangles[index4] = index4;
                draft.triangles[index5] = index5;

                //addition in this script
                float xUV0 = ((float)x / (float)xSegments) * uvScale;
                float zUV0 = ((float)z / (float)zSegments) * uvScale;
                float xUV1 = ((float)(x + 1) / (float)xSegments) * uvScale;
                float zUV1 = ((float)(z + 1) / (float)zSegments) * uvScale;
                draft.uv[index0] = new Vector2(xUV0, zUV0);
                draft.uv[index1] = new Vector2(xUV0, zUV1);
                draft.uv[index2] = new Vector2(xUV1, zUV1);
                draft.uv[index3] = new Vector2(xUV0, zUV0);
                draft.uv[index4] = new Vector2(xUV1, zUV1);
                draft.uv[index5] = new Vector2(xUV1, zUV0);
            }
        }

        return(draft);
    }
Esempio n. 27
0
        /// <summary> Draw a bezier from output to input in grid coordinates </summary>
        public void DrawNoodle(Gradient gradient, NoodlePath path, NoodleStroke stroke, float thickness, List <Vector2> gridPoints)
        {
            // convert grid points to window points
            for (int i = 0; i < gridPoints.Count; ++i)
            {
                gridPoints[i] = GridToWindowPosition(gridPoints[i]);
            }

            Handles.color = gradient.Evaluate(0f);
            int length = gridPoints.Count;

            switch (path)
            {
            case NoodlePath.Curvy:
                Vector2 outputTangent = Vector2.right;
                for (int i = 0; i < length - 1; i++)
                {
                    Vector2 inputTangent;
                    // Cached most variables that repeat themselves here to avoid so many indexer calls :p
                    Vector2 point_a = gridPoints[i];
                    Vector2 point_b = gridPoints[i + 1];
                    float   dist_ab = Vector2.Distance(point_a, point_b);
                    if (i == 0)
                    {
                        outputTangent = zoom * dist_ab * 0.01f * Vector2.right;
                    }
                    if (i < length - 2)
                    {
                        Vector2 point_c       = gridPoints[i + 2];
                        Vector2 ab            = (point_b - point_a).normalized;
                        Vector2 cb            = (point_b - point_c).normalized;
                        Vector2 ac            = (point_c - point_a).normalized;
                        Vector2 p             = (ab + cb) * 0.5f;
                        float   tangentLength = (dist_ab + Vector2.Distance(point_b, point_c)) * 0.005f * zoom;
                        float   side          = ((ac.x * (point_b.y - point_a.y)) - (ac.y * (point_b.x - point_a.x)));

                        p            = tangentLength * Mathf.Sign(side) * new Vector2(-p.y, p.x);
                        inputTangent = p;
                    }
                    else
                    {
                        inputTangent = zoom * dist_ab * 0.01f * Vector2.left;
                    }

                    // Calculates the tangents for the bezier's curves.
                    float   zoomCoef  = 50 / zoom;
                    Vector2 tangent_a = point_a + outputTangent * zoomCoef;
                    Vector2 tangent_b = point_b + inputTangent * zoomCoef;
                    // Hover effect.
                    int division = Mathf.RoundToInt(.2f * dist_ab) + 3;
                    // Coloring and bezier drawing.
                    int     draw           = 0;
                    Vector2 bezierPrevious = point_a;
                    for (int j = 1; j <= division; ++j)
                    {
                        if (stroke == NoodleStroke.Dashed)
                        {
                            draw++;
                            if (draw >= 2)
                            {
                                draw = -2;
                            }
                            if (draw < 0)
                            {
                                continue;
                            }
                            if (draw == 0)
                            {
                                bezierPrevious = CalculateBezierPoint(point_a, tangent_a, tangent_b, point_b, (j - 1f) / (float)division);
                            }
                        }
                        if (i == length - 2)
                        {
                            Handles.color = gradient.Evaluate((j + 1f) / division);
                        }
                        Vector2 bezierNext = CalculateBezierPoint(point_a, tangent_a, tangent_b, point_b, j / (float)division);
                        DrawAAPolyLineNonAlloc(thickness, bezierPrevious, bezierNext);
                        bezierPrevious = bezierNext;
                    }
                    outputTangent = -inputTangent;
                }
                break;

            case NoodlePath.Straight:
                for (int i = 0; i < length - 1; i++)
                {
                    Vector2 point_a = gridPoints[i];
                    Vector2 point_b = gridPoints[i + 1];
                    // Draws the line with the coloring.
                    Vector2 prev_point = point_a;
                    // Approximately one segment per 5 pixels
                    int segments = (int)Vector2.Distance(point_a, point_b) / 5;
                    segments = Math.Max(segments, 1);

                    int draw = 0;
                    for (int j = 0; j <= segments; j++)
                    {
                        draw++;
                        float   t    = j / (float)segments;
                        Vector2 lerp = Vector2.Lerp(point_a, point_b, t);
                        if (draw > 0)
                        {
                            if (i == length - 2)
                            {
                                Handles.color = gradient.Evaluate(t);
                            }
                            DrawAAPolyLineNonAlloc(thickness, prev_point, lerp);
                        }
                        prev_point = lerp;
                        if (stroke == NoodleStroke.Dashed && draw >= 2)
                        {
                            draw = -2;
                        }
                    }
                }
                break;

            case NoodlePath.Angled:
                for (int i = 0; i < length - 1; i++)
                {
                    if (i == length - 1)
                    {
                        continue;                      // Skip last index
                    }
                    if (gridPoints[i].x <= gridPoints[i + 1].x - (50 / zoom))
                    {
                        float   midpoint = (gridPoints[i].x + gridPoints[i + 1].x) * 0.5f;
                        Vector2 start_1  = gridPoints[i];
                        Vector2 end_1    = gridPoints[i + 1];
                        start_1.x = midpoint;
                        end_1.x   = midpoint;
                        if (i == length - 2)
                        {
                            DrawAAPolyLineNonAlloc(thickness, gridPoints[i], start_1);
                            Handles.color = gradient.Evaluate(0.5f);
                            DrawAAPolyLineNonAlloc(thickness, start_1, end_1);
                            Handles.color = gradient.Evaluate(1f);
                            DrawAAPolyLineNonAlloc(thickness, end_1, gridPoints[i + 1]);
                        }
                        else
                        {
                            DrawAAPolyLineNonAlloc(thickness, gridPoints[i], start_1);
                            DrawAAPolyLineNonAlloc(thickness, start_1, end_1);
                            DrawAAPolyLineNonAlloc(thickness, end_1, gridPoints[i + 1]);
                        }
                    }
                    else
                    {
                        float   midpoint = (gridPoints[i].y + gridPoints[i + 1].y) * 0.5f;
                        Vector2 start_1  = gridPoints[i];
                        Vector2 end_1    = gridPoints[i + 1];
                        start_1.x += 25 / zoom;
                        end_1.x   -= 25 / zoom;
                        Vector2 start_2 = start_1;
                        Vector2 end_2   = end_1;
                        start_2.y = midpoint;
                        end_2.y   = midpoint;
                        if (i == length - 2)
                        {
                            DrawAAPolyLineNonAlloc(thickness, gridPoints[i], start_1);
                            Handles.color = gradient.Evaluate(0.25f);
                            DrawAAPolyLineNonAlloc(thickness, start_1, start_2);
                            Handles.color = gradient.Evaluate(0.5f);
                            DrawAAPolyLineNonAlloc(thickness, start_2, end_2);
                            Handles.color = gradient.Evaluate(0.75f);
                            DrawAAPolyLineNonAlloc(thickness, end_2, end_1);
                            Handles.color = gradient.Evaluate(1f);
                            DrawAAPolyLineNonAlloc(thickness, end_1, gridPoints[i + 1]);
                        }
                        else
                        {
                            DrawAAPolyLineNonAlloc(thickness, gridPoints[i], start_1);
                            DrawAAPolyLineNonAlloc(thickness, start_1, start_2);
                            DrawAAPolyLineNonAlloc(thickness, start_2, end_2);
                            DrawAAPolyLineNonAlloc(thickness, end_2, end_1);
                            DrawAAPolyLineNonAlloc(thickness, end_1, gridPoints[i + 1]);
                        }
                    }
                }
                break;

            case NoodlePath.ShaderLab:
                Vector2 start = gridPoints[0];
                Vector2 end   = gridPoints[length - 1];
                //Modify first and last point in array so we can loop trough them nicely.
                gridPoints[0]          = gridPoints[0] + Vector2.right * (20 / zoom);
                gridPoints[length - 1] = gridPoints[length - 1] + Vector2.left * (20 / zoom);
                //Draw first vertical lines going out from nodes
                Handles.color = gradient.Evaluate(0f);
                DrawAAPolyLineNonAlloc(thickness, start, gridPoints[0]);
                Handles.color = gradient.Evaluate(1f);
                DrawAAPolyLineNonAlloc(thickness, end, gridPoints[length - 1]);
                for (int i = 0; i < length - 1; i++)
                {
                    Vector2 point_a = gridPoints[i];
                    Vector2 point_b = gridPoints[i + 1];
                    // Draws the line with the coloring.
                    Vector2 prev_point = point_a;
                    // Approximately one segment per 5 pixels
                    int segments = (int)Vector2.Distance(point_a, point_b) / 5;
                    segments = Math.Max(segments, 1);

                    int draw = 0;
                    for (int j = 0; j <= segments; j++)
                    {
                        draw++;
                        float   t    = j / (float)segments;
                        Vector2 lerp = Vector2.Lerp(point_a, point_b, t);
                        if (draw > 0)
                        {
                            if (i == length - 2)
                            {
                                Handles.color = gradient.Evaluate(t);
                            }
                            DrawAAPolyLineNonAlloc(thickness, prev_point, lerp);
                        }
                        prev_point = lerp;
                        if (stroke == NoodleStroke.Dashed && draw >= 2)
                        {
                            draw = -2;
                        }
                    }
                }
                gridPoints[0]          = start;
                gridPoints[length - 1] = end;
                break;
            }
        }
Esempio n. 28
0
 public void SetHealthBarColor(float percentage)
 {
     HealthBarImage.color = gradient.Evaluate(percentage);
 }
Esempio n. 29
0
        /// <summary>
        /// Converts an array of colors into an approximate Gradient using a max of 8 color keys and 8 alpha keys
        /// </summary>
        /// <param name="colors"></param>
        /// <param name="gradient"></param>
        /// <param name="approxColors"></param>
        /// <param name="approxAlpha"></param>
        /// <returns>Error data specifying deviation from ideal case</returns>
        public static ErrorData ApproximateColorArrayAsGradient(Color[] colors, Gradient gradient, List <GradientColorKey> approxColors, List <GradientAlphaKey> approxAlpha)
        {
            approxAlpha.Clear();
            approxColors.Clear();

            float invLength = 1f / (colors.Length - 1);

            // Init the lists
            for (int i = 0; i < colors.Length - 1; i++)
            {
                // Add first alpha value that deviates from front
                if (colors[i].a != colors[i + 1].a)
                {
                    var t = i * invLength;
                    approxAlpha.Add(new GradientAlphaKey(colors[i].a, t));
                    break;
                }
            }
            for (int i = 0; i < colors.Length - 1; i++)
            {
                // Add first color value that deviates from front
                if (colors[i].r != colors[i + 1].r || colors[i].g != colors[i + 1].g || colors[i].b != colors[i + 1].b)
                {
                    var t = i * invLength;
                    approxColors.Add(new GradientColorKey(colors[i], t));
                    break;
                }
            }
            for (int i = colors.Length - 1; i > 0; i--)
            {
                // Add first alpha value that deviates from back
                if (colors[i].a != colors[i - 1].a)
                {
                    var t = i * invLength;
                    approxAlpha.Add(new GradientAlphaKey(colors[i].a, t));
                    break;
                }
            }
            for (int i = colors.Length - 1; i > 0; i--)
            {
                // Add first color value that deviates from back
                if (colors[i].r != colors[i - 1].r || colors[i].g != colors[i - 1].g || colors[i].b != colors[i - 1].b)
                {
                    var t = i * invLength;
                    approxColors.Add(new GradientColorKey(colors[i], t));
                    break;
                }
            }
            gradient.SetKeys(approxColors.ToArray(), approxAlpha.ToArray());

            int iters = 8;

            while (iters-- > 0)
            {
                float maxColorDistance = 0f, maxAlphaDistance = 0f;
                int   maxColorDistanceIndex = -1, maxAlphaDistanceIndex = -1;
                for (int i = 0; i < colors.Length; i++)
                {
                    var gradientColor = gradient.Evaluate(i * invLength);
                    var alphaDistance = Mathf.Abs(colors[i].a - gradientColor.a);
                    var colorDistance = ColorRGBSqrDistance(colors[i], gradientColor);
                    if (alphaDistance > maxAlphaDistance && alphaDistance > 1e-3f)
                    {
                        maxAlphaDistance      = alphaDistance;
                        maxAlphaDistanceIndex = i;
                    }
                    if (colorDistance > maxColorDistance && colorDistance > 1e-3f)
                    {
                        maxColorDistance      = colorDistance;
                        maxColorDistanceIndex = i;
                    }
                }
                // Break if no deviations found
                if (maxColorDistanceIndex == -1 && maxAlphaDistanceIndex == -1)
                {
                    break;
                }
                // Insert new keys
                if (maxAlphaDistanceIndex != -1)
                {
                    var newKeyLocation = maxAlphaDistanceIndex * invLength;
                    var newAlpha       = colors[maxAlphaDistanceIndex].a;
                    for (int i = 0; i < approxAlpha.Count; i++)
                    {
                        if (newKeyLocation > approxAlpha[i].time)
                        {
                            approxAlpha.Insert(i + 1, new GradientAlphaKey(newAlpha, newKeyLocation));
                            break;
                        }
                    }
                }
                if (maxColorDistanceIndex != -1)
                {
                    var newKeyLocation = maxColorDistanceIndex * invLength;
                    var newColor       = colors[maxColorDistanceIndex];
                    for (int i = 0; i < approxColors.Count; i++)
                    {
                        if (newKeyLocation > approxColors[i].time)
                        {
                            approxColors.Insert(i + 1, new GradientColorKey(newColor, newKeyLocation));
                            break;
                        }
                    }
                }
                // Update gradient
                gradient.SetKeys(approxColors.ToArray(), approxAlpha.ToArray());
                // Break if we have used maximum allowed Color and Alpha keys
                if (approxAlpha.Count == 8 || approxColors.Count == 8)
                {
                    break;
                }
            }

            // Calculate error values
            var totalErr = 0f;
            var maxErr   = 0f;

            for (int i = 0; i < colors.Length; i++)
            {
                var approx = gradient.Evaluate(i / (float)(colors.Length - 1));
                var error  = Mathf.Sqrt(ColorRGBASqrDistance(approx, colors[i]));
                totalErr += error;
                maxErr    = Mathf.Max(maxErr, error);
            }
            var avg            = totalErr / colors.Length;
            var totalDeviation = 0f;

            for (int i = 0; i < colors.Length; i++)
            {
                var approx    = gradient.Evaluate(i / (float)(colors.Length - 1));
                var error     = Mathf.Sqrt(ColorRGBASqrDistance(approx, colors[i]));
                var deviation = (error - avg) * (error - avg);
                totalDeviation += deviation;
            }
            var stdDev = Mathf.Sqrt(totalDeviation / colors.Length);

            return(new ErrorData(avg, stdDev, maxErr));
        }
Esempio n. 30
0
 public Color GetColor(float inputValue)
 {
     inputValue = Mathf.Clamp(inputValue, minInputValue, maxInputValue);
     inputValue = (inputValue - minInputValue) / Mathf.Max(maxInputValue - minInputValue, .00001f);
     return(gradient.Evaluate(inputValue));
 }