Пример #1
0
        public void OnFixedUpdate()
        {
            toPosition.DoWhenAbsent(() =>
            {
                var target = Vector2.zero;
                if (Position.PlayerLocation.Equals(gunDefinition.ToPosition))
                {
                    GameProvider.GetGameView().ToMaybe()
                    .Do(game =>
                    {
                        var playerPoint = game.GetPlayerPoints().Choose();
                        var tileSize    = CanvasHelper.GetTileSize();
                        var multiplier  = random.Next(2) == 1 ? 1 : -1;
                        if (CanvasHelper.IsLeft(playerPoint.Position) ||
                            CanvasHelper.IsRight(playerPoint.Position))
                        {
                            target = playerPoint.ScreenPosition +
                                     new Vector2(0f, random.Next((int)(tileSize.y)) * multiplier);
                        }
                        else
                        {
                            target = playerPoint.ScreenPosition +
                                     new Vector2(random.Next((int)(tileSize.x * 2)) * multiplier, 0f);
                        }
                    });
                }
                else
                {
                    target = CanvasHelper.GetCanvasPosition(gunDefinition.ToPosition, view.MainRectTransform);
                }

                toPosition = target.ToMaybe();
                view.RotateTowards(target);
            });
        }
Пример #2
0
    public void FloatAndFade(Vector3 worldPosition, int scoreAmount, System.Action completed = null)
    {
        //Reset values
        this.scoreAmount = scoreAmount;

        startRectPosition     = CanvasHelper.WorldPointToCanvasPoint(gameplayCam, gameplayCanvas, worldPosition);
        startRectPosition.y  += (verticalPadding - 10);
        targetRectPosition    = startRectPosition;
        targetRectPosition.y += verticalPadding;

        startColor    = scoreText.color;
        startColor.a  = 1;
        targetColor   = startColor;
        targetColor.a = 0;

        startScale  = Vector3.one;
        targetScale = startScale * scaleFactor;


        if (floatFadeCR != null)
        {
            StopCoroutine(floatFadeCR);
        }

        floatFadeCR = StartCoroutine(CR_FloatAndFade(completed));
    }
Пример #3
0
        /// <summary>
        /// Gets the nearest line segment index from the given point.
        /// </summary>
        /// <returns>The smaller index of the segment vertex, or -1 if the point is too far from the segments.</returns>
        protected static int GetSegmentIndex(IList <Point> vertices, Point point, double maxDistance = 5)
        {
            if (vertices.Count < 2)
            {
                return(-1);
            }
            var nearestIndex = -1;
            var nearestDist  = double.PositiveInfinity;

            for (int i = 0, j = vertices.Count - 1; i < j; i++)
            {
                if (!CanvasHelper.IsBetweenPoints(point, vertices[i], vertices[i + 1]))
                {
                    continue;
                }
                var dist = CanvasHelper.DistanceToLine(point, vertices[i], vertices[i + 1]);
                if (dist > maxDistance)
                {
                    continue;
                }
                if (dist < nearestDist)
                {
                    nearestIndex = i;
                    nearestDist  = dist;
                }
            }
            return(nearestIndex);
        }
Пример #4
0
 public PlayingState(CanvasHelper _cv, Dictionary <string, object> res, Game.PlayerWraper playing) : base(_cv, res, playing)
 {
     for (int i = 0; i < segments.Length; ++i)
     {
         segments[i] += stageOffset;
     }
 }
Пример #5
0
        public void RotateTowards(Vector3 target)
        {
            var vectorToTarget = target - CanvasHelper.InverseTransformPoint(rectTransform.position);
            var angle          = Mathf.Atan2(vectorToTarget.y, vectorToTarget.x) * Mathf.Rad2Deg;
            var q = Quaternion.AngleAxis(angle, Vector3.forward);

            transform.rotation = q;
        }
Пример #6
0
 public void OnFixedUpdate()
 {
     currentWayPointIndex.DoWhenAbsent(() =>
     {
         view.SetAnchoredPosition(CanvasHelper.GetCanvasPosition(enemyViewModel.PathDefinition.SpawnPosition));
         NextWayPoint();
     });
 }
        /// <summary>
        /// Creates a `StackableSplitter` directly on
        /// top of this stack and sets its parent to
        /// the canvas.
        /// </summary>
        /// <param name="stack">The `Stackable` to create a `StacakbleSplitter` for</param>
        public static void Create(Stackable stack)
        {
            GameObject stackableSplitterResource = Resources.Load(stackableSplitterPath) as GameObject;
            GameObject stackableSplitterObject   = GameObject.Instantiate(stackableSplitterResource, stack.transform.position, Quaternion.identity) as GameObject;

            stackableSplitterObject.transform.SetParent(CanvasHelper.GetCanvas().transform);
            StackableSplitter stackableSplitter = stackableSplitterObject.GetComponent <StackableSplitter>();

            stackableSplitter.Stack = stack;
        }
Пример #8
0
 public void OnFixedUpdate()
 {
     toPosition.DoWhenAbsent(() =>
     {
         var start = CanvasHelper.GetCanvasPosition(powerUpDefinition.FromPosition, view.MainRectTransform);
         view.SetAnchoredPosition(start);
         var target = CanvasHelper.GetCanvasPosition(powerUpDefinition.ToPosition, view.MainRectTransform);
         toPosition = target.ToMaybe();
     });
 }
Пример #9
0
        public async Task <Size> DrawVacationText(int dim, string font, string text, string saved_file)
        {
            Size         size   = new Size();
            CanvasDevice device = CanvasDevice.GetSharedDevice();

            using (CanvasRenderTarget offscreen = CanvasHelper.GenImage(dim, dim, Colors.White))
            {
                CanvasTextFormat format = new CanvasTextFormat();
                format.FontFamily = font;
                format.FontStyle  = Windows.UI.Text.FontStyle.Normal;
                format.FontSize   = 52;
                format.FontWeight = Windows.UI.Text.FontWeights.Black;

                float            layoutWidth  = dim;
                float            layoutHeight = dim;
                CanvasTextLayout textLayout   = new CanvasTextLayout(device, text, format, layoutWidth, layoutHeight);

                Color light_purple = Color.FromArgb(255, 102, 159, 206);
                Color dark_purple  = Color.FromArgb(255, 35, 68, 95);
                Point pt           = new Point(10.0, 10.0);
                using (var strategyOutline3 = CanvasHelper.TextGradOutline(light_purple, dark_purple, light_purple, 9, GradientType.Linear))
                {
                    CanvasHelper.DrawTextImage(strategyOutline3, offscreen, pt, textLayout);
                }

                CanvasRenderTarget maskOutline2;
                using (var strategyOutline2 = CanvasHelper.TextNoOutline(MaskColor.Blue))
                {
                    maskOutline2 = CanvasHelper.GenMask(strategyOutline2, dim, dim, pt, textLayout);
                }
                Color light_yellow = Color.FromArgb(255, 255, 227, 85);
                Color dark_yellow  = Color.FromArgb(255, 243, 163, 73);
                using (CanvasRenderTarget text_image = CanvasHelper.GenImage(dim, dim, dark_yellow))
                {
                    using (var strategyText2 = CanvasHelper.TextGradOutlineLast(light_yellow, dark_yellow, light_yellow, 9, GradientType.Sinusoid))
                    {
                        CanvasHelper.DrawTextImage(strategyText2, text_image, pt, textLayout);
                        CanvasHelper.ApplyImageToMask(text_image, maskOutline2, offscreen, MaskColor.Blue, true);
                    }
                }

                Windows.Storage.StorageFolder storageFolder =
                    Windows.Storage.ApplicationData.Current.TemporaryFolder;
                string saved_file2 = "\\";
                saved_file2 += saved_file;
                await offscreen.SaveAsync(storageFolder.Path + saved_file2);

                imgOutlineText.Source = new BitmapImage(new Uri(storageFolder.Path + saved_file2));

                return(size);
            }
        }
Пример #10
0
        private void Update()
        {
            if (isExploting)
            {
                return;
            }

            playerPoints = CanvasHelper.GetPlayerPoints(GetScreenPosition(), 5);

            if (Input.GetButton("Fire1"))
            {
                presenter.OnFirePressed();
            }
        }
Пример #11
0
        public JsonResult DeleteTemplate(string path, string controlType)
        {
            if (System.IO.File.Exists(Server.MapPath(path)))
            {
                System.IO.File.Delete(Server.MapPath(path));

                var templates = CanvasHelper.GetTemplates(controlType);

                return(Json(new { success = true, templates = templates }));
            }
            else
            {
                return(Json(new { success = false, message = "Template file not found" }));
            }
        }
Пример #12
0
        public JsonResult SaveTemplate(string name, string content, string controlType)
        {
            if (System.IO.File.Exists(Server.MapPath("/Views/Canvas/Templates/" + controlType + "/" + name + ".cshtml")))
            {
                System.IO.File.WriteAllText(Server.MapPath("/Views/Canvas/Templates/" + controlType + "/" + name + ".cshtml"), content, Encoding.UTF8);

                var templates = CanvasHelper.GetTemplates(controlType);

                return(Json(new { success = true, templates = templates }));
            }
            else
            {
                return(Json(new { success = false, message = "Template does not exist" }));
            }
        }
Пример #13
0
 public void OnIsRayed()
 {
     if (this.canvas == null)
     {
         this.canvas = ComponentManager <CanvasHelper> .Value;
     }
     if (this.localPlayer == null)
     {
         this.localPlayer = ComponentManager <Network_Player> .Value;
     }
     if (CanvasHelper.ActiveMenu != MenuType.None || !Helper.LocalPlayerIsWithinDistance(base.transform.position, Player.UseDistance))
     {
         if (this.showingText)
         {
             this.canvas.displayTextManager.HideDisplayTexts();
             this.showingText = false;
         }
         return;
     }
     if (skyController.timeOfDay.hour < 5 || skyController.timeOfDay.hour > 19)
     {
         this.canvas.displayTextManager.ShowText("Its the spooky night! The solar panel won't work!", 0, true, 0);
         this.showingText = true;
         return;
     }
     if (!battery.BatterySlotIsEmpty)
     {
         if (battery.GetBatteryInstance().Uses < batteryMaxUses)
         {
             float progress = (float)battery.GetBatteryInstance().Uses / (float)batteryMaxUses;
             this.canvas.displayTextManager.ShowText("The battery is charging... (" + Mathf.Round(progress * 100) + "%)", 0, true, 0);
             this.showingText = true;
         }
         else
         {
             this.canvas.displayTextManager.ShowText("The battery is fully charged!", 0, true, 0);
             this.showingText = true;
         }
     }
     else
     {
         this.canvas.displayTextManager.ShowText("No battery, place one to charge it!", 0, true, 0);
         this.showingText = true;
         return;
     }
 }
Пример #14
0
        private void UpdateFruit(FruitChangedEventArgs e)
        {
            if (!e.IsEaten)
            {
                _fruit = e.FruitUpdated;

                _fruitFrameworkElement = CanvasHelper.FruitControlFactory(_fruit, _scale);
                _sprites.Add(_fruitFrameworkElement);
                CanvasHelper.ResizeElement(_fruitFrameworkElement, _fruit.Size.Width * _scale, _fruit.Size.Height * _scale);
            }
            else
            {
                this._fruit = null;
                _sprites.Remove(_fruitFrameworkElement);
                _fruitFrameworkElement = null;
            }
        }
Пример #15
0
        private void NextWayPoint()
        {
            var next = currentWayPointIndex.SelectOrElse(index => index + 1, () => 0);

            if (enemyViewModel.PathDefinition.WayPoints.Length > next)
            {
                currentWayPoint      = enemyViewModel.PathDefinition.WayPoints.ElementAt(next);
                currentWayPointIndex = next.ToMaybe();
                target = CanvasHelper.GetCanvasPosition(currentWayPoint.Position);
                view.RotateTowards(target);
            }
            else
            {
                removeCollision.Execute(view);
                view.DestroyView();
            }
        }
Пример #16
0
        public async Task <Size> DrawOutlineTextWithLibrary(int dim, string font, string text, string saved_file)
        {
            Size         size   = new Size();
            CanvasDevice device = CanvasDevice.GetSharedDevice();

            using (CanvasRenderTarget offscreen = new CanvasRenderTarget(device, dim, dim, 96, Windows.Graphics.DirectX.DirectXPixelFormat.B8G8R8A8UIntNormalized,
                                                                         CanvasAlphaMode.Premultiplied))
            {
                using (CanvasDrawingSession ds = offscreen.CreateDrawingSession())
                {
                    ds.Clear(Colors.White);
                }
                Color text_color = Colors.White;

                CanvasSolidColorBrush brush  = new CanvasSolidColorBrush(device, text_color);
                CanvasTextFormat      format = new CanvasTextFormat();
                format.FontFamily = font;
                format.FontStyle  = Windows.UI.Text.FontStyle.Normal;
                format.FontSize   = 60;
                format.FontWeight = Windows.UI.Text.FontWeights.Bold;

                float            layoutWidth  = dim;
                float            layoutHeight = dim;
                CanvasTextLayout textLayout   = new CanvasTextLayout(device, text, format, layoutWidth, layoutHeight);

                ITextStrategy strat = CanvasHelper.TextOutline(Colors.Blue, Colors.Black, 10);
                CanvasHelper.DrawTextImage(strat, offscreen, new Point(10.0, 10.0), textLayout);

                Windows.Storage.StorageFolder storageFolder =
                    Windows.Storage.ApplicationData.Current.TemporaryFolder;
                string saved_file2 = "\\";
                saved_file2 += saved_file;
                await offscreen.SaveAsync(storageFolder.Path + saved_file2);

                imgOutlineText.Source = new BitmapImage(new Uri(storageFolder.Path + saved_file2));

                using (CanvasDrawingSession ds = offscreen.CreateDrawingSession())
                {
                    ds.Clear(Colors.White);
                }

                return(size);
            }
        }
Пример #17
0
        public async Task <StatusCheck> Get(string ouNetId, string assignmentId, string courseId, string minimumGrade)
        {
            var result = new StatusCheck();
            var assignmentSubmission = await CanvasHelper.GetSubmissionGradeOfAssignmentForUser(ouNetId, assignmentId, courseId);

            if (minimumGrade.IsNumber())
            {
                if (assignmentSubmission.Grade.IsNumber())
                {
                    if (Convert.ToDouble(assignmentSubmission.Grade) >= Convert.ToDouble(minimumGrade))
                    {
                        result.IsComplete      = true;
                        result.PercentComplete = 1.0;
                    }
                }
                else
                {
                    result.IsComplete = false;
                    result.Exception  = new ExceptionMessage()
                    {
                        Message = @"Grade passed in to check was a number, but the grade value for the assignment is not numeric."
                    };
                }
            }
            else if (minimumGrade.IsAlphaGrade())
            {
                if (minimumGrade.CompareAlphaGrades(assignmentSubmission.Grade) >= 0)
                {
                    result.IsComplete      = true;
                    result.PercentComplete = 1.0;
                }
                else
                {
                    result.IsComplete = false;
                }
            }
            else if (assignmentSubmission.Grade.IsPassed())
            {
                result.IsComplete      = true;
                result.PercentComplete = 1.0;
            }

            return(result);
        }
Пример #18
0
        private static bool Prefix
        (
            // ReSharper disable InconsistentNaming
            ItemNet __instance,
            CanvasHelper ___canvas,
            ref bool ___displayText)
        // ReSharper restore InconsistentNaming
        {
            // This overrides the original logic.
            // If the internal logic is changed in the future, this has to change aswell.
            if (!Helper.LocalPlayerIsWithinDistance(
                    __instance.transform.position, Player.UseDistance))
            {
                // Not within use distance, run old logic
                return(true);
            }

            if (MyInput.GetButtonDown("Rotate"))
            {
                ToggleFilterModeForNet(__instance);
            }

            ___displayText = true;
            var toggleFilterText = string.Format("Toggle net filter ({0})", GetCurrentFilter(__instance));

            if (__instance.itemCollector.collectedItems.Count > 0)
            {
                ___canvas.displayTextManager.HideDisplayTexts();

                LocalizationParameters.itemCount = __instance.itemCollector.collectedItems.Count;

                ___canvas.displayTextManager.ShowText(
                    toggleFilterText, MyInput.Keybinds["Rotate"].MainKey, 1,
                    Helper.GetTerm("Game/CollectItemCount", true), MyInput.Keybinds["Interact"].MainKey, 2);
            }
            else
            {
                ___canvas.displayTextManager.ShowText(
                    toggleFilterText, MyInput.Keybinds["Rotate"].MainKey, 1);
            }

            // skip original logic
            return(false);
        }
Пример #19
0
    static bool Prefix(Sail __instance, ref CanvasHelper ___canvas, ref Network_Player ___localPlayer)
    {
        if (!MyInput.GetButton("Sprint"))
        {
            return(true);
        }
        if (Helper.LocalPlayerIsWithinDistance(__instance.transform.position, Player.UseDistance) && CanvasHelper.ActiveMenu == MenuType.None)
        {
            if (MyInput.GetButtonDown("Interact"))
            {
                if (Semih_Network.IsHost)
                {
                    if (__instance.open)
                    {
                        MoreSailsMoreSpeedMod.SailsClose();
                    }
                    else
                    {
                        MoreSailsMoreSpeedMod.SailsOpen();
                    }
                }
            }

            if (MyInput.GetButton("Rotate"))
            {
                if (___localPlayer.PlayerScript.MouseLookIsActive())
                {
                    ___localPlayer.PlayerScript.SetMouseLookScripts(false);
                }
                MoreSailsMoreSpeedMod.SailsRotate(Input.GetAxis("Mouse X"), __instance);
            }
            else if (MyInput.GetButtonUp("Rotate"))
            {
                ___localPlayer.PlayerScript.SetMouseLookScripts(true);
            }
            return(false);
        }
        else
        {
            ___canvas.displayTextManager.HideDisplayTexts();
        }
        return(false);
    }
Пример #20
0
 private void UpdateSnake(SnakeChangedEventArgs e)
 {
     if (!e.Killed)
     {
         var snakePart = e.SnakeUpdated;
         if (!_snakeBodies.ContainsKey(snakePart))
         {
             FrameworkElement snakeControl = CanvasHelper.SnakeControlFactory(snakePart,
                                                                              _scale);
             _snakeBodies[snakePart] = snakeControl;
             _sprites.Add(snakeControl);
         }
         else
         {
             FrameworkElement snakeControl = _snakeBodies[snakePart];
             CanvasHelper.ResizeElement(snakeControl, snakePart.Size.Width * _scale, snakePart.Size.Height * _scale);
             CanvasHelper.MoveElementOnCanvas(snakeControl, snakePart.Location.X * _scale, snakePart.Location.Y * _scale);
         }
     }
 }
Пример #21
0
        public void Start()
        {
            if (ContainerPrefab == null)
            {
                throw new MissingReferenceException("Container Parent must have a Container Prefab set.");
            }

            GameObject containerObject = GameObject.Instantiate(ContainerPrefab);

            containerObject.transform.SetParent(CanvasHelper.GetCanvas().transform);
            container = containerObject.GetComponent <Container>();

            if (container == null)
            {
                throw new MissingComponentException("Container Prefab must have `Container` component attached.");
            }

            //  don't show by default
            container.Close();
        }
Пример #22
0
        private void pageRoot_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            var gameViewModel = DataContext as GameViewModel;

            newPlayAreaSize         = e.NewSize;
            newPlayAreaSize.Width  -= 208;     // odejmuje wielkosci kolumn + grubosc ramki
            newPlayAreaSize.Height -= 152 + 8; // odjemuje wielkosci wierszy + grubosc ramki

            if (gameViewModel != null)
            {
                _scale = (newPlayAreaSize.Height / 300 + newPlayAreaSize.Width / 300) / 2;
                SnakeBody.PlayAreaSize = newPlayAreaSize;
                SnakeBody.Scale        = _scale;
                GameViewModel.Scale    = _scale;
                if (this._fruit != null && this._fruitFrameworkElement != null)
                {
                    CanvasHelper.MoveElementOnCanvas(_fruitFrameworkElement, _fruit.Location.X * _scale, _fruit.Location.Y * _scale);
                    CanvasHelper.ResizeElement(_fruitFrameworkElement, _fruit.Size.Width * _scale, _fruit.Size.Height * _scale);
                }
            }
        }
Пример #23
0
        /// <summary>
        /// Create a new tooltip from passed prefab, with text as
        /// content, and the trigger as the bounds to appear near.
        /// </summary>
        /// <param name="prefab">The `Tooltip` prefab</param>
        /// <param name="text">The text to display in the tooltip</param>
        /// <param name="trigger">The RectTransform that triggered
        /// this tooltip. Will dictate where the tooltip will display
        /// on the canvas</param>
        /// <returns>The `Tooltip` that is created</returns>
        public static Tooltip Create(GameObject prefab, string text, RectTransform trigger)
        {
            Canvas     canvas        = CanvasHelper.GetCanvas();
            GameObject tooltipObject = GameObject.Instantiate(prefab, Vector3.zero, Quaternion.identity) as GameObject;

            tooltipObject.transform.SetParent(canvas.transform);

            //  TODO: if the tooltip is off the screen, reposition
            //  should this be moved elsewhere? In the tooltip itself?
            Vector3 newPosition = trigger.position;

            newPosition.x += (trigger.rect.width * canvas.scaleFactor) / 2;
            newPosition.y += (trigger.rect.height * canvas.scaleFactor) / 2;
            tooltipObject.transform.position = newPosition;

            Tooltip t = tooltipObject.GetComponent <Tooltip>();

            t.Display(text);

            return(t);
        }
Пример #24
0
        public JsonResult GetEditControl(Guid controlId, int pageId)
        {
            var model = Repository.GetObjectById(pageId);

            if (model != null)
            {
                // Finna Area hvort sem það sé inn í Grid/section eða rótar svæði sem á undir sér Control

                foreach (var area in model.Areas)
                {
                    FindAreaWithControl(area, controlId);
                }

                if (AreaControlResult != null)
                {
                    var control = AreaControlResult.Controls.Where(x => x.ControlID == controlId).FirstOrDefault();

                    if (control != null)
                    {
                        var templates = CanvasHelper.GetTemplates(control.Type);

                        var macros = new List <CanvasMacro>();

                        if (control.Type == "Macro")
                        {
                            using (var db = DatabaseContext.Database)
                            {
                                macros = db.Fetch <CanvasMacro>("SELECT * FROM cmsMacro where macroUseInEditor = @0 ORDER BY macroName", true);
                            }
                        }

                        var controlProperties = control.GetType().GetProperties().ToDictionary(x => x.Name, x => x.GetValue(control, null) == null ? "" : HttpUtility.HtmlDecode(x.GetValue(control, null).ToString())).ToList();

                        return(Json(new { success = true, controlId = controlId, properties = controlProperties, templates = templates, type = control.Type, macros = macros }, JsonRequestBehavior.AllowGet));
                    }
                }
            }

            return(Json(new { success = false }, JsonRequestBehavior.AllowGet));
        }
Пример #25
0
        private void UpdatePathGeometry()
        {
            // Currently we connect two connectors with a straight line.
            var geometry = PathGeometry;

            //var clipGeomotry = GetValue(DesignerCanvasItemContainer.ContainerClipProperty) as PathGeometry;
            //if (clipGeomotry == null)
            //{
            //    clipGeomotry = new PathGeometry();
            //    SetValue(DesignerCanvasItemContainer.ContainerClipProperty, clipGeomotry);
            //}
            if (geometry == null)
            {
                PathGeometry = geometry = new PathGeometry();
            }
            PathGeometry.Figures.Clear();
            //clipGeomotry.Figures.Clear();
            var item = DataContext as IPolyLineCanvasItem;

            if (item?.Points.Count > 0)
            {
                geometry.Figures.Add(CanvasHelper.GenerstePathFigure(item.Points));
            }
        }
Пример #26
0
        public JsonResult GetMacroProperty(int id)
        {
            using (var db = DatabaseContext.Database)
            {
                var properties = db.Fetch <CanvasMacroProperty>("SELECT * FROM cmsMacroProperty where macro = @0 ORDER BY macroPropertySortOrder", id);

                if (CanvasHelper.GetUmbracoVersion() == 6)
                {
                    var macroPropertyTypes = db.Fetch <dynamic>("SELECT * FROM cmsMacroPropertyType");

                    foreach (var p in properties)
                    {
                        var type = macroPropertyTypes.FirstOrDefault(x => x.id == p.macroPropertyType);

                        if (type != null)
                        {
                            p.editorAlias = type.macroPropertyTypeRenderType;
                        }
                    }
                }

                return(Json(new { success = true, properties = properties }));
            }
        }
Пример #27
0
 public Vector2 GetScreenPosition()
 {
     return(CanvasHelper.InverseTransformPoint(rectTransform.position));
 }
Пример #28
0
        public void OnIsRayed()
        {
            if (!mi_loaded)
            {
                return;
            }

            if (!mi_canvas)
            {
                mi_canvas = ComponentManager <CanvasHelper> .Value;
                return;
            }

            if (CanvasHelper.ActiveMenu == MenuType.None &&
                !PlayerItemManager.IsBusy &&
                mi_canvas.CanOpenMenu &&
                Helper.LocalPlayerIsWithinDistance(transform.position, Player.UseDistance + 0.5f))
            {
                mi_canvas.displayTextManager.ShowText(IsOn ? "Extinguish" : "Light", MyInput.Keybinds["Interact"].MainKey, 0, 0, true);
                if (MyInput.GetButtonDown("Interact"))
                {
                    UserControlsState = true;
                    SetLightOn(!IsOn);

                    var netMsg = new Message_Battery_OnOff(
                        Messages.Battery_OnOff,
                        RAPI.GetLocalPlayer().Network.NetworkIDManager,
                        RAPI.GetLocalPlayer().steamID,
                        ObjectIndex,
                        (int)ELanternRequestType.TOGGLE,
                        IsOn);

                    if (Semih_Network.IsHost)
                    {
                        mi_network.RPC(netMsg, Target.Other, EP2PSend.k_EP2PSendReliable, NetworkChannel.Channel_Game);
                        return;
                    }
                    mi_network.SendP2P(mi_network.HostID, netMsg, EP2PSend.k_EP2PSendReliable, NetworkChannel.Channel_Game);
                    return;
                }
                if (UserControlsState && Input.GetKeyDown(KeyCode.F))
                {
                    var notifier     = ComponentManager <HNotify> .Value;
                    var notification = notifier.AddNotification(HNotify.NotificationType.normal, "Automatic light behaviour restored.", 5);
                    notification.Show();
                    UserControlsState = false;
                    CheckLightState(true);

                    var netMsg = new Message_Battery_OnOff(
                        Messages.Battery_OnOff,
                        RAPI.GetLocalPlayer().Network.NetworkIDManager,
                        RAPI.GetLocalPlayer().steamID,
                        ObjectIndex,
                        (int)ELanternRequestType.RELEASE_AUTO, //indicate to receiving side that we want to switch back to auto control
                        IsOn);

                    if (Semih_Network.IsHost)
                    {
                        mi_network.RPC(netMsg, Target.Other, EP2PSend.k_EP2PSendReliable, NetworkChannel.Channel_Game);
                        return;
                    }
                    mi_network.SendP2P(mi_network.HostID, netMsg, EP2PSend.k_EP2PSendReliable, NetworkChannel.Channel_Game);
                }
            }
            else
            {
                mi_canvas.displayTextManager.HideDisplayTexts();
            }
        }
Пример #29
0
        // Generating the hollow text effect where the text looks like cut out of canvas
        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.SmoothingMode     = SmoothingMode.AntiAlias;
            e.Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;

            // Generating the outline strategy for displaying inside the hollow
            var strategyOutline = CanvasHelper.TextGradOutline(Color.FromArgb(255, 255, 255), Color.FromArgb(230, 230, 230), Color.FromArgb(100, 100, 100), 9, GradientType.Linear);

            Bitmap canvas = CanvasHelper.GenImage(ClientSize.Width, ClientSize.Height);
            // Text context to store string and font info to be sent as parameter to Canvas methods
            TextContext context = new TextContext();

            FontFamily fontFamily = new FontFamily("Arial Black");

            context.fontFamily = fontFamily;
            context.fontStyle  = FontStyle.Bold;
            context.nfontSize  = 56;

            context.pszText = "CUTOUT";
            context.ptDraw  = new Point(0, 0);

            Bitmap hollowImage = CanvasHelper.GenImage(ClientSize.Width, ClientSize.Height);

            // Algorithm to shift the shadow outline in and then out continuous
            int shift = 0;

            if (_TimerLoop >= 0 && _TimerLoop <= 2)
            {
                shift = _TimerLoop;
            }
            else
            {
                shift = 2 - (_TimerLoop - 2);
            }

            // Draw the hollow (shadow) outline by shifting accordingly
            CanvasHelper.DrawTextImage(strategyOutline, hollowImage, new Point(2 + shift, 2 + shift), context);

            // Generate the green mask for the cutout holes in the text
            Bitmap maskImage    = CanvasHelper.GenImage(ClientSize.Width, ClientSize.Height);
            var    strategyMask = CanvasHelper.TextOutline(MaskColor.Green, MaskColor.Green, 0);

            CanvasHelper.DrawTextImage(strategyMask, maskImage, new Point(0, 0), context);

            // Apply the hollowed image against the green mask on the canvas
            CanvasHelper.ApplyImageToMask(hollowImage, maskImage, canvas, MaskColor.Green, false);

            Bitmap backBuffer = CanvasHelper.GenImage(ClientSize.Width, ClientSize.Height, Color.FromArgb(0, 0, 0), 255);

            // Create a black outline only strategy and blit it onto the canvas to cover
            // the unnatural outline from the gradient shadow
            //=============================================================================
            var strategyOutlineOnly = CanvasHelper.TextOnlyOutline(Color.FromArgb(0, 0, 0), 2, false);

            CanvasHelper.DrawTextImage(strategyOutlineOnly, canvas, new Point(0, 0), context);

            // Draw the transparent canvas onto the back buffer
            //===================================================
            Graphics graphics2 = Graphics.FromImage(backBuffer);

            graphics2.SmoothingMode     = SmoothingMode.AntiAlias;
            graphics2.InterpolationMode = InterpolationMode.HighQualityBicubic;
            graphics2.DrawImage(canvas, 0, 0, ClientSize.Width, ClientSize.Height);

            // Finally blit the rendered image onto the window
            e.Graphics.DrawImage(backBuffer, 0, 0, ClientSize.Width, ClientSize.Height);

            // Release all the resources
            //============================
            hollowImage.Dispose();
            maskImage.Dispose();
            canvas.Dispose();
            backBuffer.Dispose();

            strategyOutline.Dispose();
            strategyMask.Dispose();
            strategyOutlineOnly.Dispose();
        }
Пример #30
0
 public override void WorldEvent_WorldLoaded()
 {
     loaded = true;
     player = RAPI.GetLocalPlayer();
     canvas = ComponentManager <CanvasHelper> .Value;
 }