Пример #1
1
 internal static void BeginScrollView(Rect position, Vector2 scrollPosition, Rect viewRect, GUIStyle horizontalScrollbar, GUIStyle verticalScrollbar)
 {
     s_ScrollPos = scrollPosition;
     s_ViewRect = viewRect;
     s_Position = position;
     GUIClip.Push(position, new Vector2(Mathf.Round((-scrollPosition.x - viewRect.x) - ((viewRect.width - position.width) * 0.5f)), Mathf.Round((-scrollPosition.y - viewRect.y) - ((viewRect.height - position.height) * 0.5f))), Vector2.zero, false);
 }
Пример #2
1
        public static void ApplySetPieces(World world)
        {
            var map = world.Map;
            int w = map.Width, h = map.Height;

            Random rand = new Random();
            HashSet<Rect> rects = new HashSet<Rect>();
            foreach (var dat in setPieces)
            {
                int size = dat.Item1.Size;
                int count = rand.Next(dat.Item2, dat.Item3);
                for (int i = 0; i < count; i++)
                {
                    IntPoint pt = new IntPoint();
                    Rect rect;

                    int max = 50;
                    do
                    {
                        pt.X = rand.Next(0, w);
                        pt.Y = rand.Next(0, h);
                        rect = new Rect() { x = pt.X, y = pt.Y, w = size, h = size };
                        max--;
                    } while ((Array.IndexOf(dat.Item4, map[pt.X, pt.Y].Terrain) == -1 ||
                             rects.Any(_ => Rect.Intersects(rect, _))) &&
                             max > 0);
                    if (max <= 0) continue;
                    dat.Item1.RenderSetPiece(world, pt);
                    rects.Add(rect);
                }
            }
        }
Пример #3
0
    void Start()
    {
        Vector2 objs = tk2dspr.GetComponent<tk2dSprite>().GetUntrimmedBounds().size;
        r = new Rect(-3, 1.3f , TEMPSIZE.GetComponent<tk2dSprite>().GetUntrimmedBounds().size.x, TEMPSIZE.GetComponent<tk2dSprite>().GetUntrimmedBounds().size.y);

        Scale(r, Rows, Columns, objs, distBetweenXY, out RCScale);
        SetSPriteSize(tk2dspr.GetComponent<tk2dSprite>(), RCScale);

         objs = tk2dspr.GetComponent<tk2dSprite>().GetUntrimmedBounds().size;

        Vector2 pos=new Vector2(r.x,r.y);
        Debug.LogError(pos);
        for (int i = 0; i < Rows; i++) {
            for (int j = 0; j < Columns; j++) {
                positions.Add(CreateContainerPos(pos,new Vector2(pos.x+objs.x,pos.y-objs.y)));
                    pos.x += distBetweenXY.x;
                    pos.x += objs.x;
            }
            pos.x = r.xMin;
            pos.y -= distBetweenXY.y;
            pos.y -= objs.y;
        }

        foreach (var p in positions)
        {
            Instantiate(tk2dspr, p, new Quaternion());
            print(p);
        }
    }
		public MarshalRect(Rect rect)
		{
			x = rect.x;
			y = rect.y;
			width = rect.width;
			height = rect.height;
		}
Пример #5
0
    void CheckCamera()
    {
        if(Input.GetMouseButton(0)){

            if(startClick.x > Input.mousePosition.x && startClick.y > Input.mousePosition.y){ //drag left/down
                selection = new Rect(Input.mousePosition.x,
                                     InvertMouseY(startClick.y),
                                     startClick.x - Input.mousePosition.x,
                                     InvertMouseY(Input.mousePosition.y) - InvertMouseY(startClick.y));
            }else if(startClick.x > Input.mousePosition.x && startClick.y < Input.mousePosition.y){ //drag left/up
                selection = new Rect(Input.mousePosition.x,
                                     InvertMouseY(Input.mousePosition.y),
                                     startClick.x - Input.mousePosition.x,
                                     InvertMouseY(startClick.y) - InvertMouseY(Input.mousePosition.y));
            }else if(startClick.x < Input.mousePosition.x && startClick.y < Input.mousePosition.y){ //drag right/up
                selection = new Rect(startClick.x,
                                     InvertMouseY(Input.mousePosition.y),
                                     Input.mousePosition.x - startClick.x,
                                     InvertMouseY(startClick.y) - InvertMouseY(Input.mousePosition.y));
            }else{ //drag right/down
                selection = new Rect(startClick.x,
                                     InvertMouseY(startClick.y),
                                     Input.mousePosition.x - startClick.x,
                                     InvertMouseY(Input.mousePosition.y) - InvertMouseY(startClick.y));
            }
        }
    }
Пример #6
0
        private BitmapBrush CreateDirectBrush(
            ImageBrush brush,
            SharpDX.Direct2D1.RenderTarget target,
            Bitmap image, 
            Rect sourceRect, 
            Rect destinationRect)
        {
            var tileMode = brush.TileMode;
            var scale = brush.Stretch.CalculateScaling(destinationRect.Size, sourceRect.Size);
            var translate = CalculateTranslate(brush, sourceRect, destinationRect, scale);
            var transform = Matrix.CreateTranslation(-sourceRect.Position) *
                Matrix.CreateScale(scale) *
                Matrix.CreateTranslation(translate);

            var opts = new BrushProperties
            {
                Transform = transform.ToDirect2D(),
                Opacity = (float)brush.Opacity,
            };

            var bitmapOpts = new BitmapBrushProperties
            {
                ExtendModeX = GetExtendModeX(tileMode),
                ExtendModeY = GetExtendModeY(tileMode),                
            };

            return new BitmapBrush(target, image, bitmapOpts, opts);
        }
Пример #7
0
    public void init()
    {
        time_texture = Resources.Load("textures/time_gui") as Texture;
        rstats_texture = Resources.Load("textures/rstats_gui") as Texture;

        float w = time_texture.width;
        time_gui_rect = new Rect(0, 0, w, time_texture.height);
        rstats_gui_rect = new Rect(Screen.width - w, 0, w, rstats_texture.height);

        int s_w = Screen.width, s_h = Screen.height;

        debug_rect = new Rect(0, time_texture.height, s_w, (s_h * 2) / 100);
        debug_style.alignment = TextAnchor.UpperLeft;
        debug_style.fontSize = (s_h * 2) / 80;
        debug_style.normal.textColor = new Color(1, 1, 1, 1);

        Font gui_font = Resources.Load("fonts/gui_font") as Font;

        timer_rect = new Rect((time_gui_rect.width / 2.0f) - 125, (time_gui_rect.height / 2.0f) - 40, timer_rect.width, timer_rect.height);
        timer_style.alignment = TextAnchor.UpperLeft;
        timer_style.fontSize = (int)(time_texture.height / 2.0f);
        timer_style.normal.textColor = new Color(1, 1, 1, 1);
        timer_style.font = gui_font;

        rstats_rect = new Rect(rstats_gui_rect.x + ((rstats_gui_rect.width / 2.0f) - 50), (rstats_gui_rect.height / 2.0f) - 40, rstats_rect.width, rstats_rect.height);
        rstats_style.alignment = TextAnchor.UpperLeft;
        rstats_style.fontSize = (rstats_font_size = (int)(rstats_texture.height / 2.0f));
        rstats_style.normal.textColor = new Color(1, 1, 1, 1);
        rstats_style.font = gui_font;
    }
Пример #8
0
	void OnGUI()
	{
		GUI.skin.font = skin.font;
		GUI.Label (new Rect(Screen.width-250, 200, 250, 250), DisplayObjectiveOnScreen());
			


		if(activate) //activate the quest manager
		{
			GUI.skin = skin;
			windowRect0 = GUI.Window (4, windowRect0, Questmanager, "");
			//now adjust to the group. (0,0) is the topleft corner of the group.
			GUI.BeginGroup (new Rect (0,0,100,100));
			// End the group we started above. This is very important to remember!
			GUI.EndGroup ();

			if (showquest) //if we have chosen a quest
			{
				GUI.skin = skin;
				windowRect0 = GUI.Window (4, windowRect0, ShowQuest, ""); //show the information of the quest
				GUI.BeginGroup (new Rect (0,0,100,100));
				// End the group we started above. This is very important to remember!
				GUI.EndGroup ();
			}
		}
		else
		{
			showquest = false; //close the quest manager even if a quest is shown
		}

	}
Пример #9
0
    void OnGUI()
    {
        _guiRect = new Rect(7, Screen.height - 180, 250, 200);
        GUILayout.BeginArea(_guiRect);

        GUILayout.BeginVertical();
        string expName = currentDetonator.name;
        if (GUILayout.Button(expName + " (Click For Next)"))
        {
            NextExplosion();
        }
        if (GUILayout.Button("Rebuild Wall"))
        {
            SpawnWall();
        }
        if (GUILayout.Button("Camera Far"))
        {
            Camera.main.transform.position = new Vector3(0, 0, -7);
            Camera.main.transform.eulerAngles = new Vector3(13.5f, 0, 0);
        }
        if (GUILayout.Button("Camera Near"))
        {
            Camera.main.transform.position = new Vector3(0, -8.664466f, 31.38269f);
            Camera.main.transform.eulerAngles = new Vector3(1.213462f, 0, 0);
        }

        GUILayout.Label("Time Scale");
        timeScale = GUILayout.HorizontalSlider(timeScale, 0.0f, 1.0f);

        GUILayout.Label("Detail Level (re-explode after change)");
        detailLevel = GUILayout.HorizontalSlider(detailLevel, 0.0f, 1.0f);

        GUILayout.EndVertical();
        GUILayout.EndArea();
    }
Пример #10
0
 // 展现层
 void OnGUI()
 {
     // 平铺扫雷格子
     for (int i = 0; i < row; i++) {
         for (int j = 0; j < col; j++) {
             // 显示格子中的信息,用于调试
             string tip = i + "," + j;
             tip += "\n" + map[i, j].number;
             // 用按钮背景颜色区分格子
             if (map[i, j].hasBoom) { // 有雷:红色
                 GUI.backgroundColor = Color.red;
             } else {
                 GUI.backgroundColor = Color.yellow;
             }
             Rect rect = new Rect(j * size, i * size, size, size);
             if (map[i, j].opened) {
                 // Box表示已经开启过的格子
                 GUI.Box (rect , tip);
             } else if (GUI.Button(rect, tip)){
                 // Button表示未开启过的格子
                 if (map[i, j].hasBoom) {
                     // 如果踩到了雷,GameOver
                     print ("GameOver!!");
                 } else {
                     // 否则展开(i,j)处格子
                     Open (i, j);
                 }
             }
         }
     }
 }
Пример #11
0
        public static System.Drawing.Brush GetBrush(this Brush brush, Rect frame)
        {
            var cb = brush as SolidBrush;
            if (cb != null) {
                return new System.Drawing.SolidBrush (cb.Color.GetColor ());
            }

            var lgb = brush as LinearGradientBrush;
            if (lgb != null) {
                var s = lgb.Absolute ? lgb.Start : frame.Position + lgb.Start * frame.Size;
                var e = lgb.Absolute ? lgb.End : frame.Position + lgb.End * frame.Size;
                var b = new System.Drawing.Drawing2D.LinearGradientBrush (GetPointF (s), GetPointF (e), System.Drawing.Color.Black, System.Drawing.Color.Black);
                var bb = BuildBlend (lgb.Stops);
                if (bb != null) {
                    b.InterpolationColors = bb;
                }
                return b;
            }

            var rgb = brush as RadialGradientBrush;
            if (rgb != null) {
                var r = rgb.GetAbsoluteRadius (frame);
                var c = rgb.GetAbsoluteCenter (frame);
                var path = new GraphicsPath ();
                path.AddEllipse (GetRectangleF (new Rect (c - r, 2 * r)));
                var b = new PathGradientBrush (path);
                var bb = BuildBlend (rgb.Stops, true);
                if (bb != null) {
                    b.InterpolationColors = bb;
                }
                return b;
            }

            throw new NotImplementedException ("Brush " + brush);
        }
Пример #12
0
    public void SpawnGibs(GibType gType, Rect area, int amount, float force  = 10, float lifeSpan = 5)
    {
        List<Gib> eList;

        if (_gibs.TryGetValue(gType, out eList))
        {
            for (int a = 0; a < amount; a++)
            {
                Gib g = null;

                for (int i = 0; i < eList.Count; i++)
                {
                    if (!eList[i].gameObject.activeInHierarchy)
                    {
                        g = eList[i];
                        break;
                    }
                }

                if (!g)
                {
                    g = NewGib(gType);
                }

                var position = new Vector2(Random.Range(area.xMin, area.xMax), Random.Range(area.yMin, area.yMax));

                g.Spawn(gType, position, force, lifeSpan);
            }
        }
    }
Пример #13
0
    void menu()
    {
        //GameObject handCursor = GameObject.Find("HandCursor");
        pMenu = GetComponent<pauseMenu>();
        opMenu = GetComponent<optionsMenu>();
        //layout start
        GUI.BeginGroup(new Rect(Screen.width / 2 - 150, 50, 300, 300));

        //the menu background box
        GUI.Box(new Rect(0, 0, 300, 300), "");

        //logo picture
        //GUI.Label(new Rect(15, 10, 300, 68), logoTexture);

        ///////main menu buttons
        //options button
        kinectRect = new Rect(55, 50, 180, 40);
        if(GUI.Button(kinectRect, "Using Kinect - "+ (PlayerPrefs.GetInt("useKinect") == 1))) //true if currently using the Kinect. Else false. We want to toggle this.
        {
        toggleKinect();
        }
        //back button
        backRect = new Rect(55, 100, 180, 40);
        if(GUI.Button(backRect, "Back"))
        {
        back ();
        }

        //layout end
        GUI.EndGroup();
    }
Пример #14
0
    void InputManager()
    {
        if (Input.GetMouseButtonDown(0))
        {
            startClick = Input.mousePosition;
        }
        else if (Input.GetMouseButtonUp(0))
        {
            startClick = -Vector3.one;
        }
        if (Input.GetMouseButton(0))
        {
            selection = new Rect(startClick.x, InvertRectY(startClick.y), Input.mousePosition.x - startClick.x, InvertRectY(Input.mousePosition.y) - InvertRectY(startClick.y));

            if (selection.width < 0)
            {
                Debug.Log("lower width");
                selection.x += selection.width;
                selection.width = -selection.width;
            }
            if (selection.height < 0)
            {
                Debug.Log("lower height");
                selection.y += selection.height;
                selection.height = -selection.height;
            }
        }
    }
 void GenerateStimLocations()
 {
     //Position stimuli randomly according to settings (no overlaps)
     List<Rect> overlapCheckList = new List<Rect>();
     int retries = 100;
     for (int i = 0; i < numberOfStim; i++)
     {
         stimLocations[i] = new Vector3(
             Random.Range(handController.position.x - stimLocationSize.x / 2, handController.position.x + stimLocationSize.x / 2) + stimLocationOffset.x,
             Random.Range(handController.position.y - stimLocationSize.y / 2, handController.position.y + stimLocationSize.y / 2) + stimLocationOffset.y,
             Random.Range(handController.position.z - stimLocationSize.z / 2, handController.position.z + stimLocationSize.z / 2) + stimLocationOffset.z);
         //Check for overlapping boxes and regenerate box location if overlap occurs
         Rect newBox = new Rect(stimLocations[i].x, stimLocations[i].z, cube.transform.localScale.x * 2, cube.transform.localScale.z * 2);
         if (boxesOverlapArray(newBox, overlapCheckList))
         {
             retries--;
             if (retries <= 0)
             {
                 //Force quit and overlap to prevent hang
                 overlapCheckList.Add(newBox);
                 Debug.Log("Unable to find proper placement of object. Too many objects or incorrect mesh bounds?");
             }
             else i--;
         }
         else
         {
             overlapCheckList.Add(newBox);
         }
     }
 }
Пример #16
0
    // Use this for initialization
    void Start()
    {
        // Cache this component at startup instßead of looking up every frame
        gui = GetComponent<GUITexture>();

        // Store the default rect for the gui, so we can snap back to it
        defaultRect = gui.pixelInset;

        defaultRect.x += transform.position.x * Screen.width;
        defaultRect.y += transform.position.y * Screen.height;

        //this.transform.position.x = 0.0f;
        //this.transform.position.y = 0.0f;
        transform.position = new Vector3(0.0f, 0.0f, 0.0f);

        // This is an offset for touch input to match with the top left
        // corner of the GUI
        guiTouchOffset.x = defaultRect.width * 0.5f;
        guiTouchOffset.y = defaultRect.height * 0.5f;

        // Cache the center of the GUI, since it doesn't change
        guiCenter.x = defaultRect.x + guiTouchOffset.x;
        guiCenter.y = defaultRect.y + guiTouchOffset.y;

        // Let's build the GUI boundary, so we can clamp joystick movement
        guiBoundary.min.x = defaultRect.x - guiTouchOffset.x;
        guiBoundary.max.x = defaultRect.x + guiTouchOffset.x;
        guiBoundary.min.y = defaultRect.y - guiTouchOffset.y;
        guiBoundary.max.y = defaultRect.y + guiTouchOffset.y;
    }
Пример #17
0
    Texture2D Capture(Camera camera, Rect rect)
    {
        // 创建一个RenderTexture对象
        RenderTexture rt = new RenderTexture((int)rect.width, (int)rect.height, 0);
        // 临时设置相关相机的targetTexture为rt, 并手动渲染相关相机
        camera.targetTexture = rt;
        camera.Render();
        //ps: --- 如果这样加上第二个相机,可以实现只截图某几个指定的相机一起看到的图像。
        //ps: camera2.targetTexture = rt;
        //ps: camera2.Render();
        //ps: -------------------------------------------------------------------

        // 激活这个rt, 并从中中读取像素。
        RenderTexture.active = rt;
        Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.ARGB32, false);
        screenShot.ReadPixels(rect, 0, 0);// 注:这个时候,它是从RenderTexture.active中读取像素
        screenShot.Apply();

        // 重置相关参数,以使用camera继续在屏幕上显示
        camera.targetTexture = null;
        //ps: camera2.targetTexture = null;
        RenderTexture.active = null; // JC: added to avoid errors
        GameObject.Destroy(rt);
        // 最后将这些纹理数据,成一个png图片文件  
        byte[] bytes = screenShot.EncodeToPNG();
        string filename = Application.dataPath + "/Screenshot.png";
        System.IO.File.WriteAllBytes(filename, bytes);
        Debug.Log(string.Format("截屏了一张照片: {0}", filename));

        return screenShot;
    }
Пример #18
0
 private void OnGUI()
 {
     if(paused)
             {
                     windowRect = GUI.Window (0, windowRect, windowFunc, "Pause Menu");
             }
 }
Пример #19
0
 public DoubleFrame(string title,int buttonHeight, Rect position, int border)
 {
     this.title = title;
     this.position = position;
     this.border = border;
     SetUp (buttonHeight);
 }
Пример #20
0
 void Start()
 {
     this.startButtonRect = new Rect(Screen.width - this.RightMargin - this.StartButtonWidth,
                                     Screen.height - this.BottomMargin - this.StartButtonHeight,
                                     this.StartButtonWidth,
                                     this.StartButtonHeight);
 }
Пример #21
0
		public WriteableBitmap (UIElement element, Transform transform) :
			base (SafeNativeMethods.writeable_bitmap_new (), true)
		{
			if (element == null)
				throw new ArgumentNullException ("element");

			Rect bounds = new Rect ();
			// Width and Height are defined in FrameworkElement - but it's unlikely to be an "unknown" UIElement
			// descendant since there's no usable ctor to inherit from it (at least outside S.W.dll)
			FrameworkElement fe = (element as FrameworkElement);
			if (fe != null) {
				bounds.Width = fe.ActualWidth;
				bounds.Height = fe.ActualHeight;
			}

			if (transform != null)
				bounds = transform.TransformBounds (bounds);

			AllocatePixels (Double.IsNaN (bounds.Width) ? 0 : (int) bounds.Width, Double.IsNaN (bounds.Height) ? 0 : (int) bounds.Height);
			PinAndSetBitmapData ();

			Invalidate ();

			Render (element, transform);
		}
Пример #22
0
	private void ResizeMenuHorizontal(){
		Rect rect = new Rect (listRect.width - 5, listRect.y, 10, listRect.height);
		EditorGUIUtility.AddCursorRect(rect, MouseCursor.ResizeHorizontal);
		int controlID = GUIUtility.GetControlID(FocusType.Passive);
		Event ev = Event.current;
		switch (ev.rawType) {
		case EventType.MouseDown:
			if(rect.Contains(ev.mousePosition)){
				GUIUtility.hotControl = controlID;
				ev.Use();
			}
			break;
		case EventType.MouseUp:
			if (GUIUtility.hotControl == controlID)
			{
				GUIUtility.hotControl = 0;
				ev.Use();
			}
			break;
		case EventType.MouseDrag:
			if (GUIUtility.hotControl == controlID)
			{
				listRect.width=ev.mousePosition.x;
				listRect.width=Mathf.Clamp(listRect.width,200,400);
				ev.Use();
			}
			break;
		}
	}
    private void changeFrame()
    {
        if(!Loop && !firstRun)
            return;

        newUvs = new Rect(FrameSize*(currentColoum),FrameSize*(currentRow*-1) , 1,1);
        if(changeTexture){
            //EditorDebug.LogWarning("ChangeTExture");
            renderer.material.SetTexture("_MainTex", Textures[currentTexture]);
            changeTexture = false;
        }

        currentColoum++;
        if(currentColoum >= FramesPerRow){
            currentColoum = 0;
            currentRow++;
        }
        if(currentRow >= RowCount)
            currentRow = 0;
        if(currentFrameNumber%FramesPerTexture == 0){
            currentTexture++;
            if(currentTexture >= Textures.Length)
                currentTexture = 0;
            changeTexture = true;
            firstRun = false;

        }
        //EditorDebug.Log("New UVs: " + newUvs + "Row: " + currentRow + "Coloumn: " + currentColoum);
    }
Пример #24
0
    public void DrawGameBoard()
    {
        float width = 75;
        float height = 75;

        for (int y=0; y<3; y++) {
        for (int x=0; x<3; x++) {

        int boardIndex = (y*3) + x;
        Rect square = new Rect(x*width, y*height, width, height);

        string owner = board[boardIndex] == SquareState.XControl ? "X" : board[boardIndex] == SquareState.OControl ? "O" : "";

        if (board[boardIndex] == SquareState.Clear) {
        if (GUI.Button(square,owner)) SetControl(boardIndex);
        }
        else GUI.Label(square, owner);

        Rect turnRect = new Rect(300,0,100,100);
        string turnTitle = xTurn ? "X's Turn!" : "O's Turn!";
        GUI.Label(turnRect, turnTitle);

        }
        }
    }
Пример #25
0
	void OnGUI()
	{
		if (game.allowInput)
		{
			winRect = GUILayout.Window(0, winRect, theWindow, "Game GUI");
		}
	}
 private void SetAmmoTo(int newValue)
 {
     int index = 0;
     float width = (newValue * 1f) / ((float) this.userShip.maxProps.ammo);
     if (width >= 0.66f)
     {
         this.ammoSprite.SetSprite(this.progressClipName[2]);
         index = 2;
     }
     else if (width >= 0.33f)
     {
         this.ammoSprite.SetSprite(this.progressClipName[1]);
         index = 1;
     }
     else
     {
         this.ammoSprite.SetSprite(this.progressClipName[0]);
     }
     Rect rect = new Rect(0f, 0f, width, 1f);
     this.ammoSprite.ClipRect = rect;
     if (this.ammoAmountText != null)
     {
         this.ammoAmountText.color = this.textColors[index];
         this.ammoAmountText.text = newValue + "/" + this.userShip.maxProps.ammo;
         this.ammoAmountText.Commit();
     }
 }
Пример #27
0
    public void FromJSON(Ferr_JSONValue aJSON)
    {
        Ferr_JSONValue json = new Ferr_JSONValue();
        applyTo = (Ferr2DT_TerrainDirection)aJSON["applyTo", (int)Ferr2DT_TerrainDirection.Top];
        zOffset   = aJSON["zOffset",0f];
        yOffset   = aJSON["yOffset",0f];
        capOffset = aJSON["capOffset",0f];
        leftCap = new Rect(
            aJSON["leftCap.x",     0f],
            aJSON["leftCap.y",     0f],
            aJSON["leftCap.xMax",  0f],
            aJSON["leftCap.yMax",  0f]);
        rightCap = new Rect(
            aJSON["rightCap.x",    0f],
            aJSON["rightCap.y",    0f],
            aJSON["rightCap.xMax", 0f],
            aJSON["rightCap.yMax", 0f]);

        Ferr_JSONValue bodyArr = json["body"];
        body = new Rect[bodyArr.Length];
        for (int i = 0; i < body.Length; i++) {
            body[i] = new Rect(
                bodyArr[i]["x",    0 ],
                bodyArr[i]["y",    0 ],
                bodyArr[i]["xMax", 50],
                bodyArr[i]["yMax", 50]);
        }
    }
Пример #28
0
    private float vertExtent; // The size of vertical of the screen.

    #endregion Fields

    #region Methods

    void OnGUI()
    {
        float width = Screen.width/4;
        float height = Screen.height/8;

        GUI.skin = _skinNuevo;
        Rect rectBotonNewGame =  new Rect((Screen.width-width)/2,(Screen.height*.25f)-height/2, width,height);
        if (GUI.Button (rectBotonNewGame, "")){
            PlayerPrefsX.SetVector3("CheckSpawn", Vector3.zero);
            PlayerPrefs.SetInt("CountCheck",0);
            PlayerPrefsX.SetVector3 ("OldLevelLight",new Vector3(-12,1,0));
        //			PlayerPrefs.DeleteAll();
        //			Application.LoadLevel("LevelScene");
            Application.LoadLevel("Game");
        }

        GUI.skin = _skinContinuar;
        Rect rectBotonContinuar = new Rect((Screen.width-width)/2,(Screen.height*.50f)-height/2, width,height);

        if (GUI.Button(rectBotonContinuar, "")){
            Application.LoadLevel("CheckLevel");
        }

        GUI.skin = _skinSalir;
        Rect rectBotonSalir = new Rect ((Screen.width-width)/2, (Screen.height*.75f)-height/2, width,height);
        if (GUI.Button (rectBotonSalir, "")) {
            Application.Quit();
        }
    }
Пример #29
0
 void OnGUI()
 {
     Rect R = new Rect(posXrr,posYr,lCr,aCr);
     GUILayout.BeginArea (R);
         GUILayout.Window (0,R,daJanela,"",skin.box);
     GUILayout.EndArea ();
 }
Пример #30
0
		public void SliceFill(VertexBuffer vb)
		{
			Rect gridRect = (Rect)_scale9Grid;
			Rect contentRect = vb.contentRect;
			Rect uvRect = vb.uvRect;

			float sourceW = texture.width;
			float sourceH = texture.height;

			if (graphics.flip != FlipType.None)
			{
				if (graphics.flip == FlipType.Horizontal || graphics.flip == FlipType.Both)
				{
					gridRect.x = sourceW - gridRect.xMax;
					gridRect.xMax = gridRect.x + gridRect.width;
				}

				if (graphics.flip == FlipType.Vertical || graphics.flip == FlipType.Both)
				{
					gridRect.y = sourceH - gridRect.yMax;
					gridRect.yMax = gridRect.y + gridRect.height;
				}
			}

			float sx = uvRect.width / sourceW;
			float sy = uvRect.height / sourceH;
			float xMax = uvRect.xMax;
			float yMax = uvRect.yMax;
			float xMax2 = gridRect.xMax;
			float yMax2 = gridRect.yMax;

			gridTexX[0] = uvRect.x;
			gridTexX[1] = uvRect.x + gridRect.x * sx;
			gridTexX[2] = uvRect.x + xMax2 * sx;
			gridTexX[3] = xMax;
			gridTexY[0] = yMax;
			gridTexY[1] = yMax - gridRect.y * sy;
			gridTexY[2] = yMax - yMax2 * sy;
			gridTexY[3] = uvRect.y;

			if (contentRect.width >= (sourceW - gridRect.width))
			{
				gridX[1] = gridRect.x;
				gridX[2] = contentRect.width - (sourceW - xMax2);
				gridX[3] = contentRect.width;
			}
			else
			{
				float tmp = gridRect.x / (sourceW - xMax2);
				tmp = contentRect.width * tmp / (1 + tmp);
				gridX[1] = tmp;
				gridX[2] = tmp;
				gridX[3] = contentRect.width;
			}

			if (contentRect.height >= (sourceH - gridRect.height))
			{
				gridY[1] = gridRect.y;
				gridY[2] = contentRect.height - (sourceH - yMax2);
				gridY[3] = contentRect.height;
			}
			else
			{
				float tmp = gridRect.y / (sourceH - yMax2);
				tmp = contentRect.height * tmp / (1 + tmp);
				gridY[1] = tmp;
				gridY[2] = tmp;
				gridY[3] = contentRect.height;
			}

			if (_tileGridIndice == 0)
			{
				for (int cy = 0; cy < 4; cy++)
				{
					for (int cx = 0; cx < 4; cx++)
						vb.AddVert(new Vector2(gridX[cx], gridY[cy]), vb.vertexColor, new Vector2(gridTexX[cx], gridTexY[cy]));
				}
				vb.AddTriangles(TRIANGLES_9_GRID);
			}
			else
			{
				Rect drawRect;
				Rect texRect;
				int row, col;
				int part;

				for (int pi = 0; pi < 9; pi++)
				{
					col = pi % 3;
					row = pi / 3;
					part = gridTileIndice[pi];
					drawRect = Rect.MinMaxRect(gridX[col], gridY[row], gridX[col + 1], gridY[row + 1]);
					texRect = Rect.MinMaxRect(gridTexX[col], gridTexY[row + 1], gridTexX[col + 1], gridTexY[row]);

					if (part != -1 && (_tileGridIndice & (1 << part)) != 0)
					{
						TileFill(vb, drawRect, texRect,
							(part == 0 || part == 1 || part == 4) ? gridRect.width : drawRect.width,
							(part == 2 || part == 3 || part == 4) ? gridRect.height : drawRect.height);
					}
					else
					{
						vb.AddQuad(drawRect, vb.vertexColor, texRect);
					}
				}

				vb.AddTriangles();
			}
		}
Пример #31
0
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        CheckInitialize(property, label);


        var foldoutRect = position;

        foldoutRect.width -= 2 * 50;
        foldoutRect.height = 17f;
        EditorGUI.BeginChangeCheck();
        _foldout = EditorGUI.Foldout(foldoutRect, _foldout, label, true);
        if (EditorGUI.EndChangeCheck())
        {
            EditorPrefs.SetBool(label.text, _foldout);
        }

        float yPos = 17f;

        if (_foldout)
        {
            EditorGUI.LabelField(new Rect(new Vector2(position.position.x, position.position.y + yPos), new Vector2(position.size.x, 17f)), "Count: " + _dict.Count);
            yPos += 17f;
            EditorGUI.BeginChangeCheck();
            GameObject newObj = EditorGUI.ObjectField(new Rect(new Vector2(position.position.x + position.size.x / 2, position.position.y + yPos), new Vector2(position.size.x / 2, 17f)), _nextObject, typeof(GameObject), false) as GameObject;
            if (EditorGUI.EndChangeCheck())
            {
                _nextObject = newObj;
                ValueChanged(property);
            }

            yPos += 20f;
            if (GUI.Button(new Rect(new Vector2(position.position.x + position.size.x * 0.1f, position.position.y + yPos), new Vector2(position.size.x * 0.8f, 17f)), "Add"))
            {
                if (_nextObject == null)
                {
                    Debug.LogWarning("Cannot add empty gameobject here");
                    return;
                }
                else if (_dict.ContainsKey(_nextObject) == false)
                {
                    _dict.Add(_nextObject, new DictionaryIntInt());
                    DictionaryIntIntDrawer newDrawer = new DictionaryIntIntDrawer();
                    newDrawer._dict = _dict[_nextObject];
                    _drawers.Add(_nextObject, newDrawer);
                    _orderedKeys.Add(_nextObject);
                    ValueChanged(property);
                }
                else
                {
                    Debug.LogWarning("This dictionary already contains a value for key " + _nextObject.name);
                }
                return;
            }
            yPos += 17f;

            for (int keyOrder = 0; keyOrder < _orderedKeys.Count; ++keyOrder)
            {
                GameObject       key = _orderedKeys[keyOrder];
                DictionaryIntInt val = _dict[key];
                yPos += 8f;
                if (GUI.Button(new Rect(new Vector2(position.position.x, position.position.y + yPos), new Vector2(17f, 17f)), "-"))
                {
                    _dict.Remove(key);
                    _drawers.Remove(key);
                    _orderedKeys.RemoveAt(keyOrder);
                    ValueChanged(property);
                    return;
                }
                GameObject newObject = EditorGUI.ObjectField(new Rect(new Vector2(position.position.x + 18f, position.position.y + yPos), new Vector2(position.size.x / 2 - 9f, 17f)), key, typeof(GameObject), false) as GameObject;
                if (newObject == null)
                {
                    return;
                }
                if (newObject != key)
                {
                    int        idx      = _orderedKeys.FindIndex((o) => o == key);
                    GameObject oldValue = _orderedKeys[idx];
                    _orderedKeys[idx] = newObject;
                    _dict.Add(newObject, _dict[oldValue]);
                    _dict.Remove(oldValue);
                    _drawers.Add(newObject, _drawers[oldValue]);
                    _drawers.Remove(oldValue);
                    ValueChanged(property);
                    return;
                }
                GUIContent guiContent = new GUIContent("Values");
                yPos += 17f;
                _drawers[key].OnGUI(new Rect(new Vector2(position.position.x + 17f, position.position.y + yPos), new Vector2(position.size.x - 17f, _drawers[key].GetPropertyHeight(null, guiContent))), null, guiContent);
                yPos += _drawers[key].GetPropertyHeight(null, guiContent);
            }
        }
    }
Пример #32
0
    private void Create()
    {
        if (tex == null)
        {
            Debug.LogWarning("创建失败,图片为空!");
            return;
        }

        if (string.IsNullOrEmpty(fontPath))
        {
            Debug.LogWarning("字体路径为空!");
            return;
        }

        if (fontName == null)
        {
            Debug.LogWarning("创建失败,字体名称为空!");
            return;
        }
        else
        {
            if (File.Exists(Application.dataPath + fontPath + fontName + ".fontsettings"))
            {
                Debug.LogError("创建失败,已存在同名字体文件");
                return;
            }

            if (File.Exists(Application.dataPath + fontPath + fontName + ".mat"))
            {
                Debug.LogError("创建失败,已存在同名字体材质文件");
                return;
            }
        }

        string selectionPath = AssetDatabase.GetAssetPath(tex);
        if (selectionPath.Contains("/Resources/"))
        {
            string selectionExt = Path.GetExtension(selectionPath);
            if (selectionExt.Length == 0)
            {
                Debug.LogError("创建失败!");
                return;
            }

            string fontPathName = fontPath + fontName + ".fontsettings";
            string matPathName = fontPath + fontName + ".mat";
            float lineSpace = 0.1f;
            //string loadPath = selectionPath.Remove(selectionPath.Length - selectionExt.Length).Replace("Assets/Resources/", "");
            string loadPath = selectionPath.Replace(selectionExt, "")
                .Substring(selectionPath.IndexOf("/Resources/") + "/Resources/".Length);
            Sprite[] sprites = Resources.LoadAll<Sprite>(loadPath);
            if (sprites.Length > 0)
            {
                Material mat = new Material(Shader.Find("GUI/Text Shader"));
                mat.SetTexture("_MainTex", tex);
                Font m_myFont = new Font();
                m_myFont.material = mat;
                CharacterInfo[] characterInfo = new CharacterInfo[sprites.Length];
                for (int i = 0; i < sprites.Length; i++)
                {
                    if (sprites[i].rect.height > lineSpace)
                    {
                        lineSpace = sprites[i].rect.height;
                    }
                }

                for (int i = 0; i < sprites.Length; i++)
                {
                    Sprite spr = sprites[i];
                    CharacterInfo info = new CharacterInfo();
                    try
                    {
                        info.index = System.Convert.ToInt32(spr.name);
                    }
                    catch
                    {
                        Debug.LogError("创建失败,Sprite名称错误!");
                        return;
                    }

                    Rect rect = spr.rect;
                    float pivot = spr.pivot.y / rect.height - 0.5f;
                    if (pivot > 0)
                    {
                        pivot = -lineSpace / 2 - spr.pivot.y;
                    }
                    else if (pivot < 0)
                    {
                        pivot = -lineSpace / 2 + rect.height - spr.pivot.y;
                    }
                    else
                    {
                        pivot = -lineSpace / 2;
                    }

                    int offsetY = (int) (pivot + (lineSpace - rect.height) / 2);
                    info.uvBottomLeft = new Vector2((float) rect.x / tex.width, (float) (rect.y) / tex.height);
                    info.uvBottomRight = new Vector2((float) (rect.x + rect.width) / tex.width,
                        (float) (rect.y) / tex.height);
                    info.uvTopLeft = new Vector2((float) rect.x / tex.width,
                        (float) (rect.y + rect.height) / tex.height);
                    info.uvTopRight = new Vector2((float) (rect.x + rect.width) / tex.width,
                        (float) (rect.y + rect.height) / tex.height);
                    info.minX = 0;
                    info.minY = -(int) rect.height - offsetY;
                    info.maxX = (int) rect.width;
                    info.maxY = -offsetY;
                    info.advance = (int) rect.width;
                    characterInfo[i] = info;
                }

                AssetDatabase.CreateAsset(mat, "Assets" + matPathName);
                AssetDatabase.CreateAsset(m_myFont, "Assets" + fontPathName);
                m_myFont.characterInfo = characterInfo;
                EditorUtility.SetDirty(m_myFont);
                AssetDatabase.SaveAssets();
                AssetDatabase.Refresh(); //刷新资源
                Debug.Log("创建字体成功");
            }
            else
            {
                Debug.LogError("图集错误!");
            }
        }
        else
        {
            Debug.LogError("创建失败,选择的图片不在Resources文件夹内!");
        }
    }
        public override void OnGUI(Rect position, SerializedProperty prop, GUIContent label)
        {
#if !UNITY_5_0_PLUS
            EditorGUI.LabelField(position, label.text + " [works in Unity 5+]");
        }
Пример #34
0
 public override void Draw(Rect rect, object presetObject)
 {
     this.DrawInternal(rect, presetObject as Gradient);
 }
Пример #35
0
 public override void Draw(Rect rect, int index)
 {
     this.DrawInternal(rect, this.m_Presets[index].gradient);
 }
Пример #36
0
 public override void GetBounds(ref Rect outBounds, Matrix parentMatrix)
 {
     base.GetBounds(ref outBounds, parentMatrix);
     _contentGroup.GetBounds(ref outBounds, BoundsMatrix);
 }
Пример #37
0
 protected abstract void OnGUI_Internal(Rect rect, SerializedProperty property, GUIContent label);
Пример #38
0
	private static void OnProjectItemGUI(string item, Rect selectionRect)
	{
		if (string.IsNullOrEmpty(item))
			return;

		if (Event.current.isMouse)
		{
			if (Event.current.type != EventType.MouseDown || Event.current.clickCount != 2 || Event.current.button != 0)
				return;

			if (!selectionRect.Contains(Event.current.mousePosition))
				return;
		}
		else
		{
			return;
		}

		string path = AssetDatabase.GUIDToAssetPath(item);
		if (!path.EndsWith(".cs", System.StringComparison.OrdinalIgnoreCase) &&
			!path.EndsWith(".js", System.StringComparison.OrdinalIgnoreCase) &&
			!path.EndsWith(".boo", System.StringComparison.OrdinalIgnoreCase))
		{
			// not a script

			TextAsset txt = null;
			if (EditorPrefs.GetBool("ScriptInspector.HandleOpenTextFromProject", false))
			{
				if (!path.EndsWith(".dll", System.StringComparison.OrdinalIgnoreCase))
					txt = AssetDatabase.LoadAssetAtPath(path, typeof(TextAsset)) as TextAsset;
			}
			if (txt == null)
			{
				// not a text asset

				Shader shader = null;
				if (EditorPrefs.GetBool("ScriptInspector.HandleOpenShaderFromProject", false))
					shader = AssetDatabase.LoadAssetAtPath(path, typeof(Shader)) as Shader;
				if (shader == null)
				{
					// not even a shader
					return;
				}
			}

			Event.current.Use();
			OpenAssetInTab(item);
			GUIUtility.ExitGUI();
			return;
		}

		if (!EditorPrefs.GetBool("ScriptInspector.HandleOpenFromProject", false))
			return;

		MonoScript script = AssetDatabase.LoadAssetAtPath(path, typeof(MonoScript)) as MonoScript;
		if (script != null)
		{
			Event.current.Use();
			OpenAssetInTab(item);
			GUIUtility.ExitGUI();
		}
	}
		ReorderableList CreateReorderableList(SerializedProperty listProp)
		{
			var list = new ReorderableList(listProp.serializedObject, listProp);
			var recorder = ((UniversalObserver)listProp.serializedObject.targetObject).GetRecorder();

			list.drawHeaderCallback +=
				(Rect position) =>
				{
					EditorGUI.LabelField(position, "Observation Targets");
				};

			list.elementHeightCallback =
				(int index) =>
				{
					if(listProp.arraySize == 0)
						return EditorGUIUtility.singleLineHeight + 10;

					var container = listProp.GetArrayElementAtIndex(index);
					var target = container.FindPropertyRelative("target");
					var keyChain = container.FindPropertyRelative("keys");
					var height = 0f;
					if (target.objectReferenceValue == null || keyChain.arraySize == 0)
					{
						height = EditorGUIUtility.singleLineHeight + 10;
					}
					else
					{
						height = EditorGUIUtility.singleLineHeight * (2 + keyChain.arraySize) + 10;
					}
					return height;
				};

			list.drawElementBackgroundCallback =
				(Rect position, int index, bool selected, bool focused) =>
				{
					position.height = list.elementHeightCallback(index);
					if (focused)
						EditorGUI.DrawRect(position, new Color(0.35f, 0.54f, 0.81f));
					else if (selected)
						EditorGUI.DrawRect(position, new Color(0.6f, 0.6f, 0.6f));
					else if ((index & 1) == 0)
						EditorGUI.DrawRect(position, new Color(0f, 0f, 0f, 0.1f));

				};

			list.drawElementCallback =
				(Rect position, int index, bool selected, bool focused) => 
				{
					var container = listProp.GetArrayElementAtIndex(index);

					var enabled = container.FindPropertyRelative("enabled");
					var target = container.FindPropertyRelative("target");
					var propName = container.FindPropertyRelative("propertyName");
					var keyChain = container.FindPropertyRelative("keys");
					var memberType = container.FindPropertyRelative("memberType");
					var ducTrigger = container.FindPropertyRelative("distinctUntilChanged");
					
					var mPos = new Rect(position);
					mPos.height = EditorGUIUtility.singleLineHeight;
					mPos.y += 5;

					if (target.objectReferenceValue != null)
					{
						mPos.xMin = mPos.xMax - 20;
						enabled.boolValue = EditorGUI.Toggle(mPos, enabled.boolValue);
						mPos.xMin = position.xMin;
					}
					else enabled.boolValue = true;
					EditorGUI.BeginDisabledGroup(!enabled.boolValue);

					var prevName = propName.stringValue;
					var type = TargetSelectField(mPos, target, propName, memberType);
					if (type == null)
					{
						keyChain.arraySize = 0;
					}
					else
					{
						if (prevName != propName.stringValue)
						{
							var reader = TypeReader.Get(type);
							if (reader != null)
							{
								var labels = reader.CreateKeyLabels();
								var prevLength = keyChain.arraySize;
								keyChain.arraySize = labels.Length;
								for (int i = 0; i < keyChain.arraySize; i++)
								{
									var elem = keyChain.GetArrayElementAtIndex(i);
									if (prevLength <= i)
										elem.FindPropertyRelative("key").intValue = -1;
									elem.FindPropertyRelative("label").stringValue = labels[i];
								}
							}
						}

						var recorderObj = new SerializedObject(recorder);
						for (int i = 0; i < keyChain.arraySize; i++)
						{
							var elem = keyChain.GetArrayElementAtIndex(i);
							var label = elem.FindPropertyRelative("label");
							var key = elem.FindPropertyRelative("key");

							mPos.y += mPos.height;
							key.intValue = GraphDataKeyAttributeDrawer.RecorderKeyField(
									mPos, recorderObj, label.stringValue, key.intValue, false);
						}

						mPos.y += mPos.height + 5;
						EditorGUI.PropertyField(mPos, ducTrigger);
					}
					EditorGUI.EndDisabledGroup();
				};
			return list;
		}
Пример #40
0
 // Use this for initialization
 void Start()
 {
     //GUIRectPosition1 = new Rect(Screen.width / 2 - text1X, Screen.height / 2 - text1Y, text1X, text1Y);
     GUIRectPosition2 = new Rect(Screen.width / 2 - text2X, Screen.height / 2 - text2Y, text2X, text2Y);
 }
Пример #41
0
 private void AddRectToExtent(Rect newRect) => 
   CurrentExtent = Rect.Union(CurrentExtent, newRect);
        private void DrawList(AdvancedDropdownItem item)
        {
            // Start of scroll view list
            m_State.SetScrollState(item, GUILayout.BeginScrollView(m_State.GetScrollState(item), GUIStyle.none, GUI.skin.verticalScrollbar));
            EditorGUIUtility.SetIconSize(m_Gui.iconSize);
            Rect selectedRect = new Rect();

            for (var i = 0; i < item.children.Count(); i++)
            {
                var  child    = item.children.ElementAt(i);
                bool selected = m_State.GetSelectedIndex(item) == i;

                if (child.IsSeparator())
                {
                    m_Gui.DrawLineSeparator();
                }
                else
                {
                    m_Gui.DrawItem(child, child.displayName, child.icon, child.enabled, child.children.Any(), selected, hasSearch);
                }

                var r = GUILayoutUtility.GetLastRect();
                if (selected)
                {
                    selectedRect = r;
                }

                // Skip input handling for the tree used for animation
                if (item != m_CurrentlyRenderedTree)
                {
                    continue;
                }

                // Select the element the mouse cursor is over.
                // Only do it on mouse move - keyboard controls are allowed to overwrite this until the next time the mouse moves.
                if (Event.current.type == EventType.MouseMove || Event.current.type == EventType.MouseDrag)
                {
                    if (!selected && r.Contains(Event.current.mousePosition))
                    {
                        m_State.SetSelectedIndex(item, i);
                        Event.current.Use();
                    }
                }
                if (Event.current.type == EventType.MouseUp && r.Contains(Event.current.mousePosition))
                {
                    m_State.SetSelectedIndex(item, i);
                    var selectedChild = m_State.GetSelectedChild(item);
                    if (selectedChild.children.Any())
                    {
                        GoToChild();
                    }
                    else
                    {
                        if (!selectedChild.IsSeparator() && selectionChanged != null)
                        {
                            selectionChanged(selectedChild);
                        }
                        if (closeOnSelection)
                        {
                            CloseWindow();
                            GUIUtility.ExitGUI();
                        }
                    }
                    Event.current.Use();
                }
            }
            EditorGUIUtility.SetIconSize(Vector2.zero);
            GUILayout.EndScrollView();

            // Scroll to selected on windows creation
            if (m_ScrollToSelected && m_InitialSelectionPosition != 0)
            {
                float diffOfPopupAboveTheButton = m_ButtonRectScreenPos.y - position.y;
                diffOfPopupAboveTheButton -= m_Gui.searchHeight + m_Gui.headerHeight;
                m_State.SetScrollState(item, new Vector2(0, m_InitialSelectionPosition - diffOfPopupAboveTheButton));
                m_ScrollToSelected         = false;
                m_InitialSelectionPosition = 0;
            }
            // Scroll to show selected
            else if (m_ScrollToSelected && Event.current.type == EventType.Repaint)
            {
                m_ScrollToSelected = false;
                Rect scrollRect = GUILayoutUtility.GetLastRect();
                if (selectedRect.yMax - scrollRect.height > m_State.GetScrollState(item).y)
                {
                    m_State.SetScrollState(item, new Vector2(0, selectedRect.yMax - scrollRect.height));
                    Repaint();
                }
                if (selectedRect.y < m_State.GetScrollState(item).y)
                {
                    m_State.SetScrollState(item, new Vector2(0, selectedRect.y));
                    Repaint();
                }
            }
        }
Пример #43
0
        public override void OnGUI(Rect rect)
        {
            bool hasScale = true;
            string accept = "";
            switch (popupMode)
            {
                case PopupMode.BezierDetailLevel:
                    GUILayout.Label("Bezier Detail Level", EditorStyles.boldLabel);
                    hasScale = false;
                    accept = "Apply";

                    GUILayout.BeginHorizontal(EditorStyles.toolbar);
                    if (GUILayout.Button("1", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 1; onApply(this); }
                    if (GUILayout.Button("2", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 2; onApply(this); }
                    if (GUILayout.Button("3", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 3; onApply(this); }
                    if (GUILayout.Button("4", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 4; onApply(this); }
                    if (GUILayout.Button("5", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 5; onApply(this); }
                    if (GUILayout.Button("6", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 6; onApply(this); }
                    if (GUILayout.Button("7", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 7; onApply(this); }
                    if (GUILayout.Button("8", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 8; onApply(this); }
                    GUILayout.EndHorizontal();

                    GUILayout.BeginHorizontal(EditorStyles.toolbar);
                    if (GUILayout.Button("9", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 9; onApply(this); }
                    if (GUILayout.Button("10", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 10; onApply(this); }
                    if (GUILayout.Button("11", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 11; onApply(this); }
                    if (GUILayout.Button("12", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 12; onApply(this); }
                    if (GUILayout.Button("13", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 13; onApply(this); }
                    if (GUILayout.Button("14", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 14; onApply(this); }
                    if (GUILayout.Button("15", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 15; onApply(this); }
                    if (GUILayout.Button("16", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 16; onApply(this); }
                    GUILayout.EndHorizontal();

                    GUILayout.BeginHorizontal(EditorStyles.toolbar);
                    if (GUILayout.Button("17", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 17; onApply(this); }
                    if (GUILayout.Button("18", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 18; onApply(this); }
                    if (GUILayout.Button("19", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 19; onApply(this); }
                    if (GUILayout.Button("20", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 20; onApply(this); }
                    if (GUILayout.Button("21", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 21; onApply(this); }
                    if (GUILayout.Button("22", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 22; onApply(this); }
                    if (GUILayout.Button("23", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 23; onApply(this); }
                    if (GUILayout.Button("24", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 24; onApply(this); }
                    GUILayout.EndHorizontal();

                    GUILayout.BeginHorizontal(EditorStyles.toolbar);
                    if (GUILayout.Button("25", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 25; onApply(this); }
                    if (GUILayout.Button("26", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 26; onApply(this); }
                    if (GUILayout.Button("27", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 27; onApply(this); }
                    if (GUILayout.Button("28", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 28; onApply(this); }
                    if (GUILayout.Button("29", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 29; onApply(this); }
                    if (GUILayout.Button("30", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 30; onApply(this); }
                    if (GUILayout.Button("31", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 31; onApply(this); }
                    if (GUILayout.Button("32", EditorStyles.toolbarButton, GUILayout.MinWidth(24), GUILayout.MaxWidth(24))) { bezierDetailLevel_Detail = 32; onApply(this); }
                    GUILayout.EndHorizontal();

                    bezierDetailLevel_Detail = EditorGUILayout.IntField("Detail", bezierDetailLevel_Detail);
                    if (bezierDetailLevel_Detail < 1) bezierDetailLevel_Detail = 1;
                    if (bezierDetailLevel_Detail > 999) bezierDetailLevel_Detail = 999;
                    break;

                case PopupMode.GlobalPivotPosition:
                    GUILayout.Label("Global Pivot Position", EditorStyles.boldLabel);
                    hasScale = false;
                    accept = "Set Position";

#if !UNITY_2017_2_OR_NEWER
                    EditorGUIUtility.wideMode = true;
                    GlobalPivotPosition_Position = Vector2Int.FloorToInt(EditorGUILayout.Vector2Field("Position", GlobalPivotPosition_Position));
                    EditorGUIUtility.wideMode = false;
#else
                    EditorGUIUtility.wideMode = true;
                    GlobalPivotPosition_Position = EditorGUILayout.Vector2IntField("Position", GlobalPivotPosition_Position);
                    EditorGUIUtility.wideMode = false;
#endif
                    break;

                case PopupMode.CreatePolygon:
                    GUILayout.Label("Create Polygon", EditorStyles.boldLabel);
                    accept = "Create";
                    break;

                case PopupMode.RevolveShape:
                    GUILayout.Label("Revolve Shape", EditorStyles.boldLabel);
                    accept = "Revolve";

                    revolve360 = EditorGUILayout.IntField("Per 360", revolve360);
                    if (revolve360 < 3) revolve360 = 3;
                    revolveSteps = EditorGUILayout.IntField("Steps", revolveSteps);
                    if (revolveSteps < 1) revolveSteps = 1;

                    // steps can't be more than 360.
                    if (revolveSteps > revolve360) revolveSteps = revolve360;
                    break;

                case PopupMode.ExtrudeShape:
                    GUILayout.Label("Extrude Shape", EditorStyles.boldLabel);
                    accept = "Extrude";

                    extrudeDepth = EditorGUILayout.FloatField("Depth", extrudeDepth);
                    if (extrudeDepth < 0.01f) extrudeDepth = 0.01f;
                    break;

                case PopupMode.ExtrudePoint:
                    GUILayout.Label("Extrude Point", EditorStyles.boldLabel);
                    accept = "Extrude";

                    extrudeDepth = EditorGUILayout.FloatField("Depth", extrudeDepth);
                    if (extrudeDepth < 0.01f) extrudeDepth = 0.01f;
                    break;

                case PopupMode.ExtrudeBevel:
                    GUILayout.Label("Extrude Bevel", EditorStyles.boldLabel);
                    accept = "Extrude";

                    extrudeDepth = EditorGUILayout.FloatField("Depth", extrudeDepth);
                    if (extrudeDepth < 0.01f) extrudeDepth = 0.01f;
                    extrudeClipDepth = EditorGUILayout.FloatField("Clip Depth", extrudeClipDepth);
                    if (extrudeClipDepth < 0.01f) extrudeClipDepth = 0.01f;
                    if (extrudeClipDepth > extrudeDepth) extrudeClipDepth = extrudeDepth;
                    break;
            }

            if (hasScale)
            {
                EditorGUIUtility.wideMode = true;
                extrudeScale = EditorGUILayout.Vector2Field("Scale", extrudeScale);
                EditorGUIUtility.wideMode = false;
                if (extrudeScale.x < 0.01f) extrudeScale.x = 0.01f;
                if (extrudeScale.y < 0.01f) extrudeScale.y = 0.01f;
            }

            if (GUILayout.Button(accept))
            {
                onApply(this);
            }
        }
Пример #44
0
 public override void OnGUI(Rect rect)
 {
     PAlignCenter.OnGUI(rect, true);
 }
Пример #45
0
 // Token: 0x0600000F RID: 15 RVA: 0x00002718 File Offset: 0x00000918
 public override void DoSettingsWindowContents(Rect inRect)
 {
     Settings.DoSettingsWindowContents(inRect);
 }
        public float ResizeHandle(Rect windowPosition, float minSize, float minRemainingSize, float resizerHeight, Rect dragRect)
        {
            // Sanity check the cached value. It can be positive or negative, but never smaller than the minSize
            if (Mathf.Abs(m_CachedPref) < minSize)
            {
                m_CachedPref = minSize * Mathf.Sign(m_CachedPref);
            }

            float maxPreviewSize = windowPosition.height - minRemainingSize;
            bool  dragging       = (GUIUtility.hotControl == id);

            float previewSize = (dragging ? s_DraggedPreviewSize : Mathf.Max(0, m_CachedPref));
            bool  expanded    = (m_CachedPref > 0);
            float lastSize    = Mathf.Abs(m_CachedPref);

            Rect resizerRect = new Rect(0, windowPosition.height - previewSize - resizerHeight, windowPosition.width, resizerHeight);

            if (dragRect.width != 0)
            {
                resizerRect.x     = dragRect.x;
                resizerRect.width = dragRect.width;
            }

            bool expandedBefore = expanded;

            previewSize = -PixelPreciseCollapsibleSlider(id, resizerRect, -previewSize, -maxPreviewSize, -0, ref expanded);
            previewSize = Mathf.Min(previewSize, maxPreviewSize);
            dragging    = (GUIUtility.hotControl == id);

            if (dragging)
            {
                s_DraggedPreviewSize = previewSize;
            }

            // First snap size between 0 and minimum size
            if (previewSize < minSize)
            {
                previewSize = (previewSize < minSize * 0.5f ? 0 : minSize);
            }

            // If user clicked area, adjust size
            if (expanded != expandedBefore)
            {
                previewSize = (expanded ? lastSize : 0);
            }

            // Determine new expanded state
            expanded = (previewSize >= minSize / 2);

            // Keep track of last preview size while not dragging or collapsed
            // Note we don't want to save when dragging preview OR window size,
            // so just don't save while dragging anything at all
            if (GUIUtility.hotControl == 0)
            {
                if (previewSize > 0)
                {
                    lastSize = previewSize;
                }
                float newPref = lastSize * (expanded ? 1 : -1);
                if (newPref != m_CachedPref)
                {
                    // Save the value to prefs
                    m_CachedPref = newPref;
                    EditorPrefs.SetFloat(m_PrefName, m_CachedPref);
                }
            }

            s_CachedPreviewSizeWhileDragging = previewSize;
            return(previewSize);
        }
Пример #47
0
 internal static void OpenWindow(Rect rect)
 {
     PopupWindow.Show(rect, new AlignWindow());
     PAlignCenter.Start();
 }
Пример #48
0
		public HashSet<Room> roomGenerator  () {
			var watch = System.Diagnostics.Stopwatch.StartNew();
			var roomCenters = new HashSet<Vector3>();

			var rs = new List<Vector3>(requiredSpaces);
			
			
			totalPoints = new HashSet<Vector3>();
			for (int i = 0; i < width;i++){
				for (int j = 0; j < width;j++){
					for (int k = 0; k < height;k++){
						totalPoints.Add(new Vector3(i,j,k));
					}
				}
			}
			graph = EdgeMap.constructEdgemapFromPoints(totalPoints);
			var rects = new List<Rect>();
			
			int failsafe = 0;
			int roomCount = 0;
			while (roomCount< numberOfRooms || requiredSpaces.Count < 0){
				failsafe ++;
				if (failsafe > 100) {
					Debug.Log("overflow");
					break;
				}
				
				var v = new Vector3(random.Next(0,width),random.Next(0,width),0);
				Vector3 size = new Vector3(random.Next(minRoomLength,maxRoomLength),random.Next(minRoomLength,maxRoomLength),0);
				if (requiredSpaces.Count > 0){
					size = requiredSpaces[0];
				}
				
				
				
				var rect = new Rect(v,size);
				
				if (generateRoomHelper(ref roomCount,roomCenters,rect,rects,v)){
					requiredSpaces.Remove(size);

					int childCount = random.Next(minRoomChildCount,maxRoomChildCount);
					Rect current;
					for (int q = 0; q < childCount;q++){
						if (generateHypotheticalChildRoom(out current,rect,rects)){
							generateRoomHelper(ref roomCount,roomCenters,current,rects,rect.min);
						}
					}
				}				
			}
		

			var edges =(getDelaunayFromPoints(roomCenters)).ToList();
			var totalEdges = new HashSet<Edge>(edges);
			edges=  new HashSet<Edge>(new Prims().execute(edges)).ToList();
			foreach (Edge e in totalEdges){
				if (random.NextDouble() < .15 && ! edges.Contains(e)){
					edges.Add(e);
				}
			}
			var g = new EdgeMap(edges);

			foreach (Edge e in edges){	
				var points = paintRoomAroundLine(e,1,2);
				if (points.Count > 0){
					var r = new Room(points);
					r.tag = new BoundedSpaceTags(FaceTypes.HALLWAY);
					assignPointToRoom(r,false);
				}	
			}	
			
			var output = new HashSet<Room>(pointDict.Values);
			foreach (Room r in output){
				var r2 = Room.splitDisconnectedRoom(r);
				foreach (Room r3 in r2) assignPointToRoom(r3,true);
			}
			output.Clear();
			output.UnionWith(pointDict.Values);
			
			new RecursiveBackTrace().recursiveBackTrace(pointDict);

			return output;
		}
 public float ResizeHandle(Rect windowPosition, float minSize, float minRemainingSize, float resizerHeight)
 {
     return(ResizeHandle(windowPosition, minSize, minRemainingSize, resizerHeight, new Rect()));
 }
Пример #50
0
        static IEnumerable <Rect> ProcessTextLines(TextView textView, VisualLine visualLine, int segmentStartVC, int segmentEndVC)
        {
            TextLine lastTextLine = visualLine.TextLines.Last();
            Vector   scrollOffset = textView.ScrollOffset;

            for (int i = 0; i < visualLine.TextLines.Count; i++)
            {
                TextLine line           = visualLine.TextLines[i];
                double   y              = visualLine.GetTextLineVisualYPosition(line, VisualYPosition.LineTop);
                int      visualStartCol = visualLine.GetTextLineVisualStartColumn(line);
                int      visualEndCol   = visualStartCol + line.Length;
                if (line != lastTextLine)
                {
                    visualEndCol -= line.TrailingWhitespaceLength;
                }

                if (segmentEndVC < visualStartCol)
                {
                    break;
                }
                if (lastTextLine != line && segmentStartVC > visualEndCol)
                {
                    continue;
                }
                int segmentStartVCInLine = Math.Max(segmentStartVC, visualStartCol);
                int segmentEndVCInLine   = Math.Min(segmentEndVC, visualEndCol);
                y -= scrollOffset.Y;
                if (segmentStartVCInLine == segmentEndVCInLine)
                {
                    // GetTextBounds crashes for length=0, so we'll handle this case with GetDistanceFromCharacterHit
                    // We need to return a rectangle to ensure empty lines are still visible
                    double pos = visualLine.GetTextLineVisualXPosition(line, segmentStartVCInLine);
                    pos -= scrollOffset.X;
                    // The following special cases are necessary to get rid of empty rectangles at the end of a TextLine if "Show Spaces" is active.
                    // If not excluded once, the same rectangle is calculated (and added) twice (since the offset could be mapped to two visual positions; end/start of line), if there is no trailing whitespace.
                    // Skip this TextLine segment, if it is at the end of this line and this line is not the last line of the VisualLine and the selection continues and there is no trailing whitespace.
                    if (segmentEndVCInLine == visualEndCol && i < visualLine.TextLines.Count - 1 && segmentEndVC > segmentEndVCInLine && line.TrailingWhitespaceLength == 0)
                    {
                        continue;
                    }
                    if (segmentStartVCInLine == visualStartCol && i > 0 && segmentStartVC < segmentStartVCInLine && visualLine.TextLines[i - 1].TrailingWhitespaceLength == 0)
                    {
                        continue;
                    }
                    yield return(new Rect(pos, y, 1, line.Height));
                }
                else
                {
                    Rect lastRect = Rect.Empty;
                    if (segmentStartVCInLine <= visualEndCol)
                    {
                        foreach (TextBounds b in line.GetTextBounds(segmentStartVCInLine, segmentEndVCInLine - segmentStartVCInLine))
                        {
                            double left  = b.Rectangle.Left - scrollOffset.X;
                            double right = b.Rectangle.Right - scrollOffset.X;
                            if (!lastRect.IsEmpty)
                            {
                                yield return(lastRect);
                            }
                            // left>right is possible in RTL languages
                            lastRect = new Rect(Math.Min(left, right), y, Math.Abs(right - left), line.Height);
                        }
                    }
                    if (segmentEndVC >= visualLine.VisualLengthWithEndOfLineMarker)
                    {
                        double left            = (segmentStartVC > visualLine.VisualLengthWithEndOfLineMarker ? visualLine.GetTextLineVisualXPosition(lastTextLine, segmentStartVC) : line.Width) - scrollOffset.X;
                        double right           = ((segmentEndVC == int.MaxValue || line != lastTextLine) ? Math.Max(((IScrollInfo)textView).ExtentWidth, ((IScrollInfo)textView).ViewportWidth) : visualLine.GetTextLineVisualXPosition(lastTextLine, segmentEndVC)) - scrollOffset.X;
                        Rect   extendSelection = new Rect(Math.Min(left, right), y, Math.Abs(right - left), line.Height);
                        if (!lastRect.IsEmpty)
                        {
                            if (extendSelection.IntersectsWith(lastRect))
                            {
                                lastRect.Union(extendSelection);
                                yield return(lastRect);
                            }
                            else
                            {
                                yield return(lastRect);

                                yield return(extendSelection);
                            }
                        }
                        else
                        {
                            yield return(extendSelection);
                        }
                    }
                    else
                    {
                        yield return(lastRect);
                    }
                }
            }
        }
Пример #51
0
 /// <summary>
 /// Adds a rectangle to the geometry.
 /// </summary>
 /// <remarks>
 /// This overload will align the coordinates according to
 /// <see cref="AlignToWholePixels"/> or <see cref="AlignToMiddleOfPixels"/>.
 /// Use the <see cref="AddRectangle(double,double,double,double)"/>-overload instead if the coordinates should not be aligned.
 /// </remarks>
 public void AddRectangle(TextView textView, Rect rectangle)
 {
     AddRectangle(PixelSnapHelpers.GetPixelSize(textView), rectangle);
 }
Пример #52
0
    void DisplayMatches()
    {
        Rect rect = fieldRect;


        if (lastMatchKey != script.StringID)
        {
            matchedKeys = new List <string>();
            matchedIDs  = new List <int>();
            for (int i = 0; i < StringIds.Length; i++)
            {
                if (StringIds[i].ToLower().Contains(script.StringID))
                {
                    matchedKeys.Add(StringIds[i]);
                    matchedIDs.Add(i);
                }
            }
            lastMatchKey = script.StringID;
        }

        rect.y += EditorGUIUtility.singleLineHeight + 2;
        if (matchedKeys.Count > 0 && !string.IsNullOrEmpty(script.StringID))
        {
            rect.height = 125;
            EditorGUI.DrawRect(rect, new Color(0, 0, 0, 0.7f));
            lisScroll = GUI.BeginScrollView(rect, lisScroll, new Rect(0, 0, rect.width - 80, EditorGUIUtility.singleLineHeight * matchedKeys.Count), false, true);

            rect.height = EditorGUIUtility.singleLineHeight;
            for (int i = 0; i < matchedKeys.Count; i++)
            {
                Rect r = rect;
                r.x     = 0; r.y = EditorGUIUtility.singleLineHeight * i;
                r.width = 140;
                GUI.Label(r, matchedKeys[i]);
                r.x    += 142;
                r.width = 75;
                if (GUI.Button(r, new GUIContent("Set String", StringTexts[matchedIDs[i]]), EditorStyles.toolbarButton))
                {
                    EditorGUI.FocusTextInControl("");
                    GUI.FocusControl("");
                    script.StringID = matchedKeys[i];
                    showMatches     = false;
                    EditorUtility.SetDirty(target);
                }
                r.x += 76;

                if (GUI.Button(r, new GUIContent("Set ID", StringTexts[matchedIDs[i]]), EditorStyles.toolbarButton))
                {
                    EditorGUI.FocusTextInControl("");
                    GUI.FocusControl("");
                    script._arrayID         = matchedIDs[i];
                    script.StringID         = matchedKeys[i];
                    script.ManuallyAssignId = false;
                    showMatches             = false;
                    EditorUtility.SetDirty(target);
                }
                rect.y += EditorGUIUtility.singleLineHeight;
            }
            GUI.EndScrollView();
        }
        else
        {
            GUI.Box(rect, "No matches");
        }
    }
Пример #53
0
 public override bool ClickInControl()
 {
     if (!Enabled)
     {
         return(false);
     }
     _mouseInside = false;
     if (InputManager.Instance.MouseState.LeftButton == ButtonState.Pressed)
     {
         if (_mouseButtonPressed)
         {
             return(_thisPressed);
         }
         if (Rect.Contains(InputManager.Instance.GetMousePositionToVector2()))
         {
             if (!_isPressed)
             {
                 _thisPressed = true;
                 _isPressed   = true;
                 if (OnPressed != null)
                 {
                     OnPressed();
                 }
             }
             _mouseInside = true;
         }
         else
         {
             _mouseButtonPressed = true;
         }
     }
     else
     {
         _mouseButtonPressed = false;
         if (_thisPressed)
         {
             _isPressed   = false;
             _thisPressed = false;
             if (Rect.Contains(InputManager.Instance.GetMousePositionToVector2()))
             {
                 if (HoldTimeBeforeNext)
                 {
                     double newSubtract = DateTime.Now.Subtract(new DateTime(2010, 1, 1)).TotalMilliseconds;
                     if (Math.Abs(newSubtract - _lastPressed) > 300)
                     {
                         if (OnReleased != null)
                         {
                             OnReleased();
                         }
                         if (OnClicked != null)
                         {
                             OnClicked();
                         }
                         _lastPressed = newSubtract;
                     }
                 }
                 else
                 {
                     if (OnReleased != null)
                     {
                         OnReleased();
                     }
                     if (OnClicked != null)
                     {
                         OnClicked();
                     }
                 }
                 _mouseInside = true;
             }
         }
         else
         {
             _isPressed = false;
         }
     }
     return(_mouseInside);
 }
        protected virtual void DrawOverlay(Flowchart flowchart)
        {
            GUILayout.Space(8);

            GUILayout.BeginHorizontal();

            GUILayout.Space(8);

            if (GUILayout.Button(new GUIContent(addTexture, "Add a new block")))
            {
                Vector2 newNodePosition = new Vector2(50 - flowchart.scrollPos.x,
                                                      50 - flowchart.scrollPos.y);
                CreateBlock(flowchart, newNodePosition);
            }

            GUILayout.Space(8);

            flowchart.zoom = GUILayout.HorizontalSlider(flowchart.zoom, minZoomValue, maxZoomValue, GUILayout.Width(100));

            GUILayout.FlexibleSpace();

            GUILayout.BeginVertical();
            GUILayout.Label(flowchart.name, EditorStyles.whiteBoldLabel);
            if (flowchart.description.Length > 0)
            {
                GUILayout.Label(flowchart.description, EditorStyles.helpBox);
            }
            GUILayout.EndVertical();

            GUILayout.EndHorizontal();

            GUILayout.FlexibleSpace();

            GUILayout.BeginHorizontal();

            GUILayout.BeginVertical(GUILayout.Width(440));

            GUILayout.FlexibleSpace();

            flowchart.variablesScrollPos = GUILayout.BeginScrollView(flowchart.variablesScrollPos, GUILayout.MaxHeight(position.height * 0.75f));

            GUILayout.FlexibleSpace();

            GUILayout.Space(8);

            FlowchartEditor flowchartEditor = Editor.CreateEditor(flowchart) as FlowchartEditor;

            flowchartEditor.DrawVariablesGUI();
            DestroyImmediate(flowchartEditor);

            Rect variableWindowRect = GUILayoutUtility.GetLastRect();

            if (flowchart.variablesExpanded &&
                flowchart.variables.Count > 0)
            {
                variableWindowRect.y      -= 20;
                variableWindowRect.height += 20;
            }
            if (Event.current.type == EventType.Repaint)
            {
                mouseOverVariables = variableWindowRect.Contains(Event.current.mousePosition);
            }

            GUILayout.EndScrollView();

            GUILayout.EndVertical();

            GUILayout.FlexibleSpace();

            GUILayout.EndHorizontal();
        }
Пример #55
0
        public static void Canvas(int controlId, Rect rect, ref Vector2 cameraPosition, ref float zoom, float[] zoomLevels = null)
        {
            zoomLevels = zoomLevels ?? kZoomScrollLevels;
            CanvasData canvasData;
            if (!s_CanvasDatas.TryGetValue(controlId, out canvasData))
            {
                canvasData = new CanvasData { cameraPositionTarget = cameraPosition, zoomTarget = zoom };
                s_CanvasDatas[controlId] = canvasData;
            }

            var evt = Event.current;
            switch (evt.GetTypeForControl(controlId))
            {
                case EventType.MouseDown:
                    if (evt.button == 2 && rect.Contains(evt.mousePosition))
                    {
                        EditorGUIUtility.hotControl = controlId;
                        EditorGUIUtility.keyboardControl = 0;
                        canvasData.panning = true;
                        canvasData.zooming = false;
                        evt.Use();
                    }
                    break;
                case EventType.MouseDrag:
                    if (evt.button == 2 && EditorGUIUtility.hotControl == controlId)
                    {
                        cameraPosition += evt.delta;
                        evt.Use();
                    }
                    break;
                case EventType.MouseUp:
                    if (evt.button == 2 && EditorGUIUtility.hotControl == controlId)
                    {
                        EditorGUIUtility.hotControl = 0;
                        canvasData.panning = false;
                        canvasData.zooming = false;
                        evt.Use();
                    }
                    break;
                case EventType.ScrollWheel:
                    {
                        canvasData.zooming = true;
                        var oldZoomTarget = canvasData.zoomTarget;
                        canvasData.zoomTarget = IncrementZoomLevel(canvasData.zoomTarget, evt.delta.y > 0 ? -1 : 1, zoomLevels);

                        if (!Mathf.Approximately(canvasData.zoomTarget, oldZoomTarget))
                        {
                            var ratio = canvasData.zoomTarget / oldZoomTarget;
                            var mousePositionRectSpace = evt.mousePosition - rect.position;
                            var mousePositionCanvasSpace = mousePositionRectSpace - canvasData.cameraPositionTarget;
                            canvasData.cameraPositionTarget += mousePositionCanvasSpace * (1 - ratio);
                        }
                        evt.Use();
                        break;
                    }
                case EventType.Repaint:
                    {
                        DrawGrid(rect, cameraPosition, zoom);
                        break;
                    }
            }

            if (canvasData.zooming)
            {
                if (Mathf.Abs(canvasData.zoomTarget - zoom) < 0.0001f)
                {
                    zoom = canvasData.zoomTarget;
                    cameraPosition = canvasData.cameraPositionTarget;
                    canvasData.zooming = false;
                }
                else
                {
                    var deltaTime = Mathf.Min(Time.realtimeSinceStartup - canvasData.lastUpdateTime, 0.1f);
                    zoom = Mathf.Lerp(zoom, canvasData.zoomTarget, deltaTime * kLerpSpeed);
                    cameraPosition = Vector2.Lerp(cameraPosition, canvasData.cameraPositionTarget, deltaTime * kLerpSpeed);
                }
            }
            else
            {
                canvasData.zoomTarget = zoom;
                canvasData.cameraPositionTarget = cameraPosition;
            }

            s_CanvasDatas[controlId] = canvasData;
        }
Пример #56
0
        public static Rect GetBorder(this Rect r, RectBorder border, int size, bool showResizeCursor = false)
        {
            Rect retRect = r;

            // Dimensions
            if (border == RectBorder.Left || border == RectBorder.Right)
            {
                retRect.height = r.height - size * 2;
            }
            else
            {
                retRect.height = size;
            }

            if (border == RectBorder.Top || border == RectBorder.Bottom)
            {
                retRect.width = r.width - size * 2;
            }
            else
            {
                retRect.width = size;
            }

            // Position
            if (border == RectBorder.Left || border == RectBorder.Center || border == RectBorder.Right)
            {
                retRect.y += size;
            }
            if (border == RectBorder.BottomLeft || border == RectBorder.Bottom || border == RectBorder.BottomRight)
            {
                retRect.y += r.height - size;
            }

            if (border == RectBorder.Top || border == RectBorder.Center || border == RectBorder.Bottom)
            {
                retRect.x += size;
            }
            if (border == RectBorder.TopRight || border == RectBorder.Right || border == RectBorder.BottomRight)
            {
                retRect.x += r.width - size;
            }


            if (showResizeCursor)
            {
                MouseCursor cursor;

                if (border == RectBorder.Top || border == RectBorder.Bottom)
                {
                    cursor = MouseCursor.ResizeVertical;
                }
                else if (border == RectBorder.Left || border == RectBorder.Right)
                {
                    cursor = MouseCursor.ResizeHorizontal;
                }
                else if (border == RectBorder.TopLeft || border == RectBorder.BottomRight)
                {
                    cursor = MouseCursor.ResizeUpLeft;
                }
                else if (border == RectBorder.BottomLeft || border == RectBorder.TopRight)
                {
                    cursor = MouseCursor.ResizeUpRight;
                }
                else
                {
                    cursor = MouseCursor.MoveArrow;
                }

                SF_GUI.AssignCursor(retRect, cursor);
            }

            return(retRect);
        }
Пример #57
0
 public static Rect ScaleSizeBy(this Rect rect, float scale)
 {
     return(rect.ScaleSizeBy(scale, rect.center));
 }
Пример #58
0
 public static Rect Pad(this Rect r, int pixels)
 {
     return(r.Margin(-pixels));
 }
        protected virtual void DrawFlowchartView(Flowchart flowchart)
        {
            Block[] blocks = flowchart.GetComponents <Block>();

            foreach (Block block in blocks)
            {
                flowchart.scrollViewRect.xMin = Mathf.Min(flowchart.scrollViewRect.xMin, block.nodeRect.xMin - 400);
                flowchart.scrollViewRect.xMax = Mathf.Max(flowchart.scrollViewRect.xMax, block.nodeRect.xMax + 400);
                flowchart.scrollViewRect.yMin = Mathf.Min(flowchart.scrollViewRect.yMin, block.nodeRect.yMin - 400);
                flowchart.scrollViewRect.yMax = Mathf.Max(flowchart.scrollViewRect.yMax, block.nodeRect.yMax + 400);
            }

            // Calc rect for script view
            Rect scriptViewRect = new Rect(0, 0, this.position.width / flowchart.zoom, this.position.height / flowchart.zoom);

            EditorZoomArea.Begin(flowchart.zoom, scriptViewRect);

            DrawGrid(flowchart);

            GLDraw.BeginGroup(scriptViewRect);

            if (Event.current.button == 0 &&
                Event.current.type == EventType.MouseDown &&
                !mouseOverVariables)
            {
                flowchart.selectedBlock = null;
                if (!EditorGUI.actionKey)
                {
                    flowchart.ClearSelectedCommands();
                }
                Selection.activeGameObject = flowchart.gameObject;
            }

            // The center of the Flowchart depends on the block positions and window dimensions, so we calculate it
            // here in the FlowchartWindow class and store it on the Flowchart object for use later.
            CalcFlowchartCenter(flowchart, blocks);

            // Draw connections
            foreach (Block block in blocks)
            {
                DrawConnections(flowchart, block, false);
            }
            foreach (Block block in blocks)
            {
                DrawConnections(flowchart, block, true);
            }

            GUIStyle windowStyle = new GUIStyle();

            windowStyle.stretchHeight = true;

            BeginWindows();

            windowBlockMap.Clear();
            for (int i = 0; i < blocks.Length; ++i)
            {
                Block block = blocks[i];

                float nodeWidthA = nodeStyle.CalcSize(new GUIContent(block.blockName)).x + 10;
                float nodeWidthB = 0f;
                if (block.eventHandler != null)
                {
                    nodeWidthB = nodeStyle.CalcSize(new GUIContent(block.eventHandler.GetSummary())).x + 10;
                }

                block.nodeRect.width  = Mathf.Max(Mathf.Max(nodeWidthA, nodeWidthB), 120);
                block.nodeRect.height = 40;

                if (Event.current.button == 0)
                {
                    if (Event.current.type == EventType.MouseDrag && dragWindowId == i)
                    {
                        block.nodeRect.x += Event.current.delta.x;
                        block.nodeRect.y += Event.current.delta.y;

                        forceRepaintCount = 6;
                    }
                    else if (Event.current.type == EventType.MouseUp &&
                             dragWindowId == i)
                    {
                        Vector2 newPos = new Vector2(block.nodeRect.x, block.nodeRect.y);

                        block.nodeRect.x = startDragPosition.x;
                        block.nodeRect.y = startDragPosition.y;

                        Undo.RecordObject(block, "Node Position");

                        block.nodeRect.x = newPos.x;
                        block.nodeRect.y = newPos.y;

                        dragWindowId      = -1;
                        forceRepaintCount = 6;
                    }
                }

                Rect windowRect = new Rect(block.nodeRect);
                windowRect.x += flowchart.scrollPos.x;
                windowRect.y += flowchart.scrollPos.y;

                GUILayout.Window(i, windowRect, DrawWindow, "", windowStyle);

                GUI.backgroundColor = Color.white;

                windowBlockMap.Add(block);
            }

            EndWindows();

            // Draw Event Handler labels
            foreach (Block block in blocks)
            {
                if (block.eventHandler != null)
                {
                    string handlerLabel            = "";
                    EventHandlerInfoAttribute info = EventHandlerEditor.GetEventHandlerInfo(block.eventHandler.GetType());
                    if (info != null)
                    {
                        handlerLabel = "<" + info.EventHandlerName + "> ";
                    }

                    GUIStyle handlerStyle = new GUIStyle(EditorStyles.whiteLabel);
                    handlerStyle.wordWrap      = true;
                    handlerStyle.margin.top    = 0;
                    handlerStyle.margin.bottom = 0;
                    handlerStyle.alignment     = TextAnchor.MiddleCenter;

                    Rect rect = new Rect(block.nodeRect);
                    rect.height = handlerStyle.CalcHeight(new GUIContent(handlerLabel), block.nodeRect.width);
                    rect.x     += flowchart.scrollPos.x;
                    rect.y     += flowchart.scrollPos.y - rect.height;

                    GUI.Label(rect, handlerLabel, handlerStyle);
                }
            }


            // Draw play icons beside all executing blocks
            if (Application.isPlaying)
            {
                foreach (Block b in blocks)
                {
                    if (b.IsExecuting())
                    {
                        b.executingIconTimer = Time.realtimeSinceStartup + Block.executingIconFadeTime;
                        b.activeCommand.executingIconTimer = Time.realtimeSinceStartup + Block.executingIconFadeTime;
                        forceRepaintCount = 6;
                    }

                    if (b.executingIconTimer > Time.realtimeSinceStartup)
                    {
                        Rect rect = new Rect(b.nodeRect);

                        rect.x     += flowchart.scrollPos.x - 37;
                        rect.y     += flowchart.scrollPos.y + 3;
                        rect.width  = 34;
                        rect.height = 34;

                        if (!b.IsExecuting())
                        {
                            float alpha = (b.executingIconTimer - Time.realtimeSinceStartup) / Block.executingIconFadeTime;
                            alpha     = Mathf.Clamp01(alpha);
                            GUI.color = new Color(1f, 1f, 1f, alpha);
                        }

                        if (GUI.Button(rect, FungusEditorResources.texPlayBig as Texture, new GUIStyle()))
                        {
                            SelectBlock(flowchart, b);
                        }

                        GUI.color = Color.white;
                    }
                }
            }

            PanAndZoom(flowchart);

            GLDraw.EndGroup();

            EditorZoomArea.End();
        }
Пример #60
-10
		public AreaInfo(Rect theRect, int thePriority, string theName)
		{
			itsRect = theRect;
			itsPriority = thePriority;
			itsColor = new Color(Random.value,Random.value,Random.value);
			itsName = theName;
		}