/// <summary>Produces list of speed limits to offer user in the palette.</summary>
        /// <param name="unit">What kind of speed limit list is required.</param>
        /// <returns>
        ///     List from smallest to largest speed with the given unit. Zero (no limit) is
        ///     not added to the list. The values are in-game speeds as float.
        /// </returns>
        public static List <SetSpeedLimitAction> AllSpeedLimits(SpeedUnit unit)
        {
            var result = new List <SetSpeedLimitAction>();

            // SpeedLimitTextures textures = TMPELifecycle.Instance.Textures.SpeedLimits;

            switch (unit)
            {
            case SpeedUnit.Kmph:
                for (var km = RoadSignThemes.KMPH_STEP;
                     km <= RoadSignThemes.UPPER_KMPH;
                     km += RoadSignThemes.KMPH_STEP)
                {
                    result.Add(SetSpeedLimitAction.SetOverride(SpeedValue.FromKmph(km)));
                }

                break;

            case SpeedUnit.Mph:
                for (var mi = RoadSignThemes.MPH_STEP;
                     mi <= RoadSignThemes.UPPER_MPH;
                     mi += RoadSignThemes.MPH_STEP)
                {
                    result.Add(SetSpeedLimitAction.SetOverride(SpeedValue.FromMph(mi)));
                }

                break;

            case SpeedUnit.CurrentlyConfigured:
                // Automatically choose from the config
                return(AllSpeedLimits(GlobalConfig.Instance.Main.GetDisplaySpeedUnit()));
            }

            return(result);
        }
Exemple #2
0
    bool inMaxIncreaser  = false;                                       // Wheter a max increased coroutine is in place.

    /// <summary>
    /// Awake is called when the script instance is being loaded.
    /// </summary>
    void Awake()
    {
        if (instance == null)
        {
            instance = this;
        }
    }
        /// <summary>
        /// Based on the MPH/KMPH settings round the current speed to the nearest STEP and
        /// then increase by STEP.
        /// </summary>
        /// <param name="speed">Ingame speed</param>
        /// <returns>Ingame speed increased by the increment for MPH or KMPH</returns>
        public static SpeedValue GetNext(SpeedValue speed)
        {
            if (speed.GameUnits < 0f)
            {
                return(new SpeedValue(-1f));
            }

            if (GlobalConfig.Instance.Main.DisplaySpeedLimitsMph)
            {
                MphValue rounded = speed.ToMphRounded(MPH_STEP);
                rounded += MPH_STEP;

                if (rounded.Mph > UPPER_MPH)
                {
                    rounded = new MphValue(0);
                }

                return(SpeedValue.FromMph(rounded));
            }
            else
            {
                KmphValue rounded = speed.ToKmphRounded(KMPH_STEP);
                rounded += KMPH_STEP;

                if (rounded.Kmph > UPPER_KMPH)
                {
                    rounded = new KmphValue(0);
                }

                return(SpeedValue.FromKmph(rounded));
            }
        }
Exemple #4
0
        /// <summary>
        /// Given speed limit, round it up to nearest Kmph or Mph and produce a texture
        /// </summary>
        /// <param name="spd">Ingame speed</param>
        /// <returns>The texture, hopefully it existed</returns>
        public static Texture2D GetSpeedLimitTexture(SpeedValue spd)
        {
            var m    = GlobalConfig.Instance.Main;
            var unit = m.DisplaySpeedLimitsMph ? SpeedUnit.Mph : SpeedUnit.Kmph;

            return(GetSpeedLimitTexture(spd, m.MphRoadSignStyle, unit));
        }
        /// <summary>Helper to create speed limit sign + label below converted to the opposite unit</summary>
        /// <param name="showMph">Config value from GlobalConfig.I.M.ShowMPH</param>
        /// <param name="speedLimit">The float speed to show</param>
        private void GuiSpeedLimitsWindow_AddButton(bool showMph, SpeedValue speedLimit)
        {
            // The button is wrapped in vertical sub-layout and a label for MPH/KMPH is added
            GUILayout.BeginVertical();

            GUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();
            float signSize = TrafficManagerTool.AdaptWidth(GUI_SPEED_SIGN_SIZE);

            if (GUILayout.Button(
                    SpeedLimitTextures.GetSpeedLimitTexture(speedLimit),
                    GUILayout.Width(signSize),
                    GUILayout.Height(signSize * GetVerticalTextureScale())))
            {
                currentPaletteSpeedLimit = speedLimit;
            }

            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();

            // For MPH setting display KM/H below, for KM/H setting display MPH
            GUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();
            GUILayout.Label(
                showMph
                    ? ToKmphPreciseString(speedLimit)
                    : ToMphPreciseString(speedLimit));
            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();

            GUILayout.EndVertical();
        }
 public override void Cleanup()
 {
     segmentCenterByDir.Clear();
     CachedVisibleSegmentIds.Clear();
     currentInfoIndex  = -1;
     currentSpeedLimit = new SpeedValue(-1f);
 }
        /// <summary>
        /// Produces list of speed limits to offer user in the palette
        /// </summary>
        /// <param name="unit">What kind of speed limit list is required</param>
        /// <returns>List from smallest to largest speed with the given unit. Zero (no limit) is not added to the list.
        /// The values are in-game speeds as float.</returns>
        public static List <SpeedValue> EnumerateSpeedLimits(SpeedUnit unit)
        {
            var result = new List <SpeedValue>();

            switch (unit)
            {
            case SpeedUnit.Kmph:
                for (var km = LOWER_KMPH; km <= UPPER_KMPH; km += KMPH_STEP)
                {
                    result.Add(SpeedValue.FromKmph(km));
                }

                break;

            case SpeedUnit.Mph:
                for (var mi = LOWER_MPH; mi <= UPPER_MPH; mi += MPH_STEP)
                {
                    result.Add(SpeedValue.FromMph(mi));
                }

                break;

            case SpeedUnit.CurrentlyConfigured:
                // Automatically choose from the config
                return(GlobalConfig.Instance.Main.DisplaySpeedLimitsMph
                               ? EnumerateSpeedLimits(SpeedUnit.Mph)
                               : EnumerateSpeedLimits(SpeedUnit.Kmph));
            }

            return(result);
        }
 public override void Cleanup()
 {
     segmentCenterByDir.Clear();
     currentlyVisibleSegmentIds.Clear();
     lastCamPos        = null;
     lastCamRot        = null;
     currentInfoIndex  = -1;
     currentSpeedLimit = new SpeedValue(-1f);
 }
Exemple #9
0
 /// <summary>
 /// Returns a hash code for this instance.
 /// </summary>
 /// <returns>
 /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
 /// </returns>
 public override int GetHashCode()
 {
     return(Timestamp.GetHashCode()
            ^ Second.GetHashCode()
            ^ DistanceMiles.GetHashCode()
            ^ WorkoutTime.GetHashCode()
            ^ SpeedMph.GetHashCode()
            ^ RotationsPerMinute.GetHashCode()
            ^ Unknown1.GetHashCode()
            ^ SpeedValue.GetHashCode()
            ^ Unknown2.GetHashCode()
            ^ Unknown3.GetHashCode());
 }
    public void SetSpeedValues(int damage)
    {
        if (SpeedValueManager.GetSpeedValues().Count > damage)
        {
            SpeedValue newValue = SpeedValueManager.GetSpeedValues()[damage];

            turnForwardForce  = newValue.turnForwardForce;
            turnBackwardForce = newValue.turnBackwardForce;
            forwardForce      = newValue.forwardForce;
            backwardForce     = newValue.backwardForce;
            //maximumSpeed = newValue.maximumSpeed;
            sidePushForce = newValue.sidePushForce;
            paddleTime    = newValue.paddleTime;
        }
    }
Exemple #11
0
            /// <summary>
            /// Creates a button with speed value on it, and label under it, showing opposite units.
            /// Also can be zero (reset to default) and 1000 km/h (unlimited speed button).
            /// </summary>
            /// <param name="builder">UI builder.</param>
            /// <param name="actionOnClick">What happens if clicked.</param>
            /// <param name="parentTool">Parent speedlimits tool.</param>
            /// <param name="buttonPanel">Panel where buttons are added to.</param>
            /// <param name="speedInteger">Integer value of the speed in the selected units.</param>
            /// <param name="speedValue">Speed value of the button we're creating.</param>
            /// <returns>The new button.</returns>
            private SpeedLimitPaletteButton CreatePaletteButton(UBuilder builder,
                                                                SetSpeedLimitAction actionOnClick,
                                                                SpeedLimitsTool parentTool,
                                                                UPanel buttonPanel,
                                                                int speedInteger,
                                                                SpeedValue speedValue)
            {
                // Helper function to choose text for the button
                string GetSpeedButtonText()
                {
                    if (speedInteger == 0)
                    {
                        return("✖"); // Unicode symbol U+2716 Heavy Multiplication X
                    }

                    if (speedValue.GameUnits >= SpeedValue.UNLIMITED)
                    {
                        return("⊘"); // Unicode symbol U+2298 Circled Division Slash
                    }

                    return(speedInteger.ToString());
                }

                var button = builder.Button <SpeedLimitPaletteButton>(parent: buttonPanel);

                button.text      = GetSpeedButtonText();
                button.textScale = UIScaler.UIScale;
                button.textHorizontalAlignment = UIHorizontalAlignment.Center;

                button.normalBgSprite = button.hoveredBgSprite = "GenericPanel";
                button.color          = new Color32(128, 128, 128, 240);

                // button must know what to do with its speed value
                button.AssignedAction = actionOnClick;

                // The click events will be routed via the parent tool OnPaletteButtonClicked
                button.ParentTool = parentTool;

                button.SetStacking(UStackMode.NewRowBelow);

                // Width will be overwritten in SpeedLimitPaletteButton.UpdateSpeedLimitButton
                button.SetFixedSize(
                    new Vector2(
                        SpeedLimitPaletteButton.DEFAULT_WIDTH,
                        SpeedLimitPaletteButton.DEFAULT_HEIGHT));
                return(button);
            }
Exemple #12
0
        /// <summary>
        /// Given the float speed, style and MPH option return a texture to render.
        /// </summary>
        /// <param name="spd">float speed</param>
        /// <param name="mphStyle">Signs theme</param>
        /// <param name="unit">Mph or km/h</param>
        /// <returns></returns>
        public static Texture2D GetSpeedLimitTexture(SpeedValue spd, MphSignStyle mphStyle, SpeedUnit unit)
        {
            // Select the source for the textures based on unit and the theme
            bool mph = unit == SpeedUnit.Mph;
            IDictionary <int, Texture2D> textures = TexturesKmph;

            if (mph)
            {
                switch (mphStyle)
                {
                case MphSignStyle.SquareUS:
                    textures = TexturesMphUS;
                    break;

                case MphSignStyle.RoundUK:
                    textures = TexturesMphUK;
                    break;

                case MphSignStyle.RoundGerman:
                    // Do nothing, this is the default above
                    break;
                }
            }

            // Round to nearest 5 MPH or nearest 10 km/h
            ushort index = mph ? spd.ToMphRounded(SpeedLimitsTool.MPH_STEP).Mph
                               : spd.ToKmphRounded(SpeedLimitsTool.KMPH_STEP).Kmph;

            // Trim the index since 140 km/h / 90 MPH is the max sign we have
            ushort upper = mph ? SpeedLimitsTool.UPPER_MPH
                               : SpeedLimitsTool.UPPER_KMPH;

            // Show unlimited if the speed cannot be represented by the available sign textures
            if (index == 0 || index > upper)
            {
                // Log._Debug($"Trimming speed={speedLimit} index={index} to {upper}");
                return(textures[0]);
            }

            // Trim from below to not go below index 5 (5 kmph or 5 mph)
            ushort trimIndex = Math.Max((ushort)5, index);

            return(textures[trimIndex]);
        }
        /// <summary>
        /// Used to draw default speed sign subicon overlapping bottom right corner.
        /// </summary>
        /// <param name="speed">The default speed value.</param>
        public void DrawDefaultSpeedSubIcon(SpeedValue speed)
        {
            Texture2D tex = SignRenderer.ChooseTexture(
                speedlimit: speed,
                theme: RoadSignThemes.Instance.RoadDefaults);

            float size = this.screenRect_.height * 0.4f;
            float half = size / 2;

            Rect smallRect = new Rect(
                x: this.screenPos_.x + half,
                y: this.screenPos_.y + half,
                width: size,
                height: size);

            GUI.DrawTexture(
                position: smallRect,
                image: tex);
        }
        /// <summary>
        /// Based on the MPH/KMPH settings round the current speed to the nearest STEP and
        /// then decrease by STEP.
        /// </summary>
        /// <param name="speed">Ingame speed</param>
        /// <returns>Ingame speed decreased by the increment for MPH or KMPH</returns>
        public static SpeedValue GetPrevious(SpeedValue speed)
        {
            if (speed.GameUnits < 0f)
            {
                return(new SpeedValue(-1f));
            }

            if (GlobalConfig.Instance.Main.DisplaySpeedLimitsMph)
            {
                MphValue rounded = speed.ToMphRounded(MPH_STEP);
                if (rounded.Mph == LOWER_MPH)
                {
                    return(new SpeedValue(0));
                }

                if (rounded.Mph == 0)
                {
                    return(SpeedValue.FromMph(UPPER_MPH));
                }

                return(SpeedValue.FromMph(rounded.Mph > LOWER_MPH
                                              ? (ushort)(rounded.Mph - MPH_STEP)
                                              : LOWER_MPH));
            }
            else
            {
                KmphValue rounded = speed.ToKmphRounded(KMPH_STEP);
                if (rounded.Kmph == LOWER_KMPH)
                {
                    return(new SpeedValue(0));
                }

                if (rounded.Kmph == 0)
                {
                    return(SpeedValue.FromKmph(UPPER_KMPH));
                }

                return(SpeedValue.FromKmph(rounded.Kmph > LOWER_KMPH
                                               ? (ushort)(rounded.Kmph - KMPH_STEP)
                                               : LOWER_KMPH));
            }
        }
Exemple #15
0
            SetupControls_SpeedPalette_Button(UBuilder builder,
                                              UIComponent parent,
                                              bool showMph,
                                              SetSpeedLimitAction actionOnClick,
                                              SpeedLimitsTool parentTool)
            {
                SpeedValue speedValue =
                    actionOnClick.Type == SetSpeedLimitAction.ActionType.ResetToDefault
                        ? default
                        : actionOnClick.GuardedValue.Override;

                int speedInteger = showMph
                                       ? speedValue.ToMphRounded(RoadSignThemes.MPH_STEP).Mph
                                       : speedValue.ToKmphRounded(RoadSignThemes.KMPH_STEP).Kmph;

                //--------------------------------
                // Create vertical combo:
                // |[  100   ]|
                // | "65 mph" |
                //--------------------------------
                // Create a small panel which stacks together with other button panels horizontally
                var buttonPanel = builder.Panel_(parent: parent);

                buttonPanel.name = $"{GAMEOBJECT_NAME}_Button_{speedInteger}";
                buttonPanel.ResizeFunction(
                    resizeFn: (UResizer r) => {
                    r.Stack(UStackMode.ToTheRight, spacing: 2f);
                    r.FitToChildren();
                });

                SpeedLimitPaletteButton button = this.CreatePaletteButton(
                    builder,
                    actionOnClick,
                    parentTool,
                    buttonPanel,
                    speedInteger,
                    speedValue);

                this.CreatePaletteButtonHintLabel(builder, showMph, speedValue, button, buttonPanel);
                return(button);
            }
Exemple #16
0
            private void CreatePaletteButtonHintLabel(UBuilder builder,
                                                      bool showMph,
                                                      SpeedValue speedValue,
                                                      SpeedLimitPaletteButton button,
                                                      UPanel buttonPanel)
            {
                // Other speed unit info label
                string otherUnit = showMph
                                       ? ToKmphPreciseString(speedValue)
                                       : ToMphPreciseString(speedValue);

                // Choose label text under the button
                string GetSpeedButtonHintText()
                {
                    if (FloatUtil.NearlyEqual(speedValue.GameUnits, 0.0f))
                    {
                        return(Translation.SpeedLimits.Get("Palette.Text:Default"));
                    }

                    if (speedValue.GameUnits >= SpeedValue.UNLIMITED)
                    {
                        return(Translation.SpeedLimits.Get("Palette.Text:Unlimited"));
                    }

                    return(otherUnit);
                }

                ULabel label = button.AltUnitsLabel =
                    builder.Label_(
                        parent: buttonPanel,
                        t: GetSpeedButtonHintText(),
                        stack: UStackMode.Below);

                label.width         = SpeedLimitPaletteButton.SELECTED_WIDTH;
                label.textAlignment = UIHorizontalAlignment.Center;
                label.ContributeToBoundingBox(false); // parent ignore our width
            }
Exemple #17
0
 public Variant3(SpeedValue v, ActionType valueType)
 {
     this.overrideValue_ = v;
     this.Which          = valueType;
 }
Exemple #18
0
 // Start is called before the first frame update
 void Start()
 {
     _instance = this;
 }
 public static string ToKmphPreciseString(SpeedValue speed)
 {
     return(FloatUtil.IsZero(speed.GameUnits)
                ? Translation.GetString("Speed_limit_unlimited")
                : speed.ToKmphPrecise().ToString());
 }
        private void DrawSpeedLimitHandles(ushort segmentId,
                                           ref NetSegment segment,
                                           bool viewOnly,
                                           ref Vector3 camPos)
        {
            if (viewOnly && !Options.speedLimitsOverlay)
            {
                return;
            }

            Vector3    center          = segment.m_bounds.center;
            NetManager netManager      = Singleton <NetManager> .instance;
            SpeedValue speedLimitToSet = viewOnly
                                             ? new SpeedValue(-1f)
                                             : currentPaletteSpeedLimit;
            bool showPerLane = showLimitsPerLane;

            if (!viewOnly)
            {
                showPerLane = showLimitsPerLane ^
                              (Input.GetKey(KeyCode.LeftControl) ||
                               Input.GetKey(KeyCode.RightControl));
            }

            // US signs are rectangular, all other are round
            float speedLimitSignVerticalScale = GetVerticalTextureScale();

            if (showPerLane)
            {
                // show individual speed limit handle per lane
                int numLanes = TrafficManagerTool.GetSegmentNumVehicleLanes(
                    segmentId,
                    null,
                    out int numDirections,
                    SpeedLimitManager.VEHICLE_TYPES);

                NetInfo segmentInfo = segment.Info;
                Vector3 yu          = (segment.m_endDirection - segment.m_startDirection).normalized;
                Vector3 xu          = Vector3.Cross(yu, new Vector3(0, 1f, 0)).normalized;

                // if ((segment.m_flags & NetSegment.Flags.Invert) == NetSegment.Flags.None) {
                //        xu = -xu; }
                float   f    = viewOnly ? 4f : 7f; // reserved sign size in game coordinates
                Vector3 zero = center - (0.5f * (((numLanes - 1) + numDirections) - 1) * f * xu);

                uint            x           = 0;
                IList <LanePos> sortedLanes = Constants.ServiceFactory.NetService.GetSortedLanes(
                    segmentId,
                    ref segment,
                    null,
                    SpeedLimitManager.LANE_TYPES,
                    SpeedLimitManager.VEHICLE_TYPES);
                bool onlyMonorailLanes = sortedLanes.Count > 0;

                if (!viewOnly)
                {
                    foreach (LanePos laneData in sortedLanes)
                    {
                        byte         laneIndex = laneData.laneIndex;
                        NetInfo.Lane laneInfo  = segmentInfo.m_lanes[laneIndex];

                        if ((laneInfo.m_vehicleType & VehicleInfo.VehicleType.Monorail) ==
                            VehicleInfo.VehicleType.None)
                        {
                            onlyMonorailLanes = false;
                            break;
                        }
                    }
                }

                var directions      = new HashSet <NetInfo.Direction>();
                int sortedLaneIndex = -1;

                foreach (LanePos laneData in sortedLanes)
                {
                    ++sortedLaneIndex;
                    uint laneId    = laneData.laneId;
                    byte laneIndex = laneData.laneIndex;

                    NetInfo.Lane laneInfo = segmentInfo.m_lanes[laneIndex];
                    if (!directions.Contains(laneInfo.m_finalDirection))
                    {
                        if (directions.Count > 0)
                        {
                            ++x; // space between different directions
                        }

                        directions.Add(laneInfo.m_finalDirection);
                    }

                    SpeedValue laneSpeedLimit = new SpeedValue(
                        SpeedLimitManager.Instance.GetCustomSpeedLimit(laneId));

                    bool hoveredHandle = MainTool.DrawGenericOverlayGridTexture(
                        SpeedLimitTextures.GetSpeedLimitTexture(laneSpeedLimit),
                        camPos,
                        zero,
                        f,
                        f,
                        xu,
                        yu,
                        x,
                        0,
                        speedLimitSignSize,
                        speedLimitSignSize * speedLimitSignVerticalScale,
                        !viewOnly);

                    if (!viewOnly &&
                        !onlyMonorailLanes &&
                        ((laneInfo.m_vehicleType & VehicleInfo.VehicleType.Monorail) !=
                         VehicleInfo.VehicleType.None))
                    {
                        Texture2D tex1 = RoadUITextures.VehicleInfoSignTextures[
                            LegacyExtVehicleType.ToNew(ExtVehicleType.PassengerTrain)];
                        MainTool.DrawStaticSquareOverlayGridTexture(
                            tex1,
                            camPos,
                            zero,
                            f,
                            xu,
                            yu,
                            x,
                            1,
                            speedLimitSignSize);
                    }

                    if (hoveredHandle)
                    {
                    }

                    if (hoveredHandle && Input.GetMouseButton(0) && !IsCursorInPanel())
                    {
                        SpeedLimitManager.Instance.SetSpeedLimit(
                            segmentId,
                            laneIndex,
                            laneInfo,
                            laneId,
                            speedLimitToSet.GameUnits);

                        if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
                        {
                            int slIndexCopy = sortedLaneIndex;

                            SegmentLaneTraverser.Traverse(
                                segmentId,
                                SegmentTraverser.TraverseDirection.AnyDirection,
                                SegmentTraverser.TraverseSide.AnySide,
                                SegmentLaneTraverser.LaneStopCriterion.LaneCount,
                                SegmentTraverser.SegmentStopCriterion.Junction,
                                SpeedLimitManager.LANE_TYPES,
                                SpeedLimitManager.VEHICLE_TYPES,
                                data => {
                                if (data.SegVisitData.Initial)
                                {
                                    return(true);
                                }

                                if (slIndexCopy != data.SortedLaneIndex)
                                {
                                    return(true);
                                }

                                Constants.ServiceFactory.NetService.ProcessSegment(
                                    data.SegVisitData.CurSeg.segmentId,
                                    (ushort curSegmentId, ref NetSegment curSegment) =>
                                {
                                    NetInfo.Lane curLaneInfo = curSegment.Info.m_lanes[
                                        data.CurLanePos.laneIndex];

                                    SpeedLimitManager.Instance.SetSpeedLimit(
                                        curSegmentId,
                                        data.CurLanePos.laneIndex,
                                        curLaneInfo,
                                        data.CurLanePos.laneId,
                                        speedLimitToSet.GameUnits);
                                    return(true);
                                });

                                return(true);
                            });
                        }
                    }

                    ++x;
                }
            }
            else
            {
                // draw speedlimits over mean middle points of lane beziers

                if (!segmentCenterByDir.TryGetValue(
                        segmentId,
                        out Dictionary <NetInfo.Direction, Vector3> segCenter))
                {
                    segCenter = new Dictionary <NetInfo.Direction, Vector3>();
                    segmentCenterByDir.Add(segmentId, segCenter);
                    TrafficManagerTool.CalculateSegmentCenterByDir(segmentId, segCenter);
                }

                foreach (KeyValuePair <NetInfo.Direction, Vector3> e in segCenter)
                {
                    bool visible = MainTool.WorldToScreenPoint(e.Value, out Vector3 screenPos);

                    if (!visible)
                    {
                        continue;
                    }

                    float zoom        = (1.0f / (e.Value - camPos).magnitude) * 100f * MainTool.GetBaseZoom();
                    float size        = (viewOnly ? 0.8f : 1f) * speedLimitSignSize * zoom;
                    Color guiColor    = GUI.color;
                    var   boundingBox = new Rect(screenPos.x - (size / 2),
                                                 screenPos.y - (size / 2),
                                                 size,
                                                 size * speedLimitSignVerticalScale);
                    bool hoveredHandle = !viewOnly && TrafficManagerTool.IsMouseOver(boundingBox);

                    guiColor.a = TrafficManagerTool.GetHandleAlpha(hoveredHandle);

                    if (hoveredHandle)
                    {
                        // mouse hovering over sign
                    }

                    // Draw something right here, the road sign texture
                    GUI.color = guiColor;
                    SpeedValue displayLimit = new SpeedValue(
                        SpeedLimitManager.Instance.GetCustomSpeedLimit(segmentId, e.Key));
                    Texture2D tex = SpeedLimitTextures.GetSpeedLimitTexture(displayLimit);

                    GUI.DrawTexture(boundingBox, tex);

                    if (hoveredHandle && Input.GetMouseButton(0) && !IsCursorInPanel())
                    {
                        // change the speed limit to the selected one
                        // Log._Debug($"Setting speed limit of segment {segmentId}, dir {e.Key.ToString()}
                        //     to {speedLimitToSet}");
                        SpeedLimitManager.Instance.SetSpeedLimit(segmentId,
                                                                 e.Key,
                                                                 currentPaletteSpeedLimit.GameUnits);

                        if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
                        {
                            NetInfo.Direction normDir = e.Key;
                            if ((netManager.m_segments.m_buffer[segmentId].m_flags & NetSegment.Flags.Invert) != NetSegment.Flags.None)
                            {
                                normDir = NetInfo.InvertDirection(normDir);
                            }

                            SegmentLaneTraverser.Traverse(
                                segmentId,
                                SegmentTraverser.TraverseDirection.AnyDirection,
                                SegmentTraverser.TraverseSide.AnySide,
                                SegmentLaneTraverser.LaneStopCriterion.LaneCount,
                                SegmentTraverser.SegmentStopCriterion.Junction,
                                SpeedLimitManager.LANE_TYPES,
                                SpeedLimitManager.VEHICLE_TYPES,
                                data =>
                            {
                                if (data.SegVisitData.Initial)
                                {
                                    return(true);
                                }

                                bool reverse =
                                    data.SegVisitData.ViaStartNode
                                    == data.SegVisitData.ViaInitialStartNode;

                                ushort otherSegmentId    = data.SegVisitData.CurSeg.segmentId;
                                NetInfo otherSegmentInfo =
                                    netManager.m_segments.m_buffer[otherSegmentId].Info;
                                byte laneIndex        = data.CurLanePos.laneIndex;
                                NetInfo.Lane laneInfo = otherSegmentInfo.m_lanes[laneIndex];

                                NetInfo.Direction otherNormDir = laneInfo.m_finalDirection;

                                if (((netManager.m_segments.m_buffer[otherSegmentId].m_flags
                                      & NetSegment.Flags.Invert)
                                     != NetSegment.Flags.None) ^ reverse)
                                {
                                    otherNormDir = NetInfo.InvertDirection(otherNormDir);
                                }

                                if (otherNormDir == normDir)
                                {
                                    SpeedLimitManager.Instance.SetSpeedLimit(
                                        otherSegmentId,
                                        laneInfo.m_finalDirection,
                                        speedLimitToSet.GameUnits);
                                }

                                return(true);
                            });
                        }
                    }

                    guiColor.a = 1f;
                    GUI.color  = guiColor;
                }
            }
        }
        /// <summary>
        /// The window for setting the defaullt speeds per road type
        /// </summary>
        /// <param name="num"></param>
        private void GuiDefaultsWindow(int num)
        {
            List <NetInfo> mainNetInfos = SpeedLimitManager.Instance.GetCustomizableNetInfos();

            if ((mainNetInfos == null) || (mainNetInfos.Count <= 0))
            {
                Log._Debug($"mainNetInfos={mainNetInfos?.Count}");
                DragWindow(ref defaultsWindowRect);
                return;
            }

            bool updateRoadTex = false;

            if ((currentInfoIndex < 0) || (currentInfoIndex >= mainNetInfos.Count))
            {
                currentInfoIndex = 0;
                updateRoadTex    = true;
                Log._Debug($"set currentInfoIndex to 0");
            }

            NetInfo info = mainNetInfos[currentInfoIndex];

            if (updateRoadTex)
            {
                UpdateRoadTex(info);
            }

            if (currentSpeedLimit.GameUnits < 0f)
            {
                currentSpeedLimit = new SpeedValue(
                    SpeedLimitManager.Instance.GetCustomNetInfoSpeedLimit(info));
                Log._Debug($"set currentSpeedLimit to {currentSpeedLimit}");
            }

            // Log._Debug($"currentInfoIndex={currentInfoIndex} currentSpeedLimitIndex={currentSpeedLimitIndex}");
            // Road type label
            GUILayout.BeginVertical();
            GUILayout.Space(10);
            GUILayout.Label(Translation.GetString("Road_type") + ":");
            GUILayout.EndVertical();

            // switch between NetInfos
            GUILayout.BeginHorizontal();

            GUILayout.BeginVertical();
            GUILayout.FlexibleSpace();

            if (GUILayout.Button("←", GUILayout.Width(50)))
            {
                currentInfoIndex =
                    ((currentInfoIndex + mainNetInfos.Count) - 1) % mainNetInfos.Count;
                info = mainNetInfos[currentInfoIndex];
                currentSpeedLimit = new SpeedValue(
                    SpeedLimitManager.Instance.GetCustomNetInfoSpeedLimit(info));
                UpdateRoadTex(info);
            }

            GUILayout.FlexibleSpace();
            GUILayout.EndVertical();

            GUILayout.FlexibleSpace();
            GUILayout.BeginVertical();
            GUILayout.FlexibleSpace();

            // NetInfo thumbnail
            GUILayout.Box(RoadTexture, GUILayout.Height(GUI_SPEED_SIGN_SIZE));
            GUILayout.FlexibleSpace();

            GUILayout.EndVertical();
            GUILayout.FlexibleSpace();

            GUILayout.BeginVertical();
            GUILayout.FlexibleSpace();

            if (GUILayout.Button("→", GUILayout.Width(50)))
            {
                currentInfoIndex  = (currentInfoIndex + 1) % mainNetInfos.Count;
                info              = mainNetInfos[currentInfoIndex];
                currentSpeedLimit = new SpeedValue(
                    SpeedLimitManager.Instance.GetCustomNetInfoSpeedLimit(info));
                UpdateRoadTex(info);
            }

            GUILayout.FlexibleSpace();
            GUILayout.EndVertical();

            GUILayout.EndHorizontal();

            var centeredTextStyle = new GUIStyle("label")
            {
                alignment = TextAnchor.MiddleCenter
            };

            // NetInfo name
            GUILayout.Label(info.name, centeredTextStyle);

            // Default speed limit label
            GUILayout.BeginVertical();
            GUILayout.Space(10);
            GUILayout.Label(Translation.GetString("Default_speed_limit") + ":");
            GUILayout.EndVertical();

            // switch between speed limits
            GUILayout.BeginHorizontal();

            GUILayout.BeginVertical();
            GUILayout.FlexibleSpace();
            if (GUILayout.Button("←", GUILayout.Width(50)))
            {
                // currentSpeedLimit = (currentSpeedLimitIndex +
                //     SpeedLimitManager.Instance.AvailableSpeedLimits.Count - 1)
                //     % SpeedLimitManager.Instance.AvailableSpeedLimits.Count;
                currentSpeedLimit = GetPrevious(currentSpeedLimit);
            }

            GUILayout.FlexibleSpace();
            GUILayout.EndVertical();

            GUILayout.FlexibleSpace();

            GUILayout.BeginVertical();
            GUILayout.FlexibleSpace();

            // speed limit sign
            GUILayout.Box(SpeedLimitTextures.GetSpeedLimitTexture(currentSpeedLimit),
                          GUILayout.Width(GUI_SPEED_SIGN_SIZE),
                          GUILayout.Height(GUI_SPEED_SIGN_SIZE));
            GUILayout.Label(GlobalConfig.Instance.Main.DisplaySpeedLimitsMph
                                ? Translation.GetString("Miles_per_hour")
                                : Translation.GetString("Kilometers_per_hour"));

            GUILayout.FlexibleSpace();
            GUILayout.EndVertical();

            GUILayout.FlexibleSpace();

            GUILayout.BeginVertical();
            GUILayout.FlexibleSpace();

            if (GUILayout.Button("→", GUILayout.Width(50)))
            {
                // currentSpeedLimitIndex = (currentSpeedLimitIndex + 1) %
                //     SpeedLimitManager.Instance.AvailableSpeedLimits.Count;
                currentSpeedLimit = GetNext(currentSpeedLimit);
            }

            GUILayout.FlexibleSpace();
            GUILayout.EndVertical();

            GUILayout.EndHorizontal();

            // Save & Apply
            GUILayout.BeginVertical();
            GUILayout.Space(10);

            GUILayout.BeginHorizontal();

            // Close button. TODO: Make more visible or obey 'Esc' pressed or something
            GUILayout.FlexibleSpace();

            if (GUILayout.Button("X", GUILayout.Width(80)))
            {
                defaultsWindowVisible = false;
            }

            GUILayout.FlexibleSpace();

            if (GUILayout.Button(Translation.GetString("Save"), GUILayout.Width(70)))
            {
                SpeedLimitManager.Instance.FixCurrentSpeedLimits(info);
                SpeedLimitManager.Instance.SetCustomNetInfoSpeedLimit(info, currentSpeedLimit.GameUnits);
            }

            GUILayout.FlexibleSpace();

            if (GUILayout.Button(
                    Translation.GetString("Save") + " & " + Translation.GetString("Apply"),
                    GUILayout.Width(160)))
            {
                SpeedLimitManager.Instance.SetCustomNetInfoSpeedLimit(info, currentSpeedLimit.GameUnits);
                SpeedLimitManager.Instance.ClearCurrentSpeedLimits(info);
            }

            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();

            GUILayout.EndVertical();

            DragWindow(ref defaultsWindowRect);
        }
Exemple #22
0
 public static string ToMphPreciseString(SpeedValue speed)
 {
     return(FloatUtil.IsZero(speed.GameUnits)
                ? Translation.SpeedLimits.Get("Unlimited")
                : speed.ToMphPrecise().ToString());
 }
 public LaneSpeedLimit(uint laneId, SpeedValue speed)
 {
     this.laneId     = laneId;
     this.speedLimit = speed.ToKmphPrecise().Kmph;
 }