Inheritance: MonoBehaviour
	public void drawRivers(List<Corner> Corner, int num) {
		bool[] rivermade=new bool[num];

		foreach (Corner q in Corner) {
			if (q.river > 0 && q.watershed.coast && !q.coast && !rivermade[q.index]) {
				int i = 0;
				foreach (Corner t in q.adjacent)
					if (t.river>0)
							i++;
				if (i == 1) {
					List<Spline> oneriver = new List<Spline> ();
					Corner nq = q.downslope;
					Spline spp = new Spline ();
					spp.point = new Vector2(2*q.point.x-nq.point.x, 2*q.point.y-nq.point.y);
					spp.volume =1;
					oneriver.Add (spp);
					nq=q;
					while (nq.elevation>=waterlimit-0.02f && !rivermade[nq.index]) {
						Spline spl = new Spline ();
						spl.point = nq.point;
						if (nq.coast==true)
							spl.volume=oneriver[oneriver.Count-1].volume;
						else
							spl.volume = nq.river;
						oneriver.Add (spl);
						rivermade[nq.index]=true;
						nq = nq.downslope;
					}
					Spline sp = new Spline ();
					sp.point = nq.point;
					sp.volume = nq.river;
					oneriver.Add (sp);

//					Spline sp1 = new Spline ();
//					sp1.point = nq.downslope.point;
//					sp1.volume = nq.river;
//					oneriver.Add (sp1);
					if(!rivermade[nq.index]){
						rivermade[nq.index]=true;
						Spline spe = new Spline ();
						spe.point = new Vector2(2*nq.downslope.point.x-nq.point.x, 2*nq.downslope.point.y-nq.point.y);
						spe.volume =1;
						oneriver.Add (spe);
					} 
					else
					{					
						Spline sp1 = new Spline ();
						sp1.point = nq.downslope.point;
						sp1.volume = nq.river;
						oneriver.Add (sp1);
					}

					Generate(oneriver.ToArray(),0.2f);
//					if (oneriver.Count>=4)
//						break;
				}
			}
		}
	}
 public static void CreateSplineGameObject(Spline spline)
 {
     GameObject go = new GameObject("Spline");
     SplineWindow sw = go.AddComponent<SplineWindow>();
     sw.handlesColor = SplinePrefs.handlesColor;
     sw.pointColor = SplinePrefs.pointColor;
     sw.selectedColor = SplinePrefs.selectedColor;
     sw.splineColor = SplinePrefs.splineColor;
     sw.splineRefernce = spline;
     sw.spline = Spline.CreateSpline(spline);
     Selection.activeGameObject = go;
 }
Example #3
0
        public static void InitializeSplineAfterCreation(Spline spline)
        {
            spline.Visible = true;

            spline.Name = "Spline";

            FlatRedBall.Utilities.StringFunctions.MakeNameUnique<Spline>(
                spline, mSplineList);

            // Now select this Spline
            EditorData.EditorLogic.CurrentSpline = spline;
        }
Example #4
0
        internal void AddSpline()
        {
            Spline spline = new Spline();

            EditorData.SplineList.Add(spline);

            EditorData.InitializeSplineAfterCreation(spline);
            // Refresh tree view after InitializeSplineAfterCreation 
            // so that the new Spline has a name
            AppCommands.Self.Gui.RefreshTreeView();

        }
Example #5
0
        public Spline ToSpline()
        {
            Spline spline = new Spline();
            spline.Name = Name;

            for (int i = 0; i < Points.Count; i++)
            {
                spline.Add(Points[i].ToSplinePoint());
            }
            spline.Visible = this.Visible;
            return spline;
        }
Example #6
0
	private static void SetupChildren( Spline spline )
	{
		for( int i = 0; i < 4; i++ )
		{
			GameObject newNode = spline.AddSplineNode( );
			
			newNode.name = GetNodeName( i );
			newNode.transform.parent = spline.transform;
			newNode.transform.localPosition = -Vector3.forward * 1.5f + Vector3.forward * i + ( Vector3.right * ((i%3==0) ? 0 : ((i%3) - 1.5f )) );
			newNode.transform.localRotation = Quaternion.identity;
			newNode.transform.localScale = Vector3.one;
		}
	}
Example #7
0
	} ///< Returns the normlaized length of the segment in the spline.
	
	/// <summary>
	/// Initializes a new instance of the <see cref="SplineSegment"/> class.
	/// </summary>
	/// <param name='pSpline'>
	/// The spline that contains the segment.
	/// </param>
	/// <param name='sNode'>
	/// The segment's start node.
	/// </param>
	/// <param name='eNode'>
	/// The segment's end node.
	/// </param>
	/// <exception cref='ArgumentNullException'>
	/// Is thrown when pSpline is null /> .
	/// </exception>
	public SplineSegment( Spline pSpline, SplineNode sNode, SplineNode eNode )
	{
		if( pSpline != null )
		{
			parentSpline = pSpline;
			
			startNode = sNode;
			endNode = eNode;
		}
		else
		{
			throw new ArgumentNullException( "Parent Spline must not be null" );
		}
	}
Example #8
0
        public static SplineSave FromSpline(Spline spline)
        {
            SplineSave toReturn = new SplineSave();

            toReturn.Name = spline.Name;
            
            for (int i = 0; i < spline.Count; i++)
            {
                toReturn.Points.Add(
                    SplinePointSave.FromSplinePoint(spline[i]));
            }

            toReturn.Visible = spline.Visible;

            return toReturn;
        }
Example #9
0
        public void Activity()
        {

            mSplineMoving = EditorData.EditorLogic.CurrentSpline;

            mIsMouseOver = 
                mVisibleRepresentation.Visible &&
                InputManager.Mouse.IsOn3D<Sprite>(mVisibleRepresentation, false);

            MouseControl();

            UpdatePosition();

            UpdateScale();

        }
	private static void SetupChildren( Spline spline )
	{
		GameObject[] childs = new GameObject[4];
		
		for( int i = 0; i < childs.Length; i++ )
		{
			childs[i] = new GameObject( );
			childs[i].name = GetNodeName( i );
			childs[i].transform.parent = spline.transform;
			childs[i].transform.localPosition = -Vector3.forward * 1.5f + Vector3.forward * i;
			childs[i].transform.localRotation = Quaternion.identity;
			childs[i].transform.localScale = Vector3.one;
			
			SplineNode splineNode = childs[i].AddComponent<SplineNode>( );
			
			spline.splineNodesArray.Add( splineNode );
		}
	}
    private bool _drawing;     // Drawing mode active

    public KinectSolidsJig(
      Document doc, Transaction tr, double profRad
    )
    {
      // Initialise the various members

      _doc = doc;
      _tr = tr;
      _vertices = new Point3dCollection();
      _cursor = null;
      _drawing = false;
      _profile = null;
      _sweepOpts = null;
      _path = null;
      _tube = null;
      _profRad = profRad;
      _sweepBroken = false;
    }
		public void Calculate( Spline spline )
		{
			int subsegmentCount = spline.SegmentCount * spline.interpolationAccuracy;
			double invertedAccuracy = 1.0 / spline.interpolationAccuracy;
			
			subSegmentLength = new double[subsegmentCount];
			subSegmentPosition = new double[subsegmentCount];
		
			length = 0.0;
			
			for( int i = 0; i < subsegmentCount; i++ )
			{
				subSegmentLength[i] = 0.0;
				subSegmentPosition[i] = 0.0;
			}
			
			for( int i = 0; i < spline.SegmentCount; i++ )
			{
				for( int j = 0; j < spline.interpolationAccuracy; j++ )
				{
					int index = i * spline.interpolationAccuracy + j;
					
					subSegmentLength[index] = spline.GetSegmentLengthInternal( i * spline.NodesPerSegment, j*invertedAccuracy, (j+1)*invertedAccuracy, 0.2 * invertedAccuracy );
					
					length += subSegmentLength[index];
				}
			}
			
			for( int i = 0; i < spline.SegmentCount; i++ )
			{
				for( int j = 0; j < spline.interpolationAccuracy; j++ )
				{
					int index = i*spline.interpolationAccuracy+j;
					
					subSegmentLength[index] /= length;
					
					if( index < subSegmentPosition.Length-1 )
						subSegmentPosition[index+1] = subSegmentPosition[index] + subSegmentLength[index];
				}
			}
			
			SetupSplinePositions( spline );
		}
Example #13
0
        public SplineCrawler(Spline splineToMoveAlong)
        {
            ConstantVelocityValue = 3;

            mSpline = splineToMoveAlong;

            mVisibleRepresentation = SpriteManager.AddSprite("redball.bmp");
            mVisibleRepresentation.AttachTo(this, false);
            mVisibleRepresentation.ColorOperation = FlatRedBall.Graphics.ColorOperation.Add;
            mVisibleRepresentation.Blue = .5f;

            SpriteManager.AddPositionedObject(this);

            this.Position = mSpline.GetPositionAtTime(0);

            const float scaleMultiplier = 20; // so it pulses big for a sec
            mVisibleRepresentation.ScaleX = mVisibleRepresentation.ScaleY = 
                scaleMultiplier / SpriteManager.Camera.PixelsPerUnitAt(this.Z);

        }
Example #14
0
	void Start() {
		if(!spline)
			if(transform.parent)
				spline = transform.parent.GetComponent<Spline>();
				
		foreach(Transform child in transform) {
			child.gameObject.active = false;
			switch(child.name) {
			case "NextArrow": if(!nextArrow) nextArrow = child.gameObject;	break;
			case "PrevArrow": if(!prevArrow) prevArrow = child.gameObject; break;
			case "node": if(!node) node = child.gameObject; break;
			case "pause": if(!pause) pause = child.gameObject; break;
			case "reverse": if(!reverse) reverse = child.gameObject; break;
			case "stop": if(!stop) stop = child.gameObject; break;
			case "RotationHandle":
				handles = child.gameObject;
				break;
			}
		}
		RefreshModel();
		ReOrient();
	}
Example #15
0
        public static void book01()
        {
            Transaction tr = HostApplicationServices.WorkingDatabase.TransactionManager.StartTransaction();
            BlockTable bt = (BlockTable)tr.GetObject(HostApplicationServices.WorkingDatabase.BlockTableId, OpenMode.ForRead);
            BlockTableRecord btr = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);

            Point3d[] pts = new Point3d[]{
                new Point3d(15.0, 12.0, 0.0),
                new Point3d(30.0, 44.0, 0.0),
                new Point3d(60.0, 10.0, 0.0),
                new Point3d(25.0, 30.0, 0.0)
            };
            Point3dCollection points = new Point3dCollection();
            for (int i = 0; i < 4; i++) {
                points.Add(pts[i]);
            }
            Spline spline = new Spline(points, 4, 0.0);

            btr.AppendEntity(spline);
            tr.AddNewlyCreatedDBObject(spline, true);

            tr.Commit();
            tr.Dispose();
        }
    void Start()
    {
        spline = path.gameObject.GetComponent<Spline>();

        SetLayerRecursively(gameObject, path.gameObject.layer);

        float startParam = Mathf.Clamp( spline.GetClosestPointParam(transform.position, 5), 0f, 1f );

        if (startParam < 0.5f) {
            forward = true;
            lastParam = 0f;
        }
        else {
            forward = false;
            lastParam = 1f;
        }

        offset = Random.Range(0f,0.02f);
        xOffset = Random.Range(-0.4f,0.4f);
        zOffset = Random.Range(-0.4f,0.4f);

        if (Random.Range(1,100) > 10) {
            Transform flag = transform.Find("Flag");
            flag.gameObject.SetActive(false);
        }

        if (!soldier) {
            Color villagerColor =
                new Color(.0549f, 0.3960f, .0941f, 1);

            Renderer r = GetComponent(typeof(Renderer)) as Renderer;
            r.material.SetColor("_Color", villagerColor);
        }

        transform.Find("Flag").GetComponent<FlagHandler>().SetMaterial(owner);
    }
Example #17
0
        // --- Inherited Methods ---
        // Called when the game state is being initiated
        protected override void onInit()
        {
            game.clearColor=	game.getColor("#101820");
            holds=	new bool[6];
            ticks=	new int[1];
            map=	new BattleMap(ref game, this, 24, 24);
            cursorArrow=	new CursorArrow(game, Vector3.Zero);
            currAttackInfo=	new AttackInfo();
            camSpline=	new Spline();
            camTween=	new Tween(0f, 1f, 500f);

            for(int i= 0; i< holds.Length; i++)
                holds[i]=	false;
            for(int i= 0; i< ticks.Length; i++)
                ticks[i]=	0;
            playerTeamID=	0;
            stage=	0;
            prevStage=	0;
            selUnit=	new int[]	{-1, -1};
            map.tiles.forEach(delegate(GridNode<Tile> node, int x, int y)
            {
                node.item=	new Tile(game, new Vector3(-x*Tile.size, 0f, y*Tile.size), ref map);
            });
            //map.createFromBitmap("maps/map_test.bmp");
            map.tiles.items[0, 2].item.startZoneID=	0;
            map.tiles.items[2, 5].item.startZoneID=	0;
            map.tiles.items[1, 5].item.startZoneID=	0;
            map.tiles.items[0, 1].item.startZoneID=	1;

            // Ally team
            map.addTeam(new Team(game, false,
                Unit.create("Paul", game, new Cardinal(game), 30, "undying_morale"),
                Unit.create("George", game, new Berserker(game), 30),
                Unit.create("Lillianna", game, new Cardinal(game), 30, "evil\'s_bane")
            ));

            // Enemy Team
            map.addTeam(new Team(game, true,
                Unit.create("Terrence", game, new Berserker(game), 30),
                Unit.create("Gjoran", game, new Samurai(game), 30),
                Unit.create("Lorance", game, new Cardinal(game), 30),
                Unit.create("Monte", game, new Cardinal(game), 30)
            ), true);

            map.injectTeams();

            forward=	new Vector3(0f, -256f/((float)(Math.Tan(GSGameplay.deg30)+Math.Tan(3.14159f/12f))), 0f);
            forward.Z=	-1f*(float)(forward.Y*Math.Tan(GSGameplay.deg30));

            game.cameras.current.target=	new Vector3(0f, 0f, 512f);
            game.cameras.current.pos=	new Vector3(0f, 512f, 0f);
            camSel=	new int[]	{ map.width/2, map.height/2 };
            moveCameraTo(5, 5);

            isPlayer=	false;
            isUsingGamepad=	false;
            bCenterOverride=	false;

            setupGui();
        }
Example #18
0
    bool FindNextSpline(Vector3 position, Vector3 velocity, Vector3 acceleration, out Vector3 landing, out bool landed, out int traveltime)
    {
#if (DEBUG_LOG)
        Debug.Log("findNextSpline");
#endif
        traveltime = 0;
        if (predictionStep > 0)
        {
            Vector3    tmpvel = velocity;
            RaycastHit hit;
            Vector3    curr;
            bool       found = false;
            int        x;
            for (x = 0; x < predictionLength; x += predictionStep)
            {
                tmpvel     += acceleration * Time.fixedDeltaTime * predictionStep;
                curr        = position + tmpvel * Time.fixedDeltaTime * predictionStep;
                traveltime += predictionStep;
                //Debug.DrawLine(position, curr);
                if (Physics.Linecast(position, curr, out hit, 1 << SplineTopLayer))
                {
                    found = true;
                    break;
                }
                if (found)
                {
                    break;
                }
                position = curr;
            }
            if (x == 0)                         //This means that the first cast hit the collider
            {
                for (int i = 0; i < predictionStep; i++)
                {
                    tmpvel += acceleration * Time.fixedDeltaTime;
                    //Do we really want to do this?
                    snapDistance = tmpvel.magnitude * Time.fixedDeltaTime;
                    curr         = position + tmpvel * Time.fixedDeltaTime;
                    traveltime++;
                    if (Physics.Linecast(position, curr, out hit, 1 << SplineTopLayer))
                    {
                        // Debug.Log(zPlane.print());
                        if (i == 0)                             //This means that we'll land there this frame.
                        //projectedPosition = last;
                        //						if(currentSplineSource)
                        //							currentSplineSource.followers.Remove(this);
                        //Search despearately for the spline
                        {
                            if (hit.transform.parent)
                            {
                                currentSpline = hit.transform.parent.GetComponent <Spline>();
                            }
                            else
                            {
                                currentSpline = hit.transform.GetComponent <Spline>();
                            }
                            if (!currentSpline)
                            {
                                currentSpline = hit.transform.GetComponentInChildren <Spline>();
                            }
                            if (currentSpline)
                            {
                                currentSpline.followers.Add(this);
                                transform.parent = currentSpline.transform;
                                //projectedPosition.z = currentSpline.transform.position.z;
                                if (FindSplineVertex(currentSpline, position, curr, out groundNode, out landing))
                                {
                                    landed = true;
                                }
                                else
                                {
                                    landed = false;
                                    Debug.LogWarning("Error in findNextSpline - Couldn't Land");
                                }
                                return(true);
                            }
                        }
                    }
                }
            }
        }
        else
        {
            Debug.LogError("cannot find next spline, prediction step < 1!");
        }
        landing = Vector3.zero;
        landed  = false;
        return(false);
    }
Example #19
0
 public bool FindSplineVertex(Spline s, Vector3 a, Vector3 b, out SplineNode vert, out Vector3 position)
 {
     return(FindSplineVertex(s, a, b, null, out vert, out position));
 }
 private void OnEnable()
 {
     spline = GetComponent <Spline>();
     spline.NodeCountChanged.AddListener(() => toUpdate = true);
 }
Example #21
0
 /// <summary>
 /// Sets the movement to continue at a new position
 /// </summary>
 /// <param name="segment">the segment to continue movement on</param>
 /// <param name="localF">the local F within that segment</param>
 public void SetPosition(CurvySplineSegment segment, float localF = 0)
 {
     ControlPoint = segment;
     Spline       = segment.Spline;
     TF           = Spline.SegmentToTF(ControlPoint, localF);
 }
Example #22
0
 public float GetLevel(float linearizedFrequency, InterpolationMode interpolationMode)
 {
     return(Spline.Tween(linearizedFrequency, normalizedLevels, false, interpolationMode));
 }
Example #23
0
 public void RemoveSpline(Spline s)
 {
     _connectedSplines.Remove(s);
 }
Example #24
0
        private void DrawSelectedSplineHandle(Spline instance, int point_index)
        {
            var splinePoint = instance.Points[point_index];


            Handles.color = Color.white;

            var anyMoved         = false;
            var anyRotated       = false;
            var anyScaled        = false;
            var splinePointDelta = Vector3.zero;

            if (instance.GetSplineSpace() == Space.Self)
            {
                splinePoint = instance.TransformSplinePoint(splinePoint);
            }

            switch (Tools.current)
            {
            case Tool.Move:
                anyMoved = DrawHandle(Vector3.zero, ref splinePoint.position, out splinePointDelta);
                break;

            case Tool.Rotate:
                anyRotated = DrawHandleRotation(splinePoint.position, ref splinePoint.rotation);
                break;

            case Tool.Scale:
                anyScaled = DrawHandleScale(splinePoint.position, ref splinePoint.scale);
                break;
            }

            if (instance.GetSplineSpace() == Space.Self)
            {
                splinePoint = instance.InverseTransformSplinePoint(splinePoint);
            }

            if (anyMoved || anyRotated || anyScaled)
            {
                Undo.RegisterCompleteObjectUndo(instance, "Move Point");

                var original_point = instance.Points[point_index];
                instance.Points[point_index] = splinePoint;
                instance.EnsureSplineStaysClosed();

                if (LockHandleLength)
                {
                    var pointIsHandle = SplinePoint.IsHandle(instance.GetSplineMode(), point_index);
                    if (pointIsHandle)
                    {
                        var anchor_index = SplinePoint.GetAnchorIndex(instance.GetSplineMode(), point_index);
                        var anchor_point = instance.Points[anchor_index];

                        var to_anchor  = splinePoint.position - anchor_point.position;
                        var dir_anchor = to_anchor.normalized;

                        splinePoint.position         = anchor_point.position + dir_anchor * LockedHandleLength;
                        instance.Points[point_index] = splinePoint;
                    }
                }

                UpdateHandlesWhenPointMoved(instance, point_index, splinePointDelta);

                if (anyMoved)
                {
                    var delta_move = splinePoint.position - original_point.position;

                    for (var i = 0; i < SelectedPoints.Count; ++i)
                    {
                        var other_index = SelectedPoints[i];
                        if (other_index == point_index)
                        {
                            continue;
                        }

                        UpdateHandlesWhenPointMoved(instance, other_index, splinePointDelta);

                        instance.Points[other_index].position += delta_move;
                    }

                    Repaint();
                }

                if (anyRotated)
                {
                    var delta_rotation = Quaternion.Inverse(original_point.rotation) * splinePoint.rotation;

                    for (var i = 0; i < SelectedPoints.Count; ++i)
                    {
                        var other_index = SelectedPoints[i];
                        if (other_index == point_index)
                        {
                            continue;
                        }
                        instance.Points[other_index].rotation *= delta_rotation;
                    }

                    Repaint();
                }

                if (anyScaled)
                {
                    var delta_scale = splinePoint.scale - original_point.scale;

                    for (var i = 0; i < SelectedPoints.Count; ++i)
                    {
                        var other_index = SelectedPoints[i];
                        if (other_index == point_index)
                        {
                            continue;
                        }
                        instance.Points[other_index].scale += delta_scale;
                    }

                    Repaint();
                }

                instance.UpdateNative();
            }
        }
Example #25
0
 private void InsertPoint(Spline instance, SplinePoint placingPoint)
 {
     Undo.RecordObject(instance, "Inserting point.");
     instance.InsertPoint(placingPoint);
 }
Example #26
0
        private void DrawPlacePointView(Spline instance)
        {
            Handles.color = Color.red;

            // per place type handles?
            if (PlaceMode == SplinePlacePointMode.Plane)
            {
                DrawPlacePlane();

                switch (Tools.current)
                {
                case Tool.Move:
                    Undo.RecordObject(this, "Moving Place Plane");
                    var moved = DrawHandle(Vector3.zero, ref PlacePlaneOffset, out Vector3 offsetDelta);


                    // PlacePlaneOffset += offsetDelta;
                    break;

                case Tool.Rotate:
                    Undo.RecordObject(this, "Rotating Place Plane");
                    DrawHandleRotation(PlacePlaneOffset, ref PlacePlaneNormalRotation);

                    var normal = PlacePlaneNormalRotation * Vector3.forward;

                    Handles.color = Color.green;
                    Handles.DrawLine(PlacePlaneOffset, PlacePlaneOffset + normal);

                    break;
                }
            }

            // block scene input
            if (Event.current.type == EventType.Layout)
            {
                HandleUtility.AddDefaultControl(GUIUtility.GetControlID(GetHashCode(), FocusType.Passive));
            }

            // try finding point
            var validPoint = TryGetPointFromMouse(instance, out SplinePoint placingPoint);

            if (!validPoint)
            {
                return;
            }

            // draw preview spline
            if (PlaceMode != SplinePlacePointMode.InsertBetweenPoints)
            {
                // keep a copy so we can revert the operation
                var points_clone = (SplinePoint[])instance.Points.Clone();

                // perform the operation
                AppendPoint(instance, placingPoint.position, placingPoint.rotation, placingPoint.scale);

                // draw
                Handles.color = Color.white * 0.9f;
                instance.DrawAsHandles();

                // then undo it
                instance.Points = points_clone;
            }

            // show button
            DrawSquareGUI(placingPoint.position, Color.white);

            // try placing it
            if (IsLeftMouseClicked())
            {
                if (PlaceMode == SplinePlacePointMode.InsertBetweenPoints)
                {
                    InsertPoint(instance, placingPoint);
                }
                else
                {
                    AppendPoint(instance, placingPoint.position, placingPoint.rotation, placingPoint.scale);
                }

                Event.current.Use();
                Repaint();
            }
        }
Example #27
0
        private bool TryGetPointFromMouse(Spline instance, out SplinePoint point)
        {
            var mousePosition = Event.current.mousePosition;
            var worldRay      = HandleUtility.GUIPointToWorldRay(mousePosition);

            switch (PlaceMode)
            {
            case SplinePlacePointMode.CameraPlane:
                var position = worldRay.origin + worldRay.direction * 1f;     // * Camera.current.nearClipPlane;
                var up       = Vector3.up;
                point = new SplinePoint(position + worldRay.direction * PlaceOffsetFromSurface, Quaternion.LookRotation(worldRay.direction, Vector3.up), Vector3.one);
                return(true);

            case SplinePlacePointMode.Plane:
                var placePlaneNormal = PlacePlaneNormalRotation * Vector3.up;
                placePlaneNormal = placePlaneNormal.normalized;

                var offsetOnNormal = Vector3.ProjectOnPlane(PlacePlaneOffset, placePlaneNormal);
                var offsetDistance = offsetOnNormal.magnitude;

                var denom = Vector3.Dot(placePlaneNormal, worldRay.direction);
                if (Mathf.Abs(denom) <= 0.0001f)
                {
                    point = new SplinePoint();
                    return(false);
                }

                var rayDistanceToPlane = -(Vector3.Dot(placePlaneNormal, worldRay.origin) + offsetDistance) / denom;
                if (rayDistanceToPlane <= 0.0001f)
                {
                    point = new SplinePoint();
                    return(false);
                }

                var pointPos = worldRay.origin + rayDistanceToPlane * worldRay.direction;
                pointPos += placePlaneNormal * PlaceOffsetFromSurface;

                point = new SplinePoint(pointPos, PlacePlaneNormalRotation, Vector3.one);

                return(true);

            case SplinePlacePointMode.MeshSurface:

                // HandleUtility.PickGameObject only works in certain event types, so we need to cache the result to use between event types
                if (Event.current.type == EventType.MouseMove || Event.current.type == EventType.MouseDown)
                {
                    var go = HandleUtility.PickGameObject(mousePosition, false);
                    if (go != null)
                    {
                        var hit = RXLookingGlass.IntersectRayGameObject(worldRay, go, out RaycastHit info);
                        if (hit)
                        {
                            previousMeshPoint0 = info.point;
                            previousMeshPoint1 = info.point + info.normal.normalized * PlaceOffsetFromSurface;

                            point = new SplinePoint(info.point + info.normal.normalized * PlaceOffsetFromSurface, Quaternion.LookRotation(info.normal, Vector3.up), Vector3.one);
                            previousMeshSurfacePoint    = point;
                            hasPreviousMeshSurfacePoint = true;
                            return(true);
                        }
                    }
                    else
                    {
                        previousMeshSurfacePoint    = new SplinePoint();
                        hasPreviousMeshSurfacePoint = false;
                    }
                }

                Handles.color = Color.white;
                Handles.DrawLine(previousMeshPoint0, previousMeshPoint1);

                point = previousMeshSurfacePoint;
                return(hasPreviousMeshSurfacePoint);

            case SplinePlacePointMode.CollisionSurface:
                RaycastHit collisionInfo;
                var        collisionHit = Physics.Raycast(worldRay, out collisionInfo, 256f, PlaceLayerMask, QueryTriggerInteraction.Ignore);
                if (collisionHit)
                {
                    if (SnapToNearestVert && collisionInfo.triangleIndex >= 0)
                    {
                        var meshFilter = collisionInfo.collider.GetComponent <MeshFilter>();
                        var mesh       = meshFilter.sharedMesh;

                        var localToWorld = meshFilter.transform.localToWorldMatrix;

                        var vertices = mesh.vertices;
                        var normals  = mesh.normals;

                        var triangles = mesh.triangles;
                        var triIndex  = collisionInfo.triangleIndex;

                        var vertIndex0 = triangles[triIndex * 3 + 0];
                        var vertIndex1 = triangles[triIndex * 3 + 1];
                        var vertIndex2 = triangles[triIndex * 3 + 2];

                        var vertex0 = localToWorld.MultiplyPoint(vertices[vertIndex0]);
                        var vertex1 = localToWorld.MultiplyPoint(vertices[vertIndex1]);
                        var vertex2 = localToWorld.MultiplyPoint(vertices[vertIndex2]);

                        var normal0 = localToWorld.MultiplyVector(normals[vertIndex0]);
                        var normal1 = localToWorld.MultiplyVector(normals[vertIndex1]);
                        var normal2 = localToWorld.MultiplyVector(normals[vertIndex2]);

                        var distance0 = Vector3.Distance(vertex0, collisionInfo.point);
                        var distance1 = Vector3.Distance(vertex1, collisionInfo.point);
                        var distance2 = Vector3.Distance(vertex2, collisionInfo.point);

                        var rotation0 = Quaternion.LookRotation(normal0, Vector3.up);
                        var rotation1 = Quaternion.LookRotation(normal1, Vector3.up);
                        var rotation2 = Quaternion.LookRotation(normal2, Vector3.up);

                        if (distance0 < distance1 && distance0 < distance2)
                        {
                            Handles.color = Color.white;
                            Handles.DrawLine(vertex0, vertex0 + normal0 * PlaceOffsetFromSurface);

                            point = new SplinePoint(vertex0 + normal0 * PlaceOffsetFromSurface, rotation0, Vector3.one);
                        }
                        else if (distance1 < distance0 && distance1 < distance2)
                        {
                            Handles.color = Color.white;
                            Handles.DrawLine(vertex1, vertex1 + normal1 * PlaceOffsetFromSurface);

                            point = new SplinePoint(vertex1 + normal1 * PlaceOffsetFromSurface, rotation1, Vector3.one);
                        }
                        else
                        {
                            Handles.color = Color.white;
                            Handles.DrawLine(vertex2, vertex2 + normal2 * PlaceOffsetFromSurface);

                            point = new SplinePoint(vertex2 + normal2 * PlaceOffsetFromSurface, rotation2, Vector3.one);
                        }

                        return(true);
                    }
                    else
                    {
                        Handles.color = Color.white;
                        Handles.DrawLine(collisionInfo.point, collisionInfo.point + collisionInfo.normal * PlaceOffsetFromSurface);

                        point = new SplinePoint(collisionInfo.point + collisionInfo.normal * PlaceOffsetFromSurface, Quaternion.LookRotation(collisionInfo.normal, Vector3.up), Vector3.one);
                        return(true);
                    }
                }
                else
                {
                    point = new SplinePoint();
                    return(false);
                }

            case SplinePlacePointMode.InsertBetweenPoints:

                var sceneCam = SceneView.currentDrawingSceneView.camera;
                point = instance.ProjectOnSpline(sceneCam, sceneCam.WorldToScreenPoint(worldRay.origin));
                return(true);
            }

            point = new SplinePoint();
            return(false);
        }
Example #28
0
        private void DrawPointSelectorInspector(Spline spline)
        {
            var selectedPointButtonSb = new System.Text.StringBuilder();

            var selected_none = SelectedPoints.Count == 0;
            var selected_all  = SelectedPoints.Count == spline.Points.Length;

            if (selected_none)
            {
                selectedPointButtonSb.Append("No points selected.");
            }
            else if (selected_all)
            {
                selectedPointButtonSb.Append("All points selected.");
            }
            else
            {
                selectedPointButtonSb.Append("Selected: ");

                for (var i = 0; i < SelectedPoints.Count; ++i)
                {
                    var pointIndex = SelectedPoints[i];
                    var pointName  = GetPointName(spline, pointIndex);
                    selectedPointButtonSb.Append($"{pointName}");

                    if (i < SelectedPoints.Count - 1)
                    {
                        selectedPointButtonSb.Append($", ");
                    }
                }
            }

            if (GUILayout.Button(selectedPointButtonSb.ToString()))
            {
                Undo.RecordObject(this, "Point Selection");

                var selectedMenu = new GenericMenu();

                selectedMenu.AddItem(new GUIContent("Select All"), selected_all, OnAllPointsSelected, spline);
                selectedMenu.AddItem(new GUIContent("Select None"), selected_none, OnNoPointsSelected);

                var length = spline.Points.Length;
                if (spline.GetSplineClosed())
                {
                    switch (spline.GetSplineMode())
                    {
                    case SplineMode.Linear:
                        length -= 1;
                        break;

                    case SplineMode.Bezier:
                        length -= 3;
                        break;
                    }
                }

                for (var i = 0; i < length; ++i)
                {
                    var splinePoint = spline.Points[i];

                    var menuString    = GetPointName(spline, i);
                    var pointSelected = SelectedPoints.Contains(i);

                    selectedMenu.AddItem(new GUIContent(menuString), pointSelected, OnPointSelected, i);
                }

                selectedMenu.ShowAsContext();
            }
        }
Example #29
0
        private void DrawSelectablePoints(Spline instance)
        {
            var first_selected_point = SelectedPoints.Count > 0 ? SelectedPoints[0] : -1;

            var length = instance.Points.Length;

            if (instance.GetSplineClosed())
            {
                switch (instance.GetSplineMode())
                {
                case SplineMode.Linear:
                    length -= 1;
                    break;

                case SplineMode.Bezier:
                    length -= 3;
                    break;

                case SplineMode.BSpline:
                    length -= 1;
                    break;
                }
            }

            for (var p = 0; p < length; ++p)
            {
                if (p == first_selected_point)
                {
                    // if the selected point is a handle, we still need to draw its line from the handle to the anchor
                    if (p % 3 != 0)
                    {
                        TryDrawHandleToAnchorLine(instance, p);
                    }

                    continue;
                }

                var point = instance.Points[p];

                if (instance.GetSplineSpace() == Space.Self)
                {
                    point = instance.TransformSplinePoint(point);
                }

                var position = point.position;
                var isHandle = instance.GetSplineMode() == SplineMode.Bezier && p % 3 != 0;

                if (isHandle)
                {
                    // when nothing is selected, do not draw handles
                    if (first_selected_point == -1)
                    {
                        continue;
                    }


                    // when a handle is selected, we only want to draw the other handle touching our center point
                    var isSelectedHandle = first_selected_point % 3 != 0;
                    if (isSelectedHandle)
                    {
                        var handleIndex = p % 3;
                        if (handleIndex == 1)
                        {
                            var parentPoint = p - 2;
                            if (parentPoint != first_selected_point)
                            {
                                continue;
                            }
                        }
                        else
                        {
                            var parentPoint = p + 2;
                            if (parentPoint != first_selected_point)
                            {
                                continue;
                            }
                        }

                        TryDrawHandleToAnchorLine(instance, p);
                    }

                    // but if its a point selected, we want to draw both handles
                    else
                    {
                        if (p < first_selected_point - 1 || p > first_selected_point + 1)
                        {
                            continue;
                        }

                        TryDrawHandleToAnchorLine(instance, p);
                    }
                }

                var sceneView   = SceneView.currentDrawingSceneView;
                var sceneCamera = sceneView.camera;
                var screenPoint = sceneCamera.WorldToScreenPoint(position);
                screenPoint.z = 10f;

                var cameraPoint = sceneCamera.ScreenToWorldPoint(screenPoint);

                Handles.color = SelectedPoints.Contains(p) ? Color.white : isHandle ? Color.green : Color.blue;
                var selected = Handles.Button(cameraPoint, Quaternion.identity, .1f, .1f, Handles.DotHandleCap);
                if (selected)
                {
                    Undo.RegisterCompleteObjectUndo(this, "Selected Point");

                    // select a new point
                    var select_multiple = Event.current.modifiers == EventModifiers.Control;

                    if (select_multiple)
                    {
                        if (!SelectedPoints.Contains(p))
                        {
                            SelectedPoints.Add(p);
                        }
                        else
                        {
                            SelectedPoints.Remove(p);
                        }
                    }
                    else
                    {
                        SelectedPoints.Clear();
                        SelectedPoints.Add(p);
                    }

                    Repaint();
                }
            }
        }
		private void InsertNode (Spline spline, float splineParam)
		{
				SplineNode splineNode = CreateSplineNode ("New Node", spline.GetPositionOnSpline (splineParam), spline.GetOrientationOnSpline (splineParam), spline.transform);
				SplineSegment segment = spline.GetSplineSegment (splineParam);
		
				int startNodeIndex = spline.splineNodesArray.IndexOf (segment.StartNode);
		
				spline.splineNodesArray.Insert (startNodeIndex + 1, splineNode);
		}
		private void DrawHandles (Spline spline)
		{
				if (Event.current.alt || EditorGUI.actionKey)
						return;
		
				if (Tools.current == Tool.None || Tools.current == Tool.View)
						return;
		
				Handles.lighting = true;
		
				foreach (SplineNode node in spline.SplineNodes) {
						switch (Tools.current) {
						case Tool.Rotate:
								Undo.SetSnapshotTarget (node.transform, "Rotate Spline Node: " + node.name);
				
								Quaternion newRotation = Handles.RotationHandle (node.Rotation, node.Position);
				
								Handles.color = new Color (.2f, 0.4f, 1f, 1);
								Handles.ArrowCap (0, node.Position, Quaternion.LookRotation (node.transform.forward), HandleUtility.GetHandleSize (node.Position) * 0.5f);
								Handles.color = new Color (.3f, 1f, .20f, 1);
								Handles.ArrowCap (0, node.Position, Quaternion.LookRotation (node.transform.up), HandleUtility.GetHandleSize (node.Position) * 0.5f);
								Handles.color = Color.white;
				
								if (!GUI.changed)
										break;
				
								node.Rotation = newRotation;
				
								EditorUtility.SetDirty (target);
				
								break;
				
						case Tool.Move:
						case Tool.Scale: 
								Undo.SetSnapshotTarget (node.transform, "Move Spline Node: " + node.name);
				
								Vector3 newPosition = Handles.PositionHandle (node.Position, (Tools.pivotRotation == PivotRotation.Global) ? Quaternion.identity : node.transform.rotation);
				
								if (!GUI.changed)
										break;
				
								node.Position = newPosition;
				
								EditorUtility.SetDirty (target);
				
								break;
						}
			
						CreateSnapshot ();
				}
		}
Example #32
0
        private void UpdateHandlesWhenPointMoved(Spline instance, int point_index, Vector3 move_delta)
        {
            var splinePoint = instance.Points[point_index];

            if (instance.GetSplineMode() == SplineMode.Bezier)
            {
                var pointIsHandle = point_index % 3 != 0;
                if (pointIsHandle)
                {
                    var pointIndex0 = point_index - point_index % 3 + 0;
                    var pointIndex1 = point_index - point_index % 3 + 3;

                    var index = point_index % 3 == 1 ? pointIndex0 : pointIndex1;

                    if (index < 0 || index >= instance.Points.Length)
                    {
                        return;
                    }

                    var anchorPoint = instance.Points[index];

                    Handles.color = Color.gray;
                    Handles.DrawLine(splinePoint.position, anchorPoint.position);


                    if (MirrorAnchors && point_index != 1 && point_index != instance.Points.Length - 2)
                    {
                        var otherHandleIndex = index == pointIndex0
                            ? pointIndex0 - 1
                            : pointIndex1 + 1;

                        var otherHandlePoint = instance.Points[otherHandleIndex];

                        var toAnchorPoint       = anchorPoint.position - splinePoint.position;
                        var otherHandlePosition = anchorPoint.position + toAnchorPoint;
                        otherHandlePoint.position         = otherHandlePosition;
                        instance.Points[otherHandleIndex] = otherHandlePoint;

                        Handles.DrawLine(otherHandlePoint.position, anchorPoint.position);
                    }
                }
                else
                {
                    if (instance.Points.Length > 1)
                    {
                        var handleIndex0 = point_index != 0 ? point_index - 1 : point_index + 1;
                        var handleIndex1 = point_index != instance.Points.Length - 1 ? point_index + 1 : point_index - 1;

                        var handle0 = instance.Points[handleIndex0];
                        var handle1 = instance.Points[handleIndex1];

                        handle0.position = handle0.position + move_delta;
                        handle1.position = handle1.position + move_delta;

                        // only update these if they are not also selected
                        if (!SelectedPoints.Contains(handleIndex0))
                        {
                            instance.Points[handleIndex0] = handle0;
                        }
                        if (!SelectedPoints.Contains(handleIndex1))
                        {
                            instance.Points[handleIndex1] = handle1;
                        }

                        Handles.color = Color.gray;
                        Handles.DrawLine(splinePoint.position, handle0.position);
                        Handles.DrawLine(splinePoint.position, handle1.position);
                    }
                }
            }
        }
Example #33
0
        /// <summary>
        ///  Home-grown offsetter that can handle open paths (which clipper can't)
        ///  and returns paths for left and right.
        /// </summary>
        /// <returns>The offsets.</returns>
        /// <param name="planSpline">Plan spline.</param>
        /// <param name="thickR">Thick r.</param>
        /// <param name="thickL">Thick l.</param>
        public static Paths  wallOffsets(Spline planSpline, float thickR, float thickL)
        {
            /*
             *      When generating a PlanSweep, we need to know the breaking angles of each plan layer.
             *      This is because the original plan node might be convex at a certain section offset, it is concave, depending on how far out that section goes.
             *
             *      To do this:
             *      1. for each section node, do an offset using clipper - or use bevelAngles of the orginnal plan and make a new spline, whichever is more efficient
             *      2. store these offset plans as AX.Splines in a list.
             *      3. use these Splines for the isSharp and isBlend conditionals
             *
             */

            if (planSpline == null || planSpline.controlVertices == null || planSpline.controlVertices.Count == 0)
            {
                return(null);
            }


//			if (tex == null)
//				return null;



            Paths paths = new Paths();

            Path pathR = new Path();
            Path pathL = new Path();

            float samePointTolerence = .001f;


            int terminIndexSubtractor = 0;

            if (Vector2.Distance(planSpline.controlVertices[0], planSpline.controlVertices[planSpline.controlVertices.Count - 1]) < samePointTolerence)
            {
                terminIndexSubtractor = 1;
            }


            Matrix4x4 prevBevelTransform;

            for (int i = 0; i < planSpline.controlVertices.Count - terminIndexSubtractor; i++)
            {
                Matrix4x4 bevelTransform = planSpline.nodeTransforms[i];

                if (planSpline.shapeState == ShapeState.Open)
                {
                    if (i == 0)
                    {
                        bevelTransform = planSpline.begTransform;
                    }
                    else if (i == planSpline.controlVertices.Count - 1)
                    {
                        bevelTransform = planSpline.endTransform;
                    }
                }


                // Transform plan vert
                Vector3 vertr = bevelTransform.MultiplyPoint(new Vector3(thickR, 0, 0));
                Debug.Log(vertr);

                pathR.Add(Pather.Vector2IPWithPrecision(new Vector2(vertr.x, vertr.z)));

                Vector3 vertl = bevelTransform.MultiplyPoint(new Vector3(thickL, 0, 0));
                pathL.Add(Pather.Vector2IPWithPrecision(new Vector2(vertl.x, vertl.z)));
            }

            paths.Add(pathR);
            paths.Add(pathL);

            return(paths);
        }
Example #34
0
        public IInkStroke CreateStroke(Spline newSpline, IInkStroke originalStroke, int firstPointIndex, int pointsCount)
        {
            VectorInkStroke stroke = new VectorInkStroke(newSpline, originalStroke, firstPointIndex, pointsCount);

            return(stroke);
        }
Example #35
0
 /// <summary>
 /// Initializes a new instance of the <see cref="EditSplineAction"/> class.
 /// </summary>
 /// <param name="spline">The spline.</param>
 /// <param name="before">The spline keyframes state before editing it.</param>
 public EditSplineAction(Spline spline, BezierCurve <Transform> .Keyframe[] before)
 {
     _splineId = spline.ID;
     _before   = before;
     _after    = (BezierCurve <Transform> .Keyframe[])spline.SplineKeyframes.Clone();
 }
Example #36
0
    private void OnEnable()
    {
        spline = GetComponent <Spline>();

        controls.Player.Enable();
    }
    void Update()
    {
        List <Vector3> pList = new List <Vector3>();

        for (int i = 0; i < GetComponent <Transform>().childCount; i++)
        {
            if (GetComponent <Transform>().GetChild(i).gameObject.activeSelf)
            {
                pList.Add(GetComponent <Transform>().GetChild(i).position);
            }
        }
        Vector3[] pArray = pList.ToArray();

        Spline spline = new Spline(pArray);

        spline.SetRMFStartNormal(Vector3.up);
        spline.SetRMFEndNormal(Vector3.up);
        spline.ComputeRotationMinimizingFrames();

        int     nSample = 100;
        Vector3 pOut;
        Vector3 prevpOut = pArray[0];

        for (int i = 0; i < nSample + 1; i++)
        {
            float t = ((1f / nSample) * i);
            pOut = spline.GetPointOnSpline(t);
            Debug.DrawLine(prevpOut, pOut, Color.yellow);
            prevpOut = pOut;
            Vector3 tOut = spline.GetTangentToPointOnSpline(t).normalized;
            Debug.DrawRay(pOut, tOut, Color.cyan);
            Vector3 nOut = spline.DefaultGetNormalAtT(t);
            Debug.DrawRay(pOut, nOut * 2, Color.red);
        }
        //Debug.DrawLine(spline.GetPointOnSpline(0.84f), Vector3.zero, Color.red);
        //Debug.DrawLine(spline.GetPointOnSpline(0.8f), Vector3.zero, Color.red);

        count++;
        if (count < 2)
        {
            string meshName = "mesh-" + gameObject.name;
            //GameObject prefabCyl = Resources.Load("Prefabs/" + "test/testz") as GameObject;
            GameObject prefabCyl = Resources.Load("Prefabs/MazeBar-20-X/MazeBar-20-1") as GameObject;
            if (GameObject.Find(meshName) != null)
            {
                Destroy(GameObject.Find(meshName));
            }
            obj      = Instantiate(prefabCyl, GameObject.Find("holderobj").transform) as GameObject;
            obj.name = meshName;

            Utilities.MeshResize(obj, new Vector3(2, .2f, 1));
            //Utilities.MeshReplicate(obj, 1, Vector3.forward);
            //obj.transform.rotation = Quaternion.Euler(0, 90, 0);
            obj.AddComponent(typeof(SplineFittedMesh));
            SplineFittedMesh sfMesh = obj.GetComponent <SplineFittedMesh>();
            //sfMesh.SetSplineAxis(new Vector3(0, 0, 1f));
            sfMesh.SetSplineAxis(new Vector3(0, 0, 1));
            sfMesh.SetSpline(spline);
            Mesh mesh = obj.GetComponent <MeshFilter>().mesh;
            sfMesh.SetMeshBase(mesh);
        }
    }
 public bool FindNextSplineMouse(out Vector3 position, Vector3 point)
 {
     RaycastHit hit;
     if(Physics.Raycast(point, Vector3.down, out hit, snapDistance, 1 << SplineTopLayer)) {
         if(hit.transform.parent.GetComponent<Spline>()) {
             currentSpline = hit.transform.parent.GetComponent<Spline>();
             if(FindSplineVertex(currentSpline, point, point + Vector3.down * snapDistance, out groundNode, out position)) {
                 return true;
             }
         }
     }
     position = Vector3.zero;
     return false;
 }
 bool FindNextSpline(Vector3 position, Vector3 velocity, Vector3 acceleration, out Vector3 landing, out bool landed, out int traveltime)
 {
     #if (DEBUG_LOG)
     Debug.Log("findNextSpline");
     #endif
     traveltime = 0;
     if(predictionStep > 0) {
         Vector3 tmpvel = velocity;
         RaycastHit hit;
         Vector3 curr;
         bool found = false;
         int x;
         for(x = 0; x < predictionLength; x += predictionStep) {
             tmpvel += acceleration * Time.fixedDeltaTime * predictionStep;
             curr = position + tmpvel * Time.fixedDeltaTime * predictionStep;
             traveltime += predictionStep;
             //Debug.DrawLine(position, curr);
             if(Physics.Linecast(position, curr, out hit, 1 << SplineTopLayer)) {
                 found = true;
                 break;
             }
             if(found)
                 break;
             position = curr;
         }
         if(x == 0) {		//This means that the first cast hit the collider
             for(int i = 0; i < predictionStep; i++) {
                 tmpvel += acceleration * Time.fixedDeltaTime;
                 //Do we really want to do this?
                 snapDistance = tmpvel.magnitude * Time.fixedDeltaTime;
                 curr = position + tmpvel * Time.fixedDeltaTime;
                 traveltime++;
                 if(Physics.Linecast(position, curr, out hit, 1 << SplineTopLayer)) {
                     // Debug.Log(zPlane.print());
                     if(i == 0) {	//This means that we'll land there this frame.
                         //projectedPosition = last;
                         //						if(currentSplineSource)
                         //							currentSplineSource.followers.Remove(this);
                         //Search despearately for the spline
                         if(hit.transform.parent)
                             currentSpline = hit.transform.parent.GetComponent<Spline>();
                         else
                             currentSpline = hit.transform.GetComponent<Spline>();
                         if(!currentSpline)
                             currentSpline = hit.transform.GetComponentInChildren<Spline>();
                         if(currentSpline) {
                             currentSpline.followers.Add(this);
                             transform.parent = currentSpline.transform;
                             //projectedPosition.z = currentSpline.transform.position.z;
                             if(FindSplineVertex(currentSpline, position, curr, out groundNode, out landing)) {
                                 landed = true;
                             } else {
                                 landed = false;
                                 Debug.LogWarning("Error in findNextSpline - Couldn't Land");
                             }
                             return true;
                         }
                     }
                 }
             }
         }
     } else Debug.LogError("cannot find next spline, prediction step < 1!");
     landing = Vector3.zero;
     landed = false;
     return false;
 }
Example #40
0
 void Awake()
 {
     _spline     = this.GetComponent <Spline>();
     cycleLength = 1f / numberOfPoints;
 }
Example #41
0
    bool FindSplineVertex(Spline s, Vector3 a, Vector3 b, SplineNode guess, out SplineNode vert, out Vector3 position)
    {
        SplineNode countup, countdown;

        if (s != null)
        {
            if (guess == null)
            {
                if (!(s.begin && s.end))
                {
                    Debug.LogError("Could not find vertex, begin and end not set");
                    vert     = null;
                    position = Vector3.zero;
                    return(false);
                }
                countup   = s.begin;
                countdown = s.end;
            }
            else
            {
                countdown = guess;
                countup   = guess;
            }
            Utility.Vector3Pair points;
            while (countdown != null || countup != null)
            {
                if (countup.next != null)
                {
                    //#if(DEBUG_DRAW||DEBUG_DRAW_LND)
                    Debug.DrawLine(countup.transform.position, countup.next.transform.position, Color.magenta);
                    //#endif
                    points = Utility.Dist3DSegToSeg(a, b, countup.transform.position, countup.next.transform.position);
                    if ((points.a - points.b).magnitude < snapDistance)
                    {
                        //Debug.Log(points.a + ", " + points.b);
                        Debug.DrawLine(points.b, transform.position, Color.magenta);
                        vert = countup;
                        if (looseFollow)
                        {
                            position = transform.position;
                        }
                        else
                        {
                            position = points.b;
                        }
                        return(true);
                    }
                }
                countup = countup.next;
                if (countdown.previous != null)
                {
                    //#if(DEBUG_DRAW||DEBUG_DRAW_LND)
                    Debug.DrawLine(countdown.transform.position, countdown.previous.transform.position, Color.cyan);
                    //#endif
                    points = Utility.Dist3DSegToSeg(a, b, countdown.transform.position, countdown.previous.transform.position);
                    if ((points.a - points.b).magnitude < snapDistance)
                    {
                        Debug.DrawLine(points.b, transform.position, Color.green);
                        vert = countdown.previous;
                        if (looseFollow)
                        {
                            position = transform.position;
                        }
                        else
                        {
                            position = points.b;
                        }
                        return(true);
                    }
                }
                countdown = countdown.previous;
            }
        }
        else
        {
            Debug.LogError("Error in land, spline is null");
        }
        Debug.LogWarning("Warning in land - Couldn't find a vert");
        vert     = null;
        position = Vector3.zero;
        return(false);
    }
 //    public void UpdateSpline(){
 //        if(currentSpline != currentSplineSource.spline){
 //            Svertex oldBegin = currentSpline.begin;
 //            Svertex newBegin = currentSplineSource.spline.begin;
 //            while(oldBegin.next != null && newBegin.next != null){		//roll forward through both splines until we find the old groundCV
 //                if(oldBegin == groundCV)
 //                    break;
 //                oldBegin = oldBegin.next;
 //                newBegin = newBegin.next;
 //            }
 //            groundCV = newBegin;
 //            currentSpline = currentSplineSource.spline;
 //        }
 //    }
 public void Detach()
 {
     //Debug.Log("detach" + Time.frameCount);
     currentSpline = null;
     groundNode = null;
     transform.parent = null;
 }
Example #43
0
    public override void OnInspectorGUI()
    {
        DrawDefaultInspector();
        Spline spline = (Spline)target;

        if (spline)
        {
            if (spline.begin)
            {
                EditorGUILayout.BeginVertical();
                EditorGUILayout.BeginHorizontal();
                if (GUILayout.Button("Set Speed"))
                {
                    SplineNode begin = spline.begin;
                    do
                    {
                        begin.speed = spline.setSpeed;
                        begin       = begin.next;
                    } while(begin && begin != spline.begin);
                }
                if (GUILayout.Button("Set Pause Time"))
                {
                    SplineNode begin = spline.begin;
                    do
                    {
                        begin.pauseTime = spline.setPauseTime;
                        begin           = begin.next;
                    } while(begin && begin != spline.begin);
                }
                if (GUILayout.Button("Toggle handles"))
                {
                    SplineNode begin = spline.begin;
                    spline.handlesOn = !spline.handlesOn;
                    do
                    {
                        begin.hideHandles = spline.handlesOn;
                        begin.RefreshModel();
                        begin = begin.next;
                    } while(begin && begin != spline.begin);
                }
                if (GUILayout.Button("Toggle nodes"))
                {
                    SplineNode begin = spline.begin;
                    spline.nodesOn = !spline.nodesOn;
                    do
                    {
                        begin.GetComponent <Renderer>().enabled = spline.nodesOn;
                        begin = begin.next;
                    } while(begin && begin != spline.begin);
                }
                EditorGUILayout.EndHorizontal();
            }
            spline.colliderRadius = EditorGUILayout.Slider("Global Collider Radius", spline.colliderRadius, Mathf.Epsilon, spline.maxColliderRadius);
            SplineNode node = spline.begin;
            do
            {
                if (!node.colliderFreedom)
                {
                    node.colliderRadius = spline.colliderRadius;
                    node.ReOrient();
                }
                node = node.next;
            } while(node && node != spline.begin);
            EditorGUILayout.BeginHorizontal();
            if (GUILayout.Button("Toggle colliders"))
            {
                spline.collidersOn = !spline.collidersOn;
                SplineColliderDraw[] colliders = spline.GetComponentsInChildren <SplineColliderDraw>();
                foreach (SplineColliderDraw draw in colliders)
                {
                    draw.draw = spline.collidersOn;
                }
            }
            if (GUILayout.Button("Reset Colliders"))
            {
                node = spline.begin;
                do
                {
                    node.colliderType = spline.globalColliderType;
                    node.AddCollider();
                    node = node.next;
                } while(node && node != spline.begin);
                SplineColliderDraw[] colliders = spline.GetComponentsInChildren <SplineColliderDraw>();
                foreach (SplineColliderDraw draw in colliders)
                {
                    draw.draw = spline.collidersOn;
                }
            }
            if (GUILayout.Button("Lock Ornaments"))
            {
                node          = spline.begin;
                spline.locked = !spline.locked;
                do
                {
                    node.Locked = spline.locked;
                    node        = node.next;
                } while(node && node != spline.begin);
            }
            EditorGUILayout.EndHorizontal();
            EditorGUILayout.EndVertical();
        }
    }
Example #44
0
    //generate the control points for b spline,internal use
    //r1 = inner radius, r2 = outter radius, n = number of points
    void SplineRegenerator(int n = 10)
    {
        if (_spline == null)
        {
            _spline = this.GetComponent <Spline>();
        }

        RemoveNullNodes();

        _spline.autoClose = true;

        Vector2[] pt     = new Vector2 [2 * n];
        float     deltaA = 360f / n;

        cycleLength = 1f / n;

        Vector2 vi = Vector2.up * radius_inner;
        Vector2 vo = Vector2.up * radius_outter;

        vo = Quaternion.Euler(0f, 0f, deltaA * 0.5f) * vo;

        Quaternion deltaQ = Quaternion.Euler(0f, 0f, deltaA);

        for (int i = 0; i < n; i++)
        {
            pt[i * 2]     = Pos2 + vi;
            pt[i * 2 + 1] = Pos2 + vo;
            vi            = deltaQ * vi;
            vo            = deltaQ * vo;
        }

        int curNodeCont = _spline.splineNodesArray.Count;

        if (curNodeCont < 2 * n)
        {
            for (int i = 0; i < 2 * n; i++)
            {
                //if we exceed the no of existing nodes we need to create new node
                if (i >= curNodeCont)
                {
                    _spline.AddSplineNode(_spline.SplineNodes[_spline.splineNodesArray.Count - 1]);
                    _spline.splineNodesArray[i].transform.parent = this.transform;
                }
            }
        }
        else if (curNodeCont > 2 * n)
        {
            for (int i = curNodeCont - 1; i >= 2 * n; i--)
            {
                _spline.RemoveSplineNode(_spline.splineNodesArray[i]);
                //DestroyImmediate(_spline.splineNodesArray[i].gameObject); dont know why it doesnt work.
            }
        }

        for (int i = 0; i < 2 * n; i++)
        {
            _spline.splineNodesArray[i].Position = pt[i];
        }

        RemoveNullNodes();
    }
		private void DrawSplineInfo (Spline spline)
		{	
				if (Event.current.alt && !Event.current.shift) {
						foreach (SplineNode splineNode in spline.SplineNodes)
								Handles.Label (LabelPosition2D (splineNode.Position, -0.2f), splineNode.name, sceneGUIStyle);
			
						foreach (SplineSegment segment in spline.SplineSegments) {
								for (int i = 0; i < 10; i++) {
										float splineParam = segment.ConvertSegmentToSplineParamter (i / 10f);
					
										Vector3 position = spline.GetPositionOnSpline (splineParam);
										Vector3 normal = spline.GetNormalToSpline (splineParam);
					
										Handles.color = new Color (.3f, 1f, .20f, 0.75f);
										Handles.ArrowCap (0, position, Quaternion.LookRotation (normal), HandleUtility.GetHandleSize (position) * 0.5f);
								}
						}
			
						Vector3 tangentPosition0 = spline.GetPositionOnSpline (0);
			
						Handles.color = new Color (.2f, 0.4f, 1f, 1);
						Handles.ArrowCap (0, tangentPosition0, Quaternion.LookRotation (spline.GetTangentToSpline (0)), HandleUtility.GetHandleSize (tangentPosition0) * 0.5f);
			
						Vector3 tangentPosition1 = spline.GetPositionOnSpline (1);
						Handles.ArrowCap (0, tangentPosition1, Quaternion.LookRotation (spline.GetTangentToSpline (1)), HandleUtility.GetHandleSize (tangentPosition1) * 0.5f);
				} else if (Event.current.alt && Event.current.shift) {
						foreach (SplineSegment item in spline.SplineSegments) {
								Vector3 positionOnSpline = spline.GetPositionOnSpline (item.ConvertSegmentToSplineParamter (0.5f));
				
								Handles.Label (LabelPosition2D (positionOnSpline, -0.2f), item.Length.ToString (), sceneGUIStyle);
						}
			
						Handles.Label (LabelPosition2D (spline.transform.position, -0.3f), "Length: " + spline.Length.ToString (), sceneGUIStyle);
				}
		}
Example #46
0
    void OnGUI()
    {
        DemoGUIHelpers.setupGUIButtons();
        _duration = DemoGUIHelpers.durationSlider(_duration, 5f);
        DemoGUIHelpers.easeTypesGUI();


        GUILayout.Label("The splines used in this scene are on the\n*DummySpline GameObjects so you can\nhave a look at them.");
        GUILayout.Label("Just select the GameObject and the gizmos\nwill be drawn in the scene view.");
        GUILayout.Space(20);

        if (GUILayout.Button("Figure Eight Spline Tween (relative)"))
        {
            var spline = new Spline("figureEight");
            spline.closePath();             // we have to let the spline know it should close itself if using EaseTypes that go negative like Elastic to avoid clamping

            new SplineTween(quad, spline, _duration)
            .setIsRelative()
            .start();
        }


        if (GUILayout.Button("Figure Eight Spline Tween (absolute)"))
        {
            var spline = new Spline("figureEight");
            spline.closePath();

            new SplineTween(quad, spline, _duration)
            .start();
        }


        if (GUILayout.Button("Circle Position Tween (relative with PingPong)"))
        {
            var spline = new Spline("circle", true);
            spline.closePath();

            new SplineTween(quad, spline, _duration)
            .setIsRelative()
            .setLoops(LoopType.PingPong)
            .start();
        }


        if (GUILayout.Button("DemoRoute Tween (relative with PingPong)"))
        {
            var spline = new Spline("demoRoute", true);
            spline.closePath();

            new SplineTween(quad, spline, _duration)
            .setIsRelative()
            .setLoops(LoopType.PingPong)
            .start();
        }


        if (GUILayout.Button("Runtime Spline (relative with PingPong)"))
        {
            var nodes  = new Vector3[] { new Vector3(0, 0), new Vector3(0, 0), new Vector3(4f, 4f, 4f), new Vector3(-4f, 5f, 6f), new Vector3(-2f, 2f, 0f), new Vector3(0f, 0f) };
            var spline = new Spline(nodes);
            spline.closePath();

            // setup the tween
            new SplineTween(quad, spline, _duration)
            .setIsRelative()
            .setLoops(LoopType.PingPong)
            .start();
        }
    }
		private void HandleMouseInput (Spline spline)
		{
				if (!EditorGUI.actionKey) {
						toolSphereSize = 10f;
						toolSphereAlpha = 0f;
						return;
				} else {
						toolSphereAlpha = Mathf.Lerp (toolSphereAlpha, 0.75f, deltaTime * 4f);
						toolSphereSize = Mathf.Lerp (toolSphereSize, toolTargetSphereSize + Mathf.Sin (Time.realtimeSinceStartup * 2f) * 0.1f, deltaTime * 15f);
				}
		
				Ray mouseRay = Camera.current.ScreenPointToRay (new Vector2 (Event.current.mousePosition.x, Screen.height - Event.current.mousePosition.y - 32f));
				float splineParam = spline.GetClosestPointParamToRay (mouseRay, 3);
				Vector3 position = spline.GetPositionOnSpline (splineParam);
		
				float currentDistance = Vector3.Cross (mouseRay.direction, position - mouseRay.origin).magnitude;
		
				SplineNode selectedNode = null;
		
				foreach (SplineNode node in spline.SplineNodes) {
						float newDistance = Vector3.Distance (node.Position, position);
			
						if (newDistance < currentDistance || newDistance < 0.2f * HandleUtility.GetHandleSize (node.Position)) {
								currentDistance = newDistance; 
				
								selectedNode = node;
						}
				}
		
				if (selectedNode != null) {
						position = selectedNode.Position;
			
						Handles.color = new Color (.7f, 0.15f, 0.1f, toolSphereAlpha);
						Handles.SphereCap (0, position, Quaternion.identity, HandleUtility.GetHandleSize (position) * 0.25f * toolSphereSize);
			
						Handles.color = Color.white;
						Handles.Label (LabelPosition2D (position, 0.3f), "Delete Node (" + selectedNode.gameObject.name + ")", sceneGUIStyleToolLabel); 
			
						toolTargetSphereSize = 1.35f;
				} else {
						Handles.color = new Color (.5f, 1f, .1f, toolSphereAlpha);
						Handles.SphereCap (0, position, Quaternion.identity, HandleUtility.GetHandleSize (position) * 0.25f * toolSphereSize);
			
						Handles.color = Color.white;
						Handles.Label (LabelPosition2D (position, 0.3f), "Insert Node", sceneGUIStyleToolLabel); 
			
						toolTargetSphereSize = 0.8f;
				}
		
				if (Event.current.type == EventType.mouseDown && Event.current.button == 1) {
						Undo.RegisterSceneUndo ((selectedNode != null) ? "Delete Spline Node (" + selectedNode.name + ")" : "Insert Spline Node");
			
						if (selectedNode != null) {
								spline.RemoveSplineNode (selectedNode.gameObject);
								DestroyImmediate (selectedNode.gameObject);
						} else
								InsertNode (spline, splineParam);
			
						ApplyChangesToTarget (spline);
				}
		
				HandleUtility.Repaint ();
		}
Example #48
0
    //--------------------------------------------------------
    public override void OnInspectorGUI()
    {
        Spline s = target as Spline;

        base.OnInspectorGUI();

        //adjust x, y
        int ax = (int)s._adjustX;
        int ay = (int)s._adjustY;

        ax = EditorGUILayout.IntSlider("Adjust X axis -" + 200 + "-> " + 200, ax, -200, 200);
        ay = EditorGUILayout.IntSlider("Adjust Y axis -" + 200 + "-> " + 200, ay, -200, 200);
        s.OnAdjustX(ax);
        s.OnAdjustY(ay);
        //-------
        if (s.advance)
        {
            if (s.edit)
            {
                int lastSegment = s.waypointsCount - 2;
                if (lastSegment > 0)
                {
                    EditorGUILayout.Space();
                    const int firstSegment = 0;
                    int       i            = Mathf.Clamp(s.selectedSegment, firstSegment, lastSegment);
                    i = EditorGUILayout.IntSlider("Segment " + i + "-" + (i + 1).ToString(), i, firstSegment, lastSegment);
                    if (s.selectedSegment != i)
                    {
                        s.selectedSegment = i;
                        EditorUtility.SetDirty(s); // force redrawing gizmo
                    }
                    s.durations[i] = EditorGUILayout.Slider("Duration", s.durations[i], 0f, 3f);
                    s.easings[i]   = (Ease)EditorGUILayout.EnumPopup("Easing", s.easings[i]);
                    EditorGUILayout.LabelField("Length", s.lengths[i].ToString());
                }
            }
        }
        else
        {
            if (s.edit)
            {
                s.overallDuration = EditorGUILayout.Slider("Duration", s.overallDuration, 0f, 10f);
                s.overallEasing   = (Ease)EditorGUILayout.EnumPopup("Easing", s.overallEasing);
            }
            else
            {
                EditorGUILayout.LabelField("Duration", s.overallDuration.ToString());
                EditorGUILayout.LabelField("Easing", s.overallEasing.ToString());
            }
        }

        if (s.edit)
        {
            EditorGUILayout.Space();
            if (GUILayout.Button("Prepend waypoint") &&
                EditorUtility.DisplayDialog("Waypoint prepend confirmation", "Do you really want to add a new waypoint as the first one?", "Prepend", "Cancel"))
            {
                s.PrependWaypoint();
            }
        }

        if (s.edit)
        {
            EditorGUILayout.Space();
            if (GUILayout.Button("Reset") &&
                EditorUtility.DisplayDialog("Spline reset confirmation", "Do you really want to make spline from the beginning?", "Reset", "Cancel"))
            {
                s.Reset();
            }
        }

        if (s.edit && s.transform.localScale != Vector3.one)
        {
            EditorGUILayout.HelpBox(
                "Waypoints will be scaled with Spline gameobject, but the waypoints data will display in un-scaled format. So it's better to edit the path with scale = (1,1,1).",
                MessageType.Warning
                );
        }

        EditorGUI.BeginDisabledGroup(true);
        EditorGUILayout.LabelField("Scaled waypoints");
        EditorGUI.indentLevel++;
        int n = s.scaledWaypoints.Length;

        for (int i = 0; i < n; ++i)
        {
            EditorGUILayout.Vector3Field("Point #" + i, s.scaledWaypoints[i]);
        }
        EditorGUI.indentLevel--;
        EditorGUI.EndDisabledGroup();
    }
Example #49
0
        private bool GenerateTube(
          double profRad, Point3dCollection pts, out Solid3d sol
        )
        {
            bool readyToBreak;

            // Let's start by creating our spline path

            using (Spline path = new Spline(pts, 0, 0.0))
            {
                double pathLen = path.GetDistanceAtParameter(path.EndParam);
                readyToBreak = (pathLen > _profSide * _segFactor);

                // And our sweep profile

                Circle profile =
                  new Circle(pts[0], pts[1] - pts[0], profRad);
                using (profile)
                {
                    // Then our sweep options

                    SweepOptionsBuilder sob = new SweepOptionsBuilder();

                    // Align the entity to sweep to the path

                    sob.Align =
                      SweepOptionsAlignOption.AlignSweepEntityToPath;

                    // The base point is the start of the path

                    sob.BasePoint = path.StartPoint;

                    // The profile will rotate to follow the path

                    sob.Bank = true;
                    using (SweepOptions sweepOpts = sob.ToSweepOptions())
                    {
                        sol = new Solid3d();
                        sol.ColorIndex = ColorIndex;

                        // Sweep our profile along our path

                        sol.CreateSweptSolid(profile, path, sweepOpts);
                    }
                }
            }
            _lastDrawnVertex = pts.Count - 1;

            return readyToBreak;
        }
Example #50
0
        public void ReadAllShapes(FarmSimulatorVersion version)
        {
            var hasError = false;
            var gamePath = GamePaths.GetGamePath(version);

            if (gamePath == null || !Directory.Exists(gamePath))
            {
                Assert.Inconclusive($"Game path not found: {version}");
            }

            var shapeFiles = Directory.GetFiles(gamePath, $"*{GameConstants.SchapesFileExtension}", SearchOption.AllDirectories);

            shapeFiles
            .AsParallel()
            .WithDegreeOfParallelism(Environment.ProcessorCount)
            .ForEach(
                filePath =>
            {
                try
                {
                    var container = new FileContainer(filePath);
                    var entities  = container.GetEntities();
                    foreach (var valueTuple in container.ReadRawData(entities))
                    {
                        using (var stream = new MemoryStream(valueTuple.RawData))
                        {
                            try
                            {
                                using (var reader = new EndianBinaryReader(stream, container.Endian, true))
                                {
                                    switch (valueTuple.Entity.Type)
                                    {
                                    case 1:
                                        var shape = new Shape(reader, container.Header.Version);
                                        break;

                                    case 2:
                                        var spline = new Spline(reader);
                                        break;

                                    case 3:
                                        var mesh = new NavMesh(reader);
                                        break;
                                    }
                                }
                            }
                            catch
                            {
                                hasError = true;
                                stream.Seek(0, SeekOrigin.Begin);
                                using (var reader = new EndianBinaryReader(stream, container.Endian))
                                {
                                    SaveErrorShape(
                                        version,
                                        container.Header.Version,
                                        filePath,
                                        new RawNamedShapeObject(valueTuple.Entity.Type, reader, container.Endian)
                                        );
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    hasError = true;
                }
            }
                );

            Assert.IsFalse(hasError);
        }
 //-------------------//
 //    SPLINE PHYSICS!!!//
 //-------------------//
 bool NextNode()
 {
     if(groundNode.next) {
         groundNode = groundNode.next;
         return true;
     } else if(currentSpline.next) {
         if(currentSpline.next.begin) {
             currentSpline = currentSpline.next;
             groundNode = currentSpline.begin;
             return true;
         } else Debug.LogWarning("Next spline missing begin");
     }
     return false;
 }
 // Use this for initialization
 void Start()
 {
     spline = new Spline(type, points);
     //cameraRail = GameObject.Find ("Camera Rail");
 }
 public bool FindSplineVertex(Spline s, Vector3 a, Vector3 b, out SplineNode vert, out Vector3 position)
 {
     return FindSplineVertex(s, a, b, null, out vert, out position);
 }
Example #54
0
        /// <summary>
        /// 读取dwg中entities信息
        /// </summary>
        public static void GetDwgGeometry(string layerName)
        {
            Database db = HostApplicationServices.WorkingDatabase;

            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                LayerTable lt = (LayerTable)trans.GetObject(db.LayerTableId, OpenMode.ForRead);
                if (lt.Has(layerName))
                {
                    BlockTableRecord ltr = (BlockTableRecord)trans.GetObject(db.CurrentSpaceId, OpenMode.ForRead);
                    int a, r, g, b = 0;
                    foreach (ObjectId objId in ltr)
                    {
                        Entity ent = (Entity)trans.GetObject(objId, OpenMode.ForRead);

                        #region 遍历entities
                        if (ent.Layer == layerName)
                        {
                            string type = ent.GetType().ToString().Replace("Autodesk.AutoCAD.DatabaseServices.", "");
                            if (type == "Line")
                            {
                                Line line = (Line)ent;
                                //EntityLayer.Add(line.Layer);
                                //EntityType.Add(type);
                                //LineType.Add(line.Linetype);
                                a = line.Color.ColorValue.A;
                                r = line.Color.ColorValue.R;
                                g = line.Color.ColorValue.G;
                                b = line.Color.ColorValue.B;
                                EntityColor.Add(RgbToHex(a, r, g, b));
                                EntityHandle.Add(line.Handle);
                                TextRotation.Add("null");
                                //Coordinate.Add(line.StartPoint + "," + line.EndPoint);
                                //Text.Add("null");
                                //Height.Add("null");
                                //LineWidth.Add(line.LineWeight);
                                //CRadius.Add("null");
                                //ExtenedEntity.Add("null");
                            }
                            else if (type == "AttributeDefinition")
                            {
                                AttributeDefinition attribute = (AttributeDefinition)ent;
                                //EntityLayer.Add(attribute.Layer);
                                //EntityType.Add(type);
                                EntityHandle.Add(attribute.Handle);
                                //LineType.Add("null");
                                a = attribute.Color.ColorValue.A;
                                r = attribute.Color.ColorValue.R;
                                g = attribute.Color.ColorValue.G;
                                b = attribute.Color.ColorValue.B;
                                EntityColor.Add(RgbToHex(a, r, g, b));
                                TextRotation.Add("null");
                                //Coordinate.Add(attribute.Position);
                                //Text.Add("null");
                                //Height.Add("null");
                                //LineWidth.Add("null");
                                //CRadius.Add("null");
                                //ExtenedEntity.Add(attribute.ExtensionDictionary);
                            }
                            else if (type == "DBPoint")
                            {
                                DBPoint dbpoint = (DBPoint)ent;
                                //EntityLayer.Add(dbpoint.Layer);
                                //EntityType.Add(type);
                                EntityHandle.Add(dbpoint.Handle);
                                //LineType.Add(dbpoint.Linetype);
                                a = dbpoint.Color.ColorValue.A;
                                r = dbpoint.Color.ColorValue.R;
                                g = dbpoint.Color.ColorValue.G;
                                b = dbpoint.Color.ColorValue.B;
                                EntityColor.Add(RgbToHex(a, r, g, b));
                                TextRotation.Add("null");
                                //Coordinate.Add(dbpoint.Position);
                                //Text.Add("null");
                                //Height.Add("null");
                                //LineWidth.Add("null");
                                //CRadius.Add("null");
                                //ExtenedEntity.Add("null");
                            }
                            else if (type == "Ellipse")
                            {
                                Ellipse ellipse = (Ellipse)ent;
                                //EntityLayer.Add(ellipse.Layer);
                                //EntityType.Add(type);
                                EntityHandle.Add(ellipse.Handle);
                                //LineType.Add("null");
                                a = ellipse.Color.ColorValue.A;
                                r = ellipse.Color.ColorValue.R;
                                g = ellipse.Color.ColorValue.G;
                                b = ellipse.Color.ColorValue.B;
                                EntityColor.Add(RgbToHex(a, r, g, b));
                                TextRotation.Add("null");
                                //Coordinate.Add(ellipse.GetPlane().GetCoordinateSystem());
                                //Text.Add("null");
                                //Height.Add("null");
                                //LineWidth.Add("null");
                                //CRadius.Add("null");
                                //ExtenedEntity.Add("null");
                            }
                            else if (type == "DBText")
                            {
                                DBText dbtext = (DBText)ent;
                                //EntityLayer.Add(dbtext.Layer);
                                //EntityType.Add(type);
                                EntityHandle.Add(dbtext.Handle);
                                TextRotation.Add(dbtext.Rotation);
                                //LineType.Add("null");
                                a = dbtext.Color.ColorValue.A;
                                r = dbtext.Color.ColorValue.R;
                                g = dbtext.Color.ColorValue.G;
                                b = dbtext.Color.ColorValue.B;
                                EntityColor.Add(RgbToHex(a, r, g, b));
                                //Coordinate.Add(dbtext.Position);
                                Text.Add(dbtext.TextString);
                                //Height.Add(dbtext.Height);
                                //LineWidth.Add("null");
                                //CRadius.Add("null");
                                //ExtenedEntity.Add("null");
                                if (dbtext.TextString.Contains("说明"))
                                {
                                    _position = dbtext.Position.ToString();
                                }
                            }
                            else if (type == "RadialDimension")
                            {
                                RadialDimension radial = (RadialDimension)ent;
                                //EntityLayer.Add(radial.Layer);
                                //EntityType.Add(type);
                                EntityHandle.Add(radial.Handle);
                                //LineType.Add("null");
                                a = radial.Color.ColorValue.A;
                                r = radial.Color.ColorValue.R;
                                g = radial.Color.ColorValue.G;
                                b = radial.Color.ColorValue.B;
                                EntityColor.Add(RgbToHex(a, r, g, b));
                                TextRotation.Add("null");
                                //Coordinate.Add(radial.GetPlane().GetCoordinateSystem());
                                //Text.Add("null");
                                //Height.Add("null");
                                //LineWidth.Add("null");
                                //CRadius.Add("null");
                                //ExtenedEntity.Add(radial.ExtensionDictionary);
                            }
                            else if (type == "AlignedDimension")
                            {
                                AlignedDimension aligned = (AlignedDimension)ent;
                                //EntityLayer.Add(aligned.Layer);
                                //EntityType.Add(type);
                                EntityHandle.Add(aligned.Handle);
                                //LineType.Add("null");
                                a = aligned.Color.ColorValue.A;
                                r = aligned.Color.ColorValue.R;
                                g = aligned.Color.ColorValue.G;
                                b = aligned.Color.ColorValue.B;
                                EntityColor.Add(RgbToHex(a, r, g, b));
                                TextRotation.Add("null");
                                //Coordinate.Add(aligned.GeometricExtents);
                                //Text.Add(aligned.TextAttachment);
                                //Height.Add("null");
                                //LineWidth.Add("null");
                                //CRadius.Add("null");
                                //ExtenedEntity.Add("null");
                            }
                            else if (type == "Spline")
                            {
                                Spline spline = (Spline)ent;
                                //EntityLayer.Add(spline.Layer);
                                //EntityType.Add(type);
                                EntityHandle.Add(spline.Handle);
                                //LineType.Add(spline.Linetype);
                                a = spline.Color.ColorValue.A;
                                r = spline.Color.ColorValue.R;
                                g = spline.Color.ColorValue.G;
                                b = spline.Color.ColorValue.B;
                                EntityColor.Add(RgbToHex(a, r, g, b));
                                TextRotation.Add("null");
                                //List<Point3d> points_spline = new List<Point3d>();
                                //for(int i = 0; i < spline.NumControlPoints; i++)
                                //{
                                //    points_spline.Add(spline.GetControlPointAt(i));
                                //}
                                //Coordinate.Add(points_spline);
                                //Text.Add("null");
                                //Height.Add("null");
                                //LineWidth.Add(spline.LineWeight);
                                //CRadius.Add("null");
                                //ExtenedEntity.Add("null");
                            }
                            else if (type == "RotatedDimension")
                            {
                                RotatedDimension rotate = (RotatedDimension)ent;
                                //EntityLayer.Add(rotate.Layer);
                                //EntityType.Add(type);
                                EntityHandle.Add(rotate.Handle);
                                //LineType.Add("null");
                                a = rotate.Color.ColorValue.A;
                                r = rotate.Color.ColorValue.R;
                                g = rotate.Color.ColorValue.G;
                                b = rotate.Color.ColorValue.B;
                                EntityColor.Add(RgbToHex(a, r, g, b));
                                TextRotation.Add("null");
                                //Coordinate.Add(rotate.GeometricExtents);
                                //Text.Add("null");
                                //Height.Add("null");
                                //LineWidth.Add("null");
                                //CRadius.Add("null");
                                //ExtenedEntity.Add(rotate.ExtensionDictionary);
                            }
                            else if (type == "Polyline")
                            {
                                Polyline pline = (Polyline)ent;
                                //EntityLayer.Add(pline.Layer);
                                //EntityType.Add(type);
                                EntityHandle.Add(pline.Handle);
                                //LineType.Add(pline.Linetype);
                                a = pline.Color.ColorValue.A;
                                r = pline.Color.ColorValue.R;
                                g = pline.Color.ColorValue.G;
                                b = pline.Color.ColorValue.B;
                                EntityColor.Add(RgbToHex(a, r, g, b));
                                TextRotation.Add("null");
                                //CRadius.Add("null");
                                //List<Point3d> points_polyline = new List<Point3d>();
                                //for(int i = 0; i < pline.NumberOfVertices; i++)
                                //{
                                //    points_polyline.Add(pline.GetPoint3dAt(i));
                                //}
                                //Coordinate.Add(points_polyline);
                                //Text.Add("null");
                                //Height.Add("null");
                                //LineWidth.Add(pline.LineWeight);
                                //ExtenedEntity.Add("null");
                            }
                            else if (type == "MText")
                            {
                                MText mtext = (MText)ent;
                                //EntityLayer.Add(mtext.Layer);
                                //EntityType.Add(type);
                                EntityHandle.Add(mtext.Handle);
                                TextRotation.Add(mtext.Rotation);
                                //LineType.Add("null");
                                a = mtext.Color.ColorValue.A;
                                r = mtext.Color.ColorValue.R;
                                g = mtext.Color.ColorValue.G;
                                b = mtext.Color.ColorValue.B;
                                EntityColor.Add(RgbToHex(a, r, g, b));
                                //Coordinate.Add(mtext.Location);
                                //Text.Add(mtext.Contents);
                                //Height.Add(mtext.Height);
                                //LineWidth.Add("null");
                                //CRadius.Add("null");
                                //ExtenedEntity.Add("null");
                                if (mtext.Text.Contains("说明"))
                                {
                                    _position = mtext.Location.ToString();
                                }
                            }
                            else if (type == "Arc")
                            {
                                Arc arc = (Arc)ent;
                                //EntityLayer.Add(arc.Layer);
                                //EntityType.Add(type);
                                EntityHandle.Add(arc.Handle);
                                //LineType.Add("null");
                                a = arc.Color.ColorValue.A;
                                r = arc.Color.ColorValue.R;
                                g = arc.Color.ColorValue.G;
                                b = arc.Color.ColorValue.B;
                                EntityColor.Add(RgbToHex(a, r, g, b));
                                TextRotation.Add("null");
                                //Coordinate.Add(arc.Center);
                                //Text.Add("null");
                                //Height.Add("null");
                                //LineWidth.Add("null");
                                //CRadius.Add(arc.Radius);
                                //ExtenedEntity.Add("null");
                            }
                            else if (type == "Hatch")
                            {
                                Hatch hatch = (Hatch)ent;
                                //EntityLayer.Add(hatch.Layer);
                                //EntityType.Add(type);
                                EntityHandle.Add(hatch.Handle);
                                //LineType.Add("null");
                                a = hatch.Color.ColorValue.A;
                                r = hatch.Color.ColorValue.R;
                                g = hatch.Color.ColorValue.G;
                                b = hatch.Color.ColorValue.B;
                                EntityColor.Add(RgbToHex(a, r, g, b));
                                TextRotation.Add("null");
                                //Coordinate.Add(hatch.GeometricExtents);
                                //Text.Add("null");
                                //Height.Add("null");
                                //LineWidth.Add("null");
                                //CRadius.Add("null");
                                //ExtenedEntity.Add(hatch.ExtensionDictionary);
                            }
                            else if (type == "Dimension")
                            {
                                Dimension dim = (Dimension)ent;
                                //EntityLayer.Add(dim.Layer);
                                //EntityType.Add(type);
                                EntityHandle.Add(dim.Handle);
                                //LineType.Add("null");
                                a = dim.Color.ColorValue.A;
                                r = dim.Color.ColorValue.R;
                                g = dim.Color.ColorValue.G;
                                b = dim.Color.ColorValue.B;
                                EntityColor.Add(RgbToHex(a, r, g, b));
                                TextRotation.Add("null");
                                //Coordinate.Add(dim.TextPosition);
                                //Text.Add("null");
                                //Height.Add("null");
                                //LineWidth.Add("null");
                                //CRadius.Add("null");
                                //ExtenedEntity.Add(dim.ExtensionDictionary);
                            }
                            else if (type == "Circle")
                            {
                                Circle circle = (Circle)ent;
                                //EntityLayer.Add(circle.Layer);
                                //EntityType.Add(type);
                                EntityHandle.Add(circle.Handle);
                                //LineType.Add("null");
                                a = circle.Color.ColorValue.A;
                                r = circle.Color.ColorValue.R;
                                g = circle.Color.ColorValue.G;
                                b = circle.Color.ColorValue.B;
                                EntityColor.Add(RgbToHex(a, r, g, b));
                                TextRotation.Add("null");
                                //Coordinate.Add(circle.Center);
                                //Text.Add("null");
                                //Height.Add("null");
                                //LineWidth.Add("null");
                                //CRadius.Add(circle.Radius);
                                //ExtenedEntity.Add("null");
                            }
                            else if (type == "BlockReference")
                            {
                                BlockReference block = (BlockReference)ent;
                                //EntityLayer.Add(block.Layer);
                                //EntityType.Add(type);
                                EntityHandle.Add(block.Handle);
                                //LineType.Add("null");
                                a = block.Color.ColorValue.A;
                                r = block.Color.ColorValue.R;
                                g = block.Color.ColorValue.G;
                                b = block.Color.ColorValue.B;
                                EntityColor.Add(RgbToHex(a, r, g, b));
                                TextRotation.Add("null");
                                //Coordinate.Add(block.GeometricExtents);
                                //Text.Add("null");
                                //Height.Add("null");
                                //LineWidth.Add("null");
                                //CRadius.Add("null");
                                //ExtenedEntity.Add(block.ExtensionDictionary);
                            }
                            else
                            {
                                //EntityLayer.Add("null");
                                //EntityType.Add("null");
                                //EntityHandle.Add("null");
                                //LineType.Add("null");
                                //EntityColor.Add("null");
                                //Coordinate.Add("null");
                                //Text.Add("null");
                                //Height.Add("null");
                                //LineWidth.Add("null");
                                //CRadius.Add("null");
                                //ExtenedEntity.Add("null");
                            }
                            #endregion
                        }
                    }
                }
                trans.Commit();
            }
        }
 bool FindSplineVertex(Spline s, Vector3 a, Vector3 b, SplineNode guess, out SplineNode vert, out Vector3 position)
 {
     SplineNode countup, countdown;
     if(s != null) {
         if(guess == null) {
             if(!(s.begin && s.end)) {
                 Debug.LogError("Could not find vertex, begin and end not set");
                 vert = null;
                 position = Vector3.zero;
                 return false;
             }
             countup = s.begin;
             countdown = s.end;
         } else {
             countdown = guess;
             countup = guess;
         }
         Utility.Vector3Pair points;
         while(countdown != null || countup != null) {
             if(countup.next != null) {
                 //#if(DEBUG_DRAW||DEBUG_DRAW_LND)
                 Debug.DrawLine(countup.transform.position, countup.next.transform.position, Color.magenta);
                 //#endif
                 points = Utility.Dist3DSegToSeg(a, b, countup.transform.position, countup.next.transform.position);
                 if((points.a - points.b).magnitude < snapDistance) {
                     //Debug.Log(points.a + ", " + points.b);
                     Debug.DrawLine(points.b, transform.position, Color.magenta);
                     vert = countup;
                     if(looseFollow)
                         position = transform.position;
                     else
                         position = points.b;
                     return true;
                 }
             }
             countup = countup.next;
             if(countdown.previous != null) {
                 //#if(DEBUG_DRAW||DEBUG_DRAW_LND)
                 Debug.DrawLine(countdown.transform.position, countdown.previous.transform.position, Color.cyan);
                 //#endif
                 points = Utility.Dist3DSegToSeg(a, b, countdown.transform.position, countdown.previous.transform.position);
                 if((points.a - points.b).magnitude < snapDistance) {
                     Debug.DrawLine(points.b, transform.position, Color.green);
                     vert = countdown.previous;
                     if(looseFollow)
                         position = transform.position;
                     else
                         position = points.b;
                     return true;
                 }
             }
             countdown = countdown.previous;
         }
     } else
         Debug.LogError("Error in land, spline is null");
     Debug.LogWarning("Warning in land - Couldn't find a vert");
     vert = null;
     position = Vector3.zero;
     return false;
 }
 /// <summary>
 /// Gets TF for a certain local F
 /// </summary>
 /// <param name="localF">a local F in the range 0..1</param>
 /// <returns>a TF value</returns>
 public float LocalFToTF(float localF)
 {
     return(Spline.SegmentToTF(this, localF));
 }
 bool PreviousNode()
 {
     if(groundNode.previous) {
         groundNode = groundNode.previous;
         return true;
     } else {
         if(currentSpline.previous) {
             if(currentSpline.previous.end) {
                 currentSpline = currentSpline.previous;
                 groundNode = currentSpline.end;
                 return true;
             } else Debug.LogWarning("Previous spline missing end");
         }
     }
     return false;
 }
    /// <summary>
    /// Moves the Control Point along it's Up-Vector to match a desired Spline length
    /// </summary>
    /// <remarks>When the desired length can't be achieved, the Control Point will stop moving at the nearest possible point</remarks>
    /// <param name="newSplineLength">the desired length of the spline</param>
    /// <param name="stepSize">stepSize used when moving</param>
    /// <returns>false if the length can't be achieved by moving this Control Point.</returns>
    public bool SnapToFitSplineLength(float newSplineLength, float stepSize)
    {
        if (stepSize == 0 || Mathf.Approximately(newSplineLength, Spline.Length))
        {
            return(true);
        }

        float   curLength = Spline.Length;
        Vector3 oldPos    = Transform.position;
        Vector3 upstep    = Transform.up * stepSize;

        // Check if increasing by Up-Vector will increase the length
        Transform.position += upstep;
        Spline.Refresh(true, false, false);
        bool UpGrows = (Spline.Length > curLength);
        int  loops   = 30000;

        Transform.position = oldPos;

        // Need to grow?
        if (newSplineLength > curLength)
        {
            if (!UpGrows)
            {
                upstep *= -1;
            }
            while (Spline.Length < newSplineLength)
            {
                loops--;
                curLength           = Spline.Length;
                Transform.position += upstep;
                Spline.Refresh(true, false, false);
                if (curLength > Spline.Length)
                {
                    return(false);
                }
                if (loops == 0)
                {
                    Debug.LogError("CurvySplineSegment.SnapToFitSplineLength exceeds 30000 loops, considering this a dead loop! This shouldn't happen, please report this as an error!");
                    return(false);
                }
            }
        }
        else   // otherwise shrink
        {
            if (UpGrows)
            {
                upstep *= -1;
            }
            while (Spline.Length > newSplineLength)
            {
                loops--;
                curLength           = Spline.Length;
                Transform.position += upstep;
                Spline.Refresh(true, false, false);
                if (curLength < Spline.Length)
                {
                    return(false);
                }
                if (loops == 0)
                {
                    Debug.LogError("CurvySplineSegment.SnapToFitSplineLength exceeds 30000 loops, considering this a dead loop! This shouldn't happen, please report this as an error!");
                    return(false);
                }
            }
        }
        return(true);
    }
	// -----------------     ----------------     ----------------     ----------------    ----------------     ----------------      // 
	// Connects With This Creatures Registered Spline And Calculates All Necessiary Spline Animations 
    public void Move (Vector3 position, Spline spline)
    {
	
		// ----------  ----------    ----------   ---------- //
		// Calculates The Direction Between The Creature And The Spline Point Position
		Vector3 direction               = position - this.transform.position;
		float   magnitude               = direction.magnitude;
		// ----------  ----------    ----------   ---------- //
		direction                       = direction.normalized;
		     
		// ----------  ----------    ----------   ---------- //
		// Determines Certain Attribute Values On Awake
		if (!awake)
		{
	
		// ----------  ----------    ----------   ---------- //
		rotation                        = transform.rotation;
		axis                            = Quaternion.LookRotation (direction, motion);
		// ----------  ----------    ----------   ---------- //
		point                           = position;
		creature                        = transform.position;	
		// ----------  ----------    ----------   ---------- //
		velocity                        = speed;
		// ----------  ----------    ----------   ---------- //
		animation                       = this.gameObject.GetComponent <AntAnimation> ();
		// ----------  ----------    ----------   ---------- //
		awake                           = true;
		}
        
        // ----------  ----------    ----------   ---------- //
        // Determines The Creature Orientation Along The Spline
		if (transistor >= moment)
        {       
        rotation                        = transform.rotation;
		// ----------  ----------    ----------   ---------- //
		if (direction                  != Vector3.zero)
		axis                            = Quaternion.LookRotation (direction, motion);
	    // ----------  ----------    ----------   ---------- //
	    transistor                      = zero;
		// ----------  ----------    ----------   ---------- //
//		Mathematics.Logged ("Spline Rotation Reached");  
        }
        
		// ----------  ----------    ----------   ---------- //
		// Clamps The Creature Rotation Between Certain Parameters
		if (direction                  != Vector3.zero)
		contempory                      = Quaternion.LookRotation (direction, motion);
		// ----------  ----------    ----------   ---------- //
		if (Quaternion.Angle (history, contempory) >= clamp)
		{
		moment                          = zero;
		// ----------  ----------    ----------   ---------- //
//		Mathematics.Logged ( "Spline Rotation Exceeded Clamp" + Quaternion.Angle (rotation, axis) ); 
		} 
		else
		moment                          = 0.2f;
        
		// ----------  ----------    ----------   ---------- //
		// Manuevers The Selected Creature Rotation Along The Spline Over An Interval Of Time
		transistor                     += Time.deltaTime;
		transform.rotation              = Quaternion.Lerp (rotation, axis, transistor * orientation);

	    // ----------  ----------    ----------   ---------- //
	    // Dictates The Creature Position Along The Spline
        if (transform.position - point  == Vector3.zero)
        {    
        point                           = position;
        creature                        = transform.position;
		// ----------  ----------    ----------   ---------- //
		transistion                     = zero;
		// ----------  ----------    ----------   ---------- //
//        Mathematics.Logged ("Spline Point Reached");  
        }

		// ----------  ----------    ----------   ---------- //
		// Manuevers The Selected Creature Position Along The Spline Over An Interval Of Time
		transistion                   += Time.deltaTime;
		// ----------  ----------    ----------   ---------- //
		if (velocity                   > zero)
        transform.position             = Vector3.Lerp (creature, point, transistion * speed);
       
        
		
		// ----------  ----------    ----------   ---------- //
		// Traces The Former Rotational Quaternion Of The Spline Position
		if (direction                  != Vector3.zero)
		history                         = Quaternion.LookRotation (direction, motion);
		
	
		// ----------  ----------    ----------   ---------- //
		// Draws A Representative Symbol On The Spline For Each Defined Animation Trigger
		// Sets The Selected Animation That's Attributed To The Discovered Spline
		foreach (Transistion transit in node)
		{
			
			// ----------  ----------    ----------   ---------- //
			// Determines All Necessiary Attributes Needed
			float   percentage  =   transit.percentage / 100.00f;
			int     place       =   (int) Mathematics.limitation (transit.point, zero, sploot.spline.Length - 1);
			int		branch      =   (int) Mathematics.limitation (transit.branch, zero, sploot.spline.GetSubwaysLength (place) - 1);
			// ----------  ----------    ----------   ---------- //
			Vector3 note        =   sploot.spline.GetPointAtTime (percentage, place, branch);
			
			// ----------  ----------    ----------   ---------- //
		    Vector3 maximum     = Vector3.zero + (Vector3.one / approximate);
			Vector3 minimum     = Vector3.zero - (Vector3.one / approximate);
			float   distance    = Vector3.Distance (transform.position, note);
	
		    // ----------  ----------    ----------   ---------- //
		    // Determines Certain Distance Approxizations Between The Creature And The Animation Trigger
			// Determines The Set Motion Of The Animation, As Determined By The Current Creature Animation Behaviour
		    if (distance        >= minimum.x && distance  <= maximum.x)
			if (distance        >= minimum.y && distance  <= maximum.y)
			if (distance        >= minimum.z && distance  <= maximum.z)
		    animation.motion     = transit.animation;
		
			// ----------  ----------    ----------   ---------- //
			// Determines The Speed Of The Animation
			if (transit.pause        > zero)
			if (animation.motion    == transit.animation)
			if (animation.behaviour == transit.animation.ToString () )
			{
			pause.speed              = transit.speed;
			pause.pause              = transit.pause;	
			// ----------  ----------    ----------   ---------- //	
			pause.animation          = transit.animation;
			}
			
		}
		
		// -----------------     ----------------     ----------------     ----------------    ----------------     ----------------      // 
		// Deciphers The Momentum Of Certain Animations As They're Concievably Triggered
		
		// ----------  ----------    ----------   ---------- //
		// Deciphers Whether The Momentum Is In Dire Wish Of Some Change
		if (pause.animation         != null )
		if (animation.motion        == pause.animation)
		{		
		time                       += Time.deltaTime;
		// ----------  ----------    ----------   ---------- //
		if (time                    < pause.pause)
		velocity                    = Mathf.Lerp (speed, pause.speed, time * 2.00f);
		// ----------  ----------    ----------   ---------- //
		else 
		{
		time                        = zero;		
		animation.motion            = AntAnimation.Motion.walk;
		}		
		}
		
		// ----------  ----------    ----------   ---------- //
		// Transistions Back Into A Pre-Determined Motion 
		if (pause.animation         != null )
		if (animation.behaviour     != pause.animation.ToString () )
		{
		sand                        += Time.deltaTime;
        velocity                     = Mathf.Lerp (pause.speed, speed, sand * 3.00f);    
        }
		// ----------  ----------    ----------   ---------- //
		else
		sand                         = zero;
        
	
		     
        }
 /// <summary>
 /// Deletes this Control Point
 /// </summary>
 public void Delete()
 {
     Spline.Delete(this);
 }