public async Task SetAndAnimateTranslation()
        {
            await App.DispatcherQueue.EnqueueAsync(async() =>
            {
                var button = new Button();
                var grid   = new Grid()
                {
                    Children = { button }
                };

                VisualExtensions.SetTranslation(button, "80, 20, 0");

                await SetTestContentAsync(grid);

                await AnimationBuilder.Create()
                .Translation(to: new Vector3(11, 22, 0))
                .StartAsync(button);

                var success = button.GetVisual().Properties.TryGetVector3("Translation", out Vector3 translation);

                Assert.AreEqual(success, CompositionGetValueStatus.Succeeded);
                Assert.AreEqual(translation, new Vector3(11, 22, 0));

                string text = VisualExtensions.GetTranslation(button);

                Assert.AreEqual(text, new Vector3(11, 22, 0).ToString());
            });
        }
Example #2
0
        private async void OnLoaded(object sender, RoutedEventArgs e)
        {
            //await AnimationBuilder.Create().Opacity(to: 0, duration: TimeSpan.FromSeconds(0.001)).StartAsync(LayoutRoot);
            await AnimationBuilder.Create().Opacity(from: 0.01, to: 1, duration: TimeSpan.FromSeconds(1.5)).StartAsync(LayoutRoot);

            ShowTextShimming();
        }
Example #3
0
        public async Task Start_WithCallback_CompositionOnly()
        {
            await App.DispatcherQueue.EnqueueAsync(async() =>
            {
                var button = new Button();
                var grid   = new Grid()
                {
                    Children = { button }
                };

                await SetTestContentAsync(grid);

                var tcs = new TaskCompletionSource <object>();

                AnimationBuilder.Create()
                .Scale(
                    to: new Vector3(1.2f, 1, 1),
                    delay: TimeSpan.FromMilliseconds(400))
                .Opacity(
                    to: 0.7,
                    duration: TimeSpan.FromSeconds(1))
                .Start(button, () => tcs.SetResult(null));

                await tcs.Task;

                // Note: we're just testing Scale and Opacity here as they're among the Visual properties that
                // are kept in sync on the Visual object after an animation completes, so we can use their
                // values below to check that the animations have run correctly. There is no particular reason
                // why we chose these two animations specifically other than this. For instance, checking
                // Visual.TransformMatrix.Translation or Visual.Offset after an animation targeting those
                // properties doesn't correctly report the final value and remains out of sync ¯\_(ツ)_/¯
                Assert.AreEqual(button.GetVisual().Scale, new Vector3(1.2f, 1, 1));
                Assert.AreEqual(button.GetVisual().Opacity, 0.7f);
            });
        }
Example #4
0
        public EffectPropertyBuildersTests()
        {
            slide        = new SlideAnimation();
            slideBuilder = new AnimationBuilder(slide);

            property        = new PropertyAnimation();
            propertyBuilder = new AnimationBuilder(property);
        }
        public static AnimationBuilder SlideDownAnimation()
        {
            var animation = AnimationBuilder.New()
                            .InsertFrame(0, new KeyFrame(0))
                            .InsertFrame(0.2f, new KeyFrame(-MathHelper.PiOver2))
                            .IsRelative(false);

            return(animation);
        }
        public static AnimationBuilder DiveAnimation()
        {
            var animation = AnimationBuilder.New()
                            .InsertFrame(0, new KeyFrame(0))
                            .InsertFrame(0.5f, new KeyFrame(MathHelper.PiOver2 + 0.1f))
                            .IsRelative(false)
                            .AnimatePhysics();

            return(animation);
        }
        public static AnimationBuilder ClamberAnimation()
        {
            var animator = AnimationBuilder.New()
                           .InsertFrame(0, new KeyFrame(new Vector2(0)))
                           .InsertFrame(0.2f, new KeyFrame(new Vector2(0, -1)))
                           .InsertFrame(0.3f, new KeyFrame(new Vector2(0.5f, -1f)))
                           .IsRelative(true);

            return(animator);
        }
Example #8
0
        private void ItemContainer_PointerExited(object sender, Windows.UI.Xaml.Input.PointerRoutedEventArgs e)
        {
            var panel = (sender as FrameworkElement).FindDescendant <DropShadowPanel>();

            if (panel != null)
            {
                AnimationBuilder.Create().Opacity(0, duration: TimeSpan.FromMilliseconds(1200)).Start(panel);
                AnimationBuilder.Create().Scale(1, duration: TimeSpan.FromMilliseconds(1200)).Start((UIElement)panel.Parent);
            }
        }
Example #9
0
        //--------------------------------------------------------Events:---------------------------------------------------------------------\\
        #region --Events--
        private void SettingsSelectionControl_PointerEntered(object sender, Windows.UI.Xaml.Input.PointerRoutedEventArgs e)
        {
            if (!(DeviceFamilyHelper.IsMouseInteractionMode() && sender is SettingsSelectionLargeControl settingsSelection))
            {
                return;
            }

            LastPopUpElement = VisualTreeHelper.GetParent(VisualTreeHelper.GetParent(settingsSelection) as FrameworkElement) as FrameworkElement;
            Canvas.SetZIndex(LastPopUpElement, 10);
            AnimationBuilder.Create().Scale(to: 1.05, easingType: EasingType.Sine).Start(LastPopUpElement);
        }
Example #10
0
        //--------------------------------------------------------Events:---------------------------------------------------------------------\\
        #region --Events--
        private void OnSelectionButtonPointerEntered(object sender, PointerRoutedEventArgs e)
        {
            if (!(DeviceFamilyHelper.IsMouseInteractionMode() && sender is SettingsSelectionLargeControl settingsSelection))
            {
                return;
            }

            LastPopUpElement = settingsSelection;
            Canvas.SetZIndex(LastPopUpElement, 10);
            AnimationBuilder.Create().Scale(to: new Vector2(1.05f), easingType: EasingType.Sine).Start(LastPopUpElement);
        }
Example #11
0
        private void OnSelectionButtonPointerExited(object sender, PointerRoutedEventArgs e)
        {
            if (LastPopUpElement is null)
            {
                return;
            }

            Canvas.SetZIndex(LastPopUpElement, 0);
            AnimationBuilder.Create().Scale(to: new Vector2(1.0f), easingType: EasingType.Sine).Start(LastPopUpElement);
            LastPopUpElement = null;
        }
        public static AnimationBuilder RollAnimation()
        {
            var animator = AnimationBuilder.New()
                           .InsertFrame(0f, new KeyFrame(new Vector2(0f), 0, new Vector2(1)))
                           .InsertFrame(0.2f, new KeyFrame(new Vector2(1f, 0.2f), MathHelper.Pi, new Vector2(1, 0.5f)))
                           .InsertFrame(0.4f, new KeyFrame(new Vector2(2f, 0f), MathHelper.TwoPi, new Vector2(1)))
                           .AnimatePhysics()
                           .IsRelative(true);

            return(animator);
        }
Example #13
0
        private void SettingsSelectionControl_PointerExited(object sender, Windows.UI.Xaml.Input.PointerRoutedEventArgs e)
        {
            if (LastPopUpElement is null)
            {
                return;
            }

            Canvas.SetZIndex(LastPopUpElement, 0);
            AnimationBuilder.Create().Scale(to: 1.0, easingType: EasingType.Sine).Start(LastPopUpElement);
            LastPopUpElement = null;
        }
Example #14
0
        protected override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            _container = GetTemplateChild("ContentContainer") as FrameworkElement;
            AnimationBuilder.Create()
            .Opacity()
            .NormalizedKeyFrames(b => b
                                 .KeyFrame(0, 0.0, easingType: EasingType.Linear)
                                 )
            .Start(_container);
        }
Example #15
0
        private void ItemContainer_PointerEntered(object sender, Windows.UI.Xaml.Input.PointerRoutedEventArgs e)
        {
            if (e.Pointer.PointerDeviceType == Windows.Devices.Input.PointerDeviceType.Mouse)
            {
                var panel = (sender as FrameworkElement).FindDescendant <DropShadowPanel>();
                if (panel != null)
                {
                    panel.Visibility = Visibility.Visible;

                    AnimationBuilder.Create().Opacity(1, duration: TimeSpan.FromMilliseconds(600)).Start(panel);
                    AnimationBuilder.Create().Scale(1.1, duration: TimeSpan.FromMilliseconds(600)).Start((UIElement)panel.Parent);
                }
            }
        }
Example #16
0
        public async Task HideAsync(bool success)
        {
            if (success)
            {
                ImageEditDone?.Invoke(this, new ImageEditDoneEventArgs(VIEW_MODEL.MODEL.OriginalImage));
            }
            else
            {
                ImageEditDone?.Invoke(this, new ImageEditDoneEventArgs());
            }
            await AnimationBuilder.Create().Translation(Axis.Y, contentHeight, 0, TimeSpan.FromMilliseconds(500), easingMode: EasingMode.EaseInOut).StartAsync(this);

            Visibility = Visibility.Collapsed;
        }
Example #17
0
            private void LinkBuilders(AnimationBuilder builder)
            {
                builder.delegateBuilder = delegateBuilder;
                Action startNextAnbimationAction = () => { builder.CreateAndStartAnimation(); };

                if (delegateBuilder.onAnimationEndAction != null)
                {
                    Action oldAction = delegateBuilder.onAnimationEndAction;
                    delegateBuilder.onAnimationEndAction = () => { oldAction(); builder.CreateAndStartAnimation(); };
                }
                else
                {
                    delegateBuilder.onAnimationEndAction = () => { builder.CreateAndStartAnimation(); };
                }
            }
Example #18
0
        void ResetAnimation()
        {
            lock (_AnimationCtsLock)
            {
                if (_AnimationCts != null)
                {
                    _AnimationCts.Cancel();
                    _AnimationCts.Dispose();
                }

                _AnimationCts = new CancellationTokenSource();
            }

            var ct = _AnimationCts.Token;

            if (Content != null)
            {
                if (IsAutoHideEnabled)
                {
                    var ab = AnimationBuilder.Create()
                             .Opacity(layer: FrameworkLayer.Xaml)
                             .TimedKeyFrames(b => b
                                             .KeyFrame(FadeInDuration, 1.0, easingType: EasingType.Linear)
                                             .KeyFrame(DisplayDuration + FadeInDuration, 1.0, easingType: EasingType.Linear)
                                             .KeyFrame(DisplayDuration + FadeInDuration + FadeOutDuration, 0.0, easingType: EasingType.Linear)
                                             );
                    ab.StartAsync(_container, ct);
                }
                else
                {
                    var ab = AnimationBuilder.Create()
                             .Opacity()
                             .TimedKeyFrames(b => b
                                             .KeyFrame(FadeInDuration, 1.0, easingType: EasingType.Linear)
                                             );
                    ab.StartAsync(_container, ct);
                }
            }
            else
            {
                var ab = AnimationBuilder.Create()
                         .Opacity()
                         .TimedKeyFrames(b => b
                                         .KeyFrame(FadeOutDuration, 0.0, easingType: EasingType.Linear)
                                         );
                ab.StartAsync(_container, ct);
            }
        }
Example #19
0
        private void Hide()
        {
            if (this.AssociatedObject == null)
            {
                return;
            }

            StopAnimation();

            if (IsAnimationEnabled)
            {
                var ct = CreateAnimationCancellationToken();
                _ = AnimationBuilder.Create().Opacity(0.0).StartAsync(this.AssociatedObject, ct)
                    .ContinueWith(prevTask => HideAnimation_Completed());
            }
            else
            {
                AssociatedObject.Opacity = 0.0;
            }
        }
Example #20
0
        public async Task Start_WithCallback_XamlOnly()
        {
            await App.DispatcherQueue.EnqueueAsync(async() =>
            {
                var button = new Button();
                var grid   = new Grid()
                {
                    Children = { button }
                };

                await SetTestContentAsync(grid);

                var tcs = new TaskCompletionSource <object>();

                AnimationBuilder.Create()
                .Translation(
                    to: new Vector2(80, 20),
                    layer: FrameworkLayer.Xaml)
                .Scale(
                    to: new Vector2(1.2f, 1),
                    delay: TimeSpan.FromMilliseconds(400),
                    layer: FrameworkLayer.Xaml)
                .Opacity(
                    to: 0.7,
                    duration: TimeSpan.FromSeconds(1),
                    layer: FrameworkLayer.Xaml)
                .Start(button, () => tcs.SetResult(null));

                await tcs.Task;

                CompositeTransform transform = button.RenderTransform as CompositeTransform;

                Assert.IsNotNull(transform);
                Assert.AreEqual(transform.TranslateX, 80);
                Assert.AreEqual(transform.TranslateY, 20);
                Assert.AreEqual(transform.ScaleX, 1.2, 0.0000001);
                Assert.AreEqual(transform.ScaleY, 1, 0.0000001);
                Assert.AreEqual(button.Opacity, 0.7, 0.0000001);
            });
        }
Example #21
0
        private void ContainerItem_Loaded(object sender, RoutedEventArgs e)
        {
            var itemsPanel    = (ItemsWrapGrid)SamplePickerGridView.ItemsPanelRoot;
            var itemContainer = (GridViewItem)sender;

            itemContainer.Loaded -= this.ContainerItem_Loaded;

            var button = itemContainer.FindDescendant <Button>();

            if (button != null)
            {
                button.Click     -= MoreInfoClicked;
                button.LostFocus -= MoreInfoLostFocus;
                button.Click     += MoreInfoClicked;
                button.LostFocus += MoreInfoLostFocus;
            }

            var itemIndex = SamplePickerGridView.IndexFromContainer(itemContainer);

            var referenceIndex = itemsPanel.FirstVisibleIndex;

            if (SamplePickerGridView.SelectedIndex >= 0)
            {
                referenceIndex = SamplePickerGridView.SelectedIndex;
            }

            var relativeIndex = Math.Abs(itemIndex - referenceIndex);

            if (itemContainer.Content != CurrentSample && itemIndex >= 0 && itemIndex >= itemsPanel.FirstVisibleIndex && itemIndex <= itemsPanel.LastVisibleIndex)
            {
                var staggerDelay = TimeSpan.FromMilliseconds(relativeIndex * 30);

                VisualExtensions.SetNormalizedCenterPoint(itemContainer, "0.5");

                AnimationBuilder.Create()
                .Opacity(from: 0, to: 1, delay: staggerDelay)
                .Scale(from: 0.9, to: 1, delay: staggerDelay)
                .Start(itemContainer);
            }
        }
Example #22
0
        protected override AnimationBuilder Apply(
            Direction direction, AnimationBuilder animation)
        {
            switch (direction)
            {
            case Direction.Left:
                return(animation.Effect(
                           _cover ? AnimationEffect.CoverLeft : AnimationEffect.UncoverLeft));

            case Direction.Right:
                return(animation.Effect(
                           _cover ? AnimationEffect.CoverRight : AnimationEffect.UncoverRight));

            case Direction.Up:
                return(animation.Effect(
                           _cover ? AnimationEffect.CoverUp : AnimationEffect.UncoverUp));

            case Direction.Down:
                return(animation.Effect(
                           _cover ? AnimationEffect.CoverDown : AnimationEffect.UncoverDown));
            }
            return(animation);
        }
Example #23
0
 private void aPNGToolStripMenuItem_Click(object sender, EventArgs e)
 {
     if (MainPanel.DataTree.SelectedNode == null)
     {
         return;
     }
     if (!ValidAnimation((WzObject)MainPanel.DataTree.SelectedNode.Tag))
     {
         Warning.Error(HaRepacker.Properties.Resources.MainAnimationFail);
     }
     else
     {
         SaveFileDialog dialog = new SaveFileDialog()
         {
             Title = HaRepacker.Properties.Resources.SelectOutApng, Filter = string.Format("{0}|*.png", HaRepacker.Properties.Resources.ApngFilter)
         };
         if (dialog.ShowDialog() != DialogResult.OK)
         {
             return;
         }
         AnimationBuilder.ExtractAnimation((WzSubProperty)MainPanel.DataTree.SelectedNode.Tag, dialog.FileName, UserSettings.UseApngIncompatibilityFrame);
     }
 }
Example #24
0
        protected override AnimationBuilder Apply(
            Direction direction, AnimationBuilder animation)
        {
            switch (direction)
            {
            case Direction.Left:
                return(animation.Effect(
                           _push ? AnimationEffect.PushLeft : AnimationEffect.MoveLeft));

            case Direction.Right:
                return(animation.Effect(
                           _push ? AnimationEffect.PushRight : AnimationEffect.MoveRight));

            case Direction.Up:
                return(animation.Effect(
                           _push ? AnimationEffect.PushUp : AnimationEffect.MoveUp));

            case Direction.Down:
                return(animation.Effect(
                           _push ? AnimationEffect.PushDown : AnimationEffect.MoveDown));
            }
            return(animation);
        }
Example #25
0
        private void Show()
        {
            if (this.AssociatedObject == null)
            {
                return;
            }

            StopAnimation();

            if (IsAnimationEnabled)
            {
                var ct = CreateAnimationCancellationToken();
                _ = AnimationBuilder.Create().Opacity(1.0).StartAsync(this.AssociatedObject, ct);

                if (IsAutoHideEnabled)
                {
                    AutoHideSubject.OnNext(0);
                }
            }
            else
            {
                AssociatedObject.Opacity = 1.0;
            }
        }
Example #26
0
        private void TryBuild(Entity entity, GameObject prefab, GameObject instance, string directory, string prefabPath, IDictionary <int, IDictionary <int, Sprite> > folders)
        {
            var controllerPath = string.Format("{0}/{1}.controller", directory, entity.name);
            var animator       = instance.GetComponent <Animator> ();      //Fetches the prefab's Animator

            if (animator == null)
            {
                animator = instance.AddComponent <Animator> ();                              //Or creates one if it doesn't exist
            }
            AnimatorController controller = null;

            if (animator.runtimeAnimatorController != null)                              //The controller we use is hopefully the controller attached to the animator
            {
                controller = animator.runtimeAnimatorController as AnimatorController ?? //Or the one that's referenced by an OverrideController
                             (AnimatorController)((AnimatorOverrideController)animator.runtimeAnimatorController).runtimeAnimatorController;
            }
            if (controller == null)               //Otherwise we have to check the AssetDatabase for our controller
            {
                controller = (AnimatorController)AssetDatabase.LoadAssetAtPath(controllerPath, typeof(AnimatorController));
                if (controller == null)
                {
                    controller = AnimatorController.CreateAnimatorControllerAtPath(controllerPath);                      //Or create a new one if it doesn't exist.
                    ProcessingInfo.NewControllers.Add(controller);
                }
                animator.runtimeAnimatorController = controller;
            }
            var transforms = new Dictionary <string, Transform> ();       //All of the bones and sprites, identified by TimeLine.name, because those are truly unique

            transforms ["rootTransform"] = instance.transform;            //The root GameObject needs to be part of this hierarchy as well
            var defaultBones   = new Dictionary <string, SpatialInfo> (); //These are basically the object states on the first frame of the first animation
            var defaultSprites = new Dictionary <string, SpriteInfo> ();  //They are used as control values in determining whether something has changed
            var animBuilder    = new AnimationBuilder(ProcessingInfo, folders, transforms, defaultBones, defaultSprites, prefabPath, controller);
            var firstAnim      = true;                                    //The prefab's graphic will be determined by the first frame of the first animation

            foreach (var animation in entity.animations)
            {
                var timeLines = new Dictionary <int, TimeLine> ();
                foreach (var timeLine in animation.timelines)                 //TimeLines hold all the critical data such as positioning and graphics used
                {
                    timeLines [timeLine.id] = timeLine;
                }
                foreach (var key in animation.mainlineKeys)
                {
                    var parents = new Dictionary <int, string> ();      //Parents are referenced by different IDs V_V
                    parents [-1] = "rootTransform";                     //This is where "-1 == no parent" comes in handy
                    var boneRefs = new Queue <Ref> (key.boneRefs ?? new Ref[0]);
                    while (boneRefs.Count > 0)
                    {
                        var bone     = boneRefs.Dequeue();
                        var timeLine = timeLines [bone.timeline];
                        parents [bone.id] = timeLine.name;
                        if (!transforms.ContainsKey(timeLine.name))                            //We only need to go through this once, so ignore it if it's already in the dict
                        {
                            if (parents.ContainsKey(bone.parent))                              //If the parent cannot be found, it will probably be found later, so save it
                            {
                                var parentID = parents [bone.parent];
                                var parent   = transforms [parentID];
                                var child    = parent.Find(timeLine.name);           //Try to find the child transform if it exists
                                if (child == null)                                   //Or create a new one
                                {
                                    child = new GameObject(timeLine.name).transform;
                                    child.SetParent(parent);
                                }
                                transforms [timeLine.name] = child;
                                var spatialInfo = defaultBones [timeLine.name] = ArrayUtility.Find(timeLine.keys, x => x.id == bone.key).info;
                                if (!spatialInfo.processed)
                                {
                                    SpatialInfo parentInfo;
                                    defaultBones.TryGetValue(parentID, out parentInfo);
                                    spatialInfo.Process(parentInfo);
                                }
                                child.localPosition = new Vector3(spatialInfo.x, spatialInfo.y, 0f);
                                child.localRotation = spatialInfo.rotation;
                                child.localScale    = new Vector3(spatialInfo.scale_x, spatialInfo.scale_y, 1f);
                            }
                            else
                            {
                                boneRefs.Enqueue(bone);
                            }
                        }
                    }
                    foreach (var oref in key.objectRefs)
                    {
                        var timeLine = timeLines [oref.timeline];
                        if (!transforms.ContainsKey(timeLine.name))                            //Same as above
                        {
                            var parentID = parents [oref.parent];
                            var parent   = transforms [parentID];
                            var child    = parent.Find(timeLine.name);
                            if (child == null)
                            {
                                child = new GameObject(timeLine.name).transform;
                                child.SetParent(parent);
                            }
                            transforms [timeLine.name] = child;
                            var swapper = child.GetComponent <TextureController> ();                            //Destroy the Sprite Swapper, we'll make a new one later
                            if (swapper != null)
                            {
                                DestroyImmediate(swapper);
                            }
                            var renderer = child.GetComponent <SpriteRenderer> ();                            //Get or create a Sprite Renderer
                            if (renderer == null)
                            {
                                renderer = child.gameObject.AddComponent <SpriteRenderer> ();
                            }
                            var spriteInfo = defaultSprites [timeLine.name] = (SpriteInfo)ArrayUtility.Find(timeLine.keys, x => x.id == 0).info;
                            renderer.sprite = folders [spriteInfo.folder] [spriteInfo.file];
                            if (!spriteInfo.processed)
                            {
                                SpatialInfo parentInfo;
                                defaultBones.TryGetValue(parentID, out parentInfo);
                                spriteInfo.Process(parentInfo);
                            }
                            child.localPosition    = new Vector3(spriteInfo.x, spriteInfo.y, oref.z_index);                           //Z-index helps determine draw order
                            child.localEulerAngles = new Vector3(0f, 0f, spriteInfo.angle);                                           //The reason I don't use layers or layer orders is because
                            child.localScale       = new Vector3(spriteInfo.scale_x, spriteInfo.scale_y, 1f);                         //There tend to be a LOT of body parts, it's better to treat
                            var color = renderer.color;                                                                               //The entity as a single sprite for layer sorting purposes.
                            color.a        = spriteInfo.a;
                            renderer.color = color;
                            if (!firstAnim)
                            {
                                child.gameObject.SetActive(false);                                          //Disable the GameObject if this isn't the first frame of the first animation
                            }
                        }
                    }
                    if (firstAnim)
                    {
                        firstAnim = false;
                    }
                }
                try {
                    animBuilder.Build(animation, timeLines);                      //Builds the currently processed AnimationClip, see AnimationBuilder for more info
                }
                catch (Exception e) {
                    Debug.LogErrorFormat("Unable to build animation '{0}' for '{1}', reason: {2}", animation.name, entity.name, e);
                }
            }
            if (instance.GetComponent <EntityRenderer> () == null)
            {
                instance.AddComponent <EntityRenderer> ();                                                              //Adds an EntityRenderer if one is not already present
            }
            PrefabUtility.ReplacePrefab(instance, prefab, ReplacePrefabOptions.ConnectToPrefab);
            DestroyImmediate(instance);              //Apply the instance's changes to the prefab, then destroy the instance.
        }
Example #27
0
 public PushMoveBuilder(bool push, AnimationBuilder animation)
     : base(animation)
 {
     _push = push;
 }
Example #28
0
 protected abstract AnimationBuilder Apply
     (Direction direction, AnimationBuilder animation);
Example #29
0
 protected DirectionBuilder(AnimationBuilder animation)
 {
     _animation = animation;
 }
        private void TryBuild(Entity entity, GameObject prefab, GameObject instance, string directory, string prefabPath, IDictionary<int, IDictionary<int, Sprite>> folders, ScmlObject scmlObject)
        {
            var controllerPath = string.Format ("{0}/{1}.controller", directory, entity.name);
            var animator = instance.GetComponent<Animator> (); //Fetches the prefab's Animator
            if (animator == null) animator = instance.AddComponent<Animator> (); //Or creates one if it doesn't exist
            AnimatorController controller = null;
            if (animator.runtimeAnimatorController != null) { //The controller we use is hopefully the controller attached to the animator
                controller = animator.runtimeAnimatorController as AnimatorController ?? //Or the one that's referenced by an OverrideController
                    (AnimatorController)((AnimatorOverrideController)animator.runtimeAnimatorController).runtimeAnimatorController;
            }
            if (controller == null) { //Otherwise we have to check the AssetDatabase for our controller
                controller = (AnimatorController)AssetDatabase.LoadAssetAtPath (controllerPath, typeof(AnimatorController));
                if (controller == null) {
                    controller = AnimatorController.CreateAnimatorControllerAtPath (controllerPath); //Or create a new one if it doesn't exist.
                    ProcessingInfo.NewControllers.Add (controller);
                }
                animator.runtimeAnimatorController = controller;
            }
            var transforms = new Dictionary<string, Transform> (); //All of the bones and sprites, identified by TimeLine.name, because those are truly unique
            transforms ["rootTransform"] = instance.transform; //The root GameObject needs to be part of this hierarchy as well
            var defaultBones = new Dictionary<string, SpatialInfo> (); //These are basically the object states on the first frame of the first animation
            var defaultSprites = new Dictionary<string, SpriteInfo> (); //They are used as control values in determining whether something has changed
            var animBuilder = new AnimationBuilder (ProcessingInfo, folders, transforms, defaultBones, defaultSprites, prefabPath, controller);
            var firstAnim = true; //The prefab's graphic will be determined by the first frame of the first animation
            foreach (var animation in entity.animations) {
                var timeLines = new Dictionary<int, TimeLine> ();
                foreach (var timeLine in animation.timelines) //TimeLines hold all the critical data such as positioning and graphics used
                    timeLines [timeLine.id] = timeLine;
                foreach (var key in animation.mainlineKeys) {
                    var parents = new Dictionary<int, string> (); //Parents are referenced by different IDs V_V
                    parents [-1] = "rootTransform"; //This is where "-1 == no parent" comes in handy
                    var boneRefs = new Queue<Ref> (key.boneRefs ?? new Ref[0]);
                    while (boneRefs.Count > 0) {
                        var bone = boneRefs.Dequeue ();
                        var timeLine = timeLines [bone.timeline];
                        parents [bone.id] = timeLine.name;
                        if (!transforms.ContainsKey (timeLine.name)) { //We only need to go through this once, so ignore it if it's already in the dict
                            if (parents.ContainsKey (bone.parent)) { //If the parent cannot be found, it will probably be found later, so save it
                                var parentID = parents [bone.parent];
                                var parent = transforms [parentID];
                                var child = parent.Find (timeLine.name); //Try to find the child transform if it exists
                                if (child == null) { //Or create a new one
                                    child = new GameObject (timeLine.name).transform;
                                    child.SetParent (parent);
                                }
                                transforms [timeLine.name] = child;
                                var spatialInfo = defaultBones [timeLine.name] = ArrayUtility.Find (timeLine.keys, x => x.id == bone.key).info;
                                if (!spatialInfo.processed) {
                                    SpatialInfo parentInfo;
                                    defaultBones.TryGetValue (parentID, out parentInfo);
                                    spatialInfo.Process (parentInfo);
                                }
                                child.localPosition = new Vector3(spatialInfo.x, spatialInfo.y, 0f);
                                child.localRotation = spatialInfo.rotation;
                                child.localScale = new Vector3 (spatialInfo.scale_x, spatialInfo.scale_y, 1f);
                            }
                            else boneRefs.Enqueue (bone);
                        }
                    }
                    foreach (var oref in key.objectRefs) {
                        var timeLine = timeLines [oref.timeline];
                        if (!transforms.ContainsKey (timeLine.name)) { //Same as above
                            var parentID = parents [oref.parent];
                            var parent = transforms [parentID];
                            var child = parent.Find (timeLine.name);
                            if (child == null) {
                                child = new GameObject (timeLine.name).transform;
                                child.SetParent (parent);
                            }
                            transforms [timeLine.name] = child;
                            var swapper = child.GetComponent<TextureController> (); //Destroy the Sprite Swapper, we'll make a new one later
                            if (swapper != null) DestroyImmediate (swapper);
                            var renderer = child.GetComponent<SpriteRenderer> (); //Get or create a Sprite Renderer
                            if (renderer == null) renderer = child.gameObject.AddComponent<SpriteRenderer> ();
                            var spriteInfo = defaultSprites [timeLine.name] = (SpriteInfo)ArrayUtility.Find (timeLine.keys, x => x.id == 0).info;
                            renderer.sprite = folders [spriteInfo.folder] [spriteInfo.file];
                            if (!spriteInfo.processed) {
                                SpatialInfo parentInfo;
                                defaultBones.TryGetValue (parentID, out parentInfo);
                                spriteInfo.Process (parentInfo);
                            }
                            var spriteSize = scmlObject.GetSpriteSize(spriteInfo.folder, spriteInfo.file);

                            child.localEulerAngles = new Vector3 (0f, 0f, spriteInfo.angle);

                            child.localPosition = spriteInfo.PrefabPosition(spriteSize, spriteInfo.angle, oref.z_index); //Z-index helps determine draw order
                                            //The reason I don't use layers or layer orders is because
                            child.localScale = new Vector3 (spriteInfo.scale_x, spriteInfo.scale_y, 1f);	//There tend to be a LOT of body parts, it's better to treat
                            var color = renderer.color;												//The entity as a single sprite for layer sorting purposes.
                            color.a = spriteInfo.a;
                            renderer.color = color;
                            if (!firstAnim) child.gameObject.SetActive (false); //Disable the GameObject if this isn't the first frame of the first animation
                        }
                    }
                    if (firstAnim) firstAnim = false;
                }
                try {
                    animBuilder.Build (animation, timeLines); //Builds the currently processed AnimationClip, see AnimationBuilder for more info
                }
                catch (Exception e) {
                    Debug.LogErrorFormat ("Unable to build animation '{0}' for '{1}', reason: {2}", animation.name, entity.name, e);
                }
            }
            if (instance.GetComponent<EntityRenderer> () == null) instance.AddComponent<EntityRenderer> (); //Adds an EntityRenderer if one is not already present
            PrefabUtility.ReplacePrefab (instance, prefab, ReplacePrefabOptions.ConnectToPrefab);
            DestroyImmediate (instance); //Apply the instance's changes to the prefab, then destroy the instance.
        }
Example #31
0
 public CoverUncoverBuilder(bool cover, AnimationBuilder animation)
     : base(animation)
 {
     _cover = cover;
 }