Inheritance: MonoBehaviour
    private void OnSceneGUI()
    {
        curve = target as BezierCurve;

        handleTransform = curve.transform;
        handleRotation = Tools.pivotRotation == PivotRotation.Local ? handleTransform.rotation : Quaternion.identity;

        Vector3 p0 = ShowPoint(0);
        Vector3 p1 = ShowPoint(1);
        Vector3 p2 = ShowPoint(2);

        Handles.color = Color.gray;

        // Draws straight lines between p0->p1 and from p1->p2
        Handles.DrawLine(p0, p1);
        Handles.DrawLine(p1, p2);

        Handles.color = Color.white;
        Vector3 lineStart = curve.GetPoint(0f);

        Handles.color = Color.green;
        Handles.DrawLine(lineStart, lineStart + curve.GetVelocity(0f));

        for (int i = 1; i <= lineSteps; i++)
        {
            Handles.color = Color.white;
            Vector3 lineEnd = curve.GetPoint(i / (float)lineSteps);
            Handles.DrawLine(lineStart, lineEnd);
            lineStart = lineEnd;
        }
    }
	void OnSceneGUI()
	{
		_curve = target as BezierCurve;
		_curveT = _curve.transform;
		_curveR = Tools.pivotRotation == PivotRotation.Local ? _curveT.rotation : Quaternion.identity;

		Vector3 p0 = ShowPoint(0);
		Vector3 p1 = ShowPoint(1);
		Vector3 p2 = ShowPoint(2);
		Vector3 p3 = ShowPoint(3);

		// Show original lines
		Handles.color = Color.grey;
		Handles.DrawLine(p0, p1);
		Handles.DrawLine(p1, p2);
		Handles.DrawLine(p2, p3);

		// Show curve
		Handles.DrawBezier(p0, p3, p1, p2, Color.white, null, 2f);

		// Show velocity
		if(_curve.showVelocity)
		{
			Vector3 lineStart = _curve.GetPoint(0f);
			Handles.color = Color.green;
			Handles.DrawLine(lineStart, lineStart + _curve.GetDirection(0f));
		
			for (int i = 1; i <= _curve.numIterations; i++) {
				Vector3 lineEnd = _curve.GetPoint(i / (float)_curve.numIterations);
				Handles.DrawLine(lineEnd, lineEnd + _curve.GetDirection(i / (float)_curve.numIterations));
			}
		}
	}
Example #3
0
    private void OnSceneGUI()
    {
        curve = target as BezierCurve;
        handleTransform = curve.transform;
        handleRotation = Tools.pivotRotation == PivotRotation.Local ?
            handleTransform.rotation : Quaternion.identity;

        Vector3 p0 = ShowPoint(0);
        Vector3 p1 = ShowPoint(1);
        Vector3 p2 = ShowPoint(2);

        Handles.color = Color.gray;
        Handles.DrawLine(p0, p1);
        Handles.DrawLine(p1, p2);

        Handles.color = Color.white;

        Vector3 lineStart = curve.GetPoint(0f);
        Handles.color = Color.green;
        Handles.DrawLine(lineStart, lineStart + curve.GetVelocity(0f));
        for(int i = 0; i <= LINESTEPS; i++)
        {
            Vector3 lineEnd = curve.GetPoint(i / (float)LINESTEPS);
            Handles.color = Color.white;
            Handles.DrawLine(lineStart, lineEnd);
            Handles.color = Color.green;
            Handles.DrawLine(lineEnd, lineEnd + curve.GetVelocity(i / (float) LINESTEPS));
            lineStart = lineEnd;
        }
    }
    private void OnSceneGUI()
    {
        curve = target as BezierCurve;

        handleTransform = curve.transform;
        handleRotation = handleTransform.rotation;

        Vector3 p0 = ShowPoint (0);
        Vector3 p1 = ShowPoint (1);
        Vector3 p2 = ShowPoint (2);
        Vector3 p3 = ShowPoint (3);

        Handles.color = Color.gray;
        Handles.DrawLine(p0, p1);
        Handles.DrawLine(p2, p3);

        Handles.DrawBezier (p0, p3, p1, p2, Color.white, null, 2f);
        //		Handles.color = Color.white;
        //		Vector3 lineStart = curve.GetPoint (0f);
        //
        //		for (int i = 1; i <= lineSteps; i++) {
        //			Vector3 lineEnd = curve.GetPoint((float) i/lineSteps);
        //			Handles.DrawLine(lineStart, lineEnd);
        //			lineStart = lineEnd;
        //		}
    }
Example #5
0
 /**
  * curve[i + 1].begin_point.transform = curve[i].end_point.transform
  */
 public static void CopyEndPoints(BezierCurve[] curves)
 {
     for( int i = 0; i < curves.Length - 1; i++ )
     {
         CopyEndPoint(curves[i], curves[i + 1]);
     }
 }
Example #6
0
 /**
  * curve[i].end_point.transform = Lerp(end_point, begin_point, 0.5f)
  * curve[i + 1].begin_point.transform = Lerp(end_point, begin_point, 0.5f)
  */
 public static void CloseGaps(BezierCurve[] curves)
 {
     for( int i = 0; i < curves.Length - 1; i++ )
     {
         CloseGap(curves[i], curves[i + 1]);
     }
 }
 public static void DrawOtherPoints(BezierCurve curve, BezierPoint caller)
 {
     foreach(BezierPoint p in curve.GetAnchorPoints())
     {
         if(p != caller) DrawPointSceneGUI(p);
     }
 }
    public override void CreateControlPoints( BezierCurve previous )
    {
        base.CreateControlPoints( previous );

        m_control = new GameObject("ControlPoint").transform;
        m_control.parent = transform;
        m_control.position = m_begin.position + new Vector3(10, 0, 5);
    }
Example #9
0
	void OnEnable()
	{
		curve = (BezierCurve)target;
		
		resolutionProp = serializedObject.FindProperty("resolution");
		closeProp = serializedObject.FindProperty("_close");
		pointsProp = serializedObject.FindProperty("points");
		colorProp = serializedObject.FindProperty("drawColor");
	}
Example #10
0
 /**
  * curve[i].end_point.transform = Lerp(end_point, begin_point, 0.5f)
  * curve[i + 1].begin_point.transform = Lerp(end_point, begin_point, 0.5f)
  */
 public static void CloseGap(BezierCurve src, BezierCurve dst)
 {
     Vector3 p = Vector3.Lerp(src.EndPoint.position, dst.BeginPoint.position, 0.5f);
     Quaternion r = Quaternion.Slerp(src.EndPoint.rotation, dst.BeginPoint.rotation, 0.5f);
     src.EndPoint.position = p;
     src.EndPoint.rotation = r;
     dst.BeginPoint.position = p;
     dst.BeginPoint.rotation = r;
 }
Example #11
0
	public BezierCurve GetCurve(){
		BezierCurve c = new BezierCurve();
		foreach (Node n in Nodes){
			c.Add(new BezierNode(Position + n.Point, Position + n.LeftHandle, Position + n.RightHandle));
		}
		if (Closed){
			c.Close();
		}
		return c;
	}	
Example #12
0
    void Start()
    {
        foreach (var player in FindObjectsOfType<PlayerController>())
        {
            if (!player.isLocalPlayer) continue;
            bezier_curve_ = player.gameObject.GetComponentInChildren<BezierCurve>();
        }

        old_position_ = gameObject.transform.position;
    }
	IEnumerator DoJoust() {
		float t = 0;
		if (!path) {
			path = GameObject.Find ("OpponentCurve").GetComponent<BezierCurve> ();
		}
		while (MasterGame.instance.currentHandStage == MasterGame.handStage.Joust) {
			t += tSpeed * Time.deltaTime;
			t = Mathf.Clamp (t, 0, 0.99f);
			Vector2 p = path.GetPointAt (t);
			transform.position = p;
			yield return null;
		}
	}
Example #14
0
    /**
     * Start navigating a given curve
     */
    public void Navigate(BezierCurve[] curves)
    {
        if( curves.Length < 1 )
        {
            Debug.LogWarning("Curves array is empty");
            return;
        }

        m_curves = curves;
        MoveToCurve( 0 );
        ExecuteCallback( OnStart );
        m_done = false;
    }
Example #15
0
    public static void DrawCurve(BezierCurve curve)
    {
        var old = Handles.color;

        for (int i = 0; i < curve.EditorDisplayResolution; i++)
        {
            float t = (float)i / (float)curve.EditorDisplayResolution;
            float t1 = (float)(i + 1) / (float)curve.EditorDisplayResolution;

            Handles.color = CurveColour;
            Handles.DrawLine(curve.GetPoint(t), curve.GetPoint(t1));
        }

        Handles.color = HandleColour;

        var newpoint0 = Handles.FreeMoveHandle(curve.p0, Quaternion.identity, 1, Vector3.zero, Handles.CircleCap);
        if (newpoint0 != curve.p0)
        {
            Undo.RecordObject(curve, "bezier handle move");
            curve.Point1.position += (newpoint0 - curve.p0);
            curve.Point0.position = newpoint0;
        }

        var newpoint1 = Handles.FreeMoveHandle(curve.p1, Quaternion.identity, 1, Vector3.zero, Handles.CircleCap);
        if (newpoint1 != curve.p1)
        {
            Undo.RecordObject(curve, "bezier handle move");
            curve.Point1.position = newpoint1;
        }

        var newpoint2 = Handles.FreeMoveHandle(curve.p2, Quaternion.identity, 1, Vector3.zero, Handles.CircleCap);
        if (newpoint2 != curve.p2)
        {
            Undo.RecordObject(curve, "bezier handle move");
            curve.Point2.position = newpoint2;
        }

        var newpoint3 = Handles.FreeMoveHandle(curve.p3, Quaternion.identity, 1, Vector3.zero, Handles.CircleCap);
        if (newpoint3 != curve.p3)
        {
            Undo.RecordObject(curve, "bezier handle move");
            curve.Point2.position += (newpoint3 - curve.p3);
            curve.Point3.position = newpoint3;
        }

        Handles.color = HandleLineColour;
        Handles.DrawLine(curve.p0, curve.p1);
        Handles.DrawLine(curve.p2, curve.p3);

        Handles.color = old;
    }
        private void OnSceneGUI()
        {
            curve = target as BezierCurve;
            handleTransform = curve.transform;
            handleRotation = Tools.pivotRotation == PivotRotation.Local ?
                handleTransform.rotation : Quaternion.identity;

            Vector3 p0 = ShowPoint(0);
            Vector3 p1 = ShowPoint(1);
            Vector3 p2 = ShowPoint(2);

            Handles.color = Color.white;
            Handles.DrawLine(p0, p1);
            Handles.DrawLine(p1, p2);
        }
Example #17
0
    /**
     * It creates the game objects used to control the bezier.
     */
    public virtual void CreateControlPoints( BezierCurve previous )
    {
        m_begin = new GameObject("BeginPoint").transform;
        m_end = new GameObject("EndPoint").transform;

        m_begin.parent = transform;
        m_end.parent = transform;

        if( previous )
        {
            m_begin.position = previous.EndPoint.position;
            m_begin.rotation = previous.EndPoint.rotation;
        }

        m_end.position = m_begin.position + new Vector3(0, 0, 10);
        m_end.rotation = m_begin.rotation;
    }
Example #18
0
    private void OnSceneGUI() {
        _curve = target as BezierCurve;
        _handleTransform = _curve.transform;
        _handleRotation = Tools.pivotRotation == PivotRotation.Local ?
            _handleTransform.rotation : Quaternion.identity;

        Vector3 p0 = ShowPoint(0);
        Vector3 p1 = ShowPoint(1);
        Vector3 p2 = ShowPoint(2);
        Vector3 p3 = ShowPoint(3);

        Handles.color = Color.gray;
        Handles.DrawLine(p0, p1);
        Handles.DrawLine(p2, p3);

        ShowDirections();
        Handles.DrawBezier(p0, p3, p1, p2, Color.white, null, 2f);
    }
Example #19
0
 public static bool findpoint(SKPoint MousePoint, ref BezierCurve curve)
 {
     foreach (BezierPiece piece in curve)
     {
         if (IsInsidePoint(MousePoint, piece.touch, 30))
         {
             isTouch  = true;
             selected = piece;
             return(true);
         }
         if (IsInsidePoint(MousePoint, piece.intersect, 30))
         {
             isTouch  = false;
             selected = piece;
             return(true);
         }
     }
     return(false);
 }
Example #20
0
    //Display the rope with a line render
    private void DisplayRope()
    {
        //this is not actual width, but width use so we can see the ropw
        float ropeWidth = 0.2f;

        lineRenderer.startWidth = ropeWidth;
        lineRenderer.endWidth   = ropeWidth;

        //update the list with rope secctions by approximating the rope with bezier curve
        //a bezier curve needs 4 control points
        Vector3 A = whatTheRopeIsConnectedTo.position;
        Vector3 D = whatIsHangingFromTheRope.position;

        //upper control point
        //to get a little curve at the top than at the bottom
        Vector3 B = A + whatTheRopeIsConnectedTo.up * (-(A - D).magnitude * 0.1f);
        //B=A

        //Lower control point
        Vector3 C = D + whatIsHangingFromTheRope.up * ((A - D).magnitude * 0.5f);

        //get the positions
        BezierCurve.GetBezierCurve(A, B, C, D, allRopeSections);

        //an array wit all rope section positions
        Vector3[] positions = new Vector3[allRopeSections.Count];

        for (int i = 0; i < allRopeSections.Count; i++)
        {
            positions[i] = allRopeSections[i];
        }

        //just add a line between the start ad end position for testing purposes
        //Vector3[] positions = new Vector3[2];

        //position[0] = whatTheRopeIsConnectedTo.position;
        //postions[1] = whatIsHangingFromTheRope.position;

        //add the positions to the line renderer
        lineRenderer.positionCount = positions.Length;

        lineRenderer.SetPositions(positions);
    }
Example #21
0
    //获取速度
    public Vector3 GetVelocity(float t)
    {
        int i;

        if (t >= 1.0f)
        {
            t = 1.0f;
            i = CurvePointCount - 4;
        }
        else
        {
            t  = Mathf.Clamp01(t) * CurveCount;
            i  = (int)t; //取整 判定是第几根曲线
            t -= i;      //取余 判定是当前曲线的百分之多少
            i *= 3;
        }

        return(transform.TransformPoint(BezierCurve.GetFirstDirective(points[i], points[i + 1], points[i + 2], points[i + 3], t)) - transform.position);
    }
Example #22
0
    static bool  IsNearBezier(Vector2 p, BezierPoint point1, BezierPoint point2, float rad)
    {
        if (point1.curve2 != point2.curve1)
        {
            Debug.LogError("Curves Not The Same");
            return(false);
        }

        BezierCurve curve = point1.curve2;

        var r = curve.rect;

        r.x -= rad;

        r.y -= rad;

        r.width += rad * 2;

        r.height += rad * 2;

        if (!r.Contains(p))
        {
            return(false);
        }

        var nearest = NearestPointOnBezier(p, curve, 0.1f, false);

        var sec = point1.curve2.aproxLength / 10;

        if ((nearest - p).sqrMagnitude >= (sec * 3) * (sec * 3))
        {
            return(false);
        }

        nearest = NearestPointOnBezier(p, curve, 0.01f, true);

        if ((nearest - p).sqrMagnitude <= rad * rad)
        {
            return(true);
        }

        return(false);
    }
Example #23
0
    public bool checkAvailablePos(Vector2 pos)
    {
        QTEController qte = FindObjectOfType <QTEController>();

        if (!qte)
        {
            Debug.LogError("ERROR: QTEController not in the scene.");
            return(true);
        }

        foreach (GameObject go in qte.activeQTEs)
        {
            QTEMother qtemom = go.GetComponent <QTEMother>();
            if (qtemom is QTEClick click)
            {
                if (!checkProperDistance(click.transform.position, pos))
                {
                    return(false);
                }
            }

            else if (qtemom is QTETouch touch)
            {
                if (!checkProperDistance(touch.transform.position, pos))
                {
                    return(false);
                }
            }

            else if (qtemom is QTESlider slide)
            {
                BezierCurve curve = qtemom.gameObject.GetComponent <BezierCurve>();
                foreach (Vector2 v2 in curve.positions)
                {
                    if (!checkProperDistance(pos, v2))
                    {
                        return(false);
                    }
                }
            }
        }
        return(true);
    }
Example #24
0
        public BezierTest()
        {
            _points = new[] {
                new Position(10, 10),
                new Position(20, 20),
                new Position(20, 20),
                new Position(30, 10)
            };
            var _points2 = new[] {
                new Position(10, 10),
                new Position(20, 20),
                new Position(20, 20),
                new Position(27, 17),
                new Position(30, 10)
            };

            _curve  = new BezierCurve(_points, -1);
            _curve2 = new BezierCurve(_points2, -1);
        }
Example #25
0
        void UpdateLeapVariables(Vector3 moveDirection)
        {
            if (!initTransit)
            {
                initTransit          = true;
                isRootMovementEnbled = false;
                rootReached          = false;
                sfxPending           = true;
                ikFollowSideReached  = false;
                ikLandSideReached    = false;
                _time             = 0;
                _rootMovementTime = 0;
                _startPosition    = transform.position;
                _endPosition      = targetPosition + (targetPoint.climbPosition == ClimbPosition.climbing ? climbRootOffset : (hangRootOffset + modelTransform.forward * 0.15f));

                bool isJumpVertical = (Mathf.Abs(moveDirection.y) > 0.1f);
                currentCurve = isJumpVertical ? leapCurveVertical : leapCurveHorizontal;
                currentCurve.transform.rotation = currentPoint.transform.rotation;

                if (isJumpVertical)
                {
                    if (!(moveDirection.y > 0))
                    {
                        // flip movement curve
                        currentCurve.transform.eulerAngles = new Vector3(180, 180);
                    }
                }
                else
                {
                    if (!(moveDirection.x > 0))
                    {
                        // flip movement curve
                        currentCurve.transform.eulerAngles = new Vector3(0, -180);
                    }
                }

                BezierPoint[] trailPoints = currentCurve.GetAnchorPoints();
                trailPoints[0].transform.position = _startPosition;
                trailPoints[trailPoints.Length - 1].transform.position = _endPosition;

                InitIKDirect(inputDirection);
            }
        }
    private void GetCurveAndSetPointAreas()
    {
        curveComp = newCurve.GetComponent <BezierCurve>();
        PointArea[] areas = { PointArea.Left, PointArea.Up, PointArea.Right };

        int index = Random.Range(0, 2); // Left or Up

        initPointArea = areas[index];

        if (initPointArea == PointArea.Up)
        {
            index = Random.Range(0, 2) * 2; //Left Or Right
        }
        else if (initPointArea == PointArea.Left)
        {
            index = Random.Range(1, 3); // Up or Right
        }
        finalPointArea = areas[index];
    }
Example #27
0
    // Called when user clicks GUI Add Gizmo
    public void AddPoint(bool atStart)
    {
        BezierCurve curve = GameObject.Instantiate(curvePrefab).GetComponent <BezierCurve>();

        int numCurves = curves.Count;

        if (numCurves > 0)
        {
            if (atStart)
            {
                BezierCurve next   = curves[0];
                Vector3     anchor = next.GetStartPosition();
                curve.Init(NumSubDivisions, anchor, atStart, transform);

                next.SetPrev(curve);
                curve.SetNext(next);
            }
            else
            {
                BezierCurve prev   = curves[numCurves - 1];
                Vector3     anchor = prev.GetEndPosition();
                curve.Init(NumSubDivisions, anchor, atStart, transform);

                prev.SetNext(curve);
                curve.SetPrev(prev);
            }
        }
        else
        {
            curve.Init(NumSubDivisions, Vector3.zero, atStart, transform);
        }

        if (atStart)
        {
            curves.Insert(0, curve);
        }
        else
        {
            curves.Add(curve);
        }

        splineLength += curve.GetLength();
    }
Example #28
0
    // Update is called once per frame
    void FixedUpdate()
    {
        character.position = BezierCurve.GetPoint(percentage, pointsVector);
        if (Input.GetKey(KeyCode.D))
        {
            if (percentage < 1 && percentageCanChange == true)
            {
                percentage += Time.deltaTime * speed;
            }
        }

        if (Input.GetKey(KeyCode.A))
        {
            if (percentage > 0 && percentageCanChange == true)
            {
                percentage -= Time.deltaTime * speed;
            }
        }
    }
    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();

        BezierCurve curve = target as BezierCurve;

        GUILayout.BeginHorizontal();

        if (GUILayout.Button("Draw the line"))
        {
            curve.DrawAndRemoveLineInWorld(true);
        }
        if (GUILayout.Button("Remove the line"))
        {
            curve.DrawAndRemoveLineInWorld(false);
        }

        GUILayout.EndHorizontal();
    }
Example #30
0
        void HandleMount()
        {
            if (!_initTransit)
            {
                _initTransit = true;

                _ikFollowSideReached = false;
                _ikLandSideReached   = false;
                _interpolT           = 0;
                _interpolStart       = transform.position;
                _interpolTarget      = _targetPosition + rootOffset;

                _curCurve = _mountCurve;
                _curCurve.transform.rotation = _targetPoint.transform.rotation;
                var points = _curCurve.GetAnchorPoints();
                points[0].transform.position = _interpolStart;
                points[points.Length - 1].transform.position = _interpolTarget;
            }

            if (enableRootMovement)
            {
                _interpolT += Time.deltaTime * 2;
            }

            if (_interpolT >= 1)
            {
                _interpolT         = 1;
                _waitToStartClimb  = false;
                _lockInput         = false;
                _initTransit       = false;
                _ikLandSideReached = false;
                _climbState        = _targetState;
            }

            var targetPos = _curCurve.GetPointAt(_interpolT);

            Debug.DrawLine(transform.position, targetPos, Color.gray);
            Debug.DrawLine(transform.position, _interpolTarget, Color.black);
            transform.position = targetPos;

            HandleWeightAll(_interpolT, mountCurve);
            HandleRotation();
        }
Example #31
0
 private void Start()
 {
     PointS  = transform.GetChild(0);
     PointE  = transform.GetChild(1);
     HandleS = PointS.transform.GetChild(0);
     HandleE = PointE.transform.GetChild(0);
     if (GetComponent <BezierCurve>())
     {
         bZ = GetComponent <BezierCurve>();
     }
     else
     {
         bZ = gameObject.AddComponent <BezierCurve>();
     }
     sBZPoint         = bZ.AddPointAt(transform.position);
     sBZPoint.handle1 = Vector3.forward * 5;
     eBZPoint         = bZ.AddPointAt(new Vector3(0, 0, -20) + transform.position);
     eBZPoint.handle1 = Vector3.forward * 5;
 }
    private void OnSceneGUI()
    {
        curve           = target as BezierCurve;
        handleTransform = curve.transform;
        handleRotation  = Tools.pivotRotation == PivotRotation.Local ?
                          handleTransform.rotation : Quaternion.identity;

        Vector3 p0 = ShowPoint(0);
        Vector3 p1 = ShowPoint(1);
        Vector3 p2 = ShowPoint(2);
        Vector3 p3 = ShowPoint(3);

        Handles.color = Color.gray;
        Handles.DrawLine(p0, p1);
        Handles.DrawLine(p2, p3);

        ShowDirections();
        Handles.DrawBezier(p0, p3, p1, p2, Color.white, null, 2f);
    }
Example #33
0
    /*
     *  Bezier :
     *      Evaluate a Bezier curve at a particular parameter value
     *      int degree;		The degree of the bezier curve
     *      BezierCurve V   Array of control points
     *      float t		 Parametric value to find point for
     *
     */
    static Vector2 BezierII(int degree, BezierCurve V, float t)
    {
        int     i, j;
        Vector2 Q;              /* Point on curve at parameter t	*/

        Vector2[] Vtemp;        /* Local copy of control points		*/

        /* Copy array	*/
        Vtemp = new Vector2[degree + 1];
        if (degree == 3)
        {
            Vtemp[0] = V.v0;
            Vtemp[1] = V.v1;
            Vtemp[2] = V.v2;
            Vtemp[3] = V.v3;
        }
        if (degree == 2)
        {
            Vtemp[0] = V.v0;
            Vtemp[1] = V.v1;
            Vtemp[2] = V.v2;
        }
        if (degree == 1)
        {
            Vtemp[0] = V.v0;
            Vtemp[1] = V.v1;
        }



        /* Triangle computation	*/
        for (i = 1; i <= degree; i++)
        {
            for (j = 0; j <= degree - i; j++)
            {
                Vtemp[j].x = (1.0f - t) * Vtemp[j].x + t * Vtemp[j + 1].x;
                Vtemp[j].y = (1.0f - t) * Vtemp[j].y + t * Vtemp[j + 1].y;
            }
        }

        Q = Vtemp[0];
        return(Q);
    }
    private void OnSceneGUI()
    {
        this._curve           = target as BezierCurve;
        this._handleTransform = this._curve.transform;
        this._handleRotation  = Tools.pivotRotation == PivotRotation.Local ? this._handleTransform.rotation : Quaternion.identity;

        var p0 = this.ShowPoint(0);
        var p1 = this.ShowPoint(1);
        var p2 = this.ShowPoint(2);
        var p3 = this.ShowPoint(3);

        Handles.color = Color.gray;
        Handles.DrawLine(p0, p1);
        Handles.DrawLine(p1, p2);
        Handles.DrawLine(p2, p3);

        this.ShowDirections();
        Handles.DrawBezier(p0, p3, p1, p2, Color.white, null, 2.0f);
    }
    public Vector3 GetNormalizedTangent(BezierCurve curve, int n)
    {
        Vector3 tangent;

        if (n == 0)
        {
            tangent = curve.Points[1].Position - curve.Points[0].Position;
        }
        else if (n == curve.Positions.Count - 1)
        {
            tangent = curve.Points[curve.Points.Count - 1].Position - curve.Points[curve.Points.Count - 2].Position;
        }
        else
        {
            tangent = curve.Positions[n + 1] - curve.Positions[n - 1];
        }

        return(tangent.normalized);
    }
Example #36
0
        public List <BezierCurve> GetPaths(IAnimatable animatable, Ship ship)
        {
            List <BezierCurve> paths = new List <BezierCurve>();

            var cx = Constants.CanvasSize.Width / 2;

            var rotateclockwise = new BezierCurve()
            {
                StartPoint    = animatable.Location,
                EndPoint      = new PointF(animatable.Location.X + 100, animatable.Location.Y),
                ControlPoint1 = new PointF(animatable.Location.X, animatable.Location.Y - 100),
                ControlPoint2 = new PointF(animatable.Location.X + 100, animatable.Location.Y - 100)
            };
            var dive = new BezierCurve()
            {
                StartPoint    = new PointF(animatable.Location.X + 101, animatable.Location.Y + 1),
                EndPoint      = new PointF(cx, Constants.CanvasSize.Height - 50),
                ControlPoint1 = new PointF(animatable.Location.X + 100, Constants.CanvasSize.Height / 2),
                ControlPoint2 = new PointF(0, Constants.CanvasSize.Height / 2),
            };
            var swoopcounterclockwise = new BezierCurve()
            {
                StartPoint    = new PointF(cx - 1, Constants.CanvasSize.Height - 49),
                EndPoint      = new PointF(cx + 250, Constants.CanvasSize.Height - 200),
                ControlPoint1 = new PointF(cx + 50, Constants.CanvasSize.Height + 25),
                ControlPoint2 = new PointF(cx + 250, Constants.CanvasSize.Height - 20)
            };
            var gohome = new BezierCurve()
            {
                StartPoint    = new PointF(cx + 249, Constants.CanvasSize.Height - 199),
                EndPoint      = new PointF(cx + 150, 375),
                ControlPoint1 = new PointF(cx + 250, Constants.CanvasSize.Height - 300),
                ControlPoint2 = new PointF(Constants.CanvasSize.Width, Constants.CanvasSize.Height / 2)
            };

            paths.Add(rotateclockwise);
            paths.Add(dive);
            paths.Add(swoopcounterclockwise);
            paths.Add(gohome);

            return(paths);
        }
Example #37
0
        internal static MMDMotion Convert(MikuMikuDance.Motion.Motion2.MMDMotion2 input)
        {
            MMDMotion result = new MMDMotion();

            //ボーンモーションデータの変換
            MMDBoneKeyFrame[] BoneFrames = new MMDBoneKeyFrame[input.Motions.LongLength];
            for (long i = 0; i < input.Motions.LongLength; i++)
            {
                BoneFrames[i]          = new MMDBoneKeyFrame();
                BoneFrames[i].BoneName = input.Motions[i].BoneName;
                BoneFrames[i].FrameNo  = input.Motions[i].FrameNo;

                BoneFrames[i].Curve = new BezierCurve[4];
                for (int j = 0; j < BoneFrames[i].Curve.Length; j++)
                {
                    BezierCurve curve = new BezierCurve();
                    curve.v1 = new Vector2((float)input.Motions[i].Interpolation[0][0][j] / 128f, (float)input.Motions[i].Interpolation[0][1][j] / 128f);
                    curve.v2 = new Vector2((float)input.Motions[i].Interpolation[0][2][j] / 128f, (float)input.Motions[i].Interpolation[0][3][j] / 128f);
                    BoneFrames[i].Curve[j] = curve;
                }
                BoneFrames[i].Scales    = new Vector3(1, 1, 1);
                BoneFrames[i].Location  = new Vector3((decimal)input.Motions[i].Location[0], (decimal)input.Motions[i].Location[1], (decimal)input.Motions[i].Location[2]);
                BoneFrames[i].Quatanion = new Quaternion((decimal)input.Motions[i].Quatanion[0], (decimal)input.Motions[i].Quatanion[1], (decimal)input.Motions[i].Quatanion[2], (decimal)input.Motions[i].Quatanion[3]);
                BoneFrames[i].Quatanion.Normalize();
            }
            result.BoneFrames = MotionHelper.SplitBoneMotion(BoneFrames);
            //表情モーションの変換
            MMDFaceKeyFrame[] FaceFrames = new MMDFaceKeyFrame[input.FaceMotions.LongLength];
            for (long i = 0; i < input.FaceMotions.Length; i++)
            {
                FaceFrames[i]          = new MMDFaceKeyFrame();
                FaceFrames[i].Rate     = input.FaceMotions[i].Rate;
                FaceFrames[i].FaceName = input.FaceMotions[i].FaceName;
                FaceFrames[i].FrameNo  = input.FaceMotions[i].FrameNo;
                float temp = input.FaceMotions[i].FrameNo;
            }
            result.FaceFrames = MotionHelper.SplitFaceMotion(FaceFrames);
            //カメラモーションは無視(使わんので)
            //ライトモーションは無視(使わんので)
            //変換したデータを返却
            return(result);
        }
        public void SetOutput(BehaviorNodeControl target, int index)
        {
            // Not self
            if (target == this)
            {
                return;
            }

            // Make sure connection does not already exist
            foreach (BehaviorNodeControl o in m_outputs)
            {
                if (o == target)
                {
                    return;
                }
            }

            // Make sure there are no circular references
            foreach (BehaviorNodeControl o in target.m_outputs)
            {
                if (CheckCircularReference(this, o))
                {
                    return;
                }
            }

            if (index < m_outputs.Count)
            {
                // Replace
                m_outputs[index] = target;
            }
            else
            {
                // New connection

                m_outputs.Add(target);
                BezierCurve line = (BezierCurve)m_canvas.AddShape(new BezierCurve(GetOutputConnectorPosition(index), target.GetInputConnectorPosition(), Color.red, 1.0f, BezierCurve.TangentMode.AutoY, Vector2.zero, Vector2.zero));
                m_outputLines.Add(line);

                UpdateOutputs();
            }
        }
    // Drawing
    private void OnSceneGUI()
    {
        curve           = target as BezierCurve;
        handleTransform = curve.transform;
        handleRotation  = Tools.pivotRotation == PivotRotation.Local
            ? handleTransform.rotation
            : Quaternion.identity;

        // Draw point handles
        Vector3 p0 = ShowPoint(0);
        Vector3 p1 = ShowPoint(1);
        Vector3 p2 = ShowPoint(2);
        Vector3 p3 = ShowPoint(3);

        // Draw points
        Handles.color = Color.gray;
        Handles.DrawLine(p0, p1);
        Handles.DrawLine(p2, p3);

        // Draw bezier curve
        Handles.color = Color.white;
        Vector3 lineStart = curve.GetPoint(0f);

        for (int i = 1; i <= lineSteps; i++)
        {
            Vector3 lineEnd = curve.GetPoint(i / (float)lineSteps);
            Handles.DrawLine(lineStart, lineEnd);
            lineStart = lineEnd;
        }

        Handles.color = Color.green;
        Handles.DrawLine(lineStart, lineStart + curve.GetDirection(0f));
        for (int i = 1; i <= lineSteps; i++)
        {
            Vector3 lineEnd = curve.GetPoint(i / (float)lineSteps);
            Handles.color = Color.white;
            Handles.DrawLine(lineStart, lineEnd);
            Handles.color = Color.green;
            Handles.DrawLine(lineEnd, lineEnd + curve.GetDirection(i / (float)lineSteps));
            lineStart = lineEnd;
        }
    }
Example #40
0
    public override void OnInspectorGUI()
    {
        curve = target as BezierCurve;

        if (!curve.AllZIsZero)
        {
            EditorGUILayout.HelpBox("THE CURVE IS NOT FLAT IN Z-DIMENSION", MessageType.Warning);
        }

        base.OnInspectorGUI();

        EditorGUILayout.BeginHorizontal();
        if (GUILayout.Button("Make Linear"))
        {
            curve.MakeLinear();
        }
        if (GUILayout.Button("Reset Shape"))
        {
            curve.SetDefaultShape();
        }

        if (GUILayout.Button("Inv Direction"))
        {
            curve.InvertDirection();
        }

        if (GUILayout.Button("Create child"))
        {
            curve.CloneMakeChild();
        }

        EditorGUILayout.EndHorizontal();

        EditorGUILayout.BeginHorizontal();
        zValue = EditorGUILayout.FloatField(zValue);
        if (GUILayout.Button("Set All Z-values"))
        {
            curve.SetAllZTo(zValue);
        }

        EditorGUILayout.EndHorizontal();
    }
Example #41
0
    public static Vector2 NearestPointOnBezier(Vector2 p, BezierCurve c, float accuracy, bool doubleAc)
    {
        float   minDist = Mathf.Infinity;
        float   minT    = 0;
        Vector2 minP    = Vector2.zero;

        for (float i = 0; i < 1; i += accuracy)
        {
            var   point = c.Get(i);
            float d     = (p - point).sqrMagnitude;
            if (d < minDist)
            {
                minDist = d;
                minT    = i;
                minP    = point;
            }
        }

        if (!doubleAc)
        {
            return(minP);
        }

        float st = Mathf.Clamp01(minT - accuracy);
        float en = Mathf.Clamp01(minT + accuracy);


        for (var i = st; i < en; i += accuracy / 10)
        {
            var point = c.Get(i);
            var d     = (p - point).sqrMagnitude;
            if (d < minDist)
            {
                minDist = d;
                minT    = i;
                minP    = point;
            }
        }


        return(minP);
    }
        public List <PointF> ComputePathPoints(BezierCurve path, bool pathisline = false, int granularity = 10)
        {
            var cachedPath = PathCaches.FirstOrDefault(a => a.Path.StartPoint.Equals(path.StartPoint) &&
                                                       a.Path.ControlPoint1.Equals(path.ControlPoint1) &&
                                                       a.Path.ControlPoint2.Equals(path.ControlPoint2) &&
                                                       a.Path.EndPoint.Equals(path.EndPoint));

            if (cachedPath != null && !pathisline)
            {
                return(cachedPath.PathPoints);
            }

            List <PointF> pathpoints = new List <PointF>();

            if (path.BreakPath)
            {
                pathpoints.Add(new PointF(-999, -999));
            }

            for (var percent = 0F; percent <= 100; percent += granularity)
            {
                PointF point;
                if (pathisline)
                {
                    point = bezierCurveService.getLineXYatPercent(path, percent);
                }
                else
                {
                    point = bezierCurveService.getCubicBezierXYatPercent(path, percent);
                }
                pathpoints.Add(point);
            }

            pathpoints = bezierCurveService.GetEvenlyDistributedPathPointsByLength(pathpoints, 5);

            PathCaches.Add(new PathCache()
            {
                Path = path, PathPoints = pathpoints
            });

            return(pathpoints);
        }
Example #43
0
    public override void OnInspectorGUI()
    {
        //base.OnInspectorGUI();
        _curve = target as BezierCurve;
        EditorGUI.BeginChangeCheck();
        bool loop = EditorGUILayout.Toggle("Loop", _curve.Loop);

        if (EditorGUI.EndChangeCheck())
        {
            Undo.RecordObject(_curve, "Toggle Loop");
            _curve.Loop = loop;
            EditorUtility.SetDirty(_curve);
        }

        if (_selectedIndex >= 0 && _selectedIndex < _curve.ControlPointCount)
        {
            DrawSelectedPointInspector();
        }

        _curve = target as BezierCurve;
        if (GUILayout.Button("Add Curve"))
        {
            Undo.RecordObject(_curve, "Add Curve");
            _curve.AddCurve();
            EditorUtility.SetDirty(_curve);
        }

        if (GUILayout.Button("Remove Curve"))
        {
            Undo.RecordObject(_curve, "Remove Curve");
            _curve.RemoveCurve();
            EditorUtility.SetDirty(_curve);
        }

        if (GUILayout.Button("Reset Start Point"))
        {
            Undo.RecordObject(_curve, "Remove Curve");
            var origin = _curve.gameObject.transform.position;
            _curve.SetControlPoint(0, _handleTransform.InverseTransformPoint(origin));
            EditorUtility.SetDirty(_curve);
        }
    }
Example #44
0
        public override bool?Colliding(Rectangle projHitbox, Rectangle targetHitbox)
        {
            BezierCurve curve = new BezierCurve(new Vector2[] { Owner.MountedCenter, _chainMidA, _chainMidB, projectile.Center });

            int numPoints = 32;

            Vector2[] chainPositions = curve.GetPoints(numPoints).ToArray();
            float     collisionPoint = 0;

            for (int i = 1; i < numPoints; i++)
            {
                Vector2 position         = chainPositions[i];
                Vector2 previousPosition = chainPositions[i - 1];
                if (Collision.CheckAABBvLineCollision(targetHitbox.TopLeft(), targetHitbox.Size(), position, previousPosition, 6, ref collisionPoint))
                {
                    return(true);
                }
            }
            return(base.Colliding(projHitbox, targetHitbox));
        }
Example #45
0
    public bool MoveShip(float delta)
    {
        bool results = false;

        if (movePercent < 1.0f)
        {
            movePercent = Mathf.Min(movePercent + moveSpeed * delta, 1.0f);

            transform.position = BezierCurve.Curve(pathPoints, movePercent);
            Vector3 deltaPosition = BezierCurve.Curve(pathPoints, Mathf.Min(movePercent + BezierCurve.Delta(), 1.0f));

            transform.LookAt(deltaPosition);
        }
        else
        {
            results = true;
        }

        return(results);
    }
Example #46
0
 void InitializeCurve()
 {
     if (playerConfig.DrawCurve && curve == null)
     {
         curve = Instantiate(playerConfig.CurvePrefab);
         curve.transform.SetParent(transform);
         curve.Initialize();
     }
     else if (curve != null)
     {
         if (playerConfig.DrawCurve)
         {
             curve.Enable();
         }
         else
         {
             curve.Disable();
         }
     }
 }
Example #47
0
        private static double[] FindIntersectionT(BezierCurve bezierCurve, double x1, double y1, double x2, double y2)
        {
            double A = (y2 - y1);
            double B = (x1 - x2);
            double C = x1 * (y1 - y2) + y1 * (x2 - x1);

            double alpha = (double)bezierCurve.StartPoint.X * A + (double)bezierCurve.StartPoint.Y * B;
            double beta  = 3.0 * ((double)bezierCurve.FirstControlPoint.X * A + (double)bezierCurve.FirstControlPoint.Y * B);
            double gamma = 3.0 * ((double)bezierCurve.SecondControlPoint.X * A + (double)bezierCurve.SecondControlPoint.Y * B);
            double delta = (double)bezierCurve.EndPoint.X * A + (double)bezierCurve.EndPoint.Y * B;

            double a = (-alpha + beta - gamma + delta);
            double b = (3 * alpha - 2 * beta + gamma);
            double c = -3 * alpha + beta;
            double d = alpha + C;

            var solution = SolveCubicEquation(a, b, c, d);

            return(solution.Where(s => !double.IsNaN(s)).Where(s => s >= -double.Epsilon && s <= 1.0).OrderBy(s => s).ToArray());
        }
    void Update()
    {
        if (toFollow == null)
        {
            transform.Translate(Vector3.forward * moveSpeed * Time.deltaTime);
            return;
        }

        percent += followSpeed * Time.deltaTime;

        Vector3 newPoint = startPosition + startRotation * toFollow.GetPointAt(percent);

        transform.rotation = startRotation * toFollow.GetRotationAt(percent);
        transform.position = newPoint;

        if (percent >= 1f)
        {
            toFollow = null;
        }
    }
Example #49
0
    static BezierCurve AddCurve(BezierCurve previous)
    {
        BezierCurve newCurve = new GameObject().AddComponent<BezierCurve>();

        newCurve.profile = previous.profile;
        newCurve.numDivs = previous.numDivs;
        newCurve.numDivsProfile = previous.numDivsProfile;
        newCurve.width = previous.width;
        newCurve.verticalScale = previous.verticalScale;

        newCurve.Start();
        newCurve.a.position = previous.d.position;
        newCurve.a.rotation = previous.d.rotation;

        newCurve.d.position = previous.d.position + previous.d.forward * 10.0f;
        //newCurve.a.rotation = previous.d.rotation;

        previous.nextCurve = newCurve;

        return newCurve;
    }
    void OnSceneGUI()
    {
        b_curve = target as BezierCurve;
        handleTransform = b_curve.transform;
        handleRotation = Tools.pivotRotation == PivotRotation.Local ? handleTransform.rotation : Quaternion.identity;

        Vector3 point0 = ShowPoint(0);
        Vector3 point1 = ShowPoint(1);
        Vector3 point2 = ShowPoint(2);
        Vector3 point3 = ShowPoint(3);

        Handles.color = Color.gray;
        Handles.DrawLine(point0, point1);
        Handles.DrawLine(point1, point2);
        Handles.DrawLine(point2, point3);

        if (b_curve.showDirections == true)
        {
            ShowDirections();
        }
        Handles.DrawBezier(point0, point3, point1, point2, Color.white, null, 2f);

        //Handles.color = Color.white;
        //Vector3 lineStart = b_curve.GetPoint(0f);
        //Handles.color = Color.green;
        //Handles.DrawLine(lineStart, lineStart + b_curve.GetDirection(0f));

        //for (int i = 1; i < lineSteps; i++)
        //{
        //    Vector3 lineEnd = b_curve.GetPoint(i / (float)lineSteps);
        //    Handles.color = Color.white;
        //    Handles.DrawLine(lineStart, lineEnd);
        //    if (b_curve.showDirections == true)
        //    {
        //        Handles.color = Color.green;
        //        Handles.DrawLine(lineEnd, lineEnd + b_curve.GetDirection(i / (float)lineSteps));
        //    }
        //    lineStart = lineEnd;
        //}
    }
    public void BuildLinkBezier(MeshBuilder meshBuilder, BezierCurve connectionBezier, float widthStart, float widthEnd, Color colorStart, Color colorEnd) {
        List<int> verticesList = new List<int>();

        float m_splineStartRadius = widthStart;
        float m_splineEndRadius = widthEnd;
        int m_splineHeightSegmentCount = 8;
        int m_splineRadialSegmentCount = 4;

        float tInc = 1f / m_splineHeightSegmentCount; // How many subdivisions along the length of the spline

        for (int i = 0; i <= m_splineHeightSegmentCount; i++) {
            float t = tInc * (float)i;
            Vector3 ringCenter = connectionBezier.GetPoint(t);
            //Quaternion rot = Quaternion.identity;
            Vector3 dir = connectionBezier.GetDirection(t);
            Quaternion rot = Quaternion.identity;
            if (dir != Vector3.zero) {
                rot.SetLookRotation(dir);
            }
            float radius = ((1f - t) * m_splineStartRadius) + (t * m_splineEndRadius);
            // Construct the mesh Ring!
            //BuildBezierCurveRing(meshBuilder, m_splineRadialSegmentCount, ringCenter, radius, t, i > 0, rot); 
            //protected void BuildBezierCurveRing(MeshBuilder meshBuilder, int segmentCount, Vector3 center, float radius, float v, bool buildTriangles, Quaternion rotation) {
            float angleInc = (Mathf.PI * 2.0f) / m_splineRadialSegmentCount;

            for (int j = 0; j <= m_splineRadialSegmentCount; j++) {
                float angle = angleInc * j;

                Vector3 unitPosition = Vector3.zero;
                unitPosition.x = Mathf.Cos(angle);
                unitPosition.y = Mathf.Sin(angle);

                unitPosition = rot * unitPosition;
                Vector3 normal = unitPosition;

                meshBuilder.Vertices.Add(ringCenter + unitPosition * radius);
                meshBuilder.Normals.Add(normal);
                //meshBuilder.UVs.Add(new Vector2((float)i / segmentCount, v));
                meshBuilder.UVs.Add(new Vector2((float)j / m_splineRadialSegmentCount, t));
                verticesList.Add(meshBuilder.Vertices.Count - 1);
                meshBuilder.Colors.Add(Color.Lerp(colorStart, colorEnd, t));

                if (j > 0 && i > 0) {
                    //Debug.Log ("buildTriangles!");
                    int baseIndex = meshBuilder.Vertices.Count - 1;

                    int vertsPerRow = m_splineRadialSegmentCount + 1;

                    int index0 = baseIndex;
                    int index1 = baseIndex - 1;
                    int index2 = baseIndex - vertsPerRow;
                    int index3 = baseIndex - vertsPerRow - 1;

                    meshBuilder.AddTriangle(index1, index2, index0);
                    meshBuilder.AddTriangle(index1, index3, index2);
                }
            }            
        }
        connectionVertexList.Add(verticesList);  // keep track of Connection's vertices so their color can be changed without rebuilding every frame
    }
Example #52
0
    /**
     * Move the navigator to the given curve
     */
    private void MoveToCurve( int index )
    {
        if( index >= m_curves.Length )
        {
            Debug.LogError("Curve index out of bounds " + index.ToString());
            return;
        }

        m_curveIndex = index;
        m_curve = m_curves[ m_curveIndex ];

        // TODO: check if using the interpolated step makes the transition smoother
        //transform.position = m_curve.BeginPoint.position;
        //transform.rotation = m_curve.BeginPoint.rotation;
        m_step = 0;

        BezierSpeed curveSpeed = m_curve.GetComponent<BezierSpeed>();
        if( curveSpeed )
        {
            MinSpeed = curveSpeed.MinSpeed;
            MaxSpeed = curveSpeed.MaxSpeed;
            Acceleration = curveSpeed.Acceleration;
            Deceleration = curveSpeed.Deceleration;
        }
    }
    public Mesh BuildNewMesh(BrainNEAT brain) {
        if(sourceCritter == null) {
            Debug.Log("BuildNewMesh(BrainNEAT brain) SOURCE CRITTER NULL!!!");
        }
        else {
            SetNeuronSegmentPositions(brain);
        }

        if (nodeVertexList == null) {
            nodeVertexList = new List<List<int>>();
        }
        else {
            nodeVertexList.Clear();
        }
        if (connectionVertexList == null) {
            connectionVertexList = new List<List<int>>();
        }
        else {
            connectionVertexList.Clear();
        }
        
        if(nodePositionsList == null) {
            nodePositionsList = new List<Vector3>();
        }
        else {
            nodePositionsList.Clear();
        }
        if(bezierCurveList == null) {
            bezierCurveList = new List<BezierCurve>();
        }
        else {
            bezierCurveList.Clear();
        }
        if(hiddenNodeIndicesList == null) {
            hiddenNodeIndicesList = new List<int>();  // keep track of hidden nodes for later use
        }
        else {
            hiddenNodeIndicesList.Clear();
        }
        
        meshBuilder = new MeshBuilder();
        //Debug.Log("PRE ERROR: brain: " + brain.ToString());
        //neuronRadius = 1.4f / Mathf.Max((float)brain.inputNeuronList.Count, (float)brain.outputNeuronList.Count);
        //Vector3 offset = new Vector3(neuronRadius * 0.5f, neuronRadius * 0.5f, 0f);

        int currentInputIndex = 0;
        int currentOutputIndex = 0; 

        for(int i = 0; i < brain.neuronList.Count; i++) {
            // go through all nodes and place them in proper spot
            float xpos = 0f;
            float ypos = 0f;
            float zpos = 0f;

            //float size = Mathf.Min((neuronRadius * brain.neuronList[i].currentValue[0] * 0.2f + 0.02f), 2.0f);
            float size = Mathf.Max(Mathf.Min((Mathf.Abs(brain.neuronList[i].currentValue[0])) * neuronRadiusMaxValue, neuronRadiusMax), neuronRadiusMin);

            if (brain.neuronList[i].nodeType == GeneNodeNEAT.GeneNodeType.In) {
                xpos = (float)(currentInputIndex + 1) / (float)(brain.inputNeuronList.Count + 1) - 0.5f;
                ypos = 0f;
                zpos = UnityEngine.Random.Range(-0.5f, 0.5f);
                currentInputIndex++;
                BuildNodeSphere(meshBuilder, new Vector3(xpos, ypos, zpos), size, GetColorFromNeuron(brain.neuronList[i]));
            }
            else if(brain.neuronList[i].nodeType == GeneNodeNEAT.GeneNodeType.Hid) {
                xpos = 0.0f; // UnityEngine.Random.Range(neuronRadius, 1f - neuronRadius); //0.5f;
                ypos = 0.0f; // UnityEngine.Random.Range(neuronRadius, 1f - neuronRadius); //0.5f;
                zpos = UnityEngine.Random.Range(-0.5f, 0.5f);
                hiddenNodeIndicesList.Add(i);
                //BuildNode(meshBuilder, new Vector3(xpos, ypos, 0f), new Vector3(radius, 0f, 0f), new Vector3(0f, radius, 0f), GetColorFromValue(brain.neuronList[i].currentValue[0]));
            }
            else {  // output
                xpos = (float)(currentOutputIndex + 1) / (float)(brain.outputNeuronList.Count + 1) - 0.5f;
                ypos = 1f - neuronRadiusMax;
                zpos = UnityEngine.Random.Range(-0.5f, 0.5f);
                currentOutputIndex++;
                BuildNodeSphere(meshBuilder, new Vector3(xpos, ypos, zpos), size, GetColorFromNeuron(brain.neuronList[i]));
            }
            nodePositionsList.Add(new Vector3(xpos, ypos, zpos));
        }

        // position HiddenNodes!!
        
        // BUILD hidden nodes:
        for (int h = 0; h < hiddenNodeIndicesList.Count; h++) {
            float size = Mathf.Max(Mathf.Min((Mathf.Abs(brain.neuronList[hiddenNodeIndicesList[h]].currentValue[0])) * neuronRadiusMaxValue, neuronRadiusMax), neuronRadiusMin);
            BuildNodeSphere(meshBuilder, new Vector3(nodePositionsList[hiddenNodeIndicesList[h]].x, nodePositionsList[hiddenNodeIndicesList[h]].y, nodePositionsList[hiddenNodeIndicesList[h]].z), size, GetColorFromNeuron(brain.neuronList[hiddenNodeIndicesList[h]]));
        }

        // CONNECTIONS!
        //connectionWidth = Mathf.Max(neuronRadius * 0.1f, 0.01f);
        //Debug.Log("BuildNew BrainMesh: numConnections: " + brain.connectionList.Count);
        for(int c = 0; c < brain.connectionList.Count; c++) {
            BezierCurve connectionBezier = new BezierCurve();
            connectionBezier.points[0] = nodePositionsList[brain.connectionList[c].fromNodeID];
            connectionBezier.points[1] = Vector3.Lerp(nodePositionsList[brain.connectionList[c].fromNodeID], nodePositionsList[brain.connectionList[c].toNodeID], 0.333f);
            connectionBezier.points[2] = Vector3.Lerp(nodePositionsList[brain.connectionList[c].fromNodeID], nodePositionsList[brain.connectionList[c].toNodeID], 0.667f);
            connectionBezier.points[3] = nodePositionsList[brain.connectionList[c].toNodeID];
            bezierCurveList.Add(connectionBezier);
            float startWidth = Mathf.Max(Mathf.Min((Mathf.Abs(brain.neuronList[brain.connectionList[c].fromNodeID].currentValue[0]) * connectionWidthMax * 0.4f), connectionWidthMax), connectionWidthMin);
            float endWidth = Mathf.Max(Mathf.Min((Mathf.Abs(brain.neuronList[brain.connectionList[c].toNodeID].currentValue[0])) * connectionWidthMax * 0.4f, connectionWidthMax), connectionWidthMin);
            BuildLinkBezier(meshBuilder, connectionBezier, startWidth, endWidth, GetColorFromNeuron(brain.neuronList[brain.connectionList[c].fromNodeID]), GetColorFromNeuron(brain.neuronList[brain.connectionList[c].toNodeID]));
            //Debug.Log("BuildNew BrainMesh: from: " + nodePositionsList[brain.connectionList[c].fromNodeID].ToString() + ", to: " + nodePositionsList[brain.connectionList[c].toNodeID].ToString());
        }
        
        //MoveHiddenNodes(brain, 1);
        return meshBuilder.CreateMesh();
    }
        private unsafe void UpdateGeometry()
        {
            DestroyGeometry();

            Curve positionCurve = GetPositionCurve();

            Curve radiusCurve = null;
            {
                bool existsSpecialRadius = false;
                foreach (MapCurvePoint point in Points)
                {
                    RenderableCurvePoint point2 = point as RenderableCurvePoint;
                    if (point2 != null && point2.OverrideRadius >= 0)
                    {
                        existsSpecialRadius = true;
                        break;
                    }
                }

                if (existsSpecialRadius)
                {
                    switch (radiusCurveType)
                    {
                        case RadiusCurveTypes.UniformCubicSpline:
                            radiusCurve = new UniformCubicSpline();
                            break;

                        case RadiusCurveTypes.Bezier:
                            radiusCurve = new BezierCurve();
                            break;

                        case RadiusCurveTypes.Line:
                            radiusCurve = new LineCurve();
                            break;
                    }

                    for (int n = 0; n < Points.Count; n++)
                    {
                        MapCurvePoint point = Points[n];

                        if (!point.Editor_IsExcludedFromWorld())
                        {
                            float rad = radius;
                            RenderableCurvePoint renderableCurvePoint = point as RenderableCurvePoint;
                            if (renderableCurvePoint != null && renderableCurvePoint.OverrideRadius >= 0)
                                rad = renderableCurvePoint.OverrideRadius;
                            radiusCurve.AddValue(point.Time, new Vec3(rad, 0, 0));
                        }
                    }
                }
            }

            //create mesh
            Vertex[] vertices = null;
            int[] indices = null;
            if (positionCurve != null && positionCurve.Values.Count > 1 && Points.Count >= 2)
            {
                Vec3 positionOffset = -Position;

                int steps = (Points.Count - 1) * pathSteps + 1;
                int vertexCount = steps * (shapeSegments + 1);
                int indexCount = (steps - 1) * shapeSegments * 2 * 3;

                vertices = new Vertex[vertexCount];
                indices = new int[indexCount];

                //fill data
                {
                    int currentVertex = 0;
                    int currentIndex = 0;
                    float currentDistance = 0;
                    Vec3 lastPosition = Vec3.Zero;
                    Quat lastRot = Quat.Identity;

                    for (int nStep = 0; nStep < steps; nStep++)
                    {
                        int startStepVertexIndex = currentVertex;

                        float coefficient = (float)nStep / (float)(steps - 1);
                        Vec3 pos = CalculateCurvePointByCoefficient(coefficient) + positionOffset;

                        Quat rot;
                        {
                            Vec3 v = CalculateCurvePointByCoefficient(coefficient + .3f / (float)(steps - 1)) -
                                CalculateCurvePointByCoefficient(coefficient);
                            if (v != Vec3.Zero)
                                rot = Quat.FromDirectionZAxisUp(v.GetNormalize());
                            else
                                rot = lastRot;
                        }

                        if (nStep != 0)
                            currentDistance += (pos - lastPosition).Length();

                        float rad;
                        if (radiusCurve != null)
                        {
                            Range range = new Range(radiusCurve.Times[0], radiusCurve.Times[radiusCurve.Times.Count - 1]);
                            float t = range.Minimum + (range.Maximum - range.Minimum) * coefficient;
                            rad = radiusCurve.CalculateValueByTime(t).X;
                        }
                        else
                            rad = radius;

                        for (int nSegment = 0; nSegment < shapeSegments + 1; nSegment++)
                        {
                            float rotateCoefficient = ((float)nSegment / (float)(shapeSegments));
                            float angle = rotateCoefficient * MathFunctions.PI * 2;
                            Vec3 p = pos + rot * new Vec3(0, MathFunctions.Cos(angle) * rad, MathFunctions.Sin(angle) * rad);

                            Vertex vertex = new Vertex();
                            vertex.position = p;
                            Vec3 pp = p - pos;
                            if (pp != Vec3.Zero)
                                vertex.normal = pp.GetNormalize();
                            else
                                vertex.normal = Vec3.XAxis;
                            //vertex.normal = ( p - pos ).GetNormalize();
                            vertex.texCoord = new Vec2(currentDistance * textureCoordinatesTilesPerMeter, rotateCoefficient + .25f);
                            vertex.tangent = new Vec4(rot.GetForward(), 1);
                            vertices[currentVertex++] = vertex;
                        }

                        if (nStep < steps - 1)
                        {
                            for (int nSegment = 0; nSegment < shapeSegments; nSegment++)
                            {
                                indices[currentIndex++] = startStepVertexIndex + nSegment;
                                indices[currentIndex++] = startStepVertexIndex + nSegment + 1;
                                indices[currentIndex++] = startStepVertexIndex + nSegment + 1 + shapeSegments + 1;
                                indices[currentIndex++] = startStepVertexIndex + nSegment + 1 + shapeSegments + 1;
                                indices[currentIndex++] = startStepVertexIndex + nSegment + shapeSegments + 1;
                                indices[currentIndex++] = startStepVertexIndex + nSegment;
                            }
                        }

                        lastPosition = pos;
                        lastRot = rot;
                    }
                    if (currentVertex != vertexCount)
                        Log.Fatal("RenderableCurve: UpdateRenderingGeometry: currentVertex != vertexCount.");
                    if (currentIndex != indexCount)
                        Log.Fatal("RenderableCurve: UpdateRenderingGeometry: currentIndex != indexCount.");
                }

                if (vertices.Length != 0 && indices.Length != 0)
                {
                    //create mesh
                    string meshName = MeshManager.Instance.GetUniqueName(
                        string.Format("__RenderableCurve_{0}_{1}", Name, uniqueMeshIdentifier));
                    uniqueMeshIdentifier++;
                    //string meshName = MeshManager.Instance.GetUniqueName( string.Format( "__RenderableCurve_{0}", Name ) );
                    mesh = MeshManager.Instance.CreateManual(meshName);
                    SubMesh subMesh = mesh.CreateSubMesh();
                    subMesh.UseSharedVertices = false;

                    //init vertexData
                    VertexDeclaration declaration = subMesh.VertexData.VertexDeclaration;
                    declaration.AddElement(0, 0, VertexElementType.Float3, VertexElementSemantic.Position);
                    declaration.AddElement(0, 12, VertexElementType.Float3, VertexElementSemantic.Normal);
                    declaration.AddElement(0, 24, VertexElementType.Float2, VertexElementSemantic.TextureCoordinates, 0);
                    declaration.AddElement(0, 32, VertexElementType.Float4, VertexElementSemantic.Tangent, 0);

                    fixed (Vertex* pVertices = vertices)
                    {
                        subMesh.VertexData = VertexData.CreateFromArray(declaration, (IntPtr)pVertices,
                            vertices.Length * Marshal.SizeOf(typeof(Vertex)));
                    }
                    subMesh.IndexData = IndexData.CreateFromArray(indices, 0, indices.Length, false);

                    //set material
                    subMesh.MaterialName = materialName;

                    //set mesh gabarites
                    Bounds bounds = Bounds.Cleared;
                    foreach (Vertex vertex in vertices)
                        bounds.Add(vertex.position);
                    mesh.SetBoundsAndRadius(bounds, bounds.GetRadius());
                }
            }

            //create MeshObject, SceneNode
            if (mesh != null)
            {
                meshObject = SceneManager.Instance.CreateMeshObject(mesh.Name);
                if (meshObject != null)
                {
                    meshObject.SetMaterialNameForAllSubObjects(materialName);
                    meshObject.CastShadows = true;

                    sceneNode = new SceneNode();
                    sceneNode.Attach(meshObject);
                    //apply offset
                    sceneNode.Position = Position;
                    MapObject.AssociateSceneNodeWithMapObject(sceneNode, this);
                }
            }

            //create collision body
            if (mesh != null && collision)
            {
                Vec3[] positions = new Vec3[vertices.Length];
                for (int n = 0; n < vertices.Length; n++)
                    positions[n] = vertices[n].position;
                string meshPhysicsMeshName = PhysicsWorld.Instance.AddCustomMeshGeometry(positions, indices, null,
                    MeshShape.MeshTypes.TriangleMesh, 0, 0);

                collisionBody = PhysicsWorld.Instance.CreateBody();
                collisionBody.Static = true;
                collisionBody._InternalUserData = this;
                collisionBody.Position = Position;

                MeshShape shape = collisionBody.CreateMeshShape();
                shape.MeshName = meshPhysicsMeshName;
                shape.MaterialName = CollisionMaterialName;
                shape.ContactGroup = (int)ContactGroup.Collision;
                //shape.VehicleDrivableSurface = collisionVehicleDrivableSurface;

                collisionBody.PushedToWorld = true;
            }

            needUpdate = false;
        }
    void test()
    {
        float startTime = Time.realtimeSinceStartup;
        var w = 100;
        var h = 100;
        var p1 = new BezierPoint(new Vector2(10, 0), new Vector2(5, 20), new Vector2(20, 0));
        var p2 = new BezierPoint(new Vector2(50, 10), new Vector2(40, 20), new Vector2(60, -10));
        var c = new BezierCurve(p1.main, p1.control2, p2.control1, p2.main);
        p1.curve2 = c;
        p2.curve1 = c;
        Vector2 elapsedTime = new Vector2((Time.realtimeSinceStartup - startTime) * 10, 0);
        float startTime2 = Time.realtimeSinceStartup;
        for (var i = 0; i < w * h; i++)
        {
            Mathfx.IsNearBezier(new Vector2(Random.value * 80, Random.value * 30), p1, p2, 10);
        }

        Vector2 elapsedTime2 = new Vector2((Time.realtimeSinceStartup - startTime2) * 10, 0);
        Debug.Log("Drawing took " + elapsedTime.ToString() + "  " + elapsedTime2.ToString());
    }
 void Awake()
 {
     m_bezierCurve = GetComponent<BezierCurve>();
 }
Example #57
0
    /**
     * Check if the navigator has arrived to the end of the curve
     * Call the OnComplete callback if its the last curve, or move
     * to the next curve if not.
     */
    private void CheckEndOfCurve()
    {
        if( m_waitingForSkip || m_step < 1 )
        {
            return;
        }

        m_step = 0;
        ExecuteCallback( OnCurve );

        if( m_curveIndex < m_curves.Length - 1 )
        {
            MoveToCurve( m_curveIndex + 1 );
        }
        else
        {
            m_done = true;
            m_curves = null;
            m_curve = null;
            m_curveIndex = 0;
            ExecuteCallback( OnComplete );
        }
    }
 private IBezierCurveGEN CreateBazerCurve()
 {
     IPoint[] controlPoints = new IPoint[4];
     //Bezier FromPoint / From Tangent FromPoint.
     controlPoints[0] = m_PT1;
     //From Tangent ToPoint.
     controlPoints[1] = m_PT2;
     //To Tangent FromPoint.
     controlPoints[2] = m_PT3;
     //Bezier To Point / To Tangent ToPoint.
     controlPoints[3] = m_PT4;
     //Define the Bezier control points. This is a simple s-curve.
     //controlPoints[0].PutCoords(0, 100);
     //controlPoints[1].PutCoords(100, 100);
     //controlPoints[2].PutCoords(0, 0);
     //controlPoints[3].PutCoords(100, 0);
     //Create the Bezier curve.
     IBezierCurveGEN bezier = new BezierCurve();
     bezier.PutCoords(ref controlPoints);
     //Get all control points from the Bezier curve.
     bezier.QueryCoords(ref controlPoints);
     //Get each control point individually.
     bezier.QueryCoord(0, controlPoints[0]);
     bezier.QueryCoord(1, controlPoints[1]);
     bezier.QueryCoord(2, controlPoints[2]);
     bezier.QueryCoord(3, controlPoints[3]);
     //Change the control points to define a simple CircularArc-like curve.
     //controlPoints[0].PutCoords(-100, 200);
     //controlPoints[1].PutCoords(-100, 100);
     //Replace individual control points.
     bezier.PutCoord(0, controlPoints[0]);
     bezier.PutCoord(1, controlPoints[1]);
     return bezier;
 }
Example #59
0
 void Start()
 {
     bezier_curve_ = GetComponent<BezierCurve>();
 }
    public static void DrawBezier(BezierPoint[] points, float rad, Color col, Texture2D tex)
    {
        rad = Mathf.Round(rad);//It is important to round the numbers otherwise it will mess up with the texture width

        if (points.Length <= 1)
        {
            return;
        }

        Vector2 topleft = new Vector2(Mathf.Infinity, Mathf.Infinity);
        Vector2 bottomright = new Vector2(0, 0);

        for (var i = 0; i < points.Length - 1; i++)
        {
            BezierCurve curve = new BezierCurve(points[i].main, points[i].control2, points[i + 1].control1, points[i + 1].main );
            points[i].curve2 = curve;
            points[i + 1].curve1 = curve;

            topleft.x = Mathf.Min(topleft.x, curve.rect.x);

            topleft.y = Mathf.Min(topleft.y, curve.rect.y);

            bottomright.x = Mathf.Max(bottomright.x, curve.rect.x + curve.rect.width);

            bottomright.y = Mathf.Max(bottomright.y, curve.rect.y + curve.rect.height);
        }

        topleft -= new Vector2(rad, rad);
        bottomright += new Vector2(rad, rad);

        var start = new Vector2(Mathf.Clamp(topleft.x, 0, tex.width), Mathf.Clamp(topleft.y, 0, tex.height));
        var width = new Vector2(Mathf.Clamp(bottomright.x - topleft.x, 0, tex.width - start.x), Mathf.Clamp(bottomright.y - topleft.y, 0, tex.height - start.y));

        Color[] pixels = tex.GetPixels((int)start.x, (int)start.y, (int)width.x, (int)width.y, 0);

        for (var y = 0; y < width.y; y++)
        {
            for (var x = 0; x < width.x; x++)
            {
                var p = new Vector2(x + start.x, y + start.y);
                if (!Mathfx.IsNearBeziers(p, points, rad + 2))
                {
                    continue;
                }

                var samples = Sample(p);
                var c = Color.black;
                var pc = pixels[(int)(y * width.x + x)];//Previous pixel color
                for (var i = 0; i < samples.Length; i++)
                {
                    if (Mathfx.IsNearBeziers(samples[i], points, rad))
                    {
                        c += col;
                    }
                    else
                    {
                        c += pc;
                    }
                }

                c /= samples.Length;

                pixels[(int)(y * width.x + x)] = c;

            }
        }

        tex.SetPixels((int)start.x, (int)start.y, (int)width.x, (int)width.y, pixels, 0);
        tex.Apply();
    }