Set() public method

public Set ( double new_x, double new_y, double new_z ) : void
new_x double
new_y double
new_z double
return void
Exemplo n.º 1
0
            public void negative_dimension_throws()
            {
                var v = new Vector3D();

                Assert.Throws <ArgumentOutOfRangeException>(() => v.Set(-1, 0));
                Assert.Throws <ArgumentOutOfRangeException>(() => v.Set(int.MinValue, 0));
            }
Exemplo n.º 2
0
            public void large_dimension_throws()
            {
                var v = new Vector3D();

                Assert.Throws <ArgumentOutOfRangeException>(() => v.Set(3, 0));
                Assert.Throws <ArgumentOutOfRangeException>(() => v.Set(int.MaxValue, 0));
            }
Exemplo n.º 3
0
        private static bool planeBoxOverlap(Vector3D normal, Vector3D vert, Vector3D maxbox)
        {
            int      q;
            Vector3D vmin = new Vector3D(), vmax = new Vector3D();
            float    v;

            for (q = X; q <= Z; q++)
            {
                v = vert.Get(q);                                    // -NJMP-
                if (normal.Get(q) > 0.0f)
                {
                    vmin.Set(q, -maxbox.Get(q) - v);                       // -NJMP-
                    vmax.Set(q, maxbox.Get(q) - v);                        // -NJMP-
                }
                else
                {
                    vmin.Set(q, maxbox.Get(q) - v);                        // -NJMP-
                    vmax.Set(q, -maxbox.Get(q) - v);                       // -NJMP-
                }
            }
            if (normal.Dot(vmin) > 0.0f)
            {
                return(false);                                     // -NJMP-
            }
            if (normal.Dot(vmax) >= 0.0f)
            {
                return(true);                                         // -NJMP-
            }
            return(false);
        }
Exemplo n.º 4
0
        public void SetTest()
        {
            var v  = new Vector3D(1, 2, 3);
            var vv = v.Set(OrdIdx.X, 1.1);

            Assert.True(vv.EqualsTol(1e-4, 1.1, v.Y, v.Z));
            vv = v.Set(OrdIdx.Y, 2.2);
            Assert.True(vv.EqualsTol(1e-4, v.X, 2.2, v.Z));
            vv = v.Set(OrdIdx.Z, 3.3);
            Assert.True(vv.EqualsTol(1e-4, v.X, v.Y, 3.3));
        }
Exemplo n.º 5
0
            public void can_set_all_componenets()
            {
                var v = new Vector3D(1, 2, 3);

                v.Set(0, -1.0);
                v.Set(1, 5.0);
                v.Set(2, -0.5);

                Assert.Equal(-1.0, v.Get(0));
                Assert.Equal(5.0, v.Get(1));
                Assert.Equal(-0.5, v.Get(2));
            }
Exemplo n.º 6
0
        public void VectorAdditionAndSubtraction()
        {
            Vector3D Point1 = new Vector3D();

            Point1.Set(1, 1, 1);

            Vector3D Point2 = new Vector3D();

            Point2.Set(2, 2, 2);

            Vector3D Point3 = new Vector3D();

            Point3.Plus(Point1, Point2);
            Assert.IsTrue(Point3 == new Vector3D(3, 3, 3));

            Point3.Minus(Point1, Point2);
            Assert.IsTrue(Point3 == new Vector3D(-1, -1, -1));

            Point3 += Point1;
            Assert.IsTrue(Point3 == new Vector3D(0, 0, 0));

            Point3 += Point2;
            Assert.IsTrue(Point3 == new Vector3D(2, 2, 2));

            Point3.Set(3, -4, 5);
            Assert.IsTrue(Point3.GetRadius() > 7.07 && Point3.GetRadius() < 7.08);

            Vector3D InlineOpLeftSide  = new Vector3D(5.0f, -3.0f, .0f);
            Vector3D InlineOpRightSide = new Vector3D(-5.0f, 4.0f, 1.0f);

            Assert.IsTrue(InlineOpLeftSide + InlineOpRightSide == new Vector3D(.0f, 1.0f, 1.0f));

            Assert.IsTrue(InlineOpLeftSide - InlineOpRightSide == new Vector3D(10.0f, -7.0f, -1.0f));
        }
Exemplo n.º 7
0
    public static void UpdateFacePoint(SensorAdapter adapter, Frame frame, Vector2D facePoint, Transform facePointTransform, Transform viewPlane, Visualization visualization, float updateSmoothness)
    {
        bool ignoreAdapter = VideoPlayer.IsPlaying || !Application.isEditor && Application.platform == RuntimePlatform.Android;

        if ((!ignoreAdapter && adapter == null) || facePointTransform == null || viewPlane == null)
        {
            return;
        }

        Vector3 viewPlanePosition = viewPlane.position;

        LightBuzz.Quaternion viewPlaneRotation = viewPlane.rotation;
        Vector3D             viewPlaneScale    = viewPlane.localScale;

        if (viewPlane.GetType() == typeof(RectTransform))
        {
            viewPlaneScale.Set(viewPlaneScale.X * ((RectTransform)viewPlane).root.localScale.x * ((RectTransform)viewPlane).rect.size.x,
                               viewPlaneScale.Y * ((RectTransform)viewPlane).root.localScale.y * ((RectTransform)viewPlane).rect.size.y, 1);
        }

        float smoothness = Mathf.Lerp(1f, Time.deltaTime, updateSmoothness);

        Vector3D position = visualization == Visualization.Image ? facePoint : VideoPlayer.IsPlaying ? default(Vector2D) :
                            !Application.isEditor && Application.platform == RuntimePlatform.Android ? facePoint : adapter.ImageToDepthSpace(facePoint);

        Vector2Int resolution = visualization == Visualization.Image ?
                                new Vector2Int(frame.ImageWidth, frame.ImageHeight) :
                                new Vector2Int(frame.DepthWidth, frame.DepthHeight);

        facePointTransform.position = Vector3D.Lerp(facePointTransform.position,
                                                    position.GetPositionOnPlane(resolution.x, resolution.y, viewPlanePosition, viewPlaneRotation, viewPlaneScale), smoothness);
    }
Exemplo n.º 8
0
        // move the model and see if we need to send an update to the server.
        // this only applies to the currently possessed avatar atm.
        public void Move(Vector3D oldPosition, Vector3D velocity, Vector3D newRotation)
        {
            // has the change in velocity been above the threshhold?
            currentVelocity.Set(velocity);
            if ((currentVelocity - lastVelocitySent).GetMagnitudeSquared() > 1)
            {
                velocityChanged = true;
            }

            // TODO: do we really care about state? the server takes care of this,
            // all we need concern ourselves with is velocity change.
            // eg: We do need to know if we have stopped.

            // check to see if we have entered running/walking
            float magnitude = currentVelocity.GetMagnitudeSquared();

            if (magnitude > 1)
            {
                if (physicalObject is Mobile && ((Mobile)physicalObject).MobileState != EnumMobileState.Running)
                {
                    ((Mobile)physicalObject).MobileState = EnumMobileState.Running;
                    stateChanged = true;
                }
            }
            else if (magnitude > 0.3)
            {
                if (physicalObject is Mobile && ((Mobile)physicalObject).MobileState != EnumMobileState.Walking)
                {
                    ((Mobile)physicalObject).MobileState = EnumMobileState.Walking;
                    stateChanged = true;
                }
            }

            // have we stopped?
            if (currentVelocity == Vector3D.Origin)
            {
                if (lastVelocitySent != Vector3D.Origin)
                {
                    if (physicalObject is Mobile && ((Mobile)physicalObject).MobileState != EnumMobileState.Standing)
                    {
                        ((Mobile)physicalObject).MobileState = EnumMobileState.Standing;
                        stateChanged = true;
                    }
                }
            }
            else
            {
                model.Position = model.Position + currentVelocity;
                hasMoved       = true;
            }

            // have we rotated?
            if (model.Rotation != newRotation)
            {
                model.Rotation = newRotation;
                hasMoved       = true;
            }
        }
Exemplo n.º 9
0
        public void TestSet()
        {
            float    x = 10.5f, y = 109.21f, z = 100;
            Vector3D v = new Vector3D();

            v.Set(x, y, z);

            TestHelper.AssertEquals(x, y, z, v, "Test v.Set()");
        }
Exemplo n.º 10
0
        private void RotateModel(Scene scene)
        {
            Assimp.Node root = null;
            for (int i = 0; i < scene.RootNode.ChildCount; i++)
            {
                if (scene.RootNode.Children[i].Name.ToLowerInvariant() == "skeleton_root")
                {
                    if (scene.RootNode.Children[i].ChildCount == 0)
                    {
                        throw new System.Exception("skeleton_root has no children! If you are making a rigged model, make sure skeleton_root contains the root of your skeleton.");
                    }
                    root = scene.RootNode.Children[i].Children[0];
                    break;
                }
            }

            Matrix4x4 rotate    = Matrix4x4.FromRotationX((float)(-(1 / 2.0) * Math.PI));
            Matrix4x4 rotateinv = rotate;

            rotateinv.Inverse();


            foreach (Mesh mesh in scene.Meshes)
            {
                if (root != null)
                {
                    foreach (Assimp.Bone bone in mesh.Bones)
                    {
                        bone.OffsetMatrix = rotateinv * bone.OffsetMatrix;
                    }
                }

                for (int i = 0; i < mesh.VertexCount; i++)
                {
                    Vector3D vertex = mesh.Vertices[i];
                    vertex.Set(vertex.X, vertex.Z, -vertex.Y);
                    mesh.Vertices[i] = vertex;
                }
                for (int i = 0; i < mesh.Normals.Count; i++)
                {
                    Vector3D norm = mesh.Normals[i];
                    norm.Set(norm.X, norm.Z, -norm.Y);

                    mesh.Normals[i] = norm;
                }
            }
        }
Exemplo n.º 11
0
		public void GetBoundingBox( Vector3D minbox, Vector3D maxbox ) {
			minbox.Set( _boxmin );
			maxbox.Set( _boxmax );
		}
Exemplo n.º 12
0
    public void UpdateStickman(Frame frame, Body body, Transform viewPlane)
    {
        bool isPlaybackFrame = frame != null && frame.IsPlaybackFrame;

        if ((!isPlaybackFrame && adapter == null) || frame == null || body == null || viewPlane == null)
        {
            return;
        }

        Vector3D viewPlanePosition = viewPlane.position;

        LightBuzz.Quaternion viewPlaneRotation = viewPlane.rotation;
        Vector3D             viewPlaneScale    = viewPlane.localScale;

        if (viewPlane.GetType() == typeof(RectTransform))
        {
            viewPlaneScale.Set(viewPlaneScale.X * ((RectTransform)viewPlane).root.localScale.x * ((RectTransform)viewPlane).rect.size.x,
                               viewPlaneScale.Y * ((RectTransform)viewPlane).root.localScale.y * ((RectTransform)viewPlane).rect.size.y, 1);
        }

        float smoothness = Mathf.Lerp(1f, Time.deltaTime, updateSmoothness);

        //Vector3D currPosition;

        for (int i = 0; i < jointPoints.Length; i++)
        {
            //if (isPlaybackFrame)
            //{
            //    currPosition = VideoPlayer.WorldToImageSpace(JointTypes[i], frame, body).GetPositionOnPlane(
            //        frame.ImageWidth, frame.ImageHeight, viewPlanePosition, viewPlaneRotation, viewPlaneScale);
            //}
            //else
            //{
            //    currPosition = adapter.WorldToImageSpace(body.Joints[JointTypes[i]].WorldPosition).GetPositionOnPlane(
            //        frame.ImageWidth, frame.ImageHeight, viewPlanePosition, viewPlaneRotation, viewPlaneScale);
            //}

            //jointPoints[i].position = Vector3D.Lerp(jointPoints[i].position, currPosition, smoothness);

            jointPoints[i].position = body.Joints[JointTypes[i]].WorldPosition * BodyScale;
        }

        jointLines[0].SetPosition(0, jointPoints[0].position);
        jointLines[0].SetPosition(1, jointPoints[1].position);
        jointLines[0].SetPosition(2, jointPoints[2].position);
        jointLines[0].SetPosition(3, jointPoints[3].position);
        jointLines[0].SetPosition(4, jointPoints[4].position);

        jointLines[1].SetPosition(0, jointPoints[8].position);
        jointLines[1].SetPosition(1, jointPoints[7].position);
        jointLines[1].SetPosition(2, jointPoints[6].position);
        jointLines[1].SetPosition(3, jointPoints[5].position);
        jointLines[1].SetPosition(4, jointPoints[2].position);
        jointLines[1].SetPosition(5, jointPoints[9].position);
        jointLines[1].SetPosition(6, jointPoints[10].position);
        jointLines[1].SetPosition(7, jointPoints[11].position);
        jointLines[1].SetPosition(8, jointPoints[12].position);

        jointLines[2].SetPosition(0, jointPoints[16].position);
        jointLines[2].SetPosition(1, jointPoints[15].position);
        jointLines[2].SetPosition(2, jointPoints[14].position);
        jointLines[2].SetPosition(3, jointPoints[13].position);
        jointLines[2].SetPosition(4, jointPoints[4].position);
        jointLines[2].SetPosition(5, jointPoints[17].position);
        jointLines[2].SetPosition(6, jointPoints[18].position);
        jointLines[2].SetPosition(7, jointPoints[19].position);
        jointLines[2].SetPosition(8, jointPoints[20].position);
    }
Exemplo n.º 13
0
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            UnityEngine.SceneManagement.SceneManager.LoadScene(0);

            return;
        }

        if (adapter == null)
        {
            return;
        }

        if (adapter.SensorType != sensorType)
        {
            adapter.SensorType = sensorType;
        }

        Frame frame = adapter.UpdateFrame();

        if (frame != null)
        {
            if (frame.ImageData != null && frame.UserSpaceData != null)
            {
                greenScreenFilter.UpdateFilter(frame);
                if (greenScreenFilter.Result != null)
                {
                    greenScreenViewTexture = ValidateTexture(greenScreenViewTexture, frame.DepthWidth, frame.DepthHeight, greenScreenViewRawImage);

                    if (greenScreenViewTexture != null)
                    {
                        greenScreenViewTexture.LoadRawTextureData(greenScreenFilter.Result);
                        greenScreenViewTexture.Apply(false);
                    }
                }
            }

            Body body = frame.GetClosestBody();

            if (body != null)
            {
                screenViewStickman.UpdateStickman(adapter, frame, body, greenScreenViewTransform, Visualization.Depth);

                uiPlaneScale = greenScreenViewTransform.localScale;
                uiPlaneScale.Set(
                    uiPlaneScale.X * ((RectTransform)greenScreenViewTransform).root.localScale.x * ((RectTransform)greenScreenViewTransform).rect.size.x,
                    uiPlaneScale.Y * ((RectTransform)greenScreenViewTransform).root.localScale.y * ((RectTransform)greenScreenViewTransform).rect.size.y, 1);

                float spineLengthWorld;
                float spineLengthScreen;
                MeasureBoneLength(body, JointType.SpineShoulder, JointType.SpineBase, boneLengths[0], 2, 4, out spineLengthWorld, out spineLengthScreen);

                float armLeftLengthWorld;
                float armLeftLengthScreen;
                MeasureBoneLength(body, JointType.ShoulderLeft, JointType.ElbowLeft, boneLengths[1], 5, 6, out armLeftLengthWorld, out armLeftLengthScreen);

                float forearmLeftLengthWorld;
                float forearmLeftLengthScreen;
                MeasureBoneLength(body, JointType.ElbowLeft, JointType.WristLeft, boneLengths[2], 6, 7, out forearmLeftLengthWorld, out forearmLeftLengthScreen);

                float armRightLengthWorld;
                float armRightLengthScreen;
                MeasureBoneLength(body, JointType.ShoulderRight, JointType.ElbowRight, boneLengths[3], 8, 9, out armRightLengthWorld, out armRightLengthScreen);

                float forearmRightLengthWorld;
                float forearmRightLengthScreen;
                MeasureBoneLength(body, JointType.ElbowRight, JointType.WristRight, boneLengths[4], 9, 10, out forearmRightLengthWorld, out forearmRightLengthScreen);

                float thighLeftLengthWorld;
                float thighLeftLengthScreen;
                MeasureBoneLength(body, JointType.HipLeft, JointType.KneeLeft, boneLengths[5], 11, 12, out thighLeftLengthWorld, out thighLeftLengthScreen);

                float calfLeftLengthWorld;
                float calfLeftLengthScreen;
                MeasureBoneLength(body, JointType.KneeLeft, JointType.AnkleLeft, boneLengths[6], 12, 13, out calfLeftLengthWorld, out calfLeftLengthScreen);

                float thighRightLengthWorld;
                float thighRightLengthScreen;
                MeasureBoneLength(body, JointType.HipRight, JointType.KneeRight, boneLengths[7], 14, 15, out thighRightLengthWorld, out thighRightLengthScreen);

                float calfRightLengthWorld;
                float calfRightLengthScreen;
                MeasureBoneLength(body, JointType.KneeRight, JointType.AnkleRight, boneLengths[8], 15, 16, out calfRightLengthWorld, out calfRightLengthScreen);

                MeasureBoneWidth(frame, body, JointType.SpineShoulder, JointType.SpineBase, boneWidthTexts[0], boneLines[0], spineLengthWorld, spineLengthScreen);
                MeasureBoneWidth(frame, body, JointType.ShoulderLeft, JointType.ElbowLeft, boneWidthTexts[1], boneLines[1], armLeftLengthWorld, armLeftLengthScreen);
                MeasureBoneWidth(frame, body, JointType.ElbowLeft, JointType.WristLeft, boneWidthTexts[2], boneLines[2], forearmLeftLengthWorld, forearmLeftLengthScreen);
                MeasureBoneWidth(frame, body, JointType.ShoulderRight, JointType.ElbowRight, boneWidthTexts[3], boneLines[3], armRightLengthWorld, armRightLengthScreen);
                MeasureBoneWidth(frame, body, JointType.ElbowRight, JointType.WristRight, boneWidthTexts[4], boneLines[4], forearmRightLengthWorld, forearmRightLengthScreen);
                MeasureBoneWidth(frame, body, JointType.HipLeft, JointType.KneeLeft, boneWidthTexts[5], boneLines[5], thighLeftLengthWorld, thighLeftLengthScreen);
                MeasureBoneWidth(frame, body, JointType.KneeLeft, JointType.AnkleLeft, boneWidthTexts[6], boneLines[6], calfLeftLengthWorld, calfLeftLengthScreen);
                MeasureBoneWidth(frame, body, JointType.HipRight, JointType.KneeRight, boneWidthTexts[7], boneLines[7], thighRightLengthWorld, thighRightLengthScreen);
                MeasureBoneWidth(frame, body, JointType.KneeRight, JointType.AnkleRight, boneWidthTexts[8], boneLines[8], calfRightLengthWorld, calfRightLengthScreen);
            }
        }
    }
Exemplo n.º 14
0
        /// <summary>
        /// states if the given polygon contains the test point ( z not considered )
        /// https://en.wikipedia.org/wiki/Point_in_polygon
        /// By default check the point contained in the polygon perimeter.
        /// Optionally duplicate points are zapped in comparing.
        /// </summary>
        public static bool ContainsPoint(this IReadOnlyList <Vector3D> _pts, double tol, Vector3D _pt, bool zapDuplicates = false)
        {
            var pt          = _pt.Set(OrdIdx.Z, 0);
            var pts         = _pts.Select(w => w.Set(OrdIdx.Z, 0));
            var ptHs        = new HashSet <Vector3D>(new Vector3DEqualityComparer(tol));
            var ptsFiltered = pts;

            var pts_bbox = _pts.BBox();

            if (!pts_bbox.Contains2D(tol, _pt))
            {
                return(false);
            }

            if (zapDuplicates)
            {
                var tmp = new List <Vector3D>();
                foreach (var p in pts)
                {
                    if (!ptHs.Contains(p))
                    {
                        ptHs.Add(p);
                        tmp.Add(p);
                    }
                }
                ptsFiltered = tmp;
            }
            var segs = ptsFiltered.PolygonSegments(tol);

            if (_pts.Any(w => _pt.EqualsTol(tol, w)))
            {
                return(true);
            }

            var ray            = new Line3D(pt, Vector3D.XAxis, Line3DConstructMode.PointAndVector);
            var conflictVertex = false;

            do
            {
                conflictVertex = false;
                foreach (var pp in ptsFiltered)
                {
                    if (ray.LineContainsPoint(tol, pp))
                    {
                        conflictVertex = true;
                        // ray intersect vertex, change it
                        ray = new Line3D(pt, pp + Vector3D.YAxis * tol * 1.1);
                        break;
                    }
                }
            }while (conflictVertex);

            var intCnt = 0;

            foreach (var seg in segs)
            {
                if (seg.SegmentContainsPoint(tol, pt))
                {
                    return(true);
                }

                Vector3D ip = null;

                ip = ray.Intersect(tol, seg);
                if (ip != null && seg.SegmentContainsPoint(tol, ip))
                {
                    if (pt.X.GreatThanOrEqualsTol(tol, ip.X))
                    {
                        ++intCnt;
                    }
                }
            }

            return(intCnt % 2 != 0);
        }
Exemplo n.º 15
0
		void ProcessPlayerInput() 
		{
			// no avatar... no nothing
			if ( Game.CurrentWorld.CurrentAvatar == null ) return;

			if ( keyboard.GetKeyState( Key.key_F5 ) ) 
			{
				Game.CurrentMainWindow.SetGameControlMode();
			} 
			else if ( keyboard.GetKeyState( Key.key_F6 ) ) 
			{
				Game.CurrentMainWindow.ReleaseGameControlMode();
			}
			if ( Game.GameControlMode ) 
			{
				if ( keyboard.GetKeyState( Key.key_ESCAPE ) ) 
				{
					Game.CurrentMainWindow.ReleaseGameControlMode();
				} 
				else if ( keyboard.GetKeyState( Key.key_1 ) ) 
				{
					Game.CurrentGameCommand = EnumSkill.Kill;
				} 
				else if ( keyboard.GetKeyState( Key.key_2 ) ) 
				{
					Game.CurrentGameCommand = EnumSkill.AcidBlast;
				} 
				else if ( keyboard.GetKeyState( Key.key_3 ) ) 
				{
					Game.CurrentGameCommand = EnumSkill.Kick;
				} 
				else if ( keyboard.GetKeyState( Key.key_4 ) ) 
				{
					Game.CurrentGameCommand = EnumSkill.Levitate;
				} 
				else if ( keyboard.GetKeyState( Key.key_0 ) ) 
				{
					Game.CurrentGameCommand = EnumSkill.None;
				}
			}

			// if not in game control mode, don't respond to game controls
			if ( !Game.GameControlMode ) 
			{
				return;
			}
			
			float moveunit = 1.39F * (float)movementTimer.ElapsedSeconds();
			if ( keyboard.GetKeyState(Key.key_LEFTSHIFT) ) {
				moveunit *= 2.5F;
			}

			#region ProcessRotationInput

			Vector3D avatarPosition = Game.CurrentWorld.CurrentAvatar.model.Position.Clone();
			Vector3D newRotation = Game.CurrentWorld.CurrentAvatar.model.Rotation.Clone();
			mouse.GetState();
			if( mouse.X != 0 ) 
			{
				newRotation.Y += mouse.X*0.2f; 
				newRotation.X = pitch;
			}
			if( mouse.Y != 0 ) 
			{
				pitch += mouse.Y*0.2f;
				if ( pitch > 60 ) { pitch = 60; }
				if ( pitch < -60 ) { pitch = -60; }
				newRotation.X = pitch;
			}

			if( keyboard.GetKeyState(Key.key_Q) ) 
			{
				newRotation.Y -= moveunit*2F;
			}
			if(keyboard.GetKeyState(Key.key_E)) 
			{
				newRotation.Y += moveunit*2F;
			}

			#endregion
			#region 2.0 Process Movement Input


			Vector3D changeOfPosition = new Vector3D( 0, 0, 0 );
			if ( keyboard.GetKeyState(Key.key_W) ) 
			{
				changeOfPosition.X += (float)Math.Sin( newRotation.Y * Math.PI/180.0 ) * moveunit;
				changeOfPosition.Z += (float)Math.Cos( newRotation.Y * Math.PI/180.0 ) * moveunit;
			}
			if ( keyboard.GetKeyState(Key.key_S) ) 
			{
				changeOfPosition.X -= (float)Math.Sin( newRotation.Y * Math.PI/180.0 ) * moveunit/2F;
				changeOfPosition.Z -= (float)Math.Cos( newRotation.Y * Math.PI/180.0 ) * moveunit/2F;
			}
			if ( keyboard.GetKeyState(Key.key_D) ) 
			{
				changeOfPosition.X += (float)Math.Cos( newRotation.Y * Math.PI/180.0 ) * moveunit/2F;
				changeOfPosition.Z -= (float)Math.Sin( newRotation.Y * Math.PI/180.0 ) * moveunit/2F;
			}
			if( keyboard.GetKeyState(Key.key_A) ) 
			{
				changeOfPosition.X -=	(float)Math.Cos( newRotation.Y * Math.PI/180.0 ) * moveunit/2F;
				changeOfPosition.Z +=	(float)Math.Sin( newRotation.Y * Math.PI/180.0 ) * moveunit/2F;
			}

			if( changeOfPosition.GetMagnitudeSquared() != 0 ) 
			{
				// stay on the ground
				// TODO: What about when walking on objects?
				Vector3D newPosition = avatarPosition + changeOfPosition;
				try 
				{
					newPosition.Y = 
						Game.CurrentWorld.TerrainPieces.AltitudeAt( newPosition.X, newPosition.Z ) + Game.CurrentWorld.CurrentAvatar.physicalObject.Height/2;
						//Game.CurrentWorld.WorldTerrain.HeightLookup( newPosition.X, newPosition.Z ) + Game.CurrentWorld.CurrentAvatar.physicalObject.Height/2;
					changeOfPosition.Y = newPosition.Y - avatarPosition.Y;

					// check that we can go there
					foreach ( PhysicalObjectInstance poi in Game.CurrentWorld.physicalObjectInstances.Values ) 
					{
						if ( poi.physicalObject is Terrain ) 
						{
							continue;
						}
						if ( poi == Game.CurrentWorld.CurrentAvatar ) 
						{
							//ignore ourselves
							continue;
						}

						// do a bounding sphere test to see if the movement will go near poi
						// test from the middle of the line drawn between current position
						// and future position, distance is the radius of both objects
						// plus half the distance of the movement.
						float dx = avatarPosition.X + changeOfPosition.X / 2F - poi.model.Position.X;
						float dy = avatarPosition.Y + changeOfPosition.Y / 2F - poi.model.Position.Y;
						float dz = avatarPosition.Z + changeOfPosition.Z / 2F - poi.model.Position.Z;
						float distance_squared = dx*dx + dy*dy + dz*dz;
						float distance_moved = changeOfPosition.X * changeOfPosition.X + changeOfPosition.Y * changeOfPosition.Y + changeOfPosition.Z * changeOfPosition.Z;
						// TODO: optimize, no sqrts
						if ( Math.Sqrt(distance_squared) < Math.Sqrt(poi.model.RadiusSquared) + Math.Sqrt(Game.CurrentWorld.CurrentAvatar.model.RadiusSquared) + Math.Sqrt(distance_moved)/2F ) 
						{
							// ok, these objects are close enough to collide,
							// but did a collision really happen?
							// now we do a more acurate test to find out.

							Vector3D boxmin1 = new Vector3D();
							Vector3D boxmax1 = new Vector3D();
							Vector3D boxmin2 = new Vector3D();
							Vector3D boxmax2 = new Vector3D();
							poi.model.GetBoundingBox( boxmin1, boxmax1 );
							Game.CurrentWorld.CurrentAvatar.model.GetBoundingBox( boxmin2, boxmax2 );
							Vector3D halfbox1size = (boxmax1 - boxmin1)/2;
							boxmin2 -= halfbox1size;
							boxmax2 += halfbox1size;
							boxmin2 += poi.model.Position;
							boxmax2 += poi.model.Position;

							if (
								avatarPosition.X > boxmin2.X
								&& avatarPosition.Y > boxmin2.Y
								&& avatarPosition.Z > boxmin2.Z
								&& avatarPosition.X < boxmax2.X
								&& avatarPosition.Y < boxmax2.Y
								&& avatarPosition.Z < boxmax2.Z
								) 
							{
								// already in a collision, ignore collision detection
								break;
							}

							if (
								newPosition.X > boxmin2.X
								&& newPosition.Y > boxmin2.Y
								&& newPosition.Z > boxmin2.Z
								&& newPosition.X < boxmax2.X
								&& newPosition.Y < boxmax2.Y
								&& newPosition.Z < boxmax2.Z
								) 
							{
								// would be a collision
								changeOfPosition.Set( 0, 0, 0 );
								break;
								// TODO: should actually figure out the collision point
							}
						}
					}
				} 
				catch ( InvalidLocationException ) 
				{
					changeOfPosition.Set( 0, 0, 0 );
				}
				// NB: PlayerMovement is called regardless,
				// as we need to update values for message throtling
			}

			#endregion
			PlayerMovement( avatarPosition, changeOfPosition, newRotation );
			Game.CurrentWorld.RepositionCamera();
		}
Exemplo n.º 16
0
        public Model(
            Scene scene, string modelDirectory,
            List <Materials.Material> mat_presets = null, TristripOption triopt = TristripOption.DoNotTriStrip,
            bool flipAxis = false, bool fixNormals = false, string additionalTexPath = null)
        {
            Assimp.Node root = null;
            for (int i = 0; i < scene.RootNode.ChildCount; i++)
            {
                if (scene.RootNode.Children[i].Name.ToLowerInvariant() == "skeleton_root")
                {
                    if (scene.RootNode.Children[i].ChildCount == 0)
                    {
                        throw new System.Exception("skeleton_root has no children! If you are making a rigged model, make sure skeleton_root contains the root of your skeleton.");
                    }
                    root = scene.RootNode.Children[i].Children[0];
                    break;
                }
            }

            foreach (Mesh mesh in scene.Meshes)
            {
                if (mesh.HasBones && root == null)
                {
                    throw new System.Exception("Model uses bones but the skeleton root has not been found! Make sure your skeleton is inside a dummy object called 'skeleton_root'.");
                }
            }

            Matrix3x3 rotateXminus90 = Matrix3x3.FromRotationX((float)(-(1 / 2.0) * Math.PI));
            Matrix3x3 rotateXplus90  = Matrix3x3.FromRotationX((float)((1 / 2.0) * Math.PI));
            Matrix3x3 rotateYminus90 = Matrix3x3.FromRotationY((float)(-(1 / 2.0) * Math.PI));
            Matrix3x3 rotateYplus90  = Matrix3x3.FromRotationY((float)((1 / 2.0) * Math.PI));
            Matrix3x3 rotateZminus90 = Matrix3x3.FromRotationZ((float)(-(1 / 2.0) * Math.PI));
            Matrix3x3 rotateZplus90  = Matrix3x3.FromRotationZ((float)((1 / 2.0) * Math.PI));

            if (flipAxis)
            {
                Console.WriteLine("Rotating the model...");
                int       i      = 0;
                Matrix4x4 rotate = Matrix4x4.FromRotationX((float)(-(1 / 2.0) * Math.PI));
                //rotate = Matrix4x4.FromRotationZ((float)(-(1 / 2.0) * Math.PI));
                Matrix4x4 rotateinv = rotate;



                //Matrix3x3 rotvec = rotateZplus90 * rotateXplus90;
                //Matrix3x3 rotvec = rotateYplus90*rotateYplus90 * rotateZplus90 * rotateZplus90* rotateXplus90* rotateXplus90;

                rotateinv.Inverse();
                //rotate = Matrix4x4.FromRotationY((float)(-(1 / 2.0) * Math.PI));
                //rotate = Matrix4x4.FromRotationZ((float)(-(1 / 2.0) * Math.PI));
                Matrix4x4 rotateC = Matrix4x4.FromRotationX((float)(-(1 / 2.0) * Math.PI));
                Matrix4x4 trans;

                if (root != null)
                {
                    // Rotate rigged mesh
                    foreach (Mesh mesh in scene.Meshes)
                    {
                        Console.WriteLine(mesh.Name);
                        Console.WriteLine(String.Format("Does it have bones? {0}", mesh.HasBones));

                        Matrix3x3[] weightedmats = new Matrix3x3[mesh.Normals.Count];

                        foreach (Assimp.Bone bone in mesh.Bones)
                        {
                            bone.OffsetMatrix = rotateinv * bone.OffsetMatrix;

                            /*Matrix3x3 invbind = bone.OffsetMatrix;
                             * //bind.Inverse();
                             * //List<int> vertices = new List<VertexWeight>();
                             *
                             * foreach (Assimp.VertexWeight weight in bone.VertexWeights) {
                             *  Matrix3x3 weightedcurrentmat = new Matrix3x3(
                             *          weight.Weight * invbind.A1, weight.Weight * invbind.A2, weight.Weight * invbind.A1,
                             *          weight.Weight * invbind.B1, weight.Weight * invbind.B2, weight.Weight * invbind.B3,
                             *          weight.Weight * invbind.C1, weight.Weight * invbind.C2, weight.Weight * invbind.C3);
                             *
                             *  if (weightedmats[weight.VertexID] == null) {
                             *      weightedmats[weight.VertexID] = weightedcurrentmat;
                             *  }
                             *  else {
                             *      Matrix3x3 existingmat = weightedmats[weight.VertexID];
                             *      weightedmats[weight.VertexID] = new Matrix3x3(
                             *          existingmat.A1 + invbind.A1, existingmat.A2 + invbind.A2, existingmat.A3 + invbind.A3,
                             *          existingmat.B1 + invbind.B1, existingmat.B2 + invbind.B2, existingmat.B3 + invbind.B3,
                             *          existingmat.C1 + invbind.C1, existingmat.C2 + invbind.C2, existingmat.C3 + invbind.C3);
                             *  }
                             * }*/

                            //Matrix4x4 bindMat = bone.OffsetMatrix;
                            //bindMat.Inverse();
                            //trans =

                            /*bone.OffsetMatrix = root.Transform * bone.OffsetMatrix;
                             * Matrix4x4 newtransform = root.Transform * rotate;
                             * newtransform.Inverse();
                             * bone.OffsetMatrix = newtransform * bone.OffsetMatrix;*/
                        }

                        for (i = 0; i < mesh.VertexCount; i++)
                        {
                            Vector3D vertex = mesh.Vertices[i];
                            vertex.Set(vertex.X, vertex.Z, -vertex.Y);
                            mesh.Vertices[i] = vertex;
                        }
                        for (i = 0; i < mesh.Normals.Count; i++)
                        {
                            Vector3D norm = mesh.Normals[i];
                            norm.Set(norm.X, norm.Z, -norm.Y);

                            //Matrix3x3 invbind = weightedmats[i];
                            //invbind.Inverse();
                            //norm = invbind * norm;

                            mesh.Normals[i] = norm;
                        }
                    }
                }
                else
                {
                    // Rotate static mesh
                    foreach (Mesh mesh in scene.Meshes)
                    {
                        for (i = 0; i < mesh.VertexCount; i++)
                        {
                            Vector3D vertex = mesh.Vertices[i];
                            vertex.Set(vertex.X, vertex.Z, -vertex.Y);
                            mesh.Vertices[i] = vertex;
                        }
                        for (i = 0; i < mesh.Normals.Count; i++)
                        {
                            Vector3D norm = mesh.Normals[i];
                            norm.Set(norm.X, norm.Z, -norm.Y);
                            mesh.Normals[i] = norm;
                        }
                    }
                }



                if (root != null)
                {
                    List <Assimp.Node> allnodes     = new List <Assimp.Node>();
                    List <Assimp.Node> processnodes = new List <Assimp.Node>();
                    processnodes.Add(root);
                    root.Transform = root.Transform * rotate;

                    /*while (processnodes.Count > 0) {
                     *  Assimp.Node current = processnodes[0];
                     *  processnodes.RemoveAt(0);
                     *
                     *  current.Transform = current.Transform * rotate;
                     *
                     *  foreach (Assimp.Node child in current.Children) {
                     *      processnodes.Add(child);
                     *  }
                     * }*/
                }
            }

            // On rigged models we attempt to fix normals for shading to work properly (when using materials)
            // That works by multiplying the normal for a vertex with the inverse bind matrices that have an effect on the vertex.
            // Seems to work semi-well, might need to look over this at a later point again though.
            Console.WriteLine(String.Format("fixNormals is {0}", fixNormals));
            if (fixNormals && root != null)
            {
                Console.WriteLine("Fixing the normals on the rigged mesh...");
                foreach (Mesh mesh in scene.Meshes)
                {
                    List <Tuple <float, Matrix3x3> >[] weightedmats = new List <Tuple <float, Matrix3x3> > [mesh.Normals.Count];//new Matrix3x3[mesh.Normals.Count];

                    foreach (Assimp.Bone bone in mesh.Bones)
                    {
                        Matrix3x3 invbind = bone.OffsetMatrix;

                        foreach (Assimp.VertexWeight weight in bone.VertexWeights)
                        {
                            if (weightedmats[weight.VertexID] == null)
                            {
                                weightedmats[weight.VertexID] = new List <Tuple <float, Matrix3x3> >();
                            }
                            weightedmats[weight.VertexID].Add(Tuple.Create(weight.Weight, invbind));

                            /*Matrix3x3 weightedcurrentmat = new Matrix3x3(
                             *      weight.Weight * invbind.A1, weight.Weight * invbind.A2, weight.Weight * invbind.A1,
                             *      weight.Weight * invbind.B1, weight.Weight * invbind.B2, weight.Weight * invbind.B3,
                             *      weight.Weight * invbind.C1, weight.Weight * invbind.C2, weight.Weight * invbind.C3);
                             *
                             * if (weightedmats[weight.VertexID] == null) {
                             *  weightedmats[weight.VertexID] = weightedcurrentmat;
                             * }
                             * else {
                             *  Matrix3x3 existingmat = weightedmats[weight.VertexID];
                             *  weightedmats[weight.VertexID] = new Matrix3x3(
                             *      existingmat.A1 + invbind.A1, existingmat.A2 + invbind.A2, existingmat.A3 + invbind.A3,
                             *      existingmat.B1 + invbind.B1, existingmat.B2 + invbind.B2, existingmat.B3 + invbind.B3,
                             *      existingmat.C1 + invbind.C1, existingmat.C2 + invbind.C2, existingmat.C3 + invbind.C3);
                             * }*/
                        }
                    }

                    for (int i = 0; i < mesh.Normals.Count; i++)
                    {
                        if (weightedmats[i] == null)
                        {
                            continue; // means that index hasn't been weighted to so we can't do anything?
                        }

                        //weightedmats[i].Sort((x, y) => y.Item1.CompareTo(x.Item1));

                        Vector3D norm = mesh.Normals[i];

                        Matrix3x3 invbind = ScalarMultiply3x3(weightedmats[i][0].Item1, weightedmats[i][0].Item2);
                        for (int j = 1; j < weightedmats[i].Count; j++)
                        {
                            invbind = AddMatrix3x3(
                                invbind,
                                ScalarMultiply3x3(weightedmats[i][j].Item1, weightedmats[i][j].Item2)
                                );
                        }

                        norm = invbind * norm;

                        mesh.Normals[i] = norm;
                    }
                }
            }

            // We check if the model mixes weighted and unweighted vertices.
            // If that is the case, we throw an exception here. If we don't,
            // an exception will be thrown later on that is less helpful to the user.
            if (true)
            {
                bool usesWeights = false;
                foreach (Mesh mesh in scene.Meshes)
                {
                    bool[] weightedmats = new bool[mesh.VertexCount];

                    foreach (Assimp.Bone bone in mesh.Bones)
                    {
                        foreach (Assimp.VertexWeight weight in bone.VertexWeights)
                        {
                            weightedmats[weight.VertexID] = true;
                        }
                    }

                    for (uint i = 0; i < mesh.VertexCount; i++)
                    {
                        if (weightedmats[i] == true)
                        {
                            usesWeights = true;
                        }
                        else if (usesWeights)
                        {
                            throw new System.Exception("Model has a mixture of weighted and unweighted vertices! Please weight all vertices to at least one bone.");
                        }
                    }
                }
            }
            VertexData = new VTX1(scene);
            Joints     = new JNT1(scene, VertexData);
            Scenegraph = new INF1(scene, Joints);
            Textures   = new TEX1(scene, Path.GetDirectoryName(modelDirectory));

            SkinningEnvelopes = new EVP1();
            SkinningEnvelopes.SetInverseBindMatrices(scene, Joints.FlatSkeleton);
            //SkinningEnvelopes.AddInverseBindMatrices(Joints.FlatSkeleton);

            PartialWeightData = new DRW1(scene, Joints.BoneNameIndices);

            Shapes    = SHP1.Create(scene, Joints.BoneNameIndices, VertexData.Attributes, SkinningEnvelopes, PartialWeightData, triopt);
            Materials = new MAT3(scene, Textures, Shapes, mat_presets);

            if (additionalTexPath == null)
            {
                Materials.LoadAdditionalTextures(Textures, Path.GetDirectoryName(modelDirectory));
            }
            else
            {
                Materials.LoadAdditionalTextures(Textures, additionalTexPath);
            }

            Materials.MapTextureNamesToIndices(Textures);

            foreach (Geometry.Shape shape in Shapes.Shapes)
            {
                packetCount += shape.Packets.Count;
            }

            vertexCount = VertexData.Attributes.Positions.Count;
        }
Exemplo n.º 17
0
 public void GetBoundingBox(Vector3D minbox, Vector3D maxbox)
 {
     minbox.Set(_boxmin);
     maxbox.Set(_boxmax);
 }
Exemplo n.º 18
0
    public void UpdateStickface(SensorAdapter adapter, Frame frame, Face face, Transform viewPlane, Visualization visualization)
    {
        bool isPlaybackFrame = frame != null && frame.IsPlaybackFrame;

        if (face == null || viewPlane == null || (!isPlaybackFrame && adapter == null))
        {
            return;
        }

        if (!initialized)
        {
            Initialize();
        }

        Vector3 viewPlanePosition = viewPlane.position;

        LightBuzz.Quaternion viewPlaneRotation = viewPlane.rotation;
        Vector3D             viewPlaneScale    = viewPlane.localScale;

        if (viewPlane.GetType() == typeof(RectTransform))
        {
            viewPlaneScale.Set(viewPlaneScale.X * ((RectTransform)viewPlane).root.localScale.x * ((RectTransform)viewPlane).rect.size.x,
                               viewPlaneScale.Y * ((RectTransform)viewPlane).root.localScale.y * ((RectTransform)viewPlane).rect.size.y, 1);
        }

        float smoothness = Mathf.Lerp(1f, Time.deltaTime, settings.updateSmoothness);

        faceSticks[0].show = settings.leftEye;
        faceSticks[1].show = settings.rightEye;
        faceSticks[2].show = settings.leftEyebrow;
        faceSticks[3].show = settings.rightEyebrow;
        faceSticks[4].show = settings.nose;
        faceSticks[5].show = settings.mouth;
        faceSticks[6].show = settings.jaw;

        Vector2Int resolution = visualization == Visualization.Image ?
                                new Vector2Int(frame.ImageWidth, frame.ImageHeight) :
                                new Vector2Int(frame.DepthWidth, frame.DepthHeight);

        for (int i = 0; i < faceSticks.Length; i++)
        {
            if (!faceSticks[i].show)
            {
                if (faceSticks[i].indicesParent.activeSelf)
                {
                    faceSticks[i].indicesParent.SetActive(false);
                }

                if (faceSticks[i].pointsParent.activeSelf)
                {
                    faceSticks[i].pointsParent.SetActive(false);
                }
            }
            else
            {
                if (settings.showPointIds != faceSticks[i].indicesParent.activeSelf)
                {
                    faceSticks[i].indicesParent.SetActive(settings.showPointIds);
                }

                if (settings.showPointIds == faceSticks[i].pointsParent.activeSelf)
                {
                    faceSticks[i].pointsParent.SetActive(!settings.showPointIds);
                }
            }

            Vector3D position;

            for (int j = 0, index = 0; j < faceSticks[i].indices.Length; j++)
            {
                index = faceSticks[i].pointIndices[j];

                position = (visualization == Visualization.Image ? face.Points2D[index] : face.WorldToDepthSpace(index, adapter)).
                           GetPositionOnPlane(resolution.x, resolution.y, viewPlanePosition, viewPlaneRotation, viewPlaneScale);
                position = Vector3D.Lerp(faceSticks[i].points[j].position, position, smoothness);

                faceSticks[i].points[j].position  = position;
                faceSticks[i].indices[j].position = position;
            }

            if (settings.drawLines != faceSticks[i].lineParent.activeSelf)
            {
                faceSticks[i].lineParent.SetActive(settings.drawLines);
            }
        }

        // left eye
        FaceStick faceStick = faceSticks[0];

        UpdateLineVisibility(faceStick);
        faceStick.line.SetPosition(0, faceStick.GetPosition(0));
        faceStick.line.SetPosition(1, faceStick.GetPosition(1));
        faceStick.line.SetPosition(2, faceStick.GetPosition(2));
        faceStick.line.SetPosition(3, faceStick.GetPosition(3));
        faceStick.line.SetPosition(4, faceStick.GetPosition(4));
        faceStick.line.SetPosition(5, faceStick.GetPosition(5));
        faceStick.line.SetPosition(6, faceStick.GetPosition(0));

        // right eye
        faceStick = faceSticks[1];
        UpdateLineVisibility(faceStick);
        faceStick.line.SetPosition(0, faceStick.GetPosition(0));
        faceStick.line.SetPosition(1, faceStick.GetPosition(1));
        faceStick.line.SetPosition(2, faceStick.GetPosition(2));
        faceStick.line.SetPosition(3, faceStick.GetPosition(3));
        faceStick.line.SetPosition(4, faceStick.GetPosition(4));
        faceStick.line.SetPosition(5, faceStick.GetPosition(5));
        faceStick.line.SetPosition(6, faceStick.GetPosition(0));

        // left eyebrow
        faceStick = faceSticks[2];
        UpdateLineVisibility(faceStick);
        faceStick.line.SetPosition(0, faceStick.GetPosition(0));
        faceStick.line.SetPosition(1, faceStick.GetPosition(1));
        faceStick.line.SetPosition(2, faceStick.GetPosition(2));
        faceStick.line.SetPosition(3, faceStick.GetPosition(3));
        faceStick.line.SetPosition(4, faceStick.GetPosition(4));

        // right eyebrow
        faceStick = faceSticks[3];
        UpdateLineVisibility(faceStick);
        faceStick.line.SetPosition(0, faceStick.GetPosition(0));
        faceStick.line.SetPosition(1, faceStick.GetPosition(1));
        faceStick.line.SetPosition(2, faceStick.GetPosition(2));
        faceStick.line.SetPosition(3, faceStick.GetPosition(3));
        faceStick.line.SetPosition(4, faceStick.GetPosition(4));

        // nose
        faceStick = faceSticks[4];
        UpdateLineVisibility(faceStick);
        faceStick.line.SetPosition(0, faceStick.GetPosition(0));
        faceStick.line.SetPosition(1, faceStick.GetPosition(1));
        faceStick.line.SetPosition(2, faceStick.GetPosition(2));
        faceStick.line.SetPosition(3, faceStick.GetPosition(3));
        faceStick.line.SetPosition(4, faceStick.GetPosition(4));
        faceStick.line.SetPosition(5, faceStick.GetPosition(5));
        faceStick.line.SetPosition(6, faceStick.GetPosition(6));
        faceStick.line.SetPosition(7, faceStick.GetPosition(7));
        faceStick.line.SetPosition(8, faceStick.GetPosition(8));
        faceStick.line.SetPosition(9, faceStick.GetPosition(3));

        // mouth
        faceStick = faceSticks[5];
        UpdateLineVisibility(faceStick);
        faceStick.line.SetPosition(0, faceStick.GetPosition(0));
        faceStick.line.SetPosition(1, faceStick.GetPosition(1));
        faceStick.line.SetPosition(2, faceStick.GetPosition(2));
        faceStick.line.SetPosition(3, faceStick.GetPosition(3));
        faceStick.line.SetPosition(4, faceStick.GetPosition(4));
        faceStick.line.SetPosition(5, faceStick.GetPosition(5));
        faceStick.line.SetPosition(6, faceStick.GetPosition(6));
        faceStick.line.SetPosition(7, faceStick.GetPosition(7));
        faceStick.line.SetPosition(8, faceStick.GetPosition(8));
        faceStick.line.SetPosition(9, faceStick.GetPosition(9));
        faceStick.line.SetPosition(10, faceStick.GetPosition(10));
        faceStick.line.SetPosition(11, faceStick.GetPosition(11));
        faceStick.line.SetPosition(12, faceStick.GetPosition(0));
        faceStick.line.SetPosition(13, faceStick.GetPosition(12));
        faceStick.line.SetPosition(14, faceStick.GetPosition(13));
        faceStick.line.SetPosition(15, faceStick.GetPosition(14));
        faceStick.line.SetPosition(16, faceStick.GetPosition(15));
        faceStick.line.SetPosition(17, faceStick.GetPosition(16));
        faceStick.line.SetPosition(18, faceStick.GetPosition(17));
        faceStick.line.SetPosition(19, faceStick.GetPosition(18));
        faceStick.line.SetPosition(20, faceStick.GetPosition(19));
        faceStick.line.SetPosition(21, faceStick.GetPosition(12));

        // jaw
        faceStick = faceSticks[6];
        UpdateLineVisibility(faceStick);
        faceStick.line.SetPosition(0, faceStick.GetPosition(0));
        faceStick.line.SetPosition(1, faceStick.GetPosition(1));
        faceStick.line.SetPosition(2, faceStick.GetPosition(2));
        faceStick.line.SetPosition(3, faceStick.GetPosition(3));
        faceStick.line.SetPosition(4, faceStick.GetPosition(4));
        faceStick.line.SetPosition(5, faceStick.GetPosition(5));
        faceStick.line.SetPosition(6, faceStick.GetPosition(6));
        faceStick.line.SetPosition(7, faceStick.GetPosition(7));
        faceStick.line.SetPosition(8, faceStick.GetPosition(8));
        faceStick.line.SetPosition(9, faceStick.GetPosition(9));
        faceStick.line.SetPosition(10, faceStick.GetPosition(10));
        faceStick.line.SetPosition(11, faceStick.GetPosition(11));
        faceStick.line.SetPosition(12, faceStick.GetPosition(12));
        faceStick.line.SetPosition(13, faceStick.GetPosition(13));
        faceStick.line.SetPosition(14, faceStick.GetPosition(14));
        faceStick.line.SetPosition(15, faceStick.GetPosition(15));
        faceStick.line.SetPosition(16, faceStick.GetPosition(16));
    }
Exemplo n.º 19
0
        public Model(Scene scene, Arguments args, List <SuperBMDLib.Materials.Material> mat_presets = null, string additionalTexPath = null)
        {
            ModelStats = new BMDInfo();
            if (args.ensure_one_material_per_mesh)
            {
                EnsureOneMaterialPerMesh(scene);
            }

            Console.WriteLine();
            if (args.sort_meshes)
            {
                SortMeshesByObjectNames(scene);
                Console.WriteLine();
            }


            // For FBX mesh names are empty, instead we need to check the nodes and rename
            // the meshes after the node names.
            foreach (Assimp.Node node in scene.RootNode.Children)
            {
                foreach (int meshindex in node.MeshIndices)
                {
                    Assimp.Mesh mesh = scene.Meshes[meshindex];
                    if (mesh.Name == String.Empty)
                    {
                        mesh.Name = node.Name;
                    }
                }
            }

            Console.WriteLine();
            Console.Write("Searching for the Skeleton Root");
            Assimp.Node root = null;
            for (int i = 0; i < scene.RootNode.ChildCount; i++)
            {
                if (scene.RootNode.Children[i].Name.ToLowerInvariant() == "skeleton_root")
                {
                    if (scene.RootNode.Children[i].ChildCount == 0)
                    {
                        throw new System.Exception("skeleton_root has no children! If you are making a rigged model, make sure skeleton_root contains the root of your skeleton.");
                    }
                    root = scene.RootNode.Children[i].Children[0];
                    break;
                }
                Console.Write(".");
            }

            Console.Write(root == null ? "✓ No Skeleton found" : "✓ Skeleton Found");
            Console.WriteLine();

            foreach (Mesh mesh in scene.Meshes)
            {
                if (mesh.HasBones && root == null)
                {
                    throw new System.Exception("Model uses bones but the skeleton root has not been found! Make sure your skeleton is inside a dummy object called 'skeleton_root'.");
                }
            }


            if (args.rotate_model)
            {
                Console.WriteLine();
                Console.Write("Rotating the model");
                int       i         = 0;
                Matrix4x4 rotate    = Matrix4x4.FromRotationX((float)(-(1 / 2.0) * Math.PI));
                Matrix4x4 rotateinv = rotate;
                rotateinv.Inverse();


                foreach (Mesh mesh in scene.Meshes)
                {
                    if (root != null)
                    {
                        foreach (Assimp.Bone bone in mesh.Bones)
                        {
                            bone.OffsetMatrix = rotateinv * bone.OffsetMatrix;
                            Console.Write("|");
                        }
                    }

                    for (i = 0; i < mesh.VertexCount; i++)
                    {
                        Vector3D vertex = mesh.Vertices[i];
                        vertex.Set(vertex.X, vertex.Z, -vertex.Y);
                        mesh.Vertices[i] = vertex;
                    }
                    for (i = 0; i < mesh.Normals.Count; i++)
                    {
                        Vector3D norm = mesh.Normals[i];
                        norm.Set(norm.X, norm.Z, -norm.Y);

                        mesh.Normals[i] = norm;
                    }
                    Console.Write(".");
                }
                Console.Write("✓");
                Console.WriteLine();
            }

            foreach (Mesh mesh in scene.Meshes)
            {
                if (mesh.HasNormals)
                {
                    for (int i = 0; i < mesh.Normals.Count; i++)
                    {
                        Vector3D normal = mesh.Normals[i];
                        normal.X        = (float)Math.Round(normal.X, 4);
                        normal.Y        = (float)Math.Round(normal.Y, 4);
                        normal.Z        = (float)Math.Round(normal.Z, 4);
                        mesh.Normals[i] = normal;
                    }
                }
            }

            Console.WriteLine();
            Console.WriteLine("Generating the Vertex Data ->");
            VertexData = new VTX1(scene, args.forceFloat);
            Console.WriteLine();
            Console.Write("Generating the Bone Data");
            Joints = new JNT1(scene, VertexData);
            Console.WriteLine();
            Console.WriteLine("Generating the Texture Data -> ");
            Textures = new TEX1(scene, args);
            Console.WriteLine();
            Console.Write("Generating the Envelope Data");
            SkinningEnvelopes = new EVP1();
            SkinningEnvelopes.SetInverseBindMatrices(scene, Joints.FlatSkeleton);

            Console.WriteLine();
            Console.Write("Generating the Weight Data");
            PartialWeightData = new DRW1(scene, Joints.BoneNameIndices);
            Console.WriteLine();

            Console.WriteLine();
            Console.WriteLine("Generating the Mesh Data ->");
            Shapes = SHP1.Create(scene, Joints.BoneNameIndices, VertexData.Attributes, SkinningEnvelopes, PartialWeightData,
                                 args.tristrip_mode, args.degenerateTriangles);

            Console.WriteLine();
            Console.WriteLine("Generating the Material Data ->");
            Materials = new MAT3(scene, Textures, Shapes, args, mat_presets);

            Console.WriteLine();
            Console.WriteLine("Loading the Textures ->");
            if (additionalTexPath == null)
            {
                Materials.LoadAdditionalTextures(Textures, Path.GetDirectoryName(args.input_path), args.readMipmaps);
            }
            else
            {
                Materials.LoadAdditionalTextures(Textures, additionalTexPath, args.readMipmaps);
            }

            Materials.MapTextureNamesToIndices(Textures);

            if (args.output_bdl)
            {
                Console.WriteLine();
                Console.WriteLine("Compiling the MDL3 ->");
                MatDisplayList = new MDL3(Materials.m_Materials, Textures.Textures);
            }
            if (args.littleEndian)
            {
                littleEndian = true;
            }

            Console.WriteLine();
            Console.Write("Generating the Joints");
            Scenegraph = new INF1(scene, Joints);

            foreach (Geometry.Shape shape in Shapes.Shapes)
            {
                packetCount += shape.Packets.Count;
            }

            vertexCount = VertexData.Attributes.Positions.Count;
        }
Exemplo n.º 20
0
        void ProcessPlayerInput()
        {
            // no avatar... no nothing
            if (Game.CurrentWorld.CurrentAvatar == null)
            {
                return;
            }

            if (keyboard.GetKeyState(Key.key_F5))
            {
                Game.CurrentMainWindow.SetGameControlMode();
            }
            else if (keyboard.GetKeyState(Key.key_F6))
            {
                Game.CurrentMainWindow.ReleaseGameControlMode();
            }
            if (Game.GameControlMode)
            {
                if (keyboard.GetKeyState(Key.key_ESCAPE))
                {
                    Game.CurrentMainWindow.ReleaseGameControlMode();
                }
                else if (keyboard.GetKeyState(Key.key_1))
                {
                    Game.CurrentGameCommand = EnumSkill.Kill;
                }
                else if (keyboard.GetKeyState(Key.key_2))
                {
                    Game.CurrentGameCommand = EnumSkill.AcidBlast;
                }
                else if (keyboard.GetKeyState(Key.key_3))
                {
                    Game.CurrentGameCommand = EnumSkill.Kick;
                }
                else if (keyboard.GetKeyState(Key.key_4))
                {
                    Game.CurrentGameCommand = EnumSkill.Levitate;
                }
                else if (keyboard.GetKeyState(Key.key_0))
                {
                    Game.CurrentGameCommand = EnumSkill.None;
                }
            }

            // if not in game control mode, don't respond to game controls
            if (!Game.GameControlMode)
            {
                return;
            }

            float moveunit = 1.39F * (float)movementTimer.ElapsedSeconds();

            if (keyboard.GetKeyState(Key.key_LEFTSHIFT))
            {
                moveunit *= 2.5F;
            }

            #region ProcessRotationInput

            Vector3D avatarPosition = Game.CurrentWorld.CurrentAvatar.model.Position.Clone();
            Vector3D newRotation    = Game.CurrentWorld.CurrentAvatar.model.Rotation.Clone();
            mouse.GetState();
            if (mouse.X != 0)
            {
                newRotation.Y += mouse.X * 0.2f;
                newRotation.X  = pitch;
            }
            if (mouse.Y != 0)
            {
                pitch += mouse.Y * 0.2f;
                if (pitch > 60)
                {
                    pitch = 60;
                }
                if (pitch < -60)
                {
                    pitch = -60;
                }
                newRotation.X = pitch;
            }

            if (keyboard.GetKeyState(Key.key_Q))
            {
                newRotation.Y -= moveunit * 2F;
            }
            if (keyboard.GetKeyState(Key.key_E))
            {
                newRotation.Y += moveunit * 2F;
            }

            #endregion
            #region 2.0 Process Movement Input


            Vector3D changeOfPosition = new Vector3D(0, 0, 0);
            if (keyboard.GetKeyState(Key.key_W))
            {
                changeOfPosition.X += (float)Math.Sin(newRotation.Y * Math.PI / 180.0) * moveunit;
                changeOfPosition.Z += (float)Math.Cos(newRotation.Y * Math.PI / 180.0) * moveunit;
            }
            if (keyboard.GetKeyState(Key.key_S))
            {
                changeOfPosition.X -= (float)Math.Sin(newRotation.Y * Math.PI / 180.0) * moveunit / 2F;
                changeOfPosition.Z -= (float)Math.Cos(newRotation.Y * Math.PI / 180.0) * moveunit / 2F;
            }
            if (keyboard.GetKeyState(Key.key_D))
            {
                changeOfPosition.X += (float)Math.Cos(newRotation.Y * Math.PI / 180.0) * moveunit / 2F;
                changeOfPosition.Z -= (float)Math.Sin(newRotation.Y * Math.PI / 180.0) * moveunit / 2F;
            }
            if (keyboard.GetKeyState(Key.key_A))
            {
                changeOfPosition.X -= (float)Math.Cos(newRotation.Y * Math.PI / 180.0) * moveunit / 2F;
                changeOfPosition.Z += (float)Math.Sin(newRotation.Y * Math.PI / 180.0) * moveunit / 2F;
            }

            if (changeOfPosition.GetMagnitudeSquared() != 0)
            {
                // stay on the ground
                // TODO: What about when walking on objects?
                Vector3D newPosition = avatarPosition + changeOfPosition;
                try
                {
                    newPosition.Y =
                        Game.CurrentWorld.TerrainPieces.AltitudeAt(newPosition.X, newPosition.Z) + Game.CurrentWorld.CurrentAvatar.physicalObject.Height / 2;
                    //Game.CurrentWorld.WorldTerrain.HeightLookup( newPosition.X, newPosition.Z ) + Game.CurrentWorld.CurrentAvatar.physicalObject.Height/2;
                    changeOfPosition.Y = newPosition.Y - avatarPosition.Y;

                    // check that we can go there
                    foreach (PhysicalObjectInstance poi in Game.CurrentWorld.physicalObjectInstances.Values)
                    {
                        if (poi.physicalObject is Terrain)
                        {
                            continue;
                        }
                        if (poi == Game.CurrentWorld.CurrentAvatar)
                        {
                            //ignore ourselves
                            continue;
                        }

                        // do a bounding sphere test to see if the movement will go near poi
                        // test from the middle of the line drawn between current position
                        // and future position, distance is the radius of both objects
                        // plus half the distance of the movement.
                        float dx = avatarPosition.X + changeOfPosition.X / 2F - poi.model.Position.X;
                        float dy = avatarPosition.Y + changeOfPosition.Y / 2F - poi.model.Position.Y;
                        float dz = avatarPosition.Z + changeOfPosition.Z / 2F - poi.model.Position.Z;
                        float distance_squared = dx * dx + dy * dy + dz * dz;
                        float distance_moved   = changeOfPosition.X * changeOfPosition.X + changeOfPosition.Y * changeOfPosition.Y + changeOfPosition.Z * changeOfPosition.Z;
                        // TODO: optimize, no sqrts
                        if (Math.Sqrt(distance_squared) < Math.Sqrt(poi.model.RadiusSquared) + Math.Sqrt(Game.CurrentWorld.CurrentAvatar.model.RadiusSquared) + Math.Sqrt(distance_moved) / 2F)
                        {
                            // ok, these objects are close enough to collide,
                            // but did a collision really happen?
                            // now we do a more acurate test to find out.

                            Vector3D boxmin1 = new Vector3D();
                            Vector3D boxmax1 = new Vector3D();
                            Vector3D boxmin2 = new Vector3D();
                            Vector3D boxmax2 = new Vector3D();
                            poi.model.GetBoundingBox(boxmin1, boxmax1);
                            Game.CurrentWorld.CurrentAvatar.model.GetBoundingBox(boxmin2, boxmax2);
                            Vector3D halfbox1size = (boxmax1 - boxmin1) / 2;
                            boxmin2 -= halfbox1size;
                            boxmax2 += halfbox1size;
                            boxmin2 += poi.model.Position;
                            boxmax2 += poi.model.Position;

                            if (
                                avatarPosition.X > boxmin2.X &&
                                avatarPosition.Y > boxmin2.Y &&
                                avatarPosition.Z > boxmin2.Z &&
                                avatarPosition.X < boxmax2.X &&
                                avatarPosition.Y < boxmax2.Y &&
                                avatarPosition.Z < boxmax2.Z
                                )
                            {
                                // already in a collision, ignore collision detection
                                break;
                            }

                            if (
                                newPosition.X > boxmin2.X &&
                                newPosition.Y > boxmin2.Y &&
                                newPosition.Z > boxmin2.Z &&
                                newPosition.X < boxmax2.X &&
                                newPosition.Y < boxmax2.Y &&
                                newPosition.Z < boxmax2.Z
                                )
                            {
                                // would be a collision
                                changeOfPosition.Set(0, 0, 0);
                                break;
                                // TODO: should actually figure out the collision point
                            }
                        }
                    }
                }
                catch (InvalidLocationException)
                {
                    changeOfPosition.Set(0, 0, 0);
                }
                // NB: PlayerMovement is called regardless,
                // as we need to update values for message throtling
            }

            #endregion
            PlayerMovement(avatarPosition, changeOfPosition, newRotation);
            Game.CurrentWorld.RepositionCamera();
        }
Exemplo n.º 21
0
        public void TestSet()
        {
            float x = 10.5f, y = 109.21f, z = 100;
            Vector3D v = new Vector3D();
            v.Set(x, y, z);

            TestHelper.AssertEquals(x, y, z, v, "Test v.Set()");
        }