Skip to content

Commit

Permalink
Merge pull request #863 from CitiesSkylinesMods/roundabout+undo
Browse files Browse the repository at this point in the history
Added new features to roundabout quick setup (fixes #578). They can be setup in the settings.
- ban parking on roundabout/branches.
- lower speed limit on small roundabouts (fixes #793
- allow/ban entering blocked roundabout
- Undo feature (fixes #860)
- improved priority signs cycle : #860 (comment)
  • Loading branch information
kianzarrin authored May 19, 2020
2 parents e6f33a0 + 34022e4 commit 1a699f5
Show file tree
Hide file tree
Showing 31 changed files with 885 additions and 229 deletions.
17 changes: 13 additions & 4 deletions TLM/TLM/Manager/Impl/OptionsManager.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
namespace TrafficManager.Manager.Impl {
namespace TrafficManager.Manager.Impl {
using CSUtil.Commons;
using System;
using TrafficManager.API.Manager;
Expand All @@ -8,8 +8,7 @@

public class OptionsManager
: AbstractCustomManager,
IOptionsManager
{
IOptionsManager {
// TODO I contain ugly code
public static OptionsManager Instance = new OptionsManager();

Expand Down Expand Up @@ -216,7 +215,7 @@ public bool LoadData(byte[] data) {
OptionsVehicleRestrictionsTab.SetAddTrafficLightsIfApplicable(data[41] == 1);
}

int LoadBool (int idx, ILegacySerializableOption opt) {
int LoadBool(int idx, ILegacySerializableOption opt) {
if (data.Length > idx) {
opt.Load(data[idx]);
}
Expand All @@ -236,6 +235,11 @@ int LoadBool (int idx, ILegacySerializableOption opt) {
index = LoadBool(index, OptionsMassEditTab.PriorityRoad_EnterBlockedYeild);
index = LoadBool(index, OptionsMassEditTab.PriorityRoad_StopAtEntry);

index = LoadBool(index, OptionsMassEditTab.RoundAboutQuickFix_KeepClearYieldR);
index = LoadBool(index, OptionsMassEditTab.RoundAboutQuickFix_RealisticSpeedLimits);
index = LoadBool(index, OptionsMassEditTab.RoundAboutQuickFix_ParkingBanMainR);
index = LoadBool(index, OptionsMassEditTab.RoundAboutQuickFix_ParkingBanYieldR);

return true;
}

Expand Down Expand Up @@ -295,6 +299,11 @@ public byte[] SaveData(ref bool success) {
(byte)(OptionsMassEditTab.PriorityRoad_AllowLeftTurns.Save()),
(byte)(OptionsMassEditTab.PriorityRoad_EnterBlockedYeild.Save()),
(byte)(OptionsMassEditTab.PriorityRoad_StopAtEntry.Save()),

(byte)(OptionsMassEditTab.RoundAboutQuickFix_KeepClearYieldR.Save()),
(byte)(OptionsMassEditTab.RoundAboutQuickFix_RealisticSpeedLimits.Save()),
(byte)(OptionsMassEditTab.RoundAboutQuickFix_ParkingBanMainR.Save()),
(byte)(OptionsMassEditTab.RoundAboutQuickFix_ParkingBanYieldR.Save()),
};
}
}
Expand Down
11 changes: 11 additions & 0 deletions TLM/TLM/Manager/Impl/ParkingRestrictionsManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,17 @@ public bool ToggleParkingAllowed(ushort segmentId, NetInfo.Direction finalDir) {
return SetParkingAllowed(segmentId, finalDir, !IsParkingAllowed(segmentId, finalDir));
}

/// <summary>
/// Sets Parking allowed to <paramref name="flag"/> for all supported directions.
/// </summary>
/// <returns><c>false</c>if no there are no configurable lanes.
/// <c>true</c> if any parking rules were applied.</returns>
public bool SetParkingAllowed(ushort segmentId, bool flag) {
bool ret = SetParkingAllowed(segmentId, NetInfo.Direction.Forward, flag);
ret |= SetParkingAllowed(segmentId, NetInfo.Direction.Backward, flag);
return ret;
}

public bool SetParkingAllowed(ushort segmentId, NetInfo.Direction finalDir, bool flag) {
#if DEBUG
if (DebugSwitch.BasicParkingAILog.Get()) {
Expand Down
16 changes: 14 additions & 2 deletions TLM/TLM/Manager/Impl/SegmentEndManager.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
namespace TrafficManager.Manager.Impl {
namespace TrafficManager.Manager.Impl {
using CSUtil.Commons;
using System;
using TrafficManager.API.Manager;
using TrafficManager.API.Traffic;
using TrafficManager.State.ConfigData;
using TrafficManager.Traffic.Impl;
using TrafficManager.Traffic;
using CitiesGameBridge.Service;
using TrafficManager.Util;

[Obsolete("should be removed when implementing issue #240")]
public class SegmentEndManager
Expand Down Expand Up @@ -42,6 +44,10 @@ public ISegmentEnd GetSegmentEnd(ushort segmentId, bool startNode) {
return SegmentEnds[GetIndex(segmentId, startNode)];
}

internal ISegmentEnd GetSegmentEnd(int segmentEndIndex) {
return SegmentEnds[segmentEndIndex];
}

public ISegmentEnd GetOrAddSegmentEnd(ISegmentEndId endId) {
return GetOrAddSegmentEnd(endId.SegmentId, endId.StartNode);
}
Expand Down Expand Up @@ -155,10 +161,16 @@ public bool UpdateSegmentEnd(ushort segmentId, bool startNode) {
}
}

private int GetIndex(ushort segmentId, bool startNode) {
internal int GetIndex(ushort segmentId, bool startNode) {
return segmentId + (startNode ? 0 : NetManager.MAX_SEGMENT_COUNT);
}

internal void GetSegmentAndNodeFromIndex(int index, out ushort segmentId, out bool startNode) {
Shortcuts.Assert(index < 2 * NetManager.MAX_SEGMENT_COUNT && index > 0);
startNode = index < NetManager.MAX_SEGMENT_COUNT;
segmentId = (ushort)(index - (startNode ? 0 : NetManager.MAX_SEGMENT_COUNT));
}

// protected override void HandleInvalidSegment(SegmentGeometry geometry) {
// RemoveSegmentEnds(geometry.SegmentId);
// }
Expand Down
13 changes: 13 additions & 0 deletions TLM/TLM/Manager/Impl/SpeedLimitManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -575,6 +575,19 @@ public bool SetSpeedLimit(ushort segmentId,
return true;
}

/// <summary>
/// Sets speed limit for all configurable lanes.
/// </summary>
/// <param name="speedLimit">Speed limit in game units, or null to restore defaults</param>
/// <returns><c>false</c>if there are no configurable lanes. <c>true</c> if any speed limits were applied.</returns>
public bool SetSpeedLimit(ushort segmentId, float? speedLimit) {
bool ret = false;
foreach(NetInfo.Direction finaldir in Enum.GetValues(typeof(NetInfo.Direction))) {
ret |= SetSpeedLimit(segmentId, finaldir, speedLimit);
}
return ret;
}

/// <summary>
/// Sets the speed limit of a given segment and lane direction.
/// </summary>
Expand Down
33 changes: 33 additions & 0 deletions TLM/TLM/Manager/Impl/VehicleRestrictionsManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ namespace TrafficManager.Manager.Impl {
using TrafficManager.State;
using TrafficManager.Traffic;
using TrafficManager.Util;
using GenericGameBridge.Service;

public class VehicleRestrictionsManager
: AbstractGeometryObservingManager,
Expand Down Expand Up @@ -352,6 +353,38 @@ internal ExtVehicleType GetDefaultAllowedVehicleTypes(
return ExtVehicleType.None;
}

/// <summary>
/// Restores all vehicle restrictions on a given segment to default state.
/// </summary>
/// <param name="segmentId"></param>
/// <returns></returns>
internal bool ClearVehicleRestrictions(ushort segmentId) {
NetInfo segmentInfo = segmentId.ToSegment().Info;
bool ret = false;
IList<LanePos> lanes = Constants.ServiceFactory.NetService.GetSortedLanes(
segmentId,
ref segmentId.ToSegment(),
null,
LANE_TYPES,
VEHICLE_TYPES,
sort: false);

foreach (LanePos laneData in lanes) {
uint laneId = laneData.laneId;
byte laneIndex = laneData.laneIndex;
NetInfo.Lane laneInfo = segmentInfo.m_lanes[laneIndex];

ret |= SetAllowedVehicleTypes(
segmentId,
segmentInfo,
laneIndex,
laneInfo,
laneId,
EXT_VEHICLE_TYPES);
}
return ret;
}

/// <summary>
/// Sets the allowed vehicle types for the given segment and lane.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ namespace TrafficManager.Patch._RoadWorldInfoPanel
using ColossalFramework;
using Harmony;
using JetBrains.Annotations;
using TrafficManager.UI;

[HarmonyPatch(typeof(RoadWorldInfoPanel), "OnAdjustRoadButton")]
[UsedImplicitly]
Expand Down
8 changes: 0 additions & 8 deletions TLM/TLM/Resources/Translations/Menu.csv
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,6 @@
"Tooltip:Lane connector","Fahrspurverbinder","Lane Connector","Conector de carriles","Connecteur de voies","Sávcsatlakozó","Connettore di corsia","車線を接続","차선 연결","Rijstrookverbinder","Połącz pasy ruchu","Conector de faixas","Соединения Полос Движения","車道連接工具","车道连接","Lane connector","Şerit birleştiricisi","З'єднання Смуг Руху","Připojení jízdních pruhů","",""
"Tooltip:Junction restrictions","Kreuzungsbeschränkungen","Junction Restrictions","Restricciones del cruce","Restrictions des intersections","Csomópont korlátozások","Restrizioni d'incrocio","交差点の制限","교차로 규칙","Splitsingsbeperkingen","Ograniczenia na skrzyżowaniach","Restrições de junção","Ограничения на Перекрёстках","交岔路口動線連接制定","路口管制","Junction restrictions","Kavşak kısıtlamaları","Обмеження на Перехресті","Pravidla křižovatky","",""
"Tooltip.Keybinds:Auto TL","Strg+Klick: Automatische Einstellung der Ampeln","Ctrl+Click: Quick setup","Semáforos automáticos","Feux automatiques","Automatikus jelzőlámpa","Ctrl+Clic: Configurazione rapida","Ctrl+クリック: クイックセットアップ","Ctrl+클릭: 빠른 설정","Ctrl+Shift+Klik: Automatische setup van de verkeerslichten","Ctrl + Klik: Szybka instalacja","Ctrl+Clique: Configuração rápida","Ctrl+Click: Автоматическое создание светофора с таймером","自動化號誌","Ctrl+点击: 快速设置","Ctrl+Click: Quick setup","Özdevinimli TI","Ctrl+Click: Автоматичне створення світлофора з таймером","Ctrl + Levý klik: rychlé nastavení semaforu","",""
"Roundabout.Option:Allocate dedicated exit lanes","Dedizierte Ausfahrspuren zuweisen","Allocate dedicated exit lanes","","Attribuer des voies de sortie dédiées","","Assegna corsie di uscita","専用の出口レーンを割り当てる","출구 전용 차선 할당","Wijs speciale exit-rijstroken toe","Przydziel dedykowane pasy zjazdu z ronda","Atribuir faixas de saída dedicadas","Выделенные полосы для покидания круга","分配出口專用車道","","Allocate dedicated exit lanes","Ayrılmış çıkış şeritleri özgüle","Окремі смуги для виїзду з кругового перехрестя","Povolit samostatné pruhy pro výjezd","",""
"Roundabout.Tooltip:Allocate dedicated exit lanes","Dedizierte Ausfahrspuren zuweisen","One dedicated lane for each exit, the rest of lanes go straight","","Attribuer des voies de sortie dédiées","","Una corsia per ogni uscita, le restanti per proseguire dritto","各出口に1つの専用レーン、残りのレーンは直進","각 출구에 대해 전용 차선 1개, 나머지 차선은 직진","Een speciale rijstrook voor elke afslag, de rest van de rijstroken gaat rechtdoor","Dedykowany pas do zjazdu, pozostałe do jazdy na wprost","Apenas uma das faixas será dedicada para cada saída, o resto seguirá em frente","Крайние полосы будут назначены исключительно для съезда с круга","分配出口專用車道","","One dedicated lane for each exit, the rest of lanes go straight","Her çıkışa bir şerit özgüler, geriye kalan şeritler düz akar","Призначити крайні смуги руху виключно для виїзду з кругового перехрестя","Přiřadí vyhrazené pruhy pro každý výjezd, ostatní budou pokračovat rovně","",""
"Roundabout.Option:Stay in lane inside roundabout","Keine Spurwechsel im Kreisverkehr","Stay in lane inside the roundabout","","Rester dans la voie à l'intérieur du rond-point","Maradjon a sávjában a körforgalomban","Nella rotonda i veicoli devono mantenere la corsia","ラウンドアバウト交差点内では車線にとどまる","라운드어바웃 안에서의 차선 유지","Blijf in lijn binnen de rotonde","'Pozostań na pasie' na drogach wewnątrz ronda","Permanecer na faixa dentro da rotatória","Оставаться в полосе внутри круга","將車道留在圓環島內","","Stay in lane inside the roundabout","Dönel kavşak içinde şerit değiştirilmesin","Тримати смугу всередині кругового перехрестя","Zůstat v pruhu během jízdy v kruhovém objezdu","",""
"Roundabout.Option:Stay in lane outside roundabout","Keine Spurwechsel außerhalb eines Kreisverkers","Stay in lane on the roads approaching the roundabout","","Rester dans la voie à l'extérieur du rond-point","Sávon belül maradjon a körforgalmon kívül","Nelle corsie in avvicinamento alla rotonda i veicoli devono mantenere la corsia","ラウンドアバウト交差点に近づく道路で車線に留まる","라운드어바웃으로 접근하는 도로를 차선 유지","Blijf in de lijn op wegen die de rotonde naderen","'Pozostań na pasie' na drogach dojazdowych do ronda","Permanecer na faixa nas ruas de acesso à rotatória","Оставаться в полосе на подъезде к кругу","將車道留在圓環島外","","Stay in lane on the roads approaching the roundabout","Dönel kavşak bağlantılarında şerit değiştirilmesin","Тримати смугу на під'їзді до кругового перехрестя","Zůstat v pruhu opouštění kruhového objezdu","",""
"Roundabout.Tooltip:Stay in lane outside roundabout","Fahrzeuge vor einem Kreisverkehr wechseln nicht die Spur","Vehicles shall not switch lanes too close to the roundabout","","Rester dans la voie à l'extérieur du rond-point","Maradjon a sávjában a körforgalmon kívül","I veicoli non possono cambiare corsia troppo vicini alla rotonda","車両は、ラウンドアバウト交差点に接近して車線を変更してはならない","차량은 차선을 라운드어바웃에 너무 가깝게 전환하지 않는다","Voertuigen mogen niet van rijstrook wisselen die te dicht bij de rotonde liggen","Pojazdy nie powinny zmieniać pasa zbyt blisko ronda","Proibir a mudança de faixas de veículos muito próximos a rotatória","Если узел дороги находится слишком близко к кругу, будет назначено правило ""оставаться в полосе""","將車道留在圓環島外","","Vehicles shall not switch lanes too close to the roundabout","Taşıtlar dönel kavşağa yaklaşırken şerit değiştirmesin","Заборонити зміну смуг руху, якщо вузол знаходиться близько до кругового перехрестя","Vozidla nesmí měnit jízdní pruhy příliš blízko kruhovému objezdu","",""
"Roundabout.Option:No crossing inside","Fußgänger betreten nicht die Mitte eines Kreisels","Pedestrians shall not cross to the center of roundabout","","Pas de croisement à l'intérieur","Ne legyen gyalogátkelő a körforgalomban","I pedoni non possono attraversare al centro della rotonda","歩行者は、ラウンドアバウト交差点の中心部に進入してはならない。","라운드어바웃의 중앙으로 보행자가 건너지 않음","Voetgangers mogen de oversteekplaatsen niet oversteken die op de rotonde liggen","Pieszy nie powinni przechodzić przez drogę do środka ronda","Proibir a travessia de pedestres para o centro da rotatória","Запретить пешеходные переходы внутри круга","內部無路口","","Pedestrians shall not cross to the centre of the roundabout","Yayalar kavşak ortasından karşıya geçmesin","Заборонити пішохідні переходи всередині","Chodci by nesmí přecházet kruhový objezd doprostřed","",""
"Roundabout.Option:No crossing on incoming roads","Keine Überquerung über ankommende Straßen","Pedestrians shall not cross the roads approaching the roundabout","","Pas de croisement sur les routes entrantes","Ne legyen gyalogátkelő a bejövő utakon","I pedoni non possono attraversare le strade in avvicinamento alla rotonda","歩行者は、ラウンドアバウト交差点に進入する道路を横断してはならない","라운드어바웃으로 접근하는 도로를 보행자가 건너지 않음","Voetgangers mogen de weg niet oversteken die aan de inkomende wegen van de rotonde liggen","Pieszy nie powinni przechodzić przez drogę tuż przed rondem","Proibir a travessia de pedestres nas ruas de acesso a rotatória","Запретить пешеходные переходы на подъездных дорогах к кругу","路口無連接的道路","","Pedestrians shall not cross the roads approaching the roundabout","Yayalar kavşak bağlantılarına yakınken karşıya geçmesin","Заборонити пішохідні переході на під'їздних дорогах","Chodci nesmí přecházet silnici blízko kruhovému objezdu","",""
"Roundabout.Option:Set priority signs","Vorfahrtsschilder setzen","Add priority signs on the roundabout junction","Añadir señales de prioridad en los cruces de la rotonda","Définir les panneaux de priorité","Elsőbbségadás tábla hozzáadása a körforgalomhoz","Aggiungi segnali di precedenza alla rotonda","ラウンドアバウト交差点に優先標識を追加する","라운드어바웃 교차로에 우선주행 표지판 추가","Voeg Prioriteitsborden toe aan rotondes","Dodaj znaki pierwszeństwa przejazdu na rondzie","Adicionar placas de prioridade na junção da rotatória","Установить знаки приоритета","設定優先標誌","","Add priority signs on the roundabout junction","Öncelik işaretlerini ayarla","Встановити знаки пріоритету на круговому перехресті","Přidat přednost na kruhovém objezdu","",""
"Tooltip:Disable despawning","Despawn ausschalten","Toggle automatic vehicle despawning
Currently: ENABLED (easy mode, less traffic jams)","Desactivar desaparición","Désactiver la disparition","Letiltja a hajtást","Disabilita la sparizione dei veicoli","スタック除去無効化","차 사라짐 비활성화","Voertuigverdwijning uitschakelen","Zablokuj znikanie pojazdów","Desativar desaparecimento de carros","Переключение режима Исчезновения Транспорта\n
Сейчас: Включено (лёгкий режим, пробки случаются реже)","久塞車輛永不消失","禁止车辆消失","Despawning is currently enabled. Disable despawning.","Yok olmayı devre dışı bırak","Переключення режиму Зникнення Застряглих Автівок\n
Expand Down
Loading

0 comments on commit 1a699f5

Please sign in to comment.