repo_id
stringclasses
383 values
file_path
stringlengths
7
168
content
stringlengths
0
1.75M
Angelica
src\main\java\me\jellysquid\mods\sodium\client\gui\options\OptionImpact.java
package me.jellysquid.mods.sodium.client.gui.options; import net.minecraft.client.resources.I18n; import net.minecraft.util.EnumChatFormatting; public enum OptionImpact { LOW(EnumChatFormatting.GREEN, I18n.format("sodium.option_impact.low")), MEDIUM(EnumChatFormatting.YELLOW, I18n.format("sodium.option_impact.medium")), HIGH(EnumChatFormatting.GOLD, I18n.format("sodium.option_impact.high")), EXTREME(EnumChatFormatting.RED, I18n.format("sodium.option_impact.extreme")), VARIES(EnumChatFormatting.WHITE, I18n.format("sodium.option_impact.varies")); private final EnumChatFormatting color; private final String text; OptionImpact(EnumChatFormatting color, String text) { this.color = color; this.text = text; } public String toDisplayString() { return this.color + this.text; } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\gui\options\OptionImpl.java
package me.jellysquid.mods.sodium.client.gui.options; import lombok.Getter; import lombok.Setter; import me.flashyreese.mods.reeses_sodium_options.client.gui.OptionExtended; import me.jellysquid.mods.sodium.client.gui.options.binding.GenericBinding; import me.jellysquid.mods.sodium.client.gui.options.binding.OptionBinding; import me.jellysquid.mods.sodium.client.gui.options.control.Control; import me.jellysquid.mods.sodium.client.gui.options.storage.OptionStorage; import me.jellysquid.mods.sodium.client.util.Dim2i; import org.apache.commons.lang3.Validate; import java.util.Collection; import java.util.Collections; import java.util.EnumSet; import java.util.function.BiConsumer; import java.util.function.BooleanSupplier; import java.util.function.Function; public class OptionImpl<S, T> implements OptionExtended<T> { private final OptionStorage<S> storage; private final OptionBinding<S, T> binding; private final Control<T> control; private final EnumSet<OptionFlag> flags; private final String name; private final String tooltip; private final OptionImpact impact; private T value; private T modifiedValue; private BooleanSupplier iris$dynamicallyEnabled; private final boolean enabled; private OptionImpl(OptionStorage<S> storage, String name, String tooltip, OptionBinding<S, T> binding, Function<OptionImpl<S, T>, Control<T>> control, EnumSet<OptionFlag> flags, OptionImpact impact, boolean enabled) { this.storage = storage; this.name = name; this.tooltip = tooltip; this.binding = binding; this.impact = impact; this.flags = flags; this.control = control.apply(this); this.enabled = enabled; this.reset(); } @Override public String getName() { return this.name; } @Override public String getTooltip() { return this.tooltip; } @Override public OptionImpact getImpact() { return this.impact; } @Override public Control<T> getControl() { return this.control; } @Override public T getValue() { return this.modifiedValue; } @Override public void setValue(T value) { this.modifiedValue = value; } @Override public void reset() { this.value = this.binding.getValue(this.storage.getData()); this.modifiedValue = this.value; } @Override public OptionStorage<?> getStorage() { return this.storage; } @Override public boolean isAvailable() { if (iris$dynamicallyEnabled != null) { return iris$dynamicallyEnabled.getAsBoolean(); } return this.enabled; } @Override public boolean hasChanged() { return !this.value.equals(this.modifiedValue); } @Override public void applyChanges() { this.binding.setValue(this.storage.getData(), this.modifiedValue); this.value = this.modifiedValue; } public void iris$dynamicallyEnable(BooleanSupplier enabled) { this.iris$dynamicallyEnabled = enabled; } @Override public Collection<OptionFlag> getFlags() { return this.flags; } public static <S, T> OptionImpl.Builder<S, T> createBuilder(Class<T> type, OptionStorage<S> storage) { return new Builder<>(storage); } public static class Builder<S, T> { private final OptionStorage<S> storage; private String name; private String tooltip; private OptionBinding<S, T> binding; private Function<OptionImpl<S, T>, Control<T>> control; private OptionImpact impact; private final EnumSet<OptionFlag> flags = EnumSet.noneOf(OptionFlag.class); private boolean enabled = true; private Builder(OptionStorage<S> storage) { this.storage = storage; } public Builder<S, T> setName(String name) { Validate.notNull(name, "Argument must not be null"); this.name = name; return this; } public Builder<S, T> setTooltip(String tooltip) { Validate.notNull(tooltip, "Argument must not be null"); this.tooltip = tooltip; return this; } public Builder<S, T> setBinding(BiConsumer<S, T> setter, Function<S, T> getter) { Validate.notNull(setter, "Setter must not be null"); Validate.notNull(getter, "Getter must not be null"); this.binding = new GenericBinding<>(setter, getter); return this; } public Builder<S, T> setBinding(OptionBinding<S, T> binding) { Validate.notNull(binding, "Argument must not be null"); this.binding = binding; return this; } public Builder<S, T> setControl(Function<OptionImpl<S, T>, Control<T>> control) { Validate.notNull(control, "Argument must not be null"); this.control = control; return this; } public Builder<S, T> setImpact(OptionImpact impact) { this.impact = impact; return this; } public Builder<S, T> setEnabled(boolean value) { this.enabled = value; return this; } public Builder<S, T> setFlags(OptionFlag... flags) { Collections.addAll(this.flags, flags); return this; } public OptionImpl<S, T> build() { Validate.notNull(this.name, "Name must be specified"); Validate.notNull(this.tooltip, "Tooltip must be specified"); Validate.notNull(this.binding, "Option binding must be specified"); Validate.notNull(this.control, "Control must be specified"); return new OptionImpl<>(this.storage, this.name, this.tooltip, this.binding, this.control, this.flags, this.impact, this.enabled); } } @Setter @Getter private Dim2i parentDimension; @Setter @Getter private Dim2i dim2i; @Setter @Getter private boolean highlight; @Setter @Getter private boolean selected; }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\gui\options\OptionPage.java
package me.jellysquid.mods.sodium.client.gui.options; import com.google.common.collect.ImmutableList; public class OptionPage { private final String name; private final ImmutableList<OptionGroup> groups; private final ImmutableList<Option<?>> options; public OptionPage(String name, ImmutableList<OptionGroup> groups) { this.name = name; this.groups = groups; ImmutableList.Builder<Option<?>> builder = ImmutableList.builder(); for (OptionGroup group : groups) { builder.addAll(group.getOptions()); } this.options = builder.build(); } public ImmutableList<OptionGroup> getGroups() { return this.groups; } public ImmutableList<Option<?>> getOptions() { return this.options; } public String getName() { return this.name; } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\gui\utils\Rect2i.java
package me.jellysquid.mods.sodium.client.gui.utils; public class Rect2i { private final int x; private final int y; private final int width; private final int height; public Rect2i(int i, int j, int k, int l) { this.x = i; this.y = j; this.width = k; this.height = l; } public int getX() { return this.x; } public int getY() { return this.y; } public int getWidth() { return this.width; } public int getHeight() { return this.height; } public boolean contains(int x, int y) { return x >= this.x && x <= this.x + this.width && y >= this.y && y <= this.y + this.height; } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\gui\utils\URLUtils.java
package me.jellysquid.mods.sodium.client.gui.utils; import me.jellysquid.mods.sodium.client.SodiumClientMod; import net.minecraft.util.Util; import java.io.IOException; public class URLUtils { private static String[] getURLOpenCommand(String url) { return switch (Util.getOSType()) { case WINDOWS -> new String[]{"rundll32", "url.dll,FileProtocolHandler", url}; case OSX -> new String[]{"open", url}; case UNKNOWN, LINUX, SOLARIS -> new String[]{"xdg-open", url}; }; } public static void open(String url) { try { Runtime.getRuntime().exec(getURLOpenCommand(url)); } catch (IOException exception) { SodiumClientMod.logger().error("Couldn't open url '{}'", url, exception); } } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\gui\widgets\AbstractWidget.java
package me.jellysquid.mods.sodium.client.gui.widgets; import com.gtnewhorizons.angelica.compat.mojang.Drawable; import com.gtnewhorizons.angelica.compat.mojang.Element; import com.gtnewhorizons.angelica.glsm.GLStateManager; import net.minecraft.client.Minecraft; import net.minecraft.client.audio.PositionedSoundRecord; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.renderer.Tessellator; import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.GL11; import java.util.function.Consumer; public abstract class AbstractWidget implements Drawable, Element { protected final FontRenderer font; protected AbstractWidget() { this.font = Minecraft.getMinecraft().fontRenderer; } protected void drawString(String str, int x, int y, int color) { this.font.drawString(str, x, y, color); } protected void drawRect(double x1, double y1, double x2, double y2, int color) { final float a = (float) (color >> 24 & 255) / 255.0F; final float r = (float) (color >> 16 & 255) / 255.0F; final float g = (float) (color >> 8 & 255) / 255.0F; final float b = (float) (color & 255) / 255.0F; this.drawQuads(vertices -> addQuad(vertices, x1, y1, x2, y2, a, r, g, b)); } protected void drawQuads(Consumer<Tessellator> consumer) { GL11.glEnable(GL11.GL_BLEND); GL11.glDisable(GL11.GL_TEXTURE_2D); GLStateManager.defaultBlendFunc(); final Tessellator tessellator = Tessellator.instance; tessellator.startDrawingQuads(); consumer.accept(tessellator); tessellator.draw(); GL11.glEnable(GL11.GL_TEXTURE_2D); GL11.glDisable(GL11.GL_BLEND); } protected static void addQuad(Tessellator consumer, double x1, double y1, double x2, double y2, float a, float r, float g, float b) { consumer.setColorRGBA_F(r, g, b, a); consumer.addVertex(x2, y1, 0.0D); consumer.addVertex(x1, y1, 0.0D); consumer.addVertex(x1, y2, 0.0D); consumer.addVertex(x2, y2, 0.0D); } protected void playClickSound() { Minecraft.getMinecraft().getSoundHandler().playSound(PositionedSoundRecord.func_147674_a(new ResourceLocation("gui.button.press"), 1.0F)); } protected int getTextWidth(String text) { return this.font.getStringWidth(text); } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\gui\widgets\FlatButtonWidget.java
package me.jellysquid.mods.sodium.client.gui.widgets; import com.gtnewhorizons.angelica.compat.mojang.Drawable; import lombok.Setter; import me.jellysquid.mods.sodium.client.util.Dim2i; public class FlatButtonWidget extends AbstractWidget implements Drawable { private final Dim2i dim; private final String label; private final Runnable action; @Setter private boolean selected; @Setter private boolean enabled = true; @Setter private boolean visible = true; @Setter private boolean leftAligned; public FlatButtonWidget(Dim2i dim, String label, Runnable action) { this.dim = dim; this.label = label; this.action = action; } @Override public void render(int mouseX, int mouseY, float delta) { if (!this.visible) { return; } final boolean hovered = this.dim.containsCursor(mouseX, mouseY); final int backgroundColor = this.enabled ? (hovered ? 0xE0000000 : 0x90000000) : 0x60000000; final int textColor = this.enabled ? 0xFFFFFFFF : 0x90FFFFFF; final int strWidth = this.font.getStringWidth(this.label); this.drawRect(this.dim.getOriginX(), this.dim.getOriginY(), this.dim.getLimitX(), this.dim.getLimitY(), backgroundColor); final int x = leftAligned ? this.dim.getOriginX() + 10 : this.dim.getCenterX() - (strWidth / 2); this.drawString(this.label, x, this.dim.getCenterY() - 4, textColor); if (this.enabled && this.selected) { this.drawRect(this.dim.getOriginX(), leftAligned ? this.dim.getOriginY() : (this.dim.getLimitY() - 1), this.leftAligned ? (this.dim.getOriginX() + 1) : this.dim.getLimitX(), this.dim.getLimitY(), 0xFF94E4D3); } } @Override public boolean mouseClicked(double mouseX, double mouseY, int button) { if (!this.enabled || !this.visible) { return false; } if (button == 0 && this.dim.containsCursor(mouseX, mouseY)) { this.action.run(); this.playClickSound(); return true; } return false; } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\gui\options\binding\GenericBinding.java
package me.jellysquid.mods.sodium.client.gui.options.binding; import java.util.function.BiConsumer; import java.util.function.Function; public class GenericBinding<S, T> implements OptionBinding<S, T> { private final BiConsumer<S, T> setter; private final Function<S, T> getter; public GenericBinding(BiConsumer<S, T> setter, Function<S, T> getter) { this.setter = setter; this.getter = getter; } @Override public void setValue(S storage, T value) { this.setter.accept(storage, value); } @Override public T getValue(S storage) { return this.getter.apply(storage); } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\gui\options\binding\OptionBinding.java
package me.jellysquid.mods.sodium.client.gui.options.binding; public interface OptionBinding<S, T> { void setValue(S storage, T value); T getValue(S storage); }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\gui\options\control\Control.java
package me.jellysquid.mods.sodium.client.gui.options.control; import me.jellysquid.mods.sodium.client.gui.options.Option; import me.jellysquid.mods.sodium.client.gui.options.control.element.ControlElementFactory; import me.jellysquid.mods.sodium.client.util.Dim2i; public interface Control<T> { Option<T> getOption(); ControlElement<T> createElement(Dim2i dim, ControlElementFactory factory); int getMaxWidth(); }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\gui\options\control\ControlElement.java
package me.jellysquid.mods.sodium.client.gui.options.control; import me.jellysquid.mods.sodium.client.gui.options.Option; import me.jellysquid.mods.sodium.client.util.Dim2i; public interface ControlElement<T> { boolean isHovered(); Option<T> getOption(); Dim2i getDimensions(); }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\gui\options\control\ControlValueFormatter.java
package me.jellysquid.mods.sodium.client.gui.options.control; import net.minecraft.client.resources.I18n; public interface ControlValueFormatter { static ControlValueFormatter guiScale() { return (v) -> (v == 0) ? I18n.format("options.guiScale.auto") : I18n.format(v + "x"); } static ControlValueFormatter fpsLimit() { return (v) -> (v == 260) ? I18n.format("options.framerateLimit.max") : I18n.format("options.framerate", v); } static ControlValueFormatter droppedItemLimitLimit() { return (v) -> (v == 2048) ? I18n.format("options.droppedItems.max") : I18n.format("options.droppedItems", v); } static ControlValueFormatter brightness() { return (v) -> { if (v == 0) { return I18n.format("options.gamma.min"); } else if (v == 100) { return I18n.format("options.gamma.max"); } else { return v + "%"; } }; } String format(int value); static ControlValueFormatter percentage() { return (v) -> v + "%"; } static ControlValueFormatter multiplier() { return (v) -> v + "x"; } static ControlValueFormatter quantity(String name) { return (v) -> I18n.format(name, v); } static ControlValueFormatter quantityOrDisabled(String name, String disableText) { return (v) -> I18n.format(v == 0 ? disableText : name, v); } static ControlValueFormatter number() { return String::valueOf; } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\gui\options\control\CyclingControl.java
package me.jellysquid.mods.sodium.client.gui.options.control; import me.jellysquid.mods.sodium.client.gui.options.Option; import me.jellysquid.mods.sodium.client.gui.options.control.element.ControlElementFactory; import me.jellysquid.mods.sodium.client.gui.options.named.NamedState; import me.jellysquid.mods.sodium.client.util.Dim2i; import net.minecraft.client.resources.I18n; import org.apache.commons.lang3.Validate; public class CyclingControl<T extends Enum<T>> implements Control<T> { private final Option<T> option; private final T[] allowedValues; private final String[] names; public CyclingControl(Option<T> option, Class<T> enumType) { this(option, enumType, enumType.getEnumConstants()); } public CyclingControl(Option<T> option, Class<T> enumType, String[] names) { final T[] universe = enumType.getEnumConstants(); Validate.isTrue(universe.length == names.length, "Mismatch between universe length and names array length"); Validate.notEmpty(universe, "The enum universe must contain at least one item"); this.option = option; this.allowedValues = universe; this.names = names; } public CyclingControl(Option<T> option, Class<T> enumType, T[] allowedValues) { final T[] universe = enumType.getEnumConstants(); this.option = option; this.allowedValues = allowedValues; this.names = new String[universe.length]; for (int i = 0; i < this.names.length; i++) { final String name; final T value = universe[i]; name = I18n.format(value instanceof NamedState namedState ? namedState.getKey() : value.name()); this.names[i] = name; } } @Override public Option<T> getOption() { return this.option; } @Override public ControlElement<T> createElement(Dim2i dim, ControlElementFactory factory) { return factory.cyclingControlElement(this.option, dim, this.allowedValues, this.names); } @Override public int getMaxWidth() { return 70; } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\gui\options\control\SliderControl.java
package me.jellysquid.mods.sodium.client.gui.options.control; import me.jellysquid.mods.sodium.client.gui.options.Option; import me.jellysquid.mods.sodium.client.gui.options.control.element.ControlElementFactory; import me.jellysquid.mods.sodium.client.util.Dim2i; import org.apache.commons.lang3.Validate; public class SliderControl implements Control<Integer> { private final Option<Integer> option; private final int min, max, interval; private final ControlValueFormatter mode; public SliderControl(Option<Integer> option, int min, int max, int interval, ControlValueFormatter mode) { Validate.isTrue(max > min, "The maximum value must be greater than the minimum value"); Validate.isTrue(interval > 0, "The slider interval must be greater than zero"); Validate.isTrue(((max - min) % interval) == 0, "The maximum value must be divisable by the interval"); Validate.notNull(mode, "The slider mode must not be null"); this.option = option; this.min = min; this.max = max; this.interval = interval; this.mode = mode; } @Override public ControlElement<Integer> createElement(Dim2i dim, ControlElementFactory factory) { return factory.sliderControlElement(this.option, dim, this.min, this.max, this.interval, this.mode); } @Override public Option<Integer> getOption() { return this.option; } @Override public int getMaxWidth() { return 130; } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\gui\options\control\TickBoxControl.java
package me.jellysquid.mods.sodium.client.gui.options.control; import me.jellysquid.mods.sodium.client.gui.options.Option; import me.jellysquid.mods.sodium.client.gui.options.control.element.ControlElementFactory; import me.jellysquid.mods.sodium.client.util.Dim2i; public class TickBoxControl implements Control<Boolean> { private final Option<Boolean> option; public TickBoxControl(Option<Boolean> option) { this.option = option; } @Override public ControlElement<Boolean> createElement(Dim2i dim, ControlElementFactory factory) { return factory.tickBoxElement(this.option, dim); } @Override public int getMaxWidth() { return 30; } @Override public Option<Boolean> getOption() { return this.option; } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\gui\options\named\GraphicsMode.java
package me.jellysquid.mods.sodium.client.gui.options.named; public enum GraphicsMode implements NamedState { FANCY("options.graphics.fancy"), FAST("options.graphics.fast"); private final String name; GraphicsMode(String name) { this.name = name; } @Override public String getKey() { return this.name; } public boolean isFancy() { return this == FANCY; } public static GraphicsMode fromBoolean(boolean isFancy) { return isFancy ? FANCY : FAST; } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\gui\options\named\GraphicsQuality.java
package me.jellysquid.mods.sodium.client.gui.options.named; import net.minecraft.client.Minecraft; public enum GraphicsQuality implements NamedState { DEFAULT("generator.default"), FANCY("options.graphics.fancy"), FAST("options.graphics.fast"); private final String name; GraphicsQuality(String name) { this.name = name; } @Override public String getKey() { return this.name; } public boolean isFancy() { return this == FANCY || (this == DEFAULT && Minecraft.getMinecraft().gameSettings.fancyGraphics); } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\gui\options\named\LightingQuality.java
package me.jellysquid.mods.sodium.client.gui.options.named; import net.minecraft.util.MathHelper; public enum LightingQuality implements NamedState { OFF("options.ao.off"), LOW("options.ao.min"), HIGH("options.ao.max"); private static final LightingQuality[] VALUES = values(); private final String name; private final int vanilla; LightingQuality(String name) { this.name = name; this.vanilla = ordinal(); } @Override public String getKey() { return this.name; } public int getVanilla() { return vanilla; } public static LightingQuality fromOrdinal(int ordinal) { return VALUES[MathHelper.clamp_int(ordinal, 0, VALUES.length - 1)]; } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\gui\options\named\NamedState.java
package me.jellysquid.mods.sodium.client.gui.options.named; public interface NamedState { String getKey(); }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\gui\options\named\ParticleMode.java
package me.jellysquid.mods.sodium.client.gui.options.named; import net.minecraft.util.MathHelper; public enum ParticleMode implements NamedState { ALL("options.particles.all"), DECREASED("options.particles.decreased"), MINIMAL("options.particles.minimal"); private static final ParticleMode[] VALUES = values(); private final String name; ParticleMode(String name) { this.name = name; } @Override public String getKey() { return this.name; } public static ParticleMode fromOrdinal(int ordinal) { return VALUES[MathHelper.clamp_int(ordinal, 0, VALUES.length - 1)]; } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\gui\options\storage\AngelicaOptionsStorage.java
package me.jellysquid.mods.sodium.client.gui.options.storage; import com.gtnewhorizon.gtnhlib.config.ConfigurationManager; import com.gtnewhorizons.angelica.config.AngelicaConfig; import me.jellysquid.mods.sodium.client.SodiumClientMod; public class AngelicaOptionsStorage implements OptionStorage<AngelicaConfig> { public AngelicaOptionsStorage() { } @Override public AngelicaConfig getData() { return null; } @Override public void save() { ConfigurationManager.save(AngelicaConfig.class); SodiumClientMod.logger().info("Flushed changes to Angelica configuration"); } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\gui\options\storage\MinecraftOptionsStorage.java
package me.jellysquid.mods.sodium.client.gui.options.storage; import me.jellysquid.mods.sodium.client.SodiumClientMod; import net.minecraft.client.Minecraft; import net.minecraft.client.settings.GameSettings; public class MinecraftOptionsStorage implements OptionStorage<GameSettings> { private final Minecraft client; public MinecraftOptionsStorage() { this.client = Minecraft.getMinecraft(); } @Override public GameSettings getData() { return this.client.gameSettings; } @Override public void save() { this.getData().saveOptions(); SodiumClientMod.logger().info("Flushed changes to Minecraft configuration"); } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\gui\options\storage\OptionStorage.java
package me.jellysquid.mods.sodium.client.gui.options.storage; public interface OptionStorage<T> { T getData(); void save(); }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\gui\options\storage\SodiumOptionsStorage.java
package me.jellysquid.mods.sodium.client.gui.options.storage; import me.jellysquid.mods.sodium.client.SodiumClientMod; import me.jellysquid.mods.sodium.client.gui.SodiumGameOptions; import java.io.IOException; public class SodiumOptionsStorage implements OptionStorage<SodiumGameOptions> { private final SodiumGameOptions options; public SodiumOptionsStorage() { this.options = SodiumClientMod.options(); } @Override public SodiumGameOptions getData() { return this.options; } @Override public void save() { try { this.options.writeChanges(); } catch (IOException e) { throw new RuntimeException("Couldn't save configuration changes", e); } SodiumClientMod.logger().info("Flushed changes to Angelica configuration"); } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\gui\options\control\element\ControlElementFactory.java
package me.jellysquid.mods.sodium.client.gui.options.control.element; import me.jellysquid.mods.sodium.client.gui.options.Option; import me.jellysquid.mods.sodium.client.gui.options.control.ControlElement; import me.jellysquid.mods.sodium.client.gui.options.control.ControlValueFormatter; import me.jellysquid.mods.sodium.client.util.Dim2i; public interface ControlElementFactory { <T extends Enum<T>> ControlElement<T> cyclingControlElement(Option<T> option, Dim2i dim, T[] allowedValues, String[] names); ControlElement<Integer> sliderControlElement(Option<Integer> option, Dim2i dim, int min, int max, int interval, ControlValueFormatter formatter); ControlElement<Boolean> tickBoxElement(Option<Boolean> option, Dim2i dim); }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\gui\options\control\element\SodiumControlElement.java
package me.jellysquid.mods.sodium.client.gui.options.control.element; import me.flashyreese.mods.reeses_sodium_options.client.gui.OptionExtended; import me.jellysquid.mods.sodium.client.gui.options.Option; import me.jellysquid.mods.sodium.client.gui.options.control.ControlElement; import me.jellysquid.mods.sodium.client.gui.widgets.AbstractWidget; import me.jellysquid.mods.sodium.client.util.Dim2i; import net.minecraft.util.EnumChatFormatting; public class SodiumControlElement<T> extends AbstractWidget implements ControlElement<T> { protected final Option<T> option; protected final Dim2i dim; protected boolean hovered; public SodiumControlElement(Option<T> option, Dim2i dim) { this.option = option; this.dim = dim; if(option instanceof OptionExtended<?> optionExtended) { optionExtended.setDim2i(dim); } } @Override public void render(int mouseX, int mouseY, float delta) { String name = this.option.getName(); String label; if (this.hovered && this.font.getStringWidth(name) > (this.dim.getWidth() - this.option.getControl().getMaxWidth())) { name = name.substring(0, Math.min(name.length(), 10)) + "..."; } if (this.option.isAvailable()) { if (this.option.hasChanged()) { label = EnumChatFormatting.ITALIC + name + " *"; } else { label = EnumChatFormatting.WHITE + name; } } else { label = String.valueOf(EnumChatFormatting.GRAY) + EnumChatFormatting.STRIKETHROUGH + name; } this.hovered = this.dim.containsCursor(mouseX, mouseY); this.drawRect(this.dim.getOriginX(), this.dim.getOriginY(), this.dim.getLimitX(), this.dim.getLimitY(), this.hovered ? 0xE0000000 : 0x90000000); if(option instanceof OptionExtended<?> optionExtended && (optionExtended.isHighlight())) { final String replacement = optionExtended.isSelected() ? EnumChatFormatting.DARK_GREEN.toString() : EnumChatFormatting.YELLOW.toString(); label = label.replace(EnumChatFormatting.WHITE.toString(), EnumChatFormatting.WHITE + replacement); label = label.replace(EnumChatFormatting.STRIKETHROUGH.toString(), EnumChatFormatting.STRIKETHROUGH + replacement); label = label.replace(EnumChatFormatting.ITALIC.toString(), EnumChatFormatting.ITALIC + replacement); } this.drawString(label, this.dim.getOriginX() + 6, this.dim.getCenterY() - 4, 0xFFFFFFFF); } @Override public boolean isHovered() { return this.hovered; } @Override public Option<T> getOption() { return this.option; } @Override public Dim2i getDimensions() { return this.dim; } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\gui\options\control\element\SodiumControlElementFactory.java
package me.jellysquid.mods.sodium.client.gui.options.control.element; import com.gtnewhorizons.angelica.config.AngelicaConfig; import me.jellysquid.mods.sodium.client.gui.options.Option; import me.jellysquid.mods.sodium.client.gui.options.control.ControlElement; import me.jellysquid.mods.sodium.client.gui.options.control.ControlValueFormatter; import me.jellysquid.mods.sodium.client.gui.utils.Rect2i; import me.jellysquid.mods.sodium.client.util.Dim2i; import net.minecraft.util.MathHelper; public class SodiumControlElementFactory implements ControlElementFactory { @Override public <T extends Enum<T>> ControlElement<T> cyclingControlElement(Option<T> option, Dim2i dim, T[] allowedValues, String[] names) { return new CyclingControlElement<>(option, dim, allowedValues, names); } @Override public ControlElement<Integer> sliderControlElement(Option<Integer> option, Dim2i dim, int min, int max, int interval, ControlValueFormatter formatter) { return new SliderControlElement(option, dim, min, max, interval, formatter); } @Override public ControlElement<Boolean> tickBoxElement(Option<Boolean> option, Dim2i dim) { return new TickBoxControlElement(option, dim); } private static class CyclingControlElement<T extends Enum<T>> extends SodiumControlElement<T> { private final T[] allowedValues; private final String[] names; private int currentIndex; public CyclingControlElement(Option<T> option, Dim2i dim, T[] allowedValues, String[] names) { super(option, dim); this.allowedValues = allowedValues; this.names = names; this.currentIndex = 0; for (int i = 0; i < allowedValues.length; i++) { if (allowedValues[i] == option.getValue()) { this.currentIndex = i; break; } } } @Override public void render(int mouseX, int mouseY, float delta) { super.render(mouseX, mouseY, delta); Enum<T> value = this.option.getValue(); String name = this.names[value.ordinal()]; int strWidth = this.getTextWidth(name); this.drawString(name, this.dim.getLimitX() - strWidth - 6, this.dim.getCenterY() - 4, 0xFFFFFFFF); } @Override public boolean mouseClicked(double mouseX, double mouseY, int button) { if(AngelicaConfig.enableReesesSodiumOptions) { if (this.option.isAvailable() && this.dim.containsCursor(mouseX, mouseY) && (button == 0 || button == 1)) { this.currentIndex = Math.floorMod(this.option.getValue().ordinal() + (button == 0 ? 1 : -1), this.allowedValues.length); this.option.setValue(this.allowedValues[this.currentIndex]); this.playClickSound(); return true; } } else { if (this.option.isAvailable() && button == 0 && this.dim.containsCursor(mouseX, mouseY)) { this.currentIndex = (this.option.getValue().ordinal() + 1) % this.allowedValues.length; this.option.setValue(this.allowedValues[this.currentIndex]); this.playClickSound(); return true; } } return false; } } private static class SliderControlElement extends SodiumControlElement<Integer> { private static final int THUMB_WIDTH = 2, TRACK_HEIGHT = 1; private final Rect2i sliderBounds; private final ControlValueFormatter formatter; private final int min; private final int range; private final int interval; private double thumbPosition; public SliderControlElement(Option<Integer> option, Dim2i dim, int min, int max, int interval, ControlValueFormatter formatter) { super(option, dim); this.min = min; this.range = max - min; this.interval = interval; this.thumbPosition = this.getThumbPositionForValue(option.getValue()); this.formatter = formatter; this.sliderBounds = new Rect2i(dim.getLimitX() - 96, dim.getCenterY() - 5, 90, 10); } @Override public void render(int mouseX, int mouseY, float delta) { super.render(mouseX, mouseY, delta); if (this.option.isAvailable() && this.hovered) { this.renderSlider(); } else { this.renderStandaloneValue(); } } private void renderStandaloneValue() { int sliderX = this.sliderBounds.getX(); int sliderY = this.sliderBounds.getY(); int sliderWidth = this.sliderBounds.getWidth(); int sliderHeight = this.sliderBounds.getHeight(); String label = this.formatter.format(this.option.getValue()); int labelWidth = this.font.getStringWidth(label); this.drawString(label, sliderX + sliderWidth - labelWidth, sliderY + (sliderHeight / 2) - 4, 0xFFFFFFFF); } private void renderSlider() { int sliderX = this.sliderBounds.getX(); int sliderY = this.sliderBounds.getY(); int sliderWidth = this.sliderBounds.getWidth(); int sliderHeight = this.sliderBounds.getHeight(); this.thumbPosition = this.getThumbPositionForValue(option.getValue()); double thumbOffset = MathHelper.clamp_double((double) (this.getIntValue() - this.min) / this.range * sliderWidth, 0, sliderWidth); double thumbX = sliderX + thumbOffset - THUMB_WIDTH; double trackY = sliderY + (sliderHeight / 2) - ((double) TRACK_HEIGHT / 2); this.drawRect(thumbX, sliderY, thumbX + (THUMB_WIDTH * 2), sliderY + sliderHeight, 0xFFFFFFFF); this.drawRect(sliderX, trackY, sliderX + sliderWidth, trackY + TRACK_HEIGHT, 0xFFFFFFFF); String label = String.valueOf(this.getIntValue()); int labelWidth = this.font.getStringWidth(label); this.drawString(label, sliderX - labelWidth - 6, sliderY + (sliderHeight / 2) - 4, 0xFFFFFFFF); } public int getIntValue() { return this.min + (this.interval * (int) Math.round(this.getSnappedThumbPosition() / this.interval)); } public double getSnappedThumbPosition() { return this.thumbPosition / (1.0D / this.range); } public double getThumbPositionForValue(int value) { return (value - this.min) * (1.0D / this.range); } @Override public boolean mouseClicked(double mouseX, double mouseY, int button) { if (this.option.isAvailable() && button == 0 && this.sliderBounds.contains((int) mouseX, (int) mouseY)) { this.setValueFromMouse(mouseX); return true; } return false; } private void setValueFromMouse(double d) { this.setValue((d - (double) this.sliderBounds.getX()) / (double) this.sliderBounds.getWidth()); } private void setValue(double d) { this.thumbPosition = MathHelper.clamp_double(d, 0.0D, 1.0D); int value = this.getIntValue(); if (this.option.getValue() != value) { this.option.setValue(value); } } @Override public boolean mouseDragged(double mouseX, double mouseY, int button) { if (this.option.isAvailable() && this.sliderBounds.contains((int) mouseX, (int) mouseY)) { this.setValueFromMouse(mouseX); return true; } return false; } } private static class TickBoxControlElement extends SodiumControlElement<Boolean> { private final Rect2i button; public TickBoxControlElement(Option<Boolean> option, Dim2i dim) { super(option, dim); this.button = new Rect2i(dim.getLimitX() - 16, dim.getCenterY() - 5, 10, 10); } @Override public void render(int mouseX, int mouseY, float delta) { super.render(mouseX, mouseY, delta); final int x = this.button.getX(); final int y = this.button.getY(); final int w = x + this.button.getWidth(); final int h = y + this.button.getHeight(); final boolean enabled = this.option.isAvailable(); final boolean ticked = enabled && this.option.getValue(); final int color; if (enabled) { color = ticked ? 0xFF94E4D3 : 0xFFFFFFFF; } else { color = 0xFFAAAAAA; } if (ticked) { this.drawRect(x + 2, y + 2, w - 2, h - 2, color); } this.drawRectOutline(x, y, w, h, color); } @Override public boolean mouseClicked(double mouseX, double mouseY, int button) { if (this.option.isAvailable() && button == 0 && this.dim.containsCursor(mouseX, mouseY)) { this.option.setValue(!this.option.getValue()); this.playClickSound(); return true; } return false; } protected void drawRectOutline(int x, int y, int w, int h, int color) { final float a = (float) (color >> 24 & 255) / 255.0F; final float r = (float) (color >> 16 & 255) / 255.0F; final float g = (float) (color >> 8 & 255) / 255.0F; final float b = (float) (color & 255) / 255.0F; this.drawQuads(vertices -> { addQuad(vertices, x, y, w, y + 1, a, r, g, b); addQuad(vertices, x, h - 1, w, h, a, r, g, b); addQuad(vertices, x, y, x + 1, h, a, r, g, b); addQuad(vertices, w - 1, y, w, h, a, r, g, b); }); } } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\light\EntityLighter.java
package me.jellysquid.mods.sodium.client.model.light; import com.gtnewhorizon.gtnhlib.blockpos.BlockPos; import net.minecraft.util.MathHelper; import net.minecraft.entity.Entity; import net.minecraft.world.EnumSkyBlock; import static org.joml.Math.lerp; public class EntityLighter { private static final double MIN_BOX_SIZE = 0.001D; private static final double MAX_LIGHT_VAL = 15.0; private static final double MAX_LIGHTMAP_COORD = 240.0D; public static int getBlendedLight(Entity entity, float tickDelta) { final boolean calcBlockLight = !entity.isBurning(); // Find the interpolated position of the entity final double x1 = lerp(entity.prevPosX, entity.posX, tickDelta); final double y1 = lerp(entity.prevPosY, entity.posY, tickDelta); final double z1 = lerp(entity.prevPosZ, entity.posZ, tickDelta); // Bounding boxes with no volume cause issues, ensure they're non-zero // Notably, armor stands in "Marker" mode decide this is a cute thing to do // https://github.com/jellysquid3/sodium-fabric/issues/60 final double width = Math.max(entity.width, MIN_BOX_SIZE); final double height = Math.max(entity.height, MIN_BOX_SIZE); final double x2 = x1 + width; final double y2 = y1 + height; final double z2 = z1 + width; // The sampling volume of blocks which could possibly contribute light to this entity final int bMinX = MathHelper.floor_double(x1); final int bMinY = MathHelper.floor_double(y1); final int bMinZ = MathHelper.floor_double(z1); final int bMaxX = MathHelper.ceiling_double_int(x2); final int bMaxY = MathHelper.ceiling_double_int(y2); final int bMaxZ = MathHelper.ceiling_double_int(z2); // The maximum amount of light that could be contributed double max = 0.0D; // The sampled light values contributed by all sources double sl = 0; double bl = 0; final BlockPos pos = new BlockPos(); // Iterate over every block in the sampling volume for (int bX = bMinX; bX < bMaxX; bX++) { final double ix1 = Math.max(bX, x1); final double ix2 = Math.min(bX + 1, x2); for (int bY = bMinY; bY < bMaxY; bY++) { final double iy1 = Math.max(bY, y1); final double iy2 = Math.min(bY + 1, y2); for (int bZ = bMinZ; bZ < bMaxZ; bZ++) { pos.set(bX, bY, bZ); // Do not consider light-blocking volumes if (entity.worldObj.getBlock(pos.x, pos.y, pos.z).isOpaqueCube() && entity.worldObj.getBlockLightValue(pos.x, pos.y, pos.z) <= 0) { continue; } // Find the intersecting volume between the entity box and the block's bounding box final double iz1 = Math.max(bZ, z1); final double iz2 = Math.min(bZ + 1, z2); // The amount of light this block can contribute is the volume of the intersecting box final double weight = (ix2 - ix1) * (iy2 - iy1) * (iz2 - iz1); // Keep count of how much light could've been contributed max += weight; // note: lighter.bridge$getSkyLight(entity, pos) and lighter.bridge$getBlockLight(entity, pos) // were replaced, mixin+this method de-generified. as far as I can tell they only existed because // Sodium had a weird setup just for paintings, don't think we need it. // Sum the light actually contributed by this volume sl += weight * (entity.worldObj.getSkyBlockTypeBrightness(EnumSkyBlock.Sky, pos.x, pos.y, pos.z) / MAX_LIGHT_VAL); if (calcBlockLight) { bl += weight * (entity.worldObj.getSkyBlockTypeBrightness(EnumSkyBlock.Block, pos.x, pos.y, pos.z) / MAX_LIGHT_VAL); } else { bl += weight; } } } } // The final light value is calculated from the percentage of light contributed out of the total maximum final int bli = MathHelper.floor_double((bl / max) * MAX_LIGHTMAP_COORD); final int sli = MathHelper.floor_double((sl / max) * MAX_LIGHTMAP_COORD); return ((sli & 0xFFFF) << 16) | (bli & 0xFFFF); } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\light\LightMode.java
package me.jellysquid.mods.sodium.client.model.light; public enum LightMode { SMOOTH, FLAT }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\light\LightPipeline.java
package me.jellysquid.mods.sodium.client.model.light; import com.gtnewhorizon.gtnhlib.blockpos.BlockPos; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuadView; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.properties.ModelQuadFacing; import me.jellysquid.mods.sodium.client.model.light.data.QuadLightData; /** * Light pipelines allow model quads for any location in the world to be lit using various backends, including fluids * and block entities. */ public interface LightPipeline { /** * Calculates the light data for a given block model quad, storing the result in {@param out}. * @param quad The block model quad * @param pos The block position of the model this quad belongs to * @param out The data arrays which will store the calculated light data results * @param face The pre-computed facing vector of the quad * @param shade True if the block is shaded by ambient occlusion */ void calculate(ModelQuadView quad, BlockPos pos, QuadLightData out, ModelQuadFacing cullFace, ModelQuadFacing face, boolean shade); }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\light\LightPipelineProvider.java
package me.jellysquid.mods.sodium.client.model.light; import me.jellysquid.mods.sodium.client.model.light.data.LightDataAccess; import me.jellysquid.mods.sodium.client.model.light.flat.FlatLightPipeline; import me.jellysquid.mods.sodium.client.model.light.smooth.SmoothLightPipeline; import java.util.EnumMap; public class LightPipelineProvider { private final EnumMap<LightMode, LightPipeline> lighters = new EnumMap<>(LightMode.class); public LightPipelineProvider(LightDataAccess cache) { this.lighters.put(LightMode.SMOOTH, new SmoothLightPipeline(cache)); this.lighters.put(LightMode.FLAT, new FlatLightPipeline(cache)); } public LightPipeline getLighter(LightMode type) { LightPipeline pipeline = this.lighters.get(type); if (pipeline == null) { throw new NullPointerException("No lighter exists for mode: " + type.name()); } return pipeline; } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\vertex\VanillaVertexTypes.java
package me.jellysquid.mods.sodium.client.model.vertex; import me.jellysquid.mods.sodium.client.model.vertex.formats.glyph.GlyphVertexSink; import me.jellysquid.mods.sodium.client.model.vertex.formats.glyph.GlyphVertexType; import me.jellysquid.mods.sodium.client.model.vertex.formats.line.LineVertexSink; import me.jellysquid.mods.sodium.client.model.vertex.formats.line.LineVertexType; import me.jellysquid.mods.sodium.client.model.vertex.formats.particle.ParticleVertexSink; import me.jellysquid.mods.sodium.client.model.vertex.formats.particle.ParticleVertexType; import me.jellysquid.mods.sodium.client.model.vertex.formats.quad.QuadVertexSink; import me.jellysquid.mods.sodium.client.model.vertex.formats.quad.QuadVertexType; import me.jellysquid.mods.sodium.client.model.vertex.formats.screen_quad.BasicScreenQuadVertexSink; import me.jellysquid.mods.sodium.client.model.vertex.formats.screen_quad.BasicScreenQuadVertexType; import me.jellysquid.mods.sodium.client.model.vertex.type.VanillaVertexType; public class VanillaVertexTypes { public static final VanillaVertexType<QuadVertexSink> QUADS = new QuadVertexType(); public static final VanillaVertexType<LineVertexSink> LINES = new LineVertexType(); public static final VanillaVertexType<GlyphVertexSink> GLYPHS = new GlyphVertexType(); public static final VanillaVertexType<ParticleVertexSink> PARTICLES = new ParticleVertexType(); public static final VanillaVertexType<BasicScreenQuadVertexSink> BASIC_SCREEN_QUADS = new BasicScreenQuadVertexType(); }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\vertex\VertexDrain.java
package me.jellysquid.mods.sodium.client.model.vertex; import com.gtnewhorizons.angelica.compat.toremove.VertexConsumer; import me.jellysquid.mods.sodium.client.model.vertex.type.VertexType; /** * A drain allows the instantiation of {@link VertexSink} and is implemented on outputs which take vertex data. */ public interface VertexDrain { /** * Returns a {@link VertexDrain} implementation on the provided {@link VertexConsumer}. Since the interface * is always implemented on a given VertexConsumer, this is simply implemented as a cast internally. * @param consumer The {@link VertexConsumer} * @return A {@link VertexDrain} */ static VertexDrain of(VertexConsumer consumer) { return (VertexDrain) consumer; } /** * Returns a {@link VertexSink} of type {@link T}, created from {@param factory}, which transforms and writes * vertices through this vertex drain. * * @param factory The factory to create a vertex sink using * @param <T> The vertex sink's type * @return A new {@link VertexSink} of type {@link T} */ <T extends VertexSink> T createSink(VertexType<T> factory); }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\vertex\VertexSink.java
package me.jellysquid.mods.sodium.client.model.vertex; /** * Vertex sinks allow vertex data to be quickly written out to a {@link VertexDrain} while providing * compile-time data format contracts. Generally, you will want a format-specific vertex sink, such as * {@link me.jellysquid.mods.sodium.client.model.vertex.formats.quad.QuadVertexSink} in order to write * vertex data. */ public interface VertexSink { /** * Ensures the backing storage to this sink has enough space for the given number of vertices to be written. This * should be called with the number of vertices you expect to write before you make calls to write vertices. * * If the caller tries to write vertices without calling this method, or writes more vertices than they ensured * there was capacity for, an {@link java.nio.BufferUnderflowException} may occur. * * When writing batches of vertices (such as those belonging to a primitive or a large model), it is best practice * to simply call this method once at the start with the number of vertices you plan to write. This ensures the * backing storage will only be resized once (if necessary) to fit the incoming vertex data. * * @param count The number of vertices */ void ensureCapacity(int count); /** * Flushes any written vertex data to the {@link VertexDrain} this sink is connected to, ensuring it is actually * written to the backing storage. This should be called after vertex data has been written to this sink. * * It is valid to flush a sink at any time. Only vertices that have been written since the last flush will be * flushed when calling this method. If no vertices need to be flushed, this method does nothing. * * For optimal performance, callers should wait until they have written out as much vertex data as possible before * flushing, in effect batching their writes. */ void flush(); }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\light\cache\ArrayLightDataCache.java
package me.jellysquid.mods.sodium.client.model.light.cache; import com.gtnewhorizons.angelica.compat.mojang.ChunkSectionPos; import me.jellysquid.mods.sodium.client.model.light.data.LightDataAccess; import me.jellysquid.mods.sodium.client.world.WorldSlice; import java.util.Arrays; /** * A light data cache which uses a flat-array to store the light data for the blocks in a given chunk and its direct * neighbors. This is considerably faster than using a hash table to lookup values for a given block position and * can be re-used by {@link WorldSlice} to avoid allocations. */ public class ArrayLightDataCache extends LightDataAccess { private static final int NEIGHBOR_BLOCK_RADIUS = 2; private static final int BLOCK_LENGTH = 16 + (NEIGHBOR_BLOCK_RADIUS * 2); private final long[] light; private int xOffset, yOffset, zOffset; public ArrayLightDataCache(WorldSlice world) { this.world = world; this.light = new long[BLOCK_LENGTH * BLOCK_LENGTH * BLOCK_LENGTH]; } public void reset(ChunkSectionPos origin) { this.xOffset = origin.getMinX() - NEIGHBOR_BLOCK_RADIUS; this.yOffset = origin.getMinY() - NEIGHBOR_BLOCK_RADIUS; this.zOffset = origin.getMinZ() - NEIGHBOR_BLOCK_RADIUS; Arrays.fill(this.light, 0L); } private int index(int x, int y, int z) { int x2 = x - this.xOffset; int y2 = y - this.yOffset; int z2 = z - this.zOffset; return (z2 * BLOCK_LENGTH * BLOCK_LENGTH) + (y2 * BLOCK_LENGTH) + x2; } @Override public long get(int x, int y, int z) { DynamicLightsPos.get().set(x, y, z); int l = this.index(x, y, z); long word = this.light[l]; if (word != 0) { return word; } return this.light[l] = this.compute(x, y, z); } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\light\cache\HashLightDataCache.java
package me.jellysquid.mods.sodium.client.model.light.cache; import com.gtnewhorizon.gtnhlib.blockpos.IBlockPos; import it.unimi.dsi.fastutil.longs.Long2LongLinkedOpenHashMap; import me.jellysquid.mods.sodium.client.model.light.data.LightDataAccess; import me.jellysquid.mods.sodium.client.world.WorldSlice; /** * A light data cache which uses a hash table to store previously accessed values. */ public class HashLightDataCache extends LightDataAccess { private final Long2LongLinkedOpenHashMap map = new Long2LongLinkedOpenHashMap(1024, 0.50f); public HashLightDataCache(WorldSlice world) { this.world = world; } @Override public long get(int x, int y, int z) { DynamicLightsPos.get().set(x, y, z); long key = IBlockPos.asLong(x, y, z); long word = this.map.getAndMoveToFirst(key); if (word == 0) { if (this.map.size() > 1024) { this.map.removeLastLong(); } this.map.put(key, word = this.compute(x, y, z)); } return word; } public void clearCache() { this.map.clear(); } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\light\data\LightDataAccess.java
package me.jellysquid.mods.sodium.client.model.light.data; import com.gtnewhorizon.gtnhlib.blockpos.BlockPos; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.properties.ModelQuadFacing; import com.gtnewhorizons.angelica.dynamiclights.DynamicLights; import me.jellysquid.mods.sodium.client.util.StateUtil; import me.jellysquid.mods.sodium.client.world.WorldSlice; import net.minecraft.block.Block; /** * The light data cache is used to make accessing the light data and occlusion properties of blocks cheaper. The data * for each block is stored as a long integer with packed fields in order to work around the lack of value types in Java. * * This code is not very pretty, but it does perform significantly faster than the vanilla implementation and has * good cache locality. * * Each long integer contains the following fields: * - OP: Block opacity test, true if opaque * - FO: Full block opaque test, true if opaque * - AO: Ambient occlusion, floating point value in the range of 0.0..1.0 encoded as an 12-bit unsigned integer * - LM: Light map texture coordinates, two packed UV shorts in an integer * * You can use the various static pack/unpack methods to extract these values in a usable format. */ public abstract class LightDataAccess { public static final ThreadLocal<BlockPos> DynamicLightsPos = ThreadLocal.withInitial(BlockPos::new); protected WorldSlice world; public long get(int x, int y, int z, ModelQuadFacing d1, ModelQuadFacing d2) { return this.get(x + d1.getStepX() + d2.getStepX(), y + d1.getStepY() + d2.getStepY(), z + d1.getStepZ() + d2.getStepZ()); } public long get(int x, int y, int z, ModelQuadFacing dir) { return this.get(x + dir.getStepX(), y + dir.getStepY(), z + dir.getStepZ()); } public long get(BlockPos pos, ModelQuadFacing dir) { return this.get(pos.x, pos.y, pos.z, dir); } public long get(BlockPos pos) { return this.get(pos.x, pos.y, pos.getZ()); } /** * Returns the light data for the block at the given position. The property fields can then be accessed using * the various unpack methods below. */ public abstract long get(int x, int y, int z); protected long compute(int x, int y, int z) { final WorldSlice world = this.world; final Block block = world.getBlock(x, y, z); final float ao; final boolean em; if (block.getLightValue() == 0) { ao = block.getAmbientOcclusionLightValue(); em = false; //state.hasEmissiveLighting(world, pos); } else { ao = 1.0f; em = true; } // First is shouldBlockVision on modern final boolean op = !block.isOpaqueCube() || block.getLightOpacity() == 0; final boolean fo = block.isOpaqueCube(); // Should be isFullCube, but this is probably close enough final boolean fc = StateUtil.areBoundsFullCube(block); // OPTIMIZE: Do not calculate lightmap data if the block is full and opaque. // FIX: Calculate lightmap data for light-emitting or emissive blocks, even though they are full and opaque. final int lm = (fo && !em) ? 0 : block.getMixedBrightnessForBlock(world, x, y, z); return packAO(ao) | packLM(lm) | packOP(op) | packFO(fo) | packFC(fc) | (1L << 60); } public static long packOP(boolean opaque) { return (opaque ? 1L : 0L) << 56; } public static boolean unpackOP(long word) { return ((word >>> 56) & 0b1) != 0; } public static long packFO(boolean opaque) { return (opaque ? 1L : 0L) << 57; } public static boolean unpackFO(long word) { return ((word >>> 57) & 0b1) != 0; } public static long packFC(boolean fullCube) { return (fullCube ? 1L : 0L) << 58; } public static boolean unpackFC(long word) { return ((word >>> 58) & 0b1) != 0; } public static long packLM(int lm) { return (long) lm & 0xFFFFFFFFL; } public static int unpackLM(long word) { return (int) (word & 0xFFFFFFFFL); } public static long packAO(float ao) { int aoi = (int) (ao * 4096.0f); return ((long) aoi & 0xFFFFL) << 32; } public static float unpackAO(long word) { int aoi = (int) (word >>> 32 & 0xFFFFL); return aoi * (1.0f / 4096.0f); } public static int getLightMap(long originWord) { if (!DynamicLights.isEnabled()) { return unpackLM(originWord); } if (unpackFO(originWord)){ return unpackLM(originWord); } double dynamic = DynamicLights.get().getDynamicLightLevel(DynamicLightsPos.get()); return DynamicLights.get().getLightmapWithDynamicLight(dynamic, unpackLM(originWord)); } public WorldSlice getWorld() { return this.world; } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\light\data\QuadLightData.java
package me.jellysquid.mods.sodium.client.model.light.data; /** * Stores the computed light data for a block model quad. The vertex order of each array is defined as that of the * quad's vertex order. */ public class QuadLightData { /** * The brightness of each vertex in the quad as normalized floats. */ public final float[] br = new float[4]; /** * The lightmap texture coordinates for each vertex in the quad. */ public final int[] lm = new int[4]; }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\light\flat\FlatLightPipeline.java
package me.jellysquid.mods.sodium.client.model.light.flat; import com.gtnewhorizon.gtnhlib.blockpos.BlockPos; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuadView; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.properties.ModelQuadFacing; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.properties.ModelQuadFlags; import java.util.Arrays; import net.coderbot.iris.Iris; import me.jellysquid.mods.sodium.client.model.light.LightPipeline; import me.jellysquid.mods.sodium.client.model.light.data.LightDataAccess; import me.jellysquid.mods.sodium.client.model.light.data.QuadLightData; import net.coderbot.iris.block_rendering.BlockRenderingSettings; import net.minecraftforge.common.util.ForgeDirection; /** * A light pipeline which implements "classic-style" lighting through simply using the light value of the adjacent * block to a face. */ public class FlatLightPipeline implements LightPipeline { /** * The cache which light data will be accessed from. */ private final LightDataAccess lightCache; public FlatLightPipeline(LightDataAccess lightCache) { this.lightCache = lightCache; } @Override public void calculate(ModelQuadView quad, BlockPos pos, QuadLightData out, ModelQuadFacing cullFace, ModelQuadFacing face, boolean shade) { int lightmap; // To match vanilla behavior, use the cull face if it exists/is available if (cullFace != null) { lightmap = getOffsetLightmap(pos, cullFace); } else { int flags = quad.getFlags(); // If the face is aligned, use the light data above it // To match vanilla behavior, also treat the face as aligned if it is parallel and the block state is a full cube if ((flags & ModelQuadFlags.IS_ALIGNED) != 0 || ((flags & ModelQuadFlags.IS_PARALLEL) != 0 && LightDataAccess.unpackFC(this.lightCache.get(pos)))) { lightmap = getOffsetLightmap(pos, face); } else { lightmap = LightDataAccess.getLightMap(this.lightCache.get(pos)); } } Arrays.fill(out.lm, lightmap); final float brightness = (Iris.enabled && BlockRenderingSettings.INSTANCE.shouldDisableDirectionalShading()) ? 1.0F : this.lightCache.getWorld().getBrightness(face, shade); Arrays.fill(out.br, brightness); } /** * When vanilla computes an offset lightmap with flat lighting, it passes the original BlockState but the * offset BlockPos to WorldRenderer#getLightmapCoordinates(BlockRenderView, BlockState, BlockPos) * This does not make much sense but fixes certain issues, primarily dark quads on light-emitting blocks * behind tinted glass. {@link LightDataAccess} cannot efficiently store lightmaps computed with * inconsistent values so this method exists to mirror vanilla behavior as closely as possible. */ private int getOffsetLightmap(BlockPos pos, ModelQuadFacing face) { int lightmap = LightDataAccess.getLightMap(this.lightCache.get(pos, face)); // If the block light is not 15 (max)... if ((lightmap & 0xF0) != 0xF0) { int originLightmap = LightDataAccess.getLightMap(this.lightCache.get(pos)); // ...take the maximum combined block light at the origin and offset positions lightmap = (lightmap & ~0xFF) | Math.max(lightmap & 0xFF, originLightmap & 0xFF); } return lightmap; } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\light\smooth\AoCompletionFlags.java
package me.jellysquid.mods.sodium.client.model.light.smooth; /** * Bit flags to indicate which light properties have been computed for a given face. */ class AoCompletionFlags { /** * The light data has been retrieved from the cache. */ public static final int HAS_LIGHT_DATA = 0b01; /** * The light data has been unpacked into normalized floating point values. */ public static final int HAS_UNPACKED_LIGHT_DATA = 0b10; }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\light\smooth\AoFaceData.java
package me.jellysquid.mods.sodium.client.model.light.smooth; import static me.jellysquid.mods.sodium.client.model.light.cache.ArrayLightDataCache.getLightMap; import static me.jellysquid.mods.sodium.client.model.light.cache.ArrayLightDataCache.unpackAO; import static me.jellysquid.mods.sodium.client.model.light.cache.ArrayLightDataCache.unpackFO; import static me.jellysquid.mods.sodium.client.model.light.cache.ArrayLightDataCache.unpackOP; import com.gtnewhorizon.gtnhlib.blockpos.BlockPos; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.properties.ModelQuadFacing; import me.jellysquid.mods.sodium.client.model.light.data.LightDataAccess; class AoFaceData { public final int[] lm = new int[4]; public final float[] ao = new float[4]; public final float[] bl = new float[4]; public final float[] sl = new float[4]; private int flags; public void initLightData(LightDataAccess cache, BlockPos pos, ModelQuadFacing direction, boolean offset) { final int x = pos.x; final int y = pos.y; final int z = pos.z; final int adjX; final int adjY; final int adjZ; if (offset) { adjX = x + direction.getStepX(); adjY = y + direction.getStepY(); adjZ = z + direction.getStepZ(); } else { adjX = x; adjY = y; adjZ = z; } long adjWord = cache.get(adjX, adjY, adjZ); final int calm; // Use the origin block's light values if the adjacent one is opaque if (offset && unpackFO(adjWord)) { calm = getLightMap(cache.get(x, y, z)); } else { calm = getLightMap(adjWord); } final float caao = unpackAO(adjWord); var faces = AoNeighborInfo.get(direction).faces; final long e0 = cache.get(adjX, adjY, adjZ, faces[0]); final int e0lm = getLightMap(e0); final float e0ao = unpackAO(e0); final boolean e0op = unpackOP(e0); final long e1 = cache.get(adjX, adjY, adjZ, faces[1]); final int e1lm = getLightMap(e1); final float e1ao = unpackAO(e1); final boolean e1op = unpackOP(e1); final long e2 = cache.get(adjX, adjY, adjZ, faces[2]); final int e2lm = getLightMap(e2); final float e2ao = unpackAO(e2); final boolean e2op = unpackOP(e2); final long e3 = cache.get(adjX, adjY, adjZ, faces[3]); final int e3lm = getLightMap(e3); final float e3ao = unpackAO(e3); final boolean e3op = unpackOP(e3); // If neither edge of a corner is occluded, then use the light final int c0lm; final float c0ao; if (!e2op && !e0op) { c0lm = e0lm; c0ao = e0ao; } else { long d0 = cache.get(adjX, adjY, adjZ, faces[0], faces[2]); c0lm = getLightMap(d0); c0ao = unpackAO(d0); } final int c1lm; final float c1ao; if (!e3op && !e0op) { c1lm = e0lm; c1ao = e0ao; } else { long d1 = cache.get(adjX, adjY, adjZ, faces[0], faces[3]); c1lm = getLightMap(d1); c1ao = unpackAO(d1); } final int c2lm; final float c2ao; if (!e2op && !e1op) { // FIX: Use e1 instead of c0 to fix lighting errors in some directions c2lm = e1lm; c2ao = e1ao; } else { long d2 = cache.get(adjX, adjY, adjZ, faces[1], faces[2]); c2lm = getLightMap(d2); c2ao = unpackAO(d2); } final int c3lm; final float c3ao; if (!e3op && !e1op) { // FIX: Use e1 instead of c0 to fix lighting errors in some directions c3lm = e1lm; c3ao = e1ao; } else { long d3 = cache.get(adjX, adjY, adjZ, faces[1], faces[3]); c3lm = getLightMap(d3); c3ao = unpackAO(d3); } float[] ao = this.ao; ao[0] = (e3ao + e0ao + c1ao + caao) * 0.25f; ao[1] = (e2ao + e0ao + c0ao + caao) * 0.25f; ao[2] = (e2ao + e1ao + c2ao + caao) * 0.25f; ao[3] = (e3ao + e1ao + c3ao + caao) * 0.25f; int[] cb = this.lm; cb[0] = calculateCornerBrightness(e3lm, e0lm, c1lm, calm); cb[1] = calculateCornerBrightness(e2lm, e0lm, c0lm, calm); cb[2] = calculateCornerBrightness(e2lm, e1lm, c2lm, calm); cb[3] = calculateCornerBrightness(e3lm, e1lm, c3lm, calm); this.flags |= AoCompletionFlags.HAS_LIGHT_DATA; } public void unpackLightData() { int[] lm = this.lm; float[] bl = this.bl; float[] sl = this.sl; bl[0] = unpackBlockLight(lm[0]); bl[1] = unpackBlockLight(lm[1]); bl[2] = unpackBlockLight(lm[2]); bl[3] = unpackBlockLight(lm[3]); sl[0] = unpackSkyLight(lm[0]); sl[1] = unpackSkyLight(lm[1]); sl[2] = unpackSkyLight(lm[2]); sl[3] = unpackSkyLight(lm[3]); this.flags |= AoCompletionFlags.HAS_UNPACKED_LIGHT_DATA; } public float getBlendedSkyLight(float[] w) { return weightedSum(this.sl, w); } public float getBlendedBlockLight(float[] w) { return weightedSum(this.bl, w); } public float getBlendedShade(float[] w) { return weightedSum(this.ao, w); } private static float weightedSum(float[] v, float[] w) { float t0 = v[0] * w[0]; float t1 = v[1] * w[1]; float t2 = v[2] * w[2]; float t3 = v[3] * w[3]; return t0 + t1 + t2 + t3; } private static float unpackSkyLight(int i) { return (i >> 16) & 0xFF; } private static float unpackBlockLight(int i) { return i & 0xFF; } private static int calculateCornerBrightness(int a, int b, int c, int d) { // FIX: Normalize corner vectors correctly to the minimum non-zero value between each one to prevent // strange issues if ((a == 0) || (b == 0) || (c == 0) || (d == 0)) { // Find the minimum value between all corners final int min = minNonZero(minNonZero(a, b), minNonZero(c, d)); // Normalize the corner values a = Math.max(a, min); b = Math.max(b, min); c = Math.max(c, min); d = Math.max(d, min); } return ((a + b + c + d) >> 2) & 0xFF00FF; } private static int minNonZero(int a, int b) { if (a == 0) { return b; } else if (b == 0) { return a; } return Math.min(a, b); } public boolean hasLightData() { return (this.flags & AoCompletionFlags.HAS_LIGHT_DATA) != 0; } public boolean hasUnpackedLightData() { return (this.flags & AoCompletionFlags.HAS_UNPACKED_LIGHT_DATA) != 0; } public void reset() { this.flags = 0; } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\light\smooth\AoNeighborInfo.java
package me.jellysquid.mods.sodium.client.model.light.smooth; import static com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.properties.ModelQuadFacing.NEG_X; import static com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.properties.ModelQuadFacing.NEG_Y; import static com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.properties.ModelQuadFacing.NEG_Z; import static com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.properties.ModelQuadFacing.POS_X; import static com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.properties.ModelQuadFacing.POS_Y; import static com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.properties.ModelQuadFacing.POS_Z; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.properties.ModelQuadFacing; import org.jetbrains.annotations.NotNull; /** * The neighbor information for each face of a block, used when performing smooth lighting in order to calculate * the occlusion of each corner. */ enum AoNeighborInfo { EAST(new ModelQuadFacing[] { NEG_Y, POS_Y, NEG_Z, POS_Z }, 0.6F) { @Override public void calculateCornerWeights(float x, float y, float z, float[] out) { final float u = z; final float v = 1.0f - y; out[0] = v * u; out[1] = v * (1.0f - u); out[2] = (1.0f - v) * (1.0f - u); out[3] = (1.0f - v) * u; } @Override public void mapCorners(int[] lm0, float[] ao0, int[] lm1, float[] ao1) { lm1[1] = lm0[0]; lm1[2] = lm0[1]; lm1[3] = lm0[2]; lm1[0] = lm0[3]; ao1[1] = ao0[0]; ao1[2] = ao0[1]; ao1[3] = ao0[2]; ao1[0] = ao0[3]; } @Override public float getDepth(float x, float y, float z) { return 1.0f - x; } }, UP(new ModelQuadFacing[] { POS_X, NEG_X, NEG_Z, POS_Z }, 1.0F) { @Override public void calculateCornerWeights(float x, float y, float z, float[] out) { final float u = z; final float v = x; out[0] = v * u; out[1] = v * (1.0f - u); out[2] = (1.0f - v) * (1.0f - u); out[3] = (1.0f - v) * u; } @Override public void mapCorners(int[] lm0, float[] ao0, int[] lm1, float[] ao1) { lm1[2] = lm0[0]; lm1[3] = lm0[1]; lm1[0] = lm0[2]; lm1[1] = lm0[3]; ao1[2] = ao0[0]; ao1[3] = ao0[1]; ao1[0] = ao0[2]; ao1[1] = ao0[3]; } @Override public float getDepth(float x, float y, float z) { return 1.0f - y; } }, SOUTH(new ModelQuadFacing[] { NEG_X, POS_X, NEG_Y, POS_Y }, 0.8F) { @Override public void calculateCornerWeights(float x, float y, float z, float[] out) { final float u = y; final float v = 1.0f - x; out[0] = u * v; out[1] = (1.0f - u) * v; out[2] = (1.0f - u) * (1.0f - v); out[3] = u * (1.0f - v); } @Override public void mapCorners(int[] lm0, float[] ao0, int[] lm1, float[] ao1) { lm1[0] = lm0[0]; lm1[1] = lm0[1]; lm1[2] = lm0[2]; lm1[3] = lm0[3]; ao1[0] = ao0[0]; ao1[1] = ao0[1]; ao1[2] = ao0[2]; ao1[3] = ao0[3]; } @Override public float getDepth(float x, float y, float z) { return 1.0f - z; } }, WEST(new ModelQuadFacing[] { POS_Y, NEG_Y, NEG_Z, POS_Z }, 0.6F) { @Override public void calculateCornerWeights(float x, float y, float z, float[] out) { final float u = z; final float v = y; out[0] = v * u; out[1] = v * (1.0f - u); out[2] = (1.0f - v) * (1.0f - u); out[3] = (1.0f - v) * u; } @Override public void mapCorners(int[] lm0, float[] ao0, int[] lm1, float[] ao1) { lm1[3] = lm0[0]; lm1[0] = lm0[1]; lm1[1] = lm0[2]; lm1[2] = lm0[3]; ao1[3] = ao0[0]; ao1[0] = ao0[1]; ao1[1] = ao0[2]; ao1[2] = ao0[3]; } @Override public float getDepth(float x, float y, float z) { return x; } }, DOWN(new ModelQuadFacing[] { NEG_X, POS_X, NEG_Z, POS_Z }, 0.5F) { @Override public void calculateCornerWeights(float x, float y, float z, float[] out) { final float u = z; final float v = 1.0f - x; out[0] = v * u; out[1] = v * (1.0f - u); out[2] = (1.0f - v) * (1.0f - u); out[3] = (1.0f - v) * u; } @Override public void mapCorners(int[] lm0, float[] ao0, int[] lm1, float[] ao1) { lm1[0] = lm0[0]; lm1[1] = lm0[1]; lm1[2] = lm0[2]; lm1[3] = lm0[3]; ao1[0] = ao0[0]; ao1[1] = ao0[1]; ao1[2] = ao0[2]; ao1[3] = ao0[3]; } @Override public float getDepth(float x, float y, float z) { return y; } }, NORTH(new ModelQuadFacing[] { POS_Y, NEG_Y, POS_X, NEG_X }, 0.8F) { @Override public void calculateCornerWeights(float x, float y, float z, float[] out) { final float u = 1.0f - x; final float v = y; out[0] = v * u; out[1] = v * (1.0f - u); out[2] = (1.0f - v) * (1.0f - u); out[3] = (1.0f - v) * u; } @Override public void mapCorners(int[] lm0, float[] ao0, int[] lm1, float[] ao1) { lm1[3] = lm0[0]; lm1[0] = lm0[1]; lm1[1] = lm0[2]; lm1[2] = lm0[3]; ao1[3] = ao0[0]; ao1[0] = ao0[1]; ao1[1] = ao0[2]; ao1[2] = ao0[3]; } @Override public float getDepth(float x, float y, float z) { return z; } }; /** * The direction of each corner block from this face, which can be retrieved by offsetting the position of the origin * block by the direction vector. */ public final ModelQuadFacing[] faces; /** * The constant brightness modifier for this face. This data exists to emulate the results of the OpenGL lighting * model which gives a faux directional light appearance to blocks in the game. Not currently used. */ public final float strength; AoNeighborInfo(ModelQuadFacing[] directions, float strength) { this.faces = directions; this.strength = strength; } /** * Calculates how much each corner contributes to the final "darkening" of the vertex at the specified position. The * weight is a function of the distance from the vertex's position to the corner block's position. * * @param x The x-position of the vertex * @param y The y-position of the vertex * @param z The z-position of the vertex * @param out The weight values for each corner */ public abstract void calculateCornerWeights(float x, float y, float z, float[] out); /** * Maps the light map and occlusion value arrays {@param lm0} and {@param ao0} from {@link AoFaceData} to the * correct corners for this facing. * * @param lm0 The input light map texture coordinates array * @param ao0 The input ambient occlusion color array * @param lm1 The re-orientated output light map texture coordinates array * @param ao1 The re-orientated output ambient occlusion color array */ public abstract void mapCorners(int[] lm0, float[] ao0, int[] lm1, float[] ao1); /** * Calculates the depth (or inset) of the vertex into this facing of the block. Used to determine * how much shadow is contributed by the direct neighbors of a block. * * @param x The x-position of the vertex * @param y The y-position of the vertex * @param z The z-position of the vertex * @return The depth of the vertex into this face */ public abstract float getDepth(float x, float y, float z); private static final AoNeighborInfo[] VALUES = AoNeighborInfo.values(); /** * @return Returns the {@link AoNeighborInfo} which corresponds with the specified direction */ public static AoNeighborInfo get(@NotNull ModelQuadFacing direction) { return VALUES[direction.ordinal()]; } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\light\smooth\SmoothLightPipeline.java
package me.jellysquid.mods.sodium.client.model.light.smooth; import com.google.common.math.DoubleMath; import com.gtnewhorizon.gtnhlib.blockpos.BlockPos; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuadView; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.properties.ModelQuadFacing; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.properties.ModelQuadFlags; import me.jellysquid.mods.sodium.client.model.light.LightPipeline; import net.coderbot.iris.Iris; import me.jellysquid.mods.sodium.client.model.light.data.LightDataAccess; import me.jellysquid.mods.sodium.client.model.light.data.QuadLightData; import net.coderbot.iris.block_rendering.BlockRenderingSettings; /** * A light pipeline which produces smooth interpolated lighting and ambient occlusion for model quads. This * implementation makes a number of improvements over vanilla's own "smooth lighting" option. In no particular order: * * - Ambient occlusion of block slopes underwater no longer produces broken results (fixes MC-149211) * - Smooth lighting now works when underwater (fixes MC-68129) * - Corner blocks are now selected from the correct set of neighbors above block faces (fixes MC-148689 and MC-12558) * - Shading issues caused by anisotropy are fixed by re-orientating quads to a consistent ordering (fixes MC-136302) * - Inset block faces are correctly shaded by their neighbors, fixing a number of problems with non-full blocks such as * grass paths (fixes MC-11783 and MC-108621) * - Synchronization issues between the main render thread's light engine and chunk build worker threads are corrected * by copying light data alongside block states, fixing a number of inconsistencies in baked chunks (no open issue) * * This implementation also includes a significant number of optimizations: * * - Computed light data for a given block face is cached and re-used again when multiple quads exist for a given * facing, making complex block models less expensive to render * - The light data cache encodes as much information as possible into integer words to improve cache locality and * to eliminate the multiple array lookups that would otherwise be needed, significantly speeding up this section * - Block faces aligned to the block grid use a fast-path for mapping corner light values to vertices without expensive * interpolation or blending, speeding up most block renders * - Some critical code paths have been re-written to hit the JVM's happy path, allowing it to perform auto-vectorization * of the blend functions * - Information about a given model quad is cached to enable the light pipeline to make certain assumptions and skip * unnecessary computation */ public class SmoothLightPipeline implements LightPipeline { public static final double TOLERANCE = 1.0E-5F; public static final boolean useSmoothLightingOptimizations = false; /** * The cache which light data will be accessed from. */ private final LightDataAccess lightCache; /** * The cached face data for each side of a block, both inset and outset. */ private final AoFaceData[] cachedFaceData = new AoFaceData[6 * 2]; /** * The position at which the cached face data was taken at. */ private long cachedPos = Long.MIN_VALUE; /** * A temporary array for storing the intermediary results of weight data for non-aligned face blending. */ private final float[] weights = new float[4]; public SmoothLightPipeline(LightDataAccess cache) { this.lightCache = cache; for (int i = 0; i < this.cachedFaceData.length; i++) { this.cachedFaceData[i] = new AoFaceData(); } } @Override public void calculate(ModelQuadView quad, BlockPos pos, QuadLightData out, ModelQuadFacing cullFace, ModelQuadFacing face, boolean shade) { this.updateCachedData(pos.asLong()); final int flags = quad.getFlags(); final AoNeighborInfo neighborInfo = AoNeighborInfo.get(face); // If the model quad is aligned to the block's face and covers it entirely, we can take a fast path and directly // map the corner values onto this quad's vertices. This covers most situations during rendering and provides // a modest speed-up. // To match vanilla behavior, also treat the face as aligned if it is parallel and the block state is a full cube if (useSmoothLightingOptimizations) { if ((flags & ModelQuadFlags.IS_ALIGNED) != 0 || ((flags & ModelQuadFlags.IS_PARALLEL) != 0 && LightDataAccess.unpackFC(this.lightCache.get(pos)))) { if ((flags & ModelQuadFlags.IS_PARTIAL) == 0) { this.applyAlignedFullFace(neighborInfo, pos, face, out); } else { this.applyAlignedPartialFace(neighborInfo, quad, pos, face, out); } } else if ((flags & ModelQuadFlags.IS_PARALLEL) != 0) { this.applyParallelFace(neighborInfo, quad, pos, face, out); } else { this.applyNonParallelFace(neighborInfo, quad, pos, face, out); } } else { this.applyNonParallelFace(neighborInfo, quad, pos, face, out); } this.applySidedBrightness(out, face, shade); } /** * Quickly calculates the light data for a full grid-aligned quad. This represents the most common case (outward * facing quads on a full-block model) and avoids interpolation between neighbors as each corner will only ever * have two contributing sides. * Flags: IS_ALIGNED, !IS_PARTIAL */ private void applyAlignedFullFace(AoNeighborInfo neighborInfo, BlockPos pos, ModelQuadFacing dir, QuadLightData out) { final AoFaceData faceData = this.getCachedFaceData(pos, dir, true); neighborInfo.mapCorners(faceData.lm, faceData.ao, out.lm, out.br); } /** * Calculates the light data for a grid-aligned quad that does not cover the entire block volume's face. * Flags: IS_ALIGNED, IS_PARTIAL */ private void applyAlignedPartialFace(AoNeighborInfo neighborInfo, ModelQuadView quad, BlockPos pos, ModelQuadFacing dir, QuadLightData out) { for (int i = 0; i < 4; i++) { // Clamp the vertex positions to the block's boundaries to prevent weird errors in lighting final float cx = clamp(quad.getX(i)); final float cy = clamp(quad.getY(i)); final float cz = clamp(quad.getZ(i)); final float[] weights = this.weights; neighborInfo.calculateCornerWeights(cx, cy, cz, weights); this.applyAlignedPartialFaceVertex(pos, dir, weights, i, out, true); } } /** * This method is the same as {@link #applyNonParallelFace(AoNeighborInfo, ModelQuadView, BlockPos, ModelQuadFacing, * QuadLightData)} but with the check for a depth of approximately 0 removed. If the quad is parallel but not * aligned, all of its vertices will have the same depth and this depth must be approximately greater than 0, * meaning the check for 0 will always return false. * Flags: !IS_ALIGNED, IS_PARALLEL */ private void applyParallelFace(AoNeighborInfo neighborInfo, ModelQuadView quad, BlockPos pos, ModelQuadFacing dir, QuadLightData out) { for (int i = 0; i < 4; i++) { // Clamp the vertex positions to the block's boundaries to prevent weird errors in lighting final float cx = clamp(quad.getX(i)); final float cy = clamp(quad.getY(i)); final float cz = clamp(quad.getZ(i)); final float[] weights = this.weights; neighborInfo.calculateCornerWeights(cx, cy, cz, weights); final float depth = neighborInfo.getDepth(cx, cy, cz); // If the quad is approximately grid-aligned (not inset) to the other side of the block, avoid unnecessary // computation by treating it is as aligned if (DoubleMath.fuzzyEquals(depth, 1.0F, TOLERANCE)) { this.applyAlignedPartialFaceVertex(pos, dir, weights, i, out, false); } else { // Blend the occlusion factor between the blocks directly beside this face and the blocks above it // based on how inset the face is. This fixes a few issues with blocks such as farmland and paths. this.applyInsetPartialFaceVertex(pos, dir, depth, 1.0f - depth, weights, i, out); } } } /** * Flags: !IS_ALIGNED, !IS_PARALLEL */ private void applyNonParallelFace(AoNeighborInfo neighborInfo, ModelQuadView quad, BlockPos pos, ModelQuadFacing dir, QuadLightData out) { for (int i = 0; i < 4; i++) { // Clamp the vertex positions to the block's boundaries to prevent weird errors in lighting final float cx = clamp(quad.getX(i)); final float cy = clamp(quad.getY(i)); final float cz = clamp(quad.getZ(i)); final float[] weights = this.weights; neighborInfo.calculateCornerWeights(cx, cy, cz, weights); final float depth = neighborInfo.getDepth(cx, cy, cz); // If the quad is approximately grid-aligned (not inset), avoid unnecessary computation by treating it is as aligned if (DoubleMath.fuzzyEquals(depth, 0.0F, TOLERANCE)) { this.applyAlignedPartialFaceVertex(pos, dir, weights, i, out, true); } else if (DoubleMath.fuzzyEquals(depth, 1.0F, TOLERANCE)) { this.applyAlignedPartialFaceVertex(pos, dir, weights, i, out, false); } else { // Blend the occlusion factor between the blocks directly beside this face and the blocks above it // based on how inset the face is. This fixes a few issues with blocks such as farmland and paths. this.applyInsetPartialFaceVertex(pos, dir, depth, 1.0f - depth, weights, i, out); } } } private void applyAlignedPartialFaceVertex(BlockPos pos, ModelQuadFacing dir, float[] w, int i, QuadLightData out, boolean offset) { final AoFaceData faceData = this.getCachedFaceData(pos, dir, offset); if (!faceData.hasUnpackedLightData()) { faceData.unpackLightData(); } final float sl = faceData.getBlendedSkyLight(w); final float bl = faceData.getBlendedBlockLight(w); final float ao = faceData.getBlendedShade(w); out.br[i] = ao; out.lm[i] = getLightMapCoord(sl, bl); } private void applyInsetPartialFaceVertex(BlockPos pos, ModelQuadFacing dir, float n1d, float n2d, float[] w, int i, QuadLightData out) { final AoFaceData n1 = this.getCachedFaceData(pos, dir, false); if (!n1.hasUnpackedLightData()) { n1.unpackLightData(); } AoFaceData n2 = this.getCachedFaceData(pos, dir, true); if (!n2.hasUnpackedLightData()) { n2.unpackLightData(); } // Blend between the direct neighbors and above based on the passed weights final float ao = (n1.getBlendedShade(w) * n1d) + (n2.getBlendedShade(w) * n2d); final float sl = (n1.getBlendedSkyLight(w) * n1d) + (n2.getBlendedSkyLight(w) * n2d); final float bl = (n1.getBlendedBlockLight(w) * n1d) + (n2.getBlendedBlockLight(w) * n2d); out.br[i] = ao; out.lm[i] = getLightMapCoord(sl, bl); } private void applySidedBrightness(QuadLightData out, ModelQuadFacing face, boolean shade) { if(Iris.enabled && BlockRenderingSettings.INSTANCE.shouldDisableDirectionalShading()) { return; } final float brightness = this.lightCache.getWorld().getBrightness(face, shade); final float[] br = out.br; for (int i = 0; i < br.length; i++) { br[i] *= brightness; } } /** * Returns the cached data for a given facing or calculates it if it hasn't been cached. */ private AoFaceData getCachedFaceData(BlockPos pos, ModelQuadFacing face, boolean offset) { final AoFaceData data = this.cachedFaceData[offset ? face.ordinal() : face.ordinal() + 6]; if (!data.hasLightData()) { data.initLightData(this.lightCache, pos, face, offset); } return data; } private void updateCachedData(long key) { if (this.cachedPos != key) { for (AoFaceData data : this.cachedFaceData) { data.reset(); } this.cachedPos = key; } } /** * Clamps the given float to the range [0.0, 1.0]. */ private static float clamp(float v) { if (v < 0.0f) { return 0.0f; } else if (v > 1.0f) { return 1.0f; } return v; } /** * Returns a texture coordinate on the light map texture for the given block and sky light values. */ private static int getLightMapCoord(float sl, float bl) { return (((int) sl & 0xFF) << 16) | ((int) bl & 0xFF); } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\vertex\buffer\VertexBufferBuilder.java
package me.jellysquid.mods.sodium.client.model.vertex.buffer; import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.*; import me.jellysquid.mods.sodium.client.gl.attribute.BufferVertexFormat; import java.nio.ByteBuffer; public class VertexBufferBuilder implements VertexBufferView { private final BufferVertexFormat vertexFormat; private ByteBuffer buffer; private int writerOffset; private int capacity; public VertexBufferBuilder(BufferVertexFormat vertexFormat, int initialCapacity) { this.vertexFormat = vertexFormat; this.buffer = memAlloc(initialCapacity); this.capacity = initialCapacity; this.writerOffset = 0; } private void grow(int len) { // The new capacity will at least as large as the write it needs to service final int cap = Math.max(this.capacity * 2, this.capacity + len); this.buffer = memRealloc(this.buffer, cap); this.capacity = cap; } @Override public boolean ensureBufferCapacity(int bytes) { if (this.writerOffset + bytes <= this.capacity) { return false; } this.grow(bytes); return true; } @Override public ByteBuffer getDirectBuffer() { return this.buffer; } @Override public int getWriterPosition() { return this.writerOffset; } @Override public void flush(int vertexCount, BufferVertexFormat format) { if (this.vertexFormat != format) { throw new IllegalStateException("Mis-matched vertex format (expected: [" + format + "], currently using: [" + this.vertexFormat + "])"); } this.writerOffset += vertexCount * format.getStride(); } @Override public BufferVertexFormat getVertexFormat() { return this.vertexFormat; } public boolean isEmpty() { return this.writerOffset == 0; } public int getSize() { return this.writerOffset; } /** * Ends the stream of written data and makes a copy of it to be passed around. */ public void copyInto(ByteBuffer dst) { // Mark the slice of memory that needs to be copied this.buffer.position(0); this.buffer.limit(this.writerOffset); // Allocate a new buffer which is just large enough to contain the slice of vertex data // The buffer is then flipped after the operation so the callee sees a range of bytes from (0,len] which can // then be immediately passed to native libraries or the graphics driver dst.put(this.buffer.slice()); // Reset the position and limit set earlier of the backing scratch buffer this.buffer.clear(); this.writerOffset = 0; } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\vertex\buffer\VertexBufferView.java
package me.jellysquid.mods.sodium.client.model.vertex.buffer; import me.jellysquid.mods.sodium.client.gl.attribute.BufferVertexFormat; import java.nio.ByteBuffer; /** * Provides a view into {@link net.minecraft.client.render.BufferBuilder} and similar types. */ public interface VertexBufferView { /** * Ensures there is capacity in the buffer for the given number of bytes. * @param bytes The number of bytes to allocate space for * @return True if the buffer was resized, otherwise false */ boolean ensureBufferCapacity(int bytes); /** * Returns a handle to the internal storage of this buffer. The buffer can be directly written into at the * base address provided by {@link VertexBufferView#getWriterPosition()}. * * @return A {@link ByteBuffer} in off-heap space */ ByteBuffer getDirectBuffer(); /** * @return The position at which new data should be written to, in bytes */ int getWriterPosition(); /** * Flushes the given number of vertices to this buffer. This ensures that all constraints are still valid, and if * so, advances the vertex counter and writer pointer to the end of the data that was written by the caller. * @param vertexCount The number of vertices to flush * @param format The format of each vertex */ void flush(int vertexCount, BufferVertexFormat format); /** * @return The current vertex format of the buffer */ BufferVertexFormat getVertexFormat(); }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\vertex\buffer\VertexBufferWriter.java
package me.jellysquid.mods.sodium.client.model.vertex.buffer; import me.jellysquid.mods.sodium.client.gl.attribute.BufferVertexFormat; import me.jellysquid.mods.sodium.client.model.vertex.VertexSink; import me.jellysquid.mods.sodium.client.model.vertex.type.BufferVertexType; /** * Base implementation of a {@link VertexSink} which writes into a {@link VertexBufferView} directly. */ public abstract class VertexBufferWriter implements VertexSink { protected final VertexBufferView backingBuffer; protected final BufferVertexFormat vertexFormat; protected final int vertexStride; private int vertexCount; protected VertexBufferWriter(VertexBufferView backingBuffer, BufferVertexType<?> vertexType) { this.backingBuffer = backingBuffer; this.vertexFormat = vertexType.getBufferVertexFormat(); this.vertexStride = this.vertexFormat.getStride(); this.onBufferStorageChanged(); } @Override public void ensureCapacity(int count) { if (this.backingBuffer.ensureBufferCapacity((this.vertexCount + count) * this.vertexStride)) { this.onBufferStorageChanged(); } } @Override public void flush() { this.backingBuffer.flush(this.vertexCount, this.vertexFormat); this.vertexCount = 0; } /** * Advances the write pointer forward by the stride of one vertex. This should always be called after a * vertex is written. Implementations which override this should always call invoke the super implementation. */ protected void advance() { this.vertexCount++; } /** * Called when the underlying memory buffer to the backing storage changes. When this is called, the implementation * should update any pointers */ protected abstract void onBufferStorageChanged(); }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\vertex\buffer\VertexBufferWriterNio.java
package me.jellysquid.mods.sodium.client.model.vertex.buffer; import me.jellysquid.mods.sodium.client.model.vertex.type.BufferVertexType; import java.nio.ByteBuffer; /** * A safe {@link VertexBufferWriter} implementation which uses Java's NIO library to write into memory buffers. All * write operations are checked and will throw an exception if an invalid memory access is detected. Supported on all * platforms. */ public abstract class VertexBufferWriterNio extends VertexBufferWriter { protected ByteBuffer byteBuffer; protected int writeOffset; protected VertexBufferWriterNio(VertexBufferView backingBuffer, BufferVertexType<?> vertexType) { super(backingBuffer, vertexType); } @Override protected void onBufferStorageChanged() { this.byteBuffer = this.backingBuffer.getDirectBuffer(); this.writeOffset = this.backingBuffer.getWriterPosition(); } @Override protected void advance() { this.writeOffset += this.vertexStride; super.advance(); } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\vertex\buffer\VertexBufferWriterUnsafe.java
package me.jellysquid.mods.sodium.client.model.vertex.buffer; import me.jellysquid.mods.sodium.client.model.vertex.type.BufferVertexType; import org.lwjgl.MemoryUtil; /** * An unsafe {@link VertexBufferWriter} implementation which uses direct memory operations to enable fast blitting of * data into memory buffers. Only available on JVMs which support {@link sun.misc.Unsafe}, but generally produces much * better optimized code than other implementations. The implementation does not check for invalid memory accesses, * meaning that errors can corrupt process memory. */ public abstract class VertexBufferWriterUnsafe extends VertexBufferWriter { /** * The write pointer into the buffer storage. This is advanced by the vertex stride every time * {@link VertexBufferWriterUnsafe#advance()} is called. */ protected long writePointer; protected VertexBufferWriterUnsafe(VertexBufferView backingBuffer, BufferVertexType<?> vertexType) { super(backingBuffer, vertexType); } @Override protected void onBufferStorageChanged() { this.writePointer = MemoryUtil.getAddress(this.backingBuffer.getDirectBuffer(), this.backingBuffer.getWriterPosition()); } @Override protected void advance() { this.writePointer += this.vertexStride; super.advance(); } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\vertex\fallback\VertexWriterFallback.java
package me.jellysquid.mods.sodium.client.model.vertex.fallback; import com.gtnewhorizons.angelica.compat.toremove.VertexConsumer; import me.jellysquid.mods.sodium.client.model.vertex.VertexSink; /** * The base implementation for a {@link VertexSink} which writes to a black-boxed {@link VertexConsumer}. This is the * fallback path used when direct-writing optimizations cannot be used because the drain has no accessible backing * memory. This implementation is very slow and should be avoided where possible. * * This sink does not support explicit batching/flushing and as such, all written vertices are immediately flushed * to the backing implementation. */ public abstract class VertexWriterFallback implements VertexSink { protected final VertexConsumer consumer; protected VertexWriterFallback(VertexConsumer consumer) { this.consumer = consumer; } @Override public void ensureCapacity(int count) { // NO-OP } @Override public void flush() { // NO-OP } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\vertex\transformers\AbstractVertexTransformer.java
package me.jellysquid.mods.sodium.client.model.vertex.transformers; import me.jellysquid.mods.sodium.client.model.vertex.VertexSink; /** * A vertex transformer wraps an {@link VertexSink} interface to modify incoming vertex data, delegating any * actual logic to the inner sink. * @param <T> The {@link VertexSink} interface this transformer wraps */ public abstract class AbstractVertexTransformer<T extends VertexSink> implements VertexSink { protected final T delegate; protected AbstractVertexTransformer(T delegate) { this.delegate = delegate; } @Override public void ensureCapacity(int count) { this.delegate.ensureCapacity(count); } @Override public void flush() { this.delegate.flush(); } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\vertex\transformers\SpriteTexturedVertexTransformer.java
package me.jellysquid.mods.sodium.client.model.vertex.transformers; import me.jellysquid.mods.sodium.client.model.vertex.VertexSink; import me.jellysquid.mods.sodium.client.model.vertex.formats.glyph.GlyphVertexSink; import me.jellysquid.mods.sodium.client.model.vertex.formats.particle.ParticleVertexSink; import me.jellysquid.mods.sodium.client.model.vertex.formats.quad.QuadVertexSink; import net.minecraft.client.renderer.texture.TextureAtlasSprite; /** * Base implementation for a {@link VertexSink} which transforms texture coordinates relative to a sprite's bounds. * * @param <T> The {@link VertexSink} interface this transformer wraps */ public abstract class SpriteTexturedVertexTransformer<T extends VertexSink> extends AbstractVertexTransformer<T> { private final float uMin; private final float vMin; private final float uMaxMin; private final float vMaxMin; public SpriteTexturedVertexTransformer(T delegate, TextureAtlasSprite sprite) { super(delegate); this.uMin = sprite.getMinU(); this.vMin = sprite.getMinV(); this.uMaxMin = sprite.getMaxU() - this.uMin; this.vMaxMin = sprite.getMaxV() - this.vMin; } protected float transformTextureU(float u) { return (this.uMaxMin * u) + this.uMin; } protected float transformTextureV(float v) { return (this.vMaxMin * v) + this.vMin; } public static class Quad extends SpriteTexturedVertexTransformer<QuadVertexSink> implements QuadVertexSink { public Quad(QuadVertexSink delegate, TextureAtlasSprite sprite) { super(delegate, sprite); } @Override public void writeQuad(float x, float y, float z, int color, float u, float v, int light, int overlay, int normal) { u = this.transformTextureU(u); v = this.transformTextureV(v); this.delegate.writeQuad(x, y, z, color, u, v, light, overlay, normal); } } public static class Particle extends SpriteTexturedVertexTransformer<ParticleVertexSink> implements ParticleVertexSink { public Particle(ParticleVertexSink delegate, TextureAtlasSprite sprite) { super(delegate, sprite); } @Override public void writeParticle(float x, float y, float z, float u, float v, int color, int light) { u = this.transformTextureU(u); v = this.transformTextureV(v); this.delegate.writeParticle(x, y, z, u, v, color, light); } } public static class Glyph extends SpriteTexturedVertexTransformer<GlyphVertexSink> implements GlyphVertexSink { public Glyph(GlyphVertexSink delegate, TextureAtlasSprite sprite) { super(delegate, sprite); } @Override public void writeGlyph(float x, float y, float z, int color, float u, float v, int light) { u = this.transformTextureU(u); v = this.transformTextureV(v); this.delegate.writeGlyph(x, y, z, color, u, v, light); } } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\vertex\type\BlittableVertexType.java
package me.jellysquid.mods.sodium.client.model.vertex.type; import me.jellysquid.mods.sodium.client.model.vertex.VertexSink; import me.jellysquid.mods.sodium.client.model.vertex.buffer.VertexBufferView; public interface BlittableVertexType<T extends VertexSink> extends BufferVertexType<T> { /** * Creates a {@link VertexSink} which writes into a {@link VertexBufferView}. This allows for specialization * when the memory storage is known. * * @param buffer The backing vertex buffer * @param direct True if direct memory access is allowed, otherwise false */ T createBufferWriter(VertexBufferView buffer, boolean direct); }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\vertex\type\BufferVertexType.java
package me.jellysquid.mods.sodium.client.model.vertex.type; import me.jellysquid.mods.sodium.client.gl.attribute.BufferVertexFormat; import me.jellysquid.mods.sodium.client.model.vertex.VertexSink; /** * A blittable {@link VertexType} which supports direct copying into a {@link net.minecraft.client.render.BufferBuilder} * provided the buffer's vertex format matches that required by the {@link VertexSink}. * * @param <T> The {@link VertexSink} type this factory produces */ public interface BufferVertexType<T extends VertexSink> extends VertexType<T> { BufferVertexFormat getBufferVertexFormat(); }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\vertex\type\ChunkVertexType.java
package me.jellysquid.mods.sodium.client.model.vertex.type; import me.jellysquid.mods.sodium.client.render.chunk.format.ChunkMeshAttribute; import me.jellysquid.mods.sodium.client.render.chunk.format.ModelVertexSink; public interface ChunkVertexType extends BlittableVertexType<ModelVertexSink>, CustomVertexType<ModelVertexSink, ChunkMeshAttribute> { /** * @return The scale to be applied to vertex coordinates */ float getModelScale(); /** * @return The scale to be applied to texture coordinates */ float getTextureScale(); }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\vertex\type\CustomVertexType.java
package me.jellysquid.mods.sodium.client.model.vertex.type; import me.jellysquid.mods.sodium.client.gl.attribute.BufferVertexFormat; import me.jellysquid.mods.sodium.client.gl.attribute.GlVertexFormat; import me.jellysquid.mods.sodium.client.model.vertex.VertexSink; public interface CustomVertexType<T extends VertexSink, A extends Enum<A>> extends BufferVertexType<T> { /** * @return The {@link GlVertexFormat} required for blitting (direct writing into buffers) */ GlVertexFormat<A> getCustomVertexFormat(); @Override default BufferVertexFormat getBufferVertexFormat() { return this.getCustomVertexFormat(); } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\vertex\type\VanillaVertexType.java
package me.jellysquid.mods.sodium.client.model.vertex.type; import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat; import me.jellysquid.mods.sodium.client.gl.attribute.BufferVertexFormat; import me.jellysquid.mods.sodium.client.model.vertex.VertexSink; public interface VanillaVertexType<T extends VertexSink> extends BufferVertexType<T> { default BufferVertexFormat getBufferVertexFormat() { return BufferVertexFormat.from(this.getVertexFormat()); } VertexFormat getVertexFormat(); }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\vertex\type\VertexType.java
package me.jellysquid.mods.sodium.client.model.vertex.type; import com.gtnewhorizons.angelica.compat.toremove.VertexConsumer; import me.jellysquid.mods.sodium.client.model.vertex.VertexSink; /** * Provides factories which create a {@link VertexSink} for the given vertex format. * * @param <T> The {@link VertexSink} type this factory produces */ public interface VertexType<T extends VertexSink> { /** * Creates a {@link VertexSink} which can write into any {@link VertexConsumer}. This is generally used when * a special implementation of {@link VertexConsumer} is used that cannot be optimized for, or when * complex/unsupported transformations need to be performed using vanilla code paths. * @param consumer The {@link VertexConsumer} to write into */ T createFallbackWriter(VertexConsumer consumer); /** * If this vertex type supports {@link BufferVertexType}, then this method returns this vertex type as a * blittable type, performing a safe cast. */ default BlittableVertexType<T> asBlittable() { return null; } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\vertex\formats\glyph\GlyphVertexSink.java
package me.jellysquid.mods.sodium.client.model.vertex.formats.glyph; import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat; import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat; import me.jellysquid.mods.sodium.client.model.vertex.VertexSink; import me.jellysquid.mods.sodium.client.util.math.Matrix4fExtended; import me.jellysquid.mods.sodium.client.util.math.MatrixUtil; import org.joml.Matrix4f; public interface GlyphVertexSink extends VertexSink { VertexFormat VERTEX_FORMAT = DefaultVertexFormat.POSITION_TEXTURE_COLOR_LIGHT; /** * Writes a glyph vertex to the sink. * * @param matrix The transformation matrix to apply to the vertex's position * @see GlyphVertexSink#writeGlyph(float, float, float, int, float, float, int) */ default void writeGlyph(Matrix4f matrix, float x, float y, float z, int color, float u, float v, int light) { Matrix4fExtended matrixExt = MatrixUtil.getExtendedMatrix(matrix); float x2 = matrixExt.transformVecX(x, y, z); float y2 = matrixExt.transformVecY(x, y, z); float z2 = matrixExt.transformVecZ(x, y, z); this.writeGlyph(x2, y2, z2, color, u, v, light); } /** * Writes a glyph vertex to the sink. * * @param x The x-position of the vertex * @param y The y-position of the vertex * @param z The z-position of the vertex * @param color The ABGR-packed color of the vertex * @param u The u-texture of the vertex * @param v The v-texture of the vertex * @param light The packed light map texture coordinates of the vertex */ void writeGlyph(float x, float y, float z, int color, float u, float v, int light); }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\vertex\formats\glyph\GlyphVertexType.java
package me.jellysquid.mods.sodium.client.model.vertex.formats.glyph; import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat; import com.gtnewhorizons.angelica.compat.toremove.VertexConsumer; import me.jellysquid.mods.sodium.client.model.vertex.buffer.VertexBufferView; import me.jellysquid.mods.sodium.client.model.vertex.formats.glyph.writer.GlyphVertexBufferWriterNio; import me.jellysquid.mods.sodium.client.model.vertex.formats.glyph.writer.GlyphVertexBufferWriterUnsafe; import me.jellysquid.mods.sodium.client.model.vertex.formats.glyph.writer.GlyphVertexWriterFallback; import me.jellysquid.mods.sodium.client.model.vertex.type.BlittableVertexType; import me.jellysquid.mods.sodium.client.model.vertex.type.VanillaVertexType; public class GlyphVertexType implements VanillaVertexType<GlyphVertexSink>, BlittableVertexType<GlyphVertexSink> { @Override public GlyphVertexSink createBufferWriter(VertexBufferView buffer, boolean direct) { return direct ? new GlyphVertexBufferWriterUnsafe(buffer) : new GlyphVertexBufferWriterNio(buffer); } @Override public GlyphVertexSink createFallbackWriter(VertexConsumer consumer) { return new GlyphVertexWriterFallback(consumer); } @Override public VertexFormat getVertexFormat() { return GlyphVertexSink.VERTEX_FORMAT; } @Override public BlittableVertexType<GlyphVertexSink> asBlittable() { return this; } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\vertex\formats\line\LineVertexSink.java
package me.jellysquid.mods.sodium.client.model.vertex.formats.line; import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat; import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat; import me.jellysquid.mods.sodium.client.model.vertex.VertexSink; public interface LineVertexSink extends VertexSink { VertexFormat VERTEX_FORMAT = DefaultVertexFormat.POSITION_COLOR; }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\vertex\formats\line\LineVertexType.java
package me.jellysquid.mods.sodium.client.model.vertex.formats.line; import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat; import com.gtnewhorizons.angelica.compat.toremove.VertexConsumer; import me.jellysquid.mods.sodium.client.model.vertex.buffer.VertexBufferView; import me.jellysquid.mods.sodium.client.model.vertex.formats.line.writer.LineVertexBufferWriterNio; import me.jellysquid.mods.sodium.client.model.vertex.formats.line.writer.LineVertexBufferWriterUnsafe; import me.jellysquid.mods.sodium.client.model.vertex.formats.line.writer.LineVertexWriterFallback; import me.jellysquid.mods.sodium.client.model.vertex.type.BlittableVertexType; import me.jellysquid.mods.sodium.client.model.vertex.type.VanillaVertexType; public class LineVertexType implements VanillaVertexType<LineVertexSink>, BlittableVertexType<LineVertexSink> { @Override public LineVertexSink createBufferWriter(VertexBufferView buffer, boolean direct) { return direct ? new LineVertexBufferWriterUnsafe(buffer) : new LineVertexBufferWriterNio(buffer); } @Override public LineVertexSink createFallbackWriter(VertexConsumer consumer) { return new LineVertexWriterFallback(consumer); } @Override public VertexFormat getVertexFormat() { return LineVertexSink.VERTEX_FORMAT; } @Override public BlittableVertexType<LineVertexSink> asBlittable() { return this; } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\vertex\formats\particle\ParticleVertexSink.java
package me.jellysquid.mods.sodium.client.model.vertex.formats.particle; import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat; import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat; import me.jellysquid.mods.sodium.client.model.vertex.VertexSink; public interface ParticleVertexSink extends VertexSink { VertexFormat VERTEX_FORMAT = DefaultVertexFormat.POSITION_TEXTURE_COLOR_LIGHT; /** * @param x The x-position of the vertex * @param y The y-position of the vertex * @param z The z-position of the vertex * @param u The u-texture of the vertex * @param v The v-texture of the vertex * @param color The ABGR-packed color of the vertex * @param light The packed light map texture coordinates of the vertex */ void writeParticle(float x, float y, float z, float u, float v, int color, int light); }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\vertex\formats\particle\ParticleVertexType.java
package me.jellysquid.mods.sodium.client.model.vertex.formats.particle; import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat; import com.gtnewhorizons.angelica.compat.toremove.VertexConsumer; import me.jellysquid.mods.sodium.client.model.vertex.buffer.VertexBufferView; import me.jellysquid.mods.sodium.client.model.vertex.formats.particle.writer.ParticleVertexBufferWriterNio; import me.jellysquid.mods.sodium.client.model.vertex.formats.particle.writer.ParticleVertexBufferWriterUnsafe; import me.jellysquid.mods.sodium.client.model.vertex.formats.particle.writer.ParticleVertexWriterFallback; import me.jellysquid.mods.sodium.client.model.vertex.type.BlittableVertexType; import me.jellysquid.mods.sodium.client.model.vertex.type.VanillaVertexType; public class ParticleVertexType implements VanillaVertexType<ParticleVertexSink>, BlittableVertexType<ParticleVertexSink> { @Override public ParticleVertexSink createBufferWriter(VertexBufferView buffer, boolean direct) { return direct ? new ParticleVertexBufferWriterUnsafe(buffer) : new ParticleVertexBufferWriterNio(buffer); } @Override public ParticleVertexSink createFallbackWriter(VertexConsumer consumer) { return new ParticleVertexWriterFallback(consumer); } @Override public BlittableVertexType<ParticleVertexSink> asBlittable() { return this; } @Override public VertexFormat getVertexFormat() { return ParticleVertexSink.VERTEX_FORMAT; } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\vertex\formats\quad\QuadVertexSink.java
package me.jellysquid.mods.sodium.client.model.vertex.formats.quad; import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat; import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat; import com.gtnewhorizons.angelica.compat.toremove.MatrixStack; import me.jellysquid.mods.sodium.client.model.vertex.VertexSink; import me.jellysquid.mods.sodium.client.util.math.Matrix4fExtended; import me.jellysquid.mods.sodium.client.util.math.MatrixUtil; public interface QuadVertexSink extends VertexSink { VertexFormat VERTEX_FORMAT = DefaultVertexFormat.POSITION_COLOR_TEXTURE_LIGHT_NORMAL; /** * Writes a quad vertex to this sink. * * @param x The x-position of the vertex * @param y The y-position of the vertex * @param z The z-position of the vertex * @param color The ABGR-packed color of the vertex * @param u The u-texture of the vertex * @param v The y-texture of the vertex * @param light The packed light-map coordinates of the vertex * @param overlay The packed overlay-map coordinates of the vertex * @param normal The 3-byte packed normal vector of the vertex */ void writeQuad(float x, float y, float z, int color, float u, float v, int light, int overlay, int normal); /** * Writes a quad vertex to the sink, transformed by the given matrices. * * @param matrices The matrices to transform the vertex's position and normal vectors by */ default void writeQuad(MatrixStack.Entry matrices, float x, float y, float z, int color, float u, float v, int light, int overlay, int normal) { Matrix4fExtended modelMatrix = MatrixUtil.getExtendedMatrix(matrices.getModel()); float x2 = modelMatrix.transformVecX(x, y, z); float y2 = modelMatrix.transformVecY(x, y, z); float z2 = modelMatrix.transformVecZ(x, y, z); int norm = MatrixUtil.transformPackedNormal(normal, matrices.getNormal()); this.writeQuad(x2, y2, z2, color, u, v, light, overlay, norm); } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\vertex\formats\quad\QuadVertexType.java
package me.jellysquid.mods.sodium.client.model.vertex.formats.quad; import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat; import com.gtnewhorizons.angelica.compat.toremove.VertexConsumer; import me.jellysquid.mods.sodium.client.model.vertex.buffer.VertexBufferView; import me.jellysquid.mods.sodium.client.model.vertex.formats.quad.writer.QuadVertexBufferWriterNio; import me.jellysquid.mods.sodium.client.model.vertex.formats.quad.writer.QuadVertexBufferWriterUnsafe; import me.jellysquid.mods.sodium.client.model.vertex.formats.quad.writer.QuadVertexWriterFallback; import me.jellysquid.mods.sodium.client.model.vertex.type.BlittableVertexType; import me.jellysquid.mods.sodium.client.model.vertex.type.VanillaVertexType; public class QuadVertexType implements VanillaVertexType<QuadVertexSink>, BlittableVertexType<QuadVertexSink> { @Override public QuadVertexSink createFallbackWriter(VertexConsumer consumer) { return new QuadVertexWriterFallback(consumer); } @Override public QuadVertexSink createBufferWriter(VertexBufferView buffer, boolean direct) { return direct ? new QuadVertexBufferWriterUnsafe(buffer) : new QuadVertexBufferWriterNio(buffer); } @Override public VertexFormat getVertexFormat() { return QuadVertexSink.VERTEX_FORMAT; } @Override public BlittableVertexType<QuadVertexSink> asBlittable() { return this; } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\vertex\formats\screen_quad\BasicScreenQuadVertexSink.java
package me.jellysquid.mods.sodium.client.model.vertex.formats.screen_quad; import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat; import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat; import me.jellysquid.mods.sodium.client.model.vertex.VertexSink; import me.jellysquid.mods.sodium.client.util.math.Matrix4fExtended; import me.jellysquid.mods.sodium.client.util.math.MatrixUtil; import org.joml.Matrix4f; public interface BasicScreenQuadVertexSink extends VertexSink { VertexFormat VERTEX_FORMAT = DefaultVertexFormat.POSITION_COLOR; /** * Writes a quad vertex to this sink. * * @param x The x-position of the vertex * @param y The y-position of the vertex * @param z The z-position of the vertex * @param color The ABGR-packed color of the vertex */ void writeQuad(float x, float y, float z, int color); /** * Writes a quad vertex to the sink, transformed by the given matrix. * * @param matrix The matrix to transform the vertex's position by */ default void writeQuad(Matrix4f matrix, float x, float y, float z, int color) { Matrix4fExtended modelMatrix = MatrixUtil.getExtendedMatrix(matrix); float x2 = modelMatrix.transformVecX(x, y, z); float y2 = modelMatrix.transformVecY(x, y, z); float z2 = modelMatrix.transformVecZ(x, y, z); this.writeQuad(x2, y2, z2, color); } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\vertex\formats\screen_quad\BasicScreenQuadVertexType.java
package me.jellysquid.mods.sodium.client.model.vertex.formats.screen_quad; import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat; import com.gtnewhorizons.angelica.compat.toremove.VertexConsumer; import me.jellysquid.mods.sodium.client.model.vertex.buffer.VertexBufferView; import me.jellysquid.mods.sodium.client.model.vertex.formats.screen_quad.writer.BasicScreenQuadVertexBufferWriterNio; import me.jellysquid.mods.sodium.client.model.vertex.formats.screen_quad.writer.BasicScreenQuadVertexBufferWriterUnsafe; import me.jellysquid.mods.sodium.client.model.vertex.formats.screen_quad.writer.BasicScreenQuadVertexWriterFallback; import me.jellysquid.mods.sodium.client.model.vertex.type.BlittableVertexType; import me.jellysquid.mods.sodium.client.model.vertex.type.VanillaVertexType; public class BasicScreenQuadVertexType implements VanillaVertexType<BasicScreenQuadVertexSink>, BlittableVertexType<BasicScreenQuadVertexSink> { @Override public BasicScreenQuadVertexSink createFallbackWriter(VertexConsumer consumer) { return new BasicScreenQuadVertexWriterFallback(consumer); } @Override public BasicScreenQuadVertexSink createBufferWriter(VertexBufferView buffer, boolean direct) { return direct ? new BasicScreenQuadVertexBufferWriterUnsafe(buffer) : new BasicScreenQuadVertexBufferWriterNio(buffer); } @Override public VertexFormat getVertexFormat() { return BasicScreenQuadVertexSink.VERTEX_FORMAT; } @Override public BlittableVertexType<BasicScreenQuadVertexSink> asBlittable() { return this; } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\vertex\formats\glyph\writer\GlyphVertexBufferWriterNio.java
package me.jellysquid.mods.sodium.client.model.vertex.formats.glyph.writer; import me.jellysquid.mods.sodium.client.model.vertex.VanillaVertexTypes; import me.jellysquid.mods.sodium.client.model.vertex.buffer.VertexBufferView; import me.jellysquid.mods.sodium.client.model.vertex.buffer.VertexBufferWriterNio; import me.jellysquid.mods.sodium.client.model.vertex.formats.glyph.GlyphVertexSink; import java.nio.ByteBuffer; public class GlyphVertexBufferWriterNio extends VertexBufferWriterNio implements GlyphVertexSink { public GlyphVertexBufferWriterNio(VertexBufferView backingBuffer) { super(backingBuffer, VanillaVertexTypes.GLYPHS); } @Override public void writeGlyph(float x, float y, float z, int color, float u, float v, int light) { int i = this.writeOffset; ByteBuffer buffer = this.byteBuffer; buffer.putFloat(i, x); buffer.putFloat(i + 4, y); buffer.putFloat(i + 8, z); buffer.putInt(i + 12, color); buffer.putFloat(i + 16, u); buffer.putFloat(i + 20, v); buffer.putInt(i + 24, light); this.advance(); } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\vertex\formats\glyph\writer\GlyphVertexBufferWriterUnsafe.java
package me.jellysquid.mods.sodium.client.model.vertex.formats.glyph.writer; import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.*; import me.jellysquid.mods.sodium.client.model.vertex.VanillaVertexTypes; import me.jellysquid.mods.sodium.client.model.vertex.buffer.VertexBufferView; import me.jellysquid.mods.sodium.client.model.vertex.buffer.VertexBufferWriterUnsafe; import me.jellysquid.mods.sodium.client.model.vertex.formats.glyph.GlyphVertexSink; public class GlyphVertexBufferWriterUnsafe extends VertexBufferWriterUnsafe implements GlyphVertexSink { public GlyphVertexBufferWriterUnsafe(VertexBufferView backingBuffer) { super(backingBuffer, VanillaVertexTypes.GLYPHS); } @Override public void writeGlyph(float x, float y, float z, int color, float u, float v, int light) { long i = this.writePointer; memPutFloat(i, x); memPutFloat(i + 4, y); memPutFloat(i + 8, z); memPutInt(i + 12, color); memPutFloat(i + 16, u); memPutFloat(i + 20, v); memPutInt(i + 24, light); this.advance(); } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\vertex\formats\glyph\writer\GlyphVertexWriterFallback.java
package me.jellysquid.mods.sodium.client.model.vertex.formats.glyph.writer; import com.gtnewhorizon.gtnhlib.client.renderer.cel.api.util.ColorABGR; import com.gtnewhorizons.angelica.compat.toremove.VertexConsumer; import me.jellysquid.mods.sodium.client.model.vertex.fallback.VertexWriterFallback; import me.jellysquid.mods.sodium.client.model.vertex.formats.glyph.GlyphVertexSink; public class GlyphVertexWriterFallback extends VertexWriterFallback implements GlyphVertexSink { public GlyphVertexWriterFallback(VertexConsumer consumer) { super(consumer); } @Override public void writeGlyph(float x, float y, float z, int color, float u, float v, int light) { VertexConsumer consumer = this.consumer; consumer.vertex(x, y, z); consumer.color(ColorABGR.unpackRed(color), ColorABGR.unpackGreen(color), ColorABGR.unpackBlue(color), ColorABGR.unpackAlpha(color)); consumer.texture(u, v); consumer.light(light); consumer.next(); } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\vertex\formats\line\writer\LineVertexBufferWriterNio.java
package me.jellysquid.mods.sodium.client.model.vertex.formats.line.writer; import me.jellysquid.mods.sodium.client.model.vertex.VanillaVertexTypes; import me.jellysquid.mods.sodium.client.model.vertex.buffer.VertexBufferView; import me.jellysquid.mods.sodium.client.model.vertex.buffer.VertexBufferWriterNio; import me.jellysquid.mods.sodium.client.model.vertex.formats.line.LineVertexSink; public class LineVertexBufferWriterNio extends VertexBufferWriterNio implements LineVertexSink { public LineVertexBufferWriterNio(VertexBufferView backingBuffer) { super(backingBuffer, VanillaVertexTypes.LINES); } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\vertex\formats\line\writer\LineVertexBufferWriterUnsafe.java
package me.jellysquid.mods.sodium.client.model.vertex.formats.line.writer; import me.jellysquid.mods.sodium.client.model.vertex.VanillaVertexTypes; import me.jellysquid.mods.sodium.client.model.vertex.buffer.VertexBufferView; import me.jellysquid.mods.sodium.client.model.vertex.buffer.VertexBufferWriterUnsafe; import me.jellysquid.mods.sodium.client.model.vertex.formats.line.LineVertexSink; public class LineVertexBufferWriterUnsafe extends VertexBufferWriterUnsafe implements LineVertexSink { public LineVertexBufferWriterUnsafe(VertexBufferView backingBuffer) { super(backingBuffer, VanillaVertexTypes.LINES); } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\vertex\formats\line\writer\LineVertexWriterFallback.java
package me.jellysquid.mods.sodium.client.model.vertex.formats.line.writer; import com.gtnewhorizons.angelica.compat.toremove.VertexConsumer; import me.jellysquid.mods.sodium.client.model.vertex.fallback.VertexWriterFallback; import me.jellysquid.mods.sodium.client.model.vertex.formats.line.LineVertexSink; public class LineVertexWriterFallback extends VertexWriterFallback implements LineVertexSink { public LineVertexWriterFallback(VertexConsumer consumer) { super(consumer); } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\vertex\formats\particle\writer\ParticleVertexBufferWriterNio.java
package me.jellysquid.mods.sodium.client.model.vertex.formats.particle.writer; import me.jellysquid.mods.sodium.client.model.vertex.VanillaVertexTypes; import me.jellysquid.mods.sodium.client.model.vertex.buffer.VertexBufferView; import me.jellysquid.mods.sodium.client.model.vertex.buffer.VertexBufferWriterNio; import me.jellysquid.mods.sodium.client.model.vertex.formats.particle.ParticleVertexSink; import java.nio.ByteBuffer; public class ParticleVertexBufferWriterNio extends VertexBufferWriterNio implements ParticleVertexSink { public ParticleVertexBufferWriterNio(VertexBufferView backingBuffer) { super(backingBuffer, VanillaVertexTypes.PARTICLES); } @Override public void writeParticle(float x, float y, float z, float u, float v, int color, int light) { int i = this.writeOffset; ByteBuffer buffer = this.byteBuffer; buffer.putFloat(i, x); buffer.putFloat(i + 4, y); buffer.putFloat(i + 8, z); buffer.putFloat(i + 12, u); buffer.putFloat(i + 16, v); buffer.putInt(i + 20, color); buffer.putInt(i + 24, light); this.advance(); } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\vertex\formats\particle\writer\ParticleVertexBufferWriterUnsafe.java
package me.jellysquid.mods.sodium.client.model.vertex.formats.particle.writer; import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.*; import me.jellysquid.mods.sodium.client.model.vertex.VanillaVertexTypes; import me.jellysquid.mods.sodium.client.model.vertex.buffer.VertexBufferView; import me.jellysquid.mods.sodium.client.model.vertex.buffer.VertexBufferWriterUnsafe; import me.jellysquid.mods.sodium.client.model.vertex.formats.particle.ParticleVertexSink; public class ParticleVertexBufferWriterUnsafe extends VertexBufferWriterUnsafe implements ParticleVertexSink { public ParticleVertexBufferWriterUnsafe(VertexBufferView backingBuffer) { super(backingBuffer, VanillaVertexTypes.PARTICLES); } @Override public void writeParticle(float x, float y, float z, float u, float v, int color, int light) { long i = this.writePointer; memPutFloat(i, x); memPutFloat(i + 4, y); memPutFloat(i + 8, z); memPutFloat(i + 12, u); memPutFloat(i + 16, v); memPutInt(i + 20, color); memPutInt(i + 24, light); this.advance(); } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\vertex\formats\particle\writer\ParticleVertexWriterFallback.java
package me.jellysquid.mods.sodium.client.model.vertex.formats.particle.writer; import com.gtnewhorizon.gtnhlib.client.renderer.cel.api.util.ColorABGR; import com.gtnewhorizons.angelica.compat.toremove.VertexConsumer; import me.jellysquid.mods.sodium.client.model.vertex.fallback.VertexWriterFallback; import me.jellysquid.mods.sodium.client.model.vertex.formats.particle.ParticleVertexSink; public class ParticleVertexWriterFallback extends VertexWriterFallback implements ParticleVertexSink { public ParticleVertexWriterFallback(VertexConsumer consumer) { super(consumer); } @Override public void writeParticle(float x, float y, float z, float u, float v, int color, int light) { VertexConsumer consumer = this.consumer; consumer.vertex(x, y, z); consumer.texture(u, v); consumer.color(ColorABGR.unpackRed(color), ColorABGR.unpackGreen(color), ColorABGR.unpackBlue(color), ColorABGR.unpackAlpha(color)); consumer.light(light); consumer.next(); } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\vertex\formats\quad\writer\QuadVertexBufferWriterNio.java
package me.jellysquid.mods.sodium.client.model.vertex.formats.quad.writer; import me.jellysquid.mods.sodium.client.model.vertex.VanillaVertexTypes; import me.jellysquid.mods.sodium.client.model.vertex.buffer.VertexBufferView; import me.jellysquid.mods.sodium.client.model.vertex.buffer.VertexBufferWriterNio; import me.jellysquid.mods.sodium.client.model.vertex.formats.quad.QuadVertexSink; import java.nio.ByteBuffer; public class QuadVertexBufferWriterNio extends VertexBufferWriterNio implements QuadVertexSink { public QuadVertexBufferWriterNio(VertexBufferView backingBuffer) { super(backingBuffer, VanillaVertexTypes.QUADS); } @Override public void writeQuad(float x, float y, float z, int color, float u, float v, int light, int overlay, int normal) { final int i = this.writeOffset; final ByteBuffer buf = this.byteBuffer; buf.putFloat(i, x); buf.putFloat(i + 4, y); buf.putFloat(i + 8, z); buf.putInt(i + 12, color); buf.putFloat(i + 16, u); buf.putFloat(i + 20, v); buf.putInt(i + 24, overlay); buf.putInt(i + 28, light); buf.putInt(i + 32, normal); this.advance(); } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\vertex\formats\quad\writer\QuadVertexBufferWriterUnsafe.java
package me.jellysquid.mods.sodium.client.model.vertex.formats.quad.writer; import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.*; import me.jellysquid.mods.sodium.client.model.vertex.VanillaVertexTypes; import me.jellysquid.mods.sodium.client.model.vertex.buffer.VertexBufferView; import me.jellysquid.mods.sodium.client.model.vertex.buffer.VertexBufferWriterUnsafe; import me.jellysquid.mods.sodium.client.model.vertex.formats.quad.QuadVertexSink; public class QuadVertexBufferWriterUnsafe extends VertexBufferWriterUnsafe implements QuadVertexSink { public QuadVertexBufferWriterUnsafe(VertexBufferView backingBuffer) { super(backingBuffer, VanillaVertexTypes.QUADS); } @Override public void writeQuad(float x, float y, float z, int color, float u, float v, int light, int overlay, int normal) { final long i = this.writePointer; memPutFloat(i, x); memPutFloat(i + 4, y); memPutFloat(i + 8, z); memPutInt(i + 12, color); memPutFloat(i + 16, u); memPutFloat(i + 20, v); memPutInt(i + 24, overlay); memPutInt(i + 28, light); memPutInt(i + 32, normal); this.advance(); } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\vertex\formats\quad\writer\QuadVertexWriterFallback.java
package me.jellysquid.mods.sodium.client.model.vertex.formats.quad.writer; import com.gtnewhorizon.gtnhlib.client.renderer.cel.api.util.ColorABGR; import com.gtnewhorizon.gtnhlib.client.renderer.cel.api.util.NormI8; import com.gtnewhorizons.angelica.compat.toremove.VertexConsumer; import me.jellysquid.mods.sodium.client.model.vertex.fallback.VertexWriterFallback; import me.jellysquid.mods.sodium.client.model.vertex.formats.quad.QuadVertexSink; public class QuadVertexWriterFallback extends VertexWriterFallback implements QuadVertexSink { public QuadVertexWriterFallback(VertexConsumer consumer) { super(consumer); } @Override public void writeQuad(float x, float y, float z, int color, float u, float v, int light, int overlay, int normal) { VertexConsumer consumer = this.consumer; consumer.vertex(x, y, z); consumer.color(ColorABGR.unpackRed(color), ColorABGR.unpackGreen(color), ColorABGR.unpackBlue(color), ColorABGR.unpackAlpha(color)); consumer.texture(u, v); consumer.overlay(overlay); consumer.light(light); consumer.normal(NormI8.unpackX(normal), NormI8.unpackY(normal), NormI8.unpackZ(normal)); consumer.next(); } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\vertex\formats\screen_quad\writer\BasicScreenQuadVertexBufferWriterNio.java
package me.jellysquid.mods.sodium.client.model.vertex.formats.screen_quad.writer; import me.jellysquid.mods.sodium.client.model.vertex.VanillaVertexTypes; import me.jellysquid.mods.sodium.client.model.vertex.buffer.VertexBufferView; import me.jellysquid.mods.sodium.client.model.vertex.buffer.VertexBufferWriterNio; import me.jellysquid.mods.sodium.client.model.vertex.formats.screen_quad.BasicScreenQuadVertexSink; import java.nio.ByteBuffer; public class BasicScreenQuadVertexBufferWriterNio extends VertexBufferWriterNio implements BasicScreenQuadVertexSink { public BasicScreenQuadVertexBufferWriterNio(VertexBufferView backingBuffer) { super(backingBuffer, VanillaVertexTypes.BASIC_SCREEN_QUADS); } @Override public void writeQuad(float x, float y, float z, int color) { int i = this.writeOffset; ByteBuffer buf = this.byteBuffer; buf.putFloat(i, x); buf.putFloat(i + 4, y); buf.putFloat(i + 8, z); buf.putInt(i + 12, color); this.advance(); } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\vertex\formats\screen_quad\writer\BasicScreenQuadVertexBufferWriterUnsafe.java
package me.jellysquid.mods.sodium.client.model.vertex.formats.screen_quad.writer; import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.*; import me.jellysquid.mods.sodium.client.model.vertex.VanillaVertexTypes; import me.jellysquid.mods.sodium.client.model.vertex.buffer.VertexBufferView; import me.jellysquid.mods.sodium.client.model.vertex.buffer.VertexBufferWriterUnsafe; import me.jellysquid.mods.sodium.client.model.vertex.formats.screen_quad.BasicScreenQuadVertexSink; public class BasicScreenQuadVertexBufferWriterUnsafe extends VertexBufferWriterUnsafe implements BasicScreenQuadVertexSink { public BasicScreenQuadVertexBufferWriterUnsafe(VertexBufferView backingBuffer) { super(backingBuffer, VanillaVertexTypes.BASIC_SCREEN_QUADS); } @Override public void writeQuad(float x, float y, float z, int color) { long i = this.writePointer; memPutFloat(i, x); memPutFloat(i + 4, y); memPutFloat(i + 8, z); memPutInt(i + 12, color); this.advance(); } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\model\vertex\formats\screen_quad\writer\BasicScreenQuadVertexWriterFallback.java
package me.jellysquid.mods.sodium.client.model.vertex.formats.screen_quad.writer; import com.gtnewhorizon.gtnhlib.client.renderer.cel.api.util.ColorABGR; import com.gtnewhorizons.angelica.compat.toremove.VertexConsumer; import me.jellysquid.mods.sodium.client.model.vertex.fallback.VertexWriterFallback; import me.jellysquid.mods.sodium.client.model.vertex.formats.screen_quad.BasicScreenQuadVertexSink; public class BasicScreenQuadVertexWriterFallback extends VertexWriterFallback implements BasicScreenQuadVertexSink { public BasicScreenQuadVertexWriterFallback(VertexConsumer consumer) { super(consumer); } @Override public void writeQuad(float x, float y, float z, int color) { VertexConsumer consumer = this.consumer; consumer.vertex(x, y, z); consumer.color(ColorABGR.unpackRed(color), ColorABGR.unpackGreen(color), ColorABGR.unpackBlue(color), ColorABGR.unpackAlpha(color)); consumer.next(); } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\ChunkCameraContext.java
package me.jellysquid.mods.sodium.client.render.chunk; public class ChunkCameraContext { public final int blockOriginX, blockOriginY, blockOriginZ; public final float originX, originY, originZ; public ChunkCameraContext(double x, double y, double z) { this.blockOriginX = (int) x; this.blockOriginY = (int) y; this.blockOriginZ = (int) z; this.originX = (float) (x - this.blockOriginX); this.originY = (float) (y - this.blockOriginY); this.originZ = (float) (z - this.blockOriginZ); } public float getChunkModelOffset(int chunkBlockPos, int cameraBlockPos, float cameraPos) { int t = chunkBlockPos - cameraBlockPos; return t - cameraPos; } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\ChunkGraphicsState.java
package me.jellysquid.mods.sodium.client.render.chunk; import me.jellysquid.mods.sodium.client.gl.device.CommandList; import java.nio.ByteBuffer; public abstract class ChunkGraphicsState { private final int x, y, z; private ByteBuffer translucencyData; protected ChunkGraphicsState(ChunkRenderContainer<?> container) { this.x = container.getRenderX(); this.y = container.getRenderY(); this.z = container.getRenderZ(); } public abstract void delete(CommandList commandList); public int getX() { return this.x; } public int getY() { return this.y; } public int getZ() { return this.z; } public ByteBuffer getTranslucencyData() { return this.translucencyData; } public void setTranslucencyData(ByteBuffer data) { this.translucencyData = data; } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\ChunkRenderBackend.java
package me.jellysquid.mods.sodium.client.render.chunk; import com.gtnewhorizons.angelica.compat.toremove.MatrixStack; import me.jellysquid.mods.sodium.client.gl.device.CommandList; import me.jellysquid.mods.sodium.client.gl.device.RenderDevice; import me.jellysquid.mods.sodium.client.model.vertex.type.ChunkVertexType; import me.jellysquid.mods.sodium.client.render.chunk.compile.ChunkBuildResult; import me.jellysquid.mods.sodium.client.render.chunk.lists.ChunkRenderListIterator; import me.jellysquid.mods.sodium.client.render.chunk.passes.BlockRenderPass; import java.util.Collections; import java.util.Iterator; import java.util.List; /** * The chunk render backend takes care of managing the graphics resource state of chunk render containers. This includes * the handling of uploading their data to the graphics card and rendering responsibilities. * @param <T> The type of graphics state to be used in chunk render containers */ public interface ChunkRenderBackend<T extends ChunkGraphicsState> { /** * Drains the iterator of items and processes each build task's result serially. After this method returns, all * drained results should be processed. */ void upload(CommandList commandList, Iterator<ChunkBuildResult<T>> queue); /** * Renders the given chunk render list to the active framebuffer. * @param commandList The command list which OpenGL commands should be serialized to * @param renders An iterator over the list of chunks to be rendered * @param camera The camera context containing chunk offsets for the current render */ void render(CommandList commandList, ChunkRenderListIterator<T> renders, ChunkCameraContext camera); void createShaders(RenderDevice device); void begin(MatrixStack matrixStack); void end(MatrixStack matrixStack); /** * Deletes this render backend and any resources attached to it. */ void delete(); /** * Returns the vertex format used by this chunk render backend for rendering meshes. */ ChunkVertexType getVertexType(); Class<T> getGraphicsStateType(); default String getRendererName() { return this.getClass().getSimpleName(); } default List<String> getDebugStrings() { return Collections.emptyList(); } void iris$begin(MatrixStack matrixStack, BlockRenderPass pass); }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\ChunkRenderColumn.java
package me.jellysquid.mods.sodium.client.render.chunk; import static com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.properties.ModelQuadFacing.HORIZONTAL_DIRECTIONS; import static com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.properties.ModelQuadFacing.NEG_X; import static com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.properties.ModelQuadFacing.NEG_Z; import static com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.properties.ModelQuadFacing.POS_X; import static com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.properties.ModelQuadFacing.POS_Z; import net.minecraftforge.common.util.ForgeDirection; public class ChunkRenderColumn<T extends ChunkGraphicsState> { @SuppressWarnings("unchecked") private final ChunkRenderContainer<T>[] renders = new ChunkRenderContainer[16]; @SuppressWarnings("unchecked") private final ChunkRenderColumn<T>[] adjacent = new ChunkRenderColumn[6]; private final int x, z; public ChunkRenderColumn(int x, int z) { this.x = x; this.z = z; this.setAdjacentColumn(ForgeDirection.UP, this); this.setAdjacentColumn(ForgeDirection.DOWN, this); } public void setAdjacentColumn(ForgeDirection dir, ChunkRenderColumn<T> column) { this.adjacent[dir.ordinal()] = column; } public ChunkRenderColumn<T> getAdjacentColumn(ForgeDirection dir) { return this.adjacent[dir.ordinal()]; } public void setRender(int y, ChunkRenderContainer<T> render) { this.renders[y] = render; } public ChunkRenderContainer<T> getRender(int y) { if (y < 0 || y >= this.renders.length) { return null; } return this.renders[y]; } public int getX() { return this.x; } public int getZ() { return this.z; } public boolean areNeighborsPresent() { for (var dir : HORIZONTAL_DIRECTIONS) { ChunkRenderColumn<T> adj = this.adjacent[dir.ordinal()]; if (adj == null) { return false; } ForgeDirection corner; // Access the adjacent corner chunk from the neighbor in this direction if (dir == NEG_Z) { corner = ForgeDirection.EAST; } else if (dir == POS_Z) { corner = ForgeDirection.WEST; } else if (dir == NEG_X) { corner = ForgeDirection.NORTH; } else if (dir == POS_X) { corner = ForgeDirection.SOUTH; } else { continue; } // If no neighbor has been attached, the chunk is not present if (adj.getAdjacentColumn(corner) == null) { return false; } } return true; } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\ChunkRenderContainer.java
package me.jellysquid.mods.sodium.client.render.chunk; import com.gtnewhorizon.gtnhlib.blockpos.BlockPos; import com.gtnewhorizons.angelica.compat.mojang.ChunkSectionPos; import com.gtnewhorizons.angelica.utils.AnimationsRenderUtils; import lombok.Getter; import me.jellysquid.mods.sodium.client.gl.device.RenderDevice; import me.jellysquid.mods.sodium.client.render.SodiumWorldRenderer; import me.jellysquid.mods.sodium.client.render.chunk.data.ChunkRenderBounds; import me.jellysquid.mods.sodium.client.render.chunk.data.ChunkRenderData; import me.jellysquid.mods.sodium.client.render.chunk.passes.BlockRenderPass; import me.jellysquid.mods.sodium.client.util.math.FrustumExtended; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import java.lang.reflect.Array; import java.util.concurrent.CompletableFuture; /** * The render state object for a chunk section. This contains all the graphics state for each render pass along with * data about the render in the chunk visibility graph. */ public class ChunkRenderContainer<T extends ChunkGraphicsState> { private final SodiumWorldRenderer worldRenderer; @Getter private final int chunkX; @Getter private final int chunkY; @Getter private final int chunkZ; @Getter private final T[] graphicsStates; private final ChunkRenderColumn<T> column; @Getter private ChunkRenderData data = ChunkRenderData.ABSENT; private CompletableFuture<Void> rebuildTask = null; private boolean needsRebuild; private boolean needsImportantRebuild; private boolean needsSort; @Getter private boolean tickable; @Getter private int id; private boolean rebuildableForTranslucents; @SuppressWarnings("unchecked") public ChunkRenderContainer(ChunkRenderBackend<T> backend, SodiumWorldRenderer worldRenderer, int chunkX, int chunkY, int chunkZ, ChunkRenderColumn<T> column) { this.worldRenderer = worldRenderer; this.chunkX = chunkX; this.chunkY = chunkY; this.chunkZ = chunkZ; //noinspection unchecked this.graphicsStates = (T[]) Array.newInstance(backend.getGraphicsStateType(), BlockRenderPass.COUNT); this.rebuildableForTranslucents = false; this.column = column; } /** * Cancels any pending tasks to rebuild the chunk. If the result of any pending tasks has not been processed yet, * those will also be discarded when processing finally happens. */ public void cancelRebuildTask() { this.needsRebuild = false; this.needsImportantRebuild = false; this.needsSort = false; if (this.rebuildTask != null) { this.rebuildTask.cancel(false); this.rebuildTask = null; } } /** * @return True if the render's state is out of date with the world state */ public boolean needsRebuild() { return this.needsRebuild; } /** * @return True if the render's rebuild should be performed as blocking */ public boolean needsImportantRebuild() { return this.needsImportantRebuild; } public boolean needsSort() { return this.needsSort; } /** * Deletes all data attached to this render and drops any pending tasks. This should be used when the render falls * out of view or otherwise needs to be destroyed. After the render has been destroyed, the object can no longer * be used. */ public void delete() { this.cancelRebuildTask(); this.setData(ChunkRenderData.ABSENT); this.deleteGraphicsState(); } private void deleteGraphicsState() { T[] states = this.graphicsStates; for (int i = 0; i < states.length; i++) { T state = states[i]; if (state != null) { state.delete(RenderDevice.INSTANCE.createCommandList()); states[i] = null; } } } public boolean shouldRebuildForTranslucents() { return this.rebuildableForTranslucents; } public void setRebuildForTranslucents(boolean flag) { this.rebuildableForTranslucents = flag; } public void setData(ChunkRenderData info) { if (info == null) { throw new NullPointerException("Mesh information must not be null"); } this.worldRenderer.onChunkRenderUpdated(this.chunkX, this.chunkY, this.chunkZ, this.data, info); this.data = info; this.tickable = !info.getAnimatedSprites().isEmpty(); } /** * Marks this render as needing an update. Important updates are scheduled as "blocking" and will prevent the next * frame from being rendered until the update is performed. * @param important True if the update is blocking, otherwise false */ public boolean scheduleRebuild(boolean important) { boolean changed = !this.needsRebuild || (!this.needsImportantRebuild && important); this.needsImportantRebuild = important; this.needsRebuild = true; this.needsSort = false; return changed; } public boolean scheduleSort(boolean important) { if (this.needsRebuild) return false; boolean changed = !this.needsSort; this.needsSort = true; return changed; } /** * @return True if the chunk render contains no data, otherwise false */ public boolean isEmpty() { return this.data.isEmpty(); } /** * Returns the chunk section position which this render refers to in the world. */ public ChunkSectionPos getChunkPos() { return ChunkSectionPos.from(this.chunkX, this.chunkY, this.chunkZ); } /** * Tests if the given chunk render is visible within the provided frustum. * @param frustum The frustum to test against * @return True if visible, otherwise false */ public boolean isOutsideFrustum(FrustumExtended frustum) { float x = this.getOriginX(); float y = this.getOriginY(); float z = this.getOriginZ(); return !frustum.fastAabbTest(x, y, z, x + 16.0f, y + 16.0f, z + 16.0f); } /** * Ensures that all resources attached to the given chunk render are "ticked" forward. This should be called every * time before this render is drawn if {@link ChunkRenderContainer#isTickable()} is true. */ public void tick() { for (TextureAtlasSprite sprite : this.data.getAnimatedSprites()) { AnimationsRenderUtils.markBlockTextureForUpdate(sprite); } } /** * @return The x-coordinate of the origin position of this chunk render */ public int getOriginX() { return this.chunkX << 4; } /** * @return The y-coordinate of the origin position of this chunk render */ public int getOriginY() { return this.chunkY << 4; } /** * @return The z-coordinate of the origin position of this chunk render */ public int getOriginZ() { return this.chunkZ << 4; } public int getRenderX() { return this.getOriginX() - 8; } public int getRenderY() { return this.getOriginY() - 8; } public int getRenderZ() { return this.getOriginZ() - 8; } /** * @return The squared distance from the center of this chunk in the world to the given position */ public double getSquaredDistance(double x, double y, double z) { double xDist = x - this.getCenterX(); double yDist = y - this.getCenterY(); double zDist = z - this.getCenterZ(); return (xDist * xDist) + (yDist * yDist) + (zDist * zDist); } /** * @return The x-coordinate of the center position of this chunk render */ private double getCenterX() { return this.getOriginX() + 8.0D; } /** * @return The y-coordinate of the center position of this chunk render */ private double getCenterY() { return this.getOriginY() + 8.0D; } /** * @return The z-coordinate of the center position of this chunk render */ private double getCenterZ() { return this.getOriginZ() + 8.0D; } public BlockPos getRenderOrigin() { return new BlockPos(this.getRenderX(), this.getRenderY(), this.getRenderZ()); } public void setGraphicsState(BlockRenderPass pass, T state) { this.graphicsStates[pass.ordinal()] = state; } /** * @return The squared distance from the center of this chunk in the world to the given position */ public double getSquaredDistanceXZ(double x, double z) { double xDist = x - this.getCenterX(); double zDist = z - this.getCenterZ(); return (xDist * xDist) + (zDist * zDist); } public ChunkRenderBounds getBounds() { return this.data.getBounds(); } public T getGraphicsState(BlockRenderPass pass) { return this.graphicsStates[pass.ordinal()]; } public int getFacesWithData() { return this.data.getFacesWithData(); } public boolean canRebuild() { return this.column.areNeighborsPresent(); } public void setId(int id) { this.id = id; } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\ChunkRenderManager.java
package me.jellysquid.mods.sodium.client.render.chunk; import com.gtnewhorizons.angelica.compat.mojang.Camera; import com.gtnewhorizons.angelica.compat.mojang.ChunkPos; import com.gtnewhorizons.angelica.compat.toremove.MatrixStack; import com.gtnewhorizons.angelica.rendering.AngelicaRenderQueue; import net.coderbot.iris.Iris; import it.unimi.dsi.fastutil.ints.IntIterator; import it.unimi.dsi.fastutil.ints.IntList; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; import it.unimi.dsi.fastutil.longs.LongCollection; import it.unimi.dsi.fastutil.longs.LongIterator; import it.unimi.dsi.fastutil.objects.ObjectArrayFIFOQueue; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import it.unimi.dsi.fastutil.objects.ObjectList; import lombok.Getter; import me.jellysquid.mods.sodium.client.SodiumClientMod; import me.jellysquid.mods.sodium.client.gl.compat.FogHelper; import me.jellysquid.mods.sodium.client.gl.device.CommandList; import me.jellysquid.mods.sodium.client.gl.device.RenderDevice; import me.jellysquid.mods.sodium.client.render.SodiumWorldRenderer; import me.jellysquid.mods.sodium.client.render.chunk.backends.multidraw.MultidrawChunkRenderBackend; import me.jellysquid.mods.sodium.client.render.chunk.compile.ChunkBuildResult; import me.jellysquid.mods.sodium.client.render.chunk.compile.ChunkBuilder; import me.jellysquid.mods.sodium.client.render.chunk.cull.ChunkCuller; import me.jellysquid.mods.sodium.client.render.chunk.cull.ChunkFaceFlags; import me.jellysquid.mods.sodium.client.render.chunk.cull.graph.ChunkGraphCuller; import me.jellysquid.mods.sodium.client.render.chunk.data.ChunkRenderBounds; import me.jellysquid.mods.sodium.client.render.chunk.data.ChunkRenderData; import me.jellysquid.mods.sodium.client.render.chunk.lists.ChunkRenderList; import me.jellysquid.mods.sodium.client.render.chunk.lists.ChunkRenderListIterator; import me.jellysquid.mods.sodium.client.render.chunk.passes.BlockRenderPass; import me.jellysquid.mods.sodium.client.util.math.FrustumExtended; import me.jellysquid.mods.sodium.client.world.ChunkStatusListener; import me.jellysquid.mods.sodium.common.util.IdTable; import me.jellysquid.mods.sodium.common.util.collections.FutureDequeDrain; import net.coderbot.iris.shadows.ShadowRenderingState; import net.coderbot.iris.sodium.shadow_map.SwappableChunkRenderManager; import net.minecraft.client.multiplayer.WorldClient; import net.minecraft.client.renderer.WorldRenderer; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.chunk.storage.ExtendedBlockStorage; import net.minecraftforge.common.util.ForgeDirection; import org.joml.Vector3d; import java.util.ArrayDeque; import java.util.Collection; import java.util.Deque; import java.util.concurrent.CompletableFuture; public class ChunkRenderManager<T extends ChunkGraphicsState> implements ChunkStatusListener, SwappableChunkRenderManager { /** * The maximum distance a chunk can be from the player's camera in order to be eligible for blocking updates. */ private static final double NEARBY_CHUNK_DISTANCE = Math.pow(48, 2.0); /** * The minimum distance the culling plane can be from the player's camera. This helps to prevent mathematical * errors that occur when the fog distance is less than 8 blocks in width, such as when using a blindness potion. */ private static final float FOG_PLANE_MIN_DISTANCE = (float) Math.pow(8.0f, 2.0); /** * The distance past the fog's far plane at which to begin culling. Distance calculations use the center of each * chunk from the camera's position, and as such, special care is needed to ensure that the culling plane is pushed * back far enough. I'm sure there's a mathematical formula that should be used here in place of the constant, * but this value works fine in testing. */ private static final float FOG_PLANE_OFFSET = 12.0f; private final ChunkBuilder<T> builder; private final ChunkRenderBackend<T> backend; private final Thread renderThread = Thread.currentThread(); private final Long2ObjectOpenHashMap<ChunkRenderColumn<T>> columns = new Long2ObjectOpenHashMap<>(); private final IdTable<ChunkRenderContainer<T>> renders = new IdTable<>(16384); private final ObjectArrayFIFOQueue<ChunkRenderContainer<T>> importantRebuildQueue = new ObjectArrayFIFOQueue<>(); private final ObjectArrayFIFOQueue<ChunkRenderContainer<T>> rebuildQueue = new ObjectArrayFIFOQueue<>(); private final ObjectArrayFIFOQueue<ChunkRenderContainer<T>> sortQueue = new ObjectArrayFIFOQueue<>(); private final ObjectArrayFIFOQueue<ChunkRenderContainer<T>> unloadQueue = new ObjectArrayFIFOQueue<>(); @SuppressWarnings("unchecked") private ChunkRenderList<T>[] chunkRenderLists = new ChunkRenderList[BlockRenderPass.COUNT]; private ObjectList<ChunkRenderContainer<T>> tickableChunks = new ObjectArrayList<>(); private ObjectList<TileEntity> visibleTileEntities = new ObjectArrayList<>(); private final SodiumWorldRenderer renderer; private final WorldClient world; private final ChunkCuller culler; private final boolean useBlockFaceCulling; private float cameraX, cameraY, cameraZ; private boolean dirty; @Getter private int submitted; private final boolean translucencySorting; @Getter private int visibleChunkCount; private boolean useFogCulling; private double fogRenderCutoff; private final int translucencyBlockRenderDistance; private boolean alwaysDeferChunkUpdates; // Iris private ChunkRenderList<T>[] chunkRenderListsSwap; private ObjectList<ChunkRenderContainer<T>> tickableChunksSwap; private ObjectList<TileEntity> visibleTileEntitiesSwap; private int visibleChunkCountSwap; private boolean dirtySwap; private static final ThreadLocal<BlockRenderPass> threadLocalRenderPass = ThreadLocal.withInitial(() -> BlockRenderPass.CUTOUT_MIPPED); public static int getWorldRenderPass() { return threadLocalRenderPass.get().ordinal(); } public static void setWorldRenderPass(BlockRenderPass pass) { threadLocalRenderPass.set(pass); } @SuppressWarnings("unchecked") public ChunkRenderManager(SodiumWorldRenderer renderer, ChunkRenderBackend<T> backend, WorldClient world, int renderDistance) { this.backend = backend; this.renderer = renderer; this.world = world; this.builder = new ChunkBuilder<>(backend.getVertexType(), this.backend); this.builder.init(world); this.dirty = true; for (int i = 0; i < this.chunkRenderLists.length; i++) { this.chunkRenderLists[i] = new ChunkRenderList<>(); } this.culler = new ChunkGraphCuller(world, renderDistance); this.translucencySorting = SodiumClientMod.options().advanced.translucencySorting; this.translucencyBlockRenderDistance = Math.min(9216, (renderDistance << 4) * (renderDistance << 4)); this.useBlockFaceCulling = SodiumClientMod.options().advanced.useBlockFaceCulling; if(Iris.enabled) { this.chunkRenderListsSwap = new ChunkRenderList[BlockRenderPass.COUNT]; this.tickableChunksSwap = new ObjectArrayList<>(); this.visibleTileEntitiesSwap = new ObjectArrayList<>(); for (int i = 0; i < this.chunkRenderListsSwap.length; i++) { this.chunkRenderListsSwap[i] = new ChunkRenderList<>(); } this.dirtySwap = true; } } public void update(Camera camera, FrustumExtended frustum, int frame, boolean spectator) { this.reset(); this.unloadPending(); this.setup(camera); this.iterateChunks(camera, frustum, frame, spectator); this.dirty = false; } public int getRebuildQueueSize() { return this.rebuildQueue.size(); } public int getImportantRebuildQueueSize() { return this.importantRebuildQueue.size(); } private void setup(Camera camera) { Vector3d cameraPos = camera.getPos(); this.cameraX = (float) cameraPos.x; this.cameraY = (float) cameraPos.y; this.cameraZ = (float) cameraPos.z; this.useFogCulling = false; this.alwaysDeferChunkUpdates = SodiumClientMod.options().performance.alwaysDeferChunkUpdates; if (SodiumClientMod.options().advanced.useFogOcclusion) { float dist = FogHelper.getFogCutoff() + FOG_PLANE_OFFSET; if (dist != 0.0f) { this.useFogCulling = true; this.fogRenderCutoff = Math.max(FOG_PLANE_MIN_DISTANCE, dist * dist); } } } private void iterateChunks(Camera camera, FrustumExtended frustum, int frame, boolean spectator) { // Schedule new translucency sorting tasks if the camera has moved if(this.translucencySorting) { this.checkTranslucencyCameraMoved(); if(this.hasCameraMovedTranslucent) { for(Object o : this.renders.getElements()) { if(o == null) continue; @SuppressWarnings("unchecked") ChunkRenderContainer<T> render = (ChunkRenderContainer<T>)o; if(render.getData().isEmpty()) continue; if(!render.needsRebuild() && render.canRebuild() && render.shouldRebuildForTranslucents() && render.getSquaredDistance(cameraX, cameraY, cameraZ) < translucencyBlockRenderDistance) { // put it at the end of the queue, after any "real" rebuild tasks render.scheduleSort(false); } } } } IntList list = this.culler.computeVisible(camera, frustum, frame, spectator); IntIterator it = list.iterator(); while (it.hasNext()) { ChunkRenderContainer<T> render = this.renders.get(it.nextInt()); this.addChunk(render); } } private float lastCameraTranslucentX, lastCameraTranslucentY, lastCameraTranslucentZ; private boolean hasCameraMovedTranslucent; private void checkTranslucencyCameraMoved() { float dx = (cameraX - lastCameraTranslucentX); float dy = (cameraY - lastCameraTranslucentY); float dz = (cameraZ - lastCameraTranslucentZ); if((dx * dx + dy * dy + dz * dz) > 1.0) { lastCameraTranslucentX = cameraX; lastCameraTranslucentY = cameraY; lastCameraTranslucentZ = cameraZ; hasCameraMovedTranslucent = true; } else hasCameraMovedTranslucent = false; } private void addChunk(ChunkRenderContainer<T> render) { boolean canRebuild = render.canRebuild(); if (Iris.enabled && ShadowRenderingState.areShadowsCurrentlyBeingRendered()) { canRebuild = false; } if (render.needsRebuild() && canRebuild) { if (!this.alwaysDeferChunkUpdates && render.needsImportantRebuild()) { this.importantRebuildQueue.enqueue(render); } else { this.rebuildQueue.enqueue(render); } } else if (canRebuild && !render.getData().isEmpty() && render.needsSort()) { this.sortQueue.enqueue(render); } if (this.useFogCulling && render.getSquaredDistanceXZ(this.cameraX, this.cameraZ) >= this.fogRenderCutoff) { return; } if (!render.isEmpty()) { this.addChunkToRenderLists(render); this.addEntitiesToRenderLists(render); } } private void addChunkToRenderLists(ChunkRenderContainer<T> render) { int visibleFaces = this.computeVisibleFaces(render) & render.getFacesWithData(); if (visibleFaces == 0) { return; } boolean added = false; T[] states = render.getGraphicsStates(); for (int i = 0; i < states.length; i++) { T state = states[i]; if (state != null) { ChunkRenderList<T> list = this.chunkRenderLists[i]; list.add(state, (this.translucencySorting && BlockRenderPass.VALUES[i].isTranslucent()) ? (ChunkFaceFlags.ALL & render.getFacesWithData()) : visibleFaces); added = true; } } if (added) { if (render.isTickable()) { this.tickableChunks.add(render); } this.visibleChunkCount++; } } private int computeVisibleFaces(ChunkRenderContainer<T> render) { if(Iris.enabled) { // TODO: Enable chunk face culling during the shadow pass if (ShadowRenderingState.areShadowsCurrentlyBeingRendered()) { return(ChunkFaceFlags.ALL); } } // If chunk face culling is disabled, render all faces if (!this.useBlockFaceCulling) { return ChunkFaceFlags.ALL; } ChunkRenderBounds bounds = render.getBounds(); // Always render groups of vertices not belonging to any given face int visibleFaces = ChunkFaceFlags.UNASSIGNED; if (this.cameraY > (bounds.y1 - 3)) { visibleFaces |= ChunkFaceFlags.UP; } if (this.cameraY < (bounds.y2 + 3)) { visibleFaces |= ChunkFaceFlags.DOWN; } if (this.cameraX > (bounds.x1 - 3)) { visibleFaces |= ChunkFaceFlags.EAST; } if (this.cameraX < (bounds.x2 + 3)) { visibleFaces |= ChunkFaceFlags.WEST; } if (this.cameraZ > (bounds.z1 - 3)) { visibleFaces |= ChunkFaceFlags.SOUTH; } if (this.cameraZ < (bounds.z2 + 3)) { visibleFaces |= ChunkFaceFlags.NORTH; } return visibleFaces; } private void addEntitiesToRenderLists(ChunkRenderContainer<T> render) { Collection<TileEntity> tileEntities = render.getData().getTileEntities(); this.visibleTileEntities.addAll(tileEntities); } public ChunkRenderContainer<T> getRender(int x, int y, int z) { ChunkRenderColumn<T> column = this.columns.get(ChunkPos.toLong(x, z)); if (column == null) { return null; } return column.getRender(y); } private void reset() { if(!Iris.enabled || !ShadowRenderingState.areShadowsCurrentlyBeingRendered()) this.rebuildQueue.clear(); if(!Iris.enabled || !ShadowRenderingState.areShadowsCurrentlyBeingRendered()) this.importantRebuildQueue.clear(); if(!Iris.enabled || !ShadowRenderingState.areShadowsCurrentlyBeingRendered()) this.sortQueue.clear(); this.visibleTileEntities.clear(); for (ChunkRenderList<T> list : this.chunkRenderLists) { list.reset(); } this.tickableChunks.clear(); this.visibleChunkCount = 0; } private void unloadPending() { while (!this.unloadQueue.isEmpty()) { this.unloadQueue.dequeue() .delete(); } } public Collection<TileEntity> getVisibleTileEntities() { return this.visibleTileEntities; } @Override public void onChunkAdded(int x, int z) { this.loadChunk(x, z); } @Override public void onChunkRemoved(int x, int z) { this.unloadChunk(x, z); } private void loadChunk(int x, int z) { ChunkRenderColumn<T> column = new ChunkRenderColumn<>(x, z); ChunkRenderColumn<T> prev; if ((prev = this.columns.put(ChunkPos.toLong(x, z), column)) != null) { this.unloadSections(prev); } this.connectNeighborColumns(column); this.loadSections(column); this.dirty = true; } private void unloadChunk(int x, int z) { ChunkRenderColumn<T> column = this.columns.remove(ChunkPos.toLong(x, z)); if (column == null) { return; } this.disconnectNeighborColumns(column); this.unloadSections(column); this.dirty = true; } private void loadSections(ChunkRenderColumn<T> column) { int x = column.getX(); int z = column.getZ(); for (int y = 0; y < 16; y++) { ChunkRenderContainer<T> render = this.createChunkRender(column, x, y, z); column.setRender(y, render); this.culler.onSectionLoaded(x, y, z, render.getId()); } } private void unloadSections(ChunkRenderColumn<T> column) { int x = column.getX(); int z = column.getZ(); for (int y = 0; y < 16; y++) { ChunkRenderContainer<T> render = column.getRender(y); if (render != null) { this.unloadQueue.enqueue(render); this.renders.remove(render.getId()); } this.culler.onSectionUnloaded(x, y, z); } } private void connectNeighborColumns(ChunkRenderColumn<T> column) { for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { ChunkRenderColumn<T> adj = this.getAdjacentColumn(column, dir); if (adj != null) { adj.setAdjacentColumn(dir.getOpposite(), column); } column.setAdjacentColumn(dir, adj); } } private void disconnectNeighborColumns(ChunkRenderColumn<T> column) { for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { ChunkRenderColumn<T> adj = column.getAdjacentColumn(dir); if (adj != null) { adj.setAdjacentColumn(dir.getOpposite(), null); } column.setAdjacentColumn(dir, null); } } private ChunkRenderColumn<T> getAdjacentColumn(ChunkRenderColumn<T> column, ForgeDirection dir) { return this.getColumn(column.getX() + dir.offsetX, column.getZ() + dir.offsetZ); } private ChunkRenderColumn<T> getColumn(int x, int z) { return this.columns.get(ChunkPos.toLong(x, z)); } private ChunkRenderContainer<T> createChunkRender(ChunkRenderColumn<T> column, int x, int y, int z) { ChunkRenderContainer<T> render = new ChunkRenderContainer<>(this.backend, this.renderer, x, y, z, column); final ExtendedBlockStorage array = this.world.getChunkFromChunkCoords(x, z).getBlockStorageArray()[y]; if (array == null || array.isEmpty()) { render.setData(ChunkRenderData.EMPTY); } else { render.scheduleRebuild(false); } render.setId(this.renders.add(render)); return render; } public void renderLayer(MatrixStack matrixStack, BlockRenderPass pass, double x, double y, double z) { final ChunkRenderList<T> chunkRenderList = this.chunkRenderLists[pass.ordinal()]; final ChunkRenderListIterator<T> iterator = chunkRenderList.iterator(pass.isTranslucent()); final RenderDevice device = RenderDevice.INSTANCE; final CommandList commandList = device.createCommandList(); if(Iris.enabled) this.backend.iris$begin(matrixStack, pass); else this.backend.begin(matrixStack); // Ensure multidraw regions are ordered appropriately if(this.backend instanceof MultidrawChunkRenderBackend) { ((MultidrawChunkRenderBackend) this.backend).setReverseRegions(pass.isTranslucent()); } this.backend.render(commandList, iterator, new ChunkCameraContext(x, y, z)); this.backend.end(matrixStack); commandList.flush(); } public void tickVisibleRenders() { for (ChunkRenderContainer<T> render : this.tickableChunks) { render.tick(); } } public boolean isChunkVisible(int x, int y, int z) { return this.culler.isSectionVisible(x, y, z); } public void updateChunks() { if (Iris.enabled && ShadowRenderingState.areShadowsCurrentlyBeingRendered()) return; this.builder.cleanupSectionCache(); Deque<CompletableFuture<ChunkBuildResult<T>>> futures = new ArrayDeque<>(); int budget = this.builder.getSchedulingBudget(); submitted = 0; while (!this.importantRebuildQueue.isEmpty()) { ChunkRenderContainer<T> render = this.importantRebuildQueue.dequeue(); if (render == null) { continue; } CompletableFuture<ChunkBuildResult<T>> futureTask = this.builder.scheduleRebuildTaskAsync(render); if (futureTask != null) { this.dirty = true; // Do not allow distant chunks to block rendering if (this.alwaysDeferChunkUpdates || !this.isChunkPrioritized(render)) { this.builder.handleCompletion(futureTask); } else { futures.add(futureTask); } submitted++; // Limit quantity of updates submitted if we are deferring all important builds if (this.alwaysDeferChunkUpdates && submitted >= budget) break; } else { // Immediately submit empty data to the queue and do not count this against the budget this.builder.enqueueUpload(new ChunkBuildResult<>(render, ChunkRenderData.EMPTY)); } } while (submitted < budget && !this.rebuildQueue.isEmpty()) { ChunkRenderContainer<T> render = this.rebuildQueue.dequeue(); CompletableFuture<ChunkBuildResult<T>> futureTask = this.builder.scheduleRebuildTaskAsync(render); if(futureTask != null) { this.builder.handleCompletion(futureTask); submitted++; } else { // Immediately submit empty data to the queue and do not count this against the budget this.builder.enqueueUpload(new ChunkBuildResult<>(render, ChunkRenderData.EMPTY)); } } // always do at least one sort boolean sortedAnything = false; while ((!sortedAnything || submitted < budget) && !this.sortQueue.isEmpty()) { ChunkRenderContainer<T> render = this.sortQueue.dequeue(); this.builder.deferSort(render); sortedAnything = true; submitted++; } WorldRenderer.chunksUpdated += submitted; this.dirty |= submitted > 0; // Try to complete some other work on the main thread while we wait for rebuilds to complete this.dirty |= this.builder.performPendingUploads(); // See if there are failed builds this.builder.handleFailures(); if (!futures.isEmpty()) { this.dirty = true; this.backend.upload(RenderDevice.INSTANCE.createCommandList(), this.builder.filterChunkBuilds(new FutureDequeDrain<>(futures))); } } public void markDirty() { this.dirty = true; } public boolean isDirty() { return this.dirty; } public void restoreChunks(LongCollection chunks) { LongIterator it = chunks.iterator(); while (it.hasNext()) { long pos = it.nextLong(); this.loadChunk(ChunkPos.getPackedX(pos), ChunkPos.getPackedZ(pos)); } } public boolean isBuildComplete() { return this.builder.isBuildQueueEmpty(); } public void setCameraPosition(double x, double y, double z) { this.builder.setCameraPosition(x, y, z); } public void destroy() { this.reset(); for (ChunkRenderColumn<T> column : this.columns.values()) { this.unloadSections(column); } this.columns.clear(); this.builder.stopWorkers(); } public int getTotalSections() { return this.columns.size() * 16; } private void scheduleRebuildOffThread(int x, int y, int z, boolean important) { AngelicaRenderQueue.executor().execute(() -> this.scheduleRebuild(x, y, z, important)); } public void scheduleRebuild(int x, int y, int z, boolean important) { // Some mods try to schedule rebuilds off the main thread. This is dangerous, // but the vanilla renderer seems to tolerate it. Our hashmaps are not thread-safe // so the best solution is to do what the server chunk system does and handle this // on the main thread. if (Thread.currentThread() != renderThread) { this.scheduleRebuildOffThread(x, y, z, important); return; } ChunkRenderContainer<T> render = this.getRender(x, y, z); if (render != null) { // Nearby chunks are always rendered immediately important = important || this.isChunkPrioritized(render); // Only enqueue chunks for updates if they aren't already enqueued for an update if (render.scheduleRebuild(important) && render.canRebuild()) { (render.needsImportantRebuild() ? this.importantRebuildQueue : this.rebuildQueue) .enqueue(render); } this.dirty = true; } this.builder.onChunkDataChanged(x, y, z); } public boolean isChunkPrioritized(ChunkRenderContainer<T> render) { return render != null ? render.getSquaredDistance(this.cameraX, this.cameraY, this.cameraZ) <= NEARBY_CHUNK_DISTANCE : false; } public void onChunkRenderUpdates(int x, int y, int z, ChunkRenderData data) { this.culler.onSectionStateChanged(x, y, z, data.getOcclusionData()); } // Iris public void iris$swapVisibilityState() { ChunkRenderList<T>[] chunkRenderListsTmp = chunkRenderLists; chunkRenderLists = chunkRenderListsSwap; chunkRenderListsSwap = chunkRenderListsTmp; ObjectList<ChunkRenderContainer<T>> tickableChunksTmp = tickableChunks; tickableChunks = tickableChunksSwap; tickableChunksSwap = tickableChunksTmp; ObjectList<TileEntity> visibleTileEntitiesTmp = visibleTileEntities; visibleTileEntities = visibleTileEntitiesSwap; visibleTileEntitiesSwap = visibleTileEntitiesTmp; int visibleChunkCountTmp = visibleChunkCount; visibleChunkCount = visibleChunkCountSwap; visibleChunkCountSwap = visibleChunkCountTmp; boolean dirtyTmp = dirty; dirty = dirtySwap; dirtySwap = dirtyTmp; } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\entity\EntityLightSampler.java
package me.jellysquid.mods.sodium.client.render.entity; import com.gtnewhorizon.gtnhlib.blockpos.BlockPos; import net.minecraft.entity.Entity; public interface EntityLightSampler<T extends Entity> { int bridge$getBlockLight(T entity, BlockPos pos); int bridge$getSkyLight(T entity, BlockPos pos); }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\occlusion\BlockOcclusionCache.java
package me.jellysquid.mods.sodium.client.render.occlusion; import com.gtnewhorizon.gtnhlib.blockpos.BlockPos; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.properties.ModelQuadFacing; import it.unimi.dsi.fastutil.objects.Object2ByteLinkedOpenHashMap; import net.minecraft.block.Block; import net.minecraft.world.IBlockAccess; public class BlockOcclusionCache { private static final byte UNCACHED_VALUE = (byte) 127; private final Object2ByteLinkedOpenHashMap<CachedOcclusionShapeTest> map; private final BlockPos cpos = new BlockPos(); public BlockOcclusionCache() { this.map = new Object2ByteLinkedOpenHashMap<>(2048, 0.5F); this.map.defaultReturnValue(UNCACHED_VALUE); } /** * @param block The block in the world * @param meta The meta value of the block * @param view The world view for this render context * @param pos The position of the block * @param facing The facing direction of the side to check * @return True if the block side facing {@param dir} is not occluded, otherwise false */ public boolean shouldDrawSide(Block block, int meta, IBlockAccess view, BlockPos pos, ModelQuadFacing facing) { if (facing == ModelQuadFacing.UNASSIGNED) return true; final BlockPos adjPos = this.cpos; adjPos.set(pos.getX() + facing.getStepX(), pos.getY() + facing.getStepY(), pos.getZ() + facing.getStepZ()); final Block adjState = view.getBlock(adjPos.x, adjPos.y, adjPos.z); return !adjState.isOpaqueCube(); // TODO: Use VoxelShape occlusion from modern } private static final class CachedOcclusionShapeTest { private Block a, b; private int hashCode; private CachedOcclusionShapeTest() { } private CachedOcclusionShapeTest(Block a, Block b, int hashCode) { this.a = a; this.b = b; this.hashCode = hashCode; } @Override public boolean equals(Object o) { if (o instanceof CachedOcclusionShapeTest that) { return this.a == that.a && this.b == that.b; } return false; } @Override public int hashCode() { return this.hashCode; } } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\pipeline\BlockRenderer.java
package me.jellysquid.mods.sodium.client.render.pipeline; import com.gtnewhorizon.gtnhlib.blockpos.BlockPos; import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator; import com.gtnewhorizon.gtnhlib.client.renderer.TessellatorManager; import com.gtnewhorizon.gtnhlib.client.renderer.cel.api.util.ColorMixer; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuadView; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuadViewMutable; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.properties.ModelQuadFacing; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.properties.ModelQuadOrientation; import com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil; import java.util.List; import net.coderbot.iris.Iris; import java.util.Random; import me.jellysquid.mods.sodium.client.SodiumClientMod; import me.jellysquid.mods.sodium.client.model.light.LightMode; import me.jellysquid.mods.sodium.client.model.light.LightPipeline; import me.jellysquid.mods.sodium.client.model.light.LightPipelineProvider; import me.jellysquid.mods.sodium.client.model.light.data.QuadLightData; import me.jellysquid.mods.sodium.client.render.chunk.compile.buffers.ChunkModelBuffers; import me.jellysquid.mods.sodium.client.render.chunk.data.ChunkRenderData; import me.jellysquid.mods.sodium.client.render.chunk.format.ModelVertexSink; import me.jellysquid.mods.sodium.client.util.rand.XoRoShiRoRandom; import net.coderbot.iris.block_rendering.BlockRenderingSettings; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.world.IBlockAccess; import net.minecraftforge.fluids.Fluid; public class BlockRenderer { private static final BlockPos POS_ZERO = new BlockPos(0, 0, 0); private final Random random = new XoRoShiRoRandom(); private final QuadLightData cachedQuadLightData = new QuadLightData(); private final boolean useAmbientOcclusion; private final boolean useSodiumAO; private boolean useSeparateAo; private final LightPipelineProvider lighters; public BlockRenderer(LightPipelineProvider lighters) { this.lighters = lighters; // TODO: Sodium - AO Setting this.useAmbientOcclusion = Minecraft.getMinecraft().gameSettings.ambientOcclusion > 0; this.useSodiumAO = SodiumClientMod.options().quality.useSodiumAO; } public boolean renderFluidLogged(IBlockAccess world, Fluid fluid, RenderBlocks renderBlocks, BlockPos pos, ChunkModelBuffers buffers, long seed) { if (fluid == null) { return false; } Block block = fluid.getBlock(); if (block == null) { return false; } boolean rendered = false; final int emitted = block.getLightValue(world, pos.x, pos.y, pos.z); try { final LightMode mode = LightMode.SMOOTH; // TODO: this.getLightingMode(block); is what was previously used. The flat pipeline is busted and was only an optimization for very few blocks. final LightPipeline lighter = this.lighters.getLighter(mode); final CapturingTessellator tess = TessellatorManager.startCapturingAndGet(); tess.startDrawingQuads(); // Use setTranslation rather than setOffset so that the float data written to the internal buffer // is done in subchunk-relative coordinates tess.setOffset(POS_ZERO); tess.setTranslation(-pos.x, -pos.y, -pos.z); renderBlocks.renderBlockByRenderType(block, pos.x, pos.y, pos.z); final var quads = TessellatorManager.stopCapturingToPooledQuads(); tess.resetOffset(); for (ModelQuadFacing facing : ModelQuadFacing.VALUES) { this.random.setSeed(seed); this.renderQuadList(pos, lighter, emitted, buffers, quads, facing, (this.useAmbientOcclusion && this.useSodiumAO)); } if (!quads.isEmpty()) rendered = true; } finally { TessellatorManager.cleanup(); } return rendered; } public boolean renderModel(IBlockAccess world, RenderBlocks renderBlocks, Block block, int meta, BlockPos pos, ChunkModelBuffers buffers, boolean cull, long seed) { final LightMode mode = LightMode.SMOOTH; // TODO: this.getLightingMode(block); is what was previously used. The flat pipeline is busted and was only an optimization for very few blocks. final LightPipeline lighter = this.lighters.getLighter(mode); boolean rendered = false; this.useSeparateAo = Iris.enabled && BlockRenderingSettings.INSTANCE.shouldUseSeparateAo(); final int emitted = block.getLightValue(world, pos.x, pos.y, pos.z); try { final CapturingTessellator tess = TessellatorManager.startCapturingAndGet(); tess.startDrawingQuads(); // Use setTranslation rather than setOffset so that the float data written to the internal buffer // is done in subchunk-relative coordinates tess.setOffset(POS_ZERO); tess.setTranslation(-pos.x, -pos.y, -pos.z); renderBlocks.renderBlockByRenderType(block, pos.x, pos.y, pos.z); final var quads = TessellatorManager.stopCapturingToPooledQuads(); tess.resetOffset(); for (ModelQuadFacing facing : ModelQuadFacing.VALUES) { this.random.setSeed(seed); this.renderQuadList(pos, lighter, emitted, buffers, quads, facing, (this.useAmbientOcclusion && this.useSodiumAO)); } if (!quads.isEmpty()) rendered = true; } finally { TessellatorManager.cleanup(); } return rendered; } private void renderQuadList(BlockPos pos, LightPipeline lighter, int emitted, ChunkModelBuffers buffers, List<ModelQuadViewMutable> quads, ModelQuadFacing facing, boolean useSodiumLight) { final ModelVertexSink sink = buffers.getSink(facing); sink.ensureCapacity(quads.size() * 4); final ChunkRenderData.Builder renderData = buffers.getRenderData(); // This is a very hot allocation, iterate over it manually // noinspection ForLoopReplaceableByForEach for (int i = 0, quadsSize = quads.size(); i < quadsSize; i++) { final var quad = quads.get(i); final QuadLightData light = this.cachedQuadLightData; if (quad.getNormalFace() != facing) continue; if (useSodiumLight || this.useSeparateAo) lighter.calculate(quad, pos, light, facing, quad.getLightFace(), quad.hasAmbientOcclusion()); this.renderQuad(sink, quad, emitted, light, renderData, useSodiumLight); } sink.flush(); } private void renderQuad(ModelVertexSink sink, ModelQuadView quad, int emitted, QuadLightData light, ChunkRenderData.Builder renderData, boolean useSodiumLight) { final ModelQuadOrientation order = (useSodiumLight || this.useSeparateAo) ? ModelQuadOrientation.orientByBrightness(light.br, light.lm) : ModelQuadOrientation.NORMAL; int shaderBlockId = quad.getShaderBlockId(); for (int dstIndex = 0; dstIndex < 4; dstIndex++) { final int srcIndex = order.getVertexIndex(dstIndex); final float x = quad.getX(srcIndex); final float y = quad.getY(srcIndex); final float z = quad.getZ(srcIndex); int color = quad.getColor(srcIndex); final float ao = light.br[srcIndex]; if (useSeparateAo) { color &= 0x00FFFFFF; color |= ((int) (ao * 255.0f)) << 24; } else { color = (useSodiumLight) ? ColorMixer.mulSingleWithoutAlpha(quad.getColor(srcIndex), (int)(light.br[srcIndex] * 255)) : quad.getColor(srcIndex); } final float u = quad.getTexU(srcIndex); final float v = quad.getTexV(srcIndex); final int lm = (useSeparateAo) ? ModelQuadUtil.mergeBakedLight(quad.getLight(srcIndex), emitted, light.lm[srcIndex]) : (useSodiumLight) ? light.lm[srcIndex] : quad.getLight(srcIndex); sink.writeQuad(x, y, z, color, u, v, lm, shaderBlockId); } final TextureAtlasSprite sprite = (TextureAtlasSprite) quad.celeritas$getSprite(); if (sprite != null) { renderData.addSprite(sprite); } } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\pipeline\ChunkRenderCache.java
package me.jellysquid.mods.sodium.client.render.pipeline; public class ChunkRenderCache { }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\pipeline\FluidRenderer.java
package me.jellysquid.mods.sodium.client.render.pipeline; import static com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.properties.ModelQuadFacing.HORIZONTAL_DIRECTIONS; import static com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.properties.ModelQuadFacing.NEG_Y; import static com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.properties.ModelQuadFacing.POS_Y; import static org.joml.Math.lerp; import com.gtnewhorizon.gtnhlib.blockpos.BlockPos; import com.gtnewhorizon.gtnhlib.client.renderer.cel.api.util.ColorARGB; import com.gtnewhorizon.gtnhlib.client.renderer.cel.api.util.ColorMixer; import com.gtnewhorizon.gtnhlib.client.renderer.cel.api.util.NormI8; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuad; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuadView; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuadViewMutable; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.properties.ModelQuadFacing; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.properties.ModelQuadFlags; import java.util.Arrays; import net.coderbot.iris.Iris; import me.jellysquid.mods.sodium.client.model.light.LightMode; import me.jellysquid.mods.sodium.client.model.light.LightPipeline; import me.jellysquid.mods.sodium.client.model.light.LightPipelineProvider; import me.jellysquid.mods.sodium.client.model.light.data.QuadLightData; import me.jellysquid.mods.sodium.client.render.chunk.compile.buffers.ChunkModelBuffers; import me.jellysquid.mods.sodium.client.render.chunk.format.ModelVertexSink; import me.jellysquid.mods.sodium.client.world.WorldSlice; import net.coderbot.iris.block_rendering.BlockRenderingSettings; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.util.MathHelper; import net.minecraft.world.IBlockAccess; import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.fluids.Fluid; import org.joml.Vector3d; public class FluidRenderer { private static final float EPSILON = 0.001f; private final LightPipelineProvider lpp; private final BlockPos scratchPos = new BlockPos(); private final ModelQuadViewMutable quad = new ModelQuad(); private final QuadLightData quadLightData = new QuadLightData(); private boolean useSeparateAo; private final int[] quadColors = new int[4]; private final int[] biomeColors = new int[4]; private final TextureAtlasSprite missingTex = Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite("minecraft:missing"); public FluidRenderer(LightPipelineProvider lpp) { int normal = NormI8.pack(0.0f, 1.0f, 0.0f); for (int i = 0; i < 4; i++) { this.quad.setForgeNormal(i, normal); } this.lpp = lpp; } private boolean isFluidOccluded(IBlockAccess world, int x, int y, int z, ForgeDirection d, Fluid fluid) { Block block = world.getBlock(x, y, z); boolean tmp = WorldUtil.getFluid(world.getBlock(x + d.offsetX, y + d.offsetY, z + d.offsetZ)) == fluid; if (block.getMaterial().isOpaque()) { return tmp || block.isSideSolid(world, x, y, z, d); // fluidlogged or next to water, occlude sides that are solid or the same liquid // For a liquid block that's always } return tmp; } private boolean isSideExposed(IBlockAccess world, int x, int y, int z, ModelQuadFacing dir, float height) { BlockPos pos = this.scratchPos.set(x + dir.getStepX(), y + dir.getStepY(), z + dir.getStepZ()); Block block = world.getBlock(pos.x, pos.y, pos.z); if (block.getMaterial().isOpaque()) { final boolean renderAsFullCube = block.renderAsNormalBlock(); // Hoist these checks to avoid allocating the shape below if (renderAsFullCube) { // The top face always be inset, so if the shape above is a full cube it can't possibly occlude return dir == POS_Y; } else { return true; } } return true; } public boolean render(IBlockAccess world, WorldSlice slice, Block block, BlockPos pos, ChunkModelBuffers buffers) { this.useSeparateAo = Iris.enabled && BlockRenderingSettings.INSTANCE.shouldUseSeparateAo(); int posX = pos.x; int posY = pos.y; int posZ = pos.z; Fluid fluid = WorldUtil.getFluid(block); if (fluid == null) return false; // Check for occluded sides; if everything is occluded, don't render boolean sfUp = this.isFluidOccluded(world, posX, posY, posZ, ForgeDirection.UP, fluid); boolean sfDown = this.isFluidOccluded(world, posX, posY, posZ, ForgeDirection.DOWN, fluid) || !this.isSideExposed(world, posX, posY, posZ, NEG_Y, 0.8888889F); boolean sfNorth = this.isFluidOccluded(world, posX, posY, posZ, ForgeDirection.NORTH, fluid); boolean sfSouth = this.isFluidOccluded(world, posX, posY, posZ, ForgeDirection.SOUTH, fluid); boolean sfWest = this.isFluidOccluded(world, posX, posY, posZ, ForgeDirection.WEST, fluid); boolean sfEast = this.isFluidOccluded(world, posX, posY, posZ, ForgeDirection.EAST, fluid); if (sfUp && sfDown && sfEast && sfWest && sfNorth && sfSouth) { return false; } // sprites[0] should be the still frames, [1] the flowing, [2] the overlay // Sides 0 and 1 (top and bottom) are still, 2+ flowing. Overlay is null because 1.7.10 probably doesn't use it. TextureAtlasSprite[] sprites = new TextureAtlasSprite[]{ (TextureAtlasSprite) fluid.getStillIcon(), (TextureAtlasSprite) fluid.getFlowingIcon(), null }; // Because some mods are wack and return null textures here sprites[0] = sprites[0] == null ? missingTex : sprites[0]; sprites[1] = sprites[1] == null ? missingTex : sprites[1]; boolean hc = fluid.getColor() != 0xffffffff; boolean rendered = false; float h1 = this.getCornerHeight(world, posX, posY, posZ, fluid); float h2 = this.getCornerHeight(world, posX, posY, posZ + 1, fluid); float h3 = this.getCornerHeight(world, posX + 1, posY, posZ + 1, fluid); float h4 = this.getCornerHeight(world, posX + 1, posY, posZ, fluid); float yOffset = sfDown ? 0.0F : EPSILON; final ModelQuadViewMutable quad = this.quad; LightMode mode = hc && Minecraft.isAmbientOcclusionEnabled() ? LightMode.SMOOTH : LightMode.FLAT; LightPipeline lighter = this.lpp.getLighter(mode); quad.setFlags(0); if (!sfUp && this.isSideExposed(world, posX, posY, posZ, POS_Y, Math.min(Math.min(h1, h2), Math.min(h3, h4)))) { h1 -= 0.001F; h2 -= 0.001F; h3 -= 0.001F; h4 -= 0.001F; Vector3d velocity = WorldUtil.getVelocity(world, pos.x, pos.y, pos.z, block); TextureAtlasSprite sprite; ModelQuadFacing facing; float u1, u2, u3, u4; float v1, v2, v3, v4; if (velocity.x == 0.0D && velocity.z == 0.0D) { sprite = sprites[0]; facing = ModelQuadFacing.POS_Y; u1 = sprite.getInterpolatedU(0.0D); v1 = sprite.getInterpolatedV(0.0D); u2 = u1; v2 = sprite.getInterpolatedV(16.0D); u3 = sprite.getInterpolatedU(16.0D); v3 = v2; u4 = u3; v4 = v1; } else { sprite = sprites[1]; facing = ModelQuadFacing.UNASSIGNED; float dir = (float) Math.atan2(velocity.z, velocity.x) - (((float)Math.PI / 2F)); float sin = MathHelper.sin(dir) * 0.25F; float cos = MathHelper.cos(dir) * 0.25F; u1 = sprite.getInterpolatedU(8.0F + (-cos - sin) * 16.0F); v1 = sprite.getInterpolatedV(8.0F + (-cos + sin) * 16.0F); u2 = sprite.getInterpolatedU(8.0F + (-cos + sin) * 16.0F); v2 = sprite.getInterpolatedV(8.0F + (cos + sin) * 16.0F); u3 = sprite.getInterpolatedU(8.0F + (cos + sin) * 16.0F); v3 = sprite.getInterpolatedV(8.0F + (cos - sin) * 16.0F); u4 = sprite.getInterpolatedU(8.0F + (cos - sin) * 16.0F); v4 = sprite.getInterpolatedV(8.0F + (-cos - sin) * 16.0F); } float uAvg = (u1 + u2 + u3 + u4) / 4.0F; float vAvg = (v1 + v2 + v3 + v4) / 4.0F; float s1 = (float) sprites[0].getIconWidth() / (sprites[0].getMaxU() - sprites[0].getMinU()); float s2 = (float) sprites[0].getIconHeight() / (sprites[0].getMaxV() - sprites[0].getMinV()); float s3 = 4.0F / Math.max(s2, s1); u1 = lerp(u1, uAvg, s3); u2 = lerp(u2, uAvg, s3); u3 = lerp(u3, uAvg, s3); u4 = lerp(u4, uAvg, s3); v1 = lerp(v1, vAvg, s3); v2 = lerp(v2, vAvg, s3); v3 = lerp(v3, vAvg, s3); v4 = lerp(v4, vAvg, s3); quad.setSprite(sprite); this.setVertex(quad, 0, 0.0f, h1, 0.0f, u1, v1); this.setVertex(quad, 1, 0.0f, h2, 1.0F, u2, v2); this.setVertex(quad, 2, 1.0F, h3, 1.0F, u3, v3); this.setVertex(quad, 3, 1.0F, h4, 0.0f, u4, v4); this.calculateQuadColors(quad, pos, lighter, POS_Y, 1.0F, hc, slice); this.flushQuad(buffers, quad, facing, false); if (WorldUtil.method_15756(slice, this.scratchPos.set(posX, posY + 1, posZ), fluid)) { this.setVertex(quad, 3, 0.0f, h1, 0.0f, u1, v1); this.setVertex(quad, 2, 0.0f, h2, 1.0F, u2, v2); this.setVertex(quad, 1, 1.0F, h3, 1.0F, u3, v3); this.setVertex(quad, 0, 1.0F, h4, 0.0f, u4, v4); this.flushQuad(buffers, quad, ModelQuadFacing.NEG_Y, true); } rendered = true; } if (!sfDown) { TextureAtlasSprite sprite = sprites[0]; float minU = sprite.getMinU(); float maxU = sprite.getMaxU(); float minV = sprite.getMinV(); float maxV = sprite.getMaxV(); quad.setSprite(sprite); this.setVertex(quad, 0, 0.0f, yOffset, 1.0F, minU, maxV); this.setVertex(quad, 1, 0.0f, yOffset, 0.0f, minU, minV); this.setVertex(quad, 2, 1.0F, yOffset, 0.0f, maxU, minV); this.setVertex(quad, 3, 1.0F, yOffset, 1.0F, maxU, maxV); this.calculateQuadColors(quad, pos, lighter, NEG_Y, 1.0F, hc, slice); this.flushQuad(buffers, quad, ModelQuadFacing.NEG_Y, false); rendered = true; } quad.setFlags(ModelQuadFlags.IS_ALIGNED); for (var facing : HORIZONTAL_DIRECTIONS) { float c1; float c2; float x1; float z1; float x2; float z2; switch (facing) { case NEG_Z: if (sfNorth) { continue; } c1 = h1; c2 = h4; x1 = 0.0f; x2 = 1.0F; z1 = 0.001f; z2 = z1; break; case POS_Z: if (sfSouth) { continue; } c1 = h3; c2 = h2; x1 = 1.0F; x2 = 0.0f; z1 = 0.999f; z2 = z1; break; case NEG_X: if (sfWest) { continue; } c1 = h2; c2 = h1; x1 = 0.001f; x2 = x1; z1 = 1.0F; z2 = 0.0f; break; case POS_X: if (sfEast) { continue; } c1 = h4; c2 = h3; x1 = 0.999f; x2 = x1; z1 = 0.0f; z2 = 1.0F; break; default: continue; } if (this.isSideExposed(world, posX, posY, posZ, facing, Math.max(c1, c2))) { int adjX = posX + facing.getStepX(); int adjY = posY + facing.getStepY(); int adjZ = posZ + facing.getStepZ(); TextureAtlasSprite sprite = sprites[1]; TextureAtlasSprite oSprite = sprites[2]; if (oSprite != null) { Block adjBlock = world.getBlock(adjX, adjY, adjZ); if (WorldUtil.shouldDisplayFluidOverlay(adjBlock)) { // should ignore invisible blocks, barriers, light blocks // use static water when adjacent block is ice, glass, stained glass, tinted glass sprite = oSprite; } } float u1 = sprite.getInterpolatedU(0.0D); float u2 = sprite.getInterpolatedU(8.0D); float v1 = sprite.getInterpolatedV((1.0F - c1) * 16.0F * 0.5F); float v2 = sprite.getInterpolatedV((1.0F - c2) * 16.0F * 0.5F); float v3 = sprite.getInterpolatedV(8.0D); quad.setSprite(sprite); this.setVertex(quad, 0, x2, c2, z2, u2, v2); this.setVertex(quad, 1, x2, yOffset, z2, u2, v3); this.setVertex(quad, 2, x1, yOffset, z1, u1, v3); this.setVertex(quad, 3, x1, c1, z1, u1, v1); float br = facing.getStepZ() != 0 ? 0.8F : 0.6F; this.calculateQuadColors(quad, pos, lighter, facing, br, hc, slice); this.flushQuad(buffers, quad, facing, false); if (sprite != oSprite) { this.setVertex(quad, 0, x1, c1, z1, u1, v1); this.setVertex(quad, 1, x1, yOffset, z1, u1, v3); this.setVertex(quad, 2, x2, yOffset, z2, u2, v3); this.setVertex(quad, 3, x2, c2, z2, u2, v2); this.flushQuad(buffers, quad, facing.getOpposite(), true); } rendered = true; } } return rendered; } private void calculateQuadColors(ModelQuadView quad, BlockPos pos, LightPipeline lighter, ModelQuadFacing dir, float brightness, boolean colorized, WorldSlice slice) { QuadLightData light = this.quadLightData; lighter.calculate(quad, pos, light, null, dir, false); if (colorized) { int color = slice.getBlock(pos.x,pos.y,pos.z).colorMultiplier(slice,pos.x,pos.y,pos.z); Arrays.fill(this.biomeColors, ColorARGB.toABGR(color)); } for (int i = 0; i < 4; i++) { int color = colorized ? biomeColors[i] : 0xFFFFFFFF; final float ao = light.br[i] * brightness; if (useSeparateAo) { color &= 0x00FFFFFF; color |= ((int) (ao * 255.0f)) << 24; } else { color = ColorMixer.mulSingleWithoutAlpha(color, (int)(ao * 255)); } this.quadColors[i] = color; } } private void flushQuad(ChunkModelBuffers buffers, ModelQuadView quad, ModelQuadFacing facing, boolean flip) { int vertexIdx, lightOrder; if (flip) { vertexIdx = 3; lightOrder = -1; } else { vertexIdx = 0; lightOrder = 1; } ModelVertexSink sink = buffers.getSink(facing); sink.ensureCapacity(4); for (int i = 0; i < 4; i++) { float x = quad.getX(i); float y = quad.getY(i); float z = quad.getZ(i); int color = this.quadColors[vertexIdx]; float u = quad.getTexU(i); float v = quad.getTexV(i); int light = this.quadLightData.lm[vertexIdx]; sink.writeQuad(x, y, z, color, u, v, light, -1); vertexIdx += lightOrder; } TextureAtlasSprite sprite = (TextureAtlasSprite) quad.celeritas$getSprite(); if (sprite != null) { buffers.getRenderData().addSprite(sprite); } sink.flush(); } private void setVertex(ModelQuadViewMutable quad, int i, float x, float y, float z, float u, float v) { quad.setX(i, x); quad.setY(i, y); quad.setZ(i, z); quad.setTexU(i, u); quad.setTexV(i, v); } private float getCornerHeight(IBlockAccess world, int x, int y, int z, Fluid fluid) { int samples = 0; float totalHeight = 0.0F; for (int i = 0; i < 4; ++i) { int x2 = x - (i & 1); int z2 = z - (i >> 1 & 1); Block block = world.getBlock(x2, y + 1, z2); if (WorldUtil.getFluid(block) == fluid) { return 1.0F; } BlockPos pos = this.scratchPos.set(x2, y, z2); block = world.getBlock(pos.x, pos.y, pos.z); int meta = world.getBlockMetadata(pos.x, pos.y, pos.z); Fluid fluid2 = WorldUtil.getFluid(block); if (fluid2 == fluid) { float height = WorldUtil.getFluidHeight(fluid2, meta); if (height >= 0.8F) { totalHeight += height * 10.0F; samples += 10; } else { totalHeight += height; ++samples; } } else if (!block.getMaterial().isSolid()) { ++samples; } } return totalHeight / (float) samples; } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\pipeline\WorldUtil.java
package me.jellysquid.mods.sodium.client.render.pipeline; import com.gtnewhorizon.gtnhlib.blockpos.BlockPos; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.properties.ModelQuadFacing; import net.minecraft.block.Block; import net.minecraft.block.BlockLiquid; import net.minecraft.block.material.Material; import net.minecraft.world.IBlockAccess; import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.IFluidBlock; import org.joml.Vector3d; /** * Contains methods stripped from BlockState or FluidState that didn't actually need to be there. Technically these * could be a mixin to Block or Fluid, but that's annoying while not actually providing any benefit. */ public class WorldUtil { public static Vector3d getVelocity(IBlockAccess world, int x, int y, int z, Block thizz) { Vector3d velocity = new Vector3d(); int decay = getEffectiveFlowDecay(world, x, y, z, thizz); for (var dire : ModelQuadFacing.HORIZONTAL_DIRECTIONS) { int adjX = x + dire.getStepX(); int adjZ = z + dire.getStepZ(); int adjDecay = getEffectiveFlowDecay(world, adjX, y, adjZ, thizz); if (adjDecay < 0) { if (!world.getBlock(adjX, y, adjZ).getMaterial().blocksMovement()) { adjDecay = getEffectiveFlowDecay(world, adjX, y - 1, adjZ, thizz); if (adjDecay >= 0) { adjDecay -= (decay - 8); velocity = velocity.add((adjX - x) * adjDecay, 0, (adjZ - z) * adjDecay); } } } else { adjDecay -= decay; velocity = velocity.add((adjX - x) * adjDecay, 0, (adjZ - z) * adjDecay); } } if (world.getBlockMetadata(x, y, z) >= 8) { if (thizz.isBlockSolid(world, x, y, z - 1, 2) || thizz.isBlockSolid(world, x, y, z + 1, 3) || thizz.isBlockSolid(world, x - 1, y, z, 4) || thizz.isBlockSolid(world, x + 1, y, z, 5) || thizz.isBlockSolid(world, x, y + 1, z - 1, 2) || thizz.isBlockSolid(world, x, y + 1, z + 1, 3) || thizz.isBlockSolid(world, x - 1, y + 1, z, 4) || thizz.isBlockSolid(world, x + 1, y + 1, z, 5)) { velocity = velocity.normalize().add(0.0D, -6.0D, 0.0D); } } if (velocity.x == 0 && velocity.y == 0 && velocity.z == 0) return velocity.zero(); return velocity.normalize(); } /** * Returns true if any block in a 3x3x3 cube is not the same fluid and not an opaque full cube. Equivalent to * FluidState::method_15756 in modern. */ public static boolean method_15756(IBlockAccess world, BlockPos pos, Fluid fluid) { for (int i = 0; i < 2; ++i) { for (int j = 0; j < 2; ++j) { Block block = world.getBlock(pos.x, pos.y, pos.z); if (!block.isOpaqueCube() && getFluid(block) != fluid) { return true; } } } return false; } /** * Returns fluid height as a percentage of the block; 0 is none and 1 is full. */ public static float getFluidHeight(Fluid fluid, int meta) { return fluid == null ? 0 : 1 - BlockLiquid.getLiquidHeightPercent(meta); } /** * Returns the flow decay but converts values indicating falling liquid (values >=8) to their effective source block * value of zero */ public static int getEffectiveFlowDecay(IBlockAccess world, int x, int y, int z, Block thiz) { if (world.getBlock(x, y, z).getMaterial() != thiz.getMaterial()) { return -1; } else { int decay = world.getBlockMetadata(x, y, z); return decay >= 8 ? 0 : decay; } } // I believe forge mappings in modern say BreakableBlock, while yarn says TransparentBlock. // I have a sneaking suspicion isOpaque is neither, but it works for now public static boolean shouldDisplayFluidOverlay(Block block) { return !block.getMaterial().isOpaque() || block.getMaterial() == Material.leaves; } public static boolean isFluidBlock(Block block) { return block instanceof IFluidBlock || block instanceof BlockLiquid; } public static Fluid getFluid(Block b) { if (b instanceof IFluidBlock fluidBlock) return fluidBlock.getFluid(); if (b instanceof BlockLiquid) { if (b.getMaterial() == Material.water) return FluidRegistry.WATER; if (b.getMaterial() == Material.lava) return FluidRegistry.LAVA; } return null; } /** * Equivalent to method_15748 in 1.16.5 */ public static boolean isEmptyOrSame(Fluid fluid, Fluid otherFluid) { return otherFluid == null || fluid == otherFluid; } /** * Equivalent to method_15749 in 1.16.5 */ public static boolean method_15749(IBlockAccess world, Fluid thiz, BlockPos pos, ForgeDirection dir) { Block b = world.getBlock(pos.x, pos.y, pos.z); Fluid f = getFluid(b); if (f == thiz) { return false; } if (dir == ForgeDirection.UP) { return true; } return b.getMaterial() != Material.ice && b.isSideSolid(world, pos.x, pos.y, pos.z, dir); } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\compile\ChunkBufferSorter.java
package me.jellysquid.mods.sodium.client.render.chunk.compile; import com.google.common.primitives.Floats; import it.unimi.dsi.fastutil.ints.IntArrays; import me.jellysquid.mods.sodium.client.model.vertex.type.ChunkVertexType; import me.jellysquid.mods.sodium.client.render.chunk.format.hfp.HFPModelVertexType; import me.jellysquid.mods.sodium.client.render.chunk.format.sfp.SFPModelVertexType; import net.coderbot.iris.sodium.vertex_format.terrain_xhfp.XHFPModelVertexType; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.FloatBuffer; import java.nio.ShortBuffer; import java.util.BitSet; public class ChunkBufferSorter { public static void sortStandardFormat(ChunkVertexType vertexType, ByteBuffer buffer, int bufferLen, float x, float y, float z) { boolean isCompact; if(vertexType.getClass() == HFPModelVertexType.class || vertexType.getClass() == XHFPModelVertexType.class) { isCompact = true; } else if(vertexType.getClass() == SFPModelVertexType.class) { isCompact = false; } else return; // ignore unsupported vertex types to avoid corruption // Quad stride by Float size int quadStride = vertexType.getBufferVertexFormat().getStride(); int quadStart = ((Buffer)buffer).position(); int quadCount = bufferLen/quadStride/4; float[] distanceArray = new float[quadCount]; int[] indicesArray = new int[quadCount]; if(isCompact) { ShortBuffer shortBuffer = buffer.asShortBuffer(); int vertexSizeShort = quadStride / 2; for (int quadIdx = 0; quadIdx < quadCount; ++quadIdx) { distanceArray[quadIdx] = getDistanceSqHFP(shortBuffer, x, y, z, vertexSizeShort, quadStart + (quadIdx * quadStride * 2)); indicesArray[quadIdx] = quadIdx; } } else { FloatBuffer floatBuffer = buffer.asFloatBuffer(); int vertexSizeInteger = quadStride / 4; for (int quadIdx = 0; quadIdx < quadCount; ++quadIdx) { distanceArray[quadIdx] = getDistanceSqSFP(floatBuffer, x, y, z, vertexSizeInteger, quadStart + (quadIdx * quadStride)); indicesArray[quadIdx] = quadIdx; } } IntArrays.mergeSort(indicesArray, (a, b) -> Floats.compare(distanceArray[b], distanceArray[a])); rearrangeQuads(buffer, indicesArray, quadStride, quadStart); } private static void rearrangeQuads(ByteBuffer quadBuffer, int[] indicesArray, int quadStride, int quadStart) { FloatBuffer floatBuffer = quadBuffer.asFloatBuffer(); BitSet bits = new BitSet(); FloatBuffer tmp = FloatBuffer.allocate(quadStride); for (int l = bits.nextClearBit(0); l < indicesArray.length; l = bits.nextClearBit(l + 1)) { int m = indicesArray[l]; if (m != l) { sliceQuad(floatBuffer, m, quadStride, quadStart); ((Buffer)tmp).clear(); tmp.put(floatBuffer); int n = m; for (int o = indicesArray[m]; n != l; o = indicesArray[o]) { sliceQuad(floatBuffer, o, quadStride, quadStart); FloatBuffer floatBuffer3 = floatBuffer.slice(); sliceQuad(floatBuffer, n, quadStride, quadStart); floatBuffer.put(floatBuffer3); bits.set(n); n = o; } sliceQuad(floatBuffer, l, quadStride, quadStart); ((Buffer)tmp).flip(); floatBuffer.put(tmp); } bits.set(l); } } private static void sliceQuad(FloatBuffer floatBuffer, int quadIdx, int quadStride, int quadStart) { int base = quadStart + (quadIdx * quadStride); ((Buffer)floatBuffer).limit(base + quadStride); ((Buffer)floatBuffer).position(base); } private static float getDistanceSqSFP(FloatBuffer buffer, float xCenter, float yCenter, float zCenter, int stride, int start) { int vertexBase = start; float x1 = buffer.get(vertexBase); float y1 = buffer.get(vertexBase + 1); float z1 = buffer.get(vertexBase + 2); //System.out.println("camera: " + xCenter + "," + yCenter + "," + zCenter); //System.out.println("buffer1: " + x1 + "," + y1 + "," + z1); vertexBase += stride; float x2 = buffer.get(vertexBase); float y2 = buffer.get(vertexBase + 1); float z2 = buffer.get(vertexBase + 2); //System.out.println("buffer2: " + x2 + "," + y2 + "," + z2); vertexBase += stride; float x3 = buffer.get(vertexBase); float y3 = buffer.get(vertexBase + 1); float z3 = buffer.get(vertexBase + 2); //System.out.println("buffer3: " + x3 + "," + y3 + "," + z3); vertexBase += stride; float x4 = buffer.get(vertexBase); float y4 = buffer.get(vertexBase + 1); float z4 = buffer.get(vertexBase + 2); //System.out.println("buffer4: " + x4 + "," + y4 + "," + z4); float xDist = ((x1 + x2 + x3 + x4) * 0.25F) - xCenter; float yDist = ((y1 + y2 + y3 + y4) * 0.25F) - yCenter; float zDist = ((z1 + z2 + z3 + z4) * 0.25F) - zCenter; return (xDist * xDist) + (yDist * yDist) + (zDist * zDist); } private static float normalizeShort(short s) { return (float)Short.toUnsignedInt(s) / 2048.0f; } private static float getDistanceSqHFP(ShortBuffer buffer, float xCenter, float yCenter, float zCenter, int stride, int start) { int vertexBase = start; float x1 = normalizeShort(buffer.get(vertexBase)); float y1 = normalizeShort(buffer.get(vertexBase + 1)); float z1 = normalizeShort(buffer.get(vertexBase + 2)); //System.out.println("camera: " + xCenter + "," + yCenter + "," + zCenter); //System.out.println("buffer1: " + x1 + "," + y1 + "," + z1); vertexBase += stride; float x2 = normalizeShort(buffer.get(vertexBase)); float y2 = normalizeShort(buffer.get(vertexBase + 1)); float z2 = normalizeShort(buffer.get(vertexBase + 2)); //System.out.println("buffer2: " + x2 + "," + y2 + "," + z2); vertexBase += stride; float x3 = normalizeShort(buffer.get(vertexBase)); float y3 = normalizeShort(buffer.get(vertexBase + 1)); float z3 = normalizeShort(buffer.get(vertexBase + 2)); //System.out.println("buffer3: " + x3 + "," + y3 + "," + z3); vertexBase += stride; float x4 = normalizeShort(buffer.get(vertexBase)); float y4 = normalizeShort(buffer.get(vertexBase + 1)); float z4 = normalizeShort(buffer.get(vertexBase + 2)); //System.out.println("buffer4: " + x4 + "," + y4 + "," + z4); float xDist = ((x1 + x2 + x3 + x4) * 0.25F) - xCenter; float yDist = ((y1 + y2 + y3 + y4) * 0.25F) - yCenter; float zDist = ((z1 + z2 + z3 + z4) * 0.25F) - zCenter; return (xDist * xDist) + (yDist * yDist) + (zDist * zDist); } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\compile\ChunkBuildBuffers.java
package me.jellysquid.mods.sodium.client.render.chunk.compile; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.properties.ModelQuadFacing; import it.unimi.dsi.fastutil.objects.Object2IntMap; import net.coderbot.iris.Iris; import java.nio.ByteBuffer; import java.util.Map; import lombok.Getter; import me.jellysquid.mods.sodium.client.SodiumClientMod; import me.jellysquid.mods.sodium.client.gl.buffer.VertexData; import me.jellysquid.mods.sodium.client.gl.util.BufferSlice; import me.jellysquid.mods.sodium.client.model.vertex.buffer.VertexBufferBuilder; import me.jellysquid.mods.sodium.client.model.vertex.type.ChunkVertexType; import me.jellysquid.mods.sodium.client.render.chunk.compile.buffers.BakedChunkModelBuffers; import me.jellysquid.mods.sodium.client.render.chunk.compile.buffers.ChunkModelBuffers; import me.jellysquid.mods.sodium.client.render.chunk.compile.buffers.ChunkModelVertexTransformer; import me.jellysquid.mods.sodium.client.render.chunk.data.ChunkMeshData; import me.jellysquid.mods.sodium.client.render.chunk.data.ChunkRenderData; import me.jellysquid.mods.sodium.client.render.chunk.format.ChunkModelOffset; import me.jellysquid.mods.sodium.client.render.chunk.format.ModelVertexSink; import me.jellysquid.mods.sodium.client.render.chunk.passes.BlockRenderPass; import net.coderbot.iris.block_rendering.BlockRenderingSettings; import net.coderbot.iris.sodium.block_context.BlockContextHolder; import net.coderbot.iris.sodium.block_context.ChunkBuildBuffersExt; import net.coderbot.iris.sodium.block_context.ContextAwareVertexWriter; import net.minecraft.block.Block; import org.lwjgl.BufferUtils; /** * A collection of temporary buffers for each worker thread which will be used to build chunk meshes for given render * passes. This makes a best-effort attempt to pick a suitable size for each scratch buffer, but will never try to * shrink a buffer. */ public class ChunkBuildBuffers implements ChunkBuildBuffersExt { private final ChunkModelBuffers[] delegates; private final VertexBufferBuilder[][] buffersByLayer; @Getter private final ChunkVertexType vertexType; private final ChunkModelOffset offset; private BlockContextHolder iris$contextHolder; public ChunkBuildBuffers(ChunkVertexType vertexType) { this.vertexType = vertexType; this.delegates = new ChunkModelBuffers[BlockRenderPass.COUNT]; this.buffersByLayer = new VertexBufferBuilder[BlockRenderPass.COUNT][ModelQuadFacing.COUNT]; this.offset = new ChunkModelOffset(); for (BlockRenderPass pass : BlockRenderPass.VALUES) { final int passId = pass.ordinal(); final VertexBufferBuilder[] buffers = this.buffersByLayer[passId]; for (ModelQuadFacing facing : ModelQuadFacing.VALUES) { buffers[facing.ordinal()] = new VertexBufferBuilder(vertexType.getBufferVertexFormat(), pass.bufferSize() / ModelQuadFacing.COUNT); } } if(Iris.enabled) { final Object2IntMap<Block> blockMatches = BlockRenderingSettings.INSTANCE.getBlockMatches(); if (blockMatches != null) { this.iris$contextHolder = new BlockContextHolder(blockMatches); } else { this.iris$contextHolder = new BlockContextHolder(); } } } public void init(ChunkRenderData.Builder renderData) { for (int i = 0; i < this.buffersByLayer.length; i++) { ChunkModelVertexTransformer[] writers = new ChunkModelVertexTransformer[ModelQuadFacing.COUNT]; for (ModelQuadFacing facing : ModelQuadFacing.VALUES) { final ModelVertexSink sink = this.vertexType.createBufferWriter(this.buffersByLayer[i][facing.ordinal()], SodiumClientMod.isDirectMemoryAccessEnabled()); if (Iris.enabled && sink instanceof ContextAwareVertexWriter) { ((ContextAwareVertexWriter) sink).iris$setContextHolder(iris$contextHolder); } writers[facing.ordinal()] = new ChunkModelVertexTransformer(sink, this.offset); } this.delegates[i] = new BakedChunkModelBuffers(writers, renderData); } } /** * Return the {@link ChunkModelVertexTransformer} for the given {@link BlockRenderPass} as mapped by the * {@link BlockRenderPassManager} for this render context. */ public ChunkModelBuffers get(BlockRenderPass pass) { return this.delegates[pass.ordinal()]; } /** * Creates immutable baked chunk meshes from all non-empty scratch buffers and resets the state of all mesh * builders. This is used after all blocks have been rendered to pass the finished meshes over to the graphics card. */ public ChunkMeshData createMesh(BlockRenderPass pass, float x, float y, float z, boolean sortTranslucent) { VertexBufferBuilder[] builders = this.buffersByLayer[pass.ordinal()]; ChunkMeshData meshData = null; int bufferLen = 0; for (int facingId = 0; facingId < builders.length; facingId++) { VertexBufferBuilder builder = builders[facingId]; if (builder == null || builder.isEmpty()) { continue; } int start = bufferLen; int size = builder.getSize(); if(meshData == null) { meshData = new ChunkMeshData(); } meshData.setModelSlice(ModelQuadFacing.VALUES[facingId], new BufferSlice(start, size)); bufferLen += size; } if (bufferLen <= 0) { return null; } ByteBuffer buffer = BufferUtils.createByteBuffer(bufferLen); for (Map.Entry<ModelQuadFacing, BufferSlice> entry : meshData.getSlices()) { BufferSlice slice = entry.getValue(); buffer.position(slice.start); VertexBufferBuilder builder = this.buffersByLayer[pass.ordinal()][entry.getKey().ordinal()]; builder.copyInto(buffer); } buffer.flip(); if (sortTranslucent && pass.isTranslucent()) { ChunkBufferSorter.sortStandardFormat(vertexType, buffer, bufferLen, x, y, z); meshData.clearSlices(); meshData.setModelSlice(ModelQuadFacing.UNASSIGNED, new BufferSlice(0, bufferLen)); } meshData.setVertexData(new VertexData(buffer, this.vertexType.getCustomVertexFormat())); return meshData; } public void setRenderOffset(int x, int y, int z) { this.offset.set(x, y, z); } // Iris Compat public void iris$setLocalPos(int localPosX, int localPosY, int localPosZ) { if(!Iris.enabled) return; this.iris$contextHolder.setLocalPos(localPosX, localPosY, localPosZ); } public void iris$setMaterialId(Block block, short renderType) { if(!Iris.enabled) return; this.iris$contextHolder.set(block, renderType); } public void iris$resetBlockContext() { if(!Iris.enabled) return; this.iris$contextHolder.reset(); } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\compile\ChunkBuilder.java
package me.jellysquid.mods.sodium.client.render.chunk.compile; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.rendering.AngelicaRenderQueue; import it.unimi.dsi.fastutil.objects.Reference2ReferenceLinkedOpenHashMap; import me.jellysquid.mods.sodium.client.SodiumClientMod; import me.jellysquid.mods.sodium.client.gl.device.RenderDevice; import me.jellysquid.mods.sodium.client.model.vertex.type.ChunkVertexType; import me.jellysquid.mods.sodium.client.render.chunk.ChunkGraphicsState; import me.jellysquid.mods.sodium.client.render.chunk.ChunkRenderBackend; import me.jellysquid.mods.sodium.client.render.chunk.ChunkRenderContainer; import me.jellysquid.mods.sodium.client.render.chunk.tasks.ChunkRenderBuildTask; import me.jellysquid.mods.sodium.client.render.chunk.tasks.ChunkRenderRebuildTask; import me.jellysquid.mods.sodium.client.render.chunk.tasks.ChunkRenderTranslucencySortTask; import me.jellysquid.mods.sodium.client.render.pipeline.context.ChunkRenderCacheLocal; import me.jellysquid.mods.sodium.client.util.task.CancellationSource; import me.jellysquid.mods.sodium.client.world.WorldSlice; import me.jellysquid.mods.sodium.client.world.cloned.ChunkRenderContext; import me.jellysquid.mods.sodium.client.world.cloned.ClonedChunkSectionCache; import me.jellysquid.mods.sodium.common.util.collections.DequeDrain; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.WorldClient; import net.minecraft.util.MathHelper; import net.minecraft.util.ReportedException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.joml.Vector3d; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Deque; import java.util.Iterator; import java.util.List; import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentLinkedDeque; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.LockSupport; public class ChunkBuilder<T extends ChunkGraphicsState> { /** * The maximum number of jobs that can be queued for a given worker thread. */ private static final int TASK_QUEUE_LIMIT_PER_WORKER = 2; private static final Logger LOGGER = LogManager.getLogger("ChunkBuilder"); private final Deque<WrappedTask<T>> buildQueue = new ConcurrentLinkedDeque<>(); // special queue for tasks that will block until the main thread finalizes them private final Deque<WrappedTask<T>> buildQueueKnownBlocking = new ConcurrentLinkedDeque<>(); private final Deque<ChunkBuildResult<T>> uploadQueue = new ConcurrentLinkedDeque<>(); private final Deque<Throwable> failureQueue = new ConcurrentLinkedDeque<>(); private final Object jobNotifier = new Object(); private final Object jobNotifierKnownBlocking = new Object(); private final AtomicBoolean running = new AtomicBoolean(false); private final List<Thread> threads = new ArrayList<>(); private ClonedChunkSectionCache sectionCache; private WorldClient world; private Vector3d cameraPosition = new Vector3d(); private final int limitThreads; private final int limitThreadsBlocking; private final ChunkVertexType vertexType; private final ChunkRenderBackend<T> backend; public ChunkBuilder(ChunkVertexType vertexType, ChunkRenderBackend<T> backend) { this.vertexType = vertexType; this.backend = backend; this.limitThreads = getThreadCount(); this.limitThreadsBlocking = this.limitThreads; } /** * Returns the remaining number of build tasks which should be scheduled this frame. If an attempt is made to * spawn more tasks than the budget allows, it will block until resources become available. */ public int getSchedulingBudget() { return Math.max(0, (this.limitThreads * TASK_QUEUE_LIMIT_PER_WORKER) - this.buildQueue.size() - this.buildQueueKnownBlocking.size()); } /** * Spawns a number of work-stealing threads to process results in the build queue. If the builder is already * running, this method does nothing and exits. */ public void startWorkers() { if (this.running.getAndSet(true)) { return; } if (!this.threads.isEmpty()) { throw new IllegalStateException("Threads are still alive while in the STOPPED state"); } Minecraft client = Minecraft.getMinecraft(); for (int i = 0; i < this.limitThreads; i++) { ChunkBuildBuffers buffers = new ChunkBuildBuffers(this.vertexType); ChunkRenderCacheLocal pipeline = new ChunkRenderCacheLocal(client, this.world); WorkerRunnable worker = new WorkerRunnable(i, buffers, pipeline, this.world, false); Thread thread = new Thread(worker, "Chunk Render Task Executor #" + i); thread.setPriority(Math.max(0, Thread.NORM_PRIORITY - 2)); thread.start(); this.threads.add(thread); } for (int i = 0; i < this.limitThreadsBlocking; i++) { ChunkBuildBuffers buffers = new ChunkBuildBuffers(this.vertexType); ChunkRenderCacheLocal pipeline = new ChunkRenderCacheLocal(client, this.world); WorkerRunnable worker = new WorkerRunnable(this.limitThreads + i, buffers, pipeline, this.world, true); Thread thread = new Thread(worker, "Chunk Render Blocking Task Executor #" + i); thread.setPriority(Math.max(0, Thread.NORM_PRIORITY - 2)); thread.start(); this.threads.add(thread); } LOGGER.info("Started {} worker threads", this.threads.size()); } private boolean workersAlive() { for (Thread thread : this.threads) { if (thread.isAlive()) { return true; } } return false; } /** * Notifies all worker threads to stop and blocks until all workers terminate. After the workers have been shut * down, all tasks are cancelled and the pending queues are cleared. If the builder is already stopped, this * method does nothing and exits. */ public void stopWorkers() { if (!this.running.getAndSet(false)) { return; } if (this.threads.isEmpty()) { throw new IllegalStateException("No threads are alive but the executor is in the RUNNING state"); } LOGGER.info("Stopping worker threads"); // Notify all worker threads to wake up, where they will then terminate synchronized (this.jobNotifier) { this.jobNotifier.notifyAll(); } synchronized (this.jobNotifierKnownBlocking) { this.jobNotifierKnownBlocking.notifyAll(); } // Keep processing the main thread tasks so the workers don't block forever AngelicaRenderQueue.managedBlock(() -> !workersAlive()); // Ensure every remaining thread has terminated for (Thread thread : this.threads) { try { thread.join(); } catch (InterruptedException ignored) { } } this.threads.clear(); // Drop any pending work queues and cancel futures this.uploadQueue.clear(); this.failureQueue.clear(); for (WrappedTask<?> job : this.buildQueue) { job.future.cancel(true); } for (WrappedTask<?> job : this.buildQueueKnownBlocking) { job.future.cancel(true); } this.buildQueue.clear(); this.buildQueueKnownBlocking.clear(); this.world = null; this.sectionCache = null; } public void cleanupSectionCache() { this.sectionCache.cleanup(); } /** * Prevent sort updates from taking priority over rebuild updates in the upload queue. */ public Iterator<ChunkBuildResult<T>> filterChunkBuilds(Iterator<ChunkBuildResult<T>> uploadIterator) { Reference2ReferenceLinkedOpenHashMap<ChunkRenderContainer<T>, ChunkBuildResult<T>> map = new Reference2ReferenceLinkedOpenHashMap<>(); while (uploadIterator.hasNext()) { ChunkBuildResult<T> result = uploadIterator.next(); ChunkRenderContainer<T> section = result.render; ChunkBuildResult<T> oldResult = map.get(section); // Allow a result to replace the previous result in the map if one of the following conditions hold: // * There is no previous upload in the queue // * The new upload replaces more render types than the old one (in practice, is a rebuild while the other is a sort) if(oldResult == null || result.passesToUpload.length >= oldResult.passesToUpload.length) { map.put(section, result); } } return map.values().iterator(); } /** * Processes all pending build task uploads using the chunk render backend. */ // TODO: Limit the amount of time this can take per frame public boolean performPendingUploads() { if (this.uploadQueue.isEmpty()) { return false; } this.backend.upload(RenderDevice.INSTANCE.createCommandList(), filterChunkBuilds(new DequeDrain<>(this.uploadQueue))); return true; } public void handleFailures() { Iterator<Throwable> errorIterator = new DequeDrain<>(this.failureQueue); if (errorIterator.hasNext()) { // If there is any exception from the build failure queue, throw it Throwable ex = errorIterator.next(); if (ex instanceof ReportedException) { // Propagate ReportedExceptions directly to provide extra information throw (ReportedException)ex; } else { throw new RuntimeException("Chunk build failed", ex); } } } public CompletableFuture<ChunkBuildResult<T>> schedule(ChunkRenderBuildTask<T> task) { if (!this.running.get()) { throw new IllegalStateException("Executor is stopped"); } WrappedTask<T> job = new WrappedTask<>(task); this.buildQueue.add(job); synchronized (this.jobNotifier) { this.jobNotifier.notify(); } return job.future; } /** * Sets the current camera position of the player used for task prioritization. */ public void setCameraPosition(double x, double y, double z) { this.cameraPosition = new Vector3d(x, y, z); } /** * Returns the current camera position of the player used for task prioritization. */ public Vector3d getCameraPosition() { return this.cameraPosition; } /** * @return True if the build queue is empty */ public boolean isBuildQueueEmpty() { return this.buildQueue.isEmpty() && this.buildQueueKnownBlocking.isEmpty(); } /** * Initializes this chunk builder for the given world. If the builder is already running (which can happen during * a world teleportation event), the worker threads will first be stopped and all pending tasks will be discarded * before being started again. * @param world The world instance */ public void init(WorldClient world) { if (world == null) { throw new NullPointerException("World is null"); } this.stopWorkers(); this.world = world; this.sectionCache = new ClonedChunkSectionCache(this.world); this.startWorkers(); } /** * Returns the "optimal" number of threads to be used for chunk build tasks. This is always at least one thread, * but can be up to the number of available processor threads on the system. */ private static int getOptimalThreadCount() { return MathHelper.clamp_int(Math.max(getMaxThreadCount() / 3, getMaxThreadCount() - 6), 1, 10); } private static int getThreadCount() { int requested = SodiumClientMod.options().performance.chunkBuilderThreads; return requested == 0 ? getOptimalThreadCount() : Math.min(requested, getMaxThreadCount()); } private static int getMaxThreadCount() { return Runtime.getRuntime().availableProcessors(); } /** * Add a completion handler to the given future task so that the result will be processed on the main thread. */ public void handleCompletion(CompletableFuture<ChunkBuildResult<T>> future) { future.whenComplete((res, ex) -> { if (ex != null) { this.failureQueue.add(ex); } else if (res != null) { this.enqueueUpload(res); } }); } /** * Creates a rebuild task and defers it to the work queue. When the task is completed, it will be moved onto the * completed uploads queued which will then be drained during the next available synchronization point with the * main thread. * @param render The render to rebuild */ public void deferSort(ChunkRenderContainer<T> render) { handleCompletion(this.scheduleSortTaskAsync(render)); } /** * Enqueues the build task result to the pending result queue to be later processed during the next available * synchronization point on the main thread. * @param result The build task's result */ public void enqueueUpload(ChunkBuildResult<T> result) { this.uploadQueue.add(result); } /** * Schedules the rebuild task asynchronously on the worker pool, returning a future wrapping the task. * @param render The render to rebuild * @return a future representing the rebuild task, or null if the chunk section is empty */ @Nullable public CompletableFuture<ChunkBuildResult<T>> scheduleRebuildTaskAsync(ChunkRenderContainer<T> render) { ChunkRenderBuildTask<T> task = this.createRebuildTask(render); if(task != null) { return this.schedule(task); } else { return null; } } /** * Schedules the rebuild task asynchronously on the worker pool, returning a future wrapping the task. * @param render The render to rebuild */ public CompletableFuture<ChunkBuildResult<T>> scheduleSortTaskAsync(ChunkRenderContainer<T> render) { return this.schedule(this.createSortTask(render)); } /** * Creates a task to rebuild the geometry of a {@link ChunkRenderContainer}. * @param render The render to rebuild */ private ChunkRenderBuildTask<T> createRebuildTask(ChunkRenderContainer<T> render) { render.cancelRebuildTask(); ChunkRenderContext context = WorldSlice.prepare(this.world, render.getChunkPos(), this.sectionCache); if (context == null) { return null; } else { return new ChunkRenderRebuildTask<>(render, context, render.getRenderOrigin()).withCameraPosition(this.cameraPosition); } } private ChunkRenderBuildTask<T> createSortTask(ChunkRenderContainer<T> render) { render.cancelRebuildTask(); return new ChunkRenderTranslucencySortTask<>(render, render.getRenderOrigin(), this.cameraPosition); } public void onChunkDataChanged(int x, int y, int z) { this.sectionCache.invalidate(x, y, z); } private class WorkerRunnable implements Runnable { private final AtomicBoolean running = ChunkBuilder.this.running; // The re-useable build buffers used by this worker for building chunk meshes private final ChunkBuildBuffers bufferCache; // Making this thread-local provides a small boost to performance by avoiding the overhead in synchronizing // caches between different CPU cores private final ChunkRenderCacheLocal cache; private final WorldClient world; private final int i; private final boolean allowBlocking; public WorkerRunnable(int i, ChunkBuildBuffers bufferCache, ChunkRenderCacheLocal cache, WorldClient world, boolean allowBlocking) { this.i = i; this.bufferCache = bufferCache; this.cache = cache; this.world = world; this.allowBlocking = allowBlocking; } @Override public void run() { // Run until the chunk builder shuts down while (this.running.get()) { WrappedTask<T> job = this.getNextJob(); // If the job is null or no longer valid, keep searching for a task if (job == null || job.isCancelled()) { continue; } // Relegate tasks that can block for an extended period of time to a separate threadpool. if (!this.allowBlocking && job.task.willRenderInMainThread(this.cache)) { ChunkBuilder.this.buildQueueKnownBlocking.add(job); synchronized (ChunkBuilder.this.jobNotifierKnownBlocking) { ChunkBuilder.this.jobNotifierKnownBlocking.notify(); } continue; } ChunkBuildResult<T> result; try { // Perform the build task with this worker's local resources and obtain the result result = job.task.performBuild(this.cache, this.bufferCache, job); } catch (Exception e) { // Propagate any exception from chunk building job.future.completeExceptionally(e); continue; } finally { job.task.releaseResources(); } // The result can be null if the task is cancelled if (result != null) { // Notify the future that the result is now available job.future.complete(result); // Unpark the main thread so it wakes up if it was blocking on the future having completed LockSupport.unpark(GLStateManager.getMainThread()); } else if (!job.isCancelled()) { // If the job wasn't cancelled and no result was produced, we've hit a bug job.future.completeExceptionally(new RuntimeException("No result was produced by the task " + job.task.getClass() + ": " + job.task)); } } } /** * Returns the next task which this worker can work on or blocks until one becomes available. If no tasks are * currently available, it will wait on {@link ChunkBuilder#jobNotifier} field until notified. */ private WrappedTask<T> getNextJob() { if (this.allowBlocking) { WrappedTask<T> job = ChunkBuilder.this.buildQueueKnownBlocking.poll(); if (job == null) { synchronized (ChunkBuilder.this.jobNotifierKnownBlocking) { try { ChunkBuilder.this.jobNotifierKnownBlocking.wait(); } catch (InterruptedException ignored) { } } } return job; } else { WrappedTask<T> job = ChunkBuilder.this.buildQueue.poll(); if (job == null) { synchronized (ChunkBuilder.this.jobNotifier) { try { ChunkBuilder.this.jobNotifier.wait(); } catch (InterruptedException ignored) { } } } return job; } } } private static class WrappedTask<T extends ChunkGraphicsState> implements CancellationSource { private final ChunkRenderBuildTask<T> task; private final CompletableFuture<ChunkBuildResult<T>> future; private WrappedTask(ChunkRenderBuildTask<T> task) { this.task = task; this.future = new CompletableFuture<>(); this.future.exceptionally(e -> { if (!(e instanceof CancellationException)) { LOGGER.info("Exception thrown while building chunk", e); } return null; }); } @Override public boolean isCancelled() { return this.future.isCancelled(); } } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\compile\ChunkBuildResult.java
package me.jellysquid.mods.sodium.client.render.chunk.compile; import me.jellysquid.mods.sodium.client.render.chunk.ChunkGraphicsState; import me.jellysquid.mods.sodium.client.render.chunk.ChunkRenderContainer; import me.jellysquid.mods.sodium.client.render.chunk.data.ChunkRenderData; import me.jellysquid.mods.sodium.client.render.chunk.passes.BlockRenderPass; /** * The result of a chunk rebuild task which contains any and all data that needs to be processed or uploaded on * the main thread. If a task is cancelled after finishing its work and not before the result is processed, the result * will instead be discarded. */ public class ChunkBuildResult<T extends ChunkGraphicsState> { public final ChunkRenderContainer<T> render; public final ChunkRenderData data; public BlockRenderPass[] passesToUpload; public ChunkBuildResult(ChunkRenderContainer<T> render, ChunkRenderData data) { this.render = render; this.data = data; this.passesToUpload = BlockRenderPass.VALUES; } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\cull\ChunkCuller.java
package me.jellysquid.mods.sodium.client.render.chunk.cull; import com.gtnewhorizons.angelica.compat.mojang.Camera; import com.gtnewhorizons.angelica.compat.mojang.ChunkOcclusionData; import it.unimi.dsi.fastutil.ints.IntArrayList; import me.jellysquid.mods.sodium.client.util.math.FrustumExtended; public interface ChunkCuller { IntArrayList computeVisible(Camera camera, FrustumExtended frustum, int frame, boolean spectator); void onSectionStateChanged(int x, int y, int z, ChunkOcclusionData occlusionData); void onSectionLoaded(int x, int y, int z, int id); void onSectionUnloaded(int x, int y, int z); boolean isSectionVisible(int x, int y, int z); }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\cull\ChunkFaceFlags.java
package me.jellysquid.mods.sodium.client.render.chunk.cull; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.properties.ModelQuadFacing; public class ChunkFaceFlags { public static final int UP = of(ModelQuadFacing.POS_Y); public static final int DOWN = of(ModelQuadFacing.NEG_Y); public static final int WEST = of(ModelQuadFacing.NEG_X); public static final int EAST = of(ModelQuadFacing.POS_X); public static final int NORTH = of(ModelQuadFacing.NEG_Z); public static final int SOUTH = of(ModelQuadFacing.POS_Z); public static final int UNASSIGNED = of(ModelQuadFacing.UNASSIGNED); public static final int ALL = all(); public static int of(ModelQuadFacing facing) { return 1 << facing.ordinal(); } private static int all() { int v = 0; for (ModelQuadFacing facing : ModelQuadFacing.VALUES) { v |= of(facing); } return v; } }