1
0
mirror of https://github.com/tobspr/shapez.io.git synced 2025-06-13 13:04:03 +00:00

Merge branch 'master' into logic-pain-fix

This commit is contained in:
dengr1065 2020-08-29 00:29:21 +03:00
commit 997cde22d9
70 changed files with 13256 additions and 12368 deletions

View File

@ -59,7 +59,7 @@ This project is based on ES5. Some ES2015 features are used but most of them are
1. Create the component file in `src/js/game/components/<name_lowercase>.js`
2. Create a component class (e.g. `MyFancyComponent`) which `extends Component`
3. Create a `static getId()` method which should return the `CamelCaseName` without component (e.g. `MyFancy`)
3. Create a `static getId()` method which should return the `PascalCaseName` without component (e.g. `MyFancy`)
4. If any data needs to be persisted, create a `static getSchema()` which should return the properties to be saved (See other components)
5. Add a constructor. **The constructor must be called with optional parameters only!** `new MyFancyComponent({})` should always work.
6. Add any props you need in the constructor.

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 430 B

File diff suppressed because it is too large Load Diff

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 MiB

After

Width:  |  Height:  |  Size: 1.3 MiB

File diff suppressed because it is too large Load Diff

Binary file not shown.

Before

Width:  |  Height:  |  Size: 238 KiB

After

Width:  |  Height:  |  Size: 266 KiB

File diff suppressed because it is too large Load Diff

Binary file not shown.

Before

Width:  |  Height:  |  Size: 567 KiB

After

Width:  |  Height:  |  Size: 636 KiB

View File

@ -277,6 +277,12 @@
<key type="filename">sprites/blueprints/underground_belt_entry.png</key>
<key type="filename">sprites/blueprints/underground_belt_exit-tier2.png</key>
<key type="filename">sprites/blueprints/underground_belt_exit.png</key>
<key type="filename">sprites/blueprints/virtual_processor-analyzer.png</key>
<key type="filename">sprites/blueprints/virtual_processor-rotater.png</key>
<key type="filename">sprites/blueprints/virtual_processor-shapecompare.png</key>
<key type="filename">sprites/blueprints/virtual_processor-unstacker.png</key>
<key type="filename">sprites/blueprints/virtual_processor.png</key>
<key type="filename">sprites/blueprints/wire_tunnel-coating.png</key>
<key type="filename">sprites/blueprints/wire_tunnel.png</key>
<key type="filename">sprites/buildings/constant_signal.png</key>
<key type="filename">sprites/buildings/display.png</key>
@ -295,6 +301,12 @@
<key type="filename">sprites/buildings/underground_belt_entry.png</key>
<key type="filename">sprites/buildings/underground_belt_exit-tier2.png</key>
<key type="filename">sprites/buildings/underground_belt_exit.png</key>
<key type="filename">sprites/buildings/virtual_processor-analyzer.png</key>
<key type="filename">sprites/buildings/virtual_processor-rotater.png</key>
<key type="filename">sprites/buildings/virtual_processor-shapecompare.png</key>
<key type="filename">sprites/buildings/virtual_processor-unstacker.png</key>
<key type="filename">sprites/buildings/virtual_processor.png</key>
<key type="filename">sprites/buildings/wire_tunnel-coating.png</key>
<key type="filename">sprites/buildings/wire_tunnel.png</key>
<key type="filename">sprites/wires/lever_on.png</key>
<key type="filename">sprites/wires/sets/color_cross.png</key>
@ -533,6 +545,8 @@
</struct>
<key type="filename">sprites/wires/boolean_false.png</key>
<key type="filename">sprites/wires/boolean_true.png</key>
<key type="filename">sprites/wires/network_conflict.png</key>
<key type="filename">sprites/wires/network_empty.png</key>
<key type="filename">sprites/wires/wires_preview.png</key>
<struct type="IndividualSpriteSettings">
<key>pivotPoint</key>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.1 KiB

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 43 KiB

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.1 KiB

After

Width:  |  Height:  |  Size: 9.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 24 KiB

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.6 KiB

After

Width:  |  Height:  |  Size: 9.5 KiB

View File

@ -664,7 +664,7 @@ iframe {
user-select: all;
}
// Steam overlay fiy
// Steam overlay fix
#steamOverlayCanvasFix {
position: fixed;
top: 0px;

View File

@ -1,38 +1,38 @@
$buildings: belt, cutter, miner, mixer, painter, rotater, splitter, stacker, trash, underground_belt, wire,
constant_signal, logic_gate, lever, filter, wire_tunnel, display;
@each $building in $buildings {
[data-icon="building_icons/#{$building}.png"] {
background-image: uiResource("res/ui/building_icons/#{$building}.png") !important;
}
}
$buildingsAndVariants: belt, splitter, splitter-compact, splitter-compact-inverse, underground_belt,
underground_belt-tier2, miner, miner-chainable, cutter, cutter-quad, rotater, rotater-ccw, rotater-fl,
stacker, mixer, painter, painter-double, painter-quad, trash, trash-storage;
@each $building in $buildingsAndVariants {
[data-icon="building_tutorials/#{$building}.png"] {
background-image: uiResource("res/ui/building_tutorials/#{$building}.png") !important;
}
}
// Special case
[data-icon="building_tutorials/painter-mirrored.png"] {
background-image: uiResource("res/ui/building_tutorials/painter.png") !important;
}
$icons: notification_saved, notification_success, notification_upgrade;
@each $icon in $icons {
[data-icon="icons/#{$icon}.png"] {
background-image: uiResource("res/ui/icons/#{$icon}.png") !important;
}
}
$languages: en, de, cs, da, et, es-419, fr, it, pt-BR, sv, tr, el, ru, uk, zh-TW, zh-CN, nb, mt-MT, ar, nl, vi,
th, hu, pl, ja, kor, no, pt-PT;
@each $language in $languages {
[data-languageicon="#{$language}"] {
background-image: uiResource("languages/#{$language}.svg") !important;
}
}
$buildings: belt, cutter, miner, mixer, painter, rotater, splitter, stacker, trash, underground_belt, wire,
constant_signal, logic_gate, lever, filter, wire_tunnel, display, virtual_processor;
@each $building in $buildings {
[data-icon="building_icons/#{$building}.png"] {
background-image: uiResource("res/ui/building_icons/#{$building}.png") !important;
}
}
$buildingsAndVariants: belt, splitter, splitter-compact, splitter-compact-inverse, underground_belt,
underground_belt-tier2, miner, miner-chainable, cutter, cutter-quad, rotater, rotater-ccw, rotater-fl,
stacker, mixer, painter, painter-double, painter-quad, trash, trash-storage;
@each $building in $buildingsAndVariants {
[data-icon="building_tutorials/#{$building}.png"] {
background-image: uiResource("res/ui/building_tutorials/#{$building}.png") !important;
}
}
// Special case
[data-icon="building_tutorials/painter-mirrored.png"] {
background-image: uiResource("res/ui/building_tutorials/painter.png") !important;
}
$icons: notification_saved, notification_success, notification_upgrade;
@each $icon in $icons {
[data-icon="icons/#{$icon}.png"] {
background-image: uiResource("res/ui/icons/#{$icon}.png") !important;
}
}
$languages: en, de, cs, da, et, es-419, fr, it, pt-BR, sv, tr, el, ru, uk, zh-TW, zh-CN, nb, mt-MT, ar, nl, vi,
th, hu, pl, ja, kor, no, pt-PT;
@each $language in $languages {
[data-languageicon="#{$language}"] {
background-image: uiResource("languages/#{$language}.svg") !important;
}
}

View File

@ -14,20 +14,37 @@
@include S(padding, 1px, 10px);
border: 0;
box-shadow: none;
border-radius: 0;
@include IncreasedClickArea(1px);
@include S(min-width, 30px);
color: #fff;
opacity: 0.25;
@include S(margin-left, 1px);
@include S(border-radius, $globalBorderRadius);
border-radius: 0;
&:first-child {
@include S(border-top-left-radius, $globalBorderRadius);
@include S(border-bottom-left-radius, $globalBorderRadius);
}
&:last-child {
@include S(border-top-right-radius, $globalBorderRadius);
@include S(border-bottom-right-radius, $globalBorderRadius);
}
&.displayIcons,
&.displayDetailed {
&.displayDetailed,
&.displaySorted {
background: uiResource("icons/display_list.png") center center / #{D(15px)} no-repeat;
&.displayIcons {
background-image: uiResource("icons/display_icons.png");
background-size: #{D(11.5px)};
}
&.displaySorted {
background-image: uiResource("icons/display_sorted.png");
background-size: #{D(11.5px)};
margin-right: 4px;
@include S(padding, 1px, 0);
}
}
background-color: #44484a !important;
@ -80,10 +97,7 @@
background: #f4f4f4;
@include S(margin-bottom, 4px);
display: grid;
@include DarkThemeOverride {
background: #222428;
}
@include S(border-radius, $globalBorderRadius);
grid-template-columns: 1fr auto;
@include S(padding, 5px);
@ -91,6 +105,18 @@
margin-bottom: 0;
}
&.pinned {
background: #e3e5e9;
}
@include DarkThemeOverride {
background: #222428;
&.pinned {
background: darken(#222428, 10);
}
}
canvas.icon {
grid-column: 1 / 2;
grid-row: 1 / 2;
@ -100,7 +126,6 @@
.counter {
@include SuperSmallText;
@include S(padding, 0, 3px);
}
}
@ -109,6 +134,7 @@
.dialogInner {
&[data-displaymode="detailed"] .displayDetailed,
&[data-displaymode="icons"] .displayIcons,
&[data-sorted="true"] .displaySorted,
&[data-datasource="produced"] .modeProduced,
&[data-datasource="delivered"] .modeDelivered,
&[data-datasource="stored"] .modeStored {
@ -132,7 +158,6 @@
.counter {
grid-column: 1 / 2;
grid-row: 2 / 3;
background: rgba(0, 10, 20, 0.05);
justify-self: end;
}
}

View File

@ -1,124 +1,124 @@
// Control here whether to inline all resources or instead load them
@function uiResource($pth) {
@if (str-index($string: $pth, $substring: ".noinline")) {
@return resolve($pth);
}
@return inline($pth);
}
@import "icons";
@import "trigonometry";
@import "material_colors";
@import "dynamic_ui";
@import "variables";
@import "mixins";
@import "common";
@import "animations";
@import "game_state";
@import "application_error";
@import "textual_game_state";
@import "adinplay";
@import "states/preload";
@import "states/main_menu";
@import "states/ingame";
@import "states/keybindings";
@import "states/settings";
@import "states/about";
@import "states/mobile_warning";
@import "states/changelog";
@import "ingame_hud/buildings_toolbar";
@import "ingame_hud/building_placer";
@import "ingame_hud/beta_overlay";
@import "ingame_hud/keybindings_overlay";
@import "ingame_hud/unlock_notification";
@import "ingame_hud/shop";
@import "ingame_hud/game_menu";
@import "ingame_hud/dialogs";
@import "ingame_hud/vignette_overlay";
@import "ingame_hud/statistics";
@import "ingame_hud/pinned_shapes";
@import "ingame_hud/notifications";
@import "ingame_hud/settings_menu";
@import "ingame_hud/debug_info";
@import "ingame_hud/entity_debugger";
@import "ingame_hud/tutorial_hints";
@import "ingame_hud/watermark";
@import "ingame_hud/blueprint_placer";
@import "ingame_hud/waypoints";
@import "ingame_hud/interactive_tutorial";
@import "ingame_hud/color_blind_helper";
@import "ingame_hud/shape_viewer";
@import "ingame_hud/sandbox_controller";
// prettier-ignore
$elements:
// Base
ingame_Canvas,
ingame_VignetteOverlay,
// Ingame overlays
ingame_HUD_Waypoints,
ingame_HUD_PlacementHints,
ingame_HUD_PlacerVariants,
// Regular hud
ingame_HUD_PinnedShapes,
ingame_HUD_GameMenu,
ingame_HUD_KeybindingOverlay,
ingame_HUD_Notifications,
ingame_HUD_DebugInfo,
ingame_HUD_EntityDebugger,
ingame_HUD_InteractiveTutorial,
ingame_HUD_TutorialHints,
ingame_HUD_buildings_toolbar,
ingame_HUD_wires_toolbar,
ingame_HUD_BlueprintPlacer,
ingame_HUD_Waypoints_Hint,
ingame_HUD_Watermark,
ingame_HUD_ColorBlindBelowTileHelper,
ingame_HUD_SandboxController,
// Overlays
ingame_HUD_BetaOverlay,
// Dialogs
ingame_HUD_Shop,
ingame_HUD_Statistics,
ingame_HUD_ShapeViewer,
ingame_HUD_UnlockNotification,
ingame_HUD_SettingsMenu,
ingame_HUD_ModalDialogs;
$zindex: 100;
@each $elem in $elements {
##{$elem} {
z-index: $zindex;
}
$zindex: $zindex + 10;
}
body.uiHidden {
#ingame_HUD_buildings_toolbar,
#ingame_HUD_PlacementHints,
#ingame_HUD_GameMenu,
#ingame_HUD_PinnedShapes,
#ingame_HUD_Notifications,
#ingame_HUD_TutorialHints,
#ingame_HUD_Waypoints,
#ingame_HUD_Waypoints_Hint {
display: none !important;
}
}
body.modalDialogActive,
body.externalAdOpen,
body.ingameDialogOpen {
> *:not(.ingameDialog):not(.modalDialogParent):not(.loadingDialog):not(.gameLoadingOverlay):not(#ingame_HUD_ModalDialogs):not(.noBlur) {
// filter: blur(5px) !important;
}
}
// Control here whether to inline all resources or instead load them
@function uiResource($pth) {
@if (str-index($string: $pth, $substring: ".noinline")) {
@return resolve($pth);
}
@return inline($pth);
}
@import "icons";
@import "trigonometry";
@import "material_colors";
@import "dynamic_ui";
@import "variables";
@import "mixins";
@import "common";
@import "animations";
@import "game_state";
@import "application_error";
@import "textual_game_state";
@import "adinplay";
@import "states/preload";
@import "states/main_menu";
@import "states/ingame";
@import "states/keybindings";
@import "states/settings";
@import "states/about";
@import "states/mobile_warning";
@import "states/changelog";
@import "ingame_hud/buildings_toolbar";
@import "ingame_hud/building_placer";
@import "ingame_hud/beta_overlay";
@import "ingame_hud/keybindings_overlay";
@import "ingame_hud/unlock_notification";
@import "ingame_hud/shop";
@import "ingame_hud/game_menu";
@import "ingame_hud/dialogs";
@import "ingame_hud/vignette_overlay";
@import "ingame_hud/statistics";
@import "ingame_hud/pinned_shapes";
@import "ingame_hud/notifications";
@import "ingame_hud/settings_menu";
@import "ingame_hud/debug_info";
@import "ingame_hud/entity_debugger";
@import "ingame_hud/tutorial_hints";
@import "ingame_hud/watermark";
@import "ingame_hud/blueprint_placer";
@import "ingame_hud/waypoints";
@import "ingame_hud/interactive_tutorial";
@import "ingame_hud/color_blind_helper";
@import "ingame_hud/shape_viewer";
@import "ingame_hud/sandbox_controller";
// prettier-ignore
$elements:
// Base
ingame_Canvas,
ingame_VignetteOverlay,
// Ingame overlays
ingame_HUD_Waypoints,
ingame_HUD_PlacementHints,
ingame_HUD_PlacerVariants,
// Regular hud
ingame_HUD_PinnedShapes,
ingame_HUD_GameMenu,
ingame_HUD_KeybindingOverlay,
ingame_HUD_Notifications,
ingame_HUD_DebugInfo,
ingame_HUD_EntityDebugger,
ingame_HUD_InteractiveTutorial,
ingame_HUD_TutorialHints,
ingame_HUD_buildings_toolbar,
ingame_HUD_wires_toolbar,
ingame_HUD_BlueprintPlacer,
ingame_HUD_Waypoints_Hint,
ingame_HUD_Watermark,
ingame_HUD_ColorBlindBelowTileHelper,
ingame_HUD_SandboxController,
// Overlays
ingame_HUD_BetaOverlay,
// Dialogs
ingame_HUD_Shop,
ingame_HUD_Statistics,
ingame_HUD_ShapeViewer,
ingame_HUD_UnlockNotification,
ingame_HUD_SettingsMenu,
ingame_HUD_ModalDialogs;
$zindex: 100;
@each $elem in $elements {
##{$elem} {
z-index: $zindex;
}
$zindex: $zindex + 10;
}
body.uiHidden {
.ingame_buildingsToolbar,
#ingame_HUD_PlacementHints,
#ingame_HUD_GameMenu,
#ingame_HUD_PinnedShapes,
#ingame_HUD_Notifications,
#ingame_HUD_TutorialHints,
#ingame_HUD_Waypoints,
#ingame_HUD_Waypoints_Hint {
display: none !important;
}
}
body.modalDialogActive,
body.externalAdOpen,
body.ingameDialogOpen {
> *:not(.ingameDialog):not(.modalDialogParent):not(.loadingDialog):not(.gameLoadingOverlay):not(#ingame_HUD_ModalDialogs):not(.noBlur) {
// filter: blur(5px) !important;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,300 +1,304 @@
export const CHANGELOG = [
{
version: "1.2.0",
date: "unreleased",
entries: [
"WIRES",
"Reworked menu UI design (by dengr1605)",
"Allow holding ALT in belt planner to reverse direction (by jakobhellermann)",
"Clear cursor when trying to pipette the same building twice (by hexy)",
"Fixed level 18 stacker bug: If you experienced it already, you know it, if not, I don't want to spoiler (by hexy)",
"Added keybinding to close menus (by isaisstillalive / Sandwichs-del)",
"Fix rare crash regarding the buildings toolbar (by isaisstillalive)",
"Fixed some phrases (by EnderDoom77)",
"Zoom towards mouse cursor (by Dimava)",
"Added multiple settings to optimize the performance",
"Updated the soundtrack again, it is now 40 minutes in total!",
"Updated and added new translations (Thanks to all contributors!)",
"Allow editing waypoints (by isaisstillalive)",
"Show confirmation when cutting area which is too expensive to get pasted again (by isaisstillalive)",
"Show mouse and camera tile on debug overlay (F4) (by dengr)",
"Fix tunnels entrances connecting to exits sometimes when they shouldn't",
"The initial belt planner direction is now based on the cursor movement (by MizardX)",
"Fix preferred variant not getting saved when clicking on the hud (by Danacus)",
],
},
{
version: "1.1.19",
date: "02.07.2020",
entries: [
"There are now notifications every 15 minutes in the demo version to buy the full version (For further details and the reason, check the #surveys channel in the Discord)",
"I'm still working on the wires update, I hope to release it mid july!",
],
},
{
version: "1.1.18",
date: "27.06.2020",
entries: [
"Huge performance improvements - up to double fps and tick-rate! This will wipe out all current items on belts.",
"Reduce story shapes required until unlocking blueprints",
"Allow clicking on variants to select them",
"Add 'copy key' button to shape viewer",
"Add more FPS to the belt animation and fix belt animation seeming to go 'backwards' on high belt speeds",
"Fix deconstruct sound being played when right clicking hub",
"Allow clicking 'Q' over a shape or color patch to automatically select the miner building (by Gerdon262)",
"Update belt placement performance on huge factories (by Phlosioneer)",
"Fix duplicate waypoints with a shape not rendering (by hexy)",
"Fix smart tunnel placement deleting wrong tunnels (by mordof)",
"Add setting (on by default) to store the last used rotation per building instead of globally storing it (by Magos)",
"Added chinese (traditional) translation",
"Updated translations",
],
},
{
version: "1.1.17",
date: "22.06.2020",
entries: [
"Color blind mode! You can now activate it in the settings and it will show you which color is below your cursor (Either resource or on the belt)",
"Add info buttons to all shapes so you can figure out how they are built! (And also, which colors they have)",
"Allow configuring autosave interval and disabling it in the settings",
"The smart-tunnel placement has been reworked to properly replace belts. Thus the setting has been turned on again by default",
"The soundtrack now has a higher quality on the standalone version than the web version",
"Add setting to disable cut/delete warnings (by hexy)",
"Fix bug where belts in blueprints don't orient correctly (by hexy)",
"Fix camera moving weird after dragging and holding (by hexy)",
"Fix keybinding for pipette showing while pasting blueprints",
"Improve visibility of shape background in dark mode",
"Added sound when destroying a building",
"Added swedish translation",
"Update tutorial image for tier 2 tunnels to explain mix/match (by jimmyshadow1)",
],
},
{
version: "1.1.16",
date: "21.06.2020",
entries: [
"You can now pickup buildings below your cursor with 'Q'!",
"The game soundtrack has been extended! There are now 4 songs with over 13 minutes of playtime from <a href='https://soundcloud.com/pettersumelius' target='blank'>Peppsen</a>!",
"Refactor keybindings overlay to show more appropriate keybindings",
"Show keybindings for area-select in the upper left instead",
"Automatically deselect area when selecting a new building",
"Raise markers limit from 14 characters to 71 (by Joker-vD)",
"Optimize performance by caching extractor items (by Phlosioneer)",
"Added setting to enable compact building infos, which only show ratios and hide the image / description",
"Apply dark theme to menu as well (by dengr1065)",
"Fix belt planner not placing the last belt",
"Fix buildings getting deleted when right clicking while placing a blueprint",
"Fix for exporting screenshots for huge bases (It was showing an empty file) (by xSparfuchs)",
"Fix buttons not responding when using right click directly after left click (by davidburhans)",
"Fix hub marker being hidden by building info panel",
"Disable dialog background blur since it can cause performance issues",
"Added simplified chinese translations",
"Update translations (Thanks to all translators!)",
],
},
{
version: "1.1.15",
date: "17.06.2020",
entries: [
"You can now place straight belts (and tunnels) by holding SHIFT! (For you, @giantwaffle ❤️)",
"Added continue button to main menu and add seperate 'New game' button (by jaysc)",
"Added setting to disable smart tunnel placement introduced with the last update",
"Added setting to disable vignette",
"Update translations",
],
},
{
version: "1.1.14",
date: "16.06.2020",
entries: [
"There is now an indicator (compass) to the HUB for the HUB Marker!",
"You can now include shape short keys in markers to render shape icons instead of text!",
"Added mirrored variant of the painter",
"When placing tunnels, unnecessary belts inbetween are now removed!",
"You can now drag tunnels and they will automatically expand! (Just try it out, its intuitive)",
],
},
{
version: "1.1.13",
date: "15.06.2020",
entries: [
"Added shift modifier for faster pan (by jaysc)",
"Added Japanese translations",
"Added Portuguese (Portugal) translations",
"Updated icon for Spanish (Latin America) - It was showing a Spanish flag before",
"Updated existing translations",
],
},
{
version: "1.1.12",
date: "14.06.2020",
entries: [
"Huge performance improvements! The game should now run up to 60% faster!",
"Added norwegian translation",
],
},
{
version: "1.1.11",
date: "13.06.2020",
entries: [
"Pinned shapes are now smart, they dynamically update their goal and also unpin when no longer required. Completed objectives are now rendered transparent.",
"You can now cut areas, and also paste the last blueprint again! (by hexy)",
"You can now export your whole base as an image by pressing F3!",
"Improve upgrade number rounding, so there are no goals like '37.4k', instead it will now be '35k'",
"You can now configure the camera movement speed when using WASD (by mini-bomba)",
"Selecting an area now is relative to the world and thus does not move when moving the screen (by Dimava)",
"Allow higher tick-rates up to 500hz (This will burn your PC!)",
"Fix bug regarding number rounding",
"Fix dialog text being hardly readable in dark theme",
"Fix app not starting when the savegames were corrupted - there is now a better error message as well.",
"Further translation updates - Big thanks to all contributors!",
],
},
{
version: "1.1.10",
date: "12.06.2020",
entries: [
"There are now linux builds on steam! Please report any issues in the Discord!",
"Steam cloud saves are now available!",
"Added and update more translations (Big thank you to all translators!)",
"Prevent invalid connection if existing underground tunnel entrance exists (by jaysc)",
],
},
{
version: "1.1.9",
date: "11.06.2020",
entries: [
"Support for translations! Interested in helping out? Check out the <a target='_blank' href='https://github.com/tobspr/shapez.io/tree/master/translations'>translation guide</a>!",
"Update stacker artwork to clarify how it works",
"Update keybinding hints on the top left to be more accurate",
"Make it more clear when blueprints are unlocked when trying to use them",
"Fix pinned shape icons not being visible in dark mode",
"Fix being able to select buildings via hotkeys in map overview mode",
"Make shapes unpinnable in the upgrades tab (By hexy)",
],
},
{
version: "1.1.8",
date: "07.06.2020",
entries: [
"You can now purchase the standalone on steam! <a href='https://steam.shapez.io' target='blank'>View steam page</a>",
"Added ability to create markers in the demo, but only two.",
"Contest #01 has ended! I'll now work through the entries, select the 5 I like most and present them to the community to vote for!",
],
},
{
version: "1.1.7",
date: "04.06.2020",
entries: ["HOTFIX: Fix savegames not showing up on the standalone version"],
},
{
version: "1.1.6",
date: "04.06.2020",
entries: [
"The steam release will happen on the <strong>7th of June</strong> - Be sure to add it to your wishlist! <a href='https://steam.shapez.io' target='blank'>View on steam</a>",
"Fixed level complete dialog being blurred when the shop was opened before",
"Standalone: Increased icon visibility for windows builds",
"Web version: Fixed firefox not loading the game when browsing in private mode",
],
},
{
version: "1.1.5",
date: "03.06.2020",
entries: ["Added weekly contests!"],
},
{
version: "1.1.4",
date: "01.06.2020",
entries: ["Add 'interactive' tutorial for the first level to improve onboarding experience"],
},
{
version: "1.1.3",
date: "01.06.2020",
entries: [
"Added setting to configure zoom / mouse wheel / touchpad sensitivity",
"Fix belts being too slow when copied via blueprint (by Dimava)",
"Allow binding mouse buttons to actions (by Dimava)",
"Increase readability of certain HUD elements",
],
},
{
version: "1.1.2",
date: "30.05.2020",
entries: [
"The official trailer is now ready! Check it out <a href='https://www.youtube.com/watch?v=KyorY1uIqiQ' target='_blank'>here</a>!",
"The <a href='https://steam.shapez.io' target='_blank'>steam page</a> is now live!",
"Experimental linux builds are now available! Please give me feedback on them in the Discord",
"Allow hovering pinned shapes to enlarge them",
"Allow deselecting blueprints with right click and 'Q'",
"Move default key for deleting from 'X' to 'DEL'",
"Show confirmation when deleting more than 100 buildings",
"Reintroduce 'SPACE' keybinding to center on map",
"Improved keybinding hints",
"Fixed some keybindings showing as 'undefined'",
],
},
{
version: "1.1.1",
date: "28.05.2020",
entries: ["Fix crash when 'Show Hints' setting was turned off"],
},
{
version: "1.1.0",
date: "28.05.2020",
entries: [
"BLUEPRINTS! They are unlocked at level 12 and cost a special shape to build.",
"MAP MARKERS! Press 'M' to create a waypoint and be able to jump to it",
"Savegame levels are now shown in the main menu. For existing games, save them again to make the level show up.",
"Allow holding SHIFT to rotate counter clockwise",
"Added confirmation when deleting more than 500 buildings at a time",
"Added background to toolbar to increase contrast",
"Further decerase requirements of first levels",
"Pinned shapes now are saved",
"Allow placing extractors anywhere again, but they don't work at all if not placed on a resource",
"Show dialog explaining some keybindings after completing level 4",
"Fix keys being stuck when opening a dialog",
"Swapped shape order for painting upgrades",
"Allow changing all keybindings, including CTRL, ALT and SHIFT (by Dimava)",
"Fix cycling through keybindings selecting locked buildings as well (by Dimava)",
"There is now a github action, checking all pull requests with eslint. (by mrHedgehog)",
],
},
{
version: "1.0.4",
date: "26.05.2020",
entries: [
"Reduce cost of first painting upgrade, and change 'Shape Processing' to 'Cutting, Rotating & Stacking'",
"Add dialog after completing level 2 to check out the upgrades tab.",
"Allow changing the keybindings in the demo version",
],
},
{
version: "1.0.3",
date: "24.05.2020",
entries: [
"Reduced the amount of shapes required for the first 5 levels to make it easier to get into the game.",
],
},
{
version: "1.0.2",
date: "23.05.2020",
entries: [
"Introduced changelog",
"Removed 'early access' label because the game isn't actually early access - its in a pretty good state already! (No worries, a lot more updates will follow!)",
"Added a 'Show hint' button which shows a small video for almost all levels to help out",
"Now showing proper descriptions when completing levels, with instructions on what the gained reward does.",
"Show a landing page on mobile devices about the game not being ready to be played on mobile yet",
"Fix painters and mixers being affected by the shape processors upgrade and not the painter one",
"Added 'multiplace' setting which is equivalent to holding SHIFT all the time",
"Added keybindings to zoom in / zoom out",
"Tunnels now also show connection lines to tunnel exits, instead of just tunnel entries",
"Lots of minor fixes and improvements",
],
},
{
version: "1.0.1",
date: "21.05.2020",
entries: ["Initial release!"],
},
];
export const CHANGELOG = [
{
version: "1.2.0",
date: "unreleased",
entries: [
"WIRES",
"Reworked menu UI design (by dengr1605)",
"Allow holding ALT in belt planner to reverse direction (by jakobhellermann)",
"Clear cursor when trying to pipette the same building twice (by hexy)",
"Fixed level 18 stacker bug: If you experienced it already, you know it, if not, I don't want to spoiler (by hexy)",
"Added keybinding to close menus (by isaisstillalive / Sandwichs-del)",
"Fix rare crash regarding the buildings toolbar (by isaisstillalive)",
"Fixed some phrases (by EnderDoom77)",
"Zoom towards mouse cursor (by Dimava)",
"Added multiple settings to optimize the performance",
"Updated the soundtrack again, it is now 40 minutes in total!",
"Added a button to the statistics dialog to disable the sorting (by squeek502)",
"Updated and added new translations (Thanks to all contributors!)",
"Added setting to be able to delete buildings while placing (inspired by hexy)",
"Mark pinned shapes in statistics dialog and show them first (inspired by davidburhans)",
"There are now compact 1x1 splitters available to be unlocked!",
"Allow editing waypoints (by isaisstillalive)",
"Show confirmation when cutting area which is too expensive to get pasted again (by isaisstillalive)",
"Show mouse and camera tile on debug overlay (F4) (by dengr)",
"Fix tunnels entrances connecting to exits sometimes when they shouldn't",
"The initial belt planner direction is now based on the cursor movement (by MizardX)",
"Fix preferred variant not getting saved when clicking on the hud (by Danacus)",
],
},
{
version: "1.1.19",
date: "02.07.2020",
entries: [
"There are now notifications every 15 minutes in the demo version to buy the full version (For further details and the reason, check the #surveys channel in the Discord)",
"I'm still working on the wires update, I hope to release it mid july!",
],
},
{
version: "1.1.18",
date: "27.06.2020",
entries: [
"Huge performance improvements - up to double fps and tick-rate! This will wipe out all current items on belts.",
"Reduce story shapes required until unlocking blueprints",
"Allow clicking on variants to select them",
"Add 'copy key' button to shape viewer",
"Add more FPS to the belt animation and fix belt animation seeming to go 'backwards' on high belt speeds",
"Fix deconstruct sound being played when right clicking hub",
"Allow clicking 'Q' over a shape or color patch to automatically select the miner building (by Gerdon262)",
"Update belt placement performance on huge factories (by Phlosioneer)",
"Fix duplicate waypoints with a shape not rendering (by hexy)",
"Fix smart tunnel placement deleting wrong tunnels (by mordof)",
"Add setting (on by default) to store the last used rotation per building instead of globally storing it (by Magos)",
"Added chinese (traditional) translation",
"Updated translations",
],
},
{
version: "1.1.17",
date: "22.06.2020",
entries: [
"Color blind mode! You can now activate it in the settings and it will show you which color is below your cursor (Either resource or on the belt)",
"Add info buttons to all shapes so you can figure out how they are built! (And also, which colors they have)",
"Allow configuring autosave interval and disabling it in the settings",
"The smart-tunnel placement has been reworked to properly replace belts. Thus the setting has been turned on again by default",
"The soundtrack now has a higher quality on the standalone version than the web version",
"Add setting to disable cut/delete warnings (by hexy)",
"Fix bug where belts in blueprints don't orient correctly (by hexy)",
"Fix camera moving weird after dragging and holding (by hexy)",
"Fix keybinding for pipette showing while pasting blueprints",
"Improve visibility of shape background in dark mode",
"Added sound when destroying a building",
"Added swedish translation",
"Update tutorial image for tier 2 tunnels to explain mix/match (by jimmyshadow1)",
],
},
{
version: "1.1.16",
date: "21.06.2020",
entries: [
"You can now pickup buildings below your cursor with 'Q'!",
"The game soundtrack has been extended! There are now 4 songs with over 13 minutes of playtime from <a href='https://soundcloud.com/pettersumelius' target='blank'>Peppsen</a>!",
"Refactor keybindings overlay to show more appropriate keybindings",
"Show keybindings for area-select in the upper left instead",
"Automatically deselect area when selecting a new building",
"Raise markers limit from 14 characters to 71 (by Joker-vD)",
"Optimize performance by caching extractor items (by Phlosioneer)",
"Added setting to enable compact building infos, which only show ratios and hide the image / description",
"Apply dark theme to menu as well (by dengr1065)",
"Fix belt planner not placing the last belt",
"Fix buildings getting deleted when right clicking while placing a blueprint",
"Fix for exporting screenshots for huge bases (It was showing an empty file) (by xSparfuchs)",
"Fix buttons not responding when using right click directly after left click (by davidburhans)",
"Fix hub marker being hidden by building info panel",
"Disable dialog background blur since it can cause performance issues",
"Added simplified chinese translations",
"Update translations (Thanks to all translators!)",
],
},
{
version: "1.1.15",
date: "17.06.2020",
entries: [
"You can now place straight belts (and tunnels) by holding SHIFT! (For you, @giantwaffle ❤️)",
"Added continue button to main menu and add seperate 'New game' button (by jaysc)",
"Added setting to disable smart tunnel placement introduced with the last update",
"Added setting to disable vignette",
"Update translations",
],
},
{
version: "1.1.14",
date: "16.06.2020",
entries: [
"There is now an indicator (compass) to the HUB for the HUB Marker!",
"You can now include shape short keys in markers to render shape icons instead of text!",
"Added mirrored variant of the painter",
"When placing tunnels, unnecessary belts inbetween are now removed!",
"You can now drag tunnels and they will automatically expand! (Just try it out, its intuitive)",
],
},
{
version: "1.1.13",
date: "15.06.2020",
entries: [
"Added shift modifier for faster pan (by jaysc)",
"Added Japanese translations",
"Added Portuguese (Portugal) translations",
"Updated icon for Spanish (Latin America) - It was showing a Spanish flag before",
"Updated existing translations",
],
},
{
version: "1.1.12",
date: "14.06.2020",
entries: [
"Huge performance improvements! The game should now run up to 60% faster!",
"Added norwegian translation",
],
},
{
version: "1.1.11",
date: "13.06.2020",
entries: [
"Pinned shapes are now smart, they dynamically update their goal and also unpin when no longer required. Completed objectives are now rendered transparent.",
"You can now cut areas, and also paste the last blueprint again! (by hexy)",
"You can now export your whole base as an image by pressing F3!",
"Improve upgrade number rounding, so there are no goals like '37.4k', instead it will now be '35k'",
"You can now configure the camera movement speed when using WASD (by mini-bomba)",
"Selecting an area now is relative to the world and thus does not move when moving the screen (by Dimava)",
"Allow higher tick-rates up to 500hz (This will burn your PC!)",
"Fix bug regarding number rounding",
"Fix dialog text being hardly readable in dark theme",
"Fix app not starting when the savegames were corrupted - there is now a better error message as well.",
"Further translation updates - Big thanks to all contributors!",
],
},
{
version: "1.1.10",
date: "12.06.2020",
entries: [
"There are now linux builds on steam! Please report any issues in the Discord!",
"Steam cloud saves are now available!",
"Added and update more translations (Big thank you to all translators!)",
"Prevent invalid connection if existing underground tunnel entrance exists (by jaysc)",
],
},
{
version: "1.1.9",
date: "11.06.2020",
entries: [
"Support for translations! Interested in helping out? Check out the <a target='_blank' href='https://github.com/tobspr/shapez.io/tree/master/translations'>translation guide</a>!",
"Update stacker artwork to clarify how it works",
"Update keybinding hints on the top left to be more accurate",
"Make it more clear when blueprints are unlocked when trying to use them",
"Fix pinned shape icons not being visible in dark mode",
"Fix being able to select buildings via hotkeys in map overview mode",
"Make shapes unpinnable in the upgrades tab (By hexy)",
],
},
{
version: "1.1.8",
date: "07.06.2020",
entries: [
"You can now purchase the standalone on steam! <a href='https://steam.shapez.io' target='blank'>View steam page</a>",
"Added ability to create markers in the demo, but only two.",
"Contest #01 has ended! I'll now work through the entries, select the 5 I like most and present them to the community to vote for!",
],
},
{
version: "1.1.7",
date: "04.06.2020",
entries: ["HOTFIX: Fix savegames not showing up on the standalone version"],
},
{
version: "1.1.6",
date: "04.06.2020",
entries: [
"The steam release will happen on the <strong>7th of June</strong> - Be sure to add it to your wishlist! <a href='https://steam.shapez.io' target='blank'>View on steam</a>",
"Fixed level complete dialog being blurred when the shop was opened before",
"Standalone: Increased icon visibility for windows builds",
"Web version: Fixed firefox not loading the game when browsing in private mode",
],
},
{
version: "1.1.5",
date: "03.06.2020",
entries: ["Added weekly contests!"],
},
{
version: "1.1.4",
date: "01.06.2020",
entries: ["Add 'interactive' tutorial for the first level to improve onboarding experience"],
},
{
version: "1.1.3",
date: "01.06.2020",
entries: [
"Added setting to configure zoom / mouse wheel / touchpad sensitivity",
"Fix belts being too slow when copied via blueprint (by Dimava)",
"Allow binding mouse buttons to actions (by Dimava)",
"Increase readability of certain HUD elements",
],
},
{
version: "1.1.2",
date: "30.05.2020",
entries: [
"The official trailer is now ready! Check it out <a href='https://www.youtube.com/watch?v=KyorY1uIqiQ' target='_blank'>here</a>!",
"The <a href='https://steam.shapez.io' target='_blank'>steam page</a> is now live!",
"Experimental linux builds are now available! Please give me feedback on them in the Discord",
"Allow hovering pinned shapes to enlarge them",
"Allow deselecting blueprints with right click and 'Q'",
"Move default key for deleting from 'X' to 'DEL'",
"Show confirmation when deleting more than 100 buildings",
"Reintroduce 'SPACE' keybinding to center on map",
"Improved keybinding hints",
"Fixed some keybindings showing as 'undefined'",
],
},
{
version: "1.1.1",
date: "28.05.2020",
entries: ["Fix crash when 'Show Hints' setting was turned off"],
},
{
version: "1.1.0",
date: "28.05.2020",
entries: [
"BLUEPRINTS! They are unlocked at level 12 and cost a special shape to build.",
"MAP MARKERS! Press 'M' to create a waypoint and be able to jump to it",
"Savegame levels are now shown in the main menu. For existing games, save them again to make the level show up.",
"Allow holding SHIFT to rotate counter clockwise",
"Added confirmation when deleting more than 500 buildings at a time",
"Added background to toolbar to increase contrast",
"Further decerase requirements of first levels",
"Pinned shapes now are saved",
"Allow placing extractors anywhere again, but they don't work at all if not placed on a resource",
"Show dialog explaining some keybindings after completing level 4",
"Fix keys being stuck when opening a dialog",
"Swapped shape order for painting upgrades",
"Allow changing all keybindings, including CTRL, ALT and SHIFT (by Dimava)",
"Fix cycling through keybindings selecting locked buildings as well (by Dimava)",
"There is now a github action, checking all pull requests with eslint. (by mrHedgehog)",
],
},
{
version: "1.0.4",
date: "26.05.2020",
entries: [
"Reduce cost of first painting upgrade, and change 'Shape Processing' to 'Cutting, Rotating & Stacking'",
"Add dialog after completing level 2 to check out the upgrades tab.",
"Allow changing the keybindings in the demo version",
],
},
{
version: "1.0.3",
date: "24.05.2020",
entries: [
"Reduced the amount of shapes required for the first 5 levels to make it easier to get into the game.",
],
},
{
version: "1.0.2",
date: "23.05.2020",
entries: [
"Introduced changelog",
"Removed 'early access' label because the game isn't actually early access - its in a pretty good state already! (No worries, a lot more updates will follow!)",
"Added a 'Show hint' button which shows a small video for almost all levels to help out",
"Now showing proper descriptions when completing levels, with instructions on what the gained reward does.",
"Show a landing page on mobile devices about the game not being ready to be played on mobile yet",
"Fix painters and mixers being affected by the shape processors upgrade and not the painter one",
"Added 'multiplace' setting which is equivalent to holding SHIFT all the time",
"Added keybindings to zoom in / zoom out",
"Tunnels now also show connection lines to tunnel exits, instead of just tunnel entries",
"Lots of minor fixes and improvements",
],
},
{
version: "1.0.1",
date: "21.05.2020",
entries: ["Initial release!"],
},
];

View File

@ -1,434 +1,443 @@
/* typehints:start */
import { Application } from "../application";
/* typehints:end */
import { Signal, STOP_PROPAGATION } from "./signal";
import { arrayDeleteValue, waitNextFrame } from "./utils";
import { ClickDetector } from "./click_detector";
import { SOUNDS } from "../platform/sound";
import { InputReceiver } from "./input_receiver";
import { FormElement } from "./modal_dialog_forms";
import { globalConfig } from "./config";
import { getStringForKeyCode } from "../game/key_action_mapper";
import { createLogger } from "./logging";
import { T } from "../translations";
const kbEnter = 13;
const kbCancel = 27;
const logger = createLogger("dialogs");
/**
* Basic text based dialog
*/
export class Dialog {
/**
*
* Constructs a new dialog with the given options
* @param {object} param0
* @param {Application} param0.app
* @param {string} param0.title Title of the dialog
* @param {string} param0.contentHTML Inner dialog html
* @param {Array<string>} param0.buttons
* Button list, each button contains of up to 3 parts seperated by ':'.
* Part 0: The id, one of the one defined in dialog_buttons.yaml
* Part 1: The style, either good, bad or misc
* Part 2 (optional): Additional parameters seperated by '/', available are:
* timeout: This button is only available after some waiting time
* kb_enter: This button is triggered by the enter key
* kb_escape This button is triggered by the escape key
* @param {string=} param0.type The dialog type, either "info" or "warn"
* @param {boolean=} param0.closeButton Whether this dialog has a close button
*/
constructor({ app, title, contentHTML, buttons, type = "info", closeButton = false }) {
this.app = app;
this.title = title;
this.contentHTML = contentHTML;
this.type = type;
this.buttonIds = buttons;
this.closeButton = closeButton;
this.closeRequested = new Signal();
this.buttonSignals = {};
for (let i = 0; i < buttons.length; ++i) {
if (G_IS_DEV && globalConfig.debug.disableTimedButtons) {
this.buttonIds[i] = this.buttonIds[i].replace(":timeout", "");
}
const buttonId = this.buttonIds[i].split(":")[0];
this.buttonSignals[buttonId] = new Signal();
}
this.timeouts = [];
this.clickDetectors = [];
this.inputReciever = new InputReceiver("dialog-" + this.title);
this.inputReciever.keydown.add(this.handleKeydown, this);
this.enterHandler = null;
this.escapeHandler = null;
}
/**
* Internal keydown handler
* @param {object} param0
* @param {number} param0.keyCode
* @param {boolean} param0.shift
* @param {boolean} param0.alt
*/
handleKeydown({ keyCode, shift, alt }) {
if (keyCode === kbEnter && this.enterHandler) {
this.internalButtonHandler(this.enterHandler);
return STOP_PROPAGATION;
}
if (keyCode === kbCancel && this.escapeHandler) {
this.internalButtonHandler(this.escapeHandler);
return STOP_PROPAGATION;
}
}
internalButtonHandler(id, ...payload) {
this.app.inputMgr.popReciever(this.inputReciever);
if (id !== "close-button") {
this.buttonSignals[id].dispatch(...payload);
}
this.closeRequested.dispatch();
}
createElement() {
const elem = document.createElement("div");
elem.classList.add("ingameDialog");
this.dialogElem = document.createElement("div");
this.dialogElem.classList.add("dialogInner");
if (this.type) {
this.dialogElem.classList.add(this.type);
}
elem.appendChild(this.dialogElem);
const title = document.createElement("h1");
title.innerText = this.title;
title.classList.add("title");
this.dialogElem.appendChild(title);
if (this.closeButton) {
this.dialogElem.classList.add("hasCloseButton");
const closeBtn = document.createElement("button");
closeBtn.classList.add("closeButton");
this.trackClicks(closeBtn, () => this.internalButtonHandler("close-button"), {
applyCssClass: "pressedSmallElement",
});
title.appendChild(closeBtn);
this.inputReciever.backButton.add(() => this.internalButtonHandler("close-button"));
}
const content = document.createElement("div");
content.classList.add("content");
content.innerHTML = this.contentHTML;
this.dialogElem.appendChild(content);
if (this.buttonIds.length > 0) {
const buttons = document.createElement("div");
buttons.classList.add("buttons");
// Create buttons
for (let i = 0; i < this.buttonIds.length; ++i) {
const [buttonId, buttonStyle, rawParams] = this.buttonIds[i].split(":");
const button = document.createElement("button");
button.classList.add("button");
button.classList.add("styledButton");
button.classList.add(buttonStyle);
button.innerText = T.dialogs.buttons[buttonId];
const params = (rawParams || "").split("/");
const useTimeout = params.indexOf("timeout") >= 0;
const isEnter = params.indexOf("enter") >= 0;
const isEscape = params.indexOf("escape") >= 0;
if (isEscape && this.closeButton) {
logger.warn("Showing dialog with close button, and additional cancel button");
}
if (useTimeout) {
button.classList.add("timedButton");
const timeout = setTimeout(() => {
button.classList.remove("timedButton");
arrayDeleteValue(this.timeouts, timeout);
}, 5000);
this.timeouts.push(timeout);
}
if (isEnter || isEscape) {
// if (this.app.settings.getShowKeyboardShortcuts()) {
// Show keybinding
const spacer = document.createElement("code");
spacer.classList.add("keybinding");
spacer.innerHTML = getStringForKeyCode(isEnter ? kbEnter : kbCancel);
button.appendChild(spacer);
// }
if (isEnter) {
this.enterHandler = buttonId;
}
if (isEscape) {
this.escapeHandler = buttonId;
}
}
this.trackClicks(button, () => this.internalButtonHandler(buttonId));
buttons.appendChild(button);
}
this.dialogElem.appendChild(buttons);
} else {
this.dialogElem.classList.add("buttonless");
}
this.element = elem;
this.app.inputMgr.pushReciever(this.inputReciever);
return this.element;
}
setIndex(index) {
this.element.style.zIndex = index;
}
destroy() {
if (!this.element) {
assert(false, "Tried to destroy dialog twice");
return;
}
// We need to do this here, because if the backbutton event gets
// dispatched to the modal dialogs, it will not call the internalButtonHandler,
// and thus our receiver stays attached the whole time
this.app.inputMgr.destroyReceiver(this.inputReciever);
for (let i = 0; i < this.clickDetectors.length; ++i) {
this.clickDetectors[i].cleanup();
}
this.clickDetectors = [];
this.element.remove();
this.element = null;
for (let i = 0; i < this.timeouts.length; ++i) {
clearTimeout(this.timeouts[i]);
}
this.timeouts = [];
}
hide() {
this.element.classList.remove("visible");
}
show() {
this.element.classList.add("visible");
}
/**
* Helper method to track clicks on an element
* @param {Element} elem
* @param {function():void} handler
* @param {import("./click_detector").ClickDetectorConstructorArgs=} args
* @returns {ClickDetector}
*/
trackClicks(elem, handler, args = {}) {
const detector = new ClickDetector(elem, args);
detector.click.add(handler, this);
this.clickDetectors.push(detector);
return detector;
}
}
/**
* Dialog which simply shows a loading spinner
*/
export class DialogLoading extends Dialog {
constructor(app) {
super({
app,
title: "",
contentHTML: "",
buttons: [],
type: "loading",
});
// Loading dialog can not get closed with back button
this.inputReciever.backButton.removeAll();
this.inputReciever.context = "dialog-loading";
}
createElement() {
const elem = document.createElement("div");
elem.classList.add("ingameDialog");
elem.classList.add("loadingDialog");
this.element = elem;
const loader = document.createElement("div");
loader.classList.add("prefab_LoadingTextWithAnim");
loader.classList.add("loadingIndicator");
loader.innerText = T.global.loading;
elem.appendChild(loader);
this.app.inputMgr.pushReciever(this.inputReciever);
return elem;
}
}
export class DialogOptionChooser extends Dialog {
constructor({ app, title, options }) {
let html = "<div class='optionParent'>";
options.options.forEach(({ value, text, desc = null, iconPrefix = null }) => {
const descHtml = desc ? `<span class="desc">${desc}</span>` : "";
let iconHtml = iconPrefix ? `<span class="icon icon-${iconPrefix}-${value}"></span>` : "";
html += `
<div class='option ${value === options.active ? "active" : ""} ${
iconPrefix ? "hasIcon" : ""
}' data-optionvalue='${value}'>
${iconHtml}
<span class='title'>${text}</span>
${descHtml}
</div>
`;
});
html += "</div>";
super({
app,
title,
contentHTML: html,
buttons: [],
type: "info",
closeButton: true,
});
this.options = options;
this.initialOption = options.active;
this.buttonSignals.optionSelected = new Signal();
}
createElement() {
const div = super.createElement();
this.dialogElem.classList.add("optionChooserDialog");
div.querySelectorAll("[data-optionvalue]").forEach(handle => {
const value = handle.getAttribute("data-optionvalue");
if (!handle) {
logger.error("Failed to bind option value in dialog:", value);
return;
}
// Need click detector here to forward elements, otherwise scrolling does not work
const detector = new ClickDetector(handle, {
consumeEvents: false,
preventDefault: false,
clickSound: null,
applyCssClass: "pressedOption",
targetOnly: true,
});
this.clickDetectors.push(detector);
if (value !== this.initialOption) {
detector.click.add(() => {
const selected = div.querySelector(".option.active");
if (selected) {
selected.classList.remove("active");
} else {
logger.warn("No selected option");
}
handle.classList.add("active");
this.app.sound.playUiSound(SOUNDS.uiClick);
this.internalButtonHandler("optionSelected", value);
});
}
});
return div;
}
}
export class DialogWithForm extends Dialog {
/**
*
* @param {object} param0
* @param {Application} param0.app
* @param {string} param0.title
* @param {string} param0.desc
* @param {array=} param0.buttons
* @param {string=} param0.confirmButtonId
* @param {string=} param0.extraButton
* @param {Array<FormElement>} param0.formElements
*/
constructor({ app, title, desc, formElements, buttons = ["cancel", "ok:good"], confirmButtonId = "ok" }) {
let html = "";
html += desc + "<br>";
for (let i = 0; i < formElements.length; ++i) {
html += formElements[i].getHtml();
}
super({
app,
title: title,
contentHTML: html,
buttons: buttons,
type: "info",
closeButton: true,
});
this.confirmButtonId = confirmButtonId;
this.formElements = formElements;
this.enterHandler = confirmButtonId;
}
internalButtonHandler(id, ...payload) {
if (id === this.confirmButtonId) {
if (this.hasAnyInvalid()) {
this.dialogElem.classList.remove("errorShake");
waitNextFrame().then(() => {
if (this.dialogElem) {
this.dialogElem.classList.add("errorShake");
}
});
this.app.sound.playUiSound(SOUNDS.uiError);
return;
}
}
super.internalButtonHandler(id, payload);
}
hasAnyInvalid() {
for (let i = 0; i < this.formElements.length; ++i) {
if (!this.formElements[i].isValid()) {
return true;
}
}
return false;
}
createElement() {
const div = super.createElement();
for (let i = 0; i < this.formElements.length; ++i) {
const elem = this.formElements[i];
elem.bindEvents(div, this.clickDetectors);
}
waitNextFrame().then(() => {
this.formElements[0].focus();
});
return div;
}
}
/* typehints:start */
import { Application } from "../application";
/* typehints:end */
import { Signal, STOP_PROPAGATION } from "./signal";
import { arrayDeleteValue, waitNextFrame } from "./utils";
import { ClickDetector } from "./click_detector";
import { SOUNDS } from "../platform/sound";
import { InputReceiver } from "./input_receiver";
import { FormElement } from "./modal_dialog_forms";
import { globalConfig } from "./config";
import { getStringForKeyCode } from "../game/key_action_mapper";
import { createLogger } from "./logging";
import { T } from "../translations";
const kbEnter = 13;
const kbCancel = 27;
const logger = createLogger("dialogs");
/**
* Basic text based dialog
*/
export class Dialog {
/**
*
* Constructs a new dialog with the given options
* @param {object} param0
* @param {Application} param0.app
* @param {string} param0.title Title of the dialog
* @param {string} param0.contentHTML Inner dialog html
* @param {Array<string>} param0.buttons
* Button list, each button contains of up to 3 parts seperated by ':'.
* Part 0: The id, one of the one defined in dialog_buttons.yaml
* Part 1: The style, either good, bad or misc
* Part 2 (optional): Additional parameters seperated by '/', available are:
* timeout: This button is only available after some waiting time
* kb_enter: This button is triggered by the enter key
* kb_escape This button is triggered by the escape key
* @param {string=} param0.type The dialog type, either "info" or "warn"
* @param {boolean=} param0.closeButton Whether this dialog has a close button
*/
constructor({ app, title, contentHTML, buttons, type = "info", closeButton = false }) {
this.app = app;
this.title = title;
this.contentHTML = contentHTML;
this.type = type;
this.buttonIds = buttons;
this.closeButton = closeButton;
this.closeRequested = new Signal();
this.buttonSignals = {};
for (let i = 0; i < buttons.length; ++i) {
if (G_IS_DEV && globalConfig.debug.disableTimedButtons) {
this.buttonIds[i] = this.buttonIds[i].replace(":timeout", "");
}
const buttonId = this.buttonIds[i].split(":")[0];
this.buttonSignals[buttonId] = new Signal();
}
this.timeouts = [];
this.clickDetectors = [];
this.inputReciever = new InputReceiver("dialog-" + this.title);
this.inputReciever.keydown.add(this.handleKeydown, this);
this.enterHandler = null;
this.escapeHandler = null;
}
/**
* Internal keydown handler
* @param {object} param0
* @param {number} param0.keyCode
* @param {boolean} param0.shift
* @param {boolean} param0.alt
*/
handleKeydown({ keyCode, shift, alt }) {
if (keyCode === kbEnter && this.enterHandler) {
this.internalButtonHandler(this.enterHandler);
return STOP_PROPAGATION;
}
if (keyCode === kbCancel && this.escapeHandler) {
this.internalButtonHandler(this.escapeHandler);
return STOP_PROPAGATION;
}
}
internalButtonHandler(id, ...payload) {
this.app.inputMgr.popReciever(this.inputReciever);
if (id !== "close-button") {
this.buttonSignals[id].dispatch(...payload);
}
this.closeRequested.dispatch();
}
createElement() {
const elem = document.createElement("div");
elem.classList.add("ingameDialog");
this.dialogElem = document.createElement("div");
this.dialogElem.classList.add("dialogInner");
if (this.type) {
this.dialogElem.classList.add(this.type);
}
elem.appendChild(this.dialogElem);
const title = document.createElement("h1");
title.innerText = this.title;
title.classList.add("title");
this.dialogElem.appendChild(title);
if (this.closeButton) {
this.dialogElem.classList.add("hasCloseButton");
const closeBtn = document.createElement("button");
closeBtn.classList.add("closeButton");
this.trackClicks(closeBtn, () => this.internalButtonHandler("close-button"), {
applyCssClass: "pressedSmallElement",
});
title.appendChild(closeBtn);
this.inputReciever.backButton.add(() => this.internalButtonHandler("close-button"));
}
const content = document.createElement("div");
content.classList.add("content");
content.innerHTML = this.contentHTML;
this.dialogElem.appendChild(content);
if (this.buttonIds.length > 0) {
const buttons = document.createElement("div");
buttons.classList.add("buttons");
// Create buttons
for (let i = 0; i < this.buttonIds.length; ++i) {
const [buttonId, buttonStyle, rawParams] = this.buttonIds[i].split(":");
const button = document.createElement("button");
button.classList.add("button");
button.classList.add("styledButton");
button.classList.add(buttonStyle);
button.innerText = T.dialogs.buttons[buttonId];
const params = (rawParams || "").split("/");
const useTimeout = params.indexOf("timeout") >= 0;
const isEnter = params.indexOf("enter") >= 0;
const isEscape = params.indexOf("escape") >= 0;
if (isEscape && this.closeButton) {
logger.warn("Showing dialog with close button, and additional cancel button");
}
if (useTimeout) {
button.classList.add("timedButton");
const timeout = setTimeout(() => {
button.classList.remove("timedButton");
arrayDeleteValue(this.timeouts, timeout);
}, 5000);
this.timeouts.push(timeout);
}
if (isEnter || isEscape) {
// if (this.app.settings.getShowKeyboardShortcuts()) {
// Show keybinding
const spacer = document.createElement("code");
spacer.classList.add("keybinding");
spacer.innerHTML = getStringForKeyCode(isEnter ? kbEnter : kbCancel);
button.appendChild(spacer);
// }
if (isEnter) {
this.enterHandler = buttonId;
}
if (isEscape) {
this.escapeHandler = buttonId;
}
}
this.trackClicks(button, () => this.internalButtonHandler(buttonId));
buttons.appendChild(button);
}
this.dialogElem.appendChild(buttons);
} else {
this.dialogElem.classList.add("buttonless");
}
this.element = elem;
this.app.inputMgr.pushReciever(this.inputReciever);
return this.element;
}
setIndex(index) {
this.element.style.zIndex = index;
}
destroy() {
if (!this.element) {
assert(false, "Tried to destroy dialog twice");
return;
}
// We need to do this here, because if the backbutton event gets
// dispatched to the modal dialogs, it will not call the internalButtonHandler,
// and thus our receiver stays attached the whole time
this.app.inputMgr.destroyReceiver(this.inputReciever);
for (let i = 0; i < this.clickDetectors.length; ++i) {
this.clickDetectors[i].cleanup();
}
this.clickDetectors = [];
this.element.remove();
this.element = null;
for (let i = 0; i < this.timeouts.length; ++i) {
clearTimeout(this.timeouts[i]);
}
this.timeouts = [];
}
hide() {
this.element.classList.remove("visible");
}
show() {
this.element.classList.add("visible");
}
/**
* Helper method to track clicks on an element
* @param {Element} elem
* @param {function():void} handler
* @param {import("./click_detector").ClickDetectorConstructorArgs=} args
* @returns {ClickDetector}
*/
trackClicks(elem, handler, args = {}) {
const detector = new ClickDetector(elem, args);
detector.click.add(handler, this);
this.clickDetectors.push(detector);
return detector;
}
}
/**
* Dialog which simply shows a loading spinner
*/
export class DialogLoading extends Dialog {
constructor(app) {
super({
app,
title: "",
contentHTML: "",
buttons: [],
type: "loading",
});
// Loading dialog can not get closed with back button
this.inputReciever.backButton.removeAll();
this.inputReciever.context = "dialog-loading";
}
createElement() {
const elem = document.createElement("div");
elem.classList.add("ingameDialog");
elem.classList.add("loadingDialog");
this.element = elem;
const loader = document.createElement("div");
loader.classList.add("prefab_LoadingTextWithAnim");
loader.classList.add("loadingIndicator");
loader.innerText = T.global.loading;
elem.appendChild(loader);
this.app.inputMgr.pushReciever(this.inputReciever);
return elem;
}
}
export class DialogOptionChooser extends Dialog {
constructor({ app, title, options }) {
let html = "<div class='optionParent'>";
options.options.forEach(({ value, text, desc = null, iconPrefix = null }) => {
const descHtml = desc ? `<span class="desc">${desc}</span>` : "";
let iconHtml = iconPrefix ? `<span class="icon icon-${iconPrefix}-${value}"></span>` : "";
html += `
<div class='option ${value === options.active ? "active" : ""} ${
iconPrefix ? "hasIcon" : ""
}' data-optionvalue='${value}'>
${iconHtml}
<span class='title'>${text}</span>
${descHtml}
</div>
`;
});
html += "</div>";
super({
app,
title,
contentHTML: html,
buttons: [],
type: "info",
closeButton: true,
});
this.options = options;
this.initialOption = options.active;
this.buttonSignals.optionSelected = new Signal();
}
createElement() {
const div = super.createElement();
this.dialogElem.classList.add("optionChooserDialog");
div.querySelectorAll("[data-optionvalue]").forEach(handle => {
const value = handle.getAttribute("data-optionvalue");
if (!handle) {
logger.error("Failed to bind option value in dialog:", value);
return;
}
// Need click detector here to forward elements, otherwise scrolling does not work
const detector = new ClickDetector(handle, {
consumeEvents: false,
preventDefault: false,
clickSound: null,
applyCssClass: "pressedOption",
targetOnly: true,
});
this.clickDetectors.push(detector);
if (value !== this.initialOption) {
detector.click.add(() => {
const selected = div.querySelector(".option.active");
if (selected) {
selected.classList.remove("active");
} else {
logger.warn("No selected option");
}
handle.classList.add("active");
this.app.sound.playUiSound(SOUNDS.uiClick);
this.internalButtonHandler("optionSelected", value);
});
}
});
return div;
}
}
export class DialogWithForm extends Dialog {
/**
*
* @param {object} param0
* @param {Application} param0.app
* @param {string} param0.title
* @param {string} param0.desc
* @param {array=} param0.buttons
* @param {string=} param0.confirmButtonId
* @param {string=} param0.extraButton
* @param {boolean=} param0.closeButton
* @param {Array<FormElement>} param0.formElements
*/
constructor({
app,
title,
desc,
formElements,
buttons = ["cancel", "ok:good"],
confirmButtonId = "ok",
closeButton = true,
}) {
let html = "";
html += desc + "<br>";
for (let i = 0; i < formElements.length; ++i) {
html += formElements[i].getHtml();
}
super({
app,
title: title,
contentHTML: html,
buttons: buttons,
type: "info",
closeButton,
});
this.confirmButtonId = confirmButtonId;
this.formElements = formElements;
this.enterHandler = confirmButtonId;
}
internalButtonHandler(id, ...payload) {
if (id === this.confirmButtonId) {
if (this.hasAnyInvalid()) {
this.dialogElem.classList.remove("errorShake");
waitNextFrame().then(() => {
if (this.dialogElem) {
this.dialogElem.classList.add("errorShake");
}
});
this.app.sound.playUiSound(SOUNDS.uiError);
return;
}
}
super.internalButtonHandler(id, payload);
}
hasAnyInvalid() {
for (let i = 0; i < this.formElements.length; ++i) {
if (!this.formElements[i].isValid()) {
return true;
}
}
return false;
}
createElement() {
const div = super.createElement();
for (let i = 0; i < this.formElements.length; ++i) {
const elem = this.formElements[i];
elem.bindEvents(div, this.clickDetectors);
}
waitNextFrame().then(() => {
this.formElements[0].focus();
});
return div;
}
}

View File

@ -53,27 +53,6 @@ export class Rectangle {
return a.left <= b.right && b.left <= a.right && a.top <= b.bottom && b.top <= a.bottom;
}
/**
* Returns a rectangle arround a rotated point
* @param {Array<Vector>} points
* @param {number} angle
* @returns {Rectangle}
*/
static getAroundPointsRotated(points, angle) {
let minX = 1e10;
let minY = 1e10;
let maxX = -1e10;
let maxY = -1e10;
for (let i = 0; i < points.length; ++i) {
const rotated = points[i].rotated(angle);
minX = Math.min(minX, rotated.x);
minY = Math.min(minY, rotated.y);
maxX = Math.max(maxX, rotated.x);
maxY = Math.max(maxY, rotated.y);
}
return new Rectangle(minX, minY, maxX - minX, maxY - minY);
}
/**
* Copies this instance
* @returns {Rectangle}
@ -82,28 +61,6 @@ export class Rectangle {
return new Rectangle(this.x, this.y, this.w, this.h);
}
/**
* Ensures the rectangle contains the given square
* @param {number} centerX
* @param {number} centerY
* @param {number} halfWidth
* @param {number} halfHeight
*/
extendBySquare(centerX, centerY, halfWidth, halfHeight) {
if (this.isEmpty()) {
// Just assign values since this rectangle is empty
this.x = centerX - halfWidth;
this.y = centerY - halfHeight;
this.w = halfWidth * 2;
this.h = halfHeight * 2;
} else {
this.setLeft(Math.min(this.x, centerX - halfWidth));
this.setRight(Math.max(this.right(), centerX + halfWidth));
this.setTop(Math.min(this.y, centerY - halfHeight));
this.setBottom(Math.max(this.bottom(), centerY + halfHeight));
}
}
/**
* Returns if this rectangle is empty
* @returns {boolean}
@ -259,14 +216,6 @@ export class Rectangle {
return new Rectangle(this.x - amount, this.y - amount, this.w + 2 * amount, this.h + 2 * amount);
}
/**
* Helper for computing a culling area. Returns the top left tile
* @returns {Vector}
*/
getMinStartTile() {
return new Vector(this.x, this.y).snapWorldToTile();
}
/**
* Returns if the given rectangle is contained
* @param {Rectangle} rect
@ -394,7 +343,7 @@ export class Rectangle {
}
/**
* Returns a new recangle in tile space which includes all tiles which are visible in this rect
* Returns a new rectangle in tile space which includes all tiles which are visible in this rect
* @returns {Rectangle}
*/
toTileCullRectangle() {

View File

@ -1,122 +1,122 @@
import { formatItemsPerSecond } from "../../core/utils";
import { enumDirection, Vector } from "../../core/vector";
import { T } from "../../translations";
import { ItemAcceptorComponent } from "../components/item_acceptor";
import { ItemEjectorComponent } from "../components/item_ejector";
import { enumItemProcessorTypes, ItemProcessorComponent } from "../components/item_processor";
import { Entity } from "../entity";
import { defaultBuildingVariant, MetaBuilding } from "../meta_building";
import { GameRoot } from "../root";
import { enumHubGoalRewards } from "../tutorial_goals";
/** @enum {string} */
export const enumCutterVariants = { quad: "quad" };
export class MetaCutterBuilding extends MetaBuilding {
constructor() {
super("cutter");
}
getSilhouetteColor() {
return "#7dcda2";
}
getDimensions(variant) {
switch (variant) {
case defaultBuildingVariant:
return new Vector(2, 1);
case enumCutterVariants.quad:
return new Vector(4, 1);
default:
assertAlways(false, "Unknown splitter variant: " + variant);
}
}
/**
* @param {GameRoot} root
* @param {string} variant
* @returns {Array<[string, string]>}
*/
getAdditionalStatistics(root, variant) {
const speed = root.hubGoals.getProcessorBaseSpeed(
variant === enumCutterVariants.quad
? enumItemProcessorTypes.cutterQuad
: enumItemProcessorTypes.cutter
);
return [[T.ingame.buildingPlacement.infoTexts.speed, formatItemsPerSecond(speed)]];
}
/**
* @param {GameRoot} root
*/
getAvailableVariants(root) {
if (root.hubGoals.isRewardUnlocked(enumHubGoalRewards.reward_cutter_quad)) {
return [defaultBuildingVariant, enumCutterVariants.quad];
}
return super.getAvailableVariants(root);
}
/**
* @param {GameRoot} root
*/
getIsUnlocked(root) {
return root.hubGoals.isRewardUnlocked(enumHubGoalRewards.reward_cutter_and_trash);
}
/**
* Creates the entity at the given location
* @param {Entity} entity
*/
setupEntityComponents(entity) {
entity.addComponent(
new ItemProcessorComponent({
inputsPerCharge: 1,
processorType: enumItemProcessorTypes.cutter,
})
);
entity.addComponent(new ItemEjectorComponent({}));
entity.addComponent(
new ItemAcceptorComponent({
slots: [
{
pos: new Vector(0, 0),
directions: [enumDirection.bottom],
filter: "shape",
},
],
})
);
}
/**
*
* @param {Entity} entity
* @param {number} rotationVariant
* @param {string} variant
*/
updateVariants(entity, rotationVariant, variant) {
switch (variant) {
case defaultBuildingVariant: {
entity.components.ItemEjector.setSlots([
{ pos: new Vector(0, 0), direction: enumDirection.top },
{ pos: new Vector(1, 0), direction: enumDirection.top },
]);
entity.components.ItemProcessor.type = enumItemProcessorTypes.cutter;
break;
}
case enumCutterVariants.quad: {
entity.components.ItemEjector.setSlots([
{ pos: new Vector(0, 0), direction: enumDirection.top },
{ pos: new Vector(1, 0), direction: enumDirection.top },
{ pos: new Vector(2, 0), direction: enumDirection.top },
{ pos: new Vector(3, 0), direction: enumDirection.top },
]);
entity.components.ItemProcessor.type = enumItemProcessorTypes.cutterQuad;
break;
}
default:
assertAlways(false, "Unknown painter variant: " + variant);
}
}
}
import { formatItemsPerSecond } from "../../core/utils";
import { enumDirection, Vector } from "../../core/vector";
import { T } from "../../translations";
import { ItemAcceptorComponent } from "../components/item_acceptor";
import { ItemEjectorComponent } from "../components/item_ejector";
import { enumItemProcessorTypes, ItemProcessorComponent } from "../components/item_processor";
import { Entity } from "../entity";
import { defaultBuildingVariant, MetaBuilding } from "../meta_building";
import { GameRoot } from "../root";
import { enumHubGoalRewards } from "../tutorial_goals";
/** @enum {string} */
export const enumCutterVariants = { quad: "quad" };
export class MetaCutterBuilding extends MetaBuilding {
constructor() {
super("cutter");
}
getSilhouetteColor() {
return "#7dcda2";
}
getDimensions(variant) {
switch (variant) {
case defaultBuildingVariant:
return new Vector(2, 1);
case enumCutterVariants.quad:
return new Vector(4, 1);
default:
assertAlways(false, "Unknown cutter variant: " + variant);
}
}
/**
* @param {GameRoot} root
* @param {string} variant
* @returns {Array<[string, string]>}
*/
getAdditionalStatistics(root, variant) {
const speed = root.hubGoals.getProcessorBaseSpeed(
variant === enumCutterVariants.quad
? enumItemProcessorTypes.cutterQuad
: enumItemProcessorTypes.cutter
);
return [[T.ingame.buildingPlacement.infoTexts.speed, formatItemsPerSecond(speed)]];
}
/**
* @param {GameRoot} root
*/
getAvailableVariants(root) {
if (root.hubGoals.isRewardUnlocked(enumHubGoalRewards.reward_cutter_quad)) {
return [defaultBuildingVariant, enumCutterVariants.quad];
}
return super.getAvailableVariants(root);
}
/**
* @param {GameRoot} root
*/
getIsUnlocked(root) {
return root.hubGoals.isRewardUnlocked(enumHubGoalRewards.reward_cutter_and_trash);
}
/**
* Creates the entity at the given location
* @param {Entity} entity
*/
setupEntityComponents(entity) {
entity.addComponent(
new ItemProcessorComponent({
inputsPerCharge: 1,
processorType: enumItemProcessorTypes.cutter,
})
);
entity.addComponent(new ItemEjectorComponent({}));
entity.addComponent(
new ItemAcceptorComponent({
slots: [
{
pos: new Vector(0, 0),
directions: [enumDirection.bottom],
filter: "shape",
},
],
})
);
}
/**
*
* @param {Entity} entity
* @param {number} rotationVariant
* @param {string} variant
*/
updateVariants(entity, rotationVariant, variant) {
switch (variant) {
case defaultBuildingVariant: {
entity.components.ItemEjector.setSlots([
{ pos: new Vector(0, 0), direction: enumDirection.top },
{ pos: new Vector(1, 0), direction: enumDirection.top },
]);
entity.components.ItemProcessor.type = enumItemProcessorTypes.cutter;
break;
}
case enumCutterVariants.quad: {
entity.components.ItemEjector.setSlots([
{ pos: new Vector(0, 0), direction: enumDirection.top },
{ pos: new Vector(1, 0), direction: enumDirection.top },
{ pos: new Vector(2, 0), direction: enumDirection.top },
{ pos: new Vector(3, 0), direction: enumDirection.top },
]);
entity.components.ItemProcessor.type = enumItemProcessorTypes.cutterQuad;
break;
}
default:
assertAlways(false, "Unknown painter variant: " + variant);
}
}
}

View File

@ -1,61 +1,57 @@
import { enumDirection, Vector } from "../../core/vector";
import { enumPinSlotType, WiredPinsComponent } from "../components/wired_pins";
import { Entity } from "../entity";
import { MetaBuilding } from "../meta_building";
import { GameRoot } from "../root";
import { LeverComponent } from "../components/lever";
export class MetaLeverBuilding extends MetaBuilding {
constructor() {
super("lever");
}
getSilhouetteColor() {
// @todo: Render differently based on if its activated or not
return "#1a678b";
}
/**
* @param {GameRoot} root
*/
getIsUnlocked(root) {
// @todo
return true;
}
getIsRotateable() {
return false;
}
getDimensions() {
return new Vector(1, 1);
}
getSprite() {
return null;
}
getShowWiresLayerPreview() {
return true;
}
/**
* Creates the entity at the given location
* @param {Entity} entity
*/
setupEntityComponents(entity) {
entity.addComponent(
new WiredPinsComponent({
slots: [
{
pos: new Vector(0, 0),
direction: enumDirection.top,
type: enumPinSlotType.logicalEjector,
},
],
})
);
entity.addComponent(new LeverComponent({}));
}
}
import { enumDirection, Vector } from "../../core/vector";
import { enumPinSlotType, WiredPinsComponent } from "../components/wired_pins";
import { Entity } from "../entity";
import { MetaBuilding } from "../meta_building";
import { GameRoot } from "../root";
import { LeverComponent } from "../components/lever";
export class MetaLeverBuilding extends MetaBuilding {
constructor() {
super("lever");
}
getSilhouetteColor() {
// @todo: Render differently based on if its activated or not
return "#1a678b";
}
/**
* @param {GameRoot} root
*/
getIsUnlocked(root) {
// @todo
return true;
}
getDimensions() {
return new Vector(1, 1);
}
getSprite() {
return null;
}
getShowWiresLayerPreview() {
return true;
}
/**
* Creates the entity at the given location
* @param {Entity} entity
*/
setupEntityComponents(entity) {
entity.addComponent(
new WiredPinsComponent({
slots: [
{
pos: new Vector(0, 0),
direction: enumDirection.top,
type: enumPinSlotType.logicalEjector,
},
],
})
);
entity.addComponent(new LeverComponent({}));
}
}

View File

@ -1,158 +1,197 @@
import { enumDirection, Vector } from "../../core/vector";
import { ItemAcceptorComponent } from "../components/item_acceptor";
import { ItemEjectorComponent } from "../components/item_ejector";
import { enumItemProcessorTypes, ItemProcessorComponent } from "../components/item_processor";
import { Entity } from "../entity";
import { MetaBuilding, defaultBuildingVariant } from "../meta_building";
import { GameRoot } from "../root";
import { enumHubGoalRewards } from "../tutorial_goals";
import { T } from "../../translations";
import { formatItemsPerSecond } from "../../core/utils";
import { BeltUnderlaysComponent } from "../components/belt_underlays";
/** @enum {string} */
export const enumSplitterVariants = { compact: "compact", compactInverse: "compact-inverse" };
export class MetaSplitterBuilding extends MetaBuilding {
constructor() {
super("splitter");
}
getDimensions(variant) {
switch (variant) {
case defaultBuildingVariant:
return new Vector(2, 1);
case enumSplitterVariants.compact:
case enumSplitterVariants.compactInverse:
return new Vector(1, 1);
default:
assertAlways(false, "Unknown splitter variant: " + variant);
}
}
/**
* @param {GameRoot} root
* @param {string} variant
* @returns {Array<[string, string]>}
*/
getAdditionalStatistics(root, variant) {
const speed = root.hubGoals.getProcessorBaseSpeed(enumItemProcessorTypes.splitter);
return [[T.ingame.buildingPlacement.infoTexts.speed, formatItemsPerSecond(speed)]];
}
getSilhouetteColor() {
return "#444";
}
/**
* @param {GameRoot} root
*/
getAvailableVariants(root) {
if (root.hubGoals.isRewardUnlocked(enumHubGoalRewards.reward_splitter_compact)) {
return [
defaultBuildingVariant,
enumSplitterVariants.compact,
enumSplitterVariants.compactInverse,
];
}
return super.getAvailableVariants(root);
}
/**
* @param {GameRoot} root
*/
getIsUnlocked(root) {
return root.hubGoals.isRewardUnlocked(enumHubGoalRewards.reward_splitter);
}
/**
* Creates the entity at the given location
* @param {Entity} entity
*/
setupEntityComponents(entity) {
entity.addComponent(
new ItemAcceptorComponent({
slots: [], // set later
})
);
entity.addComponent(
new ItemProcessorComponent({
inputsPerCharge: 1,
processorType: enumItemProcessorTypes.splitter,
})
);
entity.addComponent(
new ItemEjectorComponent({
slots: [], // set later
})
);
entity.addComponent(new BeltUnderlaysComponent({ underlays: [] }));
}
/**
*
* @param {Entity} entity
* @param {number} rotationVariant
* @param {string} variant
*/
updateVariants(entity, rotationVariant, variant) {
switch (variant) {
case defaultBuildingVariant: {
entity.components.ItemAcceptor.setSlots([
{
pos: new Vector(0, 0),
directions: [enumDirection.bottom],
},
{
pos: new Vector(1, 0),
directions: [enumDirection.bottom],
},
]);
entity.components.ItemEjector.setSlots([
{ pos: new Vector(0, 0), direction: enumDirection.top },
{ pos: new Vector(1, 0), direction: enumDirection.top },
]);
entity.components.BeltUnderlays.underlays = [
{ pos: new Vector(0, 0), direction: enumDirection.top },
{ pos: new Vector(1, 0), direction: enumDirection.top },
];
break;
}
case enumSplitterVariants.compact:
case enumSplitterVariants.compactInverse: {
entity.components.ItemAcceptor.setSlots([
{
pos: new Vector(0, 0),
directions: [enumDirection.bottom],
},
{
pos: new Vector(0, 0),
directions: [
variant === enumSplitterVariants.compactInverse
? enumDirection.left
: enumDirection.right,
],
},
]);
entity.components.ItemEjector.setSlots([
{ pos: new Vector(0, 0), direction: enumDirection.top },
]);
entity.components.BeltUnderlays.underlays = [
{ pos: new Vector(0, 0), direction: enumDirection.top },
];
break;
}
default:
assertAlways(false, "Unknown painter variant: " + variant);
}
}
}
import { enumDirection, Vector } from "../../core/vector";
import { ItemAcceptorComponent } from "../components/item_acceptor";
import { ItemEjectorComponent } from "../components/item_ejector";
import { enumItemProcessorTypes, ItemProcessorComponent } from "../components/item_processor";
import { Entity } from "../entity";
import { MetaBuilding, defaultBuildingVariant } from "../meta_building";
import { GameRoot } from "../root";
import { enumHubGoalRewards } from "../tutorial_goals";
import { T } from "../../translations";
import { formatItemsPerSecond } from "../../core/utils";
import { BeltUnderlaysComponent } from "../components/belt_underlays";
/** @enum {string} */
export const enumSplitterVariants = {
compact: "compact",
compactInverse: "compact-inverse",
compactMerge: "compact-merge",
compactMergeInverse: "compact-merge-inverse",
};
export class MetaSplitterBuilding extends MetaBuilding {
constructor() {
super("splitter");
}
getDimensions(variant) {
switch (variant) {
case defaultBuildingVariant:
return new Vector(2, 1);
case enumSplitterVariants.compact:
case enumSplitterVariants.compactInverse:
case enumSplitterVariants.compactMerge:
case enumSplitterVariants.compactMergeInverse:
return new Vector(1, 1);
default:
assertAlways(false, "Unknown splitter variant: " + variant);
}
}
/**
* @param {GameRoot} root
* @param {string} variant
* @returns {Array<[string, string]>}
*/
getAdditionalStatistics(root, variant) {
const speed = root.hubGoals.getProcessorBaseSpeed(enumItemProcessorTypes.splitter);
return [[T.ingame.buildingPlacement.infoTexts.speed, formatItemsPerSecond(speed)]];
}
getSilhouetteColor() {
return "#444";
}
/**
* @param {GameRoot} root
*/
getAvailableVariants(root) {
let available = [defaultBuildingVariant];
if (root.hubGoals.isRewardUnlocked(enumHubGoalRewards.reward_splitter_compact)) {
available.push(enumSplitterVariants.compact, enumSplitterVariants.compactInverse);
}
if (root.hubGoals.isRewardUnlocked(enumHubGoalRewards.reward_merger_compact)) {
available.push(enumSplitterVariants.compactMerge, enumSplitterVariants.compactMergeInverse);
}
return available;
}
/**
* @param {GameRoot} root
*/
getIsUnlocked(root) {
return root.hubGoals.isRewardUnlocked(enumHubGoalRewards.reward_splitter);
}
/**
* Creates the entity at the given location
* @param {Entity} entity
*/
setupEntityComponents(entity) {
entity.addComponent(
new ItemAcceptorComponent({
slots: [], // set later
})
);
entity.addComponent(
new ItemProcessorComponent({
inputsPerCharge: 1,
processorType: enumItemProcessorTypes.splitter,
})
);
entity.addComponent(
new ItemEjectorComponent({
slots: [], // set later
})
);
entity.addComponent(new BeltUnderlaysComponent({ underlays: [] }));
}
/**
*
* @param {Entity} entity
* @param {number} rotationVariant
* @param {string} variant
*/
updateVariants(entity, rotationVariant, variant) {
switch (variant) {
case defaultBuildingVariant: {
entity.components.ItemAcceptor.setSlots([
{
pos: new Vector(0, 0),
directions: [enumDirection.bottom],
},
{
pos: new Vector(1, 0),
directions: [enumDirection.bottom],
},
]);
entity.components.ItemEjector.setSlots([
{ pos: new Vector(0, 0), direction: enumDirection.top },
{ pos: new Vector(1, 0), direction: enumDirection.top },
]);
entity.components.BeltUnderlays.underlays = [
{ pos: new Vector(0, 0), direction: enumDirection.top },
{ pos: new Vector(1, 0), direction: enumDirection.top },
];
break;
}
case enumSplitterVariants.compact:
case enumSplitterVariants.compactInverse: {
entity.components.ItemAcceptor.setSlots([
{
pos: new Vector(0, 0),
directions: [enumDirection.bottom],
},
{
pos: new Vector(0, 0),
directions: [
variant === enumSplitterVariants.compactInverse
? enumDirection.left
: enumDirection.right,
],
},
]);
entity.components.ItemEjector.setSlots([
{ pos: new Vector(0, 0), direction: enumDirection.top },
]);
entity.components.BeltUnderlays.underlays = [
{ pos: new Vector(0, 0), direction: enumDirection.top },
];
break;
}
case enumSplitterVariants.compactMerge:
case enumSplitterVariants.compactMergeInverse: {
entity.components.ItemAcceptor.setSlots([
{
pos: new Vector(0, 0),
directions: [enumDirection.bottom],
},
]);
entity.components.ItemEjector.setSlots([
{
pos: new Vector(0, 0),
direction: enumDirection.top,
},
{
pos: new Vector(0, 0),
direction:
variant === enumSplitterVariants.compactMergeInverse
? enumDirection.left
: enumDirection.right,
},
]);
entity.components.BeltUnderlays.underlays = [
{ pos: new Vector(0, 0), direction: enumDirection.top },
];
break;
}
default:
assertAlways(false, "Unknown splitter variant: " + variant);
}
}
}

View File

@ -0,0 +1,151 @@
import { Vector, enumDirection } from "../../core/vector";
import { LogicGateComponent, enumLogicGateType } from "../components/logic_gate";
import { WiredPinsComponent, enumPinSlotType } from "../components/wired_pins";
import { Entity } from "../entity";
import { defaultBuildingVariant, MetaBuilding } from "../meta_building";
import { GameRoot } from "../root";
/** @enum {string} */
export const enumVirtualProcessorVariants = {
analyzer: "analyzer",
rotater: "rotater",
unstacker: "unstacker",
shapecompare: "shapecompare",
};
/** @enum {string} */
export const enumVariantToGate = {
[defaultBuildingVariant]: enumLogicGateType.cutter,
[enumVirtualProcessorVariants.analyzer]: enumLogicGateType.analyzer,
[enumVirtualProcessorVariants.rotater]: enumLogicGateType.rotater,
[enumVirtualProcessorVariants.unstacker]: enumLogicGateType.unstacker,
[enumVirtualProcessorVariants.shapecompare]: enumLogicGateType.shapecompare,
};
export class MetaVirtualProcessorBuilding extends MetaBuilding {
constructor() {
super("virtual_processor");
}
getSilhouetteColor() {
return "#823cab";
}
/**
* @param {GameRoot} root
*/
getIsUnlocked(root) {
// @todo
return true;
}
/** @returns {"wires"} **/
getLayer() {
return "wires";
}
getDimensions() {
return new Vector(1, 1);
}
getAvailableVariants() {
return [
defaultBuildingVariant,
enumVirtualProcessorVariants.rotater,
enumVirtualProcessorVariants.unstacker,
enumVirtualProcessorVariants.analyzer,
enumVirtualProcessorVariants.shapecompare,
];
}
getRenderPins() {
// We already have it included
return false;
}
/**
*
* @param {Entity} entity
* @param {number} rotationVariant
*/
updateVariants(entity, rotationVariant, variant) {
const gateType = enumVariantToGate[variant];
entity.components.LogicGate.type = gateType;
const pinComp = entity.components.WiredPins;
switch (gateType) {
case enumLogicGateType.cutter:
case enumLogicGateType.analyzer:
case enumLogicGateType.unstacker: {
pinComp.setSlots([
{
pos: new Vector(0, 0),
direction: enumDirection.left,
type: enumPinSlotType.logicalEjector,
},
{
pos: new Vector(0, 0),
direction: enumDirection.right,
type: enumPinSlotType.logicalEjector,
},
{
pos: new Vector(0, 0),
direction: enumDirection.bottom,
type: enumPinSlotType.logicalAcceptor,
},
]);
break;
}
case enumLogicGateType.rotater: {
pinComp.setSlots([
{
pos: new Vector(0, 0),
direction: enumDirection.top,
type: enumPinSlotType.logicalEjector,
},
{
pos: new Vector(0, 0),
direction: enumDirection.bottom,
type: enumPinSlotType.logicalAcceptor,
},
]);
break;
}
case enumLogicGateType.shapecompare: {
pinComp.setSlots([
{
pos: new Vector(0, 0),
direction: enumDirection.top,
type: enumPinSlotType.logicalEjector,
},
{
pos: new Vector(0, 0),
direction: enumDirection.left,
type: enumPinSlotType.logicalAcceptor,
},
{
pos: new Vector(0, 0),
direction: enumDirection.right,
type: enumPinSlotType.logicalAcceptor,
},
]);
break;
}
default:
assertAlways("unknown logic gate type: " + gateType);
}
}
/**
* Creates the entity at the given location
* @param {Entity} entity
*/
setupEntityComponents(entity) {
entity.addComponent(
new WiredPinsComponent({
slots: [],
})
);
entity.addComponent(new LogicGateComponent({}));
}
}

View File

@ -1,30 +1,36 @@
import { Component } from "../component";
/** @enum {string} */
export const enumLogicGateType = {
and: "and",
not: "not",
xor: "xor",
or: "or",
transistor: "transistor",
};
export class LogicGateComponent extends Component {
static getId() {
return "LogicGate";
}
duplicateWithoutContents() {
return new LogicGateComponent({ type: this.type });
}
/**
*
* @param {object} param0
* @param {enumLogicGateType=} param0.type
*/
constructor({ type = enumLogicGateType.and }) {
super();
this.type = type;
}
}
import { Component } from "../component";
/** @enum {string} */
export const enumLogicGateType = {
and: "and",
not: "not",
xor: "xor",
or: "or",
transistor: "transistor",
analyzer: "analyzer",
rotater: "rotater",
unstacker: "unstacker",
cutter: "cutter",
shapecompare: "shapecompare",
};
export class LogicGateComponent extends Component {
static getId() {
return "LogicGate";
}
duplicateWithoutContents() {
return new LogicGateComponent({ type: this.type });
}
/**
*
* @param {object} param0
* @param {enumLogicGateType=} param0.type
*/
constructor({ type = enumLogicGateType.and }) {
super();
this.type = type;
}
}

View File

@ -1,492 +1,492 @@
/* typehints:start */
import { Application } from "../application";
/* typehints:end */
import { BufferMaintainer } from "../core/buffer_maintainer";
import { disableImageSmoothing, enableImageSmoothing, registerCanvas } from "../core/buffer_utils";
import { globalConfig } from "../core/config";
import { getDeviceDPI, resizeHighDPICanvas } from "../core/dpi_manager";
import { DrawParameters } from "../core/draw_parameters";
import { gMetaBuildingRegistry } from "../core/global_registries";
import { createLogger } from "../core/logging";
import { Rectangle } from "../core/rectangle";
import { randomInt, round2Digits, round3Digits } from "../core/utils";
import { Vector } from "../core/vector";
import { Savegame } from "../savegame/savegame";
import { SavegameSerializer } from "../savegame/savegame_serializer";
import { AutomaticSave } from "./automatic_save";
import { MetaHubBuilding } from "./buildings/hub";
import { Camera } from "./camera";
import { DynamicTickrate } from "./dynamic_tickrate";
import { EntityManager } from "./entity_manager";
import { GameSystemManager } from "./game_system_manager";
import { HubGoals } from "./hub_goals";
import { GameHUD } from "./hud/hud";
import { KeyActionMapper } from "./key_action_mapper";
import { GameLogic } from "./logic";
import { MapView } from "./map_view";
import { defaultBuildingVariant } from "./meta_building";
import { ProductionAnalytics } from "./production_analytics";
import { GameRoot } from "./root";
import { ShapeDefinitionManager } from "./shape_definition_manager";
import { SoundProxy } from "./sound_proxy";
import { GameTime } from "./time/game_time";
import { ORIGINAL_SPRITE_SCALE } from "../core/sprites";
const logger = createLogger("ingame/core");
// Store the canvas so we can reuse it later
/** @type {HTMLCanvasElement} */
let lastCanvas = null;
/** @type {CanvasRenderingContext2D} */
let lastContext = null;
/**
* The core manages the root and represents the whole game. It wraps the root, since
* the root class is just a data holder.
*/
export class GameCore {
/** @param {Application} app */
constructor(app) {
this.app = app;
/** @type {GameRoot} */
this.root = null;
/**
* Set to true at the beginning of a logic update and cleared when its finished.
* This is to prevent doing a recursive logic update which can lead to unexpected
* behaviour.
*/
this.duringLogicUpdate = false;
// Cached
this.boundInternalTick = this.updateLogic.bind(this);
}
/**
* Initializes the root object which stores all game related data. The state
* is required as a back reference (used sometimes)
* @param {import("../states/ingame").InGameState} parentState
* @param {Savegame} savegame
*/
initializeRoot(parentState, savegame) {
// Construct the root element, this is the data representation of the game
this.root = new GameRoot(this.app);
this.root.gameState = parentState;
this.root.keyMapper = parentState.keyActionMapper;
this.root.savegame = savegame;
this.root.gameWidth = this.app.screenWidth;
this.root.gameHeight = this.app.screenHeight;
// Initialize canvas element & context
this.internalInitCanvas();
// Members
const root = this.root;
// This isn't nice, but we need it right here
root.keyMapper = new KeyActionMapper(root, this.root.gameState.inputReciever);
// Needs to come first
root.dynamicTickrate = new DynamicTickrate(root);
// Init classes
root.camera = new Camera(root);
root.map = new MapView(root);
root.logic = new GameLogic(root);
root.hud = new GameHUD(root);
root.time = new GameTime(root);
root.automaticSave = new AutomaticSave(root);
root.soundProxy = new SoundProxy(root);
// Init managers
root.entityMgr = new EntityManager(root);
root.systemMgr = new GameSystemManager(root);
root.shapeDefinitionMgr = new ShapeDefinitionManager(root);
root.hubGoals = new HubGoals(root);
root.productionAnalytics = new ProductionAnalytics(root);
root.buffers = new BufferMaintainer(root);
// Initialize the hud once everything is loaded
this.root.hud.initialize();
// Initial resize event, it might be possible that the screen
// resized later during init tho, which is why will emit it later
// again anyways
this.resize(this.app.screenWidth, this.app.screenHeight);
if (G_IS_DEV) {
// @ts-ignore
window.globalRoot = root;
}
}
/**
* Initializes a new game, this means creating a new map and centering on the
* playerbase
* */
initNewGame() {
logger.log("Initializing new game");
this.root.gameIsFresh = true;
this.root.map.seed = randomInt(0, 100000);
// Place the hub
const hub = gMetaBuildingRegistry.findByClass(MetaHubBuilding).createEntity({
root: this.root,
origin: new Vector(-2, -2),
rotation: 0,
originalRotation: 0,
rotationVariant: 0,
variant: defaultBuildingVariant,
});
this.root.map.placeStaticEntity(hub);
this.root.entityMgr.registerEntity(hub);
}
/**
* Inits an existing game by loading the raw savegame data and deserializing it.
* Also runs basic validity checks.
*/
initExistingGame() {
logger.log("Initializing existing game");
const serializer = new SavegameSerializer();
try {
const status = serializer.deserialize(this.root.savegame.getCurrentDump(), this.root);
if (!status.isGood()) {
logger.error("savegame-deserialize-failed:" + status.reason);
return false;
}
} catch (ex) {
logger.error("Exception during deserialization:", ex);
return false;
}
this.root.gameIsFresh = false;
return true;
}
/**
* Initializes the render canvas
*/
internalInitCanvas() {
let canvas, context;
if (!lastCanvas) {
logger.log("Creating new canvas");
canvas = document.createElement("canvas");
canvas.id = "ingame_Canvas";
canvas.setAttribute("opaque", "true");
canvas.setAttribute("webkitOpaque", "true");
canvas.setAttribute("mozOpaque", "true");
this.root.gameState.getDivElement().appendChild(canvas);
context = canvas.getContext("2d", { alpha: false });
lastCanvas = canvas;
lastContext = context;
} else {
logger.log("Reusing canvas");
if (lastCanvas.parentElement) {
lastCanvas.parentElement.removeChild(lastCanvas);
}
this.root.gameState.getDivElement().appendChild(lastCanvas);
canvas = lastCanvas;
context = lastContext;
lastContext.clearRect(0, 0, lastCanvas.width, lastCanvas.height);
}
// globalConfig.smoothing.smoothMainCanvas = getDeviceDPI() < 1.5;
// globalConfig.smoothing.smoothMainCanvas = true;
canvas.classList.toggle("smoothed", globalConfig.smoothing.smoothMainCanvas);
// Oof, use :not() instead
canvas.classList.toggle("unsmoothed", !globalConfig.smoothing.smoothMainCanvas);
if (globalConfig.smoothing.smoothMainCanvas) {
enableImageSmoothing(context);
} else {
disableImageSmoothing(context);
}
this.root.canvas = canvas;
this.root.context = context;
registerCanvas(canvas, context);
}
/**
* Destructs the root, freeing all resources
*/
destruct() {
if (lastCanvas && lastCanvas.parentElement) {
lastCanvas.parentElement.removeChild(lastCanvas);
}
this.root.destruct();
delete this.root;
this.root = null;
this.app = null;
}
tick(deltaMs) {
const root = this.root;
// Extract current real time
root.time.updateRealtimeNow();
// Camera is always updated, no matter what
root.camera.update(deltaMs);
// Perform logic ticks
this.root.time.performTicks(deltaMs, this.boundInternalTick);
// Update analytics
root.productionAnalytics.update();
// Update automatic save after everything finished
root.automaticSave.update();
return true;
}
shouldRender() {
if (this.root.queue.requireRedraw) {
return true;
}
if (this.root.hud.shouldPauseRendering()) {
return false;
}
// Do not render
if (!this.app.isRenderable()) {
return false;
}
return true;
}
updateLogic() {
const root = this.root;
root.dynamicTickrate.beginTick();
if (G_IS_DEV && globalConfig.debug.disableLogicTicks) {
root.dynamicTickrate.endTick();
return true;
}
this.duringLogicUpdate = true;
// Update entities, this removes destroyed entities
root.entityMgr.update();
// IMPORTANT: At this point, the game might be game over. Stop if this is the case
if (!this.root) {
logger.log("Root destructed, returning false");
root.dynamicTickrate.endTick();
return false;
}
root.systemMgr.update();
// root.particleMgr.update();
this.duringLogicUpdate = false;
root.dynamicTickrate.endTick();
return true;
}
resize(w, h) {
this.root.gameWidth = w;
this.root.gameHeight = h;
resizeHighDPICanvas(this.root.canvas, w, h, globalConfig.smoothing.smoothMainCanvas);
this.root.signals.resized.dispatch(w, h);
this.root.queue.requireRedraw = true;
}
postLoadHook() {
logger.log("Dispatching post load hook");
this.root.signals.postLoadHook.dispatch();
if (!this.root.gameIsFresh) {
// Also dispatch game restored hook on restored savegames
this.root.signals.gameRestored.dispatch();
}
this.root.gameInitialized = true;
}
draw() {
const root = this.root;
const systems = root.systemMgr.systems;
this.root.dynamicTickrate.onFrameRendered();
if (!this.shouldRender()) {
// Always update hud tho
root.hud.update();
return;
}
this.root.signals.gameFrameStarted.dispatch();
root.queue.requireRedraw = false;
// Gather context and save all state
const context = root.context;
context.save();
if (G_IS_DEV) {
context.fillStyle = "#a10000";
context.fillRect(0, 0, window.innerWidth * 3, window.innerHeight * 3);
}
// Compute optimal zoom level and atlas scale
const zoomLevel = root.camera.zoomLevel;
const lowQuality = root.app.settings.getAllSettings().lowQualityTextures;
const effectiveZoomLevel =
(zoomLevel / globalConfig.assetsDpi) * getDeviceDPI() * globalConfig.assetsSharpness;
let desiredAtlasScale = "0.25";
if (effectiveZoomLevel > 0.8 && !lowQuality) {
desiredAtlasScale = ORIGINAL_SPRITE_SCALE;
} else if (effectiveZoomLevel > 0.4 && !lowQuality) {
desiredAtlasScale = "0.5";
}
// Construct parameters required for drawing
const params = new DrawParameters({
context: context,
visibleRect: root.camera.getVisibleRect(),
desiredAtlasScale,
zoomLevel,
root: root,
});
if (G_IS_DEV && globalConfig.debug.testCulling) {
context.clearRect(0, 0, root.gameWidth, root.gameHeight);
}
// Transform to world space
if (G_IS_DEV && globalConfig.debug.testClipping) {
params.visibleRect = params.visibleRect.expandedInAllDirections(
-200 / this.root.camera.zoomLevel
);
}
root.camera.transform(context);
assert(context.globalAlpha === 1.0, "Global alpha not 1 on frame start");
// Update hud
root.hud.update();
// Main rendering order
// -----
if (this.root.camera.getIsMapOverlayActive()) {
// Map overview
root.map.drawOverlay(params);
} else {
// Background (grid, resources, etc)
root.map.drawBackground(params);
// Belt items
systems.belt.drawBeltItems(params);
// Miner & Static map entities etc.
root.map.drawForeground(params);
// HUB Overlay
systems.hub.draw(params);
// Green wires overlay
root.hud.parts.wiresOverlay.draw(params);
if (this.root.currentLayer === "wires") {
// Static map entities
root.map.drawWiresForegroundLayer(params);
}
}
if (G_IS_DEV) {
root.map.drawStaticEntityDebugOverlays(params);
}
if (G_IS_DEV && globalConfig.debug.renderBeltPaths) {
systems.belt.drawBeltPathDebug(params);
}
// END OF GAME CONTENT
// -----
// Finally, draw the hud. Nothing should come after that
root.hud.draw(params);
assert(context.globalAlpha === 1.0, "Global alpha not 1 on frame end before restore");
// Restore to screen space
context.restore();
// Restore parameters
params.zoomLevel = 1;
params.desiredAtlasScale = ORIGINAL_SPRITE_SCALE;
params.visibleRect = new Rectangle(0, 0, this.root.gameWidth, this.root.gameHeight);
if (G_IS_DEV && globalConfig.debug.testClipping) {
params.visibleRect = params.visibleRect.expandedInAllDirections(-200);
}
// Draw overlays, those are screen space
root.hud.drawOverlays(params);
assert(context.globalAlpha === 1.0, "context.globalAlpha not 1 on frame end");
if (G_IS_DEV && globalConfig.debug.simulateSlowRendering) {
let sum = 0;
for (let i = 0; i < 1e8; ++i) {
sum += i;
}
if (Math.random() > 0.95) {
console.log(sum);
}
}
if (G_IS_DEV && globalConfig.debug.showAtlasInfo) {
context.font = "13px GameFont";
context.fillStyle = "blue";
context.fillText(
"Atlas: " +
desiredAtlasScale +
" / Zoom: " +
round2Digits(zoomLevel) +
" / Effective Zoom: " +
round2Digits(effectiveZoomLevel),
20,
600
);
const stats = this.root.buffers.getStats();
context.fillText(
"Buffers: " +
stats.rootKeys +
" root keys, " +
stats.subKeys +
" sub keys / buffers / VRAM: " +
round2Digits(stats.vramBytes / (1024 * 1024)) +
" MB",
20,
620
);
}
if (G_IS_DEV && globalConfig.debug.testClipping) {
context.strokeStyle = "red";
context.lineWidth = 1;
context.beginPath();
context.rect(200, 200, this.root.gameWidth - 400, this.root.gameHeight - 400);
context.stroke();
}
}
}
/* typehints:start */
import { Application } from "../application";
/* typehints:end */
import { BufferMaintainer } from "../core/buffer_maintainer";
import { disableImageSmoothing, enableImageSmoothing, registerCanvas } from "../core/buffer_utils";
import { globalConfig } from "../core/config";
import { getDeviceDPI, resizeHighDPICanvas } from "../core/dpi_manager";
import { DrawParameters } from "../core/draw_parameters";
import { gMetaBuildingRegistry } from "../core/global_registries";
import { createLogger } from "../core/logging";
import { Rectangle } from "../core/rectangle";
import { randomInt, round2Digits, round3Digits } from "../core/utils";
import { Vector } from "../core/vector";
import { Savegame } from "../savegame/savegame";
import { SavegameSerializer } from "../savegame/savegame_serializer";
import { AutomaticSave } from "./automatic_save";
import { MetaHubBuilding } from "./buildings/hub";
import { Camera } from "./camera";
import { DynamicTickrate } from "./dynamic_tickrate";
import { EntityManager } from "./entity_manager";
import { GameSystemManager } from "./game_system_manager";
import { HubGoals } from "./hub_goals";
import { GameHUD } from "./hud/hud";
import { KeyActionMapper } from "./key_action_mapper";
import { GameLogic } from "./logic";
import { MapView } from "./map_view";
import { defaultBuildingVariant } from "./meta_building";
import { ProductionAnalytics } from "./production_analytics";
import { GameRoot } from "./root";
import { ShapeDefinitionManager } from "./shape_definition_manager";
import { SoundProxy } from "./sound_proxy";
import { GameTime } from "./time/game_time";
import { ORIGINAL_SPRITE_SCALE } from "../core/sprites";
const logger = createLogger("ingame/core");
// Store the canvas so we can reuse it later
/** @type {HTMLCanvasElement} */
let lastCanvas = null;
/** @type {CanvasRenderingContext2D} */
let lastContext = null;
/**
* The core manages the root and represents the whole game. It wraps the root, since
* the root class is just a data holder.
*/
export class GameCore {
/** @param {Application} app */
constructor(app) {
this.app = app;
/** @type {GameRoot} */
this.root = null;
/**
* Set to true at the beginning of a logic update and cleared when its finished.
* This is to prevent doing a recursive logic update which can lead to unexpected
* behaviour.
*/
this.duringLogicUpdate = false;
// Cached
this.boundInternalTick = this.updateLogic.bind(this);
}
/**
* Initializes the root object which stores all game related data. The state
* is required as a back reference (used sometimes)
* @param {import("../states/ingame").InGameState} parentState
* @param {Savegame} savegame
*/
initializeRoot(parentState, savegame) {
// Construct the root element, this is the data representation of the game
this.root = new GameRoot(this.app);
this.root.gameState = parentState;
this.root.keyMapper = parentState.keyActionMapper;
this.root.savegame = savegame;
this.root.gameWidth = this.app.screenWidth;
this.root.gameHeight = this.app.screenHeight;
// Initialize canvas element & context
this.internalInitCanvas();
// Members
const root = this.root;
// This isn't nice, but we need it right here
root.keyMapper = new KeyActionMapper(root, this.root.gameState.inputReciever);
// Needs to come first
root.dynamicTickrate = new DynamicTickrate(root);
// Init classes
root.camera = new Camera(root);
root.map = new MapView(root);
root.logic = new GameLogic(root);
root.hud = new GameHUD(root);
root.time = new GameTime(root);
root.automaticSave = new AutomaticSave(root);
root.soundProxy = new SoundProxy(root);
// Init managers
root.entityMgr = new EntityManager(root);
root.systemMgr = new GameSystemManager(root);
root.shapeDefinitionMgr = new ShapeDefinitionManager(root);
root.hubGoals = new HubGoals(root);
root.productionAnalytics = new ProductionAnalytics(root);
root.buffers = new BufferMaintainer(root);
// Initialize the hud once everything is loaded
this.root.hud.initialize();
// Initial resize event, it might be possible that the screen
// resized later during init tho, which is why will emit it later
// again anyways
this.resize(this.app.screenWidth, this.app.screenHeight);
if (G_IS_DEV) {
// @ts-ignore
window.globalRoot = root;
}
}
/**
* Initializes a new game, this means creating a new map and centering on the
* playerbase
* */
initNewGame() {
logger.log("Initializing new game");
this.root.gameIsFresh = true;
this.root.map.seed = randomInt(0, 100000);
// Place the hub
const hub = gMetaBuildingRegistry.findByClass(MetaHubBuilding).createEntity({
root: this.root,
origin: new Vector(-2, -2),
rotation: 0,
originalRotation: 0,
rotationVariant: 0,
variant: defaultBuildingVariant,
});
this.root.map.placeStaticEntity(hub);
this.root.entityMgr.registerEntity(hub);
}
/**
* Inits an existing game by loading the raw savegame data and deserializing it.
* Also runs basic validity checks.
*/
initExistingGame() {
logger.log("Initializing existing game");
const serializer = new SavegameSerializer();
try {
const status = serializer.deserialize(this.root.savegame.getCurrentDump(), this.root);
if (!status.isGood()) {
logger.error("savegame-deserialize-failed:" + status.reason);
return false;
}
} catch (ex) {
logger.error("Exception during deserialization:", ex);
return false;
}
this.root.gameIsFresh = false;
return true;
}
/**
* Initializes the render canvas
*/
internalInitCanvas() {
let canvas, context;
if (!lastCanvas) {
logger.log("Creating new canvas");
canvas = document.createElement("canvas");
canvas.id = "ingame_Canvas";
canvas.setAttribute("opaque", "true");
canvas.setAttribute("webkitOpaque", "true");
canvas.setAttribute("mozOpaque", "true");
this.root.gameState.getDivElement().appendChild(canvas);
context = canvas.getContext("2d", { alpha: false });
lastCanvas = canvas;
lastContext = context;
} else {
logger.log("Reusing canvas");
if (lastCanvas.parentElement) {
lastCanvas.parentElement.removeChild(lastCanvas);
}
this.root.gameState.getDivElement().appendChild(lastCanvas);
canvas = lastCanvas;
context = lastContext;
lastContext.clearRect(0, 0, lastCanvas.width, lastCanvas.height);
}
// globalConfig.smoothing.smoothMainCanvas = getDeviceDPI() < 1.5;
// globalConfig.smoothing.smoothMainCanvas = true;
canvas.classList.toggle("smoothed", globalConfig.smoothing.smoothMainCanvas);
// Oof, use :not() instead
canvas.classList.toggle("unsmoothed", !globalConfig.smoothing.smoothMainCanvas);
if (globalConfig.smoothing.smoothMainCanvas) {
enableImageSmoothing(context);
} else {
disableImageSmoothing(context);
}
this.root.canvas = canvas;
this.root.context = context;
registerCanvas(canvas, context);
}
/**
* Destructs the root, freeing all resources
*/
destruct() {
if (lastCanvas && lastCanvas.parentElement) {
lastCanvas.parentElement.removeChild(lastCanvas);
}
this.root.destruct();
delete this.root;
this.root = null;
this.app = null;
}
tick(deltaMs) {
const root = this.root;
// Extract current real time
root.time.updateRealtimeNow();
// Camera is always updated, no matter what
root.camera.update(deltaMs);
// Perform logic ticks
this.root.time.performTicks(deltaMs, this.boundInternalTick);
// Update analytics
root.productionAnalytics.update();
// Update automatic save after everything finished
root.automaticSave.update();
return true;
}
shouldRender() {
if (this.root.queue.requireRedraw) {
return true;
}
if (this.root.hud.shouldPauseRendering()) {
return false;
}
// Do not render
if (!this.app.isRenderable()) {
return false;
}
return true;
}
updateLogic() {
const root = this.root;
root.dynamicTickrate.beginTick();
if (G_IS_DEV && globalConfig.debug.disableLogicTicks) {
root.dynamicTickrate.endTick();
return true;
}
this.duringLogicUpdate = true;
// Update entities, this removes destroyed entities
root.entityMgr.update();
// IMPORTANT: At this point, the game might be game over. Stop if this is the case
if (!this.root) {
logger.log("Root destructed, returning false");
root.dynamicTickrate.endTick();
return false;
}
root.systemMgr.update();
// root.particleMgr.update();
this.duringLogicUpdate = false;
root.dynamicTickrate.endTick();
return true;
}
resize(w, h) {
this.root.gameWidth = w;
this.root.gameHeight = h;
resizeHighDPICanvas(this.root.canvas, w, h, globalConfig.smoothing.smoothMainCanvas);
this.root.signals.resized.dispatch(w, h);
this.root.queue.requireRedraw = true;
}
postLoadHook() {
logger.log("Dispatching post load hook");
this.root.signals.postLoadHook.dispatch();
if (!this.root.gameIsFresh) {
// Also dispatch game restored hook on restored savegames
this.root.signals.gameRestored.dispatch();
}
this.root.gameInitialized = true;
}
draw() {
const root = this.root;
const systems = root.systemMgr.systems;
this.root.dynamicTickrate.onFrameRendered();
if (!this.shouldRender()) {
// Always update hud tho
root.hud.update();
return;
}
this.root.signals.gameFrameStarted.dispatch();
root.queue.requireRedraw = false;
// Gather context and save all state
const context = root.context;
context.save();
if (G_IS_DEV) {
context.fillStyle = "#a10000";
context.fillRect(0, 0, window.innerWidth * 3, window.innerHeight * 3);
}
// Compute optimal zoom level and atlas scale
const zoomLevel = root.camera.zoomLevel;
const lowQuality = root.app.settings.getAllSettings().lowQualityTextures;
const effectiveZoomLevel =
(zoomLevel / globalConfig.assetsDpi) * getDeviceDPI() * globalConfig.assetsSharpness;
let desiredAtlasScale = "0.25";
if (effectiveZoomLevel > 0.8 && !lowQuality) {
desiredAtlasScale = ORIGINAL_SPRITE_SCALE;
} else if (effectiveZoomLevel > 0.4 && !lowQuality) {
desiredAtlasScale = "0.5";
}
// Construct parameters required for drawing
const params = new DrawParameters({
context: context,
visibleRect: root.camera.getVisibleRect(),
desiredAtlasScale,
zoomLevel,
root: root,
});
if (G_IS_DEV && globalConfig.debug.testCulling) {
context.clearRect(0, 0, root.gameWidth, root.gameHeight);
}
// Transform to world space
if (G_IS_DEV && globalConfig.debug.testClipping) {
params.visibleRect = params.visibleRect.expandedInAllDirections(
-200 / this.root.camera.zoomLevel
);
}
root.camera.transform(context);
assert(context.globalAlpha === 1.0, "Global alpha not 1 on frame start");
// Update hud
root.hud.update();
// Main rendering order
// -----
if (this.root.camera.getIsMapOverlayActive()) {
// Map overview
root.map.drawOverlay(params);
} else {
// Background (grid, resources, etc)
root.map.drawBackground(params);
// Belt items
systems.belt.drawBeltItems(params);
// Miner & Static map entities etc.
root.map.drawForeground(params);
// HUB Overlay
systems.hub.draw(params);
// Green wires overlay
root.hud.parts.wiresOverlay.draw(params);
if (this.root.currentLayer === "wires") {
// Static map entities
root.map.drawWiresForegroundLayer(params);
}
}
if (G_IS_DEV) {
root.map.drawStaticEntityDebugOverlays(params);
}
if (G_IS_DEV && globalConfig.debug.renderBeltPaths) {
systems.belt.drawBeltPathDebug(params);
}
// END OF GAME CONTENT
// -----
// Finally, draw the hud. Nothing should come after that
root.hud.draw(params);
assert(context.globalAlpha === 1.0, "Global alpha not 1 on frame end before restore");
// Restore to screen space
context.restore();
// Restore parameters
params.zoomLevel = 1;
params.desiredAtlasScale = ORIGINAL_SPRITE_SCALE;
params.visibleRect = new Rectangle(0, 0, this.root.gameWidth, this.root.gameHeight);
if (G_IS_DEV && globalConfig.debug.testClipping) {
params.visibleRect = params.visibleRect.expandedInAllDirections(-200);
}
// Draw overlays, those are screen space
root.hud.drawOverlays(params);
assert(context.globalAlpha === 1.0, "context.globalAlpha not 1 on frame end");
if (G_IS_DEV && globalConfig.debug.simulateSlowRendering) {
let sum = 0;
for (let i = 0; i < 1e8; ++i) {
sum += i;
}
if (Math.random() > 0.95) {
console.log(sum);
}
}
if (G_IS_DEV && globalConfig.debug.showAtlasInfo) {
context.font = "13px GameFont";
context.fillStyle = "blue";
context.fillText(
"Atlas: " +
desiredAtlasScale +
" / Zoom: " +
round2Digits(zoomLevel) +
" / Effective Zoom: " +
round2Digits(effectiveZoomLevel),
20,
600
);
const stats = this.root.buffers.getStats();
context.fillText(
"Buffers: " +
stats.rootKeys +
" root keys, " +
stats.subKeys +
" sub keys / buffers / VRAM: " +
round2Digits(stats.vramBytes / (1024 * 1024)) +
" MB",
20,
620
);
}
if (G_IS_DEV && globalConfig.debug.testClipping) {
context.strokeStyle = "red";
context.lineWidth = 1;
context.beginPath();
context.rect(200, 200, this.root.gameWidth - 400, this.root.gameHeight - 400);
context.stroke();
}
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,308 +1,317 @@
import { BaseHUDPart } from "../base_hud_part";
import { Vector } from "../../../core/vector";
import { STOP_PROPAGATION } from "../../../core/signal";
import { DrawParameters } from "../../../core/draw_parameters";
import { Entity } from "../../entity";
import { Loader } from "../../../core/loader";
import { globalConfig } from "../../../core/config";
import { makeDiv, formatBigNumber, formatBigNumberFull } from "../../../core/utils";
import { DynamicDomAttach } from "../dynamic_dom_attach";
import { createLogger } from "../../../core/logging";
import { enumMouseButton } from "../../camera";
import { T } from "../../../translations";
import { KEYMAPPINGS } from "../../key_action_mapper";
import { THEME } from "../../theme";
import { enumHubGoalRewards } from "../../tutorial_goals";
import { Blueprint } from "../../blueprint";
const logger = createLogger("hud/mass_selector");
export class HUDMassSelector extends BaseHUDPart {
createElements(parent) {}
initialize() {
this.currentSelectionStartWorld = null;
this.currentSelectionEnd = null;
this.selectedUids = new Set();
this.root.signals.entityQueuedForDestroy.add(this.onEntityDestroyed, this);
this.root.hud.signals.pasteBlueprintRequested.add(this.clearSelection, this);
this.root.camera.downPreHandler.add(this.onMouseDown, this);
this.root.camera.movePreHandler.add(this.onMouseMove, this);
this.root.camera.upPostHandler.add(this.onMouseUp, this);
this.root.keyMapper.getBinding(KEYMAPPINGS.general.back).add(this.onBack, this);
this.root.keyMapper
.getBinding(KEYMAPPINGS.massSelect.confirmMassDelete)
.add(this.confirmDelete, this);
this.root.keyMapper.getBinding(KEYMAPPINGS.massSelect.massSelectCut).add(this.confirmCut, this);
this.root.keyMapper.getBinding(KEYMAPPINGS.massSelect.massSelectCopy).add(this.startCopy, this);
this.root.hud.signals.selectedPlacementBuildingChanged.add(this.clearSelection, this);
this.root.signals.editModeChanged.add(this.clearSelection, this);
}
/**
* Handles the destroy callback and makes sure we clean our list
* @param {Entity} entity
*/
onEntityDestroyed(entity) {
this.selectedUids.delete(entity.uid);
}
/**
*
*/
onBack() {
// Clear entities on escape
if (this.selectedUids.size > 0) {
this.selectedUids = new Set();
return STOP_PROPAGATION;
}
}
/**
* Clears the entire selection
*/
clearSelection() {
this.selectedUids = new Set();
}
confirmDelete() {
if (
!this.root.app.settings.getAllSettings().disableCutDeleteWarnings &&
this.selectedUids.size > 100
) {
const { ok } = this.root.hud.parts.dialogs.showWarning(
T.dialogs.massDeleteConfirm.title,
T.dialogs.massDeleteConfirm.desc.replace(
"<count>",
"" + formatBigNumberFull(this.selectedUids.size)
),
["cancel:good:escape", "ok:bad:enter"]
);
ok.add(() => this.doDelete());
} else {
this.doDelete();
}
}
doDelete() {
const entityUids = Array.from(this.selectedUids);
for (let i = 0; i < entityUids.length; ++i) {
const uid = entityUids[i];
const entity = this.root.entityMgr.findByUid(uid);
if (!this.root.logic.tryDeleteBuilding(entity)) {
logger.error("Error in mass delete, could not remove building");
this.selectedUids.delete(uid);
}
}
}
startCopy() {
if (this.selectedUids.size > 0) {
if (!this.root.hubGoals.isRewardUnlocked(enumHubGoalRewards.reward_blueprints)) {
this.root.hud.parts.dialogs.showInfo(
T.dialogs.blueprintsNotUnlocked.title,
T.dialogs.blueprintsNotUnlocked.desc
);
return;
}
this.root.hud.signals.buildingsSelectedForCopy.dispatch(Array.from(this.selectedUids));
this.selectedUids = new Set();
this.root.soundProxy.playUiClick();
} else {
this.root.soundProxy.playUiError();
}
}
confirmCut() {
if (!this.root.hubGoals.isRewardUnlocked(enumHubGoalRewards.reward_blueprints)) {
this.root.hud.parts.dialogs.showInfo(
T.dialogs.blueprintsNotUnlocked.title,
T.dialogs.blueprintsNotUnlocked.desc
);
} else if (
!this.root.app.settings.getAllSettings().disableCutDeleteWarnings &&
this.selectedUids.size > 100
) {
const { ok } = this.root.hud.parts.dialogs.showWarning(
T.dialogs.massCutConfirm.title,
T.dialogs.massCutConfirm.desc.replace(
"<count>",
"" + formatBigNumberFull(this.selectedUids.size)
),
["cancel:good:escape", "ok:bad:enter"]
);
ok.add(() => this.doCut());
} else {
this.doCut();
}
}
doCut() {
if (this.selectedUids.size > 0) {
const entityUids = Array.from(this.selectedUids);
const cutAction = () => {
// copy code relies on entities still existing, so must copy before deleting.
this.root.hud.signals.buildingsSelectedForCopy.dispatch(entityUids);
for (let i = 0; i < entityUids.length; ++i) {
const uid = entityUids[i];
const entity = this.root.entityMgr.findByUid(uid);
if (!this.root.logic.tryDeleteBuilding(entity)) {
logger.error("Error in mass cut, could not remove building");
this.selectedUids.delete(uid);
}
}
};
const blueprint = Blueprint.fromUids(this.root, entityUids);
if (blueprint.canAfford(this.root)) {
cutAction();
} else {
const { cancel, ok } = this.root.hud.parts.dialogs.showWarning(
T.dialogs.massCutInsufficientConfirm.title,
T.dialogs.massCutInsufficientConfirm.desc,
["cancel:good:escape", "ok:bad:enter"]
);
ok.add(cutAction);
}
this.root.soundProxy.playUiClick();
} else {
this.root.soundProxy.playUiError();
}
}
/**
* mouse down pre handler
* @param {Vector} pos
* @param {enumMouseButton} mouseButton
*/
onMouseDown(pos, mouseButton) {
if (!this.root.keyMapper.getBinding(KEYMAPPINGS.massSelect.massSelectStart).pressed) {
return;
}
if (mouseButton !== enumMouseButton.left) {
return;
}
if (!this.root.keyMapper.getBinding(KEYMAPPINGS.massSelect.massSelectSelectMultiple).pressed) {
// Start new selection
this.selectedUids = new Set();
}
this.currentSelectionStartWorld = this.root.camera.screenToWorld(pos.copy());
this.currentSelectionEnd = pos.copy();
return STOP_PROPAGATION;
}
/**
* mouse move pre handler
* @param {Vector} pos
*/
onMouseMove(pos) {
if (this.currentSelectionStartWorld) {
this.currentSelectionEnd = pos.copy();
}
}
onMouseUp() {
if (this.currentSelectionStartWorld) {
const worldStart = this.currentSelectionStartWorld;
const worldEnd = this.root.camera.screenToWorld(this.currentSelectionEnd);
const tileStart = worldStart.toTileSpace();
const tileEnd = worldEnd.toTileSpace();
const realTileStart = tileStart.min(tileEnd);
const realTileEnd = tileStart.max(tileEnd);
for (let x = realTileStart.x; x <= realTileEnd.x; ++x) {
for (let y = realTileStart.y; y <= realTileEnd.y; ++y) {
const contents = this.root.map.getLayerContentXY(x, y, this.root.currentLayer);
if (contents && this.root.logic.canDeleteBuilding(contents)) {
this.selectedUids.add(contents.uid);
}
}
}
this.currentSelectionStartWorld = null;
this.currentSelectionEnd = null;
}
}
/**
*
* @param {DrawParameters} parameters
*/
draw(parameters) {
const boundsBorder = 2;
if (this.currentSelectionStartWorld) {
const worldStart = this.currentSelectionStartWorld;
const worldEnd = this.root.camera.screenToWorld(this.currentSelectionEnd);
const realWorldStart = worldStart.min(worldEnd);
const realWorldEnd = worldStart.max(worldEnd);
const tileStart = worldStart.toTileSpace();
const tileEnd = worldEnd.toTileSpace();
const realTileStart = tileStart.min(tileEnd);
const realTileEnd = tileStart.max(tileEnd);
parameters.context.lineWidth = 1;
parameters.context.fillStyle = THEME.map.selectionBackground;
parameters.context.strokeStyle = THEME.map.selectionOutline;
parameters.context.beginPath();
parameters.context.rect(
realWorldStart.x,
realWorldStart.y,
realWorldEnd.x - realWorldStart.x,
realWorldEnd.y - realWorldStart.y
);
parameters.context.fill();
parameters.context.stroke();
parameters.context.fillStyle = THEME.map.selectionOverlay;
for (let x = realTileStart.x; x <= realTileEnd.x; ++x) {
for (let y = realTileStart.y; y <= realTileEnd.y; ++y) {
const contents = this.root.map.getLayerContentXY(x, y, this.root.currentLayer);
if (contents && this.root.logic.canDeleteBuilding(contents)) {
const staticComp = contents.components.StaticMapEntity;
const bounds = staticComp.getTileSpaceBounds();
parameters.context.beginRoundedRect(
bounds.x * globalConfig.tileSize + boundsBorder,
bounds.y * globalConfig.tileSize + boundsBorder,
bounds.w * globalConfig.tileSize - 2 * boundsBorder,
bounds.h * globalConfig.tileSize - 2 * boundsBorder,
2
);
parameters.context.fill();
}
}
}
}
parameters.context.fillStyle = THEME.map.selectionOverlay;
this.selectedUids.forEach(uid => {
const entity = this.root.entityMgr.findByUid(uid);
const staticComp = entity.components.StaticMapEntity;
const bounds = staticComp.getTileSpaceBounds();
parameters.context.beginRoundedRect(
bounds.x * globalConfig.tileSize + boundsBorder,
bounds.y * globalConfig.tileSize + boundsBorder,
bounds.w * globalConfig.tileSize - 2 * boundsBorder,
bounds.h * globalConfig.tileSize - 2 * boundsBorder,
2
);
parameters.context.fill();
});
}
}
import { BaseHUDPart } from "../base_hud_part";
import { Vector } from "../../../core/vector";
import { STOP_PROPAGATION } from "../../../core/signal";
import { DrawParameters } from "../../../core/draw_parameters";
import { Entity } from "../../entity";
import { Loader } from "../../../core/loader";
import { globalConfig } from "../../../core/config";
import { makeDiv, formatBigNumber, formatBigNumberFull } from "../../../core/utils";
import { DynamicDomAttach } from "../dynamic_dom_attach";
import { createLogger } from "../../../core/logging";
import { enumMouseButton } from "../../camera";
import { T } from "../../../translations";
import { KEYMAPPINGS } from "../../key_action_mapper";
import { THEME } from "../../theme";
import { enumHubGoalRewards } from "../../tutorial_goals";
import { Blueprint } from "../../blueprint";
const logger = createLogger("hud/mass_selector");
export class HUDMassSelector extends BaseHUDPart {
createElements(parent) {}
initialize() {
this.currentSelectionStartWorld = null;
this.currentSelectionEnd = null;
this.selectedUids = new Set();
this.root.signals.entityQueuedForDestroy.add(this.onEntityDestroyed, this);
this.root.hud.signals.pasteBlueprintRequested.add(this.clearSelection, this);
this.root.camera.downPreHandler.add(this.onMouseDown, this);
this.root.camera.movePreHandler.add(this.onMouseMove, this);
this.root.camera.upPostHandler.add(this.onMouseUp, this);
this.root.keyMapper.getBinding(KEYMAPPINGS.general.back).add(this.onBack, this);
this.root.keyMapper
.getBinding(KEYMAPPINGS.massSelect.confirmMassDelete)
.add(this.confirmDelete, this);
this.root.keyMapper.getBinding(KEYMAPPINGS.massSelect.massSelectCut).add(this.confirmCut, this);
this.root.keyMapper.getBinding(KEYMAPPINGS.massSelect.massSelectCopy).add(this.startCopy, this);
this.root.hud.signals.selectedPlacementBuildingChanged.add(this.clearSelection, this);
this.root.signals.editModeChanged.add(this.clearSelection, this);
}
/**
* Handles the destroy callback and makes sure we clean our list
* @param {Entity} entity
*/
onEntityDestroyed(entity) {
this.selectedUids.delete(entity.uid);
}
/**
*
*/
onBack() {
// Clear entities on escape
if (this.selectedUids.size > 0) {
this.selectedUids = new Set();
return STOP_PROPAGATION;
}
}
/**
* Clears the entire selection
*/
clearSelection() {
this.selectedUids = new Set();
}
confirmDelete() {
if (
!this.root.app.settings.getAllSettings().disableCutDeleteWarnings &&
this.selectedUids.size > 100
) {
const { ok } = this.root.hud.parts.dialogs.showWarning(
T.dialogs.massDeleteConfirm.title,
T.dialogs.massDeleteConfirm.desc.replace(
"<count>",
"" + formatBigNumberFull(this.selectedUids.size)
),
["cancel:good:escape", "ok:bad:enter"]
);
ok.add(() => this.doDelete());
} else {
this.doDelete();
}
}
doDelete() {
const entityUids = Array.from(this.selectedUids);
for (let i = 0; i < entityUids.length; ++i) {
const uid = entityUids[i];
const entity = this.root.entityMgr.findByUid(uid);
if (!this.root.logic.tryDeleteBuilding(entity)) {
logger.error("Error in mass delete, could not remove building");
this.selectedUids.delete(uid);
}
}
}
startCopy() {
if (this.selectedUids.size > 0) {
if (!this.root.hubGoals.isRewardUnlocked(enumHubGoalRewards.reward_blueprints)) {
this.root.hud.parts.dialogs.showInfo(
T.dialogs.blueprintsNotUnlocked.title,
T.dialogs.blueprintsNotUnlocked.desc
);
return;
}
this.root.hud.signals.buildingsSelectedForCopy.dispatch(Array.from(this.selectedUids));
this.selectedUids = new Set();
this.root.soundProxy.playUiClick();
} else {
this.root.soundProxy.playUiError();
}
}
confirmCut() {
if (!this.root.hubGoals.isRewardUnlocked(enumHubGoalRewards.reward_blueprints)) {
this.root.hud.parts.dialogs.showInfo(
T.dialogs.blueprintsNotUnlocked.title,
T.dialogs.blueprintsNotUnlocked.desc
);
} else if (
!this.root.app.settings.getAllSettings().disableCutDeleteWarnings &&
this.selectedUids.size > 100
) {
const { ok } = this.root.hud.parts.dialogs.showWarning(
T.dialogs.massCutConfirm.title,
T.dialogs.massCutConfirm.desc.replace(
"<count>",
"" + formatBigNumberFull(this.selectedUids.size)
),
["cancel:good:escape", "ok:bad:enter"]
);
ok.add(() => this.doCut());
} else {
this.doCut();
}
}
doCut() {
if (this.selectedUids.size > 0) {
const entityUids = Array.from(this.selectedUids);
const cutAction = () => {
// copy code relies on entities still existing, so must copy before deleting.
this.root.hud.signals.buildingsSelectedForCopy.dispatch(entityUids);
for (let i = 0; i < entityUids.length; ++i) {
const uid = entityUids[i];
const entity = this.root.entityMgr.findByUid(uid);
if (!this.root.logic.tryDeleteBuilding(entity)) {
logger.error("Error in mass cut, could not remove building");
this.selectedUids.delete(uid);
}
}
};
const blueprint = Blueprint.fromUids(this.root, entityUids);
if (blueprint.canAfford(this.root)) {
cutAction();
} else {
const { cancel, ok } = this.root.hud.parts.dialogs.showWarning(
T.dialogs.massCutInsufficientConfirm.title,
T.dialogs.massCutInsufficientConfirm.desc,
["cancel:good:escape", "ok:bad:enter"]
);
ok.add(cutAction);
}
this.root.soundProxy.playUiClick();
} else {
this.root.soundProxy.playUiError();
}
}
/**
* mouse down pre handler
* @param {Vector} pos
* @param {enumMouseButton} mouseButton
*/
onMouseDown(pos, mouseButton) {
if (!this.root.keyMapper.getBinding(KEYMAPPINGS.massSelect.massSelectStart).pressed) {
return;
}
if (mouseButton !== enumMouseButton.left) {
return;
}
if (!this.root.keyMapper.getBinding(KEYMAPPINGS.massSelect.massSelectSelectMultiple).pressed) {
// Start new selection
this.selectedUids = new Set();
}
this.currentSelectionStartWorld = this.root.camera.screenToWorld(pos.copy());
this.currentSelectionEnd = pos.copy();
return STOP_PROPAGATION;
}
/**
* mouse move pre handler
* @param {Vector} pos
*/
onMouseMove(pos) {
if (this.currentSelectionStartWorld) {
this.currentSelectionEnd = pos.copy();
}
}
onMouseUp() {
if (this.currentSelectionStartWorld) {
const worldStart = this.currentSelectionStartWorld;
const worldEnd = this.root.camera.screenToWorld(this.currentSelectionEnd);
const tileStart = worldStart.toTileSpace();
const tileEnd = worldEnd.toTileSpace();
const realTileStart = tileStart.min(tileEnd);
const realTileEnd = tileStart.max(tileEnd);
for (let x = realTileStart.x; x <= realTileEnd.x; ++x) {
for (let y = realTileStart.y; y <= realTileEnd.y; ++y) {
const contents = this.root.map.getLayerContentXY(x, y, this.root.currentLayer);
if (contents && this.root.logic.canDeleteBuilding(contents)) {
this.selectedUids.add(contents.uid);
}
}
}
this.currentSelectionStartWorld = null;
this.currentSelectionEnd = null;
}
}
/**
*
* @param {DrawParameters} parameters
*/
draw(parameters) {
const boundsBorder = 2;
if (this.currentSelectionStartWorld) {
const worldStart = this.currentSelectionStartWorld;
const worldEnd = this.root.camera.screenToWorld(this.currentSelectionEnd);
const realWorldStart = worldStart.min(worldEnd);
const realWorldEnd = worldStart.max(worldEnd);
const tileStart = worldStart.toTileSpace();
const tileEnd = worldEnd.toTileSpace();
const realTileStart = tileStart.min(tileEnd);
const realTileEnd = tileStart.max(tileEnd);
parameters.context.lineWidth = 1;
parameters.context.fillStyle = THEME.map.selectionBackground;
parameters.context.strokeStyle = THEME.map.selectionOutline;
parameters.context.beginPath();
parameters.context.rect(
realWorldStart.x,
realWorldStart.y,
realWorldEnd.x - realWorldStart.x,
realWorldEnd.y - realWorldStart.y
);
parameters.context.fill();
parameters.context.stroke();
parameters.context.fillStyle = THEME.map.selectionOverlay;
const renderedUids = new Set();
for (let x = realTileStart.x; x <= realTileEnd.x; ++x) {
for (let y = realTileStart.y; y <= realTileEnd.y; ++y) {
const contents = this.root.map.getLayerContentXY(x, y, this.root.currentLayer);
if (contents && this.root.logic.canDeleteBuilding(contents)) {
// Prevent rendering the overlay twice
const uid = contents.uid;
if (renderedUids.has(uid)) {
continue;
}
renderedUids.add(uid);
const staticComp = contents.components.StaticMapEntity;
const bounds = staticComp.getTileSpaceBounds();
parameters.context.beginRoundedRect(
bounds.x * globalConfig.tileSize + boundsBorder,
bounds.y * globalConfig.tileSize + boundsBorder,
bounds.w * globalConfig.tileSize - 2 * boundsBorder,
bounds.h * globalConfig.tileSize - 2 * boundsBorder,
2
);
parameters.context.fill();
}
}
}
}
parameters.context.fillStyle = THEME.map.selectionOverlay;
this.selectedUids.forEach(uid => {
const entity = this.root.entityMgr.findByUid(uid);
const staticComp = entity.components.StaticMapEntity;
const bounds = staticComp.getTileSpaceBounds();
parameters.context.beginRoundedRect(
bounds.x * globalConfig.tileSize + boundsBorder,
bounds.y * globalConfig.tileSize + boundsBorder,
bounds.w * globalConfig.tileSize - 2 * boundsBorder,
bounds.h * globalConfig.tileSize - 2 * boundsBorder,
2
);
parameters.context.fill();
});
}
}

View File

@ -1,133 +1,133 @@
import { InputReceiver } from "../../../core/input_receiver";
import { makeDiv, removeAllChildren } from "../../../core/utils";
import { T } from "../../../translations";
import { KeyActionMapper, KEYMAPPINGS } from "../../key_action_mapper";
import { ShapeDefinition } from "../../shape_definition";
import { BaseHUDPart } from "../base_hud_part";
import { DynamicDomAttach } from "../dynamic_dom_attach";
const copy = require("clipboard-copy");
export class HUDShapeViewer extends BaseHUDPart {
createElements(parent) {
this.background = makeDiv(parent, "ingame_HUD_ShapeViewer", ["ingameDialog"]);
// DIALOG Inner / Wrapper
this.dialogInner = makeDiv(this.background, null, ["dialogInner"]);
this.title = makeDiv(this.dialogInner, null, ["title"], T.ingame.shapeViewer.title);
this.closeButton = makeDiv(this.title, null, ["closeButton"]);
this.trackClicks(this.closeButton, this.close);
this.contentDiv = makeDiv(this.dialogInner, null, ["content"]);
this.renderArea = makeDiv(this.contentDiv, null, ["renderArea"]);
this.infoArea = makeDiv(this.contentDiv, null, ["infoArea"]);
// Create button to copy the shape area
this.copyButton = document.createElement("button");
this.copyButton.classList.add("styledButton", "copyKey");
this.copyButton.innerText = T.ingame.shapeViewer.copyKey;
this.infoArea.appendChild(this.copyButton);
}
initialize() {
this.root.hud.signals.viewShapeDetailsRequested.add(this.renderForShape, this);
this.domAttach = new DynamicDomAttach(this.root, this.background, {
attachClass: "visible",
});
this.currentShapeKey = null;
this.inputReciever = new InputReceiver("shape_viewer");
this.keyActionMapper = new KeyActionMapper(this.root, this.inputReciever);
this.keyActionMapper.getBinding(KEYMAPPINGS.general.back).add(this.close, this);
this.trackClicks(this.copyButton, this.onCopyKeyRequested);
this.close();
}
/**
* Called when the copying of a key was requested
*/
onCopyKeyRequested() {
if (this.currentShapeKey) {
copy(this.currentShapeKey);
this.close();
}
}
/**
* Closes the dialog
*/
close() {
this.visible = false;
document.body.classList.remove("ingameDialogOpen");
this.root.app.inputMgr.makeSureDetached(this.inputReciever);
this.update();
}
/**
* Shows the viewer for a given definition
* @param {ShapeDefinition} definition
*/
renderForShape(definition) {
this.visible = true;
document.body.classList.add("ingameDialogOpen");
this.root.app.inputMgr.makeSureAttachedAndOnTop(this.inputReciever);
removeAllChildren(this.renderArea);
this.currentShapeKey = definition.getHash();
const layers = definition.layers;
this.contentDiv.setAttribute("data-layers", layers.length);
for (let i = 0; i < layers.length; ++i) {
const layerElem = makeDiv(this.renderArea, null, ["layer", "layer-" + i]);
let fakeLayers = [];
for (let k = 0; k < i; ++k) {
fakeLayers.push([null, null, null, null]);
}
fakeLayers.push(layers[i]);
const thisLayerOnly = new ShapeDefinition({ layers: fakeLayers });
const thisLayerCanvas = thisLayerOnly.generateAsCanvas(160);
layerElem.appendChild(thisLayerCanvas);
for (let quad = 0; quad < 4; ++quad) {
const quadElem = makeDiv(layerElem, null, ["quad", "quad-" + quad]);
const contents = layers[i][quad];
if (contents) {
const colorLabelElem = makeDiv(
quadElem,
null,
["colorLabel"],
T.ingame.colors[contents.color]
);
} else {
const emptyLabelElem = makeDiv(
quadElem,
null,
["emptyLabel"],
T.ingame.shapeViewer.empty
);
}
}
}
}
/**
* Cleans up everything
*/
cleanup() {
document.body.classList.remove("ingameDialogOpen");
}
update() {
this.domAttach.update(this.visible);
}
}
import { InputReceiver } from "../../../core/input_receiver";
import { makeDiv, removeAllChildren } from "../../../core/utils";
import { T } from "../../../translations";
import { KeyActionMapper, KEYMAPPINGS } from "../../key_action_mapper";
import { ShapeDefinition } from "../../shape_definition";
import { BaseHUDPart } from "../base_hud_part";
import { DynamicDomAttach } from "../dynamic_dom_attach";
const copy = require("clipboard-copy");
export class HUDShapeViewer extends BaseHUDPart {
createElements(parent) {
this.background = makeDiv(parent, "ingame_HUD_ShapeViewer", ["ingameDialog"]);
// DIALOG Inner / Wrapper
this.dialogInner = makeDiv(this.background, null, ["dialogInner"]);
this.title = makeDiv(this.dialogInner, null, ["title"], T.ingame.shapeViewer.title);
this.closeButton = makeDiv(this.title, null, ["closeButton"]);
this.trackClicks(this.closeButton, this.close);
this.contentDiv = makeDiv(this.dialogInner, null, ["content"]);
this.renderArea = makeDiv(this.contentDiv, null, ["renderArea"]);
this.infoArea = makeDiv(this.contentDiv, null, ["infoArea"]);
// Create button to copy the shape area
this.copyButton = document.createElement("button");
this.copyButton.classList.add("styledButton", "copyKey");
this.copyButton.innerText = T.ingame.shapeViewer.copyKey;
this.infoArea.appendChild(this.copyButton);
}
initialize() {
this.root.hud.signals.viewShapeDetailsRequested.add(this.renderForShape, this);
this.domAttach = new DynamicDomAttach(this.root, this.background, {
attachClass: "visible",
});
this.currentShapeKey = null;
this.inputReciever = new InputReceiver("shape_viewer");
this.keyActionMapper = new KeyActionMapper(this.root, this.inputReciever);
this.keyActionMapper.getBinding(KEYMAPPINGS.general.back).add(this.close, this);
this.trackClicks(this.copyButton, this.onCopyKeyRequested);
this.close();
}
/**
* Called when the copying of a key was requested
*/
onCopyKeyRequested() {
if (this.currentShapeKey) {
copy(this.currentShapeKey);
this.close();
}
}
/**
* Closes the dialog
*/
close() {
this.visible = false;
document.body.classList.remove("ingameDialogOpen");
this.root.app.inputMgr.makeSureDetached(this.inputReciever);
this.update();
}
/**
* Shows the viewer for a given definition
* @param {ShapeDefinition} definition
*/
renderForShape(definition) {
this.visible = true;
document.body.classList.add("ingameDialogOpen");
this.root.app.inputMgr.makeSureAttachedAndOnTop(this.inputReciever);
removeAllChildren(this.renderArea);
this.currentShapeKey = definition.getHash();
const layers = definition.layers;
this.contentDiv.setAttribute("data-layers", layers.length);
for (let i = layers.length - 1; i >= 0; --i) {
const layerElem = makeDiv(this.renderArea, null, ["layer", "layer-" + i]);
let fakeLayers = [];
for (let k = 0; k < i; ++k) {
fakeLayers.push([null, null, null, null]);
}
fakeLayers.push(layers[i]);
const thisLayerOnly = new ShapeDefinition({ layers: fakeLayers });
const thisLayerCanvas = thisLayerOnly.generateAsCanvas(160);
layerElem.appendChild(thisLayerCanvas);
for (let quad = 0; quad < 4; ++quad) {
const quadElem = makeDiv(layerElem, null, ["quad", "quad-" + quad]);
const contents = layers[i][quad];
if (contents) {
const colorLabelElem = makeDiv(
quadElem,
null,
["colorLabel"],
T.ingame.colors[contents.color]
);
} else {
const emptyLabelElem = makeDiv(
quadElem,
null,
["emptyLabel"],
T.ingame.shapeViewer.empty
);
}
}
}
}
/**
* Cleans up everything
*/
cleanup() {
document.body.classList.remove("ingameDialogOpen");
}
update() {
this.domAttach.update(this.visible);
}
}

View File

@ -47,9 +47,11 @@ export class HUDStatistics extends BaseHUDPart {
this.trackClicks(button, () => this.setDataSource(dataSource));
}
const buttonDisplaySorted = makeButton(this.filtersDisplayMode, ["displaySorted"]);
const buttonDisplayDetailed = makeButton(this.filtersDisplayMode, ["displayDetailed"]);
const buttonDisplayIcons = makeButton(this.filtersDisplayMode, ["displayIcons"]);
this.trackClicks(buttonDisplaySorted, () => this.toggleSorted());
this.trackClicks(buttonDisplayIcons, () => this.setDisplayMode(enumDisplayMode.icons));
this.trackClicks(buttonDisplayDetailed, () => this.setDisplayMode(enumDisplayMode.detailed));
@ -80,6 +82,21 @@ export class HUDStatistics extends BaseHUDPart {
}
}
/**
* @param {boolean} sorted
*/
setSorted(sorted) {
this.sorted = sorted;
this.dialogInner.setAttribute("data-sorted", String(sorted));
if (this.visible) {
this.rerenderFull();
}
}
toggleSorted() {
this.setSorted(!this.sorted);
}
initialize() {
this.domAttach = new DynamicDomAttach(this.root, this.background, {
attachClass: "visible",
@ -95,6 +112,7 @@ export class HUDStatistics extends BaseHUDPart {
/** @type {Object.<string, HUDShapeStatisticsHandle>} */
this.activeHandles = {};
this.setSorted(true);
this.setDataSource(enumAnalyticsDataSource.produced);
this.setDisplayMode(enumDisplayMode.detailed);
@ -183,7 +201,22 @@ export class HUDStatistics extends BaseHUDPart {
}
}
entries.sort((a, b) => b[1] - a[1]);
const pinnedShapes = this.root.hud.parts.pinnedShapes;
entries.sort((a, b) => {
const aPinned = pinnedShapes.isShapePinned(a[0]);
const bPinned = pinnedShapes.isShapePinned(b[0]);
if (aPinned !== bPinned) {
return aPinned ? -1 : 1;
}
// Sort by shape key for some consistency
if (!this.sorted || b[1] == a[1]) {
return b[0].localeCompare(a[0]);
}
return b[1] - a[1];
});
let rendered = new Set();

View File

@ -74,6 +74,11 @@ export class HUDShapeStatisticsHandle {
return;
}
this.element.classList.toggle(
"pinned",
this.root.hud.parts.pinnedShapes.isShapePinned(this.definition.getHash())
);
switch (dataSource) {
case enumAnalyticsDataSource.stored: {
this.counter.innerText = formatBigNumber(
@ -87,15 +92,10 @@ export class HUDShapeStatisticsHandle {
(this.root.productionAnalytics.getCurrentShapeRate(dataSource, this.definition) /
globalConfig.analyticsSliceDurationSeconds) *
60;
this.counter.innerText = T.ingame.statistics.shapesPerMinute.replace(
this.counter.innerText = T.ingame.statistics.shapesPerSecond.replace(
"<shapes>",
formatBigNumber(rate)
formatBigNumber(rate / 60)
);
if (G_IS_DEV && globalConfig.debug.detailedStatistics) {
this.counter.innerText = "" + round2Digits(rate / 60) + " /s";
}
break;
}
}

View File

@ -1,25 +1,27 @@
import { HUDBaseToolbar } from "./base_toolbar";
import { MetaWireBuilding } from "../../buildings/wire";
import { MetaConstantSignalBuilding } from "../../buildings/constant_signal";
import { MetaLogicGateBuilding } from "../../buildings/logic_gate";
import { MetaLeverBuilding } from "../../buildings/lever";
import { MetaWireTunnelBuilding } from "../../buildings/wire_tunnel";
const supportedBuildings = [
MetaWireBuilding,
MetaWireTunnelBuilding,
MetaConstantSignalBuilding,
MetaLogicGateBuilding,
MetaLeverBuilding,
];
export class HUDWiresToolbar extends HUDBaseToolbar {
constructor(root) {
super(root, {
supportedBuildings,
visibilityCondition: () =>
!this.root.camera.getIsMapOverlayActive() && this.root.currentLayer === "wires",
htmlElementId: "ingame_HUD_wires_toolbar",
});
}
}
import { HUDBaseToolbar } from "./base_toolbar";
import { MetaWireBuilding } from "../../buildings/wire";
import { MetaConstantSignalBuilding } from "../../buildings/constant_signal";
import { MetaLogicGateBuilding } from "../../buildings/logic_gate";
import { MetaLeverBuilding } from "../../buildings/lever";
import { MetaWireTunnelBuilding } from "../../buildings/wire_tunnel";
import { MetaVirtualProcessorBuilding } from "../../buildings/virtual_processor";
const supportedBuildings = [
MetaWireBuilding,
MetaWireTunnelBuilding,
MetaConstantSignalBuilding,
MetaLogicGateBuilding,
MetaLeverBuilding,
MetaVirtualProcessorBuilding,
];
export class HUDWiresToolbar extends HUDBaseToolbar {
constructor(root) {
super(root, {
supportedBuildings,
visibilityCondition: () =>
!this.root.camera.getIsMapOverlayActive() && this.root.currentLayer === "wires",
htmlElementId: "ingame_HUD_wires_toolbar",
});
}
}

View File

@ -1,456 +1,457 @@
/* typehints:start */
import { GameRoot } from "./root";
import { InputReceiver } from "../core/input_receiver";
import { Application } from "../application";
/* typehints:end */
import { Signal, STOP_PROPAGATION } from "../core/signal";
import { IS_MOBILE } from "../core/config";
import { T } from "../translations";
function key(str) {
return str.toUpperCase().charCodeAt(0);
}
export const KEYMAPPINGS = {
general: {
confirm: { keyCode: 13 }, // enter
back: { keyCode: 27, builtin: true }, // escape
},
ingame: {
menuOpenShop: { keyCode: key("F") },
menuOpenStats: { keyCode: key("G") },
menuClose: { keyCode: key("Q") },
toggleHud: { keyCode: 113 }, // F2
exportScreenshot: { keyCode: 114 }, // F3PS
toggleFPSInfo: { keyCode: 115 }, // F4
switchLayers: { keyCode: key("Y") },
},
navigation: {
mapMoveUp: { keyCode: key("W") },
mapMoveRight: { keyCode: key("D") },
mapMoveDown: { keyCode: key("S") },
mapMoveLeft: { keyCode: key("A") },
mapMoveFaster: { keyCode: 16 }, //shift
centerMap: { keyCode: 32 }, // SPACE
mapZoomIn: { keyCode: 187, repeated: true }, // "+"
mapZoomOut: { keyCode: 189, repeated: true }, // "-"
createMarker: { keyCode: key("M") },
},
buildings: {
belt: { keyCode: key("1") },
splitter: { keyCode: key("2") },
underground_belt: { keyCode: key("3") },
miner: { keyCode: key("4") },
cutter: { keyCode: key("5") },
rotater: { keyCode: key("6") },
stacker: { keyCode: key("7") },
mixer: { keyCode: key("8") },
painter: { keyCode: key("9") },
trash: { keyCode: key("0") },
lever: { keyCode: key("L") },
filter: { keyCode: key("B") },
display: { keyCode: key("N") },
wire: { keyCode: key("1") },
wire_tunnel: { keyCode: key("2") },
constant_signal: { keyCode: key("3") },
logic_gate: { keyCode: key("4") },
},
placement: {
pipette: { keyCode: key("Q") },
rotateWhilePlacing: { keyCode: key("R") },
rotateInverseModifier: { keyCode: 16 }, // SHIFT
cycleBuildingVariants: { keyCode: key("T") },
cycleBuildings: { keyCode: 9 }, // TAB
switchDirectionLockSide: { keyCode: key("R") },
},
massSelect: {
massSelectStart: { keyCode: 17 }, // CTRL
massSelectSelectMultiple: { keyCode: 16 }, // SHIFT
massSelectCopy: { keyCode: key("C") },
massSelectCut: { keyCode: key("X") },
confirmMassDelete: { keyCode: 46 }, // DEL
pasteLastBlueprint: { keyCode: key("V") },
},
placementModifiers: {
lockBeltDirection: { keyCode: 16 }, // SHIFT
placementDisableAutoOrientation: { keyCode: 17 }, // CTRL
placeMultiple: { keyCode: 16 }, // SHIFT
placeInverse: { keyCode: 18 }, // ALT
},
};
// Assign ids
for (const categoryId in KEYMAPPINGS) {
for (const mappingId in KEYMAPPINGS[categoryId]) {
KEYMAPPINGS[categoryId][mappingId].id = mappingId;
}
}
export const KEYCODE_LMB = 1;
export const KEYCODE_MMB = 2;
export const KEYCODE_RMB = 3;
/**
* Returns a keycode -> string
* @param {number} code
* @returns {string}
*/
export function getStringForKeyCode(code) {
switch (code) {
case KEYCODE_LMB:
return "LMB";
case KEYCODE_MMB:
return "MMB";
case KEYCODE_RMB:
return "RMB";
case 4:
return "MB4";
case 5:
return "MB5";
case 8:
return "⌫";
case 9:
return T.global.keys.tab;
case 13:
return "⏎";
case 16:
return "⇪";
case 17:
return T.global.keys.control;
case 18:
return T.global.keys.alt;
case 19:
return "PAUSE";
case 20:
return "CAPS";
case 27:
return T.global.keys.escape;
case 32:
return T.global.keys.space;
case 33:
return "PGUP";
case 34:
return "PGDOWN";
case 35:
return "END";
case 36:
return "HOME";
case 37:
return "⬅";
case 38:
return "⬆";
case 39:
return "➡";
case 40:
return "⬇";
case 44:
return "PRNT";
case 45:
return "INS";
case 46:
return "DEL";
case 93:
return "SEL";
case 96:
return "NUM 0";
case 97:
return "NUM 1";
case 98:
return "NUM 2";
case 99:
return "NUM 3";
case 100:
return "NUM 4";
case 101:
return "NUM 5";
case 102:
return "NUM 6";
case 103:
return "NUM 7";
case 104:
return "NUM 8";
case 105:
return "NUM 9";
case 106:
return "*";
case 107:
return "+";
case 109:
return "-";
case 110:
return ".";
case 111:
return "/";
case 112:
return "F1";
case 113:
return "F2";
case 114:
return "F3";
case 115:
return "F4";
case 116:
return "F4";
case 117:
return "F5";
case 118:
return "F6";
case 119:
return "F7";
case 120:
return "F8";
case 121:
return "F9";
case 122:
return "F10";
case 123:
return "F11";
case 124:
return "F12";
case 144:
return "NUMLOCK";
case 145:
return "SCRLOCK";
case 182:
return "COMP";
case 183:
return "CALC";
case 186:
return ";";
case 187:
return "+";
case 188:
return ",";
case 189:
return "-";
case 191:
return "/";
case 219:
return "[";
case 220:
return "\\";
case 221:
return "]";
case 222:
return "'";
}
return String.fromCharCode(code);
}
export class Keybinding {
/**
*
* @param {KeyActionMapper} keyMapper
* @param {Application} app
* @param {object} param0
* @param {number} param0.keyCode
* @param {boolean=} param0.builtin
* @param {boolean=} param0.repeated
*/
constructor(keyMapper, app, { keyCode, builtin = false, repeated = false }) {
assert(keyCode && Number.isInteger(keyCode), "Invalid key code: " + keyCode);
this.keyMapper = keyMapper;
this.app = app;
this.keyCode = keyCode;
this.builtin = builtin;
this.repeated = repeated;
this.signal = new Signal();
this.toggled = new Signal();
}
/**
* Returns whether this binding is currently pressed
* @returns {boolean}
*/
get pressed() {
// Check if the key is down
if (this.app.inputMgr.keysDown.has(this.keyCode)) {
// Check if it is the top reciever
const reciever = this.keyMapper.inputReceiver;
return this.app.inputMgr.getTopReciever() === reciever;
}
return false;
}
/**
* Adds an event listener
* @param {function() : void} receiver
* @param {object=} scope
*/
add(receiver, scope = null) {
this.signal.add(receiver, scope);
}
/**
* @param {Element} elem
* @returns {HTMLElement} the created element, or null if the keybindings are not shown
* */
appendLabelToElement(elem) {
if (IS_MOBILE) {
return null;
}
const spacer = document.createElement("code");
spacer.classList.add("keybinding");
spacer.innerHTML = getStringForKeyCode(this.keyCode);
elem.appendChild(spacer);
return spacer;
}
/**
* Returns the key code as a nice string
*/
getKeyCodeString() {
return getStringForKeyCode(this.keyCode);
}
/**
* Remvoes all signal receivers
*/
clearSignalReceivers() {
this.signal.removeAll();
}
}
export class KeyActionMapper {
/**
*
* @param {GameRoot} root
* @param {InputReceiver} inputReciever
*/
constructor(root, inputReciever) {
this.root = root;
this.inputReceiver = inputReciever;
inputReciever.keydown.add(this.handleKeydown, this);
inputReciever.keyup.add(this.handleKeyup, this);
/** @type {Object.<string, Keybinding>} */
this.keybindings = {};
const overrides = root.app.settings.getKeybindingOverrides();
for (const category in KEYMAPPINGS) {
for (const key in KEYMAPPINGS[category]) {
let payload = Object.assign({}, KEYMAPPINGS[category][key]);
if (overrides[key]) {
payload.keyCode = overrides[key];
}
this.keybindings[key] = new Keybinding(this, this.root.app, payload);
}
}
inputReciever.pageBlur.add(this.onPageBlur, this);
inputReciever.destroyed.add(this.cleanup, this);
}
/**
* Returns all keybindings starting with the given id
* @param {string} pattern
* @returns {Array<Keybinding>}
*/
getKeybindingsStartingWith(pattern) {
let result = [];
for (const key in this.keybindings) {
if (key.startsWith(pattern)) {
result.push(this.keybindings[key]);
}
}
return result;
}
/**
* Forwards the given events to the other mapper (used in tooltips)
* @param {KeyActionMapper} receiver
* @param {Array<string>} bindings
*/
forward(receiver, bindings) {
for (let i = 0; i < bindings.length; ++i) {
const key = bindings[i];
this.keybindings[key].signal.add((...args) => receiver.keybindings[key].signal.dispatch(...args));
}
}
cleanup() {
for (const key in this.keybindings) {
this.keybindings[key].signal.removeAll();
}
}
onPageBlur() {
// Reset all down states
// Find mapping
for (const key in this.keybindings) {
/** @type {Keybinding} */
const binding = this.keybindings[key];
}
}
/**
* Internal keydown handler
* @param {object} param0
* @param {number} param0.keyCode
* @param {boolean} param0.shift
* @param {boolean} param0.alt
* @param {boolean=} param0.initial
*/
handleKeydown({ keyCode, shift, alt, initial }) {
let stop = false;
// Find mapping
for (const key in this.keybindings) {
/** @type {Keybinding} */
const binding = this.keybindings[key];
if (binding.keyCode === keyCode && (initial || binding.repeated)) {
/** @type {Signal} */
const signal = this.keybindings[key].signal;
if (signal.dispatch() === STOP_PROPAGATION) {
return;
}
}
}
if (stop) {
return STOP_PROPAGATION;
}
}
/**
* Internal keyup handler
* @param {object} param0
* @param {number} param0.keyCode
* @param {boolean} param0.shift
* @param {boolean} param0.alt
*/
handleKeyup({ keyCode, shift, alt }) {
// Empty
}
/**
* Returns a given keybinding
* @param {{ keyCode: number }} binding
* @returns {Keybinding}
*/
getBinding(binding) {
// @ts-ignore
const id = binding.id;
assert(id, "Not a valid keybinding: " + JSON.stringify(binding));
assert(this.keybindings[id], "Keybinding " + id + " not known!");
return this.keybindings[id];
}
}
/* typehints:start */
import { GameRoot } from "./root";
import { InputReceiver } from "../core/input_receiver";
import { Application } from "../application";
/* typehints:end */
import { Signal, STOP_PROPAGATION } from "../core/signal";
import { IS_MOBILE } from "../core/config";
import { T } from "../translations";
function key(str) {
return str.toUpperCase().charCodeAt(0);
}
export const KEYMAPPINGS = {
general: {
confirm: { keyCode: 13 }, // enter
back: { keyCode: 27, builtin: true }, // escape
},
ingame: {
menuOpenShop: { keyCode: key("F") },
menuOpenStats: { keyCode: key("G") },
menuClose: { keyCode: key("Q") },
toggleHud: { keyCode: 113 }, // F2
exportScreenshot: { keyCode: 114 }, // F3PS
toggleFPSInfo: { keyCode: 115 }, // F4
switchLayers: { keyCode: key("Y") },
},
navigation: {
mapMoveUp: { keyCode: key("W") },
mapMoveRight: { keyCode: key("D") },
mapMoveDown: { keyCode: key("S") },
mapMoveLeft: { keyCode: key("A") },
mapMoveFaster: { keyCode: 16 }, //shift
centerMap: { keyCode: 32 }, // SPACE
mapZoomIn: { keyCode: 187, repeated: true }, // "+"
mapZoomOut: { keyCode: 189, repeated: true }, // "-"
createMarker: { keyCode: key("M") },
},
buildings: {
belt: { keyCode: key("1") },
splitter: { keyCode: key("2") },
underground_belt: { keyCode: key("3") },
miner: { keyCode: key("4") },
cutter: { keyCode: key("5") },
rotater: { keyCode: key("6") },
stacker: { keyCode: key("7") },
mixer: { keyCode: key("8") },
painter: { keyCode: key("9") },
trash: { keyCode: key("0") },
lever: { keyCode: key("L") },
filter: { keyCode: key("B") },
display: { keyCode: key("N") },
wire: { keyCode: key("1") },
wire_tunnel: { keyCode: key("2") },
constant_signal: { keyCode: key("3") },
logic_gate: { keyCode: key("4") },
virtual_processor: { keyCode: key("5") },
},
placement: {
pipette: { keyCode: key("Q") },
rotateWhilePlacing: { keyCode: key("R") },
rotateInverseModifier: { keyCode: 16 }, // SHIFT
cycleBuildingVariants: { keyCode: key("T") },
cycleBuildings: { keyCode: 9 }, // TAB
switchDirectionLockSide: { keyCode: key("R") },
},
massSelect: {
massSelectStart: { keyCode: 17 }, // CTRL
massSelectSelectMultiple: { keyCode: 16 }, // SHIFT
massSelectCopy: { keyCode: key("C") },
massSelectCut: { keyCode: key("X") },
confirmMassDelete: { keyCode: 46 }, // DEL
pasteLastBlueprint: { keyCode: key("V") },
},
placementModifiers: {
lockBeltDirection: { keyCode: 16 }, // SHIFT
placementDisableAutoOrientation: { keyCode: 17 }, // CTRL
placeMultiple: { keyCode: 16 }, // SHIFT
placeInverse: { keyCode: 18 }, // ALT
},
};
// Assign ids
for (const categoryId in KEYMAPPINGS) {
for (const mappingId in KEYMAPPINGS[categoryId]) {
KEYMAPPINGS[categoryId][mappingId].id = mappingId;
}
}
export const KEYCODE_LMB = 1;
export const KEYCODE_MMB = 2;
export const KEYCODE_RMB = 3;
/**
* Returns a keycode -> string
* @param {number} code
* @returns {string}
*/
export function getStringForKeyCode(code) {
switch (code) {
case KEYCODE_LMB:
return "LMB";
case KEYCODE_MMB:
return "MMB";
case KEYCODE_RMB:
return "RMB";
case 4:
return "MB4";
case 5:
return "MB5";
case 8:
return "⌫";
case 9:
return T.global.keys.tab;
case 13:
return "⏎";
case 16:
return "⇪";
case 17:
return T.global.keys.control;
case 18:
return T.global.keys.alt;
case 19:
return "PAUSE";
case 20:
return "CAPS";
case 27:
return T.global.keys.escape;
case 32:
return T.global.keys.space;
case 33:
return "PGUP";
case 34:
return "PGDOWN";
case 35:
return "END";
case 36:
return "HOME";
case 37:
return "⬅";
case 38:
return "⬆";
case 39:
return "➡";
case 40:
return "⬇";
case 44:
return "PRNT";
case 45:
return "INS";
case 46:
return "DEL";
case 93:
return "SEL";
case 96:
return "NUM 0";
case 97:
return "NUM 1";
case 98:
return "NUM 2";
case 99:
return "NUM 3";
case 100:
return "NUM 4";
case 101:
return "NUM 5";
case 102:
return "NUM 6";
case 103:
return "NUM 7";
case 104:
return "NUM 8";
case 105:
return "NUM 9";
case 106:
return "*";
case 107:
return "+";
case 109:
return "-";
case 110:
return ".";
case 111:
return "/";
case 112:
return "F1";
case 113:
return "F2";
case 114:
return "F3";
case 115:
return "F4";
case 116:
return "F4";
case 117:
return "F5";
case 118:
return "F6";
case 119:
return "F7";
case 120:
return "F8";
case 121:
return "F9";
case 122:
return "F10";
case 123:
return "F11";
case 124:
return "F12";
case 144:
return "NUMLOCK";
case 145:
return "SCRLOCK";
case 182:
return "COMP";
case 183:
return "CALC";
case 186:
return ";";
case 187:
return "+";
case 188:
return ",";
case 189:
return "-";
case 191:
return "/";
case 219:
return "[";
case 220:
return "\\";
case 221:
return "]";
case 222:
return "'";
}
return String.fromCharCode(code);
}
export class Keybinding {
/**
*
* @param {KeyActionMapper} keyMapper
* @param {Application} app
* @param {object} param0
* @param {number} param0.keyCode
* @param {boolean=} param0.builtin
* @param {boolean=} param0.repeated
*/
constructor(keyMapper, app, { keyCode, builtin = false, repeated = false }) {
assert(keyCode && Number.isInteger(keyCode), "Invalid key code: " + keyCode);
this.keyMapper = keyMapper;
this.app = app;
this.keyCode = keyCode;
this.builtin = builtin;
this.repeated = repeated;
this.signal = new Signal();
this.toggled = new Signal();
}
/**
* Returns whether this binding is currently pressed
* @returns {boolean}
*/
get pressed() {
// Check if the key is down
if (this.app.inputMgr.keysDown.has(this.keyCode)) {
// Check if it is the top reciever
const reciever = this.keyMapper.inputReceiver;
return this.app.inputMgr.getTopReciever() === reciever;
}
return false;
}
/**
* Adds an event listener
* @param {function() : void} receiver
* @param {object=} scope
*/
add(receiver, scope = null) {
this.signal.add(receiver, scope);
}
/**
* @param {Element} elem
* @returns {HTMLElement} the created element, or null if the keybindings are not shown
* */
appendLabelToElement(elem) {
if (IS_MOBILE) {
return null;
}
const spacer = document.createElement("code");
spacer.classList.add("keybinding");
spacer.innerHTML = getStringForKeyCode(this.keyCode);
elem.appendChild(spacer);
return spacer;
}
/**
* Returns the key code as a nice string
*/
getKeyCodeString() {
return getStringForKeyCode(this.keyCode);
}
/**
* Remvoes all signal receivers
*/
clearSignalReceivers() {
this.signal.removeAll();
}
}
export class KeyActionMapper {
/**
*
* @param {GameRoot} root
* @param {InputReceiver} inputReciever
*/
constructor(root, inputReciever) {
this.root = root;
this.inputReceiver = inputReciever;
inputReciever.keydown.add(this.handleKeydown, this);
inputReciever.keyup.add(this.handleKeyup, this);
/** @type {Object.<string, Keybinding>} */
this.keybindings = {};
const overrides = root.app.settings.getKeybindingOverrides();
for (const category in KEYMAPPINGS) {
for (const key in KEYMAPPINGS[category]) {
let payload = Object.assign({}, KEYMAPPINGS[category][key]);
if (overrides[key]) {
payload.keyCode = overrides[key];
}
this.keybindings[key] = new Keybinding(this, this.root.app, payload);
}
}
inputReciever.pageBlur.add(this.onPageBlur, this);
inputReciever.destroyed.add(this.cleanup, this);
}
/**
* Returns all keybindings starting with the given id
* @param {string} pattern
* @returns {Array<Keybinding>}
*/
getKeybindingsStartingWith(pattern) {
let result = [];
for (const key in this.keybindings) {
if (key.startsWith(pattern)) {
result.push(this.keybindings[key]);
}
}
return result;
}
/**
* Forwards the given events to the other mapper (used in tooltips)
* @param {KeyActionMapper} receiver
* @param {Array<string>} bindings
*/
forward(receiver, bindings) {
for (let i = 0; i < bindings.length; ++i) {
const key = bindings[i];
this.keybindings[key].signal.add((...args) => receiver.keybindings[key].signal.dispatch(...args));
}
}
cleanup() {
for (const key in this.keybindings) {
this.keybindings[key].signal.removeAll();
}
}
onPageBlur() {
// Reset all down states
// Find mapping
for (const key in this.keybindings) {
/** @type {Keybinding} */
const binding = this.keybindings[key];
}
}
/**
* Internal keydown handler
* @param {object} param0
* @param {number} param0.keyCode
* @param {boolean} param0.shift
* @param {boolean} param0.alt
* @param {boolean=} param0.initial
*/
handleKeydown({ keyCode, shift, alt, initial }) {
let stop = false;
// Find mapping
for (const key in this.keybindings) {
/** @type {Keybinding} */
const binding = this.keybindings[key];
if (binding.keyCode === keyCode && (initial || binding.repeated)) {
/** @type {Signal} */
const signal = this.keybindings[key].signal;
if (signal.dispatch() === STOP_PROPAGATION) {
return;
}
}
}
if (stop) {
return STOP_PROPAGATION;
}
}
/**
* Internal keyup handler
* @param {object} param0
* @param {number} param0.keyCode
* @param {boolean} param0.shift
* @param {boolean} param0.alt
*/
handleKeyup({ keyCode, shift, alt }) {
// Empty
}
/**
* Returns a given keybinding
* @param {{ keyCode: number }} binding
* @returns {Keybinding}
*/
getBinding(binding) {
// @ts-ignore
const id = binding.id;
assert(id, "Not a valid keybinding: " + JSON.stringify(binding));
assert(this.keybindings[id], "Keybinding " + id + " not known!");
return this.keybindings[id];
}
}

View File

@ -1,274 +1,281 @@
import { globalConfig } from "../core/config";
import { DrawParameters } from "../core/draw_parameters";
import { getBuildingDataFromCode } from "./building_codes";
import { Entity } from "./entity";
import { MapChunk } from "./map_chunk";
import { GameRoot } from "./root";
import { THEME } from "./theme";
import { drawSpriteClipped } from "../core/draw_utils";
export const CHUNK_OVERLAY_RES = 3;
export class MapChunkView extends MapChunk {
/**
*
* @param {GameRoot} root
* @param {number} x
* @param {number} y
*/
constructor(root, x, y) {
super(root, x, y);
/**
* Whenever something changes, we increase this number - so we know we need to redraw
*/
this.renderIteration = 0;
this.markDirty();
}
/**
* Marks this chunk as dirty, rerendering all caches
*/
markDirty() {
++this.renderIteration;
this.renderKey = this.x + "/" + this.y + "@" + this.renderIteration;
}
/**
* Draws the background layer
* @param {DrawParameters} parameters
*/
drawBackgroundLayer(parameters) {
const systems = this.root.systemMgr.systems;
systems.mapResources.drawChunk(parameters, this);
systems.beltUnderlays.drawChunk(parameters, this);
systems.belt.drawChunk(parameters, this);
}
/**
* Draws the foreground layer
* @param {DrawParameters} parameters
*/
drawForegroundLayer(parameters) {
const systems = this.root.systemMgr.systems;
systems.itemEjector.drawChunk(parameters, this);
systems.itemAcceptor.drawChunk(parameters, this);
systems.miner.drawChunk(parameters, this);
systems.staticMapEntities.drawChunk(parameters, this);
systems.lever.drawChunk(parameters, this);
systems.display.drawChunk(parameters, this);
systems.storage.drawChunk(parameters, this);
}
/**
* Overlay
* @param {DrawParameters} parameters
*/
drawOverlay(parameters) {
const overlaySize = globalConfig.mapChunkSize * CHUNK_OVERLAY_RES;
const sprite = this.root.buffers.getForKey({
key: "chunk@" + this.root.currentLayer,
subKey: this.renderKey,
w: overlaySize,
h: overlaySize,
dpi: 1,
redrawMethod: this.generateOverlayBuffer.bind(this),
});
const dims = globalConfig.mapChunkWorldSize;
// Draw chunk "pixel" art
parameters.context.imageSmoothingEnabled = false;
drawSpriteClipped({
parameters,
sprite,
x: this.x * dims,
y: this.y * dims,
w: dims,
h: dims,
originalW: overlaySize,
originalH: overlaySize,
});
parameters.context.imageSmoothingEnabled = true;
// Draw patch items
if (this.root.currentLayer === "regular") {
for (let i = 0; i < this.patches.length; ++i) {
const patch = this.patches[i];
const destX = this.x * dims + patch.pos.x * globalConfig.tileSize;
const destY = this.y * dims + patch.pos.y * globalConfig.tileSize;
const diameter = Math.min(80, 30 / parameters.zoomLevel);
patch.item.drawItemCenteredClipped(destX, destY, parameters, diameter);
}
}
}
/**
*
* @param {HTMLCanvasElement} canvas
* @param {CanvasRenderingContext2D} context
* @param {number} w
* @param {number} h
* @param {number} dpi
*/
generateOverlayBuffer(canvas, context, w, h, dpi) {
context.fillStyle =
this.containedEntities.length > 0
? THEME.map.chunkOverview.filled
: THEME.map.chunkOverview.empty;
context.fillRect(0, 0, w, h);
for (let x = 0; x < globalConfig.mapChunkSize; ++x) {
const lowerArray = this.lowerLayer[x];
const upperArray = this.contents[x];
for (let y = 0; y < globalConfig.mapChunkSize; ++y) {
const upperContent = upperArray[y];
if (upperContent) {
const staticComp = upperContent.components.StaticMapEntity;
const data = getBuildingDataFromCode(staticComp.code);
const metaBuilding = data.metaInstance;
const overlayMatrix = metaBuilding.getSpecialOverlayRenderMatrix(
staticComp.rotation,
data.rotationVariant,
data.variant,
upperContent
);
if (overlayMatrix) {
// Draw lower content first since it "shines" through
const lowerContent = lowerArray[y];
if (lowerContent) {
context.fillStyle = lowerContent.getBackgroundColorAsResource();
context.fillRect(
x * CHUNK_OVERLAY_RES,
y * CHUNK_OVERLAY_RES,
CHUNK_OVERLAY_RES,
CHUNK_OVERLAY_RES
);
}
context.fillStyle = metaBuilding.getSilhouetteColor();
for (let dx = 0; dx < 3; ++dx) {
for (let dy = 0; dy < 3; ++dy) {
const isFilled = overlayMatrix[dx + dy * 3];
if (isFilled) {
context.fillRect(
x * CHUNK_OVERLAY_RES + dx,
y * CHUNK_OVERLAY_RES + dy,
1,
1
);
}
}
}
continue;
} else {
context.fillStyle = metaBuilding.getSilhouetteColor();
context.fillRect(
x * CHUNK_OVERLAY_RES,
y * CHUNK_OVERLAY_RES,
CHUNK_OVERLAY_RES,
CHUNK_OVERLAY_RES
);
continue;
}
}
const lowerContent = lowerArray[y];
if (lowerContent) {
context.fillStyle = lowerContent.getBackgroundColorAsResource();
context.fillRect(
x * CHUNK_OVERLAY_RES,
y * CHUNK_OVERLAY_RES,
CHUNK_OVERLAY_RES,
CHUNK_OVERLAY_RES
);
}
}
}
if (this.root.currentLayer === "wires") {
// Draw wires overlay
context.fillStyle = THEME.map.wires.overlayColor;
context.fillRect(0, 0, w, h);
for (let x = 0; x < globalConfig.mapChunkSize; ++x) {
const wiresArray = this.wireContents[x];
for (let y = 0; y < globalConfig.mapChunkSize; ++y) {
const content = wiresArray[y];
if (!content) {
continue;
}
MapChunkView.drawSingleWiresOverviewTile({
context,
x: x * CHUNK_OVERLAY_RES,
y: y * CHUNK_OVERLAY_RES,
entity: content,
tileSizePixels: CHUNK_OVERLAY_RES,
});
}
}
}
}
/**
* @param {object} param0
* @param {CanvasRenderingContext2D} param0.context
* @param {number} param0.x
* @param {number} param0.y
* @param {Entity} param0.entity
* @param {number} param0.tileSizePixels
* @param {string=} param0.overrideColor Optionally override the color to be rendered
*/
static drawSingleWiresOverviewTile({ context, x, y, entity, tileSizePixels, overrideColor = null }) {
const staticComp = entity.components.StaticMapEntity;
const data = getBuildingDataFromCode(staticComp.code);
const metaBuilding = data.metaInstance;
const overlayMatrix = metaBuilding.getSpecialOverlayRenderMatrix(
staticComp.rotation,
data.rotationVariant,
data.variant,
entity
);
context.fillStyle = overrideColor || metaBuilding.getSilhouetteColor();
if (overlayMatrix) {
for (let dx = 0; dx < 3; ++dx) {
for (let dy = 0; dy < 3; ++dy) {
const isFilled = overlayMatrix[dx + dy * 3];
if (isFilled) {
context.fillRect(
x + (dx * tileSizePixels) / CHUNK_OVERLAY_RES,
y + (dy * tileSizePixels) / CHUNK_OVERLAY_RES,
tileSizePixels / CHUNK_OVERLAY_RES,
tileSizePixels / CHUNK_OVERLAY_RES
);
}
}
}
} else {
context.fillRect(x, y, tileSizePixels, tileSizePixels);
}
}
/**
* Draws the wires layer
* @param {DrawParameters} parameters
*/
drawWiresForegroundLayer(parameters) {
const systems = this.root.systemMgr.systems;
systems.wire.drawChunk(parameters, this);
systems.staticMapEntities.drawWiresChunk(parameters, this);
systems.wiredPins.drawChunk(parameters, this);
}
}
import { globalConfig } from "../core/config";
import { DrawParameters } from "../core/draw_parameters";
import { getBuildingDataFromCode } from "./building_codes";
import { Entity } from "./entity";
import { MapChunk } from "./map_chunk";
import { GameRoot } from "./root";
import { THEME } from "./theme";
import { drawSpriteClipped } from "../core/draw_utils";
export const CHUNK_OVERLAY_RES = 3;
export class MapChunkView extends MapChunk {
/**
*
* @param {GameRoot} root
* @param {number} x
* @param {number} y
*/
constructor(root, x, y) {
super(root, x, y);
/**
* Whenever something changes, we increase this number - so we know we need to redraw
*/
this.renderIteration = 0;
this.markDirty();
}
/**
* Marks this chunk as dirty, rerendering all caches
*/
markDirty() {
++this.renderIteration;
this.renderKey = this.x + "/" + this.y + "@" + this.renderIteration;
}
/**
* Draws the background layer
* @param {DrawParameters} parameters
*/
drawBackgroundLayer(parameters) {
const systems = this.root.systemMgr.systems;
systems.mapResources.drawChunk(parameters, this);
systems.beltUnderlays.drawChunk(parameters, this);
systems.belt.drawChunk(parameters, this);
}
/**
* Draws the dynamic foreground layer
* @param {DrawParameters} parameters
*/
drawForegroundDynamicLayer(parameters) {
const systems = this.root.systemMgr.systems;
systems.itemEjector.drawChunk(parameters, this);
systems.itemAcceptor.drawChunk(parameters, this);
systems.miner.drawChunk(parameters, this);
}
/**
* Draws the static foreground layer
* @param {DrawParameters} parameters
*/
drawForegroundStaticLayer(parameters) {
const systems = this.root.systemMgr.systems;
systems.staticMapEntities.drawChunk(parameters, this);
systems.lever.drawChunk(parameters, this);
systems.display.drawChunk(parameters, this);
systems.storage.drawChunk(parameters, this);
}
/**
* Overlay
* @param {DrawParameters} parameters
*/
drawOverlay(parameters) {
const overlaySize = globalConfig.mapChunkSize * CHUNK_OVERLAY_RES;
const sprite = this.root.buffers.getForKey({
key: "chunk@" + this.root.currentLayer,
subKey: this.renderKey,
w: overlaySize,
h: overlaySize,
dpi: 1,
redrawMethod: this.generateOverlayBuffer.bind(this),
});
const dims = globalConfig.mapChunkWorldSize;
// Draw chunk "pixel" art
parameters.context.imageSmoothingEnabled = false;
drawSpriteClipped({
parameters,
sprite,
x: this.x * dims,
y: this.y * dims,
w: dims,
h: dims,
originalW: overlaySize,
originalH: overlaySize,
});
parameters.context.imageSmoothingEnabled = true;
// Draw patch items
if (this.root.currentLayer === "regular") {
for (let i = 0; i < this.patches.length; ++i) {
const patch = this.patches[i];
const destX = this.x * dims + patch.pos.x * globalConfig.tileSize;
const destY = this.y * dims + patch.pos.y * globalConfig.tileSize;
const diameter = Math.min(80, 30 / parameters.zoomLevel);
patch.item.drawItemCenteredClipped(destX, destY, parameters, diameter);
}
}
}
/**
*
* @param {HTMLCanvasElement} canvas
* @param {CanvasRenderingContext2D} context
* @param {number} w
* @param {number} h
* @param {number} dpi
*/
generateOverlayBuffer(canvas, context, w, h, dpi) {
context.fillStyle =
this.containedEntities.length > 0
? THEME.map.chunkOverview.filled
: THEME.map.chunkOverview.empty;
context.fillRect(0, 0, w, h);
for (let x = 0; x < globalConfig.mapChunkSize; ++x) {
const lowerArray = this.lowerLayer[x];
const upperArray = this.contents[x];
for (let y = 0; y < globalConfig.mapChunkSize; ++y) {
const upperContent = upperArray[y];
if (upperContent) {
const staticComp = upperContent.components.StaticMapEntity;
const data = getBuildingDataFromCode(staticComp.code);
const metaBuilding = data.metaInstance;
const overlayMatrix = metaBuilding.getSpecialOverlayRenderMatrix(
staticComp.rotation,
data.rotationVariant,
data.variant,
upperContent
);
if (overlayMatrix) {
// Draw lower content first since it "shines" through
const lowerContent = lowerArray[y];
if (lowerContent) {
context.fillStyle = lowerContent.getBackgroundColorAsResource();
context.fillRect(
x * CHUNK_OVERLAY_RES,
y * CHUNK_OVERLAY_RES,
CHUNK_OVERLAY_RES,
CHUNK_OVERLAY_RES
);
}
context.fillStyle = metaBuilding.getSilhouetteColor();
for (let dx = 0; dx < 3; ++dx) {
for (let dy = 0; dy < 3; ++dy) {
const isFilled = overlayMatrix[dx + dy * 3];
if (isFilled) {
context.fillRect(
x * CHUNK_OVERLAY_RES + dx,
y * CHUNK_OVERLAY_RES + dy,
1,
1
);
}
}
}
continue;
} else {
context.fillStyle = metaBuilding.getSilhouetteColor();
context.fillRect(
x * CHUNK_OVERLAY_RES,
y * CHUNK_OVERLAY_RES,
CHUNK_OVERLAY_RES,
CHUNK_OVERLAY_RES
);
continue;
}
}
const lowerContent = lowerArray[y];
if (lowerContent) {
context.fillStyle = lowerContent.getBackgroundColorAsResource();
context.fillRect(
x * CHUNK_OVERLAY_RES,
y * CHUNK_OVERLAY_RES,
CHUNK_OVERLAY_RES,
CHUNK_OVERLAY_RES
);
}
}
}
if (this.root.currentLayer === "wires") {
// Draw wires overlay
context.fillStyle = THEME.map.wires.overlayColor;
context.fillRect(0, 0, w, h);
for (let x = 0; x < globalConfig.mapChunkSize; ++x) {
const wiresArray = this.wireContents[x];
for (let y = 0; y < globalConfig.mapChunkSize; ++y) {
const content = wiresArray[y];
if (!content) {
continue;
}
MapChunkView.drawSingleWiresOverviewTile({
context,
x: x * CHUNK_OVERLAY_RES,
y: y * CHUNK_OVERLAY_RES,
entity: content,
tileSizePixels: CHUNK_OVERLAY_RES,
});
}
}
}
}
/**
* @param {object} param0
* @param {CanvasRenderingContext2D} param0.context
* @param {number} param0.x
* @param {number} param0.y
* @param {Entity} param0.entity
* @param {number} param0.tileSizePixels
* @param {string=} param0.overrideColor Optionally override the color to be rendered
*/
static drawSingleWiresOverviewTile({ context, x, y, entity, tileSizePixels, overrideColor = null }) {
const staticComp = entity.components.StaticMapEntity;
const data = getBuildingDataFromCode(staticComp.code);
const metaBuilding = data.metaInstance;
const overlayMatrix = metaBuilding.getSpecialOverlayRenderMatrix(
staticComp.rotation,
data.rotationVariant,
data.variant,
entity
);
context.fillStyle = overrideColor || metaBuilding.getSilhouetteColor();
if (overlayMatrix) {
for (let dx = 0; dx < 3; ++dx) {
for (let dy = 0; dy < 3; ++dy) {
const isFilled = overlayMatrix[dx + dy * 3];
if (isFilled) {
context.fillRect(
x + (dx * tileSizePixels) / CHUNK_OVERLAY_RES,
y + (dy * tileSizePixels) / CHUNK_OVERLAY_RES,
tileSizePixels / CHUNK_OVERLAY_RES,
tileSizePixels / CHUNK_OVERLAY_RES
);
}
}
}
} else {
context.fillRect(x, y, tileSizePixels, tileSizePixels);
}
}
/**
* Draws the wires layer
* @param {DrawParameters} parameters
*/
drawWiresForegroundLayer(parameters) {
const systems = this.root.systemMgr.systems;
systems.wire.drawChunk(parameters, this);
systems.staticMapEntities.drawWiresChunk(parameters, this);
systems.wiredPins.drawChunk(parameters, this);
}
}

View File

@ -1,252 +1,253 @@
import { globalConfig } from "../core/config";
import { DrawParameters } from "../core/draw_parameters";
import { BaseMap } from "./map";
import { freeCanvas, makeOffscreenBuffer } from "../core/buffer_utils";
import { Entity } from "./entity";
import { THEME } from "./theme";
import { MapChunkView } from "./map_chunk_view";
/**
* This is the view of the map, it extends the map which is the raw model and allows
* to draw it
*/
export class MapView extends BaseMap {
constructor(root) {
super(root);
/**
* DPI of the background cache images, required in some places
*/
this.backgroundCacheDPI = 2;
/**
* The cached background sprite, containing the flat background
* @type {HTMLCanvasElement} */
this.cachedBackgroundCanvas = null;
/** @type {CanvasRenderingContext2D} */
this.cachedBackgroundContext = null;
/**
* Cached pattern of the stripes background
* @type {CanvasPattern} */
this.cachedBackgroundPattern = null;
this.internalInitializeCachedBackgroundCanvases();
this.root.signals.aboutToDestruct.add(this.cleanup, this);
this.root.signals.entityAdded.add(this.onEntityChanged, this);
this.root.signals.entityDestroyed.add(this.onEntityChanged, this);
this.root.signals.entityChanged.add(this.onEntityChanged, this);
}
cleanup() {
freeCanvas(this.cachedBackgroundCanvas);
this.cachedBackgroundCanvas = null;
this.cachedBackgroundPattern = null;
}
/**
* Called when an entity was added, removed or changed
* @param {Entity} entity
*/
onEntityChanged(entity) {
const staticComp = entity.components.StaticMapEntity;
if (staticComp) {
const rect = staticComp.getTileSpaceBounds();
for (let x = rect.x; x <= rect.right(); ++x) {
for (let y = rect.y; y <= rect.bottom(); ++y) {
this.root.map.getOrCreateChunkAtTile(x, y).markDirty();
}
}
}
}
/**
* Draws all static entities like buildings etc.
* @param {DrawParameters} drawParameters
*/
drawStaticEntityDebugOverlays(drawParameters) {
const cullRange = drawParameters.visibleRect.toTileCullRectangle();
const top = cullRange.top();
const right = cullRange.right();
const bottom = cullRange.bottom();
const left = cullRange.left();
const border = 1;
const minY = top - border;
const maxY = bottom + border;
const minX = left - border;
const maxX = right + border - 1;
// Render y from top down for proper blending
for (let y = minY; y <= maxY; ++y) {
for (let x = minX; x <= maxX; ++x) {
// const content = this.tiles[x][y];
const chunk = this.getChunkAtTileOrNull(x, y);
if (!chunk) {
continue;
}
const content = chunk.getTileContentFromWorldCoords(x, y);
if (content) {
let isBorder = x <= left - 1 || x >= right + 1 || y <= top - 1 || y >= bottom + 1;
if (!isBorder) {
content.drawDebugOverlays(drawParameters);
}
}
}
}
}
/**
* Initializes all canvases used for background rendering
*/
internalInitializeCachedBackgroundCanvases() {
// Background canvas
const dims = globalConfig.tileSize;
const dpi = this.backgroundCacheDPI;
const [canvas, context] = makeOffscreenBuffer(dims * dpi, dims * dpi, {
smooth: false,
label: "map-cached-bg",
});
context.scale(dpi, dpi);
context.fillStyle = THEME.map.background;
context.fillRect(0, 0, dims, dims);
const borderWidth = THEME.map.gridLineWidth;
context.fillStyle = THEME.map.grid;
context.fillRect(0, 0, dims, borderWidth);
context.fillRect(0, borderWidth, borderWidth, dims);
context.fillRect(dims - borderWidth, borderWidth, borderWidth, dims - 2 * borderWidth);
context.fillRect(borderWidth, dims - borderWidth, dims, borderWidth);
this.cachedBackgroundCanvas = canvas;
this.cachedBackgroundContext = context;
}
/**
* Draws the maps foreground
* @param {DrawParameters} parameters
*/
drawForeground(parameters) {
this.drawVisibleChunks(parameters, MapChunkView.prototype.drawForegroundLayer);
}
/**
* Calls a given method on all given chunks
* @param {DrawParameters} parameters
* @param {function} method
*/
drawVisibleChunks(parameters, method) {
const cullRange = parameters.visibleRect.allScaled(1 / globalConfig.tileSize);
const top = cullRange.top();
const right = cullRange.right();
const bottom = cullRange.bottom();
const left = cullRange.left();
const border = 0;
const minY = top - border;
const maxY = bottom + border;
const minX = left - border;
const maxX = right + border;
const chunkStartX = Math.floor(minX / globalConfig.mapChunkSize);
const chunkStartY = Math.floor(minY / globalConfig.mapChunkSize);
const chunkEndX = Math.floor(maxX / globalConfig.mapChunkSize);
const chunkEndY = Math.floor(maxY / globalConfig.mapChunkSize);
// Render y from top down for proper blending
for (let chunkX = chunkStartX; chunkX <= chunkEndX; ++chunkX) {
for (let chunkY = chunkStartY; chunkY <= chunkEndY; ++chunkY) {
const chunk = this.root.map.getChunk(chunkX, chunkY, true);
method.call(chunk, parameters);
}
}
}
/**
* Draws the wires foreground
* @param {DrawParameters} parameters
*/
drawWiresForegroundLayer(parameters) {
this.drawVisibleChunks(parameters, MapChunkView.prototype.drawWiresForegroundLayer);
}
/**
* Draws the map overlay
* @param {DrawParameters} parameters
*/
drawOverlay(parameters) {
this.drawVisibleChunks(parameters, MapChunkView.prototype.drawOverlay);
}
/**
* Draws the map background
* @param {DrawParameters} parameters
*/
drawBackground(parameters) {
if (!this.cachedBackgroundPattern) {
this.cachedBackgroundPattern = parameters.context.createPattern(
this.cachedBackgroundCanvas,
"repeat"
);
}
if (!this.root.app.settings.getAllSettings().disableTileGrid) {
const dpi = this.backgroundCacheDPI;
parameters.context.scale(1 / dpi, 1 / dpi);
parameters.context.fillStyle = this.cachedBackgroundPattern;
parameters.context.fillRect(
parameters.visibleRect.x * dpi,
parameters.visibleRect.y * dpi,
parameters.visibleRect.w * dpi,
parameters.visibleRect.h * dpi
);
parameters.context.scale(dpi, dpi);
}
this.drawVisibleChunks(parameters, MapChunkView.prototype.drawBackgroundLayer);
if (G_IS_DEV && globalConfig.debug.showChunkBorders) {
const cullRange = parameters.visibleRect.toTileCullRectangle();
const top = cullRange.top();
const right = cullRange.right();
const bottom = cullRange.bottom();
const left = cullRange.left();
const border = 1;
const minY = top - border;
const maxY = bottom + border;
const minX = left - border;
const maxX = right + border - 1;
const chunkStartX = Math.floor(minX / globalConfig.mapChunkSize);
const chunkStartY = Math.floor(minY / globalConfig.mapChunkSize);
const chunkEndX = Math.ceil(maxX / globalConfig.mapChunkSize);
const chunkEndY = Math.ceil(maxY / globalConfig.mapChunkSize);
for (let chunkX = chunkStartX; chunkX <= chunkEndX; ++chunkX) {
for (let chunkY = chunkStartY; chunkY <= chunkEndY; ++chunkY) {
parameters.context.fillStyle = "#ffaaaa";
parameters.context.fillRect(
chunkX * globalConfig.mapChunkWorldSize,
chunkY * globalConfig.mapChunkWorldSize,
globalConfig.mapChunkWorldSize,
3
);
parameters.context.fillRect(
chunkX * globalConfig.mapChunkWorldSize,
chunkY * globalConfig.mapChunkWorldSize,
3,
globalConfig.mapChunkWorldSize
);
}
}
}
}
}
import { globalConfig } from "../core/config";
import { DrawParameters } from "../core/draw_parameters";
import { BaseMap } from "./map";
import { freeCanvas, makeOffscreenBuffer } from "../core/buffer_utils";
import { Entity } from "./entity";
import { THEME } from "./theme";
import { MapChunkView } from "./map_chunk_view";
/**
* This is the view of the map, it extends the map which is the raw model and allows
* to draw it
*/
export class MapView extends BaseMap {
constructor(root) {
super(root);
/**
* DPI of the background cache images, required in some places
*/
this.backgroundCacheDPI = 2;
/**
* The cached background sprite, containing the flat background
* @type {HTMLCanvasElement} */
this.cachedBackgroundCanvas = null;
/** @type {CanvasRenderingContext2D} */
this.cachedBackgroundContext = null;
/**
* Cached pattern of the stripes background
* @type {CanvasPattern} */
this.cachedBackgroundPattern = null;
this.internalInitializeCachedBackgroundCanvases();
this.root.signals.aboutToDestruct.add(this.cleanup, this);
this.root.signals.entityAdded.add(this.onEntityChanged, this);
this.root.signals.entityDestroyed.add(this.onEntityChanged, this);
this.root.signals.entityChanged.add(this.onEntityChanged, this);
}
cleanup() {
freeCanvas(this.cachedBackgroundCanvas);
this.cachedBackgroundCanvas = null;
this.cachedBackgroundPattern = null;
}
/**
* Called when an entity was added, removed or changed
* @param {Entity} entity
*/
onEntityChanged(entity) {
const staticComp = entity.components.StaticMapEntity;
if (staticComp) {
const rect = staticComp.getTileSpaceBounds();
for (let x = rect.x; x <= rect.right(); ++x) {
for (let y = rect.y; y <= rect.bottom(); ++y) {
this.root.map.getOrCreateChunkAtTile(x, y).markDirty();
}
}
}
}
/**
* Draws all static entities like buildings etc.
* @param {DrawParameters} drawParameters
*/
drawStaticEntityDebugOverlays(drawParameters) {
const cullRange = drawParameters.visibleRect.toTileCullRectangle();
const top = cullRange.top();
const right = cullRange.right();
const bottom = cullRange.bottom();
const left = cullRange.left();
const border = 1;
const minY = top - border;
const maxY = bottom + border;
const minX = left - border;
const maxX = right + border - 1;
// Render y from top down for proper blending
for (let y = minY; y <= maxY; ++y) {
for (let x = minX; x <= maxX; ++x) {
// const content = this.tiles[x][y];
const chunk = this.getChunkAtTileOrNull(x, y);
if (!chunk) {
continue;
}
const content = chunk.getTileContentFromWorldCoords(x, y);
if (content) {
let isBorder = x <= left - 1 || x >= right + 1 || y <= top - 1 || y >= bottom + 1;
if (!isBorder) {
content.drawDebugOverlays(drawParameters);
}
}
}
}
}
/**
* Initializes all canvases used for background rendering
*/
internalInitializeCachedBackgroundCanvases() {
// Background canvas
const dims = globalConfig.tileSize;
const dpi = this.backgroundCacheDPI;
const [canvas, context] = makeOffscreenBuffer(dims * dpi, dims * dpi, {
smooth: false,
label: "map-cached-bg",
});
context.scale(dpi, dpi);
context.fillStyle = THEME.map.background;
context.fillRect(0, 0, dims, dims);
const borderWidth = THEME.map.gridLineWidth;
context.fillStyle = THEME.map.grid;
context.fillRect(0, 0, dims, borderWidth);
context.fillRect(0, borderWidth, borderWidth, dims);
context.fillRect(dims - borderWidth, borderWidth, borderWidth, dims - 2 * borderWidth);
context.fillRect(borderWidth, dims - borderWidth, dims, borderWidth);
this.cachedBackgroundCanvas = canvas;
this.cachedBackgroundContext = context;
}
/**
* Draws the maps foreground
* @param {DrawParameters} parameters
*/
drawForeground(parameters) {
this.drawVisibleChunks(parameters, MapChunkView.prototype.drawForegroundDynamicLayer);
this.drawVisibleChunks(parameters, MapChunkView.prototype.drawForegroundStaticLayer);
}
/**
* Calls a given method on all given chunks
* @param {DrawParameters} parameters
* @param {function} method
*/
drawVisibleChunks(parameters, method) {
const cullRange = parameters.visibleRect.allScaled(1 / globalConfig.tileSize);
const top = cullRange.top();
const right = cullRange.right();
const bottom = cullRange.bottom();
const left = cullRange.left();
const border = 0;
const minY = top - border;
const maxY = bottom + border;
const minX = left - border;
const maxX = right + border;
const chunkStartX = Math.floor(minX / globalConfig.mapChunkSize);
const chunkStartY = Math.floor(minY / globalConfig.mapChunkSize);
const chunkEndX = Math.floor(maxX / globalConfig.mapChunkSize);
const chunkEndY = Math.floor(maxY / globalConfig.mapChunkSize);
// Render y from top down for proper blending
for (let chunkX = chunkStartX; chunkX <= chunkEndX; ++chunkX) {
for (let chunkY = chunkStartY; chunkY <= chunkEndY; ++chunkY) {
const chunk = this.root.map.getChunk(chunkX, chunkY, true);
method.call(chunk, parameters);
}
}
}
/**
* Draws the wires foreground
* @param {DrawParameters} parameters
*/
drawWiresForegroundLayer(parameters) {
this.drawVisibleChunks(parameters, MapChunkView.prototype.drawWiresForegroundLayer);
}
/**
* Draws the map overlay
* @param {DrawParameters} parameters
*/
drawOverlay(parameters) {
this.drawVisibleChunks(parameters, MapChunkView.prototype.drawOverlay);
}
/**
* Draws the map background
* @param {DrawParameters} parameters
*/
drawBackground(parameters) {
if (!this.cachedBackgroundPattern) {
this.cachedBackgroundPattern = parameters.context.createPattern(
this.cachedBackgroundCanvas,
"repeat"
);
}
if (!this.root.app.settings.getAllSettings().disableTileGrid) {
const dpi = this.backgroundCacheDPI;
parameters.context.scale(1 / dpi, 1 / dpi);
parameters.context.fillStyle = this.cachedBackgroundPattern;
parameters.context.fillRect(
parameters.visibleRect.x * dpi,
parameters.visibleRect.y * dpi,
parameters.visibleRect.w * dpi,
parameters.visibleRect.h * dpi
);
parameters.context.scale(dpi, dpi);
}
this.drawVisibleChunks(parameters, MapChunkView.prototype.drawBackgroundLayer);
if (G_IS_DEV && globalConfig.debug.showChunkBorders) {
const cullRange = parameters.visibleRect.toTileCullRectangle();
const top = cullRange.top();
const right = cullRange.right();
const bottom = cullRange.bottom();
const left = cullRange.left();
const border = 1;
const minY = top - border;
const maxY = bottom + border;
const minX = left - border;
const maxX = right + border - 1;
const chunkStartX = Math.floor(minX / globalConfig.mapChunkSize);
const chunkStartY = Math.floor(minY / globalConfig.mapChunkSize);
const chunkEndX = Math.ceil(maxX / globalConfig.mapChunkSize);
const chunkEndY = Math.ceil(maxY / globalConfig.mapChunkSize);
for (let chunkX = chunkStartX; chunkX <= chunkEndX; ++chunkX) {
for (let chunkY = chunkStartY; chunkY <= chunkEndY; ++chunkY) {
parameters.context.fillStyle = "#ffaaaa";
parameters.context.fillRect(
chunkX * globalConfig.mapChunkWorldSize,
chunkY * globalConfig.mapChunkWorldSize,
globalConfig.mapChunkWorldSize,
3
);
parameters.context.fillRect(
chunkX * globalConfig.mapChunkWorldSize,
chunkY * globalConfig.mapChunkWorldSize,
3,
globalConfig.mapChunkWorldSize
);
}
}
}
}
}

View File

@ -1,162 +1,173 @@
import { gMetaBuildingRegistry } from "../core/global_registries";
import { createLogger } from "../core/logging";
import { MetaBeltBuilding } from "./buildings/belt";
import { MetaBeltBaseBuilding } from "./buildings/belt_base";
import { enumCutterVariants, MetaCutterBuilding } from "./buildings/cutter";
import { MetaHubBuilding } from "./buildings/hub";
import { enumMinerVariants, MetaMinerBuilding } from "./buildings/miner";
import { MetaMixerBuilding } from "./buildings/mixer";
import { enumPainterVariants, MetaPainterBuilding } from "./buildings/painter";
import { enumRotaterVariants, MetaRotaterBuilding } from "./buildings/rotater";
import { enumSplitterVariants, MetaSplitterBuilding } from "./buildings/splitter";
import { MetaStackerBuilding } from "./buildings/stacker";
import { enumTrashVariants, MetaTrashBuilding } from "./buildings/trash";
import { enumUndergroundBeltVariants, MetaUndergroundBeltBuilding } from "./buildings/underground_belt";
import { MetaWireBuilding } from "./buildings/wire";
import { gBuildingVariants, registerBuildingVariant } from "./building_codes";
import { defaultBuildingVariant } from "./meta_building";
import { MetaConstantSignalBuilding } from "./buildings/constant_signal";
import { MetaLogicGateBuilding, enumLogicGateVariants } from "./buildings/logic_gate";
import { MetaLeverBuilding } from "./buildings/lever";
import { MetaFilterBuilding } from "./buildings/filter";
import { MetaWireTunnelBuilding, enumWireTunnelVariants } from "./buildings/wire_tunnel";
import { MetaDisplayBuilding } from "./buildings/display";
const logger = createLogger("building_registry");
export function initMetaBuildingRegistry() {
gMetaBuildingRegistry.register(MetaSplitterBuilding);
gMetaBuildingRegistry.register(MetaMinerBuilding);
gMetaBuildingRegistry.register(MetaCutterBuilding);
gMetaBuildingRegistry.register(MetaRotaterBuilding);
gMetaBuildingRegistry.register(MetaStackerBuilding);
gMetaBuildingRegistry.register(MetaMixerBuilding);
gMetaBuildingRegistry.register(MetaPainterBuilding);
gMetaBuildingRegistry.register(MetaTrashBuilding);
gMetaBuildingRegistry.register(MetaBeltBuilding);
gMetaBuildingRegistry.register(MetaUndergroundBeltBuilding);
gMetaBuildingRegistry.register(MetaHubBuilding);
gMetaBuildingRegistry.register(MetaWireBuilding);
gMetaBuildingRegistry.register(MetaConstantSignalBuilding);
gMetaBuildingRegistry.register(MetaLogicGateBuilding);
gMetaBuildingRegistry.register(MetaLeverBuilding);
gMetaBuildingRegistry.register(MetaFilterBuilding);
gMetaBuildingRegistry.register(MetaWireTunnelBuilding);
gMetaBuildingRegistry.register(MetaDisplayBuilding);
// Belt
registerBuildingVariant(1, MetaBeltBaseBuilding, defaultBuildingVariant, 0);
registerBuildingVariant(2, MetaBeltBaseBuilding, defaultBuildingVariant, 1);
registerBuildingVariant(3, MetaBeltBaseBuilding, defaultBuildingVariant, 2);
// Splitter
registerBuildingVariant(4, MetaSplitterBuilding);
registerBuildingVariant(5, MetaSplitterBuilding, enumSplitterVariants.compact);
registerBuildingVariant(6, MetaSplitterBuilding, enumSplitterVariants.compactInverse);
// Miner
registerBuildingVariant(7, MetaMinerBuilding);
registerBuildingVariant(8, MetaMinerBuilding, enumMinerVariants.chainable);
// Cutter
registerBuildingVariant(9, MetaCutterBuilding);
registerBuildingVariant(10, MetaCutterBuilding, enumCutterVariants.quad);
// Rotater
registerBuildingVariant(11, MetaRotaterBuilding);
registerBuildingVariant(12, MetaRotaterBuilding, enumRotaterVariants.ccw);
registerBuildingVariant(13, MetaRotaterBuilding, enumRotaterVariants.fl);
// Stacker
registerBuildingVariant(14, MetaStackerBuilding);
// Mixer
registerBuildingVariant(15, MetaMixerBuilding);
// Painter
registerBuildingVariant(16, MetaPainterBuilding);
registerBuildingVariant(17, MetaPainterBuilding, enumPainterVariants.mirrored);
registerBuildingVariant(18, MetaPainterBuilding, enumPainterVariants.double);
registerBuildingVariant(19, MetaPainterBuilding, enumPainterVariants.quad);
// Trash
registerBuildingVariant(20, MetaTrashBuilding);
registerBuildingVariant(21, MetaTrashBuilding, enumTrashVariants.storage);
// Underground belt
registerBuildingVariant(22, MetaUndergroundBeltBuilding, defaultBuildingVariant, 0);
registerBuildingVariant(23, MetaUndergroundBeltBuilding, defaultBuildingVariant, 1);
registerBuildingVariant(24, MetaUndergroundBeltBuilding, enumUndergroundBeltVariants.tier2, 0);
registerBuildingVariant(25, MetaUndergroundBeltBuilding, enumUndergroundBeltVariants.tier2, 1);
// Hub
registerBuildingVariant(26, MetaHubBuilding);
// Wire
registerBuildingVariant(27, MetaWireBuilding, defaultBuildingVariant, 0);
registerBuildingVariant(28, MetaWireBuilding, defaultBuildingVariant, 1);
registerBuildingVariant(29, MetaWireBuilding, defaultBuildingVariant, 2);
registerBuildingVariant(30, MetaWireBuilding, defaultBuildingVariant, 3);
// Constant signal
registerBuildingVariant(31, MetaConstantSignalBuilding);
// Logic gate
registerBuildingVariant(32, MetaLogicGateBuilding);
registerBuildingVariant(34, MetaLogicGateBuilding, enumLogicGateVariants.not);
registerBuildingVariant(35, MetaLogicGateBuilding, enumLogicGateVariants.xor);
registerBuildingVariant(36, MetaLogicGateBuilding, enumLogicGateVariants.or);
registerBuildingVariant(38, MetaLogicGateBuilding, enumLogicGateVariants.transistor);
// Lever
registerBuildingVariant(33, MetaLeverBuilding);
// Filter
registerBuildingVariant(37, MetaFilterBuilding);
// Wire tunnel
registerBuildingVariant(39, MetaWireTunnelBuilding);
registerBuildingVariant(41, MetaWireTunnelBuilding, enumWireTunnelVariants.coating);
// Display
registerBuildingVariant(40, MetaDisplayBuilding);
// Propagate instances
for (const key in gBuildingVariants) {
gBuildingVariants[key].metaInstance = gMetaBuildingRegistry.findByClass(
gBuildingVariants[key].metaClass
);
}
for (const key in gBuildingVariants) {
const variant = gBuildingVariants[key];
assert(variant.metaClass, "Variant has no meta: " + key);
if (typeof variant.rotationVariant === "undefined") {
variant.rotationVariant = 0;
}
if (typeof variant.variant === "undefined") {
variant.variant = defaultBuildingVariant;
}
}
logger.log("Registered", gMetaBuildingRegistry.getNumEntries(), "buildings");
logger.log("Registered", Object.keys(gBuildingVariants).length, "building codes");
}
/**
* Once all sprites are loaded, propagates the cache
*/
export function initBuildingCodesAfterResourcesLoaded() {
logger.log("Propagating sprite cache");
for (const key in gBuildingVariants) {
const variant = gBuildingVariants[key];
variant.sprite = variant.metaInstance.getSprite(variant.rotationVariant, variant.variant);
variant.blueprintSprite = variant.metaInstance.getBlueprintSprite(
variant.rotationVariant,
variant.variant
);
variant.silhouetteColor = variant.metaInstance.getSilhouetteColor();
}
}
import { gMetaBuildingRegistry } from "../core/global_registries";
import { createLogger } from "../core/logging";
import { MetaBeltBuilding } from "./buildings/belt";
import { MetaBeltBaseBuilding } from "./buildings/belt_base";
import { enumCutterVariants, MetaCutterBuilding } from "./buildings/cutter";
import { MetaHubBuilding } from "./buildings/hub";
import { enumMinerVariants, MetaMinerBuilding } from "./buildings/miner";
import { MetaMixerBuilding } from "./buildings/mixer";
import { enumPainterVariants, MetaPainterBuilding } from "./buildings/painter";
import { enumRotaterVariants, MetaRotaterBuilding } from "./buildings/rotater";
import { enumSplitterVariants, MetaSplitterBuilding } from "./buildings/splitter";
import { MetaStackerBuilding } from "./buildings/stacker";
import { enumTrashVariants, MetaTrashBuilding } from "./buildings/trash";
import { enumUndergroundBeltVariants, MetaUndergroundBeltBuilding } from "./buildings/underground_belt";
import { MetaWireBuilding } from "./buildings/wire";
import { gBuildingVariants, registerBuildingVariant } from "./building_codes";
import { defaultBuildingVariant } from "./meta_building";
import { MetaConstantSignalBuilding } from "./buildings/constant_signal";
import { MetaLogicGateBuilding, enumLogicGateVariants } from "./buildings/logic_gate";
import { MetaLeverBuilding } from "./buildings/lever";
import { MetaFilterBuilding } from "./buildings/filter";
import { MetaWireTunnelBuilding, enumWireTunnelVariants } from "./buildings/wire_tunnel";
import { MetaDisplayBuilding } from "./buildings/display";
import { MetaVirtualProcessorBuilding, enumVirtualProcessorVariants } from "./buildings/virtual_processor";
const logger = createLogger("building_registry");
export function initMetaBuildingRegistry() {
gMetaBuildingRegistry.register(MetaSplitterBuilding);
gMetaBuildingRegistry.register(MetaMinerBuilding);
gMetaBuildingRegistry.register(MetaCutterBuilding);
gMetaBuildingRegistry.register(MetaRotaterBuilding);
gMetaBuildingRegistry.register(MetaStackerBuilding);
gMetaBuildingRegistry.register(MetaMixerBuilding);
gMetaBuildingRegistry.register(MetaPainterBuilding);
gMetaBuildingRegistry.register(MetaTrashBuilding);
gMetaBuildingRegistry.register(MetaBeltBuilding);
gMetaBuildingRegistry.register(MetaUndergroundBeltBuilding);
gMetaBuildingRegistry.register(MetaHubBuilding);
gMetaBuildingRegistry.register(MetaWireBuilding);
gMetaBuildingRegistry.register(MetaConstantSignalBuilding);
gMetaBuildingRegistry.register(MetaLogicGateBuilding);
gMetaBuildingRegistry.register(MetaLeverBuilding);
gMetaBuildingRegistry.register(MetaFilterBuilding);
gMetaBuildingRegistry.register(MetaWireTunnelBuilding);
gMetaBuildingRegistry.register(MetaDisplayBuilding);
gMetaBuildingRegistry.register(MetaVirtualProcessorBuilding);
// Belt
registerBuildingVariant(1, MetaBeltBaseBuilding, defaultBuildingVariant, 0);
registerBuildingVariant(2, MetaBeltBaseBuilding, defaultBuildingVariant, 1);
registerBuildingVariant(3, MetaBeltBaseBuilding, defaultBuildingVariant, 2);
// Splitter
registerBuildingVariant(4, MetaSplitterBuilding);
registerBuildingVariant(5, MetaSplitterBuilding, enumSplitterVariants.compact);
registerBuildingVariant(6, MetaSplitterBuilding, enumSplitterVariants.compactInverse);
registerBuildingVariant(47, MetaSplitterBuilding, enumSplitterVariants.compactMerge);
registerBuildingVariant(48, MetaSplitterBuilding, enumSplitterVariants.compactMergeInverse);
// Miner
registerBuildingVariant(7, MetaMinerBuilding);
registerBuildingVariant(8, MetaMinerBuilding, enumMinerVariants.chainable);
// Cutter
registerBuildingVariant(9, MetaCutterBuilding);
registerBuildingVariant(10, MetaCutterBuilding, enumCutterVariants.quad);
// Rotater
registerBuildingVariant(11, MetaRotaterBuilding);
registerBuildingVariant(12, MetaRotaterBuilding, enumRotaterVariants.ccw);
registerBuildingVariant(13, MetaRotaterBuilding, enumRotaterVariants.fl);
// Stacker
registerBuildingVariant(14, MetaStackerBuilding);
// Mixer
registerBuildingVariant(15, MetaMixerBuilding);
// Painter
registerBuildingVariant(16, MetaPainterBuilding);
registerBuildingVariant(17, MetaPainterBuilding, enumPainterVariants.mirrored);
registerBuildingVariant(18, MetaPainterBuilding, enumPainterVariants.double);
registerBuildingVariant(19, MetaPainterBuilding, enumPainterVariants.quad);
// Trash
registerBuildingVariant(20, MetaTrashBuilding);
registerBuildingVariant(21, MetaTrashBuilding, enumTrashVariants.storage);
// Underground belt
registerBuildingVariant(22, MetaUndergroundBeltBuilding, defaultBuildingVariant, 0);
registerBuildingVariant(23, MetaUndergroundBeltBuilding, defaultBuildingVariant, 1);
registerBuildingVariant(24, MetaUndergroundBeltBuilding, enumUndergroundBeltVariants.tier2, 0);
registerBuildingVariant(25, MetaUndergroundBeltBuilding, enumUndergroundBeltVariants.tier2, 1);
// Hub
registerBuildingVariant(26, MetaHubBuilding);
// Wire
registerBuildingVariant(27, MetaWireBuilding, defaultBuildingVariant, 0);
registerBuildingVariant(28, MetaWireBuilding, defaultBuildingVariant, 1);
registerBuildingVariant(29, MetaWireBuilding, defaultBuildingVariant, 2);
registerBuildingVariant(30, MetaWireBuilding, defaultBuildingVariant, 3);
// Constant signal
registerBuildingVariant(31, MetaConstantSignalBuilding);
// Logic gate
registerBuildingVariant(32, MetaLogicGateBuilding);
registerBuildingVariant(34, MetaLogicGateBuilding, enumLogicGateVariants.not);
registerBuildingVariant(35, MetaLogicGateBuilding, enumLogicGateVariants.xor);
registerBuildingVariant(36, MetaLogicGateBuilding, enumLogicGateVariants.or);
registerBuildingVariant(38, MetaLogicGateBuilding, enumLogicGateVariants.transistor);
// Lever
registerBuildingVariant(33, MetaLeverBuilding);
// Filter
registerBuildingVariant(37, MetaFilterBuilding);
// Wire tunnel
registerBuildingVariant(39, MetaWireTunnelBuilding);
registerBuildingVariant(41, MetaWireTunnelBuilding, enumWireTunnelVariants.coating);
// Display
registerBuildingVariant(40, MetaDisplayBuilding);
// Virtual Processor
registerBuildingVariant(42, MetaVirtualProcessorBuilding);
registerBuildingVariant(43, MetaVirtualProcessorBuilding, enumVirtualProcessorVariants.analyzer);
registerBuildingVariant(44, MetaVirtualProcessorBuilding, enumVirtualProcessorVariants.rotater);
registerBuildingVariant(45, MetaVirtualProcessorBuilding, enumVirtualProcessorVariants.unstacker);
registerBuildingVariant(46, MetaVirtualProcessorBuilding, enumVirtualProcessorVariants.shapecompare);
// Propagate instances
for (const key in gBuildingVariants) {
gBuildingVariants[key].metaInstance = gMetaBuildingRegistry.findByClass(
gBuildingVariants[key].metaClass
);
}
for (const key in gBuildingVariants) {
const variant = gBuildingVariants[key];
assert(variant.metaClass, "Variant has no meta: " + key);
if (typeof variant.rotationVariant === "undefined") {
variant.rotationVariant = 0;
}
if (typeof variant.variant === "undefined") {
variant.variant = defaultBuildingVariant;
}
}
logger.log("Registered", gMetaBuildingRegistry.getNumEntries(), "buildings");
logger.log("Registered", Object.keys(gBuildingVariants).length, "building codes");
}
/**
* Once all sprites are loaded, propagates the cache
*/
export function initBuildingCodesAfterResourcesLoaded() {
logger.log("Propagating sprite cache");
for (const key in gBuildingVariants) {
const variant = gBuildingVariants[key];
variant.sprite = variant.metaInstance.getSprite(variant.rotationVariant, variant.variant);
variant.blueprintSprite = variant.metaInstance.getBlueprintSprite(
variant.rotationVariant,
variant.variant
);
variant.silhouetteColor = variant.metaInstance.getSilhouetteColor();
}
}

View File

@ -85,7 +85,7 @@ export class ShapeDefinition extends BasicSerializableObject {
return errorCode;
}
const definition = ShapeDefinition.fromShortKey(data);
this.layers = definition.layers;
this.layers = /** @type {Array<ShapeLayer>} */ (definition.layers);
}
serialize() {
@ -102,7 +102,8 @@ export class ShapeDefinition extends BasicSerializableObject {
/**
* The layers from bottom to top
* @type {Array<ShapeLayer>} */
* @type {Array<ShapeLayer>}
*/
this.layers = layers;
/** @type {string} */
@ -600,7 +601,7 @@ export class ShapeDefinition extends BasicSerializableObject {
for (let quadrantIndex = 0; quadrantIndex < 4; ++quadrantIndex) {
const item = quadrants[quadrantIndex];
if (item) {
item.color = colors[quadrantIndex] || item.color;
item.color = colors[quadrantIndex] || null;
}
}
}

View File

@ -1,129 +1,135 @@
import trim from "trim";
import { DialogWithForm } from "../../core/modal_dialog_elements";
import { FormElementInput } from "../../core/modal_dialog_forms";
import { BaseItem } from "../base_item";
import { enumColors } from "../colors";
import { ConstantSignalComponent } from "../components/constant_signal";
import { Entity } from "../entity";
import { GameSystemWithFilter } from "../game_system_with_filter";
import { BOOL_FALSE_SINGLETON, BOOL_TRUE_SINGLETON } from "../items/boolean_item";
import { COLOR_ITEM_SINGLETONS } from "../items/color_item";
import { ShapeDefinition } from "../shape_definition";
export class ConstantSignalSystem extends GameSystemWithFilter {
constructor(root) {
super(root, [ConstantSignalComponent]);
this.root.signals.entityManuallyPlaced.add(this.querySigalValue, this);
}
update() {
// Set signals
for (let i = 0; i < this.allEntities.length; ++i) {
const entity = this.allEntities[i];
const pinsComp = entity.components.WiredPins;
const signalComp = entity.components.ConstantSignal;
pinsComp.slots[0].value = signalComp.signal;
}
}
/**
* Asks the entity to enter a valid signal code
* @param {Entity} entity
*/
querySigalValue(entity) {
if (!entity.components.ConstantSignal) {
return;
}
// Ok, query, but also save the uid because it could get stale
const uid = entity.uid;
const signalValueInput = new FormElementInput({
id: "signalValue",
label: null,
placeholder: "",
defaultValue: "",
validator: val => this.parseSignalCode(val),
});
const dialog = new DialogWithForm({
app: this.root.app,
title: "Set Signal",
desc: "Enter a shape code, color or '0' or '1'",
formElements: [signalValueInput],
buttons: ["cancel:bad:escape", "ok:good:enter"],
});
this.root.hud.parts.dialogs.internalShowDialog(dialog);
// When confirmed, set the signal
dialog.buttonSignals.ok.add(() => {
if (!this.root || !this.root.entityMgr) {
// Game got stopped
return;
}
const entityRef = this.root.entityMgr.findByUid(uid, false);
if (!entityRef) {
// outdated
return;
}
const constantComp = entityRef.components.ConstantSignal;
if (!constantComp) {
// no longer interesting
return;
}
constantComp.signal = this.parseSignalCode(signalValueInput.getValue());
});
// When cancelled, destroy the entity again
dialog.buttonSignals.cancel.add(() => {
if (!this.root || !this.root.entityMgr) {
// Game got stopped
return;
}
const entityRef = this.root.entityMgr.findByUid(uid, false);
if (!entityRef) {
// outdated
return;
}
const constantComp = entityRef.components.ConstantSignal;
if (!constantComp) {
// no longer interesting
return;
}
this.root.logic.tryDeleteBuilding(entityRef);
});
}
/**
* Tries to parse a signal code
* @param {string} code
* @returns {BaseItem}
*/
parseSignalCode(code) {
code = trim(code);
const codeLower = code.toLowerCase();
if (enumColors[codeLower]) {
return COLOR_ITEM_SINGLETONS[codeLower];
}
if (code === "1" || codeLower === "true") {
return BOOL_TRUE_SINGLETON;
}
if (code === "0" || codeLower === "false") {
return BOOL_FALSE_SINGLETON;
}
if (ShapeDefinition.isValidShortKey(code)) {
return this.root.shapeDefinitionMgr.getShapeItemFromShortKey(code);
}
return null;
}
}
import trim from "trim";
import { DialogWithForm } from "../../core/modal_dialog_elements";
import { FormElementInput } from "../../core/modal_dialog_forms";
import { BaseItem } from "../base_item";
import { enumColors } from "../colors";
import { ConstantSignalComponent } from "../components/constant_signal";
import { Entity } from "../entity";
import { GameSystemWithFilter } from "../game_system_with_filter";
import { BOOL_FALSE_SINGLETON, BOOL_TRUE_SINGLETON } from "../items/boolean_item";
import { COLOR_ITEM_SINGLETONS } from "../items/color_item";
import { ShapeDefinition } from "../shape_definition";
export class ConstantSignalSystem extends GameSystemWithFilter {
constructor(root) {
super(root, [ConstantSignalComponent]);
this.root.signals.entityManuallyPlaced.add(this.querySigalValue, this);
}
update() {
// Set signals
for (let i = 0; i < this.allEntities.length; ++i) {
const entity = this.allEntities[i];
const pinsComp = entity.components.WiredPins;
const signalComp = entity.components.ConstantSignal;
pinsComp.slots[0].value = signalComp.signal;
}
}
/**
* Asks the entity to enter a valid signal code
* @param {Entity} entity
*/
querySigalValue(entity) {
if (!entity.components.ConstantSignal) {
return;
}
// Ok, query, but also save the uid because it could get stale
const uid = entity.uid;
const signalValueInput = new FormElementInput({
id: "signalValue",
label: null,
placeholder: "",
defaultValue: "",
validator: val => this.parseSignalCode(val),
});
const dialog = new DialogWithForm({
app: this.root.app,
title: "Set Signal",
desc: "Enter a shape code, color or '0' or '1'",
formElements: [signalValueInput],
buttons: ["cancel:bad:escape", "ok:good:enter"],
closeButton: false,
});
this.root.hud.parts.dialogs.internalShowDialog(dialog);
// When confirmed, set the signal
dialog.buttonSignals.ok.add(() => {
if (!this.root || !this.root.entityMgr) {
// Game got stopped
return;
}
const entityRef = this.root.entityMgr.findByUid(uid, false);
if (!entityRef) {
// outdated
return;
}
const constantComp = entityRef.components.ConstantSignal;
if (!constantComp) {
// no longer interesting
return;
}
constantComp.signal = this.parseSignalCode(signalValueInput.getValue());
});
// When cancelled, destroy the entity again
dialog.buttonSignals.cancel.add(() => {
if (!this.root || !this.root.entityMgr) {
// Game got stopped
return;
}
const entityRef = this.root.entityMgr.findByUid(uid, false);
if (!entityRef) {
// outdated
return;
}
const constantComp = entityRef.components.ConstantSignal;
if (!constantComp) {
// no longer interesting
return;
}
this.root.logic.tryDeleteBuilding(entityRef);
});
}
/**
* Tries to parse a signal code
* @param {string} code
* @returns {BaseItem}
*/
parseSignalCode(code) {
if (!this.root || !this.root.shapeDefinitionMgr) {
// Stale reference
return null;
}
code = trim(code);
const codeLower = code.toLowerCase();
if (enumColors[codeLower]) {
return COLOR_ITEM_SINGLETONS[codeLower];
}
if (code === "1" || codeLower === "true") {
return BOOL_TRUE_SINGLETON;
}
if (code === "0" || codeLower === "false") {
return BOOL_FALSE_SINGLETON;
}
if (ShapeDefinition.isValidShortKey(code)) {
return this.root.shapeDefinitionMgr.getShapeItemFromShortKey(code);
}
return null;
}
}

View File

@ -1,51 +1,44 @@
import { GameSystemWithFilter } from "../game_system_with_filter";
import { LeverComponent } from "../components/lever";
import { BOOL_TRUE_SINGLETON, BOOL_FALSE_SINGLETON } from "../items/boolean_item";
import { MapChunkView } from "../map_chunk_view";
import { globalConfig } from "../../core/config";
import { Loader } from "../../core/loader";
export class LeverSystem extends GameSystemWithFilter {
constructor(root) {
super(root, [LeverComponent]);
this.spriteOn = Loader.getSprite("sprites/wires/lever_on.png");
this.spriteOff = Loader.getSprite("sprites/buildings/lever.png");
}
update() {
for (let i = 0; i < this.allEntities.length; ++i) {
const entity = this.allEntities[i];
const leverComp = entity.components.Lever;
const pinsComp = entity.components.WiredPins;
// Simply sync the status to the first slot
pinsComp.slots[0].value = leverComp.toggled ? BOOL_TRUE_SINGLETON : BOOL_FALSE_SINGLETON;
}
}
/**
* Draws a given chunk
* @param {import("../../core/draw_utils").DrawParameters} parameters
* @param {MapChunkView} chunk
*/
drawChunk(parameters, chunk) {
const contents = chunk.containedEntitiesByLayer.regular;
for (let i = 0; i < contents.length; ++i) {
const entity = contents[i];
const leverComp = entity.components.Lever;
if (leverComp) {
const sprite = leverComp.toggled ? this.spriteOn : this.spriteOff;
const origin = entity.components.StaticMapEntity.origin;
sprite.drawCached(
parameters,
origin.x * globalConfig.tileSize,
origin.y * globalConfig.tileSize,
globalConfig.tileSize,
globalConfig.tileSize
);
}
}
}
}
import { GameSystemWithFilter } from "../game_system_with_filter";
import { LeverComponent } from "../components/lever";
import { BOOL_TRUE_SINGLETON, BOOL_FALSE_SINGLETON } from "../items/boolean_item";
import { MapChunkView } from "../map_chunk_view";
import { globalConfig } from "../../core/config";
import { Loader } from "../../core/loader";
export class LeverSystem extends GameSystemWithFilter {
constructor(root) {
super(root, [LeverComponent]);
this.spriteOn = Loader.getSprite("sprites/wires/lever_on.png");
this.spriteOff = Loader.getSprite("sprites/buildings/lever.png");
}
update() {
for (let i = 0; i < this.allEntities.length; ++i) {
const entity = this.allEntities[i];
const leverComp = entity.components.Lever;
const pinsComp = entity.components.WiredPins;
// Simply sync the status to the first slot
pinsComp.slots[0].value = leverComp.toggled ? BOOL_TRUE_SINGLETON : BOOL_FALSE_SINGLETON;
}
}
/**
* Draws a given chunk
* @param {import("../../core/draw_utils").DrawParameters} parameters
* @param {MapChunkView} chunk
*/
drawChunk(parameters, chunk) {
const contents = chunk.containedEntitiesByLayer.regular;
for (let i = 0; i < contents.length; ++i) {
const entity = contents[i];
const leverComp = entity.components.Lever;
if (leverComp) {
const sprite = leverComp.toggled ? this.spriteOn : this.spriteOff;
entity.components.StaticMapEntity.drawSpriteOnBoundsClipped(parameters, sprite);
}
}
}
}

View File

@ -1,180 +1,326 @@
import { LogicGateComponent, enumLogicGateType } from "../components/logic_gate";
import { GameSystemWithFilter } from "../game_system_with_filter";
import { BaseItem } from "../base_item";
import { enumPinSlotType } from "../components/wired_pins";
import { BOOL_TRUE_SINGLETON, BOOL_FALSE_SINGLETON, BooleanItem } from "../items/boolean_item";
import { enumItemProcessorTypes } from "../components/item_processor";
export class LogicGateSystem extends GameSystemWithFilter {
constructor(root) {
super(root, [LogicGateComponent]);
this.boundOperations = {
[enumLogicGateType.and]: this.compute_AND.bind(this),
[enumLogicGateType.not]: this.compute_NOT.bind(this),
[enumLogicGateType.xor]: this.compute_XOR.bind(this),
[enumLogicGateType.or]: this.compute_OR.bind(this),
[enumLogicGateType.transistor]: this.compute_IF.bind(this),
};
}
update() {
for (let i = 0; i < this.allEntities.length; ++i) {
const entity = this.allEntities[i];
const logicComp = entity.components.LogicGate;
const slotComp = entity.components.WiredPins;
const slotValues = [];
for (let i = 0; i < slotComp.slots.length; ++i) {
const slot = slotComp.slots[i];
if (slot.type !== enumPinSlotType.logicalAcceptor) {
continue;
}
if (slot.linkedNetwork) {
slotValues.push(slot.linkedNetwork.currentValue);
} else {
slotValues.push(null);
}
}
const result = this.boundOperations[logicComp.type](slotValues);
// @TODO: For now we hardcode the value to always be slot 0
assert(
slotValues.length === slotComp.slots.length - 1,
"Bad slot config, should have N acceptor slots and 1 ejector"
);
assert(slotComp.slots[0].type === enumPinSlotType.logicalEjector, "Slot 0 should be ejector");
slotComp.slots[0].value = result;
}
}
/**
* @param {Array<BaseItem|null>} parameters
* @returns {BaseItem}
*/
compute_AND(parameters) {
assert(parameters.length === 2, "bad parameter count for AND");
const param1 = parameters[0];
const param2 = parameters[1];
if (!param1 || !param2) {
// Not enough params
return BOOL_FALSE_SINGLETON;
}
const itemType = param1.getItemType();
if (itemType !== param2.getItemType()) {
// Differing type
return BOOL_FALSE_SINGLETON;
}
if (itemType === "boolean") {
return /** @type {BooleanItem} */ (param1).value && /** @type {BooleanItem} */ (param2).value
? BOOL_TRUE_SINGLETON
: BOOL_FALSE_SINGLETON;
}
return BOOL_FALSE_SINGLETON;
}
/**
* @param {Array<BaseItem|null>} parameters
* @returns {BaseItem}
*/
compute_NOT(parameters) {
const item = parameters[0];
if (!item) {
return BOOL_TRUE_SINGLETON;
}
if (item.getItemType() !== "boolean") {
// Not a boolean actually
return BOOL_FALSE_SINGLETON;
}
const value = /** @type {BooleanItem} */ (item).value;
return value ? BOOL_FALSE_SINGLETON : BOOL_TRUE_SINGLETON;
}
/**
* @param {Array<BaseItem|null>} parameters
* @returns {BaseItem}
*/
compute_XOR(parameters) {
assert(parameters.length === 2, "bad parameter count for XOR");
const param1 = parameters[0];
const param2 = parameters[1];
if (!param1 && !param2) {
// Not enough params
return BOOL_FALSE_SINGLETON;
}
// Check for the right types
if (param1 && param1.getItemType() !== "boolean") {
return BOOL_FALSE_SINGLETON;
}
if (param2 && param2.getItemType() !== "boolean") {
return BOOL_FALSE_SINGLETON;
}
const valueParam1 = param1 ? /** @type {BooleanItem} */ (param1).value : 0;
const valueParam2 = param2 ? /** @type {BooleanItem} */ (param2).value : 0;
return valueParam1 ^ valueParam2 ? BOOL_TRUE_SINGLETON : BOOL_FALSE_SINGLETON;
}
/**
* @param {Array<BaseItem|null>} parameters
* @returns {BaseItem}
*/
compute_OR(parameters) {
assert(parameters.length === 2, "bad parameter count for OR");
const param1 = parameters[0];
const param2 = parameters[1];
if (!param1 && !param2) {
// Not enough params
return BOOL_FALSE_SINGLETON;
}
const valueParam1 =
param1 && param1.getItemType() === "boolean" ? /** @type {BooleanItem} */ (param1).value : 0;
const valueParam2 =
param2 && param2.getItemType() === "boolean" ? /** @type {BooleanItem} */ (param2).value : 0;
return valueParam1 || valueParam2 ? BOOL_TRUE_SINGLETON : BOOL_FALSE_SINGLETON;
}
/**
* @param {Array<BaseItem|null>} parameters
* @returns {BaseItem}
*/
compute_IF(parameters) {
assert(parameters.length === 2, "bad parameter count for IF");
const flag = parameters[0];
const value = parameters[1];
if (!flag || !value) {
// Not enough params
return null;
}
if (flag.getItemType() !== "boolean") {
// Flag is not a boolean
return null;
}
// pass through item
if (/** @type {BooleanItem} */ (flag).value) {
return value;
}
return null;
}
}
import { BaseItem } from "../base_item";
import { enumColors } from "../colors";
import { enumLogicGateType, LogicGateComponent } from "../components/logic_gate";
import { enumPinSlotType } from "../components/wired_pins";
import { GameSystemWithFilter } from "../game_system_with_filter";
import { BOOL_FALSE_SINGLETON, BOOL_TRUE_SINGLETON, BooleanItem } from "../items/boolean_item";
import { COLOR_ITEM_SINGLETONS } from "../items/color_item";
import { ShapeDefinition } from "../shape_definition";
import { ShapeItem } from "../items/shape_item";
export class LogicGateSystem extends GameSystemWithFilter {
constructor(root) {
super(root, [LogicGateComponent]);
this.boundOperations = {
[enumLogicGateType.and]: this.compute_AND.bind(this),
[enumLogicGateType.not]: this.compute_NOT.bind(this),
[enumLogicGateType.xor]: this.compute_XOR.bind(this),
[enumLogicGateType.or]: this.compute_OR.bind(this),
[enumLogicGateType.transistor]: this.compute_IF.bind(this),
[enumLogicGateType.rotater]: this.compute_ROTATE.bind(this),
[enumLogicGateType.analyzer]: this.compute_ANALYZE.bind(this),
[enumLogicGateType.cutter]: this.compute_CUT.bind(this),
[enumLogicGateType.unstacker]: this.compute_UNSTACK.bind(this),
[enumLogicGateType.shapecompare]: this.compute_SHAPECOMPARE.bind(this),
};
}
update() {
for (let i = 0; i < this.allEntities.length; ++i) {
const entity = this.allEntities[i];
const logicComp = entity.components.LogicGate;
const slotComp = entity.components.WiredPins;
const slotValues = [];
for (let i = 0; i < slotComp.slots.length; ++i) {
const slot = slotComp.slots[i];
if (slot.type !== enumPinSlotType.logicalAcceptor) {
continue;
}
if (slot.linkedNetwork) {
slotValues.push(slot.linkedNetwork.currentValue);
} else {
slotValues.push(null);
}
}
const result = this.boundOperations[logicComp.type](slotValues);
if (Array.isArray(result)) {
let resultIndex = 0;
for (let i = 0; i < slotComp.slots.length; ++i) {
const slot = slotComp.slots[i];
if (slot.type !== enumPinSlotType.logicalEjector) {
continue;
}
slot.value = result[resultIndex++];
}
} else {
// @TODO: For now we hardcode the value to always be slot 0
assert(
slotValues.length === slotComp.slots.length - 1,
"Bad slot config, should have N acceptor slots and 1 ejector"
);
assert(slotComp.slots[0].type === enumPinSlotType.logicalEjector, "Slot 0 should be ejector");
slotComp.slots[0].value = result;
}
}
}
/**
* @param {Array<BaseItem|null>} parameters
* @returns {BaseItem}
*/
compute_AND(parameters) {
assert(parameters.length === 2, "bad parameter count for AND");
const param1 = parameters[0];
const param2 = parameters[1];
if (!param1 || !param2) {
// Not enough params
return BOOL_FALSE_SINGLETON;
}
const itemType = param1.getItemType();
if (itemType !== param2.getItemType()) {
// Differing type
return BOOL_FALSE_SINGLETON;
}
if (itemType === "boolean") {
return /** @type {BooleanItem} */ (param1).value && /** @type {BooleanItem} */ (param2).value
? BOOL_TRUE_SINGLETON
: BOOL_FALSE_SINGLETON;
}
return BOOL_FALSE_SINGLETON;
}
/**
* @param {Array<BaseItem|null>} parameters
* @returns {BaseItem}
*/
compute_NOT(parameters) {
const item = parameters[0];
if (!item) {
return BOOL_TRUE_SINGLETON;
}
if (item.getItemType() !== "boolean") {
// Not a boolean actually
return BOOL_FALSE_SINGLETON;
}
const value = /** @type {BooleanItem} */ (item).value;
return value ? BOOL_FALSE_SINGLETON : BOOL_TRUE_SINGLETON;
}
/**
* @param {Array<BaseItem|null>} parameters
* @returns {BaseItem}
*/
compute_XOR(parameters) {
assert(parameters.length === 2, "bad parameter count for XOR");
const param1 = parameters[0];
const param2 = parameters[1];
if (!param1 && !param2) {
// Not enough params
return BOOL_FALSE_SINGLETON;
}
// Check for the right types
if (param1 && param1.getItemType() !== "boolean") {
return BOOL_FALSE_SINGLETON;
}
if (param2 && param2.getItemType() !== "boolean") {
return BOOL_FALSE_SINGLETON;
}
const valueParam1 = param1 ? /** @type {BooleanItem} */ (param1).value : 0;
const valueParam2 = param2 ? /** @type {BooleanItem} */ (param2).value : 0;
return valueParam1 ^ valueParam2 ? BOOL_TRUE_SINGLETON : BOOL_FALSE_SINGLETON;
}
/**
* @param {Array<BaseItem|null>} parameters
* @returns {BaseItem}
*/
compute_OR(parameters) {
assert(parameters.length === 2, "bad parameter count for OR");
const param1 = parameters[0];
const param2 = parameters[1];
if (!param1 && !param2) {
// Not enough params
return BOOL_FALSE_SINGLETON;
}
const valueParam1 =
param1 && param1.getItemType() === "boolean" ? /** @type {BooleanItem} */ (param1).value : 0;
const valueParam2 =
param2 && param2.getItemType() === "boolean" ? /** @type {BooleanItem} */ (param2).value : 0;
return valueParam1 || valueParam2 ? BOOL_TRUE_SINGLETON : BOOL_FALSE_SINGLETON;
}
/**
* @param {Array<BaseItem|null>} parameters
* @returns {BaseItem}
*/
compute_IF(parameters) {
assert(parameters.length === 2, "bad parameter count for IF");
const flag = parameters[0];
const value = parameters[1];
if (!flag || !value) {
// Not enough params
return null;
}
if (flag.getItemType() !== "boolean") {
// Flag is not a boolean
return null;
}
// pass through item
if (/** @type {BooleanItem} */ (flag).value) {
return value;
}
return null;
}
/**
* @param {Array<BaseItem|null>} parameters
* @returns {BaseItem}
*/
compute_ROTATE(parameters) {
const item = parameters[0];
if (!item || item.getItemType() !== "shape") {
// Not a shape
return null;
}
const definition = /** @type {ShapeItem} */ (item).definition;
const rotatedDefinition = this.root.shapeDefinitionMgr.shapeActionRotateCW(definition);
return this.root.shapeDefinitionMgr.getShapeItemFromDefinition(rotatedDefinition);
}
/**
* @param {Array<BaseItem|null>} parameters
* @returns {[BaseItem, BaseItem]}
*/
compute_ANALYZE(parameters) {
const item = parameters[0];
if (!item || item.getItemType() !== "shape") {
// Not a shape
return [null, null];
}
const definition = /** @type {ShapeItem} */ (item).definition;
const lowerLayer = /** @type {import("../shape_definition").ShapeLayer} */ (definition.layers[0]);
if (!lowerLayer) {
return [null, null];
}
const topRightContent = lowerLayer[0];
if (!topRightContent || topRightContent.subShape === null) {
return [null, null];
}
const newDefinition = new ShapeDefinition({
layers: [
[
{ subShape: topRightContent.subShape, color: enumColors.uncolored },
{ subShape: topRightContent.subShape, color: enumColors.uncolored },
{ subShape: topRightContent.subShape, color: enumColors.uncolored },
{ subShape: topRightContent.subShape, color: enumColors.uncolored },
],
],
});
return [
COLOR_ITEM_SINGLETONS[topRightContent.color],
this.root.shapeDefinitionMgr.getShapeItemFromDefinition(newDefinition),
];
}
/**
* @param {Array<BaseItem|null>} parameters
* @returns {[BaseItem, BaseItem]}
*/
compute_CUT(parameters) {
const item = parameters[0];
if (!item || item.getItemType() !== "shape") {
// Not a shape
return [null, null];
}
const definition = /** @type {ShapeItem} */ (item).definition;
const result = this.root.shapeDefinitionMgr.shapeActionCutHalf(definition);
return [
result[0].isEntirelyEmpty()
? null
: this.root.shapeDefinitionMgr.getShapeItemFromDefinition(result[0]),
result[1].isEntirelyEmpty()
? null
: this.root.shapeDefinitionMgr.getShapeItemFromDefinition(result[1]),
];
}
/**
* @param {Array<BaseItem|null>} parameters
* @returns {[BaseItem, BaseItem]}
*/
compute_UNSTACK(parameters) {
const item = parameters[0];
if (!item || item.getItemType() !== "shape") {
// Not a shape
return [null, null];
}
const definition = /** @type {ShapeItem} */ (item).definition;
const layers = /** @type {Array<import("../shape_definition").ShapeLayer>} */ (definition.layers);
const upperLayerDefinition = new ShapeDefinition({
layers: [layers[layers.length - 1]],
});
const lowerLayers = layers.slice(0, layers.length - 1);
const lowerLayerDefinition =
lowerLayers.length > 0 ? new ShapeDefinition({ layers: lowerLayers }) : null;
return [
lowerLayerDefinition
? this.root.shapeDefinitionMgr.getShapeItemFromDefinition(lowerLayerDefinition)
: null,
this.root.shapeDefinitionMgr.getShapeItemFromDefinition(upperLayerDefinition),
];
}
/**
* @param {Array<BaseItem|null>} parameters
* @returns {BaseItem}
*/
compute_SHAPECOMPARE(parameters) {
const itemA = parameters[0];
const itemB = parameters[1];
return itemA &&
itemB &&
itemA.getItemType() === "shape" &&
itemB.getItemType() === "shape" &&
/** @type {ShapeItem} */ (itemA).definition.getHash() ===
/** @type {ShapeItem} */ (itemB).definition.getHash()
? BOOL_TRUE_SINGLETON
: BOOL_FALSE_SINGLETON;
}
}

View File

@ -1,179 +1,182 @@
import { ShapeDefinition } from "./shape_definition";
import { finalGameShape } from "./upgrades";
/**
* Don't forget to also update tutorial_goals_mappings.js as well as the translations!
* @enum {string}
*/
export const enumHubGoalRewards = {
reward_cutter_and_trash: "reward_cutter_and_trash",
reward_rotater: "reward_rotater",
reward_painter: "reward_painter",
reward_mixer: "reward_mixer",
reward_stacker: "reward_stacker",
reward_splitter: "reward_splitter",
reward_tunnel: "reward_tunnel",
reward_rotater_ccw: "reward_rotater_ccw",
reward_rotater_fl: "reward_rotater_fl",
reward_miner_chainable: "reward_miner_chainable",
reward_underground_belt_tier_2: "reward_underground_belt_tier_2",
reward_splitter_compact: "reward_splitter_compact",
reward_cutter_quad: "reward_cutter_quad",
reward_painter_double: "reward_painter_double",
reward_painter_quad: "reward_painter_quad",
reward_storage: "reward_storage",
reward_blueprints: "reward_blueprints",
reward_freeplay: "reward_freeplay",
no_reward: "no_reward",
no_reward_freeplay: "no_reward_freeplay",
};
export const tutorialGoals = [
// 1
// Circle
{
shape: "CuCuCuCu", // belts t1
required: 40,
reward: enumHubGoalRewards.reward_cutter_and_trash,
},
// 2
// Cutter
{
shape: "----CuCu", //
required: 40,
reward: enumHubGoalRewards.no_reward,
},
// 3
// Rectangle
{
shape: "RuRuRuRu", // miners t1
required: 100,
reward: enumHubGoalRewards.reward_splitter,
},
// 4
{
shape: "RuRu----", // processors t2
required: 120,
reward: enumHubGoalRewards.reward_rotater,
},
// 5
// Rotater
{
shape: "Cu----Cu", // belts t2
required: 200,
reward: enumHubGoalRewards.reward_tunnel,
},
// 6
{
shape: "Cu------", // miners t2
required: 400,
reward: enumHubGoalRewards.reward_painter,
},
// 7
// Painter
{
shape: "CrCrCrCr", // unused
required: 800,
reward: enumHubGoalRewards.reward_rotater_ccw,
},
// 8
{
shape: "RbRb----", // painter t2
required: 1000,
reward: enumHubGoalRewards.reward_mixer,
},
// 9
// Mixing (purple)
{
shape: "CpCpCpCp", // belts t3
required: 1400,
reward: enumHubGoalRewards.reward_splitter_compact,
},
// 10
// Star shape + cyan
{
shape: "ScScScSc", // miners t3
required: 1600,
reward: enumHubGoalRewards.reward_stacker,
},
// 11
// Stacker
{
shape: "CgScScCg", // processors t3
required: 1800,
reward: enumHubGoalRewards.reward_miner_chainable,
},
// 12
// Blueprints
{
shape: "CbCbCbRb:CwCwCwCw",
required: 2000,
reward: enumHubGoalRewards.reward_blueprints,
},
// 13
{
shape: "RpRpRpRp:CwCwCwCw", // painting t3
required: 12000,
reward: enumHubGoalRewards.reward_underground_belt_tier_2,
},
// 14
{
shape: "SrSrSrSr:CyCyCyCy", // unused
required: 16000,
reward: enumHubGoalRewards.reward_storage,
},
// 15
{
shape: "SrSrSrSr:CyCyCyCy:SwSwSwSw", // belts t4 (two variants)
required: 25000,
reward: enumHubGoalRewards.reward_cutter_quad,
},
// 16
{
shape: "CbRbRbCb:CwCwCwCw:WbWbWbWb", // miner t4 (two variants)
required: 50000,
reward: enumHubGoalRewards.reward_painter_double,
},
// 17
{
shape: "WrRgWrRg:CwCrCwCr:SgSgSgSg", // processors t4 (two variants)
required: 120000,
reward: enumHubGoalRewards.reward_painter_quad,
},
// 18
{
shape: finalGameShape,
required: 250000,
reward: enumHubGoalRewards.reward_freeplay,
},
];
if (G_IS_DEV) {
tutorialGoals.forEach(({ shape }) => {
try {
ShapeDefinition.fromShortKey(shape);
} catch (ex) {
throw new Error("Invalid tutorial goal: '" + ex + "' for shape" + shape);
}
});
}
import { ShapeDefinition } from "./shape_definition";
import { finalGameShape } from "./upgrades";
/**
* Don't forget to also update tutorial_goals_mappings.js as well as the translations!
* @enum {string}
*/
export const enumHubGoalRewards = {
reward_cutter_and_trash: "reward_cutter_and_trash",
reward_rotater: "reward_rotater",
reward_painter: "reward_painter",
reward_mixer: "reward_mixer",
reward_stacker: "reward_stacker",
reward_splitter: "reward_splitter",
reward_tunnel: "reward_tunnel",
reward_rotater_ccw: "reward_rotater_ccw",
reward_rotater_fl: "reward_rotater_fl",
reward_miner_chainable: "reward_miner_chainable",
reward_underground_belt_tier_2: "reward_underground_belt_tier_2",
reward_splitter_compact: "reward_splitter_compact",
reward_cutter_quad: "reward_cutter_quad",
reward_painter_double: "reward_painter_double",
reward_painter_quad: "reward_painter_quad",
reward_storage: "reward_storage",
// @todo: unlock
reward_merger_compact: "reward_compact_merger",
reward_blueprints: "reward_blueprints",
reward_freeplay: "reward_freeplay",
no_reward: "no_reward",
no_reward_freeplay: "no_reward_freeplay",
};
export const tutorialGoals = [
// 1
// Circle
{
shape: "CuCuCuCu", // belts t1
required: 40,
reward: enumHubGoalRewards.reward_cutter_and_trash,
},
// 2
// Cutter
{
shape: "----CuCu", //
required: 40,
reward: enumHubGoalRewards.no_reward,
},
// 3
// Rectangle
{
shape: "RuRuRuRu", // miners t1
required: 100,
reward: enumHubGoalRewards.reward_splitter,
},
// 4
{
shape: "RuRu----", // processors t2
required: 120,
reward: enumHubGoalRewards.reward_rotater,
},
// 5
// Rotater
{
shape: "Cu----Cu", // belts t2
required: 200,
reward: enumHubGoalRewards.reward_tunnel,
},
// 6
{
shape: "Cu------", // miners t2
required: 400,
reward: enumHubGoalRewards.reward_painter,
},
// 7
// Painter
{
shape: "CrCrCrCr", // unused
required: 800,
reward: enumHubGoalRewards.reward_rotater_ccw,
},
// 8
{
shape: "RbRb----", // painter t2
required: 1000,
reward: enumHubGoalRewards.reward_mixer,
},
// 9
// Mixing (purple)
{
shape: "CpCpCpCp", // belts t3
required: 1400,
reward: enumHubGoalRewards.reward_splitter_compact,
},
// 10
// Star shape + cyan
{
shape: "ScScScSc", // miners t3
required: 1600,
reward: enumHubGoalRewards.reward_stacker,
},
// 11
// Stacker
{
shape: "CgScScCg", // processors t3
required: 1800,
reward: enumHubGoalRewards.reward_miner_chainable,
},
// 12
// Blueprints
{
shape: "CbCbCbRb:CwCwCwCw",
required: 2000,
reward: enumHubGoalRewards.reward_blueprints,
},
// 13
{
shape: "RpRpRpRp:CwCwCwCw", // painting t3
required: 12000,
reward: enumHubGoalRewards.reward_underground_belt_tier_2,
},
// 14
{
shape: "SrSrSrSr:CyCyCyCy", // unused
required: 16000,
reward: enumHubGoalRewards.reward_storage,
},
// 15
{
shape: "SrSrSrSr:CyCyCyCy:SwSwSwSw", // belts t4 (two variants)
required: 25000,
reward: enumHubGoalRewards.reward_cutter_quad,
},
// 16
{
shape: "CbRbRbCb:CwCwCwCw:WbWbWbWb", // miner t4 (two variants)
required: 50000,
reward: enumHubGoalRewards.reward_painter_double,
},
// 17
{
shape: "WrRgWrRg:CwCrCwCr:SgSgSgSg", // processors t4 (two variants)
required: 120000,
reward: enumHubGoalRewards.reward_painter_quad,
},
// 18
{
shape: finalGameShape,
required: 250000,
reward: enumHubGoalRewards.reward_freeplay,
},
];
if (G_IS_DEV) {
tutorialGoals.forEach(({ shape }) => {
try {
ShapeDefinition.fromShortKey(shape);
} catch (ex) {
throw new Error("Invalid tutorial goal: '" + ex + "' for shape" + shape);
}
});
}

File diff suppressed because it is too large Load Diff

View File

@ -1,218 +1,225 @@
import { ExplainedResult } from "../core/explained_result";
import { createLogger } from "../core/logging";
import { ReadWriteProxy } from "../core/read_write_proxy";
import { globalConfig } from "../core/config";
import { Savegame } from "./savegame";
const logger = createLogger("savegame_manager");
const Rusha = require("rusha");
/**
* @typedef {import("./savegame_typedefs").SavegamesData} SavegamesData
* @typedef {import("./savegame_typedefs").SavegameMetadata} SavegameMetadata
*/
/** @enum {string} */
export const enumLocalSavegameStatus = {
offline: "offline",
synced: "synced",
};
export class SavegameManager extends ReadWriteProxy {
constructor(app) {
super(app, "savegames.bin");
this.currentData = this.getDefaultData();
}
// RW Proxy Impl
/**
* @returns {SavegamesData}
*/
getDefaultData() {
return {
version: this.getCurrentVersion(),
savegames: [],
};
}
getCurrentVersion() {
return 1001;
}
/**
* @returns {SavegamesData}
*/
getCurrentData() {
return super.getCurrentData();
}
verify(data) {
// TODO / FIXME!!!!
return ExplainedResult.good();
}
/**
*
* @param {SavegamesData} data
*/
migrate(data) {
if (data.version < 1001) {
data.savegames.forEach(savegame => {
savegame.level = 0;
});
data.version = 1001;
}
return ExplainedResult.good();
}
// End rw proxy
/**
* @returns {Array<SavegameMetadata>}
*/
getSavegamesMetaData() {
return this.currentData.savegames;
}
/**
*
* @param {string} internalId
* @returns {Savegame}
*/
getSavegameById(internalId) {
const metadata = this.getGameMetaDataByInternalId(internalId);
if (!metadata) {
return null;
}
return new Savegame(this.app, { internalId, metaDataRef: metadata });
}
/**
* Deletes a savegame
* @param {SavegameMetadata} game
*/
deleteSavegame(game) {
const handle = new Savegame(this.app, {
internalId: game.internalId,
metaDataRef: game,
});
return handle.deleteAsync().then(() => {
for (let i = 0; i < this.currentData.savegames.length; ++i) {
const potentialGame = this.currentData.savegames[i];
if (potentialGame.internalId === handle.internalId) {
this.currentData.savegames.splice(i, 1);
break;
}
}
return this.writeAsync();
});
}
/**
* Returns a given games metadata by id
* @param {string} id
* @returns {SavegameMetadata}
*/
getGameMetaDataByInternalId(id) {
for (let i = 0; i < this.currentData.savegames.length; ++i) {
const data = this.currentData.savegames[i];
if (data.internalId === id) {
return data;
}
}
logger.error("Savegame internal id not found:", id);
return null;
}
/**
* Creates a new savegame
* @returns {Savegame}
*/
createNewSavegame() {
const id = this.generateInternalId();
const metaData = /** @type {SavegameMetadata} */ ({
lastUpdate: Date.now(),
version: Savegame.getCurrentVersion(),
internalId: id,
});
this.currentData.savegames.push(metaData);
this.sortSavegames();
return new Savegame(this.app, {
internalId: id,
metaDataRef: metaData,
});
}
importSavegame(data) {
const savegame = this.createNewSavegame();
const migrationResult = savegame.migrate(data);
if (migrationResult.isBad()) {
return Promise.reject("Failed to migrate: " + migrationResult.reason);
}
savegame.currentData = data;
const verification = savegame.verify(data);
if (verification.isBad()) {
return Promise.reject("Verification failed: " + verification.result);
}
return savegame.writeSavegameAndMetadata().then(() => this.sortSavegames());
}
/**
* Sorts all savegames by their creation time descending
* @returns {Promise<any>}
*/
sortSavegames() {
this.currentData.savegames.sort((a, b) => b.lastUpdate - a.lastUpdate);
let promiseChain = Promise.resolve();
while (this.currentData.savegames.length > 30) {
const toRemove = this.currentData.savegames.pop();
// Try to remove the savegame since its no longer available
const game = new Savegame(this.app, {
internalId: toRemove.internalId,
metaDataRef: toRemove,
});
promiseChain = promiseChain
.then(() => game.deleteAsync())
.then(
() => {},
err => {
logger.error(this, "Failed to remove old savegame:", toRemove, ":", err);
}
);
}
return promiseChain;
}
/**
* Helper method to generate a new internal savegame id
*/
generateInternalId() {
return Rusha.createHash()
.update(Date.now() + "/" + Math.random())
.digest("hex");
}
// End
initialize() {
// First read, then directly write to ensure we have the latest data
// @ts-ignore
return this.readAsync().then(() => {
if (G_IS_DEV && globalConfig.debug.disableSavegameWrite) {
return Promise.resolve();
}
return this.sortSavegames().then(() => this.writeAsync());
});
}
}
import { ExplainedResult } from "../core/explained_result";
import { createLogger } from "../core/logging";
import { ReadWriteProxy } from "../core/read_write_proxy";
import { globalConfig } from "../core/config";
import { Savegame } from "./savegame";
const logger = createLogger("savegame_manager");
const Rusha = require("rusha");
/**
* @typedef {import("./savegame_typedefs").SavegamesData} SavegamesData
* @typedef {import("./savegame_typedefs").SavegameMetadata} SavegameMetadata
*/
/** @enum {string} */
export const enumLocalSavegameStatus = {
offline: "offline",
synced: "synced",
};
export class SavegameManager extends ReadWriteProxy {
constructor(app) {
super(app, "savegames.bin");
this.currentData = this.getDefaultData();
}
// RW Proxy Impl
/**
* @returns {SavegamesData}
*/
getDefaultData() {
return {
version: this.getCurrentVersion(),
savegames: [],
};
}
getCurrentVersion() {
return 1002;
}
/**
* @returns {SavegamesData}
*/
getCurrentData() {
return super.getCurrentData();
}
verify(data) {
// TODO / FIXME!!!!
return ExplainedResult.good();
}
/**
*
* @param {SavegamesData} data
*/
migrate(data) {
if (data.version < 1001) {
data.savegames.forEach(savegame => {
savegame.level = 0;
});
data.version = 1001;
}
if (data.version < 1002) {
data.savegames.forEach(savegame => {
savegame.name = null;
});
data.version = 1002;
}
return ExplainedResult.good();
}
// End rw proxy
/**
* @returns {Array<SavegameMetadata>}
*/
getSavegamesMetaData() {
return this.currentData.savegames;
}
/**
*
* @param {string} internalId
* @returns {Savegame}
*/
getSavegameById(internalId) {
const metadata = this.getGameMetaDataByInternalId(internalId);
if (!metadata) {
return null;
}
return new Savegame(this.app, { internalId, metaDataRef: metadata });
}
/**
* Deletes a savegame
* @param {SavegameMetadata} game
*/
deleteSavegame(game) {
const handle = new Savegame(this.app, {
internalId: game.internalId,
metaDataRef: game,
});
return handle.deleteAsync().then(() => {
for (let i = 0; i < this.currentData.savegames.length; ++i) {
const potentialGame = this.currentData.savegames[i];
if (potentialGame.internalId === handle.internalId) {
this.currentData.savegames.splice(i, 1);
break;
}
}
return this.writeAsync();
});
}
/**
* Returns a given games metadata by id
* @param {string} id
* @returns {SavegameMetadata}
*/
getGameMetaDataByInternalId(id) {
for (let i = 0; i < this.currentData.savegames.length; ++i) {
const data = this.currentData.savegames[i];
if (data.internalId === id) {
return data;
}
}
logger.error("Savegame internal id not found:", id);
return null;
}
/**
* Creates a new savegame
* @returns {Savegame}
*/
createNewSavegame() {
const id = this.generateInternalId();
const metaData = /** @type {SavegameMetadata} */ ({
lastUpdate: Date.now(),
version: Savegame.getCurrentVersion(),
internalId: id,
});
this.currentData.savegames.push(metaData);
this.sortSavegames();
return new Savegame(this.app, {
internalId: id,
metaDataRef: metaData,
});
}
importSavegame(data) {
const savegame = this.createNewSavegame();
const migrationResult = savegame.migrate(data);
if (migrationResult.isBad()) {
return Promise.reject("Failed to migrate: " + migrationResult.reason);
}
savegame.currentData = data;
const verification = savegame.verify(data);
if (verification.isBad()) {
return Promise.reject("Verification failed: " + verification.result);
}
return savegame.writeSavegameAndMetadata().then(() => this.sortSavegames());
}
/**
* Sorts all savegames by their creation time descending
* @returns {Promise<any>}
*/
sortSavegames() {
this.currentData.savegames.sort((a, b) => b.lastUpdate - a.lastUpdate);
let promiseChain = Promise.resolve();
while (this.currentData.savegames.length > 30) {
const toRemove = this.currentData.savegames.pop();
// Try to remove the savegame since its no longer available
const game = new Savegame(this.app, {
internalId: toRemove.internalId,
metaDataRef: toRemove,
});
promiseChain = promiseChain
.then(() => game.deleteAsync())
.then(
() => {},
err => {
logger.error(this, "Failed to remove old savegame:", toRemove, ":", err);
}
);
}
return promiseChain;
}
/**
* Helper method to generate a new internal savegame id
*/
generateInternalId() {
return Rusha.createHash()
.update(Date.now() + "/" + Math.random())
.digest("hex");
}
// End
initialize() {
// First read, then directly write to ensure we have the latest data
// @ts-ignore
return this.readAsync().then(() => {
if (G_IS_DEV && globalConfig.debug.disableSavegameWrite) {
return Promise.resolve();
}
return this.sortSavegames().then(() => this.writeAsync());
});
}
}

View File

@ -1,38 +1,39 @@
/**
* @typedef {import("../game/entity").Entity} Entity
*
* @typedef {{}} SavegameStats
*
* @typedef {{
* camera: any,
* time: any,
* entityMgr: any,
* map: any,
* hubGoals: any,
* pinnedShapes: any,
* waypoints: any,
* entities: Array<Entity>,
* beltPaths: Array<any>
* }} SerializedGame
*
* @typedef {{
* version: number,
* dump: SerializedGame,
* stats: SavegameStats,
* lastUpdate: number,
* }} SavegameData
*
* @typedef {{
* lastUpdate: number,
* version: number,
* internalId: string,
* level: number
* }} SavegameMetadata
*
* @typedef {{
* version: number,
* savegames: Array<SavegameMetadata>
* }} SavegamesData
*/
export default {};
/**
* @typedef {import("../game/entity").Entity} Entity
*
* @typedef {{}} SavegameStats
*
* @typedef {{
* camera: any,
* time: any,
* entityMgr: any,
* map: any,
* hubGoals: any,
* pinnedShapes: any,
* waypoints: any,
* entities: Array<Entity>,
* beltPaths: Array<any>
* }} SerializedGame
*
* @typedef {{
* version: number,
* dump: SerializedGame,
* stats: SavegameStats,
* lastUpdate: number,
* }} SavegameData
*
* @typedef {{
* lastUpdate: number,
* version: number,
* internalId: string,
* level: number
* name: string|null
* }} SavegameMetadata
*
* @typedef {{
* version: number,
* savegames: Array<SavegameMetadata>
* }} SavegamesData
*/
export default {};

File diff suppressed because it is too large Load Diff

View File

@ -17,7 +17,7 @@ export class MobileWarningState extends GameState {
There is also no estimate when this will change, but feel to make a contribution! It's
&nbsp;<a href="https://github.com/tobspr/shapez.io" target="_blank">open source</a>!</p>
<p>If you want to play on your computer, you can also get the standalone on steam:</p>
<p>If you want to play on your computer, you can also get the standalone on Steam:</p>
<a href="${

View File

@ -25,7 +25,7 @@ steamPage:
shortText: shapez.io és un joc que té com a objectiu construir i automatitzar fàbriques per tal de produir figures cada cop més complexes en un mapa infinit.
# This is the text shown above the Discord link
discordLink: Official Discord - Chat with me!
discordLink: Discord Oficial (en Anglès)
# This is the long description for the steam page - It is contained here so you can help to translate it, and I will regulary update the store page.
# NOTICE:
@ -34,50 +34,50 @@ steamPage:
longText: >-
[img]{STEAM_APP_IMAGE}/extras/store_page_gif.gif[/img]
shapez.io is a game about building factories to automate the creation and processing of increasingly complex shapes across an infinitely expanding map.
shapez.io és un joc que té com a objectiu construir i automatitzar fàbriques per tal de produir figures cada cop més complexes en un mapa infinit.
Upon delivering the requested shapes you'll progress within the game and unlock upgrades to speed up your factory.
Al lliurar les formes geomètriques sol·licitades, progressaràs i desbloquejaràs millores per accelerar la teva fàbrica.
As the demand for shapes increases, you'll have to scale up your factory to meet the demand - Don't forget about resources though, you'll have to expand across the [b]infinite map[/b]!
Com que la demanda de figures va augmentant, hauràs de augmentar proporcionalment la teva fàbrica per satisfer la demanda. Però no t'oblidis dels recursos, ja que t'hauràs d'expandre a través del [b]mapa infinit[/b]!
Soon you'll have to mix colors and paint your shapes with them - Combine red, green and blue color resources to produce different colors and paint shapes with them to satisfy the demand.
Sovint, hauràs de començar a mesclar color i pintar les figures amb aquests; combina roig, verd i blau per produïr diferents colors i pintar les figures amb aquests per satisfer la demanda.
This game features 18 progressive levels (Which should already keep you busy for hours!) but I'm constantly adding new content - There's a lot planned!
Aquest joc presenta 18 nivells progressius (Els quals ja haurien de mantenir-te ocupat durant hores!) però estic constantment afegint nou contingut. Tenim moltes coses planejades!
Purchasing the game gives you access to the standalone version which has additional features, and you'll also receive access to newly developed features.
La compra del joc et dona accés a versió independent amb característiques adicionals, i també rebràs accés a les noves característiques que es desenvolupin.
[b]Standalone Advantages[/b]
[b]Ventatges de la Versió Independent[/b]
[list]
[*] Dark Mode
[*] Unlimited Waypoints
[*] Unlimited Savegames
[*] Additional settings
[*] Coming soon: Wires & Energy! Aiming for (roughly) end of July 2020.
[*] Coming soon: More Levels
[*] Allows me to further develop shapez.io ❤️
[*] Mode Oscur
[*] Punts d'interès il·limitats
[*] Guardar partides il·limitades
[*] Configuracions Adicionals
[*] Pròximament: Cables i Energia! Objectiu (aproximadament) per finals de Juliol del 2020.
[*] Pròximament: Més Nivells
[*] Em permet seguir desenvolupant shapez.io ❤️
[/list]
[b]Future Updates[/b]
[b]Futures Actualitzacions[/b]
I am updating the game often and trying to push an update at least once every week!
Actualitzo el joc sovint i intent treure una actualització nova per setmana!
[list]
[*] Different maps and challenges (e.g. maps with obstacles)
[*] Puzzles (Deliver the requested shape with a restricted area / set of buildings)
[*] A story mode where buildings have a cost
[*] Configurable map generator (Configure resource/shape size/density, seed and more)
[*] Additional types of shapes
[*] Performance improvements (The game already runs pretty well!)
[*] And much more!
[*] Mapes i reptes diferents (p.e. mapes amb obstacles)
[*] Trencaclosques (Entrega la figura amb una àrea/conjunt d'edificis delimitats)
[*] Un "Mode Història" on els edificis tenen un cost
[*] Generador de mapes configurable (Configura el tamany/densitat de les formes/recursos, llavors i més)
[*] Formes geomètriques adicionals
[*] Millores de rendiment (El joc ja funciona força bé!)
[*] Moltes coses més!
[/list]
[b]This game is open source![/b]
[b]Aquest joc és de codi obert![/b]
Anybody can contribute, I'm actively involved in the community and attempt to review all suggestions and take feedback into consideration where possible.
Be sure to check out my trello board for the full roadmap!
Qualsevol pot contribuir, estic involucrat activament en la comunitat i intento revisar tots els suggeriments i tenir en compte els comentaris sempre que sigui possible.
Assegureu-vos de consultar el meu tauler de trello per obtenir el full de ruta complet!
[b]Links[/b]
[b]Enllaços[/b]
[list]
[*] [url=https://discord.com/invite/HN7EVzV]Official Discord[/url]
@ -174,7 +174,7 @@ dialogs:
importSavegameError:
title: Error en importar
text: >-
Failed to import your savegame:
Ha ocurrit un error intentant importar la teva partida:
importSavegameSuccess:
title: Importar
@ -184,7 +184,7 @@ dialogs:
gameLoadFailure:
title: No es pot carregar la partida guardada
text: >-
Failed to load your savegame:
Ha ocurrit un error al intentar carregar la teva partida:
confirmSavegameDelete:
title: Eliminar
@ -194,7 +194,7 @@ dialogs:
savegameDeletionError:
title: Error en eliminar
text: >-
Failed to delete the savegame:
Ha ocurrit un error al intentar eliminar la teva partida:
restartRequired:
title: Reiniciar
@ -240,12 +240,12 @@ dialogs:
massCutConfirm:
title: Tallar edificis
desc: >-
Estàs esborrant molts edificis de cop (<count> per ser exactes)! Estàs segur que vols seguir?
Estàs tallant molts edificis de cop (<count> per ser exactes)! Estàs segur que vols seguir?
massCutInsufficientConfirm:
title: Confirm cut
title: Confirmar tallar
desc: >-
You can not afford to paste this area! Are you sure you want to cut it?
No pots aferrar a aquesta zona! Estàs segur de que vols tallarla?
blueprintsNotUnlocked:
title: Encara no s'ha desbloquejat
@ -271,7 +271,7 @@ dialogs:
desc: En la Demo només pots crear dos marcadors, aconsegueix la versió completa per gaudir de l'experiència completa!
exportScreenshotWarning:
title: Export screenshot
title: Exportar Captura de Pantalla
desc: Has demanat exportar la teva/teua base com una captura de pantalla. Tin en conte que aquest procés pot ser molt lent i inclús crashear el teu joc!
ingame:
@ -307,7 +307,7 @@ ingame:
purple: Morat
cyan: Cian
white: Blanc
black: Black
black: Negre
uncolored: Sense color
# Everything related to placing buildings (I.e. as soon as you selected a building
@ -315,7 +315,7 @@ ingame:
buildingPlacement:
# Buildings can have different variants which are unlocked at later levels,
# and this is the hint shown when there are multiple variants available.
cycleBuildingVariants: Pulsa <key> per a ciclar entre variants.
cycleBuildingVariants: Prem <key> per a ciclar entre variants.
# Shows the hotkey in the ui, e.g. "Hotkey: Q"
hotkeyLabel: >-
@ -687,139 +687,139 @@ settings:
disabled: Desactivat
scrollWheelSensitivity:
title: Zoom sensitivity
title: Sensitivitat del Zoom
description: >-
Changes how sensitive the zoom is (Either mouse wheel or trackpad).
Canvia la sensitivitat del zoom (Roda del ratolí o del trackpad).
sensitivity:
super_slow: Super slow
slow: Slow
super_slow: Molt lent
slow: Lent
regular: Regular
fast: Fast
super_fast: Super fast
fast: Ràpid
super_fast: Molt Ràpid
movementSpeed:
title: Movement speed
title: Velocitat de Moviment
description: >-
Changes how fast the view moves when using the keyboard.
Canvia la rapidesa amb la que la vista es mou mentres empres el teclat.
speeds:
super_slow: Super slow
slow: Slow
super_slow: Molt lent
slow: Lent
regular: Regular
fast: Fast
super_fast: Super Fast
extremely_fast: Extremely Fast
fast: Rápid
super_fast: Molt Ràpid
extremely_fast: Extremadament Ràpid
language:
title: Language
title: Idioma
description: >-
Change the language. All translations are user-contributed and might be incomplete!
Canvia l'idioma. Totes les traduccions són contribucions d'usuaris i poden estar incompletes!
enableColorBlindHelper:
title: Color Blind Mode
title: Mode per Daltònics
description: >-
Enables various tools which allow you to play the game if you are color blind.
Habilita diverses eines que et permeten jugar si ets Daltònic.
fullscreen:
title: Fullscreen
title: Pantalla Completa
description: >-
It is recommended to play the game in fullscreen to get the best experience. Only available in the standalone.
Es recomana jugar en Pantalla Completa per aconseguir la millor experiència. Només disponible a la versió completa del joc.
soundsMuted:
title: Mute Sounds
title: Silencia els sons
description: >-
If enabled, mutes all sound effects.
Si està activat, silencia tots els sons.
musicMuted:
title: Mute Music
title: Silencia la música
description: >-
If enabled, mutes all music.
Si està activat, silencia la música.
theme:
title: Game theme
title: Tema del joc (Visual)
description: >-
Choose the game theme (light / dark).
Tria el tema visual (clar / oscur).
themes:
dark: Dark
light: Light
dark: Oscur
light: Clar
refreshRate:
title: Simulation Target
title: Objectiu de Simulació
description: >-
If you have a 144hz monitor, change the refresh rate here so the game will properly simulate at higher refresh rates. This might actually decrease the FPS if your computer is too slow.
Si tens un monitor de 144hz, canvia la tarifa de refresc aquí per que el joc es mostri de forma correcta a tarifes de refresc altes. Pot decrementar els FPS si el teu ordenador és massa lent.
alwaysMultiplace:
title: Multiplace
title: Col·locació Múltiple
description: >-
If enabled, all buildings will stay selected after placement until you cancel it. This is equivalent to holding SHIFT permanently.
Si s'activa, tots els edificis es mantindràn seleccionats després de col·locarlos fins que ho cancel·lis. Això és equivalent a mantenir SHIFT permanentment.
offerHints:
title: Hints & Tutorials
title: Pistes i Tutorials
description: >-
Whether to offer hints and tutorials while playing. Also hides certain UI elements up to a given level to make it easier to get into the game.
Si s'activa, es mostraràn pistes i tutorials mentres es juga. També amaga certs elements visuals fins a un nivell per que sigui més fàcil aprendre a jugar.
enableTunnelSmartplace:
title: Smart Tunnels
title: Túnels Intel·ligents
description: >-
When enabled, placing tunnels will automatically remove unnecessary belts. This also enables you to drag tunnels and excess tunnels will get removed.
Si s'activa, al col·locar túnels s'eliminaràn les cintes transportadores innecessaris. També et permet arrastrar túnels i els túnels sobrants s'eliminaràn.
vignette:
title: Vignette
title: Vinyeta
description: >-
Enables the vignette, which darkens the screen corners and makes text easier to read.
Activa la vinyeta, que obscureix els cantons de la pantalla i facilita la lectura de texte.
rotationByBuilding:
title: Rotation by building type
title: Rotació segons el tipus d'edifici.
description: >-
Each building type remembers the rotation you last set it to individually. This may be more comfortable if you frequently switch between placing different building types.
Cada tipus d'edifici recorda la rotació que vau definir per última vegada de manera individual. Això pot ser més còmode si canvies freqüentment entre edificis.
compactBuildingInfo:
title: Compact Building Infos
title: Informació sobre Edificis Compactes
description: >-
Shortens info boxes for buildings by only showing their ratios. Otherwise a description and image is shown.
Escurça els quadres dinformació dels edificis només mostrant les seves velocitats. En cas contrari, es mostra una descripció i una imatge.
disableCutDeleteWarnings:
title: Disable Cut/Delete Warnings
title: Desactiva els diàlegs de Talla/Borra
description: >-
Disables the warning dialogs brought up when cutting/deleting more than 100 entities.
Desactiva els diàlegs d'advertència que es mostren en tallar / suprimir més de 100 entitats.
keybindings:
title: Keybindings
title: Combinacions de tecles
hint: >-
Tip: Be sure to make use of CTRL, SHIFT and ALT! They enable different placement options.
Tip: Assegura't d'emprar CTRL, SHIFT i ALT! Et permeten col·locar objectes de formes diferents.
resetKeybindings: Reset Keybindings
resetKeybindings: Resetejar les Combinacions de tecles
categoryLabels:
general: Application
ingame: Game
navigation: Navigating
placement: Placement
massSelect: Mass Select
buildings: Building Shortcuts
placementModifiers: Placement Modifiers
general: Aplicació
ingame: Joc
navigation: Navegació
placement: Col·locació
massSelect: Sel·lecció Massiva
buildings: Dreceres d'Edificis
placementModifiers: Modificadors de col·locació
mappings:
confirm: Confirm
back: Back
mapMoveUp: Move Up
mapMoveRight: Move Right
mapMoveDown: Move Down
mapMoveLeft: Move Left
mapMoveFaster: Move Faster
centerMap: Center Map
confirm: Confirmar
back: Enrere
mapMoveUp: Moure Amunt
mapMoveRight: Moure Dreta
mapMoveDown: Moure Avall
mapMoveLeft: Moure Esquerra
mapMoveFaster: Moure més Ràpid
centerMap: Centrar Mapa
mapZoomIn: Zoom in
mapZoomOut: Zoom out
createMarker: Create Marker
mapZoomIn: Apropar
mapZoomOut: Allunyar
createMarker: Crea un Marcador
menuOpenShop: Upgrades
menuOpenStats: Statistics
menuClose: Close Menu
menuOpenShop: Millores
menuOpenStats: Estadístiques
menuClose: Tancar Menú
toggleHud: Toggle HUD
toggleFPSInfo: Toggle FPS and Debug Info
switchLayers: Switch layers
exportScreenshot: Export whole Base as Image
toggleHud: Commutar HUD
toggleFPSInfo: Commutar FPS i Informació de Depuració
switchLayers: Canviar capes
exportScreenshot: Exportar la Base com a Imatge
belt: *belt
splitter: *splitter
underground_belt: *underground_belt
@ -834,49 +834,49 @@ keybindings:
trash: *trash
wire: *wire
pipette: Pipette
rotateWhilePlacing: Rotate
pipette: Pipeta
rotateWhilePlacing: Rotar
rotateInverseModifier: >-
Modifier: Rotate CCW instead
cycleBuildingVariants: Cycle Variants
confirmMassDelete: Delete area
pasteLastBlueprint: Paste last blueprint
cycleBuildings: Cycle Buildings
lockBeltDirection: Enable belt planner
Modifier: Rotar en sentit antihorari
cycleBuildingVariants: Rotar les Variants
confirmMassDelete: Eliminar àrea
pasteLastBlueprint: Afferar el darrer pla
cycleBuildings: Rotar els Buildings
lockBeltDirection: Habilitar el planificador de cintes transportadores
switchDirectionLockSide: >-
Planner: Switch side
Planner: Canviar costat
massSelectStart: Hold and drag to start
massSelectSelectMultiple: Select multiple areas
massSelectCopy: Copy area
massSelectCut: Cut area
massSelectStart: Manteniu premut i arrossegueu per començar
massSelectSelectMultiple: Seleccionar múltiples àrees
massSelectCopy: Copiar àrea
massSelectCut: Tallar àrea
placementDisableAutoOrientation: Disable automatic orientation
placeMultiple: Stay in placement mode
placeInverse: Invert automatic belt orientation
placementDisableAutoOrientation: Desactivar orientació automàtica
placeMultiple: Mantenir-se en mode de col·locació
placeInverse: Invertir orientació automàtica de les cintes transportadores
about:
title: About this Game
title: Sobre aquest Joc
body: >-
This game is open source and developed by <a href="https://github.com/tobspr" target="_blank">Tobias Springer</a> (this is me).<br><br>
Aquest joc és de codi obert i desenvolupat per <a href="https://github.com/tobspr" target="_blank">Tobias Springer</a> (sóc jo).<br><br>
If you want to contribute, check out <a href="<githublink>" target="_blank">shapez.io on GitHub</a>.<br><br>
Si vols contribuir, visita <a href="<githublink>" target="_blank">shapez.io a GitHub</a>.<br><br>
This game wouldn't have been possible without the great Discord community around my games - You should really join the <a href="<discordlink>" target="_blank">Discord server</a>!<br><br>
Aquest joc no hauria estat possible sense la gran comunitat de Discord al voltant dels meus jocs. Recoman unir-se al <a href="<discordlink>" target="_blank">servidor de Discord</a>!<br><br>
The soundtrack was made by <a href="https://soundcloud.com/pettersumelius" target="_blank">Peppsen</a> - He's awesome.<br><br>
Banda sonora creada per<a href="https://soundcloud.com/pettersumelius" target="_blank">Peppsen</a> - És increïble.<br><br>
Finally, huge thanks to my best friend <a href="https://github.com/niklas-dahl" target="_blank">Niklas</a> - Without our Factorio sessions, this game would never have existed.
Finalment, gràcies al meu millor amic <a href="https://github.com/niklas-dahl" target="_blank">Niklas</a>. Sense les nostres sessions de Factorio, aquest joc mai hauria existit.
changelog:
title: Changelog
title: Registre de Canvis
demo:
features:
restoringGames: Restoring savegames
importingGames: Importing savegames
oneGameLimit: Limited to one savegame
customizeKeybindings: Customizing Keybindings
exportingBase: Exporting whole Base as Image
restoringGames: Restaurar partides guardats
importingGames: Importar partides guardats
oneGameLimit: Limitat a una partida guardada.
customizeKeybindings: Personalitzar teclats
exportingBase: Exportar la base com a Imatge
settingNotAvailable: Not available in the demo.
settingNotAvailable: No disponible en la versió de demostració.

View File

@ -234,8 +234,8 @@ dialogs:
createMarker:
title: Nová značka
desc: Give it a meaningful name, you can also include a <strong>short key</strong> of a shape (Which you can generate <a href="https://viewer.shapez.io" target="_blank">here</a>)
titleEdit: Edit Marker
desc: Pojmenuj jí nějak výstižně, též ji můžeš doplnit <strong>zkratkou</strong> pro tvar (Kterou si můžete vytvořit <a href="https://viewer.shapez.io" target="_blank">zde</a>)
titleEdit: Upravit značku
markerDemoLimit:
desc: V ukázce můžete vytvořit pouze dvě značky. Získejte plnou verzi pro neomezený počet značek!
@ -252,8 +252,8 @@ dialogs:
může zejména u větších základen dlouho trvat, nebo dokonce shodit hru!
massCutInsufficientConfirm:
title: Confirm cut
desc: You can not afford to paste this area! Are you sure you want to cut it?
title: Potvrdit vyjmutí
desc: Nemůžeš si dovolit vložení této oblasti! Skutečně ji chceš vyjmout?
ingame:
# This is shown in the top left corner and displays useful keybindings in
@ -510,25 +510,25 @@ buildings:
description: Skladuje věci navíc až do naplnění kapacity. Může být použit na skladování surovin navíc.
wire:
default:
name: Energy Wire
description: Allows you to transport energy.
name: Kabel
description: Dovoluje přenos energie.
advanced_processor:
default:
name: Color Inverter
description: Accepts a color or shape and inverts it.
name: Invertor barev
description: Přijme barvu či tvar a převrátí jej.
energy_generator:
deliver: Deliver
toGenerateEnergy: For
deliver: Dodej
toGenerateEnergy: Pro
default:
name: Energy Generator
description: Generates energy by consuming shapes.
name: Generátor energie
description: Vyrábí energii zpracováním tvarů.
wire_crossings:
default:
name: Wire Splitter
description: Splits a energy wire into two.
name: Dělič kabelů
description: Rozdělí kabel na dva.
merger:
name: Wire Merger
description: Merges two energy wires into one.
name: Slučovač kabelů
description: Spojí dva kabely do jednoho.
storyRewards:
# Those are the rewards gained from completing the store
@ -543,7 +543,7 @@ storyRewards:
reward_painter:
title: Barvení
desc: >-
The <strong>painter</strong> has been unlocked - Extract some color veins (just as you do with shapes) and combine it with a shape in the painter to color them!<br><br>PS: If you are colorblind, there is a <strong>color blind mode</strong> in the settings!
<strong>Barvič</strong> byl právě odemčen - Vytěžte nějaká ložiska barev (podobně jako těžíte tvary) a spojte je s tvarem v barviči pro jeho obarvení!<br><br>PS: Pokud jste barvoslepý, v nastavení naleznete <strong>režim pro barvoslepé</strong>!
reward_mixer:
title: Míchání barev
@ -587,7 +587,7 @@ storyRewards:
desc: Odemknuli jste variantu <strong>barviče</strong> - Funguje stejně jako normální, ale nabarví <strong>dva tvary naráz</strong> pomocí jedné barvy!
reward_painter_quad:
title: Quad Painting
title: Čtyřstranné barvení
desc: Odemknuli jste variantu <strong>painter</strong> - Umožní vám nabarvit každou čtvrtinu tvaru jinou barvou!
reward_storage:
@ -616,9 +616,9 @@ storyRewards:
settings:
title: Nastavení
categories:
general: General
userInterface: User Interface
advanced: Advanced
general: Obecné
userInterface: Uživatelské rozhraní
advanced: Rozšířené
versionBadges:
dev: Vývojová verze

View File

@ -44,37 +44,38 @@ steamPage:
Nutze dein gesammeltes Wissen über die Maschinen und lasse deine Fabriken die gewünschten Formen der 18 verschiedenen Level abliefern. Schalte mit jedem Level neue Arbeitsschritte oder Gebäude frei. Das sollte dich schon für Stunden beschäftigt halten! Danach werden im Freispielmodus zufällige Formen generiert, die du ebenfalls abliefern kannst. Ich füge regelmäßig neue Funktionen hinzu und davon sind eine ganze Menge geplant!
Wenn du das Spiel erwirbst, erhälst du Zugriff auf die zusätzlichen Features der Standalone-Version. Das bedeutet, du kannst unter anderem die neuesten Updates zuerst spielen!
[b]Vorteile der Standalone[/b]
[list]
[*] Dark-Mode
[*] Unbegrenzte Wegpunkte
[*] Unbegrenzte Anzahl von Spielständen
[*] Weitere Einstellungen
[*] Es kommen: Mehr Levels
[*] Es kommen: Kabel & Energie! Voraussichtlich gegen Ende Juli 2020.
[*] Unterstütze die Entwicklung von shapez.io ❤️
[*] Dark Mode
[*] unbegrenzte Anzahl an Wegpunkten
[*] unbegrenzte Anzahl an Speicherständen
[*] zusätzliche Einstellungen
[*] Bald: Strom & Kabel! (Ungefähr) geplant für ende Juli 2020.
[*] Bald: mehr Level
[*] Erlaubt es mir shapez.io weiter zu entwickeln ❤️
[/list]
[b]Geplante Funktionen[/b]
[b]Zukünftige Updates:[/b]
Ich bin aktiv mit der Entwicklung beschäftigt und versuche jede Woche ein Update oder den aktuellen Stand der Entwicklung zu veröffentlichen.
Ich update das Spiel sehr oft, und versuche wöchentlich ein Update zu veröffentlichen!
[list]
[*] Verschiedene Karten und Herausforderungen (z.B. Karten mit Hindernissen)
[*] Puzzle (Liefere die gewünschten Formen mit begrenztem Platz / limitierten Gebäuden)
[*] Story-Modus mit Gebäudekosten
[*] Einstellbare Kartengenerierung (Ändere die Grösse/Anzahl/Dichte der Ressourcenflecken, den Seed und mehr)
[*] Mehr Formentypen
[*] Performanceverbesserungen (Das Spiel läuft bereits ganz gut!)
[*] Herausforderungen (liefere die geforderte Form mit einer beschränkten Karte / anzahl an Gebäuden ab)
[*] Eine Kampange, in der die Gebäude einen Preis haben.
[*] einen konfigurierbaren Kartengenerator (bestimme Ressourcen / Größe / Dichte, den Seed und viel mehr)
[*] zusätzliche Formen
[*] Performanceverbesserungen (Das Spiel läuft bereits sehr gut!)
[*] Und vieles mehr!
[/list]
[b] Dieses Spiel ist Open Source[/b]
[b]Das Spiel ist open source![/b]
Jeder kann dazu beitragen! Ich bin aktiv in die Community involviert, versuche alle Vorschläge zu lesen und beziehe so viel Feedback wie möglich mit in die Entwicklung ein.
Jeder kann dazu beitragen. Ich bin aktiv in der Communtiy involviert und versuche alle Vorschläge zu lesen und beziehe so viel Feedback wie möglich mit in die Entwicklung ein.
Die komplette Roadmap gibt es auf dem Trello-Board zum Nachlesen!
[b]Links [/b]
@ -83,6 +84,8 @@ steamPage:
[*] [url=https://discord.com/invite/HN7EVzV]Offizieller Discord[/url]
[*] [url=https://trello.com/b/ISQncpJP/shapezio]Roadmap[/url]
[*] [url=https://www.reddit.com/r/shapezio]Subreddit[/url]
[*] [url=https://github.com/tobspr/shapez.io]Source code (GitHub)[/url]
[*] [url=https://github.com/tobspr/shapez.io/blob/master/translations/README.md]Hilf zu übersetzen[/url]
[*] [url=https://github.com/tobspr/shapez.io]Quelltext (GitHub)[/url]
[*] [url=https://github.com/tobspr/shapez.io/blob/master/translations/README.md]Hilf beim Übersetzen[/url]
[/list]
@ -105,7 +108,7 @@ global:
trillions: T
# Shown for infinitely big numbers
infinite: unend
infinite:
time:
# Used for formatting past time dates
@ -141,9 +144,9 @@ demoBanners:
mainMenu:
play: Spielen
changelog: Änderungsprotokoll
continue: Fortsetzen
newGame: Neues Spiel
changelog: Änderungshistorie
subreddit: Reddit
importSavegame: Importieren
openSourceHint: Dieses Spiel ist Open Source!
@ -153,7 +156,7 @@ mainMenu:
# This is shown when using firefox and other browsers which are not supported.
browserWarning: >-
Sorry, aber das Spiel wird in deinem Browser langsam laufen! Erwerbe die Standalone-Version oder downloade Chrome für die beste Erfahrung!
Sorry, aber das Spiel wird in deinem Browser langsam laufen! Kaufe die Standalone-Version oder downloade Chrome für die beste Erfahrung!
savegameLevel: Level <x>
savegameLevelUnknown: Unbekanntes Level
@ -167,7 +170,7 @@ dialogs:
restart: Neustart
reset: Zurücksetzen
getStandalone: Standalone Ansehen
deleteGame: Ich weiß, was ich tue
deleteGame: Ich weiß, was ich tue!
viewUpdate: Update anzeigen
showUpgrades: Upgrades anzeigen
showKeybindings: Kürzel anzeigen
@ -200,15 +203,15 @@ dialogs:
restartRequired:
title: Neustart benötigt
text: >-
Du muss das Spiel neu starten, um die Einstellungen anzuwenden.
Du musst das Spiel neu starten, um die Einstellungen anzuwenden.
editKeybinding:
title: Tastenbelegung ändern
desc: Drücke die (Maus-)Taste, die du vergeben willst, oder ESC um abzubrechen.
desc: Drücke die (Maus-)Taste, die du belegen möchtest, oder ESC um abzubrechen.
resetKeybindingsConfirmation:
title: Tastenbelegung zurücksetzen
desc: Das wird alle deine Tastenbelegungen auf den Standard zurücksetzen. Bist du dir sicher?
desc: Dies wird alle deine Tastenbelegungen auf den Standard zurücksetzen. Bist du dir sicher?
keybindingsResetOk:
title: Tastenbelegung zurückgesetzt
@ -225,13 +228,13 @@ dialogs:
updateSummary:
title: Neues Update!
desc: >-
Hier sind die Änderungen, seit dem du das letzte Mal gespielt hast:
Hier sind die Änderungen, seitdem du das letzte Mal gespielt hast:
upgradesIntroduction:
title: Upgrades Freischalten
desc: >-
Viele deiner Formen können noch benutzt werden, um Upgrades freizuschalten - <strong>Zerstöre deine alten Fabriken nicht!</strong>
Den Upgrade-Tab kannst du oben rechts im Bildschirm finden.
Den Upgrade-Tab findest du oben rechts im Bildschirm.
massDeleteConfirm:
title: Löschen bestätigen
@ -245,13 +248,12 @@ dialogs:
massCutInsufficientConfirm:
title: Ausschneiden bestätigen
desc: >-
Du hast aktuell nicht genug Blaupausenformen, um die Auswahl einzufügen! Möchtest du sie trotzdem ausschneiden?
desc: Du kannst dir das Einfügen nicht leisten! Bist du sicher, dass du trotzdem Ausschneiden möchtest?
blueprintsNotUnlocked:
title: Noch nicht freigeschaltet
desc: >-
Blueprints werden erst in Level 12 freigeschaltet!
Blaupausen werden erst in Level 12 freigeschaltet!
keybindingsIntroduction:
title: Nützliche Hotkeys
@ -264,15 +266,16 @@ dialogs:
createMarker:
title: Neuer Marker
titleEdit: Edit Marker
desc: Gib ihm einen griffigen Namen. Du kannst sogar die <strong>Abkürzung</strong> einer Form eingeben (Diese kann <a href="https://viewer.shapez.io" target="_blank">hier</a> generiert werden).
titleEdit: Marker bearbeiten
markerDemoLimit:
desc: Du kannst nur 2 benutzerdefinierte Marker in der Demo benutzen. Hol dir die Standalone, um unendlich viele Marker zu erstellen!
desc: Du kannst nur 2 Marker in der Demo benutzen. Hol dir die Standalone, um unendlich viele Marker zu erstellen!
exportScreenshotWarning:
title: Bildschirmfoto exportieren
desc: Hier kannst du ein Bildschirmfoto von deiner ganzen Fabrik erstellen. Für extrem große Fabriken kann das jedoch sehr lange dauern und ggf. zum Spielabsturz führen!
desc: >-
Hier kannst du ein Bildschirmfoto von deiner ganzen Fabrik erstellen. Für extrem große Fabriken kann das jedoch sehr lange dauern und ggf. zum Spielabsturz führen!
ingame:
# This is shown in the top left corner and displays useful keybindings in
@ -363,7 +366,7 @@ ingame:
dataSources:
stored:
title: Gelagert
description: Zeigt die Menge an Formen, die im zentralen Gebäude gelagert sind.
description: Zeigt die Menge an Formen, die im Hub gelagert sind.
produced:
title: Produziert
description: Zeigt die Menge an Formen, die deine gesamte Fabrik produziert (inkl. Zwischenprodukte).
@ -400,7 +403,7 @@ ingame:
# Map markers
waypoints:
waypoints: Markierungen
hub: HUB
hub: Hub
description: Linksklick auf einen Marker, um dort hinzugelangen, Rechtsklick, um ihn zu löschen.<br><br>Drücke <keybinding> um einen Marker aus deinem Blickwinkel, oder <strong>rechtsklicke</strong>, um einen Marker auf der ausgewählten Position zu erschaffen.
creationSuccessNotification: Marker wurde erstellt.
@ -416,7 +419,7 @@ ingame:
hints:
1_1_extractor: Platziere einen <strong>Extrahierer</strong> auf der <strong>Kreisform</strong> um sie zu extrahieren!
1_2_conveyor: >-
Verbinde den Extrahierer mit einem <strong>Förderband</strong> und schließe ihn am zentralen Gebäude an!<br><br>Tipp: <strong>Drück und ziehe</strong> das Förderband mit der Maus!
Verbinde den Extrahierer mit einem <strong>Förderband</strong> und schließe ihn am Hub an!<br><br>Tipp: <strong>Drück und ziehe</strong> das Förderband mit der Maus!
1_3_expand: >-
Dies ist <strong>KEIN</strong> Idle-Game! Baue mehr Extrahierer und Förderbänder, um das Ziel schneller zu erreichen.<br><br>Tipp: Halte <strong>UMSCH</strong>, um mehrere Gebäude zu platzieren und nutze <strong>R</strong> um sie zu rotieren.
@ -493,14 +496,14 @@ buildings:
rotater:
default:
name: &rotater Rotierer
name: &rotater Rotierer (-90°)
description: Rotiert Formen im Uhrzeigersinn um 90 Grad.
ccw:
name: Rotierer (CCW)
name: Rotierer (+90°)
description: Rotiert Formen gegen den Uhrzeigersinn um 90 Grad.
fl:
name: Rotierer (180)
description: Rotiert Formen um 180 Grad.
name: Rotierer (+180°)
description: Rotiert die Formen um 180 Grad.
stacker:
default:
@ -540,25 +543,25 @@ buildings:
wire:
default:
name: Energiekabel
description: Transportiert Energie.
name: Stromkabel
description: Erlaubt dir Strom zu transportieren.
advanced_processor:
default:
name: Farbinvertierer
description: Akzeptiert Farben und Formen und invertiert sie.
description: Invertiert die Farbe. Geht auch bei Formen.
energy_generator:
deliver: Liefere
toGenerateEnergy: für
default:
name: Energiegenerator
description: Generiert Energie, indem die Formen verbraucht werden.
name: Stromgenerator
description: Erzeugt Strom, indem er Formen verbraucht.
wire_crossings:
default:
name: Kabelverteiler
description: Teilt ein Energiekabel in zwei Ausgänge.
description: Teilt ein Stromkabel in zwei auf.
merger:
name: Kabelverbinder
description: Verbindet zwei Energiekabel zu einem.
description: Verbindet zwei Stromkabel zu einem.
storyRewards:
# Those are the rewards gained from completing the store
@ -573,7 +576,7 @@ storyRewards:
reward_painter:
title: Färben
desc: >-
The <strong>painter</strong> has been unlocked - Extract some color veins (just as you do with shapes) and combine it with a shape in the painter to color them!<br><br>PS: If you are colorblind, there is a <strong>color blind mode</strong> in the settings!
Der <strong>Färber</strong> wurde freigeschaltet. Extrahiere ein paar Farben (genauso wie bei Formen) und färbe damit eine Form im Färber!<br><br>PS: Falls du Farbenblind bist, es gibt einen <strong>Modus für Farbenblinde</strong> in den Einstellungen!
reward_mixer:
title: Farben mischen
@ -626,7 +629,7 @@ storyRewards:
reward_freeplay:
title: Freies Spiel
desc: Du hast es geschafft! Du hast den <strong>Freispielmodus</strong> freigeschaltet! Das heißt, dass abzuliefernde Formen jetzt zufällig generiert werden! (Keine Sorge, für die Standaloneversion ist noch mehr geplant!)
desc: Du hast es geschafft! Du bist im <strong>freien Spiel</strong> angekommen! Das heißt, dass abzuliefernde Formen jetzt zufällig generiert werden! (Keine Sorge, für die Standaloneversion ist noch mehr geplant!)
reward_blueprints:
title: Blaupause
@ -636,7 +639,7 @@ storyRewards:
no_reward:
title: Nächstes Level
desc: >-
Dieses Level hat dir keine Belohnung gegeben, aber das nächste schon! <br><br> PS: Denk daran, deine alten Fabriken nicht zu zerstören - Du wirst sie später <strong>alle</strong> noch brauchen, um <strong>Upgrades freizuschalten</strong>!
Dieses Level hat dir keine Belohnung gegeben, aber dafür das Nächste schon! <br><br> PS: Denk daran, deine alten Fabriken nicht zu zerstören - Du wirst sie später <strong>alle</strong> noch brauchen, um <strong>Upgrades freizuschalten</strong>!
no_reward_freeplay:
title: Nächstes Level
@ -684,7 +687,7 @@ settings:
scrollWheelSensitivity:
title: Zoomempfindlichkeit
description: >-
Ändert die Sensitivität des Zooms (Sowohl Mausrad, als auch Trackpad).
Ändert die Empfindlichkeit des Zooms (Sowohl Mausrad, als auch Trackpad).
sensitivity:
super_slow: Sehr langsam
slow: Langsam
@ -722,30 +725,30 @@ settings:
soundsMuted:
title: Geräusche stummschalten
description: >-
Bei Aktivierung werden alle Geräusche stummgeschaltet.
Bei der Aktivierung werden alle Geräusche stummgeschaltet.
musicMuted:
title: Musik stummschalten
description: >-
Bei Aktivierung wird die Musik stummgeschaltet.
Bei der Aktivierung wird die Musik stummgeschaltet.
theme:
title: Farbmodus
description: >-
Wähle zwischen dunklem und hellem Farbmodus.
Wähle zwischen dem dunklen und dem hellen Farbmodus.
themes:
dark: Dunkel
light: Hell
refreshRate:
title: Zielbildwiederholrate
title: Tickrate
description: >-
Für z.B. einen 144-Hz-Monitor kann die Bildwiederholrate hier korrekt eingestellt werden. Bei einem zu langsamen Computer kann dies die Leistung beeinträchtigen.
Das Spiel passt die Tickrate automatisch so an, dass sie immer zwischen diesem Wert und der hälfte bleibt. Zum Beispiel bei einer Tickrate von 60 Hz versucht das Spiel, diese zu halten. Falls dies zu viel ist, regelt der Computer diese runter bis zu einer Untergrenze von 30Hz.
alwaysMultiplace:
title: Mehrfachplatzierung
description: >-
Bei Aktivierung wird das platzierte Gebäude nicht abgewählt. Das hat den gleichen Effekt wie beim Platzieren permanent UMSCH gedrückt zu halten.
Bei Aktivierung wird das platzierte Gebäude nicht abgewählt. Das hat den gleichen Effekt wie beim Platzieren UMSCH gedrückt zu halten.
offerHints:
title: Hinweise & Tutorials
@ -762,11 +765,6 @@ settings:
description: >-
Aktiviert den Vignetteneffekt, der den Rand des Bildschirms zunehmend verdunkelt und das Lesen der Textfelder vereinfacht.
rotationByBuilding:
title: Rotation pro Gebäudetyp
description: >-
Jeder Gebäudetyp merkt sich einzeln, welche Rotation ausgewählt ist. Das fühlt sich möglicherweise besser an, wenn du häufig zwischen verschiedenen Gebäudetypen wechselst.
compactBuildingInfo:
title: Kompakte Gebäudeinformationen
description: >-
@ -777,6 +775,13 @@ settings:
description: >-
Deaktiviert die Warnung, die beim Löschen und Ausschneiden von mehr als 100 Feldern angezeigt wird.
rotationByBuilding:
title: Rotation pro Gebäudetyp
description: >-
Jeder Gebäudetyp merkt sich einzeln, in welche Richtung er zeigt.
Das fühlt sich möglicherweise besser an, wenn du häufig zwischen verschiedenen
Gebäudetypen wechselst.
keybindings:
title: Tastenbelegung
hint: >-
@ -785,7 +790,7 @@ keybindings:
resetKeybindings: Tastenbelegung zurücksetzen.
categoryLabels:
general: Applikation
general: Anwendung
ingame: Spiel
navigation: Navigation
placement: Platzierung
@ -803,8 +808,8 @@ keybindings:
mapMoveFaster: Schneller bewegen
centerMap: Karte zentrieren
mapZoomIn: Hineinzoomen
mapZoomOut: Herauszoomen
mapZoomIn: Reinzoomen
mapZoomOut: Rauszoomen
createMarker: Markierung erstellen
menuOpenShop: Upgrades
@ -832,7 +837,6 @@ keybindings:
Modifikator: stattdessen gegen den UZS rotieren
cycleBuildingVariants: Variante wählen
confirmMassDelete: Massenlöschung bestätigen
pasteLastBlueprint: Letzte Blaupause einfügen
cycleBuildings: Gebäude rotieren
lockBeltDirection: Bandplaner aktivieren
switchDirectionLockSide: >-
@ -846,8 +850,10 @@ keybindings:
placementDisableAutoOrientation: Automatische Orientierung deaktivieren
placeMultiple: Im Platziermodus bleiben
placeInverse: Automatische Förderbandorientierung invertieren
advanced_processor: Farbnivertierer
energy_generator: Energiegenerator
pasteLastBlueprint: Letzte Blaupause einfügen
advanced_processor: Farbinvertierer
energy_generator: Stromgenerator
wire: Stromkabel
about:
title: Über dieses Spiel

File diff suppressed because it is too large Load Diff

View File

@ -488,8 +488,8 @@ buildings:
name: Pivoteur inversé
description: Fait pivoter une forme de 90 degrés vers la gauche.
fl:
name: Pivoteur (180)
description: Fait pivoter les formes de 90 degrés.
name: Retourneur
description: Tourne la forme de 180 degrés.
stacker:
default:
@ -635,9 +635,9 @@ storyRewards:
settings:
title: Options
categories:
general: General
userInterface: User Interface
advanced: Advanced
general: Général
userInterface: Interface Utilisateur
advanced: Avancé
versionBadges:
dev: Développement

View File

@ -22,7 +22,7 @@
---
steamPage:
# This is the short text appearing on the steam page
shortText: shapez.io is a game about building factories to automate the creation and combination of increasingly complex shapes within an infinite map.
shortText: shapez.io giderek karmaşıklaşan şekillerin sonsuz bir harita üzerinde üretimi ve birleştirilmesi hakında bir oyundur.
# This is the long description for the steam page - It is contained here so you can help to translate it, and I will regulary update the store page.
# NOTICE:
@ -31,56 +31,57 @@ steamPage:
longText: >-
[img]{STEAM_APP_IMAGE}/extras/store_page_gif.gif[/img]
shapez.io is a game about building factories to automate the creation and processing of increasingly complex shapes across an infinitely expanding map.
Upon delivering the requested shapes you will progress within the game and unlock upgrades to Hız up your factory.
shapez.io giderek karmaşıklaşan şekillerin sonsuz bir harita üzerinde üretimi ve birleştirilmesi hakında bir oyundur.
Talep edilen şekilleri verdikten sonra oyundaki geliştirmeleri açıp fabrikanızı hızlandırabilirsiniz.
As the demand for shapes increases, you will have to scale up your factory to meet the demand - Don't forget about resources though, you will have to expand across the [b]infinite map[/b]!
Şekiller için talep artınca fabrikanı büyütüp talebi karşılamalısın - Kaynakları unutma! Sonsuz [b]sonsuz haritada[/b] genişlemen gerekecek!
Soon you will have to mix colors and paint your shapes with them - Combine red, green and blue color resources to produce different colors and paint shapes with it to satisfy the demand.
Yakında renkleri karıştırman ve şekileri boyaman gerekecek - Talebi karşılamak için kırmızı, mavi ve yeşili karıştırıp şekilleri boyacaksın
This game features 18 progressive levels (Which should keep you busy for hours already!) but I'm constantly adding new content - There is a lot planned!
Bu oyun 18 kademeli seviye içerir (Seni saatlerce meşgul tutumalı) ama sürekli yeni şeyler ekliyorum - Ekleyecek çok şey var!
Purchasing the game gives you access to the standalone version which has additional features and you'll also receive access to newly developed features.
Bu oyunu satın almak indirilebilir versiyonuna (Ek özellikler var) ve yeni özeliklerine erişebileceksiniz.
[b]Standalone Advantages[/b]
[b]İndirebilir versiyonun avantajları[/b]
[list]
[*] Dark Mode
[*] Unlimited Waypoints
[*] Unlimited Savegames
[*] Additional settings
[*] Coming soon: Wires & Energy! Aiming for (roughly) end of July 2020.
[*] Coming soon: More Levels
[*] Allows me to further develop shapez.io ❤️
[*] Karanlık mod
[*] Sonsuz işaret
[*] Sonsuz kayıt alanı
[*] Ek ayarlar
[*] Yakında geliyor: Kablo ve enerji! Temmuz sonunu hedefliyorum.
[*] Yakında geliyor: Daha fazla seviyeler
[*] Shapez.io'yu geliştirmeme izin veriyor ❤️
[/list]
[b]Future Updates[/b]
[b]Gelecek güncellemeler[/b]
I am updating the game very often and trying to push an update at least every week!
Oyunu sık sık güncelliyorum ve en az haftada bir güncellemeye çalışıyorum!
[list]
[*] Different maps and challenges (e.g. maps with obstacles)
[*] Puzzles (Deliver the requested shape with a restricted area / set of buildings)
[*] A story mode where buildings have a cost
[*] Configurable map generator (Configure resource/shape size/density, seed and more)
[*] Additional types of shapes
[*] Performance improvements (The game already runs pretty well!)
[*] And much more!
[*] Farklı haritalar ve görevler (Örneğin engelli haritalar)
[*] Yapbozlar (İstenen şekilleri kısıtlı bir alanda / belli yapılar ile)
[*] Hikaye modu ile yapıların maliyeti olacak.
[*] Ayarlanabilir harita yapımı(Ayarlanabilir kaynak/şekil boyut/sıklığı, seedler ve daha fazlası)
[*] Ek şekiller
[*] Performans optimizasyonları (oyun zaten iyi çalışıyor)
[*] Ve daha fazlası
[/list]
[b]This game is open source![/b]
[b]Bu oyun açık kaynaklı![/b]
Anybody can contribute, I'm actively involved in the community and attempt to review all suggestions and take feedback into consideration where possible.
Be sure to check out my trello board for the full roadmap!
Bu oyuna herkes katkıda bulunabilir! Aktif olarak toplulukğa katkıda bulunuyorum ve bütün önerileri gözden geçirmeye çalışıyorum.
Yol planıma Trello'dan bakmayı unutmayın!
[b]Links[/b]
[list]
[*] [url=https://discord.com/invite/HN7EVzV]Official Discord[/url]
[*] [url=https://trello.com/b/ISQncpJP/shapezio]Roadmap[/url]
[*] [url=https://discord.com/invite/HN7EVzV]Dİscord'umuz[/url]
[*] [url=https://trello.com/b/ISQncpJP/shapezio]yol planı[/url]
[*] [url=https://www.reddit.com/r/shapezio]Subreddit[/url]
[*] [url=https://github.com/tobspr/shapez.io]Source code (GitHub)[/url]
[*] [url=https://github.com/tobspr/shapez.io/blob/master/translations/README.md]Help translate[/url]
[*] [url=https://github.com/tobspr/shapez.io]KAynak kodu (GitHub)[/url]
[*] [url=https://github.com/tobspr/shapez.io/blob/master/translations/README.md]Çevirmeye yardımcı olun[/url]
[/list]
discordLink: Official Discord - Chat with me!