ConstructionMenuPresenter.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  1. using System.Linq;
  2. using System.Numerics;
  3. using Content.Client.Stylesheets;
  4. using Content.Client.UserInterface.Systems.MenuBar.Widgets;
  5. using Content.Shared.Construction.Prototypes;
  6. using Content.Shared.Whitelist;
  7. using Robust.Client.GameObjects;
  8. using Robust.Client.Graphics;
  9. using Robust.Client.Placement;
  10. using Robust.Client.Player;
  11. using Robust.Client.UserInterface;
  12. using Robust.Client.UserInterface.Controls;
  13. using Robust.Client.Utility;
  14. using Robust.Shared.Enums;
  15. using Robust.Shared.Prototypes;
  16. using static Robust.Client.UserInterface.Controls.BaseButton;
  17. using Robust.Shared.Map;
  18. using Content.Shared.Civ14.CivResearch;
  19. namespace Content.Client.Construction.UI
  20. {
  21. /// <summary>
  22. /// This class presents the Construction/Crafting UI to the client, linking the <see cref="ConstructionSystem" /> with the
  23. /// model. This is where the bulk of UI work is done, either calling functions in the model to change state, or collecting
  24. /// data out of the model to *present* to the screen though the UI framework.
  25. /// </summary>
  26. internal sealed class ConstructionMenuPresenter : IDisposable
  27. {
  28. [Dependency] private readonly EntityManager _entManager = default!;
  29. [Dependency] private readonly IEntitySystemManager _systemManager = default!;
  30. [Dependency] private readonly IPrototypeManager _prototypeManager = default!;
  31. [Dependency] private readonly IPlacementManager _placementManager = default!;
  32. [Dependency] private readonly IUserInterfaceManager _uiManager = default!;
  33. [Dependency] private readonly IPlayerManager _playerManager = default!;
  34. [Dependency] private readonly IMapManager _mapManager = default!;
  35. [Dependency] private readonly ILogManager _logManager = default!;
  36. private ISawmill _sawmill = default!;
  37. private readonly IConstructionMenuView _constructionView;
  38. private readonly EntityWhitelistSystem _whitelistSystem;
  39. private readonly SpriteSystem _spriteSystem;
  40. private ConstructionSystem? _constructionSystem;
  41. private ConstructionPrototype? _selected;
  42. private List<ConstructionPrototype> _favoritedRecipes = [];
  43. private Dictionary<string, TextureButton> _recipeButtons = new();
  44. private string _selectedCategory = string.Empty;
  45. private string _favoriteCatName = "construction-category-favorites";
  46. private string _forAllCategoryName = "construction-category-all";
  47. private bool CraftingAvailable
  48. {
  49. get => _uiManager.GetActiveUIWidget<GameTopMenuBar>().CraftingButton.Visible;
  50. set
  51. {
  52. _uiManager.GetActiveUIWidget<GameTopMenuBar>().CraftingButton.Visible = value;
  53. if (!value)
  54. _constructionView.Close();
  55. }
  56. }
  57. /// <summary>
  58. /// Does the window have focus? If the window is closed, this will always return false.
  59. /// </summary>
  60. private bool IsAtFront => _constructionView.IsOpen && _constructionView.IsAtFront();
  61. private bool WindowOpen
  62. {
  63. get => _constructionView.IsOpen;
  64. set
  65. {
  66. if (value && CraftingAvailable)
  67. {
  68. if (_constructionView.IsOpen)
  69. _constructionView.MoveToFront();
  70. else
  71. _constructionView.OpenCentered();
  72. if (_selected != null)
  73. PopulateInfo(_selected);
  74. }
  75. else
  76. _constructionView.Close();
  77. }
  78. }
  79. /// <summary>
  80. /// Constructs a new instance of <see cref="ConstructionMenuPresenter" />.
  81. /// <summary>
  82. /// Initializes the ConstructionMenuPresenter, injecting dependencies, setting up the construction UI, binding event handlers, and populating initial categories and recipes.
  83. /// </summary>
  84. public ConstructionMenuPresenter()
  85. {
  86. // This is a lot easier than a factory
  87. IoCManager.InjectDependencies(this);
  88. _constructionView = new ConstructionMenu();
  89. _whitelistSystem = _entManager.System<EntityWhitelistSystem>();
  90. _spriteSystem = _entManager.System<SpriteSystem>();
  91. // This is required so that if we load after the system is initialized, we can bind to it immediately
  92. if (_systemManager.TryGetEntitySystem<ConstructionSystem>(out var constructionSystem))
  93. SystemBindingChanged(constructionSystem);
  94. _systemManager.SystemLoaded += OnSystemLoaded;
  95. _systemManager.SystemUnloaded += OnSystemUnloaded;
  96. _placementManager.PlacementChanged += OnPlacementChanged;
  97. _constructionView.OnClose += () => _uiManager.GetActiveUIWidget<GameTopMenuBar>().CraftingButton.Pressed = false;
  98. _constructionView.ClearAllGhosts += (_, _) => _constructionSystem?.ClearAllGhosts();
  99. _constructionView.PopulateRecipes += OnViewPopulateRecipes;
  100. _constructionView.RecipeSelected += OnViewRecipeSelected;
  101. _constructionView.BuildButtonToggled += (_, b) => BuildButtonToggled(b);
  102. _constructionView.EraseButtonToggled += (_, b) =>
  103. {
  104. if (_constructionSystem is null) return;
  105. if (b) _placementManager.Clear();
  106. _placementManager.ToggleEraserHijacked(new ConstructionPlacementHijack(_constructionSystem, null));
  107. _constructionView.EraseButtonPressed = b;
  108. };
  109. _constructionView.RecipeFavorited += (_, _) => OnViewFavoriteRecipe();
  110. PopulateCategories();
  111. OnViewPopulateRecipes(_constructionView, (string.Empty, string.Empty));
  112. }
  113. public void OnHudCraftingButtonToggled(ButtonToggledEventArgs args)
  114. {
  115. WindowOpen = args.Pressed;
  116. }
  117. /// <inheritdoc />
  118. public void Dispose()
  119. {
  120. _constructionView.Dispose();
  121. SystemBindingChanged(null);
  122. _systemManager.SystemLoaded -= OnSystemLoaded;
  123. _systemManager.SystemUnloaded -= OnSystemUnloaded;
  124. _placementManager.PlacementChanged -= OnPlacementChanged;
  125. }
  126. private void OnPlacementChanged(object? sender, EventArgs e)
  127. {
  128. _constructionView.ResetPlacement();
  129. }
  130. /// <summary>
  131. /// Handles selection of a construction recipe from the UI, updating the selected recipe and displaying its details.
  132. /// </summary>
  133. private void OnViewRecipeSelected(object? sender, ItemList.Item? item)
  134. {
  135. if (item is null)
  136. {
  137. _selected = null;
  138. _constructionView.ClearRecipeInfo();
  139. return;
  140. }
  141. _selected = (ConstructionPrototype)item.Metadata!;
  142. if (_placementManager.IsActive && !_placementManager.Eraser) UpdateGhostPlacement();
  143. PopulateInfo(_selected);
  144. }
  145. private void OnGridViewRecipeSelected(object? sender, ConstructionPrototype? recipe)
  146. {
  147. if (recipe is null)
  148. {
  149. _selected = null;
  150. _constructionView.ClearRecipeInfo();
  151. return;
  152. }
  153. _selected = recipe;
  154. if (_placementManager.IsActive && !_placementManager.Eraser) UpdateGhostPlacement();
  155. PopulateInfo(_selected);
  156. }
  157. /// <summary>
  158. /// Populates the construction recipe list or grid in the UI based on the current search term and selected category, filtering recipes by visibility, player eligibility, whitelist, and research age.
  159. /// </summary>
  160. /// <param name="sender">The event sender (unused).</param>
  161. /// <param name="args">A tuple containing the search string and selected category.</param>
  162. private void OnViewPopulateRecipes(object? sender, (string search, string category) args)
  163. {
  164. _sawmill = _logManager.GetSawmill("craftmenu");
  165. var (search, category) = args;
  166. var recipes = new List<ConstructionPrototype>();
  167. var isEmptyCategory = string.IsNullOrEmpty(category) || category == _forAllCategoryName;
  168. if (isEmptyCategory)
  169. _selectedCategory = string.Empty;
  170. else
  171. _selectedCategory = category;
  172. _sawmill.Info("Populating...");
  173. var currentAge = 0;
  174. var isTDM = false;
  175. var mapId = _mapManager.GetAllMapIds().FirstOrDefault();
  176. if (_playerManager.LocalEntity != null)
  177. {
  178. if (_entManager.TryGetComponent<TransformComponent>(_playerManager.LocalEntity, out var xform))
  179. {
  180. mapId = xform.MapID;
  181. }
  182. }
  183. var mapUid = _mapManager.GetMapEntityId(mapId);
  184. if (_entManager.TryGetComponent(mapUid, out CivResearchComponent? component))
  185. {
  186. var newval = (int)MathF.Floor(component.ResearchLevel / 100);
  187. if (newval > currentAge)
  188. {
  189. currentAge = newval;
  190. }
  191. _sawmill.Info($"Current age: {currentAge}");
  192. }
  193. if (component != null)
  194. {
  195. if (component.IsTDM)
  196. {
  197. isTDM = true;
  198. _sawmill.Info("Map is TDM");
  199. }
  200. }
  201. foreach (var recipe in _prototypeManager.EnumeratePrototypes<ConstructionPrototype>())
  202. {
  203. if (recipe.Hide)
  204. continue;
  205. if (currentAge < recipe.AgeMin || currentAge > recipe.AgeMax)
  206. continue;
  207. if (recipe.TDM == false && isTDM == true)
  208. {
  209. continue;
  210. }
  211. if (_playerManager.LocalSession == null
  212. || _playerManager.LocalEntity == null
  213. || _whitelistSystem.IsWhitelistFail(recipe.EntityWhitelist, _playerManager.LocalEntity.Value))
  214. continue;
  215. if (!string.IsNullOrEmpty(search))
  216. {
  217. if (!recipe.Name.ToLowerInvariant().Contains(search.Trim().ToLowerInvariant()))
  218. continue;
  219. }
  220. if (!isEmptyCategory)
  221. {
  222. if (category == _favoriteCatName)
  223. {
  224. if (!_favoritedRecipes.Contains(recipe))
  225. {
  226. continue;
  227. }
  228. }
  229. else if (recipe.Category != category)
  230. {
  231. continue;
  232. }
  233. }
  234. recipes.Add(recipe);
  235. }
  236. recipes.Sort((a, b) => string.Compare(a.Name, b.Name, StringComparison.InvariantCulture));
  237. var recipesList = _constructionView.Recipes;
  238. recipesList.Clear();
  239. var recipesGrid = _constructionView.RecipesGrid;
  240. recipesGrid.RemoveAllChildren();
  241. _constructionView.RecipesGridScrollContainer.Visible = _constructionView.GridViewButtonPressed;
  242. _constructionView.Recipes.Visible = !_constructionView.GridViewButtonPressed;
  243. if (_constructionView.GridViewButtonPressed)
  244. {
  245. foreach (var recipe in recipes)
  246. {
  247. var itemButton = new TextureButton
  248. {
  249. TextureNormal = _spriteSystem.Frame0(recipe.Icon),
  250. VerticalAlignment = Control.VAlignment.Center,
  251. Name = recipe.Name,
  252. ToolTip = recipe.Name,
  253. Scale = new Vector2(1.35f),
  254. ToggleMode = true,
  255. };
  256. var itemButtonPanelContainer = new PanelContainer
  257. {
  258. PanelOverride = new StyleBoxFlat { BackgroundColor = StyleNano.ButtonColorDefault },
  259. Children = { itemButton },
  260. };
  261. itemButton.OnToggled += buttonToggledEventArgs =>
  262. {
  263. SelectGridButton(itemButton, buttonToggledEventArgs.Pressed);
  264. if (buttonToggledEventArgs.Pressed &&
  265. _selected != null &&
  266. _recipeButtons.TryGetValue(_selected.Name, out var oldButton))
  267. {
  268. oldButton.Pressed = false;
  269. SelectGridButton(oldButton, false);
  270. }
  271. OnGridViewRecipeSelected(this, buttonToggledEventArgs.Pressed ? recipe : null);
  272. };
  273. recipesGrid.AddChild(itemButtonPanelContainer);
  274. _recipeButtons[recipe.Name] = itemButton;
  275. var isCurrentButtonSelected = _selected == recipe;
  276. itemButton.Pressed = isCurrentButtonSelected;
  277. SelectGridButton(itemButton, isCurrentButtonSelected);
  278. }
  279. }
  280. else
  281. {
  282. foreach (var recipe in recipes)
  283. {
  284. recipesList.Add(GetItem(recipe, recipesList));
  285. }
  286. }
  287. }
  288. private void SelectGridButton(TextureButton button, bool select)
  289. {
  290. if (button.Parent is not PanelContainer buttonPanel)
  291. return;
  292. button.Modulate = select ? Color.Green : Color.White;
  293. var buttonColor = select ? StyleNano.ButtonColorDefault : Color.Transparent;
  294. buttonPanel.PanelOverride = new StyleBoxFlat { BackgroundColor = buttonColor };
  295. }
  296. private void PopulateCategories(string? selectCategory = null)
  297. {
  298. var uniqueCategories = new HashSet<string>();
  299. foreach (var prototype in _prototypeManager.EnumeratePrototypes<ConstructionPrototype>())
  300. {
  301. var category = prototype.Category;
  302. if (!string.IsNullOrEmpty(category))
  303. uniqueCategories.Add(category);
  304. }
  305. var isFavorites = _favoritedRecipes.Count > 0;
  306. var categoriesArray = new string[isFavorites ? uniqueCategories.Count + 2 : uniqueCategories.Count + 1];
  307. // hard-coded to show all recipes
  308. var idx = 0;
  309. categoriesArray[idx++] = _forAllCategoryName;
  310. // hard-coded to show favorites if it need
  311. if (isFavorites)
  312. {
  313. categoriesArray[idx++] = _favoriteCatName;
  314. }
  315. var sortedProtoCategories = uniqueCategories.OrderBy(Loc.GetString);
  316. foreach (var cat in sortedProtoCategories)
  317. {
  318. categoriesArray[idx++] = cat;
  319. }
  320. _constructionView.OptionCategories.Clear();
  321. for (var i = 0; i < categoriesArray.Length; i++)
  322. {
  323. _constructionView.OptionCategories.AddItem(Loc.GetString(categoriesArray[i]), i);
  324. if (!string.IsNullOrEmpty(selectCategory) && selectCategory == categoriesArray[i])
  325. _constructionView.OptionCategories.SelectId(i);
  326. }
  327. _constructionView.Categories = categoriesArray;
  328. }
  329. private void PopulateInfo(ConstructionPrototype prototype)
  330. {
  331. _constructionView.ClearRecipeInfo();
  332. _constructionView.SetRecipeInfo(
  333. prototype.Name, prototype.Description, _spriteSystem.Frame0(prototype.Icon),
  334. prototype.Type != ConstructionType.Item,
  335. !_favoritedRecipes.Contains(prototype));
  336. var stepList = _constructionView.RecipeStepList;
  337. GenerateStepList(prototype, stepList);
  338. }
  339. private void GenerateStepList(ConstructionPrototype prototype, ItemList stepList)
  340. {
  341. if (_constructionSystem?.GetGuide(prototype) is not { } guide)
  342. return;
  343. foreach (var entry in guide.Entries)
  344. {
  345. var text = entry.Arguments != null
  346. ? Loc.GetString(entry.Localization, entry.Arguments) : Loc.GetString(entry.Localization);
  347. if (entry.EntryNumber is { } number)
  348. {
  349. text = Loc.GetString("construction-presenter-step-wrapper",
  350. ("step-number", number), ("text", text));
  351. }
  352. // The padding needs to be applied regardless of text length... (See PadLeft documentation)
  353. text = text.PadLeft(text.Length + entry.Padding);
  354. var icon = entry.Icon != null ? _spriteSystem.Frame0(entry.Icon) : Texture.Transparent;
  355. stepList.AddItem(text, icon, false);
  356. }
  357. }
  358. private ItemList.Item GetItem(ConstructionPrototype recipe, ItemList itemList)
  359. {
  360. return new(itemList)
  361. {
  362. Metadata = recipe,
  363. Text = recipe.Name,
  364. Icon = _spriteSystem.Frame0(recipe.Icon),
  365. TooltipEnabled = true,
  366. TooltipText = recipe.Description,
  367. };
  368. }
  369. private void BuildButtonToggled(bool pressed)
  370. {
  371. if (pressed)
  372. {
  373. if (_selected == null) return;
  374. // not bound to a construction system
  375. if (_constructionSystem is null)
  376. {
  377. _constructionView.BuildButtonPressed = false;
  378. return;
  379. }
  380. if (_selected.Type == ConstructionType.Item)
  381. {
  382. _constructionSystem.TryStartItemConstruction(_selected.ID);
  383. _constructionView.BuildButtonPressed = false;
  384. return;
  385. }
  386. _placementManager.BeginPlacing(new PlacementInformation
  387. {
  388. IsTile = false,
  389. PlacementOption = _selected.PlacementMode
  390. }, new ConstructionPlacementHijack(_constructionSystem, _selected));
  391. UpdateGhostPlacement();
  392. }
  393. else
  394. _placementManager.Clear();
  395. _constructionView.BuildButtonPressed = pressed;
  396. }
  397. private void UpdateGhostPlacement()
  398. {
  399. if (_selected == null)
  400. return;
  401. if (_selected.Type != ConstructionType.Structure)
  402. {
  403. _placementManager.Clear();
  404. return;
  405. }
  406. var constructSystem = _systemManager.GetEntitySystem<ConstructionSystem>();
  407. _placementManager.BeginPlacing(new PlacementInformation()
  408. {
  409. IsTile = false,
  410. PlacementOption = _selected.PlacementMode,
  411. }, new ConstructionPlacementHijack(constructSystem, _selected));
  412. _constructionView.BuildButtonPressed = true;
  413. }
  414. private void OnSystemLoaded(object? sender, SystemChangedArgs args)
  415. {
  416. if (args.System is ConstructionSystem system) SystemBindingChanged(system);
  417. }
  418. private void OnSystemUnloaded(object? sender, SystemChangedArgs args)
  419. {
  420. if (args.System is ConstructionSystem) SystemBindingChanged(null);
  421. }
  422. private void OnViewFavoriteRecipe()
  423. {
  424. if (_selected is not ConstructionPrototype recipe)
  425. return;
  426. if (!_favoritedRecipes.Remove(_selected))
  427. _favoritedRecipes.Add(_selected);
  428. if (_selectedCategory == _favoriteCatName)
  429. {
  430. if (_favoritedRecipes.Count > 0)
  431. OnViewPopulateRecipes(_constructionView, (string.Empty, _favoriteCatName));
  432. else
  433. OnViewPopulateRecipes(_constructionView, (string.Empty, string.Empty));
  434. }
  435. PopulateInfo(_selected);
  436. PopulateCategories(_selectedCategory);
  437. }
  438. private void SystemBindingChanged(ConstructionSystem? newSystem)
  439. {
  440. if (newSystem is null)
  441. {
  442. if (_constructionSystem is null)
  443. return;
  444. UnbindFromSystem();
  445. }
  446. else
  447. {
  448. if (_constructionSystem is null)
  449. {
  450. BindToSystem(newSystem);
  451. return;
  452. }
  453. UnbindFromSystem();
  454. BindToSystem(newSystem);
  455. }
  456. }
  457. private void BindToSystem(ConstructionSystem system)
  458. {
  459. _constructionSystem = system;
  460. system.ToggleCraftingWindow += SystemOnToggleMenu;
  461. system.FlipConstructionPrototype += SystemFlipConstructionPrototype;
  462. system.CraftingAvailabilityChanged += SystemCraftingAvailabilityChanged;
  463. system.ConstructionGuideAvailable += SystemGuideAvailable;
  464. if (_uiManager.GetActiveUIWidgetOrNull<GameTopMenuBar>() != null)
  465. {
  466. CraftingAvailable = system.CraftingEnabled;
  467. }
  468. }
  469. private void UnbindFromSystem()
  470. {
  471. var system = _constructionSystem;
  472. if (system is null)
  473. throw new InvalidOperationException();
  474. system.ToggleCraftingWindow -= SystemOnToggleMenu;
  475. system.FlipConstructionPrototype -= SystemFlipConstructionPrototype;
  476. system.CraftingAvailabilityChanged -= SystemCraftingAvailabilityChanged;
  477. system.ConstructionGuideAvailable -= SystemGuideAvailable;
  478. _constructionSystem = null;
  479. }
  480. private void SystemCraftingAvailabilityChanged(object? sender, CraftingAvailabilityChangedArgs e)
  481. {
  482. if (_uiManager.ActiveScreen == null)
  483. return;
  484. CraftingAvailable = e.Available;
  485. }
  486. private void SystemOnToggleMenu(object? sender, EventArgs eventArgs)
  487. {
  488. if (!CraftingAvailable)
  489. return;
  490. if (WindowOpen)
  491. {
  492. if (IsAtFront)
  493. {
  494. WindowOpen = false;
  495. _uiManager.GetActiveUIWidget<GameTopMenuBar>().CraftingButton.SetClickPressed(false); // This does not call CraftingButtonToggled
  496. }
  497. else
  498. _constructionView.MoveToFront();
  499. }
  500. else
  501. {
  502. WindowOpen = true;
  503. _uiManager.GetActiveUIWidget<GameTopMenuBar>().CraftingButton.SetClickPressed(true); // This does not call CraftingButtonToggled
  504. }
  505. }
  506. private void SystemFlipConstructionPrototype(object? sender, EventArgs eventArgs)
  507. {
  508. if (!_placementManager.IsActive || _placementManager.Eraser)
  509. {
  510. return;
  511. }
  512. if (_selected == null || _selected.Mirror == null)
  513. {
  514. return;
  515. }
  516. _selected = _prototypeManager.Index<ConstructionPrototype>(_selected.Mirror);
  517. UpdateGhostPlacement();
  518. }
  519. private void SystemGuideAvailable(object? sender, string e)
  520. {
  521. if (!CraftingAvailable)
  522. return;
  523. if (!WindowOpen)
  524. return;
  525. if (_selected == null)
  526. return;
  527. PopulateInfo(_selected);
  528. }
  529. }
  530. }