MrWolfRanger

imperium

Mar 27th, 2021
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 288.73 KB | None | 0 0
  1. // Reference: System.Drawing
  2.  
  3. /*
  4. * Copyright (C) 2017-2018 chucklenugget
  5. *
  6. * Permission is hereby granted, free of charge, to any person obtaining a copy
  7. * of this software and associated documentation files (the "Software"), to deal
  8. * in the Software without restriction, including without limitation the rights
  9. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. * copies of the Software, and to permit persons to whom the Software is
  11. * furnished to do so, subject to the following conditions:
  12. *
  13. * The above copyright notice and this permission notice shall be included in all
  14. * copies or substantial portions of the Software.
  15. *
  16. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  22. * SOFTWARE.
  23. */
  24.  
  25. namespace Oxide.Plugins
  26. {
  27. using System;
  28. using System.IO;
  29. using Oxide.Core;
  30. using Oxide.Core.Configuration;
  31. using UnityEngine;
  32. using System.Collections.Generic;
  33. using System.Linq;
  34.  
  35. [Info("Imperium", "chucklenugget/Orange", "1.10.2")]
  36. public partial class Imperium : RustPlugin
  37. {
  38. static Imperium Instance;
  39.  
  40. bool Ready;
  41.  
  42. DynamicConfigFile AreasFile;
  43. DynamicConfigFile FactionsFile;
  44. DynamicConfigFile PinsFile;
  45. DynamicConfigFile WarsFile;
  46.  
  47. GameObject GameObject;
  48. ImperiumOptions Options;
  49. Timer UpkeepCollectionTimer;
  50.  
  51. AreaManager Areas;
  52. FactionManager Factions;
  53. HudManager Hud;
  54. PinManager Pins;
  55. UserManager Users;
  56. WarManager Wars;
  57. ZoneManager Zones;
  58.  
  59. void Init()
  60. {
  61. AreasFile = GetDataFile("areas");
  62. FactionsFile = GetDataFile("factions");
  63. PinsFile = GetDataFile("pins");
  64. WarsFile = GetDataFile("wars");
  65. }
  66.  
  67. void Loaded()
  68. {
  69. InitLang();
  70. Permission.RegisterAll(this);
  71.  
  72. try
  73. {
  74. Options = Config.ReadObject<ImperiumOptions>();
  75. }
  76. catch (Exception ex)
  77. {
  78. PrintError($"Error while loading configuration: {ex.ToString()}");
  79. }
  80.  
  81. Puts("Area claims are " + (Options.Claims.Enabled ? "enabled" : "disabled"));
  82. Puts("Taxation is " + (Options.Taxes.Enabled ? "enabled" : "disabled"));
  83. Puts("Badlands are " + (Options.Badlands.Enabled ? "enabled" : "disabled"));
  84. Puts("Map pins are " + (Options.Map.PinsEnabled ? "enabled" : "disabled"));
  85. Puts("War is " + (Options.War.Enabled ? "enabled" : "disabled"));
  86. Puts("Decay reduction is " + (Options.Decay.Enabled ? "enabled" : "disabled"));
  87. Puts("Claim upkeep is " + (Options.Upkeep.Enabled ? "enabled" : "disabled"));
  88. Puts("Zones are " + (Options.Zones.Enabled ? "enabled" : "disabled"));
  89.  
  90. // If the map has already been initialized, we can set up now; otherwise,
  91. // we need to wait until the savefile has been loaded.
  92. if (TerrainMeta.Size.x > 0) Setup();
  93. }
  94.  
  95. object OnSaveLoad(Dictionary<BaseEntity, ProtoBuf.Entity> entities)
  96. {
  97. Setup();
  98. return null;
  99. }
  100.  
  101. void Setup()
  102. {
  103. Instance = this;
  104. GameObject = new GameObject();
  105.  
  106. Areas = new AreaManager();
  107. Factions = new FactionManager();
  108. Hud = new HudManager();
  109. Pins = new PinManager();
  110. Users = new UserManager();
  111. Wars = new WarManager();
  112. Zones = new ZoneManager();
  113.  
  114. Factions.Init(TryLoad<FactionInfo>(FactionsFile));
  115. Areas.Init(TryLoad<AreaInfo>(AreasFile));
  116. Pins.Init(TryLoad<PinInfo>(PinsFile));
  117. Users.Init();
  118. Wars.Init(TryLoad<WarInfo>(WarsFile));
  119. Zones.Init();
  120. Hud.Init();
  121.  
  122. Hud.GenerateMapOverlayImage();
  123.  
  124. if (Options.Upkeep.Enabled)
  125. UpkeepCollectionTimer =
  126. timer.Every(Options.Upkeep.CheckIntervalMinutes * 60, Upkeep.CollectForAllFactions);
  127.  
  128. PrintToChat($"{Title} v{Version} initialized.");
  129. Ready = true;
  130. }
  131.  
  132. void Unload()
  133. {
  134. Hud.Destroy();
  135. Zones.Destroy();
  136. Users.Destroy();
  137. Wars.Destroy();
  138. Pins.Destroy();
  139. Areas.Destroy();
  140. Factions.Destroy();
  141.  
  142. if (UpkeepCollectionTimer != null && !UpkeepCollectionTimer.Destroyed)
  143. UpkeepCollectionTimer.Destroy();
  144.  
  145. if (GameObject != null)
  146. UnityEngine.Object.Destroy(GameObject);
  147.  
  148. Instance = null;
  149. }
  150.  
  151. void OnServerSave()
  152. {
  153. timer.Once(Core.Random.Range(10, 30), () =>
  154. {
  155. AreasFile.WriteObject(Areas.Serialize());
  156. FactionsFile.WriteObject(Factions.Serialize());
  157. PinsFile.WriteObject(Pins.Serialize());
  158. WarsFile.WriteObject(Wars.Serialize());
  159. });
  160. }
  161.  
  162. DynamicConfigFile GetDataFile(string name)
  163. {
  164. return Interface.Oxide.DataFileSystem.GetFile(Name + Path.DirectorySeparatorChar + name);
  165. }
  166.  
  167. IEnumerable<T> TryLoad<T>(DynamicConfigFile file)
  168. {
  169. List<T> items;
  170.  
  171. try
  172. {
  173. items = file.ReadObject<List<T>>();
  174. }
  175. catch (Exception ex)
  176. {
  177. PrintWarning($"Error reading data from {file.Filename}: ${ex.ToString()}");
  178. items = new List<T>();
  179. }
  180.  
  181. return items;
  182. }
  183.  
  184. void Log(string message, params object[] args)
  185. {
  186. LogToFile("log", String.Format(message, args), this, true);
  187. }
  188.  
  189. bool EnsureUserCanChangeFactionClaims(User user, Faction faction)
  190. {
  191. if (faction == null || !faction.HasLeader(user))
  192. {
  193. user.SendChatMessage(Messages.NotLeaderOfFaction);
  194. return false;
  195. }
  196.  
  197. if (faction.MemberCount < Options.Claims.MinFactionMembers)
  198. {
  199. user.SendChatMessage(Messages.FactionTooSmallToOwnLand, Options.Claims.MinFactionMembers);
  200. return false;
  201. }
  202.  
  203. return true;
  204. }
  205.  
  206. bool EnsureFactionCanClaimArea(User user, Faction faction, Area area)
  207. {
  208. if (area.Type == AreaType.Badlands)
  209. {
  210. user.SendChatMessage(Messages.AreaIsBadlands, area.Id);
  211. return false;
  212. }
  213.  
  214. if (faction.MemberCount < Instance.Options.Claims.MinFactionMembers)
  215. {
  216. user.SendChatMessage(Messages.FactionTooSmallToOwnLand, Instance.Options.Claims.MinFactionMembers);
  217. return false;
  218. }
  219.  
  220. Area[] claimedAreas = Areas.GetAllClaimedByFaction(faction);
  221.  
  222. if (Instance.Options.Claims.RequireContiguousClaims && !area.IsClaimed && claimedAreas.Length > 0)
  223. {
  224. int contiguousClaims = Areas.GetNumberOfContiguousClaimedAreas(area, faction);
  225. if (contiguousClaims == 0)
  226. {
  227. user.SendChatMessage(Messages.AreaNotContiguous, area.Id, faction.Id);
  228. return false;
  229. }
  230. }
  231.  
  232. int? maxClaims = Instance.Options.Claims.MaxClaims;
  233. if (maxClaims != null && claimedAreas.Length >= maxClaims)
  234. {
  235. user.SendChatMessage(Messages.FactionOwnsTooMuchLand, faction.Id, maxClaims);
  236. return false;
  237. }
  238.  
  239. return true;
  240. }
  241.  
  242. bool EnsureCupboardCanBeUsedForClaim(User user, BuildingPrivlidge cupboard)
  243. {
  244. if (cupboard == null)
  245. {
  246. user.SendChatMessage(Messages.SelectingCupboardFailedInvalidTarget);
  247. return false;
  248. }
  249.  
  250. if (!cupboard.IsAuthed(user.Player))
  251. {
  252. user.SendChatMessage(Messages.SelectingCupboardFailedNotAuthorized);
  253. return false;
  254. }
  255.  
  256. return true;
  257. }
  258.  
  259. bool EnsureUserAndFactionCanEngageInDiplomacy(User user, Faction faction)
  260. {
  261. if (faction == null)
  262. {
  263. user.SendChatMessage(Messages.NotMemberOfFaction);
  264. return false;
  265. }
  266.  
  267. if (faction.MemberCount < Options.Claims.MinFactionMembers)
  268. {
  269. user.SendChatMessage(Messages.FactionTooSmallToOwnLand);
  270. return false;
  271. }
  272.  
  273. if (Areas.GetAllClaimedByFaction(faction).Length == 0)
  274. {
  275. user.SendChatMessage(Messages.FactionDoesNotOwnLand);
  276. return false;
  277. }
  278.  
  279. return true;
  280. }
  281.  
  282. bool EnforceCommandCooldown(User user, string command, int cooldownSeconds)
  283. {
  284. int secondsRemaining = user.GetSecondsLeftOnCooldown(command);
  285.  
  286. if (secondsRemaining > 0)
  287. {
  288. user.SendChatMessage(Messages.CommandIsOnCooldown, secondsRemaining);
  289. return false;
  290. }
  291.  
  292. user.SetCooldownExpiration(command, DateTime.UtcNow.AddSeconds(cooldownSeconds));
  293. return true;
  294. }
  295.  
  296. bool TryCollectFromStacks(ItemDefinition itemDef, IEnumerable<Item> stacks, int amount)
  297. {
  298. if (stacks.Sum(item => item.amount) < amount)
  299. return false;
  300.  
  301. int amountRemaining = amount;
  302. var dirtyContainers = new HashSet<ItemContainer>();
  303.  
  304. foreach (Item stack in stacks)
  305. {
  306. var amountToTake = Math.Min(stack.amount, amountRemaining);
  307.  
  308. stack.amount -= amountToTake;
  309. amountRemaining -= amountToTake;
  310.  
  311. dirtyContainers.Add(stack.GetRootContainer());
  312.  
  313. if (stack.amount == 0)
  314. stack.RemoveFromContainer();
  315.  
  316. if (amountRemaining == 0)
  317. break;
  318. }
  319.  
  320. foreach (ItemContainer container in dirtyContainers)
  321. container.MarkDirty();
  322.  
  323. return true;
  324. }
  325. }
  326. }
  327.  
  328. namespace Oxide.Plugins
  329. {
  330. public partial class Imperium
  331. {
  332. [ChatCommand("cancel")]
  333. void OnCancelCommand(BasePlayer player, string command, string[] args)
  334. {
  335. User user = Users.Get(player);
  336.  
  337. if (user.CurrentInteraction == null)
  338. {
  339. user.SendChatMessage(Messages.NoInteractionInProgress);
  340. return;
  341. }
  342.  
  343. user.SendChatMessage(Messages.InteractionCanceled);
  344. user.CancelInteraction();
  345. }
  346. }
  347. }
  348.  
  349. namespace Oxide.Plugins
  350. {
  351. using System.Text;
  352.  
  353. public partial class Imperium
  354. {
  355. [ChatCommand("help")]
  356. void OnHelpCommand(BasePlayer player, string command, string[] args)
  357. {
  358. User user = Users.Get(player);
  359. if (user == null) return;
  360.  
  361. var sb = new StringBuilder();
  362.  
  363. sb.AppendLine($"<size=18>Welcome to {ConVar.Server.hostname}!</size>");
  364. sb.AppendLine($"Powered by {Name} v{Version} by <color=#ffd479>chucklenugget</color>");
  365. sb.AppendLine();
  366.  
  367. sb.Append(
  368. "The following commands are available. To learn more about each command, do <color=#ffd479>/command help</color>. ");
  369. sb.AppendLine("For example, to learn more about how to claim land, do <color=#ffd479>/claim help</color>.");
  370. sb.AppendLine();
  371.  
  372. sb.AppendLine("<color=#ffd479>/faction</color> Create or join a faction");
  373. sb.AppendLine("<color=#ffd479>/claim</color> Claim areas of land");
  374.  
  375. if (Options.Taxes.Enabled)
  376. sb.AppendLine("<color=#ffd479>/tax</color> Manage taxation of your land");
  377.  
  378. if (Options.Map.PinsEnabled)
  379. sb.AppendLine("<color=#ffd479>/pin</color> Add pins (points of interest) to the map");
  380.  
  381. if (Options.War.Enabled)
  382. sb.AppendLine("<color=#ffd479>/war</color> See active wars, declare war, or offer peace");
  383.  
  384. if (Options.Badlands.Enabled)
  385. {
  386. if (user.HasPermission(Permission.AdminBadlands))
  387. sb.AppendLine("<color=#ffd479>/badlands</color> Find or change badlands areas");
  388. else
  389. sb.AppendLine("<color=#ffd479>/badlands</color> Find badlands (PVP) areas");
  390. }
  391.  
  392. user.SendChatMessage(sb);
  393. }
  394. }
  395. }
  396.  
  397. namespace Oxide.Plugins
  398. {
  399. public partial class Imperium
  400. {
  401. [ChatCommand("pvp")]
  402. void OnPvpCommand(BasePlayer player, string command, string[] args)
  403. {
  404. User user = Users.Get(player);
  405.  
  406. if (!Options.Pvp.EnablePvpCommand)
  407. {
  408. user.SendChatMessage(Messages.PvpModeDisabled);
  409. return;
  410. }
  411.  
  412. if (!EnforceCommandCooldown(user, "pvp", Options.Pvp.CommandCooldownSeconds))
  413. return;
  414.  
  415. if (user.IsInPvpMode)
  416. {
  417. user.IsInPvpMode = false;
  418. user.SendChatMessage(Messages.ExitedPvpMode);
  419. }
  420. else
  421. {
  422. user.IsInPvpMode = true;
  423. user.SendChatMessage(Messages.EnteredPvpMode);
  424. }
  425.  
  426. user.Hud.Refresh();
  427. }
  428. }
  429. }
  430.  
  431. namespace Oxide.Plugins
  432. {
  433. using System.Linq;
  434.  
  435. public partial class Imperium
  436. {
  437. [ChatCommand("badlands")]
  438. void OnBadlandsCommand(BasePlayer player, string command, string[] args)
  439. {
  440. User user = Users.Get(player);
  441. if (user == null) return;
  442.  
  443. if (!Options.Badlands.Enabled)
  444. {
  445. user.SendChatMessage(Messages.BadlandsDisabled);
  446. return;
  447. }
  448.  
  449. if (args.Length == 0)
  450. {
  451. var areas = Areas.GetAllByType(AreaType.Badlands).Select(a => a.Id);
  452. user.SendChatMessage(Messages.BadlandsList, Util.Format(areas), Options.Taxes.BadlandsGatherBonus);
  453. return;
  454. }
  455.  
  456. if (!user.HasPermission(Permission.AdminBadlands))
  457. {
  458. user.SendChatMessage(Messages.NoPermission);
  459. return;
  460. }
  461.  
  462. var areaIds = args.Skip(1).Select(arg => Util.NormalizeAreaId(arg)).ToArray();
  463.  
  464. switch (args[0].ToLower())
  465. {
  466. case "add":
  467. if (args.Length < 2)
  468. user.SendChatMessage(Messages.Usage, "/badlands add [XY XY XY...]");
  469. else
  470. OnAddBadlandsCommand(user, areaIds);
  471. break;
  472.  
  473. case "remove":
  474. if (args.Length < 2)
  475. user.SendChatMessage(Messages.Usage, "/badlands remove [XY XY XY...]");
  476. else
  477. OnRemoveBadlandsCommand(user, areaIds);
  478. break;
  479.  
  480. case "set":
  481. if (args.Length < 2)
  482. user.SendChatMessage(Messages.Usage, "/badlands set [XY XY XY...]");
  483. else
  484. OnSetBadlandsCommand(user, areaIds);
  485. break;
  486.  
  487. case "clear":
  488. if (args.Length != 1)
  489. user.SendChatMessage(Messages.Usage, "/badlands clear");
  490. else
  491. OnSetBadlandsCommand(user, new string[0]);
  492. break;
  493.  
  494. default:
  495. OnBadlandsHelpCommand(user);
  496. break;
  497. }
  498. }
  499. }
  500. }
  501.  
  502. namespace Oxide.Plugins
  503. {
  504. using System.Collections.Generic;
  505. using System.Linq;
  506.  
  507. public partial class Imperium
  508. {
  509. void OnAddBadlandsCommand(User user, string[] args)
  510. {
  511. var areas = new List<Area>();
  512.  
  513. foreach (string arg in args)
  514. {
  515. Area area = Areas.Get(Util.NormalizeAreaId(arg));
  516.  
  517. if (area == null)
  518. {
  519. user.SendChatMessage(Messages.UnknownArea, arg);
  520. return;
  521. }
  522.  
  523. if (area.Type != AreaType.Wilderness)
  524. {
  525. user.SendChatMessage(Messages.AreaNotWilderness, area.Id);
  526. return;
  527. }
  528.  
  529. areas.Add(area);
  530. }
  531.  
  532. Areas.AddBadlands(areas);
  533.  
  534. user.SendChatMessage(Messages.BadlandsSet, Util.Format(Areas.GetAllByType(AreaType.Badlands)));
  535. Log($"{Util.Format(user)} added {Util.Format(areas)} to badlands");
  536. }
  537. }
  538. }
  539.  
  540. namespace Oxide.Plugins
  541. {
  542. using System.Text;
  543.  
  544. public partial class Imperium
  545. {
  546. void OnBadlandsHelpCommand(User user)
  547. {
  548. var sb = new StringBuilder();
  549.  
  550. sb.AppendLine("Available commands:");
  551. sb.AppendLine(" <color=#ffd479>/badlands add XY [XY XY...]</color>: Add area(s) to the badlands");
  552. sb.AppendLine(" <color=#ffd479>/badlands remove XY [XY XY...]</color>: Remove area(s) from the badlands");
  553. sb.AppendLine(" <color=#ffd479>/badlands set XY [XY XY...]</color>: Set the badlands to a list of areas");
  554. sb.AppendLine(" <color=#ffd479>/badlands clear</color>: Remove all areas from the badlands");
  555. sb.AppendLine(" <color=#ffd479>/badlands help</color>: Prints this message");
  556.  
  557. user.SendChatMessage(sb);
  558. }
  559. }
  560. }
  561.  
  562. namespace Oxide.Plugins
  563. {
  564. using System.Collections.Generic;
  565. using System.Linq;
  566.  
  567. public partial class Imperium
  568. {
  569. void OnRemoveBadlandsCommand(User user, string[] args)
  570. {
  571. var areas = new List<Area>();
  572.  
  573. foreach (string arg in args)
  574. {
  575. Area area = Areas.Get(Util.NormalizeAreaId(arg));
  576.  
  577. if (area == null)
  578. {
  579. user.SendChatMessage(Messages.UnknownArea, arg);
  580. return;
  581. }
  582.  
  583. if (area.Type != AreaType.Badlands)
  584. {
  585. user.SendChatMessage(Messages.AreaNotBadlands, area.Id);
  586. return;
  587. }
  588.  
  589. areas.Add(area);
  590. }
  591.  
  592. Areas.Unclaim(areas);
  593.  
  594. user.SendChatMessage(Messages.BadlandsSet, Util.Format(Areas.GetAllByType(AreaType.Badlands)));
  595. Log($"{Util.Format(user)} removed {Util.Format(areas)} from badlands");
  596. }
  597. }
  598. }
  599.  
  600. namespace Oxide.Plugins
  601. {
  602. using System.Collections.Generic;
  603. using System.Linq;
  604.  
  605. public partial class Imperium
  606. {
  607. void OnSetBadlandsCommand(User user, string[] args)
  608. {
  609. var areas = new List<Area>();
  610.  
  611. foreach (string arg in args)
  612. {
  613. Area area = Areas.Get(Util.NormalizeAreaId(arg));
  614.  
  615. if (area == null)
  616. {
  617. user.SendChatMessage(Messages.UnknownArea, arg);
  618. return;
  619. }
  620.  
  621. if (area.Type != AreaType.Wilderness)
  622. {
  623. user.SendChatMessage(Messages.AreaNotWilderness, area.Id);
  624. return;
  625. }
  626.  
  627. areas.Add(area);
  628. }
  629.  
  630. Areas.Unclaim(Areas.GetAllByType(AreaType.Badlands));
  631. Areas.AddBadlands(areas);
  632.  
  633. user.SendChatMessage(Messages.BadlandsSet, Util.Format(Areas.GetAllByType(AreaType.Badlands)));
  634. Log($"{Util.Format(user)} set badlands to {Util.Format(areas)}");
  635. }
  636. }
  637. }
  638.  
  639. namespace Oxide.Plugins
  640. {
  641. using System.Linq;
  642.  
  643. public partial class Imperium
  644. {
  645. [ChatCommand("claim")]
  646. void OnClaimCommand(BasePlayer player, string command, string[] args)
  647. {
  648. User user = Users.Get(player);
  649. if (user == null) return;
  650.  
  651. if (!Options.Claims.Enabled)
  652. {
  653. user.SendChatMessage(Messages.AreaClaimsDisabled);
  654. return;
  655. }
  656.  
  657. if (args.Length == 0)
  658. {
  659. OnClaimAddCommand(user);
  660. return;
  661. }
  662.  
  663. var restArguments = args.Skip(1).ToArray();
  664.  
  665. switch (args[0].ToLower())
  666. {
  667. case "add":
  668. OnClaimAddCommand(user);
  669. break;
  670. case "remove":
  671. OnClaimRemoveCommand(user);
  672. break;
  673. case "hq":
  674. OnClaimHeadquartersCommand(user);
  675. break;
  676. case "rename":
  677. OnClaimRenameCommand(user, restArguments);
  678. break;
  679. case "give":
  680. OnClaimGiveCommand(user, restArguments);
  681. break;
  682. case "cost":
  683. OnClaimCostCommand(user, restArguments);
  684. break;
  685. case "upkeep":
  686. OnClaimUpkeepCommand(user);
  687. break;
  688. case "show":
  689. OnClaimShowCommand(user, restArguments);
  690. break;
  691. case "list":
  692. OnClaimListCommand(user, restArguments);
  693. break;
  694. case "assign":
  695. OnClaimAssignCommand(user, restArguments);
  696. break;
  697. case "delete":
  698. OnClaimDeleteCommand(user, restArguments);
  699. break;
  700. default:
  701. OnClaimHelpCommand(user);
  702. break;
  703. }
  704. }
  705. }
  706. }
  707.  
  708. namespace Oxide.Plugins
  709. {
  710. public partial class Imperium
  711. {
  712. void OnClaimAddCommand(User user)
  713. {
  714. Faction faction = Factions.GetByMember(user);
  715.  
  716. if (!EnsureUserCanChangeFactionClaims(user, faction))
  717. return;
  718.  
  719. user.SendChatMessage(Messages.SelectClaimCupboardToAdd);
  720. user.BeginInteraction(new AddingClaimInteraction(faction));
  721. }
  722. }
  723. }
  724.  
  725. namespace Oxide.Plugins
  726. {
  727. public partial class Imperium
  728. {
  729. void OnClaimAssignCommand(User user, string[] args)
  730. {
  731. if (!user.HasPermission(Permission.AdminClaims))
  732. {
  733. user.SendChatMessage(Messages.NoPermission);
  734. return;
  735. }
  736.  
  737. if (args.Length == 0)
  738. {
  739. user.SendChatMessage(Messages.Usage, "/claim assign FACTION");
  740. return;
  741. }
  742.  
  743. string factionId = Util.NormalizeFactionId(args[0]);
  744. Faction faction = Factions.Get(factionId);
  745.  
  746. if (faction == null)
  747. {
  748. user.SendChatMessage(Messages.FactionDoesNotExist, factionId);
  749. return;
  750. }
  751.  
  752. user.SendChatMessage(Messages.SelectClaimCupboardToAssign);
  753. user.BeginInteraction(new AssigningClaimInteraction(faction));
  754. }
  755. }
  756. }
  757.  
  758. namespace Oxide.Plugins
  759. {
  760. public partial class Imperium
  761. {
  762. void OnClaimCostCommand(User user, string[] args)
  763. {
  764. Faction faction = Factions.GetByMember(user);
  765.  
  766. if (faction == null)
  767. {
  768. user.SendChatMessage(Messages.NotMemberOfFaction);
  769. return;
  770. }
  771.  
  772. if (faction.MemberCount < Options.Claims.MinFactionMembers)
  773. {
  774. user.SendChatMessage(Messages.FactionTooSmallToOwnLand, Options.Claims.MinFactionMembers);
  775. return;
  776. }
  777.  
  778. if (args.Length > 1)
  779. {
  780. user.SendChatMessage(Messages.Usage, "/claim cost [XY]");
  781. return;
  782. }
  783.  
  784. Area area;
  785. if (args.Length == 0)
  786. area = user.CurrentArea;
  787. else
  788. area = Areas.Get(Util.NormalizeAreaId(args[0]));
  789.  
  790. if (area == null)
  791. {
  792. user.SendChatMessage(Messages.Usage, "/claim cost [XY]");
  793. return;
  794. }
  795.  
  796. if (area.Type == AreaType.Badlands)
  797. {
  798. user.SendChatMessage(Messages.AreaIsBadlands, area.Id);
  799. return;
  800. }
  801. else if (area.Type != AreaType.Wilderness)
  802. {
  803. user.SendChatMessage(Messages.CannotClaimAreaAlreadyClaimed, area.Id, area.FactionId);
  804. return;
  805. }
  806.  
  807. int cost = area.GetClaimCost(faction);
  808. user.SendChatMessage(Messages.ClaimCost, area.Id, faction.Id, cost);
  809. }
  810. }
  811. }
  812.  
  813. namespace Oxide.Plugins
  814. {
  815. using System.Collections.Generic;
  816.  
  817. public partial class Imperium
  818. {
  819. void OnClaimDeleteCommand(User user, string[] args)
  820. {
  821. if (args.Length == 0)
  822. {
  823. user.SendChatMessage(Messages.Usage, "/claim delete XY [XY XY...]");
  824. return;
  825. }
  826.  
  827. if (!user.HasPermission(Permission.AdminClaims))
  828. {
  829. user.SendChatMessage(Messages.NoPermission);
  830. return;
  831. }
  832.  
  833. var areas = new List<Area>();
  834. foreach (string arg in args)
  835. {
  836. Area area = Areas.Get(Util.NormalizeAreaId(arg));
  837.  
  838. if (area.Type == AreaType.Badlands)
  839. {
  840. user.SendChatMessage(Messages.AreaIsBadlands, area.Id);
  841. return;
  842. }
  843.  
  844. if (area.Type == AreaType.Wilderness)
  845. {
  846. user.SendChatMessage(Messages.AreaIsWilderness, area.Id);
  847. return;
  848. }
  849.  
  850. areas.Add(area);
  851. }
  852.  
  853. foreach (Area area in areas)
  854. {
  855. PrintToChat(Messages.AreaClaimDeletedAnnouncement, area.FactionId, area.Id);
  856. Log($"{Util.Format(user)} deleted {area.FactionId}'s claim on {area.Id}");
  857. }
  858.  
  859. Areas.Unclaim(areas);
  860. }
  861. }
  862. }
  863.  
  864. namespace Oxide.Plugins
  865. {
  866. public partial class Imperium
  867. {
  868. void OnClaimGiveCommand(User user, string[] args)
  869. {
  870. if (args.Length == 0)
  871. {
  872. user.SendChatMessage(Messages.Usage, "/claim give FACTION");
  873. return;
  874. }
  875.  
  876. Faction sourceFaction = Factions.GetByMember(user);
  877.  
  878. if (!EnsureUserCanChangeFactionClaims(user, sourceFaction))
  879. return;
  880.  
  881. string factionId = Util.NormalizeFactionId(args[0]);
  882. Faction targetFaction = Factions.Get(factionId);
  883.  
  884. if (targetFaction == null)
  885. {
  886. user.SendChatMessage(Messages.FactionDoesNotExist, factionId);
  887. return;
  888. }
  889.  
  890. user.SendChatMessage(Messages.SelectClaimCupboardToTransfer);
  891. user.BeginInteraction(new TransferringClaimInteraction(sourceFaction, targetFaction));
  892. }
  893. }
  894. }
  895.  
  896. namespace Oxide.Plugins
  897. {
  898. public partial class Imperium
  899. {
  900. void OnClaimHeadquartersCommand(User user)
  901. {
  902. Faction faction = Factions.GetByMember(user);
  903.  
  904. if (!EnsureUserCanChangeFactionClaims(user, faction))
  905. return;
  906.  
  907. user.SendChatMessage(Messages.SelectClaimCupboardForHeadquarters);
  908. user.BeginInteraction(new SelectingHeadquartersInteraction(faction));
  909. }
  910. }
  911. }
  912.  
  913. namespace Oxide.Plugins
  914. {
  915. using System.Text;
  916.  
  917. public partial class Imperium
  918. {
  919. void OnClaimHelpCommand(User user)
  920. {
  921. var sb = new StringBuilder();
  922.  
  923. sb.AppendLine("Available commands:");
  924. sb.AppendLine(" <color=#ffd479>/claim</color>: Add a claim for your faction");
  925. sb.AppendLine(" <color=#ffd479>/claim hq</color>: Select your faction's headquarters");
  926. sb.AppendLine(" <color=#ffd479>/claim remove</color>: Remove a claim for your faction (no undo!)");
  927. sb.AppendLine(
  928. " <color=#ffd479>/claim give FACTION</color>: Give a claimed area to another faction (no undo!)");
  929. sb.AppendLine(" <color=#ffd479>/claim rename XY \"NAME\"</color>: Rename an area claimed by your faction");
  930. sb.AppendLine(" <color=#ffd479>/claim show XY</color>: Show who owns an area");
  931. sb.AppendLine(" <color=#ffd479>/claim list FACTION</color>: List all areas claimed for a faction");
  932. sb.AppendLine(" <color=#ffd479>/claim cost [XY]</color>: Show the cost for your faction to claim an area");
  933.  
  934. if (!Options.Upkeep.Enabled)
  935. sb.AppendLine(
  936. " <color=#ffd479>/claim upkeep</color>: Show information about upkeep costs for your faction");
  937.  
  938. sb.AppendLine(" <color=#ffd479>/claim help</color>: Prints this message");
  939.  
  940. if (user.HasPermission(Permission.AdminClaims))
  941. {
  942. sb.AppendLine("Admin commands:");
  943. sb.AppendLine(
  944. " <color=#ffd479>/claim assign FACTION</color>: Use the hammer to assign a claim to another faction");
  945. sb.AppendLine(
  946. " <color=#ffd479>/claim delete XY [XY XY XY...]</color>: Remove the claim on the specified areas (no undo!)");
  947. }
  948.  
  949. user.SendChatMessage(sb);
  950. }
  951. }
  952. }
  953.  
  954. namespace Oxide.Plugins
  955. {
  956. using System;
  957. using System.Linq;
  958. using System.Text;
  959.  
  960. public partial class Imperium
  961. {
  962. void OnClaimListCommand(User user, string[] args)
  963. {
  964. if (args.Length != 1)
  965. {
  966. user.SendChatMessage(Messages.Usage, "/claim list FACTION");
  967. return;
  968. }
  969.  
  970. string factionId = Util.NormalizeFactionId(args[0]);
  971. Faction faction = Factions.Get(factionId);
  972.  
  973. if (faction == null)
  974. {
  975. user.SendChatMessage(Messages.FactionDoesNotExist, factionId);
  976. return;
  977. }
  978.  
  979. Area[] areas = Areas.GetAllClaimedByFaction(faction);
  980. Area headquarters = areas.FirstOrDefault(a => a.Type == AreaType.Headquarters);
  981.  
  982. var sb = new StringBuilder();
  983.  
  984. if (areas.Length == 0)
  985. {
  986. sb.AppendFormat(String.Format("<color=#ffd479>[{0}]</color> has no land holdings.", factionId));
  987. }
  988. else
  989. {
  990. float percentageOfMap = (areas.Length / (float) Areas.Count) * 100;
  991. sb.AppendLine(String.Format("<color=#ffd479>[{0}] owns {1} tiles ({2:F2}% of the known world)</color>",
  992. faction.Id, areas.Length, percentageOfMap));
  993. sb.AppendLine(String.Format("Headquarters: {0}", (headquarters == null) ? "Unknown" : headquarters.Id));
  994. sb.AppendLine(String.Format("Areas claimed: {0}", Util.Format(areas)));
  995. }
  996.  
  997. user.SendChatMessage(sb);
  998. }
  999. }
  1000. }
  1001.  
  1002. namespace Oxide.Plugins
  1003. {
  1004. public partial class Imperium
  1005. {
  1006. void OnClaimRemoveCommand(User user)
  1007. {
  1008. Faction faction = Factions.GetByMember(user);
  1009.  
  1010. if (!EnsureUserCanChangeFactionClaims(user, faction))
  1011. return;
  1012.  
  1013. user.SendChatMessage(Messages.SelectClaimCupboardToRemove);
  1014. user.BeginInteraction(new RemovingClaimInteraction(faction));
  1015. }
  1016. }
  1017. }
  1018.  
  1019. namespace Oxide.Plugins
  1020. {
  1021. using System;
  1022.  
  1023. public partial class Imperium
  1024. {
  1025. void OnClaimRenameCommand(User user, string[] args)
  1026. {
  1027. Faction faction = Factions.GetByMember(user);
  1028.  
  1029. if (!EnsureUserCanChangeFactionClaims(user, faction))
  1030. return;
  1031.  
  1032. if (args.Length != 2)
  1033. {
  1034. user.SendChatMessage(Messages.Usage, "/claim rename XY \"NAME\"");
  1035. return;
  1036. }
  1037.  
  1038. var areaId = Util.NormalizeAreaId(args[0]);
  1039. var name = Util.NormalizeAreaName(args[1]);
  1040.  
  1041. if (name == null || name.Length < Options.Claims.MinAreaNameLength ||
  1042. name.Length > Options.Claims.MaxAreaNameLength)
  1043. {
  1044. user.SendChatMessage(Messages.InvalidAreaName, Options.Claims.MinAreaNameLength,
  1045. Options.Claims.MaxAreaNameLength);
  1046. return;
  1047. }
  1048.  
  1049. Area area = Areas.Get(areaId);
  1050.  
  1051. if (area == null)
  1052. {
  1053. user.SendChatMessage(Messages.UnknownArea, areaId);
  1054. return;
  1055. }
  1056.  
  1057. if (area.FactionId != faction.Id)
  1058. {
  1059. user.SendChatMessage(Messages.AreaNotOwnedByYourFaction, area.Id);
  1060. return;
  1061. }
  1062.  
  1063. user.SendChatMessage(Messages.AreaRenamed, area.Id, name);
  1064. Log($"{Util.Format(user)} renamed {area.Id} to {name}");
  1065.  
  1066. area.Name = name;
  1067. }
  1068. }
  1069. }
  1070.  
  1071. namespace Oxide.Plugins
  1072. {
  1073. public partial class Imperium
  1074. {
  1075. void OnClaimShowCommand(User user, string[] args)
  1076. {
  1077. if (args.Length != 1)
  1078. {
  1079. user.SendChatMessage(Messages.Usage, "/claim show XY");
  1080. return;
  1081. }
  1082.  
  1083. Area area = Areas.Get(Util.NormalizeAreaId(args[0]));
  1084.  
  1085. switch (area.Type)
  1086. {
  1087. case AreaType.Badlands:
  1088. user.SendChatMessage(Messages.AreaIsBadlands, area.Id);
  1089. return;
  1090. case AreaType.Claimed:
  1091. user.SendChatMessage(Messages.AreaIsClaimed, area.Id, area.FactionId);
  1092. return;
  1093. case AreaType.Headquarters:
  1094. user.SendChatMessage(Messages.AreaIsHeadquarters, area.Id, area.FactionId);
  1095. return;
  1096. default:
  1097. user.SendChatMessage(Messages.AreaIsWilderness, area.Id);
  1098. return;
  1099. }
  1100. }
  1101. }
  1102. }
  1103.  
  1104. namespace Oxide.Plugins
  1105. {
  1106. using System;
  1107.  
  1108. public partial class Imperium
  1109. {
  1110. void OnClaimUpkeepCommand(User user)
  1111. {
  1112. if (!Options.Upkeep.Enabled)
  1113. {
  1114. user.SendChatMessage(Messages.UpkeepDisabled);
  1115. return;
  1116. }
  1117.  
  1118. Faction faction = Factions.GetByMember(user);
  1119.  
  1120. if (faction == null)
  1121. {
  1122. user.SendChatMessage(Messages.NotMemberOfFaction);
  1123. return;
  1124. }
  1125.  
  1126. if (faction.MemberCount < Options.Claims.MinFactionMembers)
  1127. {
  1128. user.SendChatMessage(Messages.FactionTooSmallToOwnLand, Options.Claims.MinFactionMembers);
  1129. return;
  1130. }
  1131.  
  1132. Area[] areas = Areas.GetAllClaimedByFaction(faction);
  1133.  
  1134. if (areas.Length == 0)
  1135. {
  1136. user.SendChatMessage(Messages.NoAreasClaimed);
  1137. return;
  1138. }
  1139.  
  1140. int upkeep = faction.GetUpkeepPerPeriod();
  1141. var nextPaymentHours = (int) faction.NextUpkeepPaymentTime.Subtract(DateTime.UtcNow).TotalHours;
  1142.  
  1143. if (nextPaymentHours > 0)
  1144. user.SendChatMessage(Messages.UpkeepCost, upkeep, areas.Length, faction.Id, nextPaymentHours);
  1145. else
  1146. user.SendChatMessage(Messages.UpkeepCostOverdue, upkeep, areas.Length, faction.Id, nextPaymentHours);
  1147. }
  1148. }
  1149. }
  1150.  
  1151. namespace Oxide.Plugins
  1152. {
  1153. using System.Linq;
  1154.  
  1155. public partial class Imperium
  1156. {
  1157. [ChatCommand("faction")]
  1158. void OnFactionCommand(BasePlayer player, string command, string[] args)
  1159. {
  1160. User user = Users.Get(player);
  1161. if (user == null) return;
  1162.  
  1163. if (args.Length == 0)
  1164. {
  1165. OnFactionShowCommand(user);
  1166. return;
  1167. }
  1168.  
  1169. var restArguments = args.Skip(1).ToArray();
  1170.  
  1171. switch (args[0].ToLower())
  1172. {
  1173. case "create":
  1174. OnFactionCreateCommand(user, restArguments);
  1175. break;
  1176. case "join":
  1177. OnFactionJoinCommand(user, restArguments);
  1178. break;
  1179. case "leave":
  1180. OnFactionLeaveCommand(user, restArguments);
  1181. break;
  1182. case "invite":
  1183. OnFactionInviteCommand(user, restArguments);
  1184. break;
  1185. case "kick":
  1186. OnFactionKickCommand(user, restArguments);
  1187. break;
  1188. case "promote":
  1189. OnFactionPromoteCommand(user, restArguments);
  1190. break;
  1191. case "demote":
  1192. OnFactionDemoteCommand(user, restArguments);
  1193. break;
  1194. case "disband":
  1195. OnFactionDisbandCommand(user, restArguments);
  1196. break;
  1197. case "help":
  1198. default:
  1199. OnFactionHelpCommand(user);
  1200. break;
  1201. }
  1202. }
  1203.  
  1204. [ChatCommand("clan")]
  1205. void OnClanCommand(BasePlayer player, string command, string[] args)
  1206. {
  1207. OnFactionCommand(player, command, args);
  1208. }
  1209. }
  1210. }
  1211.  
  1212. namespace Oxide.Plugins
  1213. {
  1214. using System;
  1215.  
  1216. public partial class Imperium
  1217. {
  1218. [ChatCommand("f")]
  1219. void OnFactionChatCommand(BasePlayer player, string command, string[] args)
  1220. {
  1221. User user = Users.Get(player);
  1222. if (user == null) return;
  1223.  
  1224. string message = String.Join(" ", args).Trim();
  1225.  
  1226. if (message.Length == 0)
  1227. {
  1228. user.SendChatMessage(Messages.Usage, "/f MESSAGE...");
  1229. return;
  1230. }
  1231.  
  1232. Faction faction = Factions.GetByMember(user);
  1233.  
  1234. if (faction == null)
  1235. {
  1236. user.SendChatMessage(Messages.NotMemberOfFaction);
  1237. return;
  1238. }
  1239.  
  1240. faction.SendChatMessage("<color=#a1ff46>(FACTION)</color> {0}: {1}", user.UserName, message);
  1241. Puts("[FACTION] {0} - {1}: {2}", faction.Id, user.UserName, message);
  1242. }
  1243.  
  1244. [ChatCommand("c")]
  1245. void OnClanChatCommand(BasePlayer player, string command, string[] args)
  1246. {
  1247. OnFactionChatCommand(player, command, args);
  1248. }
  1249. }
  1250. }
  1251.  
  1252. namespace Oxide.Plugins
  1253. {
  1254. public partial class Imperium
  1255. {
  1256. void OnFactionCreateCommand(User user, string[] args)
  1257. {
  1258. if (!user.HasPermission(Permission.ManageFactions))
  1259. {
  1260. user.SendChatMessage(Messages.NoPermission);
  1261. return;
  1262. }
  1263.  
  1264. if (user.Faction != null)
  1265. {
  1266. user.SendChatMessage(Messages.AlreadyMemberOfFaction);
  1267. return;
  1268. }
  1269.  
  1270. if (args.Length != 1)
  1271. {
  1272. user.SendChatMessage(Messages.Usage, "/faction create NAME");
  1273. return;
  1274. }
  1275.  
  1276. string id = Util.RemoveSpecialCharacters(args[0].Replace(" ", ""));
  1277.  
  1278. if (id.Length < Options.Factions.MinFactionNameLength || id.Length > Options.Factions.MaxFactionNameLength)
  1279. {
  1280. user.SendChatMessage(Messages.InvalidFactionName, Options.Factions.MinFactionNameLength,
  1281. Options.Factions.MaxFactionNameLength);
  1282. return;
  1283. }
  1284.  
  1285. if (Factions.Exists(id))
  1286. {
  1287. user.SendChatMessage(Messages.FactionAlreadyExists, id);
  1288. return;
  1289. }
  1290.  
  1291. PrintToChat(Messages.FactionCreatedAnnouncement, id);
  1292. Log($"{Util.Format(user)} created faction {id}");
  1293.  
  1294. Faction faction = Factions.Create(id, user);
  1295. user.SetFaction(faction);
  1296. }
  1297. }
  1298. }
  1299.  
  1300. namespace Oxide.Plugins
  1301. {
  1302. public partial class Imperium
  1303. {
  1304. void OnFactionDemoteCommand(User user, string[] args)
  1305. {
  1306. if (args.Length != 1)
  1307. {
  1308. user.SendChatMessage(Messages.Usage, "/faction demote \"PLAYER\"");
  1309. return;
  1310. }
  1311.  
  1312. Faction faction = Factions.GetByMember(user);
  1313.  
  1314. if (faction == null || !faction.HasLeader(user))
  1315. {
  1316. user.SendChatMessage(Messages.NotLeaderOfFaction);
  1317. return;
  1318. }
  1319.  
  1320. User member = Users.Find(args[0]);
  1321.  
  1322. if (member == null)
  1323. {
  1324. user.SendChatMessage(Messages.InvalidUser, args[0]);
  1325. return;
  1326. }
  1327.  
  1328. if (!faction.HasMember(member))
  1329. {
  1330. user.SendChatMessage(Messages.UserIsNotMemberOfFaction, member.UserName, faction.Id);
  1331. return;
  1332. }
  1333.  
  1334. if (faction.HasOwner(member))
  1335. {
  1336. user.SendChatMessage(Messages.CannotPromoteOrDemoteOwnerOfFaction, member.UserName, faction.Id);
  1337. return;
  1338. }
  1339.  
  1340. if (!faction.HasManager(member))
  1341. {
  1342. user.SendChatMessage(Messages.UserIsNotManagerOfFaction, member.UserName, faction.Id);
  1343. return;
  1344. }
  1345.  
  1346. user.SendChatMessage(Messages.ManagerRemoved, member.UserName, faction.Id);
  1347. Log($"{Util.Format(user)} demoted {Util.Format(member)} in faction {faction.Id}");
  1348.  
  1349. faction.Demote(member);
  1350. }
  1351. }
  1352. }
  1353.  
  1354. namespace Oxide.Plugins
  1355. {
  1356. public partial class Imperium
  1357. {
  1358. void OnFactionDisbandCommand(User user, string[] args)
  1359. {
  1360. if (args.Length != 1 || args[0].ToLowerInvariant() != "forever")
  1361. {
  1362. user.SendChatMessage(Messages.Usage, "/faction disband forever");
  1363. return;
  1364. }
  1365.  
  1366. Faction faction = user.Faction;
  1367.  
  1368. if (faction == null || !faction.HasLeader(user))
  1369. {
  1370. user.SendChatMessage(Messages.NotLeaderOfFaction);
  1371. return;
  1372. }
  1373.  
  1374. PrintToChat(Messages.FactionDisbandedAnnouncement, faction.Id);
  1375. Log($"{Util.Format(user)} disbanded faction {faction.Id}");
  1376.  
  1377. Factions.Disband(faction);
  1378. }
  1379. }
  1380. }
  1381.  
  1382. namespace Oxide.Plugins
  1383. {
  1384. using System.Text;
  1385.  
  1386. public partial class Imperium
  1387. {
  1388. void OnFactionHelpCommand(User user)
  1389. {
  1390. var sb = new StringBuilder();
  1391.  
  1392. sb.AppendLine("Available commands:");
  1393. sb.AppendLine(" <color=#ffd479>/faction</color>: Show information about your faction");
  1394. sb.AppendLine(
  1395. " <color=#ffd479>/f MESSAGE...</color>: Send a message to all online members of your faction");
  1396.  
  1397. if (user.HasPermission(Permission.ManageFactions))
  1398. sb.AppendLine(" <color=#ffd479>/faction create</color>: Create a new faction");
  1399.  
  1400. sb.AppendLine(" <color=#ffd479>/faction join FACTION</color>: Join a faction if you have been invited");
  1401. sb.AppendLine(" <color=#ffd479>/faction leave</color>: Leave your current faction");
  1402. sb.AppendLine(
  1403. " <color=#ffd479>/faction invite \"PLAYER\"</color>: Invite another player to join your faction");
  1404. sb.AppendLine(" <color=#ffd479>/faction kick \"PLAYER\"</color>: Kick a player out of your faction");
  1405. sb.AppendLine(" <color=#ffd479>/faction promote \"PLAYER\"</color>: Promote a faction member to manager");
  1406. sb.AppendLine(" <color=#ffd479>/faction demote \"PLAYER\"</color>: Remove a faction member as manager");
  1407. sb.AppendLine(
  1408. " <color=#ffd479>/faction disband forever</color>: Disband your faction immediately (no undo!)");
  1409. sb.AppendLine(" <color=#ffd479>/faction help</color>: Prints this message");
  1410.  
  1411. user.SendChatMessage(sb);
  1412. }
  1413. }
  1414. }
  1415.  
  1416. namespace Oxide.Plugins
  1417. {
  1418. public partial class Imperium
  1419. {
  1420. void OnFactionInviteCommand(User user, string[] args)
  1421. {
  1422. if (args.Length != 1)
  1423. {
  1424. user.SendChatMessage(Messages.Usage, "/faction invite \"PLAYER\"");
  1425. return;
  1426. }
  1427.  
  1428. Faction faction = Factions.GetByMember(user);
  1429.  
  1430. if (faction == null || !faction.HasLeader(user))
  1431. {
  1432. user.SendChatMessage(Messages.NotLeaderOfFaction);
  1433. return;
  1434. }
  1435.  
  1436. User member = Users.Find(args[0]);
  1437.  
  1438. if (member == null)
  1439. {
  1440. user.SendChatMessage(Messages.InvalidUser, args[0]);
  1441. return;
  1442. }
  1443.  
  1444. if (faction.HasMember(member))
  1445. {
  1446. user.SendChatMessage(Messages.UserIsAlreadyMemberOfFaction, member.UserName, faction.Id);
  1447. return;
  1448. }
  1449.  
  1450. int? maxMembers = Options.Factions.MaxMembers;
  1451. if (maxMembers != null && faction.MemberCount >= maxMembers)
  1452. {
  1453. user.SendChatMessage(Messages.FactionHasTooManyMembers, faction.Id, faction.MemberCount);
  1454. return;
  1455. }
  1456.  
  1457. member.SendChatMessage(Messages.InviteReceived, user.UserName, faction.Id);
  1458. user.SendChatMessage(Messages.InviteAdded, member.UserName, faction.Id);
  1459.  
  1460. Log($"{Util.Format(user)} invited {Util.Format(member)} to faction {faction.Id}");
  1461.  
  1462. faction.AddInvite(member);
  1463. }
  1464. }
  1465. }
  1466.  
  1467. namespace Oxide.Plugins
  1468. {
  1469. public partial class Imperium
  1470. {
  1471. void OnFactionJoinCommand(User user, string[] args)
  1472. {
  1473. if (args.Length != 1)
  1474. {
  1475. user.SendChatMessage(Messages.Usage, "/faction join FACTION");
  1476. return;
  1477. }
  1478.  
  1479. if (user.Faction != null)
  1480. {
  1481. user.SendChatMessage(Messages.AlreadyMemberOfFaction);
  1482. return;
  1483. }
  1484.  
  1485. Faction faction = Factions.Get(args[0]);
  1486.  
  1487. if (faction == null)
  1488. {
  1489. user.SendChatMessage(Messages.FactionDoesNotExist, args[0]);
  1490. return;
  1491. }
  1492.  
  1493. if (!faction.HasInvite(user))
  1494. {
  1495. user.SendChatMessage(Messages.CannotJoinFactionNotInvited, faction.Id);
  1496. return;
  1497. }
  1498.  
  1499. user.SendChatMessage(Messages.YouJoinedFaction, faction.Id);
  1500. PrintToChat(Messages.FactionMemberJoinedAnnouncement, user.UserName, faction.Id);
  1501. Log($"{Util.Format(user)} joined faction {faction.Id}");
  1502.  
  1503. faction.AddMember(user);
  1504. user.SetFaction(faction);
  1505. }
  1506. }
  1507. }
  1508.  
  1509. namespace Oxide.Plugins
  1510. {
  1511. public partial class Imperium
  1512. {
  1513. void OnFactionKickCommand(User user, string[] args)
  1514. {
  1515. if (args.Length != 1)
  1516. {
  1517. user.SendChatMessage(Messages.Usage, "/faction kick \"PLAYER\"");
  1518. return;
  1519. }
  1520.  
  1521. Faction faction = user.Faction;
  1522.  
  1523. if (faction == null || !faction.HasLeader(user))
  1524. {
  1525. user.SendChatMessage(Messages.NotLeaderOfFaction);
  1526. return;
  1527. }
  1528.  
  1529. User member = Users.Find(args[0]);
  1530.  
  1531. if (member == null)
  1532. {
  1533. user.SendChatMessage(Messages.InvalidUser, args[0]);
  1534. return;
  1535. }
  1536.  
  1537. if (!faction.HasMember(member))
  1538. {
  1539. user.SendChatMessage(Messages.UserIsNotMemberOfFaction, member.UserName, faction.Id);
  1540. return;
  1541. }
  1542.  
  1543. if (faction.HasLeader(member))
  1544. {
  1545. user.SendChatMessage(Messages.CannotKickLeaderOfFaction, member.UserName, faction.Id);
  1546. return;
  1547. }
  1548.  
  1549. user.SendChatMessage(Messages.MemberRemoved, member.UserName, faction.Id);
  1550. PrintToChat(Messages.FactionMemberLeftAnnouncement, member.UserName, faction.Id);
  1551.  
  1552. Log($"{Util.Format(user)} kicked {Util.Format(member)} from faction {faction.Id}");
  1553.  
  1554. faction.RemoveMember(member);
  1555. member.SetFaction(null);
  1556. }
  1557. }
  1558. }
  1559.  
  1560. namespace Oxide.Plugins
  1561. {
  1562. public partial class Imperium
  1563. {
  1564. void OnFactionLeaveCommand(User user, string[] args)
  1565. {
  1566. if (args.Length != 0)
  1567. {
  1568. user.SendChatMessage(Messages.Usage, "/faction leave");
  1569. return;
  1570. }
  1571.  
  1572. Faction faction = user.Faction;
  1573.  
  1574. if (faction == null)
  1575. {
  1576. user.SendChatMessage(Messages.NotMemberOfFaction);
  1577. return;
  1578. }
  1579.  
  1580. if (faction.MemberCount == 1)
  1581. {
  1582. PrintToChat(Messages.FactionDisbandedAnnouncement, faction.Id);
  1583. Log($"{Util.Format(user)} disbanded faction {faction.Id} by leaving as its only member");
  1584. Factions.Disband(faction);
  1585. return;
  1586. }
  1587.  
  1588. user.SendChatMessage(Messages.YouLeftFaction, faction.Id);
  1589. PrintToChat(Messages.FactionMemberLeftAnnouncement, user.UserName, faction.Id);
  1590.  
  1591. Log($"{Util.Format(user)} left faction {faction.Id}");
  1592.  
  1593. faction.RemoveMember(user);
  1594. user.SetFaction(null);
  1595. }
  1596. }
  1597. }
  1598.  
  1599. namespace Oxide.Plugins
  1600. {
  1601. public partial class Imperium
  1602. {
  1603. void OnFactionPromoteCommand(User user, string[] args)
  1604. {
  1605. if (args.Length != 1)
  1606. {
  1607. user.SendChatMessage(Messages.Usage, "/faction promote \"PLAYER\"");
  1608. return;
  1609. }
  1610.  
  1611. Faction faction = Factions.GetByMember(user);
  1612.  
  1613. if (faction == null || !faction.HasLeader(user))
  1614. {
  1615. user.SendChatMessage(Messages.NotLeaderOfFaction);
  1616. return;
  1617. }
  1618.  
  1619. User member = Users.Find(args[0]);
  1620.  
  1621. if (member == null)
  1622. {
  1623. user.SendChatMessage(Messages.InvalidUser, args[0]);
  1624. return;
  1625. }
  1626.  
  1627. if (!faction.HasMember(member))
  1628. {
  1629. user.SendChatMessage(Messages.UserIsNotMemberOfFaction, member.UserName, faction.Id);
  1630. return;
  1631. }
  1632.  
  1633. if (faction.HasOwner(member))
  1634. {
  1635. user.SendChatMessage(Messages.CannotPromoteOrDemoteOwnerOfFaction, member.UserName, faction.Id);
  1636. return;
  1637. }
  1638.  
  1639. if (faction.HasManager(member))
  1640. {
  1641. user.SendChatMessage(Messages.UserIsAlreadyManagerOfFaction, member.UserName, faction.Id);
  1642. return;
  1643. }
  1644.  
  1645. user.SendChatMessage(Messages.ManagerAdded, member.UserName, faction.Id);
  1646. Log($"{Util.Format(user)} promoted {Util.Format(member)} in faction {faction.Id}");
  1647.  
  1648. faction.Promote(member);
  1649. }
  1650. }
  1651. }
  1652.  
  1653. namespace Oxide.Plugins
  1654. {
  1655. using System.Text;
  1656.  
  1657. public partial class Imperium
  1658. {
  1659. void OnFactionShowCommand(User user)
  1660. {
  1661. Faction faction = user.Faction;
  1662.  
  1663. if (faction == null)
  1664. {
  1665. user.SendChatMessage(Messages.NotMemberOfFaction);
  1666. return;
  1667. }
  1668.  
  1669. var sb = new StringBuilder();
  1670.  
  1671. sb.Append("You are ");
  1672. if (faction.HasOwner(user))
  1673. sb.Append("the owner");
  1674. else if (faction.HasManager(user))
  1675. sb.Append("a manager");
  1676. else
  1677. sb.Append("a member");
  1678.  
  1679. sb.AppendLine($"of <color=#ffd479>[{faction.Id}]</color>.");
  1680.  
  1681. User[] activeMembers = faction.GetAllActiveMembers();
  1682.  
  1683. sb.AppendLine(
  1684. $"<color=#ffd479>{faction.MemberCount}</color> member(s), <color=#ffd479>{activeMembers.Length}</color> online:");
  1685. sb.Append(" ");
  1686.  
  1687. foreach (User member in activeMembers)
  1688. sb.Append($"<color=#ffd479>{member.UserName}</color>, ");
  1689.  
  1690. sb.Remove(sb.Length - 2, 2);
  1691. sb.AppendLine();
  1692.  
  1693. if (faction.InviteIds.Count > 0)
  1694. {
  1695. User[] activeInvitedUsers = faction.GetAllActiveInvitedUsers();
  1696.  
  1697. sb.AppendLine(
  1698. $"<color=#ffd479>{faction.InviteIds.Count}</color> invited player(s), <color=#ffd479>{activeInvitedUsers.Length}</color> online:");
  1699. sb.Append(" ");
  1700.  
  1701. foreach (User invitedUser in activeInvitedUsers)
  1702. sb.Append($"<color=#ffd479>{invitedUser.UserName}</color>, ");
  1703.  
  1704. sb.Remove(sb.Length - 2, 2);
  1705. sb.AppendLine();
  1706. }
  1707.  
  1708. user.SendChatMessage(sb);
  1709. }
  1710. }
  1711. }
  1712.  
  1713. namespace Oxide.Plugins
  1714. {
  1715. public partial class Imperium
  1716. {
  1717. [ConsoleCommand("imperium.images.refresh")]
  1718. void OnRefreshImagesConsoleCommand(ConsoleSystem.Arg arg)
  1719. {
  1720. if (!arg.IsAdmin) return;
  1721. arg.ReplyWith("Refreshing images...");
  1722. Hud.RefreshAllImages();
  1723. }
  1724. }
  1725. }
  1726.  
  1727. namespace Oxide.Plugins
  1728. {
  1729. using System.Linq;
  1730.  
  1731. public partial class Imperium
  1732. {
  1733. [ChatCommand("pin")]
  1734. void OnPinCommand(BasePlayer player, string command, string[] args)
  1735. {
  1736. User user = Users.Get(player);
  1737. if (user == null) return;
  1738.  
  1739. if (!Options.Map.PinsEnabled)
  1740. {
  1741. user.SendChatMessage(Messages.PinsDisabled);
  1742. return;
  1743. }
  1744.  
  1745. ;
  1746.  
  1747. if (args.Length == 0)
  1748. {
  1749. OnPinHelpCommand(user);
  1750. return;
  1751. }
  1752.  
  1753. var restArguments = args.Skip(1).ToArray();
  1754.  
  1755. switch (args[0].ToLower())
  1756. {
  1757. case "add":
  1758. OnPinAddCommand(user, restArguments);
  1759. break;
  1760. case "remove":
  1761. OnPinRemoveCommand(user, restArguments);
  1762. break;
  1763. case "list":
  1764. OnPinListCommand(user, restArguments);
  1765. break;
  1766. case "delete":
  1767. OnPinDeleteCommand(user, restArguments);
  1768. break;
  1769. case "help":
  1770. default:
  1771. OnPinHelpCommand(user);
  1772. break;
  1773. }
  1774. }
  1775. }
  1776. }
  1777.  
  1778. namespace Oxide.Plugins
  1779. {
  1780. using System;
  1781. using System.Collections.Generic;
  1782. using UnityEngine;
  1783.  
  1784. public partial class Imperium
  1785. {
  1786. void OnPinAddCommand(User user, string[] args)
  1787. {
  1788. if (args.Length != 2)
  1789. {
  1790. user.SendChatMessage(Messages.Usage, "/pin add TYPE \"NAME\"");
  1791. return;
  1792. }
  1793.  
  1794. if (user.Faction == null)
  1795. {
  1796. user.SendChatMessage(Messages.NotMemberOfFaction);
  1797. return;
  1798. }
  1799.  
  1800. Area area = user.CurrentArea;
  1801.  
  1802. if (area == null)
  1803. {
  1804. user.SendChatMessage(Messages.YouAreInTheGreatUnknown);
  1805. return;
  1806. }
  1807.  
  1808. if (area.FactionId == null || area.FactionId != user.Faction.Id)
  1809. {
  1810. user.SendChatMessage(Messages.AreaNotOwnedByYourFaction, area.Id);
  1811. return;
  1812. }
  1813.  
  1814. PinType type;
  1815. if (!Util.TryParseEnum(args[0], out type))
  1816. {
  1817. user.SendChatMessage(Messages.InvalidPinType, args[0]);
  1818. return;
  1819. }
  1820.  
  1821. string name = Util.NormalizePinName(args[1]);
  1822. if (name == null || name.Length < Options.Map.MinPinNameLength ||
  1823. name.Length > Options.Map.MaxPinNameLength)
  1824. {
  1825. user.SendChatMessage(Messages.InvalidPinName, Options.Map.MinPinNameLength,
  1826. Options.Map.MaxPinNameLength);
  1827. return;
  1828. }
  1829.  
  1830. Pin existingPin = Pins.Get(name);
  1831. if (existingPin != null)
  1832. {
  1833. user.SendChatMessage(Messages.CannotCreatePinAlreadyExists, existingPin.Name, existingPin.AreaId);
  1834. return;
  1835. }
  1836.  
  1837. if (Options.Map.PinCost > 0)
  1838. {
  1839. ItemDefinition scrapDef = ItemManager.FindItemDefinition("scrap");
  1840. List<Item> stacks = user.Player.inventory.FindItemIDs(scrapDef.itemid);
  1841.  
  1842. if (!Instance.TryCollectFromStacks(scrapDef, stacks, Options.Map.PinCost))
  1843. {
  1844. user.SendChatMessage(Messages.CannotCreatePinCannotAfford, Options.Map.PinCost);
  1845. return;
  1846. }
  1847. }
  1848.  
  1849. Vector3 position = user.Player.transform.position;
  1850.  
  1851. var pin = new Pin(position, area, user, type, name);
  1852. Pins.Add(pin);
  1853.  
  1854. PrintToChat(Messages.PinAddedAnnouncement, user.Faction.Id, name, type.ToString().ToLower(), area.Id);
  1855. }
  1856. }
  1857. }
  1858.  
  1859. namespace Oxide.Plugins
  1860. {
  1861. using System;
  1862.  
  1863. public partial class Imperium
  1864. {
  1865. void OnPinDeleteCommand(User user, string[] args)
  1866. {
  1867. if (args.Length != 1)
  1868. {
  1869. user.SendChatMessage(Messages.Usage, "/pin delete \"NAME\"");
  1870. return;
  1871. }
  1872.  
  1873. if (!user.HasPermission(Permission.AdminPins))
  1874. {
  1875. user.SendChatMessage(Messages.NoPermission);
  1876. return;
  1877. }
  1878.  
  1879. string name = Util.NormalizePinName(args[0]);
  1880. Pin pin = Pins.Get(name);
  1881.  
  1882. if (pin == null)
  1883. {
  1884. user.SendChatMessage(Messages.UnknownPin, name);
  1885. return;
  1886. }
  1887.  
  1888. Pins.Remove(pin);
  1889. user.SendChatMessage(Messages.PinRemoved, pin.Name);
  1890. }
  1891. }
  1892. }
  1893.  
  1894. namespace Oxide.Plugins
  1895. {
  1896. using System;
  1897. using System.Collections.Generic;
  1898. using System.Linq;
  1899. using System.Text;
  1900.  
  1901. public partial class Imperium
  1902. {
  1903. void OnPinHelpCommand(User user)
  1904. {
  1905. var sb = new StringBuilder();
  1906.  
  1907. sb.AppendLine("Available commands:");
  1908. sb.AppendLine(" <color=#ffd479>/pin list [TYPE]</color>: List all pins (or all of a certain type)");
  1909. sb.AppendLine(" <color=#ffd479>/pin add TYPE \"NAME\"</color>: Create a pin at your current location");
  1910. sb.AppendLine(" <color=#ffd479>/pin remove \"NAME\"</color>: Remove a pin you created");
  1911. sb.AppendLine(" <color=#ffd479>/pin help</color>: Prints this message");
  1912.  
  1913. if (user.HasPermission(Permission.AdminPins))
  1914. {
  1915. sb.AppendLine("Admin commands:");
  1916. sb.AppendLine(" <color=#ffd479>/pin delete XY</color>: Delete a pin from an area");
  1917. }
  1918.  
  1919. sb.Append("Available pin types: ");
  1920. foreach (string type in Enum.GetNames(typeof(PinType)).OrderBy(str => str.ToLowerInvariant()))
  1921. sb.AppendFormat("<color=#ffd479>{0}</color>, ", type.ToLowerInvariant());
  1922. sb.Remove(sb.Length - 2, 2);
  1923. sb.AppendLine();
  1924.  
  1925. user.SendChatMessage(sb);
  1926. }
  1927. }
  1928. }
  1929.  
  1930. namespace Oxide.Plugins
  1931. {
  1932. using System;
  1933. using System.Linq;
  1934. using System.Text;
  1935.  
  1936. public partial class Imperium
  1937. {
  1938. void OnPinListCommand(User user, string[] args)
  1939. {
  1940. if (args.Length > 1)
  1941. {
  1942. user.SendChatMessage(Messages.Usage, "/pin list [TYPE]");
  1943. return;
  1944. }
  1945.  
  1946. Pin[] pins = Pins.GetAll();
  1947.  
  1948. if (args.Length == 1)
  1949. {
  1950. PinType type;
  1951. if (!Util.TryParseEnum(args[0], out type))
  1952. {
  1953. user.SendChatMessage(Messages.InvalidPinType, args[0]);
  1954. return;
  1955. }
  1956.  
  1957. pins = pins.Where(pin => pin.Type == type).ToArray();
  1958. }
  1959.  
  1960. if (pins.Length == 0)
  1961. {
  1962. user.SendChatMessage("There are no matching pins.");
  1963. return;
  1964. }
  1965.  
  1966. var sb = new StringBuilder();
  1967. sb.AppendLine(String.Format("There are <color=#ffd479>{0}</color> matching map pins:", pins.Length));
  1968. foreach (Pin pin in pins.OrderBy(pin => pin.GetDistanceFrom(user.Player)))
  1969. {
  1970. int distance = (int) Math.Floor(pin.GetDistanceFrom(user.Player));
  1971. sb.AppendLine(String.Format(
  1972. " <color=#ffd479>{0} ({1}):</color> {2} (<color=#ffd479>{3}m</color> away)", pin.Name,
  1973. pin.Type.ToString().ToLowerInvariant(), pin.AreaId, distance));
  1974. }
  1975.  
  1976. user.SendChatMessage(sb);
  1977. }
  1978. }
  1979. }
  1980.  
  1981. namespace Oxide.Plugins
  1982. {
  1983. using System;
  1984.  
  1985. public partial class Imperium
  1986. {
  1987. void OnPinRemoveCommand(User user, string[] args)
  1988. {
  1989. if (args.Length != 1)
  1990. {
  1991. user.SendChatMessage(Messages.Usage, "/pin remove \"NAME\"");
  1992. return;
  1993. }
  1994.  
  1995. if (user.Faction == null)
  1996. {
  1997. user.SendChatMessage(Messages.NotMemberOfFaction);
  1998. return;
  1999. }
  2000.  
  2001. string name = Util.NormalizePinName(args[0]);
  2002. Pin pin = Pins.Get(name);
  2003.  
  2004. if (pin == null)
  2005. {
  2006. user.SendChatMessage(Messages.UnknownPin, name);
  2007. return;
  2008. }
  2009.  
  2010. Area area = Areas.Get(pin.AreaId);
  2011. if (area.FactionId != user.Faction.Id)
  2012. {
  2013. user.SendChatMessage(Messages.CannotRemovePinAreaNotOwnedByYourFaction, pin.Name, pin.AreaId);
  2014. return;
  2015. }
  2016.  
  2017. Pins.Remove(pin);
  2018. user.SendChatMessage(Messages.PinRemoved, pin.Name);
  2019. }
  2020. }
  2021. }
  2022.  
  2023. namespace Oxide.Plugins
  2024. {
  2025. using System.Linq;
  2026.  
  2027. public partial class Imperium
  2028. {
  2029. [ChatCommand("tax")]
  2030. void OnTaxCommand(BasePlayer player, string command, string[] args)
  2031. {
  2032. User user = Users.Get(player);
  2033. if (user == null) return;
  2034.  
  2035. if (!Options.Taxes.Enabled)
  2036. {
  2037. user.SendChatMessage(Messages.TaxationDisabled);
  2038. return;
  2039. }
  2040.  
  2041. ;
  2042.  
  2043. if (args.Length == 0)
  2044. {
  2045. OnTaxHelpCommand(user);
  2046. return;
  2047. }
  2048.  
  2049. var restArguments = args.Skip(1).ToArray();
  2050.  
  2051. switch (args[0].ToLower())
  2052. {
  2053. case "chest":
  2054. OnTaxChestCommand(user);
  2055. break;
  2056. case "rate":
  2057. OnTaxRateCommand(user, restArguments);
  2058. break;
  2059. case "help":
  2060. default:
  2061. OnTaxHelpCommand(user);
  2062. break;
  2063. }
  2064. }
  2065. }
  2066. }
  2067.  
  2068. namespace Oxide.Plugins
  2069. {
  2070. public partial class Imperium
  2071. {
  2072. void OnTaxChestCommand(User user)
  2073. {
  2074. Faction faction = Factions.GetByMember(user);
  2075.  
  2076. if (faction == null || !faction.HasLeader(user))
  2077. {
  2078. user.SendChatMessage(Messages.NotLeaderOfFaction);
  2079. return;
  2080. }
  2081.  
  2082. user.SendChatMessage(Messages.SelectTaxChest);
  2083. user.BeginInteraction(new SelectingTaxChestInteraction(faction));
  2084. }
  2085. }
  2086. }
  2087.  
  2088. namespace Oxide.Plugins
  2089. {
  2090. using System.Text;
  2091.  
  2092. public partial class Imperium
  2093. {
  2094. void OnTaxHelpCommand(User user)
  2095. {
  2096. var sb = new StringBuilder();
  2097.  
  2098. sb.AppendLine("Available commands:");
  2099. sb.AppendLine(" <color=#ffd479>/tax rate NN</color>: Set the tax rate for your faction");
  2100. sb.AppendLine(" <color=#ffd479>/tax chest</color>: Select a container to use as your faction's tax chest");
  2101. sb.AppendLine(" <color=#ffd479>/tax help</color>: Prints this message");
  2102.  
  2103. user.SendChatMessage(sb);
  2104. }
  2105. }
  2106. }
  2107.  
  2108. namespace Oxide.Plugins
  2109. {
  2110. using System;
  2111.  
  2112. public partial class Imperium
  2113. {
  2114. void OnTaxRateCommand(User user, string[] args)
  2115. {
  2116. Faction faction = Factions.GetByMember(user);
  2117.  
  2118. if (faction == null || !faction.HasLeader(user))
  2119. {
  2120. user.SendChatMessage(Messages.NotLeaderOfFaction);
  2121. return;
  2122. }
  2123.  
  2124. float taxRate;
  2125. try
  2126. {
  2127. taxRate = Convert.ToInt32(args[0]) / 100f;
  2128. }
  2129. catch
  2130. {
  2131. user.SendChatMessage(Messages.CannotSetTaxRateInvalidValue, Options.Taxes.MaxTaxRate * 100);
  2132. return;
  2133. }
  2134.  
  2135. if (taxRate < 0 || taxRate > Options.Taxes.MaxTaxRate)
  2136. {
  2137. user.SendChatMessage(Messages.CannotSetTaxRateInvalidValue, Options.Taxes.MaxTaxRate * 100);
  2138. return;
  2139. }
  2140.  
  2141. user.SendChatMessage(Messages.SetTaxRateSuccessful, faction.Id, taxRate * 100);
  2142. Log($"{Util.Format(user)} set the tax rate for faction {faction.Id} to {taxRate * 100}%");
  2143.  
  2144. Factions.SetTaxRate(faction, taxRate);
  2145. }
  2146. }
  2147. }
  2148.  
  2149. namespace Oxide.Plugins
  2150. {
  2151. public partial class Imperium
  2152. {
  2153. [ChatCommand("hud")]
  2154. void OnHudCommand(BasePlayer player, string command, string[] args)
  2155. {
  2156. User user = Users.Get(player);
  2157. if (user == null) return;
  2158.  
  2159. if (!EnforceCommandCooldown(user, "hud", Options.Map.CommandCooldownSeconds))
  2160. return;
  2161.  
  2162. user.Hud.Toggle();
  2163. }
  2164. }
  2165. }
  2166.  
  2167. namespace Oxide.Plugins
  2168. {
  2169. public partial class Imperium
  2170. {
  2171. [ConsoleCommand("imperium.hud.toggle")]
  2172. void OnHudToggleConsoleCommand(ConsoleSystem.Arg arg)
  2173. {
  2174. var player = arg.Connection.player as BasePlayer;
  2175. if (player == null) return;
  2176.  
  2177. User user = Users.Get(player);
  2178. if (user == null) return;
  2179.  
  2180. if (!EnforceCommandCooldown(user, "hud", Options.Map.CommandCooldownSeconds))
  2181. return;
  2182.  
  2183. user.Hud.Toggle();
  2184. }
  2185. }
  2186. }
  2187.  
  2188. namespace Oxide.Plugins
  2189. {
  2190. using System;
  2191.  
  2192. public partial class Imperium
  2193. {
  2194. [ConsoleCommand("imperium.map.togglelayer")]
  2195. void OnMapToggleLayerConsoleCommand(ConsoleSystem.Arg arg)
  2196. {
  2197. var player = arg.Connection.player as BasePlayer;
  2198. if (player == null) return;
  2199.  
  2200. User user = Users.Get(player);
  2201. if (user == null) return;
  2202.  
  2203. if (!user.Map.IsVisible)
  2204. return;
  2205.  
  2206. string str = arg.GetString(0);
  2207. UserMapLayer layer;
  2208.  
  2209. if (String.IsNullOrEmpty(str) || !Util.TryParseEnum(arg.Args[0], out layer))
  2210. return;
  2211.  
  2212. user.Preferences.ToggleMapLayer(layer);
  2213. user.Map.Refresh();
  2214. }
  2215. }
  2216. }
  2217.  
  2218. namespace Oxide.Plugins
  2219. {
  2220. public partial class Imperium
  2221. {
  2222. [ChatCommand("map")]
  2223. void OnMapCommand(BasePlayer player, string command, string[] args)
  2224. {
  2225. User user = Users.Get(player);
  2226. if (user == null) return;
  2227.  
  2228. if (!user.Map.IsVisible && !EnforceCommandCooldown(user, "map", Options.Map.CommandCooldownSeconds))
  2229. return;
  2230.  
  2231. user.Map.Toggle();
  2232. }
  2233. }
  2234. }
  2235.  
  2236. namespace Oxide.Plugins
  2237. {
  2238. public partial class Imperium
  2239. {
  2240. [ConsoleCommand("imperium.map.toggle")]
  2241. void OnMapToggleConsoleCommand(ConsoleSystem.Arg arg)
  2242. {
  2243. var player = arg.Connection.player as BasePlayer;
  2244. if (player == null) return;
  2245.  
  2246. User user = Users.Get(player);
  2247. if (user == null) return;
  2248.  
  2249. if (!user.Map.IsVisible && !EnforceCommandCooldown(user, "map", Options.Map.CommandCooldownSeconds))
  2250. return;
  2251.  
  2252. user.Map.Toggle();
  2253. }
  2254. }
  2255. }
  2256.  
  2257. namespace Oxide.Plugins
  2258. {
  2259. using System.Linq;
  2260.  
  2261. public partial class Imperium
  2262. {
  2263. [ChatCommand("war")]
  2264. void OnWarCommand(BasePlayer player, string command, string[] args)
  2265. {
  2266. User user = Users.Get(player);
  2267. if (user == null) return;
  2268.  
  2269. if (!Options.War.Enabled)
  2270. {
  2271. user.SendChatMessage(Messages.WarDisabled);
  2272. return;
  2273. }
  2274.  
  2275. if (args.Length == 0)
  2276. {
  2277. OnWarHelpCommand(user);
  2278. return;
  2279. }
  2280.  
  2281. var restArgs = args.Skip(1).ToArray();
  2282.  
  2283. switch (args[0].ToLower())
  2284. {
  2285. case "list":
  2286. OnWarListCommand(user);
  2287. break;
  2288. case "status":
  2289. OnWarStatusCommand(user);
  2290. break;
  2291. case "declare":
  2292. OnWarDeclareCommand(user, restArgs);
  2293. break;
  2294. case "end":
  2295. OnWarEndCommand(user, restArgs);
  2296. break;
  2297. default:
  2298. OnWarHelpCommand(user);
  2299. break;
  2300. }
  2301. }
  2302. }
  2303. }
  2304.  
  2305. namespace Oxide.Plugins
  2306. {
  2307. public partial class Imperium
  2308. {
  2309. void OnWarDeclareCommand(User user, string[] args)
  2310. {
  2311. Faction attacker = Factions.GetByMember(user);
  2312.  
  2313. if (!EnsureUserAndFactionCanEngageInDiplomacy(user, attacker))
  2314. return;
  2315.  
  2316. if (args.Length < 2)
  2317. {
  2318. user.SendChatMessage(Messages.Usage, "/war declare FACTION \"REASON\"");
  2319. return;
  2320. }
  2321.  
  2322. Faction defender = Factions.Get(Util.NormalizeFactionId(args[0]));
  2323.  
  2324. if (defender == null)
  2325. {
  2326. user.SendChatMessage(Messages.FactionDoesNotExist, args[0]);
  2327. return;
  2328. }
  2329.  
  2330. if (attacker.Id == defender.Id)
  2331. {
  2332. user.SendChatMessage(Messages.CannotDeclareWarAgainstYourself);
  2333. return;
  2334. }
  2335.  
  2336. War existingWar = Wars.GetActiveWarBetween(attacker, defender);
  2337.  
  2338. if (existingWar != null)
  2339. {
  2340. user.SendChatMessage(Messages.CannotDeclareWarAlreadyAtWar, defender.Id);
  2341. return;
  2342. }
  2343.  
  2344. string cassusBelli = args[1].Trim();
  2345.  
  2346. if (cassusBelli.Length < Options.War.MinCassusBelliLength)
  2347. {
  2348. user.SendChatMessage(Messages.CannotDeclareWarInvalidCassusBelli, defender.Id);
  2349. return;
  2350. }
  2351.  
  2352. War war = Wars.DeclareWar(attacker, defender, user, cassusBelli);
  2353. PrintToChat(Messages.WarDeclaredAnnouncement, war.AttackerId, war.DefenderId, war.CassusBelli);
  2354. Log(
  2355. $"{Util.Format(user)} declared war on faction {war.DefenderId} on behalf of {war.AttackerId} for reason: {war.CassusBelli}");
  2356. }
  2357. }
  2358. }
  2359.  
  2360. namespace Oxide.Plugins
  2361. {
  2362. public partial class Imperium
  2363. {
  2364. void OnWarEndCommand(User user, string[] args)
  2365. {
  2366. Faction faction = Factions.GetByMember(user);
  2367.  
  2368. if (!EnsureUserAndFactionCanEngageInDiplomacy(user, faction))
  2369. return;
  2370.  
  2371. Faction enemy = Factions.Get(Util.NormalizeFactionId(args[0]));
  2372.  
  2373. if (enemy == null)
  2374. {
  2375. user.SendChatMessage(Messages.FactionDoesNotExist, args[0]);
  2376. return;
  2377. }
  2378.  
  2379. War war = Wars.GetActiveWarBetween(faction, enemy);
  2380.  
  2381. if (war == null)
  2382. {
  2383. user.SendChatMessage(Messages.NotAtWar, enemy.Id);
  2384. return;
  2385. }
  2386.  
  2387. if (war.IsOfferingPeace(faction))
  2388. {
  2389. user.SendChatMessage(Messages.CannotOfferPeaceAlreadyOfferedPeace, enemy.Id);
  2390. return;
  2391. }
  2392.  
  2393. war.OfferPeace(faction);
  2394.  
  2395. if (war.IsAttackerOfferingPeace && war.IsDefenderOfferingPeace)
  2396. {
  2397. PrintToChat(Messages.WarEndedTreatyAcceptedAnnouncement, faction.Id, enemy.Id);
  2398. Log($"{Util.Format(user)} accepted the peace offering of {enemy.Id} on behalf of {faction.Id}");
  2399. Wars.EndWar(war, WarEndReason.Treaty);
  2400. OnDiplomacyChanged();
  2401. }
  2402. else
  2403. {
  2404. user.SendChatMessage(Messages.PeaceOffered, enemy.Id);
  2405. Log($"{Util.Format(user)} offered peace to faction {enemy.Id} on behalf of {faction.Id}");
  2406. }
  2407. }
  2408. }
  2409. }
  2410.  
  2411. namespace Oxide.Plugins
  2412. {
  2413. using System.Text;
  2414.  
  2415. public partial class Imperium
  2416. {
  2417. void OnWarHelpCommand(User user)
  2418. {
  2419. var sb = new StringBuilder();
  2420.  
  2421. sb.AppendLine("Available commands:");
  2422. sb.AppendLine(" <color=#ffd479>/war list</color>: Show all active wars");
  2423. sb.AppendLine(" <color=#ffd479>/war status</color>: Show all active wars your faction is involved in");
  2424. sb.AppendLine(
  2425. " <color=#ffd479>/war declare FACTION \"REASON\"</color>: Declare war against another faction");
  2426. sb.AppendLine(
  2427. " <color=#ffd479>/war end FACTION</color>: Offer to end a war, or accept an offer made to you");
  2428. sb.AppendLine(" <color=#ffd479>/war help</color>: Show this message");
  2429.  
  2430. user.SendChatMessage(sb);
  2431. }
  2432. }
  2433. }
  2434.  
  2435. namespace Oxide.Plugins
  2436. {
  2437. using System;
  2438. using System.Text;
  2439.  
  2440. public partial class Imperium
  2441. {
  2442. void OnWarListCommand(User user)
  2443. {
  2444. var sb = new StringBuilder();
  2445. War[] wars = Wars.GetAllActiveWars();
  2446.  
  2447. if (wars.Length == 0)
  2448. {
  2449. sb.Append("The island is at peace... for now. No wars have been declared.");
  2450. }
  2451. else
  2452. {
  2453. sb.AppendLine(String.Format("<color=#ffd479>The island is at war! {0} wars have been declared:</color>",
  2454. wars.Length));
  2455. for (var idx = 0; idx < wars.Length; idx++)
  2456. {
  2457. War war = wars[idx];
  2458. sb.AppendFormat("{0}. <color=#ffd479>{1}</color> vs <color=#ffd479>{2}</color>: {2}", (idx + 1),
  2459. war.AttackerId, war.DefenderId, war.CassusBelli);
  2460. sb.AppendLine();
  2461. }
  2462. }
  2463.  
  2464. user.SendChatMessage(sb);
  2465. }
  2466. }
  2467. }
  2468.  
  2469. namespace Oxide.Plugins
  2470. {
  2471. using System;
  2472. using System.Text;
  2473.  
  2474. public partial class Imperium
  2475. {
  2476. void OnWarStatusCommand(User user)
  2477. {
  2478. Faction faction = Factions.GetByMember(user);
  2479.  
  2480. if (faction == null)
  2481. {
  2482. user.SendChatMessage(Messages.NotMemberOfFaction);
  2483. return;
  2484. }
  2485.  
  2486. var sb = new StringBuilder();
  2487. War[] wars = Wars.GetAllActiveWarsByFaction(faction);
  2488.  
  2489. if (wars.Length == 0)
  2490. {
  2491. sb.AppendLine("Your faction is not involved in any wars.");
  2492. }
  2493. else
  2494. {
  2495. sb.AppendLine(
  2496. String.Format("<color=#ffd479>Your faction is involved in {0} wars:</color>", wars.Length));
  2497. for (var idx = 0; idx < wars.Length; idx++)
  2498. {
  2499. War war = wars[idx];
  2500. sb.AppendFormat("{0}. <color=#ffd479>{1}</color> vs <color=#ffd479>{2}</color>", (idx + 1),
  2501. war.AttackerId, war.DefenderId);
  2502. if (war.IsAttackerOfferingPeace)
  2503. sb.AppendFormat(": <color=#ffd479>{0}</color> is offering peace!", war.AttackerId);
  2504. if (war.IsDefenderOfferingPeace)
  2505. sb.AppendFormat(": <color=#ffd479>{0}</color> is offering peace!", war.DefenderId);
  2506. sb.AppendLine();
  2507. }
  2508. }
  2509.  
  2510. user.SendChatMessage(sb);
  2511. }
  2512. }
  2513. }
  2514.  
  2515. namespace Oxide.Plugins
  2516. {
  2517. using Oxide.Core.Plugins;
  2518.  
  2519. public partial class Imperium
  2520. {
  2521. [HookMethod(nameof(GetFactionName))]
  2522. public object GetFactionName(BasePlayer player)
  2523. {
  2524. User user = Users.Get(player);
  2525.  
  2526. if (user == null || user.Faction == null)
  2527. return null;
  2528. else
  2529. return user.Faction.Id;
  2530. }
  2531. }
  2532. }
  2533.  
  2534. namespace Oxide.Plugins
  2535. {
  2536. public partial class Imperium
  2537. {
  2538. static class Decay
  2539. {
  2540. public static object AlterDecayDamage(BaseEntity entity, HitInfo hit)
  2541. {
  2542. if (!Instance.Options.Decay.Enabled)
  2543. return null;
  2544.  
  2545. Area area = GetAreaForDecayCalculation(entity);
  2546.  
  2547. if (area == null)
  2548. {
  2549. Instance.PrintWarning($"An entity decayed in an unknown area. This shouldn't happen.");
  2550. return null;
  2551. }
  2552.  
  2553. float reduction = 0;
  2554.  
  2555. if (area.Type == AreaType.Claimed || area.Type == AreaType.Headquarters)
  2556. reduction = Instance.Options.Decay.ClaimedLandDecayReduction;
  2557.  
  2558. if (reduction >= 1)
  2559. return false;
  2560.  
  2561. if (reduction > 0)
  2562. hit.damageTypes.Scale(Rust.DamageType.Decay, reduction);
  2563.  
  2564. return null;
  2565. }
  2566.  
  2567. static Area GetAreaForDecayCalculation(BaseEntity entity)
  2568. {
  2569. Area area = null;
  2570.  
  2571. // If the entity is controlled by a claim cupboard, use the area the cupboard controls.
  2572. BuildingPrivlidge cupboard = entity.GetBuildingPrivilege();
  2573. if (cupboard)
  2574. area = Instance.Areas.GetByClaimCupboard(cupboard);
  2575.  
  2576. // Otherwise, determine the area by its position in the world.
  2577. if (area == null)
  2578. area = Instance.Areas.GetByEntityPosition(entity);
  2579.  
  2580. return area;
  2581. }
  2582. }
  2583. }
  2584. }
  2585.  
  2586. namespace Oxide.Plugins
  2587. {
  2588. using Oxide.Core;
  2589.  
  2590. public partial class Imperium : RustPlugin
  2591. {
  2592. static class Events
  2593. {
  2594. public static void OnAreaChanged(Area area)
  2595. {
  2596. Interface.CallHook(nameof(OnAreaChanged), area);
  2597. }
  2598.  
  2599. public static void OnUserEnteredArea(User user, Area area)
  2600. {
  2601. Interface.CallHook(nameof(OnUserEnteredArea), user, area);
  2602. }
  2603.  
  2604. public static void OnUserLeftArea(User user, Area area)
  2605. {
  2606. Interface.CallHook(nameof(OnUserLeftArea), user, area);
  2607. }
  2608.  
  2609. public static void OnUserEnteredZone(User user, Zone zone)
  2610. {
  2611. Interface.CallHook(nameof(OnUserEnteredZone), user, zone);
  2612. }
  2613.  
  2614. public static void OnUserLeftZone(User user, Zone zone)
  2615. {
  2616. Interface.CallHook(nameof(OnUserLeftZone), user, zone);
  2617. }
  2618.  
  2619. public static void OnFactionCreated(Faction faction)
  2620. {
  2621. Interface.CallHook(nameof(OnFactionCreated), faction);
  2622. }
  2623.  
  2624. public static void OnFactionDisbanded(Faction faction)
  2625. {
  2626. Interface.CallHook(nameof(OnFactionDisbanded), faction);
  2627. }
  2628.  
  2629. public static void OnFactionTaxesChanged(Faction faction)
  2630. {
  2631. Interface.CallHook(nameof(OnFactionTaxesChanged), faction);
  2632. }
  2633.  
  2634. public static void OnPlayerJoinedFaction(Faction faction, User user)
  2635. {
  2636. Interface.CallHook(nameof(OnPlayerJoinedFaction), faction, user);
  2637. }
  2638.  
  2639. public static void OnPlayerLeftFaction(Faction faction, User user)
  2640. {
  2641. Interface.CallHook(nameof(OnPlayerLeftFaction), faction, user);
  2642. }
  2643.  
  2644. public static void OnPlayerInvitedToFaction(Faction faction, User user)
  2645. {
  2646. Interface.CallHook(nameof(OnPlayerInvitedToFaction), faction, user);
  2647. }
  2648.  
  2649. public static void OnPlayerUninvitedFromFaction(Faction faction, User user)
  2650. {
  2651. Interface.CallHook(nameof(OnPlayerUninvitedFromFaction), faction, user);
  2652. }
  2653.  
  2654. public static void OnPlayerPromoted(Faction faction, User user)
  2655. {
  2656. Interface.CallHook(nameof(OnPlayerPromoted), faction, user);
  2657. }
  2658.  
  2659. public static void OnPlayerDemoted(Faction faction, User user)
  2660. {
  2661. Interface.CallHook(nameof(OnPlayerDemoted), faction, user);
  2662. }
  2663.  
  2664. public static void OnPinCreated(Pin pin)
  2665. {
  2666. Interface.CallHook(nameof(OnPinCreated), pin);
  2667. }
  2668.  
  2669. public static void OnPinRemoved(Pin pin)
  2670. {
  2671. Interface.CallHook(nameof(OnPinRemoved), pin);
  2672. }
  2673. }
  2674. }
  2675. }
  2676.  
  2677. namespace Oxide.Plugins
  2678. {
  2679. using Network;
  2680. using Oxide.Core;
  2681. using UnityEngine;
  2682.  
  2683. public partial class Imperium : RustPlugin
  2684. {
  2685. void OnUserApprove(Connection connection)
  2686. {
  2687. Users.SetOriginalName(connection.userid.ToString(), connection.username);
  2688. }
  2689.  
  2690. void OnPlayerConnected(BasePlayer player)
  2691. {
  2692. if (player == null) return;
  2693.  
  2694. // If the player hasn't fully connected yet, try again in 2 seconds.
  2695. if (player.IsReceivingSnapshot)
  2696. {
  2697. timer.In(2, () => OnPlayerConnected(player));
  2698. return;
  2699. }
  2700.  
  2701. Users.Add(player);
  2702. }
  2703.  
  2704. void OnPlayerDisconnected(BasePlayer player)
  2705. {
  2706. if (player != null)
  2707. Users.Remove(player);
  2708. }
  2709.  
  2710. void OnHammerHit(BasePlayer player, HitInfo hit)
  2711. {
  2712. User user = Users.Get(player);
  2713.  
  2714. if (user != null && user.CurrentInteraction != null)
  2715. user.CompleteInteraction(hit);
  2716. }
  2717. object OnTrapTrigger(BaseTrap trap, GameObject obj)
  2718. {
  2719. var player = obj.GetComponent<BasePlayer>();
  2720.  
  2721. if (trap == null || player == null)
  2722. return null;
  2723.  
  2724. User defender = Users.Get(player);
  2725. return Pvp.HandleTrapTrigger(trap, defender);
  2726. }
  2727.  
  2728. object CanBeTargeted(BaseCombatEntity target, MonoBehaviour turret)
  2729. {
  2730. if (target == null || turret == null)
  2731. return null;
  2732.  
  2733. // Don't interfere with the helicopter.
  2734. if (turret is HelicopterTurret)
  2735. return null;
  2736.  
  2737. var player = target as BasePlayer;
  2738.  
  2739. if (player == null)
  2740. return null;
  2741.  
  2742. if (Users == null)
  2743. {
  2744. return null;
  2745. }
  2746.  
  2747. var defender = Users.Get(player);
  2748. var entity = turret as BaseCombatEntity;
  2749.  
  2750. if (defender == null || entity == null)
  2751. return null;
  2752.  
  2753. return Pvp.HandleTurretTarget(entity, defender);
  2754. }
  2755.  
  2756. void OnEntitySpawned(BaseNetworkable entity)
  2757. {
  2758. var plane = entity as CargoPlane;
  2759. if (plane != null)
  2760. Hud.GameEvents.BeginEvent(plane);
  2761.  
  2762. var drop = entity as SupplyDrop;
  2763. if (Options.Zones.Enabled && drop != null)
  2764. Zones.CreateForSupplyDrop(drop);
  2765.  
  2766. var heli = entity as BaseHelicopter;
  2767. if (heli != null)
  2768. Hud.GameEvents.BeginEvent(heli);
  2769.  
  2770. var chinook = entity as CH47Helicopter;
  2771. if (chinook != null)
  2772. Hud.GameEvents.BeginEvent(chinook);
  2773.  
  2774. var crate = entity as HackableLockedCrate;
  2775. if (crate != null)
  2776. Hud.GameEvents.BeginEvent(crate);
  2777. }
  2778.  
  2779. void OnEntityKill(BaseNetworkable networkable)
  2780. {
  2781. var entity = networkable as BaseEntity;
  2782.  
  2783. if (!Ready || entity == null)
  2784. return;
  2785.  
  2786. // If a claim TC was destroyed, remove the claim from the area.
  2787. var cupboard = entity as BuildingPrivlidge;
  2788. if (cupboard != null)
  2789. {
  2790. var area = Areas.GetByClaimCupboard(cupboard);
  2791. if (area != null)
  2792. {
  2793. PrintToChat(Messages.AreaClaimLostCupboardDestroyedAnnouncement, area.FactionId, area.Id);
  2794. Log(
  2795. $"{area.FactionId} lost their claim on {area.Id} because the tool cupboard was destroyed (hook function)");
  2796. Areas.Unclaim(area);
  2797. }
  2798.  
  2799. return;
  2800. }
  2801.  
  2802. // If a tax chest was destroyed, remove it from the faction data.
  2803. var container = entity as StorageContainer;
  2804. if (Options.Taxes.Enabled && container != null)
  2805. {
  2806. Faction faction = Factions.GetByTaxChest(container);
  2807. if (faction != null)
  2808. {
  2809. Log($"{faction.Id}'s tax chest was destroyed (hook function)");
  2810. faction.TaxChest = null;
  2811. }
  2812.  
  2813. return;
  2814. }
  2815.  
  2816. // If a helicopter was destroyed, create an event zone around it.
  2817. var helicopter = entity as BaseHelicopter;
  2818. if (Options.Zones.Enabled && helicopter != null)
  2819. Zones.CreateForDebrisField(helicopter);
  2820. }
  2821.  
  2822. void OnDispenserGather(ResourceDispenser dispenser, BaseEntity entity, Item item)
  2823. {
  2824. Taxes.ProcessTaxesIfApplicable(dispenser, entity, item);
  2825. Taxes.AwardBadlandsBonusIfApplicable(dispenser, entity, item);
  2826. }
  2827.  
  2828. void OnDispenserBonus(ResourceDispenser dispenser, BaseEntity entity, Item item)
  2829. {
  2830. Taxes.ProcessTaxesIfApplicable(dispenser, entity, item);
  2831. Taxes.AwardBadlandsBonusIfApplicable(dispenser, entity, item);
  2832. }
  2833.  
  2834. object OnEntityDeath(BasePlayer player, HitInfo hit)
  2835. {
  2836. if (player == null)
  2837. return null;
  2838.  
  2839. // When a player dies, remove them from the area and any zones they were in.
  2840. User user = Users.Get(player);
  2841. if (user != null)
  2842. {
  2843. user.CurrentArea = null;
  2844. user.CurrentZones.Clear();
  2845. }
  2846.  
  2847. return null;
  2848. }
  2849.  
  2850. void OnUserEnteredArea(User user, Area area)
  2851. {
  2852. Area previousArea = user.CurrentArea;
  2853.  
  2854. user.CurrentArea = area;
  2855. user.Hud.Refresh();
  2856.  
  2857. if (area == null || previousArea == null)
  2858. return;
  2859.  
  2860. if (area.Type == AreaType.Badlands && previousArea.Type != AreaType.Badlands)
  2861. {
  2862. // The player has entered the badlands.
  2863. user.SendChatMessage(Messages.EnteredBadlands);
  2864. }
  2865. else if (area.Type == AreaType.Wilderness && previousArea.Type != AreaType.Wilderness)
  2866. {
  2867. // The player has entered the wilderness.
  2868. user.SendChatMessage(Messages.EnteredWilderness);
  2869. }
  2870. else if (area.IsClaimed && !previousArea.IsClaimed)
  2871. {
  2872. // The player has entered a faction's territory.
  2873. user.SendChatMessage(Messages.EnteredClaimedArea, area.FactionId);
  2874. }
  2875. else if (area.IsClaimed && previousArea.IsClaimed && area.FactionId != previousArea.FactionId)
  2876. {
  2877. // The player has crossed a border between the territory of two factions.
  2878. user.SendChatMessage(Messages.EnteredClaimedArea, area.FactionId);
  2879. }
  2880. }
  2881.  
  2882. void OnUserEnteredZone(User user, Zone zone)
  2883. {
  2884. user.CurrentZones.Add(zone);
  2885. user.Hud.Refresh();
  2886. }
  2887.  
  2888. void OnUserLeftZone(User user, Zone zone)
  2889. {
  2890. user.CurrentZones.Remove(zone);
  2891. user.Hud.Refresh();
  2892. }
  2893.  
  2894. void OnFactionCreated(Faction faction)
  2895. {
  2896. Hud.RefreshForAllPlayers();
  2897. }
  2898.  
  2899. void OnFactionDisbanded(Faction faction)
  2900. {
  2901. Area[] areas = Instance.Areas.GetAllClaimedByFaction(faction);
  2902.  
  2903. if (areas.Length > 0)
  2904. {
  2905. foreach (Area area in areas)
  2906. PrintToChat(Messages.AreaClaimLostFactionDisbandedAnnouncement, area.FactionId, area.Id);
  2907.  
  2908. Areas.Unclaim(areas);
  2909. }
  2910.  
  2911. Wars.EndAllWarsForEliminatedFactions();
  2912. Hud.RefreshForAllPlayers();
  2913. }
  2914.  
  2915. void OnFactionTaxesChanged(Faction faction)
  2916. {
  2917. Hud.RefreshForAllPlayers();
  2918. }
  2919.  
  2920. void OnAreaChanged(Area area)
  2921. {
  2922. Wars.EndAllWarsForEliminatedFactions();
  2923. Pins.RemoveAllPinsInUnclaimedAreas();
  2924. Hud.GenerateMapOverlayImage();
  2925. Hud.RefreshForAllPlayers();
  2926. }
  2927.  
  2928. void OnDiplomacyChanged()
  2929. {
  2930. Hud.RefreshForAllPlayers();
  2931. }
  2932. }
  2933. }
  2934.  
  2935. namespace Oxide.Plugins
  2936. {
  2937. using System.Linq;
  2938. using System.Reflection;
  2939.  
  2940. public partial class Imperium : RustPlugin
  2941. {
  2942. static class Messages
  2943. {
  2944. public const string AreaClaimsDisabled = "Area claims are currently disabled.";
  2945. public const string TaxationDisabled = "Taxation is currently disabled.";
  2946. public const string BadlandsDisabled = "Badlands are currently disabled.";
  2947. public const string UpkeepDisabled = "Upkeep is currently disabled.";
  2948. public const string WarDisabled = "War is currently disabled.";
  2949. public const string PinsDisabled = "Map pins are currently disabled.";
  2950. public const string PvpModeDisabled = "PVP Mode is currently not available.";
  2951.  
  2952. public const string AreaIsBadlands = "<color=#ffd479>{0}</color> is a part of the badlands.";
  2953.  
  2954. public const string AreaIsClaimed =
  2955. "<color=#ffd479>{0}</color> has been claimed by <color=#ffd479>[{1}]</color>.";
  2956.  
  2957. public const string AreaIsHeadquarters =
  2958. "<color=#ffd479>{0}</color> is the headquarters of <color=#ffd479>[{1}]</color>.";
  2959.  
  2960. public const string AreaIsWilderness = "<color=#ffd479>{0}</color> has not been claimed by a faction.";
  2961. public const string AreaNotBadlands = "<color=#ffd479>{0}</color> is not a part of the badlands.";
  2962. public const string AreaNotOwnedByYourFaction = "<color=#ffd479>{0}</color> is not owned by your faction.";
  2963. public const string AreaNotWilderness = "<color=#ffd479>{0}</color> is not currently wilderness.";
  2964.  
  2965. public const string AreaNotContiguous =
  2966. "<color=#ffd479>{0}</color> is not connected to territory owned by <color=#ffd479>[{1}]</color>.";
  2967.  
  2968. public const string YouAreInTheGreatUnknown = "You are currently in the great unknown!";
  2969.  
  2970. public const string InteractionCanceled = "Command canceled.";
  2971. public const string NoInteractionInProgress = "You aren't currently executing any commands.";
  2972. public const string NoAreasClaimed = "Your faction has not claimed any areas.";
  2973. public const string NotMemberOfFaction = "You are not a member of a faction.";
  2974. public const string AlreadyMemberOfFaction = "You are already a member of a faction.";
  2975. public const string NotLeaderOfFaction = "You must be an owner or a manager of a faction.";
  2976. public const string FactionTooSmallToOwnLand = "To own land, a faction must have least {0} members.";
  2977.  
  2978. public const string FactionOwnsTooMuchLand =
  2979. "<color=#ffd479>[{0}]</color> already owns the maximum number of areas (<color=#ffd479>{1}</color>).";
  2980.  
  2981. public const string FactionHasTooManyMembers =
  2982. "<color=#ffd479>[{0}]</color> already has the maximum number of members (<color=#ffd479>{1}</color>).";
  2983.  
  2984. public const string FactionDoesNotOwnLand = "Your faction must own at least one area.";
  2985. public const string FactionAlreadyExists = "There is already a faction named <color=#ffd479>[{0}]</color>.";
  2986. public const string FactionDoesNotExist = "There is no faction named <color=#ffd479>[{0}]</color>.";
  2987. public const string InvalidUser = "Couldn't find a user whose name matches \"{0}\".";
  2988.  
  2989. public const string InvalidFactionName =
  2990. "Faction names must be between {0} and {1} alphanumeric characters.";
  2991.  
  2992. public const string NotAtWar = "You are not currently at war with <color=#ffd479>[{0}]</color>!";
  2993.  
  2994. public const string Usage = "Usage: <color=#ffd479>{0}</color>";
  2995. public const string CommandIsOnCooldown = "You can't do that again so quickly. Try again in {0} seconds.";
  2996. public const string NoPermission = "You don't have permission to do that.";
  2997.  
  2998. public const string MemberAdded =
  2999. "You have added <color=#ffd479>{0}</color> as a member of <color=#ffd479>[{1}]</color>.";
  3000.  
  3001. public const string MemberRemoved =
  3002. "You have removed <color=#ffd479>{0}</color> as a member of <color=#ffd479>[{1}]</color>.";
  3003.  
  3004. public const string ManagerAdded =
  3005. "You have added <color=#ffd479>{0}</color> as a manager of <color=#ffd479>[{1}]</color>.";
  3006.  
  3007. public const string ManagerRemoved =
  3008. "You have removed <color=#ffd479>{0}</color> as a manager of <color=#ffd479>[{1}]</color>.";
  3009.  
  3010. public const string UserIsAlreadyMemberOfFaction =
  3011. "<color=#ffd479>{0}</color> is already a member of <color=#ffd479>[{1}]</color>.";
  3012.  
  3013. public const string UserIsNotMemberOfFaction =
  3014. "<color=#ffd479>{0}</color> is not a member of <color=#ffd479>[{1}]</color>.";
  3015.  
  3016. public const string UserIsAlreadyManagerOfFaction =
  3017. "<color=#ffd479>{0}</color> is already a manager of <color=#ffd479>[{1}]</color>.";
  3018.  
  3019. public const string UserIsNotManagerOfFaction =
  3020. "<color=#ffd479>{0}</color> is not a manager of <color=#ffd479>[{1}]</color>.";
  3021.  
  3022. public const string CannotPromoteOrDemoteOwnerOfFaction =
  3023. "<color=#ffd479>{0}</color> cannot be promoted or demoted, since they are the owner of <color=#ffd479>[{1}]</color>.";
  3024.  
  3025. public const string CannotKickLeaderOfFaction =
  3026. "<color=#ffd479>{0}</color> cannot be kicked, since they are an owner or manager of <color=#ffd479>[{1}]</color>.";
  3027.  
  3028. public const string InviteAdded =
  3029. "You have invited <color=#ffd479>{0}</color> to join <color=#ffd479>[{1}]</color>.";
  3030.  
  3031. public const string InviteReceived =
  3032. "<color=#ffd479>{0}</color> has invited you to join <color=#ffd479>[{1}]</color>. Say <color=#ffd479>/faction join {1}</color> to accept.";
  3033.  
  3034. public const string CannotJoinFactionNotInvited =
  3035. "You cannot join <color=#ffd479>[{0}]</color>, because you have not been invited.";
  3036.  
  3037. public const string YouJoinedFaction = "You are now a member of <color=#ffd479>[{0}]</color>.";
  3038. public const string YouLeftFaction = "You are no longer a member of <color=#ffd479>[{0}]</color>.";
  3039.  
  3040. public const string SelectingCupboardFailedInvalidTarget = "You must select a tool cupboard.";
  3041. public const string SelectingCupboardFailedNotAuthorized = "You must be authorized on the tool cupboard.";
  3042.  
  3043. public const string SelectingCupboardFailedNotClaimCupboard =
  3044. "That tool cupboard doesn't represent an area claim made by your faction.";
  3045.  
  3046. public const string CannotClaimAreaAlreadyClaimed =
  3047. "<color=#ffd479>{0}</color> has already been claimed by <color=#ffd479>[{1}]</color>.";
  3048.  
  3049. public const string CannotClaimAreaCannotAfford =
  3050. "Claiming this area costs <color=#ffd479>{0}</color> scrap. Add this amount to your inventory and try again.";
  3051.  
  3052. public const string CannotClaimAreaAlreadyOwned =
  3053. "The area <color=#ffd479>{0}</color> is already owned by your faction, and this cupboard represents the claim.";
  3054.  
  3055. public const string SelectClaimCupboardToAdd =
  3056. "Use the hammer to select a tool cupboard to represent the claim. Say <color=#ffd479>/cancel</color> to cancel.";
  3057.  
  3058. public const string SelectClaimCupboardToRemove =
  3059. "Use the hammer to select the tool cupboard representing the claim you want to remove. Say <color=#ffd479>/cancel</color> to cancel.";
  3060.  
  3061. public const string SelectClaimCupboardForHeadquarters =
  3062. "Use the hammer to select the tool cupboard to represent your faction's headquarters. Say <color=#ffd479>/cancel</color> to cancel.";
  3063.  
  3064. public const string SelectClaimCupboardToAssign =
  3065. "Use the hammer to select a tool cupboard to represent the claim to assign to <color=#ffd479>[{0}]</color>. Say <color=#ffd479>/cancel</color> to cancel.";
  3066.  
  3067. public const string SelectClaimCupboardToTransfer =
  3068. "Use the hammer to select the tool cupboard representing the claim to give to <color=#ffd479>[{0}]</color>. Say <color=#ffd479>/cancel</color> to cancel.";
  3069.  
  3070. public const string ClaimCupboardMoved =
  3071. "You have moved the claim <color=#ffd479>{0}</color> to a new tool cupboard.";
  3072.  
  3073. public const string ClaimCaptured =
  3074. "You have captured <color=#ffd479>{0}</color> from <color=#ffd479>[{1}]</color>!";
  3075.  
  3076. public const string ClaimAdded = "You have claimed <color=#ffd479>{0}</color> for your faction.";
  3077. public const string ClaimRemoved = "You have removed your faction's claim on <color=#ffd479>{0}</color>.";
  3078.  
  3079. public const string ClaimTransferred =
  3080. "You have transferred ownership of <color=#ffd479>{0}</color> to <color=#ffd479>[{1}]</color>.";
  3081.  
  3082. public const string InvalidAreaName =
  3083. "Area names must be between <color=#ffd479>{0}</color> and <color=#ffd479>{1}</color> characters long.";
  3084.  
  3085. public const string UnknownArea = "Unknown area <color=#ffd479>{0}</color>.";
  3086. public const string AreaRenamed = "<color=#ffd479>{0}</color> is now known as <color=#ffd479>{1}</color>.";
  3087.  
  3088. public const string ClaimsList = "<color=#ffd479>[{0}]</color> has claimed: <color=#ffd479>{1}</color>";
  3089.  
  3090. public const string ClaimCost =
  3091. "<color=#ffd479>{0}</color> can be claimed by <color=#ffd479>[{1}]</color> for <color=#ffd479>{2}</color> scrap.";
  3092.  
  3093. public const string UpkeepCost =
  3094. "It will cost <color=#ffd479>{0}</color> scrap per day to maintain the <color=#ffd479>{1}</color> areas claimed by <color=#ffd479>[{2}]</color>. Upkeep is due <color=#ffd479>{3}</color> hours from now.";
  3095.  
  3096. public const string UpkeepCostOverdue =
  3097. "It will cost <color=#ffd479>{0}</color> scrap per day to maintain the <color=#ffd479>{1}</color> areas claimed by <color=#ffd479>[{2}]</color>. Your upkeep is <color=#ffd479>{3}</color> hours overdue! Fill your tax chest with scrap immediately, before your claims begin to fall into ruin.";
  3098.  
  3099. public const string SelectTaxChest =
  3100. "Use the hammer to select the container to receive your faction's tribute. Say <color=#ffd479>/cancel</color> to cancel.";
  3101.  
  3102. public const string SelectingTaxChestFailedInvalidTarget = "That can't be used as a tax chest.";
  3103.  
  3104. public const string SelectingTaxChestSucceeded =
  3105. "You have selected a new tax chest that will receive <color=#ffd479>{0}%</color> of the materials harvested within land owned by <color=#ffd479>[{1}]</color>. To change the tax rate, say <color=#ffd479>/tax rate PERCENT</color>.";
  3106.  
  3107. public const string CannotSetTaxRateInvalidValue =
  3108. "You must specify a valid percentage between <color=#ffd479>0-{0}%</color> as a tax rate.";
  3109.  
  3110. public const string SetTaxRateSuccessful =
  3111. "You have set the tax rate on the land holdings of <color=#ffd479>[{0}]</color> to <color=#ffd479>{1}%</color>.";
  3112.  
  3113. public const string BadlandsSet = "Badlands areas are now: <color=#ffd479>{0}</color>";
  3114.  
  3115. public const string BadlandsList =
  3116. "Badlands areas are: <color=#ffd479>{0}</color>. Gather bonus is <color=#ffd479>{1}%</color>.";
  3117.  
  3118. public const string CannotDeclareWarAgainstYourself = "You cannot declare war against yourself!";
  3119.  
  3120. public const string CannotDeclareWarAlreadyAtWar =
  3121. "You area already at war with <color=#ffd479>[{0}]</color>!";
  3122.  
  3123. public const string CannotDeclareWarInvalidCassusBelli =
  3124. "You cannot declare war against <color=#ffd479>[{0}]</color>, because your reason doesn't meet the minimum length.";
  3125.  
  3126. public const string CannotOfferPeaceAlreadyOfferedPeace =
  3127. "You have already offered peace to <color=#ffd479>[{0}]</color>.";
  3128.  
  3129. public const string PeaceOffered =
  3130. "You have offered peace to <color=#ffd479>[{0}]</color>. They must accept it before the war will end.";
  3131.  
  3132. public const string EnteredBadlands =
  3133. "<color=#ff0000>BORDER:</color> You have entered the badlands! Player violence is allowed here.";
  3134.  
  3135. public const string EnteredWilderness = "<color=#ffd479>BORDER:</color> You have entered the wilderness.";
  3136.  
  3137. public const string EnteredClaimedArea =
  3138. "<color=#ffd479>BORDER:</color> You have entered land claimed by <color=#ffd479>[{0}]</color>.";
  3139.  
  3140. public const string EnteredPvpMode =
  3141. "<color=#ff0000>PVP ENABLED:</color> You are now in PVP mode. You can now hurt, and be hurt by, other players who are also in PVP mode.";
  3142.  
  3143. public const string ExitedPvpMode =
  3144. "<color=#00ff00>PVP DISABLED:</color> You are no longer in PVP mode. You can't be harmed by other players except inside of normal PVP areas.";
  3145.  
  3146. public const string PvpModeOnCooldown = "You must wait at least {0} seconds to exit or re-enter PVP mode.";
  3147.  
  3148. public const string InvalidPinType =
  3149. "Unknown map pin type <color=#ffd479>{0}</color>. Say <color=#ffd479>/pin types</color> to see a list of available types.";
  3150.  
  3151. public const string InvalidPinName =
  3152. "Map pin names must be between <color=#ffd479>{0}</color> and <color=#ffd479>{1}</color> characters long.";
  3153.  
  3154. public const string CannotCreatePinCannotAfford =
  3155. "Creating a new map pin costs <color=#ffd479>{0}</color> scrap. Add this amount to your inventory and try again.";
  3156.  
  3157. public const string CannotCreatePinAlreadyExists =
  3158. "Cannot create a new map pin named <color=#ffd479>{0}</color>, since one already exists with the same name in <color=#ffd479>{1}</color>.";
  3159.  
  3160. public const string UnknownPin = "Unknown map pin <color=#ffd479>{0}</color>.";
  3161.  
  3162. public const string CannotRemovePinAreaNotOwnedByYourFaction =
  3163. "Cannot remove the map pin named <color=#ffd479>{0}</color>, because the area <color=#ffd479>{1} is not owned by your faction.";
  3164.  
  3165. public const string PinRemoved = "Removed map pin <color=#ffd479>{0}</color>.";
  3166.  
  3167. public const string FactionCreatedAnnouncement =
  3168. "<color=#00ff00>FACTION CREATED:</color> A new faction <color=#ffd479>[{0}]</color> has been created!";
  3169.  
  3170. public const string FactionDisbandedAnnouncement =
  3171. "<color=#00ff00>FACTION DISBANDED:</color> <color=#ffd479>[{0}]</color> has been disbanded!";
  3172.  
  3173. public const string FactionMemberJoinedAnnouncement =
  3174. "<color=#00ff00>MEMBER JOINED:</color> <color=#ffd479>{0}</color> has joined <color=#ffd479>[{1}]</color>!";
  3175.  
  3176. public const string FactionMemberLeftAnnouncement =
  3177. "<color=#00ff00>MEMBER LEFT:</color> <color=#ffd479>{0}</color> has left <color=#ffd479>[{1}]</color>!";
  3178.  
  3179. public const string AreaClaimedAnnouncement =
  3180. "<color=#00ff00>AREA CLAIMED:</color> <color=#ffd479>[{0}]</color> claims <color=#ffd479>{1}</color>!";
  3181.  
  3182. public const string AreaClaimedAsHeadquartersAnnouncement =
  3183. "<color=#00ff00>AREA CLAIMED:</color> <color=#ffd479>[{0}]</color> claims <color=#ffd479>{1}</color> as their headquarters!";
  3184.  
  3185. public const string AreaCapturedAnnouncement =
  3186. "<color=#ff0000>AREA CAPTURED:</color> <color=#ffd479>[{0}]</color> has captured <color=#ffd479>{1}</color> from <color=#ffd479>[{2}]</color>!";
  3187.  
  3188. public const string AreaClaimRemovedAnnouncement =
  3189. "<color=#ff0000>CLAIM REMOVED:</color> <color=#ffd479>[{0}]</color> has relinquished their claim on <color=#ffd479>{1}</color>!";
  3190.  
  3191. public const string AreaClaimTransferredAnnouncement =
  3192. "<color=#ff0000>CLAIM TRANSFERRED:</color> <color=#ffd479>[{0}]</color> has transferred their claim on <color=#ffd479>{1}</color> to <color=#ffd479>[{2}]</color>!";
  3193.  
  3194. public const string AreaClaimAssignedAnnouncement =
  3195. "<color=#ff0000>AREA CLAIM ASSIGNED:</color> <color=#ffd479>{0}</color> has been assigned to <color=#ffd479>[{1}]</color> by an admin.";
  3196.  
  3197. public const string AreaClaimDeletedAnnouncement =
  3198. "<color=#ff0000>AREA CLAIM REMOVED:</color> <color=#ffd479>[{0}]</color>'s claim on <color=#ffd479>{1}</color> has been removed by an admin.";
  3199.  
  3200. public const string AreaClaimLostCupboardDestroyedAnnouncement =
  3201. "<color=#ff0000>AREA CLAIM LOST:</color> <color=#ffd479>[{0}]</color> has lost its claim on <color=#ffd479>{1}</color>, because the tool cupboard was destroyed!";
  3202.  
  3203. public const string AreaClaimLostFactionDisbandedAnnouncement =
  3204. "<color=#ff0000>AREA CLAIM LOST:</color> <color=#ffd479>[{0}]</color> has been disbanded, losing its claim on <color=#ffd479>{1}</color>!";
  3205.  
  3206. public const string AreaClaimLostUpkeepNotPaidAnnouncement =
  3207. "<color=#ff0000>AREA CLAIM LOST:</color>: <color=#ffd479>[{0}]</color> has lost their claim on <color=#ffd479>{1}</color> after it fell into ruin!";
  3208.  
  3209. public const string HeadquartersChangedAnnouncement =
  3210. "<color=#00ff00>HQ CHANGED:</color> The headquarters of <color=#ffd479>[{0}]</color> is now <color=#ffd479>{1}</color>.";
  3211.  
  3212. public const string WarDeclaredAnnouncement =
  3213. "<color=#ff0000>WAR DECLARED:</color> <color=#ffd479>[{0}]</color> has declared war on <color=#ffd479>[{1}]</color>! Their reason: <color=#ffd479>{2}</color>";
  3214.  
  3215. public const string WarEndedTreatyAcceptedAnnouncement =
  3216. "<color=#00ff00>WAR ENDED:</color> The war between <color=#ffd479>[{0}]</color> and <color=#ffd479>[{1}]</color> has ended after both sides have agreed to a treaty.";
  3217.  
  3218. public const string WarEndedFactionEliminatedAnnouncement =
  3219. "<color=#00ff00>WAR ENDED:</color> The war between <color=#ffd479>[{0}]</color> and <color=#ffd479>[{1}]</color> has ended, since <color=#ffd479>[{2}]</color> no longer holds any land.";
  3220.  
  3221. public const string PinAddedAnnouncement =
  3222. "<color=#00ff00>POINT OF INTEREST:</color> <color=#ffd479>[{0}]</color> announces the creation of <color=#ffd479>{1}</color>, a new {2} located in <color=#ffd479>{3}</color>!";
  3223. }
  3224.  
  3225. void InitLang()
  3226. {
  3227. var messages = typeof(Messages).GetFields(BindingFlags.Public)
  3228. .Select(f => (string) f.GetRawConstantValue())
  3229. .ToDictionary(str => str);
  3230.  
  3231. lang.RegisterMessages(messages, this);
  3232. }
  3233. }
  3234. }
  3235.  
  3236. namespace Oxide.Plugins
  3237. {
  3238. using System;
  3239. using System.Linq;
  3240.  
  3241. public partial class Imperium
  3242. {
  3243. static class Pvp
  3244. {
  3245. static string[] BlockedPrefabs = new[]
  3246. {
  3247. "fireball_small",
  3248. "fireball_small_arrow",
  3249. "fireball_small_shotgun",
  3250. "fireexplosion"
  3251. };
  3252.  
  3253. public static object HandleDamageBetweenPlayers(User attacker, User defender, HitInfo hit)
  3254. {
  3255. if (!Instance.Options.Pvp.RestrictPvp)
  3256. return null;
  3257.  
  3258. // Allow players to take the easy way out.
  3259. if (hit.damageTypes.Has(Rust.DamageType.Suicide))
  3260. return null;
  3261.  
  3262. // If the players are both in factions who are currently at war, they can damage each other anywhere.
  3263. if (attacker.Faction != null && defender.Faction != null &&
  3264. Instance.Wars.AreFactionsAtWar(attacker.Faction, defender.Faction))
  3265. return null;
  3266.  
  3267. // If both the attacker and the defender are in PVP mode, or in a PVP area/zone, they can damage one another.
  3268. if (IsUserInDanger(attacker) && IsUserInDanger(defender))
  3269. return null;
  3270.  
  3271. // Stop the damage.
  3272. return false;
  3273. }
  3274.  
  3275. public static object HandleIncidentalDamage(User defender, HitInfo hit)
  3276. {
  3277. if (!Instance.Options.Pvp.RestrictPvp)
  3278. return null;
  3279.  
  3280. if (hit.Initiator == null)
  3281. return null;
  3282.  
  3283. // If the damage is coming from something other than a blocked prefab, allow it.
  3284. if (!BlockedPrefabs.Contains(hit.Initiator.ShortPrefabName))
  3285. return null;
  3286.  
  3287. // If the player is in a PVP area or in PVP mode, allow the damage.
  3288. if (IsUserInDanger(defender))
  3289. return null;
  3290.  
  3291. return false;
  3292. }
  3293.  
  3294. public static object HandleTrapTrigger(BaseTrap trap, User defender)
  3295. {
  3296. if (!Instance.Options.Pvp.RestrictPvp)
  3297. return null;
  3298.  
  3299. // A player can always trigger their own traps, to prevent exploiting this mechanic.
  3300. if (defender.Player.userID == trap.OwnerID)
  3301. return null;
  3302.  
  3303. Area trapArea = Instance.Areas.GetByEntityPosition(trap);
  3304.  
  3305. // If the defender is in a faction, they can trigger traps placed in areas claimed by factions with which they are at war.
  3306. if (defender.Faction != null && trapArea.FactionId != null &&
  3307. Instance.Wars.AreFactionsAtWar(defender.Faction.Id, trapArea.FactionId))
  3308. return null;
  3309.  
  3310. // If the defender is in a PVP area or zone, the trap can trigger.
  3311. // TODO: Ensure the trap is also in the PVP zone.
  3312. if (IsUserInDanger(defender))
  3313. return null;
  3314.  
  3315. // Stop the trap from triggering.
  3316. return false;
  3317. }
  3318.  
  3319. public static object HandleTurretTarget(BaseCombatEntity turret, User defender)
  3320. {
  3321. if (!Instance.Options.Pvp.RestrictPvp)
  3322. return null;
  3323.  
  3324. // A player can be always be targeted by their own turrets, to prevent exploiting this mechanic.
  3325. if (defender.Player.userID == turret.OwnerID)
  3326. return null;
  3327.  
  3328. Area turretArea = Instance.Areas.GetByEntityPosition(turret);
  3329.  
  3330. if (turretArea == null || defender.CurrentArea == null)
  3331. return null;
  3332.  
  3333. // If the defender is in a faction, they can be targeted by turrets in areas claimed by factions with which they are at war.
  3334. if (defender.Faction != null && turretArea.FactionId != null &&
  3335. Instance.Wars.AreFactionsAtWar(defender.Faction.Id, turretArea.FactionId))
  3336. return null;
  3337.  
  3338. // If the defender is in a PVP area or zone, the turret can trigger.
  3339. // TODO: Ensure the turret is also in the PVP zone.
  3340. if (IsUserInDanger(defender))
  3341. return null;
  3342.  
  3343. return false;
  3344. }
  3345.  
  3346. static bool IsUserInDanger(User user)
  3347. {
  3348. return user.IsInPvpMode || IsPvpArea(user.CurrentArea) || user.CurrentZones.Any(IsPvpZone);
  3349. }
  3350.  
  3351. static bool IsPvpZone(Zone zone)
  3352. {
  3353. switch (zone.Type)
  3354. {
  3355. case ZoneType.Debris:
  3356. case ZoneType.SupplyDrop:
  3357. return Instance.Options.Pvp.AllowedInEventZones;
  3358. case ZoneType.Monument:
  3359. return Instance.Options.Pvp.AllowedInMonumentZones;
  3360. case ZoneType.Raid:
  3361. return Instance.Options.Pvp.AllowedInRaidZones;
  3362. default:
  3363. throw new InvalidOperationException($"Unknown zone type {zone.Type}");
  3364. }
  3365. }
  3366.  
  3367. static bool IsPvpArea(Area area)
  3368. {
  3369. if (area == null)
  3370. return Instance.Options.Pvp.AllowedInDeepWater;
  3371.  
  3372. switch (area.Type)
  3373. {
  3374. case AreaType.Badlands:
  3375. return Instance.Options.Pvp.AllowedInBadlands;
  3376. case AreaType.Claimed:
  3377. case AreaType.Headquarters:
  3378. return Instance.Options.Pvp.AllowedInClaimedLand;
  3379. case AreaType.Wilderness:
  3380. return Instance.Options.Pvp.AllowedInWilderness;
  3381. default:
  3382. throw new InvalidOperationException($"Unknown area type {area.Type}");
  3383. }
  3384. }
  3385. }
  3386. }
  3387. }
  3388.  
  3389. namespace Oxide.Plugins
  3390. {
  3391. using System;
  3392. using System.Linq;
  3393.  
  3394. public partial class Imperium
  3395. {
  3396. static class Raiding
  3397. {
  3398. // Setting this to true will disable the rules which normally allow owners of land to damage their own structures
  3399. // This means that for the purposes of structural damage, the player will be considered a hostile force, which
  3400. // in turn allows easy testing of raiding rules. Should usually be false unless you're testing something.
  3401. const bool EnableTestMode = false;
  3402.  
  3403. enum DamageResult
  3404. {
  3405. Prevent,
  3406. NotProtected,
  3407. Friendly,
  3408. BeingAttacked
  3409. }
  3410.  
  3411. static string[] BlockedPrefabs = new[]
  3412. {
  3413. "fireball_small",
  3414. "fireball_small_arrow",
  3415. "fireball_small_shotgun",
  3416. "fireexplosion"
  3417. };
  3418.  
  3419. static string[] ProtectedPrefabs = new[]
  3420. {
  3421. "barricade.concrete",
  3422. "barricade.metal",
  3423. "barricade.sandbags",
  3424. "barricade.stone",
  3425. "barricade.wood",
  3426. "barricade.woodwire",
  3427. "bbq",
  3428. "bed",
  3429. "box.wooden.large",
  3430. "ceilinglight",
  3431. "chair",
  3432. "cupboard",
  3433. "door.double.hinged",
  3434. "door.hinged",
  3435. "dropbox",
  3436. "fireplace",
  3437. "floor.ladder.hatch",
  3438. "floor.grill",
  3439. "fridge",
  3440. "furnace",
  3441. "gates.external",
  3442. "jackolantern",
  3443. "lantern",
  3444. "locker",
  3445. "mailbox",
  3446. "planter.large",
  3447. "planter.small",
  3448. "reactivetarget",
  3449. "refinery",
  3450. "repairbench",
  3451. "researchtable",
  3452. "rug",
  3453. "searchlight",
  3454. "shelves",
  3455. "shutter",
  3456. "sign.hanging",
  3457. "sign.huge.wood",
  3458. "sign.large.wood",
  3459. "sign.medium.wood",
  3460. "sign.pictureframe",
  3461. "sign.pole.banner.large",
  3462. "sign.post",
  3463. "sign.small.wood",
  3464. "stash.small",
  3465. "spikes.floor",
  3466. "spinner.wheel",
  3467. "survivalfishtrap",
  3468. "table",
  3469. "tunalight",
  3470. "vendingmachine",
  3471. "wall.external",
  3472. "wall.frame",
  3473. "wall.window",
  3474. "watchtower.wood",
  3475. "water.barrel",
  3476. "water.catcher",
  3477. "water.purifier",
  3478. "waterbarrel",
  3479. "waterpurifier",
  3480. "window.bars",
  3481. "woodbox",
  3482. "workbench",
  3483. "switch",
  3484. "orswitch",
  3485. "andswitch",
  3486. "xorswitch",
  3487. "timer",
  3488. "splitter",
  3489. "blocker",
  3490. "cabletunnel",
  3491. "doorcontroller",
  3492. "generator",
  3493. "laserdetector",
  3494. "pressurepad",
  3495. "simplelight",
  3496. "solarpanel",
  3497. "electrical.branch",
  3498. "electrical.combiner",
  3499. "electrical.memorycell",
  3500. "smallrechargablebattery",
  3501. "large.rechargable.battery"
  3502. };
  3503.  
  3504. static string[] RaidTriggeringPrefabs = new[]
  3505. {
  3506. "cupboard",
  3507. "door.double.hinged",
  3508. "door.hinged",
  3509. "floor.ladder.hatch",
  3510. "floor.grill",
  3511. "gates.external",
  3512. "vendingmachine",
  3513. "wall.frame",
  3514. "wall.external",
  3515. "wall.window",
  3516. "window.bars"
  3517. };
  3518.  
  3519. public static object HandleDamageAgainstStructure(User attacker, BaseEntity entity, HitInfo hit)
  3520. {
  3521. Area area = Instance.Areas.GetByEntityPosition(entity);
  3522.  
  3523. if (area == null)
  3524. {
  3525. Instance.PrintWarning("An entity was damaged in an unknown area. This shouldn't happen.");
  3526. return null;
  3527. }
  3528.  
  3529. DamageResult result = DetermineDamageResult(attacker, area, entity);
  3530.  
  3531. if (EnableTestMode)
  3532. Instance.Log("Damage from a player to structure with prefab {0}: {1}", entity.ShortPrefabName,
  3533. result.ToString());
  3534.  
  3535. if (result == DamageResult.NotProtected || result == DamageResult.Friendly)
  3536. return null;
  3537.  
  3538. if (result == DamageResult.Prevent)
  3539. return false;
  3540.  
  3541. float reduction = area.GetDefensiveBonus();
  3542.  
  3543. if (reduction >= 1)
  3544. return false;
  3545.  
  3546. if (reduction > 0)
  3547. hit.damageTypes.ScaleAll(reduction);
  3548.  
  3549. if (Instance.Options.Zones.Enabled)
  3550. {
  3551. BuildingPrivlidge cupboard = entity.GetBuildingPrivilege();
  3552.  
  3553. if (cupboard != null && IsRaidTriggeringEntity(entity))
  3554. {
  3555. float remainingHealth = entity.Health() - hit.damageTypes.Total();
  3556. if (remainingHealth < 1)
  3557. Instance.Zones.CreateForRaid(cupboard);
  3558. }
  3559. }
  3560.  
  3561. return null;
  3562. }
  3563.  
  3564. static DamageResult DetermineDamageResult(User attacker, Area area, BaseEntity entity)
  3565. {
  3566. // Players can always damage their own entities.
  3567. if (!EnableTestMode && attacker.Player.userID == entity.OwnerID)
  3568. return DamageResult.Friendly;
  3569.  
  3570. if (!IsProtectedEntity(entity))
  3571. return DamageResult.NotProtected;
  3572.  
  3573. if (attacker.Faction != null)
  3574. {
  3575. // Factions can damage any structure built on their own land.
  3576. if (!EnableTestMode && area.FactionId != null && attacker.Faction.Id == area.FactionId)
  3577. return DamageResult.Friendly;
  3578.  
  3579. // Factions who are at war can damage any structure on enemy land, subject to the defensive bonus.
  3580. if (area.FactionId != null && Instance.Wars.AreFactionsAtWar(attacker.Faction.Id, area.FactionId))
  3581. return DamageResult.BeingAttacked;
  3582.  
  3583. // Factions who are at war can damage any structure built by a member of an enemy faction, subject
  3584. // to the defensive bonus.
  3585. BasePlayer owner = BasePlayer.FindByID(entity.OwnerID);
  3586. if (owner != null)
  3587. {
  3588. Faction owningFaction = Instance.Factions.GetByMember(owner.UserIDString);
  3589. if (owningFaction != null && Instance.Wars.AreFactionsAtWar(attacker.Faction, owningFaction))
  3590. return DamageResult.BeingAttacked;
  3591. }
  3592. }
  3593.  
  3594. // If the structure is in a raidable area, it can be damaged subject to the defensive bonus.
  3595. if (IsRaidableArea(area))
  3596. return DamageResult.BeingAttacked;
  3597.  
  3598. // Prevent the damage.
  3599. return DamageResult.Prevent;
  3600. }
  3601.  
  3602. public static object HandleIncidentalDamage(BaseEntity entity, HitInfo hit)
  3603. {
  3604. if (!Instance.Options.Raiding.RestrictRaiding)
  3605. return null;
  3606.  
  3607. Area area = Instance.Areas.GetByEntityPosition(entity);
  3608.  
  3609. if (area == null)
  3610. {
  3611. Instance.PrintWarning("An entity was damaged in an unknown area. This shouldn't happen.");
  3612. return null;
  3613. }
  3614.  
  3615. if (hit.Initiator == null)
  3616. {
  3617. if (EnableTestMode)
  3618. Instance.Log("Incidental damage to {0} with no initiator", entity.ShortPrefabName);
  3619.  
  3620. return null;
  3621. }
  3622.  
  3623. // If the damage is coming from something other than a blocked prefab, allow it.
  3624. if (!BlockedPrefabs.Contains(hit.Initiator.ShortPrefabName))
  3625. {
  3626. if (EnableTestMode)
  3627. Instance.Log("Incidental damage to {0} caused by {1}, allowing since it isn't a blocked prefab",
  3628. entity.ShortPrefabName, hit.Initiator.ShortPrefabName);
  3629.  
  3630. return null;
  3631. }
  3632.  
  3633. // If the player is in a PVP area or in PVP mode, allow the damage.
  3634. if (IsRaidableArea(area))
  3635. {
  3636. if (EnableTestMode)
  3637. Instance.Log(
  3638. "Incidental damage to {0} caused by {1}, allowing since target is in raidable area",
  3639. entity.ShortPrefabName, hit.Initiator.ShortPrefabName);
  3640.  
  3641. return null;
  3642. }
  3643.  
  3644. if (EnableTestMode)
  3645. Instance.Log("Incidental damage to {0} caused by {1}, stopping since it is a blocked prefab",
  3646. entity.ShortPrefabName, hit.Initiator.ShortPrefabName);
  3647.  
  3648. return false;
  3649. }
  3650.  
  3651. static bool IsProtectedEntity(BaseEntity entity)
  3652. {
  3653. var buildingBlock = entity as BuildingBlock;
  3654.  
  3655. // All building blocks except for twig are protected.
  3656. if (buildingBlock != null)
  3657. return buildingBlock.grade != BuildingGrade.Enum.Twigs;
  3658.  
  3659. // Some additional entities (doors, boxes, etc.) are also protected.
  3660. if (ProtectedPrefabs.Any(prefab => entity.ShortPrefabName.Contains(prefab)))
  3661. return true;
  3662.  
  3663. return false;
  3664. }
  3665.  
  3666. static bool IsRaidTriggeringEntity(BaseEntity entity)
  3667. {
  3668. var buildingBlock = entity as BuildingBlock;
  3669.  
  3670. // All building blocks except for twig are protected.
  3671. if (buildingBlock != null)
  3672. return buildingBlock.grade != BuildingGrade.Enum.Twigs;
  3673.  
  3674. // Destriction of some additional entities (doors, etc.) will also trigger raids.
  3675. if (RaidTriggeringPrefabs.Any(prefab => entity.ShortPrefabName.Contains(prefab)))
  3676. return true;
  3677.  
  3678. return false;
  3679. }
  3680.  
  3681. static bool IsRaidableArea(Area area)
  3682. {
  3683. if (!Instance.Options.Raiding.RestrictRaiding)
  3684. return true;
  3685.  
  3686. switch (area.Type)
  3687. {
  3688. case AreaType.Badlands:
  3689. return Instance.Options.Raiding.AllowedInBadlands;
  3690. case AreaType.Claimed:
  3691. case AreaType.Headquarters:
  3692. return Instance.Options.Raiding.AllowedInClaimedLand;
  3693. case AreaType.Wilderness:
  3694. return Instance.Options.Raiding.AllowedInWilderness;
  3695. default:
  3696. throw new InvalidOperationException($"Unknown area type {area.Type}");
  3697. }
  3698. }
  3699. }
  3700. }
  3701. }
  3702.  
  3703. namespace Oxide.Plugins
  3704. {
  3705. public partial class Imperium
  3706. {
  3707. static class Taxes
  3708. {
  3709. public static void ProcessTaxesIfApplicable(ResourceDispenser dispenser, BaseEntity entity, Item item)
  3710. {
  3711. if (!Instance.Options.Taxes.Enabled)
  3712. return;
  3713.  
  3714. var player = entity as BasePlayer;
  3715. if (player == null)
  3716. return;
  3717.  
  3718. User user = Instance.Users.Get(player);
  3719. if (user == null)
  3720. return;
  3721.  
  3722. Area area = user.CurrentArea;
  3723. if (area == null || !area.IsClaimed)
  3724. return;
  3725.  
  3726. Faction faction = Instance.Factions.Get(area.FactionId);
  3727. if (!faction.CanCollectTaxes || faction.TaxChest.inventory.IsFull())
  3728. return;
  3729.  
  3730. ItemDefinition itemDef = ItemManager.FindItemDefinition(item.info.itemid);
  3731. if (itemDef == null)
  3732. return;
  3733.  
  3734. int bonus = (int) (item.amount * Instance.Options.Taxes.ClaimedLandGatherBonus);
  3735. var tax = (int) (item.amount * faction.TaxRate);
  3736.  
  3737. faction.TaxChest.inventory.AddItem(itemDef, tax + bonus);
  3738. item.amount -= tax;
  3739. }
  3740.  
  3741. public static void AwardBadlandsBonusIfApplicable(ResourceDispenser dispenser, BaseEntity entity, Item item)
  3742. {
  3743. if (!Instance.Options.Badlands.Enabled)
  3744. return;
  3745.  
  3746. var player = entity as BasePlayer;
  3747. if (player == null) return;
  3748.  
  3749. User user = Instance.Users.Get(player);
  3750.  
  3751. if (user.CurrentArea != null && user.CurrentArea.Type == AreaType.Badlands)
  3752. {
  3753. var bonus = (int) (item.amount * Instance.Options.Taxes.BadlandsGatherBonus);
  3754. item.amount += bonus;
  3755. }
  3756. }
  3757. }
  3758. }
  3759. }
  3760.  
  3761. namespace Oxide.Plugins
  3762. {
  3763. using System;
  3764. using System.Collections.Generic;
  3765. using System.Linq;
  3766.  
  3767. public partial class Imperium
  3768. {
  3769. static class Upkeep
  3770. {
  3771. public static void CollectForAllFactions()
  3772. {
  3773. foreach (Faction faction in Instance.Factions.GetAll())
  3774. Collect(faction);
  3775. }
  3776.  
  3777. public static void Collect(Faction faction)
  3778. {
  3779. DateTime now = DateTime.UtcNow;
  3780. Area[] areas = Instance.Areas.GetAllTaxableClaimsByFaction(faction);
  3781.  
  3782. if (areas.Length == 0)
  3783. return;
  3784.  
  3785. if (now < faction.NextUpkeepPaymentTime)
  3786. {
  3787. Instance.Log($"[UPKEEP] {faction.Id}: Upkeep not due until {faction.NextUpkeepPaymentTime}");
  3788. return;
  3789. }
  3790.  
  3791. int amountOwed = faction.GetUpkeepPerPeriod();
  3792. var hoursSincePaid = (int) now.Subtract(faction.NextUpkeepPaymentTime).TotalHours;
  3793.  
  3794. Instance.Log(
  3795. $"[UPKEEP] {faction.Id}: {hoursSincePaid} hours since upkeep paid, trying to collect {amountOwed} scrap for {areas.Length} area claims");
  3796.  
  3797. var headquarters = areas.Where(a => a.Type == AreaType.Headquarters).FirstOrDefault();
  3798. if (headquarters == null || headquarters.ClaimCupboard == null)
  3799. {
  3800. Instance.Log($"[UPKEEP] {faction.Id}: Couldn't collect upkeep, faction has no headquarters");
  3801. }
  3802. else
  3803. {
  3804. ItemDefinition scrapDef = ItemManager.FindItemDefinition("scrap");
  3805. ItemContainer container = headquarters.ClaimCupboard.inventory;
  3806. List<Item> stacks = container.FindItemsByItemID(scrapDef.itemid);
  3807.  
  3808. if (Instance.TryCollectFromStacks(scrapDef, stacks, amountOwed))
  3809. {
  3810. faction.NextUpkeepPaymentTime =
  3811. faction.NextUpkeepPaymentTime.AddHours(Instance.Options.Upkeep.CollectionPeriodHours);
  3812. faction.IsUpkeepPastDue = false;
  3813. Instance.Log(
  3814. $"[UPKEEP] {faction.Id}: {amountOwed} scrap upkeep collected, next payment due {faction.NextUpkeepPaymentTime}");
  3815. return;
  3816. }
  3817. }
  3818.  
  3819. faction.IsUpkeepPastDue = true;
  3820.  
  3821. if (hoursSincePaid <= Instance.Options.Upkeep.GracePeriodHours)
  3822. {
  3823. Instance.Log(
  3824. $"[UPKEEP] {faction.Id}: Couldn't collect upkeep, but still within {Instance.Options.Upkeep.GracePeriodHours} hour grace period");
  3825. return;
  3826. }
  3827.  
  3828. Area lostArea = areas.OrderBy(area => Instance.Areas.GetDepthInsideFriendlyTerritory(area)).First();
  3829.  
  3830. Instance.Log(
  3831. $"[UPKEEP] {faction.Id}: Upkeep not paid in {hoursSincePaid} hours, seizing claim on {lostArea.Id}");
  3832. Instance.PrintToChat(Messages.AreaClaimLostUpkeepNotPaidAnnouncement, faction.Id, lostArea.Id);
  3833.  
  3834. Instance.Areas.Unclaim(lostArea);
  3835. }
  3836. }
  3837. }
  3838. }
  3839.  
  3840. namespace Oxide.Plugins
  3841. {
  3842. using Rust;
  3843. using UnityEngine;
  3844.  
  3845. public partial class Imperium
  3846. {
  3847. class Area : MonoBehaviour
  3848. {
  3849. public Vector3 Position { get; private set; }
  3850. public Vector3 Size { get; private set; }
  3851.  
  3852. public string Id { get; private set; }
  3853. public int Row { get; private set; }
  3854. public int Col { get; private set; }
  3855.  
  3856. public AreaType Type { get; set; }
  3857. public string Name { get; set; }
  3858. public string FactionId { get; set; }
  3859. public string ClaimantId { get; set; }
  3860. public BuildingPrivlidge ClaimCupboard { get; set; }
  3861.  
  3862. public bool IsClaimed
  3863. {
  3864. get { return FactionId != null; }
  3865. }
  3866.  
  3867. public bool IsTaxableClaim
  3868. {
  3869. get { return Type == AreaType.Claimed || Type == AreaType.Headquarters; }
  3870. }
  3871.  
  3872. public bool IsWarZone
  3873. {
  3874. get { return GetActiveWars().Length > 0; }
  3875. }
  3876.  
  3877. public void Init(string id, int row, int col, Vector3 position, Vector3 size, AreaInfo info)
  3878. {
  3879. Id = id;
  3880. Row = row;
  3881. Col = col;
  3882. Position = position;
  3883. Size = size;
  3884.  
  3885. if (info != null)
  3886. TryLoadInfo(info);
  3887.  
  3888. gameObject.layer = (int) Layer.Reserved1;
  3889. gameObject.name = $"imperium_area_{id}";
  3890. transform.position = position;
  3891. transform.rotation = Quaternion.Euler(new Vector3(0, 0, 0));
  3892.  
  3893. var collider = gameObject.AddComponent<BoxCollider>();
  3894. collider.size = Size;
  3895. collider.isTrigger = true;
  3896. collider.enabled = true;
  3897.  
  3898. gameObject.SetActive(true);
  3899. enabled = true;
  3900. }
  3901.  
  3902. void Awake()
  3903. {
  3904. InvokeRepeating("CheckClaimCupboard", 60f, 60f);
  3905. }
  3906.  
  3907. void OnDestroy()
  3908. {
  3909. var collider = GetComponent<BoxCollider>();
  3910.  
  3911. if (collider != null)
  3912. Destroy(collider);
  3913.  
  3914. if (IsInvoking("CheckClaimCupboard"))
  3915. CancelInvoke("CheckClaimCupboard");
  3916. }
  3917.  
  3918. void TryLoadInfo(AreaInfo info)
  3919. {
  3920. BuildingPrivlidge cupboard = null;
  3921.  
  3922. if (info.CupboardId != null)
  3923. {
  3924. cupboard = BaseNetworkable.serverEntities.Find((uint) info.CupboardId) as BuildingPrivlidge;
  3925. if (cupboard == null)
  3926. {
  3927. Instance.Log(
  3928. $"[LOAD] Area {Id}: Cupboard entity {info.CupboardId} not found, treating as unclaimed");
  3929. return;
  3930. }
  3931. }
  3932.  
  3933. if (info.FactionId != null)
  3934. {
  3935. Faction faction = Instance.Factions.Get(info.FactionId);
  3936. if (faction == null)
  3937. {
  3938. Instance.Log(
  3939. $"[LOAD] Area {Id}: Claimed by unknown faction {info.FactionId}, treating as unclaimed");
  3940. return;
  3941. }
  3942. }
  3943.  
  3944. Name = info.Name;
  3945. Type = info.Type;
  3946. FactionId = info.FactionId;
  3947. ClaimantId = info.ClaimantId;
  3948. ClaimCupboard = cupboard;
  3949.  
  3950. if (FactionId != null)
  3951. Instance.Log(
  3952. $"[LOAD] Area {Id}: Claimed by {FactionId}, type = {Type}, cupboard = {Util.Format(ClaimCupboard)}");
  3953. }
  3954.  
  3955. void CheckClaimCupboard()
  3956. {
  3957. if (ClaimCupboard == null || !ClaimCupboard.IsDestroyed)
  3958. return;
  3959.  
  3960. Instance.Log(
  3961. $"{FactionId} lost their claim on {Id} because the tool cupboard was destroyed (periodic check)");
  3962. Instance.PrintToChat(Messages.AreaClaimLostCupboardDestroyedAnnouncement, FactionId, Id);
  3963. Instance.Areas.Unclaim(this);
  3964. }
  3965.  
  3966. void OnTriggerEnter(Collider collider)
  3967. {
  3968. if (collider.gameObject.layer != (int) Layer.Player_Server)
  3969. return;
  3970.  
  3971. var user = collider.GetComponentInParent<User>();
  3972.  
  3973. if (user != null && user.CurrentArea != this)
  3974. Events.OnUserEnteredArea(user, this);
  3975. }
  3976.  
  3977. void OnTriggerExit(Collider collider)
  3978. {
  3979. if (collider.gameObject.layer != (int) Layer.Player_Server)
  3980. return;
  3981.  
  3982. var user = collider.GetComponentInParent<User>();
  3983.  
  3984. if (user != null)
  3985. Events.OnUserLeftArea(user, this);
  3986. }
  3987.  
  3988. public float GetDistanceFromEntity(BaseEntity entity)
  3989. {
  3990. return Vector3.Distance(entity.transform.position, transform.position);
  3991. }
  3992.  
  3993. public int GetClaimCost(Faction faction)
  3994. {
  3995. var costs = Instance.Options.Claims.Costs;
  3996. int numberOfAreasOwned = Instance.Areas.GetAllClaimedByFaction(faction).Length;
  3997. int index = Mathf.Clamp(numberOfAreasOwned, 0, costs.Count - 1);
  3998. return costs[index];
  3999. }
  4000.  
  4001. public float GetDefensiveBonus()
  4002. {
  4003. var bonuses = Instance.Options.War.DefensiveBonuses;
  4004. var depth = Instance.Areas.GetDepthInsideFriendlyTerritory(this);
  4005. int index = Mathf.Clamp(depth, 0, bonuses.Count - 1);
  4006. return bonuses[index];
  4007. }
  4008.  
  4009. public float GetTaxRate()
  4010. {
  4011. if (!IsTaxableClaim)
  4012. return 0;
  4013.  
  4014. Faction faction = Instance.Factions.Get(FactionId);
  4015.  
  4016. if (!faction.CanCollectTaxes)
  4017. return 0;
  4018.  
  4019. return faction.TaxRate;
  4020. }
  4021.  
  4022. public War[] GetActiveWars()
  4023. {
  4024. if (FactionId == null)
  4025. return new War[0];
  4026.  
  4027. return Instance.Wars.GetAllActiveWarsByFaction(FactionId);
  4028. }
  4029.  
  4030. public AreaInfo Serialize()
  4031. {
  4032. return new AreaInfo
  4033. {
  4034. Id = Id,
  4035. Name = Name,
  4036. Type = Type,
  4037. FactionId = FactionId,
  4038. ClaimantId = ClaimantId,
  4039. CupboardId = ClaimCupboard?.net?.ID
  4040. };
  4041. }
  4042. }
  4043. }
  4044. }
  4045.  
  4046. namespace Oxide.Plugins
  4047. {
  4048. using Newtonsoft.Json;
  4049. using Newtonsoft.Json.Converters;
  4050.  
  4051. public partial class Imperium : RustPlugin
  4052. {
  4053. public class AreaInfo
  4054. {
  4055. [JsonProperty("id")] public string Id;
  4056.  
  4057. [JsonProperty("name")] public string Name;
  4058.  
  4059. [JsonProperty("type"), JsonConverter(typeof(StringEnumConverter))]
  4060. public AreaType Type;
  4061.  
  4062. [JsonProperty("factionId")] public string FactionId;
  4063.  
  4064. [JsonProperty("claimantId")] public string ClaimantId;
  4065.  
  4066. [JsonProperty("cupboardId")] public uint? CupboardId;
  4067. }
  4068. }
  4069. }
  4070.  
  4071. namespace Oxide.Plugins
  4072. {
  4073. using System;
  4074. using System.Collections.Generic;
  4075. using System.Linq;
  4076. using UnityEngine;
  4077.  
  4078. public partial class Imperium
  4079. {
  4080. class AreaManager
  4081. {
  4082. Dictionary<string, Area> Areas;
  4083. Area[,] Layout;
  4084.  
  4085. public MapGrid MapGrid { get; }
  4086.  
  4087. public int Count
  4088. {
  4089. get { return Areas.Count; }
  4090. }
  4091.  
  4092. public AreaManager()
  4093. {
  4094. MapGrid = new MapGrid();
  4095. Areas = new Dictionary<string, Area>();
  4096. Layout = new Area[MapGrid.NumberOfCells, MapGrid.NumberOfCells];
  4097. }
  4098.  
  4099. public Area Get(string areaId)
  4100. {
  4101. Area area;
  4102. if (Areas.TryGetValue(areaId, out area))
  4103. return area;
  4104. else
  4105. return null;
  4106. }
  4107.  
  4108. public Area Get(int row, int col)
  4109. {
  4110. return Layout[row, col];
  4111. }
  4112.  
  4113. public Area[] GetAll()
  4114. {
  4115. return Areas.Values.ToArray();
  4116. }
  4117.  
  4118. public Area[] GetAllByType(AreaType type)
  4119. {
  4120. return Areas.Values.Where(a => a.Type == type).ToArray();
  4121. }
  4122.  
  4123. public Area[] GetAllClaimedByFaction(Faction faction)
  4124. {
  4125. return GetAllClaimedByFaction(faction.Id);
  4126. }
  4127.  
  4128. public Area[] GetAllClaimedByFaction(string factionId)
  4129. {
  4130. return Areas.Values.Where(a => a.FactionId == factionId).ToArray();
  4131. }
  4132.  
  4133. public Area[] GetAllTaxableClaimsByFaction(Faction faction)
  4134. {
  4135. return GetAllTaxableClaimsByFaction(faction.Id);
  4136. }
  4137.  
  4138. public Area[] GetAllTaxableClaimsByFaction(string factionId)
  4139. {
  4140. return Areas.Values.Where(a => a.FactionId == factionId && a.IsTaxableClaim).ToArray();
  4141. }
  4142.  
  4143. public Area GetByClaimCupboard(BuildingPrivlidge cupboard)
  4144. {
  4145. return GetByClaimCupboard(cupboard.net.ID);
  4146. }
  4147.  
  4148. public Area GetByClaimCupboard(uint cupboardId)
  4149. {
  4150. return Areas.Values.FirstOrDefault(a =>
  4151. a.ClaimCupboard != null && a.ClaimCupboard.net.ID == cupboardId);
  4152. }
  4153.  
  4154. public Area GetByEntityPosition(BaseEntity entity)
  4155. {
  4156. Vector3 position = entity.transform.position;
  4157.  
  4158. int row = (int) (MapGrid.MapSize / 2 - position.z) / MapGrid.CellSize;
  4159. int col = (int) (position.x + MapGrid.MapSize / 2) / MapGrid.CellSize;
  4160.  
  4161. if (row < 0 || col < 0 || row >= MapGrid.NumberOfCells || col >= MapGrid.NumberOfCells)
  4162. return null;
  4163.  
  4164. return Layout[row, col];
  4165. }
  4166.  
  4167. public void Claim(Area area, AreaType type, Faction faction, User claimant, BuildingPrivlidge cupboard)
  4168. {
  4169. area.Type = type;
  4170. area.FactionId = faction.Id;
  4171. area.ClaimantId = claimant.Id;
  4172. area.ClaimCupboard = cupboard;
  4173.  
  4174. Events.OnAreaChanged(area);
  4175. }
  4176.  
  4177. public void SetHeadquarters(Area area, Faction faction)
  4178. {
  4179. // Ensure that no other areas are considered headquarters.
  4180. foreach (Area otherArea in GetAllClaimedByFaction(faction).Where(a => a.Type == AreaType.Headquarters))
  4181. {
  4182. otherArea.Type = AreaType.Claimed;
  4183. Events.OnAreaChanged(otherArea);
  4184. }
  4185.  
  4186. area.Type = AreaType.Headquarters;
  4187. Events.OnAreaChanged(area);
  4188. }
  4189.  
  4190. public void Unclaim(IEnumerable<Area> areas)
  4191. {
  4192. Unclaim(areas.ToArray());
  4193. }
  4194.  
  4195. public void Unclaim(params Area[] areas)
  4196. {
  4197. foreach (Area area in areas)
  4198. {
  4199. area.Type = AreaType.Wilderness;
  4200. area.FactionId = null;
  4201. area.ClaimantId = null;
  4202. area.ClaimCupboard = null;
  4203.  
  4204. Events.OnAreaChanged(area);
  4205. }
  4206. }
  4207.  
  4208. public void AddBadlands(params Area[] areas)
  4209. {
  4210. foreach (Area area in areas)
  4211. {
  4212. area.Type = AreaType.Badlands;
  4213. area.FactionId = null;
  4214. area.ClaimantId = null;
  4215. area.ClaimCupboard = null;
  4216.  
  4217. Events.OnAreaChanged(area);
  4218. }
  4219. }
  4220.  
  4221. public void AddBadlands(IEnumerable<Area> areas)
  4222. {
  4223. AddBadlands(areas.ToArray());
  4224. }
  4225.  
  4226. public int GetNumberOfContiguousClaimedAreas(Area area, Faction owner)
  4227. {
  4228. int count = 0;
  4229.  
  4230. // North
  4231. if (area.Row > 0 && Layout[area.Row - 1, area.Col].FactionId == owner.Id)
  4232. count++;
  4233.  
  4234. // South
  4235. if (area.Row < MapGrid.NumberOfCells - 1 && Layout[area.Row + 1, area.Col].FactionId == owner.Id)
  4236. count++;
  4237.  
  4238. // West
  4239. if (area.Col > 0 && Layout[area.Row, area.Col - 1].FactionId == owner.Id)
  4240. count++;
  4241.  
  4242. // East
  4243. if (area.Col < MapGrid.NumberOfCells - 1 && Layout[area.Row, area.Col + 1].FactionId == owner.Id)
  4244. count++;
  4245.  
  4246. return count;
  4247. }
  4248.  
  4249. public int GetDepthInsideFriendlyTerritory(Area area)
  4250. {
  4251. if (!area.IsClaimed)
  4252. return 0;
  4253.  
  4254. var depth = new int[4];
  4255.  
  4256. // North
  4257. for (var row = area.Row; row >= 0; row--)
  4258. {
  4259. if (Layout[row, area.Col].FactionId != area.FactionId)
  4260. break;
  4261.  
  4262. depth[0]++;
  4263. }
  4264.  
  4265. // South
  4266. for (var row = area.Row; row < MapGrid.NumberOfCells; row++)
  4267. {
  4268. if (Layout[row, area.Col].FactionId != area.FactionId)
  4269. break;
  4270.  
  4271. depth[1]++;
  4272. }
  4273.  
  4274. // West
  4275. for (var col = area.Col; col >= 0; col--)
  4276. {
  4277. if (Layout[area.Row, col].FactionId != area.FactionId)
  4278. break;
  4279.  
  4280. depth[2]++;
  4281. }
  4282.  
  4283. // East
  4284. for (var col = area.Col; col < MapGrid.NumberOfCells; col++)
  4285. {
  4286. if (Layout[area.Row, col].FactionId != area.FactionId)
  4287. break;
  4288.  
  4289. depth[3]++;
  4290. }
  4291.  
  4292. return depth.Min() - 1;
  4293. }
  4294.  
  4295. public void Init(IEnumerable<AreaInfo> areaInfos)
  4296. {
  4297. Instance.Puts("Creating area objects...");
  4298.  
  4299. Dictionary<string, AreaInfo> lookup;
  4300. if (areaInfos != null)
  4301. lookup = areaInfos.ToDictionary(a => a.Id);
  4302. else
  4303. lookup = new Dictionary<string, AreaInfo>();
  4304.  
  4305. for (var row = 0; row < MapGrid.NumberOfCells; row++)
  4306. {
  4307. for (var col = 0; col < MapGrid.NumberOfCells; col++)
  4308. {
  4309. string areaId = MapGrid.GetAreaId(row, col);
  4310. Vector3 position = MapGrid.GetPosition(row, col);
  4311. Vector3 size = new Vector3(MapGrid.CellSize, 500, MapGrid.CellSize);
  4312.  
  4313. AreaInfo info = null;
  4314. lookup.TryGetValue(areaId, out info);
  4315.  
  4316. var area = new GameObject().AddComponent<Area>();
  4317. area.Init(areaId, row, col, position, size, info);
  4318.  
  4319. Areas[areaId] = area;
  4320. Layout[row, col] = area;
  4321. }
  4322. }
  4323.  
  4324. Instance.Puts($"Created {Areas.Values.Count} area objects.");
  4325. }
  4326.  
  4327. public void Destroy()
  4328. {
  4329. Area[] areas = UnityEngine.Object.FindObjectsOfType<Area>();
  4330.  
  4331. if (areas != null)
  4332. {
  4333. Instance.Puts($"Destroying {areas.Length} area objects...");
  4334. foreach (Area area in areas)
  4335. UnityEngine.Object.Destroy(area);
  4336. }
  4337.  
  4338. Areas.Clear();
  4339. Array.Clear(Layout, 0, Layout.Length);
  4340.  
  4341. Instance.Puts("Area objects destroyed.");
  4342. }
  4343.  
  4344. public AreaInfo[] Serialize()
  4345. {
  4346. return Areas.Values.Select(area => area.Serialize()).ToArray();
  4347. }
  4348. }
  4349. }
  4350. }
  4351.  
  4352. namespace Oxide.Plugins
  4353. {
  4354. public partial class Imperium : RustPlugin
  4355. {
  4356. public enum AreaType
  4357. {
  4358. Wilderness,
  4359. Claimed,
  4360. Headquarters,
  4361. Badlands
  4362. }
  4363. }
  4364. }
  4365.  
  4366. namespace Oxide.Plugins
  4367. {
  4368. using System;
  4369. using System.Collections.Generic;
  4370. using System.Linq;
  4371. using UnityEngine;
  4372.  
  4373. public partial class Imperium
  4374. {
  4375. class Faction
  4376. {
  4377. public string Id { get; private set; }
  4378. public string OwnerId { get; private set; }
  4379. public HashSet<string> MemberIds { get; }
  4380. public HashSet<string> ManagerIds { get; }
  4381. public HashSet<string> InviteIds { get; }
  4382.  
  4383. public float TaxRate { get; set; }
  4384. public StorageContainer TaxChest { get; set; }
  4385. public DateTime NextUpkeepPaymentTime { get; set; }
  4386. public bool IsUpkeepPastDue { get; set; }
  4387.  
  4388. public bool CanCollectTaxes
  4389. {
  4390. get { return TaxChest != null; }
  4391. }
  4392.  
  4393. public int MemberCount
  4394. {
  4395. get { return MemberIds.Count; }
  4396. }
  4397.  
  4398. public Faction(string id, User owner)
  4399. {
  4400. Id = id;
  4401.  
  4402. OwnerId = owner.Id;
  4403. MemberIds = new HashSet<string> {owner.Id};
  4404. ManagerIds = new HashSet<string>();
  4405. InviteIds = new HashSet<string>();
  4406.  
  4407. TaxRate = Instance.Options.Taxes.DefaultTaxRate;
  4408. NextUpkeepPaymentTime = DateTime.UtcNow.AddHours(Instance.Options.Upkeep.CollectionPeriodHours);
  4409. }
  4410.  
  4411. public Faction(FactionInfo info)
  4412. {
  4413. Id = info.Id;
  4414.  
  4415. OwnerId = info.OwnerId;
  4416. MemberIds = new HashSet<string>(info.MemberIds);
  4417. ManagerIds = new HashSet<string>(info.ManagerIds);
  4418. InviteIds = new HashSet<string>(info.InviteIds);
  4419.  
  4420. if (info.TaxChestId != null)
  4421. {
  4422. var taxChest = BaseNetworkable.serverEntities.Find((uint) info.TaxChestId) as StorageContainer;
  4423.  
  4424. if (taxChest == null || taxChest.IsDestroyed)
  4425. Instance.Log($"[LOAD] Faction {Id}: Tax chest entity {info.TaxChestId} was not found");
  4426. else
  4427. TaxChest = taxChest;
  4428. }
  4429.  
  4430. TaxRate = info.TaxRate;
  4431. NextUpkeepPaymentTime = info.NextUpkeepPaymentTime;
  4432. IsUpkeepPastDue = info.IsUpkeepPastDue;
  4433.  
  4434. Instance.Log($"[LOAD] Faction {Id}: {MemberIds.Count} members, tax chest = {Util.Format(TaxChest)}");
  4435. }
  4436.  
  4437. public bool AddMember(User user)
  4438. {
  4439. if (!MemberIds.Add(user.Id))
  4440. return false;
  4441.  
  4442. InviteIds.Remove(user.Id);
  4443.  
  4444. Events.OnPlayerJoinedFaction(this, user);
  4445. return true;
  4446. }
  4447.  
  4448. public bool RemoveMember(User user)
  4449. {
  4450. if (!HasMember(user.Id))
  4451. return false;
  4452.  
  4453. if (HasOwner(user.Id))
  4454. {
  4455. if (ManagerIds.Count > 0)
  4456. {
  4457. OwnerId = ManagerIds.FirstOrDefault();
  4458. ManagerIds.Remove(OwnerId);
  4459. }
  4460. else
  4461. {
  4462. OwnerId = MemberIds.FirstOrDefault();
  4463. }
  4464. }
  4465.  
  4466. MemberIds.Remove(user.Id);
  4467. ManagerIds.Remove(user.Id);
  4468.  
  4469. Events.OnPlayerLeftFaction(this, user);
  4470. return true;
  4471. }
  4472.  
  4473. public bool AddInvite(User user)
  4474. {
  4475. if (!InviteIds.Add(user.Id))
  4476. return false;
  4477.  
  4478. Events.OnPlayerInvitedToFaction(this, user);
  4479. return true;
  4480. }
  4481.  
  4482. public bool RemoveInvite(User user)
  4483. {
  4484. if (!InviteIds.Remove(user.Id))
  4485. return false;
  4486.  
  4487. Events.OnPlayerUninvitedFromFaction(this, user);
  4488. return true;
  4489. }
  4490.  
  4491. public bool Promote(User user)
  4492. {
  4493. if (!MemberIds.Contains(user.Id))
  4494. throw new InvalidOperationException(
  4495. $"Cannot promote player {user.Id} in faction {Id}, since they are not a member");
  4496.  
  4497. if (!ManagerIds.Add(user.Id))
  4498. return false;
  4499.  
  4500. Events.OnPlayerPromoted(this, user);
  4501. return true;
  4502. }
  4503.  
  4504. public bool Demote(User user)
  4505. {
  4506. if (!MemberIds.Contains(user.Id))
  4507. throw new InvalidOperationException(
  4508. $"Cannot demote player {user.Id} in faction {Id}, since they are not a member");
  4509.  
  4510. if (!ManagerIds.Remove(user.Id))
  4511. return false;
  4512.  
  4513. Events.OnPlayerDemoted(this, user);
  4514. return true;
  4515. }
  4516.  
  4517. public bool HasOwner(User user)
  4518. {
  4519. return HasOwner(user.Id);
  4520. }
  4521.  
  4522. public bool HasOwner(string userId)
  4523. {
  4524. return OwnerId == userId;
  4525. }
  4526.  
  4527. public bool HasLeader(User user)
  4528. {
  4529. return HasLeader(user.Id);
  4530. }
  4531.  
  4532. public bool HasLeader(string userId)
  4533. {
  4534. return HasOwner(userId) || HasManager(userId);
  4535. }
  4536.  
  4537. public bool HasManager(User user)
  4538. {
  4539. return HasManager(user.Id);
  4540. }
  4541.  
  4542. public bool HasManager(string userId)
  4543. {
  4544. return ManagerIds.Contains(userId);
  4545. }
  4546.  
  4547. public bool HasInvite(User user)
  4548. {
  4549. return HasInvite(user.Player.UserIDString);
  4550. }
  4551.  
  4552. public bool HasInvite(string userId)
  4553. {
  4554. return InviteIds.Contains(userId);
  4555. }
  4556.  
  4557. public bool HasMember(User user)
  4558. {
  4559. return HasMember(user.Player.UserIDString);
  4560. }
  4561.  
  4562. public bool HasMember(string userId)
  4563. {
  4564. return MemberIds.Contains(userId);
  4565. }
  4566.  
  4567. public User[] GetAllActiveMembers()
  4568. {
  4569. return MemberIds.Select(id => Instance.Users.Get(id)).Where(user => user != null).ToArray();
  4570. }
  4571.  
  4572. public User[] GetAllActiveInvitedUsers()
  4573. {
  4574. return InviteIds.Select(id => Instance.Users.Get(id)).Where(user => user != null).ToArray();
  4575. }
  4576.  
  4577. public int GetUpkeepPerPeriod()
  4578. {
  4579. var costs = Instance.Options.Upkeep.Costs;
  4580.  
  4581. int totalCost = 0;
  4582. for (var num = 0; num < Instance.Areas.GetAllTaxableClaimsByFaction(this).Length; num++)
  4583. {
  4584. var index = Mathf.Clamp(num, 0, costs.Count - 1);
  4585. totalCost += costs[index];
  4586. }
  4587.  
  4588. return totalCost;
  4589. }
  4590.  
  4591. public void SendChatMessage(string message, params object[] args)
  4592. {
  4593. foreach (User user in GetAllActiveMembers())
  4594. user.SendChatMessage(message, args);
  4595. }
  4596.  
  4597. public FactionInfo Serialize()
  4598. {
  4599. return new FactionInfo
  4600. {
  4601. Id = Id,
  4602. OwnerId = OwnerId,
  4603. MemberIds = MemberIds.ToArray(),
  4604. ManagerIds = ManagerIds.ToArray(),
  4605. InviteIds = InviteIds.ToArray(),
  4606. TaxRate = TaxRate,
  4607. TaxChestId = TaxChest?.net?.ID,
  4608. NextUpkeepPaymentTime = NextUpkeepPaymentTime
  4609. };
  4610. }
  4611. }
  4612. }
  4613. }
  4614.  
  4615. namespace Oxide.Plugins
  4616. {
  4617. using UnityEngine;
  4618.  
  4619. public partial class Imperium
  4620. {
  4621. class FactionEntityMonitor : MonoBehaviour
  4622. {
  4623. void Awake()
  4624. {
  4625. InvokeRepeating("CheckTaxChests", 60f, 60f);
  4626. }
  4627.  
  4628. void OnDestroy()
  4629. {
  4630. if (IsInvoking("CheckTaxChests")) CancelInvoke("CheckTaxChests");
  4631. }
  4632.  
  4633. void EnsureAllTaxChestsStillExist()
  4634. {
  4635. foreach (Faction faction in Instance.Factions.GetAll())
  4636. EnsureTaxChestExists(faction);
  4637. }
  4638.  
  4639. void EnsureTaxChestExists(Faction faction)
  4640. {
  4641. if (faction.TaxChest == null || !faction.TaxChest.IsDestroyed)
  4642. return;
  4643.  
  4644. Instance.Log($"{faction.Id}'s tax chest was destroyed (periodic check)");
  4645. faction.TaxChest = null;
  4646. }
  4647. }
  4648. }
  4649. }
  4650.  
  4651. namespace Oxide.Plugins
  4652. {
  4653. using System;
  4654. using Newtonsoft.Json;
  4655.  
  4656. public partial class Imperium : RustPlugin
  4657. {
  4658. class FactionInfo
  4659. {
  4660. [JsonProperty("id")] public string Id;
  4661.  
  4662. [JsonProperty("ownerId")] public string OwnerId;
  4663.  
  4664. [JsonProperty("memberIds")] public string[] MemberIds;
  4665.  
  4666. [JsonProperty("managerIds")] public string[] ManagerIds;
  4667.  
  4668. [JsonProperty("inviteIds")] public string[] InviteIds;
  4669.  
  4670. [JsonProperty("taxRate")] public float TaxRate;
  4671.  
  4672. [JsonProperty("taxChestId")] public uint? TaxChestId;
  4673.  
  4674. [JsonProperty("nextUpkeepPaymentTime")]
  4675. public DateTime NextUpkeepPaymentTime;
  4676.  
  4677. [JsonProperty("isUpkeepPastDue")] public bool IsUpkeepPastDue;
  4678. }
  4679. }
  4680. }
  4681.  
  4682. namespace Oxide.Plugins
  4683. {
  4684. using System;
  4685. using System.Collections.Generic;
  4686. using System.Linq;
  4687. using UnityEngine;
  4688.  
  4689. public partial class Imperium
  4690. {
  4691. class FactionManager
  4692. {
  4693. Dictionary<string, Faction> Factions = new Dictionary<string, Faction>();
  4694. FactionEntityMonitor EntityMonitor;
  4695.  
  4696. public FactionManager()
  4697. {
  4698. Factions = new Dictionary<string, Faction>();
  4699. EntityMonitor = Instance.GameObject.AddComponent<FactionEntityMonitor>();
  4700. }
  4701.  
  4702. public Faction Create(string id, User owner)
  4703. {
  4704. Faction faction;
  4705.  
  4706. if (Factions.TryGetValue(id, out faction))
  4707. throw new InvalidOperationException(
  4708. $"Cannot create a new faction named ${id}, since one already exists");
  4709.  
  4710. faction = new Faction(id, owner);
  4711. Factions.Add(id, faction);
  4712.  
  4713. Events.OnFactionCreated(faction);
  4714.  
  4715. return faction;
  4716. }
  4717.  
  4718. public void Disband(Faction faction)
  4719. {
  4720. foreach (User user in faction.GetAllActiveMembers())
  4721. user.SetFaction(null);
  4722.  
  4723. Factions.Remove(faction.Id);
  4724. Events.OnFactionDisbanded(faction);
  4725. }
  4726.  
  4727. public Faction[] GetAll()
  4728. {
  4729. return Factions.Values.ToArray();
  4730. }
  4731.  
  4732. public Faction Get(string id)
  4733. {
  4734. Faction faction;
  4735. if (Factions.TryGetValue(id, out faction))
  4736. return faction;
  4737. else
  4738. return null;
  4739. }
  4740.  
  4741. public bool Exists(string id)
  4742. {
  4743. return Factions.ContainsKey(id);
  4744. }
  4745.  
  4746. public Faction GetByMember(User user)
  4747. {
  4748. return GetByMember(user.Id);
  4749. }
  4750.  
  4751. public Faction GetByMember(string userId)
  4752. {
  4753. return Factions.Values.Where(f => f.HasMember(userId)).FirstOrDefault();
  4754. }
  4755.  
  4756. public Faction GetByTaxChest(StorageContainer container)
  4757. {
  4758. return GetByTaxChest(container.net.ID);
  4759. }
  4760.  
  4761. public Faction GetByTaxChest(uint containerId)
  4762. {
  4763. return Factions.Values.SingleOrDefault(f => f.TaxChest != null && f.TaxChest.net.ID == containerId);
  4764. }
  4765.  
  4766. public void SetTaxRate(Faction faction, float taxRate)
  4767. {
  4768. faction.TaxRate = taxRate;
  4769. Events.OnFactionTaxesChanged(faction);
  4770. }
  4771.  
  4772. public void SetTaxChest(Faction faction, StorageContainer taxChest)
  4773. {
  4774. faction.TaxChest = taxChest;
  4775. Events.OnFactionTaxesChanged(faction);
  4776. }
  4777.  
  4778. public void Init(IEnumerable<FactionInfo> factionInfos)
  4779. {
  4780. Instance.Puts($"Creating factions for {factionInfos.Count()} factions...");
  4781.  
  4782. foreach (FactionInfo info in factionInfos)
  4783. {
  4784. Faction faction = new Faction(info);
  4785. Factions.Add(faction.Id, faction);
  4786. }
  4787.  
  4788. Instance.Puts("Factions created.");
  4789. }
  4790.  
  4791. public void Destroy()
  4792. {
  4793. UnityEngine.Object.Destroy(EntityMonitor);
  4794. Factions.Clear();
  4795. }
  4796.  
  4797. public FactionInfo[] Serialize()
  4798. {
  4799. return Factions.Values.Select(faction => faction.Serialize()).ToArray();
  4800. }
  4801. }
  4802. }
  4803. }
  4804.  
  4805. namespace Oxide.Plugins
  4806. {
  4807. using UnityEngine;
  4808.  
  4809. public partial class Imperium
  4810. {
  4811. class Pin
  4812. {
  4813. public Vector3 Position { get; }
  4814. public string AreaId { get; }
  4815. public string CreatorId { get; set; }
  4816. public PinType Type { get; set; }
  4817. public string Name { get; set; }
  4818.  
  4819. public Pin(Vector3 position, Area area, User creator, PinType type, string name)
  4820. {
  4821. Position = position;
  4822. AreaId = area.Id;
  4823. CreatorId = creator.Id;
  4824. Type = type;
  4825. Name = name;
  4826. }
  4827.  
  4828. public Pin(PinInfo info)
  4829. {
  4830. Position = info.Position;
  4831. AreaId = info.AreaId;
  4832. CreatorId = info.CreatorId;
  4833. Type = info.Type;
  4834. Name = info.Name;
  4835. }
  4836.  
  4837. public float GetDistanceFrom(BaseEntity entity)
  4838. {
  4839. return GetDistanceFrom(entity.transform.position);
  4840. }
  4841.  
  4842. public float GetDistanceFrom(Vector3 position)
  4843. {
  4844. return Vector3.Distance(position, Position);
  4845. }
  4846.  
  4847. public PinInfo Serialize()
  4848. {
  4849. return new PinInfo
  4850. {
  4851. Position = Position,
  4852. AreaId = AreaId,
  4853. CreatorId = CreatorId,
  4854. Type = Type,
  4855. Name = Name
  4856. };
  4857. }
  4858. }
  4859. }
  4860. }
  4861.  
  4862. namespace Oxide.Plugins
  4863. {
  4864. using Newtonsoft.Json;
  4865. using Newtonsoft.Json.Converters;
  4866. using UnityEngine;
  4867.  
  4868. public partial class Imperium : RustPlugin
  4869. {
  4870. class PinInfo
  4871. {
  4872. [JsonProperty("name")] public string Name;
  4873.  
  4874. [JsonProperty("type"), JsonConverter(typeof(StringEnumConverter))]
  4875. public PinType Type;
  4876.  
  4877. [JsonProperty("position"), JsonConverter(typeof(UnityVector3Converter))]
  4878. public Vector3 Position;
  4879.  
  4880. [JsonProperty("areaId")] public string AreaId;
  4881.  
  4882. [JsonProperty("creatorId")] public string CreatorId;
  4883. }
  4884. }
  4885. }
  4886.  
  4887. namespace Oxide.Plugins
  4888. {
  4889. using System;
  4890. using System.Collections.Generic;
  4891. using System.Linq;
  4892.  
  4893. public partial class Imperium
  4894. {
  4895. class PinManager
  4896. {
  4897. Dictionary<string, Pin> Pins;
  4898.  
  4899. public PinManager()
  4900. {
  4901. Pins = new Dictionary<string, Pin>(StringComparer.OrdinalIgnoreCase);
  4902. }
  4903.  
  4904. public Pin Get(string name)
  4905. {
  4906. Pin pin;
  4907.  
  4908. if (!Pins.TryGetValue(name, out pin))
  4909. return null;
  4910.  
  4911. return pin;
  4912. }
  4913.  
  4914. public Pin[] GetAll()
  4915. {
  4916. return Pins.Values.ToArray();
  4917. }
  4918.  
  4919. public void Add(Pin pin)
  4920. {
  4921. Pins.Add(pin.Name, pin);
  4922. Events.OnPinCreated(pin);
  4923. }
  4924.  
  4925. public void Remove(Pin pin)
  4926. {
  4927. Pins.Remove(pin.Name);
  4928. Events.OnPinRemoved(pin);
  4929. }
  4930.  
  4931. public void RemoveAllPinsInUnclaimedAreas()
  4932. {
  4933. foreach (Pin pin in GetAll())
  4934. {
  4935. Area area = Instance.Areas.Get(pin.AreaId);
  4936. if (!area.IsClaimed) Remove(pin);
  4937. }
  4938. }
  4939.  
  4940. public void Init(IEnumerable<PinInfo> pinInfos)
  4941. {
  4942. Instance.Puts($"Creating pins for {pinInfos.Count()} pins...");
  4943.  
  4944. foreach (PinInfo info in pinInfos)
  4945. {
  4946. var pin = new Pin(info);
  4947. Pins.Add(pin.Name, pin);
  4948. }
  4949.  
  4950. Instance.Puts("Pins created.");
  4951. }
  4952.  
  4953. public void Destroy()
  4954. {
  4955. Pins.Clear();
  4956. }
  4957.  
  4958. public PinInfo[] Serialize()
  4959. {
  4960. return Pins.Values.Select(pin => pin.Serialize()).ToArray();
  4961. }
  4962. }
  4963. }
  4964. }
  4965.  
  4966. namespace Oxide.Plugins
  4967. {
  4968. public partial class Imperium
  4969. {
  4970. enum PinType
  4971. {
  4972. Arena,
  4973. Hotel,
  4974. Marina,
  4975. Shop,
  4976. Town
  4977. }
  4978. }
  4979. }
  4980.  
  4981. namespace Oxide.Plugins
  4982. {
  4983. using System;
  4984. using System.Collections.Generic;
  4985. using System.Text;
  4986. using UnityEngine;
  4987.  
  4988. public partial class Imperium
  4989. {
  4990. class User : MonoBehaviour
  4991. {
  4992. string OriginalName;
  4993. Dictionary<string, DateTime> CommandCooldownExpirations;
  4994.  
  4995. public BasePlayer Player { get; private set; }
  4996. public UserMap Map { get; private set; }
  4997. public UserHud Hud { get; private set; }
  4998. public UserPreferences Preferences { get; set; }
  4999.  
  5000. public Area CurrentArea { get; set; }
  5001. public HashSet<Zone> CurrentZones { get; private set; }
  5002. public Faction Faction { get; private set; }
  5003. public Interaction CurrentInteraction { get; private set; }
  5004. public DateTime MapCommandCooldownExpiration { get; set; }
  5005. public DateTime PvpCommandCooldownExpiration { get; set; }
  5006. public bool IsInPvpMode { get; set; }
  5007.  
  5008. public string Id
  5009. {
  5010. get { return Player.UserIDString; }
  5011. }
  5012.  
  5013. public string UserName
  5014. {
  5015. get { return OriginalName; }
  5016. }
  5017.  
  5018. public string UserNameWithFactionTag
  5019. {
  5020. get { return Player.displayName; }
  5021. }
  5022.  
  5023. public void Init(BasePlayer player)
  5024. {
  5025. Player = player;
  5026. OriginalName = player.displayName;
  5027. CurrentZones = new HashSet<Zone>();
  5028. CommandCooldownExpirations = new Dictionary<string, DateTime>();
  5029. Preferences = UserPreferences.Default;
  5030.  
  5031. Map = new UserMap(this);
  5032. Hud = new UserHud(this);
  5033.  
  5034. InvokeRepeating(nameof(UpdateHud), 5f, 5f);
  5035. InvokeRepeating(nameof(CheckArea), 2f, 2f);
  5036. }
  5037.  
  5038. void OnDestroy()
  5039. {
  5040. Map.Hide();
  5041. Hud.Hide();
  5042.  
  5043. if (IsInvoking(nameof(UpdateHud))) CancelInvoke(nameof(UpdateHud));
  5044. if (IsInvoking(nameof(CheckArea))) CancelInvoke(nameof(CheckArea));
  5045.  
  5046. if (Player != null)
  5047. Player.displayName = OriginalName;
  5048. }
  5049.  
  5050. public void SetFaction(Faction faction)
  5051. {
  5052. Faction = faction;
  5053.  
  5054. if (faction == null)
  5055. Player.displayName = OriginalName;
  5056. else
  5057. Player.displayName = $"[{faction.Id}] {Player.displayName}";
  5058.  
  5059. Player.SendNetworkUpdate();
  5060. }
  5061.  
  5062. public bool HasPermission(string permission)
  5063. {
  5064. return Instance.permission.UserHasPermission(Player.UserIDString, permission);
  5065. }
  5066.  
  5067. public void BeginInteraction(Interaction interaction)
  5068. {
  5069. interaction.User = this;
  5070. CurrentInteraction = interaction;
  5071. }
  5072.  
  5073. public void CompleteInteraction(HitInfo hit)
  5074. {
  5075. if (CurrentInteraction.TryComplete(hit))
  5076. CurrentInteraction = null;
  5077. }
  5078.  
  5079. public void CancelInteraction()
  5080. {
  5081. CurrentInteraction = null;
  5082. }
  5083.  
  5084. public void SendChatMessage(string message, params object[] args)
  5085. {
  5086. string format = Instance.lang.GetMessage(message, Instance, Player.UserIDString);
  5087. Instance.SendReply(Player, format, args);
  5088. }
  5089.  
  5090. public void SendChatMessage(StringBuilder sb)
  5091. {
  5092. Instance.SendReply(Player, sb.ToString().TrimEnd());
  5093. }
  5094.  
  5095. public void SendConsoleMessage(string message, params object[] args)
  5096. {
  5097. Player.ConsoleMessage(String.Format(message, args));
  5098. }
  5099.  
  5100. void UpdateHud()
  5101. {
  5102. Hud.Refresh();
  5103. }
  5104.  
  5105. public int GetSecondsLeftOnCooldown(string command)
  5106. {
  5107. DateTime expiration;
  5108.  
  5109. if (!CommandCooldownExpirations.TryGetValue(command, out expiration))
  5110. return 0;
  5111.  
  5112. return (int) Math.Max(0, expiration.Subtract(DateTime.UtcNow).TotalSeconds);
  5113. }
  5114.  
  5115. public void SetCooldownExpiration(string command, DateTime time)
  5116. {
  5117. CommandCooldownExpirations[command] = time;
  5118. }
  5119.  
  5120. void CheckArea()
  5121. {
  5122. Area currentArea = CurrentArea;
  5123. Area correctArea = Instance.Areas.GetByEntityPosition(Player);
  5124.  
  5125. if (currentArea != null && (correctArea == null || currentArea.Id != correctArea.Id))
  5126. Events.OnUserLeftArea(this, currentArea);
  5127.  
  5128. Events.OnUserEnteredArea(this, correctArea);
  5129. }
  5130.  
  5131. void CheckZones()
  5132. {
  5133. }
  5134. }
  5135. }
  5136. }
  5137.  
  5138. namespace Oxide.Plugins
  5139. {
  5140. using System.Collections.Generic;
  5141. using System.Linq;
  5142.  
  5143. public partial class Imperium
  5144. {
  5145. class UserManager
  5146. {
  5147. Dictionary<string, User> Users = new Dictionary<string, User>();
  5148. Dictionary<string, string> OriginalNames = new Dictionary<string, string>();
  5149.  
  5150. public User[] GetAll()
  5151. {
  5152. return Users.Values.ToArray();
  5153. }
  5154.  
  5155. public User Get(BasePlayer player)
  5156. {
  5157. if (player == null) return null;
  5158. return Get(player.UserIDString);
  5159. }
  5160.  
  5161. public User Get(string userId)
  5162. {
  5163. User user;
  5164. if (Users.TryGetValue(userId, out user))
  5165. return user;
  5166. else
  5167. return null;
  5168. }
  5169.  
  5170. public User Find(string searchString)
  5171. {
  5172. User user = Get(searchString);
  5173.  
  5174. if (user != null)
  5175. return user;
  5176.  
  5177. return Users.Values
  5178. .Where(u => u.UserName.ToLowerInvariant().Contains(searchString.ToLowerInvariant()))
  5179. .OrderBy(u =>
  5180. Util.GetLevenshteinDistance(searchString.ToLowerInvariant(), u.UserName.ToLowerInvariant()))
  5181. .FirstOrDefault();
  5182. }
  5183.  
  5184. public User Add(BasePlayer player)
  5185. {
  5186. Remove(player);
  5187.  
  5188. string originalName;
  5189. if (OriginalNames.TryGetValue(player.UserIDString, out originalName))
  5190. player.displayName = originalName;
  5191. else
  5192. OriginalNames[player.UserIDString] = player.displayName;
  5193.  
  5194. User user = player.gameObject.AddComponent<User>();
  5195. user.Init(player);
  5196.  
  5197. Faction faction = Instance.Factions.GetByMember(user);
  5198. if (faction != null)
  5199. user.SetFaction(faction);
  5200.  
  5201. Users[user.Player.UserIDString] = user;
  5202.  
  5203. return user;
  5204. }
  5205.  
  5206. public bool Remove(BasePlayer player)
  5207. {
  5208. User user = Get(player);
  5209. if (user == null) return false;
  5210.  
  5211. UnityEngine.Object.DestroyImmediate(user);
  5212. Users.Remove(player.UserIDString);
  5213.  
  5214. return true;
  5215. }
  5216.  
  5217. public void SetOriginalName(string userId, string name)
  5218. {
  5219. OriginalNames[userId] = name;
  5220. }
  5221.  
  5222. public void Init()
  5223. {
  5224. var players = BasePlayer.activePlayerList;
  5225.  
  5226. Instance.Puts($"Creating user objects for {players.Count} players...");
  5227.  
  5228. foreach (BasePlayer player in players)
  5229. Add(player);
  5230.  
  5231. Instance.Puts($"Created {Users.Count} user objects.");
  5232. }
  5233.  
  5234. public void Destroy()
  5235. {
  5236. User[] users = UnityEngine.Object.FindObjectsOfType<User>();
  5237.  
  5238. if (users == null)
  5239. return;
  5240.  
  5241. Instance.Puts($"Destroying {users.Length} user objects.");
  5242.  
  5243. foreach (var user in users)
  5244. UnityEngine.Object.DestroyImmediate(user);
  5245.  
  5246. Users.Clear();
  5247.  
  5248. Instance.Puts("User objects destroyed.");
  5249. }
  5250. }
  5251. }
  5252. }
  5253.  
  5254. namespace Oxide.Plugins
  5255. {
  5256. using System;
  5257.  
  5258. public partial class Imperium
  5259. {
  5260. class UserPreferences
  5261. {
  5262. public UserMapLayer VisibleMapLayers { get; private set; }
  5263.  
  5264. public void ShowMapLayer(UserMapLayer layer)
  5265. {
  5266. VisibleMapLayers |= layer;
  5267. }
  5268.  
  5269. public void HideMapLayer(UserMapLayer layer)
  5270. {
  5271. VisibleMapLayers &= ~layer;
  5272. }
  5273.  
  5274. public void ToggleMapLayer(UserMapLayer layer)
  5275. {
  5276. if (IsMapLayerVisible(layer))
  5277. HideMapLayer(layer);
  5278. else
  5279. ShowMapLayer(layer);
  5280. }
  5281.  
  5282. public bool IsMapLayerVisible(UserMapLayer layer)
  5283. {
  5284. return (VisibleMapLayers & layer) == layer;
  5285. }
  5286.  
  5287. public static UserPreferences Default
  5288. {
  5289. get
  5290. {
  5291. return new UserPreferences
  5292. {
  5293. VisibleMapLayers = UserMapLayer.Claims | UserMapLayer.Headquarters | UserMapLayer.Monuments |
  5294. UserMapLayer.Pins
  5295. };
  5296. }
  5297. }
  5298. }
  5299.  
  5300. [Flags]
  5301. enum UserMapLayer
  5302. {
  5303. Claims = 1,
  5304. Headquarters = 2,
  5305. Monuments = 4,
  5306. Pins = 8
  5307. }
  5308. }
  5309. }
  5310.  
  5311. namespace Oxide.Plugins
  5312. {
  5313. using System;
  5314.  
  5315. public partial class Imperium
  5316. {
  5317. class War
  5318. {
  5319. public string AttackerId { get; set; }
  5320. public string DefenderId { get; set; }
  5321. public string DeclarerId { get; set; }
  5322. public string CassusBelli { get; set; }
  5323.  
  5324. public DateTime? AttackerPeaceOfferingTime { get; set; }
  5325. public DateTime? DefenderPeaceOfferingTime { get; set; }
  5326.  
  5327. public DateTime StartTime { get; private set; }
  5328. public DateTime? EndTime { get; set; }
  5329. public WarEndReason? EndReason { get; set; }
  5330.  
  5331. public bool IsActive
  5332. {
  5333. get { return EndTime == null; }
  5334. }
  5335.  
  5336. public bool IsAttackerOfferingPeace
  5337. {
  5338. get { return AttackerPeaceOfferingTime != null; }
  5339. }
  5340.  
  5341. public bool IsDefenderOfferingPeace
  5342. {
  5343. get { return DefenderPeaceOfferingTime != null; }
  5344. }
  5345.  
  5346. public War(Faction attacker, Faction defender, User declarer, string cassusBelli)
  5347. {
  5348. AttackerId = attacker.Id;
  5349. DefenderId = defender.Id;
  5350. DeclarerId = declarer.Id;
  5351. CassusBelli = cassusBelli;
  5352. StartTime = DateTime.UtcNow;
  5353. }
  5354.  
  5355. public War(WarInfo info)
  5356. {
  5357. AttackerId = info.AttackerId;
  5358. DefenderId = info.DefenderId;
  5359. DeclarerId = info.DeclarerId;
  5360. CassusBelli = info.CassusBelli;
  5361. StartTime = info.StartTime;
  5362. EndTime = info.EndTime;
  5363. }
  5364.  
  5365. public void OfferPeace(Faction faction)
  5366. {
  5367. if (AttackerId == faction.Id)
  5368. AttackerPeaceOfferingTime = DateTime.UtcNow;
  5369. else if (DefenderId == faction.Id)
  5370. DefenderPeaceOfferingTime = DateTime.UtcNow;
  5371. else
  5372. throw new InvalidOperationException(String.Format(
  5373. "{0} tried to offer peace but the faction wasn't involved in the war!", faction.Id));
  5374. }
  5375.  
  5376. public bool IsOfferingPeace(Faction faction)
  5377. {
  5378. return IsOfferingPeace(faction.Id);
  5379. }
  5380.  
  5381. public bool IsOfferingPeace(string factionId)
  5382. {
  5383. return (factionId == AttackerId && IsAttackerOfferingPeace) ||
  5384. (factionId == DefenderId && IsDefenderOfferingPeace);
  5385. }
  5386.  
  5387. public WarInfo Serialize()
  5388. {
  5389. return new WarInfo
  5390. {
  5391. AttackerId = AttackerId,
  5392. DefenderId = DefenderId,
  5393. DeclarerId = DeclarerId,
  5394. CassusBelli = CassusBelli,
  5395. AttackerPeaceOfferingTime = AttackerPeaceOfferingTime,
  5396. DefenderPeaceOfferingTime = DefenderPeaceOfferingTime,
  5397. StartTime = StartTime,
  5398. EndTime = EndTime,
  5399. EndReason = EndReason
  5400. };
  5401. }
  5402. }
  5403. }
  5404. }
  5405.  
  5406. namespace Oxide.Plugins
  5407. {
  5408. public partial class Imperium : RustPlugin
  5409. {
  5410. enum WarEndReason
  5411. {
  5412. Treaty,
  5413. AttackerEliminatedDefender,
  5414. DefenderEliminatedAttacker
  5415. }
  5416. }
  5417. }
  5418.  
  5419. namespace Oxide.Plugins
  5420. {
  5421. using System;
  5422. using Newtonsoft.Json;
  5423. using Newtonsoft.Json.Converters;
  5424.  
  5425. public partial class Imperium : RustPlugin
  5426. {
  5427. class WarInfo
  5428. {
  5429. [JsonProperty("attackerId")] public string AttackerId;
  5430.  
  5431. [JsonProperty("defenderId")] public string DefenderId;
  5432.  
  5433. [JsonProperty("declarerId")] public string DeclarerId;
  5434.  
  5435. [JsonProperty("cassusBelli")] public string CassusBelli;
  5436.  
  5437. [JsonProperty("attackerPeaceOfferingTime"), JsonConverter(typeof(IsoDateTimeConverter))]
  5438. public DateTime? AttackerPeaceOfferingTime;
  5439.  
  5440. [JsonProperty("defenderPeaceOfferingTime"), JsonConverter(typeof(IsoDateTimeConverter))]
  5441. public DateTime? DefenderPeaceOfferingTime;
  5442.  
  5443. [JsonProperty("startTime"), JsonConverter(typeof(IsoDateTimeConverter))]
  5444. public DateTime StartTime;
  5445.  
  5446. [JsonProperty("endTime"), JsonConverter(typeof(IsoDateTimeConverter))]
  5447. public DateTime? EndTime;
  5448.  
  5449. [JsonProperty("endReason"), JsonConverter(typeof(StringEnumConverter))]
  5450. public WarEndReason? EndReason;
  5451. }
  5452. }
  5453. }
  5454.  
  5455. namespace Oxide.Plugins
  5456. {
  5457. using System;
  5458. using System.Collections.Generic;
  5459. using System.Linq;
  5460.  
  5461. public partial class Imperium
  5462. {
  5463. class WarManager
  5464. {
  5465. List<War> Wars = new List<War>();
  5466.  
  5467. public War[] GetAllActiveWars()
  5468. {
  5469. return Wars.Where(war => war.IsActive).OrderBy(war => war.StartTime).ToArray();
  5470. }
  5471.  
  5472. public War[] GetAllActiveWarsByFaction(Faction faction)
  5473. {
  5474. return GetAllActiveWarsByFaction(faction.Id);
  5475. }
  5476.  
  5477. public War[] GetAllActiveWarsByFaction(string factionId)
  5478. {
  5479. return GetAllActiveWars().Where(war => war.AttackerId == factionId || war.DefenderId == factionId)
  5480. .ToArray();
  5481. }
  5482.  
  5483. public War GetActiveWarBetween(Faction firstFaction, Faction secondFaction)
  5484. {
  5485. return GetActiveWarBetween(firstFaction.Id, secondFaction.Id);
  5486. }
  5487.  
  5488. public War GetActiveWarBetween(string firstFactionId, string secondFactionId)
  5489. {
  5490. return GetAllActiveWars().SingleOrDefault(war =>
  5491. (war.AttackerId == firstFactionId && war.DefenderId == secondFactionId) ||
  5492. (war.DefenderId == firstFactionId && war.AttackerId == secondFactionId)
  5493. );
  5494. }
  5495.  
  5496. public bool AreFactionsAtWar(Faction firstFaction, Faction secondFaction)
  5497. {
  5498. return AreFactionsAtWar(firstFaction.Id, secondFaction.Id);
  5499. }
  5500.  
  5501. public bool AreFactionsAtWar(string firstFactionId, string secondFactionId)
  5502. {
  5503. return GetActiveWarBetween(firstFactionId, secondFactionId) != null;
  5504. }
  5505.  
  5506. public War DeclareWar(Faction attacker, Faction defender, User user, string cassusBelli)
  5507. {
  5508. var war = new War(attacker, defender, user, cassusBelli);
  5509. Wars.Add(war);
  5510. Instance.OnDiplomacyChanged();
  5511. return war;
  5512. }
  5513.  
  5514. public void EndWar(War war, WarEndReason reason)
  5515. {
  5516. war.EndTime = DateTime.UtcNow;
  5517. war.EndReason = reason;
  5518. Instance.OnDiplomacyChanged();
  5519. }
  5520.  
  5521. public void EndAllWarsForEliminatedFactions()
  5522. {
  5523. bool dirty = false;
  5524.  
  5525. foreach (War war in Wars)
  5526. {
  5527. if (Instance.Areas.GetAllClaimedByFaction(war.AttackerId).Length == 0)
  5528. {
  5529. war.EndTime = DateTime.UtcNow;
  5530. war.EndReason = WarEndReason.DefenderEliminatedAttacker;
  5531. dirty = true;
  5532. }
  5533.  
  5534. if (Instance.Areas.GetAllClaimedByFaction(war.DefenderId).Length == 0)
  5535. {
  5536. war.EndTime = DateTime.UtcNow;
  5537. war.EndReason = WarEndReason.AttackerEliminatedDefender;
  5538. dirty = true;
  5539. }
  5540. }
  5541.  
  5542. if (dirty)
  5543. Instance.OnDiplomacyChanged();
  5544. }
  5545.  
  5546. public void Init(IEnumerable<WarInfo> warInfos)
  5547. {
  5548. Instance.Puts($"Loading {warInfos.Count()} wars...");
  5549.  
  5550. foreach (WarInfo info in warInfos)
  5551. {
  5552. var war = new War(info);
  5553. Wars.Add(war);
  5554. Instance.Log($"[LOAD] War {war.AttackerId} vs {war.DefenderId}, isActive = {war.IsActive}");
  5555. }
  5556.  
  5557. Instance.Puts("Wars loaded.");
  5558. }
  5559.  
  5560. public void Destroy()
  5561. {
  5562. Wars.Clear();
  5563. }
  5564.  
  5565. public WarInfo[] Serialize()
  5566. {
  5567. return Wars.Select(war => war.Serialize()).ToArray();
  5568. }
  5569. }
  5570. }
  5571. }
  5572.  
  5573. namespace Oxide.Plugins
  5574. {
  5575. using Rust;
  5576. using System;
  5577. using System.Collections.Generic;
  5578. using UnityEngine;
  5579.  
  5580. public partial class Imperium
  5581. {
  5582. class Zone : MonoBehaviour
  5583. {
  5584. const string SpherePrefab = "assets/prefabs/visualization/sphere.prefab";
  5585.  
  5586. List<BaseEntity> Spheres = new List<BaseEntity>();
  5587.  
  5588. public ZoneType Type { get; private set; }
  5589. public string Name { get; private set; }
  5590. public MonoBehaviour Owner { get; private set; }
  5591. public DateTime? EndTime { get; set; }
  5592.  
  5593. public void Init(ZoneType type, string name, MonoBehaviour owner, float radius, int darkness,
  5594. DateTime? endTime)
  5595. {
  5596. Type = type;
  5597. Name = name;
  5598. Owner = owner;
  5599. EndTime = endTime;
  5600.  
  5601. Vector3 position = GetGroundPosition(owner.transform.position);
  5602.  
  5603. gameObject.layer = (int) Layer.Reserved1;
  5604. gameObject.name = $"imperium_zone_{name.ToLowerInvariant()}";
  5605. transform.position = position;
  5606. transform.rotation = Quaternion.Euler(new Vector3(0, 0, 0));
  5607.  
  5608. for (var idx = 0; idx < darkness; idx++)
  5609. {
  5610. var sphere = GameManager.server.CreateEntity(SpherePrefab, position);
  5611.  
  5612. SphereEntity entity = sphere.GetComponent<SphereEntity>();
  5613. entity.lerpRadius = radius * 2;
  5614. entity.currentRadius = radius * 2;
  5615. entity.lerpSpeed = 0f;
  5616.  
  5617. sphere.Spawn();
  5618. Spheres.Add(sphere);
  5619. }
  5620.  
  5621. var collider = gameObject.AddComponent<SphereCollider>();
  5622. collider.radius = radius;
  5623. collider.isTrigger = true;
  5624. collider.enabled = true;
  5625.  
  5626. if (endTime != null)
  5627. InvokeRepeating("CheckIfShouldDestroy", 10f, 5f);
  5628. }
  5629.  
  5630. void OnDestroy()
  5631. {
  5632. var collider = GetComponent<SphereCollider>();
  5633.  
  5634. if (collider != null)
  5635. Destroy(collider);
  5636.  
  5637. foreach (BaseEntity sphere in Spheres)
  5638. sphere.KillMessage();
  5639.  
  5640. if (IsInvoking("CheckIfShouldDestroy"))
  5641. CancelInvoke("CheckIfShouldDestroy");
  5642. }
  5643.  
  5644. void OnTriggerEnter(Collider collider)
  5645. {
  5646. if (collider.gameObject.layer != (int) Layer.Player_Server)
  5647. return;
  5648.  
  5649. var user = collider.GetComponentInParent<User>();
  5650.  
  5651. if (user != null && !user.CurrentZones.Contains(this))
  5652. Events.OnUserEnteredZone(user, this);
  5653. }
  5654.  
  5655. void OnTriggerExit(Collider collider)
  5656. {
  5657. if (collider.gameObject.layer != (int) Layer.Player_Server)
  5658. return;
  5659.  
  5660. var user = collider.GetComponentInParent<User>();
  5661.  
  5662. if (user != null && user.CurrentZones.Contains(this))
  5663. Events.OnUserLeftZone(user, this);
  5664. }
  5665.  
  5666. void CheckIfShouldDestroy()
  5667. {
  5668. if (DateTime.UtcNow >= EndTime)
  5669. Instance.Zones.Remove(this);
  5670. }
  5671.  
  5672. Vector3 GetGroundPosition(Vector3 pos)
  5673. {
  5674. return new Vector3(pos.x, TerrainMeta.HeightMap.GetHeight(pos), pos.z);
  5675. }
  5676. }
  5677. }
  5678. }
  5679.  
  5680. namespace Oxide.Plugins
  5681. {
  5682. using System;
  5683. using System.Collections.Generic;
  5684. using System.Linq;
  5685. using UnityEngine;
  5686.  
  5687. public partial class Imperium
  5688. {
  5689. class ZoneManager
  5690. {
  5691. Dictionary<MonoBehaviour, Zone> Zones = new Dictionary<MonoBehaviour, Zone>();
  5692.  
  5693. public void Init()
  5694. {
  5695. if (!Instance.Options.Zones.Enabled || Instance.Options.Zones.MonumentZones == null)
  5696. return;
  5697.  
  5698. MonumentInfo[] monuments = UnityEngine.Object.FindObjectsOfType<MonumentInfo>();
  5699. foreach (MonumentInfo monument in monuments)
  5700. {
  5701. float? radius = GetMonumentZoneRadius(monument);
  5702. if (radius != null)
  5703. {
  5704. Vector3 position = monument.transform.position;
  5705. Vector3 size = monument.Bounds.size;
  5706. Create(ZoneType.Monument, monument.displayPhrase.english, monument, (float) radius);
  5707. }
  5708. }
  5709. }
  5710.  
  5711. public Zone GetByOwner(MonoBehaviour owner)
  5712. {
  5713. Zone zone;
  5714.  
  5715. if (Zones.TryGetValue(owner, out zone))
  5716. return zone;
  5717.  
  5718. return null;
  5719. }
  5720.  
  5721. public void CreateForDebrisField(BaseHelicopter helicopter)
  5722. {
  5723. Vector3 position = helicopter.transform.position;
  5724. float radius = Instance.Options.Zones.EventZoneRadius;
  5725. Create(ZoneType.Debris, "Debris Field", helicopter, radius, GetEventEndTime());
  5726. }
  5727.  
  5728. public void CreateForSupplyDrop(SupplyDrop drop)
  5729. {
  5730. Vector3 position = drop.transform.position;
  5731. float radius = Instance.Options.Zones.EventZoneRadius;
  5732. float lifespan = Instance.Options.Zones.EventZoneLifespanSeconds;
  5733. Create(ZoneType.SupplyDrop, "Supply Drop", drop, radius, GetEventEndTime());
  5734. }
  5735.  
  5736. public void CreateForRaid(BuildingPrivlidge cupboard)
  5737. {
  5738. // If the building was already being raided, just extend the lifespan of the existing zone.
  5739. Zone existingZone = GetByOwner(cupboard);
  5740. if (existingZone)
  5741. {
  5742. existingZone.EndTime = GetEventEndTime();
  5743. Instance.Puts(
  5744. $"Extending raid zone end time to {existingZone.EndTime} ({existingZone.EndTime.Value.Subtract(DateTime.UtcNow).ToShortString()} from now)");
  5745. return;
  5746. }
  5747.  
  5748. Vector3 position = cupboard.transform.position;
  5749. float radius = Instance.Options.Zones.EventZoneRadius;
  5750.  
  5751. Create(ZoneType.Raid, "Raid", cupboard, radius, GetEventEndTime());
  5752. }
  5753.  
  5754. public void Remove(Zone zone)
  5755. {
  5756. Instance.Puts($"Destroying zone {zone.name}");
  5757.  
  5758. foreach (User user in Instance.Users.GetAll())
  5759. user.CurrentZones.Remove(zone);
  5760.  
  5761. Zones.Remove(zone.Owner);
  5762.  
  5763. UnityEngine.Object.Destroy(zone);
  5764. }
  5765.  
  5766. public void Destroy()
  5767. {
  5768. Zone[] zones = UnityEngine.Object.FindObjectsOfType<Zone>();
  5769.  
  5770. if (zones != null)
  5771. {
  5772. Instance.Puts($"Destroying {zones.Length} zone objects...");
  5773. foreach (Zone zone in zones)
  5774. UnityEngine.Object.DestroyImmediate(zone);
  5775. }
  5776.  
  5777. Zones.Clear();
  5778.  
  5779. Instance.Puts("Zone objects destroyed.");
  5780. }
  5781.  
  5782. void Create(ZoneType type, string name, MonoBehaviour owner, float radius, DateTime? endTime = null)
  5783. {
  5784. var zone = new GameObject().AddComponent<Zone>();
  5785. zone.Init(type, name, owner, radius, Instance.Options.Zones.DomeDarkness, endTime);
  5786.  
  5787. Instance.Puts($"Created zone {zone.Name} at {zone.transform.position} with radius {radius}");
  5788.  
  5789. if (endTime != null)
  5790. Instance.Puts(
  5791. $"Zone {zone.Name} will be destroyed at {endTime} ({endTime.Value.Subtract(DateTime.UtcNow).ToShortString()} from now)");
  5792.  
  5793. Zones.Add(owner, zone);
  5794. }
  5795.  
  5796. float? GetMonumentZoneRadius(MonumentInfo monument)
  5797. {
  5798. if (monument.Type == MonumentType.Cave)
  5799. return null;
  5800.  
  5801. foreach (var entry in Instance.Options.Zones.MonumentZones)
  5802. {
  5803. if (monument.name.ToLowerInvariant().Contains(entry.Key))
  5804. return entry.Value;
  5805. }
  5806.  
  5807. return null;
  5808. }
  5809.  
  5810. DateTime GetEventEndTime()
  5811. {
  5812. return DateTime.UtcNow.AddSeconds(Instance.Options.Zones.EventZoneLifespanSeconds);
  5813. }
  5814. }
  5815. }
  5816. }
  5817.  
  5818. namespace Oxide.Plugins
  5819. {
  5820. public partial class Imperium
  5821. {
  5822. public enum ZoneType
  5823. {
  5824. Monument,
  5825. Debris,
  5826. SupplyDrop,
  5827. Raid
  5828. }
  5829. }
  5830. }
  5831.  
  5832. namespace Oxide.Plugins
  5833. {
  5834. using System.Collections.Generic;
  5835. using System.Drawing;
  5836.  
  5837. public partial class Imperium
  5838. {
  5839. class FactionColorPicker
  5840. {
  5841. static string[] Colors = new[]
  5842. {
  5843. "#00FF00", "#0000FF", "#FF0000", "#01FFFE", "#FFA6FE",
  5844. "#FFDB66", "#006401", "#010067", "#95003A", "#007DB5",
  5845. "#FF00F6", "#FFEEE8", "#774D00", "#90FB92", "#0076FF",
  5846. "#D5FF00", "#FF937E", "#6A826C", "#FF029D", "#FE8900",
  5847. "#7A4782", "#7E2DD2", "#85A900", "#FF0056", "#A42400",
  5848. "#00AE7E", "#683D3B", "#BDC6FF", "#263400", "#BDD393",
  5849. "#00B917", "#9E008E", "#001544", "#C28C9F", "#FF74A3",
  5850. "#01D0FF", "#004754", "#E56FFE", "#788231", "#0E4CA1",
  5851. "#91D0CB", "#BE9970", "#968AE8", "#BB8800", "#43002C",
  5852. "#DEFF74", "#00FFC6", "#FFE502", "#620E00", "#008F9C",
  5853. "#98FF52", "#7544B1", "#B500FF", "#00FF78", "#FF6E41",
  5854. "#005F39", "#6B6882", "#5FAD4E", "#A75740", "#A5FFD2",
  5855. "#FFB167", "#009BFF", "#E85EBE"
  5856. };
  5857.  
  5858. Dictionary<string, Color> AssignedColors;
  5859. int NextColor = 0;
  5860.  
  5861. public FactionColorPicker()
  5862. {
  5863. AssignedColors = new Dictionary<string, Color>();
  5864. }
  5865.  
  5866. public Color GetColorForFaction(string factionId)
  5867. {
  5868. Color color;
  5869.  
  5870. if (!AssignedColors.TryGetValue(factionId, out color))
  5871. {
  5872. color = Color.FromArgb(128, ColorTranslator.FromHtml(Colors[NextColor]));
  5873. AssignedColors.Add(factionId, color);
  5874. NextColor = (NextColor + 1) % Colors.Length;
  5875. }
  5876.  
  5877. return color;
  5878. }
  5879. }
  5880. }
  5881. }
  5882.  
  5883. namespace Oxide.Plugins
  5884. {
  5885. using System.Collections.Generic;
  5886.  
  5887. public partial class Imperium
  5888. {
  5889. class LruCache<K, V>
  5890. {
  5891. Dictionary<K, LinkedListNode<LruCacheItem>> Nodes;
  5892. LinkedList<LruCacheItem> RecencyList;
  5893.  
  5894. public int Capacity { get; private set; }
  5895.  
  5896. public LruCache(int capacity)
  5897. {
  5898. Capacity = capacity;
  5899. Nodes = new Dictionary<K, LinkedListNode<LruCacheItem>>();
  5900. RecencyList = new LinkedList<LruCacheItem>();
  5901. }
  5902.  
  5903. public bool TryGetValue(K key, out V value)
  5904. {
  5905. LinkedListNode<LruCacheItem> node;
  5906.  
  5907. if (!Nodes.TryGetValue(key, out node))
  5908. {
  5909. value = default(V);
  5910. return false;
  5911. }
  5912.  
  5913. LruCacheItem item = node.Value;
  5914. RecencyList.Remove(node);
  5915. RecencyList.AddLast(node);
  5916.  
  5917. value = item.Value;
  5918. return true;
  5919. }
  5920.  
  5921. public void Set(K key, V value)
  5922. {
  5923. LinkedListNode<LruCacheItem> node;
  5924.  
  5925. if (Nodes.TryGetValue(key, out node))
  5926. {
  5927. RecencyList.Remove(node);
  5928. node.Value.Value = value;
  5929. }
  5930. else
  5931. {
  5932. if (Nodes.Count >= Capacity)
  5933. Evict();
  5934.  
  5935. var item = new LruCacheItem(key, value);
  5936. node = new LinkedListNode<LruCacheItem>(item);
  5937. }
  5938.  
  5939. RecencyList.AddLast(node);
  5940. Nodes[key] = node;
  5941. }
  5942.  
  5943. public bool Remove(K key)
  5944. {
  5945. LinkedListNode<LruCacheItem> node;
  5946.  
  5947. if (!Nodes.TryGetValue(key, out node))
  5948. return false;
  5949.  
  5950. Nodes.Remove(key);
  5951. RecencyList.Remove(node);
  5952.  
  5953. return true;
  5954. }
  5955.  
  5956. public void Clear()
  5957. {
  5958. Nodes.Clear();
  5959. RecencyList.Clear();
  5960. }
  5961.  
  5962. void Evict()
  5963. {
  5964. LruCacheItem item = RecencyList.First.Value;
  5965. RecencyList.RemoveFirst();
  5966. Nodes.Remove(item.Key);
  5967. }
  5968.  
  5969. class LruCacheItem
  5970. {
  5971. public K Key;
  5972. public V Value;
  5973.  
  5974. public LruCacheItem(K key, V value)
  5975. {
  5976. Key = key;
  5977. Value = value;
  5978. }
  5979. }
  5980. }
  5981. }
  5982. }
  5983.  
  5984. namespace Oxide.Plugins
  5985. {
  5986. using System;
  5987. using UnityEngine;
  5988.  
  5989. public partial class Imperium
  5990. {
  5991. public class MapGrid
  5992. {
  5993. const int GRID_CELL_SIZE = 150;
  5994.  
  5995. public int MapSize
  5996. {
  5997. get { return (int) TerrainMeta.Size.x; }
  5998. }
  5999.  
  6000. public int CellSize
  6001. {
  6002. get { return GRID_CELL_SIZE; }
  6003. }
  6004.  
  6005. public float CellSizeRatio
  6006. {
  6007. get { return (float) MapSize / CellSize; }
  6008. }
  6009.  
  6010. public int NumberOfCells { get; private set; }
  6011.  
  6012. string[] RowIds;
  6013. string[] ColumnIds;
  6014. string[,] AreaIds;
  6015. Vector3[,] Positions;
  6016.  
  6017. public MapGrid()
  6018. {
  6019. NumberOfCells = (int) Math.Ceiling(MapSize / (float) CellSize);
  6020. RowIds = new string[NumberOfCells];
  6021. ColumnIds = new string[NumberOfCells];
  6022. AreaIds = new string[NumberOfCells, NumberOfCells];
  6023. Positions = new Vector3[NumberOfCells, NumberOfCells];
  6024. Build();
  6025. }
  6026.  
  6027. public string GetRowId(int row)
  6028. {
  6029. return RowIds[row];
  6030. }
  6031.  
  6032. public string GetColumnId(int col)
  6033. {
  6034. return ColumnIds[col];
  6035. }
  6036.  
  6037. public string GetAreaId(int row, int col)
  6038. {
  6039. return AreaIds[row, col];
  6040. }
  6041.  
  6042. public Vector3 GetPosition(int row, int col)
  6043. {
  6044. return Positions[row, col];
  6045. }
  6046.  
  6047. void Build()
  6048. {
  6049. string prefix = "";
  6050. char letter = 'A';
  6051.  
  6052. for (int col = 0; col < NumberOfCells; col++)
  6053. {
  6054. ColumnIds[col] = prefix + letter;
  6055. if (letter == 'Z')
  6056. {
  6057. prefix = "A";
  6058. letter = 'A';
  6059. }
  6060. else
  6061. {
  6062. letter++;
  6063. }
  6064. }
  6065.  
  6066. for (int row = 0; row < NumberOfCells; row++)
  6067. RowIds[row] = row.ToString();
  6068.  
  6069. int z = (MapSize / 2) - CellSize;
  6070. for (int row = 0; row < NumberOfCells; row++)
  6071. {
  6072. int x = -(MapSize / 2);
  6073. for (int col = 0; col < NumberOfCells; col++)
  6074. {
  6075. var areaId = ColumnIds[col] + RowIds[row];
  6076. AreaIds[row, col] = areaId;
  6077. Positions[row, col] = new Vector3(x + (CellSize / 2), 0, z + (CellSize / 2));
  6078. x += CellSize;
  6079. }
  6080.  
  6081. z -= CellSize;
  6082. }
  6083. }
  6084. }
  6085. }
  6086. }
  6087.  
  6088. namespace Oxide.Plugins
  6089. {
  6090. using System.Collections;
  6091. using System.Drawing;
  6092. using System.Drawing.Drawing2D;
  6093.  
  6094. public partial class Imperium
  6095. {
  6096. class MapOverlayGenerator : UnityEngine.MonoBehaviour
  6097. {
  6098. public bool IsGenerating { get; private set; }
  6099.  
  6100. public void Generate()
  6101. {
  6102. if (!IsGenerating)
  6103. StartCoroutine(GenerateOverlayImage());
  6104. }
  6105.  
  6106. IEnumerator GenerateOverlayImage()
  6107. {
  6108. IsGenerating = true;
  6109. Instance.Puts("Generating new map overlay image...");
  6110.  
  6111. using (var bitmap = new Bitmap(Instance.Options.Map.ImageSize, Instance.Options.Map.ImageSize))
  6112. using (var graphics = Graphics.FromImage(bitmap))
  6113. {
  6114. var grid = Instance.Areas.MapGrid;
  6115. var tileSize = (int) (Instance.Options.Map.ImageSize / grid.CellSizeRatio);
  6116.  
  6117. var colorPicker = new FactionColorPicker();
  6118. var textBrush = new SolidBrush(Color.FromArgb(255, 255, 255, 255));
  6119.  
  6120. for (int row = 0; row < grid.NumberOfCells; row++)
  6121. {
  6122. for (int col = 0; col < grid.NumberOfCells; col++)
  6123. {
  6124. Area area = Instance.Areas.Get(row, col);
  6125. var x = (col * tileSize);
  6126. var y = (row * tileSize);
  6127. var rect = new Rectangle(x, y, tileSize, tileSize);
  6128.  
  6129. if (area.Type == AreaType.Badlands)
  6130. {
  6131. // If the tile is badlands, color it in black.
  6132. var brush = new HatchBrush(HatchStyle.BackwardDiagonal, Color.FromArgb(32, 0, 0, 0),
  6133. Color.FromArgb(255, 0, 0, 0));
  6134. graphics.FillRectangle(brush, rect);
  6135. }
  6136. else if (area.Type != AreaType.Wilderness)
  6137. {
  6138. // If the tile is claimed, fill it with a color indicating the faction.
  6139. var brush = new SolidBrush(colorPicker.GetColorForFaction(area.FactionId));
  6140. graphics.FillRectangle(brush, rect);
  6141. }
  6142.  
  6143. yield return null;
  6144. }
  6145. }
  6146.  
  6147. var gridLabelFont = new Font("Consolas", 14, FontStyle.Bold);
  6148. var gridLabelOffset = 5;
  6149. var gridLinePen = new Pen(Color.FromArgb(192, 0, 0, 0), 2);
  6150.  
  6151. for (int row = 0; row < grid.NumberOfCells; row++)
  6152. {
  6153. if (row > 0)
  6154. graphics.DrawLine(gridLinePen, 0, (row * tileSize), (grid.NumberOfCells * tileSize),
  6155. (row * tileSize));
  6156. graphics.DrawString(grid.GetRowId(row), gridLabelFont, textBrush, gridLabelOffset,
  6157. (row * tileSize) + gridLabelOffset);
  6158. }
  6159.  
  6160. for (int col = 1; col < grid.NumberOfCells; col++)
  6161. {
  6162. graphics.DrawLine(gridLinePen, (col * tileSize), 0, (col * tileSize),
  6163. (grid.NumberOfCells * tileSize));
  6164. graphics.DrawString(grid.GetColumnId(col), gridLabelFont, textBrush,
  6165. (col * tileSize) + gridLabelOffset, gridLabelOffset);
  6166. }
  6167.  
  6168. var converter = new ImageConverter();
  6169. var imageData = (byte[]) converter.ConvertTo(bitmap, typeof(byte[]));
  6170.  
  6171. Image image = Instance.Hud.RegisterImage(Ui.MapOverlayImageUrl, imageData, true);
  6172.  
  6173. Instance.Puts($"Generated new map overlay image {image.Id}.");
  6174. Instance.Log($"Created new map overlay image {image.Id}.");
  6175.  
  6176. IsGenerating = false;
  6177. }
  6178. }
  6179. }
  6180. }
  6181. }
  6182.  
  6183. namespace Oxide.Plugins
  6184. {
  6185. public partial class Imperium
  6186. {
  6187. public static class MonumentPrefab
  6188. {
  6189. const string PrefabPrefix = "assets/bundled/prefabs/autospawn/monument/";
  6190.  
  6191. public const string Airfield = PrefabPrefix + "large/airfield_1.prefab";
  6192. public const string BanditTown = PrefabPrefix + "medium/bandit_town.prefab";
  6193. public const string Compound = PrefabPrefix + "medium/compound.prefab";
  6194. public const string Dome = PrefabPrefix + "small/sphere_tank.prefab";
  6195. public const string Harbor1 = PrefabPrefix + "harbor/harbor_1.prefab";
  6196. public const string Harbor2 = PrefabPrefix + "harbor/harbor_2.prefab";
  6197. public const string GasStation = PrefabPrefix + "small/gas_station_1.prefab";
  6198. public const string Junkyard = PrefabPrefix + "large/junkyard_1.prefab";
  6199. public const string LaunchSite = PrefabPrefix + "large/launch_site_1.prefab";
  6200. public const string Lighthouse = PrefabPrefix + "lighthouse/lighthouse.prefab";
  6201. public const string MilitaryTunnel = PrefabPrefix + "large/military_tunnel_1.prefab";
  6202. public const string MiningOutpost = PrefabPrefix + "small/warehouse.prefab";
  6203. public const string QuarryStone = PrefabPrefix + "small/mining_quarry_a.prefab";
  6204. public const string QuarrySulfur = PrefabPrefix + "small/mining_quarry_b.prefab";
  6205. public const string QuaryHqm = PrefabPrefix + "small/mining_quarry_c.prefab";
  6206. public const string PowerPlant = PrefabPrefix + "large/powerplant_1.prefab";
  6207. public const string Trainyard = PrefabPrefix + "large/trainyard_1.prefab";
  6208. public const string SatelliteDish = PrefabPrefix + "small/satellite_dish.prefab";
  6209. public const string SewerBranch = PrefabPrefix + "medium/radtown_small_3.prefab";
  6210. public const string Supermarket = PrefabPrefix + "small/supermarket_1.prefab";
  6211. public const string WaterTreatmentPlant = PrefabPrefix + "large/water_treatment_plant_1.prefab";
  6212. public const string WaterWellA = PrefabPrefix + "tiny/water_well_a.prefab";
  6213. public const string WaterWellB = PrefabPrefix + "tiny/water_well_b.prefab";
  6214. public const string WaterWellC = PrefabPrefix + "tiny/water_well_c.prefab";
  6215. public const string WaterWellD = PrefabPrefix + "tiny/water_well_d.prefab";
  6216. public const string WaterWellE = PrefabPrefix + "tiny/water_well_e.prefab";
  6217. }
  6218. }
  6219. }
  6220.  
  6221. namespace Oxide.Plugins
  6222. {
  6223. using System.Reflection;
  6224.  
  6225. public partial class Imperium : RustPlugin
  6226. {
  6227. public static class Permission
  6228. {
  6229. public const string AdminFactions = "imperium.factions.admin";
  6230. public const string AdminClaims = "imperium.claims.admin";
  6231. public const string AdminBadlands = "imperium.badlands.admin";
  6232. public const string AdminPins = "imperium.pins.admin";
  6233. public const string ManageFactions = "imperium.factions";
  6234.  
  6235. public static void RegisterAll(Imperium instance)
  6236. {
  6237. foreach (FieldInfo field in typeof(Permission).GetFields(BindingFlags.Public | BindingFlags.Static))
  6238. instance.permission.RegisterPermission((string) field.GetRawConstantValue(), instance);
  6239. }
  6240. }
  6241. }
  6242. }
  6243.  
  6244. namespace Oxide.Plugins
  6245. {
  6246. using System;
  6247. using Newtonsoft.Json;
  6248. using UnityEngine;
  6249.  
  6250. public partial class Imperium : RustPlugin
  6251. {
  6252. class UnityVector3Converter : JsonConverter
  6253. {
  6254. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  6255. {
  6256. var vector = (Vector3) value;
  6257. writer.WriteValue($"{vector.x} {vector.y} {vector.z}");
  6258. }
  6259.  
  6260. public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
  6261. JsonSerializer serializer)
  6262. {
  6263. string[] tokens = reader.Value.ToString().Trim().Split(' ');
  6264. float x = Convert.ToSingle(tokens[0]);
  6265. float y = Convert.ToSingle(tokens[1]);
  6266. float z = Convert.ToSingle(tokens[2]);
  6267. return new Vector3(x, y, z);
  6268. }
  6269.  
  6270. public override bool CanConvert(Type objectType)
  6271. {
  6272. return objectType == typeof(Vector3);
  6273. }
  6274. }
  6275. }
  6276. }
  6277.  
  6278. namespace Oxide.Plugins
  6279. {
  6280. using System;
  6281. using System.Collections;
  6282. using System.Text;
  6283.  
  6284. public partial class Imperium
  6285. {
  6286. static class Util
  6287. {
  6288. const string NullString = "(null)";
  6289.  
  6290. public static string Format(object obj)
  6291. {
  6292. if (obj == null) return NullString;
  6293.  
  6294. var user = obj as User;
  6295. if (user != null) return Format(user);
  6296.  
  6297. var area = obj as Area;
  6298. if (area != null) return Format(area);
  6299.  
  6300. var entity = obj as BaseEntity;
  6301. if (entity != null) return Format(entity);
  6302.  
  6303. var list = obj as IEnumerable;
  6304. if (list != null) return Format(list);
  6305.  
  6306. return obj.ToString();
  6307. }
  6308.  
  6309. public static string Format(User user)
  6310. {
  6311. if (user == null)
  6312. return NullString;
  6313. else
  6314. return $"{user.UserName} ({user.Id})";
  6315. }
  6316.  
  6317. public static string Format(Area area)
  6318. {
  6319. if (area == null)
  6320. return NullString;
  6321. else if (!String.IsNullOrEmpty(area.Name))
  6322. return $"{area.Id} ({area.Name})";
  6323. else
  6324. return area.Id;
  6325. }
  6326.  
  6327. public static string Format(BaseEntity entity)
  6328. {
  6329. if (entity == null)
  6330. return NullString;
  6331. else if (entity.net == null)
  6332. return "(missing networkable)";
  6333. else
  6334. return entity.net.ID.ToString();
  6335. }
  6336.  
  6337. public static string Format(IEnumerable items)
  6338. {
  6339. var sb = new StringBuilder();
  6340.  
  6341. foreach (object item in items)
  6342. sb.Append($"{Format(item)}, ");
  6343.  
  6344. sb.Remove(sb.Length - 2, 2);
  6345.  
  6346. return sb.ToString();
  6347. }
  6348.  
  6349. public static string NormalizeAreaId(string input)
  6350. {
  6351. return input.ToUpper().Trim();
  6352. }
  6353.  
  6354. public static string NormalizeAreaName(string input)
  6355. {
  6356. return RemoveSpecialCharacters(input.Trim());
  6357. }
  6358.  
  6359. public static string NormalizePinName(string input)
  6360. {
  6361. return RemoveSpecialCharacters(input.Trim());
  6362. }
  6363.  
  6364. public static string NormalizeFactionId(string input)
  6365. {
  6366. string factionId = input.Trim();
  6367.  
  6368. if (factionId.StartsWith("[") && factionId.EndsWith("]"))
  6369. factionId = factionId.Substring(1, factionId.Length - 2);
  6370.  
  6371. return factionId;
  6372. }
  6373.  
  6374. public static string RemoveSpecialCharacters(string str)
  6375. {
  6376. if (String.IsNullOrEmpty(str))
  6377. return String.Empty;
  6378.  
  6379. StringBuilder sb = new StringBuilder(str.Length);
  6380. foreach (char c in str)
  6381. {
  6382. if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') ||
  6383. (c >= 'А' && c <= 'Я') || (c >= 'а' && c <= 'я') || c == ' ' || c == '.' || c == '_')
  6384. sb.Append(c);
  6385. }
  6386.  
  6387. return sb.ToString();
  6388. }
  6389.  
  6390. public static int GetLevenshteinDistance(string source, string target)
  6391. {
  6392. if (string.IsNullOrEmpty(source) && string.IsNullOrEmpty(target))
  6393. return 0;
  6394.  
  6395. if (source.Length == target.Length)
  6396. return source.Length;
  6397.  
  6398. if (source.Length == 0)
  6399. return target.Length;
  6400.  
  6401. if (target.Length == 0)
  6402. return source.Length;
  6403.  
  6404. var distance = new int[source.Length + 1, target.Length + 1];
  6405.  
  6406. for (int idx = 0; idx <= source.Length; distance[idx, 0] = idx++) ;
  6407. for (int idx = 0; idx <= target.Length; distance[0, idx] = idx++) ;
  6408.  
  6409. for (int i = 1; i <= source.Length; i++)
  6410. {
  6411. for (int j = 1; j <= target.Length; j++)
  6412. {
  6413. int cost = target[j - 1] == source[i - 1] ? 0 : 1;
  6414. distance[i, j] = Math.Min(
  6415. Math.Min(distance[i - 1, j] + 1, distance[i, j - 1] + 1),
  6416. distance[i - 1, j - 1] + cost
  6417. );
  6418. }
  6419. }
  6420.  
  6421. return distance[source.Length, target.Length];
  6422. }
  6423.  
  6424. public static bool TryParseEnum<T>(string str, out T value) where T : struct
  6425. {
  6426. if (!typeof(T).IsEnum)
  6427. throw new ArgumentException("Type parameter must be an enum");
  6428.  
  6429. foreach (var name in Enum.GetNames(typeof(T)))
  6430. {
  6431. if (String.Equals(name, str, StringComparison.OrdinalIgnoreCase))
  6432. {
  6433. value = (T) Enum.Parse(typeof(T), name);
  6434. return true;
  6435. }
  6436. }
  6437.  
  6438. value = default(T);
  6439. return false;
  6440. }
  6441. }
  6442. }
  6443. }
  6444.  
  6445. namespace Oxide.Plugins
  6446. {
  6447. using System;
  6448. using System.Collections.Generic;
  6449.  
  6450. public partial class Imperium
  6451. {
  6452. class AddingClaimInteraction : Interaction
  6453. {
  6454. public Faction Faction { get; private set; }
  6455.  
  6456. public AddingClaimInteraction(Faction faction)
  6457. {
  6458. Faction = faction;
  6459. }
  6460.  
  6461. public override bool TryComplete(HitInfo hit)
  6462. {
  6463. var cupboard = hit.HitEntity as BuildingPrivlidge;
  6464. Area area = User.CurrentArea;
  6465.  
  6466. if (area == null)
  6467. return false;
  6468.  
  6469. if (!Instance.EnsureUserCanChangeFactionClaims(User, Faction))
  6470. return false;
  6471.  
  6472. if (!Instance.EnsureCupboardCanBeUsedForClaim(User, cupboard))
  6473. return false;
  6474.  
  6475. if (!Instance.EnsureFactionCanClaimArea(User, Faction, area))
  6476. return false;
  6477.  
  6478. Area[] claimedAreas = Instance.Areas.GetAllClaimedByFaction(Faction);
  6479. AreaType type = (claimedAreas.Length == 0) ? AreaType.Headquarters : AreaType.Claimed;
  6480.  
  6481. if (area.Type == AreaType.Wilderness)
  6482. {
  6483. int cost = area.GetClaimCost(Faction);
  6484.  
  6485. if (cost > 0)
  6486. {
  6487. ItemDefinition scrapDef = ItemManager.FindItemDefinition("scrap");
  6488. List<Item> stacks = User.Player.inventory.FindItemIDs(scrapDef.itemid);
  6489.  
  6490. if (!Instance.TryCollectFromStacks(scrapDef, stacks, cost))
  6491. {
  6492. User.SendChatMessage(Messages.CannotClaimAreaCannotAfford, cost);
  6493. return false;
  6494. }
  6495. }
  6496.  
  6497. User.SendChatMessage(Messages.ClaimAdded, area.Id);
  6498.  
  6499. if (type == AreaType.Headquarters)
  6500. {
  6501. Instance.PrintToChat(Messages.AreaClaimedAsHeadquartersAnnouncement, Faction.Id, area.Id);
  6502. Faction.NextUpkeepPaymentTime =
  6503. DateTime.UtcNow.AddHours(Instance.Options.Upkeep.CollectionPeriodHours);
  6504. }
  6505. else
  6506. {
  6507. Instance.PrintToChat(Messages.AreaClaimedAnnouncement, Faction.Id, area.Id);
  6508. }
  6509.  
  6510. Instance.Log($"{Util.Format(User)} claimed {area.Id} on behalf of {Faction.Id}");
  6511. Instance.Areas.Claim(area, type, Faction, User, cupboard);
  6512.  
  6513. return true;
  6514. }
  6515.  
  6516. if (area.FactionId == Faction.Id)
  6517. {
  6518. if (area.ClaimCupboard.net.ID == cupboard.net.ID)
  6519. {
  6520. User.SendChatMessage(Messages.CannotClaimAreaAlreadyOwned, area.Id);
  6521. return false;
  6522. }
  6523. else
  6524. {
  6525. // If the same faction claims a new cupboard within the same area, move the claim to the new cupboard.
  6526. User.SendChatMessage(Messages.ClaimCupboardMoved, area.Id);
  6527. Instance.Log(
  6528. $"{Util.Format(User)} moved {area.FactionId}'s claim on {area.Id} from cupboard {Util.Format(area.ClaimCupboard)} to cupboard {Util.Format(cupboard)}");
  6529. area.ClaimantId = User.Id;
  6530. area.ClaimCupboard = cupboard;
  6531. return true;
  6532. }
  6533. }
  6534.  
  6535. if (area.FactionId != Faction.Id)
  6536. {
  6537. if (area.ClaimCupboard.net.ID != cupboard.net.ID)
  6538. {
  6539. // A new faction can't make a claim on a new cabinet within an area that is already claimed by another faction.
  6540. User.SendChatMessage(Messages.CannotClaimAreaAlreadyClaimed, area.Id, area.FactionId);
  6541. return false;
  6542. }
  6543.  
  6544. string previousFactionId = area.FactionId;
  6545.  
  6546. // If a new faction claims the claim cabinet for an area, they take control of that area.
  6547. User.SendChatMessage(Messages.ClaimCaptured, area.Id, area.FactionId);
  6548. Instance.PrintToChat(Messages.AreaCapturedAnnouncement, Faction.Id, area.Id, area.FactionId);
  6549. Instance.Log(
  6550. $"{Util.Format(User)} captured the claim on {area.Id} from {area.FactionId} on behalf of {Faction.Id}");
  6551.  
  6552. Instance.Areas.Claim(area, type, Faction, User, cupboard);
  6553. return true;
  6554. }
  6555.  
  6556. Instance.PrintWarning(
  6557. "Area was in an unknown state during completion of AddingClaimInteraction. This shouldn't happen.");
  6558. return false;
  6559. }
  6560. }
  6561. }
  6562. }
  6563.  
  6564. namespace Oxide.Plugins
  6565. {
  6566. public partial class Imperium
  6567. {
  6568. class AssigningClaimInteraction : Interaction
  6569. {
  6570. public Faction Faction { get; private set; }
  6571.  
  6572. public AssigningClaimInteraction(Faction faction)
  6573. {
  6574. Faction = faction;
  6575. }
  6576.  
  6577. public override bool TryComplete(HitInfo hit)
  6578. {
  6579. var cupboard = hit.HitEntity as BuildingPrivlidge;
  6580.  
  6581. Area area = User.CurrentArea;
  6582.  
  6583. if (area == null)
  6584. {
  6585. User.SendChatMessage(Messages.YouAreInTheGreatUnknown);
  6586. return false;
  6587. }
  6588.  
  6589. if (area.Type == AreaType.Badlands)
  6590. {
  6591. User.SendChatMessage(Messages.AreaIsBadlands, area.Id);
  6592. return false;
  6593. }
  6594.  
  6595. Area[] ownedAreas = Instance.Areas.GetAllClaimedByFaction(Faction);
  6596. AreaType type = (ownedAreas.Length == 0) ? AreaType.Headquarters : AreaType.Claimed;
  6597.  
  6598. Instance.PrintToChat(Messages.AreaClaimAssignedAnnouncement, Faction.Id, area.Id);
  6599. Instance.Log($"{Util.Format(User)} assigned {area.Id} to {Faction.Id}");
  6600.  
  6601. Instance.Areas.Claim(area, type, Faction, User, cupboard);
  6602. return true;
  6603. }
  6604. }
  6605. }
  6606. }
  6607.  
  6608. namespace Oxide.Plugins
  6609. {
  6610. public partial class Imperium
  6611. {
  6612. abstract class Interaction
  6613. {
  6614. public User User { get; set; }
  6615. public abstract bool TryComplete(HitInfo hit);
  6616. }
  6617. }
  6618. }
  6619.  
  6620. namespace Oxide.Plugins
  6621. {
  6622. public partial class Imperium
  6623. {
  6624. class RemovingClaimInteraction : Interaction
  6625. {
  6626. public Faction Faction { get; private set; }
  6627.  
  6628. public RemovingClaimInteraction(Faction faction)
  6629. {
  6630. Faction = faction;
  6631. }
  6632.  
  6633. public override bool TryComplete(HitInfo hit)
  6634. {
  6635. var cupboard = hit.HitEntity as BuildingPrivlidge;
  6636.  
  6637. if (!Instance.EnsureUserCanChangeFactionClaims(User, Faction) ||
  6638. !Instance.EnsureCupboardCanBeUsedForClaim(User, cupboard))
  6639. return false;
  6640.  
  6641. Area area = Instance.Areas.GetByClaimCupboard(cupboard);
  6642.  
  6643. if (area == null)
  6644. {
  6645. User.SendChatMessage(Messages.SelectingCupboardFailedNotClaimCupboard);
  6646. return false;
  6647. }
  6648.  
  6649. Instance.PrintToChat(Messages.AreaClaimRemovedAnnouncement, Faction.Id, area.Id);
  6650. Instance.Log($"{Util.Format(User)} removed {Faction.Id}'s claim on {area.Id}");
  6651.  
  6652. Instance.Areas.Unclaim(area);
  6653. return true;
  6654. }
  6655. }
  6656. }
  6657. }
  6658.  
  6659. namespace Oxide.Plugins
  6660. {
  6661. public partial class Imperium
  6662. {
  6663. class SelectingHeadquartersInteraction : Interaction
  6664. {
  6665. public Faction Faction { get; private set; }
  6666.  
  6667. public SelectingHeadquartersInteraction(Faction faction)
  6668. {
  6669. Faction = faction;
  6670. }
  6671.  
  6672. public override bool TryComplete(HitInfo hit)
  6673. {
  6674. var cupboard = hit.HitEntity as BuildingPrivlidge;
  6675.  
  6676. if (!Instance.EnsureUserCanChangeFactionClaims(User, Faction) ||
  6677. !Instance.EnsureCupboardCanBeUsedForClaim(User, cupboard))
  6678. return false;
  6679.  
  6680. Area area = Instance.Areas.GetByClaimCupboard(cupboard);
  6681. if (area == null)
  6682. {
  6683. User.SendChatMessage(Messages.SelectingCupboardFailedNotClaimCupboard);
  6684. return false;
  6685. }
  6686.  
  6687. Instance.PrintToChat(Messages.HeadquartersChangedAnnouncement, Faction.Id, area.Id);
  6688. Instance.Log($"{Util.Format(User)} set {Faction.Id}'s headquarters to {area.Id}");
  6689.  
  6690. Instance.Areas.SetHeadquarters(area, Faction);
  6691. return true;
  6692. }
  6693. }
  6694. }
  6695. }
  6696.  
  6697. namespace Oxide.Plugins
  6698. {
  6699. public partial class Imperium
  6700. {
  6701. class SelectingTaxChestInteraction : Interaction
  6702. {
  6703. public Faction Faction { get; private set; }
  6704.  
  6705. public SelectingTaxChestInteraction(Faction faction)
  6706. {
  6707. Faction = faction;
  6708. }
  6709.  
  6710. public override bool TryComplete(HitInfo hit)
  6711. {
  6712. var container = hit.HitEntity as StorageContainer;
  6713.  
  6714. if (container == null)
  6715. {
  6716. User.SendChatMessage(Messages.SelectingTaxChestFailedInvalidTarget);
  6717. return false;
  6718. }
  6719.  
  6720. User.SendChatMessage(Messages.SelectingTaxChestSucceeded, Faction.TaxRate * 100, Faction.Id);
  6721. Instance.Log($"{Util.Format(User)} set {Faction.Id}'s tax chest to entity {Util.Format(container)}");
  6722. Instance.Factions.SetTaxChest(Faction, container);
  6723.  
  6724. return true;
  6725. }
  6726. }
  6727. }
  6728. }
  6729.  
  6730. namespace Oxide.Plugins
  6731. {
  6732. public partial class Imperium
  6733. {
  6734. class TransferringClaimInteraction : Interaction
  6735. {
  6736. public Faction SourceFaction { get; }
  6737. public Faction TargetFaction { get; }
  6738.  
  6739. public TransferringClaimInteraction(Faction sourceFaction, Faction targetFaction)
  6740. {
  6741. SourceFaction = sourceFaction;
  6742. TargetFaction = targetFaction;
  6743. }
  6744.  
  6745. public override bool TryComplete(HitInfo hit)
  6746. {
  6747. var cupboard = hit.HitEntity as BuildingPrivlidge;
  6748.  
  6749. if (!Instance.EnsureUserCanChangeFactionClaims(User, SourceFaction) ||
  6750. !Instance.EnsureCupboardCanBeUsedForClaim(User, cupboard))
  6751. return false;
  6752.  
  6753. Area area = Instance.Areas.GetByClaimCupboard(cupboard);
  6754.  
  6755. if (area == null)
  6756. {
  6757. User.SendChatMessage(Messages.SelectingCupboardFailedNotClaimCupboard);
  6758. return false;
  6759. }
  6760.  
  6761. if (area.FactionId != SourceFaction.Id)
  6762. {
  6763. User.SendChatMessage(Messages.AreaNotOwnedByYourFaction, area.Id);
  6764. return false;
  6765. }
  6766.  
  6767. if (!Instance.EnsureFactionCanClaimArea(User, TargetFaction, area))
  6768. return false;
  6769.  
  6770. Area[] claimedAreas = Instance.Areas.GetAllClaimedByFaction(TargetFaction);
  6771. AreaType type = (claimedAreas.Length == 0) ? AreaType.Headquarters : AreaType.Claimed;
  6772.  
  6773. Instance.PrintToChat(Messages.AreaClaimTransferredAnnouncement, SourceFaction.Id, area.Id,
  6774. TargetFaction.Id);
  6775. Instance.Log(
  6776. $"{Util.Format(User)} transferred {SourceFaction.Id}'s claim on {area.Id} to {TargetFaction.Id}");
  6777.  
  6778. Instance.Areas.Claim(area, type, TargetFaction, User, cupboard);
  6779.  
  6780. return true;
  6781. }
  6782. }
  6783. }
  6784. }
  6785.  
  6786. namespace Oxide.Plugins
  6787. {
  6788. using Newtonsoft.Json;
  6789.  
  6790. public partial class Imperium : RustPlugin
  6791. {
  6792. class BadlandsOptions
  6793. {
  6794. [JsonProperty("enabled")] public bool Enabled;
  6795.  
  6796. public static BadlandsOptions Default = new BadlandsOptions
  6797. {
  6798. Enabled = true
  6799. };
  6800. }
  6801. }
  6802. }
  6803.  
  6804. namespace Oxide.Plugins
  6805. {
  6806. using Newtonsoft.Json;
  6807. using System.Collections.Generic;
  6808.  
  6809. public partial class Imperium : RustPlugin
  6810. {
  6811. class ClaimOptions
  6812. {
  6813. [JsonProperty("enabled")] public bool Enabled;
  6814.  
  6815. [JsonProperty("costs")] public List<int> Costs = new List<int>();
  6816.  
  6817. [JsonProperty("maxClaims")] public int? MaxClaims;
  6818.  
  6819. [JsonProperty("minAreaNameLength")] public int MinAreaNameLength;
  6820.  
  6821. [JsonProperty("maxAreaNameLength")] public int MaxAreaNameLength;
  6822.  
  6823. [JsonProperty("minFactionMembers")] public int MinFactionMembers;
  6824.  
  6825. [JsonProperty("requireContiguousClaims")]
  6826. public bool RequireContiguousClaims;
  6827.  
  6828. public static ClaimOptions Default = new ClaimOptions
  6829. {
  6830. Enabled = true,
  6831. Costs = new List<int> {0, 100, 200, 300, 400, 500},
  6832. MaxClaims = null,
  6833. MinAreaNameLength = 3,
  6834. MaxAreaNameLength = 20,
  6835. MinFactionMembers = 3,
  6836. RequireContiguousClaims = false
  6837. };
  6838. }
  6839. }
  6840. }
  6841.  
  6842. namespace Oxide.Plugins
  6843. {
  6844. using Newtonsoft.Json;
  6845.  
  6846. public partial class Imperium : RustPlugin
  6847. {
  6848. class DecayOptions
  6849. {
  6850. [JsonProperty("enabled")] public bool Enabled;
  6851.  
  6852. [JsonProperty("claimedLandDecayReduction")]
  6853. public float ClaimedLandDecayReduction;
  6854.  
  6855. public static DecayOptions Default = new DecayOptions
  6856. {
  6857. Enabled = false,
  6858. ClaimedLandDecayReduction = 0.5f
  6859. };
  6860. }
  6861. }
  6862. }
  6863.  
  6864. namespace Oxide.Plugins
  6865. {
  6866. using Newtonsoft.Json;
  6867.  
  6868. public partial class Imperium : RustPlugin
  6869. {
  6870. class FactionOptions
  6871. {
  6872. [JsonProperty("minFactionNameLength")] public int MinFactionNameLength;
  6873.  
  6874. [JsonProperty("maxFactionNameLength")] public int MaxFactionNameLength;
  6875.  
  6876. [JsonProperty("maxMembers")] public int? MaxMembers;
  6877.  
  6878. public static FactionOptions Default = new FactionOptions
  6879. {
  6880. MinFactionNameLength = 1,
  6881. MaxFactionNameLength = 8,
  6882. MaxMembers = null
  6883. };
  6884. }
  6885. }
  6886. }
  6887.  
  6888. namespace Oxide.Plugins
  6889. {
  6890. using Newtonsoft.Json;
  6891.  
  6892. public partial class Imperium : RustPlugin
  6893. {
  6894. class MapOptions
  6895. {
  6896. [JsonProperty("pinsEnabled")] public bool PinsEnabled;
  6897.  
  6898. [JsonProperty("minPinNameLength")] public int MinPinNameLength;
  6899.  
  6900. [JsonProperty("maxPinNameLength")] public int MaxPinNameLength;
  6901.  
  6902. [JsonProperty("pinCost")] public int PinCost;
  6903.  
  6904. [JsonProperty("commandCooldownSeconds")]
  6905. public int CommandCooldownSeconds;
  6906.  
  6907. [JsonProperty("imageUrl")] public string ImageUrl;
  6908.  
  6909. [JsonProperty("imageSize")] public int ImageSize;
  6910.  
  6911. [JsonProperty("serverLogoUrl")] public string ServerLogoUrl;
  6912.  
  6913. public static MapOptions Default = new MapOptions
  6914. {
  6915. PinsEnabled = true,
  6916. MinPinNameLength = 2,
  6917. MaxPinNameLength = 20,
  6918. PinCost = 100,
  6919. CommandCooldownSeconds = 10,
  6920. ImageUrl = "",
  6921. ImageSize = 1440,
  6922. ServerLogoUrl = ""
  6923. };
  6924. }
  6925. }
  6926. }
  6927.  
  6928. namespace Oxide.Plugins
  6929. {
  6930. using Newtonsoft.Json;
  6931.  
  6932. public partial class Imperium : RustPlugin
  6933. {
  6934. class ImperiumOptions
  6935. {
  6936. [JsonProperty("badlands")] public BadlandsOptions Badlands;
  6937.  
  6938. [JsonProperty("claims")] public ClaimOptions Claims;
  6939.  
  6940. [JsonProperty("decay")] public DecayOptions Decay;
  6941.  
  6942. [JsonProperty("factions")] public FactionOptions Factions;
  6943.  
  6944. [JsonProperty("map")] public MapOptions Map;
  6945.  
  6946. [JsonProperty("pvp")] public PvpOptions Pvp;
  6947.  
  6948. [JsonProperty("raiding")] public RaidingOptions Raiding;
  6949.  
  6950. [JsonProperty("taxes")] public TaxOptions Taxes;
  6951.  
  6952. [JsonProperty("upkeep")] public UpkeepOptions Upkeep;
  6953.  
  6954. [JsonProperty("war")] public WarOptions War;
  6955.  
  6956. [JsonProperty("zones")] public ZoneOptions Zones;
  6957.  
  6958. public static ImperiumOptions Default = new ImperiumOptions
  6959. {
  6960. Badlands = BadlandsOptions.Default,
  6961. Claims = ClaimOptions.Default,
  6962. Decay = DecayOptions.Default,
  6963. Factions = FactionOptions.Default,
  6964. Map = MapOptions.Default,
  6965. Pvp = PvpOptions.Default,
  6966. Raiding = RaidingOptions.Default,
  6967. Taxes = TaxOptions.Default,
  6968. Upkeep = UpkeepOptions.Default,
  6969. War = WarOptions.Default,
  6970. Zones = ZoneOptions.Default
  6971. };
  6972. }
  6973.  
  6974. protected override void LoadDefaultConfig()
  6975. {
  6976. PrintWarning("Loading default configuration.");
  6977. Config.WriteObject(ImperiumOptions.Default, true);
  6978. }
  6979. }
  6980. }
  6981.  
  6982. namespace Oxide.Plugins
  6983. {
  6984. using Newtonsoft.Json;
  6985.  
  6986. public partial class Imperium : RustPlugin
  6987. {
  6988. class PvpOptions
  6989. {
  6990. [JsonProperty("restrictPvp")] public bool RestrictPvp;
  6991.  
  6992. [JsonProperty("allowedInBadlands")] public bool AllowedInBadlands;
  6993.  
  6994. [JsonProperty("allowedInClaimedLand")] public bool AllowedInClaimedLand;
  6995.  
  6996. [JsonProperty("allowedInWilderness")] public bool AllowedInWilderness;
  6997.  
  6998. [JsonProperty("allowedInEventZones")] public bool AllowedInEventZones;
  6999.  
  7000. [JsonProperty("allowedInMonumentZones")]
  7001. public bool AllowedInMonumentZones;
  7002.  
  7003. [JsonProperty("allowedInRaidZones")] public bool AllowedInRaidZones;
  7004.  
  7005. [JsonProperty("allowedInDeepWater")] public bool AllowedInDeepWater;
  7006.  
  7007. [JsonProperty("enablePvpCommand")] public bool EnablePvpCommand;
  7008.  
  7009. [JsonProperty("commandCooldownSeconds")]
  7010. public int CommandCooldownSeconds;
  7011.  
  7012. public static PvpOptions Default = new PvpOptions
  7013. {
  7014. RestrictPvp = false,
  7015. AllowedInBadlands = true,
  7016. AllowedInClaimedLand = true,
  7017. AllowedInEventZones = true,
  7018. AllowedInMonumentZones = true,
  7019. AllowedInRaidZones = true,
  7020. AllowedInWilderness = true,
  7021. AllowedInDeepWater = true,
  7022. EnablePvpCommand = false,
  7023. CommandCooldownSeconds = 60
  7024. };
  7025. }
  7026. }
  7027. }
  7028.  
  7029. namespace Oxide.Plugins
  7030. {
  7031. using Newtonsoft.Json;
  7032.  
  7033. public partial class Imperium : RustPlugin
  7034. {
  7035. class RaidingOptions
  7036. {
  7037. [JsonProperty("restrictRaiding")] public bool RestrictRaiding;
  7038.  
  7039. [JsonProperty("allowedInBadlands")] public bool AllowedInBadlands;
  7040.  
  7041. [JsonProperty("allowedInClaimedLand")] public bool AllowedInClaimedLand;
  7042.  
  7043. [JsonProperty("allowedInWilderness")] public bool AllowedInWilderness;
  7044.  
  7045. public static RaidingOptions Default = new RaidingOptions
  7046. {
  7047. RestrictRaiding = false,
  7048. AllowedInBadlands = true,
  7049. AllowedInClaimedLand = true,
  7050. AllowedInWilderness = true
  7051. };
  7052. }
  7053. }
  7054. }
  7055.  
  7056. namespace Oxide.Plugins
  7057. {
  7058. using Newtonsoft.Json;
  7059.  
  7060. public partial class Imperium : RustPlugin
  7061. {
  7062. class TaxOptions
  7063. {
  7064. [JsonProperty("enabled")] public bool Enabled;
  7065.  
  7066. [JsonProperty("defaultTaxRate")] public float DefaultTaxRate;
  7067.  
  7068. [JsonProperty("maxTaxRate")] public float MaxTaxRate;
  7069.  
  7070. [JsonProperty("claimedLandGatherBonus")]
  7071. public float ClaimedLandGatherBonus;
  7072.  
  7073. [JsonProperty("badlandsGatherBonus")] public float BadlandsGatherBonus;
  7074.  
  7075. public static TaxOptions Default = new TaxOptions
  7076. {
  7077. Enabled = true,
  7078. DefaultTaxRate = 0.1f,
  7079. MaxTaxRate = 0.2f,
  7080. ClaimedLandGatherBonus = 0.1f,
  7081. BadlandsGatherBonus = 0.1f
  7082. };
  7083. }
  7084. }
  7085. }
  7086.  
  7087. namespace Oxide.Plugins
  7088. {
  7089. using Newtonsoft.Json;
  7090. using System.Collections.Generic;
  7091.  
  7092. public partial class Imperium : RustPlugin
  7093. {
  7094. class UpkeepOptions
  7095. {
  7096. [JsonProperty("enabled")] public bool Enabled;
  7097.  
  7098. [JsonProperty("costs")] public List<int> Costs = new List<int>();
  7099.  
  7100. [JsonProperty("checkIntervalMinutes")] public int CheckIntervalMinutes;
  7101.  
  7102. [JsonProperty("collectionPeriodHours")]
  7103. public int CollectionPeriodHours;
  7104.  
  7105. [JsonProperty("gracePeriodHours")] public int GracePeriodHours;
  7106.  
  7107. public static UpkeepOptions Default = new UpkeepOptions
  7108. {
  7109. Enabled = false,
  7110. Costs = new List<int> {10, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100},
  7111. CheckIntervalMinutes = 15,
  7112. CollectionPeriodHours = 24,
  7113. GracePeriodHours = 12
  7114. };
  7115. }
  7116. }
  7117. }
  7118.  
  7119. namespace Oxide.Plugins
  7120. {
  7121. using Newtonsoft.Json;
  7122. using System.Collections.Generic;
  7123.  
  7124. public partial class Imperium : RustPlugin
  7125. {
  7126. class WarOptions
  7127. {
  7128. [JsonProperty("enabled")] public bool Enabled;
  7129.  
  7130. [JsonProperty("minCassusBelliLength")] public int MinCassusBelliLength;
  7131.  
  7132. [JsonProperty("defensiveBonuses")] public List<float> DefensiveBonuses = new List<float>();
  7133.  
  7134. public static WarOptions Default = new WarOptions
  7135. {
  7136. Enabled = true,
  7137. MinCassusBelliLength = 50,
  7138. DefensiveBonuses = new List<float> {0, 0.5f, 1f}
  7139. };
  7140. }
  7141. }
  7142. }
  7143.  
  7144. namespace Oxide.Plugins
  7145. {
  7146. using Newtonsoft.Json;
  7147. using System.Collections.Generic;
  7148.  
  7149. public partial class Imperium : RustPlugin
  7150. {
  7151. class ZoneOptions
  7152. {
  7153. [JsonProperty("enabled")] public bool Enabled;
  7154.  
  7155. [JsonProperty("domeDarkness")] public int DomeDarkness;
  7156.  
  7157. [JsonProperty("eventZoneRadius")] public float EventZoneRadius;
  7158.  
  7159. [JsonProperty("eventZoneLifespanSeconds")]
  7160. public float EventZoneLifespanSeconds;
  7161.  
  7162. [JsonProperty("monumentZones")]
  7163. public Dictionary<string, float> MonumentZones = new Dictionary<string, float>();
  7164.  
  7165. public static ZoneOptions Default = new ZoneOptions
  7166. {
  7167. Enabled = true,
  7168. DomeDarkness = 3,
  7169. EventZoneRadius = 150f,
  7170. EventZoneLifespanSeconds = 600f,
  7171. MonumentZones = new Dictionary<string, float>
  7172. {
  7173. {"airfield", 200},
  7174. {"sphere_tank", 120},
  7175. {"junkyard", 150},
  7176. {"launch_site", 300},
  7177. {"military_tunnel", 150},
  7178. {"powerplant", 175},
  7179. {"satellite_dish", 130},
  7180. {"trainyard", 180},
  7181. {"water_treatment_plant", 180}
  7182. }
  7183. };
  7184. }
  7185. }
  7186. }
  7187.  
  7188. namespace Oxide.Plugins
  7189. {
  7190. using System.Collections.Generic;
  7191. using UnityEngine;
  7192.  
  7193. public partial class Imperium
  7194. {
  7195. class GameEventWatcher : MonoBehaviour
  7196. {
  7197. const float CheckIntervalSeconds = 5f;
  7198.  
  7199. HashSet<CargoPlane> CargoPlanes = new HashSet<CargoPlane>();
  7200. HashSet<BaseHelicopter> PatrolHelicopters = new HashSet<BaseHelicopter>();
  7201. HashSet<CH47Helicopter> ChinookHelicopters = new HashSet<CH47Helicopter>();
  7202. HashSet<HackableLockedCrate> LockedCrates = new HashSet<HackableLockedCrate>();
  7203. HashSet<CargoShip> CargoShips = new HashSet<CargoShip>();
  7204.  
  7205. public bool IsCargoPlaneActive
  7206. {
  7207. get { return CargoPlanes.Count > 0; }
  7208. }
  7209.  
  7210. public bool IsHelicopterActive
  7211. {
  7212. get { return PatrolHelicopters.Count > 0; }
  7213. }
  7214.  
  7215. public bool IsChinookOrLockedCrateActive
  7216. {
  7217. get { return ChinookHelicopters.Count > 0 || LockedCrates.Count > 0; }
  7218. }
  7219.  
  7220. public bool IsCargoShipActive
  7221. {
  7222. get { return CargoShips.Count > 0; }
  7223. }
  7224.  
  7225. void Awake()
  7226. {
  7227. foreach (CargoPlane plane in FindObjectsOfType<CargoPlane>())
  7228. BeginEvent(plane);
  7229.  
  7230. foreach (BaseHelicopter heli in FindObjectsOfType<BaseHelicopter>())
  7231. BeginEvent(heli);
  7232.  
  7233. foreach (CH47Helicopter chinook in FindObjectsOfType<CH47Helicopter>())
  7234. BeginEvent(chinook);
  7235.  
  7236. foreach (HackableLockedCrate crate in FindObjectsOfType<HackableLockedCrate>())
  7237. BeginEvent(crate);
  7238.  
  7239. foreach (CargoShip ship in FindObjectsOfType<CargoShip>())
  7240. BeginEvent(ship);
  7241.  
  7242. InvokeRepeating("CheckEvents", CheckIntervalSeconds, CheckIntervalSeconds);
  7243. }
  7244.  
  7245. void OnDestroy()
  7246. {
  7247. CancelInvoke();
  7248. }
  7249.  
  7250. public void BeginEvent(CargoPlane plane)
  7251. {
  7252. Instance.Puts($"Beginning cargoplane event, plane at @ {plane.transform.position}");
  7253. CargoPlanes.Add(plane);
  7254. }
  7255.  
  7256. public void BeginEvent(BaseHelicopter heli)
  7257. {
  7258. Instance.Puts($"Beginning patrol helicopter event, heli at @ {heli.transform.position}");
  7259. PatrolHelicopters.Add(heli);
  7260. }
  7261.  
  7262. public void BeginEvent(CH47Helicopter chinook)
  7263. {
  7264. Instance.Puts($"Beginning chinook event, heli at @ {chinook.transform.position}");
  7265. ChinookHelicopters.Add(chinook);
  7266. }
  7267.  
  7268. public void BeginEvent(HackableLockedCrate crate)
  7269. {
  7270. Instance.Puts($"Beginning locked crate event, crate at @ {crate.transform.position}");
  7271. LockedCrates.Add(crate);
  7272. }
  7273.  
  7274. public void BeginEvent(CargoShip ship)
  7275. {
  7276. Instance.Puts($"Beginning cargo ship event, ship at @ {ship.transform.position}");
  7277. CargoShips.Add(ship);
  7278. }
  7279.  
  7280. void CheckEvents()
  7281. {
  7282. var endedEvents = CargoPlanes.RemoveWhere(IsEntityGone)
  7283. + PatrolHelicopters.RemoveWhere(IsEntityGone)
  7284. + ChinookHelicopters.RemoveWhere(IsEntityGone)
  7285. + LockedCrates.RemoveWhere(IsEntityGone)
  7286. + CargoShips.RemoveWhere(IsEntityGone);
  7287.  
  7288. if (endedEvents > 0)
  7289. Instance.Hud.RefreshForAllPlayers();
  7290. }
  7291.  
  7292. bool IsEntityGone(BaseEntity entity)
  7293. {
  7294. return !entity.IsValid() || !entity.gameObject.activeInHierarchy;
  7295. }
  7296. }
  7297. }
  7298. }
  7299.  
  7300. namespace Oxide.Plugins
  7301. {
  7302. using System;
  7303. using System.Collections.Generic;
  7304. using System.Linq;
  7305. using System.Reflection;
  7306. using Oxide.Game.Rust.Cui;
  7307.  
  7308. public partial class Imperium
  7309. {
  7310. class HudManager
  7311. {
  7312. Dictionary<string, Image> Images;
  7313. bool UpdatePending;
  7314.  
  7315. public GameEventWatcher GameEvents { get; private set; }
  7316.  
  7317. ImageDownloader ImageDownloader;
  7318. MapOverlayGenerator MapOverlayGenerator;
  7319.  
  7320. public HudManager()
  7321. {
  7322. Images = new Dictionary<string, Image>();
  7323. GameEvents = Instance.GameObject.AddComponent<GameEventWatcher>();
  7324. ImageDownloader = Instance.GameObject.AddComponent<ImageDownloader>();
  7325. MapOverlayGenerator = Instance.GameObject.AddComponent<MapOverlayGenerator>();
  7326. }
  7327.  
  7328. public void RefreshForAllPlayers()
  7329. {
  7330. if (UpdatePending)
  7331. return;
  7332.  
  7333. Instance.NextTick(() =>
  7334. {
  7335. foreach (User user in Instance.Users.GetAll())
  7336. {
  7337. user.Map.Refresh();
  7338. user.Hud.Refresh();
  7339. }
  7340.  
  7341. UpdatePending = false;
  7342. });
  7343.  
  7344. UpdatePending = true;
  7345. }
  7346.  
  7347. public Image RegisterImage(string url, byte[] imageData = null, bool overwrite = false)
  7348. {
  7349. Image image;
  7350.  
  7351. if (Images.TryGetValue(url, out image) && !overwrite)
  7352. return image;
  7353. else
  7354. image = new Image(url);
  7355.  
  7356. Images[url] = image;
  7357.  
  7358. if (imageData != null)
  7359. image.Save(imageData);
  7360. else
  7361. ImageDownloader.Download(image);
  7362.  
  7363. return image;
  7364. }
  7365.  
  7366. public void RefreshAllImages()
  7367. {
  7368. foreach (Image image in Images.Values.Where(image => !image.IsGenerated))
  7369. {
  7370. image.Delete();
  7371. ImageDownloader.Download(image);
  7372. }
  7373. }
  7374.  
  7375. public CuiRawImageComponent CreateImageComponent(string imageUrl)
  7376. {
  7377. Image image;
  7378.  
  7379. if (String.IsNullOrEmpty(imageUrl))
  7380. {
  7381. Instance.PrintError(
  7382. $"CuiRawImageComponent requested for an image with a null URL. Did you forget to set MapImageUrl in the configuration?");
  7383. return null;
  7384. }
  7385.  
  7386. if (!Images.TryGetValue(imageUrl, out image))
  7387. {
  7388. Instance.PrintError(
  7389. $"CuiRawImageComponent requested for image with an unregistered URL {imageUrl}. This shouldn't happen.");
  7390. return null;
  7391. }
  7392.  
  7393. if (image.Id != null)
  7394. return new CuiRawImageComponent {Png = image.Id, Sprite = Ui.TransparentTexture};
  7395. else
  7396. return new CuiRawImageComponent {Url = image.Url, Sprite = Ui.TransparentTexture};
  7397. }
  7398.  
  7399. public void GenerateMapOverlayImage()
  7400. {
  7401. MapOverlayGenerator.Generate();
  7402. }
  7403.  
  7404. public void Init()
  7405. {
  7406. if (!String.IsNullOrEmpty(Instance.Options.Map.ImageUrl))
  7407. RegisterImage(Instance.Options.Map.ImageUrl);
  7408.  
  7409. if (!String.IsNullOrEmpty(Instance.Options.Map.ServerLogoUrl))
  7410. RegisterImage(Instance.Options.Map.ServerLogoUrl);
  7411.  
  7412. RegisterDefaultImages(typeof(Ui.HudIcon));
  7413. RegisterDefaultImages(typeof(Ui.MapIcon));
  7414. }
  7415.  
  7416. public void Destroy()
  7417. {
  7418. UnityEngine.Object.DestroyImmediate(ImageDownloader);
  7419. UnityEngine.Object.DestroyImmediate(MapOverlayGenerator);
  7420. UnityEngine.Object.DestroyImmediate(GameEvents);
  7421.  
  7422. foreach (Image image in Images.Values)
  7423. image.Delete();
  7424.  
  7425. Images.Clear();
  7426. }
  7427.  
  7428. void RegisterDefaultImages(Type type)
  7429. {
  7430. foreach (FieldInfo field in type.GetFields(BindingFlags.Public | BindingFlags.Static))
  7431. RegisterImage((string) field.GetRawConstantValue());
  7432. }
  7433. }
  7434. }
  7435. }
  7436.  
  7437. namespace Oxide.Plugins
  7438. {
  7439. using System;
  7440.  
  7441. public partial class Imperium
  7442. {
  7443. class Image
  7444. {
  7445. public string Url { get; private set; }
  7446. public string Id { get; private set; }
  7447.  
  7448. public bool IsDownloaded
  7449. {
  7450. get { return Id != null; }
  7451. }
  7452.  
  7453. public bool IsGenerated
  7454. {
  7455. get { return Url != null && !Url.StartsWith("http", StringComparison.Ordinal); }
  7456. }
  7457.  
  7458. public Image(string url, string id = null)
  7459. {
  7460. Url = url;
  7461. Id = id;
  7462. }
  7463.  
  7464. public string Save(byte[] data)
  7465. {
  7466. if (IsDownloaded) Delete();
  7467. Id = FileStorage.server.Store(data, FileStorage.Type.png, CommunityEntity.ServerInstance.net.ID, 0)
  7468. .ToString();
  7469. return Id;
  7470. }
  7471.  
  7472. public void Delete()
  7473. {
  7474. if (!IsDownloaded) return;
  7475. FileStorage.server.Remove(Convert.ToUInt32(Id), FileStorage.Type.png,
  7476. CommunityEntity.ServerInstance.net.ID);
  7477. Id = null;
  7478. }
  7479. }
  7480. }
  7481. }
  7482.  
  7483. namespace Oxide.Plugins
  7484. {
  7485. using System;
  7486. using System.Collections;
  7487. using System.Collections.Generic;
  7488. using UnityEngine;
  7489.  
  7490. public partial class Imperium
  7491. {
  7492. class ImageDownloader : MonoBehaviour
  7493. {
  7494. Queue<Image> PendingImages = new Queue<Image>();
  7495.  
  7496. public bool IsDownloading { get; private set; }
  7497.  
  7498. public void Download(Image image)
  7499. {
  7500. PendingImages.Enqueue(image);
  7501. if (!IsDownloading) DownloadNext();
  7502. }
  7503.  
  7504. void DownloadNext()
  7505. {
  7506. if (PendingImages.Count == 0)
  7507. {
  7508. IsDownloading = false;
  7509. return;
  7510. }
  7511.  
  7512. Image image = PendingImages.Dequeue();
  7513. StartCoroutine(DownloadImage(image));
  7514.  
  7515. IsDownloading = true;
  7516. }
  7517.  
  7518. IEnumerator DownloadImage(Image image)
  7519. {
  7520. var www = new WWW(image.Url);
  7521. yield return www;
  7522.  
  7523. if (!String.IsNullOrEmpty(www.error))
  7524. {
  7525. Instance.Puts($"Error while downloading image {image.Url}: {www.error}");
  7526. }
  7527. else if (www.bytes == null || www.bytes.Length == 0)
  7528. {
  7529. Instance.Puts($"Error while downloading image {image.Url}: No data received");
  7530. }
  7531. else
  7532. {
  7533. byte[] data = www.texture.EncodeToPNG();
  7534. image.Save(data);
  7535. DestroyImmediate(www.texture);
  7536. Instance.Puts($"Stored {image.Url} as id {image.Id}");
  7537. DownloadNext();
  7538. }
  7539. }
  7540. }
  7541. }
  7542. }
  7543.  
  7544. namespace Oxide.Plugins
  7545. {
  7546. using System;
  7547. using System.Collections.Generic;
  7548.  
  7549. public partial class Imperium
  7550. {
  7551. class MapMarker
  7552. {
  7553. public string IconUrl;
  7554. public string Label;
  7555. public float X;
  7556. public float Z;
  7557.  
  7558. public static MapMarker ForUser(User user)
  7559. {
  7560. return new MapMarker
  7561. {
  7562. IconUrl = Ui.MapIcon.Player,
  7563. X = TranslatePosition(user.Player.transform.position.x),
  7564. Z = TranslatePosition(user.Player.transform.position.z)
  7565. };
  7566. }
  7567.  
  7568. public static MapMarker ForHeadquarters(Area area, Faction faction)
  7569. {
  7570. return new MapMarker
  7571. {
  7572. IconUrl = Ui.MapIcon.Headquarters,
  7573. Label = Util.RemoveSpecialCharacters(faction.Id),
  7574. X = TranslatePosition(area.ClaimCupboard.transform.position.x),
  7575. Z = TranslatePosition(area.ClaimCupboard.transform.position.z)
  7576. };
  7577. }
  7578.  
  7579. public static MapMarker ForMonument(MonumentInfo monument)
  7580. {
  7581. string iconUrl = GetIconForMonument(monument);
  7582. return new MapMarker
  7583. {
  7584. IconUrl = iconUrl,
  7585. Label = (iconUrl == Ui.MapIcon.Unknown) ? monument.name : null,
  7586. X = TranslatePosition(monument.transform.position.x),
  7587. Z = TranslatePosition(monument.transform.position.z)
  7588. };
  7589. }
  7590.  
  7591. public static MapMarker ForPin(Pin pin)
  7592. {
  7593. string iconUrl = GetIconForPin(pin);
  7594. return new MapMarker
  7595. {
  7596. IconUrl = iconUrl,
  7597. Label = pin.Name,
  7598. X = TranslatePosition(pin.Position.x),
  7599. Z = TranslatePosition(pin.Position.z)
  7600. };
  7601. }
  7602.  
  7603. static float TranslatePosition(float pos)
  7604. {
  7605. var mapSize = TerrainMeta.Size.x;
  7606. return (pos + mapSize / 2f) / mapSize;
  7607. }
  7608.  
  7609. static string GetIconForMonument(MonumentInfo monument)
  7610. {
  7611. if (monument.Type == MonumentType.Cave) return Ui.MapIcon.Cave;
  7612. if (monument.name.Contains("airfield")) return Ui.MapIcon.Airfield;
  7613. if (monument.name.Contains("bandit_town")) return Ui.MapIcon.BanditTown;
  7614. if (monument.name.Contains("compound")) return Ui.MapIcon.Compound;
  7615. if (monument.name.Contains("sphere_tank")) return Ui.MapIcon.Dome;
  7616. if (monument.name.Contains("harbor")) return Ui.MapIcon.Harbor;
  7617. if (monument.name.Contains("gas_station")) return Ui.MapIcon.GasStation;
  7618. if (monument.name.Contains("junkyard")) return Ui.MapIcon.Junkyard;
  7619. if (monument.name.Contains("launch_site")) return Ui.MapIcon.LaunchSite;
  7620. if (monument.name.Contains("lighthouse")) return Ui.MapIcon.Lighthouse;
  7621. if (monument.name.Contains("military_tunnel")) return Ui.MapIcon.MilitaryTunnel;
  7622. if (monument.name.Contains("warehouse")) return Ui.MapIcon.MiningOutpost;
  7623. if (monument.name.Contains("powerplant")) return Ui.MapIcon.PowerPlant;
  7624. if (monument.name.Contains("quarry")) return Ui.MapIcon.Quarry;
  7625. if (monument.name.Contains("satellite_dish")) return Ui.MapIcon.SatelliteDish;
  7626. if (monument.name.Contains("radtown_small_3")) return Ui.MapIcon.SewerBranch;
  7627. if (monument.name.Contains("power_sub")) return Ui.MapIcon.Substation;
  7628. if (monument.name.Contains("supermarket")) return Ui.MapIcon.Supermarket;
  7629. if (monument.name.Contains("trainyard")) return Ui.MapIcon.Trainyard;
  7630. if (monument.name.Contains("water_treatment_plant")) return Ui.MapIcon.WaterTreatmentPlant;
  7631. return Ui.MapIcon.Unknown;
  7632. }
  7633. }
  7634.  
  7635. static string GetIconForPin(Pin pin)
  7636. {
  7637. switch (pin.Type)
  7638. {
  7639. case PinType.Arena:
  7640. return Ui.MapIcon.Arena;
  7641. case PinType.Hotel:
  7642. return Ui.MapIcon.Hotel;
  7643. case PinType.Marina:
  7644. return Ui.MapIcon.Marina;
  7645. case PinType.Shop:
  7646. return Ui.MapIcon.Shop;
  7647. case PinType.Town:
  7648. return Ui.MapIcon.Town;
  7649. default:
  7650. return Ui.MapIcon.Unknown;
  7651. }
  7652. }
  7653. }
  7654. }
  7655.  
  7656. namespace Oxide.Plugins
  7657. {
  7658. public partial class Imperium
  7659. {
  7660. public static class Ui
  7661. {
  7662. public const string ImageBaseUrl = "http://assets.rustimperium.com/";
  7663. public const string MapOverlayImageUrl = "imperium://map-overlay.png";
  7664. public const string TransparentTexture = "assets/content/textures/generic/fulltransparent.tga";
  7665.  
  7666. public static class Element
  7667. {
  7668. public const string Hud = "Hud";
  7669. public const string HudPanelLeft = "Imperium.HudPanel.Top";
  7670. public const string HudPanelRight = "Imperium.HudPanel.Middle";
  7671. public const string HudPanelWarning = "Imperium.HudPanel.Warning";
  7672. public const string HudPanelText = "Imperium.HudPanel.Text";
  7673. public const string HudPanelIcon = "Imperium.HudPanel.Icon";
  7674. public const string Overlay = "Overlay";
  7675. public const string MapDialog = "Imperium.MapDialog";
  7676. public const string MapHeader = "Imperium.MapDialog.Header";
  7677. public const string MapHeaderTitle = "Imperium.MapDialog.Header.Title";
  7678. public const string MapHeaderCloseButton = "Imperium.MapDialog.Header.CloseButton";
  7679. public const string MapContainer = "Imperium.MapDialog.MapContainer";
  7680. public const string MapTerrainImage = "Imperium.MapDialog.MapTerrainImage";
  7681. public const string MapLayers = "Imperium.MapDialog.MapLayers";
  7682. public const string MapClaimsImage = "Imperium.MapDialog.MapLayers.ClaimsImage";
  7683. public const string MapMarkerIcon = "Imperium.MapDialog.MapLayers.MarkerIcon";
  7684. public const string MapMarkerLabel = "Imperium.MapDialog.MapLayers.MarkerLabel";
  7685. public const string MapSidebar = "Imperium.MapDialog.Sidebar";
  7686. public const string MapButton = "Imperium.MapDialog.Sidebar.Button";
  7687. public const string MapServerLogoImage = "Imperium.MapDialog.Sidebar.ServerLogo";
  7688. }
  7689.  
  7690. public static class HudIcon
  7691. {
  7692. public const string Badlands = ImageBaseUrl + "icons/hud/badlands.png";
  7693. public const string CargoPlaneIndicatorOn = ImageBaseUrl + "icons/hud/cargoplane-on.png";
  7694. public const string CargoPlaneIndicatorOff = ImageBaseUrl + "icons/hud/cargoplane-off.png";
  7695. public const string CargoShipIndicatorOn = ImageBaseUrl + "icons/hud/cargo-ship-on.png";
  7696. public const string CargoShipIndicatorOff = ImageBaseUrl + "icons/hud/cargo-ship-off.png";
  7697. public const string ChinookIndicatorOn = ImageBaseUrl + "icons/hud/chinook-on.png";
  7698. public const string ChinookIndicatorOff = ImageBaseUrl + "icons/hud/chinook-off.png";
  7699. public const string Claimed = ImageBaseUrl + "icons/hud/claimed.png";
  7700. public const string Clock = ImageBaseUrl + "icons/hud/clock.png";
  7701. public const string Debris = ImageBaseUrl + "icons/hud/debris.png";
  7702. public const string Defense = ImageBaseUrl + "icons/hud/defense.png";
  7703. public const string Harvest = ImageBaseUrl + "icons/hud/harvest.png";
  7704. public const string Headquarters = ImageBaseUrl + "icons/hud/headquarters.png";
  7705. public const string HelicopterIndicatorOn = ImageBaseUrl + "icons/hud/helicopter-on.png";
  7706. public const string HelicopterIndicatorOff = ImageBaseUrl + "icons/hud/helicopter-off.png";
  7707. public const string Monument = ImageBaseUrl + "icons/hud/monument.png";
  7708. public const string Players = ImageBaseUrl + "icons/hud/players.png";
  7709. public const string PvpMode = ImageBaseUrl + "icons/hud/pvp.png";
  7710. public const string Raid = ImageBaseUrl + "icons/hud/raid.png";
  7711. public const string Ruins = ImageBaseUrl + "icons/hud/ruins.png";
  7712. public const string Sleepers = ImageBaseUrl + "icons/hud/sleepers.png";
  7713. public const string SupplyDrop = ImageBaseUrl + "icons/hud/supplydrop.png";
  7714. public const string Taxes = ImageBaseUrl + "icons/hud/taxes.png";
  7715. public const string Warning = ImageBaseUrl + "icons/hud/warning.png";
  7716. public const string WarZone = ImageBaseUrl + "icons/hud/warzone.png";
  7717. public const string Wilderness = ImageBaseUrl + "icons/hud/wilderness.png";
  7718. }
  7719.  
  7720. public static class MapIcon
  7721. {
  7722. public const string Airfield = ImageBaseUrl + "icons/map/airfield.png";
  7723. public const string Arena = ImageBaseUrl + "icons/map/arena.png";
  7724. public const string BanditTown = ImageBaseUrl + "icons/map/bandit-town.png";
  7725. public const string Cave = ImageBaseUrl + "icons/map/cave.png";
  7726. public const string Compound = ImageBaseUrl + "icons/map/compound.png";
  7727. public const string Dome = ImageBaseUrl + "icons/map/dome.png";
  7728. public const string GasStation = ImageBaseUrl + "icons/map/gas-station.png";
  7729. public const string Harbor = ImageBaseUrl + "icons/map/harbor.png";
  7730. public const string Headquarters = ImageBaseUrl + "icons/map/headquarters.png";
  7731. public const string Hotel = ImageBaseUrl + "icons/map/hotel.png";
  7732. public const string Junkyard = ImageBaseUrl + "icons/map/junkyard.png";
  7733. public const string LaunchSite = ImageBaseUrl + "icons/map/launch-site.png";
  7734. public const string Lighthouse = ImageBaseUrl + "icons/map/lighthouse.png";
  7735. public const string Marina = ImageBaseUrl + "icons/map/marina.png";
  7736. public const string MilitaryTunnel = ImageBaseUrl + "icons/map/military-tunnel.png";
  7737. public const string MiningOutpost = ImageBaseUrl + "icons/map/mining-outpost.png";
  7738. public const string Player = ImageBaseUrl + "icons/map/player.png";
  7739. public const string PowerPlant = ImageBaseUrl + "icons/map/power-plant.png";
  7740. public const string Quarry = ImageBaseUrl + "icons/map/quarry.png";
  7741. public const string SatelliteDish = ImageBaseUrl + "icons/map/satellite-dish.png";
  7742. public const string SewerBranch = ImageBaseUrl + "icons/map/sewer-branch.png";
  7743. public const string Shop = ImageBaseUrl + "icons/map/shop.png";
  7744. public const string Substation = ImageBaseUrl + "icons/map/substation.png";
  7745. public const string Supermarket = ImageBaseUrl + "icons/map/supermarket.png";
  7746. public const string Town = ImageBaseUrl + "icons/map/town.png";
  7747. public const string Trainyard = ImageBaseUrl + "icons/map/trainyard.png";
  7748. public const string Unknown = ImageBaseUrl + "icons/map/unknown.png";
  7749. public const string WaterTreatmentPlant = ImageBaseUrl + "icons/map/water-treatment-plant.png";
  7750. }
  7751. }
  7752. }
  7753. }
  7754.  
  7755. namespace Oxide.Plugins
  7756. {
  7757. using Oxide.Game.Rust.Cui;
  7758. using System;
  7759. using System.Linq;
  7760. using UnityEngine;
  7761.  
  7762. public partial class Imperium
  7763. {
  7764. class UserHud
  7765. {
  7766. const float IconSize = 0.0775f;
  7767.  
  7768. static class PanelColor
  7769. {
  7770. //public const string BackgroundNormal = "1 0.95 0.875 0.075";
  7771. public const string BackgroundNormal = "0 0 0 0.0";
  7772. public const string BackgroundDanger = "0.0 0.0 0.0 0.0";
  7773. public const string BackgroundSafe = "0.0 0.0 0.0 0.0";
  7774. public const string TextNormal = "0.0 0.0 1.0 1";
  7775. public const string TextDanger = "1.0 0.0 0.0 1";
  7776. public const string TextSafe = "0.0 1.0 0.0 1";
  7777. }
  7778.  
  7779. public User User { get; }
  7780. public bool IsDisabled { get; set; }
  7781.  
  7782. public UserHud(User user)
  7783. {
  7784. User = user;
  7785. }
  7786.  
  7787. public void Show()
  7788. {
  7789. CuiHelper.AddUi(User.Player, Build());
  7790. }
  7791.  
  7792. public void Hide()
  7793. {
  7794. CuiHelper.DestroyUi(User.Player, Ui.Element.HudPanelLeft);
  7795. CuiHelper.DestroyUi(User.Player, Ui.Element.HudPanelRight);
  7796. CuiHelper.DestroyUi(User.Player, Ui.Element.HudPanelWarning);
  7797. }
  7798.  
  7799. public void Toggle()
  7800. {
  7801. if (IsDisabled)
  7802. {
  7803. IsDisabled = false;
  7804. Show();
  7805. }
  7806. else
  7807. {
  7808. IsDisabled = true;
  7809. Hide();
  7810. }
  7811. }
  7812.  
  7813. public void Refresh()
  7814. {
  7815. if (IsDisabled)
  7816. return;
  7817.  
  7818. Hide();
  7819. Show();
  7820. }
  7821.  
  7822. CuiElementContainer Build()
  7823. {
  7824. var container = new CuiElementContainer();
  7825.  
  7826. Area area = User.CurrentArea;
  7827.  
  7828. container.Add(new CuiPanel
  7829. {
  7830. Image = {Color = GetLeftPanelBackgroundColor()},
  7831. RectTransform = {AnchorMin = "0.006 0.956", AnchorMax = "0.241 0.989"}
  7832. }, Ui.Element.Hud, Ui.Element.HudPanelLeft);
  7833.  
  7834. container.Add(new CuiPanel
  7835. {
  7836. Image = {Color = PanelColor.BackgroundNormal},
  7837. RectTransform = {AnchorMin = "0.759 0.956", AnchorMax = "0.759 0.956"}
  7838. }, Ui.Element.Hud, Ui.Element.HudPanelRight);
  7839.  
  7840. AddWidget(container, Ui.Element.HudPanelLeft, GetLocationIcon(), GetLeftPanelTextColor(),
  7841. GetLocationDescription());
  7842.  
  7843. if (area != null)
  7844. {
  7845. if (area.Type == AreaType.Badlands)
  7846. {
  7847. string harvestBonus = String.Format("+{0}%", Instance.Options.Taxes.BadlandsGatherBonus * 100);
  7848. AddWidget(container, Ui.Element.HudPanelLeft, Ui.HudIcon.Harvest, GetLeftPanelTextColor(),
  7849. harvestBonus, 0.77f);
  7850. }
  7851. else if (area.IsWarZone)
  7852. {
  7853. string defensiveBonus = String.Format("+{0}%", area.GetDefensiveBonus() * 100);
  7854. AddWidget(container, Ui.Element.HudPanelLeft, Ui.HudIcon.Defense, GetLeftPanelTextColor(),
  7855. defensiveBonus, 0.77f);
  7856. }
  7857. else if (area.IsTaxableClaim)
  7858. {
  7859. string taxRate = String.Format("{0}%", area.GetTaxRate() * 100);
  7860. AddWidget(container, Ui.Element.HudPanelLeft, Ui.HudIcon.Taxes, GetLeftPanelTextColor(),
  7861. taxRate, 0.78f);
  7862. }
  7863. }
  7864.  
  7865.  
  7866. bool claimUpkeepPastDue = Instance.Options.Upkeep.Enabled && User.Faction != null &&
  7867. User.Faction.IsUpkeepPastDue;
  7868. if (User.IsInPvpMode || claimUpkeepPastDue)
  7869. {
  7870. container.Add(new CuiPanel
  7871. {
  7872. Image = {Color = PanelColor.BackgroundDanger},
  7873. RectTransform = {AnchorMin = "0.759 0.911", AnchorMax = "0.994 0.944"}
  7874. }, Ui.Element.Hud, Ui.Element.HudPanelWarning);
  7875.  
  7876. if (true || claimUpkeepPastDue)
  7877. AddWidget(container, Ui.Element.HudPanelWarning, Ui.HudIcon.Ruins, PanelColor.TextDanger,
  7878. "Claim upkeep past due!");
  7879. else
  7880. AddWidget(container, Ui.Element.HudPanelWarning, Ui.HudIcon.PvpMode, PanelColor.TextDanger,
  7881. "PVP mode enabled");
  7882. }
  7883.  
  7884. return container;
  7885. }
  7886.  
  7887. string GetRightPanelBackgroundColor()
  7888. {
  7889. if (User.IsInPvpMode)
  7890. return PanelColor.BackgroundDanger;
  7891. else
  7892. return PanelColor.BackgroundNormal;
  7893. }
  7894.  
  7895. string GetRightPanelTextColor()
  7896. {
  7897. if (User.IsInPvpMode)
  7898. return PanelColor.TextDanger;
  7899. else
  7900. return PanelColor.TextNormal;
  7901. }
  7902.  
  7903. string GetLocationIcon()
  7904. {
  7905. Zone zone = User.CurrentZones.FirstOrDefault();
  7906.  
  7907. if (zone != null)
  7908. {
  7909. switch (zone.Type)
  7910. {
  7911. case ZoneType.SupplyDrop:
  7912. return Ui.HudIcon.SupplyDrop;
  7913. case ZoneType.Debris:
  7914. return Ui.HudIcon.Debris;
  7915. case ZoneType.Monument:
  7916. return Ui.HudIcon.Monument;
  7917. case ZoneType.Raid:
  7918. return Ui.HudIcon.Raid;
  7919. }
  7920. }
  7921.  
  7922. Area area = User.CurrentArea;
  7923.  
  7924. if (area == null)
  7925. {
  7926. if (Instance.Options.Pvp.AllowedInDeepWater)
  7927. return Ui.HudIcon.Monument;
  7928. else
  7929. return Ui.HudIcon.Wilderness;
  7930. }
  7931.  
  7932. if (area.IsWarZone)
  7933. return Ui.HudIcon.WarZone;
  7934.  
  7935. switch (area.Type)
  7936. {
  7937. case AreaType.Badlands:
  7938. return Ui.HudIcon.Badlands;
  7939. case AreaType.Claimed:
  7940. return Ui.HudIcon.Claimed;
  7941. case AreaType.Headquarters:
  7942. return Ui.HudIcon.Headquarters;
  7943. default:
  7944. return Ui.HudIcon.Wilderness;
  7945. }
  7946. }
  7947.  
  7948. string GetLocationDescription()
  7949. {
  7950. Area area = User.CurrentArea;
  7951. Zone zone = User.CurrentZones.FirstOrDefault();
  7952.  
  7953. if (zone != null)
  7954. {
  7955. if (area == null)
  7956. return zone.Name;
  7957. else
  7958. return $"{area.Id}: {zone.Name}";
  7959. }
  7960.  
  7961. if (area == null)
  7962. return "The Great Unknown";
  7963.  
  7964. switch (area.Type)
  7965. {
  7966. case AreaType.Badlands:
  7967. return $"{area.Id}: Badlands";
  7968. case AreaType.Claimed:
  7969. if (!String.IsNullOrEmpty(area.Name))
  7970. return $"{area.Id}: {area.Name} ({area.FactionId})";
  7971. else
  7972. return $"{area.Id}: {area.FactionId} Territory";
  7973. case AreaType.Headquarters:
  7974. if (!String.IsNullOrEmpty(area.Name))
  7975. return $"{area.Id}: {area.Name} ({area.FactionId} HQ)";
  7976. else
  7977. return $"{area.Id}: {area.FactionId} Headquarters";
  7978. default:
  7979. return $"{area.Id}: Wilderness";
  7980. }
  7981. }
  7982.  
  7983. string GetLeftPanelBackgroundColor()
  7984. {
  7985. if (User.CurrentZones.Count > 0)
  7986. return PanelColor.BackgroundDanger;
  7987.  
  7988. Area area = User.CurrentArea;
  7989.  
  7990. if (area == null)
  7991. {
  7992. if (Instance.Options.Pvp.AllowedInDeepWater)
  7993. return PanelColor.BackgroundDanger;
  7994. else
  7995. return PanelColor.BackgroundNormal;
  7996. }
  7997.  
  7998. if (area.IsWarZone)
  7999. return PanelColor.BackgroundDanger;
  8000.  
  8001. switch (area.Type)
  8002. {
  8003. case AreaType.Badlands:
  8004. return Instance.Options.Pvp.AllowedInBadlands
  8005. ? PanelColor.BackgroundDanger
  8006. : PanelColor.BackgroundNormal;
  8007. case AreaType.Claimed:
  8008. case AreaType.Headquarters:
  8009. return Instance.Options.Pvp.AllowedInClaimedLand
  8010. ? PanelColor.BackgroundDanger
  8011. : PanelColor.BackgroundNormal;
  8012. default:
  8013. return Instance.Options.Pvp.AllowedInWilderness
  8014. ? PanelColor.BackgroundDanger
  8015. : PanelColor.BackgroundNormal;
  8016. }
  8017. }
  8018.  
  8019. string GetLeftPanelTextColor()
  8020. {
  8021. if (User.CurrentZones.Count > 0)
  8022. return PanelColor.TextDanger;
  8023.  
  8024. Area area = User.CurrentArea;
  8025.  
  8026. if (area == null)
  8027. {
  8028. if (Instance.Options.Pvp.AllowedInDeepWater)
  8029. return PanelColor.TextDanger;
  8030. else
  8031. return PanelColor.TextNormal;
  8032. }
  8033.  
  8034. if (area.IsWarZone || area.Type == AreaType.Badlands)
  8035. return PanelColor.TextDanger;
  8036. else
  8037. return PanelColor.TextNormal;
  8038. }
  8039.  
  8040. void AddWidget(CuiElementContainer container, string parent, string iconName, string textColor, string text,
  8041. float left = 0f)
  8042. {
  8043. var guid = Guid.NewGuid().ToString();
  8044.  
  8045. container.Add(new CuiElement
  8046. {
  8047. Name = Ui.Element.HudPanelIcon + guid,
  8048. Parent = parent,
  8049. Components =
  8050. {
  8051. Instance.Hud.CreateImageComponent(iconName),
  8052. new CuiRectTransformComponent
  8053. {
  8054. AnchorMin = $"{left} {IconSize}",
  8055. AnchorMax = $"{left + IconSize} {1 - IconSize}",
  8056. OffsetMin = "0 -18",
  8057. OffsetMax = "0 -18"
  8058. }
  8059. }
  8060. });
  8061.  
  8062. container.Add(new CuiLabel
  8063. {
  8064. Text =
  8065. {
  8066. Text = text,
  8067. Color = textColor,
  8068. FontSize = 14,
  8069. Align = TextAnchor.MiddleLeft,
  8070. },
  8071. RectTransform =
  8072. {
  8073. AnchorMin = $"{left + IconSize} 0",
  8074. AnchorMax = "1 1",
  8075. OffsetMin = "0 -16",
  8076. OffsetMax = "0 -16"
  8077. }
  8078. }, parent, Ui.Element.HudPanelText + guid);
  8079. }
  8080.  
  8081. void AddWidget(CuiElementContainer container, string parent, string iconName, float left = 0f)
  8082. {
  8083. var guid = Guid.NewGuid().ToString();
  8084.  
  8085. container.Add(new CuiElement
  8086. {
  8087. Name = Ui.Element.HudPanelIcon + guid,
  8088. Parent = parent,
  8089. Components =
  8090. {
  8091. Instance.Hud.CreateImageComponent(iconName),
  8092. new CuiRectTransformComponent
  8093. {
  8094. AnchorMin = "0 0",
  8095. AnchorMax = "0 0",
  8096. OffsetMin = "0 0",
  8097. OffsetMax = "0 0"
  8098. }
  8099. }
  8100. });
  8101. }
  8102. }
  8103. }
  8104. }
  8105.  
  8106. namespace Oxide.Plugins
  8107. {
  8108. using System;
  8109. using Oxide.Game.Rust.Cui;
  8110. using UnityEngine;
  8111. using System.Linq;
  8112.  
  8113. public partial class Imperium
  8114. {
  8115. class UserMap
  8116. {
  8117. public User User { get; }
  8118. public bool IsVisible { get; private set; }
  8119.  
  8120. public UserMap(User user)
  8121. {
  8122. User = user;
  8123. }
  8124.  
  8125. public void Show()
  8126. {
  8127. CuiHelper.AddUi(User.Player, BuildDialog());
  8128. CuiHelper.AddUi(User.Player, BuildSidebar());
  8129. CuiHelper.AddUi(User.Player, BuildMapLayers());
  8130. IsVisible = true;
  8131. }
  8132.  
  8133. public void Hide()
  8134. {
  8135. CuiHelper.DestroyUi(User.Player, Ui.Element.MapDialog);
  8136. IsVisible = false;
  8137. }
  8138.  
  8139. public void Toggle()
  8140. {
  8141. if (IsVisible)
  8142. Hide();
  8143. else
  8144. Show();
  8145. }
  8146.  
  8147. public void Refresh()
  8148. {
  8149. if (IsVisible)
  8150. {
  8151. CuiHelper.DestroyUi(User.Player, Ui.Element.MapSidebar);
  8152. CuiHelper.DestroyUi(User.Player, Ui.Element.MapLayers);
  8153. CuiHelper.AddUi(User.Player, BuildSidebar());
  8154. CuiHelper.AddUi(User.Player, BuildMapLayers());
  8155. }
  8156. }
  8157.  
  8158. // --- Dialog ---
  8159.  
  8160. CuiElementContainer BuildDialog()
  8161. {
  8162. var container = new CuiElementContainer();
  8163.  
  8164. container.Add(new CuiPanel
  8165. {
  8166. Image = {Color = "0 0 0 0.0"},
  8167. RectTransform = {AnchorMin = "0.164 0.014", AnchorMax = "0.836 0.986"},
  8168. CursorEnabled = true
  8169. }, Ui.Element.Overlay, Ui.Element.MapDialog);
  8170.  
  8171. container.Add(new CuiPanel
  8172. {
  8173. Image = {Color = "0 0 0 0"},
  8174. RectTransform = {AnchorMin = "0.012 0.014", AnchorMax = "0.774 0.951"}
  8175. }, Ui.Element.MapDialog, Ui.Element.MapContainer);
  8176.  
  8177. AddDialogHeader(container);
  8178. AddMapTerrainImage(container);
  8179.  
  8180. return container;
  8181. }
  8182.  
  8183. void AddDialogHeader(CuiElementContainer container)
  8184. {
  8185. container.Add(new CuiPanel
  8186. {
  8187. Image = {Color = "0 0 0 1"},
  8188. RectTransform = {AnchorMin = "0 0.966", AnchorMax = "0.999 0.999"}
  8189. }, Ui.Element.MapDialog, Ui.Element.MapHeader);
  8190.  
  8191. container.Add(new CuiLabel
  8192. {
  8193. Text = {Text = ConVar.Server.hostname, FontSize = 13, Align = TextAnchor.MiddleLeft, FadeIn = 0},
  8194. RectTransform = {AnchorMin = "0.012 0.025", AnchorMax = "0.099 0.917"}
  8195. }, Ui.Element.MapHeader, Ui.Element.MapHeaderTitle);
  8196.  
  8197. container.Add(new CuiButton
  8198. {
  8199. Text = {Text = "X", FontSize = 13, Align = TextAnchor.MiddleCenter},
  8200. Button = {Color = "0 0 0 0", Command = "imperium.map.toggle", FadeIn = 0},
  8201. RectTransform = {AnchorMin = "0.972 0.083", AnchorMax = "0.995 0.917"}
  8202. }, Ui.Element.MapHeader, Ui.Element.MapHeaderCloseButton);
  8203. }
  8204.  
  8205. void AddMapTerrainImage(CuiElementContainer container)
  8206. {
  8207. CuiRawImageComponent image = Instance.Hud.CreateImageComponent(Instance.Options.Map.ImageUrl);
  8208.  
  8209. // If the image hasn't been loaded, just display a black box so we don't cause an RPC AddUI crash.
  8210. if (image == null)
  8211. image = new CuiRawImageComponent {Color = "0 0 0 1"};
  8212.  
  8213. container.Add(new CuiElement
  8214. {
  8215. Name = Ui.Element.MapTerrainImage,
  8216. Parent = Ui.Element.MapContainer,
  8217. Components =
  8218. {
  8219. image,
  8220. new CuiRectTransformComponent {AnchorMin = "0 0", AnchorMax = "1 1"}
  8221. }
  8222. });
  8223. }
  8224.  
  8225. // --- Sidebar ---
  8226.  
  8227. CuiElementContainer BuildSidebar()
  8228. {
  8229. var container = new CuiElementContainer();
  8230.  
  8231. container.Add(new CuiPanel
  8232. {
  8233. Image = {Color = "0 0 0 0"},
  8234. RectTransform = {AnchorMin = "0.786 0.014", AnchorMax = "0.988 0.951"}
  8235. }, Ui.Element.MapDialog, Ui.Element.MapSidebar);
  8236.  
  8237. AddLayerToggleButtons(container);
  8238. AddServerLogo(container);
  8239.  
  8240. return container;
  8241. }
  8242.  
  8243. void AddLayerToggleButtons(CuiElementContainer container)
  8244. {
  8245. container.Add(new CuiButton
  8246. {
  8247. Text = {Text = "Land Claims", FontSize = 14, Align = TextAnchor.MiddleCenter},
  8248. Button =
  8249. {
  8250. Color = GetButtonColor(UserMapLayer.Claims), Command = "imperium.map.togglelayer claims",
  8251. FadeIn = 0
  8252. },
  8253. RectTransform = {AnchorMin = "0 0.924", AnchorMax = "1 1"}
  8254. }, Ui.Element.MapSidebar, Ui.Element.MapButton + Guid.NewGuid().ToString());
  8255.  
  8256. container.Add(new CuiButton
  8257. {
  8258. Text = {Text = "Faction Headquarters", FontSize = 14, Align = TextAnchor.MiddleCenter},
  8259. Button =
  8260. {
  8261. Color = GetButtonColor(UserMapLayer.Headquarters),
  8262. Command = "imperium.map.togglelayer headquarters", FadeIn = 0
  8263. },
  8264. RectTransform = {AnchorMin = "0 0.832", AnchorMax = "1 0.909"}
  8265. }, Ui.Element.MapSidebar, Ui.Element.MapButton + Guid.NewGuid().ToString());
  8266.  
  8267. container.Add(new CuiButton
  8268. {
  8269. Text = {Text = "Monuments", FontSize = 14, Align = TextAnchor.MiddleCenter},
  8270. Button =
  8271. {
  8272. Color = GetButtonColor(UserMapLayer.Monuments),
  8273. Command = "imperium.map.togglelayer monuments", FadeIn = 0
  8274. },
  8275. RectTransform = {AnchorMin = "0 0.741", AnchorMax = "1 0.817"}
  8276. }, Ui.Element.MapSidebar, Ui.Element.MapButton + Guid.NewGuid().ToString());
  8277.  
  8278. container.Add(new CuiButton
  8279. {
  8280. Text = {Text = "Pins", FontSize = 14, Align = TextAnchor.MiddleCenter},
  8281. Button =
  8282. {
  8283. Color = GetButtonColor(UserMapLayer.Pins), Command = "imperium.map.togglelayer pins",
  8284. FadeIn = 0
  8285. },
  8286. RectTransform = {AnchorMin = "0 0.649", AnchorMax = "1 0.726"}
  8287. }, Ui.Element.MapSidebar, Ui.Element.MapButton + Guid.NewGuid().ToString());
  8288. }
  8289.  
  8290. void AddServerLogo(CuiElementContainer container)
  8291. {
  8292. CuiRawImageComponent image = Instance.Hud.CreateImageComponent(Instance.Options.Map.ServerLogoUrl);
  8293.  
  8294. // If the image hasn't been loaded, just display a black box so we don't cause an RPC AddUI crash.
  8295. if (image == null)
  8296. image = new CuiRawImageComponent {Color = "0 0 0 1"};
  8297.  
  8298. container.Add(new CuiElement
  8299. {
  8300. Name = Ui.Element.MapServerLogoImage,
  8301. Parent = Ui.Element.MapSidebar,
  8302. Components =
  8303. {
  8304. image,
  8305. new CuiRectTransformComponent {AnchorMin = "0 0", AnchorMax = "1 0.133"}
  8306. }
  8307. });
  8308. }
  8309.  
  8310. // --- Map Layers ---
  8311.  
  8312. CuiElementContainer BuildMapLayers()
  8313. {
  8314. var container = new CuiElementContainer();
  8315.  
  8316. container.Add(new CuiPanel
  8317. {
  8318. Image = {Color = "0 0 0 0"},
  8319. RectTransform = {AnchorMin = "0 0", AnchorMax = "1 1"}
  8320. }, Ui.Element.MapContainer, Ui.Element.MapLayers);
  8321.  
  8322. if (User.Preferences.IsMapLayerVisible(UserMapLayer.Claims))
  8323. AddClaimsLayer(container);
  8324.  
  8325. if (User.Preferences.IsMapLayerVisible(UserMapLayer.Monuments))
  8326. AddMonumentsLayer(container);
  8327.  
  8328. if (User.Preferences.IsMapLayerVisible(UserMapLayer.Headquarters))
  8329. AddHeadquartersLayer(container);
  8330.  
  8331. if (User.Preferences.IsMapLayerVisible(UserMapLayer.Pins))
  8332. AddPinsLayer(container);
  8333.  
  8334. AddMarker(container, MapMarker.ForUser(User));
  8335.  
  8336. return container;
  8337. }
  8338.  
  8339. void AddClaimsLayer(CuiElementContainer container)
  8340. {
  8341. CuiRawImageComponent image = Instance.Hud.CreateImageComponent(Ui.MapOverlayImageUrl);
  8342.  
  8343. // If the claims overlay hasn't been generated yet, just display a black box so we don't cause an RPC AddUI crash.
  8344. if (image == null)
  8345. image = new CuiRawImageComponent {Color = "0 0 0 1"};
  8346.  
  8347. container.Add(new CuiElement
  8348. {
  8349. Name = Ui.Element.MapClaimsImage,
  8350. Parent = Ui.Element.MapLayers,
  8351. Components =
  8352. {
  8353. image,
  8354. new CuiRectTransformComponent {AnchorMin = "0 0", AnchorMax = "1 1"}
  8355. }
  8356. });
  8357. }
  8358.  
  8359. void AddMonumentsLayer(CuiElementContainer container)
  8360. {
  8361. var monuments = UnityEngine.Object.FindObjectsOfType<MonumentInfo>();
  8362. foreach (MonumentInfo monument in monuments.Where(ShowMonumentOnMap))
  8363. AddMarker(container, MapMarker.ForMonument(monument));
  8364. }
  8365.  
  8366. void AddHeadquartersLayer(CuiElementContainer container)
  8367. {
  8368. foreach (Area area in Instance.Areas.GetAllByType(AreaType.Headquarters))
  8369. {
  8370. var faction = Instance.Factions.Get(area.FactionId);
  8371. AddMarker(container, MapMarker.ForHeadquarters(area, faction));
  8372. }
  8373. }
  8374.  
  8375. void AddPinsLayer(CuiElementContainer container)
  8376. {
  8377. foreach (Pin pin in Instance.Pins.GetAll())
  8378. AddMarker(container, MapMarker.ForPin(pin));
  8379. }
  8380.  
  8381. void AddMarker(CuiElementContainer container, MapMarker marker, float iconSize = 0.01f)
  8382. {
  8383. container.Add(new CuiElement
  8384. {
  8385. Name = Ui.Element.MapMarkerIcon + Guid.NewGuid().ToString(),
  8386. Parent = Ui.Element.MapLayers,
  8387. Components =
  8388. {
  8389. Instance.Hud.CreateImageComponent(marker.IconUrl),
  8390. new CuiRectTransformComponent
  8391. {
  8392. AnchorMin = $"{marker.X - iconSize} {marker.Z - iconSize}",
  8393. AnchorMax = $"{marker.X + iconSize} {marker.Z + iconSize}"
  8394. }
  8395. }
  8396. });
  8397.  
  8398. if (!String.IsNullOrEmpty(marker.Label))
  8399. {
  8400. container.Add(new CuiLabel
  8401. {
  8402. Text = {Text = marker.Label, FontSize = 8, Align = TextAnchor.MiddleCenter, FadeIn = 0},
  8403. RectTransform =
  8404. {
  8405. AnchorMin = $"{marker.X - 0.1} {marker.Z - iconSize - 0.0175}",
  8406. AnchorMax = $"{marker.X + 0.1} {marker.Z - iconSize}"
  8407. }
  8408. }, Ui.Element.MapLayers, Ui.Element.MapMarkerLabel + Guid.NewGuid().ToString());
  8409. }
  8410. }
  8411.  
  8412. bool ShowMonumentOnMap(MonumentInfo monument)
  8413. {
  8414. return monument.Type != MonumentType.Cave
  8415. && !monument.name.Contains("power_sub")
  8416. && !monument.name.Contains("water_well")
  8417. && !monument.name.Contains("swamp")
  8418. && !monument.name.Contains("ice_lake");
  8419. }
  8420.  
  8421. string GetButtonColor(UserMapLayer layer)
  8422. {
  8423. if (User.Preferences.IsMapLayerVisible(layer))
  8424. return "0 0 0 1";
  8425. else
  8426. return "0.33 0.33 0.33 1";
  8427. }
  8428. }
  8429. }
  8430. }
Advertisement
Add Comment
Please, Sign In to add comment