void Start() { Time.timeScale = timeScale; var tpos = transform.position; // Default starting positions. nearFoot.worldPos = tpos; nearFoot.worldPos.x -= comfyDistance; nearFoot.worldPosPrev = nearFoot.worldPosNext = nearFoot.worldPos; farFoot.worldPos = tpos; farFoot.worldPos.x += comfyDistance; farFoot.worldPosPrev = farFoot.worldPosNext = farFoot.worldPos; var skeletonAnimation = GetComponent <SkeletonAnimation>(); skeleton = skeletonAnimation.Skeleton; skeletonAnimation.UpdateLocal += UpdateLocal; nearFootBone = skeleton.FindBone(nearBoneName); farFootBone = skeleton.FindBone(farBoneName); nearFoot.lerp = 1f; farFoot.lerp = 1f; }
private void Start() { SkeletonAnimation component = base.GetComponent <SkeletonAnimation>(); Skeleton skeleton = component.Skeleton; this.hipBone = skeleton.FindBone(this.hip); this.headBone = skeleton.FindBone(this.head); this.baseHeadRotation = this.headBone.Rotation; component.UpdateLocal += new UpdateBonesDelegate(this.UpdateLocal); }
public override void _Ready() { //Sets reference to the Node used at ready _targetSkeleton = GetNode <Skeleton>(_targetSkeletonNodePath); _targetNode = GetNode <Spatial>(_targetNodePath); //Gets the bone Ids of the skeleton _boneIds[2] = _targetSkeleton.FindBone(_tipBoneName); _boneIds[1] = _targetSkeleton.GetBoneParent(_boneIds[2]); _boneIds[0] = _targetSkeleton.GetBoneParent(_boneIds[1]); //Calculates the lengths of the bones _boneLengths[0] = _targetSkeleton.GetBoneGlobalPose(_boneIds[0]).origin.DistanceTo(_targetSkeleton.GetBoneGlobalPose(_boneIds[1]).origin); _boneLengths[1] = _targetSkeleton.GetBoneGlobalPose(_boneIds[1]).origin.DistanceTo(_targetSkeleton.GetBoneGlobalPose(_boneIds[2]).origin); //Calculates the Out of range variables _maxChainLength = _boneLengths[0]; _maxChainLength += _boneLengths[1]; _maxChainLength *= _maxChainLength; _minChainLength = Mathf.Abs(_boneLengths[0] - _boneLengths[1]); _minChainLength *= _minChainLength; //Sets the base transforms to what the skeleton starts them as _boneBasePose[0] = _targetSkeleton.GetBonePose(_boneIds[0]); _boneBasePose[1] = _targetSkeleton.GetBonePose(_boneIds[1]); _boneBasePose[2] = _targetSkeleton.GetBonePose(_boneIds[2]); }
private void Start() { _spineAnimator = GetComponent <SpineAnimator>(); ISkeletonAnimation s = _spineAnimator.GetSkeletonAnimation() as ISkeletonAnimation; if (s != null) { s.UpdateLocal += HandleUpdateLocal; } IAnimationStateComponent sa = _spineAnimator.GetSkeletonAnimation() as IAnimationStateComponent; if (sa != null) { this._state = sa.AnimationState; } SetSourceBone(_sourceBoneName); Skeleton skeleton = s.Skeleton; _siblingBones.Clear(); foreach (string bn in _siblingBoneNames) { Bone b = skeleton.FindBone(bn); if (b != null) { _siblingBones.Add(b); } } }
public BoneMorph( Skeleton skeleton, IAnimationManager manager, BoneMorphDefinition definition, ILoggerFactory loggerFactory) : base(definition, loggerFactory) { Ensure.That(skeleton, nameof(skeleton)).IsNotNull(); Ensure.That(manager, nameof(manager)).IsNotNull(); Skeleton = skeleton; AnimationManager = manager; int FindBone(string name) { var index = Skeleton.FindBone(name); if (index == -1) { throw new ArgumentOutOfRangeException( nameof(name), $"The morph '{Definition.Key}' contains a non-existent bone: '{name}'."); } return(index); } BoneIndexes = definition.Bones.Select(FindBone).Freeze(); if (!BoneIndexes.Any()) { throw new ArgumentOutOfRangeException( nameof(definition), $"The morph '{Definition.Key}' does not have any target bones."); } }
protected override void OnInitialize() { base.OnInitialize(); _boneIndex = Skeleton.FindBone(PositionBone); Debug.Assert(_boneIndex != -1, $"Failed to find a bone named '{PositionBone}'."); _initialTransform = Skeleton.GetBoneTransform(_boneIndex); AnimationManager.OnBeforeAdvance .Where(_ => Valid) .Subscribe(_ => OnBeforeAnimation()) .AddTo(this); AnimationManager.OnAdvance .Subscribe(OnAnimation) .AddTo(this); OnActiveStateChange .Where(v => !v && Valid) .Subscribe(_ => ResetAnimations()) .AddTo(this); AnimationManager.Player .GetAnimationList() .Select(AnimationManager.Player.GetAnimation) .Where(a => a.Loop) .ToList() .ForEach(AddTrack); Reset(); }
public Rigidbody GetRigidbody (string boneName) { var bone = skeleton.FindBone(boneName); if (bone == null) return null; if (boneTable.ContainsKey(bone)) return boneTable[bone].GetComponent<Rigidbody>(); return null; }
/// <summary> /// Gets all the bones' absolute matrices from a mesh. /// </summary> /// <param name="Msh">The mesh containing a list of bone (names).</param> /// <param name="Skel">The skeleton with the bones that the names refer to.</param> /// <returns></returns> public Matrix[] GetAllBones(Mesh Msh, Skeleton Skel) { List <Matrix> AllMatrices = new List <Matrix>(); foreach (string Bne in Msh.Bones) { AllMatrices.Add(Skel.Bones[Skel.FindBone(Bne)].AbsoluteMatrix); } return(AllMatrices.ToArray()); }
private int FindBone(string name) { var index = Skeleton.FindBone(name); if (index == -1) { throw new ArgumentOutOfRangeException( nameof(name), $"The morph '{Definition.Key}' contains a non-existent bone: '{name}'."); } return(index); }
protected virtual void PostConstruct() { var listener = this.FindClosestAncestor <IAnimatable>() .Map(a => a.AnimationManager.OnAdvance) .MatchObservable(identity, Observable.Empty <float>) .Where(_ => IsRunning() && IgnoreRotation) .Subscribe(_ => ResetRotation(), this); _listener = Some(listener); _skeleton = GetParentSkeleton(); _tipIndex = _skeleton.FindBone(TipBone); }
public Rigidbody2D GetRigidbody(string boneName) { var bone = skeleton.FindBone(boneName); if (bone == null) { return(null); } if (boneTable.ContainsKey(bone)) { return(boneTable[bone].GetComponent <Rigidbody2D>()); } return(null); }
// Called when the node enters the scene tree for the first time. public override void _Ready() { // get component references from scene tree _camera = GetNode <Camera>("Camera"); _animationTree = GetNode <AnimationTree>("AnimationTree"); _skeleton = GetNode <Skeleton>("Armature/Skeleton"); _headBoneIndex = _skeleton.FindBone("head"); _initialHeadTransform = _skeleton.GetBonePose(_headBoneIndex); _debugCamera = GetNode <Camera>("../DebugCamera"); _targetingRaycast = GetNode <RayCast>("Camera/TargetingRaycast"); // set input stuff (need to move elsewhere eventually) Input.SetMouseMode(Input.MouseMode.Captured); // activate animationTree in case it's not _animationTree.Active = true; // define gravity from params in editor _gravity = (Vector3)PhysicsServer.AreaGetParam(GetWorld().Space, PhysicsServer.AreaParameter.GravityVector) * (float)PhysicsServer.AreaGetParam(GetWorld().Space, PhysicsServer.AreaParameter.Gravity); }
private void InspectSkeleton(Transform transform, int indent) { Bone bone = Target.FindBone(transform.name); GUI.backgroundColor = bone == null ? UltiDraw.LightGrey : UltiDraw.Mustard; using (new EditorGUILayout.HorizontalScope("Box")) { GUI.backgroundColor = Color.white; EditorGUILayout.BeginHorizontal(); for (int i = 0; i < indent; i++) { EditorGUILayout.LabelField("|", GUILayout.Width(20f)); } EditorGUILayout.LabelField("-", GUILayout.Width(20f)); EditorGUILayout.LabelField(transform.name + " " + (bone == null ? string.Empty : "(" + bone.Index.ToString() + ")" + " " + "(" + bone.GetLength() + ")"), GUILayout.Width(250f), GUILayout.Height(20f)); GUILayout.FlexibleSpace(); if (GUIButton("Bone", bone == null ? UltiDraw.White : UltiDraw.DarkGrey, bone == null ? UltiDraw.DarkGrey : UltiDraw.White)) { Transform[] bones = new Transform[Target.Bones.Length]; //for (int i = 0; i < bones.Length; i++) //{ // bones[i] = Target.Bones[i].Transform; //} //if (bone == null) //{ // ArrayExtensions.Add(ref bones, transform); // Target.ExtractSkeleton(bones); //} //else //{ // ArrayExtensions.Remove(ref bones, transform); // Target.ExtractSkeleton(bones); //} } EditorGUILayout.EndHorizontal(); } //for (int i = 0; i < transform.childCount; i++) //{ // InspectSkeleton(transform.GetChild(i), indent + 1); //} }
protected virtual void OnInitialize() { HeadBone = Skeleton.FindBone(_headBone); LeftEyeBone = Skeleton.FindBone(_eyeBoneLeft); RightEyeBone = Skeleton.FindBone(_eyeBoneRight); Debug.Assert(HeadBone != -1, "Failed to find the head bone"); Debug.Assert(LeftEyeBone != -1 || RightEyeBone != -1, "Failed to find the eye bones"); NeckBone = Skeleton.GetBoneParent(HeadBone); Debug.Assert(HeadBone != -1, "Failed to find the neck bone"); RestPose = Skeleton.GetBoneRest(HeadBone); AnimationManager.OnAdvance.Subscribe(OnAnimation).AddTo(this); HeadOrientation = DetectOrientation(HeadBone); NeckOrientation = DetectOrientation(NeckBone); }
public void Apply() { isActive = true; skeleton = skeletonAnim.Skeleton; mix = 1; var ragdollRootBone = skeleton.FindBone(startingBoneName); startingBone = ragdollRootBone; RecursivelyCreateBoneProxies(ragdollRootBone); rootRigidbody = boneTable[ragdollRootBone].GetComponent <Rigidbody2D>(); rootRigidbody.isKinematic = pinStartBone; rootRigidbody.mass = rootMass; List <Collider2D> boneColliders = new List <Collider2D>(); foreach (var pair in boneTable) { var b = pair.Key; var t = pair.Value; Bone parentBone = null; Transform parentTransform = transform; boneColliders.Add(t.GetComponent <Collider2D>()); 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 <Rigidbody2D>(); if (rbParent != null) { var joint = t.gameObject.AddComponent <HingeJoint2D>(); joint.connectedBody = rbParent; Vector3 localPos = parentTransform.InverseTransformPoint(t.position); localPos.x *= 1; joint.connectedAnchor = localPos; joint.GetComponent <Rigidbody2D>().mass = joint.connectedBody.mass * massFalloffFactor; JointAngleLimits2D limits = new JointAngleLimits2D(); limits.min = -rotationLimit; limits.max = rotationLimit; joint.limits = limits; joint.useLimits = true; } } for (int x = 0; x < boneColliders.Count; x++) { for (int y = 0; y < boneColliders.Count; y++) { if (x == y) { continue; } Physics2D.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; }
/* Returns 0 if the bone was not found. */ public Bone FindBone(string boneName) { return(Skeleton.FindBone(boneName)); }
// Window GUI void OnGUI() { bool requireRepaint = false; if (staticLostValues) { Clear(); OnSelectionChange(); staticLostValues = false; requireRepaint = true; } if (SlotsRootLabel == null) { SlotsRootLabel = new GUIContent("Slots", Icons.slotRoot); SkeletonRootLabel = new GUIContent("Skeleton", Icons.skeleton); BoldFoldoutStyle = new GUIStyle(EditorStyles.foldout); BoldFoldoutStyle.fontStyle = FontStyle.Bold; BoldFoldoutStyle.stretchWidth = true; BoldFoldoutStyle.fixedWidth = 0; } EditorGUILayout.Space(); EditorGUI.BeginDisabledGroup(true); EditorGUILayout.ObjectField(SpineInspectorUtility.TempContent("Debug Selection", Icons.spine), skeletonRenderer, typeof(SkeletonRenderer), true); EditorGUI.EndDisabledGroup(); if (skeleton == null || skeletonRenderer == null) { EditorGUILayout.HelpBox("No SkeletonRenderer Spine GameObject selected.", MessageType.Info); return; } if (isPrefab) { EditorGUILayout.HelpBox("SkeletonDebug only debugs Spine GameObjects in the scene.", MessageType.Warning); return; } if (!skeletonRenderer.valid) { EditorGUILayout.HelpBox("Spine Component is invalid. Check SkeletonData Asset.", MessageType.Error); return; } if (activeSkin != skeleton.Skin) { UpdateAttachments(); } scrollPos = EditorGUILayout.BeginScrollView(scrollPos); using (new SpineInspectorUtility.BoxScope(false)) { if (SpineInspectorUtility.CenteredButton(SpineInspectorUtility.TempContent("Skeleton.SetToSetupPose()"))) { skeleton.SetToSetupPose(); requireRepaint = true; } EditorGUI.BeginChangeCheck(); EditorGUILayout.LabelField("Scene View", EditorStyles.boldLabel); using (new SpineInspectorUtility.LabelWidthScope()) { showBoneNames = EditorGUILayout.Toggle("Show Bone Names", showBoneNames); showPaths = EditorGUILayout.Toggle("Show Paths", showPaths); showShapes = EditorGUILayout.Toggle("Show Shapes", showShapes); showConstraints = EditorGUILayout.Toggle("Show Constraints", showConstraints); } requireRepaint |= EditorGUI.EndChangeCheck(); // Skeleton showSkeleton.target = EditorGUILayout.Foldout(showSkeleton.target, SkeletonRootLabel, BoldFoldoutStyle); if (showSkeleton.faded > 0) { using (new SpineInspectorUtility.IndentScope()) { using (new EditorGUILayout.FadeGroupScope(showSkeleton.faded)) { EditorGUI.BeginChangeCheck(); EditorGUI.BeginDisabledGroup(true); FalseDropDown(".Skin", skeleton.Skin != null ? skeletonRenderer.Skeleton.Skin.Name : "<None>", Icons.skin); EditorGUI.EndDisabledGroup(); // Flip skeleton.ScaleX = EditorGUILayout.DelayedFloatField(".ScaleX", skeleton.ScaleX); skeleton.ScaleY = EditorGUILayout.DelayedFloatField(".ScaleY", skeleton.ScaleY); //EditorGUILayout.BeginHorizontal(GUILayout.MaxWidth(160f)); ////EditorGUILayout.LabelField("Scale", GUILayout.Width(EditorGUIUtility.labelWidth - 20f)); //GUILayout.EndHorizontal(); // Color skeleton.SetColor(EditorGUILayout.ColorField(".R .G .B .A", skeleton.GetColor())); requireRepaint |= EditorGUI.EndChangeCheck(); } } } // Bone showInspectBoneTree.target = EditorGUILayout.Foldout(showInspectBoneTree.target, SpineInspectorUtility.TempContent("Bone", Icons.bone), BoldFoldoutStyle); if (showInspectBoneTree.faded > 0) { using (new SpineInspectorUtility.IndentScope()) { using (new EditorGUILayout.FadeGroupScope(showInspectBoneTree.faded)) { showBoneNames = EditorGUILayout.Toggle("Show Bone Names", showBoneNames); if (bpo == null) { bpo = new SerializedObject(this).FindProperty("boneName"); } EditorGUILayout.PropertyField(bpo, SpineInspectorUtility.TempContent("Bone")); if (!string.IsNullOrEmpty(bpo.stringValue)) { if (bone == null || bone.Data.Name != bpo.stringValue) { bone = skeleton.FindBone(bpo.stringValue); } if (bone != null) { using (new EditorGUI.DisabledGroupScope(true)) { var wm = EditorGUIUtility.wideMode; EditorGUIUtility.wideMode = true; EditorGUILayout.Slider("Local Rotation", ViewRound(bone.Rotation), -180f, 180f); EditorGUILayout.Vector2Field("Local Position", RoundVector2(bone.X, bone.Y)); EditorGUILayout.Vector2Field("Local Scale", RoundVector2(bone.ScaleX, bone.ScaleY)); EditorGUILayout.Vector2Field("Local Shear", RoundVector2(bone.ShearX, bone.ShearY)); EditorGUILayout.Space(); var boneParent = bone.Parent; if (boneParent != null) { FalseDropDown("Parent", boneParent.Data.Name, Icons.bone); } const string RoundFormat = "0.##"; var lw = EditorGUIUtility.labelWidth; var fw = EditorGUIUtility.fieldWidth; EditorGUIUtility.labelWidth *= 0.25f; EditorGUIUtility.fieldWidth *= 0.5f; EditorGUILayout.LabelField("LocalToWorld"); EditorGUILayout.BeginHorizontal(); EditorGUILayout.Space(); EditorGUILayout.TextField(".A", bone.A.ToString(RoundFormat)); EditorGUILayout.TextField(".B", bone.B.ToString(RoundFormat)); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.Space(); EditorGUILayout.TextField(".C", bone.C.ToString(RoundFormat)); EditorGUILayout.TextField(".D", bone.D.ToString(RoundFormat)); EditorGUILayout.EndHorizontal(); EditorGUIUtility.labelWidth = lw * 0.5f; EditorGUILayout.BeginHorizontal(); EditorGUILayout.Space(); EditorGUILayout.Space(); EditorGUILayout.TextField(".WorldX", bone.WorldX.ToString(RoundFormat)); EditorGUILayout.TextField(".WorldY", bone.WorldY.ToString(RoundFormat)); EditorGUILayout.EndHorizontal(); EditorGUIUtility.labelWidth = lw; EditorGUIUtility.fieldWidth = fw; EditorGUIUtility.wideMode = wm; } } requireRepaint = true; } else { bone = null; } } } } // Slots int preSlotsIndent = EditorGUI.indentLevel; showSlotsTree.target = EditorGUILayout.Foldout(showSlotsTree.target, SlotsRootLabel, BoldFoldoutStyle); if (showSlotsTree.faded > 0) { using (new EditorGUILayout.FadeGroupScope(showSlotsTree.faded)) { if (SpineInspectorUtility.CenteredButton(SpineInspectorUtility.TempContent("Skeleton.SetSlotsToSetupPose()"))) { skeleton.SetSlotsToSetupPose(); requireRepaint = true; } int baseIndent = EditorGUI.indentLevel; foreach (KeyValuePair <Slot, List <Attachment> > pair in attachmentTable) { Slot slot = pair.Key; using (new EditorGUILayout.HorizontalScope()) { EditorGUI.indentLevel = baseIndent + 1; EditorGUILayout.LabelField(SpineInspectorUtility.TempContent(slot.Data.Name, Icons.slot), GUILayout.ExpandWidth(false)); EditorGUI.BeginChangeCheck(); Color c = EditorGUILayout.ColorField(new Color(slot.R, slot.G, slot.B, slot.A), GUILayout.Width(60)); if (EditorGUI.EndChangeCheck()) { slot.SetColor(c); requireRepaint = true; } } foreach (var attachment in pair.Value) { GUI.contentColor = slot.Attachment == attachment ? Color.white : Color.grey; EditorGUI.indentLevel = baseIndent + 2; var icon = Icons.GetAttachmentIcon(attachment); bool isAttached = (attachment == slot.Attachment); bool swap = EditorGUILayout.ToggleLeft(SpineInspectorUtility.TempContent(attachment.Name, icon), attachment == slot.Attachment); if (isAttached != swap) { slot.Attachment = isAttached ? null : attachment; requireRepaint = true; } GUI.contentColor = Color.white; } } } } EditorGUI.indentLevel = preSlotsIndent; // Constraints const string NoneText = "<none>"; showConstraintsTree.target = EditorGUILayout.Foldout(showConstraintsTree.target, SpineInspectorUtility.TempContent("Constraints", Icons.constraintRoot), BoldFoldoutStyle); if (showConstraintsTree.faded > 0) { using (new SpineInspectorUtility.IndentScope()) { using (new EditorGUILayout.FadeGroupScope(showConstraintsTree.faded)) { const float MixMin = 0f; const float MixMax = 1f; EditorGUI.BeginChangeCheck(); showConstraints = EditorGUILayout.Toggle("Show Constraints", showConstraints); requireRepaint |= EditorGUI.EndChangeCheck(); EditorGUILayout.Space(); EditorGUILayout.LabelField(SpineInspectorUtility.TempContent(string.Format("IK Constraints ({0})", skeleton.IkConstraints.Count), Icons.constraintIK), EditorStyles.boldLabel); using (new SpineInspectorUtility.IndentScope()) { if (skeleton.IkConstraints.Count > 0) { foreach (var c in skeleton.IkConstraints) { EditorGUILayout.LabelField(SpineInspectorUtility.TempContent(c.Data.Name, Icons.constraintIK)); FalseDropDown("Goal", c.Data.Target.Name, Icons.bone, true); using (new EditorGUI.DisabledGroupScope(true)) { EditorGUILayout.Toggle(SpineInspectorUtility.TempContent("Data.Uniform", tooltip: "Uniformly scales a bone when Ik stretches or compresses."), c.Data.Uniform); } EditorGUI.BeginChangeCheck(); c.Mix = EditorGUILayout.Slider("Mix", c.Mix, MixMin, MixMax); c.BendDirection = EditorGUILayout.Toggle(SpineInspectorUtility.TempContent("Bend Clockwise", tooltip: "IkConstraint.BendDirection == 1 if clockwise; -1 if counterclockwise."), c.BendDirection > 0) ? 1 : -1; c.Compress = EditorGUILayout.Toggle(SpineInspectorUtility.TempContent("Compress", tooltip: "Compress single bone IK when the target too close. Not applied when parent bone has nonuniform scale."), c.Compress); c.Stretch = EditorGUILayout.Toggle(SpineInspectorUtility.TempContent("Stretch", tooltip: "Stretch the parent bone when the target is out of range. Not applied when parent bone has nonuniform scale."), c.Stretch); if (EditorGUI.EndChangeCheck()) { requireRepaint = true; } EditorGUILayout.Space(); } } else { EditorGUILayout.LabelField(NoneText); } } EditorGUILayout.LabelField(SpineInspectorUtility.TempContent(string.Format("Transform Constraints ({0})", skeleton.TransformConstraints.Count), Icons.constraintTransform), EditorStyles.boldLabel); using (new SpineInspectorUtility.IndentScope()) { if (skeleton.TransformConstraints.Count > 0) { foreach (var c in skeleton.TransformConstraints) { EditorGUILayout.LabelField(SpineInspectorUtility.TempContent(c.Data.Name, Icons.constraintTransform)); EditorGUI.BeginDisabledGroup(true); FalseDropDown("Goal", c.Data.Target.Name, Icons.bone); EditorGUI.EndDisabledGroup(); EditorGUI.BeginChangeCheck(); c.TranslateMix = EditorGUILayout.Slider("TranslateMix", c.TranslateMix, MixMin, MixMax); c.RotateMix = EditorGUILayout.Slider("RotateMix", c.RotateMix, MixMin, MixMax); c.ScaleMix = EditorGUILayout.Slider("ScaleMix", c.ScaleMix, MixMin, MixMax); c.ShearMix = EditorGUILayout.Slider("ShearMix", c.ShearMix, MixMin, MixMax); if (EditorGUI.EndChangeCheck()) { requireRepaint = true; } EditorGUILayout.Space(); } } else { EditorGUILayout.LabelField(NoneText); } } EditorGUILayout.LabelField(SpineInspectorUtility.TempContent(string.Format("Path Constraints ({0})", skeleton.PathConstraints.Count), Icons.constraintPath), EditorStyles.boldLabel); EditorGUI.BeginChangeCheck(); showPaths = EditorGUILayout.Toggle("Show Paths", showPaths); requireRepaint |= EditorGUI.EndChangeCheck(); using (new SpineInspectorUtility.IndentScope()) { if (skeleton.PathConstraints.Count > 0) { foreach (var c in skeleton.PathConstraints) { EditorGUILayout.LabelField(SpineInspectorUtility.TempContent(c.Data.Name, Icons.constraintPath)); EditorGUI.BeginDisabledGroup(true); FalseDropDown("Path Slot", c.Data.Target.Name, Icons.slot); var activeAttachment = c.Target.Attachment; FalseDropDown("Active Path", activeAttachment != null ? activeAttachment.Name : "<None>", activeAttachment is PathAttachment ? Icons.path : null); EditorGUILayout.LabelField("PositionMode." + c.Data.PositionMode); EditorGUILayout.LabelField("SpacingMode." + c.Data.SpacingMode); EditorGUILayout.LabelField("RotateMode." + c.Data.RotateMode); EditorGUI.EndDisabledGroup(); EditorGUI.BeginChangeCheck(); c.RotateMix = EditorGUILayout.Slider("RotateMix", c.RotateMix, MixMin, MixMax); c.TranslateMix = EditorGUILayout.Slider("TranslateMix", c.TranslateMix, MixMin, MixMax); c.Position = EditorGUILayout.FloatField("Position", c.Position); c.Spacing = EditorGUILayout.FloatField("Spacing", c.Spacing); if (EditorGUI.EndChangeCheck()) { requireRepaint = true; } EditorGUILayout.Space(); } } else { EditorGUILayout.LabelField(NoneText); } } } } } showDrawOrderTree.target = EditorGUILayout.Foldout(showDrawOrderTree.target, SpineInspectorUtility.TempContent("Draw Order and Separators", Icons.slotRoot), BoldFoldoutStyle); //var separatorSlotNamesField = //SpineInspectorUtility.ge if (showDrawOrderTree.faded > 0) { using (new SpineInspectorUtility.IndentScope()) { using (new EditorGUILayout.FadeGroupScope(showDrawOrderTree.faded)) { const string SeparatorString = "------------- v SEPARATOR v -------------"; if (Application.isPlaying) { foreach (var slot in skeleton.DrawOrder) { if (skeletonRenderer.separatorSlots.Contains(slot)) { EditorGUILayout.LabelField(SeparatorString); } EditorGUILayout.LabelField(SpineInspectorUtility.TempContent(slot.Data.Name, Icons.slot), GUILayout.ExpandWidth(false)); } } else { foreach (var slot in skeleton.DrawOrder) { var slotNames = SkeletonRendererInspector.GetSeparatorSlotNames(skeletonRenderer); for (int i = 0, n = slotNames.Length; i < n; i++) { if (string.Equals(slotNames[i], slot.Data.Name, System.StringComparison.Ordinal)) { EditorGUILayout.LabelField(SeparatorString); break; } } EditorGUILayout.LabelField(SpineInspectorUtility.TempContent(slot.Data.Name, Icons.slot), GUILayout.ExpandWidth(false)); } } } } } showEventDataTree.target = EditorGUILayout.Foldout(showEventDataTree.target, SpineInspectorUtility.TempContent("Events", Icons.userEvent), BoldFoldoutStyle); if (showEventDataTree.faded > 0) { using (new SpineInspectorUtility.IndentScope()) { using (new EditorGUILayout.FadeGroupScope(showEventDataTree.faded)) { if (skeleton.Data.Events.Count > 0) { foreach (var e in skeleton.Data.Events) { EditorGUILayout.LabelField(SpineInspectorUtility.TempContent(e.Name, Icons.userEvent)); } } else { EditorGUILayout.LabelField(NoneText); } } } } showDataTree.target = EditorGUILayout.Foldout(showDataTree.target, SpineInspectorUtility.TempContent("Data Counts", Icons.spine), BoldFoldoutStyle); if (showDataTree.faded > 0) { using (new SpineInspectorUtility.IndentScope()) { using (new EditorGUILayout.FadeGroupScope(showDataTree.faded)) { using (new SpineInspectorUtility.LabelWidthScope()) { var skeletonData = skeleton.Data; EditorGUILayout.LabelField(SpineInspectorUtility.TempContent("Bones", Icons.bone, "Skeleton.Data.Bones"), new GUIContent(skeletonData.Bones.Count.ToString())); EditorGUILayout.LabelField(SpineInspectorUtility.TempContent("Slots", Icons.slotRoot, "Skeleton.Data.Slots"), new GUIContent(skeletonData.Slots.Count.ToString())); EditorGUILayout.LabelField(SpineInspectorUtility.TempContent("Skins", Icons.skinsRoot, "Skeleton.Data.Skins"), new GUIContent(skeletonData.Skins.Count.ToString())); EditorGUILayout.LabelField(SpineInspectorUtility.TempContent("Events", Icons.userEvent, "Skeleton.Data.Events"), new GUIContent(skeletonData.Events.Count.ToString())); EditorGUILayout.LabelField(SpineInspectorUtility.TempContent("IK Constraints", Icons.constraintIK, "Skeleton.Data.IkConstraints"), new GUIContent(skeletonData.IkConstraints.Count.ToString())); EditorGUILayout.LabelField(SpineInspectorUtility.TempContent("Transform Constraints", Icons.constraintTransform, "Skeleton.Data.TransformConstraints"), new GUIContent(skeletonData.TransformConstraints.Count.ToString())); EditorGUILayout.LabelField(SpineInspectorUtility.TempContent("Path Constraints", Icons.constraintPath, "Skeleton.Data.PathConstraints"), new GUIContent(skeletonData.PathConstraints.Count.ToString())); } } } } if (IsAnimating(showSlotsTree, showSkeleton, showConstraintsTree, showDrawOrderTree, showEventDataTree, showInspectBoneTree, showDataTree)) { Repaint(); } } if (requireRepaint) { skeletonRenderer.LateUpdate(); Repaint(); SceneView.RepaintAll(); } EditorGUILayout.EndScrollView(); }
/// <summary> /// Renders the different meshes making up this avatar. /// </summary> /// <param name="ViewMatrix">A view matrix.</param> /// <param name="WorldMatrix">A world matrix.</param> /// <param name="ProjectionMatrix">A projection matrix.</param> public void Render(Matrix ViewMatrix, Matrix WorldMatrix, Matrix ProjectionMatrix) { //This sets DepthBufferEnable and DepthBufferWriteEnable. m_Devc.DepthStencilState = DepthStencilState.Default; m_Devc.BlendState = BlendState.AlphaBlend; m_Devc.RasterizerState = RasterizerState.CullNone; if (m_GPURender == false) { // Configure effects m_HeadEffect.World = WorldMatrix; m_HeadEffect.View = ViewMatrix; m_HeadEffect.Projection = ProjectionMatrix; m_HeadEffect.EnableDefaultLighting(); if (HeadTexture != null) { m_HeadEffect.Texture = HeadTexture; m_HeadEffect.TextureEnabled = true; } m_AccessoryEffect.World = WorldMatrix; m_AccessoryEffect.View = ViewMatrix; m_AccessoryEffect.Projection = ProjectionMatrix; m_AccessoryEffect.EnableDefaultLighting(); if (AccessoryTexture != null) { m_AccessoryEffect.Texture = AccessoryTexture; m_AccessoryEffect.TextureEnabled = true; } m_LeftHandEffect.World = WorldMatrix; m_LeftHandEffect.View = ViewMatrix; m_LeftHandEffect.Projection = ProjectionMatrix; m_LeftHandEffect.EnableDefaultLighting(); if (LeftHandTexture != null) { m_LeftHandEffect.Texture = LeftHandTexture; m_LeftHandEffect.TextureEnabled = true; } m_RightHandEffect.World = WorldMatrix; m_RightHandEffect.View = ViewMatrix; m_RightHandEffect.Projection = ProjectionMatrix; m_RightHandEffect.EnableDefaultLighting(); if (RightHandTexture != null) { m_RightHandEffect.Texture = RightHandTexture; m_RightHandEffect.TextureEnabled = true; } m_BodyEffect.World = WorldMatrix; m_BodyEffect.View = ViewMatrix; m_BodyEffect.Projection = ProjectionMatrix; m_BodyEffect.EnableDefaultLighting(); if (BodyTexture != null) { m_BodyEffect.Texture = BodyTexture; m_BodyEffect.TextureEnabled = true; } } else { m_VitaboyShader.Parameters["View"].SetValue(ViewMatrix); m_VitaboyShader.Parameters["Projection"].SetValue(ProjectionMatrix); } if (HeadMesh != null) { if (m_GPURender == false) { foreach (EffectPass Pass in m_HeadEffect.CurrentTechnique.Passes) { Pass.Apply(); foreach (Vector3 Fce in HeadMesh.Faces) { // Draw VertexPositionNormalTexture[] Vertex = new VertexPositionNormalTexture[3]; Vertex[0].Position = HeadMesh.TransformedVertices[(int)Fce.X].Position; Vertex[1].Position = HeadMesh.TransformedVertices[(int)Fce.Y].Position; Vertex[2].Position = HeadMesh.TransformedVertices[(int)Fce.Z].Position; Vertex[0].TextureCoordinate = HeadMesh.TransformedVertices[(int)Fce.X].TextureCoordinate; Vertex[1].TextureCoordinate = HeadMesh.TransformedVertices[(int)Fce.Y].TextureCoordinate; Vertex[2].TextureCoordinate = HeadMesh.TransformedVertices[(int)Fce.Z].TextureCoordinate; Vertex[0].Normal = HeadMesh.TransformedVertices[(int)Fce.X].Normal; Vertex[1].Normal = HeadMesh.TransformedVertices[(int)Fce.Y].Normal; Vertex[2].Normal = HeadMesh.TransformedVertices[(int)Fce.Z].Normal; m_Devc.DrawUserPrimitives(PrimitiveType.TriangleList, Vertex, 0, 1); } TransformVertices(HeadMesh, null, MeshType.Head); } } else { m_VitaboyShader.Parameters["VitaboyTexture"].SetValue(HeadTexture); m_VitaboyShader.Parameters["World"].SetValue(WorldMatrix); m_VitaboyShader.Parameters["ChildBones"].SetValue(GetAllBones(HeadMesh, Skel)); //foreach (EffectPass Pass in m_VitaboyShader.Techniques["TransformHeadTechnique"].Passes) foreach (EffectPass Pass in m_VitaboyShader.Techniques["TransformVerticesTechnique"].Passes) { Pass.Apply(); foreach (Vector3 Fce in HeadMesh.Faces) { VitaboyVertex[] Vertex = new VitaboyVertex[3]; Vertex[0].Position = HeadMesh.RealVertices[(int)Fce.X].Position; Vertex[1].Position = HeadMesh.RealVertices[(int)Fce.Y].Position; Vertex[2].Position = HeadMesh.RealVertices[(int)Fce.Z].Position; Vertex[0].TextureCoordinate = HeadMesh.RealVertices[(int)Fce.X].TextureCoordinate; Vertex[1].TextureCoordinate = HeadMesh.RealVertices[(int)Fce.Y].TextureCoordinate; Vertex[2].TextureCoordinate = HeadMesh.RealVertices[(int)Fce.Z].TextureCoordinate; Vertex[0].Normal = HeadMesh.RealVertices[(int)Fce.X].Normal; Vertex[1].Normal = HeadMesh.RealVertices[(int)Fce.Y].Normal; Vertex[2].Normal = HeadMesh.RealVertices[(int)Fce.Z].Normal; //All the meshes except the body mesh only references one bone. Vertex[0].BoneBinding = 0; Vertex[1].BoneBinding = 0; Vertex[2].BoneBinding = 0; m_Devc.DrawUserPrimitives(PrimitiveType.TriangleList, Vertex, 0, 1); } } } } if (AccessoryMesh != null) { if (m_GPURender == false) { foreach (EffectPass Pass in m_AccessoryEffect.CurrentTechnique.Passes) { Pass.Apply(); foreach (Vector3 Fce in AccessoryMesh.Faces) { // Draw VertexPositionNormalTexture[] Vertex = new VertexPositionNormalTexture[3]; Vertex[0].Position = AccessoryMesh.TransformedVertices[(int)Fce.X].Position; Vertex[1].Position = AccessoryMesh.TransformedVertices[(int)Fce.Y].Position; Vertex[2].Position = AccessoryMesh.TransformedVertices[(int)Fce.Z].Position; Vertex[0].TextureCoordinate = AccessoryMesh.TransformedVertices[(int)Fce.X].TextureCoordinate; Vertex[1].TextureCoordinate = AccessoryMesh.TransformedVertices[(int)Fce.Y].TextureCoordinate; Vertex[2].TextureCoordinate = AccessoryMesh.TransformedVertices[(int)Fce.Z].TextureCoordinate; Vertex[0].Normal = AccessoryMesh.TransformedVertices[(int)Fce.X].Normal; Vertex[1].Normal = AccessoryMesh.TransformedVertices[(int)Fce.Y].Normal; Vertex[2].Normal = AccessoryMesh.TransformedVertices[(int)Fce.Z].Normal; m_Devc.DrawUserPrimitives(PrimitiveType.TriangleList, Vertex, 0, 1); } TransformVertices(AccessoryMesh, null, MeshType.Head); } } else { m_VitaboyShader.Parameters["VitaboyTexture"].SetValue(AccessoryTexture); m_VitaboyShader.Parameters["World"].SetValue(WorldMatrix); m_VitaboyShader.Parameters["ChildBones"].SetValue(GetAllBones(HeadMesh, Skel)); foreach (EffectPass Pass in m_VitaboyShader.Techniques["TransformVerticesTechnique"].Passes) { Pass.Apply(); foreach (Vector3 Fce in AccessoryMesh.Faces) { VitaboyVertex[] Vertex = new VitaboyVertex[3]; Vertex[0].Position = AccessoryMesh.RealVertices[(int)Fce.X].Position; Vertex[1].Position = AccessoryMesh.RealVertices[(int)Fce.Y].Position; Vertex[2].Position = AccessoryMesh.RealVertices[(int)Fce.Z].Position; Vertex[0].TextureCoordinate = AccessoryMesh.RealVertices[(int)Fce.X].TextureCoordinate; Vertex[1].TextureCoordinate = AccessoryMesh.RealVertices[(int)Fce.Y].TextureCoordinate; Vertex[2].TextureCoordinate = AccessoryMesh.RealVertices[(int)Fce.Z].TextureCoordinate; Vertex[0].Normal = AccessoryMesh.RealVertices[(int)Fce.X].Normal; Vertex[1].Normal = AccessoryMesh.RealVertices[(int)Fce.Y].Normal; Vertex[2].Normal = AccessoryMesh.RealVertices[(int)Fce.Z].Normal; Vertex[0].BoneBinding = 0; Vertex[1].BoneBinding = 0; Vertex[2].BoneBinding = 0; m_Devc.DrawUserPrimitives(PrimitiveType.TriangleList, Vertex, 0, 1); } } } } if (BodyMesh != null) { if (m_GPURender == false) { foreach (EffectPass Pass in m_BodyEffect.CurrentTechnique.Passes) { Pass.Apply(); foreach (Vector3 Fce in BodyMesh.Faces) { // Draw VertexPositionNormalTexture[] Vertex = new VertexPositionNormalTexture[3]; Vertex[0].Position = BodyMesh.TransformedVertices[(int)Fce.X].Position; Vertex[1].Position = BodyMesh.TransformedVertices[(int)Fce.Y].Position; Vertex[2].Position = BodyMesh.TransformedVertices[(int)Fce.Z].Position; Vertex[0].TextureCoordinate = BodyMesh.TransformedVertices[(int)Fce.X].TextureCoordinate; Vertex[1].TextureCoordinate = BodyMesh.TransformedVertices[(int)Fce.Y].TextureCoordinate; Vertex[2].TextureCoordinate = BodyMesh.TransformedVertices[(int)Fce.Z].TextureCoordinate; Vertex[0].Normal = BodyMesh.TransformedVertices[(int)Fce.X].Normal; Vertex[1].Normal = BodyMesh.TransformedVertices[(int)Fce.Y].Normal; Vertex[2].Normal = BodyMesh.TransformedVertices[(int)Fce.Z].Normal; m_Devc.DrawUserPrimitives(PrimitiveType.TriangleList, Vertex, 0, 1); } TransformVertices(BodyMesh, Skel.Bones[Skel.FindBone("PELVIS")], MeshType.Body); } } else { CopyBodyVertices(Skel.Bones[Skel.FindBone("PELVIS")]); m_VitaboyShader.Parameters["VitaboyTexture"].SetValue(BodyTexture); m_VitaboyShader.Parameters["World"].SetValue(WorldMatrix); m_VitaboyShader.Parameters["ChildBones"].SetValue(GetAllBones(BodyMesh, Skel)); foreach (EffectPass Pass in m_VitaboyShader.Techniques["TransformVerticesTechnique"].Passes) { foreach (Vector3 Fce in BodyMesh.Faces) { Pass.Apply(); // Draw VitaboyVertex[] Vertex = new VitaboyVertex[3]; Vertex[0].Position = BodyMesh.TransformedVertices[(int)Fce.X].Position; Vertex[1].Position = BodyMesh.TransformedVertices[(int)Fce.Y].Position; Vertex[2].Position = BodyMesh.TransformedVertices[(int)Fce.Z].Position; Vertex[0].TextureCoordinate = BodyMesh.TransformedVertices[(int)Fce.X].TextureCoordinate; Vertex[1].TextureCoordinate = BodyMesh.TransformedVertices[(int)Fce.Y].TextureCoordinate; Vertex[2].TextureCoordinate = BodyMesh.TransformedVertices[(int)Fce.Z].TextureCoordinate; Vertex[0].Normal = BodyMesh.TransformedVertices[(int)Fce.X].Normal; Vertex[1].Normal = BodyMesh.TransformedVertices[(int)Fce.Y].Normal; Vertex[2].Normal = BodyMesh.TransformedVertices[(int)Fce.Z].Normal; Vertex[0].BoneBinding = BodyMesh.TransformedVertices[(int)Fce.X].BoneBinding; Vertex[1].BoneBinding = BodyMesh.TransformedVertices[(int)Fce.Y].BoneBinding; Vertex[2].BoneBinding = BodyMesh.TransformedVertices[(int)Fce.Z].BoneBinding; m_Devc.DrawUserPrimitives(PrimitiveType.TriangleList, Vertex, 0, 1); } } } } if (LeftHandMesh != null) { if (m_GPURender == false) { foreach (EffectPass Pass in m_LeftHandEffect.CurrentTechnique.Passes) { Pass.Apply(); foreach (Vector3 Fce in LeftHandMesh.Faces) { // Draw VertexPositionNormalTexture[] Vertex = new VertexPositionNormalTexture[3]; Vertex[0].Position = LeftHandMesh.TransformedVertices[(int)Fce.X].Position; Vertex[1].Position = LeftHandMesh.TransformedVertices[(int)Fce.Y].Position; Vertex[2].Position = LeftHandMesh.TransformedVertices[(int)Fce.Z].Position; m_Devc.DrawUserPrimitives(PrimitiveType.TriangleList, Vertex, 0, 1); } TransformVertices(LeftHandMesh, null, MeshType.LHand); } } else { m_VitaboyShader.Parameters["VitaboyTexture"].SetValue(LeftHandTexture); m_VitaboyShader.Parameters["World"].SetValue(WorldMatrix); m_VitaboyShader.Parameters["ChildBones"].SetValue(GetAllBones(LeftHandMesh, Skel)); foreach (EffectPass Pass in m_VitaboyShader.Techniques["TransformVerticesTechnique"].Passes) { Pass.Apply(); foreach (Vector3 Fce in LeftHandMesh.Faces) { VitaboyVertex[] Vertex = new VitaboyVertex[3]; Vertex[0].Position = LeftHandMesh.RealVertices[(int)Fce.X].Position; Vertex[1].Position = LeftHandMesh.RealVertices[(int)Fce.Y].Position; Vertex[2].Position = LeftHandMesh.RealVertices[(int)Fce.Z].Position; Vertex[0].TextureCoordinate = LeftHandMesh.RealVertices[(int)Fce.X].TextureCoordinate; Vertex[1].TextureCoordinate = LeftHandMesh.RealVertices[(int)Fce.Y].TextureCoordinate; Vertex[2].TextureCoordinate = LeftHandMesh.RealVertices[(int)Fce.Z].TextureCoordinate; Vertex[0].Normal = LeftHandMesh.RealVertices[(int)Fce.X].Normal; Vertex[1].Normal = LeftHandMesh.RealVertices[(int)Fce.Y].Normal; Vertex[2].Normal = LeftHandMesh.RealVertices[(int)Fce.Z].Normal; //All the meshes except the body mesh only references one bone. Vertex[0].BoneBinding = 0; Vertex[1].BoneBinding = 0; Vertex[2].BoneBinding = 0; m_Devc.DrawUserPrimitives(PrimitiveType.TriangleList, Vertex, 0, 1); } } } } if (RightHandMesh != null) { if (m_GPURender == false) { foreach (EffectPass Pass in m_RightHandEffect.CurrentTechnique.Passes) { Pass.Apply(); foreach (Vector3 Fce in RightHandMesh.Faces) { // Draw VertexPositionNormalTexture[] Vertex = new VertexPositionNormalTexture[3]; Vertex[0].Position = RightHandMesh.TransformedVertices[(int)Fce.X].Position; Vertex[1].Position = RightHandMesh.TransformedVertices[(int)Fce.Y].Position; Vertex[2].Position = RightHandMesh.TransformedVertices[(int)Fce.Z].Position; m_Devc.DrawUserPrimitives(PrimitiveType.TriangleList, Vertex, 0, 1); } TransformVertices(RightHandMesh, null, MeshType.RHand); } } else { m_VitaboyShader.Parameters["VitaboyTexture"].SetValue(RightHandTexture); m_VitaboyShader.Parameters["World"].SetValue(WorldMatrix); m_VitaboyShader.Parameters["ChildBones"].SetValue(GetAllBones(RightHandMesh, Skel)); foreach (EffectPass Pass in m_VitaboyShader.Techniques["TransformVerticesTechnique"].Passes) { Pass.Apply(); foreach (Vector3 Fce in RightHandMesh.Faces) { VitaboyVertex[] Vertex = new VitaboyVertex[3]; Vertex[0].Position = RightHandMesh.RealVertices[(int)Fce.X].Position; Vertex[1].Position = RightHandMesh.RealVertices[(int)Fce.Y].Position; Vertex[2].Position = RightHandMesh.RealVertices[(int)Fce.Z].Position; Vertex[0].TextureCoordinate = RightHandMesh.RealVertices[(int)Fce.X].TextureCoordinate; Vertex[1].TextureCoordinate = RightHandMesh.RealVertices[(int)Fce.Y].TextureCoordinate; Vertex[2].TextureCoordinate = RightHandMesh.RealVertices[(int)Fce.Z].TextureCoordinate; Vertex[0].Normal = RightHandMesh.RealVertices[(int)Fce.X].Normal; Vertex[1].Normal = RightHandMesh.RealVertices[(int)Fce.Y].Normal; Vertex[2].Normal = RightHandMesh.RealVertices[(int)Fce.Z].Normal; //All the meshes except the body mesh only references one bone. Vertex[0].BoneBinding = 0; Vertex[1].BoneBinding = 0; Vertex[2].BoneBinding = 0; m_Devc.DrawUserPrimitives(PrimitiveType.TriangleList, Vertex, 0, 1); } } } } }
/// <summary> /// Renders the different meshes making up this avatar. /// </summary> /// <param name="ViewMatrix">A view matrix.</param> /// <param name="WorldMatrix">A world matrix.</param> /// <param name="ProjectionMatrix">A projection matrix.</param> public void Render(Matrix ViewMatrix, Matrix WorldMatrix, Matrix ProjectionMatrix) { //This sets DepthBufferEnable and DepthBufferWriteEnable. m_Devc.DepthStencilState = DepthStencilState.Default; m_Devc.BlendState = BlendState.AlphaBlend; m_Devc.RasterizerState = RasterizerState.CullNone; if (m_GPURender == false) { // Configure effects m_HeadEffect.World = WorldMatrix; m_HeadEffect.View = ViewMatrix; m_HeadEffect.Projection = ProjectionMatrix; m_HeadEffect.EnableDefaultLighting(); } else { m_VitaboyShader.Parameters["View"].SetValue(ViewMatrix); m_VitaboyShader.Parameters["Projection"].SetValue(ProjectionMatrix); } if (HeadTexture != null) { if (m_GPURender == false) { m_HeadEffect.Texture = HeadTexture; m_HeadEffect.TextureEnabled = true; } else { m_VitaboyShader.Parameters["HeadTexture"].SetValue(HeadTexture); } } if (m_GPURender == false) { m_AccessoryEffect.World = WorldMatrix; m_AccessoryEffect.View = ViewMatrix; m_AccessoryEffect.Projection = ProjectionMatrix; m_AccessoryEffect.EnableDefaultLighting(); } if (AccessoryTexture != null) { if (m_GPURender == false) { m_AccessoryEffect.Texture = AccessoryTexture; m_AccessoryEffect.TextureEnabled = true; } else { m_VitaboyShader.Parameters["AccessoryTexture"].SetValue(AccessoryTexture); } } m_BodyEffect.World = WorldMatrix; m_BodyEffect.View = ViewMatrix; m_BodyEffect.Projection = ProjectionMatrix; m_BodyEffect.EnableDefaultLighting(); if (m_BodyEffect != null) { m_BodyEffect.Texture = BodyTexture; m_BodyEffect.TextureEnabled = true; } // Configure effects m_LeftHandEffect.World = WorldMatrix; m_LeftHandEffect.View = ViewMatrix; m_LeftHandEffect.Projection = ProjectionMatrix; m_LeftHandEffect.EnableDefaultLighting(); if (LeftHandTexture != null) { if (m_GPURender == false) { m_LeftHandEffect.Texture = LeftHandTexture; m_LeftHandEffect.TextureEnabled = true; } else { m_VitaboyShader.Parameters["LeftHandTexture"].SetValue(LeftHandTexture); } } if (RightHandTexture != null) { if (m_GPURender) { m_VitaboyShader.Parameters["RightHandTexture"].SetValue(RightHandTexture); } } if (HeadMesh != null) { if (m_GPURender == false) { foreach (EffectPass Pass in m_HeadEffect.CurrentTechnique.Passes) { Pass.Apply(); foreach (Vector3 Fce in HeadMesh.Faces) { // Draw VertexPositionNormalTexture[] Vertex = new VertexPositionNormalTexture[3]; Vertex[0] = HeadMesh.TransformedVertices[(int)Fce.X]; Vertex[1] = HeadMesh.TransformedVertices[(int)Fce.Y]; Vertex[2] = HeadMesh.TransformedVertices[(int)Fce.Z]; Vertex[0].TextureCoordinate = HeadMesh.TransformedVertices[(int)Fce.X].TextureCoordinate; Vertex[1].TextureCoordinate = HeadMesh.TransformedVertices[(int)Fce.Y].TextureCoordinate; Vertex[2].TextureCoordinate = HeadMesh.TransformedVertices[(int)Fce.Z].TextureCoordinate; Vertex[0].Normal = HeadMesh.TransformedVertices[(int)Fce.X].Normal; Vertex[1].Normal = HeadMesh.TransformedVertices[(int)Fce.Y].Normal; Vertex[2].Normal = HeadMesh.TransformedVertices[(int)Fce.Z].Normal; m_Devc.DrawUserPrimitives(PrimitiveType.TriangleList, Vertex, 0, 1); } TransformVertices(HeadMesh, null, MeshType.Head); } } else { m_VitaboyShader.Parameters["World"].SetValue(WorldMatrix * Skel.Bones[Skel.FindBone("HEAD")].AbsoluteMatrix); foreach (EffectPass Pass in m_VitaboyShader.Techniques["TransformHeadTechnique"].Passes) { Pass.Apply(); foreach (Vector3 Fce in HeadMesh.Faces) { VertexPositionNormalTexture[] Vertex = new VertexPositionNormalTexture[3]; Vertex[0] = HeadMesh.RealVertices[(int)Fce.X]; Vertex[1] = HeadMesh.RealVertices[(int)Fce.Y]; Vertex[2] = HeadMesh.RealVertices[(int)Fce.Z]; Vertex[0].TextureCoordinate = HeadMesh.RealVertices[(int)Fce.X].TextureCoordinate; Vertex[1].TextureCoordinate = HeadMesh.RealVertices[(int)Fce.Y].TextureCoordinate; Vertex[2].TextureCoordinate = HeadMesh.RealVertices[(int)Fce.Z].TextureCoordinate; Vertex[0].Normal = HeadMesh.RealVertices[(int)Fce.X].Normal; Vertex[1].Normal = HeadMesh.RealVertices[(int)Fce.Y].Normal; Vertex[2].Normal = HeadMesh.RealVertices[(int)Fce.Z].Normal; m_Devc.DrawUserPrimitives(PrimitiveType.TriangleList, Vertex, 0, 1); } } } } if (AccessoryMesh != null) { if (m_GPURender == false) { foreach (EffectPass Pass in m_AccessoryEffect.CurrentTechnique.Passes) { Pass.Apply(); foreach (Vector3 Fce in AccessoryMesh.Faces) { // Draw VertexPositionNormalTexture[] Vertex = new VertexPositionNormalTexture[3]; Vertex[0] = AccessoryMesh.TransformedVertices[(int)Fce.X]; Vertex[1] = AccessoryMesh.TransformedVertices[(int)Fce.Y]; Vertex[2] = AccessoryMesh.TransformedVertices[(int)Fce.Z]; Vertex[0].TextureCoordinate = AccessoryMesh.TransformedVertices[(int)Fce.X].TextureCoordinate; Vertex[1].TextureCoordinate = AccessoryMesh.TransformedVertices[(int)Fce.Y].TextureCoordinate; Vertex[2].TextureCoordinate = AccessoryMesh.TransformedVertices[(int)Fce.Z].TextureCoordinate; Vertex[0].Normal = AccessoryMesh.TransformedVertices[(int)Fce.X].Normal; Vertex[1].Normal = AccessoryMesh.TransformedVertices[(int)Fce.Y].Normal; Vertex[2].Normal = AccessoryMesh.TransformedVertices[(int)Fce.Z].Normal; m_Devc.DrawUserPrimitives(PrimitiveType.TriangleList, Vertex, 0, 1); } TransformVertices(AccessoryMesh, null, MeshType.Head); } } else { m_VitaboyShader.Parameters["World"].SetValue(WorldMatrix * Skel.Bones[Skel.FindBone("HEAD")].AbsoluteMatrix); foreach (EffectPass Pass in m_VitaboyShader.Techniques["TransformAccessoryTechnique"].Passes) { Pass.Apply(); foreach (Vector3 Fce in AccessoryMesh.Faces) { VertexPositionNormalTexture[] Vertex = new VertexPositionNormalTexture[3]; Vertex[0] = AccessoryMesh.RealVertices[(int)Fce.X]; Vertex[1] = AccessoryMesh.RealVertices[(int)Fce.Y]; Vertex[2] = AccessoryMesh.RealVertices[(int)Fce.Z]; Vertex[0].TextureCoordinate = AccessoryMesh.RealVertices[(int)Fce.X].TextureCoordinate; Vertex[1].TextureCoordinate = AccessoryMesh.RealVertices[(int)Fce.Y].TextureCoordinate; Vertex[2].TextureCoordinate = AccessoryMesh.RealVertices[(int)Fce.Z].TextureCoordinate; Vertex[0].Normal = AccessoryMesh.RealVertices[(int)Fce.X].Normal; Vertex[1].Normal = AccessoryMesh.RealVertices[(int)Fce.Y].Normal; Vertex[2].Normal = AccessoryMesh.RealVertices[(int)Fce.Z].Normal; m_Devc.DrawUserPrimitives(PrimitiveType.TriangleList, Vertex, 0, 1); } } } } if (BodyMesh != null) { foreach (EffectPass Pass in m_BodyEffect.CurrentTechnique.Passes) { Pass.Apply(); foreach (Vector3 Fce in BodyMesh.Faces) { // Draw VertexPositionNormalTexture[] Vertex = new VertexPositionNormalTexture[3]; Vertex[0] = BodyMesh.TransformedVertices[(int)Fce.X]; Vertex[1] = BodyMesh.TransformedVertices[(int)Fce.Y]; Vertex[2] = BodyMesh.TransformedVertices[(int)Fce.Z]; Vertex[0].TextureCoordinate = BodyMesh.TransformedVertices[(int)Fce.X].TextureCoordinate; Vertex[1].TextureCoordinate = BodyMesh.TransformedVertices[(int)Fce.Y].TextureCoordinate; Vertex[2].TextureCoordinate = BodyMesh.TransformedVertices[(int)Fce.Z].TextureCoordinate; Vertex[0].Normal = BodyMesh.TransformedVertices[(int)Fce.X].Normal; Vertex[1].Normal = BodyMesh.TransformedVertices[(int)Fce.Y].Normal; Vertex[2].Normal = BodyMesh.TransformedVertices[(int)Fce.Z].Normal; m_Devc.DrawUserPrimitives(PrimitiveType.TriangleList, Vertex, 0, 1); } TransformVertices(BodyMesh, Skel.Bones[Skel.FindBone("PELVIS")], MeshType.Body); } } if (LeftHandMesh != null) { if (m_GPURender == false) { foreach (EffectPass Pass in m_LeftHandEffect.CurrentTechnique.Passes) { Pass.Apply(); foreach (Vector3 Fce in LeftHandMesh.Faces) { // Draw VertexPositionNormalTexture[] Vertex = new VertexPositionNormalTexture[3]; Vertex[0] = LeftHandMesh.TransformedVertices[(int)Fce.X]; Vertex[1] = LeftHandMesh.TransformedVertices[(int)Fce.Y]; Vertex[2] = LeftHandMesh.TransformedVertices[(int)Fce.Z]; m_Devc.DrawUserPrimitives(PrimitiveType.TriangleList, Vertex, 0, 1); } TransformVertices(LeftHandMesh, null, MeshType.LHand); } } else { m_VitaboyShader.Parameters["World"].SetValue(WorldMatrix * Skel.Bones[Skel.FindBone("L_HAND")].AbsoluteMatrix); foreach (EffectPass Pass in m_VitaboyShader.Techniques["TransformLeftHandTechnique"].Passes) { Pass.Apply(); foreach (Vector3 Fce in LeftHandMesh.Faces) { VertexPositionNormalTexture[] Vertex = new VertexPositionNormalTexture[3]; Vertex[0] = LeftHandMesh.RealVertices[(int)Fce.X]; Vertex[1] = LeftHandMesh.RealVertices[(int)Fce.Y]; Vertex[2] = LeftHandMesh.RealVertices[(int)Fce.Z]; Vertex[0].TextureCoordinate = LeftHandMesh.RealVertices[(int)Fce.X].TextureCoordinate; Vertex[1].TextureCoordinate = LeftHandMesh.RealVertices[(int)Fce.Y].TextureCoordinate; Vertex[2].TextureCoordinate = LeftHandMesh.RealVertices[(int)Fce.Z].TextureCoordinate; Vertex[0].Normal = LeftHandMesh.RealVertices[(int)Fce.X].Normal; Vertex[1].Normal = LeftHandMesh.RealVertices[(int)Fce.Y].Normal; Vertex[2].Normal = LeftHandMesh.RealVertices[(int)Fce.Z].Normal; m_Devc.DrawUserPrimitives(PrimitiveType.TriangleList, Vertex, 0, 1); } } } } if (RightHandMesh != null) { if (m_GPURender == false) { foreach (EffectPass Pass in m_LeftHandEffect.CurrentTechnique.Passes) { Pass.Apply(); foreach (Vector3 Fce in RightHandMesh.Faces) { // Draw VertexPositionNormalTexture[] Vertex = new VertexPositionNormalTexture[3]; Vertex[0] = RightHandMesh.TransformedVertices[(int)Fce.X]; Vertex[1] = RightHandMesh.TransformedVertices[(int)Fce.Y]; Vertex[2] = RightHandMesh.TransformedVertices[(int)Fce.Z]; m_Devc.DrawUserPrimitives(PrimitiveType.TriangleList, Vertex, 0, 1); } TransformVertices(RightHandMesh, null, MeshType.RHand); } } else { m_VitaboyShader.Parameters["World"].SetValue(WorldMatrix * Skel.Bones[Skel.FindBone("R_HAND")].AbsoluteMatrix); foreach (EffectPass Pass in m_VitaboyShader.Techniques["TransformRightHandTechnique"].Passes) { Pass.Apply(); foreach (Vector3 Fce in RightHandMesh.Faces) { VertexPositionNormalTexture[] Vertex = new VertexPositionNormalTexture[3]; Vertex[0] = RightHandMesh.RealVertices[(int)Fce.X]; Vertex[1] = RightHandMesh.RealVertices[(int)Fce.Y]; Vertex[2] = RightHandMesh.RealVertices[(int)Fce.Z]; Vertex[0].TextureCoordinate = RightHandMesh.RealVertices[(int)Fce.X].TextureCoordinate; Vertex[1].TextureCoordinate = RightHandMesh.RealVertices[(int)Fce.Y].TextureCoordinate; Vertex[2].TextureCoordinate = RightHandMesh.RealVertices[(int)Fce.Z].TextureCoordinate; Vertex[0].Normal = RightHandMesh.RealVertices[(int)Fce.X].Normal; Vertex[1].Normal = RightHandMesh.RealVertices[(int)Fce.Y].Normal; Vertex[2].Normal = RightHandMesh.RealVertices[(int)Fce.Z].Normal; m_Devc.DrawUserPrimitives(PrimitiveType.TriangleList, Vertex, 0, 1); } } } } }
public void DoUpdate() { if (!this.valid) { this.Reset(); return; } Skeleton skeleton = this.skeletonUtility.skeletonRenderer.skeleton; if (this.bone == null) { if (this.boneName == null || this.boneName.get_Length() == 0) { return; } this.bone = skeleton.FindBone(this.boneName); if (this.bone == null) { Debug.LogError("Bone not found: " + this.boneName, this); return; } } float num = (!(skeleton.flipX ^ skeleton.flipY)) ? 1f : -1f; float num2 = 0f; if (this.flip && (this.flipX || this.flipX != this.bone.flipX) && this.bone.parent != null) { num2 = this.bone.parent.WorldRotation * -2f; } if (this.mode == SkeletonUtilityBone.Mode.Follow) { if (this.flip) { this.flipX = this.bone.flipX; } if (this.position) { this.cachedTransform.set_localPosition(new Vector3(this.bone.x, this.bone.y, 0f)); } if (this.rotation) { if (this.bone.Data.InheritRotation) { if (this.bone.FlipX) { this.cachedTransform.set_localRotation(Quaternion.Euler(0f, 180f, this.bone.rotationIK - num2)); } else { this.cachedTransform.set_localRotation(Quaternion.Euler(0f, 0f, this.bone.rotationIK)); } } else { Vector3 eulerAngles = this.skeletonTransform.get_rotation().get_eulerAngles(); this.cachedTransform.set_rotation(Quaternion.Euler(eulerAngles.x, eulerAngles.y, this.skeletonTransform.get_rotation().get_eulerAngles().z + this.bone.worldRotation * num)); } } if (this.scale) { this.cachedTransform.set_localScale(new Vector3(this.bone.scaleX, this.bone.scaleY, (float)((!this.bone.worldFlipX) ? 1 : -1))); this.nonUniformScaleWarning = (this.bone.scaleX != this.bone.scaleY); } } else if (this.mode == SkeletonUtilityBone.Mode.Override) { if (this.transformLerpComplete) { return; } if (this.parentReference == null) { if (this.position) { this.bone.x = Mathf.Lerp(this.bone.x, this.cachedTransform.get_localPosition().x, this.overrideAlpha); this.bone.y = Mathf.Lerp(this.bone.y, this.cachedTransform.get_localPosition().y, this.overrideAlpha); } if (this.rotation) { float num3 = Mathf.LerpAngle(this.bone.Rotation, this.cachedTransform.get_localRotation().get_eulerAngles().z, this.overrideAlpha) + num2; if (this.flip) { if (!this.flipX && this.bone.flipX) { num3 -= num2; } if (num3 >= 360f) { num3 -= 360f; } else if (num3 <= -360f) { num3 += 360f; } } this.bone.Rotation = num3; this.bone.RotationIK = num3; } if (this.scale) { this.bone.scaleX = Mathf.Lerp(this.bone.scaleX, this.cachedTransform.get_localScale().x, this.overrideAlpha); this.bone.scaleY = Mathf.Lerp(this.bone.scaleY, this.cachedTransform.get_localScale().y, this.overrideAlpha); this.nonUniformScaleWarning = (this.bone.scaleX != this.bone.scaleY); } if (this.flip) { this.bone.flipX = this.flipX; } } else { if (this.transformLerpComplete) { return; } if (this.position) { Vector3 vector = this.parentReference.InverseTransformPoint(this.cachedTransform.get_position()); this.bone.x = Mathf.Lerp(this.bone.x, vector.x, this.overrideAlpha); this.bone.y = Mathf.Lerp(this.bone.y, vector.y, this.overrideAlpha); } if (this.rotation) { float num4 = Mathf.LerpAngle(this.bone.Rotation, Quaternion.LookRotation((!this.flipX) ? Vector3.get_forward() : (Vector3.get_forward() * -1f), this.parentReference.InverseTransformDirection(this.cachedTransform.get_up())).get_eulerAngles().z, this.overrideAlpha) + num2; if (this.flip) { if (!this.flipX && this.bone.flipX) { num4 -= num2; } if (num4 >= 360f) { num4 -= 360f; } else if (num4 <= -360f) { num4 += 360f; } } this.bone.Rotation = num4; this.bone.RotationIK = num4; } if (this.scale) { this.bone.scaleX = Mathf.Lerp(this.bone.scaleX, this.cachedTransform.get_localScale().x, this.overrideAlpha); this.bone.scaleY = Mathf.Lerp(this.bone.scaleY, this.cachedTransform.get_localScale().y, this.overrideAlpha); this.nonUniformScaleWarning = (this.bone.scaleX != this.bone.scaleY); } if (this.flip) { this.bone.flipX = this.flipX; } } this.transformLerpComplete = true; } }
/// <summary>Instantiates the ragdoll simulation and applies its transforms to the skeleton.</summary> public void Apply() { isActive = true; mix = 1; Bone startingBone = this.StartingBone = skeleton.FindBone(startingBoneName); RecursivelyCreateBoneProxies(startingBone); RootRigidbody = boneTable[startingBone].GetComponent <Rigidbody2D>(); RootRigidbody.isKinematic = pinStartBone; RootRigidbody.mass = rootMass; var boneColliders = new List <Collider2D>(); foreach (var pair in boneTable) { var b = pair.Key; var t = pair.Value; Transform parentTransform; boneColliders.Add(t.GetComponent <Collider2D>()); if (b == startingBone) { ragdollRoot = new GameObject("RagdollRoot").transform; ragdollRoot.SetParent(transform, false); if (b == skeleton.RootBone) // RagdollRoot is skeleton root's parent, thus the skeleton's scale and position. { ragdollRoot.localPosition = new Vector3(skeleton.X, skeleton.Y, 0); ragdollRoot.localRotation = (skeleton.ScaleX < 0) ? Quaternion.Euler(0, 0, 180.0f) : Quaternion.identity; } else { ragdollRoot.localPosition = new Vector3(b.Parent.WorldX, b.Parent.WorldY, 0); ragdollRoot.localRotation = Quaternion.Euler(0, 0, b.Parent.WorldRotationX - b.Parent.ShearX); } parentTransform = ragdollRoot; rootOffset = t.position - transform.position; } else { parentTransform = boneTable[b.Parent]; } // Add joint and attach to parent. var rbParent = parentTransform.GetComponent <Rigidbody2D>(); if (rbParent != null) { var joint = t.gameObject.AddComponent <HingeJoint2D>(); joint.connectedBody = rbParent; Vector3 localPos = parentTransform.InverseTransformPoint(t.position); joint.connectedAnchor = localPos; joint.GetComponent <Rigidbody2D>().mass = joint.connectedBody.mass * massFalloffFactor; #if HINGE_JOINT_2019_BEHAVIOUR float referenceAngle = (rbParent.transform.eulerAngles.z - t.eulerAngles.z + 360f) % 360f; float minAngle = referenceAngle - rotationLimit; float maxAngle = referenceAngle + rotationLimit; if (maxAngle > 180f) { minAngle -= 360f; maxAngle -= 360f; } #else float minAngle = -rotationLimit; float maxAngle = rotationLimit; #endif joint.limits = new JointAngleLimits2D { min = minAngle, max = maxAngle }; joint.useLimits = true; } } // Ignore collisions among bones. for (int x = 0; x < boneColliders.Count; x++) { for (int y = 0; y < boneColliders.Count; y++) { if (x == y) { continue; } Physics2D.IgnoreCollision(boneColliders[x], boneColliders[y]); } } // Destroy existing override-mode SkeletonUtility bones. var utilityBones = GetComponentsInChildren <SkeletonUtilityBone>(); if (utilityBones.Length > 0) { var 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); } } // Disable skeleton constraints. if (disableIK) { var ikConstraints = skeleton.IkConstraints; for (int i = 0, n = ikConstraints.Count; i < n; i++) { ikConstraints.Items[i].Mix = 0; } } if (disableOtherConstraints) { var transformConstraints = skeleton.TransformConstraints; for (int i = 0, n = transformConstraints.Count; i < n; i++) { transformConstraints.Items[i].MixRotate = 0; transformConstraints.Items[i].MixScaleX = 0; transformConstraints.Items[i].MixScaleY = 0; transformConstraints.Items[i].MixShearY = 0; transformConstraints.Items[i].MixX = 0; transformConstraints.Items[i].MixY = 0; } var pathConstraints = skeleton.PathConstraints; for (int i = 0, n = pathConstraints.Count; i < n; i++) { pathConstraints.Items[i].MixRotate = 0; pathConstraints.Items[i].MixX = 0; pathConstraints.Items[i].MixY = 0; } } targetSkeletonComponent.UpdateWorld += UpdateSpineSkeleton; }
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.forward; 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; }
public void DoUpdate() { if (!this.valid) { this.Reset(); return; } Skeleton skeleton = this.skeletonUtility.skeletonRenderer.skeleton; if (this.bone == null) { if (this.boneName == null || this.boneName.Length == 0) { return; } this.bone = skeleton.FindBone(this.boneName); if (this.bone == null) { return; } } float num = (!(skeleton.flipX ^ skeleton.flipY)) ? 1f : -1f; if (this.mode == SkeletonUtilityBone.Mode.Follow) { if (this.position) { this.cachedTransform.localPosition = new Vector3(this.bone.x, this.bone.y, 0f); } if (this.rotation) { if (this.bone.Data.InheritRotation) { this.cachedTransform.localRotation = Quaternion.Euler(0f, 0f, this.bone.AppliedRotation); } else { Vector3 eulerAngles = this.skeletonTransform.rotation.eulerAngles; this.cachedTransform.rotation = Quaternion.Euler(eulerAngles.x, eulerAngles.y, eulerAngles.z + this.bone.WorldRotationX * num); } } if (this.scale) { this.cachedTransform.localScale = new Vector3(this.bone.scaleX, this.bone.scaleY, this.bone.WorldSignX); this.disableInheritScaleWarning = !this.bone.data.inheritScale; } } else if (this.mode == SkeletonUtilityBone.Mode.Override) { if (this.transformLerpComplete) { return; } if (this.parentReference == null) { if (this.position) { this.bone.x = Mathf.Lerp(this.bone.x, this.cachedTransform.localPosition.x, this.overrideAlpha); this.bone.y = Mathf.Lerp(this.bone.y, this.cachedTransform.localPosition.y, this.overrideAlpha); } if (this.rotation) { float appliedRotation = Mathf.LerpAngle(this.bone.Rotation, this.cachedTransform.localRotation.eulerAngles.z, this.overrideAlpha); this.bone.Rotation = appliedRotation; this.bone.AppliedRotation = appliedRotation; } if (this.scale) { this.bone.scaleX = Mathf.Lerp(this.bone.scaleX, this.cachedTransform.localScale.x, this.overrideAlpha); this.bone.scaleY = Mathf.Lerp(this.bone.scaleY, this.cachedTransform.localScale.y, this.overrideAlpha); } } else { if (this.transformLerpComplete) { return; } if (this.position) { Vector3 vector = this.parentReference.InverseTransformPoint(this.cachedTransform.position); this.bone.x = Mathf.Lerp(this.bone.x, vector.x, this.overrideAlpha); this.bone.y = Mathf.Lerp(this.bone.y, vector.y, this.overrideAlpha); } if (this.rotation) { float appliedRotation2 = Mathf.LerpAngle(this.bone.Rotation, Quaternion.LookRotation((!this.flipX) ? Vector3.forward : (Vector3.forward * -1f), this.parentReference.InverseTransformDirection(this.cachedTransform.up)).eulerAngles.z, this.overrideAlpha); this.bone.Rotation = appliedRotation2; this.bone.AppliedRotation = appliedRotation2; } if (this.scale) { this.bone.scaleX = Mathf.Lerp(this.bone.scaleX, this.cachedTransform.localScale.x, this.overrideAlpha); this.bone.scaleY = Mathf.Lerp(this.bone.scaleY, this.cachedTransform.localScale.y, this.overrideAlpha); } this.disableInheritScaleWarning = !this.bone.data.inheritScale; } this.transformLerpComplete = true; } }
public void AnimationEvent(AnimationState state, int trackIndex, Event e) { float Amount = e.Float; if (Amount == 0) // so it can be the float or the int { Amount = (float)e.Int; } if (((Engine.instance.DebugView.Flags & Physics.DebugViewFlags.Game) == Physics.DebugViewFlags.Game)) { Engine.instance.AddDebugText(e.Data.Name, Position, Color.White); } if (e.Data.Name.Contains("particle_")) { string ParticleName = e.Data.Name.Replace("particle_", ""); Vector2 Pos = Position; if (!string.IsNullOrEmpty(e.String)) { Pos = SpineFunc.GetBonePosition(this, e.String.Replace("\n", "")); } Particles.GameParticles[ParticleName].Trigger(Pos, -1); if (ParticleName == "spark") { Engine.instance.PlaySound("FX_M_Systems_Spark", this, Pos); } else if (ParticleName == "_new_explosion_rock") { Engine.instance.PlaySound("FX_Hazard_Crusher_Impact", this, Pos); } } else if (e.Data.Name == "shake_fluid") { if (Engine.instance.FluidSimulation != null) { Engine.instance.FluidSimulation.ShakeParticles(this, e.Int, e.Float); } } else if (e.Data.Name == "lunge") { Character.IsLunging = e.Int == 1; } else if (e.Data.Name == "push") { if (Character != null && !Character.Player && NoAirControlTime > Engine.instance.Time) { return; } bool WasIgnore = Body.IgnoreForces; float multiplier = Amount > 0 ? ForwardPushForceMult : BackwardPushForceMult; Vector2 dir = FocusDistance; if (CustomPushDirection != Vector2.Zero) { dir = CustomPushDirection; } Body.IgnoreForces = false; if (FocusDistance != Vector2.Zero) { Body.ApplyForce(Amount * Body.Mass * 400 * Vector2.Normalize(dir) * multiplier); } Body.IgnoreForces = WasIgnore; CustomPushDirection = Vector2.Zero; } else if (e.Data.Name == "melee") { if (ActiveMeleeWeapon != null) { if (Amount > 0) { if (!ActiveMeleeWeapon.MeleeStrike) { if (!string.IsNullOrEmpty(ActiveMeleeWeapon.GameObjectClass.AttackSound)) { Engine.instance.PlaySound(ActiveMeleeWeapon.GameObjectClass.AttackSound, this); } } if (ActiveMeleeWeapon.MeleeHits != null) { ActiveMeleeWeapon.MeleeHits.Clear(); } ActiveMeleeWeapon.MeleeStrike = true; Body.IgnoreForces = true; } else if (Amount < 0) { ActiveMeleeWeapon.MeleeStrike = false; ActiveMeleeWeapon = null; Body.IgnoreForces = false; } } else { Engine.instance.AddDevConsoleText("No active melee weapon for melee attack"); } /* * if (Amount > 0) * { * ActiveMeleeWeapon.MeleeHits.Clear(); * ActiveMeleeWeapon.MeleeStrike = true; * Body.IgnoreForces = true; * } * else * { * ActiveMeleeWeapon.MeleeStrike = false; * ActiveMeleeWeapon = null; * Body.IgnoreForces = false; * }*/ } else if (e.Data.Name == "blow_left_door" && Amount > 0) { Vector2 force = new Vector2((float)Math.Cos(Rotation), (float)Math.Sin(Rotation)) * -30000f; GameObject gib = LevelObjects.CreateGib(this, skeleton.FindSlot("door_l_box"), force, MiscFunc.RandomBetween(-0.5f, 0.5f), "Gibs\\gib", 3f); gib.Body.LinearDamping = 4f; gib.Body.AngularDamping = 2f; } else if (e.Data.Name == "blow_right_door" && Amount > 0) { Vector2 force = new Vector2((float)Math.Cos(Rotation), (float)Math.Sin(Rotation)) * 30000f; GameObject gib = LevelObjects.CreateGib(this, skeleton.FindSlot("door_r_box"), force, MiscFunc.RandomBetween(-0.5f, 0.5f), "Gibs\\gib", 3f); gib.Body.LinearDamping = 4f; gib.Body.AngularDamping = 2f; //Stations.GetSupplyPodContents(LastInteractBy, GameObject); } else if (e.Data.Name == "getkey") { //Stations.GetTerminalContents(LastInteractBy, GameObject); } else if (skeleton.Data.Name == "core" && e.Data.Name == "fire") { Engine.instance.PlaySound("FX_M_Core_Shot", this); if (GameObject.CoreCanFire && SystemsFunc.SystemHasHealth(GameObject)) { foreach (string muzzleName in GameObject.CoreMuzzleNames) { if (GameObject.Class.SystemLevel == 1) { if (GameObject.CoreLevel1FireSwitch && (muzzleName == "muzzle01" || muzzleName == "muzzle03")) { continue; } if (!GameObject.CoreLevel1FireSwitch && (muzzleName == "muzzle02" || muzzleName == "muzzle04")) { continue; } } Vector2 position = SpineFunc.GetBonePosition(GameObject, muzzleName); float rotation = SpineFunc.GetBoneRotation(GameObject, muzzleName); Vector2 direction = new Vector2((float)Math.Cos(rotation), (float)Math.Sin(rotation)); GameObject projectile = WeaponsFunc.CreateProjectile(this, position, "EnemyWeapons\\core_p", direction); projectile.Class.IgnoreSystemCollision = true; projectile.Class.IgnoreSystemHealthProxyCollision = true; } GameObject.CoreLevel1FireSwitch = !GameObject.CoreLevel1FireSwitch; } } else if (skeleton.Data.Name == "alarm") { if (e.Data.Name == "fire") { GameObject.AlarmCanFire = true; } else if (e.Data.Name == "fire_stop") { GameObject.AlarmCanFire = false; } else if (e.Data.Name == "vulnerable") { foreach (GameObject child in GameObject.Children) { child.ImmuneToExplosions = false; child.ImmuneToProjectiles = false; } } else if (e.Data.Name == "invulnerable") { foreach (GameObject child in GameObject.Children) { child.ImmuneToExplosions = true; child.ImmuneToProjectiles = true; } } } else if (skeleton.Data.Name == "sentry_new" || skeleton.Data.Name == "sentry_flakk") { if (e.Data.Name == "start_tracking") { GameObject.SentryTrackingAllowed = true; GameObject.SentryStartChargingAt = (float)Engine.instance.Time + 1f; } else if (e.Data.Name == "stop_tracking") { GameObject.SentryTrackingAllowed = false; } else if (e.Data.Name == "fire") { GameObject.SentryIsCharging = false; GameObject.SentryIsFiring = true; GameObject.SentryStopFiringAt = (float)Engine.instance.Time + 2f; } else if (e.Data.Name == "invulnerable") { foreach (GameObject child in GameObject.Children) { child.ImmuneToExplosions = true; child.ImmuneToProjectiles = true; } } else if (e.Data.Name == "vulnerable") { foreach (GameObject child in GameObject.Children) { child.ImmuneToExplosions = false; child.ImmuneToProjectiles = false; } } } else if (skeleton.Data.Name == "factory" || skeleton.Data.Name == "factory_advanced") { if (e.Data.Name == "invulnerable") { if (!OffScreen) { Engine.instance.PlaySound("FX_M_DroneFactory_Close", this); } foreach (GameObject child in GameObject.Children) { child.ImmuneToExplosions = true; child.ImmuneToProjectiles = true; } } else if (e.Data.Name == "vulnerable") { if (!OffScreen) { Engine.instance.PlaySound("FX_M_DroneFactory_Open", this); } foreach (GameObject child in GameObject.Children) { child.ImmuneToExplosions = false; child.ImmuneToProjectiles = false; } } else if (e.Data.Name == "fire") { GameObject.FactoryCanFire = true; } } else if (skeleton.Data.Name == "repair_system") { if (e.Data.Name == "fire_01") { GameObject.RepairCurrentMuzzleIndex = 0; GameObject.RepairFireDrone = true; } else if (e.Data.Name == "fire_02") { GameObject.RepairCurrentMuzzleIndex = 1; GameObject.RepairFireDrone = true; } else if (e.Data.Name == "fire_03") { GameObject.RepairCurrentMuzzleIndex = 2; GameObject.RepairFireDrone = true; } else if (e.Data.Name == "fire_04") { GameObject.RepairCurrentMuzzleIndex = 3; GameObject.RepairFireDrone = true; } else if (e.Data.Name == "fire_05") { GameObject.RepairCurrentMuzzleIndex = 4; GameObject.RepairFireDrone = true; } else if (e.Data.Name == "stop_regen") { GameObject.Children[0].HealthRegenEnabled = false; } else if (e.Data.Name == "start_regen") { if (GameObject.Class.SystemLevel >= 2 && GameObject.Class.Type != GameObjectType.SYSTEM_REPAIR) { GameObject.Children[0].HealthRegenEnabled = true; } } } else if (skeleton.Data.Name == "flak_turret") { if (e.Data.Name == "fire_left") { Character.FlakCurrentMuzzle = "left_muzzle"; WeaponsFunc.Fire(this, Inventory.Items[InventorySlot.WEAPON_1]); } else if (e.Data.Name == "fire_right") { Character.FlakCurrentMuzzle = "right_muzzle"; WeaponsFunc.Fire(this, Inventory.Items[InventorySlot.WEAPON_1]); } } /*else if (skeleton.Data.Name == "tanker") * { * if (e.Data.Name == "enable_fire") * { * if (Character.AIState == AIState.PATROL) * { * if (Character.Class.HazardType == HazardType.MINES) * { * GameObject mine = new GameObject(); * * mine.Classfile = "Hazards\\mine"; * mine.Position = SpineFunc.GetBonePosition(this, "muzzle"); * Engine.instance.AddEntity(mine); * mine.Team = 1; * } * } * } * }*/ else if (skeleton.Data.Name == "heavy_sentinel") { if (e.Data.Name == "fire") { WeaponsFunc.Fire(this, Inventory.Items[InventorySlot.WEAPON_1]); } else if (e.Data.Name == "activate_shield") { WeaponsFunc.ActivateShield(Character, Inventory.Items[InventorySlot.WEAPON_2]); } else if (e.Data.Name == "deactivate_shield") { WeaponsFunc.DeactivateShield(Inventory.Items[InventorySlot.WEAPON_2].ShieldObject); } } else if (skeleton.Data.Name == "tattletale") { //if (Character.CanAlarm && e.Data.Name == "alarm") // CFunc.CharacterAlarm(Character, Character.FindCharacter, Position); } else if (skeleton.Data.Name == "seeker_launcher") { if (e.Data.Name == "close") { Engine.instance.PlaySound("Combat_M_SeekerLauncher_Close", this); } else if (e.Data.Name == "open") { Engine.instance.PlaySound("Combat_M_SeekerLauncher_Open", this); } else { SwarmManager manager = SwarmManager.Instance; string muzzleName = null; Vector2 spawnPos; Character spawn; if (e.Data.Name == "fire01") { muzzleName = "muzzle01"; } else if (e.Data.Name == "fire02") { muzzleName = "muzzle02"; } else if (e.Data.Name == "fire03") { muzzleName = "muzzle03"; } else if (e.Data.Name == "fire04") { muzzleName = "muzzle04"; } if (Character.OwnerSwarmGroup == null) { Character.OwnerSwarmGroup = manager.CreateGroup(50); } spawnPos = SpineFunc.GetBonePosition(this, muzzleName); spawn = new Character(); spawn.Position = spawnPos; spawn.Classname = "Bee"; Engine.instance.AddEntity(spawn); manager.AddEntityToGroup(Character.OwnerSwarmGroup, spawn); Particles.GameParticles["_new_muzzle_enemyblaster"].Trigger(spawnPos); Engine.instance.PlaySound("FX_M_RepairSystem_Drones_Eject", spawn, spawnPos); } } else if (skeleton.Data.Name == "bully") { if (e.Data.Name == "fire") { WeaponsFunc.Fire(this, Inventory.Items[InventorySlot.WEAPON_1]); } } else if (skeleton.Data.Name == "stasis_gel_arm") { if (e.Data.Name == "start_fire") { GameObject.IsSpraying = true; } else if (e.Data.Name == "stop_fire") { GameObject.IsSpraying = false; } } else if (skeleton.Data.Name == "cage_generator") { if (e.Data.Name == "activate") { GameObject.CageActive = true; } else if (e.Data.Name == "deactivate") { GameObject.CageActive = false; } } else if (Type == EntityType.CHARACTER) { if (Character.Class.Type == CharacterType.Leviathan) { int OnscreenSpawned = 0; foreach (Character Spawned in Character.CharsSpawned) { if (!Spawned.OffScreen) { OnscreenSpawned++; } } if (e.Data.Name == "enable_fire" && OnscreenSpawned < 3) { Character spawn = new Character(); spawn.Classname = Character.Class.CharToSpawn; spawn.Position = SpineFunc.GetBonePosition(this, "muzzle"); Engine.instance.AddEntity(spawn); Character.CharsSpawned.Add(spawn); } } else if (Character.Class.Type == CharacterType.Blacksuit) { if (e.Data.Name == "start_fire") { Character.IsFiring = true; } else if (e.Data.Name == "stop_fire") { Character.IsFiring = false; } else if (e.Data.Name == "activate_shield" && Character.State != CharacterState.DEATH_ANIM) { ItemsFunc.Use(this, Inventory.Items[InventorySlot.ABILITY]); Character.CurrentShield.ShieldObject.NextAbility = float.MaxValue; Character.IsSecondaryFiring = true; } else if (e.Data.Name == "deactivate_shield" && Character.CurrentShield != null) { Character.CurrentShield.ShieldObject.NextAbility = 0.1f; Character.IsSecondaryFiring = false; } } else if (Character.Class.Type == CharacterType.Viper) { if (e.Data.Name == "fire") { WeaponsFunc.Fire(this, Inventory.Items[InventorySlot.WEAPON_1]); } } } else if (Type == EntityType.OBJECT) { if (GameObject.Class.Type == GameObjectType.CRUSHER_SINGLE) { GameObject child = GameObject.Children[0]; if (e.Data.Name == "enable") { child.CrusherPistonEnabled = true; } else { child.CrusherPistonEnabled = false; } } else if (GameObject.Class.Type == GameObjectType.CRUSHER_TRIPLE) { GameObject child = GameObject.Children[1 + e.Int]; if (e.Data.Name == "enable") { child.CrusherPistonEnabled = true; } else { child.CrusherPistonEnabled = false; } } else if (GameObject.Class.Type == GameObjectType.INCINERATOR_STATIONARY) { if (e.Data.Name == "is_open") { GameObject.IsOpen = true; } else if (e.Data.Name == "is_closing") { GameObject.IsOpen = false; } } else if (GameObject.Class.Type == GameObjectType.INCINERATOR_FORK || GameObject.Class.Type == GameObjectType.INCINERATOR_WHEEL) { if (e.Data.Name == "fireSound") { Engine.instance.PlaySound("FX_Hazard_Incinerator_Fire", GameObject); } else if (e.Data.Name == "fire") { GameObject.IsSpraying = true; } else if (e.Data.Name == "fire_stop") { GameObject.IsSpraying = false; } } else if (GameObject.Class.Type == GameObjectType.SAWBLADE_WALLARM) { if (e.Data.Name == "fire") { Vector2 debrisPos = SpineFunc.GetBonePosition(this, "muzzle"); float debrisAngle = SpineFunc.GetBoneRotation(this, "muzzle"); GameObject debris; float debrisSpeed = MiscFunc.RandomBetween(6f, 9f); debrisAngle += MiscFunc.RandomBetween(-0.4f, 0.4f); //if (GameObject.FlippedHorizontal) // debrisAngle = -debrisAngle + MathHelper.Pi; //if (GameObject.FlipVertical) // debrisAngle = -debrisAngle; debris = SpineFunc.CreateDebris(this, skeleton.FindBone("muzzle"), MiscFunc.mRandom.Next(99999999), Vector2.Zero, 1f, 1f, false, "Hazards\\sawblade_debris"); debris.Body.LinearVelocity = new Vector2((float)Math.Cos(debrisAngle), (float)Math.Sin(debrisAngle)) * debrisSpeed; } } else if (GameObject.Class.Type == GameObjectType.SYSTEM_SHUFFLE) { if (e.Data.Name == "vulnerable") { GameObject weakObj = Children[0]; weakObj.ImmuneToExplosions = false; weakObj.ImmuneToFluid = false; weakObj.ImmuneToProjectiles = false; weakObj.ImmuneToSlowExplosions = false; } else if (e.Data.Name == "invulnerable") { GameObject weakObj = Children[0]; weakObj.ImmuneToExplosions = true; weakObj.ImmuneToFluid = true; weakObj.ImmuneToProjectiles = true; weakObj.ImmuneToSlowExplosions = true; } } else if (GameObject.Class.Type == GameObjectType.PLAYERSHIP_PLAYER) { if (e.Data.Name == "teleport_effect") { GameObject refraction = new GameObject(); GameObject light = new GameObject(); refraction.Classfile = "Refractions\\shockwave_2"; refraction.Position = Position; Engine.instance.AddEntity(refraction); light.Classfile = "Lights\\death_teleport_light"; light.Position = Position; Engine.instance.AddEntity(light); } } else if (GameObject.Class.Type == GameObjectType.BEE_HIVE) { if (e.Data.Name == "fire") { Vector2 basePos = SpineFunc.GetBonePosition(this, "spawn"); Vector2 spawnPos = basePos + MiscFunc.RandomInUnitCircle() * 10f; Character bee = new Character(); if (GameObject.HiveCurrentGroup == null) { GameObject.HiveCurrentGroup = SwarmManager.Instance.CreateGroup(5); } bee.Classname = "Bee"; bee.Position = spawnPos; Engine.instance.AddEntity(bee); SwarmManager.Instance.AddEntityToGroup(GameObject.HiveCurrentGroup, bee); } } } }
/// <summary>Instantiates the ragdoll simulation and applies its transforms to the skeleton.</summary> public void Apply() { isActive = true; mix = 1; Bone startingBone = this.StartingBone = skeleton.FindBone(startingBoneName); RecursivelyCreateBoneProxies(startingBone); RootRigidbody = boneTable[startingBone].GetComponent <Rigidbody2D>(); RootRigidbody.isKinematic = pinStartBone; RootRigidbody.mass = rootMass; var boneColliders = new List <Collider2D>(); foreach (var pair in boneTable) { var b = pair.Key; var t = pair.Value; Transform parentTransform; boneColliders.Add(t.GetComponent <Collider2D>()); if (b == startingBone) { ragdollRoot = new GameObject("RagdollRoot").transform; ragdollRoot.SetParent(transform, false); if (b == skeleton.RootBone) // RagdollRoot is skeleton root. { ragdollRoot.localPosition = new Vector3(b.WorldX, b.WorldY, 0); ragdollRoot.localRotation = Quaternion.Euler(0, 0, GetPropagatedRotation(b)); } else { ragdollRoot.localPosition = new Vector3(b.Parent.WorldX, b.Parent.WorldY, 0); ragdollRoot.localRotation = Quaternion.Euler(0, 0, GetPropagatedRotation(b.Parent)); } parentTransform = ragdollRoot; rootOffset = t.position - transform.position; } else { parentTransform = boneTable[b.Parent]; } // Add joint and attach to parent. var rbParent = parentTransform.GetComponent <Rigidbody2D>(); if (rbParent != null) { var joint = t.gameObject.AddComponent <HingeJoint2D>(); joint.connectedBody = rbParent; Vector3 localPos = parentTransform.InverseTransformPoint(t.position); joint.connectedAnchor = localPos; joint.GetComponent <Rigidbody2D>().mass = joint.connectedBody.mass * massFalloffFactor; joint.limits = new JointAngleLimits2D { min = -rotationLimit, max = rotationLimit }; joint.useLimits = true; } } // Ignore collisions among bones. for (int x = 0; x < boneColliders.Count; x++) { for (int y = 0; y < boneColliders.Count; y++) { if (x == y) { continue; } Physics2D.IgnoreCollision(boneColliders[x], boneColliders[y]); } } // Destroy existing override-mode SkeletonUtility bones. var utilityBones = GetComponentsInChildren <SkeletonUtilityBone>(); if (utilityBones.Length > 0) { var 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); } } // Disable skeleton constraints. if (disableIK) { var ikConstraints = skeleton.IkConstraints; for (int i = 0, n = ikConstraints.Count; i < n; i++) { ikConstraints.Items[i].mix = 0; } } if (disableOtherConstraints) { var transformConstraints = skeleton.transformConstraints; for (int i = 0, n = transformConstraints.Count; i < n; i++) { transformConstraints.Items[i].rotateMix = 0; transformConstraints.Items[i].scaleMix = 0; transformConstraints.Items[i].shearMix = 0; transformConstraints.Items[i].translateMix = 0; } var pathConstraints = skeleton.pathConstraints; for (int i = 0, n = pathConstraints.Count; i < n; i++) { pathConstraints.Items[i].rotateMix = 0; pathConstraints.Items[i].translateMix = 0; } } targetSkeletonComponent.UpdateWorld += UpdateSpineSkeleton; }
public void Apply() { isActive = true; mix = 1f; Bone bone2 = StartingBone = skeleton.FindBone(startingBoneName); Bone bone3 = bone2; RecursivelyCreateBoneProxies(bone3); RootRigidbody = boneTable[bone3].GetComponent <Rigidbody2D>(); RootRigidbody.isKinematic = pinStartBone; RootRigidbody.mass = rootMass; List <Collider2D> list = new List <Collider2D>(); foreach (KeyValuePair <Bone, Transform> item in boneTable) { Bone key = item.Key; Transform value = item.Value; list.Add(value.GetComponent <Collider2D>()); Transform transform; if (key == bone3) { ragdollRoot = new GameObject("RagdollRoot").transform; ragdollRoot.SetParent(base.transform, worldPositionStays: false); if (key == skeleton.RootBone) { ragdollRoot.localPosition = new Vector3(key.WorldX, key.WorldY, 0f); ragdollRoot.localRotation = Quaternion.Euler(0f, 0f, GetPropagatedRotation(key)); } else { ragdollRoot.localPosition = new Vector3(key.Parent.WorldX, key.Parent.WorldY, 0f); ragdollRoot.localRotation = Quaternion.Euler(0f, 0f, GetPropagatedRotation(key.Parent)); } transform = ragdollRoot; rootOffset = value.position - base.transform.position; } else { transform = boneTable[key.Parent]; } Rigidbody2D component = transform.GetComponent <Rigidbody2D>(); if (component != null) { HingeJoint2D hingeJoint2D = value.gameObject.AddComponent <HingeJoint2D>(); hingeJoint2D.connectedBody = component; Vector3 v = transform.InverseTransformPoint(value.position); hingeJoint2D.connectedAnchor = v; hingeJoint2D.GetComponent <Rigidbody2D>().mass = hingeJoint2D.connectedBody.mass * massFalloffFactor; hingeJoint2D.limits = new JointAngleLimits2D { min = 0f - rotationLimit, max = rotationLimit }; hingeJoint2D.useLimits = true; } } for (int i = 0; i < list.Count; i++) { for (int j = 0; j < list.Count; j++) { if (i != j) { Physics2D.IgnoreCollision(list[i], list[j]); } } } SkeletonUtilityBone[] componentsInChildren = GetComponentsInChildren <SkeletonUtilityBone>(); if (componentsInChildren.Length > 0) { List <string> list2 = new List <string>(); SkeletonUtilityBone[] array = componentsInChildren; foreach (SkeletonUtilityBone skeletonUtilityBone in array) { if (skeletonUtilityBone.mode == SkeletonUtilityBone.Mode.Override) { list2.Add(skeletonUtilityBone.gameObject.name); UnityEngine.Object.Destroy(skeletonUtilityBone.gameObject); } } if (list2.Count > 0) { string text = "Destroyed Utility Bones: "; for (int l = 0; l < list2.Count; l++) { text += list2[l]; if (l != list2.Count - 1) { text += ","; } } UnityEngine.Debug.LogWarning(text); } } if (disableIK) { ExposedList <IkConstraint> ikConstraints = skeleton.IkConstraints; int m = 0; for (int count = ikConstraints.Count; m < count; m++) { ikConstraints.Items[m].mix = 0f; } } if (disableOtherConstraints) { ExposedList <TransformConstraint> transformConstraints = skeleton.transformConstraints; int n = 0; for (int count2 = transformConstraints.Count; n < count2; n++) { transformConstraints.Items[n].rotateMix = 0f; transformConstraints.Items[n].scaleMix = 0f; transformConstraints.Items[n].shearMix = 0f; transformConstraints.Items[n].translateMix = 0f; } ExposedList <PathConstraint> pathConstraints = skeleton.pathConstraints; int num = 0; for (int count3 = pathConstraints.Count; num < count3; num++) { pathConstraints.Items[num].rotateMix = 0f; pathConstraints.Items[num].translateMix = 0f; } } targetSkeletonComponent.UpdateWorld += UpdateSpineSkeleton; }
public void DoUpdate(UpdatePhase phase) { if (!this.valid) { this.Reset(); } else { Skeleton skeleton = this.skeletonUtility.skeletonRenderer.skeleton; if (this.bone == null) { if (string.IsNullOrEmpty(this.boneName)) { return; } this.bone = skeleton.FindBone(this.boneName); if (this.bone == null) { Debug.LogError("Bone not found: " + this.boneName, this); return; } } Transform cachedTransform = this.cachedTransform; float num = !(skeleton.flipX ^ skeleton.flipY) ? 1f : -1f; if (this.mode != Mode.Follow) { if ((this.mode == Mode.Override) && !this.transformLerpComplete) { if (this.parentReference == null) { if (this.position) { Vector3 localPosition = cachedTransform.localPosition; this.bone.x = Mathf.Lerp(this.bone.x, localPosition.x, this.overrideAlpha); this.bone.y = Mathf.Lerp(this.bone.y, localPosition.y, this.overrideAlpha); } if (this.rotation) { float num2 = Mathf.LerpAngle(this.bone.Rotation, cachedTransform.localRotation.eulerAngles.z, this.overrideAlpha); this.bone.Rotation = num2; this.bone.AppliedRotation = num2; } if (this.scale) { Vector3 localScale = cachedTransform.localScale; this.bone.scaleX = Mathf.Lerp(this.bone.scaleX, localScale.x, this.overrideAlpha); this.bone.scaleY = Mathf.Lerp(this.bone.scaleY, localScale.y, this.overrideAlpha); } } else { if (this.transformLerpComplete) { return; } if (this.position) { Vector3 vector6 = this.parentReference.InverseTransformPoint(cachedTransform.position); this.bone.x = Mathf.Lerp(this.bone.x, vector6.x, this.overrideAlpha); this.bone.y = Mathf.Lerp(this.bone.y, vector6.y, this.overrideAlpha); } if (this.rotation) { float num3 = Mathf.LerpAngle(this.bone.Rotation, Quaternion.LookRotation(Vector3.forward, this.parentReference.InverseTransformDirection(cachedTransform.up)).eulerAngles.z, this.overrideAlpha); this.bone.Rotation = num3; this.bone.AppliedRotation = num3; } if (this.scale) { Vector3 localScale = cachedTransform.localScale; this.bone.scaleX = Mathf.Lerp(this.bone.scaleX, localScale.x, this.overrideAlpha); this.bone.scaleY = Mathf.Lerp(this.bone.scaleY, localScale.y, this.overrideAlpha); } this.incompatibleTransformMode = BoneTransformModeIncompatible(this.bone); } this.transformLerpComplete = true; } } else if (phase != UpdatePhase.Local) { if (((phase == UpdatePhase.World) || (phase == UpdatePhase.Complete)) && !this.bone.appliedValid) { this.bone.UpdateAppliedTransform(); if (this.position) { cachedTransform.localPosition = new Vector3(this.bone.ax, this.bone.ay, 0f); } if (this.rotation) { if (this.bone.data.transformMode.InheritsRotation()) { cachedTransform.localRotation = Quaternion.Euler(0f, 0f, this.bone.AppliedRotation); } else { Vector3 eulerAngles = this.skeletonTransform.rotation.eulerAngles; cachedTransform.rotation = Quaternion.Euler(eulerAngles.x, eulerAngles.y, eulerAngles.z + (this.bone.WorldRotationX * num)); } } if (this.scale) { cachedTransform.localScale = new Vector3(this.bone.ascaleX, this.bone.ascaleY, 1f); this.incompatibleTransformMode = BoneTransformModeIncompatible(this.bone); } } } else { if (this.position) { cachedTransform.localPosition = new Vector3(this.bone.x, this.bone.y, 0f); } if (this.rotation) { if (this.bone.data.transformMode.InheritsRotation()) { cachedTransform.localRotation = Quaternion.Euler(0f, 0f, this.bone.rotation); } else { Vector3 eulerAngles = this.skeletonTransform.rotation.eulerAngles; cachedTransform.rotation = Quaternion.Euler(eulerAngles.x, eulerAngles.y, eulerAngles.z + (this.bone.WorldRotationX * num)); } } if (this.scale) { cachedTransform.localScale = new Vector3(this.bone.scaleX, this.bone.scaleY, 1f); this.incompatibleTransformMode = BoneTransformModeIncompatible(this.bone); } } } }
public void DoUpdate() { if (!valid) { Reset(); return; } Skeleton skeleton = skeletonUtility.skeletonRenderer.skeleton; if (bone == null) { if (string.IsNullOrEmpty(boneName)) { return; } bone = skeleton.FindBone(boneName); if (bone == null) { UnityEngine.Debug.LogError("Bone not found: " + boneName, this); return; } } float num = (!(skeleton.flipX ^ skeleton.flipY)) ? 1f : (-1f); if (mode == Mode.Follow) { if (!bone.appliedValid) { bone.UpdateAppliedTransform(); } if (position) { cachedTransform.localPosition = new Vector3(bone.ax, bone.ay, 0f); } if (rotation) { if (bone.data.transformMode.InheritsRotation()) { cachedTransform.localRotation = Quaternion.Euler(0f, 0f, bone.AppliedRotation); } else { Vector3 eulerAngles = skeletonTransform.rotation.eulerAngles; cachedTransform.rotation = Quaternion.Euler(eulerAngles.x, eulerAngles.y, eulerAngles.z + bone.WorldRotationX * num); } } if (scale) { cachedTransform.localScale = new Vector3(bone.ascaleX, bone.ascaleY, 1f); incompatibleTransformMode = BoneTransformModeIncompatible(bone); } } else { if (mode != Mode.Override || transformLerpComplete) { return; } if (parentReference == null) { if (position) { Vector3 localPosition = cachedTransform.localPosition; bone.x = Mathf.Lerp(bone.x, localPosition.x, overrideAlpha); bone.y = Mathf.Lerp(bone.y, localPosition.y, overrideAlpha); } if (rotation) { float a = bone.Rotation; Vector3 eulerAngles2 = cachedTransform.localRotation.eulerAngles; float appliedRotation = Mathf.LerpAngle(a, eulerAngles2.z, overrideAlpha); bone.Rotation = appliedRotation; bone.AppliedRotation = appliedRotation; } if (scale) { Vector3 localScale = cachedTransform.localScale; bone.scaleX = Mathf.Lerp(bone.scaleX, localScale.x, overrideAlpha); bone.scaleY = Mathf.Lerp(bone.scaleY, localScale.y, overrideAlpha); } } else { if (transformLerpComplete) { return; } if (position) { Vector3 vector = parentReference.InverseTransformPoint(cachedTransform.position); bone.x = Mathf.Lerp(bone.x, vector.x, overrideAlpha); bone.y = Mathf.Lerp(bone.y, vector.y, overrideAlpha); } if (rotation) { float a2 = bone.Rotation; Vector3 eulerAngles3 = Quaternion.LookRotation(Vector3.forward, parentReference.InverseTransformDirection(cachedTransform.up)).eulerAngles; float appliedRotation2 = Mathf.LerpAngle(a2, eulerAngles3.z, overrideAlpha); bone.Rotation = appliedRotation2; bone.AppliedRotation = appliedRotation2; } if (scale) { Vector3 localScale2 = cachedTransform.localScale; bone.scaleX = Mathf.Lerp(bone.scaleX, localScale2.x, overrideAlpha); bone.scaleY = Mathf.Lerp(bone.scaleY, localScale2.y, overrideAlpha); } incompatibleTransformMode = BoneTransformModeIncompatible(bone); } transformLerpComplete = true; } }