Inheritance: UnityEngine.UI.BaseMeshEffect
Beispiel #1
0
    // Use this for initialization
    void Start()
    {
        //activated = true;
        //cachedY = timeTransform.position.y;

        minXValue = 0;
        maxXValue = timeTransform.rect.width;

        //currentTime = maxTime;
        g = new Gradient();

        // Populate the color keys at the relative time 0 and 1 (0 and 100%)
        gck = new GradientColorKey[3];
        gck[0].color = new Color32(9,183,62,1);
        gck[0].time = 0.0f;
        gck[1].color = new Color32(255,228,0,1);
        gck[1].time = 0.5f;
        gck[2].color = new Color32(219,101,63,1);
        gck[2].time = 1.0f;

        // Populate the alpha  keys at relative time 0 and 1  (0 and 100%)
        gak = new GradientAlphaKey[2];
        gak[0].alpha = 1.0f;
        gak[0].time = 0.0f;
        gak[1].alpha = 1.0f;
        gak[1].time = 1.0f;
        g.SetKeys(gck, gak);

        CurrentTime = maxTime;
    }
	// Update is called once per frame
	void Update () {
    if (timer == 0) {
      LastColor = SoupMaterial.color;
    }

    if (!NextColor.Equals(SoupMaterial.color)) {
      timer += Time.deltaTime;
      Color c = Color.Lerp(LastColor, NextColor, timer / duration);
      SoupMaterial.color = c;
      SoupLight.color = c;
      SoupLight.intensity = Mathf.Max(1.5f * (duration - timer), 1);

      var col = Smoke.colorOverLifetime;
      col.enabled = true;

      Gradient grad = new Gradient();
      grad.SetKeys( new GradientColorKey[] { new GradientColorKey(c, 0.0f), new GradientColorKey(Color.gray, 1.0f) }, new GradientAlphaKey[] { new GradientAlphaKey(1.0f, 0.0f), new GradientAlphaKey(0.0f, 1.0f) } );

      col.color = new ParticleSystem.MinMaxGradient(grad);

      if (timer >= duration) {
        SoupMaterial.color = NextColor;
        SoupLight.intensity = 1;
        timer = 0;
      }
    }
	}
        private void LoadData(object sender, EventArgs e)
        {
            Gradient gradient = new Gradient(9, 0.01, 2.0, 10, 1.5);

            chart1.Series["Series1"].ChartType = SeriesChartType.Spline;

            gradient.SetStartPoint();

            double length = 0.0;
            int i = 0;
            do 
            {
                length = gradient.GetNext();
                chart1.Series["Series1"].Points.AddXY(i, length);
                i++;
            } while (length > epsilon && i < maxIteration);

            Console.WriteLine("\nIteration = " + (i - 1));
            Console.WriteLine("Distance between atoms = " + gradient.GetPoint() + "\n");

            chart1.ChartAreas[0].AxisX.Minimum = 0;
            chart1.ChartAreas[0].AxisY.Minimum = 0;

            chart1.Update();
        }
        /// <summary>
        /// Initializes a new instance of Gradient.
        /// </summary>
        static GradientPresets()
        {
            // Grayscale gradient color keys
            var grayscaleColorKeys = new List<GradientColorKey>
            {
                new GradientColorKey(Color.black, 0),
                new GradientColorKey(Color.white, 1)
            };

            // RGB gradient color keys
            var rgbColorKeys = new List<GradientColorKey>
            {
                new GradientColorKey(Color.red, 0),
                new GradientColorKey(Color.green, 0.5f),
                new GradientColorKey(Color.blue, 1)
            };

            // RGBA gradient color keys
            var rgbaColorKeys = new List<GradientColorKey>
            {
                new GradientColorKey(Color.red, 0),
                new GradientColorKey(Color.green, 1 / 3f),
                new GradientColorKey(Color.blue, 2 / 3f),
                new GradientColorKey(Color.black, 1)
            };

            // RGBA gradient alpha keys
            var rgbaAlphaKeys = new List<GradientAlphaKey> {new GradientAlphaKey(0, 2 / 3f), new GradientAlphaKey(1, 1)};

            // Terrain gradient color keys
            var terrainColorKeys = new List<GradientColorKey>
            {
                new GradientColorKey(new Color(0, 0, 0.5f), 0),
                new GradientColorKey(new Color(0.125f, 0.25f, 0.5f), 0.4f),
                new GradientColorKey(new Color(0.25f, 0.375f, 0.75f), 0.48f),
                new GradientColorKey(new Color(0, 0.75f, 0), 0.5f),
                new GradientColorKey(new Color(0.75f, 0.75f, 0), 0.625f),
                new GradientColorKey(new Color(0.625f, 0.375f, 0.25f), 0.75f),
                new GradientColorKey(new Color(0.5f, 1, 1), 0.875f),
                new GradientColorKey(Color.white, 1)
            };

            // Generic gradient alpha keys
            var alphaKeys = new List<GradientAlphaKey> {new GradientAlphaKey(1, 0), new GradientAlphaKey(1, 1)};

            _empty = new Gradient();

            _rgb = new Gradient();
            _rgb.SetKeys(rgbColorKeys.ToArray(), alphaKeys.ToArray());

            _rgba = new Gradient();
            _rgba.SetKeys(rgbaColorKeys.ToArray(), rgbaAlphaKeys.ToArray());

            _grayscale = new Gradient();
            _grayscale.SetKeys(grayscaleColorKeys.ToArray(), alphaKeys.ToArray());

            _terrain = new Gradient();
            _terrain.SetKeys(terrainColorKeys.ToArray(), alphaKeys.ToArray());
        }
        /// <summary>
        /// Creates a 1 pixel wide vertical gradient texture using the provided <see cref="GradientStop"/> array.
        /// </summary>
        /// <param name="device"><see cref="Microsoft.Xna.Framework.Graphics.GraphicsDevice"/> instance to use.</param>
        /// <param name="gradientStops">Array of <see cref="GradientStop"/> instances to use when generating the gradient.</param>
        /// <param name="height">Height of the generated texture in pixels.</param>
        /// <returns>A texture 1 pixel wide and the height specified.</returns>
        public static Texture2D CreateVerticalGradient(GraphicsDevice device, Gradient gradient, int height)
        {
            Texture2D texture = new Texture2D(device, 1, height, false, SurfaceFormat.Color);
            Color[] colors = gradient.GetColors(height);
            texture.SetData<Color>(colors);

            return texture;
        }
        /// <summary>
        /// Creates a 1 pixel high horizontal gradient texture using the provided <see cref="GradientStop"/> array.
        /// </summary>
        /// <param name="device"><see cref="Microsoft.Xna.Framework.Graphics.GraphicsDevice"/> instance to use.</param>
        /// <param name="gradientStops">Array of <see cref="GradientStop"/> instances to use when generating the gradient.</param>
        /// <param name="width">Width of the generated texture in pixels.</param>
        /// <returns>A texture with the width specified and 1 pixel high.</returns>
        public static Texture2D CreateHorizontalGradient(GraphicsDevice device, Gradient gradient, int width)
        {
            Texture2D texture = new Texture2D(device, width, 1, false, SurfaceFormat.Color);
            Color[] colors = gradient.GetColors(width);
            texture.SetData<Color>(colors);

            return texture;
        }
        public SceneFilter(float angle, Gradient gradient)
        {
            gradientFx = new GradientFilter();
            gradientFx.Gradientf = gradient;
            gradientFx.OriginAngleDegree = angle;

            saturationFx = new SaturationModifyFilter();
            saturationFx.SaturationFactor = -0.6f;
        }
	void SaveGraient(Gradient gradient)
	{
		var path = EditorUtility.SaveFilePanel("Save gradient.", "Assets/", "", "asset");
		if (!string.IsNullOrEmpty(path))
		{
			GradientObject obj = GradientObject.CreateInstance<GradientObject>();
			obj.data = gradient;
			AssetDatabase.CreateAsset(obj, LocalPath(path));
		}
	}
 private void AddGradient_Click(object sender, EventArgs e)
 {
     Gradient newGradient = new Gradient();
       newGradient.Name = CreateUniqueGradientName(Strings.NewGradient);
       gradients.Add(newGradient);
       gradientList.DataSource = null;
       gradientList.DataSource = gradients;
       gradientList.SelectedIndex = gradients.Count - 1;
       deleteGradient.Enabled = (gradients.Count > 0);
       gradientNameTextbox.Focus();
 }
        // This constructor takes a Gradient value from the
        // design-time environment, which will be used to display
        // the initial state.
        public GradientViewer(Gradient gradient, IWindowsFormsEditorService editorService)
        {
            // This call is required by the designer.
              InitializeComponent();

              // Cache the light shape value provided by the
              // design-time environment.
              this.gradient = gradient;

              // Cache the reference to the editor service.
              this.editorService = editorService;
        }
Beispiel #11
0
    public ExtendedTerrainArea(float averageHeight, float flatness, float roughness, 
	                                  Gradient coloring00, Gradient coloring10, Gradient coloring01, Gradient coloring11,
	                                  float deltaX, float deltaY)
        : base(averageHeight, flatness, roughness, null)
    {
        this.coloring00 = coloring00;
        this.coloring10 = coloring10;
        this.coloring01 = coloring01;
        this.coloring11 = coloring11;
        this.deltaX = deltaX;
        this.deltaY = deltaY;
    }
Beispiel #12
0
	private void InitImpulseGradient ()
	{
		impulseGradient = new Gradient ();
		GradientColorKey[] gck = new GradientColorKey[impulseGradientColors.Length];
		GradientAlphaKey[] gak = new GradientAlphaKey[impulseGradientColors.Length];
		for (int i = 0; i < impulseGradientColors.Length; i++) {
			gck [i].color = impulseGradientColors [i];
			gak [i].alpha = 1.0f;
			gck [i].time = gak [i].time = impulseGradientTimes [i];
		}
		impulseGradient.SetKeys (gck, gak);
	}
	private int id; // just for debugging / can be deleted after

	#endregion

	public WindParticle(int _id, Vector3 _position, int _maxDistance, Quaternion _direction, float _speed, int _maxMountainHeight, float _temperature, float _saturation, Gradient _colorArea) {
		id = _id;
		position = _position;
		source = _position;
		maxDistance = _maxDistance;
		direction = _direction;
		speed = _speed;
		maxMountainHeight = _maxMountainHeight;
		temperature = _temperature;
		saturation = getSFromFRel(_saturation,getPFromHeight((position.y-groundHeight)/scale),temperature); // saturation kommt als relative Luftfeuchte, daher die Umrechnung
		colorArea = _colorArea;
		visible = true;
	}
		// Use this for initialization
		void Awake () 
		{
		
			//set RectTransform parameters
			RectTransform rectTransform = this.GetComponent<RectTransform> ();
			rectTransform.anchorMin = new Vector2(0,0);
			rectTransform.anchorMax = new Vector2(1,1);
			rectTransform.anchoredPosition = new Vector2(1,1);

			colorGradient = GetColorGradient (bottomColor, topColor); // create the color gradient

	
		}
Beispiel #15
0
    public Gradient BlendGradient(Gradient terrain_gradient, Gradient object_gradient)
    {
        List<ColorHSV> targetPalette = new List<ColorHSV>();
        List<ColorHSV> currentPalette = new List<ColorHSV>();
        targetPalette = RandomE.TetradicPalette(0.25f, 0.75f);
        Debug.Log(targetPalette.Count);
        ColorHSV groundColor = new ColorHSV(terrain_gradient.Evaluate(0));
        ColorHSV newColor = new ColorHSV(object_gradient.Evaluate(1));
        targetPalette.Add(ColorHSV.Lerp(groundColor, newColor, 0.5f));
        var gradient = ColorE.Gradient(from: targetPalette[2].WithSV(0.8f, 0.8f),
            to: targetPalette[3].WithSV(0.8f, 0.8f));

        return object_gradient;
    }
Beispiel #16
0
	public void CreateGradTexture(){
		// Create gradient object and assign generic starting colours
		Grad = new Gradient();
		LastGrad = new Gradient();
		GradientColorKey[] gck = new GradientColorKey[2];
		gck[0] = new GradientColorKey(Color.black, 0f);
		gck[1] = new GradientColorKey(Color.white, 1f);
		GradientAlphaKey[] gak = new GradientAlphaKey[2];
		gak[0] = new GradientAlphaKey(1f, 0f);
		gak[1] = new GradientAlphaKey(1f, 1f);
		Grad.SetKeys(gck, gak);
		LastGrad.SetKeys(gck, gak);
		
		outTexture = new Texture2D(_gradientSizeX,_gradientSizeY);
		outTexture.hideFlags = HideFlags.HideAndDontSave;
//		Debug.Log (outTexture);
	}
Beispiel #17
0
    public static Color Grad(float x)
    {
        /*
        // Terrain gradient color keys
        List<GradientColorKey> terrainColorKeys = new List<GradientColorKey>
        {
            new GradientColorKey(new Color(0, 0, 0.5f), 0),
            new GradientColorKey(new Color(0.125f, 0.25f, 0.5f), 0.4f),
            new GradientColorKey(new Color(0.25f, 0.375f, 0.75f), 0.48f),
            new GradientColorKey(new Color(0, 0.75f, 0), 0.5f),
            new GradientColorKey(new Color(0.75f, 0.75f, 0), 0.625f),
            new GradientColorKey(new Color(0.625f, 0.375f, 0.25f), 0.75f),
            new GradientColorKey(new Color(0.5f, 1, 1), 0.875f),
            new GradientColorKey(Color.white, 1)
        };

        // Generic gradient alpha keys
        var alphaKeys = new List<GradientAlphaKey> {new GradientAlphaKey(1, 0), new GradientAlphaKey(1, 1)};
        */

        Gradient g = new Gradient();
        GradientColorKey[] gck;
        GradientAlphaKey[] gak;

        // Populate the color keys at the relative time 0 and 1 (0 and 100%)
        gck = new GradientColorKey[2];
        gck[0].color = Color.red;
        gck[0].time = 0.0f;
        gck[1].color = Color.blue;
        gck[1].time = 1.0f;

        // Populate the alpha  keys at relative time 0 and 1  (0 and 100%)
        gak = new GradientAlphaKey[2];
        gak[0].alpha = 1.0f;
        gak[0].time = 0.0f;
        gak[1].alpha = 0.0f;
        gak[1].time = 1.0f;

        //g.SetKeys(terrainColorKeys.ToArray(), alphaKeys.ToArray());
        g.SetKeys(gck,gak);

        return g.Evaluate(x);;
    }
	public void investigateMap() { // Werte für aktuelle Landschaft in abhängigkeit zu Werten ermitteln und speichern
		Gradient colorArea = new Gradient ();
		particle = new WindParticle(0, position, 99999, direction, 0.1f, 999, startTemperature, startSaturation, colorArea); // create WindParticle
		
		temperatures[0] = startTemperature;
		saturations[0] = startSaturation;
		heights[0] = (position.y-particle.groundHeight)/particle.scale;
		
		int n = 0;
		while (n+1 < steps) {
			particle.move();
			if(Vector3.Distance(new Vector3(particle.position.x,0,particle.position.z),new Vector3(position.x,0,position.z)) >= stepMap[n]) { // if actual position is nearest to calculated distance for actual step...
				temperatures[n+1] = particle.temperature;
				saturations[n+1] = particle.getFRel();
				heights[n+1] = (particle.position.y-particle.groundHeight)/particle.scale;
				n++;
			}
		}
	}
Beispiel #19
0
    void Start () {
        GradientColorKey[] gradColorKey;
        GradientAlphaKey[] gradAlphaKey;

        grad = new Gradient();
        gradColorKey = new GradientColorKey[3];
        gradAlphaKey = new GradientAlphaKey[1];

        gradColorKey[0].color = Color.magenta;
        gradColorKey[0].time = 0.0f;
        gradColorKey[1].color = Color.green;
        gradColorKey[1].time = 0.5f;
        gradColorKey[2].color = Color.magenta;
        gradColorKey[2].time = 1.0f;

        gradAlphaKey[0].alpha = 1.0f;

        grad.SetKeys(gradColorKey,gradAlphaKey);
    }
        /// <summary>
        /// Returns a gradient filled into a shape.
        /// </summary>
        public static Texture2D GetTexture(GraphicsDevice device, Gradient gradient, IShape shape)
        {
            string comparer = string.Concat(new string[] { shape.GetType().Name, shape.ToString(), gradient.ToString() });

            Texture2D texture;

            //Search for the texture in the dictionary, so it doesn't have to be created twice.
            if (_tempTextures.Keys.Contains(comparer))
            {
                texture = _tempTextures[comparer];
            }
            else
            {
                texture = createTexture(device, gradient, shape);
                _tempTextures.Add(comparer, texture);
            }

            return texture;
        }
        /*
        protected override IEnumerable ListParameters()
        {
          yield return "Type: " + Abbreviations.Get(_type.Value);
          yield return ((_dither) ? "With" : "Without") + " Dither";
          yield return ((_useMask) ? "With" : "Without") + " Use Mask";
        }
        */
        public static Gradient CreateGradient(string name, ListParameter colors)
        {
            Gradient gradient = new Gradient("Photoshop." + name);
              gradient.SegmentRangeSplitUniform(0, -1, colors.Count);

              int segment = 0;

              foreach (ObjcParameter parameter in colors)
            {
              RGB color;

              string type = parameter.GetValueAsString("Type");
              switch (type)
            {
            case "BckC":
              color = Context.Background;
              break;
            case "FrgC":
              color = Context.Foreground;
              break;
            case "UsrS":
              color = parameter.GetValueAsColor("Clr");
              break;
            default:
              Console.WriteLine("Gradient-1: " + type);
              color = new RGB(0, 0, 0);
              break;
            }

              long location = parameter.GetValueAsLong("Lctn");
              long midpoint = parameter.GetValueAsLong("Mdpn");
              Console.WriteLine("type: {0}, location: {1}, midpoint: {2}",
                type, location, midpoint);
              gradient.SegmentSetLeftPosition(segment, location / 4096.0);
              gradient.SegmentSetLeftColor(segment, color, 100);
              if (segment > 0)
            {
              gradient.SegmentSetRightColor(segment - 1, color, 100);
            }
              segment++;
            }
              return gradient;
        }
    public PlanetParameters(PlanetSeed planetSeed)
    {
        this.planetSeed = planetSeed;
        Random.seed = planetSeed.seed;
        gradientMultiplier = Random.Range (1.3f, 2.3f);

        seaLevel = Random.Range (0.25f, 0.8f);
        terrainHeight = Random.Range (0.04f, 0.08f);

        perlinSpaceSeed = new Vector3(Random.Range(1f, 10f), Random.Range(1f, 10f), Random.Range(1f, 10f));

        icyness = Mathf.Sqrt(Random.Range (0.01f, 15.0f))-2f;

        Color32 shore =     color(Random.Range(60, 120),  Random.Range(120, 180), Random.Range(70, 110));
        Color32 hills =     color(Random.Range(80, 140),  Random.Range(100, 160), Random.Range(60, 100));
        Color32 highHills = color(Random.Range(80, 140),  Random.Range(100, 160), Random.Range(60, 100));
        Color32 mountains = color(Random.Range(210, 250), Random.Range(210, 250), Random.Range(230, 250));

        gradient = new Gradient();
        Gradient.GradientPoint p1 = new Gradient.GradientPoint(shore,     0.0f);
        Gradient.GradientPoint p2 = new Gradient.GradientPoint(hills,     0.5f);
        Gradient.GradientPoint p3 = new Gradient.GradientPoint(highHills, 0.8f);
        Gradient.GradientPoint p4 = new Gradient.GradientPoint(mountains, 1.0f);

        gradient.gradientPoints = new Gradient.GradientPoint[] { p1, p2, p3, p4 };

        waterColor    = new Color32((byte)Random.Range(40, 50),    (byte)Random.Range(30, 90),   (byte)Random.Range(90, 150), (byte)80);
        landIceColor  = new Color32((byte)Random.Range(230, 240),  (byte)Random.Range(230, 240), (byte)Random.Range(240, 255), (byte)30);
        waterIceColor = new Color32((byte)Random.Range(230, 245),  (byte)Random.Range(240, 255), (byte)Random.Range(230, 245), (byte)240);

        starLight = new Color32(
                    (byte)(Random.Range(135, 195) - 50*icyness),
                    (byte)(Random.Range(164, 124) - 40*icyness),
                    (byte)(Random.Range(200, 255) - 2*icyness),
                    (byte)255);

        starIntensity = Random.Range (1.5f, 2.0f);

        planetSize = Random.Range (0.75f, 1.25f);

        name = PlanetNameGenerator.GenerateName();
    }
    public override void Init()
    {
        base.Init ();

        var color1 = new Color(255f / 255f, 255f / 255f, 234f / 255f, 255f / 255f);
        var color2 = new Color(189f / 255f, 223f / 255f, 255f / 255f, 255f / 255f);
        m_SunColorGradient = new Gradient();
        m_SunColorGradient.colorKeys = new GradientColorKey[] { new GradientColorKey (color2, 0f), new GradientColorKey (color1, 1f) };

        m_SunLight = this.GetComponent<Light>();
        m_SunLightIntensity = m_SunLight != null ? m_SunLight.intensity : 0f;

        var sunIdleState = new FSMSunIdleState(this);
        var sunUpdateState = new FSMSunUpdateState(this);

        m_FSMManager.RegisterState ("SunIdleState", sunIdleState);
        m_FSMManager.RegisterState ("SunUpdateState", sunUpdateState);

        m_FSMManager.LoadFSM (m_Entity.GetFSMPath());
    }
Beispiel #24
0
    // Use this for initialization
    void Start()
    {
        ren = GetComponent<MeshRenderer>();
        mat = ren.material;
        initialPos = transform.position;

        pillarGradient = new Gradient();

        gck = pillarGradient.colorKeys;
        gck[0].color = mat.color;
        gck[0].time = 0.0f;
        gck[1].color = hotColor;
        gck[1].time = 1.0f;

        gak = pillarGradient.alphaKeys;
        gak[0].alpha = 1.0f;
        gak[0].time = 0.0f;
        gak[1].alpha = 1.0f;
        gak[1].time = 1.0f;

        pillarGradient.SetKeys(gck, gak);
    }
Beispiel #25
0
	// Use this for initialization
	public WeatherProfile( string name_, Texture top_, Texture front_, Texture bottom_, Texture left_, Texture right_, Texture back_ ,
		                   Gradient dayNightColor_, float maxIntensity_, float minIntensity_, float maxAmbient_, float minAmbient_,
		                   Gradient nightDayFogColor_, AnimationCurve fogDensityCurve_, float fogScale_, float dayAtmosphereThickness_,
		                   float nightAtmosphereThickness_ ){
		top = top_;
		front = front_;
		bottom = bottom_;
		left = left_;
		right = right_;
		back = back_;
		//  New variables
		dayNightColor = dayNightColor_;
		maxIntensity = maxIntensity_;
		minIntensity = minIntensity_ ;
		maxAmbient = maxAmbient_;
		minAmbient = minAmbient_;
		nightDayFogColor = nightDayFogColor_;
		fogDensityCurve = fogDensityCurve_;
		fogScale=fogScale_;
		dayAtmosphereThickness = dayAtmosphereThickness_;
		nightAtmosphereThickness = nightAtmosphereThickness_;
		name = name_;
	}
Beispiel #26
0
    private GameObject CreateShape(GameObject shape, uint index)
    {
        GameObject newShape =(GameObject)Instantiate (shape, new Vector3 (0, 0, 0), Quaternion.identity);
        newShape.transform.parent = transform;
        newShape.transform.localPosition = Vector3.zero;
        newShape.transform.localRotation = Quaternion.identity;
        newShape.GetComponent<ShapeProperties> ().index = index;

        ColorChanger colorChanger = newShape.AddComponent<ColorChanger> ();
        Gradient gradient = new Gradient ();
        GradientColorKey[] colorKeys = new GradientColorKey[3];
        colorKeys[0].color = Color.red;
        colorKeys[0].time = 0.0f;
        colorKeys[1].color = Color.green;
        colorKeys[1].time = 0.5f;
        colorKeys[2].color = Color.red;
        colorKeys[2].time = 1.0f;
        gradient.colorKeys = colorKeys;
        colorChanger.colors = gradient;

        newShape.AddComponent<ToRandomLocation> ();

        return newShape;
    }
Beispiel #27
0
        public static IFillStyle ParseFillStyle2(SwfReader r, ShapeType shapeType)
        {
            IFillStyle result = null;

            FillType fsType = (FillType)r.GetByte();
            bool useAlpha = shapeType > ShapeType.DefineShape2;
            switch (fsType)
            {
                case FillType.Solid:
                    result = new SolidFill(r, useAlpha);
                    break;

                case FillType.Linear:
                    result = new Gradient(r, fsType, useAlpha);
                    break;

                case FillType.Radial:
                    result = new Gradient(r, fsType, useAlpha);
                    break;

                case FillType.Focal:
                    result = null;
                    //throw new NotSupportedException("Currently FillType.Focal is not supported");
                    break;

                case FillType.RepeatingBitmap:
                case FillType.ClippedBitmap:
                case FillType.NSRepeatingBitmap:
                case FillType.NSClippedBitmap:
                    uint charId = r.GetUI16();
                    Matrix bmpMatrix = new Matrix(r);
                    result = new BitmapFill(charId, bmpMatrix, fsType);
                    break;
            }
            return result;
        }
Beispiel #28
0
        private void GenerateWindEffect(MapTile tile)
        {
            GameObject air = new GameObject();

            air.transform.SetParent(tile.Structure.GameObject.transform);
            air.transform.localPosition = new Vector3(1f, -0.5f, -4.5f);
            air.transform.localScale    = new Vector3(0.5f, 0.5f, 1);

            ParticleSystem particles = air.AddComponent <ParticleSystem>();

            Particles.InitParticleSystem(particles);

            ParticleSystem.MainModule mainParticle = particles.main;
            mainParticle.startLifetime = 1.5f;
            mainParticle.startSpeed    = 0;
            mainParticle.startSize     = 0.1f;
            mainParticle.maxParticles  = 5;


            ParticleSystem.TrailModule trailMode = particles.trails;
            trailMode.enabled          = true;
            trailMode.lifetime         = new ParticleSystem.MinMaxCurve(0.8f);
            trailMode.dieWithParticles = false;
            AnimationCurve trailCurve = new AnimationCurve();

            trailCurve.AddKey(0, 0);
            trailCurve.AddKey(0.5f, 1);
            trailCurve.AddKey(1, 0);
            trailMode.widthOverTrail = new ParticleSystem.MinMaxCurve(1, trailCurve);


            ParticleSystem.EmissionModule emissionModule = particles.emission;
            emissionModule.rateOverTime = 3;
            ParticleSystemRenderer particleRenderer = particles.GetComponent <ParticleSystemRenderer>();

            particleRenderer.trailMaterial = Resources.Load <Material>("Wind");


            ParticleSystem.ShapeModule shapeModule = particles.shape;
            shapeModule.shapeType = ParticleSystemShapeType.Box;
            shapeModule.rotation  = new Vector3(0, 0, 180);
            shapeModule.scale     = new Vector3(0.1f, 1, 1);

            ParticleSystem.VelocityOverLifetimeModule velocityOverLifetimeModule = particles.velocityOverLifetime;
            velocityOverLifetimeModule.enabled = true;

            AnimationCurve curveX = new AnimationCurve();

            curveX.AddKey(0, 1);
            curveX.AddKey(1, 1);

            AnimationCurve curveY = new AnimationCurve();

            curveY.AddKey(0, 0);
            curveY.AddKey(0.33f, 1);
            curveY.AddKey(0.66f, -1);
            curveY.AddKey(1, 0);

            AnimationCurve curveZ = new AnimationCurve();

            curveZ.AddKey(0, 0);
            curveZ.AddKey(1.0f, 0);

            //velocityOverLifetimeModule.space = ParticleSystemSimulationSpace.Local;
            velocityOverLifetimeModule.x = new ParticleSystem.MinMaxCurve(1, curveX);
            velocityOverLifetimeModule.y = new ParticleSystem.MinMaxCurve(1, curveY);
            velocityOverLifetimeModule.z = new ParticleSystem.MinMaxCurve(0, curveZ);

            ParticleSystem.ColorOverLifetimeModule colorOverLifetimeModule = particles.colorOverLifetime;
            colorOverLifetimeModule.enabled = true;
            Gradient gradient = new Gradient();

            gradient.SetKeys(new [] { new GradientColorKey(new Color32(167, 232, 242, 255), 0.0f),
                                      new GradientColorKey(Color.white, 1.0f) },
                             new [] { new GradientAlphaKey(1.0f, 0.0f),
                                      new GradientAlphaKey(0.0f, 1.0f) });
            colorOverLifetimeModule.color = gradient;
        }
Beispiel #29
0
    public void AdjustTint(Color color)
    {
        if (BeamLight == null || ExplosionTrail == null)
        {
            throw new System.NullReferenceException("There are null particles.");
        }


        // BeamLight:
        var beamLightColors = new Gradient();

        beamLightColors.SetKeys(new GradientColorKey[]
        {
            new GradientColorKey(Color.white, 0.0f),
            new GradientColorKey(color, 1.0f)
        },
                                new GradientAlphaKey[]
        {
            new GradientAlphaKey(30, 0.0f),
            new GradientAlphaKey(10, 1.0f)
        });

        var beamLightColorsOverLifeTime = new Gradient();

        beamLightColorsOverLifeTime.SetKeys(new GradientColorKey[]
        {
            new GradientColorKey(color, 0.0f),
            new GradientColorKey(color, 1.0f),
        },
                                            new GradientAlphaKey[]
        {
            new GradientAlphaKey(0, 0.0f),
            new GradientAlphaKey(0.5f, 0.082f),
            new GradientAlphaKey(0.5f, 0.532f),
            new GradientAlphaKey(0, 1.0f),
        });

        var beamLightMain = BeamLight.main;
        var beamColors    = new ParticleSystem.MinMaxGradient(beamLightColors);

        beamColors.mode          = ParticleSystemGradientMode.RandomColor;
        beamLightMain.startColor = beamColors;

        var beamLightColorOverLifeTime = BeamLight.colorOverLifetime;

        beamLightColorOverLifeTime.color = beamLightColorsOverLifeTime;

        // Explosion Trail:

        var explosionTrailGradient = new Gradient();

        explosionTrailGradient.SetKeys(new GradientColorKey[]
        {
            new GradientColorKey(color, 0.0f),
            new GradientColorKey(color, 1.0f),
        },
                                       new GradientAlphaKey[]
        {
            new GradientAlphaKey(0, 0.0f),
            new GradientAlphaKey(0.5f, 0.035f),
            new GradientAlphaKey(0.5f, 0.612f),
            new GradientAlphaKey(0, 1.0f),
        });

        var explosionColors = new ParticleSystem.MinMaxGradient(explosionTrailGradient);

        explosionColors.mode = ParticleSystemGradientMode.Gradient;
        var explosionTrail = ExplosionTrail.trails;

        explosionTrail.colorOverLifetime = explosionColors;
    }
Beispiel #30
0
 public void SetGradientColor(Gradient gradientColor) => line.colorGradient = gradientColor;
 /// <summary>
 /// Applies a gradient of colors to the Graphic over time.
 /// </summary>
 static public Tween Gradient(this Graphic inRenderer, Gradient inGradient, float inTime, ColorUpdate inUpdate = ColorUpdate.PreserveAlpha)
 {
     return(Tween.Create(new TweenData_Graphic_Gradient(inRenderer, inGradient, inUpdate), inTime));
 }
 /// <summary>
 /// Applies a gradient of colors to the Graphic over time.
 /// </summary>
 static public Tween Gradient(this CanvasRenderer inRenderer, Gradient inGradient, TweenSettings inSettings, ColorUpdate inUpdate = ColorUpdate.PreserveAlpha)
 {
     return(Tween.Create(new TweenData_CanvasRenderer_Gradient(inRenderer, inGradient, inUpdate), inSettings));
 }
        TextCell[] CreateBackgroundGradientCells()
        {
            List <TextCell> result = new List <TextCell>();

            Dictionary <string, Tuple <int, Color, Color> > Colors = new Dictionary <string, Tuple <int, Color, Color> >()
            {
                { "Red", new Tuple <int, Color, Color>(Gradient.RotationTopToBottom, Color.Red, Color.Maroon) },
                { "Green", new Tuple <int, Color, Color>(Gradient.RotationLeftToRight, Color.Lime, Color.Green) },
                { "Blue", new Tuple <int, Color, Color>(Gradient.RotationBottomToTop, Color.Blue, Color.Navy) }
            };

            // Iterate through the color values, creating a new text cell for each entity
            var colorNames = Colors.Keys;

            foreach (string colorName in colorNames)
            {
                var cell = new TextCell();
                cell.Text      = colorName;
                cell.TextColor = Color.White;

                // Assign our gloss properties - You can use the standard static setter...
                var cellInfo = Colors[colorName];
                CellGloss.SetBackgroundGradient(cell, new Gradient(cellInfo.Item1, cellInfo.Item2, cellInfo.Item3));

                // ...or instantiate an instance of the Gloss properties you want to assign values to
                //	var gloss = new XFGloss.Views.Cell(cell);
                //	gloss.AccessoryType = accType;
                //	gloss.BackgroundColor = Color.Blue;
                //	gloss.TintColor = Color.Red;
                //	...

                result.Add(cell);
            }

            // Add a multi-color gradient
            rotatingCell           = new TextCell();
            rotatingCell.Text      = "All Three";
            rotatingCell.TextColor = Color.White;

            // Manually construct a multi-color gradient at an angle of our choosing
            rotatingGradient = new Gradient()
            {
                Rotation = 135,
                Steps    = new GradientStepCollection()
                {
                    new GradientStep(Colors["Red"].Item2, 0),
                    new GradientStep(Colors["Red"].Item3, .25),
                    new GradientStep(Colors["Green"].Item2, .4),
                    new GradientStep(Colors["Green"].Item3, .6),
                    new GradientStep(Colors["Blue"].Item2, .75),
                    new GradientStep(Colors["Blue"].Item3, 1),
                }
            };

            // You can also initialize a multi-color gradient in code like this:
            //rotatingGradient = new Gradient(135); // 135 degree angle
            //rotatingGradient.AddStep(Colors["Red"].Item2, 0);
            //rotatingGradient.AddStep(Colors["Red"].Item3, .25);
            //rotatingGradient.AddStep(Colors["Green"].Item2, .4);
            //rotatingGradient.AddStep(Colors["Green"].Item3, .6);
            //rotatingGradient.AddStep(Colors["Blue"].Item2, .75);
            //rotatingGradient.AddStep(Colors["Blue"].Item3, 1);

            CellGloss.SetBackgroundGradient(rotatingCell, rotatingGradient);

            result.Add(rotatingCell);

            return(result.ToArray());
        }
Beispiel #34
0
        //send a wave through the pad

        /*
         * The basic algorithm for this is as follows:
         * while(timer < propegationTime)
         * {
         *      index through the rings. index = (timer/propegationTime)*(numRings)
         *      for( each ring)
         *      {
         *          -get the distance to the index
         *          -if we're "rippleLines" or less away from the index, we're a part of the ripple
         *          -if we're part of the ripple, draw the rippleSamples on this ring, damped by distance from the center.
         *      }
         * }
         * */
        IEnumerator RipIt(float propegationTime, float[] rippleSamples)
        {
            //Vector3 firstPos = Vector3.zero; // the first position we use
            float timer      = 0;
            float radiusStep = radius / (numLines - 1);            // distance between each ring. i.e. ring0 has radius 0*radiusStep, ring10 had radius 10*radiusStep, etc.
            float angle      = 0;
            float angleStep  = 360f / lineAttributes.lineSegments; //increase the angle by this much, for every point on every line, to draw each circle.
            float percent    = 0;
            int   maxIndex   = numLines - 1;
            int   halfWidth  = rippleWidth / 2;        // (int) on purpose
            float heightStep = (1f / (halfWidth + 1)); //ripple height step size

            // another gradient, between start color and rippleColor
            Gradient lineGradient = PanelWaveform.GetColorGradient(lineAttributes.startColor, rippleColor);

            Color[] rippleColors = new Color[maxIndex];
            float   step         = 1f / (rippleWidth - 1);

            for (int i = 0; i < rippleWidth; i++)
            {
                percent         = i * step;
                rippleColors[i] = lineGradient.Evaluate(percent);
            }

            Color[] lineColors   = new Color[numLines]; //color of each line using the gradient
            float[] heightDamp   = new float[numLines]; //height damp array, how much we'll damp the ripple as it travels across the pad.
            float   scaledHeight = maxHeight * AudioSampler.instance.globalSensitivity;
            float   dampStep     = scaledHeight / (numLines - 1);

            step = 1f / (numLines - 1);
            for (int i = 0; i < numLines; i++)
            {
                percent       = i * step;
                lineColors[i] = padGradient.Evaluate(percent);
                heightDamp[i] = scaledHeight - i * dampStep;
            }



            //Debug.Log ("Ripple from " + rippleLines + " to " + numLines);
            while (timer <= propegationTime)
            {
                //what line are we on, in the range rippleLines to numLines, based on the timer
                percent = (timer / propegationTime);
                int lineIndex = (int)(percent * maxIndex);

                //start/end index
                int rippleStart = lineIndex - rippleWidth - 1; // 1 outside the ripple
                rippleStart = Mathf.Max(0, rippleStart);
                int rippleEnd = lineIndex + rippleWidth;
                rippleEnd = Mathf.Min(rippleEnd, numLines);
                Vector3 firstPos = Vector3.zero;

                Vector3 thisPos = this.transform.position;
                Vector3 right   = this.transform.right;
                Vector3 forward = this.transform.forward;
                Vector3 up      = this.transform.up;

                for (int i = rippleStart; i < rippleEnd; i++)          // for each line
                {
                    int   dist             = Mathf.Abs(lineIndex - i); // our distance from the lineIndex
                    int   invDist          = rippleWidth - dist;
                    float heightMultiplier = (dist > halfWidth) ? 0 : (1f - heightStep * dist);
                    float thisRadius       = radiusStep * i; // the radius of this ring
                    //color the ring
                    if (i == (lineIndex - rippleWidth - 1))
                    {
                        lines[i].SetColors(lineColors[lineIndex], lineColors[lineIndex]);
                    }
                    else
                    {
                        lines[i].SetColors(rippleColors[invDist], rippleColors[invDist]);
                    }
                    for (int j = 0; j < lineAttributes.lineSegments - 1; j++) // for each line segment
                    {
                        float rad = Mathf.Deg2Rad * angle;                    // get angle in radians
                        //get x,y,z of this lineSegment using equation for a circle
                        float   x   = Mathf.Cos(rad) * thisRadius;
                        float   y   = rippleSamples[j] * heightDamp[lineIndex] * heightMultiplier; // y value based on audio info (rippleSamples) * heightMultiplier
                        float   z   = Mathf.Sin(rad) * thisRadius;
                        Vector3 pos = thisPos + right * x + up * y + forward * z;
                        lines[i].SetPosition(j, pos);
                        angle += angleStep; // increase angle by angleStep
                        if (j == 0)
                        {
                            firstPos = pos; // track the first lineSegment position
                        }
                    }

                    lines[i].SetPosition(lineAttributes.lineSegments - 1, firstPos);              // set the last pos = to the first pos.
                }

                timer += Time.fixedDeltaTime;

                yield return(null);
            }
        }
 extern internal void Internal_GetGradientFromScript(int nameID, Gradient gradient);
        internal static int PrepareVolumePreview(Material material, Texture texture, Vector3 scale, float opacity,
                                                 FilterMode filterMode, bool colorRamp, Gradient customColorRamp, Camera camera, Matrix4x4 trs, float qualityModifier = 2)
        {
            float   inverseResolution;
            Vector3 inverseScale;

            PrepareGeneralPreview(material, texture, out inverseScale, out inverseResolution, customColorRamp);
            uint colorChannelCount = GraphicsFormatUtility.GetColorComponentCount(texture.graphicsFormat);

            material.SetVector(MaterialProps.globalScale, scale);
            material.SetFloat(MaterialProps.ramp, Convert.ToSingle(colorRamp));
            material.SetFloat(MaterialProps.invResolution, inverseResolution);
            material.SetVector(MaterialProps.invChannels, new Vector3(1.0f / colorChannelCount, 1.0f / colorChannelCount, 1.0f / colorChannelCount));
            material.SetFloat(MaterialProps.alpha, Mathf.Pow(Mathf.Clamp01(opacity), 3));
            material.SetFloat(MaterialProps.filterMode, Convert.ToSingle(filterMode));

            float quality = inverseResolution / qualityModifier / 2;

            material.SetFloat(MaterialProps.quality, quality);

            material.SetMatrix("_CamToW", camera.cameraToWorldMatrix);
            material.SetMatrix("_WToCam", camera.worldToCameraMatrix);
            material.SetMatrix("_ObjToW", trs);
            material.SetMatrix("_WToObj", trs.inverse);

            return(Convert.ToInt32(1 / inverseResolution * qualityModifier * 2));
        }
        internal static void PrepareSlicePreview(Material material, Texture texture, Vector3 slice,
                                                 FilterMode filterMode, bool colorRamp = false, Gradient customColorRamp = null)
        {
            float   inverseResolution;
            Vector3 inverseScale;

            PrepareGeneralPreview(material, texture, out inverseScale, out inverseResolution, customColorRamp);
            uint colorChannelCount = GraphicsFormatUtility.GetColorComponentCount(texture.graphicsFormat);

            Vector3 voxelSize         = material.GetVector("_VoxelSize");
            Vector3 textureResolution = GetTextureResolution(texture);
            Vector3 positions         = new Vector3(slice.x / textureResolution.x, slice.y / textureResolution.y, slice.z / textureResolution.z);

            positions.x = Mathf.Clamp01(positions.x);
            positions.y = Mathf.Clamp01(positions.y);
            positions.z = Mathf.Clamp01(positions.z);
            positions  -= new Vector3(0.5f, 0.5f, 0.5f);
            positions.Scale(voxelSize);
            material.SetVector(MaterialProps.positions, positions);
            material.SetVector(MaterialProps.invChannels, new Vector3(1.0f / colorChannelCount, 1.0f / colorChannelCount, 1.0f / colorChannelCount));
            material.SetFloat(MaterialProps.filterMode, Convert.ToSingle(filterMode));
            material.SetFloat(MaterialProps.ramp, Convert.ToSingle(colorRamp));
        }
    void Update()
    {
        //Debug.Log("up");
        if (GameObject.Find("Starting point(Clone)"))
        {
            Node root = new Node(starting_location, starting_location, -1, inf_radius);
            tRRT.Add(root);
            curr_num_points++;
        }
        if (GameObject.Find("Starting point(Clone)") && GameObject.Find("Final point(Clone)"))
        {
            bool redo = false;
            if (curr_num_points <= max_num_point && go)
            {
                Node    closest_node     = tRRT[0];
                Vector2 rand_loc         = new Vector2(x_max * Random.value, y_max * Random.value);
                Vector2 closest_node_loc = new Vector2(tRRT[0].position[0], tRRT[0].position[2]);
                float   closest_distance = Vector2.Distance(new Vector2(closest_node.position[0], closest_node.position[2]), rand_loc);

                for (int i = 0; i < tRRT.Count; i++)
                {
                    Node    curr_node     = tRRT[i];
                    Vector2 curr_node_loc = new Vector2(curr_node.position[0], curr_node.position[2]);

                    if (Vector2.Distance(curr_node_loc, rand_loc) < closest_distance)
                    {
                        closest_node     = tRRT[i];
                        closest_node_loc = new Vector2(tRRT[i].position[0], tRRT[i].position[2]);
                        closest_distance = Vector2.Distance(closest_node_loc, rand_loc);
                    }
                }
                if (closest_distance <= closest_node.radius)
                {
                    int iterator = 1;

                    Vector2 new_node_loc = closest_node_loc;
                    bool    broken       = false;
                    while (iterator < Vector2.Distance(closest_node_loc, rand_loc) / epsilon)
                    {
                        //Vector2 new_node_loc = Vector2.Lerp(closest_node_loc, closest_node_loc + new Vector2(rand_loc[0] - closest_node_loc[0], rand_loc[2] - closest_node_loc[2]), inter);
                        float inter = epsilon * iterator / Vector2.Distance(closest_node_loc, rand_loc);

                        Vector2 temp_new_node_loc = Vector2.Lerp(closest_node_loc, rand_loc, inter);
                        Vector3 inter_loc         = getPoint(temp_new_node_loc[0] / x_max, temp_new_node_loc[1] / y_max);
                        if (getCost(inter_loc) >= 1 || !TransitionTest(inter_loc, closest_node.position))
                        {
                            broken = true;
                            break;
                        }
                        else
                        {
                            new_node_loc = Vector2.Lerp(closest_node_loc, rand_loc, inter);
                        }
                        iterator++;
                    }
                    if (!broken)
                    {
                        //new_node_loc = getPoint(new_node_loc[0] / x_max, new_node_loc[1] / y_max); //recalculate the the new node height
                        Vector3 new_node_pos = getPoint(new_node_loc[0] / x_max, new_node_loc[1] / y_max);
                        if (TransitionTest(closest_node.position, new_node_pos))
                        //if (true)
                        {
                            int parent_ind = 0;

                            while (tRRT[parent_ind].position != closest_node.position)
                            {
                                parent_ind++;
                            }

                            Node leaf = new Node(new_node_pos, closest_node.position, parent_ind, inf_radius);
                            tRRT.Add(leaf);
                            GameObject p = Instantiate(point, new_node_pos, Quaternion.identity) as GameObject; //spawn new intial point



                            LineRenderer lineRenderer = p.GetComponent <LineRenderer>();

                            lineRenderer.material        = new Material(Shader.Find("Sprites/Default"));
                            lineRenderer.widthMultiplier = node_line_width;
                            lineRenderer.positionCount   = 2;

                            // A simple 2 color gradient with a fixed alpha of 1.0f.
                            float    alpha    = 1.0f;
                            Gradient gradient = new Gradient();
                            gradient.SetKeys(
                                new GradientColorKey[] { new GradientColorKey(Color.black, 0.0f), new GradientColorKey(Color.black, 1.0f) },
                                new GradientAlphaKey[] { new GradientAlphaKey(alpha, 0.0f), new GradientAlphaKey(alpha, 1.0f) }
                                );

                            lineRenderer.colorGradient = gradient;
                            lineRenderer.SetPosition(0, closest_node.position);
                            lineRenderer.SetPosition(1, leaf.position);

                            curr_num_points++;
                            //Debug.Log(Vector3.Distance(goal_location, leaf.position));
                            if (Vector3.Distance(goal_location, leaf.position) <= delta)
                            {
                                Node final_node = leaf;
                                build_path(final_node);
                                go         = false;
                                path_found = true;
                            }
                            redo = true;
                        }
                    }

                    else if (broken)
                    {
                        closest_node.radius = R_multiplier * epsilon;
                    }
                }
                else
                {
                    redo = false;
                }
            }
        }
    }
Beispiel #39
0
        private static Texture2D GenerateGradient(StyleFunctionCall call, Rect rect)
        {
            if (call.args.Count < 2)
            {
                Debug.LogError("Not enough linear gradient arguments.");
                return(null);
            }

            int key = call.blockKey ^ call.valueKey ^ ((int)rect.width * 30 + (int)rect.height * 8);

            if (s_Gradients.ContainsKey(key) && s_Gradients[key] != null)
            {
                return(s_Gradients[key]);
            }

            if (s_Gradients.Count > 300)
            {
                while (s_Gradients.Count > 250)
                {
                    s_Gradients.Remove(s_Gradients.Keys.ToList().First());
                }
            }

            var      width    = (int)rect.width;
            var      height   = (int)rect.height;
            Gradient gradient = new Gradient();
            var      gt       = new Texture2D(width, height)
            {
                alphaIsTransparency = true
            };
            float angle           = 0.0f;
            int   valueStartIndex = 0;

            if (call.GetValueType(0, 0) == StyleValue.Type.Number)
            {
                angle           = call.GetNumber(0, 0);
                valueStartIndex = 1;
            }

            var valueCount = call.args.Count - valueStartIndex;

            var colorKeys = new GradientColorKey[valueCount];
            var alphaKeys = new GradientAlphaKey[valueCount];

            float increment = valueCount <= 1 ? 1f : 1f / (valueCount - 1);
            float autoStep  = 0;

            for (int i = 0; i < valueCount; ++i)
            {
                var valueIndex = valueStartIndex + i;
                var values     = call.args[valueIndex];
                if (values.Length == 1 && values[0].type == StyleValue.Type.Color)
                {
                    colorKeys[i].color = call.GetColor(valueIndex, 0);
                    colorKeys[i].time  = autoStep;
                }
                else if (values.Length == 2 && values[0].type == StyleValue.Type.Color && values[1].type == StyleValue.Type.Number)
                {
                    colorKeys[i].color = call.GetColor(valueIndex, 0);
                    colorKeys[i].time  = call.GetNumber(valueIndex, 1);
                }
                else
                {
                    Debug.LogError("Invalid gradient value argument");
                }

                alphaKeys[i].time  = colorKeys[i].time;
                alphaKeys[i].alpha = colorKeys[i].color.a;

                autoStep = Mathf.Clamp(autoStep + increment, 0f, 1f);
            }

            gradient.SetKeys(colorKeys, alphaKeys);

            var   ratio  = height / (float)width;
            var   rad    = Mathf.Deg2Rad * angle;
            float CosRad = Mathf.Cos(rad);
            float SinRad = Mathf.Sin(rad);

            var matrix = GetGradientRotMatrix(angle);

            for (int y = height - 1; y >= 0; --y)
            {
                for (int x = width - 1; x >= 0; --x)
                {
                    var   pixelPosition = new Vector2(x, y);
                    var   recenteredPos = GetGradientCenterFrame(pixelPosition, width, height);
                    var   scaleVec      = GetGradientScaleVector(matrix, angle, width, height);
                    var   scaledMatrix  = GetGradientScaleMatrix(matrix, scaleVec);
                    var   posInGradient = scaledMatrix.MultiplyVector(recenteredPos);
                    Color color         = gradient.Evaluate(1f - (posInGradient.y / 2 + 0.5f));
                    gt.SetPixel(x, y, color);
                }
            }

            gt.Apply();
            s_Gradients[key] = gt;
            return(gt);
        }
Beispiel #40
0
 /// <summary>
 /// Creates a texture map for the current content of the noise map.
 /// </summary>
 /// <param name="device">The graphics device to use.</param>
 /// <param name="gradient">The gradient to color the texture map with.</param>
 /// <returns>The created texture map.</returns>
 public Texture2D GetTexture(ref Gradient gradient)
 {
     Texture2D result = new Texture2D(this.m_width, this.m_height);
     Color[] data = new Color[this.m_width * this.m_height];
     int id = 0;
     for (int y = 0; y < this.m_height; y++)
     {
         for (int x = 0; x < this.m_width; x++, id++)
         {
             float d = 0.0f;
             if (!float.IsNaN(this.m_borderValue) && (x == 0 || x == this.m_width - 1 || y == 0 || y == this.m_height - 1))
             {
                 d = this.m_borderValue;
             }
             else
             {
                 d = this.m_data[x, y];
             }
             data[id] = gradient[d];
         }
     }
     //result.SetData<Color>(data);
     //Debug.Log("Setting pixels");
     result.SetPixels(data);
     return result;
 }
Beispiel #41
0
    void Update()
    {
        if (s.valid == -1)
        {
            // Destroy star and its orbit track
            Destroy(gameObject);
        }
        else if (s.valid == 0)
        {
            // Destroy star but keep its orbit track
            var          track             = Instantiate(trackObjectPrefab);
            LineRenderer trackLineRenderer = track.GetComponent <LineRenderer>();
            trackLineRenderer.widthMultiplier = 0.1f;
            trackLineRenderer.startColor      = lineRendererColor;
            trackLineRenderer.endColor        = Color.white;

            trackLineRenderer.positionCount = lineRenderer.positionCount;

            Vector3[] positions = new Vector3[lineRenderer.positionCount];
            lineRenderer.GetPositions(positions);
            trackLineRenderer.SetPositions(positions);

            Gradient gradient = new Gradient();
            gradient.SetKeys(
                new GradientColorKey[] { new GradientColorKey(lineRendererColor, 0.0f), new GradientColorKey(Color.Lerp(lineRendererColor, Color.white, 0.5f), 0.9f), new GradientColorKey(Color.white, 1.0f) },
                new GradientAlphaKey[] { new GradientAlphaKey(lineRendererColor.a, 0.0f), new GradientAlphaKey(lineRendererColor.a, 1.0f) }
                );
            trackLineRenderer.colorGradient = gradient;

            Destroy(gameObject);
        }
        else
        {
            // Update star position and LineRenderer
            Vector3 posVec3 = new Vector3((float)s.pos[0], (float)s.pos[1], (float)s.pos[2]);
            if (transform.position != posVec3)
            {
                transform.position = posVec3;
                if (nowLineRendererIndex < maxLengthOfLineRenderer)
                {
                    lineRenderer.positionCount = nowLineRendererIndex + 1;

                    lineRenderer.SetPosition(nowLineRendererIndex, posVec3);
                    nowLineRendererIndex++;
                }
                else
                {
                    lineRenderer.Simplify(0.02f);
                    // Debug.Log("Line reduced from " + nowLineRendererIndex + " to " + lineRenderer.positionCount);
                    nowLineRendererIndex = lineRenderer.positionCount;
                    if (maxLengthOfLineRenderer < 5000)
                    {
                        maxLengthOfLineRenderer += 100;
                    }
                }
            }
        }
        if (selectedToDisplayInfo == true)
        {
            GUIObjectScript.starInfoToDisplay =
                "Pos x: " + s.pos[0].ToString() + "\n" +
                "Pos y: " + s.pos[1].ToString() + "\n" +
                "Pos x: " + s.pos[2].ToString() + "\n" +
                "V x: " + s.vel[0].ToString() + "\n" +
                "V y: " + s.vel[1].ToString() + "\n" +
                "V z: " + s.vel[2].ToString() + "\n" +
                "Mass: " + s.mass.ToString() + "\n";
        }
    }
Beispiel #42
0
        protected virtual void PostUpdateLineRenderers()
        {
            using (PostUpdateLineRenderersPerfMarker.Auto())
            {
                if (!IsInteractionEnabled)
                {
                    return;
                }

                // The distance the ray travels through the world before it hits something. Measured in world-units (as opposed to normalized distance).
                float    clearWorldLength;
                Gradient lineColor = LineColorNoTarget;

                if (Result?.CurrentPointerTarget != null)
                {
                    // We hit something
                    clearWorldLength = Result.Details.RayDistance;
                    lineColor        = IsSelectPressed ? LineColorSelected : LineColorValid;
                }
                else
                {
                    clearWorldLength = DefaultPointerExtent;
                    lineColor        = IsSelectPressed ? LineColorSelected : LineColorNoTarget;
                }

                if (IsFocusLocked)
                {
                    lineColor = LineColorLockFocus;
                }

                int maxClampLineSteps = 2;
                for (int i = 0; i < LineRenderers.Length; i++)
                {
                    // Renderers are enabled by default if line is enabled
                    maxClampLineSteps          = Mathf.Max(maxClampLineSteps, LineRenderers[i].LineStepCount);
                    LineRenderers[i].LineColor = lineColor;
                }

                // Used to ensure the line doesn't extend beyond the cursor
                float cursorOffsetWorldLength = (BaseCursor != null) ? BaseCursor.SurfaceCursorDistance : 0;

                // Readjust the Line renderer's endpoint to match the the cursor's position if it is focus locked to a target
                if (IsFocusLocked && IsTargetPositionLockedOnFocusLock && Result != null)
                {
                    SetLinePoints(Position, Result.Details.Point + Rotation * Vector3.back * cursorOffsetWorldLength);
                }

                // If focus is locked, we're sticking to the target
                // So don't clamp the world length, the line data's end point is already set to the world cursor
                if (IsFocusLocked && IsTargetPositionLockedOnFocusLock)
                {
                    LineBase.LineEndClamp = 1;
                }
                else
                {
                    // Otherwise clamp the line end by the clear distance
                    float clearLocalLength = lineBase.GetNormalizedLengthFromWorldLength(clearWorldLength - cursorOffsetWorldLength, maxClampLineSteps);
                    LineBase.LineEndClamp = clearLocalLength;
                }
            }
        }
Beispiel #43
0
        public static Color GetGradientAsColor(SerializedProperty gradientProp)
        {
            Gradient gradientValue = gradientProp.gradientValue;

            return(gradientValue.constantColor);
        }
 [FreeFunction(Name = "VisualEffectBindings::SetValueFromScript<Gradient*>", HasExplicitThis = true)] extern public void SetGradient(int nameID, Gradient g);
Beispiel #45
0
    void ChangeCheckerSprite(string spriteName, GameObject checkers)
    {
        for (int i = 0; i < checkers.transform.childCount / 2; ++i)
        {
            //установка спрайта
            Image userImg = checkers.transform.GetChild(i).gameObject.GetComponent <Image>();
            userImg.sprite = Resources.Load <Sprite>("Sprites/levels/checkers/" + spriteName);

            //установка материала
            switch (mode)
            {
            case GameRule.Mode.Normal:
                userImg.material = Resources.Load <Material>("Sprites/Materials/Checker/user_CheckerGlowMat");
                break;

            case GameRule.Mode.Speed:
                userImg.material = Resources.Load <Material>("Sprites/Materials/Checker/user_DissolveMat");
                break;
            }

            //установка текстуры материала
            Texture texture = Resources.Load <Texture>("Sprites/levels/checkers/" + spriteName);
            userImg.material.SetTexture("_MainTex", texture);

            //установка цвета материала
            TextAsset textAsset = (TextAsset)Resources.Load("XML/Game/checkerColors");
            XElement  xdoc      = XDocument.Parse(textAsset.text).Element("checkerColors");

            int   red = 0, green = 0, blue = 0;
            float intensity = 1f;

            foreach (XElement clr in xdoc.Elements(spriteName))
            {
                red       = int.Parse(clr.Element("red").Value);
                green     = int.Parse(clr.Element("green").Value);
                blue      = int.Parse(clr.Element("blue").Value);
                intensity = float.Parse(clr.Element("intensity").Value, CultureInfo.InvariantCulture);
            }

            float factor = (float)Math.Exp(-5.5115115f + 0.68895733f * intensity);

            Color color = new Color(red * factor, green * factor, blue * factor);
            userImg.material.SetColor("_Color", color);

            //установка градиента цвета трея
            Gradient           gradient;
            GradientColorKey[] colorKey;
            GradientAlphaKey[] alphaKey;

            //_Color - id цвета в материале чекеров
            colorKey          = new GradientColorKey[2];
            colorKey[0].color = userImg.material.GetColor("_Color");
            colorKey[0].time  = 0.0f;
            colorKey[1].color = userImg.material.GetColor("_Color");
            colorKey[1].time  = 1.0f;

            alphaKey          = new GradientAlphaKey[2];
            alphaKey[0].alpha = 1.0f;
            alphaKey[0].time  = 0.0f;
            alphaKey[1].alpha = 0.2f;
            alphaKey[1].time  = 1.0f;

            gradient = new Gradient();
            gradient.SetKeys(colorKey, alphaKey);

            TrailRenderer trailRenderer = checkers.transform.GetChild(i).gameObject.transform.GetChild(0).gameObject.GetComponent <TrailRenderer>();
            trailRenderer.colorGradient = gradient;
        }
    }
 [FreeFunction(Name = "VisualEffectBindings::Internal_GetGradientFromScript", HasExplicitThis = true)] extern private void Internal_GetGradient(int nameID, Gradient gradient);
 public RandomColor(Gradient source)
 {
     _source = source;
 }
 public void SetGradient(string name, Gradient g)
 {
     SetGradient(Shader.PropertyToID(name), g);
 }
 public TweenData_CanvasRenderer_Gradient(CanvasRenderer inRenderer, Gradient inTarget, ColorUpdate inUpdate)
 {
     m_Renderer = inRenderer;
     m_Gradient = inTarget;
     m_Update   = inUpdate;
 }
Beispiel #50
0
    ///*****************//
    ///Editor specific stuff.
    ///Dangerous if you do not know what you are doing.
    ///*****************//

    #region Editor Stuff
    private void Awake()
    {
        StartingColorMap = GetComponent <ParticleSystem>().colorOverLifetime.color.gradient;
        colorMap         = GetComponent <ParticleSystem>().colorOverLifetime.color.gradient;
    }
 public TweenData_Graphic_Gradient(Graphic inRenderer, Gradient inTarget, ColorUpdate inUpdate)
 {
     m_Renderer = inRenderer;
     m_Gradient = inTarget;
     m_Update   = inUpdate;
 }
Beispiel #52
0
 public void ResetColor()
 {
     colorMap = StartingColorMap;
     Debug.Log("Color Reset: " + gameObject.name);
 }
        static void CustomGraphicsBlit(RenderTexture source, RenderTexture dest, Material fxMaterial, int passNr, Gradient DistGradient, Vector2 GradientBounds, Texture2D colourPalette)
        {
            RenderTexture.active = dest;

            fxMaterial.SetTexture("_MainTex", source);



            fxMaterial.SetTexture("_ColorRamp", colourPalette);

            if (GradientBounds != Vector2.zero)
            {
                fxMaterial.SetFloat("_Close", GradientBounds.x);
                fxMaterial.SetFloat("_Far", GradientBounds.y);
            }



            GL.PushMatrix();
            GL.LoadOrtho();

            fxMaterial.SetPass(passNr);

            GL.Begin(GL.QUADS);

            GL.MultiTexCoord2(0, 0.0f, 0.0f);
            GL.Vertex3(0.0f, 0.0f, 3.0f);              // BL

            GL.MultiTexCoord2(0, 1.0f, 0.0f);
            GL.Vertex3(1.0f, 0.0f, 2.0f);              // BR

            GL.MultiTexCoord2(0, 1.0f, 1.0f);
            GL.Vertex3(1.0f, 1.0f, 1.0f);              // TR

            GL.MultiTexCoord2(0, 0.0f, 1.0f);
            GL.Vertex3(0.0f, 1.0f, 0.0f);              // TL

            GL.End();
            GL.PopMatrix();
        }
Beispiel #54
0
 private static void OnChangeGradient(Gradient gradient)
 {
     s_Gradient         = gradient;
     s_NeedBlitGradient = true;
 }
 public static void SetGradient(Gradient g1, Gradient g2, float lerpAmount)
 {
     instance.SetGradientInternal(g1, g2, lerpAmount);
 }
Beispiel #56
0
        private static RenderMesh DisplayMeshResults <TNode, TFace, TMeshElementResult>(this IMesh <TNode, TFace> mesh, IMeshResult <TMeshElementResult> meshResult, Type identifier,
                                                                                        string meshResultDisplay, Gradient gradient, double from, double to)
            where TNode : INode
            where TFace : IFace
            where TMeshElementResult : IMeshElementResult
        {
            if (mesh?.Nodes == null || mesh?.Faces == null || mesh.Nodes.Count < 1 || mesh.Faces.Count < 1)
            {
                Engine.Reflection.Compute.RecordError("A mesh is null or invalid. Cannot display results for this mesh.");
                return(null);
            }
            if (meshResult?.Results == null || meshResult.Results.Count < 1)
            {
                Engine.Reflection.Compute.RecordError("A result is null or invalid. Cannot display results for this mesh.");
                return(null);
            }

            // Order the MeshNodeResults by the IMesh Nodes
            List <List <TMeshElementResult> > tempMappedElementResults = mesh.Nodes.MapResults(meshResult.Results, "NodeId", identifier);
            // Get the relevant values into a list

            List <Vertex> verts = new List <Vertex>();
            List <Face>   faces;

            object smoothing = Reflection.Query.PropertyValue(meshResult, "Smoothing");
            MeshResultSmoothingType smoothingType = MeshResultSmoothingType.None;

            if (smoothing is MeshResultSmoothingType)
            {
                smoothingType = (MeshResultSmoothingType)smoothing;
            }

            switch (smoothingType)
            {
            case MeshResultSmoothingType.None:
                //  pair nodeValue as list<Dictionary<FaceId,nodeValue>>
                //  all nodes are expected to have FaceIds
                List <Dictionary <IComparable, double> > nodeValuePairs = tempMappedElementResults.Select(x => x.ToDictionary(y => y.MeshFaceId, y => /*propFunction(y)*/ y.ResultToValue(meshResultDisplay))).ToList();
                //  put the Faces in a Dictionary<FaceId,Face>
                Dictionary <object, Face> faceDictionaryResult   = mesh.Faces.ToDictionary(x => x.FindFragment <IAdapterId>(identifier).Id, x => x.Geometry());
                Dictionary <object, Face> faceDictionaryRefrence = mesh.Faces.ToDictionary(x => x.FindFragment <IAdapterId>(identifier).Id, x => x.Geometry());

                // Add all verticies to a list with their colour and update the Faces
                for (int k = 0; k < mesh.Nodes.Count; k++)
                {
                    foreach (KeyValuePair <IComparable, double> FaceRelatedValue in nodeValuePairs[k])
                    {
                        verts.Add(new Vertex()
                        {
                            Point = mesh.Nodes[k].Position,
                            Color = gradient.Color(FaceRelatedValue.Value, from, to)
                        });
                        // Face management, faceResult points to verts and faceReference points to mesh.Nodes
                        Face faceResult    = faceDictionaryResult[FaceRelatedValue.Key];
                        Face faceReference = faceDictionaryRefrence[FaceRelatedValue.Key];
                        Face newFace       = new Face()
                        {
                            A = faceReference.A == k ? verts.Count - 1 : faceResult.A,
                            B = faceReference.B == k ? verts.Count - 1 : faceResult.B,
                            C = faceReference.C == k ? verts.Count - 1 : faceResult.C,
                            D = faceReference.IsQuad() ? faceReference.D == k ? verts.Count - 1 : faceResult.D : -1
                        };
                        faceDictionaryResult[FaceRelatedValue.Key] = newFace;
                    }
                }
                faces = faceDictionaryResult.Select(x => x.Value).ToList();
                break;

            case MeshResultSmoothingType.ByPanel:
            case MeshResultSmoothingType.Global:
                List <double> nodeValues = tempMappedElementResults.Select(x => x[0].ResultToValue(meshResultDisplay)).ToList();

                // Add all verticies to a list with their colour
                for (int k = 0; k < mesh.Nodes.Count; k++)
                {
                    verts.Add(new Vertex()
                    {
                        Point = mesh.Nodes[k].Position,
                        Color = gradient.Color(nodeValues[k], from, to)
                    });
                }
                faces = mesh.Faces.Geometry().ToList();
                break;

            case MeshResultSmoothingType.ByFiniteElementCentres:
            case MeshResultSmoothingType.BySelection:
            default:
                Engine.Reflection.Compute.RecordError("Unsupported SmoothingType: " + Reflection.Query.PropertyValue(meshResult, "Smoothing").ToString() +
                                                      " detected, meshResult for ObjectId: " + meshResult.ObjectId.ToString() +
                                                      " and ResultCase: " + meshResult.ResultCase.ToString() + "will be returned empty.");
                return(new RenderMesh());
            }

            return(new RenderMesh()
            {
                Vertices = verts, Faces = faces
            });
        }
Beispiel #57
0
 /// <summary>
 /// Creates a texture map for the current content of the noise map.
 /// </summary>
 /// <param name="device">The graphics device to use.</param>
 /// <param name="gradient">The gradient to color the texture map with.</param>
 /// <returns>The created texture map.</returns>
 public Texture2D GetTexture(Gradient gradient)
 {
     return this.GetTexture(ref gradient);
 }
Beispiel #58
0
 void setRainbow()
 {
     grad = new Gradient();
     grad.SetKeys(new GradientColorKey[] { new GradientColorKey(Color.black, 0.0f), new GradientColorKey(Color.blue, 0.25f), new GradientColorKey(Color.green, 0.45f), new GradientColorKey(Color.yellow, 0.65f), new GradientColorKey(Color.red, .80f), new GradientColorKey(Color.white, 1.0f) }, new GradientAlphaKey[] { new GradientAlphaKey(1.0f, 0.0f), new GradientAlphaKey(1.0f, 1.0f) });
     col.color = new ParticleSystem.MinMaxGradient(grad);
 }
    static int _CreateGradient(IntPtr L)
    {
        int count = LuaDLL.lua_gettop(L);

        if (count == 0)
        {
            Gradient obj = new Gradient();
            LuaScriptMgr.PushObject(L, obj);
            return 1;
        }
        else
        {
            LuaDLL.luaL_error(L, "invalid arguments to method: Gradient.New");
        }

        return 0;
    }
Beispiel #60
0
 void setBlack()
 {
     grad = new Gradient();
     grad.SetKeys(new GradientColorKey[] { new GradientColorKey(Color.black, 0.0f), new GradientColorKey(Color.white, 1.0f) }, new GradientAlphaKey[] { new GradientAlphaKey(1.0f, 0.0f), new GradientAlphaKey(0.0f, 1.0f) });
     col.color = new ParticleSystem.MinMaxGradient(grad);
 }