Here are the examples of the csharp api char.ToUpper(char) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
660 Examples
19
View Source File : StringHelper.cs
License : MIT License
Project Creator : 0x1000000
License : MIT License
Project Creator : 0x1000000
public static string DeSnake(string input)
{
if (string.IsNullOrEmpty(input))
{
return input;
}
char[]? result = null;
int nextResultIndex = 0;
bool afterSymbol = true;
for (int i = 0; i < input.Length; i++)
{
var ch = input[i];
if (!char.IsLetterOrDigit(ch))
{
afterSymbol = true;
EnsureResult(i);
}
else
{
if (afterSymbol && char.IsLower(ch))
{
OutResult(i, char.ToUpper(ch), true);
}
else
{
OutResult(i, ch, false);
}
afterSymbol = false;
}
if (result == null)
{
nextResultIndex = i;
}
}
return result == null ? input : new string(result, 0, nextResultIndex);
void EnsureResult(int index)
{
if (result == null)
{
result = new char[input.Length + 1];
input.CopyTo(0, result, 0, input.Length);
nextResultIndex = index;
}
}
void OutResult(int index, char ch, bool changed)
{
var isFirstDigit = nextResultIndex == 0 && char.IsDigit(ch);
if (result == null)
{
if (!changed && !isFirstDigit)
{
return;
}
EnsureResult(index);
}
if (isFirstDigit)
{
result![nextResultIndex++] = 'D';
}
result![nextResultIndex++] = ch;
}
}
19
View Source File : Form1.cs
License : MIT License
Project Creator : 20chan
License : MIT License
Project Creator : 20chan
private bool TryReplace() {
foreach (var w in badWords) {
if (Match(w)) {
Replace(w.Length);
queue.Clear();
return true;
}
}
return false;
bool Match(string s) {
if (s.Length != queue.Count) {
return false;
}
for (var i = 0; i < s.Length; i++) {
if (queue[i] != char.ToUpper(s[i])) {
return false;
}
}
return true;
}
}
19
View Source File : Immutable.cs
License : MIT License
Project Creator : 71
License : MIT License
Project Creator : 71
public override ClreplacedDeclarationSyntax Apply(ClreplacedDeclarationSyntax node, INamedTypeSymbol symbol, CancellationToken cancellationToken)
{
var parameters = ImmutableArray.CreateBuilder<ParameterSyntax>();
var arguments = ImmutableArray.CreateBuilder<ArgumentSyntax>();
var ctorStmts = ImmutableArray.CreateBuilder<StatementSyntax>();
// Generate all parameters and statements
var members = symbol.GetMembers();
for (int i = 0; i < members.Length; i++)
{
IPropertySymbol member = members[i] as IPropertySymbol;
if (member == null || !member.IsReadOnly || !member.CanBeReferencedByName)
continue;
// Read-only prop, we good
string propName = member.Name;
string paramName = $"{char.ToLower(propName[0]).ToString()}{propName.Substring(1)}";
TypeSyntax paramType = ((PropertyDeclarationSyntax)member.DeclaringSyntaxReferences[0]
.GetSyntax(cancellationToken)).Type;
MemberAccessExpressionSyntax propAccess = F.MemberAccessExpression(
K.SimpleMemberAccessExpression,
F.ThisExpression(),
F.IdentifierName(propName)
);
// Make parameter & argument
parameters.Add(F.Parameter(F.Identifier(paramName)).WithType(paramType));
arguments.Add(F.Argument(propAccess));
// Make ctor stmt
ctorStmts.Add(F.ExpressionStatement(
F.replacedignmentExpression(K.SimplereplacedignmentExpression,
propAccess,
F.IdentifierName(paramName)
)
));
}
// The ctor is full, make all the 'with' methods
TypeSyntax returnType = F.IdentifierName(symbol.Name);
MemberDeclarationSyntax[] additionalMethods = new MemberDeclarationSyntax[parameters.Count + 1];
arguments.Capacity = arguments.Count;
ImmutableArray<ArgumentSyntax> args = arguments.MoveToImmutable();
for (int i = 0; i < parameters.Count; i++)
{
ParameterSyntax parameter = parameters[i];
string parameterName = parameter.Identifier.Text;
ArgumentSyntax name = F.Argument(F.IdentifierName(parameterName));
SeparatedSyntaxList<ArgumentSyntax> allArguments = F.SeparatedList(args.Replace(args[i], name));
StatementSyntax returnStmt = F.ReturnStatement(
F.ObjectCreationExpression(returnType).WithArgumentList(F.ArgumentList(allArguments))
);
additionalMethods[i] = F.MethodDeclaration(returnType, $"With{char.ToUpper(parameterName[0]).ToString()}{parameterName.Substring(1)}")
.AddModifiers(F.Token(K.PublicKeyword), F.Token(K.NewKeyword))
.AddParameterListParameters(parameter)
.AddBodyStatements(returnStmt);
}
// Add the private ctor
additionalMethods[parameters.Count] = F.ConstructorDeclaration(symbol.Name)
.AddModifiers(F.Token(K.PrivateKeyword))
.AddParameterListParameters(parameters.ToArray())
.AddBodyStatements(ctorStmts.ToArray());
return node.AddMembers(additionalMethods);
}
19
View Source File : ExtensionMethods.cs
License : Apache License 2.0
Project Creator : A7ocin
License : Apache License 2.0
Project Creator : A7ocin
public static string BreakupCamelCase(this String str)
{
StringBuilder sb = new StringBuilder();
for (int i=0;i<str.Length;i++)
{
char c = str[i];
if (i > 0 && char.IsUpper(c))
{
sb.Append(' ');
}
if (i==0)
c = char.ToUpper(c);
sb.Append(c);
}
return sb.ToString();
}
19
View Source File : Program.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
private static void CommandInput()
{
Thread.Sleep(3000);
Console.WriteLine(@"Available console commands: Q - quit (shutdown)
R - restart (shutdown and start),
L - command to save players for shutdown (EverybodyLogoff)
S - save player statistics file");
while (true)
{
Thread.Sleep(500);
var key = Console.ReadKey(true);
if (char.ToLower(key.KeyChar) == 'q') Manager.SaveAndQuit();
if (char.ToLower(key.KeyChar) == 'r') Manager.SaveAndRestart();
else if (char.ToLower(key.KeyChar) == 'l') Manager.EverybodyLogoff();
else if (char.ToLower(key.KeyChar) == 's') Manager.SavePlayerStatisticsFile();
else Console.WriteLine($"Unknow command: {char.ToUpper(key.KeyChar)}");
}
}
19
View Source File : PlayerCommands.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
[CommandHandler("reportbug", AccessLevel.Player, CommandHandlerFlag.RequiresWorld, 2,
"Generate a Bug Report",
"<category> <description>\n" +
"This command generates a URL for you to copy and paste into your web browser to submit for review by server operators and developers.\n" +
"Category can be the following:\n" +
"Creature\n" +
"NPC\n" +
"Item\n" +
"Quest\n" +
"Recipe\n" +
"Landblock\n" +
"Mechanic\n" +
"Code\n" +
"Other\n" +
"For the first three options, the bug report will include identifiers for what you currently have selected/targeted.\n" +
"After category, please include a brief description of the issue, which you can further detail in the report on the website.\n" +
"Examples:\n" +
"/reportbug creature Drudge Prowler is over powered\n" +
"/reportbug npc Ulgrim doesn't know what to do with Sake\n" +
"/reportbug quest I can't enter the portal to the Lost City of Frore\n" +
"/reportbug recipe I cannot combine Bundle of Arrowheads with Bundle of Arrowshafts\n" +
"/reportbug code I was killed by a Non-Player Killer\n"
)]
public static void HandleReportbug(Session session, params string[] parameters)
{
if (!PropertyManager.GetBool("reportbug_enabled").Item)
{
session.Network.EnqueueSend(new GameMessageSystemChat("The command \"reportbug\" is not currently enabled on this server.", ChatMessageType.Broadcast));
return;
}
var category = parameters[0];
var description = "";
for (var i = 1; i < parameters.Length; i++)
description += parameters[i] + " ";
description.Trim();
switch (category.ToLower())
{
case "creature":
case "npc":
case "quest":
case "item":
case "recipe":
case "landblock":
case "mechanic":
case "code":
case "other":
break;
default:
category = "Other";
break;
}
var sn = ConfigManager.Config.Server.WorldName;
var c = session.Player.Name;
var st = "ACE";
//var versions = ServerBuildInfo.GetVersionInfo();
var databaseVersion = DatabaseManager.World.GetVersion();
var sv = ServerBuildInfo.FullVersion;
var pv = databaseVersion.PatchVersion;
//var ct = PropertyManager.GetString("reportbug_content_type").Item;
var cg = category.ToLower();
var w = "";
var g = "";
if (cg == "creature" || cg == "npc"|| cg == "item" || cg == "item")
{
var objectId = new ObjectGuid();
if (session.Player.HealthQueryTarget.HasValue || session.Player.ManaQueryTarget.HasValue || session.Player.CurrentAppraisalTarget.HasValue)
{
if (session.Player.HealthQueryTarget.HasValue)
objectId = new ObjectGuid((uint)session.Player.HealthQueryTarget);
else if (session.Player.ManaQueryTarget.HasValue)
objectId = new ObjectGuid((uint)session.Player.ManaQueryTarget);
else
objectId = new ObjectGuid((uint)session.Player.CurrentAppraisalTarget);
//var wo = session.Player.CurrentLandblock?.GetObject(objectId);
var wo = session.Player.FindObject(objectId.Full, Player.SearchLocations.Everywhere);
if (wo != null)
{
w = $"{wo.WeenieClreplacedId}";
g = $"0x{wo.Guid:X8}";
}
}
}
var l = session.Player.Location.ToLOCString();
var issue = description;
var urlbase = $"https://www.accpp.net/bug?";
var url = urlbase;
if (sn.Length > 0)
url += $"sn={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(sn))}";
if (c.Length > 0)
url += $"&c={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(c))}";
if (st.Length > 0)
url += $"&st={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(st))}";
if (sv.Length > 0)
url += $"&sv={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(sv))}";
if (pv.Length > 0)
url += $"&pv={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(pv))}";
//if (ct.Length > 0)
// url += $"&ct={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(ct))}";
if (cg.Length > 0)
{
if (cg == "npc")
cg = cg.ToUpper();
else
cg = char.ToUpper(cg[0]) + cg.Substring(1);
url += $"&cg={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(cg))}";
}
if (w.Length > 0)
url += $"&w={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(w))}";
if (g.Length > 0)
url += $"&g={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(g))}";
if (l.Length > 0)
url += $"&l={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(l))}";
if (issue.Length > 0)
url += $"&i={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(issue))}";
var msg = "\n\n\n\n";
msg += "Bug Report - Copy and Paste the following URL into your browser to submit a bug report\n";
msg += "-=-\n";
msg += $"{url}\n";
msg += "-=-\n";
msg += "\n\n\n\n";
session.Network.EnqueueSend(new GameMessageSystemChat(msg, ChatMessageType.AdminTell));
}
19
View Source File : TabularModelSerializer.cs
License : MIT License
Project Creator : action-bi-toolkit
License : MIT License
Project Creator : action-bi-toolkit
public static string ToPascalCase(this string s)
{
var sb = new StringBuilder(s);
if (sb.Length > 0) sb[0] = Char.ToUpper(s[0]);
return sb.ToString();
}
19
View Source File : CodeGenerator.partial.cs
License : BSD 2-Clause "Simplified" License
Project Creator : adospace
License : BSD 2-Clause "Simplified" License
Project Creator : adospace
private static string Capitalize(string name)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (name.Length < 1)
return name;
var ns = new StringBuilder(name);
ns[0] = char.ToUpper(name[0]);
return ns.ToString();
}
19
View Source File : CodeGenerator.partial.cs
License : BSD 2-Clause "Simplified" License
Project Creator : adospace
License : BSD 2-Clause "Simplified" License
Project Creator : adospace
static string Capitalize(string name)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (name.Length < 1)
return name;
var ns = new StringBuilder(name);
ns[0] = char.ToUpper(name[0]);
return ns.ToString();
}
19
View Source File : CecilifierExtensions.cs
License : MIT License
Project Creator : adrianoc
License : MIT License
Project Creator : adrianoc
public static string PascalCase(this string str)
{
return str.Length > 1
? char.ToUpper(str[0]) + str.Substring(1)
: str;
}
19
View Source File : SpecialPageService.cs
License : MIT License
Project Creator : Aeroblast
License : MIT License
Project Creator : Aeroblast
public static string BookInfo()
{
StringBuilder r = new StringBuilder();
r.Append("<html><head><style>img{max-height:55vh;max-width:90vw}data-item{font-weight:bold;}table{max-width:95%;margin-left:4%;border:none;}</style></head><body>");
r.Append("<h1>" + Program.epub.replacedle + "</h1>");
if (Program.epub.cover_img != "") r.Append("<img src=\"aeroepub://domain/book/" + Program.epub.cover_img + "\"/>");
r.Append("<table>");
string creators = "";
foreach (var a in Program.epub.creatorRecords)
{
string t = a.value;
var role = a.GetRefines("role");
if (role != null && Dics.marc2name.ContainsKey(role.value))
{
t += " (" + Dics.marc2name[role.value] + ")";
}
if (creators != "") creators += ", ";
creators += t;
}
r.Append("<tr><td>Creator(s)</td><td><data-item>" + creators + "</data-item></td></tr>");
string lang = "";
foreach (var a in Program.epub.languageRecords)
{
if (Dics.langcode.ContainsKey(a.value.ToLower()))
{
lang += Dics.langcode[a.value.ToLower()] + " ";
}
else
{
lang += a.value + " ";
}
}
if (lang == "")
{
if (Dics.langcode.ContainsKey(Program.epub.language))
{
lang += Dics.langcode[Program.epub.language];
}
else
{
lang += Program.epub.language;
}
}
r.Append("<tr><td>Language</td><td><data-item>" + lang + "</data-item></td></tr>");
foreach (var a in Program.epub.otherRecords)
{
string name = a.name;
if (name.IndexOf(':') > 0) name = name.Substring(name.IndexOf(':') + 1);
name = Char.ToUpper(name[0]) + name.Substring(1);
string value = a.value;
switch (a.name)
{
case "dc:contributor":
{
var role = a.GetRefines("role");
if (role != null && Dics.marc2name.ContainsKey(role.value))
{
value += " (" + Dics.marc2name[role.value] + ")";
}
}
break;
case "dc:date":
{
var dateEvent = a.GetRefines("event");
if (dateEvent != null)
name += $" ({dateEvent.value})";
}
break;
}
r.Append("<tr><td>" + name + "</td><td><data-item>" + value + "</data-item></td></tr>");
}
r.Append("<tr><td>File</td><td><data-item>" + Program.epub.path + "</data-item></td></tr>");
r.Append("</table><p>Other metadata:</p><table>");
foreach (var a in Program.epub.identifierRecords)
{
string v = a.value;
var t = a.GetRefines("identifier-type");
if (t != null) v = t.GetRefines("scheme").value + ":" + v;
t = a.GetRefines("scheme");
if (t != null) v = t.value + ":" + v;
r.Append("<tr><td>Identifier</td><td><data-item>" + v + "</data-item></td></tr>");
}
foreach (var a in Program.epub.meta)
{
r.Append("<tr><td>" + a.name + "</td><td><data-item>" + a.value + "</data-item></td></tr>");
}
r.Append("</table>");
r.Append("<script src=\"aeroepub://domain/viewer/sp-page.js\"></script>");
r.Append("</body>");
return r.ToString();
}
19
View Source File : VehicleManager.cs
License : GNU General Public License v3.0
Project Creator : Albo1125
License : GNU General Public License v3.0
Project Creator : Albo1125
internal void towVehicle(Vehicle car, bool playanims = true)
{
GameFiber.StartNew(delegate
{
if(!car.Exists()) { return; }
try
{
bool flatbed = true;
if (car.HasOccupants)
{
Game.DisplayNotification("Vehicle has occupants. Aborting tow.");
return;
}
if (car.IsPoliceVehicle)
{
uint noti = Game.DisplayNotification("Are you sure you want to tow the police vehicle? ~h~~b~Y/N");
while (true)
{
GameFiber.Yield();
if (Albo1125.Common.CommonLibrary.ExtensionMethods.IsKeyDownComputerCheck(System.Windows.Forms.Keys.Y))
{
Game.RemoveNotification(noti);
break;
}
if (Albo1125.Common.CommonLibrary.ExtensionMethods.IsKeyDownComputerCheck(System.Windows.Forms.Keys.N))
{
Game.RemoveNotification(noti);
return;
}
}
if (!car.Exists()) { return; }
}
if (!car.Model.IsCar && !car.Model.IsBike && !car.Model.IsQuadBike && !car.Model.IsBoat && !car.Model.IsJetski)
{
Game.DisplayNotification("Unfortunately, this vehicle can't be towed or impounded.");
return;
}
car.IsPersistent = true;
if (playanims)
{
Game.LocalPlayer.Character.Tasks.PlayAnimation("[email protected]", "generic_radio_chatter", 1.5f, AnimationFlags.UpperBodyOnly | AnimationFlags.SecondaryTask);
GameFiber.Wait(1000);
bleepPlayer.Play();
GameFiber.Wait(500);
}
carblip = car.AttachBlip();
carblip.Color = System.Drawing.Color.Black;
carblip.Scale = 0.7f;
if (EntryPoint.IsLSPDFRPlusRunning)
{
API.LSPDFRPlusFuncs.AddCountToStatistic(Main.PluginName, "Vehicles towed");
}
Ped playerPed = Game.LocalPlayer.Character;
if (car.Model.IsCar && RecruitNearbyTowtruck(out driver, out towTruck))
{
Game.LogTrivial("Recruited nearby tow truck.");
}
else
{
float Heading;
bool UseSpecialID = true;
Vector3 SpawnPoint;
float travelDistance;
int waitCount = 0;
while (true)
{
GetSpawnPoint(car.Position, out SpawnPoint, out Heading, UseSpecialID);
travelDistance = Rage.Native.NativeFunction.Natives.CALCULATE_TRAVEL_DISTANCE_BETWEEN_POINTS<float>( SpawnPoint.X, SpawnPoint.Y, SpawnPoint.Z, car.Position.X, car.Position.Y, car.Position.Z);
waitCount++;
if (Vector3.Distance(car.Position, SpawnPoint) > EntryPoint.SceneManagementSpawnDistance - 15f)
{
if (travelDistance < (EntryPoint.SceneManagementSpawnDistance * 4.5f))
{
Vector3 directionFromVehicleToPed1 = (car.Position - SpawnPoint);
directionFromVehicleToPed1.Normalize();
float HeadingToPlayer = MathHelper.ConvertDirectionToHeading(directionFromVehicleToPed1);
if (Math.Abs(MathHelper.NormalizeHeading(Heading) - MathHelper.NormalizeHeading(HeadingToPlayer)) < 150f)
{
break;
}
}
}
if (waitCount >= 400)
{
UseSpecialID = false;
}
if (waitCount == 600)
{
Game.DisplayNotification("Take the car ~s~to a more reachable location.");
Game.DisplayNotification("Alternatively, press ~b~Y ~s~to force a spawn in the ~g~wilderness.");
}
if ((waitCount >= 600) && Albo1125.Common.CommonLibrary.ExtensionMethods.IsKeyDownComputerCheck(Keys.Y))
{
SpawnPoint = Game.LocalPlayer.Character.Position.Around(15f);
break;
}
GameFiber.Yield();
}
modelName = car.Model.Name.ToLower();
modelName = char.ToUpper(modelName[0]) + modelName.Substring(1);
if (car.Model.IsCar && !car.IsDead && !AlwaysFlatbed)
{
Game.DisplayNotification("A ~g~tow truck ~s~has been dispatched for the target ~r~" + modelName + ". ~s~Await arrival.");
towTruck = new Vehicle(TowtruckModel, SpawnPoint, Heading);
Game.DisplayHelp("~b~If you want to attach the vehicle yourself, get in now.");
flatbed = false;
}
else
{
Game.DisplayNotification("A ~g~flatbed ~s~has been dispatched for the target ~r~" + modelName + ". ~s~Await arrival.");
towTruck = new Vehicle(FlatbedModel, SpawnPoint, Heading);
}
}
TowTrucksBeingUsed.Add(towTruck);
towTruck.IsPersistent = true;
towTruck.CanTiresBurst = false;
towTruck.IsInvincible = true;
if (OverrideTowTruckColour)
{
towTruck.PrimaryColor = TowTruckColour;
towTruck.SecondaryColor = TowTruckColour;
towTruck.PearlescentColor = TowTruckColour;
}
towblip = towTruck.AttachBlip();
towblip.Color = System.Drawing.Color.Blue;
//Vector3 directionFromVehicleToPed = (car.Position - towTruck.Position);
//directionFromVehicleToPed.Normalize();
//towTruck.Heading = MathHelper.ConvertDirectionToHeading(directionFromVehicleToPed);
if (!driver.Exists())
{
driver = towTruck.CreateRandomDriver();
}
driver.MakeMissionPed();
driver.IsInvincible = true;
driver.Money = 1233;
driveToEnreplacedy(driver, towTruck, car, false);
Rage.Native.NativeFunction.Natives.START_VEHICLE_HORN(towTruck, 5000, 0, true);
if (towTruck.Speed > 15f)
{
NativeFunction.Natives.SET_VEHICLE_FORWARD_SPEED(towTruck, 15f);
}
driver.Tasks.PerformDrivingManeuver(VehicleManeuver.GoForwardStraightBraking);
GameFiber.Sleep(600);
driver.Tasks.PerformDrivingManeuver(VehicleManeuver.Wait);
towTruck.IsSirenOn = true;
GameFiber.Wait(2000);
bool automaticallyAttach = false;
bool showImpoundMsg = true;
if (flatbed)
{
while (car && car.HasOccupants)
{
GameFiber.Yield();
Game.DisplaySubreplacedle("~r~Please remove all occupants from the vehicle.", 1);
}
if (car)
{
car.AttachTo(towTruck, 20, FlatbedModifier, Rotator.Zero);
}
}
else
{
if (!Game.LocalPlayer.Character.IsInVehicle(car, true))
{
automaticallyAttach = true;
}
while (true)
{
GameFiber.Sleep(1);
driver.Money = 1233;
if (!car.Exists()) { break; }
if (Albo1125.Common.CommonLibrary.ExtensionMethods.IsKeyDownRightNowComputerCheck(Keys.D0) || automaticallyAttach)
{
if (Game.LocalPlayer.Character.IsInVehicle(car, false))
{
Game.DisplaySubreplacedle("~r~Get out of the vehicle first.", 5000);
}
else
{
car.Position = towTruck.GetOffsetPosition(Vector3.RelativeBack * 7f);
car.Heading = towTruck.Heading;
if (towTruck.HasTowArm)
{
towTruck.TowVehicle(car, true);
}
else
{
car.Delete();
Game.LogTrivial("Tow truck model is not registered as a tow truck ingame - if this is a custom vehicle, contact the vehicle author.");
Game.DisplayNotification("Tow truck model is not registered as a tow truck ingame - if this is a custom vehicle, contact the vehicle author.");
}
Game.HideHelp();
break;
}
}
else if (Vector3.Distance(towTruck.GetOffsetPosition(Vector3.RelativeBack * 7f), car.Position) < 2.1f)
{
//Game.LogTrivial((towTruck.Heading - car.Heading).ToString());
if ((towTruck.Heading - car.Heading < 30f) && (towTruck.Heading - car.Heading > -30f))
{
Game.DisplaySubreplacedle("~b~Exit the vehicle", 1);
if (!Game.LocalPlayer.Character.IsInVehicle(car, true))
{
GameFiber.Sleep(1000);
towTruck.TowVehicle(car, true);
break;
}
}
else if (((towTruck.Heading - car.Heading < -155f) && (towTruck.Heading - car.Heading > -205f)) || ((towTruck.Heading - car.Heading > 155f) && (towTruck.Heading - car.Heading < 205f)))
{
Game.DisplaySubreplacedle("~b~Exit the vehicle", 1);
if (!Game.LocalPlayer.Character.IsInVehicle(car, true))
{
GameFiber.Sleep(1000);
if (towTruck.HasTowArm)
{
towTruck.TowVehicle(car, false);
}
else
{
car.Delete();
Game.LogTrivial("Tow truck model is not registered as a tow truck ingame - if this is a custom vehicle, contact the vehicle author.");
Game.DisplayNotification("Tow truck model is not registered as a tow truck ingame - if this is a custom vehicle, contact the vehicle author.");
}
break;
}
}
else
{
Game.DisplaySubreplacedle("~b~Align the ~b~vehicle~s~ with the ~g~tow truck.", 1);
}
}
else
{
Game.DisplaySubreplacedle("Drive the vehicle behind the tow truck.", 1);
}
if (Vector3.Distance(Game.LocalPlayer.Character.Position, car.Position) > 70f)
{
car.Position = towTruck.GetOffsetPosition(Vector3.RelativeBack * 7f);
car.Heading = towTruck.Heading;
if (towTruck.HasTowArm)
{
towTruck.TowVehicle(car, true);
}
else
{
car.Delete();
Game.LogTrivial("Tow truck model is not registered as a tow truck ingame - if this is a custom vehicle, contact the vehicle author.");
Game.DisplayNotification("Tow truck model is not registered as a tow truck ingame - if this is a custom vehicle, contact the vehicle author.");
}
break;
}
if (Vector3.Distance(car.Position, towTruck.Position) > 80f)
{
Game.DisplaySubreplacedle("Towing service cancelled", 5000);
showImpoundMsg = false;
break;
}
}
}
Game.HideHelp();
if (showImpoundMsg)
{
Game.DisplayNotification("The target ~r~" + modelName + " ~s~has been impounded!");
}
driver.Tasks.PerformDrivingManeuver(VehicleManeuver.GoForwardStraight).WaitForCompletion(600);
driver.Tasks.CruiseWithVehicle(25f);
GameFiber.Wait(1000);
if (car.Exists() && towTruck.Exists() && !flatbed)
{
if (!car.FindTowTruck().Exists())
{
car.Position = towTruck.GetOffsetPosition(Vector3.RelativeBack * 7f);
car.Heading = towTruck.Heading;
if (towTruck.HasTowArm)
{
towTruck.TowVehicle(car, true);
}
else
{
car.Delete();
Game.LogTrivial("Tow truck model is not registered as a tow truck ingame - if this is a custom vehicle, contact the vehicle author.");
Game.DisplayNotification("Tow truck model is not registered as a tow truck ingame - if this is a custom vehicle, contact the vehicle author.");
}
}
}
if (driver.Exists()) { driver.Dismiss(); }
if (car.Exists()) { car.Dismiss(); }
if (towTruck.Exists()) { towTruck.Dismiss(); }
if (towblip.Exists()) { towblip.Delete(); }
if (carblip.Exists()) { carblip.Delete(); }
while (towTruck.Exists() && car.Exists())
{
GameFiber.Sleep(1000);
}
if (car.Exists())
{
car.Delete();
}
}
catch (Exception e)
{
Game.LogTrivial(e.ToString());
Game.LogTrivial("Tow Truck Crashed");
Game.DisplayNotification("The towing service was interrupted.");
if (towblip.Exists()) { towblip.Delete(); }
if (carblip.Exists()) { carblip.Delete(); }
if (driver.Exists()) { driver.Delete(); }
if (car.Exists()) { car.Delete(); }
if (towTruck.Exists()) { towTruck.Delete(); }
}
});
}
19
View Source File : VehicleManager.cs
License : GNU General Public License v3.0
Project Creator : Albo1125
License : GNU General Public License v3.0
Project Creator : Albo1125
internal void insurancePickUp()
{
GameFiber.StartNew(delegate
{
try
{
Vehicle[] nearbyvehs = Game.LocalPlayer.Character.GetNearbyVehicles(2);
if (nearbyvehs.Length == 0)
{
Game.DisplayNotification("~r~Couldn't detect a close enough vehicle.");
return;
}
car = nearbyvehs[0];
if (Vector3.Distance(Game.LocalPlayer.Character.Position, car.Position) > 6f)
{
Game.DisplayNotification("~r~Couldn't detect a close enough vehicle.");
return;
}
if (car.HasOccupants)
{
if (nearbyvehs.Length == 2)
{
car = nearbyvehs[1];
if (car.HasOccupants)
{
Game.DisplayNotification("~r~Couldn't detect a close enough vehicle without occupants.");
return;
}
}
else
{
Game.DisplayNotification("~r~Couldn't detect a close enough vehicle without occupants.");
return;
}
}
if (car.IsPoliceVehicle)
{
Game.DisplayNotification("Are you sure you want to remove the police vehicle? ~h~~b~Y/N");
while (true)
{
GameFiber.Yield();
if (Albo1125.Common.CommonLibrary.ExtensionMethods.IsKeyDownComputerCheck(System.Windows.Forms.Keys.Y))
{
break;
}
if (Albo1125.Common.CommonLibrary.ExtensionMethods.IsKeyDownComputerCheck(System.Windows.Forms.Keys.N))
{
return;
}
}
}
ToggleMobilePhone(Game.LocalPlayer.Character, true);
GameFiber.Sleep(3000);
ToggleMobilePhone(Game.LocalPlayer.Character, false);
car.IsPersistent = true;
carblip = car.AttachBlip();
carblip.Color = System.Drawing.Color.Black;
carblip.Scale = 0.7f;
string modelName = car.Model.Name.ToLower();
modelName = char.ToUpper(modelName[0]) + modelName.Substring(1);
Ped playerPed = Game.LocalPlayer.Character;
if (EntryPoint.IsLSPDFRPlusRunning)
{
API.LSPDFRPlusFuncs.AddCountToStatistic(Main.PluginName, "Insurance pickups");
}
Vector3 SpawnPoint = World.GetNextPositionOnStreet(playerPed.Position.Around(EntryPoint.SceneManagementSpawnDistance));
float travelDistance;
int waitCount = 0;
while (true)
{
SpawnPoint = World.GetNextPositionOnStreet(playerPed.Position.Around(EntryPoint.SceneManagementSpawnDistance));
travelDistance = Rage.Native.NativeFunction.Natives.CALCULATE_TRAVEL_DISTANCE_BETWEEN_POINTS<float>( SpawnPoint.X, SpawnPoint.Y, SpawnPoint.Z, playerPed.Position.X, playerPed.Position.Y, playerPed.Position.Z);
waitCount++;
if (Vector3.Distance(playerPed.Position, SpawnPoint) > EntryPoint.SceneManagementSpawnDistance - 10f)
{
if (travelDistance < (EntryPoint.SceneManagementSpawnDistance * 4.5f))
{
break;
}
}
if (waitCount == 600)
{
Game.DisplayNotification("Take the car ~s~to a more reachable location.");
Game.DisplayNotification("Alternatively, press ~b~Y ~s~to force a spawn in the ~g~wilderness.");
}
if ((waitCount >= 600) && Albo1125.Common.CommonLibrary.ExtensionMethods.IsKeyDownComputerCheck(Keys.Y))
{
SpawnPoint = Game.LocalPlayer.Character.Position.Around(15f);
break;
}
GameFiber.Yield();
}
car.LockStatus = VehicleLockStatus.Unlocked;
car.MustBeHotwired = false;
Game.DisplayNotification("mphud", "mp_player_ready", "~h~Mors Mutual Insurance", "~b~Vehicle Pickup Status Update", "Two of our employees are en route to pick up our client's ~h~" + modelName + ".");
businessCar = new Vehicle(insurancevehicles[rnd.Next(insurancevehicles.Length)], SpawnPoint);
businesscarblip = businessCar.AttachBlip();
businesscarblip.Color = System.Drawing.Color.Blue;
businessCar.IsPersistent = true;
Vector3 directionFromVehicleToPed = (car.Position - businessCar.Position);
directionFromVehicleToPed.Normalize();
businessCar.Heading = MathHelper.ConvertDirectionToHeading(directionFromVehicleToPed);
driver = new Ped("a_m_y_business_02", businessCar.Position, businessCar.Heading);
driver.BlockPermanentEvents = true;
driver.WarpIntoVehicle(businessCar, -1);
driver.Money = 1;
preplacedenger = new Ped("a_m_y_business_02", businessCar.Position, businessCar.Heading);
preplacedenger.BlockPermanentEvents = true;
preplacedenger.WarpIntoVehicle(businessCar, 0);
preplacedenger.Money = 1;
driveToEnreplacedy(driver, businessCar, car, true);
Rage.Native.NativeFunction.Natives.START_VEHICLE_HORN(businessCar, 3000, 0, true);
while (true)
{
GameFiber.Yield();
driver.Tasks.DriveToPosition(car.GetOffsetPosition(Vector3.RelativeFront * 2f), 10f, VehicleDrivingFlags.DriveAroundVehicles | VehicleDrivingFlags.DriveAroundObjects | VehicleDrivingFlags.AllowMedianCrossing | VehicleDrivingFlags.YieldToCrossingPedestrians).WaitForCompletion(500);
if (Vector3.Distance(businessCar.Position, car.Position) < 15f)
{
driver.Tasks.PerformDrivingManeuver(VehicleManeuver.Wait);
break;
}
if (Vector3.Distance(car.Position, businessCar.Position) > 50f)
{
SpawnPoint = World.GetNextPositionOnStreet(car.Position);
businessCar.Position = SpawnPoint;
directionFromVehicleToPed = (car.Position - SpawnPoint);
directionFromVehicleToPed.Normalize();
float vehicleHeading = MathHelper.ConvertDirectionToHeading(directionFromVehicleToPed);
businessCar.Heading = vehicleHeading;
}
}
driver.PlayAmbientSpeech("GENERIC_HOWS_IT_GOING", true);
preplacedenger.Tasks.LeaveVehicle(LeaveVehicleFlags.None).WaitForCompletion();
Rage.Native.NativeFunction.Natives.SET_PED_CAN_RAGDOLL(preplacedenger, false);
preplacedenger.Tasks.FollowNavigationMeshToPosition(car.GetOffsetPosition(Vector3.RelativeLeft * 2f), car.Heading, 2f).WaitForCompletion(2000);
driver.Dismiss();
preplacedenger.Tasks.FollowNavigationMeshToPosition(car.GetOffsetPosition(Vector3.RelativeLeft * 2f), car.Heading, 2f).WaitForCompletion(3000);
preplacedenger.Tasks.EnterVehicle(car, 9000, -1).WaitForCompletion();
if (car.HasDriver)
{
if (car.Driver != preplacedenger)
{
car.Driver.Tasks.LeaveVehicle(LeaveVehicleFlags.WarpOut).WaitForCompletion();
}
}
preplacedenger.WarpIntoVehicle(car, -1);
GameFiber.Sleep(2000);
preplacedenger.PlayAmbientSpeech("GENERIC_THANKS", true);
preplacedenger.Dismiss();
car.Dismiss();
carblip.Delete();
businesscarblip.Delete();
GameFiber.Sleep(9000);
Game.DisplayNotification("mphud", "mp_player_ready", "~h~Mors Mutual Insurance", "~b~Vehicle Pickup Status Update", "Thank you for letting us collect our client's ~h~" + modelName + "!");
}
catch (Exception e)
{
Game.LogTrivial(e.ToString());
Game.LogTrivial("Insurance company Crashed");
Game.DisplayNotification("The insurance pickup service was interrupted.");
if (businesscarblip.Exists()) { businesscarblip.Delete(); }
if (carblip.Exists()) { carblip.Delete(); }
if (driver.Exists()) { driver.Delete(); }
if (car.Exists()) { car.Delete(); }
if (businessCar.Exists()) { businessCar.Delete(); }
if (preplacedenger.Exists()) { preplacedenger.Delete(); }
}
});
}
19
View Source File : PetrolTheft.cs
License : GNU General Public License v3.0
Project Creator : Albo1125
License : GNU General Public License v3.0
Project Creator : Albo1125
public override bool OnCalloutAccepted()
{
Shopkeeper = new Ped("mp_m_shopkeep_01", SpawnPoint, 0.0f);
Shopkeeper.IsPersistent = true;
Shopkeeper.BlockPermanentEvents = true;
Vector3 CarSpawn = Game.LocalPlayer.Character.Position.Around(250f).GetClosestMajorVehicleNode();
while (Vector3.Distance(CarSpawn, Game.LocalPlayer.Character.Position) < 170f)
{
GameFiber.Yield();
CarSpawn = Game.LocalPlayer.Character.Position.Around(250f).GetClosestMajorVehicleNode();
}
SuspectCar = new Vehicle(GroundVehiclesToSelectFrom[replacedortedCalloutsHandler.rnd.Next(GroundVehiclesToSelectFrom.Length)], CarSpawn);
SuspectCar.RandomiseLicencePlate();
SuspectCar.IsPersistent = true;
//GameFiber.Yield();
Suspect = SuspectCar.CreateRandomDriver();
Suspect.IsPersistent = true;
Suspect.BlockPermanentEvents = true;
ShopkeeperBlip = Shopkeeper.AttachBlip();
ShopkeeperBlip.IsRouteEnabled = true;
CarModelName = SuspectCar.Model.Name.ToLower();
CarModelName = char.ToUpper(CarModelName[0]) + CarModelName.Substring(1);
try {
CarColor = SuspectCar.GetColors().PrimaryColorName + "~s~-coloured";
}
catch(Exception e)
{
CarColor = "weirdly-coloured";
}
if (!CalloutRunning) { CalloutHandler(); }
return base.OnCalloutAccepted();
}
19
View Source File : TrafficStopAssist.cs
License : GNU General Public License v3.0
Project Creator : Albo1125
License : GNU General Public License v3.0
Project Creator : Albo1125
public static void SetCustomPulloverLocation()
{
TrafficPolicerHandler.isSomeoneFollowing = true;
GameFiber.StartNew(delegate
{
try
{
if (!Functions.IsPlayerPerformingPullover())
{
TrafficPolicerHandler.isSomeoneFollowing = false;
return;
}
if (!Game.LocalPlayer.Character.IsInAnyVehicle(false))
{
TrafficPolicerHandler.isSomeoneFollowing = false;
return;
}
Vehicle playerCar = Game.LocalPlayer.Character.CurrentVehicle;
Vehicle stoppedCar = (Vehicle)World.GetClosestEnreplacedy(playerCar.GetOffsetPosition(Vector3.RelativeFront * 8f), 8f, (GetEnreplacediesFlags.ConsiderGroundVehicles | GetEnreplacediesFlags.ConsiderBoats | GetEnreplacediesFlags.ExcludeEmptyVehicles | GetEnreplacediesFlags.ExcludeEmergencyVehicles));
if (stoppedCar == null)
{
Game.DisplayNotification("Unable to detect the pulled over vehicle. Make sure you're behind the vehicle and try again.");
TrafficPolicerHandler.isSomeoneFollowing = false;
return;
}
if (!stoppedCar.IsValid() || (stoppedCar == playerCar))
{
Game.DisplayNotification("Unable to detect the pulled over vehicle. Make sure you're behind the vehicle and try again.");
TrafficPolicerHandler.isSomeoneFollowing = false;
return;
}
if (stoppedCar.Speed > 0.2f && !ExtensionMethods.IsPointOnWater(stoppedCar.Position))
{
Game.DisplayNotification("The vehicle must be stopped before you can do this.");
TrafficPolicerHandler.isSomeoneFollowing = false;
return;
}
string modelName = stoppedCar.Model.Name.ToLower();
if (numbers.Contains<string>(modelName.Last().ToString()))
{
modelName = modelName.Substring(0, modelName.Length - 1);
}
modelName = char.ToUpper(modelName[0]) + modelName.Substring(1);
Ped pulledDriver = stoppedCar.Driver;
if (!pulledDriver.IsPersistent || Functions.GetPulloverSuspect(Functions.GetCurrentPullover()) != pulledDriver)
{
Game.DisplayNotification("Unable to detect the pulled over vehicle. Make sure you're in front of the vehicle and try again.");
TrafficPolicerHandler.isSomeoneFollowing = false;
return;
}
Blip blip = pulledDriver.AttachBlip();
blip.Flash(500, -1);
blip.Color = System.Drawing.Color.Aqua;
playerCar.BlipSiren(true);
Vector3 CheckPointPosition = Game.LocalPlayer.Character.GetOffsetPosition(new Vector3(0f, 8f, -1f));
CheckPoint = NativeFunction.Natives.CREATE_CHECKPOINT<int>(46, CheckPointPosition.X, CheckPointPosition.Y, CheckPointPosition.Z, CheckPointPosition.X, CheckPointPosition.Y, CheckPointPosition.Z, 3.5f, 255, 0, 0, 255, 0); ;
float xOffset = 0;
float yOffset = 0;
float zOffset = 0;
bool SuccessfulSet = false;
while (true)
{
GameFiber.Wait(70);
Game.DisplaySubreplacedle("Set your desired pullover location. Hold ~b~Enter ~s~when done.", 100);
CheckPointPosition = Game.LocalPlayer.Character.GetOffsetPosition(new Vector3((float)xOffset + 0.5f, (float)(yOffset + 8), (float)(-1 + zOffset)));
if (!TrafficPolicerHandler.isSomeoneFollowing)
{
break;
}
if (!Functions.IsPlayerPerformingPullover())
{
Game.DisplayNotification("You cancelled the ~b~Traffic Stop.");
break;
}
if (!Game.LocalPlayer.Character.IsInVehicle(playerCar, false))
{
break;
}
if (Albo1125.Common.CommonLibrary.ExtensionMethods.IsKeyDownRightNowComputerCheck(SpeedChecker.PositionResetKey))
{
xOffset = 0;
yOffset = 0;
zOffset = 0;
}
if (Albo1125.Common.CommonLibrary.ExtensionMethods.IsKeyDownRightNowComputerCheck(SpeedChecker.PositionForwardKey))
{
yOffset++;
}
if (Albo1125.Common.CommonLibrary.ExtensionMethods.IsKeyDownRightNowComputerCheck(SpeedChecker.PositionBackwardKey))
{
yOffset--;
}
if (Albo1125.Common.CommonLibrary.ExtensionMethods.IsKeyDownRightNowComputerCheck(SpeedChecker.PositionRightKey))
{
xOffset++;
}
if (Albo1125.Common.CommonLibrary.ExtensionMethods.IsKeyDownRightNowComputerCheck(SpeedChecker.PositionLeftKey))
{
xOffset--;
}
if (Albo1125.Common.CommonLibrary.ExtensionMethods.IsKeyDownRightNowComputerCheck(SpeedChecker.PositionUpKey))
{
zOffset++;
}
if (Albo1125.Common.CommonLibrary.ExtensionMethods.IsKeyDownRightNowComputerCheck(SpeedChecker.PositionDownKey))
{
zOffset--;
}
if (Albo1125.Common.CommonLibrary.ExtensionMethods.IsKeyDownRightNowComputerCheck(Keys.Enter))
{
SuccessfulSet = true;
break;
}
NativeFunction.Natives.DELETE_CHECKPOINT(CheckPoint);
CheckPoint = NativeFunction.Natives.CREATE_CHECKPOINT<int>(46, CheckPointPosition.X, CheckPointPosition.Y, CheckPointPosition.Z, CheckPointPosition.X, CheckPointPosition.Y, CheckPointPosition.Z, 3f, 255, 0, 0, 255, 0);
NativeFunction.Natives.SET_CHECKPOINT_CYLINDER_HEIGHT(CheckPoint, 2f, 2f, 2f);
}
NativeFunction.Natives.DELETE_CHECKPOINT(CheckPoint);
if (SuccessfulSet)
{
try
{
Game.LocalPlayer.Character.Tasks.PlayAnimation("[email protected]@ig_1", "wave_c", 1f, AnimationFlags.SecondaryTask | AnimationFlags.UpperBodyOnly);
}
catch { }
while (true)
{
GameFiber.Yield();
if (Vector3.Distance(pulledDriver.Position, Game.LocalPlayer.Character.Position) > 25f) { Game.DisplaySubreplacedle("~h~~r~Stay close to the vehicle.", 700); }
if (!Functions.IsPlayerPerformingPullover())
{
Game.DisplayNotification("You cancelled the ~b~Traffic Stop.");
break;
}
if (!Game.LocalPlayer.Character.IsInVehicle(playerCar, false))
{
break;
}
if (!TrafficPolicerHandler.isSomeoneFollowing) { break; }
Rage.Task drivetask = pulledDriver.Tasks.DriveToPosition(CheckPointPosition, 12f, VehicleDrivingFlags.DriveAroundVehicles | VehicleDrivingFlags.DriveAroundObjects | VehicleDrivingFlags.AllowMedianCrossing | VehicleDrivingFlags.YieldToCrossingPedestrians);
GameFiber.Wait(700);
if (!drivetask.IsActive) { break; }
if (Vector3.Distance(pulledDriver.Position, CheckPointPosition) < 1.5f) { break; }
}
if (TrafficPolicerHandler.IsLSPDFRPlusRunning)
{
API.LSPDFRPlusFunctions.AddCountToStatistic(Main.PluginName, "Custom pullover locations set");
}
Game.LogTrivial("Done custom pullover location");
if (stoppedCar.Exists())
{
if (pulledDriver.Exists())
{
pulledDriver.Tasks.PerformDrivingManeuver(VehicleManeuver.Wait);
}
}
if (blip.Exists()) { blip.Delete(); }
}
}
catch (Exception e)
{
NativeFunction.Natives.DELETE_CHECKPOINT(CheckPoint);
if (blip.Exists()) { blip.Delete(); }
Game.LogTrivial(e.ToString());
Game.LogTrivial("CustomPulloverLocationError handled.");
}
finally
{
TrafficPolicerHandler.isSomeoneFollowing = false;
}
});
}
19
View Source File : IllegalImmigrantsInTruck.cs
License : GNU General Public License v3.0
Project Creator : Albo1125
License : GNU General Public License v3.0
Project Creator : Albo1125
public override bool OnCalloutAccepted()
{
SuspectCar = new Vehicle(TruckModels[replacedortedCalloutsHandler.rnd.Next(TruckModels.Length)], SpawnPoint, SpawnHeading);
SuspectCar.RandomiseLicencePlate();
SuspectCar.MakePersistent();
CarModelName = SuspectCar.Model.Name.ToLower();
CarModelName = char.ToUpper(CarModelName[0]) + CarModelName.Substring(1);
try
{
//CarColor = SuspectCar.GetColors().PrimaryColorName + "~s~-coloured";
}
catch (Exception e)
{
//CarColor = "weirdly-coloured";
}
Suspect = SuspectCar.CreateRandomDriver();
Suspect.MakeMissionPed();
int NumberOfImmigrants = replacedortedCalloutsHandler.rnd.Next(1, 5);
for (int i=0;i<NumberOfImmigrants;i++)
{
Game.LogTrivial("Spawning immigrant");
Ped immigrant = new Ped(ImmigrantModels[replacedortedCalloutsHandler.rnd.Next(ImmigrantModels.Length)], Vector3.Zero, 0f);
immigrant.MakeMissionPed();
IllegalImmigrants.Add(immigrant);
immigrant.WarpIntoVehicle(SuspectCar, i + 1);
Persona immigrantpersona = Functions.GetPersonaForPed(immigrant);
immigrantpersona.Wanted = true;
Functions.SetPersonaForPed(immigrant, immigrantpersona);
}
Game.DisplayNotification("3dtextures", "mpgroundlogo_cops", "Illegal Immigrants in Truck", "Dispatch to ~b~" + replacedortedCalloutsHandler.DivisionUnitBeat, "Citizens reporting ~r~illegal immigrants in a truck. ~b~Investigate the truck.");
CalloutHandler();
return base.OnCalloutAccepted();
}
19
View Source File : CourtSystem.cs
License : GNU General Public License v3.0
Project Creator : Albo1125
License : GNU General Public License v3.0
Project Creator : Albo1125
private void PublishCourtResults()
{
if (!CourtSystem.PublishedCourtCases.Contains(this))
{
if (CourtSystem.PendingCourtCases.Contains(this))
{
Menus.PendingResultsList.Items.RemoveAt(CourtSystem.PendingCourtCases.IndexOf(this));
if (Menus.PendingResultsList.Items.Count == 0) { Menus.PendingResultsList.Items.Add(new TabItem(" ")); PendingResultsMenuCleared = false; }
Menus.PendingResultsList.Index = 0;
CourtSystem.PendingCourtCases.Remove(this);
}
CourtSystem.PublishedCourtCases.Insert(0, this);
string CrimeString = char.ToUpper(Crime[0]) + Crime.ToLower().Substring(1);
if (GuiltyChance < 0) { GuiltyChance = 0; } else if (GuiltyChance > 100) { GuiltyChance = 100; }
if (LSPDFRPlusHandler.rnd.Next(100) >= GuiltyChance && !ResultsPublishedNotificationShown)
{
CourtVerdict = "Found not guilty and cleared of all charges.";
}
TabTexreplacedem item = new TabTexreplacedem(MenuLabel(false), "Court Result", MenuLabel(false) + "~s~. ~r~" + CrimeString + (Crime[Crime.Length - 1] == '.' ? "" : "~s~.")
+ "~s~~n~ " + CourtVerdict + (CourtVerdict[CourtVerdict.Length - 1] == '.' ? "" : "~s~.")
+ "~s~~n~ Offence took place on ~b~" + CrimeDate.ToShortDateString() + "~s~ at ~b~" + CrimeDate.ToShortTimeString()
+ "~s~.~n~ Hearing was on ~b~" + ResultsPublishTime.ToShortDateString() + "~s~ at ~b~" + ResultsPublishTime.ToShortTimeString() + "."
+ "~n~~n~~y~Select this case and press ~b~Delete ~y~to dismiss it.");
Menus.PublishedResultsList.Items.Insert(0, item);
Menus.PublishedResultsList.RefreshIndex();
if (!ResultsMenuCleared)
{
Game.LogTrivial("Emtpy items, clearing menu at index 1.");
Menus.PublishedResultsList.Items.RemoveAt(1);
ResultsMenuCleared = true;
}
ResultsPublished = true;
if (!ResultsPublishedNotificationShown)
{
if (CourtSystem.LoadingXMLFileCases)
{
GameFiber.StartNew(delegate
{
GameFiber.Wait(25000);
if (CourtSystem.OpenCourtMenuKey != Keys.None)
{
Game.DisplayNotification("3dtextures", "mpgroundlogo_cops", "~b~San Andreas Court", "~r~" + SuspectName, "A court case you're following has been heard. Press ~b~" + Albo1125.Common.CommonLibrary.ExtensionMethods.GetKeyString(CourtSystem.OpenCourtMenuKey, CourtSystem.OpenCourtMenuModifierKey) + ".");
}
});
}
else
{
if (CourtSystem.OpenCourtMenuKey != Keys.None)
{
Game.DisplayNotification("3dtextures", "mpgroundlogo_cops", "~b~San Andreas Court", "~r~" + SuspectName, "A court case you're following has been heard. Press ~b~" + Albo1125.Common.CommonLibrary.ExtensionMethods.GetKeyString(CourtSystem.OpenCourtMenuKey, CourtSystem.OpenCourtMenuModifierKey) + ".");
}
}
ResultsPublishedNotificationShown = true;
CourtSystem.OverwriteCourtCase(this);
}
}
}
19
View Source File : SpeedChecker.cs
License : GNU General Public License v3.0
Project Creator : Albo1125
License : GNU General Public License v3.0
Project Creator : Albo1125
public static void Main()
{
GameFiber.StartNew(delegate
{
Game.RawFrameRender += DrawVehicleInfo;
LowPriority();
Game.LogTrivial("Traffic Policer Speed Checker started.");
try
{
while (true)
{
GameFiber.Yield();
if (CurrentSpeedCheckerState == SpeedCheckerStates.Speedgun)
{
if (Game.LocalPlayer.Character.Inventory.EquippedWeapon == null || Game.LocalPlayer.Character.Inventory.EquippedWeapon.replacedet != speedgunWeapon
|| (Game.LocalPlayer.Character.CurrentVehicle.Exists() && Game.LocalPlayer.Character.CurrentVehicle.Speed >= 3f))
{
CurrentSpeedCheckerState = SpeedCheckerStates.Off;
continue;
}
Game.DisableControlAction(0, GameControl.Attack, true);
Game.DisableControlAction(0, GameControl.Attack2, true);
Game.DisableControlAction(0, GameControl.MeleeAttack1, true);
Game.DisableControlAction(0, GameControl.MeleeAttack2, true);
Game.DisableControlAction(0, GameControl.VehicleAttack, true);
//Game.DisableControlAction(0, GameControl.VehicleAttack2, true);
if (NativeFunction.Natives.IS_DISABLED_CONTROL_JUST_PRESSED<bool>(0, 24))
{
Vehicle veh = null;
try
{
unsafe
{
uint enreplacedyHandle;
NativeFunction.Natives.x2975C866E6713290(Game.LocalPlayer, new IntPtr(&enreplacedyHandle)); // Stores the enreplacedy the player is aiming at in the uint provided in the second parameter.
Enreplacedy ent = World.GetEnreplacedyByHandle<Rage.Enreplacedy>(enreplacedyHandle);
if (ent is Ped)
{
veh = ((Ped)ent).CurrentVehicle;
}
else if (ent is Vehicle)
{
veh = (Vehicle)ent;
}
}
}
catch (Exception e) { }
if (veh.Exists())
{
TargetModel = veh.Model.Name;
TargetModel = char.ToUpper(TargetModel[0]) + TargetModel.Substring(1).ToLower();
if (SpeedUnit == "MPH")
{
TargetSpeed = (int)Math.Round(MathHelper.ConvertMetersPerSecondToMilesPerHour(veh.Speed));
}
else
{
TargetSpeed = MathHelper.ConvertMetersPerSecondToKilometersPerHourRounded(veh.Speed);
}
if (TargetSpeed >= SpeedToColourAt)
{
SpeedColour = Color.Red;
if (PlayFlagBlip)
{
if (!VehiclesBlipPlayedFor.Contains(veh))
{
VehiclesBlipPlayedFor.Add(veh);
FlagBlipPlayer.Play();
Game.DisplayNotification("~s~Model: ~b~" + TargetModel + "~n~~s~Speed: " + (SpeedColour == Color.Red ? "~r~" : "") + TargetSpeed + " " + SpeedUnit);
}
}
}
else
{
SpeedColour = Color.White;
}
}
}
}
if (Game.LocalPlayer.Character.IsInAnyVehicle(false) && (Albo1125.Common.CommonLibrary.ExtensionMethods.IsKeyDownRightNowComputerCheck(ToggleSpeedCheckerModifierKey) || ToggleSpeedCheckerModifierKey == Keys.None))
{
if (Albo1125.Common.CommonLibrary.ExtensionMethods.IsKeyDownComputerCheck(ToggleSpeedCheckerKey))
{
if (CurrentSpeedCheckerState != SpeedCheckerStates.Off && CurrentSpeedCheckerState != SpeedCheckerStates.Speedgun)
{
GameFiber.Wait(200);
if (Albo1125.Common.CommonLibrary.ExtensionMethods.IsKeyDownRightNowComputerCheck(ToggleSpeedCheckerKey))
{
CurrentSpeedCheckerState = SpeedCheckerStates.Off;
NativeFunction.Natives.DELETE_CHECKPOINT(CheckPoint);
ResetAverageSpeedCheck();
Game.HideHelp();
}
else
{
Game.DisplaySubreplacedle("~h~Hold Speed Checker toggle to disable.", 3000);
if (CurrentSpeedCheckerState == SpeedCheckerStates.Average)
{
ResetAverageSpeedCheck();
CurrentSpeedCheckerState = SpeedCheckerStates.FixedPoint;
DisplayMaxSpeedMessage();
}
else if (CurrentSpeedCheckerState == SpeedCheckerStates.FixedPoint)
{
NativeFunction.Natives.DELETE_CHECKPOINT(CheckPoint);
CurrentSpeedCheckerState = SpeedCheckerStates.Average;
DisplayAverageSpeedCheckInstructions();
}
}
}
else if (Game.LocalPlayer.Character.IsInAnyVehicle(false))
{
if (CurrentSpeedCheckerState == SpeedCheckerStates.Speedgun)
{
Game.DisplaySubreplacedle("Please unequip your speedgun first.");
}
else
{
if (Game.LocalPlayer.Character.CurrentVehicle.Speed > 6f)
{
CurrentSpeedCheckerState = SpeedCheckerStates.Average;
DisplayAverageSpeedCheckInstructions();
}
else
{
CurrentSpeedCheckerState = SpeedCheckerStates.FixedPoint;
DisplayMaxSpeedMessage();
}
}
}
CheckPointPosition = Game.LocalPlayer.Character.GetOffsetPosition(new Vector3(0f, 8f, -1f));
//xOffset = 0;
//yOffset = 0;
//zOffset = 0;
}
}
if (CurrentSpeedCheckerState != SpeedCheckerStates.Off && CurrentSpeedCheckerState != SpeedCheckerStates.Speedgun)
{
if (Albo1125.Common.CommonLibrary.ExtensionMethods.IsKeyDownComputerCheck(SecondaryDisableKey) || !Game.LocalPlayer.Character.IsInAnyVehicle(false))
{
CurrentSpeedCheckerState = SpeedCheckerStates.Off;
NativeFunction.Natives.DELETE_CHECKPOINT(CheckPoint);
CheckPointPosition = Game.LocalPlayer.Character.GetOffsetPosition(new Vector3(0f, 8f, -1f));
ResetAverageSpeedCheck();
Game.HideHelp();
}
//xOffset = 0;
//yOffset = 0;
//zOffset = 0;
}
if (CurrentSpeedCheckerState == SpeedCheckerStates.FixedPoint && Game.LocalPlayer.Character.IsInAnyVehicle(false))
{
CheckPointPosition = Game.LocalPlayer.Character.GetOffsetPosition(new Vector3((float)xOffset + 0.5f, (float)(yOffset + 8), (float)(-1 + zOffset)));
if (Albo1125.Common.CommonLibrary.ExtensionMethods.IsKeyDownComputerCheck(PositionResetKey))
{
xOffset = 0;
yOffset = 0;
zOffset = 0;
}
if (Albo1125.Common.CommonLibrary.ExtensionMethods.IsKeyDownComputerCheck(PositionForwardKey))
{
yOffset++;
}
if (Albo1125.Common.CommonLibrary.ExtensionMethods.IsKeyDownComputerCheck(PositionBackwardKey))
{
yOffset--;
}
if (Albo1125.Common.CommonLibrary.ExtensionMethods.IsKeyDownComputerCheck(PositionRightKey))
{
xOffset++;
}
if (Albo1125.Common.CommonLibrary.ExtensionMethods.IsKeyDownComputerCheck(PositionLeftKey))
{
xOffset--;
}
if (Albo1125.Common.CommonLibrary.ExtensionMethods.IsKeyDownComputerCheck(PositionUpKey))
{
zOffset++;
}
if (Albo1125.Common.CommonLibrary.ExtensionMethods.IsKeyDownComputerCheck(PositionDownKey))
{
zOffset--;
}
NativeFunction.Natives.DELETE_CHECKPOINT(CheckPoint);
CheckPoint = NativeFunction.Natives.CREATE_CHECKPOINT<int>(46, CheckPointPosition.X, CheckPointPosition.Y, CheckPointPosition.Z, CheckPointPosition.X, CheckPointPosition.Y, CheckPointPosition.Z, 3.5f, 255, 0, 0, 255, 0);
NativeFunction.Natives.SET_CHECKPOINT_CYLINDER_HEIGHT(CheckPoint, 2f, 2f, 2f);
}
if ((CurrentSpeedCheckerState == SpeedCheckerStates.FixedPoint && Game.LocalPlayer.Character.IsInAnyVehicle(false)) || CurrentSpeedCheckerState == SpeedCheckerStates.Speedgun)
{
if (Albo1125.Common.CommonLibrary.ExtensionMethods.IsKeyDownComputerCheck(MaxSpeedUpKey))
{
SpeedToColourAt += 5;
DisplayMaxSpeedMessage();
}
if (Albo1125.Common.CommonLibrary.ExtensionMethods.IsKeyDownComputerCheck(MaxSpeedDownKey))
{
SpeedToColourAt -= 5;
if (SpeedToColourAt < 0) { SpeedToColourAt = 0; }
DisplayMaxSpeedMessage();
}
}
else if (CurrentSpeedCheckerState == SpeedCheckerStates.Average && Game.LocalPlayer.Character.IsInAnyVehicle(false))
{
if (Albo1125.Common.CommonLibrary.ExtensionMethods.IsKeyDownComputerCheck(StartStopAverageSpeedCheckKey))
{
if (MeasuringAverageSpeed)
{
StopAverageSpeedCheck();
}
else if (!MeasuringAverageSpeed && AverageSpeedCheckSecondsPreplaceded == 0f)
{
StartAverageSpeedCheck();
}
else
{
Game.DisplayHelp("Reset the average speed check first using ~b~" + TrafficPolicerHandler.kc.ConvertToString(ResetAverageSpeedCheckKey));
}
}
if (Albo1125.Common.CommonLibrary.ExtensionMethods.IsKeyDownComputerCheck(ResetAverageSpeedCheckKey))
{
if (!MeasuringAverageSpeed)
{
ResetAverageSpeedCheck();
}
else
{
Game.DisplayHelp("Stop current average speed check first using ~b~" + TrafficPolicerHandler.kc.ConvertToString(StartStopAverageSpeedCheckKey));
}
}
}
}
}
catch (Exception e) { NativeFunction.Natives.DELETE_CHECKPOINT(CheckPoint); throw; }
});
}
19
View Source File : TrafficStopAssist.cs
License : GNU General Public License v3.0
Project Creator : Albo1125
License : GNU General Public License v3.0
Project Creator : Albo1125
public static void mimicMe()
{
TrafficPolicerHandler.isSomeoneFollowing = true;
GameFiber.StartNew(delegate
{
try
{
//Safety checks
if (!Functions.IsPlayerPerformingPullover())
{
TrafficPolicerHandler.isSomeoneFollowing = false;
return;
}
Game.LogTrivial("Mimicking");
if (!Game.LocalPlayer.Character.IsInAnyVehicle(false))
{
TrafficPolicerHandler.isSomeoneFollowing = false;
return;
}
Vehicle playerCar = Game.LocalPlayer.Character.CurrentVehicle;
Vehicle stoppedCar = (Vehicle)World.GetClosestEnreplacedy(playerCar.GetOffsetPosition(Vector3.RelativeFront * 8f), 8f, (GetEnreplacediesFlags.ConsiderGroundVehicles | GetEnreplacediesFlags.ConsiderBoats | GetEnreplacediesFlags.ExcludeEmptyVehicles | GetEnreplacediesFlags.ExcludeEmergencyVehicles));
if (stoppedCar == null)
{
Game.DisplayNotification("Unable to detect the pulled over vehicle. Make sure you're behind the vehicle and try again.");
TrafficPolicerHandler.isSomeoneFollowing = false;
return;
}
if (!stoppedCar.IsValid() || (stoppedCar == playerCar))
{
Game.DisplayNotification("Unable to detect the pulled over vehicle. Make sure you're behind the vehicle and try again.");
TrafficPolicerHandler.isSomeoneFollowing = false;
return;
}
if (stoppedCar.Speed > 0.2f && !ExtensionMethods.IsPointOnWater(stoppedCar.Position))
{
Game.DisplayNotification("The vehicle must be stopped before they can mimic you.");
TrafficPolicerHandler.isSomeoneFollowing = false;
return;
}
string modelName = stoppedCar.Model.Name.ToLower();
if (numbers.Contains<string>(modelName.Last().ToString()))
{
modelName = modelName.Substring(0, modelName.Length - 1);
}
modelName = char.ToUpper(modelName[0]) + modelName.Substring(1);
Ped pulledDriver = stoppedCar.Driver;
if (!pulledDriver.IsPersistent || Functions.GetPulloverSuspect(Functions.GetCurrentPullover()) != pulledDriver)
{
Game.DisplayNotification("Unable to detect the pulled over vehicle. Make sure you're in front of the vehicle and try again.");
TrafficPolicerHandler.isSomeoneFollowing = false;
return;
}
//After checking everything
Blip blip = pulledDriver.AttachBlip();
blip.Flash(500, -1);
blip.Color = System.Drawing.Color.Aqua;
playerCar.BlipSiren(true);
Game.DisplayNotification("The blipped ~r~" + modelName + "~s~ is now mimicking you.");
Game.DisplayNotification("Press ~b~" + Albo1125.Common.CommonLibrary.ExtensionMethods.GetKeyString(TrafficPolicerHandler.trafficStopMimicKey, TrafficPolicerHandler.trafficStopMimicModifierKey) + " ~s~to stop the ~r~" + modelName + ".");
try
{
Game.LocalPlayer.Character.Tasks.PlayAnimation("[email protected]@ig_1", "wave_c", 1f, AnimationFlags.SecondaryTask | AnimationFlags.UpperBodyOnly);
}
catch { }
GameFiber.Sleep(100);
float speed = 10f;
//Game.LogTrivial("Vehicle Length: " + stoppedCar.Length.ToString());
bool CanBoost = true;
int CheckPoint = 0;
if (TrafficPolicerHandler.IsLSPDFRPlusRunning)
{
API.LSPDFRPlusFunctions.AddCountToStatistic(Main.PluginName, "Vehicles Mimicked");
}
//Driving loop
while (true)
{
float modifier = stoppedCar.Length * 3.95f;
if (modifier < 20f)
{
modifier = 20f;
}
if (modifier > 34f)
{
modifier = 34f;
}
//NativeFunction.Natives.DELETE_CHECKPOINT(CheckPoint);
//CheckPoint = NativeFunction.Natives.CREATE_CHECKPOINT<int>(46, playerCar.GetOffsetPosition(Vector3.RelativeFront * modifier).X, playerCar.GetOffsetPosition(Vector3.RelativeFront * modifier).Y, playerCar.GetOffsetPosition(Vector3.RelativeFront * modifier).Z, playerCar.GetOffsetPosition(Vector3.RelativeFront * modifier).X, playerCar.GetOffsetPosition(Vector3.RelativeFront * modifier).Y, playerCar.GetOffsetPosition(Vector3.RelativeFront * modifier).Z, 2f, 255, 0, 0, 255, 0);
//NativeFunction.Natives.SET_CHECKPOINT_CYLINDER_HEIGHT(CheckPoint, 2f, 2f, 2f);
if (Vector3.Distance(pulledDriver.GetOffsetPosition(Vector3.RelativeFront * 3f), playerCar.GetOffsetPosition(Vector3.RelativeFront * modifier)) < Vector3.Distance(pulledDriver.GetOffsetPosition(Vector3.RelativeBack * 1f), playerCar.GetOffsetPosition(Vector3.RelativeFront * modifier)))
{
pulledDriver.Tasks.DriveToPosition(playerCar.GetOffsetPosition(Vector3.RelativeFront * modifier), speed, VehicleDrivingFlags.IgnorePathFinding);
//if (speed - pulledDriver.Speed > 3f && playerCar.Speed > 5f && CanBoost)
//{
// NativeFunction.Natives.SET_VEHICLE_FORWARD_SPEED(stoppedCar, speed);
// CanBoost = false;
//}
//if (playerCar.Speed < 0.2f) { CanBoost = true; }
}
else
{
pulledDriver.Tasks.DriveToPosition(playerCar.GetOffsetPosition(Vector3.RelativeFront *modifier), speed, VehicleDrivingFlags.Reverse);
}
GameFiber.Sleep(60);
if (!TrafficPolicerHandler.isSomeoneFollowing)
{
break;
}
if (!Functions.IsPlayerPerformingPullover())
{
Game.DisplayNotification("You cancelled the ~b~Traffic Stop.");
break;
}
if (!Game.LocalPlayer.Character.IsInVehicle(playerCar, false))
{
break;
}
if (Vector3.Distance(playerCar.Position, stoppedCar.Position) > 45f)
{
stoppedCar.Position = playerCar.GetOffsetPosition(Vector3.RelativeFront * 10f);
stoppedCar.Heading = playerCar.Heading;
blip.Delete();
blip = pulledDriver.AttachBlip();
blip.Flash(500, -1);
blip.Color = System.Drawing.Color.Aqua;
}
speed = Game.LocalPlayer.Character.CurrentVehicle.Speed + 4f;
if (speed < 10f) { speed = 10f; }
else if (speed > 20f)
{
speed = 20f;
}
}
Game.DisplayNotification("The ~r~" + modelName + "~s~ is no longer mimicking you.");
Game.LogTrivial("Done mimicking");
if (stoppedCar.Exists())
{
//NativeFunction.Natives.SET_VEHICLE_FORWARD_SPEED(stoppedCar, 2f);
if (pulledDriver.Exists())
{
pulledDriver.Tasks.PerformDrivingManeuver(VehicleManeuver.Wait);
}
}
//NativeFunction.Natives.DELETE_CHECKPOINT(CheckPoint);
if (blip.Exists()) { blip.Delete(); }
}
catch (Exception e)
{
if (blip.Exists()) { blip.Delete(); }
Game.LogTrivial(e.ToString());
Game.LogTrivial("Error handled.");
}
finally
{
TrafficPolicerHandler.isSomeoneFollowing = false;
}
});
}
19
View Source File : CourtSystem.cs
License : GNU General Public License v3.0
Project Creator : Albo1125
License : GNU General Public License v3.0
Project Creator : Albo1125
private void AddToPendingCases()
{
if (!CourtSystem.PendingCourtCases.Contains(this))
{
if (CourtSystem.PublishedCourtCases.Contains(this))
{
Menus.PublishedResultsList.Items.RemoveAt(CourtSystem.PublishedCourtCases.IndexOf(this));
if (Menus.PublishedResultsList.Items.Count == 0) { Menus.PublishedResultsList.Items.Add(new TabItem(" ")); ResultsMenuCleared = false; }
Menus.PublishedResultsList.Index = 0;
CourtSystem.PublishedCourtCases.Remove(this);
}
CourtSystem.PendingCourtCases.Insert(0, this);
string CrimeString = char.ToUpper(Crime[0]) + Crime.ToLower().Substring(1);
TabTexreplacedem item = new TabTexreplacedem(MenuLabel(false), "Court Date Pending", MenuLabel(false) + ". ~n~Hearing is for: ~r~" + CrimeString + ".~s~~n~ Offence took place on ~b~"
+ CrimeDate.ToShortDateString() + "~s~ at ~b~" + CrimeDate.ToShortTimeString() + "~s~~n~ Hearing date: ~y~" + ResultsPublishTime.ToShortDateString() + " " + ResultsPublishTime.ToShortTimeString()
+ "~n~~n~~y~Select this case and press ~b~Insert ~s~to make the hearing take place immediately, or ~b~Delete ~y~to dismiss it.");
Menus.PendingResultsList.Items.Insert(0, item);
Menus.PendingResultsList.RefreshIndex();
if (!PendingResultsMenuCleared)
{
Game.LogTrivial("Emtpy items, clearing menu at index 1.");
Menus.PendingResultsList.Items.RemoveAt(1);
PendingResultsMenuCleared = true;
}
if (!CourtSystem.LoadingXMLFileCases)
{
if (CourtSystem.OpenCourtMenuKey != Keys.None)
{
Game.DisplayNotification("3dtextures", "mpgroundlogo_cops", "~b~San Andreas Court", "~r~" + SuspectName, "You're now following a new pending court case. Press ~b~" + Albo1125.Common.CommonLibrary.ExtensionMethods.GetKeyString(CourtSystem.OpenCourtMenuKey, CourtSystem.OpenCourtMenuModifierKey) + ".");
}
}
ResultsPublished = false;
}
}
19
View Source File : SpeedChecker.cs
License : GNU General Public License v3.0
Project Creator : Albo1125
License : GNU General Public License v3.0
Project Creator : Albo1125
private static void LowPriority()
{
GameFiber.StartNew(delegate
{
while (true)
{
GameFiber.Wait(100);
foreach (Ped flaggeddriver in FlaggedDrivers.ToArray())
{
if (flaggeddriver.Exists())
{
if (flaggeddriver.DistanceTo(Game.LocalPlayer.Character) > 300f)
{
flaggeddriver.IsPersistent = false;
//flaggeddriver.Dismiss();
FlaggedDrivers.Remove(flaggeddriver);
}
else if (Functions.IsPlayerPerformingPullover())
{
if (Functions.GetPulloverSuspect(Functions.GetCurrentPullover()) == flaggeddriver)
{
FlaggedDrivers.Remove(flaggeddriver);
}
}
else if (Functions.GetActivePursuit() != null)
{
if (Functions.GetPursuitPeds(Functions.GetActivePursuit()).Contains(flaggeddriver))
{
FlaggedDrivers.Remove(flaggeddriver);
}
}
}
else
{
FlaggedDrivers.Remove(flaggeddriver);
}
}
if (CurrentSpeedCheckerState != SpeedCheckerStates.Speedgun && Game.LocalPlayer.Character.Inventory.EquippedWeapon != null &&
Game.LocalPlayer.Character.Inventory.EquippedWeapon.replacedet == speedgunWeapon && !Game.LocalPlayer.Character.CurrentVehicle.Exists())
{
CurrentSpeedCheckerState = SpeedCheckerStates.Speedgun;
DisplayMaxSpeedMessage();
}
if (CurrentSpeedCheckerState == SpeedCheckerStates.FixedPoint && Game.LocalPlayer.Character.IsInAnyVehicle(false))
{
Enreplacedy[] WorldVehicles = World.GetEnreplacedies(CheckPointPosition, 7, GetEnreplacediesFlags.ConsiderAllVehicles | GetEnreplacediesFlags.ExcludePlayerVehicle);
foreach (Vehicle veh in WorldVehicles)
{
if (veh.Exists() && veh != Game.LocalPlayer.Character.CurrentVehicle && veh.DistanceTo(CheckPointPosition) <= 6.5f)
{
bool ShowVehicleNotification = false;
TargetModel = veh.Model.Name;
TargetModel = char.ToUpper(TargetModel[0]) + TargetModel.Substring(1).ToLower();
if (SpeedUnit == "MPH")
{
TargetSpeed = (int)Math.Round(MathHelper.ConvertMetersPerSecondToMilesPerHour(veh.Speed));
}
else
{
TargetSpeed = MathHelper.ConvertMetersPerSecondToKilometersPerHourRounded(veh.Speed);
}
if (TargetSpeed >= SpeedToColourAt)
{
SpeedColour = Color.Red;
if (PlayFlagBlip)
{
if (!VehiclesBlipPlayedFor.Contains(veh))
{
VehiclesBlipPlayedFor.Add(veh);
FlagBlipPlayer.Play();
ShowVehicleNotification = true;
}
}
}
else
{
SpeedColour = Color.White;
}
//TargetSpeedLimit = GetSpeedLimit(veh.Position, SpeedUnit);
TargetFlag = "";
TargetLicencePlate = veh.LicensePlate;
FlagsTextColour = Color.White;
if ((TrafficPolicerHandler.rnd.Next(101) <= FlagChance || VehiclesFlagged.Contains(veh)) && !veh.Hreplacediren && !VehiclesNotFlagged.Contains(veh))
{
if (!VehiclesFlagged.Contains(veh))
{
VehiclesFlagged.Add(veh);
}
if (!VehicleDetails.IsVehicleInDetailsDatabase(veh))
{
VehicleDetails.AddVehicleToDetailsDatabase(veh, 25);
}
if (veh.IsStolen || VehicleDetails.GetInsuranceStatusForVehicle(veh) != EVehicleDetailsStatus.Valid)
{
if (veh.IsStolen)
{
TargetFlag = "Stolen";
FlagsTextColour = Color.Red;
}
else if (VehicleDetails.GetInsuranceStatusForVehicle(veh) != EVehicleDetailsStatus.Valid)
{
TargetFlag = "Uninsured";
FlagsTextColour = Color.Red;
}
}
else
{
if (veh.HasDriver && veh.Driver.Exists())
{
if (Functions.GetPersonaForPed(veh.Driver).Wanted)
{
TargetFlag = "Owner Wanted";
FlagsTextColour = Color.Red;
}
else if (Functions.GetPersonaForPed(veh.Driver).ELicenseState == LSPD_First_Response.Engine.Scripting.Enreplacedies.ELicenseState.Suspended)
{
TargetFlag = "Licence Suspended";
FlagsTextColour = Color.Red;
}
else if (Functions.GetPersonaForPed(veh.Driver).ELicenseState == LSPD_First_Response.Engine.Scripting.Enreplacedies.ELicenseState.Expired)
{
TargetFlag = "Licence Expired";
FlagsTextColour = Color.Orange;
}
else if (Functions.GetPersonaForPed(veh.Driver).Birthday.Month == DateTime.Now.Month && Functions.GetPersonaForPed(veh.Driver).Birthday.Day == DateTime.Now.Day)
{
TargetFlag = "Owner's Birthday";
FlagsTextColour = Color.Green;
}
if (TargetFlag != "")
{
if (!FlaggedDrivers.Contains(veh.Driver))
{
if (!veh.Driver.IsPersistent)
{
FlaggedDrivers.Add(veh.Driver);
veh.Driver.IsPersistent = true;
}
}
}
}
}
if (PlayFlagBlip)
{
if (TargetFlag != "")
{
if (!VehiclesBlipPlayedFor.Contains(veh))
{
VehiclesBlipPlayedFor.Add(veh);
FlagBlipPlayer.Play();
ShowVehicleNotification = true;
}
}
}
}
if (TargetFlag == "")
{
VehiclesNotFlagged.Add(veh);
}
if (ShowVehicleNotification)
{
Game.DisplayNotification("Plate: ~b~" + TargetLicencePlate + "~n~~s~Model: ~b~" + TargetModel + "~n~~s~Speed: " + (SpeedColour == Color.Red ? "~r~" : "") + TargetSpeed + " " + SpeedUnit + "~n~~s~Flags: ~r~" + TargetFlag);
}
}
}
}
else if (CurrentSpeedCheckerState == SpeedCheckerStates.Average && Game.LocalPlayer.Character.IsInAnyVehicle(false))
{
if (SpeedUnit == "MPH")
{
AverageSpeedCheckCurrentSpeed = (int)Math.Round(MathHelper.ConvertMetersPerSecondToMilesPerHour(Game.LocalPlayer.Character.CurrentVehicle.Speed));
}
else
{
AverageSpeedCheckCurrentSpeed = MathHelper.ConvertMetersPerSecondToKilometersPerHourRounded(Game.LocalPlayer.Character.CurrentVehicle.Speed);
}
if (MeasuringAverageSpeed)
{
AverageSpeedCheckDistance += Vector3.Distance(LastAverageSpeedCheckReferencePoint, Game.LocalPlayer.Character.CurrentVehicle.Position);
LastAverageSpeedCheckReferencePoint = Game.LocalPlayer.Character.CurrentVehicle.Position;
AverageSpeedCheckSecondsPreplaceded = ((float)AverageSpeedCheckStopwatch.ElapsedMilliseconds) / 1000;
}
}
}
});
}
19
View Source File : TrafficStopAssist.cs
License : GNU General Public License v3.0
Project Creator : Albo1125
License : GNU General Public License v3.0
Project Creator : Albo1125
public static void followMe()
{
TrafficPolicerHandler.isSomeoneFollowing = true;
GameFiber.StartNew(delegate
{
try
{
if (!Functions.IsPlayerPerformingPullover())
{
TrafficPolicerHandler.isSomeoneFollowing = false;
return;
}
Game.LogTrivial("Following");
Ped playerPed = Game.LocalPlayer.Character;
if (!playerPed.IsInAnyVehicle(false))
{
TrafficPolicerHandler.isSomeoneFollowing = false;
return;
}
Vehicle playerCar = playerPed.CurrentVehicle;
Vehicle stoppedCar = (Vehicle)World.GetClosestEnreplacedy(playerCar.GetOffsetPosition(Vector3.RelativeBack * 10f), 10f, (GetEnreplacediesFlags.ConsiderGroundVehicles | GetEnreplacediesFlags.ConsiderBoats | GetEnreplacediesFlags.ExcludeEmptyVehicles | GetEnreplacediesFlags.ExcludeEmergencyVehicles));
if (stoppedCar == null)
{
Game.DisplayNotification("Unable to detect the pulled over vehicle. Make sure you're in front of the vehicle and try again.");
TrafficPolicerHandler.isSomeoneFollowing = false;
return;
}
if (!stoppedCar.IsValid() || (stoppedCar == playerCar))
{
Game.DisplayNotification("Unable to detect the pulled over vehicle. Make sure you're in front of the vehicle and try again.");
TrafficPolicerHandler.isSomeoneFollowing = false;
return;
}
if (stoppedCar.Speed > 0.2f && !ExtensionMethods.IsPointOnWater(stoppedCar.Position))
{
Game.DisplayNotification("The vehicle must be stopped before they can follow you.");
TrafficPolicerHandler.isSomeoneFollowing = false;
return;
}
string modelName = stoppedCar.Model.Name.ToLower();
if (numbers.Contains<string>(modelName.Last().ToString()))
{
modelName = modelName.Substring(0, modelName.Length - 1);
}
modelName = char.ToUpper(modelName[0]) + modelName.Substring(1);
Ped pulledDriver = stoppedCar.Driver;
if (!pulledDriver.IsPersistent || Functions.GetPulloverSuspect(Functions.GetCurrentPullover()) != pulledDriver)
{
Game.DisplayNotification("Unable to detect the pulled over vehicle. Make sure you're in front of the vehicle and try again.");
TrafficPolicerHandler.isSomeoneFollowing = false;
return;
}
Blip blip = pulledDriver.AttachBlip();
blip.Flash(500, -1);
blip.Color = System.Drawing.Color.Aqua;
playerCar.BlipSiren(true);
pulledDriver.Tasks.DriveToPosition(playerCar.GetOffsetPosition(Vector3.RelativeBack * 3f), 7f, VehicleDrivingFlags.FollowTraffic | VehicleDrivingFlags.YieldToCrossingPedestrians);
Game.DisplayNotification("The blipped ~r~" + modelName + "~s~ is now following you.");
Game.DisplayNotification("Press ~b~" + ExtensionMethods.GetKeyString(TrafficPolicerHandler.trafficStopFollowKey, TrafficPolicerHandler.trafficStopFollowModifierKey) + " ~s~to stop the ~r~" + modelName + ".");
try
{
playerPed.Tasks.PlayAnimation("[email protected]@ig_1", "wave_c", 1f, AnimationFlags.SecondaryTask | AnimationFlags.UpperBodyOnly);
}
catch { }
GameFiber.Sleep(100);
float speed = 7f;
while (true)
{
pulledDriver.Tasks.DriveToPosition(playerCar.GetOffsetPosition(Vector3.RelativeBack * 3f), speed, VehicleDrivingFlags.IgnorePathFinding);
GameFiber.Sleep(60);
if (!TrafficPolicerHandler.isSomeoneFollowing)
{
break;
}
if (!Functions.IsPlayerPerformingPullover())
{
Game.DisplayNotification("You cancelled the ~b~Traffic Stop.");
break;
}
if (!playerPed.IsInVehicle(playerCar, false))
{
break;
}
speed = playerCar.Speed;
if (Vector3.Distance(playerCar.Position, stoppedCar.Position) > 45f)
{
stoppedCar.Position = playerCar.GetOffsetPosition(Vector3.RelativeBack * 7f);
stoppedCar.Heading = playerCar.Heading;
blip.Delete();
blip = pulledDriver.AttachBlip();
blip.Flash(500, -1);
blip.Color = System.Drawing.Color.Aqua;
}
else
{
if (speed > 17f) { speed = 17f; }
else if (speed < 6.5f)
{
speed = 6.5f;
}
if (Vector3.Distance(playerCar.Position, stoppedCar.Position) > 21f)
{
speed = 17f;
}
}
}
if (TrafficPolicerHandler.IsLSPDFRPlusRunning)
{
API.LSPDFRPlusFunctions.AddCountToStatistic(Main.PluginName, "Vehicles made to follow you");
}
Game.DisplayNotification("The ~r~" + modelName + "~s~ is no longer following you.");
Game.LogTrivial("Done following");
if (blip.Exists()) { blip.Delete(); }
}
catch (Exception e)
{
if (blip.Exists()) { blip.Delete(); }
Game.LogTrivial(e.ToString());
Game.LogTrivial("Error handled.");
}
finally
{
TrafficPolicerHandler.isSomeoneFollowing = false;
}
});
}
19
View Source File : NPOIExetnsions.cs
License : MIT License
Project Creator : albyho
License : MIT License
Project Creator : albyho
public static int FromNumberSystem26(string s)
{
if (string.IsNullOrEmpty(s)) return 0;
int n = 0;
for (int i = s.Length - 1, j = 1; i >= 0; i--, j *= 26)
{
char c = Char.ToUpper(s[i]);
if (c < 'A' || c > 'Z') return 0;
n += ((int)c - 64) * j;
}
return n;
}
19
View Source File : TextFormatter.cs
License : GNU General Public License v3.0
Project Creator : alexgracianoarj
License : GNU General Public License v3.0
Project Creator : alexgracianoarj
public override string FormatText(string text)
{
if ((new Regex("^[A-Z][a-z]+(?:[A-Z][a-z]+)*$").IsMatch(text)))
return text;
if (String.IsNullOrEmpty(text))
return text;
var result = "";
string[] words = base.FormatText(new LowercaseAndUnderscoreTextFormatter().FormatText(text)).Split('_');
foreach (string word in words)
result += char.ToUpper(word[0]) + word.Substring(1);
return result;
}
19
View Source File : SubstanceSamplerNode.cs
License : MIT License
Project Creator : alexismorin
License : MIT License
Project Creator : alexismorin
private void ConfigPortsFromMaterial( bool invalidateConnections = false, Texture[] newTextures = null )
{
SetAdditonalreplacedleText( ( m_proceduralMaterial != null ) ? string.Format( Constants.PropertyValueLabel, m_proceduralMaterial.name ) : "Value( <None> )" );
Texture[] textures = newTextures != null ? newTextures : ( ( m_proceduralMaterial != null ) ? m_proceduralMaterial.GetGeneratedTextures() : null );
if( textures != null )
{
m_firstOutputConnected = -1;
string nameToRemove = m_proceduralMaterial.name + "_";
m_textureTypes = new ProceduralOutputType[ textures.Length ];
for( int i = 0; i < textures.Length; i++ )
{
ProceduralTexture procTex = textures[ i ] as ProceduralTexture;
m_textureTypes[ i ] = procTex.GetProceduralOutputType();
WirePortDataType portType = ( m_autoNormal && m_textureTypes[ i ] == ProceduralOutputType.Normal ) ? WirePortDataType.FLOAT3 : WirePortDataType.COLOR;
string newName = textures[ i ].name.Replace( nameToRemove, string.Empty );
char firstLetter = Char.ToUpper( newName[ 0 ] );
newName = firstLetter.ToString() + newName.Substring( 1 );
if( i < m_outputPorts.Count )
{
m_outputPorts[ i ].ChangeProperties( newName, portType, false );
if( invalidateConnections )
{
m_outputPorts[ i ].FullDeleteConnections();
}
}
else
{
AddOutputPort( portType, newName );
}
}
if( textures.Length < m_outputPorts.Count )
{
int itemsToRemove = m_outputPorts.Count - textures.Length;
for( int i = 0; i < itemsToRemove; i++ )
{
int idx = m_outputPorts.Count - 1;
if( m_outputPorts[ idx ].IsConnected )
{
m_outputPorts[ idx ].ForceClearConnection();
}
RemoveOutputPort( idx );
}
}
}
else
{
int itemsToRemove = m_outputPorts.Count - 1;
m_outputPorts[ 0 ].ChangeProperties( Constants.EmptyPortValue, WirePortDataType.COLOR, false );
m_outputPorts[ 0 ].ForceClearConnection();
for( int i = 0; i < itemsToRemove; i++ )
{
int idx = m_outputPorts.Count - 1;
if( m_outputPorts[ idx ].IsConnected )
{
m_outputPorts[ idx ].ForceClearConnection();
}
RemoveOutputPort( idx );
}
}
m_sizeIsDirty = true;
m_isDirty = true;
}
19
View Source File : SubstanceSamplerNode.cs
License : GNU General Public License v3.0
Project Creator : alexismorin
License : GNU General Public License v3.0
Project Creator : alexismorin
private void ConfigPortsFromMaterial( bool invalidateConnections = false, Texture[] newTextures = null )
{
//PreviewSizeX = ( m_proceduralMaterial != null ) ? UIUtils.ObjectField.CalcSize( new GUIContent( m_proceduralMaterial.name ) ).x + 15 : 110;
//m_insideSize.x = TexturePreviewSizeX + 5;
SetAdditonalreplacedleText( ( m_proceduralMaterial != null ) ? string.Format( Constants.PropertyValueLabel, m_proceduralMaterial.name ) : "Value( <None> )" );
Texture[] textures = newTextures != null ? newTextures : ( ( m_proceduralMaterial != null ) ? m_proceduralMaterial.GetGeneratedTextures() : null );
if( textures != null )
{
string nameToRemove = m_proceduralMaterial.name + "_";
m_textureTypes = new ProceduralOutputType[ textures.Length ];
for( int i = 0; i < textures.Length; i++ )
{
ProceduralTexture procTex = textures[ i ] as ProceduralTexture;
m_textureTypes[ i ] = procTex.GetProceduralOutputType();
WirePortDataType portType = ( m_autoNormal && m_textureTypes[ i ] == ProceduralOutputType.Normal ) ? WirePortDataType.FLOAT3 : WirePortDataType.COLOR;
string newName = textures[ i ].name.Replace( nameToRemove, string.Empty );
char firstLetter = Char.ToUpper( newName[ 0 ] );
newName = firstLetter.ToString() + newName.Substring( 1 );
if( i < m_outputPorts.Count )
{
m_outputPorts[ i ].ChangeProperties( newName, portType, false );
if( invalidateConnections )
{
m_outputPorts[ i ].FullDeleteConnections();
}
}
else
{
AddOutputPort( portType, newName );
}
}
if( textures.Length < m_outputPorts.Count )
{
int itemsToRemove = m_outputPorts.Count - textures.Length;
for( int i = 0; i < itemsToRemove; i++ )
{
int idx = m_outputPorts.Count - 1;
if( m_outputPorts[ idx ].IsConnected )
{
m_outputPorts[ idx ].ForceClearConnection();
}
RemoveOutputPort( idx );
}
}
}
else
{
int itemsToRemove = m_outputPorts.Count - 1;
m_outputPorts[ 0 ].ChangeProperties( Constants.EmptyPortValue, WirePortDataType.COLOR, false );
m_outputPorts[ 0 ].ForceClearConnection();
for( int i = 0; i < itemsToRemove; i++ )
{
int idx = m_outputPorts.Count - 1;
if( m_outputPorts[ idx ].IsConnected )
{
m_outputPorts[ idx ].ForceClearConnection();
}
RemoveOutputPort( idx );
}
}
m_sizeIsDirty = true;
m_isDirty = true;
//Event.current.Use();
}
19
View Source File : StringExtensions.cs
License : MIT License
Project Creator : aliakseiherman
License : MIT License
Project Creator : aliakseiherman
public static string UppercaseFirst(this string str)
{
if (string.IsNullOrEmpty(str))
{
return string.Empty;
}
char[] a = str.ToCharArray();
a[0] = char.ToUpper(a[0]);
return new string(a);
}
19
View Source File : CharExtension.cs
License : MIT License
Project Creator : AlphaYu
License : MIT License
Project Creator : AlphaYu
public static char ToUpper(this char c)
{
return char.ToUpper(c);
}
19
View Source File : ExtensionMethods.cs
License : MIT License
Project Creator : Altevir
License : MIT License
Project Creator : Altevir
public static string FirstLetterUpperCase(this string value)
{
if (string.IsNullOrEmpty(value))
return string.Empty;
return $"{char.ToUpper(value[0])}{value.Substring(1)}";
}
19
View Source File : JsonSchemaToInstanceModelGenerator.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
private void TraverseModel(string parentPath, string parentTypeName, string propertyName, JsonSchema currentJsonSchema, bool isRequired, ISet<string> alreadyVisitedTypes, JsonSchema parentJsonSchema, string parentXpath)
{
string sanitizedPropertyName = SanitizeName(propertyName);
string xPath;
string path;
int index = 0;
do
{
path = (string.IsNullOrEmpty(parentPath) ? string.Empty : parentPath + ".") + sanitizedPropertyName;
xPath = (string.IsNullOrEmpty(parentXpath) ? "/" : parentXpath + "/") + propertyName;
if (++index >= 2)
{
path += index.ToString();
xPath += index.ToString();
}
}
while (elements.ContainsKey(path));
// exclude elements that does not start with firstPropertyName
if (!path.StartsWith(firstPropertyName))
{
return;
}
string minItems = "0";
string maxItems = "1";
TypeKeyword currentJsonSchemaType = currentJsonSchema.Get<TypeKeyword>();
if (currentJsonSchemaType != null && currentJsonSchemaType.Value == JsonSchemaType.Array)
{
List<JsonSchema> items = currentJsonSchema.Items();
path += multiplicityString;
FollowRef(path, items[0], alreadyVisitedTypes, xPath); // TODO fix multiple item types. It now uses only the first
double? minItemsValue = currentJsonSchema.MinItems();
double? maxItemsValue = currentJsonSchema.MaxItems();
if (minItemsValue.HasValue)
{
minItems = minItemsValue.ToString();
}
maxItems = "*";
if (maxItemsValue.HasValue && maxItemsValue.Value != MagicNumberMaxOccurs)
{
maxItems = maxItemsValue.ToString();
}
}
else if (currentJsonSchemaType != null && currentJsonSchemaType.Value == JsonSchemaType.Object)
{
if (alreadyVisitedTypes.Contains(sanitizedPropertyName))
{
return;
}
ISet<string> currentlyVisitedTypes = new HashSet<string>(alreadyVisitedTypes);
currentlyVisitedTypes.Add(sanitizedPropertyName);
if (currentJsonSchema.Properties() != null)
{
foreach (KeyValuePair<string, JsonSchema> def in currentJsonSchema.Properties())
{
TraverseModel(path, sanitizedPropertyName, def.Key, def.Value, IsRequired(def.Key, currentJsonSchema), currentlyVisitedTypes, currentJsonSchema, xPath);
}
}
}
else
{
FollowRef(path, currentJsonSchema, alreadyVisitedTypes, xPath);
if (isRequired)
{
minItems = "1";
}
}
JsonObject result = new JsonObject();
string inputType = "Field";
string xsdType = currentJsonSchema.OtherData.TryGetString("@xsdType");
result.Add("ID", RemoveStarsFromPath(path));
string parentElement = ExtractParent(path);
if (parentElement != null)
{
result.Add("ParentElement", RemoveStarsFromPath(parentElement));
}
string xsdValueType = FollowValueType(currentJsonSchema);
string typeName = ExtractTypeNameFromSchema(currentJsonSchema);
if (typeName != null)
{
result.Add("TypeName", SanitizeName(typeName));
}
else
{
result.Add("TypeName", sanitizedPropertyName);
}
result.Add("Name", sanitizedPropertyName);
string fixedValue = null;
JsonValue fixedValueJson = currentJsonSchema.Const();
if (fixedValueJson != null)
{
fixedValue = fixedValueJson.String;
}
if (xsdType != null && xsdType.Equals("XmlAttribute"))
{
inputType = "Attribute";
}
else if ((currentJsonSchemaType == null && xsdValueType == null) || (currentJsonSchemaType != null && (currentJsonSchemaType.Value == JsonSchemaType.Object || currentJsonSchemaType.Value == JsonSchemaType.Array)))
{
inputType = "Group";
}
int maxOccursParsed = maxItems.Equals("*") ? MagicNumberMaxOccurs : int.Parse(maxItems);
if ((!inputType.Equals("Group") && string.IsNullOrEmpty(fixedValue)) || (inputType.Equals("Group") && maxOccursParsed > 1))
{
string dataBindingNameWithoutFirstPropertyName = $"{parentXpath}/{propertyName}".Replace("/" + firstPropertyName + "/", string.Empty);
string dataBindingName = dataBindingNameWithoutFirstPropertyName.Replace("/", ".");
result.Add("DataBindingName", dataBindingName);
}
result.Add("XPath", xPath);
result.Add("Restrictions", ExtractRestrictions(xsdValueType, currentJsonSchema));
result.Add("Type", inputType);
if (!string.IsNullOrEmpty(xsdValueType))
{
result.Add("XsdValueType", char.ToUpper(xsdValueType[0]) + xsdValueType.Substring(1)); // Uppercase first character
}
if (path.EndsWith(".value"))
{
result.Add("Texts", ExtractTexts(parentElement.Split(".").Last(), parentJsonSchema));
result.Add("IsTagContent", true);
}
else
{
result.Add("Texts", ExtractTexts(propertyName, currentJsonSchema));
}
result.Add("CustomProperties", new JsonObject()); // ??
result.Add("MaxOccurs", maxOccursParsed);
result.Add("MinOccurs", int.Parse(minItems));
result.Add("XName", propertyName);
if (fixedValue != null)
{
result.Add("FixedValue", fixedValue);
}
string jsonSchemaPointer = "#/properties/" + propertyName;
if (parentElement != null)
{
jsonSchemaPointer = "#/definitions/" + parentTypeName + "/properties/" + propertyName;
}
result.Add("JsonSchemaPointer", jsonSchemaPointer);
string cardinality = "[" + minItems + ".." + maxItems + "]";
string displayString = RemoveLastStar(path) + " : " + cardinality + " " + SanitizeName(typeName);
result.Add("DisplayString", displayString);
// TODO ..., XmlSchemaReference
elements.Add(RemoveStarsFromPath(path), result);
}
19
View Source File : CsharpFromJsonExampleFactory.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
private static IEnumerable<char> SafeCsNameCharacters(string name, bool upperCaseFirstCharacter)
{
if (string.IsNullOrEmpty(name))
{
yield break;
}
var first = true;
foreach (var c in name)
{
if (first)
{
if (c == '_' || char.IsLetter(c))
{
yield return upperCaseFirstCharacter ? char.ToUpper(c) : c;
}
else
{
yield return '_';
}
first = false;
}
else
{
yield return c == '_' || char.IsLetterOrDigit(c) ? c : '_';
}
}
}
19
View Source File : Config.cs
License : MIT License
Project Creator : altugbakan
License : MIT License
Project Creator : altugbakan
private string Capitalize(string word)
{
return char.ToUpper(word[0]) + word[1..];
}
19
View Source File : CsCodeGenerator.Enum.cs
License : MIT License
Project Creator : amerkoleci
License : MIT License
Project Creator : amerkoleci
private static string GetPrettyEnumName(string value, string enumPrefix)
{
if (s_knownEnumValueNames.TryGetValue(value, out string? knownName))
{
return knownName;
}
if (value.IndexOf(enumPrefix) != 0)
{
return value;
}
string[] parts = value[enumPrefix.Length..].Split(new[] { '_' }, StringSplitOptions.RemoveEmptyEntries);
var sb = new StringBuilder();
foreach (string part in parts)
{
if (s_ignoredParts.Contains(part))
{
continue;
}
if (s_preserveCaps.Contains(part))
{
sb.Append(part);
}
else
{
sb.Append(char.ToUpper(part[0]));
for (int i = 1; i < part.Length; i++)
{
sb.Append(char.ToLower(part[i]));
}
}
}
string prettyName = sb.ToString();
return (char.IsNumber(prettyName[0])) ? "_" + prettyName : prettyName;
}
19
View Source File : Helpers.cs
License : MIT License
Project Creator : Aminator
License : MIT License
Project Creator : Aminator
public static string ToPascalCase(string name)
{
if (name.Contains(" ") || name.Contains("_") || name == name.ToUpper())
{
var words = name.ToLower().Split(' ', '_');
StringBuilder sb = new StringBuilder();
foreach (string word in words)
{
sb.Append(char.ToUpper(word[0]));
sb.Append(word.Substring(1));
}
return sb.ToString();
}
else
{
return char.ToUpper(name[0]) + name.Substring(1);
}
}
19
View Source File : StringExtensions.cs
License : MIT License
Project Creator : AnnoDesigner
License : MIT License
Project Creator : AnnoDesigner
public static string FirstCharToUpper(this string input)
{
if (string.IsNullOrWhiteSpace(input))
{
return string.Empty;
}
var tempCharArray = input.ToCharArray();
tempCharArray[0] = char.ToUpper(tempCharArray[0]);
return new string(tempCharArray);
}
19
View Source File : KeyboardInteropHelper.cs
License : MIT License
Project Creator : AnnoDesigner
License : MIT License
Project Creator : AnnoDesigner
public static string GetDisplayString(Key key)
{
//Special handling for numpad keys.
if (IsNumPadKey(key))
{
return GetFriendlyDisplayString(key);
}
var c = GetCharacter(key, false);
if (c.HasValue)
{
if (IsVisibleCharacter(c.Value))
{
var str = char.ToUpper(c.Value).ToString();
if (!string.IsNullOrWhiteSpace(str))
{
return str;
}
}
return GetFriendlyDisplayString(key);
}
else
{
return key.ToString();
}
}
19
View Source File : ExtensionMethods.cs
License : MIT License
Project Creator : anthonyreilly
License : MIT License
Project Creator : anthonyreilly
public static string UppercaseFirstLetter(this string value)
{
if (value.Length > 0)
{
char[] array = value.ToCharArray();
array[0] = char.ToUpper(array[0]);
return new string(array);
}
return value;
}
19
View Source File : SharedExtensions.cs
License : GNU Lesser General Public License v3.0
Project Creator : ApexGameTools
License : GNU Lesser General Public License v3.0
Project Creator : ApexGameTools
public static string ExpandFromPascal(this string pascalString)
{
if (pascalString == null)
{
return null;
}
var transformer = new StringBuilder(pascalString.Length);
pascalString = pascalString.TrimStart('_');
var length = pascalString.Length;
if (length > 0)
{
transformer.Append(char.ToUpper(pascalString[0]));
for (int i = 1; i < length; i++)
{
if (char.IsUpper(pascalString, i) && (i + 1 < length) && (!char.IsUpper(pascalString, i - 1) || !char.IsUpper(pascalString, i + 1)))
{
transformer.Append(" ");
}
transformer.Append(pascalString[i]);
}
}
return transformer.ToString();
}
19
View Source File : StringUtil.cs
License : MIT License
Project Creator : aquilahkj
License : MIT License
Project Creator : aquilahkj
public static string ToPascalCase(string name)
{
StringBuilder sb = new StringBuilder();
string[] parts = name.Split(splitChars, StringSplitOptions.RemoveEmptyEntries);
foreach (string part in parts) {
if (part.Length > 0) {
sb.Append(Char.ToUpper(part[0]));
if (part.Length > 1) {
string o = part.Substring(1);
if (o == o.ToUpper()) {
o = o.ToLower();
}
sb.Append(o);
}
}
}
return sb.ToString();
}
19
View Source File : StringUtil.cs
License : MIT License
Project Creator : aquilahkj
License : MIT License
Project Creator : aquilahkj
public static string ToCamelCase(string name)
{
StringBuilder sb = new StringBuilder();
string[] parts = name.Split(splitChars, StringSplitOptions.RemoveEmptyEntries);
bool f = false;
foreach (string part in parts) {
if (part.Length > 0) {
if (!f) {
sb.Append(Char.ToLower(part[0]));
f = true;
}
else {
sb.Append(Char.ToUpper(part[0]));
}
if (part.Length > 1) {
string o = part.Substring(1);
if (o == o.ToUpper()) {
o = o.ToLower();
}
sb.Append(o);
}
}
}
return sb.ToString();
}
19
View Source File : DriverSettings.cs
License : Apache License 2.0
Project Creator : aquality-automation
License : Apache License 2.0
Project Creator : aquality-automation
private bool IsEnumValue(Type propertyType, object optionValue)
{
var valuereplacedtring = optionValue.ToString();
if (!propertyType.IsEnum || string.IsNullOrEmpty(valuereplacedtring))
{
return false;
}
var normalizedValue = char.ToUpper(valuereplacedtring[0]) +
(valuereplacedtring.Length > 1 ? valuereplacedtring.Substring(1) : string.Empty);
return propertyType.IsEnumDefined(normalizedValue)
|| propertyType.IsEnumDefined(valuereplacedtring)
|| (IsValueOfIntegralNumericType(optionValue)
&& propertyType.IsEnumDefined(Convert.ChangeType(optionValue, Enum.GetUnderlyingType(propertyType))));
}
19
View Source File : DataField.cs
License : MIT License
Project Creator : araditc
License : MIT License
Project Creator : araditc
DataFieldType AttributeValueToType(string value) {
value.ThrowIfNull("value");
StringBuilder b = new StringBuilder();
string s = value;
for (int i = 0; i < s.Length; i++) {
if (s[i] == '-')
b.Append(Char.ToUpper(s[++i]));
else
b.Append(s[i]);
}
value = b.ToString();
return Util.ParseEnum<DataFieldType>(value);
}
19
View Source File : SwapCase.cs
License : MIT License
Project Creator : ardalis
License : MIT License
Project Creator : ardalis
public static string SwapCase(this string text)
{
if (string.IsNullOrEmpty(text))
{
return text;
}
var result = new StringBuilder();
for (var i = 0; i < text.Length; i++)
{
if (char.IsUpper(text[i]))
{
result.Append(char.ToLower(text[i]));
}
else if (char.IsLower(text[i]))
{
result.Append(char.ToUpper(text[i]));
}
else
{
result.Append(text[i]);
}
}
return result.ToString();
}
19
View Source File : LOTD_File.cs
License : MIT License
Project Creator : Arefu
License : MIT License
Project Creator : Arefu
public static Localized_Text.Language GetLanguageFromFileName(string fileName)
{
if (fileName.LastIndexOf('_') < 0 || fileName.Length <= fileName.LastIndexOf('_') + 1)
return Localized_Text.Language.Unknown;
if (fileName.LastIndexOf('.') != -1 && fileName.LastIndexOf('.') != fileName.LastIndexOf('_') + 2)
return Localized_Text.Language.Unknown;
switch (char.ToUpper(fileName[fileName.LastIndexOf('_') + 1]))
{
case 'E': return Localized_Text.Language.English;
case 'F': return Localized_Text.Language.French;
case 'G': return Localized_Text.Language.German;
case 'I': return Localized_Text.Language.Italian;
case 'S': return Localized_Text.Language.Spanish;
default: return Localized_Text.Language.Unknown;
}
}
19
View Source File : Ex.cs
License : MIT License
Project Creator : ARKlab
License : MIT License
Project Creator : ARKlab
public static bool SqlLike(string pattern, string str)
{
bool isMatch = true,
isWildCardOn = false,
isCharWildCardOn = false,
isCharSetOn = false,
isNotCharSetOn = false,
endOfPattern = false;
int lastWildCard = -1;
int patternIndex = 0;
List<char> set = new List<char>();
char p = '\0';
for (int i = 0; i < str.Length; i++)
{
char c = str[i];
endOfPattern = (patternIndex >= pattern.Length);
if (!endOfPattern)
{
p = pattern[patternIndex];
if (!isWildCardOn && p == '%')
{
lastWildCard = patternIndex;
isWildCardOn = true;
while (patternIndex < pattern.Length &&
pattern[patternIndex] == '%')
{
patternIndex++;
}
if (patternIndex >= pattern.Length) p = '\0';
else p = pattern[patternIndex];
}
else if (p == '_')
{
isCharWildCardOn = true;
patternIndex++;
}
else if (p == '[')
{
if (pattern[++patternIndex] == '^')
{
isNotCharSetOn = true;
patternIndex++;
}
else isCharSetOn = true;
set.Clear();
if (pattern[patternIndex + 1] == '-' && pattern[patternIndex + 3] == ']')
{
char start = char.ToUpper(pattern[patternIndex]);
patternIndex += 2;
char end = char.ToUpper(pattern[patternIndex]);
if (start <= end)
{
for (char ci = start; ci <= end; ci++)
{
set.Add(ci);
}
}
patternIndex++;
}
while (patternIndex < pattern.Length &&
pattern[patternIndex] != ']')
{
set.Add(pattern[patternIndex]);
patternIndex++;
}
patternIndex++;
}
}
if (isWildCardOn)
{
if (char.ToUpper(c) == char.ToUpper(p))
{
isWildCardOn = false;
patternIndex++;
}
}
else if (isCharWildCardOn)
{
isCharWildCardOn = false;
}
else if (isCharSetOn || isNotCharSetOn)
{
bool charMatch = (set.Contains(char.ToUpper(c)));
if ((isNotCharSetOn && charMatch) || (isCharSetOn && !charMatch))
{
if (lastWildCard >= 0) patternIndex = lastWildCard;
else
{
isMatch = false;
break;
}
}
isNotCharSetOn = isCharSetOn = false;
}
else
{
if (char.ToUpper(c) == char.ToUpper(p))
{
patternIndex++;
}
else
{
if (lastWildCard >= 0) patternIndex = lastWildCard;
else
{
isMatch = false;
break;
}
}
}
}
endOfPattern = (patternIndex >= pattern.Length);
if (isMatch && !endOfPattern)
{
bool isOnlyWildCards = true;
for (int i = patternIndex; i < pattern.Length; i++)
{
if (pattern[i] != '%')
{
isOnlyWildCards = false;
break;
}
}
if (isOnlyWildCards) endOfPattern = true;
}
return isMatch && endOfPattern;
}
19
View Source File : StringExtensions.cs
License : MIT License
Project Creator : arslanaybars
License : MIT License
Project Creator : arslanaybars
public static string ToUpperFirstLetter(this string source)
{
if (string.IsNullOrEmpty(source))
return string.Empty;
// convert to char array of the string
char[] letters = source.ToCharArray();
// upper case the first char
letters[0] = char.ToUpper(letters[0]);
// return the array made of the new char array
return new string(letters);
}
19
View Source File : StringMatcher.cs
License : GNU General Public License v3.0
Project Creator : Artentus
License : GNU General Public License v3.0
Project Creator : Artentus
public static bool FuzzyMatch(this string stringToSearch, string pattern, out int score)
{
// Score consts
const int adjacencyBonus = 5; // bonus for adjacent matches
const int separatorBonus = 10; // bonus if match occurs after a separator
const int camelBonus = 10; // bonus if match is uppercase and prev is lower
const int leadingLetterPenalty = -3; // penalty applied for every letter in stringToSearch before the first match
const int maxLeadingLetterPenalty = -9; // maximum penalty for leading letters
const int unmatchedLetterPenalty = -1; // penalty for every letter that doesn't matter
// Loop variables
score = 0;
var patternIdx = 0;
var strIdx = 0;
var prevMatched = false;
var prevLower = false;
var prevSeparator = true; // true if first letter match gets separator bonus
// Use "best" matched letter if multiple string letters match the pattern
char? bestLetter = null;
char? bestLower = null;
int? bestLetterIdx = null;
var bestLetterScore = 0;
var matchedIndices = new List<int>();
// Loop over strings
while (strIdx != stringToSearch.Length)
{
var patternChar = patternIdx != pattern.Length ? pattern[patternIdx] as char? : null;
var strChar = stringToSearch[strIdx];
var patternLower = patternChar != null ? char.ToLower((char)patternChar) as char? : null;
var strLower = char.ToLower(strChar);
var strUpper = char.ToUpper(strChar);
var nextMatch = patternChar != null && patternLower == strLower;
var rematch = bestLetter != null && bestLower == strLower;
var advanced = nextMatch && bestLetter != null;
var patternRepeat = bestLetter != null && patternChar != null && bestLower == patternLower;
if (advanced || patternRepeat)
{
score += bestLetterScore;
matchedIndices.Add(bestLetterIdx!.Value);
bestLetter = null;
bestLower = null;
bestLetterIdx = null;
bestLetterScore = 0;
}
if (nextMatch || rematch)
{
var newScore = 0;
// Apply penalty for each letter before the first pattern match
// Note: Math.Max because penalties are negative values. So max is smallest penalty.
if (patternIdx == 0)
{
var penalty = Math.Max(strIdx * leadingLetterPenalty, maxLeadingLetterPenalty);
score += penalty;
}
// Apply bonus for consecutive bonuses
if (prevMatched) newScore += adjacencyBonus;
// Apply bonus for matches after a separator
if (prevSeparator) newScore += separatorBonus;
// Apply bonus across camel case boundaries. Includes "clever" isLetter check.
if (prevLower && strChar == strUpper && strLower != strUpper) newScore += camelBonus;
// Update pattern index IF the next pattern letter was matched
if (nextMatch) ++patternIdx;
// Update best letter in stringToSearch which may be for a "next" letter or a "rematch"
if (newScore >= bestLetterScore)
{
// Apply penalty for now skipped letter
if (bestLetter != null) score += unmatchedLetterPenalty;
bestLetter = strChar;
bestLower = char.ToLower((char)bestLetter);
bestLetterIdx = strIdx;
bestLetterScore = newScore;
}
prevMatched = true;
}
else
{
score += unmatchedLetterPenalty;
prevMatched = false;
}
// Includes "clever" isLetter check.
prevLower = strChar == strLower && strLower != strUpper;
prevSeparator = strChar == '_' || strChar == ' ';
++strIdx;
}
// Apply score for last match
if (bestLetter != null)
{
score += bestLetterScore;
matchedIndices.Add(bestLetterIdx!.Value);
}
return patternIdx == pattern.Length;
}
19
View Source File : NiTextKeyExtraData.cs
License : GNU General Public License v3.0
Project Creator : arycama
License : GNU General Public License v3.0
Project Creator : arycama
private ClipInfo CreateClip(string name, float start)
{
ClipInfo clipInfo;
if(niFile.animationCache.TryGetValue(name, out clipInfo))
{
return clipInfo;
}
clipInfo = new ClipInfo();
var clip = new AnimationClip()
{
// Rarely, animations may not have the first letter uppercased, such as idle4 for Rats. Manually uppercase it here for now. Internally, Morrowind probably uses a case insensitive lookup.
name =char.ToUpper(name[0]) + name.Substring(1),
legacy = true,
frameRate = 15
};
clipInfo.clip = clip;
clipInfo.Start = start;
niFile.animationCache.Add(name, clipInfo);
return clipInfo;
}
19
View Source File : DialogView.cs
License : GNU General Public License v3.0
Project Creator : arycama
License : GNU General Public License v3.0
Project Creator : arycama
void IDialogView.DisplayInfo(string text, string replacedle)
{
if (replacedle != null)
{
replacedle = char.ToUpper(replacedle[0]) + replacedle.Substring(1);
var color = IniManager.GetColor("FontColor", "color_big_header");
var colorHex = ColorUtility.ToHtmlStringRGB(color);
if(text == null)
{
text = $"<color=#{colorHex}>{replacedle}</color>{text}";
}
else
{
text = $"<color=#{colorHex}>{replacedle}</color>\r\n{text}";
}
}
if(text != null)
{
var infoClone = Instantiate(infoPrefab, infoParent);
infoClone.text = text;
}
ScrollToBottom();
}
19
View Source File : DialogView.cs
License : GNU General Public License v3.0
Project Creator : arycama
License : GNU General Public License v3.0
Project Creator : arycama
void IDialogView.AddTopic(DialogRecord topic)
{
// Convert tile to replacedle case
var replacedle = char.ToUpper(topic.name[0]) + topic.name.Substring(1);
// Create the UI game object
var clone = Instantiate(topicPrefab, topicsParent);
clone.Initialize(replacedle, () => controller.DisplayTopic(topic));
// Add it to the current list of topics, and sort
currentTopics.Add(topic);
currentTopics.Sort((x, y) => x.name.CompareTo(y.name));
// Get the index and use it to position the transform in the list correctly
var index = currentTopics.IndexOf(topic);
clone.transform.SetSiblingIndex(index);
}
See More Examples