示例#1
0
 public Animation(int width, int height, Texture2D tex, AnimationMode am, int framerate)
 {
     curFrame = 0;
     frameRect = new Rectangle(0, 0, width, height);
     spriteTex = tex;
     animationMode = am;
     frameRate = framerate;
 }
示例#2
0
 public Animation(int framerate, AnimationMode animMode, LoopMode loopMode)
 {
     this.frames = new List<Rectangle>();
     this.framerate = framerate;
     this.animationMode = animMode;
     this.loopMode = loopMode;
     SetDirectionForwards();
     loopFrom = 0;
 }
 public AnimationSequence(string name, int frameFrom, int frameTo)
 {
     this.name = name;
     this.frameFrom = frameFrom;
     this.frameTo = frameTo;
     currentFrame = frameFrom;
     status = AnimationStatus.RUNNING;
     mode = AnimationMode.STOP_AT_END;
 }
        public AnimationProcess(EntityNode entity, AnimationMode mode, int frameDelay, int startFrame, int endFrame)
        {
            _entity = entity;
            _mode = mode;
            _frameDelay = frameDelay;

            _frames = new int[(endFrame - startFrame) + 1];
            for (int i = startFrame; i <= endFrame; i++)
                _frames[i - startFrame] = i;
        }
		public static IRenderer Renderer(AnimationMode mode, FitChartValue value, RectF drawingArea)
		{
			if (mode == AnimationMode.Linear)
			{
				return new LinearValueRenderer (drawingArea, value);
			}
			else
			{
				return new OverdrawValueRenderer (drawingArea, value);
			}
		}
示例#6
0
 /// <summary>
 /// Animates TopOFfsewt to the specified position.
 /// </summary>
 /// <param name="pos"></param>
 private void AnimateTopOffset(int pos, int duration, AnimationMode mode)
 {
     if (scrollAnimation == null)
     {
         scrollAnimation = new Animation(250, TopOffset, 0);
         scrollAnimation.Scene += new EventHandler<AnimationEventArgs>(scrollAnimation_Scene);
         scrollAnimation.Interval = 40;  // set to 25 pictures per seconds.
     }
     StopAutoScroll();
     scrollAnimation.Mode = mode;
     switch (mode)
     {
         case AnimationMode.Log:
             scrollAnimation.Acceleration = 0.05f;
             break;
         case AnimationMode.Accelerated:
             scrollAnimation.Acceleration = -5f;
             break;
     }
     scrollAnimation.Duration = duration;
     scrollAnimation.BeginValue = TopOffset;
     scrollAnimation.EndValue = pos;
     scrollAnimation.Start();
 }
    private void InitializeIfNeeded()
    {
        if (controller != null)
        {
            return;
        }

        contexts = UnityEditor.Animations.AnimatorController.FindStateMachineBehaviourContext((AnimatorEventSMB)target);

        Type animatorWindowType = Type.GetType("UnityEditor.Graphs.AnimatorControllerTool, UnityEditor.Graphs");
        var  window             = EditorWindow.GetWindow(animatorWindowType);
        //var animatorField = animatorWindowType.GetField("m_PreviewAnimator", BindingFlags.Instance | BindingFlags.NonPublic);
        //animator = animatorField.GetValue(window) as Animator;
        var controllerField = animatorWindowType.GetField("m_AnimatorController", BindingFlags.Instance | BindingFlags.NonPublic);

        controller = controllerField.GetValue(window) as UnityEditor.Animations.AnimatorController;


        UpdateMatchingAnimatorEventList();

        CreateReorderableList("On State Enter Transition Start", 20, ref list_onStateEnterTransitionStart, serializedObject.FindProperty("onStateEnterTransitionStart"),
                              (rect, index, isActive, isFocused) => {
            DrawCallbackField(rect, serializedObject.FindProperty("onStateEnterTransitionStart").GetArrayElementAtIndex(index));
        });
        CreateReorderableList("On State Enter Transition End", 20, ref list_onStateEnterTransitionEnd, serializedObject.FindProperty("onStateEnterTransitionEnd"),
                              (rect, index, isActive, isFocused) => {
            DrawCallbackField(rect, serializedObject.FindProperty("onStateEnterTransitionEnd").GetArrayElementAtIndex(index));
        });
        CreateReorderableList("On State Exit Transition Start", 20, ref list_onStateExitTransitionStart, serializedObject.FindProperty("onStateExitTransitionStart"),
                              (rect, index, isActive, isFocused) => {
            DrawCallbackField(rect, serializedObject.FindProperty("onStateExitTransitionStart").GetArrayElementAtIndex(index));
        });
        CreateReorderableList("On State Exit Transition End", 20, ref list_onStateExitTransitionEnd, serializedObject.FindProperty("onStateExitTransitionEnd"),
                              (rect, index, isActive, isFocused) => {
            DrawCallbackField(rect, serializedObject.FindProperty("onStateExitTransitionEnd").GetArrayElementAtIndex(index));
        });
        CreateReorderableList("On State Update", 20, ref list_onStateUpdated, serializedObject.FindProperty("onStateUpdated"),
                              (rect, index, isActive, isFocused) => {
            DrawCallbackField(rect, serializedObject.FindProperty("onStateUpdated").GetArrayElementAtIndex(index));
        });
        CreateReorderableList("On Normalized Time Reached", 60, ref list_onNormalizedTimeReached, serializedObject.FindProperty("onNormalizedTimeReached"),
                              (rect, index, isActive, isFocused) => {
            var property = serializedObject.FindProperty("onNormalizedTimeReached").GetArrayElementAtIndex(index);

            float timeBefore = property.FindPropertyRelative("normalizedTime").floatValue;

            DrawCallbackField(rect, property);
            bool timeEdited = EditorGUI.PropertyField(new Rect(rect.x, rect.y + 20, rect.width, 20), property.FindPropertyRelative("normalizedTime"));
            EditorGUI.PropertyField(new Rect(rect.x, rect.y + 40, rect.width / 2, 20), property.FindPropertyRelative("repeat"));
            EditorGUI.PropertyField(new Rect(rect.x + rect.width / 2, rect.y + 40, rect.width / 2, 20), property.FindPropertyRelative("executeOnExitEnds"));

            float timeNow = property.FindPropertyRelative("normalizedTime").floatValue;

            if (timeBefore != timeNow)
            {
                UpdateMatchingAnimatorEventList();

                if (!AnimationMode.InAnimationMode())
                {
                    AnimationMode.StartAnimationMode();
                }

                foreach (var context in contexts)
                {
                    AnimatorState state = context.animatorObject as AnimatorState;
                    if (null == state)
                    {
                        continue;
                    }

                    AnimationClip previewClip = GetFirstAvailableClip(state.motion);
                    if (null == previewClip)
                    {
                        continue;
                    }

                    foreach (var targetObj in matchingAnimatorEvent)
                    {
                        AnimationMode.BeginSampling();
                        AnimationMode.SampleAnimationClip(targetObj.gameObject, previewClip, property.FindPropertyRelative("normalizedTime").floatValue *previewClip.length);
                        AnimationMode.EndSampling();
                    }
                }
            }
        });
    }
    public void PlayAnimation(AnimationMode mode)
    {
        if (!isReverseAnimation)
        {
            fixEventBug = false;
            return;
        }

        switch (mode)
        {
            case AnimationMode.Play:
                btnPlay.SetActive(true);
                bgPlay.SetActive(true);
                LevelSelect.SetActive(false);
                break;
            case AnimationMode.Data:
                btnData.SetActive(true);
                bgData.SetActive(true);
                Data.SetActive(false);
                break;
            case AnimationMode.Online:
                btnOnline.SetActive(true);
                bgOnline.SetActive(true);
                Online.SetActive(false);
                break;
        }

        homeAnimator.SetFloat("Speed", 0);
        homeAnimator.SetTime(0.0D);
        homeAnimator.SetInteger("AnimationMode", 0);
        isReverseAnimation = false;

        Debug.Log(mode + " Start.");
    }
示例#9
0
        public void addAnim(string path, AnimationMode am, ContentManager Content, int frames)
        {
            Texture2D tex = Content.Load <Texture2D>(Globals.getValue("StandardSpritePath") + name + "/" + path);

            anims.Add(path, new Animation(tex.Width / frames, tex.Height, tex, am, (int.Parse(Globals.getValue("DefaultFrameRate")))));
        }
示例#10
0
 public static Quaternion Lerp(Quaternion a, Quaternion b, float t, AnimationMode mode)
 {
     return(Quaternion.Lerp(a, b, Get(t, mode)));
 }
示例#11
0
 public void PlayAnimation(bool forceRestart, AnimationMode animMode, int[] frames, int pri=0)
 {
     if(playAnimation == false || forceRestart || pri >= currentAnimationPriority)
     {
         currentAnimationPriority = pri;
         currentAnimationName = null;
         animationMode = (AnimationMode)animMode;
         frameMode = FrameMode.Sequence;
         animationFrames = frames;
         CheckAnimOnPlay();
         nextAnimFrame = myTime + GetCurrentCell().delay / 1000f;
         playAnimation = true;
     }
 }
示例#12
0
		private void InitializeView(IAttributeSet attrs) 
		{
            AnimationMode = AnimationMode.Linear;
            MaxValue = DefaultMaxValue;
            MinValue = DefaultMinValue;

			chartValues = new List<FitChartValue> ();
			InitializeBackground ();
			ReadAttributes (attrs);
			PreparePaints ();

            
		}
示例#13
0
    public void PlayNamedAnimation(string name, bool forceRestart)
    {
        RagePixelAnimation animation = GetCurrentRow().GetAnimationByName(name);
        if (animation != null)
        {
            if (playAnimation == false || forceRestart || animationMinIndex != animation.startIndex || animation.endIndex != animationMaxIndex)
            {
                animationMinIndex = animation.startIndex;
                animationMaxIndex = animation.endIndex;

                animationMinIndex = Mathf.Clamp(animation.startIndex, 0, GetCurrentRow().cells.Length - 1);
                animationMaxIndex = Mathf.Clamp(animation.endIndex, animationMinIndex, GetCurrentRow().cells.Length - 1);
                animationMode = animation.mode;
                CheckAnimRangesOnPlay();

                nextAnimFrame = myTime + GetCurrentCell().delay / 1000f;
                playAnimation = true;
            }
        }
        else
        {
            Debug.Log("No animation: " + name + " found in the sprite: " + (GetCurrentRow().name.Length > 0 ? GetCurrentRow().name : "empty"));
        }
    }
        public static void Animate(this WidgetView view, AnimationMode animationMode, bool focus = false,
            Action astartAction = null,
            Action aendAction = null,
            bool? isDocked = null,
            HorizontalAlignment? dockHorizontalAlignment = null,
            VerticalAlignment? dockVerticalAlignment = null)
        {
            var settings = view.Id.GetSettings();

            var horizontalAlignment = dockHorizontalAlignment ?? settings.HorizontalAlignment;
            var verticalAlignment = dockVerticalAlignment ?? settings.VerticalAlignment;
            var docked = isDocked ?? settings.IsDocked;

            view.RenderTransformOrigin = new Point(0.5, 0.5);
            if (docked)
            {
                switch (horizontalAlignment)
                {
                    case HorizontalAlignment.Left:
                        view.RenderTransformOrigin = new Point(0, view.RenderTransformOrigin.Y);
                        break;
                    case HorizontalAlignment.Right:
                        view.RenderTransformOrigin = new Point(1, view.RenderTransformOrigin.Y);
                        break;
                }
                switch (verticalAlignment)
                {
                    case VerticalAlignment.Top:
                        view.RenderTransformOrigin = new Point(view.RenderTransformOrigin.X, 0);
                        break;
                    case VerticalAlignment.Bottom:
                        view.RenderTransformOrigin = new Point(view.RenderTransformOrigin.X, 1);
                        break;
                }
            }

            Action startAction = delegate
            {
                if (animationMode == AnimationMode.Show)
                {
                    view.Show();
                }
                astartAction?.Invoke();
                view.AnimationRunning = true;
            };
            Action finishAction = delegate
            {
                if (animationMode == AnimationMode.Hide)
                {
                    view.Hide();
                }
                else
                {
                    if (focus && view.Settings.RefocusMainElementOnShow)
                        view.FocusMainElement();
                }
                aendAction?.Invoke();
                view.AnimationRunning = false;
            };

            if (settings.Style.AnimationType == AnimationType.None)
            {
                startAction();
                finishAction();
                return;
            }

            var doubleAnimation = new DoubleAnimation
            {
                Duration = new Duration(TimeSpan.FromMilliseconds(settings.Style.AnimationTime)),
                From = animationMode == AnimationMode.Show ? 0 : 1,
                To = animationMode == AnimationMode.Show ? 1 : 0,
                FillBehavior = FillBehavior.Stop,
                EasingFunction = settings.Style.AnimationEase
                    ? new SineEase
                    {
                        EasingMode = animationMode == AnimationMode.Show ? EasingMode.EaseIn : EasingMode.EaseOut
                    }
                    : null
            };

            // Start animation.
            startAction();
            switch (settings.Style.AnimationType)
            {
                case AnimationType.Fade:
                    var storyBoard = new Storyboard();
                    storyBoard.Completed += (sender, args) => finishAction();
                    storyBoard.Children.Add(doubleAnimation);
                    Storyboard.SetTarget(doubleAnimation, view);
                    Storyboard.SetTargetProperty(doubleAnimation, new PropertyPath(UIElement.OpacityProperty));
                    storyBoard.Begin();
                    break;
                case AnimationType.Slide:
                    var counter = 0;
                    doubleAnimation.Completed += delegate
                    {
                        counter++;
                        if (counter == 2)
                            finishAction();
                    };
                    var trans = new ScaleTransform();
                    view.RenderTransform = trans;
                    trans.BeginAnimation(ScaleTransform.ScaleXProperty, doubleAnimation);
                    trans.BeginAnimation(ScaleTransform.ScaleYProperty, doubleAnimation);
                    break;
                default:
                    finishAction();
                    break;
            }
        }
示例#15
0
        private void DoValueField(Rect rect, AnimationWindowHierarchyNode node, int row)
        {
            bool curvesChanged = false;

            if (node is AnimationWindowHierarchyPropertyNode)
            {
                AnimationWindowCurve[] curves = node.curves;
                if (curves == null || curves.Length == 0)
                {
                    return;
                }

                // We do valuefields for dopelines that only have single curve
                AnimationWindowCurve curve = curves[0];
                object value = CurveBindingUtility.GetCurrentValue(state, curve);

                if (!curve.isPPtrCurve)
                {
                    Rect valueFieldDragRect = new Rect(rect.xMax - k_ValueFieldOffsetFromRightSide - k_ValueFieldDragWidth, rect.y, k_ValueFieldDragWidth, rect.height);
                    Rect valueFieldRect     = new Rect(rect.xMax - k_ValueFieldOffsetFromRightSide, rect.y, k_ValueFieldWidth, rect.height);

                    if (Event.current.type == EventType.MouseMove && valueFieldRect.Contains(Event.current.mousePosition))
                    {
                        s_WasInsideValueRectFrame = Time.frameCount;
                    }

                    EditorGUI.BeginChangeCheck();

                    if (curve.valueType == typeof(bool))
                    {
                        value = GUI.Toggle(valueFieldRect, m_HierarchyItemValueControlIDs[row], (float)value != 0, GUIContent.none, EditorStyles.toggle) ? 1f : 0f;
                    }
                    else
                    {
                        int  id = m_HierarchyItemValueControlIDs[row];
                        bool enterInTextField = (EditorGUIUtility.keyboardControl == id &&
                                                 EditorGUIUtility.editingTextField &&
                                                 Event.current.type == EventType.KeyDown &&
                                                 (Event.current.character == '\n' || (int)Event.current.character == 3));

                        //  Force back keyboard focus to float field editor when editing it.
                        //  TreeView forces keyboard focus on itself at mouse down and we lose focus here.
                        if (EditorGUI.s_RecycledEditor.controlID == id && Event.current.type == EventType.MouseDown && valueFieldRect.Contains(Event.current.mousePosition))
                        {
                            GUIUtility.keyboardControl = id;
                        }

                        if (curve.isDiscreteCurve)
                        {
                            value = EditorGUI.DoIntField(EditorGUI.s_RecycledEditor,
                                                         valueFieldRect,
                                                         valueFieldDragRect,
                                                         id,
                                                         (int)value,
                                                         EditorGUI.kIntFieldFormatString,
                                                         m_AnimationSelectionTextField,
                                                         true,
                                                         0);
                            if (enterInTextField)
                            {
                                GUI.changed = true;
                                Event.current.Use();
                            }
                        }
                        else
                        {
                            value = EditorGUI.DoFloatField(EditorGUI.s_RecycledEditor,
                                                           valueFieldRect,
                                                           valueFieldDragRect,
                                                           id,
                                                           (float)value,
                                                           "g5",
                                                           m_AnimationSelectionTextField,
                                                           true);
                            if (enterInTextField)
                            {
                                GUI.changed = true;
                                Event.current.Use();
                            }

                            if (float.IsInfinity((float)value) || float.IsNaN((float)value))
                            {
                                value = 0f;
                            }
                        }
                    }

                    if (EditorGUI.EndChangeCheck())
                    {
                        string undoLabel = "Edit Key";

                        AnimationKeyTime newAnimationKeyTime = AnimationKeyTime.Time(state.currentTime, curve.clip.frameRate);
                        AnimationWindowUtility.AddKeyframeToCurve(curve, value, curve.valueType, newAnimationKeyTime);

                        state.SaveCurve(curve.clip, curve, undoLabel);
                        curvesChanged = true;
                    }
                }
            }

            if (curvesChanged)
            {
                //Fix for case 1382193: Stop recording any candidates if a property value field is modified
                if (AnimationMode.IsRecordingCandidates())
                {
                    state.ClearCandidates();
                }

                state.ResampleAnimation();
            }
        }
示例#16
0
        private static void BakeAnimations(MeshAnimationAsset asset)
        {
            var bakeObject = Object.Instantiate(asset.skin.gameObject);

            bakeObject.hideFlags = HideFlags.HideAndDontSave;
            var bakeMesh = new Mesh {
                hideFlags = HideFlags.HideAndDontSave
            };
            var skin = bakeObject.GetComponentInChildren <SkinnedMeshRenderer>();

            var bakeTransform = bakeObject.transform;

            bakeTransform.localPosition = Vector3.zero;
            bakeTransform.localRotation = Quaternion.identity;
            bakeTransform.localScale    = Vector3.one;

            var boundMin = Vector3.zero;
            var boundMax = Vector3.zero;

            var animator = bakeObject.GetComponent <Animator>();

            if (animator != null && animator.runtimeAnimatorController == null)
            {
                Debug.LogError("animator != null && animator.runtimeAnimatorController == null");
                return;
            }

            asset.animationData.Clear();

            AnimationMode.StartAnimationMode();
            AnimationMode.BeginSampling();

            try
            {
                foreach (var clip in asset.animationClips)
                {
                    for (int frame = 0, framesCount = clip.GetFramesCount(); frame < framesCount; frame++)
                    {
                        EditorUtility.DisplayProgressBar("Mesh Animator", clip.name, 1f * frame / framesCount);

                        AnimationMode.SampleAnimationClip(bakeObject, clip, frame / clip.frameRate);
                        skin.BakeMesh(bakeMesh);

                        var vertices = bakeMesh.vertices;
                        foreach (var vertex in vertices)
                        {
                            boundMin = Vector3.Min(boundMin, vertex);
                            boundMax = Vector3.Max(boundMax, vertex);
                        }
                    }
                }

                int globalFrame = 0;
                foreach (var clip in asset.animationClips)
                {
                    var framesCount = clip.GetFramesCount();
                    var looping     = clip.isLooping;

                    asset.animationData.Add(new MeshAnimationAsset.AnimationData
                    {
                        name          = clip.name,
                        startFrame    = globalFrame,
                        lengthFrames  = framesCount,
                        lengthSeconds = clip.length,
                        looping       = looping,
                    });

                    for (int frame = 0; frame < framesCount; frame++)
                    {
                        EditorUtility.DisplayProgressBar("Mesh Animator", clip.name, 1f * frame / framesCount);

                        AnimationMode.SampleAnimationClip(bakeObject, clip, frame / clip.frameRate);
                        skin.BakeMesh(bakeMesh);

                        CaptureMeshToTexture(asset.bakedTexture, bakeMesh, boundMin, boundMax, globalFrame);

                        if (looping && frame == 0)
                        {
                            CaptureMeshToTexture(asset.bakedTexture, bakeMesh, boundMin, boundMax,
                                                 globalFrame + framesCount);
                        }
                        else if (!looping && frame == framesCount - 1)
                        {
                            CaptureMeshToTexture(asset.bakedTexture, bakeMesh, boundMin, boundMax, globalFrame + 1);
                        }

                        ++globalFrame;
                    }

                    ++globalFrame;
                }

                while (globalFrame < asset.bakedTexture.height)
                {
                    CaptureMeshToTexture(asset.bakedTexture, bakeMesh, boundMin, boundMax, globalFrame);
                    ++globalFrame;
                }
            }
            finally
            {
                AnimationMode.EndSampling();
                AnimationMode.StopAnimationMode();
            }

            Object.DestroyImmediate(bakeObject);
            Object.DestroyImmediate(bakeMesh);

            asset.bakedMaterial.SetTexture(AnimTextureProp, asset.bakedTexture);
            asset.bakedMaterial.SetVector(AnimationMulProp, boundMax - boundMin);
            asset.bakedMaterial.SetVector(AnimationAddProp, boundMin);
        }
        public static AnimationClip CreateDefaultPose(RigBuilder rigBuilder)
        {
            if (rigBuilder == null)
            {
                throw new ArgumentNullException("It is not possible to bake curves without an RigBuilder.");
            }

            var defaultPoseClip = new AnimationClip()
            {
                name = "DefaultPose"
            };

            if (!AnimationMode.InAnimationMode())
            {
                return(defaultPoseClip);
            }

            var bindings = new List <EditorCurveBinding>();

            var gameObjects = new Queue <GameObject>();

            gameObjects.Enqueue(rigBuilder.gameObject);

            while (gameObjects.Count > 0)
            {
                var gameObject = gameObjects.Dequeue();

                EditorCurveBinding[] allBindings = AnimationUtility.GetAnimatableBindings(gameObject, rigBuilder.gameObject);
                foreach (var binding in allBindings)
                {
                    if (binding.isPPtrCurve)
                    {
                        continue;
                    }

                    if (binding.type == typeof(GameObject))
                    {
                        continue;
                    }

                    UnityEngine.Object target = gameObject.GetComponent(binding.type);
                    if (!AnimationMode.IsPropertyAnimated(target, binding.propertyName))
                    {
                        continue;
                    }

                    bindings.Add(binding);
                }

                // Iterate over all child GOs
                for (int i = 0; i < gameObject.transform.childCount; i++)
                {
                    Transform childTransform = gameObject.transform.GetChild(i);
                    gameObjects.Enqueue(childTransform.gameObject);
                }
            }

            // Flush out animation mode modifications
            AnimationMode.BeginSampling();
            AnimationMode.EndSampling();

            foreach (var binding in bindings)
            {
                float floatValue;
                AnimationUtility.GetFloatValue(rigBuilder.gameObject, binding, out floatValue);

                var key   = new Keyframe(0f, floatValue);
                var curve = new AnimationCurve(new Keyframe[] { key });
                defaultPoseClip.SetCurve(binding.path, binding.type, binding.propertyName, curve);
            }

            return(defaultPoseClip);
        }
        public static void TransferMotionToConstraint(RigBuilder rigBuilder, IEnumerable <Rig> rigs)
        {
            var constraints = new List <IRigConstraint>();

            foreach (var rig in rigs)
            {
                constraints.AddRange(RigUtils.GetConstraints(rig));
            }

            var clip = AnimationWindowReflection.activeAnimationClip;

            // Make sure we have a clip selected
            if (clip == null)
            {
                throw new InvalidOperationException(
                          "There is no clip to work on." +
                          " The animation window must be open with an active clip!");
            }

            AnimationClip editableClip = clip;

            if (!GetEditableClip(ref editableClip))
            {
                return;
            }

            AnimationClip defaultPoseClip = CreateDefaultPose(rigBuilder);

            Undo.RegisterCompleteObjectUndo(editableClip, kBakeToConstraintUndoLabel);

            var animator = rigBuilder.GetComponent <Animator>();

            if (editableClip != clip)
            {
                AddClipToAnimatorController(animator, editableClip);
            }

            var bindingsToRemove = new HashSet <EditorCurveBinding>();

            // Remove weight curve & force constraint to be active
            if (Preferences.forceConstraintWeightOnBake)
            {
                AnimationCurve oneWeightCurve = AnimationCurve.Constant(0f, editableClip.length, 1f);

                foreach (var rig in rigs)
                {
                    AnimationUtility.SetEditorCurve(editableClip, GetWeightCurveBinding(rigBuilder, rig), oneWeightCurve);
                }
            }

            foreach (IRigConstraint constraint in constraints)
            {
                var bakeParameters = FindBakeParameters(constraint);
                if (bakeParameters == null || !bakeParameters.canBakeToConstraint)
                {
                    continue;
                }

                // Flush out animation mode modifications
                AnimationMode.BeginSampling();
                AnimationMode.EndSampling();

                var bindings = bakeParameters.GetSourceCurveBindings(rigBuilder, constraint);
                BakeToConstraint(rigBuilder, constraint, editableClip, defaultPoseClip, bindings, Preferences.bakeToConstraintCurveFilterOptions);

                bindingsToRemove.UnionWith(bakeParameters.GetConstrainedCurveBindings(rigBuilder, constraint));
            }

            if (Preferences.bakeToConstraintAndRemoveCurves)
            {
                RemoveCurves(editableClip, bindingsToRemove);
            }
        }
 /// <summary>
 ///		Initializes a new instance of this class with the specified parameters.
 /// </summary>
 /// <param name="entity">Entity to associate this animation with.</param>
 /// <param name="mode">Mode of animation to animate entity with.</param>
 /// <param name="frameDelay">Delay between each animation frame.</param>
 /// <param name="frames">Array of frame indexs to animate entity with.</param>
 /// <param name="loopLimit">Maximum amount of loops before this process has to finish. 0 is equal to infinite.</param>
 public AnimationProcess(EntityNode entity, AnimationMode mode, int frameDelay, int[] frames, int loopLimit)
 {
     _entity = entity;
     _mode = mode;
     _frameDelay = frameDelay;
     _loopLimit = loopLimit;
     _frames = frames;
 }
 /// <summary>
 /// Initializes a new instance of the ChangeAnimationModeRequest request
 /// </summary>
 /// <param name="animationMode"></param>
 public ChangeAnimationModeRequest(AnimationMode animationMode)
 {
     AnimationMode = animationMode;
 }
示例#21
0
 private void StopCandidateRecording()
 {
     AnimationMode.StopCandidateRecording();
 }
        public static void AnimateSize(this Window window, AnimationMode animationMode, Action finishAction = null)
        {
            if (window == null)
                return;

            var doubleAnimation = new DoubleAnimation
            {
                Duration = new Duration(TimeSpan.FromMilliseconds(Settings.Default.AnimationDuration)),
                From = animationMode == AnimationMode.Show ? 0 : 1,
                To = animationMode == AnimationMode.Show ? 1 : 0,
                FillBehavior = FillBehavior.Stop,
                EasingFunction =
                    new SineEase
                    {
                        EasingMode = animationMode == AnimationMode.Show ? EasingMode.EaseIn : EasingMode.EaseOut
                    }
            };

            Action completeAction = delegate
            {
                if (animationMode == AnimationMode.Hide)
                    window.Hide();
                if (window.Opacity < 1)
                    window.Opacity = 1;
                finishAction?.Invoke();
            };
            //doubleAnimation.Completed += (sender, args) => completeAction();

            switch (Settings.Default.NotificationPosition)
            {
                case NotificationPosition.TopLeft:
                    window.RenderTransformOrigin = new Point(0, 0);
                    break;
                case NotificationPosition.TopRight:
                    window.RenderTransformOrigin = new Point(1, 0);
                    break;
                case NotificationPosition.BottomLeft:
                    window.RenderTransformOrigin = new Point(0, 1);
                    break;
                case NotificationPosition.BottomRight:
                    window.RenderTransformOrigin = new Point(1, 1);
                    break;
            }

            if (animationMode == AnimationMode.Show)
                window.Show();

            switch (Settings.Default.AnimationType)
            {
                case AnimationType.Fade:
                    var storyBoard = new Storyboard();
                    storyBoard.Completed += (sender, args) => completeAction();
                    storyBoard.Children.Add(doubleAnimation);
                    Storyboard.SetTarget(doubleAnimation, window);
                    Storyboard.SetTargetProperty(doubleAnimation, new PropertyPath(UIElement.OpacityProperty));
                    storyBoard.Begin();
                    break;
                case AnimationType.Slide:
                    var counter = 0;
                    doubleAnimation.Completed += delegate
                    {
                        counter++;
                        if (counter == 2) completeAction();
                    };
                    var trans = new ScaleTransform();
                    window.RenderTransform = trans;
                    trans.BeginAnimation(ScaleTransform.ScaleXProperty, doubleAnimation);
                    trans.BeginAnimation(ScaleTransform.ScaleYProperty, doubleAnimation);
                    break;
                default:
                    completeAction();
                    return;
            }
        }
示例#23
0
        private void ResampleAnimation(ResampleFlags flags)
        {
            if (state.disabled)
            {
                return;
            }

            if (previewing == false)
            {
                return;
            }
            if (canPreview == false)
            {
                return;
            }

            s_ResampleAnimationMarker.Begin();
            if (state.activeAnimationClip != null)
            {
                var  animationPlayer  = state.activeAnimationPlayer;
                bool usePlayableGraph = animationPlayer is Animator;

                if (usePlayableGraph)
                {
                    if (HasFlag(flags, ResampleFlags.RebuildGraph) || !m_Graph.IsValid())
                    {
                        RebuildGraph((Animator)animationPlayer);
                    }
                }

                AnimationMode.BeginSampling();

                if (HasFlag(flags, ResampleFlags.FlushUndos))
                {
                    Undo.FlushUndoRecordObjects();
                }

                if (usePlayableGraph)
                {
                    if (m_UsesPostProcessComponents)
                    {
                        IAnimationWindowPreview[] previewComponents = FetchPostProcessComponents();
                        if (previewComponents != null)
                        {
                            foreach (var component in previewComponents)
                            {
                                component.UpdatePreviewGraph(m_Graph);
                            }
                        }
                    }

                    if (!m_CandidateClip.empty)
                    {
                        AnimationMode.AddCandidates(state.activeRootGameObject, m_CandidateClip);
                    }

                    m_ClipPlayable.SetSampleRate(playing ? -1 : state.activeAnimationClip.frameRate);

                    AnimationMode.SamplePlayableGraph(state.activeRootGameObject, m_Graph, 0, time.time);

                    // This will cover euler/quaternion matching in basic playable graphs only (animation clip + candidate clip).
                    AnimationUtility.SampleEulerHint(state.activeRootGameObject, state.activeAnimationClip, time.time, WrapMode.Clamp);
                    if (!m_CandidateClip.empty)
                    {
                        AnimationUtility.SampleEulerHint(state.activeRootGameObject, m_CandidateClip, time.time, WrapMode.Clamp);
                    }
                }
                else
                {
                    AnimationMode.SampleAnimationClip(state.activeRootGameObject, state.activeAnimationClip, time.time);
                    if (!m_CandidateClip.empty)
                    {
                        AnimationMode.SampleCandidateClip(state.activeRootGameObject, m_CandidateClip, 0f);
                    }
                }

                AnimationMode.EndSampling();

                if (HasFlag(flags, ResampleFlags.RefreshViews))
                {
                    SceneView.RepaintAll();
                    InspectorWindow.RepaintAllInspectors();

                    // Particle editor needs to be manually repainted to refresh the animated properties
                    var particleSystemWindow = ParticleSystemWindow.GetInstance();
                    if (particleSystemWindow)
                    {
                        particleSystemWindow.Repaint();
                    }
                }
            }
            s_ResampleAnimationMarker.End();
        }
示例#24
0
    private void DrawFootBox()
    {
        if (Application.isPlaying || AnimationMode.InAnimationMode())
        {
            return;
        }

        if (m_obj.Transform == null)
        {
            m_obj.Transform = m_obj.GetComponent <Transform>();
        }

        var t = m_obj.Transform;

        Vector3 up      = t.up;
        Vector3 forward = t.forward;
        Vector3 right   = t.right;

        // Draw cross signifying the Ground Plane Height
        Vector3 groundCenter = (
            t.position + m_obj.GroundPlaneHeight * up * t.lossyScale.y
            );

        Handles.color = Color.green;
        Handles.DrawLine(groundCenter - forward, groundCenter + forward);
        Handles.DrawLine(groundCenter - right, groundCenter + right);

        // Draw rect showing foot boundaries
        if (!m_obj.Ready)
        {
            return;
        }

        float scale = t.lossyScale.z;

        for (int i = 0; i < m_obj.Legs.Length; i++)
        {
            var leg = m_obj.Legs[i];
            if (leg.Hip == null)
            {
                continue;
            }
            if (leg.Ankle == null)
            {
                continue;
            }
            if (leg.Toe == null)
            {
                continue;
            }
            if (leg.FootLength + leg.FootWidth == Float.Zero)
            {
                continue;
            }

            SetupFoot(i); // Note: Samples animation
            Vector3 heel   = leg.Ankle.TransformPoint(leg.AnkleHeelVector);
            Vector3 toetip = leg.Toe.TransformPoint(leg.ToeToetipVector);
            Vector3 side   = (Quaternion.AngleAxis(Float._90Deg, up) * (toetip - heel)).normalized * leg.FootWidth * scale;

            Handles.color = Color.white;
            Handles.DrawDottedLine(leg.Hip.position, leg.Ankle.position, Float.Two);
            Handles.DrawDottedLine(leg.Ankle.position, heel, Float.Two);
            Handles.DrawDottedLine(heel, toetip, Float.Two);

            Handles.color = Color.green;

            var pa1 = heel + side / Int.Two;
            var pa2 = toetip + side / Int.Two;
            var pb1 = heel - side / Int.Two;
            var pb2 = toetip - side / Int.Two;
            var pc1 = heel - side / Int.Two;
            var pc2 = heel + side / Int.Two;
            var pd1 = toetip - side / Int.Two;
            var pd2 = toetip + side / Int.Two;

            Handles.DrawLine(pa1, pa2);
            Handles.DrawLine(pb1, pb2);
            Handles.DrawLine(pc1, pc2);
            Handles.DrawLine(pd1, pd2);
        }
    }
示例#25
0
		private void ReadAttributes(IAttributeSet attrs)
		{
			valueStrokeColor = Context.Resources.GetColor (Resource.Color.default_chart_value_color);
			backStrokeColor = Context.Resources.GetColor (Resource.Color.default_back_stroke_color);
			strokeSize = Context.Resources.GetDimension (Resource.Dimension.default_stroke_size);

			if (attrs != null) 
			{
				var attributes = Context.Theme.ObtainStyledAttributes (attrs, Resource.Styleable.FitChart, 0, 0);
				strokeSize = attributes.GetDimensionPixelSize (Resource.Styleable.FitChart_strokeSize, (int)strokeSize);
				valueStrokeColor = attributes.GetColor (Resource.Styleable.FitChart_valueStrokeColor, valueStrokeColor);
				backStrokeColor = attributes.GetColor (Resource.Styleable.FitChart_backStrokeColor, backStrokeColor);

				var attrAnimationMode = attributes.GetInt (Resource.Styleable.FitChart_animationMode, AnimationModeLinear);
				if (attrAnimationMode == AnimationModeLinear)
				{
					AnimationMode = AnimationMode.Linear;
				}
				else 
				{
					AnimationMode = AnimationMode.Overdraw;
				}

				attributes.Recycle ();
			}
		}
示例#26
0
    private void MoveTowardLocation(Vector3 location)
    {
        _animationType = AnimationMode.Loop;

        if(Mathf.Abs(location.x - transform.position.x) < MinimumHomingDistance)
        {
            if(DebugMode)
                Debug.Log("Close enough, not moving.");

            return;
        }

        if(DebugMode)
            Debug.Log("Moving towards " + location);

        if(location.x < transform.position.x)
        {
            if(DebugMode)
                Debug.Log("Moving left...");

            _currentAnimation = WalkLeft;
            _isFacingLeft = true;
            _movement.MoveLeft();
            return;
        }
        else if(location.x > transform.position.x)
        {
            if(DebugMode)
                Debug.Log("Moving right...");

            _currentAnimation = WalkRight;
            _isFacingLeft = false;
            _movement.MoveRight();
            return;
        }
    }
示例#27
0
        static bool ProcessPlayableAssetRecording(UndoPropertyModification mod, WindowState state, ICurvesOwner curvesOwner, bool allowAdd)
        {
            if (mod.currentValue == null)
            {
                return(false);
            }

            if (!curvesOwner.IsParameterAnimatable(mod.currentValue.propertyPath))
            {
                return(false);
            }

            // only animate items with existing curves
            if (!allowAdd && !curvesOwner.IsParameterAnimated(mod.currentValue.propertyPath))
            {
                return(false);
            }

            var localTime    = state.editSequence.time;
            var timelineClip = curvesOwner as TimelineClip;

            if (timelineClip != null)
            {
                // don't use time global to local since it will possibly loop.
                localTime = timelineClip.ToLocalTimeUnbound(state.editSequence.time);
            }

            if (localTime < 0)
            {
                return(false);
            }

            // grab the value from the current modification
            float fValue;

            if (!ExpressionEvaluator.Evaluate(mod.currentValue.value, out fValue))
            {
                // case 916913 -- 'Add Key' menu item will passes 'True' or 'False' (instead of 1, 0)
                // so we need a special case to parse the boolean string
                bool bValue;
                if (!bool.TryParse(mod.currentValue.value, out bValue))
                {
                    Debug.Assert(false, "Invalid type in PlayableAsset recording");
                    return(false);
                }

                fValue = bValue ? 1 : 0;
            }

            var added = curvesOwner.AddAnimatedParameterValueAt(mod.currentValue.propertyPath, fValue, (float)localTime);

            if (added && AnimationMode.InAnimationMode())
            {
                EditorCurveBinding binding = curvesOwner.GetCurveBinding(mod.previousValue.propertyPath);
                AnimationMode.AddPropertyModification(binding, mod.previousValue, true);
                curvesOwner.targetTrack.SetShowInlineCurves(true);
                if (state.GetWindow() != null && state.GetWindow().treeView != null)
                {
                    state.GetWindow().treeView.CalculateRowRects();
                }
            }

            return(added);
        }
示例#28
0
 private void StartCandidateRecording()
 {
     AnimationMode.StartCandidateRecording(GetCandidateDriver());
 }
示例#29
0
    static public void OnInspectorPlayback(string name, CharacterAnimation character_animation, bool reset_playback)
    {
        if (!EditorUtility.IsPersistent(character_animation))
        {
            EditorGUILayout.BeginHorizontal();
            float playback_time = EditorGUILayout.FloatField(name + "Time", character_animation.PlaybackTime);
            playback_time = character_animation.PlaybackTime + (playback_time - character_animation.PlaybackTime) * 0.1f;

            bool update_playback_local = playback_time != character_animation.PlaybackTime;
            bool playback_back         = playback_time < character_animation.PlaybackTime;
            if (update_playback_local)
            {
                if (character_animation.IsPlaying == false)
                {
                    character_animation.Play(true);
                }
                else
                {
                    character_animation.IsPause = true;
                }

                character_animation.UpdatePlay(playback_time);
            }
            if (EditorApplication.isPlaying == false || character_animation.GetComponent <Character>().enabled == false)
            {
                RefreshParticles(character_animation);
                if (IsApplyEffect == true && m_Particles != null && character_animation.IsPlaying == true)
                {
                    foreach (var particle in m_Particles)
                    {
                        if (particle.IsPause == false)
                        {
                            particle.IsPause = true;
                        }
                        if (particle.IsPlaying == false || particle.IsPlayingAll() == false && (playback_back == true || reset_playback == true))
                        {
                            particle.Stop();
                            particle.Play(true, particle.Seed);
                        }
                        particle.SetPlaybackTime(playback_time);
                        particle.SetLightingMax(1f);
                    }
                }
            }
            float length = character_animation.CurrentState ? character_animation.CurrentState.length : 0f;
            EditorGUILayout.LabelField(string.Format("/ {0}", length));
            EditorGUILayout.EndHorizontal();

            character_animation.PlaybackSpeed = EditorGUILayout.Slider(name + "Speed", character_animation.PlaybackSpeed, 0f, 2f);
            if (character_animation.PlaybackSpeed < 0f)
            {
                character_animation.PlaybackSpeed = 0f;
            }

            // for move
            EditorGUILayout.BeginHorizontal();
            character_animation.UseMove   = EditorGUILayout.Toggle("Move", character_animation.UseMove);
            character_animation.MoveValue = EditorGUILayout.Vector3Field("", character_animation.MoveValue);
            EditorGUILayout.EndHorizontal();
//            EditorGUILayout.Vector3Field("", character_animation.MoveValueFx);
        }

        int cur_index     = GetAnimIndex(character_animation.CurrentState);
        int prev_index    = GetAnimIndex(character_animation.PrevState);
        int default_index = GetAnimIndex(character_animation.DefaultState);

        int new_index = EditorGUILayout.Popup("Current", cur_index, s_Animations);

        if (new_index != cur_index)
        {
            character_animation.Stop();
            foreach (var particle in m_Particles)
            {
                particle.Stop();
            }

            character_animation.CurrentState = character_animation.Animation[s_Animations[new_index]];
            RefreshParticles(character_animation, true);
        }

        new_index = EditorGUILayout.Popup("Prev", prev_index, s_Animations);
        if (new_index != prev_index)
        {
            character_animation.PrevState = character_animation.Animation[s_Animations[new_index]];
        }

        new_index = EditorGUILayout.Popup("Default", default_index, s_Animations);
        if (new_index != default_index)
        {
            character_animation.DefaultState = character_animation.Animation[s_Animations[new_index]];
        }

        bool camera_mode         = EditorPrefs.GetBool("CharacterInspectorCameraMode", false);
        bool default_effect_mode = EditorPrefs.GetBool("CharacterInspectorDefaultEffectMode", false);

        EditorGUILayout.BeginHorizontal();
        bool new_camera_mode = EditorGUILayout.Toggle("Camera Mode", camera_mode);

        if (new_camera_mode != camera_mode)
        {
            EditorPrefs.SetBool("CharacterInspectorCameraMode", new_camera_mode);
        }
        EditorGUIUtility.labelWidth = 90f;
        bool new_default_effect_mode = EditorGUILayout.Toggle("Default Effect", default_effect_mode);

        if (new_default_effect_mode != default_effect_mode)
        {
            EditorPrefs.SetBool("CharacterInspectorDefaultEffectMode", new_default_effect_mode);
        }
        EditorGUILayout.EndHorizontal();

        if (new_camera_mode && EditorApplication.isPlaying == false)
        {
            GameObject camera2 = GameObject.Find("2_CameraPivot");
            if (camera2 != null)
            {
                var cam_anim = camera2.GetComponent <Animation>();
                if (cam_anim != null && cam_anim.clip != null)
                {
                    if (AnimationMode.InAnimationMode() == false)
                    {
                        cam_anim.clip.SampleAnimation(cam_anim.gameObject, character_animation.PlaybackTime);
                    }
                    else
                    {
                        AnimationMode.SampleAnimationClip(cam_anim.gameObject, cam_anim.clip, character_animation.PlaybackTime);
                    }
                }
            }
        }
    }
示例#30
0
        private void RebuildGraph(Animator animator)
        {
            DestroyGraph();

            m_Graph = PlayableGraph.Create("PreviewGraph");
            m_Graph.SetTimeUpdateMode(DirectorUpdateMode.Manual);

            m_ClipPlayable = AnimationClipPlayable.Create(m_Graph, state.activeAnimationClip);
            m_ClipPlayable.SetOverrideLoopTime(true);
            m_ClipPlayable.SetLoopTime(false);
            m_ClipPlayable.SetApplyFootIK(false);

            m_CandidateClipPlayable = AnimationClipPlayable.Create(m_Graph, m_CandidateClip);
            m_CandidateClipPlayable.SetApplyFootIK(false);

            IAnimationWindowPreview[] previewComponents = FetchPostProcessComponents();
            bool requiresDefaultPose = previewComponents != null && previewComponents.Length > 0;
            int  nInputs             = requiresDefaultPose ? 3 : 2;

            // Create a layer mixer if necessary, we'll connect playable nodes to it after having populated AnimationStream.
            AnimationLayerMixerPlayable mixer = AnimationLayerMixerPlayable.Create(m_Graph, nInputs);

            m_GraphRoot = (Playable)mixer;

            // Populate custom playable preview graph.
            if (previewComponents != null)
            {
                foreach (var component in previewComponents)
                {
                    m_GraphRoot = component.BuildPreviewGraph(m_Graph, m_GraphRoot);
                }
            }

            // Finish hooking up mixer.
            int inputIndex = 0;

            if (requiresDefaultPose)
            {
                AnimationMode.RevertPropertyModificationsForGameObject(state.activeRootGameObject);

                EditorCurveBinding[] streamBindings = AnimationUtility.GetAnimationStreamBindings(state.activeRootGameObject);

                m_DefaultPose = new AnimationClip()
                {
                    name = "DefaultPose"
                };

                AnimationWindowUtility.CreateDefaultCurves(state, m_DefaultPose, streamBindings);

                m_DefaultPosePlayable = AnimationClipPlayable.Create(m_Graph, m_DefaultPose);
                m_DefaultPosePlayable.SetApplyFootIK(false);

                mixer.ConnectInput(inputIndex++, m_DefaultPosePlayable, 0, 1.0f);
            }

            mixer.ConnectInput(inputIndex++, m_ClipPlayable, 0, 1.0f);
            mixer.ConnectInput(inputIndex++, m_CandidateClipPlayable, 0, 1.0f);

            if (animator.applyRootMotion)
            {
                var motionX = AnimationMotionXToDeltaPlayable.Create(m_Graph);
                motionX.SetAbsoluteMotion(true);
                motionX.SetInputWeight(0, 1.0f);

                m_Graph.Connect(m_GraphRoot, 0, motionX, 0);

                m_GraphRoot = (Playable)motionX;
            }

            var output = AnimationPlayableOutput.Create(m_Graph, "ouput", animator);

            output.SetSourcePlayable(m_GraphRoot);
            output.SetWeight(0.0f);
        }
 private void DoIconAndName(Rect rect, AnimationWindowHierarchyNode node, bool selected, bool focused, float indent)
 {
     EditorGUIUtility.SetIconSize(new Vector2(13f, 13f));
     if (Event.current.type == EventType.Repaint)
     {
         if (selected)
         {
             TreeViewGUI.s_Styles.selectionStyle.Draw(rect, false, false, true, focused);
         }
         if (AnimationMode.InAnimationMode())
         {
             rect.width -= 77f;
         }
         bool   flag    = AnimationWindowUtility.IsNodeLeftOverCurve(node, this.state.activeRootGameObject);
         bool   flag2   = AnimationWindowUtility.IsNodeAmbiguous(node, this.state.activeRootGameObject);
         string text    = string.Empty;
         string tooltip = string.Empty;
         if (flag)
         {
             text    = " (Missing!)";
             tooltip = "The GameObject or Component is missing (" + node.path + ")";
         }
         if (flag2)
         {
             text    = " (Duplicate GameObject name!)";
             tooltip = "Target for curve is ambiguous since there are multiple GameObjects with same name (" + node.path + ")";
         }
         if (node.depth == 0)
         {
             if (this.state.activeRootGameObject != null)
             {
                 Transform x = this.state.activeRootGameObject.transform.Find(node.path);
                 if (x == null)
                 {
                     flag = true;
                 }
             }
             TreeViewGUI.s_Styles.content = new GUIContent(this.GetGameObjectName(node.path) + " : " + node.displayName + text, this.GetIconForNode(node), tooltip);
             Color textColor = this.m_AnimationLineStyle.normal.textColor;
             Color color     = (!EditorGUIUtility.isProSkin) ? Color.black : (Color.gray * 1.35f);
             color = ((!flag && !flag2) ? color : AnimationWindowHierarchyGUI.k_LeftoverCurveColor);
             this.SetStyleTextColor(this.m_AnimationLineStyle, color);
             rect.xMin += (float)((int)(indent + this.k_FoldoutWidth));
             GUI.Label(rect, TreeViewGUI.s_Styles.content, this.m_AnimationLineStyle);
             this.SetStyleTextColor(this.m_AnimationLineStyle, textColor);
         }
         else
         {
             TreeViewGUI.s_Styles.content = new GUIContent(node.displayName + text, this.GetIconForNode(node), tooltip);
             Color textColor2 = this.m_AnimationLineStyle.normal.textColor;
             Color color2     = (!EditorGUIUtility.isProSkin) ? this.m_LightSkinPropertyTextColor : Color.gray;
             color2 = ((!flag && !flag2) ? color2 : AnimationWindowHierarchyGUI.k_LeftoverCurveColor);
             this.SetStyleTextColor(this.m_AnimationLineStyle, color2);
             rect.xMin += (float)((int)(indent + this.k_IndentWidth + this.k_FoldoutWidth));
             GUI.Label(rect, TreeViewGUI.s_Styles.content, this.m_AnimationLineStyle);
             this.SetStyleTextColor(this.m_AnimationLineStyle, textColor2);
         }
     }
     if (this.IsRenaming(node.id) && Event.current.type != EventType.Layout)
     {
         base.GetRenameOverlay().editFieldRect = new Rect(rect.x + this.k_IndentWidth, rect.y, rect.width - this.k_IndentWidth - 1f, rect.height);
     }
 }
示例#32
0
        void DrawLocalRotationGUI()
        {
            // Setup.
            GUILayout.Space(2);
            EditorGUI.BeginProperty(GUILayoutUtility.GetLastRect(), new GUIContent(string.Empty), localRotation);
            EditorGUILayout.BeginHorizontal();

            // If Rotation has been modified outside, the euler hint will not be modified and the value displayed in the inspector will be wrong.
            // If in animation mode, this creates keys every time we move the playhead since the values are changed by the animation manager.

            if (!serializedObject.isEditingMultipleObjects && !AnimationMode.InAnimationMode())
            {
                if (Quaternion.Angle(Quaternion.Euler(targetTransform.localEulerAngles), Quaternion.Euler(localEulerHint.vector3Value)) > 0.06f)
                {
                    localEulerHint.vector3Value = localRotation.quaternionValue.eulerAngles;
                    GUI.changed = true;
                }
            }

            Vector3 eulerHintCache = localEulerHint.vector3Value;

            // Label.
            EditorGUILayout.LabelField("Rotation", GUILayout.Width(59));

            #region Label Shortcuts
            EditorGUI.BeginChangeCheck();
            if (EditorGUIExtensions.ScrollWheelClickOnRect(GUILayoutUtility.GetLastRect()))
            {
                GUIUtility.keyboardControl = 0;
                eulerHintCache             = Vector3.zero;
                GUI.changed = true;
            }
            if (EditorGUIExtensions.CtrlShiftRightClickOnRect(GUILayoutUtility.GetLastRect()))
            {
                ClipboardData.clipboardRotation = eulerHintCache;
            }
            if (EditorGUIExtensions.CtrlRightClickOnRect(GUILayoutUtility.GetLastRect()))
            {
                eulerHintCache = ClipboardData.clipboardRotation;
                GUI.changed    = true;
            }

            if (EditorGUI.EndChangeCheck())
            {
                foreach (var obj in targets)
                {
                    SerializedObject serial = new SerializedObject(obj);
                    serial.Update();
                    SerializedProperty hintProp = serial.FindProperty("m_LocalEulerAnglesHint");
                    hintProp.vector3Value = eulerHintCache;
                    serial.FindProperty("m_LocalRotation").quaternionValue = Quaternion.Euler(hintProp.vector3Value);
                    serial.ApplyModifiedProperties();
                }
            }
            #endregion

            #region X Value
            EditorGUI.BeginChangeCheck();
            EditorGUI.showMixedValue = IsEntireSelectionEqualInXRot() ? false : true;
            eulerHintCache.x         = EditorGUILayout.FloatField("X", eulerHintCache.x, GUILayout.MinWidth(12));

            if (EditorGUIExtensions.ScrollWheelClickOnRect(GUILayoutUtility.GetLastRect()))
            {
                GUIUtility.keyboardControl = 0;
                foreach (var obj in targets)
                {
                    SerializedObject serial = new SerializedObject(obj);
                    serial.Update();
                    SerializedProperty hintProp = serial.FindProperty("m_LocalEulerAnglesHint");
                    hintProp.vector3Value = hintProp.vector3Value.WithX(0);
                    serial.FindProperty("m_LocalRotation").quaternionValue = Quaternion.Euler(hintProp.vector3Value);
                    serial.ApplyModifiedProperties();
                }
            }
            if (EditorGUI.EndChangeCheck())
            {
                foreach (var obj in targets)
                {
                    SerializedObject serial = new SerializedObject(obj);
                    serial.Update();
                    SerializedProperty hintProp = serial.FindProperty("m_LocalEulerAnglesHint");
                    hintProp.vector3Value = hintProp.vector3Value.WithX(eulerHintCache.x);
                    serial.FindProperty("m_LocalRotation").quaternionValue = Quaternion.Euler(hintProp.vector3Value);
                    serial.ApplyModifiedProperties();
                }
            }
            #endregion

            #region Y Value
            EditorGUI.BeginChangeCheck();
            EditorGUI.showMixedValue = IsEntireSelectionEqualInYRot() ? false : true;
            eulerHintCache.y         = EditorGUILayout.FloatField("Y", eulerHintCache.y, GUILayout.MinWidth(12));

            if (EditorGUIExtensions.ScrollWheelClickOnRect(GUILayoutUtility.GetLastRect()))
            {
                GUIUtility.keyboardControl = 0;
                foreach (var obj in targets)
                {
                    SerializedObject serial = new SerializedObject(obj);
                    serial.Update();
                    SerializedProperty prop = serial.FindProperty("m_LocalEulerAnglesHint");
                    prop.vector3Value = prop.vector3Value.WithY(0);
                    serial.FindProperty("m_LocalRotation").quaternionValue = Quaternion.Euler(prop.vector3Value);
                    serial.ApplyModifiedProperties();
                }
            }
            if (EditorGUI.EndChangeCheck())
            {
                foreach (var obj in targets)
                {
                    SerializedObject serial = new SerializedObject(obj);
                    serial.Update();
                    SerializedProperty hintProp = serial.FindProperty("m_LocalEulerAnglesHint");
                    hintProp.vector3Value = hintProp.vector3Value.WithY(eulerHintCache.y);
                    serial.FindProperty("m_LocalRotation").quaternionValue = Quaternion.Euler(hintProp.vector3Value);
                    serial.ApplyModifiedProperties();
                }
            }

            #endregion

            #region Z Value
            EditorGUI.BeginChangeCheck();
            EditorGUI.showMixedValue = IsEntireSelectionEqualInZRot() ? false : true;
            eulerHintCache.z         = EditorGUILayout.FloatField("Z", eulerHintCache.z, GUILayout.MinWidth(12));

            if (EditorGUIExtensions.ScrollWheelClickOnRect(GUILayoutUtility.GetLastRect()))
            {
                GUIUtility.keyboardControl = 0;
                foreach (var obj in targets)
                {
                    SerializedObject serial = new SerializedObject(obj);
                    serial.Update();
                    SerializedProperty prop = serial.FindProperty("m_LocalEulerAnglesHint");
                    prop.vector3Value = prop.vector3Value.WithZ(0);
                    serial.FindProperty("m_LocalRotation").quaternionValue = Quaternion.Euler(prop.vector3Value);
                    serial.ApplyModifiedProperties();
                }
            }
            if (EditorGUI.EndChangeCheck())
            {
                foreach (var obj in targets)
                {
                    SerializedObject serial = new SerializedObject(obj);
                    serial.Update();
                    SerializedProperty hintProp = serial.FindProperty("m_LocalEulerAnglesHint");
                    hintProp.vector3Value = hintProp.vector3Value.WithZ(eulerHintCache.z);
                    serial.FindProperty("m_LocalRotation").quaternionValue = Quaternion.Euler(hintProp.vector3Value);
                    serial.ApplyModifiedProperties();
                }
            }
            #endregion

            // End Block.
            EditorGUI.showMixedValue = false;
            EditorGUILayout.EndHorizontal();
            EditorGUI.EndProperty();
        }
        private void DoValueField(Rect rect, AnimationWindowHierarchyNode node, int row)
        {
            bool flag = false;

            if (!AnimationMode.InAnimationMode())
            {
                return;
            }
            EditorGUI.BeginDisabledGroup(this.state.animationIsReadOnly);
            if (node is AnimationWindowHierarchyPropertyNode)
            {
                List <AnimationWindowCurve> curves = this.state.GetCurves(node, false);
                if (curves == null || curves.Count == 0)
                {
                    return;
                }
                AnimationWindowCurve animationWindowCurve = curves[0];
                object currentValue         = CurveBindingUtility.GetCurrentValue(this.state.activeRootGameObject, animationWindowCurve.binding);
                Type   editorCurveValueType = CurveBindingUtility.GetEditorCurveValueType(this.state.activeRootGameObject, animationWindowCurve.binding);
                if (currentValue is float)
                {
                    float num      = (float)currentValue;
                    Rect  position = new Rect(rect.xMax - 75f, rect.y, 50f, rect.height);
                    if (Event.current.type == EventType.MouseMove && position.Contains(Event.current.mousePosition))
                    {
                        AnimationWindowHierarchyGUI.s_WasInsideValueRectFrame = Time.frameCount;
                    }
                    EditorGUI.BeginChangeCheck();
                    if (editorCurveValueType == typeof(bool))
                    {
                        num = (float)((!EditorGUI.Toggle(position, num != 0f)) ? 0 : 1);
                    }
                    else
                    {
                        int  controlID = GUIUtility.GetControlID(123456544, FocusType.Keyboard, position);
                        bool flag2     = GUIUtility.keyboardControl == controlID && EditorGUIUtility.editingTextField && Event.current.type == EventType.KeyDown && (Event.current.character == '\n' || Event.current.character == '\u0003');
                        num = EditorGUI.DoFloatField(EditorGUI.s_RecycledEditor, position, new Rect(0f, 0f, 0f, 0f), controlID, num, EditorGUI.kFloatFieldFormatString, this.m_AnimationSelectionTextField, false);
                        if (flag2)
                        {
                            GUI.changed = true;
                            Event.current.Use();
                        }
                    }
                    if (float.IsInfinity(num) || float.IsNaN(num))
                    {
                        num = 0f;
                    }
                    if (EditorGUI.EndChangeCheck())
                    {
                        AnimationWindowKeyframe animationWindowKeyframe = null;
                        foreach (AnimationWindowKeyframe current in animationWindowCurve.m_Keyframes)
                        {
                            if (Mathf.Approximately(current.time, this.state.time.time))
                            {
                                animationWindowKeyframe = current;
                            }
                        }
                        if (animationWindowKeyframe == null)
                        {
                            AnimationWindowUtility.AddKeyframeToCurve(animationWindowCurve, num, editorCurveValueType, this.state.time);
                        }
                        else
                        {
                            animationWindowKeyframe.value = num;
                        }
                        this.state.SaveCurve(animationWindowCurve);
                        flag = true;
                    }
                }
            }
            EditorGUI.EndDisabledGroup();
            if (flag)
            {
                this.state.ResampleAnimation();
            }
        }
示例#34
0
 public static float LerpAngle(float a, float b, float t, AnimationMode mode)
 {
     return(Mathf.LerpAngle(a, b, Get(t, mode)));
 }
        private GenericMenu GenerateMenu(List <AnimationWindowHierarchyNode> interactedNodes)
        {
            List <AnimationWindowCurve> curvesAffectedByNodes  = this.GetCurvesAffectedByNodes(interactedNodes, false);
            List <AnimationWindowCurve> curvesAffectedByNodes2 = this.GetCurvesAffectedByNodes(interactedNodes, true);
            bool        flag        = curvesAffectedByNodes.Count == 1 && AnimationWindowUtility.ForceGrouping(curvesAffectedByNodes[0].binding);
            GenericMenu genericMenu = new GenericMenu();

            genericMenu.AddItem(new GUIContent((curvesAffectedByNodes.Count <= 1 && !flag) ? "Remove Property" : "Remove Properties"), false, new GenericMenu.MenuFunction(this.RemoveCurvesFromSelectedNodes));
            bool flag2 = true;

            EditorCurveBinding[] array = new EditorCurveBinding[curvesAffectedByNodes2.Count];
            for (int i = 0; i < curvesAffectedByNodes2.Count; i++)
            {
                array[i] = curvesAffectedByNodes2[i].binding;
            }
            RotationCurveInterpolation.Mode rotationInterpolationMode = this.GetRotationInterpolationMode(array);
            if (rotationInterpolationMode == RotationCurveInterpolation.Mode.Undefined)
            {
                flag2 = false;
            }
            else
            {
                foreach (AnimationWindowHierarchyNode current in interactedNodes)
                {
                    if (!(current is AnimationWindowHierarchyPropertyGroupNode))
                    {
                        flag2 = false;
                    }
                }
            }
            if (flag2)
            {
                string str = (!this.state.activeAnimationClip.legacy) ? string.Empty : " (Not fully supported in Legacy)";
                genericMenu.AddItem(new GUIContent("Interpolation/Euler Angles" + str), rotationInterpolationMode == RotationCurveInterpolation.Mode.RawEuler, new GenericMenu.MenuFunction2(this.ChangeRotationInterpolation), RotationCurveInterpolation.Mode.RawEuler);
                genericMenu.AddItem(new GUIContent("Interpolation/Euler Angles (Quaternion Approximation)"), rotationInterpolationMode == RotationCurveInterpolation.Mode.Baked, new GenericMenu.MenuFunction2(this.ChangeRotationInterpolation), RotationCurveInterpolation.Mode.Baked);
                genericMenu.AddItem(new GUIContent("Interpolation/Quaternion"), rotationInterpolationMode == RotationCurveInterpolation.Mode.NonBaked, new GenericMenu.MenuFunction2(this.ChangeRotationInterpolation), RotationCurveInterpolation.Mode.NonBaked);
            }
            if (AnimationMode.InAnimationMode())
            {
                genericMenu.AddSeparator(string.Empty);
                bool flag3 = true;
                bool flag4 = true;
                bool flag5 = true;
                foreach (AnimationWindowCurve current2 in curvesAffectedByNodes)
                {
                    if (!current2.HasKeyframe(this.state.time))
                    {
                        flag3 = false;
                    }
                    else
                    {
                        flag4 = false;
                        if (!current2.isPPtrCurve)
                        {
                            flag5 = false;
                        }
                    }
                }
                string text = "Add Key";
                if (flag3)
                {
                    genericMenu.AddDisabledItem(new GUIContent(text));
                }
                else
                {
                    genericMenu.AddItem(new GUIContent(text), false, new GenericMenu.MenuFunction2(this.AddKeysAtCurrentTime), curvesAffectedByNodes);
                }
                text = "Delete Key";
                if (flag4)
                {
                    genericMenu.AddDisabledItem(new GUIContent(text));
                }
                else
                {
                    genericMenu.AddItem(new GUIContent(text), false, new GenericMenu.MenuFunction2(this.DeleteKeysAtCurrentTime), curvesAffectedByNodes);
                }
                if (!flag5)
                {
                    genericMenu.AddSeparator(string.Empty);
                    List <KeyIdentifier> list = new List <KeyIdentifier>();
                    foreach (AnimationWindowCurve current3 in curvesAffectedByNodes)
                    {
                        if (!current3.isPPtrCurve)
                        {
                            int keyframeIndex = current3.GetKeyframeIndex(this.state.time);
                            if (keyframeIndex != -1)
                            {
                                CurveRenderer curveRenderer = CurveRendererCache.GetCurveRenderer(this.state.activeAnimationClip, current3.binding);
                                int           curveID       = CurveUtility.GetCurveID(this.state.activeAnimationClip, current3.binding);
                                list.Add(new KeyIdentifier(curveRenderer, curveID, keyframeIndex));
                            }
                        }
                    }
                }
            }
            return(genericMenu);
        }
示例#36
0
 public static Vector3 Lerp(Vector3 a, Vector3 b, float t, AnimationMode mode)
 {
     return(Vector3.Lerp(a, b, Get(t, mode)));
 }
示例#37
0
    // Update is called once per frame
    void Update()
    {
        // Get Shaders if they are null
        if (spriteShader == null)
        {
            spriteShader = Shader.Find("Sprites/Default");
        }

        if (spriteShadowsShader == null)
        {
            spriteShadowsShader = Shader.Find("Sprites/Skeleton-CutOut");
        }

        if (bones == null || bones != null && bones.Length <= 0 || Application.isEditor)
        {
            bones = gameObject.GetComponentsInChildren <Bone>(true);
            iks   = gameObject.GetComponentsInChildren <InverseKinematics>(true);
        }

                #if UNITY_EDITOR
        // EditorUpdate();

        // Check to see if the Animation Mode is in Record
        if (!Application.isPlaying && AnimationMode.InAnimationMode() && !recordMode)
        {
            // Default normal value
            int normal = -1;

            if ((int)transform.localEulerAngles.x == 0 && (int)transform.localEulerAngles.y == 180 ||
                (int)transform.localEulerAngles.x == 180 && (int)transform.localEulerAngles.y == 0)
            {
                normal = 1;
                // Debug.Log("Changing normals for " + name);
            }

            ChangeRendererNormals(normal);
            recordMode = true;
        }

        // If the Animation Window was recording, set skins back to use reference mesh
        if (!Application.isPlaying && !AnimationMode.InAnimationMode() && recordMode)
        {
            if (skin2Ds != null)
            {
                for (int i = 0; i < skin2Ds.Length; i++)
                {
                    skin2Ds[i].AssignReferenceMesh();

                    if (skin2Ds[i].skinnedMeshRenderer.sharedMesh != null &&
                        skin2Ds[i].referenceMesh != null &&
                        skin2Ds[i].skinnedMeshRenderer.sharedMesh != skin2Ds[i].referenceMesh)
                    {
                        skin2Ds[i].skinnedMeshRenderer.sharedMesh = skin2Ds[i].referenceMesh;
                    }
                }
            }

            recordMode = false;
        }
                #endif
    }
示例#38
0
    void OnSceneGUI()
    {
        SoxLtnNode soxLtnNode = target as SoxLtnNode;

        if (soxLtnNode.soxLtn == null)
        {
            return;
        }

        ifEditorAnimationPlaying            = AnimationMode.InAnimationMode(); // 애니메이터 창이 애니메이션모드인지를 노드에 세팅해줌
        soxLtnNode.ifEditorAnimationPlaying = ifEditorAnimationPlaying;

        SoxLtnNode[] soxLtnNodes = soxLtnNode.soxLtn.GetSoxLtnNodesInChildren();
        if (!soxLtnNode)
        {
            return;
        }
        if (!soxLtnNode.soxLtn)
        {
            return;
        }

        if (soxLtnNode.circleArea < 0)
        {
            soxLtnNode.circleArea = 0;
        }

        // scaledDotSize 는 soxLtn 노드의 스케일이 변경될 때 CubeCap 역시 같이 스케일이 변하도록 하기 위한 변수
        float scaledDotSize = (
            Mathf.Abs(soxLtnNode.transform.lossyScale.x) +
            Mathf.Abs(soxLtnNode.transform.lossyScale.y) +
            Mathf.Abs(soxLtnNode.transform.lossyScale.z)
            ) / 3.0f;

        Handles.color = Color.yellow;
        Handles.CubeHandleCap(0, soxLtnNode.transform.position, soxLtnNode.transform.rotation, soxLtnNode.soxLtn.dotSize * scaledDotSize, EventType.Repaint);

        switch (soxLtnNode.nodeType)
        {
        case SoxLtnNode.NodeType.CIRCLE:
            Handles.color = new Color(1, 1, 1, 0.5f);
            Handles.CircleHandleCap(0, soxLtnNode.transform.position + new Vector3(0, 0, 0), soxLtnNode.transform.rotation, soxLtnNode.circleArea * scaledDotSize, EventType.Repaint);
            break;

        case SoxLtnNode.NodeType.SPHERE:
            Handles.color = new Color(1, 1, 1, 0.5f);
            Handles.CircleHandleCap(0, soxLtnNode.transform.position + new Vector3(0, 0, 0), soxLtnNode.transform.rotation, soxLtnNode.circleArea * scaledDotSize, EventType.Repaint);

            Handles.color = new Color(1, 1, 1, 0.5f);
            Handles.CircleHandleCap(0, soxLtnNode.transform.position + new Vector3(0, 0, 0), soxLtnNode.transform.rotation * Quaternion.AngleAxis(90, Vector3.up), soxLtnNode.circleArea * scaledDotSize, EventType.Repaint);

            Handles.color = new Color(1, 1, 1, 0.5f);
            Handles.CircleHandleCap(0, soxLtnNode.transform.position + new Vector3(0, 0, 0), soxLtnNode.transform.rotation * Quaternion.AngleAxis(90, Vector3.right), soxLtnNode.circleArea * scaledDotSize, EventType.Repaint);
            break;

        default:
            break;
        }//Switch end

        // nodeCount와 meIndex 적용, 각 노드마다 이 처리가 있는 이유는, SoxLtn 루트가 아닌 자식 노드의 수동 복제도 있을 수 있기 때문
        soxLtnNode.nodeCount = soxLtnNodes.Length;
        for (int i = 0; i < soxLtnNode.nodeCount; i++)
        {
            if (soxLtnNode.soxLtn.soxLtnNodes[i] != null)
            {
                if (soxLtnNode.soxLtn.soxLtnNodes[i].transform == soxLtnNode.transform)
                {
                    soxLtnNode.meIndex = i;
                }
            }
        }

        if (soxLtnNode.nodeCount >= 2)
        {
            Vector3 camPos;
            camPos = SceneView.lastActiveSceneView.camera.transform.position;

            if ((soxLtnNode.meIndex == 0) || ((soxLtnNode.meIndex + 1) == soxLtnNode.nodeCount))
            {
                // 처음 혹은 마지막 노드인 경우
                if (soxLtnNode.meIndex == 0)
                {   // 처음 노드
                    soxLtnNode.editorCamPos = camPos;
                    soxLtnNode.Update();
                    soxLtnNodes[1].editorCamPos = camPos;
                    soxLtnNodes[1].Update();
                }
                else
                {
                    // 마지막 노드인 경우
                    soxLtnNode.editorCamPos = camPos;
                    soxLtnNode.Update();
                    soxLtnNodes[soxLtnNode.meIndex - 1].editorCamPos = camPos;
                    soxLtnNodes[soxLtnNode.meIndex - 1].Update();
                }
            }
            else
            {
                // 중간 노드인 경우
                soxLtnNode.editorCamPos = camPos;
                soxLtnNode.Update();
                soxLtnNodes[soxLtnNode.meIndex + 1].editorCamPos = camPos;
                soxLtnNodes[soxLtnNode.meIndex + 1].Update();
                soxLtnNodes[soxLtnNode.meIndex - 1].editorCamPos = camPos;
                soxLtnNodes[soxLtnNode.meIndex - 1].Update();
            }
        }
    }
示例#39
0
    public void SetAnimationMode(AnimationMode a)
    {
        this.mode = a;

        this.rot = 0f;
    }
示例#40
0
 public Animation(List<Rectangle> frames, int framerate, AnimationMode animMode, LoopMode loopMode, int loopFrom, int loopTo)
 {
     this.frames = frames;
     this.framerate = framerate;
     this.animationMode = animMode;
     this.loopMode = loopMode;
     this.loopFrom = loopFrom;
     this.loopTo = loopTo;
     SetDirectionForwards();
 }
示例#41
0
 // Start is called before the first frame update
 void Start()
 {
     this.rot  = 0f;
     this.mode = AnimationMode.Flying;
 }
示例#42
0
 public Animation(List<Rectangle> frames, int framerate, AnimationMode animMode, int goToFrame)
 {
     this.frames = frames;
     this.framerate = framerate;
     this.animationMode = animMode;
     this.loopMode = LoopMode.DIRECTION;
     SetDirectionForwards();
     loopFrom = 0;
     loopTo = frames.Count - 1;
     this.goToFrame = goToFrame;
 }
        void SamplePose(float time)
        {
            if (sampler == null)
            {
                return;
            }

            if (!AnimationMode.InAnimationMode())
            {
                AnimationMode.StartAnimationMode();
            }

            AnimationMode.BeginSampling();

            try
            {
                // 1. Sample pose
                using (TransformBuffer.Memory pose = sampler.SamplePose(time))
                {
                    // 2. Save bindings so that we can restore the joints to their initial transform once preview is finished
                    foreach (EditorCurveBinding binding in bindings)
                    {
                        AnimationMode.AddEditorCurveBinding(targetObject, binding);
                    }

                    // 3. Sample trajectory
                    AffineTransform rootTransform = sampler.SampleTrajectory(time);
                    if (previousTime >= 0.0f && targetJoints[0] != null)
                    {
                        // If the character was previously animated, we apply delta trajectory to current transform.
                        // Otherwise, we don't move the character (this allows user to move manually previewed character between frames)
                        var currentRootTransform =
                            Missing.Convert(targetObject.transform) *
                            previousRootTransform.inverseTimes(rootTransform);

                        targetJoints[0].position = currentRootTransform.t;
                        targetJoints[0].rotation = currentRootTransform.q;
                    }

                    previousTime          = time;
                    previousRootTransform = rootTransform;

                    // 4. Sample all joints
                    for (int i = 1; i < targetJoints.Length; ++i)
                    {
                        if (targetJoints[i] == null)
                        {
                            continue;
                        }

                        var localJointTransform = pose.Ref.transforms[i];

                        targetJoints[i].localPosition = localJointTransform.t;
                        targetJoints[i].localRotation = localJointTransform.q;
                    }

                    // 5. sample past & future trajectory
                    SampleTrajectory(time);
                }
            }
            finally
            {
                AnimationMode.EndSampling();
            }
        }
示例#44
0
 static extern void BoneSceneNode_SetAnimationMode(IntPtr bone, AnimationMode mode);
示例#45
0
    private void BakeAnimation()
    {
        // 노드들이 텐터클의 자식인지 검사.
        if (!CheckNodesInTentacle())
        {
            EditorUtility.DisplayDialog("Bake Animation Error", "Bake Animation does not work because there is a Node that is not a child of Tentacle.", "OK");
            return;
        }

        // Get Path
        string pathAbs = EditorUtility.SaveFilePanel("Bake Animation", "", tentacle.gameObject.name, "anim");

        if (pathAbs == "")
        {
            return;
        }
        string path = pathAbs;

        if (pathAbs.StartsWith(Application.dataPath))
        {
            path = "Assets" + pathAbs.Substring(Application.dataPath.Length);
        }
        else
        {
            EditorUtility.DisplayDialog("Bake Animation Error", "You can not create an asset outside the project.", "OK");
            return;
        }

        if (AnimationMode.InAnimationMode())
        {
            AnimationWindowTurnOffPreview();
        }

        // Create Animator
        Animator animator = tentacle.GetComponent <Animator>();

        if (animator == null)
        {
            animator = tentacle.gameObject.AddComponent <Animator>();
        }

        // if Get Path Canceled
        if (path == "")
        {
            return;
        }

        // Create Assets
        AnimationClip animClip = new AnimationClip();

        // (Sample Rate)
        animClip.frameRate = tentacle.m_bakeSamples;
        // (Loop Time)
        AnimationClipSettings tSettings = AnimationUtility.GetAnimationClipSettings(animClip);

        tSettings.loopTime = tentacle.m_bakeLoopTime;
        AnimationUtility.SetAnimationClipSettings(animClip, tSettings);
        AssetDatabase.CreateAsset(animClip, path);
        path = System.IO.Path.GetDirectoryName(path) + "/" + System.IO.Path.GetFileNameWithoutExtension(pathAbs) + ".controller";
        // AssetDatabase.CreateAsset(animController, path); <-- 이 방식으로 animController 를 생성하면 문제가 많다. (디폴트 세팅이 거의 안되어 생성되기때문으로 짐작). 다음 방식으로 생성하면 문제 없음.
        AnimatorController animController = UnityEditor.Animations.AnimatorController.CreateAnimatorControllerAtPath(path);

        // Assign Clip
        animController.AddMotion(animClip, 0);
        animator.runtimeAnimatorController = animController;

        // Save local rotation of nodes
        Quaternion[] rotBakNodes = new Quaternion[tentacle.m_nodes.Length];
        for (int i = 0; i < tentacle.m_nodes.Length; i++)
        {
            if (tentacle.m_nodes[i] != null)
            {
                rotBakNodes[i] = tentacle.m_nodes[i].localRotation;
            }
        }

        float frameLength = 1f / (float)tentacle.m_bakeSamples;
        int   frameCount  = (int)(tentacle.m_bakeTime / frameLength) + 1;

        // Initialize Keyframes
        EulerXYZKeys[] eulerXYZKeys = new EulerXYZKeys[tentacle.m_nodes.Length];
        for (int i = 0; i < tentacle.m_nodes.Length; i++)
        {
            if (tentacle.m_nodes[i] != null)
            {
                eulerXYZKeys[i].keysX = new Keyframe[frameCount];
                eulerXYZKeys[i].keysY = new Keyframe[frameCount];
                eulerXYZKeys[i].keysZ = new Keyframe[frameCount];
            }
        }

        // Update Tentacle
        // i = node index, o = frame
        tentacle.Initialize();
        int totalFrame = frameCount * tentacle.m_nodes.Length;

        for (int o = 0; o < frameCount; o++)
        {
            float     time             = o * frameLength;
            Vector3[] localEulerAlgles = tentacle.UpdateTentalces(time, true); // Update

            for (int i = 0; i < tentacle.m_nodes.Length; i++)
            {
                if (tentacle.m_nodes[i] != null)
                {
                    eulerXYZKeys[i].keysX[o] = new Keyframe(time, localEulerAlgles[i].x);
                    eulerXYZKeys[i].keysY[o] = new Keyframe(time, localEulerAlgles[i].y);
                    eulerXYZKeys[i].keysZ[o] = new Keyframe(time, localEulerAlgles[i].z);
                }
                float progress = (float)((i + 1) * (o + 1)) / (float)totalFrame;
                EditorUtility.DisplayProgressBar("Bake Animation", ("Node " + i.ToString() + "," + " Frame " + o.ToString()), progress);
            }
        }
        EditorUtility.ClearProgressBar();

        for (int i = 0; i < tentacle.m_nodes.Length; i++)
        {
            AnimationCurve curve = new AnimationCurve(eulerXYZKeys[i].keysX);
            animClip.SetCurve(GetRelativePath(tentacle.m_nodes[i]), typeof(Transform), "localEulerAngles.x", curve);
            curve = new AnimationCurve(eulerXYZKeys[i].keysY);
            animClip.SetCurve(GetRelativePath(tentacle.m_nodes[i]), typeof(Transform), "localEulerAngles.y", curve);
            curve = new AnimationCurve(eulerXYZKeys[i].keysZ);
            animClip.SetCurve(GetRelativePath(tentacle.m_nodes[i]), typeof(Transform), "localEulerAngles.z", curve);
        }

        // Restore local rotation of nodes
        for (int i = 0; i < tentacle.m_nodes.Length; i++)
        {
            if (tentacle.m_nodes[i] != null)
            {
                tentacle.m_nodes[i].localRotation = rotBakNodes[i];
            }
        }

        // Disable Tentacle
        if (tentacle.m_bakeDisableTentacle)
        {
            tentacle.enabled = false;
        }

        AutoTangent();
    }
示例#46
0
 public void PlayAnimation(bool forceRestart, AnimationMode animMode, int rangeMinIndex, int rangeMaxIndex, int pri=0)
 {
     if(playAnimation == false || forceRestart || pri >= currentAnimationPriority)
     {
         currentAnimationPriority = pri;
         currentAnimationName = null;
         animationMode = (AnimationMode)animMode;
         frameMode = FrameMode.Range;
         animationMinIndex = Mathf.Clamp(rangeMinIndex, 0, GetCurrentRow().cells.Length - 1);
         animationMaxIndex = Mathf.Clamp(rangeMaxIndex, animationMinIndex, GetCurrentRow().cells.Length - 1);
         CheckAnimOnPlay();
         nextAnimFrame = myTime + GetCurrentCell().delay / 1000f;
         playAnimation = true;
     }
 }
示例#47
0
 private void BeHit()
 {
     _lockAnimation    = true;
     _animationType    = AnimationMode.OneShot;
     _currentAnimation = _isFacingLeft ? HitLeft : HitRight;
 }
示例#48
0
    public void PlayNamedAnimation(string name, bool forceRestart, float delayFirstFrame, int pri=0)
    {
        RagePixelAnimation animation = GetCurrentRow().GetAnimationByName(name);
        if(animation != null)
        {
            if((playAnimation == false ||
                forceRestart ||
                AnimationIsDifferent(animation) ||
                AnimationIsOver) &&
                (pri >= currentAnimationPriority))
            {
                currentAnimationName = name;
                currentAnimationPriority = pri;
                animationFrames = animation.frames;

                animationMinIndex = Mathf.Clamp(animation.startIndex, 0, GetCurrentRow().cells.Length - 1);
                animationMaxIndex = Mathf.Clamp(animation.endIndex, animationMinIndex, GetCurrentRow().cells.Length - 1);
                animationMode = animation.mode;
                frameMode = animation.frameMode;
                CheckAnimOnPlay();

                nextAnimFrame = myTime + GetCurrentCell().delay / 1000f + delayFirstFrame;
                playAnimation = true;
            }
        }
        else
        {
            Debug.Log("No animation: " + name + " found in the sprite: " + (GetCurrentRow().name.Length > 0 ? GetCurrentRow().name : "empty"));
        }
    }
示例#49
0
        public void LoadScene(int sceneNo, int vLedCount = 0, int hLedCount = 0)
        {
            if (vLedCount == 0)
            {
                vLedCount = 3;
            }
            if (hLedCount == 0)
            {
                hLedCount = 5;
            }

            _hLedCount = hLedCount;
            _vLedCount = vLedCount;

            SceneBase scene;

            switch (sceneNo)
            {
            case 0:
                scene = new SceneRandom();
                break;

            case 1:
                scene = new SceneFire();
                break;

            case 2:
                scene = new SceneTwinkle();
                break;

            case 3:
                scene = new SceneOcean();
                break;

            case 4:
                scene = new SceneRainbow();
                break;

            case 5:
                scene = new SceneJuly();
                break;

            case 6:
                scene = new SceneHoliday();
                break;

            case 7:
                scene = new ScenePop();
                break;

            case 8:
                scene = new SceneForest();
                break;

            default:
                scene = null;
                break;
            }

            if (scene == null)
            {
                return;
            }
            _colors        = scene.GetColors();
            _animationTime = scene.AnimationTime;
            _mode          = scene.Mode;
            _startInt      = 0;
            RefreshColors(_colors);
        }
示例#50
0
 public void PlayAnimation(bool forceRestart, int animMode, int rangeMinIndex, int rangeMaxIndex)
 {
     if (playAnimation == false || forceRestart)
     {
         animationMode = (AnimationMode)animMode;
         animationMinIndex = Mathf.Clamp(rangeMinIndex, 0, GetCurrentRow().cells.Length - 1);
         animationMaxIndex = Mathf.Clamp(rangeMaxIndex, animationMinIndex, GetCurrentRow().cells.Length - 1);
         CheckAnimRangesOnPlay();
         nextAnimFrame = myTime + GetCurrentCell().delay / 1000f;
         playAnimation = true;
     }
 }
示例#51
0
 public bool DiscardModification(PropertyModification modification)
 {
     return(!AnimationMode.IsPropertyAnimated(modification.target, modification.propertyPath));
 }
示例#52
0
 private void BeHit()
 {
     _lockAnimation = true;
     _animationType = AnimationMode.OneShot;
     _currentAnimation = _isFacingLeft ? HitLeft : HitRight;
 }
示例#53
0
 public void AddPropertyModification(EditorCurveBinding binding, PropertyModification propertyModification, bool keepPrefabOverride)
 {
     AnimationMode.AddCandidate(binding, propertyModification, keepPrefabOverride);
 }
示例#54
0
 private void PerformAttack(bool shouldCrouch)
 {
     _lockAnimation = true;
     _animationType = AnimationMode.OneShot;
     _currentAnimation = shouldCrouch
                             ? _isFacingLeft
                                 ? CrouchAttackLeft
                                 : CrouchAttackRight
                             : _isFacingLeft
                                 ? AttackLeft
                                 : AttackRight;
 }
示例#55
0
 public void addAnim(string path, AnimationMode am, ContentManager Content, int frames)
 {
     Texture2D tex = Content.Load<Texture2D>(Globals.getValue("StandardSpritePath") + name + "/" + path);
        anims.Add(path, new Animation(tex.Width / frames, tex.Height, tex, am, (int.Parse(Globals.getValue("DefaultFrameRate")))));
 }