public static Bone2DWeights CalculateBoneWeights(Transform owner, Bone[] bones, Mesh mesh) { if (bones != null) { Bone2DWeights boneWeights = new Bone2DWeights(); boneWeights.weights = new Bone2DWeight[] { }; int vIndex = 0; foreach (Vector3 v in mesh.vertices) { Bone closest = FindClosestBone(v, bones); if (closest != null) { boneWeights.SetWeight(vIndex++, closest.name, Array.IndexOf(bones, closest), 1f); } } BoneWeight[] unitweights = boneWeights.GetUnityBoneWeights(); mesh.boneWeights = unitweights; Transform[] bonesArr = bones.Select(b => b.transform).ToArray(); Matrix4x4[] bindPoses = new Matrix4x4[bonesArr.Length]; for (int i = 0; i < bonesArr.Length; i++) { bindPoses[i] = bonesArr[i].worldToLocalMatrix * owner.localToWorldMatrix; } mesh.bindposes = bindPoses; return boneWeights; } return null; }
public override bool SolveBoneChain(Bone[] bones, Bone target, Bone parent) { // Calculate distances float[] distances = GetDistances(ref bones); double dist = Math.Abs((bones[0].Pos - target.Pos).Length); if (dist > distances.Sum()) // the target is unreachable { TargetUnreachable(bones, target.Pos, parent); return true; } // The target is reachable int numberOfBones = bones.Length; bones[numberOfBones - 1].Orientation = target.Orientation; Vector3 root = bones[0].Pos; int iterations = 0; float lastDistToTarget = float.MaxValue; float distToTarget = (bones[bones.Length - 1].Pos - target.Pos).Length; while (distToTarget > threshold && iterations++ < MaxIterations && distToTarget < lastDistToTarget) { // Forward reaching ForwardReaching(ref bones, ref distances, target); // Backward reaching BackwardReaching(ref bones, ref distances, root, parent); lastDistToTarget = distToTarget; distToTarget = (bones[bones.Length - 1].Pos - target.Pos).Length; } bones[bones.Length - 1].Orientation = target.Orientation; return (distToTarget <= threshold); }
public void LateUpdate() { if (!valid) { Reset(); return; } if (bone == null) { if (boneName == null || boneName.Length == 0) return; bone = skeletonRenderer.skeleton.FindBone(boneName); if (bone == null) { Debug.LogError("Bone not found: " + boneName, this); return; } } if (cachedTransform.parent == skeletonTransform) { cachedTransform.localPosition = new Vector3(bone.worldX, bone.worldY, cachedTransform.localPosition.z); Vector3 rotation = cachedTransform.localRotation.eulerAngles; cachedTransform.localRotation = Quaternion.Euler(rotation.x, rotation.y, bone.worldRotation); } else { cachedTransform.position = skeletonTransform.TransformPoint(new Vector3(bone.worldX, bone.worldY, cachedTransform.position.z)); Vector3 rotation = skeletonTransform.rotation.eulerAngles; cachedTransform.rotation = Quaternion.Euler(rotation.x, rotation.y, skeletonTransform.rotation.eulerAngles.z + bone.worldRotation); } }
public void Reset () { bone = null; cachedTransform = transform; valid = skeletonRenderer != null && skeletonRenderer.valid; if (!valid) return; skeletonTransform = skeletonRenderer.transform; }
/// <summary> /// The backwards reaching phase /// </summary> /// <param name="bones"></param> /// <param name="distances"></param> /// <param name="root"></param> /// <param name="parent"></param> private void BackwardReaching(ref Bone[] bones, ref float[] distances, Vector3 root, Bone parent) { bones[0].Pos = root; for (int i = 0; i < bones.Length - 1; i++) { SamePosCheck(ref bones, i); Vector3 newPos; // Position float r = (bones[i + 1].Pos - bones[i].Pos).Length; float l = distances[i] / r; newPos = (1 - l) * bones[i].Pos + l * bones[i + 1].Pos; Bone prevBone = (i > 0) ? bones[i - 1] : parent; bones[i + 1].Pos = newPos; // Orientation bones[i].RotateTowards(bones[i + 1].Pos - bones[i].Pos,bones[i].Stiffness); if (bones[i].HasConstraints) { Quaternion rot; if (constraints.CheckOrientationalConstraint(bones[i], prevBone, out rot)) { bones[i].Rotate(rot); } } } }
public Arm(int p, Entity.Gender g) { if(p > 9 || p < 1) { throw new System.OverflowException("Position: " + p + " is invalid for arm!"); } position = p; switch(g){ case Entity.Gender.MALE: //placeholder { break; } case Entity.Gender.FEMALE: //females have weaker bone structure than males { Bone Scapula = new Bone (.7, 20, 1); Bone Humerus = new Bone (.65, 14, 2); Bone Radius = new Bone (.25, 10, 3); Bone Ulna = new Bone (.25, 10, 3); Bone Carpus = new Bone (.35, 12, 4); Bone Thumb = new Bone (.12, 8, 5); Bone Pointer = new Bone (.12, 8, 5); Bone Middle = new Bone (.12, 8, 5); Bone Ring = new Bone (.12, 8, 5); Bone Pinky = new Bone (.12, 5, 5); break; } } }
public MirrorNode(Node parentNode, Bone referenceBone) { this.ReferenceBone = referenceBone; Node = parentNode.CreateChild(ReferenceBone.InitialPosition, ReferenceBone.InitialOrientation); Children = new List<MirrorNode>(ReferenceBone.NumChildren()); foreach (Bone bone in referenceBone.GetChildIterator().OfType<Bone>()) Children.Add(new MirrorNode(Node, bone)); }
public SceneAnimator() { _skeleton = null; CurrentAnimationIndex = -1; _bonesByName = new Dictionary<string, Bone>(); _bonesToIndex = new Dictionary<string, int>(); _animationNameToId = new Dictionary<string, int>(); _bones = new List<Bone>(); Animations = new List<AnimEvaluator>(); }
/// <summary> /// Checks if an array of objects contains any duplicates. /// </summary> public static Transform ContainsDuplicateBone(Bone[] bones) { for (int i = 0; i < bones.Length; i++) { for (int i2 = 0; i2 < bones.Length; i2++) { if (i != i2 && bones[i].transform == bones[i2].transform) return bones[i].transform; } } return null; }
/// <summary> /// Gets the total length from the root of each bone in the kinematic chain (the bone chain) /// </summary> /// <param name="distances"></param> /// <param name="bones"></param> protected float[] GetDistances(ref Bone[] bones) { float[] distances = new float[bones.Length - 1]; for (int i = 0; i < distances.Length; i++) { distances[i] = (bones[i].Pos - bones[i + 1].Pos).Length; } return distances; }
/// <summary> /// Checks wheter the target is reacheble for the bone chain or not /// </summary> /// <param name="bones">The chain of bone, the IK Chain</param> /// <param name="target">The target</param> /// <returns>True if target is reachable, false otherwise</returns> protected bool IsReachable(Bone[] bones, Bone target) { float acc = 0; for (int i = 0; i < bones.Length - 1; i++) { acc += (bones[i].Pos - bones[i + 1].Pos).Length; } float dist = System.Math.Abs((bones[0].Pos - target.Pos).Length); return dist < acc; // the target is unreachable }
/// <summary> /// Initializes a new instance of the EditAttachedObjectEventArgs class. /// </summary> /// <param name="response">EditObjectResponse.</param> /// <param name="index">Index of the attached object.</param> /// <param name="modelid">Model of the attached object.</param> /// <param name="bone">The bone the object was attached to.</param> /// <param name="offset">Offset of the attached object.</param> /// <param name="rotation">Rotation of the attached object.</param> /// <param name="scale">Scale of the attached object.</param> public EditAttachedObjectEventArgs(EditObjectResponse response, int index, int modelid, Bone bone, Vector3 offset, Vector3 rotation, Vector3 scale) { EditObjectResponse = response; Index = index; ModelId = modelid; Bone = bone; Offset = offset; Rotation = rotation; Scale = scale; }
void UpdateSegmentPosition(JointID j1, JointID j2, Segment seg) { var bone = new Bone(j1, j2); if (segments.ContainsKey(bone)) { BoneData data = segments[bone]; data.UpdateSegment(seg); segments[bone] = data; } else segments.Add(bone, new BoneData(seg)); }
public HeadIK( FullBodyIK fullBodyIK ) { _settings = fullBodyIK.settings; _internalValues = fullBodyIK.internalValues; _neckBone = _PrepareBone( fullBodyIK.headBones.neck ); _headBone = _PrepareBone( fullBodyIK.headBones.head ); _leftEyeBone = _PrepareBone( fullBodyIK.headBones.leftEye ); _rightEyeBone = _PrepareBone( fullBodyIK.headBones.rightEye ); _headEffector = fullBodyIK.headEffectors.head; _eyesEffector = fullBodyIK.headEffectors.eyes; }
internal QMesh(Point3f[] v, TexCoord[] t, Color[] c, ushort[] f, Matrix m, Texture tx, string n, Bone[] pmBones, bool outline) : base(Matrix.IDENTITY, pmBones) { vertices= v; texcoords= t; colors= c; faces= f; pMatrix= m; pTexture= tx; name= n; bRenderOutline= outline; }
protected override void init() { bones = new List<Bone>(); Bone bone = new Bone(); bone.Scale(new Vector3(0.2f, 1f, 0.2f)); bones.Add(bone); bone = new Bone(); bone.Scale(new Vector3(0.2f, 0.5f, 0.2f)); bone.Move(new Vector3(0.3f, 0f, 0f)); bones[0].AddChild(bone); bones.Add(bone); SetupDepthAndCull(); }
public void Reset () { bone = null; cachedTransform = transform; valid = skeletonUtility != null && skeletonUtility.skeletonRenderer != null && skeletonUtility.skeletonRenderer.valid; if (!valid) return; skeletonTransform = skeletonUtility.transform; skeletonUtility.OnReset -= HandleOnReset; skeletonUtility.OnReset += HandleOnReset; DoUpdate(); }
public void Reset () { bone = null; cachedTransform = transform; valid = skeletonRenderer != null && skeletonRenderer.valid; if (!valid) return; skeletonTransform = skeletonRenderer.transform; skeletonRenderer.OnReset -= HandleResetRenderer; skeletonRenderer.OnReset += HandleResetRenderer; if(Application.isEditor) DoUpdate(); }
/// <summary> /// Forward kinamatic function /// </summary> /// <param name="bones">The kinamatic chain, array of bones</param> /// <param name="rotation">The rotation to be alplied to the chain</param> /// <param name="i">An index of where in the chain the rotation should starts</param> /// <param name="length">The amount of bones in the chain the kinamatics should be applied to</param> protected void ForwardKinematics(ref Bone[] bones, Quaternion rotation, int i, int length) { for (int j = length; j >= i; j--) { if (j > i) { bones[j].Pos = bones[i].Pos + Vector3.Transform((bones[j].Pos - bones[i].Pos), rotation); } // rotate orientation bones[j].Rotate(rotation); } }
void GetData() { try { this.client.Update(ref this.data); UDP_PACKETS_CODER.UDP_PACKETS_DECODER dec = new UDP_PACKETS_CODER.UDP_PACKETS_DECODER(); dec.Source = this.data; //データ格納 this.List_Humans.Clear(); int MaxofHuman = (int)dec.get_byte(); int NumofHuman = (int)dec.get_byte(); this.List_Humans = new List<Human>(); for (int i = 0; i < NumofHuman; i++) { Human human = new Human(); human.id = i; human.numofBone = (int)dec.get_byte(); human.bones = new Bone[human.numofBone]; for (int j = 0; j < human.numofBone; j++) { Bone bone = new Bone(); bone.dimensiton = (int)dec.get_byte(); bone.position.x = dec.get_float(); bone.position.y = dec.get_float(); bone.position.z = dec.get_float(); bone.quaternion.x = dec.get_float(); bone.quaternion.y = dec.get_float(); bone.quaternion.z = dec.get_float(); bone.quaternion.w = dec.get_float(); bone.IsTracking = dec.get_byte(); human.bones[j] = bone; } this.List_Humans.Add(human); } } catch { Debug.Log("Error:ReceiveData"); } }
public void Initialize () { bone = null; valid = skeletonRenderer != null && skeletonRenderer.valid; if (!valid) return; skeletonTransform = skeletonRenderer.transform; skeletonRenderer.OnRebuild -= HandleRebuildRenderer; skeletonRenderer.OnRebuild += HandleRebuildRenderer; #if UNITY_EDITOR if (Application.isEditor) LateUpdate(); #endif }
/// <summary> /// TODO: /// </summary> /// <param name="Parent"></param> /// <param name="Localvec"></param> public Bone(Bone Parent, Vector3f Localvec, TrackingState ts) { if (Parent != null) { this.Parent = Parent; this.LocalVec = Localvec; } else { this.GlobalVec = LocalVec; } this.trackingstate = ts; }
// An orientational constraint is the twist of the bone around its own direction vector // with respect to its parent // It is defined as an allowed range betwen angles [start,end] // where start != end && 0 < start, end <= 360 // If both start and end is 0 no twist constraint exist /// <summary> /// Checks if the bone has a legal rotation in regards to its parent, returns true if legal, false otherwise. /// The out rotation gives the rotation the bone should be applied to to be inside the twist constraints /// </summary> /// <param name="b">The bone under consideration</param> /// <param name="refBone">The parent of the bone, to check whether the child has legal rotation</param> /// <param name="rotation">The rotation bone b should applie to be inside the constraints</param> /// <returns></returns> public bool CheckOrientationalConstraint(Bone b, Bone refBone, out Quaternion rotation) { if (b.Orientation.Xyz.IsNaN() || refBone.Orientation.Xyz.IsNaN()) { rotation = Quaternion.Identity; return false; } Vector3 thisY = b.GetYAxis(); Quaternion referenceRotation = refBone.Orientation * b.ParentPointer; Vector3 reference = Vector3.Transform( Vector3.Transform(Vector3.UnitZ, referenceRotation), QuaternionHelper2.GetRotationBetween( Vector3.Transform(Vector3.UnitY, referenceRotation), thisY)); float twistAngle = MathHelper.RadiansToDegrees(Vector3.CalculateAngle(reference, b.GetZAxis())); if (Vector3.CalculateAngle(reference, b.GetXAxis()) > Mathf.PI / 2) // b is twisted left with respect to parent twistAngle = 360 - twistAngle; float leftLimit = b.StartTwistLimit; float rightLimit = b.EndTwistLimit; float precision = 0.5f; bool inside = (leftLimit >= rightLimit) ? // The allowed range is on both sides of the reference vector inside = twistAngle - leftLimit >= precision || twistAngle - rightLimit <= precision : inside = twistAngle - leftLimit >= precision && twistAngle - rightLimit <= precision; if (!inside) // not inside constraints { // Create a rotation to the closest limit float toLeft = Math.Min(360 - Math.Abs(twistAngle - leftLimit), Math.Abs(twistAngle - leftLimit)); float toRight = Math.Min(360 - Math.Abs(twistAngle - rightLimit), Math.Abs(twistAngle - rightLimit)); if (toLeft < toRight) { // Anti-clockwise rotation to left limit rotation = Quaternion.FromAxisAngle(thisY, -MathHelper.DegreesToRadians(toLeft)); return true; } else { // Clockwise to right limit rotation = Quaternion.FromAxisAngle(thisY, MathHelper.DegreesToRadians(toRight)); return true; } } rotation = Quaternion.Identity; return false; }
public Derpy(ThingBlock block, ThingDefinition def) : base(block, def) { bodyComponent = ModelComponents[0]; flagComponent = ModelComponents[1]; startLightComponent = ModelComponents[2]; bodyFacing = new Euler(0, 0, 0); neckFacing = new Euler(0, 0, 0); Skeleton skeleton = bodyComponent.Entity.Skeleton; skeleton.BlendMode = SkeletonAnimationBlendMode.ANIMBLEND_CUMULATIVE; blinkState = bodyComponent.Entity.GetAnimationState("Blink2"); blinkState.Enabled = true; blinkState.Loop = true; blinkState.Weight = 1f; blinkState.AddTime(ID); neckBone = skeleton.GetBone("Neck"); neckBone.SetManuallyControlled(true); foreach (var state in bodyComponent.Entity.AllAnimationStates.GetAnimationStateIterator()) { // don't add a blend mask to the blink state because we'll make a different one for it if (state == blinkState) continue; state.CreateBlendMask(skeleton.NumBones); state.SetBlendMaskEntry(neckBone.Handle, 0f); } neckBone.InheritOrientation = false; blinkState.CreateBlendMask(skeleton.NumBones, 0f); ushort handle = skeleton.GetBone("EyeBrowTop.R").Handle; blinkState.SetBlendMaskEntry(handle, 1f); handle = skeleton.GetBone("EyeBrowBottom.R").Handle; blinkState.SetBlendMaskEntry(handle, 1f); handle = skeleton.GetBone("EyeBrowTop.L").Handle; blinkState.SetBlendMaskEntry(handle, 1f); handle = skeleton.GetBone("EyeBrowBottom.L").Handle; blinkState.SetBlendMaskEntry(handle, 1f); LKernel.GetG<AnimationManager>().Add(blinkState); interpNode = LKernel.GetG<SceneManager>().RootSceneNode.CreateChildSceneNode("DerpyInterpNode" + ID, Vector3.ZERO); anim = DerpyAnimation.Hover1; }
public void SetDevice( PlayerDevice device ) { this.device = device; unitstats = gameObject.GetComponent<UnitStats>(); movement = gameObject.GetComponent<Movement>(); skeletonAnimation = gameObject.GetComponentInChildren<SkeletonAnimation>(); skeletonAnimation.state.Event += Event; skeletonAnimation.UpdateBones += UpdateBones; skeletonAnimation.state.End += End; head = gameObject.GetComponentInChildren<SkeletonAnimation>().skeleton.FindBone("head"); hip = gameObject.GetComponentInChildren<SkeletonAnimation>().skeleton.FindBone("body"); weaponmanager = gameObject.GetComponentInChildren<WeaponManager>(); meleemanager = gameObject.GetComponentInChildren<MeleeManager>(); GameObject gameGameObject = GameObject.FindGameObjectWithTag( "Level" ); level = gameGameObject.GetComponent<LevelInfo>(); }
public void Initialize () { bone = null; valid = skeletonRenderer != null && skeletonRenderer.valid; if (!valid) return; skeletonTransform = skeletonRenderer.transform; skeletonRenderer.OnRebuild -= HandleRebuildRenderer; skeletonRenderer.OnRebuild += HandleRebuildRenderer; if (!string.IsNullOrEmpty(boneName)) bone = skeletonRenderer.skeleton.FindBone(boneName); #if UNITY_EDITOR if (Application.isEditor) LateUpdate(); #endif }
public SpringWheel(Bone bone, Unit unit, float size, float stiffness, float damping) { this.bone = bone; this.size = size; this.stiffness = stiffness; this.damping = damping; this.unit = unit; originalBonePosition = bone.Position; originalBoneRotation = bone.Rotation; mesh = new MapObjectAttachedMesh(); mesh.MeshName = "Types/Units/AwesomeAircraft/AwesomeAircraftWheel.mesh"; mesh.ScaleOffset = new Vec3(1, 1, 1); mesh.RotationOffset = Quat.Identity; mesh.PositionOffset = bone.GetDerivedPosition(); unit.Attach(mesh); }
public void Init(Scene scene) { if (!scene.HasAnimations) { return; } Release(); _skeleton = CreateBoneTree(scene.RootNode, null); foreach (var mesh in scene.Meshes) { foreach (var bone in mesh.Bones) { Bone found; if (!_bonesByName.TryGetValue(bone.Name, out found)) continue; var skip = (from t in _bones let bname = bone.Name where t.Name == bname select t).Any(); if (skip) continue; found.Offset = Matrix.Transpose(bone.OffsetMatrix.ToMatrix()); _bones.Add(found); _bonesToIndex[found.Name] = _bones.IndexOf(found); } var mesh1 = mesh; foreach (var bone in _bonesByName.Keys.Where(b => mesh1.Bones.All(b1 => b1.Name != b) && b.StartsWith("Bone"))) { _bonesByName[bone].Offset = _bonesByName[bone].Parent.Offset; _bones.Add(_bonesByName[bone]); _bonesToIndex[bone] = _bones.IndexOf(_bonesByName[bone]); } } ExtractAnimations(scene); const float timestep = 1.0f / 30.0f; for (var i = 0; i < Animations.Count; i++) { SetAnimationIndex(i); var dt = 0.0f; for (var ticks = 0.0f; ticks < Animations[i].Duration; ticks += Animations[i].TicksPerSecond / 30.0f) { dt += timestep; Calculate(dt); var trans = new List<Matrix>(); for (var a = 0; a < _bones.Count; a++) { var rotMat = _bones[a].Offset * _bones[a].GlobalTransform; trans.Add(rotMat); } Animations[i].Transforms.Add(trans); } } Console.WriteLine("Finished loading animations with " + _bones.Count + " bones"); }
public void PairWithSameBonesAndTypeAreEqualsTest() { var boneX = new Bone { A = '1', B = '2' }; var boneY = new Bone { A = '2', B = '3' }; var bonePair1 = new BonePair(boneX, boneY, BonePairType.BA); var bonePair2 = new BonePair(boneX, boneY, BonePairType.BA); var set = new HashSet<BonePair>(); set.Add(bonePair1); set.Add(bonePair2); set.Add(bonePair2); Assert.AreEqual(1, set.Count); Assert.AreEqual(1, boneX.Edges.Count); Assert.AreEqual(1, boneY.Edges.Count); }
public void LateUpdate() { if (skeletonComponent == null) return; if (bone == null) { if (boneName == null) return; bone = skeletonComponent.skeleton.FindBone(boneName); if (bone == null) { Debug.Log("Bone not found: " + boneName, this); return; } } if (transform.parent == skeletonComponent.transform) { transform.localPosition = new Vector3(bone.worldX, bone.worldY, transform.localPosition.z); Vector3 rotation = transform.localRotation.eulerAngles; transform.localRotation = Quaternion.Euler(rotation.x, rotation.y, bone.worldRotation); } else { // Best effort to set this GameObject's transform when it isn't a child of the SkeletonComponent. transform.position = skeletonComponent.transform.TransformPoint(new Vector3(bone.worldX, bone.worldY, transform.position.z)); Vector3 rotation = skeletonComponent.transform.rotation.eulerAngles; transform.rotation = Quaternion.Euler(rotation.x, rotation.y, skeletonComponent.transform.rotation.eulerAngles.z + bone.worldRotation); } }
public static void GetDefaultTargetBone(Animator rig, ref Transform boneTransform, Bone boneID, params string[] boneNames) { GetDefaultBone(rig, ref boneTransform, boneID, boneNames); if (boneTransform == null) { boneTransform = TargetedBone.NewTargetTransform(boneID.ToString()); } }
public static void SetPosition(this Bone bone, Vector3 position) { bone.X = position.x; bone.Y = position.y; }
public static Vector3 GetWorldPosition(this Bone bone, Transform parentTransform) { return(parentTransform.TransformPoint(new Vector3(bone.worldX, bone.worldY))); }
/** Start using this hand model to represent a tracked hand. */ public override void BeginHand() { base.BeginHand(); #if UNITY_EDITOR if (!EditorApplication.isPlaying) { return; } // We also require a material for friction to be able to work. if (_material == null || _material.bounciness != 0.0f || _material.bounceCombine != PhysicMaterialCombine.Minimum) { Debug.LogError("An InteractionBrushHand must have a material with 0 bounciness and a bounceCombine of Minimum. Name: " + gameObject.name); } checkContactState(); #endif _handParent = new GameObject(gameObject.name); _handParent.transform.parent = null; // Prevent hand from moving when you turn your head. _brushBones = new InteractionBrushBone[N_FINGERS * N_ACTIVE_BONES]; for (int fingerIndex = 0; fingerIndex < N_FINGERS; fingerIndex++) { for (int jointIndex = 0; jointIndex < N_ACTIVE_BONES; jointIndex++) { Bone bone = _hand.Fingers[fingerIndex].Bone((Bone.BoneType)(jointIndex + 1)); // +1 to skip first bone. int boneArrayIndex = fingerIndex * N_ACTIVE_BONES + jointIndex; GameObject brushGameObject = new GameObject(gameObject.name, typeof(CapsuleCollider), typeof(Rigidbody), typeof(InteractionBrushBone)); brushGameObject.layer = gameObject.layer; brushGameObject.transform.localScale = Vector3.one; InteractionBrushBone brushBone = brushGameObject.GetComponent <InteractionBrushBone>(); brushBone.manager = _manager; _brushBones[boneArrayIndex] = brushBone; Transform capsuleTransform = brushGameObject.transform; capsuleTransform.SetParent(_handParent.transform, false); CapsuleCollider capsule = brushGameObject.GetComponent <CapsuleCollider>(); capsule.direction = 2; capsule.radius = bone.Width * 0.5f; capsule.height = bone.Length + bone.Width; capsule.material = _material; brushBone.capsuleCollider = capsule; Rigidbody body = brushGameObject.GetComponent <Rigidbody>(); brushBone.capsuleBody = body; body.position = bone.Center.ToVector3(); body.rotation = bone.Rotation.ToQuaternion(); body.freezeRotation = true; body.useGravity = false; body.mass = _perBoneMass; body.collisionDetectionMode = _collisionDetection; brushBone.lastTarget = bone.Center.ToVector3(); } } }
public static Vector2 GetSkeletonSpacePosition(this Bone bone) { return(new Vector2(bone.worldX, bone.worldY)); }
public Vector3 BoneAngles(Bone bone, Vector3 eyePos, Vector3 viewAng) => BoneAngles((int)bone, eyePos, viewAng);
void AddBoneOnData(Bone bone) { _syncPositionList.Add(bone.position); _syncRotationList.Add(bone.rotation); _syncScaleList.Add(bone.scale); }
public ChangeFlags Changed(Bone prev) { return((position != prev.position ? ChangeFlags.Position : 0) | (rotation != prev.rotation ? ChangeFlags.Rotation : 0) | (scale != prev.scale ? ChangeFlags.Scale : 0)); }
// boneNames convention: // 0 = UMA // 1 = MCS / Morph3D // 2 = AutoDesk public static void GetDefaultBone(Animator rig, ref Transform boneTransform, Bone boneId, params string[] boneNames) { GetDefaultBone(rig, ref boneTransform, BoneReference.HumanBodyBone(boneId), boneNames); }
/// <summary> /// Try to apply animation to rig. /// </summary> public void Apply(Rig rig) { bones.Clear(); Vector3Df current; for (int i = 0; i < orientations.Count; i++) { Bone bone = new Bone(); bones.Add(bone); CVector animBone = currentBones[i]; CVector positionVar = animBone.GetVariableByName("position") as CVector; CFloat dtPos = positionVar.GetVariableByName("dt") as CFloat; CUInt32 dataAddrPos = positionVar.GetVariableByName("dataAddr") as CUInt32; CUInt32 dataAddrFallbackPos = positionVar.GetVariableByName("dataAddrFallback") as CUInt32; CUInt16 numframesPos = positionVar.GetVariableByName("numFrames") as CUInt16; if (dtPos != null) { bone.position_dt = dtPos.val; } if (dataAddrPos != null) { bone.position_dataAddr = dataAddrPos.val; } if (dataAddrFallbackPos != null) { bone.position_dataAddrFallback = dataAddrFallbackPos.val; } if (numframesPos != null) { bone.position_numFrames = numframesPos.val; } CVector orientationVar = animBone.GetVariableByName("orientation") as CVector; CFloat dtRot = orientationVar.GetVariableByName("dt") as CFloat; CUInt32 dataAddrRot = orientationVar.GetVariableByName("dataAddr") as CUInt32; CUInt32 dataAddrFallbackRot = orientationVar.GetVariableByName("dataAddrFallback") as CUInt32; CUInt16 numframesRot = orientationVar.GetVariableByName("numFrames") as CUInt16; if (dtRot != null) { bone.rotation_dt = dtRot.val; } if (dataAddrRot != null) { bone.rotation_dataAddr = dataAddrRot.val; } if (dataAddrFallbackRot != null) { bone.rotation_dataAddrFallback = dataAddrFallbackRot.val; } if (numframesRot != null) { bone.rotation_numFrames = numframesRot.val; } CVector scaleVar = animBone.GetVariableByName("scale") as CVector; CFloat dtScale = scaleVar.GetVariableByName("dt") as CFloat; CUInt32 dataAddrScale = scaleVar.GetVariableByName("dataAddr") as CUInt32; CUInt32 dataAddrFallbackScale = scaleVar.GetVariableByName("dataAddrFallback") as CUInt32; CUInt16 numframesScale = scaleVar.GetVariableByName("numFrames") as CUInt16; if (dtScale != null) { bone.scale_dt = dtScale.val; } if (dataAddrScale != null) { bone.scale_dataAddr = dataAddrScale.val; } if (dataAddrFallbackScale != null) { bone.scale_dataAddrFallback = dataAddrFallbackScale.val; } if (numframesScale != null) { bone.scale_numFrames = numframesScale.val; } bone.BoneName = rig.meshSkeleton.names[i]; for (int j = 0; j < positions[i].Count; j++) { bone.positionFrames.Add(new Vector(positions[i][j].X, positions[i][j].Y, positions[i][j].Z)); } for (int j = 0; j < orientations[i].Count; j++) { current = orientationsEuler[i][j]; bone.rotationFrames.Add(orientations[i][j]); } for (int j = 0; j < scales[i].Count; j++) { bone.scaleFrames.Add(new Vector(scales[i][j].X, scales[i][j].Y, scales[i][j].Z)); } } exportData.bones = bones; }
/// <summary> /// クロスシミュレーション計算開始 /// </summary> /// <param name="update"></param> public void UpdateStartSimulation(UpdateTimeManager update) { // 時間 float deltaTime = update.DeltaTime; float physicsDeltaTime = update.PhysicsDeltaTime; float updatePower = update.UpdatePower; float updateDeltaTime = update.UpdateIntervalTime; int ups = update.UpdatePerSecond; // 活動チームが1つ以上ある場合のみ更新 if (Team.ActiveTeamCount > 0) { // 今回フレームの更新回数 int updateCount = Team.CalcMaxUpdateCount(ups, deltaTime, physicsDeltaTime, updateDeltaTime); //Debug.Log($"updateCount:{updateCount} dtime:{deltaTime} pdtime:{physicsDeltaTime} fixedCount:{update.FixedUpdateCount}"); // 風更新 Wind.UpdateWind(); // チームデータ更新、更新回数確定、ワールド移動影響、テレポート Team.PreUpdateTeamData(deltaTime, physicsDeltaTime, updateDeltaTime, ups, updateCount); // ワーカー処理 WarmupWorker(); // ボーン姿勢をパーティクルにコピーする Particle.UpdateBoneToParticle(); // 物理更新前ワーカー処理 //MasterJob = RenderMeshWorker.PreUpdate(MasterJob); // 何もなし MasterJob = VirtualMeshWorker.PreUpdate(MasterJob); // 仮想メッシュをスキニングしワールド姿勢を求める MasterJob = MeshParticleWorker.PreUpdate(MasterJob); // 仮想メッシュ頂点姿勢を連動パーティクルにコピーする //MasterJob = SpringMeshWorker.PreUpdate(MasterJob); // 何もなし //MasterJob = AdjustRotationWorker.PreUpdate(MasterJob); // 何もなし //MasterJob = LineWorker.PreUpdate(MasterJob); // 何もなし //MasterJob = BaseSkinningWorker.PreUpdate(MasterJob); // ベーススキニングによりbasePos/baseRotをスキニング // パーティクルのリセット判定 Particle.UpdateResetParticle(); // 物理更新 for (int i = 0, cnt = updateCount; i < cnt; i++) { UpdatePhysics(updateCount, i, updatePower, updateDeltaTime); } // 物理演算後処理 PostUpdatePhysics(updateDeltaTime); // 物理更新後ワーカー処理 MasterJob = TriangleWorker.PostUpdate(MasterJob); // トライアングル回転調整 MasterJob = LineWorker.PostUpdate(MasterJob); // ラインの回転調整 MasterJob = AdjustRotationWorker.PostUpdate(MasterJob); // パーティクル回転調整(Adjust Rotation) Particle.UpdateParticleToBone(); // パーティクル姿勢をボーン姿勢に書き戻す(ここに挟まないと駄目) MasterJob = SpringMeshWorker.PostUpdate(MasterJob); // メッシュスプリング MasterJob = MeshParticleWorker.PostUpdate(MasterJob); // パーティクル姿勢を仮想メッシュに書き出す MasterJob = VirtualMeshWorker.PostUpdate(MasterJob); // 仮想メッシュ座標書き込み(仮想メッシュトライアングル法線計算) MasterJob = RenderMeshWorker.PostUpdate(MasterJob); // レンダーメッシュ座標書き込み(仮想メッシュからレンダーメッシュ座標計算) // 書き込みボーン姿勢をローカル姿勢に変換する Bone.ConvertWorldToLocal(); // チームデータ後処理 Team.PostUpdateTeamData(); } }
/// <summary> /// ボーン姿勢をトランスフォームに書き込む /// </summary> public void UpdateWriteBone() { // ボーン姿勢をトランスフォームに書き出す Bone.WriteBoneToTransform(manager.IsDelay ? 1 : 0); }
/// <summary> /// Transforms a bone by a position and rotation. /// </summary> public static void Transform(this Bone bone, Vector3 position, Quaternion rotation) { bone.Transform(new LeapTransform(position.ToVector(), rotation.ToLeapQuaternion())); }
/// <summary> /// Transforms a bone to a position and rotation. /// </summary> public static void SetTransform(this Bone bone, Vector3 position, Quaternion rotation) { bone.Transform(Vector3.zero, (rotation * Quaternion.Inverse(bone.Rotation.ToQuaternion()))); bone.Transform(position - bone.PrevJoint.ToVector3(), Quaternion.identity); }
public Vector3 BonePosition(Bone boneId) => this.BonePosition((int)boneId);
public void Interpolate(Bone d0, Bone d1, float t) { position = Vector3.Lerp(d0.position, d1.position, t); rotation = Quaternion.Lerp(d0.rotation, d1.rotation, t); scale = Vector3.Lerp(d0.scale, d1.scale, t); }