From 9de4738dbdd6e259ecac9755ae3411b1106cea2b Mon Sep 17 00:00:00 2001 From: = Date: Wed, 4 Dec 2024 14:17:32 -0300 Subject: [PATCH 01/67] it can connect --- src/omaloon/content/OlUnitTypes.java | 1 + src/omaloon/entities/comp/MillipedeComp.java | 31 ++++++++++---------- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/src/omaloon/content/OlUnitTypes.java b/src/omaloon/content/OlUnitTypes.java index ac0c731b..98e4a9a8 100644 --- a/src/omaloon/content/OlUnitTypes.java +++ b/src/omaloon/content/OlUnitTypes.java @@ -55,6 +55,7 @@ public static void load() { health = 200f; regenTime = 15f * 60f; chainable = true; + splittable = true; omniMovement = false; angleLimit = 65f; segmentLength = 5; diff --git a/src/omaloon/entities/comp/MillipedeComp.java b/src/omaloon/entities/comp/MillipedeComp.java index 823b6aa3..87ad212f 100644 --- a/src/omaloon/entities/comp/MillipedeComp.java +++ b/src/omaloon/entities/comp/MillipedeComp.java @@ -147,31 +147,30 @@ public int cap(){ return Math.max(Units.getCap(team), Units.getCap(team) * max); } - //TODO WHY DOES IT NOT SHOW UP ON THE UNIT CODE - /*boolean canJoin(Millipedec other) { + boolean canJoin(Unit other) { + if (!(other instanceof Millipedec snek)) return false; MillipedeUnitType uType = (MillipedeUnitType)type; - return uType == other.type() && other.countAll() + countAll() <= uType.maxSegments; - }*/ + return uType == other.type() && snek.countAll() + countAll() <= uType.maxSegments; + } - // TODO make private - public void connect(Millipedec other){ - if(isHead() && other.isTail()){ + public void connect(Unit other){ + if(other instanceof Millipedec snek && isHead() && snek.isTail()){ MillipedeUnitType uType = (MillipedeUnitType) type; - float z = other.layer() + uType.segmentLayerOffset; + float z = snek.layer() + uType.segmentLayerOffset; distributeActionBack(u -> { u.layer(z); - u.head(other.head()); + u.head(snek.head()); }); - other.child(self()); - parent = (Unit)other; - head = other.head(); - setupWeapons(type); + snek.child(self()); + parent = other; + head = snek.head(); + ((Millipedec) head).distributeActionBack(u -> u.setupWeapons(type)); uType.chainSound.at(self()); if(controller() instanceof Player){ UnitController con = controller(); - other.head().controller(con); - con.unit(other.head()); + snek.head().controller(con); + con.unit(snek.head()); controller(type.createController(self())); } } @@ -558,7 +557,7 @@ private void updatePost(){ Tmp.r1.setCentered(Tmp.v1.x, Tmp.v1.y, hitSize()); Units.nearby(Tmp.r1, u -> { if(u.team == team && u.type == type && u instanceof Millipedec m && m.head() != self() && m.isTail() && m.countForward() + countBackward() < uType.maxSegments && m.waitTime() <= 0f && within(u, uType.segmentOffset) && OlUtils.angleDist(rotation(), angleTo(u)) < uType.angleLimit){ - connect(m); + connect(u); } }); scanTime = 0f; From b3138ecd2dead630a3c88471203ede3634b0b644 Mon Sep 17 00:00:00 2001 From: = Date: Wed, 4 Dec 2024 23:10:47 -0300 Subject: [PATCH 02/67] add liquids to the system --- src/omaloon/world/meta/PressureConfig.java | 57 ++++++++++++++----- src/omaloon/world/modules/PressureModule.java | 56 +++++++++++++++++- 2 files changed, 97 insertions(+), 16 deletions(-) diff --git a/src/omaloon/world/meta/PressureConfig.java b/src/omaloon/world/meta/PressureConfig.java index 5abfa518..d20b55af 100644 --- a/src/omaloon/world/meta/PressureConfig.java +++ b/src/omaloon/world/meta/PressureConfig.java @@ -1,13 +1,11 @@ package omaloon.world.meta; import arc.*; -import arc.graphics.Color; +import arc.graphics.*; import arc.math.*; import arc.struct.*; -import arc.util.*; -import mindustry.gen.Building; -import mindustry.graphics.*; -import mindustry.type.Liquid; +import mindustry.gen.*; +import mindustry.type.*; import mindustry.ui.*; import mindustry.world.*; import mindustry.world.meta.*; @@ -15,19 +13,24 @@ import omaloon.world.interfaces.*; public class PressureConfig { - public boolean - acceptsPressure = true, - outputsPressure = true, + public boolean acceptsPressure = true; + public boolean outputsPressure = true; /** * Determines whether linkList will function as a whitelist */ - isWhitelist = false; + public boolean isWhitelist = false; + public float overPressureDamage = 0.33f, underPressureDamage = 0.66f, maxPressure = 50, minPressure = -50f; + /** + * Standard capacity for this block. Does not define max amount that this can hold. That is defined by maxPressure and minPressure. + */ + public float fluidCapacity = 5; + /** * List of blocks that are allowed/disallowed (depends on isWhitelist true/false) for pressure connections. *

@@ -58,11 +61,33 @@ public void addStats(Stats stats) { public void addBars(Block block) { block.removeBar("liquid"); +// block.addBar("pressure-liquid", (Building entity) -> new Bar( +// () -> { +// HasPressure build = (HasPressure)entity; +// Liquid current = entity.liquids != null ? entity.liquids.current() : null; +// String liquidName = (current == null || entity.liquids.get(current) <= 0.001f) +// ? Core.bundle.get("bar.air") +// : current.localizedName; +// +// return Core.bundle.format("bar.pressure-liquid", +// liquidName, +// Mathf.round(build.getPressure(), 1), +// Mathf.round(build.getPressure() > 0 ? build.pressureConfig().maxPressure : build.pressureConfig().minPressure, 1)); +// }, +// () -> { +// Liquid current = entity.liquids != null ? entity.liquids.current() : null; +// return current != null && entity.liquids.get(current) > 0.001f ? current.color : Color.lightGray; +// }, +// () -> { +// Liquid current = entity.liquids != null ? entity.liquids.current() : null; +// return current != null ? entity.liquids.get(current) / block.liquidCapacity : 0f; +// } +// )); block.addBar("pressure-liquid", (Building entity) -> new Bar( () -> { HasPressure build = (HasPressure)entity; - Liquid current = entity.liquids != null ? entity.liquids.current() : null; - String liquidName = (current == null || entity.liquids.get(current) <= 0.001f) + Liquid current = build.pressure().current; + String liquidName = (current == null || build.pressure().liquids[current.id] < 0.01f) ? Core.bundle.get("bar.air") : current.localizedName; @@ -72,12 +97,14 @@ public void addBars(Block block) { Mathf.round(build.getPressure() > 0 ? build.pressureConfig().maxPressure : build.pressureConfig().minPressure, 1)); }, () -> { - Liquid current = entity.liquids != null ? entity.liquids.current() : null; - return current != null && entity.liquids.get(current) > 0.001f ? current.color : Color.lightGray; + HasPressure build = (HasPressure)entity; + Liquid current = build.pressure().current; + return current != null && build.pressure().liquids[current.id] > 0.001f ? current.color : Color.lightGray; }, () -> { - Liquid current = entity.liquids != null ? entity.liquids.current() : null; - return current != null ? entity.liquids.get(current) / block.liquidCapacity : 0f; + HasPressure build = (HasPressure)entity; + Liquid current = build.pressure().current; + return current != null ? Mathf.clamp(build.pressure().currentAmount()/(build.pressure().currentAmount() + build.pressure().air)) : 0; } )); } diff --git a/src/omaloon/world/modules/PressureModule.java b/src/omaloon/world/modules/PressureModule.java index 3fca25f1..11162825 100644 --- a/src/omaloon/world/modules/PressureModule.java +++ b/src/omaloon/world/modules/PressureModule.java @@ -1,15 +1,69 @@ package omaloon.world.modules; +import arc.math.*; +import arc.util.*; import arc.util.io.*; +import mindustry.*; +import mindustry.type.*; import mindustry.world.modules.*; +import omaloon.world.meta.*; public class PressureModule extends BlockModule { - public float pressure; + public static float arbitraryPressureScalar = 10f; + + public float[] liquids = new float[Vars.content.liquids().size]; + public float[] pressures = new float[Vars.content.liquids().size]; + public float air = 0, pressure = 0; + + public @Nullable Liquid current; + + /** + * Adds a certain amount of a fluid into this module, updating it's pressure accordingly. A null liquid means that air is being added to it. + */ + public void addFluid(@Nullable Liquid liquid, float amount, PressureConfig reference) { + if (liquid == null) { + air += amount; + pressure = air / reference.fluidCapacity * arbitraryPressureScalar; + } else { + liquids[liquid.id] += amount; + pressures[liquid.id] = liquids[liquid.id] / reference.fluidCapacity * arbitraryPressureScalar; + } + current = liquid; + } + + public float currentAmount() { + return current == null ? air : liquids[current.id]; + } + + /** + * Returns the amount of pressure felt by this module from a certain liquid + the pressure of air inside this module. + */ + public float getPressure(@Nullable Liquid liquid) { + if (liquid == null) { + return pressure; + } + return pressures[liquid.id] + pressure; + } @Override public void read(Reads read) { pressure = read.f(); } + + /** + * Removes a certain amount of a fluid from this module, updating pressure accordingly. A null liquid means that air is being removed from it. Liquids cannot be negative. + */ + public void removeFluid(@Nullable Liquid liquid, float amount, PressureConfig reference) { + if (liquid == null) { + air -= amount; + pressure = air / reference.fluidCapacity * arbitraryPressureScalar; + } else { + liquids[liquid.id] = Mathf.maxZero(liquids[liquid.id] - amount); + pressures[liquid.id] = liquids[liquid.id] / reference.fluidCapacity * arbitraryPressureScalar; + } + current = liquid; + } + @Override public void write(Writes write) { write.f(pressure); From 38c10cdd4153eced9cef1013f8385a3de304ee5d Mon Sep 17 00:00:00 2001 From: = Date: Wed, 4 Dec 2024 23:57:44 -0300 Subject: [PATCH 03/67] too lazy to change the bar today --- src/omaloon/world/meta/PressureConfig.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/omaloon/world/meta/PressureConfig.java b/src/omaloon/world/meta/PressureConfig.java index d20b55af..e3691cde 100644 --- a/src/omaloon/world/meta/PressureConfig.java +++ b/src/omaloon/world/meta/PressureConfig.java @@ -93,13 +93,14 @@ public void addBars(Block block) { return Core.bundle.format("bar.pressure-liquid", liquidName, - Mathf.round(build.getPressure(), 1), - Mathf.round(build.getPressure() > 0 ? build.pressureConfig().maxPressure : build.pressureConfig().minPressure, 1)); + Mathf.round(build.pressure().currentAmount(), 1), + Mathf.round(build.pressure().getPressure(build.pressure().current), 1) + ); }, () -> { HasPressure build = (HasPressure)entity; Liquid current = build.pressure().current; - return current != null && build.pressure().liquids[current.id] > 0.001f ? current.color : Color.lightGray; + return current != null ? current.color : Color.lightGray; }, () -> { HasPressure build = (HasPressure)entity; From 32300e7b25ac25fb4f64fc6caf60c00ea361eaea Mon Sep 17 00:00:00 2001 From: = Date: Thu, 5 Dec 2024 17:08:49 -0300 Subject: [PATCH 04/67] changed the bar --- assets/bundles/bundle.properties | 4 ++-- src/omaloon/world/meta/PressureConfig.java | 18 ++++++++---------- src/omaloon/world/modules/PressureModule.java | 9 +++++++++ 3 files changed, 19 insertions(+), 12 deletions(-) diff --git a/assets/bundles/bundle.properties b/assets/bundles/bundle.properties index 3642da77..02063947 100644 --- a/assets/bundles/bundle.properties +++ b/assets/bundles/bundle.properties @@ -339,8 +339,8 @@ stat.omaloon-pressurerange.format = from \uC357 @ pressure units to \uC357 @ pre ## ui units unit.omaloon-pressuresecond = pressure units / second unit.omaloon-pressureunits = pressure units -bar.air = Air -bar.pressure-liquid = {0} (\uC357 {1}/{2}) +bar.air = Air: +bar.pressure-liquid = ({0}: {1} / Air: {2}) bar.hail-shield-health = Individual Shelter omaloon-source-negative = Negative diff --git a/src/omaloon/world/meta/PressureConfig.java b/src/omaloon/world/meta/PressureConfig.java index e3691cde..395b5ff2 100644 --- a/src/omaloon/world/meta/PressureConfig.java +++ b/src/omaloon/world/meta/PressureConfig.java @@ -86,26 +86,24 @@ public void addBars(Block block) { block.addBar("pressure-liquid", (Building entity) -> new Bar( () -> { HasPressure build = (HasPressure)entity; - Liquid current = build.pressure().current; - String liquidName = (current == null || build.pressure().liquids[current.id] < 0.01f) - ? Core.bundle.get("bar.air") - : current.localizedName; + Liquid current = build.pressure().getMain(); + if (current == null) return Core.bundle.get("bar.air") + Mathf.round(build.pressure().air, 1); return Core.bundle.format("bar.pressure-liquid", - liquidName, - Mathf.round(build.pressure().currentAmount(), 1), - Mathf.round(build.pressure().getPressure(build.pressure().current), 1) + current.localizedName, + Mathf.round(build.pressure().liquids[current.id], 1), + Mathf.round(build.pressure().air, 1) ); }, () -> { HasPressure build = (HasPressure)entity; - Liquid current = build.pressure().current; + Liquid current = build.pressure().getMain(); return current != null ? current.color : Color.lightGray; }, () -> { HasPressure build = (HasPressure)entity; - Liquid current = build.pressure().current; - return current != null ? Mathf.clamp(build.pressure().currentAmount()/(build.pressure().currentAmount() + build.pressure().air)) : 0; + Liquid current = build.pressure().getMain(); + return current != null ? Mathf.clamp(build.pressure().liquids[current.id]/(build.pressure().liquids[current.id] + build.pressure().air)) : 0; } )); } diff --git a/src/omaloon/world/modules/PressureModule.java b/src/omaloon/world/modules/PressureModule.java index 11162825..ea775af7 100644 --- a/src/omaloon/world/modules/PressureModule.java +++ b/src/omaloon/world/modules/PressureModule.java @@ -35,6 +35,15 @@ public float currentAmount() { return current == null ? air : liquids[current.id]; } + public @Nullable Liquid getMain() { + Liquid out = null; + for(int i = 0; i < liquids.length; i++) { + if (out == null && liquids[i] > 0) out = Vars.content.liquid(i); + if (out != null && liquids[i] > liquids[out.id]) out = Vars.content.liquid(i); + } + return out; + } + /** * Returns the amount of pressure felt by this module from a certain liquid + the pressure of air inside this module. */ From d25cfbce998655b07f5751a15d0a28ee2ba17225 Mon Sep 17 00:00:00 2001 From: = Date: Thu, 5 Dec 2024 23:19:11 -0300 Subject: [PATCH 05/67] not fully tested gauger --- assets/bundles/bundle.properties | 4 + .../blocks/liquids/liquid-gauge-pointer.png | Bin 0 -> 161 bytes .../blocks/liquids/liquid-gauge-tiles.png | Bin 0 -> 1029 bytes .../sprites/blocks/liquids/liquid-gauge.png | Bin 0 -> 450 bytes .../content/blocks/OlDistributionBlocks.java | 13 +- src/omaloon/ui/elements/CenterBar.java | 130 ++++++++++++++ .../blocks/liquid/PressureLiquidGauge.java | 158 ++++++++++++++++++ src/omaloon/world/interfaces/HasPressure.java | 6 +- src/omaloon/world/meta/PressureSection.java | 28 ++++ src/omaloon/world/modules/PressureModule.java | 6 +- 10 files changed, 338 insertions(+), 7 deletions(-) create mode 100644 assets/sprites/blocks/liquids/liquid-gauge-pointer.png create mode 100644 assets/sprites/blocks/liquids/liquid-gauge-tiles.png create mode 100644 assets/sprites/blocks/liquids/liquid-gauge.png create mode 100644 src/omaloon/ui/elements/CenterBar.java create mode 100644 src/omaloon/world/blocks/liquid/PressureLiquidGauge.java create mode 100644 src/omaloon/world/meta/PressureSection.java diff --git a/assets/bundles/bundle.properties b/assets/bundles/bundle.properties index 02063947..24801afb 100644 --- a/assets/bundles/bundle.properties +++ b/assets/bundles/bundle.properties @@ -273,6 +273,9 @@ block.omaloon-liquid-junction.description = Acts as a bridge for two crossing li block.omaloon-liquid-valve.name = Liquid Valve block.omaloon-liquid-valve.description = Equalizes fluid systems pressure to -15 pressure units. Jams when the pressure decreases too fast. +block.omaloon-liquid-gauge.name = Liquid Gauge +block.omaloon-liquid-gauge.description = Displays the amount of pressure inside it. + block.omaloon-liquid-bridge.name = Liquid Bridge block.omaloon-liquid-bridge.description = Transports liquids over terrain or buildings. @@ -340,6 +343,7 @@ stat.omaloon-pressurerange.format = from \uC357 @ pressure units to \uC357 @ pre unit.omaloon-pressuresecond = pressure units / second unit.omaloon-pressureunits = pressure units bar.air = Air: +bar.pressure = Pressure: bar.pressure-liquid = ({0}: {1} / Air: {2}) bar.hail-shield-health = Individual Shelter omaloon-source-negative = Negative diff --git a/assets/sprites/blocks/liquids/liquid-gauge-pointer.png b/assets/sprites/blocks/liquids/liquid-gauge-pointer.png new file mode 100644 index 0000000000000000000000000000000000000000..7106ec85012f7eb4eb47835d7498a24ed7f4e45a GIT binary patch literal 161 zcmeAS@N?(olHy`uVBq!ia0vp^3LwnE1|*BCs=fdz&H|6fVg?3oVGw3ym^DWNC>ZSN z;usRq`u2*U5Q6}ZOJL!DYxlDTGj*CD?T^|Ny+DNFK=LxaUAxP>&n$_(bU|WYu#)Wt zu5fQ3es{%(ms~n`370Uj{@c@%)v0~HAk^t^2Lr=-)5q&&_;OReo&p-r;OXk;vd$@? F2>^LdGrj-- literal 0 HcmV?d00001 diff --git a/assets/sprites/blocks/liquids/liquid-gauge-tiles.png b/assets/sprites/blocks/liquids/liquid-gauge-tiles.png new file mode 100644 index 0000000000000000000000000000000000000000..5b0474f5a2c2cc189d72053be34c290062697cd2 GIT binary patch literal 1029 zcmV+g1p51lP)$pl51oozZtkBH=r;r%vjjH< znLBp5pD^+z?c`LEN%4`CEaPwl0>q9izQ~kBKD~i5I~{-j&F|H;m)EBuy}r9>?VJN~ z`?8kv9K_JWc?x1coKM$@h=_I%JE&tz`!8r``S)7wivYL|N}XEU6A_J;&SpElo!I-2 z`@Ptg^g7rPC^`T0{_grs>T?0W>)Z=M4MK}^Pg`~x=192?^Y@Lk;o^WDfwUpgv2-te z))a*E1E_NiL}@{SV?c9mY2yaa!iMLs-^IP)_1nwcHL|o4E#J4aa1m`_1WW*s-3{F_ zRRE9sJv-zj2i$Mdbt(oX3m|;}1tB@-`b=#Rgi=H6&`JTDuPty4pfkYQb^*Y%rJ`-P zzS$A*g79qR#f32%3hHqi9BCCaJ9TehCEk zd{=(p2B0U1F8qK9pa%%3Hmqs6eqi-{ApgT%5|R`|w~S~8!N!2K_{=S&A1Ix0AbWgB zKY*NYlt6g&1H;cBzr<-M4WVb-bsgPWoD)^j4|tt>L5$HnPXd9SAwx+i=Un3lI1sRY z!0KGO7t#+{oNFM8B-M1CX#QySA@u`yL6{G@mmkQV+q8aQwD5nm_<_{SvtSkdfCof1 z{eWa>GQv4eEq~>swt~%ed^?#lBE(dRCI=C54(kWJAj0|qWcMn82Hrq{fu0A~L>tHlJ^`?WNt7Q5=?9|xKuA9j z|0AMiT&f`C^-3qL><)DIxeo9YLw&ZT=H{eZ=J1jLw55v{KK zkotix{J^&K13mZw_~5bzKj6|2ctCjd1I_pWbm?ZdW9#8G>KxJ!NDWIJd!35_ydc8* zfha!^)(=GafhzieC_iA<5A@^*h&Hend;<6f#!UMj&kPfJ00000NkvXXu0mjf{2TkWYB*C;ha%AAQ-_Ww zm+;F;LZz^lW~G&0Y}h82w3?Z$#**w1#A>-eg?*Qd>Fn0YcBj!dITLYy7>Ya;;r@bL zif|V4_SgadMmHl9a7q4^6)b$dRDMzb14x0E<^#ZW37C)N=Zf}^n?}XbmV;IxMgDy_ zRE=qvk$_tAS`k?jmXO!v($_Fl$^f_Pd8d8<_!i}ao?t$p6_AM*a;;C!Ei$2>U?tCq zNNq^;HGF=Vbbd=>yPnhK(86rOzQWx-yhbKWmDv&>?_Zs^ws8UfpaRqbehp_&(`YQ` zi}2s)Lao5KY3Rgptb#_ZG7WEtiX$+( name, Prov color, Floatp fraction) { + this.fraction = fraction; + lastValue = value = Mathf.clamp(fraction.get()); + update(() -> { + this.name = name.get(); + this.blinkColor.set(color.get()); + setColor(color.get()); + }); + } + + public CenterBar() { + + } + + public void reset(float value){ + this.value = lastValue = blink = value; + } + + public void set(Prov name, Floatp fraction, Color color){ + this.fraction = fraction; + this.lastValue = fraction.get(); + this.blinkColor.set(color); + setColor(color); + update(() -> this.name = name.get()); + } + + public void snap(){ + lastValue = value = fraction.get(); + } + + public Bar outline(Color color, float stroke){ + outlineColor.set(color); + outlineRadius = Scl.scl(stroke); + return this; + } + + public void flash(){ + blink = 1f; + } + + public Bar blink(Color color){ + blinkColor.set(color); + return this; + } + + @Override + public void draw(){ + if(fraction == null) return; + + float computed = Mathf.clamp(fraction.get(), -1f, 1f); + + + if(lastValue > computed){ + blink = 1f; + lastValue = computed; + } + + if(Float.isNaN(lastValue)) lastValue = 0; + if(Float.isInfinite(lastValue)) lastValue = 1f; + if(Float.isNaN(value)) value = 0; + if(Float.isInfinite(value)) value = 1f; + if(Float.isNaN(computed)) computed = 0; + if(Float.isInfinite(computed)) computed = 1f; + + blink = Mathf.lerpDelta(blink, 0f, 0.2f); + value = Mathf.lerpDelta(value, computed, 0.15f); + + Drawable bar = Tex.bar; + + if(outlineRadius > 0){ + Draw.color(outlineColor); + bar.draw(x - outlineRadius, y - outlineRadius, width + outlineRadius*2, height + outlineRadius*2); + } + + Draw.colorl(0.1f); + Draw.alpha(parentAlpha); + bar.draw(x, y, width, height); + Draw.color(color, blinkColor, blink); + Draw.alpha(parentAlpha); + + Drawable top = Tex.barTop; + + top.draw( + x + (width/2f - Core.atlas.find("bar-top").width/2f) * (Math.min(value, 0f) + 1f), + y, + Core.atlas.find("bar-top").width + (-Core.atlas.find("bar-top").width/2f + width/2f) * Math.abs(value), + height + ); + + Draw.color(); + + Font font = Fonts.outline; + GlyphLayout lay = Pools.obtain(GlyphLayout.class, GlyphLayout::new); + lay.setText(font, name); + + font.setColor(1f, 1f, 1f, 1f); + font.getCache().clear(); + font.getCache().addText(name, x + width / 2f - lay.width / 2f, y + height / 2f + lay.height / 2f + 1); + font.getCache().draw(parentAlpha); + + Pools.free(lay); + } +} diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidGauge.java b/src/omaloon/world/blocks/liquid/PressureLiquidGauge.java new file mode 100644 index 00000000..644e25d6 --- /dev/null +++ b/src/omaloon/world/blocks/liquid/PressureLiquidGauge.java @@ -0,0 +1,158 @@ +package omaloon.world.blocks.liquid; + +import arc.*; +import arc.graphics.*; +import arc.graphics.g2d.*; +import arc.math.*; +import arc.math.geom.*; +import arc.util.*; +import arc.util.io.*; +import mindustry.entities.units.*; +import mindustry.gen.*; +import mindustry.type.*; +import mindustry.world.blocks.liquid.*; +import mindustry.world.blocks.sandbox.*; +import omaloon.ui.elements.*; +import omaloon.world.interfaces.*; +import omaloon.world.meta.*; +import omaloon.world.modules.*; + +public class PressureLiquidGauge extends LiquidBlock { + public PressureConfig pressureConfig = new PressureConfig(); + + public Color maxColor = Color.white, minColor = Color.white; + + public TextureRegion[] tileRegions; + public TextureRegion gaugeRegion; + + public PressureLiquidGauge(String name) { + super(name); + rotate = true; + } + + @Override + public void drawPlanRegion(BuildPlan plan, Eachable list) { + var tiling = new Object() { + int tiling = 0; + }; + Point2 + front = new Point2(1, 0).rotate(plan.rotation).add(plan.x, plan.y), + back = new Point2(-1, 0).rotate(plan.rotation).add(plan.x, plan.y); + + boolean inverted = plan.rotation == 1 || plan.rotation == 2; + list.each(next -> { + if (new Point2(next.x, next.y).equals(front) && next.block.outputsLiquid) tiling.tiling |= inverted ? 2 : 1; + if (new Point2(next.x, next.y).equals(back) && next.block.outputsLiquid) tiling.tiling |= inverted ? 1 : 2; + }); + + Draw.rect(tileRegions[tiling.tiling], plan.drawx(), plan.drawy(), (plan.rotation + 1) * 90f % 180 - 90); + Draw.rect(gaugeRegion, plan.drawx(), plan.drawy()); + } + + @Override + public TextureRegion[] icons() { + return new TextureRegion[]{region}; + } + + @Override + public void load() { + super.load(); + tileRegions = Core.atlas.find(name + "-tiles").split(32, 32)[0]; + gaugeRegion = Core.atlas.find(name + "-pointer"); + } + + @Override + public void setBars() { + super.setBars(); + pressureConfig.addBars(this); + addBar("pressure", entity -> { + HasPressure build = (HasPressure)entity; + + return new CenterBar( + () -> Core.bundle.get("bar.pressure") + (build.pressure().getPressure(build.pressure().getMain()) < 0 ? "-" : "+") + Strings.autoFixed(Math.abs(build.pressure().getPressure(build.pressure().getMain())), 2), + () -> build.pressure().getPressure(build.pressure().getMain()) > 0 ? maxColor : minColor, + () -> Mathf.map(build.pressure().getPressure(build.pressure().getMain()), pressureConfig.minPressure, pressureConfig.maxPressure, -1, 1) + ); + }); + } + + @Override + public void setStats() { + super.setStats(); + pressureConfig.addStats(stats); + } + + public class PressureLiquidGaugeBuild extends LiquidBuild implements HasPressure { + PressureModule pressure = new PressureModule(); + + public int tiling; + + @Override + public boolean acceptLiquid(Building source, Liquid liquid) { + return hasLiquids; + } + + @Override + public boolean canDumpLiquid(Building to, Liquid liquid) { + return super.canDumpLiquid(to, liquid) || to instanceof LiquidVoid.LiquidVoidBuild; + } + + @Override + public boolean connects(HasPressure to) { + return HasPressure.super.connects(to) && to instanceof PressureLiquidValve.PressureLiquidValveBuild ? + (front() == to || back() == to) && (to.front() == this || to.back() == this) : + (front() == to || back() == to); + } + + @Override + public void draw() { + Draw.rect(tileRegions[tiling], x, y, tiling != 0 ? 0 : (rotdeg() + 90) % 180 - 90); + float p = Mathf.map(pressure().getPressure(pressure().getMain()), pressureConfig.minPressure, pressureConfig.maxPressure, -1, 1); + Draw.color( + Color.white, + pressure().getPressure(pressure().getMain()) > 0 ? maxColor : minColor, + p + ); + Draw.rect(gaugeRegion, x, y, rotdeg() + (p > 1 ? Mathf.randomSeed((long) Time.time, -360f, 360f) : p * 180f)); + } + + @Override + public void onProximityUpdate() { + super.onProximityUpdate(); + tiling = 0; + boolean inverted = rotation == 1 || rotation == 2; + if (front() instanceof HasPressure front && connected(front)) tiling |= inverted ? 2 : 1; + if (back() instanceof HasPressure back && connected(back)) tiling |= inverted ? 1 : 2; + } + + @Override public PressureModule pressure() { + return pressure; + } + @Override public PressureConfig pressureConfig() { + return pressureConfig; + } + + @Override + public void read(Reads read, byte revision) { + super.read(read, revision); + pressure.read(read); + } + + @Override + public void updatePressure() { + HasPressure.super.updatePressure(); + } + @Override + public void updateTile() { + updatePressure(); + nextBuilds(true).each(b -> moveLiquidPressure(b, liquids.current())); + dumpPressure(); + } + + @Override + public void write(Writes write) { + super.write(write); + pressure.write(write); + } + } +} diff --git a/src/omaloon/world/interfaces/HasPressure.java b/src/omaloon/world/interfaces/HasPressure.java index 2592a3ca..cb124469 100644 --- a/src/omaloon/world/interfaces/HasPressure.java +++ b/src/omaloon/world/interfaces/HasPressure.java @@ -178,8 +178,10 @@ default void transferPressure(HasPressure to, float pressure) { * method to update pressure related things */ default void updatePressure() { - if (Mathf.round(getPressure()) <= pressureConfig().minPressure) damage(pressureConfig().underPressureDamage); - if (Mathf.round(getPressure()) >= pressureConfig().maxPressure) damage(pressureConfig().overPressureDamage); + Vars.content.liquids().each(liquid -> { + if (Mathf.round(pressure().getPressure(liquid)) <= pressureConfig().minPressure) damage(pressureConfig().underPressureDamage); + if (Mathf.round(pressure().getPressure(liquid)) >= pressureConfig().maxPressure) damage(pressureConfig().overPressureDamage); + }); } /** diff --git a/src/omaloon/world/meta/PressureSection.java b/src/omaloon/world/meta/PressureSection.java new file mode 100644 index 00000000..baa69100 --- /dev/null +++ b/src/omaloon/world/meta/PressureSection.java @@ -0,0 +1,28 @@ +package omaloon.world.meta; + +import arc.struct.*; +import arc.util.*; +import mindustry.type.*; +import omaloon.world.interfaces.*; + +public class PressureSection { + public Seq builds = new Seq<>(); + + /** + * Adds a certain amount of a fluid into this module, updating it's pressure accordingly. A null liquid means that air is being added to it. + */ + public void addFluid(@Nullable Liquid liquid, float amount) { + if (builds.isEmpty()) return; + float div = amount/builds.size; + builds.each(b -> b.pressure().addFluid(liquid, div, b.pressureConfig())); + } + + /** + * Removes a certain amount of a fluid from this module, updating pressure accordingly. A null liquid means that air is being removed from it. Liquids cannot be negative. + */ + public void removeFluid(@Nullable Liquid liquid, float amount) { + if (builds.isEmpty()) return; + float div = amount/builds.size; + builds.each(b -> b.pressure().removeFluid(liquid, div, b.pressureConfig())); + } +} diff --git a/src/omaloon/world/modules/PressureModule.java b/src/omaloon/world/modules/PressureModule.java index ea775af7..c1d71737 100644 --- a/src/omaloon/world/modules/PressureModule.java +++ b/src/omaloon/world/modules/PressureModule.java @@ -15,6 +15,8 @@ public class PressureModule extends BlockModule { public float[] pressures = new float[Vars.content.liquids().size]; public float air = 0, pressure = 0; + public PressureSection section = new PressureSection(); + public @Nullable Liquid current; /** @@ -31,10 +33,6 @@ public void addFluid(@Nullable Liquid liquid, float amount, PressureConfig refer current = liquid; } - public float currentAmount() { - return current == null ? air : liquids[current.id]; - } - public @Nullable Liquid getMain() { Liquid out = null; for(int i = 0; i < liquids.length; i++) { From ecaee4c631204e96c67671d8825b7d6c86cd3f86 Mon Sep 17 00:00:00 2001 From: = Date: Fri, 6 Dec 2024 20:01:23 -0300 Subject: [PATCH 06/67] liquid distribution --- .../blocks/liquids/liquid-gauge-pointer.png | Bin 161 -> 162 bytes .../blocks/liquids/liquid-gauge-tiles.png | Bin 1029 -> 1015 bytes .../sprites/blocks/liquids/liquid-gauge.png | Bin 450 -> 428 bytes .../content/blocks/OlDistributionBlocks.java | 3 + .../blocks/liquid/PressureLiquidConduit.java | 44 +++++--------- .../blocks/liquid/PressureLiquidGauge.java | 7 ++- src/omaloon/world/interfaces/HasPressure.java | 45 +++++++------- src/omaloon/world/meta/PressureConfig.java | 5 +- src/omaloon/world/meta/PressureSection.java | 55 ++++++++++++++++++ 9 files changed, 103 insertions(+), 56 deletions(-) diff --git a/assets/sprites/blocks/liquids/liquid-gauge-pointer.png b/assets/sprites/blocks/liquids/liquid-gauge-pointer.png index 7106ec85012f7eb4eb47835d7498a24ed7f4e45a..bc46dd8c11f49f5a29d781c8fb8e81c1562e6429 100644 GIT binary patch delta 112 zcmV-$0FVEn0ipqrIcZc$L_t(oh3(Wq4ge4gL{WABJJ*_!#t@Cef$xIz| zckdRNNxP(>G5n;&_P{D!EwObt3J=33PG|sNY?;^uN)3K Sr3M%P0000qj{fGbn&o$$(91d+{ R^~wMM002ovPDHLkV1fhgEtUWP diff --git a/assets/sprites/blocks/liquids/liquid-gauge-tiles.png b/assets/sprites/blocks/liquids/liquid-gauge-tiles.png index 5b0474f5a2c2cc189d72053be34c290062697cd2..53dcd81cd84d3cd23fc72777d998ab303f16c529 100644 GIT binary patch delta 972 zcmV;-12g=E2=@n&Ie)21L_t(|ob6jNZX+=aFxbp ze15;(s(m(h8}Yg50S|cTGi}TT0WY|hggOU2;GVYP97vf;1E#+>(ngvGq6c_GWMJ(X z?`xWba|aZ>L_!145`*3Gfam2@PBtliOkvY7MQf)h2AZx4?4%T>;j%3j&^yinfu)7Cqo4 z;R)qqu7fo#^Q3X%IbnEKJP;A(;z3V49e2a!Xtp+q({cCzXtp+q8GJ!t4H6t&B(U~D zHAEi}2}B*yL-hfo%;A*VyvL&H`-7kt9O&0hK@m3FvIt z($e~Y)$@V$3x^~moJ3egG?VC3KVZ=l#IvCm1CSVR)f27=AU7O25>`Edh-mop`>(nT zH5YoquIuX70#4MZe!vUvB{A0Kc^V1y4jD>HC4caeJ|K~R>j$jh+Ow+q0SkDEL{_Al z&J)dlCHs=~16PwUb-7m`Nc-J%{lI9^|61t-+{~+BmHGh>iDvZ!nxV;v1kNq}$;Z+T zHrxL7V9tmTD@rsei5hUYe!xq@BlTa+0VI0mNLcj*qQnD8^s;6|rF}-!h+1Vt$R-Cb z!+#!jI_`$BSTNtBhY;Xb_^T6G)DJ{nToc_uKJZOIJeY+3e?hH2P*p!rs}FeU2b$^w zs9MggsXox8e!vUvB?0e*7JY!IvVH&o?^-`#1=pTc)el&}YeIbxjxq-dlDgiHv>iU6NeW1F2 upjIDfQa@0u518u*BJ}~H8;Awp1U>=t3G9LE+ipMr0000&CqR delta 986 zcmV<0110?T2ZacbIe)iFL_t(|ob6h%j@vK{r3?SZAwQAj#+whFid$~(pA_gf1Rb*k zHwBqHcDbK0@+Ix$RFO&Xk(4asa0CLxjx4^<ezgfigQCfB((z)wGw_ry;$*yJ+p4 z19AJZmh&9M(8GBOVnCcv*NKRTb`LwKV@vxlXlMENTJ4JfxPJ~xom$%y5sjA4W;?!} z*!z$Bz1WxZI@l2?Isfzi?)pvYa{<8X+zUbtLW^@xTXq`eNVyL4_l>mS;(#52v?0>5 zbT56@6om5wsB;ZOX+eTxKyz+s;|9>ehUc%}#l7J5+soZGva}K{-?y}I5p7@uOaPGG z4c#$S0FV1UJAdRQ2i$Mdbt(oX3m|;}1tB@-`b=#Rgi=H6&`JTDuPty4pfkYQb^*Y% zrJ`-PzS$A*g79qR#f3R1L5Td5D-oI zfl^Ia1TcfB!4GI4#A%2+;M!>MqE5p#tqVVpj%4={FvY;`VW*A)vSX$((wraAWY8>0G4K?DN1t3|8az~wWf37+|U_DEy$`4qb6IJF1(2NM0hLWRbMr0Q?fVKF{EuRh@P(hpdiYaogw)pVU`{%H0g^#gZ7m=C#^AIP8Ew0>Z;@PD=Vfz-^i zU={s<2ShdffMjSg!Z}YZf90dLg3We(JDD>g#8iqV2N7`&>j%6b!ukPZ_bP!1>j#kC z%YT{?ne_vu-OHL0LHdE7+`#307`p8R^C@~40O=9_>Hrq{fu0A~L>tHlJ^`?WNt7Q5 z=?9|xKuA9j|0AMiT&f`C^-3qL><)DIxeo9YLw&ZT=H{eZ=J z1jLw55v{KKkotix{J^&K13mZw_~5bzKU3h+4|qU$^#jfL0d(nRw`1$!H0m7E4@eD5 z9ebUN0K6c=`hh4v5Y`Vw`GG3>fha#<)(`aL2Z%PX7kmQv2gXeM9?uLDc>n+a07*qo IM6N<$f}yq5LjV8( diff --git a/assets/sprites/blocks/liquids/liquid-gauge.png b/assets/sprites/blocks/liquids/liquid-gauge.png index e8d39d91672a49818684e0fa198a21ee3e8d935e..46865391aec4e27f2191df4133d6354043b4a5c5 100644 GIT binary patch delta 380 zcmV-?0fYX+1FQp(Ie%VBL_t(og~eApb^fT~g=M1PZ9hnL-T(qzR#h zj%F{hkCTK7;qjZ@kc8_4 z+$Z4}`0{g29cFJ6Rp1=|yBr`XuoYY+U?pM69Q_3V(3~34>3>+)R6nXJ(Pwx+qLq59PzjZFPCtWF4TM)NI_~iQ&NW_(BxBx zjwYAz%Sl3|u$E?}m0oPvCYH3CnXJZ=>=49ixj%({myGG`*2#9K(Kk60aef$zJQU&n zf?SGl7V`Gk0suxgBNK2*{*@Ihe7;nEQUC);ftKb2z;y|jkALOoiuRA2M#a*WgH|9# z{(U%9jcJ&XfLiie5m^(Kkk{nW*DzGd0JrOTr+xqU7UhJVU_PJ~kck#@txwJ^GNGSf zCC`aSZAkPre14g9eoJDzp3~*f!fe96!reW*MkY*^*%BY`U!AtLaRL9J0@MS34QEf& zXe{T8@ZaY`t$)C{Y3Rgptb#_ZG7WEtiX$ z+( list) { } } - @Override - public TextureRegion[] icons() { - return new TextureRegion[]{region}; - } - @Override public void load() { super.load(); + topRegions = OlUtils.split(name + "-tiles", 32, 0); - if (!bottomRegion.found()) bottomRegion = Core.atlas.find("omaloon-liquid-bottom"); + bottomRegion = Core.atlas.find(name + "-bottom", "omaloon-liquid-bottom"); liquidRegions = new TextureRegion[2][animationFrames]; if(renderer != null){ @@ -143,15 +138,10 @@ public void setStats() { pressureConfig.addStats(stats); } - public class PressureLiquidConduitBuild extends LiquidRouterBuild implements HasPressure { + public class PressureLiquidConduitBuild extends Building implements HasPressure { public int tiling = 0; PressureModule pressure = new PressureModule(); - @Override - public boolean canDumpLiquid(Building to, Liquid liquid) { - return super.canDumpLiquid(to, liquid) || to instanceof LiquidVoid.LiquidVoidBuild; - } - @Override public boolean connects(HasPressure to) { return ( @@ -163,27 +153,23 @@ public boolean connects(HasPressure to) { @Override public void draw() { Draw.rect(bottomRegion, x, y); - if (liquids().currentAmount() > 0.01f) { - int frame = liquids.current().getAnimationFrame(); - int gas = liquids.current().gas ? 1 : 0; + Liquid main = pressure.getMain(); + if (main != null && pressure.liquids[main.id] > 0.01f) { + int frame = main.getAnimationFrame(); + int gas = main.gas ? 1 : 0; float xscl = Draw.xscl, yscl = Draw.yscl; Draw.scl(1f, 1f); - Drawf.liquid(liquidRegions[gas][frame], x, y, liquids.currentAmount()/liquidCapacity, liquids.current().color.write(Tmp.c1).a(1f)); + Drawf.liquid(liquidRegions[gas][frame], x, y, Mathf.clamp(pressure.liquids[main.id]/(pressure.liquids[main.id] + pressure.air)), main.color.write(Tmp.c1).a(1f)); Draw.scl(xscl, yscl); } Draw.rect(topRegions[tiling], x, y, tiling != 0 ? 0 : (rotdeg() + 90) % 180 - 90); } - @Override - public float moveLiquid(Building next, Liquid liquid) { - if (next instanceof HasPressure p) return moveLiquidPressure(p, liquid); - return 0f; - } - @Override public void onProximityUpdate() { super.onProximityUpdate(); + tiling = 0; for (int i = 0; i < 4; i++) { HasPressure build = nearby(i) instanceof HasPressure ? (HasPressure) nearby(i) : null; @@ -191,6 +177,8 @@ public void onProximityUpdate() { build != null && connected(build) ) tiling |= (1 << i); } + + new PressureSection().mergeFlood(this); } @Override public PressureModule pressure() { @@ -209,8 +197,6 @@ public void read(Reads read, byte revision) { @Override public void updateTile() { updatePressure(); - nextBuilds(true).each(b -> moveLiquidPressure(b, liquids.current())); - dumpPressure(); } @Override diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidGauge.java b/src/omaloon/world/blocks/liquid/PressureLiquidGauge.java index 644e25d6..e817e2df 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidGauge.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidGauge.java @@ -46,7 +46,7 @@ public void drawPlanRegion(BuildPlan plan, Eachable list) { }); Draw.rect(tileRegions[tiling.tiling], plan.drawx(), plan.drawy(), (plan.rotation + 1) * 90f % 180 - 90); - Draw.rect(gaugeRegion, plan.drawx(), plan.drawy()); + Draw.rect(gaugeRegion, plan.drawx(), plan.drawy(), plan.rotation * 90f); } @Override @@ -107,7 +107,7 @@ public boolean connects(HasPressure to) { @Override public void draw() { Draw.rect(tileRegions[tiling], x, y, tiling != 0 ? 0 : (rotdeg() + 90) % 180 - 90); - float p = Mathf.map(pressure().getPressure(pressure().getMain()), pressureConfig.minPressure, pressureConfig.maxPressure, -1, 1); + float p = Math.abs(Mathf.map(pressure().getPressure(pressure().getMain()), pressureConfig.minPressure, pressureConfig.maxPressure, -1, 1)); Draw.color( Color.white, pressure().getPressure(pressure().getMain()) > 0 ? maxColor : minColor, @@ -119,10 +119,13 @@ public void draw() { @Override public void onProximityUpdate() { super.onProximityUpdate(); + tiling = 0; boolean inverted = rotation == 1 || rotation == 2; if (front() instanceof HasPressure front && connected(front)) tiling |= inverted ? 2 : 1; if (back() instanceof HasPressure back && connected(back)) tiling |= inverted ? 1 : 2; + + new PressureSection().mergeFlood(this); } @Override public PressureModule pressure() { diff --git a/src/omaloon/world/interfaces/HasPressure.java b/src/omaloon/world/interfaces/HasPressure.java index cb124469..8386f6b3 100644 --- a/src/omaloon/world/interfaces/HasPressure.java +++ b/src/omaloon/world/interfaces/HasPressure.java @@ -21,6 +21,14 @@ public interface HasPressure extends Buildingc { default boolean acceptsPressure(HasPressure from, float pressure) { return getPressure() + pressure <= from.getPressure() - pressure; } + + /** + * Adds a certain amount of a fluid into this module through the section. + */ + default void addFluid(@Nullable Liquid liquid, float amount) { + pressure().section.addFluid(liquid, amount); + } + /** * @return true if this building can dump a certain pressure amount to some building */ @@ -54,29 +62,6 @@ default void dumpPressure() { } } - default void dumpLiquidPressure(Liquid liquid) { - int dump = cdump(); - if (liquids().get(liquid) > 0.0001f) { - if (!Vars.net.client() && Vars.state.isCampaign() && team() == Vars.state.rules.defaultTeam) { - liquid.unlock(); - } - - for(int i = 0; i < nextBuilds(true).size; ++i) { - incrementDump(nextBuilds(true).size); - HasPressure other = nextBuilds(true).get((i + dump) % nextBuilds(true).size); - other = other.getLiquidDestination(as(), liquid).as(); - if (other != null && other.block().hasLiquids && canDumpLiquid(other.as(), liquid) && other.liquids() != null) { - float ofract = other.liquids().get(liquid) / other.block().liquidCapacity; - float fract = liquids().get(liquid) / block().liquidCapacity; - if (ofract < fract) { - transferLiquid(other.as(), (fract - ofract) * block().liquidCapacity * getPressureFlow(other) / nextBuilds(true).size, liquid); - } - } - } - - } - } - /** * @return current pressure of the building */ @@ -91,6 +76,13 @@ default HasPressure getPressureDestination(HasPressure from, float pressure) { return this; } + /** + * Returns the building whose section should be the same as this build's section. + */ + default @Nullable HasPressure getSectionDestination(HasPressure from) { + return this; + } + /** * @return flow of liquids from one build to another */ @@ -164,6 +156,13 @@ default Seq nextBuilds(boolean flow) { PressureModule pressure(); PressureConfig pressureConfig(); + /** + * Removes a certain amount of a fluid into this module through the section. + */ + default void removeFluid(@Nullable Liquid liquid, float amount) { + pressure().section.removeFluid(liquid, amount); + } + /** * transfers pressure between 2 buildings taking acceptsPressure into account */ diff --git a/src/omaloon/world/meta/PressureConfig.java b/src/omaloon/world/meta/PressureConfig.java index 395b5ff2..be76c5f7 100644 --- a/src/omaloon/world/meta/PressureConfig.java +++ b/src/omaloon/world/meta/PressureConfig.java @@ -4,6 +4,7 @@ import arc.graphics.*; import arc.math.*; import arc.struct.*; +import arc.util.*; import mindustry.gen.*; import mindustry.type.*; import mindustry.ui.*; @@ -91,8 +92,8 @@ public void addBars(Block block) { if (current == null) return Core.bundle.get("bar.air") + Mathf.round(build.pressure().air, 1); return Core.bundle.format("bar.pressure-liquid", current.localizedName, - Mathf.round(build.pressure().liquids[current.id], 1), - Mathf.round(build.pressure().air, 1) + Strings.autoFixed(build.pressure().liquids[current.id], 2), + Strings.autoFixed(build.pressure().air, 2) ); }, () -> { diff --git a/src/omaloon/world/meta/PressureSection.java b/src/omaloon/world/meta/PressureSection.java index baa69100..3822d751 100644 --- a/src/omaloon/world/meta/PressureSection.java +++ b/src/omaloon/world/meta/PressureSection.java @@ -2,12 +2,27 @@ import arc.struct.*; import arc.util.*; +import mindustry.*; import mindustry.type.*; import omaloon.world.interfaces.*; public class PressureSection { public Seq builds = new Seq<>(); + /** + * Temporary seqs for use in flood. + */ + public static final Seq tmp = new Seq<>(), tmp2 = new Seq<>(); + + /** + * Adds a build to this section, and removes the build from its older section. + */ + public void addBuild(HasPressure build) { + builds.add(build); + build.pressure().section.builds.remove(build); + build.pressure().section = this; + } + /** * Adds a certain amount of a fluid into this module, updating it's pressure accordingly. A null liquid means that air is being added to it. */ @@ -17,6 +32,27 @@ public void addFluid(@Nullable Liquid liquid, float amount) { builds.each(b -> b.pressure().addFluid(liquid, div, b.pressureConfig())); } + /** + * Merges buildings to this section with floodFill. + */ + public void mergeFlood(HasPressure other) { + tmp.clear().add(other); + tmp2.clear(); + + while(!tmp.isEmpty()) { + HasPressure next = tmp.pop(); + tmp2.addUnique(next); + next.nextBuilds(false).each(b -> { + if (b.getSectionDestination(next) != null && !tmp2.contains(b.getSectionDestination(next))) { + tmp.add(b.getSectionDestination(next)); + } + }); + } + + tmp2.each(this::addBuild); + updateLiquids(); + } + /** * Removes a certain amount of a fluid from this module, updating pressure accordingly. A null liquid means that air is being removed from it. Liquids cannot be negative. */ @@ -25,4 +61,23 @@ public void removeFluid(@Nullable Liquid liquid, float amount) { float div = amount/builds.size; builds.each(b -> b.pressure().removeFluid(liquid, div, b.pressureConfig())); } + + public void updateLiquids() { + float[] liquids = new float[Vars.content.liquids().size]; + float air = 0; + + for(Liquid liquid : Vars.content.liquids()) for (HasPressure build : builds) { + liquids[liquid.id] += build.pressure().liquids[liquid.id]; + build.pressure().liquids[liquid.id] = 0; + build.pressure().pressures[liquid.id] = 0; + } + for(HasPressure build : builds) { + air += build.pressure().air; + build.pressure().air = 0; + build.pressure().pressure = 0; + } + + for(Liquid liquid : Vars.content.liquids()) addFluid(liquid, liquids[liquid.id]); + addFluid(null, air); + } } From 86162b9fef1f960134d0a60a9cf3e2026349910b Mon Sep 17 00:00:00 2001 From: = Date: Fri, 6 Dec 2024 20:12:01 -0300 Subject: [PATCH 07/67] forgot --- src/omaloon/world/blocks/liquid/PressureLiquidConduit.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidConduit.java b/src/omaloon/world/blocks/liquid/PressureLiquidConduit.java index f1000926..12f0474f 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidConduit.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidConduit.java @@ -39,6 +39,8 @@ public class PressureLiquidConduit extends Block { public PressureLiquidConduit(String name) { super(name); rotate = true; + destructible = true; + update = true; } @Override From 80ef75114eb54edf0e7dffca8659234e4ddcd683 Mon Sep 17 00:00:00 2001 From: = Date: Sat, 7 Dec 2024 19:36:19 -0300 Subject: [PATCH 08/67] pump --- .../content/blocks/OlDistributionBlocks.java | 2 +- .../blocks/liquid/PressureLiquidConduit.java | 10 ++ .../blocks/liquid/PressureLiquidGauge.java | 34 ++--- .../blocks/liquid/PressureLiquidPump.java | 132 ++++++++++-------- src/omaloon/world/interfaces/HasPressure.java | 123 +++++++--------- src/omaloon/world/meta/PressureConfig.java | 8 +- 6 files changed, 155 insertions(+), 154 deletions(-) diff --git a/src/omaloon/content/blocks/OlDistributionBlocks.java b/src/omaloon/content/blocks/OlDistributionBlocks.java index 79e77252..d7d35b95 100644 --- a/src/omaloon/content/blocks/OlDistributionBlocks.java +++ b/src/omaloon/content/blocks/OlDistributionBlocks.java @@ -130,7 +130,7 @@ public static void load() { OlItems.cobalt, 20 ); pressureTransfer = 0.1f; - pressureDifference = 5f; + pressureDifference = 20f; }}; liquidValve = new PressureLiquidValve("liquid-valve") {{ diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidConduit.java b/src/omaloon/world/blocks/liquid/PressureLiquidConduit.java index 12f0474f..540a3062 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidConduit.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidConduit.java @@ -144,6 +144,11 @@ public class PressureLiquidConduitBuild extends Building implements HasPressure public int tiling = 0; PressureModule pressure = new PressureModule(); + @Override + public boolean acceptsPressurizedFluid(HasPressure from, @Nullable Liquid liquid, float amount) { + return HasPressure.super.acceptsPressurizedFluid(from, liquid, amount) && (liquid == pressure.getMain() || liquid == null || pressure.getMain() == null || from.pressure().getMain() == null); + } + @Override public boolean connects(HasPressure to) { return ( @@ -183,6 +188,11 @@ public void onProximityUpdate() { new PressureSection().mergeFlood(this); } + @Override + public boolean outputsPressurizedFluid(HasPressure to, Liquid liquid, float amount) { + return HasPressure.super.outputsPressurizedFluid(to, liquid, amount) && (liquid == to.pressure().getMain() || liquid == null || pressure.getMain() == null || to.pressure().getMain() == null); + } + @Override public PressureModule pressure() { return pressure; } diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidGauge.java b/src/omaloon/world/blocks/liquid/PressureLiquidGauge.java index e817e2df..5a02505c 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidGauge.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidGauge.java @@ -9,15 +9,13 @@ import arc.util.io.*; import mindustry.entities.units.*; import mindustry.gen.*; -import mindustry.type.*; -import mindustry.world.blocks.liquid.*; -import mindustry.world.blocks.sandbox.*; +import mindustry.world.*; import omaloon.ui.elements.*; import omaloon.world.interfaces.*; import omaloon.world.meta.*; import omaloon.world.modules.*; -public class PressureLiquidGauge extends LiquidBlock { +public class PressureLiquidGauge extends Block { public PressureConfig pressureConfig = new PressureConfig(); public Color maxColor = Color.white, minColor = Color.white; @@ -28,6 +26,8 @@ public class PressureLiquidGauge extends LiquidBlock { public PressureLiquidGauge(String name) { super(name); rotate = true; + update = true; + destructible = true; } @Override @@ -82,21 +82,11 @@ public void setStats() { pressureConfig.addStats(stats); } - public class PressureLiquidGaugeBuild extends LiquidBuild implements HasPressure { + public class PressureLiquidGaugeBuild extends Building implements HasPressure { PressureModule pressure = new PressureModule(); public int tiling; - @Override - public boolean acceptLiquid(Building source, Liquid liquid) { - return hasLiquids; - } - - @Override - public boolean canDumpLiquid(Building to, Liquid liquid) { - return super.canDumpLiquid(to, liquid) || to instanceof LiquidVoid.LiquidVoidBuild; - } - @Override public boolean connects(HasPressure to) { return HasPressure.super.connects(to) && to instanceof PressureLiquidValve.PressureLiquidValveBuild ? @@ -106,14 +96,14 @@ public boolean connects(HasPressure to) { @Override public void draw() { - Draw.rect(tileRegions[tiling], x, y, tiling != 0 ? 0 : (rotdeg() + 90) % 180 - 90); - float p = Math.abs(Mathf.map(pressure().getPressure(pressure().getMain()), pressureConfig.minPressure, pressureConfig.maxPressure, -1, 1)); + Draw.rect(tileRegions[tiling], x, y, tiling == 0 ? 0 : (rotdeg() + 90) % 180 - 90); + float p = Mathf.map(pressure().getPressure(pressure().getMain()), pressureConfig.minPressure, pressureConfig.maxPressure, -1, 1); Draw.color( Color.white, pressure().getPressure(pressure().getMain()) > 0 ? maxColor : minColor, - p + Math.abs(p) ); - Draw.rect(gaugeRegion, x, y, rotdeg() + (p > 1 ? Mathf.randomSeed((long) Time.time, -360f, 360f) : p * 180f)); + Draw.rect(gaugeRegion, x, y, rotdeg() + (Math.abs(p) > 1 ? Mathf.randomSeed((long) Time.time, -360f, 360f) : p * 180f)); } @Override @@ -141,15 +131,9 @@ public void read(Reads read, byte revision) { pressure.read(read); } - @Override - public void updatePressure() { - HasPressure.super.updatePressure(); - } @Override public void updateTile() { updatePressure(); - nextBuilds(true).each(b -> moveLiquidPressure(b, liquids.current())); - dumpPressure(); } @Override diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidPump.java b/src/omaloon/world/blocks/liquid/PressureLiquidPump.java index c4fcf495..ac2ce03a 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidPump.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidPump.java @@ -1,20 +1,22 @@ package omaloon.world.blocks.liquid; import arc.*; +import arc.graphics.*; import arc.graphics.g2d.*; import arc.math.*; import arc.math.geom.*; +import arc.scene.ui.layout.*; import arc.struct.*; import arc.util.*; import arc.util.io.*; +import mindustry.*; import mindustry.content.*; -import mindustry.entities.*; import mindustry.entities.units.*; import mindustry.gen.*; import mindustry.graphics.*; import mindustry.type.*; -import mindustry.world.blocks.liquid.*; -import omaloon.content.*; +import mindustry.world.*; +import mindustry.world.blocks.*; import omaloon.utils.*; import omaloon.world.interfaces.*; import omaloon.world.meta.*; @@ -23,25 +25,29 @@ import static mindustry.Vars.*; import static mindustry.type.Liquid.*; -public class PressureLiquidPump extends LiquidBlock { +public class PressureLiquidPump extends Block { public PressureConfig pressureConfig = new PressureConfig(); public float pressureTransfer = 0.1f; public float pressureDifference = 10; - public Effect pumpEffectForward = OlFx.pumpFront, pumpEffectBackward = OlFx.pumpBack; - public float pumpEffectInterval = 15f; - public float liquidPadding = 3f; public TextureRegion[][] liquidRegions; public TextureRegion[] tiles; - public TextureRegion arrowRegion; + public TextureRegion arrowRegion, topRegion, bottomRegion; public PressureLiquidPump(String name) { super(name); rotate = true; + destructible = true; + update = true; + configurable = true; + saveConfig = copyConfig = true; + config(Liquid.class, (PressureLiquidPumpBuild build, Liquid liquid) -> { + build.filter = liquid.id; + }); } @Override @@ -76,7 +82,8 @@ public void load() { super.load(); tiles = OlUtils.split(name + "-tiles", 32, 0); arrowRegion = Core.atlas.find(name + "-arrow"); - if (!bottomRegion.found()) bottomRegion = Core.atlas.find("omaloon-liquid-bottom"); + topRegion = Core.atlas.find(name + "-top"); + bottomRegion = Core.atlas.find(name + "-bottom", "omaloon-liquid-bottom"); liquidRegions = new TextureRegion[2][animationFrames]; if(renderer != null){ @@ -106,18 +113,16 @@ public void setStats() { stats.add(OlStats.pressureFlow, Mathf.round(pressureTransfer * 60f, 2), OlStats.pressureSecond); } - public class PressureLiquidPumpBuild extends LiquidBuild implements HasPressure { + public class PressureLiquidPumpBuild extends Building implements HasPressure { PressureModule pressure = new PressureModule(); public int tiling; - public float effectInterval; + public int filter = -1; - @Override public boolean acceptLiquid(Building source, Liquid liquid) { - return false; - } - @Override public boolean acceptsPressure(HasPressure from, float pressure) { - return false; + @Override + public void buildConfiguration(Table table) { + ItemSelection.buildTable(table, Vars.content.liquids(), () -> Vars.content.liquid(filter), other -> filter = other == null ? -1 : other.id); } @Override public boolean connects(HasPressure to) { @@ -129,22 +134,46 @@ public void draw() { float rot = rotate ? (90 + rotdeg()) % 180 - 90 : 0; if (tiling != 0) { Draw.rect(bottomRegion, x, y, rotdeg()); - if (liquids().currentAmount() > 0.01f) { - HasPressure front = (front() instanceof HasPressure b && connected(b)) ? b : null; - HasPressure back = (back() instanceof HasPressure b && connected(b)) ? b : null; + + HasPressure front = (front() instanceof HasPressure b && connected(b)) ? b : null; + HasPressure back = (back() instanceof HasPressure b && connected(b)) ? b : null; + + if ( + (front != null && front.pressure().getMain() != null) || + (back != null && back.pressure().getMain() != null) + ) { + + Color tmpColor = Tmp.c1; + if (front != null && front.pressure().getMain() != null) { + tmpColor.set(front.pressure().getMain().color); + } else if (back != null && back.pressure().getMain() != null) { + tmpColor.set(back.pressure().getMain().color); + } + + if ( + front != null && front.pressure().getMain() != null && + back != null && back.pressure().getMain() != null + ) tmpColor.lerp(back.pressure().getMain().color, 0.5f); + + float alpha = - (front == null ? 0 : front.liquids().currentAmount()/front.block().liquidCapacity) + - (back == null ? 0 : back.liquids().currentAmount()/back.block().liquidCapacity); + (front != null && front.pressure().getMain() != null ? Mathf.clamp(front.pressure().liquids[front.pressure().getMain().id]/(front.pressure().liquids[front.pressure().getMain().id] + front.pressure().air)) : 0) + + (back != null && back.pressure().getMain() != null ? Mathf.clamp(back.pressure().liquids[back.pressure().getMain().id]/(back.pressure().liquids[back.pressure().getMain().id] + back.pressure().air)) : 0); alpha /= ((front == null ? 0 : 1f) + (back == null ? 0 : 1f)); - int frame = liquids.current().getAnimationFrame(); - int gas = liquids.current().gas ? 1 : 0; + Liquid drawLiquid = Liquids.water; + if (front != null && front.pressure().getMain() != null) { + drawLiquid = front.pressure().getMain(); + } else if (back != null && back.pressure().getMain() != null) { + drawLiquid = back.pressure().getMain(); + } + + int frame = drawLiquid.getAnimationFrame(); + int gas = drawLiquid.gas ? 1 : 0; float xscl = Draw.xscl, yscl = Draw.yscl; Draw.scl(1f, 1f); - Drawf.liquid(liquidRegions[gas][frame], x, y, alpha, - front == null ? back == null ? Liquids.water.color : back.liquids().current().color : front.liquids().current().color - ); + Drawf.liquid(liquidRegions[gas][frame], x, y, alpha, tmpColor); Draw.scl(xscl, yscl); } Draw.rect(arrowRegion, x, y, rotdeg()); @@ -153,6 +182,11 @@ public void draw() { if (tiling == 0) Draw.rect(topRegion, x, y, rotdeg()); } + @Override + public HasPressure getSectionDestination(HasPressure from) { + return null; + } + @Override public Seq nextBuilds(boolean flow) { return Seq.with(); @@ -161,10 +195,13 @@ public Seq nextBuilds(boolean flow) { @Override public void onProximityUpdate() { super.onProximityUpdate(); + tiling = 0; boolean inverted = rotation == 1 || rotation == 2; if (front() instanceof HasPressure front && connected(front)) tiling |= inverted ? 2 : 1; if (back() instanceof HasPressure back && connected(back)) tiling |= inverted ? 1 : 2; + + new PressureSection().mergeFlood(this); } @Override public PressureModule pressure() { @@ -178,6 +215,7 @@ public void onProximityUpdate() { public void read(Reads read, byte revision) { super.read(read, revision); pressure.read(read); + filter = read.i(); } @Override @@ -186,37 +224,18 @@ public void updateTile() { if (efficiency > 0) { HasPressure front = (front() instanceof HasPressure b && connected(b)) ? b : null; HasPressure back = (back() instanceof HasPressure b && connected(b)) ? b : null; - boolean pumped = false; - - float solid = 1; - if (front == null && front() != null || back == null && back() != null) solid++; - - float difference = (front == null ? 0 : front.getPressure()) - (back == null ? 0 : back.getPressure()); - if (difference < pressureDifference/solid) { - if (front != null) front.handlePressure(pressureTransfer * edelta()); - if (back != null) back.removePressure(pressureTransfer * edelta()); - pumped = true; - } else if (back != null && front == null && front() == null) { - back.removePressure(pressureTransfer * edelta()); - pumped = true; - } - - if (pumped) effectInterval += delta(); - if (effectInterval > pumpEffectInterval) { - if (front() == null) pumpEffectForward.at(x, y, rotdeg()); - if (back() == null) pumpEffectBackward.at(x, y, rotdeg() + 180f); - effectInterval = 0f; - } - if (back != null) { - if (front != null) { - back.moveLiquidPressure(front, back.liquids().current()); - } else { - if (front() == null) { - float leakAmount = back.liquids().get(back.liquids().current()) / 1.5f; - Puddles.deposit(tile.nearby(rotation), tile, back.liquids().current(), leakAmount, true, true); - back.liquids().remove(back.liquids().current(), leakAmount); - } + if (front != null && back != null) { + Liquid pumpLiquid = Vars.content.liquid(filter); + float frontPressure = front.pressure().getPressure(pumpLiquid), backPressure = back.pressure().getPressure(pumpLiquid); + float flow = pressureTransfer * (backPressure - frontPressure + pressureDifference); + if (pumpLiquid != null) flow = Mathf.clamp(flow, -front.pressure().liquids[pumpLiquid.id], back.pressure().liquids[pumpLiquid.id]); + if ( + front.acceptsPressurizedFluid(back, pumpLiquid, flow) && + back.outputsPressurizedFluid(front, pumpLiquid, flow) + ) { + front.addFluid(pumpLiquid, flow); + back.removeFluid(pumpLiquid, flow); } } } @@ -226,6 +245,7 @@ public void updateTile() { public void write(Writes write) { super.write(write); pressure.write(write); + write.i(filter); } } } diff --git a/src/omaloon/world/interfaces/HasPressure.java b/src/omaloon/world/interfaces/HasPressure.java index 8386f6b3..be4796e4 100644 --- a/src/omaloon/world/interfaces/HasPressure.java +++ b/src/omaloon/world/interfaces/HasPressure.java @@ -4,7 +4,6 @@ import arc.struct.*; import arc.util.*; import mindustry.*; -import mindustry.content.*; import mindustry.gen.*; import mindustry.type.*; import omaloon.world.meta.*; @@ -22,6 +21,10 @@ default boolean acceptsPressure(HasPressure from, float pressure) { return getPressure() + pressure <= from.getPressure() - pressure; } + default boolean acceptsPressurizedFluid(HasPressure from, @Nullable Liquid liquid, float amount) { + return pressureConfig().acceptsPressure; + } + /** * Adds a certain amount of a fluid into this module through the section. */ @@ -29,13 +32,6 @@ default void addFluid(@Nullable Liquid liquid, float amount) { pressure().section.addFluid(liquid, amount); } - /** - * @return true if this building can dump a certain pressure amount to some building - */ - default boolean canDumpPressure(HasPressure to, float pressure) { - return to.getPressure() + pressure <= getPressure() - pressure; - } - /** * @return true if both buildings are connected to eachother */ @@ -53,13 +49,13 @@ default boolean connects(HasPressure to) { * dumps pressure onto available builds */ default void dumpPressure() { - for (HasPressure other : nextBuilds(true)) { - float diff = (getPressure() - other.getPressure()) / 2f; - if (other.getPressure() > getPressure()) diff *= -1f; - if (canDumpPressure(other, diff)) { - transferPressure(other, diff); - } - } +// for (HasPressure other : nextBuilds(true)) { +// float diff = (getPressure() - other.getPressure()) / 2f; +// if (other.getPressure() > getPressure()) diff *= -1f; +// if (canDumpPressure(other, diff)) { +// transferPressure(other, diff); +// } +// } } /** @@ -83,15 +79,6 @@ default HasPressure getPressureDestination(HasPressure from, float pressure) { return this; } - /** - * @return flow of liquids from one build to another - */ - default float getPressureFlow(HasPressure to) { - //ensures that the liquid flows properly - if (to.getPressure() == 0) return 1f; - return Math.max(getPressure()/to.getPressure(), 1f); - } - /** * adds pressure not taking anything into account */ @@ -100,43 +87,43 @@ default void handlePressure(float pressure) { } default float moveLiquidPressure(HasPressure next, Liquid liquid) { - if (next != null) { - next = (HasPressure) next.getLiquidDestination(as(), liquid); - if (next.team() == team() && next.block().hasLiquids && liquids().get(liquid) > 0f) { - float ofract = next.liquids().get(liquid) / next.block().liquidCapacity; - float fract = liquids().get(liquid) / block().liquidCapacity; - float flow = Math.min(Mathf.clamp(fract - ofract) * block().liquidCapacity, liquids().get(liquid)) * getPressureFlow(next); - flow = Math.min(flow, next.block().liquidCapacity - next.liquids().get(liquid))/2; - if (flow > 0f && ofract <= fract && next.acceptLiquid(this.as(), liquid)) { - next.handleLiquid(this.as(), liquid, flow); - liquids().remove(liquid, flow); - return flow; - } - - if (!next.block().consumesLiquid(liquid) && next.liquids().currentAmount() / next.block().liquidCapacity > 0.1F && fract > 0.1F) { - float fx = (x() + next.x()) / 2f; - float fy = (y() + next.y()) / 2f; - Liquid other = next.liquids().current(); - if (other.blockReactive && liquid.blockReactive) { - if ((!(other.flammability > 0.3F) || !(liquid.temperature > 0.7F)) && (!(liquid.flammability > 0.3F) || !(other.temperature > 0.7F))) { - if (liquid.temperature > 0.7F && other.temperature < 0.55F || other.temperature > 0.7F && liquid.temperature < 0.55F) { - liquids().remove(liquid, Math.min(liquids().get(liquid), 0.7F * Time.delta)); - if (Mathf.chanceDelta(0.20000000298023224)) { - Fx.steam.at(fx, fy); - } - } - } else { - this.damageContinuous(1.0F); - next.damageContinuous(1.0F); - if (Mathf.chanceDelta(0.1)) { - Fx.fire.at(fx, fy); - } - } - } - } - } - - } +// if (next != null) { +// next = (HasPressure) next.getLiquidDestination(as(), liquid); +// if (next.team() == team() && next.block().hasLiquids && liquids().get(liquid) > 0f) { +// float ofract = next.liquids().get(liquid) / next.block().liquidCapacity; +// float fract = liquids().get(liquid) / block().liquidCapacity; +// float flow = Math.min(Mathf.clamp(fract - ofract) * block().liquidCapacity, liquids().get(liquid)) * getPressureFlow(next); +// flow = Math.min(flow, next.block().liquidCapacity - next.liquids().get(liquid))/2; +// if (flow > 0f && ofract <= fract && next.acceptLiquid(this.as(), liquid)) { +// next.handleLiquid(this.as(), liquid, flow); +// liquids().remove(liquid, flow); +// return flow; +// } +// +// if (!next.block().consumesLiquid(liquid) && next.liquids().currentAmount() / next.block().liquidCapacity > 0.1F && fract > 0.1F) { +// float fx = (x() + next.x()) / 2f; +// float fy = (y() + next.y()) / 2f; +// Liquid other = next.liquids().current(); +// if (other.blockReactive && liquid.blockReactive) { +// if ((!(other.flammability > 0.3F) || !(liquid.temperature > 0.7F)) && (!(liquid.flammability > 0.3F) || !(other.temperature > 0.7F))) { +// if (liquid.temperature > 0.7F && other.temperature < 0.55F || other.temperature > 0.7F && liquid.temperature < 0.55F) { +// liquids().remove(liquid, Math.min(liquids().get(liquid), 0.7F * Time.delta)); +// if (Mathf.chanceDelta(0.20000000298023224)) { +// Fx.steam.at(fx, fy); +// } +// } +// } else { +// this.damageContinuous(1.0F); +// next.damageContinuous(1.0F); +// if (Mathf.chanceDelta(0.1)) { +// Fx.fire.at(fx, fy); +// } +// } +// } +// } +// } +// +// } return 0.0F; } @@ -153,6 +140,10 @@ default Seq nextBuilds(boolean flow) { ); } + default boolean outputsPressurizedFluid(HasPressure to, @Nullable Liquid liquid, float amount) { + return pressureConfig().outputsPressure; + } + PressureModule pressure(); PressureConfig pressureConfig(); @@ -163,16 +154,6 @@ default void removeFluid(@Nullable Liquid liquid, float amount) { pressure().section.removeFluid(liquid, amount); } - /** - * transfers pressure between 2 buildings taking acceptsPressure into account - */ - default void transferPressure(HasPressure to, float pressure) { - if (to.acceptsPressure(this, pressure)) { - removePressure(pressure); - to.handlePressure(pressure); - } - } - /** * method to update pressure related things */ diff --git a/src/omaloon/world/meta/PressureConfig.java b/src/omaloon/world/meta/PressureConfig.java index be76c5f7..18cf7794 100644 --- a/src/omaloon/world/meta/PressureConfig.java +++ b/src/omaloon/world/meta/PressureConfig.java @@ -14,7 +14,13 @@ import omaloon.world.interfaces.*; public class PressureConfig { + /** + * If true, this block's section will be able to receive fluids. + */ public boolean acceptsPressure = true; + /** + * If true, this block's section will be able to output fluids. + */ public boolean outputsPressure = true; /** * Determines whether linkList will function as a whitelist @@ -89,7 +95,7 @@ public void addBars(Block block) { HasPressure build = (HasPressure)entity; Liquid current = build.pressure().getMain(); - if (current == null) return Core.bundle.get("bar.air") + Mathf.round(build.pressure().air, 1); + if (current == null) return Core.bundle.get("bar.air") + Strings.autoFixed(build.pressure().air, 2); return Core.bundle.format("bar.pressure-liquid", current.localizedName, Strings.autoFixed(build.pressure().liquids[current.id], 2), From 70ca75cee5b08075290d8c3ff73405e83c612c89 Mon Sep 17 00:00:00 2001 From: = Date: Sun, 8 Dec 2024 22:33:59 -0300 Subject: [PATCH 09/67] valve and a few fixes --- .../blocks/liquid/PressureLiquidGauge.java | 13 +++- .../blocks/liquid/PressureLiquidPump.java | 2 +- .../blocks/liquid/PressureLiquidValve.java | 74 +++++++++++-------- src/omaloon/world/interfaces/HasPressure.java | 4 +- 4 files changed, 59 insertions(+), 34 deletions(-) diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidGauge.java b/src/omaloon/world/blocks/liquid/PressureLiquidGauge.java index 5a02505c..ded57fa3 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidGauge.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidGauge.java @@ -9,6 +9,7 @@ import arc.util.io.*; import mindustry.entities.units.*; import mindustry.gen.*; +import mindustry.type.*; import mindustry.world.*; import omaloon.ui.elements.*; import omaloon.world.interfaces.*; @@ -87,6 +88,11 @@ public class PressureLiquidGaugeBuild extends Building implements HasPressure { public int tiling; + @Override + public boolean acceptsPressurizedFluid(HasPressure from, @Nullable Liquid liquid, float amount) { + return HasPressure.super.acceptsPressurizedFluid(from, liquid, amount) && (liquid == pressure.getMain() || liquid == null || pressure.getMain() == null || from.pressure().getMain() == null); + } + @Override public boolean connects(HasPressure to) { return HasPressure.super.connects(to) && to instanceof PressureLiquidValve.PressureLiquidValveBuild ? @@ -103,7 +109,7 @@ public void draw() { pressure().getPressure(pressure().getMain()) > 0 ? maxColor : minColor, Math.abs(p) ); - Draw.rect(gaugeRegion, x, y, rotdeg() + (Math.abs(p) > 1 ? Mathf.randomSeed((long) Time.time, -360f, 360f) : p * 180f)); + Draw.rect(gaugeRegion, x, y, (rotdeg() + 90) % 180 - 90 + (Math.abs(p) > 1 ? Mathf.randomSeed((long) Time.time, -360f, 360f) : p * 180f)); } @Override @@ -118,6 +124,11 @@ public void onProximityUpdate() { new PressureSection().mergeFlood(this); } + @Override + public boolean outputsPressurizedFluid(HasPressure to, Liquid liquid, float amount) { + return HasPressure.super.outputsPressurizedFluid(to, liquid, amount) && (liquid == to.pressure().getMain() || liquid == null || pressure.getMain() == null || to.pressure().getMain() == null); + } + @Override public PressureModule pressure() { return pressure; } diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidPump.java b/src/omaloon/world/blocks/liquid/PressureLiquidPump.java index ac2ce03a..ecdc3200 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidPump.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidPump.java @@ -226,7 +226,7 @@ public void updateTile() { HasPressure back = (back() instanceof HasPressure b && connected(b)) ? b : null; if (front != null && back != null) { - Liquid pumpLiquid = Vars.content.liquid(filter); + Liquid pumpLiquid = configurable ? Vars.content.liquid(filter) : back.pressure().getMain(); float frontPressure = front.pressure().getPressure(pumpLiquid), backPressure = back.pressure().getPressure(pumpLiquid); float flow = pressureTransfer * (backPressure - frontPressure + pressureDifference); if (pumpLiquid != null) flow = Mathf.clamp(flow, -front.pressure().liquids[pumpLiquid.id], back.pressure().liquids[pumpLiquid.id]); diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidValve.java b/src/omaloon/world/blocks/liquid/PressureLiquidValve.java index 27e78ca2..bc96b85b 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidValve.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidValve.java @@ -13,8 +13,7 @@ import mindustry.gen.*; import mindustry.graphics.*; import mindustry.type.*; -import mindustry.world.blocks.liquid.*; -import mindustry.world.blocks.sandbox.*; +import mindustry.world.*; import omaloon.content.*; import omaloon.utils.*; import omaloon.world.interfaces.*; @@ -24,23 +23,25 @@ import static mindustry.Vars.*; import static mindustry.type.Liquid.*; -public class PressureLiquidValve extends LiquidBlock { +public class PressureLiquidValve extends Block { public PressureConfig pressureConfig = new PressureConfig(); public TextureRegion[] tiles; public TextureRegion[][] liquidRegions; - public TextureRegion valveRegion, topRegion; + public TextureRegion valveRegion, topRegion, bottomRegion; + public Effect jamEffect = Fx.explosion; public Sound jamSound = OlSounds.jam; public Effect pumpingEffect = OlFx.pumpBack; - public Effect jamEffect = Fx.explosion; public float pumpingEffectInterval = 15; public float pressureLoss = 0.05f; + public float minPressureLoss = 0.05f; public float openMin = -15f; - public float jamPoint = -20f; + public float openMax = 15f; + public float jamPoint = -45f; public float liquidPadding = 3f; @@ -81,7 +82,7 @@ public void load() { tiles = OlUtils.split(name + "-tiles", 32, 0); valveRegion = Core.atlas.find(name + "-valve"); topRegion = Core.atlas.find(name + "-top"); - if (!bottomRegion.found()) bottomRegion = Core.atlas.find("omaloon-liquid-bottom"); + bottomRegion = Core.atlas.find(name + "-top", "omaloon-liquid-bottom"); liquidRegions = new TextureRegion[2][animationFrames]; if(renderer != null){ @@ -117,7 +118,7 @@ public void setStats() { stats.add(OlStats.pressureFlow, Mathf.round(pressureLoss * 60f, 2), OlStats.pressureSecond); } - public class PressureLiquidValveBuild extends LiquidBuild implements HasPressure { + public class PressureLiquidValveBuild extends Building implements HasPressure { PressureModule pressure = new PressureModule(); public float draining; @@ -127,13 +128,8 @@ public class PressureLiquidValveBuild extends LiquidBuild implements HasPressure public boolean jammed; @Override - public boolean acceptLiquid(Building source, Liquid liquid) { - return hasLiquids; - } - - @Override - public boolean canDumpLiquid(Building to, Liquid liquid) { - return super.canDumpLiquid(to, liquid) || to instanceof LiquidVoid.LiquidVoidBuild; + public boolean acceptsPressurizedFluid(HasPressure from, @Nullable Liquid liquid, float amount) { + return HasPressure.super.acceptsPressurizedFluid(from, liquid, amount) && (liquid == pressure.getMain() || liquid == null || pressure.getMain() == null || from.pressure().getMain() == null); } @Override @@ -147,13 +143,14 @@ public boolean connects(HasPressure to) { public void draw() { float rot = rotate ? (90 + rotdeg()) % 180 - 90 : 0; Draw.rect(bottomRegion, x, y, rotation); - if (liquids().currentAmount() > 0.01f) { - int frame = liquids.current().getAnimationFrame(); - int gas = liquids.current().gas ? 1 : 0; + Liquid main = pressure.getMain(); + if (main != null && pressure.liquids[main.id] > 0.01f) { + int frame = main.getAnimationFrame(); + int gas = main.gas ? 1 : 0; float xscl = Draw.xscl, yscl = Draw.yscl; Draw.scl(1f, 1f); - Drawf.liquid(liquidRegions[gas][frame], x, y, liquids.currentAmount()/liquidCapacity, liquids.current().color.write(Tmp.c1).a(1f)); + Drawf.liquid(liquidRegions[gas][frame], x, y, Mathf.clamp(pressure.liquids[main.id]/(pressure.liquids[main.id] + pressure.air)), main.color.write(Tmp.c1).a(1f)); Draw.scl(xscl, yscl); } Draw.rect(tiles[tiling], x, y, rot); @@ -164,10 +161,18 @@ public void draw() { @Override public void onProximityUpdate() { super.onProximityUpdate(); + tiling = 0; boolean inverted = rotation == 1 || rotation == 2; if (front() instanceof HasPressure front && connected(front)) tiling |= inverted ? 2 : 1; if (back() instanceof HasPressure back && connected(back)) tiling |= inverted ? 1 : 2; + + new PressureSection().mergeFlood(this); + } + + @Override + public boolean outputsPressurizedFluid(HasPressure to, Liquid liquid, float amount) { + return HasPressure.super.outputsPressurizedFluid(to, liquid, amount) && (liquid == to.pressure().getMain() || liquid == null || pressure.getMain() == null || to.pressure().getMain() == null); } @Override public PressureModule pressure() { @@ -188,11 +193,14 @@ public void read(Reads read, byte revision) { @Override public void updatePressure() { HasPressure.super.updatePressure(); - if (getPressure() >= jamPoint) jammed = false; + + float pressureAmount = pressure.getPressure(pressure.getMain()); + + if (pressureAmount > jamPoint) jammed = false; if (jammed) return; - if (getPressure() <= openMin) { + if (pressureAmount < openMin) { effectInterval += delta(); - handlePressure(pressureLoss * Time.delta); + addFluid(null, Math.max(minPressureLoss, pressureLoss * Math.abs(pressureAmount - openMin)/10f)); draining = Mathf.approachDelta(draining, 1, 0.014f); if (effectInterval > pumpingEffectInterval) { @@ -200,10 +208,22 @@ public void updatePressure() { pumpingEffect.at(x, y, -draining * (rotation % 2 == 0 ? 90 : -90) - (rotate ? (90 - rotdeg()) % 180 - 90 : 0), liquids.current()); pumpingEffect.at(x, y, draining * (rotation % 2 == 0 ? -90 : 90) + (rotate ? (90 + rotdeg()) % 180 - 90 : 0), liquids.current()); } + }; + if (pressureAmount > openMax) { + effectInterval += delta(); + removeFluid(pressure.getMain(), Math.max(minPressureLoss, pressureLoss * Math.abs(pressureAmount - openMax)/10f)); + draining = Mathf.approachDelta(draining, 1, 0.014f); - } else draining = Mathf.approachDelta(draining, 0, 0.014f); + if (effectInterval > pumpingEffectInterval) { + effectInterval = 0; + pumpingEffect.at(x, y, -draining * (rotation % 2 == 0 ? 90 : -90) - (rotate ? (90 - rotdeg()) % 180 - 90 : 0), liquids.current()); + pumpingEffect.at(x, y, draining * (rotation % 2 == 0 ? -90 : 90) + (rotate ? (90 + rotdeg()) % 180 - 90 : 0), liquids.current()); + } + }; + + if (pressureAmount < openMin && pressureAmount > openMax) draining = Mathf.approachDelta(draining, 0, 0.014f); - if (getPressure() < jamPoint) { + if (pressureAmount < jamPoint) { jammed = true; draining = 0f; jamEffect.at(x, y, draining * (rotation%2 == 0 ? -90 : 90) + (rotate ? (90 + rotdeg()) % 180 - 90 : 0), valveRegion); @@ -213,12 +233,6 @@ public void updatePressure() { @Override public void updateTile() { updatePressure(); - nextBuilds(true).each(b -> moveLiquidPressure(b, liquids.current())); - dumpPressure(); - } - - @Override public byte version() { - return 1; } @Override diff --git a/src/omaloon/world/interfaces/HasPressure.java b/src/omaloon/world/interfaces/HasPressure.java index be4796e4..c540cc62 100644 --- a/src/omaloon/world/interfaces/HasPressure.java +++ b/src/omaloon/world/interfaces/HasPressure.java @@ -159,8 +159,8 @@ default void removeFluid(@Nullable Liquid liquid, float amount) { */ default void updatePressure() { Vars.content.liquids().each(liquid -> { - if (Mathf.round(pressure().getPressure(liquid)) <= pressureConfig().minPressure) damage(pressureConfig().underPressureDamage); - if (Mathf.round(pressure().getPressure(liquid)) >= pressureConfig().maxPressure) damage(pressureConfig().overPressureDamage); + if (Mathf.round(pressure().getPressure(liquid)) < pressureConfig().minPressure - 1) damage(pressureConfig().underPressureDamage); + if (Mathf.round(pressure().getPressure(liquid)) > pressureConfig().maxPressure + 1) damage(pressureConfig().overPressureDamage); }); } From 2ac4f87e7c3964d378752dc27d1722499c7f8b41 Mon Sep 17 00:00:00 2001 From: = Date: Tue, 10 Dec 2024 00:05:42 -0300 Subject: [PATCH 10/67] air well --- assets/bundles/bundle.properties | 3 + .../blocks/crafting/air-well-cap-from.png | Bin 0 -> 293 bytes .../blocks/crafting/air-well-cap-to.png | Bin 0 -> 296 bytes .../blocks/crafting/air-well-overlay.png | Bin 0 -> 275 bytes assets/sprites/blocks/crafting/air-well.png | Bin 0 -> 479 bytes .../content/blocks/OlProductionBlocks.java | 19 +- .../blocks/liquid/PressureLiquidJunction.java | 20 +- .../blocks/liquid/PressureLiquidPump.java | 1 - .../blocks/liquid/PressureLiquidValve.java | 2 + .../world/blocks/production/Pressurizer.java | 180 ++++++++++++++++++ 10 files changed, 212 insertions(+), 13 deletions(-) create mode 100644 assets/sprites/blocks/crafting/air-well-cap-from.png create mode 100644 assets/sprites/blocks/crafting/air-well-cap-to.png create mode 100644 assets/sprites/blocks/crafting/air-well-overlay.png create mode 100644 assets/sprites/blocks/crafting/air-well.png create mode 100644 src/omaloon/world/blocks/production/Pressurizer.java diff --git a/assets/bundles/bundle.properties b/assets/bundles/bundle.properties index 24801afb..32f0bf61 100644 --- a/assets/bundles/bundle.properties +++ b/assets/bundles/bundle.properties @@ -327,6 +327,9 @@ block.omaloon-impulse-node.description = Transmits power to connected buildings. block.omaloon-hammer-drill.name = Hammer drill block.omaloon-hammer-drill.description = When placed on ore, outputs items. Efficiency increases with decreasing pressure inside, reaching peak performance in near vacuum conditions. +block.omaloon-air-well.name = Air Well +block.omaloon-air-well.description = Constantly pulls air in or out. + ## stats category.omaloon-pressure = Pressure stat.omaloon-consumepressure = Consume Pressure diff --git a/assets/sprites/blocks/crafting/air-well-cap-from.png b/assets/sprites/blocks/crafting/air-well-cap-from.png new file mode 100644 index 0000000000000000000000000000000000000000..3607131eded34ffe0718b648f5a381eed0644eef GIT binary patch literal 293 zcmeAS@N?(olHy`uVBq!ia0vp^3LwnE1|*BCs=fdz&H|6fVg?3oVGw3ym^DWND0tn| z#W5tJ_3cz$zC#WoE$n(uRh?2QvlI+H4oP}kP?^&RWHq@ZRdxFM2Zc-y`j(#NE&6`) z?#bt-r+wE=kobSjg;PI#x7xPvJgeZ!m$F(j zh6h>g;h`(#uFU6PyY*?>MwLCY|9;wcWRH&hwcsSf&L@&Dg3ffUFJic7D&~3Ms@{(2 z+KQY#jhrXi4P4HNPGxlxT6p`Q1HTg6{SBw2T=q|rFzIUddcz<6%5{m;sv}jK7tBw# nI^m`9bP|K|!fDcNj12j69TV@J{20C%=tTxkS3j3^P6|;&^`NRUr1tC8D!sRwzS|Dj3Vm@gi;jcNrs%S_)IFrj)q$_oHJyLRNz;P z`s{InDS0wW%yfgc=bgL!7I-Utv(j1OcI3jbP0l+XkKuw8L$ literal 0 HcmV?d00001 diff --git a/assets/sprites/blocks/crafting/air-well-overlay.png b/assets/sprites/blocks/crafting/air-well-overlay.png new file mode 100644 index 0000000000000000000000000000000000000000..63b7d6d51e5e68d4534b9c34a8f548b8ea4dfd9a GIT binary patch literal 275 zcmeAS@N?(olHy`uVBq!ia0vp^3LwnE1|*BCs=fdz&H|6fVg?3oVGw3ym^DWND0tM< z#W5tJ_3iYHyoU?~T<70anxdua9FWE%mMA8c*fT}4$t*NwY1^p+Gd|8q{+aKte*2q# zvvq&%nuG57=H^Ek~6=;Gkvo#V}r&-{S}H6&z~^Gs5XTLP5#yq)E5d}&Gq7yHGYEh^X2RIchwzpx@LamK{fAFHL^ID50y_$5^1e%nrL UF0>ST3-l0!r>mdKI;Vst0N!tGjQ{`u literal 0 HcmV?d00001 diff --git a/assets/sprites/blocks/crafting/air-well.png b/assets/sprites/blocks/crafting/air-well.png new file mode 100644 index 0000000000000000000000000000000000000000..6baf3053916180f1a975bf1d472fbedcafbb1619 GIT binary patch literal 479 zcmV<50U-W~P)Bw(q!BQa44v9MH~5JN@RZhS&N zqJO~(Kf%IMKBDT9L~7NMfh7#c!Ex+MD&-Ca-gxo(y*r;BJDH5e#nH(zICh&Yrn5OL ztkx@aeb676d!C;bkURk3(k#brv#pTRhOR)qI8P}607!&1utaDlwN5X6NRH(C;<5mM z^Rv_1=BwL>Mgj{wOz*ERweJ)T*M?j=+=pEA1^nEEYeT+|2+PJ2k=)%s76%{eM)Iz} z!!e!BzeDhO*pEWaIVjB?eIOArz-x^2*hN7_z}s>eoKU87?FK@M&}xYqf)FCCLe{$( z4ug^UK=q=$0TL3EydvPY@Gqbg5c3i8jOfLF{ZfP)f)E*D{ibUILZ+i8q9PzhEs!Gq zP8RU4C^UGd>^QmBy><=aAQ8!AG%lo(uQh8*Ti-j<4(QS>Z)Mnq+-GCW2IXYbv|*ou zC2f6!NjVt-`ha3JtMaNXf!5=$OhyEG6K%<@HO)tw<=_KxtqzcgF57hS#Scg#z5u%z V!)v0F=^p?9002ovPDHLkV1ip*&!YeU literal 0 HcmV?d00001 diff --git a/src/omaloon/content/blocks/OlProductionBlocks.java b/src/omaloon/content/blocks/OlProductionBlocks.java index 6434d455..b0575f9b 100644 --- a/src/omaloon/content/blocks/OlProductionBlocks.java +++ b/src/omaloon/content/blocks/OlProductionBlocks.java @@ -1,8 +1,10 @@ package omaloon.content.blocks; +import arc.math.*; import mindustry.entities.effect.*; import mindustry.type.*; import mindustry.world.*; +import mindustry.world.draw.*; import omaloon.content.*; import omaloon.world.blocks.production.*; import omaloon.world.consumers.*; @@ -11,7 +13,7 @@ public class OlProductionBlocks { public static Block - hammerDrill, + hammerDrill, pressurizer, end; @@ -34,5 +36,20 @@ public static void load(){ consume(new ConsumePressure(-6, false)); consume(new PressureEfficiencyRange(-45f, -1f, 2f, true)); }}; + + pressurizer = new Pressurizer("air-well") {{ + requirements(Category.production, with( + OlItems.cobalt, 10 + )); + outputPressure = 5f; + + drawer = new DrawMulti( + new DrawDefault(), + new DrawTransition() {{ + suffix = "-cap"; + interp = a -> Interp.sine.apply(Interp.slope.apply(a)); + }} + ); + }}; } } diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidJunction.java b/src/omaloon/world/blocks/liquid/PressureLiquidJunction.java index 867b5632..b7df79a7 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidJunction.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidJunction.java @@ -3,29 +3,23 @@ import arc.struct.*; import arc.util.io.*; import mindustry.gen.*; -import mindustry.type.*; -import mindustry.world.blocks.liquid.*; +import mindustry.world.*; import omaloon.world.interfaces.*; import omaloon.world.meta.*; import omaloon.world.modules.*; -public class PressureLiquidJunction extends LiquidJunction { +public class PressureLiquidJunction extends Block { public PressureConfig pressureConfig = new PressureConfig(); public PressureLiquidJunction(String name) { super(name); + update = true; + destructible = true; } - public class PressureLiquidJunctionBuild extends LiquidJunctionBuild implements HasPressure { + public class PressureLiquidJunctionBuild extends Building implements HasPressure { PressureModule pressure = new PressureModule(); - @Override public boolean acceptLiquid(Building source, Liquid liquid) { - return false; - } - @Override public boolean acceptsPressure(HasPressure from, float pressure) { - return false; - } - @Override public boolean connects(HasPressure to) { return HasPressure.super.connects(to) && !(to instanceof PressureLiquidPump); @@ -43,6 +37,10 @@ public HasPressure getPressureDestination(HasPressure source, float pressure) { return next.getPressureDestination(this, pressure); } + @Override public HasPressure getSectionDestination(HasPressure from) { + return null; + } + @Override public Seq nextBuilds(boolean flow) { return Seq.with(); diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidPump.java b/src/omaloon/world/blocks/liquid/PressureLiquidPump.java index ecdc3200..0b33977a 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidPump.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidPump.java @@ -43,7 +43,6 @@ public PressureLiquidPump(String name) { rotate = true; destructible = true; update = true; - configurable = true; saveConfig = copyConfig = true; config(Liquid.class, (PressureLiquidPumpBuild build, Liquid liquid) -> { build.filter = liquid.id; diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidValve.java b/src/omaloon/world/blocks/liquid/PressureLiquidValve.java index bc96b85b..65c9685b 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidValve.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidValve.java @@ -48,6 +48,8 @@ public class PressureLiquidValve extends Block { public PressureLiquidValve(String name) { super(name); rotate = true; + update = true; + destructible = true; } @Override diff --git a/src/omaloon/world/blocks/production/Pressurizer.java b/src/omaloon/world/blocks/production/Pressurizer.java new file mode 100644 index 00000000..3e7a0bd1 --- /dev/null +++ b/src/omaloon/world/blocks/production/Pressurizer.java @@ -0,0 +1,180 @@ +package omaloon.world.blocks.production; + +import arc.*; +import arc.Graphics.*; +import arc.graphics.g2d.*; +import arc.math.*; +import arc.struct.*; +import arc.util.*; +import arc.util.io.*; +import mindustry.entities.units.*; +import mindustry.gen.*; +import mindustry.world.*; +import mindustry.world.draw.*; +import mindustry.world.meta.*; +import omaloon.world.interfaces.*; +import omaloon.world.meta.*; +import omaloon.world.modules.*; + +public class Pressurizer extends Block { + public PressureConfig pressureConfig = new PressureConfig(); + + public DrawBlock drawer = new DrawDefault(); + + public TextureRegion overlayRegion; + + public float progressTime = 60f; + public float warmupSpeed = 0.14f; + + public float outputPressure = 0f; + + public boolean continuous = false; + + public Pressurizer(String name) { + super(name); + update = true; + destructible = true; + solid = true; + + config(Boolean.class, (PressurizerBuild build, Boolean bool) -> build.reverse = bool); + } + + @Override + public void drawPlanRegion(BuildPlan plan, Eachable list) { + drawer.drawPlan(this, plan, list); + if (plan.config instanceof Boolean bool && bool) Draw.rect(overlayRegion, plan.drawx(), plan.drawy(), rotate ? plan.rotation * 90f : 0); + } + + @Override public void getRegionsToOutline(Seq out) { + drawer.getRegionsToOutline(this, out); + } + + @Override + protected TextureRegion[] icons() { + return drawer.finalIcons(this); + } + + @Override + public void load() { + super.load(); + + drawer.load(this); + + overlayRegion = Core.atlas.find(name + "-overlay"); + } + + @Override + public void setBars() { + super.setBars(); + + pressureConfig.addBars(this); + } + + @Override + public void setStats() { + super.setStats(); + + pressureConfig.addStats(stats); + if (outputPressure != 0) stats.add(OlStats.outputPressure, Strings.autoFixed(outputPressure * (continuous ? 60f : 1f), 2), continuous ? OlStats.pressureSecond : OlStats.pressureUnits); + if (!continuous) stats.add(Stat.productionTime, Strings.autoFixed(progressTime/60f, 2), StatUnit.seconds); + } + + public class PressurizerBuild extends Building implements HasPressure { + public PressureModule pressure = new PressureModule(); + + public boolean reverse; + + public float warmup, progress, totalProgress; + + @Override public Cursor getCursor() { + return Cursor.SystemCursor.hand; + } + + @Override + public void draw() { + drawer.draw(this); + if (reverse) Draw.rect(overlayRegion, x, y, drawrot()); + } + @Override + public void drawLight() { + super.drawLight(); + drawer.drawLight(this); + } + + @Override public HasPressure getSectionDestination(HasPressure from) { + return null; + } + + @Override + public void onProximityUpdate() { + super.onProximityUpdate(); + + new PressureSection().mergeFlood(this); + } + + @Override public PressureModule pressure() { + return pressure; + } + @Override public PressureConfig pressureConfig() { + return pressureConfig; + } + + @Override public float progress() { + return progress; + } + + @Override + public void read(Reads read, byte revision) { + super.read(read, revision); + pressure.read(read); + + progress = read.f(); + totalProgress = read.f(); + warmup = read.f(); + + reverse = read.bool(); + } + + @Override public void tapped() { + configure(!reverse); + } + + @Override public float totalProgress() { + return totalProgress; + } + + @Override + public void updateTile() { + updatePressure(); + + if (efficiency > 0) { + progress += getProgressIncrease(progressTime); + warmup = Mathf.approachDelta(warmup, 1, warmupSpeed); + totalProgress += warmup * edelta(); + + if (continuous) addFluid(null, outputPressure * warmup * (reverse ? -1f : 1f)); + } else warmup = Mathf.approachDelta(warmup, 0, warmupSpeed); + + if(progress >= 1f){ + if (!continuous) addFluid(null, outputPressure * warmup * (reverse ? -1f : 1f)); + progress %= 1f; + } + } + + @Override public float warmup() { + return warmup; + } + + @Override + public void write(Writes write) { + super.write(write); + pressure.write(write); + + write.f(progress); + write.f(totalProgress); + write.f(warmup); + + write.bool(reverse); + } + } +} From 992cd800603dab092020e7cca51679d956e05bc8 Mon Sep 17 00:00:00 2001 From: = Date: Tue, 17 Dec 2024 01:11:43 -0300 Subject: [PATCH 11/67] shelter --- assets/bundles/bundle.properties | 2 + .../content/blocks/OlDefenceBlocks.java | 43 ++++--- src/omaloon/world/blocks/defense/Shelter.java | 21 +++- .../blocks/liquid/PressureLiquidValve.java | 10 +- src/omaloon/world/consumers/ConsumeFluid.java | 108 ++++++++++++++++++ src/omaloon/world/meta/OlStats.java | 35 ++++++ 6 files changed, 192 insertions(+), 27 deletions(-) create mode 100644 src/omaloon/world/consumers/ConsumeFluid.java diff --git a/assets/bundles/bundle.properties b/assets/bundles/bundle.properties index 32f0bf61..ce4c5779 100644 --- a/assets/bundles/bundle.properties +++ b/assets/bundles/bundle.properties @@ -341,6 +341,8 @@ stat.omaloon-outputpressure = Output Pressure stat.omaloon-pressureflow = Speed stat.omaloon-pressurerange = Operating Range stat.omaloon-pressurerange.format = from \uC357 @ pressure units to \uC357 @ pressure units. +stat.omaloon-optimal-pressure = Optimal Pressure +stat.omaloon-optimal-pressure.format = \uC357 @ pressure units (@%) ## ui units unit.omaloon-pressuresecond = pressure units / second diff --git a/src/omaloon/content/blocks/OlDefenceBlocks.java b/src/omaloon/content/blocks/OlDefenceBlocks.java index fbd4cc29..d6b6490d 100644 --- a/src/omaloon/content/blocks/OlDefenceBlocks.java +++ b/src/omaloon/content/blocks/OlDefenceBlocks.java @@ -48,22 +48,33 @@ public static void load(){ }}; smallShelter = new Shelter("small-shelter") {{ - requirements(Category.effect, with( - OlItems.cobalt, 25, - Items.beryllium, 30 - )); - researchCostMultiplier = 0.3f; - size = 2; - rechargeStandard = 2f; - shieldHealth = 260f; - shieldRange = 170f; - - ambientSound = OlSounds.shelter; - ambientSoundVolume = 0.08f; - - consumePower(0.2f); - consume(new ConsumePressure(0.01f, true)); - consume(new PressureEfficiencyRange(15, 50f, 1.8f, false)); + requirements(Category.effect, with( + OlItems.cobalt, 25, + Items.beryllium, 30 + )); + researchCostMultiplier = 0.3f; + size = 2; + rechargeStandard = 2f; + shieldHealth = 260f; + shieldRange = 170f; + + ambientSound = OlSounds.shelter; + ambientSoundVolume = 0.08f; + + consumePower(0.2f); + consume(new ConsumeFluid(null, 0.1f) {{ + continuous = true; + hasOptimalPressure = true; + + startRange = 15f; + endRange = 50f; + efficiencyMultiplier = 2f; + optimalPressure = 46.5f; + + curve = t -> Math.max(0f, Mathf.slope(t - 0.25f) * 2f - 1f); + }}); +// consume(new ConsumePressure(0.01f, true)); +// consume(new PressureEfficiencyRange(15, 50f, 1.8f, false)); }}; //endregion //region turrets diff --git a/src/omaloon/world/blocks/defense/Shelter.java b/src/omaloon/world/blocks/defense/Shelter.java index 5fc0611a..558a69e6 100644 --- a/src/omaloon/world/blocks/defense/Shelter.java +++ b/src/omaloon/world/blocks/defense/Shelter.java @@ -81,7 +81,6 @@ public Shelter(String name) { solid = true; configurable = true; saveConfig = true; - hasLiquids = true; group = BlockGroup.projectors; ambientSound = Sounds.shield; ambientSoundVolume = 0.08f; @@ -220,6 +219,13 @@ public boolean onConfigureTapped(float x, float y) { return false; } + @Override + public void onProximityUpdate() { + super.onProximityUpdate(); + + new PressureSection().mergeFlood(this); + } + @Override public PressureModule pressure() { return pressure; } @@ -251,12 +257,15 @@ public void updateTile() { if (broken) { warmup = Mathf.approachDelta(warmup, 0f, warmupTime); } else { - warmup = Mathf.approachDelta(warmup, efficiency, warmupTime); + warmup = Mathf.approachDelta(warmup, efficiency * efficiencyMultiplier(), warmupTime); + + float radius = shieldRange * warmup + shieldBuffer; + Groups.bullet.intersect( - x - shieldRange - shieldBuffer, - y - shieldRange - shieldBuffer, - (shieldRange + shieldBuffer) * 2f, - (shieldRange + shieldBuffer) * 2f, + x - radius, + y - radius, + radius * 2f, + radius * 2f, b -> { if (b.team == Team.derelict) { float distance = Mathf.dst(x, y, b.x, b.y); diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidValve.java b/src/omaloon/world/blocks/liquid/PressureLiquidValve.java index 65c9685b..2ad7fc4d 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidValve.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidValve.java @@ -84,7 +84,7 @@ public void load() { tiles = OlUtils.split(name + "-tiles", 32, 0); valveRegion = Core.atlas.find(name + "-valve"); topRegion = Core.atlas.find(name + "-top"); - bottomRegion = Core.atlas.find(name + "-top", "omaloon-liquid-bottom"); + bottomRegion = Core.atlas.find(name + "-bottom", "omaloon-liquid-bottom"); liquidRegions = new TextureRegion[2][animationFrames]; if(renderer != null){ @@ -207,8 +207,8 @@ public void updatePressure() { if (effectInterval > pumpingEffectInterval) { effectInterval = 0; - pumpingEffect.at(x, y, -draining * (rotation % 2 == 0 ? 90 : -90) - (rotate ? (90 - rotdeg()) % 180 - 90 : 0), liquids.current()); - pumpingEffect.at(x, y, draining * (rotation % 2 == 0 ? -90 : 90) + (rotate ? (90 + rotdeg()) % 180 - 90 : 0), liquids.current()); + pumpingEffect.at(x, y, -draining * (rotation % 2 == 0 ? 90 : -90) - (rotate ? (90 - rotdeg()) % 180 - 90 : 0), pressure.getMain()); + pumpingEffect.at(x, y, draining * (rotation % 2 == 0 ? -90 : 90) + (rotate ? (90 + rotdeg()) % 180 - 90 : 0), pressure.getMain()); } }; if (pressureAmount > openMax) { @@ -218,8 +218,8 @@ public void updatePressure() { if (effectInterval > pumpingEffectInterval) { effectInterval = 0; - pumpingEffect.at(x, y, -draining * (rotation % 2 == 0 ? 90 : -90) - (rotate ? (90 - rotdeg()) % 180 - 90 : 0), liquids.current()); - pumpingEffect.at(x, y, draining * (rotation % 2 == 0 ? -90 : 90) + (rotate ? (90 + rotdeg()) % 180 - 90 : 0), liquids.current()); + pumpingEffect.at(x, y, -draining * (rotation % 2 == 0 ? 90 : -90) - (rotate ? (90 - rotdeg()) % 180 - 90 : 0), pressure.getMain()); + pumpingEffect.at(x, y, draining * (rotation % 2 == 0 ? -90 : 90) + (rotate ? (90 + rotdeg()) % 180 - 90 : 0), pressure.getMain()); } }; diff --git a/src/omaloon/world/consumers/ConsumeFluid.java b/src/omaloon/world/consumers/ConsumeFluid.java new file mode 100644 index 00000000..0441db47 --- /dev/null +++ b/src/omaloon/world/consumers/ConsumeFluid.java @@ -0,0 +1,108 @@ +package omaloon.world.consumers; + +import arc.*; +import arc.math.*; +import arc.util.*; +import mindustry.gen.*; +import mindustry.type.*; +import mindustry.world.consumers.*; +import mindustry.world.meta.*; +import omaloon.world.interfaces.*; +import omaloon.world.meta.*; + +public class ConsumeFluid extends Consume { + /** + * Fluid used by this consumer, if null, air is used + */ + public @Nullable Liquid fluid; + /** + * Amount of fluid consumed, will always be positive if fluid isn't air. + */ + public float amount; + /** + * If true, fluid is consumed per tick and not per craft. + */ + public boolean continuous; + + /** + * Min pressure required for this consumer to function. + */ + public float startRange; + /** + * Max pressure allowed for this consumer to function. + */ + public float endRange; + /** + * Efficiency multiplier of this consumer. Based on pressure. + */ + public float efficiencyMultiplier = 1f; + /** + * Pressure whose building's efficiency is at it's peak. + */ + public float optimalPressure; + /** + * Whether to display the optimal pressure. + */ + public boolean hasOptimalPressure = false; + /** + * Interpolation curve used to determine efficiency. 0 is startRange, 1 is endRange. + */ + public Interp curve = Interp.one; + + public ConsumeFluid(@Nullable Liquid fluid, float amount) { + this.fluid = fluid; + this.amount = amount; + } + + public HasPressure cast(Building build) { + try { + return (HasPressure) build; + } catch(Exception e) { + throw new RuntimeException("This consumer should be used on a building that implements HasPressure", e); + } + } + + @Override + public void display(Stats stats) { + if (amount != 0) { + if (continuous) { + stats.add(OlStats.removeFluid, OlStats.fluid(fluid, amount, 1f, true)); + } else { + stats.add(OlStats.removeFluid, OlStats.fluid(fluid, amount, 60f, false)); + } + } + + if (startRange != endRange) { + stats.add(OlStats.pressureRange, Core.bundle.get("stat.omaloon-pressurerange.format"), Strings.autoFixed(startRange, 2), Strings.autoFixed(endRange, 2)); + if (hasOptimalPressure) stats.add(OlStats.optimalPressure, Core.bundle.get("stat.omaloon-optimal-pressure.format"), Strings.autoFixed(optimalPressure, 2), Strings.autoFixed(efficiencyMultiplier, 2)); + } + } + + @Override + public float efficiency(Building build) { + if (!shouldConsume(cast(build))) return 0f; + return 1f; + } + @Override + public float efficiencyMultiplier(Building build) { + if (!shouldConsume(cast(build))) return 0f; + return curve.apply(1f, efficiencyMultiplier, Mathf.clamp(Mathf.map(cast(build).pressure().getPressure(fluid), startRange, endRange, 0f, 1f))); + + } + + public boolean shouldConsume(HasPressure build) { + if (startRange == endRange) return true; + return startRange <= build.getPressure() && build.getPressure() <= endRange && (fluid == null || build.pressure().liquids[fluid.id] > amount); + } + + @Override public void trigger(Building build) { + if (!continuous && shouldConsume(cast(build))) { + cast(build).removeFluid(fluid, amount); + } + } + @Override public void update(Building build) { + if (continuous && shouldConsume(cast(build))) { + cast(build).removeFluid(fluid, amount * Time.delta); + } + } +} diff --git a/src/omaloon/world/meta/OlStats.java b/src/omaloon/world/meta/OlStats.java index 235fe25f..e98a6c50 100644 --- a/src/omaloon/world/meta/OlStats.java +++ b/src/omaloon/world/meta/OlStats.java @@ -1,7 +1,16 @@ package omaloon.world.meta; +import arc.*; +import arc.graphics.*; +import arc.scene.ui.*; +import arc.scene.ui.layout.*; +import arc.util.*; +import mindustry.type.*; +import mindustry.ui.*; import mindustry.world.meta.*; +import static mindustry.Vars.*; + public class OlStats { public static final StatCat pressure = new StatCat("omaloon-pressure"); @@ -9,15 +18,41 @@ public class OlStats { minSpeed = new Stat("omaloon-min-speed"), maxSpeed = new Stat("omaloon-max-speed"), + addFluid = new Stat("omaloon-add-fluid", StatCat.crafting), + removeFluid = new Stat("omaloon-remove-fluid", StatCat.crafting), + pressureFlow = new Stat("omaloon-pressureflow", pressure), maxPressure = new Stat("omaloon-maxPressure", pressure), minPressure = new Stat("omaloon-minPressure", pressure), consumePressure = new Stat("omaloon-consumePressure", pressure), pressureRange = new Stat("omaloon-pressurerange", pressure), + optimalPressure = new Stat("omaloon-optimal-pressure", pressure), outputPressure = new Stat("omaloon-outputPressure", pressure); public static final StatUnit pressureUnits = new StatUnit("omaloon-pressureUnits", "\uC357"), pressureSecond = new StatUnit("omaloon-pressureSecond", "\uC357"); + + public static StatValue fluid(@Nullable Liquid liquid, float amount, float time, boolean showContinuous) { + return table -> { + table.table(display -> { + display.add(new Stack() {{ + add(new Image(liquid != null ? liquid.uiIcon : Core.atlas.find("omaloon-pressure-icon")).setScaling(Scaling.fit)); + + if (amount * 60f/time != 0) { + Table t = new Table().left().bottom(); + t.add(Strings.autoFixed(amount * 60f/time, 2)).style(Styles.outlineLabel); + add(t); + } + }}).size(iconMed).padRight(3 + (amount * 60f/time != 0 && Strings.autoFixed(amount * 60f/time, 2).length() > 2 ? 8 : 0)); + + if(showContinuous){ + display.add(StatUnit.perSecond.localized()).padLeft(2).padRight(5).color(Color.lightGray).style(Styles.outlineLabel); + } + + display.add(liquid != null ? liquid.localizedName : "@air"); + }); + }; + } } From 80bb54edef7f594d9c54ead91e4f7a584c06e37a Mon Sep 17 00:00:00 2001 From: = Date: Tue, 17 Dec 2024 17:25:25 -0300 Subject: [PATCH 12/67] valve effect fix --- src/omaloon/content/OlFx.java | 48 +++++++++++++------ .../content/blocks/OlDefenceBlocks.java | 2 +- .../blocks/liquid/PressureLiquidValve.java | 29 +++++------ src/omaloon/world/interfaces/HasPressure.java | 11 ++--- 4 files changed, 53 insertions(+), 37 deletions(-) diff --git a/src/omaloon/content/OlFx.java b/src/omaloon/content/OlFx.java index cb0d053a..228532b2 100644 --- a/src/omaloon/content/OlFx.java +++ b/src/omaloon/content/OlFx.java @@ -182,26 +182,44 @@ public class OlFx { Draw.blend(); }), - pumpFront = new Effect(60f, e -> { - Draw.alpha(e.fout() / 5f); + pumpOut = new Effect(60f, e -> { + Draw.color(e.color); + Draw.alpha(e.fout() / 5); vec.trns(e.rotation, 4f).add(e.x, e.y); - randLenVectors(e.id, 3, 16f * e.fin(), e.rotation, 10f, (x, y) -> { - Fill.circle(vec.x + x, vec.y + y, 3f * e.fin()); + Angles.randLenVectors(e.id, 3, 16 * e.fin(), e.rotation + 180, 10, (x, y) -> { + Fill.circle(vec.x + x, vec.y + y, 3 * e.fin()); + }); + vec.trns(e.rotation, -4f).add(e.x, e.y); + Angles.randLenVectors(e.id + 2, 3, 16 * e.fin(), e.rotation, 10, (x, y) -> { + Fill.circle(vec.x + x, vec.y + y, 3 * e.fin()); }); - Draw.alpha(e.fout() / 7f); - randLenVectors(e.id/2, 3, 16f * e.fin(), e.rotation, 20f, (x, y) -> { - Fill.rect(vec.x + x, vec.y + y, 5f * e.fin(), e.fin(), vec.angleTo(vec.x + x, vec.y + y)); + Draw.alpha(e.fout() / 7); + Angles.randLenVectors(e.id + 1, 3, 16 * e.fin(), e.rotation, 20, (x, y) -> { + Fill.rect(vec.x + x, vec.y + y, 5 * e.fin(), e.fin(), vec.angleTo(vec.x + x, vec.y + y)); + }); + vec.trns(e.rotation, 4f).add(e.x, e.y); + Angles.randLenVectors(e.id + 3, 3, 16 * e.fin(), e.rotation + 180, 20, (x, y) -> { + Fill.rect(vec.x + x, vec.y + y, 5 * e.fin(), e.fin(), vec.angleTo(vec.x + x, vec.y + y)); }); }), - pumpBack = new Effect(60f, e -> { - Draw.alpha(e.fin() / 5f); - vec.trns(e.rotation, 4).add(e.x, e.y); - randLenVectors(e.id, 3, 16f * e.fout(), e.rotation, 10f, (x, y) -> { - Fill.circle(vec.x + x, vec.y + y, 3f * e.fout()); + pumpIn = new Effect(60f, e -> { + Draw.color(e.color); + Draw.alpha(e.fin() / 5); + vec.trns(e.rotation, 4f).add(e.x, e.y); + Angles.randLenVectors(e.id, 3, 16 * e.fout(), e.rotation, 10, (x, y) -> { + Fill.circle(vec.x + x, vec.y + y, 3 * e.fout()); + }); + vec.trns(e.rotation, -4f).add(e.x, e.y); + Angles.randLenVectors(e.id + 2, 3, 16 * e.fout(), e.rotation + 180, 10, (x, y) -> { + Fill.circle(vec.x + x, vec.y + y, 3 * e.fout()); }); - Draw.alpha(e.fin() / 7f); - randLenVectors(e.id/2, 3, 16f * e.fout(), e.rotation, 20f, (x, y) -> { - Fill.rect(vec.x + x, vec.y + y, 5f * e.fout(), e.fout(), vec.angleTo(vec.x + x, vec.y + y)); + Draw.alpha(e.fin() / 7); + Angles.randLenVectors(e.id + 1, 3, 16 * e.fout(), e.rotation + 180, 20, (x, y) -> { + Fill.rect(vec.x + x, vec.y + y, 5 * e.fout(), e.fout(), vec.angleTo(vec.x + x, vec.y + y)); + }); + vec.trns(e.rotation, 4f).add(e.x, e.y); + Angles.randLenVectors(e.id + 3, 3, 16 * e.fout(), e.rotation, 20, (x, y) -> { + Fill.rect(vec.x + x, vec.y + y, 5 * e.fout(), e.fout(), vec.angleTo(vec.x + x, vec.y + y)); }); }), diff --git a/src/omaloon/content/blocks/OlDefenceBlocks.java b/src/omaloon/content/blocks/OlDefenceBlocks.java index d6b6490d..cd62122a 100644 --- a/src/omaloon/content/blocks/OlDefenceBlocks.java +++ b/src/omaloon/content/blocks/OlDefenceBlocks.java @@ -62,7 +62,7 @@ public static void load(){ ambientSoundVolume = 0.08f; consumePower(0.2f); - consume(new ConsumeFluid(null, 0.1f) {{ + consume(new ConsumeFluid(null, 1f/12f) {{ continuous = true; hasOptimalPressure = true; diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidValve.java b/src/omaloon/world/blocks/liquid/PressureLiquidValve.java index 2ad7fc4d..e895bf21 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidValve.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidValve.java @@ -2,6 +2,7 @@ import arc.*; import arc.audio.*; +import arc.graphics.*; import arc.graphics.g2d.*; import arc.math.*; import arc.math.geom.*; @@ -33,7 +34,8 @@ public class PressureLiquidValve extends Block { public Effect jamEffect = Fx.explosion; public Sound jamSound = OlSounds.jam; - public Effect pumpingEffect = OlFx.pumpBack; + public Effect pumpingEffectOut = OlFx.pumpOut; + public Effect pumpingEffectIn = OlFx.pumpIn; public float pumpingEffectInterval = 15; public float pressureLoss = 0.05f; @@ -157,7 +159,7 @@ public void draw() { } Draw.rect(tiles[tiling], x, y, rot); Draw.rect(topRegion, x, y); - Draw.rect(valveRegion, x, y, draining * (rotation%2 == 0 ? -90 : 90) + rot); + Draw.rect(valveRegion, x, y, draining * (rotation % 2 == 0 ? -90f : 90f) + rot); } @Override @@ -205,25 +207,24 @@ public void updatePressure() { addFluid(null, Math.max(minPressureLoss, pressureLoss * Math.abs(pressureAmount - openMin)/10f)); draining = Mathf.approachDelta(draining, 1, 0.014f); - if (effectInterval > pumpingEffectInterval) { - effectInterval = 0; - pumpingEffect.at(x, y, -draining * (rotation % 2 == 0 ? 90 : -90) - (rotate ? (90 - rotdeg()) % 180 - 90 : 0), pressure.getMain()); - pumpingEffect.at(x, y, draining * (rotation % 2 == 0 ? -90 : 90) + (rotate ? (90 + rotdeg()) % 180 - 90 : 0), pressure.getMain()); - } }; if (pressureAmount > openMax) { effectInterval += delta(); removeFluid(pressure.getMain(), Math.max(minPressureLoss, pressureLoss * Math.abs(pressureAmount - openMax)/10f)); draining = Mathf.approachDelta(draining, 1, 0.014f); - - if (effectInterval > pumpingEffectInterval) { - effectInterval = 0; - pumpingEffect.at(x, y, -draining * (rotation % 2 == 0 ? 90 : -90) - (rotate ? (90 - rotdeg()) % 180 - 90 : 0), pressure.getMain()); - pumpingEffect.at(x, y, draining * (rotation % 2 == 0 ? -90 : 90) + (rotate ? (90 + rotdeg()) % 180 - 90 : 0), pressure.getMain()); - } }; + if (effectInterval > pumpingEffectInterval) { + effectInterval = 0; + if (pressureAmount > openMax) { + pumpingEffectOut.at(x, y, draining * (rotation % 2 == 0 ? -90f : 90f) + (rotate ? (90 + rotdeg()) % 180 - 90 : 0), pressure.getMain() == null ? Color.white : pressure.getMain().color); + } else { + pumpingEffectIn.at(x, y, draining * (rotation % 2 == 0 ? -90f : 90f) + (rotate ? (90 + rotdeg()) % 180 - 90 : 0)); + } + } - if (pressureAmount < openMin && pressureAmount > openMax) draining = Mathf.approachDelta(draining, 0, 0.014f); + if (pressureAmount >= openMin && pressureAmount <= openMax) { + draining = Mathf.approachDelta(draining, 0, 0.014f); + } if (pressureAmount < jamPoint) { jammed = true; diff --git a/src/omaloon/world/interfaces/HasPressure.java b/src/omaloon/world/interfaces/HasPressure.java index c540cc62..530d9584 100644 --- a/src/omaloon/world/interfaces/HasPressure.java +++ b/src/omaloon/world/interfaces/HasPressure.java @@ -29,6 +29,8 @@ default boolean acceptsPressurizedFluid(HasPressure from, @Nullable Liquid liqui * Adds a certain amount of a fluid into this module through the section. */ default void addFluid(@Nullable Liquid liquid, float amount) { + if (amount == 0) return; + if (amount < 0) pressure().section.removeFluid(liquid, -amount); pressure().section.addFluid(liquid, amount); } @@ -79,13 +81,6 @@ default HasPressure getPressureDestination(HasPressure from, float pressure) { return this; } - /** - * adds pressure not taking anything into account - */ - default void handlePressure(float pressure) { - pressure().pressure += pressure; - } - default float moveLiquidPressure(HasPressure next, Liquid liquid) { // if (next != null) { // next = (HasPressure) next.getLiquidDestination(as(), liquid); @@ -151,6 +146,8 @@ default boolean outputsPressurizedFluid(HasPressure to, @Nullable Liquid liquid, * Removes a certain amount of a fluid into this module through the section. */ default void removeFluid(@Nullable Liquid liquid, float amount) { + if (amount == 0) return; + if (amount < 0) pressure().section.addFluid(liquid, -amount); pressure().section.removeFluid(liquid, amount); } From 3e41e2eb817b926b288cf6bc6fb4c9f59626b803 Mon Sep 17 00:00:00 2001 From: = Date: Tue, 17 Dec 2024 23:35:36 -0300 Subject: [PATCH 13/67] add groups --- src/omaloon/content/OlFx.java | 8 ++-- .../content/blocks/OlProductionBlocks.java | 15 ++++++- .../blocks/liquid/PressureLiquidBridge.java | 39 ++++++++++++---- .../blocks/liquid/PressureLiquidConduit.java | 2 + .../blocks/liquid/PressureLiquidGauge.java | 7 +++ .../blocks/liquid/PressureLiquidPump.java | 12 ++--- .../blocks/liquid/PressureLiquidValve.java | 11 ++++- .../blocks/production/PressureDrill.java | 15 ++++++- .../world/blocks/production/Pressurizer.java | 1 + src/omaloon/world/consumers/ConsumeFluid.java | 6 +-- src/omaloon/world/interfaces/HasPressure.java | 44 +------------------ src/omaloon/world/meta/FluidGroup.java | 12 +++++ src/omaloon/world/meta/PressureConfig.java | 26 ++++++++--- 13 files changed, 125 insertions(+), 73 deletions(-) create mode 100644 src/omaloon/world/meta/FluidGroup.java diff --git a/src/omaloon/content/OlFx.java b/src/omaloon/content/OlFx.java index 228532b2..a172d62a 100644 --- a/src/omaloon/content/OlFx.java +++ b/src/omaloon/content/OlFx.java @@ -186,19 +186,19 @@ public class OlFx { Draw.color(e.color); Draw.alpha(e.fout() / 5); vec.trns(e.rotation, 4f).add(e.x, e.y); - Angles.randLenVectors(e.id, 3, 16 * e.fin(), e.rotation + 180, 10, (x, y) -> { + Angles.randLenVectors(e.id, 3, 16 * e.fin(), e.rotation, 10, (x, y) -> { Fill.circle(vec.x + x, vec.y + y, 3 * e.fin()); }); vec.trns(e.rotation, -4f).add(e.x, e.y); - Angles.randLenVectors(e.id + 2, 3, 16 * e.fin(), e.rotation, 10, (x, y) -> { + Angles.randLenVectors(e.id + 2, 3, 16 * e.fin(), e.rotation + 180, 10, (x, y) -> { Fill.circle(vec.x + x, vec.y + y, 3 * e.fin()); }); Draw.alpha(e.fout() / 7); - Angles.randLenVectors(e.id + 1, 3, 16 * e.fin(), e.rotation, 20, (x, y) -> { + Angles.randLenVectors(e.id + 1, 3, 16 * e.fin(), e.rotation + 180, 20, (x, y) -> { Fill.rect(vec.x + x, vec.y + y, 5 * e.fin(), e.fin(), vec.angleTo(vec.x + x, vec.y + y)); }); vec.trns(e.rotation, 4f).add(e.x, e.y); - Angles.randLenVectors(e.id + 3, 3, 16 * e.fin(), e.rotation + 180, 20, (x, y) -> { + Angles.randLenVectors(e.id + 3, 3, 16 * e.fin(), e.rotation, 20, (x, y) -> { Fill.rect(vec.x + x, vec.y + y, 5 * e.fin(), e.fin(), vec.angleTo(vec.x + x, vec.y + y)); }); }), diff --git a/src/omaloon/content/blocks/OlProductionBlocks.java b/src/omaloon/content/blocks/OlProductionBlocks.java index b0575f9b..9a683828 100644 --- a/src/omaloon/content/blocks/OlProductionBlocks.java +++ b/src/omaloon/content/blocks/OlProductionBlocks.java @@ -33,8 +33,19 @@ public static void load(){ pressureConfig.linkList.add(this); - consume(new ConsumePressure(-6, false)); - consume(new PressureEfficiencyRange(-45f, -1f, 2f, true)); + consume(new ConsumeFluid(null, -5f) {{ + startRange = -45f; + endRange = -0.01f; + efficiencyMultiplier = 2f; + + optimalPressure = -40f; + hasOptimalPressure = true; + + curve = t -> Math.min( + 9f/8f * (1f - t), + 9f * t + ); + }}); }}; pressurizer = new Pressurizer("air-well") {{ diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidBridge.java b/src/omaloon/world/blocks/liquid/PressureLiquidBridge.java index a9aeadf1..125b2695 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidBridge.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidBridge.java @@ -17,7 +17,7 @@ import mindustry.world.*; import mindustry.world.blocks.liquid.*; import mindustry.world.blocks.sandbox.*; -import mindustry.world.meta.BlockGroup; +import mindustry.world.meta.*; import omaloon.world.blocks.distribution.*; import omaloon.world.interfaces.*; import omaloon.world.meta.*; @@ -40,7 +40,6 @@ public class PressureLiquidBridge extends TubeItemBridge { public PressureLiquidBridge(String name) { super(name); - hasLiquids = true; hasItems = false; outputsLiquid = true; canOverdrive = false; @@ -121,6 +120,13 @@ public TextureRegion[] icons(){ return new TextureRegion[]{atlas.find(name + "-icon")}; } + @Override + public void init() { + super.init(); + + if (pressureConfig.fluidGroup == null) pressureConfig.fluidGroup = FluidGroup.transportation; + } + @Override public void load() { super.load(); @@ -148,8 +154,8 @@ public class PressureLiquidBridgeBuild extends TubeItemBridgeBuild implements Ha PressureModule pressure = new PressureModule(); @Override - public boolean acceptLiquid(Building source, Liquid liquid) { - return source.block.hasLiquids; + public boolean acceptsPressurizedFluid(HasPressure from, @Nullable Liquid liquid, float amount) { + return HasPressure.super.acceptsPressurizedFluid(from, liquid, amount) && (liquid == pressure.getMain() || liquid == null || pressure.getMain() == null || from.pressure().getMain() == null); } @Override @@ -179,9 +185,14 @@ public void draw() { Draw.alpha(Renderer.bridgeOpacity); drawBridge(bridgeBottomRegion, endBottomRegion, pos1, pos2); - Draw.color(liquids.current().color, liquids.currentAmount()/liquidCapacity * liquids.current().color.a * Renderer.bridgeOpacity); - drawBridge(bridgeLiquidRegion, endLiquidRegion, pos1, pos2); - Draw.color(); + + Liquid main = pressure.getMain(); + + if (main != null) { + Draw.color(main.color, Mathf.clamp(pressure.liquids[main.id]/(pressure.liquids[main.id] + pressure.air)) * Renderer.bridgeOpacity); + drawBridge(bridgeLiquidRegion, endLiquidRegion, pos1, pos2); + Draw.color(); + } Draw.alpha(Renderer.bridgeOpacity); drawBridge(pos1, pos2); @@ -196,6 +207,18 @@ public Seq nextBuilds(boolean flow) { return o; } + @Override + public void onProximityUpdate() { + super.onProximityUpdate(); + + new PressureSection().mergeFlood(this); + } + + @Override + public boolean outputsPressurizedFluid(HasPressure to, Liquid liquid, float amount) { + return HasPressure.super.outputsPressurizedFluid(to, liquid, amount) && (liquid == to.pressure().getMain() || liquid == null || pressure.getMain() == null || to.pressure().getMain() == null); + } + @Override public PressureModule pressure() { return pressure; } @@ -216,9 +239,7 @@ public void updateTile() { checkIncoming(); - nextBuilds(true).each(b -> moveLiquidPressure(b, liquids.current())); updatePressure(); - dumpPressure(); Tile other = world.tile(link); if(linkValid(tile, other)) { diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidConduit.java b/src/omaloon/world/blocks/liquid/PressureLiquidConduit.java index 540a3062..42c4d422 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidConduit.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidConduit.java @@ -49,6 +49,8 @@ public void init(){ if(junctionReplacement == null) junctionReplacement = OlDistributionBlocks.liquidJunction; if(bridgeReplacement == null || !(bridgeReplacement instanceof ItemBridge)) bridgeReplacement = OlDistributionBlocks.liquidBridge; + + if (pressureConfig.fluidGroup == null) pressureConfig.fluidGroup = FluidGroup.transportation; } @Override diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidGauge.java b/src/omaloon/world/blocks/liquid/PressureLiquidGauge.java index ded57fa3..0384688e 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidGauge.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidGauge.java @@ -55,6 +55,13 @@ public TextureRegion[] icons() { return new TextureRegion[]{region}; } + @Override + public void init() { + super.init(); + + if (pressureConfig.fluidGroup == null) pressureConfig.fluidGroup = FluidGroup.transportation; + } + @Override public void load() { super.load(); diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidPump.java b/src/omaloon/world/blocks/liquid/PressureLiquidPump.java index 0b33977a..bd052070 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidPump.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidPump.java @@ -76,6 +76,13 @@ public void drawPlanRegion(BuildPlan plan, Eachable list) { return new TextureRegion[]{region, topRegion}; } + @Override + public void init() { + super.init(); + + pressureConfig.fluidGroup = FluidGroup.pumps; + } + @Override public void load() { super.load(); @@ -181,11 +188,6 @@ public void draw() { if (tiling == 0) Draw.rect(topRegion, x, y, rotdeg()); } - @Override - public HasPressure getSectionDestination(HasPressure from) { - return null; - } - @Override public Seq nextBuilds(boolean flow) { return Seq.with(); diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidValve.java b/src/omaloon/world/blocks/liquid/PressureLiquidValve.java index e895bf21..f3357877 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidValve.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidValve.java @@ -80,6 +80,13 @@ public TextureRegion[] icons() { return new TextureRegion[]{bottomRegion, region}; } + @Override + public void init() { + super.init(); + + if (pressureConfig.fluidGroup == null) pressureConfig.fluidGroup = FluidGroup.transportation; + } + @Override public void load() { super.load(); @@ -207,12 +214,12 @@ public void updatePressure() { addFluid(null, Math.max(minPressureLoss, pressureLoss * Math.abs(pressureAmount - openMin)/10f)); draining = Mathf.approachDelta(draining, 1, 0.014f); - }; + } if (pressureAmount > openMax) { effectInterval += delta(); removeFluid(pressure.getMain(), Math.max(minPressureLoss, pressureLoss * Math.abs(pressureAmount - openMax)/10f)); draining = Mathf.approachDelta(draining, 1, 0.014f); - }; + } if (effectInterval > pumpingEffectInterval) { effectInterval = 0; if (pressureAmount > openMax) { diff --git a/src/omaloon/world/blocks/production/PressureDrill.java b/src/omaloon/world/blocks/production/PressureDrill.java index 050c0016..f61bbb6e 100644 --- a/src/omaloon/world/blocks/production/PressureDrill.java +++ b/src/omaloon/world/blocks/production/PressureDrill.java @@ -17,6 +17,13 @@ public PressureDrill(String name) { pressureConfig.isWhitelist = true; } + @Override + public void init() { + super.init(); + + if (pressureConfig.fluidGroup == null) pressureConfig.fluidGroup = FluidGroup.drills; + } + @Override public void setBars() { super.setBars(); @@ -49,6 +56,13 @@ public float efficiencyMultiplier() { return super.getProgressIncrease(baseTime) * efficiencyMultiplier(); } + @Override + public void onProximityUpdate() { + super.onProximityUpdate(); + + new PressureSection().mergeFlood(this); + } + @Override public PressureModule pressure() { return pressure; } @@ -66,7 +80,6 @@ public void read(Reads read, byte revision) { public void updateTile() { super.updateTile(); updatePressure(); - dumpPressure(); } @Override public void write(Writes write) { diff --git a/src/omaloon/world/blocks/production/Pressurizer.java b/src/omaloon/world/blocks/production/Pressurizer.java index 3e7a0bd1..0e51216a 100644 --- a/src/omaloon/world/blocks/production/Pressurizer.java +++ b/src/omaloon/world/blocks/production/Pressurizer.java @@ -35,6 +35,7 @@ public Pressurizer(String name) { update = true; destructible = true; solid = true; + saveConfig = copyConfig = true; config(Boolean.class, (PressurizerBuild build, Boolean bool) -> build.reverse = bool); } diff --git a/src/omaloon/world/consumers/ConsumeFluid.java b/src/omaloon/world/consumers/ConsumeFluid.java index 0441db47..ccfef804 100644 --- a/src/omaloon/world/consumers/ConsumeFluid.java +++ b/src/omaloon/world/consumers/ConsumeFluid.java @@ -66,15 +66,15 @@ public HasPressure cast(Building build) { public void display(Stats stats) { if (amount != 0) { if (continuous) { - stats.add(OlStats.removeFluid, OlStats.fluid(fluid, amount, 1f, true)); + stats.add(amount > 0 ? OlStats.removeFluid : OlStats.addFluid, OlStats.fluid(fluid, Math.abs(amount), 1f, true)); } else { - stats.add(OlStats.removeFluid, OlStats.fluid(fluid, amount, 60f, false)); + stats.add(amount > 0 ? OlStats.removeFluid : OlStats.addFluid, OlStats.fluid(fluid, Math.abs(amount), 60f, false)); } } if (startRange != endRange) { stats.add(OlStats.pressureRange, Core.bundle.get("stat.omaloon-pressurerange.format"), Strings.autoFixed(startRange, 2), Strings.autoFixed(endRange, 2)); - if (hasOptimalPressure) stats.add(OlStats.optimalPressure, Core.bundle.get("stat.omaloon-optimal-pressure.format"), Strings.autoFixed(optimalPressure, 2), Strings.autoFixed(efficiencyMultiplier, 2)); + if (hasOptimalPressure) stats.add(OlStats.optimalPressure, Core.bundle.get("stat.omaloon-optimal-pressure.format"), Strings.autoFixed(optimalPressure, 2), Strings.autoFixed(efficiencyMultiplier * 100f, 2)); } } diff --git a/src/omaloon/world/interfaces/HasPressure.java b/src/omaloon/world/interfaces/HasPressure.java index 530d9584..975dcea5 100644 --- a/src/omaloon/world/interfaces/HasPressure.java +++ b/src/omaloon/world/interfaces/HasPressure.java @@ -78,50 +78,10 @@ default HasPressure getPressureDestination(HasPressure from, float pressure) { * Returns the building whose section should be the same as this build's section. */ default @Nullable HasPressure getSectionDestination(HasPressure from) { + if (pressureConfig().fluidGroup == null || pressureConfig().fluidGroup == FluidGroup.unset || pressureConfig().fluidGroup != from.pressureConfig().fluidGroup) return null; return this; } - default float moveLiquidPressure(HasPressure next, Liquid liquid) { -// if (next != null) { -// next = (HasPressure) next.getLiquidDestination(as(), liquid); -// if (next.team() == team() && next.block().hasLiquids && liquids().get(liquid) > 0f) { -// float ofract = next.liquids().get(liquid) / next.block().liquidCapacity; -// float fract = liquids().get(liquid) / block().liquidCapacity; -// float flow = Math.min(Mathf.clamp(fract - ofract) * block().liquidCapacity, liquids().get(liquid)) * getPressureFlow(next); -// flow = Math.min(flow, next.block().liquidCapacity - next.liquids().get(liquid))/2; -// if (flow > 0f && ofract <= fract && next.acceptLiquid(this.as(), liquid)) { -// next.handleLiquid(this.as(), liquid, flow); -// liquids().remove(liquid, flow); -// return flow; -// } -// -// if (!next.block().consumesLiquid(liquid) && next.liquids().currentAmount() / next.block().liquidCapacity > 0.1F && fract > 0.1F) { -// float fx = (x() + next.x()) / 2f; -// float fy = (y() + next.y()) / 2f; -// Liquid other = next.liquids().current(); -// if (other.blockReactive && liquid.blockReactive) { -// if ((!(other.flammability > 0.3F) || !(liquid.temperature > 0.7F)) && (!(liquid.flammability > 0.3F) || !(other.temperature > 0.7F))) { -// if (liquid.temperature > 0.7F && other.temperature < 0.55F || other.temperature > 0.7F && liquid.temperature < 0.55F) { -// liquids().remove(liquid, Math.min(liquids().get(liquid), 0.7F * Time.delta)); -// if (Mathf.chanceDelta(0.20000000298023224)) { -// Fx.steam.at(fx, fy); -// } -// } -// } else { -// this.damageContinuous(1.0F); -// next.damageContinuous(1.0F); -// if (Mathf.chanceDelta(0.1)) { -// Fx.fire.at(fx, fy); -// } -// } -// } -// } -// } -// -// } - return 0.0F; - } - /** * @param flow determines if the returned value will have only builds to which it can flow pressure to */ @@ -164,7 +124,7 @@ default void updatePressure() { /** * removes pressure not taking anything into account */ - default void removePressure(float pressure) { + default @Deprecated void removePressure(float pressure) { pressure().pressure -= pressure; } } diff --git a/src/omaloon/world/meta/FluidGroup.java b/src/omaloon/world/meta/FluidGroup.java new file mode 100644 index 00000000..ba491d91 --- /dev/null +++ b/src/omaloon/world/meta/FluidGroup.java @@ -0,0 +1,12 @@ +package omaloon.world.meta; + +public enum FluidGroup { + /** + * This group specifically acts the same as if the group is null. Only used if blocks that normally override the group have to be independent. + */ + unset, + + drills, + pumps, + transportation +} diff --git a/src/omaloon/world/meta/PressureConfig.java b/src/omaloon/world/meta/PressureConfig.java index 18cf7794..9ac37c3e 100644 --- a/src/omaloon/world/meta/PressureConfig.java +++ b/src/omaloon/world/meta/PressureConfig.java @@ -14,6 +14,11 @@ import omaloon.world.interfaces.*; public class PressureConfig { + /** + * Group used for the creation of sections. if null, this block will be a section containing only itself. + */ + public FluidGroup fluidGroup; + /** * If true, this block's section will be able to receive fluids. */ @@ -27,11 +32,22 @@ public class PressureConfig { */ public boolean isWhitelist = false; - public float - overPressureDamage = 0.33f, - underPressureDamage = 0.66f, - maxPressure = 50, - minPressure = -50f; + /** + * Damage applied each tick if pressure is higher than maxPressure. + */ + public float overPressureDamage = 0.33f; + /** + * Damage applied each tick if pressure is lower than minPressure. + */ + public float underPressureDamage = 0.66f; + /** + * Maximum pressure that this block can contain before it over-pressurizes. + */ + public float maxPressure = 50; + /** + * Minimum pressure that this block can contain before it under-pressurizes. + */ + public float minPressure = -50f; /** * Standard capacity for this block. Does not define max amount that this can hold. That is defined by maxPressure and minPressure. From 1f6c794716cf71a80493e1d974443988d4eb36d9 Mon Sep 17 00:00:00 2001 From: = Date: Wed, 18 Dec 2024 00:23:25 -0300 Subject: [PATCH 14/67] generic crafters were rather easy --- .../content/blocks/OlCraftingBlocks.java | 26 ++++++++++++++++--- .../world/blocks/production/HammerDrill.java | 2 +- .../blocks/production/PressureCrafter.java | 12 +++++---- 3 files changed, 30 insertions(+), 10 deletions(-) diff --git a/src/omaloon/content/blocks/OlCraftingBlocks.java b/src/omaloon/content/blocks/OlCraftingBlocks.java index 3a7ed0fe..56f049ac 100644 --- a/src/omaloon/content/blocks/OlCraftingBlocks.java +++ b/src/omaloon/content/blocks/OlCraftingBlocks.java @@ -26,8 +26,17 @@ public static void load() { craftEffect = OlFx.carborundumCraft; consumeItems(with(Items.beryllium, 1, OlItems.cobalt, 1)); - consume(new ConsumePressure(6f, false)); - consume(new PressureEfficiencyRange(5f, 50f, 1.6f, false)); + consume(new ConsumeFluid(null, 5) {{ + startRange = 5f; + endRange = 50f; + efficiencyMultiplier = 1.6f; + curve = t -> Math.min( + 9f/2f * (1f - t), + 9f/7f * t + ); + optimalPressure = 40f; + hasOptimalPressure = true; + }}); outputItems = with(OlItems.carborundum, 1); }}; @@ -44,8 +53,17 @@ public static void load() { craftEffect = Fx.pulverizeMedium; consumeItem(Items.coal, 4); - consume(new ConsumePressure(8f, false)); - consume(new PressureEfficiencyRange(10f, 50f, 1.5f, false)); + consume(new ConsumeFluid(null, 8f) {{ + startRange = 10f; + endRange = 50f; + efficiencyMultiplier = 1.5f; + curve = t -> Math.min( + 8f * (1f - t), + 8f/7f * t + ); + optimalPressure = 45f; + hasOptimalPressure = true; + }}); outputItem = new ItemStack(Items.graphite, 2); }}; diff --git a/src/omaloon/world/blocks/production/HammerDrill.java b/src/omaloon/world/blocks/production/HammerDrill.java index db6ce011..2703d606 100644 --- a/src/omaloon/world/blocks/production/HammerDrill.java +++ b/src/omaloon/world/blocks/production/HammerDrill.java @@ -81,7 +81,7 @@ public boolean shouldConsume(){ @Override public void updateTile(){ updatePressure(); - dumpPressure(); + if(timer(timerDump, dumpTime)){ dump(dominantItem != null && items.has(dominantItem) ? dominantItem : null); } diff --git a/src/omaloon/world/blocks/production/PressureCrafter.java b/src/omaloon/world/blocks/production/PressureCrafter.java index 72c216c1..9ea63132 100644 --- a/src/omaloon/world/blocks/production/PressureCrafter.java +++ b/src/omaloon/world/blocks/production/PressureCrafter.java @@ -1,6 +1,5 @@ package omaloon.world.blocks.production; -import arc.util.*; import arc.util.io.*; import mindustry.world.blocks.production.*; import mindustry.world.consumers.*; @@ -13,8 +12,6 @@ public class PressureCrafter extends GenericCrafter { public boolean useConsumerMultiplier = true; - public float outputPressure = 0; - public PressureCrafter(String name) { super(name); pressureConfig.isWhitelist = true; @@ -30,7 +27,6 @@ public void setBars() { public void setStats() { super.setStats(); pressureConfig.addStats(stats); - if (outputPressure != 0) stats.add(OlStats.outputPressure, Strings.autoFixed(outputPressure, 2), OlStats.pressureUnits); } public class PressureCrafterBuild extends GenericCrafterBuild implements HasPressure { @@ -53,6 +49,13 @@ public float efficiencyMultiplier() { return super.getProgressIncrease(baseTime) * efficiencyMultiplier(); } + @Override + public void onProximityUpdate() { + super.onProximityUpdate(); + + new PressureSection().mergeFlood(this); + } + @Override public PressureModule pressure() { return pressure; } @@ -70,7 +73,6 @@ public void read(Reads read, byte revision) { public void updateTile() { super.updateTile(); updatePressure(); - dumpPressure(); } @Override From 8f5ac1eb556fe74aba446080247c37bc644a6114 Mon Sep 17 00:00:00 2001 From: = Date: Wed, 18 Dec 2024 13:17:44 -0300 Subject: [PATCH 15/67] finally remove the old consumers --- .../content/blocks/OlDefenceBlocks.java | 15 +- src/omaloon/ui/dialogs/EventHints.java | 32 ---- .../world/blocks/defense/BlastTower.java | 178 +++++++++--------- .../world/blocks/defense/ConsumeTurret.java | 10 +- src/omaloon/world/blocks/defense/Shelter.java | 1 - .../world/consumers/ConsumePressure.java | 48 ----- .../consumers/PressureEfficiencyRange.java | 59 ------ src/omaloon/world/interfaces/HasPressure.java | 7 - 8 files changed, 113 insertions(+), 237 deletions(-) delete mode 100644 src/omaloon/world/consumers/ConsumePressure.java delete mode 100644 src/omaloon/world/consumers/PressureEfficiencyRange.java diff --git a/src/omaloon/content/blocks/OlDefenceBlocks.java b/src/omaloon/content/blocks/OlDefenceBlocks.java index cd62122a..71c263b7 100644 --- a/src/omaloon/content/blocks/OlDefenceBlocks.java +++ b/src/omaloon/content/blocks/OlDefenceBlocks.java @@ -163,8 +163,19 @@ Items.graphite, new BasicBulletType(4f, 16){{ )); size = 2; consumePower(70f / 60f); - consume(new ConsumePressure(-6, false)); - consume(new PressureEfficiencyRange(-45f, -1f, 3f, true)); + consume(new ConsumeFluid(null, 6f) {{ + startRange = -45f; + endRange = -0.01f; + efficiencyMultiplier = 3f; + + optimalPressure = -40f; + hasOptimalPressure = true; + + curve = t -> Math.min( + 9f/8f * (1f - t), + 9f * t + ); + }}); targetGround = true; targetAir = false; damage = 0.6f; diff --git a/src/omaloon/ui/dialogs/EventHints.java b/src/omaloon/ui/dialogs/EventHints.java index e9cc5363..904862b2 100644 --- a/src/omaloon/ui/dialogs/EventHints.java +++ b/src/omaloon/ui/dialogs/EventHints.java @@ -6,9 +6,7 @@ import arc.util.*; import mindustry.*; import mindustry.ui.fragments.HintsFragment.*; -import mindustry.world.consumers.*; import omaloon.content.blocks.*; -import omaloon.world.consumers.*; import omaloon.world.interfaces.*; public enum EventHints implements Hint { @@ -21,36 +19,6 @@ public enum EventHints implements Hint { () -> Vars.state.teams.get(Vars.state.rules.defaultTeam).getBuildings(OlCraftingBlocks.carborundumPress).find(b -> ((HasPressure) b).getPressure() < 0f) != null || Vars.state.teams.get(Vars.state.rules.defaultTeam).getBuildings(OlDefenceBlocks.smallShelter).find(b -> ((HasPressure) b).getPressure() < 0f) != null ), - pump_positive( - () -> false, - () -> Vars.state.teams.get(Vars.state.rules.defaultTeam).buildings.contains( - b -> { - if (b instanceof HasPressure pressureBuilding) { - for (Consume consumer : b.block().consumers) { - if (consumer instanceof PressureEfficiencyRange rangeConsumer) { - return pressureBuilding.getPressure() > 0 && rangeConsumer.shouldConsume(pressureBuilding); - } - } - } - return false; - } - ) - ), - pump_negative( - () -> false, - () -> Vars.state.teams.get(Vars.state.rules.defaultTeam).buildings.contains( - b -> { - if (b instanceof HasPressure pressureBuilding) { - for (Consume consumer : b.block().consumers) { - if (consumer instanceof PressureEfficiencyRange rangeConsumer) { - return pressureBuilding.getPressure() < 0 && rangeConsumer.shouldConsume(pressureBuilding); - } - } - } - return false; - } - ) - ), pump( () -> false, () -> !Vars.state.teams.get(Vars.state.rules.defaultTeam).getBuildings(OlDistributionBlocks.liquidPump).isEmpty() diff --git a/src/omaloon/world/blocks/defense/BlastTower.java b/src/omaloon/world/blocks/defense/BlastTower.java index 132845b1..37b1bb5a 100644 --- a/src/omaloon/world/blocks/defense/BlastTower.java +++ b/src/omaloon/world/blocks/defense/BlastTower.java @@ -99,76 +99,6 @@ public class BlastTowerBuild extends Building implements HasPressure { public float lastShootTime = -reload; public Seq targets = new Seq<>(); - public float efficiencyMultiplier() { - float val = 1f; - if (!useConsumerMultiplier) return val; - for (Consume consumer : consumers) { - val *= consumer.efficiencyMultiplier(this); - } - return val; - } - - @Override - public void updateTile() { - updatePressure(); - dumpPressure(); - super.updateTile(); - - targets.clear(); - Units.nearbyEnemies(team, x, y, range, u -> { - if(u.checkTarget(targetAir, targetGround)) { - targets.add(u); - } - }); - - indexer.allBuildings(x, y, range, b -> { - if(b.team != team){ - targets.add(b); - } - }); - - float effMultiplier = efficiencyMultiplier(); - - if (targets.size > 0 && canConsume()) { - smoothProgress = Mathf.approach(smoothProgress, 1f, Time.delta / chargeTime * effMultiplier); - - if (efficiency > 0 && (charge += Time.delta * effMultiplier) >= reload && smoothProgress >= 0.99f) { - shoot(); - charge = 0f; - } - } else { - smoothProgress = Mathf.approach(smoothProgress, 0f, Time.delta / chargeTime * effMultiplier); - } - } - - public void shoot() { - if (!canConsume()) return; - - consume(); - lastShootTime = Time.time; - Effect.shake(shake, shake, this); - shootSound.at(this); - waveEffect.layer(Layer.blockUnder).at(x, y, range, waveColor); - tile.getLinkedTiles(t -> OlFx.hammerHit.layer(Layer.blockUnder).at( - t.worldx(), t.worldy(), - angleTo(t.worldx(), t.worldy()) + Mathf.range(360f), - Tmp.c1.set(t.floor().mapColor).mul(1.5f + Mathf.range(0.15f))) - ); - - float damageMultiplier = efficiencyMultiplier(); - for (Teamc target : targets) { - hitEffect.at(target.x(), target.y(), hitColor); - if(target instanceof Healthc){ - ((Healthc)target).damage(damage * damageMultiplier); - } - if(target instanceof Statusc){ - ((Statusc)target).apply(status, statusDuration); - } - } - - smoothProgress = 0f; - } - @Override public void draw() { Draw.rect(region, x, y); @@ -186,23 +116,21 @@ public void drawSelect(){ Drawf.dashCircle(x, y, range, Pal.accent); } - @Override - public void write(Writes write) { - super.write(write); - write.f(lastShootTime); - write.f(smoothProgress); - write.f(charge); - pressure.write(write); - } + public float efficiencyMultiplier() { + float val = 1f; + if (!useConsumerMultiplier) return val; + for (Consume consumer : consumers) { + val *= consumer.efficiencyMultiplier(this); + } + return val; + } - @Override - public void read(Reads read, byte revision) { - super.read(read, revision); - lastShootTime = read.f(); - smoothProgress = read.f(); - charge = read.f(); - pressure.read(read); - } + @Override + public void onProximityUpdate() { + super.onProximityUpdate(); + + new PressureSection().mergeFlood(this); + } @Override public PressureModule pressure() { @@ -213,5 +141,83 @@ public PressureModule pressure() { public PressureConfig pressureConfig() { return pressureConfig; } + + @Override + public void read(Reads read, byte revision) { + super.read(read, revision); + lastShootTime = read.f(); + smoothProgress = read.f(); + charge = read.f(); + pressure.read(read); + } + + public void shoot() { + if (!canConsume()) return; + + consume(); + lastShootTime = Time.time; + Effect.shake(shake, shake, this); + shootSound.at(this); + waveEffect.layer(Layer.blockUnder).at(x, y, range, waveColor); + tile.getLinkedTiles(t -> OlFx.hammerHit.layer(Layer.blockUnder).at( + t.worldx(), t.worldy(), + angleTo(t.worldx(), t.worldy()) + Mathf.range(360f), + Tmp.c1.set(t.floor().mapColor).mul(1.5f + Mathf.range(0.15f))) + ); + + float damageMultiplier = efficiencyMultiplier(); + for (Teamc target : targets) { + hitEffect.at(target.x(), target.y(), hitColor); + if(target instanceof Healthc){ + ((Healthc)target).damage(damage * damageMultiplier); + } + if(target instanceof Statusc){ + ((Statusc)target).apply(status, statusDuration); + } + } + + smoothProgress = 0f; + } + + @Override + public void updateTile() { + updatePressure(); + super.updateTile(); + + targets.clear(); + Units.nearbyEnemies(team, x, y, range, u -> { + if(u.checkTarget(targetAir, targetGround)) { + targets.add(u); + } + }); + + indexer.allBuildings(x, y, range, b -> { + if(b.team != team){ + targets.add(b); + } + }); + + float effMultiplier = efficiencyMultiplier(); + + if (targets.size > 0 && canConsume()) { + smoothProgress = Mathf.approach(smoothProgress, 1f, Time.delta / chargeTime * effMultiplier); + + if (efficiency > 0 && (charge += Time.delta * effMultiplier) >= reload && smoothProgress >= 0.99f) { + shoot(); + charge = 0f; + } + } else { + smoothProgress = Mathf.approach(smoothProgress, 0f, Time.delta / chargeTime * effMultiplier); + } + } + + @Override + public void write(Writes write) { + super.write(write); + write.f(lastShootTime); + write.f(smoothProgress); + write.f(charge); + pressure.write(write); + } } } \ No newline at end of file diff --git a/src/omaloon/world/blocks/defense/ConsumeTurret.java b/src/omaloon/world/blocks/defense/ConsumeTurret.java index 8efe418d..28bb66cd 100644 --- a/src/omaloon/world/blocks/defense/ConsumeTurret.java +++ b/src/omaloon/world/blocks/defense/ConsumeTurret.java @@ -17,7 +17,7 @@ public class ConsumeTurret extends Turret { public PressureConfig pressureConfig = new PressureConfig(); /** - * if true, min range this turret can only target + * If true, this turret cannot target things that are closer than the minRange */ public boolean minRangeShoot = true; @@ -67,6 +67,13 @@ protected void findTarget() { return canConsume(); } + @Override + public void onProximityUpdate() { + super.onProximityUpdate(); + + new PressureSection().mergeFlood(this); + } + @Override public BulletType peekAmmo() { return shootType; } @@ -93,7 +100,6 @@ protected void shoot(BulletType type) { @Override public void updateTile() { updatePressure(); - dumpPressure(); super.updateTile(); } diff --git a/src/omaloon/world/blocks/defense/Shelter.java b/src/omaloon/world/blocks/defense/Shelter.java index 558a69e6..3026d8ec 100644 --- a/src/omaloon/world/blocks/defense/Shelter.java +++ b/src/omaloon/world/blocks/defense/Shelter.java @@ -246,7 +246,6 @@ public void read(Reads read, byte revision) { @Override public void updateTile() { updatePressure(); - dumpPressure(); if (efficiency > 0) { if (shieldDamage >= 0) { shieldDamage -= edelta() * (broken ? rechargeBroken : rechargeStandard); diff --git a/src/omaloon/world/consumers/ConsumePressure.java b/src/omaloon/world/consumers/ConsumePressure.java deleted file mode 100644 index 7ef73160..00000000 --- a/src/omaloon/world/consumers/ConsumePressure.java +++ /dev/null @@ -1,48 +0,0 @@ -package omaloon.world.consumers; - -import arc.math.*; -import arc.util.*; -import mindustry.gen.*; -import mindustry.world.*; -import mindustry.world.consumers.*; -import mindustry.world.meta.*; -import omaloon.world.interfaces.*; -import omaloon.world.meta.*; - -public class ConsumePressure extends Consume { - public float amount; - public boolean continuous; - - public ConsumePressure(float amount, boolean continuous) { - this.amount = amount; - this.continuous = continuous; - } - - public HasPressure cast(Building build) { - try { - return (HasPressure) build; - } catch(Exception e) { - throw new RuntimeException("This consumer should be used on a building that implements HasPressure", e); - } - } - - @Override public void apply(Block block) { - block.hasLiquids = true; - } - - @Override - public void display(Stats stats) { - if (continuous) { - stats.add(OlStats.consumePressure, Mathf.round(amount * 60f, 2), OlStats.pressureSecond); - } else { - stats.add(OlStats.consumePressure, Mathf.round(amount, 2), OlStats.pressureUnits); - } - } - - @Override public void trigger(Building build) { - if (!continuous) cast(build).removePressure(amount); - } - @Override public void update(Building build) { - if (continuous) cast(build).removePressure(amount * Time.delta); - } -} diff --git a/src/omaloon/world/consumers/PressureEfficiencyRange.java b/src/omaloon/world/consumers/PressureEfficiencyRange.java deleted file mode 100644 index f7e7d74a..00000000 --- a/src/omaloon/world/consumers/PressureEfficiencyRange.java +++ /dev/null @@ -1,59 +0,0 @@ -package omaloon.world.consumers; - -import arc.*; -import arc.math.*; -import arc.util.*; -import mindustry.gen.*; -import mindustry.world.*; -import mindustry.world.consumers.*; -import mindustry.world.meta.*; -import omaloon.world.interfaces.*; -import omaloon.world.meta.*; - -public class PressureEfficiencyRange extends Consume { - public float startRange, endRange, efficiencyMultiplier; - public boolean reverse; - - public PressureEfficiencyRange(float startRange, float endRange, float efficiencyMultiplier, boolean reverse) { - this.startRange = startRange; - this.endRange = endRange; - this.efficiencyMultiplier = efficiencyMultiplier; - this.reverse = reverse; - } - - @Override public void apply(Block block) { - block.hasLiquids = true; - } - - public HasPressure cast(Building build) { - try { - return (HasPressure) build; - } catch(Exception e) { - throw new RuntimeException("This consumer should be used on a building that implements HasPressure", e); - } - } - - @Override - public void display(Stats stats) { - stats.add(OlStats.pressureRange, Core.bundle.get("stat.omaloon-pressurerange.format"), Strings.autoFixed(startRange, 2), Strings.autoFixed(endRange, 2)); - } - - @Override - public float efficiency(Building build) { - return shouldConsume(cast(build)) ? 1f : 0f; - } - @Override - public float efficiencyMultiplier(Building build) { - if (!shouldConsume(cast(build))) return 0f; - if (reverse) { - return Mathf.maxZero(Mathf.map(cast(build).getPressure(), endRange, startRange, 1f, efficiencyMultiplier)); - } else { - return Mathf.maxZero(Mathf.map(cast(build).getPressure(), startRange, endRange, 1f, efficiencyMultiplier)); - } - } - - public boolean shouldConsume(HasPressure build) { - int pressure = Math.round(build.getPressure()); - return startRange <= pressure && pressure <= endRange; - } -} diff --git a/src/omaloon/world/interfaces/HasPressure.java b/src/omaloon/world/interfaces/HasPressure.java index 975dcea5..00cde3e5 100644 --- a/src/omaloon/world/interfaces/HasPressure.java +++ b/src/omaloon/world/interfaces/HasPressure.java @@ -120,11 +120,4 @@ default void updatePressure() { if (Mathf.round(pressure().getPressure(liquid)) > pressureConfig().maxPressure + 1) damage(pressureConfig().overPressureDamage); }); } - - /** - * removes pressure not taking anything into account - */ - default @Deprecated void removePressure(float pressure) { - pressure().pressure -= pressure; - } } From 06f618cdd87f3c8dedc6e10f762c84533d3abf8d Mon Sep 17 00:00:00 2001 From: = Date: Wed, 18 Dec 2024 21:26:09 -0300 Subject: [PATCH 16/67] source --- .../blocks/liquid/PressureLiquidBridge.java | 7 +- .../blocks/sandbox/PressureLiquidSource.java | 144 ++++++++++++++---- src/omaloon/world/modules/PressureModule.java | 6 +- 3 files changed, 119 insertions(+), 38 deletions(-) diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidBridge.java b/src/omaloon/world/blocks/liquid/PressureLiquidBridge.java index 125b2695..4bc2178f 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidBridge.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidBridge.java @@ -167,8 +167,9 @@ public boolean canDumpLiquid(Building to, Liquid liquid) { public void draw() { Draw.rect(bottomRegion, x, y); - if(liquids.currentAmount() > 0.001f){ - LiquidBlock.drawTiledFrames(size, x, y, liquidPadding, liquids.current(), liquids.currentAmount() / liquidCapacity); + Liquid main = pressure.getMain(); + if(main != null && pressure.liquids[main.id] > 0.001f){ + LiquidBlock.drawTiledFrames(size, x, y, liquidPadding, pressure.getMain(), Mathf.clamp(pressure.liquids[main.id]/(pressure.liquids[main.id] + pressure.air))); } drawBase(); @@ -186,8 +187,6 @@ public void draw() { Draw.alpha(Renderer.bridgeOpacity); drawBridge(bridgeBottomRegion, endBottomRegion, pos1, pos2); - Liquid main = pressure.getMain(); - if (main != null) { Draw.color(main.color, Mathf.clamp(pressure.liquids[main.id]/(pressure.liquids[main.id] + pressure.air)) * Renderer.bridgeOpacity); drawBridge(bridgeLiquidRegion, endLiquidRegion, pos1, pos2); diff --git a/src/omaloon/world/blocks/sandbox/PressureLiquidSource.java b/src/omaloon/world/blocks/sandbox/PressureLiquidSource.java index 5393c2bb..95a8a056 100644 --- a/src/omaloon/world/blocks/sandbox/PressureLiquidSource.java +++ b/src/omaloon/world/blocks/sandbox/PressureLiquidSource.java @@ -2,43 +2,66 @@ import arc.*; import arc.graphics.g2d.*; +import arc.math.*; +import arc.scene.style.*; +import arc.scene.ui.*; +import arc.scene.ui.ImageButton.*; import arc.scene.ui.layout.*; import arc.util.*; import arc.util.io.*; +import mindustry.*; import mindustry.entities.units.*; import mindustry.gen.*; import mindustry.type.*; import mindustry.ui.*; -import mindustry.world.blocks.sandbox.*; +import mindustry.world.*; +import mindustry.world.blocks.liquid.*; import omaloon.world.interfaces.*; import omaloon.world.meta.*; import omaloon.world.modules.*; -import static arc.scene.ui.TextField.TextFieldFilter.*; -import static arc.util.Strings.*; - -public class PressureLiquidSource extends LiquidSource { - // TODO cheap fix, this class should be remade to have proper configs - public static float lastAmount = 0; - public static boolean wasNegative = false; - +public class PressureLiquidSource extends Block { public PressureConfig pressureConfig = new PressureConfig(); + public TextureRegion bottomRegion; + public PressureLiquidSource(String name) { super(name); + solid = true; + destructible = true; + update = true; + configurable = true; + saveConfig = copyConfig = true; + + config(SourceEntry.class, (PressureLiquidSourceBuild build, SourceEntry entry) -> { + build.liquid = entry.fluid == null ? -1 : entry.fluid.id; + build.targetAmount = entry.amount; + }); } @Override public void drawPlanConfig(BuildPlan plan, Eachable list) { - Draw.rect(crossRegion, plan.drawx(), plan.drawy()); - drawPlanConfigCenter(plan, plan.config, "center", false); + Draw.rect(bottomRegion, plan.drawx(), plan.drawy()); + if (plan.config instanceof SourceEntry e && e.fluid != null) LiquidBlock.drawTiledFrames(size, plan.drawx(), plan.drawy(), 0f, e.fluid, 1f); + Draw.rect(region, plan.drawx(), plan.drawy()); } @Override public void load() { super.load(); bottomRegion = Core.atlas.find(name + "-bottom"); - crossRegion = Core.atlas.find(name + "-cross"); + } + + @Override + protected TextureRegion[] icons() { + return new TextureRegion[]{bottomRegion, region}; + } + + @Override + public void init() { + super.init(); + + if (pressureConfig.fluidGroup != null) pressureConfig.fluidGroup = FluidGroup.transportation; } @Override @@ -47,26 +70,74 @@ public void setBars() { pressureConfig.addBars(this); } - public class PressureLiquidSourceBuild extends LiquidSourceBuild implements HasPressure { + public class PressureLiquidSourceBuild extends Building implements HasPressure { PressureModule pressure = new PressureModule(); - public float pressureTarget = lastAmount; - public boolean negative = wasNegative; - @Override public boolean acceptLiquid(Building source, Liquid liquid) { - return false; + public int liquid = -1; + public float targetAmount; + + @Override + public void buildConfiguration(Table cont) { + cont.table(Styles.black6, table -> { + table.pane(Styles.smallPane, liquids -> Vars.content.liquids().each(liquid -> { + Button button = liquids.button( + new TextureRegionDrawable(liquid.uiIcon), + new ImageButtonStyle() {{ + over = Styles.flatOver; + down = checked = Tex.flatDownBase; + }}, () -> { + if (this.liquid != liquid.id) { + configure(new SourceEntry() {{ + fluid = liquid; + amount = targetAmount; + }}); + } else { + configure(new SourceEntry() {{ + fluid = null; + amount = targetAmount; + }}); + } + } + ).tooltip(liquid.localizedName).size(40f).get(); + button.update(() -> button.setChecked(liquid.id == this.liquid)); + if ((Vars.content.liquids().indexOf(liquid) + 1) % 4 == 0) liquids.row(); + })).maxHeight(160f).row(); + table.add("@filter.option.amount").padTop(5f).padBottom(5f).row(); + table.field( + "" + targetAmount, + (field, c) -> Character.isDigit(c) || ((!field.getText().contains(".")) && c == '.') || (field.getText().isEmpty() && c == '-'), + s -> configure(new SourceEntry() {{ + fluid = Vars.content.liquid(liquid); + amount = Strings.parseFloat(s, 0f); + }}) + ); + }).margin(5f); } - @Override public boolean acceptsPressure(HasPressure from, float pressure) { - return false; + + @Override + public SourceEntry config() { + return new SourceEntry() {{ + fluid = Vars.content.liquid(liquid); + amount = targetAmount; + }}; + } + + @Override + public void draw() { + Draw.rect(bottomRegion, x, y); + + if(liquid != -1) { + LiquidBlock.drawTiledFrames(size, x, y, 0f, Vars.content.liquid(liquid), 1f); + } + + Draw.rect(region, x, y); } @Override - public void buildConfiguration(Table table) { - super.buildConfiguration(table); - table.row(); - table.table(Styles.black6, cont -> { - cont.field(pressureTarget + "", floatsOnly, s -> pressureTarget = parseFloat(s, 0f)).row(); - cont.check(Core.bundle.get("omaloon-source-negative"), negative, b -> negative = b); - }).growX(); + public void onProximityUpdate() { + super.onProximityUpdate(); + + new PressureSection().mergeFlood(this); } @Override public PressureModule pressure() { @@ -80,24 +151,31 @@ public void buildConfiguration(Table table) { public void read(Reads read, byte revision) { super.read(read, revision); pressure.read(read); - pressureTarget = read.f(); - negative = read.bool(); + liquid = read.i(); + if (Vars.content.liquid(liquid) == null) liquid = -1; + targetAmount = read.f(); } @Override public void updateTile() { super.updateTile(); - pressure.pressure = pressureTarget * (negative ? -1f : 1f); - nextBuilds(true).each(b -> b.pressure().pressure = pressureTarget * (negative ? -1 : 1f)); - dumpPressure(); + + float difference = (Vars.content.liquid(liquid) == null ? targetAmount : Mathf.maxZero(targetAmount)) - (Vars.content.liquid(liquid) == null ? pressure.air : pressure.liquids[liquid]); + + addFluid(Vars.content.liquid(liquid), difference); } @Override public void write(Writes write) { super.write(write); pressure.write(write); - write.f(pressureTarget); - write.bool(negative); + write.i(liquid); + write.f(targetAmount); } } + + public static class SourceEntry { + public @Nullable Liquid fluid; + public float amount; + } } diff --git a/src/omaloon/world/modules/PressureModule.java b/src/omaloon/world/modules/PressureModule.java index c1d71737..8aa751b6 100644 --- a/src/omaloon/world/modules/PressureModule.java +++ b/src/omaloon/world/modules/PressureModule.java @@ -27,6 +27,10 @@ public void addFluid(@Nullable Liquid liquid, float amount, PressureConfig refer air += amount; pressure = air / reference.fluidCapacity * arbitraryPressureScalar; } else { + if (air < 0) { + air = 0; + pressure = 0; + } liquids[liquid.id] += amount; pressures[liquid.id] = liquids[liquid.id] / reference.fluidCapacity * arbitraryPressureScalar; } @@ -62,7 +66,7 @@ public void read(Reads read) { */ public void removeFluid(@Nullable Liquid liquid, float amount, PressureConfig reference) { if (liquid == null) { - air -= amount; + air -= (getMain() != null ? Math.min(air, amount) : amount); pressure = air / reference.fluidCapacity * arbitraryPressureScalar; } else { liquids[liquid.id] = Mathf.maxZero(liquids[liquid.id] - amount); From 5eed8871b0777e3abbfa17a33eb8286aeaad1a84 Mon Sep 17 00:00:00 2001 From: = Date: Thu, 19 Dec 2024 11:53:56 -0300 Subject: [PATCH 17/67] chainable pumps --- .../blocks/liquid/PressureLiquidJunction.java | 17 ++++++ .../blocks/liquid/PressureLiquidPump.java | 52 ++++++++++++++++--- src/omaloon/world/interfaces/HasPressure.java | 13 ----- 3 files changed, 61 insertions(+), 21 deletions(-) diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidJunction.java b/src/omaloon/world/blocks/liquid/PressureLiquidJunction.java index b7df79a7..7f127f5c 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidJunction.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidJunction.java @@ -1,8 +1,10 @@ package omaloon.world.blocks.liquid; import arc.struct.*; +import arc.util.*; import arc.util.io.*; import mindustry.gen.*; +import mindustry.type.*; import mindustry.world.*; import omaloon.world.interfaces.*; import omaloon.world.meta.*; @@ -20,6 +22,10 @@ public PressureLiquidJunction(String name) { public class PressureLiquidJunctionBuild extends Building implements HasPressure { PressureModule pressure = new PressureModule(); + @Override public boolean acceptsPressurizedFluid(HasPressure from, @Nullable Liquid liquid, float amount) { + return false; + } + @Override public boolean connects(HasPressure to) { return HasPressure.super.connects(to) && !(to instanceof PressureLiquidPump); @@ -46,6 +52,17 @@ public Seq nextBuilds(boolean flow) { return Seq.with(); } + @Override + public void onProximityUpdate() { + super.onProximityUpdate(); + + new PressureSection().mergeFlood(this); + } + + @Override public boolean outputsPressurizedFluid(HasPressure to, @Nullable Liquid liquid, float amount) { + return false; + } + @Override public PressureModule pressure() { return pressure; } diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidPump.java b/src/omaloon/world/blocks/liquid/PressureLiquidPump.java index bd052070..536eec67 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidPump.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidPump.java @@ -6,7 +6,6 @@ import arc.math.*; import arc.math.geom.*; import arc.scene.ui.layout.*; -import arc.struct.*; import arc.util.*; import arc.util.io.*; import mindustry.*; @@ -126,13 +125,24 @@ public class PressureLiquidPumpBuild extends Building implements HasPressure { public int filter = -1; + @Override public boolean acceptsPressurizedFluid(HasPressure from, @Nullable Liquid liquid, float amount) { + return false; + } + @Override public void buildConfiguration(Table table) { ItemSelection.buildTable(table, Vars.content.liquids(), () -> Vars.content.liquid(filter), other -> filter = other == null ? -1 : other.id); } + /** + * Returns the length of the pump chain + */ + public int chainSize() { + return pressure.section.builds.size; + } + @Override public boolean connects(HasPressure to) { - return HasPressure.super.connects(to) && !(to instanceof PressureLiquidPumpBuild) && (front() == to || back() == to); + return HasPressure.super.connects(to) && (front() == to || back() == to); } @Override @@ -188,9 +198,31 @@ public void draw() { if (tiling == 0) Draw.rect(topRegion, x, y, rotdeg()); } - @Override - public Seq nextBuilds(boolean flow) { - return Seq.with(); + /** + * Returns the building at the start of the pump chain. + */ + public @Nullable HasPressure getFrom() { + PressureLiquidPumpBuild last = this; + HasPressure out = back() instanceof HasPressure back ? back.getPressureDestination(last, 0) : null; + while (out instanceof PressureLiquidPumpBuild pump) { + if (!pump.connected(last)) return null; + last = pump; + out = pump.back() instanceof HasPressure back ? back.getPressureDestination(last, 0) : null; + } + return out.connected(last) ? out : null; + } + /** + * Returns the building at the end of the pump chain. + */ + public @Nullable HasPressure getTo() { + PressureLiquidPumpBuild last = this; + HasPressure out = front() instanceof HasPressure front ? front.getPressureDestination(last, 0) : null; + while (out instanceof PressureLiquidPumpBuild pump) { + if (!pump.connected(last)) return null; + last = pump; + out = pump.front() instanceof HasPressure front ? front.getPressureDestination(last, 0) : null; + } + return out.connected(last) ? out : null; } @Override @@ -205,6 +237,10 @@ public void onProximityUpdate() { new PressureSection().mergeFlood(this); } + @Override public boolean outputsPressurizedFluid(HasPressure to, @Nullable Liquid liquid, float amount) { + return false; + } + @Override public PressureModule pressure() { return pressure; } @@ -223,13 +259,13 @@ public void read(Reads read, byte revision) { public void updateTile() { super.updateTile(); if (efficiency > 0) { - HasPressure front = (front() instanceof HasPressure b && connected(b)) ? b : null; - HasPressure back = (back() instanceof HasPressure b && connected(b)) ? b : null; + HasPressure front = getTo(); + HasPressure back = getFrom(); if (front != null && back != null) { Liquid pumpLiquid = configurable ? Vars.content.liquid(filter) : back.pressure().getMain(); float frontPressure = front.pressure().getPressure(pumpLiquid), backPressure = back.pressure().getPressure(pumpLiquid); - float flow = pressureTransfer * (backPressure - frontPressure + pressureDifference); + float flow = pressureTransfer/chainSize() * (backPressure - frontPressure + pressureDifference * chainSize()); if (pumpLiquid != null) flow = Mathf.clamp(flow, -front.pressure().liquids[pumpLiquid.id], back.pressure().liquids[pumpLiquid.id]); if ( front.acceptsPressurizedFluid(back, pumpLiquid, flow) && diff --git a/src/omaloon/world/interfaces/HasPressure.java b/src/omaloon/world/interfaces/HasPressure.java index 00cde3e5..f9177a3f 100644 --- a/src/omaloon/world/interfaces/HasPressure.java +++ b/src/omaloon/world/interfaces/HasPressure.java @@ -47,19 +47,6 @@ default boolean connects(HasPressure to) { return pressureConfig().outputsPressure || pressureConfig().acceptsPressure; } - /** - * dumps pressure onto available builds - */ - default void dumpPressure() { -// for (HasPressure other : nextBuilds(true)) { -// float diff = (getPressure() - other.getPressure()) / 2f; -// if (other.getPressure() > getPressure()) diff *= -1f; -// if (canDumpPressure(other, diff)) { -// transferPressure(other, diff); -// } -// } - } - /** * @return current pressure of the building */ From 18b3bbc7c42ce21e285fc3151f1cb70620eaf863 Mon Sep 17 00:00:00 2001 From: = Date: Thu, 19 Dec 2024 17:35:38 -0300 Subject: [PATCH 18/67] smooth --- .../blocks/liquid/PressureLiquidBridge.java | 21 ++++++------ .../blocks/liquid/PressureLiquidConduit.java | 17 +++++++--- .../blocks/liquid/PressureLiquidPump.java | 19 +++++++---- .../blocks/liquid/PressureLiquidValve.java | 14 +++++--- src/omaloon/world/modules/PressureModule.java | 33 ++++++++++++++++--- 5 files changed, 74 insertions(+), 30 deletions(-) diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidBridge.java b/src/omaloon/world/blocks/liquid/PressureLiquidBridge.java index 4bc2178f..7adc9ab8 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidBridge.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidBridge.java @@ -153,6 +153,8 @@ public void setStats() { public class PressureLiquidBridgeBuild extends TubeItemBridgeBuild implements HasPressure { PressureModule pressure = new PressureModule(); + public float smoothAlpha; + @Override public boolean acceptsPressurizedFluid(HasPressure from, @Nullable Liquid liquid, float amount) { return HasPressure.super.acceptsPressurizedFluid(from, liquid, amount) && (liquid == pressure.getMain() || liquid == null || pressure.getMain() == null || from.pressure().getMain() == null); @@ -168,8 +170,11 @@ public void draw() { Draw.rect(bottomRegion, x, y); Liquid main = pressure.getMain(); - if(main != null && pressure.liquids[main.id] > 0.001f){ - LiquidBlock.drawTiledFrames(size, x, y, liquidPadding, pressure.getMain(), Mathf.clamp(pressure.liquids[main.id]/(pressure.liquids[main.id] + pressure.air))); + + smoothAlpha = Mathf.approachDelta(smoothAlpha, main == null ? 0f : pressure.liquids[main.id]/(pressure.liquids[main.id] + pressure.air), PressureModule.smoothingSpeed); + + if(smoothAlpha > 0.001f){ + LiquidBlock.drawTiledFrames(size, x, y, liquidPadding, pressure.current, Mathf.clamp(smoothAlpha)); } drawBase(); @@ -187,8 +192,8 @@ public void draw() { Draw.alpha(Renderer.bridgeOpacity); drawBridge(bridgeBottomRegion, endBottomRegion, pos1, pos2); - if (main != null) { - Draw.color(main.color, Mathf.clamp(pressure.liquids[main.id]/(pressure.liquids[main.id] + pressure.air)) * Renderer.bridgeOpacity); + if (smoothAlpha > 0.001f) { + Draw.color(pressure.current.color, Mathf.clamp(smoothAlpha) * Renderer.bridgeOpacity); drawBridge(bridgeLiquidRegion, endLiquidRegion, pos1, pos2); Draw.color(); } @@ -229,6 +234,7 @@ public boolean outputsPressurizedFluid(HasPressure to, Liquid liquid, float amou public void read(Reads read, byte revision) { super.read(read, revision); pressure.read(read); + smoothAlpha = read.f(); } @Override @@ -287,12 +293,7 @@ protected void drawInput(Tile other){ public void write(Writes write) { super.write(write); pressure.write(write); - } - - @Override - public void read(Reads read){ - super.read(read); - pressure.read(read); + write.f(smoothAlpha); } } } diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidConduit.java b/src/omaloon/world/blocks/liquid/PressureLiquidConduit.java index 42c4d422..c20e51e4 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidConduit.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidConduit.java @@ -143,9 +143,11 @@ public void setStats() { } public class PressureLiquidConduitBuild extends Building implements HasPressure { - public int tiling = 0; PressureModule pressure = new PressureModule(); + public int tiling = 0; + public float smoothAlpha; + @Override public boolean acceptsPressurizedFluid(HasPressure from, @Nullable Liquid liquid, float amount) { return HasPressure.super.acceptsPressurizedFluid(from, liquid, amount) && (liquid == pressure.getMain() || liquid == null || pressure.getMain() == null || from.pressure().getMain() == null); @@ -163,13 +165,16 @@ public boolean connects(HasPressure to) { public void draw() { Draw.rect(bottomRegion, x, y); Liquid main = pressure.getMain(); - if (main != null && pressure.liquids[main.id] > 0.01f) { - int frame = main.getAnimationFrame(); - int gas = main.gas ? 1 : 0; + + smoothAlpha = Mathf.approachDelta(smoothAlpha, main == null ? 0f : pressure.liquids[main.id]/(pressure.liquids[main.id] + pressure.air), PressureModule.smoothingSpeed); + + if (smoothAlpha > 0.001f) { + int frame = pressure.current.getAnimationFrame(); + int gas = pressure.current.gas ? 1 : 0; float xscl = Draw.xscl, yscl = Draw.yscl; Draw.scl(1f, 1f); - Drawf.liquid(liquidRegions[gas][frame], x, y, Mathf.clamp(pressure.liquids[main.id]/(pressure.liquids[main.id] + pressure.air)), main.color.write(Tmp.c1).a(1f)); + Drawf.liquid(liquidRegions[gas][frame], x, y, Mathf.clamp(smoothAlpha), pressure.current.color.write(Tmp.c1).a(1f)); Draw.scl(xscl, yscl); } Draw.rect(topRegions[tiling], x, y, tiling != 0 ? 0 : (rotdeg() + 90) % 180 - 90); @@ -206,6 +211,7 @@ public boolean outputsPressurizedFluid(HasPressure to, Liquid liquid, float amou public void read(Reads read, byte revision) { super.read(read, revision); pressure.read(read); + smoothAlpha = read.f(); } @Override @@ -217,6 +223,7 @@ public void updateTile() { public void write(Writes write) { super.write(write); pressure.write(write); + write.f(smoothAlpha); } } } diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidPump.java b/src/omaloon/world/blocks/liquid/PressureLiquidPump.java index 536eec67..00155bea 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidPump.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidPump.java @@ -122,6 +122,7 @@ public class PressureLiquidPumpBuild extends Building implements HasPressure { PressureModule pressure = new PressureModule(); public int tiling; + public float smoothAlpha; public int filter = -1; @@ -151,8 +152,8 @@ public void draw() { if (tiling != 0) { Draw.rect(bottomRegion, x, y, rotdeg()); - HasPressure front = (front() instanceof HasPressure b && connected(b)) ? b : null; - HasPressure back = (back() instanceof HasPressure b && connected(b)) ? b : null; + HasPressure front = getTo(); + HasPressure back = getFrom(); if ( (front != null && front.pressure().getMain() != null) || @@ -177,11 +178,13 @@ public void draw() { (back != null && back.pressure().getMain() != null ? Mathf.clamp(back.pressure().liquids[back.pressure().getMain().id]/(back.pressure().liquids[back.pressure().getMain().id] + back.pressure().air)) : 0); alpha /= ((front == null ? 0 : 1f) + (back == null ? 0 : 1f)); + smoothAlpha = Mathf.approachDelta(smoothAlpha, alpha, PressureModule.smoothingSpeed); + Liquid drawLiquid = Liquids.water; if (front != null && front.pressure().getMain() != null) { - drawLiquid = front.pressure().getMain(); + drawLiquid = front.pressure().current; } else if (back != null && back.pressure().getMain() != null) { - drawLiquid = back.pressure().getMain(); + drawLiquid = back.pressure().current; } int frame = drawLiquid.getAnimationFrame(); @@ -189,7 +192,7 @@ public void draw() { float xscl = Draw.xscl, yscl = Draw.yscl; Draw.scl(1f, 1f); - Drawf.liquid(liquidRegions[gas][frame], x, y, alpha, tmpColor); + Drawf.liquid(liquidRegions[gas][frame], x, y, smoothAlpha, tmpColor); Draw.scl(xscl, yscl); } Draw.rect(arrowRegion, x, y, rotdeg()); @@ -209,7 +212,7 @@ public void draw() { last = pump; out = pump.back() instanceof HasPressure back ? back.getPressureDestination(last, 0) : null; } - return out.connected(last) ? out : null; + return (out != null && out.connected(last)) ? out : null; } /** * Returns the building at the end of the pump chain. @@ -222,7 +225,7 @@ public void draw() { last = pump; out = pump.front() instanceof HasPressure front ? front.getPressureDestination(last, 0) : null; } - return out.connected(last) ? out : null; + return (out != null && out.connected(last)) ? out : null; } @Override @@ -253,6 +256,7 @@ public void read(Reads read, byte revision) { super.read(read, revision); pressure.read(read); filter = read.i(); + smoothAlpha = read.f(); } @Override @@ -283,6 +287,7 @@ public void write(Writes write) { super.write(write); pressure.write(write); write.i(filter); + write.f(smoothAlpha); } } } diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidValve.java b/src/omaloon/world/blocks/liquid/PressureLiquidValve.java index f3357877..a51db7f7 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidValve.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidValve.java @@ -135,6 +135,7 @@ public class PressureLiquidValveBuild extends Building implements HasPressure { public float draining; public float effectInterval; public int tiling; + public float smoothAlpha; public boolean jammed; @@ -155,13 +156,16 @@ public void draw() { float rot = rotate ? (90 + rotdeg()) % 180 - 90 : 0; Draw.rect(bottomRegion, x, y, rotation); Liquid main = pressure.getMain(); - if (main != null && pressure.liquids[main.id] > 0.01f) { - int frame = main.getAnimationFrame(); - int gas = main.gas ? 1 : 0; + + smoothAlpha = Mathf.approachDelta(smoothAlpha, main == null ? 0f : pressure.liquids[main.id]/(pressure.liquids[main.id] + pressure.air), PressureModule.smoothingSpeed); + + if (smoothAlpha > 0.01f) { + int frame = pressure.current.getAnimationFrame(); + int gas = pressure.current.gas ? 1 : 0; float xscl = Draw.xscl, yscl = Draw.yscl; Draw.scl(1f, 1f); - Drawf.liquid(liquidRegions[gas][frame], x, y, Mathf.clamp(pressure.liquids[main.id]/(pressure.liquids[main.id] + pressure.air)), main.color.write(Tmp.c1).a(1f)); + Drawf.liquid(liquidRegions[gas][frame], x, y, Mathf.clamp(smoothAlpha), pressure.current.color.write(Tmp.c1).a(1f)); Draw.scl(xscl, yscl); } Draw.rect(tiles[tiling], x, y, rot); @@ -199,6 +203,7 @@ public void read(Reads read, byte revision) { pressure.read(read); jammed = read.bool(); draining = read.f(); + smoothAlpha = read.f(); } @Override @@ -251,6 +256,7 @@ public void write(Writes write) { pressure.write(write); write.bool(jammed); write.f(draining); + write.f(smoothAlpha); } } } diff --git a/src/omaloon/world/modules/PressureModule.java b/src/omaloon/world/modules/PressureModule.java index 8aa751b6..3caec27e 100644 --- a/src/omaloon/world/modules/PressureModule.java +++ b/src/omaloon/world/modules/PressureModule.java @@ -4,12 +4,14 @@ import arc.util.*; import arc.util.io.*; import mindustry.*; +import mindustry.content.*; import mindustry.type.*; import mindustry.world.modules.*; import omaloon.world.meta.*; public class PressureModule extends BlockModule { public static float arbitraryPressureScalar = 10f; + public static float smoothingSpeed = 0.03f; public float[] liquids = new float[Vars.content.liquids().size]; public float[] pressures = new float[Vars.content.liquids().size]; @@ -17,7 +19,7 @@ public class PressureModule extends BlockModule { public PressureSection section = new PressureSection(); - public @Nullable Liquid current; + public Liquid current = Liquids.water; /** * Adds a certain amount of a fluid into this module, updating it's pressure accordingly. A null liquid means that air is being added to it. @@ -34,13 +36,13 @@ public void addFluid(@Nullable Liquid liquid, float amount, PressureConfig refer liquids[liquid.id] += amount; pressures[liquid.id] = liquids[liquid.id] / reference.fluidCapacity * arbitraryPressureScalar; } - current = liquid; + if (liquid != null) current = liquid; } public @Nullable Liquid getMain() { Liquid out = null; for(int i = 0; i < liquids.length; i++) { - if (out == null && liquids[i] > 0) out = Vars.content.liquid(i); + if (out == null && liquids[i] > 0.01) out = Vars.content.liquid(i); if (out != null && liquids[i] > liquids[out.id]) out = Vars.content.liquid(i); } return out; @@ -58,7 +60,21 @@ public float getPressure(@Nullable Liquid liquid) { @Override public void read(Reads read) { + air = read.f(); pressure = read.f(); + + int count = read.s(); + + for(int i = 0; i < count; i++){ + Liquid liq = Vars.content.liquid(read.s()); + float amount = read.f(); + float pressure = read.f(); + if(liq != null){ + if (amount > 0) current = liq; + liquids[liq.id] = amount; + pressures[liq.id] = pressure; + } + } } /** @@ -72,11 +88,20 @@ public void removeFluid(@Nullable Liquid liquid, float amount, PressureConfig re liquids[liquid.id] = Mathf.maxZero(liquids[liquid.id] - amount); pressures[liquid.id] = liquids[liquid.id] / reference.fluidCapacity * arbitraryPressureScalar; } - current = liquid; + if (liquid != null) current = liquid; } @Override public void write(Writes write) { + write.f(air); write.f(pressure); + + write.s(liquids.length); + + for(int i = 0; i < liquids.length; i++){ + write.s(i); //liquid ID + write.f(liquids[i]); //liquid amount + write.f(pressures[i]); //liquid amount + } } } From 965f01f1c51d3d4e5971d2efadb254caabc9dfde Mon Sep 17 00:00:00 2001 From: = Date: Fri, 20 Dec 2024 17:47:11 -0300 Subject: [PATCH 19/67] =?UTF-8?q?m=C3=A6th?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/omaloon/math/OlMath.java | 20 +++++++++++++++++++ .../blocks/liquid/PressureLiquidValve.java | 7 ++++--- 2 files changed, 24 insertions(+), 3 deletions(-) create mode 100644 src/omaloon/math/OlMath.java diff --git a/src/omaloon/math/OlMath.java b/src/omaloon/math/OlMath.java new file mode 100644 index 00000000..e8c7f8b4 --- /dev/null +++ b/src/omaloon/math/OlMath.java @@ -0,0 +1,20 @@ +package omaloon.math; + +import arc.math.*; + +public class OlMath { + /** + * Solves for the flow of a fluid through an area based on a difference of pressure. + * + * area is in world units squared. + * pressureStart and pressureEnd are in pascals + * density is in liquid units / world units cubed + * time is in ticks + * + * returns the amount of fluid in liquid units that passes through the area over a certain time. + */ + public static float bernoulliFlowRate(float area, float pressureStart, float pressureEnd, float density, float time) { + float diff = -2f * (pressureEnd - pressureStart); + return (area * (diff/Math.abs(diff)) * Mathf.sqrt(Math.abs(diff) / density) * time * density)/(60f); + } +} diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidValve.java b/src/omaloon/world/blocks/liquid/PressureLiquidValve.java index a51db7f7..473903bd 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidValve.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidValve.java @@ -16,6 +16,7 @@ import mindustry.type.*; import mindustry.world.*; import omaloon.content.*; +import omaloon.math.*; import omaloon.utils.*; import omaloon.world.interfaces.*; import omaloon.world.meta.*; @@ -38,7 +39,7 @@ public class PressureLiquidValve extends Block { public Effect pumpingEffectIn = OlFx.pumpIn; public float pumpingEffectInterval = 15; - public float pressureLoss = 0.05f; + public float pressureLoss = 1f; public float minPressureLoss = 0.05f; public float openMin = -15f; @@ -216,13 +217,13 @@ public void updatePressure() { if (jammed) return; if (pressureAmount < openMin) { effectInterval += delta(); - addFluid(null, Math.max(minPressureLoss, pressureLoss * Math.abs(pressureAmount - openMin)/10f)); + addFluid(null, Math.min(openMin - pressureAmount, OlMath.bernoulliFlowRate(pressureLoss, 0, pressureAmount, 1f, 1f))); draining = Mathf.approachDelta(draining, 1, 0.014f); } if (pressureAmount > openMax) { effectInterval += delta(); - removeFluid(pressure.getMain(), Math.max(minPressureLoss, pressureLoss * Math.abs(pressureAmount - openMax)/10f)); + removeFluid(pressure.getMain(), Math.min(pressureAmount - openMax, OlMath.bernoulliFlowRate(pressureLoss, pressureAmount, 0, 1f, 1f))); draining = Mathf.approachDelta(draining, 1, 0.014f); } if (effectInterval > pumpingEffectInterval) { From c968f0477dbecae9df67203b857d4963d609b6f1 Mon Sep 17 00:00:00 2001 From: = Date: Sun, 29 Dec 2024 15:35:51 -0300 Subject: [PATCH 20/67] this can be removed :3 --- .../world/blocks/liquid/PressureLiquidJunction.java | 2 +- src/omaloon/world/interfaces/HasPressure.java | 7 ------- 2 files changed, 1 insertion(+), 8 deletions(-) diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidJunction.java b/src/omaloon/world/blocks/liquid/PressureLiquidJunction.java index 7f127f5c..e2870bfb 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidJunction.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidJunction.java @@ -37,7 +37,7 @@ public HasPressure getPressureDestination(HasPressure source, float pressure) { int dir = (source.relativeTo(tile.x, tile.y) + 4) % 4; HasPressure next = nearby(dir) instanceof HasPressure ? (HasPressure) nearby(dir) : null; - if(next == null || (!next.acceptsPressure(source, pressure) && !(next.block() instanceof PressureLiquidJunction))){ + if(next == null || !(next.block() instanceof PressureLiquidJunction)){ return this; } return next.getPressureDestination(this, pressure); diff --git a/src/omaloon/world/interfaces/HasPressure.java b/src/omaloon/world/interfaces/HasPressure.java index f9177a3f..e7ea75e0 100644 --- a/src/omaloon/world/interfaces/HasPressure.java +++ b/src/omaloon/world/interfaces/HasPressure.java @@ -14,13 +14,6 @@ * only added this cause my ide did a funni */ public interface HasPressure extends Buildingc { - /** - * @return true if this building accepts a certain pressure amount from some building - */ - default boolean acceptsPressure(HasPressure from, float pressure) { - return getPressure() + pressure <= from.getPressure() - pressure; - } - default boolean acceptsPressurizedFluid(HasPressure from, @Nullable Liquid liquid, float amount) { return pressureConfig().acceptsPressure; } From 935c72f4879c5b668009d442094f1f56351a60c9 Mon Sep 17 00:00:00 2001 From: = Date: Sun, 29 Dec 2024 21:23:18 -0300 Subject: [PATCH 21/67] some fixes and more cleanup + a convenient --- src/omaloon/math/OlMath.java | 1 + src/omaloon/ui/dialogs/EventHints.java | 24 +++++++------------ .../blocks/liquid/PressureLiquidBridge.java | 4 ++-- .../blocks/liquid/PressureLiquidJunction.java | 2 +- src/omaloon/world/consumers/ConsumeFluid.java | 2 +- src/omaloon/world/interfaces/HasPressure.java | 11 ++------- src/omaloon/world/meta/PressureSection.java | 2 +- src/omaloon/world/modules/PressureModule.java | 8 +++++++ 8 files changed, 25 insertions(+), 29 deletions(-) diff --git a/src/omaloon/math/OlMath.java b/src/omaloon/math/OlMath.java index e8c7f8b4..ae7b5076 100644 --- a/src/omaloon/math/OlMath.java +++ b/src/omaloon/math/OlMath.java @@ -15,6 +15,7 @@ public class OlMath { */ public static float bernoulliFlowRate(float area, float pressureStart, float pressureEnd, float density, float time) { float diff = -2f * (pressureEnd - pressureStart); + if (diff == 0) return 0f; return (area * (diff/Math.abs(diff)) * Mathf.sqrt(Math.abs(diff) / density) * time * density)/(60f); } } diff --git a/src/omaloon/ui/dialogs/EventHints.java b/src/omaloon/ui/dialogs/EventHints.java index 904862b2..b560ed27 100644 --- a/src/omaloon/ui/dialogs/EventHints.java +++ b/src/omaloon/ui/dialogs/EventHints.java @@ -7,18 +7,17 @@ import mindustry.*; import mindustry.ui.fragments.HintsFragment.*; import omaloon.content.blocks.*; -import omaloon.world.interfaces.*; public enum EventHints implements Hint { - drill_positive_pressure( - () -> false, - () -> Vars.state.teams.get(Vars.state.rules.defaultTeam).getBuildings(OlProductionBlocks.hammerDrill).find(b -> ((HasPressure) b).getPressure() > 0f) != null - ), - press_or_shelter_negative_pressure( - () -> false, - () -> Vars.state.teams.get(Vars.state.rules.defaultTeam).getBuildings(OlCraftingBlocks.carborundumPress).find(b -> ((HasPressure) b).getPressure() < 0f) != null - || Vars.state.teams.get(Vars.state.rules.defaultTeam).getBuildings(OlDefenceBlocks.smallShelter).find(b -> ((HasPressure) b).getPressure() < 0f) != null - ), +// drill_positive_pressure( +// () -> false, +// () -> Vars.state.teams.get(Vars.state.rules.defaultTeam).getBuildings(OlProductionBlocks.hammerDrill).find(b -> ((HasPressure) b).getPressure() > 0f) != null +// ), +// press_or_shelter_negative_pressure( +// () -> false, +// () -> Vars.state.teams.get(Vars.state.rules.defaultTeam).getBuildings(OlCraftingBlocks.carborundumPress).find(b -> ((HasPressure) b).getPressure() < 0f) != null +// || Vars.state.teams.get(Vars.state.rules.defaultTeam).getBuildings(OlDefenceBlocks.smallShelter).find(b -> ((HasPressure) b).getPressure() < 0f) != null +// ), pump( () -> false, () -> !Vars.state.teams.get(Vars.state.rules.defaultTeam).getBuildings(OlDistributionBlocks.liquidPump).isEmpty() @@ -27,11 +26,6 @@ public enum EventHints implements Hint { () -> false, () -> !Vars.state.teams.get(Vars.state.rules.defaultTeam).getBuildings(OlDistributionBlocks.liquidValve).isEmpty(), pump - ), - low_pressure( - () -> !Vars.state.teams.get(Vars.state.rules.defaultTeam).getBuildings(OlDistributionBlocks.liquidValve).isEmpty(), - () -> Vars.state.teams.get(Vars.state.rules.defaultTeam).buildings.contains( - b -> b instanceof HasPressure pressure && pressure.getPressure() < 0) ); final Boolp complete; diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidBridge.java b/src/omaloon/world/blocks/liquid/PressureLiquidBridge.java index 7adc9ab8..59f31ed0 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidBridge.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidBridge.java @@ -204,8 +204,8 @@ public void draw() { } @Override - public Seq nextBuilds(boolean flow) { - Seq o = HasPressure.super.nextBuilds(flow); + public Seq nextBuilds() { + Seq o = HasPressure.super.nextBuilds(); if (Vars.world.build(link) instanceof PressureLiquidBridgeBuild b) o.add(b); for(int pos : incoming.items) if (Vars.world.build(pos) instanceof PressureLiquidBridgeBuild b) o.add(b); return o; diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidJunction.java b/src/omaloon/world/blocks/liquid/PressureLiquidJunction.java index e2870bfb..1462277a 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidJunction.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidJunction.java @@ -48,7 +48,7 @@ public HasPressure getPressureDestination(HasPressure source, float pressure) { } @Override - public Seq nextBuilds(boolean flow) { + public Seq nextBuilds() { return Seq.with(); } diff --git a/src/omaloon/world/consumers/ConsumeFluid.java b/src/omaloon/world/consumers/ConsumeFluid.java index ccfef804..be2b3240 100644 --- a/src/omaloon/world/consumers/ConsumeFluid.java +++ b/src/omaloon/world/consumers/ConsumeFluid.java @@ -92,7 +92,7 @@ public float efficiencyMultiplier(Building build) { public boolean shouldConsume(HasPressure build) { if (startRange == endRange) return true; - return startRange <= build.getPressure() && build.getPressure() <= endRange && (fluid == null || build.pressure().liquids[fluid.id] > amount); + return startRange <= build.pressure().getPressure(fluid) && build.pressure().getPressure(fluid) <= endRange && (fluid == null || build.pressure().liquids[fluid.id] > amount); } @Override public void trigger(Building build) { diff --git a/src/omaloon/world/interfaces/HasPressure.java b/src/omaloon/world/interfaces/HasPressure.java index e7ea75e0..88ffb70e 100644 --- a/src/omaloon/world/interfaces/HasPressure.java +++ b/src/omaloon/world/interfaces/HasPressure.java @@ -40,13 +40,6 @@ default boolean connects(HasPressure to) { return pressureConfig().outputsPressure || pressureConfig().acceptsPressure; } - /** - * @return current pressure of the building - */ - default float getPressure() { - return pressure().pressure; - } - /** * @return building destination to dump pressure */ @@ -63,9 +56,9 @@ default HasPressure getPressureDestination(HasPressure from, float pressure) { } /** - * @param flow determines if the returned value will have only builds to which it can flow pressure to + * Returns the next builds that this block will connect to */ - default Seq nextBuilds(boolean flow) { + default Seq nextBuilds() { return proximity().select( b -> b instanceof HasPressure ).as().map( diff --git a/src/omaloon/world/meta/PressureSection.java b/src/omaloon/world/meta/PressureSection.java index 3822d751..6fc1fe2b 100644 --- a/src/omaloon/world/meta/PressureSection.java +++ b/src/omaloon/world/meta/PressureSection.java @@ -42,7 +42,7 @@ public void mergeFlood(HasPressure other) { while(!tmp.isEmpty()) { HasPressure next = tmp.pop(); tmp2.addUnique(next); - next.nextBuilds(false).each(b -> { + next.nextBuilds().each(b -> { if (b.getSectionDestination(next) != null && !tmp2.contains(b.getSectionDestination(next))) { tmp.add(b.getSectionDestination(next)); } diff --git a/src/omaloon/world/modules/PressureModule.java b/src/omaloon/world/modules/PressureModule.java index 3caec27e..bc4cb48e 100644 --- a/src/omaloon/world/modules/PressureModule.java +++ b/src/omaloon/world/modules/PressureModule.java @@ -39,6 +39,14 @@ public void addFluid(@Nullable Liquid liquid, float amount, PressureConfig refer if (liquid != null) current = liquid; } + public float get(@Nullable Liquid liquid) { + if (liquid == null) { + return air; + } else { + return liquids[liquid.id]; + } + } + public @Nullable Liquid getMain() { Liquid out = null; for(int i = 0; i < liquids.length; i++) { From 1f678c9beb4f86eed9fced13807369345b3263c2 Mon Sep 17 00:00:00 2001 From: Elizabeth Aurora <84468589+uujuju1@users.noreply.github.com> Date: Mon, 6 Jan 2025 22:03:11 -0300 Subject: [PATCH 22/67] Revert "Fix EntityAnno" --- .github/workflows/ci.yml | 42 ------ .github/workflows/commit.yml | 24 ++++ .github/workflows/pr.yml | 24 ++++ .gitignore | 5 +- README.md | 22 ++- build.gradle | 223 +++++++++++++++++++++++++++++++ build.gradle.kts | 237 --------------------------------- gradle.properties | 10 +- settings.gradle | 13 ++ settings.gradle.kts | 18 --- src/omaloon/utils/OlUtils.java | 4 +- 11 files changed, 301 insertions(+), 321 deletions(-) delete mode 100644 .github/workflows/ci.yml create mode 100644 .github/workflows/commit.yml create mode 100644 .github/workflows/pr.yml create mode 100644 build.gradle delete mode 100644 build.gradle.kts create mode 100644 settings.gradle delete mode 100644 settings.gradle.kts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml deleted file mode 100644 index 9fecb912..00000000 --- a/.github/workflows/ci.yml +++ /dev/null @@ -1,42 +0,0 @@ -name: Omaloon Build CI - -on: - push: - pull_request: - release: - types: - - created - -permissions: - contents: write - -jobs: - buildJar: - name: Build and Publish Jar - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - name: Set up JDK 17 - uses: actions/setup-java@v4 - with: - java-version: 17 - distribution: temurin - - name: Setup Gradle - uses: gradle/actions/setup-gradle@v4 - - name: Build mod artifact - run: | - chmod +x gradlew - ./gradlew clean dex - - name: Upload built mod artifact as a GitHub Action artifact - uses: actions/upload-artifact@v4 - if: github.event_name == 'push' || github.event_name == 'pull_request' - with: - name: Omaloon (zipped) - path: build/libs/Omaloon.jar - if-no-files-found: error - compression-level: 0 - - name: Upload built mod artifact into release - uses: softprops/action-gh-release@v2 - if: github.event_name == 'release' && github.event.action == 'created' - with: - files: build/libs/Omaloon.jar \ No newline at end of file diff --git a/.github/workflows/commit.yml b/.github/workflows/commit.yml new file mode 100644 index 00000000..ca713486 --- /dev/null +++ b/.github/workflows/commit.yml @@ -0,0 +1,24 @@ +name: Omaloon Commit + +on: [push] + +jobs: + buildJar: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + - name: Set up PATH + run: | + echo "${ANDROID_HOME}/build-tools/30.0.1" >> $GITHUB_PATH + - name: Set up JDK 17 + uses: actions/setup-java@v1 + with: + java-version: 17 + - name: Build mod jar + run: ./gradlew clean dex + - name: Upload built jar file + uses: actions/upload-artifact@v4 + with: + name: ${{ github.event.repository.name }} + path: build/libs/${{ github.event.repository.name }}.jar diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml new file mode 100644 index 00000000..1f190b22 --- /dev/null +++ b/.github/workflows/pr.yml @@ -0,0 +1,24 @@ +name: Omaloon Pull Request + +on: [pull_request] + +jobs: + buildJar: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + - name: Set up PATH + run: | + echo "${ANDROID_HOME}/build-tools/30.0.1" >> $GITHUB_PATH + - name: Set up JDK 17 + uses: actions/setup-java@v1 + with: + java-version: 17 + - name: Build mod jar + run: ./gradlew clean dex + - name: Upload built jar file + uses: actions/upload-artifact@v4 + with: + name: ${{ github.event.repository.name }} Pull Request + path: build/libs/${{ github.event.repository.name }}.jar diff --git a/.gitignore b/.gitignore index d3d0d568..0369c8d4 100644 --- a/.gitignore +++ b/.gitignore @@ -148,7 +148,4 @@ gradle-app.setting Thumbs.db android/libs/ /.run/*.run.xml -modsDirectories.txt - -# Mindustry Client -/run/ \ No newline at end of file +modsDirectories.txt \ No newline at end of file diff --git a/README.md b/README.md index 31f498e0..19838e62 100644 --- a/README.md +++ b/README.md @@ -7,9 +7,7 @@ [![Download](https://img.shields.io/github/v/release/xStaBUx/Omaloon-mod-public?color=6aa84f&include_prereleases&label=Latest%20version&logo=github&logoColor=white&style=for-the-badge)](https://github.com/xStaBUx/Omaloon-mod-public/releases) [![Total Downloads](https://img.shields.io/github/downloads/xStaBUx/Omaloon-mod-public/total?color=7289da&label&logo=docusign&logoColor=white&style=for-the-badge)](https://github.com/xStaBUx/Omaloon-mod-public/releases) -> An ambitious [Mindustry](https://github.com/Anuken/Mindustry) mod -developed by [stabu](https://github.com/stabu-dev) and [uujuju](https://github.com/uujuju1). -Mod aimed at expanding a campaign by adding a new star system. +An ambitious [Mindustry](https://github.com/Anuken/Mindustry) modification developed by stabu and uujuju. This mod aims to expand the game's standard campaign by adding a new star system. ## Building from Source @@ -47,9 +45,13 @@ The built mod will be in the `build/libs` directory. To test the mod directly: ```bash -gradlew runClient +gradlew run +``` + +To install the mod to your Mindustry mods folder: +```bash +gradlew installJar ``` -This Mindustry client uses the `run` directory to store its data. ## Contributing @@ -60,18 +62,12 @@ This Mindustry client uses the `run` directory to store its data. ### Feature Suggestions - Join our [Discord server](https://discord.gg/bNMT82Hswb) to suggest new content -- Provide examples and specific arguments why your suggestion should be added to Omaloon - The Issues section is reserved for bug reports only -### Game-play Feedback -- Share your thoughts on game-play and balancing in our Discord +### Balance Feedback +- Share your thoughts on content balancing in our Discord - Provide specific examples and reasoning for balance changes -### Pull Requests -- Improve Omaloon's code/sprites/localization and propose these changes to us by creating a [Pull Request](https://github.com/stabu-dev/Omaloon/pulls). -- Make sure your code works properly and doesn't cause any issues. -- Provide specific reasoning why your Pull Request should be accepted. - ## Credits ### Developers diff --git a/build.gradle b/build.gradle new file mode 100644 index 00000000..98322657 --- /dev/null +++ b/build.gradle @@ -0,0 +1,223 @@ +import arc.files.* +import arc.util.* + +import java.util.regex.* + +buildscript{ + dependencies{ + classpath "com.github.Anuken.Arc:arc-core:$arcVersion" + } + + repositories{ + mavenCentral() + maven{url 'https://oss.sonatype.org/content/repositories/snapshots/'} + maven{url 'https://oss.sonatype.org/content/repositories/releases/'} + maven{url 'https://raw.githubusercontent.com/Zelaux/MindustryRepo/master/repository'} + maven{url 'https://jitpack.io'} + } +} + +plugins{ + // Register `EntityAnno` plugin, but only apply on `rootProject`. + id 'java' + id 'com.github.GlennFolker.EntityAnno' version "$entVersion" apply false +} + +configure(allprojects){ + sourceSets.main.java.srcDirs = [layout.projectDirectory.dir('src')] + + ext{ + compilerVersion = JavaVersion.current().ordinal() - JavaVersion.VERSION_17.ordinal() + 17 + useJitpack = Boolean.valueOf(mindustryBE) + + arc = {String module -> + return "com.github.Anuken.Arc$module:$arcVersion" + } + arcLibrary = {String module -> + return "com.github.Zelaux.ArcLibrary$module:$arcLibraryVersion" + } + mindustry = {String module -> + return "com.github.Anuken.Mindustry$module:$mindustryVersion" + } + } + + configurations.configureEach{ + // Resolve the correct Mindustry dependency, and force Arc version. + resolutionStrategy.eachDependency{ + if(useJitpack && requested.group == 'com.github.Anuken.Mindustry'){ + useTarget "com.github.Anuken.MindustryJitpack:$it.requested.name:$mindustryBEVersion" + } + + if(requested.group == 'com.github.Anuken.Arc'){ + useVersion arcVersion + } + } + } + + dependencies{ + // Downgrade Java 9+ syntax into being available in Java 8. + annotationProcessor "com.github.GlennFolker.EntityAnno:downgrader:$entVersion" + } + + repositories{ + // Necessary Maven repositories to pull dependencies from. + mavenCentral() + maven{url 'https://oss.sonatype.org/content/repositories/snapshots/'} + maven{url 'https://oss.sonatype.org/content/repositories/releases/'} + + // Use Zelaux's non-buggy repository for release Mindustry and Arc builds. + if(!useJitpack) maven{url 'https://raw.githubusercontent.com/Zelaux/MindustryRepo/master/repository'} + maven{url 'https://raw.githubusercontent.com/Zelaux/Repo/master/repository'}//for ArcLibrary + maven{url 'https://jitpack.io'} + } + + tasks.withType(JavaCompile).configureEach{ + // Use Java 17+ syntax, but target Java 8 bytecode version. + sourceCompatibility = compilerVersion + options.release.set 8 + options.compilerArgs << '-Xlint:-options' + + options.incremental = true + options.encoding = 'UTF-8' + } +} + +configure(rootProject){ + // Apply `EntityAnno` plugin to integrate the annotation processors. + apply plugin: 'com.github.GlennFolker.EntityAnno' + + entityAnno{ + modName = property('modName') + mindustryVersion = property(useJitpack ? 'mindustryBEVersion' : 'mindustryVersion') + isJitpack = useJitpack + revisionDir = layout.projectDirectory.dir('revisions').asFile + fetchPackage = modFetch + genSrcPackage = modGenSrc + genPackage = modGen + } + + dependencies{ + // Use the entity generation annotation processor. + compileOnly "com.github.GlennFolker.EntityAnno:entity:$entVersion" + kapt "com.github.GlennFolker.EntityAnno:entity:$entVersion" + + compileOnly "org.jetbrains:annotations:24.0.1" + + // Depend on Mindustry/Arc classpath. + compileOnly "${mindustry(':core')}" + compileOnly "${arc(':arc-core')}" + implementation "${arcLibrary(':graphics-draw3d')}" + implementation "${arcLibrary(':graphics-dashDraw')}" + implementation "${arcLibrary(':graphics-extendedDraw')}" + } + + jar{ + archiveFileName = "${modArtifact}Desktop.jar" + + from files(sourceSets.main.output.classesDirs) + from files(sourceSets.main.output.resourcesDir) + from configurations.runtimeClasspath.collect{it.isDirectory() ? it : zipTree(it)} + + from files(layout.projectDirectory.dir('assets')) + from(layout.projectDirectory){ + include 'mod.json' + include 'icon.png' + } + + doFirst{ + def name = Pattern + .compile('"name": "(.*)"') + .matcher(layout.projectDirectory.file('mod.json').asFile.text) + + if(name.find() && name.group(1) != modName){ + logger.log(LogLevel.WARN, "Mod name mismatch: '${name.group(1)}' (mod.json) != '$modName' (gradle.properties)") + } + } + } + + tasks.register('dex', Jar){ + inputs.files tasks.jar + archiveFileName = "${modArtifact}.jar" + + final def desktopJar = tasks.jar.archiveFile + final def dexJar = file("$temporaryDir/Dexed.jar") + + from zipTree(desktopJar), zipTree(dexJar) + doFirst{ + // Find Android SDK root. + def sdkRoot = file( + System.getenv('ANDROID_SDK_ROOT') ?: System.getenv('ANDROID_HOME') ?: + { throw new GradleException('Neither `ANDROID_SDK_ROOT` nor `ANDROID_HOME` is set') } + ) + + // Find `d8`. + def d8 = file("$sdkRoot/build-tools/$androidBuildVersion/d8") + if(!d8.exists()){ + throw new GradleException("Android SDK `build-tools;$androidBuildVersion` isn't installed or is corrupted") + } + + // Initialize a release build. + def input = desktopJar.get().asFile + def command = "$d8 --release --min-api $androidMinVersion --output $dexJar $input" + + // Include all compile and runtime classpath. + (configurations.compileClasspath.asList() + configurations.runtimeClasspath.asList()).forEach{ + if(it.exists()) command = "$command --classpath $it" + } + + // Include Android platform as library. + def androidJar = file("$sdkRoot/platforms/android-$androidSdkVersion/android.jar") + if(!androidJar.exists()){ + throw new GradleException("Android SDK `platforms;android-$androidSdkVersion` isn't installed or is corrupted") + } + + command = "$command --lib $androidJar" + if(OS.isWindows) command = "cmd /c $command" + + // Run `d8`. + logger.log(LogLevel.LIFECYCLE, 'Running `d8`.') + command.execute(null, layout.projectDirectory.asFile).waitForProcessOutput(System.out, System.err) + } + } +} + +tasks.register('installJar'){ + dependsOn tasks.jar + doLast{ + def folder = Fi.get(OS.getAppDataDirectoryString('Mindustry')).child('mods') + folder.mkdirs() + + folder.child(tasks.jar.archiveFileName.get()).delete() + folder.child(tasks.dex.archiveFileName.get()).delete() + + def jarOutput = new Fi(tasks.jar.archiveFile.get().asFile) + def dexOutput = new Fi(tasks.dex.archiveFile.get().asFile) + + if(!jarOutput.exists() && !dexOutput.exists()){ + logger.log(LogLevel.ERROR, 'Neither :jar nor :dex artifacts are found; run one of these tasks first.') + }else if(dexOutput.exists()){ + dexOutput.copyTo(folder) + logger.log(LogLevel.LIFECYCLE, "Copied :dex output to $folder.") + }else{ + jarOutput.copyTo(folder) + logger.log(LogLevel.LIFECYCLE, "Copied :jar output to $folder.") + } + } +} + +tasks.register('run'){ + dependsOn installJar + doLast{ + def gamePath = "${temporaryDir.absolutePath}\\Mindustry${mindustryVersion}.jar" + def gameUrl = mindustryVersion.startsWith("v") ? + "https://github.com/Anuken/Mindustry/releases/download/${mindustryVersion}/Mindustry.jar" : + "https://github.com/Anuken/MindustryBuilds/releases/download/${mindustryVersion}/Mindustry-BE-Desktop-${mindustryVersion}.jar" + def gameFile = new File(gamePath) + if (!gameFile.exists()) { + println "Downloading Mindustry ${mindustryVersion} from ${gameUrl} to ${gamePath}" + new URL(gameUrl).withInputStream{ i -> gameFile.withOutputStream{ it << i } } + println "Done" + } + javaexec{ classpath = files(gamePath) } + } +} \ No newline at end of file diff --git a/build.gradle.kts b/build.gradle.kts deleted file mode 100644 index 5c7dc768..00000000 --- a/build.gradle.kts +++ /dev/null @@ -1,237 +0,0 @@ -import arc.util.* -import arc.util.serialization.* -import de.undercouch.gradle.tasks.download.Download -import ent.* -import java.io.* - -buildscript{ - val arcVersion: String by project - val useJitpack = property("mindustryBE").toString().toBooleanStrict() - - dependencies{ - classpath("com.github.Anuken.Arc:arc-core:$arcVersion") - } - - repositories{ - if(!useJitpack) maven("https://raw.githubusercontent.com/Zelaux/MindustryRepo/master/repository") - maven("https://jitpack.io") - } -} - -plugins{ - java - id("de.undercouch.download") version "5.4.0" - id("com.github.GlennFolker.EntityAnno") apply false -} - -val arcVersion: String by project -val arcLibraryVersion: String by project -val mindustryVersion: String by project -val mindustryBEVersion: String by project -val entVersion: String by project - -val modName: String by project -val modArtifact: String by project -val modFetch: String by project -val modGenSrc: String by project -val modGen: String by project - -val androidSdkVersion: String by project -val androidBuildVersion: String by project -val androidMinVersion: String by project - -val useJitpack = property("mindustryBE").toString().toBooleanStrict() - -fun arc(module: String): String{ - return "com.github.Anuken.Arc$module:$arcVersion" -} - -fun arcLibrary(module: String):String{ - return "com.github.Zelaux.ArcLibrary$module:$arcLibraryVersion" -} - -fun mindustry(module: String): String{ - return "com.github.Anuken.Mindustry$module:$mindustryVersion" -} - -fun entity(module: String): String{ - return "com.github.GlennFolker.EntityAnno$module:$entVersion" -} - -allprojects{ - apply(plugin = "java") - sourceSets["main"].java.setSrcDirs(listOf(layout.projectDirectory.dir("src"))) - - configurations.configureEach{ - // Resolve the correct Mindustry dependency, and force Arc version. - resolutionStrategy.eachDependency{ - if(useJitpack && requested.group == "com.github.Anuken.Mindustry"){ - useTarget("com.github.Anuken.MindustryJitpack:${requested.module.name}:$mindustryBEVersion") - }else if(requested.group == "com.github.Anuken.Arc"){ - useVersion(arcVersion) - } - } - } - - dependencies{ - // Downgrade Java 9+ syntax into being available in Java 8. - annotationProcessor(entity(":downgrader")) - } - - repositories{ - // Necessary Maven repositories to pull dependencies from. - mavenCentral() - maven("https://oss.sonatype.org/content/repositories/snapshots/") - maven("https://oss.sonatype.org/content/repositories/releases/") - maven("https://raw.githubusercontent.com/GlennFolker/EntityAnnoMaven/main") - - // Use Zelaux's non-buggy repository for release Mindustry and Arc builds. - if(!useJitpack) maven("https://raw.githubusercontent.com/Zelaux/MindustryRepo/master/repository") - maven("https://raw.githubusercontent.com/Zelaux/Repo/master/repository")//for ArcLibrary - maven("https://jitpack.io") - } - - tasks.withType().configureEach{ - // Use Java 17+ syntax, but target Java 8 bytecode version. - sourceCompatibility = "17" - options.apply{ - release = 8 - compilerArgs.add("-Xlint:-options") - - isIncremental = true - encoding = "UTF-8" - } - } -} - -project(":"){ - apply(plugin = "com.github.GlennFolker.EntityAnno") - configure{ - modName = project.properties["modName"].toString() - mindustryVersion = project.properties[if(useJitpack) "mindustryBEVersion" else "mindustryVersion"].toString() - isJitpack = useJitpack - revisionDir = layout.projectDirectory.dir("revisions").asFile - fetchPackage = modFetch - genSrcPackage = modGenSrc - genPackage = modGen - } - - dependencies{ - // Use the entity generation annotation processor. - compileOnly(entity(":entity")) - add("kapt", entity(":entity")) - - compileOnly("org.jetbrains:annotations:24.0.1") - - compileOnly(mindustry(":core")) - compileOnly(arc(":arc-core")) - implementation(arcLibrary(":graphics-draw3d")) - implementation(arcLibrary(":graphics-dashDraw")) - implementation(arcLibrary(":graphics-extendedDraw")) - } - - val jar = tasks.named("jar"){ - archiveFileName = "${modArtifact}Desktop.jar" - - val meta = layout.projectDirectory.file("$temporaryDir/mod.json") - from( - files(sourceSets["main"].output.classesDirs), - files(sourceSets["main"].output.resourcesDir), - configurations.runtimeClasspath.map{conf -> conf.map{if(it.isDirectory) it else zipTree(it)}}, - - files(layout.projectDirectory.dir("assets")), - layout.projectDirectory.file("icon.png"), - meta - ) - - metaInf.from(layout.projectDirectory.file("LICENSE")) - doFirst{ - // Deliberately check if the mod meta is actually written in HJSON, since, well, some people actually use - // it. But this is also not mentioned in the `README.md`, for the mischievous reason of driving beginners - // into using JSON instead. - val metaJson = layout.projectDirectory.file("mod.json") - val metaHjson = layout.projectDirectory.file("mod.hjson") - - if(metaJson.asFile.exists() && metaHjson.asFile.exists()){ - throw IllegalStateException("Ambiguous mod meta: both `mod.json` and `mod.hjson` exist.") - }else if(!metaJson.asFile.exists() && !metaHjson.asFile.exists()){ - throw IllegalStateException("Missing mod meta: neither `mod.json` nor `mod.hjson` exist.") - } - - val isJson = metaJson.asFile.exists() - val map = (if(isJson) metaJson else metaHjson).asFile - .reader(Charsets.UTF_8) - .use{Jval.read(it)} - - map.put("name", modName) - meta.asFile.writer(Charsets.UTF_8).use{file -> BufferedWriter(file).use{map.writeTo(it, Jval.Jformat.formatted)}} - } - } - - tasks.register("dex"){ - inputs.files(jar) - archiveFileName = "$modArtifact.jar" - - val desktopJar = jar.flatMap{it.archiveFile} - val dexJar = File(temporaryDir, "Dex.jar") - - from(zipTree(desktopJar), zipTree(dexJar)) - doFirst{ - logger.lifecycle("Running `d8`.") - providers.exec{ - // Find Android SDK root. - val sdkRoot = File( - OS.env("ANDROID_SDK_ROOT") ?: OS.env("ANDROID_HOME") ?: - throw IllegalStateException("Neither `ANDROID_SDK_ROOT` nor `ANDROID_HOME` is set.") - ) - - // Find `d8`. - val d8 = File(sdkRoot, "build-tools/$androidBuildVersion/${if(OS.isWindows) "d8.bat" else "d8"}") - if(!d8.exists()) throw IllegalStateException("Android SDK `build-tools;$androidBuildVersion` isn't installed or is corrupted") - - // Initialize a release build. - val input = desktopJar.get().asFile - val command = arrayListOf("$d8", "--release", "--min-api", androidMinVersion, "--output", "$dexJar", "$input") - - // Include all compile and runtime classpath. - (configurations.compileClasspath.get().toList() + configurations.runtimeClasspath.get().toList()).forEach{ - if(it.exists()) command.addAll(arrayOf("--classpath", it.path)) - } - - // Include Android platform as library. - val androidJar = File(sdkRoot, "platforms/android-$androidSdkVersion/android.jar") - if(!androidJar.exists()) throw IllegalStateException("Android SDK `platforms;android-$androidSdkVersion` isn't installed or is corrupted") - - command.addAll(arrayOf("--lib", "$androidJar")) - if(OS.isWindows) command.addAll(0, arrayOf("cmd", "/c").toList()) - - // Run `d8`. - commandLine(command) - }.result.get().rethrowFailure() - } - } - - tasks.register("fetchClient") { - src("https://github.com/Anuken/Mindustry/releases/download/$mindustryVersion/Mindustry.jar") - dest(file("$rootDir/run/Mindustry.jar")) - overwrite(false) - } - - tasks.register("runClient") { - dependsOn("fetchClient") - dependsOn("jar") - - val modFilename = "${project.name}Desktop.jar" - doFirst { - copy { - from("$rootDir/build/libs/$modFilename") - into("$rootDir/run/mods") - rename { modFilename } - } - } - - environment("MINDUSTRY_DATA_DIR", "$rootDir/run") - classpath(files("$rootDir/run/Mindustry.jar")) - mainClass.set("mindustry.desktop.DesktopLauncher") - } -} \ No newline at end of file diff --git a/gradle.properties b/gradle.properties index 8e93fe38..7c240f48 100644 --- a/gradle.properties +++ b/gradle.properties @@ -13,7 +13,7 @@ modArtifact = Omaloon # EntityAnno version, for integrating syntax-downgrader and entity annotation processor. # The exact version you need should be looked up on the project's `README.md` # (see https://github.com/GlennFolker/EntityAnno?tab=readme-ov-file#version-compatibility). -entVersion = v146.0.10 +entVersion = v146.0.8 # Set to `true` if the mod is compiled against Mindustry bleeding-edge build. # See documents on `mindustryVersion` and `mindustryBEVersion`. mindustryBE = false @@ -23,16 +23,16 @@ mindustryVersion = v146 # Mindustry *bleeding-edge* version, corresponds to commit hashes of Anuken/MindustryJitpack, e.g. `345ea0d54de0aee6953a664468556f4fea1a7c4f`. # Leave empty if `mindustryBE = false`. mindustryBEVersion = -# Arc version should either follow `mindustryVersion` for release or whatever hash bleeding-edge Mindustry uses. +# Arc version, should either follow `mindustryVersion` for release or whatever hash bleeding-edge Mindustry uses. arcVersion = v146 # Arc library version, has some things that omaloon needs -arcLibraryVersion = v1.0.7 +arcLibraryVersion = v1.0.5.1 ##### Android SDK configuration for building Android artifacts. # Android platform SDK version. -androidSdkVersion = 35 +androidSdkVersion = 34 # Android build-tools version. -androidBuildVersion = 35.0.0 +androidBuildVersion = 34.0.0 # Android platform minimum API version. Should be left as 14, as that's what Mindustry officially supports. androidMinVersion = 14 diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 00000000..d556a4a1 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,13 @@ +pluginManagement{ + repositories{ + gradlePluginPortal() + maven{url 'https://jitpack.io'} + } +} + +if(JavaVersion.current().ordinal() < JavaVersion.VERSION_17.ordinal()){ + throw new GradleException("JDK 17 is a required minimum version. Yours: ${System.getProperty('java.version')}") +} + +rootProject.name = 'Omaloon' + diff --git a/settings.gradle.kts b/settings.gradle.kts deleted file mode 100644 index b1b496b3..00000000 --- a/settings.gradle.kts +++ /dev/null @@ -1,18 +0,0 @@ -pluginManagement{ - repositories{ - gradlePluginPortal() - maven("https://raw.githubusercontent.com/GlennFolker/EntityAnnoMaven/main") - } - - plugins{ - val entVersion: String by settings - id("com.github.GlennFolker.EntityAnno") version(entVersion) - } -} - -if(JavaVersion.current().ordinal < JavaVersion.VERSION_17.ordinal){ - throw IllegalStateException("JDK 17 is a required minimum version. Yours: ${System.getProperty("java.version")}") -} - -val modName: String by settings -rootProject.name = modName \ No newline at end of file diff --git a/src/omaloon/utils/OlUtils.java b/src/omaloon/utils/OlUtils.java index bec2ea64..6d26bc9e 100644 --- a/src/omaloon/utils/OlUtils.java +++ b/src/omaloon/utils/OlUtils.java @@ -3,8 +3,8 @@ import arc.func.*; import arc.graphics.g2d.*; import arc.struct.*; -import mindustry.type.*; -import omaloon.ui.*; +import mindustry.type.Item; +import omaloon.ui.MultiItemData; import org.jetbrains.annotations.*; import static arc.Core.*; From 52ee995ed7103c0854973d046827566e08ae8a2b Mon Sep 17 00:00:00 2001 From: = Date: Tue, 7 Jan 2025 00:18:31 -0300 Subject: [PATCH 23/67] lemme just this real quick --- .../content/blocks/OlProductionBlocks.java | 19 +------------------ .../blocks/sandbox/PressureLiquidVoid.java | 3 --- 2 files changed, 1 insertion(+), 21 deletions(-) diff --git a/src/omaloon/content/blocks/OlProductionBlocks.java b/src/omaloon/content/blocks/OlProductionBlocks.java index 9a683828..9f4cd80b 100644 --- a/src/omaloon/content/blocks/OlProductionBlocks.java +++ b/src/omaloon/content/blocks/OlProductionBlocks.java @@ -1,10 +1,8 @@ package omaloon.content.blocks; -import arc.math.*; import mindustry.entities.effect.*; import mindustry.type.*; import mindustry.world.*; -import mindustry.world.draw.*; import omaloon.content.*; import omaloon.world.blocks.production.*; import omaloon.world.consumers.*; @@ -13,7 +11,7 @@ public class OlProductionBlocks { public static Block - hammerDrill, pressurizer, + hammerDrill, end; @@ -47,20 +45,5 @@ public static void load(){ ); }}); }}; - - pressurizer = new Pressurizer("air-well") {{ - requirements(Category.production, with( - OlItems.cobalt, 10 - )); - outputPressure = 5f; - - drawer = new DrawMulti( - new DrawDefault(), - new DrawTransition() {{ - suffix = "-cap"; - interp = a -> Interp.sine.apply(Interp.slope.apply(a)); - }} - ); - }}; } } diff --git a/src/omaloon/world/blocks/sandbox/PressureLiquidVoid.java b/src/omaloon/world/blocks/sandbox/PressureLiquidVoid.java index 344cfbc3..78448c39 100644 --- a/src/omaloon/world/blocks/sandbox/PressureLiquidVoid.java +++ b/src/omaloon/world/blocks/sandbox/PressureLiquidVoid.java @@ -20,9 +20,6 @@ public class PressureLiquidVoidBuild extends LiquidVoidBuild implements HasPress @Override public boolean acceptLiquid(Building source, Liquid liquid) { return enabled; } - @Override public boolean acceptsPressure(HasPressure from, float pressure) { - return enabled; - } @Override public PressureModule pressure() { return pressure; From 9916f17d8a5ed0d0ddc71d91515d66832f8b17f5 Mon Sep 17 00:00:00 2001 From: xstabux Date: Mon, 6 Jan 2025 17:47:57 +0200 Subject: [PATCH 24/67] Fix EntityAnno (cherry picked from commit 9e304d46cd4397e5e50596a388419477e662ed37) --- .github/workflows/ci.yml | 42 ++++++ .github/workflows/commit.yml | 24 ---- .github/workflows/pr.yml | 24 ---- .gitignore | 5 +- README.md | 22 +-- build.gradle | 223 ------------------------------- build.gradle.kts | 237 +++++++++++++++++++++++++++++++++ gradle.properties | 10 +- settings.gradle | 13 -- settings.gradle.kts | 18 +++ src/omaloon/utils/OlUtils.java | 4 +- 11 files changed, 321 insertions(+), 301 deletions(-) create mode 100644 .github/workflows/ci.yml delete mode 100644 .github/workflows/commit.yml delete mode 100644 .github/workflows/pr.yml delete mode 100644 build.gradle create mode 100644 build.gradle.kts delete mode 100644 settings.gradle create mode 100644 settings.gradle.kts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 00000000..9fecb912 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,42 @@ +name: Omaloon Build CI + +on: + push: + pull_request: + release: + types: + - created + +permissions: + contents: write + +jobs: + buildJar: + name: Build and Publish Jar + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Set up JDK 17 + uses: actions/setup-java@v4 + with: + java-version: 17 + distribution: temurin + - name: Setup Gradle + uses: gradle/actions/setup-gradle@v4 + - name: Build mod artifact + run: | + chmod +x gradlew + ./gradlew clean dex + - name: Upload built mod artifact as a GitHub Action artifact + uses: actions/upload-artifact@v4 + if: github.event_name == 'push' || github.event_name == 'pull_request' + with: + name: Omaloon (zipped) + path: build/libs/Omaloon.jar + if-no-files-found: error + compression-level: 0 + - name: Upload built mod artifact into release + uses: softprops/action-gh-release@v2 + if: github.event_name == 'release' && github.event.action == 'created' + with: + files: build/libs/Omaloon.jar \ No newline at end of file diff --git a/.github/workflows/commit.yml b/.github/workflows/commit.yml deleted file mode 100644 index ca713486..00000000 --- a/.github/workflows/commit.yml +++ /dev/null @@ -1,24 +0,0 @@ -name: Omaloon Commit - -on: [push] - -jobs: - buildJar: - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v4 - - name: Set up PATH - run: | - echo "${ANDROID_HOME}/build-tools/30.0.1" >> $GITHUB_PATH - - name: Set up JDK 17 - uses: actions/setup-java@v1 - with: - java-version: 17 - - name: Build mod jar - run: ./gradlew clean dex - - name: Upload built jar file - uses: actions/upload-artifact@v4 - with: - name: ${{ github.event.repository.name }} - path: build/libs/${{ github.event.repository.name }}.jar diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml deleted file mode 100644 index 1f190b22..00000000 --- a/.github/workflows/pr.yml +++ /dev/null @@ -1,24 +0,0 @@ -name: Omaloon Pull Request - -on: [pull_request] - -jobs: - buildJar: - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v4 - - name: Set up PATH - run: | - echo "${ANDROID_HOME}/build-tools/30.0.1" >> $GITHUB_PATH - - name: Set up JDK 17 - uses: actions/setup-java@v1 - with: - java-version: 17 - - name: Build mod jar - run: ./gradlew clean dex - - name: Upload built jar file - uses: actions/upload-artifact@v4 - with: - name: ${{ github.event.repository.name }} Pull Request - path: build/libs/${{ github.event.repository.name }}.jar diff --git a/.gitignore b/.gitignore index 0369c8d4..d3d0d568 100644 --- a/.gitignore +++ b/.gitignore @@ -148,4 +148,7 @@ gradle-app.setting Thumbs.db android/libs/ /.run/*.run.xml -modsDirectories.txt \ No newline at end of file +modsDirectories.txt + +# Mindustry Client +/run/ \ No newline at end of file diff --git a/README.md b/README.md index 19838e62..31f498e0 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,9 @@ [![Download](https://img.shields.io/github/v/release/xStaBUx/Omaloon-mod-public?color=6aa84f&include_prereleases&label=Latest%20version&logo=github&logoColor=white&style=for-the-badge)](https://github.com/xStaBUx/Omaloon-mod-public/releases) [![Total Downloads](https://img.shields.io/github/downloads/xStaBUx/Omaloon-mod-public/total?color=7289da&label&logo=docusign&logoColor=white&style=for-the-badge)](https://github.com/xStaBUx/Omaloon-mod-public/releases) -An ambitious [Mindustry](https://github.com/Anuken/Mindustry) modification developed by stabu and uujuju. This mod aims to expand the game's standard campaign by adding a new star system. +> An ambitious [Mindustry](https://github.com/Anuken/Mindustry) mod +developed by [stabu](https://github.com/stabu-dev) and [uujuju](https://github.com/uujuju1). +Mod aimed at expanding a campaign by adding a new star system. ## Building from Source @@ -45,13 +47,9 @@ The built mod will be in the `build/libs` directory. To test the mod directly: ```bash -gradlew run -``` - -To install the mod to your Mindustry mods folder: -```bash -gradlew installJar +gradlew runClient ``` +This Mindustry client uses the `run` directory to store its data. ## Contributing @@ -62,12 +60,18 @@ gradlew installJar ### Feature Suggestions - Join our [Discord server](https://discord.gg/bNMT82Hswb) to suggest new content +- Provide examples and specific arguments why your suggestion should be added to Omaloon - The Issues section is reserved for bug reports only -### Balance Feedback -- Share your thoughts on content balancing in our Discord +### Game-play Feedback +- Share your thoughts on game-play and balancing in our Discord - Provide specific examples and reasoning for balance changes +### Pull Requests +- Improve Omaloon's code/sprites/localization and propose these changes to us by creating a [Pull Request](https://github.com/stabu-dev/Omaloon/pulls). +- Make sure your code works properly and doesn't cause any issues. +- Provide specific reasoning why your Pull Request should be accepted. + ## Credits ### Developers diff --git a/build.gradle b/build.gradle deleted file mode 100644 index 98322657..00000000 --- a/build.gradle +++ /dev/null @@ -1,223 +0,0 @@ -import arc.files.* -import arc.util.* - -import java.util.regex.* - -buildscript{ - dependencies{ - classpath "com.github.Anuken.Arc:arc-core:$arcVersion" - } - - repositories{ - mavenCentral() - maven{url 'https://oss.sonatype.org/content/repositories/snapshots/'} - maven{url 'https://oss.sonatype.org/content/repositories/releases/'} - maven{url 'https://raw.githubusercontent.com/Zelaux/MindustryRepo/master/repository'} - maven{url 'https://jitpack.io'} - } -} - -plugins{ - // Register `EntityAnno` plugin, but only apply on `rootProject`. - id 'java' - id 'com.github.GlennFolker.EntityAnno' version "$entVersion" apply false -} - -configure(allprojects){ - sourceSets.main.java.srcDirs = [layout.projectDirectory.dir('src')] - - ext{ - compilerVersion = JavaVersion.current().ordinal() - JavaVersion.VERSION_17.ordinal() + 17 - useJitpack = Boolean.valueOf(mindustryBE) - - arc = {String module -> - return "com.github.Anuken.Arc$module:$arcVersion" - } - arcLibrary = {String module -> - return "com.github.Zelaux.ArcLibrary$module:$arcLibraryVersion" - } - mindustry = {String module -> - return "com.github.Anuken.Mindustry$module:$mindustryVersion" - } - } - - configurations.configureEach{ - // Resolve the correct Mindustry dependency, and force Arc version. - resolutionStrategy.eachDependency{ - if(useJitpack && requested.group == 'com.github.Anuken.Mindustry'){ - useTarget "com.github.Anuken.MindustryJitpack:$it.requested.name:$mindustryBEVersion" - } - - if(requested.group == 'com.github.Anuken.Arc'){ - useVersion arcVersion - } - } - } - - dependencies{ - // Downgrade Java 9+ syntax into being available in Java 8. - annotationProcessor "com.github.GlennFolker.EntityAnno:downgrader:$entVersion" - } - - repositories{ - // Necessary Maven repositories to pull dependencies from. - mavenCentral() - maven{url 'https://oss.sonatype.org/content/repositories/snapshots/'} - maven{url 'https://oss.sonatype.org/content/repositories/releases/'} - - // Use Zelaux's non-buggy repository for release Mindustry and Arc builds. - if(!useJitpack) maven{url 'https://raw.githubusercontent.com/Zelaux/MindustryRepo/master/repository'} - maven{url 'https://raw.githubusercontent.com/Zelaux/Repo/master/repository'}//for ArcLibrary - maven{url 'https://jitpack.io'} - } - - tasks.withType(JavaCompile).configureEach{ - // Use Java 17+ syntax, but target Java 8 bytecode version. - sourceCompatibility = compilerVersion - options.release.set 8 - options.compilerArgs << '-Xlint:-options' - - options.incremental = true - options.encoding = 'UTF-8' - } -} - -configure(rootProject){ - // Apply `EntityAnno` plugin to integrate the annotation processors. - apply plugin: 'com.github.GlennFolker.EntityAnno' - - entityAnno{ - modName = property('modName') - mindustryVersion = property(useJitpack ? 'mindustryBEVersion' : 'mindustryVersion') - isJitpack = useJitpack - revisionDir = layout.projectDirectory.dir('revisions').asFile - fetchPackage = modFetch - genSrcPackage = modGenSrc - genPackage = modGen - } - - dependencies{ - // Use the entity generation annotation processor. - compileOnly "com.github.GlennFolker.EntityAnno:entity:$entVersion" - kapt "com.github.GlennFolker.EntityAnno:entity:$entVersion" - - compileOnly "org.jetbrains:annotations:24.0.1" - - // Depend on Mindustry/Arc classpath. - compileOnly "${mindustry(':core')}" - compileOnly "${arc(':arc-core')}" - implementation "${arcLibrary(':graphics-draw3d')}" - implementation "${arcLibrary(':graphics-dashDraw')}" - implementation "${arcLibrary(':graphics-extendedDraw')}" - } - - jar{ - archiveFileName = "${modArtifact}Desktop.jar" - - from files(sourceSets.main.output.classesDirs) - from files(sourceSets.main.output.resourcesDir) - from configurations.runtimeClasspath.collect{it.isDirectory() ? it : zipTree(it)} - - from files(layout.projectDirectory.dir('assets')) - from(layout.projectDirectory){ - include 'mod.json' - include 'icon.png' - } - - doFirst{ - def name = Pattern - .compile('"name": "(.*)"') - .matcher(layout.projectDirectory.file('mod.json').asFile.text) - - if(name.find() && name.group(1) != modName){ - logger.log(LogLevel.WARN, "Mod name mismatch: '${name.group(1)}' (mod.json) != '$modName' (gradle.properties)") - } - } - } - - tasks.register('dex', Jar){ - inputs.files tasks.jar - archiveFileName = "${modArtifact}.jar" - - final def desktopJar = tasks.jar.archiveFile - final def dexJar = file("$temporaryDir/Dexed.jar") - - from zipTree(desktopJar), zipTree(dexJar) - doFirst{ - // Find Android SDK root. - def sdkRoot = file( - System.getenv('ANDROID_SDK_ROOT') ?: System.getenv('ANDROID_HOME') ?: - { throw new GradleException('Neither `ANDROID_SDK_ROOT` nor `ANDROID_HOME` is set') } - ) - - // Find `d8`. - def d8 = file("$sdkRoot/build-tools/$androidBuildVersion/d8") - if(!d8.exists()){ - throw new GradleException("Android SDK `build-tools;$androidBuildVersion` isn't installed or is corrupted") - } - - // Initialize a release build. - def input = desktopJar.get().asFile - def command = "$d8 --release --min-api $androidMinVersion --output $dexJar $input" - - // Include all compile and runtime classpath. - (configurations.compileClasspath.asList() + configurations.runtimeClasspath.asList()).forEach{ - if(it.exists()) command = "$command --classpath $it" - } - - // Include Android platform as library. - def androidJar = file("$sdkRoot/platforms/android-$androidSdkVersion/android.jar") - if(!androidJar.exists()){ - throw new GradleException("Android SDK `platforms;android-$androidSdkVersion` isn't installed or is corrupted") - } - - command = "$command --lib $androidJar" - if(OS.isWindows) command = "cmd /c $command" - - // Run `d8`. - logger.log(LogLevel.LIFECYCLE, 'Running `d8`.') - command.execute(null, layout.projectDirectory.asFile).waitForProcessOutput(System.out, System.err) - } - } -} - -tasks.register('installJar'){ - dependsOn tasks.jar - doLast{ - def folder = Fi.get(OS.getAppDataDirectoryString('Mindustry')).child('mods') - folder.mkdirs() - - folder.child(tasks.jar.archiveFileName.get()).delete() - folder.child(tasks.dex.archiveFileName.get()).delete() - - def jarOutput = new Fi(tasks.jar.archiveFile.get().asFile) - def dexOutput = new Fi(tasks.dex.archiveFile.get().asFile) - - if(!jarOutput.exists() && !dexOutput.exists()){ - logger.log(LogLevel.ERROR, 'Neither :jar nor :dex artifacts are found; run one of these tasks first.') - }else if(dexOutput.exists()){ - dexOutput.copyTo(folder) - logger.log(LogLevel.LIFECYCLE, "Copied :dex output to $folder.") - }else{ - jarOutput.copyTo(folder) - logger.log(LogLevel.LIFECYCLE, "Copied :jar output to $folder.") - } - } -} - -tasks.register('run'){ - dependsOn installJar - doLast{ - def gamePath = "${temporaryDir.absolutePath}\\Mindustry${mindustryVersion}.jar" - def gameUrl = mindustryVersion.startsWith("v") ? - "https://github.com/Anuken/Mindustry/releases/download/${mindustryVersion}/Mindustry.jar" : - "https://github.com/Anuken/MindustryBuilds/releases/download/${mindustryVersion}/Mindustry-BE-Desktop-${mindustryVersion}.jar" - def gameFile = new File(gamePath) - if (!gameFile.exists()) { - println "Downloading Mindustry ${mindustryVersion} from ${gameUrl} to ${gamePath}" - new URL(gameUrl).withInputStream{ i -> gameFile.withOutputStream{ it << i } } - println "Done" - } - javaexec{ classpath = files(gamePath) } - } -} \ No newline at end of file diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 00000000..5c7dc768 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,237 @@ +import arc.util.* +import arc.util.serialization.* +import de.undercouch.gradle.tasks.download.Download +import ent.* +import java.io.* + +buildscript{ + val arcVersion: String by project + val useJitpack = property("mindustryBE").toString().toBooleanStrict() + + dependencies{ + classpath("com.github.Anuken.Arc:arc-core:$arcVersion") + } + + repositories{ + if(!useJitpack) maven("https://raw.githubusercontent.com/Zelaux/MindustryRepo/master/repository") + maven("https://jitpack.io") + } +} + +plugins{ + java + id("de.undercouch.download") version "5.4.0" + id("com.github.GlennFolker.EntityAnno") apply false +} + +val arcVersion: String by project +val arcLibraryVersion: String by project +val mindustryVersion: String by project +val mindustryBEVersion: String by project +val entVersion: String by project + +val modName: String by project +val modArtifact: String by project +val modFetch: String by project +val modGenSrc: String by project +val modGen: String by project + +val androidSdkVersion: String by project +val androidBuildVersion: String by project +val androidMinVersion: String by project + +val useJitpack = property("mindustryBE").toString().toBooleanStrict() + +fun arc(module: String): String{ + return "com.github.Anuken.Arc$module:$arcVersion" +} + +fun arcLibrary(module: String):String{ + return "com.github.Zelaux.ArcLibrary$module:$arcLibraryVersion" +} + +fun mindustry(module: String): String{ + return "com.github.Anuken.Mindustry$module:$mindustryVersion" +} + +fun entity(module: String): String{ + return "com.github.GlennFolker.EntityAnno$module:$entVersion" +} + +allprojects{ + apply(plugin = "java") + sourceSets["main"].java.setSrcDirs(listOf(layout.projectDirectory.dir("src"))) + + configurations.configureEach{ + // Resolve the correct Mindustry dependency, and force Arc version. + resolutionStrategy.eachDependency{ + if(useJitpack && requested.group == "com.github.Anuken.Mindustry"){ + useTarget("com.github.Anuken.MindustryJitpack:${requested.module.name}:$mindustryBEVersion") + }else if(requested.group == "com.github.Anuken.Arc"){ + useVersion(arcVersion) + } + } + } + + dependencies{ + // Downgrade Java 9+ syntax into being available in Java 8. + annotationProcessor(entity(":downgrader")) + } + + repositories{ + // Necessary Maven repositories to pull dependencies from. + mavenCentral() + maven("https://oss.sonatype.org/content/repositories/snapshots/") + maven("https://oss.sonatype.org/content/repositories/releases/") + maven("https://raw.githubusercontent.com/GlennFolker/EntityAnnoMaven/main") + + // Use Zelaux's non-buggy repository for release Mindustry and Arc builds. + if(!useJitpack) maven("https://raw.githubusercontent.com/Zelaux/MindustryRepo/master/repository") + maven("https://raw.githubusercontent.com/Zelaux/Repo/master/repository")//for ArcLibrary + maven("https://jitpack.io") + } + + tasks.withType().configureEach{ + // Use Java 17+ syntax, but target Java 8 bytecode version. + sourceCompatibility = "17" + options.apply{ + release = 8 + compilerArgs.add("-Xlint:-options") + + isIncremental = true + encoding = "UTF-8" + } + } +} + +project(":"){ + apply(plugin = "com.github.GlennFolker.EntityAnno") + configure{ + modName = project.properties["modName"].toString() + mindustryVersion = project.properties[if(useJitpack) "mindustryBEVersion" else "mindustryVersion"].toString() + isJitpack = useJitpack + revisionDir = layout.projectDirectory.dir("revisions").asFile + fetchPackage = modFetch + genSrcPackage = modGenSrc + genPackage = modGen + } + + dependencies{ + // Use the entity generation annotation processor. + compileOnly(entity(":entity")) + add("kapt", entity(":entity")) + + compileOnly("org.jetbrains:annotations:24.0.1") + + compileOnly(mindustry(":core")) + compileOnly(arc(":arc-core")) + implementation(arcLibrary(":graphics-draw3d")) + implementation(arcLibrary(":graphics-dashDraw")) + implementation(arcLibrary(":graphics-extendedDraw")) + } + + val jar = tasks.named("jar"){ + archiveFileName = "${modArtifact}Desktop.jar" + + val meta = layout.projectDirectory.file("$temporaryDir/mod.json") + from( + files(sourceSets["main"].output.classesDirs), + files(sourceSets["main"].output.resourcesDir), + configurations.runtimeClasspath.map{conf -> conf.map{if(it.isDirectory) it else zipTree(it)}}, + + files(layout.projectDirectory.dir("assets")), + layout.projectDirectory.file("icon.png"), + meta + ) + + metaInf.from(layout.projectDirectory.file("LICENSE")) + doFirst{ + // Deliberately check if the mod meta is actually written in HJSON, since, well, some people actually use + // it. But this is also not mentioned in the `README.md`, for the mischievous reason of driving beginners + // into using JSON instead. + val metaJson = layout.projectDirectory.file("mod.json") + val metaHjson = layout.projectDirectory.file("mod.hjson") + + if(metaJson.asFile.exists() && metaHjson.asFile.exists()){ + throw IllegalStateException("Ambiguous mod meta: both `mod.json` and `mod.hjson` exist.") + }else if(!metaJson.asFile.exists() && !metaHjson.asFile.exists()){ + throw IllegalStateException("Missing mod meta: neither `mod.json` nor `mod.hjson` exist.") + } + + val isJson = metaJson.asFile.exists() + val map = (if(isJson) metaJson else metaHjson).asFile + .reader(Charsets.UTF_8) + .use{Jval.read(it)} + + map.put("name", modName) + meta.asFile.writer(Charsets.UTF_8).use{file -> BufferedWriter(file).use{map.writeTo(it, Jval.Jformat.formatted)}} + } + } + + tasks.register("dex"){ + inputs.files(jar) + archiveFileName = "$modArtifact.jar" + + val desktopJar = jar.flatMap{it.archiveFile} + val dexJar = File(temporaryDir, "Dex.jar") + + from(zipTree(desktopJar), zipTree(dexJar)) + doFirst{ + logger.lifecycle("Running `d8`.") + providers.exec{ + // Find Android SDK root. + val sdkRoot = File( + OS.env("ANDROID_SDK_ROOT") ?: OS.env("ANDROID_HOME") ?: + throw IllegalStateException("Neither `ANDROID_SDK_ROOT` nor `ANDROID_HOME` is set.") + ) + + // Find `d8`. + val d8 = File(sdkRoot, "build-tools/$androidBuildVersion/${if(OS.isWindows) "d8.bat" else "d8"}") + if(!d8.exists()) throw IllegalStateException("Android SDK `build-tools;$androidBuildVersion` isn't installed or is corrupted") + + // Initialize a release build. + val input = desktopJar.get().asFile + val command = arrayListOf("$d8", "--release", "--min-api", androidMinVersion, "--output", "$dexJar", "$input") + + // Include all compile and runtime classpath. + (configurations.compileClasspath.get().toList() + configurations.runtimeClasspath.get().toList()).forEach{ + if(it.exists()) command.addAll(arrayOf("--classpath", it.path)) + } + + // Include Android platform as library. + val androidJar = File(sdkRoot, "platforms/android-$androidSdkVersion/android.jar") + if(!androidJar.exists()) throw IllegalStateException("Android SDK `platforms;android-$androidSdkVersion` isn't installed or is corrupted") + + command.addAll(arrayOf("--lib", "$androidJar")) + if(OS.isWindows) command.addAll(0, arrayOf("cmd", "/c").toList()) + + // Run `d8`. + commandLine(command) + }.result.get().rethrowFailure() + } + } + + tasks.register("fetchClient") { + src("https://github.com/Anuken/Mindustry/releases/download/$mindustryVersion/Mindustry.jar") + dest(file("$rootDir/run/Mindustry.jar")) + overwrite(false) + } + + tasks.register("runClient") { + dependsOn("fetchClient") + dependsOn("jar") + + val modFilename = "${project.name}Desktop.jar" + doFirst { + copy { + from("$rootDir/build/libs/$modFilename") + into("$rootDir/run/mods") + rename { modFilename } + } + } + + environment("MINDUSTRY_DATA_DIR", "$rootDir/run") + classpath(files("$rootDir/run/Mindustry.jar")) + mainClass.set("mindustry.desktop.DesktopLauncher") + } +} \ No newline at end of file diff --git a/gradle.properties b/gradle.properties index 7c240f48..8e93fe38 100644 --- a/gradle.properties +++ b/gradle.properties @@ -13,7 +13,7 @@ modArtifact = Omaloon # EntityAnno version, for integrating syntax-downgrader and entity annotation processor. # The exact version you need should be looked up on the project's `README.md` # (see https://github.com/GlennFolker/EntityAnno?tab=readme-ov-file#version-compatibility). -entVersion = v146.0.8 +entVersion = v146.0.10 # Set to `true` if the mod is compiled against Mindustry bleeding-edge build. # See documents on `mindustryVersion` and `mindustryBEVersion`. mindustryBE = false @@ -23,16 +23,16 @@ mindustryVersion = v146 # Mindustry *bleeding-edge* version, corresponds to commit hashes of Anuken/MindustryJitpack, e.g. `345ea0d54de0aee6953a664468556f4fea1a7c4f`. # Leave empty if `mindustryBE = false`. mindustryBEVersion = -# Arc version, should either follow `mindustryVersion` for release or whatever hash bleeding-edge Mindustry uses. +# Arc version should either follow `mindustryVersion` for release or whatever hash bleeding-edge Mindustry uses. arcVersion = v146 # Arc library version, has some things that omaloon needs -arcLibraryVersion = v1.0.5.1 +arcLibraryVersion = v1.0.7 ##### Android SDK configuration for building Android artifacts. # Android platform SDK version. -androidSdkVersion = 34 +androidSdkVersion = 35 # Android build-tools version. -androidBuildVersion = 34.0.0 +androidBuildVersion = 35.0.0 # Android platform minimum API version. Should be left as 14, as that's what Mindustry officially supports. androidMinVersion = 14 diff --git a/settings.gradle b/settings.gradle deleted file mode 100644 index d556a4a1..00000000 --- a/settings.gradle +++ /dev/null @@ -1,13 +0,0 @@ -pluginManagement{ - repositories{ - gradlePluginPortal() - maven{url 'https://jitpack.io'} - } -} - -if(JavaVersion.current().ordinal() < JavaVersion.VERSION_17.ordinal()){ - throw new GradleException("JDK 17 is a required minimum version. Yours: ${System.getProperty('java.version')}") -} - -rootProject.name = 'Omaloon' - diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 00000000..b1b496b3 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,18 @@ +pluginManagement{ + repositories{ + gradlePluginPortal() + maven("https://raw.githubusercontent.com/GlennFolker/EntityAnnoMaven/main") + } + + plugins{ + val entVersion: String by settings + id("com.github.GlennFolker.EntityAnno") version(entVersion) + } +} + +if(JavaVersion.current().ordinal < JavaVersion.VERSION_17.ordinal){ + throw IllegalStateException("JDK 17 is a required minimum version. Yours: ${System.getProperty("java.version")}") +} + +val modName: String by settings +rootProject.name = modName \ No newline at end of file diff --git a/src/omaloon/utils/OlUtils.java b/src/omaloon/utils/OlUtils.java index 6d26bc9e..bec2ea64 100644 --- a/src/omaloon/utils/OlUtils.java +++ b/src/omaloon/utils/OlUtils.java @@ -3,8 +3,8 @@ import arc.func.*; import arc.graphics.g2d.*; import arc.struct.*; -import mindustry.type.Item; -import omaloon.ui.MultiItemData; +import mindustry.type.*; +import omaloon.ui.*; import org.jetbrains.annotations.*; import static arc.Core.*; From 923b0071281944e1420f2bb4d784e1f7dca36d60 Mon Sep 17 00:00:00 2001 From: = Date: Tue, 7 Jan 2025 20:24:09 -0300 Subject: [PATCH 25/67] include an install task in the gradle --- build.gradle.kts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/build.gradle.kts b/build.gradle.kts index 5c7dc768..82e9ec2b 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,3 +1,4 @@ +import arc.files.Fi import arc.util.* import arc.util.serialization.* import de.undercouch.gradle.tasks.download.Download @@ -234,4 +235,17 @@ project(":"){ classpath(files("$rootDir/run/Mindustry.jar")) mainClass.set("mindustry.desktop.DesktopLauncher") } + + tasks.register("install"){ + dependsOn("jar") + doLast{ + val folder = Fi.get(OS.getAppDataDirectoryString("Mindustry")).child("mods") + folder.mkdirs() + + val input = Fi.get("$rootDir/build/libs/${project.name}Desktop.jar") + folder.child(input.name()).delete() + input.copyTo(folder) + logger.lifecycle("Copied :jar output to $folder.") + } + } } \ No newline at end of file From 26629b9817e04c9781c3d86ae63e3294f6834ade Mon Sep 17 00:00:00 2001 From: = Date: Tue, 7 Jan 2025 20:59:06 -0300 Subject: [PATCH 26/67] set up density --- assets/bundles/bundle.properties | 7 ++++--- src/omaloon/content/OlLiquids.java | 19 +++++++++++++++++++ src/omaloon/world/meta/OlStats.java | 4 ++++ 3 files changed, 27 insertions(+), 3 deletions(-) diff --git a/assets/bundles/bundle.properties b/assets/bundles/bundle.properties index ce4c5779..0e1c0b82 100644 --- a/assets/bundles/bundle.properties +++ b/assets/bundles/bundle.properties @@ -327,11 +327,11 @@ block.omaloon-impulse-node.description = Transmits power to connected buildings. block.omaloon-hammer-drill.name = Hammer drill block.omaloon-hammer-drill.description = When placed on ore, outputs items. Efficiency increases with decreasing pressure inside, reaching peak performance in near vacuum conditions. -block.omaloon-air-well.name = Air Well -block.omaloon-air-well.description = Constantly pulls air in or out. - ## stats category.omaloon-pressure = Pressure + +stat.omaloon-density = Density + stat.omaloon-consumepressure = Consume Pressure stat.omaloon-minpressure = Min Pressure stat.omaloon-maxpressure = Max Pressure @@ -345,6 +345,7 @@ stat.omaloon-optimal-pressure = Optimal Pressure stat.omaloon-optimal-pressure.format = \uC357 @ pressure units (@%) ## ui units +unit.omaloon-liquidPerWorldUnit = Liquid per World cube unit.omaloon-pressuresecond = pressure units / second unit.omaloon-pressureunits = pressure units bar.air = Air: diff --git a/src/omaloon/content/OlLiquids.java b/src/omaloon/content/OlLiquids.java index a11b84ae..e8249f54 100644 --- a/src/omaloon/content/OlLiquids.java +++ b/src/omaloon/content/OlLiquids.java @@ -1,8 +1,11 @@ package omaloon.content; +import arc.struct.*; +import arc.util.*; import mindustry.content.*; import mindustry.type.*; import omaloon.type.liquid.*; +import omaloon.world.meta.*; import static arc.graphics.Color.*; @@ -12,6 +15,8 @@ public class OlLiquids { end; + public static ObjectFloatMap densities = new ObjectFloatMap<>(); + public static void load(){ glacium = new CrystalLiquid("glacium", valueOf("5e929d")){{ effect = OlStatusEffects.glacied; @@ -36,6 +41,20 @@ public static void load(){ canStayOn.add(Liquids.water); }}; + addDensity(Liquids.water, 1000); + addDensity(Liquids.slag, 1600); + addDensity(Liquids.oil, 700); + addDensity(Liquids.cryofluid, 200); + addDensity(glacium, 1300); + addDensity(tiredGlacium, 1300); } + public static void addDensity(Liquid liquid, float density) { + densities.put(liquid, density); + liquid.stats.add(OlStats.density, density, OlStats.liquidPerWorldUnit); + } + + public static float getDensity(@Nullable Liquid liquid) { + return densities.get(liquid, 1.2f); + } } diff --git a/src/omaloon/world/meta/OlStats.java b/src/omaloon/world/meta/OlStats.java index e98a6c50..4202ff3a 100644 --- a/src/omaloon/world/meta/OlStats.java +++ b/src/omaloon/world/meta/OlStats.java @@ -21,6 +21,8 @@ public class OlStats { addFluid = new Stat("omaloon-add-fluid", StatCat.crafting), removeFluid = new Stat("omaloon-remove-fluid", StatCat.crafting), + density = new Stat("omaloon-density"), + pressureFlow = new Stat("omaloon-pressureflow", pressure), maxPressure = new Stat("omaloon-maxPressure", pressure), @@ -31,6 +33,8 @@ public class OlStats { outputPressure = new Stat("omaloon-outputPressure", pressure); public static final StatUnit + liquidPerWorldUnit = new StatUnit("omaloon-liquidPerWorldUnit"), + pressureUnits = new StatUnit("omaloon-pressureUnits", "\uC357"), pressureSecond = new StatUnit("omaloon-pressureSecond", "\uC357"); From 3dfa9181e50f0afe3cfeb35e207bd6d0f98c2843 Mon Sep 17 00:00:00 2001 From: = Date: Tue, 7 Jan 2025 21:09:15 -0300 Subject: [PATCH 27/67] uncomplicate --- src/omaloon/math/OlMath.java | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/omaloon/math/OlMath.java b/src/omaloon/math/OlMath.java index ae7b5076..ddf71d67 100644 --- a/src/omaloon/math/OlMath.java +++ b/src/omaloon/math/OlMath.java @@ -13,9 +13,8 @@ public class OlMath { * * returns the amount of fluid in liquid units that passes through the area over a certain time. */ - public static float bernoulliFlowRate(float area, float pressureStart, float pressureEnd, float density, float time) { - float diff = -2f * (pressureEnd - pressureStart); - if (diff == 0) return 0f; - return (area * (diff/Math.abs(diff)) * Mathf.sqrt(Math.abs(diff) / density) * time * density)/(60f); + public static float bernoulliFlowRate(float opening, float pressureStart, float pressureEnd, float density) { + return opening * (pressureEnd - pressureStart) / density; } + // TODO rename } From 5e7cf717ab4f2ccaca6d50ae505e11abb83c45ca Mon Sep 17 00:00:00 2001 From: = Date: Tue, 7 Jan 2025 21:30:29 -0300 Subject: [PATCH 28/67] a --- src/omaloon/math/OlMath.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/omaloon/math/OlMath.java b/src/omaloon/math/OlMath.java index ddf71d67..80d8c614 100644 --- a/src/omaloon/math/OlMath.java +++ b/src/omaloon/math/OlMath.java @@ -13,7 +13,7 @@ public class OlMath { * * returns the amount of fluid in liquid units that passes through the area over a certain time. */ - public static float bernoulliFlowRate(float opening, float pressureStart, float pressureEnd, float density) { + public static float bernoulliFlowRate(float opening, float pressureStart, float pressureEnd, float density, float time) { return opening * (pressureEnd - pressureStart) / density; } // TODO rename From e8ee6cc78e4b3adcfa38bb2beb2a4ea4e6ed3a54 Mon Sep 17 00:00:00 2001 From: = Date: Fri, 10 Jan 2025 22:53:51 -0300 Subject: [PATCH 29/67] flow change --- assets/bundles/bundle.properties | 3 +- src/omaloon/content/OlLiquids.java | 19 ++++++++ src/omaloon/math/OlMath.java | 6 +-- .../blocks/liquid/PressureLiquidValve.java | 5 +- src/omaloon/world/interfaces/HasPressure.java | 2 + src/omaloon/world/meta/PressureSection.java | 46 +++++++++++++++++++ src/omaloon/world/modules/PressureModule.java | 9 ++-- 7 files changed, 78 insertions(+), 12 deletions(-) diff --git a/assets/bundles/bundle.properties b/assets/bundles/bundle.properties index 0e1c0b82..f5a91bdd 100644 --- a/assets/bundles/bundle.properties +++ b/assets/bundles/bundle.properties @@ -331,6 +331,7 @@ block.omaloon-hammer-drill.description = When placed on ore, outputs items. Effi category.omaloon-pressure = Pressure stat.omaloon-density = Density +stat.omaloon-viscosity.format = @%, @ Todo stat.omaloon-consumepressure = Consume Pressure stat.omaloon-minpressure = Min Pressure @@ -345,7 +346,7 @@ stat.omaloon-optimal-pressure = Optimal Pressure stat.omaloon-optimal-pressure.format = \uC357 @ pressure units (@%) ## ui units -unit.omaloon-liquidPerWorldUnit = Liquid per World cube +unit.omaloon-liquidperworldunit = Liquid per World cube unit.omaloon-pressuresecond = pressure units / second unit.omaloon-pressureunits = pressure units bar.air = Air: diff --git a/src/omaloon/content/OlLiquids.java b/src/omaloon/content/OlLiquids.java index e8249f54..b55b9a13 100644 --- a/src/omaloon/content/OlLiquids.java +++ b/src/omaloon/content/OlLiquids.java @@ -1,9 +1,11 @@ package omaloon.content; +import arc.*; import arc.struct.*; import arc.util.*; import mindustry.content.*; import mindustry.type.*; +import mindustry.world.meta.*; import omaloon.type.liquid.*; import omaloon.world.meta.*; @@ -16,6 +18,7 @@ public class OlLiquids { end; public static ObjectFloatMap densities = new ObjectFloatMap<>(); + public static ObjectFloatMap viscosities = new ObjectFloatMap<>(); public static void load(){ glacium = new CrystalLiquid("glacium", valueOf("5e929d")){{ @@ -42,11 +45,17 @@ public static void load(){ }}; addDensity(Liquids.water, 1000); + addViscosity(Liquids.water, 10); addDensity(Liquids.slag, 1600); + addViscosity(Liquids.slag, 250); addDensity(Liquids.oil, 700); + addViscosity(Liquids.oil, 50); addDensity(Liquids.cryofluid, 200); + addViscosity(Liquids.cryofluid, 1); addDensity(glacium, 1300); + addViscosity(glacium, 13); addDensity(tiredGlacium, 1300); + addViscosity(tiredGlacium, 13); } public static void addDensity(Liquid liquid, float density) { @@ -54,7 +63,17 @@ public static void addDensity(Liquid liquid, float density) { liquid.stats.add(OlStats.density, density, OlStats.liquidPerWorldUnit); } + public static void addViscosity(Liquid liquid, float viscosity) { + viscosities.put(liquid, viscosity); + liquid.stats.remove(Stat.viscosity); + liquid.stats.add(Stat.viscosity, Core.bundle.get("stat.omaloon-viscosity.format"), liquid.viscosity * 100f, viscosity); + } + public static float getDensity(@Nullable Liquid liquid) { return densities.get(liquid, 1.2f); } + + public static float getViscosity(@Nullable Liquid liquid) { + return viscosities.get(liquid, 1f); + } } diff --git a/src/omaloon/math/OlMath.java b/src/omaloon/math/OlMath.java index 80d8c614..325467b2 100644 --- a/src/omaloon/math/OlMath.java +++ b/src/omaloon/math/OlMath.java @@ -1,7 +1,5 @@ package omaloon.math; -import arc.math.*; - public class OlMath { /** * Solves for the flow of a fluid through an area based on a difference of pressure. @@ -13,8 +11,8 @@ public class OlMath { * * returns the amount of fluid in liquid units that passes through the area over a certain time. */ - public static float bernoulliFlowRate(float opening, float pressureStart, float pressureEnd, float density, float time) { - return opening * (pressureEnd - pressureStart) / density; + public static float flowRate(float opening, float pressureStart, float pressureEnd, float viscosity) { + return opening * (pressureEnd - pressureStart) / (viscosity * 60f); } // TODO rename } diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidValve.java b/src/omaloon/world/blocks/liquid/PressureLiquidValve.java index 473903bd..4d7eef33 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidValve.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidValve.java @@ -217,13 +217,12 @@ public void updatePressure() { if (jammed) return; if (pressureAmount < openMin) { effectInterval += delta(); - addFluid(null, Math.min(openMin - pressureAmount, OlMath.bernoulliFlowRate(pressureLoss, 0, pressureAmount, 1f, 1f))); + addFluid(null, Math.min(openMin - pressureAmount, OlMath.flowRate(pressureLoss, 0, pressureAmount, OlLiquids.getViscosity(pressure.getMain())))); draining = Mathf.approachDelta(draining, 1, 0.014f); - } if (pressureAmount > openMax) { effectInterval += delta(); - removeFluid(pressure.getMain(), Math.min(pressureAmount - openMax, OlMath.bernoulliFlowRate(pressureLoss, pressureAmount, 0, 1f, 1f))); + removeFluid(pressure.getMain(), Math.min(pressureAmount - openMax, OlMath.flowRate(pressureLoss, pressureAmount, 0, OlLiquids.getViscosity(pressure.getMain())))); draining = Mathf.approachDelta(draining, 1, 0.014f); } if (effectInterval > pumpingEffectInterval) { diff --git a/src/omaloon/world/interfaces/HasPressure.java b/src/omaloon/world/interfaces/HasPressure.java index 88ffb70e..7538c734 100644 --- a/src/omaloon/world/interfaces/HasPressure.java +++ b/src/omaloon/world/interfaces/HasPressure.java @@ -88,6 +88,8 @@ default void removeFluid(@Nullable Liquid liquid, float amount) { * method to update pressure related things */ default void updatePressure() { + if (nextBuilds().contains(other -> other.pressure().section != this)) pressure().section.updateTransfer(); + Vars.content.liquids().each(liquid -> { if (Mathf.round(pressure().getPressure(liquid)) < pressureConfig().minPressure - 1) damage(pressureConfig().underPressureDamage); if (Mathf.round(pressure().getPressure(liquid)) > pressureConfig().maxPressure + 1) damage(pressureConfig().overPressureDamage); diff --git a/src/omaloon/world/meta/PressureSection.java b/src/omaloon/world/meta/PressureSection.java index 6fc1fe2b..4364a545 100644 --- a/src/omaloon/world/meta/PressureSection.java +++ b/src/omaloon/world/meta/PressureSection.java @@ -1,9 +1,13 @@ package omaloon.world.meta; +import arc.math.*; import arc.struct.*; +import arc.struct.ObjectMap.*; import arc.util.*; import mindustry.*; import mindustry.type.*; +import omaloon.content.*; +import omaloon.math.*; import omaloon.world.interfaces.*; public class PressureSection { @@ -80,4 +84,46 @@ public void updateLiquids() { for(Liquid liquid : Vars.content.liquids()) addFluid(liquid, liquids[liquid.id]); addFluid(null, air); } + + public void updateTransfer() { + Seq> links = new Seq<>(); + + builds.each(b -> { + b.nextBuilds().retainAll(other -> other.pressure().section != this).each(other -> { + links.add(new Entry<>(){{ + key = other; + value = b; + }}); + }); + }); + + FloatSeq amounts = new FloatSeq(); + + for(Entry entry : links) { + @Nullable Liquid main = entry.value.pressure().getMain(); + float flow = OlMath.flowRate(entry.value.pressureConfig().fluidCapacity, + entry.key.pressure().getPressure(main), + entry.value.pressure().getPressure(main), + OlLiquids.getViscosity(main) + )/(2f * links.size); + + if ( + entry.key.acceptsPressurizedFluid(entry.value, main, flow) && + entry.value.outputsPressurizedFluid(entry.key, main, flow) + ) { + amounts.add(flow); + } else { + amounts.add(0); + } + } + + + for(Entry entry : links) { + @Nullable Liquid main = entry.value.pressure().getMain(); + if (amounts.get(links.indexOf(entry)) != 0) { + entry.key.addFluid(main, amounts.get(links.indexOf(entry))); + entry.value.removeFluid(main, amounts.get(links.indexOf(entry))); + } + } + } } diff --git a/src/omaloon/world/modules/PressureModule.java b/src/omaloon/world/modules/PressureModule.java index bc4cb48e..2c6e0e76 100644 --- a/src/omaloon/world/modules/PressureModule.java +++ b/src/omaloon/world/modules/PressureModule.java @@ -7,6 +7,7 @@ import mindustry.content.*; import mindustry.type.*; import mindustry.world.modules.*; +import omaloon.content.*; import omaloon.world.meta.*; public class PressureModule extends BlockModule { @@ -27,14 +28,14 @@ public class PressureModule extends BlockModule { public void addFluid(@Nullable Liquid liquid, float amount, PressureConfig reference) { if (liquid == null) { air += amount; - pressure = air / reference.fluidCapacity * arbitraryPressureScalar; + pressure = air / reference.fluidCapacity * OlLiquids.getDensity(liquid); } else { if (air < 0) { air = 0; pressure = 0; } liquids[liquid.id] += amount; - pressures[liquid.id] = liquids[liquid.id] / reference.fluidCapacity * arbitraryPressureScalar; + pressures[liquid.id] = liquids[liquid.id] / reference.fluidCapacity * OlLiquids.getDensity(liquid); } if (liquid != null) current = liquid; } @@ -91,10 +92,10 @@ public void read(Reads read) { public void removeFluid(@Nullable Liquid liquid, float amount, PressureConfig reference) { if (liquid == null) { air -= (getMain() != null ? Math.min(air, amount) : amount); - pressure = air / reference.fluidCapacity * arbitraryPressureScalar; + pressure = air / reference.fluidCapacity * OlLiquids.getDensity(liquid); } else { liquids[liquid.id] = Mathf.maxZero(liquids[liquid.id] - amount); - pressures[liquid.id] = liquids[liquid.id] / reference.fluidCapacity * arbitraryPressureScalar; + pressures[liquid.id] = liquids[liquid.id] / reference.fluidCapacity * OlLiquids.getDensity(liquid); } if (liquid != null) current = liquid; } From 4a8e7b64213116e47113514d0270e37a591248dd Mon Sep 17 00:00:00 2001 From: = Date: Sun, 12 Jan 2025 01:10:07 -0300 Subject: [PATCH 30/67] flow change part 2 (havent done it dlc) --- src/omaloon/content/OlLiquids.java | 4 +- .../content/blocks/OlDistributionBlocks.java | 2 +- .../blocks/liquid/PressureLiquidPump.java | 35 ++-- .../world/blocks/production/Pressurizer.java | 181 ------------------ src/omaloon/world/interfaces/HasPressure.java | 2 +- src/omaloon/world/meta/PressureSection.java | 83 ++++++-- 6 files changed, 92 insertions(+), 215 deletions(-) delete mode 100644 src/omaloon/world/blocks/production/Pressurizer.java diff --git a/src/omaloon/content/OlLiquids.java b/src/omaloon/content/OlLiquids.java index b55b9a13..1302b1e4 100644 --- a/src/omaloon/content/OlLiquids.java +++ b/src/omaloon/content/OlLiquids.java @@ -51,7 +51,7 @@ public static void load(){ addDensity(Liquids.oil, 700); addViscosity(Liquids.oil, 50); addDensity(Liquids.cryofluid, 200); - addViscosity(Liquids.cryofluid, 1); + addViscosity(Liquids.cryofluid, 1.2f); addDensity(glacium, 1300); addViscosity(glacium, 13); addDensity(tiredGlacium, 1300); @@ -70,7 +70,7 @@ public static void addViscosity(Liquid liquid, float viscosity) { } public static float getDensity(@Nullable Liquid liquid) { - return densities.get(liquid, 1.2f); + return densities.get(liquid, 1f); } public static float getViscosity(@Nullable Liquid liquid) { diff --git a/src/omaloon/content/blocks/OlDistributionBlocks.java b/src/omaloon/content/blocks/OlDistributionBlocks.java index d7d35b95..337b6ab9 100644 --- a/src/omaloon/content/blocks/OlDistributionBlocks.java +++ b/src/omaloon/content/blocks/OlDistributionBlocks.java @@ -129,7 +129,7 @@ public static void load() { researchCost = with( OlItems.cobalt, 20 ); - pressureTransfer = 0.1f; + pumpStrength = 0.1f; pressureDifference = 20f; }}; diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidPump.java b/src/omaloon/world/blocks/liquid/PressureLiquidPump.java index 00155bea..51d9103a 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidPump.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidPump.java @@ -16,6 +16,7 @@ import mindustry.type.*; import mindustry.world.*; import mindustry.world.blocks.*; +import omaloon.content.*; import omaloon.utils.*; import omaloon.world.interfaces.*; import omaloon.world.meta.*; @@ -27,7 +28,7 @@ public class PressureLiquidPump extends Block { public PressureConfig pressureConfig = new PressureConfig(); - public float pressureTransfer = 0.1f; + public float pumpStrength = 0.1f; public float pressureDifference = 10; @@ -115,7 +116,7 @@ public void load() { public void setStats() { super.setStats(); pressureConfig.addStats(stats); - stats.add(OlStats.pressureFlow, Mathf.round(pressureTransfer * 60f, 2), OlStats.pressureSecond); + stats.add(OlStats.pressureFlow, Mathf.round(pumpStrength * 60f, 2), OlStats.pressureSecond); } public class PressureLiquidPumpBuild extends Building implements HasPressure { @@ -266,18 +267,24 @@ public void updateTile() { HasPressure front = getTo(); HasPressure back = getFrom(); - if (front != null && back != null) { - Liquid pumpLiquid = configurable ? Vars.content.liquid(filter) : back.pressure().getMain(); - float frontPressure = front.pressure().getPressure(pumpLiquid), backPressure = back.pressure().getPressure(pumpLiquid); - float flow = pressureTransfer/chainSize() * (backPressure - frontPressure + pressureDifference * chainSize()); - if (pumpLiquid != null) flow = Mathf.clamp(flow, -front.pressure().liquids[pumpLiquid.id], back.pressure().liquids[pumpLiquid.id]); - if ( - front.acceptsPressurizedFluid(back, pumpLiquid, flow) && - back.outputsPressurizedFluid(front, pumpLiquid, flow) - ) { - front.addFluid(pumpLiquid, flow); - back.removeFluid(pumpLiquid, flow); - } + @Nullable Liquid pumpLiquid = configurable ? Vars.content.liquid(filter) : (back == null ? null : back.pressure().getMain()); + + float frontPressure = front == null ? 0 : front.pressure().getPressure(pumpLiquid); + float backPressure = back == null ? 0 : back.pressure().getPressure(pumpLiquid); + + float flow = pumpStrength/chainSize() * ((backPressure + pressureDifference * chainSize()) - frontPressure) / OlLiquids.getViscosity(pumpLiquid); + + if (pumpLiquid != null && front != null && back != null) { + flow = Mathf.clamp(flow, -front.pressure().get(pumpLiquid), back.pressure().get(pumpLiquid)); + } + + if ( + front == null || back == null || + (front.acceptsPressurizedFluid(back, pumpLiquid, flow) && + back.outputsPressurizedFluid(front, pumpLiquid, flow)) + ) { + if (front != null) front.addFluid(pumpLiquid, flow); + if (back != null) back.removeFluid(pumpLiquid, flow); } } } diff --git a/src/omaloon/world/blocks/production/Pressurizer.java b/src/omaloon/world/blocks/production/Pressurizer.java deleted file mode 100644 index 0e51216a..00000000 --- a/src/omaloon/world/blocks/production/Pressurizer.java +++ /dev/null @@ -1,181 +0,0 @@ -package omaloon.world.blocks.production; - -import arc.*; -import arc.Graphics.*; -import arc.graphics.g2d.*; -import arc.math.*; -import arc.struct.*; -import arc.util.*; -import arc.util.io.*; -import mindustry.entities.units.*; -import mindustry.gen.*; -import mindustry.world.*; -import mindustry.world.draw.*; -import mindustry.world.meta.*; -import omaloon.world.interfaces.*; -import omaloon.world.meta.*; -import omaloon.world.modules.*; - -public class Pressurizer extends Block { - public PressureConfig pressureConfig = new PressureConfig(); - - public DrawBlock drawer = new DrawDefault(); - - public TextureRegion overlayRegion; - - public float progressTime = 60f; - public float warmupSpeed = 0.14f; - - public float outputPressure = 0f; - - public boolean continuous = false; - - public Pressurizer(String name) { - super(name); - update = true; - destructible = true; - solid = true; - saveConfig = copyConfig = true; - - config(Boolean.class, (PressurizerBuild build, Boolean bool) -> build.reverse = bool); - } - - @Override - public void drawPlanRegion(BuildPlan plan, Eachable list) { - drawer.drawPlan(this, plan, list); - if (plan.config instanceof Boolean bool && bool) Draw.rect(overlayRegion, plan.drawx(), plan.drawy(), rotate ? plan.rotation * 90f : 0); - } - - @Override public void getRegionsToOutline(Seq out) { - drawer.getRegionsToOutline(this, out); - } - - @Override - protected TextureRegion[] icons() { - return drawer.finalIcons(this); - } - - @Override - public void load() { - super.load(); - - drawer.load(this); - - overlayRegion = Core.atlas.find(name + "-overlay"); - } - - @Override - public void setBars() { - super.setBars(); - - pressureConfig.addBars(this); - } - - @Override - public void setStats() { - super.setStats(); - - pressureConfig.addStats(stats); - if (outputPressure != 0) stats.add(OlStats.outputPressure, Strings.autoFixed(outputPressure * (continuous ? 60f : 1f), 2), continuous ? OlStats.pressureSecond : OlStats.pressureUnits); - if (!continuous) stats.add(Stat.productionTime, Strings.autoFixed(progressTime/60f, 2), StatUnit.seconds); - } - - public class PressurizerBuild extends Building implements HasPressure { - public PressureModule pressure = new PressureModule(); - - public boolean reverse; - - public float warmup, progress, totalProgress; - - @Override public Cursor getCursor() { - return Cursor.SystemCursor.hand; - } - - @Override - public void draw() { - drawer.draw(this); - if (reverse) Draw.rect(overlayRegion, x, y, drawrot()); - } - @Override - public void drawLight() { - super.drawLight(); - drawer.drawLight(this); - } - - @Override public HasPressure getSectionDestination(HasPressure from) { - return null; - } - - @Override - public void onProximityUpdate() { - super.onProximityUpdate(); - - new PressureSection().mergeFlood(this); - } - - @Override public PressureModule pressure() { - return pressure; - } - @Override public PressureConfig pressureConfig() { - return pressureConfig; - } - - @Override public float progress() { - return progress; - } - - @Override - public void read(Reads read, byte revision) { - super.read(read, revision); - pressure.read(read); - - progress = read.f(); - totalProgress = read.f(); - warmup = read.f(); - - reverse = read.bool(); - } - - @Override public void tapped() { - configure(!reverse); - } - - @Override public float totalProgress() { - return totalProgress; - } - - @Override - public void updateTile() { - updatePressure(); - - if (efficiency > 0) { - progress += getProgressIncrease(progressTime); - warmup = Mathf.approachDelta(warmup, 1, warmupSpeed); - totalProgress += warmup * edelta(); - - if (continuous) addFluid(null, outputPressure * warmup * (reverse ? -1f : 1f)); - } else warmup = Mathf.approachDelta(warmup, 0, warmupSpeed); - - if(progress >= 1f){ - if (!continuous) addFluid(null, outputPressure * warmup * (reverse ? -1f : 1f)); - progress %= 1f; - } - } - - @Override public float warmup() { - return warmup; - } - - @Override - public void write(Writes write) { - super.write(write); - pressure.write(write); - - write.f(progress); - write.f(totalProgress); - write.f(warmup); - - write.bool(reverse); - } - } -} diff --git a/src/omaloon/world/interfaces/HasPressure.java b/src/omaloon/world/interfaces/HasPressure.java index 7538c734..16edafff 100644 --- a/src/omaloon/world/interfaces/HasPressure.java +++ b/src/omaloon/world/interfaces/HasPressure.java @@ -88,7 +88,7 @@ default void removeFluid(@Nullable Liquid liquid, float amount) { * method to update pressure related things */ default void updatePressure() { - if (nextBuilds().contains(other -> other.pressure().section != this)) pressure().section.updateTransfer(); +// if (nextBuilds().contains(other -> other.pressure().section != this)) pressure().section.updateTransfer(); Vars.content.liquids().each(liquid -> { if (Mathf.round(pressure().getPressure(liquid)) < pressureConfig().minPressure - 1) damage(pressureConfig().underPressureDamage); diff --git a/src/omaloon/world/meta/PressureSection.java b/src/omaloon/world/meta/PressureSection.java index 4364a545..c0f6461f 100644 --- a/src/omaloon/world/meta/PressureSection.java +++ b/src/omaloon/world/meta/PressureSection.java @@ -98,31 +98,82 @@ public void updateTransfer() { }); FloatSeq amounts = new FloatSeq(); - - for(Entry entry : links) { - @Nullable Liquid main = entry.value.pressure().getMain(); + + Vars.content.liquids().each(main -> { + amounts.clear(); + for (Entry entry : links) { + float flow = OlMath.flowRate(entry.value.pressureConfig().fluidCapacity, + entry.key.pressure().getPressure(main), + entry.value.pressure().getPressure(main), + OlLiquids.getViscosity(main) + ) / (2f * links.size); + + if ( + ( + flow > 0 ? + ( + entry.key.acceptsPressurizedFluid(entry.value, main, flow) && + entry.value.outputsPressurizedFluid(entry.key, main, flow) + ) : + ( + entry.value.acceptsPressurizedFluid(entry.key, main, flow) && + entry.key.outputsPressurizedFluid(entry.value, main, flow) + ) + ) && + (entry.key.pressure().get(main) > 0 || entry.value.pressure().get(main) > 0) + ) { + amounts.add(flow); + } else { + amounts.add(0); + } + } + for (Entry entry : links) { + float flow = Mathf.clamp( + amounts.get(links.indexOf(entry)), + -Math.abs(entry.key.pressure().get(main) - entry.value.pressure().get(main))/2f, + Math.abs(entry.key.pressure().get(main) - entry.value.pressure().get(main))/2f + ); +// float flow = amounts.get(links.indexOf(entry)); + if (flow != 0) { + entry.key.addFluid(main, flow); + entry.value.removeFluid(main, flow); + } + } + }); + amounts.clear(); + for (Entry entry : links) { float flow = OlMath.flowRate(entry.value.pressureConfig().fluidCapacity, - entry.key.pressure().getPressure(main), - entry.value.pressure().getPressure(main), - OlLiquids.getViscosity(main) - )/(2f * links.size); + entry.key.pressure().getPressure(null), + entry.value.pressure().getPressure(null), + OlLiquids.getViscosity(null) + ) / (2f * links.size); if ( - entry.key.acceptsPressurizedFluid(entry.value, main, flow) && - entry.value.outputsPressurizedFluid(entry.key, main, flow) + ( + flow > 0 ? + ( + entry.key.acceptsPressurizedFluid(entry.value, null, flow) && + entry.value.outputsPressurizedFluid(entry.key, null, flow) + ) : ( + entry.value.acceptsPressurizedFluid(entry.key, null, flow) && + entry.key.outputsPressurizedFluid(entry.value, null, flow) + ) + ) ) { amounts.add(flow); } else { amounts.add(0); } } - - - for(Entry entry : links) { - @Nullable Liquid main = entry.value.pressure().getMain(); - if (amounts.get(links.indexOf(entry)) != 0) { - entry.key.addFluid(main, amounts.get(links.indexOf(entry))); - entry.value.removeFluid(main, amounts.get(links.indexOf(entry))); + for (Entry entry : links) { + float flow = Mathf.clamp( + amounts.get(links.indexOf(entry)), + -Math.abs(entry.key.pressure().get(null) - entry.value.pressure().get(null))/2f, + Math.abs(entry.key.pressure().get(null) - entry.value.pressure().get(null))/2f + ); + if (flow != 0) { + entry.key.addFluid(null, amounts.get(links.indexOf(entry))); + entry.value.removeFluid(null, amounts.get(links.indexOf(entry))); } } } From 2e3e544fd020a9e714bfd53d7f729bc0f48f8b4e Mon Sep 17 00:00:00 2001 From: = Date: Sun, 12 Jan 2025 10:36:44 -0300 Subject: [PATCH 31/67] half working pump thingy --- src/omaloon/content/blocks/OlDistributionBlocks.java | 1 - .../world/blocks/liquid/PressureLiquidPump.java | 10 +++++++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/src/omaloon/content/blocks/OlDistributionBlocks.java b/src/omaloon/content/blocks/OlDistributionBlocks.java index 337b6ab9..a357d124 100644 --- a/src/omaloon/content/blocks/OlDistributionBlocks.java +++ b/src/omaloon/content/blocks/OlDistributionBlocks.java @@ -130,7 +130,6 @@ public static void load() { OlItems.cobalt, 20 ); pumpStrength = 0.1f; - pressureDifference = 20f; }}; liquidValve = new PressureLiquidValve("liquid-valve") {{ diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidPump.java b/src/omaloon/world/blocks/liquid/PressureLiquidPump.java index 51d9103a..215aaa7f 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidPump.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidPump.java @@ -202,6 +202,14 @@ public void draw() { if (tiling == 0) Draw.rect(topRegion, x, y, rotdeg()); } + public float pumpEfficiency() { + float a = 0; + for(int i = 1; i <= chainSize(); i++) { + a += pressureDifference/i; + } + return a; + } + /** * Returns the building at the start of the pump chain. */ @@ -272,7 +280,7 @@ public void updateTile() { float frontPressure = front == null ? 0 : front.pressure().getPressure(pumpLiquid); float backPressure = back == null ? 0 : back.pressure().getPressure(pumpLiquid); - float flow = pumpStrength/chainSize() * ((backPressure + pressureDifference * chainSize()) - frontPressure) / OlLiquids.getViscosity(pumpLiquid); + float flow = pumpStrength/chainSize() * ((backPressure + pumpEfficiency()) - frontPressure) / OlLiquids.getViscosity(pumpLiquid); if (pumpLiquid != null && front != null && back != null) { flow = Mathf.clamp(flow, -front.pressure().get(pumpLiquid), back.pressure().get(pumpLiquid)); From 707ce5d6fcd3db42bbd1643ee88b8b2a256f04c3 Mon Sep 17 00:00:00 2001 From: = Date: Sun, 12 Jan 2025 10:39:07 -0300 Subject: [PATCH 32/67] atleast this works with air --- src/omaloon/world/interfaces/HasPressure.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/omaloon/world/interfaces/HasPressure.java b/src/omaloon/world/interfaces/HasPressure.java index 16edafff..7538c734 100644 --- a/src/omaloon/world/interfaces/HasPressure.java +++ b/src/omaloon/world/interfaces/HasPressure.java @@ -88,7 +88,7 @@ default void removeFluid(@Nullable Liquid liquid, float amount) { * method to update pressure related things */ default void updatePressure() { -// if (nextBuilds().contains(other -> other.pressure().section != this)) pressure().section.updateTransfer(); + if (nextBuilds().contains(other -> other.pressure().section != this)) pressure().section.updateTransfer(); Vars.content.liquids().each(liquid -> { if (Mathf.round(pressure().getPressure(liquid)) < pressureConfig().minPressure - 1) damage(pressureConfig().underPressureDamage); From 3e59effc40442e76815f48adecc98d5cd8728baf Mon Sep 17 00:00:00 2001 From: = Date: Sun, 12 Jan 2025 20:56:44 -0300 Subject: [PATCH 33/67] stats --- assets/bundles/bundle.properties | 37 +++++++++++------- .../blocks/liquids/liquid-gauge-pointer.png | Bin 162 -> 211 bytes .../blocks/liquids/liquid-gauge-tiles.png | Bin 1015 -> 729 bytes .../sprites/blocks/liquids/liquid-gauge.png | Bin 428 -> 508 bytes src/omaloon/content/OlLiquids.java | 4 +- .../blocks/liquid/PressureLiquidPump.java | 5 ++- src/omaloon/world/consumers/ConsumeFluid.java | 2 +- src/omaloon/world/meta/OlStats.java | 19 +++++---- src/omaloon/world/meta/PressureConfig.java | 6 ++- 9 files changed, 45 insertions(+), 28 deletions(-) diff --git a/assets/bundles/bundle.properties b/assets/bundles/bundle.properties index f5a91bdd..9e3c6209 100644 --- a/assets/bundles/bundle.properties +++ b/assets/bundles/bundle.properties @@ -330,30 +330,39 @@ block.omaloon-hammer-drill.description = When placed on ore, outputs items. Effi ## stats category.omaloon-pressure = Pressure -stat.omaloon-density = Density -stat.omaloon-viscosity.format = @%, @ Todo - -stat.omaloon-consumepressure = Consume Pressure -stat.omaloon-minpressure = Min Pressure -stat.omaloon-maxpressure = Max Pressure stat.omaloon-max-speed = Max Speed stat.omaloon-min-speed = Min Speed -stat.omaloon-outputpressure = Output Pressure + +stat.omaloon-add-fluid = Add Fluid +air = Air +stat.omaloon-remove-fluid = Remove Fluid + +stat.omaloon-density = Density + +stat.omaloon-pump-strength = Pump Strength +stat.omaloon-pressure-gradient = Pressure Gradient + +stat.omaloon-min-pressure = Min Pressure +stat.omaloon-max-pressure = Max Pressure + stat.omaloon-pressureflow = Speed -stat.omaloon-pressurerange = Operating Range -stat.omaloon-pressurerange.format = from \uC357 @ pressure units to \uC357 @ pressure units. +stat.omaloon-pressure-range = Operating Range +stat.omaloon-pressure-range.format = between \uC357 @ Pascals and \uC357 @ Pascals. stat.omaloon-optimal-pressure = Optimal Pressure -stat.omaloon-optimal-pressure.format = \uC357 @ pressure units (@%) +stat.omaloon-optimal-pressure.format = \uC357 @ Pascals (@%) ## ui units -unit.omaloon-liquidperworldunit = Liquid per World cube -unit.omaloon-pressuresecond = pressure units / second -unit.omaloon-pressureunits = pressure units +unit.omaloon-density-unit = Pascals/Fluid Capacity +unit.omaloon-viscosity-unit = Pascal Seconds + +unit.omaloon-pressure-unit = Pascals +unit.omaloon-pressure-second = Pascals/Second + + bar.air = Air: bar.pressure = Pressure: bar.pressure-liquid = ({0}: {1} / Air: {2}) bar.hail-shield-health = Individual Shelter -omaloon-source-negative = Negative ## abilities ability.hailshield = Individual Shelter diff --git a/assets/sprites/blocks/liquids/liquid-gauge-pointer.png b/assets/sprites/blocks/liquids/liquid-gauge-pointer.png index bc46dd8c11f49f5a29d781c8fb8e81c1562e6429..b8df1cbfab802b4dbcce9b423e55c6f28e73cd46 100644 GIT binary patch delta 162 zcmZ3)c$sm6Wqqrsi(^PcYjT1F>*55Fo~A&90}T^ndiVXy{6F#MZ1ZzUr*$@&ER6Q+ zRQ9;maJq;M2(pchMfNS)qr?mZ&J{hze$_KFQZ0=lcBbh2)v8!F$eiZ1Y|`Rez!Gqj z(cOQp(h9b4D}|GcKY}dn+#h(iIO|J4Dq`8mdQk&tr8LM+Ms|kvx77qLu;`s<00K`} KKbLh*2~7a#GCH0B delta 112 zcmV-$0FVFE0ipqrIcZc$L_t(oh3(Wq4ge4gL{WABJJ*_!#t@Cef$xIz| zckdRNNxP(>G5n;&_P{D!EwObt3J=33PG|sNY?;^uN)3K Sr3M%P0000@kd7vLXu)1+@3I&EN2YWr@hk1ybpI&5fd*7azkMsam)p#W%E5IMW4-c;9Jia8-D7>3lbv zzh7oUa>KJfsfo{DD^~B_uQ@?PpGkMxE#}h#fn5*(85#95Y6jfi_GojSqB-{ire#NV za%fvJ@a$+^w&k0(?LLiV&dSes9I12=TDZ1=vC>v^?TVu!1?E#uEH%4Tw2zTtWxY5< zbmPH;K^N}yo}ZnWxvVpS_1&@O|GhWgQtH^Fyr8XP${f*v-CkuM*&`U`o&+<-{bLAN z(Q`=tfxtfo#XpSNhvYSm7Oe*g6!<&-VE*e1Bs77tOl|fGK9bow;T{F(iBtt)A)h?kUU4d!XL)(A}#h8?gNPlN`Dyj z5`HiX-J5H_ps(@EvC2PCluf0^Ur&vO2)mA=LlJ!e_O z*ME##*)K(&4VqP)>wPr;2lGSz9r`D6nXM*tNdClavG4p9Kbc$p`5oQ*fs4Ji(C|%0 Ryek6`c)I$ztaD0e0s!jYKcD~r delta 973 zcmV;;12X*C1@{M#IDZ4FNklWI<4CEg6AAvvNCS~g2svu43`^f?K2IERM zMk>Sgm1**cg!Y=#G^C`Z5rjYhdo5|kv?Nj^W}w6l`+pzlvzGS!@-XoCS8sZQ zOC&BY)&fsS3=!a*#2|t1Uk_r3m#1fFU`ziW79ee4FSts;OMk-SIq@eTBAU*V+Uf26 zU3`AO-Ku>ycN_7!=m8IS=`(H21pzO(mxMY8Jm8+T;v7hsN&}|9H_}F$2cidfLu6p> z8SiVFgmVWJyhK6+&k{fZJZ;tuGJ=Ny0^e{09^srwhIEDkczgE#uh!` zCE*F>W3GcWE%T&t;W=S=Ry+_9<>En4I~{k!E0Jz$yxo4ZZX3rNJ|bELaIP+A3D^#NobSo{RiQk%}x0-)q-1Y9JbnMA@0E`7P? z`hW#oB!5st!U|4Q*od@_8bLH8f|j8MRGSf*MJnE*HY1Yyhw1|t0+A#_^Z}JX1PSPD z*wWJafz|VY^b3b1B%DN8Ml_S?Qa@nP6U4Kj76XtNZ`Bj72p~5cITBVqfrx1M^ZT#5 z3^f;e!mjJ;)&fq{sD8i;?j0p{mIAD z4mR8V^g8OIa(Y z1E^Zgt*JiHq<+8)?j-^5gcf~(sIqIXa|y!8X!^Z|717DmId^>P{ohw2BkhPi>g;3@$xiR$`+T796p vexOz#Xi`5=s}Gp#2O{+Wq8o?>-vmAZ^9k&M>)UQX00000NkvXXu0mjf84|}4 diff --git a/assets/sprites/blocks/liquids/liquid-gauge.png b/assets/sprites/blocks/liquids/liquid-gauge.png index 46865391aec4e27f2191df4133d6354043b4a5c5..79359a548b55c5905bebd5533c7d10328612d121 100644 GIT binary patch delta 461 zcmV;;0W$uq1N;M!Ie)H6L_t(oh0T{ePQySDh2J8VNE`v>5^3n5=BI)JIwUA^03>=M za)2!okq!!|@>4@clS^2+1szly*2}!v*(kAimF?K`J@5QD>yYU6`TaY+wn<%F9l7|t zak6c=WMXyD7CbfKa`1Xt0{}i3iz2{5w+jI1>~~ZX&H@jznturJAkD;%6)pv~z*(%I z$_fvfO@;sf?|tKXuh#YO78bER1vv$w6VLEWEaLr7Sfo&^mARRK2EFUSB0(X3RBh~Bz0NX1RH=Y0amj->q5OCIbAAfi_IUZ~*uLGN8se-p30?00000NkvXXu0mjf DZ^zS( delta 380 zcmV-?0fYYh1FQp(Ie%VBL_t(og~eApb^fT~g=M1PZ9hnL-T(qzR#h zj%F{hkCTK7;qjZ@kc8_4 z+$Z4}`0{g29cFJ6Rp1=|yBr`XuoYY+U?pM69Q_3V(3~34>3>+)R6nXJ(Pwx+q Date: Sun, 12 Jan 2025 22:22:28 -0300 Subject: [PATCH 34/67] pump effects --- src/omaloon/content/OlFx.java | 30 +++++++++++++++++-- src/omaloon/content/OlLiquids.java | 2 +- .../content/blocks/OlDistributionBlocks.java | 8 +++-- .../blocks/liquid/PressureLiquidPump.java | 18 +++++++++++ .../blocks/liquid/PressureLiquidValve.java | 4 +-- 5 files changed, 55 insertions(+), 7 deletions(-) diff --git a/src/omaloon/content/OlFx.java b/src/omaloon/content/OlFx.java index a172d62a..498945d4 100644 --- a/src/omaloon/content/OlFx.java +++ b/src/omaloon/content/OlFx.java @@ -182,7 +182,7 @@ public class OlFx { Draw.blend(); }), - pumpOut = new Effect(60f, e -> { + flowOut = new Effect(60f, e -> { Draw.color(e.color); Draw.alpha(e.fout() / 5); vec.trns(e.rotation, 4f).add(e.x, e.y); @@ -202,7 +202,7 @@ public class OlFx { Fill.rect(vec.x + x, vec.y + y, 5 * e.fin(), e.fin(), vec.angleTo(vec.x + x, vec.y + y)); }); }), - pumpIn = new Effect(60f, e -> { + flowIn = new Effect(60f, e -> { Draw.color(e.color); Draw.alpha(e.fin() / 5); vec.trns(e.rotation, 4f).add(e.x, e.y); @@ -223,6 +223,32 @@ public class OlFx { }); }), + pumpOut = new Effect(60f, e -> { + Draw.color(e.color); + Draw.alpha(e.fout() / 5); + vec.trns(e.rotation, 4f).add(e.x, e.y); + Angles.randLenVectors(e.id, 3, 16 * e.fin(), e.rotation, 10, (x, y) -> { + Fill.circle(vec.x + x, vec.y + y, 3 * e.fin()); + }); + Draw.alpha(e.fout() / 7); + vec.trns(e.rotation, 4f).add(e.x, e.y); + Angles.randLenVectors(e.id + 3, 3, 16 * e.fin(), e.rotation, 20, (x, y) -> { + Fill.rect(vec.x + x, vec.y + y, 5 * e.fin(), e.fin(), vec.angleTo(vec.x + x, vec.y + y)); + }); + }), + pumpIn = new Effect(60f, e -> { + Draw.color(e.color); + Draw.alpha(e.fin() / 5); + vec.trns(e.rotation, 4f).add(e.x, e.y); + Angles.randLenVectors(e.id, 3, 16 * e.fout(), e.rotation, 10, (x, y) -> { + Fill.circle(vec.x + x, vec.y + y, 3 * e.fout()); + }); + Draw.alpha(e.fin() / 7); + Angles.randLenVectors(e.id + 3, 3, 16 * e.fout(), e.rotation, 20, (x, y) -> { + Fill.rect(vec.x + x, vec.y + y, 5 * e.fout(), e.fout(), vec.angleTo(vec.x + x, vec.y + y)); + }); + }), + shelterRotate = new Effect(60f, e -> { if (!(e.data instanceof Block data)) return; diff --git a/src/omaloon/content/OlLiquids.java b/src/omaloon/content/OlLiquids.java index 2e6f0059..7cc040be 100644 --- a/src/omaloon/content/OlLiquids.java +++ b/src/omaloon/content/OlLiquids.java @@ -66,7 +66,7 @@ public static void addDensity(Liquid liquid, float density) { public static void addViscosity(Liquid liquid, float viscosity) { viscosities.put(liquid, viscosity); liquid.stats.remove(Stat.viscosity); - liquid.stats.add(Stat.viscosity, viscosity, OlStats.viscosityUnit); + liquid.stats.add(Stat.viscosity, Strings.autoFixed(viscosity/60f, 2), OlStats.viscosityUnit); } public static float getDensity(@Nullable Liquid liquid) { diff --git a/src/omaloon/content/blocks/OlDistributionBlocks.java b/src/omaloon/content/blocks/OlDistributionBlocks.java index a357d124..83564ab6 100644 --- a/src/omaloon/content/blocks/OlDistributionBlocks.java +++ b/src/omaloon/content/blocks/OlDistributionBlocks.java @@ -130,6 +130,9 @@ public static void load() { OlItems.cobalt, 20 ); pumpStrength = 0.1f; + + pumpEffectIn = OlFx.pumpIn; + pumpEffectOut = OlFx.pumpOut; }}; liquidValve = new PressureLiquidValve("liquid-valve") {{ @@ -142,6 +145,9 @@ public static void load() { Items.beryllium, 20 ); pressureLoss = 0.3f; + + pumpingEffectIn = OlFx.flowIn; + pumpingEffectOut = OlFx.flowOut; }}; liquidGauge = new PressureLiquidGauge("liquid-gauge") {{ @@ -153,8 +159,6 @@ public static void load() { OlItems.cobalt, 20, OlItems.carborundum, 10 ); - maxColor = Color.lightGray; - minColor = Color.darkGray; }}; //endregion } diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidPump.java b/src/omaloon/world/blocks/liquid/PressureLiquidPump.java index e3ee4a79..02f803c5 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidPump.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidPump.java @@ -10,6 +10,7 @@ import arc.util.io.*; import mindustry.*; import mindustry.content.*; +import mindustry.entities.*; import mindustry.entities.units.*; import mindustry.gen.*; import mindustry.graphics.*; @@ -35,6 +36,10 @@ public class PressureLiquidPump extends Block { public float liquidPadding = 3f; + public float effectInterval = 5f; + public Effect pumpEffectOut = Fx.none; + public Effect pumpEffectIn = Fx.none; + public TextureRegion[][] liquidRegions; public TextureRegion[] tiles; public TextureRegion arrowRegion, topRegion, bottomRegion; @@ -125,6 +130,7 @@ public void setStats() { public class PressureLiquidPumpBuild extends Building implements HasPressure { PressureModule pressure = new PressureModule(); + public float effectTimer; public int tiling; public float smoothAlpha; @@ -285,6 +291,17 @@ public void updateTile() { float flow = pumpStrength/chainSize() * ((backPressure + pumpEfficiency()) - frontPressure) / OlLiquids.getViscosity(pumpLiquid); + if (effectTimer >= effectInterval && !Mathf.zero(flow, 0.001f)) { + if (flow < 0) { + if (back == null && !(back() instanceof PressureLiquidPumpBuild)) pumpEffectOut.at(x, y, rotdeg() + 180f); + if (front == null && !(front() instanceof PressureLiquidPumpBuild)) pumpEffectIn.at(x, y, rotdeg()); + } else { + if (back == null && !(back() instanceof PressureLiquidPumpBuild)) pumpEffectIn.at(x, y, rotdeg() + 180f); + if (front == null && !(front() instanceof PressureLiquidPumpBuild)) pumpEffectOut.at(x, y, rotdeg()); + } + effectTimer %= 1; + } + if (pumpLiquid != null && front != null && back != null) { flow = Mathf.clamp(flow, -front.pressure().get(pumpLiquid), back.pressure().get(pumpLiquid)); } @@ -294,6 +311,7 @@ public void updateTile() { (front.acceptsPressurizedFluid(back, pumpLiquid, flow) && back.outputsPressurizedFluid(front, pumpLiquid, flow)) ) { + effectTimer += edelta(); if (front != null) front.addFluid(pumpLiquid, flow); if (back != null) back.removeFluid(pumpLiquid, flow); } diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidValve.java b/src/omaloon/world/blocks/liquid/PressureLiquidValve.java index 4d7eef33..6a598ec4 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidValve.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidValve.java @@ -35,8 +35,8 @@ public class PressureLiquidValve extends Block { public Effect jamEffect = Fx.explosion; public Sound jamSound = OlSounds.jam; - public Effect pumpingEffectOut = OlFx.pumpOut; - public Effect pumpingEffectIn = OlFx.pumpIn; + public Effect pumpingEffectOut = Fx.none; + public Effect pumpingEffectIn = Fx.none; public float pumpingEffectInterval = 15; public float pressureLoss = 1f; From ff117adf185cb8ff4b8f9154ae3836b11efc8b67 Mon Sep 17 00:00:00 2001 From: = Date: Mon, 13 Jan 2025 20:01:10 -0300 Subject: [PATCH 35/67] hints --- assets/bundles/bundle.properties | 8 +------ .../blocks/liquids/liquid-gauge-tiles.png | Bin 729 -> 724 bytes .../sprites/blocks/liquids/liquid-gauge.png | Bin 508 -> 502 bytes src/omaloon/ui/dialogs/EventHints.java | 20 +++--------------- .../blocks/liquid/PressureLiquidPump.java | 6 ++---- 5 files changed, 6 insertions(+), 28 deletions(-) diff --git a/assets/bundles/bundle.properties b/assets/bundles/bundle.properties index 9e3c6209..51026329 100644 --- a/assets/bundles/bundle.properties +++ b/assets/bundles/bundle.properties @@ -61,13 +61,7 @@ omaloon.update.dialog.fullclean.confirm = Are you sure you want to reset your cu requirement.omaloon-at-wave = Reach Wave {0} in {1} ## Hints -hint.omaloon-pump_positive = To create higher pressure, place \uC353[accent] mechanical pumps[] in series, adding liquid pipes between them.\nTo increase pressure faster, place \uC353[accent] mechanical pumps[] in parallel. -hint.omaloon-pump_negative = To decrease pressure faster, add more \uC353[accent]mechanical pumps[]. -hint.omaloon-drill_positive_pressure = \uC351 [accent]Hammer drills[] require negative pressure to operate. Rotate the \uC353[accent] mechanical pumps[] away from the drills to create negative pressure. -hint.omaloon-press_or_shelter_negative_pressure = Some buildings require positive pressure. Rotate the \uC353[accent] mechanical pumps[] to these blocks to create positive pressure. -hint.omaloon-pump = The pumps only stop when there is a block in front of it or the front block has enough pressure. -hint.omaloon-low_pressure = Buildings will implode when it reaches -50 pressure units. To avoid this, use \uC354 [accent]Liquid Valve[], which will reduce the pressure, preventing it from reaching dangerous levels. -hint.omaloon-valve = One valve can handle up to three pumps. If you have more pumps, place more valves to avoid jamming. +hint.omaloon-pump_chaining = Pumps chained in series can reach a higher pressure gradient between the ends. If they're chained in parallel, they work faster. ## planets planet.omaloon-omaloon.name = Omaloon diff --git a/assets/sprites/blocks/liquids/liquid-gauge-tiles.png b/assets/sprites/blocks/liquids/liquid-gauge-tiles.png index 6f9ad340582862b2cca383c546db3f192bfcc1c8..1b10b2d84b9c4aa0607e29148af712e0573148c2 100644 GIT binary patch delta 679 zcmcb~dWCg@Wqq5ci(^Q|oVQWde$0jfwcSAh3WY33R5M;Icy`%=E690bu|i>^uEUgt z3{rNcFEe(y91)zL@nXTOggG-e-h5NFZAQ3dr|tWrkH0=&tL?I5?w*?C_qTRF%-GIl z|NrL&Q%m)vI1N|1?iE2#CjY*@w8PEaIn?E&)FbPvXqI^d#m^n^1S5gM}M4Z``}(HR-Z_-|0yKdTIlVj(!rpHig#_3i-uflpa8&SL z{Dqp2KR2HGH}6ej#i2~6bqDKhSUnj}FHu;YyS2RFRA1w=$^9&uRqyh-wuHXje<5k5 z?S;0E5S~)QTX$}-T&M|KQtA->>8PB-Cxd{VUF(jf+vW%#J0*0$w8ORK$VLvo4Jt_v z*>!$TchAl=lD+lmbYbV`hHaB`nKI{R?$>5xSSjA{wAx9zzHZN|XYR(nF5(q+^?QEV z&YCLb_=KCutApcYB;!*5lWPAMv=21Z=p8sE&mg3({GHumhrL5Vy@L2V{v}B>=l9%^ zH}G%#&HUFFNHqLrE^<(Mekvx`x8*nUx7|qx&dJZ<_UL>er1q~t+-(`eh+o;B?s!@~W+g_?gD<`$$ZT_u{knE?nqUHx3v IIVCg!06u;~`~Uy| delta 684 zcmcb@dXsg6Wqr4&i(^Q|oVQUM{iGcQYTIK16h3lJtZ!=5Tj?A$v8lu(;0LqPQuc%F zF^pWYA`1@%wD+~m-|&NFiO9X$+1ato#jbJ|1B0BL{Bxxn_ii!OGw|5+gbMby&Pfn; ze8S>;WY*L<+&PNVlLXnqiVnR!E6K1R_x8-!i!X986jaq5yk}lHYlE%fg%d@8e(cQ8 zTHJX;aoGYFzyB8Y&u(R9`1RF^%I~jaS~j67$<5*A&--_O?+~zj`0G{N-&o&+(I<5c zT^LU*Y(HYee<;*ZrbT-8e}?)J_aA!}{CxEOv(@kFjqIN|(*=uo-)U-aRd{phd^elF zUuHvc!?QoBiO*jvR`1=fIYC69Nq5>U=F}XxK<(swbK8=`kC9=ecs)aO ze!>apsi!d9MOQ?US%KIBN*kL1T)6{V+dH$ zb4dPyz&{4XKaARk87m<3O}=3G3{{)`3|D? z%@SU>VaT;u2GE)NV(~-4}<~OsM1&0L;VP6D`7z)rvYyfr|tq2S^S0 z==M96$Q@>rrTRRpN*?B!MXB5Gs3K?^mLX?rDZbPQq>?*4-ai-aTZgTv09u6m2VVe+ z6|Rv>h2{hRa(@c~N(vmpfs;zEi76$ZZbSuyLq>v|7aCX!%*ol6SOcuB%G7~hgv_pV z7ihEo=Jv9zJDvjVOQq;&<684YQ;^~~1sXXJ*^E*Ki3T@nS;5^3n5=BI)JIwUA^03>=M za)2!okq!!|@>4@clS^2+1szly*2}!v*(kAimF?K`J@5QD>yYU6`TaY+wn<%F9l7|t zak6c=WMXyD7CbfKa`1Xt0{}i3iz2{5w+jI1>~~ZX&H@jznturJAkD;%6)pv~z*(%I z$_fvfO@;sf?|tKXuh#YO78bER1vv$w6VLEWEaLr7Sfo&^mARRK2EFUSB0(X3RBh~Bz0NX1RH=Y0amj->q5OCIbAAfi_IUZ~*uLGN8se-p30?00000NkvXXu0mjf D^$FA0 diff --git a/src/omaloon/ui/dialogs/EventHints.java b/src/omaloon/ui/dialogs/EventHints.java index b560ed27..a475501c 100644 --- a/src/omaloon/ui/dialogs/EventHints.java +++ b/src/omaloon/ui/dialogs/EventHints.java @@ -6,26 +6,12 @@ import arc.util.*; import mindustry.*; import mindustry.ui.fragments.HintsFragment.*; -import omaloon.content.blocks.*; +import omaloon.world.blocks.liquid.*; public enum EventHints implements Hint { -// drill_positive_pressure( -// () -> false, -// () -> Vars.state.teams.get(Vars.state.rules.defaultTeam).getBuildings(OlProductionBlocks.hammerDrill).find(b -> ((HasPressure) b).getPressure() > 0f) != null -// ), -// press_or_shelter_negative_pressure( -// () -> false, -// () -> Vars.state.teams.get(Vars.state.rules.defaultTeam).getBuildings(OlCraftingBlocks.carborundumPress).find(b -> ((HasPressure) b).getPressure() < 0f) != null -// || Vars.state.teams.get(Vars.state.rules.defaultTeam).getBuildings(OlDefenceBlocks.smallShelter).find(b -> ((HasPressure) b).getPressure() < 0f) != null -// ), - pump( + pump_chaining( () -> false, - () -> !Vars.state.teams.get(Vars.state.rules.defaultTeam).getBuildings(OlDistributionBlocks.liquidPump).isEmpty() - ), - valve( - () -> false, - () -> !Vars.state.teams.get(Vars.state.rules.defaultTeam).getBuildings(OlDistributionBlocks.liquidValve).isEmpty(), - pump + () -> Vars.control.input.block instanceof PressureLiquidPump ); final Boolp complete; diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidPump.java b/src/omaloon/world/blocks/liquid/PressureLiquidPump.java index 02f803c5..9bbae047 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidPump.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidPump.java @@ -50,9 +50,7 @@ public PressureLiquidPump(String name) { destructible = true; update = true; saveConfig = copyConfig = true; - config(Liquid.class, (PressureLiquidPumpBuild build, Liquid liquid) -> { - build.filter = liquid.id; - }); + config(Liquid.class, (PressureLiquidPumpBuild build, Liquid liquid) -> build.filter = liquid.id); } @Override @@ -153,7 +151,7 @@ public int chainSize() { } @Override public boolean connects(HasPressure to) { - return HasPressure.super.connects(to) && (front() == to || back() == to); + return HasPressure.super.connects(to) && (front() == to || back() == to) && (!(to instanceof PressureLiquidPumpBuild) || to.rotation() == rotation); } @Override From 1e126b26846b621576d39f869cdfa8491459e1ac Mon Sep 17 00:00:00 2001 From: = Date: Mon, 13 Jan 2025 22:04:44 -0300 Subject: [PATCH 36/67] flow that actually works --- src/omaloon/math/OlMath.java | 18 +++++++++++++++--- .../blocks/liquid/PressureLiquidValve.java | 18 ++++++++++++++++-- src/omaloon/world/meta/PressureSection.java | 14 ++++++++++---- 3 files changed, 41 insertions(+), 9 deletions(-) diff --git a/src/omaloon/math/OlMath.java b/src/omaloon/math/OlMath.java index 325467b2..38267560 100644 --- a/src/omaloon/math/OlMath.java +++ b/src/omaloon/math/OlMath.java @@ -11,8 +11,20 @@ public class OlMath { * * returns the amount of fluid in liquid units that passes through the area over a certain time. */ - public static float flowRate(float opening, float pressureStart, float pressureEnd, float viscosity) { - return opening * (pressureEnd - pressureStart) / (viscosity * 60f); + public static float flowRate(float pressureStart, float pressureEnd, float capacityStart, float capacityEnd, float density, float viscosity) { + return + ( + capacityStart * ( + pressureStart * ( + capacityStart + capacityEnd + ) - ( + pressureEnd * capacityEnd + pressureStart * capacityStart + ) + ) + ) / ( + density * ( + capacityStart + capacityEnd + ) * viscosity + ); } - // TODO rename } diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidValve.java b/src/omaloon/world/blocks/liquid/PressureLiquidValve.java index 6a598ec4..8930d09c 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidValve.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidValve.java @@ -217,12 +217,26 @@ public void updatePressure() { if (jammed) return; if (pressureAmount < openMin) { effectInterval += delta(); - addFluid(null, Math.min(openMin - pressureAmount, OlMath.flowRate(pressureLoss, 0, pressureAmount, OlLiquids.getViscosity(pressure.getMain())))); + addFluid(null, Math.min(openMin - pressureAmount, OlMath.flowRate( + 0, + pressureAmount, + 5, + pressureConfig.fluidCapacity, + OlLiquids.getDensity(null), + OlLiquids.getViscosity(null) + ))); draining = Mathf.approachDelta(draining, 1, 0.014f); } if (pressureAmount > openMax) { effectInterval += delta(); - removeFluid(pressure.getMain(), Math.min(pressureAmount - openMax, OlMath.flowRate(pressureLoss, pressureAmount, 0, OlLiquids.getViscosity(pressure.getMain())))); + removeFluid(pressure.getMain(), Math.min(pressureAmount - openMax, OlMath.flowRate( + pressureAmount, + 0, + pressureConfig.fluidCapacity, + 5, + OlLiquids.getDensity(null), + OlLiquids.getViscosity(null) + ))); draining = Mathf.approachDelta(draining, 1, 0.014f); } if (effectInterval > pumpingEffectInterval) { diff --git a/src/omaloon/world/meta/PressureSection.java b/src/omaloon/world/meta/PressureSection.java index c0f6461f..1f213873 100644 --- a/src/omaloon/world/meta/PressureSection.java +++ b/src/omaloon/world/meta/PressureSection.java @@ -102,9 +102,12 @@ public void updateTransfer() { Vars.content.liquids().each(main -> { amounts.clear(); for (Entry entry : links) { - float flow = OlMath.flowRate(entry.value.pressureConfig().fluidCapacity, - entry.key.pressure().getPressure(main), + float flow = OlMath.flowRate( entry.value.pressure().getPressure(main), + entry.key.pressure().getPressure(main), + entry.value.pressureConfig().fluidCapacity, + entry.key.pressureConfig().fluidCapacity, + OlLiquids.getDensity(main), OlLiquids.getViscosity(main) ) / (2f * links.size); @@ -142,9 +145,12 @@ public void updateTransfer() { }); amounts.clear(); for (Entry entry : links) { - float flow = OlMath.flowRate(entry.value.pressureConfig().fluidCapacity, - entry.key.pressure().getPressure(null), + float flow = OlMath.flowRate( entry.value.pressure().getPressure(null), + entry.key.pressure().getPressure(null), + entry.value.pressureConfig().fluidCapacity, + entry.key.pressureConfig().fluidCapacity, + OlLiquids.getDensity(null), OlLiquids.getViscosity(null) ) / (2f * links.size); From ff21f2827efa087b23227456821d69f71b6bebb4 Mon Sep 17 00:00:00 2001 From: = Date: Tue, 14 Jan 2025 02:16:28 -0300 Subject: [PATCH 37/67] pump fix (only on front) --- .../world/blocks/liquid/PressureLiquidPump.java | 10 +++++++--- src/omaloon/world/interfaces/HasPressure.java | 4 ++-- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidPump.java b/src/omaloon/world/blocks/liquid/PressureLiquidPump.java index 9bbae047..563833a3 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidPump.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidPump.java @@ -31,6 +31,7 @@ public class PressureLiquidPump extends Block { public PressureConfig pressureConfig = new PressureConfig(); public float pumpStrength = 0.1f; + public float efficiencyScale = 0.5f; public float pressureDifference = 10; @@ -211,10 +212,13 @@ public void draw() { public float pumpEfficiency() { float a = 0; - for(int i = 1; i <= chainSize(); i++) { - a += pressureDifference/i; + for(int i = 0; i < chainSize(); i++) { + a += pressureDifference * Mathf.pow(efficiencyScale, i); } - return a; + return a * ((pressureDifference)/((getFrom() == null ? pressureDifference : Math.max( + pressureDifference, + Math.abs(getFrom().pressure().getPressure(configurable ? Vars.content.liquid(filter) : getFrom().pressure().getMain())) + )))); } /** diff --git a/src/omaloon/world/interfaces/HasPressure.java b/src/omaloon/world/interfaces/HasPressure.java index 7538c734..604608c1 100644 --- a/src/omaloon/world/interfaces/HasPressure.java +++ b/src/omaloon/world/interfaces/HasPressure.java @@ -91,8 +91,8 @@ default void updatePressure() { if (nextBuilds().contains(other -> other.pressure().section != this)) pressure().section.updateTransfer(); Vars.content.liquids().each(liquid -> { - if (Mathf.round(pressure().getPressure(liquid)) < pressureConfig().minPressure - 1) damage(pressureConfig().underPressureDamage); - if (Mathf.round(pressure().getPressure(liquid)) > pressureConfig().maxPressure + 1) damage(pressureConfig().overPressureDamage); + if (pressure().getPressure(liquid) < pressureConfig().minPressure - 1f) damage(pressureConfig().underPressureDamage); + if (pressure().getPressure(liquid) > pressureConfig().maxPressure + 1f) damage(pressureConfig().overPressureDamage); }); } } From f5df403a91e1a5a213fc569baf8a6645b90da092 Mon Sep 17 00:00:00 2001 From: = Date: Tue, 14 Jan 2025 13:23:45 -0300 Subject: [PATCH 38/67] fluid capacity stat --- assets/bundles/bundle.properties | 7 ++++++- src/omaloon/world/meta/OlStats.java | 4 ++++ src/omaloon/world/meta/PressureConfig.java | 2 +- 3 files changed, 11 insertions(+), 2 deletions(-) diff --git a/assets/bundles/bundle.properties b/assets/bundles/bundle.properties index 51026329..60685a05 100644 --- a/assets/bundles/bundle.properties +++ b/assets/bundles/bundle.properties @@ -331,6 +331,9 @@ stat.omaloon-add-fluid = Add Fluid air = Air stat.omaloon-remove-fluid = Remove Fluid +stat.omaloon-fluid-capacity = Fluid Capacity +stat.omaloon-fluid-capacity.format = @x@x@ Blocks + stat.omaloon-density = Density stat.omaloon-pump-strength = Pump Strength @@ -346,7 +349,9 @@ stat.omaloon-optimal-pressure = Optimal Pressure stat.omaloon-optimal-pressure.format = \uC357 @ Pascals (@%) ## ui units -unit.omaloon-density-unit = Pascals/Fluid Capacity +unit.omaloon-blocks-cubed = Blocks\u00B3 + +unit.omaloon-density-unit = Pascals/Blocks\u00B3 unit.omaloon-viscosity-unit = Pascal Seconds unit.omaloon-pressure-unit = Pascals diff --git a/src/omaloon/world/meta/OlStats.java b/src/omaloon/world/meta/OlStats.java index 76b4c2f3..6b173779 100644 --- a/src/omaloon/world/meta/OlStats.java +++ b/src/omaloon/world/meta/OlStats.java @@ -21,6 +21,8 @@ public class OlStats { addFluid = new Stat("omaloon-add-fluid", StatCat.crafting), removeFluid = new Stat("omaloon-remove-fluid", StatCat.crafting), + fluidCapacity = new Stat("omaloon-fluid-capacity", StatCat.liquids), + density = new Stat("omaloon-density"), pressureFlow = new Stat("omaloon-pressureflow", pressure), @@ -35,6 +37,8 @@ public class OlStats { optimalPressure = new Stat("omaloon-optimal-pressure", pressure); public static final StatUnit + blocksCubed = new StatUnit("omaloon-blocks-cubed"), + densityUnit = new StatUnit("omaloon-density-unit", "\uC357"), viscosityUnit = new StatUnit("omaloon-viscosity-unit", "\uC357"), diff --git a/src/omaloon/world/meta/PressureConfig.java b/src/omaloon/world/meta/PressureConfig.java index a350fd28..e95753d4 100644 --- a/src/omaloon/world/meta/PressureConfig.java +++ b/src/omaloon/world/meta/PressureConfig.java @@ -78,7 +78,7 @@ public class PressureConfig { }; public void addStats(Stats stats) { - stats.add(Stat.liquidCapacity, fluidCapacity, StatUnit.liquidUnits); + stats.add(OlStats.fluidCapacity, Core.bundle.get("stat.omaloon-fluid-capacity.format"), fluidCapacity/8f, fluidCapacity/8f, fluidCapacity/8f); stats.add(OlStats.maxPressure, maxPressure, OlStats.pressureUnit); stats.add(OlStats.minPressure, minPressure, OlStats.pressureUnit); From e3fc2ba30ef9c0fea163f40d2cdfece5677a8bf1 Mon Sep 17 00:00:00 2001 From: xstabux Date: Tue, 14 Jan 2025 16:00:21 +0200 Subject: [PATCH 39/67] pump sprite retouch (cherry picked from commit 725b6844f0fc63c7c28c94ce3545cbdf51609321) --- .../blocks/liquids/liquid-pump-tiles.png | Bin 1167 -> 1087 bytes .../blocks/liquids/liquid-pump-top.png | Bin 173 -> 163 bytes assets/sprites/blocks/liquids/liquid-pump.png | Bin 606 -> 539 bytes 3 files changed, 0 insertions(+), 0 deletions(-) diff --git a/assets/sprites/blocks/liquids/liquid-pump-tiles.png b/assets/sprites/blocks/liquids/liquid-pump-tiles.png index e82cb5309d0e3af37b0cbbf48e66762eaa4548e9..792a5fb3cc79b986789a6cf0211dc4d077853842 100644 GIT binary patch delta 1054 zcmV+(1mXLS3BL%CFnTS&q>4ce z1Vrs@gJ3O)e?pLeaLt)21X4w?xx)2tkmVW`5>lqHiH)<&&AoZ^W_D)wH2L5l?Creo zeeb<{^J6y!3=9XK&j8@?V8{Fl0B~}2OkP*Ga&?Zpe*eKU0Dr*x#=U|YpPFBaT>6#X zT>K_FHfMYT#zD7b6P$}bT|-vO#g> z!B;SyP~-|ePJg7}k5L3v@TL4Q^ylCg6@VFhia>HtC_?$06ag1}DSs3Fx%fM_)uyju z>KZjx$Kk<_b+sFVUk{ufP#1iIZ@VVZ-zGl*6fd4UJp<^)LP%9f$C%<{@VmB{@7{h8 zO?R)~JQr@X!)Q~8f=}`lnr;ns zZd*H+>JRlLL^s7b(E)seUyUnvapn6<$dUZmNYM#$qH}U|4D~UgZ=+1;iRX%dvY~T^ z^3Ou@6@NHiT>9I_L`?BkF$i*K6K4${4VAJ1*FFGf=3%J1f!Bht@VJ=#@)*N!bFaIpVbsRm5 zxaa`q98(?O(dHHa``k1tOKVkA=hh0n`5t&WR47 zf)DTq6qM7h8D#&O#AzKKu(OfyMITQY~O^;WmIcj&nASzkemig!1q2ZF?OI*&Yk~ zK7WY|O}?&w_3^79ev{iL2D<+L;%T5yC*a-*kiIYA;tbU<<)^r%F)%sm0#Ls`g_Q3D zm|QXVB>|8GSaMI(lRVz%%?|Qw8g6mzvnEEO0x%dH~ zkoCdoI)P=`{f_2=U6NLP=# zLFzP5za}N$-`g%y@Hb69HCDG7Q-7QMz~BE20_+PLbIW$)`Zd;|dAMPl-%atk`K3s$ z-!%oN)?ZHnR5jZ6>pq}tP+U3rbByI|NV{GR{S#{d-LV+tlr2tt4*ry5B(`!UUl(HQ Y4+Or5vSgw8I{*Lx07*qoM6N<$g10IOd;kCd delta 1134 zcmV-!1d;o{2#*PnFn4e-6#n**6qXV}ZNib#Kq^l{8bvEXQpKPK z0-|=dL9iCYpCA$t(!{GmAXS7kDZKm!Ij&J5A!Q1i*f`7V+?zM=&Fs#ukPi;R-pu>n z_ukvLGqaZh4tBP`T>!wr{+9a{0O0K8l)P?m?fNWv{o$h*0DpkB^#=tvziECca_KjE zbMd?A`JB-PjDu~lXE1tIQ=>JU6chtIaY@glnsh2Cx4E)oQ<4C5VBEd9NHf4 z003srC*=2kuFe4f)>qd=&Y5;tH~;crP+sfL^+mq;FrJLdzmG;E5x+)%NPCm~01$M* zzy#mGb;6JvXn&k&g1?R;pn@;uuS0(heo+Cq!3U}VrX18b5yS7=4*94p0xtMc{uKSW z_@qJ+bgaJ ze5Y6;ej8m%zJas|IQ?y4Y7H=RKEa)PtHFtO;>VM5usbXd1~@((2JK4uQ=mB$(12SL z`1CjB3kRE%+y!V1aMv!;eN1%#AMC}8uRTk~Xn)bQMNa>r#c8Ts| zsslXP*aQ%6=|`hcS>2N4_viZPZ*1c0myhf?DSrx@D%Qsfb-#hI0-D478XkZv-5WW(2i@L$z1YJe|#tBaQs~0_I5w1 z4u*WMg|%HQhthC z8UvT3EC6%&8N?QWB>66vls~lyBmtI;NqSu40 zANcp5L4bc@<8Ik*-MqmXbPqRt&v#dRZhk46)*pHVH?6;X1W?uJ+plXt*`T;`^5>Y# z*^qX<9QrG30Nb%T$SGT#_#FIA&XL&4nS6<@znXN21cUVQKL7v#07*qoM6N<$g7fDw AVgLXD diff --git a/assets/sprites/blocks/liquids/liquid-pump-top.png b/assets/sprites/blocks/liquids/liquid-pump-top.png index 72083caee7bc222f82692081f46951d715c22061..2eee05b2e5582103e112143fc73d04b80ad36e3f 100644 GIT binary patch delta 134 zcmV;10D1qd0iywsB!2;OQb$4nuFf3k00018NklF%G~W3`5a```@`;x`4z` z+k)l410+@wr~&{Oo{v+bo#s=aZmHH#1FY0Z$P?H#{W}ROKq7>_0(JMX04_VgwP(0% oe(VSn&8vbp;2xtS@f8CAUhG0F0NZ(1&;S4c07*qoM6N<$g2)~>j{pDw delta 145 zcmV;C0B--I0j&X$B!3BTNLh0L01FcU01FcV0GgZ_0001ANklK@Pwm2t-lv z{&%*UZZt6|%(UJ7w^t^BMgRZ|=B;x!9mSUmGfQ_4HNdXg3AqEOqE93-b6vzJw#i4G+g6(n~ zeg_>o+Nn@FRiPDxLi-W?5d8=aLczs$62Zxi4!!SCt5#Sjj9k_xRPl?!IgYXco{I^6u@T; zC28C3+{9FjnyYIx?EG#*n+fi!I3^TRnt`-%jtQM5&B43CIVP+Ic7=0Ii2Iw{^(mMx z^DOuzo&W&CAb+%up`gY5a(yiqvpG~VbyhBKg`3wtIdo>?5$MIm7tS?d7O;&ykXyxU zxUUJSgp;S>FLkhOfVqiWcPGvGz2AWi1GQ$$d921!l&UWbLe!cqw*h?s*TgnB#Q*^L z@i~QRu8A(7FI-7yChh>Y43DG83HK?-dw&=FpSNM5RC>w8gb!S2NeZ6U1ZU-nDQ$4B zi8TKS3#E!*C8QGNR&k^)2800000NkvXXu0mjf DrNQpv delta 581 zcmV-L0=oU11l|OYB!3BTNLh0L01FcU01FcV0GgZ_0006INklZu}T9$5QhIf zLJI99g4%?`R|f<{vpP#7Jn8?Vti}&1OQNPR1J*> z5}cke3(;JZkubm)W@SRkL0QHHm(=NX0RY9xNL>G#D+2%;hjo>?dZTKLFWicouy8A_ z36%j32Y^ZxC64bOA5(iYCIVNr`@mf>>0GKo|Khg@T_&{fJSHqN;DNkw9}|=n@Xh~$ z`1Jb(UPczJzuCJM`8!bByCGEHdO zmogKNKpK^r5$glz470hm9zTN8>IMM$kA!cVO@n_tKg2Qhuc3AfXTiB*1NQ3wYeEC3 ztU!Y2HQ{sRmKnI=00000NkvXXu0mjf4SfQ2 From 5af549eca2be29671dd9e5086dd73b159546f5dd Mon Sep 17 00:00:00 2001 From: = Date: Tue, 14 Jan 2025 17:00:35 -0300 Subject: [PATCH 40/67] some fixes --- .../blocks/liquid/PressureLiquidGauge.java | 10 +++++++++- .../blocks/liquid/PressureLiquidPump.java | 7 ++----- .../blocks/sandbox/PressureLiquidSource.java | 19 ++++++++++++++++++- 3 files changed, 29 insertions(+), 7 deletions(-) diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidGauge.java b/src/omaloon/world/blocks/liquid/PressureLiquidGauge.java index 0384688e..6db247cf 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidGauge.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidGauge.java @@ -116,7 +116,15 @@ public void draw() { pressure().getPressure(pressure().getMain()) > 0 ? maxColor : minColor, Math.abs(p) ); - Draw.rect(gaugeRegion, x, y, (rotdeg() + 90) % 180 - 90 + (Math.abs(p) > 1 ? Mathf.randomSeed((long) Time.time, -360f, 360f) : p * 180f)); + Draw.rect(gaugeRegion, + x, + y, + (rotdeg() + 90) % 180 - 90 + ( + pressure().getPressure(pressure().getMain()) > pressureConfig.maxPressure + 1 || + pressure().getPressure(pressure().getMain()) < pressureConfig.minPressure - 1 + ? Mathf.randomSeed((long) Time.time, -360f, 360f) : p * 180f + ) + ); } @Override diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidPump.java b/src/omaloon/world/blocks/liquid/PressureLiquidPump.java index 563833a3..91944109 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidPump.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidPump.java @@ -213,12 +213,9 @@ public void draw() { public float pumpEfficiency() { float a = 0; for(int i = 0; i < chainSize(); i++) { - a += pressureDifference * Mathf.pow(efficiencyScale, i); + a += pressureDifference; } - return a * ((pressureDifference)/((getFrom() == null ? pressureDifference : Math.max( - pressureDifference, - Math.abs(getFrom().pressure().getPressure(configurable ? Vars.content.liquid(filter) : getFrom().pressure().getMain())) - )))); + return a; } /** diff --git a/src/omaloon/world/blocks/sandbox/PressureLiquidSource.java b/src/omaloon/world/blocks/sandbox/PressureLiquidSource.java index 95a8a056..bbea7edb 100644 --- a/src/omaloon/world/blocks/sandbox/PressureLiquidSource.java +++ b/src/omaloon/world/blocks/sandbox/PressureLiquidSource.java @@ -36,6 +36,13 @@ public PressureLiquidSource(String name) { config(SourceEntry.class, (PressureLiquidSourceBuild build, SourceEntry entry) -> { build.liquid = entry.fluid == null ? -1 : entry.fluid.id; build.targetAmount = entry.amount; + + Vars.content.liquids().each(liquid -> { + build.pressure.liquids[liquid.id] = 0; + build.pressure.pressures[liquid.id] = 0; + }); + + build.pressure.air = build.pressure.pressure = 0; }); } @@ -76,6 +83,11 @@ public class PressureLiquidSourceBuild extends Building implements HasPressure { public int liquid = -1; public float targetAmount; + @Override + public boolean acceptsPressurizedFluid(HasPressure from, Liquid liquid, float amount) { + return HasPressure.super.acceptsPressurizedFluid(from, liquid, amount) && liquid == Vars.content.liquid(this.liquid); + } + @Override public void buildConfiguration(Table cont) { cont.table(Styles.black6, table -> { @@ -140,6 +152,11 @@ public void onProximityUpdate() { new PressureSection().mergeFlood(this); } + @Override + public boolean outputsPressurizedFluid(HasPressure to, Liquid liquid, float amount) { + return HasPressure.super.outputsPressurizedFluid(to, liquid, amount) && liquid == Vars.content.liquid(this.liquid); + } + @Override public PressureModule pressure() { return pressure; } @@ -158,7 +175,7 @@ public void read(Reads read, byte revision) { @Override public void updateTile() { - super.updateTile(); + pressure.section.updateTransfer(); float difference = (Vars.content.liquid(liquid) == null ? targetAmount : Mathf.maxZero(targetAmount)) - (Vars.content.liquid(liquid) == null ? pressure.air : pressure.liquids[liquid]); From 808bfee8da6598ebd8407ebdb0664341529b29ba Mon Sep 17 00:00:00 2001 From: = Date: Sun, 19 Jan 2025 18:55:23 -0300 Subject: [PATCH 41/67] gauge resprite again remove fluidCapacity for pump add pressure bar for liquid source --- .../blocks/liquids/liquid-gauge-pointer.png | Bin 211 -> 157 bytes .../blocks/liquids/liquid-gauge-tiles.png | Bin 724 -> 576 bytes assets/sprites/blocks/liquids/liquid-gauge.png | Bin 502 -> 432 bytes .../world/blocks/liquid/PressureLiquidPump.java | 3 +-- .../blocks/sandbox/PressureLiquidSource.java | 11 +++++++++++ 5 files changed, 12 insertions(+), 2 deletions(-) diff --git a/assets/sprites/blocks/liquids/liquid-gauge-pointer.png b/assets/sprites/blocks/liquids/liquid-gauge-pointer.png index b8df1cbfab802b4dbcce9b423e55c6f28e73cd46..8cfa110f9d6a3f758261f8252dcb7544f402dbbb 100644 GIT binary patch delta 107 zcmV-x0F?jJ0i6MmIb=^sL_t(oh3%C|3IHGs#9IIV=kX>e^xz;AA-Q)9bTI;;nRE*! zX$#7EkNMEA*>|a-w*%*U;;B~6dF}a|1|&r N002ovPDHLkV1h%@Da-%> delta 162 zcmbQsc$sm6Wqqrsi(^PcYjT1F>*55Fo~A&90}T^ndiVXy{6F#MZ1ZzUr*$@&ER6Q+ zRQ9;maJq;M2(pchMfNS)qr?mZ&J{hze$_KFQZ0=lcBbh2)v8!F$eiZ1Y|`Rez!Gqj z(cOQp(h9b4D}|GcKY}dn+#h(iIO|J4Dq`8mdQk&tr8LM+Ms|kvx77qLu;`s<00K`} KKbLh*2~7ay2s)Vn diff --git a/assets/sprites/blocks/liquids/liquid-gauge-tiles.png b/assets/sprites/blocks/liquids/liquid-gauge-tiles.png index 1b10b2d84b9c4aa0607e29148af712e0573148c2..afcea6c37646e325c468b450b6e3e67540834608 100644 GIT binary patch delta 531 zcmV+u0_^?N1;7N5IDY~1NklHAN%wT!p-z2V2sL2vO8g#9o| zTtb+f_~ZBCwf)@h!E>K?JFji~v`s>oR^qh~Q%mvKIiY(c0e@=6Yaq>? z1Mmk_{Q(P*gXkG5{y-E!10wlu*dt_i9ljRGAFQ$%aes*H5Mcj6iFoWB_yauP4@fQe z0|0U=fh)*)VzEMDqpri0 zg$z=5rY|#gxEv9jpz&hCtb{o;H{N_xwQWYYWvA`?qmREnU#so1WA2`sz-kKT@cv ztrli})==f7#NJ{k@aRX%azV?7@6uNN)3amEo$&mK0P7aVdBWar8-)beAKv;U-f&d# zU;Krdk3Tn_`Zw=QW5uCNr*-uQZCE`SPcKnep1ZZY;8b7ZvdR4{nN{!dxweG9-G3oz zrR{~bju4(w!&`T5uw1AKTT2zV|=Z0;QbD1*dXYSW#V^}HP@U+@VxxQ}Cs%P%TzAoYwK;|#o zSyROvpKvpIb#R=FWL)ZhQtcmu_JO7vy#uG@8HCi8zq4EHuy-h^R}g>4za(kq{GL1V z2L6q|ng99%iH6_IMGi{OPsPOgw)|%Pwma#-Ir$mf9-S|Q)c!SS9B^_e3cq9a=r{Ax z@WVg&XX_ka*pb5Z=bwXgL4Csmpf&Xe{x<5JEXHr@v)xHw4Rf4bKK*N$s_&40(RbOS z52AI2jNISZ*W8;W{A;(=v_lG^3t#_cUiP^`>%d>eUYpS4e;J#8Gg}(okuRt}V8i;3 z|BE@0V0g!Wg0XXsc5$hx;5+^q@4FPwo@Y(_$FOjJaG~ZOhPeePOIL~JZe{=iPgg&e IbxsLQ0RB@#-Ie%hFL_t(oh1Hikj>0eyhR2c5!Q%$0prG7(MVW@08&E*cL)sf4 zN*c5kqNb#P$~WL~5vT(8cWt^scZBDC`YCaqyWd~g0u12lJjKuV!EZkKD&odNf>f&!&8ZL{NO_t<4V-?h8 z-zflBfXU}#T&_=B$8rG)aVED*B8O`N e>JTBr0RUcpEWkREWyp^J0000>VaT;u2GE)NV(~-4}<~OsM1&0L;VP6D`7z)rvYyfr|tq2S^S0 z==M96$Q@>rrTRRpN*?B!MXB5Gs3K?^mLX?rDZbPQq>?*4-ai-aTZgTv09u6m2VVe+ z6|Rv>h2{hRa(@c~N(vmpfs;zEi76$ZZbSuyLq>v|7aCX!%*ol6SOcuB%G7~hgv_pV z7ihEo=Jv9zJDvjVOQq;&<684YQ;^~~1sXXJ*^E*Ki3T@nS; { + HasPressure build = (HasPressure)entity; + + return new CenterBar( + () -> Core.bundle.get("bar.pressure") + (build.pressure().getPressure(build.pressure().getMain()) < 0 ? "-" : "+") + Strings.autoFixed(Math.abs(build.pressure().getPressure(build.pressure().getMain())), 2), + () -> Color.white, + () -> Mathf.map(build.pressure().getPressure(build.pressure().getMain()), pressureConfig.minPressure, pressureConfig.maxPressure, -1, 1) + ); + }); } public class PressureLiquidSourceBuild extends Building implements HasPressure { From 460fdea2ce800c4fd594e8057e12fdbe1627f45f Mon Sep 17 00:00:00 2001 From: = Date: Sun, 19 Jan 2025 23:18:49 -0300 Subject: [PATCH 42/67] made javelin consume air gauge now shows the liquid (untested) --- .../content/blocks/OlDefenceBlocks.java | 26 +++++++++- .../blocks/liquid/PressureLiquidGauge.java | 52 +++++++++++++++++-- 2 files changed, 73 insertions(+), 5 deletions(-) diff --git a/src/omaloon/content/blocks/OlDefenceBlocks.java b/src/omaloon/content/blocks/OlDefenceBlocks.java index 71c263b7..324cac8d 100644 --- a/src/omaloon/content/blocks/OlDefenceBlocks.java +++ b/src/omaloon/content/blocks/OlDefenceBlocks.java @@ -18,6 +18,7 @@ import omaloon.content.*; import omaloon.world.blocks.defense.*; import omaloon.world.consumers.*; +import omaloon.world.meta.*; import static mindustry.type.ItemStack.*; @@ -257,7 +258,7 @@ public void draw(Bullet b){ }}; }}; - //TODO: 0.2, but let this be sandbox only + //TODO: 0.2, but let this be sandbox only (this needs a massive nerf lmao) javelin = new ConsumeTurret("javelin") {{ requirements(Category.turret, BuildVisibility.sandboxOnly, with()); outlineColor = Color.valueOf("2f2f36"); @@ -288,7 +289,24 @@ public void draw(Bullet b){ }}; shootSound = OlSounds.theShoot; - consumeItem(Items.coal, 1); + consumeItems(with( + Items.coal, 1, + OlItems.carborundum, 3 + )); + consume(new ConsumeFluid(null, 36) {{ + startRange = 1.8f; + endRange = 18f; + + curve = t -> Math.min( + 2f * t, + -2 * t + 2 + ); + + hasOptimalPressure = true; + optimalPressure = 9f; + + efficiencyMultiplier = 2f; + }}); shootType = new BasicBulletType(1.6f, 12f, "omaloon-javelin-missile-outlined"){{ lifetime = 40f; ammoMultiplier = 1f; @@ -369,6 +387,10 @@ public void draw(Bullet b){ }}); }}; }}; + + pressureConfig = new PressureConfig() {{ + fluidCapacity = 20; + }}; }}; //endregion //region walls diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidGauge.java b/src/omaloon/world/blocks/liquid/PressureLiquidGauge.java index 6db247cf..61a37dbe 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidGauge.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidGauge.java @@ -9,6 +9,7 @@ import arc.util.io.*; import mindustry.entities.units.*; import mindustry.gen.*; +import mindustry.graphics.*; import mindustry.type.*; import mindustry.world.*; import omaloon.ui.elements.*; @@ -16,13 +17,19 @@ import omaloon.world.meta.*; import omaloon.world.modules.*; +import static mindustry.Vars.*; +import static mindustry.type.Liquid.*; + public class PressureLiquidGauge extends Block { public PressureConfig pressureConfig = new PressureConfig(); public Color maxColor = Color.white, minColor = Color.white; + public TextureRegion[][] liquidRegions; public TextureRegion[] tileRegions; - public TextureRegion gaugeRegion; + public TextureRegion bottomRegion, gaugeRegion; + + public float liquidPadding = 3f; public PressureLiquidGauge(String name) { super(name); @@ -52,7 +59,7 @@ public void drawPlanRegion(BuildPlan plan, Eachable list) { @Override public TextureRegion[] icons() { - return new TextureRegion[]{region}; + return new TextureRegion[]{bottomRegion, region}; } @Override @@ -66,7 +73,28 @@ public void init() { public void load() { super.load(); tileRegions = Core.atlas.find(name + "-tiles").split(32, 32)[0]; - gaugeRegion = Core.atlas.find(name + "-pointer"); + gaugeRegion = Core.atlas.find(name + "-pointer");; + bottomRegion = Core.atlas.find(name + "-bottom", "omaloon-liquid-bottom"); + + liquidRegions = new TextureRegion[2][animationFrames]; + if(renderer != null){ + var frames = renderer.getFluidFrames(); + + for (int fluid = 0; fluid < 2; fluid++) { + for (int frame = 0; frame < animationFrames; frame++) { + TextureRegion base = frames[fluid][frame]; + TextureRegion result = new TextureRegion(); + result.set(base); + + result.setHeight(result.height - liquidPadding); + result.setWidth(result.width - liquidPadding); + result.setX(result.getX() + liquidPadding); + result.setY(result.getY() + liquidPadding); + + liquidRegions[fluid][frame] = result; + } + } + } } @Override @@ -94,6 +122,7 @@ public class PressureLiquidGaugeBuild extends Building implements HasPressure { PressureModule pressure = new PressureModule(); public int tiling; + public float smoothAlpha; @Override public boolean acceptsPressurizedFluid(HasPressure from, @Nullable Liquid liquid, float amount) { @@ -109,7 +138,22 @@ public boolean connects(HasPressure to) { @Override public void draw() { + Draw.rect(bottomRegion, x, y); + Liquid main = pressure.getMain(); + + smoothAlpha = Mathf.approachDelta(smoothAlpha, main == null ? 0f : pressure.liquids[main.id]/(pressure.liquids[main.id] + pressure.air), PressureModule.smoothingSpeed); + + if (smoothAlpha > 0.001f) { + int frame = pressure.current.getAnimationFrame(); + int gas = pressure.current.gas ? 1 : 0; + + float xscl = Draw.xscl, yscl = Draw.yscl; + Draw.scl(1f, 1f); + Drawf.liquid(liquidRegions[gas][frame], x, y, Mathf.clamp(smoothAlpha), pressure.current.color.write(Tmp.c1).a(1f)); + Draw.scl(xscl, yscl); + } Draw.rect(tileRegions[tiling], x, y, tiling == 0 ? 0 : (rotdeg() + 90) % 180 - 90); + float p = Mathf.map(pressure().getPressure(pressure().getMain()), pressureConfig.minPressure, pressureConfig.maxPressure, -1, 1); Draw.color( Color.white, @@ -155,6 +199,7 @@ public boolean outputsPressurizedFluid(HasPressure to, Liquid liquid, float amou public void read(Reads read, byte revision) { super.read(read, revision); pressure.read(read); + smoothAlpha = read.f(); } @Override @@ -166,6 +211,7 @@ public void updateTile() { public void write(Writes write) { super.write(write); pressure.write(write); + write.f(smoothAlpha); } } } From 3ec76f2dd5b4c4c5d9d0d23d624fb2b88c226568 Mon Sep 17 00:00:00 2001 From: = Date: Mon, 20 Jan 2025 22:02:56 -0300 Subject: [PATCH 43/67] pump blows up earlier --- assets/bundles/bundle.properties | 1 + .../content/blocks/OlDistributionBlocks.java | 12 ++- src/omaloon/math/OlMath.java | 15 ++-- src/omaloon/ui/dialogs/EventHints.java | 6 ++ .../blocks/liquid/PressureLiquidGauge.java | 1 + .../blocks/liquid/PressureLiquidPump.java | 73 +++++++++++++------ 6 files changed, 80 insertions(+), 28 deletions(-) diff --git a/assets/bundles/bundle.properties b/assets/bundles/bundle.properties index 60685a05..61c39982 100644 --- a/assets/bundles/bundle.properties +++ b/assets/bundles/bundle.properties @@ -62,6 +62,7 @@ requirement.omaloon-at-wave = Reach Wave {0} in {1} ## Hints hint.omaloon-pump_chaining = Pumps chained in series can reach a higher pressure gradient between the ends. If they're chained in parallel, they work faster. +hint.omaloon-pump_min_max_pressure = Pumps can only pump out so much before the pressure starts damaging them. ## planets planet.omaloon-omaloon.name = Omaloon diff --git a/src/omaloon/content/blocks/OlDistributionBlocks.java b/src/omaloon/content/blocks/OlDistributionBlocks.java index 83564ab6..96b03258 100644 --- a/src/omaloon/content/blocks/OlDistributionBlocks.java +++ b/src/omaloon/content/blocks/OlDistributionBlocks.java @@ -2,6 +2,7 @@ import arc.graphics.*; import mindustry.content.*; +import mindustry.gen.*; import mindustry.graphics.*; import mindustry.type.*; import mindustry.world.*; @@ -9,6 +10,7 @@ import omaloon.content.*; import omaloon.world.blocks.distribution.*; import omaloon.world.blocks.liquid.*; +import omaloon.world.meta.*; import static mindustry.type.ItemStack.*; @@ -129,10 +131,18 @@ public static void load() { researchCost = with( OlItems.cobalt, 20 ); - pumpStrength = 0.1f; + pumpStrength = 5f/60f; + + ambientSound = Sounds.wind2; + ambientSoundVolume = 0.1f; pumpEffectIn = OlFx.pumpIn; pumpEffectOut = OlFx.pumpOut; + + pressureConfig = new PressureConfig() {{ + minPressure = -25f; + maxPressure = 25f; + }}; }}; liquidValve = new PressureLiquidValve("liquid-valve") {{ diff --git a/src/omaloon/math/OlMath.java b/src/omaloon/math/OlMath.java index 38267560..3a5fee21 100644 --- a/src/omaloon/math/OlMath.java +++ b/src/omaloon/math/OlMath.java @@ -3,13 +3,16 @@ public class OlMath { /** * Solves for the flow of a fluid through an area based on a difference of pressure. + *

* - * area is in world units squared. - * pressureStart and pressureEnd are in pascals - * density is in liquid units / world units cubed - * time is in ticks - * - * returns the amount of fluid in liquid units that passes through the area over a certain time. + * returns the amount of fluid in liquid units that flows per tick */ public static float flowRate(float pressureStart, float pressureEnd, float capacityStart, float capacityEnd, float density, float viscosity) { return diff --git a/src/omaloon/ui/dialogs/EventHints.java b/src/omaloon/ui/dialogs/EventHints.java index a475501c..09ec93f5 100644 --- a/src/omaloon/ui/dialogs/EventHints.java +++ b/src/omaloon/ui/dialogs/EventHints.java @@ -12,6 +12,12 @@ public enum EventHints implements Hint { pump_chaining( () -> false, () -> Vars.control.input.block instanceof PressureLiquidPump + ), + pump_max_min_pressure( + () -> false, + () -> + Vars.state.rules.defaultTeam.data().buildings.contains(b -> b instanceof PressureLiquidPump.PressureLiquidPumpBuild) && + Vars.control.input.block instanceof PressureLiquidPump ); final Boolp complete; diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidGauge.java b/src/omaloon/world/blocks/liquid/PressureLiquidGauge.java index 61a37dbe..f760818b 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidGauge.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidGauge.java @@ -53,6 +53,7 @@ public void drawPlanRegion(BuildPlan plan, Eachable list) { if (new Point2(next.x, next.y).equals(back) && next.block.outputsLiquid) tiling.tiling |= inverted ? 1 : 2; }); + Draw.rect(bottomRegion, plan.drawx(), plan.drawy()); Draw.rect(tileRegions[tiling.tiling], plan.drawx(), plan.drawy(), (plan.rotation + 1) * 90f % 180 - 90); Draw.rect(gaugeRegion, plan.drawx(), plan.drawy(), plan.rotation * 90f); } diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidPump.java b/src/omaloon/world/blocks/liquid/PressureLiquidPump.java index 003f12dc..7ff559ca 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidPump.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidPump.java @@ -17,7 +17,9 @@ import mindustry.type.*; import mindustry.world.*; import mindustry.world.blocks.*; +import mindustry.world.meta.*; import omaloon.content.*; +import omaloon.math.*; import omaloon.utils.*; import omaloon.world.interfaces.*; import omaloon.world.meta.*; @@ -30,7 +32,6 @@ public class PressureLiquidPump extends Block { public PressureConfig pressureConfig = new PressureConfig(); public float pumpStrength = 0.1f; - public float efficiencyScale = 0.5f; public float pressureDifference = 10; @@ -121,7 +122,7 @@ public void setStats() { super.setStats(); pressureConfig.addStats(stats); stats.remove(OlStats.fluidCapacity); - stats.add(OlStats.pumpStrength, pumpStrength); + stats.add(OlStats.pumpStrength, pumpStrength, StatUnit.liquidSecond); stats.add(OlStats.pressureGradient, pressureDifference, OlStats.pressureUnit); } @@ -132,12 +133,19 @@ public class PressureLiquidPumpBuild extends Building implements HasPressure { public int tiling; public float smoothAlpha; + public boolean functioning; + public int filter = -1; @Override public boolean acceptsPressurizedFluid(HasPressure from, @Nullable Liquid liquid, float amount) { return false; } + @Override + public float ambientVolume() { + return 1f/chainSize(); + } + @Override public void buildConfiguration(Table table) { ItemSelection.buildTable(table, Vars.content.liquids(), () -> Vars.content.liquid(filter), other -> filter = other == null ? -1 : other.id); @@ -209,14 +217,6 @@ public void draw() { if (tiling == 0) Draw.rect(topRegion, x, y, rotdeg()); } - public float pumpEfficiency() { - float a = 0; - for(int i = 0; i < chainSize(); i++) { - a += pressureDifference; - } - return a; - } - /** * Returns the building at the start of the pump chain. */ @@ -275,9 +275,13 @@ public void read(Reads read, byte revision) { smoothAlpha = read.f(); } + @Override + public boolean shouldAmbientSound() { + return functioning; + } + @Override public void updateTile() { - super.updateTile(); if (efficiency > 0) { HasPressure front = getTo(); HasPressure back = getFrom(); @@ -287,22 +291,43 @@ public void updateTile() { float frontPressure = front == null ? 0 : front.pressure().getPressure(pumpLiquid); float backPressure = back == null ? 0 : back.pressure().getPressure(pumpLiquid); - float flow = pumpStrength/chainSize() * ((backPressure + pumpEfficiency()) - frontPressure) / OlLiquids.getViscosity(pumpLiquid); - - if (effectTimer >= effectInterval && !Mathf.zero(flow, 0.001f)) { - if (flow < 0) { - if (back == null && !(back() instanceof PressureLiquidPumpBuild)) pumpEffectOut.at(x, y, rotdeg() + 180f); - if (front == null && !(front() instanceof PressureLiquidPumpBuild)) pumpEffectIn.at(x, y, rotdeg()); + float maxFlow = OlMath.flowRate( + backPressure + pressureDifference * chainSize(), + frontPressure, + back == null ? 5 : back.pressureConfig().fluidCapacity, + front == null ? 5 : front.pressureConfig().fluidCapacity, + OlLiquids.getDensity(pumpLiquid), + 1 + ); + + if (effectTimer >= effectInterval && !Mathf.zero(maxFlow, 0.001f)) { + if (maxFlow < 0) { + if (back == null && !(back() instanceof PressureLiquidPumpBuild && back().rotation == rotation)) pumpEffectOut.at(x, y, rotdeg() + 180f); + if (front == null && !(front() instanceof PressureLiquidPumpBuild && back().rotation == rotation)) pumpEffectIn.at(x, y, rotdeg()); } else { - if (back == null && !(back() instanceof PressureLiquidPumpBuild)) pumpEffectIn.at(x, y, rotdeg() + 180f); - if (front == null && !(front() instanceof PressureLiquidPumpBuild)) pumpEffectOut.at(x, y, rotdeg()); + if (back == null && !(back() instanceof PressureLiquidPumpBuild && front().rotation == rotation)) pumpEffectIn.at(x, y, rotdeg() + 180f); + if (front == null && !(front() instanceof PressureLiquidPumpBuild && front().rotation == rotation)) pumpEffectOut.at(x, y, rotdeg()); } effectTimer %= 1; } - if (pumpLiquid != null && front != null && back != null) { - flow = Mathf.clamp(flow, -front.pressure().get(pumpLiquid), back.pressure().get(pumpLiquid)); + if (back != null) { + pressure.pressure = back.pressure().getPressure(pumpLiquid); + updatePressure(); } + if (front != null) { + pressure.pressure = front.pressure().getPressure(pumpLiquid); + updatePressure(); + } + pressure.pressure = 0; + + float flow = Mathf.clamp( + (maxFlow > 0 ? pumpStrength : -pumpStrength)/chainSize() * Time.delta, + -Math.abs(maxFlow), + Math.abs(maxFlow) + ); + + functioning = !Mathf.zero(flow, 0.001f); if ( front == null || back == null || @@ -316,6 +341,12 @@ public void updateTile() { } } + @Override + public void updatePressure() { + if (pressure().pressure < pressureConfig().minPressure - 1f) damage(pressureConfig().underPressureDamage); + if (pressure().pressure > pressureConfig().maxPressure + 1f) damage(pressureConfig().overPressureDamage); + } + @Override public void write(Writes write) { super.write(write); From 4122b37a764d4475f79090c14b5d7fa54fe56cbc Mon Sep 17 00:00:00 2001 From: = Date: Mon, 20 Jan 2025 22:55:01 -0300 Subject: [PATCH 44/67] some tweaks --- assets/bundles/bundle.properties | 2 +- .../blocks/liquid/PressureLiquidJunction.java | 2 +- .../blocks/liquid/PressureLiquidPump.java | 10 +++--- src/omaloon/world/meta/PressureSection.java | 31 ++++++++++++++----- 4 files changed, 31 insertions(+), 14 deletions(-) diff --git a/assets/bundles/bundle.properties b/assets/bundles/bundle.properties index 61c39982..ed295b9d 100644 --- a/assets/bundles/bundle.properties +++ b/assets/bundles/bundle.properties @@ -62,7 +62,7 @@ requirement.omaloon-at-wave = Reach Wave {0} in {1} ## Hints hint.omaloon-pump_chaining = Pumps chained in series can reach a higher pressure gradient between the ends. If they're chained in parallel, they work faster. -hint.omaloon-pump_min_max_pressure = Pumps can only pump out so much before the pressure starts damaging them. +hint.omaloon-pump_max_min_pressure = Pumps can only pump out so much before the pressure starts damaging them. ## planets planet.omaloon-omaloon.name = Omaloon diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidJunction.java b/src/omaloon/world/blocks/liquid/PressureLiquidJunction.java index 1462277a..bdc99927 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidJunction.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidJunction.java @@ -37,7 +37,7 @@ public HasPressure getPressureDestination(HasPressure source, float pressure) { int dir = (source.relativeTo(tile.x, tile.y) + 4) % 4; HasPressure next = nearby(dir) instanceof HasPressure ? (HasPressure) nearby(dir) : null; - if(next == null || !(next.block() instanceof PressureLiquidJunction)){ + if(next == null) { return this; } return next.getPressureDestination(this, pressure); diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidPump.java b/src/omaloon/world/blocks/liquid/PressureLiquidPump.java index 7ff559ca..47a7edf8 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidPump.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidPump.java @@ -122,7 +122,7 @@ public void setStats() { super.setStats(); pressureConfig.addStats(stats); stats.remove(OlStats.fluidCapacity); - stats.add(OlStats.pumpStrength, pumpStrength, StatUnit.liquidSecond); + stats.add(OlStats.pumpStrength, pumpStrength * 60f, StatUnit.liquidSecond); stats.add(OlStats.pressureGradient, pressureDifference, OlStats.pressureUnit); } @@ -302,11 +302,11 @@ public void updateTile() { if (effectTimer >= effectInterval && !Mathf.zero(maxFlow, 0.001f)) { if (maxFlow < 0) { - if (back == null && !(back() instanceof PressureLiquidPumpBuild && back().rotation == rotation)) pumpEffectOut.at(x, y, rotdeg() + 180f); - if (front == null && !(front() instanceof PressureLiquidPumpBuild && back().rotation == rotation)) pumpEffectIn.at(x, y, rotdeg()); + if (back == null && !(back() instanceof PressureLiquidPumpBuild p && p.rotation == rotation)) pumpEffectOut.at(x, y, rotdeg() + 180f); + if (front == null && !(front() instanceof PressureLiquidPumpBuild p && p.rotation == rotation)) pumpEffectIn.at(x, y, rotdeg()); } else { - if (back == null && !(back() instanceof PressureLiquidPumpBuild && front().rotation == rotation)) pumpEffectIn.at(x, y, rotdeg() + 180f); - if (front == null && !(front() instanceof PressureLiquidPumpBuild && front().rotation == rotation)) pumpEffectOut.at(x, y, rotdeg()); + if (back == null && !(back() instanceof PressureLiquidPumpBuild p && p.rotation == rotation)) pumpEffectIn.at(x, y, rotdeg() + 180f); + if (front == null && !(front() instanceof PressureLiquidPumpBuild p && p.rotation == rotation)) pumpEffectOut.at(x, y, rotdeg()); } effectTimer %= 1; } diff --git a/src/omaloon/world/meta/PressureSection.java b/src/omaloon/world/meta/PressureSection.java index 1f213873..dfbbdda9 100644 --- a/src/omaloon/world/meta/PressureSection.java +++ b/src/omaloon/world/meta/PressureSection.java @@ -131,12 +131,20 @@ public void updateTransfer() { } } for (Entry entry : links) { + float maxFlow = OlMath.flowRate( + entry.value.pressure().getPressure(main), + entry.key.pressure().getPressure(main), + entry.value.pressureConfig().fluidCapacity, + entry.key.pressureConfig().fluidCapacity, + OlLiquids.getDensity(main), + 0 + ) / (2f * links.size); + float flow = Mathf.clamp( - amounts.get(links.indexOf(entry)), - -Math.abs(entry.key.pressure().get(main) - entry.value.pressure().get(main))/2f, - Math.abs(entry.key.pressure().get(main) - entry.value.pressure().get(main))/2f + amounts.get(links.indexOf(entry)) * Time.delta, + -Math.abs(maxFlow), + Math.abs(maxFlow) ); -// float flow = amounts.get(links.indexOf(entry)); if (flow != 0) { entry.key.addFluid(main, flow); entry.value.removeFluid(main, flow); @@ -172,10 +180,19 @@ public void updateTransfer() { } } for (Entry entry : links) { + float maxFlow = OlMath.flowRate( + entry.value.pressure().getPressure(null), + entry.key.pressure().getPressure(null), + entry.value.pressureConfig().fluidCapacity, + entry.key.pressureConfig().fluidCapacity, + OlLiquids.getDensity(null), + 0 + ) / (2f * links.size); + float flow = Mathf.clamp( - amounts.get(links.indexOf(entry)), - -Math.abs(entry.key.pressure().get(null) - entry.value.pressure().get(null))/2f, - Math.abs(entry.key.pressure().get(null) - entry.value.pressure().get(null))/2f + amounts.get(links.indexOf(entry)) * Time.delta, + -Math.abs(maxFlow), + Math.abs(maxFlow) ); if (flow != 0) { entry.key.addFluid(null, amounts.get(links.indexOf(entry))); From 453021595134fd0a02df95f522c9a4bfae7979ec Mon Sep 17 00:00:00 2001 From: = Date: Tue, 21 Jan 2025 19:48:54 -0300 Subject: [PATCH 45/67] filter pump (untested config thingy) --- assets/bundles/bundle.properties | 3 ++ .../blocks/liquids/filter-pump-arrow.png | Bin 0 -> 179 bytes .../blocks/liquids/filter-pump-filter.png | Bin 0 -> 220 bytes .../blocks/liquids/filter-pump-tiles.png | Bin 0 -> 1100 bytes .../blocks/liquids/filter-pump-top.png | Bin 0 -> 163 bytes assets/sprites/blocks/liquids/filter-pump.png | Bin 0 -> 546 bytes .../content/blocks/OlDistributionBlocks.java | 21 ++++++++- .../blocks/liquid/PressureLiquidPump.java | 43 ++++++++++++------ 8 files changed, 53 insertions(+), 14 deletions(-) create mode 100644 assets/sprites/blocks/liquids/filter-pump-arrow.png create mode 100644 assets/sprites/blocks/liquids/filter-pump-filter.png create mode 100644 assets/sprites/blocks/liquids/filter-pump-tiles.png create mode 100644 assets/sprites/blocks/liquids/filter-pump-top.png create mode 100644 assets/sprites/blocks/liquids/filter-pump.png diff --git a/assets/bundles/bundle.properties b/assets/bundles/bundle.properties index ed295b9d..b3086382 100644 --- a/assets/bundles/bundle.properties +++ b/assets/bundles/bundle.properties @@ -262,6 +262,9 @@ block.omaloon-liquid-tube.description = Moves liquids. block.omaloon-liquid-pump.name = Mechanical Pump block.omaloon-liquid-pump.description = Moves liquids forward. +block.omaloon-filter-pump.name = Filter +block.omaloon-filter-pump.description = Moves liquids forward. Liquid can be choosen manually + block.omaloon-liquid-junction.name = Liquid Junction block.omaloon-liquid-junction.description = Acts as a bridge for two crossing liquid tubes. diff --git a/assets/sprites/blocks/liquids/filter-pump-arrow.png b/assets/sprites/blocks/liquids/filter-pump-arrow.png new file mode 100644 index 0000000000000000000000000000000000000000..9fa9e34ae3825962b60afd17c241c0bbaa4cdc90 GIT binary patch literal 179 zcmeAS@N?(olHy`uVBq!ia0vp^3LwnE1|*BCs=fdz&H|6fVg?3oVGw3ym^DWND46Q$ z;usRq`gV#V-vI>AMA8JCXu5d}Utnz-_xxBI| zv|`%vIR#=5?rOc_w9oz~@Q$nOTg9WB?;J$mF@!#S{bzfNIiEOZ$%0)y!Fe@D85lk= Y#l(bvu;~jl0$Rx6>FVdQ&MBb@0N@`#jsO4v literal 0 HcmV?d00001 diff --git a/assets/sprites/blocks/liquids/filter-pump-filter.png b/assets/sprites/blocks/liquids/filter-pump-filter.png new file mode 100644 index 0000000000000000000000000000000000000000..f45278034a6e4c10e8e96b0ceb817d8dfabf15e0 GIT binary patch literal 220 zcmeAS@N?(olHy`uVBq!ia0vp^3LwnE1|*BCs=fdz&H|6fVg?3oVGw3ym^DWNDA?!e z;usRq`gZz8-Ub66mfWyL)ddSv1lSyT4k>769uhL>UMYN&agB&bee9Ya|JRxrPHybz z2;1LxI7?A!(YE(jt&BH^!X}92kxsA@G3h)T_pvuOJ3G5?ckeX$AQ1L;=bLY4 zvTt|pr2@fz@8bvny35D(BLKknPe0gkgF6pzv*U*!9svN>)*n~W`rQ0ll+thXmg1*q zxts|Nm;~FFOK>UvoNF|;B>g4$De3~?982K@XM^J^$zNivWTRve_-s@m4)qT90RX!j z^X%u(-dzF!)}O4YoHN^DYW}58rygrBv{k;iFgzdDzn=^SD*h1tKJ7XA0l@2kfeF3= zb;6JvggB9dKSdF6!PoMq&|iXoPBV!H9{^4-x@2U0PVZnpSrNqWp9}_d5e(0V!9^ei zU&G&2e<}W!>$GVbqTmd3W87LB-Q{EFX*UJG9XLCnKKO#4QvWph0ie44_HqR9hXrl$ zW7bgdDfoR?%$-+nRFAvu=bNglDu+=0uixHH#vh}P#3bJ}huY#QzbU^@Jm3$k zc8AcpW8x6lH2L-#YD;r4 z$(ekErdLCo+qE5Q^~d@WqnqO#+W|s@KRh3bhpW)Pgc8Y5jT}2cNz6&TW&18oVJBX? zW-WC(6DL_;KU>2;3&}T-c7i7QOJHmVu$v3o z=JEdPqH}?iXx~oo^xm1*As>GVg!BYb!KHs1zSx}XE#Mkg2i{gNJ+w$$bIklu{#gd+ zYg7HXalHdvaZKz0rx#tc7u?S#`%4z?GZ)$mZJb`T@!-ax=#Y;;1tdRn!KHs1zSx{& zJAnNSlhmN#oc1N3LQw-3gq9B9MIeCpv+2fa_OteQh6N#fS2*tZt2t`g=i*A=eq^sJ|Ct zCQ0&bUqbjPcSsCu&i~@uz>u9ldM7~pzJQN2R=<{?f-w@dH4m z`ODE5&UxU8<&R0eL1+?E>o3KxDgcgvHZhD!K_){dGuC;BZ)IUvr;O~D10q%p1c}^SLx_?tNNShn3=Q|Z&nqQ0D`h7ca zZvFMATs2bi7;rW?u9EyE)=D|aRZ2bXG)>`p` SbvUm80000Ac&5+<~Qi9upsfAHeD&w>}`t-Kb%yylAM3E>;2 zf2}#S9h6%3GL?Sc$e?F^U~Br0?7BA`!e>`EnLm(QtnyKmnIZ0tlMch}%CHMSix@mz L{an^LB{Ts5pX54_ literal 0 HcmV?d00001 diff --git a/assets/sprites/blocks/liquids/filter-pump.png b/assets/sprites/blocks/liquids/filter-pump.png new file mode 100644 index 0000000000000000000000000000000000000000..8bd6b2c23630aef464f40d61da51c8d11578060a GIT binary patch literal 546 zcmV+-0^R+IP)`|P3@kiA)R_q($_5NzxVUG>cEX>NDm8cZ{XSclvm>C{Fu8dH zfVe%=LjZt>+eg-~Z0BH`^-r#k005nCOHjY$;B-P2Msra{PJkY$N(7gKvV;lFSuz>| z0Q$W;8$Z8#0RVJQJ5J&{-Ifr(aAmp(1y|-Oq80)NfW<1-Joz!nXy_zDnyTFf=Mr;1 zZZ5UBJ^Ls^lL%LMhzP}$x+4_sBZ9J|KDZ3rM}$#8S-7tVSv0@~&z2doWmZZ=&DPrw zn@ua6{*M}wF~>Yjb3V$fUfy5nKyr--6$?!d9#ojcs>A z#{c;atO;1GVq--ESgUB)Sk#D^156V@2l$F8f^!T2kWY8dP(Ry58_*T5j514g!g-on z;VzxeT<)&cs#vRL`U zfzJ;Umt6q9SGm72VdJXFxWcF7f%y7RG>N#}ea$^@?QL3<>J80QU(@kG0OT!D4jVkg kxEz!vO@S)lTrPc~?+<(^b literal 0 HcmV?d00001 diff --git a/src/omaloon/content/blocks/OlDistributionBlocks.java b/src/omaloon/content/blocks/OlDistributionBlocks.java index 96b03258..d6f2a9d4 100644 --- a/src/omaloon/content/blocks/OlDistributionBlocks.java +++ b/src/omaloon/content/blocks/OlDistributionBlocks.java @@ -20,7 +20,7 @@ public class OlDistributionBlocks { tubeConveyor, tubeDistributor, tubeJunction, tubeSorter, tubeGate, tubeBridge, //liquid - liquidTube, liquidJunction, liquidBridge, liquidPump, liquidValve, liquidGauge, + liquidTube, liquidJunction, liquidBridge, liquidPump, filterPump, liquidValve, liquidGauge, end; @@ -145,6 +145,25 @@ public static void load() { }}; }}; + filterPump = new PressureLiquidPump("filter-pump") {{ + requirements(Category.liquid, with( + OlItems.cobalt, 4 + )); + researchCost = with( + OlItems.cobalt, 20 + ); + pumpStrength = 1f/6f; + pressureDifference = 1; + + configurable = true; + + ambientSound = Sounds.wind2; + ambientSoundVolume = 0.1f; + + pumpEffectIn = OlFx.pumpIn; + pumpEffectOut = OlFx.pumpOut; + }}; + liquidValve = new PressureLiquidValve("liquid-valve") {{ requirements(Category.liquid, with( OlItems.cobalt, 2, diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidPump.java b/src/omaloon/world/blocks/liquid/PressureLiquidPump.java index 47a7edf8..0d2f1084 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidPump.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidPump.java @@ -43,7 +43,7 @@ public class PressureLiquidPump extends Block { public TextureRegion[][] liquidRegions; public TextureRegion[] tiles; - public TextureRegion arrowRegion, topRegion, bottomRegion; + public TextureRegion arrowRegion, topRegion, bottomRegion, filterRegion; public PressureLiquidPump(String name) { super(name); @@ -51,7 +51,9 @@ public PressureLiquidPump(String name) { destructible = true; update = true; saveConfig = copyConfig = true; - config(Liquid.class, (PressureLiquidPumpBuild build, Liquid liquid) -> build.filter = liquid.id); + config(Liquid.class, (PressureLiquidPumpBuild build, Liquid liquid) -> { + build.filter = liquid == null ? -1 : liquid.id; + }); } @Override @@ -94,6 +96,7 @@ public void load() { tiles = OlUtils.split(name + "-tiles", 32, 0); arrowRegion = Core.atlas.find(name + "-arrow"); topRegion = Core.atlas.find(name + "-top"); + filterRegion = Core.atlas.find(name + "-filter"); bottomRegion = Core.atlas.find(name + "-bottom", "omaloon-liquid-bottom"); liquidRegions = new TextureRegion[2][animationFrames]; @@ -158,6 +161,11 @@ public int chainSize() { return pressure.section.builds.size; } + @Override + public Liquid config() { + return content.liquid(filter); + } + @Override public boolean connects(HasPressure to) { return HasPressure.super.connects(to) && (front() == to || back() == to) && (!(to instanceof PressureLiquidPumpBuild) || to.rotation() == rotation); } @@ -214,6 +222,11 @@ public void draw() { Draw.rect(arrowRegion, x, y, rotdeg()); } Draw.rect(tiles[tiling], x, y, rot); + if (filterRegion.found() && configurable && content.liquid(filter) != null) { + Draw.color(content.liquid(filter).color); + Draw.rect(filterRegion, x, y, rot); + Draw.color(); + } if (tiling == 0) Draw.rect(topRegion, x, y, rotdeg()); } @@ -300,17 +313,6 @@ public void updateTile() { 1 ); - if (effectTimer >= effectInterval && !Mathf.zero(maxFlow, 0.001f)) { - if (maxFlow < 0) { - if (back == null && !(back() instanceof PressureLiquidPumpBuild p && p.rotation == rotation)) pumpEffectOut.at(x, y, rotdeg() + 180f); - if (front == null && !(front() instanceof PressureLiquidPumpBuild p && p.rotation == rotation)) pumpEffectIn.at(x, y, rotdeg()); - } else { - if (back == null && !(back() instanceof PressureLiquidPumpBuild p && p.rotation == rotation)) pumpEffectIn.at(x, y, rotdeg() + 180f); - if (front == null && !(front() instanceof PressureLiquidPumpBuild p && p.rotation == rotation)) pumpEffectOut.at(x, y, rotdeg()); - } - effectTimer %= 1; - } - if (back != null) { pressure.pressure = back.pressure().getPressure(pumpLiquid); updatePressure(); @@ -327,6 +329,21 @@ public void updateTile() { Math.abs(maxFlow) ); + if (effectTimer >= effectInterval && !Mathf.zero(flow, 0.001f)) { + if (flow < 0) { + if (pumpLiquid == null || (front != null && front.pressure().get(pumpLiquid) > 0.001f)) { + if (back == null && !(back() instanceof PressureLiquidPumpBuild p && p.rotation == rotation)) pumpEffectOut.at(x, y, rotdeg() + 180f, pumpLiquid == null ? Color.white : pumpLiquid.color); + if (front == null && !(front() instanceof PressureLiquidPumpBuild p && p.rotation == rotation)) pumpEffectIn.at(x, y, rotdeg(), pumpLiquid == null ? Color.white : pumpLiquid.color); + } + } else { + if (pumpLiquid == null || (back != null && back.pressure().get(pumpLiquid) > 0.001f)) { + if (back == null && !(back() instanceof PressureLiquidPumpBuild p && p.rotation == rotation)) pumpEffectIn.at(x, y, rotdeg() + 180f, pumpLiquid == null ? Color.white : pumpLiquid.color); + if (front == null && !(front() instanceof PressureLiquidPumpBuild p && p.rotation == rotation)) pumpEffectOut.at(x, y, rotdeg(), pumpLiquid == null ? Color.white : pumpLiquid.color); + } + } + effectTimer %= 1; + } + functioning = !Mathf.zero(flow, 0.001f); if ( From d5d9fdb72fbad08276d732a64a636921674b6366 Mon Sep 17 00:00:00 2001 From: = Date: Wed, 22 Jan 2025 12:45:59 -0300 Subject: [PATCH 46/67] change settings to a proper place (cherry picked from commit 90bdf715c608a3319cefe73eeebb8f032a3089d0) --- assets/bundles/bundle.properties | 5 +- src/omaloon/OmaloonMod.java | 2 + src/omaloon/core/OlSettings.java | 39 ++++---- src/omaloon/ui/StartSplash.java | 4 +- .../ui/dialogs/OlDisclaimerDialog.java | 4 +- src/omaloon/ui/dialogs/OlGameDialog.java | 89 +++++++++++++++++++ src/omaloon/world/blocks/defense/Shelter.java | 4 +- 7 files changed, 123 insertions(+), 24 deletions(-) create mode 100644 src/omaloon/ui/dialogs/OlGameDialog.java diff --git a/assets/bundles/bundle.properties b/assets/bundles/bundle.properties index b3086382..b19a01d0 100644 --- a/assets/bundles/bundle.properties +++ b/assets/bundles/bundle.properties @@ -40,14 +40,15 @@ ui.omaloon-exit-dialog.mobile = [gray]Tap to exit ## settings settings.omaloon = Omaloon Settings +settings.omaloon-moddata = Omaloon Data + setting.omaloon-check-updates = Check for Updates setting.omaloon-shield-opacity = Shelter Opacity setting.omaloon-show-disclaimer = Hide Disclaimer setting.omaloon-discord-join = Join Omaloon discord server! -setting.omaloon-enable-soft-cleaner.name = Enable Safe Cleaner +setting.omaloon-enable-soft-cleaner = Enable Safe Cleaner setting.omaloon-enable-soft-cleaner.description = Cleans your campaign from not allowed content and research. -settings.omaloon-moddata = Omaloon Data binding.category-omaloon-editor = Editor settings.omaloon-resethints = Reset Hints diff --git a/src/omaloon/OmaloonMod.java b/src/omaloon/OmaloonMod.java index 8b1d3c58..8d7a0e9e 100644 --- a/src/omaloon/OmaloonMod.java +++ b/src/omaloon/OmaloonMod.java @@ -29,6 +29,7 @@ public class OmaloonMod extends Mod{ public static OlInputDialog olInputDialog; public static OlGameDataDialog olGameDataDialog; + public static OlGameDialog olGameDialog; public static OlEndDialog olEndDialog; /** @@ -93,6 +94,7 @@ public void init() { cliffFragment = new CliffFragment(); olInputDialog = new OlInputDialog(); olGameDataDialog = new OlGameDataDialog(); + olGameDialog = new OlGameDialog(); olEndDialog = new OlEndDialog(); Events.on(EventType.SectorCaptureEvent.class, e -> { if (e.sector.preset == OlSectorPresets.deadValley) olEndDialog.show(Core.scene, Actions.sequence( diff --git a/src/omaloon/core/OlSettings.java b/src/omaloon/core/OlSettings.java index b5917077..ce87ba50 100644 --- a/src/omaloon/core/OlSettings.java +++ b/src/omaloon/core/OlSettings.java @@ -18,8 +18,8 @@ public class OlSettings{ public static void load(){ //add omaloon settings ui.settings.addCategory("@settings.omaloon", OlIcons.settings, table -> { - if(!mobile || Core.settings.getBool("keyboard")) { - table.pref(new TableSetting("category", new Table(Tex.button, cat -> { + table.table(Tex.button, cat -> { + if(!mobile || Core.settings.getBool("keyboard")) { cat.button( "@settings.controls", Icon.move, @@ -27,20 +27,27 @@ public static void load(){ iconMed, () -> OmaloonMod.olInputDialog.show() ).growX().marginLeft(8f).height(50f).row(); - cat.button( - "@settings.omaloon-moddata", - Icon.save, - Styles.flatt, - iconMed, - () -> OmaloonMod.olGameDataDialog.show() - ).growX().marginLeft(8f).height(50f).row(); - }))); - } - table.sliderPref("@setting.omaloon-shield-opacity", 20, 0, 100, s -> s + "%"); - //checks - table.checkPref("@setting.omaloon-show-disclaimer", false); - table.checkPref("omaloon-enable-soft-cleaner", true); - table.checkPref("@setting.omaloon-check-updates", true); + } + cat.button( + "@settings.game", + Icon.settings, + Styles.flatt, + iconMed, + () -> OmaloonMod.olGameDialog.show() + ).growX().marginLeft(8f).height(50f).row(); + cat.button( + "@settings.omaloon-moddata", + Icon.save, + Styles.flatt, + iconMed, + () -> OmaloonMod.olGameDataDialog.show() + ).growX().marginLeft(8f).height(50f).row(); + }).width(Math.min(Core.graphics.getWidth() / 1.2f, 460.0F)).padBottom(45); +// table.sliderPref("@setting.omaloon-shield-opacity", 20, 0, 100, s -> s + "%"); +// //checks +// table.checkPref("@setting.omaloon-show-disclaimer", false); +// table.checkPref("omaloon-enable-soft-cleaner", true); +// table.checkPref("@setting.omaloon-check-updates", true); //discord link table.fill(c -> c diff --git a/src/omaloon/ui/StartSplash.java b/src/omaloon/ui/StartSplash.java index 6e96cc7b..c25f2c67 100644 --- a/src/omaloon/ui/StartSplash.java +++ b/src/omaloon/ui/StartSplash.java @@ -55,11 +55,11 @@ public static void show(){ } private static void onComplete() { - if (!settings.getBool("@setting.omaloon-show-disclaimer")) { + if (!settings.getBool("omaloon-show-disclaimer", false)) { new OlDisclaimerDialog().show(); } - if (settings.getBool("@setting.omaloon-check-updates")) { + if (settings.getBool("omaloon-check-updates", true)) { OlUpdateCheckerDialog.check(); } diff --git a/src/omaloon/ui/dialogs/OlDisclaimerDialog.java b/src/omaloon/ui/dialogs/OlDisclaimerDialog.java index 2651f1c3..821bfe5f 100644 --- a/src/omaloon/ui/dialogs/OlDisclaimerDialog.java +++ b/src/omaloon/ui/dialogs/OlDisclaimerDialog.java @@ -44,7 +44,7 @@ public OlDisclaimerDialog() { TextButton s = buttons.button("@button.omaloon-show-disclaimer", Icon.cancel, () -> { hide(); - Core.settings.put("@setting.omaloon-show-disclaimer", true); + Core.settings.put("omaloon-show-disclaimer", true); }).get(); s.setDisabled(() -> @@ -64,6 +64,6 @@ public OlDisclaimerDialog() { } boolean shouldSkip() { - return Core.settings.getBool("@setting.omaloon-show-disclaimer", false); + return Core.settings.getBool("omaloon-show-disclaimer", false); } } diff --git a/src/omaloon/ui/dialogs/OlGameDialog.java b/src/omaloon/ui/dialogs/OlGameDialog.java new file mode 100644 index 00000000..2ba85ac5 --- /dev/null +++ b/src/omaloon/ui/dialogs/OlGameDialog.java @@ -0,0 +1,89 @@ +package omaloon.ui.dialogs; + +import arc.*; +import arc.func.*; +import arc.scene.event.*; +import arc.scene.ui.*; +import arc.scene.ui.layout.*; +import arc.struct.*; +import arc.util.*; +import mindustry.*; +import mindustry.ui.*; +import mindustry.ui.dialogs.*; + +public class OlGameDialog extends BaseDialog { + public final ObjectMap settings = new ObjectMap<>(); + + public OlGameDialog() { + super("@settings.game"); + + addCloseButton(); + + rebuild(); + } + + public void addCheck(String name, @Nullable String description, String setting, boolean def, Boolc cons) { + CheckBox box = new CheckBox(name); + box.update(() -> box.setChecked(Core.settings.getBool(setting, def))); + box.changed(() -> { + Core.settings.put(setting, box.isChecked()); + cons.get(box.isChecked()); + }); + box.left(); + cont.add(box).left().padTop(3f).get(); + if (description != null) Vars.ui.addDescTooltip(box, description); + settings.put(setting, def); + cont.row(); + } + + public void addSlider(String name, @Nullable String description, String setting, Slider slider, float def, Func sp) { + slider.setValue(Core.settings.getFloat(setting, def)); + Label value = new Label("", Styles.outlineLabel); + Table content = new Table(); + content.add(name, Styles.outlineLabel).left().growX().wrap(); + content.add(value).padLeft(10f).right(); + content.margin(3f, 33f, 3f, 33f); + content.touchable = Touchable.disabled; + slider.changed(() -> { + Core.settings.put(setting, slider.getValue()); + value.setText(sp.get(slider.getValue())); + }); + slider.change(); + Stack added = cont.stack(slider, content).width(Math.min(Core.graphics.getWidth() / 1.2f, 460f)).left().padTop(4f).get(); + if (description != null) Vars.ui.addDescTooltip(added, description); + settings.put(setting, def); + cont.row(); + } + + public void rebuild() { + cont.clear(); + + addSlider( + "@setting.omaloon-shield-opacity", null, "omaloon-shield-opacity", + new Slider(0, 100, 1, false), 20, + f -> Strings.autoFixed(f, 20) + "%" + ); + + addCheck( + "@setting.omaloon-show-disclaimer", null, "omaloon-show-disclaimer", + false, b -> {} + ); + addCheck( + "@setting.omaloon-enable-soft-cleaner", "@setting.omaloon-enable-soft-cleaner.description", "omaloon-enable-soft-cleaner", + true, b -> {} + ); + addCheck( + "@setting.omaloon-check-updates", null, "omaloon-check-updates", + true, b -> {} + ); + + cont.button("@settings.reset", () -> { + resetToDefaults(); + rebuild(); + }).size(250, 50); + } + + public void resetToDefaults() { + settings.each((name, value) -> Core.settings.put(name, value)); + } +} diff --git a/src/omaloon/world/blocks/defense/Shelter.java b/src/omaloon/world/blocks/defense/Shelter.java index 3026d8ec..2a4e98f6 100644 --- a/src/omaloon/world/blocks/defense/Shelter.java +++ b/src/omaloon/world/blocks/defense/Shelter.java @@ -67,7 +67,7 @@ public class Shelter extends Block { fieldBuffer.begin(Color.clear); buffer.each(Runnable::run); fieldBuffer.end(); - Draw.color(deflectColor, Vars.renderer.animateShields ? 1f : Core.settings.getInt("@setting.omaloon-shield-opacity", 20)/100f); + Draw.color(deflectColor, Vars.renderer.animateShields ? 1f : Core.settings.getFloat("omaloon-shield-opacity", 20f)/100f); EDraw.drawBuffer(fieldBuffer); Draw.flush(); Draw.color(); @@ -178,7 +178,7 @@ public void draw() { Draw.z(Layer.blockOver); float mousex = Core.input.mouseWorldX(), mousey = Core.input.mouseWorldY(); - Draw.color(Pal.accent, Interp.circle.apply(configureWarmup) * Core.settings.getInt("@setting.omaloon-shield-opacity", 20)/100f); + Draw.color(Pal.accent, Interp.circle.apply(configureWarmup) * Core.settings.getFloat("omaloon-shield-opacity", 20f)/100f); Fill.arc(x, y, shieldRange * Interp.circle.apply(configureWarmup), shieldAngle/360f, -shieldAngle/2f + Core.input.mouseWorld().angleTo(x, y) + 180f); for(int i = 0; i < configSerrations; i++) { From 619929a2434775af21b23b501cf1b521d2f00363 Mon Sep 17 00:00:00 2001 From: = Date: Tue, 28 Jan 2025 22:51:05 -0300 Subject: [PATCH 47/67] add setting for custom liquid stats --- assets/bundles/bundle.properties | 4 ++++ src/omaloon/content/OlLiquids.java | 15 ++++++++++++--- src/omaloon/ui/dialogs/OlGameDialog.java | 5 +++++ 3 files changed, 21 insertions(+), 3 deletions(-) diff --git a/assets/bundles/bundle.properties b/assets/bundles/bundle.properties index b19a01d0..9c4487cb 100644 --- a/assets/bundles/bundle.properties +++ b/assets/bundles/bundle.properties @@ -49,6 +49,9 @@ setting.omaloon-discord-join = Join Omaloon discord server! setting.omaloon-enable-soft-cleaner = Enable Safe Cleaner setting.omaloon-enable-soft-cleaner.description = Cleans your campaign from not allowed content and research. +setting.omaloon-display-liquid-stats = Display custom viscosity/density +setting.omaloon-display-liquid-stats.description = [red]NEEDS RELOAD + binding.category-omaloon-editor = Editor settings.omaloon-resethints = Reset Hints @@ -340,6 +343,7 @@ stat.omaloon-fluid-capacity = Fluid Capacity stat.omaloon-fluid-capacity.format = @x@x@ Blocks stat.omaloon-density = Density +stat.omaloon-viscosity = @%, \uC357 @ stat.omaloon-pump-strength = Pump Strength stat.omaloon-pressure-gradient = Pressure Gradient diff --git a/src/omaloon/content/OlLiquids.java b/src/omaloon/content/OlLiquids.java index 7cc040be..3a538d99 100644 --- a/src/omaloon/content/OlLiquids.java +++ b/src/omaloon/content/OlLiquids.java @@ -4,6 +4,7 @@ import arc.struct.*; import arc.util.*; import mindustry.content.*; +import mindustry.game.*; import mindustry.type.*; import mindustry.world.meta.*; import omaloon.type.liquid.*; @@ -56,17 +57,25 @@ public static void load(){ addViscosity(glacium, 13); addDensity(tiredGlacium, 1300); addViscosity(tiredGlacium, 13); + + if (Core.settings.getBool("omaloon-display-liquid-stats", true)) Events.on(EventType.ContentInitEvent.class, e -> { + densities.each(map -> { + map.key.stats.add(OlStats.density, map.value, OlStats.densityUnit); + }); + viscosities.each(map -> { + map.key.checkStats(); + map.key.stats.remove(Stat.viscosity); + map.key.stats.add(Stat.viscosity, Core.bundle.get("stat.omaloon-viscosity"), map.key.viscosity * 100f ,Strings.autoFixed(map.value/60f, 2) + " " + OlStats.viscosityUnit.localized()); + }); + }); } public static void addDensity(Liquid liquid, float density) { densities.put(liquid, density); - liquid.stats.add(OlStats.density, density, OlStats.densityUnit); } public static void addViscosity(Liquid liquid, float viscosity) { viscosities.put(liquid, viscosity); - liquid.stats.remove(Stat.viscosity); - liquid.stats.add(Stat.viscosity, Strings.autoFixed(viscosity/60f, 2), OlStats.viscosityUnit); } public static float getDensity(@Nullable Liquid liquid) { diff --git a/src/omaloon/ui/dialogs/OlGameDialog.java b/src/omaloon/ui/dialogs/OlGameDialog.java index 2ba85ac5..871efbda 100644 --- a/src/omaloon/ui/dialogs/OlGameDialog.java +++ b/src/omaloon/ui/dialogs/OlGameDialog.java @@ -77,6 +77,11 @@ public void rebuild() { true, b -> {} ); + addCheck( + "@setting.omaloon-display-liquid-stats", "@setting.omaloon-display-liquid-stats.description", "omaloon-display-liquid-stats", + true, b -> {} + ); + cont.button("@settings.reset", () -> { resetToDefaults(); rebuild(); From 221e21471bf0127da89236d66cb899270de636e9 Mon Sep 17 00:00:00 2001 From: = Date: Wed, 29 Jan 2025 12:59:01 -0300 Subject: [PATCH 48/67] demo boiler block, it has issues though --- .../blocks/crafting/air-well-cap-from.png | Bin 293 -> 0 bytes .../blocks/crafting/air-well-cap-to.png | Bin 296 -> 0 bytes .../blocks/crafting/air-well-overlay.png | Bin 275 -> 0 bytes assets/sprites/blocks/crafting/air-well.png | Bin 479 -> 0 bytes .../blocks/crafting/glacium-boiler.png | Bin 0 -> 1102 bytes .../content/blocks/OlCraftingBlocks.java | 21 ++++++- .../content/blocks/OlDistributionBlocks.java | 2 +- .../blocks/production/PressureCrafter.java | 58 ++++++++++++++++++ src/omaloon/world/consumers/ConsumeFluid.java | 1 + 9 files changed, 80 insertions(+), 2 deletions(-) delete mode 100644 assets/sprites/blocks/crafting/air-well-cap-from.png delete mode 100644 assets/sprites/blocks/crafting/air-well-cap-to.png delete mode 100644 assets/sprites/blocks/crafting/air-well-overlay.png delete mode 100644 assets/sprites/blocks/crafting/air-well.png create mode 100644 assets/sprites/blocks/crafting/glacium-boiler.png diff --git a/assets/sprites/blocks/crafting/air-well-cap-from.png b/assets/sprites/blocks/crafting/air-well-cap-from.png deleted file mode 100644 index 3607131eded34ffe0718b648f5a381eed0644eef..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 293 zcmeAS@N?(olHy`uVBq!ia0vp^3LwnE1|*BCs=fdz&H|6fVg?3oVGw3ym^DWND0tn| z#W5tJ_3cz$zC#WoE$n(uRh?2QvlI+H4oP}kP?^&RWHq@ZRdxFM2Zc-y`j(#NE&6`) z?#bt-r+wE=kobSjg;PI#x7xPvJgeZ!m$F(j zh6h>g;h`(#uFU6PyY*?>MwLCY|9;wcWRH&hwcsSf&L@&Dg3ffUFJic7D&~3Ms@{(2 z+KQY#jhrXi4P4HNPGxlxT6p`Q1HTg6{SBw2T=q|rFzIUddcz<6%5{m;sv}jK7tBw# nI^m`9bP|K|!fDcNj12j69TV@J{20C%=tTxkS3j3^P6|;&^`NRUr1tC8D!sRwzS|Dj3Vm@gi;jcNrs%S_)IFrj)q$_oHJyLRNz;P z`s{InDS0wW%yfgc=bgL!7I-Utv(j1OcI3jbP0l+XkKuw8L$ diff --git a/assets/sprites/blocks/crafting/air-well-overlay.png b/assets/sprites/blocks/crafting/air-well-overlay.png deleted file mode 100644 index 63b7d6d51e5e68d4534b9c34a8f548b8ea4dfd9a..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 275 zcmeAS@N?(olHy`uVBq!ia0vp^3LwnE1|*BCs=fdz&H|6fVg?3oVGw3ym^DWND0tM< z#W5tJ_3iYHyoU?~T<70anxdua9FWE%mMA8c*fT}4$t*NwY1^p+Gd|8q{+aKte*2q# zvvq&%nuG57=H^Ek~6=;Gkvo#V}r&-{S}H6&z~^Gs5XTLP5#yq)E5d}&Gq7yHGYEh^X2RIchwzpx@LamK{fAFHL^ID50y_$5^1e%nrL UF0>ST3-l0!r>mdKI;Vst0N!tGjQ{`u diff --git a/assets/sprites/blocks/crafting/air-well.png b/assets/sprites/blocks/crafting/air-well.png deleted file mode 100644 index 6baf3053916180f1a975bf1d472fbedcafbb1619..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 479 zcmV<50U-W~P)Bw(q!BQa44v9MH~5JN@RZhS&N zqJO~(Kf%IMKBDT9L~7NMfh7#c!Ex+MD&-Ca-gxo(y*r;BJDH5e#nH(zICh&Yrn5OL ztkx@aeb676d!C;bkURk3(k#brv#pTRhOR)qI8P}607!&1utaDlwN5X6NRH(C;<5mM z^Rv_1=BwL>Mgj{wOz*ERweJ)T*M?j=+=pEA1^nEEYeT+|2+PJ2k=)%s76%{eM)Iz} z!!e!BzeDhO*pEWaIVjB?eIOArz-x^2*hN7_z}s>eoKU87?FK@M&}xYqf)FCCLe{$( z4ug^UK=q=$0TL3EydvPY@Gqbg5c3i8jOfLF{ZfP)f)E*D{ibUILZ+i8q9PzhEs!Gq zP8RU4C^UGd>^QmBy><=aAQ8!AG%lo(uQh8*Ti-j<4(QS>Z)Mnq+-GCW2IXYbv|*ou zC2f6!NjVt-`ha3JtMaNXf!5=$OhyEG6K%<@HO)tw<=_KxtqzcgF57hS#Scg#z5u%z V!)v0F=^p?9002ovPDHLkV1ip*&!YeU diff --git a/assets/sprites/blocks/crafting/glacium-boiler.png b/assets/sprites/blocks/crafting/glacium-boiler.png new file mode 100644 index 0000000000000000000000000000000000000000..363b4c312d40a5975e74d8aa8961913ac0f9dc7d GIT binary patch literal 1102 zcmV-U1hM;xP)Px(2uVaiRCt{2TfJ%-X_-*h{DtQnZ19vxUJgX zit)O6f!*saROoxc7yuwAVfVWGF9|8>HBLXUC3s1QHqi*#oL)x)7PBea(SjNzL?};P zyU+;0PBIDLoaf!*R(v>xo6D=#HOWbr#-o|QlO-TMfcxDSJY&m=8s|485%0M|Dvd@m9} z#RcAhcu3In(UQRV3zC3H+Fz2I?{R|$&@T1Y!}F{QzX<-UMst#qYES|x@w&(wREVyYA47kmZPgB)Kb0#(=MPTL7QH)+|yc*H4afP zfgIc{=T206sFIK?&#iY!`A$n9M~NW3gG3}%@XVJyzBd9Lef|EkWdWL*vnc1a1k3iR z@h|F}U^G0I5c$HE!&wLzGCm0CdjNgogMhvV&^OLPfM**#*Xyhz}>Fx8JbN_U9{ zOW7YP8q@?rR6mymltN)lN<=8EO}cthaOU>{(y@5ctYAJ{vdWhNqf(z_3DUWLd)S*p zVv_}Ea{?aarF&YRV6_A_0TBriPlh>%c6Kc!kjG(7UXXHvU6s$lSrMh6CNHRRg4(1g zZWpP%)CXIFHYrNAJ0ZZD7EkRtyF`LDEsooh`2Y_nlf?>X3C4s` z1XnMRumYPbHG3LMpxS61um>Umi`n$}Cn1qgW57wK^lBd9U#Xm_P?7>xT0=t3*~(>? zNWj-563jJ15(%F7i&{`gS50+jc#TjWB$Q+(5~P_9uMt|zrtDrlpDk71oRaI^Jv``C zDQY?GY2PYY+jgyJ>s%?S8GuD0OP`2xzK}S88;D1FP2Z^3Zk;PdIdoAzQbx5((f5QB z2`vIV%J)%TAN5_s2?0_jr&K4{7fR!?WR}>k#;6CCe)k2>*i2uId1rmotkkJ<+>Zj+ zk1OkymNfg-n0JOf36NScDIHW_jSWfpuCloT@759+!n&>jYH}ynlX@Ra3>}Gtzm*G} U@WKS}kN^Mx07*qoM6N<$f*%|1kpKVy literal 0 HcmV?d00001 diff --git a/src/omaloon/content/blocks/OlCraftingBlocks.java b/src/omaloon/content/blocks/OlCraftingBlocks.java index 56f049ac..caf4323d 100644 --- a/src/omaloon/content/blocks/OlCraftingBlocks.java +++ b/src/omaloon/content/blocks/OlCraftingBlocks.java @@ -3,6 +3,7 @@ import mindustry.content.*; import mindustry.type.*; import mindustry.world.*; +import mindustry.world.meta.*; import omaloon.content.*; import omaloon.world.blocks.production.*; import omaloon.world.consumers.*; @@ -10,7 +11,7 @@ import static mindustry.type.ItemStack.*; public class OlCraftingBlocks { - public static Block carborundumPress, graphitePress; + public static Block carborundumPress, graphitePress, glaciumBoiler; public static void load() { carborundumPress = new PressureCrafter("carborundum-press") {{ @@ -67,5 +68,23 @@ public static void load() { outputItem = new ItemStack(Items.graphite, 2); }}; + + glaciumBoiler = new PressureCrafter("glacium-boiler") {{ + requirements(Category.crafting, BuildVisibility.sandboxOnly, with()); + size = 2; + + useVanillaLiquids = false; + ignoreLiquidFullness = true; + dumpExtraLiquid = true; + + craftTime = 120f; + + consumeItem(Items.coal, 1); + consume(new ConsumeFluid(OlLiquids.glacium, 1f/60f) {{ + continuous = true; + }}); + + outputAir = 4f/6f; + }}; } } diff --git a/src/omaloon/content/blocks/OlDistributionBlocks.java b/src/omaloon/content/blocks/OlDistributionBlocks.java index d6f2a9d4..f76086aa 100644 --- a/src/omaloon/content/blocks/OlDistributionBlocks.java +++ b/src/omaloon/content/blocks/OlDistributionBlocks.java @@ -153,7 +153,7 @@ public static void load() { OlItems.cobalt, 20 ); pumpStrength = 1f/6f; - pressureDifference = 1; + pressureDifference = 0; configurable = true; diff --git a/src/omaloon/world/blocks/production/PressureCrafter.java b/src/omaloon/world/blocks/production/PressureCrafter.java index 9ea63132..c4b5166e 100644 --- a/src/omaloon/world/blocks/production/PressureCrafter.java +++ b/src/omaloon/world/blocks/production/PressureCrafter.java @@ -1,8 +1,11 @@ package omaloon.world.blocks.production; +import arc.util.*; import arc.util.io.*; +import mindustry.type.*; import mindustry.world.blocks.production.*; import mindustry.world.consumers.*; +import mindustry.world.meta.*; import omaloon.world.interfaces.*; import omaloon.world.meta.*; import omaloon.world.modules.*; @@ -12,11 +15,34 @@ public class PressureCrafter extends GenericCrafter { public boolean useConsumerMultiplier = true; + /** + * Set this to false every time you want the outputs to use the pressure liquid system instead. + * Alternatively, creating ConsumeFluids with negative values for it's amount will work too. + */ + public boolean useVanillaLiquids = true; + + /** + * Internal variable used to output pressurized liquids, Do not modify manually. + */ + private @Nullable LiquidStack[] outputPressurizedLiquids; + + public float outputAir; + public PressureCrafter(String name) { super(name); pressureConfig.isWhitelist = true; } + @Override + public void init() { + if (!useVanillaLiquids) { + outputPressurizedLiquids = outputLiquids; + outputLiquids = null; + } + + super.init(); + } + @Override public void setBars() { super.setBars(); @@ -27,6 +53,13 @@ public void setBars() { public void setStats() { super.setStats(); pressureConfig.addStats(stats); + + if(outputPressurizedLiquids != null) { + stats.add(Stat.output, StatValues.liquids(1f, outputPressurizedLiquids)); + } + if (outputAir > 0) { + stats.add(OlStats.addFluid, OlStats.fluid(null, outputAir, 1f, true)); + } } public class PressureCrafterBuild extends GenericCrafterBuild implements HasPressure { @@ -69,9 +102,34 @@ public void read(Reads read, byte revision) { pressure.read(read); } + @Override + public boolean shouldConsume() { + if(outputPressurizedLiquids != null && !ignoreLiquidFullness) { + boolean allFull = true; + if (pressure.get(null) >= pressureConfig.fluidCapacity - 0.001f) { + if (!dumpExtraLiquid) return false; + } else allFull = false; + for(var output : outputPressurizedLiquids) { + if(pressure.get(output.liquid) >= pressureConfig.fluidCapacity - 0.001f) { + if(!dumpExtraLiquid) return false; + } else allFull = false; + } + + //if there is no space left for any liquid, it can't reproduce + if(allFull) return false; + } + return super.shouldConsume(); + } + @Override public void updateTile() { super.updateTile(); + if(efficiency > 0) { + float inc = getProgressIncrease(1f); + if (outputPressurizedLiquids != null) for(var output : outputPressurizedLiquids) addFluid(output.liquid, output.amount * inc); + if (outputAir > 0) addFluid(null, outputAir * inc); + } + updatePressure(); } diff --git a/src/omaloon/world/consumers/ConsumeFluid.java b/src/omaloon/world/consumers/ConsumeFluid.java index 7a559869..6b4acf9f 100644 --- a/src/omaloon/world/consumers/ConsumeFluid.java +++ b/src/omaloon/world/consumers/ConsumeFluid.java @@ -91,6 +91,7 @@ public float efficiencyMultiplier(Building build) { } public boolean shouldConsume(HasPressure build) { + if (fluid != null && amount > 0 && build.pressure().get(fluid) <= amount) return false; if (startRange == endRange) return true; return startRange <= build.pressure().getPressure(fluid) && build.pressure().getPressure(fluid) <= endRange && (fluid == null || build.pressure().liquids[fluid.id] > amount); } From f0fba682c19e6dfa8304fb6989babf86c4a6f743 Mon Sep 17 00:00:00 2001 From: Zelaux <58040045+zelaux@users.noreply.github.com> Date: Thu, 30 Jan 2025 20:09:57 +0300 Subject: [PATCH 49/67] Added @Load --- .run/Omaloon [debug jar].run.xml | 29 ++++ annotations/build.gradle | 48 +++++++ .../main/java/omaloon/annotations/Load.java | 33 +++++ .../java/omaloon/annotations/Starter.java | 55 +++++++ .../annotations/lombok/FieldDescriptor.java | 117 +++++++++++++++ .../lombok/LoadAnnotationASTVisitor.java | 88 ++++++++++++ .../omaloon/annotations/lombok/Reference.java | 34 +++++ .../annotations/lombok/RegionName.java | 135 ++++++++++++++++++ .../javax.annotation.processing.Processor | 1 + .../services/lombok.javac.JavacASTVisitor | 1 + build.gradle.kts | 38 ++++- gradle.properties | 7 + settings.gradle.kts | 20 +++ src/omaloon/annotations/Load.java | 33 +++++ .../world/blocks/defense/BlastTower.java | 15 +- .../world/blocks/defense/RepairProjector.java | 7 +- src/omaloon/world/blocks/defense/Shelter.java | 13 +- .../blocks/distribution/TubeDistributor.java | 15 +- .../world/blocks/distribution/TubeGate.java | 8 +- .../blocks/distribution/TubeJunction.java | 14 +- .../blocks/liquid/PressureLiquidBridge.java | 28 ++-- .../blocks/liquid/PressureLiquidPump.java | 3 +- .../blocks/liquid/PressureLiquidValve.java | 4 +- .../world/blocks/production/HammerDrill.java | 8 +- 24 files changed, 685 insertions(+), 69 deletions(-) create mode 100644 .run/Omaloon [debug jar].run.xml create mode 100644 annotations/build.gradle create mode 100644 annotations/src/main/java/omaloon/annotations/Load.java create mode 100644 annotations/src/main/java/omaloon/annotations/Starter.java create mode 100644 annotations/src/main/java/omaloon/annotations/lombok/FieldDescriptor.java create mode 100644 annotations/src/main/java/omaloon/annotations/lombok/LoadAnnotationASTVisitor.java create mode 100644 annotations/src/main/java/omaloon/annotations/lombok/Reference.java create mode 100644 annotations/src/main/java/omaloon/annotations/lombok/RegionName.java create mode 100644 annotations/src/main/resources/META-INF/services/javax.annotation.processing.Processor create mode 100644 annotations/src/main/resources/META-INF/services/lombok.javac.JavacASTVisitor create mode 100644 src/omaloon/annotations/Load.java diff --git a/.run/Omaloon [debug jar].run.xml b/.run/Omaloon [debug jar].run.xml new file mode 100644 index 00000000..dff11c19 --- /dev/null +++ b/.run/Omaloon [debug jar].run.xml @@ -0,0 +1,29 @@ + + + + + + + + true + true + false + false + + + \ No newline at end of file diff --git a/annotations/build.gradle b/annotations/build.gradle new file mode 100644 index 00000000..24306a2a --- /dev/null +++ b/annotations/build.gradle @@ -0,0 +1,48 @@ +println("Hello from gradle") +apply plugin: "java" + +tasks.withType(JavaCompile).tap{ + configureEach{ + options.fork = true + options.compilerArgs += [ + '--add-exports', 'jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED', + '--add-exports', 'jdk.compiler/com.sun.tools.javac.code.Symbol=ALL-UNNAMED', + '--add-exports', 'jdk.compiler/com.sun.tools.javac.code.Type=ALL-UNNAMED', + '--add-exports', 'jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED', + '--add-exports', 'jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED', + '--add-exports', 'jdk.compiler/com.sun.tools.javac.jvm=ALL-UNNAMED', + '--add-exports', 'jdk.compiler/com.sun.tools.javac.model=ALL-UNNAMED', + '--add-exports', 'jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED', + '--add-exports', 'jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED', + '--add-exports', 'jdk.compiler/com.sun.tools.javac.tree.JCTree=ALL-UNNAMED', + '--add-exports', 'jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED', + '--add-exports', 'jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED', + ] + } +} +repositories{ + // Necessary Maven repositories to pull dependencies from. + mavenCentral() + + maven{url "https://oss.sonatype.org/content/repositories/snapshots/"} + maven{url "https://oss.sonatype.org/content/repositories/releases/"} + maven{url "https://raw.githubusercontent.com/GlennFolker/EntityAnnoMaven/main"} + + // Use Zelaux's non-buggy repository for release Mindustry and Arc builds. + maven{url "https://raw.githubusercontent.com/Zelaux/MindustryRepo/master/repository"} + maven{url "https://raw.githubusercontent.com/Zelaux/Repo/master/repository" } +} + +dependencies{ + println(asmLib.invoke(":annotations:lombok-plugin-starter")) + println(asmLib) + implementation asmLib.invoke(":annotations:lombok-plugin-starter") + + + compileOnly "org.jetbrains:annotations:24.0.1" + + implementation "com.github.javaparser:javaparser-symbol-solver-core:$jparcerVersion" + + compileOnly "org.projectlombok:lombok:$lombokVersion" + annotationProcessor "org.projectlombok:lombok:$lombokVersion" +} \ No newline at end of file diff --git a/annotations/src/main/java/omaloon/annotations/Load.java b/annotations/src/main/java/omaloon/annotations/Load.java new file mode 100644 index 00000000..aa00a5c1 --- /dev/null +++ b/annotations/src/main/java/omaloon/annotations/Load.java @@ -0,0 +1,33 @@ +package omaloon.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target(ElementType.FIELD) +@Retention(RetentionPolicy.SOURCE) +public @interface Load { + /** + * The region name to load. Variables can be used: + * "@" -> block name + * "@size" -> block size + * "#" "#1" "#2" -> index number, for arrays + */ + String value(); + + /** + * 1D Array length, if applicable. + */ + int length() default 1; + + /** + * 2D array lengths. + */ + int[] lengths() default {}; + + /** + * Fallback strings used to replace "@" (the block name) if the region isn't found. + */ + String[] fallback() default {}; +} diff --git a/annotations/src/main/java/omaloon/annotations/Starter.java b/annotations/src/main/java/omaloon/annotations/Starter.java new file mode 100644 index 00000000..d24e9cb7 --- /dev/null +++ b/annotations/src/main/java/omaloon/annotations/Starter.java @@ -0,0 +1,55 @@ +package omaloon.annotations; + +import asmlib.annotations.LombokPluginStarter; +import asmlib.annotations.Permit; + +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodHandles.Lookup; + +import com.sun.tools.javac.code.*; +import com.sun.tools.javac.code.Source.*; + +import javax.annotation.processing.*; +import javax.lang.model.*; +import javax.lang.model.element.*; +import java.lang.invoke.*; +import java.lang.invoke.MethodHandles.*; +import java.util.*; + +import static com.sun.tools.javac.code.Source.Feature.*; + +public class Starter extends LombokPluginStarter { + static{ + initSelf(omaloon.annotations.Starter.class); + } + static{ + try{ + // Get the trusted private lookup. + Lookup lookup = (Lookup) Permit.getField(Lookup.class, "IMPL_LOOKUP").get(null); + // Get the minimum level setter, to force certain features to qualify as a Java 8 feature. + MethodHandle set = lookup.findSetter(Feature.class, "minLevel", Source.class); + + // Downgrade most Java 8-compatible features. + for(Feature feature : new Feature[]{ + EFFECTIVELY_FINAL_VARIABLES_IN_TRY_WITH_RESOURCES, + PRIVATE_SAFE_VARARGS, + DIAMOND_WITH_ANONYMOUS_CLASS_CREATION, + LOCAL_VARIABLE_TYPE_INFERENCE, + VAR_SYNTAX_IMPLICIT_LAMBDAS, + SWITCH_MULTIPLE_CASE_LABELS, + SWITCH_RULE, + SWITCH_EXPRESSION, + TEXT_BLOCKS, + PATTERN_MATCHING_IN_INSTANCEOF, + REIFIABLE_TYPES_INSTANCEOF + }) set.invokeExact(feature, Source.JDK8); + }catch(Throwable t){ + throw new RuntimeException(t); + } + } + @Override + public String dontForgetToInitSelfInStatic(){ + return "ok"; + } +} diff --git a/annotations/src/main/java/omaloon/annotations/lombok/FieldDescriptor.java b/annotations/src/main/java/omaloon/annotations/lombok/FieldDescriptor.java new file mode 100644 index 00000000..6cdde894 --- /dev/null +++ b/annotations/src/main/java/omaloon/annotations/lombok/FieldDescriptor.java @@ -0,0 +1,117 @@ +package omaloon.annotations.lombok; + +import com.github.javaparser.StaticJavaParser; +import com.github.javaparser.ast.stmt.BlockStmt; +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.experimental.FieldDefaults; +import lombok.javac.JavacNode; +import omaloon.annotations.Load; +import org.jetbrains.annotations.NotNull; + +import java.util.Arrays; +import java.util.StringJoiner; + +@FieldDefaults(makeFinal = true, level = AccessLevel.PUBLIC) +@AllArgsConstructor +public class FieldDescriptor { + public static final String ARC_CORE_ATLAS_FIND = "arc.Core.atlas.find"; + public static final String INDECIES__MARKER = "<<>"; + JavacNode field; + Load an; + + public void addMe(BlockStmt block) { +// JCTree.JCVariableDecl variableDecl = (JCTree.JCVariableDecl) field.get(); +// variableDecl.getType() + RegionName expression = new RegionName(); + expression.string("this.%s%s = %s(".formatted(field.getName(), INDECIES__MARKER, ARC_CORE_ATLAS_FIND)); + expression.join(RegionName.build('"' + an.value() + '"')); + for (String fallback : an.fallback()) { + expression.string(", " + ARC_CORE_ATLAS_FIND + "(\""); + expression.join(RegionName.build(fallback)); + expression.string("\""); + } + { + char[] close = new char[an.fallback().length + 1]; + Arrays.fill(close, ')'); + expression.string(new String(close)); + } + + //TODO dimension check + int dimension = (int) (expression.dimensions + Math.random() * 0); + if (expression.dimensions != dimension) { + field.addError("@Load Dimension mismatch"); + return; + } + int[] lengths = lengths(); + if (expression.dimensions > lengths.length) { + field.addError("@Load expected %d lengths but found %d".formatted(expression.dimensions, lengths.length)); + return; + } + + if (expression.dimensions < lengths.length && an.lengths().length > 0) { + field.addWarning("@Load the extra size for the array is indicated"); + } + + + //TODO check type + if (false) { + field.addError("@Load Expected TextureRegion as field type"); + return; + } + + + int totalRounds = 1; + for (int length : lengths) totalRounds *= length; + + if (totalRounds == 0) { + field.addError("@Load one of given lengths are 0"); + return; + } + + if(expression.getItems().get(0) instanceof Reference.StringReference ref){ + StringJoiner joiner=new StringJoiner("][","[","]"); + RegionName indecies = new RegionName(); + int markerIndex = ref.value.indexOf(INDECIES__MARKER); + indecies.string(ref.value.substring(0, markerIndex)); + for (int i = 0; i < expression.dimensions; i++) { + indecies.string("["); + indecies.index(i); + indecies.string("]"); + } + indecies.string(ref.value.substring(markerIndex+INDECIES__MARKER.length())); + for (int i = 1; i < expression.getItems().size(); i++) { + indecies.add(expression.getItems().get(i)); + } + expression.getItems().clear(); + expression.join(indecies); + } + int[] indecies = new int[expression.dimensions]; + for (int __i = 0; __i < totalRounds; __i++) { + String calculatedExpression = expression.calculate(indecies); + + block.addStatement( + StaticJavaParser.parseStatement( + calculatedExpression + ";" + ) + ); + increase(indecies, lengths, 0); + } + + } + + private void increase(int[] indecies, int[] lengths, int i) { + if (i >= indecies.length) return; + indecies[i]++; + if (indecies[i] <= lengths[i]) return; + indecies[i] = 0; + increase(indecies, lengths, i + 1); + } + + @NotNull + private int[] lengths() { + int[] lengths = an.lengths(); + if (lengths.length == 0) lengths = new int[]{an.length()}; + return lengths; + } +} diff --git a/annotations/src/main/java/omaloon/annotations/lombok/LoadAnnotationASTVisitor.java b/annotations/src/main/java/omaloon/annotations/lombok/LoadAnnotationASTVisitor.java new file mode 100644 index 00000000..5a135680 --- /dev/null +++ b/annotations/src/main/java/omaloon/annotations/lombok/LoadAnnotationASTVisitor.java @@ -0,0 +1,88 @@ +package omaloon.annotations.lombok; + +import asmlib.lombok.javaparser.CompileBodyVisitor; +import com.github.javaparser.StaticJavaParser; +import com.github.javaparser.ast.Modifier; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.stmt.BlockStmt; +import com.sun.tools.javac.tree.JCTree; +import com.sun.tools.javac.util.List; +import lombok.core.AST; +import lombok.core.AnnotationValues; +import lombok.javac.JavacASTAdapter; +import lombok.javac.JavacNode; +import lombok.javac.handlers.JavacHandlerUtil; +import omaloon.annotations.Load; +import org.jetbrains.annotations.NotNull; + +import java.util.ArrayList; +//TODO try handle something like @Load(name+"-hello") +//TODO support for delegate function +public class LoadAnnotationASTVisitor extends JavacASTAdapter { + @Override + public void visitType(JavacNode typeNode, JCTree.JCClassDecl type) { + super.visitType(typeNode, type); + ArrayList loadFields = new ArrayList<>(); + JavacNode loadMethod = null; + for (JavacNode field : typeNode.down()) { + if (field.getKind() == AST.Kind.METHOD) { + //TODO hierarchy check + JCTree.JCMethodDecl methodDecl = (JCTree.JCMethodDecl) field.get(); + if (field.getName().equals("load") && methodDecl.getParameters().isEmpty()) { + loadMethod = field; + } + continue; + } + if (field.getKind() != AST.Kind.FIELD) { + continue; + } + AnnotationValues annotation = field.findAnnotation(Load.class); + if (annotation == null) continue; + loadFields.add(new FieldDescriptor(field, annotation.getInstance())); + } + if (loadFields.isEmpty()) return; + CompileBodyVisitor transformer = transformer(typeNode); + if (loadMethod == null) { + BlockStmt body = new BlockStmt(); + MethodDeclaration declaration = new MethodDeclaration() + .setName("load") + .setType(void.class) + .addAnnotation(Override.class) + .setModifiers(Modifier.Keyword.PUBLIC) + .setBody(body) + ; + + body.addStatement(StaticJavaParser.parseStatement("super.load();")); + + addFields(loadFields, body); + + JCTree.JCMethodDecl methodDecl = transformer.visit(declaration, null); + JavacHandlerUtil.injectMethod(typeNode, methodDecl); + } else { + JCTree.JCMethodDecl decl = (JCTree.JCMethodDecl) loadMethod.get(); + List oldStats = decl.body.stats; + + JCTree.JCBlock newBlock = transformer.visit(addFields(loadFields, new BlockStmt()), null); + List stats = newBlock.stats; + decl.body.stats= stats.appendList(oldStats); + loadMethod.getAst().setChanged(); + } + + } + + private static BlockStmt addFields(java.util.List loadFields, BlockStmt block) { + for (FieldDescriptor field : loadFields) + field.addMe(block); + return block; + } + + @NotNull + private static CompileBodyVisitor transformer(JavacNode typeNode) { + return new CompileBodyVisitor( + typeNode.getTreeMaker(), + typeNode.getAst(), + typeNode.getContext() + ); + } + +} diff --git a/annotations/src/main/java/omaloon/annotations/lombok/Reference.java b/annotations/src/main/java/omaloon/annotations/lombok/Reference.java new file mode 100644 index 00000000..861944ea --- /dev/null +++ b/annotations/src/main/java/omaloon/annotations/lombok/Reference.java @@ -0,0 +1,34 @@ +package omaloon.annotations.lombok; + +import lombok.AllArgsConstructor; + +public abstract class Reference { + abstract String stringify(int[] data); + @AllArgsConstructor + public static class IndexReference extends Reference { + public final int index; + @Override + String stringify(int[] data) { + return data[index] + ""; + } + } + @AllArgsConstructor + public static class ExpressionReference extends Reference { + public final String expression; + @Override + String stringify(int[] data) { + return "\" + "+expression+"+ \""; + } + } + @AllArgsConstructor + public static class StringReference extends Reference{ + public final String value; + @Override + String stringify(int[] data) { + return value; + } + } + public boolean isString() { + return this instanceof StringReference; + } +} diff --git a/annotations/src/main/java/omaloon/annotations/lombok/RegionName.java b/annotations/src/main/java/omaloon/annotations/lombok/RegionName.java new file mode 100644 index 00000000..22da7daf --- /dev/null +++ b/annotations/src/main/java/omaloon/annotations/lombok/RegionName.java @@ -0,0 +1,135 @@ +package omaloon.annotations.lombok; + +import lombok.Getter; +import omaloon.annotations.lombok.Reference.ExpressionReference; +import omaloon.annotations.lombok.Reference.IndexReference; +import omaloon.annotations.lombok.Reference.StringReference; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.BiConsumer; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class RegionName { + public static final int[] EMPTY_INTS = new int[0]; + static Pattern accessExpressionPattern = Pattern.compile("@(\\w+(\\(\\))?(\\.\\w+(\\(\\))?)*)*"); + static Pattern indexAccessPattern = Pattern.compile("#\\d*"); + + public int dimensions; + @Getter + private List items = new ArrayList<>(); + + private static void flatReplacePattern(RegionName regionName, Pattern pattern, BiConsumer replacement) { + + ArrayList copy = new ArrayList<>(regionName.items); + regionName.items.clear(); + for (Reference reference : copy) { + if (!reference.isString()) { + regionName.add(reference); + continue; + } + String value = reference.stringify(EMPTY_INTS); + Matcher matcher = pattern.matcher(value); + if (matcher.find()) { + + int prevIndex = 0; + while (matcher.find(prevIndex)) { + regionName.string(value.substring(prevIndex, matcher.start())); + replacement.accept(matcher.group(), regionName); + prevIndex = matcher.end(); + } + regionName.string(value.substring(prevIndex)); + }else{ + regionName.string(value); + } + } + } + + public static RegionName build(String string) { + RegionName name = new RegionName(); + name.string(string); +// StringBuilder builder = new StringBuilder("\""); + flatReplacePattern(name, accessExpressionPattern, (group, l) -> { + String expression = group.substring(1);//removing "@" + if (expression.isEmpty()) { + expression = "name"; + } + l.expression("this."+expression); + }); + flatReplacePattern(name, indexAccessPattern, (group, l) -> { + String number = group.substring(1);//removing "#" + if (number.isEmpty()) { + number = "0"; + } + l.index(Integer.parseInt(number)); + }); + name.updateDimentions(); + return name; + } + + public void add(Reference reference) { + if (reference instanceof StringReference stringReference) { + string(stringReference.value); + } else items.add(reference); + + } + + public RegionName copy() { + RegionName name = new RegionName(); + name.items.addAll(items); + name.dimensions = dimensions; + return name; + } + + public void join(RegionName other) { + for (Reference reference : other.items) { + add(reference); + } + updateDimentions(); + } + + ; + + private void updateDimentions() { + dimensions = (int) items.stream().filter(it -> it instanceof IndexReference).count(); + } + + public boolean isString() { + for (Reference item : items) { + if (!(item instanceof StringReference)) { + return false; + } + } + return true; + } + + public String calculate(int... indecies) { + String[] strings = new String[items.size()]; + for (int i = 0; i < strings.length; i++) { + strings[i] = items.get(i).stringify(indecies); + } + return String.join("", strings); + } + + public void index(int num) { + items.add(new IndexReference(num)); + } + + public void string(String string) { + int lastIdx = items.size() - 1; + if (lastIdx >= 0 && items.get(lastIdx) instanceof StringReference last_) { + items.set(lastIdx, new StringReference( + last_.value + string + )); + } else { + items.add(new StringReference(string)); + } + } + + public void expression(String expression) { + items.add(new ExpressionReference(expression)); + } + + +} diff --git a/annotations/src/main/resources/META-INF/services/javax.annotation.processing.Processor b/annotations/src/main/resources/META-INF/services/javax.annotation.processing.Processor new file mode 100644 index 00000000..a6abb4e0 --- /dev/null +++ b/annotations/src/main/resources/META-INF/services/javax.annotation.processing.Processor @@ -0,0 +1 @@ +omaloon.annotations.Starter \ No newline at end of file diff --git a/annotations/src/main/resources/META-INF/services/lombok.javac.JavacASTVisitor b/annotations/src/main/resources/META-INF/services/lombok.javac.JavacASTVisitor new file mode 100644 index 00000000..5847eb38 --- /dev/null +++ b/annotations/src/main/resources/META-INF/services/lombok.javac.JavacASTVisitor @@ -0,0 +1 @@ +omaloon.annotations.lombok.LoadAnnotationASTVisitor \ No newline at end of file diff --git a/build.gradle.kts b/build.gradle.kts index 5c7dc768..fdb664ea 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -23,6 +23,15 @@ plugins{ id("de.undercouch.download") version "5.4.0" id("com.github.GlennFolker.EntityAnno") apply false } +val asmLib: (String) -> Any = { + val asmLibVersion: String by project + val name = it.trim(':').replace(':', '-') + try { + project(":JavaAsmLib:$it") + } catch (e: Exception) { + "com.github.Zelaux.JavaAsmExtension:$name:$asmLibVersion" + } +} val arcVersion: String by project val arcLibraryVersion: String by project @@ -46,7 +55,7 @@ fun arc(module: String): String{ return "com.github.Anuken.Arc$module:$arcVersion" } -fun arcLibrary(module: String):String{ +fun arcLibrary(module: String): String{ return "com.github.Zelaux.ArcLibrary$module:$arcLibraryVersion" } @@ -58,7 +67,8 @@ fun entity(module: String): String{ return "com.github.GlennFolker.EntityAnno$module:$entVersion" } -allprojects{ +extra.set("asmLib", asmLib) +project(":"){ apply(plugin = "java") sourceSets["main"].java.setSrcDirs(listOf(layout.projectDirectory.dir("src"))) @@ -75,7 +85,8 @@ allprojects{ dependencies{ // Downgrade Java 9+ syntax into being available in Java 8. - annotationProcessor(entity(":downgrader")) + //moved into :annotation because of 'missing opens issue' +// annotationProcessor(entity(":downgrader")) } repositories{ @@ -116,7 +127,21 @@ project(":"){ genPackage = modGen } + //Added debuging diring compilation to debug annotation processors + tasks.withType(JavaCompile::class).configureEach{ + options.isDebug = true + options.isFork = true + options.compilerArgs.add("-g") + + options.forkOptions.jvmArgs!!.add( + "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5008" + ) + } dependencies{ + annotationProcessor("org.projectlombok:lombok:1.18.32") + annotationProcessor(asmLib("annotations:debug-print")) + annotationProcessor(project(":annotations")) + // Use the entity generation annotation processor. compileOnly(entity(":entity")) add("kapt", entity(":entity")) @@ -170,6 +195,7 @@ project(":"){ tasks.register("dex"){ inputs.files(jar) + group="android" archiveFileName = "$modArtifact.jar" val desktopJar = jar.flatMap{it.archiveFile} @@ -211,13 +237,15 @@ project(":"){ } } - tasks.register("fetchClient") { + tasks.register("fetchClient"){ + group="run" src("https://github.com/Anuken/Mindustry/releases/download/$mindustryVersion/Mindustry.jar") dest(file("$rootDir/run/Mindustry.jar")) overwrite(false) } - tasks.register("runClient") { + tasks.register("runClient"){ + group="run" dependsOn("fetchClient") dependsOn("jar") diff --git a/gradle.properties b/gradle.properties index 8e93fe38..c9434c90 100644 --- a/gradle.properties +++ b/gradle.properties @@ -36,6 +36,12 @@ androidBuildVersion = 35.0.0 # Android platform minimum API version. Should be left as 14, as that's what Mindustry officially supports. androidMinVersion = 14 +#### annotation dependencies +jparcerVersion = 3.26.0 +lombokVersion = 1.18.32 +jetbrainsAnnotations = 24.0.1 +asmLibVersion = v0.9.6 + ##### Other stuff that should be left as-is. # Enable parallel compilation. org.gradle.parallel = true @@ -53,3 +59,4 @@ org.gradle.jvmargs = \ --add-opens=jdk.compiler/com.sun.tools.javac.jvm=ALL-UNNAMED \ --add-opens=jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED \ --add-opens=java.base/sun.reflect.annotation=ALL-UNNAMED + diff --git a/settings.gradle.kts b/settings.gradle.kts index b1b496b3..01b4ce7e 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -1,3 +1,5 @@ +import groovy.lang.Closure + pluginManagement{ repositories{ gradlePluginPortal() @@ -14,5 +16,23 @@ if(JavaVersion.current().ordinal < JavaVersion.VERSION_17.ordinal){ throw IllegalStateException("JDK 17 is a required minimum version. Yours: ${System.getProperty("java.version")}") } +include("annotations") + +val localprop = java.util.Properties() +localprop.load(file("local.properties").reader()) +val asmLibPath = localprop["asm_lib_path"] + +if(asmLibPath != null){ + println("Loading local AsmLib") + val root = file(asmLibPath) + val includeSelfPath = File(root, "includeSelf.gradle").canonicalPath + apply{ + from(includeSelfPath) + } + (extra["includeSelf"] as Closure<*>).call(root) + //added in includeSelf, then autodeleted +} + + val modName: String by settings rootProject.name = modName \ No newline at end of file diff --git a/src/omaloon/annotations/Load.java b/src/omaloon/annotations/Load.java new file mode 100644 index 00000000..aa00a5c1 --- /dev/null +++ b/src/omaloon/annotations/Load.java @@ -0,0 +1,33 @@ +package omaloon.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target(ElementType.FIELD) +@Retention(RetentionPolicy.SOURCE) +public @interface Load { + /** + * The region name to load. Variables can be used: + * "@" -> block name + * "@size" -> block size + * "#" "#1" "#2" -> index number, for arrays + */ + String value(); + + /** + * 1D Array length, if applicable. + */ + int length() default 1; + + /** + * 2D array lengths. + */ + int[] lengths() default {}; + + /** + * Fallback strings used to replace "@" (the block name) if the region isn't found. + */ + String[] fallback() default {}; +} diff --git a/src/omaloon/world/blocks/defense/BlastTower.java b/src/omaloon/world/blocks/defense/BlastTower.java index 132845b1..bf46f8d8 100644 --- a/src/omaloon/world/blocks/defense/BlastTower.java +++ b/src/omaloon/world/blocks/defense/BlastTower.java @@ -16,6 +16,7 @@ import mindustry.world.*; import mindustry.world.consumers.*; import mindustry.world.meta.*; +import omaloon.annotations.Load; import omaloon.content.*; import omaloon.world.interfaces.*; import omaloon.world.meta.*; @@ -41,7 +42,7 @@ public class BlastTower extends Block { public Color waveColor = Color.white; public Effect waveEffect = Fx.dynamicWave; public Sound shootSound = OlSounds.hammer; - + @Load("@-hammer") public TextureRegion hammerRegion; public BlastTower(String name){ @@ -50,12 +51,6 @@ public BlastTower(String name){ solid = true; } - @Override - public void load(){ - super.load(); - hammerRegion = atlas.find(name + "-hammer"); - } - @Override public void setStats(){ super.setStats(); @@ -150,9 +145,9 @@ public void shoot() { shootSound.at(this); waveEffect.layer(Layer.blockUnder).at(x, y, range, waveColor); tile.getLinkedTiles(t -> OlFx.hammerHit.layer(Layer.blockUnder).at( - t.worldx(), t.worldy(), - angleTo(t.worldx(), t.worldy()) + Mathf.range(360f), - Tmp.c1.set(t.floor().mapColor).mul(1.5f + Mathf.range(0.15f))) + t.worldx(), t.worldy(), + angleTo(t.worldx(), t.worldy()) + Mathf.range(360f), + Tmp.c1.set(t.floor().mapColor).mul(1.5f + Mathf.range(0.15f))) ); float damageMultiplier = efficiencyMultiplier(); diff --git a/src/omaloon/world/blocks/defense/RepairProjector.java b/src/omaloon/world/blocks/defense/RepairProjector.java index 34dfc9fb..090acb1c 100644 --- a/src/omaloon/world/blocks/defense/RepairProjector.java +++ b/src/omaloon/world/blocks/defense/RepairProjector.java @@ -12,6 +12,7 @@ import mindustry.logic.*; import mindustry.world.*; import mindustry.world.meta.*; +import omaloon.annotations.Load; import static arc.Core.*; import static mindustry.Vars.*; @@ -24,6 +25,7 @@ public class RepairProjector extends Block{ public float healWaveSpeed = 120f; public float reload = 20f; public float healAmount = 1f; + @Load("@-top") public TextureRegion top; public RepairProjector(String name){ @@ -32,11 +34,6 @@ public RepairProjector(String name){ solid = true; } - public void load(){ - super.load(); - top = atlas.find(name + "-top"); - } - @Override public void setStats(){ super.setStats(); diff --git a/src/omaloon/world/blocks/defense/Shelter.java b/src/omaloon/world/blocks/defense/Shelter.java index f002eec8..cf0c5a86 100644 --- a/src/omaloon/world/blocks/defense/Shelter.java +++ b/src/omaloon/world/blocks/defense/Shelter.java @@ -21,6 +21,7 @@ import mindustry.world.*; import mindustry.world.consumers.*; import mindustry.world.meta.*; +import omaloon.annotations.Load; import omaloon.content.*; import omaloon.world.interfaces.*; import omaloon.world.meta.*; @@ -29,7 +30,10 @@ import static omaloon.OmaloonMod.*; public class Shelter extends Block { - public TextureRegion baseRegion, glowRegion; + @Load(value = "@-base",fallback = {"block-@size"}) + public TextureRegion baseRegion; + @Load("@-glow") + public TextureRegion glowRegion; public PressureConfig pressureConfig = new PressureConfig(); @@ -90,13 +94,6 @@ public Shelter(String name) { configClear((ShelterBuild build) -> build.rot = 90); } - @Override - public void load() { - super.load(); - baseRegion = Core.atlas.find(name + "-base", "block-" + size); - glowRegion = Core.atlas.find(name + "-glow"); - } - @Override public TextureRegion[] icons() { return new TextureRegion[]{baseRegion, region}; diff --git a/src/omaloon/world/blocks/distribution/TubeDistributor.java b/src/omaloon/world/blocks/distribution/TubeDistributor.java index 8e0f861f..c5ba488d 100644 --- a/src/omaloon/world/blocks/distribution/TubeDistributor.java +++ b/src/omaloon/world/blocks/distribution/TubeDistributor.java @@ -11,6 +11,7 @@ import mindustry.world.*; import mindustry.world.blocks.distribution.*; import mindustry.world.draw.*; +import omaloon.annotations.Load; import static arc.Core.*; import static mindustry.Vars.*; @@ -18,7 +19,14 @@ public class TubeDistributor extends Router { public DrawBlock drawer = new DrawDefault(); - public TextureRegion rotorRegion, lockedRegion1, lockedRegion2; + @Load("@-rotator") + public TextureRegion rotorRegion; + @Load("@-locked-side1") + public TextureRegion lockedRegion1; + @Load("@-locked-side2") + public TextureRegion lockedRegion2; + @Load("@-bottom") + public TextureRegion bottomRegion; public TubeDistributor(String name) { super(name); @@ -29,16 +37,13 @@ public TubeDistributor(String name) { public void load() { super.load(); drawer.load(this); - rotorRegion = atlas.find(name + "-rotator"); - lockedRegion1 = atlas.find(name + "-locked-side1"); - lockedRegion2 = atlas.find(name + "-locked-side2"); uiIcon = atlas.find(name + "-icon"); } @Override public void drawPlanRegion(BuildPlan plan, Eachable list){ super.drawPlanRegion(plan, list); - Draw.rect(atlas.find(name + "-bottom"), plan.drawx(), plan.drawy()); + Draw.rect(bottomRegion, plan.drawx(), plan.drawy()); Draw.rect(rotorRegion, plan.drawx(), plan.drawy()); Draw.rect(region, plan.drawx(), plan.drawy()); Draw.rect(plan.rotation > 1 ? lockedRegion2 : lockedRegion1, plan.drawx(), plan.drawy(), plan.rotation * 90); diff --git a/src/omaloon/world/blocks/distribution/TubeGate.java b/src/omaloon/world/blocks/distribution/TubeGate.java index 51078774..2e0d8467 100644 --- a/src/omaloon/world/blocks/distribution/TubeGate.java +++ b/src/omaloon/world/blocks/distribution/TubeGate.java @@ -12,10 +12,12 @@ import mindustry.gen.*; import mindustry.type.*; import mindustry.world.blocks.distribution.*; +import omaloon.annotations.Load; import static mindustry.Vars.*; public class TubeGate extends OverflowGate { + @Load("@-top-underflow") public TextureRegion topUnder; public Effect switchEffect = Fx.doorclose; public Sound switchSound = Sounds.door; @@ -26,12 +28,6 @@ public TubeGate(String name) { config(Boolean.class, (TubeGateBuild build, Boolean invert) -> build.invert = invert); } - @Override - public void load() { - super.load(); - topUnder = Core.atlas.find(name + "-top-underflow"); - } - @Override public void drawPlanConfig(BuildPlan plan, Eachable list) { if(plan.config instanceof Boolean boll && boll) Draw.rect(topUnder, plan.drawx(), plan.drawy(), 0); diff --git a/src/omaloon/world/blocks/distribution/TubeJunction.java b/src/omaloon/world/blocks/distribution/TubeJunction.java index 343a053e..a63598f8 100644 --- a/src/omaloon/world/blocks/distribution/TubeJunction.java +++ b/src/omaloon/world/blocks/distribution/TubeJunction.java @@ -8,12 +8,18 @@ import mindustry.gen.Building; import mindustry.world.blocks.distribution.*; import mindustry.world.draw.*; +import omaloon.annotations.Load; import static arc.Core.*; public class TubeJunction extends Junction { public DrawBlock drawer = new DrawDefault(); - public TextureRegion side1, side2; + @Load("@-side1") + public TextureRegion side1; + @Load("@-side2") + public TextureRegion side2; + @Load("@-bottom") + protected TextureAtlas.AtlasRegion bottomRegion; protected int tempBlend = 0; public TubeJunction(String name) { @@ -24,9 +30,6 @@ public TubeJunction(String name) { public void load(){ super.load(); drawer.load(this); - side1 = atlas.find(name + "-side1"); - side2 = atlas.find(name + "-side2"); - uiIcon = atlas.find(name + "-icon"); } @Override @@ -49,7 +52,8 @@ public void drawPlanRegion(BuildPlan plan, Eachable list){ float x = plan.drawx(), y = plan.drawy(); - Draw.rect(atlas.find(name + "-bottom"), x, y); + + Draw.rect(bottomRegion, x, y); Draw.rect(region, x, y); //code duplication, awful diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidBridge.java b/src/omaloon/world/blocks/liquid/PressureLiquidBridge.java index a9aeadf1..93877415 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidBridge.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidBridge.java @@ -18,6 +18,7 @@ import mindustry.world.blocks.liquid.*; import mindustry.world.blocks.sandbox.*; import mindustry.world.meta.BlockGroup; +import omaloon.annotations.Load; import omaloon.world.blocks.distribution.*; import omaloon.world.interfaces.*; import omaloon.world.meta.*; @@ -33,10 +34,18 @@ public class PressureLiquidBridge extends TubeItemBridge { public float liquidPadding = 1f; - public TextureRegion - bottomRegion, endRegion1, - endBottomRegion, endLiquidRegion, - bridgeBottomRegion, bridgeLiquidRegion; + @Load("omaloon-liquid-bottom") + public TextureRegion bottomRegion; + @Load("@-end1") + public TextureRegion endRegion1; + @Load("@-end-bottom") + public TextureRegion endBottomRegion; + @Load("@-end-liquid") + public TextureRegion endLiquidRegion; + @Load("@-bridge-bottom") + public TextureRegion bridgeBottomRegion; + @Load("@-bridge-liquid") + public TextureRegion bridgeLiquidRegion; public PressureLiquidBridge(String name) { super(name); @@ -121,17 +130,6 @@ public TextureRegion[] icons(){ return new TextureRegion[]{atlas.find(name + "-icon")}; } - @Override - public void load() { - super.load(); - bottomRegion = Core.atlas.find("omaloon-liquid-bottom"); - endRegion1 = Core.atlas.find(name + "-end1"); - endBottomRegion = Core.atlas.find(name + "-end-bottom"); - endLiquidRegion = Core.atlas.find(name + "-end-liquid"); - bridgeBottomRegion = Core.atlas.find(name + "-bridge-bottom"); - bridgeLiquidRegion = Core.atlas.find(name + "-bridge-liquid"); - } - @Override public void setBars() { super.setBars(); diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidPump.java b/src/omaloon/world/blocks/liquid/PressureLiquidPump.java index c4fcf495..16a76d2d 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidPump.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidPump.java @@ -14,6 +14,7 @@ import mindustry.graphics.*; import mindustry.type.*; import mindustry.world.blocks.liquid.*; +import omaloon.annotations.Load; import omaloon.content.*; import omaloon.utils.*; import omaloon.world.interfaces.*; @@ -37,6 +38,7 @@ public class PressureLiquidPump extends LiquidBlock { public TextureRegion[][] liquidRegions; public TextureRegion[] tiles; + @Load("@-arrow") public TextureRegion arrowRegion; public PressureLiquidPump(String name) { @@ -75,7 +77,6 @@ public void drawPlanRegion(BuildPlan plan, Eachable list) { public void load() { super.load(); tiles = OlUtils.split(name + "-tiles", 32, 0); - arrowRegion = Core.atlas.find(name + "-arrow"); if (!bottomRegion.found()) bottomRegion = Core.atlas.find("omaloon-liquid-bottom"); liquidRegions = new TextureRegion[2][animationFrames]; diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidValve.java b/src/omaloon/world/blocks/liquid/PressureLiquidValve.java index 27e78ca2..f104dafe 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidValve.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidValve.java @@ -79,8 +79,6 @@ public TextureRegion[] icons() { public void load() { super.load(); tiles = OlUtils.split(name + "-tiles", 32, 0); - valveRegion = Core.atlas.find(name + "-valve"); - topRegion = Core.atlas.find(name + "-top"); if (!bottomRegion.found()) bottomRegion = Core.atlas.find("omaloon-liquid-bottom"); liquidRegions = new TextureRegion[2][animationFrames]; @@ -220,7 +218,7 @@ public void updateTile() { @Override public byte version() { return 1; } - + @Override public void write(Writes write) { super.write(write); diff --git a/src/omaloon/world/blocks/production/HammerDrill.java b/src/omaloon/world/blocks/production/HammerDrill.java index db6ce011..73516df4 100644 --- a/src/omaloon/world/blocks/production/HammerDrill.java +++ b/src/omaloon/world/blocks/production/HammerDrill.java @@ -9,6 +9,7 @@ import mindustry.gen.*; import mindustry.graphics.*; import mindustry.type.*; +import omaloon.annotations.Load; import omaloon.content.*; import static arc.Core.*; @@ -18,6 +19,7 @@ public class HammerDrill extends PressureDrill { public float invertedTime = 200f; public Sound drillSound = OlSounds.hammer; public float drillSoundVolume = 0.2f, drillSoundPitchRand = 0.3f; + @Load("@-hammer") public TextureRegion hammerRegion; public HammerDrill(String name){ @@ -29,12 +31,6 @@ public HammerDrill(String name){ ambientSound = Sounds.none; } - @Override - public void load(){ - super.load(); - hammerRegion = atlas.find(name + "-hammer"); - } - @Override public void drawPlanRegion(BuildPlan plan, Eachable list) { super.drawPlanRegion(plan, list); From dc3deed1ab54d5a1dae89507f948c30581684a6b Mon Sep 17 00:00:00 2001 From: Zelaux <58040045+zelaux@users.noreply.github.com> Date: Thu, 30 Jan 2025 20:14:21 +0300 Subject: [PATCH 50/67] Fixed settings.gradle.kts --- settings.gradle.kts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/settings.gradle.kts b/settings.gradle.kts index 01b4ce7e..d96a7cb7 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -19,7 +19,7 @@ if(JavaVersion.current().ordinal < JavaVersion.VERSION_17.ordinal){ include("annotations") val localprop = java.util.Properties() -localprop.load(file("local.properties").reader()) +if(file("local.properties").exists()) localprop.load(file("local.properties").reader()) val asmLibPath = localprop["asm_lib_path"] if(asmLibPath != null){ From 2729f8da15f66d627d3b92b89e76022926eb6ff8 Mon Sep 17 00:00:00 2001 From: Zelaux <58040045+zelaux@users.noreply.github.com> Date: Thu, 30 Jan 2025 20:26:01 +0300 Subject: [PATCH 51/67] Debug annotation --- src/asmlib/annotations/DebugAST.java | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 src/asmlib/annotations/DebugAST.java diff --git a/src/asmlib/annotations/DebugAST.java b/src/asmlib/annotations/DebugAST.java new file mode 100644 index 00000000..0728ee08 --- /dev/null +++ b/src/asmlib/annotations/DebugAST.java @@ -0,0 +1,5 @@ +package asmlib.annotations; + +public @interface DebugAST { + String outfile() default ""; +} From a8fb06ce0d797b73754a9fb446d548781dd92720 Mon Sep 17 00:00:00 2001 From: = Date: Thu, 30 Jan 2025 20:13:55 -0300 Subject: [PATCH 52/67] how tf was this it working --- .../world/blocks/sandbox/PressureLiquidSource.java | 10 +++++++--- src/omaloon/world/meta/PressureSection.java | 4 ++-- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/src/omaloon/world/blocks/sandbox/PressureLiquidSource.java b/src/omaloon/world/blocks/sandbox/PressureLiquidSource.java index dffd66ae..1ec863e6 100644 --- a/src/omaloon/world/blocks/sandbox/PressureLiquidSource.java +++ b/src/omaloon/world/blocks/sandbox/PressureLiquidSource.java @@ -17,6 +17,7 @@ import mindustry.ui.*; import mindustry.world.*; import mindustry.world.blocks.liquid.*; +import omaloon.content.*; import omaloon.ui.elements.*; import omaloon.world.interfaces.*; import omaloon.world.meta.*; @@ -188,9 +189,12 @@ public void read(Reads read, byte revision) { public void updateTile() { pressure.section.updateTransfer(); - float difference = (Vars.content.liquid(liquid) == null ? targetAmount : Mathf.maxZero(targetAmount)) - (Vars.content.liquid(liquid) == null ? pressure.air : pressure.liquids[liquid]); - - addFluid(Vars.content.liquid(liquid), difference); + pressure.air = Vars.content.liquid(liquid) == null ? targetAmount : 0; + pressure.pressure = pressure.air / pressureConfig.fluidCapacity * OlLiquids.getDensity(null); + Vars.content.liquids().each(liq -> { + pressure.liquids[liq.id] = liq.id == liquid ? Mathf.maxZero(targetAmount) : 0; + pressure.pressures[liq.id] = pressure.liquids[liq.id] / pressureConfig.fluidCapacity * OlLiquids.getDensity(liq); + }); } @Override diff --git a/src/omaloon/world/meta/PressureSection.java b/src/omaloon/world/meta/PressureSection.java index dfbbdda9..d77201d2 100644 --- a/src/omaloon/world/meta/PressureSection.java +++ b/src/omaloon/world/meta/PressureSection.java @@ -137,7 +137,7 @@ public void updateTransfer() { entry.value.pressureConfig().fluidCapacity, entry.key.pressureConfig().fluidCapacity, OlLiquids.getDensity(main), - 0 + 1 ) / (2f * links.size); float flow = Mathf.clamp( @@ -186,7 +186,7 @@ public void updateTransfer() { entry.value.pressureConfig().fluidCapacity, entry.key.pressureConfig().fluidCapacity, OlLiquids.getDensity(null), - 0 + 1 ) / (2f * links.size); float flow = Mathf.clamp( From 54b72d9befefbb1f00cf3a77123a6016b4acfebc Mon Sep 17 00:00:00 2001 From: = Date: Thu, 30 Jan 2025 22:13:05 -0300 Subject: [PATCH 53/67] light stat change --- assets/bundles/bundle.properties | 2 +- .../world/blocks/liquid/PressureLiquidPump.java | 2 +- src/omaloon/world/consumers/ConsumeFluid.java | 14 ++++++++++++-- src/omaloon/world/meta/OlStats.java | 15 +++++++++++++-- src/omaloon/world/meta/PressureConfig.java | 4 ++-- 5 files changed, 29 insertions(+), 8 deletions(-) diff --git a/assets/bundles/bundle.properties b/assets/bundles/bundle.properties index 9c4487cb..d508b160 100644 --- a/assets/bundles/bundle.properties +++ b/assets/bundles/bundle.properties @@ -353,7 +353,7 @@ stat.omaloon-max-pressure = Max Pressure stat.omaloon-pressureflow = Speed stat.omaloon-pressure-range = Operating Range -stat.omaloon-pressure-range.format = between \uC357 @ Pascals and \uC357 @ Pascals. +stat.omaloon-pressure-range.format = Between \uC357 @ Pascals and \uC357 @ Pascals. stat.omaloon-optimal-pressure = Optimal Pressure stat.omaloon-optimal-pressure.format = \uC357 @ Pascals (@%) diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidPump.java b/src/omaloon/world/blocks/liquid/PressureLiquidPump.java index 0d2f1084..0f055cce 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidPump.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidPump.java @@ -126,7 +126,7 @@ public void setStats() { pressureConfig.addStats(stats); stats.remove(OlStats.fluidCapacity); stats.add(OlStats.pumpStrength, pumpStrength * 60f, StatUnit.liquidSecond); - stats.add(OlStats.pressureGradient, pressureDifference, OlStats.pressureUnit); + stats.add(OlStats.pressureGradient, OlStats.pressure(pressureDifference, true)); } public class PressureLiquidPumpBuild extends Building implements HasPressure { diff --git a/src/omaloon/world/consumers/ConsumeFluid.java b/src/omaloon/world/consumers/ConsumeFluid.java index 6b4acf9f..8fae3ab0 100644 --- a/src/omaloon/world/consumers/ConsumeFluid.java +++ b/src/omaloon/world/consumers/ConsumeFluid.java @@ -73,8 +73,18 @@ public void display(Stats stats) { } if (startRange != endRange) { - stats.add(OlStats.pressureRange, Core.bundle.get("stat.omaloon-pressure-range.format"), Strings.autoFixed(startRange, 2), Strings.autoFixed(endRange, 2)); - if (hasOptimalPressure) stats.add(OlStats.optimalPressure, Core.bundle.get("stat.omaloon-optimal-pressure.format"), Strings.autoFixed(optimalPressure, 2), Strings.autoFixed(efficiencyMultiplier * 100f, 2)); + stats.add( + OlStats.pressureRange, + Core.bundle.get("stat.omaloon-pressure-range.format"), + (startRange == 0 ? "" : (startRange > 0 ? "+" : "-")) + Strings.autoFixed(Math.abs(startRange), 2), + (endRange == 0 ? "" : (endRange > 0 ? "+" : "-")) + Strings.autoFixed(Math.abs(endRange), 2) + ); + if (hasOptimalPressure) stats.add( + OlStats.optimalPressure, + Core.bundle.get("stat.omaloon-optimal-pressure.format"), + (optimalPressure == 0 ? "" : (optimalPressure > 0 ? "+" : "-")) + Strings.autoFixed(Math.abs(optimalPressure), 2), + Strings.autoFixed(efficiencyMultiplier * 100f, 2) + ); } } diff --git a/src/omaloon/world/meta/OlStats.java b/src/omaloon/world/meta/OlStats.java index 6b173779..9c2c2ace 100644 --- a/src/omaloon/world/meta/OlStats.java +++ b/src/omaloon/world/meta/OlStats.java @@ -37,8 +37,6 @@ public class OlStats { optimalPressure = new Stat("omaloon-optimal-pressure", pressure); public static final StatUnit - blocksCubed = new StatUnit("omaloon-blocks-cubed"), - densityUnit = new StatUnit("omaloon-density-unit", "\uC357"), viscosityUnit = new StatUnit("omaloon-viscosity-unit", "\uC357"), @@ -66,4 +64,17 @@ public static StatValue fluid(@Nullable Liquid liquid, float amount, float time, }); }; } + + public static StatValue pressure(float amount, boolean merge) { + return table -> { + String l1 = (pressureUnit.icon == null ? "" : pressureUnit.icon + " ") + (amount == 0 ? "" : (amount > 0 ? "+" : "-")) + Strings.autoFixed(Math.abs(amount), 2), l2 = (pressureUnit.space ? " " : "") + pressureUnit.localized(); + + if(merge){ + table.add(l1 + l2).left(); + }else{ + table.add(l1).left(); + table.add(l2).left(); + } + }; + } } diff --git a/src/omaloon/world/meta/PressureConfig.java b/src/omaloon/world/meta/PressureConfig.java index e95753d4..7cff4ee8 100644 --- a/src/omaloon/world/meta/PressureConfig.java +++ b/src/omaloon/world/meta/PressureConfig.java @@ -80,8 +80,8 @@ public class PressureConfig { public void addStats(Stats stats) { stats.add(OlStats.fluidCapacity, Core.bundle.get("stat.omaloon-fluid-capacity.format"), fluidCapacity/8f, fluidCapacity/8f, fluidCapacity/8f); - stats.add(OlStats.maxPressure, maxPressure, OlStats.pressureUnit); - stats.add(OlStats.minPressure, minPressure, OlStats.pressureUnit); + stats.add(OlStats.maxPressure, OlStats.pressure(maxPressure, true)); + stats.add(OlStats.minPressure, OlStats.pressure(minPressure, true)); } public void addBars(Block block) { From 7eb28cd18aeca12a95df55c1b0c54d485c9fbb8d Mon Sep 17 00:00:00 2001 From: = Date: Fri, 31 Jan 2025 01:04:35 -0300 Subject: [PATCH 54/67] techtree and change the gauge cost --- src/omaloon/content/OlTechTree.java | 12 ++++++------ .../content/blocks/OlDistributionBlocks.java | 15 ++++++++------- 2 files changed, 14 insertions(+), 13 deletions(-) diff --git a/src/omaloon/content/OlTechTree.java b/src/omaloon/content/OlTechTree.java index 77d4736d..5f5ca348 100644 --- a/src/omaloon/content/OlTechTree.java +++ b/src/omaloon/content/OlTechTree.java @@ -33,13 +33,13 @@ public static void load() { }); node(hammerDrill, () -> { - node(liquidTube, () -> { - node(liquidJunction, () -> { - node(liquidBridge); - }); - node(liquidPump, () -> { - node(liquidValve); + node(liquidPump, () -> { + node(liquidTube, () -> { + node(liquidJunction, () -> { + node(liquidBridge); + }); }); + node(liquidGauge); }); node(carborundumPress, with(new Research(smallShelter)), () -> { diff --git a/src/omaloon/content/blocks/OlDistributionBlocks.java b/src/omaloon/content/blocks/OlDistributionBlocks.java index f76086aa..c27bca91 100644 --- a/src/omaloon/content/blocks/OlDistributionBlocks.java +++ b/src/omaloon/content/blocks/OlDistributionBlocks.java @@ -7,6 +7,7 @@ import mindustry.type.*; import mindustry.world.*; import mindustry.world.draw.*; +import mindustry.world.meta.*; import omaloon.content.*; import omaloon.world.blocks.distribution.*; import omaloon.world.blocks.liquid.*; @@ -105,7 +106,7 @@ public static void load() { OlItems.cobalt, 2 )); researchCost = with( - OlItems.cobalt, 15 + OlItems.cobalt, 10 ); }}; @@ -129,7 +130,7 @@ public static void load() { OlItems.cobalt, 4 )); researchCost = with( - OlItems.cobalt, 20 + OlItems.cobalt, 25 ); pumpStrength = 5f/60f; @@ -140,8 +141,8 @@ public static void load() { pumpEffectOut = OlFx.pumpOut; pressureConfig = new PressureConfig() {{ - minPressure = -25f; - maxPressure = 25f; +// minPressure = -25f; +// maxPressure = 25f; }}; }}; @@ -165,7 +166,7 @@ public static void load() { }}; liquidValve = new PressureLiquidValve("liquid-valve") {{ - requirements(Category.liquid, with( + requirements(Category.liquid, BuildVisibility.sandboxOnly, with( OlItems.cobalt, 2, Items.beryllium, 2 )); @@ -182,11 +183,11 @@ public static void load() { liquidGauge = new PressureLiquidGauge("liquid-gauge") {{ requirements(Category.liquid, with( OlItems.cobalt, 2, - OlItems.carborundum, 1 + Items.beryllium, 1 )); researchCost = with( OlItems.cobalt, 20, - OlItems.carborundum, 10 + Items.beryllium, 10 ); }}; //endregion From a4ea4eb26a8b3cd4a3990e012efb9d9f2145bc1d Mon Sep 17 00:00:00 2001 From: Zelaux <58040045+zelaux@users.noreply.github.com> Date: Fri, 31 Jan 2025 14:32:11 +0300 Subject: [PATCH 55/67] Separated package for @Load handling --- .../annotations/lombok/{ => load}/FieldDescriptor.java | 2 +- .../lombok/{ => load}/LoadAnnotationASTVisitor.java | 2 +- .../omaloon/annotations/lombok/{ => load}/Reference.java | 2 +- .../omaloon/annotations/lombok/{ => load}/RegionName.java | 8 ++++---- .../META-INF/services/lombok.javac.JavacASTVisitor | 2 +- 5 files changed, 8 insertions(+), 8 deletions(-) rename annotations/src/main/java/omaloon/annotations/lombok/{ => load}/FieldDescriptor.java (99%) rename annotations/src/main/java/omaloon/annotations/lombok/{ => load}/LoadAnnotationASTVisitor.java (98%) rename annotations/src/main/java/omaloon/annotations/lombok/{ => load}/Reference.java (95%) rename annotations/src/main/java/omaloon/annotations/lombok/{ => load}/RegionName.java (94%) diff --git a/annotations/src/main/java/omaloon/annotations/lombok/FieldDescriptor.java b/annotations/src/main/java/omaloon/annotations/lombok/load/FieldDescriptor.java similarity index 99% rename from annotations/src/main/java/omaloon/annotations/lombok/FieldDescriptor.java rename to annotations/src/main/java/omaloon/annotations/lombok/load/FieldDescriptor.java index 6cdde894..c339598c 100644 --- a/annotations/src/main/java/omaloon/annotations/lombok/FieldDescriptor.java +++ b/annotations/src/main/java/omaloon/annotations/lombok/load/FieldDescriptor.java @@ -1,4 +1,4 @@ -package omaloon.annotations.lombok; +package omaloon.annotations.lombok.load; import com.github.javaparser.StaticJavaParser; import com.github.javaparser.ast.stmt.BlockStmt; diff --git a/annotations/src/main/java/omaloon/annotations/lombok/LoadAnnotationASTVisitor.java b/annotations/src/main/java/omaloon/annotations/lombok/load/LoadAnnotationASTVisitor.java similarity index 98% rename from annotations/src/main/java/omaloon/annotations/lombok/LoadAnnotationASTVisitor.java rename to annotations/src/main/java/omaloon/annotations/lombok/load/LoadAnnotationASTVisitor.java index 5a135680..733b63f6 100644 --- a/annotations/src/main/java/omaloon/annotations/lombok/LoadAnnotationASTVisitor.java +++ b/annotations/src/main/java/omaloon/annotations/lombok/load/LoadAnnotationASTVisitor.java @@ -1,4 +1,4 @@ -package omaloon.annotations.lombok; +package omaloon.annotations.lombok.load; import asmlib.lombok.javaparser.CompileBodyVisitor; import com.github.javaparser.StaticJavaParser; diff --git a/annotations/src/main/java/omaloon/annotations/lombok/Reference.java b/annotations/src/main/java/omaloon/annotations/lombok/load/Reference.java similarity index 95% rename from annotations/src/main/java/omaloon/annotations/lombok/Reference.java rename to annotations/src/main/java/omaloon/annotations/lombok/load/Reference.java index 861944ea..89103da3 100644 --- a/annotations/src/main/java/omaloon/annotations/lombok/Reference.java +++ b/annotations/src/main/java/omaloon/annotations/lombok/load/Reference.java @@ -1,4 +1,4 @@ -package omaloon.annotations.lombok; +package omaloon.annotations.lombok.load; import lombok.AllArgsConstructor; diff --git a/annotations/src/main/java/omaloon/annotations/lombok/RegionName.java b/annotations/src/main/java/omaloon/annotations/lombok/load/RegionName.java similarity index 94% rename from annotations/src/main/java/omaloon/annotations/lombok/RegionName.java rename to annotations/src/main/java/omaloon/annotations/lombok/load/RegionName.java index 22da7daf..8cb576b3 100644 --- a/annotations/src/main/java/omaloon/annotations/lombok/RegionName.java +++ b/annotations/src/main/java/omaloon/annotations/lombok/load/RegionName.java @@ -1,9 +1,9 @@ -package omaloon.annotations.lombok; +package omaloon.annotations.lombok.load; import lombok.Getter; -import omaloon.annotations.lombok.Reference.ExpressionReference; -import omaloon.annotations.lombok.Reference.IndexReference; -import omaloon.annotations.lombok.Reference.StringReference; +import omaloon.annotations.lombok.load.Reference.ExpressionReference; +import omaloon.annotations.lombok.load.Reference.IndexReference; +import omaloon.annotations.lombok.load.Reference.StringReference; import java.util.ArrayList; import java.util.List; diff --git a/annotations/src/main/resources/META-INF/services/lombok.javac.JavacASTVisitor b/annotations/src/main/resources/META-INF/services/lombok.javac.JavacASTVisitor index 5847eb38..bef51bea 100644 --- a/annotations/src/main/resources/META-INF/services/lombok.javac.JavacASTVisitor +++ b/annotations/src/main/resources/META-INF/services/lombok.javac.JavacASTVisitor @@ -1 +1 @@ -omaloon.annotations.lombok.LoadAnnotationASTVisitor \ No newline at end of file +omaloon.annotations.lombok.load.LoadAnnotationASTVisitor \ No newline at end of file From ad6f120f629f5156303f388ce87068cdb6f70ed4 Mon Sep 17 00:00:00 2001 From: = Date: Fri, 31 Jan 2025 12:31:11 -0300 Subject: [PATCH 56/67] slight density change --- src/omaloon/content/OlLiquids.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/omaloon/content/OlLiquids.java b/src/omaloon/content/OlLiquids.java index 3a538d99..4574f738 100644 --- a/src/omaloon/content/OlLiquids.java +++ b/src/omaloon/content/OlLiquids.java @@ -79,7 +79,7 @@ public static void addViscosity(Liquid liquid, float viscosity) { } public static float getDensity(@Nullable Liquid liquid) { - return densities.get(liquid, 1f); + return densities.get(liquid, 5f); } public static float getViscosity(@Nullable Liquid liquid) { From e402dc7731ce2d9107d69e1ccdc65b1656414bdc Mon Sep 17 00:00:00 2001 From: = Date: Fri, 31 Jan 2025 18:00:58 -0300 Subject: [PATCH 57/67] hints --- assets/bundles/bundle.properties | 4 +++- src/omaloon/ui/dialogs/EventHints.java | 17 +++++++++++++---- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/assets/bundles/bundle.properties b/assets/bundles/bundle.properties index d508b160..9b0c9807 100644 --- a/assets/bundles/bundle.properties +++ b/assets/bundles/bundle.properties @@ -65,8 +65,10 @@ omaloon.update.dialog.fullclean.confirm = Are you sure you want to reset your cu requirement.omaloon-at-wave = Reach Wave {0} in {1} ## Hints +hint.omaloon-air = Air is equivalent to pressure in it's density. So each fluid unit of air equals one pascal inside the Liquid Tube. +hint.omaloon-drill = Drills work with negative pressure, working faster with lower pressures. hint.omaloon-pump_chaining = Pumps chained in series can reach a higher pressure gradient between the ends. If they're chained in parallel, they work faster. -hint.omaloon-pump_max_min_pressure = Pumps can only pump out so much before the pressure starts damaging them. +hint.omaloon-shelter = Shelters work with positive pressure, covering a larger area at higher pressures. ## planets planet.omaloon-omaloon.name = Omaloon diff --git a/src/omaloon/ui/dialogs/EventHints.java b/src/omaloon/ui/dialogs/EventHints.java index 09ec93f5..880df303 100644 --- a/src/omaloon/ui/dialogs/EventHints.java +++ b/src/omaloon/ui/dialogs/EventHints.java @@ -6,18 +6,27 @@ import arc.util.*; import mindustry.*; import mindustry.ui.fragments.HintsFragment.*; +import omaloon.world.blocks.defense.Shelter.*; import omaloon.world.blocks.liquid.*; +import omaloon.world.blocks.production.PressureDrill.*; +import omaloon.world.interfaces.*; public enum EventHints implements Hint { + air( + () -> false, + () -> Vars.state.rules.defaultTeam.data().buildings.contains(b -> b instanceof HasPressure) + ), + drill( + () -> false, + () -> Vars.state.rules.defaultTeam.data().buildings.contains(b -> b instanceof PressureDrillBuild) + ), pump_chaining( () -> false, () -> Vars.control.input.block instanceof PressureLiquidPump ), - pump_max_min_pressure( + shelter( () -> false, - () -> - Vars.state.rules.defaultTeam.data().buildings.contains(b -> b instanceof PressureLiquidPump.PressureLiquidPumpBuild) && - Vars.control.input.block instanceof PressureLiquidPump + () -> Vars.state.rules.defaultTeam.data().buildings.contains(b -> b instanceof ShelterBuild) ); final Boolp complete; From 2112f2ff15962c5c706a019a328067275f5d1878 Mon Sep 17 00:00:00 2001 From: = Date: Sun, 2 Feb 2025 20:55:25 -0300 Subject: [PATCH 58/67] funni stat changes --- assets/bundles/bundle.properties | 16 +++++++--------- src/omaloon/content/OlLiquids.java | 2 +- .../world/blocks/production/PressureCrafter.java | 2 +- src/omaloon/world/consumers/ConsumeFluid.java | 4 ++-- src/omaloon/world/meta/OlStats.java | 5 ++--- src/omaloon/world/meta/PressureConfig.java | 4 ++-- 6 files changed, 15 insertions(+), 18 deletions(-) diff --git a/assets/bundles/bundle.properties b/assets/bundles/bundle.properties index 9b0c9807..88be8de2 100644 --- a/assets/bundles/bundle.properties +++ b/assets/bundles/bundle.properties @@ -337,15 +337,13 @@ category.omaloon-pressure = Pressure stat.omaloon-max-speed = Max Speed stat.omaloon-min-speed = Min Speed -stat.omaloon-add-fluid = Add Fluid air = Air -stat.omaloon-remove-fluid = Remove Fluid stat.omaloon-fluid-capacity = Fluid Capacity stat.omaloon-fluid-capacity.format = @x@x@ Blocks stat.omaloon-density = Density -stat.omaloon-viscosity = @%, \uC357 @ +stat.omaloon-viscosity = @% (\uC357 @) stat.omaloon-pump-strength = Pump Strength stat.omaloon-pressure-gradient = Pressure Gradient @@ -355,18 +353,18 @@ stat.omaloon-max-pressure = Max Pressure stat.omaloon-pressureflow = Speed stat.omaloon-pressure-range = Operating Range -stat.omaloon-pressure-range.format = Between \uC357 @ Pascals and \uC357 @ Pascals. +stat.omaloon-pressure-range.format = \uC357 @ to @ Pressure Units. stat.omaloon-optimal-pressure = Optimal Pressure -stat.omaloon-optimal-pressure.format = \uC357 @ Pascals (@%) +stat.omaloon-optimal-pressure.format = \uC357 @ Pressure Units (@%) ## ui units unit.omaloon-blocks-cubed = Blocks\u00B3 -unit.omaloon-density-unit = Pascals/Blocks\u00B3 -unit.omaloon-viscosity-unit = Pascal Seconds +unit.omaloon-density-unit = Pressure Units / Blocks\u00B3 +unit.omaloon-viscosity-unit = Viscosity Units -unit.omaloon-pressure-unit = Pascals -unit.omaloon-pressure-second = Pascals/Second +unit.omaloon-pressure-unit = Pressure Units +unit.omaloon-pressure-second = Pressure Units / Second bar.air = Air: diff --git a/src/omaloon/content/OlLiquids.java b/src/omaloon/content/OlLiquids.java index 4574f738..b53fe848 100644 --- a/src/omaloon/content/OlLiquids.java +++ b/src/omaloon/content/OlLiquids.java @@ -79,7 +79,7 @@ public static void addViscosity(Liquid liquid, float viscosity) { } public static float getDensity(@Nullable Liquid liquid) { - return densities.get(liquid, 5f); + return densities.get(liquid, 8f); } public static float getViscosity(@Nullable Liquid liquid) { diff --git a/src/omaloon/world/blocks/production/PressureCrafter.java b/src/omaloon/world/blocks/production/PressureCrafter.java index c4b5166e..29a6fe78 100644 --- a/src/omaloon/world/blocks/production/PressureCrafter.java +++ b/src/omaloon/world/blocks/production/PressureCrafter.java @@ -58,7 +58,7 @@ public void setStats() { stats.add(Stat.output, StatValues.liquids(1f, outputPressurizedLiquids)); } if (outputAir > 0) { - stats.add(OlStats.addFluid, OlStats.fluid(null, outputAir, 1f, true)); + stats.add(Stat.output, OlStats.fluid(null, outputAir, 1f, true)); } } diff --git a/src/omaloon/world/consumers/ConsumeFluid.java b/src/omaloon/world/consumers/ConsumeFluid.java index 8fae3ab0..78347d5a 100644 --- a/src/omaloon/world/consumers/ConsumeFluid.java +++ b/src/omaloon/world/consumers/ConsumeFluid.java @@ -66,9 +66,9 @@ public HasPressure cast(Building build) { public void display(Stats stats) { if (amount != 0) { if (continuous) { - stats.add(amount > 0 ? OlStats.removeFluid : OlStats.addFluid, OlStats.fluid(fluid, Math.abs(amount), 1f, true)); + stats.add(amount > 0 ? Stat.input : Stat.output, OlStats.fluid(fluid, Math.abs(amount), 1f, true)); } else { - stats.add(amount > 0 ? OlStats.removeFluid : OlStats.addFluid, OlStats.fluid(fluid, Math.abs(amount), 60f, false)); + stats.add(amount > 0 ? Stat.input : Stat.output, OlStats.fluid(fluid, Math.abs(amount), 60f, false)); } } diff --git a/src/omaloon/world/meta/OlStats.java b/src/omaloon/world/meta/OlStats.java index 9c2c2ace..65cca68a 100644 --- a/src/omaloon/world/meta/OlStats.java +++ b/src/omaloon/world/meta/OlStats.java @@ -18,9 +18,6 @@ public class OlStats { minSpeed = new Stat("omaloon-min-speed"), maxSpeed = new Stat("omaloon-max-speed"), - addFluid = new Stat("omaloon-add-fluid", StatCat.crafting), - removeFluid = new Stat("omaloon-remove-fluid", StatCat.crafting), - fluidCapacity = new Stat("omaloon-fluid-capacity", StatCat.liquids), density = new Stat("omaloon-density"), @@ -37,6 +34,8 @@ public class OlStats { optimalPressure = new Stat("omaloon-optimal-pressure", pressure); public static final StatUnit + blocksCubed = new StatUnit("omaloon-blocks-cubed"), + densityUnit = new StatUnit("omaloon-density-unit", "\uC357"), viscosityUnit = new StatUnit("omaloon-viscosity-unit", "\uC357"), diff --git a/src/omaloon/world/meta/PressureConfig.java b/src/omaloon/world/meta/PressureConfig.java index 7cff4ee8..e50df3a5 100644 --- a/src/omaloon/world/meta/PressureConfig.java +++ b/src/omaloon/world/meta/PressureConfig.java @@ -52,7 +52,7 @@ public class PressureConfig { /** * Standard capacity for this block. Does not define max amount that this can hold. That is defined by maxPressure and minPressure. */ - public float fluidCapacity = 5; + public float fluidCapacity = 8; /** * List of blocks that are allowed/disallowed (depends on isWhitelist true/false) for pressure connections. @@ -78,7 +78,7 @@ public class PressureConfig { }; public void addStats(Stats stats) { - stats.add(OlStats.fluidCapacity, Core.bundle.get("stat.omaloon-fluid-capacity.format"), fluidCapacity/8f, fluidCapacity/8f, fluidCapacity/8f); + stats.add(OlStats.fluidCapacity, StatValues.number(fluidCapacity/8f, OlStats.blocksCubed)); stats.add(OlStats.maxPressure, OlStats.pressure(maxPressure, true)); stats.add(OlStats.minPressure, OlStats.pressure(minPressure, true)); From 2346a87df19c21b02d68c6bc78b8f2e77cb0ee86 Mon Sep 17 00:00:00 2001 From: Elizabeth Aurora <84468589+uujuju1@users.noreply.github.com> Date: Sun, 2 Feb 2025 21:23:14 -0300 Subject: [PATCH 59/67] Update BlastTower.java --- .../world/blocks/defense/BlastTower.java | 72 +------------------ 1 file changed, 1 insertion(+), 71 deletions(-) diff --git a/src/omaloon/world/blocks/defense/BlastTower.java b/src/omaloon/world/blocks/defense/BlastTower.java index 3b1e4e62..d8d91ebc 100644 --- a/src/omaloon/world/blocks/defense/BlastTower.java +++ b/src/omaloon/world/blocks/defense/BlastTower.java @@ -103,67 +103,6 @@ public float efficiencyMultiplier() { return val; } - @Override - public void updateTile() { - updatePressure(); - dumpPressure(); - super.updateTile(); - - targets.clear(); - Units.nearbyEnemies(team, x, y, range, u -> { - if(u.checkTarget(targetAir, targetGround)) { - targets.add(u); - } - }); - - indexer.allBuildings(x, y, range, b -> { - if(b.team != team){ - targets.add(b); - } - }); - - float effMultiplier = efficiencyMultiplier(); - - if (targets.size > 0 && canConsume()) { - smoothProgress = Mathf.approach(smoothProgress, 1f, Time.delta / chargeTime * effMultiplier); - - if (efficiency > 0 && (charge += Time.delta * effMultiplier) >= reload && smoothProgress >= 0.99f) { - shoot(); - charge = 0f; - } - } else { - smoothProgress = Mathf.approach(smoothProgress, 0f, Time.delta / chargeTime * effMultiplier); - } - } - - public void shoot() { - if (!canConsume()) return; - - consume(); - lastShootTime = Time.time; - Effect.shake(shake, shake, this); - shootSound.at(this); - waveEffect.layer(Layer.blockUnder).at(x, y, range, waveColor); - tile.getLinkedTiles(t -> OlFx.hammerHit.layer(Layer.blockUnder).at( - t.worldx(), t.worldy(), - angleTo(t.worldx(), t.worldy()) + Mathf.range(360f), - Tmp.c1.set(t.floor().mapColor).mul(1.5f + Mathf.range(0.15f))) - ); - - float damageMultiplier = efficiencyMultiplier(); - for (Teamc target : targets) { - hitEffect.at(target.x(), target.y(), hitColor); - if(target instanceof Healthc){ - ((Healthc)target).damage(damage * damageMultiplier); - } - if(target instanceof Statusc){ - ((Statusc)target).apply(status, statusDuration); - } - } - - smoothProgress = 0f; - } - @Override public void draw() { Draw.rect(region, x, y); @@ -181,15 +120,6 @@ public void drawSelect(){ Drawf.dashCircle(x, y, range, Pal.accent); } - public float efficiencyMultiplier() { - float val = 1f; - if (!useConsumerMultiplier) return val; - for (Consume consumer : consumers) { - val *= consumer.efficiencyMultiplier(this); - } - return val; - } - @Override public void onProximityUpdate() { super.onProximityUpdate(); @@ -285,4 +215,4 @@ public void write(Writes write) { pressure.write(write); } } -} \ No newline at end of file +} From 08d794e51cb71cfb838842ea42b529f1ffe7a35f Mon Sep 17 00:00:00 2001 From: Zelaux <58040045+zelaux@users.noreply.github.com> Date: Mon, 3 Feb 2025 21:01:19 +0300 Subject: [PATCH 60/67] Added @AutoImplement --- annotations/build.gradle | 32 +- .../hierarchy/CollectedHierarchyInfo.java | 107 ++++++ .../lombok/hierarchy/HierarchyCollector.java | 105 ++++++ .../lombok/hierarchy/info/AbstractInfo.java | 46 +++ .../lombok/hierarchy/info/ClassInfo.java | 57 +++ .../lombok/hierarchy/info/InfoKey.java | 5 + .../lombok/hierarchy/info/InterfaceInfo.java | 69 ++++ .../remove/RemoveFromCompilationHandler.java | 46 +++ .../bytelogic/lombok/util/ContextLibrary.java | 55 +++ .../bytelogic/lombok/util/ContextTools.java | 33 ++ .../lombok/util/GeneratedByVisitor.java | 20 ++ .../main/java/bytelogic/lombok/util/Util.java | 164 +++++++++ .../omaloon/annotations/AutoImplement.java | 49 +++ .../annotations/RemoveFromCompilation.java | 8 + .../lombok/autoimpl/AutoImplContext.java | 26 ++ .../lombok/autoimpl/AutoImplUtil.java | 17 + .../lombok/autoimpl/CleanupHandler.java | 31 ++ .../lombok/autoimpl/HierarchyMarker.java | 54 +++ .../lombok/autoimpl/ImplMarker.java | 31 ++ .../lombok/autoimpl/ImplProcessor.java | 245 +++++++++++++ .../annotations/lombok/autoimpl/Paths.java | 26 ++ .../autoimpl/info/AutoImplInformation.java | 77 ++++ .../autoimpl/info/InlineApplyPrinter.java | 44 +++ .../autoimpl/info/MethodDeclarationInfo.java | 38 ++ .../lombok/autoimpl/info/MethodInfo.java | 336 ++++++++++++++++++ .../lombok/autoimpl/info/TypeInliner.java | 99 ++++++ .../lombok/load/LoadAnnotationASTVisitor.java | 13 +- .../services/lombok.javac.JavacASTVisitor | 4 +- .../lombok.javac.JavacAnnotationHandler | 3 + gradle.properties | 2 +- src/omaloon/annotations/AutoImplement.java | 49 +++ .../annotations/RemoveFromCompilation.java | 4 + .../world/blocks/defense/BlastTower.java | 21 +- .../world/blocks/defense/ConsumeTurret.java | 21 +- src/omaloon/world/blocks/defense/Shelter.java | 14 +- .../blocks/liquid/PressureLiquidBridge.java | 28 +- .../blocks/liquid/PressureLiquidConduit.java | 21 +- .../blocks/liquid/PressureLiquidJunction.java | 23 +- .../blocks/liquid/PressureLiquidPump.java | 23 +- .../blocks/liquid/PressureLiquidValve.java | 16 +- .../blocks/production/PressureCrafter.java | 25 +- .../blocks/production/PressureDrill.java | 22 +- .../blocks/sandbox/PressureLiquidSource.java | 14 +- .../blocks/sandbox/PressureLiquidVoid.java | 13 +- src/omaloon/world/interfaces/HasPressure.java | 4 +- .../world/interfaces/HasPressureImpl.java | 35 ++ 46 files changed, 1944 insertions(+), 231 deletions(-) create mode 100644 annotations/src/main/java/bytelogic/lombok/hierarchy/CollectedHierarchyInfo.java create mode 100644 annotations/src/main/java/bytelogic/lombok/hierarchy/HierarchyCollector.java create mode 100644 annotations/src/main/java/bytelogic/lombok/hierarchy/info/AbstractInfo.java create mode 100644 annotations/src/main/java/bytelogic/lombok/hierarchy/info/ClassInfo.java create mode 100644 annotations/src/main/java/bytelogic/lombok/hierarchy/info/InfoKey.java create mode 100644 annotations/src/main/java/bytelogic/lombok/hierarchy/info/InterfaceInfo.java create mode 100644 annotations/src/main/java/bytelogic/lombok/remove/RemoveFromCompilationHandler.java create mode 100644 annotations/src/main/java/bytelogic/lombok/util/ContextLibrary.java create mode 100644 annotations/src/main/java/bytelogic/lombok/util/ContextTools.java create mode 100644 annotations/src/main/java/bytelogic/lombok/util/GeneratedByVisitor.java create mode 100644 annotations/src/main/java/bytelogic/lombok/util/Util.java create mode 100644 annotations/src/main/java/omaloon/annotations/AutoImplement.java create mode 100644 annotations/src/main/java/omaloon/annotations/RemoveFromCompilation.java create mode 100644 annotations/src/main/java/omaloon/annotations/lombok/autoimpl/AutoImplContext.java create mode 100644 annotations/src/main/java/omaloon/annotations/lombok/autoimpl/AutoImplUtil.java create mode 100644 annotations/src/main/java/omaloon/annotations/lombok/autoimpl/CleanupHandler.java create mode 100644 annotations/src/main/java/omaloon/annotations/lombok/autoimpl/HierarchyMarker.java create mode 100644 annotations/src/main/java/omaloon/annotations/lombok/autoimpl/ImplMarker.java create mode 100644 annotations/src/main/java/omaloon/annotations/lombok/autoimpl/ImplProcessor.java create mode 100644 annotations/src/main/java/omaloon/annotations/lombok/autoimpl/Paths.java create mode 100644 annotations/src/main/java/omaloon/annotations/lombok/autoimpl/info/AutoImplInformation.java create mode 100644 annotations/src/main/java/omaloon/annotations/lombok/autoimpl/info/InlineApplyPrinter.java create mode 100644 annotations/src/main/java/omaloon/annotations/lombok/autoimpl/info/MethodDeclarationInfo.java create mode 100644 annotations/src/main/java/omaloon/annotations/lombok/autoimpl/info/MethodInfo.java create mode 100644 annotations/src/main/java/omaloon/annotations/lombok/autoimpl/info/TypeInliner.java create mode 100644 annotations/src/main/resources/META-INF/services/lombok.javac.JavacAnnotationHandler create mode 100644 src/omaloon/annotations/AutoImplement.java create mode 100644 src/omaloon/annotations/RemoveFromCompilation.java create mode 100644 src/omaloon/world/interfaces/HasPressureImpl.java diff --git a/annotations/build.gradle b/annotations/build.gradle index 24306a2a..8263e896 100644 --- a/annotations/build.gradle +++ b/annotations/build.gradle @@ -1,8 +1,8 @@ println("Hello from gradle") apply plugin: "java" -tasks.withType(JavaCompile).tap{ - configureEach{ +tasks.withType(JavaCompile).tap { + configureEach { options.fork = true options.compilerArgs += [ '--add-exports', 'jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED', @@ -20,22 +20,29 @@ tasks.withType(JavaCompile).tap{ ] } } -repositories{ +repositories { // Necessary Maven repositories to pull dependencies from. mavenCentral() - maven{url "https://oss.sonatype.org/content/repositories/snapshots/"} - maven{url "https://oss.sonatype.org/content/repositories/releases/"} - maven{url "https://raw.githubusercontent.com/GlennFolker/EntityAnnoMaven/main"} + maven { url "https://oss.sonatype.org/content/repositories/snapshots/" } + maven { url "https://oss.sonatype.org/content/repositories/releases/" } + maven { url "https://raw.githubusercontent.com/GlennFolker/EntityAnnoMaven/main" } // Use Zelaux's non-buggy repository for release Mindustry and Arc builds. - maven{url "https://raw.githubusercontent.com/Zelaux/MindustryRepo/master/repository"} - maven{url "https://raw.githubusercontent.com/Zelaux/Repo/master/repository" } + maven { url "https://raw.githubusercontent.com/Zelaux/MindustryRepo/master/repository" } + maven { url "https://raw.githubusercontent.com/Zelaux/Repo/master/repository" } } -dependencies{ - println(asmLib.invoke(":annotations:lombok-plugin-starter")) - println(asmLib) +/*tasks.withType(JavaCompile){ + options.debug = true + options.fork = true + options.compilerArgs.add("-g") + + options.forkOptions.jvmArgs.add( + "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5008" + ) +}*/ +dependencies { implementation asmLib.invoke(":annotations:lombok-plugin-starter") @@ -44,5 +51,6 @@ dependencies{ implementation "com.github.javaparser:javaparser-symbol-solver-core:$jparcerVersion" compileOnly "org.projectlombok:lombok:$lombokVersion" - annotationProcessor "org.projectlombok:lombok:$lombokVersion" + annotationProcessor "org.projectlombok:lombok:$lombokVersion"//,asmLib.invoke(":annotations:lombok-plugin-starter") + implementation "one.util:streamex:$streamExVersion" } \ No newline at end of file diff --git a/annotations/src/main/java/bytelogic/lombok/hierarchy/CollectedHierarchyInfo.java b/annotations/src/main/java/bytelogic/lombok/hierarchy/CollectedHierarchyInfo.java new file mode 100644 index 00000000..0b568884 --- /dev/null +++ b/annotations/src/main/java/bytelogic/lombok/hierarchy/CollectedHierarchyInfo.java @@ -0,0 +1,107 @@ +package bytelogic.lombok.hierarchy; + +import bytelogic.lombok.hierarchy.info.ClassInfo; +import bytelogic.lombok.hierarchy.info.InterfaceInfo; +import bytelogic.lombok.util.Util; +import lombok.javac.JavacNode; +import lombok.val; +import one.util.streamex.EntryStream; +import org.jetbrains.annotations.NotNull; + +import java.util.*; +import java.util.function.BiConsumer; + +public class CollectedHierarchyInfo { + public static final String JAVA_LANG_OBJECT = "java.lang.Object"; + public static final InterfaceInfo interfacesRoot = new InterfaceInfo("?interfacesRoot?", "?interfacesRoot?"); + static ClassInfo javaLangObject = new ClassInfo(JAVA_LANG_OBJECT, JAVA_LANG_OBJECT); + static Map classInfoMap; + static Map interfacesInfoMap; + + public static ClassInfo classInfo(String className) { + return classInfoMap.get(className); + } + + public static InterfaceInfo interfaceInfo(String name) { + return interfacesInfoMap.get(name); + } + + public static EntryStream interfaces() { + return EntryStream.of(interfacesInfoMap) + .removeKeys(it -> it.equals(interfacesRoot.name)); + } + + public static EntryStream classes() { + return EntryStream.of(classInfoMap); + } + + + @NotNull + public static ArrayList collectAllImpl(InterfaceInfo interfaceInfo) { + ArrayList allSubTypes = collectAllSub(interfaceInfo); + val classInfoStream = allSubTypes + .stream() + .map(it -> it.impltypes.values()) + .flatMap(Collection::stream) + .distinct() + .toArray(ClassInfo[]::new); + ; + + ArrayList implementedClasses = new ArrayList<>(); + Set visitedNames = new HashSet<>(); + class Visitor { + static void visit(Set visitedNames, ClassInfo info, ArrayList targetCollection) { + if (!visitedNames.add(info.name)) return; + targetCollection.add(info); + for (ClassInfo value : info.subtypes.values()) { + visit(visitedNames, value, targetCollection); + } + } + } + for (ClassInfo info : classInfoStream) { + Visitor.visit(visitedNames, info, implementedClasses); + } + return implementedClasses; + } + + @NotNull + public static ArrayList collectAllSub(InterfaceInfo interfaceInfo) { + ArrayList allSubTypes = new ArrayList<>(); + //noinspection unchecked + BiConsumer visitor = new BiConsumer<>() { + + Set visitedNames = new HashSet<>(); + + @Override + public void accept(String name, InterfaceInfo info) { + if (!visitedNames.add(info.name)) return; + allSubTypes.add(info); + info.subtypes.forEach(this); + } + }; + visitor.accept(interfaceInfo.name, interfaceInfo); + return allSubTypes; + } + + public static ClassInfo classInfo(JavacNode typeNode) { + return classInfo(Util.canonicalFullname(typeNode)); + } + + public static ClassInfo classInfoOrThrown(JavacNode typeNode) { + String mirrorName = Util.canonicalFullname(typeNode); + ClassInfo classInfo = classInfo(mirrorName); + if (classInfo == null) throw new RuntimeException("Cannot find info for class " + mirrorName); + return classInfo; + } + + public static InterfaceInfo interfaceInfo(JavacNode typeNode) { + return interfaceInfo(Util.canonicalFullname(typeNode)); + } + + public static InterfaceInfo interfaceInfoOrThrown(JavacNode typeNode) { + String string = Util.canonicalFullname(typeNode); + InterfaceInfo interfaceInfo = interfaceInfo(string); + if (interfaceInfo == null) throw new RuntimeException("Cannot find info for interface " + string); + return interfaceInfo; + } +} diff --git a/annotations/src/main/java/bytelogic/lombok/hierarchy/HierarchyCollector.java b/annotations/src/main/java/bytelogic/lombok/hierarchy/HierarchyCollector.java new file mode 100644 index 00000000..fe7c5cef --- /dev/null +++ b/annotations/src/main/java/bytelogic/lombok/hierarchy/HierarchyCollector.java @@ -0,0 +1,105 @@ +package bytelogic.lombok.hierarchy; + +import bytelogic.lombok.hierarchy.info.ClassInfo; +import bytelogic.lombok.hierarchy.info.InterfaceInfo; +import bytelogic.lombok.util.Util; +import com.sun.source.util.Trees; +import com.sun.tools.javac.code.Type; +import com.sun.tools.javac.model.JavacTypes; +import com.sun.tools.javac.tree.JCTree.JCClassDecl; +import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; +import lombok.NonNull; +import lombok.core.HandlerPriority; +import lombok.javac.JavacASTAdapter; +import lombok.javac.JavacNode; +import lombok.val; + +import javax.lang.model.type.TypeMirror; +import java.util.HashMap; +import java.util.List; + +import static bytelogic.lombok.hierarchy.CollectedHierarchyInfo.*; +import static bytelogic.lombok.util.Util.mirror; +import static bytelogic.lombok.util.Util.supertypes; + +@HandlerPriority(value = -10, subValue = 0) +public class HierarchyCollector extends JavacASTAdapter { + + Trees trees; + + @Override + public void visitCompilationUnit(JavacNode top, JCCompilationUnit unit) { + super.visitCompilationUnit(top, unit); + } + + @Override + public void endVisitCompilationUnit(JavacNode top, JCCompilationUnit unit) { + super.endVisitCompilationUnit(top, unit); + } + + @Override + public void visitType(JavacNode typeNode, JCClassDecl type) { + if (typeNode.getElement() == null) {//Anonymous class +// System.out.println("Warning: empty element"); + return; + } + Type selfMirror = mirror(typeNode); + List supertypes = supertypes(typeNode); + if (!Util.isInterface(type.mods)) { + + Type parent = supertypes.get(0); + indexHierarchy(parent, selfMirror, typeNode.getTypesUtil()); + ClassInfo selfInfo = getOrCreateClassInfo(selfMirror); + for (int i = 1; i < supertypes.size(); i++) { + getOrCreateInterInfo(supertypes.get(i)).addImpl(selfInfo); + } + return; + } + + + InterfaceInfo target = getOrCreateInterInfo(selfMirror); + + List list = supertypes + .stream() + .map(this::getOrCreateInterInfo) + .toList(); + + for (val info : list) { + if (target == info) continue; + info.addSub(target); + } + + } + + private void indexHierarchy(@NonNull Type parent, @NonNull Type subtype, JavacTypes typesUtil) { + + ClassInfo parentInfo = getOrCreateClassInfo(parent); + ClassInfo subInfo = getOrCreateClassInfo(subtype); + + parentInfo.addSub(subInfo); + + if (parent.toString().equals(CollectedHierarchyInfo.JAVA_LANG_OBJECT)) return; + Type newParent = supertypes(parent, typesUtil).get(0); + indexHierarchy(newParent, parent, typesUtil); + } + + private ClassInfo getOrCreateClassInfo(Type mirror) { + return classInfoMap.computeIfAbsent(mirror.toString(), name -> new ClassInfo(mirror)); + } + private InterfaceInfo getOrCreateInterInfo(Type mirror) { + String string = mirror.toString(); + if(string.equals(JAVA_LANG_OBJECT))return interfacesRoot; + return interfacesInfoMap.computeIfAbsent(string, type -> new InterfaceInfo(mirror)); + } + + + @Override + public void setTrees(Trees trees) { + this.trees = (trees); + + classInfoMap = new HashMap<>(); + classInfoMap.put(javaLangObject.name, javaLangObject); + interfacesInfoMap = new HashMap<>(); + interfacesInfoMap.put(interfacesRoot.name,interfacesRoot); + } +} diff --git a/annotations/src/main/java/bytelogic/lombok/hierarchy/info/AbstractInfo.java b/annotations/src/main/java/bytelogic/lombok/hierarchy/info/AbstractInfo.java new file mode 100644 index 00000000..aca72f6b --- /dev/null +++ b/annotations/src/main/java/bytelogic/lombok/hierarchy/info/AbstractInfo.java @@ -0,0 +1,46 @@ +package bytelogic.lombok.hierarchy.info; + +import com.sun.tools.javac.code.Type; +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NonNull; +import lombok.experimental.FieldDefaults; +import org.jetbrains.annotations.Nullable; + +import java.util.HashMap; +import java.util.Map; + +@AllArgsConstructor +@FieldDefaults(level = AccessLevel.PUBLIC) +public class AbstractInfo { + @NonNull + @Getter + final String name; + @NonNull + @Getter + final String flatName; + private final Map, Object> infoMap = new HashMap<>(); + + public AbstractInfo(Type type) { + this(type.toString(),type.tsym.flatName().toString()); + } + + @Nullable + public T get(InfoKey key) { + //noinspection unchecked + return (T) infoMap.get(key); + } + + @Override + public int hashCode() { + return name.hashCode(); + } + + public void put(InfoKey key, T value) { + infoMap.put(key, value); + } + public boolean has(InfoKey key) { + return infoMap.containsKey(key); + } +} diff --git a/annotations/src/main/java/bytelogic/lombok/hierarchy/info/ClassInfo.java b/annotations/src/main/java/bytelogic/lombok/hierarchy/info/ClassInfo.java new file mode 100644 index 00000000..f0ff8d9a --- /dev/null +++ b/annotations/src/main/java/bytelogic/lombok/hierarchy/info/ClassInfo.java @@ -0,0 +1,57 @@ +package bytelogic.lombok.hierarchy.info; + +import com.sun.tools.javac.code.Type; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.NonNull; +import lombok.RequiredArgsConstructor; +import lombok.experimental.FieldDefaults; +import org.jetbrains.annotations.Nullable; + +import java.util.HashMap; +import java.util.Map; +import java.util.function.Consumer; + + +@FieldDefaults(level = AccessLevel.PUBLIC) +public class ClassInfo extends AbstractInfo { + final Map subtypes = new HashMap<>(); + + @Nullable + private ClassInfo parent; + + public ClassInfo(@NonNull String name, @NonNull String flatName) { + super(name, flatName); + } + + public ClassInfo(Type type) { + super(type); + } + + + public ClassInfo parent() { + return parent; + } + + @Override + public boolean equals(Object obj) { + return obj == this || obj instanceof ClassInfo info && info.name.equals(name); + } + + + public void visitSubtypes(Consumer visitor, boolean visitDeep, boolean visitSelf) { + if (visitSelf) visitor.accept(this); + if (!visitDeep) { + subtypes.values().forEach(visitor); + return; + } + for (ClassInfo info : subtypes.values()) { + info.visitSubtypes(visitor, true, true); + } + } + + public void addSub(ClassInfo subInfo) { + subtypes.put(subInfo.name, subInfo); + subInfo.parent = this; + } +} diff --git a/annotations/src/main/java/bytelogic/lombok/hierarchy/info/InfoKey.java b/annotations/src/main/java/bytelogic/lombok/hierarchy/info/InfoKey.java new file mode 100644 index 00000000..b040b857 --- /dev/null +++ b/annotations/src/main/java/bytelogic/lombok/hierarchy/info/InfoKey.java @@ -0,0 +1,5 @@ +package bytelogic.lombok.hierarchy.info; + +public class InfoKey { + +} diff --git a/annotations/src/main/java/bytelogic/lombok/hierarchy/info/InterfaceInfo.java b/annotations/src/main/java/bytelogic/lombok/hierarchy/info/InterfaceInfo.java new file mode 100644 index 00000000..8b719e87 --- /dev/null +++ b/annotations/src/main/java/bytelogic/lombok/hierarchy/info/InterfaceInfo.java @@ -0,0 +1,69 @@ +package bytelogic.lombok.hierarchy.info; + +import com.sun.tools.javac.code.Type; +import lombok.AccessLevel; +import lombok.NonNull; +import lombok.RequiredArgsConstructor; +import lombok.experimental.FieldDefaults; +import org.jetbrains.annotations.Nullable; + +import java.util.HashMap; +import java.util.Map; +import java.util.function.Consumer; + +@FieldDefaults(level = AccessLevel.PUBLIC) +public class InterfaceInfo extends AbstractInfo { + + final Map subtypes = new HashMap<>(); + final Map impltypes = new HashMap<>(); + private final Map, Object> infoMap = new HashMap<>(); + /** + * interface It extends It1,It2,It2{ + * + * } + * + * It.supertypes={ + * "It1":It1, + * "It2":It2, + * "It3":It3 + * } + * */ + public Map supertypes = new HashMap<>(); + + public InterfaceInfo(@NonNull String name, @NonNull String flatName) { + super(name, flatName); + } + + public InterfaceInfo(Type type) { + super(type); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + return o instanceof InterfaceInfo info && name.equals(info.name); + } + + + public void visitSubtypes(Consumer visitor, boolean visitDeep, boolean visitSelf) { + if (visitSelf) visitor.accept(this); + if (!visitDeep) { + subtypes.values().forEach(visitor); + return; + } + for (InterfaceInfo info : subtypes.values()) { + info.visitSubtypes(visitor, true, true); + } + } + + public void addSub(InterfaceInfo subInfo) { + subtypes.put(subInfo.name, subInfo); + subInfo.supertypes.put(name, this); + } + + public void addImpl(ClassInfo info) { + impltypes.put(info.name, info); + } + + +} diff --git a/annotations/src/main/java/bytelogic/lombok/remove/RemoveFromCompilationHandler.java b/annotations/src/main/java/bytelogic/lombok/remove/RemoveFromCompilationHandler.java new file mode 100644 index 00000000..6bb39afd --- /dev/null +++ b/annotations/src/main/java/bytelogic/lombok/remove/RemoveFromCompilationHandler.java @@ -0,0 +1,46 @@ +package bytelogic.lombok.remove; + +import com.sun.tools.javac.tree.*; +import com.sun.tools.javac.tree.JCTree.*; +import com.sun.tools.javac.util.*; +import lombok.core.*; +import lombok.javac.*; +import omaloon.annotations.RemoveFromCompilation; + +import java.util.function.*; + +public class RemoveFromCompilationHandler extends JavacAnnotationHandler{ + + @Override + public void handle(AnnotationValues annotationValues, JCAnnotation jcAnnotation, JavacNode javacNode){ + JavacNode element = javacNode.up(); + JavacNode parent = element.up(); + JCTree o = element.get(); + List defs = null; + Consumer> consumer; + if(parent.get() instanceof JCClassDecl it){ + defs = it.defs; + consumer=val->it.defs=val; + }else if(parent.get() instanceof JCCompilationUnit it){ + defs = it.defs; + consumer=val->it.defs=val; + }else{ + javacNode.addError("Unsupported parent (" + parent.get().getKind() + ")"); + return; + } + List prev = null; + while(defs != null && defs.head != o){ + prev = defs; + defs = defs.tail; + } + if(defs == null){ + javacNode.addError("Stange, I cant find annotated element in parent"); + return; + } + if(prev==null){ + consumer.accept(defs.tail); + return; + } + prev.tail=defs.tail; + } +} diff --git a/annotations/src/main/java/bytelogic/lombok/util/ContextLibrary.java b/annotations/src/main/java/bytelogic/lombok/util/ContextLibrary.java new file mode 100644 index 00000000..760f0868 --- /dev/null +++ b/annotations/src/main/java/bytelogic/lombok/util/ContextLibrary.java @@ -0,0 +1,55 @@ +package bytelogic.lombok.util; + +import com.sun.tools.javac.tree.JCTree; +import com.sun.tools.javac.util.Context; +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.With; +import lombok.core.TypeLibrary; +import lombok.javac.JavacNode; +import lombok.javac.JavacResolution; +import org.jetbrains.annotations.Contract; + +import java.util.Map; + +@AllArgsConstructor(access = AccessLevel.PROTECTED) +@With +@Getter +public class ContextLibrary { + public final JavacNode context; + public final TypeLibrary library; + public final JavacResolution resolution; + public final Map resolvedParts; + + public static ContextLibrary makeLib(JavacNode contextNode, TypeLibrary library) { + Context context = contextNode.getContext(); + JavacResolution javacResolution = Util.resolution(context); + return new ContextLibrary( + contextNode, + library, + javacResolution, + javacResolution.resolveMethodMember(contextNode) + ); + } + + public static ContextLibrary ofClasses(JavacNode context) { + return makeLib(context, Util.buildClassLibrary(context)); + } + + @Contract("null -> null") + public String className(JCTree typeRepresentation) { + if (typeRepresentation == null) return null; + String resolved = resolveFull(typeRepresentation.toString()); + if(resolved==null){ + return resolvedParts.get(typeRepresentation).type.toString(); + } + return resolved; + } + + + public String resolveFull(String string) { + return context.getImportListAsTypeResolver() + .typeRefToFullyQualifiedName(context, library, string); + } +} diff --git a/annotations/src/main/java/bytelogic/lombok/util/ContextTools.java b/annotations/src/main/java/bytelogic/lombok/util/ContextTools.java new file mode 100644 index 00000000..a59483cb --- /dev/null +++ b/annotations/src/main/java/bytelogic/lombok/util/ContextTools.java @@ -0,0 +1,33 @@ +package bytelogic.lombok.util; + +import com.sun.tools.javac.code.Symtab; +import com.sun.tools.javac.parser.ParserFactory; +import com.sun.tools.javac.util.Context; +import com.sun.tools.javac.util.Names; +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.experimental.FieldDefaults; +import lombok.javac.JavacNode; +import lombok.javac.JavacResolution; + +@AllArgsConstructor +@FieldDefaults(level = AccessLevel.PUBLIC,makeFinal = true) +public class ContextTools { + JavacResolution resolution; + Names names; + Symtab symtab; + ParserFactory parserFactory; + public static ContextTools make(Context context){ + + return new ContextTools( + Util.resolution(context), + Names.instance(context), + Symtab.instance(context), + ParserFactory.instance(context) + ); + } + + public static ContextTools make(JavacNode typeNode) { + return make(typeNode.getContext()); + } +} diff --git a/annotations/src/main/java/bytelogic/lombok/util/GeneratedByVisitor.java b/annotations/src/main/java/bytelogic/lombok/util/GeneratedByVisitor.java new file mode 100644 index 00000000..2346b6b4 --- /dev/null +++ b/annotations/src/main/java/bytelogic/lombok/util/GeneratedByVisitor.java @@ -0,0 +1,20 @@ +package bytelogic.lombok.util; + +import com.github.javaparser.ast.visitor.TreeVisitor; +import com.sun.source.tree.Tree; +import com.sun.source.util.TreeScanner; +import com.sun.tools.javac.tree.JCTree; +import lombok.AllArgsConstructor; +import lombok.javac.JavacNode; + +@AllArgsConstructor +public class GeneratedByVisitor extends TreeScanner { + public final JavacNode contextNode; + public final JCTree sourceNode; + + @Override + public Void scan(Tree tree, Void unused) { + Util.setGeneratedBy((JCTree) tree, contextNode, sourceNode); + return super.scan(tree, unused); + } +} diff --git a/annotations/src/main/java/bytelogic/lombok/util/Util.java b/annotations/src/main/java/bytelogic/lombok/util/Util.java new file mode 100644 index 00000000..13713bda --- /dev/null +++ b/annotations/src/main/java/bytelogic/lombok/util/Util.java @@ -0,0 +1,164 @@ +package bytelogic.lombok.util; + +import asmlib.lombok.javaparser.CompileBodyVisitor; +import com.sun.tools.javac.code.Symtab; +import com.sun.tools.javac.code.Type; +import com.sun.tools.javac.model.JavacTypes; +import com.sun.tools.javac.tree.JCTree; +import com.sun.tools.javac.util.Context; +import lombok.NonNull; +import lombok.SneakyThrows; +import lombok.core.TypeLibrary; +import lombok.javac.Javac; +import lombok.javac.JavacAugments; +import lombok.javac.JavacNode; +import lombok.javac.JavacResolution; +import lombok.javac.handlers.JavacHandlerUtil; +import one.util.streamex.StreamEx; +import org.jetbrains.annotations.Contract; +import org.jetbrains.annotations.NotNull; + +import javax.lang.model.type.TypeMirror; +import java.lang.reflect.Field; +import java.util.List; +import java.util.Map; + +import static com.sun.tools.javac.code.Flags.INTERFACE; + +public class Util { + + public static List supertypes(JavacNode typeNode) { + return supertypes(mirror(typeNode), typeNode.getTypesUtil()); + } + + public static List supertypes(TypeMirror mirror, JavacTypes typesUtil) { + if (mirror != null && mirror.toString().equals("java.lang.Object")) return List.of(); + return typesUtil.directSupertypes(mirror); + } + + public static Type mirror(JavacNode typeNode) { + return (Type) typeNode.getElement().asType(); + } + + public static boolean isInterface(JCTree.JCModifiers modifiers) { + return (modifiers.flags & INTERFACE) != 0; + } + + public static Type supertype(JavacNode typeNode) { + return supertypes(typeNode).get(0); + } + + @Contract("_,null->null;_, !null -> !null") + public static String methodDesc(@NonNull JavacNode context, JCTree.JCMethodDecl decl) { + return methodDesc(ContextLibrary.ofClasses(context), decl); + } + + @Contract("_, null->null; _, !null -> !null") + public static String methodDesc(ContextLibrary library, JCTree.JCMethodDecl decl) { + if (decl == null) return null; + String ret = library.className(decl.getReturnType()); + String params = StreamEx.of(decl.getParameters()) + .map(JCTree.JCVariableDecl::getType) + .map(library::className) + .joining(";", "(", ")"); + return decl.name.toString() + params + ";" + ret; + } + + @SneakyThrows + @NotNull + public static TypeLibrary buildClassLibrary(@NotNull JavacNode context) { + TypeLibrary library = new TypeLibrary(); + StreamEx.of(context) + .map(JavacNode::getSymbolTable) + .map(Symtab::getAllClasses) + .map(Iterable::iterator) + .flatMap(StreamEx::of) + .map(it -> it.flatname.toString()) + .forEach(library::addType); + String[] primitives = { + "byte", "short", "char", "int", "long", + "float", "double", + "boolean", + "void" + }; + Field field = TypeLibrary.class.getDeclaredField("unqualifiedToQualifiedMap"); + field.setAccessible(true); + //noinspection unchecked + final Map unqualifiedToQualifiedMap = (Map) field.get(library); + + for (String primitive : primitives) { + unqualifiedToQualifiedMap.put(primitive, primitive); + } + library.lock(); + return library; + } + + @Contract("null -> null; !null -> !null") + public static JavacNode extractCompilationUnit(JavacNode javacNode) { + if (javacNode == null) return null; + return javacNode.top(); + } + + public static String canonicalFullname(JavacNode typeNode) { + return mirror(typeNode).toString(); + } + + public static String reflectionFullname(JavacNode typeNode) { + return mirror(typeNode).tsym.flatName().toString(); + } + + @NotNull + public static CompileBodyVisitor transformer(JavacNode typeNode) { + return new CompileBodyVisitor( + typeNode.getTreeMaker(), + typeNode.getAst(), + typeNode.getContext() + ); + } + + @NotNull + public static JavacResolution resolution(Context context) { + JavacResolution javacResolution = context.get(JavacResolution.class); + if (javacResolution == null) { + context.put(JavacResolution.class, javacResolution = new JavacResolution(context)); + } + return javacResolution; + } + + public static U resolveSym(JavacNode node) { + JavacResolution resolution = resolution(node.getContext()); + //noinspection unchecked + return (U) resolution.resolveMethodMember(node).get(node.get()); + + } + + public static T setGeneratedBy(T node, JavacNode contextNode, JCTree sourceTree) { + if (node == null) return null; + if (sourceTree == null) { + JavacAugments.JCTree_generatedNode.clear(node); + return node; + } + JavacAugments.JCTree_generatedNode.set(node, sourceTree); + if (JavacAugments.JCTree_keepPosition.get(node)) { + return node; + } + if (JavacHandlerUtil.inNetbeansEditor(contextNode.getContext()) && !JavacHandlerUtil.isParameter(node)) { + return node; + } + node.pos = sourceTree.getPreferredPosition(); + Javac.storeEnd(node, contextNode.getEndPosition(sourceTree), (JCTree.JCCompilationUnit) (contextNode.top()).get()); + return node; + + } + + public static String methodSymbolString(ContextLibrary library, JCTree.JCMethodDecl decl) { + if (decl == null) return null; + + String params = StreamEx.of(decl.getParameters()) + .map(JCTree.JCVariableDecl::getType) + .map(library::className) + .joining(",", "(", ")"); + ; + return decl.name.toString() + params; + } +} diff --git a/annotations/src/main/java/omaloon/annotations/AutoImplement.java b/annotations/src/main/java/omaloon/annotations/AutoImplement.java new file mode 100644 index 00000000..77406236 --- /dev/null +++ b/annotations/src/main/java/omaloon/annotations/AutoImplement.java @@ -0,0 +1,49 @@ +package omaloon.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Target; + +@Target(ElementType.TYPE) +public @interface AutoImplement { + + + @Target(ElementType.METHOD) + @interface NoInject { + + } + + + /** + * This need ONLY for Annotation Processing, and it will be removed during compilation + */ + interface Util { + static T Inject(Class type, Object... args) { + return error(); + } + + static T Param(String paramName, String defaultExpression) { + return error(); + } + + static T error() { + throw new RuntimeException("Why are you calling this?! This need ONLY for Annotation Processing and it will be removed during compilation"); + } + + + @interface SetParam { + String name(); + String value(); + } + } + + + public @interface Inject { + InjectPosition value(); + boolean shouldAddSuper() default true; + enum InjectPosition{ + AfterSuper,BeforeSuper, + + Head,Tail; + } + } +} diff --git a/annotations/src/main/java/omaloon/annotations/RemoveFromCompilation.java b/annotations/src/main/java/omaloon/annotations/RemoveFromCompilation.java new file mode 100644 index 00000000..d8adda1d --- /dev/null +++ b/annotations/src/main/java/omaloon/annotations/RemoveFromCompilation.java @@ -0,0 +1,8 @@ +package omaloon.annotations; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +@Retention(RetentionPolicy.SOURCE) +public @interface RemoveFromCompilation { +} diff --git a/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/AutoImplContext.java b/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/AutoImplContext.java new file mode 100644 index 00000000..79beca29 --- /dev/null +++ b/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/AutoImplContext.java @@ -0,0 +1,26 @@ +package omaloon.annotations.lombok.autoimpl; + +import bytelogic.lombok.util.GeneratedByVisitor; +import com.sun.tools.javac.tree.JCTree; +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.experimental.FieldDefaults; +import lombok.javac.JavacNode; + +import java.util.Map; + +@AllArgsConstructor +@Builder +@FieldDefaults(level = AccessLevel.PUBLIC) +public class AutoImplContext { + Map paramMap; + JavacNode callerTypeNode; + JavacNode callerMethodNode; + JCTree.JCExpression producerNode; + boolean justCreated; + + public GeneratedByVisitor generatedBy() { + return new GeneratedByVisitor(callerTypeNode, producerNode); + } +} diff --git a/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/AutoImplUtil.java b/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/AutoImplUtil.java new file mode 100644 index 00000000..5a6b527e --- /dev/null +++ b/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/AutoImplUtil.java @@ -0,0 +1,17 @@ +package omaloon.annotations.lombok.autoimpl; + +import com.sun.tools.javac.tree.JCTree; +import com.sun.tools.javac.util.ListBuffer; +import omaloon.annotations.AutoImplement; + +public class AutoImplUtil { + public static void removeAutoImplAnnos(JCTree.JCModifiers mods) { + ListBuffer newAnnotations = new ListBuffer<>(); + for (JCTree.JCAnnotation annotation : mods.annotations) { + if (annotation.attribute.type.toString().startsWith(AutoImplement.class.getCanonicalName())) + continue; + newAnnotations.add(annotation); + } + mods.annotations = newAnnotations.toList(); + } +} diff --git a/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/CleanupHandler.java b/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/CleanupHandler.java new file mode 100644 index 00000000..96d3c3b1 --- /dev/null +++ b/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/CleanupHandler.java @@ -0,0 +1,31 @@ +package omaloon.annotations.lombok.autoimpl; + +import com.sun.tools.javac.code.Flags; +import com.sun.tools.javac.tree.JCTree; +import com.sun.tools.javac.util.List; +import lombok.AllArgsConstructor; +import lombok.core.AlreadyHandledAnnotations; +import lombok.core.AnnotationValues; +import lombok.core.HandlerPriority; +import lombok.javac.JavacAnnotationHandler; +import lombok.javac.JavacNode; +import omaloon.annotations.AutoImplement; +import one.util.streamex.StreamEx; + +@AlreadyHandledAnnotations +public class CleanupHandler extends JavacAnnotationHandler { + + @Override + public void handle(AnnotationValues annotationValues, JCTree.JCAnnotation jcAnnotation, JavacNode javacNode) { + JCTree.JCClassDecl decl = (JCTree.JCClassDecl) javacNode.up().get(); + decl.defs=List.from(StreamEx.of(decl.defs).filter(it->!(it instanceof JCTree.JCVariableDecl))); + for (JCTree def : decl.defs) { + if(!(def instanceof JCTree.JCMethodDecl methodDecl))continue; + AutoImplUtil.removeAutoImplAnnos(methodDecl.mods); + if ((methodDecl.mods.flags& Flags.DEFAULT)==0) continue; + methodDecl.mods.flags&=~Flags.DEFAULT; + methodDecl.body=null; + } + javacNode.getAst().setChanged(); + } +} diff --git a/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/HierarchyMarker.java b/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/HierarchyMarker.java new file mode 100644 index 00000000..74a6649f --- /dev/null +++ b/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/HierarchyMarker.java @@ -0,0 +1,54 @@ +package omaloon.annotations.lombok.autoimpl; + +import bytelogic.lombok.hierarchy.CollectedHierarchyInfo; +import bytelogic.lombok.hierarchy.info.ClassInfo; +import bytelogic.lombok.hierarchy.info.InfoKey; +import bytelogic.lombok.hierarchy.info.InterfaceInfo; +import bytelogic.lombok.util.Util; +import com.sun.source.util.Trees; +import com.sun.tools.javac.tree.JCTree.JCClassDecl; +import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; +import lombok.core.HandlerPriority; +import lombok.javac.JavacASTAdapter; +import lombok.javac.JavacNode; +import lombok.javac.ResolutionResetNeeded; + +import java.util.ArrayList; + +import static bytelogic.lombok.util.Util.mirror; + +//0b10000000000000000000000000000010 +@HandlerPriority(value = -5) +@ResolutionResetNeeded +public class HierarchyMarker extends JavacASTAdapter { + public static InfoKey hasSavingProcKey = new InfoKey<>(); + Trees trees; + + @Override + public void visitCompilationUnit(JavacNode top, JCCompilationUnit unit) { + super.visitCompilationUnit(top, unit); + } + + @Override + public void endVisitCompilationUnit(JavacNode top, JCCompilationUnit unit) { + super.endVisitCompilationUnit(top, unit); + } + + @Override + public void visitType(JavacNode typeNode, JCClassDecl type) { + if (typeNode.getElement() == null) return;//Anonymous classes + if (!typeNode.getName().equals("CustomSaveBuilding") || !Util.isInterface(type.mods)) return; + + InterfaceInfo interfaceInfo = CollectedHierarchyInfo.interfaceInfo(mirror(typeNode).toString()); + ArrayList implementedClasses = CollectedHierarchyInfo.collectAllImpl(interfaceInfo); + + for (ClassInfo info : implementedClasses) + info.put(hasSavingProcKey, true); + + } + + @Override + public void setTrees(Trees trees) { + this.trees = (trees); + } +} diff --git a/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/ImplMarker.java b/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/ImplMarker.java new file mode 100644 index 00000000..80e0fadb --- /dev/null +++ b/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/ImplMarker.java @@ -0,0 +1,31 @@ +package omaloon.annotations.lombok.autoimpl; + +import bytelogic.lombok.hierarchy.CollectedHierarchyInfo; +import bytelogic.lombok.hierarchy.info.InfoKey; +import bytelogic.lombok.hierarchy.info.InterfaceInfo; +import com.sun.tools.javac.tree.JCTree; +import lombok.core.AnnotationValues; +import lombok.core.HandlerPriority; +import lombok.javac.JavacAnnotationHandler; +import lombok.javac.JavacNode; +import lombok.javac.ResolutionResetNeeded; +import omaloon.annotations.AutoImplement; +import omaloon.annotations.lombok.autoimpl.info.AutoImplInformation; + +//0b10000000000000000000000000000010 +@HandlerPriority(value = -10,subValue = 10) +@ResolutionResetNeeded +public class ImplMarker extends JavacAnnotationHandler { + public static InfoKey isAutoImpl = new InfoKey<>(); + + static boolean hasAutoImplData(InterfaceInfo it) { + return it.has(isAutoImpl); + } + + @Override + public void handle(AnnotationValues annotationValues, JCTree.JCAnnotation jcAnnotation, JavacNode annotationNode) { + ImplProcessor.setUpdated(); + CollectedHierarchyInfo.interfaceInfo(annotationNode.up()).put(isAutoImpl, + AutoImplInformation.build(annotationValues,jcAnnotation,annotationNode)); + } +} diff --git a/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/ImplProcessor.java b/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/ImplProcessor.java new file mode 100644 index 00000000..f3db245b --- /dev/null +++ b/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/ImplProcessor.java @@ -0,0 +1,245 @@ +package omaloon.annotations.lombok.autoimpl; + +import bytelogic.lombok.hierarchy.CollectedHierarchyInfo; +import bytelogic.lombok.hierarchy.info.AbstractInfo; +import bytelogic.lombok.hierarchy.info.ClassInfo; +import bytelogic.lombok.hierarchy.info.InterfaceInfo; +import bytelogic.lombok.util.Util; +import com.sun.tools.javac.code.Flags; +import com.sun.tools.javac.tree.JCTree; +import com.sun.tools.javac.tree.TreeCopier; +import com.sun.tools.javac.tree.TreeMaker; +import lombok.AllArgsConstructor; +import lombok.NonNull; +import lombok.core.*; +import lombok.javac.JavacAST; +import lombok.javac.JavacASTAdapter; +import lombok.javac.JavacNode; +import lombok.javac.JavacTreeMaker; +import lombok.javac.handlers.JavacHandlerUtil; +import omaloon.annotations.AutoImplement; +import omaloon.annotations.lombok.autoimpl.info.AutoImplInformation; +import omaloon.annotations.lombok.autoimpl.info.MethodInfo; +import omaloon.annotations.lombok.autoimpl.info.TypeInliner; +import one.util.streamex.EntryStream; +import one.util.streamex.StreamEx; + +import java.util.*; +import java.util.function.BiConsumer; +import java.util.function.Function; + +import static bytelogic.lombok.hierarchy.CollectedHierarchyInfo.interfaces; +import static bytelogic.lombok.util.Util.canonicalFullname; + +@HandlerPriority(value = -10, subValue = 20) +public class ImplProcessor extends JavacASTAdapter { + private static boolean updated; + private Set autoImplClasses; + private TypeLibrary interfacesLibrary; + private Map> simpleInterfaceToAutoImpl; + + public static void setUpdated() { + updated = true; + } + + private static ArrayList flatInterfaceSuper(InterfaceInfo info) { + + ArrayList flatten = new ArrayList<>(); + BiConsumer consumer = new BiConsumer<>() { + Set nameSet = new HashSet<>(); + + @Override + public void accept(String s, InterfaceInfo info) { + if (info == CollectedHierarchyInfo.interfacesRoot || !nameSet.add(s)) return; + flatten.add(info); + info.supertypes.forEach(this); + + } + }; + consumer.accept(info.name, info); + return flatten; + } + + @Override + public void visitCompilationUnit(JavacNode top, JCTree.JCCompilationUnit unit) { + if (!updated) return; + updated = false; + + interfacesLibrary = new TypeLibrary(); + interfaces() + .values() + .map(AbstractInfo::getFlatName) + .forEach(interfacesLibrary::addType); + + interfacesLibrary.lock(); + + autoImplClasses = interfaces() + .values() + .filter(ImplMarker::hasAutoImplData) + .map(CollectedHierarchyInfo::collectAllImpl) + .flatMap(StreamEx::of) + .map(ClassInfo::getName) + .toSet(); + simpleInterfaceToAutoImpl = interfaces() + .values() + + //TODO guess alphabetic order moment + .mapToEntry(ImplProcessor::flatInterfaceSuper) + .mapValues(it -> it + .stream() + .filter(ImplMarker::hasAutoImplData) + .toList() + ).filterValues(it -> !it.isEmpty()) + .mapValues(ArrayList::new) + .toMap(); + + } + + @Override + public void visitType(JavacNode typeNode, JCTree.JCClassDecl type) { + if (typeNode.getElement() == null) { + + return; + } + if (!autoImplClasses.contains(canonicalFullname(typeNode))) return; + + InfoAndPos[] interfaceInfos = StreamEx + .of(type.implementing) + .mapToEntry(Function.identity()) + .mapKeys(Object::toString) + .filterKeys(string -> !string.contains("<")) //TODO Generic implement + .mapKeys(it -> Paths.fullifyName(typeNode, it, interfacesLibrary)) + .mapKeys(CollectedHierarchyInfo::interfaceInfo) + .nonNullKeys() + .mapKeys(simpleInterfaceToAutoImpl::get) + .flatMapKeys(StreamEx::of) + .distinctKeys() + .mapKeyValue(InfoAndPos::new) + .toArray(InfoAndPos[]::new); + + for (InfoAndPos info : interfaceInfos) { + + implement(info.info, info.producer, typeNode, type); + } + + } + + private void implement(InterfaceInfo info, @NonNull JCTree.JCExpression producer, JavacNode typeNode, JCTree.JCClassDecl type) { + AutoImplInformation information = info.get(ImplMarker.isAutoImpl); + Map>> childrenMap = StreamEx + .of(typeNode.down().iterator()) + .mapToEntry(LombokNode::getKind, Function.identity()) + .sortedBy(Map.Entry::getKey) + .collapseKeys() + .mapValues(StreamEx::of) + .mapValues(it -> it.mapToEntry(JavacNode::getName, Function.identity())) + .mapValues(it -> it.collapseKeys().sortedBy(Map.Entry::getKey).toMap()) + .toMap(); + Map fields = EntryStream + .of(childrenMap.getOrDefault(AST.Kind.FIELD, new HashMap<>())) + .mapValues(it -> it.get(0)) + .toMap(); + for (Map.Entry entry : information.fields.entrySet()) { + JavacNode existed = fields.get(entry.getKey()); + AutoImplInformation.FieldInfo fieldInfo = entry.getValue(); + if (existed != null) { + existed.addError("Cannot insert field %s.%s. Field with this name already exists.".formatted( + fieldInfo.intefaceName, fieldInfo.name + )); + continue; + } + JavacTreeMaker m = typeNode.getTreeMaker(); + TreeMaker imaker = m.getUnderlyingTreeMaker(); + + JavacAST ast = typeNode.getAst(); + + + TreeCopier copier = new TreeCopier<>(imaker); + + JCTree.JCVariableDecl decl = TypeInliner.copyWithInlineTypes(fieldInfo.fieldNode); + JCTree.JCVariableDecl newChild = m.VarDef( + m.Modifiers(decl.mods.flags & ~Flags.STATIC), + ast.toName(fieldInfo.name), + copier.copy(decl.vartype), + copier.copy(decl.init) + ); + type.defs = type.defs.append(newChild); + typeNode.add( + newChild, + AST.Kind.FIELD); + } + + Map methods = EntryStream + .of(childrenMap.get(AST.Kind.METHOD)) + .values() + .flatMap(StreamEx::of) + .mapToEntry(it -> Util.methodDesc(it, (JCTree.JCMethodDecl) it.get()), Function.identity()) + .toMap(); + + + for (Map.Entry entry : information.methods.entrySet()) { + String methodDecs = entry.getKey(); + MethodInfo methodInfo = entry.getValue(); + JavacNode existed = methods.get(methodDecs); + JCTree.JCMethodDecl decl; + + + AutoImplContext.AutoImplContextBuilder contextBuilder = AutoImplContext + .builder() + .callerTypeNode(typeNode) + .producerNode(producer); + if (existed == null) { + contextBuilder + .paramMap(collectParams(typeNode)) + .justCreated(true); + decl = methodInfo.make(contextBuilder.build()); + JavacHandlerUtil.injectMethod(typeNode, decl); + JavacNode nodeFor = typeNode.getNodeFor(decl); + methods.put(methodDecs, nodeFor); + contextBuilder.callerMethodNode(nodeFor); + } else { + contextBuilder + .paramMap(collectParams(existed)) + .callerMethodNode(existed) + .justCreated(false); + decl = (JCTree.JCMethodDecl) existed.get(); + + } + methodInfo.join(decl, contextBuilder.build()); + + } + } + + private Map collectParams(JavacNode typeNode) { + JavacNode node = typeNode; + Map map = new HashMap<>(); + JavacAST ast = typeNode.getAst(); + while (node != null) { + JCTree.JCModifiers mods = + switch (typeNode.getKind()) { + case TYPE -> ((JCTree.JCClassDecl) typeNode.get()).mods; + case FIELD -> ((JCTree.JCVariableDecl) typeNode.get()).mods; + case METHOD -> ((JCTree.JCMethodDecl) typeNode.get()).mods; + case COMPILATION_UNIT, INITIALIZER, ANNOTATION, ARGUMENT, LOCAL, STATEMENT, TYPE_USE -> null; + }; + if (mods != null) { + + for (JCTree.JCAnnotation annotation : mods.annotations) { + JavacNode annotationNode = ast.get(annotation); + if (!JavacHandlerUtil.annotationTypeMatches(AutoImplement.Util.SetParam.class, annotationNode)) + continue; + AutoImplement.Util.SetParam setParam = AnnotationValues.of(AutoImplement.Util.SetParam.class, annotationNode).getInstance(); + map.put(setParam.name(), setParam.value()); + } + } + node = node.up(); + } + return map; + } + + @AllArgsConstructor + static class InfoAndPos { + InterfaceInfo info; + JCTree.JCExpression producer; + } +} diff --git a/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/Paths.java b/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/Paths.java new file mode 100644 index 00000000..ef01706d --- /dev/null +++ b/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/Paths.java @@ -0,0 +1,26 @@ +package omaloon.annotations.lombok.autoimpl; + +import lombok.core.TypeLibrary; +import lombok.javac.JavacNode; +import omaloon.annotations.AutoImplement; + +public class Paths { + public static final String PARAM_METHOD = AutoImplement.Util.class.getCanonicalName() + ".Param"; + public static final String INJECT_METHOD = AutoImplement.Util.class.getCanonicalName() + ".Inject"; + public static final TypeLibrary library = new TypeLibrary() {{ + addType(AutoImplement.Util.class.getName() + "$Param"); + addType(AutoImplement.Util.class.getName() + "$Inject"); + lock(); + }}; + + public static boolean expressionMatch(JavacNode context, String expressionToCheck, String expected) { + String resolved = fullifyName(context, expressionToCheck, library); + return resolved != null && resolved.equals(expected); + } + + public static String fullifyName(JavacNode context, String expressionToUnwrap, TypeLibrary library1) { + return context + .getImportListAsTypeResolver() + .typeRefToFullyQualifiedName(context, library1, expressionToUnwrap); + } +} diff --git a/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/info/AutoImplInformation.java b/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/info/AutoImplInformation.java new file mode 100644 index 00000000..817ac30d --- /dev/null +++ b/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/info/AutoImplInformation.java @@ -0,0 +1,77 @@ +package omaloon.annotations.lombok.autoimpl.info; + +import asmlib.lombok.javaparser.CompileBodyVisitor; +import com.sun.tools.javac.tree.JCTree; +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.NonNull; +import lombok.core.AST; +import lombok.core.AnnotationValues; +import lombok.core.LombokNode; +import lombok.experimental.FieldDefaults; +import lombok.javac.JavacNode; +import omaloon.annotations.AutoImplement; +import one.util.streamex.StreamEx; + +import java.util.Map; +import java.util.function.Function; + +public class AutoImplInformation { + public Map methods; + public Map fields; + + public static AutoImplInformation build(AnnotationValues annotationValues, JCTree.JCAnnotation jcAnnotation, JavacNode annotationNode) { + AutoImplInformation information = new AutoImplInformation(); + JavacNode typeNode = annotationNode.up(); + CompileBodyVisitor transformer = new CompileBodyVisitor(typeNode.getTreeMaker(), typeNode.getAst(), typeNode.getContext()); + + information.methods = StreamEx + .of(typeNode.down().iterator()) + .filterBy(LombokNode::getKind, AST.Kind.METHOD) + .map(javacNode -> { + AnnotationValues foundAnnotation = javacNode.findAnnotation(AutoImplement.Inject.class); + AutoImplement.Inject annotationInstance = foundAnnotation == null ? null : foundAnnotation.getInstance(); + return MethodInfo.create( + typeNode, + javacNode, + annotationInstance + ); + }) + .mapToEntry(it -> it.info.descriptor, Function.identity()) + .toMap() + ; + + + information.fields = StreamEx + .of(typeNode.down().iterator()) + .filterBy(LombokNode::getKind, AST.Kind.FIELD) + .mapToEntry(JavacNode::getName, Function.identity()) + .mapValues(javacNode -> new FieldInfo( + typeNode.getName(), + typeNode, + javacNode.getName(), + cast(javacNode), + javacNode, + transformer + )) + .toMap(); + return information; + } + + private static T cast(JavacNode javacNode) { + return (T) javacNode.get(); + } + + @AllArgsConstructor + @FieldDefaults(level = AccessLevel.PUBLIC, makeFinal = true) + public static class FieldInfo { + String intefaceName; + JavacNode typeNode; + String name; + @NonNull + JCTree.JCVariableDecl decl; + @NonNull + JavacNode fieldNode; + CompileBodyVisitor transformer; + } +} diff --git a/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/info/InlineApplyPrinter.java b/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/info/InlineApplyPrinter.java new file mode 100644 index 00000000..8bb2adb4 --- /dev/null +++ b/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/info/InlineApplyPrinter.java @@ -0,0 +1,44 @@ +package omaloon.annotations.lombok.autoimpl.info; + +import bytelogic.lombok.util.ContextLibrary; +import com.sun.tools.javac.tree.JCTree; +import com.sun.tools.javac.tree.Pretty; +import lombok.SneakyThrows; + +import java.io.IOException; +import java.io.Writer; + +public class InlineApplyPrinter extends Pretty { + + final String expectedMethod; + final ContextLibrary contextLibrary; + final Handler handler; + + public InlineApplyPrinter(Writer out, String expectedMethod, ContextLibrary contextLibrary, Handler handler) { + super(out, true); + this.expectedMethod = expectedMethod; + this.contextLibrary = contextLibrary; + this.handler = handler; + } + + @SneakyThrows + @Override + public void visitApply(JCTree.JCMethodInvocation tree) { + + String string = contextLibrary.resolveFull(tree.meth.toString()); + if (!expectedMethod.equals(string)) { + super.visitApply(tree); + return; + } + handler.handle(this, tree); + } + + @Override + public void printExpr(JCTree tree) throws IOException { + super.printExpr(tree); + } + + public interface Handler { + void handle(InlineApplyPrinter self, JCTree.JCMethodInvocation tree) throws IOException; + } +} diff --git a/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/info/MethodDeclarationInfo.java b/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/info/MethodDeclarationInfo.java new file mode 100644 index 00000000..9d907692 --- /dev/null +++ b/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/info/MethodDeclarationInfo.java @@ -0,0 +1,38 @@ +package omaloon.annotations.lombok.autoimpl.info; + +import bytelogic.lombok.util.ContextLibrary; +import bytelogic.lombok.util.Util; +import com.sun.tools.javac.tree.JCTree; +import lombok.*; +import lombok.core.TypeLibrary; +import lombok.experimental.FieldDefaults; +import lombok.javac.JavacNode; + +@AllArgsConstructor +@Getter +@FieldDefaults(level = AccessLevel.PUBLIC, makeFinal = true) +public class MethodDeclarationInfo { + + public static final TypeLibrary EMPTY_LIB = new TypeLibrary(); + public String name; + public final String descriptor; + @NonNull + JavacNode node; + @NonNull + JCTree.JCMethodDecl decl; + ContextLibrary contextLibrary; + public final String symbolString; + + public static MethodDeclarationInfo make(JavacNode methodNode) { + ContextLibrary library = ContextLibrary.makeLib(methodNode, EMPTY_LIB); + JCTree.JCMethodDecl methodDecl = (JCTree.JCMethodDecl) methodNode.get(); + return new MethodDeclarationInfo( + methodNode.getName(), + Util.methodDesc(library, methodDecl), + methodNode, + methodDecl, + library, + Util.methodSymbolString(library,methodDecl) + ); + } +} diff --git a/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/info/MethodInfo.java b/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/info/MethodInfo.java new file mode 100644 index 00000000..65e1921d --- /dev/null +++ b/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/info/MethodInfo.java @@ -0,0 +1,336 @@ +package omaloon.annotations.lombok.autoimpl.info; + +import asmlib.lombok.javaparser.CompileBodyVisitor; +import bytelogic.lombok.util.ContextLibrary; +import bytelogic.lombok.util.GeneratedByVisitor; +import bytelogic.lombok.util.Util; +import com.sun.tools.javac.code.Flags; +import com.sun.tools.javac.code.Symbol; +import com.sun.tools.javac.parser.JavacParser; +import com.sun.tools.javac.parser.ParserFactory; +import com.sun.tools.javac.tree.JCTree; +import com.sun.tools.javac.tree.TreeCopier; +import com.sun.tools.javac.tree.TreeScanner; +import com.sun.tools.javac.util.List; +import com.sun.tools.javac.util.Names; +import lombok.*; +import lombok.javac.JavacAST; +import lombok.javac.JavacNode; +import lombok.javac.JavacResolution; +import omaloon.annotations.AutoImplement; +import omaloon.annotations.AutoImplement.Inject.InjectPosition; +import omaloon.annotations.lombok.autoimpl.AutoImplContext; +import omaloon.annotations.lombok.autoimpl.AutoImplUtil; +import omaloon.annotations.lombok.autoimpl.Paths; +import org.jetbrains.annotations.Nullable; + +import java.io.IOException; +import java.io.StringWriter; +import java.util.Collection; +import java.util.Map; +import java.util.function.Function; + +import static bytelogic.lombok.util.ContextLibrary.makeLib; +import static one.util.streamex.StreamEx.of; + +@AllArgsConstructor +@Getter +public class MethodInfo { + public final String interfaceFullName; + public final JavacNode typeNode; + + final MethodDeclarationInfo info; + final JavacResolution resolution; + final ParserFactory parserFactory; + + final CompileBodyVisitor transformer; + @Nullable + AutoImplement.Inject inject; + + public static MethodInfo create(JavacNode typeNode, JavacNode methodNode, AutoImplement.Inject inject) { + MethodDeclarationInfo info = MethodDeclarationInfo.make(methodNode); + return new MethodInfo( + Util.canonicalFullname(typeNode), + typeNode, + info, + info.contextLibrary.resolution, + ParserFactory.instance(typeNode.getContext()), + Util.transformer(methodNode), + inject + ); + } + + @Nullable + public static String extractString(JCTree.JCExpression jcExpression, JavacAST ast, String desc) { + String string; + if (!(jcExpression instanceof JCTree.JCLiteral literal)) { + ast.get(jcExpression).addError("Only Literals allowed in " + desc); + string = null; + + } else { + string = literal.value.toString(); + } + return string; + } + + private boolean tryInjectPosition(JCTree.JCMethodDecl decl, AutoImplContext context, List newCode) { + + + boolean[] hasInject = {false}; + ParserFactory parserFactory = ParserFactory.instance(context.callerMethodNode.getContext()); + TreeCopier copier = new TreeCopier<>(transformer.imaker) { + @Override + public T copy(T tree, Object o) { + super.copy(tree, o); + return tree; + } + + @Override + public List copy(List trees, Object o) { + if (trees.isEmpty() || trees.stream().filter(it -> it instanceof JCTree.JCStatement).count() != trees.length()) + return trees.map(this::copy); + //noinspection unchecked + return (List) List.from(of((List) trees) + .limit(trees.length()) + .flatCollection(it -> { + if (!hasInject(context, it)) return List.of(copy(it)); + hasInject[0] = true; + StringWriter writer = new StringWriter(); + try { + new InlineApplyPrinter(writer, Paths.INJECT_METHOD, makeLib(context.callerMethodNode, Paths.library), (printer, tree) -> { + printer.printStats(newCode); + + }).printExpr(it); + } catch (IOException e) { + throw Lombok.sneakyThrow(e); + } + String input = "{\n" + writer + "\n}"; + JavacParser parser = parserFactory.newParser(input, true, true, true, false); + return ((JCTree.JCBlock) parser.parseStatement()).stats; + }) + .toArray(JCTree.JCStatement[]::new) + ); + } + }; + decl.body.stats = copier.copy(decl.body.stats); + if (hasInject[0]) { + context.callerMethodNode.getAst().setChanged(); + } + return hasInject[0]; + } + + private boolean hasInject(AutoImplContext context, JCTree tree) { + boolean[] hasInject = {false}; + + tree.accept(new TreeScanner() { + @Override + public void scan(JCTree tree) { + if (!hasInject[0]) super.scan(tree); + } + + @Override + public void scan(List trees) { + //TODO mayby just filter + } + + @Override + public void visitApply(JCTree.JCMethodInvocation tree) { + + JavacNode tmpNode = context.callerMethodNode; + + if (!Paths.expressionMatch(tmpNode, tree.meth.toString(), Paths.INJECT_METHOD)) { + super.visitApply(tree); + return; + } + ContextLibrary library = ContextLibrary.ofClasses(tmpNode); + + JCTree.JCFieldAccess access = (JCTree.JCFieldAccess) tree.args.get(0); + String innerClass = library.className(access.selected); + hasInject[0] |= interfaceFullName.equals(innerClass); + } + }); + return hasInject[0]; + } + + public JCTree.JCMethodDecl make(@NonNull AutoImplContext rawContext) { + + JCTree.JCMethodDecl declaration = TypeInliner.copyWithInlineTypes(info.node); + AutoImplUtil.removeAutoImplAnnos(declaration.mods); + declaration.mods.flags &= ~Flags.DEFAULT; + declaration.mods.flags |= Flags.PUBLIC; + + + if (inject != null && inject.shouldAddSuper()) { + var m = transformer.maker; + m.at(rawContext.producerNode.getPreferredPosition()); + Names names = Names.instance(typeNode.getContext()); + declaration.body = m.Block(0, List.of( + m.Exec( + m.Apply( + declaration.typarams + .map(JCTree.JCTypeParameter::getName) + .map(m::Ident), + m.Select(m.Ident(names._super), declaration.name), + declaration.params.map(JCTree.JCVariableDecl::getName) + .map(m::Ident) + ) + ) + )); + } else { + declaration.body.stats = List.nil(); + } + rawContext.generatedBy().scan(declaration, null); + return declaration; + } + + public void join(JCTree.JCMethodDecl existed, AutoImplContext context) { + + JCTree.JCBlock body = existed.body; + List preprocessed = prepareStats(context); + if (tryInjectPosition(existed, context, preprocessed)) { + return; + } + InjectPosition position; + if (inject == null) { + //TODO + position = InjectPosition.Head; + } else { + position = inject.value(); + } + + Void nil = switch (position) { + case Head -> { + body.stats = body.stats.prependList(preprocessed); + yield null; + } + case Tail -> { + body.stats = body.stats.appendList(preprocessed); + + yield null; + } + case AfterSuper, BeforeSuper -> { + final JavacResolution resolution = getResolution(); + final ContextLibrary library = info.contextLibrary; + final String originalParams = of(info.decl.getParameters()) + .map(JCTree.JCVariableDecl::getType) + .map(library::className) + .joining(";"); + TreeCopier simpleCopier = new TreeCopier<>(transformer.imaker); + boolean[] foundSuper = {false}; + TreeCopier copier = new TreeCopier<>(transformer.imaker) { + + + @SuppressWarnings("rawtypes") + @Override + public List copy(List trees, Object object) { + + Function tCollectionFunction = (Function>) it__ -> { + if (!(it__ instanceof JCTree.JCExpressionStatement it)) return List.of(it__); + JCTree.JCExpressionStatement it__Copy = copy(it, object); + if (!(it.expr instanceof JCTree.JCMethodInvocation apply)) return List.of(it__Copy); + String postfix = "super." + info.name; + //TODO better super handling + if (!apply.meth.toString().equals(postfix) && !apply.meth.toString().endsWith('.' + postfix)) + return List.of(it__Copy); + + JavacNode localContext = context.callerMethodNode.getNodeFor(it); + + + Map resolved = resolution.resolveMethodMember(localContext); + String resolvedArguments = of(apply.getArguments()) + .map(resolved::get) + .map(it_ -> it_.type) + .joining(";"); + if (!originalParams.equals(resolvedArguments)) return List.of(it__Copy); + foundSuper[0] = true; + if (position == InjectPosition.BeforeSuper) { + return simpleCopier.copy(preprocessed).append(it__Copy); + } else { + return simpleCopier.copy(preprocessed).prepend(it__Copy); + } + }; + //noinspection unchecked + return List.from(of(trees) + .flatCollection(tCollectionFunction) + + + ); + } + }; + existed.body.stats = copier.copy(existed.body.stats); + + if (!foundSuper[0]) { + context.callerMethodNode + .addError("Cannot find invoking super method to inject implementation from " + interfaceFullName); + } + yield null; + } + }; + //noinspection ConstantValue + if (false) System.out.println(nil); + context.callerMethodNode.getAst().setChanged(); + context.callerMethodNode.rebuild(); + } + + @SneakyThrows + private List preprocess(List stats, AutoImplContext context) { + + + JCTree.JCStatement[] array = stats.toArray(JCTree.JCStatement[]::new); + ParserFactory parserFactory = ParserFactory.instance(info.node.getContext()); + GeneratedByVisitor generatedByMarker = context.generatedBy(); + for (int i = 0; i < array.length; i++) { + + JCTree.JCStatement jcStatement = array[i]; + StringWriter s = new StringWriter(); + new InlineApplyPrinter(s, Paths.PARAM_METHOD, makeLib(info.node, Paths.library), (printer, tree) -> { + JavacAST ast = info.node + .getAst(); + + String paramName = extractString(tree.args.get(0), ast, Paths.PARAM_METHOD); + String defaultExpression = extractString(tree.args.get(1), ast, Paths.PARAM_METHOD); + + String expression = context.paramMap.getOrDefault(paramName, defaultExpression); + + printer.print(expression); + + }) { + @SneakyThrows + boolean tryFixName(JCTree.JCIdent tree) { + if (!(tree.sym instanceof Symbol.VarSymbol varSymbol)) return false; + if (!(varSymbol.owner instanceof Symbol.MethodSymbol methodSymbol)) return false; + if (!(methodSymbol.owner instanceof Symbol.ClassSymbol classSymbol)) return false; + if (!classSymbol.className().equals(interfaceFullName)) return false; + if (!methodSymbol.toString().equals(info.symbolString)) return false; + JCTree.JCMethodDecl newDecl = (JCTree.JCMethodDecl) context.callerMethodNode.get(); + int varIndex = methodSymbol.params.indexOf(varSymbol); + print(newDecl.params.get(varIndex).getName().toString()); + return true; + } + + @Override + public void visitIdent(JCTree.JCIdent tree) { + + if (tryFixName(tree)) return; + super.visitIdent(tree); + } + }.printStat(jcStatement); + String stringify = s.toString(); + + + JavacParser javacParser = parserFactory.newParser(stringify, false, false, false, false); + + array[i] = javacParser.parseStatement(); + generatedByMarker.scan(array[i], null); + } + return List.from(array); + } + + public List prepareStats(AutoImplContext context) { + info.decl.body = TypeInliner.copyWithInlineTypes(info.node, info.decl.body); + + JCTree.JCMethodDecl decl = Util.resolveSym(info.node); + return preprocess(decl.body.stats, context); + } + +} diff --git a/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/info/TypeInliner.java b/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/info/TypeInliner.java new file mode 100644 index 00000000..2b5a5500 --- /dev/null +++ b/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/info/TypeInliner.java @@ -0,0 +1,99 @@ +package omaloon.annotations.lombok.autoimpl.info; + +import bytelogic.lombok.util.Util; +import com.sun.source.tree.MethodInvocationTree; +import com.sun.source.tree.MethodTree; +import com.sun.source.tree.Tree; +import com.sun.tools.javac.code.Symbol; +import com.sun.tools.javac.tree.JCTree; +import com.sun.tools.javac.tree.JCTree.JCFieldAccess; +import com.sun.tools.javac.tree.TreeCopier; +import com.sun.tools.javac.tree.TreeMaker; +import com.sun.tools.javac.util.List; +import lombok.javac.JavacNode; +import lombok.javac.JavacResolution; +import lombok.javac.handlers.JavacHandlerUtil; +import org.jetbrains.annotations.Nullable; + +public class TypeInliner extends TreeCopier { + + private final JavacNode context; + private TreeMaker M; + + /** + * Creates a new instance of TreeCopier + * + * @param M + * @param context + */ + public TypeInliner(TreeMaker M, JavacNode context) { + super(M); + this.M = M; + this.context = context; + } + + public static T copyWithInlineTypes(JavacNode javacNode) { + T resolved = Util.resolveSym(javacNode); + TypeInliner inliner = new TypeInliner(javacNode.getTreeMaker().getUnderlyingTreeMaker(), javacNode); + return inliner.copy(resolved); + } + public static T copyWithInlineTypes(JavacNode context,T tree) { + JavacResolution resolution = Util.resolution(context.getContext()); + //noinspection unchecked + T resolved = (T) resolution.resolveMethodMember(context).get(tree); + return + new TypeInliner(context.getTreeMaker().getUnderlyingTreeMaker(), context) + .copy(resolved); + } + + + @Override + public T copy(T tree, Void unused) { + if (tree instanceof JCFieldAccess fieldAccess) { + T new_ = unwrap(tree, fieldAccess.sym); + if (new_ != tree) return new_; + + } + if (tree instanceof JCTree.JCIdent ident) { + T new_ = unwrap(tree, ident.sym); + if (new_ != tree) return new_; + } + return super.copy(tree, unused); + } + + @Nullable + private T unwrap(T tree, Symbol sym) { + + if (!(sym instanceof Symbol.ClassSymbol classSymbol)) return tree; + if (classSymbol.name.isEmpty()) { + //Anonymous + //TO debug + throw new RuntimeException("To debug"); + } else { + String string = classSymbol.className(); + + JCFieldAccess jcFieldAccess = (JCFieldAccess) JavacHandlerUtil.chainDots(context, string.split("\\.")); + jcFieldAccess.sym = sym; + jcFieldAccess.pos = tree.pos; + //noinspection unchecked + return (T) jcFieldAccess; + } + } + + + private T cast(Tree node) { + //noinspection unchecked + return (T) node; + } + + @Override + public JCTree visitMethodInvocation(MethodInvocationTree node, Void unused) { + return super.visitMethodInvocation(node, unused); + } + + @Override + public List copy(List trees, Void unused) { + return super.copy(trees, unused); + } +} + diff --git a/annotations/src/main/java/omaloon/annotations/lombok/load/LoadAnnotationASTVisitor.java b/annotations/src/main/java/omaloon/annotations/lombok/load/LoadAnnotationASTVisitor.java index 733b63f6..6be53201 100644 --- a/annotations/src/main/java/omaloon/annotations/lombok/load/LoadAnnotationASTVisitor.java +++ b/annotations/src/main/java/omaloon/annotations/lombok/load/LoadAnnotationASTVisitor.java @@ -1,6 +1,7 @@ package omaloon.annotations.lombok.load; import asmlib.lombok.javaparser.CompileBodyVisitor; +import bytelogic.lombok.util.Util; import com.github.javaparser.StaticJavaParser; import com.github.javaparser.ast.Modifier; import com.github.javaparser.ast.body.MethodDeclaration; @@ -13,7 +14,6 @@ import lombok.javac.JavacNode; import lombok.javac.handlers.JavacHandlerUtil; import omaloon.annotations.Load; -import org.jetbrains.annotations.NotNull; import java.util.ArrayList; //TODO try handle something like @Load(name+"-hello") @@ -41,7 +41,7 @@ public void visitType(JavacNode typeNode, JCTree.JCClassDecl type) { loadFields.add(new FieldDescriptor(field, annotation.getInstance())); } if (loadFields.isEmpty()) return; - CompileBodyVisitor transformer = transformer(typeNode); + CompileBodyVisitor transformer = Util.transformer(typeNode); if (loadMethod == null) { BlockStmt body = new BlockStmt(); MethodDeclaration declaration = new MethodDeclaration() @@ -76,13 +76,4 @@ private static BlockStmt addFields(java.util.List loadFields, B return block; } - @NotNull - private static CompileBodyVisitor transformer(JavacNode typeNode) { - return new CompileBodyVisitor( - typeNode.getTreeMaker(), - typeNode.getAst(), - typeNode.getContext() - ); - } - } diff --git a/annotations/src/main/resources/META-INF/services/lombok.javac.JavacASTVisitor b/annotations/src/main/resources/META-INF/services/lombok.javac.JavacASTVisitor index bef51bea..dc81b95c 100644 --- a/annotations/src/main/resources/META-INF/services/lombok.javac.JavacASTVisitor +++ b/annotations/src/main/resources/META-INF/services/lombok.javac.JavacASTVisitor @@ -1 +1,3 @@ -omaloon.annotations.lombok.load.LoadAnnotationASTVisitor \ No newline at end of file +omaloon.annotations.lombok.load.LoadAnnotationASTVisitor +omaloon.annotations.lombok.autoimpl.ImplProcessor +bytelogic.lombok.hierarchy.HierarchyCollector \ No newline at end of file diff --git a/annotations/src/main/resources/META-INF/services/lombok.javac.JavacAnnotationHandler b/annotations/src/main/resources/META-INF/services/lombok.javac.JavacAnnotationHandler new file mode 100644 index 00000000..adada164 --- /dev/null +++ b/annotations/src/main/resources/META-INF/services/lombok.javac.JavacAnnotationHandler @@ -0,0 +1,3 @@ +omaloon.annotations.lombok.autoimpl.ImplMarker +bytelogic.lombok.remove.RemoveFromCompilationHandler +omaloon.annotations.lombok.autoimpl.CleanupHandler \ No newline at end of file diff --git a/gradle.properties b/gradle.properties index c9434c90..350f3752 100644 --- a/gradle.properties +++ b/gradle.properties @@ -41,7 +41,7 @@ jparcerVersion = 3.26.0 lombokVersion = 1.18.32 jetbrainsAnnotations = 24.0.1 asmLibVersion = v0.9.6 - +streamExVersion = 0.8.3 ##### Other stuff that should be left as-is. # Enable parallel compilation. org.gradle.parallel = true diff --git a/src/omaloon/annotations/AutoImplement.java b/src/omaloon/annotations/AutoImplement.java new file mode 100644 index 00000000..77406236 --- /dev/null +++ b/src/omaloon/annotations/AutoImplement.java @@ -0,0 +1,49 @@ +package omaloon.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Target; + +@Target(ElementType.TYPE) +public @interface AutoImplement { + + + @Target(ElementType.METHOD) + @interface NoInject { + + } + + + /** + * This need ONLY for Annotation Processing, and it will be removed during compilation + */ + interface Util { + static T Inject(Class type, Object... args) { + return error(); + } + + static T Param(String paramName, String defaultExpression) { + return error(); + } + + static T error() { + throw new RuntimeException("Why are you calling this?! This need ONLY for Annotation Processing and it will be removed during compilation"); + } + + + @interface SetParam { + String name(); + String value(); + } + } + + + public @interface Inject { + InjectPosition value(); + boolean shouldAddSuper() default true; + enum InjectPosition{ + AfterSuper,BeforeSuper, + + Head,Tail; + } + } +} diff --git a/src/omaloon/annotations/RemoveFromCompilation.java b/src/omaloon/annotations/RemoveFromCompilation.java new file mode 100644 index 00000000..7921dde8 --- /dev/null +++ b/src/omaloon/annotations/RemoveFromCompilation.java @@ -0,0 +1,4 @@ +package omaloon.annotations; + +public @interface RemoveFromCompilation { +} diff --git a/src/omaloon/world/blocks/defense/BlastTower.java b/src/omaloon/world/blocks/defense/BlastTower.java index bf46f8d8..97f6bc45 100644 --- a/src/omaloon/world/blocks/defense/BlastTower.java +++ b/src/omaloon/world/blocks/defense/BlastTower.java @@ -7,6 +7,7 @@ import arc.struct.*; import arc.util.*; import arc.util.io.*; +import asmlib.annotations.DebugAST; import mindustry.content.*; import mindustry.entities.*; import mindustry.entities.units.*; @@ -16,6 +17,7 @@ import mindustry.world.*; import mindustry.world.consumers.*; import mindustry.world.meta.*; +import omaloon.annotations.AutoImplement; import omaloon.annotations.Load; import omaloon.content.*; import omaloon.world.interfaces.*; @@ -87,8 +89,7 @@ public TextureRegion[] icons(){ return new TextureRegion[]{region, hammerRegion}; } - public class BlastTowerBuild extends Building implements HasPressure { - public PressureModule pressure = new PressureModule(); + public class BlastTowerBuild extends Building implements HasPressureImpl { public float smoothProgress = 0f; public float charge; public float lastShootTime = -reload; @@ -182,31 +183,23 @@ public void drawSelect(){ } @Override + @DebugAST public void write(Writes write) { super.write(write); write.f(lastShootTime); write.f(smoothProgress); write.f(charge); - pressure.write(write); + AutoImplement.Util.Inject(HasPressureImpl.class); } @Override + @DebugAST public void read(Reads read, byte revision) { super.read(read, revision); lastShootTime = read.f(); smoothProgress = read.f(); charge = read.f(); - pressure.read(read); - } - - @Override - public PressureModule pressure() { - return pressure; - } - - @Override - public PressureConfig pressureConfig() { - return pressureConfig; + AutoImplement.Util.Inject(HasPressureImpl.class); } } } \ No newline at end of file diff --git a/src/omaloon/world/blocks/defense/ConsumeTurret.java b/src/omaloon/world/blocks/defense/ConsumeTurret.java index 8efe418d..11093c79 100644 --- a/src/omaloon/world/blocks/defense/ConsumeTurret.java +++ b/src/omaloon/world/blocks/defense/ConsumeTurret.java @@ -47,8 +47,7 @@ public void setBars() { stats.add(Stat.ammo, StatValues.ammo(ObjectMap.of(this, shootType))); } - public class ConsumeTurretBuild extends TurretBuild implements HasPressure { - public PressureModule pressure = new PressureModule(); + public class ConsumeTurretBuild extends TurretBuild implements HasPressureImpl { @Override public void drawSelect() { @@ -71,18 +70,8 @@ protected void findTarget() { return shootType; } - @Override public PressureModule pressure() { - return pressure; - } - @Override public PressureConfig pressureConfig() { - return pressureConfig; - } - @Override - public void read(Reads read, byte revision) { - super.read(read, revision); - pressure.read(read); - } + @Override protected void shoot(BulletType type) { @@ -101,10 +90,6 @@ public void updateTile() { return shootType; } - @Override - public void write(Writes write) { - super.write(write); - pressure.write(write); - } + } } diff --git a/src/omaloon/world/blocks/defense/Shelter.java b/src/omaloon/world/blocks/defense/Shelter.java index cf0c5a86..b301f379 100644 --- a/src/omaloon/world/blocks/defense/Shelter.java +++ b/src/omaloon/world/blocks/defense/Shelter.java @@ -10,6 +10,7 @@ import arc.util.*; import arc.util.io.*; import arclibrary.graphics.*; +import asmlib.annotations.DebugAST; import mindustry.*; import mindustry.content.*; import mindustry.entities.*; @@ -133,8 +134,7 @@ public void drawPlanRegion(BuildPlan plan, Eachable list) { Draw.rect(region, plan.drawx(), plan.drawy(), rot - 90); } - public class ShelterBuild extends Building implements HasPressure { - public PressureModule pressure = new PressureModule(); + public class ShelterBuild extends Building implements HasPressureImpl { public float rot = 90; public float shieldDamage = 0; @@ -217,17 +217,11 @@ public boolean onConfigureTapped(float x, float y) { return false; } - @Override public PressureModule pressure() { - return pressure; - } - @Override public PressureConfig pressureConfig() { - return pressureConfig; - } @Override + @DebugAST public void read(Reads read, byte revision) { super.read(read, revision); - pressure.read(read); rot = read.f(); shieldDamage = read.f(); warmup = read.f(); @@ -281,9 +275,9 @@ public void updateTile() { } @Override + @DebugAST public void write(Writes write) { super.write(write); - pressure.write(write); write.f(rot); write.f(shieldDamage); write.f(warmup); diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidBridge.java b/src/omaloon/world/blocks/liquid/PressureLiquidBridge.java index 93877415..c34f21c2 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidBridge.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidBridge.java @@ -142,8 +142,7 @@ public void setStats() { pressureConfig.addStats(stats); } - public class PressureLiquidBridgeBuild extends TubeItemBridgeBuild implements HasPressure { - PressureModule pressure = new PressureModule(); + public class PressureLiquidBridgeBuild extends TubeItemBridgeBuild implements HasPressureImpl { @Override public boolean acceptLiquid(Building source, Liquid liquid) { @@ -188,24 +187,12 @@ public void draw() { @Override public Seq nextBuilds(boolean flow) { - Seq o = HasPressure.super.nextBuilds(flow); + Seq o = HasPressureImpl.super.nextBuilds(flow); if (Vars.world.build(link) instanceof PressureLiquidBridgeBuild b) o.add(b); for(int pos : incoming.items) if (Vars.world.build(pos) instanceof PressureLiquidBridgeBuild b) o.add(b); return o; } - @Override public PressureModule pressure() { - return pressure; - } - @Override public PressureConfig pressureConfig() { - return pressureConfig; - } - - @Override - public void read(Reads read, byte revision) { - super.read(read, revision); - pressure.read(read); - } @Override public void updateTile() { @@ -261,16 +248,5 @@ protected void drawInput(Tile other){ } } - @Override - public void write(Writes write) { - super.write(write); - pressure.write(write); - } - - @Override - public void read(Reads read){ - super.read(read); - pressure.read(read); - } } } diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidConduit.java b/src/omaloon/world/blocks/liquid/PressureLiquidConduit.java index cf172bef..6f5e9738 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidConduit.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidConduit.java @@ -143,9 +143,8 @@ public void setStats() { pressureConfig.addStats(stats); } - public class PressureLiquidConduitBuild extends LiquidRouterBuild implements HasPressure { + public class PressureLiquidConduitBuild extends LiquidRouterBuild implements HasPressureImpl { public int tiling = 0; - PressureModule pressure = new PressureModule(); @Override public boolean canDumpLiquid(Building to, Liquid liquid) { @@ -157,7 +156,7 @@ public boolean connects(HasPressure to) { return ( to instanceof PressureLiquidConduitBuild || to instanceof PressureLiquidValveBuild) ? (front() == to || back() == to || to.front() == this || to.back() == this) : - to != null && HasPressure.super.connects(to); + to != null && HasPressureImpl.super.connects(to); } @Override @@ -193,18 +192,7 @@ public void onProximityUpdate() { } } - @Override public PressureModule pressure() { - return pressure; - } - @Override public PressureConfig pressureConfig() { - return pressureConfig; - } - @Override - public void read(Reads read, byte revision) { - super.read(read, revision); - pressure.read(read); - } @Override public void updateTile() { @@ -213,10 +201,5 @@ public void updateTile() { dumpPressure(); } - @Override - public void write(Writes write) { - super.write(write); - pressure.write(write); - } } } diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidJunction.java b/src/omaloon/world/blocks/liquid/PressureLiquidJunction.java index 867b5632..91d4fa9e 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidJunction.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidJunction.java @@ -16,8 +16,7 @@ public PressureLiquidJunction(String name) { super(name); } - public class PressureLiquidJunctionBuild extends LiquidJunctionBuild implements HasPressure { - PressureModule pressure = new PressureModule(); + public class PressureLiquidJunctionBuild extends LiquidJunctionBuild implements HasPressureImpl { @Override public boolean acceptLiquid(Building source, Liquid liquid) { return false; @@ -28,7 +27,7 @@ public class PressureLiquidJunctionBuild extends LiquidJunctionBuild implements @Override public boolean connects(HasPressure to) { - return HasPressure.super.connects(to) && !(to instanceof PressureLiquidPump); + return HasPressureImpl.super.connects(to) && !(to instanceof PressureLiquidPump); } @Override @@ -47,23 +46,5 @@ public HasPressure getPressureDestination(HasPressure source, float pressure) { public Seq nextBuilds(boolean flow) { return Seq.with(); } - - @Override public PressureModule pressure() { - return pressure; - } - @Override public PressureConfig pressureConfig() { - return pressureConfig; - } - - @Override - public void read(Reads read, byte revision) { - super.read(read, revision); - pressure.read(read); - } - @Override - public void write(Writes write) { - super.write(write); - pressure.write(write); - } } } diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidPump.java b/src/omaloon/world/blocks/liquid/PressureLiquidPump.java index 16a76d2d..c69ace9d 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidPump.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidPump.java @@ -107,8 +107,8 @@ public void setStats() { stats.add(OlStats.pressureFlow, Mathf.round(pressureTransfer * 60f, 2), OlStats.pressureSecond); } - public class PressureLiquidPumpBuild extends LiquidBuild implements HasPressure { - PressureModule pressure = new PressureModule(); + public class PressureLiquidPumpBuild extends LiquidBuild implements HasPressureImpl { + public int tiling; @@ -122,7 +122,7 @@ public class PressureLiquidPumpBuild extends LiquidBuild implements HasPressure } @Override public boolean connects(HasPressure to) { - return HasPressure.super.connects(to) && !(to instanceof PressureLiquidPumpBuild) && (front() == to || back() == to); + return HasPressureImpl.super.connects(to) && !(to instanceof PressureLiquidPumpBuild) && (front() == to || back() == to); } @Override @@ -168,18 +168,6 @@ public void onProximityUpdate() { if (back() instanceof HasPressure back && connected(back)) tiling |= inverted ? 1 : 2; } - @Override public PressureModule pressure() { - return pressure; - } - @Override public PressureConfig pressureConfig() { - return pressureConfig; - } - - @Override - public void read(Reads read, byte revision) { - super.read(read, revision); - pressure.read(read); - } @Override public void updateTile() { @@ -223,10 +211,5 @@ public void updateTile() { } } - @Override - public void write(Writes write) { - super.write(write); - pressure.write(write); - } } } diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidValve.java b/src/omaloon/world/blocks/liquid/PressureLiquidValve.java index f104dafe..994d5f6a 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidValve.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidValve.java @@ -115,8 +115,7 @@ public void setStats() { stats.add(OlStats.pressureFlow, Mathf.round(pressureLoss * 60f, 2), OlStats.pressureSecond); } - public class PressureLiquidValveBuild extends LiquidBuild implements HasPressure { - PressureModule pressure = new PressureModule(); + public class PressureLiquidValveBuild extends LiquidBuild implements HasPressureImpl { public float draining; public float effectInterval; @@ -136,7 +135,7 @@ public boolean canDumpLiquid(Building to, Liquid liquid) { @Override public boolean connects(HasPressure to) { - return HasPressure.super.connects(to) && to instanceof PressureLiquidValveBuild ? + return HasPressureImpl.super.connects(to) && to instanceof PressureLiquidValveBuild ? (front() == to || back() == to) && (to.front() == this || to.back() == this) : (front() == to || back() == to); } @@ -168,24 +167,16 @@ public void onProximityUpdate() { if (back() instanceof HasPressure back && connected(back)) tiling |= inverted ? 1 : 2; } - @Override public PressureModule pressure() { - return pressure; - } - @Override public PressureConfig pressureConfig() { - return pressureConfig; - } - @Override public void read(Reads read, byte revision) { super.read(read, revision); - pressure.read(read); jammed = read.bool(); draining = read.f(); } @Override public void updatePressure() { - HasPressure.super.updatePressure(); + HasPressureImpl.super.updatePressure(); if (getPressure() >= jamPoint) jammed = false; if (jammed) return; if (getPressure() <= openMin) { @@ -222,7 +213,6 @@ public void updateTile() { @Override public void write(Writes write) { super.write(write); - pressure.write(write); write.bool(jammed); write.f(draining); } diff --git a/src/omaloon/world/blocks/production/PressureCrafter.java b/src/omaloon/world/blocks/production/PressureCrafter.java index 72c216c1..e71a49a2 100644 --- a/src/omaloon/world/blocks/production/PressureCrafter.java +++ b/src/omaloon/world/blocks/production/PressureCrafter.java @@ -2,6 +2,7 @@ import arc.util.*; import arc.util.io.*; +import asmlib.annotations.DebugAST; import mindustry.world.blocks.production.*; import mindustry.world.consumers.*; import omaloon.world.interfaces.*; @@ -32,9 +33,8 @@ public void setStats() { pressureConfig.addStats(stats); if (outputPressure != 0) stats.add(OlStats.outputPressure, Strings.autoFixed(outputPressure, 2), OlStats.pressureUnits); } - - public class PressureCrafterBuild extends GenericCrafterBuild implements HasPressure { - PressureModule pressure = new PressureModule(); +@DebugAST + public class PressureCrafterBuild extends GenericCrafterBuild implements HasPressureImpl { public float efficiencyMultiplier() { float val = 1; @@ -53,30 +53,11 @@ public float efficiencyMultiplier() { return super.getProgressIncrease(baseTime) * efficiencyMultiplier(); } - @Override public PressureModule pressure() { - return pressure; - } - @Override public PressureConfig pressureConfig() { - return pressureConfig; - } - - @Override - public void read(Reads read, byte revision) { - super.read(read, revision); - pressure.read(read); - } - @Override public void updateTile() { super.updateTile(); updatePressure(); dumpPressure(); } - - @Override - public void write(Writes write) { - super.write(write); - pressure.write(write); - } } } diff --git a/src/omaloon/world/blocks/production/PressureDrill.java b/src/omaloon/world/blocks/production/PressureDrill.java index 050c0016..8255a554 100644 --- a/src/omaloon/world/blocks/production/PressureDrill.java +++ b/src/omaloon/world/blocks/production/PressureDrill.java @@ -29,8 +29,8 @@ public void setStats() { pressureConfig.addStats(stats); } - public class PressureDrillBuild extends DrillBuild implements HasPressure { - PressureModule pressure = new PressureModule(); + public class PressureDrillBuild extends DrillBuild implements HasPressureImpl { + public float efficiencyMultiplier() { float val = 1; @@ -49,29 +49,11 @@ public float efficiencyMultiplier() { return super.getProgressIncrease(baseTime) * efficiencyMultiplier(); } - @Override public PressureModule pressure() { - return pressure; - } - @Override public PressureConfig pressureConfig() { - return pressureConfig; - } - - @Override - public void read(Reads read, byte revision) { - super.read(read, revision); - pressure.read(read); - } - @Override public void updateTile() { super.updateTile(); updatePressure(); dumpPressure(); } - @Override - public void write(Writes write) { - super.write(write); - pressure.write(write); - } } } diff --git a/src/omaloon/world/blocks/sandbox/PressureLiquidSource.java b/src/omaloon/world/blocks/sandbox/PressureLiquidSource.java index 5393c2bb..e2c6abd1 100644 --- a/src/omaloon/world/blocks/sandbox/PressureLiquidSource.java +++ b/src/omaloon/world/blocks/sandbox/PressureLiquidSource.java @@ -47,8 +47,7 @@ public void setBars() { pressureConfig.addBars(this); } - public class PressureLiquidSourceBuild extends LiquidSourceBuild implements HasPressure { - PressureModule pressure = new PressureModule(); + public class PressureLiquidSourceBuild extends LiquidSourceBuild implements HasPressureImpl { public float pressureTarget = lastAmount; public boolean negative = wasNegative; @@ -69,17 +68,9 @@ public void buildConfiguration(Table table) { }).growX(); } - @Override public PressureModule pressure() { - return pressure; - } - @Override public PressureConfig pressureConfig() { - return pressureConfig; - } - @Override public void read(Reads read, byte revision) { super.read(read, revision); - pressure.read(read); pressureTarget = read.f(); negative = read.bool(); } @@ -87,7 +78,7 @@ public void read(Reads read, byte revision) { @Override public void updateTile() { super.updateTile(); - pressure.pressure = pressureTarget * (negative ? -1f : 1f); + __pressure__.pressure = pressureTarget * (negative ? -1f : 1f); nextBuilds(true).each(b -> b.pressure().pressure = pressureTarget * (negative ? -1 : 1f)); dumpPressure(); } @@ -95,7 +86,6 @@ public void updateTile() { @Override public void write(Writes write) { super.write(write); - pressure.write(write); write.f(pressureTarget); write.bool(negative); } diff --git a/src/omaloon/world/blocks/sandbox/PressureLiquidVoid.java b/src/omaloon/world/blocks/sandbox/PressureLiquidVoid.java index 344cfbc3..593a05a5 100644 --- a/src/omaloon/world/blocks/sandbox/PressureLiquidVoid.java +++ b/src/omaloon/world/blocks/sandbox/PressureLiquidVoid.java @@ -14,8 +14,8 @@ public PressureLiquidVoid(String name) { super(name); } - public class PressureLiquidVoidBuild extends LiquidVoidBuild implements HasPressure { - PressureModule pressure = new PressureModule(); + public class PressureLiquidVoidBuild extends LiquidVoidBuild implements HasPressureImpl { + @Override public boolean acceptLiquid(Building source, Liquid liquid) { return enabled; @@ -24,17 +24,12 @@ public class PressureLiquidVoidBuild extends LiquidVoidBuild implements HasPress return enabled; } - @Override public PressureModule pressure() { - return pressure; - } - @Override public PressureConfig pressureConfig() { - return pressureConfig; - } + @Override public void updateTile() { super.updateTile(); - pressure.pressure = 0f; + __pressure__.pressure = 0f; } } } diff --git a/src/omaloon/world/interfaces/HasPressure.java b/src/omaloon/world/interfaces/HasPressure.java index 2592a3ca..cc5d1659 100644 --- a/src/omaloon/world/interfaces/HasPressure.java +++ b/src/omaloon/world/interfaces/HasPressure.java @@ -15,6 +15,8 @@ * only added this cause my ide did a funni */ public interface HasPressure extends Buildingc { + PressureModule pressure(); + PressureConfig pressureConfig(); /** * @return true if this building accepts a certain pressure amount from some building */ @@ -161,8 +163,6 @@ default Seq nextBuilds(boolean flow) { ); } - PressureModule pressure(); - PressureConfig pressureConfig(); /** * transfers pressure between 2 buildings taking acceptsPressure into account diff --git a/src/omaloon/world/interfaces/HasPressureImpl.java b/src/omaloon/world/interfaces/HasPressureImpl.java new file mode 100644 index 00000000..78dbe4cc --- /dev/null +++ b/src/omaloon/world/interfaces/HasPressureImpl.java @@ -0,0 +1,35 @@ +package omaloon.world.interfaces; + +import arc.util.io.Reads; +import arc.util.io.Writes; +import omaloon.annotations.AutoImplement; +import omaloon.world.meta.PressureConfig; +import omaloon.world.modules.PressureModule; + +import static omaloon.annotations.AutoImplement.Inject.InjectPosition.AfterSuper; + + +@AutoImplement +public interface HasPressureImpl extends HasPressure { + + PressureModule __pressure__ = new PressureModule(); + + default PressureModule pressure() { + return __pressure__; + } + + @AutoImplement.Inject(AfterSuper) + default void write(Writes writes) { + __pressure__.write(writes); + } + + @AutoImplement.Inject(AfterSuper) + default void read(Reads reads, byte b) { + __pressure__.read(reads); + } + + @Override + default PressureConfig pressureConfig() { + return AutoImplement.Util.Param("pressureConfig", "pressureConfig"); + } +} From c435a2e97d79e6ba15ddc3b0ac94f0612eb33f2a Mon Sep 17 00:00:00 2001 From: Zelaux <58040045+zelaux@users.noreply.github.com> Date: Tue, 4 Feb 2025 15:04:17 +0300 Subject: [PATCH 61/67] Removed debug print --- src/omaloon/world/blocks/defense/BlastTower.java | 5 +---- src/omaloon/world/blocks/defense/Shelter.java | 5 +---- src/omaloon/world/blocks/production/PressureCrafter.java | 4 +--- 3 files changed, 3 insertions(+), 11 deletions(-) diff --git a/src/omaloon/world/blocks/defense/BlastTower.java b/src/omaloon/world/blocks/defense/BlastTower.java index 97f6bc45..c514f81a 100644 --- a/src/omaloon/world/blocks/defense/BlastTower.java +++ b/src/omaloon/world/blocks/defense/BlastTower.java @@ -6,8 +6,7 @@ import arc.math.*; import arc.struct.*; import arc.util.*; -import arc.util.io.*; -import asmlib.annotations.DebugAST; +import arc.util.io.*;; import mindustry.content.*; import mindustry.entities.*; import mindustry.entities.units.*; @@ -183,7 +182,6 @@ public void drawSelect(){ } @Override - @DebugAST public void write(Writes write) { super.write(write); write.f(lastShootTime); @@ -193,7 +191,6 @@ public void write(Writes write) { } @Override - @DebugAST public void read(Reads read, byte revision) { super.read(read, revision); lastShootTime = read.f(); diff --git a/src/omaloon/world/blocks/defense/Shelter.java b/src/omaloon/world/blocks/defense/Shelter.java index b301f379..643642b3 100644 --- a/src/omaloon/world/blocks/defense/Shelter.java +++ b/src/omaloon/world/blocks/defense/Shelter.java @@ -9,8 +9,7 @@ import arc.struct.*; import arc.util.*; import arc.util.io.*; -import arclibrary.graphics.*; -import asmlib.annotations.DebugAST; +import arclibrary.graphics.*;; import mindustry.*; import mindustry.content.*; import mindustry.entities.*; @@ -219,7 +218,6 @@ public boolean onConfigureTapped(float x, float y) { @Override - @DebugAST public void read(Reads read, byte revision) { super.read(read, revision); rot = read.f(); @@ -275,7 +273,6 @@ public void updateTile() { } @Override - @DebugAST public void write(Writes write) { super.write(write); write.f(rot); diff --git a/src/omaloon/world/blocks/production/PressureCrafter.java b/src/omaloon/world/blocks/production/PressureCrafter.java index e71a49a2..ef81f8e3 100644 --- a/src/omaloon/world/blocks/production/PressureCrafter.java +++ b/src/omaloon/world/blocks/production/PressureCrafter.java @@ -1,8 +1,7 @@ package omaloon.world.blocks.production; import arc.util.*; -import arc.util.io.*; -import asmlib.annotations.DebugAST; +import arc.util.io.*;; import mindustry.world.blocks.production.*; import mindustry.world.consumers.*; import omaloon.world.interfaces.*; @@ -33,7 +32,6 @@ public void setStats() { pressureConfig.addStats(stats); if (outputPressure != 0) stats.add(OlStats.outputPressure, Strings.autoFixed(outputPressure, 2), OlStats.pressureUnits); } -@DebugAST public class PressureCrafterBuild extends GenericCrafterBuild implements HasPressureImpl { public float efficiencyMultiplier() { From 4206907690dcb55738ac7b2274bab06da5db6b59 Mon Sep 17 00:00:00 2001 From: Zelaux <58040045+zelaux@users.noreply.github.com> Date: Wed, 5 Feb 2025 15:23:14 +0300 Subject: [PATCH 62/67] Merge master into auto-impl-pressure --- assets/bundles/bundle.properties | 63 ++-- .../blocks/crafting/glacium-boiler.png | Bin 0 -> 1102 bytes .../blocks/liquids/filter-pump-arrow.png | Bin 0 -> 179 bytes .../blocks/liquids/filter-pump-filter.png | Bin 0 -> 220 bytes .../blocks/liquids/filter-pump-tiles.png | Bin 0 -> 1100 bytes .../blocks/liquids/filter-pump-top.png | Bin 0 -> 163 bytes assets/sprites/blocks/liquids/filter-pump.png | Bin 0 -> 546 bytes .../blocks/liquids/liquid-gauge-pointer.png | Bin 0 -> 157 bytes .../blocks/liquids/liquid-gauge-tiles.png | Bin 0 -> 576 bytes .../sprites/blocks/liquids/liquid-gauge.png | Bin 0 -> 432 bytes build.gradle.kts | 14 + src/omaloon/annotations/AutoImplement.java | 2 +- src/omaloon/content/OlFx.java | 74 ++++- src/omaloon/content/OlLiquids.java | 47 +++ src/omaloon/content/OlTechTree.java | 12 +- src/omaloon/content/OlUnitTypes.java | 1 + .../content/blocks/OlCraftingBlocks.java | 47 ++- .../content/blocks/OlDefenceBlocks.java | 84 ++++-- .../content/blocks/OlDistributionBlocks.java | 57 +++- .../content/blocks/OlProductionBlocks.java | 15 +- src/omaloon/entities/comp/MillipedeComp.java | 31 +- src/omaloon/math/OlMath.java | 33 +++ src/omaloon/ui/dialogs/EventHints.java | 59 +--- src/omaloon/ui/dialogs/OlGameDialog.java | 5 + src/omaloon/ui/elements/CenterBar.java | 130 +++++++++ .../world/blocks/defense/BlastTower.java | 159 +++++----- .../world/blocks/defense/ConsumeTurret.java | 4 +- src/omaloon/world/blocks/defense/Shelter.java | 21 +- .../blocks/liquid/PressureLiquidBridge.java | 66 ++++- .../blocks/liquid/PressureLiquidConduit.java | 65 +++-- .../blocks/liquid/PressureLiquidGauge.java | 200 +++++++++++++ .../blocks/liquid/PressureLiquidJunction.java | 26 +- .../blocks/liquid/PressureLiquidPump.java | 273 ++++++++++++++---- .../blocks/liquid/PressureLiquidValve.java | 125 +++++--- .../world/blocks/production/HammerDrill.java | 2 +- .../blocks/production/PressureCrafter.java | 63 +++- .../blocks/production/PressureDrill.java | 15 +- .../blocks/sandbox/PressureLiquidSource.java | 179 +++++++++--- .../blocks/sandbox/PressureLiquidVoid.java | 6 +- src/omaloon/world/consumers/ConsumeFluid.java | 119 ++++++++ .../world/consumers/ConsumePressure.java | 48 --- .../consumers/PressureEfficiencyRange.java | 59 ---- src/omaloon/world/interfaces/HasPressure.java | 152 ++-------- .../world/interfaces/HasPressureImpl.java | 20 +- src/omaloon/world/meta/FluidGroup.java | 12 + src/omaloon/world/meta/OlStats.java | 68 ++++- src/omaloon/world/meta/PressureConfig.java | 103 +++++-- src/omaloon/world/meta/PressureSection.java | 203 +++++++++++++ src/omaloon/world/modules/PressureModule.java | 101 ++++++- 49 files changed, 2061 insertions(+), 702 deletions(-) create mode 100644 assets/sprites/blocks/crafting/glacium-boiler.png create mode 100644 assets/sprites/blocks/liquids/filter-pump-arrow.png create mode 100644 assets/sprites/blocks/liquids/filter-pump-filter.png create mode 100644 assets/sprites/blocks/liquids/filter-pump-tiles.png create mode 100644 assets/sprites/blocks/liquids/filter-pump-top.png create mode 100644 assets/sprites/blocks/liquids/filter-pump.png create mode 100644 assets/sprites/blocks/liquids/liquid-gauge-pointer.png create mode 100644 assets/sprites/blocks/liquids/liquid-gauge-tiles.png create mode 100644 assets/sprites/blocks/liquids/liquid-gauge.png create mode 100644 src/omaloon/math/OlMath.java create mode 100644 src/omaloon/ui/elements/CenterBar.java create mode 100644 src/omaloon/world/blocks/liquid/PressureLiquidGauge.java create mode 100644 src/omaloon/world/consumers/ConsumeFluid.java delete mode 100644 src/omaloon/world/consumers/ConsumePressure.java delete mode 100644 src/omaloon/world/consumers/PressureEfficiencyRange.java create mode 100644 src/omaloon/world/meta/FluidGroup.java create mode 100644 src/omaloon/world/meta/PressureSection.java diff --git a/assets/bundles/bundle.properties b/assets/bundles/bundle.properties index 01dd2d32..88be8de2 100644 --- a/assets/bundles/bundle.properties +++ b/assets/bundles/bundle.properties @@ -49,6 +49,9 @@ setting.omaloon-discord-join = Join Omaloon discord server! setting.omaloon-enable-soft-cleaner = Enable Safe Cleaner setting.omaloon-enable-soft-cleaner.description = Cleans your campaign from not allowed content and research. +setting.omaloon-display-liquid-stats = Display custom viscosity/density +setting.omaloon-display-liquid-stats.description = [red]NEEDS RELOAD + binding.category-omaloon-editor = Editor settings.omaloon-resethints = Reset Hints @@ -62,13 +65,10 @@ omaloon.update.dialog.fullclean.confirm = Are you sure you want to reset your cu requirement.omaloon-at-wave = Reach Wave {0} in {1} ## Hints -hint.omaloon-pump_positive = To create higher pressure, place \uC353[accent] mechanical pumps[] in series, adding liquid pipes between them.\nTo increase pressure faster, place \uC353[accent] mechanical pumps[] in parallel. -hint.omaloon-pump_negative = To decrease pressure faster, add more \uC353[accent]mechanical pumps[]. -hint.omaloon-drill_positive_pressure = \uC351 [accent]Hammer drills[] require negative pressure to operate. Rotate the \uC353[accent] mechanical pumps[] away from the drills to create negative pressure. -hint.omaloon-press_or_shelter_negative_pressure = Some buildings require positive pressure. Rotate the \uC353[accent] mechanical pumps[] to these blocks to create positive pressure. -hint.omaloon-pump = The pumps only stop when there is a block in front of it or the front block has enough pressure. -hint.omaloon-low_pressure = Buildings will implode when it reaches -50 pressure units. To avoid this, use \uC354 [accent]Liquid Valve[], which will reduce the pressure, preventing it from reaching dangerous levels. -hint.omaloon-valve = One valve can handle up to three pumps. If you have more pumps, place more valves to avoid jamming. +hint.omaloon-air = Air is equivalent to pressure in it's density. So each fluid unit of air equals one pascal inside the Liquid Tube. +hint.omaloon-drill = Drills work with negative pressure, working faster with lower pressures. +hint.omaloon-pump_chaining = Pumps chained in series can reach a higher pressure gradient between the ends. If they're chained in parallel, they work faster. +hint.omaloon-shelter = Shelters work with positive pressure, covering a larger area at higher pressures. ## planets planet.omaloon-omaloon.name = Omaloon @@ -268,12 +268,18 @@ block.omaloon-liquid-tube.description = Moves liquids. block.omaloon-liquid-pump.name = Mechanical Pump block.omaloon-liquid-pump.description = Moves liquids forward. +block.omaloon-filter-pump.name = Filter +block.omaloon-filter-pump.description = Moves liquids forward. Liquid can be choosen manually + block.omaloon-liquid-junction.name = Liquid Junction block.omaloon-liquid-junction.description = Acts as a bridge for two crossing liquid tubes. block.omaloon-liquid-valve.name = Liquid Valve block.omaloon-liquid-valve.description = Equalizes fluid systems pressure to -15 pressure units. Jams when the pressure decreases too fast. +block.omaloon-liquid-gauge.name = Liquid Gauge +block.omaloon-liquid-gauge.description = Displays the amount of pressure inside it. + block.omaloon-liquid-bridge.name = Liquid Bridge block.omaloon-liquid-bridge.description = Transports liquids over terrain or buildings. @@ -327,23 +333,44 @@ block.omaloon-hammer-drill.description = When placed on ore, outputs items. Effi ## stats category.omaloon-pressure = Pressure -stat.omaloon-consumepressure = Consume Pressure -stat.omaloon-minpressure = Min Pressure -stat.omaloon-maxpressure = Max Pressure + stat.omaloon-max-speed = Max Speed stat.omaloon-min-speed = Min Speed -stat.omaloon-outputpressure = Output Pressure + +air = Air + +stat.omaloon-fluid-capacity = Fluid Capacity +stat.omaloon-fluid-capacity.format = @x@x@ Blocks + +stat.omaloon-density = Density +stat.omaloon-viscosity = @% (\uC357 @) + +stat.omaloon-pump-strength = Pump Strength +stat.omaloon-pressure-gradient = Pressure Gradient + +stat.omaloon-min-pressure = Min Pressure +stat.omaloon-max-pressure = Max Pressure + stat.omaloon-pressureflow = Speed -stat.omaloon-pressurerange = Operating Range -stat.omaloon-pressurerange.format = from \uC357 @ pressure units to \uC357 @ pressure units. +stat.omaloon-pressure-range = Operating Range +stat.omaloon-pressure-range.format = \uC357 @ to @ Pressure Units. +stat.omaloon-optimal-pressure = Optimal Pressure +stat.omaloon-optimal-pressure.format = \uC357 @ Pressure Units (@%) ## ui units -unit.omaloon-pressuresecond = pressure units / second -unit.omaloon-pressureunits = pressure units -bar.air = Air -bar.pressure-liquid = {0} (\uC357 {1}/{2}) +unit.omaloon-blocks-cubed = Blocks\u00B3 + +unit.omaloon-density-unit = Pressure Units / Blocks\u00B3 +unit.omaloon-viscosity-unit = Viscosity Units + +unit.omaloon-pressure-unit = Pressure Units +unit.omaloon-pressure-second = Pressure Units / Second + + +bar.air = Air: +bar.pressure = Pressure: +bar.pressure-liquid = ({0}: {1} / Air: {2}) bar.hail-shield-health = Individual Shelter -omaloon-source-negative = Negative ## abilities ability.hailshield = Individual Shelter diff --git a/assets/sprites/blocks/crafting/glacium-boiler.png b/assets/sprites/blocks/crafting/glacium-boiler.png new file mode 100644 index 0000000000000000000000000000000000000000..363b4c312d40a5975e74d8aa8961913ac0f9dc7d GIT binary patch literal 1102 zcmV-U1hM;xP)Px(2uVaiRCt{2TfJ%-X_-*h{DtQnZ19vxUJgX zit)O6f!*saROoxc7yuwAVfVWGF9|8>HBLXUC3s1QHqi*#oL)x)7PBea(SjNzL?};P zyU+;0PBIDLoaf!*R(v>xo6D=#HOWbr#-o|QlO-TMfcxDSJY&m=8s|485%0M|Dvd@m9} z#RcAhcu3In(UQRV3zC3H+Fz2I?{R|$&@T1Y!}F{QzX<-UMst#qYES|x@w&(wREVyYA47kmZPgB)Kb0#(=MPTL7QH)+|yc*H4afP zfgIc{=T206sFIK?&#iY!`A$n9M~NW3gG3}%@XVJyzBd9Lef|EkWdWL*vnc1a1k3iR z@h|F}U^G0I5c$HE!&wLzGCm0CdjNgogMhvV&^OLPfM**#*Xyhz}>Fx8JbN_U9{ zOW7YP8q@?rR6mymltN)lN<=8EO}cthaOU>{(y@5ctYAJ{vdWhNqf(z_3DUWLd)S*p zVv_}Ea{?aarF&YRV6_A_0TBriPlh>%c6Kc!kjG(7UXXHvU6s$lSrMh6CNHRRg4(1g zZWpP%)CXIFHYrNAJ0ZZD7EkRtyF`LDEsooh`2Y_nlf?>X3C4s` z1XnMRumYPbHG3LMpxS61um>Umi`n$}Cn1qgW57wK^lBd9U#Xm_P?7>xT0=t3*~(>? zNWj-563jJ15(%F7i&{`gS50+jc#TjWB$Q+(5~P_9uMt|zrtDrlpDk71oRaI^Jv``C zDQY?GY2PYY+jgyJ>s%?S8GuD0OP`2xzK}S88;D1FP2Z^3Zk;PdIdoAzQbx5((f5QB z2`vIV%J)%TAN5_s2?0_jr&K4{7fR!?WR}>k#;6CCe)k2>*i2uId1rmotkkJ<+>Zj+ zk1OkymNfg-n0JOf36NScDIHW_jSWfpuCloT@759+!n&>jYH}ynlX@Ra3>}Gtzm*G} U@WKS}kN^Mx07*qoM6N<$f*%|1kpKVy literal 0 HcmV?d00001 diff --git a/assets/sprites/blocks/liquids/filter-pump-arrow.png b/assets/sprites/blocks/liquids/filter-pump-arrow.png new file mode 100644 index 0000000000000000000000000000000000000000..9fa9e34ae3825962b60afd17c241c0bbaa4cdc90 GIT binary patch literal 179 zcmeAS@N?(olHy`uVBq!ia0vp^3LwnE1|*BCs=fdz&H|6fVg?3oVGw3ym^DWND46Q$ z;usRq`gV#V-vI>AMA8JCXu5d}Utnz-_xxBI| zv|`%vIR#=5?rOc_w9oz~@Q$nOTg9WB?;J$mF@!#S{bzfNIiEOZ$%0)y!Fe@D85lk= Y#l(bvu;~jl0$Rx6>FVdQ&MBb@0N@`#jsO4v literal 0 HcmV?d00001 diff --git a/assets/sprites/blocks/liquids/filter-pump-filter.png b/assets/sprites/blocks/liquids/filter-pump-filter.png new file mode 100644 index 0000000000000000000000000000000000000000..f45278034a6e4c10e8e96b0ceb817d8dfabf15e0 GIT binary patch literal 220 zcmeAS@N?(olHy`uVBq!ia0vp^3LwnE1|*BCs=fdz&H|6fVg?3oVGw3ym^DWNDA?!e z;usRq`gZz8-Ub66mfWyL)ddSv1lSyT4k>769uhL>UMYN&agB&bee9Ya|JRxrPHybz z2;1LxI7?A!(YE(jt&BH^!X}92kxsA@G3h)T_pvuOJ3G5?ckeX$AQ1L;=bLY4 zvTt|pr2@fz@8bvny35D(BLKknPe0gkgF6pzv*U*!9svN>)*n~W`rQ0ll+thXmg1*q zxts|Nm;~FFOK>UvoNF|;B>g4$De3~?982K@XM^J^$zNivWTRve_-s@m4)qT90RX!j z^X%u(-dzF!)}O4YoHN^DYW}58rygrBv{k;iFgzdDzn=^SD*h1tKJ7XA0l@2kfeF3= zb;6JvggB9dKSdF6!PoMq&|iXoPBV!H9{^4-x@2U0PVZnpSrNqWp9}_d5e(0V!9^ei zU&G&2e<}W!>$GVbqTmd3W87LB-Q{EFX*UJG9XLCnKKO#4QvWph0ie44_HqR9hXrl$ zW7bgdDfoR?%$-+nRFAvu=bNglDu+=0uixHH#vh}P#3bJ}huY#QzbU^@Jm3$k zc8AcpW8x6lH2L-#YD;r4 z$(ekErdLCo+qE5Q^~d@WqnqO#+W|s@KRh3bhpW)Pgc8Y5jT}2cNz6&TW&18oVJBX? zW-WC(6DL_;KU>2;3&}T-c7i7QOJHmVu$v3o z=JEdPqH}?iXx~oo^xm1*As>GVg!BYb!KHs1zSx}XE#Mkg2i{gNJ+w$$bIklu{#gd+ zYg7HXalHdvaZKz0rx#tc7u?S#`%4z?GZ)$mZJb`T@!-ax=#Y;;1tdRn!KHs1zSx{& zJAnNSlhmN#oc1N3LQw-3gq9B9MIeCpv+2fa_OteQh6N#fS2*tZt2t`g=i*A=eq^sJ|Ct zCQ0&bUqbjPcSsCu&i~@uz>u9ldM7~pzJQN2R=<{?f-w@dH4m z`ODE5&UxU8<&R0eL1+?E>o3KxDgcgvHZhD!K_){dGuC;BZ)IUvr;O~D10q%p1c}^SLx_?tNNShn3=Q|Z&nqQ0D`h7ca zZvFMATs2bi7;rW?u9EyE)=D|aRZ2bXG)>`p` SbvUm80000Ac&5+<~Qi9upsfAHeD&w>}`t-Kb%yylAM3E>;2 zf2}#S9h6%3GL?Sc$e?F^U~Br0?7BA`!e>`EnLm(QtnyKmnIZ0tlMch}%CHMSix@mz L{an^LB{Ts5pX54_ literal 0 HcmV?d00001 diff --git a/assets/sprites/blocks/liquids/filter-pump.png b/assets/sprites/blocks/liquids/filter-pump.png new file mode 100644 index 0000000000000000000000000000000000000000..8bd6b2c23630aef464f40d61da51c8d11578060a GIT binary patch literal 546 zcmV+-0^R+IP)`|P3@kiA)R_q($_5NzxVUG>cEX>NDm8cZ{XSclvm>C{Fu8dH zfVe%=LjZt>+eg-~Z0BH`^-r#k005nCOHjY$;B-P2Msra{PJkY$N(7gKvV;lFSuz>| z0Q$W;8$Z8#0RVJQJ5J&{-Ifr(aAmp(1y|-Oq80)NfW<1-Joz!nXy_zDnyTFf=Mr;1 zZZ5UBJ^Ls^lL%LMhzP}$x+4_sBZ9J|KDZ3rM}$#8S-7tVSv0@~&z2doWmZZ=&DPrw zn@ua6{*M}wF~>Yjb3V$fUfy5nKyr--6$?!d9#ojcs>A z#{c;atO;1GVq--ESgUB)Sk#D^156V@2l$F8f^!T2kWY8dP(Ry58_*T5j514g!g-on z;VzxeT<)&cs#vRL`U zfzJ;Umt6q9SGm72VdJXFxWcF7f%y7RG>N#}ea$^@?QL3<>J80QU(@kG0OT!D4jVkg kxEz!vO@S)lTrPc~?+<(^b literal 0 HcmV?d00001 diff --git a/assets/sprites/blocks/liquids/liquid-gauge-pointer.png b/assets/sprites/blocks/liquids/liquid-gauge-pointer.png new file mode 100644 index 0000000000000000000000000000000000000000..8cfa110f9d6a3f758261f8252dcb7544f402dbbb GIT binary patch literal 157 zcmeAS@N?(olHy`uVBq!ia0vp^3LwnE1|*BCs=fdz&H|6fVg?3oVGw3ym^DWNDCqC$ z;usRq`gW=(7lQ)Nk*NRwpMO--`0_wOL~&<1Pl+MZf|(`Us+ruUwrpzC{=mf|;Bes9 z-Op@m3?7Tch==s=7J94e@L<2<8kIZu1sE6-n2a+;q(Z&_n*xny@O1TaS?83{1OSgu BFUtS` literal 0 HcmV?d00001 diff --git a/assets/sprites/blocks/liquids/liquid-gauge-tiles.png b/assets/sprites/blocks/liquids/liquid-gauge-tiles.png new file mode 100644 index 0000000000000000000000000000000000000000..afcea6c37646e325c468b450b6e3e67540834608 GIT binary patch literal 576 zcmeAS@N?(olHy`uVBq!ia0vp^3P9Yz!3HF=(z2z16lZ})WHAE+w=f7ZGR&GI!N9=y z$^B zz4QKH@%(b@^|`;d_&Uu9d$d&`*!$xR%Z1gdj9Evs70x{Td|I;U!qM%oFIMz&KYIH0 zuymZIiy!|Mk^We1(`7frvyV=9a!GGI6OpaFOn5HqVkQP@JNsbC)u{!(f8`#qFF(C= zw!nUKf45(@0h1m_vtAE*&&Y7&sl^oLsI}}1OB2qqPR=ye^rJ*&T>dTdsF*nr4Tb;q|U_Hu9_oxkL3Y zercN!x{2N3mu}=yc@CzGj%Wtm`UZ`UX(3v1+>G@M{}}!-eqANO@PYjS{{eXhAnynB z2lkM^jNB8NUr1{Ga}aT0R{EKDLph~PcAwY@`8As)3On8iB>Z>itau~ygW2W*zlZJ* zW`+iP29RM4AX6IbC(LPEDiHdceM?Q_&aeFVdQ&MBb@09L^BqW}N^ literal 0 HcmV?d00001 diff --git a/assets/sprites/blocks/liquids/liquid-gauge.png b/assets/sprites/blocks/liquids/liquid-gauge.png new file mode 100644 index 0000000000000000000000000000000000000000..42ab6a4de5cdd66297bc4b50b44f314620a25709 GIT binary patch literal 432 zcmV;h0Z;ykP)72C1N++D*B8O`N>JTBr a0RUcpEWkREWyp^J0000("install"){ + dependsOn("jar") + doLast{ + val folder = Fi.get(OS.getAppDataDirectoryString("Mindustry")).child("mods") + folder.mkdirs() + + val input = Fi.get("$rootDir/build/libs/${project.name}Desktop.jar") + folder.child(input.name()).delete() + input.copyTo(folder) + logger.lifecycle("Copied :jar output to $folder.") + } + } } \ No newline at end of file diff --git a/src/omaloon/annotations/AutoImplement.java b/src/omaloon/annotations/AutoImplement.java index 77406236..e9fd4914 100644 --- a/src/omaloon/annotations/AutoImplement.java +++ b/src/omaloon/annotations/AutoImplement.java @@ -9,7 +9,7 @@ @Target(ElementType.METHOD) @interface NoInject { - + Class value(); } diff --git a/src/omaloon/content/OlFx.java b/src/omaloon/content/OlFx.java index cb0d053a..498945d4 100644 --- a/src/omaloon/content/OlFx.java +++ b/src/omaloon/content/OlFx.java @@ -182,26 +182,70 @@ public class OlFx { Draw.blend(); }), - pumpFront = new Effect(60f, e -> { - Draw.alpha(e.fout() / 5f); + flowOut = new Effect(60f, e -> { + Draw.color(e.color); + Draw.alpha(e.fout() / 5); vec.trns(e.rotation, 4f).add(e.x, e.y); - randLenVectors(e.id, 3, 16f * e.fin(), e.rotation, 10f, (x, y) -> { - Fill.circle(vec.x + x, vec.y + y, 3f * e.fin()); + Angles.randLenVectors(e.id, 3, 16 * e.fin(), e.rotation, 10, (x, y) -> { + Fill.circle(vec.x + x, vec.y + y, 3 * e.fin()); + }); + vec.trns(e.rotation, -4f).add(e.x, e.y); + Angles.randLenVectors(e.id + 2, 3, 16 * e.fin(), e.rotation + 180, 10, (x, y) -> { + Fill.circle(vec.x + x, vec.y + y, 3 * e.fin()); + }); + Draw.alpha(e.fout() / 7); + Angles.randLenVectors(e.id + 1, 3, 16 * e.fin(), e.rotation + 180, 20, (x, y) -> { + Fill.rect(vec.x + x, vec.y + y, 5 * e.fin(), e.fin(), vec.angleTo(vec.x + x, vec.y + y)); }); - Draw.alpha(e.fout() / 7f); - randLenVectors(e.id/2, 3, 16f * e.fin(), e.rotation, 20f, (x, y) -> { - Fill.rect(vec.x + x, vec.y + y, 5f * e.fin(), e.fin(), vec.angleTo(vec.x + x, vec.y + y)); + vec.trns(e.rotation, 4f).add(e.x, e.y); + Angles.randLenVectors(e.id + 3, 3, 16 * e.fin(), e.rotation, 20, (x, y) -> { + Fill.rect(vec.x + x, vec.y + y, 5 * e.fin(), e.fin(), vec.angleTo(vec.x + x, vec.y + y)); }); }), - pumpBack = new Effect(60f, e -> { - Draw.alpha(e.fin() / 5f); - vec.trns(e.rotation, 4).add(e.x, e.y); - randLenVectors(e.id, 3, 16f * e.fout(), e.rotation, 10f, (x, y) -> { - Fill.circle(vec.x + x, vec.y + y, 3f * e.fout()); + flowIn = new Effect(60f, e -> { + Draw.color(e.color); + Draw.alpha(e.fin() / 5); + vec.trns(e.rotation, 4f).add(e.x, e.y); + Angles.randLenVectors(e.id, 3, 16 * e.fout(), e.rotation, 10, (x, y) -> { + Fill.circle(vec.x + x, vec.y + y, 3 * e.fout()); + }); + vec.trns(e.rotation, -4f).add(e.x, e.y); + Angles.randLenVectors(e.id + 2, 3, 16 * e.fout(), e.rotation + 180, 10, (x, y) -> { + Fill.circle(vec.x + x, vec.y + y, 3 * e.fout()); + }); + Draw.alpha(e.fin() / 7); + Angles.randLenVectors(e.id + 1, 3, 16 * e.fout(), e.rotation + 180, 20, (x, y) -> { + Fill.rect(vec.x + x, vec.y + y, 5 * e.fout(), e.fout(), vec.angleTo(vec.x + x, vec.y + y)); + }); + vec.trns(e.rotation, 4f).add(e.x, e.y); + Angles.randLenVectors(e.id + 3, 3, 16 * e.fout(), e.rotation, 20, (x, y) -> { + Fill.rect(vec.x + x, vec.y + y, 5 * e.fout(), e.fout(), vec.angleTo(vec.x + x, vec.y + y)); + }); + }), + + pumpOut = new Effect(60f, e -> { + Draw.color(e.color); + Draw.alpha(e.fout() / 5); + vec.trns(e.rotation, 4f).add(e.x, e.y); + Angles.randLenVectors(e.id, 3, 16 * e.fin(), e.rotation, 10, (x, y) -> { + Fill.circle(vec.x + x, vec.y + y, 3 * e.fin()); + }); + Draw.alpha(e.fout() / 7); + vec.trns(e.rotation, 4f).add(e.x, e.y); + Angles.randLenVectors(e.id + 3, 3, 16 * e.fin(), e.rotation, 20, (x, y) -> { + Fill.rect(vec.x + x, vec.y + y, 5 * e.fin(), e.fin(), vec.angleTo(vec.x + x, vec.y + y)); + }); + }), + pumpIn = new Effect(60f, e -> { + Draw.color(e.color); + Draw.alpha(e.fin() / 5); + vec.trns(e.rotation, 4f).add(e.x, e.y); + Angles.randLenVectors(e.id, 3, 16 * e.fout(), e.rotation, 10, (x, y) -> { + Fill.circle(vec.x + x, vec.y + y, 3 * e.fout()); }); - Draw.alpha(e.fin() / 7f); - randLenVectors(e.id/2, 3, 16f * e.fout(), e.rotation, 20f, (x, y) -> { - Fill.rect(vec.x + x, vec.y + y, 5f * e.fout(), e.fout(), vec.angleTo(vec.x + x, vec.y + y)); + Draw.alpha(e.fin() / 7); + Angles.randLenVectors(e.id + 3, 3, 16 * e.fout(), e.rotation, 20, (x, y) -> { + Fill.rect(vec.x + x, vec.y + y, 5 * e.fout(), e.fout(), vec.angleTo(vec.x + x, vec.y + y)); }); }), diff --git a/src/omaloon/content/OlLiquids.java b/src/omaloon/content/OlLiquids.java index a11b84ae..b53fe848 100644 --- a/src/omaloon/content/OlLiquids.java +++ b/src/omaloon/content/OlLiquids.java @@ -1,8 +1,14 @@ package omaloon.content; +import arc.*; +import arc.struct.*; +import arc.util.*; import mindustry.content.*; +import mindustry.game.*; import mindustry.type.*; +import mindustry.world.meta.*; import omaloon.type.liquid.*; +import omaloon.world.meta.*; import static arc.graphics.Color.*; @@ -12,6 +18,9 @@ public class OlLiquids { end; + public static ObjectFloatMap densities = new ObjectFloatMap<>(); + public static ObjectFloatMap viscosities = new ObjectFloatMap<>(); + public static void load(){ glacium = new CrystalLiquid("glacium", valueOf("5e929d")){{ effect = OlStatusEffects.glacied; @@ -36,6 +45,44 @@ public static void load(){ canStayOn.add(Liquids.water); }}; + addDensity(Liquids.water, 1000); + addViscosity(Liquids.water, 10); + addDensity(Liquids.slag, 1600); + addViscosity(Liquids.slag, 250); + addDensity(Liquids.oil, 700); + addViscosity(Liquids.oil, 50); + addDensity(Liquids.cryofluid, 200); + addViscosity(Liquids.cryofluid, 1.2f); + addDensity(glacium, 1300); + addViscosity(glacium, 13); + addDensity(tiredGlacium, 1300); + addViscosity(tiredGlacium, 13); + + if (Core.settings.getBool("omaloon-display-liquid-stats", true)) Events.on(EventType.ContentInitEvent.class, e -> { + densities.each(map -> { + map.key.stats.add(OlStats.density, map.value, OlStats.densityUnit); + }); + viscosities.each(map -> { + map.key.checkStats(); + map.key.stats.remove(Stat.viscosity); + map.key.stats.add(Stat.viscosity, Core.bundle.get("stat.omaloon-viscosity"), map.key.viscosity * 100f ,Strings.autoFixed(map.value/60f, 2) + " " + OlStats.viscosityUnit.localized()); + }); + }); } + public static void addDensity(Liquid liquid, float density) { + densities.put(liquid, density); + } + + public static void addViscosity(Liquid liquid, float viscosity) { + viscosities.put(liquid, viscosity); + } + + public static float getDensity(@Nullable Liquid liquid) { + return densities.get(liquid, 8f); + } + + public static float getViscosity(@Nullable Liquid liquid) { + return viscosities.get(liquid, 1f); + } } diff --git a/src/omaloon/content/OlTechTree.java b/src/omaloon/content/OlTechTree.java index 77d4736d..5f5ca348 100644 --- a/src/omaloon/content/OlTechTree.java +++ b/src/omaloon/content/OlTechTree.java @@ -33,13 +33,13 @@ public static void load() { }); node(hammerDrill, () -> { - node(liquidTube, () -> { - node(liquidJunction, () -> { - node(liquidBridge); - }); - node(liquidPump, () -> { - node(liquidValve); + node(liquidPump, () -> { + node(liquidTube, () -> { + node(liquidJunction, () -> { + node(liquidBridge); + }); }); + node(liquidGauge); }); node(carborundumPress, with(new Research(smallShelter)), () -> { diff --git a/src/omaloon/content/OlUnitTypes.java b/src/omaloon/content/OlUnitTypes.java index ac0c731b..98e4a9a8 100644 --- a/src/omaloon/content/OlUnitTypes.java +++ b/src/omaloon/content/OlUnitTypes.java @@ -55,6 +55,7 @@ public static void load() { health = 200f; regenTime = 15f * 60f; chainable = true; + splittable = true; omniMovement = false; angleLimit = 65f; segmentLength = 5; diff --git a/src/omaloon/content/blocks/OlCraftingBlocks.java b/src/omaloon/content/blocks/OlCraftingBlocks.java index 3a7ed0fe..caf4323d 100644 --- a/src/omaloon/content/blocks/OlCraftingBlocks.java +++ b/src/omaloon/content/blocks/OlCraftingBlocks.java @@ -3,6 +3,7 @@ import mindustry.content.*; import mindustry.type.*; import mindustry.world.*; +import mindustry.world.meta.*; import omaloon.content.*; import omaloon.world.blocks.production.*; import omaloon.world.consumers.*; @@ -10,7 +11,7 @@ import static mindustry.type.ItemStack.*; public class OlCraftingBlocks { - public static Block carborundumPress, graphitePress; + public static Block carborundumPress, graphitePress, glaciumBoiler; public static void load() { carborundumPress = new PressureCrafter("carborundum-press") {{ @@ -26,8 +27,17 @@ public static void load() { craftEffect = OlFx.carborundumCraft; consumeItems(with(Items.beryllium, 1, OlItems.cobalt, 1)); - consume(new ConsumePressure(6f, false)); - consume(new PressureEfficiencyRange(5f, 50f, 1.6f, false)); + consume(new ConsumeFluid(null, 5) {{ + startRange = 5f; + endRange = 50f; + efficiencyMultiplier = 1.6f; + curve = t -> Math.min( + 9f/2f * (1f - t), + 9f/7f * t + ); + optimalPressure = 40f; + hasOptimalPressure = true; + }}); outputItems = with(OlItems.carborundum, 1); }}; @@ -44,10 +54,37 @@ public static void load() { craftEffect = Fx.pulverizeMedium; consumeItem(Items.coal, 4); - consume(new ConsumePressure(8f, false)); - consume(new PressureEfficiencyRange(10f, 50f, 1.5f, false)); + consume(new ConsumeFluid(null, 8f) {{ + startRange = 10f; + endRange = 50f; + efficiencyMultiplier = 1.5f; + curve = t -> Math.min( + 8f * (1f - t), + 8f/7f * t + ); + optimalPressure = 45f; + hasOptimalPressure = true; + }}); outputItem = new ItemStack(Items.graphite, 2); }}; + + glaciumBoiler = new PressureCrafter("glacium-boiler") {{ + requirements(Category.crafting, BuildVisibility.sandboxOnly, with()); + size = 2; + + useVanillaLiquids = false; + ignoreLiquidFullness = true; + dumpExtraLiquid = true; + + craftTime = 120f; + + consumeItem(Items.coal, 1); + consume(new ConsumeFluid(OlLiquids.glacium, 1f/60f) {{ + continuous = true; + }}); + + outputAir = 4f/6f; + }}; } } diff --git a/src/omaloon/content/blocks/OlDefenceBlocks.java b/src/omaloon/content/blocks/OlDefenceBlocks.java index fbd4cc29..324cac8d 100644 --- a/src/omaloon/content/blocks/OlDefenceBlocks.java +++ b/src/omaloon/content/blocks/OlDefenceBlocks.java @@ -18,6 +18,7 @@ import omaloon.content.*; import omaloon.world.blocks.defense.*; import omaloon.world.consumers.*; +import omaloon.world.meta.*; import static mindustry.type.ItemStack.*; @@ -48,22 +49,33 @@ public static void load(){ }}; smallShelter = new Shelter("small-shelter") {{ - requirements(Category.effect, with( - OlItems.cobalt, 25, - Items.beryllium, 30 - )); - researchCostMultiplier = 0.3f; - size = 2; - rechargeStandard = 2f; - shieldHealth = 260f; - shieldRange = 170f; - - ambientSound = OlSounds.shelter; - ambientSoundVolume = 0.08f; - - consumePower(0.2f); - consume(new ConsumePressure(0.01f, true)); - consume(new PressureEfficiencyRange(15, 50f, 1.8f, false)); + requirements(Category.effect, with( + OlItems.cobalt, 25, + Items.beryllium, 30 + )); + researchCostMultiplier = 0.3f; + size = 2; + rechargeStandard = 2f; + shieldHealth = 260f; + shieldRange = 170f; + + ambientSound = OlSounds.shelter; + ambientSoundVolume = 0.08f; + + consumePower(0.2f); + consume(new ConsumeFluid(null, 1f/12f) {{ + continuous = true; + hasOptimalPressure = true; + + startRange = 15f; + endRange = 50f; + efficiencyMultiplier = 2f; + optimalPressure = 46.5f; + + curve = t -> Math.max(0f, Mathf.slope(t - 0.25f) * 2f - 1f); + }}); +// consume(new ConsumePressure(0.01f, true)); +// consume(new PressureEfficiencyRange(15, 50f, 1.8f, false)); }}; //endregion //region turrets @@ -152,8 +164,19 @@ Items.graphite, new BasicBulletType(4f, 16){{ )); size = 2; consumePower(70f / 60f); - consume(new ConsumePressure(-6, false)); - consume(new PressureEfficiencyRange(-45f, -1f, 3f, true)); + consume(new ConsumeFluid(null, 6f) {{ + startRange = -45f; + endRange = -0.01f; + efficiencyMultiplier = 3f; + + optimalPressure = -40f; + hasOptimalPressure = true; + + curve = t -> Math.min( + 9f/8f * (1f - t), + 9f * t + ); + }}); targetGround = true; targetAir = false; damage = 0.6f; @@ -235,7 +258,7 @@ public void draw(Bullet b){ }}; }}; - //TODO: 0.2, but let this be sandbox only + //TODO: 0.2, but let this be sandbox only (this needs a massive nerf lmao) javelin = new ConsumeTurret("javelin") {{ requirements(Category.turret, BuildVisibility.sandboxOnly, with()); outlineColor = Color.valueOf("2f2f36"); @@ -266,7 +289,24 @@ public void draw(Bullet b){ }}; shootSound = OlSounds.theShoot; - consumeItem(Items.coal, 1); + consumeItems(with( + Items.coal, 1, + OlItems.carborundum, 3 + )); + consume(new ConsumeFluid(null, 36) {{ + startRange = 1.8f; + endRange = 18f; + + curve = t -> Math.min( + 2f * t, + -2 * t + 2 + ); + + hasOptimalPressure = true; + optimalPressure = 9f; + + efficiencyMultiplier = 2f; + }}); shootType = new BasicBulletType(1.6f, 12f, "omaloon-javelin-missile-outlined"){{ lifetime = 40f; ammoMultiplier = 1f; @@ -347,6 +387,10 @@ public void draw(Bullet b){ }}); }}; }}; + + pressureConfig = new PressureConfig() {{ + fluidCapacity = 20; + }}; }}; //endregion //region walls diff --git a/src/omaloon/content/blocks/OlDistributionBlocks.java b/src/omaloon/content/blocks/OlDistributionBlocks.java index ff608546..c27bca91 100644 --- a/src/omaloon/content/blocks/OlDistributionBlocks.java +++ b/src/omaloon/content/blocks/OlDistributionBlocks.java @@ -1,13 +1,17 @@ package omaloon.content.blocks; +import arc.graphics.*; import mindustry.content.*; +import mindustry.gen.*; import mindustry.graphics.*; import mindustry.type.*; import mindustry.world.*; import mindustry.world.draw.*; +import mindustry.world.meta.*; import omaloon.content.*; import omaloon.world.blocks.distribution.*; import omaloon.world.blocks.liquid.*; +import omaloon.world.meta.*; import static mindustry.type.ItemStack.*; @@ -17,7 +21,7 @@ public class OlDistributionBlocks { tubeConveyor, tubeDistributor, tubeJunction, tubeSorter, tubeGate, tubeBridge, //liquid - liquidTube, liquidJunction, liquidBridge, liquidPump, liquidValve, + liquidTube, liquidJunction, liquidBridge, liquidPump, filterPump, liquidValve, liquidGauge, end; @@ -102,7 +106,7 @@ public static void load() { OlItems.cobalt, 2 )); researchCost = with( - OlItems.cobalt, 15 + OlItems.cobalt, 10 ); }}; @@ -122,18 +126,47 @@ public static void load() { }}; liquidPump = new PressureLiquidPump("liquid-pump") {{ + requirements(Category.liquid, with( + OlItems.cobalt, 4 + )); + researchCost = with( + OlItems.cobalt, 25 + ); + pumpStrength = 5f/60f; + + ambientSound = Sounds.wind2; + ambientSoundVolume = 0.1f; + + pumpEffectIn = OlFx.pumpIn; + pumpEffectOut = OlFx.pumpOut; + + pressureConfig = new PressureConfig() {{ +// minPressure = -25f; +// maxPressure = 25f; + }}; + }}; + + filterPump = new PressureLiquidPump("filter-pump") {{ requirements(Category.liquid, with( OlItems.cobalt, 4 )); researchCost = with( OlItems.cobalt, 20 ); - pressureTransfer = 0.1f; - pressureDifference = 5f; + pumpStrength = 1f/6f; + pressureDifference = 0; + + configurable = true; + + ambientSound = Sounds.wind2; + ambientSoundVolume = 0.1f; + + pumpEffectIn = OlFx.pumpIn; + pumpEffectOut = OlFx.pumpOut; }}; liquidValve = new PressureLiquidValve("liquid-valve") {{ - requirements(Category.liquid, with( + requirements(Category.liquid, BuildVisibility.sandboxOnly, with( OlItems.cobalt, 2, Items.beryllium, 2 )); @@ -142,6 +175,20 @@ public static void load() { Items.beryllium, 20 ); pressureLoss = 0.3f; + + pumpingEffectIn = OlFx.flowIn; + pumpingEffectOut = OlFx.flowOut; + }}; + + liquidGauge = new PressureLiquidGauge("liquid-gauge") {{ + requirements(Category.liquid, with( + OlItems.cobalt, 2, + Items.beryllium, 1 + )); + researchCost = with( + OlItems.cobalt, 20, + Items.beryllium, 10 + ); }}; //endregion } diff --git a/src/omaloon/content/blocks/OlProductionBlocks.java b/src/omaloon/content/blocks/OlProductionBlocks.java index 6434d455..9f4cd80b 100644 --- a/src/omaloon/content/blocks/OlProductionBlocks.java +++ b/src/omaloon/content/blocks/OlProductionBlocks.java @@ -31,8 +31,19 @@ public static void load(){ pressureConfig.linkList.add(this); - consume(new ConsumePressure(-6, false)); - consume(new PressureEfficiencyRange(-45f, -1f, 2f, true)); + consume(new ConsumeFluid(null, -5f) {{ + startRange = -45f; + endRange = -0.01f; + efficiencyMultiplier = 2f; + + optimalPressure = -40f; + hasOptimalPressure = true; + + curve = t -> Math.min( + 9f/8f * (1f - t), + 9f * t + ); + }}); }}; } } diff --git a/src/omaloon/entities/comp/MillipedeComp.java b/src/omaloon/entities/comp/MillipedeComp.java index 823b6aa3..87ad212f 100644 --- a/src/omaloon/entities/comp/MillipedeComp.java +++ b/src/omaloon/entities/comp/MillipedeComp.java @@ -147,31 +147,30 @@ public int cap(){ return Math.max(Units.getCap(team), Units.getCap(team) * max); } - //TODO WHY DOES IT NOT SHOW UP ON THE UNIT CODE - /*boolean canJoin(Millipedec other) { + boolean canJoin(Unit other) { + if (!(other instanceof Millipedec snek)) return false; MillipedeUnitType uType = (MillipedeUnitType)type; - return uType == other.type() && other.countAll() + countAll() <= uType.maxSegments; - }*/ + return uType == other.type() && snek.countAll() + countAll() <= uType.maxSegments; + } - // TODO make private - public void connect(Millipedec other){ - if(isHead() && other.isTail()){ + public void connect(Unit other){ + if(other instanceof Millipedec snek && isHead() && snek.isTail()){ MillipedeUnitType uType = (MillipedeUnitType) type; - float z = other.layer() + uType.segmentLayerOffset; + float z = snek.layer() + uType.segmentLayerOffset; distributeActionBack(u -> { u.layer(z); - u.head(other.head()); + u.head(snek.head()); }); - other.child(self()); - parent = (Unit)other; - head = other.head(); - setupWeapons(type); + snek.child(self()); + parent = other; + head = snek.head(); + ((Millipedec) head).distributeActionBack(u -> u.setupWeapons(type)); uType.chainSound.at(self()); if(controller() instanceof Player){ UnitController con = controller(); - other.head().controller(con); - con.unit(other.head()); + snek.head().controller(con); + con.unit(snek.head()); controller(type.createController(self())); } } @@ -558,7 +557,7 @@ private void updatePost(){ Tmp.r1.setCentered(Tmp.v1.x, Tmp.v1.y, hitSize()); Units.nearby(Tmp.r1, u -> { if(u.team == team && u.type == type && u instanceof Millipedec m && m.head() != self() && m.isTail() && m.countForward() + countBackward() < uType.maxSegments && m.waitTime() <= 0f && within(u, uType.segmentOffset) && OlUtils.angleDist(rotation(), angleTo(u)) < uType.angleLimit){ - connect(m); + connect(u); } }); scanTime = 0f; diff --git a/src/omaloon/math/OlMath.java b/src/omaloon/math/OlMath.java new file mode 100644 index 00000000..3a5fee21 --- /dev/null +++ b/src/omaloon/math/OlMath.java @@ -0,0 +1,33 @@ +package omaloon.math; + +public class OlMath { + /** + * Solves for the flow of a fluid through an area based on a difference of pressure. + *
    + *
  • pressureStart is the pressure at the back + *
  • pressureEnd is the pressure at the front + *
  • capacityStart is the fluid capacity at the back + *
  • capacityEnd is the fluid capacity at the front + *
  • density is the fluid density + *
  • viscosity is the fluid viscosity + *
+ * + * returns the amount of fluid in liquid units that flows per tick + */ + public static float flowRate(float pressureStart, float pressureEnd, float capacityStart, float capacityEnd, float density, float viscosity) { + return + ( + capacityStart * ( + pressureStart * ( + capacityStart + capacityEnd + ) - ( + pressureEnd * capacityEnd + pressureStart * capacityStart + ) + ) + ) / ( + density * ( + capacityStart + capacityEnd + ) * viscosity + ); + } +} diff --git a/src/omaloon/ui/dialogs/EventHints.java b/src/omaloon/ui/dialogs/EventHints.java index e9cc5363..880df303 100644 --- a/src/omaloon/ui/dialogs/EventHints.java +++ b/src/omaloon/ui/dialogs/EventHints.java @@ -6,64 +6,27 @@ import arc.util.*; import mindustry.*; import mindustry.ui.fragments.HintsFragment.*; -import mindustry.world.consumers.*; -import omaloon.content.blocks.*; -import omaloon.world.consumers.*; +import omaloon.world.blocks.defense.Shelter.*; +import omaloon.world.blocks.liquid.*; +import omaloon.world.blocks.production.PressureDrill.*; import omaloon.world.interfaces.*; public enum EventHints implements Hint { - drill_positive_pressure( + air( () -> false, - () -> Vars.state.teams.get(Vars.state.rules.defaultTeam).getBuildings(OlProductionBlocks.hammerDrill).find(b -> ((HasPressure) b).getPressure() > 0f) != null + () -> Vars.state.rules.defaultTeam.data().buildings.contains(b -> b instanceof HasPressure) ), - press_or_shelter_negative_pressure( + drill( () -> false, - () -> Vars.state.teams.get(Vars.state.rules.defaultTeam).getBuildings(OlCraftingBlocks.carborundumPress).find(b -> ((HasPressure) b).getPressure() < 0f) != null - || Vars.state.teams.get(Vars.state.rules.defaultTeam).getBuildings(OlDefenceBlocks.smallShelter).find(b -> ((HasPressure) b).getPressure() < 0f) != null + () -> Vars.state.rules.defaultTeam.data().buildings.contains(b -> b instanceof PressureDrillBuild) ), - pump_positive( - () -> false, - () -> Vars.state.teams.get(Vars.state.rules.defaultTeam).buildings.contains( - b -> { - if (b instanceof HasPressure pressureBuilding) { - for (Consume consumer : b.block().consumers) { - if (consumer instanceof PressureEfficiencyRange rangeConsumer) { - return pressureBuilding.getPressure() > 0 && rangeConsumer.shouldConsume(pressureBuilding); - } - } - } - return false; - } - ) - ), - pump_negative( - () -> false, - () -> Vars.state.teams.get(Vars.state.rules.defaultTeam).buildings.contains( - b -> { - if (b instanceof HasPressure pressureBuilding) { - for (Consume consumer : b.block().consumers) { - if (consumer instanceof PressureEfficiencyRange rangeConsumer) { - return pressureBuilding.getPressure() < 0 && rangeConsumer.shouldConsume(pressureBuilding); - } - } - } - return false; - } - ) - ), - pump( + pump_chaining( () -> false, - () -> !Vars.state.teams.get(Vars.state.rules.defaultTeam).getBuildings(OlDistributionBlocks.liquidPump).isEmpty() + () -> Vars.control.input.block instanceof PressureLiquidPump ), - valve( + shelter( () -> false, - () -> !Vars.state.teams.get(Vars.state.rules.defaultTeam).getBuildings(OlDistributionBlocks.liquidValve).isEmpty(), - pump - ), - low_pressure( - () -> !Vars.state.teams.get(Vars.state.rules.defaultTeam).getBuildings(OlDistributionBlocks.liquidValve).isEmpty(), - () -> Vars.state.teams.get(Vars.state.rules.defaultTeam).buildings.contains( - b -> b instanceof HasPressure pressure && pressure.getPressure() < 0) + () -> Vars.state.rules.defaultTeam.data().buildings.contains(b -> b instanceof ShelterBuild) ); final Boolp complete; diff --git a/src/omaloon/ui/dialogs/OlGameDialog.java b/src/omaloon/ui/dialogs/OlGameDialog.java index 2ba85ac5..871efbda 100644 --- a/src/omaloon/ui/dialogs/OlGameDialog.java +++ b/src/omaloon/ui/dialogs/OlGameDialog.java @@ -77,6 +77,11 @@ public void rebuild() { true, b -> {} ); + addCheck( + "@setting.omaloon-display-liquid-stats", "@setting.omaloon-display-liquid-stats.description", "omaloon-display-liquid-stats", + true, b -> {} + ); + cont.button("@settings.reset", () -> { resetToDefaults(); rebuild(); diff --git a/src/omaloon/ui/elements/CenterBar.java b/src/omaloon/ui/elements/CenterBar.java new file mode 100644 index 00000000..64335209 --- /dev/null +++ b/src/omaloon/ui/elements/CenterBar.java @@ -0,0 +1,130 @@ +package omaloon.ui.elements; + +import arc.*; +import arc.func.*; +import arc.graphics.*; +import arc.graphics.g2d.*; +import arc.math.*; +import arc.scene.style.*; +import arc.scene.ui.layout.*; +import arc.util.pooling.*; +import mindustry.gen.*; +import mindustry.ui.*; + +public class CenterBar extends Bar { + private Floatp fraction; + private CharSequence name = ""; + private float value, lastValue, blink, outlineRadius; + private Color blinkColor = new Color(), outlineColor = new Color(); + + public CenterBar(String name, Color color, Floatp fraction) { + this.fraction = fraction; + this.name = Core.bundle.get(name, name); + this.blinkColor.set(color); + lastValue = value = fraction.get(); + setColor(color); + } + + public CenterBar(Prov name, Prov color, Floatp fraction) { + this.fraction = fraction; + lastValue = value = Mathf.clamp(fraction.get()); + update(() -> { + this.name = name.get(); + this.blinkColor.set(color.get()); + setColor(color.get()); + }); + } + + public CenterBar() { + + } + + public void reset(float value){ + this.value = lastValue = blink = value; + } + + public void set(Prov name, Floatp fraction, Color color){ + this.fraction = fraction; + this.lastValue = fraction.get(); + this.blinkColor.set(color); + setColor(color); + update(() -> this.name = name.get()); + } + + public void snap(){ + lastValue = value = fraction.get(); + } + + public Bar outline(Color color, float stroke){ + outlineColor.set(color); + outlineRadius = Scl.scl(stroke); + return this; + } + + public void flash(){ + blink = 1f; + } + + public Bar blink(Color color){ + blinkColor.set(color); + return this; + } + + @Override + public void draw(){ + if(fraction == null) return; + + float computed = Mathf.clamp(fraction.get(), -1f, 1f); + + + if(lastValue > computed){ + blink = 1f; + lastValue = computed; + } + + if(Float.isNaN(lastValue)) lastValue = 0; + if(Float.isInfinite(lastValue)) lastValue = 1f; + if(Float.isNaN(value)) value = 0; + if(Float.isInfinite(value)) value = 1f; + if(Float.isNaN(computed)) computed = 0; + if(Float.isInfinite(computed)) computed = 1f; + + blink = Mathf.lerpDelta(blink, 0f, 0.2f); + value = Mathf.lerpDelta(value, computed, 0.15f); + + Drawable bar = Tex.bar; + + if(outlineRadius > 0){ + Draw.color(outlineColor); + bar.draw(x - outlineRadius, y - outlineRadius, width + outlineRadius*2, height + outlineRadius*2); + } + + Draw.colorl(0.1f); + Draw.alpha(parentAlpha); + bar.draw(x, y, width, height); + Draw.color(color, blinkColor, blink); + Draw.alpha(parentAlpha); + + Drawable top = Tex.barTop; + + top.draw( + x + (width/2f - Core.atlas.find("bar-top").width/2f) * (Math.min(value, 0f) + 1f), + y, + Core.atlas.find("bar-top").width + (-Core.atlas.find("bar-top").width/2f + width/2f) * Math.abs(value), + height + ); + + Draw.color(); + + Font font = Fonts.outline; + GlyphLayout lay = Pools.obtain(GlyphLayout.class, GlyphLayout::new); + lay.setText(font, name); + + font.setColor(1f, 1f, 1f, 1f); + font.getCache().clear(); + font.getCache().addText(name, x + width / 2f - lay.width / 2f, y + height / 2f + lay.height / 2f + 1); + font.getCache().draw(parentAlpha); + + Pools.free(lay); + } +} diff --git a/src/omaloon/world/blocks/defense/BlastTower.java b/src/omaloon/world/blocks/defense/BlastTower.java index c514f81a..e9459c7f 100644 --- a/src/omaloon/world/blocks/defense/BlastTower.java +++ b/src/omaloon/world/blocks/defense/BlastTower.java @@ -6,7 +6,7 @@ import arc.math.*; import arc.struct.*; import arc.util.*; -import arc.util.io.*;; +import arc.util.io.*; import mindustry.content.*; import mindustry.entities.*; import mindustry.entities.units.*; @@ -103,67 +103,6 @@ public float efficiencyMultiplier() { return val; } - @Override - public void updateTile() { - updatePressure(); - dumpPressure(); - super.updateTile(); - - targets.clear(); - Units.nearbyEnemies(team, x, y, range, u -> { - if(u.checkTarget(targetAir, targetGround)) { - targets.add(u); - } - }); - - indexer.allBuildings(x, y, range, b -> { - if(b.team != team){ - targets.add(b); - } - }); - - float effMultiplier = efficiencyMultiplier(); - - if (targets.size > 0 && canConsume()) { - smoothProgress = Mathf.approach(smoothProgress, 1f, Time.delta / chargeTime * effMultiplier); - - if (efficiency > 0 && (charge += Time.delta * effMultiplier) >= reload && smoothProgress >= 0.99f) { - shoot(); - charge = 0f; - } - } else { - smoothProgress = Mathf.approach(smoothProgress, 0f, Time.delta / chargeTime * effMultiplier); - } - } - - public void shoot() { - if (!canConsume()) return; - - consume(); - lastShootTime = Time.time; - Effect.shake(shake, shake, this); - shootSound.at(this); - waveEffect.layer(Layer.blockUnder).at(x, y, range, waveColor); - tile.getLinkedTiles(t -> OlFx.hammerHit.layer(Layer.blockUnder).at( - t.worldx(), t.worldy(), - angleTo(t.worldx(), t.worldy()) + Mathf.range(360f), - Tmp.c1.set(t.floor().mapColor).mul(1.5f + Mathf.range(0.15f))) - ); - - float damageMultiplier = efficiencyMultiplier(); - for (Teamc target : targets) { - hitEffect.at(target.x(), target.y(), hitColor); - if(target instanceof Healthc){ - ((Healthc)target).damage(damage * damageMultiplier); - } - if(target instanceof Statusc){ - ((Statusc)target).apply(status, statusDuration); - } - } - - smoothProgress = 0f; - } - @Override public void draw() { Draw.rect(region, x, y); @@ -181,22 +120,82 @@ public void drawSelect(){ Drawf.dashCircle(x, y, range, Pal.accent); } - @Override - public void write(Writes write) { - super.write(write); - write.f(lastShootTime); - write.f(smoothProgress); - write.f(charge); - AutoImplement.Util.Inject(HasPressureImpl.class); - } - - @Override - public void read(Reads read, byte revision) { - super.read(read, revision); - lastShootTime = read.f(); - smoothProgress = read.f(); - charge = read.f(); - AutoImplement.Util.Inject(HasPressureImpl.class); - } + @Override + public void read(Reads read, byte revision) { + super.read(read, revision); + lastShootTime = read.f(); + smoothProgress = read.f(); + charge = read.f(); + AutoImplement.Util.Inject(HasPressureImpl.class); + } + + public void shoot() { + if (!canConsume()) return; + + consume(); + lastShootTime = Time.time; + Effect.shake(shake, shake, this); + shootSound.at(this); + waveEffect.layer(Layer.blockUnder).at(x, y, range, waveColor); + tile.getLinkedTiles(t -> OlFx.hammerHit.layer(Layer.blockUnder).at( + t.worldx(), t.worldy(), + angleTo(t.worldx(), t.worldy()) + Mathf.range(360f), + Tmp.c1.set(t.floor().mapColor).mul(1.5f + Mathf.range(0.15f))) + ); + + float damageMultiplier = efficiencyMultiplier(); + for (Teamc target : targets) { + hitEffect.at(target.x(), target.y(), hitColor); + if(target instanceof Healthc){ + ((Healthc)target).damage(damage * damageMultiplier); + } + if(target instanceof Statusc){ + ((Statusc)target).apply(status, statusDuration); + } + } + + smoothProgress = 0f; + } + + @Override + public void updateTile() { + AutoImplement.Util.Inject(HasPressureImpl.class); + super.updateTile(); + + targets.clear(); + Units.nearbyEnemies(team, x, y, range, u -> { + if(u.checkTarget(targetAir, targetGround)) { + targets.add(u); + } + }); + + indexer.allBuildings(x, y, range, b -> { + if(b.team != team){ + targets.add(b); + } + }); + + float effMultiplier = efficiencyMultiplier(); + + if (targets.size > 0 && canConsume()) { + smoothProgress = Mathf.approach(smoothProgress, 1f, Time.delta / chargeTime * effMultiplier); + + if (efficiency > 0 && (charge += Time.delta * effMultiplier) >= reload && smoothProgress >= 0.99f) { + shoot(); + charge = 0f; + } + } else { + smoothProgress = Mathf.approach(smoothProgress, 0f, Time.delta / chargeTime * effMultiplier); + } + } + + @Override + public void write(Writes write) { + super.write(write); + write.f(lastShootTime); + write.f(smoothProgress); + write.f(charge); + AutoImplement.Util.Inject(HasPressureImpl.class); + } } -} \ No newline at end of file +} diff --git a/src/omaloon/world/blocks/defense/ConsumeTurret.java b/src/omaloon/world/blocks/defense/ConsumeTurret.java index 11093c79..b91e9f1b 100644 --- a/src/omaloon/world/blocks/defense/ConsumeTurret.java +++ b/src/omaloon/world/blocks/defense/ConsumeTurret.java @@ -17,7 +17,7 @@ public class ConsumeTurret extends Turret { public PressureConfig pressureConfig = new PressureConfig(); /** - * if true, min range this turret can only target + * If true, this turret cannot target things that are closer than the minRange */ public boolean minRangeShoot = true; @@ -66,6 +66,7 @@ protected void findTarget() { return canConsume(); } + @Override public BulletType peekAmmo() { return shootType; } @@ -82,7 +83,6 @@ protected void shoot(BulletType type) { @Override public void updateTile() { updatePressure(); - dumpPressure(); super.updateTile(); } diff --git a/src/omaloon/world/blocks/defense/Shelter.java b/src/omaloon/world/blocks/defense/Shelter.java index 643642b3..a05d6449 100644 --- a/src/omaloon/world/blocks/defense/Shelter.java +++ b/src/omaloon/world/blocks/defense/Shelter.java @@ -9,7 +9,7 @@ import arc.struct.*; import arc.util.*; import arc.util.io.*; -import arclibrary.graphics.*;; +import arclibrary.graphics.*; import mindustry.*; import mindustry.content.*; import mindustry.entities.*; @@ -85,7 +85,6 @@ public Shelter(String name) { solid = true; configurable = true; saveConfig = true; - hasLiquids = true; group = BlockGroup.projectors; ambientSound = Sounds.shield; ambientSoundVolume = 0.08f; @@ -135,6 +134,7 @@ public void drawPlanRegion(BuildPlan plan, Eachable list) { public class ShelterBuild extends Building implements HasPressureImpl { + public float rot = 90; public float shieldDamage = 0; public float warmup = 0; @@ -216,7 +216,6 @@ public boolean onConfigureTapped(float x, float y) { return false; } - @Override public void read(Reads read, byte revision) { super.read(read, revision); @@ -228,8 +227,8 @@ public void read(Reads read, byte revision) { @Override public void updateTile() { + HasPressureImpl.super.updateTile(); updatePressure(); - dumpPressure(); if (efficiency > 0) { if (shieldDamage >= 0) { shieldDamage -= edelta() * (broken ? rechargeBroken : rechargeStandard); @@ -240,12 +239,15 @@ public void updateTile() { if (broken) { warmup = Mathf.approachDelta(warmup, 0f, warmupTime); } else { - warmup = Mathf.approachDelta(warmup, efficiency, warmupTime); + warmup = Mathf.approachDelta(warmup, efficiency * efficiencyMultiplier(), warmupTime); + + float radius = shieldRange * warmup + shieldBuffer; + Groups.bullet.intersect( - x - shieldRange - shieldBuffer, - y - shieldRange - shieldBuffer, - (shieldRange + shieldBuffer) * 2f, - (shieldRange + shieldBuffer) * 2f, + x - radius, + y - radius, + radius * 2f, + radius * 2f, b -> { if (b.team == Team.derelict) { float distance = Mathf.dst(x, y, b.x, b.y); @@ -275,6 +277,7 @@ public void updateTile() { @Override public void write(Writes write) { super.write(write); + pressure.write(write); write.f(rot); write.f(shieldDamage); write.f(warmup); diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidBridge.java b/src/omaloon/world/blocks/liquid/PressureLiquidBridge.java index c34f21c2..2295ba34 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidBridge.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidBridge.java @@ -17,7 +17,7 @@ import mindustry.world.*; import mindustry.world.blocks.liquid.*; import mindustry.world.blocks.sandbox.*; -import mindustry.world.meta.BlockGroup; +import mindustry.world.meta.*; import omaloon.annotations.Load; import omaloon.world.blocks.distribution.*; import omaloon.world.interfaces.*; @@ -49,7 +49,6 @@ public class PressureLiquidBridge extends TubeItemBridge { public PressureLiquidBridge(String name) { super(name); - hasLiquids = true; hasItems = false; outputsLiquid = true; canOverdrive = false; @@ -130,6 +129,24 @@ public TextureRegion[] icons(){ return new TextureRegion[]{atlas.find(name + "-icon")}; } + @Override + public void init() { + super.init(); + + if (pressureConfig.fluidGroup == null) pressureConfig.fluidGroup = FluidGroup.transportation; + } + + @Override + public void load() { + super.load(); + bottomRegion = Core.atlas.find("omaloon-liquid-bottom"); + endRegion1 = Core.atlas.find(name + "-end1"); + endBottomRegion = Core.atlas.find(name + "-end-bottom"); + endLiquidRegion = Core.atlas.find(name + "-end-liquid"); + bridgeBottomRegion = Core.atlas.find(name + "-bridge-bottom"); + bridgeLiquidRegion = Core.atlas.find(name + "-bridge-liquid"); + } + @Override public void setBars() { super.setBars(); @@ -144,9 +161,12 @@ public void setStats() { public class PressureLiquidBridgeBuild extends TubeItemBridgeBuild implements HasPressureImpl { + + public float smoothAlpha; + @Override - public boolean acceptLiquid(Building source, Liquid liquid) { - return source.block.hasLiquids; + public boolean acceptsPressurizedFluid(HasPressure from, @Nullable Liquid liquid, float amount) { + return HasPressureImpl.super.acceptsPressurizedFluid(from, liquid, amount) && (liquid == pressure.getMain() || liquid == null || pressure.getMain() == null || from.pressure().getMain() == null); } @Override @@ -158,8 +178,12 @@ public boolean canDumpLiquid(Building to, Liquid liquid) { public void draw() { Draw.rect(bottomRegion, x, y); - if(liquids.currentAmount() > 0.001f){ - LiquidBlock.drawTiledFrames(size, x, y, liquidPadding, liquids.current(), liquids.currentAmount() / liquidCapacity); + Liquid main = pressure.getMain(); + + smoothAlpha = Mathf.approachDelta(smoothAlpha, main == null ? 0f : pressure.liquids[main.id]/(pressure.liquids[main.id] + pressure.air), PressureModule.smoothingSpeed); + + if(smoothAlpha > 0.001f){ + LiquidBlock.drawTiledFrames(size, x, y, liquidPadding, pressure.current, Mathf.clamp(smoothAlpha)); } drawBase(); @@ -176,9 +200,12 @@ public void draw() { Draw.alpha(Renderer.bridgeOpacity); drawBridge(bridgeBottomRegion, endBottomRegion, pos1, pos2); - Draw.color(liquids.current().color, liquids.currentAmount()/liquidCapacity * liquids.current().color.a * Renderer.bridgeOpacity); - drawBridge(bridgeLiquidRegion, endLiquidRegion, pos1, pos2); - Draw.color(); + + if (smoothAlpha > 0.001f) { + Draw.color(pressure.current.color, Mathf.clamp(smoothAlpha) * Renderer.bridgeOpacity); + drawBridge(bridgeLiquidRegion, endLiquidRegion, pos1, pos2); + Draw.color(); + } Draw.alpha(Renderer.bridgeOpacity); drawBridge(pos1, pos2); @@ -186,14 +213,24 @@ public void draw() { } @Override - public Seq nextBuilds(boolean flow) { - Seq o = HasPressureImpl.super.nextBuilds(flow); + public Seq nextBuilds() { + Seq o = HasPressureImpl.super.nextBuilds(); if (Vars.world.build(link) instanceof PressureLiquidBridgeBuild b) o.add(b); for(int pos : incoming.items) if (Vars.world.build(pos) instanceof PressureLiquidBridgeBuild b) o.add(b); return o; } + @Override + public boolean outputsPressurizedFluid(HasPressure to, Liquid liquid, float amount) { + return HasPressureImpl.super.outputsPressurizedFluid(to, liquid, amount) && (liquid == to.pressure().getMain() || liquid == null || pressure.getMain() == null || to.pressure().getMain() == null); + } + @Override + public void read(Reads read, byte revision) { + super.read(read, revision); + smoothAlpha = read.f(); + } + @Override public void updateTile() { incoming.size = Math.min(incoming.size, maxConnections - (link == -1 ? 0 : 1)); @@ -201,9 +238,7 @@ public void updateTile() { checkIncoming(); - nextBuilds(true).each(b -> moveLiquidPressure(b, liquids.current())); updatePressure(); - dumpPressure(); Tile other = world.tile(link); if(linkValid(tile, other)) { @@ -248,5 +283,10 @@ protected void drawInput(Tile other){ } } + @Override + public void write(Writes write) { + super.write(write); + write.f(smoothAlpha); + } } } diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidConduit.java b/src/omaloon/world/blocks/liquid/PressureLiquidConduit.java index 6f5e9738..1d0b6a5e 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidConduit.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidConduit.java @@ -5,7 +5,7 @@ import arc.graphics.g2d.*; import arc.math.*; import arc.math.geom.*; -import arc.struct.Seq; +import arc.struct.*; import arc.util.*; import arc.util.io.*; import mindustry.entities.units.*; @@ -13,10 +13,8 @@ import mindustry.graphics.*; import mindustry.input.*; import mindustry.type.*; -import mindustry.world.Block; +import mindustry.world.*; import mindustry.world.blocks.distribution.*; -import mindustry.world.blocks.liquid.*; -import mindustry.world.blocks.sandbox.*; import omaloon.content.blocks.*; import omaloon.utils.*; import omaloon.world.blocks.liquid.PressureLiquidValve.*; @@ -27,9 +25,10 @@ import static mindustry.Vars.*; import static mindustry.type.Liquid.*; -public class PressureLiquidConduit extends LiquidRouter { +public class PressureLiquidConduit extends Block { public PressureConfig pressureConfig = new PressureConfig(); + public TextureRegion bottomRegion; public TextureRegion[] topRegions; public TextureRegion[][] liquidRegions; @@ -40,6 +39,8 @@ public class PressureLiquidConduit extends LiquidRouter { public PressureLiquidConduit(String name) { super(name); rotate = true; + destructible = true; + update = true; } @Override @@ -48,6 +49,8 @@ public void init(){ if(junctionReplacement == null) junctionReplacement = OlDistributionBlocks.liquidJunction; if(bridgeReplacement == null || !(bridgeReplacement instanceof ItemBridge)) bridgeReplacement = OlDistributionBlocks.liquidBridge; + + if (pressureConfig.fluidGroup == null) pressureConfig.fluidGroup = FluidGroup.transportation; } @Override @@ -80,16 +83,12 @@ public void drawPlanRegion(BuildPlan plan, Eachable list) { } } - @Override - public TextureRegion[] icons() { - return new TextureRegion[]{region}; - } - @Override public void load() { super.load(); + topRegions = OlUtils.split(name + "-tiles", 32, 0); - if (!bottomRegion.found()) bottomRegion = Core.atlas.find("omaloon-liquid-bottom"); + bottomRegion = Core.atlas.find(name + "-bottom", "omaloon-liquid-bottom"); liquidRegions = new TextureRegion[2][animationFrames]; if(renderer != null){ @@ -143,12 +142,14 @@ public void setStats() { pressureConfig.addStats(stats); } - public class PressureLiquidConduitBuild extends LiquidRouterBuild implements HasPressureImpl { + public class PressureLiquidConduitBuild extends Building implements HasPressureImpl { + public int tiling = 0; + public float smoothAlpha; @Override - public boolean canDumpLiquid(Building to, Liquid liquid) { - return super.canDumpLiquid(to, liquid) || to instanceof LiquidVoid.LiquidVoidBuild; + public boolean acceptsPressurizedFluid(HasPressure from, @Nullable Liquid liquid, float amount) { + return HasPressureImpl.super.acceptsPressurizedFluid(from, liquid, amount) && (liquid == pressure.getMain() || liquid == null || pressure.getMain() == null || from.pressure().getMain() == null); } @Override @@ -162,27 +163,26 @@ public boolean connects(HasPressure to) { @Override public void draw() { Draw.rect(bottomRegion, x, y); - if (liquids().currentAmount() > 0.01f) { - int frame = liquids.current().getAnimationFrame(); - int gas = liquids.current().gas ? 1 : 0; + Liquid main = pressure.getMain(); + + smoothAlpha = Mathf.approachDelta(smoothAlpha, main == null ? 0f : pressure.liquids[main.id]/(pressure.liquids[main.id] + pressure.air), PressureModule.smoothingSpeed); + + if (smoothAlpha > 0.001f) { + int frame = pressure.current.getAnimationFrame(); + int gas = pressure.current.gas ? 1 : 0; float xscl = Draw.xscl, yscl = Draw.yscl; Draw.scl(1f, 1f); - Drawf.liquid(liquidRegions[gas][frame], x, y, liquids.currentAmount()/liquidCapacity, liquids.current().color.write(Tmp.c1).a(1f)); + Drawf.liquid(liquidRegions[gas][frame], x, y, Mathf.clamp(smoothAlpha), pressure.current.color.write(Tmp.c1).a(1f)); Draw.scl(xscl, yscl); } Draw.rect(topRegions[tiling], x, y, tiling != 0 ? 0 : (rotdeg() + 90) % 180 - 90); } - @Override - public float moveLiquid(Building next, Liquid liquid) { - if (next instanceof HasPressure p) return moveLiquidPressure(p, liquid); - return 0f; - } - @Override public void onProximityUpdate() { super.onProximityUpdate(); + tiling = 0; for (int i = 0; i < 4; i++) { HasPressure build = nearby(i) instanceof HasPressure ? (HasPressure) nearby(i) : null; @@ -192,14 +192,21 @@ public void onProximityUpdate() { } } - + @Override + public boolean outputsPressurizedFluid(HasPressure to, Liquid liquid, float amount) { + return HasPressureImpl.super.outputsPressurizedFluid(to, liquid, amount) && (liquid == to.pressure().getMain() || liquid == null || pressure.getMain() == null || to.pressure().getMain() == null); + } @Override - public void updateTile() { - updatePressure(); - nextBuilds(true).each(b -> moveLiquidPressure(b, liquids.current())); - dumpPressure(); + public void read(Reads read, byte revision) { + super.read(read, revision); + smoothAlpha = read.f(); } + @Override + public void write(Writes write) { + super.write(write); + write.f(smoothAlpha); + } } } diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidGauge.java b/src/omaloon/world/blocks/liquid/PressureLiquidGauge.java new file mode 100644 index 00000000..3ee9a066 --- /dev/null +++ b/src/omaloon/world/blocks/liquid/PressureLiquidGauge.java @@ -0,0 +1,200 @@ +package omaloon.world.blocks.liquid; + +import arc.*; +import arc.graphics.*; +import arc.graphics.g2d.*; +import arc.math.*; +import arc.math.geom.*; +import arc.util.*; +import arc.util.io.*; +import mindustry.entities.units.*; +import mindustry.gen.*; +import mindustry.graphics.*; +import mindustry.type.*; +import mindustry.world.*; +import omaloon.ui.elements.*; +import omaloon.world.interfaces.*; +import omaloon.world.meta.*; +import omaloon.world.modules.*; + +import static mindustry.Vars.*; +import static mindustry.type.Liquid.*; + +public class PressureLiquidGauge extends Block { + public PressureConfig pressureConfig = new PressureConfig(); + + public Color maxColor = Color.white, minColor = Color.white; + + public TextureRegion[][] liquidRegions; + public TextureRegion[] tileRegions; + public TextureRegion bottomRegion, gaugeRegion; + + public float liquidPadding = 3f; + + public PressureLiquidGauge(String name) { + super(name); + rotate = true; + update = true; + destructible = true; + } + + @Override + public void drawPlanRegion(BuildPlan plan, Eachable list) { + var tiling = new Object() { + int tiling = 0; + }; + Point2 + front = new Point2(1, 0).rotate(plan.rotation).add(plan.x, plan.y), + back = new Point2(-1, 0).rotate(plan.rotation).add(plan.x, plan.y); + + boolean inverted = plan.rotation == 1 || plan.rotation == 2; + list.each(next -> { + if (new Point2(next.x, next.y).equals(front) && next.block.outputsLiquid) tiling.tiling |= inverted ? 2 : 1; + if (new Point2(next.x, next.y).equals(back) && next.block.outputsLiquid) tiling.tiling |= inverted ? 1 : 2; + }); + + Draw.rect(bottomRegion, plan.drawx(), plan.drawy()); + Draw.rect(tileRegions[tiling.tiling], plan.drawx(), plan.drawy(), (plan.rotation + 1) * 90f % 180 - 90); + Draw.rect(gaugeRegion, plan.drawx(), plan.drawy(), plan.rotation * 90f); + } + + @Override + public TextureRegion[] icons() { + return new TextureRegion[]{bottomRegion, region}; + } + + @Override + public void init() { + super.init(); + + if (pressureConfig.fluidGroup == null) pressureConfig.fluidGroup = FluidGroup.transportation; + } + + @Override + public void load() { + super.load(); + tileRegions = Core.atlas.find(name + "-tiles").split(32, 32)[0]; + gaugeRegion = Core.atlas.find(name + "-pointer");; + bottomRegion = Core.atlas.find(name + "-bottom", "omaloon-liquid-bottom"); + + liquidRegions = new TextureRegion[2][animationFrames]; + if(renderer != null){ + var frames = renderer.getFluidFrames(); + + for (int fluid = 0; fluid < 2; fluid++) { + for (int frame = 0; frame < animationFrames; frame++) { + TextureRegion base = frames[fluid][frame]; + TextureRegion result = new TextureRegion(); + result.set(base); + + result.setHeight(result.height - liquidPadding); + result.setWidth(result.width - liquidPadding); + result.setX(result.getX() + liquidPadding); + result.setY(result.getY() + liquidPadding); + + liquidRegions[fluid][frame] = result; + } + } + } + } + + @Override + public void setBars() { + super.setBars(); + pressureConfig.addBars(this); + addBar("pressure", entity -> { + HasPressure build = (HasPressure)entity; + + return new CenterBar( + () -> Core.bundle.get("bar.pressure") + (build.pressure().getPressure(build.pressure().getMain()) < 0 ? "-" : "+") + Strings.autoFixed(Math.abs(build.pressure().getPressure(build.pressure().getMain())), 2), + () -> build.pressure().getPressure(build.pressure().getMain()) > 0 ? maxColor : minColor, + () -> Mathf.map(build.pressure().getPressure(build.pressure().getMain()), pressureConfig.minPressure, pressureConfig.maxPressure, -1, 1) + ); + }); + } + + @Override + public void setStats() { + super.setStats(); + pressureConfig.addStats(stats); + } + + public class PressureLiquidGaugeBuild extends Building implements HasPressureImpl { + + public int tiling; + public float smoothAlpha; + + @Override + public boolean acceptsPressurizedFluid(HasPressure from, @Nullable Liquid liquid, float amount) { + return HasPressureImpl.super.acceptsPressurizedFluid(from, liquid, amount) && (liquid == pressure.getMain() || liquid == null || pressure.getMain() == null || from.pressure().getMain() == null); + } + + @Override + public boolean connects(HasPressure to) { + return HasPressureImpl.super.connects(to) && to instanceof PressureLiquidValve.PressureLiquidValveBuild ? + (front() == to || back() == to) && (to.front() == this || to.back() == this) : + (front() == to || back() == to); + } + + @Override + public void draw() { + Draw.rect(bottomRegion, x, y); + Liquid main = pressure.getMain(); + + smoothAlpha = Mathf.approachDelta(smoothAlpha, main == null ? 0f : pressure.liquids[main.id]/(pressure.liquids[main.id] + pressure.air), PressureModule.smoothingSpeed); + + if (smoothAlpha > 0.001f) { + int frame = pressure.current.getAnimationFrame(); + int gas = pressure.current.gas ? 1 : 0; + + float xscl = Draw.xscl, yscl = Draw.yscl; + Draw.scl(1f, 1f); + Drawf.liquid(liquidRegions[gas][frame], x, y, Mathf.clamp(smoothAlpha), pressure.current.color.write(Tmp.c1).a(1f)); + Draw.scl(xscl, yscl); + } + Draw.rect(tileRegions[tiling], x, y, tiling == 0 ? 0 : (rotdeg() + 90) % 180 - 90); + + float p = Mathf.map(pressure().getPressure(pressure().getMain()), pressureConfig.minPressure, pressureConfig.maxPressure, -1, 1); + Draw.color( + Color.white, + pressure().getPressure(pressure().getMain()) > 0 ? maxColor : minColor, + Math.abs(p) + ); + Draw.rect(gaugeRegion, + x, + y, + (rotdeg() + 90) % 180 - 90 + ( + pressure().getPressure(pressure().getMain()) > pressureConfig.maxPressure + 1 || + pressure().getPressure(pressure().getMain()) < pressureConfig.minPressure - 1 + ? Mathf.randomSeed((long) Time.time, -360f, 360f) : p * 180f + ) + ); + } + + @Override + public void onProximityUpdate() { + super.onProximityUpdate(); + + tiling = 0; + boolean inverted = rotation == 1 || rotation == 2; + if (front() instanceof HasPressure front && connected(front)) tiling |= inverted ? 2 : 1; + if (back() instanceof HasPressure back && connected(back)) tiling |= inverted ? 1 : 2; + } + + @Override + public boolean outputsPressurizedFluid(HasPressure to, Liquid liquid, float amount) { + return HasPressureImpl.super.outputsPressurizedFluid(to, liquid, amount) && (liquid == to.pressure().getMain() || liquid == null || pressure.getMain() == null || to.pressure().getMain() == null); + } + @Override + public void read(Reads read, byte revision) { + super.read(read, revision); + smoothAlpha = read.f(); + } + + @Override + public void write(Writes write) { + super.write(write); + write.f(smoothAlpha); + } + } +} diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidJunction.java b/src/omaloon/world/blocks/liquid/PressureLiquidJunction.java index 91d4fa9e..20b26a90 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidJunction.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidJunction.java @@ -1,27 +1,27 @@ package omaloon.world.blocks.liquid; import arc.struct.*; +import arc.util.*; import arc.util.io.*; import mindustry.gen.*; import mindustry.type.*; -import mindustry.world.blocks.liquid.*; +import mindustry.world.*; import omaloon.world.interfaces.*; import omaloon.world.meta.*; import omaloon.world.modules.*; -public class PressureLiquidJunction extends LiquidJunction { +public class PressureLiquidJunction extends Block { public PressureConfig pressureConfig = new PressureConfig(); public PressureLiquidJunction(String name) { super(name); + update = true; + destructible = true; } - public class PressureLiquidJunctionBuild extends LiquidJunctionBuild implements HasPressureImpl { + public class PressureLiquidJunctionBuild extends Building implements HasPressureImpl { - @Override public boolean acceptLiquid(Building source, Liquid liquid) { - return false; - } - @Override public boolean acceptsPressure(HasPressure from, float pressure) { + @Override public boolean acceptsPressurizedFluid(HasPressure from, @Nullable Liquid liquid, float amount) { return false; } @@ -36,15 +36,23 @@ public HasPressure getPressureDestination(HasPressure source, float pressure) { int dir = (source.relativeTo(tile.x, tile.y) + 4) % 4; HasPressure next = nearby(dir) instanceof HasPressure ? (HasPressure) nearby(dir) : null; - if(next == null || (!next.acceptsPressure(source, pressure) && !(next.block() instanceof PressureLiquidJunction))){ + if(next == null) { return this; } return next.getPressureDestination(this, pressure); } + @Override public HasPressure getSectionDestination(HasPressure from) { + return null; + } + @Override - public Seq nextBuilds(boolean flow) { + public Seq nextBuilds() { return Seq.with(); } + + @Override public boolean outputsPressurizedFluid(HasPressure to, @Nullable Liquid liquid, float amount) { + return false; + } } } diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidPump.java b/src/omaloon/world/blocks/liquid/PressureLiquidPump.java index c69ace9d..c0e6d691 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidPump.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidPump.java @@ -1,21 +1,28 @@ package omaloon.world.blocks.liquid; import arc.*; +import arc.graphics.*; import arc.graphics.g2d.*; import arc.math.*; import arc.math.geom.*; -import arc.struct.*; +import arc.scene.ui.layout.*; import arc.util.*; import arc.util.io.*; +import mindustry.*; import mindustry.content.*; import mindustry.entities.*; import mindustry.entities.units.*; import mindustry.gen.*; import mindustry.graphics.*; import mindustry.type.*; +import mindustry.world.*; +import mindustry.world.blocks.*; +import mindustry.world.meta.*; import mindustry.world.blocks.liquid.*; +import omaloon.annotations.AutoImplement; import omaloon.annotations.Load; import omaloon.content.*; +import omaloon.math.*; import omaloon.utils.*; import omaloon.world.interfaces.*; import omaloon.world.meta.*; @@ -24,26 +31,33 @@ import static mindustry.Vars.*; import static mindustry.type.Liquid.*; -public class PressureLiquidPump extends LiquidBlock { +public class PressureLiquidPump extends Block { public PressureConfig pressureConfig = new PressureConfig(); - public float pressureTransfer = 0.1f; + public float pumpStrength = 0.1f; public float pressureDifference = 10; - public Effect pumpEffectForward = OlFx.pumpFront, pumpEffectBackward = OlFx.pumpBack; - public float pumpEffectInterval = 15f; - public float liquidPadding = 3f; + public float effectInterval = 5f; + public Effect pumpEffectOut = Fx.none; + public Effect pumpEffectIn = Fx.none; + public TextureRegion[][] liquidRegions; public TextureRegion[] tiles; - @Load("@-arrow") - public TextureRegion arrowRegion; + public TextureRegion topRegion, bottomRegion, filterRegion; + @Load("@-arrow") public TextureRegion arrowRegion; public PressureLiquidPump(String name) { super(name); rotate = true; + destructible = true; + update = true; + saveConfig = copyConfig = true; + config(Liquid.class, (PressureLiquidPumpBuild build, Liquid liquid) -> { + build.filter = liquid == null ? -1 : liquid.id; + }); } @Override @@ -73,11 +87,21 @@ public void drawPlanRegion(BuildPlan plan, Eachable list) { return new TextureRegion[]{region, topRegion}; } + @Override + public void init() { + super.init(); + + pressureConfig.fluidGroup = FluidGroup.pumps; + } + @Override public void load() { super.load(); tiles = OlUtils.split(name + "-tiles", 32, 0); - if (!bottomRegion.found()) bottomRegion = Core.atlas.find("omaloon-liquid-bottom"); + arrowRegion = Core.atlas.find(name + "-arrow"); + topRegion = Core.atlas.find(name + "-top"); + filterRegion = Core.atlas.find(name + "-filter"); + bottomRegion = Core.atlas.find(name + "-bottom", "omaloon-liquid-bottom"); liquidRegions = new TextureRegion[2][animationFrames]; if(renderer != null){ @@ -104,25 +128,48 @@ public void load() { public void setStats() { super.setStats(); pressureConfig.addStats(stats); - stats.add(OlStats.pressureFlow, Mathf.round(pressureTransfer * 60f, 2), OlStats.pressureSecond); + stats.remove(OlStats.fluidCapacity); + stats.add(OlStats.pumpStrength, pumpStrength * 60f, StatUnit.liquidSecond); + stats.add(OlStats.pressureGradient, OlStats.pressure(pressureDifference, true)); } - public class PressureLiquidPumpBuild extends LiquidBuild implements HasPressureImpl { - - + public class PressureLiquidPumpBuild extends Building implements HasPressureImpl { + public float effectTimer; public int tiling; + public float smoothAlpha; + + public boolean functioning; - public float effectInterval; + public int filter = -1; - @Override public boolean acceptLiquid(Building source, Liquid liquid) { + @Override public boolean acceptsPressurizedFluid(HasPressure from, @Nullable Liquid liquid, float amount) { return false; } - @Override public boolean acceptsPressure(HasPressure from, float pressure) { - return false; + + @Override + public float ambientVolume() { + return 1f/chainSize(); + } + + @Override + public void buildConfiguration(Table table) { + ItemSelection.buildTable(table, Vars.content.liquids(), () -> Vars.content.liquid(filter), other -> filter = other == null ? -1 : other.id); + } + + /** + * Returns the length of the pump chain + */ + public int chainSize() { + return pressure.section.builds.size; + } + + @Override + public Liquid config() { + return content.liquid(filter); } @Override public boolean connects(HasPressure to) { - return HasPressureImpl.super.connects(to) && !(to instanceof PressureLiquidPumpBuild) && (front() == to || back() == to); + return HasPressureImpl.super.connects(to) && (front() == to || back() == to) && (!(to instanceof PressureLiquidPumpBuild) || to.rotation() == rotation); } @Override @@ -130,86 +177,192 @@ public void draw() { float rot = rotate ? (90 + rotdeg()) % 180 - 90 : 0; if (tiling != 0) { Draw.rect(bottomRegion, x, y, rotdeg()); - if (liquids().currentAmount() > 0.01f) { - HasPressure front = (front() instanceof HasPressure b && connected(b)) ? b : null; - HasPressure back = (back() instanceof HasPressure b && connected(b)) ? b : null; + + HasPressure front = getTo(); + HasPressure back = getFrom(); + + if ( + (front != null && front.pressure().getMain() != null) || + (back != null && back.pressure().getMain() != null) + ) { + + Color tmpColor = Tmp.c1; + if (front != null && front.pressure().getMain() != null) { + tmpColor.set(front.pressure().getMain().color); + } else if (back != null && back.pressure().getMain() != null) { + tmpColor.set(back.pressure().getMain().color); + } + + if ( + front != null && front.pressure().getMain() != null && + back != null && back.pressure().getMain() != null + ) tmpColor.lerp(back.pressure().getMain().color, 0.5f); + + float alpha = - (front == null ? 0 : front.liquids().currentAmount()/front.block().liquidCapacity) + - (back == null ? 0 : back.liquids().currentAmount()/back.block().liquidCapacity); + (front != null && front.pressure().getMain() != null ? Mathf.clamp(front.pressure().liquids[front.pressure().getMain().id]/(front.pressure().liquids[front.pressure().getMain().id] + front.pressure().air)) : 0) + + (back != null && back.pressure().getMain() != null ? Mathf.clamp(back.pressure().liquids[back.pressure().getMain().id]/(back.pressure().liquids[back.pressure().getMain().id] + back.pressure().air)) : 0); alpha /= ((front == null ? 0 : 1f) + (back == null ? 0 : 1f)); - int frame = liquids.current().getAnimationFrame(); - int gas = liquids.current().gas ? 1 : 0; + smoothAlpha = Mathf.approachDelta(smoothAlpha, alpha, PressureModule.smoothingSpeed); + + Liquid drawLiquid = Liquids.water; + if (front != null && front.pressure().getMain() != null) { + drawLiquid = front.pressure().current; + } else if (back != null && back.pressure().getMain() != null) { + drawLiquid = back.pressure().current; + } + + int frame = drawLiquid.getAnimationFrame(); + int gas = drawLiquid.gas ? 1 : 0; float xscl = Draw.xscl, yscl = Draw.yscl; Draw.scl(1f, 1f); - Drawf.liquid(liquidRegions[gas][frame], x, y, alpha, - front == null ? back == null ? Liquids.water.color : back.liquids().current().color : front.liquids().current().color - ); + Drawf.liquid(liquidRegions[gas][frame], x, y, smoothAlpha, tmpColor); Draw.scl(xscl, yscl); } Draw.rect(arrowRegion, x, y, rotdeg()); } Draw.rect(tiles[tiling], x, y, rot); + if (filterRegion.found() && configurable && content.liquid(filter) != null) { + Draw.color(content.liquid(filter).color); + Draw.rect(filterRegion, x, y, rot); + Draw.color(); + } if (tiling == 0) Draw.rect(topRegion, x, y, rotdeg()); } - @Override - public Seq nextBuilds(boolean flow) { - return Seq.with(); + /** + * Returns the building at the start of the pump chain. + */ + public @Nullable HasPressure getFrom() { + PressureLiquidPumpBuild last = this; + HasPressure out = back() instanceof HasPressure back ? back.getPressureDestination(last, 0) : null; + while (out instanceof PressureLiquidPumpBuild pump) { + if (!pump.connected(last)) return null; + last = pump; + out = pump.back() instanceof HasPressure back ? back.getPressureDestination(last, 0) : null; + } + return (out != null && out.connected(last)) ? out : null; + } + /** + * Returns the building at the end of the pump chain. + */ + public @Nullable HasPressure getTo() { + PressureLiquidPumpBuild last = this; + HasPressure out = front() instanceof HasPressure front ? front.getPressureDestination(last, 0) : null; + while (out instanceof PressureLiquidPumpBuild pump) { + if (!pump.connected(last)) return null; + last = pump; + out = pump.front() instanceof HasPressure front ? front.getPressureDestination(last, 0) : null; + } + return (out != null && out.connected(last)) ? out : null; } @Override public void onProximityUpdate() { super.onProximityUpdate(); + tiling = 0; boolean inverted = rotation == 1 || rotation == 2; if (front() instanceof HasPressure front && connected(front)) tiling |= inverted ? 2 : 1; if (back() instanceof HasPressure back && connected(back)) tiling |= inverted ? 1 : 2; } + @Override public boolean outputsPressurizedFluid(HasPressure to, @Nullable Liquid liquid, float amount) { + return false; + } + + + @Override + public void read(Reads read, byte revision) { + super.read(read, revision); + filter = read.i(); + smoothAlpha = read.f(); + } + + @Override + public boolean shouldAmbientSound() { + return functioning; + } @Override + @AutoImplement.NoInject(HasPressureImpl.class) public void updateTile() { - super.updateTile(); if (efficiency > 0) { - HasPressure front = (front() instanceof HasPressure b && connected(b)) ? b : null; - HasPressure back = (back() instanceof HasPressure b && connected(b)) ? b : null; - boolean pumped = false; - - float solid = 1; - if (front == null && front() != null || back == null && back() != null) solid++; - - float difference = (front == null ? 0 : front.getPressure()) - (back == null ? 0 : back.getPressure()); - if (difference < pressureDifference/solid) { - if (front != null) front.handlePressure(pressureTransfer * edelta()); - if (back != null) back.removePressure(pressureTransfer * edelta()); - pumped = true; - } else if (back != null && front == null && front() == null) { - back.removePressure(pressureTransfer * edelta()); - pumped = true; - } + HasPressure front = getTo(); + HasPressure back = getFrom(); - if (pumped) effectInterval += delta(); - if (effectInterval > pumpEffectInterval) { - if (front() == null) pumpEffectForward.at(x, y, rotdeg()); - if (back() == null) pumpEffectBackward.at(x, y, rotdeg() + 180f); - effectInterval = 0f; - } + @Nullable Liquid pumpLiquid = configurable ? Vars.content.liquid(filter) : (back == null ? null : back.pressure().getMain()); + + float frontPressure = front == null ? 0 : front.pressure().getPressure(pumpLiquid); + float backPressure = back == null ? 0 : back.pressure().getPressure(pumpLiquid); + + float maxFlow = OlMath.flowRate( + backPressure + pressureDifference * chainSize(), + frontPressure, + back == null ? 5 : back.pressureConfig().fluidCapacity, + front == null ? 5 : front.pressureConfig().fluidCapacity, + OlLiquids.getDensity(pumpLiquid), + 1 + ); if (back != null) { - if (front != null) { - back.moveLiquidPressure(front, back.liquids().current()); + pressure.pressure = back.pressure().getPressure(pumpLiquid); + updatePressure(); + } + if (front != null) { + pressure.pressure = front.pressure().getPressure(pumpLiquid); + updatePressure(); + } + pressure.pressure = 0; + + float flow = Mathf.clamp( + (maxFlow > 0 ? pumpStrength : -pumpStrength)/chainSize() * Time.delta, + -Math.abs(maxFlow), + Math.abs(maxFlow) + ); + + if (effectTimer >= effectInterval && !Mathf.zero(flow, 0.001f)) { + if (flow < 0) { + if (pumpLiquid == null || (front != null && front.pressure().get(pumpLiquid) > 0.001f)) { + if (back == null && !(back() instanceof PressureLiquidPumpBuild p && p.rotation == rotation)) pumpEffectOut.at(x, y, rotdeg() + 180f, pumpLiquid == null ? Color.white : pumpLiquid.color); + if (front == null && !(front() instanceof PressureLiquidPumpBuild p && p.rotation == rotation)) pumpEffectIn.at(x, y, rotdeg(), pumpLiquid == null ? Color.white : pumpLiquid.color); + } } else { - if (front() == null) { - float leakAmount = back.liquids().get(back.liquids().current()) / 1.5f; - Puddles.deposit(tile.nearby(rotation), tile, back.liquids().current(), leakAmount, true, true); - back.liquids().remove(back.liquids().current(), leakAmount); + if (pumpLiquid == null || (back != null && back.pressure().get(pumpLiquid) > 0.001f)) { + if (back == null && !(back() instanceof PressureLiquidPumpBuild p && p.rotation == rotation)) pumpEffectIn.at(x, y, rotdeg() + 180f, pumpLiquid == null ? Color.white : pumpLiquid.color); + if (front == null && !(front() instanceof PressureLiquidPumpBuild p && p.rotation == rotation)) pumpEffectOut.at(x, y, rotdeg(), pumpLiquid == null ? Color.white : pumpLiquid.color); } } + effectTimer %= 1; + } + + functioning = !Mathf.zero(flow, 0.001f); + + if ( + front == null || back == null || + (front.acceptsPressurizedFluid(back, pumpLiquid, flow) && + back.outputsPressurizedFluid(front, pumpLiquid, flow)) + ) { + effectTimer += edelta(); + if (front != null) front.addFluid(pumpLiquid, flow); + if (back != null) back.removeFluid(pumpLiquid, flow); } } } + @Override + public void updatePressure() { + if (pressure().pressure < pressureConfig().minPressure - 1f) damage(pressureConfig().underPressureDamage); + if (pressure().pressure > pressureConfig().maxPressure + 1f) damage(pressureConfig().overPressureDamage); + } + + @Override + public void write(Writes write) { + super.write(write); + write.i(filter); + write.f(smoothAlpha); + } } } diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidValve.java b/src/omaloon/world/blocks/liquid/PressureLiquidValve.java index 994d5f6a..1337711a 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidValve.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidValve.java @@ -2,6 +2,7 @@ import arc.*; import arc.audio.*; +import arc.graphics.*; import arc.graphics.g2d.*; import arc.math.*; import arc.math.geom.*; @@ -13,9 +14,10 @@ import mindustry.gen.*; import mindustry.graphics.*; import mindustry.type.*; -import mindustry.world.blocks.liquid.*; -import mindustry.world.blocks.sandbox.*; +import mindustry.world.*; +import omaloon.annotations.AutoImplement; import omaloon.content.*; +import omaloon.math.*; import omaloon.utils.*; import omaloon.world.interfaces.*; import omaloon.world.meta.*; @@ -24,29 +26,34 @@ import static mindustry.Vars.*; import static mindustry.type.Liquid.*; -public class PressureLiquidValve extends LiquidBlock { +public class PressureLiquidValve extends Block { public PressureConfig pressureConfig = new PressureConfig(); public TextureRegion[] tiles; public TextureRegion[][] liquidRegions; - public TextureRegion valveRegion, topRegion; + public TextureRegion valveRegion, topRegion, bottomRegion; + public Effect jamEffect = Fx.explosion; public Sound jamSound = OlSounds.jam; - public Effect pumpingEffect = OlFx.pumpBack; - public Effect jamEffect = Fx.explosion; + public Effect pumpingEffectOut = Fx.none; + public Effect pumpingEffectIn = Fx.none; public float pumpingEffectInterval = 15; - public float pressureLoss = 0.05f; + public float pressureLoss = 1f; + public float minPressureLoss = 0.05f; public float openMin = -15f; - public float jamPoint = -20f; + public float openMax = 15f; + public float jamPoint = -45f; public float liquidPadding = 3f; public PressureLiquidValve(String name) { super(name); rotate = true; + update = true; + destructible = true; } @Override @@ -75,11 +82,20 @@ public TextureRegion[] icons() { return new TextureRegion[]{bottomRegion, region}; } + @Override + public void init() { + super.init(); + + if (pressureConfig.fluidGroup == null) pressureConfig.fluidGroup = FluidGroup.transportation; + } + @Override public void load() { super.load(); tiles = OlUtils.split(name + "-tiles", 32, 0); - if (!bottomRegion.found()) bottomRegion = Core.atlas.find("omaloon-liquid-bottom"); + valveRegion = Core.atlas.find(name + "-valve"); + topRegion = Core.atlas.find(name + "-top"); + bottomRegion = Core.atlas.find(name + "-bottom", "omaloon-liquid-bottom"); liquidRegions = new TextureRegion[2][animationFrames]; if(renderer != null){ @@ -115,22 +131,18 @@ public void setStats() { stats.add(OlStats.pressureFlow, Mathf.round(pressureLoss * 60f, 2), OlStats.pressureSecond); } - public class PressureLiquidValveBuild extends LiquidBuild implements HasPressureImpl { + public class PressureLiquidValveBuild extends Building implements HasPressureImpl { public float draining; public float effectInterval; public int tiling; + public float smoothAlpha; public boolean jammed; @Override - public boolean acceptLiquid(Building source, Liquid liquid) { - return hasLiquids; - } - - @Override - public boolean canDumpLiquid(Building to, Liquid liquid) { - return super.canDumpLiquid(to, liquid) || to instanceof LiquidVoid.LiquidVoidBuild; + public boolean acceptsPressurizedFluid(HasPressure from, @Nullable Liquid liquid, float amount) { + return HasPressureImpl.super.acceptsPressurizedFluid(from, liquid, amount) && (liquid == pressure.getMain() || liquid == null || pressure.getMain() == null || from.pressure().getMain() == null); } @Override @@ -144,77 +156,106 @@ public boolean connects(HasPressure to) { public void draw() { float rot = rotate ? (90 + rotdeg()) % 180 - 90 : 0; Draw.rect(bottomRegion, x, y, rotation); - if (liquids().currentAmount() > 0.01f) { - int frame = liquids.current().getAnimationFrame(); - int gas = liquids.current().gas ? 1 : 0; + Liquid main = pressure.getMain(); + + smoothAlpha = Mathf.approachDelta(smoothAlpha, main == null ? 0f : pressure.liquids[main.id]/(pressure.liquids[main.id] + pressure.air), PressureModule.smoothingSpeed); + + if (smoothAlpha > 0.01f) { + int frame = pressure.current.getAnimationFrame(); + int gas = pressure.current.gas ? 1 : 0; float xscl = Draw.xscl, yscl = Draw.yscl; Draw.scl(1f, 1f); - Drawf.liquid(liquidRegions[gas][frame], x, y, liquids.currentAmount()/liquidCapacity, liquids.current().color.write(Tmp.c1).a(1f)); + Drawf.liquid(liquidRegions[gas][frame], x, y, Mathf.clamp(smoothAlpha), pressure.current.color.write(Tmp.c1).a(1f)); Draw.scl(xscl, yscl); } Draw.rect(tiles[tiling], x, y, rot); Draw.rect(topRegion, x, y); - Draw.rect(valveRegion, x, y, draining * (rotation%2 == 0 ? -90 : 90) + rot); + Draw.rect(valveRegion, x, y, draining * (rotation % 2 == 0 ? -90f : 90f) + rot); } @Override public void onProximityUpdate() { super.onProximityUpdate(); + tiling = 0; boolean inverted = rotation == 1 || rotation == 2; if (front() instanceof HasPressure front && connected(front)) tiling |= inverted ? 2 : 1; if (back() instanceof HasPressure back && connected(back)) tiling |= inverted ? 1 : 2; + + new PressureSection().mergeFlood(this); } + @Override + public boolean outputsPressurizedFluid(HasPressure to, Liquid liquid, float amount) { + return HasPressureImpl.super.outputsPressurizedFluid(to, liquid, amount) && (liquid == to.pressure().getMain() || liquid == null || pressure.getMain() == null || to.pressure().getMain() == null); + } @Override public void read(Reads read, byte revision) { super.read(read, revision); jammed = read.bool(); draining = read.f(); + smoothAlpha = read.f(); } @Override public void updatePressure() { HasPressureImpl.super.updatePressure(); - if (getPressure() >= jamPoint) jammed = false; + float pressureAmount = pressure.getPressure(pressure.getMain()); + + if (pressureAmount > jamPoint) jammed = false; if (jammed) return; - if (getPressure() <= openMin) { + if (pressureAmount < openMin) { effectInterval += delta(); - handlePressure(pressureLoss * Time.delta); + addFluid(null, Math.min(openMin - pressureAmount, OlMath.flowRate( + 0, + pressureAmount, + 5, + pressureConfig.fluidCapacity, + OlLiquids.getDensity(null), + OlLiquids.getViscosity(null) + ))); draining = Mathf.approachDelta(draining, 1, 0.014f); - - if (effectInterval > pumpingEffectInterval) { - effectInterval = 0; - pumpingEffect.at(x, y, -draining * (rotation % 2 == 0 ? 90 : -90) - (rotate ? (90 - rotdeg()) % 180 - 90 : 0), liquids.current()); - pumpingEffect.at(x, y, draining * (rotation % 2 == 0 ? -90 : 90) + (rotate ? (90 + rotdeg()) % 180 - 90 : 0), liquids.current()); + } + if (pressureAmount > openMax) { + effectInterval += delta(); + removeFluid(pressure.getMain(), Math.min(pressureAmount - openMax, OlMath.flowRate( + pressureAmount, + 0, + pressureConfig.fluidCapacity, + 5, + OlLiquids.getDensity(null), + OlLiquids.getViscosity(null) + ))); + draining = Mathf.approachDelta(draining, 1, 0.014f); + } + if (effectInterval > pumpingEffectInterval) { + effectInterval = 0; + if (pressureAmount > openMax) { + pumpingEffectOut.at(x, y, draining * (rotation % 2 == 0 ? -90f : 90f) + (rotate ? (90 + rotdeg()) % 180 - 90 : 0), pressure.getMain() == null ? Color.white : pressure.getMain().color); + } else { + pumpingEffectIn.at(x, y, draining * (rotation % 2 == 0 ? -90f : 90f) + (rotate ? (90 + rotdeg()) % 180 - 90 : 0)); } + } - } else draining = Mathf.approachDelta(draining, 0, 0.014f); + if (pressureAmount >= openMin && pressureAmount <= openMax) { + draining = Mathf.approachDelta(draining, 0, 0.014f); + } - if (getPressure() < jamPoint) { + if (pressureAmount < jamPoint) { jammed = true; draining = 0f; jamEffect.at(x, y, draining * (rotation%2 == 0 ? -90 : 90) + (rotate ? (90 + rotdeg()) % 180 - 90 : 0), valveRegion); jamSound.at(x, y); } } - @Override - public void updateTile() { - updatePressure(); - nextBuilds(true).each(b -> moveLiquidPressure(b, liquids.current())); - dumpPressure(); - } - - @Override public byte version() { - return 1; - } @Override public void write(Writes write) { super.write(write); write.bool(jammed); write.f(draining); + write.f(smoothAlpha); } } } diff --git a/src/omaloon/world/blocks/production/HammerDrill.java b/src/omaloon/world/blocks/production/HammerDrill.java index 73516df4..f0353f49 100644 --- a/src/omaloon/world/blocks/production/HammerDrill.java +++ b/src/omaloon/world/blocks/production/HammerDrill.java @@ -77,7 +77,7 @@ public boolean shouldConsume(){ @Override public void updateTile(){ updatePressure(); - dumpPressure(); + if(timer(timerDump, dumpTime)){ dump(dominantItem != null && items.has(dominantItem) ? dominantItem : null); } diff --git a/src/omaloon/world/blocks/production/PressureCrafter.java b/src/omaloon/world/blocks/production/PressureCrafter.java index ef81f8e3..a73bd62b 100644 --- a/src/omaloon/world/blocks/production/PressureCrafter.java +++ b/src/omaloon/world/blocks/production/PressureCrafter.java @@ -1,9 +1,11 @@ package omaloon.world.blocks.production; import arc.util.*; -import arc.util.io.*;; +import arc.util.io.*; +import mindustry.type.*; import mindustry.world.blocks.production.*; import mindustry.world.consumers.*; +import mindustry.world.meta.*; import omaloon.world.interfaces.*; import omaloon.world.meta.*; import omaloon.world.modules.*; @@ -13,13 +15,34 @@ public class PressureCrafter extends GenericCrafter { public boolean useConsumerMultiplier = true; - public float outputPressure = 0; + /** + * Set this to false every time you want the outputs to use the pressure liquid system instead. + * Alternatively, creating ConsumeFluids with negative values for it's amount will work too. + */ + public boolean useVanillaLiquids = true; + + /** + * Internal variable used to output pressurized liquids, Do not modify manually. + */ + private @Nullable LiquidStack[] outputPressurizedLiquids; + + public float outputAir; public PressureCrafter(String name) { super(name); pressureConfig.isWhitelist = true; } + @Override + public void init() { + if (!useVanillaLiquids) { + outputPressurizedLiquids = outputLiquids; + outputLiquids = null; + } + + super.init(); + } + @Override public void setBars() { super.setBars(); @@ -30,10 +53,16 @@ public void setBars() { public void setStats() { super.setStats(); pressureConfig.addStats(stats); - if (outputPressure != 0) stats.add(OlStats.outputPressure, Strings.autoFixed(outputPressure, 2), OlStats.pressureUnits); + + if(outputPressurizedLiquids != null) { + stats.add(Stat.output, StatValues.liquids(1f, outputPressurizedLiquids)); + } + if (outputAir > 0) { + stats.add(Stat.output, OlStats.fluid(null, outputAir, 1f, true)); + } } - public class PressureCrafterBuild extends GenericCrafterBuild implements HasPressureImpl { + public class PressureCrafterBuild extends GenericCrafterBuild implements HasPressureImpl { public float efficiencyMultiplier() { float val = 1; if (!useConsumerMultiplier) return val; @@ -51,11 +80,33 @@ public float efficiencyMultiplier() { return super.getProgressIncrease(baseTime) * efficiencyMultiplier(); } + @Override + public boolean shouldConsume() { + if(outputPressurizedLiquids != null && !ignoreLiquidFullness) { + boolean allFull = true; + if (pressure.get(null) >= pressureConfig.fluidCapacity - 0.001f) { + if (!dumpExtraLiquid) return false; + } else allFull = false; + for(var output : outputPressurizedLiquids) { + if(pressure.get(output.liquid) >= pressureConfig.fluidCapacity - 0.001f) { + if(!dumpExtraLiquid) return false; + } else allFull = false; + } + + //if there is no space left for any liquid, it can't reproduce + if(allFull) return false; + } + return super.shouldConsume(); + } + @Override public void updateTile() { super.updateTile(); - updatePressure(); - dumpPressure(); + if(efficiency > 0) { + float inc = getProgressIncrease(1f); + if (outputPressurizedLiquids != null) for(var output : outputPressurizedLiquids) addFluid(output.liquid, output.amount * inc); + if (outputAir > 0) addFluid(null, outputAir * inc); + } } } } diff --git a/src/omaloon/world/blocks/production/PressureDrill.java b/src/omaloon/world/blocks/production/PressureDrill.java index 8255a554..5de5bf3e 100644 --- a/src/omaloon/world/blocks/production/PressureDrill.java +++ b/src/omaloon/world/blocks/production/PressureDrill.java @@ -17,6 +17,13 @@ public PressureDrill(String name) { pressureConfig.isWhitelist = true; } + @Override + public void init() { + super.init(); + + if (pressureConfig.fluidGroup == null) pressureConfig.fluidGroup = FluidGroup.drills; + } + @Override public void setBars() { super.setBars(); @@ -31,7 +38,6 @@ public void setStats() { public class PressureDrillBuild extends DrillBuild implements HasPressureImpl { - public float efficiencyMultiplier() { float val = 1; if (!useConsumerMultiplier) return val; @@ -48,12 +54,5 @@ public float efficiencyMultiplier() { @Override public float getProgressIncrease(float baseTime) { return super.getProgressIncrease(baseTime) * efficiencyMultiplier(); } - - @Override - public void updateTile() { - super.updateTile(); - updatePressure(); - dumpPressure(); - } } } diff --git a/src/omaloon/world/blocks/sandbox/PressureLiquidSource.java b/src/omaloon/world/blocks/sandbox/PressureLiquidSource.java index e2c6abd1..61bc864a 100644 --- a/src/omaloon/world/blocks/sandbox/PressureLiquidSource.java +++ b/src/omaloon/world/blocks/sandbox/PressureLiquidSource.java @@ -1,93 +1,204 @@ package omaloon.world.blocks.sandbox; import arc.*; +import arc.graphics.*; import arc.graphics.g2d.*; +import arc.math.*; +import arc.scene.style.*; +import arc.scene.ui.*; +import arc.scene.ui.ImageButton.*; import arc.scene.ui.layout.*; import arc.util.*; import arc.util.io.*; +import mindustry.*; import mindustry.entities.units.*; import mindustry.gen.*; import mindustry.type.*; import mindustry.ui.*; -import mindustry.world.blocks.sandbox.*; +import mindustry.world.*; +import mindustry.world.blocks.liquid.*; +import omaloon.annotations.AutoImplement; +import omaloon.content.*; +import omaloon.ui.elements.*; import omaloon.world.interfaces.*; import omaloon.world.meta.*; import omaloon.world.modules.*; -import static arc.scene.ui.TextField.TextFieldFilter.*; -import static arc.util.Strings.*; - -public class PressureLiquidSource extends LiquidSource { - // TODO cheap fix, this class should be remade to have proper configs - public static float lastAmount = 0; - public static boolean wasNegative = false; - +public class PressureLiquidSource extends Block { public PressureConfig pressureConfig = new PressureConfig(); + public TextureRegion bottomRegion; + public PressureLiquidSource(String name) { super(name); + solid = true; + destructible = true; + update = true; + configurable = true; + saveConfig = copyConfig = true; + + config(SourceEntry.class, (PressureLiquidSourceBuild build, SourceEntry entry) -> { + build.liquid = entry.fluid == null ? -1 : entry.fluid.id; + build.targetAmount = entry.amount; + + Vars.content.liquids().each(liquid -> { + build.pressure.liquids[liquid.id] = 0; + build.pressure.pressures[liquid.id] = 0; + }); + + build.pressure.air = build.pressure.pressure = 0; + }); } @Override public void drawPlanConfig(BuildPlan plan, Eachable list) { - Draw.rect(crossRegion, plan.drawx(), plan.drawy()); - drawPlanConfigCenter(plan, plan.config, "center", false); + Draw.rect(bottomRegion, plan.drawx(), plan.drawy()); + if (plan.config instanceof SourceEntry e && e.fluid != null) LiquidBlock.drawTiledFrames(size, plan.drawx(), plan.drawy(), 0f, e.fluid, 1f); + Draw.rect(region, plan.drawx(), plan.drawy()); } @Override public void load() { super.load(); bottomRegion = Core.atlas.find(name + "-bottom"); - crossRegion = Core.atlas.find(name + "-cross"); + } + + @Override + protected TextureRegion[] icons() { + return new TextureRegion[]{bottomRegion, region}; + } + + @Override + public void init() { + super.init(); + + if (pressureConfig.fluidGroup != null) pressureConfig.fluidGroup = FluidGroup.transportation; } @Override public void setBars() { super.setBars(); pressureConfig.addBars(this); + addBar("pressure", entity -> { + HasPressure build = (HasPressure)entity; + + return new CenterBar( + () -> Core.bundle.get("bar.pressure") + (build.pressure().getPressure(build.pressure().getMain()) < 0 ? "-" : "+") + Strings.autoFixed(Math.abs(build.pressure().getPressure(build.pressure().getMain())), 2), + () -> Color.white, + () -> Mathf.map(build.pressure().getPressure(build.pressure().getMain()), pressureConfig.minPressure, pressureConfig.maxPressure, -1, 1) + ); + }); } - public class PressureLiquidSourceBuild extends LiquidSourceBuild implements HasPressureImpl { - public float pressureTarget = lastAmount; - public boolean negative = wasNegative; + public class PressureLiquidSourceBuild extends Building implements HasPressureImpl { + + public int liquid = -1; + public float targetAmount; - @Override public boolean acceptLiquid(Building source, Liquid liquid) { - return false; + @Override + public boolean acceptsPressurizedFluid(HasPressure from, Liquid liquid, float amount) { + return HasPressureImpl.super.acceptsPressurizedFluid(from, liquid, amount) && liquid == Vars.content.liquid(this.liquid); } - @Override public boolean acceptsPressure(HasPressure from, float pressure) { - return false; + + @Override + public void buildConfiguration(Table cont) { + cont.table(Styles.black6, table -> { + table.pane(Styles.smallPane, liquids -> Vars.content.liquids().each(liquid -> { + Button button = liquids.button( + new TextureRegionDrawable(liquid.uiIcon), + new ImageButtonStyle() {{ + over = Styles.flatOver; + down = checked = Tex.flatDownBase; + }}, () -> { + if (this.liquid != liquid.id) { + configure(new SourceEntry() {{ + fluid = liquid; + amount = targetAmount; + }}); + } else { + configure(new SourceEntry() {{ + fluid = null; + amount = targetAmount; + }}); + } + } + ).tooltip(liquid.localizedName).size(40f).get(); + button.update(() -> button.setChecked(liquid.id == this.liquid)); + if ((Vars.content.liquids().indexOf(liquid) + 1) % 4 == 0) liquids.row(); + })).maxHeight(160f).row(); + table.add("@filter.option.amount").padTop(5f).padBottom(5f).row(); + table.field( + "" + targetAmount, + (field, c) -> Character.isDigit(c) || ((!field.getText().contains(".")) && c == '.') || (field.getText().isEmpty() && c == '-'), + s -> configure(new SourceEntry() {{ + fluid = Vars.content.liquid(liquid); + amount = Strings.parseFloat(s, 0f); + }}) + ); + }).margin(5f); } @Override - public void buildConfiguration(Table table) { - super.buildConfiguration(table); - table.row(); - table.table(Styles.black6, cont -> { - cont.field(pressureTarget + "", floatsOnly, s -> pressureTarget = parseFloat(s, 0f)).row(); - cont.check(Core.bundle.get("omaloon-source-negative"), negative, b -> negative = b); - }).growX(); + public SourceEntry config() { + return new SourceEntry() {{ + fluid = Vars.content.liquid(liquid); + amount = targetAmount; + }}; } + @Override + public void draw() { + Draw.rect(bottomRegion, x, y); + + if(liquid != -1) { + LiquidBlock.drawTiledFrames(size, x, y, 0f, Vars.content.liquid(liquid), 1f); + } + + Draw.rect(region, x, y); + } + + + @Override + public boolean outputsPressurizedFluid(HasPressure to, Liquid liquid, float amount) { + return HasPressureImpl.super.outputsPressurizedFluid(to, liquid, amount) && liquid == Vars.content.liquid(this.liquid); + } @Override public void read(Reads read, byte revision) { super.read(read, revision); - pressureTarget = read.f(); - negative = read.bool(); + liquid = read.i(); + if (Vars.content.liquid(liquid) == null) liquid = -1; + targetAmount = read.f(); } @Override + @AutoImplement.NoInject(HasPressureImpl.class) public void updateTile() { - super.updateTile(); - __pressure__.pressure = pressureTarget * (negative ? -1f : 1f); - nextBuilds(true).each(b -> b.pressure().pressure = pressureTarget * (negative ? -1 : 1f)); - dumpPressure(); + pressure.section.updateTransfer(); + + pressure.air = Vars.content.liquid(liquid) == null ? targetAmount : 0; + pressure.pressure = pressure.air / pressureConfig.fluidCapacity * OlLiquids.getDensity(null); + Vars.content.liquids().each(liq -> { + pressure.liquids[liq.id] = liq.id == liquid ? Mathf.maxZero(targetAmount) : 0; + pressure.pressures[liq.id] = pressure.liquids[liq.id] / pressureConfig.fluidCapacity * OlLiquids.getDensity(liq); + }); + if(false){ + //in original code here we wont to invoke updatePressure? + //will fix this later + AutoImplement.Util.Inject(HasPressureImpl.class); + } } @Override public void write(Writes write) { super.write(write); - write.f(pressureTarget); - write.bool(negative); + write.i(liquid); + write.f(targetAmount); } } + + + public static class SourceEntry { + public @Nullable Liquid fluid; + public float amount; + } } diff --git a/src/omaloon/world/blocks/sandbox/PressureLiquidVoid.java b/src/omaloon/world/blocks/sandbox/PressureLiquidVoid.java index 593a05a5..551bec65 100644 --- a/src/omaloon/world/blocks/sandbox/PressureLiquidVoid.java +++ b/src/omaloon/world/blocks/sandbox/PressureLiquidVoid.java @@ -5,7 +5,6 @@ import mindustry.world.blocks.sandbox.*; import omaloon.world.interfaces.*; import omaloon.world.meta.*; -import omaloon.world.modules.*; public class PressureLiquidVoid extends LiquidVoid { public PressureConfig pressureConfig = new PressureConfig(); @@ -20,16 +19,13 @@ public class PressureLiquidVoidBuild extends LiquidVoidBuild implements HasPress @Override public boolean acceptLiquid(Building source, Liquid liquid) { return enabled; } - @Override public boolean acceptsPressure(HasPressure from, float pressure) { - return enabled; - } @Override public void updateTile() { super.updateTile(); - __pressure__.pressure = 0f; + pressure.pressure = 0f; } } } diff --git a/src/omaloon/world/consumers/ConsumeFluid.java b/src/omaloon/world/consumers/ConsumeFluid.java new file mode 100644 index 00000000..78347d5a --- /dev/null +++ b/src/omaloon/world/consumers/ConsumeFluid.java @@ -0,0 +1,119 @@ +package omaloon.world.consumers; + +import arc.*; +import arc.math.*; +import arc.util.*; +import mindustry.gen.*; +import mindustry.type.*; +import mindustry.world.consumers.*; +import mindustry.world.meta.*; +import omaloon.world.interfaces.*; +import omaloon.world.meta.*; + +public class ConsumeFluid extends Consume { + /** + * Fluid used by this consumer, if null, air is used + */ + public @Nullable Liquid fluid; + /** + * Amount of fluid consumed, will always be positive if fluid isn't air. + */ + public float amount; + /** + * If true, fluid is consumed per tick and not per craft. + */ + public boolean continuous; + + /** + * Min pressure required for this consumer to function. + */ + public float startRange; + /** + * Max pressure allowed for this consumer to function. + */ + public float endRange; + /** + * Efficiency multiplier of this consumer. Based on pressure. + */ + public float efficiencyMultiplier = 1f; + /** + * Pressure whose building's efficiency is at it's peak. + */ + public float optimalPressure; + /** + * Whether to display the optimal pressure. + */ + public boolean hasOptimalPressure = false; + /** + * Interpolation curve used to determine efficiency. 0 is startRange, 1 is endRange. + */ + public Interp curve = Interp.one; + + public ConsumeFluid(@Nullable Liquid fluid, float amount) { + this.fluid = fluid; + this.amount = amount; + } + + public HasPressure cast(Building build) { + try { + return (HasPressure) build; + } catch(Exception e) { + throw new RuntimeException("This consumer should be used on a building that implements HasPressure", e); + } + } + + @Override + public void display(Stats stats) { + if (amount != 0) { + if (continuous) { + stats.add(amount > 0 ? Stat.input : Stat.output, OlStats.fluid(fluid, Math.abs(amount), 1f, true)); + } else { + stats.add(amount > 0 ? Stat.input : Stat.output, OlStats.fluid(fluid, Math.abs(amount), 60f, false)); + } + } + + if (startRange != endRange) { + stats.add( + OlStats.pressureRange, + Core.bundle.get("stat.omaloon-pressure-range.format"), + (startRange == 0 ? "" : (startRange > 0 ? "+" : "-")) + Strings.autoFixed(Math.abs(startRange), 2), + (endRange == 0 ? "" : (endRange > 0 ? "+" : "-")) + Strings.autoFixed(Math.abs(endRange), 2) + ); + if (hasOptimalPressure) stats.add( + OlStats.optimalPressure, + Core.bundle.get("stat.omaloon-optimal-pressure.format"), + (optimalPressure == 0 ? "" : (optimalPressure > 0 ? "+" : "-")) + Strings.autoFixed(Math.abs(optimalPressure), 2), + Strings.autoFixed(efficiencyMultiplier * 100f, 2) + ); + } + } + + @Override + public float efficiency(Building build) { + if (!shouldConsume(cast(build))) return 0f; + return 1f; + } + @Override + public float efficiencyMultiplier(Building build) { + if (!shouldConsume(cast(build))) return 0f; + return curve.apply(1f, efficiencyMultiplier, Mathf.clamp(Mathf.map(cast(build).pressure().getPressure(fluid), startRange, endRange, 0f, 1f))); + + } + + public boolean shouldConsume(HasPressure build) { + if (fluid != null && amount > 0 && build.pressure().get(fluid) <= amount) return false; + if (startRange == endRange) return true; + return startRange <= build.pressure().getPressure(fluid) && build.pressure().getPressure(fluid) <= endRange && (fluid == null || build.pressure().liquids[fluid.id] > amount); + } + + @Override public void trigger(Building build) { + if (!continuous && shouldConsume(cast(build))) { + cast(build).removeFluid(fluid, amount); + } + } + @Override public void update(Building build) { + if (continuous && shouldConsume(cast(build))) { + cast(build).removeFluid(fluid, amount * Time.delta); + } + } +} diff --git a/src/omaloon/world/consumers/ConsumePressure.java b/src/omaloon/world/consumers/ConsumePressure.java deleted file mode 100644 index 7ef73160..00000000 --- a/src/omaloon/world/consumers/ConsumePressure.java +++ /dev/null @@ -1,48 +0,0 @@ -package omaloon.world.consumers; - -import arc.math.*; -import arc.util.*; -import mindustry.gen.*; -import mindustry.world.*; -import mindustry.world.consumers.*; -import mindustry.world.meta.*; -import omaloon.world.interfaces.*; -import omaloon.world.meta.*; - -public class ConsumePressure extends Consume { - public float amount; - public boolean continuous; - - public ConsumePressure(float amount, boolean continuous) { - this.amount = amount; - this.continuous = continuous; - } - - public HasPressure cast(Building build) { - try { - return (HasPressure) build; - } catch(Exception e) { - throw new RuntimeException("This consumer should be used on a building that implements HasPressure", e); - } - } - - @Override public void apply(Block block) { - block.hasLiquids = true; - } - - @Override - public void display(Stats stats) { - if (continuous) { - stats.add(OlStats.consumePressure, Mathf.round(amount * 60f, 2), OlStats.pressureSecond); - } else { - stats.add(OlStats.consumePressure, Mathf.round(amount, 2), OlStats.pressureUnits); - } - } - - @Override public void trigger(Building build) { - if (!continuous) cast(build).removePressure(amount); - } - @Override public void update(Building build) { - if (continuous) cast(build).removePressure(amount * Time.delta); - } -} diff --git a/src/omaloon/world/consumers/PressureEfficiencyRange.java b/src/omaloon/world/consumers/PressureEfficiencyRange.java deleted file mode 100644 index f7e7d74a..00000000 --- a/src/omaloon/world/consumers/PressureEfficiencyRange.java +++ /dev/null @@ -1,59 +0,0 @@ -package omaloon.world.consumers; - -import arc.*; -import arc.math.*; -import arc.util.*; -import mindustry.gen.*; -import mindustry.world.*; -import mindustry.world.consumers.*; -import mindustry.world.meta.*; -import omaloon.world.interfaces.*; -import omaloon.world.meta.*; - -public class PressureEfficiencyRange extends Consume { - public float startRange, endRange, efficiencyMultiplier; - public boolean reverse; - - public PressureEfficiencyRange(float startRange, float endRange, float efficiencyMultiplier, boolean reverse) { - this.startRange = startRange; - this.endRange = endRange; - this.efficiencyMultiplier = efficiencyMultiplier; - this.reverse = reverse; - } - - @Override public void apply(Block block) { - block.hasLiquids = true; - } - - public HasPressure cast(Building build) { - try { - return (HasPressure) build; - } catch(Exception e) { - throw new RuntimeException("This consumer should be used on a building that implements HasPressure", e); - } - } - - @Override - public void display(Stats stats) { - stats.add(OlStats.pressureRange, Core.bundle.get("stat.omaloon-pressurerange.format"), Strings.autoFixed(startRange, 2), Strings.autoFixed(endRange, 2)); - } - - @Override - public float efficiency(Building build) { - return shouldConsume(cast(build)) ? 1f : 0f; - } - @Override - public float efficiencyMultiplier(Building build) { - if (!shouldConsume(cast(build))) return 0f; - if (reverse) { - return Mathf.maxZero(Mathf.map(cast(build).getPressure(), endRange, startRange, 1f, efficiencyMultiplier)); - } else { - return Mathf.maxZero(Mathf.map(cast(build).getPressure(), startRange, endRange, 1f, efficiencyMultiplier)); - } - } - - public boolean shouldConsume(HasPressure build) { - int pressure = Math.round(build.getPressure()); - return startRange <= pressure && pressure <= endRange; - } -} diff --git a/src/omaloon/world/interfaces/HasPressure.java b/src/omaloon/world/interfaces/HasPressure.java index cc5d1659..479902ad 100644 --- a/src/omaloon/world/interfaces/HasPressure.java +++ b/src/omaloon/world/interfaces/HasPressure.java @@ -4,7 +4,6 @@ import arc.struct.*; import arc.util.*; import mindustry.*; -import mindustry.content.*; import mindustry.gen.*; import mindustry.type.*; import omaloon.world.meta.*; @@ -15,19 +14,19 @@ * only added this cause my ide did a funni */ public interface HasPressure extends Buildingc { - PressureModule pressure(); - PressureConfig pressureConfig(); - /** - * @return true if this building accepts a certain pressure amount from some building - */ - default boolean acceptsPressure(HasPressure from, float pressure) { - return getPressure() + pressure <= from.getPressure() - pressure; + PressureModule pressure(); + PressureConfig pressureConfig(); + default boolean acceptsPressurizedFluid(HasPressure from, @Nullable Liquid liquid, float amount) { + return pressureConfig().acceptsPressure; } + /** - * @return true if this building can dump a certain pressure amount to some building + * Adds a certain amount of a fluid into this module through the section. */ - default boolean canDumpPressure(HasPressure to, float pressure) { - return to.getPressure() + pressure <= getPressure() - pressure; + default void addFluid(@Nullable Liquid liquid, float amount) { + if (amount == 0) return; + if (amount < 0) pressure().section.removeFluid(liquid, -amount); + pressure().section.addFluid(liquid, amount); } /** @@ -43,49 +42,6 @@ default boolean connects(HasPressure to) { return pressureConfig().outputsPressure || pressureConfig().acceptsPressure; } - /** - * dumps pressure onto available builds - */ - default void dumpPressure() { - for (HasPressure other : nextBuilds(true)) { - float diff = (getPressure() - other.getPressure()) / 2f; - if (other.getPressure() > getPressure()) diff *= -1f; - if (canDumpPressure(other, diff)) { - transferPressure(other, diff); - } - } - } - - default void dumpLiquidPressure(Liquid liquid) { - int dump = cdump(); - if (liquids().get(liquid) > 0.0001f) { - if (!Vars.net.client() && Vars.state.isCampaign() && team() == Vars.state.rules.defaultTeam) { - liquid.unlock(); - } - - for(int i = 0; i < nextBuilds(true).size; ++i) { - incrementDump(nextBuilds(true).size); - HasPressure other = nextBuilds(true).get((i + dump) % nextBuilds(true).size); - other = other.getLiquidDestination(as(), liquid).as(); - if (other != null && other.block().hasLiquids && canDumpLiquid(other.as(), liquid) && other.liquids() != null) { - float ofract = other.liquids().get(liquid) / other.block().liquidCapacity; - float fract = liquids().get(liquid) / block().liquidCapacity; - if (ofract < fract) { - transferLiquid(other.as(), (fract - ofract) * block().liquidCapacity * getPressureFlow(other) / nextBuilds(true).size, liquid); - } - } - } - - } - } - - /** - * @return current pressure of the building - */ - default float getPressure() { - return pressure().pressure; - } - /** * @return building destination to dump pressure */ @@ -94,66 +50,17 @@ default HasPressure getPressureDestination(HasPressure from, float pressure) { } /** - * @return flow of liquids from one build to another + * Returns the building whose section should be the same as this build's section. */ - default float getPressureFlow(HasPressure to) { - //ensures that the liquid flows properly - if (to.getPressure() == 0) return 1f; - return Math.max(getPressure()/to.getPressure(), 1f); - } - - /** - * adds pressure not taking anything into account - */ - default void handlePressure(float pressure) { - pressure().pressure += pressure; - } - - default float moveLiquidPressure(HasPressure next, Liquid liquid) { - if (next != null) { - next = (HasPressure) next.getLiquidDestination(as(), liquid); - if (next.team() == team() && next.block().hasLiquids && liquids().get(liquid) > 0f) { - float ofract = next.liquids().get(liquid) / next.block().liquidCapacity; - float fract = liquids().get(liquid) / block().liquidCapacity; - float flow = Math.min(Mathf.clamp(fract - ofract) * block().liquidCapacity, liquids().get(liquid)) * getPressureFlow(next); - flow = Math.min(flow, next.block().liquidCapacity - next.liquids().get(liquid))/2; - if (flow > 0f && ofract <= fract && next.acceptLiquid(this.as(), liquid)) { - next.handleLiquid(this.as(), liquid, flow); - liquids().remove(liquid, flow); - return flow; - } - - if (!next.block().consumesLiquid(liquid) && next.liquids().currentAmount() / next.block().liquidCapacity > 0.1F && fract > 0.1F) { - float fx = (x() + next.x()) / 2f; - float fy = (y() + next.y()) / 2f; - Liquid other = next.liquids().current(); - if (other.blockReactive && liquid.blockReactive) { - if ((!(other.flammability > 0.3F) || !(liquid.temperature > 0.7F)) && (!(liquid.flammability > 0.3F) || !(other.temperature > 0.7F))) { - if (liquid.temperature > 0.7F && other.temperature < 0.55F || other.temperature > 0.7F && liquid.temperature < 0.55F) { - liquids().remove(liquid, Math.min(liquids().get(liquid), 0.7F * Time.delta)); - if (Mathf.chanceDelta(0.20000000298023224)) { - Fx.steam.at(fx, fy); - } - } - } else { - this.damageContinuous(1.0F); - next.damageContinuous(1.0F); - if (Mathf.chanceDelta(0.1)) { - Fx.fire.at(fx, fy); - } - } - } - } - } - - } - return 0.0F; + default @Nullable HasPressure getSectionDestination(HasPressure from) { + if (pressureConfig().fluidGroup == null || pressureConfig().fluidGroup == FluidGroup.unset || pressureConfig().fluidGroup != from.pressureConfig().fluidGroup) return null; + return this; } /** - * @param flow determines if the returned value will have only builds to which it can flow pressure to + * Returns the next builds that this block will connect to */ - default Seq nextBuilds(boolean flow) { + default Seq nextBuilds() { return proximity().select( b -> b instanceof HasPressure ).as().map( @@ -163,29 +70,28 @@ default Seq nextBuilds(boolean flow) { ); } + default boolean outputsPressurizedFluid(HasPressure to, @Nullable Liquid liquid, float amount) { + return pressureConfig().outputsPressure; + } /** - * transfers pressure between 2 buildings taking acceptsPressure into account + * Removes a certain amount of a fluid into this module through the section. */ - default void transferPressure(HasPressure to, float pressure) { - if (to.acceptsPressure(this, pressure)) { - removePressure(pressure); - to.handlePressure(pressure); - } + default void removeFluid(@Nullable Liquid liquid, float amount) { + if (amount == 0) return; + if (amount < 0) pressure().section.addFluid(liquid, -amount); + pressure().section.removeFluid(liquid, amount); } /** * method to update pressure related things */ default void updatePressure() { - if (Mathf.round(getPressure()) <= pressureConfig().minPressure) damage(pressureConfig().underPressureDamage); - if (Mathf.round(getPressure()) >= pressureConfig().maxPressure) damage(pressureConfig().overPressureDamage); - } + if (nextBuilds().contains(other -> other.pressure().section != this)) pressure().section.updateTransfer(); - /** - * removes pressure not taking anything into account - */ - default void removePressure(float pressure) { - pressure().pressure -= pressure; + Vars.content.liquids().each(liquid -> { + if (pressure().getPressure(liquid) < pressureConfig().minPressure - 1f) damage(pressureConfig().underPressureDamage); + if (pressure().getPressure(liquid) > pressureConfig().maxPressure + 1f) damage(pressureConfig().overPressureDamage); + }); } } diff --git a/src/omaloon/world/interfaces/HasPressureImpl.java b/src/omaloon/world/interfaces/HasPressureImpl.java index 78dbe4cc..2f8a428a 100644 --- a/src/omaloon/world/interfaces/HasPressureImpl.java +++ b/src/omaloon/world/interfaces/HasPressureImpl.java @@ -4,28 +4,38 @@ import arc.util.io.Writes; import omaloon.annotations.AutoImplement; import omaloon.world.meta.PressureConfig; +import omaloon.world.meta.PressureSection; import omaloon.world.modules.PressureModule; -import static omaloon.annotations.AutoImplement.Inject.InjectPosition.AfterSuper; +import static omaloon.annotations.AutoImplement.Inject.InjectPosition.*; @AutoImplement public interface HasPressureImpl extends HasPressure { - PressureModule __pressure__ = new PressureModule(); + PressureModule pressure = new PressureModule(); default PressureModule pressure() { - return __pressure__; + return pressure; } + @AutoImplement.Inject(Tail) + default void onProximityUpdate(){ + new PressureSection().mergeFlood(this); + } + + @AutoImplement.Inject(Tail) + default void updateTile() { + updatePressure(); + } @AutoImplement.Inject(AfterSuper) default void write(Writes writes) { - __pressure__.write(writes); + pressure.write(writes); } @AutoImplement.Inject(AfterSuper) default void read(Reads reads, byte b) { - __pressure__.read(reads); + pressure.read(reads); } @Override diff --git a/src/omaloon/world/meta/FluidGroup.java b/src/omaloon/world/meta/FluidGroup.java new file mode 100644 index 00000000..ba491d91 --- /dev/null +++ b/src/omaloon/world/meta/FluidGroup.java @@ -0,0 +1,12 @@ +package omaloon.world.meta; + +public enum FluidGroup { + /** + * This group specifically acts the same as if the group is null. Only used if blocks that normally override the group have to be independent. + */ + unset, + + drills, + pumps, + transportation +} diff --git a/src/omaloon/world/meta/OlStats.java b/src/omaloon/world/meta/OlStats.java index 235fe25f..65cca68a 100644 --- a/src/omaloon/world/meta/OlStats.java +++ b/src/omaloon/world/meta/OlStats.java @@ -1,7 +1,16 @@ package omaloon.world.meta; +import arc.*; +import arc.graphics.*; +import arc.scene.ui.*; +import arc.scene.ui.layout.*; +import arc.util.*; +import mindustry.type.*; +import mindustry.ui.*; import mindustry.world.meta.*; +import static mindustry.Vars.*; + public class OlStats { public static final StatCat pressure = new StatCat("omaloon-pressure"); @@ -9,15 +18,62 @@ public class OlStats { minSpeed = new Stat("omaloon-min-speed"), maxSpeed = new Stat("omaloon-max-speed"), + fluidCapacity = new Stat("omaloon-fluid-capacity", StatCat.liquids), + + density = new Stat("omaloon-density"), + pressureFlow = new Stat("omaloon-pressureflow", pressure), - maxPressure = new Stat("omaloon-maxPressure", pressure), - minPressure = new Stat("omaloon-minPressure", pressure), - consumePressure = new Stat("omaloon-consumePressure", pressure), - pressureRange = new Stat("omaloon-pressurerange", pressure), - outputPressure = new Stat("omaloon-outputPressure", pressure); + pumpStrength = new Stat("omaloon-pump-strength", pressure), + pressureGradient = new Stat("omaloon-pressure-gradient", pressure), + + maxPressure = new Stat("omaloon-max-pressure", pressure), + minPressure = new Stat("omaloon-min-pressure", pressure), + + pressureRange = new Stat("omaloon-pressure-range", pressure), + optimalPressure = new Stat("omaloon-optimal-pressure", pressure); public static final StatUnit - pressureUnits = new StatUnit("omaloon-pressureUnits", "\uC357"), + blocksCubed = new StatUnit("omaloon-blocks-cubed"), + + densityUnit = new StatUnit("omaloon-density-unit", "\uC357"), + viscosityUnit = new StatUnit("omaloon-viscosity-unit", "\uC357"), + + pressureUnit = new StatUnit("omaloon-pressure-unit", "\uC357"), pressureSecond = new StatUnit("omaloon-pressureSecond", "\uC357"); + + public static StatValue fluid(@Nullable Liquid liquid, float amount, float time, boolean showContinuous) { + return table -> { + table.table(display -> { + display.add(new Stack() {{ + add(new Image(liquid != null ? liquid.uiIcon : Core.atlas.find("omaloon-pressure-icon")).setScaling(Scaling.fit)); + + if (amount * 60f/time != 0) { + Table t = new Table().left().bottom(); + t.add(Strings.autoFixed(amount * 60f/time, 2)).style(Styles.outlineLabel); + add(t); + } + }}).size(iconMed).padRight(3 + (amount * 60f/time != 0 && Strings.autoFixed(amount * 60f/time, 2).length() > 2 ? 8 : 0)); + + if(showContinuous){ + display.add(StatUnit.perSecond.localized()).padLeft(2).padRight(5).color(Color.lightGray).style(Styles.outlineLabel); + } + + display.add(liquid != null ? liquid.localizedName : "@air"); + }); + }; + } + + public static StatValue pressure(float amount, boolean merge) { + return table -> { + String l1 = (pressureUnit.icon == null ? "" : pressureUnit.icon + " ") + (amount == 0 ? "" : (amount > 0 ? "+" : "-")) + Strings.autoFixed(Math.abs(amount), 2), l2 = (pressureUnit.space ? " " : "") + pressureUnit.localized(); + + if(merge){ + table.add(l1 + l2).left(); + }else{ + table.add(l1).left(); + table.add(l2).left(); + } + }; + } } diff --git a/src/omaloon/world/meta/PressureConfig.java b/src/omaloon/world/meta/PressureConfig.java index 5abfa518..e50df3a5 100644 --- a/src/omaloon/world/meta/PressureConfig.java +++ b/src/omaloon/world/meta/PressureConfig.java @@ -1,13 +1,12 @@ package omaloon.world.meta; import arc.*; -import arc.graphics.Color; +import arc.graphics.*; import arc.math.*; import arc.struct.*; import arc.util.*; -import mindustry.gen.Building; -import mindustry.graphics.*; -import mindustry.type.Liquid; +import mindustry.gen.*; +import mindustry.type.*; import mindustry.ui.*; import mindustry.world.*; import mindustry.world.meta.*; @@ -15,18 +14,45 @@ import omaloon.world.interfaces.*; public class PressureConfig { - public boolean - acceptsPressure = true, - outputsPressure = true, + /** + * Group used for the creation of sections. if null, this block will be a section containing only itself. + */ + public FluidGroup fluidGroup; + + /** + * If true, this block's section will be able to receive fluids. + */ + public boolean acceptsPressure = true; + /** + * If true, this block's section will be able to output fluids. + */ + public boolean outputsPressure = true; /** * Determines whether linkList will function as a whitelist */ - isWhitelist = false; - public float - overPressureDamage = 0.33f, - underPressureDamage = 0.66f, - maxPressure = 50, - minPressure = -50f; + public boolean isWhitelist = false; + + /** + * Damage applied each tick if pressure is higher than maxPressure. + */ + public float overPressureDamage = 0.33f; + /** + * Damage applied each tick if pressure is lower than minPressure. + */ + public float underPressureDamage = 0.66f; + /** + * Maximum pressure that this block can contain before it over-pressurizes. + */ + public float maxPressure = 50; + /** + * Minimum pressure that this block can contain before it under-pressurizes. + */ + public float minPressure = -50f; + + /** + * Standard capacity for this block. Does not define max amount that this can hold. That is defined by maxPressure and minPressure. + */ + public float fluidCapacity = 8; /** * List of blocks that are allowed/disallowed (depends on isWhitelist true/false) for pressure connections. @@ -52,32 +78,57 @@ public class PressureConfig { }; public void addStats(Stats stats) { - stats.add(OlStats.maxPressure, Mathf.round(maxPressure, 2), OlStats.pressureUnits); - stats.add(OlStats.minPressure, Mathf.round(minPressure, 2), OlStats.pressureUnits); + stats.add(OlStats.fluidCapacity, StatValues.number(fluidCapacity/8f, OlStats.blocksCubed)); + + stats.add(OlStats.maxPressure, OlStats.pressure(maxPressure, true)); + stats.add(OlStats.minPressure, OlStats.pressure(minPressure, true)); } public void addBars(Block block) { block.removeBar("liquid"); +// block.addBar("pressure-liquid", (Building entity) -> new Bar( +// () -> { +// HasPressure build = (HasPressure)entity; +// Liquid current = entity.liquids != null ? entity.liquids.current() : null; +// String liquidName = (current == null || entity.liquids.get(current) <= 0.001f) +// ? Core.bundle.get("bar.air") +// : current.localizedName; +// +// return Core.bundle.format("bar.pressure-liquid", +// liquidName, +// Mathf.round(build.getPressure(), 1), +// Mathf.round(build.getPressure() > 0 ? build.pressureConfig().maxPressure : build.pressureConfig().minPressure, 1)); +// }, +// () -> { +// Liquid current = entity.liquids != null ? entity.liquids.current() : null; +// return current != null && entity.liquids.get(current) > 0.001f ? current.color : Color.lightGray; +// }, +// () -> { +// Liquid current = entity.liquids != null ? entity.liquids.current() : null; +// return current != null ? entity.liquids.get(current) / block.liquidCapacity : 0f; +// } +// )); block.addBar("pressure-liquid", (Building entity) -> new Bar( () -> { HasPressure build = (HasPressure)entity; - Liquid current = entity.liquids != null ? entity.liquids.current() : null; - String liquidName = (current == null || entity.liquids.get(current) <= 0.001f) - ? Core.bundle.get("bar.air") - : current.localizedName; + Liquid current = build.pressure().getMain(); + if (current == null) return Core.bundle.get("bar.air") + Strings.autoFixed(build.pressure().air, 2); return Core.bundle.format("bar.pressure-liquid", - liquidName, - Mathf.round(build.getPressure(), 1), - Mathf.round(build.getPressure() > 0 ? build.pressureConfig().maxPressure : build.pressureConfig().minPressure, 1)); + current.localizedName, + Strings.autoFixed(build.pressure().liquids[current.id], 2), + Strings.autoFixed(build.pressure().air, 2) + ); }, () -> { - Liquid current = entity.liquids != null ? entity.liquids.current() : null; - return current != null && entity.liquids.get(current) > 0.001f ? current.color : Color.lightGray; + HasPressure build = (HasPressure)entity; + Liquid current = build.pressure().getMain(); + return current != null ? current.color : Color.lightGray; }, () -> { - Liquid current = entity.liquids != null ? entity.liquids.current() : null; - return current != null ? entity.liquids.get(current) / block.liquidCapacity : 0f; + HasPressure build = (HasPressure)entity; + Liquid current = build.pressure().getMain(); + return current != null ? Mathf.clamp(build.pressure().liquids[current.id]/(build.pressure().liquids[current.id] + build.pressure().air)) : 0; } )); } diff --git a/src/omaloon/world/meta/PressureSection.java b/src/omaloon/world/meta/PressureSection.java new file mode 100644 index 00000000..d77201d2 --- /dev/null +++ b/src/omaloon/world/meta/PressureSection.java @@ -0,0 +1,203 @@ +package omaloon.world.meta; + +import arc.math.*; +import arc.struct.*; +import arc.struct.ObjectMap.*; +import arc.util.*; +import mindustry.*; +import mindustry.type.*; +import omaloon.content.*; +import omaloon.math.*; +import omaloon.world.interfaces.*; + +public class PressureSection { + public Seq builds = new Seq<>(); + + /** + * Temporary seqs for use in flood. + */ + public static final Seq tmp = new Seq<>(), tmp2 = new Seq<>(); + + /** + * Adds a build to this section, and removes the build from its older section. + */ + public void addBuild(HasPressure build) { + builds.add(build); + build.pressure().section.builds.remove(build); + build.pressure().section = this; + } + + /** + * Adds a certain amount of a fluid into this module, updating it's pressure accordingly. A null liquid means that air is being added to it. + */ + public void addFluid(@Nullable Liquid liquid, float amount) { + if (builds.isEmpty()) return; + float div = amount/builds.size; + builds.each(b -> b.pressure().addFluid(liquid, div, b.pressureConfig())); + } + + /** + * Merges buildings to this section with floodFill. + */ + public void mergeFlood(HasPressure other) { + tmp.clear().add(other); + tmp2.clear(); + + while(!tmp.isEmpty()) { + HasPressure next = tmp.pop(); + tmp2.addUnique(next); + next.nextBuilds().each(b -> { + if (b.getSectionDestination(next) != null && !tmp2.contains(b.getSectionDestination(next))) { + tmp.add(b.getSectionDestination(next)); + } + }); + } + + tmp2.each(this::addBuild); + updateLiquids(); + } + + /** + * Removes a certain amount of a fluid from this module, updating pressure accordingly. A null liquid means that air is being removed from it. Liquids cannot be negative. + */ + public void removeFluid(@Nullable Liquid liquid, float amount) { + if (builds.isEmpty()) return; + float div = amount/builds.size; + builds.each(b -> b.pressure().removeFluid(liquid, div, b.pressureConfig())); + } + + public void updateLiquids() { + float[] liquids = new float[Vars.content.liquids().size]; + float air = 0; + + for(Liquid liquid : Vars.content.liquids()) for (HasPressure build : builds) { + liquids[liquid.id] += build.pressure().liquids[liquid.id]; + build.pressure().liquids[liquid.id] = 0; + build.pressure().pressures[liquid.id] = 0; + } + for(HasPressure build : builds) { + air += build.pressure().air; + build.pressure().air = 0; + build.pressure().pressure = 0; + } + + for(Liquid liquid : Vars.content.liquids()) addFluid(liquid, liquids[liquid.id]); + addFluid(null, air); + } + + public void updateTransfer() { + Seq> links = new Seq<>(); + + builds.each(b -> { + b.nextBuilds().retainAll(other -> other.pressure().section != this).each(other -> { + links.add(new Entry<>(){{ + key = other; + value = b; + }}); + }); + }); + + FloatSeq amounts = new FloatSeq(); + + Vars.content.liquids().each(main -> { + amounts.clear(); + for (Entry entry : links) { + float flow = OlMath.flowRate( + entry.value.pressure().getPressure(main), + entry.key.pressure().getPressure(main), + entry.value.pressureConfig().fluidCapacity, + entry.key.pressureConfig().fluidCapacity, + OlLiquids.getDensity(main), + OlLiquids.getViscosity(main) + ) / (2f * links.size); + + if ( + ( + flow > 0 ? + ( + entry.key.acceptsPressurizedFluid(entry.value, main, flow) && + entry.value.outputsPressurizedFluid(entry.key, main, flow) + ) : + ( + entry.value.acceptsPressurizedFluid(entry.key, main, flow) && + entry.key.outputsPressurizedFluid(entry.value, main, flow) + ) + ) && + (entry.key.pressure().get(main) > 0 || entry.value.pressure().get(main) > 0) + ) { + amounts.add(flow); + } else { + amounts.add(0); + } + } + for (Entry entry : links) { + float maxFlow = OlMath.flowRate( + entry.value.pressure().getPressure(main), + entry.key.pressure().getPressure(main), + entry.value.pressureConfig().fluidCapacity, + entry.key.pressureConfig().fluidCapacity, + OlLiquids.getDensity(main), + 1 + ) / (2f * links.size); + + float flow = Mathf.clamp( + amounts.get(links.indexOf(entry)) * Time.delta, + -Math.abs(maxFlow), + Math.abs(maxFlow) + ); + if (flow != 0) { + entry.key.addFluid(main, flow); + entry.value.removeFluid(main, flow); + } + } + }); + amounts.clear(); + for (Entry entry : links) { + float flow = OlMath.flowRate( + entry.value.pressure().getPressure(null), + entry.key.pressure().getPressure(null), + entry.value.pressureConfig().fluidCapacity, + entry.key.pressureConfig().fluidCapacity, + OlLiquids.getDensity(null), + OlLiquids.getViscosity(null) + ) / (2f * links.size); + + if ( + ( + flow > 0 ? + ( + entry.key.acceptsPressurizedFluid(entry.value, null, flow) && + entry.value.outputsPressurizedFluid(entry.key, null, flow) + ) : ( + entry.value.acceptsPressurizedFluid(entry.key, null, flow) && + entry.key.outputsPressurizedFluid(entry.value, null, flow) + ) + ) + ) { + amounts.add(flow); + } else { + amounts.add(0); + } + } + for (Entry entry : links) { + float maxFlow = OlMath.flowRate( + entry.value.pressure().getPressure(null), + entry.key.pressure().getPressure(null), + entry.value.pressureConfig().fluidCapacity, + entry.key.pressureConfig().fluidCapacity, + OlLiquids.getDensity(null), + 1 + ) / (2f * links.size); + + float flow = Mathf.clamp( + amounts.get(links.indexOf(entry)) * Time.delta, + -Math.abs(maxFlow), + Math.abs(maxFlow) + ); + if (flow != 0) { + entry.key.addFluid(null, amounts.get(links.indexOf(entry))); + entry.value.removeFluid(null, amounts.get(links.indexOf(entry))); + } + } + } +} diff --git a/src/omaloon/world/modules/PressureModule.java b/src/omaloon/world/modules/PressureModule.java index 3fca25f1..2c6e0e76 100644 --- a/src/omaloon/world/modules/PressureModule.java +++ b/src/omaloon/world/modules/PressureModule.java @@ -1,17 +1,116 @@ package omaloon.world.modules; +import arc.math.*; +import arc.util.*; import arc.util.io.*; +import mindustry.*; +import mindustry.content.*; +import mindustry.type.*; import mindustry.world.modules.*; +import omaloon.content.*; +import omaloon.world.meta.*; public class PressureModule extends BlockModule { - public float pressure; + public static float arbitraryPressureScalar = 10f; + public static float smoothingSpeed = 0.03f; + + public float[] liquids = new float[Vars.content.liquids().size]; + public float[] pressures = new float[Vars.content.liquids().size]; + public float air = 0, pressure = 0; + + public PressureSection section = new PressureSection(); + + public Liquid current = Liquids.water; + + /** + * Adds a certain amount of a fluid into this module, updating it's pressure accordingly. A null liquid means that air is being added to it. + */ + public void addFluid(@Nullable Liquid liquid, float amount, PressureConfig reference) { + if (liquid == null) { + air += amount; + pressure = air / reference.fluidCapacity * OlLiquids.getDensity(liquid); + } else { + if (air < 0) { + air = 0; + pressure = 0; + } + liquids[liquid.id] += amount; + pressures[liquid.id] = liquids[liquid.id] / reference.fluidCapacity * OlLiquids.getDensity(liquid); + } + if (liquid != null) current = liquid; + } + + public float get(@Nullable Liquid liquid) { + if (liquid == null) { + return air; + } else { + return liquids[liquid.id]; + } + } + + public @Nullable Liquid getMain() { + Liquid out = null; + for(int i = 0; i < liquids.length; i++) { + if (out == null && liquids[i] > 0.01) out = Vars.content.liquid(i); + if (out != null && liquids[i] > liquids[out.id]) out = Vars.content.liquid(i); + } + return out; + } + + /** + * Returns the amount of pressure felt by this module from a certain liquid + the pressure of air inside this module. + */ + public float getPressure(@Nullable Liquid liquid) { + if (liquid == null) { + return pressure; + } + return pressures[liquid.id] + pressure; + } @Override public void read(Reads read) { + air = read.f(); pressure = read.f(); + + int count = read.s(); + + for(int i = 0; i < count; i++){ + Liquid liq = Vars.content.liquid(read.s()); + float amount = read.f(); + float pressure = read.f(); + if(liq != null){ + if (amount > 0) current = liq; + liquids[liq.id] = amount; + pressures[liq.id] = pressure; + } + } } + + /** + * Removes a certain amount of a fluid from this module, updating pressure accordingly. A null liquid means that air is being removed from it. Liquids cannot be negative. + */ + public void removeFluid(@Nullable Liquid liquid, float amount, PressureConfig reference) { + if (liquid == null) { + air -= (getMain() != null ? Math.min(air, amount) : amount); + pressure = air / reference.fluidCapacity * OlLiquids.getDensity(liquid); + } else { + liquids[liquid.id] = Mathf.maxZero(liquids[liquid.id] - amount); + pressures[liquid.id] = liquids[liquid.id] / reference.fluidCapacity * OlLiquids.getDensity(liquid); + } + if (liquid != null) current = liquid; + } + @Override public void write(Writes write) { + write.f(air); write.f(pressure); + + write.s(liquids.length); + + for(int i = 0; i < liquids.length; i++){ + write.s(i); //liquid ID + write.f(liquids[i]); //liquid amount + write.f(pressures[i]); //liquid amount + } } } From d51ec2344c0ec46fcf47ca36f4e23ab09a396447 Mon Sep 17 00:00:00 2001 From: Zelaux <58040045+zelaux@users.noreply.github.com> Date: Wed, 5 Feb 2025 17:16:53 +0300 Subject: [PATCH 63/67] Merge master into auto-impl-pressure#2 --- .../bytelogic/lombok/util/ContextLibrary.java | 37 +- .../omaloon/annotations/AutoImplement.java | 2 +- .../lombok/autoimpl/ImplProcessor.java | 28 +- src/omaloon/annotations/AutoImplement.java | 2 +- src/omaloon/struct/IntRef.java | 24 + src/omaloon/world/blocks/defense/Shelter.java | 1 - .../blocks/liquid/PressureLiquidGauge.java | 20 +- .../blocks/liquid/PressureLiquidPump.java | 30 +- .../blocks/liquid/PressureLiquidValve.java | 525 +++++++++--------- .../blocks/sandbox/PressureLiquidSource.java | 6 +- 10 files changed, 383 insertions(+), 292 deletions(-) create mode 100644 src/omaloon/struct/IntRef.java diff --git a/annotations/src/main/java/bytelogic/lombok/util/ContextLibrary.java b/annotations/src/main/java/bytelogic/lombok/util/ContextLibrary.java index 760f0868..7817e108 100644 --- a/annotations/src/main/java/bytelogic/lombok/util/ContextLibrary.java +++ b/annotations/src/main/java/bytelogic/lombok/util/ContextLibrary.java @@ -6,6 +6,7 @@ import lombok.AllArgsConstructor; import lombok.Getter; import lombok.With; +import lombok.core.AST; import lombok.core.TypeLibrary; import lombok.javac.JavacNode; import lombok.javac.JavacResolution; @@ -20,16 +21,35 @@ public class ContextLibrary { public final JavacNode context; public final TypeLibrary library; public final JavacResolution resolution; - public final Map resolvedParts; + public final Map resolvedParts; public static ContextLibrary makeLib(JavacNode contextNode, TypeLibrary library) { Context context = contextNode.getContext(); JavacResolution javacResolution = Util.resolution(context); + Map resolvedParts = null; + try { + + resolvedParts = javacResolution.resolveMethodMember(contextNode); + } catch (Throwable e) { + try { + JavacNode node = contextNode; + while (node != null) { + if (node.getKind() == AST.Kind.TYPE) + for (JavacNode javacNode : node.down()) + javacResolution.resolveClassMember(javacNode); + node = node.up(); + } + resolvedParts = javacResolution.resolveMethodMember(contextNode); + } catch (Throwable ex) { + + } + + } return new ContextLibrary( contextNode, library, javacResolution, - javacResolution.resolveMethodMember(contextNode) + resolvedParts ); } @@ -41,8 +61,17 @@ public static ContextLibrary ofClasses(JavacNode context) { public String className(JCTree typeRepresentation) { if (typeRepresentation == null) return null; String resolved = resolveFull(typeRepresentation.toString()); - if(resolved==null){ - return resolvedParts.get(typeRepresentation).type.toString(); + if (resolved == null) { + /*if (resolvedParts==null) { + try { + resolvedParts=resolution.resolveMethodMember(context); + }catch (Exception i){ + + } + }*/ + if (resolvedParts != null) { + return resolvedParts.get(typeRepresentation).type.toString(); + } } return resolved; } diff --git a/annotations/src/main/java/omaloon/annotations/AutoImplement.java b/annotations/src/main/java/omaloon/annotations/AutoImplement.java index 77406236..7f58fafc 100644 --- a/annotations/src/main/java/omaloon/annotations/AutoImplement.java +++ b/annotations/src/main/java/omaloon/annotations/AutoImplement.java @@ -9,7 +9,7 @@ @Target(ElementType.METHOD) @interface NoInject { - + Class[] value(); } diff --git a/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/ImplProcessor.java b/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/ImplProcessor.java index f3db245b..8f5de906 100644 --- a/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/ImplProcessor.java +++ b/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/ImplProcessor.java @@ -4,6 +4,7 @@ import bytelogic.lombok.hierarchy.info.AbstractInfo; import bytelogic.lombok.hierarchy.info.ClassInfo; import bytelogic.lombok.hierarchy.info.InterfaceInfo; +import bytelogic.lombok.util.ContextLibrary; import bytelogic.lombok.util.Util; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.tree.JCTree; @@ -23,6 +24,7 @@ import omaloon.annotations.lombok.autoimpl.info.TypeInliner; import one.util.streamex.EntryStream; import one.util.streamex.StreamEx; +import org.jetbrains.annotations.NotNull; import java.util.*; import java.util.function.BiConsumer; @@ -60,6 +62,25 @@ public void accept(String s, InterfaceInfo info) { return flatten; } + @NotNull + private static ArrayList findNoInject(JavacNode typeNode, JCTree.JCModifiers mods) { + ArrayList list = new ArrayList<>(); + ContextLibrary classLibrary = ContextLibrary + .ofClasses(typeNode) + .withResolvedParts(null); + + for (JCTree.JCAnnotation annotation : mods.annotations) { + if (!annotation.annotationType.toString().endsWith("NoInject")) continue; + AnnotationValues values = JavacHandlerUtil.createAnnotation(AutoImplement.NoInject.class, typeNode.getNodeFor(annotation)); + String postfix = ".class"; + for (String classGuessDotClass : values.getRawExpressions("value")) { + if (!classGuessDotClass.endsWith(postfix)) continue; + list.add(classLibrary.resolveFull(classGuessDotClass.substring(0, classGuessDotClass.length() - postfix.length()))); + } + } + return list; + } + @Override public void visitCompilationUnit(JavacNode top, JCTree.JCCompilationUnit unit) { if (!updated) return; @@ -119,6 +140,7 @@ public void visitType(JavacNode typeNode, JCTree.JCClassDecl type) { for (InfoAndPos info : interfaceInfos) { + if (findNoInject(typeNode, type.mods).contains(info.info.name)) continue; implement(info.info, info.producer, typeNode, type); } @@ -143,6 +165,9 @@ private void implement(InterfaceInfo info, @NonNull JCTree.JCExpression producer JavacNode existed = fields.get(entry.getKey()); AutoImplInformation.FieldInfo fieldInfo = entry.getValue(); if (existed != null) { + if (existed.hasAnnotation(AutoImplement.NoInject.class)) { + continue; + } existed.addError("Cannot insert field %s.%s. Field with this name already exists.".formatted( fieldInfo.intefaceName, fieldInfo.name )); @@ -181,6 +206,7 @@ private void implement(InterfaceInfo info, @NonNull JCTree.JCExpression producer String methodDecs = entry.getKey(); MethodInfo methodInfo = entry.getValue(); JavacNode existed = methods.get(methodDecs); + JCTree.JCMethodDecl decl; @@ -203,7 +229,7 @@ private void implement(InterfaceInfo info, @NonNull JCTree.JCExpression producer .callerMethodNode(existed) .justCreated(false); decl = (JCTree.JCMethodDecl) existed.get(); - + if (findNoInject(existed, decl.mods).contains(info.name)) continue; } methodInfo.join(decl, contextBuilder.build()); diff --git a/src/omaloon/annotations/AutoImplement.java b/src/omaloon/annotations/AutoImplement.java index e9fd4914..ab334d17 100644 --- a/src/omaloon/annotations/AutoImplement.java +++ b/src/omaloon/annotations/AutoImplement.java @@ -9,7 +9,7 @@ @Target(ElementType.METHOD) @interface NoInject { - Class value(); + Class[] value(); } diff --git a/src/omaloon/struct/IntRef.java b/src/omaloon/struct/IntRef.java new file mode 100644 index 00000000..bf689373 --- /dev/null +++ b/src/omaloon/struct/IntRef.java @@ -0,0 +1,24 @@ +package omaloon.struct; + +public class IntRef { + public static final IntRef + tmp1=new IntRef(), + tmp2=new IntRef(), + tmp3=new IntRef(), + tmp4=new IntRef() + ; + public int value; + + public IntRef zero(){ + value=0; + return this; + } + + public IntRef(int value) { + this.value = value; + } + + + public IntRef() { + } +} diff --git a/src/omaloon/world/blocks/defense/Shelter.java b/src/omaloon/world/blocks/defense/Shelter.java index a05d6449..456bb9e1 100644 --- a/src/omaloon/world/blocks/defense/Shelter.java +++ b/src/omaloon/world/blocks/defense/Shelter.java @@ -227,7 +227,6 @@ public void read(Reads read, byte revision) { @Override public void updateTile() { - HasPressureImpl.super.updateTile(); updatePressure(); if (efficiency > 0) { if (shieldDamage >= 0) { diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidGauge.java b/src/omaloon/world/blocks/liquid/PressureLiquidGauge.java index 3ee9a066..b46363aa 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidGauge.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidGauge.java @@ -12,6 +12,7 @@ import mindustry.graphics.*; import mindustry.type.*; import mindustry.world.*; +import omaloon.struct.IntRef; import omaloon.ui.elements.*; import omaloon.world.interfaces.*; import omaloon.world.meta.*; @@ -40,21 +41,22 @@ public PressureLiquidGauge(String name) { @Override public void drawPlanRegion(BuildPlan plan, Eachable list) { - var tiling = new Object() { - int tiling = 0; - }; - Point2 - front = new Point2(1, 0).rotate(plan.rotation).add(plan.x, plan.y), - back = new Point2(-1, 0).rotate(plan.rotation).add(plan.x, plan.y); + var tiling = IntRef.tmp1.zero(); + + int dx = Geometry.d4x(plan.rotation),dy = Geometry.d4y(plan.rotation); + var front = Point2.pack(plan.x + dx, plan.y + dy); + var back = Point2.pack(plan.x - dx, plan.y - dy); boolean inverted = plan.rotation == 1 || plan.rotation == 2; list.each(next -> { - if (new Point2(next.x, next.y).equals(front) && next.block.outputsLiquid) tiling.tiling |= inverted ? 2 : 1; - if (new Point2(next.x, next.y).equals(back) && next.block.outputsLiquid) tiling.tiling |= inverted ? 1 : 2; + var nextPoint = Point2.pack(next.x, next.y); + if(!next.block.outputsLiquid)return; + if (nextPoint == front) tiling.value |= inverted ? 0b10 : 1; + if (nextPoint == back) tiling.value |= inverted ? 1 : 0b10; }); Draw.rect(bottomRegion, plan.drawx(), plan.drawy()); - Draw.rect(tileRegions[tiling.tiling], plan.drawx(), plan.drawy(), (plan.rotation + 1) * 90f % 180 - 90); + Draw.rect(tileRegions[tiling.value], plan.drawx(), plan.drawy(), (plan.rotation + 1) * 90f % 180 - 90); Draw.rect(gaugeRegion, plan.drawx(), plan.drawy(), plan.rotation * 90f); } diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidPump.java b/src/omaloon/world/blocks/liquid/PressureLiquidPump.java index c0e6d691..a799df98 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidPump.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidPump.java @@ -8,6 +8,7 @@ import arc.scene.ui.layout.*; import arc.util.*; import arc.util.io.*; +import asmlib.annotations.DebugAST; import mindustry.*; import mindustry.content.*; import mindustry.entities.*; @@ -23,6 +24,7 @@ import omaloon.annotations.Load; import omaloon.content.*; import omaloon.math.*; +import omaloon.struct.IntRef; import omaloon.utils.*; import omaloon.world.interfaces.*; import omaloon.world.meta.*; @@ -30,7 +32,7 @@ import static mindustry.Vars.*; import static mindustry.type.Liquid.*; - +@DebugAST public class PressureLiquidPump extends Block { public PressureConfig pressureConfig = new PressureConfig(); @@ -62,25 +64,25 @@ public PressureLiquidPump(String name) { @Override public void drawPlanRegion(BuildPlan plan, Eachable list) { - var tiling = new Object() { - int tiling = 0; - }; - Point2 - front = new Point2(1, 0).rotate(plan.rotation).add(plan.x, plan.y), - back = new Point2(-1, 0).rotate(plan.rotation).add(plan.x, plan.y); + + var tiling = IntRef.tmp1.zero(); + + int dx = Geometry.d4x(plan.rotation),dy = Geometry.d4y(plan.rotation); + var front = Point2.pack(plan.x + dx, plan.y + dy); + var back = Point2.pack(plan.x - dx, plan.y - dy); boolean inverted = plan.rotation == 1 || plan.rotation == 2; list.each(next -> { - if (!(next.block instanceof PressureLiquidPump)) { - if (new Point2(next.x, next.y).equals(front) && next.block.outputsLiquid) tiling.tiling |= inverted ? 2 : 1; - if (new Point2(next.x, next.y).equals(back) && next.block.outputsLiquid) tiling.tiling |= inverted ? 1 : 2; - } + var nextPoint = Point2.pack(next.x, next.y); + if(!next.block.outputsLiquid)return; + if (nextPoint == front) tiling.value |= inverted ? 0b10 : 1; + if (nextPoint == back) tiling.value |= inverted ? 1 : 0b10; }); Draw.rect(bottomRegion, plan.drawx(), plan.drawy(), 0); - if (tiling.tiling != 0) Draw.rect(arrowRegion, plan.drawx(), plan.drawy(), (plan.rotation) * 90f); - Draw.rect(tiles[tiling.tiling], plan.drawx(), plan.drawy(), (plan.rotation + 1) * 90f % 180 - 90); - if (tiling.tiling == 0) Draw.rect(topRegion, plan.drawx(), plan.drawy(), (plan.rotation) * 90f); + if (tiling.value != 0) Draw.rect(arrowRegion, plan.drawx(), plan.drawy(), (plan.rotation) * 90f); + Draw.rect(tiles[tiling.value], plan.drawx(), plan.drawy(), (plan.rotation + 1) * 90f % 180 - 90); + if (tiling.value == 0) Draw.rect(topRegion, plan.drawx(), plan.drawy(), (plan.rotation) * 90f); } @Override public TextureRegion[] icons() { diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidValve.java b/src/omaloon/world/blocks/liquid/PressureLiquidValve.java index 1337711a..dd78c665 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidValve.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidValve.java @@ -1,261 +1,274 @@ package omaloon.world.blocks.liquid; -import arc.*; -import arc.audio.*; -import arc.graphics.*; -import arc.graphics.g2d.*; -import arc.math.*; -import arc.math.geom.*; -import arc.util.*; -import arc.util.io.*; -import mindustry.content.*; -import mindustry.entities.*; -import mindustry.entities.units.*; -import mindustry.gen.*; -import mindustry.graphics.*; -import mindustry.type.*; -import mindustry.world.*; -import omaloon.annotations.AutoImplement; -import omaloon.content.*; -import omaloon.math.*; -import omaloon.utils.*; -import omaloon.world.interfaces.*; -import omaloon.world.meta.*; -import omaloon.world.modules.*; - -import static mindustry.Vars.*; -import static mindustry.type.Liquid.*; +import arc.Core; +import arc.audio.Sound; +import arc.graphics.Color; +import arc.graphics.g2d.Draw; +import arc.graphics.g2d.TextureRegion; +import arc.math.Mathf; +import arc.math.geom.Geometry; +import arc.math.geom.Point2; +import arc.util.Eachable; +import arc.util.Nullable; +import arc.util.Pack; +import arc.util.Tmp; +import arc.util.io.Reads; +import arc.util.io.Writes; +import mindustry.content.Fx; +import mindustry.entities.Effect; +import mindustry.entities.units.BuildPlan; +import mindustry.gen.Building; +import mindustry.graphics.Drawf; +import mindustry.type.Liquid; +import mindustry.world.Block; +import omaloon.content.OlLiquids; +import omaloon.content.OlSounds; +import omaloon.math.OlMath; +import omaloon.struct.IntRef; +import omaloon.utils.OlUtils; +import omaloon.world.interfaces.HasPressure; +import omaloon.world.interfaces.HasPressureImpl; +import omaloon.world.meta.FluidGroup; +import omaloon.world.meta.OlStats; +import omaloon.world.meta.PressureConfig; +import omaloon.world.meta.PressureSection; +import omaloon.world.modules.PressureModule; + +import static mindustry.Vars.renderer; +import static mindustry.type.Liquid.animationFrames; public class PressureLiquidValve extends Block { - public PressureConfig pressureConfig = new PressureConfig(); - - public TextureRegion[] tiles; - public TextureRegion[][] liquidRegions; - public TextureRegion valveRegion, topRegion, bottomRegion; - - public Effect jamEffect = Fx.explosion; - public Sound jamSound = OlSounds.jam; - - public Effect pumpingEffectOut = Fx.none; - public Effect pumpingEffectIn = Fx.none; - public float pumpingEffectInterval = 15; - - public float pressureLoss = 1f; - public float minPressureLoss = 0.05f; - - public float openMin = -15f; - public float openMax = 15f; - public float jamPoint = -45f; - - public float liquidPadding = 3f; - - public PressureLiquidValve(String name) { - super(name); - rotate = true; - update = true; - destructible = true; - } - - @Override - public void drawPlanRegion(BuildPlan plan, Eachable list) { - var tiling = new Object() { - int tiling = 0; - }; - Point2 - front = new Point2(1, 0).rotate(plan.rotation).add(plan.x, plan.y), - back = new Point2(-1, 0).rotate(plan.rotation).add(plan.x, plan.y); - - boolean inverted = plan.rotation == 1 || plan.rotation == 2; - list.each(next -> { - if (new Point2(next.x, next.y).equals(front) && next.block.outputsLiquid) tiling.tiling |= inverted ? 2 : 1; - if (new Point2(next.x, next.y).equals(back) && next.block.outputsLiquid) tiling.tiling |= inverted ? 1 : 2; - }); - - Draw.rect(bottomRegion, plan.drawx(), plan.drawy(), 0); - Draw.rect(tiles[tiling.tiling], plan.drawx(), plan.drawy(), (plan.rotation + 1) * 90f % 180 - 90); - Draw.rect(valveRegion, plan.drawx(), plan.drawy(), (plan.rotation + 1) * 90f % 180 - 90); - Draw.rect(topRegion, plan.drawx(), plan.drawy()); - } - - @Override - public TextureRegion[] icons() { - return new TextureRegion[]{bottomRegion, region}; - } - - @Override - public void init() { - super.init(); - - if (pressureConfig.fluidGroup == null) pressureConfig.fluidGroup = FluidGroup.transportation; - } - - @Override - public void load() { - super.load(); - tiles = OlUtils.split(name + "-tiles", 32, 0); - valveRegion = Core.atlas.find(name + "-valve"); - topRegion = Core.atlas.find(name + "-top"); - bottomRegion = Core.atlas.find(name + "-bottom", "omaloon-liquid-bottom"); - - liquidRegions = new TextureRegion[2][animationFrames]; - if(renderer != null){ - var frames = renderer.getFluidFrames(); - - for (int fluid = 0; fluid < 2; fluid++) { - for (int frame = 0; frame < animationFrames; frame++) { - TextureRegion base = frames[fluid][frame]; - TextureRegion result = new TextureRegion(); - result.set(base); - - result.setHeight(result.height - liquidPadding); - result.setWidth(result.width - liquidPadding); - result.setX(result.getX() + liquidPadding); - result.setY(result.getY() + liquidPadding); - - liquidRegions[fluid][frame] = result; - } - } - } - } - - @Override - public void setBars() { - super.setBars(); - pressureConfig.addBars(this); - } - - @Override - public void setStats() { - super.setStats(); - pressureConfig.addStats(stats); - stats.add(OlStats.pressureFlow, Mathf.round(pressureLoss * 60f, 2), OlStats.pressureSecond); - } - - public class PressureLiquidValveBuild extends Building implements HasPressureImpl { - - public float draining; - public float effectInterval; - public int tiling; - public float smoothAlpha; - - public boolean jammed; - - @Override - public boolean acceptsPressurizedFluid(HasPressure from, @Nullable Liquid liquid, float amount) { - return HasPressureImpl.super.acceptsPressurizedFluid(from, liquid, amount) && (liquid == pressure.getMain() || liquid == null || pressure.getMain() == null || from.pressure().getMain() == null); - } - - @Override - public boolean connects(HasPressure to) { - return HasPressureImpl.super.connects(to) && to instanceof PressureLiquidValveBuild ? - (front() == to || back() == to) && (to.front() == this || to.back() == this) : - (front() == to || back() == to); - } - - @Override - public void draw() { - float rot = rotate ? (90 + rotdeg()) % 180 - 90 : 0; - Draw.rect(bottomRegion, x, y, rotation); - Liquid main = pressure.getMain(); - - smoothAlpha = Mathf.approachDelta(smoothAlpha, main == null ? 0f : pressure.liquids[main.id]/(pressure.liquids[main.id] + pressure.air), PressureModule.smoothingSpeed); - - if (smoothAlpha > 0.01f) { - int frame = pressure.current.getAnimationFrame(); - int gas = pressure.current.gas ? 1 : 0; - - float xscl = Draw.xscl, yscl = Draw.yscl; - Draw.scl(1f, 1f); - Drawf.liquid(liquidRegions[gas][frame], x, y, Mathf.clamp(smoothAlpha), pressure.current.color.write(Tmp.c1).a(1f)); - Draw.scl(xscl, yscl); - } - Draw.rect(tiles[tiling], x, y, rot); - Draw.rect(topRegion, x, y); - Draw.rect(valveRegion, x, y, draining * (rotation % 2 == 0 ? -90f : 90f) + rot); - } - - @Override - public void onProximityUpdate() { - super.onProximityUpdate(); - - tiling = 0; - boolean inverted = rotation == 1 || rotation == 2; - if (front() instanceof HasPressure front && connected(front)) tiling |= inverted ? 2 : 1; - if (back() instanceof HasPressure back && connected(back)) tiling |= inverted ? 1 : 2; - - new PressureSection().mergeFlood(this); - } - - @Override - public boolean outputsPressurizedFluid(HasPressure to, Liquid liquid, float amount) { - return HasPressureImpl.super.outputsPressurizedFluid(to, liquid, amount) && (liquid == to.pressure().getMain() || liquid == null || pressure.getMain() == null || to.pressure().getMain() == null); - } - @Override - public void read(Reads read, byte revision) { - super.read(read, revision); - jammed = read.bool(); - draining = read.f(); - smoothAlpha = read.f(); - } - - @Override - public void updatePressure() { - HasPressureImpl.super.updatePressure(); - float pressureAmount = pressure.getPressure(pressure.getMain()); - - if (pressureAmount > jamPoint) jammed = false; - if (jammed) return; - if (pressureAmount < openMin) { - effectInterval += delta(); - addFluid(null, Math.min(openMin - pressureAmount, OlMath.flowRate( - 0, - pressureAmount, - 5, - pressureConfig.fluidCapacity, - OlLiquids.getDensity(null), - OlLiquids.getViscosity(null) - ))); - draining = Mathf.approachDelta(draining, 1, 0.014f); - } - if (pressureAmount > openMax) { - effectInterval += delta(); - removeFluid(pressure.getMain(), Math.min(pressureAmount - openMax, OlMath.flowRate( - pressureAmount, - 0, - pressureConfig.fluidCapacity, - 5, - OlLiquids.getDensity(null), - OlLiquids.getViscosity(null) - ))); - draining = Mathf.approachDelta(draining, 1, 0.014f); - } - if (effectInterval > pumpingEffectInterval) { - effectInterval = 0; - if (pressureAmount > openMax) { - pumpingEffectOut.at(x, y, draining * (rotation % 2 == 0 ? -90f : 90f) + (rotate ? (90 + rotdeg()) % 180 - 90 : 0), pressure.getMain() == null ? Color.white : pressure.getMain().color); - } else { - pumpingEffectIn.at(x, y, draining * (rotation % 2 == 0 ? -90f : 90f) + (rotate ? (90 + rotdeg()) % 180 - 90 : 0)); - } - } - - if (pressureAmount >= openMin && pressureAmount <= openMax) { - draining = Mathf.approachDelta(draining, 0, 0.014f); - } - - if (pressureAmount < jamPoint) { - jammed = true; - draining = 0f; - jamEffect.at(x, y, draining * (rotation%2 == 0 ? -90 : 90) + (rotate ? (90 + rotdeg()) % 180 - 90 : 0), valveRegion); - jamSound.at(x, y); - } - } - - @Override - public void write(Writes write) { - super.write(write); - write.bool(jammed); - write.f(draining); - write.f(smoothAlpha); - } - } + public PressureConfig pressureConfig = new PressureConfig(); + + public TextureRegion[] tiles; + public TextureRegion[][] liquidRegions; + public TextureRegion valveRegion, topRegion, bottomRegion; + + public Effect jamEffect = Fx.explosion; + public Sound jamSound = OlSounds.jam; + + public Effect pumpingEffectOut = Fx.none; + public Effect pumpingEffectIn = Fx.none; + public float pumpingEffectInterval = 15; + + public float pressureLoss = 1f; + public float minPressureLoss = 0.05f; + + public float openMin = -15f; + public float openMax = 15f; + public float jamPoint = -45f; + + public float liquidPadding = 3f; + + public PressureLiquidValve(String name) { + super(name); + rotate = true; + update = true; + destructible = true; + } + + @Override + public void drawPlanRegion(BuildPlan plan, Eachable list) { + var tiling = IntRef.tmp1.zero(); + + int dx = Geometry.d4x(plan.rotation),dy = Geometry.d4y(plan.rotation); + var front = Point2.pack(plan.x + dx, plan.y + dy); + var back = Point2.pack(plan.x - dx, plan.y - dy); + + boolean inverted = plan.rotation == 1 || plan.rotation == 2; + list.each(next -> { + var nextPoint = Point2.pack(next.x, next.y); + if(!next.block.outputsLiquid)return; + if (nextPoint == front) tiling.value |= inverted ? 0b10 : 1; + if (nextPoint == back) tiling.value |= inverted ? 1 : 0b10; + }); + + Draw.rect(bottomRegion, plan.drawx(), plan.drawy(), 0); + Draw.rect(tiles[tiling.value], plan.drawx(), plan.drawy(), (plan.rotation + 1) * 90f % 180 - 90); + Draw.rect(valveRegion, plan.drawx(), plan.drawy(), (plan.rotation + 1) * 90f % 180 - 90); + Draw.rect(topRegion, plan.drawx(), plan.drawy()); + } + + @Override + public TextureRegion[] icons() { + return new TextureRegion[]{bottomRegion, region}; + } + + @Override + public void init() { + super.init(); + + if (pressureConfig.fluidGroup == null) pressureConfig.fluidGroup = FluidGroup.transportation; + } + + @Override + public void load() { + super.load(); + tiles = OlUtils.split(name + "-tiles", 32, 0); + valveRegion = Core.atlas.find(name + "-valve"); + topRegion = Core.atlas.find(name + "-top"); + bottomRegion = Core.atlas.find(name + "-bottom", "omaloon-liquid-bottom"); + + liquidRegions = new TextureRegion[2][animationFrames]; + if (renderer != null) { + var frames = renderer.getFluidFrames(); + + for (int fluid = 0; fluid < 2; fluid++) { + for (int frame = 0; frame < animationFrames; frame++) { + TextureRegion base = frames[fluid][frame]; + TextureRegion result = new TextureRegion(); + result.set(base); + + result.setHeight(result.height - liquidPadding); + result.setWidth(result.width - liquidPadding); + result.setX(result.getX() + liquidPadding); + result.setY(result.getY() + liquidPadding); + + liquidRegions[fluid][frame] = result; + } + } + } + } + + @Override + public void setBars() { + super.setBars(); + pressureConfig.addBars(this); + } + + @Override + public void setStats() { + super.setStats(); + pressureConfig.addStats(stats); + stats.add(OlStats.pressureFlow, Mathf.round(pressureLoss * 60f, 2), OlStats.pressureSecond); + } + + public class PressureLiquidValveBuild extends Building implements HasPressureImpl { + + public float draining; + public float effectInterval; + public int tiling; + public float smoothAlpha; + + public boolean jammed; + + @Override + public boolean acceptsPressurizedFluid(HasPressure from, @Nullable Liquid liquid, float amount) { + return HasPressureImpl.super.acceptsPressurizedFluid(from, liquid, amount) && (liquid == pressure.getMain() || liquid == null || pressure.getMain() == null || from.pressure().getMain() == null); + } + + @Override + public boolean connects(HasPressure to) { + return HasPressureImpl.super.connects(to) && to instanceof PressureLiquidValveBuild ? + (front() == to || back() == to) && (to.front() == this || to.back() == this) : + (front() == to || back() == to); + } + + @Override + public void draw() { + float rot = rotate ? (90 + rotdeg()) % 180 - 90 : 0; + Draw.rect(bottomRegion, x, y, rotation); + Liquid main = pressure.getMain(); + + smoothAlpha = Mathf.approachDelta(smoothAlpha, main == null ? 0f : pressure.liquids[main.id] / (pressure.liquids[main.id] + pressure.air), PressureModule.smoothingSpeed); + + if (smoothAlpha > 0.01f) { + int frame = pressure.current.getAnimationFrame(); + int gas = pressure.current.gas ? 1 : 0; + + float xscl = Draw.xscl, yscl = Draw.yscl; + Draw.scl(1f, 1f); + Drawf.liquid(liquidRegions[gas][frame], x, y, Mathf.clamp(smoothAlpha), pressure.current.color.write(Tmp.c1).a(1f)); + Draw.scl(xscl, yscl); + } + Draw.rect(tiles[tiling], x, y, rot); + Draw.rect(topRegion, x, y); + Draw.rect(valveRegion, x, y, draining * (rotation % 2 == 0 ? -90f : 90f) + rot); + } + + @Override + public void onProximityUpdate() { + super.onProximityUpdate(); + + tiling = 0; + boolean inverted = rotation == 1 || rotation == 2; + if (front() instanceof HasPressure front && connected(front)) tiling |= inverted ? 2 : 1; + if (back() instanceof HasPressure back && connected(back)) tiling |= inverted ? 1 : 2; + + new PressureSection().mergeFlood(this); + } + + @Override + public boolean outputsPressurizedFluid(HasPressure to, Liquid liquid, float amount) { + return HasPressureImpl.super.outputsPressurizedFluid(to, liquid, amount) && (liquid == to.pressure().getMain() || liquid == null || pressure.getMain() == null || to.pressure().getMain() == null); + } + + @Override + public void read(Reads read, byte revision) { + super.read(read, revision); + jammed = read.bool(); + draining = read.f(); + smoothAlpha = read.f(); + } + + @Override + public void updatePressure() { + HasPressureImpl.super.updatePressure(); + float pressureAmount = pressure.getPressure(pressure.getMain()); + + if (pressureAmount > jamPoint) jammed = false; + if (jammed) return; + if (pressureAmount < openMin) { + effectInterval += delta(); + addFluid(null, Math.min(openMin - pressureAmount, OlMath.flowRate( + 0, + pressureAmount, + 5, + pressureConfig.fluidCapacity, + OlLiquids.getDensity(null), + OlLiquids.getViscosity(null) + ))); + draining = Mathf.approachDelta(draining, 1, 0.014f); + } + if (pressureAmount > openMax) { + effectInterval += delta(); + removeFluid(pressure.getMain(), Math.min(pressureAmount - openMax, OlMath.flowRate( + pressureAmount, + 0, + pressureConfig.fluidCapacity, + 5, + OlLiquids.getDensity(null), + OlLiquids.getViscosity(null) + ))); + draining = Mathf.approachDelta(draining, 1, 0.014f); + } + if (effectInterval > pumpingEffectInterval) { + effectInterval = 0; + if (pressureAmount > openMax) { + pumpingEffectOut.at(x, y, draining * (rotation % 2 == 0 ? -90f : 90f) + (rotate ? (90 + rotdeg()) % 180 - 90 : 0), pressure.getMain() == null ? Color.white : pressure.getMain().color); + } else { + pumpingEffectIn.at(x, y, draining * (rotation % 2 == 0 ? -90f : 90f) + (rotate ? (90 + rotdeg()) % 180 - 90 : 0)); + } + } + + if (pressureAmount >= openMin && pressureAmount <= openMax) { + draining = Mathf.approachDelta(draining, 0, 0.014f); + } + + if (pressureAmount < jamPoint) { + jammed = true; + draining = 0f; + jamEffect.at(x, y, draining * (rotation % 2 == 0 ? -90 : 90) + (rotate ? (90 + rotdeg()) % 180 - 90 : 0), valveRegion); + jamSound.at(x, y); + } + } + + @Override + public void write(Writes write) { + super.write(write); + write.bool(jammed); + write.f(draining); + write.f(smoothAlpha); + } + } } diff --git a/src/omaloon/world/blocks/sandbox/PressureLiquidSource.java b/src/omaloon/world/blocks/sandbox/PressureLiquidSource.java index 61bc864a..8a0ee469 100644 --- a/src/omaloon/world/blocks/sandbox/PressureLiquidSource.java +++ b/src/omaloon/world/blocks/sandbox/PressureLiquidSource.java @@ -10,6 +10,7 @@ import arc.scene.ui.layout.*; import arc.util.*; import arc.util.io.*; +import asmlib.annotations.DebugAST; import mindustry.*; import mindustry.entities.units.*; import mindustry.gen.*; @@ -181,11 +182,6 @@ public void updateTile() { pressure.liquids[liq.id] = liq.id == liquid ? Mathf.maxZero(targetAmount) : 0; pressure.pressures[liq.id] = pressure.liquids[liq.id] / pressureConfig.fluidCapacity * OlLiquids.getDensity(liq); }); - if(false){ - //in original code here we wont to invoke updatePressure? - //will fix this later - AutoImplement.Util.Inject(HasPressureImpl.class); - } } @Override From 738959e65042753aec0f7407e9026ba5b06447df Mon Sep 17 00:00:00 2001 From: = Date: Wed, 5 Feb 2025 22:57:35 -0300 Subject: [PATCH 64/67] millipede code thingy --- revisions/ChainedUnit/0.json | 1 + revisions/LegsMillipedeUnit/0.json | 1 - src/omaloon/ai/MillipedeAI.java | 6 +- src/omaloon/content/OlUnitTypes.java | 90 ++- src/omaloon/entities/comp/ChainedComp.java | 347 ++++++++++ src/omaloon/entities/comp/MillipedeComp.java | 595 ------------------ .../entities/units/MillipedeDefaultUnit.java | 499 --------------- .../entities/units/MillipedeSegmentUnit.java | 448 ------------- src/omaloon/type/MillipedeUnitType.java | 211 ++----- 9 files changed, 456 insertions(+), 1742 deletions(-) create mode 100644 revisions/ChainedUnit/0.json delete mode 100644 revisions/LegsMillipedeUnit/0.json create mode 100644 src/omaloon/entities/comp/ChainedComp.java delete mode 100644 src/omaloon/entities/comp/MillipedeComp.java delete mode 100644 src/omaloon/entities/units/MillipedeDefaultUnit.java delete mode 100644 src/omaloon/entities/units/MillipedeSegmentUnit.java diff --git a/revisions/ChainedUnit/0.json b/revisions/ChainedUnit/0.json new file mode 100644 index 00000000..7e4a25c8 --- /dev/null +++ b/revisions/ChainedUnit/0.json @@ -0,0 +1 @@ +{fields:[{name:abilities,type:"mindustry.entities.abilities.Ability[]"},{name:ammo,type:float},{name:childID,type:int},{name:controller,type:mindustry.entities.units.UnitController},{name:elevation,type:float},{name:flag,type:double},{name:grown,type:boolean},{name:health,type:float},{name:isShooting,type:boolean},{name:mineTile,type:mindustry.world.Tile},{name:mounts,type:"mindustry.entities.units.WeaponMount[]"},{name:parentID,type:int},{name:plans,type:arc.struct.Queue},{name:rotation,type:float},{name:shield,type:float},{name:spawnedByCore,type:boolean},{name:stack,type:mindustry.type.ItemStack},{name:statuses,type:arc.struct.Seq},{name:team,type:mindustry.game.Team},{name:type,type:mindustry.type.UnitType},{name:updateBuilding,type:boolean},{name:vel,type:arc.math.geom.Vec2},{name:x,type:float},{name:y,type:float}]} \ No newline at end of file diff --git a/revisions/LegsMillipedeUnit/0.json b/revisions/LegsMillipedeUnit/0.json deleted file mode 100644 index 9c70f932..00000000 --- a/revisions/LegsMillipedeUnit/0.json +++ /dev/null @@ -1 +0,0 @@ -{fields:[{name:abilities,type:"mindustry.entities.abilities.Ability[]"},{name:ammo,type:float},{name:childId,type:int},{name:controller,type:mindustry.entities.units.UnitController},{name:elevation,type:float},{name:flag,type:double},{name:headId,type:int},{name:health,type:float},{name:isShooting,type:boolean},{name:mineTile,type:mindustry.world.Tile},{name:mounts,type:"mindustry.entities.units.WeaponMount[]"},{name:plans,type:arc.struct.Queue},{name:regenTime,type:float},{name:rotation,type:float},{name:shield,type:float},{name:spawnedByCore,type:boolean},{name:splitHealthDiv,type:float},{name:stack,type:mindustry.type.ItemStack},{name:statuses,type:arc.struct.Seq},{name:team,type:mindustry.game.Team},{name:type,type:mindustry.type.UnitType},{name:updateBuilding,type:boolean},{name:vel,type:arc.math.geom.Vec2},{name:waitTime,type:float},{name:x,type:float},{name:y,type:float}]} \ No newline at end of file diff --git a/src/omaloon/ai/MillipedeAI.java b/src/omaloon/ai/MillipedeAI.java index 915f10de..f9332893 100644 --- a/src/omaloon/ai/MillipedeAI.java +++ b/src/omaloon/ai/MillipedeAI.java @@ -16,7 +16,7 @@ public class MillipedeAI extends GroundAI { @Override public void updateWeapons() { - if (!(unit instanceof Millipedec millipedec)) return; + if (!(unit instanceof Chainedc millipedec)) return; if (!millipedec.isHead()) return; float rotation = unit.rotation - 90; @@ -34,7 +34,7 @@ public void updateWeapons() { unit.isShooting = false; - cast().distributeActionBack(u -> { + cast().consBackwards(u -> { for(WeaponMount mount : u.mounts){ Weapon weapon = mount.weapon; float wrange = weapon.range(); @@ -116,7 +116,7 @@ public void commandTarget(Teamc moveTo) { this.commandPosition.setZero(); } - public T cast() { + public T cast() { return (T) unit; } } \ No newline at end of file diff --git a/src/omaloon/content/OlUnitTypes.java b/src/omaloon/content/OlUnitTypes.java index 98e4a9a8..01a50b81 100644 --- a/src/omaloon/content/OlUnitTypes.java +++ b/src/omaloon/content/OlUnitTypes.java @@ -38,7 +38,7 @@ public class OlUnitTypes { public static @EntityDef({Unitc.class, Flyingc.class, Ornitopterc.class}) UnitType effort; // millipede - public static @EntityDef({Unitc.class, Millipedec.class, Legsc.class}) UnitType collector; + public static @EntityDef({Unitc.class, Chainedc.class}) UnitType collector; // core public static UnitType discovery; @@ -49,69 +49,55 @@ public class OlUnitTypes { public static void load() { collector = new MillipedeUnitType("collector"){{ - constructor = LegsMillipedeUnit::create; + constructor = ChainedUnit::create; aiController = MillipedeAI::new; + + omniMovement = false; + speed = 0.6f; health = 200f; regenTime = 15f * 60f; - chainable = true; + + segmentLength = 5; + maxSegments = 20; + splittable = true; - omniMovement = false; + angleLimit = 65f; - segmentLength = 5; segmentDamageScl = 8f; segmentCast = 8; segmentOffset = 7.3f; - maxSegments = 20; - preventDrifting = true; + hidden = true; - legLength = 8f; - lockLegBase = true; - legContinuousMove = true; - legExtension = -2f; - legBaseOffset = 3f; - legMaxLength = 1.1f; - legMinLength = 0.2f; - legLengthScl = 0.96f; - legForwardScl = 0.7f; - legGroupSize = 2; - rippleScale = 0.7f; - headLegCount = segmentLegCount = tailLegCount = 2; - - legMoveSpace = 2f; - allowLegStep = true; - hovering = false; - legPhysicsLayer = true; - - Seq weaponSeq = Seq.with( - new Weapon("omaloon-collector-beam") {{ - x = 0f; - y = 1f; - rotate = true; - mirror = false; - reload = 60f; - bullet = new ArtilleryBulletType(5f, 7) {{ - maxRange = 40f; - collidesTiles = collidesAir = collidesGround = true; - width = height = 11f; - splashDamage = 25f; - splashDamageRadius = 25f; - trailColor = hitColor = lightColor = backColor = Pal.thoriumPink; - frontColor = Pal.thoriumPink; - }}; - }} - ); - segmentWeapons = new Seq[] { - Seq.with(), - weaponSeq, weaponSeq, weaponSeq, - weaponSeq, weaponSeq, weaponSeq, - weaponSeq, weaponSeq, weaponSeq, - weaponSeq, weaponSeq, weaponSeq, - weaponSeq, weaponSeq, weaponSeq, - weaponSeq, weaponSeq, weaponSeq, - Seq.with() + weaponsIndex = unit -> { + if (unit instanceof Chainedc chain) { + if (chain.isHead() || chain.isTail()) return 0; + return 1; + } + return 0; }; + chainWeapons.add( + Seq.with(), + Seq.with( + new Weapon("omaloon-collector-beam") {{ + x = 0f; + y = 1f; + rotate = true; + mirror = false; + reload = 60f; + bullet = new ArtilleryBulletType(5f, 7) {{ + maxRange = 40f; + collidesTiles = collidesAir = collidesGround = true; + width = height = 11f; + splashDamage = 25f; + splashDamageRadius = 25f; + trailColor = hitColor = lightColor = backColor = Pal.thoriumPink; + frontColor = Pal.thoriumPink; + }}; + }} + ) + ); }}; //region core diff --git a/src/omaloon/entities/comp/ChainedComp.java b/src/omaloon/entities/comp/ChainedComp.java new file mode 100644 index 00000000..868a1e35 --- /dev/null +++ b/src/omaloon/entities/comp/ChainedComp.java @@ -0,0 +1,347 @@ +package omaloon.entities.comp; + +import arc.func.*; +import arc.math.*; +import arc.struct.*; +import arc.util.*; +import arc.util.io.*; +import ent.anno.Annotations.*; +import mindustry.entities.*; +import mindustry.entities.units.*; +import mindustry.game.*; +import mindustry.gen.*; +import mindustry.type.*; +import omaloon.gen.*; +import omaloon.type.*; +import omaloon.utils.*; + +@SuppressWarnings({"unused", "unchecked", "RedundantVariable", "UnnecessaryReturnStatement"}) +@EntityComponent +abstract class ChainedComp implements Unitc { + transient Unit head, tail, parent, child; + + transient float growTime = 0, chainTime = 0; + + // internal values that i wish i had the entityanno knowledge to not make it generate io + private int parentID = -1, childID = -1; + boolean grown; + + @Import UnitType type; + @Import UnitController controller; + @Import Team team; + @Import float x, y, rotation; + @Import WeaponMount[] mounts; + + /** + * Add first segments if this unit is not grown. + */ + @Override + public void add() { + head = tail = self(); + + if (!grown) { + for(int i = 0; i < checkType(type).minSegments - 1; i++) { + grow(); + } + // i need this because again, i don't know how to not genio. + grown = true; + } + } + + @Override + public void aim(float x, float y) { + if (isHead()) { + final float finalX = x, finalY = y; + consBackwards(u -> { + if (!u.isHead()) u.aim(finalX, finalY); + }); + } + } + + /** + * Multiplies the unit cap to fit the amount of biggest sized chains. If it overflows, then just pick the regular unit cap. + */ + @Override + @Replace + public int cap() { + MillipedeUnitType uType = checkType(type); + return Math.max(Units.getCap(team) * Math.max(uType.segmentLength, uType.maxSegments), Units.getCap(team)); + } + + /** + * Wrong cast errors are way too long. So long in fact that the crash box is too small for it. + */ + public MillipedeUnitType checkType(UnitType def) { + if (!(def instanceof MillipedeUnitType)) throw new RuntimeException("Unit's type must be MillipedeUnitType"); + return (MillipedeUnitType) def; + } + + /** + * Connects this centipede with another one. + *
  • + * If this unit is not the chain unit's tail, it'll call this method on the tail unit. + *
  • + *
  • + * If Parameter "to" is not the chain unit's head, "to" will become its head() method. + *
  • + */ + public void connect(Unit to) { + Chainedc cast = ((Chainedc) to).head().as(); + if (isTail()) { + cast.parent(self()); + child = to; + + ((Chainedc) head).consBackwards(u -> { + u.head(head); + u.tail(cast.tail()); + }); + + ((Chainedc) head).consBackwards(u -> { + u.setupWeapons(u.type); + if (!(u.controller() instanceof Player)) u.resetController(); + }); + } else ((Chainedc) tail).connect(to); + } + + /** + * @param cons will run through this unit and it's children recursively. + */ + public void consBackwards(Cons cons){ + T current = as(); + cons.get(current); + while(current.child() != null){ + cons.get(current.child().as()); + current = current.child().as(); + } + } + + /** + * @param cons will run through this unit and it's parents recursively. + */ + public void consForward(Cons cons){ + T current = as(); + cons.get(current); + while(current.parent() != null) { + cons.get(current.parent().as()); + current = current.parent().as(); + } + } + + /** + * Force a specific controller on certain parts of the chain. + */ + @MethodPriority(-1) + @Override + @BreakAll + public void controller(UnitController next){ + if (!isHead()) { + if(next instanceof Player){ + head.controller(next); + return; + } + + controller = new AIController(); + if (controller.unit() != self()) controller.unit(self()); + return; + } + } + + @Override + public void controlWeapons(boolean rotate, boolean shoot) { + if (isHead()) consBackwards(unit -> { + if (!unit.isHead()) unit.controlWeapons(rotate, shoot); + }); + } + + /** + * Counts the amount of children from this unit recursively. + */ + public int countBackwards() { + int out = 0; + + T current = as(); + while(current.child() != null) { + out++; + current = current.child().as(); + } + + return out; + } + + /** + * Counts the amount of parents from this unit recursively. + */ + public int countForward() { + int out = 0; + + T current = as(); + while(current.parent() != null) { + out++; + current = current.parent().as(); + } + + return out; + } + + /** + * Adds an extra segment to the chain. + */ + public void grow() { + if (!isTail()) { + ((Chainedc) tail).grow(); + } else { + MillipedeUnitType uType = checkType(type); + + T tail = ((T) type.create(team)); + tail.grown(true); + tail.set( + x + Angles.trnsx(rotation + 90, 0, uType.segmentOffset), + y + Angles.trnsy(rotation + 90, 0, uType.segmentOffset) + ); + tail.rotation = rotation; + tail.add(); + connect(tail); + } + } + + /** + * Self explanatory, they'll return true if it is the head, if it isn't the head nor the tail, or if it is tje tail. Respectively. + */ + public boolean isHead() { + return head == self(); + } + public boolean isSegment() { + return head != self() && tail != self(); + } + public boolean isTail() { + return tail == self(); + } + + /** + * Read parent and child id. + */ + @Override + public void read(Reads read) { + parentID = read.i(); + childID = read.i(); + } + + /** + * Split the chain or kill the whole chain if an unit is removed. + */ + @Override + public void remove() { + if (checkType(type).splittable) { + if (parent != null) { + ((Chainedc) parent).child(null); + ((Chainedc) parent).consForward(u -> { + u.tail(parent); + u.setupWeapons(u.type); + }); + } + if (child != null) { + ((Chainedc) child).parent(null); + ((Chainedc) child).consBackwards(u -> { + u.head(child); + u.setupWeapons(u.type); + }); + } + if (parent != null && child != null) checkType(type).splitSound.at(x, y); + } else { + if (parent != null) ((Chainedc) parent).consForward(Unitc::kill); + if (child != null) ((Chainedc) child).consBackwards(Unitc::kill); + } + } + + /** + * Updates the mounts to be based on the unit's position in the chain. Called when the chain connects. + */ + @Override + @Replace + public void setupWeapons(UnitType def) { + MillipedeUnitType uType = checkType(def); + Seq weapons = uType.chainWeapons.get(uType.weaponsIndex.get(self())); + mounts = new WeaponMount[weapons.size]; + for (int i = 0; i < mounts.length; i++) { + mounts[i] = weapons.get(i).mountType.get(weapons.get(i)); + } + } + + /** + * Connect the units together after read. + */ + @Override + public void update() { + if (parentID != -1) { + if (parent == null) ((Chainedc) Groups.unit.getByID(parentID)).connect(self()); + parentID = -1; + } + if (childID != -1) { + if (child == null) connect(Groups.unit.getByID(childID)); + childID = -1; + } + + if (isTail()) { + MillipedeUnitType uType = checkType(type); + + if (countForward() + 1 < uType.segmentLength && uType.regenTime > 0) { + growTime += Time.delta; + if (growTime > uType.regenTime) { + grow(); + uType.chainSound.at(x, y); + growTime %= uType.regenTime; + } + } + + Tmp.r1.setCentered( + x + Angles.trnsx(rotation + 90, 0, uType.segmentOffset), + y + Angles.trnsy(rotation + 90, 0, uType.segmentOffset), + uType.segmentOffset + ); + Units.nearby(Tmp.r1, u -> { + if (u instanceof Chainedc chain && chain.isHead() && u != head && countForward() + chain.countBackwards() + 2 <= uType.maxSegments && uType.chainTime > 0) { + chainTime += Time.delta; + if (chainTime > uType.chainTime) { + Log.info("a"); + connect(u); + uType.chainSound.at(x, y); + chainTime %= uType.chainTime; + } + } + }); + + if (countForward() + 1 < uType.minSegments) { + consBackwards(Unitc::kill); + } + } + } + + /** + * Updates the position and rotation of each segment in the chain. + */ + @Insert("update()") + public void updateChain() { + MillipedeUnitType uType = checkType(type); + if (isHead()) consBackwards(c -> { + if (c.parent() != null) { + Tmp.v1.set(c).sub(c.parent()).nor().scl(uType.segmentOffset); + float angleDst = OlUtils.angleDistSigned(Tmp.v1.angle(), c.parent().rotation + 180); + if (Math.abs(angleDst) > uType.angleLimit) { + Tmp.v1.rotate(-Tmp.v1.angle() + c.parent().rotation + 180 + (angleDst > 0 ? uType.angleLimit : -uType.angleLimit)); + } + Tmp.v1.add(c.parent()); + c.set(Tmp.v1.x, Tmp.v1.y); + c.rotation = c.angleTo(c.parent()); + } + }); + } + + /** + * Save parent and child id to be read later. + */ + @Override + public void write(Writes write) { + write.i(parent == null ? -1 : parent.id); + write.i(child == null ? -1 : child.id); + } +} diff --git a/src/omaloon/entities/comp/MillipedeComp.java b/src/omaloon/entities/comp/MillipedeComp.java deleted file mode 100644 index 87ad212f..00000000 --- a/src/omaloon/entities/comp/MillipedeComp.java +++ /dev/null @@ -1,595 +0,0 @@ -package omaloon.entities.comp; - -import arc.func.*; -import arc.graphics.g2d.*; -import arc.math.*; -import arc.math.geom.*; -import arc.struct.*; -import arc.util.*; -import arc.util.io.*; -import ent.anno.Annotations.*; -import mindustry.entities.*; -import mindustry.entities.EntityCollisions.*; -import mindustry.entities.units.*; -import mindustry.game.*; -import mindustry.gen.*; -import mindustry.type.*; -import omaloon.gen.*; -import omaloon.type.*; -import omaloon.utils.*; - -@SuppressWarnings({"unused", "UnnecessaryReturnStatement"}) -@EntityComponent -abstract class MillipedeComp implements Unitc, Legsc { - private static Unit last; - transient Unit head, parent, child, tail; - transient float layer = 0f, scanTime = 0f; - transient byte weaponIdx = 0; - transient boolean removing = false, saveAdd = false; - - protected float splitHealthDiv = 1f; - protected float regenTime = 0f; - protected float waitTime = 0f; - - @SyncLocal public int childId = -1, headId = -1; - @Import UnitType type; - @Import float healthMultiplier, health, x, y, elevation, rotation, baseRotation; - @Import boolean dead, isShooting; - @Import Leg[] legs; - @Import WeaponMount[] mounts; - @Import Team team; - - @Override - public void add(){ - MillipedeUnitType uType = (MillipedeUnitType)type; - Unit current = self(); - if(isHead()){ - if(saveAdd){ - var seg = (Unit & Millipedec)child; - while(seg != null){ - seg.add(); - seg.setupWeapons(uType); - seg = (Unit & Millipedec)seg.child(); - } - saveAdd = false; - return; - } else { - ((Millipedec) addTail()).addTail(); - } - float[] rot = {rotation() + uType.angleLimit}; - Tmp.v1.trns(rot[0] + 180f, uType.segmentOffset + uType.headOffset).add(self()); - distributeActionBack(u -> { - if(u != self()){ - u.x = Tmp.v1.x; - u.y = Tmp.v1.y; - u.rotation = rot[0]; - - rot[0] += uType.angleLimit; - Tmp.v2.trns(rot[0] + 180f, uType.segmentOffset); - Tmp.v1.add(Tmp.v2); - - u.add(); - u.setupWeapons(uType); - } - }); - } - } - - Unit addTail(){ - if(isHead()) head = self(); - if(!isTail()) return null; - Unit tail = type.constructor.get(); - tail.team = team; - tail.setType(type); - tail.ammo = type.ammoCapacity; - tail.elevation = type.flying ? 1f : 0; - tail.heal(); - - MillipedeUnitType uType = (MillipedeUnitType)type; - if(tail instanceof Millipedec){ - float z = layer + uType.segmentLayerOffset; - Tmp.v1.trns(rotation() + 180f, uType.segmentOffset).add(self()); - tail.set(Tmp.v1); - ((Millipedec)tail).layer(z); - ((Millipedec)tail).head(head); - ((Millipedec)tail).parent(self()); - child = tail; - tail.setupWeapons(uType); - tail.add(); - ((Millipedec) tail).distributeActionForward(u -> u.setupWeapons(uType)); - } - return tail; - } - - @Override - public void afterSync(){ - if(headId != -1 && head == null){ - Unit h = Groups.unit.getByID(headId); - if(h instanceof Millipedec wc){ - head = h; - headId = -1; - } - } - if(childId != -1 && child == null){ - Unit c = Groups.unit.getByID(childId); - if(c instanceof Millipedec wc){ - child = c; - wc.parent(self()); - childId = -1; - } - } - } - - @Replace - @Override - public void aim(float x, float y) { - if (isHead()) distributeActionBack(u -> { - Tmp.v1.set(x, y).sub(this.x, this.y); - if (Tmp.v1.len() < type.aimDst) Tmp.v1.setLength(type.aimDst); - float - tx = Tmp.v1.x + this.x, - ty = Tmp.v1.y + this.y; - - for (WeaponMount mount : u.mounts) if (mount.weapon.controllable) { - mount.aimX = tx; - mount.aimY = ty; - } - - u.aimX = tx; - u.aimY = ty; - }); - } - - @Replace - @Override - public int cap(){ - int max = Math.max(((MillipedeUnitType)type).maxSegments, ((MillipedeUnitType)type).segmentLength); - return Math.max(Units.getCap(team), Units.getCap(team) * max); - } - - boolean canJoin(Unit other) { - if (!(other instanceof Millipedec snek)) return false; - MillipedeUnitType uType = (MillipedeUnitType)type; - - return uType == other.type() && snek.countAll() + countAll() <= uType.maxSegments; - } - - public void connect(Unit other){ - if(other instanceof Millipedec snek && isHead() && snek.isTail()){ - MillipedeUnitType uType = (MillipedeUnitType) type; - float z = snek.layer() + uType.segmentLayerOffset; - distributeActionBack(u -> { - u.layer(z); - u.head(snek.head()); - }); - snek.child(self()); - parent = other; - head = snek.head(); - ((Millipedec) head).distributeActionBack(u -> u.setupWeapons(type)); - uType.chainSound.at(self()); - if(controller() instanceof Player){ - UnitController con = controller(); - snek.head().controller(con); - con.unit(snek.head()); - controller(type.createController(self())); - } - } - } - - @MethodPriority(-1) - @Override - @BreakAll - public void controller(UnitController next){ - if(next instanceof Player && head != null && !isHead()){ - head.controller(next); - return; - } - } - - @Override - @Replace - public void controlWeapons(boolean rotate, boolean shoot) { - if (isHead()) distributeActionBack((unit) -> { - for(WeaponMount mount : unit.mounts) { - if (mount.weapon.controllable) { - mount.rotate = rotate; - mount.shoot = shoot; - } - } - - unit.isShooting = shoot; - }); - } - - /** - * counts the number of units towards the tail - */ - int countBackward(){ - Millipedec current = self(); - int num = 0; - while(current != null && current.child() != null){ - if(current.child() instanceof Millipedec){ - num++; - current = (Millipedec)current.child(); - }else{ - current = null; - } - } - return num; - } - /** - * counts the number of units in this snake, including itself - */ - int countAll() { - return countBackward() + countForward() + 1; - } - /** - * counts the number of units towards the head - */ - int countForward(){ - Millipedec current = self(); - int num = 0; - while(current != null && current.parent() != null){ - if(current.parent() instanceof Millipedec){ - num++; - current = (Millipedec)current.parent(); - }else{ - current = null; - } - } - return num; - } - - @Replace - @MethodPriority(-2) - @Override - @BreakAll - public void damage(float amount){ - if(!isHead() && head != null && !((MillipedeUnitType)type).splittable){ - head.damage(amount); - return; - } - } - - /** - * runs a consumer with every unit towards the tail - */ - void distributeActionBack(Cons cons){ - T current = as(); - cons.get(current); - while(current.child() != null){ - cons.get(current.child().as()); - current = current.child().as(); - } - } - - /** - * runs a consumer with every unit towards the head - */ - void distributeActionForward(Cons cons){ - T current = as(); - cons.get(current); - while(current.parent() != null){ - cons.get(current.parent().as()); - current = current.parent().as(); - } - } - - @MethodPriority(-1) - @Override - @BreakAll - public void heal(float amount){ - if(!isHead() && head != null && !((MillipedeUnitType)type).splittable){ - head.heal(amount); - return; - } - } - - @Override - @Replace - public TextureRegion icon(){ - MillipedeUnitType uType = (MillipedeUnitType)type; - - if(isHead() && isTail()) return type.fullIcon; - if(isTail()) return uType.tailOutline; - if(!isHead()) return uType.segmentOutline; - return type.fullIcon; - } - - boolean isHead(){ - return parent == null || head == self(); - } - boolean isSegment() { - return !isHead() && !isTail(); - } - boolean isTail(){ - return child == null; - } - - @Replace - @Override - public boolean isAI(){ - if(head != null && !isHead()) return head.isAI(); - return controller() instanceof AIController; - } - - @MethodPriority(100) - @Override - public void read(Reads read){ - if(read.bool()){ - MillipedeUnitType uType = (MillipedeUnitType)type; - saveAdd = true; - int seg = read.s(); - Millipedec current = self(); - for(int i = 0; i < seg; i++){ - Unit u = type.constructor.get(); - Millipedec w = (Millipedec)u; - current.child(u); - w.parent((Unit)current); - w.head(self()); - w.layer(layer + uType.segmentLayerOffset * i); - w.weaponIdx(read.b()); - u.read(read); - current = w; - } - } - } - - @Override - @BreakAll - public void remove(){ - MillipedeUnitType uType = (MillipedeUnitType)type; - if(uType.splittable){ - if(child != null && parent != null) uType.splitSound.at(x(), y()); - if(child != null){ - var wc = (Unit & Millipedec)child; - float z = 0f; - wc.parent(null); - wc.distributeActionBack(u -> u.setupWeapons(uType)); - while(wc != null){ - wc.layer(z += uType.segmentLayerOffset); - wc.splitHealthDiv(wc.splitHealthDiv() * 2f); - wc.head(child); - if(wc.isTail()) wc.waitTime(5f * 60f); - wc = (Unit & Millipedec)wc.child(); - } - } - if(parent != null) { - Millipedec wp = ((Millipedec)parent); - distributeActionForward(u -> { - u.setupWeapons(uType); - if(u != self()){ - u.splitHealthDiv(u.splitHealthDiv() * 2f); - } - }); - wp.child(null); - wp.waitTime(5f * 60f); - } - parent = null; - child = null; - } - if(!isHead() && !uType.splittable && !removing){ - head.remove(); - return; - } - if(isHead() && !uType.splittable){ - distributeActionBack(u -> { - if(u != self()){ - u.removing(true); - u.remove(); - u.removing(false); - } - }); - } - parent = null; - child = null; - } - - @Replace - @Override - public void resetLegs(float legLength) { - MillipedeUnitType uType = (MillipedeUnitType)type; - int count = 0; - if ((isHead() && isTail()) || isSegment()) { - count = uType.segmentLegCount; - } else { - if (isHead()) count = uType.headLegCount; - if (isTail()) count = uType.tailLegCount; - } - - if (legs.length == count) return; - - legs = new Leg[count]; - if (type.lockLegBase) { - baseRotation = rotation; - } - - for(int i = 0; i < legs.length; ++i) { - Leg l = new Leg(); - float dstRot = this.legAngle(i); - Vec2 baseOffset = this.legOffset(Tmp.v5, i).add(this.x, this.y); - l.joint.trns(dstRot, legLength / 2.0F).add(baseOffset); - l.base.trns(dstRot, legLength).add(baseOffset); - legs[i] = l; - } - - } - - /** - * only heads will be written - */ - @Override - public boolean serialize(){ - return isHead(); - } - - @Replace(1) - @Override - public void setupWeapons(UnitType def) { - MillipedeUnitType uType = (MillipedeUnitType)def; - if ((isTail() && uType.tailHasWeapon) || (isHead() && uType.headHasWeapon) || isSegment()) { - Seq seq = uType.segmentWeapons[Math.min(uType.segmentWeapons.length - 1, countForward())]; - mounts = new WeaponMount[seq.size]; - for (int i = 0; i < mounts.length; i++) { - mounts[i] = seq.get(i).mountType.get(seq.get(i)); - } - } else { - mounts = new WeaponMount[] {}; - } - } - - @Replace(1) - @Override - public SolidPred solidity() { - if (!isHead()) return null; - - return type.allowLegStep ? EntityCollisions::legsSolid : EntityCollisions::solid; - } - - @Replace - @Override - public boolean moving(){ - if(!isHead()) return head.moving(); - return !vel().isZero(0.01f); - } - - @Replace - @Override - public float speed(){ - if(!isHead()) return 0f; - float strafePenalty = isGrounded() || !isPlayer() ? 1f : Mathf.lerp(1f, type.strafePenalty, Angles.angleDist(vel().angle(), rotation) / 180f); - float boost = Mathf.lerp(1f, type.canBoost ? type.boostMultiplier : 1f, elevation); - return type.speed * strafePenalty * boost * floorSpeedMultiplier(); - } - - @Override - public void update(){ - MillipedeUnitType uType = (MillipedeUnitType)type; - if (countAll() < 3) kill(); - if(uType.splittable && isTail() && uType.regenTime > 0f){ - int forward = countForward(); - if(forward < uType.segmentLength - 1){ - regenTime += Time.delta; - if(regenTime >= uType.regenTime){ - regenTime = 0f; - Unit unit; - if((unit = addTail()) != null){ - health /= 2f; - unit.health = health; - ((MillipedeUnitType)type).chainSound.at(self()); - } - } - } - }else regenTime = 0f; - if(isTail() && waitTime > 0) waitTime -= Time.delta; - if(!uType.splittable){ - if(!isHead()) health = head.health; - if((isHead() && isAdded()) || (head != null && head.isAdded())){ - Millipedec t = (Millipedec)child; - while(t != null && !t.isAdded()){ - t.add(); - t = (Millipedec)t.child(); - } - } - } - if(uType.splittable && (parent != null || child != null) && dead){ - destroy(); - } - } - - @Wrap(value = "update()", block = Boundedc.class) - boolean updateBounded(){ - return isHead(); - } - - @Insert(value = "update()", block = Statusc.class) - private void updateHealthDiv(){ - healthMultiplier /= splitHealthDiv; - } - - @Insert("update()") - private void updatePost(){ - if(isHead()){ - MillipedeUnitType uType = (MillipedeUnitType)type; - last = self(); - distributeActionBack(u -> { - if(u == self()) return; - - u.aim(aimX(), aimY()); - - float offset = self() == last ? uType.headOffset : 0f; - Tmp.v1.trns(last.rotation + 180f, (uType.segmentOffset / 2f) + offset).add(last); - - float rdx = u.deltaX - last.deltaX; - float rdy = u.deltaY - last.deltaY; - - float angTo = !uType.preventDrifting || (last.deltaLen() > 0.001f && (rdx * rdx) + (rdy * rdy) > 0.00001f) ? u.angleTo(Tmp.v1) : u.rotation; - - u.rotation = angTo - (OlUtils.angleDistSigned(angTo, last.rotation, uType.angleLimit) * (1f - uType.anglePhysicsSmooth)); - u.trns(Tmp.v3.trns(u.rotation, last.deltaLen())); - Tmp.v2.trns(u.rotation, uType.segmentOffset / 2f).add(u); - - Tmp.v2.sub(Tmp.v1).scl(Mathf.clamp(uType.jointStrength * Time.delta)); - - Unit n = u; - int cast = uType.segmentCast; - while(cast > 0 && n != null){ - float scl = cast / (float)uType.segmentCast; - n.set(n.x - (Tmp.v2.x * scl), n.y - (Tmp.v2.y * scl)); - n.updateLastPosition(); - n = ((Millipedec)n).child(); - cast--; - } - - float nextHealth = (last.health() + u.health()) / 2f; - if(!Mathf.equal(nextHealth, last.health(), 0.0001f)) last.health(Mathf.lerpDelta(last.health(), nextHealth, uType.healthDistribution)); - if(!Mathf.equal(nextHealth, u.health(), 0.0001f)) u.health(Mathf.lerpDelta(u.health(), nextHealth, uType.healthDistribution)); - - Millipedec wrm = ((Millipedec)last); - float nextHealthDv = (wrm.splitHealthDiv() + u.splitHealthDiv()) / 2f; - if(!Mathf.equal(nextHealth, wrm.splitHealthDiv(), 0.0001f)) wrm.splitHealthDiv(Mathf.lerpDelta(wrm.splitHealthDiv(), nextHealthDv, uType.healthDistribution)); - if(!Mathf.equal(nextHealth, u.splitHealthDiv(), 0.0001f)) u.splitHealthDiv(Mathf.lerpDelta(u.splitHealthDiv(), nextHealthDv, uType.healthDistribution)); - last = u; - }); - scanTime += Time.delta; - if(scanTime >= 5f && uType.chainable){ - Tmp.v1.trns(rotation(), uType.segmentOffset / 2f).add(self()); - Tmp.r1.setCentered(Tmp.v1.x, Tmp.v1.y, hitSize()); - Units.nearby(Tmp.r1, u -> { - if(u.team == team && u.type == type && u instanceof Millipedec m && m.head() != self() && m.isTail() && m.countForward() + countBackward() < uType.maxSegments && m.waitTime() <= 0f && within(u, uType.segmentOffset) && OlUtils.angleDist(rotation(), angleTo(u)) < uType.angleLimit){ - connect(u); - } - }); - scanTime = 0f; - } - } - } - - @Replace - @Override - public void wobble(){ - - } - - @MethodPriority(100) - @Override - public void write(Writes write){ - write.bool(isHead()); - if(isHead()){ - Millipedec ch = (Millipedec)child; - int amount = 0; - while(ch != null){ - amount++; - ch = (Millipedec)ch.child(); - } - write.s(amount); - - ch = (Millipedec)child; - while(ch != null){ - write.b(weaponIdx); - ch.write(write); - ch = (Millipedec)ch.child(); - } - } - } -} diff --git a/src/omaloon/entities/units/MillipedeDefaultUnit.java b/src/omaloon/entities/units/MillipedeDefaultUnit.java deleted file mode 100644 index 62d3f218..00000000 --- a/src/omaloon/entities/units/MillipedeDefaultUnit.java +++ /dev/null @@ -1,499 +0,0 @@ -package omaloon.entities.units; - -import arc.graphics.g2d.*; -import arc.math.*; -import arc.math.geom.*; -import arc.util.*; -import arc.util.io.*; -import ent.anno.Annotations.*; -import mindustry.*; -import mindustry.content.*; -import mindustry.entities.*; -import mindustry.entities.abilities.*; -import mindustry.gen.*; -import mindustry.type.*; -import omaloon.type.*; -import omaloon.utils.*; - -import java.util.*; - -//@EntityPoint -public class MillipedeDefaultUnit extends UnitEntity{ - public MillipedeUnitType wormType; - public MillipedeSegmentUnit[] segmentUnits; - public float repairTime = 0f; - protected float attachTime = 4f * 60f; - protected float healthDistributionEfficiency = 1f; - protected Vec2[] segments, segmentVelocities; - protected boolean addSegments = true; - protected boolean found; - protected final Interval scanTimer = new Interval(); - protected final Vec2 lastVelocityC = new Vec2(), lastVelocityD = new Vec2(); - - public int getSegmentLength(){ - return wormType.segmentLength; - } - - @Override - public void type(UnitType type){ - super.type(type); - if(type instanceof MillipedeUnitType w) wormType = w; - else throw new ClassCastException("you set this unit's type in a sneaky way"); - } - - @Override - public void setType(UnitType type){ - super.setType(type); - if(type instanceof MillipedeUnitType w) wormType = w; - else throw new ClassCastException("you set this unit's type in a sneaky way"); - } - - protected void setEffects(){ - segmentUnits = new MillipedeSegmentUnit[wormType.segmentLength]; - segments = new Vec2[wormType.segmentLength]; - segmentVelocities = new Vec2[wormType.segmentLength]; - for(int i = 0; i < getSegmentLength(); i++){ - segments[i] = new Vec2(x, y); - segmentVelocities[i] = new Vec2(); - } - } - - @Override - public void damage(float amount){ - super.damage(amount); - healthDistributionEfficiency = Mathf.clamp(healthDistributionEfficiency - (amount / 15f)); - } - - @Override - public void update(){ - lastVelocityD.set(lastVelocityC); - lastVelocityC.set(vel); - super.update(); - healthDistributionEfficiency = Mathf.clamp(healthDistributionEfficiency + (Time.delta / 160f)); - updateSegmentVLocal(lastVelocityC); - updateSegmentsLocal(); - if(wormType.chainable && segmentUnits.length < wormType.maxSegments && scanTimer.get(15f) && attachTime >= 4f * 60f){ - scanTailSegment(); - } - attachTime += Time.delta; - if(regenAvailable()){ - if(repairTime >= wormType.regenTime){ - float damage = (health / segmentUnits.length) / 2f; - damage(damage); - for(MillipedeSegmentUnit seg : segmentUnits){ - float sDamage = (seg.segmentHealth / segmentUnits.length) / 2f; - seg.segmentDamage(sDamage); - } - addSegment(); - repairTime = 0f; - }else{ - repairTime += Time.delta; - } - } - } - - public boolean regenAvailable(){ - return wormType.splittable && (segmentUnits.length < wormType.segmentLength || segmentUnits.length < wormType.maxSegments) && wormType.regenTime > 0f; - } - - protected void updateSegmentVLocal(Vec2 vec){ - int len = getSegmentLength(); - for(int i = 0; i < len; i++){ - Vec2 seg = segments[i]; - Vec2 segV = segmentVelocities[i]; - segV.limit(type.speed); - float angleB = i != 0 ? Angles.angle(seg.x, seg.y, segments[i - 1].x, segments[i - 1].y) : Angles.angle(seg.x, seg.y, x, y); - float velocity = i != 0 ? segmentVelocities[i - 1].len() : vec.len(); - - Tmp.v1.set(vel); - Tmp.v1.add(vec); - Tmp.v1.add(lastVelocityD); - Tmp.v1.scl(1f / 3f); - - float trueVel = Math.max(Math.max(velocity, segV.len()), Tmp.v1.len()); - Tmp.v1.trns(angleB, trueVel); - segV.add(Tmp.v1); - segV.setLength(trueVel); - if(wormType.counterDrag) segV.scl(1f - drag); - segmentUnits[i].vel.set(segV); - } - for(int i = 0; i < len; i++) segmentVelocities[i].scl(Time.delta); - } - - protected void updateSegmentsLocal(){ - float segmentOffset = wormType.segmentOffset / 2f; - float angleC = OlUtils.clampedAngle(Angles.angle(segments[0].x, segments[0].y, x, y), rotation, wormType.angleLimit) + 180f; - Tmp.v1.trns(angleC, segmentOffset + wormType.headOffset); - Tmp.v1.add(x, y); - segments[0].set(Tmp.v1); - int len = getSegmentLength(); - - segments[0].add(segmentVelocities[0]); - - rotation -= OlUtils.angleDistSigned(rotation, segmentUnits[0].rotation, wormType.angleLimit) / 1.25f; - Tmp.v1.trns(rotation + 180f, segmentOffset + wormType.headOffset).add(this); - segmentUnits[0].rotation = OlUtils.clampedAngle(segments[0].angleTo(Tmp.v1), rotation, wormType.angleLimit); - Tmp.v2.trns(segmentUnits[0].rotation, segmentOffset).add(segments[0]).sub(Tmp.v1); - segments[0].sub(Tmp.v2); - - segmentVelocities[0].scl(Mathf.clamp(1f - (drag * Time.delta))); - segmentUnits[0].set(segments[0].x, segments[0].y); - segmentUnits[0].segmentUpdate(); - if(wormType.healthDistribution > 0) distributeHealth(0); - - for(int i = 1; i < len; i++){ - Vec2 seg = segments[i], segLast = segments[i - 1]; - MillipedeSegmentUnit segU = segmentUnits[i], segULast = segmentUnits[i - 1]; - - seg.add(segmentVelocities[i]); - - segULast.rotation -= OlUtils.angleDistSigned(segULast.rotation, segU.rotation, wormType.angleLimit) / 1.25f; - Tmp.v1.trns(segULast.rotation + 180f, segmentOffset).add(segLast); - segU.rotation = OlUtils.clampedAngle(segU.angleTo(Tmp.v1), segULast.rotation, wormType.angleLimit); - Tmp.v2.trns(segU.rotation, segmentOffset).add(seg).sub(Tmp.v1); - seg.sub(Tmp.v2); - - segmentVelocities[i].scl(Mathf.clamp(1f - (drag * Time.delta))); - segU.set(seg); - segU.segmentUpdate(); - if(wormType.healthDistribution > 0) distributeHealth(i); - } - for(int i = 0; i < segmentUnits.length; i++){ - Vec2 seg = segments[i]; - Vec2 segV = segmentVelocities[i]; - MillipedeSegmentUnit segU = segmentUnits[i]; - seg.add(segV); - float angleD = i == 0 ? Angles.angle(seg.x, seg.y, x, y) : Angles.angle(seg.x, seg.y, segments[i - 1].x, segments[i - 1].y); - segV.scl(Mathf.clamp(1f - drag * Time.delta)); - segU.set(seg.x, seg.y); - segU.rotation = angleD; - segU.segmentUpdate(); - if(wormType.healthDistribution > 0) distributeHealth(i); - } - } - - protected void distributeHealth(int index){ - int idx = 0; - float mHealth = 0f; - float mMaxHealth = 0f; - for(int i = -1; i < 2; i++){ - Unit seg = getSegment(i + index); - if(seg == null) break; - mHealth += seg.health; - mMaxHealth += seg.maxHealth; - idx++; - } - mMaxHealth /= idx; - mHealth /= idx; - for(int i = -1; i < 2; i++){ - Unit seg = getSegment(i + index); - if(seg == null) break; - if(seg instanceof MillipedeSegmentUnit ws){ - if(!Mathf.equal(ws.segmentHealth, mHealth, 0.001f)) ws.segmentHealth = Mathf.lerpDelta(ws.segmentHealth, mHealth, wormType.healthDistribution * healthDistributionEfficiency); - }else{ - if(!Mathf.equal(seg.health, mHealth, 0.001f)) seg.health = Mathf.lerpDelta(seg.health, mHealth, wormType.healthDistribution * healthDistributionEfficiency); - } - if(!Mathf.equal(seg.maxHealth, mMaxHealth, 0.001f)) seg.maxHealth = Mathf.lerpDelta(seg.maxHealth, mMaxHealth, wormType.healthDistribution * healthDistributionEfficiency); - } - } - - protected Unit getSegment(int index){ - if(index < 0) return this; - if(index >= segmentUnits.length) return null; - return segmentUnits[index]; - } - - /*@Override - public int classId(){ - return UnityEntityMapping.classId(WormDefaultUnit.class); - }*/ - - @Override - public float clipSize(){ - return segmentUnits.length * wormType.segmentOffset * 2f; - } - - public void drawShadow(){ - float originZ = Draw.z(); - for(int i = 0, len = segmentUnits.length; i < len; i++){ - Draw.z(originZ - (i + 1) / 10000f); - segmentUnits[i].drawShadow(); - } - Draw.z(originZ); - } - - public MillipedeSegmentUnit newSegment(){ - return new MillipedeSegmentUnit(); - } - - @Override - public void destroy(){ - if(!added) return; - super.destroy(); - for(MillipedeSegmentUnit seg : segmentUnits){ - float explosiveness = 2f + seg.item().explosiveness * stack().amount * 1.53f; - float flammability = seg.item().flammability * seg.stack().amount / 1.9f; - float power = seg.item().charge * seg.stack().amount * 150f; - - if(!spawnedByCore){ - Damage.dynamicExplosion(seg.x, seg.y, flammability, explosiveness, power, bounds() / 2f, Vars.state.rules.damageExplosions, item().flammability > 1, team); - } - - float shake = hitSize / 3f; - - Effect.scorch(seg.x, seg.y, (int)(hitSize / 5)); - Fx.explosion.at(seg); - Effect.shake(shake, shake, seg); - type.deathSound.at(seg); - - if(type.flying && !spawnedByCore){ - Damage.damage(team, seg.x, seg.y, Mathf.pow(seg.hitSize, 0.94f) * 1.25f, Mathf.pow(seg.hitSize, 0.75f) * type.crashDamageMultiplier * 5f, true, false, true); - } - - if(!Vars.headless){ - for(int i = 0; i < type.wreckRegions.length; i++){ - if(type.wreckRegions[i].found()){ - float range = type.hitSize / 4f; - Tmp.v1.rnd(range); - Effect.decal(type.wreckRegions[i], seg.x + Tmp.v1.x, seg.y + Tmp.v1.y, seg.rotation - 90); - } - } - } - } - } - - @Override - public void remove(){ - if(!added) return; - super.remove(); - for(MillipedeSegmentUnit segmentUnit : segmentUnits){ - segmentUnit.remove(); - } - } - - protected void superRemove(){ - super.remove(); - } - - @Override - public int count(){ - return Math.max(super.count() / Math.max(wormType.segmentLength, wormType.maxSegments), 1); - } - - protected void scanTailSegment(){ - Tmp.v1.trns(rotation, wormType.segmentOffset).add(this); - float size = wormType.hitSize / 2f; - found = false; - Units.nearby(team, Tmp.v1.x - size, Tmp.v1.y - size, size * 2f, size * 2f, e -> { - if(found) return; - if(e instanceof MillipedeSegmentUnit ms && ms.segmentType == 1 && ms.millipedeType == wormType && ms.trueParentUnit != this && within(ms, (wormType.segmentOffset) + 5f) && Angles.within(angleTo(e), e.rotation, wormType.angleLimit + 2f)){ - if(ms.trueParentUnit == null || ms.trueParentUnit.segmentUnits.length > wormType.maxSegments) return; - wormType.chainSound.at(this, Mathf.random(0.9f, 1.1f)); - MillipedeSegmentUnit head = newSegment(); - head.setType(wormType); - head.set(this); - head.rotation = rotation; - head.vel.set(vel); - head.team = team; - head.maxHealth = maxHealth; - head.health = head.segmentHealth = health; - head.segmentType = 0; - segmentUnits[0].parentUnit = head; - head.add(); - superRemove(); - - MillipedeSegmentUnit.SegmentData data = new MillipedeSegmentUnit.SegmentData(segmentUnits.length + 1); - data.add(head, head.vel); - - for(int i = 0; i < segmentUnits.length; i++){ - data.add(this, i); - } - for(int i = 0; i < data.size; i++){ - ms.trueParentUnit.addSegment(data.units[i], data.pos[i], data.vel[i]); - } - found = true; - } - }); - } - - protected void removeTail(){ - int index = segments.length - 1; - if(index <= 0) return; - - segmentUnits[index].remove(); - segmentUnits[index] = null; - segmentUnits[index - 1].segmentType = 1; - - segmentUnits = Arrays.copyOf(segmentUnits, segmentUnits.length - 1); - segments = Arrays.copyOf(segments, segments.length - 1); - segmentVelocities = Arrays.copyOf(segmentVelocities, segmentVelocities.length - 1); - } - - public void addSegment(MillipedeSegmentUnit unit, Vec2 pos, Vec2 vel){ - int index = segments.length; - Unit parent = segmentUnits[index - 1]; - segmentUnits[index - 1].segmentType = 0; - segmentUnits = Arrays.copyOf(segmentUnits, segmentUnits.length + 1); - segments = Arrays.copyOf(segments, segments.length + 1); - segmentVelocities = Arrays.copyOf(segmentVelocities, segmentVelocities.length + 1); - - unit.elevation = elevation; - unit.segmentType = 1; - unit.parentUnit = parent; - unit.trueParentUnit = this; - - segmentUnits[segmentUnits.length - 1] = unit; - segments[segments.length - 1] = pos; - segmentVelocities[segmentVelocities.length - 1] = vel; - } - - public void addSegment(){ - int index = segments.length; - Unit parent = segmentUnits[index - 1]; - Tmp.v1.trns(segmentUnits[index - 1].rotation + 180f, wormType.segmentOffset).add(segmentUnits[index - 1]); - segmentUnits[index - 1].segmentType = 0; - segmentUnits = Arrays.copyOf(segmentUnits, segmentUnits.length + 1); - segments = Arrays.copyOf(segments, segments.length + 1); - segmentVelocities = Arrays.copyOf(segmentVelocities, segmentVelocities.length + 1); - - MillipedeSegmentUnit segment = newSegment(); - segment.elevation = elevation; - segment.segmentType = 1; - segment.setType(type); - segment.parentUnit = parent; - segment.trueParentUnit = this; - segment.set(Tmp.v1); - segment.team = team; - segment.health = health; - segment.maxHealth = maxHealth; - segment.segmentHealth = health; - segment.dead = false; - segment.add(); - segmentUnits[segmentUnits.length - 1] = segment; - segments[segments.length - 1] = new Vec2(Tmp.v1); - segmentVelocities[segmentVelocities.length - 1] = new Vec2(segmentVelocities[segmentVelocities.length - 2]); - } - - @Override - public void add(){ - if(added) return; - super.add(); - if(!addSegments){ - postAdd(); - return; - } - setEffects(); - Unit parent = this; - for(int i = 0, len = getSegmentLength(); i < len; i++){ - int typeS = i == len - 1 ? 1 : 0; - segments[i].set(x, y); - MillipedeSegmentUnit temp = newSegment(); - - temp.elevation = elevation; - temp.setSegmentType(typeS); - temp.type(type); - temp.resetController(); - temp.team = team; - temp.setTrueParent(this); - temp.setParent(parent); - temp.add(); - temp.afterSync(); - temp.heal(); - parent = temp; - segmentUnits[i] = temp; - } - } - - void postAdd(){ - for(MillipedeSegmentUnit ms : segmentUnits){ - ms.add(); - } - } - - @Override - public void read(Reads read){ - super.read(read); - addSegments = false; - int length = read.s(); - boolean splittable = read.bool(); - repairTime = read.f(); - - segmentUnits = new MillipedeSegmentUnit[length]; - segments = new Vec2[length]; - segmentVelocities = new Vec2[length]; - - Unit parent = this; - for(int i = 0; i < length; i++){ - segments[i] = new Vec2(); - segmentVelocities[i] = new Vec2(); - MillipedeSegmentUnit temp = newSegment(); - temp.elevation = elevation; - temp.type(type); - temp.team = team; - temp.drag = type.drag; - temp.armor = type.armor; - temp.hitSize = type.hitSize; - temp.hovering = type.hovering; - temp.setupWeapons(type); - temp.resetController(); - temp.abilities = type.abilities.toArray(Ability.class); - temp.setTrueParent(this); - temp.setParent(parent); - - temp.x = segments[i].x = read.f(); - temp.y = segments[i].y = read.f(); - temp.rotation = read.f(); - temp.segmentType = read.b(); - if(splittable){ - temp.segmentHealth = temp.health = read.f(); - temp.maxHealth = read.f(); - } - - parent = temp; - segmentUnits[i] = temp; - } - } - - @Override - public void write(Writes write){ - super.write(write); - - write.s(segmentUnits.length); - write.bool(wormType.splittable); - write.f(repairTime); - - for(int i = 0; i < segmentUnits.length; i++){ - write.f(segments[i].x); - write.f(segments[i].y); - write.f(segmentUnits[i].rotation); - write.b(segmentUnits[i].segmentType); - if(wormType.splittable){ - write.f(segmentUnits[i].segmentHealth); - write.f(segmentUnits[i].maxHealth); - } - } - } - - /* seems uselss because multiple setStats() does nothing at end. - @Override - public void read(Reads read){ - super.read(read); - for(int i = 0, len = getSegmentLength(); i < len; i++){ - segments[i].x = read.f(); - segments[i].y = read.f(); - } - } - - @Override - public void write(Writes write){ - super.write(write); - for(int i = 0, len = getSegmentLength(); i < len; i++){ - write.f(segments[i].x); - write.f(segments[i].y); - } - }*/ - - public void handleCollision(Hitboxc originUnit, Hitboxc other, float x, float y){ - - } -} diff --git a/src/omaloon/entities/units/MillipedeSegmentUnit.java b/src/omaloon/entities/units/MillipedeSegmentUnit.java deleted file mode 100644 index c8f04155..00000000 --- a/src/omaloon/entities/units/MillipedeSegmentUnit.java +++ /dev/null @@ -1,448 +0,0 @@ -package omaloon.entities.units; - -import arc.graphics.*; -import arc.graphics.g2d.*; -import arc.math.*; -import arc.math.geom.*; -import arc.struct.*; -import arc.util.*; -import ent.anno.Annotations.*; -import mindustry.audio.*; -import mindustry.entities.*; -import mindustry.entities.bullet.*; -import mindustry.entities.units.*; -import mindustry.gen.*; -import mindustry.graphics.*; -import mindustry.type.*; -import omaloon.type.*; -import omaloon.utils.*; - -import static arc.Core.*; -import static mindustry.Vars.*; - -//@EntityPoint -public class MillipedeSegmentUnit extends UnitEntity{ - public MillipedeUnitType millipedeType; - protected float segmentHealth; - protected MillipedeDefaultUnit trueParentUnit; - protected Unit parentUnit; - protected boolean isBugged; - protected int shootSequence, segmentType; - - public int getSegmentLength(){ - return millipedeType.segmentLength; - } - - @Override - public void type(UnitType type){ - super.type(type); - if(type instanceof MillipedeUnitType m) millipedeType = m; - else throw new ClassCastException("you set this unit's type a in sneaky way"); - } - - @Override - public boolean collides(Hitboxc other){ - if(trueParentUnit == null) return true; - MillipedeSegmentUnit[] segs = trueParentUnit.segmentUnits; - for(int i = 0, len = getSegmentLength(); i < len; i++){ - if(segs[i] == other) return false; - } - return true; - } - - @Override - public void add(){ - if(added) return; - isBugged = true; - Groups.all.add(this); - Groups.unit.add(this); - Groups.sync.add(this); - Groups.draw.add(this); - added = true; - updateLastPosition(); - } - - @Override - public void setType(UnitType type){ - this.type = type; - maxHealth = segmentHealth = type.health; - drag = type.drag; - armor = type.armor; - hitSize = type.hitSize; - hovering = type.hovering; - - if(controller == null) controller(type.createController(self())); - if(mounts().length != type.weapons.size) setupWeapons(type); - if(type instanceof MillipedeUnitType m) millipedeType = m; - else throw new ClassCastException("you set this unit's type in sneaky way"); - } - - @Override - public void remove(){ - if(!added) return; - Groups.all.remove(this); - Groups.unit.remove(this); - Groups.sync.remove(this); - Groups.draw.remove(this); - added = false; - controller.removed(this); - if(net.client()) netClient.addRemovedEntity(id); - } - - @Override - public void damage(float amount){ - if(millipedeType.splittable) segmentHealth -= amount * millipedeType.segmentDamageScl; - trueParentUnit.damage(amount); - /*if(trueParentUnit.controller instanceof MillipedeAI){ - ((MillipedeAI)trueParentUnit.controller).setTarget(x, y, amount); - }*/ - } - - public void segmentDamage(float amount){ - segmentHealth -= amount; - } - - @Override - public void controller(UnitController next){ - if(!(next instanceof Player)){ - controller = next; - if(controller.unit() != this) controller.unit(this); - }else if(trueParentUnit != null){ - trueParentUnit.controller(next); - if(trueParentUnit.controller().unit() != trueParentUnit) trueParentUnit.controller().unit(trueParentUnit); - } - } - - @Override - public boolean isPlayer(){ - if(trueParentUnit == null) return false; - return trueParentUnit.controller() instanceof Player; - } - - @Override - public boolean isAI(){ - if(trueParentUnit == null) return true; - return trueParentUnit.controller() instanceof AIController; - } - - @Override - public Player getPlayer(){ - if(trueParentUnit == null) return null; - return isPlayer() ? (Player)trueParentUnit.controller() : null; - } - - /*@Override - public int classId(){ - return OlEntityMapping.classId(MillipedeSegmentUnit.class); - }*/ - - @Override - public void heal(float amount){ - if(trueParentUnit != null) trueParentUnit.heal(amount); - health += amount; - segmentHealth = Mathf.clamp(segmentHealth + amount, 0f, maxHealth); - clampHealth(); - } - - @Override - public void kill(){ - if(dead || net.client()) return; - if(trueParentUnit != null) Call.unitDeath(trueParentUnit.id); - Call.unitDeath(id); - } - - public void setSegmentType(int val){ - segmentType = val; - } - - @Override - public void setupWeapons(UnitType def){ - if(!(def instanceof MillipedeUnitType w)) super.setupWeapons(def); - else{ - Seq tmpSeq = new Seq<>(); - Seq originSeq = w.segWeapSeq; - for(int i = 0; i < originSeq.size; i++) tmpSeq.add(new WeaponMount(originSeq.get(i))); - mounts = tmpSeq.toArray(WeaponMount.class); - } - } - - @Override - public boolean serialize(){ - return false; - } - - @Override - public void update(){ - if(parentUnit == null || parentUnit.dead || !parentUnit.isAdded()){ - dead = true; - remove(); - } - if(trueParentUnit != null && isBugged){ - if(!Structs.contains(trueParentUnit.segmentUnits, s -> s == this)) remove(); - else isBugged = false; - } - } - - public void segmentUpdate(){ - if(trueParentUnit != null){ - if(millipedeType.splittable && millipedeType.healthDistribution <= 0f) maxHealth = trueParentUnit.maxHealth; - if(!millipedeType.splittable){ - health = trueParentUnit.health; - }else{ - if(segmentHealth > maxHealth) segmentHealth = maxHealth; - health = segmentHealth; - } - hitTime = trueParentUnit.hitTime; - ammo = trueParentUnit.ammo; - }else{ - return; - } - if(millipedeType.splittable && segmentHealth <= 0f){ - split(); - } - if(team != trueParentUnit.team) team = trueParentUnit.team; - if(!net.client() && !dead && controller != null) controller.updateUnit(); - if(controller == null || !controller.isValidController()) resetController(); - updateWeapon(); - updateStatus(); - } - - //probably inefficient - protected void split(){ - int index = 0; - MillipedeDefaultUnit hd = trueParentUnit; - hd.maxHealth /= 2f; - hd.health = Math.min(hd.health, hd.maxHealth); - for(int i = 0; i < hd.segmentUnits.length; i++){ - if(hd.segmentUnits[i] == this){ - index = i; - break; - } - } - if(index >= hd.segmentUnits.length - 1) trueParentUnit.removeTail(); - if(index <= 0 || index >= hd.segmentUnits.length - 1){ - return; - } - hd.segmentUnits[index - 1].segmentType = 1; - MillipedeDefaultUnit newHead = (MillipedeDefaultUnit)type.create(team); - hd.segmentUnits[index + 1].parentUnit = newHead; - newHead.addSegments = false; - newHead.attachTime = 0f; - newHead.set(this); - newHead.vel.set(vel); - newHead.maxHealth /= 2f; - newHead.health /= 2f; - newHead.rotation = rotation; - - SegmentData oldSeg = new SegmentData(hd.segmentUnits.length), newSeg = new SegmentData(hd.segmentUnits.length); - for(int i = 0; i < hd.segmentUnits.length; i++){ - hd.segmentUnits[i].maxHealth /= 2f; - hd.segmentUnits[i].clampHealth(); - if(i < index){ - oldSeg.add(hd, i); - } - if(i > index){ - newSeg.add(hd, i); - } - } - oldSeg.set(hd); - newSeg.set(newHead); - newHead.add(); - millipedeType.splitSound.at(x, y, Mathf.random(0.9f, 1.1f)); - remove(); - } - - protected void updateStatus(){ - if(trueParentUnit == null || trueParentUnit.dead) return; - if(!statuses.isEmpty()) statuses.each(s -> trueParentUnit.apply(s.effect, s.time)); - statuses.clear(); - } - - protected void updateWeapon(){ - boolean can = canShoot(); - for(WeaponMount mount : mounts){ - Weapon weapon = mount.weapon; - mount.reload = Math.max(mount.reload - Time.delta * reloadMultiplier, 0); - float weaponRotation = this.rotation - 90 + (weapon.rotate ? mount.rotation : 0); - float mountX = this.x + Angles.trnsx(this.rotation - 90, weapon.x, weapon.y); - float mountY = this.y + Angles.trnsy(this.rotation - 90, weapon.x, weapon.y); - float shootX = mountX + Angles.trnsx(weaponRotation, weapon.shootX, weapon.shootY); - float shootY = mountY + Angles.trnsy(weaponRotation, weapon.shootX, weapon.shootY); - float shootAngle = weapon.rotate ? weaponRotation + 90 : Angles.angle(shootX, shootY, mount.aimX, mount.aimY) + (this.rotation - angleTo(mount.aimX, mount.aimY)); - if(weapon.continuous && mount.bullet != null){ - if(!mount.bullet.isAdded() || mount.bullet.time >= mount.bullet.lifetime || mount.bullet.type != weapon.bullet){ - mount.bullet = null; - }else{ - mount.bullet.rotation(weaponRotation + 90); - mount.bullet.set(shootX, shootY); - mount.reload = weapon.reload; - vel.add(Tmp.v1.trns(rotation + 180.0F, mount.bullet.type.recoil)); - if(weapon.shootSound != Sounds.none && !headless){ - if(mount.sound == null) mount.sound = new SoundLoop(weapon.shootSound, 1.0F); - mount.sound.update(x, y, true); - } - } - }else{ - mount.heat = Math.max(mount.heat - Time.delta * reloadMultiplier / mount.weapon.cooldownTime, 0); - if(mount.sound != null){ - mount.sound.update(x, y, false); - } - } - if(weapon.otherSide != -1 && weapon.alternate && mount.side == weapon.flipSprite && mount.reload + Time.delta > weapon.reload / 2.0F && mount.reload <= weapon.reload / 2.0F){ - mounts[weapon.otherSide].side = !mounts[weapon.otherSide].side; - mount.side = !mount.side; - } - if(weapon.rotate && (mount.rotate || mount.shoot) && can){ - float axisX = this.x + Angles.trnsx(this.rotation - 90, weapon.x, weapon.y); - float axisY = this.y + Angles.trnsy(this.rotation - 90, weapon.x, weapon.y); - mount.targetRotation = Angles.angle(axisX, axisY, mount.aimX, mount.aimY) - this.rotation; - mount.rotation = Angles.moveToward(mount.rotation, mount.targetRotation, weapon.rotateSpeed * Time.delta); - }else if(!weapon.rotate){ - mount.rotation = 0; - mount.targetRotation = angleTo(mount.aimX, mount.aimY); - } - if(mount.shoot && can && (ammo > 0 || !state.rules.unitAmmo || team().rules().infiniteAmmo) && (!weapon.alternate || mount.side == weapon.flipSprite) && (vel.len() >= mount.weapon.minShootVelocity || (net.active() && !isLocal())) && mount.reload <= 1.0E-4F && Angles.within(weapon.rotate ? mount.rotation : this.rotation, mount.targetRotation, mount.weapon.shootCone)){ - shoot(mount, shootX, shootY, mount.aimX, mount.aimY, mountX, mountY, shootAngle, Mathf.sign(weapon.x)); - mount.reload = weapon.reload; - ammo--; - if(ammo < 0) ammo = 0; - } - } - } - - protected void shoot(WeaponMount mount, float x, float y, float aimX, float aimY, float mountX, - float mountY, float rotation, int side){ - Weapon weapon = mount.weapon; - float baseX = this.x; - float baseY = this.y; - boolean delay = weapon.shoot.firstShotDelay + weapon.shoot.shotDelay > 0f; - (delay ? weapon.chargeSound : weapon.continuous ? Sounds.none : weapon.shootSound).at(x, y, Mathf.random(weapon.soundPitchMin, weapon.soundPitchMax)); - BulletType ammo = weapon.bullet; - float lifeScl = ammo.keepVelocity ? Mathf.clamp(Mathf.dst(x, y, aimX, aimY) / ammo.range) : 1f; - final float[] sequenceNum = {0}; - if(delay){ - OlUtils.shotgun(weapon.shoot.shots, weapon.reload, rotation, (f)->{ - Time.run(sequenceNum[0] * weapon.shoot.shotDelay + weapon.shoot.firstShotDelay, ()->{ - if(!isAdded()) return; - mount.bullet = bullet(weapon, x + this.x - baseX, y + this.y - baseY, f + Mathf.range(weapon.inaccuracy), lifeScl); - }); - sequenceNum[0]++; - }); - } else { - OlUtils.shotgun(weapon.shoot.shots, weapon.reload, rotation, f -> mount.bullet = bullet(weapon, x, y, f + Mathf.range(weapon.inaccuracy), lifeScl)); - } - boolean parentize = ammo.keepVelocity; - if(delay){ - Time.run(weapon.shoot.firstShotDelay, () -> { - if(!isAdded()) return; - vel.add(Tmp.v1.trns(rotation + 180f, ammo.recoil)); - Effect.shake(weapon.shake, weapon.shake, x, y); - mount.heat = 1f; - if(!weapon.continuous){ - weapon.shootSound.at(x, y, Mathf.random(weapon.soundPitchMin, weapon.soundPitchMax)); - } - }); - }else{ - vel.add(Tmp.v1.trns(rotation + 180f, ammo.recoil)); - Effect.shake(weapon.shake, weapon.shake, x, y); - mount.heat = 1f; - } - weapon.ejectEffect.at(mountX, mountY, rotation * side); - ammo.shootEffect.at(x, y, rotation, parentize ? this : null); - ammo.smokeEffect.at(x, y, rotation, parentize ? this : null); - apply(weapon.shootStatus, weapon.shootStatusDuration); - } - - protected Bullet bullet(Weapon weapon, float x, float y, float angle, float lifescl){ - return weapon.bullet.create(this, this.team, x, y, angle, 1.0f - weapon.velocityRnd + Mathf.random(weapon.velocityRnd), lifescl); - } - - public void drawBody(){ - float z = Draw.z(); - type.applyColor(this); - TextureRegion region = segmentType == 0 ? millipedeType.segmentRegion : millipedeType.tailRegion; - Draw.rect(region, this, rotation - 90); - TextureRegion segCellReg = millipedeType.segmentCellRegion; - if(segmentType == 0 && segCellReg != atlas.find("error")) drawCell(segCellReg); - TextureRegion outline = millipedeType.segmentOutline == null || millipedeType.tailOutline == null ? null : segmentType == 0 ? millipedeType.segmentOutline : millipedeType.tailOutline; - if(outline != null){ - Draw.color(Color.white); - Draw.z(Draw.z()); - Draw.rect(outline, this, rotation - 90f); - Draw.z(z); - } - Draw.reset(); - } - - public void drawCell(TextureRegion cellRegion){ - Draw.color(type.cellColor(this)); - Draw.rect(cellRegion, x, y, rotation - 90f); - } - - public void drawShadow(){ - TextureRegion region = segmentType == 0 ? millipedeType.segmentRegion : millipedeType.tailRegion; - Draw.color(Pal.shadow); //seems to not exist in v106 - float e = Math.max(elevation, type.shadowElevation); - Draw.rect(region, x + (UnitType.shadowTX * e), y + UnitType.shadowTY * e, rotation - 90f); - Draw.color(); - } - - @Override - public void draw(){ - - } - - @Override - public void collision(Hitboxc other, float x, float y){ - super.collision(other, x, y); - if(trueParentUnit != null) trueParentUnit.handleCollision(this, other, x, y); - } - - protected void setTrueParent(MillipedeDefaultUnit parent){ - shootSequence = 0; - trueParentUnit = parent; - } - - public void setParent(Unit parent){ - parentUnit = parent; - } - - protected static class SegmentData{ - MillipedeSegmentUnit[] units; - Vec2[] pos; - Vec2[] vel; - int size = 0; - - SegmentData(int size){ - units = new MillipedeSegmentUnit[size]; - pos = new Vec2[size]; - vel = new Vec2[size]; - } - - void add(MillipedeSegmentUnit unit, Vec2 vel){ - units[size] = unit; - pos[size] = new Vec2(unit.getX(), unit.getY()); - this.vel[size++] = vel; - } - - void add(MillipedeDefaultUnit unit, int index){ - Log.info(toString() + ":" + unit.segmentUnits[index] + ":" + unit.segments[index] + ":" + unit.segmentVelocities[index] + ":" + index); - units[size] = unit.segmentUnits[index]; - pos[size] = unit.segments[index]; - vel[size++] = unit.segmentVelocities[index]; - } - - void set(MillipedeDefaultUnit unit){ - for(MillipedeSegmentUnit seg : units){ - if(seg == null) break; - seg.trueParentUnit = unit; - } - unit.segmentUnits = new MillipedeSegmentUnit[size]; - unit.segments = new Vec2[size]; - unit.segmentVelocities = new Vec2[size]; - System.arraycopy(units, 0, unit.segmentUnits, 0, size); - System.arraycopy(pos, 0, unit.segments, 0, size); - System.arraycopy(vel, 0, unit.segmentVelocities, 0, size); - } - } -} \ No newline at end of file diff --git a/src/omaloon/type/MillipedeUnitType.java b/src/omaloon/type/MillipedeUnitType.java index 13c3bc8d..a114ea73 100644 --- a/src/omaloon/type/MillipedeUnitType.java +++ b/src/omaloon/type/MillipedeUnitType.java @@ -1,29 +1,25 @@ package omaloon.type; import arc.audio.*; +import arc.func.*; import arc.graphics.g2d.*; import arc.math.*; import arc.math.geom.*; import arc.struct.*; import arc.util.*; -import mindustry.ctype.*; import mindustry.entities.abilities.*; import mindustry.entities.units.*; import mindustry.game.*; import mindustry.gen.*; import mindustry.graphics.*; import mindustry.type.*; -import omaloon.entities.units.*; import omaloon.gen.*; import static arc.Core.*; -import static mindustry.Vars.*; public class MillipedeUnitType extends GlassmoreUnitType { - public final Seq segWeapSeq = new Seq<>(); - public TextureRegion segmentRegion, tailRegion, segmentCellRegion, tailCellRegion, - segmentOutline, tailOutline, payloadCellRegion; + segmentOutline, tailOutline; public Seq bottomWeapons = new Seq<>(); //Millipedes /** @@ -31,47 +27,69 @@ public class MillipedeUnitType extends GlassmoreUnitType { */ public MillipedeDecal millipedeDecal; + /** + * Min amount of segments required for this chain, any less and everything dies. + */ + public int minSegments = 3; + // TODO rename + /** + * Max amount of segments that this chain can grow to. + */ public int segmentLength = 9; - public int maxSegments = -1; + /** + * Max amount of segments that this chain can be. Will not chain if total amount of the resulting chain is bigger. + */ + public int maxSegments = 18; + + /** + * Offset between each segment of the chain. + */ + public float segmentOffset = -1f; + /** + * Max difference of angle that one segment can be from the parent. + */ + public float angleLimit = 30f; + + /** + * Time taken for a new segment to grow. If -1 it will not grow. + */ + public float regenTime = -1f; + /** + * Time taken for 2 chains to connect to each-other. If -1 will now connect. + */ + public float chainTime = -1f; + + /** + * Sound played when growing/chaining. + */ + public Sound chainSound = Sounds.door; + + /** + * Sound played when splitting. Splittable must be true. + */ + public Sound splitSound = Sounds.door; + + /** + * If true, this unit can split when one of it's segments die. If applicable. + */ + public boolean splittable = false; + //Should reduce the "Whip" effect. public int segmentCast = 4; - public float segmentOffset = 23f, headOffset = 0f; - public float angleLimit = 30f; - public float regenTime = -1f, healthDistribution = 0.1f; public float segmentDamageScl = 6f; - public float anglePhysicsSmooth = 0f; - public float jointStrength = 1f; - // Hopefully make segment movement more consistent - public boolean counterDrag = false; - // Attempt to prevent angle drifting due to the inaccurate Atan2 - public boolean preventDrifting = false; - public boolean splittable = false, chainable = false; - public Sound splitSound = Sounds.door, chainSound = Sounds.door; - //Millipede rendering - private final static Rect viewport = new Rect(), viewport2 = new Rect(); - private final static int chunks = 4; public float segmentLayerOffset = 0f; - protected boolean immuneAll = false; - - public int headLegCount = 2, segmentLegCount = 2, tailLegCount = 2; - //Legs extra protected static Vec2 legOffsetB = new Vec2(); - /** - * Weapons for each segment. - * The Last item of the array will be repeated if the unit is too big - */ - public Seq[] segmentWeapons; - public boolean tailHasWeapon = false; - public boolean headHasWeapon = false; + public final Seq> chainWeapons = new Seq<>(); + public Intf weaponsIndex = unit -> { + if (unit instanceof Chainedc chain) return chain.countForward(); + else return 0; + }; public MillipedeUnitType(String name) { super(name); - //controller = u -> new MillipedeAI(); - // outlandish legCount should be different from any amount of legs this unit can have - // legCount = 3; } @Override @@ -91,35 +109,19 @@ public void load() { segmentOutline = atlas.find(name + "-segment-outline"); tailOutline = atlas.find(name + "-tail-outline"); - for (Seq segmentWeapon : segmentWeapons) { - segmentWeapon.each(Weapon::load); - } + chainWeapons.each(w -> w.each(Weapon::load)); } @Override public void init() { super.init(); - if(segmentWeapons == null){ - sortSegWeapons(segWeapSeq); - segmentWeapons = new Seq[]{segWeapSeq}; - }else{ - for(Seq seq : segmentWeapons){ - sortSegWeapons(seq); - } - } - - Seq addBottoms = new Seq<>(); - for(Weapon w : weapons){ - if(bottomWeapons.contains(w) && w.otherSide != -1){ - addBottoms.add(weapons.get(w.otherSide)); - } - } - bottomWeapons.addAll(addBottoms.distinct()); + if (segmentOffset < 0) segmentOffset = hitSize * 2f; - if(immuneAll){ - immunities.addAll(content.getBy(ContentType.status)); - } + chainWeapons.each(w -> { + sortSegWeapons(w); + w.each(Weapon::init); + }); } public void sortSegWeapons(Seq weaponSeq){ @@ -150,9 +152,9 @@ public void sortSegWeapons(Seq weaponSeq){ weaponSeq.set(mapped); } - public void drawWorm(T unit){ + public void drawWorm(T unit){ Mechc mech = unit instanceof Mechc ? (Mechc)unit : null; - float z = (unit.elevation > 0.5f ? (lowAltitude ? Layer.flyingUnitLow : Layer.flyingUnit) : groundLayer + Mathf.clamp(hitSize / 4000f, 0, 0.01f)) - (unit.layer() * 0.00001f); + float z = (unit.elevation > 0.5f ? (lowAltitude ? Layer.flyingUnitLow : Layer.flyingUnit) : groundLayer + Mathf.clamp(hitSize / 4000f, 0, 0.01f)) + (unit.countForward() * segmentLayerOffset); if(unit.isFlying() || shadowElevation > 0){ TextureRegion tmpShadow = shadowRegion; @@ -177,7 +179,7 @@ public void drawWorm(T unit){ unit.trns(legOffsetB.x, legOffsetB.y); } - drawLegs((Unit & Legsc) unit); + if (unit instanceof Legsc) drawLegs((Unit & Legsc) unit); Draw.z(Math.min(z - 0.01f, Layer.groundUnit - 1f)); @@ -202,8 +204,8 @@ public void drawWorm(T unit){ if(unit.isTail()){ Draw.draw(z + 0.01f, () -> { Tmp.v1.trns(unit.rotation + 180f, segmentOffset).add(unit); - Drawf.construct(Tmp.v1.x, Tmp.v1.y, tailRegion, unit.rotation - 90f, unit.regenTime() / regenTime, unit.regenTime() / regenTime, Time.time); - Drawf.construct(unit.x, unit.y, segmentRegion, unit.rotation - 90f, unit.regenTime() / regenTime, unit.regenTime() / regenTime, Time.time); + Drawf.construct(Tmp.v1.x, Tmp.v1.y, tailRegion, unit.rotation - 90f, unit.growTime() / regenTime, unit.growTime() / regenTime, Time.time); + Drawf.construct(unit.x, unit.y, segmentRegion, unit.rotation - 90f, unit.growTime() / regenTime, unit.growTime() / regenTime, Time.time); }); } @@ -239,91 +241,13 @@ public void drawWorm(T unit){ @Override public void draw(Unit unit){ - if (unit instanceof Millipedec m && !m.isHead()) { - drawWorm((Unit & Millipedec) m); + if (unit instanceof Chainedc m && !m.isHead()) { + drawWorm((Unit & Chainedc) m); } else { super.draw(unit); } } - /*@Override - public void drawCell(Unit unit) { - if(unit.isAdded()){ - super.drawCell(unit); - }else{ - applyColor(unit); - - Draw.color(cellColor(unit)); - Draw.rect(payloadCellRegion, unit.x, unit.y, unit.rotation - 90); - Draw.reset(); - } - } - - @Override - public void drawShadow(Unit unit){ - super.drawShadow(unit); - if(unit instanceof MillipedeDefaultUnit millipedeUnit) millipedeUnit.drawShadow(); - } - - @Override - public void drawSoftShadow(Unit unit){ - //worm - if(!(unit instanceof MillipedeDefaultUnit millipedeUnit)) return; - for(MillipedeSegmentUnit s : millipedeUnit.segmentUnits){ - millipedeUnit.type.drawSoftShadow(s); - } - float z = Draw.z(); - for(int i = 0; i < millipedeUnit.segmentUnits.length; i++){ - Draw.z(z - (i + 1.1f) / 10000f); - millipedeUnit.type.drawSoftShadow(millipedeUnit.segmentUnits[i]); - } - Draw.z(z); - }*/ - - @Override - public void drawOutline(Unit unit) { - super.drawOutline(unit); - } - - @Override - public void drawBody(Unit unit) { - float z = Draw.z(); - if(unit instanceof MillipedeDefaultUnit millipedeUnit){ - camera.bounds(viewport); - int index = -chunks; - for(int i = 0; i < millipedeUnit.segmentUnits.length; i++){ - if(i >= index + chunks){ - index = i; - Unit seg = millipedeUnit.segmentUnits[index]; - Unit segN = millipedeUnit.segmentUnits[Math.min(index + chunks, millipedeUnit.segmentUnits.length - 1)]; - float grow = millipedeUnit.regenAvailable() && (index + chunks) >= millipedeUnit.segmentUnits.length - 1 ? seg.clipSize() : 0f; - Tmp.r3.setCentered(segN.x, segN.y, segN.clipSize()); - viewport2.setCentered(seg.x, seg.y, seg.clipSize()).merge(Tmp.r3).grow(grow + (seg.clipSize() / 2f)); - } - if(viewport.overlaps(viewport2)){ - Draw.z(z - (i + 1f) / 10000f); - if(millipedeUnit.regenAvailable() && i == millipedeUnit.segmentUnits.length - 1){ - int finalI = i; - Draw.draw(z - (i + 2f) / 10000f, () -> { - Tmp.v1.trns(millipedeUnit.segmentUnits[finalI].rotation + 180f, segmentOffset).add(millipedeUnit.segmentUnits[finalI]); - Drawf.construct(Tmp.v1.x, Tmp.v1.y, tailRegion, millipedeUnit.segmentUnits[finalI].rotation - 90f, millipedeUnit.repairTime / regenTime, 1f, millipedeUnit.repairTime); - }); - } - millipedeUnit.segmentUnits[i].drawBody(); - drawWeapons(millipedeUnit.segmentUnits[i]); - } - } - }else{ - applyColor(unit); - - Draw.rect(region, unit.x, unit.y, unit.rotation - 90); - - Draw.reset(); - } - - Draw.z(z); - } - @Override public void drawWeapons(Unit unit){ float z = Draw.z(); @@ -342,7 +266,6 @@ public void drawWeapons(Unit unit){ @Override public boolean hasWeapons() { - for (Seq segmentWeapon : segmentWeapons) if (!segmentWeapon.isEmpty()) return true; - return false; + return chainWeapons.contains(w -> !w.isEmpty()); } } From d4a6a9780019ab5ee88119457efcc994132cb06a Mon Sep 17 00:00:00 2001 From: Zelaux <58040045+zelaux@users.noreply.github.com> Date: Fri, 7 Feb 2025 01:33:56 +0300 Subject: [PATCH 65/67] After merge fixes --- .../world/blocks/defense/BlastTower.java | 84 ++++++------------- .../blocks/liquid/PressureLiquidBridge.java | 3 +- .../blocks/liquid/PressureLiquidPump.java | 2 +- .../blocks/liquid/PressureLiquidValve.java | 8 -- .../blocks/sandbox/PressureLiquidSource.java | 4 +- 5 files changed, 32 insertions(+), 69 deletions(-) diff --git a/src/omaloon/world/blocks/defense/BlastTower.java b/src/omaloon/world/blocks/defense/BlastTower.java index da72fc29..794fd92c 100644 --- a/src/omaloon/world/blocks/defense/BlastTower.java +++ b/src/omaloon/world/blocks/defense/BlastTower.java @@ -157,67 +157,37 @@ public void shoot() { smoothProgress = 0f; } - @Override - public void updateTile() { - AutoImplement.Util.Inject(HasPressureImpl.class); - super.updateTile(); - targets.clear(); - Units.nearbyEnemies(team, x, y, range, u -> { - if(u.checkTarget(targetAir, targetGround)) { - targets.add(u); - } - }); - - indexer.allBuildings(x, y, range, b -> { - if(b.team != team){ - targets.add(b); - } - }); - - float effMultiplier = efficiencyMultiplier(); - - if (targets.size > 0 && canConsume()) { - smoothProgress = Mathf.approach(smoothProgress, 1f, Time.delta / chargeTime * effMultiplier); - - if (efficiency > 0 && (charge += Time.delta * effMultiplier) >= reload && smoothProgress >= 0.99f) { - shoot(); - charge = 0f; - } - } else { - smoothProgress = Mathf.approach(smoothProgress, 0f, Time.delta / chargeTime * effMultiplier); - } - } @Override public void updateTile() { AutoImplement.Util.Inject(HasPressureImpl.class); - super.updateTile(); - - targets.clear(); - Units.nearbyEnemies(team, x, y, range, u -> { - if(u.checkTarget(targetAir, targetGround)) { - targets.add(u); - } - }); - - indexer.allBuildings(x, y, range, b -> { - if(b.team != team){ - targets.add(b); - } - }); - - float effMultiplier = efficiencyMultiplier(); - - if (targets.size > 0 && canConsume()) { - smoothProgress = Mathf.approach(smoothProgress, 1f, Time.delta / chargeTime * effMultiplier); - - if (efficiency > 0 && (charge += Time.delta * effMultiplier) >= reload && smoothProgress >= 0.99f) { - shoot(); - charge = 0f; - } - } else { - smoothProgress = Mathf.approach(smoothProgress, 0f, Time.delta / chargeTime * effMultiplier); - } + super.updateTile(); + + targets.clear(); + Units.nearbyEnemies(team, x, y, range, u -> { + if(u.checkTarget(targetAir, targetGround)) { + targets.add(u); + } + }); + + indexer.allBuildings(x, y, range, b -> { + if(b.team != team){ + targets.add(b); + } + }); + + float effMultiplier = efficiencyMultiplier(); + + if (targets.size > 0 && canConsume()) { + smoothProgress = Mathf.approach(smoothProgress, 1f, Time.delta / chargeTime * effMultiplier); + + if (efficiency > 0 && (charge += Time.delta * effMultiplier) >= reload && smoothProgress >= 0.99f) { + shoot(); + charge = 0f; + } + } else { + smoothProgress = Mathf.approach(smoothProgress, 0f, Time.delta / chargeTime * effMultiplier); + } } @Override diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidBridge.java b/src/omaloon/world/blocks/liquid/PressureLiquidBridge.java index 8039ee03..a8cc281f 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidBridge.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidBridge.java @@ -18,6 +18,7 @@ import mindustry.world.blocks.liquid.*; import mindustry.world.blocks.sandbox.*; import mindustry.world.meta.*; +import omaloon.annotations.AutoImplement; import omaloon.annotations.Load; import omaloon.world.blocks.distribution.*; import omaloon.world.interfaces.*; @@ -232,6 +233,7 @@ public void read(Reads read, byte revision) { } @Override + @AutoImplement.NoInject(HasPressureImpl.class) public void updateTile() { incoming.size = Math.min(incoming.size, maxConnections - (link == -1 ? 0 : 1)); incoming.shrink(); @@ -239,7 +241,6 @@ public void updateTile() { checkIncoming(); updatePressure(); - BUG_NEED_TO_INJECT//I'll fix this after merge Tile other = world.tile(link); if(linkValid(tile, other)) { diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidPump.java b/src/omaloon/world/blocks/liquid/PressureLiquidPump.java index 49c19d4f..c1bd56ba 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidPump.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidPump.java @@ -171,7 +171,7 @@ public Liquid config() { } @Override public boolean connects(HasPressure to) { - return HasPressure.super.connects(to) && (front() == to || back() == to) && (!(to instanceof PressureLiquidPumpBuild) || to.rotation() == rotation); + return HasPressureImpl.super.connects(to) && (front() == to || back() == to) && (!(to instanceof PressureLiquidPumpBuild) || to.rotation() == rotation); } @Override diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidValve.java b/src/omaloon/world/blocks/liquid/PressureLiquidValve.java index 16c832d5..c285df90 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidValve.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidValve.java @@ -190,14 +190,6 @@ public boolean outputsPressurizedFluid(HasPressure to, Liquid liquid, float amou return HasPressureImpl.super.outputsPressurizedFluid(to, liquid, amount) && (liquid == to.pressure().getMain() || liquid == null || pressure.getMain() == null || to.pressure().getMain() == null); } - new PressureSection().mergeFlood(this); - } - - @Override - public boolean outputsPressurizedFluid(HasPressure to, Liquid liquid, float amount) { - return HasPressureImpl.super.outputsPressurizedFluid(to, liquid, amount) && (liquid == to.pressure().getMain() || liquid == null || pressure.getMain() == null || to.pressure().getMain() == null); - } - @Override public void read(Reads read, byte revision) { super.read(read, revision); diff --git a/src/omaloon/world/blocks/sandbox/PressureLiquidSource.java b/src/omaloon/world/blocks/sandbox/PressureLiquidSource.java index a842e446..a8e7b099 100644 --- a/src/omaloon/world/blocks/sandbox/PressureLiquidSource.java +++ b/src/omaloon/world/blocks/sandbox/PressureLiquidSource.java @@ -102,7 +102,7 @@ public class PressureLiquidSourceBuild extends Building implements HasPressureIm @Override public boolean acceptsPressurizedFluid(HasPressure from, Liquid liquid, float amount) { - return HasPressure.super.acceptsPressurizedFluid(from, liquid, amount) && liquid == Vars.content.liquid(this.liquid); + return HasPressureImpl.super.acceptsPressurizedFluid(from, liquid, amount) && liquid == Vars.content.liquid(this.liquid); } @Override @@ -164,7 +164,7 @@ public void draw() { @Override public boolean outputsPressurizedFluid(HasPressure to, Liquid liquid, float amount) { - return HasPressure.super.outputsPressurizedFluid(to, liquid, amount) && liquid == Vars.content.liquid(this.liquid); + return HasPressureImpl.super.outputsPressurizedFluid(to, liquid, amount) && liquid == Vars.content.liquid(this.liquid); } @Override From 55fbe2565cb5499dd0dfb7fe1e29aa9f867e9345 Mon Sep 17 00:00:00 2001 From: Zelaux <58040045+zelaux@users.noreply.github.com> Date: Fri, 7 Feb 2025 01:51:04 +0300 Subject: [PATCH 66/67] Added project codeStyle (Mindustry Style with some additions) --- .idea/codeStyles/Project.xml | 89 ++++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 .idea/codeStyles/Project.xml diff --git a/.idea/codeStyles/Project.xml b/.idea/codeStyles/Project.xml new file mode 100644 index 00000000..32a10a6e --- /dev/null +++ b/.idea/codeStyles/Project.xml @@ -0,0 +1,89 @@ + + + + \ No newline at end of file From 630d512b7adccff7b08bbba3365fa5e6c74cb2ad Mon Sep 17 00:00:00 2001 From: Zelaux <58040045+zelaux@users.noreply.github.com> Date: Fri, 7 Feb 2025 01:51:41 +0300 Subject: [PATCH 67/67] Reformat all project code with new style --- .github/ISSUE_TEMPLATE/bug_report.yml | 2 +- .run/Omaloon [debug jar].run.xml | 54 +- README.md | 17 +- annotations/build.gradle | 18 +- .../hierarchy/CollectedHierarchyInfo.java | 67 +- .../lombok/hierarchy/HierarchyCollector.java | 70 +- .../lombok/hierarchy/info/AbstractInfo.java | 31 +- .../lombok/hierarchy/info/ClassInfo.java | 36 +- .../lombok/hierarchy/info/InfoKey.java | 2 +- .../lombok/hierarchy/info/InterfaceInfo.java | 42 +- .../remove/RemoveFromCompilationHandler.java | 10 +- .../bytelogic/lombok/util/ContextLibrary.java | 57 +- .../bytelogic/lombok/util/ContextTools.java | 30 +- .../lombok/util/GeneratedByVisitor.java | 15 +- .../main/java/bytelogic/lombok/util/Util.java | 111 ++- .../omaloon/annotations/AutoImplement.java | 26 +- .../main/java/omaloon/annotations/Load.java | 7 +- .../annotations/RemoveFromCompilation.java | 5 +- .../java/omaloon/annotations/Starter.java | 43 +- .../lombok/autoimpl/AutoImplContext.java | 18 +- .../lombok/autoimpl/AutoImplUtil.java | 14 +- .../lombok/autoimpl/CleanupHandler.java | 36 +- .../lombok/autoimpl/HierarchyMarker.java | 39 +- .../lombok/autoimpl/ImplMarker.java | 28 +- .../lombok/autoimpl/ImplProcessor.java | 253 +++---- .../annotations/lombok/autoimpl/Paths.java | 18 +- .../autoimpl/info/AutoImplInformation.java | 84 +-- .../autoimpl/info/InlineApplyPrinter.java | 22 +- .../autoimpl/info/MethodDeclarationInfo.java | 29 +- .../lombok/autoimpl/info/MethodInfo.java | 234 +++--- .../lombok/autoimpl/info/TypeInliner.java | 73 +- .../lombok/load/FieldDescriptor.java | 66 +- .../lombok/load/LoadAnnotationASTVisitor.java | 68 +- .../annotations/lombok/load/Reference.java | 25 +- .../annotations/lombok/load/RegionName.java | 76 +- assets/bundles/bundle.properties | 24 +- assets/bundles/bundle_uk_UA.properties | 24 +- assets/bundles/bundle_zh_CN.properties | 26 +- assets/icons/omaloon-icons.properties | 16 +- assets/mod.json | 16 +- assets/shaders/circle-mesh.vert | 2 +- assets/shaders/dalani.frag | 6 +- assets/shaders/depth-atmosphere.frag | 6 +- build.gradle.kts | 109 ++- gradle/wrapper/gradle-wrapper.properties | 10 +- mod.json | 16 +- revisions/ChainedUnit/0.json | 101 ++- revisions/DroneUnit/0.json | 89 ++- revisions/FloatMechCoreUnit/0.json | 93 ++- revisions/FloatMechCoreUnit/1.json | 90 ++- revisions/FloatMechCoreUnit/2.json | 94 ++- revisions/OrnitopterFlyingUnit/0.json | 109 ++- settings.gradle.kts | 16 +- src/asmlib/annotations/DebugAST.java | 2 +- src/omaloon/OmaloonMod.java | 34 +- src/omaloon/ai/CowardAI.java | 34 +- src/omaloon/ai/DroneAI.java | 18 +- src/omaloon/ai/MillipedeAI.java | 221 +++--- src/omaloon/ai/drone/AttackDroneAI.java | 22 +- src/omaloon/ai/drone/UtilityDroneAI.java | 141 ++-- src/omaloon/annotations/AutoImplement.java | 28 +- src/omaloon/annotations/Load.java | 7 +- .../annotations/RemoveFromCompilation.java | 2 +- src/omaloon/content/OlBlocks.java | 2 +- src/omaloon/content/OlFx.java | 84 +-- src/omaloon/content/OlIcons.java | 9 +- src/omaloon/content/OlItems.java | 6 +- src/omaloon/content/OlLiquids.java | 74 +- src/omaloon/content/OlMusics.java | 294 ++++---- src/omaloon/content/OlPlanets.java | 648 ++++++++--------- src/omaloon/content/OlSchematics.java | 54 +- src/omaloon/content/OlSectorPresets.java | 88 +-- src/omaloon/content/OlSounds.java | 28 +- src/omaloon/content/OlStatusEffects.java | 56 +- src/omaloon/content/OlTechTree.java | 170 ++--- src/omaloon/content/OlUnitTypes.java | 354 ++++----- src/omaloon/content/OlWeathers.java | 180 ++--- .../content/blocks/OlCraftingBlocks.java | 132 ++-- .../content/blocks/OlDefenceBlocks.java | 393 +++++----- .../content/blocks/OlDistributionBlocks.java | 97 ++- .../content/blocks/OlEnvironmentBlocks.java | 178 +++-- src/omaloon/content/blocks/OlPowerBlocks.java | 42 +- .../content/blocks/OlProductionBlocks.java | 16 +- .../content/blocks/OlSandboxBlocks.java | 16 +- .../content/blocks/OlStorageBlocks.java | 14 +- src/omaloon/core/EditorListener.java | 36 +- src/omaloon/core/OlSettings.java | 75 +- src/omaloon/core/SafeClearer.java | 60 +- .../entities/abilities/DroneAbility.java | 51 +- .../entities/abilities/HailShieldAbility.java | 314 ++++---- .../entities/abilities/JavelinAbility.java | 309 ++++---- .../entities/bullet/FallingBulletType.java | 32 +- .../entities/bullet/HailStoneBulletType.java | 23 +- .../entities/bullet/LaunchBulletType.java | 290 ++++---- src/omaloon/entities/comp/ChainedComp.java | 662 ++++++++--------- src/omaloon/entities/comp/CoreComp.java | 107 +-- src/omaloon/entities/comp/DroneComp.java | 23 +- src/omaloon/entities/comp/FloatMechComp.java | 23 +- src/omaloon/entities/comp/OrnitopterComp.java | 32 +- .../entities/effect/LumenLiquidEffect.java | 62 +- src/omaloon/entities/part/ConstructPart.java | 100 +-- src/omaloon/graphics/OlGraphics.java | 73 +- src/omaloon/graphics/OlShaders.java | 29 +- src/omaloon/graphics/g3d/CircleMesh.java | 66 +- src/omaloon/graphics/g3d/MeshUtils.java | 30 +- .../shaders/DepthAtmosphereShader.java | 6 +- src/omaloon/graphics/shaders/DepthShader.java | 4 +- src/omaloon/maps/ColorPass.java | 176 ++--- src/omaloon/maps/HeightPass.java | 404 ++++++----- .../maps/planets/GlasmorePlanetGenerator.java | 54 +- .../maps/planets/PurpuraPlanetGenerator.java | 43 +- src/omaloon/math/Math3D.java | 8 +- src/omaloon/math/OlMath.java | 60 +- src/omaloon/struct/BitWordList.java | 16 +- src/omaloon/struct/IntRef.java | 17 +- src/omaloon/type/BetterPlanet.java | 2 +- src/omaloon/type/Blade.java | 8 +- src/omaloon/type/DroneUnitType.java | 4 +- src/omaloon/type/ExtraSectorPreset.java | 45 +- src/omaloon/type/FilterWeapon.java | 96 +-- src/omaloon/type/GlassmoreUnitType.java | 35 +- src/omaloon/type/MillipedeDecal.java | 2 +- src/omaloon/type/MillipedeUnitType.java | 37 +- src/omaloon/type/OrnitopterUnitType.java | 34 +- src/omaloon/type/customshape/CustomShape.java | 8 +- .../type/customshape/CustomShapeLoader.java | 1 + .../shapeloaders/SpriteShapeLoader.java | 2 +- src/omaloon/type/liquid/CrystalLiquid.java | 31 +- src/omaloon/type/weather/EffectWeather.java | 13 +- .../type/weather/HailStormWeather.java | 34 +- src/omaloon/type/weather/SpawnerWeather.java | 48 +- src/omaloon/ui/MultiItemConfig.java | 10 +- src/omaloon/ui/MultiItemData.java | 48 +- src/omaloon/ui/MultiItemSelection.java | 24 +- src/omaloon/ui/OlBinding.java | 10 +- src/omaloon/ui/StartSplash.java | 36 +- .../ui/dialogs/AfterUpdateCleanDialog.java | 20 +- src/omaloon/ui/dialogs/EventHints.java | 178 ++--- .../ui/dialogs/OlDisclaimerDialog.java | 40 +- src/omaloon/ui/dialogs/OlDiscordLink.java | 15 +- src/omaloon/ui/dialogs/OlEndDialog.java | 32 +- src/omaloon/ui/dialogs/OlGameDataDialog.java | 56 +- src/omaloon/ui/dialogs/OlGameDialog.java | 142 ++-- src/omaloon/ui/dialogs/OlInputDialog.java | 274 +++---- .../ui/dialogs/OlUpdateCheckerDialog.java | 42 +- src/omaloon/ui/elements/CenterBar.java | 232 +++--- src/omaloon/ui/fragments/CliffFragment.java | 116 +-- .../ui/fragments/ShapedEnvPlacerFragment.java | 194 ++--- src/omaloon/utils/IconLoader.java | 31 +- src/omaloon/utils/OlUtils.java | 34 +- src/omaloon/world/MultiPropGroup.java | 86 +-- .../world/blocks/defense/BlastTower.java | 177 +++-- .../world/blocks/defense/ConsumeTurret.java | 113 ++- .../world/blocks/defense/RepairProjector.java | 9 +- src/omaloon/world/blocks/defense/Shelter.java | 511 ++++++------- .../blocks/distribution/TubeConveyor.java | 142 ++-- .../blocks/distribution/TubeDistributor.java | 90 +-- .../world/blocks/distribution/TubeGate.java | 185 ++--- .../blocks/distribution/TubeItemBridge.java | 81 ++- .../blocks/distribution/TubeJunction.java | 24 +- .../world/blocks/distribution/TubeSorter.java | 64 +- .../world/blocks/environment/CliffHelper.java | 30 +- .../blocks/environment/CustomShapeProp.java | 56 +- .../environment/CustomShapePropProcess.java | 20 +- .../world/blocks/environment/OlCliff.java | 147 ++-- .../world/blocks/environment/RotatedProp.java | 9 +- .../blocks/liquid/PressureLiquidBridge.java | 511 +++++++------ .../blocks/liquid/PressureLiquidConduit.java | 355 ++++----- .../blocks/liquid/PressureLiquidGauge.java | 366 +++++----- .../blocks/liquid/PressureLiquidJunction.java | 97 +-- .../blocks/liquid/PressureLiquidPump.java | 684 +++++++++--------- .../blocks/liquid/PressureLiquidValve.java | 356 ++++----- .../world/blocks/power/ImpulseNode.java | 46 +- .../world/blocks/power/WindGenerator.java | 15 +- .../world/blocks/production/HammerDrill.java | 14 +- .../blocks/production/PressureCrafter.java | 200 ++--- .../blocks/production/PressureDrill.java | 102 +-- .../blocks/sandbox/PressureLiquidSource.java | 354 +++++---- .../blocks/sandbox/PressureLiquidVoid.java | 32 +- .../blocks/storage/GlassmoreCoreBlock.java | 36 +- src/omaloon/world/consumers/ConsumeFluid.java | 198 ++--- src/omaloon/world/draw/Draw3dSpin.java | 16 +- src/omaloon/world/draw/Drawo.java | 7 +- src/omaloon/world/draw/Outliner.java | 34 +- src/omaloon/world/interfaces/HasPressure.java | 147 ++-- .../world/interfaces/HasPressureImpl.java | 23 +- src/omaloon/world/interfaces/MultiPropI.java | 11 +- src/omaloon/world/meta/FluidGroup.java | 16 +- src/omaloon/world/meta/OlStats.java | 100 +-- src/omaloon/world/meta/PressureConfig.java | 194 ++--- src/omaloon/world/meta/PressureSection.java | 381 +++++----- src/omaloon/world/modules/PressureModule.java | 206 +++--- 192 files changed, 8965 insertions(+), 8416 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index a6502477..c9ad5d5b 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -1,6 +1,6 @@ name: Bug report description: Submit an issue that you have found while playing Omaloon. -labels: ["bug"] +labels: [ "bug" ] body: - type: dropdown diff --git a/.run/Omaloon [debug jar].run.xml b/.run/Omaloon [debug jar].run.xml index dff11c19..9fd71ee2 100644 --- a/.run/Omaloon [debug jar].run.xml +++ b/.run/Omaloon [debug jar].run.xml @@ -1,29 +1,29 @@ - - - - - - - true - true - false - false - - + + + + + + + true + true + false + false + + \ No newline at end of file diff --git a/README.md b/README.md index 09a98120..fa515dcd 100644 --- a/README.md +++ b/README.md @@ -8,8 +8,8 @@ [![Total Downloads](https://img.shields.io/github/downloads/xStaBUx/Omaloon-mod-public/total?color=7289da&label&logo=docusign&logoColor=white&style=for-the-badge)](https://github.com/xStaBUx/Omaloon-mod-public/releases) > An ambitious [Mindustry](https://github.com/Anuken/Mindustry) mod -developed by [stabu](https://github.com/stabu-dev) and [uujuju](https://github.com/uujuju1). -Mod aimed at expanding a campaign by adding a new star system. +> developed by [stabu](https://github.com/stabu-dev) and [uujuju](https://github.com/uujuju1). +> Mod aimed at expanding a campaign by adding a new star system. ## Building from Source @@ -22,21 +22,25 @@ Mod aimed at expanding a campaign by adding a new star system. ### Setup 1. Clone the repository: + ```bash git clone -b master --single-branch https://github.com/xstabux/Omaloon ``` 2. Set up environment variables: + - Set `ANDROID_SDK_ROOT` or `ANDROID_HOME` to your Android SDK installation path (required for Android builds) ### Building For Desktop: + ```bash gradlew jar ``` For Android: + ```bash gradlew dex ``` @@ -46,28 +50,34 @@ The built mod will be in the `build/libs` directory. ### Running To test the mod directly: + ```bash gradlew runClient ``` + This Mindustry client uses the `run` directory to store its data. ## Contributing ### Bug Reports + - Submit bug reports in the [Issues](https://github.com/xStaBUx/Omaloon-mod-public/issues) section - Include detailed steps to reproduce the issue - Mention your game version and mod version ### Feature Suggestions + - Join our [Discord server](https://discord.gg/bNMT82Hswb) to suggest new content - Provide examples and specific arguments why your suggestion should be added to Omaloon - The Issues section is reserved for bug reports only ### Game-play Feedback + - Share your thoughts on game-play and balancing in our Discord - Provide specific examples and reasoning for balance changes ### Pull Requests + - Improve Omaloon's code/sprites/localization and propose these changes to us by creating a [Pull Request](https://github.com/stabu-dev/Omaloon/pulls). - Make sure your code works properly and doesn't cause any issues. - Provide specific reasoning why your Pull Request should be accepted. @@ -75,9 +85,12 @@ This Mindustry client uses the `run` directory to store its data. ## Credits ### Developers + - stabu - Lead Dev - uujuju - Dev + ### Contributors + - randomguy - Weathers code - zelaux - Arc library, some code - saigononozomi - Music diff --git a/annotations/build.gradle b/annotations/build.gradle index 8263e896..37b53570 100644 --- a/annotations/build.gradle +++ b/annotations/build.gradle @@ -1,8 +1,8 @@ println("Hello from gradle") apply plugin: "java" -tasks.withType(JavaCompile).tap { - configureEach { +tasks.withType(JavaCompile).tap{ + configureEach{ options.fork = true options.compilerArgs += [ '--add-exports', 'jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED', @@ -20,17 +20,17 @@ tasks.withType(JavaCompile).tap { ] } } -repositories { +repositories{ // Necessary Maven repositories to pull dependencies from. mavenCentral() - maven { url "https://oss.sonatype.org/content/repositories/snapshots/" } - maven { url "https://oss.sonatype.org/content/repositories/releases/" } - maven { url "https://raw.githubusercontent.com/GlennFolker/EntityAnnoMaven/main" } + maven{ url "https://oss.sonatype.org/content/repositories/snapshots/" } + maven{ url "https://oss.sonatype.org/content/repositories/releases/" } + maven{ url "https://raw.githubusercontent.com/GlennFolker/EntityAnnoMaven/main" } // Use Zelaux's non-buggy repository for release Mindustry and Arc builds. - maven { url "https://raw.githubusercontent.com/Zelaux/MindustryRepo/master/repository" } - maven { url "https://raw.githubusercontent.com/Zelaux/Repo/master/repository" } + maven{ url "https://raw.githubusercontent.com/Zelaux/MindustryRepo/master/repository" } + maven{ url "https://raw.githubusercontent.com/Zelaux/Repo/master/repository" } } /*tasks.withType(JavaCompile){ @@ -42,7 +42,7 @@ repositories { "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5008" ) }*/ -dependencies { +dependencies{ implementation asmLib.invoke(":annotations:lombok-plugin-starter") diff --git a/annotations/src/main/java/bytelogic/lombok/hierarchy/CollectedHierarchyInfo.java b/annotations/src/main/java/bytelogic/lombok/hierarchy/CollectedHierarchyInfo.java index 0b568884..9c4df92a 100644 --- a/annotations/src/main/java/bytelogic/lombok/hierarchy/CollectedHierarchyInfo.java +++ b/annotations/src/main/java/bytelogic/lombok/hierarchy/CollectedHierarchyInfo.java @@ -1,80 +1,79 @@ package bytelogic.lombok.hierarchy; -import bytelogic.lombok.hierarchy.info.ClassInfo; -import bytelogic.lombok.hierarchy.info.InterfaceInfo; -import bytelogic.lombok.util.Util; -import lombok.javac.JavacNode; -import lombok.val; -import one.util.streamex.EntryStream; -import org.jetbrains.annotations.NotNull; +import bytelogic.lombok.hierarchy.info.*; +import bytelogic.lombok.util.*; +import lombok.javac.*; +import lombok.*; +import one.util.streamex.*; +import org.jetbrains.annotations.*; import java.util.*; -import java.util.function.BiConsumer; +import java.util.function.*; -public class CollectedHierarchyInfo { +public class CollectedHierarchyInfo{ public static final String JAVA_LANG_OBJECT = "java.lang.Object"; public static final InterfaceInfo interfacesRoot = new InterfaceInfo("?interfacesRoot?", "?interfacesRoot?"); static ClassInfo javaLangObject = new ClassInfo(JAVA_LANG_OBJECT, JAVA_LANG_OBJECT); static Map classInfoMap; static Map interfacesInfoMap; - public static ClassInfo classInfo(String className) { + public static ClassInfo classInfo(String className){ return classInfoMap.get(className); } - public static InterfaceInfo interfaceInfo(String name) { + public static InterfaceInfo interfaceInfo(String name){ return interfacesInfoMap.get(name); } - public static EntryStream interfaces() { + public static EntryStream interfaces(){ return EntryStream.of(interfacesInfoMap) .removeKeys(it -> it.equals(interfacesRoot.name)); } - public static EntryStream classes() { + public static EntryStream classes(){ return EntryStream.of(classInfoMap); } @NotNull - public static ArrayList collectAllImpl(InterfaceInfo interfaceInfo) { + public static ArrayList collectAllImpl(InterfaceInfo interfaceInfo){ ArrayList allSubTypes = collectAllSub(interfaceInfo); val classInfoStream = allSubTypes - .stream() - .map(it -> it.impltypes.values()) - .flatMap(Collection::stream) - .distinct() - .toArray(ClassInfo[]::new); + .stream() + .map(it -> it.impltypes.values()) + .flatMap(Collection::stream) + .distinct() + .toArray(ClassInfo[]::new); ; ArrayList implementedClasses = new ArrayList<>(); Set visitedNames = new HashSet<>(); - class Visitor { - static void visit(Set visitedNames, ClassInfo info, ArrayList targetCollection) { - if (!visitedNames.add(info.name)) return; + class Visitor{ + static void visit(Set visitedNames, ClassInfo info, ArrayList targetCollection){ + if(!visitedNames.add(info.name)) return; targetCollection.add(info); - for (ClassInfo value : info.subtypes.values()) { + for(ClassInfo value : info.subtypes.values()){ visit(visitedNames, value, targetCollection); } } } - for (ClassInfo info : classInfoStream) { + for(ClassInfo info : classInfoStream){ Visitor.visit(visitedNames, info, implementedClasses); } return implementedClasses; } @NotNull - public static ArrayList collectAllSub(InterfaceInfo interfaceInfo) { + public static ArrayList collectAllSub(InterfaceInfo interfaceInfo){ ArrayList allSubTypes = new ArrayList<>(); //noinspection unchecked - BiConsumer visitor = new BiConsumer<>() { + BiConsumer visitor = new BiConsumer<>(){ Set visitedNames = new HashSet<>(); @Override - public void accept(String name, InterfaceInfo info) { - if (!visitedNames.add(info.name)) return; + public void accept(String name, InterfaceInfo info){ + if(!visitedNames.add(info.name)) return; allSubTypes.add(info); info.subtypes.forEach(this); } @@ -83,25 +82,25 @@ public void accept(String name, InterfaceInfo info) { return allSubTypes; } - public static ClassInfo classInfo(JavacNode typeNode) { + public static ClassInfo classInfo(JavacNode typeNode){ return classInfo(Util.canonicalFullname(typeNode)); } - public static ClassInfo classInfoOrThrown(JavacNode typeNode) { + public static ClassInfo classInfoOrThrown(JavacNode typeNode){ String mirrorName = Util.canonicalFullname(typeNode); ClassInfo classInfo = classInfo(mirrorName); - if (classInfo == null) throw new RuntimeException("Cannot find info for class " + mirrorName); + if(classInfo == null) throw new RuntimeException("Cannot find info for class " + mirrorName); return classInfo; } - public static InterfaceInfo interfaceInfo(JavacNode typeNode) { + public static InterfaceInfo interfaceInfo(JavacNode typeNode){ return interfaceInfo(Util.canonicalFullname(typeNode)); } - public static InterfaceInfo interfaceInfoOrThrown(JavacNode typeNode) { + public static InterfaceInfo interfaceInfoOrThrown(JavacNode typeNode){ String string = Util.canonicalFullname(typeNode); InterfaceInfo interfaceInfo = interfaceInfo(string); - if (interfaceInfo == null) throw new RuntimeException("Cannot find info for interface " + string); + if(interfaceInfo == null) throw new RuntimeException("Cannot find info for interface " + string); return interfaceInfo; } } diff --git a/annotations/src/main/java/bytelogic/lombok/hierarchy/HierarchyCollector.java b/annotations/src/main/java/bytelogic/lombok/hierarchy/HierarchyCollector.java index fe7c5cef..55a43540 100644 --- a/annotations/src/main/java/bytelogic/lombok/hierarchy/HierarchyCollector.java +++ b/annotations/src/main/java/bytelogic/lombok/hierarchy/HierarchyCollector.java @@ -1,56 +1,49 @@ package bytelogic.lombok.hierarchy; -import bytelogic.lombok.hierarchy.info.ClassInfo; -import bytelogic.lombok.hierarchy.info.InterfaceInfo; -import bytelogic.lombok.util.Util; -import com.sun.source.util.Trees; -import com.sun.tools.javac.code.Type; -import com.sun.tools.javac.model.JavacTypes; -import com.sun.tools.javac.tree.JCTree.JCClassDecl; -import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; -import lombok.NonNull; -import lombok.core.HandlerPriority; -import lombok.javac.JavacASTAdapter; -import lombok.javac.JavacNode; -import lombok.val; - -import javax.lang.model.type.TypeMirror; -import java.util.HashMap; -import java.util.List; +import bytelogic.lombok.hierarchy.info.*; +import bytelogic.lombok.util.*; +import com.sun.source.util.*; +import com.sun.tools.javac.code.*; +import com.sun.tools.javac.model.*; +import com.sun.tools.javac.tree.JCTree.*; +import lombok.*; +import lombok.core.*; +import lombok.javac.*; + +import java.util.*; import static bytelogic.lombok.hierarchy.CollectedHierarchyInfo.*; -import static bytelogic.lombok.util.Util.mirror; -import static bytelogic.lombok.util.Util.supertypes; +import static bytelogic.lombok.util.Util.*; @HandlerPriority(value = -10, subValue = 0) -public class HierarchyCollector extends JavacASTAdapter { +public class HierarchyCollector extends JavacASTAdapter{ Trees trees; @Override - public void visitCompilationUnit(JavacNode top, JCCompilationUnit unit) { + public void visitCompilationUnit(JavacNode top, JCCompilationUnit unit){ super.visitCompilationUnit(top, unit); } @Override - public void endVisitCompilationUnit(JavacNode top, JCCompilationUnit unit) { + public void endVisitCompilationUnit(JavacNode top, JCCompilationUnit unit){ super.endVisitCompilationUnit(top, unit); } @Override - public void visitType(JavacNode typeNode, JCClassDecl type) { - if (typeNode.getElement() == null) {//Anonymous class + public void visitType(JavacNode typeNode, JCClassDecl type){ + if(typeNode.getElement() == null){//Anonymous class // System.out.println("Warning: empty element"); return; } Type selfMirror = mirror(typeNode); List supertypes = supertypes(typeNode); - if (!Util.isInterface(type.mods)) { + if(!Util.isInterface(type.mods)){ Type parent = supertypes.get(0); indexHierarchy(parent, selfMirror, typeNode.getTypesUtil()); ClassInfo selfInfo = getOrCreateClassInfo(selfMirror); - for (int i = 1; i < supertypes.size(); i++) { + for(int i = 1; i < supertypes.size(); i++){ getOrCreateInterInfo(supertypes.get(i)).addImpl(selfInfo); } return; @@ -60,46 +53,47 @@ public void visitType(JavacNode typeNode, JCClassDecl type) { InterfaceInfo target = getOrCreateInterInfo(selfMirror); List list = supertypes - .stream() - .map(this::getOrCreateInterInfo) - .toList(); + .stream() + .map(this::getOrCreateInterInfo) + .toList(); - for (val info : list) { - if (target == info) continue; + for(val info : list){ + if(target == info) continue; info.addSub(target); } } - private void indexHierarchy(@NonNull Type parent, @NonNull Type subtype, JavacTypes typesUtil) { + private void indexHierarchy(@NonNull Type parent, @NonNull Type subtype, JavacTypes typesUtil){ ClassInfo parentInfo = getOrCreateClassInfo(parent); ClassInfo subInfo = getOrCreateClassInfo(subtype); parentInfo.addSub(subInfo); - if (parent.toString().equals(CollectedHierarchyInfo.JAVA_LANG_OBJECT)) return; + if(parent.toString().equals(CollectedHierarchyInfo.JAVA_LANG_OBJECT)) return; Type newParent = supertypes(parent, typesUtil).get(0); indexHierarchy(newParent, parent, typesUtil); } - private ClassInfo getOrCreateClassInfo(Type mirror) { + private ClassInfo getOrCreateClassInfo(Type mirror){ return classInfoMap.computeIfAbsent(mirror.toString(), name -> new ClassInfo(mirror)); } - private InterfaceInfo getOrCreateInterInfo(Type mirror) { + + private InterfaceInfo getOrCreateInterInfo(Type mirror){ String string = mirror.toString(); - if(string.equals(JAVA_LANG_OBJECT))return interfacesRoot; + if(string.equals(JAVA_LANG_OBJECT)) return interfacesRoot; return interfacesInfoMap.computeIfAbsent(string, type -> new InterfaceInfo(mirror)); } @Override - public void setTrees(Trees trees) { + public void setTrees(Trees trees){ this.trees = (trees); classInfoMap = new HashMap<>(); classInfoMap.put(javaLangObject.name, javaLangObject); interfacesInfoMap = new HashMap<>(); - interfacesInfoMap.put(interfacesRoot.name,interfacesRoot); + interfacesInfoMap.put(interfacesRoot.name, interfacesRoot); } } diff --git a/annotations/src/main/java/bytelogic/lombok/hierarchy/info/AbstractInfo.java b/annotations/src/main/java/bytelogic/lombok/hierarchy/info/AbstractInfo.java index aca72f6b..1a5aa601 100644 --- a/annotations/src/main/java/bytelogic/lombok/hierarchy/info/AbstractInfo.java +++ b/annotations/src/main/java/bytelogic/lombok/hierarchy/info/AbstractInfo.java @@ -1,19 +1,15 @@ package bytelogic.lombok.hierarchy.info; -import com.sun.tools.javac.code.Type; -import lombok.AccessLevel; -import lombok.AllArgsConstructor; -import lombok.Getter; -import lombok.NonNull; -import lombok.experimental.FieldDefaults; -import org.jetbrains.annotations.Nullable; +import com.sun.tools.javac.code.*; +import lombok.*; +import lombok.experimental.*; +import org.jetbrains.annotations.*; -import java.util.HashMap; -import java.util.Map; +import java.util.*; @AllArgsConstructor @FieldDefaults(level = AccessLevel.PUBLIC) -public class AbstractInfo { +public class AbstractInfo{ @NonNull @Getter final String name; @@ -22,25 +18,26 @@ public class AbstractInfo { final String flatName; private final Map, Object> infoMap = new HashMap<>(); - public AbstractInfo(Type type) { - this(type.toString(),type.tsym.flatName().toString()); + public AbstractInfo(Type type){ + this(type.toString(), type.tsym.flatName().toString()); } @Nullable - public T get(InfoKey key) { + public T get(InfoKey key){ //noinspection unchecked - return (T) infoMap.get(key); + return (T)infoMap.get(key); } @Override - public int hashCode() { + public int hashCode(){ return name.hashCode(); } - public void put(InfoKey key, T value) { + public void put(InfoKey key, T value){ infoMap.put(key, value); } - public boolean has(InfoKey key) { + + public boolean has(InfoKey key){ return infoMap.containsKey(key); } } diff --git a/annotations/src/main/java/bytelogic/lombok/hierarchy/info/ClassInfo.java b/annotations/src/main/java/bytelogic/lombok/hierarchy/info/ClassInfo.java index f0ff8d9a..220d03fc 100644 --- a/annotations/src/main/java/bytelogic/lombok/hierarchy/info/ClassInfo.java +++ b/annotations/src/main/java/bytelogic/lombok/hierarchy/info/ClassInfo.java @@ -1,56 +1,52 @@ package bytelogic.lombok.hierarchy.info; -import com.sun.tools.javac.code.Type; -import lombok.AccessLevel; -import lombok.Getter; -import lombok.NonNull; -import lombok.RequiredArgsConstructor; -import lombok.experimental.FieldDefaults; -import org.jetbrains.annotations.Nullable; +import com.sun.tools.javac.code.*; +import lombok.*; +import lombok.experimental.*; +import org.jetbrains.annotations.*; -import java.util.HashMap; -import java.util.Map; -import java.util.function.Consumer; +import java.util.*; +import java.util.function.*; @FieldDefaults(level = AccessLevel.PUBLIC) -public class ClassInfo extends AbstractInfo { +public class ClassInfo extends AbstractInfo{ final Map subtypes = new HashMap<>(); @Nullable private ClassInfo parent; - public ClassInfo(@NonNull String name, @NonNull String flatName) { + public ClassInfo(@NonNull String name, @NonNull String flatName){ super(name, flatName); } - public ClassInfo(Type type) { + public ClassInfo(Type type){ super(type); } - public ClassInfo parent() { + public ClassInfo parent(){ return parent; } @Override - public boolean equals(Object obj) { + public boolean equals(Object obj){ return obj == this || obj instanceof ClassInfo info && info.name.equals(name); } - public void visitSubtypes(Consumer visitor, boolean visitDeep, boolean visitSelf) { - if (visitSelf) visitor.accept(this); - if (!visitDeep) { + public void visitSubtypes(Consumer visitor, boolean visitDeep, boolean visitSelf){ + if(visitSelf) visitor.accept(this); + if(!visitDeep){ subtypes.values().forEach(visitor); return; } - for (ClassInfo info : subtypes.values()) { + for(ClassInfo info : subtypes.values()){ info.visitSubtypes(visitor, true, true); } } - public void addSub(ClassInfo subInfo) { + public void addSub(ClassInfo subInfo){ subtypes.put(subInfo.name, subInfo); subInfo.parent = this; } diff --git a/annotations/src/main/java/bytelogic/lombok/hierarchy/info/InfoKey.java b/annotations/src/main/java/bytelogic/lombok/hierarchy/info/InfoKey.java index b040b857..464beff3 100644 --- a/annotations/src/main/java/bytelogic/lombok/hierarchy/info/InfoKey.java +++ b/annotations/src/main/java/bytelogic/lombok/hierarchy/info/InfoKey.java @@ -1,5 +1,5 @@ package bytelogic.lombok.hierarchy.info; -public class InfoKey { +public class InfoKey{ } diff --git a/annotations/src/main/java/bytelogic/lombok/hierarchy/info/InterfaceInfo.java b/annotations/src/main/java/bytelogic/lombok/hierarchy/info/InterfaceInfo.java index 8b719e87..4aebba1a 100644 --- a/annotations/src/main/java/bytelogic/lombok/hierarchy/info/InterfaceInfo.java +++ b/annotations/src/main/java/bytelogic/lombok/hierarchy/info/InterfaceInfo.java @@ -1,67 +1,63 @@ package bytelogic.lombok.hierarchy.info; -import com.sun.tools.javac.code.Type; -import lombok.AccessLevel; -import lombok.NonNull; -import lombok.RequiredArgsConstructor; -import lombok.experimental.FieldDefaults; -import org.jetbrains.annotations.Nullable; +import com.sun.tools.javac.code.*; +import lombok.*; +import lombok.experimental.*; -import java.util.HashMap; -import java.util.Map; -import java.util.function.Consumer; +import java.util.*; +import java.util.function.*; @FieldDefaults(level = AccessLevel.PUBLIC) -public class InterfaceInfo extends AbstractInfo { +public class InterfaceInfo extends AbstractInfo{ final Map subtypes = new HashMap<>(); final Map impltypes = new HashMap<>(); private final Map, Object> infoMap = new HashMap<>(); /** * interface It extends It1,It2,It2{ - * + *

    * } - * + *

    * It.supertypes={ * "It1":It1, * "It2":It2, * "It3":It3 * } - * */ + */ public Map supertypes = new HashMap<>(); - public InterfaceInfo(@NonNull String name, @NonNull String flatName) { + public InterfaceInfo(@NonNull String name, @NonNull String flatName){ super(name, flatName); } - public InterfaceInfo(Type type) { + public InterfaceInfo(Type type){ super(type); } @Override - public boolean equals(Object o) { - if (this == o) return true; + public boolean equals(Object o){ + if(this == o) return true; return o instanceof InterfaceInfo info && name.equals(info.name); } - public void visitSubtypes(Consumer visitor, boolean visitDeep, boolean visitSelf) { - if (visitSelf) visitor.accept(this); - if (!visitDeep) { + public void visitSubtypes(Consumer visitor, boolean visitDeep, boolean visitSelf){ + if(visitSelf) visitor.accept(this); + if(!visitDeep){ subtypes.values().forEach(visitor); return; } - for (InterfaceInfo info : subtypes.values()) { + for(InterfaceInfo info : subtypes.values()){ info.visitSubtypes(visitor, true, true); } } - public void addSub(InterfaceInfo subInfo) { + public void addSub(InterfaceInfo subInfo){ subtypes.put(subInfo.name, subInfo); subInfo.supertypes.put(name, this); } - public void addImpl(ClassInfo info) { + public void addImpl(ClassInfo info){ impltypes.put(info.name, info); } diff --git a/annotations/src/main/java/bytelogic/lombok/remove/RemoveFromCompilationHandler.java b/annotations/src/main/java/bytelogic/lombok/remove/RemoveFromCompilationHandler.java index 6bb39afd..551a2c71 100644 --- a/annotations/src/main/java/bytelogic/lombok/remove/RemoveFromCompilationHandler.java +++ b/annotations/src/main/java/bytelogic/lombok/remove/RemoveFromCompilationHandler.java @@ -5,7 +5,7 @@ import com.sun.tools.javac.util.*; import lombok.core.*; import lombok.javac.*; -import omaloon.annotations.RemoveFromCompilation; +import omaloon.annotations.*; import java.util.function.*; @@ -20,10 +20,10 @@ public void handle(AnnotationValues annotationValues, JCA Consumer> consumer; if(parent.get() instanceof JCClassDecl it){ defs = it.defs; - consumer=val->it.defs=val; + consumer = val -> it.defs = val; }else if(parent.get() instanceof JCCompilationUnit it){ defs = it.defs; - consumer=val->it.defs=val; + consumer = val -> it.defs = val; }else{ javacNode.addError("Unsupported parent (" + parent.get().getKind() + ")"); return; @@ -37,10 +37,10 @@ public void handle(AnnotationValues annotationValues, JCA javacNode.addError("Stange, I cant find annotated element in parent"); return; } - if(prev==null){ + if(prev == null){ consumer.accept(defs.tail); return; } - prev.tail=defs.tail; + prev.tail = defs.tail; } } diff --git a/annotations/src/main/java/bytelogic/lombok/util/ContextLibrary.java b/annotations/src/main/java/bytelogic/lombok/util/ContextLibrary.java index 7817e108..d7d671a4 100644 --- a/annotations/src/main/java/bytelogic/lombok/util/ContextLibrary.java +++ b/annotations/src/main/java/bytelogic/lombok/util/ContextLibrary.java @@ -1,67 +1,62 @@ package bytelogic.lombok.util; -import com.sun.tools.javac.tree.JCTree; -import com.sun.tools.javac.util.Context; -import lombok.AccessLevel; -import lombok.AllArgsConstructor; -import lombok.Getter; -import lombok.With; -import lombok.core.AST; -import lombok.core.TypeLibrary; -import lombok.javac.JavacNode; -import lombok.javac.JavacResolution; -import org.jetbrains.annotations.Contract; +import com.sun.tools.javac.tree.*; +import com.sun.tools.javac.util.*; +import lombok.*; +import lombok.core.*; +import lombok.javac.*; +import org.jetbrains.annotations.*; -import java.util.Map; +import java.util.*; @AllArgsConstructor(access = AccessLevel.PROTECTED) @With @Getter -public class ContextLibrary { +public class ContextLibrary{ public final JavacNode context; public final TypeLibrary library; public final JavacResolution resolution; public final Map resolvedParts; - public static ContextLibrary makeLib(JavacNode contextNode, TypeLibrary library) { + public static ContextLibrary makeLib(JavacNode contextNode, TypeLibrary library){ Context context = contextNode.getContext(); JavacResolution javacResolution = Util.resolution(context); Map resolvedParts = null; - try { + try{ resolvedParts = javacResolution.resolveMethodMember(contextNode); - } catch (Throwable e) { - try { + }catch(Throwable e){ + try{ JavacNode node = contextNode; - while (node != null) { - if (node.getKind() == AST.Kind.TYPE) - for (JavacNode javacNode : node.down()) + while(node != null){ + if(node.getKind() == AST.Kind.TYPE) + for(JavacNode javacNode : node.down()) javacResolution.resolveClassMember(javacNode); node = node.up(); } resolvedParts = javacResolution.resolveMethodMember(contextNode); - } catch (Throwable ex) { + }catch(Throwable ex){ } } return new ContextLibrary( - contextNode, - library, - javacResolution, - resolvedParts + contextNode, + library, + javacResolution, + resolvedParts ); } - public static ContextLibrary ofClasses(JavacNode context) { + public static ContextLibrary ofClasses(JavacNode context){ return makeLib(context, Util.buildClassLibrary(context)); } @Contract("null -> null") - public String className(JCTree typeRepresentation) { - if (typeRepresentation == null) return null; + public String className(JCTree typeRepresentation){ + if(typeRepresentation == null) return null; String resolved = resolveFull(typeRepresentation.toString()); - if (resolved == null) { + if(resolved == null){ /*if (resolvedParts==null) { try { resolvedParts=resolution.resolveMethodMember(context); @@ -69,7 +64,7 @@ public String className(JCTree typeRepresentation) { } }*/ - if (resolvedParts != null) { + if(resolvedParts != null){ return resolvedParts.get(typeRepresentation).type.toString(); } } @@ -77,7 +72,7 @@ public String className(JCTree typeRepresentation) { } - public String resolveFull(String string) { + public String resolveFull(String string){ return context.getImportListAsTypeResolver() .typeRefToFullyQualifiedName(context, library, string); } diff --git a/annotations/src/main/java/bytelogic/lombok/util/ContextTools.java b/annotations/src/main/java/bytelogic/lombok/util/ContextTools.java index a59483cb..e80b9a79 100644 --- a/annotations/src/main/java/bytelogic/lombok/util/ContextTools.java +++ b/annotations/src/main/java/bytelogic/lombok/util/ContextTools.java @@ -1,33 +1,31 @@ package bytelogic.lombok.util; -import com.sun.tools.javac.code.Symtab; -import com.sun.tools.javac.parser.ParserFactory; -import com.sun.tools.javac.util.Context; -import com.sun.tools.javac.util.Names; -import lombok.AccessLevel; -import lombok.AllArgsConstructor; -import lombok.experimental.FieldDefaults; -import lombok.javac.JavacNode; -import lombok.javac.JavacResolution; +import com.sun.tools.javac.code.*; +import com.sun.tools.javac.parser.*; +import com.sun.tools.javac.util.*; +import lombok.*; +import lombok.experimental.*; +import lombok.javac.*; @AllArgsConstructor -@FieldDefaults(level = AccessLevel.PUBLIC,makeFinal = true) -public class ContextTools { +@FieldDefaults(level = AccessLevel.PUBLIC, makeFinal = true) +public class ContextTools{ JavacResolution resolution; Names names; Symtab symtab; ParserFactory parserFactory; + public static ContextTools make(Context context){ return new ContextTools( - Util.resolution(context), - Names.instance(context), - Symtab.instance(context), - ParserFactory.instance(context) + Util.resolution(context), + Names.instance(context), + Symtab.instance(context), + ParserFactory.instance(context) ); } - public static ContextTools make(JavacNode typeNode) { + public static ContextTools make(JavacNode typeNode){ return make(typeNode.getContext()); } } diff --git a/annotations/src/main/java/bytelogic/lombok/util/GeneratedByVisitor.java b/annotations/src/main/java/bytelogic/lombok/util/GeneratedByVisitor.java index 2346b6b4..b2327efb 100644 --- a/annotations/src/main/java/bytelogic/lombok/util/GeneratedByVisitor.java +++ b/annotations/src/main/java/bytelogic/lombok/util/GeneratedByVisitor.java @@ -1,20 +1,19 @@ package bytelogic.lombok.util; -import com.github.javaparser.ast.visitor.TreeVisitor; -import com.sun.source.tree.Tree; +import com.sun.source.tree.*; import com.sun.source.util.TreeScanner; -import com.sun.tools.javac.tree.JCTree; -import lombok.AllArgsConstructor; -import lombok.javac.JavacNode; +import com.sun.tools.javac.tree.*; +import lombok.*; +import lombok.javac.*; @AllArgsConstructor -public class GeneratedByVisitor extends TreeScanner { +public class GeneratedByVisitor extends TreeScanner{ public final JavacNode contextNode; public final JCTree sourceNode; @Override - public Void scan(Tree tree, Void unused) { - Util.setGeneratedBy((JCTree) tree, contextNode, sourceNode); + public Void scan(Tree tree, Void unused){ + Util.setGeneratedBy((JCTree)tree, contextNode, sourceNode); return super.scan(tree, unused); } } diff --git a/annotations/src/main/java/bytelogic/lombok/util/Util.java b/annotations/src/main/java/bytelogic/lombok/util/Util.java index 13713bda..06f049c3 100644 --- a/annotations/src/main/java/bytelogic/lombok/util/Util.java +++ b/annotations/src/main/java/bytelogic/lombok/util/Util.java @@ -1,61 +1,56 @@ package bytelogic.lombok.util; -import asmlib.lombok.javaparser.CompileBodyVisitor; -import com.sun.tools.javac.code.Symtab; +import asmlib.lombok.javaparser.*; import com.sun.tools.javac.code.Type; -import com.sun.tools.javac.model.JavacTypes; -import com.sun.tools.javac.tree.JCTree; -import com.sun.tools.javac.util.Context; -import lombok.NonNull; -import lombok.SneakyThrows; -import lombok.core.TypeLibrary; -import lombok.javac.Javac; -import lombok.javac.JavacAugments; -import lombok.javac.JavacNode; -import lombok.javac.JavacResolution; -import lombok.javac.handlers.JavacHandlerUtil; -import one.util.streamex.StreamEx; -import org.jetbrains.annotations.Contract; -import org.jetbrains.annotations.NotNull; - -import javax.lang.model.type.TypeMirror; -import java.lang.reflect.Field; +import com.sun.tools.javac.code.*; +import com.sun.tools.javac.model.*; +import com.sun.tools.javac.tree.*; +import com.sun.tools.javac.util.*; +import lombok.*; +import lombok.core.*; +import lombok.javac.*; +import lombok.javac.handlers.*; +import one.util.streamex.*; +import org.jetbrains.annotations.*; + +import javax.lang.model.type.*; +import java.lang.reflect.*; import java.util.List; -import java.util.Map; +import java.util.*; import static com.sun.tools.javac.code.Flags.INTERFACE; -public class Util { +public class Util{ - public static List supertypes(JavacNode typeNode) { + public static List supertypes(JavacNode typeNode){ return supertypes(mirror(typeNode), typeNode.getTypesUtil()); } - public static List supertypes(TypeMirror mirror, JavacTypes typesUtil) { - if (mirror != null && mirror.toString().equals("java.lang.Object")) return List.of(); + public static List supertypes(TypeMirror mirror, JavacTypes typesUtil){ + if(mirror != null && mirror.toString().equals("java.lang.Object")) return List.of(); return typesUtil.directSupertypes(mirror); } - public static Type mirror(JavacNode typeNode) { - return (Type) typeNode.getElement().asType(); + public static Type mirror(JavacNode typeNode){ + return (Type)typeNode.getElement().asType(); } - public static boolean isInterface(JCTree.JCModifiers modifiers) { + public static boolean isInterface(JCTree.JCModifiers modifiers){ return (modifiers.flags & INTERFACE) != 0; } - public static Type supertype(JavacNode typeNode) { + public static Type supertype(JavacNode typeNode){ return supertypes(typeNode).get(0); } @Contract("_,null->null;_, !null -> !null") - public static String methodDesc(@NonNull JavacNode context, JCTree.JCMethodDecl decl) { + public static String methodDesc(@NonNull JavacNode context, JCTree.JCMethodDecl decl){ return methodDesc(ContextLibrary.ofClasses(context), decl); } @Contract("_, null->null; _, !null -> !null") - public static String methodDesc(ContextLibrary library, JCTree.JCMethodDecl decl) { - if (decl == null) return null; + public static String methodDesc(ContextLibrary library, JCTree.JCMethodDecl decl){ + if(decl == null) return null; String ret = library.className(decl.getReturnType()); String params = StreamEx.of(decl.getParameters()) .map(JCTree.JCVariableDecl::getType) @@ -66,7 +61,7 @@ public static String methodDesc(ContextLibrary library, JCTree.JCMethodDecl decl @SneakyThrows @NotNull - public static TypeLibrary buildClassLibrary(@NotNull JavacNode context) { + public static TypeLibrary buildClassLibrary(@NotNull JavacNode context){ TypeLibrary library = new TypeLibrary(); StreamEx.of(context) .map(JavacNode::getSymbolTable) @@ -76,17 +71,17 @@ public static TypeLibrary buildClassLibrary(@NotNull JavacNode context) { .map(it -> it.flatname.toString()) .forEach(library::addType); String[] primitives = { - "byte", "short", "char", "int", "long", - "float", "double", - "boolean", - "void" + "byte", "short", "char", "int", "long", + "float", "double", + "boolean", + "void" }; Field field = TypeLibrary.class.getDeclaredField("unqualifiedToQualifiedMap"); field.setAccessible(true); //noinspection unchecked - final Map unqualifiedToQualifiedMap = (Map) field.get(library); + final Map unqualifiedToQualifiedMap = (Map)field.get(library); - for (String primitive : primitives) { + for(String primitive : primitives){ unqualifiedToQualifiedMap.put(primitive, primitive); } library.lock(); @@ -94,65 +89,65 @@ public static TypeLibrary buildClassLibrary(@NotNull JavacNode context) { } @Contract("null -> null; !null -> !null") - public static JavacNode extractCompilationUnit(JavacNode javacNode) { - if (javacNode == null) return null; + public static JavacNode extractCompilationUnit(JavacNode javacNode){ + if(javacNode == null) return null; return javacNode.top(); } - public static String canonicalFullname(JavacNode typeNode) { + public static String canonicalFullname(JavacNode typeNode){ return mirror(typeNode).toString(); } - public static String reflectionFullname(JavacNode typeNode) { + public static String reflectionFullname(JavacNode typeNode){ return mirror(typeNode).tsym.flatName().toString(); } @NotNull - public static CompileBodyVisitor transformer(JavacNode typeNode) { + public static CompileBodyVisitor transformer(JavacNode typeNode){ return new CompileBodyVisitor( - typeNode.getTreeMaker(), - typeNode.getAst(), - typeNode.getContext() + typeNode.getTreeMaker(), + typeNode.getAst(), + typeNode.getContext() ); } @NotNull - public static JavacResolution resolution(Context context) { + public static JavacResolution resolution(Context context){ JavacResolution javacResolution = context.get(JavacResolution.class); - if (javacResolution == null) { + if(javacResolution == null){ context.put(JavacResolution.class, javacResolution = new JavacResolution(context)); } return javacResolution; } - public static U resolveSym(JavacNode node) { + public static U resolveSym(JavacNode node){ JavacResolution resolution = resolution(node.getContext()); //noinspection unchecked - return (U) resolution.resolveMethodMember(node).get(node.get()); + return (U)resolution.resolveMethodMember(node).get(node.get()); } - public static T setGeneratedBy(T node, JavacNode contextNode, JCTree sourceTree) { - if (node == null) return null; - if (sourceTree == null) { + public static T setGeneratedBy(T node, JavacNode contextNode, JCTree sourceTree){ + if(node == null) return null; + if(sourceTree == null){ JavacAugments.JCTree_generatedNode.clear(node); return node; } JavacAugments.JCTree_generatedNode.set(node, sourceTree); - if (JavacAugments.JCTree_keepPosition.get(node)) { + if(JavacAugments.JCTree_keepPosition.get(node)){ return node; } - if (JavacHandlerUtil.inNetbeansEditor(contextNode.getContext()) && !JavacHandlerUtil.isParameter(node)) { + if(JavacHandlerUtil.inNetbeansEditor(contextNode.getContext()) && !JavacHandlerUtil.isParameter(node)){ return node; } node.pos = sourceTree.getPreferredPosition(); - Javac.storeEnd(node, contextNode.getEndPosition(sourceTree), (JCTree.JCCompilationUnit) (contextNode.top()).get()); + Javac.storeEnd(node, contextNode.getEndPosition(sourceTree), (JCTree.JCCompilationUnit)(contextNode.top()).get()); return node; } - public static String methodSymbolString(ContextLibrary library, JCTree.JCMethodDecl decl) { - if (decl == null) return null; + public static String methodSymbolString(ContextLibrary library, JCTree.JCMethodDecl decl){ + if(decl == null) return null; String params = StreamEx.of(decl.getParameters()) .map(JCTree.JCVariableDecl::getType) diff --git a/annotations/src/main/java/omaloon/annotations/AutoImplement.java b/annotations/src/main/java/omaloon/annotations/AutoImplement.java index 7f58fafc..c70b1da0 100644 --- a/annotations/src/main/java/omaloon/annotations/AutoImplement.java +++ b/annotations/src/main/java/omaloon/annotations/AutoImplement.java @@ -1,14 +1,13 @@ package omaloon.annotations; -import java.lang.annotation.ElementType; -import java.lang.annotation.Target; +import java.lang.annotation.*; @Target(ElementType.TYPE) -public @interface AutoImplement { +public @interface AutoImplement{ @Target(ElementType.METHOD) - @interface NoInject { + @interface NoInject{ Class[] value(); } @@ -16,34 +15,37 @@ /** * This need ONLY for Annotation Processing, and it will be removed during compilation */ - interface Util { - static T Inject(Class type, Object... args) { + interface Util{ + static T Inject(Class type, Object... args){ return error(); } - static T Param(String paramName, String defaultExpression) { + static T Param(String paramName, String defaultExpression){ return error(); } - static T error() { + static T error(){ throw new RuntimeException("Why are you calling this?! This need ONLY for Annotation Processing and it will be removed during compilation"); } - @interface SetParam { + @interface SetParam{ String name(); + String value(); } } - public @interface Inject { + public @interface Inject{ InjectPosition value(); + boolean shouldAddSuper() default true; + enum InjectPosition{ - AfterSuper,BeforeSuper, + AfterSuper, BeforeSuper, - Head,Tail; + Head, Tail; } } } diff --git a/annotations/src/main/java/omaloon/annotations/Load.java b/annotations/src/main/java/omaloon/annotations/Load.java index aa00a5c1..117bebcd 100644 --- a/annotations/src/main/java/omaloon/annotations/Load.java +++ b/annotations/src/main/java/omaloon/annotations/Load.java @@ -1,13 +1,10 @@ package omaloon.annotations; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; +import java.lang.annotation.*; @Target(ElementType.FIELD) @Retention(RetentionPolicy.SOURCE) -public @interface Load { +public @interface Load{ /** * The region name to load. Variables can be used: * "@" -> block name diff --git a/annotations/src/main/java/omaloon/annotations/RemoveFromCompilation.java b/annotations/src/main/java/omaloon/annotations/RemoveFromCompilation.java index d8adda1d..90c6416b 100644 --- a/annotations/src/main/java/omaloon/annotations/RemoveFromCompilation.java +++ b/annotations/src/main/java/omaloon/annotations/RemoveFromCompilation.java @@ -1,8 +1,7 @@ package omaloon.annotations; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.*; @Retention(RetentionPolicy.SOURCE) -public @interface RemoveFromCompilation { +public @interface RemoveFromCompilation{ } diff --git a/annotations/src/main/java/omaloon/annotations/Starter.java b/annotations/src/main/java/omaloon/annotations/Starter.java index d24e9cb7..5199ad2b 100644 --- a/annotations/src/main/java/omaloon/annotations/Starter.java +++ b/annotations/src/main/java/omaloon/annotations/Starter.java @@ -1,53 +1,46 @@ package omaloon.annotations; -import asmlib.annotations.LombokPluginStarter; -import asmlib.annotations.Permit; - -import java.lang.invoke.MethodHandle; -import java.lang.invoke.MethodHandles; -import java.lang.invoke.MethodHandles.Lookup; - +import asmlib.annotations.*; import com.sun.tools.javac.code.*; import com.sun.tools.javac.code.Source.*; -import javax.annotation.processing.*; -import javax.lang.model.*; -import javax.lang.model.element.*; import java.lang.invoke.*; import java.lang.invoke.MethodHandles.*; -import java.util.*; import static com.sun.tools.javac.code.Source.Feature.*; -public class Starter extends LombokPluginStarter { +public class Starter extends LombokPluginStarter{ static{ initSelf(omaloon.annotations.Starter.class); } + static{ try{ // Get the trusted private lookup. - Lookup lookup = (Lookup) Permit.getField(Lookup.class, "IMPL_LOOKUP").get(null); + Lookup lookup = (Lookup)Permit.getField(Lookup.class, "IMPL_LOOKUP").get(null); // Get the minimum level setter, to force certain features to qualify as a Java 8 feature. MethodHandle set = lookup.findSetter(Feature.class, "minLevel", Source.class); // Downgrade most Java 8-compatible features. for(Feature feature : new Feature[]{ - EFFECTIVELY_FINAL_VARIABLES_IN_TRY_WITH_RESOURCES, - PRIVATE_SAFE_VARARGS, - DIAMOND_WITH_ANONYMOUS_CLASS_CREATION, - LOCAL_VARIABLE_TYPE_INFERENCE, - VAR_SYNTAX_IMPLICIT_LAMBDAS, - SWITCH_MULTIPLE_CASE_LABELS, - SWITCH_RULE, - SWITCH_EXPRESSION, - TEXT_BLOCKS, - PATTERN_MATCHING_IN_INSTANCEOF, - REIFIABLE_TYPES_INSTANCEOF - }) set.invokeExact(feature, Source.JDK8); + EFFECTIVELY_FINAL_VARIABLES_IN_TRY_WITH_RESOURCES, + PRIVATE_SAFE_VARARGS, + DIAMOND_WITH_ANONYMOUS_CLASS_CREATION, + LOCAL_VARIABLE_TYPE_INFERENCE, + VAR_SYNTAX_IMPLICIT_LAMBDAS, + SWITCH_MULTIPLE_CASE_LABELS, + SWITCH_RULE, + SWITCH_EXPRESSION, + TEXT_BLOCKS, + PATTERN_MATCHING_IN_INSTANCEOF, + REIFIABLE_TYPES_INSTANCEOF + }) + set.invokeExact(feature, Source.JDK8); }catch(Throwable t){ throw new RuntimeException(t); } } + @Override public String dontForgetToInitSelfInStatic(){ return "ok"; diff --git a/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/AutoImplContext.java b/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/AutoImplContext.java index 79beca29..9183ca12 100644 --- a/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/AutoImplContext.java +++ b/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/AutoImplContext.java @@ -1,26 +1,24 @@ package omaloon.annotations.lombok.autoimpl; -import bytelogic.lombok.util.GeneratedByVisitor; -import com.sun.tools.javac.tree.JCTree; -import lombok.AccessLevel; -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.experimental.FieldDefaults; -import lombok.javac.JavacNode; +import bytelogic.lombok.util.*; +import com.sun.tools.javac.tree.*; +import lombok.*; +import lombok.experimental.*; +import lombok.javac.*; -import java.util.Map; +import java.util.*; @AllArgsConstructor @Builder @FieldDefaults(level = AccessLevel.PUBLIC) -public class AutoImplContext { +public class AutoImplContext{ Map paramMap; JavacNode callerTypeNode; JavacNode callerMethodNode; JCTree.JCExpression producerNode; boolean justCreated; - public GeneratedByVisitor generatedBy() { + public GeneratedByVisitor generatedBy(){ return new GeneratedByVisitor(callerTypeNode, producerNode); } } diff --git a/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/AutoImplUtil.java b/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/AutoImplUtil.java index 5a6b527e..84553f5a 100644 --- a/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/AutoImplUtil.java +++ b/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/AutoImplUtil.java @@ -1,14 +1,14 @@ package omaloon.annotations.lombok.autoimpl; -import com.sun.tools.javac.tree.JCTree; -import com.sun.tools.javac.util.ListBuffer; -import omaloon.annotations.AutoImplement; +import com.sun.tools.javac.tree.*; +import com.sun.tools.javac.util.*; +import omaloon.annotations.*; -public class AutoImplUtil { - public static void removeAutoImplAnnos(JCTree.JCModifiers mods) { +public class AutoImplUtil{ + public static void removeAutoImplAnnos(JCTree.JCModifiers mods){ ListBuffer newAnnotations = new ListBuffer<>(); - for (JCTree.JCAnnotation annotation : mods.annotations) { - if (annotation.attribute.type.toString().startsWith(AutoImplement.class.getCanonicalName())) + for(JCTree.JCAnnotation annotation : mods.annotations){ + if(annotation.attribute.type.toString().startsWith(AutoImplement.class.getCanonicalName())) continue; newAnnotations.add(annotation); } diff --git a/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/CleanupHandler.java b/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/CleanupHandler.java index 96d3c3b1..51ebe274 100644 --- a/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/CleanupHandler.java +++ b/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/CleanupHandler.java @@ -1,30 +1,26 @@ package omaloon.annotations.lombok.autoimpl; -import com.sun.tools.javac.code.Flags; -import com.sun.tools.javac.tree.JCTree; -import com.sun.tools.javac.util.List; -import lombok.AllArgsConstructor; -import lombok.core.AlreadyHandledAnnotations; -import lombok.core.AnnotationValues; -import lombok.core.HandlerPriority; -import lombok.javac.JavacAnnotationHandler; -import lombok.javac.JavacNode; -import omaloon.annotations.AutoImplement; -import one.util.streamex.StreamEx; +import com.sun.tools.javac.code.*; +import com.sun.tools.javac.tree.*; +import com.sun.tools.javac.util.*; +import lombok.core.*; +import lombok.javac.*; +import omaloon.annotations.*; +import one.util.streamex.*; @AlreadyHandledAnnotations -public class CleanupHandler extends JavacAnnotationHandler { +public class CleanupHandler extends JavacAnnotationHandler{ @Override - public void handle(AnnotationValues annotationValues, JCTree.JCAnnotation jcAnnotation, JavacNode javacNode) { - JCTree.JCClassDecl decl = (JCTree.JCClassDecl) javacNode.up().get(); - decl.defs=List.from(StreamEx.of(decl.defs).filter(it->!(it instanceof JCTree.JCVariableDecl))); - for (JCTree def : decl.defs) { - if(!(def instanceof JCTree.JCMethodDecl methodDecl))continue; + public void handle(AnnotationValues annotationValues, JCTree.JCAnnotation jcAnnotation, JavacNode javacNode){ + JCTree.JCClassDecl decl = (JCTree.JCClassDecl)javacNode.up().get(); + decl.defs = List.from(StreamEx.of(decl.defs).filter(it -> !(it instanceof JCTree.JCVariableDecl))); + for(JCTree def : decl.defs){ + if(!(def instanceof JCTree.JCMethodDecl methodDecl)) continue; AutoImplUtil.removeAutoImplAnnos(methodDecl.mods); - if ((methodDecl.mods.flags& Flags.DEFAULT)==0) continue; - methodDecl.mods.flags&=~Flags.DEFAULT; - methodDecl.body=null; + if((methodDecl.mods.flags & Flags.DEFAULT) == 0) continue; + methodDecl.mods.flags &= ~Flags.DEFAULT; + methodDecl.body = null; } javacNode.getAst().setChanged(); } diff --git a/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/HierarchyMarker.java b/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/HierarchyMarker.java index 74a6649f..1bc83180 100644 --- a/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/HierarchyMarker.java +++ b/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/HierarchyMarker.java @@ -1,54 +1,49 @@ package omaloon.annotations.lombok.autoimpl; -import bytelogic.lombok.hierarchy.CollectedHierarchyInfo; -import bytelogic.lombok.hierarchy.info.ClassInfo; -import bytelogic.lombok.hierarchy.info.InfoKey; -import bytelogic.lombok.hierarchy.info.InterfaceInfo; -import bytelogic.lombok.util.Util; -import com.sun.source.util.Trees; -import com.sun.tools.javac.tree.JCTree.JCClassDecl; -import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; -import lombok.core.HandlerPriority; -import lombok.javac.JavacASTAdapter; -import lombok.javac.JavacNode; -import lombok.javac.ResolutionResetNeeded; - -import java.util.ArrayList; +import bytelogic.lombok.hierarchy.*; +import bytelogic.lombok.hierarchy.info.*; +import bytelogic.lombok.util.*; +import com.sun.source.util.*; +import com.sun.tools.javac.tree.JCTree.*; +import lombok.core.*; +import lombok.javac.*; + +import java.util.*; import static bytelogic.lombok.util.Util.mirror; //0b10000000000000000000000000000010 @HandlerPriority(value = -5) @ResolutionResetNeeded -public class HierarchyMarker extends JavacASTAdapter { +public class HierarchyMarker extends JavacASTAdapter{ public static InfoKey hasSavingProcKey = new InfoKey<>(); Trees trees; @Override - public void visitCompilationUnit(JavacNode top, JCCompilationUnit unit) { + public void visitCompilationUnit(JavacNode top, JCCompilationUnit unit){ super.visitCompilationUnit(top, unit); } @Override - public void endVisitCompilationUnit(JavacNode top, JCCompilationUnit unit) { + public void endVisitCompilationUnit(JavacNode top, JCCompilationUnit unit){ super.endVisitCompilationUnit(top, unit); } @Override - public void visitType(JavacNode typeNode, JCClassDecl type) { - if (typeNode.getElement() == null) return;//Anonymous classes - if (!typeNode.getName().equals("CustomSaveBuilding") || !Util.isInterface(type.mods)) return; + public void visitType(JavacNode typeNode, JCClassDecl type){ + if(typeNode.getElement() == null) return;//Anonymous classes + if(!typeNode.getName().equals("CustomSaveBuilding") || !Util.isInterface(type.mods)) return; InterfaceInfo interfaceInfo = CollectedHierarchyInfo.interfaceInfo(mirror(typeNode).toString()); ArrayList implementedClasses = CollectedHierarchyInfo.collectAllImpl(interfaceInfo); - for (ClassInfo info : implementedClasses) + for(ClassInfo info : implementedClasses) info.put(hasSavingProcKey, true); } @Override - public void setTrees(Trees trees) { + public void setTrees(Trees trees){ this.trees = (trees); } } diff --git a/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/ImplMarker.java b/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/ImplMarker.java index 80e0fadb..1166b2a1 100644 --- a/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/ImplMarker.java +++ b/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/ImplMarker.java @@ -1,31 +1,27 @@ package omaloon.annotations.lombok.autoimpl; -import bytelogic.lombok.hierarchy.CollectedHierarchyInfo; -import bytelogic.lombok.hierarchy.info.InfoKey; -import bytelogic.lombok.hierarchy.info.InterfaceInfo; -import com.sun.tools.javac.tree.JCTree; -import lombok.core.AnnotationValues; -import lombok.core.HandlerPriority; -import lombok.javac.JavacAnnotationHandler; -import lombok.javac.JavacNode; -import lombok.javac.ResolutionResetNeeded; -import omaloon.annotations.AutoImplement; -import omaloon.annotations.lombok.autoimpl.info.AutoImplInformation; +import bytelogic.lombok.hierarchy.*; +import bytelogic.lombok.hierarchy.info.*; +import com.sun.tools.javac.tree.*; +import lombok.core.*; +import lombok.javac.*; +import omaloon.annotations.*; +import omaloon.annotations.lombok.autoimpl.info.*; //0b10000000000000000000000000000010 -@HandlerPriority(value = -10,subValue = 10) +@HandlerPriority(value = -10, subValue = 10) @ResolutionResetNeeded -public class ImplMarker extends JavacAnnotationHandler { +public class ImplMarker extends JavacAnnotationHandler{ public static InfoKey isAutoImpl = new InfoKey<>(); - static boolean hasAutoImplData(InterfaceInfo it) { + static boolean hasAutoImplData(InterfaceInfo it){ return it.has(isAutoImpl); } @Override - public void handle(AnnotationValues annotationValues, JCTree.JCAnnotation jcAnnotation, JavacNode annotationNode) { + public void handle(AnnotationValues annotationValues, JCTree.JCAnnotation jcAnnotation, JavacNode annotationNode){ ImplProcessor.setUpdated(); CollectedHierarchyInfo.interfaceInfo(annotationNode.up()).put(isAutoImpl, - AutoImplInformation.build(annotationValues,jcAnnotation,annotationNode)); + AutoImplInformation.build(annotationValues, jcAnnotation, annotationNode)); } } diff --git a/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/ImplProcessor.java b/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/ImplProcessor.java index 8f5de906..358fe4d7 100644 --- a/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/ImplProcessor.java +++ b/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/ImplProcessor.java @@ -1,58 +1,45 @@ package omaloon.annotations.lombok.autoimpl; -import bytelogic.lombok.hierarchy.CollectedHierarchyInfo; -import bytelogic.lombok.hierarchy.info.AbstractInfo; -import bytelogic.lombok.hierarchy.info.ClassInfo; -import bytelogic.lombok.hierarchy.info.InterfaceInfo; -import bytelogic.lombok.util.ContextLibrary; -import bytelogic.lombok.util.Util; -import com.sun.tools.javac.code.Flags; -import com.sun.tools.javac.tree.JCTree; -import com.sun.tools.javac.tree.TreeCopier; -import com.sun.tools.javac.tree.TreeMaker; -import lombok.AllArgsConstructor; -import lombok.NonNull; +import bytelogic.lombok.hierarchy.*; +import bytelogic.lombok.hierarchy.info.*; +import bytelogic.lombok.util.*; +import com.sun.tools.javac.code.*; +import com.sun.tools.javac.tree.*; +import lombok.*; import lombok.core.*; -import lombok.javac.JavacAST; -import lombok.javac.JavacASTAdapter; -import lombok.javac.JavacNode; -import lombok.javac.JavacTreeMaker; -import lombok.javac.handlers.JavacHandlerUtil; -import omaloon.annotations.AutoImplement; -import omaloon.annotations.lombok.autoimpl.info.AutoImplInformation; -import omaloon.annotations.lombok.autoimpl.info.MethodInfo; -import omaloon.annotations.lombok.autoimpl.info.TypeInliner; -import one.util.streamex.EntryStream; -import one.util.streamex.StreamEx; -import org.jetbrains.annotations.NotNull; +import lombok.javac.*; +import lombok.javac.handlers.*; +import omaloon.annotations.*; +import omaloon.annotations.lombok.autoimpl.info.*; +import one.util.streamex.*; +import org.jetbrains.annotations.*; import java.util.*; -import java.util.function.BiConsumer; -import java.util.function.Function; +import java.util.function.*; import static bytelogic.lombok.hierarchy.CollectedHierarchyInfo.interfaces; import static bytelogic.lombok.util.Util.canonicalFullname; @HandlerPriority(value = -10, subValue = 20) -public class ImplProcessor extends JavacASTAdapter { +public class ImplProcessor extends JavacASTAdapter{ private static boolean updated; private Set autoImplClasses; private TypeLibrary interfacesLibrary; private Map> simpleInterfaceToAutoImpl; - public static void setUpdated() { + public static void setUpdated(){ updated = true; } - private static ArrayList flatInterfaceSuper(InterfaceInfo info) { + private static ArrayList flatInterfaceSuper(InterfaceInfo info){ ArrayList flatten = new ArrayList<>(); - BiConsumer consumer = new BiConsumer<>() { + BiConsumer consumer = new BiConsumer<>(){ Set nameSet = new HashSet<>(); @Override - public void accept(String s, InterfaceInfo info) { - if (info == CollectedHierarchyInfo.interfacesRoot || !nameSet.add(s)) return; + public void accept(String s, InterfaceInfo info){ + if(info == CollectedHierarchyInfo.interfacesRoot || !nameSet.add(s)) return; flatten.add(info); info.supertypes.forEach(this); @@ -63,18 +50,18 @@ public void accept(String s, InterfaceInfo info) { } @NotNull - private static ArrayList findNoInject(JavacNode typeNode, JCTree.JCModifiers mods) { + private static ArrayList findNoInject(JavacNode typeNode, JCTree.JCModifiers mods){ ArrayList list = new ArrayList<>(); ContextLibrary classLibrary = ContextLibrary - .ofClasses(typeNode) - .withResolvedParts(null); + .ofClasses(typeNode) + .withResolvedParts(null); - for (JCTree.JCAnnotation annotation : mods.annotations) { - if (!annotation.annotationType.toString().endsWith("NoInject")) continue; + for(JCTree.JCAnnotation annotation : mods.annotations){ + if(!annotation.annotationType.toString().endsWith("NoInject")) continue; AnnotationValues values = JavacHandlerUtil.createAnnotation(AutoImplement.NoInject.class, typeNode.getNodeFor(annotation)); String postfix = ".class"; - for (String classGuessDotClass : values.getRawExpressions("value")) { - if (!classGuessDotClass.endsWith(postfix)) continue; + for(String classGuessDotClass : values.getRawExpressions("value")){ + if(!classGuessDotClass.endsWith(postfix)) continue; list.add(classLibrary.resolveFull(classGuessDotClass.substring(0, classGuessDotClass.length() - postfix.length()))); } } @@ -82,94 +69,94 @@ private static ArrayList findNoInject(JavacNode typeNode, JCTree.JCModif } @Override - public void visitCompilationUnit(JavacNode top, JCTree.JCCompilationUnit unit) { - if (!updated) return; + public void visitCompilationUnit(JavacNode top, JCTree.JCCompilationUnit unit){ + if(!updated) return; updated = false; interfacesLibrary = new TypeLibrary(); interfaces() - .values() - .map(AbstractInfo::getFlatName) - .forEach(interfacesLibrary::addType); + .values() + .map(AbstractInfo::getFlatName) + .forEach(interfacesLibrary::addType); interfacesLibrary.lock(); autoImplClasses = interfaces() - .values() - .filter(ImplMarker::hasAutoImplData) - .map(CollectedHierarchyInfo::collectAllImpl) - .flatMap(StreamEx::of) - .map(ClassInfo::getName) - .toSet(); + .values() + .filter(ImplMarker::hasAutoImplData) + .map(CollectedHierarchyInfo::collectAllImpl) + .flatMap(StreamEx::of) + .map(ClassInfo::getName) + .toSet(); simpleInterfaceToAutoImpl = interfaces() - .values() - - //TODO guess alphabetic order moment - .mapToEntry(ImplProcessor::flatInterfaceSuper) - .mapValues(it -> it - .stream() - .filter(ImplMarker::hasAutoImplData) - .toList() - ).filterValues(it -> !it.isEmpty()) - .mapValues(ArrayList::new) - .toMap(); + .values() + + //TODO guess alphabetic order moment + .mapToEntry(ImplProcessor::flatInterfaceSuper) + .mapValues(it -> it + .stream() + .filter(ImplMarker::hasAutoImplData) + .toList() + ).filterValues(it -> !it.isEmpty()) + .mapValues(ArrayList::new) + .toMap(); } @Override - public void visitType(JavacNode typeNode, JCTree.JCClassDecl type) { - if (typeNode.getElement() == null) { + public void visitType(JavacNode typeNode, JCTree.JCClassDecl type){ + if(typeNode.getElement() == null){ return; } - if (!autoImplClasses.contains(canonicalFullname(typeNode))) return; + if(!autoImplClasses.contains(canonicalFullname(typeNode))) return; InfoAndPos[] interfaceInfos = StreamEx - .of(type.implementing) - .mapToEntry(Function.identity()) - .mapKeys(Object::toString) - .filterKeys(string -> !string.contains("<")) //TODO Generic implement - .mapKeys(it -> Paths.fullifyName(typeNode, it, interfacesLibrary)) - .mapKeys(CollectedHierarchyInfo::interfaceInfo) - .nonNullKeys() - .mapKeys(simpleInterfaceToAutoImpl::get) - .flatMapKeys(StreamEx::of) - .distinctKeys() - .mapKeyValue(InfoAndPos::new) - .toArray(InfoAndPos[]::new); - - for (InfoAndPos info : interfaceInfos) { - - if (findNoInject(typeNode, type.mods).contains(info.info.name)) continue; + .of(type.implementing) + .mapToEntry(Function.identity()) + .mapKeys(Object::toString) + .filterKeys(string -> !string.contains("<")) //TODO Generic implement + .mapKeys(it -> Paths.fullifyName(typeNode, it, interfacesLibrary)) + .mapKeys(CollectedHierarchyInfo::interfaceInfo) + .nonNullKeys() + .mapKeys(simpleInterfaceToAutoImpl::get) + .flatMapKeys(StreamEx::of) + .distinctKeys() + .mapKeyValue(InfoAndPos::new) + .toArray(InfoAndPos[]::new); + + for(InfoAndPos info : interfaceInfos){ + + if(findNoInject(typeNode, type.mods).contains(info.info.name)) continue; implement(info.info, info.producer, typeNode, type); } } - private void implement(InterfaceInfo info, @NonNull JCTree.JCExpression producer, JavacNode typeNode, JCTree.JCClassDecl type) { + private void implement(InterfaceInfo info, @NonNull JCTree.JCExpression producer, JavacNode typeNode, JCTree.JCClassDecl type){ AutoImplInformation information = info.get(ImplMarker.isAutoImpl); Map>> childrenMap = StreamEx - .of(typeNode.down().iterator()) - .mapToEntry(LombokNode::getKind, Function.identity()) - .sortedBy(Map.Entry::getKey) - .collapseKeys() - .mapValues(StreamEx::of) - .mapValues(it -> it.mapToEntry(JavacNode::getName, Function.identity())) - .mapValues(it -> it.collapseKeys().sortedBy(Map.Entry::getKey).toMap()) - .toMap(); + .of(typeNode.down().iterator()) + .mapToEntry(LombokNode::getKind, Function.identity()) + .sortedBy(Map.Entry::getKey) + .collapseKeys() + .mapValues(StreamEx::of) + .mapValues(it -> it.mapToEntry(JavacNode::getName, Function.identity())) + .mapValues(it -> it.collapseKeys().sortedBy(Map.Entry::getKey).toMap()) + .toMap(); Map fields = EntryStream - .of(childrenMap.getOrDefault(AST.Kind.FIELD, new HashMap<>())) - .mapValues(it -> it.get(0)) - .toMap(); - for (Map.Entry entry : information.fields.entrySet()) { + .of(childrenMap.getOrDefault(AST.Kind.FIELD, new HashMap<>())) + .mapValues(it -> it.get(0)) + .toMap(); + for(Map.Entry entry : information.fields.entrySet()){ JavacNode existed = fields.get(entry.getKey()); AutoImplInformation.FieldInfo fieldInfo = entry.getValue(); - if (existed != null) { - if (existed.hasAnnotation(AutoImplement.NoInject.class)) { + if(existed != null){ + if(existed.hasAnnotation(AutoImplement.NoInject.class)){ continue; } existed.addError("Cannot insert field %s.%s. Field with this name already exists.".formatted( - fieldInfo.intefaceName, fieldInfo.name + fieldInfo.intefaceName, fieldInfo.name )); continue; } @@ -183,26 +170,26 @@ private void implement(InterfaceInfo info, @NonNull JCTree.JCExpression producer JCTree.JCVariableDecl decl = TypeInliner.copyWithInlineTypes(fieldInfo.fieldNode); JCTree.JCVariableDecl newChild = m.VarDef( - m.Modifiers(decl.mods.flags & ~Flags.STATIC), - ast.toName(fieldInfo.name), - copier.copy(decl.vartype), - copier.copy(decl.init) + m.Modifiers(decl.mods.flags & ~Flags.STATIC), + ast.toName(fieldInfo.name), + copier.copy(decl.vartype), + copier.copy(decl.init) ); type.defs = type.defs.append(newChild); typeNode.add( - newChild, - AST.Kind.FIELD); + newChild, + AST.Kind.FIELD); } Map methods = EntryStream - .of(childrenMap.get(AST.Kind.METHOD)) - .values() - .flatMap(StreamEx::of) - .mapToEntry(it -> Util.methodDesc(it, (JCTree.JCMethodDecl) it.get()), Function.identity()) - .toMap(); + .of(childrenMap.get(AST.Kind.METHOD)) + .values() + .flatMap(StreamEx::of) + .mapToEntry(it -> Util.methodDesc(it, (JCTree.JCMethodDecl)it.get()), Function.identity()) + .toMap(); - for (Map.Entry entry : information.methods.entrySet()) { + for(Map.Entry entry : information.methods.entrySet()){ String methodDecs = entry.getKey(); MethodInfo methodInfo = entry.getValue(); JavacNode existed = methods.get(methodDecs); @@ -211,48 +198,48 @@ private void implement(InterfaceInfo info, @NonNull JCTree.JCExpression producer AutoImplContext.AutoImplContextBuilder contextBuilder = AutoImplContext - .builder() - .callerTypeNode(typeNode) - .producerNode(producer); - if (existed == null) { + .builder() + .callerTypeNode(typeNode) + .producerNode(producer); + if(existed == null){ contextBuilder - .paramMap(collectParams(typeNode)) - .justCreated(true); + .paramMap(collectParams(typeNode)) + .justCreated(true); decl = methodInfo.make(contextBuilder.build()); JavacHandlerUtil.injectMethod(typeNode, decl); JavacNode nodeFor = typeNode.getNodeFor(decl); methods.put(methodDecs, nodeFor); contextBuilder.callerMethodNode(nodeFor); - } else { + }else{ contextBuilder - .paramMap(collectParams(existed)) - .callerMethodNode(existed) - .justCreated(false); - decl = (JCTree.JCMethodDecl) existed.get(); - if (findNoInject(existed, decl.mods).contains(info.name)) continue; + .paramMap(collectParams(existed)) + .callerMethodNode(existed) + .justCreated(false); + decl = (JCTree.JCMethodDecl)existed.get(); + if(findNoInject(existed, decl.mods).contains(info.name)) continue; } methodInfo.join(decl, contextBuilder.build()); } } - private Map collectParams(JavacNode typeNode) { + private Map collectParams(JavacNode typeNode){ JavacNode node = typeNode; Map map = new HashMap<>(); JavacAST ast = typeNode.getAst(); - while (node != null) { + while(node != null){ JCTree.JCModifiers mods = - switch (typeNode.getKind()) { - case TYPE -> ((JCTree.JCClassDecl) typeNode.get()).mods; - case FIELD -> ((JCTree.JCVariableDecl) typeNode.get()).mods; - case METHOD -> ((JCTree.JCMethodDecl) typeNode.get()).mods; - case COMPILATION_UNIT, INITIALIZER, ANNOTATION, ARGUMENT, LOCAL, STATEMENT, TYPE_USE -> null; - }; - if (mods != null) { - - for (JCTree.JCAnnotation annotation : mods.annotations) { + switch(typeNode.getKind()){ + case TYPE -> ((JCTree.JCClassDecl)typeNode.get()).mods; + case FIELD -> ((JCTree.JCVariableDecl)typeNode.get()).mods; + case METHOD -> ((JCTree.JCMethodDecl)typeNode.get()).mods; + case COMPILATION_UNIT, INITIALIZER, ANNOTATION, ARGUMENT, LOCAL, STATEMENT, TYPE_USE -> null; + }; + if(mods != null){ + + for(JCTree.JCAnnotation annotation : mods.annotations){ JavacNode annotationNode = ast.get(annotation); - if (!JavacHandlerUtil.annotationTypeMatches(AutoImplement.Util.SetParam.class, annotationNode)) + if(!JavacHandlerUtil.annotationTypeMatches(AutoImplement.Util.SetParam.class, annotationNode)) continue; AutoImplement.Util.SetParam setParam = AnnotationValues.of(AutoImplement.Util.SetParam.class, annotationNode).getInstance(); map.put(setParam.name(), setParam.value()); @@ -264,7 +251,7 @@ private Map collectParams(JavacNode typeNode) { } @AllArgsConstructor - static class InfoAndPos { + static class InfoAndPos{ InterfaceInfo info; JCTree.JCExpression producer; } diff --git a/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/Paths.java b/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/Paths.java index ef01706d..e51a1230 100644 --- a/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/Paths.java +++ b/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/Paths.java @@ -1,26 +1,26 @@ package omaloon.annotations.lombok.autoimpl; -import lombok.core.TypeLibrary; -import lombok.javac.JavacNode; -import omaloon.annotations.AutoImplement; +import lombok.core.*; +import lombok.javac.*; +import omaloon.annotations.*; -public class Paths { +public class Paths{ public static final String PARAM_METHOD = AutoImplement.Util.class.getCanonicalName() + ".Param"; public static final String INJECT_METHOD = AutoImplement.Util.class.getCanonicalName() + ".Inject"; - public static final TypeLibrary library = new TypeLibrary() {{ + public static final TypeLibrary library = new TypeLibrary(){{ addType(AutoImplement.Util.class.getName() + "$Param"); addType(AutoImplement.Util.class.getName() + "$Inject"); lock(); }}; - public static boolean expressionMatch(JavacNode context, String expressionToCheck, String expected) { + public static boolean expressionMatch(JavacNode context, String expressionToCheck, String expected){ String resolved = fullifyName(context, expressionToCheck, library); return resolved != null && resolved.equals(expected); } - public static String fullifyName(JavacNode context, String expressionToUnwrap, TypeLibrary library1) { + public static String fullifyName(JavacNode context, String expressionToUnwrap, TypeLibrary library1){ return context - .getImportListAsTypeResolver() - .typeRefToFullyQualifiedName(context, library1, expressionToUnwrap); + .getImportListAsTypeResolver() + .typeRefToFullyQualifiedName(context, library1, expressionToUnwrap); } } diff --git a/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/info/AutoImplInformation.java b/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/info/AutoImplInformation.java index 817ac30d..c7f23a4e 100644 --- a/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/info/AutoImplInformation.java +++ b/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/info/AutoImplInformation.java @@ -1,70 +1,66 @@ package omaloon.annotations.lombok.autoimpl.info; -import asmlib.lombok.javaparser.CompileBodyVisitor; -import com.sun.tools.javac.tree.JCTree; -import lombok.AccessLevel; -import lombok.AllArgsConstructor; -import lombok.NonNull; -import lombok.core.AST; -import lombok.core.AnnotationValues; -import lombok.core.LombokNode; -import lombok.experimental.FieldDefaults; -import lombok.javac.JavacNode; -import omaloon.annotations.AutoImplement; -import one.util.streamex.StreamEx; +import asmlib.lombok.javaparser.*; +import com.sun.tools.javac.tree.*; +import lombok.*; +import lombok.core.*; +import lombok.experimental.*; +import lombok.javac.*; +import omaloon.annotations.*; +import one.util.streamex.*; -import java.util.Map; -import java.util.function.Function; +import java.util.*; +import java.util.function.*; -public class AutoImplInformation { +public class AutoImplInformation{ public Map methods; public Map fields; - public static AutoImplInformation build(AnnotationValues annotationValues, JCTree.JCAnnotation jcAnnotation, JavacNode annotationNode) { + public static AutoImplInformation build(AnnotationValues annotationValues, JCTree.JCAnnotation jcAnnotation, JavacNode annotationNode){ AutoImplInformation information = new AutoImplInformation(); JavacNode typeNode = annotationNode.up(); CompileBodyVisitor transformer = new CompileBodyVisitor(typeNode.getTreeMaker(), typeNode.getAst(), typeNode.getContext()); information.methods = StreamEx - .of(typeNode.down().iterator()) - .filterBy(LombokNode::getKind, AST.Kind.METHOD) - .map(javacNode -> { - AnnotationValues foundAnnotation = javacNode.findAnnotation(AutoImplement.Inject.class); - AutoImplement.Inject annotationInstance = foundAnnotation == null ? null : foundAnnotation.getInstance(); - return MethodInfo.create( - typeNode, - javacNode, - annotationInstance - ); - }) - .mapToEntry(it -> it.info.descriptor, Function.identity()) - .toMap() + .of(typeNode.down().iterator()) + .filterBy(LombokNode::getKind, AST.Kind.METHOD) + .map(javacNode -> { + AnnotationValues foundAnnotation = javacNode.findAnnotation(AutoImplement.Inject.class); + AutoImplement.Inject annotationInstance = foundAnnotation == null ? null : foundAnnotation.getInstance(); + return MethodInfo.create( + typeNode, + javacNode, + annotationInstance + ); + }) + .mapToEntry(it -> it.info.descriptor, Function.identity()) + .toMap() ; information.fields = StreamEx - .of(typeNode.down().iterator()) - .filterBy(LombokNode::getKind, AST.Kind.FIELD) - .mapToEntry(JavacNode::getName, Function.identity()) - .mapValues(javacNode -> new FieldInfo( - typeNode.getName(), - typeNode, - javacNode.getName(), - cast(javacNode), - javacNode, - transformer - )) - .toMap(); + .of(typeNode.down().iterator()) + .filterBy(LombokNode::getKind, AST.Kind.FIELD) + .mapToEntry(JavacNode::getName, Function.identity()) + .mapValues(javacNode -> new FieldInfo( + typeNode.getName(), + typeNode, + javacNode.getName(), + cast(javacNode), + javacNode, + transformer + )) + .toMap(); return information; } - private static T cast(JavacNode javacNode) { - return (T) javacNode.get(); + private static T cast(JavacNode javacNode){ + return (T)javacNode.get(); } @AllArgsConstructor @FieldDefaults(level = AccessLevel.PUBLIC, makeFinal = true) - public static class FieldInfo { + public static class FieldInfo{ String intefaceName; JavacNode typeNode; String name; diff --git a/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/info/InlineApplyPrinter.java b/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/info/InlineApplyPrinter.java index 8bb2adb4..17891d5f 100644 --- a/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/info/InlineApplyPrinter.java +++ b/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/info/InlineApplyPrinter.java @@ -1,20 +1,18 @@ package omaloon.annotations.lombok.autoimpl.info; -import bytelogic.lombok.util.ContextLibrary; -import com.sun.tools.javac.tree.JCTree; -import com.sun.tools.javac.tree.Pretty; -import lombok.SneakyThrows; +import bytelogic.lombok.util.*; +import com.sun.tools.javac.tree.*; +import lombok.*; -import java.io.IOException; -import java.io.Writer; +import java.io.*; -public class InlineApplyPrinter extends Pretty { +public class InlineApplyPrinter extends Pretty{ final String expectedMethod; final ContextLibrary contextLibrary; final Handler handler; - public InlineApplyPrinter(Writer out, String expectedMethod, ContextLibrary contextLibrary, Handler handler) { + public InlineApplyPrinter(Writer out, String expectedMethod, ContextLibrary contextLibrary, Handler handler){ super(out, true); this.expectedMethod = expectedMethod; this.contextLibrary = contextLibrary; @@ -23,10 +21,10 @@ public InlineApplyPrinter(Writer out, String expectedMethod, ContextLibrary cont @SneakyThrows @Override - public void visitApply(JCTree.JCMethodInvocation tree) { + public void visitApply(JCTree.JCMethodInvocation tree){ String string = contextLibrary.resolveFull(tree.meth.toString()); - if (!expectedMethod.equals(string)) { + if(!expectedMethod.equals(string)){ super.visitApply(tree); return; } @@ -34,11 +32,11 @@ public void visitApply(JCTree.JCMethodInvocation tree) { } @Override - public void printExpr(JCTree tree) throws IOException { + public void printExpr(JCTree tree) throws IOException{ super.printExpr(tree); } - public interface Handler { + public interface Handler{ void handle(InlineApplyPrinter self, JCTree.JCMethodInvocation tree) throws IOException; } } diff --git a/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/info/MethodDeclarationInfo.java b/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/info/MethodDeclarationInfo.java index 9d907692..c3af6f9c 100644 --- a/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/info/MethodDeclarationInfo.java +++ b/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/info/MethodDeclarationInfo.java @@ -1,17 +1,16 @@ package omaloon.annotations.lombok.autoimpl.info; -import bytelogic.lombok.util.ContextLibrary; -import bytelogic.lombok.util.Util; -import com.sun.tools.javac.tree.JCTree; +import bytelogic.lombok.util.*; +import com.sun.tools.javac.tree.*; import lombok.*; -import lombok.core.TypeLibrary; -import lombok.experimental.FieldDefaults; -import lombok.javac.JavacNode; +import lombok.core.*; +import lombok.experimental.*; +import lombok.javac.*; @AllArgsConstructor @Getter @FieldDefaults(level = AccessLevel.PUBLIC, makeFinal = true) -public class MethodDeclarationInfo { +public class MethodDeclarationInfo{ public static final TypeLibrary EMPTY_LIB = new TypeLibrary(); public String name; @@ -23,16 +22,16 @@ public class MethodDeclarationInfo { ContextLibrary contextLibrary; public final String symbolString; - public static MethodDeclarationInfo make(JavacNode methodNode) { + public static MethodDeclarationInfo make(JavacNode methodNode){ ContextLibrary library = ContextLibrary.makeLib(methodNode, EMPTY_LIB); - JCTree.JCMethodDecl methodDecl = (JCTree.JCMethodDecl) methodNode.get(); + JCTree.JCMethodDecl methodDecl = (JCTree.JCMethodDecl)methodNode.get(); return new MethodDeclarationInfo( - methodNode.getName(), - Util.methodDesc(library, methodDecl), - methodNode, - methodDecl, - library, - Util.methodSymbolString(library,methodDecl) + methodNode.getName(), + Util.methodDesc(library, methodDecl), + methodNode, + methodDecl, + library, + Util.methodSymbolString(library, methodDecl) ); } } diff --git a/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/info/MethodInfo.java b/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/info/MethodInfo.java index 65e1921d..dd9d5d33 100644 --- a/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/info/MethodInfo.java +++ b/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/info/MethodInfo.java @@ -1,41 +1,29 @@ package omaloon.annotations.lombok.autoimpl.info; -import asmlib.lombok.javaparser.CompileBodyVisitor; -import bytelogic.lombok.util.ContextLibrary; -import bytelogic.lombok.util.GeneratedByVisitor; -import bytelogic.lombok.util.Util; -import com.sun.tools.javac.code.Flags; -import com.sun.tools.javac.code.Symbol; -import com.sun.tools.javac.parser.JavacParser; -import com.sun.tools.javac.parser.ParserFactory; -import com.sun.tools.javac.tree.JCTree; -import com.sun.tools.javac.tree.TreeCopier; -import com.sun.tools.javac.tree.TreeScanner; +import asmlib.lombok.javaparser.*; +import bytelogic.lombok.util.*; +import com.sun.tools.javac.code.*; +import com.sun.tools.javac.parser.*; +import com.sun.tools.javac.tree.*; import com.sun.tools.javac.util.List; -import com.sun.tools.javac.util.Names; +import com.sun.tools.javac.util.*; import lombok.*; -import lombok.javac.JavacAST; -import lombok.javac.JavacNode; -import lombok.javac.JavacResolution; -import omaloon.annotations.AutoImplement; -import omaloon.annotations.AutoImplement.Inject.InjectPosition; -import omaloon.annotations.lombok.autoimpl.AutoImplContext; -import omaloon.annotations.lombok.autoimpl.AutoImplUtil; -import omaloon.annotations.lombok.autoimpl.Paths; -import org.jetbrains.annotations.Nullable; - -import java.io.IOException; -import java.io.StringWriter; -import java.util.Collection; -import java.util.Map; -import java.util.function.Function; +import lombok.javac.*; +import omaloon.annotations.*; +import omaloon.annotations.AutoImplement.Inject.*; +import omaloon.annotations.lombok.autoimpl.*; +import org.jetbrains.annotations.*; + +import java.io.*; +import java.util.*; +import java.util.function.*; import static bytelogic.lombok.util.ContextLibrary.makeLib; import static one.util.streamex.StreamEx.of; @AllArgsConstructor @Getter -public class MethodInfo { +public class MethodInfo{ public final String interfaceFullName; public final JavacNode typeNode; @@ -47,104 +35,104 @@ public class MethodInfo { @Nullable AutoImplement.Inject inject; - public static MethodInfo create(JavacNode typeNode, JavacNode methodNode, AutoImplement.Inject inject) { + public static MethodInfo create(JavacNode typeNode, JavacNode methodNode, AutoImplement.Inject inject){ MethodDeclarationInfo info = MethodDeclarationInfo.make(methodNode); return new MethodInfo( - Util.canonicalFullname(typeNode), - typeNode, - info, - info.contextLibrary.resolution, - ParserFactory.instance(typeNode.getContext()), - Util.transformer(methodNode), - inject + Util.canonicalFullname(typeNode), + typeNode, + info, + info.contextLibrary.resolution, + ParserFactory.instance(typeNode.getContext()), + Util.transformer(methodNode), + inject ); } @Nullable - public static String extractString(JCTree.JCExpression jcExpression, JavacAST ast, String desc) { + public static String extractString(JCTree.JCExpression jcExpression, JavacAST ast, String desc){ String string; - if (!(jcExpression instanceof JCTree.JCLiteral literal)) { + if(!(jcExpression instanceof JCTree.JCLiteral literal)){ ast.get(jcExpression).addError("Only Literals allowed in " + desc); string = null; - } else { + }else{ string = literal.value.toString(); } return string; } - private boolean tryInjectPosition(JCTree.JCMethodDecl decl, AutoImplContext context, List newCode) { + private boolean tryInjectPosition(JCTree.JCMethodDecl decl, AutoImplContext context, List newCode){ boolean[] hasInject = {false}; ParserFactory parserFactory = ParserFactory.instance(context.callerMethodNode.getContext()); - TreeCopier copier = new TreeCopier<>(transformer.imaker) { + TreeCopier copier = new TreeCopier<>(transformer.imaker){ @Override - public T copy(T tree, Object o) { + public T copy(T tree, Object o){ super.copy(tree, o); return tree; } @Override - public List copy(List trees, Object o) { - if (trees.isEmpty() || trees.stream().filter(it -> it instanceof JCTree.JCStatement).count() != trees.length()) + public List copy(List trees, Object o){ + if(trees.isEmpty() || trees.stream().filter(it -> it instanceof JCTree.JCStatement).count() != trees.length()) return trees.map(this::copy); //noinspection unchecked - return (List) List.from(of((List) trees) - .limit(trees.length()) - .flatCollection(it -> { - if (!hasInject(context, it)) return List.of(copy(it)); - hasInject[0] = true; - StringWriter writer = new StringWriter(); - try { - new InlineApplyPrinter(writer, Paths.INJECT_METHOD, makeLib(context.callerMethodNode, Paths.library), (printer, tree) -> { - printer.printStats(newCode); - - }).printExpr(it); - } catch (IOException e) { - throw Lombok.sneakyThrow(e); - } - String input = "{\n" + writer + "\n}"; - JavacParser parser = parserFactory.newParser(input, true, true, true, false); - return ((JCTree.JCBlock) parser.parseStatement()).stats; - }) - .toArray(JCTree.JCStatement[]::new) + return (List)List.from(of((List)trees) + .limit(trees.length()) + .flatCollection(it -> { + if(!hasInject(context, it)) return List.of(copy(it)); + hasInject[0] = true; + StringWriter writer = new StringWriter(); + try{ + new InlineApplyPrinter(writer, Paths.INJECT_METHOD, makeLib(context.callerMethodNode, Paths.library), (printer, tree) -> { + printer.printStats(newCode); + + }).printExpr(it); + }catch(IOException e){ + throw Lombok.sneakyThrow(e); + } + String input = "{\n" + writer + "\n}"; + JavacParser parser = parserFactory.newParser(input, true, true, true, false); + return ((JCTree.JCBlock)parser.parseStatement()).stats; + }) + .toArray(JCTree.JCStatement[]::new) ); } }; decl.body.stats = copier.copy(decl.body.stats); - if (hasInject[0]) { + if(hasInject[0]){ context.callerMethodNode.getAst().setChanged(); } return hasInject[0]; } - private boolean hasInject(AutoImplContext context, JCTree tree) { + private boolean hasInject(AutoImplContext context, JCTree tree){ boolean[] hasInject = {false}; - tree.accept(new TreeScanner() { + tree.accept(new TreeScanner(){ @Override - public void scan(JCTree tree) { - if (!hasInject[0]) super.scan(tree); + public void scan(JCTree tree){ + if(!hasInject[0]) super.scan(tree); } @Override - public void scan(List trees) { + public void scan(List trees){ //TODO mayby just filter } @Override - public void visitApply(JCTree.JCMethodInvocation tree) { + public void visitApply(JCTree.JCMethodInvocation tree){ JavacNode tmpNode = context.callerMethodNode; - if (!Paths.expressionMatch(tmpNode, tree.meth.toString(), Paths.INJECT_METHOD)) { + if(!Paths.expressionMatch(tmpNode, tree.meth.toString(), Paths.INJECT_METHOD)){ super.visitApply(tree); return; } ContextLibrary library = ContextLibrary.ofClasses(tmpNode); - JCTree.JCFieldAccess access = (JCTree.JCFieldAccess) tree.args.get(0); + JCTree.JCFieldAccess access = (JCTree.JCFieldAccess)tree.args.get(0); String innerClass = library.className(access.selected); hasInject[0] |= interfaceFullName.equals(innerClass); } @@ -152,7 +140,7 @@ public void visitApply(JCTree.JCMethodInvocation tree) { return hasInject[0]; } - public JCTree.JCMethodDecl make(@NonNull AutoImplContext rawContext) { + public JCTree.JCMethodDecl make(@NonNull AutoImplContext rawContext){ JCTree.JCMethodDecl declaration = TypeInliner.copyWithInlineTypes(info.node); AutoImplUtil.removeAutoImplAnnos(declaration.mods); @@ -160,45 +148,45 @@ public JCTree.JCMethodDecl make(@NonNull AutoImplContext rawContext) { declaration.mods.flags |= Flags.PUBLIC; - if (inject != null && inject.shouldAddSuper()) { + if(inject != null && inject.shouldAddSuper()){ var m = transformer.maker; m.at(rawContext.producerNode.getPreferredPosition()); Names names = Names.instance(typeNode.getContext()); declaration.body = m.Block(0, List.of( - m.Exec( - m.Apply( - declaration.typarams - .map(JCTree.JCTypeParameter::getName) - .map(m::Ident), - m.Select(m.Ident(names._super), declaration.name), - declaration.params.map(JCTree.JCVariableDecl::getName) - .map(m::Ident) - ) - ) + m.Exec( + m.Apply( + declaration.typarams + .map(JCTree.JCTypeParameter::getName) + .map(m::Ident), + m.Select(m.Ident(names._super), declaration.name), + declaration.params.map(JCTree.JCVariableDecl::getName) + .map(m::Ident) + ) + ) )); - } else { + }else{ declaration.body.stats = List.nil(); } rawContext.generatedBy().scan(declaration, null); return declaration; } - public void join(JCTree.JCMethodDecl existed, AutoImplContext context) { + public void join(JCTree.JCMethodDecl existed, AutoImplContext context){ JCTree.JCBlock body = existed.body; List preprocessed = prepareStats(context); - if (tryInjectPosition(existed, context, preprocessed)) { + if(tryInjectPosition(existed, context, preprocessed)){ return; } InjectPosition position; - if (inject == null) { + if(inject == null){ //TODO position = InjectPosition.Head; - } else { + }else{ position = inject.value(); } - Void nil = switch (position) { + Void nil = switch(position){ case Head -> { body.stats = body.stats.prependList(preprocessed); yield null; @@ -212,25 +200,25 @@ public void join(JCTree.JCMethodDecl existed, AutoImplContext context) { final JavacResolution resolution = getResolution(); final ContextLibrary library = info.contextLibrary; final String originalParams = of(info.decl.getParameters()) - .map(JCTree.JCVariableDecl::getType) - .map(library::className) - .joining(";"); + .map(JCTree.JCVariableDecl::getType) + .map(library::className) + .joining(";"); TreeCopier simpleCopier = new TreeCopier<>(transformer.imaker); boolean[] foundSuper = {false}; - TreeCopier copier = new TreeCopier<>(transformer.imaker) { + TreeCopier copier = new TreeCopier<>(transformer.imaker){ @SuppressWarnings("rawtypes") @Override - public List copy(List trees, Object object) { + public List copy(List trees, Object object){ - Function tCollectionFunction = (Function>) it__ -> { - if (!(it__ instanceof JCTree.JCExpressionStatement it)) return List.of(it__); + Function tCollectionFunction = (Function>)it__ -> { + if(!(it__ instanceof JCTree.JCExpressionStatement it)) return List.of(it__); JCTree.JCExpressionStatement it__Copy = copy(it, object); - if (!(it.expr instanceof JCTree.JCMethodInvocation apply)) return List.of(it__Copy); + if(!(it.expr instanceof JCTree.JCMethodInvocation apply)) return List.of(it__Copy); String postfix = "super." + info.name; //TODO better super handling - if (!apply.meth.toString().equals(postfix) && !apply.meth.toString().endsWith('.' + postfix)) + if(!apply.meth.toString().equals(postfix) && !apply.meth.toString().endsWith('.' + postfix)) return List.of(it__Copy); JavacNode localContext = context.callerMethodNode.getNodeFor(it); @@ -238,20 +226,20 @@ public List copy(List trees, Object object) { Map resolved = resolution.resolveMethodMember(localContext); String resolvedArguments = of(apply.getArguments()) - .map(resolved::get) - .map(it_ -> it_.type) - .joining(";"); - if (!originalParams.equals(resolvedArguments)) return List.of(it__Copy); + .map(resolved::get) + .map(it_ -> it_.type) + .joining(";"); + if(!originalParams.equals(resolvedArguments)) return List.of(it__Copy); foundSuper[0] = true; - if (position == InjectPosition.BeforeSuper) { + if(position == InjectPosition.BeforeSuper){ return simpleCopier.copy(preprocessed).append(it__Copy); - } else { + }else{ return simpleCopier.copy(preprocessed).prepend(it__Copy); } }; //noinspection unchecked return List.from(of(trees) - .flatCollection(tCollectionFunction) + .flatCollection(tCollectionFunction) ); @@ -259,33 +247,33 @@ public List copy(List trees, Object object) { }; existed.body.stats = copier.copy(existed.body.stats); - if (!foundSuper[0]) { + if(!foundSuper[0]){ context.callerMethodNode - .addError("Cannot find invoking super method to inject implementation from " + interfaceFullName); + .addError("Cannot find invoking super method to inject implementation from " + interfaceFullName); } yield null; } }; //noinspection ConstantValue - if (false) System.out.println(nil); + if(false) System.out.println(nil); context.callerMethodNode.getAst().setChanged(); context.callerMethodNode.rebuild(); } @SneakyThrows - private List preprocess(List stats, AutoImplContext context) { + private List preprocess(List stats, AutoImplContext context){ JCTree.JCStatement[] array = stats.toArray(JCTree.JCStatement[]::new); ParserFactory parserFactory = ParserFactory.instance(info.node.getContext()); GeneratedByVisitor generatedByMarker = context.generatedBy(); - for (int i = 0; i < array.length; i++) { + for(int i = 0; i < array.length; i++){ JCTree.JCStatement jcStatement = array[i]; StringWriter s = new StringWriter(); new InlineApplyPrinter(s, Paths.PARAM_METHOD, makeLib(info.node, Paths.library), (printer, tree) -> { JavacAST ast = info.node - .getAst(); + .getAst(); String paramName = extractString(tree.args.get(0), ast, Paths.PARAM_METHOD); String defaultExpression = extractString(tree.args.get(1), ast, Paths.PARAM_METHOD); @@ -294,24 +282,24 @@ private List preprocess(List stats, Auto printer.print(expression); - }) { + }){ @SneakyThrows - boolean tryFixName(JCTree.JCIdent tree) { - if (!(tree.sym instanceof Symbol.VarSymbol varSymbol)) return false; - if (!(varSymbol.owner instanceof Symbol.MethodSymbol methodSymbol)) return false; - if (!(methodSymbol.owner instanceof Symbol.ClassSymbol classSymbol)) return false; - if (!classSymbol.className().equals(interfaceFullName)) return false; - if (!methodSymbol.toString().equals(info.symbolString)) return false; - JCTree.JCMethodDecl newDecl = (JCTree.JCMethodDecl) context.callerMethodNode.get(); + boolean tryFixName(JCTree.JCIdent tree){ + if(!(tree.sym instanceof Symbol.VarSymbol varSymbol)) return false; + if(!(varSymbol.owner instanceof Symbol.MethodSymbol methodSymbol)) return false; + if(!(methodSymbol.owner instanceof Symbol.ClassSymbol classSymbol)) return false; + if(!classSymbol.className().equals(interfaceFullName)) return false; + if(!methodSymbol.toString().equals(info.symbolString)) return false; + JCTree.JCMethodDecl newDecl = (JCTree.JCMethodDecl)context.callerMethodNode.get(); int varIndex = methodSymbol.params.indexOf(varSymbol); print(newDecl.params.get(varIndex).getName().toString()); return true; } @Override - public void visitIdent(JCTree.JCIdent tree) { + public void visitIdent(JCTree.JCIdent tree){ - if (tryFixName(tree)) return; + if(tryFixName(tree)) return; super.visitIdent(tree); } }.printStat(jcStatement); @@ -326,7 +314,7 @@ public void visitIdent(JCTree.JCIdent tree) { return List.from(array); } - public List prepareStats(AutoImplContext context) { + public List prepareStats(AutoImplContext context){ info.decl.body = TypeInliner.copyWithInlineTypes(info.node, info.decl.body); JCTree.JCMethodDecl decl = Util.resolveSym(info.node); diff --git a/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/info/TypeInliner.java b/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/info/TypeInliner.java index 2b5a5500..fbda23d3 100644 --- a/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/info/TypeInliner.java +++ b/annotations/src/main/java/omaloon/annotations/lombok/autoimpl/info/TypeInliner.java @@ -1,98 +1,91 @@ package omaloon.annotations.lombok.autoimpl.info; -import bytelogic.lombok.util.Util; -import com.sun.source.tree.MethodInvocationTree; -import com.sun.source.tree.MethodTree; -import com.sun.source.tree.Tree; -import com.sun.tools.javac.code.Symbol; -import com.sun.tools.javac.tree.JCTree; -import com.sun.tools.javac.tree.JCTree.JCFieldAccess; -import com.sun.tools.javac.tree.TreeCopier; -import com.sun.tools.javac.tree.TreeMaker; -import com.sun.tools.javac.util.List; -import lombok.javac.JavacNode; -import lombok.javac.JavacResolution; -import lombok.javac.handlers.JavacHandlerUtil; -import org.jetbrains.annotations.Nullable; - -public class TypeInliner extends TreeCopier { +import bytelogic.lombok.util.*; +import com.sun.source.tree.*; +import com.sun.tools.javac.code.*; +import com.sun.tools.javac.tree.*; +import com.sun.tools.javac.tree.JCTree.*; +import com.sun.tools.javac.util.*; +import lombok.javac.*; +import lombok.javac.handlers.*; +import org.jetbrains.annotations.*; + +public class TypeInliner extends TreeCopier{ private final JavacNode context; private TreeMaker M; /** * Creates a new instance of TreeCopier - * - * @param M - * @param context */ - public TypeInliner(TreeMaker M, JavacNode context) { + public TypeInliner(TreeMaker M, JavacNode context){ super(M); this.M = M; this.context = context; } - public static T copyWithInlineTypes(JavacNode javacNode) { + public static T copyWithInlineTypes(JavacNode javacNode){ T resolved = Util.resolveSym(javacNode); TypeInliner inliner = new TypeInliner(javacNode.getTreeMaker().getUnderlyingTreeMaker(), javacNode); return inliner.copy(resolved); } - public static T copyWithInlineTypes(JavacNode context,T tree) { + + public static T copyWithInlineTypes(JavacNode context, T tree){ JavacResolution resolution = Util.resolution(context.getContext()); //noinspection unchecked - T resolved = (T) resolution.resolveMethodMember(context).get(tree); + T resolved = (T)resolution.resolveMethodMember(context).get(tree); return - new TypeInliner(context.getTreeMaker().getUnderlyingTreeMaker(), context) - .copy(resolved); + new TypeInliner(context.getTreeMaker().getUnderlyingTreeMaker(), context) + .copy(resolved); } @Override - public T copy(T tree, Void unused) { - if (tree instanceof JCFieldAccess fieldAccess) { + public T copy(T tree, Void unused){ + if(tree instanceof JCFieldAccess fieldAccess){ T new_ = unwrap(tree, fieldAccess.sym); - if (new_ != tree) return new_; + if(new_ != tree) return new_; } - if (tree instanceof JCTree.JCIdent ident) { + if(tree instanceof JCTree.JCIdent ident){ T new_ = unwrap(tree, ident.sym); - if (new_ != tree) return new_; + if(new_ != tree) return new_; } return super.copy(tree, unused); } @Nullable - private T unwrap(T tree, Symbol sym) { + private T unwrap(T tree, Symbol sym){ - if (!(sym instanceof Symbol.ClassSymbol classSymbol)) return tree; - if (classSymbol.name.isEmpty()) { + if(!(sym instanceof Symbol.ClassSymbol classSymbol)) return tree; + if(classSymbol.name.isEmpty()){ //Anonymous //TO debug throw new RuntimeException("To debug"); - } else { + }else{ String string = classSymbol.className(); - JCFieldAccess jcFieldAccess = (JCFieldAccess) JavacHandlerUtil.chainDots(context, string.split("\\.")); + JCFieldAccess jcFieldAccess = (JCFieldAccess)JavacHandlerUtil.chainDots(context, string.split("\\.")); jcFieldAccess.sym = sym; jcFieldAccess.pos = tree.pos; //noinspection unchecked - return (T) jcFieldAccess; + return (T)jcFieldAccess; } } - private T cast(Tree node) { + private T cast(Tree node){ //noinspection unchecked - return (T) node; + return (T)node; } @Override - public JCTree visitMethodInvocation(MethodInvocationTree node, Void unused) { + public JCTree visitMethodInvocation(MethodInvocationTree node, Void unused){ return super.visitMethodInvocation(node, unused); } @Override - public List copy(List trees, Void unused) { + public List copy(List trees, Void unused){ return super.copy(trees, unused); } } diff --git a/annotations/src/main/java/omaloon/annotations/lombok/load/FieldDescriptor.java b/annotations/src/main/java/omaloon/annotations/lombok/load/FieldDescriptor.java index c339598c..d5914974 100644 --- a/annotations/src/main/java/omaloon/annotations/lombok/load/FieldDescriptor.java +++ b/annotations/src/main/java/omaloon/annotations/lombok/load/FieldDescriptor.java @@ -1,32 +1,30 @@ package omaloon.annotations.lombok.load; -import com.github.javaparser.StaticJavaParser; -import com.github.javaparser.ast.stmt.BlockStmt; -import lombok.AccessLevel; -import lombok.AllArgsConstructor; -import lombok.experimental.FieldDefaults; -import lombok.javac.JavacNode; -import omaloon.annotations.Load; -import org.jetbrains.annotations.NotNull; - -import java.util.Arrays; -import java.util.StringJoiner; +import com.github.javaparser.*; +import com.github.javaparser.ast.stmt.*; +import lombok.*; +import lombok.experimental.*; +import lombok.javac.*; +import omaloon.annotations.*; +import org.jetbrains.annotations.*; + +import java.util.*; @FieldDefaults(makeFinal = true, level = AccessLevel.PUBLIC) @AllArgsConstructor -public class FieldDescriptor { +public class FieldDescriptor{ public static final String ARC_CORE_ATLAS_FIND = "arc.Core.atlas.find"; public static final String INDECIES__MARKER = "<<>"; JavacNode field; Load an; - public void addMe(BlockStmt block) { + public void addMe(BlockStmt block){ // JCTree.JCVariableDecl variableDecl = (JCTree.JCVariableDecl) field.get(); // variableDecl.getType() RegionName expression = new RegionName(); expression.string("this.%s%s = %s(".formatted(field.getName(), INDECIES__MARKER, ARC_CORE_ATLAS_FIND)); expression.join(RegionName.build('"' + an.value() + '"')); - for (String fallback : an.fallback()) { + for(String fallback : an.fallback()){ expression.string(", " + ARC_CORE_ATLAS_FIND + "(\""); expression.join(RegionName.build(fallback)); expression.string("\""); @@ -38,80 +36,80 @@ public void addMe(BlockStmt block) { } //TODO dimension check - int dimension = (int) (expression.dimensions + Math.random() * 0); - if (expression.dimensions != dimension) { + int dimension = (int)(expression.dimensions + Math.random() * 0); + if(expression.dimensions != dimension){ field.addError("@Load Dimension mismatch"); return; } int[] lengths = lengths(); - if (expression.dimensions > lengths.length) { + if(expression.dimensions > lengths.length){ field.addError("@Load expected %d lengths but found %d".formatted(expression.dimensions, lengths.length)); return; } - if (expression.dimensions < lengths.length && an.lengths().length > 0) { + if(expression.dimensions < lengths.length && an.lengths().length > 0){ field.addWarning("@Load the extra size for the array is indicated"); } //TODO check type - if (false) { + if(false){ field.addError("@Load Expected TextureRegion as field type"); return; } int totalRounds = 1; - for (int length : lengths) totalRounds *= length; + for(int length : lengths) totalRounds *= length; - if (totalRounds == 0) { + if(totalRounds == 0){ field.addError("@Load one of given lengths are 0"); return; } if(expression.getItems().get(0) instanceof Reference.StringReference ref){ - StringJoiner joiner=new StringJoiner("][","[","]"); + StringJoiner joiner = new StringJoiner("][", "[", "]"); RegionName indecies = new RegionName(); int markerIndex = ref.value.indexOf(INDECIES__MARKER); indecies.string(ref.value.substring(0, markerIndex)); - for (int i = 0; i < expression.dimensions; i++) { + for(int i = 0; i < expression.dimensions; i++){ indecies.string("["); indecies.index(i); indecies.string("]"); } - indecies.string(ref.value.substring(markerIndex+INDECIES__MARKER.length())); - for (int i = 1; i < expression.getItems().size(); i++) { + indecies.string(ref.value.substring(markerIndex + INDECIES__MARKER.length())); + for(int i = 1; i < expression.getItems().size(); i++){ indecies.add(expression.getItems().get(i)); } expression.getItems().clear(); expression.join(indecies); } int[] indecies = new int[expression.dimensions]; - for (int __i = 0; __i < totalRounds; __i++) { + for(int __i = 0; __i < totalRounds; __i++){ String calculatedExpression = expression.calculate(indecies); block.addStatement( - StaticJavaParser.parseStatement( - calculatedExpression + ";" - ) + StaticJavaParser.parseStatement( + calculatedExpression + ";" + ) ); increase(indecies, lengths, 0); } } - private void increase(int[] indecies, int[] lengths, int i) { - if (i >= indecies.length) return; + private void increase(int[] indecies, int[] lengths, int i){ + if(i >= indecies.length) return; indecies[i]++; - if (indecies[i] <= lengths[i]) return; + if(indecies[i] <= lengths[i]) return; indecies[i] = 0; increase(indecies, lengths, i + 1); } @NotNull - private int[] lengths() { + private int[] lengths(){ int[] lengths = an.lengths(); - if (lengths.length == 0) lengths = new int[]{an.length()}; + if(lengths.length == 0) lengths = new int[]{an.length()}; return lengths; } } diff --git a/annotations/src/main/java/omaloon/annotations/lombok/load/LoadAnnotationASTVisitor.java b/annotations/src/main/java/omaloon/annotations/lombok/load/LoadAnnotationASTVisitor.java index 6be53201..cfc8a7f2 100644 --- a/annotations/src/main/java/omaloon/annotations/lombok/load/LoadAnnotationASTVisitor.java +++ b/annotations/src/main/java/omaloon/annotations/lombok/load/LoadAnnotationASTVisitor.java @@ -1,56 +1,54 @@ package omaloon.annotations.lombok.load; -import asmlib.lombok.javaparser.CompileBodyVisitor; -import bytelogic.lombok.util.Util; -import com.github.javaparser.StaticJavaParser; -import com.github.javaparser.ast.Modifier; -import com.github.javaparser.ast.body.MethodDeclaration; -import com.github.javaparser.ast.stmt.BlockStmt; -import com.sun.tools.javac.tree.JCTree; +import asmlib.lombok.javaparser.*; +import bytelogic.lombok.util.*; +import com.github.javaparser.*; +import com.github.javaparser.ast.*; +import com.github.javaparser.ast.body.*; +import com.github.javaparser.ast.stmt.*; +import com.sun.tools.javac.tree.*; import com.sun.tools.javac.util.List; -import lombok.core.AST; -import lombok.core.AnnotationValues; -import lombok.javac.JavacASTAdapter; -import lombok.javac.JavacNode; -import lombok.javac.handlers.JavacHandlerUtil; -import omaloon.annotations.Load; +import lombok.core.*; +import lombok.javac.*; +import lombok.javac.handlers.*; +import omaloon.annotations.*; + +import java.util.*; -import java.util.ArrayList; //TODO try handle something like @Load(name+"-hello") //TODO support for delegate function -public class LoadAnnotationASTVisitor extends JavacASTAdapter { +public class LoadAnnotationASTVisitor extends JavacASTAdapter{ @Override - public void visitType(JavacNode typeNode, JCTree.JCClassDecl type) { + public void visitType(JavacNode typeNode, JCTree.JCClassDecl type){ super.visitType(typeNode, type); ArrayList loadFields = new ArrayList<>(); JavacNode loadMethod = null; - for (JavacNode field : typeNode.down()) { - if (field.getKind() == AST.Kind.METHOD) { + for(JavacNode field : typeNode.down()){ + if(field.getKind() == AST.Kind.METHOD){ //TODO hierarchy check - JCTree.JCMethodDecl methodDecl = (JCTree.JCMethodDecl) field.get(); - if (field.getName().equals("load") && methodDecl.getParameters().isEmpty()) { + JCTree.JCMethodDecl methodDecl = (JCTree.JCMethodDecl)field.get(); + if(field.getName().equals("load") && methodDecl.getParameters().isEmpty()){ loadMethod = field; } continue; } - if (field.getKind() != AST.Kind.FIELD) { + if(field.getKind() != AST.Kind.FIELD){ continue; } AnnotationValues annotation = field.findAnnotation(Load.class); - if (annotation == null) continue; + if(annotation == null) continue; loadFields.add(new FieldDescriptor(field, annotation.getInstance())); } - if (loadFields.isEmpty()) return; + if(loadFields.isEmpty()) return; CompileBodyVisitor transformer = Util.transformer(typeNode); - if (loadMethod == null) { + if(loadMethod == null){ BlockStmt body = new BlockStmt(); MethodDeclaration declaration = new MethodDeclaration() - .setName("load") - .setType(void.class) - .addAnnotation(Override.class) - .setModifiers(Modifier.Keyword.PUBLIC) - .setBody(body) - ; + .setName("load") + .setType(void.class) + .addAnnotation(Override.class) + .setModifiers(Modifier.Keyword.PUBLIC) + .setBody(body); body.addStatement(StaticJavaParser.parseStatement("super.load();")); @@ -58,20 +56,20 @@ public void visitType(JavacNode typeNode, JCTree.JCClassDecl type) { JCTree.JCMethodDecl methodDecl = transformer.visit(declaration, null); JavacHandlerUtil.injectMethod(typeNode, methodDecl); - } else { - JCTree.JCMethodDecl decl = (JCTree.JCMethodDecl) loadMethod.get(); + }else{ + JCTree.JCMethodDecl decl = (JCTree.JCMethodDecl)loadMethod.get(); List oldStats = decl.body.stats; JCTree.JCBlock newBlock = transformer.visit(addFields(loadFields, new BlockStmt()), null); List stats = newBlock.stats; - decl.body.stats= stats.appendList(oldStats); + decl.body.stats = stats.appendList(oldStats); loadMethod.getAst().setChanged(); } } - private static BlockStmt addFields(java.util.List loadFields, BlockStmt block) { - for (FieldDescriptor field : loadFields) + private static BlockStmt addFields(java.util.List loadFields, BlockStmt block){ + for(FieldDescriptor field : loadFields) field.addMe(block); return block; } diff --git a/annotations/src/main/java/omaloon/annotations/lombok/load/Reference.java b/annotations/src/main/java/omaloon/annotations/lombok/load/Reference.java index 89103da3..b2350548 100644 --- a/annotations/src/main/java/omaloon/annotations/lombok/load/Reference.java +++ b/annotations/src/main/java/omaloon/annotations/lombok/load/Reference.java @@ -1,34 +1,41 @@ package omaloon.annotations.lombok.load; -import lombok.AllArgsConstructor; +import lombok.*; -public abstract class Reference { +public abstract class Reference{ abstract String stringify(int[] data); + @AllArgsConstructor - public static class IndexReference extends Reference { + public static class IndexReference extends Reference{ public final int index; + @Override - String stringify(int[] data) { + String stringify(int[] data){ return data[index] + ""; } } + @AllArgsConstructor - public static class ExpressionReference extends Reference { + public static class ExpressionReference extends Reference{ public final String expression; + @Override - String stringify(int[] data) { - return "\" + "+expression+"+ \""; + String stringify(int[] data){ + return "\" + " + expression + "+ \""; } } + @AllArgsConstructor public static class StringReference extends Reference{ public final String value; + @Override - String stringify(int[] data) { + String stringify(int[] data){ return value; } } - public boolean isString() { + + public boolean isString(){ return this instanceof StringReference; } } diff --git a/annotations/src/main/java/omaloon/annotations/lombok/load/RegionName.java b/annotations/src/main/java/omaloon/annotations/lombok/load/RegionName.java index 8cb576b3..e70476b3 100644 --- a/annotations/src/main/java/omaloon/annotations/lombok/load/RegionName.java +++ b/annotations/src/main/java/omaloon/annotations/lombok/load/RegionName.java @@ -1,17 +1,13 @@ package omaloon.annotations.lombok.load; -import lombok.Getter; -import omaloon.annotations.lombok.load.Reference.ExpressionReference; -import omaloon.annotations.lombok.load.Reference.IndexReference; -import omaloon.annotations.lombok.load.Reference.StringReference; - -import java.util.ArrayList; -import java.util.List; -import java.util.function.BiConsumer; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class RegionName { +import lombok.*; +import omaloon.annotations.lombok.load.Reference.*; + +import java.util.*; +import java.util.function.*; +import java.util.regex.*; + +public class RegionName{ public static final int[] EMPTY_INTS = new int[0]; static Pattern accessExpressionPattern = Pattern.compile("@(\\w+(\\(\\))?(\\.\\w+(\\(\\))?)*)*"); static Pattern indexAccessPattern = Pattern.compile("#\\d*"); @@ -20,21 +16,21 @@ public class RegionName { @Getter private List items = new ArrayList<>(); - private static void flatReplacePattern(RegionName regionName, Pattern pattern, BiConsumer replacement) { + private static void flatReplacePattern(RegionName regionName, Pattern pattern, BiConsumer replacement){ ArrayList copy = new ArrayList<>(regionName.items); regionName.items.clear(); - for (Reference reference : copy) { - if (!reference.isString()) { + for(Reference reference : copy){ + if(!reference.isString()){ regionName.add(reference); continue; } String value = reference.stringify(EMPTY_INTS); Matcher matcher = pattern.matcher(value); - if (matcher.find()) { + if(matcher.find()){ int prevIndex = 0; - while (matcher.find(prevIndex)) { + while(matcher.find(prevIndex)){ regionName.string(value.substring(prevIndex, matcher.start())); replacement.accept(matcher.group(), regionName); prevIndex = matcher.end(); @@ -46,20 +42,20 @@ private static void flatReplacePattern(RegionName regionName, Pattern pattern, B } } - public static RegionName build(String string) { + public static RegionName build(String string){ RegionName name = new RegionName(); name.string(string); // StringBuilder builder = new StringBuilder("\""); flatReplacePattern(name, accessExpressionPattern, (group, l) -> { String expression = group.substring(1);//removing "@" - if (expression.isEmpty()) { + if(expression.isEmpty()){ expression = "name"; } - l.expression("this."+expression); + l.expression("this." + expression); }); flatReplacePattern(name, indexAccessPattern, (group, l) -> { String number = group.substring(1);//removing "#" - if (number.isEmpty()) { + if(number.isEmpty()){ number = "0"; } l.index(Integer.parseInt(number)); @@ -68,22 +64,22 @@ public static RegionName build(String string) { return name; } - public void add(Reference reference) { - if (reference instanceof StringReference stringReference) { + public void add(Reference reference){ + if(reference instanceof StringReference stringReference){ string(stringReference.value); - } else items.add(reference); + }else items.add(reference); } - public RegionName copy() { + public RegionName copy(){ RegionName name = new RegionName(); name.items.addAll(items); name.dimensions = dimensions; return name; } - public void join(RegionName other) { - for (Reference reference : other.items) { + public void join(RegionName other){ + for(Reference reference : other.items){ add(reference); } updateDimentions(); @@ -91,43 +87,43 @@ public void join(RegionName other) { ; - private void updateDimentions() { - dimensions = (int) items.stream().filter(it -> it instanceof IndexReference).count(); + private void updateDimentions(){ + dimensions = (int)items.stream().filter(it -> it instanceof IndexReference).count(); } - public boolean isString() { - for (Reference item : items) { - if (!(item instanceof StringReference)) { + public boolean isString(){ + for(Reference item : items){ + if(!(item instanceof StringReference)){ return false; } } return true; } - public String calculate(int... indecies) { + public String calculate(int... indecies){ String[] strings = new String[items.size()]; - for (int i = 0; i < strings.length; i++) { + for(int i = 0; i < strings.length; i++){ strings[i] = items.get(i).stringify(indecies); } return String.join("", strings); } - public void index(int num) { + public void index(int num){ items.add(new IndexReference(num)); } - public void string(String string) { + public void string(String string){ int lastIdx = items.size() - 1; - if (lastIdx >= 0 && items.get(lastIdx) instanceof StringReference last_) { + if(lastIdx >= 0 && items.get(lastIdx) instanceof StringReference last_){ items.set(lastIdx, new StringReference( - last_.value + string + last_.value + string )); - } else { + }else{ items.add(new StringReference(string)); } } - public void expression(String expression) { + public void expression(String expression){ items.add(new ExpressionReference(expression)); } diff --git a/assets/bundles/bundle.properties b/assets/bundles/bundle.properties index 88be8de2..ae1b9940 100644 --- a/assets/bundles/bundle.properties +++ b/assets/bundles/bundle.properties @@ -83,59 +83,59 @@ tc.cobalt = \ \nof the buildings here. Mine some of it to create\ \nfirst mining automation. -tc.reshammer =\ +tc.reshammer = \ Open the \uE875 tech tree \n and research the \uC351[accent] Hammer Drill[]. -tc.distributor-error1=\ +tc.distributor-error1 = \ The \uC352 [accent]Tube Distributor[]\ \nhas one side from which\ \nit does not accept items. -tc.distributor-error2=\ +tc.distributor-error2 = \ In that case, this\ \n\uC351[accent] Hammer Drill[] won't\ \nbe able to drop items. -tc.distributor-error3=\ +tc.distributor-error3 = \ So carefully check in which direction\ \nthe \uC352 [accent]Tube Distributor[]\ \nis facing. -tc.pump=\ +tc.pump = \ Research and place \uC353[accent] Liquid Pump[]\ \nfacing away from the hammer drill.\ \nThis will pump air out of all neighboring\ \ndrills, making them mine. -tc.beryllium=\ +tc.beryllium = \ \uF748 [#92DD7E] Beryllium [] is another\ \nmajor resource here, needed for\ \nmore complex structures. -tc.shelter=\ +tc.shelter = \ It looks like a massive hailstorm is approaching.\ \nResearch the \uC355[accent] Small Shelter[]\ \nand cover all your buildings from the hail. -tc.hail-timer=\ +tc.hail-timer = \ A massive hailstorm is approaching! Cover your buildings! [lightgray]{0}[] -tc.press=\ +tc.press = \ While the hailstorm continues, make sure you cover\ \nall your buildings and then set up the\ \n\uC356[#8691b3] Carborundum[] production. -tc.core=\ +tc.core = \ It's time to leave this place. Upgrade your core. sector.omaloon-redeployment_path.name = Redeployment Path sector.omaloon-redeployment_path.description = Very windy wasteland, away from craters and mountains. A regular redeployments of small enemy unit groups has been noticed here. Beware of strong dust storms and waves of enemies. -rp.text=\ +rp.text = \ Next enemy group approaching! Research defenses\ \nand prepare your base for further attacks. -rp.next-enemy-group=[lightgray]Next enemy group in {0} +rp.next-enemy-group = [lightgray]Next enemy group in {0} sector.omaloon-dead_valley.name = Dead Valley sector.omaloon-dead_valley.description = A quiet mountain valley without any dangerous weather features. The enemies, having noticed your presence earlier, have sent stronger and more dangerous groups to attack you. Explore the dead forest and its coal reserves to research new weapons to defend yourself against enemies. diff --git a/assets/bundles/bundle_uk_UA.properties b/assets/bundles/bundle_uk_UA.properties index b36a7613..6ba90c58 100644 --- a/assets/bundles/bundle_uk_UA.properties +++ b/assets/bundles/bundle_uk_UA.properties @@ -82,58 +82,58 @@ tc.cobalt = \ \nбудівель тут. Видобудьте трохи цього ресурсу, щоб створити\ \nпершу автоматизацію видобутку. -tc.reshammer =\ +tc.reshammer = \ Відкрийте \uE875 дерево технологій та дослідіть \uC351[accent] ударний бур[]. -tc.distributor-error1=\ +tc.distributor-error1 = \ \uC352 [accent]Трубковий розподільник[]\ \nмає одну сторону з якої\ \nвін не приймає предметів. -tc.distributor-error2=\ +tc.distributor-error2 = \ У цьому випадку, цей\ \n\uC351[accent] ударний бур[] не\ \nмає куди викидати предмети. -tc.distributor-error3=\ +tc.distributor-error3 = \ Тож уважно слідкуйте, куди розвернуто\ \n\uC352 [accent]трубковий розподільник[]. -tc.pump=\ +tc.pump = \ Дослідіть та розмістіть \uC353[accent] механічний насос[]\ \nрозвернутим від ударного бура.\ \nТак ви будете викачувати повітря з усіх суміжніх\ \nбурів, змушуючи їх видобувати. -tc.beryllium=\ +tc.beryllium = \ \uF748 [#92DD7E] Берилій [] - це ще один\ \nважливий тут ресурс, потрібний для\ \nтрохи складніших будівель. -tc.shelter=\ +tc.shelter = \ Схоже насувається сильний град.\ \nДослідіть \uC355[accent] мале укриття[]\ \nта захистіть усі свої будівлі від граду. -tc.hail-timer=\ +tc.hail-timer = \ Насувається сильний град! Захистіть свої будівлі! [lightgray]{0}[] -tc.press=\ +tc.press = \ Поки град триває, переконайтеся, що ви захистили\ \nвсі свої будівлі, та організуйте\ \nвиробництво \uC356[#8691b3] карборунду[]. -tc.core=\ +tc.core = \ Настав час покинути це місце. Оновіть своє ядро. sector.omaloon-redeployment_path.name = Шлях передислокації sector.omaloon-redeployment_path.description = Дуже вітряна пустка, далеко від кратерів та гір. Тут спостерігаються регулярні переміщення невеликих ворожих груп. Остерігайтеся потужних пилових бур та хвиль ворогів. -rp.text=\ +rp.text = \ Наближається наступна ворожа група! Дослідіть захисні засоби\ \nі підготуйте свою базу до подальших атак. -rp.next-enemy-group=[lightgray]Наступна ворожа група \nчерез {0} +rp.next-enemy-group = [lightgray]Наступна ворожа група \nчерез {0} sector.omaloon-dead_valley.name = Мертва долина sector.omaloon-dead_valley.description = Тиха гірська долина без небезпечних погодних умов. Вороги, помітивши вашу присутність раніше, відправили сюди сильніші та небезпечніші загони, щоб знищити вас. Дослідіть мертвий ліс і його запаси вугілля, щоб виробити нові засоби захисту від ворогів. diff --git a/assets/bundles/bundle_zh_CN.properties b/assets/bundles/bundle_zh_CN.properties index c4a33e20..897f1fcc 100644 --- a/assets/bundles/bundle_zh_CN.properties +++ b/assets/bundles/bundle_zh_CN.properties @@ -57,7 +57,7 @@ settings.omaloon-clearcampaignsaves-confirm = 确定清除 Omaloon 的战役存 omaloon.update.dialog.fullclean.confirm = Are you sure you want to reset your current Omaloon campaign? ## objectives -requirement.omaloon-at-wave = {1} 内 达到第 {0} 波次 +requirement.omaloon-at-wave = {1} 内 达到第 {0} 波次 ## Hints hint.omaloon-pump_positive = To create higher pressure, place \uC353[accent] mechanical pumps[] in series, adding liquid pipes between them.\nTo increase pressure faster, place \uC353[accent] mechanical pumps[] in parallel. @@ -79,47 +79,47 @@ tc.cobalt = \ \uC350 [#bbc7c9]钴[] 是本星球用于建筑的基础材料。\ \n收集一些以启动初步挖矿自动化。 -tc.reshammer =\ +tc.reshammer = \ 打开 \uE875 科技树 \n 并研究 \uC351[accent] 气锤钻井[]。 -tc.distributor-error1=\ +tc.distributor-error1 = \ \uC352 [accent]管式分配器[] 的朝向一侧不接受物品的输入。 -tc.distributor-error2=\ +tc.distributor-error2 = \ 这种情况下,\uC351[accent] 气锤钻井[] 无法输出物品。 -tc.distributor-error3=\ +tc.distributor-error3 = \ 请注意检查 \uC352 [accent]管式分配器[] 的朝向。 -tc.pump=\ +tc.pump = \ 研究 \uC353[accent] 流体泵[] 并背对气锤钻井放置,\ \n流体泵可以抽出该钻井及其毗连钻井的空气,使其工作。 -tc.beryllium=\ +tc.beryllium = \ \uF748 [#92DD7E] 铍 [] 是该星球的另一种主要资源。\ \n可用于更为高级的建筑。 -tc.shelter=\ +tc.shelter = \ 一场大规模的冰雹天气即将到来。\ \n研究并放置 \uC355[accent] 小型庇护力场[] 以保护建筑。 -tc.hail-timer=\ +tc.hail-timer = \ 大规模的冰雹天气即将来临!做好准备! [lightgray]{0}[] -tc.press=\ +tc.press = \ 发生冰雹天气时,确保你的建筑都受到庇护力场的保护。\ \n在此同时, 可以进行\uC356[#8691b3] 钴钢[] 的生产. -tc.core=\ +tc.core = \ 是时候离开了。升级你的核心。 sector.omaloon-redeployment_path.name = 敌巡小径 sector.omaloon-redeployment_path.description = 远离陨石坑和群峰的多风荒地。这里敌方小股部队定期重新部署。当心强烈的沙尘暴和一波又一波的敌人。 -rp.text=\ +rp.text = \ 敌方单位即将来袭!建造防御,抵御来袭敌人。 -rp.next-enemy-group=[lightgray]下一波敌方单位将于 {0} 后到达 +rp.next-enemy-group = [lightgray]下一波敌方单位将于 {0} 后到达 sector.omaloon-dead_valley.name = 死寂山谷 sector.omaloon-dead_valley.description = 死寂的山谷。未检测到危险天气。敌人已注意到了你的存在,派出了更强大、更危险的进攻队伍。探索枯死的森林,利用其煤炭储备,研究新武器来抵御敌人。 diff --git a/assets/icons/omaloon-icons.properties b/assets/icons/omaloon-icons.properties index ace78159..535ba58a 100644 --- a/assets/icons/omaloon-icons.properties +++ b/assets/icons/omaloon-icons.properties @@ -1,16 +1,16 @@ #\uC350 -50000=cobalt|omaloon-cobalt-icon +50000 = cobalt|omaloon-cobalt-icon #\uC351 -50001=hammer-drill|omaloon-hammer-drill-icon +50001 = hammer-drill|omaloon-hammer-drill-icon #\uC352 -50002=tube-distributor|omaloon-tube-distributor-icon +50002 = tube-distributor|omaloon-tube-distributor-icon #\uC353 -50003=liquid-pump|omaloon-liquid-pump-icon +50003 = liquid-pump|omaloon-liquid-pump-icon #\uC354 -50004=liquid-valve|omaloon-liquid-valve-icon +50004 = liquid-valve|omaloon-liquid-valve-icon #\uC355 -50005=small-shelter|omaloon-small-shelter-icon +50005 = small-shelter|omaloon-small-shelter-icon #\uC356 -50006=carborundum|omaloon-carborundum-icon +50006 = carborundum|omaloon-carborundum-icon #\uC357 -50007=pressure|omaloon-pressure-icon \ No newline at end of file +50007 = pressure|omaloon-pressure-icon \ No newline at end of file diff --git a/assets/mod.json b/assets/mod.json index 59a69c29..3c7184c2 100644 --- a/assets/mod.json +++ b/assets/mod.json @@ -1,10 +1,10 @@ { -"displayName": "Omaloon", -"name": "omaloon", -"author": "stabu, uujuju", -"main": "omaloon.OmaloonMod", -"description": "An ambitious modification aimed at expanding the game's standard campaign by adding a new star system.", -"version": "0.1.1Ah", -"minGameVersion": 146, -"java": true + "displayName": "Omaloon", + "name": "omaloon", + "author": "stabu, uujuju", + "main": "omaloon.OmaloonMod", + "description": "An ambitious modification aimed at expanding the game's standard campaign by adding a new star system.", + "version": "0.1.1Ah", + "minGameVersion": 146, + "java": true } \ No newline at end of file diff --git a/assets/shaders/circle-mesh.vert b/assets/shaders/circle-mesh.vert index f8abeab9..2c506625 100644 --- a/assets/shaders/circle-mesh.vert +++ b/assets/shaders/circle-mesh.vert @@ -32,7 +32,7 @@ void main(){ vec3 vertexEye = normalize(u_campos - my_position); float specularFactor = dot(vertexEye, lightReflect); - if(specularFactor > 0.0){ + if (specularFactor > 0.0){ specular = vec3(1.0 * pow(specularFactor, 40.0)) * (1.0-a_color.a); } diff --git a/assets/shaders/dalani.frag b/assets/shaders/dalani.frag index 068bf7c5..d39e6bb7 100644 --- a/assets/shaders/dalani.frag +++ b/assets/shaders/dalani.frag @@ -35,15 +35,15 @@ void main() { vec4 color = texture2D(u_texture, c); - if(noise > 0.85){ - if(color.g > mth - 0.1){ + if (noise > 0.85){ + if (color.g > mth - 0.1){ color *= brightnessFactor; } else { color *= brightnessFactor; } } - if(orig.g < mth){ + if (orig.g < mth){ color *= brightnessFactor; } diff --git a/assets/shaders/depth-atmosphere.frag b/assets/shaders/depth-atmosphere.frag index 31a16fb6..29fd3091 100644 --- a/assets/shaders/depth-atmosphere.frag +++ b/assets/shaders/depth-atmosphere.frag @@ -33,7 +33,7 @@ vec2 intersect(vec3 ray_origin, vec3 ray_dir, float radius){ float c = dot(ray_origin, ray_origin) - radius * radius; float d = b * b - c; - if(d < 0.0) discard; + if (d < 0.0) discard; d = sqrt(d); float near = -b - d; @@ -67,7 +67,7 @@ float optic(vec3 p, vec3 q){ vec3 v = p + step * 0.5; float sum = 0.0; - for(int i = 0; i < numOutScatter; i++){ + for (int i = 0; i < numOutScatter; i++){ sum += density(v); v += step; } @@ -82,7 +82,7 @@ vec3 inScatter(vec3 eye, vec3 ray, vec2 bound, vec3 light){ vec3 march = start + ray * (len * 0.5); vec3 sum = vec3(0.0); - for(int i = 0; i < numInScatter; i++){ + for (int i = 0; i < numInScatter; i++){ vec2 f = intersect(march, light, u_outerRadius); vec3 u = march + light * f.y; float n = (optic(start, march) + optic(march, u)) * (pi * 4.0); diff --git a/build.gradle.kts b/build.gradle.kts index a9682d66..7631ff10 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,25 +1,25 @@ import arc.files.Fi -import arc.util.* -import arc.util.serialization.* +import arc.util.OS +import arc.util.serialization.Jval import de.undercouch.gradle.tasks.download.Download -import ent.* -import java.io.* +import ent.EntityAnnoExtension +import java.io.BufferedWriter -buildscript{ +buildscript { val arcVersion: String by project val useJitpack = property("mindustryBE").toString().toBooleanStrict() - dependencies{ + dependencies { classpath("com.github.Anuken.Arc:arc-core:$arcVersion") } - repositories{ - if(!useJitpack) maven("https://raw.githubusercontent.com/Zelaux/MindustryRepo/master/repository") + repositories { + if (!useJitpack) maven("https://raw.githubusercontent.com/Zelaux/MindustryRepo/master/repository") maven("https://jitpack.io") } } -plugins{ +plugins { java id("de.undercouch.download") version "5.4.0" id("com.github.GlennFolker.EntityAnno") apply false @@ -52,45 +52,45 @@ val androidMinVersion: String by project val useJitpack = property("mindustryBE").toString().toBooleanStrict() -fun arc(module: String): String{ +fun arc(module: String): String { return "com.github.Anuken.Arc$module:$arcVersion" } -fun arcLibrary(module: String): String{ +fun arcLibrary(module: String): String { return "com.github.Zelaux.ArcLibrary$module:$arcLibraryVersion" } -fun mindustry(module: String): String{ +fun mindustry(module: String): String { return "com.github.Anuken.Mindustry$module:$mindustryVersion" } -fun entity(module: String): String{ +fun entity(module: String): String { return "com.github.GlennFolker.EntityAnno$module:$entVersion" } extra.set("asmLib", asmLib) -project(":"){ +project(":") { apply(plugin = "java") sourceSets["main"].java.setSrcDirs(listOf(layout.projectDirectory.dir("src"))) - configurations.configureEach{ + configurations.configureEach { // Resolve the correct Mindustry dependency, and force Arc version. - resolutionStrategy.eachDependency{ - if(useJitpack && requested.group == "com.github.Anuken.Mindustry"){ + resolutionStrategy.eachDependency { + if (useJitpack && requested.group == "com.github.Anuken.Mindustry") { useTarget("com.github.Anuken.MindustryJitpack:${requested.module.name}:$mindustryBEVersion") - }else if(requested.group == "com.github.Anuken.Arc"){ + } else if (requested.group == "com.github.Anuken.Arc") { useVersion(arcVersion) } } } - dependencies{ + dependencies { // Downgrade Java 9+ syntax into being available in Java 8. //moved into :annotation because of 'missing opens issue' // annotationProcessor(entity(":downgrader")) } - repositories{ + repositories { // Necessary Maven repositories to pull dependencies from. mavenCentral() maven("https://oss.sonatype.org/content/repositories/snapshots/") @@ -98,15 +98,15 @@ project(":"){ maven("https://raw.githubusercontent.com/GlennFolker/EntityAnnoMaven/main") // Use Zelaux's non-buggy repository for release Mindustry and Arc builds. - if(!useJitpack) maven("https://raw.githubusercontent.com/Zelaux/MindustryRepo/master/repository") + if (!useJitpack) maven("https://raw.githubusercontent.com/Zelaux/MindustryRepo/master/repository") maven("https://raw.githubusercontent.com/Zelaux/Repo/master/repository")//for ArcLibrary maven("https://jitpack.io") } - tasks.withType().configureEach{ + tasks.withType().configureEach { // Use Java 17+ syntax, but target Java 8 bytecode version. sourceCompatibility = "17" - options.apply{ + options.apply { release = 8 compilerArgs.add("-Xlint:-options") @@ -116,11 +116,11 @@ project(":"){ } } -project(":"){ +project(":") { apply(plugin = "com.github.GlennFolker.EntityAnno") - configure{ + configure { modName = project.properties["modName"].toString() - mindustryVersion = project.properties[if(useJitpack) "mindustryBEVersion" else "mindustryVersion"].toString() + mindustryVersion = project.properties[if (useJitpack) "mindustryBEVersion" else "mindustryVersion"].toString() isJitpack = useJitpack revisionDir = layout.projectDirectory.dir("revisions").asFile fetchPackage = modFetch @@ -129,7 +129,7 @@ project(":"){ } //Added debuging diring compilation to debug annotation processors - tasks.withType(JavaCompile::class).configureEach{ + tasks.withType(JavaCompile::class).configureEach { options.isDebug = true options.isFork = true options.compilerArgs.add("-g") @@ -138,7 +138,7 @@ project(":"){ "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5008" ) } - dependencies{ + dependencies { annotationProcessor("org.projectlombok:lombok:1.18.32") annotationProcessor(asmLib("annotations:debug-print")) annotationProcessor(project(":annotations")) @@ -156,14 +156,14 @@ project(":"){ implementation(arcLibrary(":graphics-extendedDraw")) } - val jar = tasks.named("jar"){ + val jar = tasks.named("jar") { archiveFileName = "${modArtifact}Desktop.jar" val meta = layout.projectDirectory.file("$temporaryDir/mod.json") from( files(sourceSets["main"].output.classesDirs), files(sourceSets["main"].output.resourcesDir), - configurations.runtimeClasspath.map{conf -> conf.map{if(it.isDirectory) it else zipTree(it)}}, + configurations.runtimeClasspath.map { conf -> conf.map { if (it.isDirectory) it else zipTree(it) } }, files(layout.projectDirectory.dir("assets")), layout.projectDirectory.file("icon.png"), @@ -171,66 +171,65 @@ project(":"){ ) metaInf.from(layout.projectDirectory.file("LICENSE")) - doFirst{ + doFirst { // Deliberately check if the mod meta is actually written in HJSON, since, well, some people actually use // it. But this is also not mentioned in the `README.md`, for the mischievous reason of driving beginners // into using JSON instead. val metaJson = layout.projectDirectory.file("mod.json") val metaHjson = layout.projectDirectory.file("mod.hjson") - if(metaJson.asFile.exists() && metaHjson.asFile.exists()){ + if (metaJson.asFile.exists() && metaHjson.asFile.exists()) { throw IllegalStateException("Ambiguous mod meta: both `mod.json` and `mod.hjson` exist.") - }else if(!metaJson.asFile.exists() && !metaHjson.asFile.exists()){ + } else if (!metaJson.asFile.exists() && !metaHjson.asFile.exists()) { throw IllegalStateException("Missing mod meta: neither `mod.json` nor `mod.hjson` exist.") } val isJson = metaJson.asFile.exists() - val map = (if(isJson) metaJson else metaHjson).asFile + val map = (if (isJson) metaJson else metaHjson).asFile .reader(Charsets.UTF_8) - .use{Jval.read(it)} + .use { Jval.read(it) } map.put("name", modName) - meta.asFile.writer(Charsets.UTF_8).use{file -> BufferedWriter(file).use{map.writeTo(it, Jval.Jformat.formatted)}} + meta.asFile.writer(Charsets.UTF_8).use { file -> BufferedWriter(file).use { map.writeTo(it, Jval.Jformat.formatted) } } } } - tasks.register("dex"){ + tasks.register("dex") { inputs.files(jar) - group="android" + group = "android" archiveFileName = "$modArtifact.jar" - val desktopJar = jar.flatMap{it.archiveFile} + val desktopJar = jar.flatMap { it.archiveFile } val dexJar = File(temporaryDir, "Dex.jar") from(zipTree(desktopJar), zipTree(dexJar)) - doFirst{ + doFirst { logger.lifecycle("Running `d8`.") - providers.exec{ + providers.exec { // Find Android SDK root. val sdkRoot = File( - OS.env("ANDROID_SDK_ROOT") ?: OS.env("ANDROID_HOME") ?: - throw IllegalStateException("Neither `ANDROID_SDK_ROOT` nor `ANDROID_HOME` is set.") + OS.env("ANDROID_SDK_ROOT") ?: OS.env("ANDROID_HOME") ?: throw IllegalStateException("Neither `ANDROID_SDK_ROOT` nor `ANDROID_HOME` is set.") ) // Find `d8`. - val d8 = File(sdkRoot, "build-tools/$androidBuildVersion/${if(OS.isWindows) "d8.bat" else "d8"}") - if(!d8.exists()) throw IllegalStateException("Android SDK `build-tools;$androidBuildVersion` isn't installed or is corrupted") + val d8 = File(sdkRoot, "build-tools/$androidBuildVersion/${if (OS.isWindows) "d8.bat" else "d8"}") + if (!d8.exists()) throw IllegalStateException("Android SDK `build-tools;$androidBuildVersion` isn't installed or is corrupted") // Initialize a release build. val input = desktopJar.get().asFile val command = arrayListOf("$d8", "--release", "--min-api", androidMinVersion, "--output", "$dexJar", "$input") // Include all compile and runtime classpath. - (configurations.compileClasspath.get().toList() + configurations.runtimeClasspath.get().toList()).forEach{ - if(it.exists()) command.addAll(arrayOf("--classpath", it.path)) + (configurations.compileClasspath.get().toList() + configurations.runtimeClasspath.get().toList()).forEach { + if (it.exists()) command.addAll(arrayOf("--classpath", it.path)) } // Include Android platform as library. val androidJar = File(sdkRoot, "platforms/android-$androidSdkVersion/android.jar") - if(!androidJar.exists()) throw IllegalStateException("Android SDK `platforms;android-$androidSdkVersion` isn't installed or is corrupted") + if (!androidJar.exists()) throw IllegalStateException("Android SDK `platforms;android-$androidSdkVersion` isn't installed or is corrupted") command.addAll(arrayOf("--lib", "$androidJar")) - if(OS.isWindows) command.addAll(0, arrayOf("cmd", "/c").toList()) + if (OS.isWindows) command.addAll(0, arrayOf("cmd", "/c").toList()) // Run `d8`. commandLine(command) @@ -238,15 +237,15 @@ project(":"){ } } - tasks.register("fetchClient"){ - group="run" + tasks.register("fetchClient") { + group = "run" src("https://github.com/Anuken/Mindustry/releases/download/$mindustryVersion/Mindustry.jar") dest(file("$rootDir/run/Mindustry.jar")) overwrite(false) } - tasks.register("runClient"){ - group="run" + tasks.register("runClient") { + group = "run" dependsOn("fetchClient") dependsOn("jar") @@ -264,9 +263,9 @@ project(":"){ mainClass.set("mindustry.desktop.DesktopLauncher") } - tasks.register("install"){ + tasks.register("install") { dependsOn("jar") - doLast{ + doLast { val folder = Fi.get(OS.getAppDataDirectoryString("Mindustry")).child("mods") folder.mkdirs() diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 84a0b92f..ad1210ac 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,5 @@ -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.2.1-bin.zip -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists +distributionBase = GRADLE_USER_HOME +distributionPath = wrapper/dists +distributionUrl = https\://services.gradle.org/distributions/gradle-8.2.1-bin.zip +zipStoreBase = GRADLE_USER_HOME +zipStorePath = wrapper/dists diff --git a/mod.json b/mod.json index 59a69c29..3c7184c2 100644 --- a/mod.json +++ b/mod.json @@ -1,10 +1,10 @@ { -"displayName": "Omaloon", -"name": "omaloon", -"author": "stabu, uujuju", -"main": "omaloon.OmaloonMod", -"description": "An ambitious modification aimed at expanding the game's standard campaign by adding a new star system.", -"version": "0.1.1Ah", -"minGameVersion": 146, -"java": true + "displayName": "Omaloon", + "name": "omaloon", + "author": "stabu, uujuju", + "main": "omaloon.OmaloonMod", + "description": "An ambitious modification aimed at expanding the game's standard campaign by adding a new star system.", + "version": "0.1.1Ah", + "minGameVersion": 146, + "java": true } \ No newline at end of file diff --git a/revisions/ChainedUnit/0.json b/revisions/ChainedUnit/0.json index 7e4a25c8..9b0e8f89 100644 --- a/revisions/ChainedUnit/0.json +++ b/revisions/ChainedUnit/0.json @@ -1 +1,100 @@ -{fields:[{name:abilities,type:"mindustry.entities.abilities.Ability[]"},{name:ammo,type:float},{name:childID,type:int},{name:controller,type:mindustry.entities.units.UnitController},{name:elevation,type:float},{name:flag,type:double},{name:grown,type:boolean},{name:health,type:float},{name:isShooting,type:boolean},{name:mineTile,type:mindustry.world.Tile},{name:mounts,type:"mindustry.entities.units.WeaponMount[]"},{name:parentID,type:int},{name:plans,type:arc.struct.Queue},{name:rotation,type:float},{name:shield,type:float},{name:spawnedByCore,type:boolean},{name:stack,type:mindustry.type.ItemStack},{name:statuses,type:arc.struct.Seq},{name:team,type:mindustry.game.Team},{name:type,type:mindustry.type.UnitType},{name:updateBuilding,type:boolean},{name:vel,type:arc.math.geom.Vec2},{name:x,type:float},{name:y,type:float}]} \ No newline at end of file +{ + fields: [ + { + name: abilities, + type: "mindustry.entities.abilities.Ability[]" + }, + { + name: ammo, + type: float + }, + { + name: childID, + type: int + }, + { + name: controller, + type: mindustry.entities.units.UnitController + }, + { + name: elevation, + type: float + }, + { + name: flag, + type: double + }, + { + name: grown, + type: boolean + }, + { + name: health, + type: float + }, + { + name: isShooting, + type: boolean + }, + { + name: mineTile, + type: mindustry.world.Tile + }, + { + name: mounts, + type: "mindustry.entities.units.WeaponMount[]" + }, + { + name: parentID, + type: int + }, + { + name: plans, + type: arc.struct.Queue + }, + { + name: rotation, + type: float + }, + { + name: shield, + type: float + }, + { + name: spawnedByCore, + type: boolean + }, + { + name: stack, + type: mindustry.type.ItemStack + }, + { + name: statuses, + type: arc.struct.Seq + }, + { + name: team, + type: mindustry.game.Team + }, + { + name: type, + type: mindustry.type.UnitType + }, + { + name: updateBuilding, + type: boolean + }, + { + name: vel, + type: arc.math.geom.Vec2 + }, + { + name: x, + type: float + }, + { + name: y, + type: float + } + ] +} \ No newline at end of file diff --git a/revisions/DroneUnit/0.json b/revisions/DroneUnit/0.json index 545bb6c8..f70b4f68 100644 --- a/revisions/DroneUnit/0.json +++ b/revisions/DroneUnit/0.json @@ -1 +1,88 @@ -{fields:[{name:abilities,type:"mindustry.entities.abilities.Ability[]"},{name:ammo,type:float},{name:controller,type:mindustry.entities.units.UnitController},{name:elevation,type:float},{name:flag,type:double},{name:health,type:float},{name:isShooting,type:boolean},{name:mineTile,type:mindustry.world.Tile},{name:mounts,type:"mindustry.entities.units.WeaponMount[]"},{name:plans,type:arc.struct.Queue},{name:rotation,type:float},{name:shield,type:float},{name:spawnedByCore,type:boolean},{name:stack,type:mindustry.type.ItemStack},{name:statuses,type:arc.struct.Seq},{name:team,type:mindustry.game.Team},{name:type,type:mindustry.type.UnitType},{name:updateBuilding,type:boolean},{name:vel,type:arc.math.geom.Vec2},{name:x,type:float},{name:y,type:float}]} \ No newline at end of file +{ + fields: [ + { + name: abilities, + type: "mindustry.entities.abilities.Ability[]" + }, + { + name: ammo, + type: float + }, + { + name: controller, + type: mindustry.entities.units.UnitController + }, + { + name: elevation, + type: float + }, + { + name: flag, + type: double + }, + { + name: health, + type: float + }, + { + name: isShooting, + type: boolean + }, + { + name: mineTile, + type: mindustry.world.Tile + }, + { + name: mounts, + type: "mindustry.entities.units.WeaponMount[]" + }, + { + name: plans, + type: arc.struct.Queue + }, + { + name: rotation, + type: float + }, + { + name: shield, + type: float + }, + { + name: spawnedByCore, + type: boolean + }, + { + name: stack, + type: mindustry.type.ItemStack + }, + { + name: statuses, + type: arc.struct.Seq + }, + { + name: team, + type: mindustry.game.Team + }, + { + name: type, + type: mindustry.type.UnitType + }, + { + name: updateBuilding, + type: boolean + }, + { + name: vel, + type: arc.math.geom.Vec2 + }, + { + name: x, + type: float + }, + { + name: y, + type: float + } + ] +} \ No newline at end of file diff --git a/revisions/FloatMechCoreUnit/0.json b/revisions/FloatMechCoreUnit/0.json index 653894aa..15020e78 100644 --- a/revisions/FloatMechCoreUnit/0.json +++ b/revisions/FloatMechCoreUnit/0.json @@ -1 +1,92 @@ -{fields:[{name:abilities,type:"mindustry.entities.abilities.Ability[]"},{name:ammo,type:float},{name:baseRotation,type:float},{name:controller,type:mindustry.entities.units.UnitController},{name:elevation,type:float},{name:flag,type:double},{name:health,type:float},{name:isShooting,type:boolean},{name:mineTile,type:mindustry.world.Tile},{name:mounts,type:"mindustry.entities.units.WeaponMount[]"},{name:plans,type:arc.struct.Queue},{name:rotation,type:float},{name:shield,type:float},{name:spawnedByCore,type:boolean},{name:stack,type:mindustry.type.ItemStack},{name:statuses,type:arc.struct.Seq},{name:team,type:mindustry.game.Team},{name:type,type:mindustry.type.UnitType},{name:updateBuilding,type:boolean},{name:vel,type:arc.math.geom.Vec2},{name:x,type:float},{name:y,type:float}]} \ No newline at end of file +{ + fields: [ + { + name: abilities, + type: "mindustry.entities.abilities.Ability[]" + }, + { + name: ammo, + type: float + }, + { + name: baseRotation, + type: float + }, + { + name: controller, + type: mindustry.entities.units.UnitController + }, + { + name: elevation, + type: float + }, + { + name: flag, + type: double + }, + { + name: health, + type: float + }, + { + name: isShooting, + type: boolean + }, + { + name: mineTile, + type: mindustry.world.Tile + }, + { + name: mounts, + type: "mindustry.entities.units.WeaponMount[]" + }, + { + name: plans, + type: arc.struct.Queue + }, + { + name: rotation, + type: float + }, + { + name: shield, + type: float + }, + { + name: spawnedByCore, + type: boolean + }, + { + name: stack, + type: mindustry.type.ItemStack + }, + { + name: statuses, + type: arc.struct.Seq + }, + { + name: team, + type: mindustry.game.Team + }, + { + name: type, + type: mindustry.type.UnitType + }, + { + name: updateBuilding, + type: boolean + }, + { + name: vel, + type: arc.math.geom.Vec2 + }, + { + name: x, + type: float + }, + { + name: y, + type: float + } + ] +} \ No newline at end of file diff --git a/revisions/FloatMechCoreUnit/1.json b/revisions/FloatMechCoreUnit/1.json index f9d94442..5a09230f 100644 --- a/revisions/FloatMechCoreUnit/1.json +++ b/revisions/FloatMechCoreUnit/1.json @@ -1 +1,89 @@ -{version:1,fields:[{name:abilities,type:"mindustry.entities.abilities.Ability[]"},{name:ammo,type:float},{name:controller,type:mindustry.entities.units.UnitController},{name:elevation,type:float},{name:flag,type:double},{name:health,type:float},{name:isShooting,type:boolean},{name:mineTile,type:mindustry.world.Tile},{name:mounts,type:"mindustry.entities.units.WeaponMount[]"},{name:plans,type:arc.struct.Queue},{name:rotation,type:float},{name:shield,type:float},{name:spawnedByCore,type:boolean},{name:stack,type:mindustry.type.ItemStack},{name:statuses,type:arc.struct.Seq},{name:team,type:mindustry.game.Team},{name:type,type:mindustry.type.UnitType},{name:updateBuilding,type:boolean},{name:vel,type:arc.math.geom.Vec2},{name:x,type:float},{name:y,type:float}]} \ No newline at end of file +{ + version: 1, + fields: [ + { + name: abilities, + type: "mindustry.entities.abilities.Ability[]" + }, + { + name: ammo, + type: float + }, + { + name: controller, + type: mindustry.entities.units.UnitController + }, + { + name: elevation, + type: float + }, + { + name: flag, + type: double + }, + { + name: health, + type: float + }, + { + name: isShooting, + type: boolean + }, + { + name: mineTile, + type: mindustry.world.Tile + }, + { + name: mounts, + type: "mindustry.entities.units.WeaponMount[]" + }, + { + name: plans, + type: arc.struct.Queue + }, + { + name: rotation, + type: float + }, + { + name: shield, + type: float + }, + { + name: spawnedByCore, + type: boolean + }, + { + name: stack, + type: mindustry.type.ItemStack + }, + { + name: statuses, + type: arc.struct.Seq + }, + { + name: team, + type: mindustry.game.Team + }, + { + name: type, + type: mindustry.type.UnitType + }, + { + name: updateBuilding, + type: boolean + }, + { + name: vel, + type: arc.math.geom.Vec2 + }, + { + name: x, + type: float + }, + { + name: y, + type: float + } + ] +} \ No newline at end of file diff --git a/revisions/FloatMechCoreUnit/2.json b/revisions/FloatMechCoreUnit/2.json index 9c21579d..f05cbec1 100644 --- a/revisions/FloatMechCoreUnit/2.json +++ b/revisions/FloatMechCoreUnit/2.json @@ -1 +1,93 @@ -{version:2,fields:[{name:abilities,type:"mindustry.entities.abilities.Ability[]"},{name:ammo,type:float},{name:baseRotation,type:float},{name:controller,type:mindustry.entities.units.UnitController},{name:elevation,type:float},{name:flag,type:double},{name:health,type:float},{name:isShooting,type:boolean},{name:mineTile,type:mindustry.world.Tile},{name:mounts,type:"mindustry.entities.units.WeaponMount[]"},{name:plans,type:arc.struct.Queue},{name:rotation,type:float},{name:shield,type:float},{name:spawnedByCore,type:boolean},{name:stack,type:mindustry.type.ItemStack},{name:statuses,type:arc.struct.Seq},{name:team,type:mindustry.game.Team},{name:type,type:mindustry.type.UnitType},{name:updateBuilding,type:boolean},{name:vel,type:arc.math.geom.Vec2},{name:x,type:float},{name:y,type:float}]} \ No newline at end of file +{ + version: 2, + fields: [ + { + name: abilities, + type: "mindustry.entities.abilities.Ability[]" + }, + { + name: ammo, + type: float + }, + { + name: baseRotation, + type: float + }, + { + name: controller, + type: mindustry.entities.units.UnitController + }, + { + name: elevation, + type: float + }, + { + name: flag, + type: double + }, + { + name: health, + type: float + }, + { + name: isShooting, + type: boolean + }, + { + name: mineTile, + type: mindustry.world.Tile + }, + { + name: mounts, + type: "mindustry.entities.units.WeaponMount[]" + }, + { + name: plans, + type: arc.struct.Queue + }, + { + name: rotation, + type: float + }, + { + name: shield, + type: float + }, + { + name: spawnedByCore, + type: boolean + }, + { + name: stack, + type: mindustry.type.ItemStack + }, + { + name: statuses, + type: arc.struct.Seq + }, + { + name: team, + type: mindustry.game.Team + }, + { + name: type, + type: mindustry.type.UnitType + }, + { + name: updateBuilding, + type: boolean + }, + { + name: vel, + type: arc.math.geom.Vec2 + }, + { + name: x, + type: float + }, + { + name: y, + type: float + } + ] +} \ No newline at end of file diff --git a/revisions/OrnitopterFlyingUnit/0.json b/revisions/OrnitopterFlyingUnit/0.json index c7ff2f33..adbda371 100644 --- a/revisions/OrnitopterFlyingUnit/0.json +++ b/revisions/OrnitopterFlyingUnit/0.json @@ -1 +1,108 @@ -{fields:[{name:abilities,type:"mindustry.entities.abilities.Ability[]"},{name:ammo,type:float},{name:bladeMoveSpeedScl,type:float},{name:blades,type:"omaloon.type.Blade.BladeMount[]"},{name:controller,type:mindustry.entities.units.UnitController},{name:drawSeed,type:long},{name:driftAngle,type:float},{name:elevation,type:float},{name:flag,type:double},{name:hasDriftAngle,type:boolean},{name:health,type:float},{name:isShooting,type:boolean},{name:mineTile,type:mindustry.world.Tile},{name:mounts,type:"mindustry.entities.units.WeaponMount[]"},{name:plans,type:arc.struct.Queue},{name:rotation,type:float},{name:shield,type:float},{name:spawnedByCore,type:boolean},{name:stack,type:mindustry.type.ItemStack},{name:statuses,type:arc.struct.Seq},{name:team,type:mindustry.game.Team},{name:type,type:mindustry.type.UnitType},{name:updateBuilding,type:boolean},{name:vel,type:arc.math.geom.Vec2},{name:x,type:float},{name:y,type:float}]} \ No newline at end of file +{ + fields: [ + { + name: abilities, + type: "mindustry.entities.abilities.Ability[]" + }, + { + name: ammo, + type: float + }, + { + name: bladeMoveSpeedScl, + type: float + }, + { + name: blades, + type: "omaloon.type.Blade.BladeMount[]" + }, + { + name: controller, + type: mindustry.entities.units.UnitController + }, + { + name: drawSeed, + type: long + }, + { + name: driftAngle, + type: float + }, + { + name: elevation, + type: float + }, + { + name: flag, + type: double + }, + { + name: hasDriftAngle, + type: boolean + }, + { + name: health, + type: float + }, + { + name: isShooting, + type: boolean + }, + { + name: mineTile, + type: mindustry.world.Tile + }, + { + name: mounts, + type: "mindustry.entities.units.WeaponMount[]" + }, + { + name: plans, + type: arc.struct.Queue + }, + { + name: rotation, + type: float + }, + { + name: shield, + type: float + }, + { + name: spawnedByCore, + type: boolean + }, + { + name: stack, + type: mindustry.type.ItemStack + }, + { + name: statuses, + type: arc.struct.Seq + }, + { + name: team, + type: mindustry.game.Team + }, + { + name: type, + type: mindustry.type.UnitType + }, + { + name: updateBuilding, + type: boolean + }, + { + name: vel, + type: arc.math.geom.Vec2 + }, + { + name: x, + type: float + }, + { + name: y, + type: float + } + ] +} \ No newline at end of file diff --git a/settings.gradle.kts b/settings.gradle.kts index d96a7cb7..6254dbd8 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -1,32 +1,32 @@ import groovy.lang.Closure -pluginManagement{ - repositories{ +pluginManagement { + repositories { gradlePluginPortal() maven("https://raw.githubusercontent.com/GlennFolker/EntityAnnoMaven/main") } - plugins{ + plugins { val entVersion: String by settings - id("com.github.GlennFolker.EntityAnno") version(entVersion) + id("com.github.GlennFolker.EntityAnno") version (entVersion) } } -if(JavaVersion.current().ordinal < JavaVersion.VERSION_17.ordinal){ +if (JavaVersion.current().ordinal < JavaVersion.VERSION_17.ordinal) { throw IllegalStateException("JDK 17 is a required minimum version. Yours: ${System.getProperty("java.version")}") } include("annotations") val localprop = java.util.Properties() -if(file("local.properties").exists()) localprop.load(file("local.properties").reader()) +if (file("local.properties").exists()) localprop.load(file("local.properties").reader()) val asmLibPath = localprop["asm_lib_path"] -if(asmLibPath != null){ +if (asmLibPath != null) { println("Loading local AsmLib") val root = file(asmLibPath) val includeSelfPath = File(root, "includeSelf.gradle").canonicalPath - apply{ + apply { from(includeSelfPath) } (extra["includeSelf"] as Closure<*>).call(root) diff --git a/src/asmlib/annotations/DebugAST.java b/src/asmlib/annotations/DebugAST.java index 0728ee08..bee11dcc 100644 --- a/src/asmlib/annotations/DebugAST.java +++ b/src/asmlib/annotations/DebugAST.java @@ -1,5 +1,5 @@ package asmlib.annotations; -public @interface DebugAST { +public @interface DebugAST{ String outfile() default ""; } diff --git a/src/omaloon/OmaloonMod.java b/src/omaloon/OmaloonMod.java index 8d7a0e9e..92698be0 100644 --- a/src/omaloon/OmaloonMod.java +++ b/src/omaloon/OmaloonMod.java @@ -18,7 +18,7 @@ import omaloon.utils.*; import omaloon.world.blocks.environment.*; -import static arc.Core.*; +import static arc.Core.app; public class OmaloonMod extends Mod{ public static EditorListener editorListener; @@ -43,13 +43,13 @@ public OmaloonMod(){ Events.on(EventType.ClientLoadEvent.class, e -> { StartSplash.build(Vars.ui.menuGroup); StartSplash.show(); - if (!Vars.mobile && !Vars.headless) { + if(!Vars.mobile && !Vars.headless){ shapedEnvPlacerFragment.build(Vars.ui.hudGroup); cliffFragment.build(Vars.ui.hudGroup); OlBinding.load(); } Vars.maps.all().removeAll(map -> { - if (map.mod != null && map.mod.name.equals("omaloon")) { + if(map.mod != null && map.mod.name.equals("omaloon")){ Mods.LoadedMod otherMod = Vars.mods.getMod("test-utils"); return otherMod == null || !otherMod.enabled(); } @@ -59,7 +59,7 @@ public OmaloonMod(){ }); - if(!Vars.headless) { + if(!Vars.headless){ editorListener = new EditorListener(); } Events.on(EventType.ClientLoadEvent.class, ignored -> { @@ -72,24 +72,24 @@ public OmaloonMod(){ }); Events.on(EventType.FileTreeInitEvent.class, e -> - app.post(OlShaders::load) + app.post(OlShaders::load) ); Events.on(EventType.MusicRegisterEvent.class, e -> - OlMusics.load() + OlMusics.load() ); Events.on(EventType.DisposeEvent.class, e -> - OlShaders.dispose() + OlShaders.dispose() ); Log.info("Loaded OmaloonMod constructor."); } @Override - public void init() { + public void init(){ super.init(); - if (!Vars.headless) { + if(!Vars.headless){ shapedEnvPlacerFragment = new ShapedEnvPlacerFragment(); cliffFragment = new CliffFragment(); olInputDialog = new OlInputDialog(); @@ -97,9 +97,9 @@ public void init() { olGameDialog = new OlGameDialog(); olEndDialog = new OlEndDialog(); Events.on(EventType.SectorCaptureEvent.class, e -> { - if (e.sector.preset == OlSectorPresets.deadValley) olEndDialog.show(Core.scene, Actions.sequence( - Actions.fadeOut(0), - Actions.fadeIn(1) + if(e.sector.preset == OlSectorPresets.deadValley) olEndDialog.show(Core.scene, Actions.sequence( + Actions.fadeOut(0), + Actions.fadeIn(1) )); }); } @@ -122,16 +122,16 @@ public void loadContent(){ OlTechTree.load(); } - public static void resetSaves(Planet planet) { + public static void resetSaves(Planet planet){ planet.sectors.each(sector -> { - if (sector.hasSave()) { - sector.save.delete(); - sector.save = null; + if(sector.hasSave()){ + sector.save.delete(); + sector.save = null; } }); } - public static void resetTree(TechNode root) { + public static void resetTree(TechNode root){ root.reset(); root.content.clearUnlock(); root.children.each(OmaloonMod::resetTree); diff --git a/src/omaloon/ai/CowardAI.java b/src/omaloon/ai/CowardAI.java index f98d3be8..c88fc4a0 100644 --- a/src/omaloon/ai/CowardAI.java +++ b/src/omaloon/ai/CowardAI.java @@ -2,24 +2,24 @@ import mindustry.ai.types.*; -import static mindustry.Vars.*; +import static mindustry.Vars.state; -public class CowardAI extends FlyingAI { - @Override - public void updateMovement(){ - unloadPayloads(); +public class CowardAI extends FlyingAI{ + @Override + public void updateMovement(){ + unloadPayloads(); - if(target != null && unit.hasWeapons()){ - if(unit.health >= unit.maxHealth){ - circleAttack(120f); - }else{ - moveTo(target, unit.type.range * 0.8f, 20f); - unit.lookAt(target); - } - } + if(target != null && unit.hasWeapons()){ + if(unit.health >= unit.maxHealth){ + circleAttack(120f); + }else{ + moveTo(target, unit.type.range * 0.8f, 20f); + unit.lookAt(target); + } + } - if(target == null && state.rules.waves && unit.team == state.rules.defaultTeam){ - moveTo(getClosestSpawner(), state.rules.dropZoneRadius + 130f); - } - } + if(target == null && state.rules.waves && unit.team == state.rules.defaultTeam){ + moveTo(getClosestSpawner(), state.rules.dropZoneRadius + 130f); + } + } } diff --git a/src/omaloon/ai/DroneAI.java b/src/omaloon/ai/DroneAI.java index 2e93ce20..fca9f3d7 100644 --- a/src/omaloon/ai/DroneAI.java +++ b/src/omaloon/ai/DroneAI.java @@ -5,20 +5,20 @@ import mindustry.entities.units.*; import mindustry.gen.*; -public class DroneAI extends AIController { +public class DroneAI extends AIController{ protected Unit owner; protected Vec2 anchorPos; protected PosTeam posTeam; - public DroneAI(Unit owner) { + public DroneAI(Unit owner){ this.owner = owner; this.anchorPos = new Vec2(); this.posTeam = PosTeam.create(); } @Override - public void updateUnit() { - if (!owner.isValid()) { + public void updateUnit(){ + if(!owner.isValid()){ Call.unitDespawn(unit); return; } @@ -26,15 +26,15 @@ public void updateUnit() { } @Override - public void updateMovement() { + public void updateMovement(){ rally(); } - public void rally(Vec2 pos) { + public void rally(Vec2 pos){ anchorPos = pos; } - public void rally() { + public void rally(){ Tmp.v2.set(owner.x, owner.y); Vec2 targetPos = Tmp.v1.set(anchorPos).add(Tmp.v2).rotateAround(Tmp.v2, owner.rotation - 90); @@ -42,9 +42,9 @@ public void rally() { moveTo(targetPos, 2f, 30f); - if (distance > 5f) { + if(distance > 5f){ unit.lookAt(targetPos.x, targetPos.y); - } else { + }else{ unit.lookAt(owner.rotation()); } } diff --git a/src/omaloon/ai/MillipedeAI.java b/src/omaloon/ai/MillipedeAI.java index f9332893..b85c8d4d 100644 --- a/src/omaloon/ai/MillipedeAI.java +++ b/src/omaloon/ai/MillipedeAI.java @@ -8,115 +8,114 @@ import mindustry.entities.units.*; import mindustry.gen.*; import mindustry.type.*; -import omaloon.gen.*; - -public class MillipedeAI extends GroundAI { - protected Vec2 commandPosition = new Vec2(); - protected Teamc commandTarget; - - @Override - public void updateWeapons() { - if (!(unit instanceof Chainedc millipedec)) return; - if (!millipedec.isHead()) return; - - float rotation = unit.rotation - 90; - boolean ret = retarget(); - - if(ret) { - target = findMainTarget(unit.x, unit.y, unit.range(), unit.type.targetAir, unit.type.targetGround); - } - - noTargetTime += Time.delta; - - if(invalid(target)) { - target = null; - }else noTargetTime = 0f; - - unit.isShooting = false; - - cast().consBackwards(u -> { - for(WeaponMount mount : u.mounts){ - Weapon weapon = mount.weapon; - float wrange = weapon.range(); - - if(!weapon.controllable || weapon.noAttack) continue; - if(!weapon.aiControllable){ - mount.rotate = false; - continue; - } - - float - mountX = u.x + Angles.trnsx(rotation, weapon.x, weapon.y), - mountY = u.y + Angles.trnsy(rotation, weapon.x, weapon.y); - - if(unit.type.singleTarget){ - mount.target = target; - }else{ - if(ret) mount.target = findTarget(mountX, mountY, wrange, weapon.bullet.collidesAir, weapon.bullet.collidesGround); - if(checkTarget(mount.target, mountX, mountY, wrange)) mount.target = null; - } - - boolean shoot = false; - - if(mount.target != null){ - shoot = mount.target.within(mountX, mountY, wrange + (mount.target instanceof Sized s ? s.hitSize()/2f : 0f)) && shouldShoot(); - - Vec2 to = Predict.intercept(unit, mount.target, weapon.bullet.speed); - mount.aimX = to.x; - mount.aimY = to.y; - } - - unit.isShooting |= (mount.shoot = mount.rotate = shoot); - - if(mount.target == null && !shoot && !Angles.within(mount.rotation, mount.weapon.baseRotation, 0.01f) && noTargetTime >= rotateBackTimer){ - mount.rotate = true; - Tmp.v1.trns(u.rotation + mount.weapon.baseRotation, 5f); - mount.aimX = mountX + Tmp.v1.x; - mount.aimY = mountY + Tmp.v1.y; - } - - if(shoot){ - unit.aimX = mount.aimX; - unit.aimY = mount.aimY; - } - } - }); - } - - @Override - public void updateMovement() { - if (commandTarget != null && !unit.within(commandTarget, unit.type.range * 0.8f)) { - moveTo(commandTarget, unit.type.range * 0.8f); - } else if (!commandPosition.isZero()) { - moveTo(commandPosition, 0); - } else { - super.updateMovement(); - } - - faceTarget(); - } - - @Override - public Teamc findTarget(float x, float y, float range, boolean air, boolean ground) { - Teamc target = commandTarget != null && commandTarget.within(x, y, range) && - commandTarget.team() == unit.team && commandTarget.isNull() ? commandTarget : null; - - return target != null ? target : super.findTarget(x, y, range, air, ground); - } - - @Override - public void commandPosition(Vec2 pos) { - this.commandPosition.set(pos); - this.commandTarget = null; - } - - @Override - public void commandTarget(Teamc moveTo) { - this.commandTarget = moveTo; - this.commandPosition.setZero(); - } - - public T cast() { - return (T) unit; - } + +public class MillipedeAI extends GroundAI{ + protected Vec2 commandPosition = new Vec2(); + protected Teamc commandTarget; + + @Override + public void updateWeapons(){ + if(!(unit instanceof Chainedc millipedec)) return; + if(!millipedec.isHead()) return; + + float rotation = unit.rotation - 90; + boolean ret = retarget(); + + if(ret){ + target = findMainTarget(unit.x, unit.y, unit.range(), unit.type.targetAir, unit.type.targetGround); + } + + noTargetTime += Time.delta; + + if(invalid(target)){ + target = null; + }else noTargetTime = 0f; + + unit.isShooting = false; + + cast().consBackwards(u -> { + for(WeaponMount mount : u.mounts){ + Weapon weapon = mount.weapon; + float wrange = weapon.range(); + + if(!weapon.controllable || weapon.noAttack) continue; + if(!weapon.aiControllable){ + mount.rotate = false; + continue; + } + + float + mountX = u.x + Angles.trnsx(rotation, weapon.x, weapon.y), + mountY = u.y + Angles.trnsy(rotation, weapon.x, weapon.y); + + if(unit.type.singleTarget){ + mount.target = target; + }else{ + if(ret) mount.target = findTarget(mountX, mountY, wrange, weapon.bullet.collidesAir, weapon.bullet.collidesGround); + if(checkTarget(mount.target, mountX, mountY, wrange)) mount.target = null; + } + + boolean shoot = false; + + if(mount.target != null){ + shoot = mount.target.within(mountX, mountY, wrange + (mount.target instanceof Sized s ? s.hitSize() / 2f : 0f)) && shouldShoot(); + + Vec2 to = Predict.intercept(unit, mount.target, weapon.bullet.speed); + mount.aimX = to.x; + mount.aimY = to.y; + } + + unit.isShooting |= (mount.shoot = mount.rotate = shoot); + + if(mount.target == null && !shoot && !Angles.within(mount.rotation, mount.weapon.baseRotation, 0.01f) && noTargetTime >= rotateBackTimer){ + mount.rotate = true; + Tmp.v1.trns(u.rotation + mount.weapon.baseRotation, 5f); + mount.aimX = mountX + Tmp.v1.x; + mount.aimY = mountY + Tmp.v1.y; + } + + if(shoot){ + unit.aimX = mount.aimX; + unit.aimY = mount.aimY; + } + } + }); + } + + @Override + public void updateMovement(){ + if(commandTarget != null && !unit.within(commandTarget, unit.type.range * 0.8f)){ + moveTo(commandTarget, unit.type.range * 0.8f); + }else if(!commandPosition.isZero()){ + moveTo(commandPosition, 0); + }else{ + super.updateMovement(); + } + + faceTarget(); + } + + @Override + public Teamc findTarget(float x, float y, float range, boolean air, boolean ground){ + Teamc target = commandTarget != null && commandTarget.within(x, y, range) && + commandTarget.team() == unit.team && commandTarget.isNull() ? commandTarget : null; + + return target != null ? target : super.findTarget(x, y, range, air, ground); + } + + @Override + public void commandPosition(Vec2 pos){ + this.commandPosition.set(pos); + this.commandTarget = null; + } + + @Override + public void commandTarget(Teamc moveTo){ + this.commandTarget = moveTo; + this.commandPosition.setZero(); + } + + public T cast(){ + return (T)unit; + } } \ No newline at end of file diff --git a/src/omaloon/ai/drone/AttackDroneAI.java b/src/omaloon/ai/drone/AttackDroneAI.java index 8eec2aad..00682a37 100644 --- a/src/omaloon/ai/drone/AttackDroneAI.java +++ b/src/omaloon/ai/drone/AttackDroneAI.java @@ -3,25 +3,25 @@ import mindustry.gen.*; import omaloon.ai.*; -public class AttackDroneAI extends DroneAI { - public AttackDroneAI(Unit owner) { +public class AttackDroneAI extends DroneAI{ + public AttackDroneAI(Unit owner){ super(owner); } @Override - public void updateMovement() { - if (owner.isShooting()) { - if (unit.hasWeapons()) { + public void updateMovement(){ + if(owner.isShooting()){ + if(unit.hasWeapons()){ posTeam.set(owner.aimX(), owner.aimY()); float distanceToTarget = unit.dst(posTeam); float distanceToOwner = unit.dst(owner); - if (distanceToOwner < owner.range()) { + if(distanceToOwner < owner.range()){ moveTo(posTeam, unit.type().range * 0.75f, 30f); - } else { + }else{ moveTo(owner, owner.range() * 0.95f, 30f); - if (distanceToTarget > unit.type().range) { + if(distanceToTarget > unit.type().range){ unit.lookAt(posTeam); unit.controlWeapons(true, true); } @@ -29,18 +29,18 @@ public void updateMovement() { unit.lookAt(posTeam); } - } else { + }else{ rally(); } } @Override - public Teamc target(float x, float y, float range, boolean air, boolean ground) { + public Teamc target(float x, float y, float range, boolean air, boolean ground){ return (!owner.isValid() && !owner.isShooting()) ? null : posTeam; } @Override - public boolean shouldShoot() { + public boolean shouldShoot(){ return owner.isShooting(); } } \ No newline at end of file diff --git a/src/omaloon/ai/drone/UtilityDroneAI.java b/src/omaloon/ai/drone/UtilityDroneAI.java index 52771a04..0f175bf3 100644 --- a/src/omaloon/ai/drone/UtilityDroneAI.java +++ b/src/omaloon/ai/drone/UtilityDroneAI.java @@ -10,86 +10,87 @@ import mindustry.world.blocks.*; import omaloon.ai.*; -public class UtilityDroneAI extends DroneAI { - public float mineRangeScl = 0.75f; - public float buildRangeScl = 0.75f; +public class UtilityDroneAI extends DroneAI{ + public float mineRangeScl = 0.75f; + public float buildRangeScl = 0.75f; - public @Nullable Teams.BlockPlan lastPlan; + public @Nullable Teams.BlockPlan lastPlan; - public UtilityDroneAI(Unit owner) { - super(owner); - } + public UtilityDroneAI(Unit owner){ + super(owner); + } - @Override - public void updateMovement() { - unit.updateBuilding = true; + @Override + public void updateMovement(){ + unit.updateBuilding = true; - if (owner.activelyBuilding()) { - unit.plans.clear(); + if(owner.activelyBuilding()){ + unit.plans.clear(); - BuildPlan plan = owner.buildPlan(); - if (!unit.plans.contains(plan))unit.plans.addFirst(plan); - lastPlan = null; + BuildPlan plan = owner.buildPlan(); + if(!unit.plans.contains(plan)) unit.plans.addFirst(plan); + lastPlan = null; - if (unit.buildPlan() != null) { - BuildPlan req = unit.buildPlan(); + if(unit.buildPlan() != null){ + BuildPlan req = unit.buildPlan(); - if (!req.breaking && timer.get(timerTarget2, 40f)) { - for (Player player : Groups.player) { - if (player.isBuilder() && player.unit().activelyBuilding() && player.unit().buildPlan().samePos(req) && player.unit().buildPlan().breaking) { - unit.plans.removeFirst(); - unit.team.data().plans.remove(p -> p.x == req.x && p.y == req.y); - return; - } - } - } + if(!req.breaking && timer.get(timerTarget2, 40f)){ + for(Player player : Groups.player){ + if(player.isBuilder() && player.unit().activelyBuilding() && player.unit().buildPlan().samePos(req) && player.unit().buildPlan().breaking){ + unit.plans.removeFirst(); + unit.team.data().plans.remove(p -> p.x == req.x && p.y == req.y); + return; + } + } + } - boolean valid = !(lastPlan != null && lastPlan.removed) && - ((req.tile() != null && req.tile().build instanceof ConstructBlock.ConstructBuild cons && cons.current == req.block) || - (req.breaking ? Build.validBreak(unit.team(), req.x, req.y) : - Build.validPlace(req.block, unit.team(), req.x, req.y, req.rotation))); + boolean valid = !(lastPlan != null && lastPlan.removed) && + ((req.tile() != null && req.tile().build instanceof ConstructBlock.ConstructBuild cons && cons.current == req.block) || + (req.breaking ? Build.validBreak(unit.team(), req.x, req.y) : + Build.validPlace(req.block, unit.team(), req.x, req.y, req.rotation))); - if (valid) { - moveTo(req.tile(), unit.type.buildRange * buildRangeScl, 30f); - } else { - unit.plans.removeFirst(); - lastPlan = null; - } - } - } else { - unit.plans.clear(); - if (owner.mineTile() != null && owner.stack.amount != owner.type.itemCapacity && - ((owner.getMineResult(owner.mineTile) == owner.stack.item && owner.stack.amount > 0) || - (owner.stack.amount == 0))) { - Tmp.v1.set(owner.mineTile.worldx(), owner.mineTile.worldy()); - if (unit.dst(Tmp.v1) <= unit.type.mineRange) unit.mineTile = owner.mineTile; - moveTo(Tmp.v1, unit.type.mineRange * mineRangeScl, 30f); - } else { - unit.mineTile = null; - rally(); - } - } + if(valid){ + moveTo(req.tile(), unit.type.buildRange * buildRangeScl, 30f); + }else{ + unit.plans.removeFirst(); + lastPlan = null; + } + } + }else{ + unit.plans.clear(); + if(owner.mineTile() != null && owner.stack.amount != owner.type.itemCapacity && + ((owner.getMineResult(owner.mineTile) == owner.stack.item && owner.stack.amount > 0) || + (owner.stack.amount == 0))){ + Tmp.v1.set(owner.mineTile.worldx(), owner.mineTile.worldy()); + if(unit.dst(Tmp.v1) <= unit.type.mineRange) unit.mineTile = owner.mineTile; + moveTo(Tmp.v1, unit.type.mineRange * mineRangeScl, 30f); + }else{ + unit.mineTile = null; + rally(); + } + } - if (unit.stack.amount > 0) { - if (!unit.within(unit.closestCore(), owner.type.range) && unit.closestCore() != null) { - for (int i = 0; i < unit.stack.amount; i++) { - Call.transferItemToUnit(unit.stack.item, unit.x, unit.y, owner); - } - } else { - Call.transferItemTo(unit, unit.stack.item, unit.stack.amount, unit.x, unit.y, unit.closestCore()); - } - unit.clearItem(); - } - } + if(unit.stack.amount > 0){ + if(!unit.within(unit.closestCore(), owner.type.range) && unit.closestCore() != null){ + for(int i = 0; i < unit.stack.amount; i++){ + Call.transferItemToUnit(unit.stack.item, unit.x, unit.y, owner); + } + }else{ + Call.transferItemTo(unit, unit.stack.item, unit.stack.amount, unit.x, unit.y, unit.closestCore()); + } + unit.clearItem(); + } + } - //TODO: implement ignoring shouldSkip plans - /** @return whether this plan should be skipped, in favor of the next one.*/ - @SuppressWarnings({"unused"}) - boolean shouldSkip(BuildPlan plan, @Nullable Building core) { - //plans that you have at least *started* are considered - if (Vars.state.rules.infiniteResources || unit.team.rules().infiniteResources || plan.breaking || core == null || plan.isRotation(unit.team) || (unit.isBuilding() && !unit.within(unit.plans.last(), owner.type.buildRange + unit.type.buildRange))) - return false; + //TODO: implement ignoring shouldSkip plans - return (plan.stuck && !core.items.has(plan.block.requirements)) || (Structs.contains(plan.block.requirements, i -> !core.items.has(i.item, Math.min(i.amount, 15)) && Mathf.round(i.amount * Vars.state.rules.buildCostMultiplier) > 0) && !plan.initialized); - } + /** @return whether this plan should be skipped, in favor of the next one. */ + @SuppressWarnings({"unused"}) + boolean shouldSkip(BuildPlan plan, @Nullable Building core){ + //plans that you have at least *started* are considered + if(Vars.state.rules.infiniteResources || unit.team.rules().infiniteResources || plan.breaking || core == null || plan.isRotation(unit.team) || (unit.isBuilding() && !unit.within(unit.plans.last(), owner.type.buildRange + unit.type.buildRange))) + return false; + + return (plan.stuck && !core.items.has(plan.block.requirements)) || (Structs.contains(plan.block.requirements, i -> !core.items.has(i.item, Math.min(i.amount, 15)) && Mathf.round(i.amount * Vars.state.rules.buildCostMultiplier) > 0) && !plan.initialized); + } } diff --git a/src/omaloon/annotations/AutoImplement.java b/src/omaloon/annotations/AutoImplement.java index ab334d17..c70b1da0 100644 --- a/src/omaloon/annotations/AutoImplement.java +++ b/src/omaloon/annotations/AutoImplement.java @@ -1,49 +1,51 @@ package omaloon.annotations; -import java.lang.annotation.ElementType; -import java.lang.annotation.Target; +import java.lang.annotation.*; @Target(ElementType.TYPE) -public @interface AutoImplement { +public @interface AutoImplement{ @Target(ElementType.METHOD) - @interface NoInject { - Class[] value(); + @interface NoInject{ + Class[] value(); } /** * This need ONLY for Annotation Processing, and it will be removed during compilation */ - interface Util { - static T Inject(Class type, Object... args) { + interface Util{ + static T Inject(Class type, Object... args){ return error(); } - static T Param(String paramName, String defaultExpression) { + static T Param(String paramName, String defaultExpression){ return error(); } - static T error() { + static T error(){ throw new RuntimeException("Why are you calling this?! This need ONLY for Annotation Processing and it will be removed during compilation"); } - @interface SetParam { + @interface SetParam{ String name(); + String value(); } } - public @interface Inject { + public @interface Inject{ InjectPosition value(); + boolean shouldAddSuper() default true; + enum InjectPosition{ - AfterSuper,BeforeSuper, + AfterSuper, BeforeSuper, - Head,Tail; + Head, Tail; } } } diff --git a/src/omaloon/annotations/Load.java b/src/omaloon/annotations/Load.java index aa00a5c1..117bebcd 100644 --- a/src/omaloon/annotations/Load.java +++ b/src/omaloon/annotations/Load.java @@ -1,13 +1,10 @@ package omaloon.annotations; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; +import java.lang.annotation.*; @Target(ElementType.FIELD) @Retention(RetentionPolicy.SOURCE) -public @interface Load { +public @interface Load{ /** * The region name to load. Variables can be used: * "@" -> block name diff --git a/src/omaloon/annotations/RemoveFromCompilation.java b/src/omaloon/annotations/RemoveFromCompilation.java index 7921dde8..9b919a75 100644 --- a/src/omaloon/annotations/RemoveFromCompilation.java +++ b/src/omaloon/annotations/RemoveFromCompilation.java @@ -1,4 +1,4 @@ package omaloon.annotations; -public @interface RemoveFromCompilation { +public @interface RemoveFromCompilation{ } diff --git a/src/omaloon/content/OlBlocks.java b/src/omaloon/content/OlBlocks.java index 22536657..ec24c973 100644 --- a/src/omaloon/content/OlBlocks.java +++ b/src/omaloon/content/OlBlocks.java @@ -2,7 +2,7 @@ import omaloon.content.blocks.*; -public class OlBlocks { +public class OlBlocks{ public static void load(){ OlEnvironmentBlocks.load(); OlDefenceBlocks.load(); diff --git a/src/omaloon/content/OlFx.java b/src/omaloon/content/OlFx.java index 498945d4..580c6f55 100644 --- a/src/omaloon/content/OlFx.java +++ b/src/omaloon/content/OlFx.java @@ -16,15 +16,15 @@ import omaloon.world.*; import static arc.graphics.g2d.Draw.*; -import static arc.math.Angles.*; +import static arc.math.Angles.randLenVectors; -public class OlFx { +public class OlFx{ public static final Rand rand = new Rand(); public static final Vec2 vec = new Vec2(), vec2 = new Vec2(); public static Effect bigExplosionStone = new Effect(80f, e -> randLenVectors(e.id, 22, e.fin() * 50f, (x, y) -> { - float elevation = Interp.bounceIn.apply(e.fout() - 0.3f) * (Mathf.randomSeed((int) Angles.angle(x, y), 30f, 60f)); + float elevation = Interp.bounceIn.apply(e.fout() - 0.3f) * (Mathf.randomSeed((int)Angles.angle(x, y), 30f, 60f)); Draw.z(Layer.power + 0.1f); Draw.color(Pal.shadow); @@ -45,11 +45,11 @@ public class OlFx { Fill.circle(vec.x, vec.y, rad * e.fout()); }); - if (e.time <= 5)Effect.shake(0.5f, 5f, e.x, e.y); + if(e.time <= 5) Effect.shake(0.5f, 5f, e.x, e.y); }), explosionStone = new Effect(60f, e -> randLenVectors(e.id, 12, e.fin() * 50f, (x, y) -> { - float elevation = Interp.bounceIn.apply(e.fout() - 0.3f) * (Mathf.randomSeed((int) Angles.angle(x, y), 30f, 60f)); + float elevation = Interp.bounceIn.apply(e.fout() - 0.3f) * (Mathf.randomSeed((int)Angles.angle(x, y), 30f, 60f)); Draw.z(Layer.power + 0.1f); Draw.color(Pal.shadow); @@ -64,7 +64,7 @@ public class OlFx { if(!(e.data instanceof HailStoneBulletType.HailStoneData data)) return; rand.setSeed(e.id); - vec2.trns(rand.random(360f), data.fallTime/2f + rand.random(data.fallTime)); + vec2.trns(rand.random(360f), data.fallTime / 2f + rand.random(data.fallTime)); float scl = Interp.bounceIn.apply(e.fout() - 0.3f); float rot = vec2.angle(); float x = e.x + (vec2.x * e.finpow()), y = e.y + (vec2.y * e.finpow()); @@ -75,13 +75,13 @@ public class OlFx { Draw.z(Layer.power + 0.2f); Draw.color(e.color); Draw.alpha(e.fout()); - Draw.rect(data.region, x, y + (scl * data.fallTime/2f), rot); + Draw.rect(data.region, x, y + (scl * data.fallTime / 2f), rot); }), fellStoneAghanite = new Effect(120f, e -> { if(!(e.data instanceof HailStoneBulletType.HailStoneData data)) return; rand.setSeed(e.id); - vec2.trns(e.rotation + rand.range(30f), data.fallTime/2f + rand.random(data.fallTime)); + vec2.trns(e.rotation + rand.range(30f), data.fallTime / 2f + rand.random(data.fallTime)); float scl = Interp.bounceIn.apply(e.fout() - 0.3f); float rot = vec2.angle(); float x = e.x + (vec2.x * e.finpow()), y = e.y + (vec2.y * e.finpow()); @@ -92,7 +92,7 @@ public class OlFx { Draw.z(Layer.power + 0.2f); Draw.color(e.color); Draw.alpha(e.fout()); - Draw.rect(data.region, x, y + (scl * data.fallTime/2f), rot); + Draw.rect(data.region, x, y + (scl * data.fallTime / 2f), rot); }), drillHammerHit = new Effect(80f, e -> { @@ -101,7 +101,7 @@ public class OlFx { Draw.z(Layer.block); rand.setSeed(e.id); - for(int i = 0; i < 3; i++) { + for(int i = 0; i < 3; i++){ float len = rand.random(6f), rot = rand.range(40f) + e.rotation; e.scaled(e.lifetime * rand.random(0.3f, 1f), e2 -> { @@ -116,7 +116,7 @@ public class OlFx { color(e.color, e.fout(0.1f)); rand.setSeed(e.id); - for(int i = 0; i < 3; i++) { + for(int i = 0; i < 3; i++){ float len = rand.random(16f), rot = rand.range(360f) + e.rotation; e.scaled(e.lifetime * rand.random(0.3f, 1f), e2 -> { @@ -130,36 +130,36 @@ public class OlFx { hitSage = new Effect(30f, e -> { Lines.stroke(3f * e.fout(), Color.valueOf("8CA9E8")); Lines.circle(e.x, e.y, 32f * e.finpow()); - for(int i = 0; i < 4; i++) { + for(int i = 0; i < 4; i++){ Draw.color(Color.valueOf("D1EFFF")); Drawf.tri(e.x, e.y, 6f * e.fout(), 24f * e.finpow(), e.rotation + i * 90f + 45f); } }), stealInvalid = new Effect(60f, e -> { - if (!(e.data instanceof Block block)) return; + if(!(e.data instanceof Block block)) return; Draw.mixcol(Color.white, 0); Draw.alpha(e.fout()); Draw.rect( - block.uiIcon, - e.x + Math3D.xOffset(e.x, block.size * e.finpowdown()), - e.y + Math3D.yOffset(e.y, block.size * e.finpowdown()), - -45 * e.fin() + block.uiIcon, + e.x + Math3D.xOffset(e.x, block.size * e.finpowdown()), + e.y + Math3D.yOffset(e.y, block.size * e.finpowdown()), + -45 * e.fin() ); Draw.mixcol(Color.white, e.foutpow()); Draw.alpha(e.foutpowdown()); Draw.rect( - Core.atlas.find("omaloon-hail-shield-base"), - e.x + Math3D.xOffset(e.x, block.size * e.finpowdown()), - e.y + Math3D.yOffset(e.y, block.size * e.finpowdown()), - -45 * e.fin() + Time.time * 4 + Core.atlas.find("omaloon-hail-shield-base"), + e.x + Math3D.xOffset(e.x, block.size * e.finpowdown()), + e.y + Math3D.yOffset(e.y, block.size * e.finpowdown()), + -45 * e.fin() + Time.time * 4 ); Draw.rect( - Core.atlas.find("omaloon-hail-shield"), - e.x + Math3D.xOffset(e.x, block.size * e.finpowdown()), - e.y + Math3D.yOffset(e.y, block.size * e.finpowdown()), - -45 * e.fin() + Core.atlas.find("omaloon-hail-shield"), + e.x + Math3D.xOffset(e.x, block.size * e.finpowdown()), + e.y + Math3D.yOffset(e.y, block.size * e.finpowdown()), + -45 * e.fin() ); }).layer(Layer.effect + 1), @@ -250,16 +250,16 @@ public class OlFx { }), shelterRotate = new Effect(60f, e -> { - if (!(e.data instanceof Block data)) return; + if(!(e.data instanceof Block data)) return; Draw.color(Pal.accent, e.fout()); Fill.rect(e.x, e.y, data.size * 8f, data.size * 8f); Lines.stroke(2f * e.fout(), Pal.accent); Lines.rect( - e.x - data.size * 4f, - e.y - data.size * 4f, - data.size * 8f, - data.size * 8f + e.x - data.size * 4f, + e.y - data.size * 4f, + data.size * 8f, + data.size * 8f ); Lines.circle(e.x, e.y, data.size * 16f * e.finpow()); vec.trns(e.rotation, data.size * 16f * e.finpow()).add(e.x, e.y); @@ -271,9 +271,9 @@ public class OlFx { Draw.color(Color.valueOf("8CA9E8")); float - fin = Interp.circleOut.apply(e.fout()), - fin2 = new Interp.ExpOut(10, 10).apply(e.fin()), - fout = new Interp.ExpOut(10, 10).apply(e.fout()); + fin = Interp.circleOut.apply(e.fout()), + fin2 = new Interp.ExpOut(10, 10).apply(e.fin()), + fout = new Interp.ExpOut(10, 10).apply(e.fout()); float progress = e.fin(); @@ -282,21 +282,21 @@ public class OlFx { vec.trns(e.rotation, 5.5f - 15f * fin).add(e.x, e.y); EFill.donutEllipse( - vec.x, vec.y, - 4f * progress * fout, 14f * fout, - 2f * progress * fout, 12f * fout, - cover/360f, - -cover/2f, e.rotation + vec.x, vec.y, + 4f * progress * fout, 14f * fout, + 2f * progress * fout, 12f * fout, + cover / 360f, + -cover / 2f, e.rotation ); }).followParent(true).rotWithParent(true), breakShapedProp = new Effect(23, e -> { - if (!(e.data instanceof MultiPropGroup group)) return; + if(!(e.data instanceof MultiPropGroup group)) return; float scl = Math.max(e.rotation, 1); color(Tmp.c1.set(e.color).mul(1.1f)); - for (Tile tile : group.group) { + for(Tile tile : group.group){ randLenVectors(e.id + tile.pos(), 2, 19f * e.finpow() * scl, (x, y) -> { float wx = tile.worldx() + x; float wy = tile.worldy() + y; @@ -331,14 +331,14 @@ public class OlFx { float x = (scl * dis) + Mathf.cos(scl * 10) * force * rx; float y = Mathf.sin(scl * 10) * force * ry; - vec.trns(e.rotation,x, y); + vec.trns(e.rotation, x, y); vec.add(e.x, e.y); vec.add(Math3D.xOffset(e.x, z), Math3D.yOffset(e.y, z)); windTailPoints[i] = new Vec3(vec.x, vec.y, e.fslope()); } - for (int i = 0; i < windTailPoints.length - 1; i++) { + for(int i = 0; i < windTailPoints.length - 1; i++){ Vec3 v1 = windTailPoints[i]; Vec3 v2 = windTailPoints[i + 1]; diff --git a/src/omaloon/content/OlIcons.java b/src/omaloon/content/OlIcons.java index 77e16fb8..b0561592 100644 --- a/src/omaloon/content/OlIcons.java +++ b/src/omaloon/content/OlIcons.java @@ -2,12 +2,13 @@ import arc.scene.style.*; -import static arc.Core.*; -import static mindustry.gen.Icon.*; +import static arc.Core.atlas; +import static mindustry.gen.Icon.icons; -public class OlIcons { +public class OlIcons{ public static TextureRegionDrawable settings, glasmore, purpura; - public static void load() { + + public static void load(){ settings = atlas.getDrawable("omaloon-settings"); glasmore = atlas.getDrawable("omaloon-glasmore"); purpura = atlas.getDrawable("omaloon-purpura"); diff --git a/src/omaloon/content/OlItems.java b/src/omaloon/content/OlItems.java index d053593c..395b6839 100644 --- a/src/omaloon/content/OlItems.java +++ b/src/omaloon/content/OlItems.java @@ -5,9 +5,9 @@ import mindustry.content.*; import mindustry.type.*; -public class OlItems { +public class OlItems{ public static Item - cobalt, carborundum, + cobalt, carborundum, end; @@ -24,7 +24,7 @@ public static void load(){ }}; glasmoreItems.addAll( - cobalt, carborundum, Items.beryllium, Items.coal, Items.graphite + cobalt, carborundum, Items.beryllium, Items.coal, Items.graphite ); } } diff --git a/src/omaloon/content/OlLiquids.java b/src/omaloon/content/OlLiquids.java index b53fe848..a5770a19 100644 --- a/src/omaloon/content/OlLiquids.java +++ b/src/omaloon/content/OlLiquids.java @@ -10,11 +10,11 @@ import omaloon.type.liquid.*; import omaloon.world.meta.*; -import static arc.graphics.Color.*; +import static arc.graphics.Color.valueOf; -public class OlLiquids { +public class OlLiquids{ public static Liquid - glacium, tiredGlacium, + glacium, tiredGlacium, end; @@ -46,43 +46,43 @@ public static void load(){ }}; addDensity(Liquids.water, 1000); - addViscosity(Liquids.water, 10); - addDensity(Liquids.slag, 1600); - addViscosity(Liquids.slag, 250); - addDensity(Liquids.oil, 700); - addViscosity(Liquids.oil, 50); - addDensity(Liquids.cryofluid, 200); - addViscosity(Liquids.cryofluid, 1.2f); - addDensity(glacium, 1300); - addViscosity(glacium, 13); - addDensity(tiredGlacium, 1300); - addViscosity(tiredGlacium, 13); - - if (Core.settings.getBool("omaloon-display-liquid-stats", true)) Events.on(EventType.ContentInitEvent.class, e -> { - densities.each(map -> { - map.key.stats.add(OlStats.density, map.value, OlStats.densityUnit); - }); - viscosities.each(map -> { - map.key.checkStats(); - map.key.stats.remove(Stat.viscosity); - map.key.stats.add(Stat.viscosity, Core.bundle.get("stat.omaloon-viscosity"), map.key.viscosity * 100f ,Strings.autoFixed(map.value/60f, 2) + " " + OlStats.viscosityUnit.localized()); - }); - }); + addViscosity(Liquids.water, 10); + addDensity(Liquids.slag, 1600); + addViscosity(Liquids.slag, 250); + addDensity(Liquids.oil, 700); + addViscosity(Liquids.oil, 50); + addDensity(Liquids.cryofluid, 200); + addViscosity(Liquids.cryofluid, 1.2f); + addDensity(glacium, 1300); + addViscosity(glacium, 13); + addDensity(tiredGlacium, 1300); + addViscosity(tiredGlacium, 13); + + if(Core.settings.getBool("omaloon-display-liquid-stats", true)) Events.on(EventType.ContentInitEvent.class, e -> { + densities.each(map -> { + map.key.stats.add(OlStats.density, map.value, OlStats.densityUnit); + }); + viscosities.each(map -> { + map.key.checkStats(); + map.key.stats.remove(Stat.viscosity); + map.key.stats.add(Stat.viscosity, Core.bundle.get("stat.omaloon-viscosity"), map.key.viscosity * 100f, Strings.autoFixed(map.value / 60f, 2) + " " + OlStats.viscosityUnit.localized()); + }); + }); } - public static void addDensity(Liquid liquid, float density) { - densities.put(liquid, density); - } + public static void addDensity(Liquid liquid, float density){ + densities.put(liquid, density); + } - public static void addViscosity(Liquid liquid, float viscosity) { - viscosities.put(liquid, viscosity); - } + public static void addViscosity(Liquid liquid, float viscosity){ + viscosities.put(liquid, viscosity); + } - public static float getDensity(@Nullable Liquid liquid) { - return densities.get(liquid, 8f); - } + public static float getDensity(@Nullable Liquid liquid){ + return densities.get(liquid, 8f); + } - public static float getViscosity(@Nullable Liquid liquid) { - return viscosities.get(liquid, 1f); - } + public static float getViscosity(@Nullable Liquid liquid){ + return viscosities.get(liquid, 1f); + } } diff --git a/src/omaloon/content/OlMusics.java b/src/omaloon/content/OlMusics.java index 728bc781..1f4c450d 100644 --- a/src/omaloon/content/OlMusics.java +++ b/src/omaloon/content/OlMusics.java @@ -7,158 +7,158 @@ import mindustry.*; import mindustry.content.*; import mindustry.game.*; -import mindustry.gen.*; import mindustry.game.EventType.*; +import mindustry.gen.*; import omaloon.content.blocks.*; /** * Manages music, including vanilla and custom tracks. * @author stabu_ */ -public class OlMusics { - private static final ObjectMap> musicSets = new ObjectMap<>(); - - public static Music - // Vanilla - launch, land, - // Omaloon launch - orbital, - // Glasmore music - glLand, - // Ambient - chained, darkPurity, wisdom, space, sundown, - // Dark - fragile, solidFire, soredLuna, - // Boss - buryAlive, chaoticFlames, liquefy, piercingLine; - - public static void load() { - initializeMusics(); - initializeMusicSets(); - setupEventHandlers(); - } - - /** Initializes individual music tracks. */ - private static void initializeMusics() { - // Vanilla - launch = Musics.launch; - land = Musics.land; - - // Omaloon - orbital = loadMusic("orbital"); - - // Glasmore - glLand = loadMusic("landings/glasmore-land"); - - // Load Glasmore musics - String[] ambientTracks = {"chained", "darkPurity", "wisdom", "space", "sundown"}; - String[] darkTracks = {"fragile", "solidFire", "soredLuna"}; - String[] bossTracks = {"buryAlive", "chaoticFlames", "liquefy", "piercingLine"}; - - loadMusicSet("glasmore/ambient/", ambientTracks); - loadMusicSet("glasmore/dark/", darkTracks); - loadMusicSet("glasmore/boss/", bossTracks); - } - - /** - * Loads a set of music tracks from a specified base path. - * @param basePath Base path for the music files. - * @param trackNames Array of track names to load. - */ - private static void loadMusicSet(String basePath, String[] trackNames) { - for (String track : trackNames) { - try { - Music music = loadMusic(basePath + track); - OlMusics.class.getField(track).set(null, music); - } catch (Exception e) { - Log.err("Failed to load music: " + track, e); - } - } - } - - /** Initializes music sets for different game scenarios. */ - private static void initializeMusicSets() { - musicSets.put("vanillaAmbient", new Seq<>(Vars.control.sound.ambientMusic)); - musicSets.put("vanillaDark", new Seq<>(Vars.control.sound.darkMusic)); - musicSets.put("vanillaBoss", new Seq<>(Vars.control.sound.bossMusic)); - - musicSets.put("glasmoreAmbient", Seq.with(chained, darkPurity, wisdom, space, sundown)); - musicSets.put("glasmoreDark", Seq.with(fragile, solidFire, soredLuna)); - musicSets.put("glasmoreBoss", Seq.with(buryAlive, chaoticFlames, liquefy, piercingLine)); - } - - /** Sets up event handlers for updating music based on game events. */ - private static void setupEventHandlers() { - Events.run(EventType.Trigger.update, OlMusics::updateLaunchMusic); - Events.on(WorldLoadEvent.class, e -> { - updateLandMusic(); - updatePlanetMusic(); - }); - } - - /** Updates launch music based on current planet. */ - private static void updateLaunchMusic() { - Musics.launch = (Vars.ui.planet.state.planet == OlPlanets.omaloon || Vars.ui.planet.state.planet == OlPlanets.glasmore) - ? orbital - : launch; - } - - /** Updates landing music based on core block type. */ - private static void updateLandMusic() { - Vars.state.rules.defaultTeam.cores().each(core -> - Musics.land = (core.block == OlStorageBlocks.landingCapsule || core.block == OlStorageBlocks.coreFloe) - ? glLand - : land); - } - - /** Updates planet music sets based on a current planet. */ - private static void updatePlanetMusic() { - if (Vars.state.rules.planet != Planets.sun) { - String prefix = Vars.state.rules.planet == OlPlanets.glasmore ? "glasmore" : "vanilla"; - setMusicSet(prefix + "Ambient", Vars.control.sound.ambientMusic); - setMusicSet(prefix + "Dark", Vars.control.sound.darkMusic); - setMusicSet(prefix + "Boss", Vars.control.sound.bossMusic); - } else { - // For 'any' environment (Planets.sun), mix mod and vanilla music - mixMusic(); - } - } - - /** Mixes vanilla and mod music sets. */ - private static void mixMusic() { - mixMusicSets("vanillaAmbient", "glasmoreAmbient", Vars.control.sound.ambientMusic); - mixMusicSets("vanillaDark", "glasmoreDark", Vars.control.sound.darkMusic); - mixMusicSets("vanillaBoss", "glasmoreBoss", Vars.control.sound.bossMusic); - } - - /** - * Mixes two music sets and assigns the result to a target set. - * @param target Target sequence to store the mixed music. - */ - private static void mixMusicSets(String vanillaSetName, String modSetName, Seq target) { - Seq vanillaSet = musicSets.get(vanillaSetName); - Seq modSet = musicSets.get(modSetName); - if (vanillaSet != null && modSet != null) { - target.clear(); - target.addAll(vanillaSet); - target.addAll(modSet); - } - } - - /** - * Sets a music set to a target sequence. - * @param setName Name of the music set to use. - * @param target Target sequence to update. - */ - private static void setMusicSet(String setName, Seq target) { - Seq set = musicSets.get(setName); - if (set != null) { - target.set(set); - } - } - - /** Loads a music file from the game's asset tree. */ - private static Music loadMusic(String name) { - return Vars.tree.loadMusic(name); - } +public class OlMusics{ + private static final ObjectMap> musicSets = new ObjectMap<>(); + + public static Music + // Vanilla + launch, land, + // Omaloon launch + orbital, + // Glasmore music + glLand, + // Ambient + chained, darkPurity, wisdom, space, sundown, + // Dark + fragile, solidFire, soredLuna, + // Boss + buryAlive, chaoticFlames, liquefy, piercingLine; + + public static void load(){ + initializeMusics(); + initializeMusicSets(); + setupEventHandlers(); + } + + /** Initializes individual music tracks. */ + private static void initializeMusics(){ + // Vanilla + launch = Musics.launch; + land = Musics.land; + + // Omaloon + orbital = loadMusic("orbital"); + + // Glasmore + glLand = loadMusic("landings/glasmore-land"); + + // Load Glasmore musics + String[] ambientTracks = {"chained", "darkPurity", "wisdom", "space", "sundown"}; + String[] darkTracks = {"fragile", "solidFire", "soredLuna"}; + String[] bossTracks = {"buryAlive", "chaoticFlames", "liquefy", "piercingLine"}; + + loadMusicSet("glasmore/ambient/", ambientTracks); + loadMusicSet("glasmore/dark/", darkTracks); + loadMusicSet("glasmore/boss/", bossTracks); + } + + /** + * Loads a set of music tracks from a specified base path. + * @param basePath Base path for the music files. + * @param trackNames Array of track names to load. + */ + private static void loadMusicSet(String basePath, String[] trackNames){ + for(String track : trackNames){ + try{ + Music music = loadMusic(basePath + track); + OlMusics.class.getField(track).set(null, music); + }catch(Exception e){ + Log.err("Failed to load music: " + track, e); + } + } + } + + /** Initializes music sets for different game scenarios. */ + private static void initializeMusicSets(){ + musicSets.put("vanillaAmbient", new Seq<>(Vars.control.sound.ambientMusic)); + musicSets.put("vanillaDark", new Seq<>(Vars.control.sound.darkMusic)); + musicSets.put("vanillaBoss", new Seq<>(Vars.control.sound.bossMusic)); + + musicSets.put("glasmoreAmbient", Seq.with(chained, darkPurity, wisdom, space, sundown)); + musicSets.put("glasmoreDark", Seq.with(fragile, solidFire, soredLuna)); + musicSets.put("glasmoreBoss", Seq.with(buryAlive, chaoticFlames, liquefy, piercingLine)); + } + + /** Sets up event handlers for updating music based on game events. */ + private static void setupEventHandlers(){ + Events.run(EventType.Trigger.update, OlMusics::updateLaunchMusic); + Events.on(WorldLoadEvent.class, e -> { + updateLandMusic(); + updatePlanetMusic(); + }); + } + + /** Updates launch music based on current planet. */ + private static void updateLaunchMusic(){ + Musics.launch = (Vars.ui.planet.state.planet == OlPlanets.omaloon || Vars.ui.planet.state.planet == OlPlanets.glasmore) + ? orbital + : launch; + } + + /** Updates landing music based on core block type. */ + private static void updateLandMusic(){ + Vars.state.rules.defaultTeam.cores().each(core -> + Musics.land = (core.block == OlStorageBlocks.landingCapsule || core.block == OlStorageBlocks.coreFloe) + ? glLand + : land); + } + + /** Updates planet music sets based on a current planet. */ + private static void updatePlanetMusic(){ + if(Vars.state.rules.planet != Planets.sun){ + String prefix = Vars.state.rules.planet == OlPlanets.glasmore ? "glasmore" : "vanilla"; + setMusicSet(prefix + "Ambient", Vars.control.sound.ambientMusic); + setMusicSet(prefix + "Dark", Vars.control.sound.darkMusic); + setMusicSet(prefix + "Boss", Vars.control.sound.bossMusic); + }else{ + // For 'any' environment (Planets.sun), mix mod and vanilla music + mixMusic(); + } + } + + /** Mixes vanilla and mod music sets. */ + private static void mixMusic(){ + mixMusicSets("vanillaAmbient", "glasmoreAmbient", Vars.control.sound.ambientMusic); + mixMusicSets("vanillaDark", "glasmoreDark", Vars.control.sound.darkMusic); + mixMusicSets("vanillaBoss", "glasmoreBoss", Vars.control.sound.bossMusic); + } + + /** + * Mixes two music sets and assigns the result to a target set. + * @param target Target sequence to store the mixed music. + */ + private static void mixMusicSets(String vanillaSetName, String modSetName, Seq target){ + Seq vanillaSet = musicSets.get(vanillaSetName); + Seq modSet = musicSets.get(modSetName); + if(vanillaSet != null && modSet != null){ + target.clear(); + target.addAll(vanillaSet); + target.addAll(modSet); + } + } + + /** + * Sets a music set to a target sequence. + * @param setName Name of the music set to use. + * @param target Target sequence to update. + */ + private static void setMusicSet(String setName, Seq target){ + Seq set = musicSets.get(setName); + if(set != null){ + target.set(set); + } + } + + /** Loads a music file from the game's asset tree. */ + private static Music loadMusic(String name){ + return Vars.tree.loadMusic(name); + } } \ No newline at end of file diff --git a/src/omaloon/content/OlPlanets.java b/src/omaloon/content/OlPlanets.java index 2b479727..b2a553c8 100644 --- a/src/omaloon/content/OlPlanets.java +++ b/src/omaloon/content/OlPlanets.java @@ -20,328 +20,328 @@ import omaloon.maps.planets.*; import omaloon.type.*; -import static arc.Core.*; -import static arc.graphics.Color.*; - -public class OlPlanets { - public static Planet omaloon, glasmore, purpura, tupi, salv, lyssa; - - public static void load() { - omaloon = new Planet("omaloon", null, 4f, 0) {{ - bloom = true; - accessible = false; - hasAtmosphere = true; - solarSystem = this; - - meshLoader = () -> new SunMesh( - this, 4, 5, 0.3f, 1.0f, 1.2f, 1, 1.3f, - - valueOf("#8B4513"), - valueOf("#A0522D"), - valueOf("c2311e"), - valueOf("ff6730"), - valueOf("bf342f"), - valueOf("8e261d") - ); - }}; - - glasmore = new BetterPlanet("glasmore", omaloon, 1f, 4){{ - icon = "glasmore"; - solarSystem = omaloon; - startSector = 492; - alwaysUnlocked = allowLaunchLoadout = allowLaunchSchematics = clearSectorOnLose = true; - allowLaunchToNumbered = false; - orbitRadius = 40f; - rotateTime = 23f * 60f; - atmosphereRadIn = 0f; - atmosphereRadOut = 0.3f; - atmosphereColor = OlEnvironmentBlocks.glacium.mapColor; - - itemWhitelist.add(OlItems.glasmoreItems); - unlockedOnLand.add(OlItems.cobalt); - - ruleSetter = r -> { - r.blockWhitelist = true; - r.hideBannedBlocks = true; - r.bannedBlocks.clear(); - r.bannedBlocks.addAll(Vars.content.blocks().select(block -> { - boolean omaloonOnly = block.minfo.mod != null && block.minfo.mod.name.equals("omaloon"); - boolean sandboxOnly = block.buildVisibility == BuildVisibility.sandboxOnly; - - return omaloonOnly || sandboxOnly; - })); - }; - - Vec3 ringPos = new Vec3(0,1,0).rotate(Vec3.X, 25); - - generator = new GlasmorePlanetGenerator() {{ - defaultLoadout = Schematics.readBase64("bXNjaAF4nGNgZmBmZmDJS8xNZeB0zi9KVXDLyU9l4E5JLU4uyiwoyczPY2BgYMtJTErNKWZgio5lZBDMz03Myc/P000GKtdNAylnYGAEISABADBoE3w="); - - baseHeight = 0; - baseColor = OlEnvironmentBlocks.albaster.mapColor; - - heights.add(new HeightPass.NoiseHeight() {{ - offset.set(1000, 0, 0); - octaves = 7; - persistence = 0.5; - magnitude = 1; - heightOffset = -0.5f; - }}); - - Mathf.rand.setSeed(2); - Seq mountains = new Seq<>(); - for (int i = 0; i < 20; i++) { - mountains.add(new HeightPass.DotHeight() {{ - dir.setToRandomDirection().y = Mathf.random(2f, 5f); - min = 0.99f; - magnitude = Math.max(0.7f, dir.nor().y) * 0.3f; - interp = Interp.exp10In; - }}); - } - heights.add(new HeightPass.MultiHeight(mountains, MixType.max, Operation.add)); - - mountains = new Seq<>(); - for (int i = 0; i < 20; i++) { - mountains.add(new HeightPass.DotHeight() {{ - dir.setToRandomDirection().y = Mathf.random(-2f, -5f); - min = 0.99f; - magnitude = Math.max(0.7f, dir.nor().y) * 0.3f; - dir.rotate(Vec3.X, 22f); - interp = Interp.exp10In; - }}); - } - heights.add(new HeightPass.MultiHeight(mountains, MixType.max, Operation.add)); - - Seq craters = new Seq<>(); - Mathf.rand.setSeed(3); - for(int i = 0; i < 5; i++) { - craters.add(new HeightPass.SphereHeight() {{ - pos.set(Vec3.Y).rotate(Vec3.X, 115f).rotate(ringPos, Mathf.random(360f)); - radius = 0.14f + Mathf.random(0.05f); - offset = 0.2f; - set = true; - }}); - } - heights.addAll(new HeightPass.MultiHeight(craters, MixType.max, Operation.set)); - Mathf.rand.setSeed(3); - for(int i = 0; i < 5; i++) { - heights.add(new HeightPass.SphereHeight() {{ - pos.set(Vec3.Y).rotate(Vec3.X, 115f).rotate(ringPos, Mathf.random(360f)); - radius = 0.07f + Mathf.random(0.05f); - set = true; - }}); - } - heights.add(new HeightPass.ClampHeight(0f, 0.8f)); - - colors.addAll( - new NoiseColorPass() {{ - scale = 1.5; - persistence = 0.5; - octaves = 3; - magnitude = 1.2f; - min = 0.3f; - max = 0.6f; - out = OlEnvironmentBlocks.deadGrass.mapColor; - offset.set(1500f, 300f, -500f); - }}, - new NoiseColorPass() {{ - seed = 5; - scale = 1.5; - persistence = 0.5; - octaves = 5; - magnitude = 1.2f; - min = 0.1f; - max = 0.4f; - out = OlEnvironmentBlocks.aghatite.mapColor; - offset.set(1500f, 300f, -500f); - }}, - new NoiseColorPass() {{ - seed = 8; - scale = 1.5; - persistence = 0.5; - octaves = 7; - magnitude = 1.2f; - min = 0.1f; - max = 0.4f; - out = OlEnvironmentBlocks.quartzSand.mapColor; - offset.set(1500f, 300f, -500f); - }} - ); - for(int i = 0; i < 5; i++) { - colors.add(new SphereColorPass(new Vec3().setToRandomDirection(), 0.06f, OlEnvironmentBlocks.grenite.mapColor)); - } - colors.add( - new FlatColorPass() {{ - min = max = 0f; - out = OlEnvironmentBlocks.blueIce.mapColor; - }}, - new FlatColorPass() {{ - min = 0.3f; - max = 0.5f; - out = OlEnvironmentBlocks.deadGrass.mapColor; - }}, - new FlatColorPass() {{ - max = 1f; - min = 0.5f; - out = OlEnvironmentBlocks.blueIce.mapColor; - }} - ); - craters.map(height -> (HeightPass.SphereHeight) height).each(height -> colors.add( - new SphereColorPass(height.pos, height.radius/1.75f, OlEnvironmentBlocks.glacium.mapColor) - )); - }}; - - meshLoader = () -> new MultiMesh( - new AtmosphereHexMesh(7), - new HexMesh(this, 7), - - new CircleMesh(atlas.find("omaloon-ring4"), this, 80, 2.55f, 2.6f, ringPos), - new CircleMesh(atlas.find("omaloon-ring3"), this,80, 2.2f, 2.5f, ringPos), - new CircleMesh(atlas.find("omaloon-ring2"), this,80, 1.9f, 2.1f, ringPos), - new CircleMesh(atlas.find("omaloon-ring1"), this,80, 1.8f, 1.85f, ringPos) - ); - - cloudMeshLoader = () -> new MultiMesh( - new HexSkyMesh(this, 6, -0.5f, 0.14f, 6, OlEnvironmentBlocks.blueIce.mapColor.cpy().a(0.2f), 2, 0.42f, 1f, 0.6f), - new HexSkyMesh(this, 1, 0.6f, 0.15f, 6, OlEnvironmentBlocks.blueIce.mapColor.cpy().a(0.2f), 2, 0.42f, 1.2f, 0.5f) - ); - }}; - - purpura = new BetterPlanet("purpura", omaloon, 1f) {{ - icon = "purpura"; - accessible = false; - - atmosphereColor = Color.valueOf("4F424D"); - atmosphereRadIn = 0; - atmosphereRadOut = 0.05f; - orbitRadius = 20f; - generator = new PurpuraPlanetGenerator(); - - meshLoader = () -> new MultiMesh( - new AtmosphereHexMesh(7), - new HexMesh(this, 7) - ); - cloudMeshLoader = () -> new MultiMesh( - new HexSkyMesh(this, 1, 1f, 0.05f, 6, Color.valueOf("242424").a(0.6f), 2, 0.8f, 1f, 0.f), - new HexSkyMesh(this, 2, -1.3f, 0.06f, 6, Color.valueOf("413B42").a(0.6f), 2, 0.8f, 1f, 0.5f), - new HexSkyMesh(this, 3, 1.3f, 0.07f, 6, Color.valueOf("7F777E").a(0.6f), 2, 0.8f, 1.2f, 0.5f), - new HexSkyMesh(this, 4, -1.6f, 0.08f, 6, Color.valueOf("B2B2B2").a(0.6f), 2, 0.8f, 1.2f, 0.5f) - ); - }}; - - tupi = new Planet("tupi", omaloon, 0.12f){{ - Block base = OlEnvironmentBlocks.albaster, tint = OlEnvironmentBlocks.blueIce; - hasAtmosphere = false; - updateLighting = false; - sectors.add(new Sector(this, PlanetGrid.Ptile.empty)); - camRadius = 0.68f * 2f; - minZoom = 0.6f; - orbitRadius = 30f; - drawOrbit = false; - accessible = false; - clipRadius = 2f; - defaultEnv = Env.space; - icon = "commandRally"; - generator = new AsteroidGenerator(); - - meshLoader = () -> { - iconColor = tint.mapColor; - Color tinted = tint.mapColor.cpy().a(1f - tint.mapColor.a); - Seq meshes = new Seq<>(); - Color color = base.mapColor; - Rand rand = new Rand(id + 2); - - meshes.add(new NoiseMesh( - this, 0, 2, radius, 2, 0.55f, 0.45f, 14f, - color, tinted, 3, 0.6f, 0.38f, 0.5f - )); - - for(int j = 0; j < 8; j++){ - meshes.add(new MatMesh( - new NoiseMesh(this, j + 1, 1, 0.022f + rand.random(0.039f) * 2f, 2, 0.6f, 0.38f, 20f, - color, tinted, 3, 0.6f, 0.38f, 0.5f), - new Mat3D().setToTranslation(Tmp.v31.setToRandomDirection(rand).setLength(rand.random(0.44f, 1.4f) * 2f))) - ); - } - - return new MultiMesh(meshes.toArray(GenericMesh.class)); - }; - }}; - salv = new Planet("salv", omaloon, 0.12f){{ - Block base = OlEnvironmentBlocks.aghatite, tint = OlEnvironmentBlocks.weatheredAghanite; - hasAtmosphere = false; - updateLighting = false; - orbitRadius = 10f; - sectors.add(new Sector(this, PlanetGrid.Ptile.empty)); - camRadius = 0.68f * 2f; - minZoom = 0.6f; - drawOrbit = false; - accessible = false; - clipRadius = 2f; - defaultEnv = Env.space; - icon = "commandRally"; - generator = new AsteroidGenerator(); - - meshLoader = () -> { - iconColor = tint.mapColor; - Color tinted = tint.mapColor.cpy().a(1f - tint.mapColor.a); - Seq meshes = new Seq<>(); - Color color = base.mapColor; - Rand rand = new Rand(id + 2); - - meshes.add(new NoiseMesh( - this, 0, 2, radius, 2, 0.55f, 0.45f, 14f, - color, tinted, 3, 0.6f, 0.38f, 0.5f - )); - - for(int j = 0; j < 8; j++){ - meshes.add(new MatMesh( - new NoiseMesh(this, j + 1, 1, 0.022f + rand.random(0.039f) * 2f, 2, 0.6f, 0.38f, 20f, - color, tinted, 3, 0.6f, 0.38f, 0.5f), - new Mat3D().setToTranslation(Tmp.v31.setToRandomDirection(rand).setLength(rand.random(0.44f, 1.4f) * 2f))) - ); - } - - return new MultiMesh(meshes.toArray(GenericMesh.class)); - }; - }}; - lyssa = new Planet("lyssa", omaloon, 0.12f){{ - Block base = OlEnvironmentBlocks.blueIce, tint = OlEnvironmentBlocks.berylledAghanite; - hasAtmosphere = false; - updateLighting = false; - orbitRadius = 50f; - sectors.add(new Sector(this, PlanetGrid.Ptile.empty)); - camRadius = 0.68f * 2f; - minZoom = 0.6f; - drawOrbit = false; - accessible = false; - clipRadius = 2f; - defaultEnv = Env.space; - icon = "commandRally"; - generator = new AsteroidGenerator(); - - meshLoader = () -> { - iconColor = tint.mapColor; - Color tinted = tint.mapColor.cpy().a(1f - tint.mapColor.a); - Seq meshes = new Seq<>(); - Color color = base.mapColor; - Rand rand = new Rand(id + 2); - - meshes.add(new NoiseMesh( - this, 0, 2, radius, 2, 0.55f, 0.45f, 14f, - color, tinted, 3, 0.6f, 0.38f, 0.5f - )); - - for(int j = 0; j < 8; j++){ - meshes.add(new MatMesh( - new NoiseMesh(this, j + 1, 1, 0.022f + rand.random(0.039f) * 2f, 2, 0.6f, 0.38f, 20f, - color, tinted, 3, 0.6f, 0.38f, 0.5f), - new Mat3D().setToTranslation(Tmp.v31.setToRandomDirection(rand).setLength(rand.random(0.44f, 1.4f) * 2f))) - ); - } - - return new MultiMesh(meshes.toArray(GenericMesh.class)); - }; - }}; - } +import static arc.Core.atlas; +import static arc.graphics.Color.valueOf; + +public class OlPlanets{ + public static Planet omaloon, glasmore, purpura, tupi, salv, lyssa; + + public static void load(){ + omaloon = new Planet("omaloon", null, 4f, 0){{ + bloom = true; + accessible = false; + hasAtmosphere = true; + solarSystem = this; + + meshLoader = () -> new SunMesh( + this, 4, 5, 0.3f, 1.0f, 1.2f, 1, 1.3f, + + valueOf("#8B4513"), + valueOf("#A0522D"), + valueOf("c2311e"), + valueOf("ff6730"), + valueOf("bf342f"), + valueOf("8e261d") + ); + }}; + + glasmore = new BetterPlanet("glasmore", omaloon, 1f, 4){{ + icon = "glasmore"; + solarSystem = omaloon; + startSector = 492; + alwaysUnlocked = allowLaunchLoadout = allowLaunchSchematics = clearSectorOnLose = true; + allowLaunchToNumbered = false; + orbitRadius = 40f; + rotateTime = 23f * 60f; + atmosphereRadIn = 0f; + atmosphereRadOut = 0.3f; + atmosphereColor = OlEnvironmentBlocks.glacium.mapColor; + + itemWhitelist.add(OlItems.glasmoreItems); + unlockedOnLand.add(OlItems.cobalt); + + ruleSetter = r -> { + r.blockWhitelist = true; + r.hideBannedBlocks = true; + r.bannedBlocks.clear(); + r.bannedBlocks.addAll(Vars.content.blocks().select(block -> { + boolean omaloonOnly = block.minfo.mod != null && block.minfo.mod.name.equals("omaloon"); + boolean sandboxOnly = block.buildVisibility == BuildVisibility.sandboxOnly; + + return omaloonOnly || sandboxOnly; + })); + }; + + Vec3 ringPos = new Vec3(0, 1, 0).rotate(Vec3.X, 25); + + generator = new GlasmorePlanetGenerator(){{ + defaultLoadout = Schematics.readBase64("bXNjaAF4nGNgZmBmZmDJS8xNZeB0zi9KVXDLyU9l4E5JLU4uyiwoyczPY2BgYMtJTErNKWZgio5lZBDMz03Myc/P000GKtdNAylnYGAEISABADBoE3w="); + + baseHeight = 0; + baseColor = OlEnvironmentBlocks.albaster.mapColor; + + heights.add(new HeightPass.NoiseHeight(){{ + offset.set(1000, 0, 0); + octaves = 7; + persistence = 0.5; + magnitude = 1; + heightOffset = -0.5f; + }}); + + Mathf.rand.setSeed(2); + Seq mountains = new Seq<>(); + for(int i = 0; i < 20; i++){ + mountains.add(new HeightPass.DotHeight(){{ + dir.setToRandomDirection().y = Mathf.random(2f, 5f); + min = 0.99f; + magnitude = Math.max(0.7f, dir.nor().y) * 0.3f; + interp = Interp.exp10In; + }}); + } + heights.add(new HeightPass.MultiHeight(mountains, MixType.max, Operation.add)); + + mountains = new Seq<>(); + for(int i = 0; i < 20; i++){ + mountains.add(new HeightPass.DotHeight(){{ + dir.setToRandomDirection().y = Mathf.random(-2f, -5f); + min = 0.99f; + magnitude = Math.max(0.7f, dir.nor().y) * 0.3f; + dir.rotate(Vec3.X, 22f); + interp = Interp.exp10In; + }}); + } + heights.add(new HeightPass.MultiHeight(mountains, MixType.max, Operation.add)); + + Seq craters = new Seq<>(); + Mathf.rand.setSeed(3); + for(int i = 0; i < 5; i++){ + craters.add(new HeightPass.SphereHeight(){{ + pos.set(Vec3.Y).rotate(Vec3.X, 115f).rotate(ringPos, Mathf.random(360f)); + radius = 0.14f + Mathf.random(0.05f); + offset = 0.2f; + set = true; + }}); + } + heights.addAll(new HeightPass.MultiHeight(craters, MixType.max, Operation.set)); + Mathf.rand.setSeed(3); + for(int i = 0; i < 5; i++){ + heights.add(new HeightPass.SphereHeight(){{ + pos.set(Vec3.Y).rotate(Vec3.X, 115f).rotate(ringPos, Mathf.random(360f)); + radius = 0.07f + Mathf.random(0.05f); + set = true; + }}); + } + heights.add(new HeightPass.ClampHeight(0f, 0.8f)); + + colors.addAll( + new NoiseColorPass(){{ + scale = 1.5; + persistence = 0.5; + octaves = 3; + magnitude = 1.2f; + min = 0.3f; + max = 0.6f; + out = OlEnvironmentBlocks.deadGrass.mapColor; + offset.set(1500f, 300f, -500f); + }}, + new NoiseColorPass(){{ + seed = 5; + scale = 1.5; + persistence = 0.5; + octaves = 5; + magnitude = 1.2f; + min = 0.1f; + max = 0.4f; + out = OlEnvironmentBlocks.aghatite.mapColor; + offset.set(1500f, 300f, -500f); + }}, + new NoiseColorPass(){{ + seed = 8; + scale = 1.5; + persistence = 0.5; + octaves = 7; + magnitude = 1.2f; + min = 0.1f; + max = 0.4f; + out = OlEnvironmentBlocks.quartzSand.mapColor; + offset.set(1500f, 300f, -500f); + }} + ); + for(int i = 0; i < 5; i++){ + colors.add(new SphereColorPass(new Vec3().setToRandomDirection(), 0.06f, OlEnvironmentBlocks.grenite.mapColor)); + } + colors.add( + new FlatColorPass(){{ + min = max = 0f; + out = OlEnvironmentBlocks.blueIce.mapColor; + }}, + new FlatColorPass(){{ + min = 0.3f; + max = 0.5f; + out = OlEnvironmentBlocks.deadGrass.mapColor; + }}, + new FlatColorPass(){{ + max = 1f; + min = 0.5f; + out = OlEnvironmentBlocks.blueIce.mapColor; + }} + ); + craters.map(height -> (HeightPass.SphereHeight)height).each(height -> colors.add( + new SphereColorPass(height.pos, height.radius / 1.75f, OlEnvironmentBlocks.glacium.mapColor) + )); + }}; + + meshLoader = () -> new MultiMesh( + new AtmosphereHexMesh(7), + new HexMesh(this, 7), + + new CircleMesh(atlas.find("omaloon-ring4"), this, 80, 2.55f, 2.6f, ringPos), + new CircleMesh(atlas.find("omaloon-ring3"), this, 80, 2.2f, 2.5f, ringPos), + new CircleMesh(atlas.find("omaloon-ring2"), this, 80, 1.9f, 2.1f, ringPos), + new CircleMesh(atlas.find("omaloon-ring1"), this, 80, 1.8f, 1.85f, ringPos) + ); + + cloudMeshLoader = () -> new MultiMesh( + new HexSkyMesh(this, 6, -0.5f, 0.14f, 6, OlEnvironmentBlocks.blueIce.mapColor.cpy().a(0.2f), 2, 0.42f, 1f, 0.6f), + new HexSkyMesh(this, 1, 0.6f, 0.15f, 6, OlEnvironmentBlocks.blueIce.mapColor.cpy().a(0.2f), 2, 0.42f, 1.2f, 0.5f) + ); + }}; + + purpura = new BetterPlanet("purpura", omaloon, 1f){{ + icon = "purpura"; + accessible = false; + + atmosphereColor = Color.valueOf("4F424D"); + atmosphereRadIn = 0; + atmosphereRadOut = 0.05f; + orbitRadius = 20f; + generator = new PurpuraPlanetGenerator(); + + meshLoader = () -> new MultiMesh( + new AtmosphereHexMesh(7), + new HexMesh(this, 7) + ); + cloudMeshLoader = () -> new MultiMesh( + new HexSkyMesh(this, 1, 1f, 0.05f, 6, Color.valueOf("242424").a(0.6f), 2, 0.8f, 1f, 0.f), + new HexSkyMesh(this, 2, -1.3f, 0.06f, 6, Color.valueOf("413B42").a(0.6f), 2, 0.8f, 1f, 0.5f), + new HexSkyMesh(this, 3, 1.3f, 0.07f, 6, Color.valueOf("7F777E").a(0.6f), 2, 0.8f, 1.2f, 0.5f), + new HexSkyMesh(this, 4, -1.6f, 0.08f, 6, Color.valueOf("B2B2B2").a(0.6f), 2, 0.8f, 1.2f, 0.5f) + ); + }}; + + tupi = new Planet("tupi", omaloon, 0.12f){{ + Block base = OlEnvironmentBlocks.albaster, tint = OlEnvironmentBlocks.blueIce; + hasAtmosphere = false; + updateLighting = false; + sectors.add(new Sector(this, PlanetGrid.Ptile.empty)); + camRadius = 0.68f * 2f; + minZoom = 0.6f; + orbitRadius = 30f; + drawOrbit = false; + accessible = false; + clipRadius = 2f; + defaultEnv = Env.space; + icon = "commandRally"; + generator = new AsteroidGenerator(); + + meshLoader = () -> { + iconColor = tint.mapColor; + Color tinted = tint.mapColor.cpy().a(1f - tint.mapColor.a); + Seq meshes = new Seq<>(); + Color color = base.mapColor; + Rand rand = new Rand(id + 2); + + meshes.add(new NoiseMesh( + this, 0, 2, radius, 2, 0.55f, 0.45f, 14f, + color, tinted, 3, 0.6f, 0.38f, 0.5f + )); + + for(int j = 0; j < 8; j++){ + meshes.add(new MatMesh( + new NoiseMesh(this, j + 1, 1, 0.022f + rand.random(0.039f) * 2f, 2, 0.6f, 0.38f, 20f, + color, tinted, 3, 0.6f, 0.38f, 0.5f), + new Mat3D().setToTranslation(Tmp.v31.setToRandomDirection(rand).setLength(rand.random(0.44f, 1.4f) * 2f))) + ); + } + + return new MultiMesh(meshes.toArray(GenericMesh.class)); + }; + }}; + salv = new Planet("salv", omaloon, 0.12f){{ + Block base = OlEnvironmentBlocks.aghatite, tint = OlEnvironmentBlocks.weatheredAghanite; + hasAtmosphere = false; + updateLighting = false; + orbitRadius = 10f; + sectors.add(new Sector(this, PlanetGrid.Ptile.empty)); + camRadius = 0.68f * 2f; + minZoom = 0.6f; + drawOrbit = false; + accessible = false; + clipRadius = 2f; + defaultEnv = Env.space; + icon = "commandRally"; + generator = new AsteroidGenerator(); + + meshLoader = () -> { + iconColor = tint.mapColor; + Color tinted = tint.mapColor.cpy().a(1f - tint.mapColor.a); + Seq meshes = new Seq<>(); + Color color = base.mapColor; + Rand rand = new Rand(id + 2); + + meshes.add(new NoiseMesh( + this, 0, 2, radius, 2, 0.55f, 0.45f, 14f, + color, tinted, 3, 0.6f, 0.38f, 0.5f + )); + + for(int j = 0; j < 8; j++){ + meshes.add(new MatMesh( + new NoiseMesh(this, j + 1, 1, 0.022f + rand.random(0.039f) * 2f, 2, 0.6f, 0.38f, 20f, + color, tinted, 3, 0.6f, 0.38f, 0.5f), + new Mat3D().setToTranslation(Tmp.v31.setToRandomDirection(rand).setLength(rand.random(0.44f, 1.4f) * 2f))) + ); + } + + return new MultiMesh(meshes.toArray(GenericMesh.class)); + }; + }}; + lyssa = new Planet("lyssa", omaloon, 0.12f){{ + Block base = OlEnvironmentBlocks.blueIce, tint = OlEnvironmentBlocks.berylledAghanite; + hasAtmosphere = false; + updateLighting = false; + orbitRadius = 50f; + sectors.add(new Sector(this, PlanetGrid.Ptile.empty)); + camRadius = 0.68f * 2f; + minZoom = 0.6f; + drawOrbit = false; + accessible = false; + clipRadius = 2f; + defaultEnv = Env.space; + icon = "commandRally"; + generator = new AsteroidGenerator(); + + meshLoader = () -> { + iconColor = tint.mapColor; + Color tinted = tint.mapColor.cpy().a(1f - tint.mapColor.a); + Seq meshes = new Seq<>(); + Color color = base.mapColor; + Rand rand = new Rand(id + 2); + + meshes.add(new NoiseMesh( + this, 0, 2, radius, 2, 0.55f, 0.45f, 14f, + color, tinted, 3, 0.6f, 0.38f, 0.5f + )); + + for(int j = 0; j < 8; j++){ + meshes.add(new MatMesh( + new NoiseMesh(this, j + 1, 1, 0.022f + rand.random(0.039f) * 2f, 2, 0.6f, 0.38f, 20f, + color, tinted, 3, 0.6f, 0.38f, 0.5f), + new Mat3D().setToTranslation(Tmp.v31.setToRandomDirection(rand).setLength(rand.random(0.44f, 1.4f) * 2f))) + ); + } + + return new MultiMesh(meshes.toArray(GenericMesh.class)); + }; + }}; + } } diff --git a/src/omaloon/content/OlSchematics.java b/src/omaloon/content/OlSchematics.java index 6e31ccc0..a2a77f28 100644 --- a/src/omaloon/content/OlSchematics.java +++ b/src/omaloon/content/OlSchematics.java @@ -6,33 +6,33 @@ import mindustry.world.blocks.storage.*; import omaloon.content.blocks.*; -public class OlSchematics { - public static Schematic +public class OlSchematics{ + public static Schematic - landingCapsule, - coreFloe; + landingCapsule, + coreFloe; - public static void load() { - landingCapsule = Schematics.readBase64("bXNjaAF4nGNgYmBiZmDJS8xNZeD3ScxLycxLV3BOLCguzUll4E5JLU4uyiwoyczPY2BgYMtJTErNKWZgio5lZBDPz03Myc/P082BaNJNhmpiYGBkAANGAJEyGHs="); - coreFloe = Schematics.readBase64("bXNjaAF4nGNgZmBmZmDJS8xNZeB0zi9KVXDLyU9l4E5JLU4uyiwoyczPY2BgYMtJTErNKWZgio5lZBDMz03Myc/P000GKtdNAylnYGAEISAEADBpE30="); - Events.run(EventType.Trigger.update, () -> { - if (!Vars.schematics.getLoadouts((CoreBlock) OlStorageBlocks.coreFloe).contains(coreFloe)) { - Vars.schematics.getLoadouts((CoreBlock) OlStorageBlocks.coreFloe).clear(); - Vars.schematics.getLoadouts((CoreBlock) OlStorageBlocks.coreFloe).add(coreFloe); - } - if (!Vars.schematics.getLoadouts((CoreBlock) OlStorageBlocks.landingCapsule).contains(landingCapsule)) { - Vars.schematics.getLoadouts((CoreBlock) OlStorageBlocks.landingCapsule).clear(); - Vars.schematics.getLoadouts((CoreBlock) OlStorageBlocks.landingCapsule).add(landingCapsule); - } - if (Vars.ui.planet.state.planet.solarSystem == OlPlanets.omaloon) { - if (Vars.ui.planet.selected == OlSectorPresets.theCrater.sector) { - OlPlanets.glasmore.defaultCore = OlStorageBlocks.landingCapsule; - OlPlanets.glasmore.generator.defaultLoadout = landingCapsule; - } else { - OlPlanets.glasmore.defaultCore = OlStorageBlocks.coreFloe; - OlPlanets.glasmore.generator.defaultLoadout = coreFloe; - } - } - }); - } + public static void load(){ + landingCapsule = Schematics.readBase64("bXNjaAF4nGNgYmBiZmDJS8xNZeD3ScxLycxLV3BOLCguzUll4E5JLU4uyiwoyczPY2BgYMtJTErNKWZgio5lZBDPz03Myc/P082BaNJNhmpiYGBkAANGAJEyGHs="); + coreFloe = Schematics.readBase64("bXNjaAF4nGNgZmBmZmDJS8xNZeB0zi9KVXDLyU9l4E5JLU4uyiwoyczPY2BgYMtJTErNKWZgio5lZBDMz03Myc/P000GKtdNAylnYGAEISAEADBpE30="); + Events.run(EventType.Trigger.update, () -> { + if(!Vars.schematics.getLoadouts((CoreBlock)OlStorageBlocks.coreFloe).contains(coreFloe)){ + Vars.schematics.getLoadouts((CoreBlock)OlStorageBlocks.coreFloe).clear(); + Vars.schematics.getLoadouts((CoreBlock)OlStorageBlocks.coreFloe).add(coreFloe); + } + if(!Vars.schematics.getLoadouts((CoreBlock)OlStorageBlocks.landingCapsule).contains(landingCapsule)){ + Vars.schematics.getLoadouts((CoreBlock)OlStorageBlocks.landingCapsule).clear(); + Vars.schematics.getLoadouts((CoreBlock)OlStorageBlocks.landingCapsule).add(landingCapsule); + } + if(Vars.ui.planet.state.planet.solarSystem == OlPlanets.omaloon){ + if(Vars.ui.planet.selected == OlSectorPresets.theCrater.sector){ + OlPlanets.glasmore.defaultCore = OlStorageBlocks.landingCapsule; + OlPlanets.glasmore.generator.defaultLoadout = landingCapsule; + }else{ + OlPlanets.glasmore.defaultCore = OlStorageBlocks.coreFloe; + OlPlanets.glasmore.generator.defaultLoadout = coreFloe; + } + } + }); + } } diff --git a/src/omaloon/content/OlSectorPresets.java b/src/omaloon/content/OlSectorPresets.java index ecff1449..dc99fb91 100644 --- a/src/omaloon/content/OlSectorPresets.java +++ b/src/omaloon/content/OlSectorPresets.java @@ -8,50 +8,50 @@ import omaloon.type.*; import static arc.util.Time.*; -import static omaloon.type.ExtraSectorPreset.*; +import static omaloon.type.ExtraSectorPreset.getFlag; -public class OlSectorPresets { - public static SectorPreset theCrater, redeploymentPath, deadValley; +public class OlSectorPresets{ + public static SectorPreset theCrater, redeploymentPath, deadValley; - public static void load() { - theCrater = new ExtraSectorPreset("crater", OlPlanets.glasmore, 492, () -> { - if (getFlag("hail", true)) { - Vars.state.rules.weather.add(new WeatherEntry(OlWeathers.hailStone, - 2.5f * toMinutes, 5f * toMinutes, - 30f * Time.toSeconds, 1.5f * toMinutes - ) {{ - always = true; - }}); - } - if (getFlag("final", true) && !Vars.state.rules.weather.isEmpty()) { - Vars.state.rules.weather.clear(); - Vars.state.rules.weather.add(new WeatherEntry(OlWeathers.hailStone, - 2.5f * toMinutes, 5f * toMinutes, - 30f * toSeconds, 1.5f * toMinutes - )); - Groups.weather.each(weather -> weather.life = 300f); - } - if (getFlag("haildemo", true)) { - Call.createWeather(OlWeathers.hailStone, 0.3f, 8f * 60f, 1f, 1f); - } - }) {{ - alwaysUnlocked = true; - difficulty = 1; - }}; - redeploymentPath = new ExtraSectorPreset("redeployment_path", OlPlanets.glasmore, 607, () -> { - if (getFlag("addweather", true)) { - Vars.state.rules.weather.clear(); - Vars.state.rules.weather.add( - new WeatherEntry(OlWeathers.wind, toMinutes, 12f * toMinutes, 2f * toMinutes, 3f * toMinutes), - new WeatherEntry(OlWeathers.aghaniteStorm, 1.5f * toMinutes, 5f * toMinutes, 5f * toMinutes, 8f * toMinutes) - ); - } - }) {{ - captureWave = 15; - }}; - deadValley = new ExtraSectorPreset("dead_valley", OlPlanets.glasmore, 660) {{ - captureWave = 20; - difficulty = 3; - }}; - } + public static void load(){ + theCrater = new ExtraSectorPreset("crater", OlPlanets.glasmore, 492, () -> { + if(getFlag("hail", true)){ + Vars.state.rules.weather.add(new WeatherEntry(OlWeathers.hailStone, + 2.5f * toMinutes, 5f * toMinutes, + 30f * Time.toSeconds, 1.5f * toMinutes + ){{ + always = true; + }}); + } + if(getFlag("final", true) && !Vars.state.rules.weather.isEmpty()){ + Vars.state.rules.weather.clear(); + Vars.state.rules.weather.add(new WeatherEntry(OlWeathers.hailStone, + 2.5f * toMinutes, 5f * toMinutes, + 30f * toSeconds, 1.5f * toMinutes + )); + Groups.weather.each(weather -> weather.life = 300f); + } + if(getFlag("haildemo", true)){ + Call.createWeather(OlWeathers.hailStone, 0.3f, 8f * 60f, 1f, 1f); + } + }){{ + alwaysUnlocked = true; + difficulty = 1; + }}; + redeploymentPath = new ExtraSectorPreset("redeployment_path", OlPlanets.glasmore, 607, () -> { + if(getFlag("addweather", true)){ + Vars.state.rules.weather.clear(); + Vars.state.rules.weather.add( + new WeatherEntry(OlWeathers.wind, toMinutes, 12f * toMinutes, 2f * toMinutes, 3f * toMinutes), + new WeatherEntry(OlWeathers.aghaniteStorm, 1.5f * toMinutes, 5f * toMinutes, 5f * toMinutes, 8f * toMinutes) + ); + } + }){{ + captureWave = 15; + }}; + deadValley = new ExtraSectorPreset("dead_valley", OlPlanets.glasmore, 660){{ + captureWave = 20; + difficulty = 3; + }}; + } } diff --git a/src/omaloon/content/OlSounds.java b/src/omaloon/content/OlSounds.java index de5ec549..cdfb18d4 100644 --- a/src/omaloon/content/OlSounds.java +++ b/src/omaloon/content/OlSounds.java @@ -6,19 +6,19 @@ import arc.audio.*; import mindustry.*; -public class OlSounds { +public class OlSounds{ public static Sound - debrisBreak = new Sound(), - bigHailstoneHit = new Sound(), - giantHailstoneFall = new Sound(), - giantHailstoneHit = new Sound(), - hailRain = new Sound(), - hammer = new Sound(), - jam = new Sound(), - shelter = new Sound(), - shelterPush = new Sound(), - theShoot = new Sound(), - convergence = new Sound(); + debrisBreak = new Sound(), + bigHailstoneHit = new Sound(), + giantHailstoneFall = new Sound(), + giantHailstoneHit = new Sound(), + hailRain = new Sound(), + hammer = new Sound(), + jam = new Sound(), + shelter = new Sound(), + shelterPush = new Sound(), + theShoot = new Sound(), + convergence = new Sound(); public static void load(){ debrisBreak = loadSound("debris_break"); @@ -35,7 +35,7 @@ public static void load(){ } private static Sound loadSound(String soundName){ - if(!Vars.headless) { + if(!Vars.headless){ String name = "sounds/" + soundName; String path = Vars.tree.get(name + ".ogg").exists() ? name + ".ogg" : name + ".mp3"; @@ -46,7 +46,7 @@ private static Sound loadSound(String soundName){ return sound; - } else { + }else{ return new Sound(); } } diff --git a/src/omaloon/content/OlStatusEffects.java b/src/omaloon/content/OlStatusEffects.java index 48bc6690..8dd13031 100644 --- a/src/omaloon/content/OlStatusEffects.java +++ b/src/omaloon/content/OlStatusEffects.java @@ -14,10 +14,10 @@ import static arc.graphics.g2d.Draw.*; import static mindustry.content.StatusEffects.*; -public class OlStatusEffects { +public class OlStatusEffects{ public static StatusEffect - glacied, breeze, - filledWithWater, filledWithGlacium, filledWithSlag, filledWithOil; + glacied, breeze, + filledWithWater, filledWithGlacium, filledWithSlag, filledWithOil; public static void load(){ glacied = new StatusEffect("glacied"){{ @@ -46,28 +46,44 @@ public static void load(){ opposite(burning, melting); }); }}; - breeze = new StatusEffect("wind-breeze") {{ + breeze = new StatusEffect("wind-breeze"){{ speedMultiplier = 1.2f; }}; - filledWithWater = new StatusEffect("filled-with-water"){{ - } - @Override - public boolean isHidden(){return Vars.state.getState() != GameState.State.menu;} + filledWithWater = new StatusEffect("filled-with-water"){ + { + } + + @Override + public boolean isHidden(){ + return Vars.state.getState() != GameState.State.menu; + } }; - filledWithGlacium = new StatusEffect("filled-with-glacium"){{ - } - @Override - public boolean isHidden(){return Vars.state.getState() != GameState.State.menu;} + filledWithGlacium = new StatusEffect("filled-with-glacium"){ + { + } + + @Override + public boolean isHidden(){ + return Vars.state.getState() != GameState.State.menu; + } }; - filledWithSlag = new StatusEffect("filled-with-slag"){{ - } - @Override - public boolean isHidden(){return Vars.state.getState() != GameState.State.menu;} + filledWithSlag = new StatusEffect("filled-with-slag"){ + { + } + + @Override + public boolean isHidden(){ + return Vars.state.getState() != GameState.State.menu; + } }; - filledWithOil = new StatusEffect("filled-with-oil"){{ - } - @Override - public boolean isHidden(){return Vars.state.getState() != GameState.State.menu;} + filledWithOil = new StatusEffect("filled-with-oil"){ + { + } + + @Override + public boolean isHidden(){ + return Vars.state.getState() != GameState.State.menu; + } }; } } diff --git a/src/omaloon/content/OlTechTree.java b/src/omaloon/content/OlTechTree.java index 5f5ca348..706aede9 100644 --- a/src/omaloon/content/OlTechTree.java +++ b/src/omaloon/content/OlTechTree.java @@ -3,7 +3,7 @@ import mindustry.content.*; import mindustry.game.Objectives.*; -import static arc.struct.Seq.*; +import static arc.struct.Seq.with; import static mindustry.content.TechTree.*; import static omaloon.content.OlItems.*; import static omaloon.content.OlSectorPresets.*; @@ -11,67 +11,67 @@ import static omaloon.content.blocks.OlDefenceBlocks.*; import static omaloon.content.blocks.OlDistributionBlocks.*; import static omaloon.content.blocks.OlPowerBlocks.*; -import static omaloon.content.blocks.OlProductionBlocks.*; +import static omaloon.content.blocks.OlProductionBlocks.hammerDrill; import static omaloon.content.blocks.OlStorageBlocks.*; -public class OlTechTree { - public static void load() { - OlPlanets.glasmore.techTree = nodeRoot("omaloon-glasmore", landingCapsule, () -> { - node(coreFloe); - - node(tubeConveyor, with(new Research(hammerDrill)), () -> { - node(tubeDistributor, with(new Research(hammerDrill)), () -> { - node(tubeJunction, () -> { - node(tubeSorter, with(new Produce(carborundum)), () -> { - node(tubeGate, with(new Produce(carborundum)), () -> { - - }); - }); - node(tubeBridge); - }); - }); - }); - - node(hammerDrill, () -> { - node(liquidPump, () -> { - node(liquidTube, () -> { - node(liquidJunction, () -> { - node(liquidBridge); - }); - }); - node(liquidGauge); - }); - - node(carborundumPress, with(new Research(smallShelter)), () -> { - node(graphitePress, () -> { - - }); - }); - - node(windTurbine, () -> { - node(smallShelter, () -> { - node(repairer, with(new Research(coalGenerator)), () -> { - - }); - }); - node(impulseNode, () -> { - node(coalGenerator, with(new Produce(Items.graphite)), () -> { - - }); - }); - }); - }); - - node(apex, with(new OnSector(redeploymentPath)), () -> { - node(carborundumWall, () -> node(carborundumWallLarge)); - node(blast, with(new SectorComplete(redeploymentPath)), () -> { - node(convergence, with(new OnSector(deadValley)), () -> { - - }); - }); - }); - - // TODO change this when an unit factory is added +public class OlTechTree{ + public static void load(){ + OlPlanets.glasmore.techTree = nodeRoot("omaloon-glasmore", landingCapsule, () -> { + node(coreFloe); + + node(tubeConveyor, with(new Research(hammerDrill)), () -> { + node(tubeDistributor, with(new Research(hammerDrill)), () -> { + node(tubeJunction, () -> { + node(tubeSorter, with(new Produce(carborundum)), () -> { + node(tubeGate, with(new Produce(carborundum)), () -> { + + }); + }); + node(tubeBridge); + }); + }); + }); + + node(hammerDrill, () -> { + node(liquidPump, () -> { + node(liquidTube, () -> { + node(liquidJunction, () -> { + node(liquidBridge); + }); + }); + node(liquidGauge); + }); + + node(carborundumPress, with(new Research(smallShelter)), () -> { + node(graphitePress, () -> { + + }); + }); + + node(windTurbine, () -> { + node(smallShelter, () -> { + node(repairer, with(new Research(coalGenerator)), () -> { + + }); + }); + node(impulseNode, () -> { + node(coalGenerator, with(new Produce(Items.graphite)), () -> { + + }); + }); + }); + }); + + node(apex, with(new OnSector(redeploymentPath)), () -> { + node(carborundumWall, () -> node(carborundumWallLarge)); + node(blast, with(new SectorComplete(redeploymentPath)), () -> { + node(convergence, with(new OnSector(deadValley)), () -> { + + }); + }); + }); + + // TODO change this when an unit factory is added // node(legionnaire, () -> { // node(centurion, () -> { // node(praetorian); @@ -87,29 +87,29 @@ public static void load() { // }); // }); - node(theCrater, () -> { - node(redeploymentPath, with( - new SectorComplete(theCrater), - new Research(coreFloe) - ), () -> { - node(deadValley, with(new SectorComplete(redeploymentPath)), () -> { - - }); - }); - }); - - nodeProduce(cobalt, () -> { - nodeProduce(Items.beryllium, () -> { - nodeProduce(carborundum, () -> { - - }); - }); - nodeProduce(Items.coal, () -> { - nodeProduce(Items.graphite, () -> { - - }); - }); - }); - }); - } + node(theCrater, () -> { + node(redeploymentPath, with( + new SectorComplete(theCrater), + new Research(coreFloe) + ), () -> { + node(deadValley, with(new SectorComplete(redeploymentPath)), () -> { + + }); + }); + }); + + nodeProduce(cobalt, () -> { + nodeProduce(Items.beryllium, () -> { + nodeProduce(carborundum, () -> { + + }); + }); + nodeProduce(Items.coal, () -> { + nodeProduce(Items.graphite, () -> { + + }); + }); + }); + }); + } } diff --git a/src/omaloon/content/OlUnitTypes.java b/src/omaloon/content/OlUnitTypes.java index 01a50b81..7708cd97 100644 --- a/src/omaloon/content/OlUnitTypes.java +++ b/src/omaloon/content/OlUnitTypes.java @@ -22,9 +22,9 @@ import omaloon.gen.*; import omaloon.type.*; -import static arc.Core.*; +import static arc.Core.atlas; -public class OlUnitTypes { +public class OlUnitTypes{ // flying public static UnitType cilantro, basil, sage; @@ -47,7 +47,7 @@ public class OlUnitTypes { public static @EntityDef({Unitc.class, Dronec.class}) UnitType attackDroneAlpha, actionDroneMono; - public static void load() { + public static void load(){ collector = new MillipedeUnitType("collector"){{ constructor = ChainedUnit::create; aiController = MillipedeAI::new; @@ -71,37 +71,37 @@ public static void load() { hidden = true; weaponsIndex = unit -> { - if (unit instanceof Chainedc chain) { - if (chain.isHead() || chain.isTail()) return 0; + if(unit instanceof Chainedc chain){ + if(chain.isHead() || chain.isTail()) return 0; return 1; } return 0; }; chainWeapons.add( - Seq.with(), - Seq.with( - new Weapon("omaloon-collector-beam") {{ - x = 0f; - y = 1f; - rotate = true; - mirror = false; - reload = 60f; - bullet = new ArtilleryBulletType(5f, 7) {{ - maxRange = 40f; - collidesTiles = collidesAir = collidesGround = true; - width = height = 11f; - splashDamage = 25f; - splashDamageRadius = 25f; - trailColor = hitColor = lightColor = backColor = Pal.thoriumPink; - frontColor = Pal.thoriumPink; - }}; - }} - ) + Seq.with(), + Seq.with( + new Weapon("omaloon-collector-beam"){{ + x = 0f; + y = 1f; + rotate = true; + mirror = false; + reload = 60f; + bullet = new ArtilleryBulletType(5f, 7){{ + maxRange = 40f; + collidesTiles = collidesAir = collidesGround = true; + width = height = 11f; + splashDamage = 25f; + splashDamageRadius = 25f; + trailColor = hitColor = lightColor = backColor = Pal.thoriumPink; + frontColor = Pal.thoriumPink; + }}; + }} + ) ); }}; //region core - attackDroneAlpha = new DroneUnitType("combat-drone-alpha") {{ + attackDroneAlpha = new DroneUnitType("combat-drone-alpha"){{ constructor = DroneUnit::create; itemCapacity = 0; @@ -143,7 +143,7 @@ public static void load() { shadowElevationScl = 0.4f; }}; - actionDroneMono = new GlassmoreUnitType("main-drone-mono") {{ + actionDroneMono = new GlassmoreUnitType("main-drone-mono"){{ constructor = DroneUnit::create; mineTier = 3; @@ -168,7 +168,7 @@ public static void load() { shadowElevationScl = 0.4f; }}; - walker = new GlassmoreUnitType("walker") {{ + walker = new GlassmoreUnitType("walker"){{ constructor = FloatMechCoreUnit::create; aiController = BuilderAI::new; @@ -185,30 +185,32 @@ public static void load() { mineTier = 3; abilities.addAll( - new DroneAbility() {{ - name = "omaloon-combat-drone"; - droneUnit = attackDroneAlpha; - droneController = AttackDroneAI::new; - spawnTime = 180f; - spawnX = 5f; spawnY = 0f; - spawnEffect = Fx.spawn; - parentizeEffects = true; - anchorPos = new Vec2[] { - new Vec2(12f, 0f), - }; - }}, - new DroneAbility() {{ - name = "omaloon-utility-drone"; - droneUnit = actionDroneMono; - droneController = UtilityDroneAI::new; - spawnTime = 180f; - spawnX = -5f; spawnY = 0f; - spawnEffect = Fx.spawn; - parentizeEffects = true; - anchorPos = new Vec2[] { - new Vec2(-12f, 0f), - }; - }} + new DroneAbility(){{ + name = "omaloon-combat-drone"; + droneUnit = attackDroneAlpha; + droneController = AttackDroneAI::new; + spawnTime = 180f; + spawnX = 5f; + spawnY = 0f; + spawnEffect = Fx.spawn; + parentizeEffects = true; + anchorPos = new Vec2[]{ + new Vec2(12f, 0f), + }; + }}, + new DroneAbility(){{ + name = "omaloon-utility-drone"; + droneUnit = actionDroneMono; + droneController = UtilityDroneAI::new; + spawnTime = 180f; + spawnX = -5f; + spawnY = 0f; + spawnEffect = Fx.spawn; + parentizeEffects = true; + anchorPos = new Vec2[]{ + new Vec2(-12f, 0f), + }; + }} ); shadowElevationScl = 0.3f; @@ -264,24 +266,26 @@ public static void load() { parts.add(new RegionPart("-tusk"){{ layerOffset = -0.001f; mirror = true; - x = 2.7f; y = 8.6f; + x = 2.7f; + y = 8.6f; outline = true; }}); abilities.add( - new JavelinAbility(20f, 5f, 29f) {{ - minDamage = 5f; - minSpeed = 2; - maxSpeed = 4; - magX = 0.2f; - magY = 0.1f; - }} + new JavelinAbility(20f, 5f, 29f){{ + minDamage = 5f; + minSpeed = 2; + maxSpeed = 4; + magX = 0.2f; + magY = 0.1f; + }} ); weapons.add(new Weapon(name + "-launcher"){{ layerOffset = 1f; mirror = true; - x = 4.7f; y = 2f; + x = 4.7f; + y = 2f; shootCone = 60f; smoothReloadSpeed = 0.5f; shootSound = Sounds.missile; @@ -312,7 +316,7 @@ public static void load() { hitSize = 16; }}; - lumen = new GlassmoreUnitType("lumen") {{ + lumen = new GlassmoreUnitType("lumen"){{ constructor = UnitEntity::create; hitSize = 10f; @@ -325,7 +329,7 @@ public static void load() { range = 5f; health = 70; - weapons.add(new FilterWeapon() {{ + weapons.add(new FilterWeapon(){{ mirror = false; x = 0; y = 4f; @@ -339,75 +343,75 @@ public static void load() { shootCone = 20f; bullets = new BulletType[]{ - new LiquidBulletType(OlLiquids.glacium){{ - recoil = 0.06f; - killShooter = true; - - speed = 2.5f; - drag = 0.009f; - shootEffect = Fx.shootSmall; - lifetime = 27f; - collidesAir = false; - status = OlStatusEffects.glacied; - statusDuration = 60f * 5f; - - despawnSound = hitSound = Sounds.splash; - }}, - new LiquidBulletType(Liquids.water){{ - recoil = 0.06f; - killShooter = true; - - speed = 2.5f; - drag = 0.009f; - shootEffect = Fx.shootSmall; - lifetime = 27f; - collidesAir = false; - status = StatusEffects.wet; - statusDuration = 60f * 5f; - - despawnSound = hitSound = Sounds.splash; - }}, - new LiquidBulletType(Liquids.slag){{ - recoil = 0.06f; - killShooter = true; - - speed = 2.5f; - drag = 0.009f; - shootEffect = Fx.shootSmall; - lifetime = 27f; - collidesAir = false; - status = StatusEffects.melting; - statusDuration = 60f * 5f; - - despawnSound = hitSound = Sounds.splash; - }}, - new LiquidBulletType(Liquids.oil){{ - recoil = 0.06f; - killShooter = true; - - speed = 2.5f; - drag = 0.009f; - shootEffect = Fx.shootSmall; - lifetime = 27f; - collidesAir = false; - status = StatusEffects.tarred; - statusDuration = 60f * 5f; - - despawnSound = hitSound = Sounds.splash; - }} + new LiquidBulletType(OlLiquids.glacium){{ + recoil = 0.06f; + killShooter = true; + + speed = 2.5f; + drag = 0.009f; + shootEffect = Fx.shootSmall; + lifetime = 27f; + collidesAir = false; + status = OlStatusEffects.glacied; + statusDuration = 60f * 5f; + + despawnSound = hitSound = Sounds.splash; + }}, + new LiquidBulletType(Liquids.water){{ + recoil = 0.06f; + killShooter = true; + + speed = 2.5f; + drag = 0.009f; + shootEffect = Fx.shootSmall; + lifetime = 27f; + collidesAir = false; + status = StatusEffects.wet; + statusDuration = 60f * 5f; + + despawnSound = hitSound = Sounds.splash; + }}, + new LiquidBulletType(Liquids.slag){{ + recoil = 0.06f; + killShooter = true; + + speed = 2.5f; + drag = 0.009f; + shootEffect = Fx.shootSmall; + lifetime = 27f; + collidesAir = false; + status = StatusEffects.melting; + statusDuration = 60f * 5f; + + despawnSound = hitSound = Sounds.splash; + }}, + new LiquidBulletType(Liquids.oil){{ + recoil = 0.06f; + killShooter = true; + + speed = 2.5f; + drag = 0.009f; + shootEffect = Fx.shootSmall; + lifetime = 27f; + collidesAir = false; + status = StatusEffects.tarred; + statusDuration = 60f * 5f; + + despawnSound = hitSound = Sounds.splash; + }} + }; + icons = new String[]{ + "omaloon-filled-with-glacium", + "omaloon-filled-with-water", + "omaloon-filled-with-slag", + "omaloon-filled-with-oil" }; - icons = new String[] { - "omaloon-filled-with-glacium", - "omaloon-filled-with-water", - "omaloon-filled-with-slag", - "omaloon-filled-with-oil" - }; bulletFilter = unit -> { - if (unit.hasEffect(OlStatusEffects.filledWithGlacium)) return bullets[0]; - if (unit.hasEffect(OlStatusEffects.filledWithWater)) return bullets[1]; - if (unit.hasEffect(OlStatusEffects.filledWithSlag)) return bullets[2]; - if (unit.hasEffect(OlStatusEffects.filledWithOil)) return bullets[3]; - return new BulletType(0,0){{ + if(unit.hasEffect(OlStatusEffects.filledWithGlacium)) return bullets[0]; + if(unit.hasEffect(OlStatusEffects.filledWithWater)) return bullets[1]; + if(unit.hasEffect(OlStatusEffects.filledWithSlag)) return bullets[2]; + if(unit.hasEffect(OlStatusEffects.filledWithOil)) return bullets[3]; + return new BulletType(0, 0){{ shootEffect = smokeEffect = hitEffect = despawnEffect = Fx.none; }}; }; @@ -453,7 +457,7 @@ public static void load() { }}); }}; - centurion = new GlassmoreUnitType("centurion"){{ + centurion = new GlassmoreUnitType("centurion"){{ constructor = MechUnit::create; speed = 0.4f; hitSize = 9f; @@ -513,7 +517,7 @@ public static void load() { }}); }}; - praetorian = new GlassmoreUnitType("praetorian") {{ + praetorian = new GlassmoreUnitType("praetorian"){{ constructor = MechUnit::create; speed = 0.3f; hitSize = 16f; @@ -521,13 +525,13 @@ public static void load() { health = 400; range = 80f; - parts.add(new ConstructPart("-can") {{ + parts.add(new ConstructPart("-can"){{ y = 3.75f; outlineLayerOffset = -0.01f; progress = PartProgress.reload.inv(); }}); - weapons.add(new Weapon("") {{ + weapons.add(new Weapon(""){{ x = 0f; y = 3.75f; reload = 100f; @@ -536,7 +540,7 @@ public static void load() { shootCone = 45f; shootSound = Sounds.missileLarge; - bullet = new LaunchBulletType(1f, 0) {{ + bullet = new LaunchBulletType(1f, 0){{ sprite = "omaloon-praetorian-can"; frontColor = Color.white; lifetime = 120f; @@ -548,7 +552,7 @@ public static void load() { trailLength = 5; despawnSound = Sounds.artillery; - despawnEffect = new WaveEffect() {{ + despawnEffect = new WaveEffect(){{ colorFrom = colorTo = Color.valueOf("FEB380"); interp = Interp.bounceOut; lifetime = 60f; @@ -561,7 +565,7 @@ public static void load() { shadowInterp = Interp.circleOut; fragBullets = 3; - fragBullet = new BasicBulletType(6f, 10, "omaloon-cross-bullet") {{ + fragBullet = new BasicBulletType(6f, 10, "omaloon-cross-bullet"){{ frontColor = backColor = hitColor = trailColor = Color.valueOf("FEB380"); lifetime = 20f; width = height = 12f; @@ -578,9 +582,9 @@ public static void load() { //endregion //region vegetable - cilantro = new GlassmoreUnitType("cilantro") {{ + cilantro = new GlassmoreUnitType("cilantro"){{ flying = lowAltitude = true; - health = 160; + health = 160; hitSize = 8f; accel = 0.05f; @@ -590,7 +594,7 @@ public static void load() { constructor = UnitEntity::create; - weapons.addAll(new Weapon() {{ + weapons.addAll(new Weapon(){{ mirror = false; x = 0; @@ -602,7 +606,7 @@ public static void load() { shootCone = 45f; shootSound = Sounds.lasershoot; - bullet = new BasicBulletType(2f, 6, "omaloon-triangle-bullet") {{ + bullet = new BasicBulletType(2f, 6, "omaloon-triangle-bullet"){{ width = height = 8f; shrinkY = 0f; trailWidth = 2f; @@ -617,9 +621,9 @@ public static void load() { }}); }}; - basil = new GlassmoreUnitType("basil") {{ + basil = new GlassmoreUnitType("basil"){{ flying = lowAltitude = true; - health = 280; + health = 280; hitSize = 20f; drag = 0.09f; @@ -632,7 +636,7 @@ public static void load() { constructor = UnitEntity::create; - weapons.addAll(new Weapon() {{ + weapons.addAll(new Weapon(){{ mirror = false; continuous = alwaysContinuous = true; @@ -640,8 +644,8 @@ public static void load() { y = -3f; shootSound = Sounds.smelter; - bullet = new ContinuousFlameBulletType(5) {{ - colors = new Color[] {Color.valueOf("8CA9E8"), Color.valueOf("8CA9E8"), Color.valueOf("D1EFFF")}; + bullet = new ContinuousFlameBulletType(5){{ + colors = new Color[]{Color.valueOf("8CA9E8"), Color.valueOf("8CA9E8"), Color.valueOf("D1EFFF")}; lifetime = 60f; @@ -655,7 +659,7 @@ public static void load() { pierceCap = 1; flareColor = Color.valueOf("D1EFFF"); - hitEffect = new ParticleEffect() {{ + hitEffect = new ParticleEffect(){{ lifetime = 30f; length = 20f; @@ -668,9 +672,9 @@ public static void load() { }}); }}; - sage = new GlassmoreUnitType("sage") {{ + sage = new GlassmoreUnitType("sage"){{ flying = lowAltitude = true; - health = 550; + health = 550; hitSize = 35f; speed = 0.8f; @@ -684,11 +688,11 @@ public static void load() { engineSize = 6f; setEnginesMirror(new UnitEngine(10, -14f, 3, -45)); - BulletType shootType = new BasicBulletType(2f, 5) {{ + BulletType shootType = new BasicBulletType(2f, 5){{ lifetime = 55f; - splashDamage = 20f; - splashDamageRadius = 32f; + splashDamage = 20f; + splashDamageRadius = 32f; width = height = 8f; shrinkY = 0f; @@ -704,30 +708,30 @@ public static void load() { }}; weapons.addAll( - new Weapon("omaloon-sage-salvo") {{ - reload = 90f; - rotate = true; - rotateSpeed = 12f; - x = 6.5f; - y = 1f; - - shoot.firstShotDelay = 40f; - - shootCone = 45f; - - shootSound = Sounds.missile; - bullet = shootType; - }}, - new Weapon("omaloon-sage-salvo") {{ - reload = 90f; - rotate = true; - rotateSpeed = 14f; - x = -10.25f; - y = -8f; - - shootSound = Sounds.missile; - bullet = shootType; - }} + new Weapon("omaloon-sage-salvo"){{ + reload = 90f; + rotate = true; + rotateSpeed = 12f; + x = 6.5f; + y = 1f; + + shoot.firstShotDelay = 40f; + + shootCone = 45f; + + shootSound = Sounds.missile; + bullet = shootType; + }}, + new Weapon("omaloon-sage-salvo"){{ + reload = 90f; + rotate = true; + rotateSpeed = 14f; + x = -10.25f; + y = -8f; + + shootSound = Sounds.missile; + bullet = shootType; + }} ); }}; //endregion diff --git a/src/omaloon/content/OlWeathers.java b/src/omaloon/content/OlWeathers.java index 2a5dce66..5bee02a5 100644 --- a/src/omaloon/content/OlWeathers.java +++ b/src/omaloon/content/OlWeathers.java @@ -10,7 +10,7 @@ import omaloon.entities.bullet.*; import omaloon.type.weather.*; -public class OlWeathers { +public class OlWeathers{ public static Weather hailStone, aghaniteStorm, wind; public static void load(){ @@ -25,7 +25,7 @@ public static void load(){ sound = OlSounds.hailRain; setBullets( - //TODO (Maybe this should be added in to the other weather?), Random: Meteor Rain Maybe + //TODO (Maybe this should be added in to the other weather?), Random: Meteor Rain Maybe /*new HailStoneBulletType("omaloon-hailstone-giant", 1){{ hitEffect = Fx.explosion.layer(Layer.power); hitSound = OlSounds.giantHailstoneHit; @@ -37,62 +37,62 @@ public static void load(){ hitShake = 40f; }}, 1/1600f,*/ - new HailStoneBulletType("omaloon-hailstone-big", 3){{ - hitEffect = Fx.explosion.layer(Layer.power); - hitSound = OlSounds.bigHailstoneHit; - hitSoundVolume = 0.2f; - despawnEffect = OlFx.staticStone; - damage = splashDamage = 95f; - splashDamageRadius = 40f; - - canCollideFalling = pierce = true; - fallingDamage = 120f; - fallingRadius = 30f; - minDistanceFallingCollide = 15f; - hitFallingEffect = OlFx.bigExplosionStone; - hitFallingColor = Color.valueOf("5e9098"); - }}, 1/1600f, - - new HailStoneBulletType("omaloon-hailstone-middle", 2){{ - hitEffect = Fx.dynamicWave.layer(Layer.power); - despawnEffect = OlFx.fellStone; - damage = splashDamage = 10f; - splashDamageRadius = 25f; - - canCollideFalling = true; - fallingDamage = 25f; - fallingRadius = 15f; - minDistanceFallingCollide = 5f; - hitFallingEffect = OlFx.explosionStone; - hitFallingColor = Color.valueOf("5e9098"); - }}, 1/12f, - - new HailStoneBulletType("omaloon-hailstone-small", 5){{ - hitEffect = Fx.none; - despawnEffect = OlFx.fellStone; - splashDamage = 0f; - splashDamageRadius = 0; - }}, 1f + new HailStoneBulletType("omaloon-hailstone-big", 3){{ + hitEffect = Fx.explosion.layer(Layer.power); + hitSound = OlSounds.bigHailstoneHit; + hitSoundVolume = 0.2f; + despawnEffect = OlFx.staticStone; + damage = splashDamage = 95f; + splashDamageRadius = 40f; + + canCollideFalling = pierce = true; + fallingDamage = 120f; + fallingRadius = 30f; + minDistanceFallingCollide = 15f; + hitFallingEffect = OlFx.bigExplosionStone; + hitFallingColor = Color.valueOf("5e9098"); + }}, 1 / 1600f, + + new HailStoneBulletType("omaloon-hailstone-middle", 2){{ + hitEffect = Fx.dynamicWave.layer(Layer.power); + despawnEffect = OlFx.fellStone; + damage = splashDamage = 10f; + splashDamageRadius = 25f; + + canCollideFalling = true; + fallingDamage = 25f; + fallingRadius = 15f; + minDistanceFallingCollide = 5f; + hitFallingEffect = OlFx.explosionStone; + hitFallingColor = Color.valueOf("5e9098"); + }}, 1 / 12f, + + new HailStoneBulletType("omaloon-hailstone-small", 5){{ + hitEffect = Fx.none; + despawnEffect = OlFx.fellStone; + splashDamage = 0f; + splashDamageRadius = 0; + }}, 1f ); }}; - aghaniteStorm = new HailStormWeather("aghanite-storm") {{ - attrs.set(Attribute.light, -2f); + aghaniteStorm = new HailStormWeather("aghanite-storm"){{ + attrs.set(Attribute.light, -2f); - particleRegion = "omaloon-aghanite-storm-small-3"; - noisePath = "distortAlpha"; + particleRegion = "omaloon-aghanite-storm-small-3"; + noisePath = "distortAlpha"; - inBounceCam = drawRain = false; - useWindVector = drawNoise = true; - noiseColor = Color.valueOf("968B79"); - baseSpeed = 5.4f; - duration = 15f * Time.toMinutes; - bulletChange = 0.5f; - soundVol = 0.05f; + inBounceCam = drawRain = false; + useWindVector = drawNoise = true; + noiseColor = Color.valueOf("968B79"); + baseSpeed = 5.4f; + duration = 15f * Time.toMinutes; + bulletChange = 0.5f; + soundVol = 0.05f; - sound = Sounds.wind; + sound = Sounds.wind; - setBullets( + setBullets( //TODO (Maybe this should be added in to the other weather?), Random: Meteor Rain Maybe /*new HailStoneBulletType("omaloon-hailstone-giant", 1){{ hitEffect = Fx.explosion.layer(Layer.power); @@ -106,51 +106,51 @@ public static void load(){ }}, 1/1600f,*/ new HailStoneBulletType("omaloon-aghanite-storm-big", 3){{ - speed = 4f; - - hitEffect = Fx.explosion.layer(Layer.power); - hitSound = OlSounds.bigHailstoneHit; - hitSoundVolume = 0.2f; - despawnEffect = OlFx.staticStone; - damage = splashDamage = 95f; - splashDamageRadius = 40f; - - canCollideFalling = pierce = true; - immovable = false; - fallingDamage = 120f; - fallingRadius = 30f; - minDistanceFallingCollide = 15f; - hitFallingEffect = OlFx.bigExplosionStone; - hitFallingColor = Color.valueOf("5e9098"); - }}, 1/1600f, + speed = 4f; + + hitEffect = Fx.explosion.layer(Layer.power); + hitSound = OlSounds.bigHailstoneHit; + hitSoundVolume = 0.2f; + despawnEffect = OlFx.staticStone; + damage = splashDamage = 95f; + splashDamageRadius = 40f; + + canCollideFalling = pierce = true; + immovable = false; + fallingDamage = 120f; + fallingRadius = 30f; + minDistanceFallingCollide = 15f; + hitFallingEffect = OlFx.bigExplosionStone; + hitFallingColor = Color.valueOf("5e9098"); + }}, 1 / 1600f, new HailStoneBulletType("omaloon-aghanite-storm-middle", 2){{ - speed = 4f; - - hitEffect = Fx.none; - despawnEffect = OlFx.fellStoneAghanite; - damage = splashDamage = 10f; - splashDamageRadius = 25f; - - canCollideFalling = true; - immovable = false; - fallingDamage = 25f; - fallingRadius = 15f; - minDistanceFallingCollide = 5f; - hitFallingEffect = OlFx.explosionStone; - hitFallingColor = Color.valueOf("5e9098"); - }}, 1/12f, + speed = 4f; + + hitEffect = Fx.none; + despawnEffect = OlFx.fellStoneAghanite; + damage = splashDamage = 10f; + splashDamageRadius = 25f; + + canCollideFalling = true; + immovable = false; + fallingDamage = 25f; + fallingRadius = 15f; + minDistanceFallingCollide = 5f; + hitFallingEffect = OlFx.explosionStone; + hitFallingColor = Color.valueOf("5e9098"); + }}, 1 / 12f, new HailStoneBulletType("omaloon-aghanite-storm-small", 5){{ - speed = 4f; + speed = 4f; - immovable = false; - hitEffect = Fx.none; - despawnEffect = OlFx.fellStoneAghanite; - splashDamage = 0f; - splashDamageRadius = 0; + immovable = false; + hitEffect = Fx.none; + despawnEffect = OlFx.fellStoneAghanite; + splashDamage = 0f; + splashDamageRadius = 0; }}, 1f - ); + ); }}; wind = new EffectWeather("wind"){{ diff --git a/src/omaloon/content/blocks/OlCraftingBlocks.java b/src/omaloon/content/blocks/OlCraftingBlocks.java index caf4323d..5848177f 100644 --- a/src/omaloon/content/blocks/OlCraftingBlocks.java +++ b/src/omaloon/content/blocks/OlCraftingBlocks.java @@ -8,83 +8,83 @@ import omaloon.world.blocks.production.*; import omaloon.world.consumers.*; -import static mindustry.type.ItemStack.*; +import static mindustry.type.ItemStack.with; -public class OlCraftingBlocks { - public static Block carborundumPress, graphitePress, glaciumBoiler; +public class OlCraftingBlocks{ + public static Block carborundumPress, graphitePress, glaciumBoiler; - public static void load() { - carborundumPress = new PressureCrafter("carborundum-press") {{ - requirements(Category.crafting, with( - OlItems.cobalt, 30, - Items.beryllium, 30 - )); - researchCostMultiplier = 0.3f; - size = 2; - craftTime = 120f; - outputsLiquid = true; + public static void load(){ + carborundumPress = new PressureCrafter("carborundum-press"){{ + requirements(Category.crafting, with( + OlItems.cobalt, 30, + Items.beryllium, 30 + )); + researchCostMultiplier = 0.3f; + size = 2; + craftTime = 120f; + outputsLiquid = true; - craftEffect = OlFx.carborundumCraft; + craftEffect = OlFx.carborundumCraft; - consumeItems(with(Items.beryllium, 1, OlItems.cobalt, 1)); - consume(new ConsumeFluid(null, 5) {{ - startRange = 5f; - endRange = 50f; - efficiencyMultiplier = 1.6f; - curve = t -> Math.min( - 9f/2f * (1f - t), - 9f/7f * t - ); - optimalPressure = 40f; - hasOptimalPressure = true; - }}); + consumeItems(with(Items.beryllium, 1, OlItems.cobalt, 1)); + consume(new ConsumeFluid(null, 5){{ + startRange = 5f; + endRange = 50f; + efficiencyMultiplier = 1.6f; + curve = t -> Math.min( + 9f / 2f * (1f - t), + 9f / 7f * t + ); + optimalPressure = 40f; + hasOptimalPressure = true; + }}); - outputItems = with(OlItems.carborundum, 1); - }}; + outputItems = with(OlItems.carborundum, 1); + }}; - graphitePress = new PressureCrafter("graphite-press") {{ - requirements(Category.crafting, with( - OlItems.cobalt, 15, - Items.beryllium, 25, - OlItems.carborundum, 2 - )); - size = 2; - craftTime = 140f; - outputsLiquid = true; + graphitePress = new PressureCrafter("graphite-press"){{ + requirements(Category.crafting, with( + OlItems.cobalt, 15, + Items.beryllium, 25, + OlItems.carborundum, 2 + )); + size = 2; + craftTime = 140f; + outputsLiquid = true; - craftEffect = Fx.pulverizeMedium; - consumeItem(Items.coal, 4); - consume(new ConsumeFluid(null, 8f) {{ - startRange = 10f; - endRange = 50f; - efficiencyMultiplier = 1.5f; - curve = t -> Math.min( - 8f * (1f - t), - 8f/7f * t - ); - optimalPressure = 45f; - hasOptimalPressure = true; - }}); + craftEffect = Fx.pulverizeMedium; + consumeItem(Items.coal, 4); + consume(new ConsumeFluid(null, 8f){{ + startRange = 10f; + endRange = 50f; + efficiencyMultiplier = 1.5f; + curve = t -> Math.min( + 8f * (1f - t), + 8f / 7f * t + ); + optimalPressure = 45f; + hasOptimalPressure = true; + }}); - outputItem = new ItemStack(Items.graphite, 2); - }}; + outputItem = new ItemStack(Items.graphite, 2); + }}; - glaciumBoiler = new PressureCrafter("glacium-boiler") {{ - requirements(Category.crafting, BuildVisibility.sandboxOnly, with()); - size = 2; + glaciumBoiler = new PressureCrafter("glacium-boiler"){{ + requirements(Category.crafting, BuildVisibility.sandboxOnly, with()); + size = 2; - useVanillaLiquids = false; - ignoreLiquidFullness = true; - dumpExtraLiquid = true; + useVanillaLiquids = false; + ignoreLiquidFullness = true; + dumpExtraLiquid = true; - craftTime = 120f; + craftTime = 120f; - consumeItem(Items.coal, 1); - consume(new ConsumeFluid(OlLiquids.glacium, 1f/60f) {{ - continuous = true; - }}); + consumeItem(Items.coal, 1); + consume(new ConsumeFluid(OlLiquids.glacium, 1f / 60f){{ + continuous = true; + }}); - outputAir = 4f/6f; - }}; - } + outputAir = 4f / 6f; + }}; + } } diff --git a/src/omaloon/content/blocks/OlDefenceBlocks.java b/src/omaloon/content/blocks/OlDefenceBlocks.java index 324cac8d..e2916d6d 100644 --- a/src/omaloon/content/blocks/OlDefenceBlocks.java +++ b/src/omaloon/content/blocks/OlDefenceBlocks.java @@ -22,14 +22,14 @@ import static mindustry.type.ItemStack.*; -public class OlDefenceBlocks { +public class OlDefenceBlocks{ public static Block - //projectors - repairer, smallShelter, - //turrets - apex, convergence, blast, javelin, - //walls - carborundumWall, carborundumWallLarge, + //projectors + repairer, smallShelter, + //turrets + apex, convergence, blast, javelin, + //walls + carborundumWall, carborundumWallLarge, end; @@ -37,8 +37,8 @@ public static void load(){ //region projectors repairer = new RepairProjector("repairer"){{ requirements(Category.effect, with( - OlItems.carborundum, 10, - Items.beryllium, 15, Items.graphite, 3 + OlItems.carborundum, 10, + Items.beryllium, 15, Items.graphite, 3 )); researchCostMultiplier = 0.6f; consumePower(0.2f); @@ -48,10 +48,10 @@ public static void load(){ health = 80; }}; - smallShelter = new Shelter("small-shelter") {{ + smallShelter = new Shelter("small-shelter"){{ requirements(Category.effect, with( - OlItems.cobalt, 25, - Items.beryllium, 30 + OlItems.cobalt, 25, + Items.beryllium, 30 )); researchCostMultiplier = 0.3f; size = 2; @@ -63,16 +63,16 @@ public static void load(){ ambientSoundVolume = 0.08f; consumePower(0.2f); - consume(new ConsumeFluid(null, 1f/12f) {{ - continuous = true; - hasOptimalPressure = true; + consume(new ConsumeFluid(null, 1f / 12f){{ + continuous = true; + hasOptimalPressure = true; - startRange = 15f; - endRange = 50f; - efficiencyMultiplier = 2f; - optimalPressure = 46.5f; + startRange = 15f; + endRange = 50f; + efficiencyMultiplier = 2f; + optimalPressure = 46.5f; - curve = t -> Math.max(0f, Mathf.slope(t - 0.25f) * 2f - 1f); + curve = t -> Math.max(0f, Mathf.slope(t - 0.25f) * 2f - 1f); }}); // consume(new ConsumePressure(0.01f, true)); // consume(new PressureEfficiencyRange(15, 50f, 1.8f, false)); @@ -81,66 +81,66 @@ public static void load(){ //region turrets apex = new ItemTurret("apex"){{ requirements(Category.turret, with( - OlItems.carborundum, 10, - OlItems.cobalt, 20 + OlItems.carborundum, 10, + OlItems.cobalt, 20 )); outlineColor = Color.valueOf("2f2f36"); ammo(OlItems.cobalt, - new BasicBulletType(2.5f, 9){{ - width = 7f; - height = 7f; - lifetime = 25f; - ammoMultiplier = 3; + new BasicBulletType(2.5f, 9){{ + width = 7f; + height = 7f; + lifetime = 25f; + ammoMultiplier = 3; + + despawnEffect = Fx.hitBulletColor; + hitEffect = Fx.hitBulletColor; + hitColor = OlItems.cobalt.color; - despawnEffect = Fx.hitBulletColor; - hitEffect = Fx.hitBulletColor; - hitColor = OlItems.cobalt.color; + trailWidth = 1.3f; + trailLength = 10; + trailColor = OlItems.cobalt.color; - trailWidth = 1.3f; - trailLength = 10; - trailColor = OlItems.cobalt.color; + backColor = OlItems.cobalt.color; - backColor = OlItems.cobalt.color; + fragBullet = new BasicBulletType(2.5f, 2.5f){{ + width = 4f; + height = 4f; + lifetime = 15f; - fragBullet = new BasicBulletType(2.5f, 2.5f){{ - width = 4f; - height = 4f; - lifetime = 15f; + despawnEffect = Fx.none; + hitEffect = Fx.none; + hitColor = OlItems.cobalt.color; - despawnEffect = Fx.none; - hitEffect = Fx.none; - hitColor = OlItems.cobalt.color; + trailWidth = 0.8f; + trailLength = 10; + trailColor = OlItems.cobalt.color; - trailWidth = 0.8f; - trailLength = 10; - trailColor = OlItems.cobalt.color; + backColor = OlItems.cobalt.color; + }}; - backColor = OlItems.cobalt.color; - }}; + fragOnHit = true; + fragBullets = 4; + fragRandomSpread = 45f; + fragVelocityMin = 0.7f; + }}, + Items.graphite, new BasicBulletType(4f, 16){{ + width = 7f; + height = 7f; + lifetime = 25f; + ammoMultiplier = 2; + reloadMultiplier = 1.13f; - fragOnHit = true; - fragBullets = 4; - fragRandomSpread = 45f; - fragVelocityMin = 0.7f; - }}, - Items.graphite, new BasicBulletType(4f, 16){{ - width = 7f; - height = 7f; - lifetime = 25f; - ammoMultiplier = 2; - reloadMultiplier = 1.13f; - - despawnEffect = Fx.hitBulletColor; - hitEffect = Fx.hitBulletColor; - hitColor = Items.graphite.color; - - trailWidth = 1.3f; - trailLength = 3; - trailColor = Items.graphite.color; - - backColor = Items.graphite.color; - knockback = 0.8f; - }} + despawnEffect = Fx.hitBulletColor; + hitEffect = Fx.hitBulletColor; + hitColor = Items.graphite.color; + + trailWidth = 1.3f; + trailLength = 3; + trailColor = Items.graphite.color; + + backColor = Items.graphite.color; + knockback = 0.8f; + }} ); shootY = 0f; @@ -158,13 +158,13 @@ Items.graphite, new BasicBulletType(4f, 16){{ blast = new BlastTower("blast"){{ requirements(Category.turret, with( - OlItems.carborundum, 25, - OlItems.cobalt, 40, - Items.beryllium, 40, Items.graphite, 10 + OlItems.carborundum, 25, + OlItems.cobalt, 40, + Items.beryllium, 40, Items.graphite, 10 )); size = 2; consumePower(70f / 60f); - consume(new ConsumeFluid(null, 6f) {{ + consume(new ConsumeFluid(null, 6f){{ startRange = -45f; endRange = -0.01f; efficiencyMultiplier = 3f; @@ -173,8 +173,8 @@ Items.graphite, new BasicBulletType(4f, 16){{ hasOptimalPressure = true; curve = t -> Math.min( - 9f/8f * (1f - t), - 9f * t + 9f / 8f * (1f - t), + 9f * t ); }}); targetGround = true; @@ -189,9 +189,9 @@ Items.graphite, new BasicBulletType(4f, 16){{ convergence = new PowerTurret("convergence"){{ requirements(Category.turret, with( - OlItems.carborundum, 20, - OlItems.cobalt, 15, - Items.beryllium, 20 + OlItems.carborundum, 20, + OlItems.cobalt, 15, + Items.beryllium, 20 )); consumePower(0.2f); outlineColor = Color.valueOf("2f2f36"); @@ -205,61 +205,64 @@ Items.graphite, new BasicBulletType(4f, 16){{ drawer = new DrawTurret("gl-"); - shootType = new BasicBulletType(2.5f, 18f, "omaloon-orb"){{ - hitEffect = Fx.hitBulletColor; - despawnEffect = Fx.hitBulletColor; + shootType = new BasicBulletType(2.5f, 18f, "omaloon-orb"){ + { + hitEffect = Fx.hitBulletColor; + despawnEffect = Fx.hitBulletColor; - lifetime = 73; - collidesGround = false; - collidesAir = true; + lifetime = 73; + collidesGround = false; + collidesAir = true; - shrinkX = shrinkY = 0f; - height = 5; - - homingDelay = 1f; - homingPower = 0.2f; - homingRange = 120f; - - backColor = Color.valueOf("8ca9e8"); - frontColor = Color.valueOf("d1efff"); - trailWidth = 2.5f; - trailLength = 4; - trailColor = Color.valueOf("8ca9e8"); - } - //I just didn't want to make a separate bulletType for one turret. (Maybe someday I will). - @Override - public void draw(Bullet b){ - super.draw(b); - drawTrail(b); - int sides = 4; - float radius = 0f, radiusTo = 15f, stroke = 3f, innerScl = 0.5f, innerRadScl = 0.33f; - Color color1 = Color.valueOf("8ca9e8"), color2 = Color.valueOf("d1efff"); - float progress = b.fslope(); - float rotation = 45f; - float layer = Layer.effect; - - float z = Draw.z(); - Draw.z(layer); - - float rx = b.x, ry = b.y, rad = Mathf.lerp(radius, radiusTo, progress); - - Draw.color(color1); - for(int j = 0; j < sides; j++){ - Drawf.tri(rx, ry, stroke, rad, j * 360f / sides + rotation); - } + shrinkX = shrinkY = 0f; + height = 5; + + homingDelay = 1f; + homingPower = 0.2f; + homingRange = 120f; - Draw.color(color2); - for(int j = 0; j < sides; j++){ - Drawf.tri(rx, ry, stroke * innerScl, rad * innerRadScl, j * 360f / sides + rotation); + backColor = Color.valueOf("8ca9e8"); + frontColor = Color.valueOf("d1efff"); + trailWidth = 2.5f; + trailLength = 4; + trailColor = Color.valueOf("8ca9e8"); } - Draw.color(); - Draw.z(z); - }}; + //I just didn't want to make a separate bulletType for one turret. (Maybe someday I will). + @Override + public void draw(Bullet b){ + super.draw(b); + drawTrail(b); + int sides = 4; + float radius = 0f, radiusTo = 15f, stroke = 3f, innerScl = 0.5f, innerRadScl = 0.33f; + Color color1 = Color.valueOf("8ca9e8"), color2 = Color.valueOf("d1efff"); + float progress = b.fslope(); + float rotation = 45f; + float layer = Layer.effect; + + float z = Draw.z(); + Draw.z(layer); + + float rx = b.x, ry = b.y, rad = Mathf.lerp(radius, radiusTo, progress); + + Draw.color(color1); + for(int j = 0; j < sides; j++){ + Drawf.tri(rx, ry, stroke, rad, j * 360f / sides + rotation); + } + + Draw.color(color2); + for(int j = 0; j < sides; j++){ + Drawf.tri(rx, ry, stroke * innerScl, rad * innerRadScl, j * 360f / sides + rotation); + } + + Draw.color(); + Draw.z(z); + } + }; }}; //TODO: 0.2, but let this be sandbox only (this needs a massive nerf lmao) - javelin = new ConsumeTurret("javelin") {{ + javelin = new ConsumeTurret("javelin"){{ requirements(Category.turret, BuildVisibility.sandboxOnly, with()); outlineColor = Color.valueOf("2f2f36"); @@ -272,41 +275,41 @@ public void draw(Bullet b){ drawer = new DrawTurret("gl-"){{ parts.add( - new RegionPart("-missile"){{ - y = 2f; - progress = PartProgress.smoothReload.curve(Interp.pow2In); - - colorTo = new Color(1f, 1f, 1f, 0f); - color = Color.white; - mixColorTo = Pal.accent; - mixColor = new Color(1f, 1f, 1f, 0f); - outline = false; - under = true; - - layerOffset = -0.01f; - }} + new RegionPart("-missile"){{ + y = 2f; + progress = PartProgress.smoothReload.curve(Interp.pow2In); + + colorTo = new Color(1f, 1f, 1f, 0f); + color = Color.white; + mixColorTo = Pal.accent; + mixColor = new Color(1f, 1f, 1f, 0f); + outline = false; + under = true; + + layerOffset = -0.01f; + }} ); }}; shootSound = OlSounds.theShoot; consumeItems(with( - Items.coal, 1, - OlItems.carborundum, 3 + Items.coal, 1, + OlItems.carborundum, 3 )); - consume(new ConsumeFluid(null, 36) {{ - startRange = 1.8f; - endRange = 18f; + consume(new ConsumeFluid(null, 36){{ + startRange = 1.8f; + endRange = 18f; - curve = t -> Math.min( - 2f * t, - -2 * t + 2 - ); + curve = t -> Math.min( + 2f * t, + -2 * t + 2 + ); - hasOptimalPressure = true; - optimalPressure = 9f; + hasOptimalPressure = true; + optimalPressure = 9f; - efficiencyMultiplier = 2f; - }}); + efficiencyMultiplier = 2f; + }}); shootType = new BasicBulletType(1.6f, 12f, "omaloon-javelin-missile-outlined"){{ lifetime = 40f; ammoMultiplier = 1f; @@ -322,7 +325,7 @@ public void draw(Bullet b){ despawnSound = Sounds.missileLarge; layer = Layer.turret - 0.01f; - despawnUnit = new MissileUnitType("javelin-missile") {{ + despawnUnit = new MissileUnitType("javelin-missile"){{ hittable = drawCell = false; speed = 4.6f; maxRange = 6f; @@ -345,52 +348,52 @@ public void draw(Bullet b){ health = 210; weapons.add(new Weapon(){{ - shootCone = 360f; - mirror = false; - reload = 1f; - deathExplosionEffect = Fx.massiveExplosion; - shootOnDeath = true; - shake = 10f; - bullet = new ExplosionBulletType(700f, 65f){{ - hitColor = Pal.redLight; - - collidesAir = false; - buildingDamageMultiplier = 0.3f; - - ammoMultiplier = 1f; - fragLifeMin = 0.1f; - fragBullets = 7; - fragBullet = new ArtilleryBulletType(3.4f, 32){{ - buildingDamageMultiplier = 0.3f; - drag = 0.02f; - hitEffect = Fx.massiveExplosion; - despawnEffect = Fx.scatheSlash; - knockback = 0.8f; - lifetime = 23f; - width = height = 18f; - collidesTiles = false; - splashDamageRadius = 40f; - splashDamage = 80f; - backColor = trailColor = hitColor = Pal.redLight; - frontColor = Color.white; - smokeEffect = Fx.shootBigSmoke2; - despawnShake = 7f; - lightRadius = 30f; - lightColor = Pal.redLight; - lightOpacity = 0.5f; - - trailLength = 10; - trailWidth = 0.5f; - trailEffect = Fx.none; - }}; - }}; - }}); + shootCone = 360f; + mirror = false; + reload = 1f; + deathExplosionEffect = Fx.massiveExplosion; + shootOnDeath = true; + shake = 10f; + bullet = new ExplosionBulletType(700f, 65f){{ + hitColor = Pal.redLight; + + collidesAir = false; + buildingDamageMultiplier = 0.3f; + + ammoMultiplier = 1f; + fragLifeMin = 0.1f; + fragBullets = 7; + fragBullet = new ArtilleryBulletType(3.4f, 32){{ + buildingDamageMultiplier = 0.3f; + drag = 0.02f; + hitEffect = Fx.massiveExplosion; + despawnEffect = Fx.scatheSlash; + knockback = 0.8f; + lifetime = 23f; + width = height = 18f; + collidesTiles = false; + splashDamageRadius = 40f; + splashDamage = 80f; + backColor = trailColor = hitColor = Pal.redLight; + frontColor = Color.white; + smokeEffect = Fx.shootBigSmoke2; + despawnShake = 7f; + lightRadius = 30f; + lightColor = Pal.redLight; + lightOpacity = 0.5f; + + trailLength = 10; + trailWidth = 0.5f; + trailEffect = Fx.none; + }}; + }}; + }}); }}; }}; - pressureConfig = new PressureConfig() {{ - fluidCapacity = 20; - }}; + pressureConfig = new PressureConfig(){{ + fluidCapacity = 20; + }}; }}; //endregion //region walls diff --git a/src/omaloon/content/blocks/OlDistributionBlocks.java b/src/omaloon/content/blocks/OlDistributionBlocks.java index c27bca91..306fb1ea 100644 --- a/src/omaloon/content/blocks/OlDistributionBlocks.java +++ b/src/omaloon/content/blocks/OlDistributionBlocks.java @@ -1,6 +1,5 @@ package omaloon.content.blocks; -import arc.graphics.*; import mindustry.content.*; import mindustry.gen.*; import mindustry.graphics.*; @@ -15,7 +14,7 @@ import static mindustry.type.ItemStack.*; -public class OlDistributionBlocks { +public class OlDistributionBlocks{ public static Block //item tubeConveyor, tubeDistributor, tubeJunction, tubeSorter, tubeGate, tubeBridge, @@ -25,11 +24,11 @@ public class OlDistributionBlocks { end; - public static void load() { + public static void load(){ // region items - tubeConveyor = new TubeConveyor("tube-conveyor") {{ + tubeConveyor = new TubeConveyor("tube-conveyor"){{ requirements(Category.distribution, with( - OlItems.cobalt, 1 + OlItems.cobalt, 1 )); researchCost = empty; health = 65; @@ -39,48 +38,48 @@ public static void load() { tubeDistributor = new TubeDistributor("tube-distributor"){{ requirements(Category.distribution, with( - OlItems.cobalt, 3 + OlItems.cobalt, 3 )); researchCost = empty; speed = 10f; buildCostMultiplier = 4f; health = 65; drawer = new DrawMulti( - new DrawRegion("-bottom"){{ - layer = Layer.blockUnder; - }} + new DrawRegion("-bottom"){{ + layer = Layer.blockUnder; + }} ); }}; tubeJunction = new TubeJunction("tube-junction"){{ requirements(Category.distribution, with( - OlItems.cobalt, 3 + OlItems.cobalt, 3 )); researchCostMultiplier = 0.3f; speed = 25; capacity = 4; health = 65; drawer = new DrawMulti( - new DrawRegion("-bottom"){{ - layer = Layer.blockUnder; - }}, - new DrawDefault() + new DrawRegion("-bottom"){{ + layer = Layer.blockUnder; + }}, + new DrawDefault() ); }}; tubeSorter = new TubeSorter("tube-sorter"){{ requirements(Category.distribution, with( - OlItems.cobalt, 3, - Items.beryllium, 2, OlItems.carborundum, 1 + OlItems.cobalt, 3, + Items.beryllium, 2, OlItems.carborundum, 1 )); researchCostMultiplier = 0.3f; health = 65; }}; - tubeGate = new TubeGate("tube-gate") {{ + tubeGate = new TubeGate("tube-gate"){{ requirements(Category.distribution, with( - OlItems.cobalt, 3, - Items.beryllium, 2, OlItems.carborundum, 1 + OlItems.cobalt, 3, + Items.beryllium, 2, OlItems.carborundum, 1 )); researchCostMultiplier = 0.3f; health = 65; @@ -88,8 +87,8 @@ public static void load() { tubeBridge = new TubeItemBridge("tube-bridge-conveyor"){{ requirements(Category.distribution, with( - OlItems.cobalt, 3, - Items.beryllium, 2 + OlItems.cobalt, 3, + Items.beryllium, 2 )); researchCostMultiplier = 0.3f; fadeIn = moveArrows = false; @@ -101,38 +100,38 @@ public static void load() { //endregion //region liquids - liquidTube = new PressureLiquidConduit("liquid-tube") {{ + liquidTube = new PressureLiquidConduit("liquid-tube"){{ requirements(Category.liquid, with( - OlItems.cobalt, 2 + OlItems.cobalt, 2 )); researchCost = with( - OlItems.cobalt, 10 + OlItems.cobalt, 10 ); }}; - liquidJunction = new PressureLiquidJunction("liquid-junction") {{ + liquidJunction = new PressureLiquidJunction("liquid-junction"){{ requirements(Category.liquid, with( - OlItems.cobalt, 5 + OlItems.cobalt, 5 )); researchCostMultiplier = 0.3f; }}; - liquidBridge = new PressureLiquidBridge("liquid-bridge") {{ + liquidBridge = new PressureLiquidBridge("liquid-bridge"){{ requirements(Category.liquid, with( - OlItems.cobalt, 2, - Items.beryllium, 3 + OlItems.cobalt, 2, + Items.beryllium, 3 )); range = 4; }}; - liquidPump = new PressureLiquidPump("liquid-pump") {{ + liquidPump = new PressureLiquidPump("liquid-pump"){{ requirements(Category.liquid, with( - OlItems.cobalt, 4 + OlItems.cobalt, 4 )); researchCost = with( - OlItems.cobalt, 25 + OlItems.cobalt, 25 ); - pumpStrength = 5f/60f; + pumpStrength = 5f / 60f; ambientSound = Sounds.wind2; ambientSoundVolume = 0.1f; @@ -140,23 +139,23 @@ public static void load() { pumpEffectIn = OlFx.pumpIn; pumpEffectOut = OlFx.pumpOut; - pressureConfig = new PressureConfig() {{ + pressureConfig = new PressureConfig(){{ // minPressure = -25f; // maxPressure = 25f; }}; }}; - filterPump = new PressureLiquidPump("filter-pump") {{ + filterPump = new PressureLiquidPump("filter-pump"){{ requirements(Category.liquid, with( - OlItems.cobalt, 4 + OlItems.cobalt, 4 )); researchCost = with( - OlItems.cobalt, 20 + OlItems.cobalt, 20 ); - pumpStrength = 1f/6f; + pumpStrength = 1f / 6f; pressureDifference = 0; - configurable = true; + configurable = true; ambientSound = Sounds.wind2; ambientSoundVolume = 0.1f; @@ -165,14 +164,14 @@ public static void load() { pumpEffectOut = OlFx.pumpOut; }}; - liquidValve = new PressureLiquidValve("liquid-valve") {{ + liquidValve = new PressureLiquidValve("liquid-valve"){{ requirements(Category.liquid, BuildVisibility.sandboxOnly, with( - OlItems.cobalt, 2, - Items.beryllium, 2 + OlItems.cobalt, 2, + Items.beryllium, 2 )); researchCost = with( - OlItems.cobalt, 20, - Items.beryllium, 20 + OlItems.cobalt, 20, + Items.beryllium, 20 ); pressureLoss = 0.3f; @@ -180,14 +179,14 @@ public static void load() { pumpingEffectOut = OlFx.flowOut; }}; - liquidGauge = new PressureLiquidGauge("liquid-gauge") {{ + liquidGauge = new PressureLiquidGauge("liquid-gauge"){{ requirements(Category.liquid, with( - OlItems.cobalt, 2, - Items.beryllium, 1 + OlItems.cobalt, 2, + Items.beryllium, 1 )); researchCost = with( - OlItems.cobalt, 20, - Items.beryllium, 10 + OlItems.cobalt, 20, + Items.beryllium, 10 ); }}; //endregion diff --git a/src/omaloon/content/blocks/OlEnvironmentBlocks.java b/src/omaloon/content/blocks/OlEnvironmentBlocks.java index 4c3724d0..5b9b04d3 100644 --- a/src/omaloon/content/blocks/OlEnvironmentBlocks.java +++ b/src/omaloon/content/blocks/OlEnvironmentBlocks.java @@ -3,54 +3,52 @@ import arc.graphics.*; import arc.math.geom.*; import mindustry.content.*; -import mindustry.gen.Sounds; -import mindustry.graphics.CacheLayer; -import mindustry.graphics.Layer; +import mindustry.gen.*; import mindustry.world.*; import mindustry.world.blocks.environment.*; import omaloon.content.*; import omaloon.graphics.*; import omaloon.world.blocks.environment.*; -public class OlEnvironmentBlocks { +public class OlEnvironmentBlocks{ public static Block - //cliff - cliffUp, cliffHelper, - //ores - oreCobalt, oreBeryllium, oreCoal, - //biomes - deadShrub, gerbDebris, - deadGrass, - - frozenSoilWall, frozenSoilBoulder, - frozenSoil, - - albasterWall, albasterBoulder, - albaster, albasterTiles, albasterCrater, - - aghatiteWall, weatheredAghaniteWall, cobaltedAghaniteWall, - aghatiteBoulder, weatheredAghaniteBoulder, berylledAghaniteBoulder, cobaltedAghaniteStones, - aghaniteConcretion, largeAghaniteConcretion, - aghatite, aghatitePebbles, - smoothAghanite, weatheredAghanite, aghaniteShale, aghaniteDust, - coastalAghanite, berylledAghanite, cobaltedAghanite, - - quartzSandWall, quartzSandBoulder, - quartzSand, - - deepGlacium, glacium, greniteGlacium, - greniteWall, darkGreniteWall, greniteBoulder, - grenite, coastalGrenite, - - blueIceWall, blueSnowWall, blueBoulder, - blueIce, blueIcePieces, blueSnow, blueSnowdrifts, weatheredIce, - //artificial - glasmoreMetal, ruinedGerbTiles, ruinedGerbMasonry, - ruinedGerbWall, - //dead tree - fallenDeadTree, fallenDeadTreeTopHalf, fallenDeadTreeBottomHalf, - spikedTree, bushTree, - standingDeadTree, deadTreeStump, + //cliff + cliffUp, cliffHelper, + //ores + oreCobalt, oreBeryllium, oreCoal, + //biomes + deadShrub, gerbDebris, + deadGrass, + + frozenSoilWall, frozenSoilBoulder, + frozenSoil, + + albasterWall, albasterBoulder, + albaster, albasterTiles, albasterCrater, + + aghatiteWall, weatheredAghaniteWall, cobaltedAghaniteWall, + aghatiteBoulder, weatheredAghaniteBoulder, berylledAghaniteBoulder, cobaltedAghaniteStones, + aghaniteConcretion, largeAghaniteConcretion, + aghatite, aghatitePebbles, + smoothAghanite, weatheredAghanite, aghaniteShale, aghaniteDust, + coastalAghanite, berylledAghanite, cobaltedAghanite, + + quartzSandWall, quartzSandBoulder, + quartzSand, + + deepGlacium, glacium, greniteGlacium, + greniteWall, darkGreniteWall, greniteBoulder, + grenite, coastalGrenite, + + blueIceWall, blueSnowWall, blueBoulder, + blueIce, blueIcePieces, blueSnow, blueSnowdrifts, weatheredIce, + //artificial + glasmoreMetal, ruinedGerbTiles, ruinedGerbMasonry, + ruinedGerbWall, + //dead tree + fallenDeadTree, fallenDeadTreeTopHalf, fallenDeadTreeBottomHalf, + spikedTree, bushTree, + standingDeadTree, deadTreeStump, end; @@ -148,10 +146,10 @@ public static void load(){ variants = 2; }}; - aghaniteConcretion = new TallBlock("aghanite-concretion") {{ + aghaniteConcretion = new TallBlock("aghanite-concretion"){{ variants = 2; }}; - largeAghaniteConcretion = new TallBlock("large-aghanite-concretion") {{ + largeAghaniteConcretion = new TallBlock("large-aghanite-concretion"){{ variants = 2; }}; @@ -164,31 +162,31 @@ public static void load(){ decoration = aghatiteBoulder; }}; - smoothAghanite = new Floor("smooth-aghanite", 4) {{ + smoothAghanite = new Floor("smooth-aghanite", 4){{ wall = weatheredAghaniteWall; decoration = weatheredAghaniteBoulder; }}; - weatheredAghanite = new Floor("weathered-aghanite", 2) {{ + weatheredAghanite = new Floor("weathered-aghanite", 2){{ wall = weatheredAghaniteWall; decoration = weatheredAghaniteBoulder; }}; - aghaniteShale = new Floor("aghanite-shale", 4) {{ + aghaniteShale = new Floor("aghanite-shale", 4){{ wall = weatheredAghaniteWall; decoration = weatheredAghaniteBoulder; }}; aghaniteDust = new OverlayFloor("aghanite-dust"){{ - variants = 2; + variants = 2; }}; - coastalAghanite = new Floor("coastal-aghanite",3) {{ + coastalAghanite = new Floor("coastal-aghanite", 3){{ wall = aghatiteWall; decoration = aghatiteBoulder; }}; - berylledAghanite = new Floor("berylled-aghanite", 3) {{ + berylledAghanite = new Floor("berylled-aghanite", 3){{ wall = weatheredAghaniteWall; decoration = berylledAghaniteBoulder; }}; - cobaltedAghanite = new Floor("cobalted-aghanite", 2) {{ + cobaltedAghanite = new Floor("cobalted-aghanite", 2){{ wall = cobaltedAghaniteWall; decoration = cobaltedAghaniteStones; }}; @@ -257,7 +255,7 @@ public static void load(){ }}; darkGreniteWall = new StaticWall("dark-grenite-wall"){{ - variants = 2; + variants = 2; }}; greniteBoulder = new Prop("grenite-boulder"){{ @@ -301,9 +299,9 @@ public static void load(){ }}; blueBoulder = new Prop("blue-boulder"){{ - variants = 3; - blueIce.asFloor().decoration = this; - blueSnow.asFloor().decoration = this; + variants = 3; + blueIce.asFloor().decoration = this; + blueSnow.asFloor().decoration = this; }}; //endregion //region frozen soil @@ -332,78 +330,78 @@ public static void load(){ }}; //endregion //region fallen dead tree - fallenDeadTree = new CustomShapeProp("fallen-dead-tree") {{ + fallenDeadTree = new CustomShapeProp("fallen-dead-tree"){{ clipSize = 144f; variants = 8; canMirror = true; spriteOffsets = new Vec2[]{ - new Vec2(-16f, -32f), - new Vec2(8f, -32f), - new Vec2(-16, -32f), - new Vec2(-8f, -32f), - - new Vec2(-8f, -16f), - new Vec2(-32f, -16f), - new Vec2(0f, -16f), - new Vec2(-32f, -16f) + new Vec2(-16f, -32f), + new Vec2(8f, -32f), + new Vec2(-16, -32f), + new Vec2(-8f, -32f), + + new Vec2(-8f, -16f), + new Vec2(-32f, -16f), + new Vec2(0f, -16f), + new Vec2(-32f, -16f) }; }}; - fallenDeadTreeTopHalf = new CustomShapeProp("fallen-dead-tree-top-half") {{ + fallenDeadTreeTopHalf = new CustomShapeProp("fallen-dead-tree-top-half"){{ clipSize = 80f; variants = 8; canMirror = true; spriteOffsets = new Vec2[]{ - new Vec2(-8f, -16f), - new Vec2(-8f, -16f), - new Vec2(-8f, -16f), - new Vec2(0f, -16f), - - new Vec2(-16f, -8f), - new Vec2(-16f, -8f), - new Vec2(-8f, -8f), - new Vec2(-16f, -8f) + new Vec2(-8f, -16f), + new Vec2(-8f, -16f), + new Vec2(-8f, -16f), + new Vec2(0f, -16f), + + new Vec2(-16f, -8f), + new Vec2(-16f, -8f), + new Vec2(-8f, -8f), + new Vec2(-16f, -8f) }; }}; - fallenDeadTreeBottomHalf = new CustomShapeProp("fallen-dead-tree-bottom-half") {{ + fallenDeadTreeBottomHalf = new CustomShapeProp("fallen-dead-tree-bottom-half"){{ clipSize = 64f; variants = 8; canMirror = true; spriteOffsets = new Vec2[]{ - new Vec2(-12f, -8f), - new Vec2(-4f, -8f), - new Vec2(-12f, -8f), - new Vec2(-12f, -8f), - - new Vec2(-8f, -12f), - new Vec2(-8f, -12f), - new Vec2(0f, -12f), - new Vec2(-8f, -12f) + new Vec2(-12f, -8f), + new Vec2(-4f, -8f), + new Vec2(-12f, -8f), + new Vec2(-12f, -8f), + + new Vec2(-8f, -12f), + new Vec2(-8f, -12f), + new Vec2(0f, -12f), + new Vec2(-8f, -12f) }; }}; - spikedTree = new Prop("spiked-tree") {{ + spikedTree = new Prop("spiked-tree"){{ variants = 2; customShadow = true; }}; - bushTree = new RotatedProp("bush-tree") {{ + bushTree = new RotatedProp("bush-tree"){{ variants = 0; customShadow = true; breakSound = Sounds.plantBreak; }}; - standingDeadTree = new CustomShapeProp("standing-dead-tree") {{ + standingDeadTree = new CustomShapeProp("standing-dead-tree"){{ clipSize = 32f; variants = 1; spriteOffsets = new Vec2[]{ - new Vec2(-4f, -12f), + new Vec2(-4f, -12f), }; }}; - deadTreeStump = new CustomShapeProp("dead-tree-stump") {{ + deadTreeStump = new CustomShapeProp("dead-tree-stump"){{ clipSize = 16f; variants = 1; rotateRegions = drawUnder = true; spriteOffsets = new Vec2[]{ - new Vec2(-4f, -4f), + new Vec2(-4f, -4f), }; }}; //endregion diff --git a/src/omaloon/content/blocks/OlPowerBlocks.java b/src/omaloon/content/blocks/OlPowerBlocks.java index 3ffdf6e8..2040f60c 100644 --- a/src/omaloon/content/blocks/OlPowerBlocks.java +++ b/src/omaloon/content/blocks/OlPowerBlocks.java @@ -13,7 +13,7 @@ import omaloon.world.blocks.power.*; import omaloon.world.draw.*; -import static mindustry.type.ItemStack.*; +import static mindustry.type.ItemStack.with; public class OlPowerBlocks{ public static Block @@ -24,19 +24,19 @@ public class OlPowerBlocks{ public static void load(){ windTurbine = new WindGenerator("wind-turbine"){{ requirements(Category.power, with( - Items.beryllium, 7 + Items.beryllium, 7 )); researchCostMultiplier = 0.5f; drawer = new DrawMulti( - new DrawDefault(), - new Draw3dSpin("-holder", "-rotator"){{ - baseOffset.x = Vars.tilesize / 2f; - axis = Vec3.Y; - rotationProvider(WindGeneratorBuild::baseRotation); - rotationAroundAxis = -55f; - rotateSpeed = baseRotateSpeed = 3.3f; - scale.set(0.5f, 1f, 0f); - }} + new DrawDefault(), + new Draw3dSpin("-holder", "-rotator"){{ + baseOffset.x = Vars.tilesize / 2f; + axis = Vec3.Y; + rotationProvider(WindGeneratorBuild::baseRotation); + rotationAroundAxis = -55f; + rotateSpeed = baseRotateSpeed = 3.3f; + scale.set(0.5f, 1f, 0f); + }} ); size = 1; powerProduction = 0.2f; @@ -44,8 +44,8 @@ public static void load(){ coalGenerator = new ConsumeGenerator("coal-generator"){{ requirements(Category.power, with( - OlItems.cobalt, 15, - Items.beryllium, 10, Items.graphite, 5 + OlItems.cobalt, 15, + Items.beryllium, 10, Items.graphite, 5 )); powerProduction = 1f; itemDuration = 120f; @@ -58,19 +58,19 @@ public static void load(){ consumeItem(Items.coal, 1); drawer = new DrawMulti(new DrawDefault(), - new DrawFlame(Color.valueOf("ffcd66")){{ - flameRadius = 2f; - flameRadiusIn = 1f; - flameRadiusScl = 4f; - flameRadiusMag = 1f; - flameRadiusInMag = 0.5f; - }} + new DrawFlame(Color.valueOf("ffcd66")){{ + flameRadius = 2f; + flameRadiusIn = 1f; + flameRadiusScl = 4f; + flameRadiusMag = 1f; + flameRadiusInMag = 0.5f; + }} ); }}; impulseNode = new ImpulseNode("impulse-node"){{ requirements(Category.power, with( - Items.beryllium, 5 + Items.beryllium, 5 )); researchCostMultiplier = 0.5f; maxNodes = 10; diff --git a/src/omaloon/content/blocks/OlProductionBlocks.java b/src/omaloon/content/blocks/OlProductionBlocks.java index 9f4cd80b..96ea2c94 100644 --- a/src/omaloon/content/blocks/OlProductionBlocks.java +++ b/src/omaloon/content/blocks/OlProductionBlocks.java @@ -7,21 +7,21 @@ import omaloon.world.blocks.production.*; import omaloon.world.consumers.*; -import static mindustry.type.ItemStack.*; +import static mindustry.type.ItemStack.with; -public class OlProductionBlocks { +public class OlProductionBlocks{ public static Block - hammerDrill, + hammerDrill, end; public static void load(){ hammerDrill = new HammerDrill("hammer-drill"){{ requirements(Category.production, with( - OlItems.cobalt, 10 + OlItems.cobalt, 10 )); researchCost = with( - OlItems.cobalt, 30 + OlItems.cobalt, 30 ); drillTime = 920f; tier = 3; @@ -31,7 +31,7 @@ public static void load(){ pressureConfig.linkList.add(this); - consume(new ConsumeFluid(null, -5f) {{ + consume(new ConsumeFluid(null, -5f){{ startRange = -45f; endRange = -0.01f; efficiencyMultiplier = 2f; @@ -40,8 +40,8 @@ public static void load(){ hasOptimalPressure = true; curve = t -> Math.min( - 9f/8f * (1f - t), - 9f * t + 9f / 8f * (1f - t), + 9f * t ); }}); }}; diff --git a/src/omaloon/content/blocks/OlSandboxBlocks.java b/src/omaloon/content/blocks/OlSandboxBlocks.java index d33dab4b..6ce4c5e8 100644 --- a/src/omaloon/content/blocks/OlSandboxBlocks.java +++ b/src/omaloon/content/blocks/OlSandboxBlocks.java @@ -5,19 +5,19 @@ import mindustry.world.meta.*; import omaloon.world.blocks.sandbox.*; -public class OlSandboxBlocks { - public static Block pressureSource/*, pressureVoid*/; +public class OlSandboxBlocks{ + public static Block pressureSource/*, pressureVoid*/; - public static void load() { - pressureSource = new PressureLiquidSource("pressure-source") {{ - buildVisibility = BuildVisibility.sandboxOnly; - category = Category.liquid; - }}; + public static void load(){ + pressureSource = new PressureLiquidSource("pressure-source"){{ + buildVisibility = BuildVisibility.sandboxOnly; + category = Category.liquid; + }}; /* pressureVoid = new PressureLiquidVoid("pressure-void") {{ buildVisibility = BuildVisibility.sandboxOnly; category = Category.liquid; }}; */ - } + } } diff --git a/src/omaloon/content/blocks/OlStorageBlocks.java b/src/omaloon/content/blocks/OlStorageBlocks.java index d7e3e75f..a181e075 100644 --- a/src/omaloon/content/blocks/OlStorageBlocks.java +++ b/src/omaloon/content/blocks/OlStorageBlocks.java @@ -9,16 +9,16 @@ import static mindustry.type.ItemStack.*; -public class OlStorageBlocks { +public class OlStorageBlocks{ public static Block - landingCapsule, coreFloe, + landingCapsule, coreFloe, end; public static void load(){ landingCapsule = new GlassmoreCoreBlock("landing-capsule"){{ requirements(Category.effect, BuildVisibility.editorOnly, with( - OlItems.cobalt, 600, - Items.beryllium, 300, Items.coal, 50 + OlItems.cobalt, 600, + Items.beryllium, 300, Items.coal, 50 )); isFirstTier = true; @@ -35,9 +35,9 @@ public static void load(){ coreFloe = new GlassmoreCoreBlock("core-floe"){{ requirements(Category.effect, with( - OlItems.carborundum, 250, - OlItems.cobalt, 450, - Items.beryllium, 350 + OlItems.carborundum, 250, + OlItems.cobalt, 450, + Items.beryllium, 350 )); researchCost = empty; diff --git a/src/omaloon/core/EditorListener.java b/src/omaloon/core/EditorListener.java index dc09d295..80d63ef8 100644 --- a/src/omaloon/core/EditorListener.java +++ b/src/omaloon/core/EditorListener.java @@ -7,25 +7,25 @@ import static mindustry.Vars.*; -public class EditorListener implements ApplicationListener { - boolean isEditor; +public class EditorListener implements ApplicationListener{ + boolean isEditor; - public EditorListener() { - if (Vars.platform instanceof ApplicationCore core) core.add(this); - Events.on(StateChangeEvent.class, e -> { - if(e.from == State.menu && e.to == State.playing && state.isEditor()){ - if(true){ - state.map.tags.put("name", editor.tags.get("name")); + public EditorListener(){ + if(Vars.platform instanceof ApplicationCore core) core.add(this); + Events.on(StateChangeEvent.class, e -> { + if(e.from == State.menu && e.to == State.playing && state.isEditor()){ + if(true){ + state.map.tags.put("name", editor.tags.get("name")); - isEditor = true; - } - }else if(isEditor && e.to == State.menu){ - isEditor = false; - } - }); - } + isEditor = true; + } + }else if(isEditor && e.to == State.menu){ + isEditor = false; + } + }); + } - public boolean isEditor() { - return isEditor; - } + public boolean isEditor(){ + return isEditor; + } } diff --git a/src/omaloon/core/OlSettings.java b/src/omaloon/core/OlSettings.java index ce87ba50..4e25ce44 100644 --- a/src/omaloon/core/OlSettings.java +++ b/src/omaloon/core/OlSettings.java @@ -15,32 +15,33 @@ public class OlSettings{ public static String discordURL = "https://discord.gg/bNMT82Hswb"; + public static void load(){ //add omaloon settings ui.settings.addCategory("@settings.omaloon", OlIcons.settings, table -> { table.table(Tex.button, cat -> { - if(!mobile || Core.settings.getBool("keyboard")) { + if(!mobile || Core.settings.getBool("keyboard")){ cat.button( - "@settings.controls", - Icon.move, - Styles.flatt, - iconMed, - () -> OmaloonMod.olInputDialog.show() + "@settings.controls", + Icon.move, + Styles.flatt, + iconMed, + () -> OmaloonMod.olInputDialog.show() ).growX().marginLeft(8f).height(50f).row(); - } + } cat.button( - "@settings.game", - Icon.settings, - Styles.flatt, - iconMed, - () -> OmaloonMod.olGameDialog.show() + "@settings.game", + Icon.settings, + Styles.flatt, + iconMed, + () -> OmaloonMod.olGameDialog.show() ).growX().marginLeft(8f).height(50f).row(); cat.button( - "@settings.omaloon-moddata", - Icon.save, - Styles.flatt, - iconMed, - () -> OmaloonMod.olGameDataDialog.show() + "@settings.omaloon-moddata", + Icon.save, + Styles.flatt, + iconMed, + () -> OmaloonMod.olGameDataDialog.show() ).growX().marginLeft(8f).height(50f).row(); }).width(Math.min(Core.graphics.getWidth() / 1.2f, 460.0F)).padBottom(45); // table.sliderPref("@setting.omaloon-shield-opacity", 20, 0, 100, s -> s + "%"); @@ -51,36 +52,36 @@ public static void load(){ //discord link table.fill(c -> c - .bottom() - .right() - .button( - Icon.discord, - new ImageButton.ImageButtonStyle(), - () -> { - if(!app.openURI(discordURL)) { - ui.showInfoFade("@linkfail"); - app.setClipboardText(discordURL); - } - } - ) - .marginTop(9f) - .marginLeft(10f) - .tooltip(bundle.get("setting.omaloon-discord-join")) - .size(84, 45) - .name("discord")); + .bottom() + .right() + .button( + Icon.discord, + new ImageButton.ImageButtonStyle(), + () -> { + if(!app.openURI(discordURL)){ + ui.showInfoFade("@linkfail"); + app.setClipboardText(discordURL); + } + } + ) + .marginTop(9f) + .marginLeft(10f) + .tooltip(bundle.get("setting.omaloon-discord-join")) + .size(84, 45) + .name("discord")); }); } - public static class TableSetting extends Setting { + public static class TableSetting extends Setting{ public Table t; - public TableSetting(String name, Table table) { + public TableSetting(String name, Table table){ super(name); t = table; } @Override - public void add(SettingsMenuDialog.SettingsTable table) { + public void add(SettingsMenuDialog.SettingsTable table){ addDesc(table.add(t).growX().get()); table.row(); } diff --git a/src/omaloon/core/SafeClearer.java b/src/omaloon/core/SafeClearer.java index 8096a40b..e09701ba 100644 --- a/src/omaloon/core/SafeClearer.java +++ b/src/omaloon/core/SafeClearer.java @@ -9,39 +9,39 @@ import mindustry.world.meta.*; import omaloon.content.*; -public class SafeClearer implements ApplicationListener { - public static final Seq invalidBuilds = new Seq<>(); +public class SafeClearer implements ApplicationListener{ + public static final Seq invalidBuilds = new Seq<>(); - public SafeClearer() { - if (Vars.platform instanceof ApplicationCore core) core.add(this); - } + public SafeClearer(){ + if(Vars.platform instanceof ApplicationCore core) core.add(this); + } - public boolean enabled() { - return Core.settings.getBool("omaloon-enable-soft-cleaner", true); - } + public boolean enabled(){ + return Core.settings.getBool("omaloon-enable-soft-cleaner", true); + } - @Override - public void update() { - if (enabled()) { - invalidBuilds.clear(); - if (Vars.state.isCampaign() && Vars.state.getPlanet().solarSystem == OlPlanets.omaloon) { - Block out = Vars.content.blocks().find(block -> { - boolean omaloonOnly = block.minfo.mod != null && block.minfo.mod.name.equals("omaloon"); - boolean sandboxOnly = block.buildVisibility == BuildVisibility.sandboxOnly || block.buildVisibility == BuildVisibility.editorOnly; - boolean empty = Vars.player.team().data().getBuildings(block).isEmpty(); + @Override + public void update(){ + if(enabled()){ + invalidBuilds.clear(); + if(Vars.state.isCampaign() && Vars.state.getPlanet().solarSystem == OlPlanets.omaloon){ + Block out = Vars.content.blocks().find(block -> { + boolean omaloonOnly = block.minfo.mod != null && block.minfo.mod.name.equals("omaloon"); + boolean sandboxOnly = block.buildVisibility == BuildVisibility.sandboxOnly || block.buildVisibility == BuildVisibility.editorOnly; + boolean empty = Vars.player.team().data().getBuildings(block).isEmpty(); - return !omaloonOnly && !sandboxOnly && !empty && !(block instanceof ConstructBlock); - }); - if (out != null) invalidBuilds.add(Vars.player.team().data().getBuildings(out)); - invalidBuilds.removeAll(b -> b instanceof ConstructBlock.ConstructBuild); - } + return !omaloonOnly && !sandboxOnly && !empty && !(block instanceof ConstructBlock); + }); + if(out != null) invalidBuilds.add(Vars.player.team().data().getBuildings(out)); + invalidBuilds.removeAll(b -> b instanceof ConstructBlock.ConstructBuild); + } - if (!invalidBuilds.isEmpty()) { - invalidBuilds.each(build -> { - OlFx.stealInvalid.at(build.x, build.y, 0, build.block); - build.tile.setAir(); - }); - } - } - } + if(!invalidBuilds.isEmpty()){ + invalidBuilds.each(build -> { + OlFx.stealInvalid.at(build.x, build.y, 0, build.block); + build.tile.setAir(); + }); + } + } + } } diff --git a/src/omaloon/entities/abilities/DroneAbility.java b/src/omaloon/entities/abilities/DroneAbility.java index d31b35aa..1fa89de3 100644 --- a/src/omaloon/entities/abilities/DroneAbility.java +++ b/src/omaloon/entities/abilities/DroneAbility.java @@ -22,7 +22,7 @@ import java.util.*; import java.util.function.*; -public class DroneAbility extends Ability { +public class DroneAbility extends Ability{ private Unit paramUnit; private DroneAbility paramAbility; private final Vec2 paramPos = new Vec2(); @@ -43,14 +43,15 @@ public class DroneAbility extends Ability { public Function droneController = DroneAI::new; @Override - public void init(UnitType type) { + public void init(UnitType type){ this.data = 0; } - public DroneAbility(){} + public DroneAbility(){ + } @Override - public void addStats(Table t) { + public void addStats(Table t){ t.add("[lightgray]" + Stat.productionTime.localized() + ": []" + Strings.autoFixed(spawnTime, 2)).row(); t.table(unit -> { Image icon = unit.image(droneUnit.fullIcon).get(); @@ -65,31 +66,31 @@ public void addStats(Table t) { } @Override - public Ability copy() { - DroneAbility ability = (DroneAbility) super.copy(); + public Ability copy(){ + DroneAbility ability = (DroneAbility)super.copy(); ability.drones = new ArrayList<>(); return ability; } @Override - public String localized() { + public String localized(){ return Core.bundle.get("ability." + name); } @Override - public void update(Unit unit) { + public void update(Unit unit){ paramUnit = unit; paramAbility = this; paramPos.set(spawnX, spawnY).rotate(unit.rotation - 90f).add(unit); timer += Time.delta * Vars.state.rules.unitBuildSpeed(unit.team()); - if (drones.isEmpty()) { - for (Unit u : Groups.unit) { - if (u.team() == unit.team() - && u.type == this.droneUnit - && u instanceof DroneUnit - && ((DroneUnit) u).owner == unit) { + if(drones.isEmpty()){ + for(Unit u : Groups.unit){ + if(u.team() == unit.team() + && u.type == this.droneUnit + && u instanceof DroneUnit + && ((DroneUnit)u).owner == unit){ drones.add(u); u.controller(droneController.apply(unit)); data++; @@ -99,7 +100,7 @@ public void update(Unit unit) { } drones.removeIf(u -> { - if (!u.isValid()) { + if(!u.isValid()){ data--; timer = 0; return true; @@ -107,41 +108,41 @@ public void update(Unit unit) { return false; }); - if (data < maxDroneCount) { - if (timer > spawnTime) { + if(data < maxDroneCount){ + if(timer > spawnTime){ spawnDrone(); timer = 0; } } } - protected void spawnDrone() { + protected void spawnDrone(){ spawnEffect.at(paramPos.x, paramPos.y, 0f, parentizeEffects ? paramUnit : null); Unit u = droneUnit.create(paramUnit.team()); u.set(paramPos.x, paramPos.y); u.rotation = paramUnit.rotation + rotation; - if (u instanceof DroneUnit drone) drone.owner(paramUnit); + if(u instanceof DroneUnit drone) drone.owner(paramUnit); drones.add(0, u); data++; - for(int i = 0; i < paramUnit.abilities.length; i++) { + for(int i = 0; i < paramUnit.abilities.length; i++){ Ability self = paramUnit.abilities[i]; - if (self == this && u instanceof Dronec drone) drone.abilityIndex(i); + if(self == this && u instanceof Dronec drone) drone.abilityIndex(i); } u.controller(droneController.apply(paramUnit)); updateAnchor(); Events.fire(new UnitCreateEvent(u, null, paramUnit)); - if (!Vars.net.client()) { + if(!Vars.net.client()){ u.add(); } } - public void updateAnchor() { - for (int i = 0; i < drones.size(); i++) { + public void updateAnchor(){ + for(int i = 0; i < drones.size(); i++){ Unit u = drones.get(i); - ((DroneAI) u.controller()).rally(anchorPos[i]); + ((DroneAI)u.controller()).rally(anchorPos[i]); } } diff --git a/src/omaloon/entities/abilities/HailShieldAbility.java b/src/omaloon/entities/abilities/HailShieldAbility.java index 65d05ace..1387c2cc 100644 --- a/src/omaloon/entities/abilities/HailShieldAbility.java +++ b/src/omaloon/entities/abilities/HailShieldAbility.java @@ -18,165 +18,165 @@ import java.util.concurrent.atomic.*; -import static mindustry.Vars.*; -import static omaloon.OmaloonMod.*; +import static mindustry.Vars.tilesize; +import static omaloon.OmaloonMod.shieldBuffer; /** * An ability for a shield covering the unit that protects from hail, but not enemy bullets. */ -public class HailShieldAbility extends Ability { - /** - * Position relative to unit. - */ - public float x, y; - - /** - * Shield radius, defaults to twice the unit's hitsize. - */ - public float radius = -1f; - - /** - * Shield regen amount per tick while active. - */ - public float regen = 0.1f; - /** - * Shield regen amount per tick while broken. - */ - public float regenBroken = 1f; - /** - * Maximum shield health. - */ - public float maxHealth = 100f; - - /** - * When true, effects and sounds will be played at the position of the shield instead of the bullet's position. - */ - public boolean parentizeEffect = true; - - /** - * Layer offset for ability. - */ - public float layerOffset = 0f; - - /** - * Effect displayed when something hits the shield. - */ - public Effect hitEffect = Fx.none; - /** - * Effect displayed when the shield is broken. - */ - public Effect breakEffect = Fx.none; - /** - * Effect displayed when the shield regenerates. - */ - public Effect regenEffect = Fx.none; - - /** - * Sound played when something hits the shield. - */ - public Sound hitSound = Sounds.none; - public float hitSoundVolume = 1; - - /** - * Color displayed in shield health bar. - */ - public Color barColor = Pal.heal; - - /** - * Color used in HitEffect; - */ - public Color hitColor = Color.white; - - /** Shield visibility timer. */ - protected float shieldVisibleTime = 0f; - - /** Duration the shield remains visible after being hit. */ - public float shieldVisibleDuration = 10f; - - - protected float damage; - protected boolean broken; - - @Override - public void addStats(Table t) { - t.add("[lightgray]" + Stat.health.localized() + ": [white]" + Math.round(maxHealth)).row(); - t.add("[lightgray]" + Stat.range.localized() + ": [white]" + Strings.autoFixed(radius / tilesize, 2) + " " + StatUnit.blocks.localized()).row(); - t.add("[lightgray]" + Stat.repairSpeed.localized() + ": [white]" + Strings.autoFixed(regen * 60f, 2) + StatUnit.perSecond.localized()).row(); - t.add("[lightgray]" + Stat.cooldownTime.localized() + ": [white]" + Strings.autoFixed(maxHealth/regenBroken/60f, 2) + " " + StatUnit.seconds.localized()).row(); - } - - @Override - public void displayBars(Unit unit, Table bars) { - bars.add(new Bar("bar.hail-shield-health", barColor, () -> 1f - (damage/maxHealth)).blink(Color.white)); - } - - @Override - public void init(UnitType type) { - if (radius == -1) radius = type.hitSize * 1.3f; - } - - @Override - public void draw(Unit unit) { - if (broken) return; - - float alpha = Mathf.clamp(shieldVisibleTime / shieldVisibleDuration); - - if (alpha > 0.001f) { - Fill.light(unit.x + x, unit.y + y, Lines.circleVertices(radius), radius, - Color.clear, - Tmp.c2.set(Pal.heal).lerp(Color.white, Mathf.clamp(unit.hitTime() / 2f)).a(0.7f * alpha) - ); - } - } - - @Override - public void update(Unit unit) { - float dx = unit.x + x, - dy = unit.y + y; - - if (broken) { - if (damage > 0) { - damage -= Time.delta * regenBroken; - } else { - broken = false; - regenEffect.at(dx, dy); - } - } else { - if (damage > 0) damage -= Time.delta * regen; - - AtomicBoolean wasHit = new AtomicBoolean(false); - Groups.bullet.intersect( - unit.x + x - radius - shieldBuffer, - unit.y + y - radius - shieldBuffer, - (radius + shieldBuffer) * 2f, - (radius + shieldBuffer) * 2f, - b -> { - if (b.team == Team.derelict) { - if (Mathf.dst(unit.x + x, unit.y + y, b.x, b.y) <= radius + b.type.splashDamageRadius) { - b.absorb(); - if (parentizeEffect) { - hitEffect.at(dx, dy, b.hitSize, hitColor); - hitSound.at(dx, dy, Mathf.random(0.9f, 1.1f), hitSoundVolume); - } else { - hitEffect.at(b.x, b.y, b.hitSize, hitColor); - hitSound.at(b.x, b.y, Mathf.random(0.9f, 1.1f), hitSoundVolume); - } - damage += b.damage; - wasHit.set(true); - if (damage > maxHealth) { - broken = true; - breakEffect.at(dx, dy, b.hitSize, unit); - } - } - } - } - ); - - if (wasHit.get()) { - shieldVisibleTime = shieldVisibleDuration; - } else { - shieldVisibleTime = Math.max(0f, shieldVisibleTime - Time.delta); - } - } - } +public class HailShieldAbility extends Ability{ + /** + * Position relative to unit. + */ + public float x, y; + + /** + * Shield radius, defaults to twice the unit's hitsize. + */ + public float radius = -1f; + + /** + * Shield regen amount per tick while active. + */ + public float regen = 0.1f; + /** + * Shield regen amount per tick while broken. + */ + public float regenBroken = 1f; + /** + * Maximum shield health. + */ + public float maxHealth = 100f; + + /** + * When true, effects and sounds will be played at the position of the shield instead of the bullet's position. + */ + public boolean parentizeEffect = true; + + /** + * Layer offset for ability. + */ + public float layerOffset = 0f; + + /** + * Effect displayed when something hits the shield. + */ + public Effect hitEffect = Fx.none; + /** + * Effect displayed when the shield is broken. + */ + public Effect breakEffect = Fx.none; + /** + * Effect displayed when the shield regenerates. + */ + public Effect regenEffect = Fx.none; + + /** + * Sound played when something hits the shield. + */ + public Sound hitSound = Sounds.none; + public float hitSoundVolume = 1; + + /** + * Color displayed in shield health bar. + */ + public Color barColor = Pal.heal; + + /** + * Color used in HitEffect; + */ + public Color hitColor = Color.white; + + /** Shield visibility timer. */ + protected float shieldVisibleTime = 0f; + + /** Duration the shield remains visible after being hit. */ + public float shieldVisibleDuration = 10f; + + + protected float damage; + protected boolean broken; + + @Override + public void addStats(Table t){ + t.add("[lightgray]" + Stat.health.localized() + ": [white]" + Math.round(maxHealth)).row(); + t.add("[lightgray]" + Stat.range.localized() + ": [white]" + Strings.autoFixed(radius / tilesize, 2) + " " + StatUnit.blocks.localized()).row(); + t.add("[lightgray]" + Stat.repairSpeed.localized() + ": [white]" + Strings.autoFixed(regen * 60f, 2) + StatUnit.perSecond.localized()).row(); + t.add("[lightgray]" + Stat.cooldownTime.localized() + ": [white]" + Strings.autoFixed(maxHealth / regenBroken / 60f, 2) + " " + StatUnit.seconds.localized()).row(); + } + + @Override + public void displayBars(Unit unit, Table bars){ + bars.add(new Bar("bar.hail-shield-health", barColor, () -> 1f - (damage / maxHealth)).blink(Color.white)); + } + + @Override + public void init(UnitType type){ + if(radius == -1) radius = type.hitSize * 1.3f; + } + + @Override + public void draw(Unit unit){ + if(broken) return; + + float alpha = Mathf.clamp(shieldVisibleTime / shieldVisibleDuration); + + if(alpha > 0.001f){ + Fill.light(unit.x + x, unit.y + y, Lines.circleVertices(radius), radius, + Color.clear, + Tmp.c2.set(Pal.heal).lerp(Color.white, Mathf.clamp(unit.hitTime() / 2f)).a(0.7f * alpha) + ); + } + } + + @Override + public void update(Unit unit){ + float dx = unit.x + x, + dy = unit.y + y; + + if(broken){ + if(damage > 0){ + damage -= Time.delta * regenBroken; + }else{ + broken = false; + regenEffect.at(dx, dy); + } + }else{ + if(damage > 0) damage -= Time.delta * regen; + + AtomicBoolean wasHit = new AtomicBoolean(false); + Groups.bullet.intersect( + unit.x + x - radius - shieldBuffer, + unit.y + y - radius - shieldBuffer, + (radius + shieldBuffer) * 2f, + (radius + shieldBuffer) * 2f, + b -> { + if(b.team == Team.derelict){ + if(Mathf.dst(unit.x + x, unit.y + y, b.x, b.y) <= radius + b.type.splashDamageRadius){ + b.absorb(); + if(parentizeEffect){ + hitEffect.at(dx, dy, b.hitSize, hitColor); + hitSound.at(dx, dy, Mathf.random(0.9f, 1.1f), hitSoundVolume); + }else{ + hitEffect.at(b.x, b.y, b.hitSize, hitColor); + hitSound.at(b.x, b.y, Mathf.random(0.9f, 1.1f), hitSoundVolume); + } + damage += b.damage; + wasHit.set(true); + if(damage > maxHealth){ + broken = true; + breakEffect.at(dx, dy, b.hitSize, unit); + } + } + } + } + ); + + if(wasHit.get()){ + shieldVisibleTime = shieldVisibleDuration; + }else{ + shieldVisibleTime = Math.max(0f, shieldVisibleTime - Time.delta); + } + } + } } diff --git a/src/omaloon/entities/abilities/JavelinAbility.java b/src/omaloon/entities/abilities/JavelinAbility.java index 5a22262d..1b820aa1 100644 --- a/src/omaloon/entities/abilities/JavelinAbility.java +++ b/src/omaloon/entities/abilities/JavelinAbility.java @@ -16,158 +16,159 @@ import mindustry.world.meta.*; import omaloon.world.meta.*; -import static mindustry.Vars.*; - -public class JavelinAbility extends Ability { - public String suffix = ""; - public String name; - - /** - * Base damaged applied when this ability is active. - */ - public float damage = 1; - /** - * Min damage that this ability will apply - */ - public float minDamage = 0f; - /** - * Time taken for the ability to apply the damage. In ticks. - */ - public float damageInterval = 5f; - /** - * Radius of ability. Set to unit's hitSize by default. - */ - public float radius = -1; - - public boolean targetAir = true, targetGround = true; - - /** - * Min speed that the abiility functions. - */ - public float minSpeed = 0.8f; - /** - * Max speed where it stops getting better. - */ - public float maxSpeed = 1.2f; - - /** - * Position offset relative to the unit. - */ - public float x, y; - - /** - * Layer offset relative to unit;. - */ - public float layerOffset = 0f; - - /** - * Position offset based on sine wave. Purely visual. - */ - public float sclX = 1, magX = 0; - public float sclY = 1, magY = 0; - public float sinOffset = Mathf.PI; - - /** - * Overlay region and effect tint. - */ - public Color color = Color.white; - /** - * Overaly blending mode; - */ - public Blending blending = Blending.additive; - /** - * When true, draws an overlay sprite on top of the unit. - */ - public boolean drawOverlay = true; - - /** - * Effect applied on every target that has been damaged by this ability. uses the unit's rotation. - */ - public Effect hitEffect = Fx.none; - - public TextureRegion overlayRegion; - - protected float timer; - protected final Seq targets = new Seq<>(); - - public JavelinAbility(float damage, float damageInterval, float radius) { - this.damage = damage; - this.damageInterval = damageInterval; - this.radius = radius; - - suffix = "-overlay"; - } - - public JavelinAbility() {} - - @Override - public void addStats(Table t) { - t.add( - "[lightgray]" + Stat.damage.localized() + ": [white]" + - Strings.autoFixed(60f * minDamage / damageInterval, 2) + " - " + - Strings.autoFixed(60f * damage / damageInterval, 2) + " " + StatUnit.perSecond.localized() - ).row(); - t.add("[lightgray]" + Stat.range.localized() + ": [white]" + Strings.autoFixed(radius/8f, 2) + " " + StatUnit.blocks.localized()).row(); - t.add("[lightgray]" + OlStats.minSpeed.localized() + ": [white]" + Strings.autoFixed(minSpeed/8f, 2) + " " + StatUnit.tilesSecond.localized()).row(); - t.add("[lightgray]" + OlStats.maxSpeed.localized() + ": [white]" + Strings.autoFixed(maxSpeed/8f, 2) + " " + StatUnit.tilesSecond.localized()).row(); - t.add("[lightgray]" + Stat.targetsAir.localized() + ": [white]" + Core.bundle.get(targetAir ? "yes" : "no")).row(); - t.add("[lightgray]" + Stat.targetsGround.localized() + ": [white]" + Core.bundle.get(targetGround ? "yes" : "no")).row(); - } - - @Override - public void draw(Unit unit) { - if (drawOverlay) { - float scl = Mathf.clamp(Mathf.map(unit.vel().len(), minSpeed, maxSpeed, 0f, 1f)); - - if (overlayRegion == null) overlayRegion = Core.atlas.find(name); - float - drawx = unit.x + x + Mathf.sin(Time.time + unit.id, sclX, magX), - drawy = unit.y + y + Mathf.sin(Time.time + sinOffset + unit.id, sclY, magY); - float z = Draw.z(); - Draw.z(z - layerOffset); - Draw.color(color); - Draw.alpha(scl); - Draw.blend(blending); - Draw.rect(overlayRegion, drawx, drawy, unit.rotation - 90f); - Draw.blend(); - Draw.z(z); - } - } - - @Override - public void init(UnitType type) { - if (name == null) name = type.name + suffix; - if (radius == -1) radius = type.hitSize; - } - - @Override - public void update(Unit unit) { - float scl = Mathf.clamp(Mathf.map(unit.vel().len(), minSpeed, maxSpeed, 0f, 1f)); - if (scl <= 0) return; - if (timer >= damageInterval) { - float ax = unit.x + x, ay = unit.y + y; - targets.clear(); - Units.nearby(null, ax, ay, radius, other -> { - if(other != unit && other.checkTarget(targetAir, targetGround) && other.targetable(unit.team) && (other.team != unit.team)) { - targets.add(other); - } - }); - if(targetGround) { - Units.nearbyBuildings(ax, ay, radius, b -> { - if((b.team != Team.derelict || state.rules.coreCapture) && (b.team != unit.team)) { - targets.add(b); - } - }); - } - float dmg = Math.max(minDamage, damage * scl * state.rules.unitDamage(unit.team)); - targets.each(other -> { - if(other instanceof Building b) { - b.damage(unit.team, dmg); - } else other.damage(dmg); - hitEffect.at(other.x(), other.y(), unit.rotation - 90f, color); - }); - timer %= 1f; - } - timer += Time.delta; - } +import static mindustry.Vars.state; + +public class JavelinAbility extends Ability{ + public String suffix = ""; + public String name; + + /** + * Base damaged applied when this ability is active. + */ + public float damage = 1; + /** + * Min damage that this ability will apply + */ + public float minDamage = 0f; + /** + * Time taken for the ability to apply the damage. In ticks. + */ + public float damageInterval = 5f; + /** + * Radius of ability. Set to unit's hitSize by default. + */ + public float radius = -1; + + public boolean targetAir = true, targetGround = true; + + /** + * Min speed that the abiility functions. + */ + public float minSpeed = 0.8f; + /** + * Max speed where it stops getting better. + */ + public float maxSpeed = 1.2f; + + /** + * Position offset relative to the unit. + */ + public float x, y; + + /** + * Layer offset relative to unit;. + */ + public float layerOffset = 0f; + + /** + * Position offset based on sine wave. Purely visual. + */ + public float sclX = 1, magX = 0; + public float sclY = 1, magY = 0; + public float sinOffset = Mathf.PI; + + /** + * Overlay region and effect tint. + */ + public Color color = Color.white; + /** + * Overaly blending mode; + */ + public Blending blending = Blending.additive; + /** + * When true, draws an overlay sprite on top of the unit. + */ + public boolean drawOverlay = true; + + /** + * Effect applied on every target that has been damaged by this ability. uses the unit's rotation. + */ + public Effect hitEffect = Fx.none; + + public TextureRegion overlayRegion; + + protected float timer; + protected final Seq targets = new Seq<>(); + + public JavelinAbility(float damage, float damageInterval, float radius){ + this.damage = damage; + this.damageInterval = damageInterval; + this.radius = radius; + + suffix = "-overlay"; + } + + public JavelinAbility(){ + } + + @Override + public void addStats(Table t){ + t.add( + "[lightgray]" + Stat.damage.localized() + ": [white]" + + Strings.autoFixed(60f * minDamage / damageInterval, 2) + " - " + + Strings.autoFixed(60f * damage / damageInterval, 2) + " " + StatUnit.perSecond.localized() + ).row(); + t.add("[lightgray]" + Stat.range.localized() + ": [white]" + Strings.autoFixed(radius / 8f, 2) + " " + StatUnit.blocks.localized()).row(); + t.add("[lightgray]" + OlStats.minSpeed.localized() + ": [white]" + Strings.autoFixed(minSpeed / 8f, 2) + " " + StatUnit.tilesSecond.localized()).row(); + t.add("[lightgray]" + OlStats.maxSpeed.localized() + ": [white]" + Strings.autoFixed(maxSpeed / 8f, 2) + " " + StatUnit.tilesSecond.localized()).row(); + t.add("[lightgray]" + Stat.targetsAir.localized() + ": [white]" + Core.bundle.get(targetAir ? "yes" : "no")).row(); + t.add("[lightgray]" + Stat.targetsGround.localized() + ": [white]" + Core.bundle.get(targetGround ? "yes" : "no")).row(); + } + + @Override + public void draw(Unit unit){ + if(drawOverlay){ + float scl = Mathf.clamp(Mathf.map(unit.vel().len(), minSpeed, maxSpeed, 0f, 1f)); + + if(overlayRegion == null) overlayRegion = Core.atlas.find(name); + float + drawx = unit.x + x + Mathf.sin(Time.time + unit.id, sclX, magX), + drawy = unit.y + y + Mathf.sin(Time.time + sinOffset + unit.id, sclY, magY); + float z = Draw.z(); + Draw.z(z - layerOffset); + Draw.color(color); + Draw.alpha(scl); + Draw.blend(blending); + Draw.rect(overlayRegion, drawx, drawy, unit.rotation - 90f); + Draw.blend(); + Draw.z(z); + } + } + + @Override + public void init(UnitType type){ + if(name == null) name = type.name + suffix; + if(radius == -1) radius = type.hitSize; + } + + @Override + public void update(Unit unit){ + float scl = Mathf.clamp(Mathf.map(unit.vel().len(), minSpeed, maxSpeed, 0f, 1f)); + if(scl <= 0) return; + if(timer >= damageInterval){ + float ax = unit.x + x, ay = unit.y + y; + targets.clear(); + Units.nearby(null, ax, ay, radius, other -> { + if(other != unit && other.checkTarget(targetAir, targetGround) && other.targetable(unit.team) && (other.team != unit.team)){ + targets.add(other); + } + }); + if(targetGround){ + Units.nearbyBuildings(ax, ay, radius, b -> { + if((b.team != Team.derelict || state.rules.coreCapture) && (b.team != unit.team)){ + targets.add(b); + } + }); + } + float dmg = Math.max(minDamage, damage * scl * state.rules.unitDamage(unit.team)); + targets.each(other -> { + if(other instanceof Building b){ + b.damage(unit.team, dmg); + }else other.damage(dmg); + hitEffect.at(other.x(), other.y(), unit.rotation - 90f, color); + }); + timer %= 1f; + } + timer += Time.delta; + } } diff --git a/src/omaloon/entities/bullet/FallingBulletType.java b/src/omaloon/entities/bullet/FallingBulletType.java index e8a76fb7..32f35f7c 100644 --- a/src/omaloon/entities/bullet/FallingBulletType.java +++ b/src/omaloon/entities/bullet/FallingBulletType.java @@ -13,9 +13,9 @@ import mindustry.graphics.*; import omaloon.math.*; -import static mindustry.Vars.*; +import static mindustry.Vars.headless; -public class FallingBulletType extends BulletType { +public class FallingBulletType extends BulletType{ public float fallTime = 50f; public float fallSpread = 60; public String sprite; @@ -41,7 +41,7 @@ public FallingBulletType(String sprite){ } @Override - public void load() { + public void load(){ super.load(); region = Core.atlas.find(sprite); @@ -51,7 +51,7 @@ public void load() { public void init(Bullet b){ super.init(b); - if (immovable) { + if(immovable){ Tmp.v2.trns(b.rotation(), b.lifetime() * speed); b.set(b.x + Tmp.v2.x, b.y + Tmp.v2.y); @@ -68,7 +68,7 @@ public void draw(Bullet b){ public void drawFalling(Bullet b, TextureRegion region, Color col){ float rot = getRotTrajectory(b); - float sclFall = 1f + getElevation(b)/4; + float sclFall = 1f + getElevation(b) / 4; float sclShadow = 0.1f + b.fin(); Vec2 pos = getTrajectory(b); @@ -88,7 +88,7 @@ public void drawFalling(Bullet b, TextureRegion region, Color col){ @Override - public void drawLight(Bullet b) { + public void drawLight(Bullet b){ if(lightOpacity <= 0f || lightRadius <= 0f) return; Drawf.light(getTrajectory(b), (1 + b.fout()) * lightRadius, lightColor, lightOpacity); } @@ -100,20 +100,20 @@ public void update(Bullet b){ } public void updateFalling(Bullet b){ - if (canCollideFalling && isLanding(b)){ + if(canCollideFalling && isLanding(b)){ Teamc target = Units.closestTarget(b.team, b.x, b.y, fallingRadius, - e -> e.checkTarget(true, false) && e.team != b.team && !b.hasCollided(e.id) //ONLY AIR UNITS + e -> e.checkTarget(true, false) && e.team != b.team && !b.hasCollided(e.id) //ONLY AIR UNITS ); Vec2 pos = getTrajectory(b); - if (target != null && pos.dst(target.x(), target.y()) < minDistanceFallingCollide){ + if(target != null && pos.dst(target.x(), target.y()) < minDistanceFallingCollide){ hitFalling(b); - if (pierce) { + if(pierce){ b.collided.add(target.id()); - }else { + }else{ b.remove(); } } @@ -121,7 +121,7 @@ public void updateFalling(Bullet b){ } @Override - public void updateTrail(Bullet b) { + public void updateTrail(Bullet b){ if(!headless && trailLength > 0){ if(b.trail == null){ b.trail = new Trail(trailLength); @@ -160,7 +160,7 @@ public void hitFalling(Bullet b, float x, float y){ Effect.shake(hitShake, hitShake, b); - if (b.absorbed) return; + if(b.absorbed) return; Damage.damage(b.team, x, y, fallingRadius, fallingDamage * b.damageMultiplier(), splashDamagePierce, true, fallingHitCollideGround, scaledSplashDamage, b); if(status != StatusEffects.none){ @@ -179,7 +179,7 @@ public Vec2 getTrajectory(Bullet b){ } public Vec2 getOffsetTrajectory(Bullet b){ - return Tmp.v2.trns(90 + (Mathf.randomSeed(b.id + 1) - 0.5f) * fallSpread/2, fallTime); + return Tmp.v2.trns(90 + (Mathf.randomSeed(b.id + 1) - 0.5f) * fallSpread / 2, fallTime); } public float getRotTrajectory(Bullet b){ @@ -190,5 +190,7 @@ public float getElevation(Bullet b){ return b.fout() * fallTime / 10; } - public boolean isLanding(Bullet b) {return b.fin() > 0.75; } + public boolean isLanding(Bullet b){ + return b.fin() > 0.75; + } } diff --git a/src/omaloon/entities/bullet/HailStoneBulletType.java b/src/omaloon/entities/bullet/HailStoneBulletType.java index d3a138d6..fabb28cf 100644 --- a/src/omaloon/entities/bullet/HailStoneBulletType.java +++ b/src/omaloon/entities/bullet/HailStoneBulletType.java @@ -9,9 +9,10 @@ import mindustry.graphics.*; /* IS JUST POR HAILSTONE WEATHER */ -public class HailStoneBulletType extends FallingBulletType { +public class HailStoneBulletType extends FallingBulletType{ public TextureRegion[] variantsRegion; public int variants; + public HailStoneBulletType(String sprite, int variants){ super(sprite); this.variants = variants; @@ -20,16 +21,16 @@ public HailStoneBulletType(String sprite, int variants){ } @Override - public void init(Bullet b) { + public void init(Bullet b){ super.init(b); b.data = new HailStoneData(getRegion(b), fallTime); } @Override - public void load() { + public void load(){ variantsRegion = new TextureRegion[variants]; - for (int i = 0; i < variants; i++) { + for(int i = 0; i < variants; i++){ variantsRegion[i] = Core.atlas.find(sprite + "-" + i); } } @@ -39,7 +40,7 @@ public void draw(Bullet b){ Draw.alpha(255); drawTrail(b); - if (b.data instanceof HailStoneData data){ + if(b.data instanceof HailStoneData data){ drawFalling(b, data.region, regionColor); } } @@ -56,8 +57,8 @@ public void despawned(Bullet b){ createFrags(b, b.x, b.y); } - if (!b.absorbed) despawnEffect.at(b.x, b.y, b.rotation(), hitColor, b.data); - if (!b.absorbed) despawnSound.at(b); + if(!b.absorbed) despawnEffect.at(b.x, b.y, b.rotation(), hitColor, b.data); + if(!b.absorbed) despawnSound.at(b); Effect.shake(despawnShake, despawnShake, b); } @@ -67,9 +68,9 @@ public TextureRegion getRegion(Bullet b){ } @Override - public void hit(Bullet b, float x, float y) { - if (!b.absorbed) hitEffect.at(x, y, b.rotation(), hitColor); - if (!b.absorbed) hitSound.at(x, y, hitSoundPitch, hitSoundVolume); + public void hit(Bullet b, float x, float y){ + if(!b.absorbed) hitEffect.at(x, y, b.rotation(), hitColor); + if(!b.absorbed) hitSound.at(x, y, hitSoundPitch, hitSoundVolume); Effect.shake(hitShake, hitShake, b); @@ -88,7 +89,7 @@ public void hit(Bullet b, float x, float y) { createSplashDamage(b, x, y); for(int i = 0; i < lightning; i++){ - Lightning.create(b, lightningColor, lightningDamage < 0 ? damage : lightningDamage, b.x, b.y, b.rotation() + Mathf.range(lightningCone/2) + lightningAngle, lightningLength + Mathf.random(lightningLengthRand)); + Lightning.create(b, lightningColor, lightningDamage < 0 ? damage : lightningDamage, b.x, b.y, b.rotation() + Mathf.range(lightningCone / 2) + lightningAngle, lightningLength + Mathf.random(lightningLengthRand)); } } diff --git a/src/omaloon/entities/bullet/LaunchBulletType.java b/src/omaloon/entities/bullet/LaunchBulletType.java index 0260a302..2884dbc2 100644 --- a/src/omaloon/entities/bullet/LaunchBulletType.java +++ b/src/omaloon/entities/bullet/LaunchBulletType.java @@ -14,166 +14,166 @@ import mindustry.gen.*; import mindustry.graphics.*; -import static arc.Core.*; +import static arc.Core.graphics; /** * Bullet type that is launched into the sky, frags and then spawns the frags later on. Needs to not collide to work properly. * It doesn't abide by regular frag behaviour so most old frag fields are unused. */ -public class LaunchBulletType extends BasicBulletType { - /** - * Percentage of bullet's lifetime where the main bullet will be rendered. - */ - public float fadeAt = 0.25f; - /** - * Percentage of bullet's distance from origin to end where frag bullets will spawn. - */ - public float fragAt = 0.75f; - /** - * Radius for calculating possible final frag positions. - */ - public float fragRadius = 24f; - /** - * Interpolation curve of the bullet's shadow. - */ - public Interp shadowInterp = Interp.linear; - /** - * Interpolation curve of frag bullets' shadows. - */ - public Interp fragInterp = Interp.linear; - /** - * Pitch inclination, should be between 0 and 1 otherwise it becomes way too distorted. - */ - public float pitch = 1f; +public class LaunchBulletType extends BasicBulletType{ + /** + * Percentage of bullet's lifetime where the main bullet will be rendered. + */ + public float fadeAt = 0.25f; + /** + * Percentage of bullet's distance from origin to end where frag bullets will spawn. + */ + public float fragAt = 0.75f; + /** + * Radius for calculating possible final frag positions. + */ + public float fragRadius = 24f; + /** + * Interpolation curve of the bullet's shadow. + */ + public Interp shadowInterp = Interp.linear; + /** + * Interpolation curve of frag bullets' shadows. + */ + public Interp fragInterp = Interp.linear; + /** + * Pitch inclination, should be between 0 and 1 otherwise it becomes way too distorted. + */ + public float pitch = 1f; - public static final FrameBuffer - drawBuffer = new FrameBuffer(), - shadowBuffer = new FrameBuffer(); - public static final Seq shadowRuns = new Seq<>(); - public static boolean shouldResize; + public static final FrameBuffer + drawBuffer = new FrameBuffer(), + shadowBuffer = new FrameBuffer(); + public static final Seq shadowRuns = new Seq<>(); + public static boolean shouldResize; - public static final Quat quat = new Quat(); - public static final Mat3D mat = new Mat3D(); + public static final Quat quat = new Quat(); + public static final Mat3D mat = new Mat3D(); - static { - Events.run(EventType.Trigger.draw, () -> { - if(!shadowRuns.isEmpty()) { - shadowBuffer.resize(graphics.getWidth(), graphics.getHeight()); - Seq buffer = shadowRuns.copy(); - shadowRuns.clear(); - Draw.draw(Layer.bullet - 1f, () -> { - Draw.flush(); - shadowBuffer.begin(Color.clear); - buffer.each(Runnable::run); - shadowBuffer.end(); - Draw.color(Pal.shadow, Pal.shadow.a); - EDraw.drawBuffer(shadowBuffer); - Draw.flush(); - Draw.color(); - }); - } - if(shouldResize) { - drawBuffer.resize(graphics.getWidth(), graphics.getHeight()); - shouldResize = false; - } - }); - } + static{ + Events.run(EventType.Trigger.draw, () -> { + if(!shadowRuns.isEmpty()){ + shadowBuffer.resize(graphics.getWidth(), graphics.getHeight()); + Seq buffer = shadowRuns.copy(); + shadowRuns.clear(); + Draw.draw(Layer.bullet - 1f, () -> { + Draw.flush(); + shadowBuffer.begin(Color.clear); + buffer.each(Runnable::run); + shadowBuffer.end(); + Draw.color(Pal.shadow, Pal.shadow.a); + EDraw.drawBuffer(shadowBuffer); + Draw.flush(); + Draw.color(); + }); + } + if(shouldResize){ + drawBuffer.resize(graphics.getWidth(), graphics.getHeight()); + shouldResize = false; + } + }); + } - public LaunchBulletType(float speed, float damage) { - super(speed, damage); - collides = collidesAir = collidesGround = false; - absorbable = false; - scaleLife = true; - } + public LaunchBulletType(float speed, float damage){ + super(speed, damage); + collides = collidesAir = collidesGround = false; + absorbable = false; + scaleLife = true; + } - @Override - public void createFrags(Bullet b, float x, float y) { - if(fragBullet != null) { - Angles.randLenVectors(b.id, fragBullets, fragRadius, (ox, oy) -> fragBullet.create( - b, - Mathf.lerp(b.originX, x + ox, fragAt), - Mathf.lerp(b.originY, y + oy, fragAt), - Angles.angle(b.originX, b.originY, x + ox, y + oy), - 1f, - b.lifetime/lifetime - )); - } - } + @Override + public void createFrags(Bullet b, float x, float y){ + if(fragBullet != null){ + Angles.randLenVectors(b.id, fragBullets, fragRadius, (ox, oy) -> fragBullet.create( + b, + Mathf.lerp(b.originX, x + ox, fragAt), + Mathf.lerp(b.originY, y + oy, fragAt), + Angles.angle(b.originX, b.originY, x + ox, y + oy), + 1f, + b.lifetime / lifetime + )); + } + } - @Override - public void draw(Bullet b) { - drawShadow(b); - drawTrail(b); - drawParts(b); + @Override + public void draw(Bullet b){ + drawShadow(b); + drawTrail(b); + drawParts(b); - if (b.fin() <= fadeAt) { - shouldResize = true; - float currentPitch = b.fin()/fadeAt; + if(b.fin() <= fadeAt){ + shouldResize = true; + float currentPitch = b.fin() / fadeAt; - mat.set(quat.set( - Angles.trnsx(b.rotation(), shrinkInterp.apply(currentPitch) * pitch), - Angles.trnsy(b.rotation(), shrinkInterp.apply(currentPitch) * pitch), - 1f, 0f - )); + mat.set(quat.set( + Angles.trnsx(b.rotation(), shrinkInterp.apply(currentPitch) * pitch), + Angles.trnsy(b.rotation(), shrinkInterp.apply(currentPitch) * pitch), + 1f, 0f + )); - drawBuffer.begin(Color.clear); - for(int i = 4; i >= 0; i--) { - if (backRegion.found()) { - Draw3d.rect( - mat, backRegion, - b.x - width/2f + Angles.trnsx(b.rotation(), currentPitch/4f * i), - b.y - height/2f + Angles.trnsy(b.rotation(), currentPitch/4f * i), - width, height, b.rotation() - ); - } - } - for(int i = 4; i >= 0; i--) { - Draw3d.rect( - mat, frontRegion, - b.x - width/2f + Angles.trnsx(b.rotation(), currentPitch/4f * i), - b.y - height/2f + Angles.trnsy(b.rotation(), currentPitch/4f * i), - width, height, b.rotation() + 90 - ); - } - drawBuffer.end(); + drawBuffer.begin(Color.clear); + for(int i = 4; i >= 0; i--){ + if(backRegion.found()){ + Draw3d.rect( + mat, backRegion, + b.x - width / 2f + Angles.trnsx(b.rotation(), currentPitch / 4f * i), + b.y - height / 2f + Angles.trnsy(b.rotation(), currentPitch / 4f * i), + width, height, b.rotation() + ); + } + } + for(int i = 4; i >= 0; i--){ + Draw3d.rect( + mat, frontRegion, + b.x - width / 2f + Angles.trnsx(b.rotation(), currentPitch / 4f * i), + b.y - height / 2f + Angles.trnsy(b.rotation(), currentPitch / 4f * i), + width, height, b.rotation() + 90 + ); + } + drawBuffer.end(); - Draw.draw(Layer.bullet - 0.1f, () -> { - Draw.color(Color.white); - Draw.alpha(1f - b.fin() / fadeAt); - EDraw.drawBuffer(drawBuffer); - }); - } - } + Draw.draw(Layer.bullet - 0.1f, () -> { + Draw.color(Color.white); + Draw.alpha(1f - b.fin() / fadeAt); + EDraw.drawBuffer(drawBuffer); + }); + } + } - public void drawShadow(Bullet b) { - if (b.fin() <= 0.5f) { - shadowRuns.add(() -> Fill.circle( - Mathf.lerp(b.x, b.originX, shadowInterp.apply(Mathf.clamp(b.fin() * 2f))), - Mathf.lerp(b.y, b.originY, shadowInterp.apply(Mathf.clamp(b.fin() * 2f))), - hitSize - )); - } else { - if (fragBullet != null) { - shadowRuns.add(() -> Angles.randLenVectors(b.id, fragBullets, fragRadius, (x, y) -> { - float endX = b.x + Tmp.v1.set(b.vel).scl(b.lifetime - b.time).x + x; - float endY = b.y + Tmp.v1.set(b.vel).scl(b.lifetime - b.time).y + y; - Fill.circle( - Mathf.lerp(b.originX, endX, fragInterp.apply(Mathf.clamp(b.fin() * 2f - 1f)) * fragAt), - Mathf.lerp(b.originY, endY, fragInterp.apply(Mathf.clamp(b.fin() * 2f - 1f)) * fragAt), - fragBullet.hitSize - ); - })); - } - } - } + public void drawShadow(Bullet b){ + if(b.fin() <= 0.5f){ + shadowRuns.add(() -> Fill.circle( + Mathf.lerp(b.x, b.originX, shadowInterp.apply(Mathf.clamp(b.fin() * 2f))), + Mathf.lerp(b.y, b.originY, shadowInterp.apply(Mathf.clamp(b.fin() * 2f))), + hitSize + )); + }else{ + if(fragBullet != null){ + shadowRuns.add(() -> Angles.randLenVectors(b.id, fragBullets, fragRadius, (x, y) -> { + float endX = b.x + Tmp.v1.set(b.vel).scl(b.lifetime - b.time).x + x; + float endY = b.y + Tmp.v1.set(b.vel).scl(b.lifetime - b.time).y + y; + Fill.circle( + Mathf.lerp(b.originX, endX, fragInterp.apply(Mathf.clamp(b.fin() * 2f - 1f)) * fragAt), + Mathf.lerp(b.originY, endY, fragInterp.apply(Mathf.clamp(b.fin() * 2f - 1f)) * fragAt), + fragBullet.hitSize + ); + })); + } + } + } - @Override - public void drawTrail(Bullet b) { - if(trailLength > 0 && b.trail != null && b.fin() <= fadeAt){ - float z = Draw.z(); - Draw.z(z - 0.0001f); - b.trail.draw(trailColor, trailWidth * (1f - b.fin()/fadeAt)); - Draw.z(z); - } - } + @Override + public void drawTrail(Bullet b){ + if(trailLength > 0 && b.trail != null && b.fin() <= fadeAt){ + float z = Draw.z(); + Draw.z(z - 0.0001f); + b.trail.draw(trailColor, trailWidth * (1f - b.fin() / fadeAt)); + Draw.z(z); + } + } } diff --git a/src/omaloon/entities/comp/ChainedComp.java b/src/omaloon/entities/comp/ChainedComp.java index 868a1e35..52482ddf 100644 --- a/src/omaloon/entities/comp/ChainedComp.java +++ b/src/omaloon/entities/comp/ChainedComp.java @@ -11,337 +11,343 @@ import mindustry.game.*; import mindustry.gen.*; import mindustry.type.*; -import omaloon.gen.*; import omaloon.type.*; import omaloon.utils.*; @SuppressWarnings({"unused", "unchecked", "RedundantVariable", "UnnecessaryReturnStatement"}) @EntityComponent -abstract class ChainedComp implements Unitc { - transient Unit head, tail, parent, child; - - transient float growTime = 0, chainTime = 0; - - // internal values that i wish i had the entityanno knowledge to not make it generate io - private int parentID = -1, childID = -1; - boolean grown; - - @Import UnitType type; - @Import UnitController controller; - @Import Team team; - @Import float x, y, rotation; - @Import WeaponMount[] mounts; - - /** - * Add first segments if this unit is not grown. - */ - @Override - public void add() { - head = tail = self(); - - if (!grown) { - for(int i = 0; i < checkType(type).minSegments - 1; i++) { - grow(); - } - // i need this because again, i don't know how to not genio. - grown = true; - } - } - - @Override - public void aim(float x, float y) { - if (isHead()) { - final float finalX = x, finalY = y; - consBackwards(u -> { - if (!u.isHead()) u.aim(finalX, finalY); - }); - } - } - - /** - * Multiplies the unit cap to fit the amount of biggest sized chains. If it overflows, then just pick the regular unit cap. - */ - @Override - @Replace - public int cap() { - MillipedeUnitType uType = checkType(type); - return Math.max(Units.getCap(team) * Math.max(uType.segmentLength, uType.maxSegments), Units.getCap(team)); - } - - /** - * Wrong cast errors are way too long. So long in fact that the crash box is too small for it. - */ - public MillipedeUnitType checkType(UnitType def) { - if (!(def instanceof MillipedeUnitType)) throw new RuntimeException("Unit's type must be MillipedeUnitType"); - return (MillipedeUnitType) def; - } - - /** - * Connects this centipede with another one. - *
  • - * If this unit is not the chain unit's tail, it'll call this method on the tail unit. - *
  • - *
  • - * If Parameter "to" is not the chain unit's head, "to" will become its head() method. - *
  • - */ - public void connect(Unit to) { - Chainedc cast = ((Chainedc) to).head().as(); - if (isTail()) { - cast.parent(self()); - child = to; - - ((Chainedc) head).consBackwards(u -> { - u.head(head); - u.tail(cast.tail()); - }); - - ((Chainedc) head).consBackwards(u -> { - u.setupWeapons(u.type); - if (!(u.controller() instanceof Player)) u.resetController(); - }); - } else ((Chainedc) tail).connect(to); - } - - /** - * @param cons will run through this unit and it's children recursively. - */ - public void consBackwards(Cons cons){ - T current = as(); - cons.get(current); - while(current.child() != null){ - cons.get(current.child().as()); - current = current.child().as(); - } - } - - /** - * @param cons will run through this unit and it's parents recursively. - */ - public void consForward(Cons cons){ - T current = as(); - cons.get(current); - while(current.parent() != null) { - cons.get(current.parent().as()); - current = current.parent().as(); - } - } - - /** - * Force a specific controller on certain parts of the chain. - */ - @MethodPriority(-1) - @Override - @BreakAll - public void controller(UnitController next){ - if (!isHead()) { - if(next instanceof Player){ - head.controller(next); - return; - } - - controller = new AIController(); - if (controller.unit() != self()) controller.unit(self()); - return; - } - } - - @Override - public void controlWeapons(boolean rotate, boolean shoot) { - if (isHead()) consBackwards(unit -> { - if (!unit.isHead()) unit.controlWeapons(rotate, shoot); - }); - } - - /** - * Counts the amount of children from this unit recursively. - */ - public int countBackwards() { - int out = 0; - - T current = as(); - while(current.child() != null) { - out++; - current = current.child().as(); - } - - return out; - } - - /** - * Counts the amount of parents from this unit recursively. - */ - public int countForward() { - int out = 0; - - T current = as(); - while(current.parent() != null) { - out++; - current = current.parent().as(); - } - - return out; - } - - /** - * Adds an extra segment to the chain. - */ - public void grow() { - if (!isTail()) { - ((Chainedc) tail).grow(); - } else { - MillipedeUnitType uType = checkType(type); - - T tail = ((T) type.create(team)); - tail.grown(true); - tail.set( - x + Angles.trnsx(rotation + 90, 0, uType.segmentOffset), - y + Angles.trnsy(rotation + 90, 0, uType.segmentOffset) - ); - tail.rotation = rotation; - tail.add(); - connect(tail); - } - } - - /** - * Self explanatory, they'll return true if it is the head, if it isn't the head nor the tail, or if it is tje tail. Respectively. - */ - public boolean isHead() { - return head == self(); - } - public boolean isSegment() { - return head != self() && tail != self(); - } - public boolean isTail() { - return tail == self(); - } - - /** - * Read parent and child id. - */ - @Override - public void read(Reads read) { - parentID = read.i(); - childID = read.i(); - } - - /** - * Split the chain or kill the whole chain if an unit is removed. - */ - @Override - public void remove() { - if (checkType(type).splittable) { - if (parent != null) { - ((Chainedc) parent).child(null); - ((Chainedc) parent).consForward(u -> { - u.tail(parent); - u.setupWeapons(u.type); - }); - } - if (child != null) { - ((Chainedc) child).parent(null); - ((Chainedc) child).consBackwards(u -> { - u.head(child); - u.setupWeapons(u.type); - }); - } - if (parent != null && child != null) checkType(type).splitSound.at(x, y); - } else { - if (parent != null) ((Chainedc) parent).consForward(Unitc::kill); - if (child != null) ((Chainedc) child).consBackwards(Unitc::kill); - } - } - - /** - * Updates the mounts to be based on the unit's position in the chain. Called when the chain connects. - */ - @Override - @Replace - public void setupWeapons(UnitType def) { - MillipedeUnitType uType = checkType(def); - Seq weapons = uType.chainWeapons.get(uType.weaponsIndex.get(self())); - mounts = new WeaponMount[weapons.size]; - for (int i = 0; i < mounts.length; i++) { - mounts[i] = weapons.get(i).mountType.get(weapons.get(i)); - } - } - - /** - * Connect the units together after read. - */ - @Override - public void update() { - if (parentID != -1) { - if (parent == null) ((Chainedc) Groups.unit.getByID(parentID)).connect(self()); - parentID = -1; - } - if (childID != -1) { - if (child == null) connect(Groups.unit.getByID(childID)); - childID = -1; - } - - if (isTail()) { - MillipedeUnitType uType = checkType(type); - - if (countForward() + 1 < uType.segmentLength && uType.regenTime > 0) { - growTime += Time.delta; - if (growTime > uType.regenTime) { - grow(); - uType.chainSound.at(x, y); - growTime %= uType.regenTime; - } - } - - Tmp.r1.setCentered( - x + Angles.trnsx(rotation + 90, 0, uType.segmentOffset), - y + Angles.trnsy(rotation + 90, 0, uType.segmentOffset), - uType.segmentOffset - ); - Units.nearby(Tmp.r1, u -> { - if (u instanceof Chainedc chain && chain.isHead() && u != head && countForward() + chain.countBackwards() + 2 <= uType.maxSegments && uType.chainTime > 0) { - chainTime += Time.delta; - if (chainTime > uType.chainTime) { - Log.info("a"); - connect(u); - uType.chainSound.at(x, y); - chainTime %= uType.chainTime; - } - } - }); - - if (countForward() + 1 < uType.minSegments) { - consBackwards(Unitc::kill); - } - } - } - - /** - * Updates the position and rotation of each segment in the chain. - */ - @Insert("update()") - public void updateChain() { - MillipedeUnitType uType = checkType(type); - if (isHead()) consBackwards(c -> { - if (c.parent() != null) { - Tmp.v1.set(c).sub(c.parent()).nor().scl(uType.segmentOffset); - float angleDst = OlUtils.angleDistSigned(Tmp.v1.angle(), c.parent().rotation + 180); - if (Math.abs(angleDst) > uType.angleLimit) { - Tmp.v1.rotate(-Tmp.v1.angle() + c.parent().rotation + 180 + (angleDst > 0 ? uType.angleLimit : -uType.angleLimit)); - } - Tmp.v1.add(c.parent()); - c.set(Tmp.v1.x, Tmp.v1.y); - c.rotation = c.angleTo(c.parent()); - } - }); - } - - /** - * Save parent and child id to be read later. - */ - @Override - public void write(Writes write) { - write.i(parent == null ? -1 : parent.id); - write.i(child == null ? -1 : child.id); - } +abstract class ChainedComp implements Unitc{ + transient Unit head, tail, parent, child; + + transient float growTime = 0, chainTime = 0; + + // internal values that i wish i had the entityanno knowledge to not make it generate io + private int parentID = -1, childID = -1; + boolean grown; + + @Import + UnitType type; + @Import + UnitController controller; + @Import + Team team; + @Import + float x, y, rotation; + @Import + WeaponMount[] mounts; + + /** + * Add first segments if this unit is not grown. + */ + @Override + public void add(){ + head = tail = self(); + + if(!grown){ + for(int i = 0; i < checkType(type).minSegments - 1; i++){ + grow(); + } + // i need this because again, i don't know how to not genio. + grown = true; + } + } + + @Override + public void aim(float x, float y){ + if(isHead()){ + final float finalX = x, finalY = y; + consBackwards(u -> { + if(!u.isHead()) u.aim(finalX, finalY); + }); + } + } + + /** + * Multiplies the unit cap to fit the amount of biggest sized chains. If it overflows, then just pick the regular unit cap. + */ + @Override + @Replace + public int cap(){ + MillipedeUnitType uType = checkType(type); + return Math.max(Units.getCap(team) * Math.max(uType.segmentLength, uType.maxSegments), Units.getCap(team)); + } + + /** + * Wrong cast errors are way too long. So long in fact that the crash box is too small for it. + */ + public MillipedeUnitType checkType(UnitType def){ + if(!(def instanceof MillipedeUnitType)) throw new RuntimeException("Unit's type must be MillipedeUnitType"); + return (MillipedeUnitType)def; + } + + /** + * Connects this centipede with another one. + *
  • + * If this unit is not the chain unit's tail, it'll call this method on the tail unit. + *
  • + *
  • + * If Parameter "to" is not the chain unit's head, "to" will become its head() method. + *
  • + */ + public void connect(Unit to){ + Chainedc cast = ((Chainedc)to).head().as(); + if(isTail()){ + cast.parent(self()); + child = to; + + ((Chainedc)head).consBackwards(u -> { + u.head(head); + u.tail(cast.tail()); + }); + + ((Chainedc)head).consBackwards(u -> { + u.setupWeapons(u.type); + if(!(u.controller() instanceof Player)) u.resetController(); + }); + }else ((Chainedc)tail).connect(to); + } + + /** + * @param cons will run through this unit and it's children recursively. + */ + public void consBackwards(Cons cons){ + T current = as(); + cons.get(current); + while(current.child() != null){ + cons.get(current.child().as()); + current = current.child().as(); + } + } + + /** + * @param cons will run through this unit and it's parents recursively. + */ + public void consForward(Cons cons){ + T current = as(); + cons.get(current); + while(current.parent() != null){ + cons.get(current.parent().as()); + current = current.parent().as(); + } + } + + /** + * Force a specific controller on certain parts of the chain. + */ + @MethodPriority(-1) + @Override + @BreakAll + public void controller(UnitController next){ + if(!isHead()){ + if(next instanceof Player){ + head.controller(next); + return; + } + + controller = new AIController(); + if(controller.unit() != self()) controller.unit(self()); + return; + } + } + + @Override + public void controlWeapons(boolean rotate, boolean shoot){ + if(isHead()) consBackwards(unit -> { + if(!unit.isHead()) unit.controlWeapons(rotate, shoot); + }); + } + + /** + * Counts the amount of children from this unit recursively. + */ + public int countBackwards(){ + int out = 0; + + T current = as(); + while(current.child() != null){ + out++; + current = current.child().as(); + } + + return out; + } + + /** + * Counts the amount of parents from this unit recursively. + */ + public int countForward(){ + int out = 0; + + T current = as(); + while(current.parent() != null){ + out++; + current = current.parent().as(); + } + + return out; + } + + /** + * Adds an extra segment to the chain. + */ + public void grow(){ + if(!isTail()){ + ((Chainedc)tail).grow(); + }else{ + MillipedeUnitType uType = checkType(type); + + T tail = ((T)type.create(team)); + tail.grown(true); + tail.set( + x + Angles.trnsx(rotation + 90, 0, uType.segmentOffset), + y + Angles.trnsy(rotation + 90, 0, uType.segmentOffset) + ); + tail.rotation = rotation; + tail.add(); + connect(tail); + } + } + + /** + * Self explanatory, they'll return true if it is the head, if it isn't the head nor the tail, or if it is tje tail. Respectively. + */ + public boolean isHead(){ + return head == self(); + } + + public boolean isSegment(){ + return head != self() && tail != self(); + } + + public boolean isTail(){ + return tail == self(); + } + + /** + * Read parent and child id. + */ + @Override + public void read(Reads read){ + parentID = read.i(); + childID = read.i(); + } + + /** + * Split the chain or kill the whole chain if an unit is removed. + */ + @Override + public void remove(){ + if(checkType(type).splittable){ + if(parent != null){ + ((Chainedc)parent).child(null); + ((Chainedc)parent).consForward(u -> { + u.tail(parent); + u.setupWeapons(u.type); + }); + } + if(child != null){ + ((Chainedc)child).parent(null); + ((Chainedc)child).consBackwards(u -> { + u.head(child); + u.setupWeapons(u.type); + }); + } + if(parent != null && child != null) checkType(type).splitSound.at(x, y); + }else{ + if(parent != null) ((Chainedc)parent).consForward(Unitc::kill); + if(child != null) ((Chainedc)child).consBackwards(Unitc::kill); + } + } + + /** + * Updates the mounts to be based on the unit's position in the chain. Called when the chain connects. + */ + @Override + @Replace + public void setupWeapons(UnitType def){ + MillipedeUnitType uType = checkType(def); + Seq weapons = uType.chainWeapons.get(uType.weaponsIndex.get(self())); + mounts = new WeaponMount[weapons.size]; + for(int i = 0; i < mounts.length; i++){ + mounts[i] = weapons.get(i).mountType.get(weapons.get(i)); + } + } + + /** + * Connect the units together after read. + */ + @Override + public void update(){ + if(parentID != -1){ + if(parent == null) ((Chainedc)Groups.unit.getByID(parentID)).connect(self()); + parentID = -1; + } + if(childID != -1){ + if(child == null) connect(Groups.unit.getByID(childID)); + childID = -1; + } + + if(isTail()){ + MillipedeUnitType uType = checkType(type); + + if(countForward() + 1 < uType.segmentLength && uType.regenTime > 0){ + growTime += Time.delta; + if(growTime > uType.regenTime){ + grow(); + uType.chainSound.at(x, y); + growTime %= uType.regenTime; + } + } + + Tmp.r1.setCentered( + x + Angles.trnsx(rotation + 90, 0, uType.segmentOffset), + y + Angles.trnsy(rotation + 90, 0, uType.segmentOffset), + uType.segmentOffset + ); + Units.nearby(Tmp.r1, u -> { + if(u instanceof Chainedc chain && chain.isHead() && u != head && countForward() + chain.countBackwards() + 2 <= uType.maxSegments && uType.chainTime > 0){ + chainTime += Time.delta; + if(chainTime > uType.chainTime){ + Log.info("a"); + connect(u); + uType.chainSound.at(x, y); + chainTime %= uType.chainTime; + } + } + }); + + if(countForward() + 1 < uType.minSegments){ + consBackwards(Unitc::kill); + } + } + } + + /** + * Updates the position and rotation of each segment in the chain. + */ + @Insert("update()") + public void updateChain(){ + MillipedeUnitType uType = checkType(type); + if(isHead()) consBackwards(c -> { + if(c.parent() != null){ + Tmp.v1.set(c).sub(c.parent()).nor().scl(uType.segmentOffset); + float angleDst = OlUtils.angleDistSigned(Tmp.v1.angle(), c.parent().rotation + 180); + if(Math.abs(angleDst) > uType.angleLimit){ + Tmp.v1.rotate(-Tmp.v1.angle() + c.parent().rotation + 180 + (angleDst > 0 ? uType.angleLimit : -uType.angleLimit)); + } + Tmp.v1.add(c.parent()); + c.set(Tmp.v1.x, Tmp.v1.y); + c.rotation = c.angleTo(c.parent()); + } + }); + } + + /** + * Save parent and child id to be read later. + */ + @Override + public void write(Writes write){ + write.i(parent == null ? -1 : parent.id); + write.i(child == null ? -1 : child.id); + } } diff --git a/src/omaloon/entities/comp/CoreComp.java b/src/omaloon/entities/comp/CoreComp.java index c6e6d021..7762910b 100644 --- a/src/omaloon/entities/comp/CoreComp.java +++ b/src/omaloon/entities/comp/CoreComp.java @@ -1,12 +1,12 @@ package omaloon.entities.comp; -import arc.struct.Queue; +import arc.struct.*; import ent.anno.Annotations.*; import mindustry.entities.units.*; import mindustry.gen.*; import mindustry.type.*; -import mindustry.world.Build; -import mindustry.world.blocks.ConstructBlock; +import mindustry.world.*; +import mindustry.world.blocks.*; import static mindustry.Vars.state; @@ -15,57 +15,62 @@ */ @SuppressWarnings("unused") @EntityComponent -abstract class CoreComp implements Unitc { - @Import float rotation; - @Import UnitType type; - @Import StatusEntry[] statuses; +abstract class CoreComp implements Unitc{ + @Import + float rotation; + @Import + UnitType type; + @Import + StatusEntry[] statuses; - @Replace(1) - @Override - public void updateBuildLogic() { - Queue plans = plans(); - for (BuildPlan req : plans) { - boolean valid = - ((req.tile() != null && req.tile().build instanceof ConstructBlock.ConstructBuild cons && cons.current == req.block) || - (req.breaking ? Build.validBreak(team(), req.x, req.y) : - Build.validPlace(req.block, team(), req.x, req.y, req.rotation))); - if (!valid) plans.remove(req); - } - } + @Replace(1) + @Override + public void updateBuildLogic(){ + Queue plans = plans(); + for(BuildPlan req : plans){ + boolean valid = + ((req.tile() != null && req.tile().build instanceof ConstructBlock.ConstructBuild cons && cons.current == req.block) || + (req.breaking ? Build.validBreak(team(), req.x, req.y) : + Build.validPlace(req.block, team(), req.x, req.y, req.rotation))); + if(!valid) plans.remove(req); + } + } - @Replace(1) - @Override - public boolean canBuild() { - return true; - } - @Replace(1) - @Override - public boolean mining(){ - return false; - } + @Replace(1) + @Override + public boolean canBuild(){ + return true; + } - @Replace(1) - @Override - public float prefRotation() { - if (moving() && type.omniMovement) { - return vel().angle(); - } - return rotation; - } + @Replace(1) + @Override + public boolean mining(){ + return false; + } - @Replace(1) - @Override - public void drawBuilding(){} + @Replace(1) + @Override + public float prefRotation(){ + if(moving() && type.omniMovement){ + return vel().angle(); + } + return rotation; + } - @Replace(1) - @Override - public boolean activelyBuilding() { - if (isBuilding()) { - var plan = buildPlan(); - if (!state.isEditor() && plan != null && !within(plan, state.rules.infiniteResources ? Float.MAX_VALUE : type.buildRange)) { - return false; - } - } - return isBuilding() && updateBuilding(); - } + @Replace(1) + @Override + public void drawBuilding(){ + } + + @Replace(1) + @Override + public boolean activelyBuilding(){ + if(isBuilding()){ + var plan = buildPlan(); + if(!state.isEditor() && plan != null && !within(plan, state.rules.infiniteResources ? Float.MAX_VALUE : type.buildRange)){ + return false; + } + } + return isBuilding() && updateBuilding(); + } } diff --git a/src/omaloon/entities/comp/DroneComp.java b/src/omaloon/entities/comp/DroneComp.java index c60d3077..37ad8283 100644 --- a/src/omaloon/entities/comp/DroneComp.java +++ b/src/omaloon/entities/comp/DroneComp.java @@ -8,47 +8,48 @@ @SuppressWarnings("unused") @EntityComponent -abstract class DroneComp implements Unitc, Flyingc { - @Import Team team; +abstract class DroneComp implements Unitc, Flyingc{ + @Import + Team team; transient int abilityIndex = -1; transient Unit owner; transient int ownerID = -1; - public boolean hasOwner() { + public boolean hasOwner(){ return owner != null && owner.isValid() && owner.team() == team; } @Override - public void read(Reads read) { + public void read(Reads read){ ownerID = read.i(); abilityIndex = read.i(); - if (ownerID != -1) { + if(ownerID != -1){ owner = Groups.unit.getByID(ownerID); } } @Override - public void update() { - if (ownerID != -1 && owner == null) { + public void update(){ + if(ownerID != -1 && owner == null){ owner = Groups.unit.getByID(ownerID); ownerID = -1; - if (hasOwner() && abilityIndex < owner.abilities.length && owner.abilities[abilityIndex] instanceof DroneAbility a) { + if(hasOwner() && abilityIndex < owner.abilities.length && owner.abilities[abilityIndex] instanceof DroneAbility a){ a.drones.add(0, self()); a.data++; controller(a.droneController.apply(owner)); - } else abilityIndex = -1; + }else abilityIndex = -1; } - if (!hasOwner() || abilityIndex == -1) { + if(!hasOwner() || abilityIndex == -1){ Call.unitDespawn(self()); } } @Override - public void write(Writes write) { + public void write(Writes write){ write.i(hasOwner() ? owner.id() : -1); write.i(abilityIndex); } diff --git a/src/omaloon/entities/comp/FloatMechComp.java b/src/omaloon/entities/comp/FloatMechComp.java index 9bfbb2f9..ccf1ebb7 100644 --- a/src/omaloon/entities/comp/FloatMechComp.java +++ b/src/omaloon/entities/comp/FloatMechComp.java @@ -13,17 +13,20 @@ import static mindustry.Vars.*; @EntityComponent -abstract class FloatMechComp implements Posc, Flyingc, Hitboxc, Unitc, FloatMechc, ElevationMovec { - @Import float x, y, hitSize; - @Import UnitType type; - @Import float elevation; +abstract class FloatMechComp implements Posc, Flyingc, Hitboxc, Unitc, FloatMechc, ElevationMovec{ + @Import + float x, y, hitSize; + @Import + UnitType type; + @Import + float elevation; //TODO: SyncField(false) & SyncLocal causes BufferUnderflowException in multiplayer /*@SyncField(false) @SyncLocal*/ float baseRotation; transient float walkTime, walkExtension; transient private boolean walked; @Override - public void update() { + public void update(){ elevation = Mathf.approachDelta(elevation, onSolid() ? 1f : 0f, type.riseSpeed); //trigger animation only when walking manually @@ -46,14 +49,14 @@ public void update() { float width = hitSize / 2f * side, length = type.mechStride * 1.35f; float cx = x + Angles.trnsx(baseRotation, length, width), - cy = y + Angles.trnsy(baseRotation, length, width); + cy = y + Angles.trnsy(baseRotation, length, width); if(type.stepShake > 0){ Effect.shake(type.stepShake, type.stepShake, cx, cy); } if(type.mechStepParticles){ - Effect.floorDust(cx, cy, hitSize/8f); + Effect.floorDust(cx, cy, hitSize / 8f); } } @@ -82,8 +85,8 @@ public float walkExtend(boolean scaled){ if(scaled) return raw / type.mechStride; - if(raw > type.mechStride*3) raw = raw - type.mechStride * 4; - else if(raw > type.mechStride*2) raw = type.mechStride * 2 - raw; + if(raw > type.mechStride * 3) raw = raw - type.mechStride * 4; + else if(raw > type.mechStride * 2) raw = type.mechStride * 2 - raw; else if(raw > type.mechStride) raw = type.mechStride * 2 - raw; return raw; @@ -118,7 +121,7 @@ public void approach(Vec2 vector){ @Replace(1) @Override - public EntityCollisions.SolidPred solidity() { + public EntityCollisions.SolidPred solidity(){ return null; } } diff --git a/src/omaloon/entities/comp/OrnitopterComp.java b/src/omaloon/entities/comp/OrnitopterComp.java index 5c0fe16c..1f1a6e71 100644 --- a/src/omaloon/entities/comp/OrnitopterComp.java +++ b/src/omaloon/entities/comp/OrnitopterComp.java @@ -12,9 +12,12 @@ @EntityComponent abstract class OrnitopterComp implements Unitc, Ornitopterc{ - @Import float x,y,rotation; - @Import boolean dead; - @Import UnitType type; + @Import + float x, y, rotation; + @Import + boolean dead; + @Import + UnitType type; public BladeMount[] blades; public float bladeMoveSpeedScl = 1f; @@ -24,14 +27,14 @@ public void afterRead(){ } @Override - public void setType(UnitType type) { + public void setType(UnitType type){ setBlades(type); } public void setBlades(UnitType type){ - if (type instanceof OrnitopterUnitType ornitopter) { + if(type instanceof OrnitopterUnitType ornitopter){ blades = new BladeMount[ornitopter.blades.size]; - for (int i = 0; i < blades.length; i++) { + for(int i = 0; i < blades.length; i++){ Blade bladeType = ornitopter.blades.get(i); blades[i] = new BladeMount(bladeType); } @@ -41,26 +44,27 @@ public void setBlades(UnitType type){ public long drawSeed = 0; private float driftAngle; private boolean hasDriftAngle = false; - public float driftAngle() { + + public float driftAngle(){ return driftAngle; } @Override - public void update() { + public void update(){ drawSeed++; - OrnitopterUnitType type = (OrnitopterUnitType) this.type; + OrnitopterUnitType type = (OrnitopterUnitType)this.type; float rX = x + Angles.trnsx(rotation - 90, type.fallSmokeX, type.fallSmokeY); float rY = y + Angles.trnsy(rotation - 90, type.fallSmokeX, type.fallSmokeY); // When dying - if (dead || health() <= 0) { - if (Mathf.chanceDelta(type.fallSmokeChance)) { + if(dead || health() <= 0){ + if(Mathf.chanceDelta(type.fallSmokeChance)){ Fx.fallSmoke.at(rX, rY); Fx.burning.at(rX, rY); } // Compute random drift angle if not already set - if (!hasDriftAngle) { + if(!hasDriftAngle){ float speed = Math.max(Math.abs(vel().x), Math.abs(vel().y)); float maxAngle = Math.min(180f, speed * type.fallDriftScl); // Maximum drift angle based on speed driftAngle = (Angles.angle(x, y, x + vel().x, y + vel().y) + Mathf.range(maxAngle)) % 360f; @@ -76,12 +80,12 @@ public void update() { rotation = Mathf.lerpDelta(rotation, driftAngle, 0.01f); bladeMoveSpeedScl = Mathf.lerpDelta(bladeMoveSpeedScl, 0f, type.bladeDeathMoveSlowdown); - } else { + }else{ hasDriftAngle = false; // Reset the drift angle flag bladeMoveSpeedScl = Mathf.lerpDelta(bladeMoveSpeedScl, 1f, type.bladeDeathMoveSlowdown); } - for (BladeMount blade : blades) { + for(BladeMount blade : blades){ blade.bladeRotation += ((blade.blade.bladeMaxMoveAngle * bladeMoveSpeedScl) + blade.blade.bladeMinMoveAngle) * Time.delta; } type.fallSpeed = 0.01f; diff --git a/src/omaloon/entities/effect/LumenLiquidEffect.java b/src/omaloon/entities/effect/LumenLiquidEffect.java index 057952ef..f21bcb11 100644 --- a/src/omaloon/entities/effect/LumenLiquidEffect.java +++ b/src/omaloon/entities/effect/LumenLiquidEffect.java @@ -6,38 +6,38 @@ import arc.math.geom.*; import mindustry.entities.*; -public class LumenLiquidEffect extends Effect { - public static final Rand rand = new Rand(); - public static final Vec2 rv = new Vec2(); +public class LumenLiquidEffect extends Effect{ + public static final Rand rand = new Rand(); + public static final Vec2 rv = new Vec2(); - public Color base, middle, top; + public Color base, middle, top; - public LumenLiquidEffect(float lifetime, Color base, Color middle, Color top) { - this.lifetime = lifetime; - this.base = base; - this.middle = middle; - this.top = top; - } + public LumenLiquidEffect(float lifetime, Color base, Color middle, Color top){ + this.lifetime = lifetime; + this.base = base; + this.middle = middle; + this.top = top; + } - @Override - public void render(EffectContainer e) { - Draw.color(base); - rand.setSeed(e.id); - for(int i = 0; i < 4f; i++){ - rv.trns(rand.range(10) + e.rotation, e.fin() * (12 + rand.random(32))).add(e.x, e.y); - Fill.circle(rv.x, rv.y, 4 * e.foutpow()); - } - Draw.color(middle); - for(int i = 0; i < 11f; i++){ - rv.trns(rand.range(15) + e.rotation, e.fin() * (10 + rand.random(29))).add(e.x, e.y); - Fill.circle(rv.x, rv.y, 3 * e.foutpow()); - rv.trns(rand.range(20) + e.rotation, e.finpow() * (9 + rand.random(26))).add(e.x, e.y); - Fill.circle(rv.x, rv.y, 2 * e.fout()); - } - Draw.color(top); - for(int i = 0; i < 30f; i++){ - rv.trns(rand.range(30) + e.rotation, e.finpow() * (8 + rand.random(24))).add(e.x, e.y); - Fill.circle(rv.x, rv.y, 1 * e.fout()); - } - } + @Override + public void render(EffectContainer e){ + Draw.color(base); + rand.setSeed(e.id); + for(int i = 0; i < 4f; i++){ + rv.trns(rand.range(10) + e.rotation, e.fin() * (12 + rand.random(32))).add(e.x, e.y); + Fill.circle(rv.x, rv.y, 4 * e.foutpow()); + } + Draw.color(middle); + for(int i = 0; i < 11f; i++){ + rv.trns(rand.range(15) + e.rotation, e.fin() * (10 + rand.random(29))).add(e.x, e.y); + Fill.circle(rv.x, rv.y, 3 * e.foutpow()); + rv.trns(rand.range(20) + e.rotation, e.finpow() * (9 + rand.random(26))).add(e.x, e.y); + Fill.circle(rv.x, rv.y, 2 * e.fout()); + } + Draw.color(top); + for(int i = 0; i < 30f; i++){ + rv.trns(rand.range(30) + e.rotation, e.finpow() * (8 + rand.random(24))).add(e.x, e.y); + Fill.circle(rv.x, rv.y, 1 * e.fout()); + } + } } diff --git a/src/omaloon/entities/part/ConstructPart.java b/src/omaloon/entities/part/ConstructPart.java index 2eb7e9e5..97a54014 100644 --- a/src/omaloon/entities/part/ConstructPart.java +++ b/src/omaloon/entities/part/ConstructPart.java @@ -10,63 +10,63 @@ /** * Draws a region with a construct animation, is meant to be used only on units. */ -public class ConstructPart extends DrawPart { - /** Appended to unit/weapon/block name and drawn. */ - public String suffix; - /** Overrides suffix if set. */ - public @Nullable String name; +public class ConstructPart extends DrawPart{ + /** Appended to unit/weapon/block name and drawn. */ + public String suffix; + /** Overrides suffix if set. */ + public @Nullable String name; - /** - * Construction progress. - */ - public PartProgress progress = PartProgress.reload; + /** + * Construction progress. + */ + public PartProgress progress = PartProgress.reload; - /** - * When to consider that it finished constructing. - */ - public float finishTresh = 0.95f; + /** + * When to consider that it finished constructing. + */ + public float finishTresh = 0.95f; - /** - * Position and rotation offset. - */ - public float x, y, rot; + /** + * Position and rotation offset. + */ + public float x, y, rot; - /** - * Offset for construct and outline region. - */ - public float layerOffset = 0f, outlineLayerOffset = 0f; + /** + * Offset for construct and outline region. + */ + public float layerOffset = 0f, outlineLayerOffset = 0f; - public TextureRegion constructRegion, outlineRegion; + public TextureRegion constructRegion, outlineRegion; - public ConstructPart(String suffix) { - this.suffix = suffix; - } + public ConstructPart(String suffix){ + this.suffix = suffix; + } - @Override - public void draw(PartParams params) { - float z = Draw.z(), - dx = params.x + Angles.trnsx(params.rotation - 90f, x, y), - dy = params.y + Angles.trnsy(params.rotation - 90f, x, y), - dr = params.rotation + rot - 90, - prog = progress.getClamp(params); - Draw.z(z + outlineLayerOffset); - Draw.rect(outlineRegion, dx, dy, dr); - Draw.z(z + layerOffset); - if (prog < finishTresh) { - Draw.draw(Draw.z(), () -> Drawf.construct(dx, dy, constructRegion, dr, prog, 1f, Time.time)); - } else { - Draw.rect(constructRegion, dx, dy, dr); - } - Draw.z(z); - } + @Override + public void draw(PartParams params){ + float z = Draw.z(), + dx = params.x + Angles.trnsx(params.rotation - 90f, x, y), + dy = params.y + Angles.trnsy(params.rotation - 90f, x, y), + dr = params.rotation + rot - 90, + prog = progress.getClamp(params); + Draw.z(z + outlineLayerOffset); + Draw.rect(outlineRegion, dx, dy, dr); + Draw.z(z + layerOffset); + if(prog < finishTresh){ + Draw.draw(Draw.z(), () -> Drawf.construct(dx, dy, constructRegion, dr, prog, 1f, Time.time)); + }else{ + Draw.rect(constructRegion, dx, dy, dr); + } + Draw.z(z); + } - @Override - public void load(String name) { - if (this.name == null) { - this.name = name + suffix; - } + @Override + public void load(String name){ + if(this.name == null){ + this.name = name + suffix; + } - constructRegion = Core.atlas.find(this.name); - outlineRegion = Core.atlas.find(this.name + "-outline"); - } + constructRegion = Core.atlas.find(this.name); + outlineRegion = Core.atlas.find(this.name + "-outline"); + } } diff --git a/src/omaloon/graphics/OlGraphics.java b/src/omaloon/graphics/OlGraphics.java index c97b9f9a..8efa54b1 100644 --- a/src/omaloon/graphics/OlGraphics.java +++ b/src/omaloon/graphics/OlGraphics.java @@ -5,20 +5,20 @@ import arc.math.*; import arc.util.*; -public class OlGraphics { +public class OlGraphics{ /** * Original code from Project Unity * Author: @Xeloboyo * Creates connections for blocks - * */ - public static TextureRegion[] getRegions(TextureRegion region, int w, int h, int tilesize) { + */ + public static TextureRegion[] getRegions(TextureRegion region, int w, int h, int tilesize){ int size = w * h; TextureRegion[] regions = new TextureRegion[size]; float tileW = (region.u2 - region.u) / w; float tileH = (region.v2 - region.v) / h; - for(int i = 0; i < size; i++) { + for(int i = 0; i < size; i++){ float tileX = ((float)(i % w)) / w; float tileY = ((float)(i / w)) / h; TextureRegion reg = new TextureRegion(region); @@ -38,35 +38,35 @@ public static TextureRegion[] getRegions(TextureRegion region, int w, int h, int } static int[][] joinschkdirs = { - {-1, 1},{0, 1},{1, 1}, - {-1, 0},/*{X}*/{1, 0}, - {-1,-1},{0,-1},{1,-1}, + {-1, 1}, {0, 1}, {1, 1}, + {-1, 0},/*{X}*/{1, 0}, + {-1, -1}, {0, -1}, {1, -1}, }; static int[] joinsMap = { - 39,39,27,27,39,39,27,27,38,38,17,26,38,38,17,26,36, - 36,16,16,36,36,24,24,37,37,41,21,37,37,43,25,39, - 39,27,27,39,39,27,27,38,38,17,26,38,38,17,26,36, - 36,16,16,36,36,24,24,37,37,41,21,37,37,43,25,3, - 3,15,15,3,3,15,15,5,5,29,31,5,5,29,31,4, - 4,40,40,4,4,20,20,28,28,10,11,28,28,23,32,3, - 3,15,15,3,3,15,15,2,2,9,14,2,2,9,14,4, - 4,40,40,4,4,20,20,30,30,47,44,30,30,22,6,39, - 39,27,27,39,39,27,27,38,38,17,26,38,38,17,26,36, - 36,16,16,36,36,24,24,37,37,41,21,37,37,43,25,39, - 39,27,27,39,39,27,27,38,38,17,26,38,38,17,26,36, - 36,16,16,36,36,24,24,37,37,41,21,37,37,43,25,3, - 3,15,15,3,3,15,15,5,5,29,31,5,5,29,31,0, - 0,42,42,0,0,12,12,8,8,35,34,8,8,33,7,3, - 3,15,15,3,3,15,15,2,2,9,14,2,2,9,14,0, - 0,42,42,0,0,12,12,1,1,45,18,1,1,19,13 + 39, 39, 27, 27, 39, 39, 27, 27, 38, 38, 17, 26, 38, 38, 17, 26, 36, + 36, 16, 16, 36, 36, 24, 24, 37, 37, 41, 21, 37, 37, 43, 25, 39, + 39, 27, 27, 39, 39, 27, 27, 38, 38, 17, 26, 38, 38, 17, 26, 36, + 36, 16, 16, 36, 36, 24, 24, 37, 37, 41, 21, 37, 37, 43, 25, 3, + 3, 15, 15, 3, 3, 15, 15, 5, 5, 29, 31, 5, 5, 29, 31, 4, + 4, 40, 40, 4, 4, 20, 20, 28, 28, 10, 11, 28, 28, 23, 32, 3, + 3, 15, 15, 3, 3, 15, 15, 2, 2, 9, 14, 2, 2, 9, 14, 4, + 4, 40, 40, 4, 4, 20, 20, 30, 30, 47, 44, 30, 30, 22, 6, 39, + 39, 27, 27, 39, 39, 27, 27, 38, 38, 17, 26, 38, 38, 17, 26, 36, + 36, 16, 16, 36, 36, 24, 24, 37, 37, 41, 21, 37, 37, 43, 25, 39, + 39, 27, 27, 39, 39, 27, 27, 38, 38, 17, 26, 38, 38, 17, 26, 36, + 36, 16, 16, 36, 36, 24, 24, 37, 37, 41, 21, 37, 37, 43, 25, 3, + 3, 15, 15, 3, 3, 15, 15, 5, 5, 29, 31, 5, 5, 29, 31, 0, + 0, 42, 42, 0, 0, 12, 12, 8, 8, 35, 34, 8, 8, 33, 7, 3, + 3, 15, 15, 3, 3, 15, 15, 2, 2, 9, 14, 2, 2, 9, 14, 0, + 0, 42, 42, 0, 0, 12, 12, 1, 1, 45, 18, 1, 1, 19, 13 }; - public static int getMaskIndex(T[][] map, int x,int y, Boolf canConnect){ + public static int getMaskIndex(T[][] map, int x, int y, Boolf canConnect){ int index = 0, ax, ay; T t; - for(int i = 0; i < joinschkdirs.length; i++) { + for(int i = 0; i < joinschkdirs.length; i++){ ax = joinschkdirs[i][0] + x; ay = joinschkdirs[i][1] + y; t = null; @@ -75,35 +75,36 @@ public static int getMaskIndex(T[][] map, int x,int y, Boolf canConnect){ t = map[ax][ay]; } - index += canConnect.get(t) ? (1< int getTilingIndex(T[][] map, int x, int y, Boolf canConnect) { + public static int getTilingIndex(T[][] map, int x, int y, Boolf canConnect){ return joinsMap[getMaskIndex(map, x, y, canConnect)]; } + /*end*/ public static Rand rand = new Rand(); - public static void bubbles(int seed, float x, float y, int bubblesAmount, float bubblesSize, float baseLife, float baseSize) { + public static void bubbles(int seed, float x, float y, int bubblesAmount, float bubblesSize, float baseLife, float baseSize){ rand.setSeed(seed); - for (int i = 0; i < bubblesAmount; i++) { + for(int i = 0; i < bubblesAmount; i++){ float - angle = rand.random(360f), - fin = (rand.random(0.8f)*(Time.time/baseLife)) % rand.random(0.1f, 0.6f), - len = rand.random(baseSize/2f, baseSize) / fin, + angle = rand.random(360f), + fin = (rand.random(0.8f) * (Time.time / baseLife)) % rand.random(0.1f, 0.6f), + len = rand.random(baseSize / 2f, baseSize) / fin, - trnsx = x + Angles.trnsx(angle, len, rand.random(baseSize/4f, baseSize/4f)), - trnsy = y + Angles.trnsy(angle, len, rand.random(baseSize/4f, baseSize/4f)); + trnsx = x + Angles.trnsx(angle, len, rand.random(baseSize / 4f, baseSize / 4f)), + trnsy = y + Angles.trnsy(angle, len, rand.random(baseSize / 4f, baseSize / 4f)); - Fill.poly(trnsx, trnsy,18 , Interp.sine.apply(fin * 3.5f) * bubblesSize); + Fill.poly(trnsx, trnsy, 18, Interp.sine.apply(fin * 3.5f) * bubblesSize); } } - public static void l(float layer) { + public static void l(float layer){ Draw.z(layer); } } \ No newline at end of file diff --git a/src/omaloon/graphics/OlShaders.java b/src/omaloon/graphics/OlShaders.java index 75a308ef..440f3c93 100644 --- a/src/omaloon/graphics/OlShaders.java +++ b/src/omaloon/graphics/OlShaders.java @@ -9,13 +9,12 @@ import mindustry.*; import mindustry.graphics.*; import mindustry.type.*; -import omaloon.*; import omaloon.graphics.shaders.*; import static arc.Core.*; import static mindustry.Vars.*; -public class OlShaders { +public class OlShaders{ public static DepthShader depth; public static DepthAtmosphereShader depthAtmosphere; @@ -25,7 +24,7 @@ public class OlShaders { public static PlanetTextureShader planetTextureShader; - public static void load() { + public static void load(){ String prevVert = Shader.prependVertexCode, prevFrag = Shader.prependFragmentCode; Shader.prependVertexCode = Shader.prependFragmentCode = ""; @@ -55,7 +54,7 @@ public static void dispose(){ /** * Resolves shader files from this mod via {@link Vars#tree}. * @param name The shader file name, e.g. {@code my-shader.frag}. - * @return The shader file, located inside {@code shaders/confictura/}. + * @return The shader file, located inside {@code shaders/confictura/}. */ public static Fi file(String name){ return tree.get("shaders/" + name); @@ -96,8 +95,8 @@ public static class OlLoadShader extends Shader{ public OlLoadShader(String fragment, String vertex){ super( - file(vertex + ".vert"), - file(fragment + ".frag") + file(vertex + ".vert"), + file(fragment + ".frag") ); } @@ -113,19 +112,19 @@ public void apply(){ } } - public static class SurfaceShader extends Shader { + public static class SurfaceShader extends Shader{ Texture noiseTex; - public SurfaceShader(String frag) { + public SurfaceShader(String frag){ super(Shaders.getShaderFi("screenspace.vert"), tree.get("shaders/" + frag + ".frag")); loadNoise(); } - public String textureName() { + public String textureName(){ return "noise"; } - public void loadNoise() { + public void loadNoise(){ assets.load("sprites/" + textureName() + ".png", Texture.class).loaded = t -> { t.setFilter(Texture.TextureFilter.linear); t.setWrap(Texture.TextureWrap.repeat); @@ -133,18 +132,18 @@ public void loadNoise() { } @Override - public void apply() { + public void apply(){ setUniformf("u_campos", - camera.position.x - camera.width / 2, - camera.position.y - camera.height / 2 + camera.position.x - camera.width / 2, + camera.position.y - camera.height / 2 ); setUniformf("u_ccampos", camera.position); setUniformf("u_resolution", camera.width, camera.height); setUniformf("u_rresolution", graphics.getWidth(), graphics.getHeight()); setUniformf("u_time", Time.time); - if(hasUniform("u_noise")) { - if(noiseTex == null) { + if(hasUniform("u_noise")){ + if(noiseTex == null){ noiseTex = assets.get("sprites/" + textureName() + ".png", Texture.class); } diff --git a/src/omaloon/graphics/g3d/CircleMesh.java b/src/omaloon/graphics/g3d/CircleMesh.java index 09d4944b..466da36f 100644 --- a/src/omaloon/graphics/g3d/CircleMesh.java +++ b/src/omaloon/graphics/g3d/CircleMesh.java @@ -4,13 +4,11 @@ import arc.graphics.*; import arc.graphics.g2d.*; import arc.graphics.gl.*; -import arc.math.Mathf; +import arc.math.*; import arc.math.geom.*; import arc.util.*; -import mindustry.graphics.Shaders; import mindustry.graphics.g3d.*; import mindustry.type.*; -import omaloon.content.OlPlanets; import omaloon.graphics.*; public class CircleMesh extends PlanetMesh{ @@ -38,47 +36,47 @@ public MeshPoint(Vec3 position, Vec2 textureCords){ } MeshPoint[] meshPoints = { - new MeshPoint(Tmp.v31.setZero(), Tmp.v1.set(0, 0)), - new MeshPoint(Tmp.v33.setZero(), Tmp.v3.set(1, 0)), - new MeshPoint(Tmp.v34.setZero(), Tmp.v4.set(1, 1)), - new MeshPoint(Tmp.v32.setZero(), Tmp.v2.set(0, 1)), + new MeshPoint(Tmp.v31.setZero(), Tmp.v1.set(0, 0)), + new MeshPoint(Tmp.v33.setZero(), Tmp.v3.set(1, 0)), + new MeshPoint(Tmp.v34.setZero(), Tmp.v4.set(1, 1)), + new MeshPoint(Tmp.v32.setZero(), Tmp.v2.set(0, 1)), }; int[] order = {0, 1, 2, 2, 3, 0}; Vec3 plane = new Vec3() - .set(1, 0, 0) - .rotate(Vec3.X, 90) - .rotate(Vec3.X, axis.angle(Vec3.X) + 1) - .rotate(Vec3.Y, axis.angle(Vec3.Y) + 1) - .rotate(Vec3.Z, axis.angle(Vec3.Z) + 1) - .crs(axis); + .set(1, 0, 0) + .rotate(Vec3.X, 90) + .rotate(Vec3.X, axis.angle(Vec3.X) + 1) + .rotate(Vec3.Y, axis.angle(Vec3.Y) + 1) + .rotate(Vec3.Z, axis.angle(Vec3.Z) + 1) + .crs(axis); Vec3 inv = axis.cpy().unaryMinus(); for(int i = 0; i < sides; i++){ meshPoints[0].position - .set(plane) - .rotate(axis, i * 1f / sides * 360) - .setLength2(1) - .scl(radiusIn); + .set(plane) + .rotate(axis, i * 1f / sides * 360) + .setLength2(1) + .scl(radiusIn); meshPoints[1].position - .set(plane) - .rotate(axis, i * 1f / sides * 360) - .setLength2(1) - .scl(radiusOut); + .set(plane) + .rotate(axis, i * 1f / sides * 360) + .setLength2(1) + .scl(radiusOut); meshPoints[2].position - .set(plane) - .rotate(axis, (i + 1f) / sides * 360) - .setLength2(1) - .scl(radiusOut); + .set(plane) + .rotate(axis, (i + 1f) / sides * 360) + .setLength2(1) + .scl(radiusOut); meshPoints[3].position - .set(plane) - .rotate(axis, (i + 1f) / sides * 360) - .setLength2(1) - .scl(radiusIn); + .set(plane) + .rotate(axis, (i + 1f) / sides * 360) + .setLength2(1) + .scl(radiusIn); for(int j : order){ MeshPoint point = meshPoints[j]; @@ -121,12 +119,12 @@ public void render(PlanetParams params, Mat3D projection, Mat3D transform){ public void preRender(PlanetParams params){ OlShaders.planetTextureShader.planet = planet; OlShaders.planetTextureShader.lightDir - .set(planet.solarSystem.position) - .sub(planet.position) - .rotate(Vec3.Y, planet.getRotation()) - .nor(); + .set(planet.solarSystem.position) + .sub(planet.position) + .rotate(Vec3.Y, planet.getRotation()) + .nor(); OlShaders.planetTextureShader.ambientColor - .set(planet.solarSystem.lightColor); + .set(planet.solarSystem.lightColor); //TODO: better disappearing OlShaders.planetTextureShader.alpha = params.planet == planet ? 1f - params.uiAlpha : 1f; } diff --git a/src/omaloon/graphics/g3d/MeshUtils.java b/src/omaloon/graphics/g3d/MeshUtils.java index 2981ae12..7f995c3f 100644 --- a/src/omaloon/graphics/g3d/MeshUtils.java +++ b/src/omaloon/graphics/g3d/MeshUtils.java @@ -3,21 +3,21 @@ import arc.graphics.*; import arc.math.geom.*; -public class MeshUtils { +public class MeshUtils{ static final Vec3 - v1 = new Vec3(), - v2 = new Vec3(), - v3 = new Vec3(), - v4 = new Vec3(); + v1 = new Vec3(), + v2 = new Vec3(), + v3 = new Vec3(), + v4 = new Vec3(); static final float[] floats = new float[8]; //3 + 3 + 2 static Mesh mesh; - static void begin(int count) { + static void begin(int count){ mesh = new Mesh(true, count, 0, - VertexAttribute.position3, - VertexAttribute.normal, - VertexAttribute.texCoords + VertexAttribute.position3, + VertexAttribute.normal, + VertexAttribute.texCoords ); mesh.getVerticesBuffer().limit(mesh.getMaxVertices()); @@ -28,19 +28,19 @@ static Mesh end(){ Mesh last = mesh; last.getVerticesBuffer().limit(last - .getVerticesBuffer() - .position() + .getVerticesBuffer() + .position() ); mesh = null; return last; } - static Vec3 normal(Vec3 v1, Vec3 v2, Vec3 v3) { + static Vec3 normal(Vec3 v1, Vec3 v2, Vec3 v3){ return v4.set(v2).sub(v1).crs( - v3.x - v1.x, - v3.y - v1.y, - v3.z - v1.z + v3.x - v1.x, + v3.y - v1.y, + v3.z - v1.z ).nor(); } diff --git a/src/omaloon/graphics/shaders/DepthAtmosphereShader.java b/src/omaloon/graphics/shaders/DepthAtmosphereShader.java index 5b20f7b0..8c4c09dd 100644 --- a/src/omaloon/graphics/shaders/DepthAtmosphereShader.java +++ b/src/omaloon/graphics/shaders/DepthAtmosphereShader.java @@ -6,15 +6,15 @@ import arc.util.*; import omaloon.type.*; -import static arc.Core.*; -import static omaloon.graphics.OlShaders.*; +import static arc.Core.graphics; +import static omaloon.graphics.OlShaders.file; /** * An atmosphere shader that incorporates the planet shape in a form of depth texture. Better quality, but at the little * cost of performance. * @author GlFolker */ -public class DepthAtmosphereShader extends Shader { +public class DepthAtmosphereShader extends Shader{ private static final Mat3D mat = new Mat3D(); public Camera3D camera; diff --git a/src/omaloon/graphics/shaders/DepthShader.java b/src/omaloon/graphics/shaders/DepthShader.java index 3fea373b..b6c25d80 100644 --- a/src/omaloon/graphics/shaders/DepthShader.java +++ b/src/omaloon/graphics/shaders/DepthShader.java @@ -3,13 +3,13 @@ import arc.graphics.g3d.*; import arc.graphics.gl.*; -import static omaloon.graphics.OlShaders.*; +import static omaloon.graphics.OlShaders.file; /** * Specialized mesh shader to capture fragment depths. * @author GlFolker */ -public class DepthShader extends Shader { +public class DepthShader extends Shader{ public Camera3D camera; public DepthShader(){ diff --git a/src/omaloon/maps/ColorPass.java b/src/omaloon/maps/ColorPass.java index 7e873a70..e71ee6b1 100644 --- a/src/omaloon/maps/ColorPass.java +++ b/src/omaloon/maps/ColorPass.java @@ -6,96 +6,98 @@ import arc.util.*; import arc.util.noise.*; -public abstract class ColorPass { - public abstract @Nullable Color color(Vec3 pos, float height); +public abstract class ColorPass{ + public abstract @Nullable Color color(Vec3 pos, float height); - /** - * A pass that paints points inside a sphere. - * @see HeightPass.SphereHeight SphereHeight - */ - public static class SphereColorPass extends ColorPass { - /** - * Position of the sphere relative to the planet. - */ - public Vec3 pos; - /** - * Radius of the sphere. - */ - public float radius; - /** - * Color painted inside the sphere. - */ - public Color out; + /** + * A pass that paints points inside a sphere. + * @see HeightPass.SphereHeight SphereHeight + */ + public static class SphereColorPass extends ColorPass{ + /** + * Position of the sphere relative to the planet. + */ + public Vec3 pos; + /** + * Radius of the sphere. + */ + public float radius; + /** + * Color painted inside the sphere. + */ + public Color out; - public SphereColorPass(Vec3 pos, float radius, Color out) { - this.pos = pos; - this.radius = radius; - this.out = out; - } + public SphereColorPass(Vec3 pos, float radius, Color out){ + this.pos = pos; + this.radius = radius; + this.out = out; + } - @Override - public Color color(Vec3 pos, float height) { - if (pos.dst(this.pos) < radius) return out; - return null; - } - } - /** - * A pass that uses noise to fill regions on the planet. - * @see HeightPass.NoiseHeight NoiseHeight - */ - public static class NoiseColorPass extends ColorPass { - /** - * Offset for the noise sample relative to the planet. Values far away from the origin are reccomended. - */ - public Vec3 offset = new Vec3(); - /** - * Noise seed. - */ - public int seed; - /** - * The amount of octves added to the noise. - */ - public double octaves = 1.0; - /** - * Intensity multiplier for each octave. - */ - public double persistence = 1.0; - /** - * Noise scale. - */ - public double scale = 1.0; - /** - * Noise magnitude. - */ - public float magnitude = 1; - /** - * Min and max treshold values of noise that paint will apply - */ - public float min = 0f, max = 1f; - /** - * Color painted based on the noise. - */ - public Color out = Color.white; + @Override + public Color color(Vec3 pos, float height){ + if(pos.dst(this.pos) < radius) return out; + return null; + } + } - @Override - public Color color(Vec3 pos, float height) { - float noise = Simplex.noise3d(seed, octaves, persistence, scale, pos.x + offset.x, pos.y + offset.y, pos.z + offset.z) * magnitude; - if (min <= noise && noise <= max) return out; - return null; - } - } - /** - * A pass that paints regions whose height is within a boundary. - * @see HeightPass.ClampHeight ClampHeight - */ - public static class FlatColorPass extends ColorPass { - public float min = 0f, max = 1f; - public Color out = Color.white; + /** + * A pass that uses noise to fill regions on the planet. + * @see HeightPass.NoiseHeight NoiseHeight + */ + public static class NoiseColorPass extends ColorPass{ + /** + * Offset for the noise sample relative to the planet. Values far away from the origin are reccomended. + */ + public Vec3 offset = new Vec3(); + /** + * Noise seed. + */ + public int seed; + /** + * The amount of octves added to the noise. + */ + public double octaves = 1.0; + /** + * Intensity multiplier for each octave. + */ + public double persistence = 1.0; + /** + * Noise scale. + */ + public double scale = 1.0; + /** + * Noise magnitude. + */ + public float magnitude = 1; + /** + * Min and max treshold values of noise that paint will apply + */ + public float min = 0f, max = 1f; + /** + * Color painted based on the noise. + */ + public Color out = Color.white; - @Override - public Color color(Vec3 pos, float height) { - if (min <= height && height <= max) return out; - return null; - } - } + @Override + public Color color(Vec3 pos, float height){ + float noise = Simplex.noise3d(seed, octaves, persistence, scale, pos.x + offset.x, pos.y + offset.y, pos.z + offset.z) * magnitude; + if(min <= noise && noise <= max) return out; + return null; + } + } + + /** + * A pass that paints regions whose height is within a boundary. + * @see HeightPass.ClampHeight ClampHeight + */ + public static class FlatColorPass extends ColorPass{ + public float min = 0f, max = 1f; + public Color out = Color.white; + + @Override + public Color color(Vec3 pos, float height){ + if(min <= height && height <= max) return out; + return null; + } + } } \ No newline at end of file diff --git a/src/omaloon/maps/HeightPass.java b/src/omaloon/maps/HeightPass.java index 2ca27195..baced732 100644 --- a/src/omaloon/maps/HeightPass.java +++ b/src/omaloon/maps/HeightPass.java @@ -8,203 +8,209 @@ /** * a pass for custom height for a planet mesh */ -public abstract class HeightPass { - public abstract float height(Vec3 pos, float height); - - public boolean valid(Vec3 pos, float height) { - return true; - } - - /** - * A pass that affects points inside a sphere. - */ - public static class SphereHeight extends HeightPass { - /** - * Position of the sphere relative to the planet. - */ - public Vec3 pos = new Vec3(); - /** - * Radius of the sphere. - */ - public float radius = 0f; - /** - * Height offset applied inside the sphere - */ - public float offset = 0f; - /** - * When true, this pass will set the current height to the offset instead of increasing the height by the offset. - */ - public boolean set = false; - - @Override - public float height(Vec3 pos, float height) { - if (!valid(pos, height)) return height; - if (pos.dst(this.pos) < radius) return offset + height * (set ? 0f : 1f); - return height; - } - } - /** - * A pass that affects points based on noise. - * @see Simplex - */ - public static class NoiseHeight extends HeightPass { - /** - * Offset for the noise sample relative to the planet. Values far away from the origin are reccomended. - */ - public Vec3 offset = new Vec3(); - /** - * Noise seed. - */ - public int seed; - /** - * The amount of octves added to the noise. - */ - public double octaves = 1.0; - /** - * Intensity multiplier for each octave. - */ - public double persistence = 1.0; - /** - * Noise scale. - */ - public double scale = 1.0; - /** - * Noise magnitude. - */ - public float magnitude = 1; - /** - * Value offset applied to the noise result. - */ - public float heightOffset = 0; - - @Override - public float height(Vec3 pos, float height) { - return Simplex.noise3d(seed, octaves, persistence, scale, pos.x + offset.x, pos.y + offset.y, pos.z + offset.z) * magnitude + heightOffset + height; - } - } - /** - * A pass that clamps the current point's height between a min and max value. - */ - public static class ClampHeight extends HeightPass { - public float min, max; - - public ClampHeight(float min, float max) { - this.min = min; - this.max = max; - } - - @Override - public float height(Vec3 pos, float height) { - return Mathf.clamp(height, min, max); - } - } - /** - * A pass that affects points based on it's dot product in relation to a direction. - */ - public static class DotHeight extends HeightPass { - /** - * Main direction vector. Is normalized later. - */ - public Vec3 dir = new Vec3(); - - /** - * Min and max dot result where this pass applies. - */ - public float min = -1f; - public float max = 1f; - - /** - * When true, the dot result will be mapped from min to max instead of -1 to 1. - */ - public boolean map = true; - - /** - * Interpolation curve applied to the mapped dot result. - */ - public Interp interp = Interp.linear; - /** - * Magnitude applied to the final height offset. - */ - public float magnitude = 1; - - @Override - public float height(Vec3 pos, float height) { - if (!valid(pos, height)) return height; - float dot = dir.nor().dot(pos); - dot = Mathf.map(dot, map ? min : -1f, map ? max : 1f, 0f, 1f); - return interp.apply(dot) * magnitude + height; - } - - @Override - public boolean valid(Vec3 pos, float height) { - float dot = dir.nor().dot(pos); - return dot >= min && dot <= max; - } - } - /** - * A pass that preclaculates the height of multiple other passes. so that they're applied all at once. - */ - public static class MultiHeight extends HeightPass { - /** - * Heights used to create the raw height value. - */ - public Seq heights; - /** - * Height mixing type for the raw height, can either get the highest, or average between results. - */ - public MixType mixType; - /** - * Operation applied to the final height, can either add, subtract(carve) or set to this height. - */ - public Operation operation; - - public MultiHeight(Seq heights, MixType mixType, Operation operation) { - this.heights = heights; - this.mixType = mixType; - this.operation = operation; - } - - @Override - public float height(Vec3 pos, float height) { - if (!valid(pos, height)) return height; - switch (operation) { - case add -> { - return height + rawHeight(pos, height); - } - case set -> { - return rawHeight(pos, height); - } - case carve -> { - return height - rawHeight(pos, height); - } - } - return height; - } - float rawHeight(Vec3 pos, float base) { - switch (mixType) { - case max -> { - return heights.select(pass -> pass.valid(pos, base)).max(pass -> pass.height(pos, base)).height(pos, base); - } - case average -> { - return heights.select(pass -> pass.valid(pos, base)).sumf(pass -> pass.height(pos, base))/(float)heights.size; - } - case min -> { - return heights.select(pass -> pass.valid(pos, base)).min(pass -> pass.height(pos, base)).height(pos, base); - } - } - return 0f; - } - - @Override - public boolean valid(Vec3 pos, float height) { - return heights.contains(pass -> pass.valid(pos, height)); - } - - public enum MixType { - max, average, min - } - public enum Operation { - add, set, carve - } - } +public abstract class HeightPass{ + public abstract float height(Vec3 pos, float height); + + public boolean valid(Vec3 pos, float height){ + return true; + } + + /** + * A pass that affects points inside a sphere. + */ + public static class SphereHeight extends HeightPass{ + /** + * Position of the sphere relative to the planet. + */ + public Vec3 pos = new Vec3(); + /** + * Radius of the sphere. + */ + public float radius = 0f; + /** + * Height offset applied inside the sphere + */ + public float offset = 0f; + /** + * When true, this pass will set the current height to the offset instead of increasing the height by the offset. + */ + public boolean set = false; + + @Override + public float height(Vec3 pos, float height){ + if(!valid(pos, height)) return height; + if(pos.dst(this.pos) < radius) return offset + height * (set ? 0f : 1f); + return height; + } + } + + /** + * A pass that affects points based on noise. + * @see Simplex + */ + public static class NoiseHeight extends HeightPass{ + /** + * Offset for the noise sample relative to the planet. Values far away from the origin are reccomended. + */ + public Vec3 offset = new Vec3(); + /** + * Noise seed. + */ + public int seed; + /** + * The amount of octves added to the noise. + */ + public double octaves = 1.0; + /** + * Intensity multiplier for each octave. + */ + public double persistence = 1.0; + /** + * Noise scale. + */ + public double scale = 1.0; + /** + * Noise magnitude. + */ + public float magnitude = 1; + /** + * Value offset applied to the noise result. + */ + public float heightOffset = 0; + + @Override + public float height(Vec3 pos, float height){ + return Simplex.noise3d(seed, octaves, persistence, scale, pos.x + offset.x, pos.y + offset.y, pos.z + offset.z) * magnitude + heightOffset + height; + } + } + + /** + * A pass that clamps the current point's height between a min and max value. + */ + public static class ClampHeight extends HeightPass{ + public float min, max; + + public ClampHeight(float min, float max){ + this.min = min; + this.max = max; + } + + @Override + public float height(Vec3 pos, float height){ + return Mathf.clamp(height, min, max); + } + } + + /** + * A pass that affects points based on it's dot product in relation to a direction. + */ + public static class DotHeight extends HeightPass{ + /** + * Main direction vector. Is normalized later. + */ + public Vec3 dir = new Vec3(); + + /** + * Min and max dot result where this pass applies. + */ + public float min = -1f; + public float max = 1f; + + /** + * When true, the dot result will be mapped from min to max instead of -1 to 1. + */ + public boolean map = true; + + /** + * Interpolation curve applied to the mapped dot result. + */ + public Interp interp = Interp.linear; + /** + * Magnitude applied to the final height offset. + */ + public float magnitude = 1; + + @Override + public float height(Vec3 pos, float height){ + if(!valid(pos, height)) return height; + float dot = dir.nor().dot(pos); + dot = Mathf.map(dot, map ? min : -1f, map ? max : 1f, 0f, 1f); + return interp.apply(dot) * magnitude + height; + } + + @Override + public boolean valid(Vec3 pos, float height){ + float dot = dir.nor().dot(pos); + return dot >= min && dot <= max; + } + } + + /** + * A pass that preclaculates the height of multiple other passes. so that they're applied all at once. + */ + public static class MultiHeight extends HeightPass{ + /** + * Heights used to create the raw height value. + */ + public Seq heights; + /** + * Height mixing type for the raw height, can either get the highest, or average between results. + */ + public MixType mixType; + /** + * Operation applied to the final height, can either add, subtract(carve) or set to this height. + */ + public Operation operation; + + public MultiHeight(Seq heights, MixType mixType, Operation operation){ + this.heights = heights; + this.mixType = mixType; + this.operation = operation; + } + + @Override + public float height(Vec3 pos, float height){ + if(!valid(pos, height)) return height; + switch(operation){ + case add -> { + return height + rawHeight(pos, height); + } + case set -> { + return rawHeight(pos, height); + } + case carve -> { + return height - rawHeight(pos, height); + } + } + return height; + } + + float rawHeight(Vec3 pos, float base){ + switch(mixType){ + case max -> { + return heights.select(pass -> pass.valid(pos, base)).max(pass -> pass.height(pos, base)).height(pos, base); + } + case average -> { + return heights.select(pass -> pass.valid(pos, base)).sumf(pass -> pass.height(pos, base)) / (float)heights.size; + } + case min -> { + return heights.select(pass -> pass.valid(pos, base)).min(pass -> pass.height(pos, base)).height(pos, base); + } + } + return 0f; + } + + @Override + public boolean valid(Vec3 pos, float height){ + return heights.contains(pass -> pass.valid(pos, height)); + } + + public enum MixType{ + max, average, min + } + + public enum Operation{ + add, set, carve + } + } } diff --git a/src/omaloon/maps/planets/GlasmorePlanetGenerator.java b/src/omaloon/maps/planets/GlasmorePlanetGenerator.java index d9f0ef22..5c081faa 100644 --- a/src/omaloon/maps/planets/GlasmorePlanetGenerator.java +++ b/src/omaloon/maps/planets/GlasmorePlanetGenerator.java @@ -7,36 +7,36 @@ import mindustry.type.*; import omaloon.maps.*; -public class GlasmorePlanetGenerator extends PlanetGenerator { - public Seq heights = new Seq<>(); - public Seq colors = new Seq<>(); - public float baseHeight = 1; - public Color baseColor = Color.white; +public class GlasmorePlanetGenerator extends PlanetGenerator{ + public Seq heights = new Seq<>(); + public Seq colors = new Seq<>(); + public float baseHeight = 1; + public Color baseColor = Color.white; - public float rawHeight(Vec3 position) { - float height = baseHeight; - for (HeightPass h : heights) { - height = h.height(position, height); - } - return height; - } + public float rawHeight(Vec3 position){ + float height = baseHeight; + for(HeightPass h : heights){ + height = h.height(position, height); + } + return height; + } - @Override - public void generateSector(Sector sector) { + @Override + public void generateSector(Sector sector){ - } + } - @Override - public float getHeight(Vec3 position) { - return rawHeight(position); - } + @Override + public float getHeight(Vec3 position){ + return rawHeight(position); + } - @Override - public Color getColor(Vec3 position) { - Color color = baseColor; - for (ColorPass c : colors) { - if (c.color(position, rawHeight(position)) != null) color = c.color(position, rawHeight(position)); - } - return color; - } + @Override + public Color getColor(Vec3 position){ + Color color = baseColor; + for(ColorPass c : colors){ + if(c.color(position, rawHeight(position)) != null) color = c.color(position, rawHeight(position)); + } + return color; + } } diff --git a/src/omaloon/maps/planets/PurpuraPlanetGenerator.java b/src/omaloon/maps/planets/PurpuraPlanetGenerator.java index a81f2e5b..e7ed4fa2 100644 --- a/src/omaloon/maps/planets/PurpuraPlanetGenerator.java +++ b/src/omaloon/maps/planets/PurpuraPlanetGenerator.java @@ -7,29 +7,30 @@ import arc.util.noise.*; import mindustry.maps.generators.*; -import static arc.graphics.Color.*; +import static arc.graphics.Color.valueOf; -public class PurpuraPlanetGenerator extends PlanetGenerator { - public double octaves = 5, persistence = 0.3, scl = 3.0, pow = 1.2, mag = 1; - public float rotationScl = 360; +public class PurpuraPlanetGenerator extends PlanetGenerator{ + public double octaves = 5, persistence = 0.3, scl = 3.0, pow = 1.2, mag = 1; + public float rotationScl = 360; - public Color[] colors = new Color[]{ - valueOf("242424"), - valueOf("413B42"), - valueOf("7F777E"), - valueOf("B2B2B2"), - valueOf("807881"), - valueOf("4F424D") - }; + public Color[] colors = new Color[]{ + valueOf("242424"), + valueOf("413B42"), + valueOf("7F777E"), + valueOf("B2B2B2"), + valueOf("807881"), + valueOf("4F424D") + }; - @Override public float getHeight(Vec3 position) { - return 0; - } + @Override + public float getHeight(Vec3 position){ + return 0; + } - @Override - public Color getColor(Vec3 position) { - Tmp.v31.set(position).rotate(Vec3.Y, position.y * rotationScl).add(1000f, 0f, 500f); - double height = Math.pow(Simplex.noise3d(0, octaves, persistence, scl, Tmp.v31.x, Tmp.v31.y, Tmp.v31.z), pow) * mag; - return Tmp.c1.set(colors[Mathf.clamp((int)(height * colors.length), 0, colors.length - 1)]); - } + @Override + public Color getColor(Vec3 position){ + Tmp.v31.set(position).rotate(Vec3.Y, position.y * rotationScl).add(1000f, 0f, 500f); + double height = Math.pow(Simplex.noise3d(0, octaves, persistence, scl, Tmp.v31.x, Tmp.v31.y, Tmp.v31.z), pow) * mag; + return Tmp.c1.set(colors[Mathf.clamp((int)(height * colors.length), 0, colors.length - 1)]); + } } diff --git a/src/omaloon/math/Math3D.java b/src/omaloon/math/Math3D.java index 33a14fff..dc2654a1 100644 --- a/src/omaloon/math/Math3D.java +++ b/src/omaloon/math/Math3D.java @@ -1,18 +1,18 @@ package omaloon.math; -import mindustry.Vars; +import mindustry.*; import static arc.Core.camera; import static arc.math.Mathf.dst; -public class Math3D { +public class Math3D{ /** * @author MEEP, modified by RandomJelly * From prog-mat-java * https://github.com/MEEPofFaith/prog-mats-java - * */ + */ - public static final float horiToVerti = 1f/48f; + public static final float horiToVerti = 1f / 48f; public static float xOffset(float x, float height){ return (x - camera.position.x) * hMul(height); diff --git a/src/omaloon/math/OlMath.java b/src/omaloon/math/OlMath.java index 3a5fee21..728e9c6c 100644 --- a/src/omaloon/math/OlMath.java +++ b/src/omaloon/math/OlMath.java @@ -1,33 +1,33 @@ package omaloon.math; -public class OlMath { - /** - * Solves for the flow of a fluid through an area based on a difference of pressure. - *
      - *
    • pressureStart is the pressure at the back - *
    • pressureEnd is the pressure at the front - *
    • capacityStart is the fluid capacity at the back - *
    • capacityEnd is the fluid capacity at the front - *
    • density is the fluid density - *
    • viscosity is the fluid viscosity - *
    - * - * returns the amount of fluid in liquid units that flows per tick - */ - public static float flowRate(float pressureStart, float pressureEnd, float capacityStart, float capacityEnd, float density, float viscosity) { - return - ( - capacityStart * ( - pressureStart * ( - capacityStart + capacityEnd - ) - ( - pressureEnd * capacityEnd + pressureStart * capacityStart - ) - ) - ) / ( - density * ( - capacityStart + capacityEnd - ) * viscosity - ); - } +public class OlMath{ + /** + * Solves for the flow of a fluid through an area based on a difference of pressure. + *
      + *
    • pressureStart is the pressure at the back + *
    • pressureEnd is the pressure at the front + *
    • capacityStart is the fluid capacity at the back + *
    • capacityEnd is the fluid capacity at the front + *
    • density is the fluid density + *
    • viscosity is the fluid viscosity + *
    + *

    + * returns the amount of fluid in liquid units that flows per tick + */ + public static float flowRate(float pressureStart, float pressureEnd, float capacityStart, float capacityEnd, float density, float viscosity){ + return + ( + capacityStart * ( + pressureStart * ( + capacityStart + capacityEnd + ) - ( + pressureEnd * capacityEnd + pressureStart * capacityStart + ) + ) + ) / ( + density * ( + capacityStart + capacityEnd + ) * viscosity + ); + } } diff --git a/src/omaloon/struct/BitWordList.java b/src/omaloon/struct/BitWordList.java index 935cf159..08a4f5d3 100644 --- a/src/omaloon/struct/BitWordList.java +++ b/src/omaloon/struct/BitWordList.java @@ -8,7 +8,7 @@ public class BitWordList{ final byte wordLen; final short wordMask; - public final int initialWordsAmount; + public final int initialWordsAmount; long[] bits = {0}; @@ -20,7 +20,7 @@ public class BitWordList{ */ public BitWordList(int nwords, WordLength wordLen){ checkCapacity(nwords * wordLen.value >>> 6); - this.initialWordsAmount =nwords; + this.initialWordsAmount = nwords; this.wordLen = wordLen.value; wordMask = (short)~(~1 << (wordLen.value - 1)); @@ -43,7 +43,7 @@ public byte get(int index){ if(wordPosition >= bits.length){ throw new IndexOutOfBoundsException(); } - index = (index*wordLen) & 63; + index = (index * wordLen) & 63; return (byte)(bits[wordPosition] >>> index & wordMask); } @@ -54,10 +54,10 @@ public byte get(int index){ public void set(int index, byte number){ final int wordIndex = index * wordLen >>> 6; - index = (index*wordLen)&63; + index = (index * wordLen) & 63; number &= wordMask; checkCapacity(wordIndex); - bits[wordIndex] &=~((long)wordMask <not the highset set bit! */ public int size(){ - return bits.length << 6/ wordLen ; + return bits.length << 6 / wordLen; } /** @@ -93,9 +93,9 @@ public int nonZeroLength(){ for(int word = bits.length - 1; word >= 0; --word){ long bitsAtWord = bits[word]; if(bitsAtWord != 0){ - for(int bit = 63; bit >= 0; bit-=wordLen){ + for(int bit = 63; bit >= 0; bit -= wordLen){ if((bitsAtWord & ((long)wordMask << bit)) != 0L){ - return ((word << 6) + bit + 1)/wordLen; + return ((word << 6) + bit + 1) / wordLen; } } } diff --git a/src/omaloon/struct/IntRef.java b/src/omaloon/struct/IntRef.java index bf689373..fbd0a5cc 100644 --- a/src/omaloon/struct/IntRef.java +++ b/src/omaloon/struct/IntRef.java @@ -1,24 +1,23 @@ package omaloon.struct; -public class IntRef { +public class IntRef{ public static final IntRef - tmp1=new IntRef(), - tmp2=new IntRef(), - tmp3=new IntRef(), - tmp4=new IntRef() - ; + tmp1 = new IntRef(), + tmp2 = new IntRef(), + tmp3 = new IntRef(), + tmp4 = new IntRef(); public int value; public IntRef zero(){ - value=0; + value = 0; return this; } - public IntRef(int value) { + public IntRef(int value){ this.value = value; } - public IntRef() { + public IntRef(){ } } diff --git a/src/omaloon/type/BetterPlanet.java b/src/omaloon/type/BetterPlanet.java index 2917e28e..12c43ceb 100644 --- a/src/omaloon/type/BetterPlanet.java +++ b/src/omaloon/type/BetterPlanet.java @@ -6,10 +6,10 @@ import arc.graphics.gl.*; import arc.math.geom.*; import arc.util.*; -import omaloon.graphics.*; import mindustry.graphics.*; import mindustry.graphics.g3d.*; import mindustry.type.*; +import omaloon.graphics.*; import static arc.Core.*; import static mindustry.Vars.*; diff --git a/src/omaloon/type/Blade.java b/src/omaloon/type/Blade.java index 5eaa42e4..ca6500ee 100644 --- a/src/omaloon/type/Blade.java +++ b/src/omaloon/type/Blade.java @@ -4,7 +4,7 @@ import arc.graphics.g2d.*; import mindustry.io.*; -public class Blade { +public class Blade{ public final String spriteName; public TextureRegion bladeRegion, blurRegion, bladeOutlineRegion, shadeRegion; @@ -24,7 +24,7 @@ public class Blade { public float blurAlpha = 0.9f; - public Blade(String name) { + public Blade(String name){ this.spriteName = name; } @@ -37,7 +37,7 @@ public BladeMount(Blade blade){ } } - public void load() { + public void load(){ bladeRegion = Core.atlas.find(spriteName); blurRegion = Core.atlas.find(spriteName + "-blur"); bladeOutlineRegion = Core.atlas.find(spriteName + "-outline"); @@ -45,7 +45,7 @@ public void load() { } // For mirroring - public Blade copy() { + public Blade copy(){ return JsonIO.copy(this, new Blade(spriteName)); } } \ No newline at end of file diff --git a/src/omaloon/type/DroneUnitType.java b/src/omaloon/type/DroneUnitType.java index b7069454..da5a2698 100644 --- a/src/omaloon/type/DroneUnitType.java +++ b/src/omaloon/type/DroneUnitType.java @@ -2,8 +2,8 @@ import omaloon.gen.*; -public class DroneUnitType extends GlassmoreUnitType { - public DroneUnitType(String name) { +public class DroneUnitType extends GlassmoreUnitType{ + public DroneUnitType(String name){ super(name); hidden = flying = true; playerControllable = logicControllable = false; diff --git a/src/omaloon/type/ExtraSectorPreset.java b/src/omaloon/type/ExtraSectorPreset.java index 0d79682f..f811cc97 100644 --- a/src/omaloon/type/ExtraSectorPreset.java +++ b/src/omaloon/type/ExtraSectorPreset.java @@ -6,30 +6,31 @@ import mindustry.game.*; import mindustry.type.*; -public class ExtraSectorPreset extends SectorPreset { - public static ObjectMap scripts = new ObjectMap<>(); +public class ExtraSectorPreset extends SectorPreset{ + public static ObjectMap scripts = new ObjectMap<>(); - static { - Events.run(EventType.Trigger.update, () -> { - if (Vars.state.getSector() != null) scripts.get(Vars.state.getSector(), () -> {}).run(); - }); - } + static{ + Events.run(EventType.Trigger.update, () -> { + if(Vars.state.getSector() != null) scripts.get(Vars.state.getSector(), () -> { + }).run(); + }); + } - public ExtraSectorPreset(String name, Planet planet, int sector, Runnable run) { - this(name, planet, sector); - scripts.put(this.sector, run); - } + public ExtraSectorPreset(String name, Planet planet, int sector, Runnable run){ + this(name, planet, sector); + scripts.put(this.sector, run); + } - public ExtraSectorPreset(String name, Planet planet, int sector) { - super(name, planet, sector); - } + public ExtraSectorPreset(String name, Planet planet, int sector){ + super(name, planet, sector); + } - /** - * returns true if a flag is present. - */ - public static boolean getFlag(String flag, boolean remove) { - if (Vars.state.rules.objectiveFlags.isEmpty()) return false; - if (remove) return Vars.state.rules.objectiveFlags.remove(flag); - return Vars.state.rules.objectiveFlags.contains(flag); - } + /** + * returns true if a flag is present. + */ + public static boolean getFlag(String flag, boolean remove){ + if(Vars.state.rules.objectiveFlags.isEmpty()) return false; + if(remove) return Vars.state.rules.objectiveFlags.remove(flag); + return Vars.state.rules.objectiveFlags.contains(flag); + } } diff --git a/src/omaloon/type/FilterWeapon.java b/src/omaloon/type/FilterWeapon.java index 98f5b02a..92a94973 100644 --- a/src/omaloon/type/FilterWeapon.java +++ b/src/omaloon/type/FilterWeapon.java @@ -17,56 +17,56 @@ /** * a weapon that shoots different things depending on things in a unit */ -public class FilterWeapon extends Weapon { - /** - * separate from bulletFilter for stats - */ - public BulletType[] bullets = new BulletType[] {Bullets.placeholder}; - public Func bulletFilter = unit -> bullets[0]; -// TODO i don't know how to make those icons work, and i have no clue as to why it is casting a string to BulletType - public TextureRegion[] iconRegions; - public String[] icons = new String[] {""}; +public class FilterWeapon extends Weapon{ + /** + * separate from bulletFilter for stats + */ + public BulletType[] bullets = new BulletType[]{Bullets.placeholder}; + public Func bulletFilter = unit -> bullets[0]; + // TODO i don't know how to make those icons work, and i have no clue as to why it is casting a string to BulletType + public TextureRegion[] iconRegions; + public String[] icons = new String[]{""}; - @Override - public void addStats(UnitType u, Table t) { - if(inaccuracy > 0){ - t.row(); - t.add("[lightgray]" + Stat.inaccuracy.localized() + ": [white]" + (int)inaccuracy + " " + StatUnit.degrees.localized()); - } - if(!alwaysContinuous && reload > 0){ - t.row(); - t.add("[lightgray]" + Stat.reload.localized() + ": " + (mirror ? "2x " : "") + "[white]" + Strings.autoFixed(60f / reload * shoot.shots, 2) + " " + StatUnit.perSecond.localized()); - } + @Override + public void addStats(UnitType u, Table t){ + if(inaccuracy > 0){ + t.row(); + t.add("[lightgray]" + Stat.inaccuracy.localized() + ": [white]" + (int)inaccuracy + " " + StatUnit.degrees.localized()); + } + if(!alwaysContinuous && reload > 0){ + t.row(); + t.add("[lightgray]" + Stat.reload.localized() + ": " + (mirror ? "2x " : "") + "[white]" + Strings.autoFixed(60f / reload * shoot.shots, 2) + " " + StatUnit.perSecond.localized()); + } - t.row(); - t.table(Styles.grayPanel, weapon -> { - for(int i = 0; i < bullets.length; i++) { - int finalI = i; - weapon.table(Tex.underline, b -> { - b.left(); - if (iconRegions[finalI].found()) b.image(iconRegions[finalI]).padRight(10).center(); - StatValues.ammo(ObjectMap.of(u, bullets[finalI])).display(b.add(new Table()).get()); - }).growX().row(); - } - }).margin(10f); - } + t.row(); + t.table(Styles.grayPanel, weapon -> { + for(int i = 0; i < bullets.length; i++){ + int finalI = i; + weapon.table(Tex.underline, b -> { + b.left(); + if(iconRegions[finalI].found()) b.image(iconRegions[finalI]).padRight(10).center(); + StatValues.ammo(ObjectMap.of(u, bullets[finalI])).display(b.add(new Table()).get()); + }).growX().row(); + } + }).margin(10f); + } - @Override - public void load() { - super.load(); - iconRegions = new TextureRegion[bullets.length]; - for(int i = 0; i < iconRegions.length; i++) { - if (i < icons.length) { - iconRegions[i] = Core.atlas.find(icons[i]); - } else { - iconRegions[i] = Core.atlas.find("error"); - } - } - } + @Override + public void load(){ + super.load(); + iconRegions = new TextureRegion[bullets.length]; + for(int i = 0; i < iconRegions.length; i++){ + if(i < icons.length){ + iconRegions[i] = Core.atlas.find(icons[i]); + }else{ + iconRegions[i] = Core.atlas.find("error"); + } + } + } - @Override - protected void shoot(Unit unit, WeaponMount mount, float shootX, float shootY, float rotation) { - bullet = bulletFilter.get(unit); - super.shoot(unit, mount, shootX, shootY, rotation); - } + @Override + protected void shoot(Unit unit, WeaponMount mount, float shootX, float shootY, float rotation){ + bullet = bulletFilter.get(unit); + super.shoot(unit, mount, shootX, shootY, rotation); + } } diff --git a/src/omaloon/type/GlassmoreUnitType.java b/src/omaloon/type/GlassmoreUnitType.java index 1f4aab68..645fa705 100644 --- a/src/omaloon/type/GlassmoreUnitType.java +++ b/src/omaloon/type/GlassmoreUnitType.java @@ -3,14 +3,14 @@ import arc.graphics.*; import arc.graphics.g2d.*; import arc.math.*; -import arc.math.geom.Vec2; +import arc.math.geom.*; import arc.util.*; -import mindustry.Vars; +import mindustry.*; import mindustry.content.*; -import mindustry.entities.abilities.Ability; +import mindustry.entities.abilities.*; import mindustry.entities.effect.*; -import mindustry.entities.part.DrawPart; -import mindustry.entities.units.WeaponMount; +import mindustry.entities.part.*; +import mindustry.entities.units.*; import mindustry.gen.*; import mindustry.graphics.*; import mindustry.type.*; @@ -23,9 +23,10 @@ import static mindustry.Vars.player; -public class GlassmoreUnitType extends UnitType { +public class GlassmoreUnitType extends UnitType{ private static final Vec2 legOffset = new Vec2(); - public GlassmoreUnitType(String name) { + + public GlassmoreUnitType(String name){ super(name); outlineColor = Color.valueOf("2f2f36"); envDisabled = Env.space; @@ -41,7 +42,7 @@ public GlassmoreUnitType(String name) { } @Override - public void draw(Unit unit) { + public void draw(Unit unit){ if(unit.inFogTo(Vars.player.team())) return; boolean isPayload = !unit.isAdded(); @@ -65,10 +66,10 @@ public void draw(Unit unit) { drawMech(floatMech); //side - legOffset.trns(floatMech.baseRotation(), 0f, Mathf.lerp(Mathf.sin(floatMech.walkExtend(true), 2f/Mathf.PI, 1) * mechSideSway, 0f, unit.elevation)); + legOffset.trns(floatMech.baseRotation(), 0f, Mathf.lerp(Mathf.sin(floatMech.walkExtend(true), 2f / Mathf.PI, 1) * mechSideSway, 0f, unit.elevation)); //front - legOffset.add(Tmp.v1.trns(floatMech.baseRotation() + 90, 0f, Mathf.lerp(Mathf.sin(floatMech.walkExtend(true), 1f/Mathf.PI, 1) * mechFrontSway, 0f, unit.elevation))); + legOffset.add(Tmp.v1.trns(floatMech.baseRotation() + 90, 0f, Mathf.lerp(Mathf.sin(floatMech.walkExtend(true), 1f / Mathf.PI, 1) * mechFrontSway, 0f, unit.elevation))); unit.trns(legOffset.x, legOffset.y); } @@ -77,10 +78,10 @@ public void draw(Unit unit) { drawMech(mech); //side - legOffset.trns(mech.baseRotation(), 0f, Mathf.lerp(Mathf.sin(mech.walkExtend(true), 2f/Mathf.PI, 1) * mechSideSway, 0f, unit.elevation)); + legOffset.trns(mech.baseRotation(), 0f, Mathf.lerp(Mathf.sin(mech.walkExtend(true), 2f / Mathf.PI, 1) * mechSideSway, 0f, unit.elevation)); //front - legOffset.add(Tmp.v1.trns(mech.baseRotation() + 90, 0f, Mathf.lerp(Mathf.sin(mech.walkExtend(true), 1f/Mathf.PI, 1) * mechFrontSway, 0f, unit.elevation))); + legOffset.add(Tmp.v1.trns(mech.baseRotation() + 90, 0f, Mathf.lerp(Mathf.sin(mech.walkExtend(true), 1f / Mathf.PI, 1) * mechFrontSway, 0f, unit.elevation))); unit.trns(legOffset.x, legOffset.y); } @@ -184,11 +185,11 @@ public void drawMech(FloatMechc floatMech){ Draw.mixcol(Tmp.c1.set(mechLegColor).lerp(Color.white, Mathf.clamp(unit.hitTime)), Math.max(Math.max(0, i * extension / mechStride), unit.hitTime)); Draw.rect(legRegion, - unit.x + Angles.trnsx(floatMech.baseRotation(), extension * i - boostTrns, -boostTrns*i), - unit.y + Angles.trnsy(floatMech.baseRotation(), extension * i - boostTrns, -boostTrns*i), - legRegion.width * legRegion.scl() * i, - legRegion.height * legRegion.scl() * (1 - Math.max(-sin * i, 0) * 0.5f), - floatMech.baseRotation() - 90 + 35f*i*e); + unit.x + Angles.trnsx(floatMech.baseRotation(), extension * i - boostTrns, -boostTrns * i), + unit.y + Angles.trnsy(floatMech.baseRotation(), extension * i - boostTrns, -boostTrns * i), + legRegion.width * legRegion.scl() * i, + legRegion.height * legRegion.scl() * (1 - Math.max(-sin * i, 0) * 0.5f), + floatMech.baseRotation() - 90 + 35f * i * e); } Draw.mixcol(Color.white, unit.hitTime); diff --git a/src/omaloon/type/MillipedeDecal.java b/src/omaloon/type/MillipedeDecal.java index 2c5f11a6..c5efc966 100644 --- a/src/omaloon/type/MillipedeDecal.java +++ b/src/omaloon/type/MillipedeDecal.java @@ -6,7 +6,7 @@ import arc.math.geom.*; import mindustry.gen.*; -import static arc.Core.*; +import static arc.Core.atlas; public class MillipedeDecal{ private final static Vec2 v1 = new Vec2(); diff --git a/src/omaloon/type/MillipedeUnitType.java b/src/omaloon/type/MillipedeUnitType.java index a114ea73..1a52ac29 100644 --- a/src/omaloon/type/MillipedeUnitType.java +++ b/src/omaloon/type/MillipedeUnitType.java @@ -13,13 +13,12 @@ import mindustry.gen.*; import mindustry.graphics.*; import mindustry.type.*; -import omaloon.gen.*; -import static arc.Core.*; +import static arc.Core.atlas; -public class MillipedeUnitType extends GlassmoreUnitType { +public class MillipedeUnitType extends GlassmoreUnitType{ public TextureRegion segmentRegion, tailRegion, segmentCellRegion, tailCellRegion, - segmentOutline, tailOutline; + segmentOutline, tailOutline; public Seq bottomWeapons = new Seq<>(); //Millipedes /** @@ -30,7 +29,7 @@ public class MillipedeUnitType extends GlassmoreUnitType { /** * Min amount of segments required for this chain, any less and everything dies. */ - public int minSegments = 3; + public int minSegments = 3; // TODO rename /** * Max amount of segments that this chain can grow to. @@ -84,11 +83,11 @@ public class MillipedeUnitType extends GlassmoreUnitType { public final Seq> chainWeapons = new Seq<>(); public Intf weaponsIndex = unit -> { - if (unit instanceof Chainedc chain) return chain.countForward(); + if(unit instanceof Chainedc chain) return chain.countForward(); else return 0; }; - public MillipedeUnitType(String name) { + public MillipedeUnitType(String name){ super(name); } @@ -98,7 +97,7 @@ public Unit create(Team team){ } @Override - public void load() { + public void load(){ super.load(); //worm if(millipedeDecal != null) millipedeDecal.load(); @@ -109,14 +108,14 @@ public void load() { segmentOutline = atlas.find(name + "-segment-outline"); tailOutline = atlas.find(name + "-tail-outline"); - chainWeapons.each(w -> w.each(Weapon::load)); + chainWeapons.each(w -> w.each(Weapon::load)); } @Override - public void init() { + public void init(){ super.init(); - if (segmentOffset < 0) segmentOffset = hitSize * 2f; + if(segmentOffset < 0) segmentOffset = hitSize * 2f; chainWeapons.each(w -> { sortSegWeapons(w); @@ -152,7 +151,7 @@ public void sortSegWeapons(Seq weaponSeq){ weaponSeq.set(mapped); } - public void drawWorm(T unit){ + public void drawWorm(T unit){ Mechc mech = unit instanceof Mechc ? (Mechc)unit : null; float z = (unit.elevation > 0.5f ? (lowAltitude ? Layer.flyingUnitLow : Layer.flyingUnit) : groundLayer + Mathf.clamp(hitSize / 4000f, 0, 0.01f)) + (unit.countForward() * segmentLayerOffset); @@ -172,14 +171,14 @@ public void drawWorm(T unit){ drawMech(mech); //side - legOffsetB.trns(mech.baseRotation(), 0f, Mathf.lerp(Mathf.sin(mech.walkExtend(true), 2f/Mathf.PI, 1) * mechSideSway, 0f, unit.elevation)); + legOffsetB.trns(mech.baseRotation(), 0f, Mathf.lerp(Mathf.sin(mech.walkExtend(true), 2f / Mathf.PI, 1) * mechSideSway, 0f, unit.elevation)); //front - legOffsetB.add(Tmp.v1.trns(mech.baseRotation() + 90, 0f, Mathf.lerp(Mathf.sin(mech.walkExtend(true), 1f/Mathf.PI, 1) * mechFrontSway, 0f, unit.elevation))); + legOffsetB.add(Tmp.v1.trns(mech.baseRotation() + 90, 0f, Mathf.lerp(Mathf.sin(mech.walkExtend(true), 1f / Mathf.PI, 1) * mechFrontSway, 0f, unit.elevation))); unit.trns(legOffsetB.x, legOffsetB.y); } - if (unit instanceof Legsc) drawLegs((Unit & Legsc) unit); + if(unit instanceof Legsc) drawLegs((Unit & Legsc)unit); Draw.z(Math.min(z - 0.01f, Layer.groundUnit - 1f)); @@ -241,9 +240,9 @@ public void drawWorm(T unit){ @Override public void draw(Unit unit){ - if (unit instanceof Chainedc m && !m.isHead()) { - drawWorm((Unit & Chainedc) m); - } else { + if(unit instanceof Chainedc m && !m.isHead()){ + drawWorm((Unit & Chainedc)m); + }else{ super.draw(unit); } } @@ -265,7 +264,7 @@ public void drawWeapons(Unit unit){ } @Override - public boolean hasWeapons() { + public boolean hasWeapons(){ return chainWeapons.contains(w -> !w.isEmpty()); } } diff --git a/src/omaloon/type/OrnitopterUnitType.java b/src/omaloon/type/OrnitopterUnitType.java index 206158be..1c938fc5 100644 --- a/src/omaloon/type/OrnitopterUnitType.java +++ b/src/omaloon/type/OrnitopterUnitType.java @@ -42,16 +42,16 @@ public void drawBlade(Unit unit){ Draw.z(z + blade.layerOffset); Draw.alpha(blade.blurRegion.found() ? 1 - (copter.bladeMoveSpeedScl() / 0.8f) : 1); Draw.rect( - blade.bladeOutlineRegion, rx, ry, - blade.bladeOutlineRegion.width * bladeScl * sign, - blade.bladeOutlineRegion.height * bladeScl, - unit.rotation - 90 + sign * Mathf.randomSeed(copter.drawSeed() + (seedOffset++), blade.bladeMaxMoveAngle, -blade.bladeMinMoveAngle) + blade.bladeOutlineRegion, rx, ry, + blade.bladeOutlineRegion.width * bladeScl * sign, + blade.bladeOutlineRegion.height * bladeScl, + unit.rotation - 90 + sign * Mathf.randomSeed(copter.drawSeed() + (seedOffset++), blade.bladeMaxMoveAngle, -blade.bladeMinMoveAngle) ); Draw.mixcol(Color.white, unit.hitTime); Draw.rect(blade.bladeRegion, rx, ry, - blade.bladeRegion.width * bladeScl * sign, - blade.bladeRegion.height * bladeScl, - unit.rotation - 90 + sign * Mathf.randomSeed(copter.drawSeed() + (seedOffset++), blade.bladeMaxMoveAngle, -blade.bladeMinMoveAngle) + blade.bladeRegion.width * bladeScl * sign, + blade.bladeRegion.height * bladeScl, + unit.rotation - 90 + sign * Mathf.randomSeed(copter.drawSeed() + (seedOffset++), blade.bladeMaxMoveAngle, -blade.bladeMinMoveAngle) ); Draw.reset(); } @@ -60,10 +60,10 @@ public void drawBlade(Unit unit){ Draw.z(z + blade.layerOffset); Draw.alpha(copter.bladeMoveSpeedScl() * blade.blurAlpha * (copter.dead() ? copter.bladeMoveSpeedScl() * 0.5f : 1)); Draw.rect( - blade.blurRegion, rx, ry, - blade.blurRegion.width * bladeScl * sign, - blade.blurRegion.height * bladeScl, - unit.rotation - 90 + sign * Mathf.randomSeed(copter.drawSeed() + (seedOffset++), blade.bladeMaxMoveAngle, -blade.bladeMinMoveAngle) + blade.blurRegion, rx, ry, + blade.blurRegion.width * bladeScl * sign, + blade.blurRegion.height * bladeScl, + unit.rotation - 90 + sign * Mathf.randomSeed(copter.drawSeed() + (seedOffset++), blade.bladeMaxMoveAngle, -blade.bladeMinMoveAngle) ); Draw.reset(); } @@ -72,10 +72,10 @@ public void drawBlade(Unit unit){ Draw.z(z + blade.layerOffset + 0.001f); Draw.alpha(copter.bladeMoveSpeedScl() * blade.blurAlpha * (copter.dead() ? copter.bladeMoveSpeedScl() * 0.5f : 1)); Draw.rect( - blade.shadeRegion, rx, ry, - blade.shadeRegion.width * shadeScl * sign, - blade.shadeRegion.height * shadeScl, - unit.rotation - 90 + sign * Mathf.randomSeed(copter.drawSeed() + (seedOffset++), blade.bladeMaxMoveAngle, -blade.bladeMinMoveAngle) + blade.shadeRegion, rx, ry, + blade.shadeRegion.width * shadeScl * sign, + blade.shadeRegion.height * shadeScl, + unit.rotation - 90 + sign * Mathf.randomSeed(copter.drawSeed() + (seedOffset++), blade.bladeMaxMoveAngle, -blade.bladeMinMoveAngle) ); Draw.mixcol(Color.white, unit.hitTime); Draw.reset(); @@ -86,9 +86,9 @@ public void drawBlade(Unit unit){ } @Override - public void createIcons(MultiPacker packer) { + public void createIcons(MultiPacker packer){ super.createIcons(packer); - for (Blade blade : blades) { + for(Blade blade : blades){ Outliner.outlineRegion(packer, blade.bladeRegion, outlineColor, blade.spriteName + "-outline", outlineRadius); Outliner.outlineRegion(packer, blade.shadeRegion, outlineColor, blade.spriteName + "-top-outline", outlineRadius); } diff --git a/src/omaloon/type/customshape/CustomShape.java b/src/omaloon/type/customshape/CustomShape.java index 1c764852..b37ebfad 100644 --- a/src/omaloon/type/customshape/CustomShape.java +++ b/src/omaloon/type/customshape/CustomShape.java @@ -25,11 +25,12 @@ public CustomShape(int width, int height, BitWordList blocks){ public int centerX(){ return centerX; } + public int centerY(){ return centerY; } - public void findCenter() { + public void findCenter(){ for(int i = 0; i < blocks.initialWordsAmount; i++){ if(blocks.get(i) == 3){ centerX = unpackX(i); @@ -43,6 +44,7 @@ public void findCenter() { public int unpackX(int index){ return index % width; } + public int unpackY(int index){ return index / width; } @@ -62,8 +64,8 @@ public int getIdRelativeCenter(int x, int y){ } @Override - public boolean equals(Object obj) { - if (!(obj instanceof CustomShape shape)) return false; + public boolean equals(Object obj){ + if(!(obj instanceof CustomShape shape)) return false; return width == shape.width && height == shape.height && blocks.equals(shape.blocks); } } diff --git a/src/omaloon/type/customshape/CustomShapeLoader.java b/src/omaloon/type/customshape/CustomShapeLoader.java index 961a3a54..7cd9e89d 100644 --- a/src/omaloon/type/customshape/CustomShapeLoader.java +++ b/src/omaloon/type/customshape/CustomShapeLoader.java @@ -13,6 +13,7 @@ public abstract class CustomShapeLoader{ public BitWordList blocks; public abstract void load(T type); + public CustomShape loadToShape(T type){ load(type); return toShape(); diff --git a/src/omaloon/type/customshape/shapeloaders/SpriteShapeLoader.java b/src/omaloon/type/customshape/shapeloaders/SpriteShapeLoader.java index ffc34320..9e883ff9 100644 --- a/src/omaloon/type/customshape/shapeloaders/SpriteShapeLoader.java +++ b/src/omaloon/type/customshape/shapeloaders/SpriteShapeLoader.java @@ -8,7 +8,7 @@ * ... * by Zelaux */ -public class SpriteShapeLoader extends CustomShapeLoader { +public class SpriteShapeLoader extends CustomShapeLoader{ /* public final int chunkSize; public final ChunkProcessor chunkProcessor; diff --git a/src/omaloon/type/liquid/CrystalLiquid.java b/src/omaloon/type/liquid/CrystalLiquid.java index c40c284e..34f90a79 100644 --- a/src/omaloon/type/liquid/CrystalLiquid.java +++ b/src/omaloon/type/liquid/CrystalLiquid.java @@ -4,17 +4,16 @@ import arc.graphics.g2d.*; import arc.math.*; import arc.util.*; - import mindustry.gen.*; import mindustry.graphics.*; -import mindustry.type.Liquid; +import mindustry.type.*; -import static mindustry.entities.Puddles.*; +import static mindustry.entities.Puddles.maxLiquid; -public class CrystalLiquid extends Liquid { +public class CrystalLiquid extends Liquid{ public Color - colorFrom = Color.white.cpy(), - colorTo = Color.white.cpy(); + colorFrom = Color.white.cpy(), + colorTo = Color.white.cpy(); public int cells = 18; @@ -23,7 +22,7 @@ public CrystalLiquid(String name, Color color){ } @Override - public void drawPuddle(Puddle puddle) { + public void drawPuddle(Puddle puddle){ super.drawPuddle(puddle); Draw.z(Layer.debris - 0.5f); @@ -35,24 +34,24 @@ public void drawPuddle(Puddle puddle) { Draw.color(Tmp.c1.set(color).shiftValue(-0.05f)); Fill.poly( - x + Mathf.sin(Time.time + id * 5, sscl, smag), - y + Mathf.sin(Time.time + id * 3, sscl, smag), - 6, f * 8.6f + x + Mathf.sin(Time.time + id * 5, sscl, smag), + y + Mathf.sin(Time.time + id * 3, sscl, smag), + 6, f * 8.6f ); rand.setSeed(id); - for(int i = 0; i < cells; i++) { - Draw.z(Layer.debris - 0.5f + i/1000f + (id % 100) / 10000f); + for(int i = 0; i < cells; i++){ + Draw.z(Layer.debris - 0.5f + i / 1000f + (id % 100) / 10000f); Tmp.v1.trns(rand.random(360f), rand.random(length)); float vx = x + Tmp.v1.x, vy = y + Tmp.v1.y; Draw.color(colorFrom, colorTo, rand.random(1f)); Fill.poly( - vx + Mathf.sin(Time.time + i * 53, sscl, smag), - vy + Mathf.sin(Time.time + i * 3, sscl, smag), - 6, - f * 3.8f * rand.random(0.2f, 1f) * Mathf.absin(Time.time + ((i + id) % 60) * 54, 75f * rand.random(1f, 2f), 1f) + vx + Mathf.sin(Time.time + i * 53, sscl, smag), + vy + Mathf.sin(Time.time + i * 3, sscl, smag), + 6, + f * 3.8f * rand.random(0.2f, 1f) * Mathf.absin(Time.time + ((i + id) % 60) * 54, 75f * rand.random(1f, 2f), 1f) ); } diff --git a/src/omaloon/type/weather/EffectWeather.java b/src/omaloon/type/weather/EffectWeather.java index 6747601f..0935db10 100644 --- a/src/omaloon/type/weather/EffectWeather.java +++ b/src/omaloon/type/weather/EffectWeather.java @@ -1,19 +1,20 @@ package omaloon.type.weather; -import arc.math.Mathf; -import mindustry.content.Fx; -import mindustry.entities.Effect; -import mindustry.gen.WeatherState; +import arc.math.*; +import mindustry.content.*; +import mindustry.entities.*; +import mindustry.gen.*; public class EffectWeather extends SpawnerWeather{ public Effect weatherFx = Fx.none; - public EffectWeather(String name) { + + public EffectWeather(String name){ super(name); useWindVector = true; } @Override - public void spawnAt(WeatherState state, float x, float y) { + public void spawnAt(WeatherState state, float x, float y){ weatherFx.at(x, y, Mathf.angle(state.windVector.x, state.windVector.y)); } } diff --git a/src/omaloon/type/weather/HailStormWeather.java b/src/omaloon/type/weather/HailStormWeather.java index 8f064c4d..04742981 100644 --- a/src/omaloon/type/weather/HailStormWeather.java +++ b/src/omaloon/type/weather/HailStormWeather.java @@ -13,7 +13,7 @@ import java.util.*; -public class HailStormWeather extends SpawnerWeather { +public class HailStormWeather extends SpawnerWeather{ public float yspeed = 5f, xspeed = 1.5f, density = 900f, stroke = 0.75f, sizeMin = 8f, sizeMax = 40f, splashTimeScale = 22f; public Liquid liquid = OlLiquids.glacium; public TextureRegion[] splashes = new TextureRegion[12]; @@ -25,7 +25,7 @@ public class HailStormWeather extends SpawnerWeather { public float bulletChange = 0.2f; public Team bulletTeam = Team.derelict; - public HailStormWeather(String name) { + public HailStormWeather(String name){ super(name); } @@ -39,7 +39,7 @@ public void load(){ } @Override - public void spawnAt(WeatherState state, float x, float y) { + public void spawnAt(WeatherState state, float x, float y){ BulletType b = getBullet(); if(!Vars.net.client()){ @@ -53,28 +53,28 @@ public boolean canSpawn(WeatherState state){ } public BulletType getBullet(){ - for (int i = 0; i < bullets.length; i++) { - var item = (BulletStack) bullets[i]; + for(int i = 0; i < bullets.length; i++){ + var item = (BulletStack)bullets[i]; - if (Mathf.random() < item.change){ + if(Mathf.random() < item.change){ return item.bullet; } } - return bullets[bullets.length-1].bullet; + return bullets[bullets.length - 1].bullet; } public void setBullets(Object... items){ - var stack = new BulletStack[items.length/2]; + var stack = new BulletStack[items.length / 2]; - for (int i = 0; i < items.length; i += 2) { - stack[i/2] = new BulletStack((BulletType) items[i], (float) items[i + 1]); + for(int i = 0; i < items.length; i += 2){ + stack[i / 2] = new BulletStack((BulletType)items[i], (float)items[i + 1]); } - Arrays.sort(stack, new Comparator() { + Arrays.sort(stack, new Comparator(){ @Override - public int compare(BulletStack o1, BulletStack o2) { - if (o1.change == o2.change) return 0; + public int compare(BulletStack o1, BulletStack o2){ + if(o1.change == o2.change) return 0; return o1.change > o2.change ? 1 : -1; } }); @@ -83,19 +83,19 @@ public int compare(BulletStack o1, BulletStack o2) { } @Override - public void drawOver(WeatherState state) { + public void drawOver(WeatherState state){ super.drawOver(state); - if (drawRain) + if(drawRain) drawRain(sizeMin, sizeMax, xspeed, yspeed, density, state.intensity, stroke, color); } @Override public void drawUnder(WeatherState state){ - if (drawRain) + if(drawRain) drawSplashes(splashes, sizeMax, density, state.intensity, state.opacity, splashTimeScale, stroke, color, liquid); } - public static class BulletStack { + public static class BulletStack{ public BulletType bullet; public float change; diff --git a/src/omaloon/type/weather/SpawnerWeather.java b/src/omaloon/type/weather/SpawnerWeather.java index abd360b0..409c5261 100644 --- a/src/omaloon/type/weather/SpawnerWeather.java +++ b/src/omaloon/type/weather/SpawnerWeather.java @@ -1,32 +1,30 @@ package omaloon.type.weather; -import arc.Core; -import arc.math.Mathf; -import arc.util.Time; -import arc.util.Tmp; -import mindustry.Vars; -import mindustry.gen.WeatherState; -import mindustry.type.weather.ParticleWeather; - -import static mindustry.Vars.renderer; -import static mindustry.Vars.world; - -public class SpawnerWeather extends ParticleWeather { +import arc.*; +import arc.math.*; +import arc.util.*; +import mindustry.*; +import mindustry.gen.*; +import mindustry.type.weather.*; + +import static mindustry.Vars.*; + +public class SpawnerWeather extends ParticleWeather{ public int maxSpawn = 6; public boolean inBounceCam = true; - public SpawnerWeather(String name) { + public SpawnerWeather(String name){ super(name); } @Override - public void update(WeatherState state) { + public void update(WeatherState state){ super.update(state); //I don't know how to make it more simplified --random - if (inBounceCam){ + if(inBounceCam){ spawnByBounceCam(state); - }else { + }else{ spawn(state); } } @@ -37,13 +35,13 @@ public void spawnByBounceCam(WeatherState state){ Tmp.r1.setCentered(Core.camera.position.x, Core.camera.position.y, Core.graphics.getWidth() / renderer.minScale(), Core.graphics.getHeight() / renderer.minScale()); Tmp.r1.grow(sizeMax * 1.5f); Core.camera.bounds(Tmp.r2); - rand.setSeed((long) Time.time); + rand.setSeed((long)Time.time); float speed = force * state.intensity * Time.delta; float windx = state.windVector.x * speed, windy = state.windVector.y * speed; - int total = (int) Mathf.clamp(Tmp.r1.area() / density * state.intensity, 0f, maxSpawn); + int total = (int)Mathf.clamp(Tmp.r1.area() / density * state.intensity, 0f, maxSpawn); - for (int i = 0; i < total; i++) { + for(int i = 0; i < total; i++){ float scl = rand.random(0.5f, 1f); float scl2 = rand.random(0.5f, 1f); float size = rand.random(sizeMin, sizeMax); @@ -59,7 +57,7 @@ public void spawnByBounceCam(WeatherState state){ x += Tmp.r1.x; y += Tmp.r1.y; - if(Tmp.r3.setCentered(x, y, size).overlaps(Tmp.r2) && canSpawn(state)) { + if(Tmp.r3.setCentered(x, y, size).overlaps(Tmp.r2) && canSpawn(state)){ float x1 = Mathf.random(1, world.tiles.width - 1) * Vars.tilesize; float y1 = Mathf.random(1, world.tiles.height - 1) * Vars.tilesize; @@ -70,13 +68,13 @@ public void spawnByBounceCam(WeatherState state){ //Spawn on the world public void spawn(WeatherState state){ - Tmp.r2.set(0f,0f, world.unitWidth(), world.unitHeight()); - rand.setSeed((long) Time.time); + Tmp.r2.set(0f, 0f, world.unitWidth(), world.unitHeight()); + rand.setSeed((long)Time.time); - int total = (int) Mathf.clamp(Tmp.r2.area() / density * state.intensity, 0f, maxSpawn); + int total = (int)Mathf.clamp(Tmp.r2.area() / density * state.intensity, 0f, maxSpawn); - for (int i = 0; i < total; i++) { - if(canSpawn(state)) { + for(int i = 0; i < total; i++){ + if(canSpawn(state)){ float x1 = Mathf.random(1, world.tiles.width - 1) * Vars.tilesize; float y1 = Mathf.random(1, world.tiles.height - 1) * Vars.tilesize; diff --git a/src/omaloon/ui/MultiItemConfig.java b/src/omaloon/ui/MultiItemConfig.java index cd7c6fc8..f16f2966 100644 --- a/src/omaloon/ui/MultiItemConfig.java +++ b/src/omaloon/ui/MultiItemConfig.java @@ -5,8 +5,8 @@ import mindustry.type.*; import mindustry.world.*; -public class MultiItemConfig { - public static void configure(Block block, Func getter) { +public class MultiItemConfig{ + public static void configure(Block block, Func getter){ block.config(Integer.class, (T build, Integer config) -> { getter.get(build).toggle(config); }); @@ -21,21 +21,21 @@ public static void configure(Block block, Func { var data = getter.get(build); - for(int i : config) { + for(int i : config){ data.toggle(i); } }); block.config(String[].class, (T build, String[] config) -> { var data = getter.get(build); - for(String i : config) { + for(String i : config){ data.toggle(i); } }); block.config(Item[].class, (T build, Item[] config) -> { var data = getter.get(build); - for(Item i : config) { + for(Item i : config){ data.toggle(i); } }); diff --git a/src/omaloon/ui/MultiItemData.java b/src/omaloon/ui/MultiItemData.java index a0b61fdf..25f99132 100644 --- a/src/omaloon/ui/MultiItemData.java +++ b/src/omaloon/ui/MultiItemData.java @@ -4,88 +4,88 @@ import arc.util.io.*; import mindustry.type.*; -import static mindustry.Vars.*; +import static mindustry.Vars.content; -public class MultiItemData { +public class MultiItemData{ private final Seq items = new Seq<>(); - public int length() { + public int length(){ return items.size; } - public IntSet asIntSet() { + public IntSet asIntSet(){ IntSet seq = new IntSet(); items.forEach((i) -> seq.add(i.id)); return seq; } - public void write(Writes writes) { + public void write(Writes writes){ writes.i(items.size); items.forEach(item -> writes.str(item.name)); } - public void read(Reads reads) { + public void read(Reads reads){ int len = reads.i(); - for (int i = 0; i < len; i++) { + for(int i = 0; i < len; i++){ toggle(reads.str()); } } - public int[] config() { + public int[] config(){ int[] config = new int[items.size]; - for (int i = 0; i < config.length; i++) { + for(int i = 0; i < config.length; i++){ config[i] = items.get(i).id; } return config; } - public boolean isToggled(Item item) { + public boolean isToggled(Item item){ return items.contains(item); } - public boolean isToggled(String name) { + public boolean isToggled(String name){ return isToggled(content.item(name)); } - public boolean isToggled(int id) { + public boolean isToggled(int id){ return isToggled(content.item(id)); } - public void toggle(Item item) { - if (item != null) { - if (items.contains(item)) { + public void toggle(Item item){ + if(item != null){ + if(items.contains(item)){ items.remove(item); - } else { + }else{ items.add(item); } } } - public void toggle(String name) { + public void toggle(String name){ toggle(content.item(name)); } - public void toggle(int id) { + public void toggle(int id){ toggle(content.item(id)); } - public void clear() { + public void clear(){ items.clear(); } - public void enable(Item item) { - if (!items.contains(item)) { + public void enable(Item item){ + if(!items.contains(item)){ items.add(item); } } - public void disable(Item item) { - if (items.contains(item)) { + public void disable(Item item){ + if(items.contains(item)){ items.remove(item); } } - public Seq getItems() { + public Seq getItems(){ return items; } } diff --git a/src/omaloon/ui/MultiItemSelection.java b/src/omaloon/ui/MultiItemSelection.java index aad51c7c..0a60c45c 100644 --- a/src/omaloon/ui/MultiItemSelection.java +++ b/src/omaloon/ui/MultiItemSelection.java @@ -14,29 +14,29 @@ import mindustry.ui.*; import mindustry.world.*; -import static mindustry.Vars.*; +import static mindustry.Vars.state; -public class MultiItemSelection { +public class MultiItemSelection{ private static TextField search; private static int rowCount; - public static void buildTable(Table table, MultiItemData data) { + public static void buildTable(Table table, MultiItemData data){ buildTable(table, Vars.content.items(), data); } - public static void buildTable(Table table, Seq items, MultiItemData data) { + public static void buildTable(Table table, Seq items, MultiItemData data){ buildTable(table, items, data::isToggled, data::toggle); } - public static void buildTable(Table table, Seq items, Boolf holder, Cons toggle) { + public static void buildTable(Table table, Seq items, Boolf holder, Cons toggle){ buildTable(null, table, items, holder, toggle, 5, 4); } - public static void buildTable(@Nullable Block block, Table table, Seq items, Boolf holder, Cons toggle, int rows, int columns) { + public static void buildTable(@Nullable Block block, Table table, Seq items, Boolf holder, Cons toggle, int rows, int columns){ Table cont = new Table().top(); cont.defaults().size(40); - if (search != null) search.clearText(); + if(search != null) search.clearText(); Runnable rebuild = () -> { cont.clearChildren(); @@ -46,8 +46,8 @@ public static void buildTable(@Nullable Block bloc rowCount = 0; Seq list = items.select(u -> (text.isEmpty() || u.localizedName.toLowerCase().contains(text.toLowerCase()))); - for (T item : list) { - if (!item.unlockedNow() || (item instanceof Item checkVisible && state.rules.hiddenBuildItems.contains(checkVisible)) || item.isHidden()) + for(T item : list){ + if(!item.unlockedNow() || (item instanceof Item checkVisible && state.rules.hiddenBuildItems.contains(checkVisible)) || item.isHidden()) continue; ImageButton button = cont.button(Tex.whiteui, Styles.clearNoneTogglei, Mathf.clamp(item.selectionSize, 0f, 40f), () -> { @@ -56,7 +56,7 @@ public static void buildTable(@Nullable Block bloc button.getStyle().imageUp = new TextureRegionDrawable(item.uiIcon); button.update(() -> button.setChecked(holder.get(item))); - if (i++ % columns == (columns - 1)) { + if(i++ % columns == (columns - 1)){ cont.row(); rowCount++; } @@ -66,7 +66,7 @@ public static void buildTable(@Nullable Block bloc rebuild.run(); Table main = new Table().background(Styles.black6); - if (rowCount > rows * 1.5f) { + if(rowCount > rows * 1.5f){ main.table(s -> { s.image(Icon.zoom).padLeft(4f); search = s.field(null, text -> rebuild.run()).padBottom(4).left().growX().get(); @@ -77,7 +77,7 @@ public static void buildTable(@Nullable Block bloc ScrollPane pane = new ScrollPane(cont, Styles.smallPane); pane.setScrollingDisabled(true, false); - if (block != null) { + if(block != null){ pane.setScrollYForce(block.selectScroll); pane.update(() -> block.selectScroll = pane.getScrollY()); } diff --git a/src/omaloon/ui/OlBinding.java b/src/omaloon/ui/OlBinding.java index 5e5a2d27..f5675c06 100644 --- a/src/omaloon/ui/OlBinding.java +++ b/src/omaloon/ui/OlBinding.java @@ -7,29 +7,29 @@ import static arc.Core.*; -public enum OlBinding implements KeyBind { +public enum OlBinding implements KeyBind{ shaped_env_placer(KeyCode.o, "omaloon-editor"), cliff_placer(KeyCode.p, "omaloon-editor"); private final KeybindValue defaultValue; private final String category; - OlBinding(KeybindValue defaultValue, String category) { + OlBinding(KeybindValue defaultValue, String category){ this.defaultValue = defaultValue; this.category = category; } @Override - public KeybindValue defaultValue(DeviceType type) { + public KeybindValue defaultValue(DeviceType type){ return defaultValue; } @Override - public String category() { + public String category(){ return category; } - public static void load() { + public static void load(){ KeyBind[] orign = Binding.values(); KeyBind[] moded = values(); KeyBind[] binds = new KeyBind[orign.length + moded.length]; diff --git a/src/omaloon/ui/StartSplash.java b/src/omaloon/ui/StartSplash.java index c25f2c67..39f2929f 100644 --- a/src/omaloon/ui/StartSplash.java +++ b/src/omaloon/ui/StartSplash.java @@ -6,16 +6,12 @@ import arc.scene.actions.*; import arc.scene.event.*; import arc.scene.ui.layout.*; -import arc.util.Log; -import mindustry.Vars; import mindustry.ui.*; import omaloon.ui.dialogs.*; -import java.util.Objects; +import static arc.Core.settings; -import static arc.Core.*; - -public class StartSplash { +public class StartSplash{ private static Table omaloonIcon, cont; private static boolean finished = false; @@ -37,29 +33,29 @@ public static void show(){ cont.visible(() -> true); omaloonIcon.actions( - Actions.alpha(0f), - Actions.delay(1f), - Actions.fadeIn(1f, Interp.pow3Out), - Actions.delay(1f), - Actions.fadeOut(1f, Interp.pow3Out) + Actions.alpha(0f), + Actions.delay(1f), + Actions.fadeIn(1f, Interp.pow3Out), + Actions.delay(1f), + Actions.fadeOut(1f, Interp.pow3Out) ); cont.actions( - Actions.delay(6f, Actions.fadeOut(1f)), - Actions.run(() -> { - cont.visible(() -> false); - cont.touchable(() -> Touchable.disabled); - onComplete(); - }) + Actions.delay(6f, Actions.fadeOut(1f)), + Actions.run(() -> { + cont.visible(() -> false); + cont.touchable(() -> Touchable.disabled); + onComplete(); + }) ); } - private static void onComplete() { - if (!settings.getBool("omaloon-show-disclaimer", false)) { + private static void onComplete(){ + if(!settings.getBool("omaloon-show-disclaimer", false)){ new OlDisclaimerDialog().show(); } - if (settings.getBool("omaloon-check-updates", true)) { + if(settings.getBool("omaloon-check-updates", true)){ OlUpdateCheckerDialog.check(); } diff --git a/src/omaloon/ui/dialogs/AfterUpdateCleanDialog.java b/src/omaloon/ui/dialogs/AfterUpdateCleanDialog.java index ca3dced3..6d476738 100644 --- a/src/omaloon/ui/dialogs/AfterUpdateCleanDialog.java +++ b/src/omaloon/ui/dialogs/AfterUpdateCleanDialog.java @@ -12,28 +12,28 @@ import static arc.Core.*; -public class AfterUpdateCleanDialog { +public class AfterUpdateCleanDialog{ public static Mods.LoadedMod mod = Vars.mods.locateMod("omaloon"); - public static void check() { + public static void check(){ String lastVersion = settings.getString("last-omaloon-version", null); - if (lastVersion == null) { + if(lastVersion == null){ settings.put("last-omaloon-version", mod.meta.version); - } else if (!mod.meta.version.equals(lastVersion)) { + }else if(!mod.meta.version.equals(lastVersion)){ showUpdateDialog(); } } - private static void showUpdateDialog() { + private static void showUpdateDialog(){ BaseDialog dialog = new BaseDialog("@dialog.omaloon-update-cleanup.title", Core.scene.getStyle(Dialog.DialogStyle.class)); dialog.cont.add(bundle.format("dialog.omaloon-update-cleanup.text", settings.getString("last-omaloon-version"), mod.meta.version)) - .width(500f) - .wrap() - .pad(4f) - .get() - .setAlignment(Align.center, Align.center); + .width(500f) + .wrap() + .pad(4f) + .get() + .setAlignment(Align.center, Align.center); dialog.buttons.defaults().size(200f, 54f).pad(2f); dialog.setFillParent(false); diff --git a/src/omaloon/ui/dialogs/EventHints.java b/src/omaloon/ui/dialogs/EventHints.java index 880df303..41f9b2bc 100644 --- a/src/omaloon/ui/dialogs/EventHints.java +++ b/src/omaloon/ui/dialogs/EventHints.java @@ -11,90 +11,96 @@ import omaloon.world.blocks.production.PressureDrill.*; import omaloon.world.interfaces.*; -public enum EventHints implements Hint { - air( - () -> false, - () -> Vars.state.rules.defaultTeam.data().buildings.contains(b -> b instanceof HasPressure) - ), - drill( - () -> false, - () -> Vars.state.rules.defaultTeam.data().buildings.contains(b -> b instanceof PressureDrillBuild) - ), - pump_chaining( - () -> false, - () -> Vars.control.input.block instanceof PressureLiquidPump - ), - shelter( - () -> false, - () -> Vars.state.rules.defaultTeam.data().buildings.contains(b -> b instanceof ShelterBuild) - ); - - final Boolp complete; - Boolp shown = () -> true; - EventHints[] requirements; - - int visibility = visibleAll; - boolean cached, finished; - - static final String prefix = "omaloon-"; - - public static void addHints() { - Vars.ui.hints.hints.add(Seq.with(EventHints.values()).removeAll( - hint -> Core.settings.getBool(prefix + hint.name() + "-hint-done", false) - )); - } - - EventHints(Boolp complete) { - this.complete = complete; - } - EventHints(Boolp complete, Boolp shown) { - this(complete); - this.shown = shown; - } - EventHints(Boolp complete, Boolp shown, EventHints... requirements) { - this(complete, shown); - this.requirements = requirements; - } - - @Override public boolean complete() { - return complete.get(); - } - - @Override - public void finish() { - Core.settings.put(prefix + name() + "-hint-done", finished = true); - } - - @Override - public boolean finished() { - if(!cached){ - cached = true; - finished = Core.settings.getBool(prefix + name() + "-hint-done", false); - } - return finished; - } - - @Override public int order() { - return ordinal(); - } - - public static void reset() { - for(EventHints hint : values()) { - Core.settings.put(prefix + hint.name() + "-hint-done", hint.finished = false); - } - addHints(); - } - - @Override public boolean show() { - return shown.get() && (requirements == null || (requirements.length == 0 || !Structs.contains(requirements, d -> !d.finished()))); - } - - @Override public String text() { - return Core.bundle.get("hint." + prefix + name(), "Missing bundle for hint: hint." + prefix + name()); - } - - @Override - public boolean valid() { - return (Vars.mobile && (visibility & visibleMobile) != 0) || (!Vars.mobile && (visibility & visibleDesktop) != 0); - } +public enum EventHints implements Hint{ + air( + () -> false, + () -> Vars.state.rules.defaultTeam.data().buildings.contains(b -> b instanceof HasPressure) + ), + drill( + () -> false, + () -> Vars.state.rules.defaultTeam.data().buildings.contains(b -> b instanceof PressureDrillBuild) + ), + pump_chaining( + () -> false, + () -> Vars.control.input.block instanceof PressureLiquidPump + ), + shelter( + () -> false, + () -> Vars.state.rules.defaultTeam.data().buildings.contains(b -> b instanceof ShelterBuild) + ); + + final Boolp complete; + Boolp shown = () -> true; + EventHints[] requirements; + + int visibility = visibleAll; + boolean cached, finished; + + static final String prefix = "omaloon-"; + + public static void addHints(){ + Vars.ui.hints.hints.add(Seq.with(EventHints.values()).removeAll( + hint -> Core.settings.getBool(prefix + hint.name() + "-hint-done", false) + )); + } + + EventHints(Boolp complete){ + this.complete = complete; + } + + EventHints(Boolp complete, Boolp shown){ + this(complete); + this.shown = shown; + } + + EventHints(Boolp complete, Boolp shown, EventHints... requirements){ + this(complete, shown); + this.requirements = requirements; + } + + @Override + public boolean complete(){ + return complete.get(); + } + + @Override + public void finish(){ + Core.settings.put(prefix + name() + "-hint-done", finished = true); + } + + @Override + public boolean finished(){ + if(!cached){ + cached = true; + finished = Core.settings.getBool(prefix + name() + "-hint-done", false); + } + return finished; + } + + @Override + public int order(){ + return ordinal(); + } + + public static void reset(){ + for(EventHints hint : values()){ + Core.settings.put(prefix + hint.name() + "-hint-done", hint.finished = false); + } + addHints(); + } + + @Override + public boolean show(){ + return shown.get() && (requirements == null || (requirements.length == 0 || !Structs.contains(requirements, d -> !d.finished()))); + } + + @Override + public String text(){ + return Core.bundle.get("hint." + prefix + name(), "Missing bundle for hint: hint." + prefix + name()); + } + + @Override + public boolean valid(){ + return (Vars.mobile && (visibility & visibleMobile) != 0) || (!Vars.mobile && (visibility & visibleDesktop) != 0); + } } diff --git a/src/omaloon/ui/dialogs/OlDisclaimerDialog.java b/src/omaloon/ui/dialogs/OlDisclaimerDialog.java index 821bfe5f..7ac7a029 100644 --- a/src/omaloon/ui/dialogs/OlDisclaimerDialog.java +++ b/src/omaloon/ui/dialogs/OlDisclaimerDialog.java @@ -7,23 +7,23 @@ import mindustry.gen.*; import mindustry.ui.dialogs.*; -public class OlDisclaimerDialog extends BaseDialog { - public OlDisclaimerDialog() { +public class OlDisclaimerDialog extends BaseDialog{ + public OlDisclaimerDialog(){ super("@dialog.omaloon-disclaimer.title", Core.scene.getStyle(DialogStyle.class)); cont.add("@dialog.omaloon-disclaimer") - .width(500f) - .wrap() - .pad(4f) - .get() - .setAlignment(Align.center, Align.center); + .width(500f) + .wrap() + .pad(4f) + .get() + .setAlignment(Align.center, Align.center); buttons.defaults().size(200f, 54f).pad(2f); setFillParent(false); TextButton b = buttons.button("@ok", Icon.ok, this::hide).get(); - if(shouldSkip()) { + if(shouldSkip()){ return; } @@ -32,11 +32,11 @@ public OlDisclaimerDialog() { }); b.actions( - Actions.alpha(0), - Actions.moveBy(0f, 0f), - Actions.delay(1.5f), - Actions.fadeIn(1f), - Actions.delay(1f) + Actions.alpha(0), + Actions.moveBy(0f, 0f), + Actions.delay(1.5f), + Actions.fadeIn(1f), + Actions.delay(1f) ); b.getStyle().disabledFontColor = b.getStyle().fontColor; @@ -48,22 +48,22 @@ public OlDisclaimerDialog() { }).get(); s.setDisabled(() -> - s.color.a < 1 + s.color.a < 1 ); s.actions( - Actions.alpha(0), - Actions.moveBy(0f, 0f), - Actions.delay(2f), - Actions.fadeIn(1f), - Actions.delay(1f) + Actions.alpha(0), + Actions.moveBy(0f, 0f), + Actions.delay(2f), + Actions.fadeIn(1f), + Actions.delay(1f) ); s.getStyle().disabledFontColor = b.getStyle().fontColor; s.getStyle().disabled = s.getStyle().up; } - boolean shouldSkip() { + boolean shouldSkip(){ return Core.settings.getBool("omaloon-show-disclaimer", false); } } diff --git a/src/omaloon/ui/dialogs/OlDiscordLink.java b/src/omaloon/ui/dialogs/OlDiscordLink.java index b546bd1a..ab283dcc 100644 --- a/src/omaloon/ui/dialogs/OlDiscordLink.java +++ b/src/omaloon/ui/dialogs/OlDiscordLink.java @@ -4,13 +4,13 @@ import arc.scene.ui.*; import mindustry.gen.*; -import static arc.Core.*; -import static mindustry.Vars.*; +import static arc.Core.app; +import static mindustry.Vars.ui; -public class OlDiscordLink extends Dialog { +public class OlDiscordLink extends Dialog{ public String discordURL = "https://discord.gg/bNMT82Hswb"; - public OlDiscordLink() { + public OlDiscordLink(){ super(""); float h = 200f; @@ -20,11 +20,12 @@ public OlDiscordLink() { cont.table(t -> { t.background(Tex.button).margin(0); - t.table(img -> {img.image().height(h - 5).width(40f).color(color); + t.table(img -> { + img.image().height(h - 5).width(40f).color(color); img.row(); img.image().height(5).width(40f).color( - color.cpy().mul(0.8f, 0.8f, 0.8f, 1f) + color.cpy().mul(0.8f, 0.8f, 0.8f, 1f) ); }).expandY(); @@ -42,7 +43,7 @@ public OlDiscordLink() { }); buttons.button("@openlink", Icon.discord, () -> { - if(!app.openURI(discordURL)) { + if(!app.openURI(discordURL)){ ui.showInfoFade("@linkfail"); app.setClipboardText(discordURL); } diff --git a/src/omaloon/ui/dialogs/OlEndDialog.java b/src/omaloon/ui/dialogs/OlEndDialog.java index 08083298..e853738c 100644 --- a/src/omaloon/ui/dialogs/OlEndDialog.java +++ b/src/omaloon/ui/dialogs/OlEndDialog.java @@ -4,23 +4,23 @@ import arc.scene.ui.layout.*; import mindustry.ui.dialogs.*; -import static mindustry.Vars.*; +import static mindustry.Vars.mobile; -public class OlEndDialog extends BaseDialog { - public OlEndDialog() { - super(""); - titleTable.remove(); - buttons.remove(); +public class OlEndDialog extends BaseDialog{ + public OlEndDialog(){ + super(""); + titleTable.remove(); + buttons.remove(); - cont.stack( - new Table(t -> t.add("@ui.omaloon-finished-campaign")), - new Table(t -> t.add(mobile ? "@ui.omaloon-exit-dialog.mobile" : "@ui.omaloon-exit-dialog")).bottom().left() - ).grow(); + cont.stack( + new Table(t -> t.add("@ui.omaloon-finished-campaign")), + new Table(t -> t.add(mobile ? "@ui.omaloon-exit-dialog.mobile" : "@ui.omaloon-exit-dialog")).bottom().left() + ).grow(); - actions(Actions.fadeOut(1)); - clicked(() -> hide(Actions.sequence( - Actions.fadeIn(0), - Actions.fadeOut(1) - ))); - } + actions(Actions.fadeOut(1)); + clicked(() -> hide(Actions.sequence( + Actions.fadeIn(0), + Actions.fadeOut(1) + ))); + } } diff --git a/src/omaloon/ui/dialogs/OlGameDataDialog.java b/src/omaloon/ui/dialogs/OlGameDataDialog.java index 7289f884..fb6c0255 100644 --- a/src/omaloon/ui/dialogs/OlGameDataDialog.java +++ b/src/omaloon/ui/dialogs/OlGameDataDialog.java @@ -7,34 +7,34 @@ import omaloon.*; import omaloon.content.*; -public class OlGameDataDialog extends BaseDialog { - public OlGameDataDialog() { - super("@settings.omaloon-moddata"); +public class OlGameDataDialog extends BaseDialog{ + public OlGameDataDialog(){ + super("@settings.omaloon-moddata"); - addCloseButton(); + addCloseButton(); - cont.table(Tex.button, cat -> { - cat.button( - "@settings.clearresearch", - Icon.trash, - Styles.flatt, - Vars.iconMed, - () -> Vars.ui.showConfirm("@settings.omaloon-clearresearch-confirm", () -> OmaloonMod.resetTree(OlPlanets.glasmore.techTree)) - ).growX().marginLeft(8).height(50).row(); - cat.button( - "@settings.clearcampaignsaves", - Icon.trash, - Styles.flatt, - Vars.iconMed, - () -> Vars.ui.showConfirm("@settings.omaloon-clearcampaignsaves-confirm", () -> OmaloonMod.resetSaves(OlPlanets.glasmore)) - ).growX().marginLeft(8).height(50).row(); - cat.button( - "@settings.omaloon-resethints", - Icon.trash, - Styles.flatt, - Vars.iconMed, - () -> Vars.ui.showConfirm("@settings.omaloon-resethints-confirm", EventHints::reset) - ).growX().marginLeft(8).height(50).row(); - }).width(400f).row(); - } + cont.table(Tex.button, cat -> { + cat.button( + "@settings.clearresearch", + Icon.trash, + Styles.flatt, + Vars.iconMed, + () -> Vars.ui.showConfirm("@settings.omaloon-clearresearch-confirm", () -> OmaloonMod.resetTree(OlPlanets.glasmore.techTree)) + ).growX().marginLeft(8).height(50).row(); + cat.button( + "@settings.clearcampaignsaves", + Icon.trash, + Styles.flatt, + Vars.iconMed, + () -> Vars.ui.showConfirm("@settings.omaloon-clearcampaignsaves-confirm", () -> OmaloonMod.resetSaves(OlPlanets.glasmore)) + ).growX().marginLeft(8).height(50).row(); + cat.button( + "@settings.omaloon-resethints", + Icon.trash, + Styles.flatt, + Vars.iconMed, + () -> Vars.ui.showConfirm("@settings.omaloon-resethints-confirm", EventHints::reset) + ).growX().marginLeft(8).height(50).row(); + }).width(400f).row(); + } } diff --git a/src/omaloon/ui/dialogs/OlGameDialog.java b/src/omaloon/ui/dialogs/OlGameDialog.java index 871efbda..7892abbe 100644 --- a/src/omaloon/ui/dialogs/OlGameDialog.java +++ b/src/omaloon/ui/dialogs/OlGameDialog.java @@ -11,84 +11,88 @@ import mindustry.ui.*; import mindustry.ui.dialogs.*; -public class OlGameDialog extends BaseDialog { - public final ObjectMap settings = new ObjectMap<>(); +public class OlGameDialog extends BaseDialog{ + public final ObjectMap settings = new ObjectMap<>(); - public OlGameDialog() { - super("@settings.game"); + public OlGameDialog(){ + super("@settings.game"); - addCloseButton(); + addCloseButton(); - rebuild(); - } + rebuild(); + } - public void addCheck(String name, @Nullable String description, String setting, boolean def, Boolc cons) { - CheckBox box = new CheckBox(name); - box.update(() -> box.setChecked(Core.settings.getBool(setting, def))); - box.changed(() -> { - Core.settings.put(setting, box.isChecked()); - cons.get(box.isChecked()); - }); - box.left(); - cont.add(box).left().padTop(3f).get(); - if (description != null) Vars.ui.addDescTooltip(box, description); - settings.put(setting, def); - cont.row(); - } + public void addCheck(String name, @Nullable String description, String setting, boolean def, Boolc cons){ + CheckBox box = new CheckBox(name); + box.update(() -> box.setChecked(Core.settings.getBool(setting, def))); + box.changed(() -> { + Core.settings.put(setting, box.isChecked()); + cons.get(box.isChecked()); + }); + box.left(); + cont.add(box).left().padTop(3f).get(); + if(description != null) Vars.ui.addDescTooltip(box, description); + settings.put(setting, def); + cont.row(); + } - public void addSlider(String name, @Nullable String description, String setting, Slider slider, float def, Func sp) { - slider.setValue(Core.settings.getFloat(setting, def)); - Label value = new Label("", Styles.outlineLabel); - Table content = new Table(); - content.add(name, Styles.outlineLabel).left().growX().wrap(); - content.add(value).padLeft(10f).right(); - content.margin(3f, 33f, 3f, 33f); - content.touchable = Touchable.disabled; - slider.changed(() -> { - Core.settings.put(setting, slider.getValue()); - value.setText(sp.get(slider.getValue())); - }); - slider.change(); - Stack added = cont.stack(slider, content).width(Math.min(Core.graphics.getWidth() / 1.2f, 460f)).left().padTop(4f).get(); - if (description != null) Vars.ui.addDescTooltip(added, description); - settings.put(setting, def); - cont.row(); - } + public void addSlider(String name, @Nullable String description, String setting, Slider slider, float def, Func sp){ + slider.setValue(Core.settings.getFloat(setting, def)); + Label value = new Label("", Styles.outlineLabel); + Table content = new Table(); + content.add(name, Styles.outlineLabel).left().growX().wrap(); + content.add(value).padLeft(10f).right(); + content.margin(3f, 33f, 3f, 33f); + content.touchable = Touchable.disabled; + slider.changed(() -> { + Core.settings.put(setting, slider.getValue()); + value.setText(sp.get(slider.getValue())); + }); + slider.change(); + Stack added = cont.stack(slider, content).width(Math.min(Core.graphics.getWidth() / 1.2f, 460f)).left().padTop(4f).get(); + if(description != null) Vars.ui.addDescTooltip(added, description); + settings.put(setting, def); + cont.row(); + } - public void rebuild() { - cont.clear(); + public void rebuild(){ + cont.clear(); - addSlider( - "@setting.omaloon-shield-opacity", null, "omaloon-shield-opacity", - new Slider(0, 100, 1, false), 20, - f -> Strings.autoFixed(f, 20) + "%" - ); + addSlider( + "@setting.omaloon-shield-opacity", null, "omaloon-shield-opacity", + new Slider(0, 100, 1, false), 20, + f -> Strings.autoFixed(f, 20) + "%" + ); - addCheck( - "@setting.omaloon-show-disclaimer", null, "omaloon-show-disclaimer", - false, b -> {} - ); - addCheck( - "@setting.omaloon-enable-soft-cleaner", "@setting.omaloon-enable-soft-cleaner.description", "omaloon-enable-soft-cleaner", - true, b -> {} - ); - addCheck( - "@setting.omaloon-check-updates", null, "omaloon-check-updates", - true, b -> {} - ); + addCheck( + "@setting.omaloon-show-disclaimer", null, "omaloon-show-disclaimer", + false, b -> { + } + ); + addCheck( + "@setting.omaloon-enable-soft-cleaner", "@setting.omaloon-enable-soft-cleaner.description", "omaloon-enable-soft-cleaner", + true, b -> { + } + ); + addCheck( + "@setting.omaloon-check-updates", null, "omaloon-check-updates", + true, b -> { + } + ); - addCheck( - "@setting.omaloon-display-liquid-stats", "@setting.omaloon-display-liquid-stats.description", "omaloon-display-liquid-stats", - true, b -> {} - ); + addCheck( + "@setting.omaloon-display-liquid-stats", "@setting.omaloon-display-liquid-stats.description", "omaloon-display-liquid-stats", + true, b -> { + } + ); - cont.button("@settings.reset", () -> { - resetToDefaults(); - rebuild(); - }).size(250, 50); - } + cont.button("@settings.reset", () -> { + resetToDefaults(); + rebuild(); + }).size(250, 50); + } - public void resetToDefaults() { - settings.each((name, value) -> Core.settings.put(name, value)); - } + public void resetToDefaults(){ + settings.each((name, value) -> Core.settings.put(name, value)); + } } diff --git a/src/omaloon/ui/dialogs/OlInputDialog.java b/src/omaloon/ui/dialogs/OlInputDialog.java index 0c01647b..ccdf89fb 100644 --- a/src/omaloon/ui/dialogs/OlInputDialog.java +++ b/src/omaloon/ui/dialogs/OlInputDialog.java @@ -17,141 +17,141 @@ import static arc.Core.*; -public class OlInputDialog extends BaseDialog { - ObjectMap categories = new ObjectMap<>(); - Table rebindTable; - Dialog rebindDialog; - - boolean rebindAxis, rebindMin; - KeyBinds.KeyBind rebindKey; - KeyCode minKey; - - public OlInputDialog() { - super("@keybind.title"); - addCloseButton(); - setFillParent(true); - fill(Styles.black5, t -> rebindTable = t); - rebindTable.actions(Actions.fadeOut(0)); - rebindDialog = new Dialog("a", new DialogStyle() {{ - titleFont = Fonts.def; - }}); - shown(this::build); - } - - private void build() { - cont.clear(); - categories.clear(); - cont.pane(table -> { - for (KeyBinds.Section section : keybinds.getSections()) { - var binds = OlBinding.values(); - for (OlBinding keybind : binds) { - Table t = categories.get(keybind.category(), () -> { - table.row(); - return table.table(init -> { - init.label(() -> Core.bundle.get("binding.category-" + keybind.category())).color(Pal.accent).row(); - init.image().color(Pal.accent).growX().row(); - }).get().table().minWidth(400f).padTop(10f).growX().get(); - }); - - if(keybind.defaultValue(section.device.type()) instanceof KeyBinds.Axis) { - t.add(bundle.get("keybind." + keybind.name() + ".name", Strings.capitalize(keybind.name())), Color.white).left().padRight(40).padLeft(8); - - t.labelWrap(() -> { - KeyBinds.Axis axis = keybinds.get(section, keybind); - return axis.key != null ? axis.key.toString() : axis.min + " [red]/[] " + axis.max; - }).color(Pal.accent).left().minWidth(90).fillX().padRight(20); - - t.button("@settings.rebind", Styles.defaultt, () -> { - if (!rebindTable.hasActions()) { - rebindAxis = true; - rebindMin = true; - openDialog(section, keybind, true); - } - }).width(130f); - }else{ - t.add(bundle.get("keybind." + keybind.name() + ".name", Strings.capitalize(keybind.name())), Color.white).left().padRight(40).padLeft(8); - t.label(() -> keybinds.get(section, keybind).key.toString()).color(Pal.accent).left().minWidth(90).padRight(20); - - t.button("@settings.rebind", Styles.defaultt, () -> { - if (!rebindTable.hasActions()) { - rebindAxis = false; - rebindMin = false; - openDialog(section, keybind, true); - } - }).width(130f); - } - t.button("@settings.resetKey", Styles.defaultt, () -> keybinds.resetToDefault(section, keybind)).width(130f).pad(2f).padLeft(4f); - t.row(); - } - } - }).height(800f); - } - - private void openDialog(KeyBinds.Section section, KeyBinds.KeyBind name, boolean act) { - rebindTable.clear(); - rebindTable.add(rebindAxis ? bundle.get("keybind.press.axis") : bundle.get("keybind.press")); - rebindKey = name; - rebindDialog.show(); - - rebindDialog.clear(); - if(section.device.type() == InputDevice.DeviceType.keyboard){ - rebindDialog.addListener(new InputListener(){ - @Override - public boolean touchDown(InputEvent event, float x, float y, int pointer, KeyCode button){ - if(Core.app.isAndroid() || rebindTable.hasActions()) return false; - rebind(section, name, button); - return false; - } - - @Override - public boolean keyDown(InputEvent event, KeyCode keycode){ - if(keycode == KeyCode.escape || rebindTable.hasActions()) return false; - rebind(section, name, keycode); - return false; - } - - @Override - public boolean scrolled(InputEvent event, float x, float y, float amountX, float amountY){ - if(!rebindAxis || rebindTable.hasActions()) return false; - rebind(section, name, KeyCode.scroll); - return false; - } - }); - } - - if (act) rebindTable.actions( - Actions.moveBy(rebindTable.getWidth(), 0), - Actions.fadeIn(0), - Actions.moveBy(-rebindTable.getWidth(), 0f, 0.5f, Interp.sine) - ); - - Time.runTask(30f, () -> getScene().setScrollFocus(rebindDialog)); - } - - private void rebind(KeyBinds.Section section, KeyBinds.KeyBind bind, KeyCode newKey) { - rebindDialog.hide(); - if (rebindKey == null) return; - boolean isAxis = bind.defaultValue(section.device.type()) instanceof KeyBinds.Axis; - - if(isAxis){ - if(newKey.axis || !rebindMin){ - section.binds.get(section.device.type(), OrderedMap::new).put(rebindKey, newKey.axis ? new KeyBinds.Axis(newKey) : new KeyBinds.Axis(minKey, newKey)); - } - }else{ - section.binds.get(section.device.type(), OrderedMap::new).put(rebindKey, new KeyBinds.Axis(newKey)); - } - - if(rebindAxis && isAxis && rebindMin && !newKey.axis){ - minKey = newKey; - openDialog(section, rebindKey, false); - }else{ - rebindKey = null; - rebindAxis = false; - rebindTable.actions( - Actions.moveBy(rebindTable.getWidth(), 0f, 0.5f, Interp.sine), - Actions.fadeOut(0f), - Actions.moveBy(-rebindTable.getWidth(), 0f) - ); - } - } +public class OlInputDialog extends BaseDialog{ + ObjectMap categories = new ObjectMap<>(); + Table rebindTable; + Dialog rebindDialog; + + boolean rebindAxis, rebindMin; + KeyBinds.KeyBind rebindKey; + KeyCode minKey; + + public OlInputDialog(){ + super("@keybind.title"); + addCloseButton(); + setFillParent(true); + fill(Styles.black5, t -> rebindTable = t); + rebindTable.actions(Actions.fadeOut(0)); + rebindDialog = new Dialog("a", new DialogStyle(){{ + titleFont = Fonts.def; + }}); + shown(this::build); + } + + private void build(){ + cont.clear(); + categories.clear(); + cont.pane(table -> { + for(KeyBinds.Section section : keybinds.getSections()){ + var binds = OlBinding.values(); + for(OlBinding keybind : binds){ + Table t = categories.get(keybind.category(), () -> { + table.row(); + return table.table(init -> { + init.label(() -> Core.bundle.get("binding.category-" + keybind.category())).color(Pal.accent).row(); + init.image().color(Pal.accent).growX().row(); + }).get().table().minWidth(400f).padTop(10f).growX().get(); + }); + + if(keybind.defaultValue(section.device.type()) instanceof KeyBinds.Axis){ + t.add(bundle.get("keybind." + keybind.name() + ".name", Strings.capitalize(keybind.name())), Color.white).left().padRight(40).padLeft(8); + + t.labelWrap(() -> { + KeyBinds.Axis axis = keybinds.get(section, keybind); + return axis.key != null ? axis.key.toString() : axis.min + " [red]/[] " + axis.max; + }).color(Pal.accent).left().minWidth(90).fillX().padRight(20); + + t.button("@settings.rebind", Styles.defaultt, () -> { + if(!rebindTable.hasActions()){ + rebindAxis = true; + rebindMin = true; + openDialog(section, keybind, true); + } + }).width(130f); + }else{ + t.add(bundle.get("keybind." + keybind.name() + ".name", Strings.capitalize(keybind.name())), Color.white).left().padRight(40).padLeft(8); + t.label(() -> keybinds.get(section, keybind).key.toString()).color(Pal.accent).left().minWidth(90).padRight(20); + + t.button("@settings.rebind", Styles.defaultt, () -> { + if(!rebindTable.hasActions()){ + rebindAxis = false; + rebindMin = false; + openDialog(section, keybind, true); + } + }).width(130f); + } + t.button("@settings.resetKey", Styles.defaultt, () -> keybinds.resetToDefault(section, keybind)).width(130f).pad(2f).padLeft(4f); + t.row(); + } + } + }).height(800f); + } + + private void openDialog(KeyBinds.Section section, KeyBinds.KeyBind name, boolean act){ + rebindTable.clear(); + rebindTable.add(rebindAxis ? bundle.get("keybind.press.axis") : bundle.get("keybind.press")); + rebindKey = name; + rebindDialog.show(); + + rebindDialog.clear(); + if(section.device.type() == InputDevice.DeviceType.keyboard){ + rebindDialog.addListener(new InputListener(){ + @Override + public boolean touchDown(InputEvent event, float x, float y, int pointer, KeyCode button){ + if(Core.app.isAndroid() || rebindTable.hasActions()) return false; + rebind(section, name, button); + return false; + } + + @Override + public boolean keyDown(InputEvent event, KeyCode keycode){ + if(keycode == KeyCode.escape || rebindTable.hasActions()) return false; + rebind(section, name, keycode); + return false; + } + + @Override + public boolean scrolled(InputEvent event, float x, float y, float amountX, float amountY){ + if(!rebindAxis || rebindTable.hasActions()) return false; + rebind(section, name, KeyCode.scroll); + return false; + } + }); + } + + if(act) rebindTable.actions( + Actions.moveBy(rebindTable.getWidth(), 0), + Actions.fadeIn(0), + Actions.moveBy(-rebindTable.getWidth(), 0f, 0.5f, Interp.sine) + ); + + Time.runTask(30f, () -> getScene().setScrollFocus(rebindDialog)); + } + + private void rebind(KeyBinds.Section section, KeyBinds.KeyBind bind, KeyCode newKey){ + rebindDialog.hide(); + if(rebindKey == null) return; + boolean isAxis = bind.defaultValue(section.device.type()) instanceof KeyBinds.Axis; + + if(isAxis){ + if(newKey.axis || !rebindMin){ + section.binds.get(section.device.type(), OrderedMap::new).put(rebindKey, newKey.axis ? new KeyBinds.Axis(newKey) : new KeyBinds.Axis(minKey, newKey)); + } + }else{ + section.binds.get(section.device.type(), OrderedMap::new).put(rebindKey, new KeyBinds.Axis(newKey)); + } + + if(rebindAxis && isAxis && rebindMin && !newKey.axis){ + minKey = newKey; + openDialog(section, rebindKey, false); + }else{ + rebindKey = null; + rebindAxis = false; + rebindTable.actions( + Actions.moveBy(rebindTable.getWidth(), 0f, 0.5f, Interp.sine), + Actions.fadeOut(0f), + Actions.moveBy(-rebindTable.getWidth(), 0f) + ); + } + } } diff --git a/src/omaloon/ui/dialogs/OlUpdateCheckerDialog.java b/src/omaloon/ui/dialogs/OlUpdateCheckerDialog.java index 7a0f5953..b2314887 100644 --- a/src/omaloon/ui/dialogs/OlUpdateCheckerDialog.java +++ b/src/omaloon/ui/dialogs/OlUpdateCheckerDialog.java @@ -1,22 +1,22 @@ package omaloon.ui.dialogs; -import arc.Core; +import arc.*; import arc.files.*; -import arc.input.KeyCode; +import arc.input.*; import arc.util.*; import arc.util.io.*; import arc.util.serialization.*; -import java.net.*; - -import mindustry.Vars; +import mindustry.*; import mindustry.gen.*; import mindustry.mod.*; import mindustry.ui.dialogs.*; +import java.net.*; + import static arc.Core.*; import static mindustry.Vars.*; -public class OlUpdateCheckerDialog { +public class OlUpdateCheckerDialog{ public static final String repo = "xstabux/Omaloon"; public static Mods.LoadedMod mod = Vars.mods.locateMod("omaloon"); @@ -26,7 +26,7 @@ public class OlUpdateCheckerDialog { public static float progress; public static String download; - public static void check() { + public static void check(){ Log.info("Checking for Omaloon updates..."); Http.get(url, res -> { @@ -38,11 +38,11 @@ public static void check() { BaseDialog dialog = new BaseDialog("@dialog.omaloon-updater.tile"); dialog.cont.add(bundle.format("dialog.omaloon-updater", mod.meta.version, latest)) - .width(mobile ? 400f : 500f) - .wrap() - .pad(4f) - .get() - .setAlignment(Align.center, Align.center); + .width(mobile ? 400f : 500f) + .wrap() + .pad(4f) + .get() + .setAlignment(Align.center, Align.center); dialog.buttons.defaults().size(200f, 54f).pad(2f); @@ -74,7 +74,8 @@ public static void update(){ } mod.loader = null; - }catch(Throwable ignored){} + }catch(Throwable ignored){ + } ui.loadfrag.show("@downloading"); ui.loadfrag.setProgress(() -> progress); @@ -82,15 +83,15 @@ public static void update(){ Http.get(download, OlUpdateCheckerDialog::handle); } - public static void handle(Http.HttpResponse res) { + public static void handle(Http.HttpResponse res){ try{ Fi file = tmpDirectory.child(repo.replace("/", "") + ".zip"); Streams.copyProgress( - res.getResultAsStream(), - file.write(false), - res.getContentLength(), - 4096, - p -> progress = p + res.getResultAsStream(), + file.write(false), + res.getContentLength(), + 4096, + p -> progress = p ); mods.importMod(file).setRepo(repo); @@ -98,6 +99,7 @@ public static void handle(Http.HttpResponse res) { app.post(ui.loadfrag::hide); ui.showInfoOnHidden("@mods.reloadexit", app::exit); - }catch(Throwable ignored){} + }catch(Throwable ignored){ + } } } diff --git a/src/omaloon/ui/elements/CenterBar.java b/src/omaloon/ui/elements/CenterBar.java index 64335209..1a4cd14d 100644 --- a/src/omaloon/ui/elements/CenterBar.java +++ b/src/omaloon/ui/elements/CenterBar.java @@ -11,120 +11,120 @@ import mindustry.gen.*; import mindustry.ui.*; -public class CenterBar extends Bar { - private Floatp fraction; - private CharSequence name = ""; - private float value, lastValue, blink, outlineRadius; - private Color blinkColor = new Color(), outlineColor = new Color(); - - public CenterBar(String name, Color color, Floatp fraction) { - this.fraction = fraction; - this.name = Core.bundle.get(name, name); - this.blinkColor.set(color); - lastValue = value = fraction.get(); - setColor(color); - } - - public CenterBar(Prov name, Prov color, Floatp fraction) { - this.fraction = fraction; - lastValue = value = Mathf.clamp(fraction.get()); - update(() -> { - this.name = name.get(); - this.blinkColor.set(color.get()); - setColor(color.get()); - }); - } - - public CenterBar() { - - } - - public void reset(float value){ - this.value = lastValue = blink = value; - } - - public void set(Prov name, Floatp fraction, Color color){ - this.fraction = fraction; - this.lastValue = fraction.get(); - this.blinkColor.set(color); - setColor(color); - update(() -> this.name = name.get()); - } - - public void snap(){ - lastValue = value = fraction.get(); - } - - public Bar outline(Color color, float stroke){ - outlineColor.set(color); - outlineRadius = Scl.scl(stroke); - return this; - } - - public void flash(){ - blink = 1f; - } - - public Bar blink(Color color){ - blinkColor.set(color); - return this; - } - - @Override - public void draw(){ - if(fraction == null) return; - - float computed = Mathf.clamp(fraction.get(), -1f, 1f); - - - if(lastValue > computed){ - blink = 1f; - lastValue = computed; - } - - if(Float.isNaN(lastValue)) lastValue = 0; - if(Float.isInfinite(lastValue)) lastValue = 1f; - if(Float.isNaN(value)) value = 0; - if(Float.isInfinite(value)) value = 1f; - if(Float.isNaN(computed)) computed = 0; - if(Float.isInfinite(computed)) computed = 1f; - - blink = Mathf.lerpDelta(blink, 0f, 0.2f); - value = Mathf.lerpDelta(value, computed, 0.15f); - - Drawable bar = Tex.bar; - - if(outlineRadius > 0){ - Draw.color(outlineColor); - bar.draw(x - outlineRadius, y - outlineRadius, width + outlineRadius*2, height + outlineRadius*2); - } - - Draw.colorl(0.1f); - Draw.alpha(parentAlpha); - bar.draw(x, y, width, height); - Draw.color(color, blinkColor, blink); - Draw.alpha(parentAlpha); - - Drawable top = Tex.barTop; - - top.draw( - x + (width/2f - Core.atlas.find("bar-top").width/2f) * (Math.min(value, 0f) + 1f), - y, - Core.atlas.find("bar-top").width + (-Core.atlas.find("bar-top").width/2f + width/2f) * Math.abs(value), - height - ); - - Draw.color(); - - Font font = Fonts.outline; - GlyphLayout lay = Pools.obtain(GlyphLayout.class, GlyphLayout::new); - lay.setText(font, name); - - font.setColor(1f, 1f, 1f, 1f); - font.getCache().clear(); - font.getCache().addText(name, x + width / 2f - lay.width / 2f, y + height / 2f + lay.height / 2f + 1); - font.getCache().draw(parentAlpha); - - Pools.free(lay); - } +public class CenterBar extends Bar{ + private Floatp fraction; + private CharSequence name = ""; + private float value, lastValue, blink, outlineRadius; + private Color blinkColor = new Color(), outlineColor = new Color(); + + public CenterBar(String name, Color color, Floatp fraction){ + this.fraction = fraction; + this.name = Core.bundle.get(name, name); + this.blinkColor.set(color); + lastValue = value = fraction.get(); + setColor(color); + } + + public CenterBar(Prov name, Prov color, Floatp fraction){ + this.fraction = fraction; + lastValue = value = Mathf.clamp(fraction.get()); + update(() -> { + this.name = name.get(); + this.blinkColor.set(color.get()); + setColor(color.get()); + }); + } + + public CenterBar(){ + + } + + public void reset(float value){ + this.value = lastValue = blink = value; + } + + public void set(Prov name, Floatp fraction, Color color){ + this.fraction = fraction; + this.lastValue = fraction.get(); + this.blinkColor.set(color); + setColor(color); + update(() -> this.name = name.get()); + } + + public void snap(){ + lastValue = value = fraction.get(); + } + + public Bar outline(Color color, float stroke){ + outlineColor.set(color); + outlineRadius = Scl.scl(stroke); + return this; + } + + public void flash(){ + blink = 1f; + } + + public Bar blink(Color color){ + blinkColor.set(color); + return this; + } + + @Override + public void draw(){ + if(fraction == null) return; + + float computed = Mathf.clamp(fraction.get(), -1f, 1f); + + + if(lastValue > computed){ + blink = 1f; + lastValue = computed; + } + + if(Float.isNaN(lastValue)) lastValue = 0; + if(Float.isInfinite(lastValue)) lastValue = 1f; + if(Float.isNaN(value)) value = 0; + if(Float.isInfinite(value)) value = 1f; + if(Float.isNaN(computed)) computed = 0; + if(Float.isInfinite(computed)) computed = 1f; + + blink = Mathf.lerpDelta(blink, 0f, 0.2f); + value = Mathf.lerpDelta(value, computed, 0.15f); + + Drawable bar = Tex.bar; + + if(outlineRadius > 0){ + Draw.color(outlineColor); + bar.draw(x - outlineRadius, y - outlineRadius, width + outlineRadius * 2, height + outlineRadius * 2); + } + + Draw.colorl(0.1f); + Draw.alpha(parentAlpha); + bar.draw(x, y, width, height); + Draw.color(color, blinkColor, blink); + Draw.alpha(parentAlpha); + + Drawable top = Tex.barTop; + + top.draw( + x + (width / 2f - Core.atlas.find("bar-top").width / 2f) * (Math.min(value, 0f) + 1f), + y, + Core.atlas.find("bar-top").width + (-Core.atlas.find("bar-top").width / 2f + width / 2f) * Math.abs(value), + height + ); + + Draw.color(); + + Font font = Fonts.outline; + GlyphLayout lay = Pools.obtain(GlyphLayout.class, GlyphLayout::new); + lay.setText(font, name); + + font.setColor(1f, 1f, 1f, 1f); + font.getCache().clear(); + font.getCache().addText(name, x + width / 2f - lay.width / 2f, y + height / 2f + lay.height / 2f + 1); + font.getCache().draw(parentAlpha); + + Pools.free(lay); + } } diff --git a/src/omaloon/ui/fragments/CliffFragment.java b/src/omaloon/ui/fragments/CliffFragment.java index 79384993..fa31e2fd 100644 --- a/src/omaloon/ui/fragments/CliffFragment.java +++ b/src/omaloon/ui/fragments/CliffFragment.java @@ -16,67 +16,67 @@ import static mindustry.Vars.*; -public class CliffFragment extends Table { - private Table layout; - private boolean enabled; - private final Color col = Color.valueOf("645654"); +public class CliffFragment extends Table{ + private Table layout; + private boolean enabled; + private final Color col = Color.valueOf("645654"); - public CliffFragment() { - setFillParent(true); - visible(() -> ui.hudfrag.shown && OmaloonMod.editorListener.isEditor()); - touchable(() -> enabled && visible ? Touchable.enabled : Touchable.disabled); - left(); + public CliffFragment(){ + setFillParent(true); + visible(() -> ui.hudfrag.shown && OmaloonMod.editorListener.isEditor()); + touchable(() -> enabled && visible ? Touchable.enabled : Touchable.disabled); + left(); - add(layout = new Table(Styles.black5, t -> { - t.table(title -> { - title.image(Icon.treeSmall).size(15f).center().padRight(15f).color(col); - title.label(() -> "@fragment.omaloon.cliff-placer").grow(); - title.image(Icon.treeSmall).size(15f).center().padLeft(15f).color(col); - }).growX().padBottom(10f).row(); - t.table(Styles.black3, buttons -> { - buttons.button("@ui.omaloon-process-cliffs", Icon.play, Styles.nonet, OlCliff::processCliffs).growX().height(50f).pad(5f).row(); - buttons.button("@ui.omaloon-un-process-cliffs", Icon.undo, Styles.nonet, OlCliff::unProcessCliffs).growX().height(50f).pad(5f); - }).growX(); - })).margin(10f); - } + add(layout = new Table(Styles.black5, t -> { + t.table(title -> { + title.image(Icon.treeSmall).size(15f).center().padRight(15f).color(col); + title.label(() -> "@fragment.omaloon.cliff-placer").grow(); + title.image(Icon.treeSmall).size(15f).center().padLeft(15f).color(col); + }).growX().padBottom(10f).row(); + t.table(Styles.black3, buttons -> { + buttons.button("@ui.omaloon-process-cliffs", Icon.play, Styles.nonet, OlCliff::processCliffs).growX().height(50f).pad(5f).row(); + buttons.button("@ui.omaloon-un-process-cliffs", Icon.undo, Styles.nonet, OlCliff::unProcessCliffs).growX().height(50f).pad(5f); + }).growX(); + })).margin(10f); + } - public void build(Group parent) { - layout.actions(Actions.alpha(0)); - parent.addChildAt(0, this); + public void build(Group parent){ + layout.actions(Actions.alpha(0)); + parent.addChildAt(0, this); - if (!mobile) { - Core.scene.addListener(new InputListener() { - @Override - public boolean keyDown(InputEvent event, KeyCode keycode) { - if (Core.input.keyTap(OlBinding.cliff_placer) && visible) { - toggle(); - return true; - } - return false; - } - }); - } - } + if(!mobile){ + Core.scene.addListener(new InputListener(){ + @Override + public boolean keyDown(InputEvent event, KeyCode keycode){ + if(Core.input.keyTap(OlBinding.cliff_placer) && visible){ + toggle(); + return true; + } + return false; + } + }); + } + } - private void toggle() { - if (!visible || layout.hasActions()) return; - enabled = !enabled; - if (enabled) { - layout.actions( - Actions.moveBy(-layout.getWidth(), 0), - Actions.parallel( - Actions.alpha(1, 0.3f, Interp.pow3Out), - Actions.moveBy(layout.getWidth(), 0, 0.3f, Interp.pow3Out) - ) - ); - } else { - layout.actions( - Actions.parallel( - Actions.moveBy(-layout.getWidth(), 0, 0.3f, Interp.pow3Out), - Actions.alpha(0, 0.3f, Interp.pow3Out) - ), - Actions.moveBy(layout.getWidth(), 0) - ); - } - } + private void toggle(){ + if(!visible || layout.hasActions()) return; + enabled = !enabled; + if(enabled){ + layout.actions( + Actions.moveBy(-layout.getWidth(), 0), + Actions.parallel( + Actions.alpha(1, 0.3f, Interp.pow3Out), + Actions.moveBy(layout.getWidth(), 0, 0.3f, Interp.pow3Out) + ) + ); + }else{ + layout.actions( + Actions.parallel( + Actions.moveBy(-layout.getWidth(), 0, 0.3f, Interp.pow3Out), + Actions.alpha(0, 0.3f, Interp.pow3Out) + ), + Actions.moveBy(layout.getWidth(), 0) + ); + } + } } diff --git a/src/omaloon/ui/fragments/ShapedEnvPlacerFragment.java b/src/omaloon/ui/fragments/ShapedEnvPlacerFragment.java index 11e60bec..c419fd2a 100644 --- a/src/omaloon/ui/fragments/ShapedEnvPlacerFragment.java +++ b/src/omaloon/ui/fragments/ShapedEnvPlacerFragment.java @@ -27,7 +27,7 @@ import static arc.Core.*; import static mindustry.Vars.*; -import static omaloon.OmaloonMod.*; +import static omaloon.OmaloonMod.shapedEnvPlacerFragment; public class ShapedEnvPlacerFragment extends Table{ private Table indicator; @@ -40,12 +40,12 @@ public class ShapedEnvPlacerFragment extends Table{ private final int[] group1 = {1, 5, 3, 7}; // ↑1, →1, ↓1, ←1 private final int[] group2 = {2, 6, 4, 8}; // ↑2, →2, ↓2, ←2 - public ShapedEnvPlacerFragment() { + public ShapedEnvPlacerFragment(){ setFillParent(true); visible(() -> ui.hudfrag.shown && OmaloonMod.editorListener.isEditor()); touchable(() -> selecting && visible ? Touchable.enabled : Touchable.disabled); update(() -> { - if (selecting) { + if(selecting){ scene.setKeyboardFocus(this); scene.setScrollFocus(this); } @@ -64,33 +64,33 @@ public ShapedEnvPlacerFragment() { t1.pane(Styles.smallPane, selector -> content.blocks().each(block -> block instanceof CustomShapeProp, block -> { Button b = selector.button( - button -> button.add(new Image(block.uiIcon).setScaling(Scaling.fit)).size(32), - new Button.ButtonStyle() {{ - up = Tex.windowEmpty; - down = Tex.windowEmpty; - checked = Tex.buttonSelect; - }}, - () -> { - currentBlock = block; - currentShape = 1; - } + button -> button.add(new Image(block.uiIcon).setScaling(Scaling.fit)).size(32), + new Button.ButtonStyle(){{ + up = Tex.windowEmpty; + down = Tex.windowEmpty; + checked = Tex.buttonSelect; + }}, + () -> { + currentBlock = block; + currentShape = 1; + } ).size(50f).tooltip(block.localizedName).get(); b.update(() -> b.setChecked(currentBlock == block)); })).size(300f, 50f).padTop(5f); t1.row(); t1.button( - b -> b.add("@place"), - new Button.ButtonStyle() {{ - up = Tex.windowEmpty; - down = Tex.windowEmpty; - over = Tex.buttonSelect; - }}, - () -> { - if (selecting && visible) { - place(); - } - } + b -> b.add("@place"), + new Button.ButtonStyle(){{ + up = Tex.windowEmpty; + down = Tex.windowEmpty; + over = Tex.buttonSelect; + }}, + () -> { + if(selecting && visible){ + place(); + } + } ).size(120f, 40f).pad(5f); t1.setTransform(true); }).fill().bottom(); @@ -102,25 +102,25 @@ public ShapedEnvPlacerFragment() { Events.run(Trigger.draw, ShapedEnvPlacerFragment::drawPreview); } - public void build(Group parent) { + public void build(Group parent){ indicator.actions(Actions.alpha(0)); parent.addChildAt(0, this); - if (!mobile) { - scene.addListener(new InputListener() { + if(!mobile){ + scene.addListener(new InputListener(){ @Override - public boolean keyDown(InputEvent event, KeyCode keycode) { - if (input.keyTap(OlBinding.shaped_env_placer) && visible) { + public boolean keyDown(InputEvent event, KeyCode keycode){ + if(input.keyTap(OlBinding.shaped_env_placer) && visible){ toggle(); return true; } - if (selecting && visible && currentBlock != null && ((CustomShapeProp) currentBlock).canMirror) { - if (input.keyTap(Binding.schematic_flip_x)) { + if(selecting && visible && currentBlock != null && ((CustomShapeProp)currentBlock).canMirror){ + if(input.keyTap(Binding.schematic_flip_x)){ mirrorHorizontally(); return true; } - if (input.keyTap(Binding.schematic_flip_y)) { + if(input.keyTap(Binding.schematic_flip_y)){ mirrorVertically(); return true; } @@ -129,9 +129,9 @@ public boolean keyDown(InputEvent event, KeyCode keycode) { } @Override - public boolean scrolled(InputEvent event, float x, float y, float amountX, float amountY) { - if (selecting && visible) { - changeShape((int) Math.signum(-amountY)); + public boolean scrolled(InputEvent event, float x, float y, float amountX, float amountY){ + if(selecting && visible){ + changeShape((int)Math.signum(-amountY)); return true; } return false; @@ -139,50 +139,50 @@ public boolean scrolled(InputEvent event, float x, float y, float amountX, float }); } - Core.scene.root.addListener(new ElementGestureListener() { + Core.scene.root.addListener(new ElementGestureListener(){ @Override - public void tap(InputEvent event, float x, float y, int count, KeyCode button) { - if (selecting && visible && isOverIndicator(x, y)) { + public void tap(InputEvent event, float x, float y, int count, KeyCode button){ + if(selecting && visible && isOverIndicator(x, y)){ updateMousePosition(x, y); } } }); } - private boolean isOverIndicator(float x, float y) { - if (indicator == null) return true; + private boolean isOverIndicator(float x, float y){ + if(indicator == null) return true; return !(x >= indicator.x) || !(x <= indicator.x + indicator.getWidth()) || - !(y >= indicator.y) || !(y <= indicator.y + indicator.getHeight()); + !(y >= indicator.y) || !(y <= indicator.y + indicator.getHeight()); } //TODO: What a monstrosity... - private static void drawPreview() { - if (!shapedEnvPlacerFragment.selecting || !shapedEnvPlacerFragment.visible || !(shapedEnvPlacerFragment.currentBlock instanceof CustomShapeProp block)) return; + private static void drawPreview(){ + if(!shapedEnvPlacerFragment.selecting || !shapedEnvPlacerFragment.visible || !(shapedEnvPlacerFragment.currentBlock instanceof CustomShapeProp block)) return; int tileX = World.toTile(shapedEnvPlacerFragment.lastMousePosition.x); int tileY = World.toTile(shapedEnvPlacerFragment.lastMousePosition.y); int[][] overlaps = new int[Vars.world.width()][Vars.world.height()]; - for (int i = 0; i < block.shapes.get(shapedEnvPlacerFragment.currentShape - 1).blocks.initialWordsAmount; i++) { - if ((block.shapes.get(shapedEnvPlacerFragment.currentShape - 1).blocks.get(i) & 2) == 2) { + for(int i = 0; i < block.shapes.get(shapedEnvPlacerFragment.currentShape - 1).blocks.initialWordsAmount; i++){ + if((block.shapes.get(shapedEnvPlacerFragment.currentShape - 1).blocks.get(i) & 2) == 2){ int dx = block.shapes.get(shapedEnvPlacerFragment.currentShape - 1).unpackX(i); int dy = block.shapes.get(shapedEnvPlacerFragment.currentShape - 1).unpackY(i); Tile tile = Vars.world.tile(tileX + dx, tileY + dy); - if (tile != null) { + if(tile != null){ Draw.z(Layer.overlayUI); Lines.stroke(2f, (tile.block() instanceof StaticWall || tile.block() instanceof CustomShapeProp) ? Pal.remove : Pal.accent); Draw.alpha(0.7f); Fill.square(tile.worldx(), tile.worldy(), tilesize / 2f); // Check neighboring tiles only if current tile is not StaticWall or CustomShapeProp - if (!(tile.block() instanceof StaticWall || tile.block() instanceof CustomShapeProp)) { - for (int j = 0; j < 4; j++) { + if(!(tile.block() instanceof StaticWall || tile.block() instanceof CustomShapeProp)){ + for(int j = 0; j < 4; j++){ int neighborX = tileX + dx + Geometry.d4x[j]; int neighborY = tileY + dy + Geometry.d4y[j]; Tile neighborTile = Vars.world.tile(neighborX, neighborY); - if (neighborTile != null && neighborTile.block() instanceof CustomShapeProp && overlaps[neighborX][neighborY] < 2) { + if(neighborTile != null && neighborTile.block() instanceof CustomShapeProp && overlaps[neighborX][neighborY] < 2){ Draw.z(Layer.overlayUI); Lines.stroke(2f, Pal.remove); Draw.alpha(0.35f); @@ -197,25 +197,25 @@ private static void drawPreview() { Draw.reset(); } - private boolean canPlace() { - if (!(currentBlock instanceof CustomShapeProp block)) return false; + private boolean canPlace(){ + if(!(currentBlock instanceof CustomShapeProp block)) return false; int tileX = World.toTile(lastMousePosition.x); int tileY = World.toTile(lastMousePosition.y); - for (int i = 0; i < block.shapes.get(currentShape - 1).blocks.initialWordsAmount; i++) { - if ((block.shapes.get(currentShape - 1).blocks.get(i) & 2) == 2) { + for(int i = 0; i < block.shapes.get(currentShape - 1).blocks.initialWordsAmount; i++){ + if((block.shapes.get(currentShape - 1).blocks.get(i) & 2) == 2){ int dx = block.shapes.get(currentShape - 1).unpackX(i); int dy = block.shapes.get(currentShape - 1).unpackY(i); Tile tile = Vars.world.tile(tileX + dx, tileY + dy); - if (tile != null && (tile.block() instanceof StaticWall || tile.block() instanceof CustomShapeProp)) { + if(tile != null && (tile.block() instanceof StaticWall || tile.block() instanceof CustomShapeProp)){ return false; } - for (int j = 0; j < 4; j++) { + for(int j = 0; j < 4; j++){ int neighborX = tileX + dx + Geometry.d4x[j]; int neighborY = tileY + dy + Geometry.d4y[j]; Tile neighborTile = Vars.world.tile(neighborX, neighborY); - if (neighborTile != null && neighborTile.block() instanceof CustomShapeProp) { + if(neighborTile != null && neighborTile.block() instanceof CustomShapeProp){ return false; } } @@ -224,20 +224,20 @@ private boolean canPlace() { return true; } - private void place() { - if (!canPlace()) return; + private void place(){ + if(!canPlace()) return; - if (!(currentBlock instanceof CustomShapeProp block)) return; + if(!(currentBlock instanceof CustomShapeProp block)) return; int tileX = World.toTile(lastMousePosition.x); int tileY = World.toTile(lastMousePosition.y); - for (int i = 0; i < block.shapes.get(currentShape - 1).blocks.initialWordsAmount; i++) { - if ((block.shapes.get(currentShape - 1).blocks.get(i) & 2) == 2) { + for(int i = 0; i < block.shapes.get(currentShape - 1).blocks.initialWordsAmount; i++){ + if((block.shapes.get(currentShape - 1).blocks.get(i) & 2) == 2){ int dx = block.shapes.get(currentShape - 1).unpackX(i); int dy = block.shapes.get(currentShape - 1).unpackY(i); Tile tile = Vars.world.tile(tileX + dx, tileY + dy); - if (tile != null) { + if(tile != null){ Call.setTile(tile, currentBlock, tile.team(), 0); } } @@ -246,49 +246,49 @@ private void place() { CustomShapePropProcess.instance.init(); } - public void toggle() { - if (!visible || indicator.hasActions()) return; + public void toggle(){ + if(!visible || indicator.hasActions()) return; selecting = !selecting; - if (selecting) { + if(selecting){ showUI(); lastMousePosition.set(Core.input.mouseWorld()); - } else { + }else{ hideUI(); scene.setKeyboardFocus(null); scene.setScrollFocus(null); } } - private void showUI() { + private void showUI(){ indicator.actions( - Actions.moveBy(0, -indicator.getHeight()), - Actions.parallel( - Actions.alpha(1, 0.3f, Interp.pow3Out), - Actions.moveBy(0, indicator.getHeight(), 0.3f, Interp.pow3Out) - ) + Actions.moveBy(0, -indicator.getHeight()), + Actions.parallel( + Actions.alpha(1, 0.3f, Interp.pow3Out), + Actions.moveBy(0, indicator.getHeight(), 0.3f, Interp.pow3Out) + ) ); } - private void hideUI() { + private void hideUI(){ indicator.actions( - Actions.parallel( - Actions.moveBy(0, -indicator.getHeight(), 0.3f, Interp.pow3In), - Actions.alpha(0, 0.3f, Interp.pow3In) - ), - Actions.moveBy(0, indicator.getHeight()) + Actions.parallel( + Actions.moveBy(0, -indicator.getHeight(), 0.3f, Interp.pow3In), + Actions.alpha(0, 0.3f, Interp.pow3In) + ), + Actions.moveBy(0, indicator.getHeight()) ); } - private void updateMousePosition(float x, float y) { + private void updateMousePosition(float x, float y){ lastMousePosition.set(Core.input.mouseWorld(x, y)); } - private void changeShape(int delta) { - if (currentBlock instanceof CustomShapeProp) { + private void changeShape(int delta){ + if(currentBlock instanceof CustomShapeProp){ int[] currentGroup = (currentShape % 2 == 1) ? group1 : group2; int currentIndex = findIndex(currentGroup, currentShape); - if (currentIndex != -1) { + if(currentIndex != -1){ currentIndex = (currentIndex + delta + 4) % 4; currentShape = currentGroup[currentIndex]; } @@ -297,43 +297,43 @@ private void changeShape(int delta) { } } - private void mirrorVertically() { + private void mirrorVertically(){ int[][] pairs = (currentShape <= 4) ? - new int[][]{{1, 4}, {2, 3}} : - new int[][]{{5, 6}, {8, 7}}; + new int[][]{{1, 4}, {2, 3}} : + new int[][]{{5, 6}, {8, 7}}; applyMirror(pairs); } - private void mirrorHorizontally() { + private void mirrorHorizontally(){ int[][] pairs = (currentShape <= 4) ? - new int[][]{{1, 2}, {3, 4}} : - new int[][]{{5, 8}, {7, 6}}; + new int[][]{{1, 2}, {3, 4}} : + new int[][]{{5, 8}, {7, 6}}; applyMirror(pairs); } - private void applyMirror(int[][] pairs) { - for (int[] pair : pairs) { - if (currentShape == pair[0]) { + private void applyMirror(int[][] pairs){ + for(int[] pair : pairs){ + if(currentShape == pair[0]){ currentShape = pair[1]; return; - } else if (currentShape == pair[1]) { + }else if(currentShape == pair[1]){ currentShape = pair[0]; return; } } } - private int findIndex(int[] array, int value) { - for (int i = 0; i < array.length; i++) { - if (array[i] == value) { + private int findIndex(int[] array, int value){ + for(int i = 0; i < array.length; i++){ + if(array[i] == value){ return i; } } return -1; } - private void updateCurrentShape() { - if (currentBlock instanceof CustomShapeProp block) { + private void updateCurrentShape(){ + if(currentBlock instanceof CustomShapeProp block){ int totalShapes = block.shapes.size; currentShape = Math.min(Math.max(currentShape, 1), totalShapes); } diff --git a/src/omaloon/utils/IconLoader.java b/src/omaloon/utils/IconLoader.java index d18e899c..a1ed1d4e 100644 --- a/src/omaloon/utils/IconLoader.java +++ b/src/omaloon/utils/IconLoader.java @@ -11,26 +11,26 @@ import java.io.*; import java.util.*; -public class IconLoader { - public static void loadIcons() { +public class IconLoader{ + public static void loadIcons(){ Seq availableFonts = Seq.with(Fonts.def, Fonts.outline); - int fontSize = (int) (Fonts.def.getData().lineHeight / Fonts.def.getData().scaleY); + int fontSize = (int)(Fonts.def.getData().lineHeight / Fonts.def.getData().scaleY); Properties iconProperties = new Properties(); - try (Reader reader = Vars.tree.get("icons/omaloon-icons.properties").reader(512)) { + try(Reader reader = Vars.tree.get("icons/omaloon-icons.properties").reader(512)){ iconProperties.load(reader); - } catch (Exception e) { + }catch(Exception e){ return; } - for (Map.Entry entry : iconProperties.entrySet()) { - String codePointStr = (String) entry.getKey(); - String[] valueParts = ((String) entry.getValue()).split("\\|"); - if (valueParts.length < 2) { + for(Map.Entry entry : iconProperties.entrySet()){ + String codePointStr = (String)entry.getKey(); + String[] valueParts = ((String)entry.getValue()).split("\\|"); + if(valueParts.length < 2){ continue; } - try { + try{ int codePoint = Integer.parseInt(codePointStr); String textureName = valueParts[1]; TextureRegion region = Core.atlas.find(textureName); @@ -38,21 +38,22 @@ public static void loadIcons() { Vec2 scaledSize = Scaling.fit.apply(region.width, region.height, fontSize, fontSize); Font.Glyph glyph = constructGlyph(codePoint, region, scaledSize, fontSize); - for (Font font : availableFonts) { + for(Font font : availableFonts){ font.getData().setGlyph(codePoint, glyph); } - } catch (Exception ignored) {} + }catch(Exception ignored){ + } } } - private static Font.Glyph constructGlyph(int id, TextureRegion region, Vec2 size, int fontSize) { + private static Font.Glyph constructGlyph(int id, TextureRegion region, Vec2 size, int fontSize){ Font.Glyph glyph = new Font.Glyph(); glyph.id = id; glyph.srcX = 0; glyph.srcY = 0; - glyph.width = (int) size.x; - glyph.height = (int) size.y; + glyph.width = (int)size.x; + glyph.height = (int)size.y; glyph.u = region.u; glyph.v = region.v2; glyph.u2 = region.u2; diff --git a/src/omaloon/utils/OlUtils.java b/src/omaloon/utils/OlUtils.java index bec2ea64..2b056441 100644 --- a/src/omaloon/utils/OlUtils.java +++ b/src/omaloon/utils/OlUtils.java @@ -7,9 +7,9 @@ import omaloon.ui.*; import org.jetbrains.annotations.*; -import static arc.Core.*; +import static arc.Core.atlas; -public class OlUtils { +public class OlUtils{ public static float angleDistSigned(float a, float b){ a += 360f; a %= 360f; @@ -51,30 +51,33 @@ public static float clampedAngle(float angle, float relative, float limit){ } @Contract(pure = true) - public static int reverse(int rotation) { - return switch(rotation) { - case 0 -> 2; case 2 -> 0;case 1 -> 3; case 3 -> 1; + public static int reverse(int rotation){ + return switch(rotation){ + case 0 -> 2; + case 2 -> 0; + case 1 -> 3; + case 3 -> 1; default -> throw new IllegalStateException("Unexpected value: " + rotation); }; } - public static Item getByIndexAsItem(MultiItemData data, int index) { - if (index < 0 || index >= data.length()) { + public static Item getByIndexAsItem(MultiItemData data, int index){ + if(index < 0 || index >= data.length()){ throw new IndexOutOfBoundsException("Index " + index + " is out of bounds for MultiItemData of size " + data.length()); } return data.getItems().get(index); } - public static int getByIndex(IntSet intSet, int index) { - if (index < 0 || index >= intSet.size) { + public static int getByIndex(IntSet intSet, int index){ + if(index < 0 || index >= intSet.size){ throw new IndexOutOfBoundsException("Index " + index + " is out of bounds for IntSet of size " + intSet.size); } int counter = 0; - for (IntSet.IntSetIterator iterator = intSet.iterator(); iterator.hasNext; ) { + for(IntSet.IntSetIterator iterator = intSet.iterator(); iterator.hasNext; ){ int item = iterator.next(); - if (counter == index) { + if(counter == index){ return item; } counter++; @@ -83,7 +86,8 @@ public static int getByIndex(IntSet intSet, int index) { throw new IllegalArgumentException("Index out of range for IntSet."); } - /**bittiler stuff + /** + * bittiler stuff *

    * Original code from Serilia[...] */ @@ -111,9 +115,9 @@ public static TextureRegion[] split(String name, int size, int layer){ /** * reads every single pixel on a textureRegion from bottom left to top right */ - public static void readTexturePixels(PixmapRegion pixmap, Intc2 cons) { - for(int j = 0; j < pixmap.height; j++) { - for(int i = 0; i < pixmap.width; i++) { + public static void readTexturePixels(PixmapRegion pixmap, Intc2 cons){ + for(int j = 0; j < pixmap.height; j++){ + for(int i = 0; i < pixmap.width; i++){ cons.get(pixmap.get(i, j), i + pixmap.width * (pixmap.height - 1 - j)); } } diff --git a/src/omaloon/world/MultiPropGroup.java b/src/omaloon/world/MultiPropGroup.java index 69ef9c70..cbc86400 100644 --- a/src/omaloon/world/MultiPropGroup.java +++ b/src/omaloon/world/MultiPropGroup.java @@ -7,50 +7,52 @@ import mindustry.world.*; import omaloon.world.interfaces.*; -public class MultiPropGroup { - public Seq group = new Seq<>(); - public Tile center; - public int shape = 0; - public Block type; - public boolean removed = false; +public class MultiPropGroup{ + public Seq group = new Seq<>(); + public Tile center; + public int shape = 0; + public Block type; + public boolean removed = false; - public MultiPropGroup(Block type) { - this.type = type; - } + public MultiPropGroup(Block type){ + this.type = type; + } - public void findCenter() { - center = group.max(tile -> tile.x + Vars.world.width() * tile.y); - if (center == null) Log.errTag("what", "HUH?"); - } - public void findShape() { - if (!(type instanceof MultiPropI prop)) throw new IllegalArgumentException("that's not a multiprop ya dummy"); - shape = prop.shapes().indexOf(shape -> { - var find = new Object() { - boolean found = true; - }; - shape.eachRelativeCenter((x, y) -> { - switch (shape.getIdRelativeCenter(x, y)) { - case 2 -> { - if (!group.contains(center.nearby(x, y))) find.found = false; - } - case 3 -> {} - default -> { - if (group.contains(center.nearby(x, y))) find.found = false; - } - } - }); - return find.found; - }); - if (shape == -1) shape = 0; - } + public void findCenter(){ + center = group.max(tile -> tile.x + Vars.world.width() * tile.y); + if(center == null) Log.errTag("what", "HUH?"); + } - public void remove() { - group.each(tile -> tile.setBlock(Blocks.air)); - ((MultiPropI )type).removed(this).run(); - removed = true; - } + public void findShape(){ + if(!(type instanceof MultiPropI prop)) throw new IllegalArgumentException("that's not a multiprop ya dummy"); + shape = prop.shapes().indexOf(shape -> { + var find = new Object(){ + boolean found = true; + }; + shape.eachRelativeCenter((x, y) -> { + switch(shape.getIdRelativeCenter(x, y)){ + case 2 -> { + if(!group.contains(center.nearby(x, y))) find.found = false; + } + case 3 -> { + } + default -> { + if(group.contains(center.nearby(x, y))) find.found = false; + } + } + }); + return find.found; + }); + if(shape == -1) shape = 0; + } - public void update() { - if (group.contains(tile -> tile.block() != type)) remove(); - } + public void remove(){ + group.each(tile -> tile.setBlock(Blocks.air)); + ((MultiPropI)type).removed(this).run(); + removed = true; + } + + public void update(){ + if(group.contains(tile -> tile.block() != type)) remove(); + } } diff --git a/src/omaloon/world/blocks/defense/BlastTower.java b/src/omaloon/world/blocks/defense/BlastTower.java index 794fd92c..a90a84ae 100644 --- a/src/omaloon/world/blocks/defense/BlastTower.java +++ b/src/omaloon/world/blocks/defense/BlastTower.java @@ -16,17 +16,14 @@ import mindustry.world.*; import mindustry.world.consumers.*; import mindustry.world.meta.*; -import omaloon.annotations.AutoImplement; -import omaloon.annotations.Load; +import omaloon.annotations.*; import omaloon.content.*; import omaloon.world.interfaces.*; import omaloon.world.meta.*; -import omaloon.world.modules.*; -import static arc.Core.*; import static mindustry.Vars.*; -public class BlastTower extends Block { +public class BlastTower extends Block{ public PressureConfig pressureConfig = new PressureConfig(); public boolean useConsumerMultiplier = true; public float shake = 3f; @@ -65,13 +62,13 @@ public void setStats(){ } @Override - public void setBars() { + public void setBars(){ super.setBars(); pressureConfig.addBars(this); } @Override - public void drawPlanRegion(BuildPlan plan, Eachable list) { + public void drawPlanRegion(BuildPlan plan, Eachable list){ super.drawPlanRegion(plan, list); Draw.rect(hammerRegion, plan.drawx(), plan.drawy()); } @@ -88,23 +85,23 @@ public TextureRegion[] icons(){ return new TextureRegion[]{region, hammerRegion}; } - public class BlastTowerBuild extends Building implements HasPressureImpl { + public class BlastTowerBuild extends Building implements HasPressureImpl{ public float smoothProgress = 0f; public float charge; public float lastShootTime = -reload; public Seq targets = new Seq<>(); - public float efficiencyMultiplier() { + public float efficiencyMultiplier(){ float val = 1f; - if (!useConsumerMultiplier) return val; - for (Consume consumer : consumers) { + if(!useConsumerMultiplier) return val; + for(Consume consumer : consumers){ val *= consumer.efficiencyMultiplier(this); } return val; } @Override - public void draw() { + public void draw(){ Draw.rect(region, x, y); float fract = Mathf.clamp(smoothProgress, 0.25f, 0.3f); @@ -120,83 +117,83 @@ public void drawSelect(){ Drawf.dashCircle(x, y, range, Pal.accent); } - @Override - public void read(Reads read, byte revision) { - super.read(read, revision); - lastShootTime = read.f(); - smoothProgress = read.f(); - charge = read.f(); - AutoImplement.Util.Inject(HasPressureImpl.class); - } - - public void shoot() { - if (!canConsume()) return; - - consume(); - lastShootTime = Time.time; - Effect.shake(shake, shake, this); - shootSound.at(this); - waveEffect.layer(Layer.blockUnder).at(x, y, range, waveColor); - tile.getLinkedTiles(t -> OlFx.hammerHit.layer(Layer.blockUnder).at( - t.worldx(), t.worldy(), - angleTo(t.worldx(), t.worldy()) + Mathf.range(360f), - Tmp.c1.set(t.floor().mapColor).mul(1.5f + Mathf.range(0.15f))) - ); - - float damageMultiplier = efficiencyMultiplier(); - for (Teamc target : targets) { - hitEffect.at(target.x(), target.y(), hitColor); - if(target instanceof Healthc){ - ((Healthc)target).damage(damage * damageMultiplier); - } - if(target instanceof Statusc){ - ((Statusc)target).apply(status, statusDuration); - } - } - - smoothProgress = 0f; - } - - - @Override - public void updateTile() { - AutoImplement.Util.Inject(HasPressureImpl.class); - super.updateTile(); - - targets.clear(); - Units.nearbyEnemies(team, x, y, range, u -> { - if(u.checkTarget(targetAir, targetGround)) { - targets.add(u); - } - }); - - indexer.allBuildings(x, y, range, b -> { - if(b.team != team){ - targets.add(b); - } - }); - - float effMultiplier = efficiencyMultiplier(); - - if (targets.size > 0 && canConsume()) { - smoothProgress = Mathf.approach(smoothProgress, 1f, Time.delta / chargeTime * effMultiplier); - - if (efficiency > 0 && (charge += Time.delta * effMultiplier) >= reload && smoothProgress >= 0.99f) { - shoot(); - charge = 0f; - } - } else { - smoothProgress = Mathf.approach(smoothProgress, 0f, Time.delta / chargeTime * effMultiplier); - } - } - - @Override - public void write(Writes write) { - super.write(write); - write.f(lastShootTime); - write.f(smoothProgress); - write.f(charge); - AutoImplement.Util.Inject(HasPressureImpl.class); - } + @Override + public void read(Reads read, byte revision){ + super.read(read, revision); + lastShootTime = read.f(); + smoothProgress = read.f(); + charge = read.f(); + AutoImplement.Util.Inject(HasPressureImpl.class); + } + + public void shoot(){ + if(!canConsume()) return; + + consume(); + lastShootTime = Time.time; + Effect.shake(shake, shake, this); + shootSound.at(this); + waveEffect.layer(Layer.blockUnder).at(x, y, range, waveColor); + tile.getLinkedTiles(t -> OlFx.hammerHit.layer(Layer.blockUnder).at( + t.worldx(), t.worldy(), + angleTo(t.worldx(), t.worldy()) + Mathf.range(360f), + Tmp.c1.set(t.floor().mapColor).mul(1.5f + Mathf.range(0.15f))) + ); + + float damageMultiplier = efficiencyMultiplier(); + for(Teamc target : targets){ + hitEffect.at(target.x(), target.y(), hitColor); + if(target instanceof Healthc){ + ((Healthc)target).damage(damage * damageMultiplier); + } + if(target instanceof Statusc){ + ((Statusc)target).apply(status, statusDuration); + } + } + + smoothProgress = 0f; + } + + + @Override + public void updateTile(){ + AutoImplement.Util.Inject(HasPressureImpl.class); + super.updateTile(); + + targets.clear(); + Units.nearbyEnemies(team, x, y, range, u -> { + if(u.checkTarget(targetAir, targetGround)){ + targets.add(u); + } + }); + + indexer.allBuildings(x, y, range, b -> { + if(b.team != team){ + targets.add(b); + } + }); + + float effMultiplier = efficiencyMultiplier(); + + if(targets.size > 0 && canConsume()){ + smoothProgress = Mathf.approach(smoothProgress, 1f, Time.delta / chargeTime * effMultiplier); + + if(efficiency > 0 && (charge += Time.delta * effMultiplier) >= reload && smoothProgress >= 0.99f){ + shoot(); + charge = 0f; + } + }else{ + smoothProgress = Mathf.approach(smoothProgress, 0f, Time.delta / chargeTime * effMultiplier); + } + } + + @Override + public void write(Writes write){ + super.write(write); + write.f(lastShootTime); + write.f(smoothProgress); + write.f(charge); + AutoImplement.Util.Inject(HasPressureImpl.class); + } } } \ No newline at end of file diff --git a/src/omaloon/world/blocks/defense/ConsumeTurret.java b/src/omaloon/world/blocks/defense/ConsumeTurret.java index 93b4bf73..d0133be3 100644 --- a/src/omaloon/world/blocks/defense/ConsumeTurret.java +++ b/src/omaloon/world/blocks/defense/ConsumeTurret.java @@ -1,7 +1,6 @@ package omaloon.world.blocks.defense; import arc.struct.*; -import arc.util.io.*; import mindustry.content.*; import mindustry.entities.bullet.*; import mindustry.graphics.*; @@ -9,79 +8,79 @@ import mindustry.world.meta.*; import omaloon.world.interfaces.*; import omaloon.world.meta.*; -import omaloon.world.modules.*; -import static mindustry.Vars.*; +import static mindustry.Vars.tilesize; -public class ConsumeTurret extends Turret { - public PressureConfig pressureConfig = new PressureConfig(); +public class ConsumeTurret extends Turret{ + public PressureConfig pressureConfig = new PressureConfig(); - /** - * If true, this turret cannot target things that are closer than the minRange - */ - public boolean minRangeShoot = true; + /** + * If true, this turret cannot target things that are closer than the minRange + */ + public boolean minRangeShoot = true; - public BulletType shootType = Bullets.placeholder; + public BulletType shootType = Bullets.placeholder; - public ConsumeTurret(String name) { - super(name); - } + public ConsumeTurret(String name){ + super(name); + } - @Override - public void drawPlace(int x, int y, int rotation, boolean valid){ - super.drawPlace(x, y, rotation, valid); + @Override + public void drawPlace(int x, int y, int rotation, boolean valid){ + super.drawPlace(x, y, rotation, valid); - if (!minRangeShoot) Drawf.dashCircle(x * tilesize + offset, y * tilesize + offset, minRange, Pal.placing); - } + if(!minRangeShoot) Drawf.dashCircle(x * tilesize + offset, y * tilesize + offset, minRange, Pal.placing); + } - @Override - public void setStats() { - super.setStats(); - pressureConfig.addStats(stats); - } + @Override + public void setStats(){ + super.setStats(); + pressureConfig.addStats(stats); + } - @Override - public void setBars() { - super.setBars(); - pressureConfig.addBars(this); - stats.add(Stat.ammo, StatValues.ammo(ObjectMap.of(this, shootType))); - } + @Override + public void setBars(){ + super.setBars(); + pressureConfig.addBars(this); + stats.add(Stat.ammo, StatValues.ammo(ObjectMap.of(this, shootType))); + } - public class ConsumeTurretBuild extends TurretBuild implements HasPressureImpl { + public class ConsumeTurretBuild extends TurretBuild implements HasPressureImpl{ - @Override - public void drawSelect() { - super.drawSelect(); + @Override + public void drawSelect(){ + super.drawSelect(); - if (!minRangeShoot) Drawf.dashCircle(x, y, minRange, team.color); - } + if(!minRangeShoot) Drawf.dashCircle(x, y, minRange, team.color); + } - @Override - protected void findTarget() { - super.findTarget(); - if (target != null && dst(target) < minRange && !minRangeShoot) target = null; - } + @Override + protected void findTarget(){ + super.findTarget(); + if(target != null && dst(target) < minRange && !minRangeShoot) target = null; + } - @Override public boolean hasAmmo() { - return canConsume(); - } + @Override + public boolean hasAmmo(){ + return canConsume(); + } - @Override public BulletType peekAmmo() { - return shootType; - } + @Override + public BulletType peekAmmo(){ + return shootType; + } + @Override + protected void shoot(BulletType type){ + super.shoot(type); + consume(); + } - - @Override - protected void shoot(BulletType type) { - super.shoot(type); - consume(); - } - - @Override public BulletType useAmmo() { - return shootType; - } - } + @Override + public BulletType useAmmo(){ + return shootType; + } + } } diff --git a/src/omaloon/world/blocks/defense/RepairProjector.java b/src/omaloon/world/blocks/defense/RepairProjector.java index 090acb1c..0f9a3835 100644 --- a/src/omaloon/world/blocks/defense/RepairProjector.java +++ b/src/omaloon/world/blocks/defense/RepairProjector.java @@ -3,18 +3,17 @@ import arc.graphics.*; import arc.graphics.g2d.*; import arc.math.*; -import arc.struct.Seq; +import arc.struct.*; import arc.util.*; -import mindustry.content.Fx; +import mindustry.content.*; import mindustry.entities.*; import mindustry.gen.*; import mindustry.graphics.*; import mindustry.logic.*; import mindustry.world.*; import mindustry.world.meta.*; -import omaloon.annotations.Load; +import omaloon.annotations.*; -import static arc.Core.*; import static mindustry.Vars.*; public class RepairProjector extends Block{ @@ -65,7 +64,7 @@ public void updateTile(){ refresh = 0f; indexer.eachBlock(team, Tmp.r1.setCentered(x, y, range() * 2), b -> b.damaged() && !b.isHealSuppressed(), buildingTargets::add); Units.nearby(team, x, y, range(), u -> { - if(u.damaged()) { + if(u.damaged()){ unitTargets.add(u); } }); diff --git a/src/omaloon/world/blocks/defense/Shelter.java b/src/omaloon/world/blocks/defense/Shelter.java index 456bb9e1..575d4ec8 100644 --- a/src/omaloon/world/blocks/defense/Shelter.java +++ b/src/omaloon/world/blocks/defense/Shelter.java @@ -21,266 +21,267 @@ import mindustry.world.*; import mindustry.world.consumers.*; import mindustry.world.meta.*; -import omaloon.annotations.Load; +import omaloon.annotations.*; import omaloon.content.*; import omaloon.world.interfaces.*; import omaloon.world.meta.*; -import omaloon.world.modules.*; -import static omaloon.OmaloonMod.*; +import static omaloon.OmaloonMod.shieldBuffer; -public class Shelter extends Block { - @Load(value = "@-base",fallback = {"block-@size"}) - public TextureRegion baseRegion; - @Load("@-glow") +public class Shelter extends Block{ + @Load(value = "@-base", fallback = {"block-@size"}) + public TextureRegion baseRegion; + @Load("@-glow") public TextureRegion glowRegion; - public PressureConfig pressureConfig = new PressureConfig(); - - public float configSerrations = 20; - public float shieldAngle = 120f; - public float shieldHealth = 120f; - public float shieldRange = 80f; - public float rechargeStandard = 0.1f; - public float rechargeBroken = 1f; - public float warmupTime = 0.1f; - public boolean useConsumerMultiplier = true; - public float rotateSpeed = 1; - - public float glowMinAlpha = 0f, glowMaxAlpha = 0.5f, glowBlinkSpeed = 0.16f; - - public Color deflectColor = Pal.heal; - - public Effect hitEffect = Fx.absorb; - public Sound hitSound = Sounds.none; - public float hitSoundVolume = 1f; - - public Effect rotateEffect = OlFx.shelterRotate; - - private static final FrameBuffer fieldBuffer = new FrameBuffer(); - public static final Seq runs = new Seq<>(); - - { - Events.run(EventType.Trigger.draw, () -> { - fieldBuffer.resize(Core.graphics.getWidth(), Core.graphics.getHeight()); - Seq buffer = runs.copy(); - runs.clear(); - - Draw.draw(Layer.shields, () -> { - Draw.flush(); - fieldBuffer.begin(Color.clear); - buffer.each(Runnable::run); - fieldBuffer.end(); - Draw.color(deflectColor, Vars.renderer.animateShields ? 1f : Core.settings.getFloat("omaloon-shield-opacity", 20f)/100f); - EDraw.drawBuffer(fieldBuffer); - Draw.flush(); - Draw.color(); - }); - }); - } - - public Shelter(String name) { - super(name); - update = true; - solid = true; - configurable = true; - saveConfig = true; - group = BlockGroup.projectors; - ambientSound = Sounds.shield; - ambientSoundVolume = 0.08f; - pressureConfig.isWhitelist = true; - config(Float.class, (build, rot) -> ((ShelterBuild) build).rot = rot); - configClear((ShelterBuild build) -> build.rot = 90); - } - - @Override - public TextureRegion[] icons() { - return new TextureRegion[]{baseRegion, region}; - } - - @Override - public void init() { - super.init(); - clipSize = shieldRange * 2f; - } - - @Override - public void setStats() { - super.setStats(); - pressureConfig.addStats(stats); - - stats.add(Stat.shieldHealth, shieldHealth, StatUnit.none); - stats.add(Stat.cooldownTime, (int) (rechargeStandard * 60f), StatUnit.perSecond); - } - - @Override - public void setBars() { - super.setBars(); - pressureConfig.addBars(this); - addBar("shield", (ShelterBuild entity) -> new Bar("stat.shieldhealth", Pal.accent, () -> entity.broken ? 0f : 1 - entity.shieldDamage / shieldHealth).blink(Color.white)); - } - - @Override - public void drawOverlay(float x, float y, int rotation) { - Drawf.dashCircle(x, y, shieldRange, Pal.accent); - } - - @Override - public void drawPlanRegion(BuildPlan plan, Eachable list) { - Draw.rect(baseRegion, plan.drawx(), plan.drawy()); - float rot = plan.config instanceof Float ? (float) plan.config : 0; - Draw.rect(region, plan.drawx(), plan.drawy(), rot - 90); - } - - public class ShelterBuild extends Building implements HasPressureImpl { - - - public float rot = 90; - public float shieldDamage = 0; - public float warmup = 0; - public boolean broken = false; - - public float configureWarmup = 0; - - @Override - public Float config() { - return rot; - } - - @Override - public void draw() { - configureWarmup = Mathf.approachDelta(configureWarmup, 0, 0.014f); - Draw.rect(baseRegion, x, y, 0); - Draw.rect(region, x, y, rot - 90); - - float z = Draw.z(); - Draw.z(Layer.blockAdditive); - Draw.blend(Blending.additive); - Draw.color(Color.valueOf("cbffc2")); - - float cycleAlpha = glowMinAlpha + (glowMaxAlpha - glowMinAlpha) * (0.5f + 0.5f * Mathf.sin(Time.time * glowBlinkSpeed)); - Draw.alpha(warmup * cycleAlpha); - Draw.rect(glowRegion, x, y, rot - 90); - Draw.reset(); - Draw.blend(); - Draw.z(z); - - runs.add(() -> { - Draw.color(); - Fill.circle(x, y, warmup * (hitSize() * 1.2f)); - Fill.arc(x, y, shieldRange * warmup, shieldAngle/360f, -shieldAngle/2f + rot); - Draw.color(); - }); - - Draw.z(Layer.blockOver); - float mousex = Core.input.mouseWorldX(), mousey = Core.input.mouseWorldY(); - - Draw.color(Pal.accent, Interp.circle.apply(configureWarmup) * Core.settings.getFloat("omaloon-shield-opacity", 20f)/100f); - Fill.arc(x, y, shieldRange * Interp.circle.apply(configureWarmup), shieldAngle/360f, -shieldAngle/2f + Core.input.mouseWorld().angleTo(x, y) + 180f); - - for(int i = 0; i < configSerrations; i++) { - Tmp.v1.trns(360f/configSerrations * i, size * 8f).nor(); - float dot = Mathf.maxZero(Tmp.v1.dot(Tmp.v2.set(mousex - x, mousey - y).nor())); - Tmp.v1.trns(360f/configSerrations * i, size * 8f); - Lines.stroke(2 * Interp.circle.apply(configureWarmup), Pal.accent); - Lines.lineAngle( - Tmp.v1.x + x, Tmp.v1.y + y, - Tmp.v1.angle(), - (0.5f + 3f * Interp.circleIn.apply(dot)) * Interp.circle.apply(configureWarmup) - ); - } - } - - @Override - public void drawConfigure() { - configureWarmup = Mathf.approachDelta(configureWarmup, 1, 0.028f); - } - - @Override public float edelta() { - return super.edelta() * efficiencyMultiplier(); - } - - public float efficiencyMultiplier() { - float val = 1; - if (!useConsumerMultiplier) return val; - for (Consume consumer : consumers) { - val *= consumer.efficiencyMultiplier(this); - } - return val; - } - - @Override - public boolean onConfigureTapped(float x, float y) { - configure(Tmp.v1.set(this.x, this.y).angleTo(x, y)); - rotateEffect.at(this.x, this.y, rot, block); - return false; - } - - @Override - public void read(Reads read, byte revision) { - super.read(read, revision); - rot = read.f(); - shieldDamage = read.f(); - warmup = read.f(); - broken = read.bool(); - } - - @Override - public void updateTile() { - updatePressure(); - if (efficiency > 0) { - if (shieldDamage >= 0) { - shieldDamage -= edelta() * (broken ? rechargeBroken : rechargeStandard); - } else { - broken = false; - } - - if (broken) { - warmup = Mathf.approachDelta(warmup, 0f, warmupTime); - } else { - warmup = Mathf.approachDelta(warmup, efficiency * efficiencyMultiplier(), warmupTime); - - float radius = shieldRange * warmup + shieldBuffer; - - Groups.bullet.intersect( - x - radius, - y - radius, - radius * 2f, - radius * 2f, - b -> { - if (b.team == Team.derelict) { - float distance = Mathf.dst(x, y, b.x, b.y); - float angle = Math.abs(((b.angleTo(x, y) - rot) % 360f + 360f) % 360f - 180f); - boolean inWarmupRadius = distance <= warmup * (hitSize() * 1.4f); - - if ((distance <= shieldRange * warmup + b.type.splashDamageRadius && angle <= shieldAngle / 2f) || inWarmupRadius) { - b.absorb(); - hitEffect.at(b.x, b.y, b.hitSize); - hitSound.at(b.x, b.y, Mathf.random(0.9f, 1.1f), hitSoundVolume); - shieldDamage += b.damage; - if (shieldDamage >= shieldHealth) broken = true; - } - } - } - ); - } - } else { - warmup = Mathf.approachDelta(warmup, 0f, warmupTime); - } - } - - @Override public byte version() { - return 1; - } - - @Override - public void write(Writes write) { - super.write(write); - pressure.write(write); - write.f(rot); - write.f(shieldDamage); - write.f(warmup); - write.bool(broken); - } - } + public PressureConfig pressureConfig = new PressureConfig(); + + public float configSerrations = 20; + public float shieldAngle = 120f; + public float shieldHealth = 120f; + public float shieldRange = 80f; + public float rechargeStandard = 0.1f; + public float rechargeBroken = 1f; + public float warmupTime = 0.1f; + public boolean useConsumerMultiplier = true; + public float rotateSpeed = 1; + + public float glowMinAlpha = 0f, glowMaxAlpha = 0.5f, glowBlinkSpeed = 0.16f; + + public Color deflectColor = Pal.heal; + + public Effect hitEffect = Fx.absorb; + public Sound hitSound = Sounds.none; + public float hitSoundVolume = 1f; + + public Effect rotateEffect = OlFx.shelterRotate; + + private static final FrameBuffer fieldBuffer = new FrameBuffer(); + public static final Seq runs = new Seq<>(); + + { + Events.run(EventType.Trigger.draw, () -> { + fieldBuffer.resize(Core.graphics.getWidth(), Core.graphics.getHeight()); + Seq buffer = runs.copy(); + runs.clear(); + + Draw.draw(Layer.shields, () -> { + Draw.flush(); + fieldBuffer.begin(Color.clear); + buffer.each(Runnable::run); + fieldBuffer.end(); + Draw.color(deflectColor, Vars.renderer.animateShields ? 1f : Core.settings.getFloat("omaloon-shield-opacity", 20f) / 100f); + EDraw.drawBuffer(fieldBuffer); + Draw.flush(); + Draw.color(); + }); + }); + } + + public Shelter(String name){ + super(name); + update = true; + solid = true; + configurable = true; + saveConfig = true; + group = BlockGroup.projectors; + ambientSound = Sounds.shield; + ambientSoundVolume = 0.08f; + pressureConfig.isWhitelist = true; + config(Float.class, (build, rot) -> ((ShelterBuild)build).rot = rot); + configClear((ShelterBuild build) -> build.rot = 90); + } + + @Override + public TextureRegion[] icons(){ + return new TextureRegion[]{baseRegion, region}; + } + + @Override + public void init(){ + super.init(); + clipSize = shieldRange * 2f; + } + + @Override + public void setStats(){ + super.setStats(); + pressureConfig.addStats(stats); + + stats.add(Stat.shieldHealth, shieldHealth, StatUnit.none); + stats.add(Stat.cooldownTime, (int)(rechargeStandard * 60f), StatUnit.perSecond); + } + + @Override + public void setBars(){ + super.setBars(); + pressureConfig.addBars(this); + addBar("shield", (ShelterBuild entity) -> new Bar("stat.shieldhealth", Pal.accent, () -> entity.broken ? 0f : 1 - entity.shieldDamage / shieldHealth).blink(Color.white)); + } + + @Override + public void drawOverlay(float x, float y, int rotation){ + Drawf.dashCircle(x, y, shieldRange, Pal.accent); + } + + @Override + public void drawPlanRegion(BuildPlan plan, Eachable list){ + Draw.rect(baseRegion, plan.drawx(), plan.drawy()); + float rot = plan.config instanceof Float ? (float)plan.config : 0; + Draw.rect(region, plan.drawx(), plan.drawy(), rot - 90); + } + + public class ShelterBuild extends Building implements HasPressureImpl{ + + + public float rot = 90; + public float shieldDamage = 0; + public float warmup = 0; + public boolean broken = false; + + public float configureWarmup = 0; + + @Override + public Float config(){ + return rot; + } + + @Override + public void draw(){ + configureWarmup = Mathf.approachDelta(configureWarmup, 0, 0.014f); + Draw.rect(baseRegion, x, y, 0); + Draw.rect(region, x, y, rot - 90); + + float z = Draw.z(); + Draw.z(Layer.blockAdditive); + Draw.blend(Blending.additive); + Draw.color(Color.valueOf("cbffc2")); + + float cycleAlpha = glowMinAlpha + (glowMaxAlpha - glowMinAlpha) * (0.5f + 0.5f * Mathf.sin(Time.time * glowBlinkSpeed)); + Draw.alpha(warmup * cycleAlpha); + Draw.rect(glowRegion, x, y, rot - 90); + Draw.reset(); + Draw.blend(); + Draw.z(z); + + runs.add(() -> { + Draw.color(); + Fill.circle(x, y, warmup * (hitSize() * 1.2f)); + Fill.arc(x, y, shieldRange * warmup, shieldAngle / 360f, -shieldAngle / 2f + rot); + Draw.color(); + }); + + Draw.z(Layer.blockOver); + float mousex = Core.input.mouseWorldX(), mousey = Core.input.mouseWorldY(); + + Draw.color(Pal.accent, Interp.circle.apply(configureWarmup) * Core.settings.getFloat("omaloon-shield-opacity", 20f) / 100f); + Fill.arc(x, y, shieldRange * Interp.circle.apply(configureWarmup), shieldAngle / 360f, -shieldAngle / 2f + Core.input.mouseWorld().angleTo(x, y) + 180f); + + for(int i = 0; i < configSerrations; i++){ + Tmp.v1.trns(360f / configSerrations * i, size * 8f).nor(); + float dot = Mathf.maxZero(Tmp.v1.dot(Tmp.v2.set(mousex - x, mousey - y).nor())); + Tmp.v1.trns(360f / configSerrations * i, size * 8f); + Lines.stroke(2 * Interp.circle.apply(configureWarmup), Pal.accent); + Lines.lineAngle( + Tmp.v1.x + x, Tmp.v1.y + y, + Tmp.v1.angle(), + (0.5f + 3f * Interp.circleIn.apply(dot)) * Interp.circle.apply(configureWarmup) + ); + } + } + + @Override + public void drawConfigure(){ + configureWarmup = Mathf.approachDelta(configureWarmup, 1, 0.028f); + } + + @Override + public float edelta(){ + return super.edelta() * efficiencyMultiplier(); + } + + public float efficiencyMultiplier(){ + float val = 1; + if(!useConsumerMultiplier) return val; + for(Consume consumer : consumers){ + val *= consumer.efficiencyMultiplier(this); + } + return val; + } + + @Override + public boolean onConfigureTapped(float x, float y){ + configure(Tmp.v1.set(this.x, this.y).angleTo(x, y)); + rotateEffect.at(this.x, this.y, rot, block); + return false; + } + + @Override + public void read(Reads read, byte revision){ + super.read(read, revision); + rot = read.f(); + shieldDamage = read.f(); + warmup = read.f(); + broken = read.bool(); + } + + @Override + public void updateTile(){ + updatePressure(); + if(efficiency > 0){ + if(shieldDamage >= 0){ + shieldDamage -= edelta() * (broken ? rechargeBroken : rechargeStandard); + }else{ + broken = false; + } + + if(broken){ + warmup = Mathf.approachDelta(warmup, 0f, warmupTime); + }else{ + warmup = Mathf.approachDelta(warmup, efficiency * efficiencyMultiplier(), warmupTime); + + float radius = shieldRange * warmup + shieldBuffer; + + Groups.bullet.intersect( + x - radius, + y - radius, + radius * 2f, + radius * 2f, + b -> { + if(b.team == Team.derelict){ + float distance = Mathf.dst(x, y, b.x, b.y); + float angle = Math.abs(((b.angleTo(x, y) - rot) % 360f + 360f) % 360f - 180f); + boolean inWarmupRadius = distance <= warmup * (hitSize() * 1.4f); + + if((distance <= shieldRange * warmup + b.type.splashDamageRadius && angle <= shieldAngle / 2f) || inWarmupRadius){ + b.absorb(); + hitEffect.at(b.x, b.y, b.hitSize); + hitSound.at(b.x, b.y, Mathf.random(0.9f, 1.1f), hitSoundVolume); + shieldDamage += b.damage; + if(shieldDamage >= shieldHealth) broken = true; + } + } + } + ); + } + }else{ + warmup = Mathf.approachDelta(warmup, 0f, warmupTime); + } + } + + @Override + public byte version(){ + return 1; + } + + @Override + public void write(Writes write){ + super.write(write); + pressure.write(write); + write.f(rot); + write.f(shieldDamage); + write.f(warmup); + write.bool(broken); + } + } } diff --git a/src/omaloon/world/blocks/distribution/TubeConveyor.java b/src/omaloon/world/blocks/distribution/TubeConveyor.java index 855e5813..7a7d4a4f 100644 --- a/src/omaloon/world/blocks/distribution/TubeConveyor.java +++ b/src/omaloon/world/blocks/distribution/TubeConveyor.java @@ -18,20 +18,20 @@ import omaloon.content.blocks.*; import omaloon.utils.*; -import static arc.Core.*; +import static arc.Core.atlas; import static mindustry.Vars.*; -import static omaloon.utils.OlUtils.*; +import static omaloon.utils.OlUtils.reverse; public class TubeConveyor extends Conveyor{ private static final float itemSpace = 0.4f; private static final int capacity = 3; public static final int[][] tiles = new int[][]{ - {}, - {0, 2}, {1, 3}, {0, 1}, - {0, 2}, {0, 2}, {1, 2}, - {0, 1, 2}, {1, 3}, {0, 3}, - {1, 3}, {0, 1, 3}, {2, 3}, - {0, 2, 3}, {1, 2, 3}, {0, 1, 2, 3} + {}, + {0, 2}, {1, 3}, {0, 1}, + {0, 2}, {0, 2}, {1, 2}, + {0, 1, 2}, {1, 3}, {0, 3}, + {1, 3}, {0, 1, 3}, {2, 3}, + {0, 2, 3}, {1, 2, 3}, {0, 1, 2, 3} }; public TextureRegion[][] topRegion; @@ -49,17 +49,17 @@ public void init(){ if(bridgeReplacement == null) bridgeReplacement = OlDistributionBlocks.tubeBridge; } - public boolean validBlock(Block otherblock) { - return ((otherblock instanceof TubeConveyor) || (otherblock instanceof TubeDistributor) || - (otherblock instanceof TubeSorter) || (otherblock instanceof TubeJunction) || - (otherblock instanceof TubeGate) || otherblock instanceof TubeItemBridge || - (otherblock instanceof CoreBlock) || (otherblock instanceof ItemSource) || (otherblock instanceof ItemVoid)); - } + public boolean validBlock(Block otherblock){ + return ((otherblock instanceof TubeConveyor) || (otherblock instanceof TubeDistributor) || + (otherblock instanceof TubeSorter) || (otherblock instanceof TubeJunction) || + (otherblock instanceof TubeGate) || otherblock instanceof TubeItemBridge || + (otherblock instanceof CoreBlock) || (otherblock instanceof ItemSource) || (otherblock instanceof ItemVoid)); + } @Override public boolean blends(Tile tile, int rotation, int otherx, int othery, int otherrot, Block otherblock){ return (otherblock instanceof TubeDistributor) || (otherblock.outputsItems() || (lookingAt(tile, rotation, otherx, othery, otherblock) && otherblock.hasItems)) - && lookingAtEither(tile, rotation, otherx, othery, otherrot, otherblock) && validBlock(otherblock); + && lookingAtEither(tile, rotation, otherx, othery, otherrot, otherblock) && validBlock(otherblock); } @Override @@ -71,17 +71,17 @@ public void handlePlacementLine(Seq plans){ @Override public Block getReplacement(BuildPlan req, Seq plans){ - if (junctionReplacement == null) return this; + if(junctionReplacement == null) return this; Boolf cont = p -> plans.contains(o -> o.x == req.x + p.x && o.y == req.y + p.y - && (req.block instanceof TubeConveyor || req.block instanceof Junction)); + && (req.block instanceof TubeConveyor || req.block instanceof Junction)); return cont.get(Geometry.d4(req.rotation)) - && cont.get(Geometry.d4(req.rotation - 2)) - && req.tile() != null - && req.tile().block() instanceof TubeConveyor - && Mathf.mod(req.tile().build.rotation - req.rotation, 2) == 1 - ? junctionReplacement - : this; + && cont.get(Geometry.d4(req.rotation - 2)) + && req.tile() != null + && req.tile().block() instanceof TubeConveyor + && Mathf.mod(req.tile().build.rotation - req.rotation, 2) == 1 + ? junctionReplacement + : this; } @Override @@ -94,14 +94,14 @@ public void drawPlanRegion(BuildPlan req, Eachable list){ int i = 0; for(Point2 point : Geometry.d4){ int x = req.x + point.x, y = req.y + point.y; - if(x >= other.x -(other.block.size - 1) / 2 && x <= other.x + (other.block.size / 2) && y >= other.y -(other.block.size - 1) / 2 && y <= other.y + (other.block.size / 2)){ - if ((other.block instanceof Conveyor ? - (req.rotation == i || (other.rotation + 2) % 4 == i) : - ( - (req.rotation == i && other.block.acceptsItems) || - (req.rotation != i && other.block.outputsItems()) - )) && validBlock(other.block) - ) { + if(x >= other.x - (other.block.size - 1) / 2 && x <= other.x + (other.block.size / 2) && y >= other.y - (other.block.size - 1) / 2 && y <= other.y + (other.block.size / 2)){ + if((other.block instanceof Conveyor ? + (req.rotation == i || (other.rotation + 2) % 4 == i) : + ( + (req.rotation == i && other.block.acceptsItems) || + (req.rotation != i && other.block.outputsItems()) + )) && validBlock(other.block) + ){ directionals[i] = other; } } @@ -110,8 +110,8 @@ public void drawPlanRegion(BuildPlan req, Eachable list){ }); int mask = 0; - for(int i = 0; i < directionals.length; i++) { - if (directionals[i] != null) { + for(int i = 0; i < directionals.length; i++){ + if(directionals[i] != null){ mask += (1 << i); } } @@ -119,14 +119,14 @@ public void drawPlanRegion(BuildPlan req, Eachable list){ Draw.rect(topRegion[0][mask], req.drawx(), req.drawy(), 0); for(int i : tiles[mask]){ if( - directionals[i] == null || - (directionals[i].block instanceof Conveyor ? - (directionals[i].rotation + 2) % 4 == req.rotation : - ( - (req.rotation == i && !directionals[i].block.acceptsItems) || - (req.rotation != i && !directionals[i].block.outputsItems()) - ) - ) + directionals[i] == null || + (directionals[i].block instanceof Conveyor ? + (directionals[i].rotation + 2) % 4 == req.rotation : + ( + (req.rotation == i && !directionals[i].block.acceptsItems) || + (req.rotation != i && !directionals[i].block.outputsItems()) + ) + ) ){ int id = i == 0 || i == 3 ? 1 : 0; Draw.rect(capRegion[id], req.drawx(), req.drawy(), i == 0 || i == 2 ? 0 : -90); @@ -138,7 +138,7 @@ public void drawPlanRegion(BuildPlan req, Eachable list){ public void load(){ super.load(); topRegion = OlUtils.splitLayers(name + "-sheet", 32, 2); - capRegion = new TextureRegion[] { topRegion[1][0], topRegion[1][1] }; + capRegion = new TextureRegion[]{topRegion[1][0], topRegion[1][1]}; uiIcon = atlas.find(name + "-icon"); } @@ -171,7 +171,7 @@ public void updateTile(){ if(isEnd(reverse(rotation)) && blendbits == 0){ float nextMaxReverse = aligned ? (items.total() > 2 ? (0.5f - Math.max(itemSpace - nextc.minitem, 0)) - : Math.max(itemSpace - nextc.minitem, 0)) : 0f; + : Math.max(itemSpace - nextc.minitem, 0)) : 0f; float movedReverse = speed * edelta(); @@ -218,8 +218,8 @@ public void updateTile(){ } if(minitem < itemSpace + (blendbits == 1 ? 0.3f : 0f) - || isEnd(reverse(rotation)) && items.total() >= 2 - || isEnd(reverse(rotation)) && isEnd(rotation) && items.total() >= 1){ + || isEnd(reverse(rotation)) && items.total() >= 2 + || isEnd(reverse(rotation)) && isEnd(rotation) && items.total() >= 1){ clogHeat = Mathf.approachDelta(clogHeat, 1f, 1f / 60f); }else{ clogHeat = 0f; @@ -228,7 +228,7 @@ public void updateTile(){ noSleep(); } - public void updateProximity() { + public void updateProximity(){ super.updateProximity(); calls++; } @@ -240,21 +240,21 @@ public Building buildAt(int i){ public boolean valid(int i){ Building b = buildAt(i); return b != null && (b instanceof TubeConveyorBuild ? (b.front() != null && b.front() == this) - : b.block.acceptsItems) && ((b.block instanceof TubeConveyor) || (b.block instanceof TubeDistributor) || - (b.block instanceof TubeSorter) || (b.block instanceof TubeJunction) || - (b.block instanceof TubeGate) || b.block instanceof TubeItemBridge || - (b.block instanceof CoreBlock) || (b.block instanceof ItemSource) || (b.block instanceof ItemVoid)); + : b.block.acceptsItems) && ((b.block instanceof TubeConveyor) || (b.block instanceof TubeDistributor) || + (b.block instanceof TubeSorter) || (b.block instanceof TubeJunction) || + (b.block instanceof TubeGate) || b.block instanceof TubeItemBridge || + (b.block instanceof CoreBlock) || (b.block instanceof ItemSource) || (b.block instanceof ItemVoid)); } public boolean isEnd(int i){ var b = buildAt(i); return (!valid(i) && (b == null ? null : b.block) != this.block) || - (b instanceof ConveyorBuild && ((b.rotation + 2) % 4 == rotation || (b.front() != this && back() == b))); + (b instanceof ConveyorBuild && ((b.rotation + 2) % 4 == rotation || (b.front() != this && back() == b))); } @Override public void draw(){ - int frame = enabled && clogHeat <= 0.5f ? (int) (((Time.time * speed * 8f * timeScale * efficiency)) % 4) : 0; + int frame = enabled && clogHeat <= 0.5f ? (int)(((Time.time * speed * 8f * timeScale * efficiency)) % 4) : 0; //draw extra conveyors facing this one for non-square tiling purposes Draw.z(Layer.blockUnder); @@ -264,8 +264,8 @@ public void draw(){ float rot = i == 0 ? rotation * 90 : (dir) * 90; Draw.rect(sliced(regions[0][frame], i != 0 ? SliceMode.bottom : SliceMode.top), - x + Geometry.d4x(dir) * tilesize * 0.75f, y + Geometry.d4y(dir) * tilesize * 0.75f, - rot); + x + Geometry.d4x(dir) * tilesize * 0.75f, y + Geometry.d4y(dir) * tilesize * 0.75f, + rot); } } @@ -275,7 +275,7 @@ public void draw(){ Draw.z(Layer.block - 0.2f); float layer = Layer.block - 0.2f, wwidth = world.unitWidth(), wheight = world.unitHeight(), - scaling = 0.01f; + scaling = 0.01f; for(int i = 0; i < len; i++){ Item item = ids[i]; @@ -309,10 +309,10 @@ public void drawCracks(){ @Override public boolean pass(Item item){ if(item != null && next != null && next.team == team && next.acceptItem(this, item) && - ((next.block instanceof TubeConveyor) || (next.block instanceof TubeDistributor) || - (next.block instanceof TubeSorter) || (next.block instanceof TubeJunction) || - (next.block instanceof TubeGate) || next.block instanceof TubeItemBridge || - (next.block instanceof CoreBlock) || (next.block instanceof ItemSource) || (next.block instanceof ItemVoid))){ + ((next.block instanceof TubeConveyor) || (next.block instanceof TubeDistributor) || + (next.block instanceof TubeSorter) || (next.block instanceof TubeJunction) || + (next.block instanceof TubeGate) || next.block instanceof TubeItemBridge || + (next.block instanceof CoreBlock) || (next.block instanceof ItemSource) || (next.block instanceof ItemVoid))){ next.handleItem(this, item); return true; } @@ -326,10 +326,10 @@ public boolean acceptItem(Building source, Item item){ if(facing == null) return false; int direction = Math.abs(facing.relativeTo(tile.x, tile.y) - rotation); return (((direction == 0) && minitem >= itemSpace) || ((direction % 2 == 1) && minitem > 0.7f)) && !(source.block.rotate && next == source) && - ((source.block instanceof TubeConveyor) || (source.block instanceof TubeDistributor) || - (source.block instanceof TubeSorter) || (source.block instanceof TubeJunction) || - (source.block instanceof TubeGate) || source.block instanceof TubeItemBridge || - (source.block instanceof CoreBlock) || (source.block instanceof ItemSource) || (source.block instanceof ItemVoid)); + ((source.block instanceof TubeConveyor) || (source.block instanceof TubeDistributor) || + (source.block instanceof TubeSorter) || (source.block instanceof TubeJunction) || + (source.block instanceof TubeGate) || source.block instanceof TubeItemBridge || + (source.block instanceof CoreBlock) || (source.block instanceof ItemSource) || (source.block instanceof ItemVoid)); } @Override @@ -353,14 +353,14 @@ public void onProximityUpdate(){ tiling = 0; for(int i = 0; i < 4; i++){ Building otherblock = nearby(i); - if (otherblock == null) continue; - if ((otherblock.block instanceof Conveyor ? - (rotation == i || (otherblock.rotation + 2) % 4 == i) : - ( - (rotation == i && otherblock.block.acceptsItems) || - (rotation != i && otherblock.block.outputsItems()) - )) && validBlock(otherblock.block) - ) { + if(otherblock == null) continue; + if((otherblock.block instanceof Conveyor ? + (rotation == i || (otherblock.rotation + 2) % 4 == i) : + ( + (rotation == i && otherblock.block.acceptsItems) || + (rotation != i && otherblock.block.outputsItems()) + )) && validBlock(otherblock.block) + ){ tiling |= (1 << i); } } diff --git a/src/omaloon/world/blocks/distribution/TubeDistributor.java b/src/omaloon/world/blocks/distribution/TubeDistributor.java index c5ba488d..4167f964 100644 --- a/src/omaloon/world/blocks/distribution/TubeDistributor.java +++ b/src/omaloon/world/blocks/distribution/TubeDistributor.java @@ -11,13 +11,13 @@ import mindustry.world.*; import mindustry.world.blocks.distribution.*; import mindustry.world.draw.*; -import omaloon.annotations.Load; +import omaloon.annotations.*; -import static arc.Core.*; -import static mindustry.Vars.*; -import static omaloon.utils.OlUtils.*; +import static arc.Core.atlas; +import static mindustry.Vars.itemSize; +import static omaloon.utils.OlUtils.reverse; -public class TubeDistributor extends Router { +public class TubeDistributor extends Router{ public DrawBlock drawer = new DrawDefault(); @Load("@-rotator") public TextureRegion rotorRegion; @@ -28,13 +28,13 @@ public class TubeDistributor extends Router { @Load("@-bottom") public TextureRegion bottomRegion; - public TubeDistributor(String name) { + public TubeDistributor(String name){ super(name); rotate = true; } @Override - public void load() { + public void load(){ super.load(); drawer.load(this); uiIcon = atlas.find(name + "-icon"); @@ -54,7 +54,7 @@ public TextureRegion[] icons(){ return new TextureRegion[]{atlas.find(name + "-icon")}; } - public class TubeDistributorBuild extends RouterBuild { + public class TubeDistributorBuild extends RouterBuild{ public Item lastItem; public Tile lastInput; public int lastTargetAngle, lastSourceAngle; @@ -70,14 +70,14 @@ public void updateTile(){ if(lastItem != null){ Building target = getTileTarget(lastItem, lastInput, false); - if(blockValidInDirection(targetAngle())) { - if (target != null || time < 1f) { + if(blockValidInDirection(targetAngle())){ + if(target != null || time < 1f){ time += 1f / speed * delta(); - if (time > 1f) time = 1f; + if(time > 1f) time = 1f; } }else if(time < 0.4f){ time += 0.4f / speed * delta(); - if (time > 0.4f) time = 0.4f; + if(time > 0.4f) time = 0.4f; } if(target != null && time >= 1f){ @@ -93,27 +93,27 @@ public void updateTile(){ angle = computeAngle(sa, ta); } - if (items.total() > 0 && !Vars.state.isPaused() && (!(time >= 1f) && (blockValidInDirection(targetAngle()))) - || (!blockValidInDirection(targetAngle()) && !(time >= 0.4f))) { + if(items.total() > 0 && !Vars.state.isPaused() && (!(time >= 1f) && (blockValidInDirection(targetAngle()))) + || (!blockValidInDirection(targetAngle()) && !(time >= 0.4f))){ lastRot = rot; rot += speed * angle * delta(); } } } - private float computeAngle(int sa, int ta) { + private float computeAngle(int sa, int ta){ return (sa == 0) ? ((ta == 2) ? 1 : ((ta == 0 || ta == 3) ? -1 : 1)) : - (sa == 2) ? ((ta == 0 || ta == 1) ? -1 : 1) : - (sa == 1) ? ((ta == 0 || ta == 3) ? -1 : 1) : - ((ta == 0 || ta == 1) ? 1 : -1); + (sa == 2) ? ((ta == 0 || ta == 1) ? -1 : 1) : + (sa == 1) ? ((ta == 0 || ta == 3) ? -1 : 1) : + ((ta == 0 || ta == 1) ? 1 : -1); } - public boolean blockValidInDirection(int direction) { + public boolean blockValidInDirection(int direction){ Tile targetTile = tile.nearby(direction); return targetTile != null && (targetTile.block().hasItems - || targetTile.block() instanceof Junction - || targetTile.block() instanceof TubeSorter - || targetTile.block() instanceof OverflowGate + || targetTile.block() instanceof Junction + || targetTile.block() instanceof TubeSorter + || targetTile.block() instanceof OverflowGate ); } @@ -140,9 +140,9 @@ public int removeStack(Item item, int amount){ return result; } - public int sourceAngle() { - for(int sourceAngle = 0; sourceAngle < 4; sourceAngle++) { - if(nearby(sourceAngle) == lastInput.build) { + public int sourceAngle(){ + for(int sourceAngle = 0; sourceAngle < 4; sourceAngle++){ + if(nearby(sourceAngle) == lastInput.build){ lastSourceAngle = sourceAngle; return sourceAngle; } @@ -150,12 +150,12 @@ public int sourceAngle() { return lastSourceAngle; } - public int targetAngle() { - if (lastItem == null) return lastTargetAngle; + public int targetAngle(){ + if(lastItem == null) return lastTargetAngle; Building target = getTileTarget(lastItem, lastInput, false); - if(target != null) { - for (int targetAngle = 0; targetAngle < 4; targetAngle++) { - if (nearby(targetAngle) == target) { + if(target != null){ + for(int targetAngle = 0; targetAngle < 4; targetAngle++){ + if(nearby(targetAngle) == target){ lastTargetAngle = targetAngle; return targetAngle; } @@ -164,38 +164,38 @@ public int targetAngle() { return lastTargetAngle; } - public void drawItem() { - if (lastInput != null && lastInput.build != null && lastItem != null) { + public void drawItem(){ + if(lastInput != null && lastInput.build != null && lastItem != null){ boolean isf = reverse(sourceAngle()) == targetAngle() || sourceAngle() == targetAngle(); boolean alignment = targetAngle() == 0 || targetAngle() == 2; float ox, oy, s = size * 4, s2 = s * 2; - float linearMove = (float) Math.sin(Math.PI * time) / 2.4f * s; + float linearMove = (float)Math.sin(Math.PI * time) / 2.4f * s; - if (alignment) { - if (isf) { + if(alignment){ + if(isf){ if(sourceAngle() == targetAngle()){ oy = time >= 0.5f ? linearMove : -linearMove; ox = time >= 0.5f ? (time * s2 - s) * (targetAngle() == 0 ? 1 : -1) - : (time * s2 - s) * (targetAngle() == 0 ? -1 : 1); - } else { + : (time * s2 - s) * (targetAngle() == 0 ? -1 : 1); + }else{ oy = linearMove; ox = (time * s2 - s) * (targetAngle() == 0 ? 1 : -1); } - } else { + }else{ oy = sourceAngle() == 1 ? (time * -s + s) : (time * s - s); ox = time * s * (targetAngle() == 0 ? 1 : -1); } - } else { - if (isf) { + }else{ + if(isf){ if(sourceAngle() == targetAngle()){ ox = time >= 0.5f ? linearMove : -linearMove; oy = time >= 0.5f ? (time * s2 - s) * (targetAngle() == 1 ? 1 : -1) - : (time * s2 - s) * (targetAngle() == 1 ? -1 : 1); - } else { - ox = (float) Math.sin(Math.PI * time) / 2.4f * s; + : (time * s2 - s) * (targetAngle() == 1 ? -1 : 1); + }else{ + ox = (float)Math.sin(Math.PI * time) / 2.4f * s; oy = (time * s2 - s) * (targetAngle() == 1 ? 1 : -1); } - } else { + }else{ ox = sourceAngle() == 0 ? (time * -s + s) : (time * s - s); oy = time * s * (targetAngle() == 1 ? 1 : -1); } @@ -206,7 +206,7 @@ public void drawItem() { } @Override - public void draw() { + public void draw(){ drawer.draw(this); Draw.z(Layer.block - 0.2f); drawItem(); diff --git a/src/omaloon/world/blocks/distribution/TubeGate.java b/src/omaloon/world/blocks/distribution/TubeGate.java index 2e0d8467..c7ef9d62 100644 --- a/src/omaloon/world/blocks/distribution/TubeGate.java +++ b/src/omaloon/world/blocks/distribution/TubeGate.java @@ -12,95 +12,98 @@ import mindustry.gen.*; import mindustry.type.*; import mindustry.world.blocks.distribution.*; -import omaloon.annotations.Load; - -import static mindustry.Vars.*; - -public class TubeGate extends OverflowGate { - @Load("@-top-underflow") - public TextureRegion topUnder; - public Effect switchEffect = Fx.doorclose; - public Sound switchSound = Sounds.door; - - public TubeGate(String name) { - super(name); - saveConfig = copyConfig = true; - config(Boolean.class, (TubeGateBuild build, Boolean invert) -> build.invert = invert); - } - - @Override - public void drawPlanConfig(BuildPlan plan, Eachable list) { - if(plan.config instanceof Boolean boll && boll) Draw.rect(topUnder, plan.drawx(), plan.drawy(), 0); - } - - public class TubeGateBuild extends OverflowGateBuild { - boolean invert = false; - - @Override public void tapped() { - switchEffect.at(this, size); - switchSound.at(this); - configure(!invert); - } - - @Override public Graphics.Cursor getCursor(){ - return interactable(player.team()) ? Graphics.Cursor.SystemCursor.hand : Graphics.Cursor.SystemCursor.arrow; - } - - @Override - public void draw() { - super.draw(); - if(invert) { - Draw.rect(topUnder, x, y, 0); - } - } - - @Override - public Object config() { - return invert; - } - - @Override - public @Nullable Building getTileTarget(Item item, Building src, boolean flip){ - int from = relativeToEdge(src.tile); - if(from == -1) return null; - Building to = nearby((from + 2) % 4); - boolean - fromInst = src.block.instantTransfer, - canForward = to != null && to.team == team && !(fromInst && to.block.instantTransfer) && to.acceptItem(this, item), - inv = invert == enabled; - - if(!canForward || inv){ - Building a = nearby(Mathf.mod(from - 1, 4)); - Building b = nearby(Mathf.mod(from + 1, 4)); - boolean ac = a != null && !(fromInst && a.block.instantTransfer) && a.team == team && a.acceptItem(this, item); - boolean bc = b != null && !(fromInst && b.block.instantTransfer) && b.team == team && b.acceptItem(this, item); - - if(!ac && !bc){ - return inv && canForward ? to : null; - } - - if(ac && !bc){ - to = a; - }else if(bc && !ac){ - to = b; - }else{ - to = (rotation & (1 << from)) == 0 ? a : b; - if(flip) rotation ^= (1 << from); - } - } - - return to; - } - - @Override - public void read(Reads read, byte revision) { - super.read(read, revision); - invert = read.bool(); - } - @Override - public void write(Writes write) { - super.write(write); - write.bool(invert); - } - } +import omaloon.annotations.*; + +import static mindustry.Vars.player; + +public class TubeGate extends OverflowGate{ + @Load("@-top-underflow") + public TextureRegion topUnder; + public Effect switchEffect = Fx.doorclose; + public Sound switchSound = Sounds.door; + + public TubeGate(String name){ + super(name); + saveConfig = copyConfig = true; + config(Boolean.class, (TubeGateBuild build, Boolean invert) -> build.invert = invert); + } + + @Override + public void drawPlanConfig(BuildPlan plan, Eachable list){ + if(plan.config instanceof Boolean boll && boll) Draw.rect(topUnder, plan.drawx(), plan.drawy(), 0); + } + + public class TubeGateBuild extends OverflowGateBuild{ + boolean invert = false; + + @Override + public void tapped(){ + switchEffect.at(this, size); + switchSound.at(this); + configure(!invert); + } + + @Override + public Graphics.Cursor getCursor(){ + return interactable(player.team()) ? Graphics.Cursor.SystemCursor.hand : Graphics.Cursor.SystemCursor.arrow; + } + + @Override + public void draw(){ + super.draw(); + if(invert){ + Draw.rect(topUnder, x, y, 0); + } + } + + @Override + public Object config(){ + return invert; + } + + @Override + public @Nullable Building getTileTarget(Item item, Building src, boolean flip){ + int from = relativeToEdge(src.tile); + if(from == -1) return null; + Building to = nearby((from + 2) % 4); + boolean + fromInst = src.block.instantTransfer, + canForward = to != null && to.team == team && !(fromInst && to.block.instantTransfer) && to.acceptItem(this, item), + inv = invert == enabled; + + if(!canForward || inv){ + Building a = nearby(Mathf.mod(from - 1, 4)); + Building b = nearby(Mathf.mod(from + 1, 4)); + boolean ac = a != null && !(fromInst && a.block.instantTransfer) && a.team == team && a.acceptItem(this, item); + boolean bc = b != null && !(fromInst && b.block.instantTransfer) && b.team == team && b.acceptItem(this, item); + + if(!ac && !bc){ + return inv && canForward ? to : null; + } + + if(ac && !bc){ + to = a; + }else if(bc && !ac){ + to = b; + }else{ + to = (rotation & (1 << from)) == 0 ? a : b; + if(flip) rotation ^= (1 << from); + } + } + + return to; + } + + @Override + public void read(Reads read, byte revision){ + super.read(read, revision); + invert = read.bool(); + } + + @Override + public void write(Writes write){ + super.write(write); + write.bool(invert); + } + } } diff --git a/src/omaloon/world/blocks/distribution/TubeItemBridge.java b/src/omaloon/world/blocks/distribution/TubeItemBridge.java index 2aa03435..8f9ffd5d 100644 --- a/src/omaloon/world/blocks/distribution/TubeItemBridge.java +++ b/src/omaloon/world/blocks/distribution/TubeItemBridge.java @@ -24,7 +24,7 @@ import static arc.util.Tmp.*; import static mindustry.Vars.*; -public class TubeItemBridge extends ItemBridge { +public class TubeItemBridge extends ItemBridge{ public Prov> connectBlocksGetter = Seq::new; Seq connectibleBlocks = new Seq<>(); public Boolf connectFilter = (building) -> connectibleBlocks.contains(building.block()); @@ -47,7 +47,7 @@ public TubeItemBridge(String name){ } public TubeItemBridgeBuild cast(Building b){ - return (TubeItemBridgeBuild) b; + return (TubeItemBridgeBuild)b; } @Override @@ -71,28 +71,28 @@ public void setStats(){ public void setBars(){ super.setBars(); addBar("connections", entity -> new Bar(() -> - Core.bundle.format("bar.powerlines", cast(entity).realConnections(), maxConnections - 1), - () -> Pal.items, - () -> (float) cast(entity).realConnections() / (float)(maxConnections - 1) + Core.bundle.format("bar.powerlines", cast(entity).realConnections(), maxConnections - 1), + () -> Pal.items, + () -> (float)cast(entity).realConnections() / (float)(maxConnections - 1) )); } @Override - public void drawBridge(BuildPlan req, float ox, float oy, float flip) { + public void drawBridge(BuildPlan req, float ox, float oy, float flip){ drawBridge(bridgeRegion, endRegion, new Vec2(req.drawx(), req.drawy()), new Vec2(ox, oy)); Draw.rect(arrowRegion, - (req.drawx() + ox) / 2f, - (req.drawy() + oy) / 2f, - Angles.angle(req.drawx(), req.drawy(), ox, oy) + (req.drawx() + ox) / 2f, + (req.drawy() + oy) / 2f, + Angles.angle(req.drawx(), req.drawy(), ox, oy) ); } - public void drawBridge(TextureRegion bridgeRegion, TextureRegion endRegion, Vec2 pos1, Vec2 pos2) { + public void drawBridge(TextureRegion bridgeRegion, TextureRegion endRegion, Vec2 pos1, Vec2 pos2){ float angle = pos1.angleTo(pos2) - 90; if(angle >= 0f && angle < 180f) Draw.yscl = -1f; - Tmp.v1.set(pos2.x, pos2.y).sub(pos1.x, pos1.y).setLength(tilesize/2f); + Tmp.v1.set(pos2.x, pos2.y).sub(pos1.x, pos1.y).setLength(tilesize / 2f); Lines.stroke(8 * Draw.yscl); Lines.line(bridgeRegion, pos1.x + Tmp.v1.x, pos1.y + Tmp.v1.y, pos2.x - Tmp.v1.x, pos2.y - Tmp.v1.y, false); @@ -111,7 +111,7 @@ public Tile findLinkTile(int x, int y, boolean checkBlock){ Tile tile = world.tile(x, y); if(tile != null && lastBuild != null && lastBuild.tile != tile){ boolean validLink = checkBlock ? linkValid(tile, lastBuild.tile) && lastBuild.link == -1 : - linkValid(tile, lastBuild.tile, false, true); + linkValid(tile, lastBuild.tile, false, true); if(validLink) return lastBuild.tile; } return null; @@ -132,10 +132,10 @@ public void drawPlace(int x, int y, int rotation, boolean valid){ Draw.z(Layer.blockUnder - 0.3f); Lines.poly(new Vec2[]{ - start.cpy().add(Tmp.v1.trns(angle, -0.4f)), - end.cpy().add(Tmp.v1.trns(angle, -0.4f)), - end.cpy().add(Tmp.v1.trns(angle, 0.4f)), - start.cpy().add(Tmp.v1.trns(angle, 0.4f)), + start.cpy().add(Tmp.v1.trns(angle, -0.4f)), + end.cpy().add(Tmp.v1.trns(angle, -0.4f)), + end.cpy().add(Tmp.v1.trns(angle, 0.4f)), + start.cpy().add(Tmp.v1.trns(angle, 0.4f)), }, 0, 0, 8); Tmp.v1.set(start).sub(end).setLength(4); @@ -165,12 +165,13 @@ public boolean linkValid(Tile tile, Tile other, boolean checkDouble){ public boolean linkValid(Tile tile, Tile other, boolean checkDouble, boolean old){ if(old){ if(other != null && tile != null && this.positionsValid(tile.x, tile.y, other.x, other.y)){ - return (other.block() == tile.block() && tile.block() == this || !(tile.block() instanceof ItemBridge) && other.block() == this) && (other.team() == tile.team() || tile.block() != this) && (!checkDouble || ((ItemBridgeBuild) other.build).link != tile.pos()); + return (other.block() == tile.block() && tile.block() == this || !(tile.block() instanceof ItemBridge) && other.block() == this) && (other.team() == tile.team() || tile.block() != this) && (!checkDouble || ((ItemBridgeBuild)other.build).link != tile.pos()); }else{ return false; } }else{ - check:{ + check: + { if(!(other != null && tile != null) || other.build == null || tile.build == null) break check; other = other.build.tile; tile = tile.build.tile; @@ -179,27 +180,27 @@ public boolean linkValid(Tile tile, Tile other, boolean checkDouble, boolean old if(tile.block() == this){ Vec2 offVec = v1.trns(tile.angleTo(other) + 90f, offset, offset); if(!positionsValid(tile.x, tile.y, Mathf.ceil(other.x + offVec.x), Mathf.ceil(other.y + offVec.y))) break check; - TubeItemBridge block = (TubeItemBridge) tile.block(); + TubeItemBridge block = (TubeItemBridge)tile.block(); boolean connected = false; if(other.build instanceof ItemBridgeBuild){ connected = other.build.as().link == tile.pos(); } return ((block.connectFilter.get(other.build)) || !(tile.block() instanceof ItemBridge) && other.block() == this) && - b2 && - (other.team() == tile.team() || other.block() != this) && + b2 && + (other.team() == tile.team() || other.block() != this) && - (!checkDouble || !connected); + (!checkDouble || !connected); }else{ if(!positionsValid(tile.x, tile.y, other.x, other.y)) break check; boolean b3 = other.team() == tile.team() || tile.block() != this; if(other.block() == this){ other.block(); - boolean b4 = !checkDouble || !(other.build instanceof ItemBridgeBuild && ((ItemBridgeBuild) other.build).link == tile.pos()); + boolean b4 = !checkDouble || !(other.build instanceof ItemBridgeBuild && ((ItemBridgeBuild)other.build).link == tile.pos()); return b2 && b3 && b4; }else{ return (other.block() == tile.block() && tile.block() == this || !(tile.block() instanceof ItemBridge) && other.block() == this) - && b3 && - (!checkDouble || ((ItemBridgeBuild) other.build).link != tile.pos()); + && b3 && + (!checkDouble || ((ItemBridgeBuild)other.build).link != tile.pos()); } } } @@ -240,7 +241,7 @@ public void checkIncoming(){ Tile other; for(int i : incoming.toArray()){ other = Vars.world.tile(i); - boolean valid = linkValid(this.tile, other, false) && (other.build instanceof ItemBridgeBuild && ((ItemBridgeBuild) other.build).link == this.tile.pos()); + boolean valid = linkValid(this.tile, other, false) && (other.build instanceof ItemBridgeBuild && ((ItemBridgeBuild)other.build).link == this.tile.pos()); if(!valid){ incoming.removeValue(i); } @@ -261,13 +262,13 @@ public boolean canReLink(){ @Override public boolean onConfigureBuildTapped(Building other){ - if(other instanceof ItemBridgeBuild && ((ItemBridgeBuild) other).link == this.pos()){ + if(other instanceof ItemBridgeBuild && ((ItemBridgeBuild)other).link == this.pos()){ incoming.removeValue(other.pos()); other.as().incoming.add(this.pos()); this.configure(other.pos()); other.configure(-1); }else if(linkValid(this.tile, other.tile) - && other instanceof TubeItemBridgeBuild bridge){ + && other instanceof TubeItemBridgeBuild bridge){ if(this.link == other.pos()){ other.as().incoming.removeValue(this.pos()); @@ -313,7 +314,7 @@ public void updateTile(){ } } - IntSeq inc = ((ItemBridgeBuild) other.build).incoming; + IntSeq inc = ((ItemBridgeBuild)other.build).incoming; int pos = tile.pos(); if(!inc.contains(pos)){ inc.add(pos); @@ -325,17 +326,17 @@ public void updateTile(){ } @Override - public void updateTransport(Building other) { + public void updateTransport(Building other){ if(cachedLink != link || other == null || link == -1){ cachedLinkValid = linkValid(tile, other.tile()); cachedLink = link; } - if(!cachedLinkValid) { + if(!cachedLinkValid){ doDump(); warmup = 0f; }else{ - if(buffer.accepts() && items.total() > 0) { + if(buffer.accepts() && items.total() > 0){ buffer.accept(items.take()); } @@ -371,10 +372,10 @@ public void draw(){ drawBridge(bridgeRegion, endRegion, pos1, pos2); Draw.color(); - int arrows = Mathf.round(pos1.dst(pos2)/arrowSpacing); + int arrows = Mathf.round(pos1.dst(pos2) / arrowSpacing); float angle = pos1.angleTo(pos2); v2.trns(angle - 45f, 1f, 1f); - for(float a = 0; a < arrows - 2; ++a) { + for(float a = 0; a < arrows - 2; ++a){ Draw.alpha(Mathf.absin(a - time / arrowTimeScl, arrowPeriod, 1f) * warmup * Renderer.bridgeOpacity); float arrowX, arrowY; arrowX = x - v1.x + v2.x * (tilesize / 2.5f + a * arrowSpacing + arrowOffset); @@ -404,7 +405,7 @@ protected void drawInput(Tile other){ float ty = tile.drawy(); float ox = other.drawx(); float oy = other.drawy(); - float alpha = Math.abs((float) (linked ? 100 : 0) - Time.time * 2.0F % 100.0F) / 100.0F; + float alpha = Math.abs((float)(linked ? 100 : 0) - Time.time * 2.0F % 100.0F) / 100.0F; float x = Mathf.lerp(ox, tx, alpha); float y = Mathf.lerp(oy, ty, alpha); Tile otherLink = linked ? other : tile; @@ -426,7 +427,7 @@ protected void drawInput(Tile other){ } public void drawConfigure(){ - Drawf.select(this.x, this.y, (float) (this.tile.block().size * 8) / 2.0F + 2.0F, Pal.accent); + Drawf.select(this.x, this.y, (float)(this.tile.block().size * 8) / 2.0F + 2.0F, Pal.accent); Drawf.dashCircle(x, y, (range) * 8f, Pal.accent); Draw.color(); if(!canReLink() && !canLinked() && realConnections() >= maxConnections - 1) return; @@ -434,7 +435,7 @@ public void drawConfigure(){ for(int x = -range; x <= range; ++x){ for(int y = -range; y <= range; ++y){ Tile other = this.tile.nearby(x, y); - if (linkValid(this.tile, other) && !(tile == other)) { + if(linkValid(this.tile, other) && !(tile == other)){ if(!orderedMap.containsKey(other.build)) orderedMap.put(other.build, false); } } @@ -449,16 +450,16 @@ public void drawConfigure(){ } if(orderedMap.containsKey(this)) orderedMap.remove(this); orderedMap.each((other, linked) -> - Drawf.select(other.x, other.y, (float) (other.block().size * 8) / 2.0F + 2.0F + (linked ? 0.0F : Mathf.absin(Time.time, 4.0F, 1.0F)), linked ? Pal.place : Pal.breakInvalid) + Drawf.select(other.x, other.y, (float)(other.block().size * 8) / 2.0F + 2.0F + (linked ? 0.0F : Mathf.absin(Time.time, 4.0F, 1.0F)), linked ? Pal.place : Pal.breakInvalid) ); } - public void write(Writes write) { + public void write(Writes write){ super.write(write); buffer.write(write); } - public void read(Reads read, byte revision) { + public void read(Reads read, byte revision){ super.read(read, revision); buffer.read(read); } diff --git a/src/omaloon/world/blocks/distribution/TubeJunction.java b/src/omaloon/world/blocks/distribution/TubeJunction.java index a63598f8..65dfa5dd 100644 --- a/src/omaloon/world/blocks/distribution/TubeJunction.java +++ b/src/omaloon/world/blocks/distribution/TubeJunction.java @@ -1,18 +1,16 @@ package omaloon.world.blocks.distribution; import arc.graphics.g2d.*; -import arc.math.Mathf; -import arc.math.geom.Geometry; +import arc.math.*; +import arc.math.geom.*; import arc.util.*; import mindustry.entities.units.*; -import mindustry.gen.Building; +import mindustry.gen.*; import mindustry.world.blocks.distribution.*; import mindustry.world.draw.*; -import omaloon.annotations.Load; +import omaloon.annotations.*; -import static arc.Core.*; - -public class TubeJunction extends Junction { +public class TubeJunction extends Junction{ public DrawBlock drawer = new DrawDefault(); @Load("@-side1") public TextureRegion side1; @@ -22,7 +20,7 @@ public class TubeJunction extends Junction { protected TextureAtlas.AtlasRegion bottomRegion; protected int tempBlend = 0; - public TubeJunction(String name) { + public TubeJunction(String name){ super(name); } @@ -57,7 +55,7 @@ public void drawPlanRegion(BuildPlan plan, Eachable list){ Draw.rect(region, x, y); //code duplication, awful - for(int i = 0; i < 4; i ++){ + for(int i = 0; i < 4; i++){ if((blending & (1 << i)) == 0){ Draw.rect(i >= 2 ? side2 : side1, x, y, i * 90); @@ -76,20 +74,20 @@ public void drawPlanRegion(BuildPlan plan, Eachable list){ public class TubeJunctionBuild extends JunctionBuild{ - public Building buildAt(int i) { + public Building buildAt(int i){ return nearby(i); } - public boolean valid(int i) { + public boolean valid(int i){ Building b = buildAt(i); return b != null && b.block.acceptsItems; } @Override - public void draw() { + public void draw(){ super.draw(); drawer.draw(this); - for(int i = 0; i < 4; i++) { + for(int i = 0; i < 4; i++){ if(!valid(i)){ Draw.rect(i >= 2 ? side2 : side1, x, y, i * 90); } diff --git a/src/omaloon/world/blocks/distribution/TubeSorter.java b/src/omaloon/world/blocks/distribution/TubeSorter.java index 8b1077fd..87116c10 100644 --- a/src/omaloon/world/blocks/distribution/TubeSorter.java +++ b/src/omaloon/world/blocks/distribution/TubeSorter.java @@ -16,8 +16,8 @@ import static mindustry.Vars.*; -public class TubeSorter extends Block { - public TubeSorter(String name) { +public class TubeSorter extends Block{ + public TubeSorter(String name){ super(name); update = false; destructible = true; @@ -33,36 +33,36 @@ public TubeSorter(String name) { } @Override - public void drawPlanConfig(BuildPlan plan, Eachable list) { + public void drawPlanConfig(BuildPlan plan, Eachable list){ drawPlanConfigCenter(plan, plan.config, name + "-center", false); } @Override - public boolean outputsItems() { + public boolean outputsItems(){ return true; } - public class TubeSorterBuild extends Building { + public class TubeSorterBuild extends Building{ public final MultiItemData data = new MultiItemData(); @Override - public void configured(Unit player, Object value) { + public void configured(Unit player, Object value){ super.configured(player, value); - if (!headless) { + if(!headless){ renderer.minimap.update(tile); } } @Override - public void draw() { + public void draw(){ super.draw(); - if (data.length() > 0) { + if(data.length() > 0){ // Use getByIndex safely for the item, checking the index within bounds - int itemIndex = (int) Time.time / 40 + id; + int itemIndex = (int)Time.time / 40 + id; Item item = OlUtils.getByIndexAsItem(data, itemIndex % data.length()); - if (item != null) { + if(item != null){ Draw.color(item.color); Draw.rect(Core.atlas.find(name + "-center"), x, y); Draw.color(); @@ -71,48 +71,48 @@ public void draw() { } @Override - public boolean acceptItem(Building source, Item item) { + public boolean acceptItem(Building source, Item item){ Building to = getTileTarget(item, source, false); return to != null && to.acceptItem(this, item) && to.team == team; } @Override - public void handleItem(Building source, Item item) { + public void handleItem(Building source, Item item){ getTileTarget(item, source, true).handleItem(this, item); } - public boolean isSame(Building other) { + public boolean isSame(Building other){ return other != null && other.block.instantTransfer; } - public Building getTileTarget(Item item, Building source, boolean flip) { + public Building getTileTarget(Item item, Building source, boolean flip){ int dir = source.relativeTo(tile.x, tile.y); - if (dir == -1) return null; + if(dir == -1) return null; Building to; - if ((item != null && data.isToggled(item) && enabled)) { + if((item != null && data.isToggled(item) && enabled)){ // Prevent 3-chains - if (isSame(source) && isSame(nearby(dir))) { + if(isSame(source) && isSame(nearby(dir))){ return null; } to = nearby(dir); - } else { + }else{ Building a = nearby(Mathf.mod(dir - 1, 4)); Building b = nearby(Mathf.mod(dir + 1, 4)); boolean ac = a != null && !(a.block.instantTransfer && source.block.instantTransfer) && - a.acceptItem(this, item); + a.acceptItem(this, item); boolean bc = b != null && !(b.block.instantTransfer && source.block.instantTransfer) && - b.acceptItem(this, item); + b.acceptItem(this, item); - if (ac && !bc) { + if(ac && !bc){ to = a; - } else if (bc && !ac) { + }else if(bc && !ac){ to = b; - } else if (!bc) { + }else if(!bc){ return null; - } else { + }else{ to = (rotation & (1 << dir)) == 0 ? a : b; - if (flip) rotation ^= (1 << dir); + if(flip) rotation ^= (1 << dir); } } @@ -120,32 +120,32 @@ public Building getTileTarget(Item item, Building source, boolean flip) { } @Override - public void buildConfiguration(Table table) { + public void buildConfiguration(Table table){ MultiItemSelection.buildTable(table, data); } @Override - public int[] config() { + public int[] config(){ return data.config(); } @Override - public byte version() { + public byte version(){ return 2; } @Override - public void write(Writes write) { + public void write(Writes write){ super.write(write); data.write(write); } @Override - public void read(Reads read, byte revision) { + public void read(Reads read, byte revision){ super.read(read, revision); data.read(read); - if (revision == 1) { + if(revision == 1){ new DirectionalItemBuffer(20).read(read); } } diff --git a/src/omaloon/world/blocks/environment/CliffHelper.java b/src/omaloon/world/blocks/environment/CliffHelper.java index 161e712d..b37340f6 100644 --- a/src/omaloon/world/blocks/environment/CliffHelper.java +++ b/src/omaloon/world/blocks/environment/CliffHelper.java @@ -6,20 +6,20 @@ import mindustry.graphics.*; import mindustry.world.*; -public class CliffHelper extends Block { - public CliffHelper(String name) { - super(name); - breakable = alwaysReplace = false; - solid = true; - cacheLayer = CacheLayer.walls; - fillsTile = false; - hasShadow = false; - } +public class CliffHelper extends Block{ + public CliffHelper(String name){ + super(name); + breakable = alwaysReplace = false; + solid = true; + cacheLayer = CacheLayer.walls; + fillsTile = false; + hasShadow = false; + } - @Override - public void drawBase(Tile tile) { - Draw.color(Color.red); - Fill.square(tile.worldx(), tile.worldy(), 1f, Time.time); - Draw.color(); - } + @Override + public void drawBase(Tile tile){ + Draw.color(Color.red); + Fill.square(tile.worldx(), tile.worldy(), 1f, Time.time); + Draw.color(); + } } diff --git a/src/omaloon/world/blocks/environment/CustomShapeProp.java b/src/omaloon/world/blocks/environment/CustomShapeProp.java index 602f2624..b75a9e04 100644 --- a/src/omaloon/world/blocks/environment/CustomShapeProp.java +++ b/src/omaloon/world/blocks/environment/CustomShapeProp.java @@ -16,7 +16,7 @@ import omaloon.world.*; import omaloon.world.interfaces.*; -import static arc.Core.*; +import static arc.Core.atlas; /** * A breakable prop with custom shape. @@ -24,13 +24,13 @@ * remember, when making the mask it is important to always paint the corner of the sprite with 00000AFF, the other occupied tiles with black and the rest should be transparent. * @see Tiles */ -public class CustomShapeProp extends Prop implements MultiPropI { +public class CustomShapeProp extends Prop implements MultiPropI{ public TextureRegion[] shadows, shapeRegions, underRegions; /** * shape of this multiblock represented as offsets from the center. * make all offsets connected to eachother in atleas one of the 4 cardinal directions. - * @apiNote DO NOT SET MANUALLY + * @apiNote DO NOT SET MANUALLY */ public Seq shapes = new Seq<>(); @@ -72,22 +72,22 @@ public class CustomShapeProp extends Prop implements MultiPropI { */ public float rotateRegionMagnitude = 7.5f; - public CustomShapeProp(String name) { + public CustomShapeProp(String name){ super(name); customShadow = true; alwaysReplace = false; breakEffect = Fx.breakProp; } - public static CustomShape createShape(TextureRegion region) { + public static CustomShape createShape(TextureRegion region){ PixmapRegion pixmap = Core.atlas.getPixmap(region); BitWordList list = new BitWordList(pixmap.width * pixmap.height, BitWordList.WordLength.two); OlUtils.readTexturePixels(pixmap, (color, index) -> { - switch (color) { - case 2815 -> list.set(index, (byte) 3); - case 255 -> list.set(index, (byte) 2); - default -> list.set(index, (byte) 1); + switch(color){ + case 2815 -> list.set(index, (byte)3); + case 255 -> list.set(index, (byte)2); + default -> list.set(index, (byte)1); } }); @@ -95,30 +95,30 @@ public static CustomShape createShape(TextureRegion region) { } @Override - public void drawBase(Tile tile) { + public void drawBase(Tile tile){ MultiPropGroup multiProp = CustomShapePropProcess.instance.multiProps.find(multiPropGroup -> multiPropGroup.center == tile); - if (multiProp != null) { + if(multiProp != null){ Draw.z(layer); - if (drawUnder) Draw.rect(underRegions[multiProp.shape], - tile.worldx() + spriteOffsets[multiProp.shape].x, - tile.worldy() + spriteOffsets[multiProp.shape].y, - rotateRegions ? Mathf.randomSeed(tile.pos() + 1, 0, 4) * 90f : 0f + if(drawUnder) Draw.rect(underRegions[multiProp.shape], + tile.worldx() + spriteOffsets[multiProp.shape].x, + tile.worldy() + spriteOffsets[multiProp.shape].y, + rotateRegions ? Mathf.randomSeed(tile.pos() + 1, 0, 4) * 90f : 0f ); Draw.rect(variantRegions[multiProp.shape], - tile.worldx() + spriteOffsets[multiProp.shape].x, - tile.worldy() + spriteOffsets[multiProp.shape].y, - rotateRegions ? Mathf.randomSeed(tile.pos(), -rotateRegionMagnitude, rotateRegionMagnitude) : 0f + tile.worldx() + spriteOffsets[multiProp.shape].x, + tile.worldy() + spriteOffsets[multiProp.shape].y, + rotateRegions ? Mathf.randomSeed(tile.pos(), -rotateRegionMagnitude, rotateRegionMagnitude) : 0f ); } } @Override - public void drawShadow(Tile tile) { + public void drawShadow(Tile tile){ MultiPropGroup multiProp = CustomShapePropProcess.instance.multiProps.find(multiPropGroup -> multiPropGroup.center == tile); - if (multiProp != null) { + if(multiProp != null){ Draw.rect(shadows[multiProp.shape], - tile.worldx() + spriteOffsets[multiProp.shape].x, - tile.worldy() + spriteOffsets[multiProp.shape].y + tile.worldx() + spriteOffsets[multiProp.shape].x, + tile.worldy() + spriteOffsets[multiProp.shape].y ); } } @@ -129,7 +129,7 @@ public void load(){ shadows = new TextureRegion[variants]; shapeRegions = new TextureRegion[variants]; underRegions = new TextureRegion[variants]; - for (int i = 0; i < variants; i++) { + for(int i = 0; i < variants; i++){ shadows[i] = atlas.find(name + (i + 1) + "-shadow"); shapeRegions[i] = atlas.find(name + "-shape" + (i + 1), "omaloon-shape-err"); underRegions[i] = atlas.find(name + (i + 1) + "-under"); @@ -138,16 +138,16 @@ public void load(){ } @Override - public Runnable removed(MultiPropGroup from) { + public Runnable removed(MultiPropGroup from){ return () -> deconstructEffect.at( - from.center.worldx() + spriteOffsets[from.shape].x, - from.center.worldy() + spriteOffsets[from.shape].y, - 0, mapColor, from + from.center.worldx() + spriteOffsets[from.shape].x, + from.center.worldy() + spriteOffsets[from.shape].y, + 0, mapColor, from ); } @Override - public Seq shapes() { + public Seq shapes(){ return shapes; } } diff --git a/src/omaloon/world/blocks/environment/CustomShapePropProcess.java b/src/omaloon/world/blocks/environment/CustomShapePropProcess.java index f6ac426d..41208d39 100644 --- a/src/omaloon/world/blocks/environment/CustomShapePropProcess.java +++ b/src/omaloon/world/blocks/environment/CustomShapePropProcess.java @@ -8,7 +8,7 @@ import omaloon.world.*; import omaloon.world.interfaces.*; -public class CustomShapePropProcess implements AsyncProcess { +public class CustomShapePropProcess implements AsyncProcess{ public static CustomShapePropProcess instance; //TODO interfaces public Seq multiPropTiles = new Seq<>(); @@ -20,27 +20,27 @@ public void init(){ multiProps.clear(); for(Tile tile : Vars.world.tiles){ Block block = tile.block(); - if(block instanceof MultiPropI&& !multiPropTiles.contains(tile)){ + if(block instanceof MultiPropI && !multiPropTiles.contains(tile)){ MultiPropGroup multiProp = createMultiProp(tile); multiProps.add(multiProp); multiPropTiles.add(multiProp.group); multiProp.findCenter(); - multiProp.findShape(); + multiProp.findShape(); } } } - public MultiPropGroup createMultiProp(Tile from) { + public MultiPropGroup createMultiProp(Tile from){ Seq temp = Seq.with(from); MultiPropGroup out = new MultiPropGroup(from.block()); out.group.add(from); - while (!temp.isEmpty()) { + while(!temp.isEmpty()){ Tile tile = temp.pop(); - for (Point2 point : Geometry.d4) { + for(Point2 point : Geometry.d4){ Tile nearby = tile.nearby(point); - if (nearby == null) continue; - if (nearby.block() instanceof MultiPropI && !out.group.contains(nearby) && nearby.block() == out.type) { + if(nearby == null) continue; + if(nearby.block() instanceof MultiPropI && !out.group.contains(nearby) && nearby.block() == out.type){ out.group.add(nearby); temp.add(nearby); } @@ -54,14 +54,14 @@ public MultiPropGroup createMultiProp(Tile from) { public void process(){ multiProps.each(multiProp -> { multiProp.update(); - if (multiProp.removed) multiProps.remove(multiProp); + if(multiProp.removed) multiProps.remove(multiProp); }); } public void onRemoveBlock(Tile tile, Block block){ multiProps.each(multiPropGroup -> { - if (multiPropGroup.group.contains(tile)) { + if(multiPropGroup.group.contains(tile)){ multiPropGroup.remove(); } }); diff --git a/src/omaloon/world/blocks/environment/OlCliff.java b/src/omaloon/world/blocks/environment/OlCliff.java index 42071ba8..5e6b87ca 100644 --- a/src/omaloon/world/blocks/environment/OlCliff.java +++ b/src/omaloon/world/blocks/environment/OlCliff.java @@ -11,82 +11,83 @@ import mindustry.world.*; import omaloon.content.blocks.*; -public class OlCliff extends Block { - public float colorMultiplier = 1.5f; - public boolean useMapColor = true; - public TextureRegion[] cliffs; +public class OlCliff extends Block{ + public float colorMultiplier = 1.5f; + public boolean useMapColor = true; + public TextureRegion[] cliffs; - public OlCliff(String name){ - super(name); - breakable = alwaysReplace = false; - solid = true; - saveData = true; - cacheLayer = CacheLayer.walls; - fillsTile = false; - hasShadow = false; - } + public OlCliff(String name){ + super(name); + breakable = alwaysReplace = false; + solid = true; + saveData = true; + cacheLayer = CacheLayer.walls; + fillsTile = false; + hasShadow = false; + } - public static void processCliffs() { - Vars.world.tiles.eachTile(tile -> { - if (tile.block() instanceof OlCliff && tile.data == 0) { - for(int i = 0; i < 4; i++) { - if (tile.nearby(i).block() instanceof CliffHelper) tile.data = (byte) (i + 1); - } - if (tile.data == 0) for(int i = 0; i < 4; i++) { - if (tile.nearby(Geometry.d8edge(i)).block() instanceof CliffHelper) tile.data = (byte) (i + 5); - } - for(int i = 0; i < 4; i++) { - if ( - tile.nearby(i).block() instanceof CliffHelper && - tile.nearby((i + 1)% 4).block() instanceof CliffHelper - ) tile.data = (byte) (i + 9); - } - if (tile.data == 0) tile.setBlock(Blocks.air); - } - }); - Vars.world.tiles.eachTile(tile -> { - if (tile.block() instanceof CliffHelper) mindustry.gen.Call.setTile(tile, Blocks.air, Team.derelict, 0); - }); - } - public static void unProcessCliffs() { - Vars.world.tiles.eachTile(tile -> { - if (tile.block() instanceof OlCliff && tile.data != 0) { - if (tile.data <= 4) { - tile.nearby(tile.data - 1).setBlock(OlEnvironmentBlocks.cliffHelper); - } else if (tile.data <= 8) { - tile.nearby(Geometry.d8edge(tile.data - 5)).setBlock(OlEnvironmentBlocks.cliffHelper); - } else { - tile.nearby(Geometry.d4(tile.data - 9)).setBlock(OlEnvironmentBlocks.cliffHelper); - tile.nearby(Geometry.d4(tile.data - 8)).setBlock(OlEnvironmentBlocks.cliffHelper); - } - tile.data = 0; - } - }); - } + public static void processCliffs(){ + Vars.world.tiles.eachTile(tile -> { + if(tile.block() instanceof OlCliff && tile.data == 0){ + for(int i = 0; i < 4; i++){ + if(tile.nearby(i).block() instanceof CliffHelper) tile.data = (byte)(i + 1); + } + if(tile.data == 0) for(int i = 0; i < 4; i++){ + if(tile.nearby(Geometry.d8edge(i)).block() instanceof CliffHelper) tile.data = (byte)(i + 5); + } + for(int i = 0; i < 4; i++){ + if( + tile.nearby(i).block() instanceof CliffHelper && + tile.nearby((i + 1) % 4).block() instanceof CliffHelper + ) tile.data = (byte)(i + 9); + } + if(tile.data == 0) tile.setBlock(Blocks.air); + } + }); + Vars.world.tiles.eachTile(tile -> { + if(tile.block() instanceof CliffHelper) mindustry.gen.Call.setTile(tile, Blocks.air, Team.derelict, 0); + }); + } - @Override - public void drawBase(Tile tile) { - if (tile.data == 0) { - Draw.color(); - Draw.rect(region, tile.drawx(), tile.drawy()); - } else { - if (useMapColor) Draw.color(Tmp.c1.set(tile.floor().mapColor).mul(colorMultiplier)); - Draw.rect(cliffs[tile.data - 1], tile.drawx(), tile.drawy()); - } - Draw.color(); - } + public static void unProcessCliffs(){ + Vars.world.tiles.eachTile(tile -> { + if(tile.block() instanceof OlCliff && tile.data != 0){ + if(tile.data <= 4){ + tile.nearby(tile.data - 1).setBlock(OlEnvironmentBlocks.cliffHelper); + }else if(tile.data <= 8){ + tile.nearby(Geometry.d8edge(tile.data - 5)).setBlock(OlEnvironmentBlocks.cliffHelper); + }else{ + tile.nearby(Geometry.d4(tile.data - 9)).setBlock(OlEnvironmentBlocks.cliffHelper); + tile.nearby(Geometry.d4(tile.data - 8)).setBlock(OlEnvironmentBlocks.cliffHelper); + } + tile.data = 0; + } + }); + } - @Override - public void load() { - super.load(); - cliffs = new TextureRegion[12]; - for(int i = 0; i < 12; i++) { - cliffs[i] = Core.atlas.find(name + "-" + (i + 1), "omaloon-cliff-" + (i + 1)); - } - } + @Override + public void drawBase(Tile tile){ + if(tile.data == 0){ + Draw.color(); + Draw.rect(region, tile.drawx(), tile.drawy()); + }else{ + if(useMapColor) Draw.color(Tmp.c1.set(tile.floor().mapColor).mul(colorMultiplier)); + Draw.rect(cliffs[tile.data - 1], tile.drawx(), tile.drawy()); + } + Draw.color(); + } - @Override - public int minimapColor(Tile tile){ - return Tmp.c1.set(tile.floor().mapColor).mul(1.2f).rgba(); - } + @Override + public void load(){ + super.load(); + cliffs = new TextureRegion[12]; + for(int i = 0; i < 12; i++){ + cliffs[i] = Core.atlas.find(name + "-" + (i + 1), "omaloon-cliff-" + (i + 1)); + } + } + + @Override + public int minimapColor(Tile tile){ + return Tmp.c1.set(tile.floor().mapColor).mul(1.2f).rgba(); + } } \ No newline at end of file diff --git a/src/omaloon/world/blocks/environment/RotatedProp.java b/src/omaloon/world/blocks/environment/RotatedProp.java index fe200920..b5cd43c5 100644 --- a/src/omaloon/world/blocks/environment/RotatedProp.java +++ b/src/omaloon/world/blocks/environment/RotatedProp.java @@ -8,8 +8,8 @@ import mindustry.world.*; import mindustry.world.blocks.environment.*; -public class RotatedProp extends Prop { - public RotatedProp(String name) { +public class RotatedProp extends Prop{ + public RotatedProp(String name){ super(name); breakable = true; alwaysReplace = true; @@ -17,8 +17,9 @@ public RotatedProp(String name) { breakEffect = Fx.breakProp; breakSound = Sounds.rockBreak; } + @Override - public void drawBase(Tile tile) { + public void drawBase(Tile tile){ float rot = Mathf.randomSeed(tile.pos(), 0, 360); Draw.z(Layer.blockProp); @@ -30,7 +31,7 @@ public void drawBase(Tile tile) { } @Override - public TextureRegion[] icons() { + public TextureRegion[] icons(){ return new TextureRegion[]{region}; } } diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidBridge.java b/src/omaloon/world/blocks/liquid/PressureLiquidBridge.java index a8cc281f..9b3c2293 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidBridge.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidBridge.java @@ -18,277 +18,276 @@ import mindustry.world.blocks.liquid.*; import mindustry.world.blocks.sandbox.*; import mindustry.world.meta.*; -import omaloon.annotations.AutoImplement; -import omaloon.annotations.Load; +import omaloon.annotations.*; import omaloon.world.blocks.distribution.*; import omaloon.world.interfaces.*; import omaloon.world.meta.*; import omaloon.world.modules.*; -import static arc.Core.*; +import static arc.Core.atlas; import static arc.graphics.g2d.Draw.*; -import static arc.util.Tmp.*; +import static arc.util.Tmp.v2; import static mindustry.Vars.*; -public class PressureLiquidBridge extends TubeItemBridge { - public PressureConfig pressureConfig = new PressureConfig(); +public class PressureLiquidBridge extends TubeItemBridge{ + public PressureConfig pressureConfig = new PressureConfig(); - public float liquidPadding = 1f; + public float liquidPadding = 1f; - @Load("omaloon-liquid-bottom") - public TextureRegion bottomRegion; - @Load("@-end1") + @Load("omaloon-liquid-bottom") + public TextureRegion bottomRegion; + @Load("@-end1") public TextureRegion endRegion1; - @Load("@-end-bottom") + @Load("@-end-bottom") public TextureRegion endBottomRegion; - @Load("@-end-liquid") + @Load("@-end-liquid") public TextureRegion endLiquidRegion; - @Load("@-bridge-bottom") + @Load("@-bridge-bottom") public TextureRegion bridgeBottomRegion; - @Load("@-bridge-liquid") + @Load("@-bridge-liquid") public TextureRegion bridgeLiquidRegion; - public PressureLiquidBridge(String name) { - super(name); - hasItems = false; - outputsLiquid = true; - canOverdrive = false; - group = BlockGroup.liquids; - } - - @Override - public void drawBridge(BuildPlan req, float ox, float oy, float flip) { - drawBridge(bridgeBottomRegion, endBottomRegion, new Vec2(req.drawx(), req.drawy()), new Vec2(ox, oy)); - drawBridge(new Vec2(req.drawx(), req.drawy()), new Vec2(ox, oy)); - } - - public void drawBridge(Vec2 pos1, Vec2 pos2){ - boolean line = pos1.x == pos2.x || pos1.y == pos2.y; - - int segments = length(pos1.x, pos1.y, pos2.x, pos2.y) + 1; - float sl = 0; - if(!line){ - sl = Mathf.dst(pos1.x, pos1.y, pos2.x, pos2.y) / segments; - } - float sa = pos1.angleTo(pos2); - float oa = pos2.angleTo(pos1); - - if(line){ - if(pos1.y == pos2.y){ - Position a = pos1.x < pos2.x ? pos2 : pos1; - Position b = pos1.x < pos2.x ? pos1 : pos2; - - segments = (int)(a.getX() / 8 - b.getX() / 8); - } - - if(pos1.x == pos2.x){ - Position a = pos1.y < pos2.y ? pos2 : pos1; - Position b = pos1.y < pos2.y ? pos1 : pos2; - - segments = (int)(a.getY() / 8 - b.getY() / 8); - } - } - - boolean reverse = pos1.x > pos2.x; - - if(line){ - reverse |= pos1.y < pos2.y; - } - - float r = sa + (reverse ? 180 : 0); - - TextureRegion end = reverse ? endRegion1 : endRegion; - TextureRegion str = reverse ? endRegion : endRegion1; - - Draw.rect(end, pos1.x, pos1.y, sa); - Draw.rect(str, pos2.x, pos2.y, oa); - - for(int i = 1; i < segments; i++){ - float s_x = Mathf.lerp(pos1.x, pos2.x, (float)i / segments); - float s_y = Mathf.lerp(pos1.y, pos2.y, (float)i / segments); - - if(line){ - Draw.rect(bridgeRegion, s_x, s_y, r); - }else{ - Draw.rect(bridgeRegion, s_x, s_y, sl, bridgeRegion.height * scl * xscl, r); - } - } - } - - public int length(float x1, float y1, float x2, float y2){ - return (int)(Mathf.dst(x1, y1, x2, y2) / tilesize); - } - - @Override - public void drawPlanRegion(BuildPlan plan, Eachable list){ - Draw.rect(bottomRegion, plan.drawx(), plan.drawy()); - super.drawPlanRegion(plan, list); - } - - @Override - public TextureRegion[] icons(){ - return new TextureRegion[]{atlas.find(name + "-icon")}; - } - - @Override - public void init() { - super.init(); - - if (pressureConfig.fluidGroup == null) pressureConfig.fluidGroup = FluidGroup.transportation; - } - - @Override - public void load() { - super.load(); - bottomRegion = Core.atlas.find("omaloon-liquid-bottom"); - endRegion1 = Core.atlas.find(name + "-end1"); - endBottomRegion = Core.atlas.find(name + "-end-bottom"); - endLiquidRegion = Core.atlas.find(name + "-end-liquid"); - bridgeBottomRegion = Core.atlas.find(name + "-bridge-bottom"); - bridgeLiquidRegion = Core.atlas.find(name + "-bridge-liquid"); - } - - @Override - public void setBars() { - super.setBars(); - pressureConfig.addBars(this); - } - - @Override - public void setStats() { - super.setStats(); - pressureConfig.addStats(stats); - } - - public class PressureLiquidBridgeBuild extends TubeItemBridgeBuild implements HasPressureImpl { - - - public float smoothAlpha; - - @Override - public boolean acceptsPressurizedFluid(HasPressure from, @Nullable Liquid liquid, float amount) { - return HasPressureImpl.super.acceptsPressurizedFluid(from, liquid, amount) && (liquid == pressure.getMain() || liquid == null || pressure.getMain() == null || from.pressure().getMain() == null); - } - - @Override - public boolean canDumpLiquid(Building to, Liquid liquid) { - return super.canDumpLiquid(to, liquid) || to instanceof LiquidVoid.LiquidVoidBuild; - } - - @Override - public void draw() { - Draw.rect(bottomRegion, x, y); - - Liquid main = pressure.getMain(); - - smoothAlpha = Mathf.approachDelta(smoothAlpha, main == null ? 0f : pressure.liquids[main.id]/(pressure.liquids[main.id] + pressure.air), PressureModule.smoothingSpeed); - - if(smoothAlpha > 0.001f){ - LiquidBlock.drawTiledFrames(size, x, y, liquidPadding, pressure.current, Mathf.clamp(smoothAlpha)); - } - - drawBase(); - - Draw.z(Layer.power); - Tile other = Vars.world.tile(link); - Building build = Vars.world.build(link); - if(build == this) build = null; - if(build != null) other = build.tile; - if(!linkValid(this.tile, other) || build == null || Mathf.zero(Renderer.bridgeOpacity)) return; - Vec2 pos1 = new Vec2(x, y), pos2 = new Vec2(other.drawx(), other.drawy()); - - if(pulse) Draw.color(Color.white, Color.black, Mathf.absin(Time.time, 6f, 0.07f)); - - Draw.alpha(Renderer.bridgeOpacity); - drawBridge(bridgeBottomRegion, endBottomRegion, pos1, pos2); - - if (smoothAlpha > 0.001f) { - Draw.color(pressure.current.color, Mathf.clamp(smoothAlpha) * Renderer.bridgeOpacity); - drawBridge(bridgeLiquidRegion, endLiquidRegion, pos1, pos2); - Draw.color(); - } - Draw.alpha(Renderer.bridgeOpacity); - drawBridge(pos1, pos2); - - Draw.reset(); - } - - @Override - public Seq nextBuilds() { - Seq o = HasPressureImpl.super.nextBuilds(); - if (Vars.world.build(link) instanceof PressureLiquidBridgeBuild b) o.add(b); - for(int pos : incoming.items) if (Vars.world.build(pos) instanceof PressureLiquidBridgeBuild b) o.add(b); - return o; - } - - @Override - public boolean outputsPressurizedFluid(HasPressure to, Liquid liquid, float amount) { - return HasPressureImpl.super.outputsPressurizedFluid(to, liquid, amount) && (liquid == to.pressure().getMain() || liquid == null || pressure.getMain() == null || to.pressure().getMain() == null); - } - - @Override - public void read(Reads read, byte revision) { - super.read(read, revision); - smoothAlpha = read.f(); - } - - @Override + public PressureLiquidBridge(String name){ + super(name); + hasItems = false; + outputsLiquid = true; + canOverdrive = false; + group = BlockGroup.liquids; + } + + @Override + public void drawBridge(BuildPlan req, float ox, float oy, float flip){ + drawBridge(bridgeBottomRegion, endBottomRegion, new Vec2(req.drawx(), req.drawy()), new Vec2(ox, oy)); + drawBridge(new Vec2(req.drawx(), req.drawy()), new Vec2(ox, oy)); + } + + public void drawBridge(Vec2 pos1, Vec2 pos2){ + boolean line = pos1.x == pos2.x || pos1.y == pos2.y; + + int segments = length(pos1.x, pos1.y, pos2.x, pos2.y) + 1; + float sl = 0; + if(!line){ + sl = Mathf.dst(pos1.x, pos1.y, pos2.x, pos2.y) / segments; + } + float sa = pos1.angleTo(pos2); + float oa = pos2.angleTo(pos1); + + if(line){ + if(pos1.y == pos2.y){ + Position a = pos1.x < pos2.x ? pos2 : pos1; + Position b = pos1.x < pos2.x ? pos1 : pos2; + + segments = (int)(a.getX() / 8 - b.getX() / 8); + } + + if(pos1.x == pos2.x){ + Position a = pos1.y < pos2.y ? pos2 : pos1; + Position b = pos1.y < pos2.y ? pos1 : pos2; + + segments = (int)(a.getY() / 8 - b.getY() / 8); + } + } + + boolean reverse = pos1.x > pos2.x; + + if(line){ + reverse |= pos1.y < pos2.y; + } + + float r = sa + (reverse ? 180 : 0); + + TextureRegion end = reverse ? endRegion1 : endRegion; + TextureRegion str = reverse ? endRegion : endRegion1; + + Draw.rect(end, pos1.x, pos1.y, sa); + Draw.rect(str, pos2.x, pos2.y, oa); + + for(int i = 1; i < segments; i++){ + float s_x = Mathf.lerp(pos1.x, pos2.x, (float)i / segments); + float s_y = Mathf.lerp(pos1.y, pos2.y, (float)i / segments); + + if(line){ + Draw.rect(bridgeRegion, s_x, s_y, r); + }else{ + Draw.rect(bridgeRegion, s_x, s_y, sl, bridgeRegion.height * scl * xscl, r); + } + } + } + + public int length(float x1, float y1, float x2, float y2){ + return (int)(Mathf.dst(x1, y1, x2, y2) / tilesize); + } + + @Override + public void drawPlanRegion(BuildPlan plan, Eachable list){ + Draw.rect(bottomRegion, plan.drawx(), plan.drawy()); + super.drawPlanRegion(plan, list); + } + + @Override + public TextureRegion[] icons(){ + return new TextureRegion[]{atlas.find(name + "-icon")}; + } + + @Override + public void init(){ + super.init(); + + if(pressureConfig.fluidGroup == null) pressureConfig.fluidGroup = FluidGroup.transportation; + } + + @Override + public void load(){ + super.load(); + bottomRegion = Core.atlas.find("omaloon-liquid-bottom"); + endRegion1 = Core.atlas.find(name + "-end1"); + endBottomRegion = Core.atlas.find(name + "-end-bottom"); + endLiquidRegion = Core.atlas.find(name + "-end-liquid"); + bridgeBottomRegion = Core.atlas.find(name + "-bridge-bottom"); + bridgeLiquidRegion = Core.atlas.find(name + "-bridge-liquid"); + } + + @Override + public void setBars(){ + super.setBars(); + pressureConfig.addBars(this); + } + + @Override + public void setStats(){ + super.setStats(); + pressureConfig.addStats(stats); + } + + public class PressureLiquidBridgeBuild extends TubeItemBridgeBuild implements HasPressureImpl{ + + + public float smoothAlpha; + + @Override + public boolean acceptsPressurizedFluid(HasPressure from, @Nullable Liquid liquid, float amount){ + return HasPressureImpl.super.acceptsPressurizedFluid(from, liquid, amount) && (liquid == pressure.getMain() || liquid == null || pressure.getMain() == null || from.pressure().getMain() == null); + } + + @Override + public boolean canDumpLiquid(Building to, Liquid liquid){ + return super.canDumpLiquid(to, liquid) || to instanceof LiquidVoid.LiquidVoidBuild; + } + + @Override + public void draw(){ + Draw.rect(bottomRegion, x, y); + + Liquid main = pressure.getMain(); + + smoothAlpha = Mathf.approachDelta(smoothAlpha, main == null ? 0f : pressure.liquids[main.id] / (pressure.liquids[main.id] + pressure.air), PressureModule.smoothingSpeed); + + if(smoothAlpha > 0.001f){ + LiquidBlock.drawTiledFrames(size, x, y, liquidPadding, pressure.current, Mathf.clamp(smoothAlpha)); + } + + drawBase(); + + Draw.z(Layer.power); + Tile other = Vars.world.tile(link); + Building build = Vars.world.build(link); + if(build == this) build = null; + if(build != null) other = build.tile; + if(!linkValid(this.tile, other) || build == null || Mathf.zero(Renderer.bridgeOpacity)) return; + Vec2 pos1 = new Vec2(x, y), pos2 = new Vec2(other.drawx(), other.drawy()); + + if(pulse) Draw.color(Color.white, Color.black, Mathf.absin(Time.time, 6f, 0.07f)); + + Draw.alpha(Renderer.bridgeOpacity); + drawBridge(bridgeBottomRegion, endBottomRegion, pos1, pos2); + + if(smoothAlpha > 0.001f){ + Draw.color(pressure.current.color, Mathf.clamp(smoothAlpha) * Renderer.bridgeOpacity); + drawBridge(bridgeLiquidRegion, endLiquidRegion, pos1, pos2); + Draw.color(); + } + Draw.alpha(Renderer.bridgeOpacity); + drawBridge(pos1, pos2); + + Draw.reset(); + } + + @Override + public Seq nextBuilds(){ + Seq o = HasPressureImpl.super.nextBuilds(); + if(Vars.world.build(link) instanceof PressureLiquidBridgeBuild b) o.add(b); + for(int pos : incoming.items) if(Vars.world.build(pos) instanceof PressureLiquidBridgeBuild b) o.add(b); + return o; + } + + @Override + public boolean outputsPressurizedFluid(HasPressure to, Liquid liquid, float amount){ + return HasPressureImpl.super.outputsPressurizedFluid(to, liquid, amount) && (liquid == to.pressure().getMain() || liquid == null || pressure.getMain() == null || to.pressure().getMain() == null); + } + + @Override + public void read(Reads read, byte revision){ + super.read(read, revision); + smoothAlpha = read.f(); + } + + @Override @AutoImplement.NoInject(HasPressureImpl.class) - public void updateTile() { - incoming.size = Math.min(incoming.size, maxConnections - (link == -1 ? 0 : 1)); - incoming.shrink(); - - checkIncoming(); - - updatePressure(); - - Tile other = world.tile(link); - if(linkValid(tile, other)) { - if(other.build instanceof TubeItemBridgeBuild && cast(other.build).acceptIncoming(this.tile.pos())){ - configureAny(-1); - return; - } - - IntSeq inc = ((ItemBridgeBuild) other.build).incoming; - int pos = tile.pos(); - if(!inc.contains(pos)){ - inc.add(pos); - } - - warmup = Mathf.approachDelta(warmup, efficiency(), 1f / 30f); - } - } - - @Override - protected void drawInput(Tile other){ - if(linkValid(this.tile, other, false)){ - final float angle = tile.angleTo(other); - v2.trns(angle, 2.0F); - float tx = tile.drawx(); - float ty = tile.drawy(); - float ox = other.drawx(); - float oy = other.drawy(); - Draw.color(Pal.gray); - Lines.stroke(2.5F); - Lines.square(ox, oy, 2.0F, 45.0F); - Lines.square(tx, ty, 2.0F, 45.0F); - Lines.stroke(2.5F); - Lines.line(tx + v2.x, ty + v2.y, ox - v2.x, oy - v2.y); - Draw.color(Pal.place); - Lines.stroke(1.0F); - Lines.line(tx + v2.x, ty + v2.y, ox - v2.x, oy - v2.y); - Lines.square(ox, oy, 2.0F, 45.0F); - Lines.square(tx, ty, 2.0F, 45.0F); - Draw.mixcol(Draw.getColor(), 1.0F); - Draw.color(); - Draw.mixcol(); - } - } - - @Override - public void write(Writes write) { - super.write(write); - write.f(smoothAlpha); - } - } + public void updateTile(){ + incoming.size = Math.min(incoming.size, maxConnections - (link == -1 ? 0 : 1)); + incoming.shrink(); + + checkIncoming(); + + updatePressure(); + + Tile other = world.tile(link); + if(linkValid(tile, other)){ + if(other.build instanceof TubeItemBridgeBuild && cast(other.build).acceptIncoming(this.tile.pos())){ + configureAny(-1); + return; + } + + IntSeq inc = ((ItemBridgeBuild)other.build).incoming; + int pos = tile.pos(); + if(!inc.contains(pos)){ + inc.add(pos); + } + + warmup = Mathf.approachDelta(warmup, efficiency(), 1f / 30f); + } + } + + @Override + protected void drawInput(Tile other){ + if(linkValid(this.tile, other, false)){ + final float angle = tile.angleTo(other); + v2.trns(angle, 2.0F); + float tx = tile.drawx(); + float ty = tile.drawy(); + float ox = other.drawx(); + float oy = other.drawy(); + Draw.color(Pal.gray); + Lines.stroke(2.5F); + Lines.square(ox, oy, 2.0F, 45.0F); + Lines.square(tx, ty, 2.0F, 45.0F); + Lines.stroke(2.5F); + Lines.line(tx + v2.x, ty + v2.y, ox - v2.x, oy - v2.y); + Draw.color(Pal.place); + Lines.stroke(1.0F); + Lines.line(tx + v2.x, ty + v2.y, ox - v2.x, oy - v2.y); + Lines.square(ox, oy, 2.0F, 45.0F); + Lines.square(tx, ty, 2.0F, 45.0F); + Draw.mixcol(Draw.getColor(), 1.0F); + Draw.color(); + Draw.mixcol(); + } + } + + @Override + public void write(Writes write){ + super.write(write); + write.f(smoothAlpha); + } + } } diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidConduit.java b/src/omaloon/world/blocks/liquid/PressureLiquidConduit.java index 35d45748..83d6dfe9 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidConduit.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidConduit.java @@ -22,190 +22,191 @@ import omaloon.world.meta.*; import omaloon.world.modules.*; -import static mindustry.Vars.*; -import static mindustry.type.Liquid.*; - -public class PressureLiquidConduit extends Block { - public PressureConfig pressureConfig = new PressureConfig(); - - public TextureRegion bottomRegion; - public TextureRegion[] topRegions; - public TextureRegion[][] liquidRegions; - - public float liquidPadding = 3f; - - public @Nullable Block junctionReplacement, bridgeReplacement; - - public PressureLiquidConduit(String name) { - super(name); - rotate = true; - destructible = true; - update = true; - } - - @Override - public void init(){ - super.init(); - - if(junctionReplacement == null) junctionReplacement = OlDistributionBlocks.liquidJunction; - if(bridgeReplacement == null || !(bridgeReplacement instanceof ItemBridge)) bridgeReplacement = OlDistributionBlocks.liquidBridge; - - if (pressureConfig.fluidGroup == null) pressureConfig.fluidGroup = FluidGroup.transportation; - } - - @Override - public void drawPlanRegion(BuildPlan plan, Eachable list) { - int tiling = 0; - BuildPlan[] proximity = new BuildPlan[4]; - - list.each(next -> { - for(int i = 0; i < 4; i++) { - Point2 side = new Point2(plan.x, plan.y).add(Geometry.d4[i]); - if(new Point2(next.x, next.y).equals(side) && ( - (next.block instanceof PressureLiquidConduit || next.block instanceof PressureLiquidPump || next.block instanceof PressureLiquidValve) ? - (plan.rotation%2 == i%2 || next.rotation%2 == i%2) : (next.block.outputsLiquid)) - ){ - proximity[i] = next; - break; - } - } - }); - - for(int i = 0; i < 4; i++){ - if (proximity[i] != null) tiling |= (1 << i); - } - - Draw.rect(bottomRegion, plan.drawx(), plan.drawy(), 0); - if(tiling == 0){ - Draw.rect(topRegions[tiling], plan.drawx(), plan.drawy(), (plan.rotation + 1) * 90f % 180 - 90); - }else{ - Draw.rect(topRegions[tiling], plan.drawx(), plan.drawy(), 0); - } - } - - @Override - public void load() { - super.load(); - - topRegions = OlUtils.split(name + "-tiles", 32, 0); - bottomRegion = Core.atlas.find(name + "-bottom", "omaloon-liquid-bottom"); - - liquidRegions = new TextureRegion[2][animationFrames]; - if(renderer != null){ - var frames = renderer.getFluidFrames(); - - for (int fluid = 0; fluid < 2; fluid++) { - for (int frame = 0; frame < animationFrames; frame++) { - TextureRegion base = frames[fluid][frame]; - TextureRegion result = new TextureRegion(); - result.set(base); - - result.setHeight(result.height - liquidPadding); - result.setWidth(result.width - liquidPadding); - result.setX(result.getX() + liquidPadding); - result.setY(result.getY() + liquidPadding); - - liquidRegions[fluid][frame] = result; - } - } - } - } - - @Override - public Block getReplacement(BuildPlan req, Seq plans){ - if(junctionReplacement == null) return this; - - Boolf cont = p -> plans.contains(o -> o.x == req.x + p.x && o.y == req.y + p.y && (req.block instanceof PressureLiquidConduit || req.block instanceof PressureLiquidJunction)); - return cont.get(Geometry.d4(req.rotation)) && - cont.get(Geometry.d4(req.rotation - 2)) && - req.tile() != null && - req.tile().block() instanceof PressureLiquidConduit && - Mathf.mod(req.build().rotation - req.rotation, 2) == 1 ? junctionReplacement : this; - } - - @Override - public void handlePlacementLine(Seq plans){ - if(bridgeReplacement == null) return; - - Placement.calculateBridges(plans, (ItemBridge)bridgeReplacement); - } - - @Override - public void setBars() { - super.setBars(); - pressureConfig.addBars(this); - } - - @Override - public void setStats() { - super.setStats(); - pressureConfig.addStats(stats); - } - - public class PressureLiquidConduitBuild extends Building implements HasPressureImpl { - - public int tiling = 0; - public float smoothAlpha; - - @Override - public boolean acceptsPressurizedFluid(HasPressure from, @Nullable Liquid liquid, float amount) { - return HasPressureImpl.super.acceptsPressurizedFluid(from, liquid, amount) && (liquid == pressure.getMain() || liquid == null || pressure.getMain() == null || from.pressure().getMain() == null); - } - - @Override - public boolean connects(HasPressure to) { - return ( - to instanceof PressureLiquidConduitBuild || to instanceof PressureLiquidValveBuild) ? - (front() == to || back() == to || to.front() == this || to.back() == this) : - to != null && HasPressureImpl.super.connects(to); - } - - @Override - public void draw() { - Draw.rect(bottomRegion, x, y); - Liquid main = pressure.getMain(); - - smoothAlpha = Mathf.approachDelta(smoothAlpha, main == null ? 0f : pressure.liquids[main.id]/(pressure.liquids[main.id] + pressure.air), PressureModule.smoothingSpeed); - - if (smoothAlpha > 0.001f) { - int frame = pressure.current.getAnimationFrame(); - int gas = pressure.current.gas ? 1 : 0; - - float xscl = Draw.xscl, yscl = Draw.yscl; - Draw.scl(1f, 1f); - Drawf.liquid(liquidRegions[gas][frame], x, y, Mathf.clamp(smoothAlpha), pressure.current.color.write(Tmp.c1).a(1f)); - Draw.scl(xscl, yscl); - } - Draw.rect(topRegions[tiling], x, y, tiling != 0 ? 0 : (rotdeg() + 90) % 180 - 90); - } - - @Override - public void onProximityUpdate() { - super.onProximityUpdate(); - - tiling = 0; - for (int i = 0; i < 4; i++) { - HasPressure build = nearby(i) instanceof HasPressure ? (HasPressure) nearby(i) : null; - if ( - build != null && connected(build) - ) tiling |= (1 << i); - } - } - - @Override - public boolean outputsPressurizedFluid(HasPressure to, Liquid liquid, float amount) { - return HasPressureImpl.super.outputsPressurizedFluid(to, liquid, amount) && (liquid == to.pressure().getMain() || liquid == null || pressure.getMain() == null || to.pressure().getMain() == null); - } +import static mindustry.Vars.renderer; +import static mindustry.type.Liquid.animationFrames; + +public class PressureLiquidConduit extends Block{ + public PressureConfig pressureConfig = new PressureConfig(); + + public TextureRegion bottomRegion; + public TextureRegion[] topRegions; + public TextureRegion[][] liquidRegions; + + public float liquidPadding = 3f; + + public @Nullable Block junctionReplacement, bridgeReplacement; + + public PressureLiquidConduit(String name){ + super(name); + rotate = true; + destructible = true; + update = true; + } + + @Override + public void init(){ + super.init(); + + if(junctionReplacement == null) junctionReplacement = OlDistributionBlocks.liquidJunction; + if(bridgeReplacement == null || !(bridgeReplacement instanceof ItemBridge)) bridgeReplacement = OlDistributionBlocks.liquidBridge; + + if(pressureConfig.fluidGroup == null) pressureConfig.fluidGroup = FluidGroup.transportation; + } + + @Override + public void drawPlanRegion(BuildPlan plan, Eachable list){ + int tiling = 0; + BuildPlan[] proximity = new BuildPlan[4]; + + list.each(next -> { + for(int i = 0; i < 4; i++){ + Point2 side = new Point2(plan.x, plan.y).add(Geometry.d4[i]); + if(new Point2(next.x, next.y).equals(side) && ( + (next.block instanceof PressureLiquidConduit || next.block instanceof PressureLiquidPump || next.block instanceof PressureLiquidValve) ? + (plan.rotation % 2 == i % 2 || next.rotation % 2 == i % 2) : (next.block.outputsLiquid)) + ){ + proximity[i] = next; + break; + } + } + }); + + for(int i = 0; i < 4; i++){ + if(proximity[i] != null) tiling |= (1 << i); + } + + Draw.rect(bottomRegion, plan.drawx(), plan.drawy(), 0); + if(tiling == 0){ + Draw.rect(topRegions[tiling], plan.drawx(), plan.drawy(), (plan.rotation + 1) * 90f % 180 - 90); + }else{ + Draw.rect(topRegions[tiling], plan.drawx(), plan.drawy(), 0); + } + } + + @Override + public void load(){ + super.load(); + + topRegions = OlUtils.split(name + "-tiles", 32, 0); + bottomRegion = Core.atlas.find(name + "-bottom", "omaloon-liquid-bottom"); + + liquidRegions = new TextureRegion[2][animationFrames]; + if(renderer != null){ + var frames = renderer.getFluidFrames(); + + for(int fluid = 0; fluid < 2; fluid++){ + for(int frame = 0; frame < animationFrames; frame++){ + TextureRegion base = frames[fluid][frame]; + TextureRegion result = new TextureRegion(); + result.set(base); + + result.setHeight(result.height - liquidPadding); + result.setWidth(result.width - liquidPadding); + result.setX(result.getX() + liquidPadding); + result.setY(result.getY() + liquidPadding); + + liquidRegions[fluid][frame] = result; + } + } + } + } + + @Override + public Block getReplacement(BuildPlan req, Seq plans){ + if(junctionReplacement == null) return this; + + Boolf cont = p -> plans.contains(o -> o.x == req.x + p.x && o.y == req.y + p.y && (req.block instanceof PressureLiquidConduit || req.block instanceof PressureLiquidJunction)); + return cont.get(Geometry.d4(req.rotation)) && + cont.get(Geometry.d4(req.rotation - 2)) && + req.tile() != null && + req.tile().block() instanceof PressureLiquidConduit && + Mathf.mod(req.build().rotation - req.rotation, 2) == 1 ? junctionReplacement : this; + } + + @Override + public void handlePlacementLine(Seq plans){ + if(bridgeReplacement == null) return; + + Placement.calculateBridges(plans, (ItemBridge)bridgeReplacement); + } + + @Override + public void setBars(){ + super.setBars(); + pressureConfig.addBars(this); + } + + @Override + public void setStats(){ + super.setStats(); + pressureConfig.addStats(stats); + } + + public class PressureLiquidConduitBuild extends Building implements HasPressureImpl{ + + public int tiling = 0; + public float smoothAlpha; + + @Override + public boolean acceptsPressurizedFluid(HasPressure from, @Nullable Liquid liquid, float amount){ + return HasPressureImpl.super.acceptsPressurizedFluid(from, liquid, amount) && (liquid == pressure.getMain() || liquid == null || pressure.getMain() == null || from.pressure().getMain() == null); + } + + @Override + public boolean connects(HasPressure to){ + return ( + to instanceof PressureLiquidConduitBuild || to instanceof PressureLiquidValveBuild) ? + (front() == to || back() == to || to.front() == this || to.back() == this) : + to != null && HasPressureImpl.super.connects(to); + } + + @Override + public void draw(){ + Draw.rect(bottomRegion, x, y); + Liquid main = pressure.getMain(); + + smoothAlpha = Mathf.approachDelta(smoothAlpha, main == null ? 0f : pressure.liquids[main.id] / (pressure.liquids[main.id] + pressure.air), PressureModule.smoothingSpeed); + + if(smoothAlpha > 0.001f){ + int frame = pressure.current.getAnimationFrame(); + int gas = pressure.current.gas ? 1 : 0; + + float xscl = Draw.xscl, yscl = Draw.yscl; + Draw.scl(1f, 1f); + Drawf.liquid(liquidRegions[gas][frame], x, y, Mathf.clamp(smoothAlpha), pressure.current.color.write(Tmp.c1).a(1f)); + Draw.scl(xscl, yscl); + } + Draw.rect(topRegions[tiling], x, y, tiling != 0 ? 0 : (rotdeg() + 90) % 180 - 90); + } + + @Override + public void onProximityUpdate(){ + super.onProximityUpdate(); + + tiling = 0; + for(int i = 0; i < 4; i++){ + HasPressure build = nearby(i) instanceof HasPressure ? (HasPressure)nearby(i) : null; + if( + build != null && connected(build) + ) tiling |= (1 << i); + } + } + + @Override + public boolean outputsPressurizedFluid(HasPressure to, Liquid liquid, float amount){ + return HasPressureImpl.super.outputsPressurizedFluid(to, liquid, amount) && (liquid == to.pressure().getMain() || liquid == null || pressure.getMain() == null || to.pressure().getMain() == null); + } + @Override - public void read(Reads read, byte revision) { + public void read(Reads read, byte revision){ super.read(read, revision); smoothAlpha = read.f(); } @Override - public void write(Writes write) { + public void write(Writes write){ super.write(write); write.f(smoothAlpha); } - } + } } diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidGauge.java b/src/omaloon/world/blocks/liquid/PressureLiquidGauge.java index b46363aa..b8a108ff 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidGauge.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidGauge.java @@ -12,191 +12,193 @@ import mindustry.graphics.*; import mindustry.type.*; import mindustry.world.*; -import omaloon.struct.IntRef; +import omaloon.struct.*; import omaloon.ui.elements.*; import omaloon.world.interfaces.*; import omaloon.world.meta.*; import omaloon.world.modules.*; -import static mindustry.Vars.*; -import static mindustry.type.Liquid.*; - -public class PressureLiquidGauge extends Block { - public PressureConfig pressureConfig = new PressureConfig(); - - public Color maxColor = Color.white, minColor = Color.white; - - public TextureRegion[][] liquidRegions; - public TextureRegion[] tileRegions; - public TextureRegion bottomRegion, gaugeRegion; - - public float liquidPadding = 3f; - - public PressureLiquidGauge(String name) { - super(name); - rotate = true; - update = true; - destructible = true; - } - - @Override - public void drawPlanRegion(BuildPlan plan, Eachable list) { - var tiling = IntRef.tmp1.zero(); - - int dx = Geometry.d4x(plan.rotation),dy = Geometry.d4y(plan.rotation); - var front = Point2.pack(plan.x + dx, plan.y + dy); - var back = Point2.pack(plan.x - dx, plan.y - dy); - - boolean inverted = plan.rotation == 1 || plan.rotation == 2; - list.each(next -> { - var nextPoint = Point2.pack(next.x, next.y); - if(!next.block.outputsLiquid)return; - if (nextPoint == front) tiling.value |= inverted ? 0b10 : 1; - if (nextPoint == back) tiling.value |= inverted ? 1 : 0b10; - }); - - Draw.rect(bottomRegion, plan.drawx(), plan.drawy()); - Draw.rect(tileRegions[tiling.value], plan.drawx(), plan.drawy(), (plan.rotation + 1) * 90f % 180 - 90); - Draw.rect(gaugeRegion, plan.drawx(), plan.drawy(), plan.rotation * 90f); - } - - @Override - public TextureRegion[] icons() { - return new TextureRegion[]{bottomRegion, region}; - } - - @Override - public void init() { - super.init(); - - if (pressureConfig.fluidGroup == null) pressureConfig.fluidGroup = FluidGroup.transportation; - } - - @Override - public void load() { - super.load(); - tileRegions = Core.atlas.find(name + "-tiles").split(32, 32)[0]; - gaugeRegion = Core.atlas.find(name + "-pointer");; - bottomRegion = Core.atlas.find(name + "-bottom", "omaloon-liquid-bottom"); - - liquidRegions = new TextureRegion[2][animationFrames]; - if(renderer != null){ - var frames = renderer.getFluidFrames(); - - for (int fluid = 0; fluid < 2; fluid++) { - for (int frame = 0; frame < animationFrames; frame++) { - TextureRegion base = frames[fluid][frame]; - TextureRegion result = new TextureRegion(); - result.set(base); - - result.setHeight(result.height - liquidPadding); - result.setWidth(result.width - liquidPadding); - result.setX(result.getX() + liquidPadding); - result.setY(result.getY() + liquidPadding); - - liquidRegions[fluid][frame] = result; - } - } - } - } - - @Override - public void setBars() { - super.setBars(); - pressureConfig.addBars(this); - addBar("pressure", entity -> { - HasPressure build = (HasPressure)entity; - - return new CenterBar( - () -> Core.bundle.get("bar.pressure") + (build.pressure().getPressure(build.pressure().getMain()) < 0 ? "-" : "+") + Strings.autoFixed(Math.abs(build.pressure().getPressure(build.pressure().getMain())), 2), - () -> build.pressure().getPressure(build.pressure().getMain()) > 0 ? maxColor : minColor, - () -> Mathf.map(build.pressure().getPressure(build.pressure().getMain()), pressureConfig.minPressure, pressureConfig.maxPressure, -1, 1) - ); - }); - } - - @Override - public void setStats() { - super.setStats(); - pressureConfig.addStats(stats); - } - - public class PressureLiquidGaugeBuild extends Building implements HasPressureImpl { - - public int tiling; - public float smoothAlpha; - - @Override - public boolean acceptsPressurizedFluid(HasPressure from, @Nullable Liquid liquid, float amount) { - return HasPressureImpl.super.acceptsPressurizedFluid(from, liquid, amount) && (liquid == pressure.getMain() || liquid == null || pressure.getMain() == null || from.pressure().getMain() == null); - } - - @Override - public boolean connects(HasPressure to) { - return HasPressureImpl.super.connects(to) && to instanceof PressureLiquidValve.PressureLiquidValveBuild ? - (front() == to || back() == to) && (to.front() == this || to.back() == this) : - (front() == to || back() == to); - } - - @Override - public void draw() { - Draw.rect(bottomRegion, x, y); - Liquid main = pressure.getMain(); - - smoothAlpha = Mathf.approachDelta(smoothAlpha, main == null ? 0f : pressure.liquids[main.id]/(pressure.liquids[main.id] + pressure.air), PressureModule.smoothingSpeed); - - if (smoothAlpha > 0.001f) { - int frame = pressure.current.getAnimationFrame(); - int gas = pressure.current.gas ? 1 : 0; - - float xscl = Draw.xscl, yscl = Draw.yscl; - Draw.scl(1f, 1f); - Drawf.liquid(liquidRegions[gas][frame], x, y, Mathf.clamp(smoothAlpha), pressure.current.color.write(Tmp.c1).a(1f)); - Draw.scl(xscl, yscl); - } - Draw.rect(tileRegions[tiling], x, y, tiling == 0 ? 0 : (rotdeg() + 90) % 180 - 90); - - float p = Mathf.map(pressure().getPressure(pressure().getMain()), pressureConfig.minPressure, pressureConfig.maxPressure, -1, 1); - Draw.color( - Color.white, - pressure().getPressure(pressure().getMain()) > 0 ? maxColor : minColor, - Math.abs(p) - ); - Draw.rect(gaugeRegion, - x, - y, - (rotdeg() + 90) % 180 - 90 + ( - pressure().getPressure(pressure().getMain()) > pressureConfig.maxPressure + 1 || - pressure().getPressure(pressure().getMain()) < pressureConfig.minPressure - 1 - ? Mathf.randomSeed((long) Time.time, -360f, 360f) : p * 180f - ) - ); - } - - @Override - public void onProximityUpdate() { - super.onProximityUpdate(); - - tiling = 0; - boolean inverted = rotation == 1 || rotation == 2; - if (front() instanceof HasPressure front && connected(front)) tiling |= inverted ? 2 : 1; - if (back() instanceof HasPressure back && connected(back)) tiling |= inverted ? 1 : 2; - } - - @Override - public boolean outputsPressurizedFluid(HasPressure to, Liquid liquid, float amount) { - return HasPressureImpl.super.outputsPressurizedFluid(to, liquid, amount) && (liquid == to.pressure().getMain() || liquid == null || pressure.getMain() == null || to.pressure().getMain() == null); - } - @Override - public void read(Reads read, byte revision) { - super.read(read, revision); - smoothAlpha = read.f(); - } - - @Override - public void write(Writes write) { - super.write(write); - write.f(smoothAlpha); - } - } +import static mindustry.Vars.renderer; +import static mindustry.type.Liquid.animationFrames; + +public class PressureLiquidGauge extends Block{ + public PressureConfig pressureConfig = new PressureConfig(); + + public Color maxColor = Color.white, minColor = Color.white; + + public TextureRegion[][] liquidRegions; + public TextureRegion[] tileRegions; + public TextureRegion bottomRegion, gaugeRegion; + + public float liquidPadding = 3f; + + public PressureLiquidGauge(String name){ + super(name); + rotate = true; + update = true; + destructible = true; + } + + @Override + public void drawPlanRegion(BuildPlan plan, Eachable list){ + var tiling = IntRef.tmp1.zero(); + + int dx = Geometry.d4x(plan.rotation), dy = Geometry.d4y(plan.rotation); + var front = Point2.pack(plan.x + dx, plan.y + dy); + var back = Point2.pack(plan.x - dx, plan.y - dy); + + boolean inverted = plan.rotation == 1 || plan.rotation == 2; + list.each(next -> { + var nextPoint = Point2.pack(next.x, next.y); + if(!next.block.outputsLiquid) return; + if(nextPoint == front) tiling.value |= inverted ? 0b10 : 1; + if(nextPoint == back) tiling.value |= inverted ? 1 : 0b10; + }); + + Draw.rect(bottomRegion, plan.drawx(), plan.drawy()); + Draw.rect(tileRegions[tiling.value], plan.drawx(), plan.drawy(), (plan.rotation + 1) * 90f % 180 - 90); + Draw.rect(gaugeRegion, plan.drawx(), plan.drawy(), plan.rotation * 90f); + } + + @Override + public TextureRegion[] icons(){ + return new TextureRegion[]{bottomRegion, region}; + } + + @Override + public void init(){ + super.init(); + + if(pressureConfig.fluidGroup == null) pressureConfig.fluidGroup = FluidGroup.transportation; + } + + @Override + public void load(){ + super.load(); + tileRegions = Core.atlas.find(name + "-tiles").split(32, 32)[0]; + gaugeRegion = Core.atlas.find(name + "-pointer"); + ; + bottomRegion = Core.atlas.find(name + "-bottom", "omaloon-liquid-bottom"); + + liquidRegions = new TextureRegion[2][animationFrames]; + if(renderer != null){ + var frames = renderer.getFluidFrames(); + + for(int fluid = 0; fluid < 2; fluid++){ + for(int frame = 0; frame < animationFrames; frame++){ + TextureRegion base = frames[fluid][frame]; + TextureRegion result = new TextureRegion(); + result.set(base); + + result.setHeight(result.height - liquidPadding); + result.setWidth(result.width - liquidPadding); + result.setX(result.getX() + liquidPadding); + result.setY(result.getY() + liquidPadding); + + liquidRegions[fluid][frame] = result; + } + } + } + } + + @Override + public void setBars(){ + super.setBars(); + pressureConfig.addBars(this); + addBar("pressure", entity -> { + HasPressure build = (HasPressure)entity; + + return new CenterBar( + () -> Core.bundle.get("bar.pressure") + (build.pressure().getPressure(build.pressure().getMain()) < 0 ? "-" : "+") + Strings.autoFixed(Math.abs(build.pressure().getPressure(build.pressure().getMain())), 2), + () -> build.pressure().getPressure(build.pressure().getMain()) > 0 ? maxColor : minColor, + () -> Mathf.map(build.pressure().getPressure(build.pressure().getMain()), pressureConfig.minPressure, pressureConfig.maxPressure, -1, 1) + ); + }); + } + + @Override + public void setStats(){ + super.setStats(); + pressureConfig.addStats(stats); + } + + public class PressureLiquidGaugeBuild extends Building implements HasPressureImpl{ + + public int tiling; + public float smoothAlpha; + + @Override + public boolean acceptsPressurizedFluid(HasPressure from, @Nullable Liquid liquid, float amount){ + return HasPressureImpl.super.acceptsPressurizedFluid(from, liquid, amount) && (liquid == pressure.getMain() || liquid == null || pressure.getMain() == null || from.pressure().getMain() == null); + } + + @Override + public boolean connects(HasPressure to){ + return HasPressureImpl.super.connects(to) && to instanceof PressureLiquidValve.PressureLiquidValveBuild ? + (front() == to || back() == to) && (to.front() == this || to.back() == this) : + (front() == to || back() == to); + } + + @Override + public void draw(){ + Draw.rect(bottomRegion, x, y); + Liquid main = pressure.getMain(); + + smoothAlpha = Mathf.approachDelta(smoothAlpha, main == null ? 0f : pressure.liquids[main.id] / (pressure.liquids[main.id] + pressure.air), PressureModule.smoothingSpeed); + + if(smoothAlpha > 0.001f){ + int frame = pressure.current.getAnimationFrame(); + int gas = pressure.current.gas ? 1 : 0; + + float xscl = Draw.xscl, yscl = Draw.yscl; + Draw.scl(1f, 1f); + Drawf.liquid(liquidRegions[gas][frame], x, y, Mathf.clamp(smoothAlpha), pressure.current.color.write(Tmp.c1).a(1f)); + Draw.scl(xscl, yscl); + } + Draw.rect(tileRegions[tiling], x, y, tiling == 0 ? 0 : (rotdeg() + 90) % 180 - 90); + + float p = Mathf.map(pressure().getPressure(pressure().getMain()), pressureConfig.minPressure, pressureConfig.maxPressure, -1, 1); + Draw.color( + Color.white, + pressure().getPressure(pressure().getMain()) > 0 ? maxColor : minColor, + Math.abs(p) + ); + Draw.rect(gaugeRegion, + x, + y, + (rotdeg() + 90) % 180 - 90 + ( + pressure().getPressure(pressure().getMain()) > pressureConfig.maxPressure + 1 || + pressure().getPressure(pressure().getMain()) < pressureConfig.minPressure - 1 + ? Mathf.randomSeed((long)Time.time, -360f, 360f) : p * 180f + ) + ); + } + + @Override + public void onProximityUpdate(){ + super.onProximityUpdate(); + + tiling = 0; + boolean inverted = rotation == 1 || rotation == 2; + if(front() instanceof HasPressure front && connected(front)) tiling |= inverted ? 2 : 1; + if(back() instanceof HasPressure back && connected(back)) tiling |= inverted ? 1 : 2; + } + + @Override + public boolean outputsPressurizedFluid(HasPressure to, Liquid liquid, float amount){ + return HasPressureImpl.super.outputsPressurizedFluid(to, liquid, amount) && (liquid == to.pressure().getMain() || liquid == null || pressure.getMain() == null || to.pressure().getMain() == null); + } + + @Override + public void read(Reads read, byte revision){ + super.read(read, revision); + smoothAlpha = read.f(); + } + + @Override + public void write(Writes write){ + super.write(write); + write.f(smoothAlpha); + } + } } diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidJunction.java b/src/omaloon/world/blocks/liquid/PressureLiquidJunction.java index 20b26a90..8ef3bda3 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidJunction.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidJunction.java @@ -2,57 +2,58 @@ import arc.struct.*; import arc.util.*; -import arc.util.io.*; import mindustry.gen.*; import mindustry.type.*; import mindustry.world.*; import omaloon.world.interfaces.*; import omaloon.world.meta.*; -import omaloon.world.modules.*; - -public class PressureLiquidJunction extends Block { - public PressureConfig pressureConfig = new PressureConfig(); - - public PressureLiquidJunction(String name) { - super(name); - update = true; - destructible = true; - } - - public class PressureLiquidJunctionBuild extends Building implements HasPressureImpl { - - @Override public boolean acceptsPressurizedFluid(HasPressure from, @Nullable Liquid liquid, float amount) { - return false; - } - - @Override - public boolean connects(HasPressure to) { - return HasPressureImpl.super.connects(to) && !(to instanceof PressureLiquidPump); - } - - @Override - public HasPressure getPressureDestination(HasPressure source, float pressure) { - if(!enabled) return this; - - int dir = (source.relativeTo(tile.x, tile.y) + 4) % 4; - HasPressure next = nearby(dir) instanceof HasPressure ? (HasPressure) nearby(dir) : null; - if(next == null) { - return this; - } - return next.getPressureDestination(this, pressure); - } - - @Override public HasPressure getSectionDestination(HasPressure from) { - return null; - } - - @Override - public Seq nextBuilds() { - return Seq.with(); - } - - @Override public boolean outputsPressurizedFluid(HasPressure to, @Nullable Liquid liquid, float amount) { - return false; - } - } + +public class PressureLiquidJunction extends Block{ + public PressureConfig pressureConfig = new PressureConfig(); + + public PressureLiquidJunction(String name){ + super(name); + update = true; + destructible = true; + } + + public class PressureLiquidJunctionBuild extends Building implements HasPressureImpl{ + + @Override + public boolean acceptsPressurizedFluid(HasPressure from, @Nullable Liquid liquid, float amount){ + return false; + } + + @Override + public boolean connects(HasPressure to){ + return HasPressureImpl.super.connects(to) && !(to instanceof PressureLiquidPump); + } + + @Override + public HasPressure getPressureDestination(HasPressure source, float pressure){ + if(!enabled) return this; + + int dir = (source.relativeTo(tile.x, tile.y) + 4) % 4; + HasPressure next = nearby(dir) instanceof HasPressure ? (HasPressure)nearby(dir) : null; + if(next == null){ + return this; + } + return next.getPressureDestination(this, pressure); + } + + @Override + public HasPressure getSectionDestination(HasPressure from){ + return null; + } + + @Override + public Seq nextBuilds(){ + return Seq.with(); + } + + @Override + public boolean outputsPressurizedFluid(HasPressure to, @Nullable Liquid liquid, float amount){ + return false; + } + } } diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidPump.java b/src/omaloon/world/blocks/liquid/PressureLiquidPump.java index c1bd56ba..5c38cdba 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidPump.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidPump.java @@ -8,7 +8,6 @@ import arc.scene.ui.layout.*; import arc.util.*; import arc.util.io.*; -import asmlib.annotations.DebugAST; import mindustry.*; import mindustry.content.*; import mindustry.entities.*; @@ -19,351 +18,356 @@ import mindustry.world.*; import mindustry.world.blocks.*; import mindustry.world.meta.*; -import mindustry.world.blocks.liquid.*; -import omaloon.annotations.AutoImplement; -import omaloon.annotations.Load; +import omaloon.annotations.*; import omaloon.content.*; import omaloon.math.*; -import omaloon.struct.IntRef; +import omaloon.struct.*; import omaloon.utils.*; import omaloon.world.interfaces.*; import omaloon.world.meta.*; import omaloon.world.modules.*; import static mindustry.Vars.*; -import static mindustry.type.Liquid.*; - -public class PressureLiquidPump extends Block { - public PressureConfig pressureConfig = new PressureConfig(); - - public float pumpStrength = 0.1f; - - public float pressureDifference = 10; - - public float liquidPadding = 3f; - - public float effectInterval = 5f; - public Effect pumpEffectOut = Fx.none; - public Effect pumpEffectIn = Fx.none; - - public TextureRegion[][] liquidRegions; - public TextureRegion[] tiles; - public TextureRegion topRegion, bottomRegion, filterRegion; - @Load("@-arrow") public TextureRegion arrowRegion; - - public PressureLiquidPump(String name) { - super(name); - rotate = true; - destructible = true; - update = true; - saveConfig = copyConfig = true; - config(Liquid.class, (PressureLiquidPumpBuild build, Liquid liquid) -> { - build.filter = liquid == null ? -1 : liquid.id; - }); - } - - @Override - public void drawPlanRegion(BuildPlan plan, Eachable list) { - - var tiling = IntRef.tmp1.zero(); - - int dx = Geometry.d4x(plan.rotation),dy = Geometry.d4y(plan.rotation); - var front = Point2.pack(plan.x + dx, plan.y + dy); - var back = Point2.pack(plan.x - dx, plan.y - dy); - - boolean inverted = plan.rotation == 1 || plan.rotation == 2; - list.each(next -> { - var nextPoint = Point2.pack(next.x, next.y); - if(!next.block.outputsLiquid)return; - if (nextPoint == front) tiling.value |= inverted ? 0b10 : 1; - if (nextPoint == back) tiling.value |= inverted ? 1 : 0b10; - }); - - Draw.rect(bottomRegion, plan.drawx(), plan.drawy(), 0); - if (tiling.value != 0) Draw.rect(arrowRegion, plan.drawx(), plan.drawy(), (plan.rotation) * 90f); - Draw.rect(tiles[tiling.value], plan.drawx(), plan.drawy(), (plan.rotation + 1) * 90f % 180 - 90); - if (tiling.value == 0) Draw.rect(topRegion, plan.drawx(), plan.drawy(), (plan.rotation) * 90f); - } - - @Override public TextureRegion[] icons() { - return new TextureRegion[]{region, topRegion}; - } - - @Override - public void init() { - super.init(); - - pressureConfig.fluidGroup = FluidGroup.pumps; - } - - @Override - public void load() { - super.load(); - tiles = OlUtils.split(name + "-tiles", 32, 0); - arrowRegion = Core.atlas.find(name + "-arrow"); - topRegion = Core.atlas.find(name + "-top"); - filterRegion = Core.atlas.find(name + "-filter"); - bottomRegion = Core.atlas.find(name + "-bottom", "omaloon-liquid-bottom"); - - liquidRegions = new TextureRegion[2][animationFrames]; - if(renderer != null){ - var frames = renderer.getFluidFrames(); - - for (int fluid = 0; fluid < 2; fluid++) { - for (int frame = 0; frame < animationFrames; frame++) { - TextureRegion base = frames[fluid][frame]; - TextureRegion result = new TextureRegion(); - result.set(base); - - result.setHeight(result.height - liquidPadding); - result.setWidth(result.width - liquidPadding); - result.setX(result.getX() + liquidPadding); - result.setY(result.getY() + liquidPadding); - - liquidRegions[fluid][frame] = result; - } - } - } - } - - @Override - public void setStats() { - super.setStats(); - pressureConfig.addStats(stats); - stats.remove(OlStats.fluidCapacity); - stats.add(OlStats.pumpStrength, pumpStrength * 60f, StatUnit.liquidSecond); - stats.add(OlStats.pressureGradient, OlStats.pressure(pressureDifference, true)); - } - - public class PressureLiquidPumpBuild extends Building implements HasPressureImpl { - public float effectTimer; - public int tiling; - public float smoothAlpha; - - public boolean functioning; - - public int filter = -1; - - @Override public boolean acceptsPressurizedFluid(HasPressure from, @Nullable Liquid liquid, float amount) { - return false; - } - - @Override - public float ambientVolume() { - return 1f/chainSize(); - } - - @Override - public void buildConfiguration(Table table) { - ItemSelection.buildTable(table, Vars.content.liquids(), () -> Vars.content.liquid(filter), other -> filter = other == null ? -1 : other.id); - } - - /** - * Returns the length of the pump chain - */ - public int chainSize() { - return pressure.section.builds.size; - } - - @Override - public Liquid config() { - return content.liquid(filter); - } - - @Override public boolean connects(HasPressure to) { - return HasPressureImpl.super.connects(to) && (front() == to || back() == to) && (!(to instanceof PressureLiquidPumpBuild) || to.rotation() == rotation); - } - - @Override - public void draw() { - float rot = rotate ? (90 + rotdeg()) % 180 - 90 : 0; - if (tiling != 0) { - Draw.rect(bottomRegion, x, y, rotdeg()); - - HasPressure front = getTo(); - HasPressure back = getFrom(); - - if ( - (front != null && front.pressure().getMain() != null) || - (back != null && back.pressure().getMain() != null) - ) { - - Color tmpColor = Tmp.c1; - if (front != null && front.pressure().getMain() != null) { - tmpColor.set(front.pressure().getMain().color); - } else if (back != null && back.pressure().getMain() != null) { - tmpColor.set(back.pressure().getMain().color); - } - - if ( - front != null && front.pressure().getMain() != null && - back != null && back.pressure().getMain() != null - ) tmpColor.lerp(back.pressure().getMain().color, 0.5f); - - - float alpha = - (front != null && front.pressure().getMain() != null ? Mathf.clamp(front.pressure().liquids[front.pressure().getMain().id]/(front.pressure().liquids[front.pressure().getMain().id] + front.pressure().air)) : 0) + - (back != null && back.pressure().getMain() != null ? Mathf.clamp(back.pressure().liquids[back.pressure().getMain().id]/(back.pressure().liquids[back.pressure().getMain().id] + back.pressure().air)) : 0); - alpha /= ((front == null ? 0 : 1f) + (back == null ? 0 : 1f)); - - smoothAlpha = Mathf.approachDelta(smoothAlpha, alpha, PressureModule.smoothingSpeed); - - Liquid drawLiquid = Liquids.water; - if (front != null && front.pressure().getMain() != null) { - drawLiquid = front.pressure().current; - } else if (back != null && back.pressure().getMain() != null) { - drawLiquid = back.pressure().current; - } - - int frame = drawLiquid.getAnimationFrame(); - int gas = drawLiquid.gas ? 1 : 0; - - float xscl = Draw.xscl, yscl = Draw.yscl; - Draw.scl(1f, 1f); - Drawf.liquid(liquidRegions[gas][frame], x, y, smoothAlpha, tmpColor); - Draw.scl(xscl, yscl); - } - Draw.rect(arrowRegion, x, y, rotdeg()); - } - Draw.rect(tiles[tiling], x, y, rot); - if (filterRegion.found() && configurable && content.liquid(filter) != null) { - Draw.color(content.liquid(filter).color); - Draw.rect(filterRegion, x, y, rot); - Draw.color(); - } - if (tiling == 0) Draw.rect(topRegion, x, y, rotdeg()); - } - - /** - * Returns the building at the start of the pump chain. - */ - public @Nullable HasPressure getFrom() { - PressureLiquidPumpBuild last = this; - HasPressure out = back() instanceof HasPressure back ? back.getPressureDestination(last, 0) : null; - while (out instanceof PressureLiquidPumpBuild pump) { - if (!pump.connected(last)) return null; - last = pump; - out = pump.back() instanceof HasPressure back ? back.getPressureDestination(last, 0) : null; - } - return (out != null && out.connected(last)) ? out : null; - } - /** - * Returns the building at the end of the pump chain. - */ - public @Nullable HasPressure getTo() { - PressureLiquidPumpBuild last = this; - HasPressure out = front() instanceof HasPressure front ? front.getPressureDestination(last, 0) : null; - while (out instanceof PressureLiquidPumpBuild pump) { - if (!pump.connected(last)) return null; - last = pump; - out = pump.front() instanceof HasPressure front ? front.getPressureDestination(last, 0) : null; - } - return (out != null && out.connected(last)) ? out : null; - } - - @Override - public void onProximityUpdate() { - super.onProximityUpdate(); - - tiling = 0; - boolean inverted = rotation == 1 || rotation == 2; - if (front() instanceof HasPressure front && connected(front)) tiling |= inverted ? 2 : 1; - if (back() instanceof HasPressure back && connected(back)) tiling |= inverted ? 1 : 2;; - } - - @Override public boolean outputsPressurizedFluid(HasPressure to, @Nullable Liquid liquid, float amount) { - return false; - } - - @Override - public void read(Reads read, byte revision) { - super.read(read, revision); - filter = read.i(); - smoothAlpha = read.f(); - } - - @Override - public boolean shouldAmbientSound() { - return functioning; - } - - @Override - @AutoImplement.NoInject(HasPressureImpl.class) - public void updateTile() { - if (efficiency > 0) { - HasPressure front = getTo(); - HasPressure back = getFrom(); - - @Nullable Liquid pumpLiquid = configurable ? Vars.content.liquid(filter) : (back == null ? null : back.pressure().getMain()); - - float frontPressure = front == null ? 0 : front.pressure().getPressure(pumpLiquid); - float backPressure = back == null ? 0 : back.pressure().getPressure(pumpLiquid); - - float maxFlow = OlMath.flowRate( - backPressure + pressureDifference * chainSize(), - frontPressure, - back == null ? 5 : back.pressureConfig().fluidCapacity, - front == null ? 5 : front.pressureConfig().fluidCapacity, - OlLiquids.getDensity(pumpLiquid), - 1 - ); - - if (back != null) { - pressure.pressure = back.pressure().getPressure(pumpLiquid); - updatePressure(); - } - if (front != null) { - pressure.pressure = front.pressure().getPressure(pumpLiquid); - updatePressure(); - } - pressure.pressure = 0; - - float flow = Mathf.clamp( - (maxFlow > 0 ? pumpStrength : -pumpStrength)/chainSize() * Time.delta, - -Math.abs(maxFlow), - Math.abs(maxFlow) - ); - - if (effectTimer >= effectInterval && !Mathf.zero(flow, 0.001f)) { - if (flow < 0) { - if (pumpLiquid == null || (front != null && front.pressure().get(pumpLiquid) > 0.001f)) { - if (back == null && !(back() instanceof PressureLiquidPumpBuild p && p.rotation == rotation)) pumpEffectOut.at(x, y, rotdeg() + 180f, pumpLiquid == null ? Color.white : pumpLiquid.color); - if (front == null && !(front() instanceof PressureLiquidPumpBuild p && p.rotation == rotation)) pumpEffectIn.at(x, y, rotdeg(), pumpLiquid == null ? Color.white : pumpLiquid.color); - } - } else { - if (pumpLiquid == null || (back != null && back.pressure().get(pumpLiquid) > 0.001f)) { - if (back == null && !(back() instanceof PressureLiquidPumpBuild p && p.rotation == rotation)) pumpEffectIn.at(x, y, rotdeg() + 180f, pumpLiquid == null ? Color.white : pumpLiquid.color); - if (front == null && !(front() instanceof PressureLiquidPumpBuild p && p.rotation == rotation)) pumpEffectOut.at(x, y, rotdeg(), pumpLiquid == null ? Color.white : pumpLiquid.color); - } - } - effectTimer %= 1; - } - - functioning = !Mathf.zero(flow, 0.001f); - - if ( - front == null || back == null || - (front.acceptsPressurizedFluid(back, pumpLiquid, flow) && - back.outputsPressurizedFluid(front, pumpLiquid, flow)) - ) { - effectTimer += edelta(); - if (front != null) front.addFluid(pumpLiquid, flow); - if (back != null) back.removeFluid(pumpLiquid, flow); - } - } - } - - @Override - public void updatePressure() { - if (pressure().pressure < pressureConfig().minPressure - 1f) damage(pressureConfig().underPressureDamage); - if (pressure().pressure > pressureConfig().maxPressure + 1f) damage(pressureConfig().overPressureDamage); - } - - @Override - public void write(Writes write) { - super.write(write); - write.i(filter); - write.f(smoothAlpha); - } - } +import static mindustry.type.Liquid.animationFrames; + +public class PressureLiquidPump extends Block{ + public PressureConfig pressureConfig = new PressureConfig(); + + public float pumpStrength = 0.1f; + + public float pressureDifference = 10; + + public float liquidPadding = 3f; + + public float effectInterval = 5f; + public Effect pumpEffectOut = Fx.none; + public Effect pumpEffectIn = Fx.none; + + public TextureRegion[][] liquidRegions; + public TextureRegion[] tiles; + public TextureRegion topRegion, bottomRegion, filterRegion; + @Load("@-arrow") + public TextureRegion arrowRegion; + + public PressureLiquidPump(String name){ + super(name); + rotate = true; + destructible = true; + update = true; + saveConfig = copyConfig = true; + config(Liquid.class, (PressureLiquidPumpBuild build, Liquid liquid) -> { + build.filter = liquid == null ? -1 : liquid.id; + }); + } + + @Override + public void drawPlanRegion(BuildPlan plan, Eachable list){ + + var tiling = IntRef.tmp1.zero(); + + int dx = Geometry.d4x(plan.rotation), dy = Geometry.d4y(plan.rotation); + var front = Point2.pack(plan.x + dx, plan.y + dy); + var back = Point2.pack(plan.x - dx, plan.y - dy); + + boolean inverted = plan.rotation == 1 || plan.rotation == 2; + list.each(next -> { + var nextPoint = Point2.pack(next.x, next.y); + if(!next.block.outputsLiquid) return; + if(nextPoint == front) tiling.value |= inverted ? 0b10 : 1; + if(nextPoint == back) tiling.value |= inverted ? 1 : 0b10; + }); + + Draw.rect(bottomRegion, plan.drawx(), plan.drawy(), 0); + if(tiling.value != 0) Draw.rect(arrowRegion, plan.drawx(), plan.drawy(), (plan.rotation) * 90f); + Draw.rect(tiles[tiling.value], plan.drawx(), plan.drawy(), (plan.rotation + 1) * 90f % 180 - 90); + if(tiling.value == 0) Draw.rect(topRegion, plan.drawx(), plan.drawy(), (plan.rotation) * 90f); + } + + @Override + public TextureRegion[] icons(){ + return new TextureRegion[]{region, topRegion}; + } + + @Override + public void init(){ + super.init(); + + pressureConfig.fluidGroup = FluidGroup.pumps; + } + + @Override + public void load(){ + super.load(); + tiles = OlUtils.split(name + "-tiles", 32, 0); + arrowRegion = Core.atlas.find(name + "-arrow"); + topRegion = Core.atlas.find(name + "-top"); + filterRegion = Core.atlas.find(name + "-filter"); + bottomRegion = Core.atlas.find(name + "-bottom", "omaloon-liquid-bottom"); + + liquidRegions = new TextureRegion[2][animationFrames]; + if(renderer != null){ + var frames = renderer.getFluidFrames(); + + for(int fluid = 0; fluid < 2; fluid++){ + for(int frame = 0; frame < animationFrames; frame++){ + TextureRegion base = frames[fluid][frame]; + TextureRegion result = new TextureRegion(); + result.set(base); + + result.setHeight(result.height - liquidPadding); + result.setWidth(result.width - liquidPadding); + result.setX(result.getX() + liquidPadding); + result.setY(result.getY() + liquidPadding); + + liquidRegions[fluid][frame] = result; + } + } + } + } + + @Override + public void setStats(){ + super.setStats(); + pressureConfig.addStats(stats); + stats.remove(OlStats.fluidCapacity); + stats.add(OlStats.pumpStrength, pumpStrength * 60f, StatUnit.liquidSecond); + stats.add(OlStats.pressureGradient, OlStats.pressure(pressureDifference, true)); + } + + public class PressureLiquidPumpBuild extends Building implements HasPressureImpl{ + public float effectTimer; + public int tiling; + public float smoothAlpha; + + public boolean functioning; + + public int filter = -1; + + @Override + public boolean acceptsPressurizedFluid(HasPressure from, @Nullable Liquid liquid, float amount){ + return false; + } + + @Override + public float ambientVolume(){ + return 1f / chainSize(); + } + + @Override + public void buildConfiguration(Table table){ + ItemSelection.buildTable(table, Vars.content.liquids(), () -> Vars.content.liquid(filter), other -> filter = other == null ? -1 : other.id); + } + + /** + * Returns the length of the pump chain + */ + public int chainSize(){ + return pressure.section.builds.size; + } + + @Override + public Liquid config(){ + return content.liquid(filter); + } + + @Override + public boolean connects(HasPressure to){ + return HasPressureImpl.super.connects(to) && (front() == to || back() == to) && (!(to instanceof PressureLiquidPumpBuild) || to.rotation() == rotation); + } + + @Override + public void draw(){ + float rot = rotate ? (90 + rotdeg()) % 180 - 90 : 0; + if(tiling != 0){ + Draw.rect(bottomRegion, x, y, rotdeg()); + + HasPressure front = getTo(); + HasPressure back = getFrom(); + + if( + (front != null && front.pressure().getMain() != null) || + (back != null && back.pressure().getMain() != null) + ){ + + Color tmpColor = Tmp.c1; + if(front != null && front.pressure().getMain() != null){ + tmpColor.set(front.pressure().getMain().color); + }else if(back != null && back.pressure().getMain() != null){ + tmpColor.set(back.pressure().getMain().color); + } + + if( + front != null && front.pressure().getMain() != null && + back != null && back.pressure().getMain() != null + ) tmpColor.lerp(back.pressure().getMain().color, 0.5f); + + + float alpha = + (front != null && front.pressure().getMain() != null ? Mathf.clamp(front.pressure().liquids[front.pressure().getMain().id] / (front.pressure().liquids[front.pressure().getMain().id] + front.pressure().air)) : 0) + + (back != null && back.pressure().getMain() != null ? Mathf.clamp(back.pressure().liquids[back.pressure().getMain().id] / (back.pressure().liquids[back.pressure().getMain().id] + back.pressure().air)) : 0); + alpha /= ((front == null ? 0 : 1f) + (back == null ? 0 : 1f)); + + smoothAlpha = Mathf.approachDelta(smoothAlpha, alpha, PressureModule.smoothingSpeed); + + Liquid drawLiquid = Liquids.water; + if(front != null && front.pressure().getMain() != null){ + drawLiquid = front.pressure().current; + }else if(back != null && back.pressure().getMain() != null){ + drawLiquid = back.pressure().current; + } + + int frame = drawLiquid.getAnimationFrame(); + int gas = drawLiquid.gas ? 1 : 0; + + float xscl = Draw.xscl, yscl = Draw.yscl; + Draw.scl(1f, 1f); + Drawf.liquid(liquidRegions[gas][frame], x, y, smoothAlpha, tmpColor); + Draw.scl(xscl, yscl); + } + Draw.rect(arrowRegion, x, y, rotdeg()); + } + Draw.rect(tiles[tiling], x, y, rot); + if(filterRegion.found() && configurable && content.liquid(filter) != null){ + Draw.color(content.liquid(filter).color); + Draw.rect(filterRegion, x, y, rot); + Draw.color(); + } + if(tiling == 0) Draw.rect(topRegion, x, y, rotdeg()); + } + + /** + * Returns the building at the start of the pump chain. + */ + public @Nullable HasPressure getFrom(){ + PressureLiquidPumpBuild last = this; + HasPressure out = back() instanceof HasPressure back ? back.getPressureDestination(last, 0) : null; + while(out instanceof PressureLiquidPumpBuild pump){ + if(!pump.connected(last)) return null; + last = pump; + out = pump.back() instanceof HasPressure back ? back.getPressureDestination(last, 0) : null; + } + return (out != null && out.connected(last)) ? out : null; + } + + /** + * Returns the building at the end of the pump chain. + */ + public @Nullable HasPressure getTo(){ + PressureLiquidPumpBuild last = this; + HasPressure out = front() instanceof HasPressure front ? front.getPressureDestination(last, 0) : null; + while(out instanceof PressureLiquidPumpBuild pump){ + if(!pump.connected(last)) return null; + last = pump; + out = pump.front() instanceof HasPressure front ? front.getPressureDestination(last, 0) : null; + } + return (out != null && out.connected(last)) ? out : null; + } + + @Override + public void onProximityUpdate(){ + super.onProximityUpdate(); + + tiling = 0; + boolean inverted = rotation == 1 || rotation == 2; + if(front() instanceof HasPressure front && connected(front)) tiling |= inverted ? 2 : 1; + if(back() instanceof HasPressure back && connected(back)) tiling |= inverted ? 1 : 2; + ; + } + + @Override + public boolean outputsPressurizedFluid(HasPressure to, @Nullable Liquid liquid, float amount){ + return false; + } + + @Override + public void read(Reads read, byte revision){ + super.read(read, revision); + filter = read.i(); + smoothAlpha = read.f(); + } + + @Override + public boolean shouldAmbientSound(){ + return functioning; + } + + @Override + @AutoImplement.NoInject(HasPressureImpl.class) + public void updateTile(){ + if(efficiency > 0){ + HasPressure front = getTo(); + HasPressure back = getFrom(); + + @Nullable Liquid pumpLiquid = configurable ? Vars.content.liquid(filter) : (back == null ? null : back.pressure().getMain()); + + float frontPressure = front == null ? 0 : front.pressure().getPressure(pumpLiquid); + float backPressure = back == null ? 0 : back.pressure().getPressure(pumpLiquid); + + float maxFlow = OlMath.flowRate( + backPressure + pressureDifference * chainSize(), + frontPressure, + back == null ? 5 : back.pressureConfig().fluidCapacity, + front == null ? 5 : front.pressureConfig().fluidCapacity, + OlLiquids.getDensity(pumpLiquid), + 1 + ); + + if(back != null){ + pressure.pressure = back.pressure().getPressure(pumpLiquid); + updatePressure(); + } + if(front != null){ + pressure.pressure = front.pressure().getPressure(pumpLiquid); + updatePressure(); + } + pressure.pressure = 0; + + float flow = Mathf.clamp( + (maxFlow > 0 ? pumpStrength : -pumpStrength) / chainSize() * Time.delta, + -Math.abs(maxFlow), + Math.abs(maxFlow) + ); + + if(effectTimer >= effectInterval && !Mathf.zero(flow, 0.001f)){ + if(flow < 0){ + if(pumpLiquid == null || (front != null && front.pressure().get(pumpLiquid) > 0.001f)){ + if(back == null && !(back() instanceof PressureLiquidPumpBuild p && p.rotation == rotation)) pumpEffectOut.at(x, y, rotdeg() + 180f, pumpLiquid == null ? Color.white : pumpLiquid.color); + if(front == null && !(front() instanceof PressureLiquidPumpBuild p && p.rotation == rotation)) pumpEffectIn.at(x, y, rotdeg(), pumpLiquid == null ? Color.white : pumpLiquid.color); + } + }else{ + if(pumpLiquid == null || (back != null && back.pressure().get(pumpLiquid) > 0.001f)){ + if(back == null && !(back() instanceof PressureLiquidPumpBuild p && p.rotation == rotation)) pumpEffectIn.at(x, y, rotdeg() + 180f, pumpLiquid == null ? Color.white : pumpLiquid.color); + if(front == null && !(front() instanceof PressureLiquidPumpBuild p && p.rotation == rotation)) pumpEffectOut.at(x, y, rotdeg(), pumpLiquid == null ? Color.white : pumpLiquid.color); + } + } + effectTimer %= 1; + } + + functioning = !Mathf.zero(flow, 0.001f); + + if( + front == null || back == null || + (front.acceptsPressurizedFluid(back, pumpLiquid, flow) && + back.outputsPressurizedFluid(front, pumpLiquid, flow)) + ){ + effectTimer += edelta(); + if(front != null) front.addFluid(pumpLiquid, flow); + if(back != null) back.removeFluid(pumpLiquid, flow); + } + } + } + + @Override + public void updatePressure(){ + if(pressure().pressure < pressureConfig().minPressure - 1f) damage(pressureConfig().underPressureDamage); + if(pressure().pressure > pressureConfig().maxPressure + 1f) damage(pressureConfig().overPressureDamage); + } + + @Override + public void write(Writes write){ + super.write(write); + write.i(filter); + write.f(smoothAlpha); + } + } } diff --git a/src/omaloon/world/blocks/liquid/PressureLiquidValve.java b/src/omaloon/world/blocks/liquid/PressureLiquidValve.java index c285df90..b5cf3622 100644 --- a/src/omaloon/world/blocks/liquid/PressureLiquidValve.java +++ b/src/omaloon/world/blocks/liquid/PressureLiquidValve.java @@ -17,59 +17,59 @@ import mindustry.world.*; import omaloon.content.*; import omaloon.math.*; -import omaloon.utils.*; import omaloon.struct.*; +import omaloon.utils.*; import omaloon.world.interfaces.*; import omaloon.world.meta.*; import omaloon.world.modules.*; -import static mindustry.Vars.*; -import static mindustry.type.Liquid.*; +import static mindustry.Vars.renderer; +import static mindustry.type.Liquid.animationFrames; -public class PressureLiquidValve extends Block { - public PressureConfig pressureConfig = new PressureConfig(); +public class PressureLiquidValve extends Block{ + public PressureConfig pressureConfig = new PressureConfig(); - public TextureRegion[] tiles; - public TextureRegion[][] liquidRegions; - public TextureRegion valveRegion, topRegion, bottomRegion; + public TextureRegion[] tiles; + public TextureRegion[][] liquidRegions; + public TextureRegion valveRegion, topRegion, bottomRegion; - public Effect jamEffect = Fx.explosion; - public Sound jamSound = OlSounds.jam; + public Effect jamEffect = Fx.explosion; + public Sound jamSound = OlSounds.jam; - public Effect pumpingEffectOut = Fx.none; - public Effect pumpingEffectIn = Fx.none; - public float pumpingEffectInterval = 15; + public Effect pumpingEffectOut = Fx.none; + public Effect pumpingEffectIn = Fx.none; + public float pumpingEffectInterval = 15; - public float pressureLoss = 1f; - public float minPressureLoss = 0.05f; + public float pressureLoss = 1f; + public float minPressureLoss = 0.05f; - public float openMin = -15f; - public float openMax = 15f; - public float jamPoint = -45f; + public float openMin = -15f; + public float openMax = 15f; + public float jamPoint = -45f; - public float liquidPadding = 3f; + public float liquidPadding = 3f; - public PressureLiquidValve(String name) { - super(name); - rotate = true; - update = true; - destructible = true; - } + public PressureLiquidValve(String name){ + super(name); + rotate = true; + update = true; + destructible = true; + } @Override - public void drawPlanRegion(BuildPlan plan, Eachable list) { + public void drawPlanRegion(BuildPlan plan, Eachable list){ var tiling = IntRef.tmp1.zero(); - int dx = Geometry.d4x(plan.rotation),dy = Geometry.d4y(plan.rotation); + int dx = Geometry.d4x(plan.rotation), dy = Geometry.d4y(plan.rotation); var front = Point2.pack(plan.x + dx, plan.y + dy); var back = Point2.pack(plan.x - dx, plan.y - dy); boolean inverted = plan.rotation == 1 || plan.rotation == 2; list.each(next -> { var nextPoint = Point2.pack(next.x, next.y); - if(!next.block.outputsLiquid)return; - if (nextPoint == front) tiling.value |= inverted ? 0b10 : 1; - if (nextPoint == back) tiling.value |= inverted ? 1 : 0b10; + if(!next.block.outputsLiquid) return; + if(nextPoint == front) tiling.value |= inverted ? 0b10 : 1; + if(nextPoint == back) tiling.value |= inverted ? 1 : 0b10; }); Draw.rect(bottomRegion, plan.drawx(), plan.drawy(), 0); @@ -78,32 +78,32 @@ public void drawPlanRegion(BuildPlan plan, Eachable list) { Draw.rect(topRegion, plan.drawx(), plan.drawy()); } - @Override - public TextureRegion[] icons() { - return new TextureRegion[]{bottomRegion, region}; - } + @Override + public TextureRegion[] icons(){ + return new TextureRegion[]{bottomRegion, region}; + } - @Override - public void init() { - super.init(); + @Override + public void init(){ + super.init(); - if (pressureConfig.fluidGroup == null) pressureConfig.fluidGroup = FluidGroup.transportation; - } + if(pressureConfig.fluidGroup == null) pressureConfig.fluidGroup = FluidGroup.transportation; + } - @Override - public void load() { - super.load(); - tiles = OlUtils.split(name + "-tiles", 32, 0); - valveRegion = Core.atlas.find(name + "-valve"); - topRegion = Core.atlas.find(name + "-top"); - bottomRegion = Core.atlas.find(name + "-bottom", "omaloon-liquid-bottom"); + @Override + public void load(){ + super.load(); + tiles = OlUtils.split(name + "-tiles", 32, 0); + valveRegion = Core.atlas.find(name + "-valve"); + topRegion = Core.atlas.find(name + "-top"); + bottomRegion = Core.atlas.find(name + "-bottom", "omaloon-liquid-bottom"); liquidRegions = new TextureRegion[2][animationFrames]; - if (renderer != null) { + if(renderer != null){ var frames = renderer.getFluidFrames(); - for (int fluid = 0; fluid < 2; fluid++) { - for (int frame = 0; frame < animationFrames; frame++) { + for(int fluid = 0; fluid < 2; fluid++){ + for(int frame = 0; frame < animationFrames; frame++){ TextureRegion base = frames[fluid][frame]; TextureRegion result = new TextureRegion(); result.set(base); @@ -120,143 +120,143 @@ public void load() { } @Override - public void setBars() { + public void setBars(){ super.setBars(); pressureConfig.addBars(this); } @Override - public void setStats() { + public void setStats(){ super.setStats(); pressureConfig.addStats(stats); stats.add(OlStats.pressureFlow, Mathf.round(pressureLoss * 60f, 2), OlStats.pressureSecond); } - public class PressureLiquidValveBuild extends Building implements HasPressureImpl { - - public float draining; - public float effectInterval; - public int tiling; - public float smoothAlpha; - - public boolean jammed; - - @Override - public boolean acceptsPressurizedFluid(HasPressure from, @Nullable Liquid liquid, float amount) { - return HasPressureImpl.super.acceptsPressurizedFluid(from, liquid, amount) && (liquid == pressure.getMain() || liquid == null || pressure.getMain() == null || from.pressure().getMain() == null); - } - - @Override - public boolean connects(HasPressure to) { - return HasPressureImpl.super.connects(to) && to instanceof PressureLiquidValveBuild ? - (front() == to || back() == to) && (to.front() == this || to.back() == this) : - (front() == to || back() == to); - } - - @Override - public void draw() { - float rot = rotate ? (90 + rotdeg()) % 180 - 90 : 0; - Draw.rect(bottomRegion, x, y, rotation); - Liquid main = pressure.getMain(); - - smoothAlpha = Mathf.approachDelta(smoothAlpha, main == null ? 0f : pressure.liquids[main.id]/(pressure.liquids[main.id] + pressure.air), PressureModule.smoothingSpeed); - - if (smoothAlpha > 0.01f) { - int frame = pressure.current.getAnimationFrame(); - int gas = pressure.current.gas ? 1 : 0; - - float xscl = Draw.xscl, yscl = Draw.yscl; - Draw.scl(1f, 1f); - Drawf.liquid(liquidRegions[gas][frame], x, y, Mathf.clamp(smoothAlpha), pressure.current.color.write(Tmp.c1).a(1f)); - Draw.scl(xscl, yscl); - } - Draw.rect(tiles[tiling], x, y, rot); - Draw.rect(topRegion, x, y); - Draw.rect(valveRegion, x, y, draining * (rotation % 2 == 0 ? -90f : 90f) + rot); - } - - @Override - public void onProximityUpdate() { - super.onProximityUpdate(); - - tiling = 0; - boolean inverted = rotation == 1 || rotation == 2; - if (front() instanceof HasPressure front && connected(front)) tiling |= inverted ? 2 : 1; - if (back() instanceof HasPressure back && connected(back)) tiling |= inverted ? 1 : 2; - } - - @Override - public boolean outputsPressurizedFluid(HasPressure to, Liquid liquid, float amount) { - return HasPressureImpl.super.outputsPressurizedFluid(to, liquid, amount) && (liquid == to.pressure().getMain() || liquid == null || pressure.getMain() == null || to.pressure().getMain() == null); - } - - @Override - public void read(Reads read, byte revision) { - super.read(read, revision); - jammed = read.bool(); - draining = read.f(); - smoothAlpha = read.f(); - } - - @Override - public void updatePressure() { - HasPressureImpl.super.updatePressure(); - - float pressureAmount = pressure.getPressure(pressure.getMain()); - - if (pressureAmount > jamPoint) jammed = false; - if (jammed) return; - if (pressureAmount < openMin) { - effectInterval += delta(); - addFluid(null, Math.min(openMin - pressureAmount, OlMath.flowRate( - 0, - pressureAmount, - 5, - pressureConfig.fluidCapacity, - OlLiquids.getDensity(null), - OlLiquids.getViscosity(null) - ))); - draining = Mathf.approachDelta(draining, 1, 0.014f); - } - if (pressureAmount > openMax) { - effectInterval += delta(); - removeFluid(pressure.getMain(), Math.min(pressureAmount - openMax, OlMath.flowRate( - pressureAmount, - 0, - pressureConfig.fluidCapacity, - 5, - OlLiquids.getDensity(null), - OlLiquids.getViscosity(null) - ))); - draining = Mathf.approachDelta(draining, 1, 0.014f); - } - if (effectInterval > pumpingEffectInterval) { - effectInterval = 0; - if (pressureAmount > openMax) { - pumpingEffectOut.at(x, y, draining * (rotation % 2 == 0 ? -90f : 90f) + (rotate ? (90 + rotdeg()) % 180 - 90 : 0), pressure.getMain() == null ? Color.white : pressure.getMain().color); - } else { - pumpingEffectIn.at(x, y, draining * (rotation % 2 == 0 ? -90f : 90f) + (rotate ? (90 + rotdeg()) % 180 - 90 : 0)); - } - } - - if (pressureAmount >= openMin && pressureAmount <= openMax) { - draining = Mathf.approachDelta(draining, 0, 0.014f); - } - - if (pressureAmount < jamPoint) { - jammed = true; - draining = 0f; - jamEffect.at(x, y, draining * (rotation%2 == 0 ? -90 : 90) + (rotate ? (90 + rotdeg()) % 180 - 90 : 0), valveRegion); - jamSound.at(x, y); - } - } - - @Override - public void write(Writes write) { - super.write(write); - write.bool(jammed); - write.f(draining); - write.f(smoothAlpha); - } - } + public class PressureLiquidValveBuild extends Building implements HasPressureImpl{ + + public float draining; + public float effectInterval; + public int tiling; + public float smoothAlpha; + + public boolean jammed; + + @Override + public boolean acceptsPressurizedFluid(HasPressure from, @Nullable Liquid liquid, float amount){ + return HasPressureImpl.super.acceptsPressurizedFluid(from, liquid, amount) && (liquid == pressure.getMain() || liquid == null || pressure.getMain() == null || from.pressure().getMain() == null); + } + + @Override + public boolean connects(HasPressure to){ + return HasPressureImpl.super.connects(to) && to instanceof PressureLiquidValveBuild ? + (front() == to || back() == to) && (to.front() == this || to.back() == this) : + (front() == to || back() == to); + } + + @Override + public void draw(){ + float rot = rotate ? (90 + rotdeg()) % 180 - 90 : 0; + Draw.rect(bottomRegion, x, y, rotation); + Liquid main = pressure.getMain(); + + smoothAlpha = Mathf.approachDelta(smoothAlpha, main == null ? 0f : pressure.liquids[main.id] / (pressure.liquids[main.id] + pressure.air), PressureModule.smoothingSpeed); + + if(smoothAlpha > 0.01f){ + int frame = pressure.current.getAnimationFrame(); + int gas = pressure.current.gas ? 1 : 0; + + float xscl = Draw.xscl, yscl = Draw.yscl; + Draw.scl(1f, 1f); + Drawf.liquid(liquidRegions[gas][frame], x, y, Mathf.clamp(smoothAlpha), pressure.current.color.write(Tmp.c1).a(1f)); + Draw.scl(xscl, yscl); + } + Draw.rect(tiles[tiling], x, y, rot); + Draw.rect(topRegion, x, y); + Draw.rect(valveRegion, x, y, draining * (rotation % 2 == 0 ? -90f : 90f) + rot); + } + + @Override + public void onProximityUpdate(){ + super.onProximityUpdate(); + + tiling = 0; + boolean inverted = rotation == 1 || rotation == 2; + if(front() instanceof HasPressure front && connected(front)) tiling |= inverted ? 2 : 1; + if(back() instanceof HasPressure back && connected(back)) tiling |= inverted ? 1 : 2; + } + + @Override + public boolean outputsPressurizedFluid(HasPressure to, Liquid liquid, float amount){ + return HasPressureImpl.super.outputsPressurizedFluid(to, liquid, amount) && (liquid == to.pressure().getMain() || liquid == null || pressure.getMain() == null || to.pressure().getMain() == null); + } + + @Override + public void read(Reads read, byte revision){ + super.read(read, revision); + jammed = read.bool(); + draining = read.f(); + smoothAlpha = read.f(); + } + + @Override + public void updatePressure(){ + HasPressureImpl.super.updatePressure(); + + float pressureAmount = pressure.getPressure(pressure.getMain()); + + if(pressureAmount > jamPoint) jammed = false; + if(jammed) return; + if(pressureAmount < openMin){ + effectInterval += delta(); + addFluid(null, Math.min(openMin - pressureAmount, OlMath.flowRate( + 0, + pressureAmount, + 5, + pressureConfig.fluidCapacity, + OlLiquids.getDensity(null), + OlLiquids.getViscosity(null) + ))); + draining = Mathf.approachDelta(draining, 1, 0.014f); + } + if(pressureAmount > openMax){ + effectInterval += delta(); + removeFluid(pressure.getMain(), Math.min(pressureAmount - openMax, OlMath.flowRate( + pressureAmount, + 0, + pressureConfig.fluidCapacity, + 5, + OlLiquids.getDensity(null), + OlLiquids.getViscosity(null) + ))); + draining = Mathf.approachDelta(draining, 1, 0.014f); + } + if(effectInterval > pumpingEffectInterval){ + effectInterval = 0; + if(pressureAmount > openMax){ + pumpingEffectOut.at(x, y, draining * (rotation % 2 == 0 ? -90f : 90f) + (rotate ? (90 + rotdeg()) % 180 - 90 : 0), pressure.getMain() == null ? Color.white : pressure.getMain().color); + }else{ + pumpingEffectIn.at(x, y, draining * (rotation % 2 == 0 ? -90f : 90f) + (rotate ? (90 + rotdeg()) % 180 - 90 : 0)); + } + } + + if(pressureAmount >= openMin && pressureAmount <= openMax){ + draining = Mathf.approachDelta(draining, 0, 0.014f); + } + + if(pressureAmount < jamPoint){ + jammed = true; + draining = 0f; + jamEffect.at(x, y, draining * (rotation % 2 == 0 ? -90 : 90) + (rotate ? (90 + rotdeg()) % 180 - 90 : 0), valveRegion); + jamSound.at(x, y); + } + } + + @Override + public void write(Writes write){ + super.write(write); + write.bool(jammed); + write.f(draining); + write.f(smoothAlpha); + } + } } diff --git a/src/omaloon/world/blocks/power/ImpulseNode.java b/src/omaloon/world/blocks/power/ImpulseNode.java index b8d78af6..dabf0667 100644 --- a/src/omaloon/world/blocks/power/ImpulseNode.java +++ b/src/omaloon/world/blocks/power/ImpulseNode.java @@ -5,23 +5,23 @@ import arc.math.*; import arc.math.geom.*; import arc.struct.*; -import mindustry.Vars; +import mindustry.*; import mindustry.content.*; import mindustry.core.*; import mindustry.entities.*; import mindustry.gen.*; import mindustry.graphics.*; -import mindustry.world.Tile; +import mindustry.world.*; import mindustry.world.blocks.power.*; import static mindustry.Vars.*; -public class ImpulseNode extends PowerNode { +public class ImpulseNode extends PowerNode{ public int effectTimer = timers++; public float effectTime = 20; - public ImpulseNode(String name) { + public ImpulseNode(String name){ super(name); } @@ -46,21 +46,21 @@ public void draw(){ Draw.alpha(Renderer.laserOpacity / 2f); drawLaser(x, y, link.x, link.y, size, link.block.size); - if(timer.get(effectTimer, effectTime) && power.graph.getSatisfaction() > 0) { - for (int l = 0; l < power.links.size; l++) { + if(timer.get(effectTimer, effectTime) && power.graph.getSatisfaction() > 0){ + for(int l = 0; l < power.links.size; l++){ Tile otherTile = Vars.world.tile(power.links.get(l)); - if (otherTile != null) { + if(otherTile != null){ Building other = otherTile.build; - if (other != null) { + if(other != null){ float angle1 = Angles.angle(x, y, other.x, other.y), - vx = Mathf.cosDeg(angle1), vy = Mathf.sinDeg(angle1), - len1 = size * tilesize / 2f - 1.5f, len2 = other.block.size * tilesize / 2f - 1.5f; - - lightning(x + vx * len1, y + vy * len1, - other.x - vx * len2, other.y - vy * len2, - 2, Mathf.random(-8f, 8f), - laserColor2.cpy().lerp(laserColor1, power.graph.getSatisfaction()).a(Renderer.laserOpacity), - Fx.lightning.layer(Layer.power)); + vx = Mathf.cosDeg(angle1), vy = Mathf.sinDeg(angle1), + len1 = size * tilesize / 2f - 1.5f, len2 = other.block.size * tilesize / 2f - 1.5f; + + lightning(x + vx * len1, y + vy * len1, + other.x - vx * len2, other.y - vy * len2, + 2, Mathf.random(-8f, 8f), + laserColor2.cpy().lerp(laserColor1, power.graph.getSatisfaction()).a(Renderer.laserOpacity), + Fx.lightning.layer(Layer.power)); } } } @@ -73,18 +73,18 @@ public void draw(){ /** * Original code from Project HPL[...] */ - public void lightning(float x1, float y1, float x2, float y2, int iterations, float rndScale, Color c, Effect e) { + public void lightning(float x1, float y1, float x2, float y2, int iterations, float rndScale, Color c, Effect e){ Seq lines = new Seq<>(); boolean swap = Math.abs(y1 - y2) < Math.abs(x1 - x2); - if(swap) { + if(swap){ lines.add(new Vec2(y1, x1)); lines.add(new Vec2(y2, x2)); - } else { + }else{ lines.add(new Vec2(x1, y1)); lines.add(new Vec2(x2, y2)); } - for (int i = 0; i < iterations; i++) { - for (int j = 0; j < lines.size - 1; j += 2) { + for(int i = 0; i < iterations; i++){ + for(int j = 0; j < lines.size - 1; j += 2){ Vec2 v1 = lines.get(j), v2 = lines.get(j + 1); Vec2 v = new Vec2((v1.x + v2.x) / 2, ((v1.y + v2.y) / 2)); float ang = (v2.angle(v1) + 90f) * Mathf.degRad; @@ -95,8 +95,8 @@ public void lightning(float x1, float y1, float x2, float y2, int iterations, fl lines.insert(j + 1, v); } } - if(swap) { - for(int i = 0; i < lines.size; i++) { + if(swap){ + for(int i = 0; i < lines.size; i++){ Vec2 v = lines.get(i); float px = v.x; v.x = v.y; diff --git a/src/omaloon/world/blocks/power/WindGenerator.java b/src/omaloon/world/blocks/power/WindGenerator.java index 7a250ce7..d3e6603e 100644 --- a/src/omaloon/world/blocks/power/WindGenerator.java +++ b/src/omaloon/world/blocks/power/WindGenerator.java @@ -11,12 +11,11 @@ import mindustry.gen.*; import mindustry.graphics.*; import mindustry.input.*; -import mindustry.type.weather.*; import mindustry.world.*; import mindustry.world.blocks.power.*; import mindustry.world.meta.*; import omaloon.graphics.*; -import omaloon.type.weather.EffectWeather; +import omaloon.type.weather.*; import static mindustry.Vars.*; @@ -24,7 +23,7 @@ public class WindGenerator extends PowerGenerator{ public int spacing = 9; public float boostWeather = 0.25f; public float baseRotateSpeed = 4f; - public float rotChangeTime = Mathf.randomSeed(id,80.0f, 300.0f); + public float rotChangeTime = Mathf.randomSeed(id, 80.0f, 300.0f); public WindGenerator(String name){ super(name); @@ -47,10 +46,10 @@ public void drawOverlay(float x, float y, int rotation){ x -= size / 2f; y -= size / 2f; Drawm.dashPoly(size / 8f, Pal.accent, - x, y, - x + size, y, - x + size, y + size, - x, y + size); + x, y, + x + size, y, + x + size, y + size, + x, y + size); } @Override @@ -89,7 +88,7 @@ public boolean intersectsSpacing(int sx, int sy, int ox, int oy, int ext){ //TOD int sizeOffset = 1 - (size & 1); return ox >= sx + sizeOffset - spacingOffset && ox <= sx + spacingOffset && - oy >= sy + sizeOffset - spacingOffset && oy <= sy + spacingOffset; + oy >= sy + sizeOffset - spacingOffset && oy <= sy + spacingOffset; } public boolean intersectsSpacing(Tile self, Tile other){ diff --git a/src/omaloon/world/blocks/production/HammerDrill.java b/src/omaloon/world/blocks/production/HammerDrill.java index f0353f49..f1fc69da 100644 --- a/src/omaloon/world/blocks/production/HammerDrill.java +++ b/src/omaloon/world/blocks/production/HammerDrill.java @@ -9,12 +9,10 @@ import mindustry.gen.*; import mindustry.graphics.*; import mindustry.type.*; -import omaloon.annotations.Load; +import omaloon.annotations.*; import omaloon.content.*; -import static arc.Core.*; - -public class HammerDrill extends PressureDrill { +public class HammerDrill extends PressureDrill{ public float shake = 0.3f; public float invertedTime = 200f; public Sound drillSound = OlSounds.hammer; @@ -32,7 +30,7 @@ public HammerDrill(String name){ } @Override - public void drawPlanRegion(BuildPlan plan, Eachable list) { + public void drawPlanRegion(BuildPlan plan, Eachable list){ super.drawPlanRegion(plan, list); Draw.rect(hammerRegion, plan.drawx(), plan.drawy()); } @@ -47,7 +45,7 @@ public float getDrillTime(Item item){ return drillTime / drillMultipliers.get(item, 1f); } - public class HammerDrillBuild extends PressureDrillBuild { + public class HammerDrillBuild extends PressureDrillBuild{ public float smoothProgress = 0f; public float invertTime = 0f; @@ -106,13 +104,13 @@ public void updateTile(){ return; } - if(dominantItems > 0 && progress >= delay && items.total() < itemCapacity) { + if(dominantItems > 0 && progress >= delay && items.total() < itemCapacity){ offload(dominantItem); consume(); invertTime = 1f; progress %= delay; - if (wasVisible) { + if(wasVisible){ Effect.shake(shake, shake, this); drillSound.at(x, y, 1f + Mathf.range(drillSoundPitchRand), drillSoundVolume); drillEffect.at(x + Mathf.range(drillEffectRnd), y + Mathf.range(drillEffectRnd), dominantItem.color); diff --git a/src/omaloon/world/blocks/production/PressureCrafter.java b/src/omaloon/world/blocks/production/PressureCrafter.java index 2a269f3f..4333f148 100644 --- a/src/omaloon/world/blocks/production/PressureCrafter.java +++ b/src/omaloon/world/blocks/production/PressureCrafter.java @@ -1,112 +1,112 @@ package omaloon.world.blocks.production; import arc.util.*; -import arc.util.io.*; import mindustry.type.*; import mindustry.world.blocks.production.*; import mindustry.world.consumers.*; import mindustry.world.meta.*; import omaloon.world.interfaces.*; import omaloon.world.meta.*; -import omaloon.world.modules.*; - -public class PressureCrafter extends GenericCrafter { - public PressureConfig pressureConfig = new PressureConfig(); - - public boolean useConsumerMultiplier = true; - - /** - * Set this to false every time you want the outputs to use the pressure liquid system instead. - * Alternatively, creating ConsumeFluids with negative values for it's amount will work too. - */ - public boolean useVanillaLiquids = true; - - /** - * Internal variable used to output pressurized liquids, Do not modify manually. - */ - private @Nullable LiquidStack[] outputPressurizedLiquids; - - public float outputAir; - - public PressureCrafter(String name) { - super(name); - pressureConfig.isWhitelist = true; - } - - @Override - public void init() { - if (!useVanillaLiquids) { - outputPressurizedLiquids = outputLiquids; - outputLiquids = null; - } - - super.init(); - } - - @Override - public void setBars() { - super.setBars(); - pressureConfig.addBars(this); - } - - @Override - public void setStats() { - super.setStats(); - pressureConfig.addStats(stats); - - if(outputPressurizedLiquids != null) { - stats.add(Stat.output, StatValues.liquids(1f, outputPressurizedLiquids)); - } - if (outputAir > 0) { - stats.add(Stat.output, OlStats.fluid(null, outputAir, 1f, true)); - } - } - - public class PressureCrafterBuild extends GenericCrafterBuild implements HasPressureImpl { - public float efficiencyMultiplier() { - float val = 1; - if (!useConsumerMultiplier) return val; - for (Consume consumer : consumers) { - val *= consumer.efficiencyMultiplier(this); - } - return val; - } - - @Override public float efficiencyScale() { - return super.efficiencyScale() * efficiencyMultiplier(); - } - - @Override public float getProgressIncrease(float baseTime) { - return super.getProgressIncrease(baseTime) * efficiencyMultiplier(); - } - - @Override - public boolean shouldConsume() { - if(outputPressurizedLiquids != null && !ignoreLiquidFullness) { - boolean allFull = true; - if (pressure.get(null) >= pressureConfig.fluidCapacity - 0.001f) { - if (!dumpExtraLiquid) return false; - } else allFull = false; - for(var output : outputPressurizedLiquids) { - if(pressure.get(output.liquid) >= pressureConfig.fluidCapacity - 0.001f) { - if(!dumpExtraLiquid) return false; - } else allFull = false; - } - - //if there is no space left for any liquid, it can't reproduce - if(allFull) return false; - } - return super.shouldConsume(); - } - - @Override - public void updateTile() { - super.updateTile(); - if(efficiency > 0) { + +public class PressureCrafter extends GenericCrafter{ + public PressureConfig pressureConfig = new PressureConfig(); + + public boolean useConsumerMultiplier = true; + + /** + * Set this to false every time you want the outputs to use the pressure liquid system instead. + * Alternatively, creating ConsumeFluids with negative values for it's amount will work too. + */ + public boolean useVanillaLiquids = true; + + /** + * Internal variable used to output pressurized liquids, Do not modify manually. + */ + private @Nullable LiquidStack[] outputPressurizedLiquids; + + public float outputAir; + + public PressureCrafter(String name){ + super(name); + pressureConfig.isWhitelist = true; + } + + @Override + public void init(){ + if(!useVanillaLiquids){ + outputPressurizedLiquids = outputLiquids; + outputLiquids = null; + } + + super.init(); + } + + @Override + public void setBars(){ + super.setBars(); + pressureConfig.addBars(this); + } + + @Override + public void setStats(){ + super.setStats(); + pressureConfig.addStats(stats); + + if(outputPressurizedLiquids != null){ + stats.add(Stat.output, StatValues.liquids(1f, outputPressurizedLiquids)); + } + if(outputAir > 0){ + stats.add(Stat.output, OlStats.fluid(null, outputAir, 1f, true)); + } + } + + public class PressureCrafterBuild extends GenericCrafterBuild implements HasPressureImpl{ + public float efficiencyMultiplier(){ + float val = 1; + if(!useConsumerMultiplier) return val; + for(Consume consumer : consumers){ + val *= consumer.efficiencyMultiplier(this); + } + return val; + } + + @Override + public float efficiencyScale(){ + return super.efficiencyScale() * efficiencyMultiplier(); + } + + @Override + public float getProgressIncrease(float baseTime){ + return super.getProgressIncrease(baseTime) * efficiencyMultiplier(); + } + + @Override + public boolean shouldConsume(){ + if(outputPressurizedLiquids != null && !ignoreLiquidFullness){ + boolean allFull = true; + if(pressure.get(null) >= pressureConfig.fluidCapacity - 0.001f){ + if(!dumpExtraLiquid) return false; + }else allFull = false; + for(var output : outputPressurizedLiquids){ + if(pressure.get(output.liquid) >= pressureConfig.fluidCapacity - 0.001f){ + if(!dumpExtraLiquid) return false; + }else allFull = false; + } + + //if there is no space left for any liquid, it can't reproduce + if(allFull) return false; + } + return super.shouldConsume(); + } + + @Override + public void updateTile(){ + super.updateTile(); + if(efficiency > 0){ float inc = getProgressIncrease(1f); - if (outputPressurizedLiquids != null) for(var output : outputPressurizedLiquids) addFluid(output.liquid, output.amount * inc); - if (outputAir > 0) addFluid(null, outputAir * inc); + if(outputPressurizedLiquids != null) for(var output : outputPressurizedLiquids) addFluid(output.liquid, output.amount * inc); + if(outputAir > 0) addFluid(null, outputAir * inc); } - } - } + } + } } diff --git a/src/omaloon/world/blocks/production/PressureDrill.java b/src/omaloon/world/blocks/production/PressureDrill.java index 5de5bf3e..1d5fc426 100644 --- a/src/omaloon/world/blocks/production/PressureDrill.java +++ b/src/omaloon/world/blocks/production/PressureDrill.java @@ -1,58 +1,58 @@ package omaloon.world.blocks.production; -import arc.util.io.*; import mindustry.world.blocks.production.*; import mindustry.world.consumers.*; import omaloon.world.interfaces.*; import omaloon.world.meta.*; -import omaloon.world.modules.*; - -public class PressureDrill extends Drill { - public PressureConfig pressureConfig = new PressureConfig(); - - public boolean useConsumerMultiplier = true; - - public PressureDrill(String name) { - super(name); - pressureConfig.isWhitelist = true; - } - - @Override - public void init() { - super.init(); - - if (pressureConfig.fluidGroup == null) pressureConfig.fluidGroup = FluidGroup.drills; - } - - @Override - public void setBars() { - super.setBars(); - pressureConfig.addBars(this); - } - - @Override - public void setStats() { - super.setStats(); - pressureConfig.addStats(stats); - } - - public class PressureDrillBuild extends DrillBuild implements HasPressureImpl { - - public float efficiencyMultiplier() { - float val = 1; - if (!useConsumerMultiplier) return val; - for (Consume consumer : consumers) { - val *= consumer.efficiencyMultiplier(this); - } - return val; - } - - @Override public float efficiencyScale() { - return super.efficiencyScale() * efficiencyMultiplier(); - } - - @Override public float getProgressIncrease(float baseTime) { - return super.getProgressIncrease(baseTime) * efficiencyMultiplier(); - } - } + +public class PressureDrill extends Drill{ + public PressureConfig pressureConfig = new PressureConfig(); + + public boolean useConsumerMultiplier = true; + + public PressureDrill(String name){ + super(name); + pressureConfig.isWhitelist = true; + } + + @Override + public void init(){ + super.init(); + + if(pressureConfig.fluidGroup == null) pressureConfig.fluidGroup = FluidGroup.drills; + } + + @Override + public void setBars(){ + super.setBars(); + pressureConfig.addBars(this); + } + + @Override + public void setStats(){ + super.setStats(); + pressureConfig.addStats(stats); + } + + public class PressureDrillBuild extends DrillBuild implements HasPressureImpl{ + + public float efficiencyMultiplier(){ + float val = 1; + if(!useConsumerMultiplier) return val; + for(Consume consumer : consumers){ + val *= consumer.efficiencyMultiplier(this); + } + return val; + } + + @Override + public float efficiencyScale(){ + return super.efficiencyScale() * efficiencyMultiplier(); + } + + @Override + public float getProgressIncrease(float baseTime){ + return super.getProgressIncrease(baseTime) * efficiencyMultiplier(); + } + } } diff --git a/src/omaloon/world/blocks/sandbox/PressureLiquidSource.java b/src/omaloon/world/blocks/sandbox/PressureLiquidSource.java index a8e7b099..2e8c997f 100644 --- a/src/omaloon/world/blocks/sandbox/PressureLiquidSource.java +++ b/src/omaloon/world/blocks/sandbox/PressureLiquidSource.java @@ -10,7 +10,6 @@ import arc.scene.ui.layout.*; import arc.util.*; import arc.util.io.*; -import asmlib.annotations.DebugAST; import mindustry.*; import mindustry.entities.units.*; import mindustry.gen.*; @@ -18,187 +17,182 @@ import mindustry.ui.*; import mindustry.world.*; import mindustry.world.blocks.liquid.*; -import omaloon.annotations.AutoImplement; -import omaloon.content.*; -import omaloon.ui.elements.*; -import mindustry.world.*; -import mindustry.world.blocks.liquid.*; +import omaloon.annotations.*; import omaloon.content.*; import omaloon.ui.elements.*; import omaloon.world.interfaces.*; import omaloon.world.meta.*; -import omaloon.world.modules.*; - -public class PressureLiquidSource extends Block { - public PressureConfig pressureConfig = new PressureConfig(); - - public TextureRegion bottomRegion; - - public PressureLiquidSource(String name) { - super(name); - solid = true; - destructible = true; - update = true; - configurable = true; - saveConfig = copyConfig = true; - - config(SourceEntry.class, (PressureLiquidSourceBuild build, SourceEntry entry) -> { - build.liquid = entry.fluid == null ? -1 : entry.fluid.id; - build.targetAmount = entry.amount; - - Vars.content.liquids().each(liquid -> { - build.pressure.liquids[liquid.id] = 0; - build.pressure.pressures[liquid.id] = 0; - }); - - build.pressure.air = build.pressure.pressure = 0; - }); - } - - @Override - public void drawPlanConfig(BuildPlan plan, Eachable list) { - Draw.rect(bottomRegion, plan.drawx(), plan.drawy()); - if (plan.config instanceof SourceEntry e && e.fluid != null) LiquidBlock.drawTiledFrames(size, plan.drawx(), plan.drawy(), 0f, e.fluid, 1f); - Draw.rect(region, plan.drawx(), plan.drawy()); - } - - @Override - public void load() { - super.load(); - bottomRegion = Core.atlas.find(name + "-bottom"); - } - - @Override - protected TextureRegion[] icons() { - return new TextureRegion[]{bottomRegion, region}; - } - - @Override - public void init() { - super.init(); - - if (pressureConfig.fluidGroup != null) pressureConfig.fluidGroup = FluidGroup.transportation; - } - - @Override - public void setBars() { - super.setBars(); - pressureConfig.addBars(this); - addBar("pressure", entity -> { - HasPressure build = (HasPressure)entity; - - return new CenterBar( - () -> Core.bundle.get("bar.pressure") + (build.pressure().getPressure(build.pressure().getMain()) < 0 ? "-" : "+") + Strings.autoFixed(Math.abs(build.pressure().getPressure(build.pressure().getMain())), 2), - () -> Color.white, - () -> Mathf.map(build.pressure().getPressure(build.pressure().getMain()), pressureConfig.minPressure, pressureConfig.maxPressure, -1, 1) - ); - }); - } - - public class PressureLiquidSourceBuild extends Building implements HasPressureImpl { - - public int liquid = -1; - public float targetAmount; - - @Override - public boolean acceptsPressurizedFluid(HasPressure from, Liquid liquid, float amount) { - return HasPressureImpl.super.acceptsPressurizedFluid(from, liquid, amount) && liquid == Vars.content.liquid(this.liquid); - } - - @Override - public void buildConfiguration(Table cont) { - cont.table(Styles.black6, table -> { - table.pane(Styles.smallPane, liquids -> Vars.content.liquids().each(liquid -> { - Button button = liquids.button( - new TextureRegionDrawable(liquid.uiIcon), - new ImageButtonStyle() {{ - over = Styles.flatOver; - down = checked = Tex.flatDownBase; - }}, () -> { - if (this.liquid != liquid.id) { - configure(new SourceEntry() {{ - fluid = liquid; - amount = targetAmount; - }}); - } else { - configure(new SourceEntry() {{ - fluid = null; - amount = targetAmount; - }}); - } - } - ).tooltip(liquid.localizedName).size(40f).get(); - button.update(() -> button.setChecked(liquid.id == this.liquid)); - if ((Vars.content.liquids().indexOf(liquid) + 1) % 4 == 0) liquids.row(); - })).maxHeight(160f).row(); - table.add("@filter.option.amount").padTop(5f).padBottom(5f).row(); - table.field( - "" + targetAmount, - (field, c) -> Character.isDigit(c) || ((!field.getText().contains(".")) && c == '.') || (field.getText().isEmpty() && c == '-'), - s -> configure(new SourceEntry() {{ - fluid = Vars.content.liquid(liquid); - amount = Strings.parseFloat(s, 0f); - }}) - ); - }).margin(5f); - } - - @Override - public SourceEntry config() { - return new SourceEntry() {{ - fluid = Vars.content.liquid(liquid); - amount = targetAmount; - }}; - } - - @Override - public void draw() { - Draw.rect(bottomRegion, x, y); - - if(liquid != -1) { - LiquidBlock.drawTiledFrames(size, x, y, 0f, Vars.content.liquid(liquid), 1f); - } - - Draw.rect(region, x, y); - } - - @Override - public boolean outputsPressurizedFluid(HasPressure to, Liquid liquid, float amount) { - return HasPressureImpl.super.outputsPressurizedFluid(to, liquid, amount) && liquid == Vars.content.liquid(this.liquid); - } - - @Override - public void read(Reads read, byte revision) { - super.read(read, revision); - liquid = read.i(); - if (Vars.content.liquid(liquid) == null) liquid = -1; - targetAmount = read.f(); - } - - @Override - @AutoImplement.NoInject(HasPressureImpl.class) - public void updateTile() { - pressure.section.updateTransfer(); - - pressure.air = Vars.content.liquid(liquid) == null ? targetAmount : 0; - pressure.pressure = pressure.air / pressureConfig.fluidCapacity * OlLiquids.getDensity(null); - Vars.content.liquids().each(liq -> { - pressure.liquids[liq.id] = liq.id == liquid ? Mathf.maxZero(targetAmount) : 0; - pressure.pressures[liq.id] = pressure.liquids[liq.id] / pressureConfig.fluidCapacity * OlLiquids.getDensity(liq); - }); - } - - @Override - public void write(Writes write) { - super.write(write); - write.i(liquid); - write.f(targetAmount); - } - } - - - public static class SourceEntry { - public @Nullable Liquid fluid; - public float amount; - } + +public class PressureLiquidSource extends Block{ + public PressureConfig pressureConfig = new PressureConfig(); + + public TextureRegion bottomRegion; + + public PressureLiquidSource(String name){ + super(name); + solid = true; + destructible = true; + update = true; + configurable = true; + saveConfig = copyConfig = true; + + config(SourceEntry.class, (PressureLiquidSourceBuild build, SourceEntry entry) -> { + build.liquid = entry.fluid == null ? -1 : entry.fluid.id; + build.targetAmount = entry.amount; + + Vars.content.liquids().each(liquid -> { + build.pressure.liquids[liquid.id] = 0; + build.pressure.pressures[liquid.id] = 0; + }); + + build.pressure.air = build.pressure.pressure = 0; + }); + } + + @Override + public void drawPlanConfig(BuildPlan plan, Eachable list){ + Draw.rect(bottomRegion, plan.drawx(), plan.drawy()); + if(plan.config instanceof SourceEntry e && e.fluid != null) LiquidBlock.drawTiledFrames(size, plan.drawx(), plan.drawy(), 0f, e.fluid, 1f); + Draw.rect(region, plan.drawx(), plan.drawy()); + } + + @Override + public void load(){ + super.load(); + bottomRegion = Core.atlas.find(name + "-bottom"); + } + + @Override + protected TextureRegion[] icons(){ + return new TextureRegion[]{bottomRegion, region}; + } + + @Override + public void init(){ + super.init(); + + if(pressureConfig.fluidGroup != null) pressureConfig.fluidGroup = FluidGroup.transportation; + } + + @Override + public void setBars(){ + super.setBars(); + pressureConfig.addBars(this); + addBar("pressure", entity -> { + HasPressure build = (HasPressure)entity; + + return new CenterBar( + () -> Core.bundle.get("bar.pressure") + (build.pressure().getPressure(build.pressure().getMain()) < 0 ? "-" : "+") + Strings.autoFixed(Math.abs(build.pressure().getPressure(build.pressure().getMain())), 2), + () -> Color.white, + () -> Mathf.map(build.pressure().getPressure(build.pressure().getMain()), pressureConfig.minPressure, pressureConfig.maxPressure, -1, 1) + ); + }); + } + + public class PressureLiquidSourceBuild extends Building implements HasPressureImpl{ + + public int liquid = -1; + public float targetAmount; + + @Override + public boolean acceptsPressurizedFluid(HasPressure from, Liquid liquid, float amount){ + return HasPressureImpl.super.acceptsPressurizedFluid(from, liquid, amount) && liquid == Vars.content.liquid(this.liquid); + } + + @Override + public void buildConfiguration(Table cont){ + cont.table(Styles.black6, table -> { + table.pane(Styles.smallPane, liquids -> Vars.content.liquids().each(liquid -> { + Button button = liquids.button( + new TextureRegionDrawable(liquid.uiIcon), + new ImageButtonStyle(){{ + over = Styles.flatOver; + down = checked = Tex.flatDownBase; + }}, () -> { + if(this.liquid != liquid.id){ + configure(new SourceEntry(){{ + fluid = liquid; + amount = targetAmount; + }}); + }else{ + configure(new SourceEntry(){{ + fluid = null; + amount = targetAmount; + }}); + } + } + ).tooltip(liquid.localizedName).size(40f).get(); + button.update(() -> button.setChecked(liquid.id == this.liquid)); + if((Vars.content.liquids().indexOf(liquid) + 1) % 4 == 0) liquids.row(); + })).maxHeight(160f).row(); + table.add("@filter.option.amount").padTop(5f).padBottom(5f).row(); + table.field( + "" + targetAmount, + (field, c) -> Character.isDigit(c) || ((!field.getText().contains(".")) && c == '.') || (field.getText().isEmpty() && c == '-'), + s -> configure(new SourceEntry(){{ + fluid = Vars.content.liquid(liquid); + amount = Strings.parseFloat(s, 0f); + }}) + ); + }).margin(5f); + } + + @Override + public SourceEntry config(){ + return new SourceEntry(){{ + fluid = Vars.content.liquid(liquid); + amount = targetAmount; + }}; + } + + @Override + public void draw(){ + Draw.rect(bottomRegion, x, y); + + if(liquid != -1){ + LiquidBlock.drawTiledFrames(size, x, y, 0f, Vars.content.liquid(liquid), 1f); + } + + Draw.rect(region, x, y); + } + + @Override + public boolean outputsPressurizedFluid(HasPressure to, Liquid liquid, float amount){ + return HasPressureImpl.super.outputsPressurizedFluid(to, liquid, amount) && liquid == Vars.content.liquid(this.liquid); + } + + @Override + public void read(Reads read, byte revision){ + super.read(read, revision); + liquid = read.i(); + if(Vars.content.liquid(liquid) == null) liquid = -1; + targetAmount = read.f(); + } + + @Override + @AutoImplement.NoInject(HasPressureImpl.class) + public void updateTile(){ + pressure.section.updateTransfer(); + + pressure.air = Vars.content.liquid(liquid) == null ? targetAmount : 0; + pressure.pressure = pressure.air / pressureConfig.fluidCapacity * OlLiquids.getDensity(null); + Vars.content.liquids().each(liq -> { + pressure.liquids[liq.id] = liq.id == liquid ? Mathf.maxZero(targetAmount) : 0; + pressure.pressures[liq.id] = pressure.liquids[liq.id] / pressureConfig.fluidCapacity * OlLiquids.getDensity(liq); + }); + } + + @Override + public void write(Writes write){ + super.write(write); + write.i(liquid); + write.f(targetAmount); + } + } + + + public static class SourceEntry{ + public @Nullable Liquid fluid; + public float amount; + } } diff --git a/src/omaloon/world/blocks/sandbox/PressureLiquidVoid.java b/src/omaloon/world/blocks/sandbox/PressureLiquidVoid.java index 551bec65..52b106ef 100644 --- a/src/omaloon/world/blocks/sandbox/PressureLiquidVoid.java +++ b/src/omaloon/world/blocks/sandbox/PressureLiquidVoid.java @@ -6,27 +6,27 @@ import omaloon.world.interfaces.*; import omaloon.world.meta.*; -public class PressureLiquidVoid extends LiquidVoid { - public PressureConfig pressureConfig = new PressureConfig(); +public class PressureLiquidVoid extends LiquidVoid{ + public PressureConfig pressureConfig = new PressureConfig(); - public PressureLiquidVoid(String name) { - super(name); - } + public PressureLiquidVoid(String name){ + super(name); + } - public class PressureLiquidVoidBuild extends LiquidVoidBuild implements HasPressureImpl { + public class PressureLiquidVoidBuild extends LiquidVoidBuild implements HasPressureImpl{ - @Override public boolean acceptLiquid(Building source, Liquid liquid) { - return enabled; - } + @Override + public boolean acceptLiquid(Building source, Liquid liquid){ + return enabled; + } - - @Override - public void updateTile() { - super.updateTile(); - pressure.pressure = 0f; - } - } + @Override + public void updateTile(){ + super.updateTile(); + pressure.pressure = 0f; + } + } } diff --git a/src/omaloon/world/blocks/storage/GlassmoreCoreBlock.java b/src/omaloon/world/blocks/storage/GlassmoreCoreBlock.java index a604c8f5..e2991116 100644 --- a/src/omaloon/world/blocks/storage/GlassmoreCoreBlock.java +++ b/src/omaloon/world/blocks/storage/GlassmoreCoreBlock.java @@ -8,14 +8,14 @@ import mindustry.graphics.*; import mindustry.world.blocks.storage.*; -public class GlassmoreCoreBlock extends CoreBlock { +public class GlassmoreCoreBlock extends CoreBlock{ public float spawnCooldown = 2f * 60f; - public GlassmoreCoreBlock(String name) { + public GlassmoreCoreBlock(String name){ super(name); } - public class DelayedSpawnCoreBuild extends CoreBuild { + public class DelayedSpawnCoreBuild extends CoreBuild{ public float timer = 0f; public boolean requested = false; public float heat, progress, time; @@ -24,26 +24,26 @@ public class DelayedSpawnCoreBuild extends CoreBuild { public boolean justSpawned = false; @Override - public void draw() { + public void draw(){ super.draw(); - if ((heat > 0.001f || animating) && !justSpawned) { + if((heat > 0.001f || animating) && !justSpawned){ drawRespawn(); } } @Override - public void updateTile() { + public void updateTile(){ super.updateTile(); - if (timer > 0) timer -= Time.delta; + if(timer > 0) timer -= Time.delta; - if (spawnPlayer != null || animating) { + if(spawnPlayer != null || animating){ heat = Mathf.lerpDelta(heat, 1f, 0.1f); time += Time.delta; progress += 1f / spawnCooldown * Time.delta; - if (progress >= 1f) { - if (spawnPlayer != null && spawnPlayer.dead()) { + if(progress >= 1f){ + if(spawnPlayer != null && spawnPlayer.dead()){ playerSpawn(tile, spawnPlayer); justSpawned = true; } @@ -51,20 +51,20 @@ public void updateTile() { spawnPlayer = null; requested = false; } - } else { + }else{ heat = Mathf.lerpDelta(heat, 0f, 0.1f); - if (justSpawned && heat <= 0.001f) { + if(justSpawned && heat <= 0.001f){ justSpawned = false; } } } @Override - public void requestSpawn(Player player) { - if (Vars.state.isEditor()){ + public void requestSpawn(Player player){ + if(Vars.state.isEditor()){ spawnPlayer = player; playerSpawn(tile, spawnPlayer); - } else if (!requested && player.dead() && !justSpawned) { + }else if(!requested && player.dead() && !justSpawned){ timer = spawnCooldown; requested = true; spawnPlayer = player; @@ -75,13 +75,13 @@ public void requestSpawn(Player player) { } } - void drawRespawn() { + void drawRespawn(){ Draw.color(Pal.darkMetal); Lines.stroke(2f * heat); Fill.poly(x, y, 4, 10f * heat); Draw.reset(); - if (spawnPlayer != null) { + if(spawnPlayer != null){ TextureRegion region = spawnPlayer.icon(); Draw.color(0f, 0f, 0f, 0.4f * progress); @@ -105,7 +105,7 @@ void drawRespawn() { Draw.color(Pal.darkMetal); Lines.line(x - len, y + oy, x + len, y + oy); - for (int i : Mathf.signs) { + for(int i : Mathf.signs){ Fill.tri(x + len * i, y + oy - Lines.getStroke() / 2f, x + len * i, y + oy + Lines.getStroke() / 2f, x + (len + Lines.getStroke() * heat) * i, y + oy); } diff --git a/src/omaloon/world/consumers/ConsumeFluid.java b/src/omaloon/world/consumers/ConsumeFluid.java index 78347d5a..09e361ad 100644 --- a/src/omaloon/world/consumers/ConsumeFluid.java +++ b/src/omaloon/world/consumers/ConsumeFluid.java @@ -10,110 +10,114 @@ import omaloon.world.interfaces.*; import omaloon.world.meta.*; -public class ConsumeFluid extends Consume { - /** - * Fluid used by this consumer, if null, air is used - */ - public @Nullable Liquid fluid; - /** - * Amount of fluid consumed, will always be positive if fluid isn't air. - */ - public float amount; - /** - * If true, fluid is consumed per tick and not per craft. - */ - public boolean continuous; +public class ConsumeFluid extends Consume{ + /** + * Fluid used by this consumer, if null, air is used + */ + public @Nullable Liquid fluid; + /** + * Amount of fluid consumed, will always be positive if fluid isn't air. + */ + public float amount; + /** + * If true, fluid is consumed per tick and not per craft. + */ + public boolean continuous; - /** - * Min pressure required for this consumer to function. - */ - public float startRange; - /** - * Max pressure allowed for this consumer to function. - */ - public float endRange; - /** - * Efficiency multiplier of this consumer. Based on pressure. - */ - public float efficiencyMultiplier = 1f; - /** - * Pressure whose building's efficiency is at it's peak. - */ - public float optimalPressure; - /** - * Whether to display the optimal pressure. - */ - public boolean hasOptimalPressure = false; - /** - * Interpolation curve used to determine efficiency. 0 is startRange, 1 is endRange. - */ - public Interp curve = Interp.one; + /** + * Min pressure required for this consumer to function. + */ + public float startRange; + /** + * Max pressure allowed for this consumer to function. + */ + public float endRange; + /** + * Efficiency multiplier of this consumer. Based on pressure. + */ + public float efficiencyMultiplier = 1f; + /** + * Pressure whose building's efficiency is at it's peak. + */ + public float optimalPressure; + /** + * Whether to display the optimal pressure. + */ + public boolean hasOptimalPressure = false; + /** + * Interpolation curve used to determine efficiency. 0 is startRange, 1 is endRange. + */ + public Interp curve = Interp.one; - public ConsumeFluid(@Nullable Liquid fluid, float amount) { - this.fluid = fluid; - this.amount = amount; - } + public ConsumeFluid(@Nullable Liquid fluid, float amount){ + this.fluid = fluid; + this.amount = amount; + } - public HasPressure cast(Building build) { - try { - return (HasPressure) build; - } catch(Exception e) { - throw new RuntimeException("This consumer should be used on a building that implements HasPressure", e); - } - } + public HasPressure cast(Building build){ + try{ + return (HasPressure)build; + }catch(Exception e){ + throw new RuntimeException("This consumer should be used on a building that implements HasPressure", e); + } + } - @Override - public void display(Stats stats) { - if (amount != 0) { - if (continuous) { - stats.add(amount > 0 ? Stat.input : Stat.output, OlStats.fluid(fluid, Math.abs(amount), 1f, true)); - } else { - stats.add(amount > 0 ? Stat.input : Stat.output, OlStats.fluid(fluid, Math.abs(amount), 60f, false)); - } - } + @Override + public void display(Stats stats){ + if(amount != 0){ + if(continuous){ + stats.add(amount > 0 ? Stat.input : Stat.output, OlStats.fluid(fluid, Math.abs(amount), 1f, true)); + }else{ + stats.add(amount > 0 ? Stat.input : Stat.output, OlStats.fluid(fluid, Math.abs(amount), 60f, false)); + } + } - if (startRange != endRange) { - stats.add( - OlStats.pressureRange, - Core.bundle.get("stat.omaloon-pressure-range.format"), - (startRange == 0 ? "" : (startRange > 0 ? "+" : "-")) + Strings.autoFixed(Math.abs(startRange), 2), - (endRange == 0 ? "" : (endRange > 0 ? "+" : "-")) + Strings.autoFixed(Math.abs(endRange), 2) - ); - if (hasOptimalPressure) stats.add( - OlStats.optimalPressure, - Core.bundle.get("stat.omaloon-optimal-pressure.format"), - (optimalPressure == 0 ? "" : (optimalPressure > 0 ? "+" : "-")) + Strings.autoFixed(Math.abs(optimalPressure), 2), - Strings.autoFixed(efficiencyMultiplier * 100f, 2) - ); - } - } + if(startRange != endRange){ + stats.add( + OlStats.pressureRange, + Core.bundle.get("stat.omaloon-pressure-range.format"), + (startRange == 0 ? "" : (startRange > 0 ? "+" : "-")) + Strings.autoFixed(Math.abs(startRange), 2), + (endRange == 0 ? "" : (endRange > 0 ? "+" : "-")) + Strings.autoFixed(Math.abs(endRange), 2) + ); + if(hasOptimalPressure) stats.add( + OlStats.optimalPressure, + Core.bundle.get("stat.omaloon-optimal-pressure.format"), + (optimalPressure == 0 ? "" : (optimalPressure > 0 ? "+" : "-")) + Strings.autoFixed(Math.abs(optimalPressure), 2), + Strings.autoFixed(efficiencyMultiplier * 100f, 2) + ); + } + } - @Override - public float efficiency(Building build) { - if (!shouldConsume(cast(build))) return 0f; - return 1f; - } - @Override - public float efficiencyMultiplier(Building build) { - if (!shouldConsume(cast(build))) return 0f; - return curve.apply(1f, efficiencyMultiplier, Mathf.clamp(Mathf.map(cast(build).pressure().getPressure(fluid), startRange, endRange, 0f, 1f))); + @Override + public float efficiency(Building build){ + if(!shouldConsume(cast(build))) return 0f; + return 1f; + } - } + @Override + public float efficiencyMultiplier(Building build){ + if(!shouldConsume(cast(build))) return 0f; + return curve.apply(1f, efficiencyMultiplier, Mathf.clamp(Mathf.map(cast(build).pressure().getPressure(fluid), startRange, endRange, 0f, 1f))); - public boolean shouldConsume(HasPressure build) { - if (fluid != null && amount > 0 && build.pressure().get(fluid) <= amount) return false; - if (startRange == endRange) return true; - return startRange <= build.pressure().getPressure(fluid) && build.pressure().getPressure(fluid) <= endRange && (fluid == null || build.pressure().liquids[fluid.id] > amount); - } + } - @Override public void trigger(Building build) { - if (!continuous && shouldConsume(cast(build))) { - cast(build).removeFluid(fluid, amount); - } - } - @Override public void update(Building build) { - if (continuous && shouldConsume(cast(build))) { - cast(build).removeFluid(fluid, amount * Time.delta); - } - } + public boolean shouldConsume(HasPressure build){ + if(fluid != null && amount > 0 && build.pressure().get(fluid) <= amount) return false; + if(startRange == endRange) return true; + return startRange <= build.pressure().getPressure(fluid) && build.pressure().getPressure(fluid) <= endRange && (fluid == null || build.pressure().liquids[fluid.id] > amount); + } + + @Override + public void trigger(Building build){ + if(!continuous && shouldConsume(cast(build))){ + cast(build).removeFluid(fluid, amount); + } + } + + @Override + public void update(Building build){ + if(continuous && shouldConsume(cast(build))){ + cast(build).removeFluid(fluid, amount * Time.delta); + } + } } diff --git a/src/omaloon/world/draw/Draw3dSpin.java b/src/omaloon/world/draw/Draw3dSpin.java index 70086a57..45d8f3c4 100644 --- a/src/omaloon/world/draw/Draw3dSpin.java +++ b/src/omaloon/world/draw/Draw3dSpin.java @@ -17,7 +17,7 @@ import mindustry.world.*; import mindustry.world.draw.*; -import static arc.Core.*; +import static arc.Core.graphics; @SuppressWarnings("UnusedReturnValue") public class Draw3dSpin extends DrawBlock{ @@ -32,12 +32,14 @@ public class Draw3dSpin extends DrawBlock{ public static final Seq runs = new Seq<>(); public static Cons proc; - public static void draw(Runnable run) { + public static void draw(Runnable run){ if(proc != null) proc.get(run); } - static { - proc = (run) -> {if(run != null) runs.add(run);}; + static{ + proc = (run) -> { + if(run != null) runs.add(run); + }; Events.run(Trigger.draw, () -> { shadowBuffer.resize(graphics.getWidth(), graphics.getHeight()); @@ -75,7 +77,7 @@ public static void draw(Runnable run) { public TextureRegion baseRegion, rotorRegion; public String baseSuffix, rotorSuffix; - public Draw3dSpin(String baseSuffix, String rotorSuffix) { + public Draw3dSpin(String baseSuffix, String rotorSuffix){ this.baseSuffix = baseSuffix; this.rotorSuffix = rotorSuffix; } @@ -163,8 +165,8 @@ public void draw(Building build){ float localDrawX = drawX, localDrawY = drawY; for(int i = halfRegionWidth; i >= -halfRegionWidth; i--){ - Draw3d.rect(transformation, rotorRegion, localDrawX - shadowElevation, localDrawY - shadowElevation, realWidth, realHeight, mainRotation); - Draw3d.rect(transformation, rotorRegion, localDrawX - shadowElevation, localDrawY - shadowElevation, realWidth, realHeight, subRotation); + Draw3d.rect(transformation, rotorRegion, localDrawX - shadowElevation, localDrawY - shadowElevation, realWidth, realHeight, mainRotation); + Draw3d.rect(transformation, rotorRegion, localDrawX - shadowElevation, localDrawY - shadowElevation, realWidth, realHeight, subRotation); localDrawX -= pixelOffset.x; localDrawY -= pixelOffset.y; } diff --git a/src/omaloon/world/draw/Drawo.java b/src/omaloon/world/draw/Drawo.java index adf33ce1..45504a3b 100644 --- a/src/omaloon/world/draw/Drawo.java +++ b/src/omaloon/world/draw/Drawo.java @@ -1,10 +1,9 @@ package omaloon.world.draw; -import arc.graphics.g2d.Draw; -import arc.graphics.g2d.TextureRegion; -import arc.math.Mathf; +import arc.graphics.g2d.*; +import arc.math.*; -public class Drawo { +public class Drawo{ public static void asymmetricSpinSprite(TextureRegion region, float x, float y, float r){ float a = Draw.getColor().a; r = Mathf.mod(r, 180f); diff --git a/src/omaloon/world/draw/Outliner.java b/src/omaloon/world/draw/Outliner.java index 65aba1dc..daa4d565 100644 --- a/src/omaloon/world/draw/Outliner.java +++ b/src/omaloon/world/draw/Outliner.java @@ -1,56 +1,50 @@ package omaloon.world.draw; -import arc.Core; +import arc.*; import arc.graphics.*; import arc.graphics.g2d.*; import mindustry.graphics.*; -public class Outliner { +public class Outliner{ /** @author MEEP of Faith#7277 */ - public static void outlineRegion(MultiPacker packer, TextureRegion textureRegion, String outputName) { + public static void outlineRegion(MultiPacker packer, TextureRegion textureRegion, String outputName){ outlineRegion(packer, textureRegion, Pal.darkerMetal, outputName, 3); } /** @author MEEP of Faith#7277 */ - public static void outlineRegion(MultiPacker packer, TextureRegion textureRegion, Color outlineColor, String outputName) { + public static void outlineRegion(MultiPacker packer, TextureRegion textureRegion, Color outlineColor, String outputName){ outlineRegion(packer, textureRegion, outlineColor, outputName, 3); } /** @author MEEP of Faith#7277 */ - public static void outlineRegion(MultiPacker packer, TextureRegion[] textures, Color outlineColor, String outputName) { + public static void outlineRegion(MultiPacker packer, TextureRegion[] textures, Color outlineColor, String outputName){ outlineRegion(packer, textures, outlineColor, outputName, 4); } /** * Outlines a list of regions. Run in createIcons. - * * @author MEEP of Faith#7277 */ - public static void outlineRegion(MultiPacker packer, TextureRegion[] textures, Color outlineColor, String outputName, int radius) { - for (int i = 0; i < textures.length; i++) { + public static void outlineRegion(MultiPacker packer, TextureRegion[] textures, Color outlineColor, String outputName, int radius){ + for(int i = 0; i < textures.length; i++){ outlineRegion(packer, textures[i], outlineColor, outputName + "-" + i, radius); } } /** * Outlines a given textureRegion. Run in createIcons. - * - * @param textureRegion - * The texture you want to generate outline with - * @param outlineColor - * The color1 of the outline, default is Pal.darkerMetal - * @param outputName - * The outline name - * @param outlineRadius - * The thiccness of the outline, default is 3 or 4 + * @param textureRegion The texture you want to generate outline with + * @param outlineColor The color1 of the outline, default is Pal.darkerMetal + * @param outputName The outline name + * @param outlineRadius The thiccness of the outline, default is 3 or 4 * @author MEEP of Faith#7277 */ - public static void outlineRegion(MultiPacker packer, TextureRegion textureRegion, Color outlineColor, String outputName, int outlineRadius) { - if (textureRegion == null) return; + public static void outlineRegion(MultiPacker packer, TextureRegion textureRegion, Color outlineColor, String outputName, int outlineRadius){ + if(textureRegion == null) return; PixmapRegion region = Core.atlas.getPixmap(textureRegion); Pixmap out = Pixmaps.outline(region, outlineColor, outlineRadius); - if (Core.settings.getBool("linear", true)) { + if(Core.settings.getBool("linear", true)){ Pixmaps.bleed(out); } packer.add(MultiPacker.PageType.main, outputName, out); diff --git a/src/omaloon/world/interfaces/HasPressure.java b/src/omaloon/world/interfaces/HasPressure.java index 604608c1..f1ba4f9a 100644 --- a/src/omaloon/world/interfaces/HasPressure.java +++ b/src/omaloon/world/interfaces/HasPressure.java @@ -1,6 +1,5 @@ package omaloon.world.interfaces; -import arc.math.*; import arc.struct.*; import arc.util.*; import mindustry.*; @@ -13,86 +12,88 @@ * @author Liz * only added this cause my ide did a funni */ -public interface HasPressure extends Buildingc { - default boolean acceptsPressurizedFluid(HasPressure from, @Nullable Liquid liquid, float amount) { - return pressureConfig().acceptsPressure; - } +public interface HasPressure extends Buildingc{ + default boolean acceptsPressurizedFluid(HasPressure from, @Nullable Liquid liquid, float amount){ + return pressureConfig().acceptsPressure; + } - /** - * Adds a certain amount of a fluid into this module through the section. - */ - default void addFluid(@Nullable Liquid liquid, float amount) { - if (amount == 0) return; - if (amount < 0) pressure().section.removeFluid(liquid, -amount); - pressure().section.addFluid(liquid, amount); - } + /** + * Adds a certain amount of a fluid into this module through the section. + */ + default void addFluid(@Nullable Liquid liquid, float amount){ + if(amount == 0) return; + if(amount < 0) pressure().section.removeFluid(liquid, -amount); + pressure().section.addFluid(liquid, amount); + } - /** - * @return true if both buildings are connected to eachother - */ - default boolean connected(HasPressure to) { - return connects(to) && to.connects(this); - } - /** - * @return true if this building connects to another one. - */ - default boolean connects(HasPressure to) { - return pressureConfig().outputsPressure || pressureConfig().acceptsPressure; - } + /** + * @return true if both buildings are connected to eachother + */ + default boolean connected(HasPressure to){ + return connects(to) && to.connects(this); + } - /** - * @return building destination to dump pressure - */ - default HasPressure getPressureDestination(HasPressure from, float pressure) { - return this; - } + /** + * @return true if this building connects to another one. + */ + default boolean connects(HasPressure to){ + return pressureConfig().outputsPressure || pressureConfig().acceptsPressure; + } - /** - * Returns the building whose section should be the same as this build's section. - */ - default @Nullable HasPressure getSectionDestination(HasPressure from) { - if (pressureConfig().fluidGroup == null || pressureConfig().fluidGroup == FluidGroup.unset || pressureConfig().fluidGroup != from.pressureConfig().fluidGroup) return null; - return this; - } + /** + * @return building destination to dump pressure + */ + default HasPressure getPressureDestination(HasPressure from, float pressure){ + return this; + } - /** - * Returns the next builds that this block will connect to - */ - default Seq nextBuilds() { - return proximity().select( - b -> b instanceof HasPressure - ).as().map( - b -> b.getPressureDestination(this, 0) - ).removeAll( - b -> !connected(b) && proximity().contains((Building) b) || !pressureConfig().isAllowed(b.block()) - ); - } + /** + * Returns the building whose section should be the same as this build's section. + */ + default @Nullable HasPressure getSectionDestination(HasPressure from){ + if(pressureConfig().fluidGroup == null || pressureConfig().fluidGroup == FluidGroup.unset || pressureConfig().fluidGroup != from.pressureConfig().fluidGroup) return null; + return this; + } - default boolean outputsPressurizedFluid(HasPressure to, @Nullable Liquid liquid, float amount) { - return pressureConfig().outputsPressure; - } + /** + * Returns the next builds that this block will connect to + */ + default Seq nextBuilds(){ + return proximity().select( + b -> b instanceof HasPressure + ).as().map( + b -> b.getPressureDestination(this, 0) + ).removeAll( + b -> !connected(b) && proximity().contains((Building)b) || !pressureConfig().isAllowed(b.block()) + ); + } - PressureModule pressure(); - PressureConfig pressureConfig(); + default boolean outputsPressurizedFluid(HasPressure to, @Nullable Liquid liquid, float amount){ + return pressureConfig().outputsPressure; + } - /** - * Removes a certain amount of a fluid into this module through the section. - */ - default void removeFluid(@Nullable Liquid liquid, float amount) { - if (amount == 0) return; - if (amount < 0) pressure().section.addFluid(liquid, -amount); - pressure().section.removeFluid(liquid, amount); - } + PressureModule pressure(); - /** - * method to update pressure related things - */ - default void updatePressure() { - if (nextBuilds().contains(other -> other.pressure().section != this)) pressure().section.updateTransfer(); + PressureConfig pressureConfig(); - Vars.content.liquids().each(liquid -> { - if (pressure().getPressure(liquid) < pressureConfig().minPressure - 1f) damage(pressureConfig().underPressureDamage); - if (pressure().getPressure(liquid) > pressureConfig().maxPressure + 1f) damage(pressureConfig().overPressureDamage); - }); - } + /** + * Removes a certain amount of a fluid into this module through the section. + */ + default void removeFluid(@Nullable Liquid liquid, float amount){ + if(amount == 0) return; + if(amount < 0) pressure().section.addFluid(liquid, -amount); + pressure().section.removeFluid(liquid, amount); + } + + /** + * method to update pressure related things + */ + default void updatePressure(){ + if(nextBuilds().contains(other -> other.pressure().section != this)) pressure().section.updateTransfer(); + + Vars.content.liquids().each(liquid -> { + if(pressure().getPressure(liquid) < pressureConfig().minPressure - 1f) damage(pressureConfig().underPressureDamage); + if(pressure().getPressure(liquid) > pressureConfig().maxPressure + 1f) damage(pressureConfig().overPressureDamage); + }); + } } diff --git a/src/omaloon/world/interfaces/HasPressureImpl.java b/src/omaloon/world/interfaces/HasPressureImpl.java index 2f8a428a..1202fce6 100644 --- a/src/omaloon/world/interfaces/HasPressureImpl.java +++ b/src/omaloon/world/interfaces/HasPressureImpl.java @@ -1,21 +1,19 @@ package omaloon.world.interfaces; -import arc.util.io.Reads; -import arc.util.io.Writes; -import omaloon.annotations.AutoImplement; -import omaloon.world.meta.PressureConfig; -import omaloon.world.meta.PressureSection; -import omaloon.world.modules.PressureModule; +import arc.util.io.*; +import omaloon.annotations.*; +import omaloon.world.meta.*; +import omaloon.world.modules.*; import static omaloon.annotations.AutoImplement.Inject.InjectPosition.*; @AutoImplement -public interface HasPressureImpl extends HasPressure { +public interface HasPressureImpl extends HasPressure{ PressureModule pressure = new PressureModule(); - default PressureModule pressure() { + default PressureModule pressure(){ return pressure; } @@ -25,21 +23,22 @@ default void onProximityUpdate(){ } @AutoImplement.Inject(Tail) - default void updateTile() { + default void updateTile(){ updatePressure(); } + @AutoImplement.Inject(AfterSuper) - default void write(Writes writes) { + default void write(Writes writes){ pressure.write(writes); } @AutoImplement.Inject(AfterSuper) - default void read(Reads reads, byte b) { + default void read(Reads reads, byte b){ pressure.read(reads); } @Override - default PressureConfig pressureConfig() { + default PressureConfig pressureConfig(){ return AutoImplement.Util.Param("pressureConfig", "pressureConfig"); } } diff --git a/src/omaloon/world/interfaces/MultiPropI.java b/src/omaloon/world/interfaces/MultiPropI.java index f97c1218..82fbcea2 100644 --- a/src/omaloon/world/interfaces/MultiPropI.java +++ b/src/omaloon/world/interfaces/MultiPropI.java @@ -4,10 +4,11 @@ import omaloon.type.customshape.*; import omaloon.world.*; -public interface MultiPropI { - Seq shapes(); +public interface MultiPropI{ + Seq shapes(); - default Runnable removed(MultiPropGroup from) { - return () -> {}; - } + default Runnable removed(MultiPropGroup from){ + return () -> { + }; + } } diff --git a/src/omaloon/world/meta/FluidGroup.java b/src/omaloon/world/meta/FluidGroup.java index ba491d91..d18081a7 100644 --- a/src/omaloon/world/meta/FluidGroup.java +++ b/src/omaloon/world/meta/FluidGroup.java @@ -1,12 +1,12 @@ package omaloon.world.meta; -public enum FluidGroup { - /** - * This group specifically acts the same as if the group is null. Only used if blocks that normally override the group have to be independent. - */ - unset, +public enum FluidGroup{ + /** + * This group specifically acts the same as if the group is null. Only used if blocks that normally override the group have to be independent. + */ + unset, - drills, - pumps, - transportation + drills, + pumps, + transportation } diff --git a/src/omaloon/world/meta/OlStats.java b/src/omaloon/world/meta/OlStats.java index 65cca68a..984f9ea5 100644 --- a/src/omaloon/world/meta/OlStats.java +++ b/src/omaloon/world/meta/OlStats.java @@ -9,71 +9,71 @@ import mindustry.ui.*; import mindustry.world.meta.*; -import static mindustry.Vars.*; +import static mindustry.Vars.iconMed; -public class OlStats { - public static final StatCat pressure = new StatCat("omaloon-pressure"); +public class OlStats{ + public static final StatCat pressure = new StatCat("omaloon-pressure"); - public static final Stat - minSpeed = new Stat("omaloon-min-speed"), - maxSpeed = new Stat("omaloon-max-speed"), + public static final Stat + minSpeed = new Stat("omaloon-min-speed"), + maxSpeed = new Stat("omaloon-max-speed"), - fluidCapacity = new Stat("omaloon-fluid-capacity", StatCat.liquids), + fluidCapacity = new Stat("omaloon-fluid-capacity", StatCat.liquids), - density = new Stat("omaloon-density"), + density = new Stat("omaloon-density"), - pressureFlow = new Stat("omaloon-pressureflow", pressure), + pressureFlow = new Stat("omaloon-pressureflow", pressure), - pumpStrength = new Stat("omaloon-pump-strength", pressure), - pressureGradient = new Stat("omaloon-pressure-gradient", pressure), + pumpStrength = new Stat("omaloon-pump-strength", pressure), + pressureGradient = new Stat("omaloon-pressure-gradient", pressure), - maxPressure = new Stat("omaloon-max-pressure", pressure), - minPressure = new Stat("omaloon-min-pressure", pressure), + maxPressure = new Stat("omaloon-max-pressure", pressure), + minPressure = new Stat("omaloon-min-pressure", pressure), - pressureRange = new Stat("omaloon-pressure-range", pressure), - optimalPressure = new Stat("omaloon-optimal-pressure", pressure); + pressureRange = new Stat("omaloon-pressure-range", pressure), + optimalPressure = new Stat("omaloon-optimal-pressure", pressure); - public static final StatUnit - blocksCubed = new StatUnit("omaloon-blocks-cubed"), + public static final StatUnit + blocksCubed = new StatUnit("omaloon-blocks-cubed"), - densityUnit = new StatUnit("omaloon-density-unit", "\uC357"), - viscosityUnit = new StatUnit("omaloon-viscosity-unit", "\uC357"), + densityUnit = new StatUnit("omaloon-density-unit", "\uC357"), + viscosityUnit = new StatUnit("omaloon-viscosity-unit", "\uC357"), - pressureUnit = new StatUnit("omaloon-pressure-unit", "\uC357"), - pressureSecond = new StatUnit("omaloon-pressureSecond", "\uC357"); + pressureUnit = new StatUnit("omaloon-pressure-unit", "\uC357"), + pressureSecond = new StatUnit("omaloon-pressureSecond", "\uC357"); - public static StatValue fluid(@Nullable Liquid liquid, float amount, float time, boolean showContinuous) { - return table -> { - table.table(display -> { - display.add(new Stack() {{ - add(new Image(liquid != null ? liquid.uiIcon : Core.atlas.find("omaloon-pressure-icon")).setScaling(Scaling.fit)); + public static StatValue fluid(@Nullable Liquid liquid, float amount, float time, boolean showContinuous){ + return table -> { + table.table(display -> { + display.add(new Stack(){{ + add(new Image(liquid != null ? liquid.uiIcon : Core.atlas.find("omaloon-pressure-icon")).setScaling(Scaling.fit)); - if (amount * 60f/time != 0) { - Table t = new Table().left().bottom(); - t.add(Strings.autoFixed(amount * 60f/time, 2)).style(Styles.outlineLabel); - add(t); - } - }}).size(iconMed).padRight(3 + (amount * 60f/time != 0 && Strings.autoFixed(amount * 60f/time, 2).length() > 2 ? 8 : 0)); + if(amount * 60f / time != 0){ + Table t = new Table().left().bottom(); + t.add(Strings.autoFixed(amount * 60f / time, 2)).style(Styles.outlineLabel); + add(t); + } + }}).size(iconMed).padRight(3 + (amount * 60f / time != 0 && Strings.autoFixed(amount * 60f / time, 2).length() > 2 ? 8 : 0)); - if(showContinuous){ - display.add(StatUnit.perSecond.localized()).padLeft(2).padRight(5).color(Color.lightGray).style(Styles.outlineLabel); - } + if(showContinuous){ + display.add(StatUnit.perSecond.localized()).padLeft(2).padRight(5).color(Color.lightGray).style(Styles.outlineLabel); + } - display.add(liquid != null ? liquid.localizedName : "@air"); - }); - }; - } + display.add(liquid != null ? liquid.localizedName : "@air"); + }); + }; + } - public static StatValue pressure(float amount, boolean merge) { - return table -> { - String l1 = (pressureUnit.icon == null ? "" : pressureUnit.icon + " ") + (amount == 0 ? "" : (amount > 0 ? "+" : "-")) + Strings.autoFixed(Math.abs(amount), 2), l2 = (pressureUnit.space ? " " : "") + pressureUnit.localized(); + public static StatValue pressure(float amount, boolean merge){ + return table -> { + String l1 = (pressureUnit.icon == null ? "" : pressureUnit.icon + " ") + (amount == 0 ? "" : (amount > 0 ? "+" : "-")) + Strings.autoFixed(Math.abs(amount), 2), l2 = (pressureUnit.space ? " " : "") + pressureUnit.localized(); - if(merge){ - table.add(l1 + l2).left(); - }else{ - table.add(l1).left(); - table.add(l2).left(); - } - }; - } + if(merge){ + table.add(l1 + l2).left(); + }else{ + table.add(l1).left(); + table.add(l2).left(); + } + }; + } } diff --git a/src/omaloon/world/meta/PressureConfig.java b/src/omaloon/world/meta/PressureConfig.java index e50df3a5..4e4662de 100644 --- a/src/omaloon/world/meta/PressureConfig.java +++ b/src/omaloon/world/meta/PressureConfig.java @@ -13,79 +13,79 @@ import omaloon.world.blocks.liquid.*; import omaloon.world.interfaces.*; -public class PressureConfig { - /** - * Group used for the creation of sections. if null, this block will be a section containing only itself. - */ - public FluidGroup fluidGroup; +public class PressureConfig{ + /** + * Group used for the creation of sections. if null, this block will be a section containing only itself. + */ + public FluidGroup fluidGroup; - /** - * If true, this block's section will be able to receive fluids. - */ - public boolean acceptsPressure = true; - /** - * If true, this block's section will be able to output fluids. - */ - public boolean outputsPressure = true; - /** - * Determines whether linkList will function as a whitelist - */ - public boolean isWhitelist = false; + /** + * If true, this block's section will be able to receive fluids. + */ + public boolean acceptsPressure = true; + /** + * If true, this block's section will be able to output fluids. + */ + public boolean outputsPressure = true; + /** + * Determines whether linkList will function as a whitelist + */ + public boolean isWhitelist = false; - /** - * Damage applied each tick if pressure is higher than maxPressure. - */ - public float overPressureDamage = 0.33f; - /** - * Damage applied each tick if pressure is lower than minPressure. - */ - public float underPressureDamage = 0.66f; - /** - * Maximum pressure that this block can contain before it over-pressurizes. - */ - public float maxPressure = 50; - /** - * Minimum pressure that this block can contain before it under-pressurizes. - */ - public float minPressure = -50f; + /** + * Damage applied each tick if pressure is higher than maxPressure. + */ + public float overPressureDamage = 0.33f; + /** + * Damage applied each tick if pressure is lower than minPressure. + */ + public float underPressureDamage = 0.66f; + /** + * Maximum pressure that this block can contain before it over-pressurizes. + */ + public float maxPressure = 50; + /** + * Minimum pressure that this block can contain before it under-pressurizes. + */ + public float minPressure = -50f; - /** - * Standard capacity for this block. Does not define max amount that this can hold. That is defined by maxPressure and minPressure. - */ - public float fluidCapacity = 8; + /** + * Standard capacity for this block. Does not define max amount that this can hold. That is defined by maxPressure and minPressure. + */ + public float fluidCapacity = 8; - /** - * List of blocks that are allowed/disallowed (depends on isWhitelist true/false) for pressure connections. - *

    - * Note: If block A filters block B, also filter block A in block B's config. - *

    - * Without mutual filtering, connections may be inconsistent: - * Block A might connect to Block B, but Block B might not connect to Block A. - * This can create confusing pressure networks where connections - * work from one side but not the other. - */ - public Seq linkList = new Seq<>(); + /** + * List of blocks that are allowed/disallowed (depends on isWhitelist true/false) for pressure connections. + *

    + * Note: If block A filters block B, also filter block A in block B's config. + *

    + * Without mutual filtering, connections may be inconsistent: + * Block A might connect to Block B, but Block B might not connect to Block A. + * This can create confusing pressure networks where connections + * work from one side but not the other. + */ + public Seq linkList = new Seq<>(); - /** - * Always allowed block types - */ - private static final Class[] alwaysAllowed = { - PressureLiquidBridge.class, - PressureLiquidConduit.class, - PressureLiquidJunction.class, - PressureLiquidPump.class, - PressureLiquidValve.class - }; + /** + * Always allowed block types + */ + private static final Class[] alwaysAllowed = { + PressureLiquidBridge.class, + PressureLiquidConduit.class, + PressureLiquidJunction.class, + PressureLiquidPump.class, + PressureLiquidValve.class + }; - public void addStats(Stats stats) { - stats.add(OlStats.fluidCapacity, StatValues.number(fluidCapacity/8f, OlStats.blocksCubed)); + public void addStats(Stats stats){ + stats.add(OlStats.fluidCapacity, StatValues.number(fluidCapacity / 8f, OlStats.blocksCubed)); - stats.add(OlStats.maxPressure, OlStats.pressure(maxPressure, true)); - stats.add(OlStats.minPressure, OlStats.pressure(minPressure, true)); - } + stats.add(OlStats.maxPressure, OlStats.pressure(maxPressure, true)); + stats.add(OlStats.minPressure, OlStats.pressure(minPressure, true)); + } - public void addBars(Block block) { - block.removeBar("liquid"); + public void addBars(Block block){ + block.removeBar("liquid"); // block.addBar("pressure-liquid", (Building entity) -> new Bar( // () -> { // HasPressure build = (HasPressure)entity; @@ -108,39 +108,39 @@ public void addBars(Block block) { // return current != null ? entity.liquids.get(current) / block.liquidCapacity : 0f; // } // )); - block.addBar("pressure-liquid", (Building entity) -> new Bar( - () -> { - HasPressure build = (HasPressure)entity; - Liquid current = build.pressure().getMain(); + block.addBar("pressure-liquid", (Building entity) -> new Bar( + () -> { + HasPressure build = (HasPressure)entity; + Liquid current = build.pressure().getMain(); - if (current == null) return Core.bundle.get("bar.air") + Strings.autoFixed(build.pressure().air, 2); - return Core.bundle.format("bar.pressure-liquid", - current.localizedName, - Strings.autoFixed(build.pressure().liquids[current.id], 2), - Strings.autoFixed(build.pressure().air, 2) - ); - }, - () -> { - HasPressure build = (HasPressure)entity; - Liquid current = build.pressure().getMain(); - return current != null ? current.color : Color.lightGray; - }, - () -> { - HasPressure build = (HasPressure)entity; - Liquid current = build.pressure().getMain(); - return current != null ? Mathf.clamp(build.pressure().liquids[current.id]/(build.pressure().liquids[current.id] + build.pressure().air)) : 0; - } - )); - } + if(current == null) return Core.bundle.get("bar.air") + Strings.autoFixed(build.pressure().air, 2); + return Core.bundle.format("bar.pressure-liquid", + current.localizedName, + Strings.autoFixed(build.pressure().liquids[current.id], 2), + Strings.autoFixed(build.pressure().air, 2) + ); + }, + () -> { + HasPressure build = (HasPressure)entity; + Liquid current = build.pressure().getMain(); + return current != null ? current.color : Color.lightGray; + }, + () -> { + HasPressure build = (HasPressure)entity; + Liquid current = build.pressure().getMain(); + return current != null ? Mathf.clamp(build.pressure().liquids[current.id] / (build.pressure().liquids[current.id] + build.pressure().air)) : 0; + } + )); + } - public boolean isAllowed(Block block) { - for (Class alwaysAllowedClass : alwaysAllowed) { - if (alwaysAllowedClass.isAssignableFrom(block.getClass())) { - return true; - } - } + public boolean isAllowed(Block block){ + for(Class alwaysAllowedClass : alwaysAllowed){ + if(alwaysAllowedClass.isAssignableFrom(block.getClass())){ + return true; + } + } - boolean inList = linkList.contains(block); - return isWhitelist == inList; - } + boolean inList = linkList.contains(block); + return isWhitelist == inList; + } } \ No newline at end of file diff --git a/src/omaloon/world/meta/PressureSection.java b/src/omaloon/world/meta/PressureSection.java index d77201d2..97502794 100644 --- a/src/omaloon/world/meta/PressureSection.java +++ b/src/omaloon/world/meta/PressureSection.java @@ -10,194 +10,195 @@ import omaloon.math.*; import omaloon.world.interfaces.*; -public class PressureSection { - public Seq builds = new Seq<>(); - - /** - * Temporary seqs for use in flood. - */ - public static final Seq tmp = new Seq<>(), tmp2 = new Seq<>(); - - /** - * Adds a build to this section, and removes the build from its older section. - */ - public void addBuild(HasPressure build) { - builds.add(build); - build.pressure().section.builds.remove(build); - build.pressure().section = this; - } - - /** - * Adds a certain amount of a fluid into this module, updating it's pressure accordingly. A null liquid means that air is being added to it. - */ - public void addFluid(@Nullable Liquid liquid, float amount) { - if (builds.isEmpty()) return; - float div = amount/builds.size; - builds.each(b -> b.pressure().addFluid(liquid, div, b.pressureConfig())); - } - - /** - * Merges buildings to this section with floodFill. - */ - public void mergeFlood(HasPressure other) { - tmp.clear().add(other); - tmp2.clear(); - - while(!tmp.isEmpty()) { - HasPressure next = tmp.pop(); - tmp2.addUnique(next); - next.nextBuilds().each(b -> { - if (b.getSectionDestination(next) != null && !tmp2.contains(b.getSectionDestination(next))) { - tmp.add(b.getSectionDestination(next)); - } - }); - } - - tmp2.each(this::addBuild); - updateLiquids(); - } - - /** - * Removes a certain amount of a fluid from this module, updating pressure accordingly. A null liquid means that air is being removed from it. Liquids cannot be negative. - */ - public void removeFluid(@Nullable Liquid liquid, float amount) { - if (builds.isEmpty()) return; - float div = amount/builds.size; - builds.each(b -> b.pressure().removeFluid(liquid, div, b.pressureConfig())); - } - - public void updateLiquids() { - float[] liquids = new float[Vars.content.liquids().size]; - float air = 0; - - for(Liquid liquid : Vars.content.liquids()) for (HasPressure build : builds) { - liquids[liquid.id] += build.pressure().liquids[liquid.id]; - build.pressure().liquids[liquid.id] = 0; - build.pressure().pressures[liquid.id] = 0; - } - for(HasPressure build : builds) { - air += build.pressure().air; - build.pressure().air = 0; - build.pressure().pressure = 0; - } - - for(Liquid liquid : Vars.content.liquids()) addFluid(liquid, liquids[liquid.id]); - addFluid(null, air); - } - - public void updateTransfer() { - Seq> links = new Seq<>(); - - builds.each(b -> { - b.nextBuilds().retainAll(other -> other.pressure().section != this).each(other -> { - links.add(new Entry<>(){{ - key = other; - value = b; - }}); - }); - }); - - FloatSeq amounts = new FloatSeq(); - - Vars.content.liquids().each(main -> { - amounts.clear(); - for (Entry entry : links) { - float flow = OlMath.flowRate( - entry.value.pressure().getPressure(main), - entry.key.pressure().getPressure(main), - entry.value.pressureConfig().fluidCapacity, - entry.key.pressureConfig().fluidCapacity, - OlLiquids.getDensity(main), - OlLiquids.getViscosity(main) - ) / (2f * links.size); - - if ( - ( - flow > 0 ? - ( - entry.key.acceptsPressurizedFluid(entry.value, main, flow) && - entry.value.outputsPressurizedFluid(entry.key, main, flow) - ) : - ( - entry.value.acceptsPressurizedFluid(entry.key, main, flow) && - entry.key.outputsPressurizedFluid(entry.value, main, flow) - ) - ) && - (entry.key.pressure().get(main) > 0 || entry.value.pressure().get(main) > 0) - ) { - amounts.add(flow); - } else { - amounts.add(0); - } - } - for (Entry entry : links) { - float maxFlow = OlMath.flowRate( - entry.value.pressure().getPressure(main), - entry.key.pressure().getPressure(main), - entry.value.pressureConfig().fluidCapacity, - entry.key.pressureConfig().fluidCapacity, - OlLiquids.getDensity(main), - 1 - ) / (2f * links.size); - - float flow = Mathf.clamp( - amounts.get(links.indexOf(entry)) * Time.delta, - -Math.abs(maxFlow), - Math.abs(maxFlow) - ); - if (flow != 0) { - entry.key.addFluid(main, flow); - entry.value.removeFluid(main, flow); - } - } - }); - amounts.clear(); - for (Entry entry : links) { - float flow = OlMath.flowRate( - entry.value.pressure().getPressure(null), - entry.key.pressure().getPressure(null), - entry.value.pressureConfig().fluidCapacity, - entry.key.pressureConfig().fluidCapacity, - OlLiquids.getDensity(null), - OlLiquids.getViscosity(null) - ) / (2f * links.size); - - if ( - ( - flow > 0 ? - ( - entry.key.acceptsPressurizedFluid(entry.value, null, flow) && - entry.value.outputsPressurizedFluid(entry.key, null, flow) - ) : ( - entry.value.acceptsPressurizedFluid(entry.key, null, flow) && - entry.key.outputsPressurizedFluid(entry.value, null, flow) - ) - ) - ) { - amounts.add(flow); - } else { - amounts.add(0); - } - } - for (Entry entry : links) { - float maxFlow = OlMath.flowRate( - entry.value.pressure().getPressure(null), - entry.key.pressure().getPressure(null), - entry.value.pressureConfig().fluidCapacity, - entry.key.pressureConfig().fluidCapacity, - OlLiquids.getDensity(null), - 1 - ) / (2f * links.size); - - float flow = Mathf.clamp( - amounts.get(links.indexOf(entry)) * Time.delta, - -Math.abs(maxFlow), - Math.abs(maxFlow) - ); - if (flow != 0) { - entry.key.addFluid(null, amounts.get(links.indexOf(entry))); - entry.value.removeFluid(null, amounts.get(links.indexOf(entry))); - } - } - } +public class PressureSection{ + public Seq builds = new Seq<>(); + + /** + * Temporary seqs for use in flood. + */ + public static final Seq tmp = new Seq<>(), tmp2 = new Seq<>(); + + /** + * Adds a build to this section, and removes the build from its older section. + */ + public void addBuild(HasPressure build){ + builds.add(build); + build.pressure().section.builds.remove(build); + build.pressure().section = this; + } + + /** + * Adds a certain amount of a fluid into this module, updating it's pressure accordingly. A null liquid means that air is being added to it. + */ + public void addFluid(@Nullable Liquid liquid, float amount){ + if(builds.isEmpty()) return; + float div = amount / builds.size; + builds.each(b -> b.pressure().addFluid(liquid, div, b.pressureConfig())); + } + + /** + * Merges buildings to this section with floodFill. + */ + public void mergeFlood(HasPressure other){ + tmp.clear().add(other); + tmp2.clear(); + + while(!tmp.isEmpty()){ + HasPressure next = tmp.pop(); + tmp2.addUnique(next); + next.nextBuilds().each(b -> { + if(b.getSectionDestination(next) != null && !tmp2.contains(b.getSectionDestination(next))){ + tmp.add(b.getSectionDestination(next)); + } + }); + } + + tmp2.each(this::addBuild); + updateLiquids(); + } + + /** + * Removes a certain amount of a fluid from this module, updating pressure accordingly. A null liquid means that air is being removed from it. Liquids cannot be negative. + */ + public void removeFluid(@Nullable Liquid liquid, float amount){ + if(builds.isEmpty()) return; + float div = amount / builds.size; + builds.each(b -> b.pressure().removeFluid(liquid, div, b.pressureConfig())); + } + + public void updateLiquids(){ + float[] liquids = new float[Vars.content.liquids().size]; + float air = 0; + + for(Liquid liquid : Vars.content.liquids()) + for(HasPressure build : builds){ + liquids[liquid.id] += build.pressure().liquids[liquid.id]; + build.pressure().liquids[liquid.id] = 0; + build.pressure().pressures[liquid.id] = 0; + } + for(HasPressure build : builds){ + air += build.pressure().air; + build.pressure().air = 0; + build.pressure().pressure = 0; + } + + for(Liquid liquid : Vars.content.liquids()) addFluid(liquid, liquids[liquid.id]); + addFluid(null, air); + } + + public void updateTransfer(){ + Seq> links = new Seq<>(); + + builds.each(b -> { + b.nextBuilds().retainAll(other -> other.pressure().section != this).each(other -> { + links.add(new Entry<>(){{ + key = other; + value = b; + }}); + }); + }); + + FloatSeq amounts = new FloatSeq(); + + Vars.content.liquids().each(main -> { + amounts.clear(); + for(Entry entry : links){ + float flow = OlMath.flowRate( + entry.value.pressure().getPressure(main), + entry.key.pressure().getPressure(main), + entry.value.pressureConfig().fluidCapacity, + entry.key.pressureConfig().fluidCapacity, + OlLiquids.getDensity(main), + OlLiquids.getViscosity(main) + ) / (2f * links.size); + + if( + ( + flow > 0 ? + ( + entry.key.acceptsPressurizedFluid(entry.value, main, flow) && + entry.value.outputsPressurizedFluid(entry.key, main, flow) + ) : + ( + entry.value.acceptsPressurizedFluid(entry.key, main, flow) && + entry.key.outputsPressurizedFluid(entry.value, main, flow) + ) + ) && + (entry.key.pressure().get(main) > 0 || entry.value.pressure().get(main) > 0) + ){ + amounts.add(flow); + }else{ + amounts.add(0); + } + } + for(Entry entry : links){ + float maxFlow = OlMath.flowRate( + entry.value.pressure().getPressure(main), + entry.key.pressure().getPressure(main), + entry.value.pressureConfig().fluidCapacity, + entry.key.pressureConfig().fluidCapacity, + OlLiquids.getDensity(main), + 1 + ) / (2f * links.size); + + float flow = Mathf.clamp( + amounts.get(links.indexOf(entry)) * Time.delta, + -Math.abs(maxFlow), + Math.abs(maxFlow) + ); + if(flow != 0){ + entry.key.addFluid(main, flow); + entry.value.removeFluid(main, flow); + } + } + }); + amounts.clear(); + for(Entry entry : links){ + float flow = OlMath.flowRate( + entry.value.pressure().getPressure(null), + entry.key.pressure().getPressure(null), + entry.value.pressureConfig().fluidCapacity, + entry.key.pressureConfig().fluidCapacity, + OlLiquids.getDensity(null), + OlLiquids.getViscosity(null) + ) / (2f * links.size); + + if( + ( + flow > 0 ? + ( + entry.key.acceptsPressurizedFluid(entry.value, null, flow) && + entry.value.outputsPressurizedFluid(entry.key, null, flow) + ) : ( + entry.value.acceptsPressurizedFluid(entry.key, null, flow) && + entry.key.outputsPressurizedFluid(entry.value, null, flow) + ) + ) + ){ + amounts.add(flow); + }else{ + amounts.add(0); + } + } + for(Entry entry : links){ + float maxFlow = OlMath.flowRate( + entry.value.pressure().getPressure(null), + entry.key.pressure().getPressure(null), + entry.value.pressureConfig().fluidCapacity, + entry.key.pressureConfig().fluidCapacity, + OlLiquids.getDensity(null), + 1 + ) / (2f * links.size); + + float flow = Mathf.clamp( + amounts.get(links.indexOf(entry)) * Time.delta, + -Math.abs(maxFlow), + Math.abs(maxFlow) + ); + if(flow != 0){ + entry.key.addFluid(null, amounts.get(links.indexOf(entry))); + entry.value.removeFluid(null, amounts.get(links.indexOf(entry))); + } + } + } } diff --git a/src/omaloon/world/modules/PressureModule.java b/src/omaloon/world/modules/PressureModule.java index 2c6e0e76..5645a666 100644 --- a/src/omaloon/world/modules/PressureModule.java +++ b/src/omaloon/world/modules/PressureModule.java @@ -10,107 +10,107 @@ import omaloon.content.*; import omaloon.world.meta.*; -public class PressureModule extends BlockModule { - public static float arbitraryPressureScalar = 10f; - public static float smoothingSpeed = 0.03f; - - public float[] liquids = new float[Vars.content.liquids().size]; - public float[] pressures = new float[Vars.content.liquids().size]; - public float air = 0, pressure = 0; - - public PressureSection section = new PressureSection(); - - public Liquid current = Liquids.water; - - /** - * Adds a certain amount of a fluid into this module, updating it's pressure accordingly. A null liquid means that air is being added to it. - */ - public void addFluid(@Nullable Liquid liquid, float amount, PressureConfig reference) { - if (liquid == null) { - air += amount; - pressure = air / reference.fluidCapacity * OlLiquids.getDensity(liquid); - } else { - if (air < 0) { - air = 0; - pressure = 0; - } - liquids[liquid.id] += amount; - pressures[liquid.id] = liquids[liquid.id] / reference.fluidCapacity * OlLiquids.getDensity(liquid); - } - if (liquid != null) current = liquid; - } - - public float get(@Nullable Liquid liquid) { - if (liquid == null) { - return air; - } else { - return liquids[liquid.id]; - } - } - - public @Nullable Liquid getMain() { - Liquid out = null; - for(int i = 0; i < liquids.length; i++) { - if (out == null && liquids[i] > 0.01) out = Vars.content.liquid(i); - if (out != null && liquids[i] > liquids[out.id]) out = Vars.content.liquid(i); - } - return out; - } - - /** - * Returns the amount of pressure felt by this module from a certain liquid + the pressure of air inside this module. - */ - public float getPressure(@Nullable Liquid liquid) { - if (liquid == null) { - return pressure; - } - return pressures[liquid.id] + pressure; - } - - @Override - public void read(Reads read) { - air = read.f(); - pressure = read.f(); - - int count = read.s(); - - for(int i = 0; i < count; i++){ - Liquid liq = Vars.content.liquid(read.s()); - float amount = read.f(); - float pressure = read.f(); - if(liq != null){ - if (amount > 0) current = liq; - liquids[liq.id] = amount; - pressures[liq.id] = pressure; - } - } - } - - /** - * Removes a certain amount of a fluid from this module, updating pressure accordingly. A null liquid means that air is being removed from it. Liquids cannot be negative. - */ - public void removeFluid(@Nullable Liquid liquid, float amount, PressureConfig reference) { - if (liquid == null) { - air -= (getMain() != null ? Math.min(air, amount) : amount); - pressure = air / reference.fluidCapacity * OlLiquids.getDensity(liquid); - } else { - liquids[liquid.id] = Mathf.maxZero(liquids[liquid.id] - amount); - pressures[liquid.id] = liquids[liquid.id] / reference.fluidCapacity * OlLiquids.getDensity(liquid); - } - if (liquid != null) current = liquid; - } - - @Override - public void write(Writes write) { - write.f(air); - write.f(pressure); - - write.s(liquids.length); - - for(int i = 0; i < liquids.length; i++){ - write.s(i); //liquid ID - write.f(liquids[i]); //liquid amount - write.f(pressures[i]); //liquid amount - } - } +public class PressureModule extends BlockModule{ + public static float arbitraryPressureScalar = 10f; + public static float smoothingSpeed = 0.03f; + + public float[] liquids = new float[Vars.content.liquids().size]; + public float[] pressures = new float[Vars.content.liquids().size]; + public float air = 0, pressure = 0; + + public PressureSection section = new PressureSection(); + + public Liquid current = Liquids.water; + + /** + * Adds a certain amount of a fluid into this module, updating it's pressure accordingly. A null liquid means that air is being added to it. + */ + public void addFluid(@Nullable Liquid liquid, float amount, PressureConfig reference){ + if(liquid == null){ + air += amount; + pressure = air / reference.fluidCapacity * OlLiquids.getDensity(liquid); + }else{ + if(air < 0){ + air = 0; + pressure = 0; + } + liquids[liquid.id] += amount; + pressures[liquid.id] = liquids[liquid.id] / reference.fluidCapacity * OlLiquids.getDensity(liquid); + } + if(liquid != null) current = liquid; + } + + public float get(@Nullable Liquid liquid){ + if(liquid == null){ + return air; + }else{ + return liquids[liquid.id]; + } + } + + public @Nullable Liquid getMain(){ + Liquid out = null; + for(int i = 0; i < liquids.length; i++){ + if(out == null && liquids[i] > 0.01) out = Vars.content.liquid(i); + if(out != null && liquids[i] > liquids[out.id]) out = Vars.content.liquid(i); + } + return out; + } + + /** + * Returns the amount of pressure felt by this module from a certain liquid + the pressure of air inside this module. + */ + public float getPressure(@Nullable Liquid liquid){ + if(liquid == null){ + return pressure; + } + return pressures[liquid.id] + pressure; + } + + @Override + public void read(Reads read){ + air = read.f(); + pressure = read.f(); + + int count = read.s(); + + for(int i = 0; i < count; i++){ + Liquid liq = Vars.content.liquid(read.s()); + float amount = read.f(); + float pressure = read.f(); + if(liq != null){ + if(amount > 0) current = liq; + liquids[liq.id] = amount; + pressures[liq.id] = pressure; + } + } + } + + /** + * Removes a certain amount of a fluid from this module, updating pressure accordingly. A null liquid means that air is being removed from it. Liquids cannot be negative. + */ + public void removeFluid(@Nullable Liquid liquid, float amount, PressureConfig reference){ + if(liquid == null){ + air -= (getMain() != null ? Math.min(air, amount) : amount); + pressure = air / reference.fluidCapacity * OlLiquids.getDensity(liquid); + }else{ + liquids[liquid.id] = Mathf.maxZero(liquids[liquid.id] - amount); + pressures[liquid.id] = liquids[liquid.id] / reference.fluidCapacity * OlLiquids.getDensity(liquid); + } + if(liquid != null) current = liquid; + } + + @Override + public void write(Writes write){ + write.f(air); + write.f(pressure); + + write.s(liquids.length); + + for(int i = 0; i < liquids.length; i++){ + write.s(i); //liquid ID + write.f(liquids[i]); //liquid amount + write.f(pressures[i]); //liquid amount + } + } }