CABasicAnimation basicAnimationNamed (string name, float duration)
		{
			CABasicAnimation animation = new CABasicAnimation ();
			animation.Duration = duration;
			animation.SetValueForKey ((NSString)name, (NSString)"name");
			return animation;
		}
		partial void makeFast (NSButton sender)
		{
			CABasicAnimation frameOriginAnimation = new CABasicAnimation();
			frameOriginAnimation.Duration = 0.1f;
			NSDictionary animations = NSDictionary.FromObjectAndKey(frameOriginAnimation,
			                                                        (NSString)"frameOrigin");
			myView.Mover.Animations = animations;
		}
		private CABasicAnimation rotationAnimation ()
		{
			CABasicAnimation rotation = new CABasicAnimation ();
			rotation.KeyPath = "frameRotation";
			rotation.From = NSNumber.FromFloat (0);
			rotation.To = NSNumber.FromFloat (45);
			return rotation;
		}
Example #4
0
		public void By ()
		{
			var a = new CABasicAnimation {
				By = NSNumber.FromFloat (45),
				KeyPath = "cornerRadius",
				Duration = 2,
			};
			solidView.Layer.AddAnimation (a, "CornerRadiusAnimation");
		}
		CABasicAnimation MoveItAnimation()
		{
			if (moveAnimation == null)
				moveAnimation = new CABasicAnimation() {
					Duration = 2,
					TimingFunction = new CAMediaTimingFunction (0.5f, 1, 0.5f, 0)
				};
			return moveAnimation;
		}
Example #6
0
		public void FromTo ()
		{
			var a = new CABasicAnimation {
				From = NSNumber.FromFloat (50),
				To = NSNumber.FromFloat (5),
				KeyPath = "cornerRadius",
				Duration = 2,
			};
			solidView.Layer.AddAnimation (a, "CornerRadiusAnimation");
		}
Example #7
0
		static new NSObject DefaultAnimationFor (NSString key)
		{
			if (key == "drawnLineWidth"){
				if (drawnLineWidthBasicAnimation == null) {
					drawnLineWidthBasicAnimation = new CABasicAnimation ();
					//drawnLineWidthBasicAnimation.Duration = 2.0f;
				}
				return drawnLineWidthBasicAnimation;
			} else
				return NSView.DefaultAnimationFor (key);
		}
Example #8
0
		public void ToDidStop ()
		{
			var a = new CABasicAnimation {
				To = NSNumber.FromFloat (50),
				KeyPath = "cornerRadius",
				Duration = 2,
			};
			a.AnimationStopped += (sender, e) => {
				solidView.Layer.CornerRadius = 50;
			}; 
			solidView.Layer.AddAnimation (a, "CornerRadiusAnimation");
		}
Example #9
0
		public void Basic ()
		{
			var a = new CABasicAnimation {
				From = NSNumber.FromDouble (pieChart.Angle),
				To = NSNumber.FromDouble (3*Math.PI/2),
				KeyPath = "angle",
				Duration = 3,
				TimingFunction = CAMediaTimingFunction.FromName (
					CAMediaTimingFunction.EaseInEaseOut),
			};
			pieChart.AddAnimation (a, "AngleAnimation");
			pieChart.Angle = 3*Math.PI/2;
		}
		private void AddAnimationToTorusFilter()
		{
			string keyPath = string.Format ("backgroundFilters.torus.{0}", CIFilterInputKey.Width.ToString ());
			CABasicAnimation animation = new CABasicAnimation ();
			animation.KeyPath = keyPath;
			animation.From = NSNumber.FromFloat (50);
			animation.To = NSNumber.FromFloat (80);
			animation.Duration = 1;
			animation.RepeatCount = float.MaxValue;
			animation.TimingFunction = CAMediaTimingFunction.FromName (CAMediaTimingFunction.EaseInEaseOut);
			animation.AutoReverses = true;
			controls.Layer.AddAnimation (animation, "torusAnimation");
		}
 private CABasicAnimation GetRotationAnimation()
 {
     if (_rotationAnimation == null)
     {
         _rotationAnimation = CABasicAnimation.FromKeyPath ("transform.rotation.z");
         _rotationAnimation.To = NSNumber.FromDouble (-Math.PI * 2d);
         _rotationAnimation.Duration = 1f;
         _rotationAnimation.RepeatCount = float.PositiveInfinity;
         _rotationAnimation.Cumulative = true;
         _rotationAnimation.FillMode = CAFillMode.Forwards;
         _rotationAnimation.RemovedOnCompletion = false;
     }
     return _rotationAnimation;
 }
Example #12
0
        public override void LayoutSubviews()
        {
            base.LayoutSubviews();      

            image.Frame = new CoreGraphics.CGRect(Frame.Size.Width - 40, Frame.Size.Height - 40, 20, 20);
            image.ContentMode = UIViewContentMode.ScaleAspectFit;

            CABasicAnimation rotationAnimation = new CABasicAnimation();
            rotationAnimation.KeyPath = "transform.rotation.z";
            rotationAnimation.To = new NSNumber(Math.PI * 2);
            rotationAnimation.Duration = 1;
            rotationAnimation.Cumulative = true;
            rotationAnimation.RepeatCount = float.MaxValue;
            Add(image);
            image.Layer.AddAnimation(rotationAnimation, "rotationAnimation");            
        }
		public override bool FinishedLaunching (UIApplication app, NSDictionary options)
		{
			// create a new window instance based on the screen size
			window = new UIWindow (UIScreen.MainScreen.Bounds);
		
			vc = new UIViewController ();
			vc.View.BackgroundColor = UIColor.Black;
			testLayer = new CircleLayer();
			testLayer.Color = UIColor.Green.CGColor;
			testLayer.Thickness = 19f;
			testLayer.Radius = 60f;
	
			testLayer.Frame = vc.View.Layer.Bounds;
			vc.View.Layer.AddSublayer(testLayer);
			
			testLayer.SetNeedsDisplay();
			
			radiusAnimation = CABasicAnimation.FromKeyPath ("radius");
			radiusAnimation.Duration = 3;
			radiusAnimation.To = NSNumber.FromDouble (120);
			radiusAnimation.RepeatCount = 1000;
			
			thicknessAnimation = CABasicAnimation.FromKeyPath ("thickness");
			thicknessAnimation.Duration = 2;
			thicknessAnimation.From = NSNumber.FromDouble (5);
			thicknessAnimation.To = NSNumber.FromDouble (38);
			thicknessAnimation.RepeatCount = 1000;
			
			colorAnimation = CABasicAnimation.FromKeyPath ("circleColor");
			colorAnimation.Duration = 4;
			colorAnimation.To = new NSObject (UIColor.Blue.CGColor.Handle);
			colorAnimation.RepeatCount = 1000;
			
			testLayer.AddAnimation (radiusAnimation, "radiusAnimation");
			testLayer.AddAnimation (thicknessAnimation, "thicknessAnimation");
			testLayer.AddAnimation (colorAnimation, "colorAnimation");
			
			window.RootViewController = vc;
			// make the window visible
			window.MakeKeyAndVisible ();
			
			return true;
		}
        public ComparisonView(RectangleF frame)
            : base(frame)
        {
            BackgroundColor = UIColor.White;

            animationImagesImageView = new UIImageView() {
                Frame = new RectangleF(PointF.Empty, new SizeF(40f, 40f)),
                AutoresizingMask = UIViewAutoresizing.FlexibleMargins,
                AnimationImages = new UIImage[] {
                    UIImage.FromBundle("loading_1"),
                    UIImage.FromBundle("loading_2"),
                    UIImage.FromBundle("loading_3"),
                    UIImage.FromBundle("loading_4"),
                },
            };
            animationImagesImageView.AnimationRepeatCount = 0;
            animationImagesImageView.AnimationDuration = 0.5;
            animationImagesImageView.StartAnimating();
            Add(animationImagesImageView);

            basicAnimationImageView = new UIImageView(UIImage.FromBundle("loading_1")) {
                Frame = new RectangleF(PointF.Empty, new SizeF(40f, 40f)),
                AutoresizingMask = UIViewAutoresizing.FlexibleMargins,
                Hidden = true,
            };
            rotationAnimation = CABasicAnimation.FromKeyPath("transform.rotation");
            rotationAnimation.To = NSNumber.FromDouble(Math.PI * 2); // full rotation (in radians)
            rotationAnimation.RepeatCount = int.MaxValue; // repeat forever
            rotationAnimation.Duration = 0.5;
            // Give the added animation a key for referencing it later (e.g., to remove it when it is replaced).
            basicAnimationImageView.Layer.AddAnimation(rotationAnimation, "rotationAnimation");
            Add(basicAnimationImageView);

            // Button overlay to switch between the two versions.
            switchButton = new UIButton();
            switchButton.TouchUpInside += (sender, e) => {
                animationImagesImageView.Hidden = !animationImagesImageView.Hidden;
                basicAnimationImageView.Hidden = !basicAnimationImageView.Hidden;
            };
            Add(switchButton);
        }
Example #15
0
        public static CALayer RenderRasterOnLayer(IRaster raster, IStyle style, IViewport viewport)
        {
            var tile = new CALayer();
            var data = NSData.FromArray(raster.Data.ToArray());
            var image = UIImage.LoadFromData(data);
            var frame = ConvertBoundingBox(raster.GetBoundingBox(), viewport);

            tile.Frame = frame;
            tile.Contents = image.CGImage;

            var aOpacity = new CABasicAnimation
                {
                    KeyPath = @"opacity",
                    From = new NSNumber(0.1),
                    To = new NSNumber(1.0),
                    Duration = 0.6
                };

            tile.AddAnimation(aOpacity, "opacity");

            return tile;
        }
Example #16
0
        public override void PresentStep(int switchIndex, PresentationViewController presentationViewController)
        {
            switch (switchIndex)
            {
            case 0:
                // Set the slide's title and subtitle and add some text
                TextManager.SetTitle("Core Image");
                TextManager.SetSubtitle("CI Filters");

                TextManager.AddBulletAtLevel("Screen-space effects", 0);
                TextManager.AddBulletAtLevel("Applies to a node hierarchy", 0);
                TextManager.AddBulletAtLevel("Filter parameters are animatable", 0);
                TextManager.AddCode("#aNode.#Filters# = new CIFilter[] { filter1, filter2 };#");
                break;

            case 1:
                SCNTransaction.Begin();
                SCNTransaction.AnimationDuration = 1.0f;
                // Dim the text and move back a little
                TextManager.TextNode.Opacity = 0.0f;
                presentationViewController.CameraHandle.Position = presentationViewController.CameraNode.ConvertPositionToNode(new SCNVector3(0, 0, 5.0f), presentationViewController.CameraHandle.ParentNode);
                SCNTransaction.Commit();

                // Reveal the grid
                GroupNode.Opacity = 1;
                break;

            case 2:
                SCNTransaction.Begin();
                SCNTransaction.AnimationDuration = 1;
                // Highlight an item
                HighlightContact(13, presentationViewController);
                SCNTransaction.Commit();
                break;

            case 3:
                var index   = 13;
                var subStep = 0;

                // Successively select items
                for (var i = 0; i < 5; ++i)
                {
                    var popTime = new DispatchTime(DispatchTime.Now, (Int64)(i * 0.2 * Utils.NSEC_PER_SEC));
                    DispatchQueue.MainQueue.DispatchAfter(popTime, () => {
                        SCNTransaction.Begin();
                        SCNTransaction.AnimationDuration = 0.2f;
                        UnhighlightContact(index);

                        if (subStep++ == 3)
                        {
                            index += ColumnCount;
                        }
                        else
                        {
                            index++;
                        }

                        HighlightContact(index, presentationViewController);
                        SCNTransaction.Commit();
                    });
                }
                break;

            case 4:
                // BLUR+DESATURATE in the background, GLOW in the foreground

                // Here we will change the node hierarchy in order to group all the nodes in the background under a single node.
                // This way we can use a single Core Image filter and apply it on the whole grid, and have another CI filter for the node in the foreground.

                var selectionParent = HeroNode.ParentNode;

                SCNTransaction.Begin();
                SCNTransaction.AnimationDuration = 0;
                // Stop the animations of the selected node
                HeroNode.Transform = HeroNode.PresentationNode.Transform;                 // set the current rotation to the current presentation value
                HeroNode.RemoveAllAnimations();

                // Re-parent the node by preserving its world tranform
                var wantedWorldTransform = selectionParent.WorldTransform;
                GroupNode.ParentNode.AddChildNode(selectionParent);
                selectionParent.Transform = selectionParent.ParentNode.ConvertTransformFromNode(wantedWorldTransform, null);
                SCNTransaction.Commit();

                // Add CIFilters

                SCNTransaction.Begin();
                SCNTransaction.AnimationDuration = 1;
                // A negative 'centerX' value means no scaling.
                //TODO HeroNode.Filters [0].SetValueForKey (new NSNumber (-1), new NSString ("centerX"));

                // Move the selection to the foreground
                selectionParent.Rotation = new SCNVector4(0, 1, 0, 0);
                HeroNode.Transform       = ContentNode.ConvertTransformToNode(SCNMatrix4.CreateTranslation(0, Altitude, 29), selectionParent);
                HeroNode.Scale           = new SCNVector3(1, 1, 1);
                HeroNode.Rotation        = new SCNVector4(1, 0, 0, -(float)(Math.PI / 4) * 0.25f);

                // Upon completion, rotate the selection forever
                SCNTransaction.SetCompletionBlock(() => {
                    var animation            = CABasicAnimation.FromKeyPath("rotation");
                    animation.Duration       = 4.0f;
                    animation.From           = NSValue.FromVector(new SCNVector4(0, 1, 0, 0));
                    animation.To             = NSValue.FromVector(new SCNVector4(0, 1, 0, (float)Math.PI * 2));
                    animation.TimingFunction = CAMediaTimingFunction.FromName(CAMediaTimingFunction.EaseInEaseOut);
                    animation.RepeatCount    = float.MaxValue;

                    HeroNode.ChildNodes [0].AddAnimation(animation, new NSString("heroNodeAnimation"));
                });

                // Add the filters
                var blurFilter = CIFilter.FromName("CIGaussianBlur");
                blurFilter.SetDefaults();
                blurFilter.Name = "blur";
                blurFilter.SetValueForKey(new NSNumber(0), CIFilterInputKey.Radius);

                var desaturateFilter = CIFilter.FromName("CIColorControls");
                desaturateFilter.SetDefaults();
                desaturateFilter.Name = "desaturate";
                GroupNode.Filters     = new CIFilter[] { blurFilter, desaturateFilter };
                SCNTransaction.Commit();

                // Increate the blur radius and desaturate progressively
                SCNTransaction.Begin();
                SCNTransaction.AnimationDuration = 2;
                GroupNode.SetValueForKey(new NSNumber(10), new NSString("filters.blur.inputRadius"));
                GroupNode.SetValueForKey(new NSNumber(0.1), new NSString("filters.desaturate.inputSaturation"));
                SCNTransaction.Commit();

                break;
            }
        }
        public void SetChecked(bool value, bool animated)
        {
            if (isChecked == value)
            {
                return;
            }

            isChecked = value;

            if (animated)
            {
                var strokeStart   = CABasicAnimation.FromKeyPath("strokeStart");
                var strokeEnd     = CABasicAnimation.FromKeyPath("strokeEnd");
                var lineWidthAnim = CABasicAnimation.FromKeyPath("lineWidth");
                if (isChecked)
                {
                    strokeStart.To             = NSNumber.FromDouble(checkStrokeStart);
                    strokeStart.Duration       = 0.3;
                    strokeStart.TimingFunction = timingFunc;

                    strokeEnd.To             = NSNumber.FromDouble(checkStrokeEnd);
                    strokeEnd.Duration       = 0.3;
                    strokeEnd.TimingFunction = timingFunc;

                    lineWidthAnim.To             = NSNumber.FromDouble(lineWidthBold);
                    lineWidthAnim.BeginTime      = 0.2;
                    lineWidthAnim.Duration       = 0.1;
                    lineWidthAnim.TimingFunction = timingFunc;
                }
                else
                {
                    strokeStart.To             = NSNumber.FromDouble(circleStrokeStart);
                    strokeStart.Duration       = 0.2;
                    strokeStart.TimingFunction = backFunc;
                    strokeStart.FillMode       = CAFillMode.Backwards;

                    strokeEnd.To             = NSNumber.FromDouble(circleStrokeEnd);
                    strokeEnd.Duration       = 0.3;
                    strokeEnd.TimingFunction = backFunc;

                    lineWidthAnim.To             = NSNumber.FromDouble(lineWidth);
                    lineWidthAnim.Duration       = 0.1;
                    lineWidthAnim.TimingFunction = backFunc;
                }
                ApplyAnimationCopy(shape, strokeStart);
                ApplyAnimationCopy(shape, strokeEnd);
                ApplyAnimationCopy(shape, lineWidthAnim);
            }
            else
            {
                if (isChecked)
                {
                    shape.StrokeStart = checkStrokeStart;
                    shape.StrokeEnd   = checkStrokeEnd;
                    shape.LineWidth   = lineWidthBold;
                }
                else
                {
                    shape.StrokeStart = circleStrokeStart;
                    shape.StrokeEnd   = circleStrokeEnd;
                    shape.LineWidth   = lineWidth;
                }
            }

            OnCheckedChanged();
        }
        // Create a carousel of 3D primitives
        private void PresentPrimitives()
        {
            // Create the carousel node. It will host all the primitives as child nodes.
            CarouselNode          = SCNNode.Create();
            CarouselNode.Position = new SCNVector3(0, 0.1f, -5);
            CarouselNode.Scale    = new SCNVector3(0, 0, 0);           // start infinitely small
            ContentNode.AddChildNode(CarouselNode);

            // Animate the scale to achieve a "grow" effect
            SCNTransaction.Begin();
            SCNTransaction.AnimationDuration = 1;
            CarouselNode.Scale = new SCNVector3(1, 1, 1);
            SCNTransaction.Commit();

            // Rotate the carousel forever
            var rotationAnimation = CABasicAnimation.FromKeyPath("rotation");

            rotationAnimation.Duration    = 40.0f;
            rotationAnimation.RepeatCount = float.MaxValue;
            rotationAnimation.To          = NSValue.FromVector(new SCNVector4(0, 1, 0, NMath.PI * 2));
            CarouselNode.AddAnimation(rotationAnimation, new NSString("rotationAnimation"));

            // A material shared by all the primitives
            var sharedMaterial = SCNMaterial.Create();

            sharedMaterial.Reflective.Contents  = new NSImage(NSBundle.MainBundle.PathForResource("SharedTextures/envmap", "jpg"));
            sharedMaterial.Reflective.Intensity = 0.2f;
            sharedMaterial.DoubleSided          = true;

            PrimitiveIndex = 0;

            // SCNBox
            var box = SCNBox.Create(5.0f, 5.0f, 5.0f, 5.0f * 0.05f);

            box.WidthSegmentCount   = 4;
            box.HeightSegmentCount  = 4;
            box.LengthSegmentCount  = 4;
            box.ChamferSegmentCount = 4;
            AddPrimitive(box, 5.0f / 2, rotationAnimation, sharedMaterial);

            // SCNPyramid
            var pyramid = SCNPyramid.Create(5.0f * 0.8f, 5.0f, 5.0f * 0.8f);

            pyramid.WidthSegmentCount  = 4;
            pyramid.HeightSegmentCount = 10;
            pyramid.LengthSegmentCount = 4;
            AddPrimitive(pyramid, 0, rotationAnimation, sharedMaterial);

            // SCNCone
            var cone = SCNCone.Create(0, 5.0f / 2, 5.0f);

            cone.RadialSegmentCount = 20;
            cone.HeightSegmentCount = 4;
            AddPrimitive(cone, 5.0f / 2, rotationAnimation, sharedMaterial);

            // SCNTube
            var tube = SCNTube.Create(5.0f * 0.25f, 5.0f * 0.5f, 5.0f);

            tube.HeightSegmentCount = 5;
            tube.RadialSegmentCount = 40;
            AddPrimitive(tube, 5.0f / 2, rotationAnimation, sharedMaterial);

            // SCNCapsule
            var capsule = SCNCapsule.Create(5.0f * 0.4f, 5.0f * 1.4f);

            capsule.HeightSegmentCount = 5;
            capsule.RadialSegmentCount = 20;
            AddPrimitive(capsule, 5.0f * 0.7f, rotationAnimation, sharedMaterial);

            // SCNCylinder
            var cylinder = SCNCylinder.Create(5.0f * 0.5f, 5.0f);

            cylinder.HeightSegmentCount = 5;
            cylinder.RadialSegmentCount = 40;
            AddPrimitive(cylinder, 5.0f / 2, rotationAnimation, sharedMaterial);

            // SCNSphere
            var sphere = SCNSphere.Create(5.0f * 0.5f);

            sphere.SegmentCount = 20;
            AddPrimitive(sphere, 5.0f / 2, rotationAnimation, sharedMaterial);

            // SCNTorus
            var torus = SCNTorus.Create(5.0f * 0.5f, 5.0f * 0.25f);

            torus.RingSegmentCount = 40;
            torus.PipeSegmentCount = 20;
            AddPrimitive(torus, 5.0f / 4, rotationAnimation, sharedMaterial);

            // SCNPlane
            var plane = SCNPlane.Create(5.0f, 5.0f);

            plane.WidthSegmentCount  = 5;
            plane.HeightSegmentCount = 5;
            plane.CornerRadius       = 5.0f * 0.1f;
            AddPrimitive(plane, 5.0f / 2, rotationAnimation, sharedMaterial);
        }
Example #19
0
        void Setup()
        {
            // create a new scene
            var scene = SCNScene.FromFile("art.scnassets/ship");

            // create and add a camera to the scene
            var cameraNode = SCNNode.Create();

            cameraNode.Camera = SCNCamera.Create();
            scene.RootNode.AddChildNode(cameraNode);

            // place the camera
            cameraNode.Position = new SCNVector3(0, 0, 15);

            // create and add a light to the scene
            var lightNode = SCNNode.Create();

            lightNode.Light           = SCNLight.Create();
            lightNode.Light.LightType = SCNLightType.Omni;
            lightNode.Position        = new SCNVector3(0, 10, 10);
            scene.RootNode.AddChildNode(lightNode);

            // create and add an ambient light to the scene
            var ambientLightNode = SCNNode.Create();

            ambientLightNode.Light           = SCNLight.Create();
            ambientLightNode.Light.LightType = SCNLightType.Ambient;
            ambientLightNode.Light.Color     = SKColor.DarkGray;
            scene.RootNode.AddChildNode(ambientLightNode);

            // retrieve the ship node
            var ship = scene.RootNode.FindChildNode("ship", true);

            // animate the 3d object
#if __IOS__
            ship.RunAction(SCNAction.RepeatActionForever(SCNAction.RotateBy(0, 2, 0, 1)));
#else
            var animation = CABasicAnimation.FromKeyPath("rotation");
            animation.To          = NSValue.FromVector(new SCNVector4(0, 1, 0, NMath.PI * 2));
            animation.Duration    = 3;
            animation.RepeatCount = float.MaxValue; //repeat forever
            ship.AddAnimation(animation, null);
#endif

            // retrieve the SCNView
            var scnView = (SCNView)View;

            // set the scene to the view
            scnView.Scene = scene;

            // allows the user to manipulate the camera
            scnView.AllowsCameraControl = true;

            // show statistics such as fps and timing information
            scnView.ShowsStatistics = true;

            // configure the view
            scnView.BackgroundColor = SKColor.Black;

#if __IOS__
            // add a tap gesture recognizer
            var tapGesture         = new UITapGestureRecognizer(HandleTap);
            var gestureRecognizers = new List <UIGestureRecognizer> ();
            gestureRecognizers.Add(tapGesture);
            gestureRecognizers.AddRange(scnView.GestureRecognizers);
            scnView.GestureRecognizers = gestureRecognizers.ToArray();
#endif
        }
Example #20
0
 public void AnimationDidStart (CABasicAnimation anim)
 {
     if (_animationTimer == null) {
         const double timeInterval = 1.0f / 60.0f;
         _animationTimer = NSTimer.CreateTimer (timeInterval, this, new Selector ("updateTimerFired:"),null, true);
         NSRunLoop.Main.AddTimer (_animationTimer, NSRunLoopMode.Common);
     }
     _animations.Add (anim);
 }
        public override void PresentStep(int index, PresentationViewController presentationViewController)
        {
            switch (index)
            {
            case 0:
                // Set the slide's title and subtitle
                TextManager.SetTitle("Scene Graph");
                TextManager.SetSubtitle("Summary");
                break;

            case 1:
                // A node that will help visualize the position of the stars
                WireframeBoxNode          = SCNNode.Create();
                WireframeBoxNode.Rotation = new SCNVector4(0, 1, 0, (float)(Math.PI / 4));
                WireframeBoxNode.Geometry = SCNBox.Create(1, 1, 1, 0);
                WireframeBoxNode.Geometry.FirstMaterial.Diffuse.Contents  = new NSImage(NSBundle.MainBundle.PathForResource("SharedTextures/box_wireframe", "png"));
                WireframeBoxNode.Geometry.FirstMaterial.LightingModelName = SCNLightingModel.Constant; // no lighting
                WireframeBoxNode.Geometry.FirstMaterial.DoubleSided       = true;                      // double sided

                // Sun
                SunNode          = SCNNode.Create();
                SunNode.Position = new SCNVector3(0, 30, 0);
                ContentNode.AddChildNode(SunNode);
                SunNode.AddChildNode((SCNNode)WireframeBoxNode.Copy());

                // Earth-rotation (center of rotation of the Earth around the Sun)
                var earthRotationNode = SCNNode.Create();
                SunNode.AddChildNode(earthRotationNode);

                // Earth-group (will contain the Earth, and the Moon)
                EarthGroupNode          = SCNNode.Create();
                EarthGroupNode.Position = new SCNVector3(15, 0, 0);
                earthRotationNode.AddChildNode(EarthGroupNode);

                // Earth
                EarthNode          = (SCNNode)WireframeBoxNode.Copy();
                EarthNode.Position = new SCNVector3(0, 0, 0);
                EarthGroupNode.AddChildNode(EarthNode);

                // Rotate the Earth around the Sun
                var animation = CABasicAnimation.FromKeyPath("rotation");
                animation.Duration    = 10.0f;
                animation.To          = NSValue.FromVector(new SCNVector4(0, 1, 0, (float)(Math.PI * 2)));
                animation.RepeatCount = float.MaxValue;
                earthRotationNode.AddAnimation(animation, new NSString("earth rotation around sun"));

                // Rotate the Earth
                animation             = CABasicAnimation.FromKeyPath("rotation");
                animation.Duration    = 1.0f;
                animation.From        = NSValue.FromVector(new SCNVector4(0, 1, 0, 0));
                animation.To          = NSValue.FromVector(new SCNVector4(0, 1, 0, (float)(Math.PI * 2)));
                animation.RepeatCount = float.MaxValue;
                EarthNode.AddAnimation(animation, new NSString("earth rotation"));
                break;

            case 2:
                // Moon-rotation (center of rotation of the Moon around the Earth)
                var moonRotationNode = SCNNode.Create();
                EarthGroupNode.AddChildNode(moonRotationNode);

                // Moon
                MoonNode          = (SCNNode)WireframeBoxNode.Copy();
                MoonNode.Position = new SCNVector3(5, 0, 0);
                moonRotationNode.AddChildNode(MoonNode);

                // Rotate the moon around the Earth
                animation             = CABasicAnimation.FromKeyPath("rotation");
                animation.Duration    = 1.5f;
                animation.To          = NSValue.FromVector(new SCNVector4(0, 1, 0, (float)(Math.PI * 2)));
                animation.RepeatCount = float.MaxValue;
                moonRotationNode.AddAnimation(animation, new NSString("moon rotation around earth"));

                // Rotate the moon
                animation             = CABasicAnimation.FromKeyPath("rotation");
                animation.Duration    = 1.5f;
                animation.To          = NSValue.FromVector(new SCNVector4(0, 1, 0, (float)(Math.PI * 2)));
                animation.RepeatCount = float.MaxValue;
                MoonNode.AddAnimation(animation, new NSString("moon rotation"));
                break;

            case 3:
                // Add geometries (spheres) to represent the stars
                SunNode.Geometry   = SCNSphere.Create(2.5f);
                EarthNode.Geometry = SCNSphere.Create(1.5f);
                MoonNode.Geometry  = SCNSphere.Create(0.75f);

                // Add a textured plane to represent Earth's orbit
                var earthOrbit = SCNNode.Create();
                earthOrbit.Opacity  = 0.4f;
                earthOrbit.Geometry = SCNPlane.Create(31, 31);
                earthOrbit.Geometry.FirstMaterial.Diffuse.Contents  = new NSImage(NSBundle.MainBundle.PathForResource("Scenes/earth/orbit", "png"));
                earthOrbit.Geometry.FirstMaterial.Diffuse.MipFilter = SCNFilterMode.Linear;
                earthOrbit.Rotation = new SCNVector4(1, 0, 0, -(float)(Math.PI / 2));
                earthOrbit.Geometry.FirstMaterial.LightingModelName = SCNLightingModel.Constant;                 // no lighting
                SunNode.AddChildNode(earthOrbit);
                break;

            case 4:
                // Add a halo to the Sun (a simple textured plane that does not write to depth)
                SunHaloNode          = SCNNode.Create();
                SunHaloNode.Geometry = SCNPlane.Create(30, 30);
                SunHaloNode.Rotation = new SCNVector4(1, 0, 0, Pitch * (float)(Math.PI / 180.0f));
                SunHaloNode.Geometry.FirstMaterial.Diffuse.Contents    = new NSImage(NSBundle.MainBundle.PathForResource("Scenes/earth/sun-halo", "png"));
                SunHaloNode.Geometry.FirstMaterial.LightingModelName   = SCNLightingModel.Constant; // no lighting
                SunHaloNode.Geometry.FirstMaterial.WritesToDepthBuffer = false;                     // do not write to depth
                SunHaloNode.Opacity = 0.2f;
                SunNode.AddChildNode(SunHaloNode);

                // Add materials to the stars
                EarthNode.Geometry.FirstMaterial.Diffuse.Contents  = new NSImage(NSBundle.MainBundle.PathForResource("Scenes/earth/earth-diffuse-mini", "jpg"));
                EarthNode.Geometry.FirstMaterial.Emission.Contents = new NSImage(NSBundle.MainBundle.PathForResource("Scenes/earth/earth-emissive-mini", "jpg"));
                EarthNode.Geometry.FirstMaterial.Specular.Contents = new NSImage(NSBundle.MainBundle.PathForResource("Scenes/earth/earth-specular-mini", "jpg"));
                MoonNode.Geometry.FirstMaterial.Diffuse.Contents   = new NSImage(NSBundle.MainBundle.PathForResource("Scenes/earth/moon", "jpg"));
                SunNode.Geometry.FirstMaterial.Multiply.Contents   = new NSImage(NSBundle.MainBundle.PathForResource("Scenes/earth/sun", "jpg"));
                SunNode.Geometry.FirstMaterial.Diffuse.Contents    = new NSImage(NSBundle.MainBundle.PathForResource("Scenes/earth/sun", "jpg"));
                SunNode.Geometry.FirstMaterial.Multiply.Intensity  = 0.5f;
                SunNode.Geometry.FirstMaterial.LightingModelName   = SCNLightingModel.Constant;

                SunNode.Geometry.FirstMaterial.Multiply.WrapS            =
                    SunNode.Geometry.FirstMaterial.Diffuse.WrapS         =
                        SunNode.Geometry.FirstMaterial.Multiply.WrapT    =
                            SunNode.Geometry.FirstMaterial.Diffuse.WrapT = SCNWrapMode.Repeat;

                EarthNode.Geometry.FirstMaterial.LocksAmbientWithDiffuse       =
                    MoonNode.Geometry.FirstMaterial.LocksAmbientWithDiffuse    =
                        SunNode.Geometry.FirstMaterial.LocksAmbientWithDiffuse = true;

                EarthNode.Geometry.FirstMaterial.Shininess          = 0.1f;
                EarthNode.Geometry.FirstMaterial.Specular.Intensity = 0.5f;
                MoonNode.Geometry.FirstMaterial.Specular.Contents   = NSColor.Gray;

                // Achieve a lava effect by animating textures
                animation          = CABasicAnimation.FromKeyPath("contentsTransform");
                animation.Duration = 10.0f;

                var animationTransform1 = CATransform3D.MakeTranslation(0, 0, 0);
                animationTransform1 = animationTransform1.Concat(CATransform3D.MakeScale(3, 3, 3));
                var animationTransform2 = CATransform3D.MakeTranslation(1, 0, 0);
                animationTransform2 = animationTransform1.Concat(CATransform3D.MakeScale(3, 3, 3));

                animation.From        = NSValue.FromCATransform3D(animationTransform1);
                animation.To          = NSValue.FromCATransform3D(animationTransform2);
                animation.RepeatCount = float.MaxValue;
                SunNode.Geometry.FirstMaterial.Diffuse.AddAnimation(animation, new NSString("sun-texture"));

                animation          = CABasicAnimation.FromKeyPath("contentsTransform");
                animation.Duration = 30.0f;

                animationTransform1 = CATransform3D.MakeTranslation(0, 0, 0);
                animationTransform1 = animationTransform1.Concat(CATransform3D.MakeScale(5, 5, 5));
                animationTransform2 = CATransform3D.MakeTranslation(1, 0, 0);
                animationTransform2 = animationTransform1.Concat(CATransform3D.MakeScale(5, 5, 5));

                animation.From        = NSValue.FromCATransform3D(animationTransform1);
                animation.To          = NSValue.FromCATransform3D(animationTransform2);
                animation.RepeatCount = float.MaxValue;
                SunNode.Geometry.FirstMaterial.Multiply.AddAnimation(animation, new NSString("sun-texture2"));
                break;

            case 5:
                // We will turn off all the lights in the scene and add a new light
                // to give the impression that the Sun lights the scene
                var lightNode = SCNNode.Create();
                lightNode.Light           = SCNLight.Create();
                lightNode.Light.Color     = NSColor.Black;             // initially switched off
                lightNode.Light.LightType = SCNLightType.Omni;
                SunNode.AddChildNode(lightNode);

                // Configure attenuation distances because we don't want to light the floor
                lightNode.Light.SetAttribute(new NSNumber(20), SCNLightAttribute.AttenuationEndKey);
                lightNode.Light.SetAttribute(new NSNumber(19.5), SCNLightAttribute.AttenuationStartKey);

                // Animation
                SCNTransaction.Begin();
                SCNTransaction.AnimationDuration = 1;
                lightNode.Light.Color            = NSColor.White;                               // switch on
                presentationViewController.UpdateLightingWithIntensities(new float[] { 0.0f }); //switch off all the other lights
                SunHaloNode.Opacity = 0.5f;                                                     // make the halo stronger
                SCNTransaction.Commit();
                break;
            }
        }
Example #22
0
        public override void PresentStep(int index, PresentationViewController presentationViewController)
        {
            SCNTransaction.Begin();

            switch (index)
            {
            case 1:
                TextManager.FlipOutText(SlideTextManager.TextType.Bullet);

                TextManager.SetSubtitle("API");

                TextManager.AddEmptyLine();
                TextManager.AddCode("#aMaterial.#ShaderModifiers# = new SCNShaderModifiers {\n"
                                    + "     <Entry Point> = <GLSL Code>\n"
                                    + "};#");
                TextManager.FlipInText(SlideTextManager.TextType.Code);
                TextManager.FlipInText(SlideTextManager.TextType.Subtitle);

                break;

            case 2:
                TextManager.FlipOutText(SlideTextManager.TextType.Code);

                TextManager.AddEmptyLine();
                TextManager.AddCode("#aMaterial.#ShaderModifiers# = new SCNShaderModifiers { \n"
                                    + "     EntryCGPointragment = \n"
                                    + "     new Vector3 (1.0f) - #output#.Color.GetRgb () \n"
                                    + "};#");

                TextManager.FlipInText(SlideTextManager.TextType.Code);

                break;

            case 3:
                TextManager.FlipOutText(SlideTextManager.TextType.Code);
                TextManager.FlipOutText(SlideTextManager.TextType.Subtitle);

                TextManager.SetSubtitle("Entry points");

                TextManager.AddBulletAtLevel("Geometry", 0);
                TextManager.AddBulletAtLevel("Surface", 0);
                TextManager.AddBulletAtLevel("Lighting", 0);
                TextManager.AddBulletAtLevel("Fragment", 0);
                TextManager.FlipInText(SlideTextManager.TextType.Bullet);
                TextManager.FlipInText(SlideTextManager.TextType.Subtitle);

                break;

            case 4:
                SCNTransaction.AnimationDuration = 1;

                TextManager.HighlightBullet(0);

                // Create a (very) tesselated plane
                var plane = SCNPlane.Create(10, 10);
                plane.WidthSegmentCount  = 200;
                plane.HeightSegmentCount = 200;

                // Setup the material (same as the floor)
                plane.FirstMaterial.Diffuse.WrapS             = SCNWrapMode.Mirror;
                plane.FirstMaterial.Diffuse.WrapT             = SCNWrapMode.Mirror;
                plane.FirstMaterial.Diffuse.Contents          = new NSImage("/Library/Desktop Pictures/Circles.jpg");
                plane.FirstMaterial.Diffuse.ContentsTransform = SCNMatrix4.CreateFromAxisAngle(new SCNVector3(0, 0, 1), NMath.PI / 4);
                plane.FirstMaterial.Specular.Contents         = NSColor.White;
                plane.FirstMaterial.Reflective.Contents       = new NSImage(NSBundle.MainBundle.PathForResource("SharedTextures/envmap", "jpg"));
                plane.FirstMaterial.Reflective.Intensity      = 0.0f;

                // Create a node to hold that plane
                PlaneNode          = SCNNode.Create();
                PlaneNode.Position = new SCNVector3(0, 0.1f, 0);
                PlaneNode.Rotation = new SCNVector4(1, 0, 0, -(float)(Math.PI / 2));
                PlaneNode.Scale    = new SCNVector3(5, 5, 1);
                PlaneNode.Geometry = plane;
                ContentNode.AddChildNode(PlaneNode);

                // Attach the "wave" shader modifier, and set an initial intensity value of 0
                var shaderFile       = NSBundle.MainBundle.PathForResource("Shaders/wave", "shader");
                var geometryModifier = File.ReadAllText(shaderFile);
                PlaneNode.Geometry.ShaderModifiers = new SCNShaderModifiers {
                    EntryPointGeometry = geometryModifier
                };
                PlaneNode.Geometry.SetValueForKey(new NSNumber(0.0f), new NSString("intensity"));

                SCNTransaction.Begin();
                SCNTransaction.AnimationDuration = 0;
                // Show the pseudo code for the deformation
                var textNode = TextManager.AddCode("#float len = #geometry#.Position.Xy.Length;\n"
                                                   + "aMaterial.ShaderModifiers = new SCNShaderModifiers { \n"
                                                   + "     #EntryPointGeometry# = geometry.Position.Y \n"
                                                   + "};#");

                textNode.Position = new SCNVector3(8.5f, 7, 0);
                SCNTransaction.Commit();
                break;

            case 5:
                // Progressively increase the intensity
                SCNTransaction.Begin();
                SCNTransaction.AnimationDuration = 2;
                PlaneNode.Geometry.SetValueForKey(new NSNumber(1.0f), new NSString("intensity"));
                PlaneNode.Geometry.FirstMaterial.Reflective.Intensity = 0.3f;
                SCNTransaction.Commit();

                // Redraw forever
                ((SCNView)presentationViewController.View).Playing = true;
                ((SCNView)presentationViewController.View).Loops   = true;
                break;

            case 6:
                SCNTransaction.AnimationDuration = 1;

                TextManager.FadeOutText(SlideTextManager.TextType.Code);

                // Hide the plane used for the previous modifier
                PlaneNode.Geometry.SetValueForKey(new NSNumber(0.0f), new NSString("intensity"));
                PlaneNode.Geometry.FirstMaterial.Reflective.Intensity = 0.0f;
                PlaneNode.Opacity = 0.0f;

                // Create a sphere to illustrate the "car paint" modifier
                var sphere = SCNSphere.Create(6);
                sphere.SegmentCount = 100;
                sphere.FirstMaterial.Diffuse.Contents    = new NSImage(NSBundle.MainBundle.PathForResource("SharedTextures/noise", "png"));
                sphere.FirstMaterial.Diffuse.WrapS       = SCNWrapMode.Repeat;
                sphere.FirstMaterial.Diffuse.WrapT       = SCNWrapMode.Repeat;
                sphere.FirstMaterial.Reflective.Contents = new NSImage(NSBundle.MainBundle.PathForResource("SharedTextures/envmap3", "jpg"));
                sphere.FirstMaterial.FresnelExponent     = 1.3f;

                SphereNode          = SCNNode.FromGeometry(sphere);
                SphereNode.Position = new SCNVector3(5, 6, 0);
                GroundNode.AddChildNode(SphereNode);

                // Attach the "car paint" shader modifier
                shaderFile = NSBundle.MainBundle.PathForResource("Shaders/carPaint", "shader");
                var surfaceModifier = File.ReadAllText(shaderFile);
                sphere.FirstMaterial.ShaderModifiers = new SCNShaderModifiers {
                    EntryPointSurface = surfaceModifier
                };

                var rotationAnimation = CABasicAnimation.FromKeyPath("rotation");
                rotationAnimation.Duration    = 15.0f;
                rotationAnimation.RepeatCount = float.MaxValue;
                rotationAnimation.By          = NSValue.FromVector(new SCNVector4(0, 1, 0, -(float)(Math.PI * 2)));
                SphereNode.AddAnimation(rotationAnimation, new NSString("sphereNodeAnimation"));

                TextManager.HighlightBullet(1);
                break;

            case 7:
                SCNTransaction.Begin();
                SCNTransaction.AnimationDuration       = 1.5f;
                SCNTransaction.AnimationTimingFunction = CAMediaTimingFunction.FromName(CAMediaTimingFunction.EaseInEaseOut);
                // Move the camera closer
                presentationViewController.CameraNode.Position = new SCNVector3(5, -0.5f, -17);
                SCNTransaction.Commit();
                break;

            case 8:
                SCNTransaction.Begin();
                SCNTransaction.AnimationDuration       = 1.0f;
                SCNTransaction.AnimationTimingFunction = CAMediaTimingFunction.FromName(CAMediaTimingFunction.EaseInEaseOut);
                // Move back
                presentationViewController.CameraNode.Position = new SCNVector3(0, 0, 0);
                SCNTransaction.Commit();
                break;

            case 9:
                SCNTransaction.Begin();
                SCNTransaction.AnimationDuration = 1.0f;
                // Hide the sphere used for the previous modifier
                SphereNode.Opacity  = 0.0f;
                SphereNode.Position = new SCNVector3(6, 4, -8);
                SCNTransaction.Commit();

                SCNTransaction.AnimationDuration = 0;

                TextManager.HighlightBullet(2);

                // Load the model, animate
                var intermediateNode = SCNNode.Create();
                intermediateNode.Position = new SCNVector3(4, 0.1f, 10);
                TorusNode = Utils.SCAddChildNode(intermediateNode, "torus", "Scenes/torus/torus", 11);

                rotationAnimation             = CABasicAnimation.FromKeyPath("rotation");
                rotationAnimation.Duration    = 10.0f;
                rotationAnimation.RepeatCount = float.MaxValue;
                rotationAnimation.To          = NSValue.FromVector(new SCNVector4(0, 1, 0, (float)(Math.PI * 2)));
                TorusNode.AddAnimation(rotationAnimation, new NSString("torusNodeAnimation"));

                GroundNode.AddChildNode(intermediateNode);

                SCNTransaction.Begin();
                SCNTransaction.AnimationDuration = 1.0f;
                intermediateNode.Position        = new SCNVector3(4, 0.1f, 0);
                SCNTransaction.Commit();

                break;

            case 10:
                // Attach the shader modifier
                shaderFile = NSBundle.MainBundle.PathForResource("Shaders/toon", "shader");
                var lightingModifier = File.ReadAllText(shaderFile);
                TorusNode.Geometry.ShaderModifiers = new SCNShaderModifiers {
                    EntryPointLightingModel = lightingModifier
                };
                break;

            case 11:
                SCNTransaction.AnimationDuration = 1.0f;

                // Hide the torus used for the previous modifier
                TorusNode.Position = new SCNVector3(TorusNode.Position.X, TorusNode.Position.Y, TorusNode.Position.Z - 10);
                TorusNode.Opacity  = 0.0f;

                // Load the model, animate
                intermediateNode          = SCNNode.Create();
                intermediateNode.Position = new SCNVector3(4, -2.6f, 14);
                intermediateNode.Scale    = new SCNVector3(70, 70, 70);

                XRayNode          = Utils.SCAddChildNode(intermediateNode, "node", "Scenes/bunny", 12);
                XRayNode.Position = new SCNVector3(0, 0, 0);
                XRayNode.Opacity  = 0.0f;

                GroundNode.AddChildNode(intermediateNode);

                rotationAnimation             = CABasicAnimation.FromKeyPath("rotation");
                rotationAnimation.Duration    = 10.0f;
                rotationAnimation.RepeatCount = float.MaxValue;
                rotationAnimation.From        = NSValue.FromVector(new SCNVector4(0, 1, 0, 0));
                rotationAnimation.To          = NSValue.FromVector(new SCNVector4(0, 1, 0, (float)(Math.PI * 2)));
                intermediateNode.AddAnimation(rotationAnimation, new NSString("bunnyNodeAnimation"));

                TextManager.HighlightBullet(3);

                SCNTransaction.Begin();
                SCNTransaction.AnimationDuration = 1.0f;
                XRayNode.Opacity          = 1.0f;
                intermediateNode.Position = new SCNVector3(4, -2.6f, -2);
                SCNTransaction.Commit();
                break;

            case 12:
                // Attach the "x ray" modifier
                shaderFile = NSBundle.MainBundle.PathForResource("Shaders/xRay", "shader");
                var fragmentModifier = File.ReadAllText(shaderFile);
                XRayNode.Geometry.ShaderModifiers = new SCNShaderModifiers {
                    EntryPointFragment = fragmentModifier
                };
                XRayNode.Geometry.FirstMaterial.ReadsFromDepthBuffer = false;
                break;

            case 13:
                // Highlight everything
                TextManager.HighlightBullet(-1);

                // Hide the node used for the previous modifier
                XRayNode.Opacity             = 0.0f;
                XRayNode.ParentNode.Position = new SCNVector3(4, -2.6f, -5);

                // Create the model
                sphere = SCNSphere.Create(5);
                sphere.SegmentCount = 150;                 // tesselate a lot

                VirusNode          = SCNNode.FromGeometry(sphere);
                VirusNode.Position = new SCNVector3(3, 6, 0);
                VirusNode.Rotation = new SCNVector4(1, 0, 0, Pitch * (float)(Math.PI / 180.0f));
                GroundNode.AddChildNode(VirusNode);

                // Set the shader modifiers
                var geomFile  = NSBundle.MainBundle.PathForResource("Shaders/sm_geom", "shader");
                var surfFile  = NSBundle.MainBundle.PathForResource("Shaders/sm_surf", "shader");
                var lightFile = NSBundle.MainBundle.PathForResource("Shaders/sm_light", "shader");
                var fragFile  = NSBundle.MainBundle.PathForResource("Shaders/sm_frag", "shader");
                geometryModifier = File.ReadAllText(geomFile);
                surfaceModifier  = File.ReadAllText(surfFile);
                lightingModifier = File.ReadAllText(lightFile);
                fragmentModifier = File.ReadAllText(fragFile);
                VirusNode.Geometry.FirstMaterial.ShaderModifiers = new SCNShaderModifiers {
                    EntryPointGeometry      = geometryModifier,
                    EntryPointSurface       = surfaceModifier,
                    EntryPointLightingModel = lightingModifier,
                    EntryPointFragment      = fragmentModifier
                };
                break;

            case 14:
                SCNTransaction.AnimationDuration = 1.0f;

                // Hide the node used for the previous modifier
                VirusNode.Opacity  = 0.0f;
                VirusNode.Position = new SCNVector3(3, 6, -10);

                // Change the text
                TextManager.FadeOutText(SlideTextManager.TextType.Code);
                TextManager.FlipOutText(SlideTextManager.TextType.Bullet);
                TextManager.FlipOutText(SlideTextManager.TextType.Subtitle);

                TextManager.SetSubtitle("SCNShadable");

                TextManager.AddBulletAtLevel("Protocol adopted by SCNMaterial and SCNGeometry", 0);
                TextManager.AddBulletAtLevel("Shaders parameters are animatable", 0);
                TextManager.AddBulletAtLevel("Texture samplers are bound to a SCNMaterialProperty", 0);

                TextManager.AddCode("#var aProperty = SCNMaterialProperty.#Create# (anImage);\n"
                                    + "aMaterial.#SetValueForKey# (aProperty, #new NSString# (\"aSampler\"));#");

                TextManager.FlipInText(SlideTextManager.TextType.Subtitle);
                TextManager.FlipInText(SlideTextManager.TextType.Bullet);
                TextManager.FlipInText(SlideTextManager.TextType.Code);
                break;
            }
            SCNTransaction.Commit();
        }
Example #23
0
        private void Animate(CALayer layer, float from, float to, float delayMilliseconds, float durationMilliseconds)
        {
            if (_isDiscrete)
            {
                var animation = CAKeyFrameAnimation.FromKeyPath(_property);
                animation.KeyTimes        = new NSNumber[] { new NSNumber(0.0), new NSNumber(1.0) };
                animation.Values          = new NSObject[] { _nsValueConversion(to) };
                animation.CalculationMode = CAKeyFrameAnimation.AnimationDescrete;
                _animation = animation;
            }
            else
            {
                var animation = CABasicAnimation.FromKeyPath(_property);
                animation.From           = _nsValueConversion(from);
                animation.To             = _nsValueConversion(to);
                animation.TimingFunction = _timingFunction;
                _animation = animation;
            }

            if (delayMilliseconds > 0)
            {
                // Note: We must make sure to use the time relative to the 'layer', otherwise we might introduce a random delay and the animations
                //		 will run twice (once "managed" while updating the DP, and a second "native" using this animator)
                _animation.BeginTime = layer.ConvertTimeFromLayer(CAAnimation.CurrentMediaTime() + delayMilliseconds / __millisecondsPerSecond, null);
            }
            _animation.Duration            = durationMilliseconds / __millisecondsPerSecond;
            _animation.FillMode            = CAFillMode.Forwards;
            _animation.RemovedOnCompletion = false;

            if (this.Log().IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug))
            {
                this.Log().DebugFormat("CoreAnimation on property {0} from {1} to {2} is starting.", _property, from, to);
            }

            _onAnimationStarted = (s, e) =>
            {
                // This will disable the transform while the native animation handles it
                // It must be the first thing we do when the animation starts
                // (However we have to wait for the first frame in order to not remove the transform while waiting for the BeginTime)
                _prepare?.Invoke();

                var anim = s as CAAnimation;

                if (anim == null)
                {
                    return;
                }

                if (this.Log().IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug))
                {
                    this.Log().DebugFormat("CoreAnimation on property {0} from {1} to {2} started.", _property, from, to);
                }

                anim.AnimationStarted -= _onAnimationStarted;
                anim.AnimationStopped += _onAnimationStopped;
            };

            _onAnimationStopped = (s, e) =>
            {
                var anim = s as CAAnimation;

                if (anim == null)
                {
                    return;
                }

                CATransaction.Begin();
                CATransaction.DisableActions = true;
                layer.SetValueForKeyPath(_nsValueConversion(to), new NSString(_property));
                CATransaction.Commit();
                _cleanup?.Invoke();

                anim.AnimationStopped -= _onAnimationStopped;

                if (e.Finished)
                {
                    if (this.Log().IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug))
                    {
                        this.Log().DebugFormat("CoreAnimation on property {0} from {1} to {2} finished.", _property, from, to);
                    }

                    _onFinish();

                    ExecuteIfLayer(l => l.RemoveAnimation(_key));
                }
                else
                {
                    if (this.Log().IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug))
                    {
                        this.Log().DebugFormat("CoreAnimation on property {0} from {1} to {2} stopped before finishing.", _property, from, to);
                    }

                    anim.AnimationStarted += _onAnimationStarted;
                }
            };

            _animation.AnimationStarted += _onAnimationStarted;

            layer.AddAnimation(_animation, _key);
        }
        void LayoutSidebar(bool animate, bool cancelExisting = false)
        {
            if (_gestureActive)
            {
                return;
            }

            if (cancelExisting && _flyoutAnimation != null)
            {
                _flyoutAnimation.StopAnimation(true);
                _flyoutAnimation = null;
            }

            if (animate && _flyoutAnimation != null)
            {
                return;
            }

            if (!animate && _flyoutAnimation != null)
            {
                _flyoutAnimation.StopAnimation(true);
                _flyoutAnimation = null;
            }

            if (Forms.IsiOS10OrNewer)
            {
                if (IsOpen)
                {
                    UpdateTapoffView();
                }

                if (animate && TapoffView != null)
                {
                    var tapOffViewAnimation = CABasicAnimation.FromKeyPath(@"opacity");
                    tapOffViewAnimation.BeginTime = 0;
                    tapOffViewAnimation.Duration  = AnimationDurationInSeconds;
                    tapOffViewAnimation.SetFrom(NSNumber.FromFloat(TapoffView.Layer.Opacity));
                    tapOffViewAnimation.SetTo(NSNumber.FromFloat(IsOpen ? 1 : 0));
                    tapOffViewAnimation.FillMode            = CAFillMode.Forwards;
                    tapOffViewAnimation.RemovedOnCompletion = false;

                    _flyoutAnimation = new UIViewPropertyAnimator(AnimationDurationInSeconds, UIViewAnimationCurve.EaseOut, () =>
                    {
                        FlyoutTransition.LayoutViews(View.Bounds, IsOpen ? 1 : 0, Flyout.ViewController.View, Detail.View, _flyoutBehavior);

                        if (TapoffView != null)
                        {
                            TapoffView.Layer.AddAnimation(tapOffViewAnimation, "opacity");
                        }
                    });

                    _flyoutAnimation.AddCompletion((p) =>
                    {
                        if (p == UIViewAnimatingPosition.End)
                        {
                            if (TapoffView != null)
                            {
                                TapoffView.Layer.Opacity = IsOpen ? 1 : 0;
                                TapoffView.Layer.RemoveAllAnimations();
                            }

                            UpdateTapoffView();
                            _flyoutAnimation = null;
                        }
                    });

                    _flyoutAnimation.StartAnimation();
                    View.LayoutIfNeeded();
                }
                else if (_flyoutAnimation == null)
                {
                    FlyoutTransition.LayoutViews(View.Bounds, IsOpen ? 1 : 0, Flyout.ViewController.View, Detail.View, _flyoutBehavior);
                    UpdateTapoffView();

                    if (TapoffView != null)
                    {
                        TapoffView.Layer.Opacity = IsOpen ? 1 : 0;
                    }
                }
            }
            else
            {
                if (animate)
                {
                    UIView.BeginAnimations(FlyoutAnimationName);
                }

                FlyoutTransition.LayoutViews(View.Bounds, IsOpen ? 1 : 0, Flyout.ViewController.View, Detail.View, _flyoutBehavior);

                if (animate)
                {
                    UIView.SetAnimationCurve(AnimationCurve);
                    UIView.SetAnimationDuration(AnimationDurationInSeconds);
                    UIView.CommitAnimations();
                    View.LayoutIfNeeded();
                }
                UpdateTapoffView();
            }

            void UpdateTapoffView()
            {
                if (IsOpen && _flyoutBehavior == FlyoutBehavior.Flyout)
                {
                    AddTapoffView();
                }
                else
                {
                    RemoveTapoffView();
                }
            }
        }
Example #25
0
		void drawLines ()
		{
			layer.RemoveAllAnimations ();

			var dot = new CGRect (0, 0, lineWidth, lineWidth);

			nfloat x, y;

			CGPoint start = CGPoint.Empty;
			CGPoint end = CGPoint.Empty;


			// Draw curved graph line
			using (UIColor color = UIColor.White.ColorWithAlpha (0.25f), dotColor = UIColor.White.ColorWithAlpha (0.70f)) {

				//color.SetStroke ();

				//dotColor.SetFill ();

				//ctx.SetLineWidth (lineWidth);

				using (CGPath path = new CGPath ()) {


					var count = hourly ? HourlyTemps.Count : (Forecasts.Count * 2);

					for (int i = 0; i < count; i++) {

						// adjusted index
						var ai = i;

						double temp;

						if (hourly) {

							temp = HourlyTemps [ai];

						} else {

							// reset start when switching from highs to lows
							if (i == Forecasts.Count) start = CGPoint.Empty;

							var highs = i < Forecasts.Count;

							ai = highs ? i : i - Forecasts.Count;

							temp = highs ? HighTemps [ai] : LowTemps [ai];
						}

						var percent = ((nfloat)temp - scaleLow) / scaleRange;


						x = padding + inset + (ai * scaleX);

						y = graphRect.GetMaxY () - (graphRect.Height * percent);

						end = new CGPoint (x, y);


						if (!hourly) {

							dot.X = end.X - (lineWidth / 2);
							dot.Y = end.Y - (lineWidth / 2);

							path.AddEllipseInRect (dot);

							//ctx.AddEllipseInRect (dot);
						}


						if (start == CGPoint.Empty) {

							path.MoveToPoint (end);

						} else {

							path.MoveToPoint (start);

							if (hourly) {

								path.AddLineToPoint (end);

							} else {

								var diff = (end.X - start.X) / 2;

								path.AddCurveToPoint (end.X - diff, start.Y, start.X + diff, end.Y, end.X, end.Y);
							}
						}

						start = end;
					}

					// draw all dots to context
					//if (!hourly) ctx.DrawPath (CGPathDrawingMode.Fill);

					// add line path to context
					layer.Path = path;
					//ctx.AddPath (path);

					// draw lines
					//ctx.DrawPath (CGPathDrawingMode.Stroke);

					layer.LineWidth = lineWidth;
					layer.StrokeColor = color.CGColor;
					layer.FillColor = dotColor.CGColor;

					CABasicAnimation pathAnimation = new CABasicAnimation { KeyPath = "strokeEnd" };
					pathAnimation.Duration = 1.0;
					pathAnimation.From = NSNumber.FromNFloat (0);
					pathAnimation.To = NSNumber.FromNFloat (1);
					layer.AddAnimation (pathAnimation, "strokeEndAnimation");

				}
			}
		}
Example #26
0
        public override void PresentStep(int index, PresentationViewController presentationViewController)
        {
            switch (index)
            {
            case 1:
                // Load the scene
                var intermediateNode = SCNNode.Create();
                intermediateNode.Position = new SCNVector3(0.0f, 0.1f, -24.5f);
                intermediateNode.Scale    = new SCNVector3(2.3f, 1.0f, 1.0f);
                intermediateNode.Opacity  = 0.0f;
                RoomNode = Utils.SCAddChildNode(intermediateNode, "Mesh", "Scenes/cornell-box/cornell-box", 15);
                ContentNode.AddChildNode(intermediateNode);

                // Hide the light maps for now
                foreach (var material in RoomNode.Geometry.Materials)
                {
                    material.Multiply.Intensity = 0.0f;
                    material.LightingModelName  = SCNLightingModel.Blinn;
                }

                // Animate the point of view with an implicit animation.
                // On completion add to move the camera from right to left and back and forth.
                SCNTransaction.Begin();
                SCNTransaction.AnimationDuration = 0.75f;

                SCNTransaction.SetCompletionBlock(() => {
                    SCNTransaction.Begin();
                    SCNTransaction.AnimationDuration = 2;

                    SCNTransaction.SetCompletionBlock(() => {
                        var animation            = CABasicAnimation.FromKeyPath("position");
                        animation.Duration       = 10.0f;
                        animation.Additive       = true;
                        animation.To             = NSValue.FromVector(new SCNVector3(-5, 0, 0));
                        animation.From           = NSValue.FromVector(new SCNVector3(5, 0, 0));
                        animation.TimeOffset     = -animation.Duration / 2;
                        animation.AutoReverses   = true;
                        animation.TimingFunction = CAMediaTimingFunction.FromName(CAMediaTimingFunction.EaseInEaseOut);
                        animation.RepeatCount    = float.MaxValue;

                        presentationViewController.CameraNode.AddAnimation(animation, new NSString("myAnim"));
                    });
                    presentationViewController.CameraHandle.Position = presentationViewController.CameraHandle.ConvertPositionToNode(new SCNVector3(0, +5, -30), presentationViewController.CameraHandle.ParentNode);
                    presentationViewController.CameraPitch.Rotation  = new SCNVector4(1, 0, 0, -(float)(Math.PI / 4) * 0.2f);
                    SCNTransaction.Commit();
                });

                intermediateNode.Opacity = 1.0f;
                SCNTransaction.Commit();
                break;

            case 2:
                // Remove the lighting by using a constant lighing model (no lighting)
                foreach (var material in RoomNode.Geometry.Materials)
                {
                    material.LightingModelName = SCNLightingModel.Constant;
                }
                break;

            case 3:
                // Activate the light maps smoothly
                SCNTransaction.Begin();
                SCNTransaction.AnimationDuration = 1;
                foreach (var material in RoomNode.Geometry.Materials)
                {
                    material.Multiply.Intensity = 1.0f;
                }
                SCNTransaction.Commit();
                break;
            }
        }
		private void AddPrimitive (SCNGeometry geometry, float yPos, CABasicAnimation rotationAnimation, SCNMaterial sharedMaterial)
		{
			var xPos = 13.0f * NMath.Sin (NMath.PI * 2 * PrimitiveIndex / 9.0f);
			var zPos = 13.0f * NMath.Cos (NMath.PI * 2 * PrimitiveIndex / 9.0f);

			var node = SCNNode.Create ();
			node.Position = new SCNVector3 (xPos, yPos, zPos);
			node.Geometry = geometry;
			node.Geometry.FirstMaterial = sharedMaterial;
			CarouselNode.AddChildNode (node);

			PrimitiveIndex++;
			rotationAnimation.TimeOffset = -PrimitiveIndex;
			node.AddAnimation (rotationAnimation, new NSString ("rotationAnimation"));
		}
Example #28
0
        public override void PresentStep(int index, PresentationViewController presentationViewController)
        {
            switch (index)
            {
            case 0:
                // Adjust the near clipping plane of the spotlight to maximize the precision of the dynamic drop shadows
                presentationViewController.SpotLight.Light.SetAttribute(new NSNumber(30), SCNLightAttribute.ShadowNearClippingKey);

                // Show what needs to be shown, hide what needs to be hidden
                PositionsVisualizationNode.Opacity = 1.0f;
                NormalsVisualizationNode.Opacity   = 1.0f;
                TeapotNodeForUVs.Opacity           = 0.0f;
                TeapotNodeForMaterials.Opacity     = 1.0f;

                TeapotNodeForPositionsAndNormals.Opacity = 0.0f;

                // Don't highlight bullets (this is useful when we go back from the next slide)
                TextManager.HighlightBullet(-1);
                break;

            case 1:
                TextManager.HighlightBullet(0);

                // Animate the "explodeValue" parameter (uniform) of the shader modifier
                var explodeAnimation = CABasicAnimation.FromKeyPath("explodeValue");
                explodeAnimation.Duration       = 2.0f;
                explodeAnimation.RepeatCount    = float.MaxValue;
                explodeAnimation.AutoReverses   = true;
                explodeAnimation.To             = new NSNumber(20);
                explodeAnimation.TimingFunction = CAMediaTimingFunction.FromName(CAMediaTimingFunction.EaseInEaseOut);
                TeapotNodeForPositionsAndNormals.Geometry.AddAnimation(explodeAnimation, new NSString("expode"));
                break;

            case 2:
                TextManager.HighlightBullet(1);

                // Remove the "explode" animation and freeze the "explodeValue" parameter to the current value
                SCNTransaction.Begin();
                SCNTransaction.AnimationDuration = 0;
                var explodeValue = TeapotNodeForPositionsAndNormals.PresentationNode.Geometry.ValueForKey(new NSString("explodeValue"));
                TeapotNodeForPositionsAndNormals.Geometry.SetValueForKey(explodeValue, new NSString("explodeValue"));
                TeapotNodeForPositionsAndNormals.Geometry.RemoveAllAnimations();
                SCNTransaction.Commit();

                SCNTransaction.Begin();
                SCNTransaction.AnimationDuration = 1.0f;
                SCNTransaction.SetCompletionBlock(() => {
                    // Animate to a "no explosion" state and show the positions on completion
                    SCNTransaction.Begin();
                    SCNTransaction.AnimationDuration   = 1.0f;
                    PositionsVisualizationNode.Opacity = 1.0f;
                    SCNTransaction.Commit();
                });
                TeapotNodeForPositionsAndNormals.Geometry.SetValueForKey(new NSNumber(0.0f), new NSString("explodeValue"));
                SCNTransaction.Commit();
                break;

            case 3:
                TextManager.HighlightBullet(2);

                SCNTransaction.Begin();
                SCNTransaction.AnimationDuration   = 1.0f;
                PositionsVisualizationNode.Opacity = 0.0f;
                NormalsVisualizationNode.Opacity   = 1.0f;
                SCNTransaction.Commit();
                break;

            case 4:
                TextManager.HighlightBullet(3);

                SCNTransaction.Begin();
                SCNTransaction.AnimationDuration         = 0;
                NormalsVisualizationNode.Hidden          = true;
                TeapotNodeForUVs.Opacity                 = 1.0f;
                TeapotNodeForPositionsAndNormals.Opacity = 0.0f;
                SCNTransaction.Commit();
                break;

            case 5:
                TextManager.HighlightBullet(4);

                SCNTransaction.Begin();
                SCNTransaction.AnimationDuration = 0;
                TeapotNodeForUVs.Hidden          = true;
                TeapotNodeForMaterials.Opacity   = 1.0f;
                SCNTransaction.Commit();
                break;
            }
        }
Example #29
0
        void drawLines()
        {
            layer.RemoveAllAnimations();

            var dot = new CGRect(0, 0, lineWidth, lineWidth);

            nfloat x, y;

            CGPoint start = CGPoint.Empty;
            CGPoint end   = CGPoint.Empty;


            // Draw curved graph line
            using (UIColor color = UIColor.White.ColorWithAlpha(0.25f), dotColor = UIColor.White.ColorWithAlpha(0.70f)) {
                //color.SetStroke ();

                //dotColor.SetFill ();

                //ctx.SetLineWidth (lineWidth);

                using (CGPath path = new CGPath()) {
                    var count = hourly ? HourlyTemps.Count : (Forecasts.Count * 2);

                    for (int i = 0; i < count; i++)
                    {
                        // adjusted index
                        var ai = i;

                        double temp;

                        if (hourly)
                        {
                            temp = HourlyTemps [ai];
                        }
                        else
                        {
                            // reset start when switching from highs to lows
                            if (i == Forecasts.Count)
                            {
                                start = CGPoint.Empty;
                            }

                            var highs = i < Forecasts.Count;

                            ai = highs ? i : i - Forecasts.Count;

                            temp = highs ? HighTemps [ai] : LowTemps [ai];
                        }

                        var percent = ((nfloat)temp - scaleLow) / scaleRange;


                        x = padding + inset + (ai * scaleX);

                        y = graphRect.GetMaxY() - (graphRect.Height * percent);

                        end = new CGPoint(x, y);


                        if (!hourly)
                        {
                            dot.X = end.X - (lineWidth / 2);
                            dot.Y = end.Y - (lineWidth / 2);

                            path.AddEllipseInRect(dot);

                            //ctx.AddEllipseInRect (dot);
                        }


                        if (start == CGPoint.Empty)
                        {
                            path.MoveToPoint(end);
                        }
                        else
                        {
                            path.MoveToPoint(start);

                            if (hourly)
                            {
                                path.AddLineToPoint(end);
                            }
                            else
                            {
                                var diff = (end.X - start.X) / 2;

                                path.AddCurveToPoint(end.X - diff, start.Y, start.X + diff, end.Y, end.X, end.Y);
                            }
                        }

                        start = end;
                    }

                    // draw all dots to context
                    //if (!hourly) ctx.DrawPath (CGPathDrawingMode.Fill);

                    // add line path to context
                    layer.Path = path;
                    //ctx.AddPath (path);

                    // draw lines
                    //ctx.DrawPath (CGPathDrawingMode.Stroke);

                    layer.LineWidth   = lineWidth;
                    layer.StrokeColor = color.CGColor;
                    layer.FillColor   = dotColor.CGColor;

                    CABasicAnimation pathAnimation = new CABasicAnimation {
                        KeyPath = "strokeEnd"
                    };
                    pathAnimation.Duration = 1.0;
                    pathAnimation.From     = NSNumber.FromNFloat(0);
                    pathAnimation.To       = NSNumber.FromNFloat(1);
                    layer.AddAnimation(pathAnimation, "strokeEndAnimation");
                }
            }
        }
Example #30
0
        private void ShowConnectingAnimation(bool isResuming = false)
        {
            if (!NSThread.IsMain)
            {
                InvokeOnMainThread(() => ShowConnectingAnimation(isResuming));
                return;
            }
            // prepare GUI controls
            GuiConnectButtonImage.Hidden = false;
            GuiConnectButtonImage.Image  = Colors.IsDarkMode ? NSImage.ImageNamed("buttonConnectDark") : NSImage.ImageNamed("buttonConnecting");

            if (isResuming == false)
            {
                GuiConnectButtonText.AttributedStringValue = AttributedString.Create(
                    LocalizedStrings.Instance.LocalizedString("Button_Connecting"),
                    Colors.ConnectButtonTextColor,
                    NSTextAlignment.Center);
            }
            else
            {
                GuiConnectButtonText.AttributedStringValue = AttributedString.Create(
                    LocalizedStrings.Instance.LocalizedString("Button_Resuming"),
                    Colors.ConnectButtonTextColor,
                    NSTextAlignment.Center);
            }

            GuiConnectButtonText.AlphaValue = 1f;
            View.IsVisibleCircles           = false;

            // initialize animation
            NSColor startCircleColor = Colors.ConnectiongAnimationCircleColor;

            UpdateToDoLabelHiddenStatus(true);

            __animationLayer.FillColor   = NSColor.Clear.CGColor;
            __animationLayer.StrokeColor = startCircleColor.CGColor;

            var frame       = GuiConnectButtonImage.Frame;
            var startCircle = CGPath.EllipseFromRect(
                new CGRect(frame.X + 6,
                           frame.Y + 6,
                           frame.Width - 12,
                           frame.Height - 12)
                );

            var endCircle = CGPath.EllipseFromRect(
                new CGRect(frame.X + 3,
                           frame.Y + 3,
                           frame.Width - 6,
                           frame.Height - 6)
                );

            CABasicAnimation circleRadiusAnimation = CABasicAnimation.FromKeyPath("path");

            circleRadiusAnimation.From = FromObject(startCircle);
            circleRadiusAnimation.To   = FromObject(endCircle);

            CABasicAnimation lineWidthAnimation = CABasicAnimation.FromKeyPath("lineWidth");

            lineWidthAnimation.From = FromObject(1);
            lineWidthAnimation.To   = FromObject(8);

            CAAnimationGroup animationGroup = new CAAnimationGroup();

            animationGroup.Animations   = new CAAnimation[] { circleRadiusAnimation, lineWidthAnimation };
            animationGroup.Duration     = 1f;
            animationGroup.RepeatCount  = float.PositiveInfinity;
            animationGroup.AutoReverses = true;
            __animationLayer.AddAnimation(animationGroup, null);

            AnimateButtonTextBlinking();
        }
Example #31
0
 public void AnimationDidStop (CABasicAnimation anim, bool isFinished)
 {
     _animations.Remove (anim);
     if (_animations.Count == 0) {
         _animationTimer.Invalidate ();
         _animationTimer = null;
     }
 }
        private void UpdateShimmering()
        {
            CreateMaskIfNeeded();
            if (!Shimmering && _maskLayer == null)
            {
                return;
            }

            LayoutIfNeeded();
            bool disableActions = CATransaction.DisableActions;

            if (!Shimmering)
            {
                if (disableActions)
                {
                    ClearMask();
                }
                else
                {
                    double      slideEndTime   = 0;
                    CAAnimation slideAnimation = _maskLayer.AnimationForKey(ShimmerSlideAnimationKey);
                    if (slideAnimation != null)
                    {
                        double      now = CAAnimation.CurrentMediaTime();
                        double      slideTotalDuration = now - slideAnimation.BeginTime;
                        double      slideTimeOffset    = slideTotalDuration % slideAnimation.Duration;
                        CAAnimation finishAnimation    = ShimmerSlideFinish(slideAnimation);
                        finishAnimation.BeginTime = now - slideTimeOffset;
                        slideEndTime = finishAnimation.BeginTime + slideAnimation.Duration;
                        _maskLayer.AddAnimation(finishAnimation, ShimmerSlideAnimationKey);
                    }

                    CABasicAnimation fadeInAnimation = FadeAnimation(_maskLayer.FadeLayer, 1.0f, ShimmeringEndFadeDuration);
                    fadeInAnimation.AnimationStopped += (sender, e) =>
                    {
                        if (e.Finished && ((NSNumber)fadeInAnimation.ValueForKey(EndFadeAnimationKey)).BoolValue)
                        {
                            ClearMask();
                        }
                    };
                    fadeInAnimation.SetValueForKey(NSNumber.FromBoolean(true), EndFadeAnimationKey);
                    fadeInAnimation.BeginTime = slideEndTime;
                    _maskLayer.FadeLayer.AddAnimation(fadeInAnimation, FadeAnimationKey);
                    ShimmeringFadeTime = slideEndTime;
                }
            }
            else
            {
                CABasicAnimation fadeOutAnimation = null;
                if (ShimmeringBeginFadeDuration > 0.0 && !disableActions)
                {
                    fadeOutAnimation = FadeAnimation(_maskLayer.FadeLayer, 0.0f, ShimmeringBeginFadeDuration);
                    _maskLayer.FadeLayer.AddAnimation(fadeOutAnimation, FadeAnimationKey);
                }
                else
                {
                    bool innerDisableActions = CATransaction.DisableActions;
                    CATransaction.DisableActions = true;
                    _maskLayer.FadeLayer.Opacity = 0.0f;
                    _maskLayer.FadeLayer.RemoveAllAnimations();
                    CATransaction.DisableActions = innerDisableActions;
                }

                CAAnimation slideAnimation = _maskLayer.AnimationForKey(ShimmerSlideAnimationKey);
                nfloat      length         = 0.0f;
                if (_contentLayer != null)
                {
                    if (ShimmeringDirection == ShimmeringDirection.Down || ShimmeringDirection == ShimmeringDirection.Up)
                    {
                        length = _contentLayer.Bounds.Height;
                    }
                    else
                    {
                        length = _contentLayer.Bounds.Width;
                    }
                }

                double animationDuration = (length / ShimmeringSpeed) + ShimmeringPauseDuration;
                if (slideAnimation != null)
                {
                    _maskLayer.AddAnimation(ShimmerSlideRepeat(slideAnimation, animationDuration, ShimmeringDirection), ShimmerSlideAnimationKey);
                }
                else
                {
                    slideAnimation                     = ShimmerSlideAnimation(animationDuration, ShimmeringDirection);
                    slideAnimation.FillMode            = CAFillMode.Forwards;
                    slideAnimation.RemovedOnCompletion = false;
                    if (ShimmeringBeginTime == double.MaxValue)
                    {
                        ShimmeringBeginTime = CAAnimation.CurrentMediaTime() + fadeOutAnimation.Duration;
                    }

                    slideAnimation.BeginTime = ShimmeringBeginTime;
                    _maskLayer.AddAnimation(slideAnimation, ShimmerSlideAnimationKey);
                }
            }
        }
Example #33
0
        private void Animate(CALayer layer, float from, float to, float delayMilliseconds, float durationMilliseconds)
        {
            if (_isDiscrete)
            {
                var animation = CAKeyFrameAnimation.FromKeyPath(_property);
                animation.KeyTimes        = new NSNumber[] { new NSNumber(0.0), new NSNumber(1.0) };
                animation.Values          = new NSObject[] { _nsValueConversion(to) };
                animation.CalculationMode = CAKeyFrameAnimation.AnimationDescrete;
                _animation = animation;
            }
            else
            {
                var animation = CABasicAnimation.FromKeyPath(_property);
                animation.From           = _nsValueConversion(from);
                animation.To             = _nsValueConversion(to);
                animation.TimingFunction = _timingFunction;
                _animation = animation;
            }
            _animation.BeginTime           = CAAnimation.CurrentMediaTime() + delayMilliseconds / __millisecondsPerSecond;
            _animation.Duration            = durationMilliseconds / __millisecondsPerSecond;
            _animation.FillMode            = CAFillMode.Forwards;
            _animation.RemovedOnCompletion = false;

            if (this.Log().IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug))
            {
                this.Log().DebugFormat("CoreAnimation on property {0} from {1} to {2} is starting.", _property, from, to);
            }

            _onAnimationStarted = (s, e) =>
            {
                var anim = s as CAAnimation;

                if (anim == null)
                {
                    return;
                }

                if (this.Log().IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug))
                {
                    this.Log().DebugFormat("CoreAnimation on property {0} from {1} to {2} started.", _property, from, to);
                }

                anim.AnimationStarted -= _onAnimationStarted;
                anim.AnimationStopped += _onAnimationStopped;
            };

            _onAnimationStopped = (s, e) =>
            {
                var anim = s as CAAnimation;

                if (anim == null)
                {
                    return;
                }

                CATransaction.Begin();
                CATransaction.DisableActions = true;
                layer.SetValueForKeyPath(_nsValueConversion(to), new NSString(_property));
                CATransaction.Commit();
                _cleanup?.Invoke();

                anim.AnimationStopped -= _onAnimationStopped;

                if (e.Finished)
                {
                    if (this.Log().IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug))
                    {
                        this.Log().DebugFormat("CoreAnimation on property {0} from {1} to {2} finished.", _property, from, to);
                    }

                    _onFinish();

                    ExecuteIfLayer(l => l.RemoveAnimation(_key));
                }
                else
                {
                    if (this.Log().IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug))
                    {
                        this.Log().DebugFormat("CoreAnimation on property {0} from {1} to {2} stopped before finishing.", _property, from, to);
                    }

                    anim.AnimationStarted += _onAnimationStarted;
                }
            };

            _animation.AnimationStarted += _onAnimationStarted;

            _prepare?.Invoke();
            layer.AddAnimation(_animation, _key);
        }
Example #34
0
        void FadeInBackgroundAndRippleTapCircle()
        {
            if (IsColorClear(BackgroundColor))
            {
                if (TapCircleColor == null)
                {
                    TapCircleColor = UsesSmartColor ? TitleLabel.TextColor.ColorWithAlpha(ClearBackgroundDumbTapCircleColor.CGColor.Alpha) : ClearBackgroundDumbTapCircleColor;
                }

                if (BackgroundFadeColor == null)
                {
                    BackgroundFadeColor = UsesSmartColor ? TitleLabel.TextColor.ColorWithAlpha(ClearBackgroundDumbFadeColor.CGColor.Alpha) : ClearBackgroundDumbFadeColor;
                }

                BackgroundColorFadeLayer.BackgroundColor = BackgroundFadeColor.CGColor;

                float startingOpacity = BackgroundColorFadeLayer.Opacity;

                if (BackgroundColorFadeLayer.AnimationKeys != null &&
                    BackgroundColorFadeLayer.AnimationKeys.Length > 0 &&
                    BackgroundColorFadeLayer.PresentationLayer != null)
                {
                    startingOpacity = BackgroundColorFadeLayer.PresentationLayer.Opacity;
                }

                CABasicAnimation fadeBackgroundDarker = CABasicAnimation.FromKeyPath("opacity");
                fadeBackgroundDarker.Duration       = TouchDownAnimationDuration;
                fadeBackgroundDarker.TimingFunction = CAMediaTimingFunction.FromName(CAMediaTimingFunction.Linear);
                fadeBackgroundDarker.SetFrom(NSNumber.FromNFloat(startingOpacity));
                fadeBackgroundDarker.SetTo(NSNumber.FromNFloat(1));
                fadeBackgroundDarker.FillMode            = CAFillMode.Forwards;
                fadeBackgroundDarker.RemovedOnCompletion = !false;
                BackgroundColorFadeLayer.Opacity         = 1;

                BackgroundColorFadeLayer.AddAnimation(fadeBackgroundDarker, "animateOpacity");
            }
            else
            {
                if (TapCircleColor == null)
                {
                    TapCircleColor = UsesSmartColor ? TitleLabel.TextColor.ColorWithAlpha(DumbTapCircleFillColor.CGColor.Alpha) : DumbTapCircleFillColor;
                }
            }

            nfloat tapCircleFinalDiameter = CalculateTapCircleFinalDiameter();

            var tapCircleLayerSizerView = new UIView(new CGRect(0, 0, tapCircleFinalDiameter, tapCircleFinalDiameter));

            tapCircleLayerSizerView.Center = RippleFromTapLocation ? TapPoint : new CGPoint(Bounds.GetMidX(), Bounds.GetMidY());

            var startingRectSizerView = new UIView(new CGRect(0, 0, TapCircleDiameterStartValue, TapCircleDiameterStartValue));

            startingRectSizerView.Center = tapCircleLayerSizerView.Center;

            UIBezierPath startingCirclePath = UIBezierPath.FromRoundedRect(startingRectSizerView.Frame, TapCircleDiameterStartValue / 2f);

            var endingRectSizerView = new UIView(new CGRect(0, 0, tapCircleFinalDiameter, tapCircleFinalDiameter));

            endingRectSizerView.Center = tapCircleLayerSizerView.Center;

            UIBezierPath endingCirclePath = UIBezierPath.FromRoundedRect(endingRectSizerView.Frame, tapCircleFinalDiameter / 2f);

            CAShapeLayer tapCircle = new CAShapeLayer();

            tapCircle.FillColor   = TapCircleColor.CGColor;
            tapCircle.StrokeColor = UIColor.Clear.CGColor;
            tapCircle.BorderColor = UIColor.Clear.CGColor;
            tapCircle.BorderWidth = 0;
            tapCircle.Path        = startingCirclePath.CGPath;

            if (!RippleBeyondBounds)
            {
                CAShapeLayer mask = new CAShapeLayer();
                mask.Path        = UIBezierPath.FromRoundedRect(FadeAndClippingMaskRect, CornerRadius).CGPath;
                mask.FillColor   = UIColor.Black.CGColor;
                mask.StrokeColor = UIColor.Clear.CGColor;
                mask.BorderColor = UIColor.Clear.CGColor;
                mask.BorderWidth = 0;

                tapCircle.Mask = mask;
            }

            RippleAnimationQueue.AddObjects(new NSObject[] { tapCircle });
            Layer.InsertSublayerAbove(tapCircle, BackgroundColorFadeLayer);

            CABasicAnimation tapCircleGrowthAnimation = CABasicAnimation.FromKeyPath("path");

            tapCircleGrowthAnimation.Duration       = TouchDownAnimationDuration;
            tapCircleGrowthAnimation.TimingFunction = CAMediaTimingFunction.FromName(CAMediaTimingFunction.EaseOut);
            tapCircleGrowthAnimation.SetFrom(startingCirclePath.CGPath);
            tapCircleGrowthAnimation.SetTo(endingCirclePath.CGPath);
            tapCircleGrowthAnimation.FillMode            = CAFillMode.Forwards;
            tapCircleGrowthAnimation.RemovedOnCompletion = false;

            CABasicAnimation fadeIn = CABasicAnimation.FromKeyPath("opacity");

            fadeIn.Duration       = TouchDownAnimationDuration;
            fadeIn.TimingFunction = CAMediaTimingFunction.FromName(CAMediaTimingFunction.Linear);
            fadeIn.SetFrom(NSNumber.FromNFloat(0));
            fadeIn.SetTo(NSNumber.FromNFloat(1));
            fadeIn.FillMode            = CAFillMode.Forwards;
            fadeIn.RemovedOnCompletion = false;

            tapCircle.AddAnimation(tapCircleGrowthAnimation, "animatePath");
            tapCircle.AddAnimation(fadeIn, "opacityAnimation");
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            base.ViewDidLoad();

            #region "Capa Imagen 1"
            CapaImagen1          = new CALayer();
            CapaImagen1.Bounds   = new CGRect(0, 0, 100, 100);
            CapaImagen1.Position = new CGPoint(50, 100);
            CapaImagen1.Contents = UIImage.FromFile
                                       ("foto1.jpg").CGImage;
            CapaImagen1.ContentsGravity = CALayer.
                                          GravityResizeAspectFill;

            #region "Rotació Imagen 1"
            CapaImagen1.Transform = CATransform3D.
                                    MakeRotation((float)Math.PI * 2, 0, 0, 1);
            CAKeyFrameAnimation Rotacion1 =
                (CAKeyFrameAnimation)
                CAKeyFrameAnimation.FromKeyPath("transform");
            Rotacion1.Values = new NSObject[] {
                NSNumber.FromFloat(0f),
                NSNumber.FromFloat((float)Math.PI / 2f),
                NSNumber.FromFloat((float)Math.PI),
                NSNumber.FromFloat((float)Math.PI * 2)
            };
            Rotacion1.ValueFunction = CAValueFunction.
                                      FromName(CAValueFunction.RotateZ);
            Rotacion1.Duration = 5;
            CapaImagen1.AddAnimation(Rotacion1, "transform");
            #endregion
            #endregion


            #region "Capa Imagen 3"
            CapaImagen3                 = new CALayer();
            CapaImagen3.Bounds          = new CGRect(0, 0, 100, 100);
            CapaImagen3.Position        = new CGPoint(50, 500);
            CapaImagen3.Contents        = UIImage.FromFile("foto1.jpg").CGImage;
            CapaImagen3.ContentsGravity = CALayer.GravityResizeAspectFill;

            #region "Animació Imagen 3"
            var OrigenImagen3 = CapaImagen3.Position;
            CapaImagen3.Position = new CGPoint(290, 100);
            var Animacion3 = CABasicAnimation.FromKeyPath("position");
            Animacion3.TimingFunction = CAMediaTimingFunction.FromName
                                            (CAMediaTimingFunction.EaseInEaseOut);
            Animacion3.From = NSValue.FromCGPoint(OrigenImagen3);
            Animacion3.To   = NSValue.FromCGPoint(new CGPoint(290, 100));
            #endregion

            #region "Rotació Imagen 3"
            CapaImagen3.Transform = CATransform3D.
                                    MakeRotation((float)Math.PI * 2, 0, 0, 1);
            var Rotacion2 = (CAKeyFrameAnimation)
                            CAKeyFrameAnimation.FromKeyPath("transform");
            Rotacion2.Values = new NSObject[] {
                NSNumber.FromFloat(0f),
                NSNumber.FromFloat((float)Math.PI / 2f),
                NSNumber.FromFloat((float)Math.PI),
                NSNumber.FromFloat((float)Math.PI * 2)
            };
            Rotacion2.ValueFunction = CAValueFunction.FromName(CAValueFunction.RotateY);
            #endregion

            #region "Agregar Animació y Rotació a la Capa 3"
            var ConjuntodeAnimacion = CAAnimationGroup.CreateAnimation();
            ConjuntodeAnimacion.Duration   = 2;
            ConjuntodeAnimacion.Animations = new CAAnimation[]
            { Animacion3, Rotacion2 };
            CapaImagen3.AddAnimation(ConjuntodeAnimacion, null);
            #endregion
            #endregion

            //wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
            #region "Capa Imagen 4"
            capaImagen4                 = new CALayer();
            capaImagen4.Bounds          = new CGRect(0, 0, 100, 100);
            capaImagen4.Position        = new CGPoint(300, 500);
            capaImagen4.Contents        = UIImage.FromFile("foto1.jpg").CGImage;
            capaImagen4.ContentsGravity = CALayer.GravityResizeAspectFill;

            #region "Animació Imagen 4"
            var OrigenImagen4 = capaImagen4.Position;
            capaImagen4.Position = new CGPoint(38, 100);
            var Animacion4 = CABasicAnimation.FromKeyPath("position");
            Animacion4.TimingFunction = CAMediaTimingFunction.FromName
                                            (CAMediaTimingFunction.EaseInEaseOut);
            Animacion4.From = NSValue.FromCGPoint(OrigenImagen4);
            Animacion4.To   = NSValue.FromCGPoint(new CGPoint(38, 100));
            #endregion

            #region "Rotació Imagen 3"
            capaImagen4.Transform = CATransform3D.
                                    MakeRotation((float)Math.PI * 2, 0, 0, 1);
            var Rotacion3 = (CAKeyFrameAnimation)
                            CAKeyFrameAnimation.FromKeyPath("transform");
            Rotacion3.Values = new NSObject[] {
                NSNumber.FromFloat(0f),
                NSNumber.FromFloat((float)Math.PI / 2f),
                NSNumber.FromFloat((float)Math.PI),
                NSNumber.FromFloat((float)Math.PI * 2)
            };
            Rotacion3.ValueFunction = CAValueFunction.FromName(CAValueFunction.RotateY);
            #endregion

            #region "Agregar Animació y Rotació a la Capa 3"
            var ConjuntodeAnimacion1 = CAAnimationGroup.CreateAnimation();
            ConjuntodeAnimacion1.Duration   = 2;
            ConjuntodeAnimacion1.Animations = new CAAnimation[]
            { Animacion4, Rotacion3 };
            capaImagen4.AddAnimation(ConjuntodeAnimacion1, null);
            #endregion
            #endregion


            View.Layer.AddSublayer(CapaImagen3);
            View.Layer.AddSublayer(capaImagen4);
        }
Example #36
0
        void LowerButtonAndFadeOutBackground()
        {
            if (IsRaised)
            {
                nfloat startRadius  = LiftedShadowRadius;
                nfloat startOpacity = LiftedShadowOpacity;
                CGPath startPath    = UIBezierPath.FromRoundedRect(UpRect, CornerRadius).CGPath;

                if (Layer.AnimationKeys != null && Layer.AnimationKeys.Length > 0)
                {
                    startRadius  = Layer.PresentationLayer.ShadowRadius;
                    startOpacity = Layer.PresentationLayer.ShadowOpacity;
                    startPath    = Layer.PresentationLayer.ShadowPath;
                }

                CABasicAnimation decreaseRadius = CABasicAnimation.FromKeyPath("shadowRadius");
                decreaseRadius.SetFrom(NSNumber.FromNFloat(startRadius));
                decreaseRadius.SetTo(NSNumber.FromNFloat(LoweredShadowRadius));
                decreaseRadius.Duration            = TouchUpAnimationDuration;
                decreaseRadius.FillMode            = CAFillMode.Forwards;
                decreaseRadius.RemovedOnCompletion = true;
                Layer.ShadowRadius = LoweredShadowRadius;

                CABasicAnimation shadowOpacityAnimation = CABasicAnimation.FromKeyPath("shadowOpacity");
                shadowOpacityAnimation.Duration = TouchUpAnimationDuration;
                shadowOpacityAnimation.SetFrom(NSNumber.FromNFloat(startOpacity));
                shadowOpacityAnimation.SetTo(NSNumber.FromNFloat(LoweredShadowOpacity));
                shadowOpacityAnimation.FillMode            = CAFillMode.Backwards;
                shadowOpacityAnimation.RemovedOnCompletion = true;
                Layer.ShadowOpacity = LoweredShadowOpacity;

                CABasicAnimation shadowAnimation = CABasicAnimation.FromKeyPath("shadowPath");
                shadowAnimation.Duration = TouchUpAnimationDuration;
                shadowAnimation.SetFrom(startPath);
                shadowAnimation.SetTo(UIBezierPath.FromRoundedRect(DownRect, CornerRadius).CGPath);
                shadowAnimation.FillMode            = CAFillMode.Forwards;
                shadowAnimation.RemovedOnCompletion = true;
                Layer.ShadowPath = UIBezierPath.FromRoundedRect(DownRect, CornerRadius).CGPath;


                Layer.AddAnimation(shadowAnimation, "shadow");
                Layer.AddAnimation(decreaseRadius, "shadowRadius");
                Layer.AddAnimation(shadowOpacityAnimation, "shadowOpacity");
            }

            if (IsColorClear(BackgroundColor))
            {
                nfloat startingOpacity = BackgroundColorFadeLayer.Opacity;

                if (BackgroundColorFadeLayer.AnimationKeys != null &&
                    BackgroundColorFadeLayer.AnimationKeys.Length > 0 &&
                    BackgroundColorFadeLayer.PresentationLayer != null)
                {
                    startingOpacity = BackgroundColorFadeLayer.PresentationLayer.Opacity;
                }

                CABasicAnimation removeFadeBackgroundDarker = CABasicAnimation.FromKeyPath("opacity");
                removeFadeBackgroundDarker.Duration       = TouchUpAnimationDuration;
                removeFadeBackgroundDarker.TimingFunction = CAMediaTimingFunction.FromName(CAMediaTimingFunction.Linear);
                removeFadeBackgroundDarker.SetFrom(NSNumber.FromNFloat(startingOpacity));
                removeFadeBackgroundDarker.SetTo(NSNumber.FromNFloat(0));
                removeFadeBackgroundDarker.FillMode            = CAFillMode.Forwards;
                removeFadeBackgroundDarker.RemovedOnCompletion = !false;
                BackgroundColorFadeLayer.Opacity = 0;

                BackgroundColorFadeLayer.AddAnimation(removeFadeBackgroundDarker, "animateOpacity");
            }
        }
        public override void SetupSlide(PresentationViewController presentationViewController)
        {
            // Set the slide's title and add some code
            TextManager.SetTitle("Materials");

            TextManager.AddBulletAtLevel("Diffuse", 0);
            TextManager.AddBulletAtLevel("Ambient", 0);
            TextManager.AddBulletAtLevel("Specular", 0);
            TextManager.AddBulletAtLevel("Normal", 0);
            TextManager.AddBulletAtLevel("Reflective", 0);
            TextManager.AddBulletAtLevel("Emission", 0);
            TextManager.AddBulletAtLevel("Transparent", 0);
            TextManager.AddBulletAtLevel("Multiply", 0);

            // Create a node for Earth and another node to display clouds
            // Use the 'pivot' property to tilt Earth because we don't want to see the north pole.
            EarthNode          = SCNNode.Create();
            EarthNode.Pivot    = SCNMatrix4.CreateFromAxisAngle(new SCNVector3(1, 0, 0), (float)(Math.PI * 0.1f));
            EarthNode.Position = new SCNVector3(6, 7.2f, -2);
            EarthNode.Geometry = SCNSphere.Create(7.2f);

            CloudsNode          = SCNNode.Create();
            CloudsNode.Geometry = SCNSphere.Create(7.9f);

            GroundNode.AddChildNode(EarthNode);
            EarthNode.AddChildNode(CloudsNode);

            // Initially hide everything
            EarthNode.Opacity  = 1.0f;
            CloudsNode.Opacity = 0.5f;

            EarthNode.Geometry.FirstMaterial.Ambient.Intensity    = 1;
            EarthNode.Geometry.FirstMaterial.Normal.Intensity     = 1;
            EarthNode.Geometry.FirstMaterial.Reflective.Intensity = 0.2f;
            EarthNode.Geometry.FirstMaterial.Reflective.Contents  = NSColor.White;
            EarthNode.Geometry.FirstMaterial.FresnelExponent      = 3;

            EarthNode.Geometry.FirstMaterial.Emission.Intensity = 1;
            EarthNode.Geometry.FirstMaterial.Diffuse.Contents   = new NSImage(NSBundle.MainBundle.PathForResource("Scenes.scnassets/earth/earth-diffuse", "jpg"));

            EarthNode.Geometry.FirstMaterial.Shininess          = 0.1f;
            EarthNode.Geometry.FirstMaterial.Specular.Contents  = new NSImage(NSBundle.MainBundle.PathForResource("Scenes.scnassets/earth/earth-specular", "jpg"));
            EarthNode.Geometry.FirstMaterial.Specular.Intensity = 0.8f;

            EarthNode.Geometry.FirstMaterial.Normal.Contents  = new NSImage(NSBundle.MainBundle.PathForResource("Scenes.scnassets/earth/earth-bump", "png"));
            EarthNode.Geometry.FirstMaterial.Normal.Intensity = 1.3f;

            EarthNode.Geometry.FirstMaterial.Emission.Contents = new NSImage(NSBundle.MainBundle.PathForResource("Scenes.scnassets/earth/earth-emissive", "jpg"));
            //EarthNode.Geometry.FirstMaterial.Reflective.Intensity = 1.0f;

            // This effect can also be achieved with an image with some transparency set as the contents of the 'diffuse' property
            CloudsNode.Geometry.FirstMaterial.Transparent.Contents = new NSImage(NSBundle.MainBundle.PathForResource("Scenes.scnassets/earth/cloudsTransparency", "png"));
            CloudsNode.Geometry.FirstMaterial.TransparencyMode     = SCNTransparencyMode.RgbZero;

            // Use a shader modifier to display an environment map independently of the lighting model used

            /*EarthNode.Geometry.ShaderModifiers = new SCNShaderModifiers {
             *      EntryCGPointragment = " _output.color.rgb -= _surface.reflective.rgb * _lightingContribution.diffuse;"
             + "_output.color.rgb += _surface.reflective.rgb;"
             + };*/

            // Add animations
            var rotationAnimation = CABasicAnimation.FromKeyPath("rotation");

            rotationAnimation.Duration    = 40.0f;
            rotationAnimation.RepeatCount = float.MaxValue;
            rotationAnimation.To          = NSValue.FromVector(new SCNVector4(0, 1, 0, (float)(Math.PI * 2)));
            EarthNode.AddAnimation(rotationAnimation, new NSString("earthNodeAnimation"));

            rotationAnimation.Duration = 100.0f;
            CloudsNode.AddAnimation(rotationAnimation, new NSString("cloudsNodeAnimation"));

            //animate light
            var lightHandleNode = SCNNode.Create();
            var lightNode       = SCNNode.Create();

            lightNode.Light             = SCNLight.Create();
            lightNode.Light.LightType   = SCNLightType.Directional;
            lightNode.Light.CastsShadow = true;
            lightHandleNode.RunAction(SCNAction.RepeatActionForever(SCNAction.RotateBy(0, -NMath.PI * 2, 0, 12)));
            lightHandleNode.AddChildNode(lightNode);

            EarthNode.AddChildNode(lightHandleNode);
        }
Example #38
0
        public void StartAnimating()
        {
            if (IsAnimating)
            {
                return;
            }

            CABasicAnimation animation = new CABasicAnimation();

            animation.KeyPath        = "transform.rotation";
            animation.Duration       = 4.0;
            animation.From           = new NSNumber(0.0f);
            animation.To             = new NSNumber(2 * Math.PI);
            animation.RepeatCount    = float.MaxValue;
            animation.TimingFunction = _timingFunction;
            ProgressLayer.AddAnimation(animation, KNBCircleRotationAnimationKey);

            CABasicAnimation headAnimation = new CABasicAnimation();

            headAnimation.KeyPath        = "strokeStart";
            headAnimation.Duration       = 1.0;
            headAnimation.From           = new NSNumber(0.0);
            headAnimation.To             = new NSNumber(0.25);
            headAnimation.TimingFunction = _timingFunction;

            CABasicAnimation tailAnimation = new CABasicAnimation();

            tailAnimation.KeyPath        = "strokeEnd";
            tailAnimation.Duration       = 1.0;
            tailAnimation.From           = new NSNumber(0.0);
            tailAnimation.To             = new NSNumber(1.0);
            tailAnimation.TimingFunction = _timingFunction;

            CABasicAnimation endHeadAnimation = new CABasicAnimation();

            endHeadAnimation.KeyPath        = "strokeStart";
            endHeadAnimation.BeginTime      = 1.0;
            endHeadAnimation.Duration       = 0.5;
            endHeadAnimation.From           = new NSNumber(0.25);
            endHeadAnimation.To             = new NSNumber(1.0);
            endHeadAnimation.TimingFunction = _timingFunction;

            CABasicAnimation endTailAnimation = new CABasicAnimation();

            endTailAnimation.KeyPath        = "strokeEnd";
            endTailAnimation.BeginTime      = 1.0;
            endTailAnimation.Duration       = 0.5;
            endTailAnimation.From           = new NSNumber(1.0);
            endTailAnimation.To             = new NSNumber(1.0);
            endTailAnimation.TimingFunction = _timingFunction;

            CAAnimationGroup animations = new CAAnimationGroup();

            animations.Duration    = 1.5;
            animations.Animations  = new CAAnimation[] { headAnimation, tailAnimation, endHeadAnimation, endTailAnimation };
            animations.RepeatCount = float.MaxValue;
            ProgressLayer.AddAnimation(animations, KNBCircleStrokeAnimationKey);

            _isAnimating = true;

            if (HidesWhenStopped)
            {
                Hidden = false;
            }
        }
Example #39
0
        public override void PresentStep(int index, PresentationViewController presentationViewController)
        {
            // Animate by default
            SCNTransaction.Begin();
            SCNTransaction.AnimationDuration = 0;

            switch (index)
            {
            case 0:
                TextManager.FlipInText(SlideTextManager.TextType.Bullet);
                break;

            case 1:
                TextManager.FlipOutText(SlideTextManager.TextType.Bullet);
                TextManager.AddEmptyLine();
                TextManager.AddCode("#// Rotate forever\n"
                                    + "[aNode #runAction:#\n"
                                    + "  [SCNAction repeatActionForever:\n"
                                    + "  [SCNAction rotateByX:0 y:M_PI*2 z:0 duration:5.0]]];#");

                TextManager.FlipInText(SlideTextManager.TextType.Code);
                break;

            case 2:
                TextManager.FlipOutText(SlideTextManager.TextType.Bullet);
                TextManager.FlipOutText(SlideTextManager.TextType.Code);

                TextManager.AddBulletAtLevel("Move", 0);
                TextManager.AddBulletAtLevel("Rotate", 0);
                TextManager.AddBulletAtLevel("Scale", 0);
                TextManager.AddBulletAtLevel("Opacity", 0);
                TextManager.AddBulletAtLevel("Remove", 0);
                TextManager.AddBulletAtLevel("Wait", 0);
                TextManager.AddBulletAtLevel("Custom block", 0);

                TextManager.FlipInText(SlideTextManager.TextType.Bullet);
                break;

            case 3:
                TextManager.FlipOutText(SlideTextManager.TextType.Bullet);
                TextManager.AddEmptyLine();
                TextManager.AddBulletAtLevel("Directly targets the render tree", 0);
                TextManager.FlipInText(SlideTextManager.TextType.Bullet);
                break;

            case 4:
                TextManager.AddBulletAtLevel("node.position / node.presentationNode.position", 0);

                //labels
                var label1 = TextManager.AddTextAtLevel("Action", 0);
                label1.Position = new SCNVector3(-15, 3, 0);
                var label2 = TextManager.AddTextAtLevel("Animation", 0);
                label2.Position = new SCNVector3(-15, -2, 0);

                //animation
                var animNode = SCNNode.Create();
                var cubeSize = 4.0f;
                animNode.Position = new SCNVector3(-5, cubeSize / 2, 0);

                var cube = SCNBox.Create(cubeSize, cubeSize, cubeSize, 0.05f * cubeSize);

                cube.FirstMaterial.Diffuse.Contents  = new NSImage(NSBundle.MainBundle.PathForResource("SharedTextures/texture", "png"));
                cube.FirstMaterial.Diffuse.MipFilter = SCNFilterMode.Linear;
                cube.FirstMaterial.Diffuse.WrapS     = SCNWrapMode.Repeat;
                cube.FirstMaterial.Diffuse.WrapT     = SCNWrapMode.Repeat;
                animNode.Geometry = cube;
                ContentNode.AddChildNode(animNode);

                SCNTransaction.Begin();


                SCNNode           animPosIndicator = null;
                SCNAnimationEvent startEvt         = SCNAnimationEvent.Create(0, (CAAnimation animation, NSObject animatedObject, bool playingBackward) => {
                    SCNTransaction.Begin();
                    SCNTransaction.AnimationDuration = 0;
                    animPosIndicator.Position        = new SCNVector3(10, animPosIndicator.Position.Y, animPosIndicator.Position.Z);
                    SCNTransaction.Commit();
                });
                SCNAnimationEvent endEvt = SCNAnimationEvent.Create(1, (CAAnimation animation, NSObject animatedObject, bool playingBackward) => {
                    SCNTransaction.Begin();
                    SCNTransaction.AnimationDuration = 0;
                    animPosIndicator.Position        = new SCNVector3(-5, animPosIndicator.Position.Y, animPosIndicator.Position.Z);
                    SCNTransaction.Commit();
                });

                var anim = CABasicAnimation.FromKeyPath("position.x");
                anim.Duration        = 3;
                anim.From            = new NSNumber(0.0);
                anim.To              = new NSNumber(15.0);
                anim.Additive        = true;
                anim.AutoReverses    = true;
                anim.AnimationEvents = new SCNAnimationEvent[] { startEvt, endEvt };
                anim.RepeatCount     = float.MaxValue;
                animNode.AddAnimation(anim, new NSString("cubeAnimation"));

                //action
                var actionNode = SCNNode.Create();
                actionNode.Position = new SCNVector3(-5, cubeSize * 1.5f + 1, 0);
                actionNode.Geometry = cube;

                ContentNode.AddChildNode(actionNode);

                var mv = SCNAction.MoveBy(15, 0, 0, 3);

                actionNode.RunAction(SCNAction.RepeatActionForever(SCNAction.Sequence(new SCNAction[] {
                    mv,
                    mv.ReversedAction()
                })));

                //position indicator
                var positionIndicator = SCNNode.Create();
                positionIndicator.Geometry = SCNCylinder.Create(0.5f, 0.01f);
                positionIndicator.Geometry.FirstMaterial.Diffuse.Contents  = NSColor.Red;
                positionIndicator.Geometry.FirstMaterial.LightingModelName = SCNLightingModel.Constant;
                positionIndicator.EulerAngles = new SCNVector3(NMath.PI / 2, 0, 0);
                positionIndicator.Position    = new SCNVector3(0, 0, cubeSize * 0.5f);
                actionNode.AddChildNode(positionIndicator);

                //anim pos indicator
                animPosIndicator          = positionIndicator.Clone();
                animPosIndicator.Position = new SCNVector3(5, cubeSize / 2, cubeSize * 0.5f);
                ContentNode.AddChildNode(animPosIndicator);

                SCNTransaction.Commit();

                break;
            }
            SCNTransaction.Commit();
        }
Example #40
0
        //- (void)presentImage:(NSImage *)image;
        void PresentImage(NSImage image, string filename)
        {
            int animationSpeed = 3;

            CGRect  superLayerBounds = View.Layer.Bounds;
            CGPoint center           = new CGPoint(superLayerBounds.GetMidX(), superLayerBounds.GetMidY());

            CGRect imageBounds = new CGRect(0, 0, image.Size.Width, image.Size.Height);

            nfloat  X           = (nfloat)random.Next((int)Math.Floor(imageBounds.Width / 2), (int)Math.Floor(superLayerBounds.GetMaxX() - imageBounds.Width / 2));   //(superLayerBounds.GetMaxX() - imageBounds.Width/2) * random.NextDouble();
            nfloat  Y           = (nfloat)random.Next((int)Math.Floor(imageBounds.Height / 2), (int)Math.Floor(superLayerBounds.GetMaxY() - imageBounds.Height / 2)); //(superLayerBounds.GetMaxY() - imageBounds.Height/2) * random.NextDouble();
            CGPoint randomPoint = new CGPoint(X, Y);

            CAMediaTimingFunction tf = CAMediaTimingFunction.FromName(CAMediaTimingFunction.EaseInEaseOut);

            // Animations for image layer
            CABasicAnimation posAnim = CABasicAnimation.FromKeyPath("position");

            posAnim.From           = NSValue.FromCGPoint(center);
            posAnim.Duration       = animationSpeed;
            posAnim.TimingFunction = tf;

            CABasicAnimation bdsAnim = CABasicAnimation.FromKeyPath("bounds");

            bdsAnim.From           = NSValue.FromCGRect(CGRect.Empty);
            bdsAnim.Duration       = animationSpeed;
            bdsAnim.TimingFunction = tf;

            // Image layer
            CALayer layer = new CALayer();

            layer.Contents  = image.CGImage;
            layer.Position  = center;
            layer.ZPosition = random.Next(-100, 99);
            layer.Actions   = NSDictionary.FromObjectsAndKeys(new NSObject[] { posAnim, bdsAnim }, new NSObject[] { new NSString("position"), new NSString("bounds") });

            // Animation for text layer
            CATransform3D    scale      = CATransform3D.MakeScale(0.0f, 0.0f, 0.0f);
            CABasicAnimation tScaleAnim = CABasicAnimation.FromKeyPath("transform");

            tScaleAnim.From           = NSValue.FromCATransform3D(scale);
            tScaleAnim.Duration       = animationSpeed;
            tScaleAnim.TimingFunction = tf;

            // text layer
            CATextLayer fileNameLayer = new CATextLayer();

            fileNameLayer.FontSize        = 24;
            fileNameLayer.ForegroundColor = NSColor.White.CGColor;
            SetText(" " + filename + " ", fileNameLayer);
            fileNameLayer.Transform     = scale;
            fileNameLayer.Position      = CGPoint.Empty;
            fileNameLayer.AnchorPoint   = CGPoint.Empty;
            fileNameLayer.ShadowColor   = NSColor.Black.CGColor;
            fileNameLayer.ShadowOffset  = new CGSize(5, 5);
            fileNameLayer.ShadowOpacity = 1.0f;
            fileNameLayer.ShadowRadius  = 0.0f;
            fileNameLayer.BorderColor   = NSColor.White.CGColor;
            fileNameLayer.BorderWidth   = 1.0f;
            fileNameLayer.Actions       = NSDictionary.FromObjectsAndKeys(new NSObject[] { tScaleAnim }, new NSObject[] { new NSString("transform") });

            layer.AddSublayer(fileNameLayer);
            View.Layer.AddSublayer(layer);

            CATransaction.Begin();
            layer.Position          = randomPoint;
            layer.Bounds            = imageBounds;
            fileNameLayer.Transform = CATransform3D.Identity;
            CATransaction.Commit();
        }
Example #41
0
        public override void PresentStep(int index, PresentationViewController presentationViewController)
        {
            switch (index)
            {
            case (int)ParticleSteps.Fire:
                TextManager.FlipOutText(SlideTextManager.TextType.Bullet);

                TextManager.AddEmptyLine();
                TextManager.AddBulletAtLevel("Particle Image", 0);
                TextManager.AddBulletAtLevel("Color over life duration", 0);
                TextManager.AddBulletAtLevel("Size over life duration", 0);
                TextManager.AddBulletAtLevel("Several blend modes", 0);

                TextManager.FlipInText(SlideTextManager.TextType.Bullet);

                var hole = SCNNode.Create();
                hole.Geometry = SCNTube.Create(1.7f, 1.9f, 1.5f);
                hole.Position = new SCNVector3(0, 0, HOLE_Z);
                hole.Scale    = new SCNVector3(1, 0, 1);

                GroundNode.AddChildNode(hole);

                SCNTransaction.Begin();
                SCNTransaction.AnimationDuration = 0.5f;

                hole.Scale = new SCNVector3(1, 1, 1);

                SCNTransaction.Commit();

                var ps = SCNParticleSystem.Create("fire", "Particles");
                hole.AddParticleSystem(ps);

                Hole = hole;
                break;

            case (int)ParticleSteps.FireScreen:
                ps           = Hole.ParticleSystems [0];
                ps.BlendMode = SCNParticleBlendMode.Screen;
                break;

            case (int)ParticleSteps.Local:
                TextManager.FlipOutText(SlideTextManager.TextType.Bullet);

                TextManager.AddBulletAtLevel("Local vs Global", 0);
                TextManager.FlipInText(SlideTextManager.TextType.Bullet);

                Hole.RemoveAllParticleSystems();
                Hole2          = Hole.Clone();
                Hole2.Geometry = (SCNGeometry)Hole.Geometry.Copy();
                Hole2.Position = new SCNVector3(0, -2, HOLE_Z - 4);
                GroundNode.AddChildNode(Hole2);
                SCNTransaction.Begin();
                SCNTransaction.AnimationDuration = 0.5;
                Hole2.Position = new SCNVector3(0, 0, HOLE_Z - 4);
                SCNTransaction.Commit();

                ps = SCNParticleSystem.Create("reactor", "Particles");
                ps.ParticleColorVariation = new SCNVector4(0, 0, 0.5f, 0);
                Hole.AddParticleSystem(ps);

                var localPs = (SCNParticleSystem)ps.Copy();
                localPs.ParticleImage = ps.ParticleImage;
                localPs.Local         = true;
                Hole2.AddParticleSystem(localPs);

                var animation = CABasicAnimation.FromKeyPath("position");
                animation.From           = NSValue.FromVector(new SCNVector3(7, 0, HOLE_Z));
                animation.To             = NSValue.FromVector(new SCNVector3(-7, 0, HOLE_Z));
                animation.BeginTime      = CAAnimation.CurrentMediaTime() + 0.75;
                animation.Duration       = 8;
                animation.AutoReverses   = true;
                animation.RepeatCount    = float.MaxValue;
                animation.TimingFunction = CAMediaTimingFunction.FromName(CAMediaTimingFunction.EaseInEaseOut);
                animation.TimeOffset     = animation.Duration / 2;
                Hole.AddAnimation(animation, new NSString("animateHole"));

                animation                = CABasicAnimation.FromKeyPath("position");
                animation.From           = NSValue.FromVector(new SCNVector3(-7, 0, HOLE_Z - 4));
                animation.To             = NSValue.FromVector(new SCNVector3(7, 0, HOLE_Z - 4));
                animation.BeginTime      = CAAnimation.CurrentMediaTime() + 0.75;
                animation.Duration       = 8;
                animation.AutoReverses   = true;
                animation.RepeatCount    = float.MaxValue;
                animation.TimingFunction = CAMediaTimingFunction.FromName(CAMediaTimingFunction.EaseInEaseOut);
                animation.TimeOffset     = animation.Duration / 2;
                Hole2.AddAnimation(animation, new NSString("animateHole"));
                break;

            case (int)ParticleSteps.Gravity:
                TextManager.FlipOutText(SlideTextManager.TextType.Bullet);

                TextManager.AddBulletAtLevel("Affected by gravity", 0);
                TextManager.FlipInText(SlideTextManager.TextType.Bullet);

                Hole2.RemoveAllParticleSystems();
                Hole2.RunAction(SCNAction.Sequence(new SCNAction[] {
                    SCNAction.ScaleTo(0, 0.5),
                    SCNAction.RemoveFromParentNode()
                }));
                Hole.RemoveAllParticleSystems();
                Hole.RemoveAnimation(new NSString("animateHole"), 0.5f);

                SCNTransaction.Begin();
                SCNTransaction.AnimationDuration = 0.5;

                var tube = (SCNTube)Hole.Geometry;
                tube.InnerRadius = 0.3f;
                tube.OuterRadius = 0.4f;
                tube.Height      = 1.0f;

                SCNTransaction.Commit();

                ps = SCNParticleSystem.Create("sparks", "Particles");
                Hole.RemoveAllParticleSystems();
                Hole.AddParticleSystem(ps);

                foreach (var child in ((SCNView)presentationViewController.View).Scene.RootNode.ChildNodes)
                {
                    if (child.Geometry != null)
                    {
                        if (child.Geometry.GetType() == typeof(SCNFloor))
                        {
                            FloorNode = child;
                        }
                    }
                }

                /*FloorNode = ((SCNView)presentationViewController.View).Scene.RootNode.FindNodes ((SCNNode child, out bool stop) => {
                 *      stop = false;
                 *      if (child.Geometry != null)
                 *              stop = (child.Geometry.GetType () == typeof(SCNFloor));
                 *      return stop;
                 * });*/

                /*FloorNode = [presentationViewController.view.scene.rootNode childNodesPassingTest:^BOOL(SCNNode *child, BOOL *stop) {
                 *      return [child.geometry isKindOfClass:[SCNFloor class]];
                 * }][0];*/

                ps.ColliderNodes = new SCNNode[] { FloorNode };

                break;

            case (int)ParticleSteps.Collider:
                TextManager.FlipOutText(SlideTextManager.TextType.Bullet);

                TextManager.AddBulletAtLevel("Affected by colliders", 0);
                TextManager.FlipInText(SlideTextManager.TextType.Bullet);

                var boxNode = SCNNode.Create();
                boxNode.Geometry = SCNBox.Create(5, 0.2f, 5, 0);
                boxNode.Position = new SCNVector3(0, 7, HOLE_Z);
                boxNode.Geometry.FirstMaterial.Emission.Contents = NSColor.DarkGray;

                GroundNode.AddChildNode(boxNode);

                ps = Hole.ParticleSystems [0];
                ps.ColliderNodes = new SCNNode[] { FloorNode, boxNode };

                animation                = CABasicAnimation.FromKeyPath("eulerAngles");
                animation.From           = NSValue.FromVector(new SCNVector3(0, 0, (nfloat)Math.PI / 4 * 1.7f));
                animation.To             = NSValue.FromVector(new SCNVector3(0, 0, -(nfloat)Math.PI / 4 * 1.7f));
                animation.BeginTime      = CAAnimation.CurrentMediaTime() + 0.5;
                animation.Duration       = 2;
                animation.AutoReverses   = true;
                animation.RepeatCount    = float.MaxValue;
                animation.TimingFunction = CAMediaTimingFunction.FromName(CAMediaTimingFunction.EaseInEaseOut);
                animation.TimeOffset     = animation.Duration / 2;
                boxNode.AddAnimation(animation, new NSString("animateHole"));

                BoxNode = boxNode;
                break;

            case (int)ParticleSteps.Fields:
                Hole.RemoveAllParticleSystems();

                Hole.RunAction(SCNAction.Sequence(new SCNAction[] {
                    SCNAction.ScaleTo(0, 0.75),
                    SCNAction.RemoveFromParentNode()
                }));

                BoxNode.RunAction(SCNAction.Sequence(new SCNAction[] {
                    SCNAction.MoveBy(0, 15, 0, 1.0),
                    SCNAction.RemoveFromParentNode()
                }));

                var particleHolder = SCNNode.Create();
                particleHolder.Position = new SCNVector3(0, 20, HOLE_Z);
                GroundNode.AddChildNode(particleHolder);

                ParticleHolder = particleHolder;

                TextManager.FlipOutText(SlideTextManager.TextType.Bullet);
                TextManager.AddBulletAtLevel("Affected by physics fields", 0);
                TextManager.FlipInText(SlideTextManager.TextType.Bullet);

                ps = SCNParticleSystem.Create("snow", "Particles");
                ps.AffectedByPhysicsFields = true;
                ParticleHolder.AddParticleSystem(ps);
                Snow = ps;

                //physics field
                var field = SCNPhysicsField.CreateTurbulenceField(50, 1);
                field.HalfExtent = new SCNVector3(20, 20, 20);
                field.Strength   = 4.0f;

                var fieldOwner = SCNNode.Create();
                fieldOwner.Position = new SCNVector3(0, 5, HOLE_Z);

                GroundNode.AddChildNode(fieldOwner);
                fieldOwner.PhysicsField = field;
                FieldOwner = fieldOwner;

                ps.ColliderNodes = new SCNNode[] { FloorNode };
                break;

            case (int)ParticleSteps.FieldsVortex:
                VortexFieldOwner          = SCNNode.Create();
                VortexFieldOwner.Position = new SCNVector3(0, 5, HOLE_Z);

                GroundNode.AddChildNode(VortexFieldOwner);

                //tornado
                var worldOrigin = new SCNVector3(FieldOwner.WorldTransform.M41, FieldOwner.WorldTransform.M42, FieldOwner.WorldTransform.M43);
                var worldAxis   = new SCNVector3(0, 1, 0);

                var vortex = SCNPhysicsField.CustomField((SCNVector3 position, SCNVector3 velocity, float mass, float charge, double timeInSeconds) => {
                    var l        = new SCNVector3();
                    l.X          = worldOrigin.X - position.X;
                    l.Z          = worldOrigin.Z - position.Z;
                    SCNVector3 t = Cross(worldAxis, l);
                    var d2       = (l.X * l.X + l.Z * l.Z);
                    var vs       = (nfloat)(VS / Math.Sqrt(d2));
                    var fy       = (nfloat)(1.0 - (Math.Min(1.0, (position.Y / 15.0))));
                    return(new SCNVector3(t.X * vs + l.X * (nfloat)VW * fy, 0, t.Z * vs + l.Z * (nfloat)VW * fy));
                });
                vortex.HalfExtent             = new SCNVector3(100, 100, 100);
                VortexFieldOwner.PhysicsField = vortex;
                break;

            case (int)ParticleSteps.SubSystems:
                FieldOwner.RemoveFromParentNode();
                ParticleHolder.RemoveAllParticleSystems();
                Snow.DampingFactor = -1;

                TextManager.FlipOutText(SlideTextManager.TextType.Bullet);
                TextManager.AddBulletAtLevel("Sub-particle system on collision", 0);
                TextManager.FlipInText(SlideTextManager.TextType.Bullet);

                ps = SCNParticleSystem.Create("rain", "Particles");
                var pss = SCNParticleSystem.Create("plok", "Particles");
                pss.IdleDuration = 0;
                pss.Loops        = false;

                ps.SystemSpawnedOnCollision = pss;

                ParticleHolder.AddParticleSystem(ps);
                ps.ColliderNodes = new SCNNode[] { FloorNode };
                break;

            case (int)ParticleSteps.Confetti:
                ParticleHolder.RemoveAllParticleSystems();

                TextManager.FlipOutText(SlideTextManager.TextType.Bullet);
                TextManager.AddBulletAtLevel("Custom blocks", 0);
                TextManager.FlipInText(SlideTextManager.TextType.Bullet);

                ps = SCNParticleSystem.Create();
                ps.EmitterShape                     = SCNBox.Create(20, 9, 5, 0);
                ps.BirthRate                        = 100;
                ps.ParticleLifeSpan                 = 10;
                ps.ParticleLifeSpanVariation        = 0;
                ps.SpreadingAngle                   = 20;
                ps.ParticleSize                     = 0.25f;
                ps.ParticleVelocity                 = 10;
                ps.ParticleVelocityVariation        = 19;
                ps.BirthDirection                   = SCNParticleBirthDirection.Constant;
                ps.EmittingDirection                = new SCNVector3(0, -1, 0);
                ps.BirthLocation                    = SCNParticleBirthLocation.Volume;
                ps.ParticleImage                    = new NSImage(NSBundle.MainBundle.PathForResource("Particles/confetti", "png"));
                ps.LightingEnabled                  = true;
                ps.OrientationMode                  = SCNParticleOrientationMode.Free;
                ps.SortingMode                      = SCNParticleSortingMode.Distance;
                ps.ParticleAngleVariation           = 180;
                ps.ParticleAngularVelocity          = 200;
                ps.ParticleAngularVelocityVariation = 400;
                ps.ParticleColor                    = NSColor.Green;
                ps.ParticleColorVariation           = new SCNVector4(0.2f, 0.1f, 0.1f, 0);
                ps.ParticleBounce                   = 0;
                ps.ParticleFriction                 = 0.6f;
                ps.ColliderNodes                    = new SCNNode[] { FloorNode };
                ps.BlendMode                        = SCNParticleBlendMode.Alpha;

                var floatAnimation = CAKeyFrameAnimation.FromKeyPath("");
                floatAnimation.Values   = new NSNumber[] { 1, 1, 0 };
                floatAnimation.KeyTimes = new NSNumber[] { 0, 0.9f, 1 };
                floatAnimation.Duration = 1.0f;
                floatAnimation.Additive = false;

                //ps.PropertyControllers = @{ SCNParticlePropertyOpacity: [SCNParticlePropertyController controllerWithAnimation:floatAnimation] };
                //ps.HandleEvent (SCNParticleEvent.Birth,

                /*[ps handleEvent:SCNParticleEventBirth forProperties:@[SCNParticlePropertyColor] withBlock:^(void **data, size_t *dataStride, uint32_t *indices , NSInteger count) {
                 *
                 *      for (int i = 0; i < count; ++i) {
                 *              var col = (float *)((char *)data[0] + dataStride[0] * i);
                 *              if (rand() & 0x1) { // swith green for red
                 *                      col[0] = col[1];
                 *                      col[1] = 0;
                 *              }
                 *
                 *      }
                 * }];*/

                /*[ps handleEvent:SCNParticleEventCollision forProperties:@[SCNParticlePropertyAngle, SCNParticlePropertyRotationAxis, SCNParticlePropertyAngularVelocity, SCNParticlePropertyVelocity, SCNParticlePropertyContactNormal] withBlock:^(void **data, size_t *dataStride, uint32_t *indices , NSInteger count) {
                 *
                 *      for (NSInteger i = 0; i < count; ++i) {
                 *              // fix orientation
                 *              float *angle = (float *)((char *)data[0] + dataStride[0] * indices[i]);
                 *              float *axis = (float *)((char *)data[1] + dataStride[1] * indices[i]);
                 *
                 *              float *colNrm = (float *)((char *)data[4] + dataStride[4] * indices[i]);
                 *              SCNVector3 collisionNormal = {colNrm[0], colNrm[1], colNrm[2]};
                 *              SCNVector3 cp = SCNVector3CrossProduct(collisionNormal, SCNVector3Make(0, 0, 1));
                 *              CGFloat cpLen = SCNVector3Length(cp);
                 *              angle[0] = asin(cpLen);
                 *
                 *              axis[0] = cp.x / cpLen;
                 *              axis[1] = cp.y / cpLen;
                 *              axis[2] = cp.z / cpLen;
                 *
                 *              // kill angular rotation
                 *              float *angVel = (float *)((char *)data[2] + dataStride[2] * indices[i]);
                 *              angVel[0] = 0;
                 *
                 *              if (colNrm[1] > 0.4) {
                 *                      float *vel = (float *)((char *)data[3] + dataStride[3] * indices[i]);
                 *                      vel[0] = 0;
                 *                      vel[1] = 0;
                 *                      vel[2] = 0;
                 *              }
                 *      }
                 * }];*/

                ParticleHolder.AddParticleSystem(ps);
                break;

            case (int)ParticleSteps.EmitterCube:
                ParticleHolder.RemoveAllParticleSystems();

                TextManager.FlipOutText(SlideTextManager.TextType.Bullet);
                TextManager.AddBulletAtLevel("Emitter shape", 0);
                TextManager.FlipInText(SlideTextManager.TextType.Bullet);

                ParticleHolder.RemoveFromParentNode();

                ps       = SCNParticleSystem.Create("emitters", "Particles");
                ps.Local = true;
                ParticleHolder.AddParticleSystem(ps);

                var node = SCNNode.Create();
                node.Position = new SCNVector3(3, 6, HOLE_Z);
                node.RunAction(SCNAction.RepeatActionForever(SCNAction.RotateBy((float)Math.PI * 2, new SCNVector3(0.3f, 1, 0), 8)));
                GroundNode.AddChildNode(node);
                Bokeh = ps;

                node.AddParticleSystem(ps);
                break;

            case (int)ParticleSteps.EmitterSphere:
                Bokeh.EmitterShape = SCNSphere.Create(5);
                break;

            case (int)ParticleSteps.EmitterTorus:
                Bokeh.EmitterShape = SCNTorus.Create(5, 1);
                break;
            }
        }
Example #42
0
        public void loadcomboTaks()
        {
            int items = 0;

            try {
                items = dataPos.shareoptions.Count;
            } catch {
                items = 0;
            }

            if (items == 0)
            {
                return;
            }

            shareList = new string[items];
            items     = 0;
            foreach (shareOptions s in dataPos.shareoptions)
            {
                shareList [items] = s.key;
                items++;
            }

            /*
             * shareList[0]= "FaceBook";
             * shareList[1]= "Twitter";
             * shareList[2]= "Email";
             */
            if (showComboTaks)
            {
                return;
            }

            cmbShare _pickerDataModel;

            _pickerDataModel = new cmbShare(this, shareList);

            if (IsTall)
            {
                pkrShare = new UIPickerView(new RectangleF(0, 290, 320, 216));
            }
            else
            {
                pkrShare = new UIPickerView(new RectangleF(0, 200, 320, 216));
            }

            pkrShare.Source = _pickerDataModel;
            pkrShare.ShowSelectionIndicator = true;



            var animation = CABasicAnimation.FromKeyPath("transform.translation.y");

            animation.From     = NSNumber.FromFloat(100);
            animation.To       = NSNumber.FromFloat(0);
            animation.Duration = .2;
            animation.FillMode = CAFillMode.Both;

            this.View.AddSubview(pkrShare);
            BarraShare = BarraShareGet();
            this.View.AddSubview(BarraShare);

            animation.AutoReverses = false;
            //animation.Delegate = new MyAnimationDelegate (v, true);
            pkrShare.Layer.AddAnimation(animation, "moveToHeader");

            pkrShare.Select(0, 0, false);

            showComboTaks = true;

            UpdatecurrenShareOpt = 0;
        }
        // Handle the badge changing value
        void UpdateBadgeValueAnimated(bool animated)
        {
            // Bounce animation on badge if value changed and if animation authorized
            if (animated && this.ShouldAnimateBadge && _badge.Text != this.BadgeValue)
            {
                var animation = new CABasicAnimation ();
                animation.KeyPath = @"transform.scale";
                animation.From = NSObject.FromObject (1.5);
                animation.To = NSObject.FromObject (1);
                animation.Duration = 0.2;
                animation.TimingFunction = new CAMediaTimingFunction(0.4f,1.3f,1f,1f);
                _badge.Layer.AddAnimation (animation, @"bounceAnimation");
            }

            // Set the new value
            _badge.Text = this.BadgeValue;

            // Animate the size modification if needed
            double duration = animated ? 0.2 : 0;
            UIView.Animate (duration, UpdateBadgeFrame);
        }
Example #44
0

            if (SelectedCard.IsFlipped)
            {
                cardBack.Hidden = false;
            }
            else
            {
                cardFront.Hidden = false;
            }


            var SwipeGestureRecognizer = new UISwipeGestureRecognizer((UISwipeGestureRecognizer obj) =>
            {
                Flip();
            });
            SwipeGestureRecognizer.Direction = UISwipeGestureRecognizerDirection.Left | UISwipeGestureRecognizerDirection.Right;
            ContainerView.AddGestureRecognizer(SwipeGestureRecognizer);


        }

        public override void ViewWillAppear(bool animated)
        {
            base.ViewWillAppear(animated);

            Update(true);

            CABasicAnimation grow = CABasicAnimation.FromKeyPath("transform.scale");
            grow.From = NSObject.FromObject(0);
            grow.Duration = .5;
            grow.RemovedOnCompletion = true;
            ContainerView.Layer.AddAnimation(grow, "grow");
        }
        public override void ViewDidAppear(bool animated)
        {
            base.ViewDidAppear(animated);

            TableViewRowEditingChangedNotification = NSNotificationCenter.DefaultCenter.AddObserver(new NSString(Strings.InternalNotifications.notification_table_row_editing_changed), (obj) =>
            {
                InvokeOnMainThread(() =>
                {
                    Update(false);
                });
            });
        }
        public override void ViewDidDisappear(bool animated)
        {
            base.ViewDidDisappear(animated);

            TableViewRowEditingChangedNotification?.Dispose();
            TableViewRowEditingChangedNotification = null;
        }
        public override void ViewWillLayoutSubviews()
        {
            base.ViewWillLayoutSubviews();

            if (ContainerView != null)
            {
                ContainerView.Frame = new CGRect(8, 8, View.Bounds.Width - 16, GetCalculatedHeight() + 33); //40 is the total insets that appear in a tableviewcell

                var cardFront = ContainerView.Subviews.Where(c => c.GetType() == typeof(CardFront)).FirstOrDefault() as CardFront;
                if (cardFront != null)
                    cardFront.Frame = ContainerView.Bounds;

                var cardBack = ContainerView.Subviews.Where(c => c.GetType() == typeof(CardBack)).FirstOrDefault() as CardBack;
                if (cardBack != null) 
                    cardBack.Frame = ContainerView.Bounds;
            }
        }
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
            if (disposing)
            {
                ContainerView.Subviews.ToList().ForEach(v => v.RemoveFromSuperview());
                ContainerView?.RemoveFromSuperview();
                ContainerView?.Dispose();
                ContainerView = null;

                TableViewRowEditingChangedNotification?.Dispose();
                TableViewRowEditingChangedNotification = null;
            }
        }
        public void FocusOnName()
        {
            NameTextField.BecomeFirstResponder();
        }
        public void Update(bool reloadImages)
        {
            if (SelectedCard == null) return;

            NameTextField.Text = (SelectedCard.Name.Equals(Strings.Basic.new_card, StringComparison.InvariantCultureIgnoreCase) && Editable) ? null : SelectedCard.Name;

            var cardFront = ContainerView.Subviews.Where(c => c.GetType() == typeof(CardFront)).FirstOrDefault() as CardFront;
Example #45
0
 public void UpdateBadgeValueAnimated(bool animated)
 {
     // Bounce animation on badge if value changed and if animation authorized
     if (animated && ShouldAnimate && Badge.Text != BadgeValue)
     {
         CABasicAnimation animation = new CABasicAnimation()
         {
             KeyPath = "transform.scale",
             From = NSNumber.FromDouble(1.5),
             To = NSNumber.FromDouble(1),
             Duration = .2,
             TimingFunction = CAMediaTimingFunction.FromControlPoints((float)0.4, (float).3, 1, 1)
         };
         Badge.Layer.AddAnimation(animation, "bounceAnimation");
     }
     // Set the new value
     Badge.Text = BadgeValue;
     // Animate the size modification if needed
     //NSTimeInterval duration = animated ? 0.2 : 0;
     //[UIView animateWithDuration:duration animations:^{
     UpdateBadgeFrame();
     //}]; // this animation breaks the rounded corners in iOS 9
 }
Example #46
0
        public override void PresentStep(int index, PresentationViewController presentationViewController)
        {
            switch (index)
            {
            case 0:
                // Set the slide's title and subtitle and add some text
                TextManager.SetTitle("Constraints");
                TextManager.SetSubtitle("SCNConstraint");

                TextManager.AddBulletAtLevel("Applied sequentially at render time", 0);
                TextManager.AddBulletAtLevel("Only affect presentation values", 0);

                TextManager.AddCode("#aNode.#Constraints# = new SCNConstraint[] { aConstraint, anotherConstraint, ... };#");

                // Tweak the near clipping plane of the spot light to get a precise shadow map
                presentationViewController.SpotLight.Light.SetAttribute(new NSNumber(10), SCNLightAttribute.ShadowNearClippingKey);
                break;

            case 1:
                // Remove previous text
                TextManager.FlipOutText(SlideTextManager.TextType.Subtitle);
                TextManager.FlipOutText(SlideTextManager.TextType.Bullet);
                TextManager.FlipOutText(SlideTextManager.TextType.Code);

                // Add new text
                TextManager.SetSubtitle("SCNLookAtConstraint");
                TextManager.AddBulletAtLevel("Makes a node to look at another node", 0);
                TextManager.AddCode("#nodeA.Constraints = new SCNConstraint[] { #SCNLookAtConstraint.Create# (nodeB) };#");

                TextManager.FlipInText(SlideTextManager.TextType.Subtitle);
                TextManager.FlipInText(SlideTextManager.TextType.Bullet);
                TextManager.FlipInText(SlideTextManager.TextType.Code);
                break;

            case 2:
                // Setup the scene
                SetupLookAtScene();

                SCNTransaction.Begin();
                SCNTransaction.AnimationDuration = 1;
                // Dim the text and move back a little bit
                TextManager.TextNode.Opacity = 0.5f;
                presentationViewController.CameraHandle.Position = presentationViewController.CameraNode.ConvertPositionToNode(new SCNVector3(0, 0, 5.0f), presentationViewController.CameraHandle.ParentNode);
                SCNTransaction.Commit();
                break;

            case 3:
                // Add constraints to the arrows
                var container = ContentNode.FindChildNode("arrowContainer", true);

                // "Look at" constraint
                var constraint = SCNLookAtConstraint.Create(BallNode);

                var i = 0;
                foreach (var arrow in container.ChildNodes)
                {
                    var delayInSeconds = 0.1 * i++;
                    var popTime        = new DispatchTime(DispatchTime.Now, (long)(delayInSeconds * Utils.NSEC_PER_SEC));
                    DispatchQueue.MainQueue.DispatchAfter(popTime, () => {
                        SCNTransaction.Begin();
                        SCNTransaction.AnimationDuration = 1;
                        // Animate to the result of applying the constraint
                        arrow.ChildNodes [0].Rotation = new SCNVector4(0, 1, 0, (float)(Math.PI / 2));
                        arrow.Constraints             = new SCNConstraint[] { constraint };
                        SCNTransaction.Commit();
                    });
                }
                break;

            case 4:
                // Create a keyframe animation to move the ball
                var animation = CAKeyFrameAnimation.GetFromKeyPath("position");
                animation.KeyTimes = new NSNumber[] {
                    0.0f,
                    (1.0f / 8.0f),
                    (2.0f / 8.0f),
                    (3.0f / 8.0f),
                    (4.0f / 8.0f),
                    (5.0f / 8.0f),
                    (6.0f / 8.0f),
                    (7.0f / 8.0f),
                    1.0f
                };

                animation.Values = new NSObject[] {
                    NSValue.FromVector(new SCNVector3(0, 0.0f, 0)),
                    NSValue.FromVector(new SCNVector3(20.0f, 0.0f, 20.0f)),
                    NSValue.FromVector(new SCNVector3(40.0f, 0.0f, 0)),
                    NSValue.FromVector(new SCNVector3(20.0f, 0.0f, -20.0f)),
                    NSValue.FromVector(new SCNVector3(0, 0.0f, 0)),
                    NSValue.FromVector(new SCNVector3(-20.0f, 0.0f, 20.0f)),
                    NSValue.FromVector(new SCNVector3(-40.0f, 0.0f, 0)),
                    NSValue.FromVector(new SCNVector3(-20.0f, 0.0f, -20.0f)),
                    NSValue.FromVector(new SCNVector3(0, 0.0f, 0))
                };

                animation.CalculationMode = CAAnimation.AnimationCubicPaced;                 // smooth the movement between keyframes
                animation.RepeatCount     = float.MaxValue;
                animation.Duration        = 10.0f;
                animation.TimingFunction  = CAMediaTimingFunction.FromName(CAMediaTimingFunction.Linear);
                BallNode.AddAnimation(animation, new NSString("ballNodeAnimation"));

                // Rotate the ball to give the illusion of a rolling ball
                // We need two animations to do that:
                // - one rotation to orient the ball in the right direction
                // - one rotation to spin the ball
                animation          = CAKeyFrameAnimation.GetFromKeyPath("rotation");
                animation.KeyTimes = new NSNumber[] {
                    0.0f,
                    (0.7f / 8.0f),
                    (1.0f / 8.0f),
                    (2.0f / 8.0f),
                    (3.0f / 8.0f),
                    (3.3f / 8.0f),
                    (4.7f / 8.0f),
                    (5.0f / 8.0f),
                    (6.0f / 8.0f),
                    (7.0f / 8.0f),
                    (7.3f / 8.0f),
                    1.0f
                };

                animation.Values = new NSObject[] {
                    NSValue.FromVector(new SCNVector4(0, 1, 0, (float)(Math.PI / 4))),
                    NSValue.FromVector(new SCNVector4(0, 1, 0, (float)(Math.PI / 4))),
                    NSValue.FromVector(new SCNVector4(0, 1, 0, (float)(Math.PI / 2))),
                    NSValue.FromVector(new SCNVector4(0, 1, 0, (float)(Math.PI))),
                    NSValue.FromVector(new SCNVector4(0, 1, 0, (float)(Math.PI + Math.PI / 2))),
                    NSValue.FromVector(new SCNVector4(0, 1, 0, (float)(Math.PI * 2 - Math.PI / 4))),
                    NSValue.FromVector(new SCNVector4(0, 1, 0, (float)(Math.PI * 2 - Math.PI / 4))),
                    NSValue.FromVector(new SCNVector4(0, 1, 0, (float)(Math.PI * 2 - Math.PI / 2))),
                    NSValue.FromVector(new SCNVector4(0, 1, 0, (float)(Math.PI))),
                    NSValue.FromVector(new SCNVector4(0, 1, 0, (float)(Math.PI - Math.PI / 2))),
                    NSValue.FromVector(new SCNVector4(0, 1, 0, (float)(Math.PI / 4))),
                    NSValue.FromVector(new SCNVector4(0, 1, 0, (float)(Math.PI / 4)))
                };

                animation.RepeatCount    = float.MaxValue;
                animation.Duration       = 10.0f;
                animation.TimingFunction = CAMediaTimingFunction.FromName(CAMediaTimingFunction.Linear);
                BallNode.AddAnimation(animation, new NSString("ballNodeAnimation2"));

                var rotationAnimation = CABasicAnimation.FromKeyPath("rotation");
                rotationAnimation.Duration    = 1.0f;
                rotationAnimation.RepeatCount = float.MaxValue;
                rotationAnimation.To          = NSValue.FromVector(new SCNVector4(1, 0, 0, (float)(Math.PI * 2)));
                BallNode.ChildNodes [1].AddAnimation(rotationAnimation, new NSString("ballNodeRotation"));
                break;

            case 5:
                // Add a constraint to the camera
                SCNTransaction.Begin();
                SCNTransaction.AnimationDuration = 1;
                constraint = SCNLookAtConstraint.Create(BallNode);
                presentationViewController.CameraNode.Constraints = new SCNConstraint[] { constraint };
                SCNTransaction.Commit();
                break;

            case 6:
                // Add a constraint to the light
                SCNTransaction.Begin();
                SCNTransaction.AnimationDuration = 1;
                var cameraTarget = ContentNode.FindChildNode("cameraTarget", true);
                constraint = SCNLookAtConstraint.Create(cameraTarget);
                presentationViewController.SpotLight.Constraints = new SCNConstraint[] { constraint };
                SCNTransaction.Commit();
                break;
            }
        }
        public void SetProgress(float progress, bool animated)
        {
            if(progress < 0.0f)
                progress = 0.0f;
            else if(progress > 1.0f)
                progress = 1.0f;
            var rl = this.Layer as RoundProgressLayer;

            if(animated){
                CABasicAnimation animation = new CABasicAnimation();
                animation.KeyPath = "progress";
                animation.Duration = 0.25;
                animation.From = NSNumber.FromFloat(rl.Progress);
                animation.To = NSNumber.FromFloat(progress);
                rl.AddAnimation(animation,"progressAnimation");
                rl.Progress = progress;
            }
            else {
                rl.Progress = progress;
                rl.SetNeedsDisplay();
            }
        }
Example #48
0
        public override void PresentStep(int index, PresentationViewController presentationViewController)
        {
            switch (index)
            {
            case 0:
                break;

            case 1:
                TextManager.HighlightBullet(0);

                StaticShadowNode.Opacity = 1;

                var node = TextManager.AddCode("#aMaterial.#multiply#.contents = aShadowMap;#");
                node.Position = new SCNVector3(node.Position.X, node.Position.Y - 4, node.Position.Z);
                foreach (var child in node.ChildNodes)
                {
                    child.RenderingOrder = 1;
                    foreach (var m in child.Geometry.Materials)
                    {
                        m.ReadsFromDepthBuffer = false;
                    }
                }
                break;

            case 2:
                //move the tree
                PalmTree.RunAction(SCNAction.RotateBy(0, NMath.PI * 4, 0, 8));
                break;

            case 3:
                TextManager.FadesIn = true;
                TextManager.FadeOutText(SlideTextManager.TextType.Code);
                TextManager.AddEmptyLine();

                node = TextManager.AddCode("#aLight.#castsShadow# = YES;#");
                foreach (SCNNode child in node.ChildNodes)
                {
                    child.RenderingOrder = 1;
                    foreach (SCNMaterial m in child.Geometry.Materials)
                    {
                        m.ReadsFromDepthBuffer = false;
                        m.WritesToDepthBuffer  = false;
                    }
                }

                node.Position = new SCNVector3(node.Position.X, node.Position.Y - 6, node.Position.Z);

                SCNTransaction.Begin();
                SCNTransaction.AnimationDuration = 0.75f;

                var spot = presentationViewController.SpotLight;
                OldSpotShadowColor      = spot.Light.ShadowColor;
                spot.Light.ShadowColor  = NSColor.Black;
                spot.Light.ShadowRadius = 3;

                var tp = TextManager.TextNode.Position;

                var superNode = presentationViewController.CameraNode.ParentNode.ParentNode;

                var p0 = GroundNode.ConvertPositionToNode(SCNVector3.Zero, null);
                var p1 = GroundNode.ConvertPositionToNode(new SCNVector3(20, 0, 0), null);
                var tr = new SCNVector3(p1.X - p0.X, p1.Y - p0.Y, p1.Z - p0.Z);

                var p = superNode.Position;
                p.X  += tr.X;
                p.Y  += tr.Y;
                p.Z  += tr.Z;
                tp.X += 20;
                tp.Y += 0;
                tp.Z += 0;
                superNode.Position            = p;
                TextManager.TextNode.Position = tp;
                SCNTransaction.Commit();

                TextManager.HighlightBullet(1);

                break;

            case 4:
                //move the light
                var lightPivot = SCNNode.Create();
                lightPivot.Position = Character.Position;
                GroundNode.AddChildNode(lightPivot);

                spot            = presentationViewController.SpotLight;
                OldSpotPosition = spot.Position;
                OldSpotParent   = spot.ParentNode;
                OldSpotZNear    = spot.Light.ZNear;

                spot.Light.ZNear = 20;
                spot.Position    = lightPivot.ConvertPositionFromNode(spot.Position, spot.ParentNode);
                lightPivot.AddChildNode(spot);

                //add an object to represent the light
                var lightModel  = SCNNode.Create();
                var lightHandle = SCNNode.Create();
                var cone        = SCNCone.Create(0, 0.5f, 1);
                cone.RadialSegmentCount = 10;
                cone.HeightSegmentCount = 5;
                lightModel.Geometry     = cone;
                lightModel.Geometry.FirstMaterial.Emission.Contents = NSColor.Yellow;
                lightHandle.Position   = new SCNVector3(spot.Position.X * DIST, spot.Position.Y * DIST, spot.Position.Z * DIST);
                lightModel.CastsShadow = false;
                lightModel.EulerAngles = new SCNVector3(NMath.PI / 2, 0, 0);
                lightHandle.AddChildNode(lightModel);
                lightHandle.Constraints = new SCNConstraint[] { SCNLookAtConstraint.Create(Character) };
                lightPivot.AddChildNode(lightHandle);
                LightHandle = lightHandle;

                var animation = CABasicAnimation.FromKeyPath("eulerAngles.z");
                animation.From           = new NSNumber((nfloat)(Math.PI / 4) * 1.7f);
                animation.To             = new NSNumber((nfloat)(-Math.PI / 4) * 0.3f);
                animation.Duration       = 4;
                animation.AutoReverses   = true;
                animation.RepeatCount    = float.MaxValue;
                animation.TimingFunction = CAMediaTimingFunction.FromName(CAMediaTimingFunction.EaseInEaseOut);
                animation.TimeOffset     = animation.Duration / 2;
                lightPivot.AddAnimation(animation, new NSString("lightAnim"));
                break;

            case 5:
                TextManager.FadeOutText(SlideTextManager.TextType.Code);
                var text = TextManager.AddCode("#aLight.#shadowMode# =\n#SCNShadowModeModulated#;\naLight.#gobo# = anImage;#");
                text.Position = new SCNVector3(text.Position.X, text.Position.Y - 6, text.Position.Z);
                text.EnumerateChildNodes((SCNNode child, out bool stop) => {
                    stop = false;
                    child.RenderingOrder = 1;
                    foreach (var m in child.Geometry.Materials)
                    {
                        m.ReadsFromDepthBuffer = false;
                        m.WritesToDepthBuffer  = false;
                    }
                    return(stop);
                });

                LightHandle.RemoveFromParentNode();

                RestoreSpotPosition(presentationViewController);
                TextManager.HighlightBullet(2);


                spot = presentationViewController.SpotLight;
                spot.Light.CastsShadow = false;

                var head = Character.FindChildNode("Bip001_Pelvis", true);

                node                      = SCNNode.Create();
                node.Light                = SCNLight.Create();
                node.Light.LightType      = SCNLightType.Spot;
                node.Light.SpotOuterAngle = 30;
                node.Constraints          = new SCNConstraint[] { SCNLookAtConstraint.Create(head) };
                node.Position             = new SCNVector3(0, 220, 0);
                node.Light.ZNear          = 10;
                node.Light.ZFar           = 1000;
                node.Light.Gobo.Contents  = new NSImage(NSBundle.MainBundle.PathForResource("SharedTextures/blobShadow", "jpg"));
                node.Light.Gobo.Intensity = 0.65f;
                node.Light.ShadowMode     = SCNShadowMode.Modulated;

                //exclude character from shadow
                node.Light.CategoryBitMask = 0x1;
                Character.FindNodes((SCNNode child, out bool stop) => {
                    stop = false;
                    child.CategoryBitMask = 0x2;
                    return(stop);
                });

                Projector = node;
                Character.AddChildNode(node);

                break;
            }
        }
        void StartInkAtPoint(CGPoint point, bool animated)
        {
            nfloat radius = FinalRadius;

            if (MaxRippleRadius > 0)
            {
                radius = MaxRippleRadius;
            }
            CGRect ovalRect = new CGRect(Bounds.Width / 2 - radius,
                                         Bounds.Height / 2 - radius,
                                         radius * 2,
                                         radius * 2);
            UIBezierPath circlePath = UIBezierPath.FromOval(ovalRect);

            Path      = circlePath.CGPath;
            FillColor = InkColor.CGColor;
            if (!animated)
            {
                Opacity  = 1;
                Position = new CGPoint(Bounds.Width / 2, Bounds.Height / 2);
            }
            else
            {
                Opacity  = 0;
                Position = point;
                _startAnimationActive = true;

                CAMediaTimingFunction materialTimingFunction = CAMediaTimingFunction.FromControlPoints(0.4f, 0, 0.2f, 1.0f);
                nfloat scaleStart = (nfloat)(Math.Min(Bounds.Width, Bounds.Height) / MDCInkLayerScaleDivisor);
                if (scaleStart < MDCInkLayerScaleStartMin)
                {
                    scaleStart = MDCInkLayerScaleStartMin;
                }
                else if (scaleStart > MDCInkLayerScaleStartMax)
                {
                    scaleStart = MDCInkLayerScaleStartMax;
                }

                CABasicAnimation scaleAnim = new CABasicAnimation
                {
                    KeyPath             = MDCInkLayerScaleString,
                    From                = new NSNumber(scaleStart),
                    To                  = new NSNumber(1.0f),
                    Duration            = MDCInkLayerStartScalePositionDuration,
                    BeginTime           = MDCInkLayerCommonDuration,
                    TimingFunction      = materialTimingFunction,
                    FillMode            = CAFillMode.Forwards,
                    RemovedOnCompletion = true
                };

                UIBezierPath centerPath = new UIBezierPath();
                CGPoint      startPoint = point;
                CGPoint      endPoint   = new CGPoint(Bounds.Width / 2, Bounds.Height / 2);
                centerPath.MoveTo(startPoint);
                centerPath.AddLineTo(endPoint);
                centerPath.ClosePath();

                CAKeyFrameAnimation positionAnim = new CAKeyFrameAnimation
                {
                    KeyPath             = MDCInkLayerPositionString,
                    Path                = centerPath.CGPath,
                    KeyTimes            = new NSNumber[] { 0, 1.0f },
                    Values              = new NSNumber[] { 0, 1.0f },
                    Duration            = MDCInkLayerStartScalePositionDuration,
                    BeginTime           = MDCInkLayerCommonDuration,
                    TimingFunction      = materialTimingFunction,
                    FillMode            = CAFillMode.Forwards,
                    RemovedOnCompletion = false
                };

                CABasicAnimation fadeInAnim = new CABasicAnimation();
                fadeInAnim.KeyPath             = MDCInkLayerOpacityString;
                fadeInAnim.From                = new NSNumber(0);
                fadeInAnim.To                  = new NSNumber(1.0f);
                fadeInAnim.Duration            = MDCInkLayerCommonDuration;
                fadeInAnim.BeginTime           = MDCInkLayerCommonDuration;
                fadeInAnim.TimingFunction      = CAMediaTimingFunction.FromName(CAMediaTimingFunction.Linear);
                fadeInAnim.FillMode            = CAFillMode.Forwards;
                fadeInAnim.RemovedOnCompletion = false;

                CATransaction.Begin();
                CAAnimationGroup animGroup = new CAAnimationGroup();
                animGroup.Animations          = new CAAnimation[] { scaleAnim, positionAnim, fadeInAnim };
                animGroup.Duration            = MDCInkLayerStartScalePositionDuration;
                animGroup.FillMode            = CAFillMode.Forwards;
                animGroup.RemovedOnCompletion = false;
                CATransaction.CompletionBlock = new Action(() => { _startAnimationActive = false; });

                AddAnimation(animGroup, null);
                CATransaction.Commit();
            }

            //if (AnimationDelegate respondsToSelector: @selector(inkLayerAnimationDidStart:))
            //{
            //    [self.animationDelegate inkLayerAnimationDidStart:self];
            //}
        }
Example #50
0
        public override void SetupSlide(PresentationViewController presentationViewController)
        {
            // Set the slide's title and subtile and add some text
            TextManager.SetTitle("Node Attributes");
            TextManager.SetSubtitle("SCNGeometry");

            TextManager.AddBulletAtLevel("Triangles", 0);
            TextManager.AddBulletAtLevel("Vertices", 0);
            TextManager.AddBulletAtLevel("Normals", 0);
            TextManager.AddBulletAtLevel("UVs", 0);
            TextManager.AddBulletAtLevel("Materials", 0);

            // We create a container for several versions of the teapot model
            // - one teapot to show positions and normals
            // - one teapot to show texture coordinates
            // - one teapot to show materials
            var allTeapotsNode = SCNNode.Create();

            allTeapotsNode.Rotation = new SCNVector4(1, 0, 0, -(float)(Math.PI / 2));
            GroundNode.AddChildNode(allTeapotsNode);

            TeapotNodeForPositionsAndNormals = Utils.SCAddChildNode(allTeapotsNode, "TeapotLowRes", "Scenes.scnassets/teapots/teapotLowRes", 17);
            TeapotNodeForUVs       = Utils.SCAddChildNode(allTeapotsNode, "Teapot", "Scenes.scnassets/teapots/teapot", 17);
            TeapotNodeForMaterials = Utils.SCAddChildNode(allTeapotsNode, "teapotMaterials", "Scenes.scnassets/teapots/teapotMaterial", 17);

            TeapotNodeForPositionsAndNormals.Position = new SCNVector3(4, 0, 0);
            TeapotNodeForUVs.Position       = new SCNVector3(4, 0, 0);
            TeapotNodeForMaterials.Position = new SCNVector3(4, 0, 0);

            foreach (var child in TeapotNodeForMaterials.ChildNodes)
            {
                foreach (var material in child.Geometry.Materials)
                {
                    material.Multiply.Contents = new NSImage(NSBundle.MainBundle.PathForResource("Scenes.scnassets/teapots/UVs", "png"));
                    material.Multiply.WrapS    = SCNWrapMode.Repeat;
                    material.Multiply.WrapT    = SCNWrapMode.Repeat;
                    //material.Reflective.Contents = NSColor.White;
                    //material.Reflective.Intensity = 3.0f;
                    //material.FresnelExponent = 3.0f;
                }
            }

            // Animate the teapots (rotate forever)
            var rotationAnimation = CABasicAnimation.FromKeyPath("rotation");

            rotationAnimation.Duration    = 40.0f;
            rotationAnimation.RepeatCount = float.MaxValue;
            rotationAnimation.To          = NSValue.FromVector(new SCNVector4(0, 0, 1, (float)(Math.PI * 2)));

            TeapotNodeForPositionsAndNormals.AddAnimation(rotationAnimation, new NSString("teapotNodeForPositionsAndNormalsAnimation"));
            TeapotNodeForUVs.AddAnimation(rotationAnimation, new NSString("teapotNodeForUVsAnimation"));
            TeapotNodeForMaterials.AddAnimation(rotationAnimation, new NSString("teapotNodeForMaterialsAnimation"));

            // Load the "explode" shader modifier and add it to the geometry
            //var explodeShaderPath = NSBundle.MainBundle.PathForResource ("Shaders/explode", "shader");
            //var explodeShaderSource = System.IO.File.ReadAllText (explodeShaderPath);
            // TODO TeapotNodeForPositionsAndNormals.Geometry.ShaderModifiers = new SCNShaderModifiers { EntryPointGeometry = explodeShaderSource };

            PositionsVisualizationNode = SCNNode.Create();
            NormalsVisualizationNode   = SCNNode.Create();

            // Build nodes that will help visualize the vertices (position and normal)
            BuildVisualizationsOfNode(TeapotNodeForPositionsAndNormals, ref PositionsVisualizationNode, ref NormalsVisualizationNode);

            NormalsVisualizationNode.CastsShadow = false;

            TeapotNodeForMaterials.AddChildNode(PositionsVisualizationNode);
            TeapotNodeForMaterials.AddChildNode(NormalsVisualizationNode);
        }
		private void DrawMarker (CGRect rowRect, float position)
		{
			if (Layer.Sublayers != null) {
				Layer.Sublayers = new CALayer[0];
			}

			var visibleRect = Layer.Bounds;
			var currentTimeRect = visibleRect;

			// The red band of the timeMaker will be 7 pixels wide
			currentTimeRect.X = 0f;
			currentTimeRect.Width = 7f;

			var timeMarkerRedBandLayer = new CAShapeLayer ();
			timeMarkerRedBandLayer.Frame = currentTimeRect;
			timeMarkerRedBandLayer.Position = new CGPoint (rowRect.X, Bounds.Height / 2f);

			var linePath = CGPath.FromRect (currentTimeRect);
			timeMarkerRedBandLayer.FillColor = UIColor.FromRGBA (1.00f, 0.00f, 0.00f, 0.50f).CGColor;

			timeMarkerRedBandLayer.Path = linePath;

			currentTimeRect.X = 0f;
			currentTimeRect.Width = 1f;

			CAShapeLayer timeMarkerWhiteLineLayer = new CAShapeLayer ();
			timeMarkerWhiteLineLayer.Frame = currentTimeRect;
			timeMarkerWhiteLineLayer.Position = new CGPoint (3f, Bounds.Height / 2f);

			CGPath whiteLinePath = CGPath.FromRect (currentTimeRect);
			timeMarkerWhiteLineLayer.FillColor = UIColor.FromRGBA (1.00f, 1.00f, 1.00f, 1.00f).CGColor;
			timeMarkerWhiteLineLayer.Path = whiteLinePath;

			timeMarkerRedBandLayer.AddSublayer (timeMarkerWhiteLineLayer);
			CABasicAnimation scrubbingAnimation = new CABasicAnimation ();
			scrubbingAnimation.KeyPath = "position.x";

			scrubbingAnimation.From = new NSNumber (HorizontalPositionForTime (CMTime.Zero));
			scrubbingAnimation.To = new NSNumber (HorizontalPositionForTime (duration));
			scrubbingAnimation.RemovedOnCompletion = false;
			scrubbingAnimation.BeginTime = 0.000000001;
			scrubbingAnimation.Duration = duration.Seconds;
			scrubbingAnimation.FillMode = CAFillMode.Both;
			timeMarkerRedBandLayer.AddAnimation (scrubbingAnimation, null);
			if (Player != null) {
				Console.WriteLine ("Duration in  seconds - " + Player.CurrentItem.Asset.Duration.Seconds);
				var syncLayer = new AVSynchronizedLayer () {
					PlayerItem = Player.CurrentItem,
				};
				syncLayer.AddSublayer (timeMarkerRedBandLayer);
				Layer.AddSublayer (syncLayer);
			}
		}
Example #52
0
        void AddAnimations(bool desireSelectedState)
        {
            var circleAnimationDuration = animationDuration * 0.5;

            var checkmarkEndDuration    = animationDuration * 0.8;
            var checkmarkStartDuration  = checkmarkEndDuration - circleAnimationDuration;
            var checkmarkBounceDuration = animationDuration - checkmarkEndDuration;

            var checkmarkAnimationGroup = new CAAnimationGroup();

            checkmarkAnimationGroup.RemovedOnCompletion = false;
            checkmarkAnimationGroup.FillMode            = CAFillMode.Forwards;
            checkmarkAnimationGroup.Duration            = animationDuration;
            checkmarkAnimationGroup.TimingFunction      = CAMediaTimingFunction.FromName(CAMediaTimingFunction.Linear);

            var checkmarkStrokeEndAnimation = CAKeyFrameAnimation.FromKeyPath("strokeEnd");

            checkmarkStrokeEndAnimation.Duration            = checkmarkEndDuration + checkmarkBounceDuration;
            checkmarkStrokeEndAnimation.RemovedOnCompletion = false;
            checkmarkStrokeEndAnimation.FillMode            = CAFillMode.Forwards;
            checkmarkStrokeEndAnimation.CalculationMode     = CAAnimation.AnimationPaced;

            if (desireSelectedState)
            {
                checkmarkStrokeEndAnimation.Values = new NSObject[] { NSNumber.FromFloat(0),
                                                                      NSNumber.FromFloat(finalStrokeEndForCheckmark + checkmarkBounceAmount),
                                                                      NSNumber.FromFloat(finalStrokeEndForCheckmark) };

                checkmarkStrokeEndAnimation.KeyTimes = new NSNumber[] { NSNumber.FromDouble(0),
                                                                        NSNumber.FromDouble(checkmarkEndDuration),
                                                                        NSNumber.FromDouble(checkmarkEndDuration + checkmarkBounceDuration) };
            }
            else
            {
                checkmarkStrokeEndAnimation.Values = new NSObject[] { NSNumber.FromFloat(finalStrokeEndForCheckmark),
                                                                      NSNumber.FromFloat(finalStrokeEndForCheckmark + checkmarkBounceAmount),
                                                                      NSNumber.FromFloat(-0.1f) };

                checkmarkStrokeEndAnimation.KeyTimes = new NSNumber[] { NSNumber.FromDouble(0),
                                                                        NSNumber.FromDouble(checkmarkBounceDuration),
                                                                        NSNumber.FromDouble(checkmarkEndDuration + checkmarkBounceDuration) };
            }

            var checkmarkStrokeStartAnimation = CAKeyFrameAnimation.FromKeyPath("strokeStart");

            checkmarkStrokeStartAnimation.Duration            = checkmarkStartDuration + checkmarkBounceDuration;
            checkmarkStrokeStartAnimation.RemovedOnCompletion = false;
            checkmarkStrokeStartAnimation.FillMode            = CAFillMode.Forwards;
            checkmarkStrokeStartAnimation.CalculationMode     = CAAnimation.AnimationPaced;

            if (desireSelectedState)
            {
                checkmarkStrokeStartAnimation.Values = new NSObject[] { NSNumber.FromFloat(0),
                                                                        NSNumber.FromFloat(finalStrokeStartForCheckmark + checkmarkBounceAmount),
                                                                        NSNumber.FromFloat(finalStrokeStartForCheckmark) };

                checkmarkStrokeStartAnimation.KeyTimes = new NSNumber[] { NSNumber.FromDouble(0),
                                                                          NSNumber.FromDouble(checkmarkStartDuration),
                                                                          NSNumber.FromDouble(checkmarkStartDuration + checkmarkBounceDuration) };
            }
            else
            {
                checkmarkStrokeStartAnimation.Values = new NSObject[] { NSNumber.FromFloat(finalStrokeStartForCheckmark),
                                                                        NSNumber.FromFloat(finalStrokeStartForCheckmark + checkmarkBounceAmount),
                                                                        NSNumber.FromFloat(0) };

                checkmarkStrokeStartAnimation.KeyTimes = new NSNumber[] { NSNumber.FromDouble(0),
                                                                          NSNumber.FromDouble(checkmarkBounceDuration),
                                                                          NSNumber.FromDouble(checkmarkStartDuration + checkmarkBounceDuration) };
            }

            if (desireSelectedState)
            {
                checkmarkStrokeStartAnimation.BeginTime = circleAnimationDuration;
            }

            checkmarkAnimationGroup.Animations = new CAAnimation[] { checkmarkStrokeEndAnimation, checkmarkStrokeStartAnimation };
            checkmark.AddAnimation(checkmarkAnimationGroup, "checkmarkAnimation");

            var circleAnimationGroup = new CAAnimationGroup();

            circleAnimationGroup.RemovedOnCompletion = false;
            circleAnimationGroup.FillMode            = CAFillMode.Forwards;
            circleAnimationGroup.Duration            = animationDuration;
            circleAnimationGroup.TimingFunction      = CAMediaTimingFunction.FromName(CAMediaTimingFunction.Linear);

            var circleStrokeEnd = CABasicAnimation.FromKeyPath("strokeEnd");

            circleStrokeEnd.Duration = circleAnimationDuration;

            if (desireSelectedState)
            {
                circleStrokeEnd.BeginTime = 0;
                circleStrokeEnd.SetFrom(NSNumber.FromFloat(1));
                circleStrokeEnd.SetTo(NSNumber.FromFloat(-0.1f));
            }
            else
            {
                circleStrokeEnd.BeginTime = animationDuration - circleAnimationDuration;
                circleStrokeEnd.SetFrom(NSNumber.FromFloat(0));
                circleStrokeEnd.SetTo(NSNumber.FromFloat(1));
            }

            circleStrokeEnd.RemovedOnCompletion = false;
            circleStrokeEnd.FillMode            = CAFillMode.Forwards;

            circleAnimationGroup.Animations = new CAAnimation[] { circleStrokeEnd };

            if (animationDelegate == null)
            {
                animationDelegate = new AnimationDelegate(this);
            }
            circleAnimationGroup.Delegate = animationDelegate;

            circle.AddAnimation(circleAnimationGroup, "circleStrokeEnd");

            var trailCircleColor = CABasicAnimation.FromKeyPath("opacity");

            trailCircleColor.Duration = animationDuration;

            if (desireSelectedState)
            {
                trailCircleColor.SetFrom(NSNumber.FromFloat(0));
                trailCircleColor.SetTo(NSNumber.FromFloat(1));
            }
            else
            {
                trailCircleColor.SetFrom(NSNumber.FromFloat(1));
                trailCircleColor.SetTo(NSNumber.FromFloat(0));
            }
            trailCircleColor.TimingFunction      = CAMediaTimingFunction.FromName(CAMediaTimingFunction.Linear);
            trailCircleColor.FillMode            = CAFillMode.Forwards;
            trailCircleColor.RemovedOnCompletion = false;
            trailCircle.AddAnimation(trailCircleColor, "trailCircleColor");
        }
Example #53
0
		void AnimateDynamicNodes ()
		{
			SCNNode dummyFront = RootNode.FindChildNode ("dummy_front", true);
			var dynamicNodesWithVertColorAnimation = new List<SCNNode> ();

			foreach (var split in dummyFront.ChildNodes)
				foreach (var splitElement in split.ChildNodes)
					foreach (var child in splitElement.ChildNodes) {

						var range = new NSRange ();
						if (!string.IsNullOrEmpty (child.ParentNode.Name)) {
							int index = child.ParentNode.Name.LastIndexOf ("vine");
							range = new NSRange (index, 4);
						}

						if (child.Geometry != null && child.Geometry.GetGeometrySourcesForSemantic (SCNGeometrySourceSemantic.Color) != null
						    && range.Location != NSRange.NotFound) {
							dynamicNodesWithVertColorAnimation.Add (child);
						}
					}

			string shaderCode = "uniform float timeOffset;\n" +
			                    "#pragma body\n" +
			                    "float speed = 20.05;\n" +
			                    "_geometry.position.xyz += (speed * sin(u_time + timeOffset) * _geometry.color.rgb);\n";

			foreach (SCNNode dynamicNode in dynamicNodesWithVertColorAnimation) {
				dynamicNode.Geometry.ShaderModifiers = new SCNShaderModifiers { EntryPointGeometry = shaderCode };
				var explodeAnimation = new CABasicAnimation {
					KeyPath = "timeOffset",
					Duration = 2.0,
					RepeatCount = float.MaxValue,
					AutoReverses = true,
					To = new NSNumber (MathUtils.RandomPercent ()),
					TimingFunction = CAMediaTimingFunction.FromName (CAMediaTimingFunction.EaseInEaseOut)
				};

				dynamicNode.Geometry.AddAnimation (explodeAnimation, (NSString)"sway");
			}
		}
                                                                                                                     
 void ApplyAnimation()
                                                                                                                     {
                                                                                                                         
 //already started
            if (PhoneButton.Layer.Sublayers.Count() > 2) return;

                                                                                                                             shape = new CAShapeLayer();

                                                                                                                         shape.Bounds      = new CGRect(0, 0, PhoneButton.Frame.Width, PhoneButton.Frame.Height);
                                                                                                                         shape.Position    = new CGPoint(PhoneButton.Frame.Width / 2, PhoneButton.Frame.Height / 2);
                                                                                                                         shape.Path        = UIBezierPath.FromOval(PhoneButton.Bounds).CGPath;
                                                                                                                         shape.StrokeColor = UIColor.White.CGColor;
                                                                                                                         shape.LineWidth   = (nfloat).5;
                                                                                                                         shape.FillColor   = UIColor.Clear.CGColor;
                                                                                                                         PhoneButton.Layer.AddSublayer(shape);

                                                                                                                         CABasicAnimation grow = CABasicAnimation.FromKeyPath("transform.scale");

                                                                                                                         grow.From                = NSObject.FromObject(0);
                                                                                                                         grow.Duration            = 2;
                                                                                                                         grow.To                  = NSObject.FromObject(3);
                                                                                                                         grow.FillMode            = CAFillMode.Forwards;
                                                                                                                         grow.RepeatCount         = 10000;
                                                                                                                         grow.RemovedOnCompletion = false;
                                                                                                                         shape.AddAnimation(grow, "grow"); 

 SharingButton.SetTitle("Sharing", new UIControlState()); 

                                                                                                                     }