Inheritance: MonoBehaviour
        public SkeletonViewer(Skeleton _skel)
        {
            InitializeComponent();
            skelet = _skel;

            sdi = new SkeletDrawInfo(skelet, ClientRectangle);
        }
    public void ForceBuild()
    {
        skeletonDataAsset.ForceUpdate();
        skeleton = new Skeleton(skeletonDataAsset.GetSkeletonData());

        UpdateMesh();
    }
Exemplo n.º 3
0
	public float[] WriteSkeletonToFile(Skeleton skeleton, SkeletonFrame skeletonFrame, System.IO.StreamWriter file)
	{

        int count = 2; 
            float[] dataLine = new float[63];
            System.Text.StringBuilder sb = new System.Text.StringBuilder(150);
            string str_framenum = skeletonFrame.FrameNumber.ToString();
            dataLine[0] = float.Parse(str_framenum);
            sb.Append(str_framenum);
            sb.Append(" , ");
            string str_timestamp = skeletonFrame.Timestamp.ToString();
            dataLine[1] = float.Parse(str_timestamp);
            sb.Append(str_timestamp);
            sb.Append(" , ");

            foreach (Joint joint in skeleton.Joints){

                dataLine[count] = joint.Position.X;
                sb.Append(joint.Position.X.ToString());
                sb.Append(" , ");
                dataLine[count + 1] = joint.Position.Y;
                sb.Append(joint.Position.Y.ToString());
                sb.Append(" , ");
                dataLine[count + 2] = joint.Position.Z;
                sb.Append(joint.Position.Z.ToString());
                sb.Append(" , ");
                count = count + 3;
            }

            string str = sb.ToString();
         
            file.WriteLine(str);
            return dataLine;
	}
Exemplo n.º 4
0
		public void Test3()
		{
			var skeleton = new CoreSkeleton(skelPath);
			var animation = new CoreAnimation(animPath, skeleton);

			var skelInstance = new Skeleton(skeleton);
		}
        public ViewPropertiesOfInputElement_Form(string path_to_xml)
        {
            InitializeComponent();

            try
            {
                current_skelet_loaded = ViewProperties_Form.Read_from_xml(path_to_xml);
                element_list = new Classes.Element[current_skelet_loaded.list_of_cell.Count];
                Bitmap bm = new Bitmap(current_skelet_loaded.Size.X, current_skelet_loaded.Size.Y);
                foreach (Skeleton.cell sc in current_skelet_loaded.list_of_cell)
                {
                    foreach (Skeleton.node sn in sc.list_of_node)
                    {
                        bm.SetPixel(sn.x, sn.y, Color.White);
                    }
                }
                ibReader.Image = new Image<Gray, byte>(bm);
                listBox1.Items.Clear();
                for (int i = 0; i < current_skelet_loaded.list_of_cell.Count; i++)
                    listBox1.Items.Add(i);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
            }
        }
Exemplo n.º 6
0
    public SkeletonAnalyzer(long millis)
    {
        this.millis = millis;
        this.history = new Queue<Tuple<Skeleton,long>>();

        skeleton = null;
    }
Exemplo n.º 7
0
	public virtual void Reset () {
		if (meshFilter != null) meshFilter.sharedMesh = null;
		if (mesh != null) DestroyImmediate(mesh);
		if (renderer != null) renderer.sharedMaterial = null;
		mesh = null;
		mesh1 = null;
		mesh2 = null;
		lastVertexCount = 0;
		vertices = null;
		colors = null;
		uvs = null;
		sharedMaterials = new Material[0];
		submeshMaterials.Clear();
		submeshes.Clear();
		skeleton = null;

		valid = false;
		if (!skeletonDataAsset) {
			Debug.LogError("Missing SkeletonData asset.", this);
			return;
		}
		SkeletonData skeletonData = skeletonDataAsset.GetSkeletonData(false);
		if (skeletonData == null) return;
		valid = true;
		
		meshFilter = GetComponent<MeshFilter>();
		mesh1 = newMesh();
		mesh2 = newMesh();
		vertices = new Vector3[0];
		
		skeleton = new Skeleton(skeletonData);
		if (initialSkinName != null && initialSkinName.Length > 0 && initialSkinName != "default")
			skeleton.SetSkin(initialSkinName);
	}
Exemplo n.º 8
0
		public Form1()
		{
			ClientSize = new Size(640, 480);
			Text = "Ijw.Skeletal.Viewer";
			Visible = true;

			device = GraphicsDevice.Create(this, ClientSize.Width, ClientSize.Height, true, true,
				Surfaces.Color | Surfaces.Depth);

			shader = new Shader(device, File.OpenRead("../../../res/shader.fx"));
			wireframe = new Shader(device, File.OpenRead("../../../res/wire.fx"));
			points = new Shader(device, File.OpenRead("../../../res/point.fx"));

			meshes = new Cache<string,CoreMesh>(
				x => new CoreMesh("../../../res/" + x + ".xmf", coreSkeleton ));

			animations = new Cache<string, CoreAnimation>(
				x => new CoreAnimation("../../../res/" + x + ".xaf", coreSkeleton));

			vertices = new FvfVertexBuffer<Vertex>(device, 1024,
				VertexFormat.Position | VertexFormat.Normal | VertexFormat.Texture);

			haxVerts = new FvfVertexBuffer<Vector3>(device, 1024,
				VertexFormat.Position);

			indices = new IndexBuffer(device, 1024);

			textures = new Cache<string, Texture>(
				x => Texture.Create(File.OpenRead("../../../res/" + x), device));

			skeleton = new Skeleton(coreSkeleton);

			mixer.Play(animations["walk"]).Looping().WithWeight(0.3f);
			mixer.Play(animations["aim"]).Looping();
		}
Exemplo n.º 9
0
		private Bone CreateBoneTree(ref Skeleton skele, Node node, Bone parent) {

			var internalNode = new Bone {
				Name = node.Name, Parent = parent,
			};
			if (boneNames.ContainsKey (node.Name)) {
				boneNames [node.Name].OffsetMatrix.Transpose ();
				internalNode.Offset = FromMatrix (boneNames [node.Name].OffsetMatrix);

			}if (internalNode.Name == "") {
				internalNode.Name = "bone_" + _i++;
			}
			//skele[internalNode.Name] = internalNode;
			var trans = node.Transform;
			trans.Transpose(); //drectx stuff
			internalNode.LocalTransform =FromMatrix(trans);
			internalNode.OriginalLocalTransform = internalNode.LocalTransform;
			CalculateBoneToWorldTransform(internalNode);
			internalNode.Children = new List<Bone> ();
			for (var i = 0; i < node.ChildCount; i++) {
				var child = CreateBoneTree(ref skele,node.Children[i], internalNode);
				if (child != null) {
					internalNode.Children.Add(child);
				}
			}

			return internalNode;
		}
Exemplo n.º 10
0
        static void Main( string[] args )
        {
            IShoutable shouter = new Shouter();

              Skeleton skeleton = new Skeleton( 6010, shouter );
              skeleton.Start();
        }
Exemplo n.º 11
0
		public override IAsset Import (string pathToFile)
		{
			
			boneNames = new Dictionary<string, Assimp.Bone>();
			//rootBones = new List<Node> ();
			Assimp.Node rootBone=null;
			foreach (var mesh in scene.Meshes)
				foreach (var bone in mesh.Bones)
					boneNames.Add (bone.Name,bone);
			
			foreach(var boneName in boneNames.Keys){
				var boneNode=scene.RootNode.FindNode (boneName);
				if (boneNode.Parent == null || !boneNames.ContainsKey (boneNode.Parent.Name)) {
					rootBone = boneNode.Parent;
					break;
				}
			}
			var skele = new Skeleton ();
			skele.Name = "_Skeleton";
			skele[rootBone.Name]=CreateBoneTree (ref skele, rootBone,null);
			//bvh_to_vertices (skele[rootBone.Name],);
			//Console.WriteLine ("/n Start bone list: /n"+rootBone.Name);
		
			return skele;
		}
Exemplo n.º 12
0
        /// <summary>
        /// Sets the value(s) for the specified time.
        /// </summary>
        /// <param name="skeleton">The skeleton.</param>
        /// <param name="time">The time.</param>
        /// <param name="alpha">The alpha.</param>
        public override void Apply(Skeleton skeleton, float time, float alpha)
        {
            float[] frames = Frames;
            if (time < frames[0])
            {
                // Time is before first frame.
                return;
            }

            Bone bone = skeleton.Bones[BoneIndex];
            if (time >= frames[frames.Length - 3])
            {
                // Time is after last frame.
                bone.ScaleX += (bone.Data.ScaleX - 1 + frames[frames.Length - 2] - bone.ScaleX) * alpha;
                bone.ScaleY += (bone.Data.ScaleY - 1 + frames[frames.Length - 1] - bone.ScaleY) * alpha;

                return;
            }

            // Interpolate between the last frame and the current frame.
            int frameIndex = Animation.BinarySearch(frames, time, 3);
            float lastFrameX = frames[frameIndex - 2];
            float lastFrameY = frames[frameIndex - 1];
            float frameTime = frames[frameIndex];
            float percent = 1 - ((time - frameTime) / (frames[frameIndex + lastFrameTime] - frameTime));
            percent = this.GetCurvePercent((frameIndex / 3) - 1, percent < 0 ? 0 : (percent > 1 ? 1 : percent));

            bone.ScaleX += (bone.Data.ScaleX - 1 + lastFrameX + ((frames[frameIndex + TranslateTimeline.frameX] - lastFrameX) * percent) - bone.ScaleX) * alpha;
            bone.ScaleY += (bone.Data.ScaleY - 1 + lastFrameY + ((frames[frameIndex + TranslateTimeline.frameY] - lastFrameY) * percent) - bone.ScaleY) * alpha;
        }
Exemplo n.º 13
0
 public virtual void Clear()
 {
     GetComponent<MeshFilter>().mesh = null;
     DestroyImmediate(mesh);
     mesh = null;
     renderer.sharedMaterial = null;
     skeleton = null;
 }
Exemplo n.º 14
0
 public static Skeleton[] GetSkeletons(this SkeletonFrame frame)
 {
     if (frame == null)
         return null;
     var skeletons = new Skeleton[frame.SkeletonArrayLength];
     frame.CopySkeletonDataTo(skeletons);
     return skeletons;
 }
Exemplo n.º 15
0
    private void Clear()
    {
        GetComponent<MeshFilter>().mesh = null;
        DestroyImmediate(mesh);
        mesh = null;

        skeleton = null;
    }
Exemplo n.º 16
0
	public virtual void Clear () {
		meshFilter.sharedMesh = null;
		DestroyImmediate(mesh);
		mesh = null;
		mesh1 = null;
		mesh2 = null;
		renderer.sharedMaterial = null;
		skeleton = null;
	}
Exemplo n.º 17
0
        //public string debugString;
        //constructor
        public BVHLoader()
        {
            FSkeleton = new Skeleton();

            FFrames = new List<List<float>>();

            FChannelCountOfSkeleton = 0;
            FJointCounter = 0;
        }
Exemplo n.º 18
0
        public AssimpSkeletonNode(IPluginHost host)
        {
            FSkeleton = new Skeleton();

            System.Guid[] guids = new System.Guid[1];
            guids[0] = new Guid("AB312E34-8025-40F2-8241-1958793F3D39");

            host.CreateNodeOutput("Skeleton", TSliceMode.Dynamic, TPinVisibility.True, out FSkeletonOutput);
            FSkeletonOutput.SetSubType(guids, "Skeleton");
        }
Exemplo n.º 19
0
    /*
     */
    private void Initialize()
    {
        mesh = new Mesh();
        GetComponent<MeshFilter>().mesh = mesh;
        mesh.name = "tk2dSkeleton Mesh";
        mesh.hideFlags = HideFlags.HideAndDontSave;

        state = new Spine.AnimationState(skeletonDataAsset.GetAnimationStateData());
        skeleton = new Skeleton(skeletonDataAsset.GetSkeletonData());
    }
Exemplo n.º 20
0
    private void Initialize()
    {
        mesh = new Mesh();
        GetComponent<MeshFilter>().mesh = mesh;
        mesh.name = "tk2dSkeleton Mesh";
        mesh.hideFlags = HideFlags.HideAndDontSave;

        if(skeletonDataAsset != null) {
            skeleton = new Skeleton(skeletonDataAsset.GetSkeletonData());
        }
    }
Exemplo n.º 21
0
	public Trajectory(Skeleton s, DrawingContext dc)
	{
        
        this.s = s;
        this.dc = dc;
        this.pointList = new List<Point>();

        this.trajectoryPathFigure = new PathFigure();
        this.tr
                trajectoryPathFigure.StartPoint = SkeletonPointToScreen(s.Position);
                trajectoryPathFigure.IsClosed = false;
                trajectoryPathGeometry.Figures.Add(trajectoryPathFigure);
	}
Exemplo n.º 22
0
    private void InitClasses()
    {
        this.BoneObjects = new List<GameObject>();
        this.Positions = new List<Vector3>();
        this.UV = new List<Vector2>();
        this.Indices = new List<int>();
        this.Weights = new List<int>();

        this.modelskeleton = new Skeleton();
        this.CurrentSkeleton = new Skeleton();
        this.mesh = new Mesh();
        this.CIPCClient = new CIPC_CS_Unity.CLIENT.CLIENT(4120, this.IPAddress, 50000, "Shadow3DUnity", 30);
        this.CIPCThread = new Thread(this.CIPCthreadTask);
    }
    public virtual void Initialize()
    {
        mesh = new Mesh();
        GetComponent<MeshFilter>().mesh = mesh;
        mesh.name = "Skeleton Mesh";
        mesh.hideFlags = HideFlags.HideAndDontSave;

        skeleton = new Skeleton(skeletonDataAsset.GetSkeletonData(false));

        if (initialSkinName != null && initialSkinName.Length > 0) {
            skeleton.SetSkin(initialSkinName);
            skeleton.SetSlotsToSetupPose();
        }
    }
Exemplo n.º 24
0
        private void runtime_SkeletonFrameReady(object sender, SkeletonFrameReadyEventArgs e)
        {
            Skeleton[] skeletons = null;
            body = Body.Instance;

            using (SkeletonFrame skeletonFrame = e.OpenSkeletonFrame())
            {
                if (skeletonFrame != null)
                {
                    if (skeletons == null)
                    {
                        // Skelettarray zuweisen
                        skeletons = new Skeleton[skeletonFrame.SkeletonArrayLength];
                    }

                    skeletonFrame.CopySkeletonDataTo(skeletons);

                    if (skeletons.Length != 0)
                    {
                        // Getrackte Körperpunkte zwischenspeichern
                        Parallel.ForEach(skeletons, skel =>
                        {
                            setPosition(skel.Joints[JointType.AnkleLeft]);
                            setPosition(skel.Joints[JointType.AnkleRight]);
                            setPosition(skel.Joints[JointType.ElbowLeft]);
                            setPosition(skel.Joints[JointType.ElbowRight]);
                            setPosition(skel.Joints[JointType.FootLeft]);
                            setPosition(skel.Joints[JointType.FootRight]);
                            setPosition(skel.Joints[JointType.HandLeft]);
                            setPosition(skel.Joints[JointType.HandRight]);
                            setPosition(skel.Joints[JointType.Head]);
                            setPosition(skel.Joints[JointType.HipCenter]);
                            setPosition(skel.Joints[JointType.HipLeft]);
                            setPosition(skel.Joints[JointType.HipRight]);
                            setPosition(skel.Joints[JointType.KneeLeft]);
                            setPosition(skel.Joints[JointType.KneeRight]);
                            setPosition(skel.Joints[JointType.ShoulderCenter]);
                            setPosition(skel.Joints[JointType.ShoulderLeft]);
                            setPosition(skel.Joints[JointType.ShoulderRight]);
                            setPosition(skel.Joints[JointType.Spine]);
                            setPosition(skel.Joints[JointType.WristLeft]);
                            setPosition(skel.Joints[JointType.WristRight]);
                        });
                        if (SkeletonEvent != null)
                            SkeletonEvent();
                    }
                }
            }
        }
Exemplo n.º 25
0
		IEnumerator Start () {
			if (parentSpaceHelper == null) {
				parentSpaceHelper = (new GameObject("Parent Space Helper")).transform;
				parentSpaceHelper.hideFlags = HideFlags.HideInHierarchy;
			}

			targetSkeletonComponent = GetComponent<SkeletonRenderer>() as ISkeletonAnimation;
			if (targetSkeletonComponent == null) Debug.LogError("Attached Spine component does not implement ISkeletonAnimation. This script is not compatible.");
			skeleton = targetSkeletonComponent.Skeleton;

			if (applyOnStart) {
				yield return null;
				Apply();
			}
		}
Exemplo n.º 26
0
	public virtual void Clear () {
		if (meshFilter != null) meshFilter.sharedMesh = null;
		if (mesh != null) DestroyImmediate(mesh);
		if (renderer != null) renderer.sharedMaterial = null;
		mesh = null;
		mesh1 = null;
		mesh2 = null;
		lastVertexCount = 0;
		vertices = null;
		colors = null;
		uvs = null;
		sharedMaterials = new Material[0];
		submeshMaterials.Clear();
		submeshes.Clear();
		skeleton = null;
	}
Exemplo n.º 27
0
    public BodiesMessage(string kinectId, List<Kinect.Body> listOfBodies)
    {
        _start();
        this.KinectId = kinectId;

        Message = "" + KinectId;
        if (listOfBodies.Count == 0) Message += "" + MessageSeparators.L1 + "None";
        else
        {
            foreach (Kinect.Body b in listOfBodies)
            {
                Skeleton newBody = new Skeleton(b);
                _bodies.Add(newBody);
                Message += "" + MessageSeparators.L1 + newBody.Message;
            }
        }
    }
		public Mesh GenerateMesh (Skeleton skeleton) {
			skeletonColor.r = skeleton.r;
			skeletonColor.g = skeleton.g;
			skeletonColor.b = skeleton.b;
			skeletonColor.a = skeleton.a;

			ClearBuffers();
			var drawOrderItems = skeleton.drawOrder.Items;
			for (int i = 0, n = skeleton.drawOrder.Count; i < n; i++) {
				AddSlot(drawOrderItems[i]);
			}

			Mesh currentMesh = doubleBufferedMesh.GetNextMesh();
			FillMesh(currentMesh);
			lastGeneratedMesh = currentMesh;
			return currentMesh;
		}
Exemplo n.º 29
0
		public void Test5()
		{
			var skeleton = new CoreSkeleton(skelPath);
			var mesh = new CoreMesh(meshPath, skeleton);
			var anim = new CoreAnimation(animPath, skeleton);

			var skelInstance = new Skeleton(skeleton);
			var mixer = new Mixer();

			// play the animation
			mixer.Play(anim).Once();
			mixer.Update(0);

			skelInstance.Animate(mixer);

			var verts = mesh.GetTransformedVertices(skelInstance);
			var indices = mesh.GetIndices();
		}
Exemplo n.º 30
0
    public virtual void Initialize()
    {
        mesh = new Mesh();
        GetComponent<MeshFilter>().mesh = mesh;
        mesh.name = "Skeleton Mesh";
        mesh.hideFlags = HideFlags.HideAndDontSave;
        mesh.MarkDynamic();

        renderer.sharedMaterial = skeletonDataAsset.atlasAsset.material;

        vertices = new Vector3[0];

        skeleton = new Skeleton(skeletonDataAsset.GetSkeletonData(false));

        if (initialSkinName != null && initialSkinName.Length > 0) {
            skeleton.SetSkin(initialSkinName);
            skeleton.SetSlotsToSetupPose();
        }
    }
Exemplo n.º 31
0
 /// <summary>Sets the Skeleton's local scale using a UnityEngine.Vector2. If only individual components need to be set, set Skeleton.ScaleX or Skeleton.ScaleY.</summary>
 public static void SetLocalScale(this Skeleton skeleton, Vector2 scale)
 {
     skeleton.scaleX = scale.x;
     skeleton.scaleY = scale.y;
 }
Exemplo n.º 32
0
        void sensor_SkeletonFrameReady(object sender, SkeletonFrameReadyEventArgs e)
        {
            //declare an array of Skeletons
            Skeleton[] skeletons = new Skeleton[6];

            //Opens a SkeletonFrame object, which contains one frame of skeleton data.
            using (SkeletonFrame skeletonframe = e.OpenSkeletonFrame())
            {
                //Check if the Frame is Indeed open
                if (skeletonframe != null)
                {
                    skeletons = new Skeleton[skeletonframe.SkeletonArrayLength];

                    // Copies skeleton data to an array of Skeletons, where each Skeleton contains a collection of the joints.
                    skeletonframe.CopySkeletonDataTo(skeletons);

                    Skeleton skeleton = GetPrimarySkeleton(skeletons);
                    if (skeleton != null)
                    {
                        // Get 3 joints - rightelbow, rightwrist and rightshoulder
                        Joint rightelbow    = skeleton.Joints[JointType.ElbowRight];
                        Joint rightwrist    = skeleton.Joints[JointType.WristRight];
                        Joint rightshoulder = skeleton.Joints[JointType.ShoulderRight];
                        // Get 3 joints - leftelbow, leftwrist and leftshoulder
                        Joint leftelbow    = skeleton.Joints[JointType.ElbowLeft];
                        Joint leftwrist    = skeleton.Joints[JointType.Spine];
                        Joint leftshoulder = skeleton.Joints[JointType.ShoulderLeft];
                        // Get 2 joints - hipcenter, head and spine
                        Joint hipcenter = skeleton.Joints[JointType.HipCenter];
                        Joint head      = skeleton.Joints[JointType.Head];
                        Joint spine     = skeleton.Joints[JointType.Spine];
                        // get angles between the 3 sets defined
                        double rightangle = GetAngle(spine, rightshoulder, rightelbow);
                        double leftangle  = GetAngle(leftwrist, leftshoulder, leftelbow);
                        double angle      = GetAngle(hipcenter, spine, head);

                        // based on the angles obtained, gestures are defined
                        label4.Content = " Action Performed by Firebird -  ";
                        if (hipcenter.Position.Z - rightwrist.Position.Z > 0.35)
                        {
                            // Punch gesture
                            try
                            {
                                if (System.IO.Ports.SerialPort.GetPortNames().Contains("COM2"))
                                {
                                    if (myport.IsOpen)
                                    {
                                        myport.WriteLine("57");
                                        label2.Content = " PUNCH !!!";
                                    }
                                    else
                                    {
                                        label2.Content = "";
                                        myport.Open();
                                    }
                                }
                                else
                                {
                                    label4.Content = "COM port does not exist";
                                }
                            }
                            catch (System.InvalidOperationException)
                            {
                                MessageBox.Show("Unable to write to COM port");
                            }
                        }
                        // lean forward for 'move forward' gesture
                        else if (angle > 165)
                        {
                            try
                            {
                                if (System.IO.Ports.SerialPort.GetPortNames().Contains("COM2"))
                                {
                                    if (myport.IsOpen)
                                    {
                                        myport.WriteLine("958");
                                        label2.Content = " Forward";
                                    }
                                    else
                                    {
                                        label2.Content = "";
                                        myport.Open();
                                    }
                                }
                                else
                                {
                                    label4.Content = "COM port does not exist";
                                }
                            }
                            catch (System.InvalidOperationException)
                            {
                                MessageBox.Show("Unable to write to COM port");
                            }
                        }
                        // stand straight with hands down for 'stop' gesture
                        else if (rightangle < 150 && leftangle < 150 && rightangle > 100 && leftangle > 100)
                        {
                            try
                            {
                                if (System.IO.Ports.SerialPort.GetPortNames().Contains("COM2"))
                                {
                                    if (myport.IsOpen)
                                    {
                                        myport.WriteLine("95");
                                        label2.Content = " Stop";
                                    }
                                    else
                                    {
                                        label2.Content = "";
                                        myport.Open();
                                    }
                                }
                                else
                                {
                                    label4.Content = "COM port does not exist";
                                }
                            }
                            catch (System.InvalidOperationException)
                            {
                                MessageBox.Show("Unable to write to COM port");
                            }
                        }
                        // raise both hands for 'back' gesture
                        else if (rightangle > 150 && leftangle > 150)
                        {
                            try
                            {
                                if (System.IO.Ports.SerialPort.GetPortNames().Contains("COM2"))
                                {
                                    if (myport.IsOpen)
                                    {
                                        myport.WriteLine("952");
                                        label2.Content = " Back";
                                    }
                                    else
                                    {
                                        label2.Content = "";
                                        myport.Open();
                                    }
                                }
                                else
                                {
                                    label4.Content = "COM port does not exist";
                                }
                            }
                            catch (System.InvalidOperationException)
                            {
                                MessageBox.Show("Unable to write to COM port");
                            }
                        }
                        // raise right hand parallel to ground for 'right' gesture
                        else if (rightangle > 100 && rightangle < 150)
                        {
                            try
                            {
                                if (System.IO.Ports.SerialPort.GetPortNames().Contains("COM2"))
                                {
                                    if (myport.IsOpen)
                                    {
                                        myport.WriteLine("956");
                                        label2.Content = " Right";
                                    }
                                    else
                                    {
                                        label2.Content = "";
                                        myport.Open();
                                    }
                                }
                                else
                                {
                                    label4.Content = "COM port does not exist";
                                }
                            }
                            catch (System.InvalidOperationException)
                            {
                                MessageBox.Show("Unable to write to COM port");
                            }
                        }
                        // raise right hand parallel to ground for 'left' gesture
                        else if (leftangle > 100 && leftangle < 150)
                        {
                            try
                            {
                                if (System.IO.Ports.SerialPort.GetPortNames().Contains("COM2"))
                                {
                                    if (myport.IsOpen)
                                    {
                                        myport.WriteLine("954");
                                        label2.Content = " Left";
                                    }
                                    else
                                    {
                                        label2.Content = "";
                                        myport.Open();
                                    }
                                }
                                else
                                {
                                    label4.Content = "COM port does not exist";
                                }
                            }
                            catch (System.InvalidOperationException)
                            {
                                MessageBox.Show("Unable to write to COM port");
                            }
                        }

                        else if (rightangle < 100 && leftangle < 100)
                        {
                            try
                            {
                                if (System.IO.Ports.SerialPort.GetPortNames().Contains("COM2"))
                                {
                                    if (myport.IsOpen)
                                    {
                                        myport.WriteLine("95");
                                        label2.Content = " Stop";
                                    }
                                    else
                                    {
                                        label2.Content = "";
                                        myport.Open();
                                    }
                                }
                                else
                                {
                                    label4.Content = "COM port does not exist";
                                }
                            }
                            catch (System.InvalidOperationException)
                            {
                                MessageBox.Show("Unable to write to COM port");
                            }
                        }

                        // Copies skeleton data to an array of Skeletons, where each Skeleton contains a collection of the joints.
                        skeletonframe.CopySkeletonDataTo(skeletons);
                        //draw the Skeleton based on the Default Mode(Standing), "Seated"
                        if (sensor.SkeletonStream.TrackingMode == SkeletonTrackingMode.Default)
                        {
                            //Draw standing Skeleton
                            DrawStandingSkeletons(skeletons);
                        }
                        else if (sensor.SkeletonStream.TrackingMode == SkeletonTrackingMode.Seated)
                        {
                            //Draw a Seated Skeleton with 10 joints
                            DrawSeatedSkeletons(skeletons);
                        }
                    }
                }
            }
        }
Exemplo n.º 33
0
        /// <summary>
        /// Processes the given skeleton and updates the network packet data structure, then
        /// sends the resulting packet.
        /// </summary>
        /// <param name="frame">The Kinect skeleton to process.</param>
        public void ProcessSkeleton(SkeletonFrame frame)
        {
            sbyte[] nullAxis = new sbyte[6];

            if ((m_skeletonArray == null) || (m_skeletonArray.Length != frame.SkeletonArrayLength))
            {
                m_skeletonArray = new Skeleton[frame.SkeletonArrayLength];
            }

            frame.CopySkeletonDataTo(m_skeletonArray);

            // Do stuff here
            lock (m_version0Packet)
            {
                m_version0Packet.PlayerCount.Set((byte)KinectUtils.CountTrackedSkeletons(m_skeletonArray));

                m_version0Packet.Flags.Set(0);      //Flags only accessible in the C++ API??
                m_version0Packet.FloorClipPlane.Set(frame.FloorClipPlane.Item1,
                                                    frame.FloorClipPlane.Item2,
                                                    frame.FloorClipPlane.Item3,
                                                    frame.FloorClipPlane.Item4);
                m_version0Packet.GravityNormal.Set(0, 0, 0); //Gravity Normal removed from SDK

                // Get the best skeleton
                Skeleton s = KinectUtils.SelectBestSkeleton(m_skeletonArray);

                m_version0Packet.Quality.Set((byte)s.ClippedEdges);
                m_version0Packet.CenterOfMass.Set(s.Position.X,
                                                  s.Position.Y,
                                                  s.Position.Z);
                m_version0Packet.SkeletonTrackState.Set((uint)s.TrackingState);

                // Loop through joints; get tracking states and positions
                byte[]           trackingStates = new byte[20];
                WritableVertex[] vertices       = new WritableVertex[20];

                for (uint i = 0; i < s.Joints.Count; i++)
                {
                    Joint j = s.Joints[(JointType)i];

                    trackingStates[i] = (byte)(j.TrackingState);
                    vertices[i]       = new WritableVertex(j.Position.X,
                                                           j.Position.Y,
                                                           j.Position.Z);
                }
                m_version0Packet.SkeletonTrackingStates.Set(trackingStates);
                m_version0Packet.SkeletonJoints.Set(vertices);

                // Update Joysticks
                WritableJoystick[] sticks = new WritableJoystick[2] {
                    m_version0Packet.Joystick1,
                    m_version0Packet.Joystick2
                };
                if (m_version0Packet.PlayerCount.Get() != 0)        //Only process and send valid data if a player is detected
                {
                    m_gestureProcessor.ProcessGestures(sticks, s);
                }
                else
                {
                    m_version0Packet.Joystick1.Set(nullAxis, 0);
                    m_version0Packet.Joystick2.Set(nullAxis, 0);
                }
            }

            send();
            m_heartbeatTimer.Change(HEARTBEAT_PERIOD_MS, HEARTBEAT_PERIOD_MS);
        }
Exemplo n.º 34
0
            /// <summary>Generates a monster and places it on the specified map and tile.</summary>
            /// <param name="monsterType">The monster type's name and an optional dictionary of monster-specific settings.</param>
            /// <param name="location">The GameLocation where the monster should be spawned.</param>
            /// <param name="tile">The x/y coordinates of the tile where the monster should be spawned.</param>
            /// <param name="areaID">The UniqueAreaID of the related SpawnArea. Required for log messages.</param>
            /// <returns>Returns the monster's ID value, or null if the spawn process failed.</returns>
            public static int?SpawnMonster(MonsterType monsterType, GameLocation location, Vector2 tile, string areaID = "")
            {
                Monster monster = null;                                                                      //an instatiated monster, to be spawned into the world later

                Color?color = null;                                                                          //the monster's color (used by specific monster types)

                if (monsterType.Settings != null)                                                            //if settings were provided
                {
                    if (monsterType.Settings.ContainsKey("Color"))                                           //if this setting was provided
                    {
                        string[]   colorText    = ((string)monsterType.Settings["Color"]).Trim().Split(' '); //split the setting string into strings for each number
                        List <int> colorNumbers = new List <int>();
                        foreach (string text in colorText)                                                   //for each string
                        {
                            int num = Convert.ToInt32(text);                                                 //convert it to a number
                            if (num < 0)
                            {
                                num = 0;
                            }                         //minimum 0
                            else if (num > 255)
                            {
                                num = 255;
                            }                      //maximum 255
                            colorNumbers.Add(num); //add it to the list
                        }

                        //convert strings into RGBA values
                        int r = Convert.ToInt32(colorNumbers[0]);
                        int g = Convert.ToInt32(colorNumbers[1]);
                        int b = Convert.ToInt32(colorNumbers[2]);
                        int a;
                        if (colorNumbers.Count > 3) //if the setting included an "A" value
                        {
                            a = Convert.ToInt32(colorNumbers[3]);
                        }
                        else //if the setting did not include an "A" value
                        {
                            a = 255; //default to no transparency
                        }

                        color = new Color(r, g, b, a);                                                                     //set the color
                    }
                    else if (monsterType.Settings.ContainsKey("MinColor") && monsterType.Settings.ContainsKey("MaxColor")) //if color wasn't provided, but mincolor & maxcolor were
                    {
                        string[]   minColorText    = ((string)monsterType.Settings["MinColor"]).Trim().Split(' ');         //split the setting string into strings for each number
                        List <int> minColorNumbers = new List <int>();
                        foreach (string text in minColorText)                                                              //for each string
                        {
                            int num = Convert.ToInt32(text);                                                               //convert it to a number
                            if (num < 0)
                            {
                                num = 0;
                            }                         //minimum 0
                            else if (num > 255)
                            {
                                num = 255;
                            }                         //maximum 255
                            minColorNumbers.Add(num); //add it to the list
                        }

                        string[]   maxColorText    = ((string)monsterType.Settings["MaxColor"]).Trim().Split(' '); //split the setting string into strings for each number
                        List <int> maxColorNumbers = new List <int>();
                        foreach (string text in maxColorText)                                                      //for each string
                        {
                            int num = Convert.ToInt32(text);                                                       //convert it to a number
                            if (num < 0)
                            {
                                num = 0;
                            }                         //minimum 0
                            else if (num > 255)
                            {
                                num = 255;
                            }                         //maximum 255
                            maxColorNumbers.Add(num); //convert to number
                        }

                        for (int x = 0; x < minColorNumbers.Count && x < maxColorNumbers.Count; x++) //for each pair of values
                        {
                            if (minColorNumbers[x] > maxColorNumbers[x])                             //if min > max
                            {
                                //swap min and max
                                int temp = minColorNumbers[x];
                                minColorNumbers[x] = maxColorNumbers[x];
                                maxColorNumbers[x] = temp;
                            }
                        }

                        //pick random RGBA values between min and max
                        int r = RNG.Next(minColorNumbers[0], maxColorNumbers[0] + 1);
                        int g = RNG.Next(minColorNumbers[1], maxColorNumbers[1] + 1);
                        int b = RNG.Next(minColorNumbers[2], maxColorNumbers[2] + 1);
                        int a;
                        if (minColorNumbers.Count > 3 && maxColorNumbers.Count > 3) //if both settings included an "A" value
                        {
                            a = RNG.Next(minColorNumbers[3], maxColorNumbers[3] + 1);
                        }
                        else //if one/both of the settings did not include an "A" value
                        {
                            a = 255; //default to no transparency
                        }

                        color = new Color(r, g, b, a); //set the color
                    }
                }

                bool seesPlayers = false;                                               //whether the monster automatically "sees" players at spawn (handled differently by some monster types)

                if (monsterType.Settings != null)                                       //if settings were provided
                {
                    if (monsterType.Settings.ContainsKey("SeesPlayersAtSpawn"))         //if this setting was provided
                    {
                        seesPlayers = (bool)monsterType.Settings["SeesPlayersAtSpawn"]; //use the provided setting
                    }
                }

                int facingDirection = 2;                                                          //the direction the monster should be facing at spawn (handled differently by some monster types)

                if (monsterType.Settings != null)                                                 //if settings were provided
                {
                    if (monsterType.Settings.ContainsKey("FacingDirection"))                      //if this setting was provided
                    {
                        string directionString = (string)monsterType.Settings["FacingDirection"]; //get the provided setting
                        switch (directionString.Trim().ToLower())
                        {
                        //get an integer representing the provided direction
                        case "up":
                            facingDirection = 0;
                            break;

                        case "right":
                            facingDirection = 1;
                            break;

                        case "down":
                            facingDirection = 2;
                            break;

                        case "left":
                            facingDirection = 3;
                            break;
                        }
                    }
                }

                //create a new monster based on the provided name & apply type-specific settings
                switch (monsterType.MonsterName.ToLower()) //avoid most casing issues by making this lower-case
                {
                case "bat":
                    monster = new BatFTM(tile, 0);
                    break;

                case "frostbat":
                case "frost bat":
                    monster = new BatFTM(tile, 40);
                    break;

                case "lavabat":
                case "lava bat":
                    monster = new BatFTM(tile, 80);
                    break;

                case "iridiumbat":
                case "iridium bat":
                    monster = new BatFTM(tile, 171);
                    break;

                case "doll":
                case "curseddoll":
                case "cursed doll":
                    monster = new BatFTM(tile, -666);
                    break;

                case "skull":
                case "hauntedskull":
                case "haunted skull":
                    monster = new BatFTM(tile, 77377);
                    break;

                case "magmasprite":
                case "magma sprite":
                    monster = new BatFTM(tile, -555);
                    break;

                case "magmasparker":
                case "magma sparker":
                    monster = new BatFTM(tile, -556);
                    break;

                case "bigslime":
                case "big slime":
                case "biggreenslime":
                case "big green slime":
                    monster = new BigSlimeFTM(tile, 0);
                    if (color.HasValue)                               //if color was provided
                    {
                        ((BigSlimeFTM)monster).c.Value = color.Value; //set its color after creation
                    }
                    if (seesPlayers)                                  //if the "SeesPlayersAtSpawn" setting is true
                    {
                        monster.IsWalkingTowardPlayer = true;
                    }
                    break;

                case "bigblueslime":
                case "big blue slime":
                case "bigfrostjelly":
                case "big frost jelly":
                    monster = new BigSlimeFTM(tile, 40);
                    if (color.HasValue)                               //if color was provided
                    {
                        ((BigSlimeFTM)monster).c.Value = color.Value; //set its color after creation
                    }
                    if (seesPlayers)                                  //if the "SeesPlayersAtSpawn" setting is true
                    {
                        monster.IsWalkingTowardPlayer = true;
                    }
                    break;

                case "bigredslime":
                case "big red slime":
                case "bigredsludge":
                case "big red sludge":
                    monster = new BigSlimeFTM(tile, 80);
                    if (color.HasValue)                               //if color was provided
                    {
                        ((BigSlimeFTM)monster).c.Value = color.Value; //set its color after creation
                    }
                    if (seesPlayers)                                  //if the "SeesPlayersAtSpawn" setting is true
                    {
                        monster.IsWalkingTowardPlayer = true;
                    }
                    break;

                case "bigpurpleslime":
                case "big purple slime":
                case "bigpurplesludge":
                case "big purple sludge":
                    monster = new BigSlimeFTM(tile, 121);
                    if (color.HasValue)                               //if color was provided
                    {
                        ((BigSlimeFTM)monster).c.Value = color.Value; //set its color after creation
                    }
                    if (seesPlayers)                                  //if the "SeesPlayersAtSpawn" setting is true
                    {
                        monster.IsWalkingTowardPlayer = true;
                    }
                    break;

                case "bluesquid":
                case "blue squid":
                    monster = new BlueSquid(tile);
                    break;

                case "bug":
                    monster = new Bug(tile, 0);
                    break;

                case "armoredbug":
                case "armored bug":
                    monster = new Bug(tile, 121);
                    break;

                case "dino":
                case "dinomonster":
                case "dino monster":
                case "pepper":
                case "pepperrex":
                case "pepper rex":
                case "rex":
                    monster = new DinoMonster(tile);
                    break;

                case "duggy":
                    monster = new DuggyFTM(tile);
                    break;

                case "magmaduggy":
                case "magma duggy":
                    monster = new DuggyFTM(tile, true);
                    break;

                case "dust":
                case "sprite":
                case "dustsprite":
                case "dust sprite":
                case "spirit":
                case "dustspirit":
                case "dust spirit":
                    monster = new DustSpirit(tile);
                    break;

                case "dwarvishsentry":
                case "dwarvish sentry":
                case "dwarvish":
                case "sentry":
                    monster = new DwarvishSentry(tile);
                    for (int x = Game1.delayedActions.Count - 1; x >= 0; x--)       //check each existing DelayedAction (from last to first)
                    {
                        if (Game1.delayedActions[x].stringData == "DwarvishSentry") //if this action seems to be playing this monster's sound effect
                        {
                            Game1.delayedActions.Remove(Game1.delayedActions[x]);   //remove the action (preventing this monster's global sound effect after creation)
                            break;                                                  //skip the rest of the actions
                        }
                    }
                    break;

                case "ghost":
                    monster = new GhostFTM(tile);
                    break;

                case "carbonghost":
                case "carbon ghost":
                    monster = new GhostFTM(tile, "Carbon Ghost");
                    break;

                case "putridghost":
                case "putrid ghost":
                    monster = new GhostFTM(tile, "Putrid Ghost");
                    break;

                case "slime":
                case "greenslime":
                case "green slime":
                    monster = new GreenSlime(tile, 0);
                    if (color.HasValue)                                  //if color was also provided
                    {
                        ((GreenSlime)monster).color.Value = color.Value; //set its color after creation
                    }
                    break;

                case "blueslime":
                case "blue slime":
                case "frostjelly":
                case "frost jelly":
                    monster = new GreenSlime(tile, 40);
                    if (color.HasValue)                                  //if color was also provided
                    {
                        ((GreenSlime)monster).color.Value = color.Value; //set its color after creation
                    }
                    break;

                case "redslime":
                case "red slime":
                case "redsludge":
                case "red sludge":
                    monster = new GreenSlime(tile, 80);
                    if (color.HasValue)                                  //if color was also provided
                    {
                        ((GreenSlime)monster).color.Value = color.Value; //set its color after creation
                    }
                    break;

                case "purpleslime":
                case "purple slime":
                case "purplesludge":
                case "purple sludge":
                    monster = new GreenSlime(tile, 121);
                    if (color.HasValue)                                  //if color was also provided
                    {
                        ((GreenSlime)monster).color.Value = color.Value; //set its color after creation
                    }
                    break;

                case "tigerslime":
                case "tiger slime":
                    monster = new GreenSlime(tile, 0);                   //create any "normal" slime
                    ((GreenSlime)monster).makeTigerSlime();              //convert it into a tiger slime
                    if (color.HasValue)                                  //if color was also provided
                    {
                        ((GreenSlime)monster).color.Value = color.Value; //set its color after creation
                    }
                    break;

                case "prismaticslime":
                case "prismatic slime":
                    monster = new GreenSlime(tile, 0);                   //create any "normal" slime
                    ((GreenSlime)monster).makePrismatic();               //convert it into a prismatic slime
                    if (color.HasValue)                                  //if color was also provided
                    {
                        ((GreenSlime)monster).color.Value = color.Value; //set its color after creation
                    }
                    break;

                case "grub":
                case "cavegrub":
                case "cave grub":
                    monster = new GrubFTM(tile, false);
                    break;

                case "fly":
                case "cavefly":
                case "cave fly":
                    monster = new FlyFTM(tile, false);
                    break;

                case "mutantgrub":
                case "mutant grub":
                    monster = new GrubFTM(tile, true);
                    break;

                case "mutantfly":
                case "mutant fly":
                    monster = new FlyFTM(tile, true);
                    break;

                case "metalhead":
                case "metal head":
                    monster = new MetalHead(tile, 0);
                    if (color.HasValue)                             //if color was provided
                    {
                        ((MetalHead)monster).c.Value = color.Value; //set its color after creation
                    }
                    break;

                case "hothead":
                case "hot head":
                    monster = new HotHead(tile);
                    if (color.HasValue)                           //if color was provided
                    {
                        ((HotHead)monster).c.Value = color.Value; //set its color after creation
                    }
                    break;

                case "lavalurk":
                case "lava lurk":
                    monster = new LavaLurk(tile);
                    break;

                case "leaper":
                    monster = new Leaper(tile);
                    break;

                case "mummy":
                    monster = new MummyFTM(tile);
                    break;

                case "rockcrab":
                case "rock crab":
                    monster = new RockCrab(tile);
                    break;

                case "lavacrab":
                case "lava crab":
                    monster = new LavaCrab(tile);
                    break;

                case "iridiumcrab":
                case "iridium crab":
                    monster = new RockCrab(tile, "Iridium Crab");
                    break;

                case "falsemagmacap":
                case "false magma cap":
                case "magmacap":
                case "magma cap":
                    monster            = new RockCrab(tile, "False Magma Cap");
                    monster.HideShadow = true;     //hide shadow, making them look more like "real" magma caps
                    break;

                case "stickbug":
                case "stick bug":
                    monster = new RockCrab(tile);
                    (monster as RockCrab).makeStickBug();
                    break;

                case "rockgolem":
                case "rock golem":
                case "stonegolem":
                case "stone golem":
                    monster = new RockGolemFTM(tile);
                    break;

                case "wildernessgolem":
                case "wilderness golem":
                    monster = new RockGolemFTM(tile, Game1.player.CombatLevel);
                    break;

                case "serpent":
                    monster = new SerpentFTM(tile);
                    break;

                case "royalserpent":
                case "royal serpent":
                    monster = new SerpentFTM(tile, "Royal Serpent");
                    break;

                case "brute":
                case "shadowbrute":
                case "shadow brute":
                    monster = new ShadowBrute(tile);
                    break;

                case "shaman":
                case "shadowshaman":
                case "shadow shaman":
                    monster = new ShadowShaman(tile);
                    break;

                case "sniper":
                case "shadowsniper":
                case "shadow sniper":
                    monster = new Shooter(tile);
                    break;

                case "skeleton":
                    monster = new Skeleton(tile);
                    if (seesPlayers)                                                                                        //if the "SeesPlayersAtSpawn" setting is true
                    {
                        IReflectedField <bool> spottedPlayer = Helper.Reflection.GetField <bool>(monster, "spottedPlayer"); //try to access this skeleton's private "spottedPlayer" field
                        spottedPlayer.SetValue(true);
                        monster.IsWalkingTowardPlayer = true;
                    }
                    break;

                case "skeletonmage":
                case "skeleton mage":
                    monster = new Skeleton(tile, true);
                    if (seesPlayers)                                                                                        //if the "SeesPlayersAtSpawn" setting is true
                    {
                        IReflectedField <bool> spottedPlayer = Helper.Reflection.GetField <bool>(monster, "spottedPlayer"); //try to access this skeleton's private "spottedPlayer" field
                        spottedPlayer.SetValue(true);
                        monster.IsWalkingTowardPlayer = true;
                    }
                    break;

                case "spiker":
                    monster = new Spiker(tile, facingDirection);
                    break;

                case "squidkid":
                case "squid kid":
                    monster = new SquidKidFTM(tile);
                    break;

                default:                                                                           //if the name doesn't match any directly known monster types
                    Type externalType = GetTypeFromName(monsterType.MonsterName, typeof(Monster)); //find a monster subclass with a matching name
                    monster = (Monster)Activator.CreateInstance(externalType, tile);               //create a monster with the Vector2 constructor
                    break;
                }

                if (monster == null)
                {
                    Monitor.Log($"The monster to be spawned (\"{monsterType.MonsterName}\") doesn't match any known monster types. Make sure that name isn't misspelled in your config file.", LogLevel.Info);
                    return(null);
                }

                int?ID = MonsterTracker.AddMonster(monster);  //generate an ID for this monster

                if (!ID.HasValue)
                {
                    Monitor.Log("A new monster ID could not be generated. This is may be due to coding issue; please report it to this mod's developer. This monster won't be spawned.", LogLevel.Warn);
                    return(null);
                }
                monster.id = ID.Value;                                       //assign the ID to this monster

                monster.MaxHealth = monster.Health;                          //some monster types set Health on creation and expect MaxHealth to be updated like this

                ApplyMonsterSettings(monster, monsterType.Settings, areaID); //adjust the monster based on any other provided optional settings

                //spawn the completed monster at the target location
                Monitor.VerboseLog($"Spawning monster. Type: {monsterType.MonsterName}. Location: {tile.X},{tile.Y} ({location.Name}).");
                monster.currentLocation = location;
                monster.setTileLocation(tile);
                location.addCharacter(monster);
                return(monster.id);
            }
Exemplo n.º 35
0
        private void ProcessGesture(Skeleton s)
        {
            Joint        rightHand      = (from j in s.Joints where j.JointType == JointType.HandRight select j).FirstOrDefault();
            Joint        head           = (from j in s.Joints where j.JointType == JointType.Head select j).FirstOrDefault();
            Joint        centerShoulder = (from j in s.Joints where j.JointType == JointType.ShoulderCenter select j).FirstOrDefault();
            Joint        rightfoot      = (from j in s.Joints where j.JointType == JointType.FootRight select j).FirstOrDefault();//Being right hand, head, shoulder and foot bones midpoint of the original information
            RealPosition realPositionRightHand;
            RealPosition realPositionHead;
            RealPosition realPositionRightFoot;
            RealPosition realPositionCenterShoulder;//The definition of the right hand, head,	shoulder and foot bones midpoint of the true position variable (realPosition category)

            realPositionRightHand      = new RealPosition(rightHand);
            realPositionHead           = new RealPosition(head);
            realPositionRightFoot      = new RealPosition(rightfoot);
            realPositionCenterShoulder = new RealPosition(centerShoulder);           //The right hand, head, shoulder and foot bones midpoint of the original information into skeletal real location, and given to the appropriate properties (see specific process Class1.cs)
            height           = realPositionHead.realY - realPositionRightFoot.realY; //Users measuring height
            centerPosition   = new CenterPosition();
            centerPosition.X = realPositionCenterShoulder.realX + 0.1 * height;
            centerPosition.Y = realPositionCenterShoulder.realY - 0.1 * height; //Set reference point X, Y coordinate values
            textBox2.Text    = Convert.ToString(height);
            if (realPositionRightHand.realX < centerPosition.X - height * 0.2)  //Detecting whether the left hand
            {
                if (isLeftGestureActive)
                {
                }  //If you have left is not issued a directive (here it is mainly to prevent repeat sending the same instruction, wasting CPU memory)
                else
                {
                    mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
                    mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);//Click
                    System.Windows.Forms.SendKeys.SendWait("{Backspace}");
                    System.Windows.Forms.SendKeys.SendWait("{Backspace}");
                    System.Windows.Forms.SendKeys.SendWait("{Backspace}");
                    System.Windows.Forms.SendKeys.SendWait("{Backspace}"); //Delete an existing command
                    System.Windows.Forms.SendKeys.SendWait("3");           //Enter the appropriate command
                    System.Windows.Forms.SendKeys.SendWait("{Enter}");
                    System.Windows.Forms.SendKeys.SendWait("{Enter}");
                    System.Windows.Forms.SendKeys.SendWait("{Enter}");
                    System.Windows.Forms.SendKeys.SendWait("{Enter}");//Implementation of existing directives (repeated here mainly to prevent leakage of the key, because the situation of several key leak appeared in the previous debugging)
                    isForwardGestureActive = false;
                    isBackGestureActive    = false;
                    isLeftGestureActive    = true;
                    isRightGestureActive   = false;//Update four Boolean
                }
            }
            if (realPositionRightHand.realX > centerPosition.X + height * 0.2) //检测右手是否向右
            {
                if (isRightGestureActive)                                      //如果已经向右,则不做动作
                {
                }
                else
                {
                    mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
                    mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);//单击
                    System.Windows.Forms.SendKeys.SendWait("{Backspace}");
                    System.Windows.Forms.SendKeys.SendWait("{Backspace}");
                    System.Windows.Forms.SendKeys.SendWait("{Backspace}");
                    System.Windows.Forms.SendKeys.SendWait("{Backspace}"); //将现有指令删除
                    System.Windows.Forms.SendKeys.SendWait("4");           //输入相应的指令
                    System.Windows.Forms.SendKeys.SendWait("{Enter}");
                    System.Windows.Forms.SendKeys.SendWait("{Enter}");
                    System.Windows.Forms.SendKeys.SendWait("{Enter}");
                    System.Windows.Forms.SendKeys.SendWait("{Enter}");//执行现有指令(这里的多次重复主要是为了防止漏键,因为此前的调试中出现过几次漏键的情况)
                    isForwardGestureActive = false;
                    isBackGestureActive    = false;
                    isLeftGestureActive    = false;
                    isRightGestureActive   = true;//更新四个布尔量
                }
            }
            if (realPositionRightHand.realX > centerPosition.X - height * 0.2 && realPositionRightHand.realX < centerPosition.X + height * 0.2 && realPositionRightHand.realY < centerPosition.Y + height * 0.2 && realPositionRightHand.realY > centerPosition.Y - height * 0.2)
            {
                if (!isForwardGestureActive && !isBackGestureActive && !isLeftGestureActive && !isRightGestureActive)
                {
                }
                else
                {
                    mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
                    mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);//单击
                    System.Windows.Forms.SendKeys.SendWait("{Backspace}");
                    System.Windows.Forms.SendKeys.SendWait("{Backspace}");
                    System.Windows.Forms.SendKeys.SendWait("{Backspace}");
                    System.Windows.Forms.SendKeys.SendWait("{Backspace}"); //将现有指令删除
                    System.Windows.Forms.SendKeys.SendWait("0");           //输入相应的指令
                    System.Windows.Forms.SendKeys.SendWait("{Enter}");
                    System.Windows.Forms.SendKeys.SendWait("{Enter}");
                    System.Windows.Forms.SendKeys.SendWait("{Enter}");
                    System.Windows.Forms.SendKeys.SendWait("{Enter}");//执行现有指令(这里的多次重复主要是为了防止漏键,因为此前的调试中出现过几次漏键的情况)
                    isForwardGestureActive = false;
                    isBackGestureActive    = false;
                    isLeftGestureActive    = false;
                    isRightGestureActive   = false;//更新四个布尔量
                }
            }

            if (realPositionRightHand.realY > centerPosition.Y + height * 0.2)
            {
                if (isForwardGestureActive)
                {
                }
                else
                {
                    mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
                    mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);//单击
                    System.Windows.Forms.SendKeys.SendWait("{Backspace}");
                    System.Windows.Forms.SendKeys.SendWait("{Backspace}");
                    System.Windows.Forms.SendKeys.SendWait("{Backspace}");
                    System.Windows.Forms.SendKeys.SendWait("{Backspace}"); //将现有指令删除
                    System.Windows.Forms.SendKeys.SendWait("1");           //输入相应的指令
                    System.Windows.Forms.SendKeys.SendWait("{Enter}");
                    System.Windows.Forms.SendKeys.SendWait("{Enter}");
                    System.Windows.Forms.SendKeys.SendWait("{Enter}");
                    System.Windows.Forms.SendKeys.SendWait("{Enter}");//执行现有指令(这里的多次重复主要是为了防止漏键,因为此前的调试中出现过几次漏键的情况)
                    isForwardGestureActive = true;
                    isBackGestureActive    = false;
                    isLeftGestureActive    = false;
                    isRightGestureActive   = false;//更新四个布尔量
                }
            }
            if (realPositionRightHand.realY < centerPosition.Y - height * 0.2)
            {
                if (isBackGestureActive)
                {
                }
                else
                {
                    mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
                    mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0); //单击
                    System.Windows.Forms.SendKeys.SendWait("{Backspace}");
                    System.Windows.Forms.SendKeys.SendWait("{Backspace}");
                    System.Windows.Forms.SendKeys.SendWait("{Backspace}");
                    System.Windows.Forms.SendKeys.SendWait("{Backspace}"); //将现有指令删除
                    System.Windows.Forms.SendKeys.SendWait("2");           //输入相应的指令
                    System.Windows.Forms.SendKeys.SendWait("{Enter}");
                    System.Windows.Forms.SendKeys.SendWait("{Enter}");
                    System.Windows.Forms.SendKeys.SendWait("{Enter}");
                    System.Windows.Forms.SendKeys.SendWait("{Enter}"); //执行现有指令(这里的多次重复主要是为了防止漏键,因为此前的调试中出现过几次漏键的情况)
                    isForwardGestureActive = false;
                    isBackGestureActive    = true;
                    isLeftGestureActive    = false;
                    isRightGestureActive   = false;//更新四个布尔量
                }
            }
        }
Exemplo n.º 36
0
            protected override void OnTick()
            {
                if (m_Item.Deleted)
                {
                    return;
                }

                Mobile spawn;

                switch (Utility.Random(12))
                {
                default:
                case 0:
                    spawn = new Skeleton();
                    break;

                case 1:
                    spawn = new Zombie();
                    break;

                case 2:
                    spawn = new Wraith();
                    break;

                case 3:
                    spawn = new Spectre();
                    break;

                case 4:
                    spawn = new Ghoul();
                    break;

                case 5:
                    spawn = new Mummy();
                    break;

                case 6:
                    spawn = new Bogle();
                    break;

                case 7:
                    spawn = new RottingCorpse();
                    break;

                case 8:
                    spawn = new BoneKnight();
                    break;

                case 9:
                    spawn = new SkeletalKnight();
                    break;

                case 10:
                    spawn = new Lich();
                    break;

                case 11:
                    spawn = new LichLord();
                    break;
                }

                spawn.MoveToWorld(m_Item.Location, m_Item.Map);

                m_Item.Delete();
            }
Exemplo n.º 37
0
        void SensorSkeletonFrameReady(AllFramesReadyEventArgs e)
        {
            SerialPort serialPort1 = new SerialPort("COM8", 9600);

            using (SkeletonFrame skeletonFrameData = e.OpenSkeletonFrame())
            {
                if (skeletonFrameData == null)
                {
                    return;
                }

                var allSkeletons = new Skeleton[skeletonFrameData.SkeletonArrayLength];
                skeletonFrameData.CopySkeletonDataTo(allSkeletons);

                foreach (Skeleton sd in allSkeletons)
                {
                    // If this skeleton is no longer being tracked, skip it
                    if (sd.TrackingState != SkeletonTrackingState.Tracked)
                    {
                        continue;
                    }

                    // If there is not already a gesture state map for this skeleton, then create one
                    if (!_gestureMaps.ContainsKey(sd.TrackingId))
                    {
                        var mapstate = new GestureMapState(_gestureMap);
                        _gestureMaps.Add(sd.TrackingId, mapstate);
                    }
                    var keycode = new VirtualKeyCode();
                    try
                    {
                        keycode = _gestureMaps[sd.TrackingId].Evaluate(sd, false, _bitmap.Width, _bitmap.Height);
                        GetWaitingMessages(_gestureMaps);
                    }
                    catch (NullReferenceException nre)
                    {
                        Console.WriteLine(nre.Message);
                    }

                    if (keycode != VirtualKeyCode.NONAME)
                    {
                        rtbMessages.AppendText("Gesture accepted from player " + sd.TrackingId + "\r");
                        rtbMessages.ScrollToCaret();
                        rtbMessages.AppendText("Command passed to System: " + keycode + "\r");
                        rtbMessages.ScrollToCaret();
                        //InputSimulator.SimulateKeyPress(keycode);
                        _gestureMaps[sd.TrackingId].ResetAll(sd);
                        serialPort1.Open();
                        if (serialPort1.IsOpen)
                        {
                            try
                            {
                                serialPort1.WriteLine(keycode.ToString().Substring(3, 1));
                                rtbMessages.AppendText("Command passed to Arduino: " + keycode.ToString().Substring(3, 1) + "\r");
                            }
                            catch (ArgumentOutOfRangeException aoore)
                            {
                                Console.WriteLine(aoore.Message);
                            }
                        }
                        else
                        {
                            rtbMessages.AppendText("Failed to pass command to Arduino.\r");
                        }
                        serialPort1.Close();
                    }

                    // This break prevents multiple player data from being confused during evaluation.
                    // If one were going to dis-allow multiple players, this trackingId would facilitate
                    // that feat.
                    PlayerId = sd.TrackingId;


                    if (_bitmap != null)
                    {
                        _bitmap = AddSkeletonToDepthBitmap(sd, _bitmap, true);
                    }
                }
            }
        }
Exemplo n.º 38
0
        /// <summary>
        /// Dibuja los huesos y las articulaciones de un esqueleto.
        /// </summary>
        /// <param name="skeleton">esqueleto para dibujar</param>
        /// <param name="drawingContext">contexto de dibujo para dibujar</param>
        private void DrawBonesAndJoints(Skeleton skeleton, DrawingContext drawingContext)
        {
            // Render Torso
            this.DrawBone(skeleton, drawingContext, JointType.Head, JointType.ShoulderCenter);
            this.DrawBone(skeleton, drawingContext, JointType.ShoulderCenter, JointType.ShoulderLeft);
            this.DrawBone(skeleton, drawingContext, JointType.ShoulderCenter, JointType.ShoulderRight);
            this.DrawBone(skeleton, drawingContext, JointType.ShoulderCenter, JointType.Spine);
            this.DrawBone(skeleton, drawingContext, JointType.Spine, JointType.HipCenter);
            this.DrawBone(skeleton, drawingContext, JointType.HipCenter, JointType.HipLeft);
            this.DrawBone(skeleton, drawingContext, JointType.HipCenter, JointType.HipRight);
            // Brazo izquierdo
            this.DrawBone(skeleton, drawingContext, JointType.ShoulderLeft, JointType.ElbowLeft);
            this.DrawBone(skeleton, drawingContext, JointType.ElbowLeft, JointType.WristLeft);
            this.DrawBone(skeleton, drawingContext, JointType.WristLeft, JointType.HandLeft);
            // Brazo Derecho
            this.DrawBone(skeleton, drawingContext, JointType.ShoulderRight, JointType.ElbowRight);
            this.DrawBone(skeleton, drawingContext, JointType.ElbowRight, JointType.WristRight);
            this.DrawBone(skeleton, drawingContext, JointType.WristRight, JointType.HandRight);
            // Pierna izquierda
            this.DrawBone(skeleton, drawingContext, JointType.HipLeft, JointType.KneeLeft);
            this.DrawBone(skeleton, drawingContext, JointType.KneeLeft, JointType.AnkleLeft);
            this.DrawBone(skeleton, drawingContext, JointType.AnkleLeft, JointType.FootLeft);
            // Pierna Derecha
            this.DrawBone(skeleton, drawingContext, JointType.HipRight, JointType.KneeRight);
            this.DrawBone(skeleton, drawingContext, JointType.KneeRight, JointType.AnkleRight);
            this.DrawBone(skeleton, drawingContext, JointType.AnkleRight, JointType.FootRight);
            //****************************************************
            manoDerechaVZ       = skeleton.Joints[JointType.HandRight].Position.Z;
            manoDerechaVX       = skeleton.Joints[JointType.HandRight].Position.X;
            manoDerechaVY       = skeleton.Joints[JointType.HandRight].Position.Y;
            manoDerechaZ.Text   = manoDerechaVZ.ToString();
            manoDerechaX.Text   = manoDerechaVX.ToString();
            manoDerechaY.Text   = manoDerechaVY.ToString();
            manoIzquiedaVZ      = skeleton.Joints[JointType.HandLeft].Position.Z;
            manoIzquiedaVX      = skeleton.Joints[JointType.HandLeft].Position.X;
            manoIzquiedaVY      = skeleton.Joints[JointType.HandLeft].Position.Y;
            manoIzquierdaZ.Text = manoIzquiedaVZ.ToString();
            manoIzquierdaX.Text = manoIzquiedaVX.ToString();
            manoIzquierdaY.Text = manoIzquiedaVY.ToString();
            cabezaZ             = (skeleton.Joints[JointType.Head].Position.Z);
            cabezaXV            = (skeleton.Joints[JointType.Head].Position.X);
            cabezaYV            = (skeleton.Joints[JointType.Head].Position.Y);
            cabeza.Text         = cabezaZ.ToString();
            cabezaX.Text        = cabezaXV.ToString();
            cabezaY.Text        = cabezaYV.ToString();
            codoDerechoZ        = skeleton.Joints[JointType.ElbowRight].Position.Z;
            codoDerechoX        = skeleton.Joints[JointType.ElbowRight].Position.X;
            codoDerechoY        = skeleton.Joints[JointType.ElbowRight].Position.Y;
            hombroDerechoZ      = skeleton.Joints[JointType.ShoulderRight].Position.Z;
            hombroDerechoX      = skeleton.Joints[JointType.ShoulderRight].Position.X;
            hombroDerechoY      = skeleton.Joints[JointType.ShoulderRight].Position.Y;
            //*****************************Matriz de Datos
            //0 brazo derecho, 1 Brazo Izquierdo, 2 Cabeza, 3 Codo Derecho, 4 Hombro Derecho
            matriz[0, 0] = manoDerechaVZ;
            matriz[0, 1] = manoDerechaVX;
            matriz[0, 2] = manoDerechaVY;
            matriz[1, 0] = manoIzquiedaVZ;
            matriz[1, 1] = manoIzquiedaVX;
            matriz[1, 2] = manoIzquiedaVY;
            matriz[2, 0] = cabezaZ;
            matriz[2, 1] = cabezaXV;
            matriz[2, 2] = cabezaYV;
            matriz[3, 0] = codoDerechoZ;
            matriz[3, 1] = codoDerechoX;
            matriz[3, 2] = codoDerechoY;
            matriz[4, 0] = hombroDerechoZ;
            matriz[4, 1] = hombroDerechoX;
            matriz[4, 2] = hombroDerechoY;
            matriz[5, 0] = skeleton.Joints[JointType.ShoulderCenter].Position.Y;
            matriz[5, 1] = skeleton.Joints[JointType.ShoulderRight].Position.X;
            matriz[5, 2] = skeleton.Joints[JointType.ShoulderCenter].Position.Y;

            //******************************FIN Matriz de Datos
            //estado = proceso.analizar2(Ske);//proceso.analizar(matriz);
            estado = proceso.analizar2(skeleton);
            if (estado != "Pausa")
            {
                palabra.Text = estado;
            }
            //****************************************************
            // Render Articulaciones
            foreach (Joint joint in skeleton.Joints)
            {
                Brush drawBrush = null;
                if (joint.TrackingState == JointTrackingState.Tracked)
                {
                    drawBrush = this.SeguimientoJunturaPincel;
                }
                else if (joint.TrackingState == JointTrackingState.Inferred)
                {
                    drawBrush = this.NoJunturaPincel;
                }
                if (drawBrush != null)
                {
                    drawingContext.DrawEllipse(drawBrush, null, this.SkeletonPointToScreen(joint.Position), LineasUnion, LineasUnion);
                }
            }
        }
Exemplo n.º 39
0
    public void Apply()
    {
        isActive = true;
        skeleton = skeletonAnim.Skeleton;
        mix      = 1;

        var ragdollRootBone = skeleton.FindBone(startingBoneName);

        startingBone = ragdollRootBone;
        RecursivelyCreateBoneProxies(ragdollRootBone);

        rootRigidbody             = boneTable[ragdollRootBone].GetComponent <Rigidbody>();
        rootRigidbody.isKinematic = pinStartBone;

        rootRigidbody.mass = rootMass;

        List <Collider> boneColliders = new List <Collider>();

        foreach (var pair in boneTable)
        {
            var       b               = pair.Key;
            var       t               = pair.Value;
            Bone      parentBone      = null;
            Transform parentTransform = transform;

            boneColliders.Add(t.GetComponent <Collider>());

            if (b != startingBone)
            {
                parentBone      = b.Parent;
                parentTransform = boneTable[parentBone];
            }
            else
            {
                ragdollRoot        = new GameObject("RagdollRoot").transform;
                ragdollRoot.parent = transform;

                if (b == skeleton.RootBone)
                {
                    ragdollRoot.localPosition = new Vector3(b.WorldX, b.WorldY, 0);
                    ragdollRoot.localRotation = Quaternion.Euler(0, 0, GetCompensatedRotationIK(b));
                    parentTransform           = ragdollRoot;
                }
                else
                {
                    ragdollRoot.localPosition = new Vector3(b.Parent.WorldX, b.Parent.WorldY, 0);
                    ragdollRoot.localRotation = Quaternion.Euler(0, 0, GetCompensatedRotationIK(b.Parent));
                    parentTransform           = ragdollRoot;
                }

                rootOffset = t.position - transform.position;
            }

            var rbParent = parentTransform.GetComponent <Rigidbody>();

            if (rbParent != null)
            {
                var joint = t.gameObject.AddComponent <HingeJoint>();
                joint.connectedBody = rbParent;
                Vector3 localPos = parentTransform.InverseTransformPoint(t.position);
                localPos.x           *= 1;
                joint.connectedAnchor = localPos;
                joint.axis            = Vector3.up;
                joint.GetComponent <Rigidbody>().mass = joint.connectedBody.mass * massFalloffFactor;
                JointLimits limits = new JointLimits();
                limits.min            = -rotationLimit;
                limits.max            = rotationLimit;
                joint.limits          = limits;
                joint.useLimits       = true;
                joint.enableCollision = enableJointCollision;
            }
        }

        for (int x = 0; x < boneColliders.Count; x++)
        {
            for (int y = 0; y < boneColliders.Count; y++)
            {
                if (x == y)
                {
                    continue;
                }
                Physics.IgnoreCollision(boneColliders[x], boneColliders[y]);
            }
        }

        var utilityBones = GetComponentsInChildren <SkeletonUtilityBone>();

        if (utilityBones.Length > 0)
        {
            List <string> destroyedUtilityBoneNames = new List <string>();
            foreach (var ub in utilityBones)
            {
                if (ub.mode == SkeletonUtilityBone.Mode.Override)
                {
                    destroyedUtilityBoneNames.Add(ub.gameObject.name);
                    Destroy(ub.gameObject);
                }
            }

            if (destroyedUtilityBoneNames.Count > 0)
            {
                string msg = "Destroyed Utility Bones: ";
                for (int i = 0; i < destroyedUtilityBoneNames.Count; i++)
                {
                    msg += destroyedUtilityBoneNames[i];
                    if (i != destroyedUtilityBoneNames.Count - 1)
                    {
                        msg += ",";
                    }
                }
                Debug.LogWarning(msg);
            }
        }

        if (disableIK)
        {
            foreach (IkConstraint ik in skeleton.IkConstraints)
            {
                ik.Mix = 0;
            }
        }

        skeletonAnim.UpdateWorld += UpdateWorld;
    }
Exemplo n.º 40
0
        public virtual void Initialize(bool overwrite)
        {
            if (valid && !overwrite)
            {
                return;
            }

            // Clear
            {
                if (meshFilter != null)
                {
                    meshFilter.sharedMesh = null;
                }

                meshRenderer = GetComponent <MeshRenderer>();
                if (meshRenderer != null)
                {
                    meshRenderer.sharedMaterial = null;
                }

                currentInstructions.Clear();
                rendererBuffers.Clear();
                meshGenerator.Begin();
                skeleton = null;
                valid    = false;
            }

            if (!skeletonDataAsset)
            {
                if (logErrors)
                {
                    Debug.LogError("Missing SkeletonData asset.", this);
                }
                return;
            }

            SkeletonData skeletonData = skeletonDataAsset.GetSkeletonData(false);

            if (skeletonData == null)
            {
                return;
            }
            valid = true;

            meshFilter   = GetComponent <MeshFilter>();
            meshRenderer = GetComponent <MeshRenderer>();
            rendererBuffers.Initialize();

            skeleton = new Skeleton(skeletonData)
            {
                flipX = initialFlipX,
                flipY = initialFlipY
            };

            if (!string.IsNullOrEmpty(initialSkinName) && !string.Equals(initialSkinName, "default", System.StringComparison.Ordinal))
            {
                skeleton.SetSkin(initialSkinName);
            }

            separatorSlots.Clear();
            for (int i = 0; i < separatorSlotNames.Length; i++)
            {
                separatorSlots.Add(skeleton.FindSlot(separatorSlotNames[i]));
            }

            LateUpdate();             // Generate mesh for the first frame it exists.

            if (OnRebuild != null)
            {
                OnRebuild(this);
            }
        }
Exemplo n.º 41
0
        public void Evaluate(int SpreadMax)
        {
            if (this.FInvalidateConnect)
            {
                if (runtime != null)
                {
                    this.runtime.SkeletonFrameReady -= SkeletonReady;
                }

                if (this.FInRuntime.PluginIO.IsConnected)
                {
                    //Cache runtime node
                    this.runtime = this.FInRuntime[0];

                    if (runtime != null)
                    {
                        this.FInRuntime[0].SkeletonFrameReady += SkeletonReady;
                    }
                }

                this.FInvalidateConnect = false;
            }

            if (this.FInvalidate)
            {
                if (this.lastframe != null)
                {
                    List <Skeleton> skels = new List <Skeleton>();
                    lock (m_lock)
                    {
                        foreach (Skeleton sk in this.lastframe)
                        {
                            if (sk.TrackingState == SkeletonTrackingState.Tracked)
                            {
                                skels.Add(sk);
                            }
                        }
                    }

                    int cnt = skels.Count;
                    this.FOutCount[0] = cnt;

                    this.FOutPosition.SliceCount           = cnt;
                    this.FOutUserIndex.SliceCount          = cnt;
                    this.FOutClipped.SliceCount            = cnt;
                    this.FOutJointPosition.SliceCount      = cnt * 20;
                    this.FOutJointColorPosition.SliceCount = cnt * 20;
                    this.FOutJointDepthPosition.SliceCount = cnt * 20;
                    this.FOutJointState.SliceCount         = cnt * 20;
                    this.FOutJointID.SliceCount            = cnt * 20;
                    this.FOutJointOrientation.SliceCount   = cnt * 20;
                    this.FOutJointWOrientation.SliceCount  = cnt * 20;
                    this.FOutJointTo.SliceCount            = cnt * 20;
                    this.FOutJointFrom.SliceCount          = cnt * 20;
                    this.FOutFrameNumber[0] = this.frameid;


                    int jc = 0;
                    for (int i = 0; i < cnt; i++)
                    {
                        Skeleton sk = skels[i];
                        this.FOutPosition[i]  = new Vector3(sk.Position.X, sk.Position.Y, sk.Position.Z);
                        this.FOutUserIndex[i] = sk.TrackingId;

                        Vector4 clip = Vector4.Zero;
                        clip.X = Convert.ToSingle(sk.ClippedEdges.HasFlag(FrameEdges.Left));
                        clip.Y = Convert.ToSingle(sk.ClippedEdges.HasFlag(FrameEdges.Right));
                        clip.Z = Convert.ToSingle(sk.ClippedEdges.HasFlag(FrameEdges.Top));
                        clip.W = Convert.ToSingle(sk.ClippedEdges.HasFlag(FrameEdges.Bottom));

                        this.FOutClipped[i] = clip;

                        foreach (Joint joint in sk.Joints)
                        {
                            this.FOutJointFrom[jc] = sk.BoneOrientations[joint.JointType].StartJoint.ToString();
                            this.FOutJointTo[jc]   = sk.BoneOrientations[joint.JointType].EndJoint.ToString();
                            BoneRotation bo  = sk.BoneOrientations[joint.JointType].HierarchicalRotation;
                            BoneRotation bow = sk.BoneOrientations[joint.JointType].AbsoluteRotation;
                            this.FOutJointID[jc]       = joint.JointType.ToString();
                            this.FOutJointPosition[jc] = new Vector3(joint.Position.X, joint.Position.Y, joint.Position.Z);

                            ColorImagePoint cp = this.runtime.Runtime.CoordinateMapper.MapSkeletonPointToColorPoint(joint.Position, ColorImageFormat.RgbResolution640x480Fps30);
                            this.FOutJointColorPosition[jc] = new Vector2(cp.X, cp.Y);
                            DepthImagePoint dp = this.runtime.Runtime.CoordinateMapper.MapSkeletonPointToDepthPoint(joint.Position, DepthImageFormat.Resolution320x240Fps30);
#pragma warning disable
                            this.FOutJointDepthPosition[jc] = new Vector4(dp.X, dp.Y, dp.Depth, dp.PlayerIndex);
#pragma warning restore
                            this.FOutJointOrientation[jc]  = new Quaternion(bo.Quaternion.X, bo.Quaternion.Y, bo.Quaternion.Z, bo.Quaternion.W);
                            this.FOutJointWOrientation[jc] = new Quaternion(bow.Quaternion.X, bow.Quaternion.Y, bow.Quaternion.Z, bow.Quaternion.W);
                            this.FOutJointState[jc]        = joint.TrackingState.ToString();
                            jc++;
                        }
                    }
                }
                else
                {
                    this.FOutCount[0]                      = 0;
                    this.FOutPosition.SliceCount           = 0;
                    this.FOutUserIndex.SliceCount          = 0;
                    this.FOutJointID.SliceCount            = 0;
                    this.FOutJointPosition.SliceCount      = 0;
                    this.FOutJointState.SliceCount         = 0;
                    this.FOutFrameNumber[0]                = 0;
                    this.FOutJointOrientation.SliceCount   = 0;
                    this.FOutJointWOrientation.SliceCount  = 0;
                    this.FOutJointTo.SliceCount            = 0;
                    this.FOutJointFrom.SliceCount          = 0;
                    this.FOutJointColorPosition.SliceCount = 0;
                    this.FOutJointDepthPosition.SliceCount = 0;
                }
                this.FInvalidate = false;
            }
        }
Exemplo n.º 42
0
        /// <summary>
        /// Initialize this component. Attempts to load the SkeletonData and creates the internal Skeleton object and buffers.</summary>
        /// <param name="overwrite">If set to <c>true</c>, it will overwrite internal objects if they were already generated. Otherwise, the initialized component will ignore subsequent calls to initialize.</param>
        public virtual void Initialize(bool overwrite)
        {
            if (valid && !overwrite)
            {
                return;
            }

            // Clear
            {
                if (meshFilter != null)
                {
                    meshFilter.sharedMesh = null;
                }

                meshRenderer = GetComponent <MeshRenderer>();
                if (meshRenderer != null && meshRenderer.enabled)
                {
                    meshRenderer.sharedMaterial = null;
                }

                currentInstructions.Clear();
                rendererBuffers.Clear();
                meshGenerator.Begin();
                skeleton = null;
                valid    = false;
            }

            if (skeletonDataAsset == null)
            {
                return;
            }

            SkeletonData skeletonData = skeletonDataAsset.GetSkeletonData(false);

            if (skeletonData == null)
            {
                return;
            }
            valid = true;

            meshFilter   = GetComponent <MeshFilter>();
            meshRenderer = GetComponent <MeshRenderer>();
            rendererBuffers.Initialize();

            skeleton = new Skeleton(skeletonData)
            {
                ScaleX = initialFlipX ? -1 : 1,
                ScaleY = initialFlipY ? -1 : 1
            };

            if (!string.IsNullOrEmpty(initialSkinName) && !string.Equals(initialSkinName, "default", System.StringComparison.Ordinal))
            {
                skeleton.SetSkin(initialSkinName);
            }

            separatorSlots.Clear();
            for (int i = 0; i < separatorSlotNames.Length; i++)
            {
                separatorSlots.Add(skeleton.FindSlot(separatorSlotNames[i]));
            }

            LateUpdate();             // Generate mesh for the first frame it exists.

            if (OnRebuild != null)
            {
                OnRebuild(this);
            }

                        #if UNITY_EDITOR
            if (!Application.isPlaying)
            {
                string errorMessage = null;
                if (MaterialChecks.IsMaterialSetupProblematic(this, ref errorMessage))
                {
                    Debug.LogWarningFormat(this, "Problematic material setup at {0}: {1}", this.name, errorMessage);
                }
            }
                        #endif
        }
Exemplo n.º 43
0
        private Monster GetMonster(int x, Vector2 loc)
        {
            Monster m;

            switch (x)
            {
            case 0:
                m = new DustSpirit(loc);
                break;

            case 1:
                m = new Grub(loc);
                break;

            case 2:
                m = new Skeleton(loc);
                break;

            case 3:
                m = new RockCrab(loc);
                break;

            case 4:
                m = new Ghost(loc);
                break;

            case 5:
                m = new GreenSlime(loc);
                break;

            case 6:
                m = new RockGolem(loc);
                break;

            case 7:
                m = new ShadowBrute(loc);
                break;

            case 8:
                int y = rand.Next(1, 6);

                //m = new Monster();

                if (y == 1)
                {
                    m = new RockCrab(loc, "Iridium Crab");
                }
                else if (y == 2)
                {
                    m = new Ghost(loc, "Carbon Ghost");
                }
                else if (y == 3)
                {
                    m = new LavaCrab(loc);
                }
                //else if (y == 4)
                //m = new Bat(loc, Math.Max(Game1.player.CombatLevel * 5, 50));
                else if (y == 4)
                {
                    m = new GreenSlime(loc, Math.Max(Game1.player.CombatLevel * 5, 50));
                }
                else if (y == 5)
                {
                    m = new BigSlime(loc, Math.Max(Game1.player.CombatLevel * 5, 50));
                }
                else
                {
                    m = new Mummy(loc);
                }

                break;

            default:
                m = new Monster();
                break;
            }

            return(m);
        }
Exemplo n.º 44
0
 public static Color GetColor(this Skeleton s)
 {
     return(new Color(s.r, s.g, s.b, s.a));
 }
Exemplo n.º 45
0
        public static Texture2D GenHeadTex(Outfit headOft, string name)
        {
            var      skels = Content.Content.Get().AvatarSkeletons;
            Skeleton skel  = null;
            bool     pet   = false;

            if (name.StartsWith("uaa"))
            {
                //pet
                if (name.Contains("cat"))
                {
                    skel = skels.Get("cat.skel");
                }
                else
                {
                    skel = skels.Get("dog.skel");
                }
                pet = true;
            }
            else
            {
                skel = skels.Get("adult.skel");
            }

            var m_Head = new SimAvatar(skel);

            m_Head.Head = headOft;
            m_Head.ReloadSkeleton();
            m_Head.StripAllButHead();

            var HeadCamera = new BasicCamera(GameFacade.GraphicsDevice, new Vector3(0.0f, 7.0f, -17.0f), Vector3.Zero, Vector3.Up);

            var pos2 = m_Head.Skeleton.GetBone("HEAD").AbsolutePosition;

            pos2.Y += (pet)?((name.Contains("dog"))?0.16f:0.1f):0.12f;
            HeadCamera.Position         = new Vector3(0, pos2.Y, 12.5f);
            HeadCamera.FOV              = (float)Math.PI / 3f;
            HeadCamera.Target           = pos2;
            HeadCamera.ProjectionOrigin = new Vector2(66 / 2, 66 / 2);

            var HeadScene = new _3DTargetScene(GameFacade.GraphicsDevice, HeadCamera, new Point(66, 66), 0);// (GlobalSettings.Default.AntiAlias) ? 8 : 0);

            HeadScene.ID         = "UIPieMenuHead";
            HeadScene.ClearColor = new Color(49, 65, 88);

            m_Head.Scene = HeadScene;
            m_Head.Scale = new Vector3(1f);

            HeadCamera.Zoom = 19.5f;

            //rotate camera, similar to pie menu

            double xdir = 0; //Math.Atan(0);
            double ydir = 0; //Math.Atan(0);

            Vector3 off = new Vector3(0, 0, 13.5f);
            Matrix  mat = Microsoft.Xna.Framework.Matrix.CreateRotationY((float)xdir) * Microsoft.Xna.Framework.Matrix.CreateRotationX((float)ydir);

            HeadCamera.Position = new Vector3(0, pos2.Y, 0) + Vector3.Transform(off, mat);

            if (pet)
            {
                HeadCamera.Zoom *= 1.3f;
            }
            //end rotate camera

            HeadScene.Initialize(GameFacade.Scenes);
            HeadScene.Add(m_Head);

            HeadScene.Draw(GameFacade.GraphicsDevice);
            return(Common.Utils.TextureUtils.Decimate(HeadScene.Target, GameFacade.GraphicsDevice, 2, true));
        }
Exemplo n.º 46
0
        private void pcTimer_tick(Object sender, EventArgs e)
        {
            if (countdown == 3)
            {
                //get current skeleton tracking state
                Skeleton skeleton = this.kinectInterp.getSkeletons();
                jointDepths = enumerateSkeletonDepths(skeleton);

                //PointCloud structure methods
                PointCloud frontCloud = new PointCloud(this.kinectInterp.getRGBTexture(), this.kinectInterp.getDepthArray());
                //frontCloud.deleteFloor();
                fincloud.Add(frontCloud);
                sandra.Speak("Scan Added.");

                //freeze skelL skelDepth and skelR
                this.kinectInterp.kinectSensor.SkeletonStream.Disable();

                tmpCanvas              = skeloutline;
                skeloutline            = tmpCanvas;
                skeloutline.Visibility = Visibility.Collapsed;

                sandra.Speak("Please turn left.");
                this.instructionblock.Text = "Please turn left";
                countdown--;
            }
            else if (countdown == 2)
            {
                //PointCloud structure methods
                PointCloud rightCloud = new PointCloud(this.kinectInterp.getRGBTexture(), this.kinectInterp.getDepthArray());
                //rightCloud.deleteFloor();
                fincloud.Add(rightCloud);
                sandra.Speak("Scan Added.");
                sandra.Speak("Please turn left with your back to the camera.");
                this.instructionblock.Text = "Turn left with your back to the camera";
                countdown--;
            }
            else if (countdown == 1)
            {
                //PointCloud structure methods
                PointCloud backCloud = new PointCloud(this.kinectInterp.getRGBTexture(), this.kinectInterp.getDepthArray());
                //backCloud.deleteFloor();
                fincloud.Add(backCloud);
                sandra.Speak("Scan Added.");
                sandra.Speak("Please turn left once more.");
                this.instructionblock.Text = "Please turn left once more.";
                countdown--;
            }
            else if (countdown == 0)
            {
                //PointCloud structure methods
                PointCloud leftCloud = new PointCloud(this.kinectInterp.getRGBTexture(), this.kinectInterp.getDepthArray());
                //leftCloud.deleteFloor();
                fincloud.Add(leftCloud);

                this.instructionblock.Text = "You have now been captured. Thank you for your time.";

                sandra.Speak("Scan Added.");
                sandra.Speak("You have now been captured. Thank you for your time.");

                //stop streams
                kinectInterp.stopStreams();

                if ((((CoreLoader)((PatientLoader)((OptionLoader)(this.Owner)).Owner).Owner).windowPatient.nameText.Text.CompareTo("Greg Corbett")) == 0)
                {
                    CloudVisualisation fudge = ScanSerializer.deserialize("./Corbett.PARSE");
                    ((CoreLoader)((PatientLoader)((OptionLoader)(this.Owner)).Owner).Owner).setPC(null, ScanSerializer.depthPc);
                    ((CoreLoader)((PatientLoader)((OptionLoader)(this.Owner)).Owner).Owner).LoadPointCloud();
                    //((CoreLoader)((PatientLoader)((OptionLoader)(this.Owner)).Owner).Owner).fudge();
                }
                else if (this.Owner is CoreLoader)
                {
                    ((CoreLoader)(this.Owner)).setPC(pcd, fincloud);
                    ((CoreLoader)(this.Owner)).LoadPointCloud();
                    ((CoreLoader)(this.Owner)).export1.IsEnabled     = true;
                    ((CoreLoader)(this.Owner)).export2.IsEnabled     = true;
                    ((CoreLoader)(this.Owner)).removefloor.IsEnabled = true;
                }
                else if (this.Owner is OptionLoader)
                {
                    ((CoreLoader)((PatientLoader)((OptionLoader)(this.Owner)).Owner).Owner).setPC(pcd, fincloud);
                    ((CoreLoader)((PatientLoader)((OptionLoader)(this.Owner)).Owner).Owner).LoadPointCloud();
                    ((CoreLoader)((PatientLoader)((OptionLoader)(this.Owner)).Owner).Owner).export1.IsEnabled     = true;
                    ((CoreLoader)((PatientLoader)((OptionLoader)(this.Owner)).Owner).Owner).export2.IsEnabled     = true;
                    ((CoreLoader)((PatientLoader)((OptionLoader)(this.Owner)).Owner).Owner).removefloor.IsEnabled = true;
                }

                /*
                 * double height = Math.Round(HeightCalculator.getHeight(pcd), 3);
                 * ((CoreLoader)(this.Owner)).windowHistory.heightoutput.Content = height + "m";
                 *
                 * GroupVisualiser gg = new GroupVisualiser(fincloud);
                 * gg.preprocess(null);
                 * this.DataContext = gg;
                 *
                 * //Visualisation instantiation based on KDTree array clouds
                 * this.instructionblock.Text = "Scanning complete.";
                 * this.instructionblock.Visibility = Visibility.Collapsed;
                 *
                 *
                 */
                pcTimer.Stop();
                this.Close();

                //TODO: write all these results to the database; sql insertion clauses.
            }
        }
Exemplo n.º 47
0
    /// <summary>
    /// -40度から、0度の間に敵が生成される
    /// </summary>
    public void DropEnemy1()
    {
        int enemy = Random.Range(1, 4);             //生成される敵の種類

        Set_px();                                   //敵とプレイヤの最大距離を設定
        //EnemyCountに+1
        EnemyCount++;

        //生成される位置が-40度から0度の間の普通の敵
        if (enemy == 1)
        {
            GameObject go = Instantiate(Enemy1) as GameObject;

            int pz = Random.Range(-40, 1);                  //角度を設定する

            //度数法から弧度法に変換している
            float radian = pz * Mathf.PI / 180;

            float x2 = Mathf.Cos(radian) * px;              //最初のX座標
            float y2 = Mathf.Sin(radian) * px;              //最初のY座標(Z座標)

            float a2 = Mathf.Cos(radian) * Enemy1_distance; //最後のX座標
            float b2 = Mathf.Sin(radian) * Enemy1_distance; //最後のY座標(Z座標)

            //敵のスクリプトのInitialize関数に引数を渡す
            Bat_Script bat = go.GetComponent <Bat_Script>();
            bat.Initialize(x2, y2, a2, b2, pz);
        }

        //生成される位置が-40度から0度の間の普通の敵
        else if (enemy == 2)
        {
            GameObject go = Instantiate(Enemy2) as GameObject;

            int pz = Random.Range(-40, 1);                  //角度を設定する

            //度数法から弧度法に変換している
            float radian = pz * Mathf.PI / 180;

            float x2 = Mathf.Cos(radian) * px;              //最初のX座標
            float y2 = Mathf.Sin(radian) * px;              //最初のY座標(Z座標)

            float a2 = Mathf.Cos(radian) * Enemy2_distance; //最後のX座標
            float b2 = Mathf.Sin(radian) * Enemy2_distance; //最後のY座標(Z座標)

            //敵のスクリプトのInitialize関数に引数を渡す
            Golem_Script golem = go.GetComponent <Golem_Script>();
            golem.Initialize(x2, y2, a2, b2, pz);
        }

        //生成される位置が-40度から0度の間の弱点付きの敵
        else if (enemy == 3)
        {
            GameObject go = Instantiate(Enemy3) as GameObject;

            int pz = Random.Range(-40, 1);                  //角度を設定する

            //度数法から弧度法に変換している
            float radian = pz * Mathf.PI / 180;

            float x2 = Mathf.Cos(radian) * px;              //最初のX座標
            float y2 = Mathf.Sin(radian) * px;              //最初のY座標(Z座標)

            float a2 = Mathf.Cos(radian) * Enemy3_distance; //最後のX座標
            float b2 = Mathf.Sin(radian) * Enemy3_distance; //最後のY座標(Z座標)

            //敵のスクリプトのInitialize関数に引数を渡す
            Skeleton skeleton = go.GetComponent <Skeleton>();
            skeleton.Initialize(x2, y2, a2, b2, pz);
        }
    }
Exemplo n.º 48
0
            /// <summary>
            /// Updates the face tracking information for this skeleton
            /// </summary>
            internal void OnFrameReady(KinectSensor kinectSensor, ColorImageFormat colorImageFormat, byte[] colorImage, DepthImageFormat depthImageFormat, short[] depthImage, Skeleton skeletonOfInterest)
            {
                this.skeletonTrackingState = skeletonOfInterest.TrackingState;

                if (this.skeletonTrackingState != SkeletonTrackingState.Tracked)
                {
                    // nothing to do with an untracked skeleton.
                    return;
                }

                if (this.faceTracker == null)
                {
                    try
                    {
                        this.faceTracker = new FaceTracker(kinectSensor);
                    }
                    catch (InvalidOperationException)
                    {
                        // During some shutdown scenarios the FaceTracker
                        // is unable to be instantiated.  Catch that exception
                        // and don't track a face.
                        Debug.WriteLine("AllFramesReady - creating a new FaceTracker threw an InvalidOperationException");
                        this.faceTracker = null;
                    }
                }

                if (this.faceTracker != null)
                {
                    FaceTrackFrame frame = this.faceTracker.Track(
                        colorImageFormat, colorImage, depthImageFormat, depthImage, skeletonOfInterest);
                    this.lastFaceTrackSucceeded = frame.TrackSuccessful;
                    if (this.lastFaceTrackSucceeded)
                    {
                        if (faceTriangles == null)
                        {
                            //    only need to get this once.  It doesn't change.
                            faceTriangles = frame.GetTriangles();
                        }

                        this.facePoints3DRaw = frame.Get3DShape();
                        this.facePoints      = frame.GetProjected3DShape();
                        animationUnitsRaw    = frame.GetAnimationUnitCoefficients();
                    }
                    x              = frame.Rotation.X;
                    y              = frame.Rotation.Y;
                    z              = frame.Rotation.Z;
                    facePointS3D   = this.facePoints3DRaw;
                    animationUnits = animationUnitsRaw;
                    //Debug.WriteLine(animationUnits[AnimationUnit.JawLower]);
                    //Debug.WriteLine(animationUnits[AnimationUnit.BrowLower]);
                    //Debug.WriteLine(animationUnits[AnimationUnit.BrowRaiser]);
                    //Debug.WriteLine(animationUnits[AnimationUnit.JawLower]);
                    //Debug.WriteLine(animationUnits[AnimationUnit.LipCornerDepressor]);
                    //Debug.WriteLine(animationUnits[AnimationUnit.LipRaiser]);
                    //Debug.WriteLine(animationUnits[AnimationUnit.LipStretcher]);
                    //Debug.WriteLine(frame.Translation.ToString());
                    //Debug.WriteLine(frame.Rotation.ToString());
                    //this.facePoints[FeaturePoint.AboveChin].X+2;
                    //Debug.WriteLine(frame.Translation.X.ToString());
                    //Debug.WriteLine(frame.Translation.Y.ToString());
                    //Debug.WriteLine(frame.Translation.Z.ToString());
                }
            }
Exemplo n.º 49
0
 public void SetSkeleton(Skeleton skeleton) => Skeleton = skeleton;
Exemplo n.º 50
0
 /// <summary>
 /// Send MIDI signal with using skeleton coordinations and math expressions
 /// </summary>
 public abstract void Send(Skeleton skeleton);
Exemplo n.º 51
0
    public virtual void Reset()
    {
        if (meshFilter != null)
        {
            meshFilter.sharedMesh = null;
        }
        if (GetComponent <Renderer>() != null)
        {
            GetComponent <Renderer>().sharedMaterial = null;
        }

        if (mesh1 != null)
        {
            if (Application.isPlaying)
            {
                Destroy(mesh1);
            }
            else
            {
                DestroyImmediate(mesh1);
            }
        }

        if (mesh2 != null)
        {
            if (Application.isPlaying)
            {
                Destroy(mesh2);
            }
            else
            {
                DestroyImmediate(mesh2);
            }
        }

        mesh1           = null;
        mesh2           = null;
        lastVertexCount = 0;
        vertices        = null;
        colors          = null;
        uvs             = null;
        sharedMaterials = new Material[0];
        submeshMaterials.Clear();
        submeshes.Clear();
        skeleton = null;

        valid = false;
        if (!skeletonDataAsset)
        {
            if (logErrors)
            {
                Debug.LogError("Missing SkeletonData asset.", this);
            }

            return;
        }
        SkeletonData skeletonData = skeletonDataAsset.GetSkeletonData(false);

        if (skeletonData == null)
        {
            return;
        }
        valid = true;

        meshFilter = GetComponent <MeshFilter>();
        mesh1      = newMesh();
        mesh2      = newMesh();
        vertices   = new Vector3[0];

        skeleton = new Skeleton(skeletonData);
        if (initialSkinName != null && initialSkinName.Length > 0 && initialSkinName != "default")
        {
            skeleton.SetSkin(initialSkinName);
        }

        submeshSeparatorSlots.Clear();
        for (int i = 0; i < submeshSeparators.Length; i++)
        {
            submeshSeparatorSlots.Add(skeleton.FindSlot(submeshSeparators[i]));
        }

        if (OnReset != null)
        {
            OnReset(this);
        }
    }
 void OnEnable()
 {
     skeleton = (Skeleton)target;
 }
Exemplo n.º 53
0
        //here we go, thats the method called by vvvv each frame
        //all data handling should be in here
        public void Evaluate(int SpreadMax)
        {
            //if any of the inputs has changed
            //recompute the outputs

            if (FSkeletonInput.PinIsChanged || !initialized)
            {
                jointPositions = new Dictionary <string, Vector3D>();
                object currInterface;
                FSkeletonInput.GetUpstreamInterface(out currInterface);
                try
                {
                    skeleton  = (Skeleton)currInterface;
                    rootJoint = (IJoint)skeleton.Root;
                }
                catch (Exception e)
                {
                    FHost.Log(TLogType.Error, e.Message);
                }

                if (!initialized && configSelectedNames != null)
                {
                    selectedJoints.Clear();
                    IJoint currJoint;
                    for (int i = 0; i < configSelectedNames.Length; i++)
                    {
                        if (string.IsNullOrEmpty(configSelectedNames[i]))
                        {
                            break;
                        }
                        if (skeleton.JointTable.ContainsKey(configSelectedNames[i]))
                        {
                            currJoint = skeleton.JointTable[configSelectedNames[i]];
                            if (currJoint != null)
                            {
                                selectedJoints.Add(currJoint);
                            }
                        }
                    }
                }

                //redraw gui only if anything changed
                Invalidate();
            }

            if (selectedJoints.Count > 0)
            {
                FJointNameOutput.SliceCount = selectedJoints.Count;
                for (int i = 0; i < selectedJoints.Count; i++)
                {
                    FJointNameOutput.SetString(i, selectedJoints[i].Name);
                }
            }
            else
            {
                FJointNameOutput.SetString(0, "");
            }

            buildConfig();

            initialized = true;
        }
Exemplo n.º 54
0
        public virtual void Initialize(bool overwrite)
        {
            if (valid && !overwrite)
            {
                return;
            }

            // Clear
            {
                if (meshFilter != null)
                {
                    meshFilter.sharedMesh = null;
                }

                meshRenderer = GetComponent <MeshRenderer>();
                if (meshRenderer != null)
                {
                    meshRenderer.sharedMaterial = null;
                }

                currentInstructions.Clear();
                vertices        = null;
                colors          = null;
                uvs             = null;
                sharedMaterials = new Material[0];
                submeshMaterials.Clear();
                submeshes.Clear();
                skeleton = null;

                valid = false;
            }

            if (!skeletonDataAsset)
            {
                if (logErrors)
                {
                    Debug.LogError("Missing SkeletonData asset.", this);
                }

                return;
            }
            SkeletonData skeletonData = skeletonDataAsset.GetSkeletonData(false);

            if (skeletonData == null)
            {
                return;
            }
            valid = true;

            meshFilter         = GetComponent <MeshFilter>();
            meshRenderer       = GetComponent <MeshRenderer>();
            doubleBufferedMesh = new DoubleBuffered <SmartMesh>();
            vertices           = new Vector3[0];

            skeleton = new Skeleton(skeletonData);
            if (!string.IsNullOrEmpty(initialSkinName) && initialSkinName != "default")
            {
                skeleton.SetSkin(initialSkinName);
            }

            separatorSlots.Clear();
            for (int i = 0; i < separatorSlotNames.Length; i++)
            {
                separatorSlots.Add(skeleton.FindSlot(separatorSlotNames[i]));
            }

            LateUpdate();

            if (OnRebuild != null)
            {
                OnRebuild(this);
            }
        }
Exemplo n.º 55
0
 public Bone(string name, ushort handle, Skeleton creator) : this(OgrePINVOKE.new_Bone__SWIG_1(name, handle, Skeleton.getCPtr(creator)), true)
 {
     if (OgrePINVOKE.SWIGPendingException.Pending)
     {
         throw OgrePINVOKE.SWIGPendingException.Retrieve();
     }
 }
Exemplo n.º 56
0
 /// <summary>Returns the Skeleton's local scale as a UnityEngine.Vector2. If only individual components are needed, use Skeleton.ScaleX or Skeleton.ScaleY.</summary>
 public static Vector2 GetLocalScale(this Skeleton skeleton)
 {
     return(new Vector2(skeleton.scaleX, skeleton.scaleY));
 }
Exemplo n.º 57
0
        //Includes rules that the user needs to follow in order to perform the exercise correctly.
        //If a joint position is found to be incorrect, it adds the joint to the jointErrorDict with a list of strings.
        //The list of strings contains the problem and also a solution.
        internal static void TrackPress(Skeleton skeleton)
        {
            jointErrorDict.Clear();

            //Knees Correction
            if (previousLeftKneeZ == 0.0f || previousRightKneeZ == 0.0f || previousRightKneeY == 0.0f || previousLeftKneeY == 0.0f)
            {
                previousLeftKneeZ  = skeleton.Joints[JointType.KneeLeft].Position.X;
                previousLeftKneeY  = skeleton.Joints[JointType.KneeLeft].Position.Y;
                previousRightKneeZ = skeleton.Joints[JointType.KneeRight].Position.X;
                previousRightKneeY = skeleton.Joints[JointType.KneeRight].Position.Y;
            }
            float currentLeftKneeY  = skeleton.Joints[JointType.KneeLeft].Position.Y;
            float currentLeftKneeZ  = skeleton.Joints[JointType.KneeLeft].Position.Z;
            float currentRightKneeY = skeleton.Joints[JointType.KneeRight].Position.Y;
            float currentRightKneeZ = skeleton.Joints[JointType.KneeRight].Position.Z;

            //Check if knees have changed position
            if (previousLeftKneeY > currentLeftKneeY + 0.005 * skeletonHeight || previousLeftKneeY < currentLeftKneeY - 0.005 * skeletonHeight ||
                previousLeftKneeZ > currentLeftKneeZ + 0.005 * skeletonHeight || previousLeftKneeZ < currentLeftKneeZ - 0.005 * skeletonHeight)
            {
                List <string> list = new List <string>
                {
                    "Knees should not move during overhead press.",
                    "This is an exercise for the shoulders, triceps and back. If you cannot lift the weight without using your knees, consider lightening it."
                };
                jointErrorDict.AddOrUpdate("KneeLeft", list, (key, oldValue) => list);
            }

            if (previousRightKneeY > currentRightKneeY + 0.005 * skeletonHeight || previousRightKneeY < currentRightKneeY - 0.005 * skeletonHeight ||
                previousRightKneeZ > currentRightKneeZ + 0.005 * skeletonHeight || previousRightKneeZ < currentRightKneeZ - 0.005 * skeletonHeight)
            {
                List <string> list = new List <string>
                {
                    "Knees should not move during overhead press.",
                    "This is an exercise for the shoulders, triceps and back. If you cannot lift the weight without using your knees, consider lightening it."
                };
                jointErrorDict.AddOrUpdate("KneeRight", list, (key, oldValue) => list);
            }

            //Update previous knee position store
            previousLeftKneeY  = currentLeftKneeY;
            previousLeftKneeZ  = currentLeftKneeZ;
            previousRightKneeY = currentRightKneeY;
            previousRightKneeZ = currentRightKneeZ;

            //Elbows Correction
            if (skeleton.Joints[JointType.ElbowLeft].Position.Z < (skeleton.Joints[JointType.ShoulderLeft].Position.Z - 0.1 * skeletonHeight) ||
                skeleton.Joints[JointType.ElbowLeft].Position.X < (skeleton.Joints[JointType.HandLeft].Position.X - 0.05 * skeletonHeight))
            {
                List <string> list = new List <string>
                {
                    "Elbows should not flare too far forward or out.",
                    "Keep your elbows close to your side and pointed down. This is safer and will help you lift more weight."
                };
                jointErrorDict.AddOrUpdate("ElbowLeft", list, (key, oldValue) => list);
            }

            if (skeleton.Joints[JointType.ElbowRight].Position.Z <(skeleton.Joints[JointType.ShoulderRight].Position.Z - 0.1 * skeletonHeight) ||
                                                                  skeleton.Joints[JointType.ElbowRight].Position.X> (skeleton.Joints[JointType.HandRight].Position.X + 0.05 * skeletonHeight))
            {
                List <string> list = new List <string>
                {
                    "Elbows should not flare too far forward or out.",
                    "Keep your elbows close to your side and pointed down. This is safer and will help you lift more weight."
                };
                jointErrorDict.AddOrUpdate("ElbowRight", list, (key, oldValue) => list);
            }

            //Hand Correction
            if (skeleton.Joints[JointType.HandRight].Position.Y < (skeleton.Joints[JointType.HandLeft].Position.Y - 0.05 * skeletonHeight))
            {
                List <string> list = new List <string>
                {
                    "Right hand is rising slower than the left hand",
                    "This is a sign of an imbalance in the right shoulder. Consider doing isolation exercises for that shoulder until it is as strong as the other. For example, single arm dumbbell press: https://www.youtube.com/watch?v=NVnyDQqmhPo"
                };
                jointErrorDict.AddOrUpdate("HandRight", list, (key, oldValue) => list);
            }

            if (skeleton.Joints[JointType.HandRight].Position.Y > skeleton.Joints[JointType.HandLeft].Position.Y + 0.05 * skeletonHeight)
            {
                List <string> list = new List <string>
                {
                    "Left hand is rising slower than the right hand",
                    "This is a sign of an imbalance in the left shoulder. Consider doing isolation exercises for that shoulder until it is as strong as the other. For example, single arm dumbbell press: https://www.youtube.com/watch?v=NVnyDQqmhPo"
                };
                jointErrorDict.AddOrUpdate("HandLeft", list, (key, oldValue) => list);
            }

            float handLineY     = (skeleton.Joints[JointType.HandRight].Position.Y + skeleton.Joints[JointType.HandLeft].Position.Y) / 2;
            float handLineZ     = (skeleton.Joints[JointType.HandRight].Position.Z + skeleton.Joints[JointType.HandLeft].Position.Z) / 2;
            float shoulderLineZ = (skeleton.Joints[JointType.ShoulderRight].Position.Z + skeleton.Joints[JointType.ShoulderLeft].Position.Z) / 2;

            if ((handLineY > skeleton.Joints[JointType.Head].Position.Y) && (handLineZ > shoulderLineZ + (0.1 * skeletonHeight)))
            {
                List <string> list = new List <string>
                {
                    "Bringing the bar too far back at the end.",
                    "This puts unnecessary strain on the shoulders and will cause you to lose balance. Try to keep it directly over your head."
                };
                jointErrorDict.AddOrUpdate("HandLeft", list, (key, oldValue) => list);
                jointErrorDict.AddOrUpdate("HandRight", list, (key, oldValue) => list);
            }

            if ((handLineY > skeleton.Joints[JointType.Head].Position.Y) && (handLineZ < shoulderLineZ - (0.1 * skeletonHeight)))
            {
                List <string> list = new List <string>
                {
                    "Bringing the bar too far forward at the end.",
                    "This puts unnecessary strain on the shoulders and will cause you to lose balance. Try to keep it directly over your head."
                };
                jointErrorDict.AddOrUpdate("HandLeft", list, (key, oldValue) => list);
                jointErrorDict.AddOrUpdate("HandRight", list, (key, oldValue) => list);
            }
        }
Exemplo n.º 58
0
        /// <summary>
        /// Dessine une main
        /// </summary>
        /// <param name="skel">Squelette auquel appartient la main</param>
        /// <param name="jointType">Type du joint à dessiner</param>
        private void DrawHand(Skeleton skel, JointType jointType)
        {
            // Le joint à dessiner
            Joint joint = skel.Joints[jointType];
            // Le color point associer
            ColorImagePoint colorPoint = coordMap.MapSkeletonPointToColorPoint(joint.Position, ColorImageFormat.RgbResolution640x480Fps30);

            // Si le joint n'est pas trouvé ou pas bien trouvé
            if (joint.TrackingState == JointTrackingState.NotTracked || joint.TrackingState == JointTrackingState.Inferred)
            {
                return;
            }

            // Si on a le droit de dessiner, on affiche un crayon
            if (actualHandState == InteractionHandEventType.GripRelease)
            {
                // Afficher crayon pour dessiner (main ouverte)
                Image i = new Image();
                i.Source = new BitmapImage(new Uri("img\\crayon.gif", UriKind.Relative));
                i.Height = 100;
                i.Width  = 100;
                i.Margin = new Thickness(colorPoint.X, colorPoint.Y - i.Width, 0, 0);
                canvas.Children.Add(i);

                // Les points à dessiner, en color point
                ColorImagePoint dernierPointColor = coordMap.MapSkeletonPointToColorPoint(DernierPoint, ColorImageFormat.RgbResolution640x480Fps30);
                ColorImagePoint pointActuelColor  = coordMap.MapSkeletonPointToColorPoint(joint.Position, ColorImageFormat.RgbResolution640x480Fps30);

                // Ajout dans la liste de segment (avec les coordonnées de color point)
                Draw.getInstance().Add(new Segment(dernierPointColor.X, dernierPointColor.Y, pointActuelColor.X, pointActuelColor.Y));

                // Dessine le segment sur le canvas de dessin
                Line l = new Line();
                l.Stroke          = Brushes.Red;
                l.StrokeThickness = 5;

                l.X1 = dernierPointColor.X;
                l.Y1 = dernierPointColor.Y;
                l.X2 = pointActuelColor.X;
                l.Y2 = pointActuelColor.Y;

                canvasDessin.Children.Add(l);
            }

            // Si on n'a pas le droit de dessiner, on affiche un curseur et la main d'arrêt
            else if (actualHandState == InteractionHandEventType.Grip)
            {
                // Afficher main d'arrêt de dessin (main fermer)
                Image i = new Image();
                i.Source = new BitmapImage(new Uri("img\\mainArret.gif", UriKind.Relative));
                i.Height = 130;
                i.Width  = 130;
                i.Margin = new Thickness(colorPoint.X - (i.Height / 2), colorPoint.Y - (i.Width / 2), 0, 0);
                canvas.Children.Add(i);

                // Afficher position de la main
                canvasPosition.Children.Clear();

                Line l1 = new Line();
                Line l2 = new Line();
                l1.Stroke          = Brushes.Green;
                l2.Stroke          = Brushes.Green;
                l1.StrokeThickness = 3;
                l2.StrokeThickness = 3;

                int TailleCroixPositionMain = 10;
                l1.X1 = colorPoint.X - TailleCroixPositionMain;
                l1.Y1 = colorPoint.Y + TailleCroixPositionMain;
                l1.X2 = colorPoint.X + TailleCroixPositionMain;
                l1.Y2 = colorPoint.Y - TailleCroixPositionMain;
                l2.X1 = colorPoint.X + TailleCroixPositionMain;
                l2.Y1 = colorPoint.Y + TailleCroixPositionMain;
                l2.X2 = colorPoint.X - TailleCroixPositionMain;
                l2.Y2 = colorPoint.Y - TailleCroixPositionMain;

                canvasPosition.Children.Add(l1);
                canvasPosition.Children.Add(l2);
            }
            DernierPoint = joint.Position;
        }
Exemplo n.º 59
0
        //Sets skeleton height.
        public float SetSkeletonHeight(Skeleton skeleton)
        {
            float footAverageY = (skeleton.Joints[JointType.FootRight].Position.Y + skeleton.Joints[JointType.FootLeft].Position.Y) / 2;

            return(skeleton.Joints[JointType.Head].Position.Y - footAverageY + 0.1f);
        }
Exemplo n.º 60
0
 public Skeleton_MeleeAttackState(Entity entity1, FiniteStateMachine stateMachine, string animBoolName, Transform attackPosition, D_MeleeAttack stateData, Skeleton enemy) : base(entity1, stateMachine, animBoolName, attackPosition, stateData)
 {
     this.enemy = enemy;
 }