repo_id
stringclasses 383
values | file_path
stringlengths 7
168
| content
stringlengths 0
1.75M
|
|---|---|---|
Amulet-Map-Editor
|
amulet_map_editor\programs\edit\plugins\tools\export_tool.py
|
from amulet_map_editor.programs.edit.api.ui.tool import BaseOperationChoiceToolUI
class ExportTool(BaseOperationChoiceToolUI):
OperationGroupName = "export_operations"
ShowOpenFolder = False
@property
def name(self) -> str:
return "Export"
|
Amulet-Map-Editor
|
amulet_map_editor\programs\edit\plugins\tools\import_tool.py
|
import wx
from typing import TYPE_CHECKING
import traceback
import logging
import amulet
from amulet.api.errors import LoaderNoneMatched
from amulet_map_editor.api.wx.ui.traceback_dialog import TracebackDialog
from amulet_map_editor.programs.edit.api.ui.tool import DefaultBaseToolUI
from amulet_map_editor.programs.edit.api.behaviour import StaticSelectionBehaviour
if TYPE_CHECKING:
from amulet_map_editor.programs.edit.api.canvas import EditCanvas
log = logging.getLogger(__name__)
class ImportTool(wx.BoxSizer, DefaultBaseToolUI):
def __init__(self, canvas: "EditCanvas"):
wx.BoxSizer.__init__(self, wx.VERTICAL)
DefaultBaseToolUI.__init__(self, canvas)
self._selection = StaticSelectionBehaviour(self.canvas)
self._open_file_button = wx.Button(canvas, label="Import File")
self._open_file_button.Bind(wx.EVT_BUTTON, self._on_open_file)
self.AddStretchSpacer()
self.Add(self._open_file_button, flag=wx.ALL, border=10)
self.AddStretchSpacer()
@property
def name(self) -> str:
return "Import"
def bind_events(self):
super().bind_events()
self._selection.bind_events()
def enable(self):
super().enable()
self._selection.update_selection()
def disable(self):
super().disable()
def _on_open_file(self, evt):
with wx.FileDialog(
self.canvas,
"Open a Minecraft data file",
wildcard="|".join(
[ # TODO: Automatically load these from the FormatWrapper classes.
"All files (*.construction;*.mcstructure;*.schematic .schem)|*.construction;*.mcstructure;*.schematic;*.schem",
"Construction file (*.construction)|*.construction",
"Bedrock mcstructure file (*.mcstructure)|*.mcstructure",
"Legacy Schematic file (*.schematic)|*.schematic",
"Sponge Schematic file (*.schem)|*.schem",
]
),
style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST,
) as fileDialog:
if fileDialog.ShowModal() == wx.ID_CANCEL:
return
else:
pathname = fileDialog.GetPath()
try:
level = amulet.load_level(pathname)
except LoaderNoneMatched:
msg = f"Could not find a matching loader for {pathname}."
log.error(msg)
wx.MessageBox(msg)
except Exception as e:
log.error(f"Could not open {pathname}.", exc_info=True)
dialog = TracebackDialog(
self.canvas,
f"Could not open {pathname}.",
str(e),
traceback.format_exc(),
)
dialog.ShowModal()
dialog.Destroy()
else:
self.canvas.paste(level, level.dimensions[0])
|
Amulet-Map-Editor
|
amulet_map_editor\programs\edit\plugins\tools\operation.py
|
from amulet_map_editor.programs.edit.api.ui.tool import BaseOperationChoiceToolUI
class OperationTool(BaseOperationChoiceToolUI):
OperationGroupName = "operations"
@property
def name(self) -> str:
return "Operation"
|
Amulet-Map-Editor
|
amulet_map_editor\programs\edit\plugins\tools\paste.py
|
import wx
from typing import TYPE_CHECKING, Tuple, Union, Type
from OpenGL.GL import (
glClear,
GL_DEPTH_BUFFER_BIT,
)
import math
import numpy
import weakref
from amulet.api.data_types import PointCoordinates
from amulet.api.level import BaseLevel
from amulet.api.structure import structure_cache
from amulet.operations.paste import paste_iter
from amulet.utils.matrix import (
rotation_matrix_xyz,
decompose_transformation_matrix,
scale_matrix,
transform_matrix,
)
from amulet_map_editor import lang
from amulet_map_editor.api import image
from amulet_map_editor.api.wx.util.validators import IntValidator, FloatValidator
from amulet_map_editor.api.wx.ui.simple import SimpleScrollablePanel
from amulet_map_editor.api.opengl.camera import Projection, Camera
from amulet_map_editor.api.opengl.mesh.level import RenderLevel
from amulet_map_editor.programs.edit.api.key_config import (
KeybindGroup,
)
from amulet_map_editor.programs.edit.api.operations import OperationSuccessful
from amulet_map_editor.programs.edit.api.ui.nudge_button import NudgeButton
from amulet_map_editor.programs.edit.api.ui.tool import DefaultBaseToolUI
from amulet_map_editor.programs.edit.api.behaviour import StaticSelectionBehaviour
from amulet_map_editor.programs.edit.api.behaviour.pointer_behaviour import (
PointerBehaviour,
EVT_POINT_CHANGE,
PointChangeEvent,
)
from amulet_map_editor.programs.edit.api.events import (
InputPressEvent,
EVT_INPUT_PRESS,
)
from amulet_map_editor.programs.edit.api.key_config import ACT_BOX_CLICK
if TYPE_CHECKING:
from amulet_map_editor.programs.edit.api.canvas import EditCanvas
BottomLeftRight = wx.BOTTOM | wx.LEFT | wx.RIGHT
BottomLeftRightCentre = BottomLeftRight | wx.ALIGN_CENTER_HORIZONTAL
BottomLeftRightExpand = BottomLeftRight | wx.EXPAND
class TupleInput(wx.FlexGridSizer):
WindowCls: Union[Type[wx.SpinCtrl], Type[wx.SpinCtrlDouble]] = None
Validator: Type[wx.Validator] = None
def __init__(
self,
parent: wx.Window,
x_str: str,
y_str: str,
z_str: str,
min_value: int = -30_000_000,
max_value: int = 30_000_000,
start_value: int = 0,
style=wx.SP_ARROW_KEYS,
):
super().__init__(3, 2, 5, 5)
x_label = wx.StaticText(parent, label=x_str)
self.Add(x_label, 0, wx.ALIGN_CENTER)
self.x = self.WindowCls(
parent, min=min_value, max=max_value, initial=start_value, style=style
)
self.x.SetValidator(self.Validator())
self.Add(self.x, 0, wx.EXPAND)
y_label = wx.StaticText(parent, label=y_str)
self.Add(y_label, 0, wx.ALIGN_CENTER)
self.y = self.WindowCls(
parent, min=min_value, max=max_value, initial=start_value, style=style
)
self.y.SetValidator(self.Validator())
self.Add(self.y, 0, wx.EXPAND)
z_label = wx.StaticText(parent, label=z_str)
self.Add(z_label, 0, wx.ALIGN_CENTER)
self.z = self.WindowCls(
parent, min=min_value, max=max_value, initial=start_value, style=style
)
self.z.SetValidator(self.Validator())
self.Add(self.z, 0, wx.EXPAND)
self.AddGrowableCol(1)
@property
def value(self):
return self.x.GetValue(), self.y.GetValue(), self.z.GetValue()
@value.setter
def value(self, value):
self.x.SetValue(value[0])
self.y.SetValue(value[1])
self.z.SetValue(value[2])
class TupleIntInput(TupleInput):
WindowCls = wx.SpinCtrl
Validator = IntValidator
@property
def value(self) -> Tuple[int, int, int]:
return self.x.GetValue(), self.y.GetValue(), self.z.GetValue()
@value.setter
def value(self, value: Tuple[int, int, int]):
self.x.SetValue(value[0])
self.y.SetValue(value[1])
self.z.SetValue(value[2])
class TupleFloatInput(TupleInput):
WindowCls = wx.SpinCtrlDouble
Validator = FloatValidator
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.x.Bind(wx.EVT_MOUSEWHEEL, self._on_wheel)
self.y.Bind(wx.EVT_MOUSEWHEEL, self._on_wheel)
self.z.Bind(wx.EVT_MOUSEWHEEL, self._on_wheel)
self.x.SetIncrement(1)
self.y.SetIncrement(1)
self.z.SetIncrement(1)
@property
def value(self) -> Tuple[float, float, float]:
return self.x.GetValue(), self.y.GetValue(), self.z.GetValue()
@value.setter
def value(self, value: Tuple[float, float, float]):
self.x.SetValue(value[0])
self.y.SetValue(value[1])
self.z.SetValue(value[2])
def _on_wheel(self, evt: wx.MouseEvent):
"""Add scroll wheel behaviour to the input."""
rotation = evt.GetWheelRotation()
ctrl = evt.GetEventObject()
if rotation > 0:
ctrl.SetValue(ctrl.GetValue() + ctrl.GetIncrement())
self._changed(ctrl)
elif rotation < 0:
ctrl.SetValue(ctrl.GetValue() - ctrl.GetIncrement())
self._changed(ctrl)
@staticmethod
def _changed(ctrl: wx.SpinCtrlDouble):
"""Create a changed event for the SpinCtrlDouble."""
evt = wx.SpinDoubleEvent(wx.wxEVT_SPINCTRLDOUBLE, ctrl.GetId(), ctrl.GetValue())
evt.SetEventObject(ctrl)
wx.PostEvent(ctrl, evt)
class RotationTupleInput(TupleFloatInput):
def __init__(
self,
parent: wx.Window,
x_str: str,
y_str: str,
z_str: str,
increment=90,
):
super().__init__(
parent, x_str, y_str, z_str, -180, 180, style=wx.SP_ARROW_KEYS | wx.SP_WRAP
)
self.increment = increment
self.x.Bind(wx.EVT_SPINCTRLDOUBLE, self._on_change)
self.y.Bind(wx.EVT_SPINCTRLDOUBLE, self._on_change)
self.z.Bind(wx.EVT_SPINCTRLDOUBLE, self._on_change)
@property
def value(self) -> Tuple[float, float, float]:
return self.x.GetValue(), self.y.GetValue(), self.z.GetValue()
@value.setter
def value(self, value: Tuple[float, float, float]):
self.x.SetValue(round(value[0]))
self.y.SetValue(round(value[1]))
self.z.SetValue(round(value[2]))
@property
def rotation_radians(self) -> Tuple[float, float, float]:
return (
math.radians(self.x.GetValue()),
math.radians(self.y.GetValue()),
math.radians(self.z.GetValue()),
)
@property
def increment(self) -> int:
return self.x.GetIncrement()
@increment.setter
def increment(self, increment: int):
assert isinstance(increment, int) and increment >= 1
self.x.SetIncrement(increment)
self.y.SetIncrement(increment)
self.z.SetIncrement(increment)
self._round_values()
@staticmethod
def _on_change(evt: wx.SpinDoubleEvent):
ctrl = evt.GetEventObject()
ctrl.SetValue(
int(round(ctrl.GetValue() / ctrl.GetIncrement())) * ctrl.GetIncrement()
)
evt.SetValue(ctrl.GetValue())
evt.Skip()
def _round_value(self, ctrl: wx.SpinCtrlDouble):
ctrl.SetValue(
int(round(ctrl.GetValue() / ctrl.GetIncrement())) * ctrl.GetIncrement()
)
self._changed(ctrl)
def _round_values(self):
self._round_value(self.x)
self._round_value(self.y)
self._round_value(self.z)
class MoveButton(NudgeButton):
def __init__(
self,
parent: wx.Window,
camera: Camera,
keybinds: KeybindGroup,
label: str,
tooltip: str,
paste_tool: "PasteTool",
):
super().__init__(parent, camera, keybinds, label, tooltip)
self._paste_tool = weakref.ref(paste_tool)
def _move(self, offset: Tuple[int, int, int]):
ox, oy, oz = offset
x, y, z = self._paste_tool().location
self._paste_tool().location = x + ox, y + oy, z + oz
class PasteTool(wx.BoxSizer, DefaultBaseToolUI):
def __init__(self, canvas: "EditCanvas"):
wx.BoxSizer.__init__(self, wx.HORIZONTAL)
DefaultBaseToolUI.__init__(self, canvas)
self._selection = StaticSelectionBehaviour(self.canvas)
self._cursor = PointerBehaviour(self.canvas)
self._moving = False
self._is_enabled = False
self._paste_panel = SimpleScrollablePanel(canvas)
self._paste_sizer = wx.BoxSizer(wx.VERTICAL)
self._paste_panel.SetSizer(self._paste_sizer)
self.Add(self._paste_panel, 0, wx.ALIGN_CENTER_VERTICAL)
def add_line():
"""add a line to the UI"""
line = wx.StaticLine(self._paste_panel)
self._paste_sizer.Add(line, 0, wx.BOTTOM | wx.EXPAND, 5)
def add_tick_box(name: str, state: bool = True):
tick = wx.CheckBox(self._paste_panel, label=name)
tick.SetValue(state)
self._paste_sizer.Add(
tick,
flag=BottomLeftRight,
border=5,
)
return tick
def add_label(name: str):
label = wx.StaticText(self._paste_panel, label=name)
label.SetFont(
wx.Font(
12,
wx.FONTFAMILY_DEFAULT,
wx.FONTSTYLE_NORMAL,
wx.FONTWEIGHT_NORMAL,
True,
)
)
self._paste_sizer.Add(label, 0, BottomLeftRightCentre, 5)
self._paste_sizer.AddSpacer(5)
add_label(lang.get("program_3d_edit.paste_tool.location_label"))
self._location = TupleIntInput(
self._paste_panel,
lang.get("program_3d_edit.paste_tool.location_x_label"),
lang.get("program_3d_edit.paste_tool.location_y_label"),
lang.get("program_3d_edit.paste_tool.location_z_label"),
)
self._location.x.SetToolTip(
lang.get("program_3d_edit.paste_tool.location_x_tooltip")
)
self._location.y.SetToolTip(
lang.get("program_3d_edit.paste_tool.location_y_tooltip")
)
self._location.z.SetToolTip(
lang.get("program_3d_edit.paste_tool.location_z_tooltip")
)
self._paste_sizer.Add(
self._location,
flag=BottomLeftRightExpand,
border=5,
)
self._move_button = MoveButton(
self._paste_panel,
self.canvas.camera,
self.canvas.key_binds,
lang.get("program_3d_edit.paste_tool.move_selection_label"),
lang.get("program_3d_edit.paste_tool.move_selection_tooltip"),
self,
)
self._paste_sizer.Add(
self._move_button,
flag=BottomLeftRightExpand,
border=5,
)
add_line()
add_label(lang.get("program_3d_edit.paste_tool.rotation_label"))
self._free_rotation = wx.CheckBox(
self._paste_panel,
label=lang.get("program_3d_edit.paste_tool.free_rotation_label"),
)
self._free_rotation.SetToolTip(
lang.get("program_3d_edit.paste_tool.free_rotation_tooltip")
)
self._paste_sizer.Add(
self._free_rotation,
flag=BottomLeftRight,
border=5,
)
self._rotation = RotationTupleInput(
self._paste_panel,
lang.get("program_3d_edit.paste_tool.rotation_x_label"),
lang.get("program_3d_edit.paste_tool.rotation_y_label"),
lang.get("program_3d_edit.paste_tool.rotation_z_label"),
)
self._rotation.x.SetToolTip(
lang.get("program_3d_edit.paste_tool.rotation_x_tooltip")
)
self._rotation.y.SetToolTip(
lang.get("program_3d_edit.paste_tool.rotation_y_tooltip")
)
self._rotation.z.SetToolTip(
lang.get("program_3d_edit.paste_tool.rotation_z_tooltip")
)
self._paste_sizer.Add(
self._rotation,
flag=BottomLeftRightExpand,
border=5,
)
self._free_rotation.Bind(wx.EVT_CHECKBOX, self._on_free_rotation_change)
rotate_sizer = wx.BoxSizer(wx.HORIZONTAL)
self._paste_sizer.Add(
rotate_sizer,
flag=BottomLeftRightCentre,
border=5,
)
self._rotate_left_button = wx.BitmapButton(
self._paste_panel, bitmap=image.icon.tablericons.rotate_2.bitmap(22, 22)
)
self._rotate_left_button.SetToolTip(
lang.get("program_3d_edit.paste_tool.rotate_anti_clockwise_tooltip")
)
self._rotate_left_button.Bind(wx.EVT_BUTTON, self._on_rotate_left)
rotate_sizer.Add(self._rotate_left_button)
self._rotate_right_button = wx.BitmapButton(
self._paste_panel,
bitmap=image.icon.tablericons.rotate_clockwise_2.bitmap(22, 22),
)
self._rotate_right_button.SetToolTip(
lang.get("program_3d_edit.paste_tool.rotate_clockwise_tooltip")
)
self._rotate_right_button.Bind(wx.EVT_BUTTON, self._on_rotate_right)
rotate_sizer.Add(self._rotate_right_button)
add_line()
add_label(lang.get("program_3d_edit.paste_tool.scale_label"))
self._scale = TupleFloatInput(
self._paste_panel,
lang.get("program_3d_edit.paste_tool.scale_x_label"),
lang.get("program_3d_edit.paste_tool.scale_y_label"),
lang.get("program_3d_edit.paste_tool.scale_z_label"),
start_value=1,
)
self._scale.x.SetToolTip(lang.get("program_3d_edit.paste_tool.scale_x_tooltip"))
self._scale.y.SetToolTip(lang.get("program_3d_edit.paste_tool.scale_y_tooltip"))
self._scale.z.SetToolTip(lang.get("program_3d_edit.paste_tool.scale_z_tooltip"))
self._scale.x.SetDigits(2)
self._scale.y.SetDigits(2)
self._scale.z.SetDigits(2)
self._paste_sizer.Add(
self._scale,
flag=BottomLeftRightExpand,
border=5,
)
self._paste_panel.Bind(wx.EVT_SPINCTRL, self._on_transform_change)
self._paste_panel.Bind(wx.EVT_SPINCTRLDOUBLE, self._on_transform_change)
mirror_sizer = wx.BoxSizer(wx.HORIZONTAL)
self._paste_sizer.Add(
mirror_sizer,
flag=BottomLeftRightCentre,
border=5,
)
# the tablericons file names are the wrong way around
self._mirror_horizontal_button = wx.BitmapButton(
self._paste_panel,
bitmap=image.icon.tablericons.flip_vertical.bitmap(22, 22),
)
self._mirror_horizontal_button.SetToolTip(
lang.get("program_3d_edit.paste_tool.mirror_horizontal_tooltip")
)
self._mirror_horizontal_button.Bind(wx.EVT_BUTTON, self._on_mirror_horizontal)
mirror_sizer.Add(self._mirror_horizontal_button)
self._mirror_vertical_button = wx.BitmapButton(
self._paste_panel,
bitmap=image.icon.tablericons.flip_horizontal.bitmap(22, 22),
)
self._mirror_vertical_button.SetToolTip(
lang.get("program_3d_edit.paste_tool.mirror_vertical_tooltip")
)
self._mirror_vertical_button.Bind(wx.EVT_BUTTON, self._on_mirror_vertical)
mirror_sizer.Add(self._mirror_vertical_button)
add_line()
self._copy_air = add_tick_box(
lang.get("program_3d_edit.paste_tool.copy_air_label")
)
self._copy_air.SetToolTip(
lang.get("program_3d_edit.paste_tool.copy_air_tooltip")
)
self._copy_water = add_tick_box(
lang.get("program_3d_edit.paste_tool.copy_water_label")
)
self._copy_water.SetToolTip(
lang.get("program_3d_edit.paste_tool.copy_water_tooltip")
)
self._copy_lava = add_tick_box(
lang.get("program_3d_edit.paste_tool.copy_lava_label")
)
self._copy_lava.SetToolTip(
lang.get("program_3d_edit.paste_tool.copy_lava_tooltip")
)
add_line()
confirm_button = wx.Button(self._paste_panel, label="Confirm")
self._paste_sizer.Add(confirm_button, 0, BottomLeftRightExpand, 5)
confirm_button.Bind(wx.EVT_BUTTON, self._paste_confirm)
self._paste_panel.Disable()
self.Layout()
@property
def name(self) -> str:
return "Paste"
def bind_events(self):
super().bind_events()
self._selection.bind_events()
self._cursor.bind_events()
self.canvas.Bind(EVT_POINT_CHANGE, self._on_pointer_change)
self.canvas.Bind(EVT_INPUT_PRESS, self._on_input_press)
def enable(self):
super().enable()
self._move_button.enable()
self._selection.update_selection()
self._moving = False
def set_state(self, state):
if (
isinstance(state, dict)
and isinstance(state.get("structure"), BaseLevel)
and isinstance(state.get("dimension"), str)
):
structure = state["structure"]
dimension = state["dimension"]
elif structure_cache:
structure, dimension = structure_cache.get_structure()
else:
wx.MessageBox("A structure needs to be copied before one can be pasted.")
return
self._paste_panel.Enable()
self._is_enabled = True
self.canvas.renderer.fake_levels.clear()
self.canvas.renderer.fake_levels.append(
structure, dimension, (0, 0, 0), (1, 1, 1), (0, 0, 0)
)
self._moving = True
def disable(self):
super().disable()
self._move_button.disable()
self._paste_panel.Disable()
self._is_enabled = False
self.canvas.renderer.fake_levels.clear()
@property
def location(self) -> PointCoordinates:
"""The location as specified in the UI."""
return self._location.value
@location.setter
def location(self, location: PointCoordinates):
"""Set the location value.
Will update the UI and the renderer."""
self._location.value = location
self._update_transform()
def _on_free_rotation_change(self, evt):
if self._free_rotation.GetValue():
self._rotation.increment = 1
else:
self._rotation.increment = 90
def _on_rotate_left(self, evt):
self._rotate(-90)
def _on_rotate_right(self, evt):
self._rotate(90)
def _rotate(self, angle: int):
"""Rotate the floating selection by the angle based on the camera rotation."""
angle = math.radians(angle)
ry, rx = self.canvas.camera.rotation
if rx < -45:
rotation_change = rotation_matrix_xyz(0, angle, 0)
elif -45 <= rx < 45:
if -135 <= ry < -45:
# east
rotation_change = rotation_matrix_xyz(angle, 0, 0)
elif -45 <= ry < 45:
# south
rotation_change = rotation_matrix_xyz(0, 0, angle)
elif 45 <= ry < 135:
# west
rotation_change = rotation_matrix_xyz(-angle, 0, 0)
else:
# north
rotation_change = rotation_matrix_xyz(0, 0, -angle)
else:
rotation_change = rotation_matrix_xyz(0, -angle, 0)
self._rotation.value = numpy.rad2deg(
decompose_transformation_matrix(
numpy.matmul(
rotation_change, rotation_matrix_xyz(*self._rotation_radians())
)
)[1]
)
self._update_transform()
def _rotation_radians(self) -> Tuple[float, float, float]:
return tuple(math.radians(v) for v in self._rotation.value)
def _on_mirror_vertical(self, evt):
ry, rx = self.canvas.camera.rotation
if -45 <= rx < 45:
# looking north, east, south or west vertical mirror is always in y
self._mirror(1)
elif -135 <= ry < -45 or 45 <= ry < 135:
# looking down or up facing east or west
self._mirror(0)
else:
# looking down or up facing north or south
self._mirror(2)
def _on_mirror_horizontal(self, evt):
ry, rx = self.canvas.camera.rotation
if -135 <= ry < -45 or 45 <= ry < 135:
# facing east or west
self._mirror(2)
else:
# facing north or south
self._mirror(0)
def _mirror(self, axis: int):
"""Mirror the selection in the given axis.
:param axis: The axis to scale in 0=x, 1=y, 2=z
:return:
"""
scale = [(-1, 1, 1), (1, -1, 1), (1, 1, -1)][axis]
self._scale.value, rotation, _ = decompose_transformation_matrix(
numpy.matmul(
scale_matrix(*scale),
transform_matrix(
self._scale.value, self._rotation_radians(), (0, 0, 0)
),
)
)
self._rotation.value = numpy.rad2deg(rotation)
self._update_transform()
def _on_pointer_change(self, evt: PointChangeEvent):
if self._is_enabled and self._moving:
self.canvas.renderer.fake_levels.active_transform = (
evt.point,
self._scale.value,
self._rotation_radians(),
)
self._location.value = evt.point
evt.Skip()
def _on_transform_change(self, evt):
self._update_transform()
evt.Skip()
def _update_transform(self):
"""Update the renderer with the new values."""
self.canvas.renderer.fake_levels.active_transform = (
self._location.value,
self._scale.value,
self._rotation_radians(),
)
def _on_input_press(self, evt: InputPressEvent):
if evt.action_id == ACT_BOX_CLICK:
if self._is_enabled:
self._moving = not self._moving
if self._moving:
self.canvas.renderer.fake_levels.active_transform = (
self._location.value,
self._scale.value,
self._rotation_radians(),
)
evt.Skip()
def _paste_operation(self):
if all(self._scale.value):
fake_levels = self.canvas.renderer.fake_levels
level_index: int = fake_levels.active_level_index
if level_index is not None:
render_level: RenderLevel = fake_levels.render_levels[level_index]
yield from paste_iter(
self.canvas.world,
self.canvas.dimension,
render_level.level,
render_level.dimension,
self._location.value,
self._scale.value,
self._rotation.value,
self._copy_air.GetValue(),
self._copy_water.GetValue(),
self._copy_lava.GetValue(),
)
else:
raise OperationSuccessful(
lang.get("program_3d_edit.paste_tool.zero_scale_message")
)
def _paste_confirm(self, evt):
self.canvas.run_operation(self._paste_operation)
def _on_draw(self, evt):
self.canvas.renderer.start_draw()
if self.canvas.camera.projection_mode == Projection.PERSPECTIVE:
self.canvas.renderer.draw_sky_box()
glClear(GL_DEPTH_BUFFER_BIT)
self.canvas.renderer.draw_level()
self.canvas.renderer.draw_fake_levels()
self._selection.draw()
self.canvas.renderer.end_draw()
|
Amulet-Map-Editor
|
amulet_map_editor\programs\edit\plugins\tools\select.py
|
from typing import TYPE_CHECKING, Type, Any, Callable, Tuple
import wx
from OpenGL.GL import (
glClear,
GL_DEPTH_BUFFER_BIT,
)
from amulet.api.data_types import BlockCoordinates
from amulet_map_editor import lang
from amulet_map_editor.api.wx.ui.simple import SimpleScrollablePanel
from amulet_map_editor.api.wx.util.validators import IntValidator
from amulet_map_editor.api.opengl.camera import Projection, Camera
from amulet_map_editor.programs.edit.api.events import EVT_SELECTION_CHANGE
from amulet_map_editor.programs.edit.api.behaviour.inspect_block_behaviour import (
InspectBlockBehaviour,
)
from amulet_map_editor.programs.edit.api.behaviour.block_selection_behaviour import (
BlockSelectionBehaviour,
EVT_RENDER_BOX_CHANGE,
RenderBoxChangeEvent,
EVT_RENDER_BOX_DISABLE_INPUTS,
EVT_RENDER_BOX_ENABLE_INPUTS,
)
from amulet_map_editor.programs.edit.api.ui.tool import DefaultBaseToolUI
from amulet_map_editor.programs.edit.api.key_config import (
KeybindGroup,
)
from amulet_map_editor.programs.edit.api.ui.nudge_button import NudgeButton
if TYPE_CHECKING:
from amulet_map_editor.programs.edit.api.canvas import EditCanvas
class BaseSelectionMoveButton(NudgeButton):
def __init__(
self,
parent: wx.Window,
camera: Camera,
keybinds: KeybindGroup,
label: str,
tooltip: str,
selection: BlockSelectionBehaviour,
):
super().__init__(parent, camera, keybinds, label, tooltip)
self._selection = selection
class Point1MoveButton(BaseSelectionMoveButton):
def _move(self, offset: Tuple[int, int, int]):
ox, oy, oz = offset
(x, y, z), point2 = self._selection.active_block_positions
self._selection.active_block_positions = (x + ox, y + oy, z + oz), point2
class Point2MoveButton(BaseSelectionMoveButton):
def _move(self, offset: Tuple[int, int, int]):
ox, oy, oz = offset
point1, (x, y, z) = self._selection.active_block_positions
self._selection.active_block_positions = point1, (x + ox, y + oy, z + oz)
class SelectionMoveButton(BaseSelectionMoveButton):
def _move(self, offset: Tuple[int, int, int]):
ox, oy, oz = offset
(x1, y1, z1), (x2, y2, z2) = self._selection.active_block_positions
self._selection.active_block_positions = (x1 + ox, y1 + oy, z1 + oz), (
x2 + ox,
y2 + oy,
z2 + oz,
)
class SelectTool(wx.BoxSizer, DefaultBaseToolUI):
_x1: wx.SpinCtrl
_y1: wx.SpinCtrl
_z1: wx.SpinCtrl
_x2: wx.SpinCtrl
_y2: wx.SpinCtrl
_z2: wx.SpinCtrl
def __init__(self, canvas: "EditCanvas"):
wx.BoxSizer.__init__(self, wx.HORIZONTAL)
DefaultBaseToolUI.__init__(self, canvas)
self._selection = BlockSelectionBehaviour(self.canvas)
self._inspect_block = InspectBlockBehaviour(self.canvas, self._selection)
self._button_panel = SimpleScrollablePanel(canvas)
button_sizer = wx.BoxSizer(wx.VERTICAL)
self._button_panel.SetSizer(button_sizer)
def add_button(
label: str, tooltip: str, action: Callable[[wx.PyEventBinder], None]
):
button = wx.Button(self._button_panel, label=label)
button.SetToolTip(tooltip)
button_sizer.Add(button, 0, wx.ALL | wx.EXPAND, 5)
button.Bind(wx.EVT_BUTTON, action)
add_button(
lang.get("program_3d_edit.select_tool.delete_button"),
lang.get("program_3d_edit.select_tool.delete_button_tooltip"),
lambda evt: self.canvas.delete(),
)
add_button(
lang.get("program_3d_edit.select_tool.copy_button"),
lang.get("program_3d_edit.select_tool.copy_button_tooltip"),
lambda evt: self.canvas.copy(),
)
add_button(
lang.get("program_3d_edit.select_tool.cut_button"),
lang.get("program_3d_edit.select_tool.cut_button_tooltip"),
lambda evt: self.canvas.cut(),
)
add_button(
lang.get("program_3d_edit.select_tool.paste_button"),
lang.get("program_3d_edit.select_tool.paste_button_tooltip"),
lambda evt: self.canvas.paste_from_cache(),
)
self.Add(self._button_panel, 0, wx.ALIGN_CENTER_VERTICAL)
self._x1 = self._add_spin_ctrl(
lang.get("program_3d_edit.select_tool.scroll_point_x1"),
lang.get("program_3d_edit.select_tool.scroll_point_x1_tooltip"),
(160, 215, 145),
)
self._y1 = self._add_spin_ctrl(
lang.get("program_3d_edit.select_tool.scroll_point_y1"),
lang.get("program_3d_edit.select_tool.scroll_point_y1_tooltip"),
(160, 215, 145),
)
self._z1 = self._add_spin_ctrl(
lang.get("program_3d_edit.select_tool.scroll_point_z1"),
lang.get("program_3d_edit.select_tool.scroll_point_z1_tooltip"),
(160, 215, 145),
)
self._x2 = self._add_spin_ctrl(
lang.get("program_3d_edit.select_tool.scroll_point_x2"),
lang.get("program_3d_edit.select_tool.scroll_point_x2_tooltip"),
(150, 150, 215),
)
self._y2 = self._add_spin_ctrl(
lang.get("program_3d_edit.select_tool.scroll_point_y2"),
lang.get("program_3d_edit.select_tool.scroll_point_y2_tooltip"),
(150, 150, 215),
)
self._z2 = self._add_spin_ctrl(
lang.get("program_3d_edit.select_tool.scroll_point_z2"),
lang.get("program_3d_edit.select_tool.scroll_point_z2_tooltip"),
(150, 150, 215),
)
self._box_size_selector_fstring = lang.get(
"program_3d_edit.select_tool.box_size_selector_fstring"
)
try:
box_size_fstring = self._box_size_selector_fstring.format(x=0, y=0, z=0)
except:
self._box_size_selector_fstring = "dx={x},dy={y},dz={z}"
box_size_fstring = self._box_size_selector_fstring.format(x=0, y=0, z=0)
self._box_size_selector_text = wx.StaticText(
self._button_panel, label=box_size_fstring, style=wx.ALIGN_CENTER_HORIZONTAL
)
self._box_size_selector_text.SetToolTip(
lang.get("program_3d_edit.select_tool.box_size_selector_tooltip")
)
button_sizer.Add(self._box_size_selector_text, 0, wx.ALL | wx.EXPAND, 5)
self._box_volume_text = wx.StaticText(
self._button_panel, label="0x0x0=0", style=wx.ALIGN_CENTER_HORIZONTAL
)
button_sizer.Add(self._box_volume_text, 0, wx.ALL | wx.EXPAND, 5)
self._box_volume_text.SetToolTip(
lang.get("program_3d_edit.select_tool.box_size_tooltip")
)
self._point1_move = Point1MoveButton(
self._button_panel,
self.canvas.camera,
self.canvas.key_binds,
lang.get("program_3d_edit.select_tool.button_point1"),
lang.get("program_3d_edit.select_tool.button_point1_tooltip"),
self._selection,
)
self._point1_move.SetBackgroundColour((160, 215, 145))
self._point1_move.Disable()
button_sizer.Add(self._point1_move, 0, wx.ALL | wx.EXPAND, 5)
self._point2_move = Point2MoveButton(
self._button_panel,
self.canvas.camera,
self.canvas.key_binds,
lang.get("program_3d_edit.select_tool.button_point2"),
lang.get("program_3d_edit.select_tool.button_point2_tooltip"),
self._selection,
)
self._point2_move.SetBackgroundColour((150, 150, 215))
self._point2_move.Disable()
button_sizer.Add(self._point2_move, 0, wx.ALL | wx.EXPAND, 5)
self._selection_move = SelectionMoveButton(
self._button_panel,
self.canvas.camera,
self.canvas.key_binds,
lang.get("program_3d_edit.select_tool.button_selection_box"),
lang.get("program_3d_edit.select_tool.button_selection_box_tooltip"),
self._selection,
)
self._selection_move.SetBackgroundColour((255, 255, 255))
self._selection_move.Disable()
button_sizer.Add(self._selection_move, 0, wx.ALL | wx.EXPAND, 5)
@property
def name(self) -> str:
return "Select"
def bind_events(self):
super().bind_events()
self.canvas.Bind(EVT_RENDER_BOX_CHANGE, self._box_renderer_change)
self.canvas.Bind(EVT_RENDER_BOX_DISABLE_INPUTS, self._disable_inputs)
self.canvas.Bind(EVT_RENDER_BOX_ENABLE_INPUTS, self._enable_inputs)
self.canvas.Bind(EVT_SELECTION_CHANGE, self._on_selection_change)
self._selection.bind_events()
self._inspect_block.bind_events()
def enable(self):
super().enable()
self._selection.enable()
self._pull_selection()
self._point1_move.enable()
self._point2_move.enable()
self._selection_move.enable()
def disable(self):
super().disable()
self._point1_move.disable()
self._point2_move.disable()
self._selection_move.disable()
def _add_spin_ctrl(
self, label: str, tooltip: str, colour: Tuple[int, int, int]
) -> wx.SpinCtrl:
sizer = wx.BoxSizer(wx.HORIZONTAL)
self._button_panel.GetSizer().Add(sizer, 0, wx.EXPAND)
name_text = wx.StaticText(self._button_panel, label=label)
sizer.Add(name_text, flag=wx.ALIGN_CENTER | wx.ALL, border=5)
obj = wx.SpinCtrl(
self._button_panel,
style=wx.SP_ARROW_KEYS
| wx.TE_PROCESS_ENTER
| wx.ALIGN_CENTER_VERTICAL
| wx.WANTS_CHARS,
min=-30000000,
max=30000000,
)
sizer.Add(obj, 1, flag=wx.CENTER | wx.TOP | wx.BOTTOM | wx.RIGHT, border=5)
obj.Bind(wx.EVT_SPINCTRL, self._box_input_change)
obj.SetValidator(IntValidator())
obj.Disable()
obj.SetToolTip(tooltip)
obj.SetBackgroundColour(colour)
return obj
def _box_input_change(self, _):
self._selection.active_block_positions = (
(self._x1.GetValue(), self._y1.GetValue(), self._z1.GetValue()),
(self._x2.GetValue(), self._y2.GetValue(), self._z2.GetValue()),
)
def _box_renderer_change(self, evt: RenderBoxChangeEvent):
self._update_selection_inputs(*evt.points)
evt.Skip()
def _on_selection_change(self, evt):
self._pull_selection()
evt.Skip()
def _pull_selection(self):
self._update_selection_inputs(*self._selection.active_block_positions)
def _update_selection_inputs(
self, point1: BlockCoordinates, point2: BlockCoordinates
):
x1, y1, z1, x2, y2, z2 = map(int, (*point1, *point2))
self._x1.SetValue(x1)
self._y1.SetValue(y1)
self._z1.SetValue(z1)
self._x2.SetValue(x2)
self._y2.SetValue(y2)
self._z2.SetValue(z2)
xdim = int(abs(x2 - x1))
ydim = int(abs(y2 - y1))
zdim = int(abs(z2 - z1))
self._box_size_selector_text.SetLabel(
self._box_size_selector_fstring.format(
x=xdim,
y=ydim,
z=zdim,
)
)
self._box_volume_text.SetLabel(
f"{xdim + 1}x{ydim + 1}x{zdim + 1}={(xdim + 1)*(ydim + 1)*(zdim + 1):,}"
)
self.Layout()
def _enable_inputs(self, evt):
self._set_scroll_state(True)
self._point1_move.Enable()
self._point2_move.Enable()
self._selection_move.Enable()
evt.Skip()
def _disable_inputs(self, evt):
self._set_scroll_state(False)
self._point1_move.Disable()
self._point2_move.Disable()
self._selection_move.Disable()
evt.Skip()
def _set_scroll_state(self, state: bool):
for scroll in (self._x1, self._y1, self._z1, self._x2, self._y2, self._z2):
scroll.Enable(state)
def _on_draw(self, evt):
self.canvas.renderer.start_draw()
if self.canvas.camera.projection_mode == Projection.PERSPECTIVE:
self.canvas.renderer.draw_sky_box()
glClear(GL_DEPTH_BUFFER_BIT)
self.canvas.renderer.draw_level()
self._selection.draw()
self.canvas.renderer.end_draw()
|
Amulet-Map-Editor
|
amulet_map_editor\programs\edit\plugins\tools\__init__.py
|
from .select import SelectTool
from .operation import OperationTool
from .export_tool import ExportTool
from .import_tool import ImportTool
from .chunk import ChunkTool
from .paste import PasteTool
|
Amulet-Map-Editor
|
amulet_map_editor\programs\edit\plugins\operations\examples\1_fixed_function_pipeline.py
|
# Fixed function example plugin
# The fixed function operation pipeline works in much the same way as MCEdit Unified filters with some modifications
# You define a function and it will appear in the UI for you to run
from amulet.api.selection import SelectionGroup
from amulet.api.level import BaseLevel
from amulet.api.data_types import Dimension
# for those that are new to python 3 the thing after the colon is the object type that the variable should be
def operation(
world: BaseLevel, dimension: Dimension, selection: SelectionGroup, options: dict
):
# world is the object that contains all the data related to the world
# dimension in a string used to identify the currently loaded dimension. It can be used to access the right dimension from the world
# selection is an object describing the selections made by the user. It is possible there may not be any boxes selected
# options will be explored in further examples
pass
export = { # This is what the program will actually look for. It describes how the operation will work
"name": "Fixed Function Pipeline Example 1", # the name of the plugin
"operation": operation, # the actual function to call when running the plugin
}
|
Amulet-Map-Editor
|
amulet_map_editor\programs\edit\plugins\operations\examples\2_fixed_function_pipeline.py
|
# Fixed function example plugin 2
# see example 1 before looking at this example
# Notes about the operation
from amulet.api.selection import SelectionGroup
from amulet.api.level import BaseLevel
from amulet.api.data_types import Dimension
# Notes about the operation
# The operation is allowed to yield floats in the range 0 to 1.
# This is used to update the loading bar in the UI. Without this the UI may appear to be not responding
# It can optionally also yield a float and a string. The float is the same as the above and the string is used to display in the loading bar
# The operation is allowed to return a value however nothing will be done with it
def operation(
world: BaseLevel, dimension: Dimension, selection: SelectionGroup, options: dict
):
for i in range(10):
# do some logic
yield (i + 1) / 10
for i in range(10):
# do some logic
yield (i + 1) / 10, f"Step {i} of 10"
return "hello" # This will not actually do anything but is allowed
export = {
"name": "Fixed Function Pipeline Example 2",
"operation": operation,
}
|
Amulet-Map-Editor
|
amulet_map_editor\programs\edit\plugins\operations\examples\3_fixed_function_pipeline.py
|
# Fixed function example plugin 3
# see example 2 before looking at this example
# This example shows how to use options with the fixed function pipeline
from amulet.api.selection import SelectionGroup
from amulet.api.level import BaseLevel
from amulet.api.data_types import Dimension
# function example for the Button input.
def function_name():
print("you have clicked a button.")
operation_options = { # options is a dictionary where the key is the description shown to the user and the value describes how to build the UI
"Text Label": ["label"], # This will just be a label
# bool examples https://wxpython.org/Phoenix/docs/html/wx.CheckBox.html
"Bool input default": [
"bool"
], # This will be a check box that takes the default value (unchecked)
"Bool input False": [
"bool",
False,
], # This will be a check box that starts unchecked
"Bool input True": ["bool", True], # This will be a check box that starts checked
# int examples https://wxpython.org/Phoenix/docs/html/wx.SpinCtrl.html
"Int input default": ["int"], # This will be an integer input with starting value 0
"Int input 10": [
"int",
10,
], # This will be an integer input with starting value 10 (or whatever you put in the second slot)
"Int input 10 bounded": [
"int",
10,
0,
20,
], # same as above but must be between the third and fourth values
# float examples https://wxpython.org/Phoenix/docs/html/wx.SpinCtrlDouble.html
"Float input default": [
"float"
], # This will be a float input with starting value 0.0
"Float input 10": [
"float",
10,
], # This will be a float input with starting value 10.0 (or whatever you put in the second slot)
"Float input 10 bounded": [
"float",
10,
0,
20,
], # same as above but must be between the third and fourth values
# string input examples https://wxpython.org/Phoenix/docs/html/wx.TextCtrl.html
"String input empty": [
"str"
], # This will be a text input with an empty starting value
"String input empty2": ["str", ""], # Same as the above
"String input hello": ["str", "hello"], # Text entry with starting value "hello"
# string choice examples https://wxpython.org/Phoenix/docs/html/wx.Choice.html
"Text choice": ["str_choice", "choice 1", "choice 2", "choice 3"],
# OS examples
"File Open picker": ["file_open"], # UI to pick an existing file, will be blank
"File Save picker": ["file_save"], # UI to pick a file to save to, will be blank
"Folder picker": ["directory"], # UI to pick a directory, will be blank
"File Open picker": ["file_open", path], # UI to pick an existing file with a path
"File Save picker": ["file_save", path], # UI to pick a file to save to with a path
"Folder picker": ["directory", path], # UI to pick a directory with a path
# UI to add a button and it will run the function_name() when clicked
"Button input": ["button", "button name", function_name],
}
def operation(
world: BaseLevel, dimension: Dimension, selection: SelectionGroup, options: dict
):
# When the user presses the run button this function will be run as normal but
# since the "options" key was defined in export this function will get another
# input in the form of a dictionary where the keys are the same as you defined
# them in the options dictionary above and the values are what the user picked
# in the UI (bool, int, float, str)
# If "options" is not defined in export this will just be an empty dictionary
pass
export = {
"name": "Fixed Function Pipeline Example 3",
"operation": operation,
"options": operation_options, # The options you defined above should be added here to show in the UI
}
|
Amulet-Map-Editor
|
amulet_map_editor\programs\edit\plugins\operations\examples\__init__.py
| |
Amulet-Map-Editor
|
amulet_map_editor\programs\edit\plugins\operations\stock_plugins\__init__.py
| |
Amulet-Map-Editor
|
amulet_map_editor\programs\edit\plugins\operations\stock_plugins\export_operations\construction.py
|
from typing import TYPE_CHECKING
import wx
import os
from amulet.api.selection import SelectionGroup
from amulet.api.errors import ChunkLoadError
from amulet.api.data_types import Dimension, OperationReturnType
from amulet.level.formats.construction import ConstructionFormatWrapper
from amulet_map_editor.api.wx.ui.version_select import VersionSelect
from amulet_map_editor.programs.edit.api.operations import (
SimpleOperationPanel,
OperationError,
)
if TYPE_CHECKING:
from amulet.api.level import BaseLevel
from amulet_map_editor.programs.edit.api.canvas import EditCanvas
class ExportConstruction(SimpleOperationPanel):
def __init__(
self,
parent: wx.Window,
canvas: "EditCanvas",
world: "BaseLevel",
options_path: str,
):
SimpleOperationPanel.__init__(self, parent, canvas, world, options_path)
options = self._load_options({})
self._file_picker = wx.FilePickerCtrl(
self,
path=options.get("path", ""),
wildcard="Construction file (*.construction)|*.construction",
style=wx.FLP_USE_TEXTCTRL | wx.FLP_SAVE | wx.FLP_OVERWRITE_PROMPT,
)
self._sizer.Add(self._file_picker, 0, wx.ALL | wx.CENTER, 5)
self._version_define = VersionSelect(
self,
world.translation_manager,
options.get("platform", None) or world.level_wrapper.platform,
allow_universal=False,
)
self._sizer.Add(self._version_define, 0, wx.CENTRE, 5)
self._add_run_button("Export")
self.Layout()
def disable(self):
self._save_options(
{
"path": self._file_picker.GetPath(),
"platform": self._version_define.platform,
"version": self._version_define.version_number,
}
)
def _operation(
self, world: "BaseLevel", dimension: Dimension, selection: SelectionGroup
) -> OperationReturnType:
path = self._file_picker.GetPath()
platform = self._version_define.platform
version = self._version_define.version_number
if isinstance(path, str) and platform and version:
wrapper = ConstructionFormatWrapper(path)
if wrapper.exists:
response = wx.MessageDialog(
self,
f"A file is already present at {path}. Do you want to continue?",
style=wx.YES | wx.NO,
).ShowModal()
if response == wx.ID_CANCEL:
return
wrapper.create_and_open(platform, version, selection, True)
wrapper.translation_manager = world.translation_manager
wrapper_dimension = wrapper.dimensions[0]
chunk_count = len(list(selection.chunk_locations()))
yield 0, f"Exporting {os.path.basename(path)}"
for chunk_index, (cx, cz) in enumerate(selection.chunk_locations()):
try:
chunk = world.get_chunk(cx, cz, dimension)
wrapper.commit_chunk(chunk, wrapper_dimension)
except ChunkLoadError:
continue
yield (chunk_index + 1) / chunk_count
wrapper.save()
wrapper.close()
else:
raise OperationError(
"Please specify a save location and version in the options before running."
)
export = {
"name": "\tExport Construction", # the name of the plugin
"operation": ExportConstruction, # the UI class to display
}
|
Amulet-Map-Editor
|
amulet_map_editor\programs\edit\plugins\operations\stock_plugins\export_operations\mcstructure.py
|
from typing import TYPE_CHECKING
import wx
import os
from amulet.api.selection import SelectionGroup
from amulet.api.errors import ChunkLoadError
from amulet.api.data_types import Dimension, OperationReturnType
from amulet.level.formats.mcstructure import MCStructureFormatWrapper
from amulet_map_editor.api.wx.ui.version_select import VersionSelect
from amulet_map_editor.programs.edit.api.operations import (
SimpleOperationPanel,
OperationError,
)
if TYPE_CHECKING:
from amulet.api.level import BaseLevel
from amulet_map_editor.programs.edit.api.canvas import EditCanvas
class ExportMCStructure(SimpleOperationPanel):
def __init__(
self,
parent: wx.Window,
canvas: "EditCanvas",
world: "BaseLevel",
options_path: str,
):
SimpleOperationPanel.__init__(self, parent, canvas, world, options_path)
options = self._load_options({})
self._file_picker = wx.FilePickerCtrl(
self,
path=options.get("path", ""),
wildcard="mcstructure file (*.mcstructure)|*.mcstructure",
style=wx.FLP_USE_TEXTCTRL | wx.FLP_SAVE | wx.FLP_OVERWRITE_PROMPT,
)
self._sizer.Add(self._file_picker, 0, wx.ALL | wx.CENTER, 5)
self._version_define = VersionSelect(
self,
world.translation_manager,
options.get("platform", None) or world.level_wrapper.platform,
allowed_platforms=("bedrock",),
allow_numerical=False,
)
self._sizer.Add(self._version_define, 0, wx.CENTRE, 5)
self._add_run_button("Export")
self.Layout()
def disable(self):
self._save_options(
{
"path": self._file_picker.GetPath(),
"version": self._version_define.version_number,
}
)
def _operation(
self, world: "BaseLevel", dimension: Dimension, selection: SelectionGroup
) -> OperationReturnType:
if len(selection.selection_boxes) == 0:
raise OperationError("No selection was given to export.")
elif len(selection.selection_boxes) != 1:
raise OperationError(
"The mcstructure format only supports a single selection box."
)
path = self._file_picker.GetPath()
version = self._version_define.version_number
if isinstance(path, str):
wrapper = MCStructureFormatWrapper(path)
if wrapper.exists:
response = wx.MessageDialog(
self,
f"A file is already present at {path}. Do you want to continue?",
style=wx.YES | wx.NO,
).ShowModal()
if response == wx.ID_CANCEL:
return
wrapper.create_and_open("bedrock", version, selection, True)
wrapper.translation_manager = world.translation_manager
wrapper_dimension = wrapper.dimensions[0]
chunk_count = len(list(selection.chunk_locations()))
yield 0, f"Exporting {os.path.basename(path)}"
for chunk_index, (cx, cz) in enumerate(selection.chunk_locations()):
try:
chunk = world.get_chunk(cx, cz, dimension)
wrapper.commit_chunk(chunk, wrapper_dimension)
except ChunkLoadError:
continue
yield (chunk_index + 1) / chunk_count
wrapper.save()
wrapper.close()
else:
raise OperationError(
"Please specify a save location and version in the options before running."
)
export = {
"name": "Export Bedrock .mcstructure", # the name of the plugin
"operation": ExportMCStructure, # the UI class to display
}
|
Amulet-Map-Editor
|
amulet_map_editor\programs\edit\plugins\operations\stock_plugins\export_operations\schematic.py
|
from typing import TYPE_CHECKING
import wx
import os
from amulet.api.selection import SelectionGroup
from amulet.api.errors import ChunkLoadError
from amulet.api.data_types import Dimension, OperationReturnType
from amulet.level.formats.schematic import SchematicFormatWrapper
from amulet_map_editor.api.wx.ui.version_select import PlatformSelect
from amulet_map_editor.programs.edit.api.operations import (
SimpleOperationPanel,
OperationError,
)
if TYPE_CHECKING:
from amulet.api.level import BaseLevel
from amulet_map_editor.programs.edit.api.canvas import EditCanvas
WarningMsg = """The Schematic format is a
legacy format that can only
save data in the numerical
format. Anything that was
added to the game in version
1.13 or after will not be
saved in the schematic file.
We suggest using the Construction
file format instead."""
class ExportSchematic(SimpleOperationPanel):
def __init__(
self,
parent: wx.Window,
canvas: "EditCanvas",
world: "BaseLevel",
options_path: str,
):
SimpleOperationPanel.__init__(self, parent, canvas, world, options_path)
options = self._load_options({})
self._file_picker = wx.FilePickerCtrl(
self,
path=options.get("path", ""),
wildcard="Schematic file (*.schematic)|*.schematic",
style=wx.FLP_USE_TEXTCTRL | wx.FLP_SAVE,
)
self._sizer.Add(self._file_picker, 0, wx.ALL | wx.CENTER, 5)
self._platform_define = PlatformSelect(
self,
world.translation_manager,
options.get("platform", None) or world.level_wrapper.platform,
allow_universal=False,
)
self._sizer.Add(self._platform_define, 0, wx.CENTRE, 5)
self._sizer.Add(
wx.StaticText(self, label=WarningMsg, style=wx.ALIGN_CENTRE_HORIZONTAL),
0,
wx.ALL | wx.CENTER,
5,
)
self._add_run_button("Export")
self.Layout()
def disable(self):
self._save_options(
{
"path": self._file_picker.GetPath(),
"platform": self._platform_define.platform,
}
)
def _operation(
self, world: "BaseLevel", dimension: Dimension, selection: SelectionGroup
) -> OperationReturnType:
if len(selection.selection_boxes) == 0:
raise OperationError("No selection was given to export.")
elif len(selection.selection_boxes) != 1:
raise OperationError(
"The schematic format only supports a single selection box."
)
path = self._file_picker.GetPath()
platform = self._platform_define.platform
if isinstance(path, str):
wrapper = SchematicFormatWrapper(path)
if wrapper.exists:
response = wx.MessageDialog(
self,
f"A file is already present at {path}. Do you want to continue?",
style=wx.YES | wx.NO,
).ShowModal()
if response == wx.ID_CANCEL:
return
wrapper.create_and_open(platform, (1, 12, 2), selection, True)
wrapper.translation_manager = world.translation_manager
wrapper_dimension = wrapper.dimensions[0]
chunk_count = len(list(selection.chunk_locations()))
yield 0, f"Exporting {os.path.basename(path)}"
for chunk_index, (cx, cz) in enumerate(selection.chunk_locations()):
try:
chunk = world.get_chunk(cx, cz, dimension)
wrapper.commit_chunk(chunk, wrapper_dimension)
except ChunkLoadError:
continue
yield (chunk_index + 1) / chunk_count
wrapper.save()
wrapper.close()
else:
raise OperationError(
"Please specify a save location and platform in the options before running."
)
export = {
"name": "Export Schematic (legacy)", # the name of the plugin
"operation": ExportSchematic, # the UI class to display
}
|
Amulet-Map-Editor
|
amulet_map_editor\programs\edit\plugins\operations\stock_plugins\export_operations\sponge_schematic.py
|
from typing import TYPE_CHECKING
import wx
import os
from amulet.api.selection import SelectionGroup
from amulet.api.errors import ChunkLoadError
from amulet.api.data_types import Dimension, OperationReturnType
from amulet.level.formats.sponge_schem import SpongeSchemFormatWrapper
from amulet_map_editor.api.wx.ui.version_select import VersionSelect
from amulet_map_editor.programs.edit.api.operations import (
SimpleOperationPanel,
OperationError,
)
if TYPE_CHECKING:
from amulet.api.level import BaseLevel
from amulet_map_editor.programs.edit.api.canvas import EditCanvas
class ExportSpongeSchematic(SimpleOperationPanel):
def __init__(
self,
parent: wx.Window,
canvas: "EditCanvas",
world: "BaseLevel",
options_path: str,
):
SimpleOperationPanel.__init__(self, parent, canvas, world, options_path)
options = self._load_options({})
self._file_picker = wx.FilePickerCtrl(
self,
path=options.get("path", ""),
wildcard="sponge schematic file (*.schem)|*.schem",
style=wx.FLP_USE_TEXTCTRL | wx.FLP_SAVE | wx.FLP_OVERWRITE_PROMPT,
)
self._sizer.Add(self._file_picker, 0, wx.ALL | wx.CENTER, 5)
self._version_define = VersionSelect(
self,
world.translation_manager,
options.get("platform", None) or world.level_wrapper.platform,
allowed_platforms=("java",),
allow_numerical=False,
)
self._sizer.Add(self._version_define, 0, wx.CENTRE, 5)
self._add_run_button("Export")
self.Layout()
def disable(self):
self._save_options(
{
"path": self._file_picker.GetPath(),
"version": self._version_define.version_number,
}
)
def _operation(
self, world: "BaseLevel", dimension: Dimension, selection: SelectionGroup
) -> OperationReturnType:
if len(selection.selection_boxes) == 0:
raise OperationError("No selection was given to export.")
elif len(selection.selection_boxes) != 1:
raise OperationError(
"The Sponge Schematic format only supports a single selection box."
)
path = self._file_picker.GetPath()
version = self._version_define.version_number
if isinstance(path, str):
wrapper = SpongeSchemFormatWrapper(path)
if wrapper.exists:
response = wx.MessageDialog(
self,
f"A file is already present at {path}. Do you want to continue?",
style=wx.YES | wx.NO,
).ShowModal()
if response == wx.ID_CANCEL:
return
wrapper.create_and_open("java", version, selection, True)
wrapper.translation_manager = world.translation_manager
wrapper_dimension = wrapper.dimensions[0]
chunk_count = len(list(selection.chunk_locations()))
yield 0, f"Exporting {os.path.basename(path)}"
for chunk_index, (cx, cz) in enumerate(selection.chunk_locations()):
try:
chunk = world.get_chunk(cx, cz, dimension)
wrapper.commit_chunk(chunk, wrapper_dimension)
except ChunkLoadError:
continue
yield (chunk_index + 1) / chunk_count
wrapper.save()
wrapper.close()
else:
raise OperationError(
"Please specify a save location and version in the options before running."
)
export = {
"name": "Export Sponge Schematic", # the name of the plugin
"operation": ExportSpongeSchematic, # the UI class to display
}
|
Amulet-Map-Editor
|
amulet_map_editor\programs\edit\plugins\operations\stock_plugins\export_operations\__init__.py
| |
Amulet-Map-Editor
|
amulet_map_editor\programs\edit\plugins\operations\stock_plugins\internal_operations\copy.py
|
from typing import TYPE_CHECKING
from amulet.api.structure import structure_cache
from amulet.api.data_types import Dimension
from amulet.api.selection import SelectionGroup
from amulet_map_editor.programs.edit.api.operations import (
OperationSilentAbort,
OperationError,
)
from amulet.api.data_types import OperationReturnType
if TYPE_CHECKING:
from amulet.api.level import BaseLevel
def copy(
world: "BaseLevel", dimension: Dimension, selection: SelectionGroup
) -> OperationReturnType:
if selection:
yield 0, "Copying"
structure = yield from world.extract_structure_iter(selection, dimension)
structure_cache.add_structure(structure, structure.dimensions[0])
raise OperationSilentAbort
else:
raise OperationError(
"At least one selection is required for the copy operation."
)
|
Amulet-Map-Editor
|
amulet_map_editor\programs\edit\plugins\operations\stock_plugins\internal_operations\cut.py
|
from typing import TYPE_CHECKING
from amulet.api.structure import structure_cache
from amulet.api.data_types import Dimension, OperationReturnType
from amulet.api.selection import SelectionGroup
from amulet_map_editor.programs.edit.plugins.operations.stock_plugins.internal_operations.delete import (
delete,
)
from amulet_map_editor.programs.edit.api.operations import OperationError
if TYPE_CHECKING:
from amulet.api.level import BaseLevel
def cut(
world: "BaseLevel", dimension: Dimension, selection: SelectionGroup
) -> OperationReturnType:
if selection:
structure = world.extract_structure(selection, dimension)
structure_cache.add_structure(structure, structure.dimensions[0])
yield from delete(
world,
dimension,
selection,
)
else:
raise OperationError(
"At least one selection is required for the copy operation."
)
|
Amulet-Map-Editor
|
amulet_map_editor\programs\edit\plugins\operations\stock_plugins\internal_operations\delete.py
|
from __future__ import annotations
from typing import TYPE_CHECKING
from amulet.api.selection import SelectionGroup
from amulet.api.block import UniversalAirBlock
from amulet.api.data_types import Dimension, OperationReturnType
if TYPE_CHECKING:
from amulet.api.level import BaseLevel
def delete(
world: "BaseLevel", dimension: Dimension, selection: SelectionGroup
) -> OperationReturnType:
internal_id = world.block_palette.get_add_block(UniversalAirBlock)
iter_count = len(list(world.get_coord_box(dimension, selection, False)))
count = 0
for chunk, slices, _ in world.get_chunk_slice_box(dimension, selection, False):
chunk.blocks[slices] = internal_id
chunk_x, chunk_z = chunk.coordinates
chunk_x *= 16
chunk_z *= 16
x_min = chunk_x + slices[0].start
y_min = slices[1].start
z_min = chunk_z + slices[2].start
x_max = chunk_x + slices[0].stop
y_max = slices[1].stop
z_max = chunk_z + slices[2].stop
for x, y, z in list(chunk.block_entities.keys()):
if x_min <= x < x_max and y_min <= y < y_max and z_min <= z < z_max:
chunk.block_entities.pop((x, y, z))
chunk.changed = True
count += 1
yield count / iter_count
|
Amulet-Map-Editor
|
amulet_map_editor\programs\edit\plugins\operations\stock_plugins\internal_operations\prune_chunks.py
|
from amulet.api.level import BaseLevel
from amulet.api.data_types import Dimension
from amulet.api.selection import SelectionGroup
from amulet.api.chunk import Chunk
def prune_chunks(
world: "BaseLevel",
dimension: Dimension,
selection: SelectionGroup,
load_original: bool = True,
):
chunks = world.all_chunk_coords(dimension).difference(selection.chunk_locations())
iter_count = len(chunks)
for count, (cx, cz) in enumerate(chunks):
world.delete_chunk(cx, cz, dimension)
if not load_original:
# this part is kind of hacky.
# Work out a propery API to do this.
key = dimension, cx, cz
if key not in world.chunks._history_database:
world.chunks._register_original_entry(key, Chunk(cx, cz))
yield (count + 1) / iter_count
|
Amulet-Map-Editor
|
amulet_map_editor\programs\edit\plugins\operations\stock_plugins\internal_operations\__init__.py
|
from .copy import copy
from .cut import cut
from .delete import delete
|
Amulet-Map-Editor
|
amulet_map_editor\programs\edit\plugins\operations\stock_plugins\operations\clone.py
|
"""
This license applies to this file only.
-- begin license --
MIT License
Copyright (c) 2021 Amulet-Team
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-- end license --
"""
from typing import TYPE_CHECKING
import wx
from amulet.api.selection import SelectionGroup
from amulet.api.data_types import Dimension, OperationReturnType
from amulet_map_editor.programs.edit.api.operations import (
SimpleOperationPanel,
OperationSilentAbort,
)
if TYPE_CHECKING:
from amulet.api.level import BaseLevel
from amulet_map_editor.programs.edit.api.canvas import EditCanvas
class Clone(SimpleOperationPanel):
def __init__(
self,
parent: wx.Window,
canvas: "EditCanvas",
world: "BaseLevel",
options_path: str,
):
SimpleOperationPanel.__init__(self, parent, canvas, world, options_path)
self._add_run_button()
self.Layout()
def _operation(
self, world: "BaseLevel", dimension: Dimension, selection: SelectionGroup
) -> OperationReturnType:
structure = world.extract_structure(selection, dimension)
self.canvas.paste(structure, structure.dimensions[0])
raise OperationSilentAbort
export = {
"name": "Clone", # the name of the plugin
"operation": Clone, # the actual function to call when running the plugin
}
|
Amulet-Map-Editor
|
amulet_map_editor\programs\edit\plugins\operations\stock_plugins\operations\fill.py
|
"""
This license applies to this file only.
-- begin license --
MIT License
Copyright (c) 2021 Amulet-Team
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-- end license --
"""
from typing import TYPE_CHECKING, Tuple
import wx
from amulet.api.selection import SelectionGroup
from amulet.api.block import Block
from amulet.api.data_types import Dimension, OperationReturnType
from amulet_map_editor.api.wx.ui.base_select import EVT_PICK
from amulet_map_editor.api.wx.ui.block_select import BlockDefine
from amulet_map_editor.programs.edit.api.operations import DefaultOperationUI
if TYPE_CHECKING:
from amulet.api.level import BaseLevel
from amulet_map_editor.programs.edit.api.canvas import EditCanvas
class Fill(wx.Panel, DefaultOperationUI):
def __init__(
self,
parent: wx.Window,
canvas: "EditCanvas",
world: "BaseLevel",
options_path: str,
):
wx.Panel.__init__(self, parent)
DefaultOperationUI.__init__(self, parent, canvas, world, options_path)
self.Freeze()
self._sizer = wx.BoxSizer(wx.VERTICAL)
self.SetSizer(self._sizer)
options = self._load_options({})
self._block_define = BlockDefine(
self,
world.translation_manager,
wx.VERTICAL,
*(options.get("fill_block_options", []) or [world.level_wrapper.platform]),
show_pick_block=True
)
self._block_define.Bind(EVT_PICK, self._on_pick_block_button)
self._sizer.Add(self._block_define, 1, wx.ALL | wx.ALIGN_CENTRE_HORIZONTAL, 5)
self._run_button = wx.Button(self, label="Run Operation")
self._run_button.Bind(wx.EVT_BUTTON, self._run_operation)
self._sizer.Add(self._run_button, 0, wx.ALL | wx.ALIGN_CENTRE_HORIZONTAL, 5)
self.Layout()
self.Thaw()
@property
def wx_add_options(self) -> Tuple[int, ...]:
return (1,)
def _on_pick_block_button(self, evt):
"""Set up listening for the block click"""
self._show_pointer = True
def _on_box_click(self):
if self._show_pointer:
self._show_pointer = False
x, y, z = self._pointer.pointer_base
self._block_define.universal_block = (
self.world.get_block(x, y, z, self.canvas.dimension),
None,
)
def _get_fill_block(self):
return self._block_define.universal_block[0]
def disable(self):
self._save_options(
{
"fill_block": self._get_fill_block(),
"fill_block_options": (
self._block_define.platform,
self._block_define.version_number,
self._block_define.force_blockstate,
self._block_define.namespace,
self._block_define.block_name,
self._block_define.properties,
),
}
)
def _run_operation(self, _):
self.canvas.run_operation(self._fill)
def _fill(self):
world = self.world
dimension = self.canvas.dimension
target_box = self.canvas.selection.selection_group
fill_block, block_entity = self._block_define.universal_block
internal_id = world.block_palette.get_add_block(fill_block)
iter_count = len(list(world.get_coord_box(dimension, target_box, True)))
count = 0
for chunk, slices, _ in world.get_chunk_slice_box(dimension, target_box, True):
chunk.blocks[slices] = internal_id
chunk_x, chunk_z = chunk.coordinates
chunk_x *= 16
chunk_z *= 16
x_min = chunk_x + slices[0].start
y_min = slices[1].start
z_min = chunk_z + slices[2].start
x_max = chunk_x + slices[0].stop
y_max = slices[1].stop
z_max = chunk_z + slices[2].stop
if block_entity is None:
for x, y, z in list(chunk.block_entities.keys()):
if x_min <= x < x_max and y_min <= y < y_max and z_min <= z < z_max:
chunk.block_entities.pop((x, y, z))
else:
for x in range(x_min, x_max):
for y in range(y_min, y_max):
for z in range(z_min, z_max):
chunk.block_entities[(x, y, z)] = block_entity
chunk.changed = True
count += 1
yield count / iter_count
export = {
"name": "Fill", # the name of the plugin
"operation": Fill, # the actual function to call when running the plugin
}
|
Amulet-Map-Editor
|
amulet_map_editor\programs\edit\plugins\operations\stock_plugins\operations\replace.py
|
"""
This license applies to this file only.
-- begin license --
MIT License
Copyright (c) 2021 Amulet-Team
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-- end license --
"""
from typing import TYPE_CHECKING, Tuple
import wx
import numpy
from amulet.api.block import Block
from amulet_map_editor.api.wx.ui.base_select import EVT_PICK
from amulet_map_editor.api.wx.ui.block_select import BlockDefine
from amulet_map_editor.api.wx.ui.simple import SimpleScrollablePanel
from amulet_map_editor.programs.edit.api.operations import DefaultOperationUI
if TYPE_CHECKING:
from amulet.api.level import BaseLevel
from amulet_map_editor.programs.edit.api.canvas import EditCanvas
class Replace(SimpleScrollablePanel, DefaultOperationUI):
def __init__(
self,
parent: wx.Window,
canvas: "EditCanvas",
world: "BaseLevel",
options_path: str,
):
SimpleScrollablePanel.__init__(self, parent)
DefaultOperationUI.__init__(self, parent, canvas, world, options_path)
self.Freeze()
options = self._load_options({})
self._original_block = BlockDefine(
self,
world.level_wrapper.translation_manager,
wx.VERTICAL,
*(
options.get("original_block_options", [])
or [world.level_wrapper.platform]
),
wildcard_properties=True,
show_pick_block=True
)
self._sizer.Add(self._original_block, 1, wx.ALL | wx.ALIGN_CENTRE_HORIZONTAL, 5)
self._original_block.Bind(EVT_PICK, lambda evt: self._on_pick_block_button(1))
self._replacement_block = BlockDefine(
self,
world.level_wrapper.translation_manager,
wx.VERTICAL,
*(
options.get("replacement_block_options", [])
or [world.level_wrapper.platform]
),
show_pick_block=True
)
self._sizer.Add(
self._replacement_block, 1, wx.ALL | wx.ALIGN_CENTRE_HORIZONTAL, 5
)
self._replacement_block.Bind(
EVT_PICK, lambda evt: self._on_pick_block_button(2)
)
self._run_button = wx.Button(self, label="Run Operation")
self._run_button.Bind(wx.EVT_BUTTON, self._run_operation)
self._sizer.Add(self._run_button, 0, wx.ALL | wx.ALIGN_CENTRE_HORIZONTAL, 5)
self.Layout()
self.Thaw()
@property
def wx_add_options(self) -> Tuple[int, ...]:
return (1,)
def _on_pick_block_button(self, code):
"""Set up listening for the block click"""
self._show_pointer = code
def _on_box_click(self):
if self._show_pointer:
x, y, z = self._pointer.pointer_base
if self._show_pointer == 1:
self._original_block.universal_block = (
self.world.get_block(x, y, z, self.canvas.dimension),
None,
)
elif self._show_pointer == 2:
self._replacement_block.universal_block = (
self.world.get_block(x, y, z, self.canvas.dimension),
None,
)
self._show_pointer = False
def _get_replacement_block(self) -> Block:
return self._replacement_block.universal_block[0]
def disable(self):
self._save_options(
{
"original_block_options": (
self._original_block.platform,
self._original_block.version_number,
self._original_block.force_blockstate,
self._original_block.namespace,
self._original_block.block_name,
self._original_block.str_properties,
),
"replacement_block": self._get_replacement_block(),
"replacement_block_options": (
self._replacement_block.platform,
self._replacement_block.version_number,
self._replacement_block.force_blockstate,
self._replacement_block.namespace,
self._replacement_block.block_name,
self._replacement_block.str_properties,
),
}
)
def _run_operation(self, _):
self.canvas.run_operation(self._replace)
def _replace(self):
world = self.world
selection = self.canvas.selection.selection_group
dimension = self.canvas.dimension
(
original_platform,
original_version,
original_blockstate,
original_namespace,
original_base_name,
original_properties,
) = (
self._original_block.platform,
self._original_block.version_number,
self._original_block.force_blockstate,
self._original_block.namespace,
self._original_block.block_name,
self._original_block.str_properties,
)
replacement_block, block_entity = self._replacement_block.universal_block
replacement_block_id = world.block_palette.get_add_block(replacement_block)
original_block_matches = []
universal_block_count = 0
iter_count = len(list(world.get_coord_box(dimension, selection)))
count = 0
for chunk, slices, _ in world.get_chunk_slice_box(dimension, selection):
if universal_block_count < len(world.block_palette):
for universal_block_id in range(
universal_block_count, len(world.block_palette)
):
version_block = world.translation_manager.get_version(
original_platform, original_version
).block.from_universal(
world.block_palette[universal_block_id],
force_blockstate=original_blockstate,
)[
0
]
if (
version_block.namespace == original_namespace
and version_block.base_name == original_base_name
and all(
original_properties.get(prop) in ["*", val.to_snbt()]
for prop, val in version_block.properties.items()
)
):
original_block_matches.append(universal_block_id)
universal_block_count = len(world.block_palette)
blocks = chunk.blocks[slices]
replace_mask = numpy.isin(blocks, original_block_matches)
blocks[replace_mask] = replacement_block_id
chunk.blocks[slices] = blocks
chunk_x, chunk_z = chunk.coordinates
chunk_x *= 16
chunk_z *= 16
x_min = chunk_x + slices[0].start
y_min = slices[1].start
z_min = chunk_z + slices[2].start
for dx, dy, dz in numpy.argwhere(replace_mask):
x = int(x_min * dx)
y = int(y_min * dy)
z = int(z_min * dz)
coord = (x, y, z)
if block_entity is not None:
chunk.block_entities[coord] = block_entity
elif coord in chunk.block_entities:
chunk.block_entities.pop(coord)
chunk.changed = True
count += 1
yield count / iter_count
def DoGetBestClientSize(self):
sizer = self.GetSizer()
if sizer is None:
return -1, -1
else:
sx, sy = self.GetSizer().CalcMin()
return (
sx + wx.SystemSettings.GetMetric(wx.SYS_VSCROLL_X),
sy + wx.SystemSettings.GetMetric(wx.SYS_HSCROLL_Y),
)
export = {
"name": "Replace", # the name of the plugin
"operation": Replace, # the actual function to call when running the plugin
}
|
Amulet-Map-Editor
|
amulet_map_editor\programs\edit\plugins\operations\stock_plugins\operations\set_biome.py
|
"""
This license applies to this file only.
-- begin license --
MIT License
Copyright (c) 2021 Amulet-Team
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-- end license --
"""
from typing import TYPE_CHECKING
import wx
import math
from amulet.utils import block_coords_to_chunk_coords
from amulet.api.chunk.biomes import BiomesShape
from amulet_map_editor.api.wx.ui.base_select import EVT_PICK
from amulet_map_editor.api.wx.ui.biome_select import BiomeDefine
from amulet_map_editor.programs.edit.api.operations import SimpleOperationPanel
from amulet_map_editor.api.wx.ui.simple import SimpleChoiceAny
if TYPE_CHECKING:
from amulet.api.level import BaseLevel
from amulet_map_editor.programs.edit.api.canvas import EditCanvas
from amulet.api.selection import SelectionGroup
from amulet.api.data_types import Dimension, OperationReturnType
BoxMode = "box"
ColumnMode = "column"
lang = {
ColumnMode: "Selected Column",
BoxMode: "Selected Box",
}
MODES = {
ColumnMode: "Set the biomes for the vertical column the selection intersects.",
BoxMode: "Set the biomes for only the blocks in the selection.",
}
Border = wx.TOP | wx.LEFT | wx.RIGHT | wx.EXPAND
class SetBiome(SimpleOperationPanel):
def __init__(
self,
parent: wx.Window,
canvas: "EditCanvas",
world: "BaseLevel",
options_path: str,
):
SimpleOperationPanel.__init__(self, parent, canvas, world, options_path)
self.Freeze()
options = self._load_options({})
self._mode = SimpleChoiceAny(self, sort=False)
self._mode.SetItems({mode: lang[mode] for mode in MODES.keys()})
self._sizer.Add(self._mode, 0, Border, 5)
self._mode.Bind(wx.EVT_CHOICE, self._on_mode_change)
self._mode_description = wx.TextCtrl(
self, style=wx.TE_MULTILINE | wx.TE_READONLY | wx.TE_BESTWRAP
)
self._sizer.Add(self._mode_description, 0, Border, 5)
self._mode_description.SetLabel(MODES[self._mode.GetCurrentObject()])
self._mode_description.Fit()
self._biome_choice = BiomeDefine(
self,
world.level_wrapper.translation_manager,
wx.VERTICAL,
*(
options.get("original_block_options", [])
or [world.level_wrapper.platform]
),
show_pick_biome=True,
)
self._biome_choice.Bind(EVT_PICK, self._on_pick_biome_button)
self._sizer.Add(self._biome_choice, 1, Border, 5)
self._add_run_button()
self.Thaw()
def _on_mode_change(self, evt):
self._mode_description.SetLabel(MODES[self._mode.GetCurrentObject()])
self._mode_description.Fit()
self.Layout()
evt.Skip()
def _on_pick_biome_button(self, evt):
"""Set up listening for the biome click"""
self._show_pointer = True
def _on_box_click(self):
if self._show_pointer:
self._show_pointer = False
x, y, z = self._pointer.pointer_base
# TODO: replace with "get_biome(x, y, z)" if it'll be created
cx, cz = block_coords_to_chunk_coords(
x, z, sub_chunk_size=self.world.sub_chunk_size
)
offset_x, offset_z = x - 16 * cx, z - 16 * cz
chunk = self.world.get_chunk(cx, cz, self.canvas.dimension)
if chunk.biomes.dimension == BiomesShape.Shape3D:
biome = chunk.biomes[offset_x // 4, y // 4, offset_z // 4]
elif chunk.biomes.dimension == BiomesShape.Shape2D:
biome = chunk.biomes[offset_x, offset_z]
else:
return
self._biome_choice.universal_biome = chunk.biome_palette[biome]
def _operation(
self, world: "BaseLevel", dimension: "Dimension", selection: "SelectionGroup"
) -> "OperationReturnType":
mode = self._mode.GetCurrentObject()
iter_count = len(list(world.get_coord_box(dimension, selection, False)))
for count, (chunk, slices, _) in enumerate(
world.get_chunk_slice_box(dimension, selection, False)
):
new_biome = chunk.biome_palette.get_add_biome(
self._biome_choice.universal_biome
)
if mode == BoxMode:
if chunk.biomes.dimension == BiomesShape.Shape3D:
slices = (
slice(slices[0].start // 4, math.ceil(slices[0].stop / 4)),
slice(slices[1].start // 4, math.ceil(slices[1].stop / 4)),
slice(slices[2].start // 4, math.ceil(slices[2].stop / 4)),
)
elif chunk.biomes.dimension == BiomesShape.Shape2D:
slices = (slices[0], slices[2])
else:
continue
elif mode == ColumnMode:
if chunk.biomes.dimension == BiomesShape.Shape3D:
bounds = world.bounds(dimension)
slices = (
slice(slices[0].start // 4, math.ceil(slices[0].stop / 4)),
# TODO this might cause issues with infinite height worlds. The biome handling needs a rewrite
slice(bounds.min_y // 4, math.ceil(bounds.max_y / 4)),
slice(slices[2].start // 4, math.ceil(slices[2].stop / 4)),
)
elif chunk.biomes.dimension == BiomesShape.Shape2D:
slices = (slices[0], slices[2])
else:
continue
else:
raise ValueError(
f"mode {mode} is not a valid mode for the Set Biome operation."
)
chunk.biomes[slices] = new_biome
chunk.changed = True
yield (count + 1) / iter_count
export = {
"name": "Set Biome", # the name of the plugin
"operation": SetBiome, # the actual function to call when running the plugin
}
|
Amulet-Map-Editor
|
amulet_map_editor\programs\edit\plugins\operations\stock_plugins\operations\waterlog.py
|
"""
This license applies to this file only.
-- begin license --
MIT License
Copyright (c) 2021 Amulet-Team
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-- end license --
"""
import numpy
from typing import TYPE_CHECKING, Tuple
import wx
from amulet_map_editor.api.wx.ui.base_select import EVT_PICK
from amulet_map_editor.api.wx.ui.simple import SimpleDialog
from amulet_map_editor.api.wx.ui.block_select import BlockDefine
from amulet_map_editor.programs.edit.api.operations import DefaultOperationUI
from amulet_map_editor.api import image
if TYPE_CHECKING:
from amulet.api.level import BaseLevel
from amulet_map_editor.programs.edit.api.canvas import EditCanvas
MODES = {
"Overlay": "Overlay the block on the existing. If the first block is air it replaces the first block otherwise it sets the second block.",
"Underlay": "Underlay the block on the existing. If the first block is not air it moves the first block to the second block. It then replaces the first block.",
"Normal Fill": "Replace all selected blocks with the chosen block.",
"Game Fill": "Fill like in game. Moves water blocks to the second block and replaces the first block. Useful for setting blocks in existing water.",
"Set First": "Set the first block leaving the second block as it was. If you want to change the first block without modifying the second block.",
"Set Second": 'Set the second block leaving the first block as it was. This can cause issues if the first block is air. You might prefer "Overlay"',
}
class Waterlog(wx.Panel, DefaultOperationUI):
def __init__(
self,
parent: wx.Window,
canvas: "EditCanvas",
world: "BaseLevel",
options_path: str,
):
wx.Panel.__init__(self, parent)
DefaultOperationUI.__init__(self, parent, canvas, world, options_path)
self.Freeze()
self._sizer = wx.BoxSizer(wx.VERTICAL)
self.SetSizer(self._sizer)
options = self._load_options({})
top_sizer = wx.BoxSizer(wx.HORIZONTAL)
self._sizer.Add(top_sizer, 0, wx.EXPAND | wx.ALL, 5)
help_button = wx.BitmapButton(
self, bitmap=image.icon.tablericons.help.bitmap(22, 22)
)
top_sizer.Add(help_button)
def on_button(evt):
dialog = SimpleDialog(self, "Extra block help.")
text = wx.TextCtrl(
dialog,
value="Blocks in the newer versions of Minecraft support having two blocks in the same location.\n"
"This is how the game is able to have water and blocks like fences at the same location.\n"
"In the example of waterlogged fences the fence is the first block and the water is the second. Unless it is water the second block is usually just visual.\n"
"In Java currently the second block is strictly water but in Bedrock there is no limit on what the second block can be.\n"
"It is not possible to set non-water second blocks in the game but this operation enables the use of that feature.\n"
"There are a number of different modes which can be selected at the top. A description of how it works will appear.",
style=wx.TE_MULTILINE | wx.TE_READONLY | wx.TE_BESTWRAP,
)
dialog.sizer.Add(text, 1, wx.EXPAND)
dialog.ShowModal()
evt.Skip()
help_button.Bind(wx.EVT_BUTTON, on_button)
self._mode = wx.Choice(self, choices=list(MODES.keys()))
self._mode.SetSelection(0)
top_sizer.Add(self._mode, 1, wx.EXPAND | wx.LEFT, 5)
self._mode.Bind(wx.EVT_CHOICE, self._on_mode_change)
self._mode_description = wx.TextCtrl(
self, style=wx.TE_MULTILINE | wx.TE_READONLY | wx.TE_BESTWRAP
)
self._sizer.Add(self._mode_description, 0, wx.EXPAND | wx.LEFT | wx.RIGHT, 5)
self._mode_description.SetLabel(
MODES[self._mode.GetString(self._mode.GetSelection())]
)
self._mode_description.Fit()
self._block_define = BlockDefine(
self,
world.level_wrapper.translation_manager,
wx.VERTICAL,
*(options.get("fill_block_options", []) or [world.level_wrapper.platform]),
show_pick_block=True
)
self._block_define.Bind(EVT_PICK, self._on_pick_block_button)
self._sizer.Add(self._block_define, 1, wx.ALL | wx.ALIGN_CENTRE_HORIZONTAL, 5)
self._run_button = wx.Button(self, label="Run Operation")
self._run_button.Bind(wx.EVT_BUTTON, self._run_operation)
self._sizer.Add(self._run_button, 0, wx.ALL | wx.ALIGN_CENTRE_HORIZONTAL, 5)
self.Layout()
self.Thaw()
@property
def wx_add_options(self) -> Tuple[int, ...]:
return (1,)
def _on_mode_change(self, evt):
self._mode_description.SetLabel(
MODES[self._mode.GetString(self._mode.GetSelection())]
)
self._mode_description.Fit()
self.Layout()
evt.Skip()
def _on_pick_block_button(self, evt):
"""Set up listening for the block click"""
self._show_pointer = True
def _on_box_click(self):
if self._show_pointer:
self._show_pointer = False
x, y, z = self._pointer.pointer_base
self._block_define.universal_block = (
self.world.get_block(x, y, z, self.canvas.dimension),
None,
)
def _get_fill_block(self):
return self._block_define.universal_block[0]
def disable(self):
self._save_options(
{
"fill_block": self._get_fill_block(),
"fill_block_options": (
self._block_define.platform,
self._block_define.version_number,
self._block_define.force_blockstate,
self._block_define.namespace,
self._block_define.block_name,
self._block_define.properties,
),
}
)
def _run_operation(self, _):
self.canvas.run_operation(lambda: self._waterlog())
def _waterlog(self):
mode = self._mode.GetString(self._mode.GetSelection())
waterlog_block = self._get_fill_block().base_block
world = self.world
selection = self.canvas.selection.selection_group
dimension = self.canvas.dimension
iter_count = len(list(world.get_coord_box(dimension, selection, True)))
count = 0
for chunk, slices, _ in world.get_chunk_slice_box(dimension, selection, True):
original_blocks = chunk.blocks[slices]
palette, blocks = numpy.unique(original_blocks, return_inverse=True)
blocks = blocks.reshape(original_blocks.shape)
if mode == "Overlay":
lut = numpy.array(
[
world.block_palette.get_add_block(
waterlog_block
if world.block_palette[block_id].namespaced_name
== "universal_minecraft:air"
else world.block_palette[block_id].base_block
+ waterlog_block # get the Block object for that id and add the user specified block
) # register the new block / get the numerical id if it was already registered
for block_id in palette
] # add the new id to the palette
)
elif mode == "Underlay":
lut = numpy.array(
[
world.block_palette.get_add_block(
waterlog_block
if world.block_palette[block_id].namespaced_name
== "universal_minecraft:air"
else waterlog_block
+ world.block_palette[ # get the Block object for that id and add the user specified block
block_id
].base_block
) # register the new block / get the numerical id if it was already registered
for block_id in palette
] # add the new id to the palette
)
elif mode == "Normal Fill":
lut = numpy.array(
[
world.block_palette.get_add_block(
waterlog_block
) # register the new block / get the numerical id if it was already registered
]
* len(palette) # add the new id to the palette
)
elif mode == "Game Fill":
lut = numpy.array(
[
world.block_palette.get_add_block(
waterlog_block + world.block_palette[block_id].base_block
if world.block_palette[block_id].namespaced_name
== "universal_minecraft:water"
else waterlog_block
) # register the new block / get the numerical id if it was already registered
for block_id in palette
] # add the new id to the palette
)
elif mode == "Set First":
lut = numpy.array(
[
world.block_palette.get_add_block(
waterlog_block
+ world.block_palette[block_id].extra_blocks[0]
if world.block_palette[block_id].extra_blocks
else waterlog_block
) # register the new block / get the numerical id if it was already registered
for block_id in palette
] # add the new id to the palette
)
elif mode == "Set Second":
lut = numpy.array(
[
world.block_palette.get_add_block(
world.block_palette[block_id].base_block + waterlog_block
) # register the new block / get the numerical id if it was already registered
for block_id in palette
] # add the new id to the palette
)
else:
raise Exception("hello")
chunk.blocks[slices] = lut[blocks]
chunk.changed = True
count += 1
yield count / iter_count
export = {
"name": "Waterlog", # the name of the plugin
"operation": Waterlog, # the actual function to call when running the plugin
}
|
Amulet-Map-Editor
|
amulet_map_editor\programs\edit\plugins\operations\stock_plugins\operations\__init__.py
| |
Angelica
|
dependencies.gradle
|
/*
* Add your dependencies here. Supported configurations:
* - api("group:name:version:classifier"): if you use the types from this dependency in the public API of this mod
* Available at runtime and compiletime for mods depending on this mod
* - implementation("g:n:v:c"): if you need this for internal implementation details of the mod, but none of it is visible via the public API
* Available at runtime but not compiletime for mods depending on this mod
* - compileOnly("g:n:v:c"): if the mod you're building doesn't need this dependency during runtime at all, e.g. for optional mods
* Not available at all for mods depending on this mod, only visible at compiletime for this mod
* - compileOnlyApi("g:n:v:c"): like compileOnly, but also visible at compiletime for mods depending on this mod
* Available at compiletime but not runtime for mods depending on this mod
* - runtimeOnlyNonPublishable("g:n:v:c"): if you want to include a mod in this mod's runClient/runServer runs, but not publish it as a dependency
* Not available at all for mods depending on this mod, only visible at runtime for this mod
* - devOnlyNonPublishable("g:n:v:c"): a combination of runtimeOnlyNonPublishable and compileOnly for dependencies present at both compiletime and runtime,
* but not published as Maven dependencies - useful for RFG-deobfuscated dependencies or local testing
* - runtimeOnly("g:n:v:c"): if you don't need this at compile time, but want it to be present at runtime
* Available at runtime for mods depending on this mod
* - annotationProcessor("g:n:v:c"): mostly for java compiler plugins, if you know you need this, use it, otherwise don't worry
* - testCONFIG("g:n:v:c") - replace CONFIG by one of the above (except api), same as above but for the test sources instead of main
*
* - shadowImplementation("g:n:v:c"): effectively the same as API, but the dependency is included in your jar under a renamed package name
* Requires you to enable usesShadowedDependencies in gradle.properties
*
* - compile("g:n:v:c"): deprecated, replace with "api" (works like the old "compile") or "implementation" (can be more efficient)
*
* You can exclude transitive dependencies (dependencies of the chosen dependency) by appending { transitive = false } if needed,
* but use this sparingly as it can break using your mod as another mod's dependency if you're not careful.
*
* To depend on obfuscated jars you can use `devOnlyNonPublishable(rfg.deobf("dep:spec:1.2.3"))` to fetch an obfuscated jar from maven,
* or `devOnlyNonPublishable(rfg.deobf(project.files("libs/my-mod-jar.jar")))` to use a file.
*
* Gradle names for some of the configuration can be misleading, compileOnlyApi and runtimeOnly both get published as dependencies in Maven, but compileOnly does not.
* The buildscript adds runtimeOnlyNonPublishable to also have a runtime dependency that's not published.
*
* For more details, see https://docs.gradle.org/8.0.1/userguide/java_library_plugin.html#sec:java_library_configurations_graph
*/
configurations {
transformedMod // Mods that can be transformed - used for compiling angelica, but not necessary at runtime
transformedMod.canBeConsumed = false
transformedModCompileOnly
transformedModCompileOnly.canBeConsumed = false
// Add the transformed mod dependencies to the compilation classpaths, but don't publish them in the Maven metadata
compileClasspath.extendsFrom(transformedMod, transformedModCompileOnly)
testCompileClasspath.extendsFrom(transformedMod, transformedModCompileOnly)
// Can be enabled for testing if desired
// runtimeClasspath.extendsFrom(transformedMod)
// testRuntimeClasspath.extendsFrom(transformedMod)
}
dependencies {
compileOnly("com.github.GTNewHorizons:Hodgepodge:2.7.14")
compileOnly("com.gtnewhorizons.retrofuturabootstrap:RetroFuturaBootstrap:1.0.7") { transitive = false }
compileOnly("org.projectlombok:lombok:1.18.34") { transitive = false }
annotationProcessor("org.projectlombok:lombok:1.18.34")
// Iris Shaders
compileOnly('org.jetbrains:annotations:26.0.2')
api("com.github.GTNewHorizons:GTNHLib:0.8.21:dev")
shadowImplementation("org.anarres:jcpp:1.4.14") // Apache 2.0
shadowImplementation("org.taumc:glsl-transformation-lib:0.2.0-25.g3a943bb") {
exclude module: "antlr4" // we only want to shadow the runtime module
}
shadowImplementation("org.antlr:antlr4-runtime:4.13.2")
compileOnly "org.apache.ant:ant:1.8.2"
// Because who doesn't want NEI
devOnlyNonPublishable('com.github.GTNewHorizons:NotEnoughItems:2.8.35-GTNH:dev')
devOnlyNonPublishable('com.github.GTNewHorizons:CodeChickenCore:1.4.7:dev')
// Notfine Deps
compileOnly("thaumcraft:Thaumcraft:1.7.10-4.2.3.5:dev")
devOnlyNonPublishable("com.github.GTNewHorizons:Baubles-Expanded:2.2.2-GTNH:dev")
compileOnly("com.github.GTNewHorizons:twilightforest:2.7.13:dev") { transitive = false }
compileOnly(rfg.deobf('curse.maven:witchery-69673:2234410'))
compileOnly("com.github.GTNewHorizons:TinkersConstruct:1.14.6-GTNH:dev") { transitive = false }
compileOnly("com.github.GTNewHorizons:Natura:2.8.9:dev")
compileOnly("com.github.GTNewHorizons:ThaumicHorizons:1.8.4:dev")
compileOnly("com.github.GTNewHorizons:Battlegear2:1.4.3:dev") { transitive = false }
compileOnly("com.falsepattern:chunkapi-mc1.7.10:0.5.1:api") { transitive = false }
compileOnly("com.falsepattern:endlessids-mc1.7.10:1.5-beta0003:dev") { transitive = false }
compileOnly(rfg.deobf("curse.maven:extrautils-225561:2264383"))
compileOnly(rfg.deobf("curse.maven:dynamiclights-227874:2337326"))
compileOnly("curse.maven:minefactory-reloaded-66672:2277486")
compileOnly("com.github.GTNewHorizons:NotEnoughIds:2.1.10:dev") // Mixin Version
compileOnly("com.github.GTNewHorizons:NotEnoughIds-Legacy:1.4.7:dev") // ASM Version
compileOnly(rfg.deobf("curse.maven:ntm-space-1121235:6974420"))
compileOnly(rfg.deobf("curse.maven:campfirebackport-387444:4611675"))
compileOnly(rfg.deobf("curse.maven:xaeros-minimap-263420:5060684"))
compileOnly(rfg.deobf("curse.maven:security-craft-64760:2818228"))
runtimeOnlyNonPublishable(rfg.deobf("CoreTweaks:CoreTweaks:0.3.3.2"))
// For testing alternative splash screens, can be sourced from https://github.com/MalTeeez/ModernSplash/releases
//runtimeOnly(rfg.deobf(files("dependencies/modernsplash-1.7.10-1.2.2-dev.jar")))
// Hodgepodge
transformedMod("net.industrial-craft:industrialcraft-2:2.2.828-experimental:dev")
// Better Crashes
compileOnly("com.github.GTNewHorizons:BetterCrashes:1.4.0-GTNH:dev")
afterEvaluate {
dependencies {
testImplementation(platform('org.junit:junit-bom:5.14.1'))
testImplementation('org.junit.jupiter:junit-jupiter')
testImplementation("org.mockito:mockito-core:3.+")
testImplementation("org.lwjgl.lwjgl:lwjgl:2.9.4-nightly-20150209")
// testAnnotationProcessor("com.github.GTNewHorizons:jabel-javac-plugin:1.0.2-GTNH") // Soon :tm:
testAnnotationProcessor("com.github.bsideup.jabel:jabel-javac-plugin:1.0.1")
testImplementation('org.junit.platform:junit-platform-engine')
testImplementation('org.junit.platform:junit-platform-reporting')
testImplementation('org.junit.platform:junit-platform-launcher')
}
}
compileOnly("mega:fluidlogged-mc1.7.10:0.1.2")
}
|
Angelica
|
repositories.gradle
|
// Add any additional repositories for your dependencies here
repositories {
maven {
name = 'mavenpattern'
url = 'https://mvn.falsepattern.com/releases'
content {
includeGroup 'com.falsepattern'
}
}
maven {
name = 'mega'
url = 'https://mvn.falsepattern.com/gtmega_releases/'
content {
includeGroup 'mega'
}
}
exclusiveContent {
forRepository {
ivy {
name = 'CoreTweaks releases'
url = 'https://github.com/makamys/CoreTweaks/releases/download/'
patternLayout {
artifact '[revision]/[module]-1.7.10-[revision]+nomixin(-[classifier])(.[ext])'
}
metadataSources {
artifact()
}
}
}
filter {
includeGroup('CoreTweaks')
}
}
maven {
name = 'taumc'
url = 'https://maven.taumc.org/releases'
content {
includeGroup 'org.taumc'
}
}
mavenLocal()
}
|
Angelica
|
src\main\resources\centerDepth.fsh
|
#version VERSIONPLACEHOLDER
// This will be removed by Iris if the system does not support GL3.
#define IS_GL3
uniform sampler2D depth;
uniform sampler2D altDepth;
uniform float lastFrameTime;
uniform float decay;
#ifdef IS_GL3
out float oculus_fragColor;
#endif
void main() {
float currentDepth = texture2D(depth, vec2(0.5)).r;
float decay2 = 1.0 - exp(-decay * lastFrameTime);
float oldDepth = texture2D(altDepth, vec2(0.5)).r;
#ifdef IS_GL3
if (isnan(oldDepth)) {
oldDepth = currentDepth;
}
oculus_fragColor = mix(oldDepth, currentDepth, decay2);
#else
if (oldDepth != oldDepth) { // cheap isNaN
oldDepth = currentDepth;
}
gl_FragColor = vec4(mix(texture2D(altDepth, vec2(0.5)).r, currentDepth, decay2), 0, 0, 0);
#endif
}
|
Angelica
|
src\main\resources\centerDepth.vsh
|
#version 120
void main() { gl_Position = ftransform(); }
|
Angelica
|
src\main\resources\mixins.angelica.early.json
|
{
"required": true,
"minVersion": "0.8.3-GTNH",
"package": "com.gtnewhorizons.angelica.mixins.early",
"refmap": "mixins.angelica.refmap.json",
"target": "@env(DEFAULT)",
"injectors":{
"maxShiftBy": 2
},
"compatibilityLevel": "JAVA_8"
}
|
Angelica
|
src\main\resources\mixins.angelica.json
|
{
"required": true,
"minVersion": "0.8.3-GTNH",
"refmap": "mixins.angelica.refmap.json",
"target": "@env(DEFAULT)",
"compatibilityLevel": "JAVA_8"
}
|
Angelica
|
src\main\resources\mixins.angelica.late.json
|
{
"required": true,
"minVersion": "0.8.3-GTNH",
"package": "com.gtnewhorizons.angelica.mixins.late",
"refmap": "mixins.angelica.refmap.json",
"target": "@env(DEFAULT)",
"compatibilityLevel": "JAVA_8"
}
|
Angelica
|
src\main\resources\rubidium.mixins.json
|
{
"package": "me.jellysquid.mods.sodium.mixin",
"required": true,
"minVersion": "0.0.0",
"compatibilityLevel": "JAVA_8",
"plugin": "me.jellysquid.mods.sodium.mixin.SodiumMixinPlugin",
"refmap": "embeddium-refmap.json",
"injectors": {
"defaultRequire": 1
},
"overwrites": {
"conformVisibility": true
},
"client": [
"core.MixinDirection",
"core.frustum.MixinFrustum",
"core.matrix.MixinMatrix3f",
"core.matrix.MixinMatrix4f",
"core.matrix.MixinGameRenderer",
"core.model.MixinBlockColors",
"core.model.MixinItemColors",
"core.pipeline.MixinBakedQuad",
"core.pipeline.MixinBufferBuilder",
"core.pipeline.MixinVertexConsumer",
"core.pipeline.MixinVertexFormat",
"features.block.MixinBlockModelRenderer",
"features.block.MixinWorldRenderer",
"features.buffer_builder.fast_advance.MixinBufferBuilder",
"features.buffer_builder.fast_advance.MixinVertexFormat",
"features.buffer_builder.fast_sort.MixinBufferBuilder",
"features.buffer_builder.intrinsics.MixinBufferBuilder",
"features.buffer_builder.intrinsics.MixinSpriteTexturedVertexConsumer",
"features.buffer_builder.intrinsics.MixinWorldRenderer",
"features.chunk_rendering.MixinChunkBuilder",
"features.chunk_rendering.MixinClientChunkManager",
"features.chunk_rendering.MixinClientChunkManager$MixinClientChunkMap",
"features.chunk_rendering.MixinClientWorld",
"features.chunk_rendering.MixinPalettedContainer",
"features.chunk_rendering.MixinWorldRenderer",
"features.chunk_rendering.MixinPackedIntegerArray",
"features.chunk_rendering.MixinRenderLayer",
"features.debug.MixinDebugHud",
"features.entity.fast_render.MixinCuboid",
"features.entity.fast_render.MixinModelPart",
"features.entity.smooth_lighting.MixinEntityRenderer",
"features.entity.smooth_lighting.MixinPaintingEntityRenderer",
"features.gui.MixinDebugHud",
"features.gui.fast_loading_screen.MixinLevelLoadingScreen",
"features.gui.fast_status_bars.MixinInGameHud",
"features.gui.fast_fps_pie.MixinMinecraftClient",
"features.gui.font.MixinGlyphRenderer",
"features.item.MixinItemRenderer",
"features.matrix_stack.MixinMatrixStack",
"features.matrix_stack.MixinVertexConsumer",
"features.model.MixinMultipartBakedModel",
"features.model.MixinWeightedBakedModel",
"features.optimized_bamboo.MixinBambooBlock",
"features.options.MixinGameOptions",
"features.options.MixinInGameHud",
"features.options.MixinMinecraftClient",
"features.options.MixinOptionsScreen",
"features.options.MixinWorldRenderer",
"features.particle.fast_render.MixinBillboardParticle",
"features.render_layer.leaves.MixinRenderLayers",
"features.render_layer.leaves.MixinLeavesBlock",
"features.sky.MixinWorldRenderer",
"features.texture_tracking.MixinSprite",
"features.texture_tracking.MixinSpriteAtlasTexture",
"features.texture_tracking.MixinSpriteBillboardParticle",
"features.world_ticking.MixinClientWorld",
"features.fast_biome_colors.MixinBackgroundRenderer",
"features.fast_biome_colors.MixinBlock",
"features.fast_biome_colors.MixinFluid"
]
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\AngelicaLateMixins.java
|
package com.gtnewhorizons.angelica;
import com.gtnewhorizon.gtnhmixins.ILateMixinLoader;
import com.gtnewhorizon.gtnhmixins.LateMixin;
import com.gtnewhorizon.gtnhmixins.builders.IMixins;
import com.gtnewhorizons.angelica.mixins.Mixins;
import java.util.List;
import java.util.Set;
@LateMixin
public class AngelicaLateMixins implements ILateMixinLoader {
@Override
public String getMixinConfig() {
return "mixins.angelica.late.json";
}
@Override
public List<String> getMixins(Set<String> loadedMods) {
return IMixins.getLateMixins(Mixins.class, loadedMods);
}
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\AngelicaMod.java
|
package com.gtnewhorizons.angelica;
import static com.gtnewhorizons.angelica.AngelicaMod.MOD_ID;
import com.gtnewhorizons.angelica.common.BlockError;
import com.gtnewhorizons.angelica.compat.ModStatus;
import com.gtnewhorizons.angelica.proxy.CommonProxy;
import com.gtnewhorizons.angelica.utils.AnimationMode;
import com.gtnewhorizons.angelica.utils.ManagedEnum;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
@Mod(
modid = MOD_ID,
name = "Angelica",
version = Tags.VERSION,
dependencies = """
required-after:gtnhlib@[0.8.21,);\
before:lwjgl3ify@[1.5.3,);\
after:hodgepodge@[2.4.4,);\
after:CodeChickenCore@[1.2.0,);\
after:archaicfix@[0.7.0,);\
""",
acceptedMinecraftVersions = "[1.7.10]",
acceptableRemoteVersions = "*",
guiFactory = "com.gtnewhorizons.angelica.config.AngelicaGuiConfigFactory")
public class AngelicaMod {
public static final String MOD_ID = "angelica";
@SidedProxy(clientSide = "com.gtnewhorizons.angelica.proxy.ClientProxy", serverSide = "com.gtnewhorizons.angelica.proxy.CommonProxy")
public static CommonProxy proxy;
public static final boolean lwjglDebug = Boolean.parseBoolean(System.getProperty("org.lwjgl.util.Debug", "false"));
public static final ManagedEnum<AnimationMode> animationsMode = new ManagedEnum<>(AnimationMode.VISIBLE_ONLY);
public static BlockError blockError;
@Mod.EventHandler
public void preInit(FMLPreInitializationEvent event) {
ModStatus.preInit();
proxy.preInit(event);
blockError = new BlockError();
}
@Mod.EventHandler
public void init(FMLInitializationEvent event) {
proxy.init(event);
}
@Mod.EventHandler
public void postInit(FMLPostInitializationEvent event) {
proxy.postInit(event);
}
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\api\IBlockAccessExtended.java
|
package com.gtnewhorizons.angelica.api;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
public interface IBlockAccessExtended extends IBlockAccess {
World getWorld();
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\api\IDynamicLightProducer.java
|
package com.gtnewhorizons.angelica.api;
/**
* To be used for modded items that don't have blocks. Baubles for example.
*/
public interface IDynamicLightProducer {
int getLuminance();
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\api\TextureServices.java
|
package com.gtnewhorizons.angelica.api;
import com.gtnewhorizons.angelica.mixins.interfaces.IPatchedTextureAtlasSprite;
import com.gtnewhorizons.angelica.mixins.interfaces.ITexturesCache;
import net.minecraft.client.renderer.RenderBlocks;
import net.minecraft.util.IIcon;
/**
* Exposes a method to the API that allow mods to add texture update compat
*/
@SuppressWarnings("unused")
public class TextureServices {
@SuppressWarnings("unused")
public static void updateBlockTextureAnimation(IIcon icon, RenderBlocks renderBlocks) {
if (renderBlocks instanceof ITexturesCache texturesCache) {
texturesCache.getRenderedTextures().add(icon);
}
}
@SuppressWarnings("unused")
public static void updateTextureAnimation(IIcon icon) {
if(icon instanceof IPatchedTextureAtlasSprite patchedSprite) {
patchedSprite.markNeedsAnimationUpdate();
}
}
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\api\ThreadSafeISBRH.java
|
package com.gtnewhorizons.angelica.api;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* Marks an ISBRH as thread-safe, allowing Angelica to run it off-thread.
*
* <p>Note: Any tessellator access <i>must</i> be done within the methods of the ISBRH and not cached in the class.</p>
*/
@Documented
@Target({ TYPE })
@Retention(RUNTIME)
public @interface ThreadSafeISBRH {
/**
* Specifies whether Angelica should create a thread local instance of the class for each thread.
* <ul>
* <li>If this is set to <tt>true</tt>, a new instance will be created using the default constructor on each thread.</li>
* <ul>
* <li>Note: If your renderer requires arguments to the constructor, do <i>not</i> use this annotation;
* instead use the {@link ThreadSafeISBRHFactory} interface and implement the {@link ThreadSafeISBRHFactory#newInstance} method. </li>
* </ul>
* <li>If this is set to <tt>false</tt>, the main thread instance will be used on all threads.
* Use this option if your renderer class has no state, and can be safely used from multiple threads as is.</li>
* <ul>
* <li>No state/non final variables should be stored in the ISBRH as it is not guaranteed to be thread safe.</li>
* </ul>
* </ul>
*/
boolean perThread();
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\api\ThreadSafeISBRHFactory.java
|
package com.gtnewhorizons.angelica.api;
import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler;
/**
* Marks an ISBRH as thread-safe using a thread local instance, allowing Angelica to run it off-thread.
* Use this when your ISBRH uses a non-default constructor.
* <p>To avoid a hard dependency on Angelica, you will likely want to mark this as an optional interface using:</p>
* <pre>
* @Optional.Interface(modid = "angelica", iface = "com.gtnewhorizons.angelica.api.ThreadSafeISBRHFactory")
* </pre>
*
* <p><b>Notes</b></p>
* <ul>
* <li>Any tessellator access <i>must</i> be done within the methods of the ISBRH and not cached in the class.</li>
* <li>If your class uses a default constructor or is thread-safe by default, consider using the simpler {@link ThreadSafeISBRH}
* annotation instead.
* </ul>
*/
public interface ThreadSafeISBRHFactory extends ISimpleBlockRenderingHandler {
ThreadSafeISBRHFactory newInstance();
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\common\BlockError.java
|
package com.gtnewhorizons.angelica.common;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.util.IIcon;
import net.minecraftforge.client.event.TextureStitchEvent;
import net.minecraftforge.common.MinecraftForge;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
/**
* This Block is not actually getting registered. A static instance is created in AngelicaMod.
* Actually registering the block on the client but not the server can cause block IDs to
* different between client/server, which is not good.
* We're essentially injecting the block's texture, so that we may use this block as if it were
* any normal block for rendering purposes with RenderBlocks and such, but not have to actually
* register it as a block.
*/
public class BlockError extends Block {
public static final IIcon[] icons = new IIcon[2];
public BlockError() {
super(Material.rock);
MinecraftForge.EVENT_BUS.register(new EventHandler());
}
@Override
@SideOnly(Side.CLIENT)
public IIcon getIcon(int side, int meta) {
return meta >= 0 && meta < icons.length ? icons[meta] : null;
}
public static class EventHandler{
@SubscribeEvent
@SideOnly(Side.CLIENT)
public void onTextureStitch(TextureStitchEvent.Pre event) {
if (event.map.getTextureType() == 0) {
for (int i = 0; i < icons.length; i++) {
icons[i] = event.map.registerIcon("angelica:error_block_" + i);
}
}
}
}
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\common\BlockTest.java
|
package com.gtnewhorizons.angelica.common;
import static com.gtnewhorizon.gtnhlib.client.model.ModelISBRH.JSON_ISBRH_ID;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
import org.jetbrains.annotations.NotNull;
/// Unline {@link BlockError}, this *is* registered on both sides. It's intended to test functionality in a SP
/// development environment.
public class BlockTest extends Block {
public BlockTest() {
super(Material.wood);
setHardness(0.7f);
}
@Override
public boolean isOpaqueCube() {
return false;
}
/**
* Called when a block is placed using its ItemBlock. Args: World, X, Y, Z, side, hitX, hitY, hitZ, block metadata
*/
@Override
public int onBlockPlaced(@NotNull World worldIn, int x, int y, int z, int side, float subX, float subY, float subZ, int meta) {
// Face NORTH if placed up or down
final var s = ForgeDirection.getOrientation(side);
if (s == ForgeDirection.UP || s == ForgeDirection.DOWN)
return 2;
// Face the placed side
return side;
}
@Override
public int getRenderType() {
return JSON_ISBRH_ID;
}
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\compat\ExtendedBlockStorageExt.java
|
package com.gtnewhorizons.angelica.compat;
import com.falsepattern.chunk.api.DataRegistry;
import com.gtnewhorizons.neid.mixins.interfaces.IExtendedBlockStorageMixin;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.chunk.NibbleArray;
import net.minecraft.world.chunk.storage.ExtendedBlockStorage;
import ru.fewizz.idextender.Hooks;
public class ExtendedBlockStorageExt extends ExtendedBlockStorage {
public boolean hasSky;
public ExtendedBlockStorageExt(int yBase, boolean hasSky) {
super(yBase, hasSky);
this.hasSky = hasSky;
}
public ExtendedBlockStorageExt(Chunk chunk, ExtendedBlockStorage storage) {
super(storage.yBase, storage.getSkylightArray() != null);
if (ModStatus.isChunkAPILoaded) {
if (storage.getSkylightArray() != null) {
hasSky = true;
}
DataRegistry.cloneSubChunk(chunk, storage, this);
} else {
int arrayLen;
if (ModStatus.isNEIDLoaded){
final short[] block16BArray = ((IExtendedBlockStorageMixin)(Object)this).getBlock16BArray();
System.arraycopy(((IExtendedBlockStorageMixin)(Object)storage).getBlock16BArray(), 0, block16BArray, 0, block16BArray.length);
if(storage.getBlockMSBArray() != null) {
this.setBlockMSBArray(new NibbleArray(block16BArray.length, 4));
copyNibbleArray(storage.getBlockMSBArray(), this.getBlockMSBArray());
}
arrayLen = block16BArray.length;
if (ModStatus.isNEIDMetadataExtended) {
final short[] block16BMetaArray = ((IExtendedBlockStorageMixin)(Object)this).getBlock16BMetaArray();
System.arraycopy(((IExtendedBlockStorageMixin)(Object)storage).getBlock16BMetaArray(), 0, block16BMetaArray, 0, block16BMetaArray.length);
}
}
else if (ModStatus.isOldNEIDLoaded){
final short[] blockLSBArray = Hooks.get(this);
System.arraycopy(Hooks.get(storage), 0, blockLSBArray, 0, blockLSBArray.length);
// getBlockMSBArray is nuked in asm version
arrayLen = blockLSBArray.length;
}
else {
final byte[] blockLSBArray = this.getBlockLSBArray();
System.arraycopy(storage.getBlockLSBArray(), 0, blockLSBArray, 0, blockLSBArray.length);
if(storage.getBlockMSBArray() != null) {
this.setBlockMSBArray(new NibbleArray(blockLSBArray.length, 4));
copyNibbleArray(storage.getBlockMSBArray(), this.getBlockMSBArray());
}
arrayLen = blockLSBArray.length;
}
if (!ModStatus.isNEIDMetadataExtended) copyNibbleArray(storage.getMetadataArray(), this.getMetadataArray());
copyNibbleArray(storage.getBlocklightArray(), this.getBlocklightArray());
if(storage.getSkylightArray() != null) {
hasSky = true;
if(this.getSkylightArray() == null) {
this.setSkylightArray(new NibbleArray(arrayLen, 4));
}
copyNibbleArray(storage.getSkylightArray(), this.getSkylightArray());
}
}
this.blockRefCount = storage.blockRefCount;
}
private static void copyNibbleArray(NibbleArray srcArray, NibbleArray dstArray) {
if (srcArray == null || dstArray == null) {
throw new RuntimeException("NibbleArray is null src: " + (srcArray == null) + " dst: " + (dstArray == null));
}
final byte[] data = srcArray.data;
System.arraycopy(data, 0, dstArray.data, 0, data.length);
}
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\compat\ModStatus.java
|
package com.gtnewhorizons.angelica.compat;
import com.gtnewhorizons.angelica.compat.backhand.BackhandReflectionCompat;
import com.gtnewhorizons.angelica.helpers.LoadControllerHelper;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.versioning.DefaultArtifactVersion;
import mods.battlegear2.Battlegear;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class ModStatus {
public static final Logger LOGGER = LogManager.getLogger("ModCompat");
public static BackhandReflectionCompat backhandCompat;
/**
* Mixin Version
*/
public static boolean isNEIDLoaded;
/**
* ASM Version
*/
public static boolean isOldNEIDLoaded;
public static boolean isBetterCrashesLoaded;
public static boolean isNEIDMetadataExtended;
public static boolean isLotrLoaded;
public static boolean isChunkAPILoaded;
public static boolean isEIDBiomeLoaded;
public static boolean isXaerosMinimapLoaded;
public static boolean isHoloInventoryLoaded;
public static boolean isBattlegearLoaded;
public static boolean isBackhandLoaded;
public static boolean isThaumcraftLoaded;
public static boolean isThaumicHorizonsLoaded;
public static boolean isBaublesLoaded;
public static boolean isFluidLoggedLoaded;
public static void preInit(){
isBackhandLoaded = Loader.isModLoaded("backhand");
if(isBackhandLoaded) {
isBackhandLoaded = BackhandReflectionCompat.isBackhandLoaded();
}
isBetterCrashesLoaded = Loader.isModLoaded("bettercrashes");
isNEIDLoaded = Loader.isModLoaded("neid");
isOldNEIDLoaded = Loader.isModLoaded("notenoughIDs");
isLotrLoaded = Loader.isModLoaded("lotr");
isChunkAPILoaded = Loader.isModLoaded("chunkapi");
isEIDBiomeLoaded = Loader.isModLoaded("endlessids_biome");
isXaerosMinimapLoaded = Loader.isModLoaded("XaeroMinimap");
isHoloInventoryLoaded = Loader.isModLoaded("holoinventory");
isBattlegearLoaded = Loader.isModLoaded("battlegear2");
isThaumcraftLoaded = Loader.isModLoaded("Thaumcraft");
isThaumicHorizonsLoaded = Loader.isModLoaded("ThaumicHorizons");
isBaublesLoaded = Loader.isModLoaded("Baubles");
isFluidLoggedLoaded = Loader.isModLoaded("fluidlogged");
isHoloInventoryLoaded = Loader.isModLoaded("holoinventory");
// remove compat with original release of BG2
if (isBattlegearLoaded){
isBattlegearLoaded = new DefaultArtifactVersion("1.2.0")
.compareTo(
LoadControllerHelper.getOwningMod(Battlegear.class).getProcessedVersion()
) <= 0;
}
isNEIDMetadataExtended = false;
if (isNEIDLoaded) {
final int majorVersion = Integer.parseInt(Loader.instance().getIndexedModList().get("neid").getVersion().split("\\.")[0]);
if (majorVersion >= 2) {
isNEIDMetadataExtended = true;
}
}
}
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\config\AngelicaConfig.java
|
package com.gtnewhorizons.angelica.config;
import com.gtnewhorizon.gtnhlib.config.Config;
@Config(modid = "angelica", filename = "angelica-modules")
public class AngelicaConfig {
@Config.Comment("Enable Sodium rendering")
@Config.DefaultBoolean(true)
@Config.RequiresMcRestart
public static boolean enableSodium;
@Config.Comment("Enable NotFine Options")
@Config.DefaultBoolean(false)
public static boolean enableNotFineOptions;
@Config.Comment("Enable Reese's Sodium Options")
@Config.DefaultBoolean(true)
public static boolean enableReesesSodiumOptions;
@Config.Comment("Enable Sodium fluid rendering [Experimental]")
@Config.DefaultBoolean(false)
@Config.RequiresMcRestart
public static boolean enableSodiumFluidRendering;
@Config.Comment("Inject BakedModel rendering into some vanilla blocks")
@Config.DefaultBoolean(false)
@Config.RequiresMcRestart
public static boolean injectQPRendering;
@Config.Comment("Enable Angelica's test blocks")
@Config.DefaultBoolean(false)
@Config.Ignore()
public static boolean enableTestBlocks;
@Config.Comment("Enable Iris Shaders [Requires Sodium]")
@Config.DefaultBoolean(true)
@Config.RequiresMcRestart
public static boolean enableIris;
@Config.Comment("Enable MCPatcherForge features, still in Alpha. Individual features are toggled in mcpatcher.json")
@Config.DefaultBoolean(true)
@Config.RequiresMcRestart
public static boolean enableMCPatcherForgeFeatures;
@Config.Comment("Replace cloud renderer with a VBO version.")
@Config.DefaultBoolean(true)
@Config.RequiresMcRestart
public static boolean enableVBOClouds;
@Config.Comment("Uses cached attributes for VBO rendering, resulting in less CPU overhead. Disable if you notice any graphical issues.")
@Config.DefaultBoolean(true)
@Config.RequiresMcRestart
public static boolean enableVAO;
@Config.Comment("Enable NotFine features")
@Config.DefaultBoolean(true)
@Config.RequiresMcRestart
public static boolean enableNotFineFeatures;
@Config.Comment("Tweak F3 screen to be closer to modern versions. [From ArchaicFix]")
@Config.DefaultBoolean(true)
public static boolean modernizeF3Screen;
@Config.Comment("Show block registry name and meta value in F3, similar to 1.8+. [From ArchaicFix]")
@Config.DefaultBoolean(true)
public static boolean showBlockDebugInfo;
@Config.DefaultBoolean(true)
@Config.Comment("Hide downloading terrain screen. [From ArchaicFix]")
public static boolean hideDownloadingTerrainScreen;
@Config.Comment("Show memory usage during game load. [From ArchaicFix]")
@Config.DefaultBoolean(true)
public static boolean showSplashMemoryBar;
@Config.Comment("Renders the HUD elements once per 20 frames (by default) and reuses the pixels to improve performance. [Experimental]")
@Config.DefaultBoolean(true)
@Config.RequiresMcRestart
public static boolean enableHudCaching;
@Config.Comment("Inject a conditional early return into all RenderGameOverlayEvent receivers; Requires enableHudCaching")
@Config.DefaultBoolean(true)
@Config.RequiresMcRestart
public static boolean enableHudCachingEventTransformer;
@Config.Comment("The amount of frames to wait before updating the HUD elements. [Experimental]")
@Config.DefaultInt(20)
@Config.RangeInt(min = 1, max = 60)
public static int hudCachingFPS = 20;
@Config.Comment("Batch drawScreen fonts [Experimental]")
@Config.DefaultBoolean(true)
@Config.RequiresMcRestart
public static boolean enableFontRenderer;
@Config.Comment("Enable Dynamic Lights")
@Config.DefaultBoolean(true)
@Config.RequiresMcRestart
public static boolean enableDynamicLights;
@Config.Comment("Optimize world update light. [From Hodgepodge]")
@Config.DefaultBoolean(true)
@Config.RequiresMcRestart
public static boolean optimizeWorldUpdateLight;
@Config.Comment("Speedup Animations. [From Hodgepodge]")
@Config.DefaultBoolean(true)
@Config.RequiresMcRestart
public static boolean speedupAnimations;
@Config.Comment("Optimize Texture Loading. [From Hodgepodge]")
@Config.DefaultBoolean(true)
@Config.RequiresMcRestart
public static boolean optimizeTextureLoading;
@Config.Comment("Fix RenderBlockFluid reading the block type from the world access multiple times")
@Config.DefaultBoolean(true)
@Config.RequiresMcRestart
public static boolean fixFluidRendererCheckingBlockAgain;
@Config.Comment("Dynamically modifies the render distance of dropped items entities to preserve performance."
+ " It starts reducing the render distance when exceeding the threshold set below.")
@Config.DefaultBoolean(true)
@Config.RequiresMcRestart
public static boolean dynamicItemRenderDistance;
@Config.Comment("Max amount of dropped item rendered")
@Config.DefaultInt(256)
@Config.RangeInt(min = 32, max = 2048)
public static int droppedItemLimit;
@Config.Comment("Use total world time instead of normal world time. Allows most shader animations to play when "
+ "doDaylightCycle is off, but causes shader animations to desync from time of day.")
@Config.DefaultBoolean(false)
public static boolean useTotalWorldTime;
@Config.Comment("Enable Debug Logging")
@Config.DefaultBoolean(false)
@Config.RequiresMcRestart
public static boolean enableDebugLogging;
@Config.Comment("Enables PBR atlas dumping")
@Config.DefaultBoolean(false)
@Config.Name("Enable PBR Debug")
public static boolean enablePBRDebug;
@Config.Comment("Enable Zoom")
@Config.DefaultBoolean(true)
@Config.RequiresMcRestart
public static boolean enableZoom;
@Config.Comment("Optimizes in-world item rendering")
@Config.DefaultBoolean(true)
@Config.RequiresMcRestart
public static boolean optimizeInWorldItemRendering;
@Config.Comment("Upper limit for the amount of VBO's to cache for optimized item rendering. Higher number can potentially use more VRAM.")
@Config.DefaultInt(512)
@Config.RangeInt(min = 256, max = 1024)
public static int itemRendererCacheSize;
@Config.Comment("Render distance for the spinning mob inside mod spawners")
@Config.DefaultDouble(16D)
@Config.RangeDouble(min = 16D, max = 64D)
public static double mobSpawnerRenderDistance;
@Config.Comment("Switches to an alternate FPS limiter that gives more stable frametimes, in exchange for slightly " +
"more latency. Will never introduce more than one frame of latency, and has a lower impact at higher framerates.")
@Config.DefaultBoolean(false)
public static boolean sleepBeforeSwap;
@Config.Comment("Allows unicode languages to use an odd gui scale")
@Config.DefaultBoolean(true)
public static boolean removeUnicodeEvenScaling;
@Config.Comment({"Block corners and edges between chunks might have \"cracks\" (various lines/dots) in them.",
"While using \"Compact Vertex Format\" makes the situation even worse.",
"This option fixes it.",
"Requires texture reloading (F3 + T) after changing this option to take effect"})
@Config.DefaultBoolean(true)
public static boolean fixBlockCrack;
@Config.Comment({
"The \"epsilon\" value for the fixBlockCrack option. ",
"Set this a bit higher if you can still see lines/dots between solid blocks in dark areas.",
"May cause intense flickering (z-fighting) between blocks if the value is too high"
})
@Config.RangeDouble(min = 0, max = 0.005)
@Config.DefaultDouble(0.001)
public static double blockCrackFixEpsilon;
@Config.Comment("Block classes that have bugs when rendering with the fixBlockCrack can be put here to avoid manipulating them")
@Config.DefaultStringList({
"net.minecraft.block.BlockCauldron",
"net.minecraft.block.BlockStairs"
})
public static String[] blockCrackFixBlacklist;
@Config.Comment({"Block classes that have render pass other than 0 but still need to be manipulated.",
"Add a block class here if you see flickering (z-fighting) with fixBlockCrack enabled"
})
@Config.DefaultStringList({
"gregtech.common.blocks.BlockOres",
"gregtech.common.blocks.GTBlockOre",
"shukaro.artifice.block.world.BlockOre",
"bartworks.system.material.BWMetaGeneratedOres",
"gtPlusPlus.core.block.base.BlockBaseOre",
})
public static String[] blockCrackFixRenderPassWhitelist__;
@Config.Comment("Register HardcodedCustomUniforms in Iris Shaders. May help with compatibility in certain shader packs")
@Config.DefaultBoolean(false)
public static boolean enableHardcodedCustomUniforms;
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\config\AngelicaGuiConfig.java
|
package com.gtnewhorizons.angelica.config;
import com.gtnewhorizon.gtnhlib.config.ConfigException;
import com.gtnewhorizon.gtnhlib.config.SimpleGuiConfig;
import net.minecraft.client.gui.GuiScreen;
public class AngelicaGuiConfig extends SimpleGuiConfig {
public AngelicaGuiConfig(GuiScreen parent) throws ConfigException {
super(parent,
"angelica",
"Angelica",
true,
AngelicaConfig.class,
CompatConfig.class,
FontConfig.class
);
}
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\config\AngelicaGuiConfigFactory.java
|
package com.gtnewhorizons.angelica.config;
import com.gtnewhorizon.gtnhlib.config.SimpleGuiFactory;
import net.minecraft.client.gui.GuiScreen;
public class AngelicaGuiConfigFactory implements SimpleGuiFactory {
@Override
public Class<? extends GuiScreen> mainConfigGuiClass() {
return AngelicaGuiConfig.class;
}
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\config\CompatConfig.java
|
package com.gtnewhorizons.angelica.config;
import com.gtnewhorizon.gtnhlib.config.Config;
@Config(modid = "angelica", filename = "angelica-compat", category = "compat")
public class CompatConfig {
@Config.Comment("Apply fixes to the LOTR mod")
@Config.DefaultBoolean(true)
@Config.RequiresMcRestart
public static boolean fixLotr;
@Config.Comment("Apply fixes to Extra Utilities")
@Config.DefaultBoolean(true)
@Config.RequiresMcRestart
public static boolean fixExtraUtils;
@Config.Comment("Apply fixes to Stacks on Stacks")
@Config.DefaultBoolean(true)
@Config.RequiresMcRestart
public static boolean fixStacksOnStacks;
@Config.Comment("Apply fixes to Minefactory Reloaded")
@Config.DefaultBoolean(true)
@Config.RequiresMcRestart
public static boolean fixMinefactoryReloaded;
@Config.Comment("Apply fixes to Thaumcraft")
@Config.DefaultBoolean(true)
@Config.RequiresMcRestart
public static boolean fixThaumcraft;
@Config.Comment("Apply fixes to ThaumicHorizons")
@Config.DefaultBoolean(true)
@Config.RequiresMcRestart
public static boolean fixThaumicHorizons;
@Config.Comment("Apply fixes to Immersive Engineering")
@Config.DefaultBoolean(true)
@Config.RequiresMcRestart
public static boolean fixImmersiveEngineering;
@Config.Comment("Apply fixes to Security Craft")
@Config.DefaultBoolean(true)
@Config.RequiresMcRestart
public static boolean fixSecurityCraft;
@Config.Comment("Apply tweaks to NTM:Space")
@Config.DefaultBoolean(true)
@Config.RequiresMcRestart
public static boolean tweakNTMSpace;
@Config.Comment("Apply fixes to NTM:Space")
@Config.DefaultBoolean(true)
@Config.RequiresMcRestart
public static boolean fixNTMSpace;
@Config.Comment("Disables rendering of the planet below the player at high altitudes [Requires tweakNTMSpace]")
@Config.DefaultEnum("ShadersOnly")
public static altitudePlanetRendererState NTMSpace_disableAltitudePlanetRenderer;
public enum altitudePlanetRendererState {
Always,
ShadersOnly,
Never
}
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\config\ConfigMigrator.java
|
package com.gtnewhorizons.angelica.config;
import net.minecraft.client.Minecraft;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class ConfigMigrator {
public static Logger LOGGER = LogManager.getLogger("Angelica");
/**
* Tries to migrate the equivalent config file from Rubidium to the Angelica name if possible.
*/
public static Path handleConfigMigration(String fileName) {
final Path configDir = Minecraft.getMinecraft().mcDataDir.toPath().resolve("config");
final Path mainPath = configDir.resolve(fileName);
try {
if(Files.notExists(mainPath)) {
final String legacyName = fileName.replace("angelica", "rubidium");
final Path legacyPath = configDir.resolve(legacyName);
if(Files.exists(legacyPath)) {
Files.move(legacyPath, mainPath);
LOGGER.warn("Migrated {} config file to {}", legacyName, fileName);
}
}
} catch(IOException | RuntimeException e) {
LOGGER.error("Exception encountered while attempting config migration", e);
}
return mainPath;
}
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\config\FontConfig.java
|
package com.gtnewhorizons.angelica.config;
import com.gtnewhorizon.gtnhlib.config.Config;
@Config(modid = "angelica", category = "customfont")
public class FontConfig {
@Config.Comment("Whether or not to use custom fonts when drawing text.")
@Config.DefaultBoolean(false)
public static boolean enableCustomFont;
@Config.Comment("Name of the primary custom font. Best not to set it from here.")
@Config.DefaultString("(none)")
public static String customFontNamePrimary;
@Config.Comment("Name of the fallback custom font. Best not to set it from here.")
@Config.DefaultString("(none)")
public static String customFontNameFallback;
@Config.Comment("The quality at which custom fonts are rendered, making them less pixelated but increasing memory usage.")
@Config.DefaultInt(30)
@Config.RangeInt(min = 6, max = 72)
public static int customFontQuality;
@Config.Comment("Controls the distance at which the font's shadow is drawn.")
@Config.DefaultFloat(1F)
@Config.RangeFloat(min = 0F, max = 2F)
public static float fontShadowOffset;
@Config.Comment("The number of shadows to be drawn behind text at various offsets.")
@Config.DefaultInt(1)
@Config.RangeInt(min = 1, max = 8)
public static int shadowCopies;
@Config.Comment("The number of bold copies to be drawn behind text at various offsets.")
@Config.DefaultInt(2)
@Config.RangeInt(min = 1, max = 8)
public static int boldCopies;
@Config.Comment("Influences the aspect ratio of each glyph.")
@Config.DefaultFloat(0F)
@Config.RangeFloat(min = -1F, max = 1F)
public static float glyphAspect;
@Config.Comment("Scale of each glyph, whitespace excluded.")
@Config.DefaultFloat(1F)
@Config.RangeFloat(min = 0.1F, max = 3F)
public static float glyphScale;
@Config.Comment("Whitespace scale.")
@Config.DefaultFloat(1F)
@Config.RangeFloat(min = 0.1F, max = 3F)
public static float whitespaceScale;
@Config.Comment("Adds extra spacing between glyphs.")
@Config.DefaultFloat(0F)
@Config.RangeFloat(min = -2F, max = 2F)
public static float glyphSpacing;
@Config.Comment("Controls font antialiasing. 0 = none, 1 = 4x MSAA, 2 = 16x MSAA.")
@Config.DefaultInt(2)
@Config.RangeInt(min = 0, max = 2)
public static int fontAAMode;
@Config.Comment("Affects font antialiasing sample spacing. Higher values increase blur.")
@Config.DefaultInt(7)
@Config.RangeInt(min = 1, max = 24)
public static int fontAAStrength;
@Config.Comment("Custom font scale multiplier, for bugfixes.")
@Config.DefaultFloat(1.5F)
@Config.RangeFloat(min = 0.1F, max = 3F)
public static float customFontScale;
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\debug\F3Direction.java
|
package com.gtnewhorizons.angelica.debug;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.entity.Entity;
import net.minecraftforge.client.event.RenderGameOverlayEvent;
import org.lwjgl.opengl.GL11;
public class F3Direction {
public static void renderWorldDirectionsEvent(Minecraft mc, RenderGameOverlayEvent.Pre event) {
if (mc.gameSettings.showDebugInfo && mc.gameSettings.thirdPersonView == 0) {
ScaledResolution scaledresolution = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight);
int width = scaledresolution.getScaledWidth();
int height = scaledresolution.getScaledHeight();
GL11.glPushMatrix();
GL11.glTranslatef((float) (width / 2), (float) (height / 2), -90);
Entity entity = mc.renderViewEntity;
GL11.glRotatef(entity.prevRotationPitch + (entity.rotationPitch - entity.prevRotationPitch) * event.partialTicks, -1.0F, 0.0F, 0.0F);
GL11.glRotatef(entity.prevRotationYaw + (entity.rotationYaw - entity.prevRotationYaw) * event.partialTicks, 0.0F, 1.0F, 0.0F);
GL11.glScalef(-1.0F, -1.0F, -1.0F);
renderWorldDirections();
GL11.glPopMatrix();
}
}
public static void renderWorldDirections() {
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glDepthMask(false);
Tessellator tessellator = Tessellator.instance;
GL11.glLineWidth(2.0F);
tessellator.startDrawing(GL11.GL_LINES);
//X
tessellator.setColorRGBA_F(255, 0, 0, 1);
tessellator.addVertex(0.0D, 0.0D, 0.0D);
tessellator.addVertex(10, 0.0D, 0.0D);
//Z
tessellator.setColorRGBA_F(0, 0, 255, 1);
tessellator.addVertex(0.0D, 0.0D, 0.0D);
tessellator.addVertex(0.0D, 0.0D, 10);
//Y
tessellator.setColorRGBA_F(0, 255, 0, 1);
tessellator.addVertex(0.0D, 0.0D, 0.0D);
tessellator.addVertex(0.0D, 10, 0.0D);
tessellator.draw();
GL11.glLineWidth(1.0F);
GL11.glDepthMask(true);
GL11.glEnable(GL11.GL_TEXTURE_2D);
}
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\debug\F3Graph.java
|
package com.gtnewhorizons.angelica.debug;
import static org.lwjgl.opengl.GL11.GL_ALPHA_TEST;
import static org.lwjgl.opengl.GL11.GL_BLEND;
import static org.lwjgl.opengl.GL11.GL_CULL_FACE;
import static org.lwjgl.opengl.GL11.GL_DEPTH_TEST;
import static org.lwjgl.opengl.GL11.GL_FLOAT;
import static org.lwjgl.opengl.GL11.GL_ONE_MINUS_SRC_ALPHA;
import static org.lwjgl.opengl.GL11.GL_SRC_ALPHA;
import static org.lwjgl.opengl.GL11.GL_TEXTURE_2D;
import static org.lwjgl.opengl.GL11.GL_TRIANGLE_STRIP;
import static org.lwjgl.opengl.GL11.GL_VERTEX_ARRAY;
import static org.lwjgl.opengl.GL11.glBlendFunc;
import static org.lwjgl.opengl.GL11.glColor4f;
import static org.lwjgl.opengl.GL11.glDisable;
import static org.lwjgl.opengl.GL11.glDisableClientState;
import static org.lwjgl.opengl.GL11.glDrawArrays;
import static org.lwjgl.opengl.GL11.glEnable;
import static org.lwjgl.opengl.GL11.glEnableClientState;
import static org.lwjgl.opengl.GL15.GL_ARRAY_BUFFER;
import static org.lwjgl.opengl.GL15.GL_STATIC_DRAW;
import static org.lwjgl.opengl.GL15.glBindBuffer;
import static org.lwjgl.opengl.GL15.glBufferData;
import static org.lwjgl.opengl.GL15.glGenBuffers;
import static org.lwjgl.opengl.GL20.glDisableVertexAttribArray;
import static org.lwjgl.opengl.GL20.glEnableVertexAttribArray;
import static org.lwjgl.opengl.GL20.glUniform1;
import static org.lwjgl.opengl.GL20.glUniform1f;
import static org.lwjgl.opengl.GL20.glUniform1i;
import static org.lwjgl.opengl.GL20.glVertexAttribPointer;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryStack.*;
import com.gtnewhorizon.gtnhlib.bytebuf.MemoryStack;
import com.gtnewhorizon.gtnhlib.client.renderer.shader.ShaderProgram;
import java.nio.FloatBuffer;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.BufferUtils;
public abstract class F3Graph {
private static final int NUM_SAMPLES = 240;
// Two floats (x,y)
private static final int VERT_FLOATS = 2;
private static final int VERT_COUNT = 4;
private static final int BORDER = 1;
private static final int HEIGHT = 60;
private static final int WIDTH = NUM_SAMPLES;
private static final int FONT_COLOR = 0xFFE0E0E0;
// Due to GLSL 120 limitations, it's just easier to use floats
private final FloatBuffer sampleBuf = BufferUtils.createFloatBuffer(NUM_SAMPLES);
private final long[] samples = new long[NUM_SAMPLES]; // long version for calculations
// Circular buffer holding the last 240 samples, in nanoseconds
private int samplesHead = 0; // one ahead of the position of the last sample
private boolean initialized = false;
private ShaderProgram shader;
private int aPos;
private int uFBWidth;
private int uFBHeight;
private int uScaleFactor;
private int uHeadIdx;
private int uSamples;
private int vertBuf;
private final ResourceLocation texture;
private final float pxPerNs;
private final boolean left;
private long sum;
protected F3Graph(ResourceLocation texture, float pxPerNs, boolean left) {
this.texture = texture;
this.pxPerNs = pxPerNs;
this.left = left;
}
public void putSample(long time) {
// Manage running trackers
sum -= samples[samplesHead];
sum += time;
samples[samplesHead] = time;
sampleBuf.put(samplesHead, (float) time);
samplesHead = (samplesHead + 1) % NUM_SAMPLES;
}
private int getVertX(ScaledResolution sres, int idx) {
if (left) {
return switch (idx) {
case 0, 3 -> WIDTH + BORDER * 2;
case 1, 2 -> 0;
default -> throw new RuntimeException("Tried to get out-of-bounds vertex for graph!");
};
}
final int displayWidth = sres.getScaledWidth();
return switch (idx) {
case 0, 3 -> displayWidth;
case 1, 2 -> displayWidth - WIDTH - BORDER * 2;
default -> throw new RuntimeException("Tried to get out-of-bounds vertex for graph!");
};
}
private int getVertY(ScaledResolution sres, int idx) {
final int displayHeight = sres.getScaledHeight();
return switch (idx) {
case 0, 1 -> displayHeight - HEIGHT - BORDER * 2;
case 2, 3 -> displayHeight;
default -> throw new RuntimeException("Tried to get out-of-bounds vertex for graph!");
};
}
private void init() {
shader = new ShaderProgram(
"angelica",
"shaders/debug_graph.vert.glsl",
"shaders/debug_graph.frag.glsl");
shader.use();
// Register attributes
aPos = shader.getAttribLocation("pos");
// Register uniforms
uFBWidth = shader.getUniformLocation("fbWidth");
uFBHeight = shader.getUniformLocation("fbHeight");
uScaleFactor = shader.getUniformLocation("scaleFactor");
uSamples = shader.getUniformLocation("samples");
uHeadIdx = shader.getUniformLocation("headIdx");
final int uPxPerNs = shader.getUniformLocation("pxPerNs");
final int uLeft = shader.getUniformLocation("left");
// Load vertex buffer
vertBuf = glGenBuffers();
glBindBuffer(GL_ARRAY_BUFFER, vertBuf);
try (final MemoryStack stack = stackPush()) {
final FloatBuffer vertices = stack.mallocFloat(VERT_COUNT * VERT_FLOATS);
// Since we use a triangle strip, we only need 4 vertices. The quad extends to the top of the screen so spikes
// don't get truncated. The max height is replaced in the vert shader, no need to be precise.
vertices.put(new float[]{
BORDER, BORDER,
WIDTH + BORDER, BORDER,
BORDER, Float.MAX_VALUE,
WIDTH + BORDER, Float.MAX_VALUE
});
vertices.rewind();
glBufferData(GL_ARRAY_BUFFER, vertices, GL_STATIC_DRAW);
}
glBindBuffer(GL_ARRAY_BUFFER, 0);
final Minecraft mc = Minecraft.getMinecraft();
final ScaledResolution sr = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight);
// Load initial value for uniforms
glUniform1f(uFBWidth, mc.displayWidth);
glUniform1f(uFBHeight, mc.displayHeight);
glUniform1f(uScaleFactor, sr.getScaleFactor());
glUniform1i(uHeadIdx, samplesHead);
glUniform1(uSamples, sampleBuf);
glUniform1f(uPxPerNs, pxPerNs);
glUniform1i(uLeft, left ? 1 : 0); // this is how you load bool uniforms
ShaderProgram.clear();
}
public void render() {
if (!initialized) {
init();
initialized = true;
}
/*
* We try to copy modern vanilla's tracker.
* It is 240 (FRAME_TIMES) wide by 60 tall, including the 1px borders.
* We instead make it 242x62 including borders to prevent the borders from overlapping the samples.
* The background is ARGB 90505050, the borders FFFFFFFF, and the text FFE0E0E0.
* First the background is rendered, then the samples, then the foreground texture and the text.
* The background is drawn via a 242x62 translucent rect.
* Next, the samples are rendered by a shader on a transparent 240x60 rect.
* Finally, the foreground texture and the text is rendered on top.
* The shader pipeline is only needed for the sample draw.
*/
final Minecraft mc = Minecraft.getMinecraft();
final ScaledResolution sr = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight);
// Setup GL state
final Tessellator tess = Tessellator.instance;
glDisable(GL_DEPTH_TEST);
glEnable(GL_ALPHA_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// Draw background
glDisable(GL_TEXTURE_2D);
glColor4f(0x50 / 255.0F, 0x50 / 255.0F, 0x50 / 255.0F, 0x90 / 255.0F);
tess.startDrawingQuads();
for (int i = 0; i < 4; ++i) {
tess.addVertex(getVertX(sr, i), getVertY(sr, i), 0);
}
tess.draw();
glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
glEnable(GL_TEXTURE_2D);
// Draw samples
shader.use();
// Load uniforms
glUniform1f(uFBWidth, mc.displayWidth);
glUniform1f(uFBHeight, mc.displayHeight);
glUniform1f(uScaleFactor, sr.getScaleFactor());
glUniform1i(uHeadIdx, samplesHead);
glUniform1(uSamples, sampleBuf);
glBindBuffer(GL_ARRAY_BUFFER, vertBuf);
glEnableVertexAttribArray(aPos);
glVertexAttribPointer(aPos, VERT_FLOATS, GL_FLOAT, false, VERT_FLOATS * 4, 0);
glEnableClientState(GL_VERTEX_ARRAY);
// Left side graphs are inverted, so temporarily disable culling
if (!left) glDisable(GL_CULL_FACE);
glDrawArrays(GL_TRIANGLE_STRIP, 0, VERT_COUNT);
if (!left) glEnable(GL_CULL_FACE);
glDisableClientState(GL_VERTEX_ARRAY);
glDisableVertexAttribArray(aPos);
glBindBuffer(GL_ARRAY_BUFFER, 0);
ShaderProgram.clear();
// Draw foreground
mc.getTextureManager().bindTexture(texture);
tess.startDrawingQuads();
tess.addVertexWithUV(getVertX(sr, 0), getVertY(sr, 0), 0.0D, 1, 0);
tess.addVertexWithUV(getVertX(sr, 1), getVertY(sr, 1), 0.0D, 0, 0);
tess.addVertexWithUV(getVertX(sr, 2), getVertY(sr, 2), 0.0D, 0, 1);
tess.addVertexWithUV(getVertX(sr, 3), getVertY(sr, 3), 0.0D, 1, 1);
tess.draw();
// Reset GL state
glEnable(GL_DEPTH_TEST);
glDisable(GL_ALPHA_TEST);
glDisable(GL_BLEND);
// Draw text
// Ensure running counters are reset on first sample
long min = Long.MAX_VALUE;
long max = Long.MIN_VALUE;
for (int i = 0; i < NUM_SAMPLES; ++i) {
min = Math.min(min, samples[i]);
max = Math.max(max, samples[i]);
}
String minStr = String.format("%.1f ms min", min / 1_000_000D);
String avgStr = String.format("%.1f ms avg", sum / 1_000_000 / (double) NUM_SAMPLES);
String maxStr = String.format("%.1f ms max", max / 1_000_000D);
final FontRenderer fr = mc.fontRenderer;
final int top = sr.getScaledHeight() - HEIGHT - BORDER * 2 - fr.FONT_HEIGHT;
final int scaledWidth = sr.getScaledWidth();
if (left) {
fr.drawString(minStr, BORDER * 2, top, FONT_COLOR, true);
fr.drawString(avgStr, BORDER + WIDTH / 2 - fr.getStringWidth(avgStr) / 2, top, FONT_COLOR, true);
fr.drawString(maxStr, BORDER * 2 + WIDTH - fr.getStringWidth(maxStr), top, FONT_COLOR, true);
} else {
fr.drawString(minStr, scaledWidth - (BORDER * 2 + WIDTH), top, FONT_COLOR, true);
fr.drawString(avgStr, scaledWidth - (BORDER + WIDTH / 2 + fr.getStringWidth(avgStr) / 2), top, FONT_COLOR, true);
fr.drawString(maxStr, scaledWidth - (BORDER * 2 + fr.getStringWidth(maxStr)), top, FONT_COLOR, true);
}
}
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\debug\FrametimeGraph.java
|
package com.gtnewhorizons.angelica.debug;
import net.minecraft.util.ResourceLocation;
public class FrametimeGraph extends F3Graph {
public FrametimeGraph() {
// At 1x scale, 30 FPS should be 60 px. 30 FPS = 33_333_333ns per frame, 60px/33_333_333ns = 0.0000018f px/ns
super(
new ResourceLocation("angelica:textures/frametimes_fg.png"),
0.0000018f,
true
);
}
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\debug\TPSGraph.java
|
package com.gtnewhorizons.angelica.debug;
import net.minecraft.util.ResourceLocation;
public class TPSGraph extends F3Graph {
public TPSGraph() {
// At 1x scale, 20 TPS should be 60 px. 20 FPS = 50_000_000ns per frame, 60px/50_000_000ns = 0.0000012 px/ns
super(
new ResourceLocation("angelica:textures/tps_fg.png"),
0.0000012f,
false
);
}
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\dynamiclights\DynamicLights.java
|
package com.gtnewhorizons.angelica.dynamiclights;
import baubles.common.lib.PlayerHandler;
import com.gtnewhorizon.gtnhlib.blockpos.BlockPos;
import com.gtnewhorizon.gtnhlib.blockpos.IBlockPos;
import com.gtnewhorizon.gtnhlib.util.CoordinatePacker;
import com.gtnewhorizons.angelica.api.IDynamicLightProducer;
import com.gtnewhorizons.angelica.compat.ModStatus;
import com.gtnewhorizons.angelica.compat.battlegear2.Battlegear2Compat;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import it.unimi.dsi.fastutil.longs.LongOpenHashSet;
import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet;
import me.jellysquid.mods.sodium.client.render.SodiumWorldRenderer;
import mods.battlegear2.api.core.IBattlePlayer;
import net.irisshaders.iris.api.v0.IrisApi;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.util.MathHelper;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Set;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Predicate;
public class DynamicLights {
private static DynamicLights instance;
public static DynamicLightsMode Mode = DynamicLightsMode.OFF;
public static boolean ShaderForce = false;
public static final boolean configEnabled = AngelicaConfig.enableDynamicLights;
private static final double MAX_RADIUS = 7.75;
private static final double MAX_RADIUS_SQUARED = MAX_RADIUS * MAX_RADIUS;
private final Set<IDynamicLightSource> dynamicLightSources = new ObjectOpenHashSet<>();
private final ReentrantReadWriteLock lightSourcesLock = new ReentrantReadWriteLock();
private long lastUpdate = System.currentTimeMillis();
private int lastUpdateCount = 0;
public static DynamicLights get() {
if (instance == null)
instance = new DynamicLights();
return instance;
}
public static boolean isEnabled() {
return configEnabled &&
Mode.isEnabled() &&
// if shader force is enabled then true
// if not, then true when shaders are not in use
(ShaderForce || !IrisApi.getInstance().isShaderPackInUse());
}
/**
* Updates all light sources.
*
* @param renderer the renderer
*/
public void updateAll(@NotNull SodiumWorldRenderer renderer) {
if (!isEnabled())
return;
long now = System.currentTimeMillis();
if (now >= this.lastUpdate + Mode.getDelay()) {
this.lastUpdate = now;
this.lastUpdateCount = 0;
this.lightSourcesLock.readLock().lock();
for (var lightSource : this.dynamicLightSources) {
if (lightSource.angelica$updateDynamicLight(renderer))
this.lastUpdateCount++;
}
this.lightSourcesLock.readLock().unlock();
}
}
public int getLastUpdateCount() {
return this.lastUpdateCount;
}
public void addLightSource(IDynamicLightSource lightSource) {
this.lightSourcesLock.writeLock().lock();
this.dynamicLightSources.add(lightSource);
this.lightSourcesLock.writeLock().unlock();
}
/**
* Removes the light source from the tracked light sources.
*
* @param lightSource the light source to remove
*/
public void removeLightSource(@NotNull IDynamicLightSource lightSource) {
this.lightSourcesLock.writeLock().lock();
var dynamicLightSources = this.dynamicLightSources.iterator();
IDynamicLightSource it;
while (dynamicLightSources.hasNext()) {
it = dynamicLightSources.next();
if (it.equals(lightSource)) {
dynamicLightSources.remove();
if (SodiumWorldRenderer.getInstance() != null)
lightSource.angelica$scheduleTrackedChunksRebuild(SodiumWorldRenderer.getInstance());
break;
}
}
this.lightSourcesLock.writeLock().unlock();
}
/**
* Removes light sources if the filter matches.
*
* @param filter the removal filter
*/
public void removeLightSources(@NotNull Predicate<IDynamicLightSource> filter) {
this.lightSourcesLock.writeLock().lock();
var dynamicLightSources = this.dynamicLightSources.iterator();
IDynamicLightSource it;
while (dynamicLightSources.hasNext()) {
it = dynamicLightSources.next();
if (filter.test(it)) {
dynamicLightSources.remove();
if (SodiumWorldRenderer.getInstance() != null) {
if (it.angelica$getLuminance() > 0)
it.angelica$resetDynamicLight();
it.angelica$scheduleTrackedChunksRebuild(SodiumWorldRenderer.getInstance());
}
break;
}
}
this.lightSourcesLock.writeLock().unlock();
}
/**
* Clears light sources.
*/
public void clearLightSources() {
this.lightSourcesLock.writeLock().lock();
var dynamicLightSources = this.dynamicLightSources.iterator();
IDynamicLightSource it;
while (dynamicLightSources.hasNext()) {
it = dynamicLightSources.next();
dynamicLightSources.remove();
if (SodiumWorldRenderer.getInstance() != null) {
if (it.angelica$getLuminance() > 0)
it.angelica$resetDynamicLight();
it.angelica$scheduleTrackedChunksRebuild(SodiumWorldRenderer.getInstance());
}
}
this.lightSourcesLock.writeLock().unlock();
}
/**
* Returns whether the light source is tracked or not.
*
* @param lightSource the light source to check
* @return {@code true} if the light source is tracked, else {@code false}
*/
public boolean containsLightSource(@NotNull IDynamicLightSource lightSource) {
boolean result;
this.lightSourcesLock.readLock().lock();
result = this.dynamicLightSources.contains(lightSource);
this.lightSourcesLock.readLock().unlock();
return result;
}
/**
* Returns the number of dynamic light sources that currently emit lights.
*
* @return the number of dynamic light sources emitting light
*/
public int getLightSourcesCount() {
int result;
this.lightSourcesLock.readLock().lock();
result = this.dynamicLightSources.size();
this.lightSourcesLock.readLock().unlock();
return result;
}
public double getDynamicLightLevel(int x, int y, int z) {
double result = 0;
this.lightSourcesLock.readLock().lock();
for (var lightSource : this.dynamicLightSources) {
result = maxDynamicLightLevel(x, y, z, lightSource, result);
}
this.lightSourcesLock.readLock().unlock();
return MathHelper.clamp_double(result, 0, 15);
}
public double getDynamicLightLevel(@NotNull BlockPos pos) {
return this.getDynamicLightLevel(pos.getX(), pos.getY(), pos.getZ());
}
public static double maxDynamicLightLevel(int x, int y, int z, @NotNull IDynamicLightSource lightSource, double currentLightLevel) {
int luminance = lightSource.angelica$getLuminance();
if (luminance > 0) {
// Can't use Entity#squaredDistanceTo because of eye Y coordinate.
double dx = x - lightSource.angelica$getDynamicLightX() + 0.5;
double dy = y - lightSource.angelica$getDynamicLightY() + 0.5;
double dz = z - lightSource.angelica$getDynamicLightZ() + 0.5;
double distanceSquared = dx * dx + dy * dy + dz * dz;
// 7.75 because else we would have to update more chunks and that's not a good idea.
// 15 (max range for blocks) would be too much and a bit cheaty.
if (distanceSquared <= MAX_RADIUS_SQUARED) {
double multiplier = 1.0 - Math.sqrt(distanceSquared) / MAX_RADIUS;
double lightLevel = multiplier * (double) luminance;
if (lightLevel > currentLightLevel) {
return lightLevel;
}
}
}
return currentLightLevel;
}
/**
* Returns the dynamic light level generated by the light source at the specified position.
*
* @param pos the position
* @param lightSource the light source
* @param currentLightLevel the current surrounding dynamic light level
* @return the dynamic light level at the specified position
*/
public static double maxDynamicLightLevel(@NotNull BlockPos pos, @NotNull IDynamicLightSource lightSource, double currentLightLevel) {
return maxDynamicLightLevel(pos.getX(), pos.getY(), pos.getZ(), lightSource, currentLightLevel);
}
public int getLightmapWithDynamicLight(int x, int y, int z, int lightmap) {
return this.getLightmapWithDynamicLight(this.getDynamicLightLevel(x, y, z), lightmap);
}
/**
* Returns the lightmap with combined light levels.
*
* @param dynamicLightLevel the dynamic light level
* @param lightmap the vanilla lightmap coordinates
* @return the modified lightmap coordinates
*/
public int getLightmapWithDynamicLight(double dynamicLightLevel, int lightmap) {
if (dynamicLightLevel > 0) {
// lightmap is (skyLevel << 20 | blockLevel << 4)
// Get vanilla block light level.
int blockLevel = (lightmap & 0xFFFF) >> 4;
if (dynamicLightLevel > blockLevel) {
// Equivalent to a << 4 bitshift with a little quirk: this one ensure more precision (more decimals are saved).
int luminance = (int) (dynamicLightLevel * 16.0);
lightmap &= 0xfff00000;
lightmap |= luminance & 0x000fffff;
}
}
return lightmap;
}
/**
* Schedules a chunk rebuild at the specified chunk position.
*
* @param renderer the renderer
* @param chunkPos the chunk position
*/
public static void scheduleChunkRebuild(@NotNull SodiumWorldRenderer renderer, @NotNull IBlockPos chunkPos) {
scheduleChunkRebuild(renderer, chunkPos.getX(), chunkPos.getY(), chunkPos.getZ());
}
/**
* Schedules a chunk rebuild at the specified chunk position.
*
* @param renderer the renderer
* @param chunkPos the packed chunk position
*/
public static void scheduleChunkRebuild(@NotNull SodiumWorldRenderer renderer, long chunkPos) {
scheduleChunkRebuild(renderer, CoordinatePacker.unpackX(chunkPos), CoordinatePacker.unpackY(chunkPos), CoordinatePacker.unpackZ(chunkPos));
}
public static void scheduleChunkRebuild(@NotNull SodiumWorldRenderer renderer, int x, int y, int z) {
renderer.scheduleRebuildForChunk(x, y, z, false);
}
/**
* Updates the tracked chunk sets.
*
* @param chunkPos the packed chunk position
* @param old the set of old chunk coordinates to remove this chunk from it
* @param newPos the set of new chunk coordinates to add this chunk to it
*/
public static void updateTrackedChunks(@NotNull IBlockPos chunkPos, @Nullable LongOpenHashSet old, @Nullable LongOpenHashSet newPos) {
if (old != null || newPos != null) {
final long pos = chunkPos.asLong();
if (old != null)
old.remove(pos);
if (newPos != null)
newPos.add(pos);
}
}
/**
* Updates the dynamic lights tracking.
*
* @param lightSource the light source
*/
public static void updateTracking(@NotNull IDynamicLightSource lightSource) {
boolean enabled = lightSource.angelica$isDynamicLightEnabled();
int luminance = lightSource.angelica$getLuminance();
if (!enabled && luminance > 0) {
lightSource.angelica$setDynamicLightEnabled(true);
} else if (enabled && luminance < 1) {
lightSource.angelica$setDynamicLightEnabled(false);
}
}
/**
* Returns the luminance from an item stack.
*
* @param stack the item stack
* @param submergedInWater {@code true} if the stack is submerged in water, else {@code false}
* @return the luminance of the item
*/
public static int getLuminanceFromItemStack(@NotNull ItemStack stack, boolean submergedInWater) {
// TODO only have certain items not glow in water?
if (submergedInWater) return 0;
Item item = stack.getItem();
if (item instanceof ItemBlock itemBlock) {
Block block = itemBlock.field_150939_a;
if (block != null) {
return block.getLightValue();
}
} else if (item instanceof IDynamicLightProducer lightProducer){
return lightProducer.getLuminance();
}
if (item == Items.lava_bucket) return Blocks.lava.getLightValue();
return 0;
}
public static int getLuminanceFromEntity(@NotNull Entity entity) {
if (entity.fire > 0) return 15;
if (entity instanceof EntityItem item) {
return getLuminanceFromItemStack(item.getEntityItem(), item.isInsideOfMaterial(Material.water));
}
if (entity instanceof EntityLivingBase living) {
int luminance = 0;
boolean inWater = living.isInsideOfMaterial(Material.water);
// check equipment + hand for light (should work for all entities)
ItemStack itemStack;
for (int i = 0; i < 5; i++) {
if ((itemStack = living.getEquipmentInSlot(i)) != null) {
luminance = Math.max(luminance, getLuminanceFromItemStack(itemStack, inWater));
}
}
if (ModStatus.isBattlegearLoaded &&
living instanceof EntityPlayer player &&
player instanceof IBattlePlayer battlePlayer &&
battlePlayer.battlegear2$isBattlemode()
) {
ItemStack offhand = Battlegear2Compat.getBattlegear2Offhand(player);
if (offhand != null) {
luminance = Math.max(luminance, getLuminanceFromItemStack(offhand, inWater));
}
}
else if (ModStatus.isBackhandLoaded && living instanceof EntityPlayer player){
ItemStack offhand = ModStatus.backhandCompat.getOffhandItem(player);
if (offhand != null) {
luminance = Math.max(luminance, getLuminanceFromItemStack(offhand, inWater));
}
}
if (ModStatus.isBaublesLoaded && living instanceof EntityPlayer player){
var playerBaubles = PlayerHandler.getPlayerBaubles(player);
if (playerBaubles != null){
for (int i = 0; i < playerBaubles.getSizeInventory(); i++){
var stack = playerBaubles.getStackInSlot(i);
if (stack != null){
luminance = Math.max(luminance, getLuminanceFromItemStack(stack, inWater));
}
}
}
}
return luminance;
}
// TODO: Creepers? TNT? Dusts?
return 0;
}
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\dynamiclights\DynamicLightsMode.java
|
package com.gtnewhorizons.angelica.dynamiclights;
import java.util.Objects;
public enum DynamicLightsMode
{
OFF("Off", 0),
FASTEST("Fastest", 500),
FAST("Fast", 250),
FANCY("Fancy", 50),
REALTIME("Realtime", 0);
private final String name;
private final int delay;
public boolean hasDelay() {
return delay > 0;
}
public int getDelay(){
return delay;
}
public String getName() {
return name;
}
DynamicLightsMode(String name, int delay) {
this.name = name;
this.delay = delay;
}
public boolean isEnabled() {
return !Objects.equals(this, DynamicLightsMode.OFF);
}
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\dynamiclights\IDynamicLightSource.java
|
package com.gtnewhorizons.angelica.dynamiclights;
import me.jellysquid.mods.sodium.client.render.SodiumWorldRenderer;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
public interface IDynamicLightSource {
/**
* Returns the dynamic light source X coordinate.
*
* @return the X coordinate
*/
double angelica$getDynamicLightX();
/**
* Returns the dynamic light source Y coordinate.
*
* @return the Y coordinate
*/
double angelica$getDynamicLightY();
/**
* Returns the dynamic light source Z coordinate.
*
* @return the Z coordinate
*/
double angelica$getDynamicLightZ();
/**
* Returns the dynamic light source world.
*
* @return the world instance
*/
SodiumWorldRenderer angelica$getDynamicLightWorld();
/**
* Returns whether the dynamic light is enabled or not.
*
* @return {@code true} if the dynamic light is enabled, else {@code false}
*/
default boolean angelica$isDynamicLightEnabled() {
return DynamicLights.isEnabled() && DynamicLights.get().containsLightSource(this);
}
/**
* Sets whether the dynamic light is enabled or not.
* <p>
* Note: please do not call this function in your mod or you will break things.
*
* @param enabled {@code true} if the dynamic light is enabled, else {@code false}
*/
@ApiStatus.Internal
default void angelica$setDynamicLightEnabled(boolean enabled) {
this.angelica$resetDynamicLight();
if (enabled)
DynamicLights.get().addLightSource(this);
else
DynamicLights.get().removeLightSource(this);
}
void angelica$resetDynamicLight();
/**
* Returns the luminance of the light source.
* The maximum is 15, below 1 values are ignored.
*
* @return the luminance of the light source
*/
int angelica$getLuminance();
/**
* Executed at each tick.
*/
void angelica$dynamicLightTick();
boolean angelica$updateDynamicLight(@NotNull SodiumWorldRenderer renderer);
void angelica$scheduleTrackedChunksRebuild(@NotNull SodiumWorldRenderer renderer);
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\glsm\CommandBufferBuilder.java
|
package com.gtnewhorizons.angelica.glsm;
import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer;
import com.gtnewhorizons.angelica.glsm.recording.CommandBuffer;
import com.gtnewhorizons.angelica.glsm.recording.CommandBufferProcessor;
import com.gtnewhorizons.angelica.glsm.recording.CommandBufferProcessor.BufferTransformOptimizer;
import it.unimi.dsi.fastutil.objects.Object2IntMap;
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
/**
* Builds final command buffers from raw command buffers and compiled VBO data.
* Transforms are already collapsed to MultMatrix during recording; the optimizer
* tracks transform state to emit deltas when draws need a different transform.
*/
public final class CommandBufferBuilder {
private static final Logger LOGGER = LogManager.getLogger("CommandBufferBuilder");
private CommandBufferBuilder() {}
/** Build with transform delta optimization and merged draw ranges. */
public static void buildOptimizedFromRawBuffer(
CommandBuffer rawBuffer,
Map<CapturingTessellator.Flags, CompiledFormatBuffer> compiledQuadBuffers,
final CompiledLineBuffer compiledLineBuffer,
final Map<CapturingTessellator.Flags, CompiledPrimitiveBuffers> compiledPrimitiveBuffers,
VertexBuffer[] ownedVbos,
int glListId,
CommandBuffer finalBuffer) {
// Build VBO index map for efficient lookup (no boxing)
final Object2IntMap<VertexBuffer> vboIndexMap = new Object2IntOpenHashMap<>();
vboIndexMap.defaultReturnValue(-1);
for (int i = 0; i < ownedVbos.length; i++) {
vboIndexMap.put(ownedVbos[i], i);
}
// Collect all merged draw ranges sorted by command index
final List<DrawRangeWithBuffer> allRanges = collectDrawRanges(compiledQuadBuffers, compiledLineBuffer, compiledPrimitiveBuffers);
// Buffer optimizer state
final BufferTransformOptimizer opt = new BufferTransformOptimizer();
rawBuffer.resetRead();
int cmdIndex = 0;
int rangeIndex = 0;
while (rawBuffer.hasRemaining()) {
// Emit draw ranges at this command position
while (rangeIndex < allRanges.size() && allRanges.get(rangeIndex).range().commandIndex() == cmdIndex) {
emitDrawRangeToBuffer(allRanges.get(rangeIndex++), opt, finalBuffer, vboIndexMap);
}
// Read and process the command
final int opcode = rawBuffer.readInt();
CommandBufferProcessor.processCommandForOptimization(opcode, rawBuffer, opt, finalBuffer);
cmdIndex++;
}
// Emit remaining draw ranges at end of command stream
while (rangeIndex < allRanges.size()) {
emitDrawRangeToBuffer(allRanges.get(rangeIndex++), opt, finalBuffer, vboIndexMap);
}
// Emit residual transform if not identity
if (!opt.isIdentity()) {
opt.emitPendingTransform(finalBuffer);
}
}
/** Debug build: no optimizations, 1:1 draw commands. */
public static void buildUnoptimizedFromRawBuffer(
CommandBuffer rawBuffer,
Map<CapturingTessellator.Flags, CompiledFormatBuffer> compiledQuadBuffers,
CompiledLineBuffer compiledLineBuffer,
Map<CapturingTessellator.Flags, CompiledPrimitiveBuffers> compiledPrimitiveBuffers,
VertexBuffer[] ownedVbos,
CommandBuffer finalBuffer) {
// Build VBO index map for efficient lookup (no boxing)
final Object2IntMap<VertexBuffer> vboIndexMap = new Object2IntOpenHashMap<>();
vboIndexMap.defaultReturnValue(-1);
for (int i = 0; i < ownedVbos.length; i++) {
vboIndexMap.put(ownedVbos[i], i);
}
// Collect per-draw ranges (no merging) sorted by command index
final List<DrawRangeWithBuffer> allRanges = collectDrawRangesUnoptimized(compiledQuadBuffers, compiledLineBuffer, compiledPrimitiveBuffers);
rawBuffer.resetRead();
int cmdIndex = 0;
int rangeIndex = 0;
while (rawBuffer.hasRemaining()) {
// Emit draw ranges at this command position
while (rangeIndex < allRanges.size() && allRanges.get(rangeIndex).range().commandIndex() == cmdIndex) {
final DrawRangeWithBuffer drb = allRanges.get(rangeIndex++);
final int vboIdx = vboIndexMap.getInt(drb.vbo());
if (vboIdx >= 0) {
finalBuffer.writeDrawRange(vboIdx, drb.range().startVertex(), drb.range().vertexCount(), drb.hasBrightness());
DisplayListManager.trackDrawRangeSource(drb.source().toString());
}
}
// Copy the command directly
CommandBufferProcessor.copyCommand(rawBuffer, finalBuffer);
cmdIndex++;
}
// Emit remaining draw ranges at end of command stream
while (rangeIndex < allRanges.size()) {
final DrawRangeWithBuffer drb = allRanges.get(rangeIndex++);
final int vboIdx = vboIndexMap.getInt(drb.vbo());
if (vboIdx >= 0) {
finalBuffer.writeDrawRange(vboIdx, drb.range().startVertex(), drb.range().vertexCount(), drb.hasBrightness());
DisplayListManager.trackDrawRangeSource(drb.source().toString());
}
}
}
/** Collect merged draw ranges, sorted by command index. */
static List<DrawRangeWithBuffer> collectDrawRanges(
Map<CapturingTessellator.Flags, CompiledFormatBuffer> compiledQuadBuffers,
CompiledLineBuffer compiledLineBuffer,
Map<CapturingTessellator.Flags, CompiledPrimitiveBuffers> compiledPrimitiveBuffers) {
return collectDrawRangesInternal(compiledQuadBuffers, compiledLineBuffer, compiledPrimitiveBuffers, true);
}
/** Collect unmerged draw ranges for debug mode. */
static List<DrawRangeWithBuffer> collectDrawRangesUnoptimized(
Map<CapturingTessellator.Flags, CompiledFormatBuffer> compiledQuadBuffers,
CompiledLineBuffer compiledLineBuffer,
Map<CapturingTessellator.Flags, CompiledPrimitiveBuffers> compiledPrimitiveBuffers) {
return collectDrawRangesInternal(compiledQuadBuffers, compiledLineBuffer, compiledPrimitiveBuffers, false);
}
private static List<DrawRangeWithBuffer> collectDrawRangesInternal(
Map<CapturingTessellator.Flags, CompiledFormatBuffer> compiledQuadBuffers,
CompiledLineBuffer compiledLineBuffer,
Map<CapturingTessellator.Flags, CompiledPrimitiveBuffers> compiledPrimitiveBuffers,
boolean useMerged) {
final List<DrawRangeWithBuffer> allRanges = new ArrayList<>();
// Add quad ranges
final CompiledFormatBuffer[] quadBufferArray = compiledQuadBuffers.values().toArray(new CompiledFormatBuffer[0]);
for (int b = 0; b < quadBufferArray.length; b++) {
final CompiledFormatBuffer compiledBuffer = quadBufferArray[b];
final DrawRange[] ranges = useMerged ? compiledBuffer.mergedRanges() : compiledBuffer.perDrawRanges();
for (int i = 0; i < ranges.length; i++) {
allRanges.add(new DrawRangeWithBuffer(ranges[i], compiledBuffer.vbo(), compiledBuffer.flags(),
DrawRangeWithBuffer.DrawSource.TESSELLATOR_QUADS));
}
}
// Add immediate mode line ranges
// Lines use a minimal flags (color only, no texture/brightness/normals)
if (compiledLineBuffer != null) {
final CapturingTessellator.Flags lineFlags = new CapturingTessellator.Flags(false, false, true, false);
final DrawRange[] ranges = useMerged ? compiledLineBuffer.mergedRanges() : compiledLineBuffer.perDrawRanges();
for (int i = 0; i < ranges.length; i++) {
allRanges.add(new DrawRangeWithBuffer(ranges[i], compiledLineBuffer.vbo(), lineFlags,
DrawRangeWithBuffer.DrawSource.IMMEDIATE_MODE_LINES));
}
}
// Add tessellator primitive ranges (lines and triangles) - grouped by format
if (compiledPrimitiveBuffers != null && !compiledPrimitiveBuffers.isEmpty()) {
final CompiledPrimitiveBuffers[] primBufferArray = compiledPrimitiveBuffers.values().toArray(new CompiledPrimitiveBuffers[0]);
for (int p = 0; p < primBufferArray.length; p++) {
final CompiledPrimitiveBuffers primBuffers = primBufferArray[p];
final CapturingTessellator.Flags primFlags = primBuffers.flags();
// Tessellator lines
if (primBuffers.hasLines()) {
final DrawRange[] ranges = useMerged ? primBuffers.lineMergedRanges() : primBuffers.linePerDrawRanges();
final VertexBuffer vbo = primBuffers.lineVbo();
for (int i = 0; i < ranges.length; i++) {
allRanges.add(new DrawRangeWithBuffer(ranges[i], vbo, primFlags,
DrawRangeWithBuffer.DrawSource.TESSELLATOR_LINES));
}
}
// Tessellator triangles
if (primBuffers.hasTriangles()) {
final DrawRange[] ranges = useMerged ? primBuffers.triangleMergedRanges() : primBuffers.trianglePerDrawRanges();
final VertexBuffer vbo = primBuffers.triangleVbo();
for (int i = 0; i < ranges.length; i++) {
allRanges.add(new DrawRangeWithBuffer(ranges[i], vbo, primFlags,
DrawRangeWithBuffer.DrawSource.TESSELLATOR_TRIANGLES));
}
}
}
}
allRanges.sort(Comparator.comparingInt(r -> r.range().commandIndex()));
return allRanges;
}
/** Emit draw range with delta transform. Uses writeDrawRangeRestore for immediate mode. */
private static void emitDrawRangeToBuffer(
DrawRangeWithBuffer drb,
BufferTransformOptimizer opt,
CommandBuffer out,
Object2IntMap<VertexBuffer> vboIndexMap) {
// Emit transform to reach the draw's expected transform
opt.emitTransformTo(out, drb.range().transform());
// Write the draw range command
final int vboIdx = vboIndexMap.getInt(drb.vbo());
if (vboIdx >= 0) {
final var restoreData = drb.range().restoreData();
if (restoreData != null) {
// Immediate mode draw with attribute restoration
final var flags = drb.flags();
out.writeDrawRangeRestore(
vboIdx, drb.range().startVertex(), drb.range().vertexCount(),
drb.hasBrightness(), flags.hasColor, flags.hasNormals, flags.hasTexture,
restoreData.lastColorR(), restoreData.lastColorG(),
restoreData.lastColorB(), restoreData.lastColorA(),
restoreData.lastNormalX(), restoreData.lastNormalY(), restoreData.lastNormalZ(),
restoreData.lastTexCoordS(), restoreData.lastTexCoordT()
);
} else {
// Regular tessellator draw (no restoration needed)
out.writeDrawRange(vboIdx, drb.range().startVertex(), drb.range().vertexCount(), drb.hasBrightness());
}
DisplayListManager.trackDrawRangeSource(drb.source().toString());
}
}
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\glsm\CompiledFormatBuffer.java
|
package com.gtnewhorizons.angelica.glsm;
import com.github.bsideup.jabel.Desugar;
import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer;
/**
* A compiled VBO with its associated draw ranges.
* All ranges reference vertices within this single VBO.
* <p>
* Contains two range arrays:
* <ul>
* <li><b>mergedRanges</b>: For optimized path - consecutive same-transform draws merged</li>
* <li><b>perDrawRanges</b>: For unoptimized path - 1:1 with original draws</li>
* </ul>
*/
@Desugar
public record CompiledFormatBuffer(
VertexBuffer vbo,
CapturingTessellator.Flags flags,
DrawRange[] mergedRanges,
DrawRange[] perDrawRanges
) {}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\glsm\CompiledLineBuffer.java
|
package com.gtnewhorizons.angelica.glsm;
import com.github.bsideup.jabel.Desugar;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer;
/**
* A compiled VBO containing all line geometry with associated draw ranges.
* All ranges reference vertices within this single VBO.
* <p>
* Contains two range arrays:
* <ul>
* <li><b>mergedRanges</b>: For optimized path - consecutive same-transform draws merged</li>
* <li><b>perDrawRanges</b>: For unoptimized path - 1:1 with original draws</li>
* </ul>
*/
@Desugar
public record CompiledLineBuffer(
VertexBuffer vbo,
DrawRange[] mergedRanges,
DrawRange[] perDrawRanges
) {}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\glsm\CompiledPrimitiveBuffers.java
|
package com.gtnewhorizons.angelica.glsm;
import com.github.bsideup.jabel.Desugar;
import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer;
/**
* Compiled VBOs containing tessellator primitives (lines and triangles) for a single vertex format.
* Separate VBOs are used for lines (GL_LINES) and triangles (GL_TRIANGLES) since they have different draw modes.
* <p>
* Contains range arrays for both optimized (merged) and unoptimized (per-draw) paths.
* Similar to CompiledFormatBuffer but handles primitives instead of quads.
*/
@Desugar
public record CompiledPrimitiveBuffers(
CapturingTessellator.Flags flags,
VertexBuffer lineVbo,
DrawRange[] lineMergedRanges,
DrawRange[] linePerDrawRanges,
VertexBuffer triangleVbo,
DrawRange[] triangleMergedRanges,
DrawRange[] trianglePerDrawRanges
) {
public boolean hasLines() {
return lineVbo != null;
}
public boolean hasTriangles() {
return triangleVbo != null;
}
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\glsm\DisplayListManager.java
|
package com.gtnewhorizons.angelica.glsm;
import com.github.bsideup.jabel.Desugar;
import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator;
import com.gtnewhorizon.gtnhlib.client.renderer.TessellatorManager;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.primitive.ModelPrimitiveView;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuadViewMutable;
import com.gtnewhorizon.gtnhlib.client.renderer.vao.VAOManager;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VBOManager;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat;
import com.gtnewhorizons.angelica.glsm.recording.AccumulatedDraw;
import com.gtnewhorizons.angelica.glsm.recording.AccumulatedLineDraw;
import com.gtnewhorizons.angelica.glsm.recording.AccumulatedPrimitiveDraw;
import com.gtnewhorizons.angelica.glsm.recording.CommandBuffer;
import com.gtnewhorizons.angelica.glsm.recording.CommandRecorder;
import com.gtnewhorizons.angelica.glsm.recording.CompiledDisplayList;
import com.gtnewhorizons.angelica.glsm.recording.GLCommand;
import com.gtnewhorizons.angelica.glsm.recording.ImmediateModeRecorder;
import com.gtnewhorizons.angelica.glsm.recording.commands.DisplayListCommand;
import com.gtnewhorizons.angelica.glsm.recording.commands.OptimizationContext;
import com.gtnewhorizons.angelica.glsm.GLDebug;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import lombok.Getter;
import lombok.experimental.UtilityClass;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.joml.Matrix4f;
import org.joml.Matrix4fStack;
import org.joml.Vector3f;
import org.lwjgl.opengl.GL11;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* VBO-based display list emulation with command recording, transform collapsing, and format-based batching.
*
* <p><b>Transform Collapsing:</b> Consecutive transforms collapse into single MultMatrix commands,
* emitted at barriers (draws, CallList, exit). Vertices stay canonical in VBOs. Handles nested
* display lists correctly and maintains Push/Pop semantics.
*
* <p><b>Format-Based Batching:</b> Draws with same vertex format share a VBO via {@link FormatBuffer}.
* Each draw's position is tracked as a {@link DrawRange}. Consecutive same-transform draws merge.
* Delta transforms handled via {@link TransformOptimizer}.
*/
@UtilityClass
public class DisplayListManager {
private static final Logger LOGGER = LogManager.getLogger("DisplayListManager");
// -Dangelica.debugDisplayLists: disable transform collapsing and draw merging
private static final boolean DEBUG_DISPLAY_LISTS = Boolean.getBoolean("angelica.debugDisplayLists");
// -Dangelica.logDisplayListCompilation: log compiled display list commands
private static final boolean LOG_DISPLAY_LIST_COMPILATION;
static {
LOG_DISPLAY_LIST_COMPILATION = Boolean.getBoolean("angelica.logDisplayListCompilation");
if (LOG_DISPLAY_LIST_COMPILATION) {
LogManager.getLogger("DisplayListManager").warn("Display list compilation logging ENABLED (-Dangelica.logDisplayListCompilation=true)");
}
}
// Track which display list is currently being rendered
@Getter private static int currentRenderingList = -1;
private static final Matrix4f IDENTITY = new Matrix4f();
public static boolean isIdentity(Matrix4f m) {
return (m.properties() & Matrix4f.PROPERTY_IDENTITY) != 0 || m.equals(IDENTITY, 1e-6f);
}
/** Transform operation types for relative transform tracking. */
public enum TransformOp { TRANSLATE, SCALE, ROTATE }
/** Recording mode for display list compilation. */
public enum RecordMode {
NONE, // Not recording
COMPILE, // GL_COMPILE: record only, don't execute
COMPILE_AND_EXECUTE // GL_COMPILE_AND_EXECUTE: record and execute
}
// Display list compilation state (current/active context)
private static int glListMode = 0;
private static int glListId = -1;
private static boolean tessellatorCompiling = false; // Track if we started compiling
private static CommandRecorder currentRecorder = null; // Command recorder (null when not recording)
private static volatile Thread recordingThread = null; // Thread that started recording (for thread-safety)
private static List<AccumulatedDraw> accumulatedDraws = null; // Accumulates quad draws for batching
private static List<AccumulatedLineDraw> accumulatedLineDraws = null; // Accumulates immediate mode line draws
private static List<AccumulatedPrimitiveDraw> accumulatedPrimitiveDraws = null; // Accumulates tessellator primitive draws (lines, triangles)
private static Matrix4fStack relativeTransform = null; // Tracks delta from current GL state (reset to I after each flush)
/**
* -- GETTER --
* Get the current matrix generation (for draw batching).
*/
@Getter
private static int matrixGeneration = 0; // Increments when relativeTransform changes; used for draw batching
private static int lastFlushedGeneration = -1; // Generation at last flush; draws trigger flush when gen changes
/**
* -- GETTER --
* Get the current state generation (for draw merging).
*/
@Getter
private static int stateGeneration = 0; // Increments at draw barriers (state commands); used for draw merging
private static Matrix4f lastFlushedTransform = null; // The transform that was flushed; consecutive same-gen draws share this
@Getter private static ImmediateModeRecorder immediateModeRecorder = null; // Records glBegin/glEnd/glVertex during compilation
private static StackTraceElement[] compilationStackTrace = null; // For logging: captured at glNewList()
// Debug logging: track sources of MULT_MATRIX commands and draw origins; only populated when LOG_DISPLAY_LIST_COMPILATION is true
private static List<String> pendingTransformOps = null; // Ops accumulated since last flush
private static List<List<String>> multMatrixSources = null; // Source ops for each MULT_MATRIX in raw buffer
private static List<String> drawRangeSources = null; // Source type for each DRAW_RANGE in final buffer
// For flushMatrix() - reusable buffer for executing collapsed transforms
private static final FloatBuffer flushMatrixBuffer = org.lwjgl.BufferUtils.createFloatBuffer(16);
// Nested compilation support - stack of parent contexts
private static final Deque<CompilationContext> compilationStack = new ArrayDeque<>();
// Display list cache
private static final Int2ObjectMap<CompiledDisplayList> displayListCache = new Int2ObjectOpenHashMap<>();
/**
* Compilation context for a single display list being compiled.
* Used to support nested glNewList() calls (spec-violating but needed for mod compatibility).
*/
@Desugar
private record CompilationContext(
int listId,
int listMode,
CommandRecorder recorder,
List<AccumulatedDraw> draws,
List<AccumulatedLineDraw> lineDraws,
List<AccumulatedPrimitiveDraw> primitiveDraws,
Matrix4fStack transform,
boolean wasTessellatorCompiling,
ImmediateModeRecorder immediateRecorder,
StackTraceElement[] stackTrace,
// Debug logging fields (only used when LOG_DISPLAY_LIST_COMPILATION)
List<String> pendingOps,
List<List<String>> matrixSources,
List<String> drawSources
) {}
public static RecordMode getRecordMode() {
if (currentRecorder == null || Thread.currentThread() != recordingThread) {
return RecordMode.NONE;
}
return glListMode == GL11.GL_COMPILE_AND_EXECUTE ? RecordMode.COMPILE_AND_EXECUTE : RecordMode.COMPILE;
}
/** True only for the thread that started recording. */
public static boolean isRecording() {
return currentRecorder != null && Thread.currentThread() == recordingThread;
}
public static boolean isCompileAndExecute() {
return glListMode == GL11.GL_COMPILE_AND_EXECUTE;
}
/** Emit accumulated transform as MultMatrix if non-identity, then reset. */
public static boolean flushMatrix() {
if (relativeTransform == null || isIdentity(relativeTransform)) {
// Clear pending ops even if we don't emit - they were no-ops (identity)
if (pendingTransformOps != null) {
pendingTransformOps.clear();
}
return false;
}
// Save pending transform ops for logging (before we clear them)
if (multMatrixSources != null && pendingTransformOps != null) {
if (pendingTransformOps.isEmpty()) {
LOGGER.warn("flushMatrix: non-identity transform with no tracked ops");
multMatrixSources.add(Collections.singletonList("(unknown source)"));
} else {
multMatrixSources.add(new ArrayList<>(pendingTransformOps));
}
pendingTransformOps.clear();
}
// Record the collapsed MultMatrix command (for playback)
if (currentRecorder != null) {
currentRecorder.recordMultMatrix(relativeTransform);
}
// COMPILE_AND_EXECUTE: execute now. Bypass GLSM to avoid re-entering recording path.
if (glListMode == GL11.GL_COMPILE_AND_EXECUTE) {
flushMatrixBuffer.clear();
relativeTransform.get(flushMatrixBuffer);
GL11.glMultMatrix(flushMatrixBuffer);
GLStateManager.getMatrixStack().mul(relativeTransform);
}
// Reset to identity - we're now synchronized with GL
relativeTransform.identity();
return true;
}
public static void matrixBarrier() {
flushMatrix();
}
public static int getRecordingListId() {
return glListId;
}
public static int getListMode() {
return glListMode;
}
public static int getCommandCount() {
return currentRecorder != null ? currentRecorder.getCommandCount() : 0;
}
public static void trackDrawRangeSource(String source) {
if (drawRangeSources != null) {
drawRangeSources.add(source);
}
}
// Draw barriers: state commands that prevent draw merging
private static void drawBarrier() {
stateGeneration++;
}
public static void recordEnable(int cap) {
if (currentRecorder == null) return;
drawBarrier();
currentRecorder.recordEnable(cap);
}
public static void recordDisable(int cap) {
if (currentRecorder == null) return;
drawBarrier();
currentRecorder.recordDisable(cap);
}
// ==================== NON-BARRIER COMMANDS ====================
// Clear commands don't affect subsequent draws, just clear buffers.
public static void recordClear(int mask) {
if (currentRecorder == null) return;
currentRecorder.recordClear(mask);
}
public static void recordClearColor(float r, float g, float b, float a) {
if (currentRecorder == null) return;
currentRecorder.recordClearColor(r, g, b, a);
}
public static void recordClearDepth(double depth) {
if (currentRecorder == null) return;
currentRecorder.recordClearDepth(depth);
}
public static void recordClearStencil(int s) {
if (currentRecorder == null) return;
currentRecorder.recordClearStencil(s);
}
// ==================== MORE DRAW BARRIER COMMANDS ====================
public static void recordBlendColor(float r, float g, float b, float a) {
if (currentRecorder == null) return;
drawBarrier();
currentRecorder.recordBlendColor(r, g, b, a);
}
public static void recordColor(float r, float g, float b, float a) {
if (currentRecorder == null) return;
drawBarrier();
currentRecorder.recordColor(r, g, b, a);
}
public static void recordColorMask(boolean r, boolean g, boolean b, boolean a) {
if (currentRecorder == null) return;
drawBarrier();
currentRecorder.recordColorMask(r, g, b, a);
}
public static void recordDepthMask(boolean flag) {
if (currentRecorder == null) return;
drawBarrier();
currentRecorder.recordDepthMask(flag);
}
public static void recordFrontFace(int mode) {
if (currentRecorder == null) return;
drawBarrier();
currentRecorder.recordFrontFace(mode);
}
public static void recordDepthFunc(int func) {
if (currentRecorder == null) return;
drawBarrier();
currentRecorder.recordDepthFunc(func);
}
public static void recordBlendFunc(int srcRgb, int dstRgb, int srcAlpha, int dstAlpha) {
if (currentRecorder == null) return;
drawBarrier();
currentRecorder.recordBlendFunc(srcRgb, dstRgb, srcAlpha, dstAlpha);
}
public static void recordAlphaFunc(int func, float ref) {
if (currentRecorder == null) return;
drawBarrier();
currentRecorder.recordAlphaFunc(func, ref);
}
public static void recordCullFace(int mode) {
if (currentRecorder == null) return;
drawBarrier();
currentRecorder.recordCullFace(mode);
}
public static void recordShadeModel(int mode) {
if (currentRecorder == null) return;
drawBarrier();
currentRecorder.recordShadeModel(mode);
}
public static void recordBindTexture(int target, int texture) {
if (currentRecorder == null) return;
drawBarrier();
currentRecorder.recordBindTexture(target, texture);
}
public static void recordTexParameteri(int target, int pname, int param) {
if (currentRecorder == null) return;
drawBarrier();
currentRecorder.recordTexParameteri(target, pname, param);
}
public static void recordTexParameterf(int target, int pname, float param) {
if (currentRecorder == null) return;
drawBarrier();
currentRecorder.recordTexParameterf(target, pname, param);
}
public static void recordMatrixMode(int mode) {
if (currentRecorder == null) return;
matrixBarrier(); // Matrix barrier: flush and reset
currentRecorder.recordMatrixMode(mode);
}
public static void recordPushMatrix() {
if (currentRecorder == null) return;
// Flush any pending delta, then record push.
flushMatrix();
currentRecorder.recordPushMatrix();
}
public static void recordPopMatrix() {
if (currentRecorder == null) return;
// Flush any pending delta, then record pop.
flushMatrix();
currentRecorder.recordPopMatrix();
}
public static void recordViewport(int x, int y, int width, int height) {
if (currentRecorder == null) return;
drawBarrier();
currentRecorder.recordViewport(x, y, width, height);
}
public static void recordPointSize(float size) {
if (currentRecorder == null) return;
drawBarrier();
currentRecorder.recordPointSize(size);
}
public static void recordLineWidth(float width) {
if (currentRecorder == null) return;
drawBarrier();
currentRecorder.recordLineWidth(width);
}
public static void recordLineStipple(int factor, int pattern) {
if (currentRecorder == null) return;
drawBarrier();
currentRecorder.recordLineStipple(factor, pattern);
}
public static void recordPolygonOffset(float factor, float units) {
if (currentRecorder == null) return;
drawBarrier();
currentRecorder.recordPolygonOffset(factor, units);
}
public static void recordPolygonMode(int face, int mode) {
if (currentRecorder == null) return;
drawBarrier();
currentRecorder.recordPolygonMode(face, mode);
}
public static void recordColorMaterial(int face, int mode) {
if (currentRecorder == null) return;
drawBarrier();
currentRecorder.recordColorMaterial(face, mode);
}
public static void recordLogicOp(int opcode) {
if (currentRecorder == null) return;
drawBarrier();
currentRecorder.recordLogicOp(opcode);
}
public static void recordActiveTexture(int texture) {
if (currentRecorder == null) return;
drawBarrier();
currentRecorder.recordActiveTexture(texture);
}
public static void recordUseProgram(int program) {
if (currentRecorder == null) return;
drawBarrier();
currentRecorder.recordUseProgram(program);
}
// PushAttrib saves state but doesn't change it - not a draw barrier
public static void recordPushAttrib(int mask) {
if (currentRecorder == null) return;
currentRecorder.recordPushAttrib(mask);
}
// PopAttrib restores potentially any state - draw barrier
public static void recordPopAttrib() {
if (currentRecorder == null) return;
drawBarrier();
currentRecorder.recordPopAttrib();
}
public static void recordFogf(int pname, float param) {
if (currentRecorder == null) return;
drawBarrier();
currentRecorder.recordFogf(pname, param);
}
public static void recordFogi(int pname, int param) {
if (currentRecorder == null) return;
drawBarrier();
currentRecorder.recordFogi(pname, param);
}
public static void recordHint(int target, int mode) {
if (currentRecorder == null) return;
drawBarrier();
currentRecorder.recordHint(target, mode);
}
public static void recordFog(int pname, java.nio.FloatBuffer params) {
if (currentRecorder == null) return;
drawBarrier();
currentRecorder.recordFog(pname, params);
}
public static void recordLightf(int light, int pname, float param) {
if (currentRecorder == null) return;
drawBarrier();
currentRecorder.recordLightf(light, pname, param);
}
public static void recordLighti(int light, int pname, int param) {
if (currentRecorder == null) return;
drawBarrier();
currentRecorder.recordLighti(light, pname, param);
}
public static void recordLight(int light, int pname, java.nio.FloatBuffer params) {
if (currentRecorder == null) return;
drawBarrier();
currentRecorder.recordLight(light, pname, params);
}
public static void recordLightModelf(int pname, float param) {
if (currentRecorder == null) return;
drawBarrier();
currentRecorder.recordLightModelf(pname, param);
}
public static void recordLightModeli(int pname, int param) {
if (currentRecorder == null) return;
drawBarrier();
currentRecorder.recordLightModeli(pname, param);
}
public static void recordLightModel(int pname, java.nio.FloatBuffer params) {
if (currentRecorder == null) return;
drawBarrier();
currentRecorder.recordLightModel(pname, params);
}
public static void recordMaterialf(int face, int pname, float val) {
if (currentRecorder == null) return;
drawBarrier();
currentRecorder.recordMaterialf(face, pname, val);
}
public static void recordMaterial(int face, int pname, java.nio.FloatBuffer params) {
if (currentRecorder == null) return;
drawBarrier();
currentRecorder.recordMaterial(face, pname, params);
}
public static void recordStencilFunc(int func, int ref, int mask) {
if (currentRecorder == null) return;
drawBarrier();
currentRecorder.recordStencilFunc(func, ref, mask);
}
public static void recordStencilFuncSeparate(int face, int func, int ref, int mask) {
if (currentRecorder == null) return;
drawBarrier();
currentRecorder.recordStencilFuncSeparate(face, func, ref, mask);
}
public static void recordStencilOp(int fail, int zfail, int zpass) {
if (currentRecorder == null) return;
drawBarrier();
currentRecorder.recordStencilOp(fail, zfail, zpass);
}
public static void recordStencilOpSeparate(int face, int sfail, int dpfail, int dppass) {
if (currentRecorder == null) return;
drawBarrier();
currentRecorder.recordStencilOpSeparate(face, sfail, dpfail, dppass);
}
public static void recordStencilMask(int mask) {
if (currentRecorder == null) return;
drawBarrier();
currentRecorder.recordStencilMask(mask);
}
public static void recordStencilMaskSeparate(int face, int mask) {
if (currentRecorder == null) return;
drawBarrier();
currentRecorder.recordStencilMaskSeparate(face, mask);
}
public static void recordCallList(int listId) {
if (currentRecorder == null) return;
matrixBarrier(); // Matrix barrier: nested list has own transforms
currentRecorder.recordCallList(listId);
}
public static void recordDrawBuffer(int mode) {
if (currentRecorder == null) return;
drawBarrier();
currentRecorder.recordDrawBuffer(mode);
}
public static void recordDrawBuffers(int count, int buf) {
if (currentRecorder == null) return;
drawBarrier();
currentRecorder.recordDrawBuffers(count, buf);
}
public static void recordDrawBuffers(int count, java.nio.IntBuffer bufs) {
if (currentRecorder == null) return;
drawBarrier();
currentRecorder.recordDrawBuffers(count, bufs);
}
// Complex commands are texture uploads - not draw barriers
public static void recordComplexCommand(DisplayListCommand cmd) {
if (currentRecorder == null) return;
currentRecorder.recordComplexCommand(cmd);
}
public static void recordLoadMatrix(Matrix4f matrix) {
if (currentRecorder != null) currentRecorder.recordLoadMatrix(matrix);
}
public static void recordLoadIdentity() {
if (currentRecorder != null) currentRecorder.recordLoadIdentity();
}
// recordOrtho/recordFrustum removed - these now accumulate into relativeTransform
// via updateRelativeTransformOrtho/updateRelativeTransformFrustum
/**
* Add an immediate mode draw to the current display list compilation.
* Called by GLStateManager.glEnd() when immediate mode geometry is ready.
*
* <p>This method captures the current transform and command position, creating
* an AccumulatedDraw that will be interleaved correctly with other commands
* during display list playback.
*
* @param result The immediate mode result containing quads, lines, and flags
*/
public static void addImmediateModeDraw(ImmediateModeRecorder.Result result) {
if (accumulatedDraws == null || result == null) {
return;
}
if (matrixGeneration != lastFlushedGeneration) {
if (lastFlushedTransform == null) {
lastFlushedTransform = new Matrix4f();
}
lastFlushedTransform.set(relativeTransform);
flushMatrix();
lastFlushedGeneration = matrixGeneration;
}
final Matrix4f currentTransform = new Matrix4f(lastFlushedTransform);
final int currentGeneration = matrixGeneration;
final int currentBatchId = stateGeneration;
final int cmdIndex = getCommandCount();
if (!result.quads().isEmpty()) {
final var flags = result.flags();
final AccumulatedDraw.RestoreData restoreData;
if (flags.hasColor || flags.hasNormals || flags.hasTexture) {
restoreData = new AccumulatedDraw.RestoreData(
result.lastColorR(), result.lastColorG(), result.lastColorB(), result.lastColorA(),
result.lastNormalX(), result.lastNormalY(), result.lastNormalZ(),
result.lastTexCoordS(), result.lastTexCoordT()
);
} else {
restoreData = null; // Position-only draw, no attributes to restore
}
final AccumulatedDraw quadDraw = new AccumulatedDraw(
result.quads(), currentTransform, flags,
cmdIndex, currentGeneration, currentBatchId, restoreData
);
accumulatedDraws.add(quadDraw);
}
// Add line draw if we have lines
if (!result.lines().isEmpty()) {
final AccumulatedLineDraw lineDraw = new AccumulatedLineDraw(result.lines(), currentTransform, result.flags(), getCommandCount(), currentBatchId);
accumulatedLineDraws.add(lineDraw);
}
}
private static void applyTransformOp(Matrix4f m, float x, float y, float z, TransformOp op, Vector3f axis) {
switch (op) {
case TRANSLATE -> m.translate(x, y, z);
case SCALE -> m.scale(x, y, z);
case ROTATE -> { if (axis != null) m.rotate((float) Math.toRadians(x), axis); }
}
}
public static void updateRelativeTransform(float x, float y, float z, TransformOp op, Vector3f rotationAxis) {
if (relativeTransform == null) return;
if (DEBUG_DISPLAY_LISTS) {
final Matrix4f singleTransform = new Matrix4f();
applyTransformOp(singleTransform, x, y, z, op, rotationAxis);
if (currentRecorder != null) currentRecorder.recordMultMatrix(singleTransform);
if (glListMode == GL11.GL_COMPILE_AND_EXECUTE) {
flushMatrixBuffer.clear();
singleTransform.get(flushMatrixBuffer);
GL11.glMultMatrix(flushMatrixBuffer);
GLStateManager.getMatrixStack().mul(singleTransform);
}
return;
}
applyTransformOp(relativeTransform, x, y, z, op, rotationAxis);
matrixGeneration++;
if (pendingTransformOps != null) {
final String log = switch (op) {
case TRANSLATE -> String.format("glTranslatef(%.4f, %.4f, %.4f)", x, y, z);
case SCALE -> String.format("glScalef(%.4f, %.4f, %.4f)", x, y, z);
case ROTATE -> rotationAxis != null ? String.format("glRotatef(%.4f, %.4f, %.4f, %.4f)", x, rotationAxis.x, rotationAxis.y, rotationAxis.z) : null;
};
if (log != null) pendingTransformOps.add(log);
}
}
/**
* Update the relative transform with a matrix multiplication during display list compilation.
* Called by GLStateManager.glMultMatrix().
*
* <p>In normal mode: accumulates transforms, emits collapsed MultMatrix at barriers.
* <p>In debug mode: emits MultMatrix immediately (no collapsing).
*
* @param matrix The matrix to multiply
*/
public static void updateRelativeTransform(Matrix4f matrix) {
if (relativeTransform == null) {
return;
}
if (DEBUG_DISPLAY_LISTS) {
if (currentRecorder != null) {
currentRecorder.recordMultMatrix(matrix);
}
if (glListMode == GL11.GL_COMPILE_AND_EXECUTE) {
flushMatrixBuffer.clear();
matrix.get(flushMatrixBuffer);
GL11.glMultMatrix(flushMatrixBuffer);
GLStateManager.getMatrixStack().mul(matrix);
}
return;
}
relativeTransform.mul(matrix);
matrixGeneration++;
if (pendingTransformOps != null) {
pendingTransformOps.add("glMultMatrixf(...)");
}
}
// Reusable matrix for ortho/frustum computation
private static final Matrix4f orthoFrustumTemp = new Matrix4f();
/** Accumulate ortho projection into relativeTransform. */
public static void updateRelativeTransformOrtho(double left, double right, double bottom, double top, double zNear, double zFar) {
if (relativeTransform == null) return;
orthoFrustumTemp.identity().ortho((float) left, (float) right, (float) bottom, (float) top, (float) zNear, (float) zFar);
if (DEBUG_DISPLAY_LISTS) {
if (currentRecorder != null) currentRecorder.recordMultMatrix(orthoFrustumTemp);
if (glListMode == GL11.GL_COMPILE_AND_EXECUTE) {
flushMatrixBuffer.clear();
orthoFrustumTemp.get(flushMatrixBuffer);
GL11.glMultMatrix(flushMatrixBuffer);
GLStateManager.getMatrixStack().mul(orthoFrustumTemp);
}
return;
}
relativeTransform.mul(orthoFrustumTemp);
matrixGeneration++;
if (pendingTransformOps != null) {
pendingTransformOps.add(String.format("glOrtho(%.4f, %.4f, %.4f, %.4f, %.4f, %.4f)", left, right, bottom, top, zNear, zFar));
}
}
/** Accumulate frustum projection into relativeTransform. */
public static void updateRelativeTransformFrustum(double left, double right, double bottom, double top, double zNear, double zFar) {
if (relativeTransform == null) return;
orthoFrustumTemp.identity().frustum((float) left, (float) right, (float) bottom, (float) top, (float) zNear, (float) zFar);
if (DEBUG_DISPLAY_LISTS) {
if (currentRecorder != null) currentRecorder.recordMultMatrix(orthoFrustumTemp);
if (glListMode == GL11.GL_COMPILE_AND_EXECUTE) {
flushMatrixBuffer.clear();
orthoFrustumTemp.get(flushMatrixBuffer);
GL11.glMultMatrix(flushMatrixBuffer);
GLStateManager.getMatrixStack().mul(orthoFrustumTemp);
}
return;
}
relativeTransform.mul(orthoFrustumTemp);
matrixGeneration++;
if (pendingTransformOps != null) {
pendingTransformOps.add(String.format("glFrustum(%.4f, %.4f, %.4f, %.4f, %.4f, %.4f)", left, right, bottom, top, zNear, zFar));
}
}
/**
* Reset the relative transform to identity during display list compilation.
* Called by GLStateManager.glLoadMatrix() - after loading an absolute matrix,
* subsequent transforms are relative to that loaded matrix (i.e., start from identity).
*/
public static void resetRelativeTransform() {
if (relativeTransform == null) {
return;
}
relativeTransform.identity();
}
/**
* Check if a display list exists (has been compiled and stored).
* Checks both DisplayListManager's cache and VBOManager for GTNHLib compatibility.
*
* @param list The display list ID to check
* @return true if the display list exists, false otherwise
*/
public static boolean displayListExists(int list) {
if (displayListCache.containsKey(list)) {
return true;
}
// Check VBOManager for GTNHLib compatibility (negative IDs)
if (list < -1) {
return VBOManager.get(list) != null;
}
return false;
}
/**
* Get a compiled display list from the cache.
*
* @param list The display list ID
* @return The CompiledDisplayList, or null if not found
*/
public static CompiledDisplayList getDisplayList(int list) {
return displayListCache.get(list);
}
/**
* Start display list compilation.
* Supports nested glNewList() calls (spec-violating but needed for mod compatibility).
* GL_COMPILE: Commands are recorded only (not executed), GLSM cache unchanged
* GL_COMPILE_AND_EXECUTE: Commands are recorded AND executed (GLSM cache updated)
*/
public static void glNewList(int list, int mode) {
// Assert main thread for display list compilation
if (!Thread.currentThread().equals(GLStateManager.getMainThread())) {
throw new IllegalStateException("Display list compilation must happen on main thread");
}
// Handle nested compilation - push current context onto stack
final boolean isNested = glListMode > 0;
if (isNested) {
// Nested display list compilation violates OpenGL spec, but some of our optimizations require it
// Save current compilation context and start fresh for nested list
final CompilationContext parentContext = new CompilationContext(
glListId, glListMode, currentRecorder, accumulatedDraws, accumulatedLineDraws,
accumulatedPrimitiveDraws, relativeTransform,
tessellatorCompiling, immediateModeRecorder, compilationStackTrace,
pendingTransformOps, multMatrixSources, drawRangeSources
);
compilationStack.push(parentContext);
}
// Initialize fresh context for this (possibly nested) list
glListId = list;
glListMode = mode;
recordingThread = Thread.currentThread(); // Track which thread is recording
currentRecorder = new CommandRecorder(); // Create command recorder
accumulatedDraws = new ArrayList<>(64); // Fewer draws than commands typically
accumulatedLineDraws = new ArrayList<>(16); // Immediate mode line draws are less common
accumulatedPrimitiveDraws = new ArrayList<>(16); // Tessellator primitive draws are less common
relativeTransform = new Matrix4fStack(GLStateManager.MAX_MODELVIEW_STACK_DEPTH);
relativeTransform.identity(); // Delta from current GL state, starts at identity
lastFlushedGeneration = -1; // Reset so first draw triggers flush
lastFlushedTransform = null; // Will be set on first flush
stateGeneration = 0; // Reset state generation for fresh list
immediateModeRecorder = new ImmediateModeRecorder(); // For glBegin/glEnd/glVertex
compilationStackTrace = LOG_DISPLAY_LIST_COMPILATION ? Thread.currentThread().getStackTrace() : null;
// Initialize debug logging fields (only when logging enabled)
if (LOG_DISPLAY_LIST_COMPILATION) {
pendingTransformOps = new ArrayList<>();
multMatrixSources = new ArrayList<>();
drawRangeSources = new ArrayList<>();
} else {
pendingTransformOps = null;
multMatrixSources = null;
drawRangeSources = null;
}
// Start compiling mode with per-draw callback (works for both root and nested lists now)
// Callback receives quads (GL_QUADS) and primitives (GL_TRIANGLES, GL_LINES, etc.)
TessellatorManager.setCompiling((quads, primitives, flags) -> {
final boolean hasQuads = !quads.isEmpty();
final boolean hasPrimitives = !primitives.isEmpty();
// Early exit to avoid allocations when nothing to accumulate
if (!hasQuads && !hasPrimitives) {
return;
}
if (matrixGeneration != lastFlushedGeneration) {
if (lastFlushedTransform == null) {
lastFlushedTransform = new Matrix4f();
}
lastFlushedTransform.set(relativeTransform);
flushMatrix();
lastFlushedGeneration = matrixGeneration;
}
final Matrix4f currentTransform = new Matrix4f(lastFlushedTransform);
final int currentGeneration = matrixGeneration;
final int currentBatchId = stateGeneration;
final int cmdIndex = getCommandCount();
// Accumulate quads for batching at glEndList()
if (hasQuads) {
accumulatedDraws.add(new AccumulatedDraw(quads, currentTransform, flags, cmdIndex, currentGeneration, currentBatchId));
}
// Accumulate primitives (lines, triangles) for batching at glEndList()
if (hasPrimitives) {
accumulatedPrimitiveDraws.add(new AccumulatedPrimitiveDraw(primitives, currentTransform, flags, cmdIndex, currentGeneration, currentBatchId));
}
});
tessellatorCompiling = true;
// We hijack display list compilation completely - no GL11.glNewList() calls
}
/**
* End display list compilation and build optimized/unoptimized versions.
*/
public static void glEndList() {
if (glListMode == 0) {
throw new RuntimeException("glEndList called outside of a display list!");
}
flushMatrix();
final boolean isNested = !compilationStack.isEmpty();
// Stop compiling mode (works for both root and nested lists now)
if (tessellatorCompiling) {
TessellatorManager.stopCompiling();
tessellatorCompiling = false;
}
final CompiledDisplayList compiled;
// Create CompiledDisplayList with both unoptimized and optimized versions
final CommandBuffer rawCommandBuffer = currentRecorder != null ? currentRecorder.getBuffer() : null;
final boolean hasCommands = rawCommandBuffer != null && rawCommandBuffer.size() > 0;
final boolean hasDraws = accumulatedDraws != null && !accumulatedDraws.isEmpty();
final boolean hasLineDraws = accumulatedLineDraws != null && !accumulatedLineDraws.isEmpty();
final boolean hasPrimitiveDraws = accumulatedPrimitiveDraws != null && !accumulatedPrimitiveDraws.isEmpty();
if (hasCommands || hasDraws || hasLineDraws || hasPrimitiveDraws) {
// Phase 1: Compile format-based VBOs (shared by both optimized and unoptimized paths)
final Map<CapturingTessellator.Flags, CompiledFormatBuffer> compiledQuadBuffers = compileFormatBasedVBOs(accumulatedDraws);
// Phase 2: Compile immediate mode line VBO (shared by both paths)
final CompiledLineBuffer compiledLineBuffer = compileLineBuffer(accumulatedLineDraws);
// Phase 3: Compile tessellator primitive VBOs (lines, triangles) - grouped by format
final Map<CapturingTessellator.Flags, CompiledPrimitiveBuffers> compiledPrimitiveBuffers = compilePrimitiveBuffers(accumulatedPrimitiveDraws);
// Collect all owned VBOs (quads + immediate mode lines + tessellator primitives)
final VertexBuffer[] ownedVbos = extractOwnedVbos(compiledQuadBuffers, compiledLineBuffer, compiledPrimitiveBuffers);
// Build to CommandBuffer - optimize raw buffer to final buffer
final CommandBuffer finalBuffer = new CommandBuffer();
if (DEBUG_DISPLAY_LISTS) {
CommandBufferBuilder.buildUnoptimizedFromRawBuffer(rawCommandBuffer, compiledQuadBuffers, compiledLineBuffer, compiledPrimitiveBuffers, ownedVbos, finalBuffer);
} else {
CommandBufferBuilder.buildOptimizedFromRawBuffer(rawCommandBuffer, compiledQuadBuffers, compiledLineBuffer, compiledPrimitiveBuffers, ownedVbos, glListId, finalBuffer);
}
// Free the recorder (and its buffer) after optimization
currentRecorder.free();
compiled = new CompiledDisplayList(finalBuffer.toBuffer(), finalBuffer.getComplexObjects(), ownedVbos);
} else {
// Free the recorder even if empty
if (currentRecorder != null) {
currentRecorder.free();
}
// Empty display list - per OpenGL spec, still valid after glNewList/glEndList
compiled = CompiledDisplayList.EMPTY;
}
// Store the compiled list (even if empty - an empty list is still a valid list)
displayListCache.put(glListId, compiled);
// Log compilation details if enabled (before context restoration changes glListId)
if (LOG_DISPLAY_LIST_COMPILATION) {
logCompiledDisplayList(glListId, compiled, compilationStackTrace);
}
// Handle nested compilation - restore parent context
if (isNested) {
final CompilationContext parentContext = compilationStack.pop();
// Restore parent context
glListId = parentContext.listId;
glListMode = parentContext.listMode;
currentRecorder = parentContext.recorder;
accumulatedDraws = parentContext.draws;
accumulatedLineDraws = parentContext.lineDraws;
accumulatedPrimitiveDraws = parentContext.primitiveDraws;
relativeTransform = parentContext.transform;
tessellatorCompiling = parentContext.wasTessellatorCompiling;
immediateModeRecorder = parentContext.immediateRecorder;
compilationStackTrace = parentContext.stackTrace;
pendingTransformOps = parentContext.pendingOps;
multMatrixSources = parentContext.matrixSources;
drawRangeSources = parentContext.drawSources;
// Note: TessellatorManager callback stack was popped by stopCompiling()
// Parent's COMPILING callback is now active again
} else {
// Not nested - clear all compilation state
currentRecorder = null;
recordingThread = null;
accumulatedDraws = null;
accumulatedLineDraws = null;
accumulatedPrimitiveDraws = null;
relativeTransform = null;
immediateModeRecorder = null;
compilationStackTrace = null;
pendingTransformOps = null;
multMatrixSources = null;
drawRangeSources = null;
glListId = -1;
glListMode = 0;
}
}
/**
* Execute a compiled display list.
*/
public static void glCallList(int list) {
if (currentRecorder != null) {
recordCallList(list);
if (glListMode == GL11.GL_COMPILE) {
return;
}
}
final CompiledDisplayList compiled = displayListCache.get(list);
if (compiled != null) {
GLStateManager.trySyncProgram();
final int prevList = currentRenderingList;
currentRenderingList = list;
compiled.render();
currentRenderingList = prevList;
return;
}
// Fall back to VBOManager or legacy display list
if (list < 0) {
// Negative IDs are VBOManager space (entity models, etc.)
final VertexBuffer vbo = VBOManager.get(list);
if (vbo != null) {
vbo.render();
}
// Per OpenGL spec: if list is undefined, glCallList has no effect
} else {
// Positive IDs - fall back to native GL display lists
// This happens for lists allocated but never compiled via glNewList
GLStateManager.trySyncProgram();
GL11.glCallList(list);
}
}
/**
* Delete display lists and free their VBO resources.
*/
public static void glDeleteLists(int list, int range) {
for (int i = list; i < list + range; i++) {
CompiledDisplayList compiled = displayListCache.remove(i);
if (compiled != null) {
compiled.delete();
}
}
// Also call legacy glDeleteLists for any lists we didn't handle
GL11.glDeleteLists(list, range);
}
/**
* Compile format-based VBOs from accumulated draws.
* Groups draws by vertex format and compiles each format's geometry into a single VBO.
* Both optimized and unoptimized paths share these VBOs.
*
* @param accumulatedDraws The accumulated draws to compile
* @return Map from format flags to compiled buffers (VBO + ranges)
*/
private static Map<CapturingTessellator.Flags, CompiledFormatBuffer> compileFormatBasedVBOs(
List<AccumulatedDraw> accumulatedDraws) {
if (accumulatedDraws == null || accumulatedDraws.isEmpty()) {
return Collections.emptyMap();
}
// Group draws by vertex format
final Map<CapturingTessellator.Flags, FormatBuffer> formatBuffers = new HashMap<>();
for (AccumulatedDraw draw : accumulatedDraws) {
formatBuffers.computeIfAbsent(draw.flags, FormatBuffer::new).addDraw(draw);
}
// Compile each format's geometry into a single VBO
final Map<CapturingTessellator.Flags, CompiledFormatBuffer> compiled = new HashMap<>();
for (var entry : formatBuffers.entrySet()) {
compiled.put(entry.getKey(), entry.getValue().finish());
}
return compiled;
}
/**
* Compile line draws into a shared VBO.
*
* @param lineDraws The accumulated line draws
* @return Compiled line buffer, or null if no lines
*/
private static CompiledLineBuffer compileLineBuffer(List<AccumulatedLineDraw> lineDraws) {
if (lineDraws == null || lineDraws.isEmpty()) {
return null;
}
final LineBuffer buffer = new LineBuffer();
for (AccumulatedLineDraw draw : lineDraws) {
buffer.addDraw(draw);
}
return buffer.finish();
}
/**
* Extract owned VBOs from compiled buffers (quads + lines).
* These VBOs are shared by both optimized and unoptimized paths.
*
* @param compiledQuadBuffers The compiled quad format buffers
* @param compiledLineBuffer The compiled line buffer (may be null)
* @return Array of VBOs that need to be deleted when the display list is deleted
*/
private static VertexBuffer[] extractOwnedVbos(
Map<CapturingTessellator.Flags, CompiledFormatBuffer> compiledQuadBuffers,
CompiledLineBuffer compiledLineBuffer,
Map<CapturingTessellator.Flags, CompiledPrimitiveBuffers> compiledPrimitiveBuffers) {
final List<VertexBuffer> vbos = new ArrayList<>();
// Add quad VBOs
final CompiledFormatBuffer[] quadBufferArray = compiledQuadBuffers.values().toArray(new CompiledFormatBuffer[0]);
for (int i = 0; i < quadBufferArray.length; i++) {
vbos.add(quadBufferArray[i].vbo());
}
// Add immediate mode line VBO if present
if (compiledLineBuffer != null) {
vbos.add(compiledLineBuffer.vbo());
}
// Add tessellator primitive VBOs if present (one per format, separate for lines/triangles)
if (!compiledPrimitiveBuffers.isEmpty()) {
final CompiledPrimitiveBuffers[] primBufferArray = compiledPrimitiveBuffers.values().toArray(new CompiledPrimitiveBuffers[0]);
for (int i = 0; i < primBufferArray.length; i++) {
final CompiledPrimitiveBuffers primBuffers = primBufferArray[i];
if (primBuffers.hasLines()) {
vbos.add(primBuffers.lineVbo());
}
if (primBuffers.hasTriangles()) {
vbos.add(primBuffers.triangleVbo());
}
}
}
return vbos.toArray(new VertexBuffer[0]);
}
/**
* Compile tessellator primitives (lines, triangles) into format-based VBOs.
* Groups draws by vertex format for optimal memory usage.
*
* @param primitiveDraws The accumulated primitive draws from tessellator callback
* @return Map of flags to compiled primitive buffers, empty map if no primitives
*/
private static Map<CapturingTessellator.Flags, CompiledPrimitiveBuffers> compilePrimitiveBuffers(
List<AccumulatedPrimitiveDraw> primitiveDraws) {
if (primitiveDraws == null || primitiveDraws.isEmpty()) {
return Collections.emptyMap();
}
// Group draws by vertex format
final Map<CapturingTessellator.Flags, TessellatorPrimitiveBuffer> formatBuffers = new HashMap<>();
final int size = primitiveDraws.size();
for (int i = 0; i < size; i++) {
final AccumulatedPrimitiveDraw draw = primitiveDraws.get(i);
formatBuffers.computeIfAbsent(draw.flags, TessellatorPrimitiveBuffer::new).addDraw(draw);
}
// Compile each format's geometry into VBOs
final Map<CapturingTessellator.Flags, CompiledPrimitiveBuffers> compiled = new HashMap<>();
@SuppressWarnings("unchecked")
final Map.Entry<CapturingTessellator.Flags, TessellatorPrimitiveBuffer>[] entries =
formatBuffers.entrySet().toArray(new Map.Entry[0]);
for (int i = 0; i < entries.length; i++) {
final Map.Entry<CapturingTessellator.Flags, TessellatorPrimitiveBuffer> entry = entries[i];
final CompiledPrimitiveBuffers result = entry.getValue().finish();
if (result != null) {
compiled.put(entry.getKey(), result);
}
}
return compiled;
}
// ==================== Buffer-to-Buffer Optimization ====================
/**
* Build optimized command list using pre-compiled VBOs.
* Uses mergedRanges (consecutive same-transform draws combined) and collapses MODELVIEW transforms.
* (Package-private for testing)
*
* @param currentCommands Original matrix/state commands
* @param compiledQuadBuffers Pre-compiled format-based quad VBOs
* @param compiledLineBuffer Pre-compiled line VBO (may be null)
* @param glListId Display list ID for logging
* @return Optimized command array
*/
static DisplayListCommand[] buildOptimizedCommands(
List<DisplayListCommand> currentCommands,
Map<CapturingTessellator.Flags, CompiledFormatBuffer> compiledQuadBuffers,
CompiledLineBuffer compiledLineBuffer,
Map<CapturingTessellator.Flags, CompiledPrimitiveBuffers> compiledPrimitiveBuffers,
int glListId) {
final List<DisplayListCommand> optimized = new ArrayList<>();
final TransformOptimizer transformOpt = new TransformOptimizer(glListId);
// Collect all merged draw ranges (quads + lines + primitives) sorted by command index
final List<DrawRangeWithBuffer> allRanges = CommandBufferBuilder.collectDrawRanges(
compiledQuadBuffers, compiledLineBuffer, compiledPrimitiveBuffers);
// Process command stream with interleaved draws
final OptimizationContextImpl ctx = new OptimizationContextImpl(transformOpt, optimized);
int rangeIndex = 0;
for (int i = 0; i < currentCommands.size(); i++) {
// Emit draw ranges (quads and lines) at this command position
while (rangeIndex < allRanges.size() && allRanges.get(rangeIndex).range().commandIndex() == i) {
emitDrawRangeLegacy(allRanges.get(rangeIndex++), transformOpt, optimized);
}
// Process the original command
final DisplayListCommand cmd = currentCommands.get(i);
if (cmd.handleOptimization(ctx)) {
optimized.add(cmd);
}
}
// Emit remaining draw ranges at end of command stream
while (rangeIndex < allRanges.size()) {
emitDrawRangeLegacy(allRanges.get(rangeIndex++), transformOpt, optimized);
}
// Emit residual transform to match expected GL state
if (!transformOpt.isIdentity()) {
transformOpt.emitPendingTransform(optimized);
}
return optimized.toArray(new DisplayListCommand[0]);
}
/**
* Build optimized display list: batches draws with same flags, collapses MODELVIEW transforms.
* Instead of baking transforms into vertices, we emit collapsed MultMatrix commands at barriers.
* This properly handles nested display lists (CallList) which need GL state to be correct.
*
* <p>Transform collapsing strategy:
* <ul>
* <li>Track accumulated MODELVIEW transform during command stream analysis</li>
* <li>At barriers (Draw, CallList), emit a single MultMatrix if transform changed</li>
* <li>Push/Pop maintain proper stack semantics</li>
* <li>Vertices stay canonical (untransformed) in VBOs</li>
* </ul>
*/
// Package-private for testing
static OptimizedListResult buildOptimizedDisplayList(
List<DisplayListCommand> currentCommands,
List<AccumulatedDraw> accumulatedDraws,
List<AccumulatedPrimitiveDraw> accumulatedPrimitiveDraws,
int glListId) {
// Compile quad VBOs
final Map<CapturingTessellator.Flags, CompiledFormatBuffer> compiledQuadBuffers = compileFormatBasedVBOs(accumulatedDraws);
// Compile tessellator primitive VBOs (lines, triangles) - grouped by format
final Map<CapturingTessellator.Flags, CompiledPrimitiveBuffers> compiledPrimitiveBuffers = compilePrimitiveBuffers(accumulatedPrimitiveDraws);
// Extract owned VBOs (quads + primitives, no immediate mode lines in test path)
final VertexBuffer[] ownedVbos = extractOwnedVbos(compiledQuadBuffers, null, compiledPrimitiveBuffers);
// Build optimized commands using the new unified path
final DisplayListCommand[] optimized = buildOptimizedCommands(currentCommands, compiledQuadBuffers, null, compiledPrimitiveBuffers, glListId);
return new OptimizedListResult(optimized, ownedVbos);
}
/**
* Emit a draw range command for the legacy path (testing).
* Uses delta-based transform emission via TransformOptimizer.
*/
private static void emitDrawRangeLegacy(DrawRangeWithBuffer drwb, TransformOptimizer transformOpt,
List<DisplayListCommand> output) {
final DrawRange range = drwb.range();
// Delta-based: only emit MultMatrix if transform differs from last emitted
if (transformOpt.needsTransformForDraw(range.transform())) {
transformOpt.emitTransformTo(output, range.transform());
}
output.add(new com.gtnewhorizons.angelica.glsm.recording.commands.DrawRangeCmd(
drwb.vbo(),
range.startVertex(),
range.vertexCount(),
drwb.hasBrightness()
));
}
/**
* Implementation of OptimizationContext that wraps transform optimizer.
*/
@Desugar
private record OptimizationContextImpl(
TransformOptimizer transformOpt,
List<DisplayListCommand> output
) implements OptimizationContext {
@Override public Matrix4f getAccumulatedTransform() { return transformOpt.getAccumulated(); }
@Override public void loadIdentity() { transformOpt.loadIdentity(); }
@Override public void pushTransform() { transformOpt.pushTransform(); }
@Override public void popTransform() { transformOpt.popTransform(); }
@Override public void emitPendingTransform() { transformOpt.emitPendingTransform(output); }
@Override public void emitTransformTo(Matrix4f target) { transformOpt.emitTransformTo(output, target); }
@Override public void emit(DisplayListCommand cmd) { output.add(cmd); }
@Override public void markAbsoluteMatrix() { transformOpt.markAbsoluteMatrix(); }
@Override public boolean checkAndClearAbsoluteMatrix() { return transformOpt.checkAndClearAbsoluteMatrix(); }
}
/**
* Selects the optimal VertexFormat from GTNHLib defaults based on actual attribute usage.
* This reduces memory usage by excluding unused attributes.
*/
static VertexFormat selectOptimalFormat(CapturingTessellator.Flags flags) {
final boolean hasColor = flags.hasColor;
final boolean hasTexture = flags.hasTexture;
final boolean hasBrightness = flags.hasBrightness;
final boolean hasNormals = flags.hasNormals;
final VertexFormat format;
// Map flags to GTNHLib formats, ordered by guess at frequency/likelihood
if (!hasColor && hasTexture && !hasBrightness && !hasNormals) {
format = DefaultVertexFormat.POSITION_TEXTURE; // Entity models, common
} else if (!hasColor && !hasTexture && !hasBrightness && !hasNormals) {
format = DefaultVertexFormat.POSITION; // Sky rendering, simple geometry
} else if (hasColor && hasTexture && !hasBrightness && !hasNormals) {
format = DefaultVertexFormat.POSITION_COLOR_TEXTURE; // Colored blocks/UI
} else if (!hasColor && hasTexture && hasBrightness && hasNormals) {
format = DefaultVertexFormat.POSITION_TEXTURE_LIGHT_NORMAL; // BuildCraft fluids
} else if (!hasColor && hasTexture && !hasBrightness && hasNormals) {
format = DefaultVertexFormat.POSITION_TEXTURE_NORMAL; // Lit geometry with normals
} else if (hasColor && hasTexture && hasBrightness && !hasNormals) {
format = DefaultVertexFormat.POSITION_COLOR_TEX_LIGHTMAP; // Colored lit blocks
} else if (hasColor && !hasTexture && !hasBrightness && !hasNormals) {
format = DefaultVertexFormat.POSITION_COLOR; // Colored lines/particles
} else {
format = DefaultVertexFormat.POSITION_COLOR_TEXTURE_LIGHT_NORMAL; // Full format fallback
}
return format;
}
/**
* Compile captured Tessellator quads into a VertexBuffer (VAO or VBO).
* Uses VertexBuffer for proper compatibility with fixed-function pipeline.
*
* @param quads The quads to compile
* @param flags The vertex attribute flags
* @return The uploaded VertexBuffer
*/
static VertexBuffer compileQuads(List<ModelQuadViewMutable> quads, CapturingTessellator.Flags flags) {
// Select optimal predefined format from GTNHLib
final VertexFormat format = selectOptimalFormat(flags);
// Use VAOManager to create VAO with optimal format (falls back to VBO if unsupported)
final VertexBuffer vao = VAOManager.createVAO(format, GL11.GL_QUADS);
final ByteBuffer buffer = CapturingTessellator.quadsToBuffer(quads, format);
vao.upload(buffer);
return vao;
}
// ==================== DEBUG LOGGING ====================
private static void logCompiledDisplayList(int listId, CompiledDisplayList compiled, StackTraceElement[] stackTrace) {
final StringBuilder sb = new StringBuilder();
sb.append("\n========== Display List Compiled: ID=").append(listId).append(" ==========\n");
// Identify probable source mod from stack trace
sb.append("Source: ").append(identifySourceFromStackTrace(stackTrace)).append("\n");
// Log commands if not empty
if (compiled == CompiledDisplayList.EMPTY) {
sb.append("Contents: EMPTY (no commands or draws)\n");
} else {
final ByteBuffer buffer = compiled.getCommandBuffer();
if (buffer == null || buffer.limit() == 0) {
sb.append("Contents: No commands\n");
} else {
sb.append("Commands (").append(buffer.limit()).append(" bytes):\n");
dumpCommandBuffer(buffer, compiled.getComplexObjects(), compiled.getOwnedVbos(), sb);
}
}
// Log full stack trace
sb.append("\nFull Stack Trace:\n");
if (stackTrace != null) {
for (StackTraceElement element : stackTrace) {
sb.append(" at ").append(element.toString()).append("\n");
}
} else {
sb.append(" (not captured)\n");
}
sb.append("========== End Display List ").append(listId).append(" ==========\n");
LOGGER.debug(sb.toString());
}
private static String identifySourceFromStackTrace(StackTraceElement[] stackTrace) {
if (stackTrace == null || stackTrace.length == 0) {
return "Unknown (no stack trace)";
}
for (StackTraceElement element : stackTrace) {
final String className = element.getClassName();
// Skip Java/LWJGL/Angelica/Minecraft internals
if (className.startsWith("java.") || className.startsWith("sun.") ||
className.startsWith("jdk.") ||
className.startsWith("org.lwjgl.") ||
className.startsWith("com.gtnewhorizons.angelica.") ||
className.startsWith("com.gtnewhorizon.gtnhlib.") ||
className.startsWith("net.minecraft.") ||
className.startsWith("net.minecraftforge.") ||
className.contains("GLStateManager") ||
className.contains("GradleStart") ||
className.contains("launchwrapper") ||
className.contains("retrofuturabootstrap")) {
continue;
}
// Try to extract mod name from package
final String modGuess = guessModFromClassName(className);
return modGuess + " (" + element.getClassName() + "." + element.getMethodName() +
":" + element.getLineNumber() + ")";
}
// Fallback: return the first non-internal frame with class info
for (StackTraceElement element : stackTrace) {
final String className = element.getClassName();
if (!className.startsWith("java.") && !className.startsWith("sun.") && !className.startsWith("jdk.")) {
return guessModFromClassName(className) + " (" + element + ")";
}
}
return "Unknown";
}
private static String guessModFromClassName(String className) {
final String lc = className.toLowerCase();
// Common mod package patterns (use lowercase for matching)
if (lc.contains("buildcraft")) return "BuildCraft";
if (lc.contains("cofh")) return "CoFH/ThermalExpansion";
if (lc.contains(".ic2.") || lc.startsWith("ic2.")) return "IndustrialCraft2";
if (lc.contains("gregtech")) return "GregTech";
if (lc.contains("thaumcraft")) return "Thaumcraft";
if (lc.contains("forestry")) return "Forestry";
if (lc.contains("appeng") || lc.contains(".ae2.")) return "Applied Energistics 2";
if (lc.contains("enderio") || lc.contains("crazypants.ender")) return "EnderIO";
if (lc.contains("mekanism")) return "Mekanism";
if (lc.contains("tconstruct")) return "Tinkers Construct";
if (lc.contains("chisel")) return "Chisel";
if (lc.contains("opencomputers") || lc.contains("li.cil.oc")) return "OpenComputers";
if (lc.contains("computercraft") || lc.contains("dan200.computer")) return "ComputerCraft";
if (lc.contains("railcraft")) return "Railcraft";
if (lc.contains("projectred") || lc.contains("mrtjpcore")) return "Project Red";
if (lc.contains("botania")) return "Botania";
if (lc.contains("extrautil")) return "ExtraUtilities";
if (lc.contains("openblocks")) return "OpenBlocks";
if (lc.contains("carpenters")) return "Carpenters Blocks";
if (lc.contains("biomesoplenty")) return "Biomes O Plenty";
if (lc.contains("natura")) return "Natura";
if (lc.contains("twilightforest")) return "Twilight Forest";
if (lc.contains("immersive")) return "Immersive Engineering";
if (lc.contains("galacticraft")) return "Galacticraft";
if (lc.contains("draconicevolution")) return "Draconic Evolution";
if (lc.contains("net.minecraft")) return "Minecraft";
// Extract first 2 package segments as fallback
final String[] parts = className.split("\\.");
if (parts.length >= 2) {
return parts[0] + "." + parts[1];
}
return className;
}
private static void dumpCommandBuffer(ByteBuffer buffer, Object[] complexObjects, VertexBuffer[] ownedVbos, StringBuilder sb) {
if (buffer == null) return;
final long basePtr = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAddress(buffer);
long ptr = basePtr;
final long end = basePtr + buffer.limit();
int cmdNum = 0;
int multMatrixIdx = 0; // Index into multMatrixSources for source tracking
int drawRangeIdx = 0; // Index into drawRangeSources for source tracking
while (ptr < end) {
final int opcode = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr);
final String cmdName = GLCommand.getName(opcode);
sb.append(" ").append(cmdNum++).append(": ").append(cmdName);
// Add command-specific details
switch (opcode) {
case GLCommand.ENABLE, GLCommand.DISABLE -> {
final int cap = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 4);
sb.append("(").append(GLDebug.getCapabilityName(cap)).append(")");
ptr += 8;
}
case GLCommand.BIND_TEXTURE -> {
final int target = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 4);
final int texture = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 8);
sb.append("(target=").append(target).append(", texture=").append(texture).append(")");
ptr += 12;
}
case GLCommand.DRAW_RANGE -> {
final int vboIdx = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 4);
final int start = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 8);
final int count = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 12);
final int brightness = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 16);
sb.append("(vbo=").append(vboIdx).append(", start=").append(start)
.append(", count=").append(count).append(", brightness=").append(brightness != 0).append(")");
// Show draw source if available
if (drawRangeSources != null && drawRangeIdx < drawRangeSources.size()) {
sb.append(" [from: ").append(drawRangeSources.get(drawRangeIdx)).append("]");
}
drawRangeIdx++;
ptr += 20;
}
case GLCommand.MULT_MATRIX, GLCommand.LOAD_MATRIX -> {
// Show source ops if available (only for MULT_MATRIX from recording phase)
if (opcode == GLCommand.MULT_MATRIX && multMatrixSources != null && multMatrixIdx < multMatrixSources.size()) {
final List<String> sources = multMatrixSources.get(multMatrixIdx);
sb.append(" [from: ").append(String.join(" -> ", sources)).append("]");
}
multMatrixIdx++;
ptr += 68; // cmd + 16 floats
}
case GLCommand.COLOR -> {
final float r = Float.intBitsToFloat(com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 4));
final float g = Float.intBitsToFloat(com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 8));
final float b = Float.intBitsToFloat(com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 12));
final float a = Float.intBitsToFloat(com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 16));
sb.append("(").append(r).append(", ").append(g).append(", ").append(b).append(", ").append(a).append(")");
ptr += 20;
}
case GLCommand.DEPTH_MASK -> {
final int flag = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 4);
sb.append("(").append(flag != 0).append(")");
ptr += 8;
}
case GLCommand.BLEND_FUNC -> {
final int srcRgb = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 4);
final int dstRgb = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 8);
final int srcAlpha = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 12);
final int dstAlpha = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 16);
sb.append("(srcRgb=").append(srcRgb).append(", dstRgb=").append(dstRgb)
.append(", srcAlpha=").append(srcAlpha).append(", dstAlpha=").append(dstAlpha).append(")");
ptr += 20;
}
case GLCommand.CALL_LIST -> {
final int calledList = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 4);
sb.append("(").append(calledList).append(")");
ptr += 8;
}
case GLCommand.MATRIX_MODE -> {
final int mode = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 4);
sb.append("(").append(mode == GL11.GL_MODELVIEW ? "MODELVIEW" : mode == GL11.GL_PROJECTION ? "PROJECTION" : mode).append(")");
ptr += 8;
}
case GLCommand.PUSH_MATRIX, GLCommand.POP_MATRIX, GLCommand.LOAD_IDENTITY -> ptr += 4;
case GLCommand.COMPLEX_REF -> {
final int idx = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 4);
final Object obj = complexObjects != null && idx < complexObjects.length ? complexObjects[idx] : null;
sb.append("(idx=").append(idx).append(", type=").append(obj != null ? obj.getClass().getSimpleName() : "null").append(")");
ptr += 8;
}
default -> {
// Skip based on command size (from CompiledDisplayList.getCommandSize logic)
ptr += getCommandSize(opcode, ptr);
}
}
sb.append("\n");
}
}
/**
* Get the size of a command in bytes for buffer iteration.
*/
private static int getCommandSize(int cmd, long ptr) {
return switch (cmd) {
case GLCommand.LOAD_IDENTITY, GLCommand.PUSH_MATRIX, GLCommand.POP_MATRIX -> 4;
case GLCommand.ENABLE, GLCommand.DISABLE, GLCommand.CLEAR, GLCommand.CLEAR_STENCIL,
GLCommand.CULL_FACE, GLCommand.DEPTH_FUNC, GLCommand.SHADE_MODEL, GLCommand.LOGIC_OP,
GLCommand.MATRIX_MODE, GLCommand.ACTIVE_TEXTURE, GLCommand.USE_PROGRAM,
GLCommand.PUSH_ATTRIB, GLCommand.POP_ATTRIB, GLCommand.STENCIL_MASK,
GLCommand.DEPTH_MASK, GLCommand.FRONT_FACE, GLCommand.POINT_SIZE, GLCommand.LINE_WIDTH,
GLCommand.CALL_LIST, GLCommand.COMPLEX_REF, GLCommand.DRAW_BUFFER -> 8;
case GLCommand.BIND_TEXTURE, GLCommand.POLYGON_MODE, GLCommand.COLOR_MATERIAL,
GLCommand.LINE_STIPPLE, GLCommand.STENCIL_MASK_SEPARATE, GLCommand.FOGI,
GLCommand.HINT, GLCommand.POLYGON_OFFSET, GLCommand.ALPHA_FUNC, GLCommand.FOGF,
GLCommand.LIGHT_MODELF, GLCommand.LIGHT_MODELI, GLCommand.CLEAR_DEPTH -> 12;
case GLCommand.STENCIL_FUNC, GLCommand.STENCIL_OP, GLCommand.TEX_PARAMETERI,
GLCommand.LIGHTF, GLCommand.LIGHTI, GLCommand.MATERIALF, GLCommand.TEX_PARAMETERF,
GLCommand.NORMAL -> 16;
case GLCommand.VIEWPORT, GLCommand.BLEND_FUNC, GLCommand.COLOR_MASK,
GLCommand.STENCIL_FUNC_SEPARATE, GLCommand.STENCIL_OP_SEPARATE,
GLCommand.COLOR, GLCommand.CLEAR_COLOR, GLCommand.BLEND_COLOR,
GLCommand.DRAW_RANGE -> 20;
case GLCommand.TRANSLATE, GLCommand.SCALE -> 28;
case GLCommand.ROTATE -> 36;
case GLCommand.ORTHO, GLCommand.FRUSTUM -> 52;
case GLCommand.MULT_MATRIX, GLCommand.LOAD_MATRIX -> 68;
case GLCommand.FOG, GLCommand.LIGHT_MODEL -> {
final int count = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 8);
yield 12 + count * 4;
}
case GLCommand.LIGHT, GLCommand.MATERIAL -> {
final int count = com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt(ptr + 12);
yield 16 + count * 4;
}
case GLCommand.DRAW_BUFFERS -> 40;
default -> 8; // Default to 8 bytes to avoid infinite loop
};
}
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\glsm\DrawRange.java
|
package com.gtnewhorizons.angelica.glsm;
import com.github.bsideup.jabel.Desugar;
import com.gtnewhorizons.angelica.glsm.recording.AccumulatedDraw;
import org.joml.Matrix4f;
/**
* Represents a vertex range within a shared VBO, along with its transform.
* Used during format-based batching to track where each draw's vertices are stored.
*
* <p>The restoreData field holds last vertex attributes for GL state restoration
* after VBO rendering (immediate mode draws only). Null for tessellator draws.
*/
@Desugar
public record DrawRange(
int startVertex,
int vertexCount,
Matrix4f transform,
int commandIndex,
AccumulatedDraw.RestoreData restoreData
) {
DrawRange(int startVertex, int vertexCount, Matrix4f transform, int commandIndex) {
this(startVertex, vertexCount, transform, commandIndex, null);
}
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\glsm\DrawRangeWithBuffer.java
|
package com.gtnewhorizons.angelica.glsm;
import com.github.bsideup.jabel.Desugar;
import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer;
/**
* Helper record pairing a DrawRange with its VBO and vertex format flags.
* Used for sorting ranges by command index while retaining VBO reference.
* Works for both quad ranges (from CompiledFormatBuffer) and line ranges (from CompiledLineBuffer).
*/
@Desugar
record DrawRangeWithBuffer(
DrawRange range,
VertexBuffer vbo,
CapturingTessellator.Flags flags,
DrawSource source
) {
boolean hasBrightness() {
return flags != null && flags.hasBrightness;
}
/**
* Source of a draw command for debug logging.
*/
enum DrawSource {
TESSELLATOR_QUADS("tessellator quads"),
TESSELLATOR_LINES("tessellator lines"),
TESSELLATOR_TRIANGLES("tessellator triangles"),
IMMEDIATE_MODE_LINES("immediate mode lines");
private final String description;
DrawSource(String description) {
this.description = description;
}
@Override
public String toString() {
return description;
}
}
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\glsm\Feature.java
|
package com.gtnewhorizons.angelica.glsm;
import com.google.common.collect.ImmutableSet;
import com.gtnewhorizon.gtnhlib.client.renderer.stacks.IStateStack;
import com.gtnewhorizons.angelica.glsm.stacks.BooleanStateStack;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class Feature {
private static final int[] supportedAttribs = new int[] { GL11.GL_ACCUM_BUFFER_BIT, GL11.GL_COLOR_BUFFER_BIT, GL11.GL_CURRENT_BIT, GL11.GL_DEPTH_BUFFER_BIT,
GL11.GL_ENABLE_BIT, GL11.GL_EVAL_BIT, GL11.GL_FOG_BIT, GL11.GL_HINT_BIT, GL11.GL_LIGHTING_BIT, GL11.GL_LINE_BIT, GL11.GL_LIST_BIT,
GL13.GL_MULTISAMPLE_BIT, GL11.GL_PIXEL_MODE_BIT, GL11.GL_POINT_BIT, GL11.GL_POLYGON_BIT, GL11.GL_POLYGON_STIPPLE_BIT, GL11.GL_SCISSOR_BIT,
GL11.GL_STENCIL_BUFFER_BIT, GL11.GL_TEXTURE_BIT, GL11.GL_TRANSFORM_BIT, GL11.GL_VIEWPORT_BIT };
static final Int2ObjectMap<List<IStateStack<?>>> maskToFeaturesMap = new Int2ObjectOpenHashMap<>();
static final Int2ObjectMap<IStateStack<?>[]> maskToNonBooleanStacksMap = new Int2ObjectOpenHashMap<>();
static List<IStateStack<?>> maskToFeatures(int mask) {
if(maskToFeaturesMap.containsKey(mask)) {
return maskToFeaturesMap.get(mask);
}
final Set<IStateStack<?>> features = new HashSet<>();
for(int attrib : Feature.supportedAttribs) {
if((mask & attrib) == attrib) {
features.addAll(getFeatures(attrib));
}
}
final List<IStateStack<?>> asList = new ArrayList<>(features);
maskToFeaturesMap.put(mask, asList);
return asList;
}
/**
* Returns only non-BooleanStateStack instances for the given mask.
* These use traditional push/pop without global depth tracking.
*/
static IStateStack<?>[] maskToNonBooleanStacks(int mask) {
IStateStack<?>[] cached = maskToNonBooleanStacksMap.get(mask);
if (cached != null) {
return cached;
}
final List<IStateStack<?>> all = maskToFeatures(mask);
final List<IStateStack<?>> nonBooleans = new ArrayList<>();
for (int i = 0; i < all.size(); i++) {
final IStateStack<?> stack = all.get(i);
if (!(stack instanceof BooleanStateStack)) {
nonBooleans.add(stack);
}
}
cached = nonBooleans.toArray(new IStateStack<?>[0]);
maskToNonBooleanStacksMap.put(mask, cached);
return cached;
}
private static final Map<Integer, Set<IStateStack<?>>> attribToFeatures = new HashMap<>();
/**
* Helper method to add all texture gen states (S, T, R, Q) for all texture units to a collection.
* Used by both GL_ENABLE_BIT and GL_TEXTURE_BIT.
*/
private static void addTextureGenStates(Set<IStateStack<?>> collection) {
for(int i = 0 ; i < GLStateManager.MAX_TEXTURE_UNITS; i++) {
collection.add(GLStateManager.textures.getTexGenSStates(i));
collection.add(GLStateManager.textures.getTexGenTStates(i));
collection.add(GLStateManager.textures.getTexGenRStates(i));
collection.add(GLStateManager.textures.getTexGenQStates(i));
}
}
static {
attribToFeatures.put(GL11.GL_COLOR_BUFFER_BIT, ImmutableSet.of(
GLStateManager.alphaTest // GL_ALPHA_TEST enable bit
, GLStateManager.alphaState // Alpha test function and reference value
, GLStateManager.blendMode // GL_BLEND enable bit
, GLStateManager.blendState // Blending source and destination functions
// Constant blend color
// Blending equation
, GLStateManager.colorLogicOpState // GL_COLOR_LOGIC_OP enable bit
, GLStateManager.ditherState // GL_DITHER enable bit
, GLStateManager.drawBuffer // GL_DRAW_BUFFER setting
, GLStateManager.indexLogicOpState // GL_INDEX_LOGIC_OP enable bit
// Logic op function
, GLStateManager.colorMask // Color-mode and index-mode writemasks
, GLStateManager.clearColor // Color-mode and index-mode clear values
));
attribToFeatures.put(GL11.GL_CURRENT_BIT, ImmutableSet.of(
GLStateManager.color // Current RGBA color
// Current color index
// Current normal vector
// Current texture coordinates
// Current raster position
// GL_CURRENT_RASTER_POSITION_VALID flag
// RGBA color associated with current raster position
// Color index associated with current raster position
// Texture coordinates associated with current raster position
// GL_EDGE_FLAG flag
));
attribToFeatures.put(GL11.GL_DEPTH_BUFFER_BIT, ImmutableSet.of(
GLStateManager.depthTest // GL_DEPTH_TEST enable bit
, GLStateManager.depthState // Depth buffer test function
// Depth buffer clear value
// GL_DEPTH_WRITEMASK enable bit
));
final HashSet<IStateStack<?>> enableBits = new HashSet<>(ImmutableSet.of(
GLStateManager.alphaTest // GL_ALPHA_TEST flag
, GLStateManager.autoNormalState // GL_AUTO_NORMAL flag
, GLStateManager.blendMode // GL_BLEND flag
, GLStateManager.colorLogicOpState // GL_COLOR_LOGIC_OP flag
, GLStateManager.colorMaterial // GL_COLOR_MATERIAL
, GLStateManager.cullState // GL_CULL_FACE flag
, GLStateManager.depthTest // GL_DEPTH_TEST flag
, GLStateManager.ditherState // GL_DITHER flag
, GLStateManager.fogMode // GL_FOG flag
, GLStateManager.indexLogicOpState // GL_INDEX_LOGIC_OP flag
, GLStateManager.lightStates[0] // GL_LIGHT0
, GLStateManager.lightStates[1] // GL_LIGHT1
, GLStateManager.lightStates[2] // GL_LIGHT2
, GLStateManager.lightStates[3] // GL_LIGHT3
, GLStateManager.lightStates[4] // GL_LIGHT4
, GLStateManager.lightStates[5] // GL_LIGHT5
, GLStateManager.lightStates[6] // GL_LIGHT6
, GLStateManager.lightStates[7] // GL_LIGHT7
, GLStateManager.lightingState // GL_LIGHTING flag
, GLStateManager.lineSmoothState // GL_LINE_SMOOTH flag
, GLStateManager.lineStippleState // GL_LINE_STIPPLE flag
, GLStateManager.map1Color4State // GL_MAP1_COLOR_4
, GLStateManager.map1IndexState // GL_MAP1_INDEX
, GLStateManager.map1NormalState // GL_MAP1_NORMAL
, GLStateManager.map1TextureCoord1State // GL_MAP1_TEXTURE_COORD_1
, GLStateManager.map1TextureCoord2State // GL_MAP1_TEXTURE_COORD_2
, GLStateManager.map1TextureCoord3State // GL_MAP1_TEXTURE_COORD_3
, GLStateManager.map1TextureCoord4State // GL_MAP1_TEXTURE_COORD_4
, GLStateManager.map1Vertex3State // GL_MAP1_VERTEX_3
, GLStateManager.map1Vertex4State // GL_MAP1_VERTEX_4
, GLStateManager.map2Color4State // GL_MAP2_COLOR_4
, GLStateManager.map2IndexState // GL_MAP2_INDEX
, GLStateManager.map2NormalState // GL_MAP2_NORMAL
, GLStateManager.map2TextureCoord1State // GL_MAP2_TEXTURE_COORD_1
, GLStateManager.map2TextureCoord2State // GL_MAP2_TEXTURE_COORD_2
, GLStateManager.map2TextureCoord3State // GL_MAP2_TEXTURE_COORD_3
, GLStateManager.map2TextureCoord4State // GL_MAP2_TEXTURE_COORD_4
, GLStateManager.map2Vertex3State // GL_MAP2_VERTEX_3
, GLStateManager.map2Vertex4State // GL_MAP2_VERTEX_4
, GLStateManager.multisampleState // GL_MULTISAMPLE flag
, GLStateManager.normalizeState // GL_NORMALIZE flag
, GLStateManager.pointSmoothState // GL_POINT_SMOOTH flag
, GLStateManager.polygonOffsetPointState // GL_POLYGON_OFFSET_POINT flag
, GLStateManager.polygonOffsetLineState // GL_POLYGON_OFFSET_LINE flag
, GLStateManager.polygonOffsetFillState // GL_POLYGON_OFFSET_FILL flag
, GLStateManager.polygonSmoothState // GL_POLYGON_SMOOTH flag
, GLStateManager.polygonStippleState // GL_POLYGON_STIPPLE flag
, GLStateManager.rescaleNormalState // GL_RESCALE_NORMAL flag
, GLStateManager.sampleAlphaToCoverageState // GL_SAMPLE_ALPHA_TO_COVERAGE flag
, GLStateManager.sampleAlphaToOneState // GL_SAMPLE_ALPHA_TO_ONE flag
, GLStateManager.sampleCoverageState // GL_SAMPLE_COVERAGE flag
, GLStateManager.scissorTest // GL_SCISSOR_TEST flag
, GLStateManager.stencilTest // GL_STENCIL_TEST flag
));
// Enable bits for the user-definable clipping planes
for(int i = 0; i < GLStateManager.clipPlaneStates.length; i++) {
enableBits.add(GLStateManager.clipPlaneStates[i]);
}
// GL_TEXTURE_1D, GL_TEXTURE_2D, GL_TEXTURE_3D flags
for(int i = 0 ; i < GLStateManager.MAX_TEXTURE_UNITS; i++) {
enableBits.add(GLStateManager.textures.getTexture1DStates(i));
enableBits.add(GLStateManager.textures.getTextureUnitStates(i));
enableBits.add(GLStateManager.textures.getTexture3DStates(i));
}
// Flags GL_TEXTURE_GEN_x where x is S, T, R, or Q
addTextureGenStates(enableBits);
attribToFeatures.put(GL11.GL_ENABLE_BIT, enableBits);
attribToFeatures.put(GL11.GL_EVAL_BIT, ImmutableSet.of(
// GL_MAP1_x enable bits, where x is a map type
// GL_MAP2_x enable bits, where x is a map type
// 1D grid endpoints and divisions
// 2D grid endpoints and divisions
// GL_AUTO_NORMAL enable bit
));
attribToFeatures.put(GL11.GL_FOG_BIT, ImmutableSet.of(
GLStateManager.fogMode // GL_FOG enable bit
, GLStateManager.fogState // Fog color
// ^^ Fog density
// ^^ Linear fog start
// ^^ Linear fog end
// Fog index
// ^^ GL_FOG_MODE value
));
attribToFeatures.put(GL11.GL_HINT_BIT, ImmutableSet.of(
// GL_PERSPECTIVE_CORRECTION_HINT setting
// GL_POINT_SMOOTH_HINT setting
// GL_LINE_SMOOTH_HINT setting
// GL_POLYGON_SMOOTH_HINT setting
// GL_FOG_HINT setting
// GL_GENERATE_MIPMAP_HINT setting
// GL_TEXTURE_COMPRESSION_HINT setting
));
attribToFeatures.put(GL11.GL_LIGHTING_BIT, ImmutableSet.of(
GLStateManager.colorMaterial // GL_COLOR_MATERIAL enable bit
, GLStateManager.colorMaterialFace // GL_COLOR_MATERIAL_FACE value
, GLStateManager.colorMaterialParameter // Color material parameters that are tracking the current color
, GLStateManager.lightModel // Ambient scene color, GL_LIGHT_MODEL_LOCAL_VIEWER, GL_LIGHT_MODEL_TWO_SIDE
, GLStateManager.lightingState // GL_LIGHTING enable bit
// Enable bit for each light
, GLStateManager.lightStates[0] // GL_LIGHT0
, GLStateManager.lightStates[1] // GL_LIGHT1
, GLStateManager.lightStates[2] // GL_LIGHT2
, GLStateManager.lightStates[3] // GL_LIGHT3
, GLStateManager.lightStates[4] // GL_LIGHT4
, GLStateManager.lightStates[5] // GL_LIGHT5
, GLStateManager.lightStates[6] // GL_LIGHT6
, GLStateManager.lightStates[7] // GL_LIGHT7
// Ambient, diffuse, and specular intensity for each light
// Direction, position, exponent, and cutoff angle for each light
// Constant, linear, and quadratic attenuation factors for each light
, GLStateManager.lightDataStates[0]
, GLStateManager.lightDataStates[1]
, GLStateManager.lightDataStates[2]
, GLStateManager.lightDataStates[3]
, GLStateManager.lightDataStates[4]
, GLStateManager.lightDataStates[5]
, GLStateManager.lightDataStates[6]
, GLStateManager.lightDataStates[7]
// Ambient, diffuse, specular, and emissive color for each material
// Ambient, diffuse, and specular color indices for each material
// Specular exponent for each material
, GLStateManager.frontMaterial
, GLStateManager.backMaterial
, GLStateManager.shadeModelState // GL_SHADE_MODEL setting
));
attribToFeatures.put(GL11.GL_LINE_BIT, ImmutableSet.of(
GLStateManager.lineSmoothState // GL_LINE_SMOOTH flag
, GLStateManager.lineStippleState // GL_LINE_STIPPLE enable bit
, GLStateManager.lineState // Line stipple pattern, repeat counter, and width
));
attribToFeatures.put(GL11.GL_LIST_BIT, ImmutableSet.of(
// GL_LIST_BASE setting
));
attribToFeatures.put(GL13.GL_MULTISAMPLE_BIT, ImmutableSet.of(
// GL_MULTISAMPLE enable bit
// GL_SAMPLE_ALPHA_TO_COVERAGE flag
// GL_SAMPLE_ALPHA_TO_ONE flag
// GL_SAMPLE_COVERAGE flag
// GL_SAMPLE_COVERAGE_VALUE value
// GL_SAMPLE_COVERAGE_INVERT value
));
attribToFeatures.put(GL11.GL_PIXEL_MODE_BIT, ImmutableSet.of(
// GL_RED_BIAS and GL_RED_SCALE settings
// GL_GREEN_BIAS and GL_GREEN_SCALE values
// GL_BLUE_BIAS and GL_BLUE_SCALE
// GL_ALPHA_BIAS and GL_ALPHA_SCALE
// GL_DEPTH_BIAS and GL_DEPTH_SCALE
// GL_INDEX_OFFSET and GL_INDEX_SHIFT values
// GL_MAP_COLOR and GL_MAP_STENCIL flags
// GL_ZOOM_X and GL_ZOOM_Y factors
// GL_READ_BUFFER setting
));
attribToFeatures.put(GL11.GL_POINT_BIT, ImmutableSet.of(
GLStateManager.pointSmoothState // GL_POINT_SMOOTH flag
, GLStateManager.pointState // Point size
));
attribToFeatures.put(GL11.GL_POLYGON_BIT, ImmutableSet.of(
GLStateManager.cullState // GL_CULL_FACE enable bit
, GLStateManager.polygonSmoothState // GL_POLYGON_SMOOTH flag
, GLStateManager.polygonStippleState // GL_POLYGON_STIPPLE enable bit
, GLStateManager.polygonOffsetFillState // GL_POLYGON_OFFSET_FILL flag
, GLStateManager.polygonOffsetLineState // GL_POLYGON_OFFSET_LINE flag
, GLStateManager.polygonOffsetPointState // GL_POLYGON_OFFSET_POINT flag
, GLStateManager.polygonState // GL_CULL_FACE_MODE, GL_FRONT_FACE, GL_POLYGON_MODE, GL_POLYGON_OFFSET_FACTOR/UNITS
));
attribToFeatures.put(GL11.GL_POLYGON_STIPPLE_BIT, ImmutableSet.of(
// Polygon stipple pattern
));
attribToFeatures.put(GL11.GL_SCISSOR_BIT, ImmutableSet.of(
GLStateManager.scissorTest // GL_SCISSOR_TEST enable bit
// Scissor box
));
attribToFeatures.put(GL11.GL_STENCIL_BUFFER_BIT, ImmutableSet.of(
GLStateManager.stencilTest // GL_STENCIL_TEST enable bit
, GLStateManager.stencilState // Stencil function, ref, mask, ops, writemask, clear value
));
final Set<IStateStack<?>> textureAttribs = new HashSet<>(ImmutableSet.of(
GLStateManager.activeTextureUnit // Active texture unit
// Enable bits for the four texture coordinates
// Border color for each texture image
// Minification function for each texture image
// Magnification function for each texture image
// Texture coordinates and wrap mode for each texture image
// Color and mode for each texture environment
// Enable bits GL_TEXTURE_GEN_x, x is S, T, R, and Q
// GL_TEXTURE_GEN_MODE setting for S, T, R, and Q
// glTexGen plane equations for S, T, R, and Q
// Current texture bindings (for example, GL_TEXTURE_BINDING_2D) - Below
));
// Current Texture Bindings - GL_TEXTURE_BINDING_2D
for(int i = 0 ; i < GLStateManager.MAX_TEXTURE_UNITS; i++) {
textureAttribs.add(GLStateManager.textures.getTextureUnitBindings(i));
// textureAttribs.add(GLStateManager.textures.getInfo(i))
}
// Enable bits GL_TEXTURE_GEN_x where x is S, T, R, or Q
addTextureGenStates(textureAttribs);
attribToFeatures.put(GL11.GL_TEXTURE_BIT, textureAttribs);
attribToFeatures.put(GL11.GL_TRANSFORM_BIT, ImmutableSet.of(
// Coefficients of the six clipping planes
// Enable bits for the user-definable clipping planes
GLStateManager.matrixMode
, GLStateManager.normalizeState // GL_NORMALIZE flag
, GLStateManager.rescaleNormalState // GL_RESCALE_NORMAL flag
));
attribToFeatures.put(GL11.GL_VIEWPORT_BIT, ImmutableSet.of(
// Depth range (near and far)
GLStateManager.viewportState
));
}
public static Set<IStateStack<?>> getFeatures(int attrib) {
return attribToFeatures.getOrDefault(attrib, Collections.emptySet());
}
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\glsm\FormatBuffer.java
|
package com.gtnewhorizons.angelica.glsm;
import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuadViewMutable;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer;
import com.gtnewhorizons.angelica.glsm.recording.AccumulatedDraw;
import org.joml.Matrix4f;
import java.util.ArrayList;
import java.util.List;
/**
* Accumulates geometry for a single vertex format during display list compilation.
* Tracks merged ranges (same-transform draws combined) and per-draw ranges (1:1).
*/
class FormatBuffer {
final CapturingTessellator.Flags flags;
final List<ModelQuadViewMutable> allQuads = new ArrayList<>();
// Merged ranges for optimized path (consecutive same-transform draws combined)
final List<DrawRange> mergedRanges = new ArrayList<>();
// Per-draw ranges for unoptimized path (1:1 with input draws)
final List<DrawRange> perDrawRanges = new ArrayList<>();
int currentVertexOffset = 0;
// Track the current range being built for merging consecutive same-transform draws
private int pendingStartVertex = -1;
private int pendingVertexCount = 0;
private Matrix4f pendingTransform = null;
private int pendingCommandIndex = -1;
private int pendingGeneration = -1;
private int pendingStateGen = -1;
// Track last restore data for merged draws (uses the LAST draw's data)
private AccumulatedDraw.RestoreData pendingRestoreData = null;
FormatBuffer(CapturingTessellator.Flags flags) {
this.flags = flags;
}
/** Add a draw, tracking both merged and per-draw ranges. */
void addDraw(AccumulatedDraw draw) {
final int vertexCount = draw.quads.size() * 4; // 4 vertices per quad
// Always track per-draw range for unoptimized path (includes restoreData)
perDrawRanges.add(new DrawRange(
currentVertexOffset, vertexCount, draw.transform, draw.commandIndex, draw.restoreData
));
// Merge logic for optimized path:
// - same matrixGeneration = same matrix transform context
// - same stateGeneration = no state commands (draw barriers) between draws
boolean canMerge = pendingGeneration != -1
&& pendingGeneration == draw.matrixGeneration
&& pendingStateGen == draw.stateGeneration;
if (canMerge) {
// Extend the pending range
pendingVertexCount += vertexCount;
// Update restoreData to the LAST draw's data (used after merged draw completes)
pendingRestoreData = draw.restoreData;
} else {
// Flush pending range if any
flushPendingRange();
// Start new pending range
pendingStartVertex = currentVertexOffset;
pendingVertexCount = vertexCount;
pendingTransform = new Matrix4f(draw.transform);
pendingCommandIndex = draw.commandIndex;
pendingGeneration = draw.matrixGeneration;
pendingStateGen = draw.stateGeneration;
pendingRestoreData = draw.restoreData;
}
allQuads.addAll(draw.quads);
currentVertexOffset += vertexCount;
}
private void flushPendingRange() {
if (pendingGeneration != -1) {
mergedRanges.add(new DrawRange(
pendingStartVertex, pendingVertexCount, pendingTransform, pendingCommandIndex, pendingRestoreData
));
pendingTransform = null;
pendingGeneration = -1;
pendingStateGen = -1;
pendingRestoreData = null;
}
}
/** Compile accumulated quads into a VBO. */
CompiledFormatBuffer finish() {
// Flush any remaining pending range
flushPendingRange();
VertexBuffer vbo = DisplayListManager.compileQuads(allQuads, flags);
return new CompiledFormatBuffer(
vbo,
flags,
mergedRanges.toArray(new DrawRange[0]),
perDrawRanges.toArray(new DrawRange[0])
);
}
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\glsm\GLDebug.java
|
/*
* Copyright LWJGL. All rights reserved. Modified by IMS for use in Iris (net.coderbot.iris.gl).
* License terms: https://www.lwjgl.org/license
*/
package com.gtnewhorizons.angelica.glsm;
import org.lwjgl.opengl.AMDDebugOutput;
import org.lwjgl.opengl.AMDDebugOutputCallback;
import org.lwjgl.opengl.ARBDebugOutput;
import org.lwjgl.opengl.ARBDebugOutputCallback;
import org.lwjgl.opengl.EXTBlendColor;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL14;
import org.lwjgl.opengl.GL30;
import org.lwjgl.opengl.GL43;
import org.lwjgl.opengl.KHRDebug;
import org.lwjgl.opengl.KHRDebugCallback;
import java.io.PrintStream;
import java.util.function.Consumer;
import static com.gtnewhorizons.angelica.loading.AngelicaTweaker.LOGGER;
import static org.lwjgl.opengl.ARBDebugOutput.glDebugMessageCallbackARB;
public final class GLDebug {
/**
* Sets up debug callbacks
* @return 0 for failure, 1 for success, 2 for restart required.
*/
public static int setupDebugMessageCallback() {
if (Thread.currentThread() != GLStateManager.getMainThread()) {
LOGGER.warn("setupDebugMessageCallback called from non-main thread!");
return 0;
}
return setupDebugMessageCallback(System.err);
}
private static void trace(Consumer<String> output) {
/*
* We can not just use a fixed stacktrace element offset, because some methods
* are intercepted and some are not. So, check the package name.
*/
StackTraceElement[] elems = filterStackTrace(new Throwable(), 4).getStackTrace();
for (StackTraceElement ste : elems) {
output.accept(ste.toString());
}
}
public static Throwable filterStackTrace(Throwable throwable, int offset) {
StackTraceElement[] elems = throwable.getStackTrace();
StackTraceElement[] filtered = new StackTraceElement[elems.length];
int j = 0;
for (int i = offset; i < elems.length; i++) {
String className = elems[i].getClassName();
if (className == null) {
className = "";
}
filtered[j++] = elems[i];
}
StackTraceElement[] newElems = new StackTraceElement[j];
System.arraycopy(filtered, 0, newElems, 0, j);
throwable.setStackTrace(newElems);
return throwable;
}
public static void printTrace(PrintStream stream) {
trace(new Consumer<String>() {
boolean first = true;
public void accept(String str) {
if (first) {
printDetail(stream, "Stacktrace", str);
first = false;
} else {
printDetailLine(stream, "Stacktrace", str);
}
}
});
}
/**
* Sets up debug callbacks
* @return 0 for failure, 1 for success, 2 for restart required.
*/
public static int setupDebugMessageCallback(PrintStream stream) {
if (GLStateManager.capabilities.OpenGL43 || GLStateManager.capabilities.GL_KHR_debug) {
LOGGER.info("[GL] Using OpenGL 4.3 for error logging.");
KHRDebugCallback proc = new KHRDebugCallback((source, type, id, severity, message) -> {
stream.println("[LWJGL] OpenGL debug message");
printDetail(stream, "ID", String.format("0x%X", id));
printDetail(stream, "Source", getDebugSource(source));
printDetail(stream, "Type", getDebugType(type));
printDetail(stream, "Severity", getDebugSeverity(severity));
printDetail(stream, "Message", message);
printTrace(stream);
});
GL43.glDebugMessageControl(GL11.GL_DONT_CARE, GL11.GL_DONT_CARE, GL43.GL_DEBUG_SEVERITY_HIGH, null, true);
GL43.glDebugMessageControl(GL11.GL_DONT_CARE, GL11.GL_DONT_CARE, GL43.GL_DEBUG_SEVERITY_MEDIUM, null, false);
GL43.glDebugMessageControl(GL11.GL_DONT_CARE, GL11.GL_DONT_CARE, GL43.GL_DEBUG_SEVERITY_LOW, null, false);
GL43.glDebugMessageControl(GL11.GL_DONT_CARE, GL11.GL_DONT_CARE, GL43.GL_DEBUG_SEVERITY_NOTIFICATION, null, false);
GL43.glDebugMessageCallback(proc);
if ((GL11.glGetInteger(GL30.GL_CONTEXT_FLAGS) & GL43.GL_CONTEXT_FLAG_DEBUG_BIT) == 0) {
LOGGER.warn("[GL] Warning: A non-debug context may not produce any debug output.");
GL11.glEnable(GL43.GL_DEBUG_OUTPUT);
return 2;
}
return 1;
} else if (GLStateManager.capabilities.GL_ARB_debug_output) {
LOGGER.info("[GL] Using ARB_debug_output for error logging.");
ARBDebugOutputCallback proc = new ARBDebugOutputCallback((source, type, id, severity, message) -> {
stream.println("[LWJGL] ARB_debug_output message");
printDetail(stream, "ID", String.format("0x%X", id));
printDetail(stream, "Source", getSourceARB(source));
printDetail(stream, "Type", getTypeARB(type));
printDetail(stream, "Severity", getSeverityARB(severity));
printDetail(stream, "Message", message);
printTrace(stream);
});
ARBDebugOutput.glDebugMessageControlARB(GL11.GL_DONT_CARE, GL11.GL_DONT_CARE, GL43.GL_DEBUG_SEVERITY_HIGH, null, true);
ARBDebugOutput.glDebugMessageControlARB(GL11.GL_DONT_CARE, GL11.GL_DONT_CARE, GL43.GL_DEBUG_SEVERITY_MEDIUM, null, false);
ARBDebugOutput.glDebugMessageControlARB(GL11.GL_DONT_CARE, GL11.GL_DONT_CARE, GL43.GL_DEBUG_SEVERITY_LOW, null, false);
ARBDebugOutput.glDebugMessageControlARB(GL11.GL_DONT_CARE, GL11.GL_DONT_CARE, GL43.GL_DEBUG_SEVERITY_NOTIFICATION, null, false);
ARBDebugOutput.glDebugMessageCallbackARB(proc);
return 1;
} else if (GLStateManager.capabilities.GL_AMD_debug_output) {
LOGGER.info("[GL] Using AMD_debug_output for error logging.");
AMDDebugOutputCallback proc = new AMDDebugOutputCallback((id, category, severity, message) -> {
stream.println("[LWJGL] AMD_debug_output message");
printDetail(stream, "ID", String.format("0x%X", id));
printDetail(stream, "Category", getCategoryAMD(category));
printDetail(stream, "Severity", getSeverityAMD(severity));
printDetail(stream, "Message", message);
printTrace(stream);
});
AMDDebugOutput.glDebugMessageEnableAMD(0, GL43.GL_DEBUG_SEVERITY_HIGH, null, true);
AMDDebugOutput.glDebugMessageEnableAMD(0, GL43.GL_DEBUG_SEVERITY_MEDIUM, null, false);
AMDDebugOutput.glDebugMessageEnableAMD(0, GL43.GL_DEBUG_SEVERITY_LOW, null, false);
AMDDebugOutput.glDebugMessageEnableAMD(0, GL43.GL_DEBUG_SEVERITY_NOTIFICATION, null, false);
AMDDebugOutput.glDebugMessageCallbackAMD(proc);
return 1;
} else {
LOGGER.info("[GL] No debug output implementation is available, cannot return debug info.");
return 0;
}
}
public static int disableDebugMessages() {
if (GLStateManager.capabilities.OpenGL43) {
GL43.glDebugMessageCallback(null);
return 1;
} else if (GLStateManager.capabilities.GL_KHR_debug) {
KHRDebug.glDebugMessageCallback(null);
if (GLStateManager.capabilities.OpenGL30 && (GL11.glGetInteger(GL30.GL_CONTEXT_FLAGS) & 2) == 0) {
GL11.glDisable(GL43.GL_DEBUG_OUTPUT);
}
return 1;
} else if (GLStateManager.capabilities.GL_ARB_debug_output) {
glDebugMessageCallbackARB(null);
return 1;
} else if (GLStateManager.capabilities.GL_AMD_debug_output) {
AMDDebugOutput.glDebugMessageCallbackAMD(null);
return 1;
} else {
LOGGER.info("[GL] No debug output implementation is available, cannot disable debug info.");
return 0;
}
}
private static void printDetail(PrintStream stream, String type, String message) {
stream.printf("\t%s: %s\n", type, message);
}
private static void printDetailLine(PrintStream stream, String type, String message) {
stream.append(" ");
for (int i = 0; i < type.length(); i++) {
stream.append(" ");
}
stream.append(message).append("\n");
}
private static String getDebugSource(int source) {
return switch (source) {
case GL43.GL_DEBUG_SOURCE_API -> "API";
case GL43.GL_DEBUG_SOURCE_WINDOW_SYSTEM -> "WINDOW SYSTEM";
case GL43.GL_DEBUG_SOURCE_SHADER_COMPILER -> "SHADER COMPILER";
case GL43.GL_DEBUG_SOURCE_THIRD_PARTY -> "THIRD PARTY";
case GL43.GL_DEBUG_SOURCE_APPLICATION -> "APPLICATION";
case GL43.GL_DEBUG_SOURCE_OTHER -> "OTHER";
default -> String.format("Unknown [0x%X]", source);
};
}
private static String getDebugType(int type) {
return switch (type) {
case GL43.GL_DEBUG_TYPE_ERROR -> "ERROR";
case GL43.GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR -> "DEPRECATED BEHAVIOR";
case GL43.GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR -> "UNDEFINED BEHAVIOR";
case GL43.GL_DEBUG_TYPE_PORTABILITY -> "PORTABILITY";
case GL43.GL_DEBUG_TYPE_PERFORMANCE -> "PERFORMANCE";
case GL43.GL_DEBUG_TYPE_OTHER -> "OTHER";
case GL43.GL_DEBUG_TYPE_MARKER -> "MARKER";
default -> String.format("Unknown [0x%X]", type);
};
}
private static String getDebugSeverity(int severity) {
return switch (severity) {
case GL43.GL_DEBUG_SEVERITY_NOTIFICATION -> "NOTIFICATION";
case GL43.GL_DEBUG_SEVERITY_HIGH -> "HIGH";
case GL43.GL_DEBUG_SEVERITY_MEDIUM -> "MEDIUM";
case GL43.GL_DEBUG_SEVERITY_LOW -> "LOW";
default -> String.format("Unknown [0x%X]", severity);
};
}
private static String getSourceARB(int source) {
return switch (source) {
case ARBDebugOutput.GL_DEBUG_SOURCE_API_ARB -> "API";
case ARBDebugOutput.GL_DEBUG_SOURCE_WINDOW_SYSTEM_ARB -> "WINDOW SYSTEM";
case ARBDebugOutput.GL_DEBUG_SOURCE_SHADER_COMPILER_ARB -> "SHADER COMPILER";
case ARBDebugOutput.GL_DEBUG_SOURCE_THIRD_PARTY_ARB -> "THIRD PARTY";
case ARBDebugOutput.GL_DEBUG_SOURCE_APPLICATION_ARB -> "APPLICATION";
case ARBDebugOutput.GL_DEBUG_SOURCE_OTHER_ARB -> "OTHER";
default -> String.format("Unknown [0x%X]", source);
};
}
private static String getTypeARB(int type) {
return switch (type) {
case ARBDebugOutput.GL_DEBUG_TYPE_ERROR_ARB -> "ERROR";
case ARBDebugOutput.GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB -> "DEPRECATED BEHAVIOR";
case ARBDebugOutput.GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB -> "UNDEFINED BEHAVIOR";
case ARBDebugOutput.GL_DEBUG_TYPE_PORTABILITY_ARB -> "PORTABILITY";
case ARBDebugOutput.GL_DEBUG_TYPE_PERFORMANCE_ARB -> "PERFORMANCE";
case ARBDebugOutput.GL_DEBUG_TYPE_OTHER_ARB -> "OTHER";
default -> String.format("Unknown [0x%X]", type);
};
}
private static String getSeverityARB(int severity) {
return switch (severity) {
case ARBDebugOutput.GL_DEBUG_SEVERITY_HIGH_ARB -> "HIGH";
case ARBDebugOutput.GL_DEBUG_SEVERITY_MEDIUM_ARB -> "MEDIUM";
case ARBDebugOutput.GL_DEBUG_SEVERITY_LOW_ARB -> "LOW";
default -> String.format("Unknown [0x%X]", severity);
};
}
private static String getCategoryAMD(int category) {
return switch (category) {
case AMDDebugOutput.GL_DEBUG_CATEGORY_API_ERROR_AMD -> "API ERROR";
case AMDDebugOutput.GL_DEBUG_CATEGORY_WINDOW_SYSTEM_AMD -> "WINDOW SYSTEM";
case AMDDebugOutput.GL_DEBUG_CATEGORY_DEPRECATION_AMD -> "DEPRECATION";
case AMDDebugOutput.GL_DEBUG_CATEGORY_UNDEFINED_BEHAVIOR_AMD -> "UNDEFINED BEHAVIOR";
case AMDDebugOutput.GL_DEBUG_CATEGORY_PERFORMANCE_AMD -> "PERFORMANCE";
case AMDDebugOutput.GL_DEBUG_CATEGORY_SHADER_COMPILER_AMD -> "SHADER COMPILER";
case AMDDebugOutput.GL_DEBUG_CATEGORY_APPLICATION_AMD -> "APPLICATION";
case AMDDebugOutput.GL_DEBUG_CATEGORY_OTHER_AMD -> "OTHER";
default -> String.format("Unknown [0x%X]", category);
};
}
private static String getSeverityAMD(int severity) {
return switch (severity) {
case AMDDebugOutput.GL_DEBUG_SEVERITY_HIGH_AMD -> "HIGH";
case AMDDebugOutput.GL_DEBUG_SEVERITY_MEDIUM_AMD -> "MEDIUM";
case AMDDebugOutput.GL_DEBUG_SEVERITY_LOW_AMD -> "LOW";
default -> String.format("Unknown [0x%X]", severity);
};
}
public static String getMatrixModeName(int mode) {
return switch (mode) {
case GL11.GL_MODELVIEW -> "MODELVIEW";
case GL11.GL_PROJECTION -> "PROJECTION";
case GL11.GL_TEXTURE -> "TEXTURE";
case GL11.GL_COLOR -> "COLOR";
default -> String.format("0x%X", mode);
};
}
public static String getCapabilityName(int cap) {
return switch (cap) {
case GL11.GL_ALPHA_TEST -> "ALPHA_TEST";
case GL11.GL_BLEND -> "BLEND";
case GL11.GL_COLOR_MATERIAL -> "COLOR_MATERIAL";
case GL11.GL_CULL_FACE -> "CULL_FACE";
case GL11.GL_DEPTH_TEST -> "DEPTH_TEST";
case GL11.GL_FOG -> "FOG";
case GL11.GL_LIGHTING -> "LIGHTING";
case GL11.GL_LINE_SMOOTH -> "LINE_SMOOTH";
case GL11.GL_NORMALIZE -> "NORMALIZE";
case GL11.GL_POINT_SMOOTH -> "POINT_SMOOTH";
case GL11.GL_POLYGON_OFFSET_FILL -> "POLYGON_OFFSET_FILL";
case GL11.GL_POLYGON_OFFSET_LINE -> "POLYGON_OFFSET_LINE";
case GL11.GL_POLYGON_SMOOTH -> "POLYGON_SMOOTH";
case GL12.GL_RESCALE_NORMAL -> "RESCALE_NORMAL";
case GL11.GL_SCISSOR_TEST -> "SCISSOR_TEST";
case GL11.GL_STENCIL_TEST -> "STENCIL_TEST";
case GL11.GL_TEXTURE_1D -> "TEXTURE_1D";
case GL11.GL_TEXTURE_2D -> "TEXTURE_2D";
case GL11.GL_LIGHT0 -> "LIGHT0";
case GL11.GL_LIGHT1 -> "LIGHT1";
case GL11.GL_LIGHT2 -> "LIGHT2";
case GL11.GL_LIGHT3 -> "LIGHT3";
case GL11.GL_LIGHT4 -> "LIGHT4";
case GL11.GL_LIGHT5 -> "LIGHT5";
case GL11.GL_LIGHT6 -> "LIGHT6";
case GL11.GL_LIGHT7 -> "LIGHT7";
default -> String.format("0x%X", cap);
};
}
public static String getComparisonFuncName(int func) {
return switch (func) {
case GL11.GL_NEVER -> "NEVER";
case GL11.GL_LESS -> "LESS";
case GL11.GL_EQUAL -> "EQUAL";
case GL11.GL_LEQUAL -> "LEQUAL";
case GL11.GL_GREATER -> "GREATER";
case GL11.GL_NOTEQUAL -> "NOTEQUAL";
case GL11.GL_GEQUAL -> "GEQUAL";
case GL11.GL_ALWAYS -> "ALWAYS";
default -> String.format("0x%X", func);
};
}
public static String getBlendFactorName(int factor) {
return switch (factor) {
case GL11.GL_ZERO -> "ZERO";
case GL11.GL_ONE -> "ONE";
case GL11.GL_SRC_COLOR -> "SRC_COLOR";
case GL11.GL_ONE_MINUS_SRC_COLOR -> "ONE_MINUS_SRC_COLOR";
case GL11.GL_DST_COLOR -> "DST_COLOR";
case GL11.GL_ONE_MINUS_DST_COLOR -> "ONE_MINUS_DST_COLOR";
case GL11.GL_SRC_ALPHA -> "SRC_ALPHA";
case GL11.GL_ONE_MINUS_SRC_ALPHA -> "ONE_MINUS_SRC_ALPHA";
case GL11.GL_DST_ALPHA -> "DST_ALPHA";
case GL11.GL_ONE_MINUS_DST_ALPHA -> "ONE_MINUS_DST_ALPHA";
case EXTBlendColor.GL_CONSTANT_COLOR_EXT -> "CONSTANT_COLOR";
case EXTBlendColor.GL_ONE_MINUS_CONSTANT_COLOR_EXT -> "ONE_MINUS_CONSTANT_COLOR";
case EXTBlendColor.GL_CONSTANT_ALPHA_EXT -> "CONSTANT_ALPHA";
case EXTBlendColor.GL_ONE_MINUS_CONSTANT_ALPHA_EXT -> "ONE_MINUS_CONSTANT_ALPHA";
case GL11.GL_SRC_ALPHA_SATURATE -> "SRC_ALPHA_SATURATE";
default -> String.format("0x%X", factor);
};
}
public static String getShadeModelName(int mode) {
return switch (mode) {
case GL11.GL_FLAT -> "FLAT";
case GL11.GL_SMOOTH -> "SMOOTH";
default -> String.format("0x%X", mode);
};
}
public static String getTextureTargetName(int target) {
return switch (target) {
case GL11.GL_TEXTURE_1D -> "TEXTURE_1D";
case GL11.GL_TEXTURE_2D -> "TEXTURE_2D";
case GL12.GL_TEXTURE_3D -> "TEXTURE_3D";
case GL13.GL_TEXTURE_CUBE_MAP -> "TEXTURE_CUBE_MAP";
default -> String.format("0x%X", target);
};
}
public static String getTexturePnameName(int pname) {
return switch (pname) {
case GL11.GL_TEXTURE_MIN_FILTER -> "TEXTURE_MIN_FILTER";
case GL11.GL_TEXTURE_MAG_FILTER -> "TEXTURE_MAG_FILTER";
case GL11.GL_TEXTURE_WRAP_S -> "TEXTURE_WRAP_S";
case GL11.GL_TEXTURE_WRAP_T -> "TEXTURE_WRAP_T";
case GL12.GL_TEXTURE_WRAP_R -> "TEXTURE_WRAP_R";
case GL12.GL_TEXTURE_MIN_LOD -> "TEXTURE_MIN_LOD";
case GL12.GL_TEXTURE_MAX_LOD -> "TEXTURE_MAX_LOD";
case GL12.GL_TEXTURE_BASE_LEVEL -> "TEXTURE_BASE_LEVEL";
case GL12.GL_TEXTURE_MAX_LEVEL -> "TEXTURE_MAX_LEVEL";
case GL11.GL_TEXTURE_BORDER_COLOR -> "TEXTURE_BORDER_COLOR";
case GL11.GL_TEXTURE_PRIORITY -> "TEXTURE_PRIORITY";
case GL14.GL_TEXTURE_LOD_BIAS -> "TEXTURE_LOD_BIAS";
case GL14.GL_GENERATE_MIPMAP -> "GENERATE_MIPMAP";
default -> String.format("0x%X", pname);
};
}
public static String getTextureFormatName(int format) {
return switch (format) {
case GL11.GL_RED -> "RED";
case GL11.GL_GREEN -> "GREEN";
case GL11.GL_BLUE -> "BLUE";
case GL11.GL_ALPHA -> "ALPHA";
case GL11.GL_RGB -> "RGB";
case GL11.GL_RGBA -> "RGBA";
case GL11.GL_LUMINANCE -> "LUMINANCE";
case GL11.GL_LUMINANCE_ALPHA -> "LUMINANCE_ALPHA";
case GL12.GL_BGR -> "BGR";
case GL12.GL_BGRA -> "BGRA";
case GL11.GL_DEPTH_COMPONENT -> "DEPTH_COMPONENT";
case GL11.GL_STENCIL_INDEX -> "STENCIL_INDEX";
case GL30.GL_DEPTH_STENCIL -> "DEPTH_STENCIL";
// Internal formats
case GL11.GL_RGB8 -> "RGB8";
case GL11.GL_RGBA8 -> "RGBA8";
case GL11.GL_ALPHA8 -> "ALPHA8";
case GL11.GL_LUMINANCE8 -> "LUMINANCE8";
case GL11.GL_LUMINANCE8_ALPHA8 -> "LUMINANCE8_ALPHA8";
default -> String.format("0x%X", format);
};
}
public static String getDataTypeName(int type) {
return switch (type) {
case GL11.GL_UNSIGNED_BYTE -> "UNSIGNED_BYTE";
case GL11.GL_BYTE -> "BYTE";
case GL11.GL_UNSIGNED_SHORT -> "UNSIGNED_SHORT";
case GL11.GL_SHORT -> "SHORT";
case GL11.GL_UNSIGNED_INT -> "UNSIGNED_INT";
case GL11.GL_INT -> "INT";
case GL11.GL_FLOAT -> "FLOAT";
case GL11.GL_DOUBLE -> "DOUBLE";
case GL12.GL_UNSIGNED_BYTE_3_3_2 -> "UNSIGNED_BYTE_3_3_2";
case GL12.GL_UNSIGNED_SHORT_4_4_4_4 -> "UNSIGNED_SHORT_4_4_4_4";
case GL12.GL_UNSIGNED_SHORT_5_5_5_1 -> "UNSIGNED_SHORT_5_5_5_1";
case GL12.GL_UNSIGNED_INT_8_8_8_8 -> "UNSIGNED_INT_8_8_8_8";
case GL12.GL_UNSIGNED_INT_10_10_10_2 -> "UNSIGNED_INT_10_10_10_2";
default -> String.format("0x%X", type);
};
}
public static String getLightName(int light) {
return switch (light) {
case GL11.GL_LIGHT0 -> "LIGHT0";
case GL11.GL_LIGHT1 -> "LIGHT1";
case GL11.GL_LIGHT2 -> "LIGHT2";
case GL11.GL_LIGHT3 -> "LIGHT3";
case GL11.GL_LIGHT4 -> "LIGHT4";
case GL11.GL_LIGHT5 -> "LIGHT5";
case GL11.GL_LIGHT6 -> "LIGHT6";
case GL11.GL_LIGHT7 -> "LIGHT7";
default -> String.format("0x%X", light);
};
}
public static String getLightPnameName(int pname) {
return switch (pname) {
case GL11.GL_AMBIENT -> "AMBIENT";
case GL11.GL_DIFFUSE -> "DIFFUSE";
case GL11.GL_SPECULAR -> "SPECULAR";
case GL11.GL_POSITION -> "POSITION";
case GL11.GL_SPOT_DIRECTION -> "SPOT_DIRECTION";
case GL11.GL_SPOT_EXPONENT -> "SPOT_EXPONENT";
case GL11.GL_SPOT_CUTOFF -> "SPOT_CUTOFF";
case GL11.GL_CONSTANT_ATTENUATION -> "CONSTANT_ATTENUATION";
case GL11.GL_LINEAR_ATTENUATION -> "LINEAR_ATTENUATION";
case GL11.GL_QUADRATIC_ATTENUATION -> "QUADRATIC_ATTENUATION";
default -> String.format("0x%X", pname);
};
}
public static String getMaterialPnameName(int pname) {
return switch (pname) {
case GL11.GL_AMBIENT -> "AMBIENT";
case GL11.GL_DIFFUSE -> "DIFFUSE";
case GL11.GL_SPECULAR -> "SPECULAR";
case GL11.GL_EMISSION -> "EMISSION";
case GL11.GL_SHININESS -> "SHININESS";
case GL11.GL_AMBIENT_AND_DIFFUSE -> "AMBIENT_AND_DIFFUSE";
case GL11.GL_COLOR_INDEXES -> "COLOR_INDEXES";
default -> String.format("0x%X", pname);
};
}
public static String getFaceName(int face) {
return switch (face) {
case GL11.GL_FRONT -> "FRONT";
case GL11.GL_BACK -> "BACK";
case GL11.GL_FRONT_AND_BACK -> "FRONT_AND_BACK";
default -> String.format("0x%X", face);
};
}
public static String getColorMaterialModeName(int mode) {
return switch (mode) {
case GL11.GL_AMBIENT -> "AMBIENT";
case GL11.GL_DIFFUSE -> "DIFFUSE";
case GL11.GL_SPECULAR -> "SPECULAR";
case GL11.GL_EMISSION -> "EMISSION";
case GL11.GL_AMBIENT_AND_DIFFUSE -> "AMBIENT_AND_DIFFUSE";
default -> String.format("0x%X", mode);
};
}
public static String getFogPnameName(int pname) {
return switch (pname) {
case GL11.GL_FOG_MODE -> "FOG_MODE";
case GL11.GL_FOG_DENSITY -> "FOG_DENSITY";
case GL11.GL_FOG_START -> "FOG_START";
case GL11.GL_FOG_END -> "FOG_END";
case GL11.GL_FOG_INDEX -> "FOG_INDEX";
case GL11.GL_FOG_COLOR -> "FOG_COLOR";
default -> String.format("0x%X", pname);
};
}
public static String getLightModelPnameName(int pname) {
return switch (pname) {
case GL11.GL_LIGHT_MODEL_AMBIENT -> "LIGHT_MODEL_AMBIENT";
case GL11.GL_LIGHT_MODEL_LOCAL_VIEWER -> "LIGHT_MODEL_LOCAL_VIEWER";
case GL11.GL_LIGHT_MODEL_TWO_SIDE -> "LIGHT_MODEL_TWO_SIDE";
case GL12.GL_LIGHT_MODEL_COLOR_CONTROL -> "LIGHT_MODEL_COLOR_CONTROL";
default -> String.format("0x%X", pname);
};
}
public static String getClearMaskString(int mask) {
StringBuilder sb = new StringBuilder();
boolean first = true;
if ((mask & GL11.GL_COLOR_BUFFER_BIT) != 0) {
sb.append("COLOR");
first = false;
}
if ((mask & GL11.GL_DEPTH_BUFFER_BIT) != 0) {
if (!first) sb.append("|");
sb.append("DEPTH");
first = false;
}
if ((mask & GL11.GL_STENCIL_BUFFER_BIT) != 0) {
if (!first) sb.append("|");
sb.append("STENCIL");
first = false;
}
if ((mask & GL11.GL_ACCUM_BUFFER_BIT) != 0) {
if (!first) sb.append("|");
sb.append("ACCUM");
}
return sb.toString();
}
public static String getCullFaceName(int mode) {
return switch (mode) {
case GL11.GL_FRONT -> "FRONT";
case GL11.GL_BACK -> "BACK";
case GL11.GL_FRONT_AND_BACK -> "FRONT_AND_BACK";
default -> String.format("0x%X", mode);
};
}
public static String getLogicOpName(int opcode) {
return switch (opcode) {
case GL11.GL_CLEAR -> "CLEAR";
case GL11.GL_AND -> "AND";
case GL11.GL_AND_REVERSE -> "AND_REVERSE";
case GL11.GL_COPY -> "COPY";
case GL11.GL_AND_INVERTED -> "AND_INVERTED";
case GL11.GL_NOOP -> "NOOP";
case GL11.GL_XOR -> "XOR";
case GL11.GL_OR -> "OR";
case GL11.GL_NOR -> "NOR";
case GL11.GL_EQUIV -> "EQUIV";
case GL11.GL_INVERT -> "INVERT";
case GL11.GL_OR_REVERSE -> "OR_REVERSE";
case GL11.GL_COPY_INVERTED -> "COPY_INVERTED";
case GL11.GL_OR_INVERTED -> "OR_INVERTED";
case GL11.GL_NAND -> "NAND";
case GL11.GL_SET -> "SET";
default -> String.format("0x%X", opcode);
};
}
private static DebugState debugState;
private interface DebugState {
void nameObject(int id, int object, String name);
void pushGroup(String name);
void popGroup();
void debugMessage(String name);
String getObjectLabel(int glProgram, int program);
}
private static class KHRDebugState implements DebugState {
private static final int ID = 0;
private int depth = 0;
private static final int maxDepth = GL11.glGetInteger(KHRDebug.GL_MAX_DEBUG_GROUP_STACK_DEPTH);
private static final int maxNameLength = GL11.glGetInteger(KHRDebug.GL_MAX_LABEL_LENGTH);
@Override
public void nameObject(int id, int object, String name) {
KHRDebug.glObjectLabel(id, object, name);
}
@Override
public void pushGroup(String name) {
depth++;
if (depth > maxDepth) {
throw new RuntimeException("Stack overflow");
}
KHRDebug.glPushDebugGroup(KHRDebug.GL_DEBUG_SOURCE_APPLICATION, ID, name);
}
@Override
public void popGroup() {
depth--;
if (depth < 0) {
throw new RuntimeException("Stack underflow");
}
KHRDebug.glPopDebugGroup();
}
@Override
public void debugMessage(String message) {
KHRDebug.glDebugMessageInsert(KHRDebug.GL_DEBUG_SOURCE_APPLICATION, KHRDebug.GL_DEBUG_TYPE_MARKER, ID, KHRDebug.GL_DEBUG_SEVERITY_NOTIFICATION, message);
}
@Override
public String getObjectLabel(int glProgram, int program) {
if(program == 0)
return "";
return KHRDebug.glGetObjectLabel(glProgram, program, maxNameLength);
}
}
private static class UnsupportedDebugState implements DebugState {
@Override
public void nameObject(int id, int object, String name) {
}
@Override
public void pushGroup(String name) {
}
@Override
public void popGroup() {
}
@Override
public void debugMessage(String name) {
}
@Override
public String getObjectLabel(int glProgram, int program) {
return "";
}
}
public static void initDebugState() {
if (GLStateManager.capabilities.GL_KHR_debug || GLStateManager.capabilities.OpenGL43) {
debugState = new KHRDebugState();
} else {
debugState = new UnsupportedDebugState();
}
}
public static void nameObject(int id, int object, String name) {
if(debugState != null && Thread.currentThread() == GLStateManager.getMainThread()) {
debugState.nameObject(id, object, name);
}
}
public static void pushGroup(String group) {
if(debugState != null && Thread.currentThread() == GLStateManager.getMainThread()) {
debugState.pushGroup(group);
}
}
public static void popGroup() {
if(debugState != null && Thread.currentThread() == GLStateManager.getMainThread()) {
debugState.popGroup();
}
}
public static void debugMessage(String message) {
if(debugState != null && Thread.currentThread() == GLStateManager.getMainThread()) {
debugState.debugMessage(message);
}
}
public static String getObjectLabel(int glProgram, int program) {
if(debugState != null && Thread.currentThread() == GLStateManager.getMainThread()) {
return debugState.getObjectLabel(glProgram, program);
}
return "";
}
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\glsm\GLStateManager.java
|
package com.gtnewhorizons.angelica.glsm;
import com.gtnewhorizon.gtnhlib.client.renderer.stacks.IStateStack;
import com.gtnewhorizons.angelica.AngelicaMod;
import com.gtnewhorizons.angelica.glsm.DisplayListManager.RecordMode;
import com.gtnewhorizons.angelica.glsm.recording.CompiledDisplayList;
import com.gtnewhorizons.angelica.glsm.recording.ImmediateModeRecorder;
import com.gtnewhorizons.angelica.glsm.recording.commands.TexImage2DCmd;
import com.gtnewhorizons.angelica.glsm.recording.commands.TexSubImage2DCmd;
import com.gtnewhorizons.angelica.glsm.stacks.AlphaStateStack;
import com.gtnewhorizons.angelica.glsm.stacks.BlendStateStack;
import com.gtnewhorizons.angelica.glsm.stacks.BooleanStateStack;
import com.gtnewhorizons.angelica.glsm.stacks.Color4Stack;
import com.gtnewhorizons.angelica.glsm.stacks.ColorMaskStack;
import com.gtnewhorizons.angelica.glsm.stacks.DepthStateStack;
import com.gtnewhorizons.angelica.glsm.stacks.FogStateStack;
import com.gtnewhorizons.angelica.glsm.stacks.IntegerStateStack;
import com.gtnewhorizons.angelica.glsm.stacks.LightModelStateStack;
import com.gtnewhorizons.angelica.glsm.stacks.LightStateStack;
import com.gtnewhorizons.angelica.glsm.stacks.LineStateStack;
import com.gtnewhorizons.angelica.glsm.stacks.MaterialStateStack;
import com.gtnewhorizons.angelica.glsm.stacks.MatrixModeStack;
import com.gtnewhorizons.angelica.glsm.stacks.PointStateStack;
import com.gtnewhorizons.angelica.glsm.stacks.PolygonStateStack;
import com.gtnewhorizons.angelica.glsm.stacks.StencilStateStack;
import com.gtnewhorizons.angelica.glsm.stacks.TextureBindingStack;
import com.gtnewhorizons.angelica.glsm.stacks.ViewPortStateStack;
import com.gtnewhorizons.angelica.glsm.states.ClientArrayState;
import com.gtnewhorizons.angelica.glsm.states.Color4;
import com.gtnewhorizons.angelica.glsm.states.TextureBinding;
import com.gtnewhorizons.angelica.glsm.states.TextureUnitArray;
import com.gtnewhorizons.angelica.glsm.texture.TextureInfo;
import com.gtnewhorizons.angelica.glsm.texture.TextureInfoCache;
import com.gtnewhorizons.angelica.glsm.texture.TextureTracker;
import com.gtnewhorizons.angelica.hudcaching.HUDCaching;
import com.gtnewhorizons.angelica.loading.AngelicaTweaker;
import cpw.mods.fml.relauncher.ReflectionHelper;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
import it.unimi.dsi.fastutil.ints.IntStack;
import lombok.Getter;
import lombok.Setter;
import lombok.SneakyThrows;
import net.coderbot.iris.Iris;
import net.coderbot.iris.gbuffer_overrides.state.StateTracker;
import net.coderbot.iris.gl.blending.AlphaTestStorage;
import net.coderbot.iris.gl.blending.BlendModeStorage;
import net.coderbot.iris.gl.blending.DepthColorStorage;
import net.coderbot.iris.gl.state.StateUpdateNotifiers;
import net.coderbot.iris.pipeline.WorldRenderingPipeline;
import net.coderbot.iris.samplers.IrisSamplers;
import net.coderbot.iris.texture.pbr.PBRTextureManager;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.OpenGlHelper;
import org.joml.Matrix4d;
import org.joml.Matrix4f;
import org.joml.Matrix4fStack;
import org.joml.Vector3d;
import org.joml.Vector3f;
import org.lwjgl.BufferUtils;
import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.ARBMultitexture;
import org.lwjgl.opengl.ContextCapabilities;
import org.lwjgl.opengl.Drawable;
import org.lwjgl.opengl.EXTTextureFilterAnisotropic;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL14;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.GLContext;
import org.lwjgl.opengl.KHRDebug;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Field;
import java.nio.ByteBuffer;
import java.nio.DoubleBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.nio.ShortBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.function.IntSupplier;
import static com.gtnewhorizons.angelica.glsm.Vendor.AMD;
import static com.gtnewhorizons.angelica.glsm.Vendor.INTEL;
import static com.gtnewhorizons.angelica.glsm.Vendor.MESA;
import static com.gtnewhorizons.angelica.glsm.Vendor.NVIDIA;
import static com.gtnewhorizons.angelica.loading.AngelicaTweaker.LOGGER;
/**
* OpenGL State Manager - Provides cached state tracking and management for OpenGL operations.
*
* <p><b>IMPORTANT INITIALIZATION ORDER:</b></p>
* <ul>
* <li>This class performs GL queries in static initializers (MAX_CLIP_PLANES, MAX_TEXTURE_UNITS, etc.)</li>
* <li>The class MUST NOT be loaded until after the GL context has been created and made current</li>
* <li>Violating this requirement will cause crashes with "No current context" or return invalid values</li>
* <li>Call {@link #preInit()} after GL context creation to initialize runtime state</li>
* </ul>
*/
@SuppressWarnings("unused") // Used in ASM
public class GLStateManager {
// Thread Checking - must be early in static init order so isMainThread() works for state initialization
@Getter private static final Thread MainThread = Thread.currentThread();
public static boolean isMainThread() {
return Thread.currentThread() == MainThread;
}
public static ContextCapabilities capabilities;
@Getter protected static boolean poppingAttributes;
public static boolean BYPASS_CACHE = Boolean.parseBoolean(System.getProperty("angelica.disableGlCache", "false"));
// +2 headroom for internal operations (display list compilation) that push cache but not driver
public static final int MAX_ATTRIB_STACK_DEPTH = GL11.glGetInteger(GL11.GL_MAX_ATTRIB_STACK_DEPTH) + 2;
public static final int MAX_MODELVIEW_STACK_DEPTH = GL11.glGetInteger(GL11.GL_MAX_MODELVIEW_STACK_DEPTH) + 2;
public static final int MAX_PROJECTION_STACK_DEPTH = GL11.glGetInteger(GL11.GL_MAX_PROJECTION_STACK_DEPTH);
public static final int MAX_TEXTURE_STACK_DEPTH = GL11.glGetInteger(GL11.GL_MAX_TEXTURE_STACK_DEPTH);
public static final int MAX_TEXTURE_UNITS = GL11.glGetInteger(GL20.GL_MAX_TEXTURE_IMAGE_UNITS);
public static final int MAX_CLIP_PLANES = GL11.glGetInteger(GL11.GL_MAX_CLIP_PLANES);
public static final GLFeatureSet HAS_MULTIPLE_SET = new GLFeatureSet();
@Getter private static Vendor VENDOR;
// This setting varies depending on driver, so it gets queried at runtime
public static final int DEFAULT_DRAW_BUFFER = GL11.glGetInteger(GL11.GL_DRAW_BUFFER);
private static Thread CurrentThread = MainThread;
@Setter @Getter private static boolean runningSplash = true;
private static volatile boolean splashComplete = false;
private static volatile Thread drawableGLHolder = MainThread;
// Reference to SharedDrawable so makeCurrent() can distinguish it from DrawableGL
@Setter private static volatile Drawable sharedDrawable = null;
public static boolean isCachingEnabled() {
if (splashComplete) return true;
return Thread.currentThread() == drawableGLHolder;
}
/**
* Check if splash screen is complete.
* After splash, there's only one GL context and no locking is needed.
*/
public static boolean isSplashComplete() {
return splashComplete;
}
/**
* Get the active texture unit for server-side state operations.
* If caching is enabled, returns cached value.
* If caching is disabled (SharedDrawable), queries actual GL state.
*/
public static int getActiveTextureUnitForServerState() {
if (isCachingEnabled()) {
return getActiveTextureUnit();
}
// Query actual GL state for SharedDrawable context
return GL11.glGetInteger(GL13.GL_ACTIVE_TEXTURE) - GL13.GL_TEXTURE0;
}
/**
* Get the texture bound to the current texture unit for server-side state operations.
* If caching is enabled, returns cached value.
* If caching is disabled (SharedDrawable), queries actual GL state.
*/
public static int getBoundTextureForServerState() {
if (isCachingEnabled()) {
return getBoundTexture();
}
// Query actual GL state for SharedDrawable context
return GL11.glGetInteger(GL11.GL_TEXTURE_BINDING_2D);
}
/**
* Get the texture bound to a specific texture unit for server-side state operations.
* If caching is enabled, returns cached value.
* If caching is disabled (SharedDrawable), returns -1 to force operations to proceed
*/
public static int getBoundTextureForServerState(int unit) {
if (isCachingEnabled()) {
return getBoundTexture(unit);
}
return -1;
}
// GLStateManager State Trackers
private static final IntStack attribs = new IntArrayList(MAX_ATTRIB_STACK_DEPTH);
// Lazy copy-on-write tracking: only iterate modified states during popState
@Getter private static int attribDepth = 0;
@SuppressWarnings("unchecked")
private static final List<IStateStack<?>>[] modifiedAtDepth = new List[MAX_ATTRIB_STACK_DEPTH];
static {
for (int i = 0; i < MAX_ATTRIB_STACK_DEPTH; i++) {
modifiedAtDepth[i] = new ArrayList<>();
}
}
/** Register a state stack as modified at the current depth (called from beforeModify). */
public static void registerModifiedState(IStateStack<?> stack) {
if (attribDepth > 0) {
modifiedAtDepth[attribDepth - 1].add(stack);
}
}
protected static final IntegerStateStack activeTextureUnit = new IntegerStateStack(0);
protected static final IntegerStateStack shadeModelState = new IntegerStateStack(GL11.GL_SMOOTH);
// Client array state (not push/pop tracked, but needed for display list compilation)
@Getter private static final ClientArrayState clientArrayState = new ClientArrayState();
@Getter protected static final TextureUnitArray textures = new TextureUnitArray();
@Getter protected static final BlendStateStack blendState = new BlendStateStack();
@Getter protected static final BooleanStateStack blendMode = new BooleanStateStack(GL11.GL_BLEND);
@Getter protected static final BooleanStateStack scissorTest = new BooleanStateStack(GL11.GL_SCISSOR_TEST);
@Getter protected static final DepthStateStack depthState = new DepthStateStack();
@Getter protected static final BooleanStateStack depthTest = new BooleanStateStack(GL11.GL_DEPTH_TEST);
@Getter protected static final FogStateStack fogState = new FogStateStack();
@Getter protected static final BooleanStateStack fogMode = new BooleanStateStack(GL11.GL_FOG);
@Getter protected static final Color4Stack color = new Color4Stack();
@Getter protected static final Color4Stack clearColor = new Color4Stack(new Color4(0.0F, 0.0F, 0.0F, 0.0F));
@Getter protected static final ColorMaskStack colorMask = new ColorMaskStack();
@Getter protected static final IntegerStateStack drawBuffer = new IntegerStateStack(DEFAULT_DRAW_BUFFER);
@Getter protected static final BooleanStateStack cullState = new BooleanStateStack(GL11.GL_CULL_FACE);
@Getter protected static final AlphaStateStack alphaState = new AlphaStateStack();
@Getter protected static final BooleanStateStack alphaTest = new BooleanStateStack(GL11.GL_ALPHA_TEST);
@Getter protected static final BooleanStateStack lightingState = new BooleanStateStack(GL11.GL_LIGHTING);
@Getter protected static final BooleanStateStack rescaleNormalState = new BooleanStateStack(GL12.GL_RESCALE_NORMAL);
@Getter protected static final BooleanStateStack normalizeState = new BooleanStateStack(GL11.GL_NORMALIZE);
// Additional enable bit states tracked by GL_ENABLE_BIT
@Getter protected static final BooleanStateStack ditherState = new BooleanStateStack(GL11.GL_DITHER, true); // Defaults to true per OpenGL spec
@Getter protected static final BooleanStateStack stencilTest = new BooleanStateStack(GL11.GL_STENCIL_TEST);
@Getter protected static final BooleanStateStack lineSmoothState = new BooleanStateStack(GL11.GL_LINE_SMOOTH);
@Getter protected static final BooleanStateStack lineStippleState = new BooleanStateStack(GL11.GL_LINE_STIPPLE);
@Getter protected static final BooleanStateStack pointSmoothState = new BooleanStateStack(GL11.GL_POINT_SMOOTH);
@Getter protected static final BooleanStateStack polygonSmoothState = new BooleanStateStack(GL11.GL_POLYGON_SMOOTH);
@Getter protected static final BooleanStateStack polygonStippleState = new BooleanStateStack(GL11.GL_POLYGON_STIPPLE);
@Getter protected static final BooleanStateStack multisampleState = new BooleanStateStack(GL13.GL_MULTISAMPLE, true); // Defaults to true per OpenGL spec
@Getter protected static final BooleanStateStack sampleAlphaToCoverageState = new BooleanStateStack(GL13.GL_SAMPLE_ALPHA_TO_COVERAGE);
@Getter protected static final BooleanStateStack sampleAlphaToOneState = new BooleanStateStack(GL13.GL_SAMPLE_ALPHA_TO_ONE);
@Getter protected static final BooleanStateStack sampleCoverageState = new BooleanStateStack(GL13.GL_SAMPLE_COVERAGE);
@Getter protected static final BooleanStateStack colorLogicOpState = new BooleanStateStack(GL11.GL_COLOR_LOGIC_OP);
@Getter protected static final BooleanStateStack indexLogicOpState = new BooleanStateStack(GL11.GL_INDEX_LOGIC_OP);
// Polygon offset states (enable bits)
@Getter protected static final BooleanStateStack polygonOffsetPointState = new BooleanStateStack(GL11.GL_POLYGON_OFFSET_POINT);
@Getter protected static final BooleanStateStack polygonOffsetLineState = new BooleanStateStack(GL11.GL_POLYGON_OFFSET_LINE);
@Getter protected static final BooleanStateStack polygonOffsetFillState = new BooleanStateStack(GL11.GL_POLYGON_OFFSET_FILL);
// Line state (GL_LINE_BIT)
@Getter protected static final LineStateStack lineState = new LineStateStack();
// Point state (GL_POINT_BIT)
@Getter protected static final PointStateStack pointState = new PointStateStack();
// Polygon state (GL_POLYGON_BIT) - mode, offset values, cull face mode, front face
@Getter protected static final PolygonStateStack polygonState = new PolygonStateStack();
// Stencil state (GL_STENCIL_BUFFER_BIT)
@Getter protected static final StencilStateStack stencilState = new StencilStateStack();
// Evaluator states
@Getter protected static final BooleanStateStack autoNormalState = new BooleanStateStack(GL11.GL_AUTO_NORMAL);
@Getter protected static final BooleanStateStack map1Color4State = new BooleanStateStack(GL11.GL_MAP1_COLOR_4);
@Getter protected static final BooleanStateStack map1IndexState = new BooleanStateStack(GL11.GL_MAP1_INDEX);
@Getter protected static final BooleanStateStack map1NormalState = new BooleanStateStack(GL11.GL_MAP1_NORMAL);
@Getter protected static final BooleanStateStack map1TextureCoord1State = new BooleanStateStack(GL11.GL_MAP1_TEXTURE_COORD_1);
@Getter protected static final BooleanStateStack map1TextureCoord2State = new BooleanStateStack(GL11.GL_MAP1_TEXTURE_COORD_2);
@Getter protected static final BooleanStateStack map1TextureCoord3State = new BooleanStateStack(GL11.GL_MAP1_TEXTURE_COORD_3);
@Getter protected static final BooleanStateStack map1TextureCoord4State = new BooleanStateStack(GL11.GL_MAP1_TEXTURE_COORD_4);
@Getter protected static final BooleanStateStack map1Vertex3State = new BooleanStateStack(GL11.GL_MAP1_VERTEX_3);
@Getter protected static final BooleanStateStack map1Vertex4State = new BooleanStateStack(GL11.GL_MAP1_VERTEX_4);
@Getter protected static final BooleanStateStack map2Color4State = new BooleanStateStack(GL11.GL_MAP2_COLOR_4);
@Getter protected static final BooleanStateStack map2IndexState = new BooleanStateStack(GL11.GL_MAP2_INDEX);
@Getter protected static final BooleanStateStack map2NormalState = new BooleanStateStack(GL11.GL_MAP2_NORMAL);
@Getter protected static final BooleanStateStack map2TextureCoord1State = new BooleanStateStack(GL11.GL_MAP2_TEXTURE_COORD_1);
@Getter protected static final BooleanStateStack map2TextureCoord2State = new BooleanStateStack(GL11.GL_MAP2_TEXTURE_COORD_2);
@Getter protected static final BooleanStateStack map2TextureCoord3State = new BooleanStateStack(GL11.GL_MAP2_TEXTURE_COORD_3);
@Getter protected static final BooleanStateStack map2TextureCoord4State = new BooleanStateStack(GL11.GL_MAP2_TEXTURE_COORD_4);
@Getter protected static final BooleanStateStack map2Vertex3State = new BooleanStateStack(GL11.GL_MAP2_VERTEX_3);
@Getter protected static final BooleanStateStack map2Vertex4State = new BooleanStateStack(GL11.GL_MAP2_VERTEX_4);
// Clip plane states
@Getter protected static final BooleanStateStack[] clipPlaneStates = new BooleanStateStack[MAX_CLIP_PLANES];
@Getter protected static final MatrixModeStack matrixMode = new MatrixModeStack();
@Getter protected static final Matrix4fStack modelViewMatrix = new Matrix4fStack(MAX_MODELVIEW_STACK_DEPTH);
@Getter protected static final Matrix4fStack projectionMatrix = new Matrix4fStack(MAX_PROJECTION_STACK_DEPTH);
@Getter protected static final BooleanStateStack[] lightStates = new BooleanStateStack[8];
@Getter protected static final LightStateStack[] lightDataStates = new LightStateStack[8];
@Getter protected static final BooleanStateStack colorMaterial = new BooleanStateStack(GL11.GL_COLOR_MATERIAL);
@Getter protected static final IntegerStateStack colorMaterialFace = new IntegerStateStack(GL11.GL_FRONT_AND_BACK);
@Getter protected static final IntegerStateStack colorMaterialParameter = new IntegerStateStack(GL11.GL_AMBIENT_AND_DIFFUSE);
@Getter protected static final LightModelStateStack lightModel = new LightModelStateStack();
@Getter protected static final MaterialStateStack frontMaterial = new MaterialStateStack(GL11.GL_FRONT);
@Getter protected static final MaterialStateStack backMaterial = new MaterialStateStack(GL11.GL_BACK);
private static final MethodHandle MAT4_STACK_CURR_DEPTH;
static {
for (int i = 0; i < lightStates.length; i ++) {
lightStates[i] = new BooleanStateStack(GL11.GL_LIGHT0 + i);
lightDataStates[i] = new LightStateStack(GL11.GL_LIGHT0 + i);
}
for (int i = 0; i < MAX_CLIP_PLANES; i++) {
clipPlaneStates[i] = new BooleanStateStack(GL11.GL_CLIP_PLANE0 + i);
}
try {
final Field curr = ReflectionHelper.findField(Matrix4fStack.class, "curr");
curr.setAccessible(true);
MAT4_STACK_CURR_DEPTH = MethodHandles.lookup().unreflectGetter(curr);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
@Getter protected static final ViewPortStateStack viewportState = new ViewPortStateStack();
@Getter protected static int activeProgram = 0;
public static void reset() {
runningSplash = true;
while(!attribs.isEmpty()) {
attribs.popInt();
}
final List<IStateStack<?>> stacks = Feature.maskToFeatures(GL11.GL_ALL_ATTRIB_BITS);
final int size = stacks.size();
for(int i = 0; i < size; i++) {
final IStateStack<?> stack = stacks.get(i);
while(!stack.isEmpty()) {
stack.pop();
}
}
modelViewMatrix.clear();
projectionMatrix.clear();
}
// Iris Listeners
private static Runnable blendFuncListener = null;
private static Runnable fogToggleListener = null;
private static Runnable fogModeListener = null;
private static Runnable fogStartListener = null;
private static Runnable fogEndListener = null;
private static Runnable fogDensityListener = null;
/**
* Check if a display list exists (has been compiled and stored).
* Delegates to DisplayListManager.
*
* @param list The display list ID to check
* @return true if the display list exists, false otherwise
*/
public static boolean displayListExists(int list) {
return DisplayListManager.displayListExists(list);
}
public static class GLFeatureSet extends IntOpenHashSet {
private static final long serialVersionUID = 8558779940775721010L;
public GLFeatureSet addFeature(int feature) {
super.add(feature);
return this;
}
}
public static void preInit() {
capabilities = GLContext.getCapabilities();
HAS_MULTIPLE_SET
.addFeature(GL11.GL_ACCUM_CLEAR_VALUE)
.addFeature(GL14.GL_BLEND_COLOR)
.addFeature(GL11.GL_COLOR_CLEAR_VALUE)
.addFeature(GL11.GL_COLOR_WRITEMASK)
.addFeature(GL11.GL_CURRENT_COLOR)
.addFeature(GL11.GL_CURRENT_NORMAL)
.addFeature(GL11.GL_CURRENT_RASTER_COLOR)
.addFeature(GL11.GL_CURRENT_RASTER_POSITION)
.addFeature(GL11.GL_CURRENT_RASTER_TEXTURE_COORDS)
.addFeature(GL11.GL_CURRENT_TEXTURE_COORDS)
.addFeature(GL11.GL_DEPTH_RANGE)
.addFeature(GL11.GL_FOG_COLOR)
.addFeature(GL11.GL_LIGHT_MODEL_AMBIENT)
.addFeature(GL11.GL_LINE_WIDTH_RANGE)
.addFeature(GL11.GL_MAP1_GRID_DOMAIN)
.addFeature(GL11.GL_MAP2_GRID_DOMAIN)
.addFeature(GL11.GL_MAP2_GRID_SEGMENTS)
.addFeature(GL11.GL_MAX_VIEWPORT_DIMS)
.addFeature(GL11.GL_MODELVIEW_MATRIX)
.addFeature(GL11.GL_POINT_SIZE_RANGE)
.addFeature(GL11.GL_POLYGON_MODE)
.addFeature(GL11.GL_PROJECTION_MATRIX)
.addFeature(GL11.GL_SCISSOR_BOX)
.addFeature(GL11.GL_TEXTURE_ENV_COLOR)
.addFeature(GL11.GL_TEXTURE_MATRIX)
.addFeature(GL11.GL_VIEWPORT);
final String glVendor = GL11.glGetString(GL11.GL_VENDOR);
VENDOR = Vendor.getVendor(glVendor.toLowerCase());
if (vendorIsAMD()) {
// AMD Drivers seem to default to 0 for the matrix mode, so we need to set it to the default
GL11.glMatrixMode(GL11.GL_MODELVIEW);
}
final Minecraft mc = Minecraft.getMinecraft();
if (mc != null) {
// Initialize viewport state from display dimensions.
// After Display.create(), viewport is (0, 0, width, height)
viewportState.setViewPort(0, 0, mc.displayWidth, mc.displayHeight);
}
}
public static void init() {
RenderSystem.initRenderer();
if (Iris.enabled) {
StateUpdateNotifiers.blendFuncNotifier = listener -> blendFuncListener = listener;
StateUpdateNotifiers.fogToggleNotifier = listener -> fogToggleListener = listener;
StateUpdateNotifiers.fogModeNotifier = listener -> fogModeListener = listener;
StateUpdateNotifiers.fogStartNotifier = listener -> fogStartListener = listener;
StateUpdateNotifiers.fogEndNotifier = listener -> fogEndListener = listener;
StateUpdateNotifiers.fogDensityNotifier = listener -> fogDensityListener = listener;
}
if(BYPASS_CACHE) {
LOGGER.info("GLStateManager cache bypassed");
}
if(AngelicaMod.lwjglDebug) {
LOGGER.info("Enabling additional LWJGL debug output");
GLDebug.setupDebugMessageCallback();
GLDebug.initDebugState();
GLDebug.debugMessage("Angelica Debug Annotator Initialized");
}
}
public static void assertMainThread() {
if (Thread.currentThread() != CurrentThread && !runningSplash) {
LOGGER.info("Call from not the Current Thread! - " + Thread.currentThread().getName() + " Current thread: " + CurrentThread.getName());
}
}
public static boolean shouldBypassCache() {
// Bypass cache when not using the main DrawableGL context
return BYPASS_CACHE || !isCachingEnabled();
}
/**
* Returns true if we should use DSA for texture operations.
* DSA relies on cached texture bindings, which aren't tracked when caching is disabled.
* Also, proxy textures are special query textures that shouldn't use DSA.
*/
private static boolean shouldUseDSA(int target) {
if (!isCachingEnabled()) return false;
// Proxy textures are for capability queries, not real textures
return target != GL11.GL_PROXY_TEXTURE_1D
&& target != GL11.GL_PROXY_TEXTURE_2D
&& target != GL12.GL_PROXY_TEXTURE_3D;
}
// LWJGL Overrides
public static void glEnable(int cap) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordEnable(cap);
if (mode == RecordMode.COMPILE) {
return;
}
}
// Handle clip planes dynamically (supports up to MAX_CLIP_PLANES)
if (cap >= GL11.GL_CLIP_PLANE0 && cap < GL11.GL_CLIP_PLANE0 + MAX_CLIP_PLANES) {
clipPlaneStates[cap - GL11.GL_CLIP_PLANE0].enable();
return;
}
switch (cap) {
case GL11.GL_ALPHA_TEST -> enableAlphaTest();
case GL11.GL_AUTO_NORMAL -> autoNormalState.enable();
case GL11.GL_BLEND -> enableBlend();
case GL11.GL_COLOR_MATERIAL -> enableColorMaterial();
case GL11.GL_COLOR_LOGIC_OP -> colorLogicOpState.enable();
case GL11.GL_CULL_FACE -> enableCull();
case GL11.GL_DEPTH_TEST -> enableDepthTest();
case GL11.GL_DITHER -> ditherState.enable();
case GL11.GL_FOG -> enableFog();
case GL11.GL_INDEX_LOGIC_OP -> indexLogicOpState.enable();
case GL11.GL_LIGHTING -> enableLighting();
case GL11.GL_LIGHT0 -> enableLight(0);
case GL11.GL_LIGHT1 -> enableLight(1);
case GL11.GL_LIGHT2 -> enableLight(2);
case GL11.GL_LIGHT3 -> enableLight(3);
case GL11.GL_LIGHT4 -> enableLight(4);
case GL11.GL_LIGHT5 -> enableLight(5);
case GL11.GL_LIGHT6 -> enableLight(6);
case GL11.GL_LIGHT7 -> enableLight(7);
case GL11.GL_LINE_SMOOTH -> lineSmoothState.enable();
case GL11.GL_LINE_STIPPLE -> lineStippleState.enable();
case GL11.GL_MAP1_COLOR_4 -> map1Color4State.enable();
case GL11.GL_MAP1_INDEX -> map1IndexState.enable();
case GL11.GL_MAP1_NORMAL -> map1NormalState.enable();
case GL11.GL_MAP1_TEXTURE_COORD_1 -> map1TextureCoord1State.enable();
case GL11.GL_MAP1_TEXTURE_COORD_2 -> map1TextureCoord2State.enable();
case GL11.GL_MAP1_TEXTURE_COORD_3 -> map1TextureCoord3State.enable();
case GL11.GL_MAP1_TEXTURE_COORD_4 -> map1TextureCoord4State.enable();
case GL11.GL_MAP1_VERTEX_3 -> map1Vertex3State.enable();
case GL11.GL_MAP1_VERTEX_4 -> map1Vertex4State.enable();
case GL11.GL_MAP2_COLOR_4 -> map2Color4State.enable();
case GL11.GL_MAP2_INDEX -> map2IndexState.enable();
case GL11.GL_MAP2_NORMAL -> map2NormalState.enable();
case GL11.GL_MAP2_TEXTURE_COORD_1 -> map2TextureCoord1State.enable();
case GL11.GL_MAP2_TEXTURE_COORD_2 -> map2TextureCoord2State.enable();
case GL11.GL_MAP2_TEXTURE_COORD_3 -> map2TextureCoord3State.enable();
case GL11.GL_MAP2_TEXTURE_COORD_4 -> map2TextureCoord4State.enable();
case GL11.GL_MAP2_VERTEX_3 -> map2Vertex3State.enable();
case GL11.GL_MAP2_VERTEX_4 -> map2Vertex4State.enable();
case GL13.GL_MULTISAMPLE -> multisampleState.enable();
case GL11.GL_NORMALIZE -> normalizeState.enable();
case GL11.GL_POINT_SMOOTH -> pointSmoothState.enable();
case GL11.GL_POLYGON_OFFSET_POINT -> polygonOffsetPointState.enable();
case GL11.GL_POLYGON_OFFSET_LINE -> polygonOffsetLineState.enable();
case GL11.GL_POLYGON_OFFSET_FILL -> polygonOffsetFillState.enable();
case GL11.GL_POLYGON_SMOOTH -> polygonSmoothState.enable();
case GL11.GL_POLYGON_STIPPLE -> polygonStippleState.enable();
case GL12.GL_RESCALE_NORMAL -> enableRescaleNormal();
case GL13.GL_SAMPLE_ALPHA_TO_COVERAGE -> sampleAlphaToCoverageState.enable();
case GL13.GL_SAMPLE_ALPHA_TO_ONE -> sampleAlphaToOneState.enable();
case GL13.GL_SAMPLE_COVERAGE -> sampleCoverageState.enable();
case GL11.GL_SCISSOR_TEST -> enableScissorTest();
case GL11.GL_STENCIL_TEST -> stencilTest.enable();
case GL11.GL_TEXTURE_1D -> textures.getTexture1DStates(activeTextureUnit.getValue()).enable();
case GL11.GL_TEXTURE_2D -> enableTexture();
case GL12.GL_TEXTURE_3D -> textures.getTexture3DStates(activeTextureUnit.getValue()).enable();
case GL11.GL_TEXTURE_GEN_S -> textures.getTexGenSStates(activeTextureUnit.getValue()).enable();
case GL11.GL_TEXTURE_GEN_T -> textures.getTexGenTStates(activeTextureUnit.getValue()).enable();
case GL11.GL_TEXTURE_GEN_R -> textures.getTexGenRStates(activeTextureUnit.getValue()).enable();
case GL11.GL_TEXTURE_GEN_Q -> textures.getTexGenQStates(activeTextureUnit.getValue()).enable();
default -> GL11.glEnable(cap);
}
}
public static void glDisable(int cap) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordDisable(cap);
if (mode == RecordMode.COMPILE) {
return;
}
}
// Handle clip planes dynamically (supports up to MAX_CLIP_PLANES)
if (cap >= GL11.GL_CLIP_PLANE0 && cap < GL11.GL_CLIP_PLANE0 + MAX_CLIP_PLANES) {
clipPlaneStates[cap - GL11.GL_CLIP_PLANE0].disable();
return;
}
switch (cap) {
case GL11.GL_ALPHA_TEST -> disableAlphaTest();
case GL11.GL_AUTO_NORMAL -> autoNormalState.disable();
case GL11.GL_BLEND -> disableBlend();
case GL11.GL_COLOR_MATERIAL -> disableColorMaterial();
case GL11.GL_COLOR_LOGIC_OP -> colorLogicOpState.disable();
case GL11.GL_CULL_FACE -> disableCull();
case GL11.GL_DEPTH_TEST -> disableDepthTest();
case GL11.GL_DITHER -> ditherState.disable();
case GL11.GL_FOG -> disableFog();
case GL11.GL_INDEX_LOGIC_OP -> indexLogicOpState.disable();
case GL11.GL_LIGHTING -> disableLighting();
case GL11.GL_LIGHT0 -> disableLight(0);
case GL11.GL_LIGHT1 -> disableLight(1);
case GL11.GL_LIGHT2 -> disableLight(2);
case GL11.GL_LIGHT3 -> disableLight(3);
case GL11.GL_LIGHT4 -> disableLight(4);
case GL11.GL_LIGHT5 -> disableLight(5);
case GL11.GL_LIGHT6 -> disableLight(6);
case GL11.GL_LIGHT7 -> disableLight(7);
case GL11.GL_LINE_SMOOTH -> lineSmoothState.disable();
case GL11.GL_LINE_STIPPLE -> lineStippleState.disable();
case GL11.GL_MAP1_COLOR_4 -> map1Color4State.disable();
case GL11.GL_MAP1_INDEX -> map1IndexState.disable();
case GL11.GL_MAP1_NORMAL -> map1NormalState.disable();
case GL11.GL_MAP1_TEXTURE_COORD_1 -> map1TextureCoord1State.disable();
case GL11.GL_MAP1_TEXTURE_COORD_2 -> map1TextureCoord2State.disable();
case GL11.GL_MAP1_TEXTURE_COORD_3 -> map1TextureCoord3State.disable();
case GL11.GL_MAP1_TEXTURE_COORD_4 -> map1TextureCoord4State.disable();
case GL11.GL_MAP1_VERTEX_3 -> map1Vertex3State.disable();
case GL11.GL_MAP1_VERTEX_4 -> map1Vertex4State.disable();
case GL11.GL_MAP2_COLOR_4 -> map2Color4State.disable();
case GL11.GL_MAP2_INDEX -> map2IndexState.disable();
case GL11.GL_MAP2_NORMAL -> map2NormalState.disable();
case GL11.GL_MAP2_TEXTURE_COORD_1 -> map2TextureCoord1State.disable();
case GL11.GL_MAP2_TEXTURE_COORD_2 -> map2TextureCoord2State.disable();
case GL11.GL_MAP2_TEXTURE_COORD_3 -> map2TextureCoord3State.disable();
case GL11.GL_MAP2_TEXTURE_COORD_4 -> map2TextureCoord4State.disable();
case GL11.GL_MAP2_VERTEX_3 -> map2Vertex3State.disable();
case GL11.GL_MAP2_VERTEX_4 -> map2Vertex4State.disable();
case GL13.GL_MULTISAMPLE -> multisampleState.disable();
case GL11.GL_NORMALIZE -> normalizeState.disable();
case GL11.GL_POINT_SMOOTH -> pointSmoothState.disable();
case GL11.GL_POLYGON_OFFSET_POINT -> polygonOffsetPointState.disable();
case GL11.GL_POLYGON_OFFSET_LINE -> polygonOffsetLineState.disable();
case GL11.GL_POLYGON_OFFSET_FILL -> polygonOffsetFillState.disable();
case GL11.GL_POLYGON_SMOOTH -> polygonSmoothState.disable();
case GL11.GL_POLYGON_STIPPLE -> polygonStippleState.disable();
case GL12.GL_RESCALE_NORMAL -> disableRescaleNormal();
case GL13.GL_SAMPLE_ALPHA_TO_COVERAGE -> sampleAlphaToCoverageState.disable();
case GL13.GL_SAMPLE_ALPHA_TO_ONE -> sampleAlphaToOneState.disable();
case GL13.GL_SAMPLE_COVERAGE -> sampleCoverageState.disable();
case GL11.GL_SCISSOR_TEST -> disableScissorTest();
case GL11.GL_STENCIL_TEST -> stencilTest.disable();
case GL11.GL_TEXTURE_1D -> textures.getTexture1DStates(activeTextureUnit.getValue()).disable();
case GL11.GL_TEXTURE_2D -> disableTexture();
case GL12.GL_TEXTURE_3D -> textures.getTexture3DStates(activeTextureUnit.getValue()).disable();
case GL11.GL_TEXTURE_GEN_S -> textures.getTexGenSStates(activeTextureUnit.getValue()).disable();
case GL11.GL_TEXTURE_GEN_T -> textures.getTexGenTStates(activeTextureUnit.getValue()).disable();
case GL11.GL_TEXTURE_GEN_R -> textures.getTexGenRStates(activeTextureUnit.getValue()).disable();
case GL11.GL_TEXTURE_GEN_Q -> textures.getTexGenQStates(activeTextureUnit.getValue()).disable();
default -> GL11.glDisable(cap);
}
}
public static boolean glIsEnabled(int cap) {
if(shouldBypassCache()) {
return GL11.glIsEnabled(cap);
}
// Handle clip planes dynamically (supports up to MAX_CLIP_PLANES)
if (cap >= GL11.GL_CLIP_PLANE0 && cap < GL11.GL_CLIP_PLANE0 + MAX_CLIP_PLANES) {
return clipPlaneStates[cap - GL11.GL_CLIP_PLANE0].isEnabled();
}
return switch (cap) {
case GL11.GL_ALPHA_TEST -> alphaTest.isEnabled();
case GL11.GL_AUTO_NORMAL -> autoNormalState.isEnabled();
case GL11.GL_BLEND -> blendMode.isEnabled();
case GL11.GL_COLOR_MATERIAL -> colorMaterial.isEnabled();
case GL11.GL_COLOR_LOGIC_OP -> colorLogicOpState.isEnabled();
case GL11.GL_CULL_FACE -> cullState.isEnabled();
case GL11.GL_DEPTH_TEST -> depthTest.isEnabled();
case GL11.GL_DITHER -> ditherState.isEnabled();
case GL11.GL_FOG -> fogMode.isEnabled();
case GL11.GL_INDEX_LOGIC_OP -> indexLogicOpState.isEnabled();
case GL11.GL_LIGHTING -> lightingState.isEnabled();
case GL11.GL_LIGHT0 -> lightStates[0].isEnabled();
case GL11.GL_LIGHT1 -> lightStates[1].isEnabled();
case GL11.GL_LIGHT2 -> lightStates[2].isEnabled();
case GL11.GL_LIGHT3 -> lightStates[3].isEnabled();
case GL11.GL_LIGHT4 -> lightStates[4].isEnabled();
case GL11.GL_LIGHT5 -> lightStates[5].isEnabled();
case GL11.GL_LIGHT6 -> lightStates[6].isEnabled();
case GL11.GL_LIGHT7 -> lightStates[7].isEnabled();
case GL11.GL_LINE_SMOOTH -> lineSmoothState.isEnabled();
case GL11.GL_LINE_STIPPLE -> lineStippleState.isEnabled();
case GL11.GL_MAP1_COLOR_4 -> map1Color4State.isEnabled();
case GL11.GL_MAP1_INDEX -> map1IndexState.isEnabled();
case GL11.GL_MAP1_NORMAL -> map1NormalState.isEnabled();
case GL11.GL_MAP1_TEXTURE_COORD_1 -> map1TextureCoord1State.isEnabled();
case GL11.GL_MAP1_TEXTURE_COORD_2 -> map1TextureCoord2State.isEnabled();
case GL11.GL_MAP1_TEXTURE_COORD_3 -> map1TextureCoord3State.isEnabled();
case GL11.GL_MAP1_TEXTURE_COORD_4 -> map1TextureCoord4State.isEnabled();
case GL11.GL_MAP1_VERTEX_3 -> map1Vertex3State.isEnabled();
case GL11.GL_MAP1_VERTEX_4 -> map1Vertex4State.isEnabled();
case GL11.GL_MAP2_COLOR_4 -> map2Color4State.isEnabled();
case GL11.GL_MAP2_INDEX -> map2IndexState.isEnabled();
case GL11.GL_MAP2_NORMAL -> map2NormalState.isEnabled();
case GL11.GL_MAP2_TEXTURE_COORD_1 -> map2TextureCoord1State.isEnabled();
case GL11.GL_MAP2_TEXTURE_COORD_2 -> map2TextureCoord2State.isEnabled();
case GL11.GL_MAP2_TEXTURE_COORD_3 -> map2TextureCoord3State.isEnabled();
case GL11.GL_MAP2_TEXTURE_COORD_4 -> map2TextureCoord4State.isEnabled();
case GL11.GL_MAP2_VERTEX_3 -> map2Vertex3State.isEnabled();
case GL11.GL_MAP2_VERTEX_4 -> map2Vertex4State.isEnabled();
case GL13.GL_MULTISAMPLE -> multisampleState.isEnabled();
case GL11.GL_NORMALIZE -> normalizeState.isEnabled();
case GL11.GL_POINT_SMOOTH -> pointSmoothState.isEnabled();
case GL11.GL_POLYGON_OFFSET_POINT -> polygonOffsetPointState.isEnabled();
case GL11.GL_POLYGON_OFFSET_LINE -> polygonOffsetLineState.isEnabled();
case GL11.GL_POLYGON_OFFSET_FILL -> polygonOffsetFillState.isEnabled();
case GL11.GL_POLYGON_SMOOTH -> polygonSmoothState.isEnabled();
case GL11.GL_POLYGON_STIPPLE -> polygonStippleState.isEnabled();
case GL12.GL_RESCALE_NORMAL -> rescaleNormalState.isEnabled();
case GL13.GL_SAMPLE_ALPHA_TO_COVERAGE -> sampleAlphaToCoverageState.isEnabled();
case GL13.GL_SAMPLE_ALPHA_TO_ONE -> sampleAlphaToOneState.isEnabled();
case GL13.GL_SAMPLE_COVERAGE -> sampleCoverageState.isEnabled();
case GL11.GL_SCISSOR_TEST -> scissorTest.isEnabled();
case GL11.GL_STENCIL_TEST -> stencilTest.isEnabled();
case GL11.GL_TEXTURE_1D -> textures.getTexture1DStates(activeTextureUnit.getValue()).isEnabled();
case GL11.GL_TEXTURE_2D -> textures.getTextureUnitStates(activeTextureUnit.getValue()).isEnabled();
case GL12.GL_TEXTURE_3D -> textures.getTexture3DStates(activeTextureUnit.getValue()).isEnabled();
case GL11.GL_TEXTURE_GEN_S -> textures.getTexGenSStates(activeTextureUnit.getValue()).isEnabled();
case GL11.GL_TEXTURE_GEN_T -> textures.getTexGenTStates(activeTextureUnit.getValue()).isEnabled();
case GL11.GL_TEXTURE_GEN_R -> textures.getTexGenRStates(activeTextureUnit.getValue()).isEnabled();
case GL11.GL_TEXTURE_GEN_Q -> textures.getTexGenQStates(activeTextureUnit.getValue()).isEnabled();
default -> GL11.glIsEnabled(cap);
};
}
public static boolean glGetBoolean(int pname) {
if(shouldBypassCache()) {
return GL11.glGetBoolean(pname);
}
// Handle clip planes dynamically (supports up to MAX_CLIP_PLANES)
if (pname >= GL11.GL_CLIP_PLANE0 && pname < GL11.GL_CLIP_PLANE0 + MAX_CLIP_PLANES) {
return clipPlaneStates[pname - GL11.GL_CLIP_PLANE0].isEnabled();
}
return switch (pname) {
case GL11.GL_ALPHA_TEST -> alphaTest.isEnabled();
case GL11.GL_AUTO_NORMAL -> autoNormalState.isEnabled();
case GL11.GL_BLEND -> blendMode.isEnabled();
case GL11.GL_COLOR_MATERIAL -> colorMaterial.isEnabled();
case GL11.GL_COLOR_LOGIC_OP -> colorLogicOpState.isEnabled();
case GL11.GL_CULL_FACE -> cullState.isEnabled();
case GL11.GL_DEPTH_TEST -> depthTest.isEnabled();
case GL11.GL_DEPTH_WRITEMASK -> depthState.isEnabled();
case GL11.GL_DITHER -> ditherState.isEnabled();
case GL11.GL_FOG -> fogMode.isEnabled();
case GL11.GL_INDEX_LOGIC_OP -> indexLogicOpState.isEnabled();
case GL11.GL_LIGHTING -> lightingState.isEnabled();
case GL11.GL_LIGHT0 -> lightStates[0].isEnabled();
case GL11.GL_LIGHT1 -> lightStates[1].isEnabled();
case GL11.GL_LIGHT2 -> lightStates[2].isEnabled();
case GL11.GL_LIGHT3 -> lightStates[3].isEnabled();
case GL11.GL_LIGHT4 -> lightStates[4].isEnabled();
case GL11.GL_LIGHT5 -> lightStates[5].isEnabled();
case GL11.GL_LIGHT6 -> lightStates[6].isEnabled();
case GL11.GL_LIGHT7 -> lightStates[7].isEnabled();
case GL11.GL_LINE_SMOOTH -> lineSmoothState.isEnabled();
case GL11.GL_LINE_STIPPLE -> lineStippleState.isEnabled();
case GL11.GL_MAP1_COLOR_4 -> map1Color4State.isEnabled();
case GL11.GL_MAP1_INDEX -> map1IndexState.isEnabled();
case GL11.GL_MAP1_NORMAL -> map1NormalState.isEnabled();
case GL11.GL_MAP1_TEXTURE_COORD_1 -> map1TextureCoord1State.isEnabled();
case GL11.GL_MAP1_TEXTURE_COORD_2 -> map1TextureCoord2State.isEnabled();
case GL11.GL_MAP1_TEXTURE_COORD_3 -> map1TextureCoord3State.isEnabled();
case GL11.GL_MAP1_TEXTURE_COORD_4 -> map1TextureCoord4State.isEnabled();
case GL11.GL_MAP1_VERTEX_3 -> map1Vertex3State.isEnabled();
case GL11.GL_MAP1_VERTEX_4 -> map1Vertex4State.isEnabled();
case GL11.GL_MAP2_COLOR_4 -> map2Color4State.isEnabled();
case GL11.GL_MAP2_INDEX -> map2IndexState.isEnabled();
case GL11.GL_MAP2_NORMAL -> map2NormalState.isEnabled();
case GL11.GL_MAP2_TEXTURE_COORD_1 -> map2TextureCoord1State.isEnabled();
case GL11.GL_MAP2_TEXTURE_COORD_2 -> map2TextureCoord2State.isEnabled();
case GL11.GL_MAP2_TEXTURE_COORD_3 -> map2TextureCoord3State.isEnabled();
case GL11.GL_MAP2_TEXTURE_COORD_4 -> map2TextureCoord4State.isEnabled();
case GL11.GL_MAP2_VERTEX_3 -> map2Vertex3State.isEnabled();
case GL11.GL_MAP2_VERTEX_4 -> map2Vertex4State.isEnabled();
case GL13.GL_MULTISAMPLE -> multisampleState.isEnabled();
case GL11.GL_NORMALIZE -> normalizeState.isEnabled();
case GL11.GL_POINT_SMOOTH -> pointSmoothState.isEnabled();
case GL11.GL_POLYGON_OFFSET_POINT -> polygonOffsetPointState.isEnabled();
case GL11.GL_POLYGON_OFFSET_LINE -> polygonOffsetLineState.isEnabled();
case GL11.GL_POLYGON_OFFSET_FILL -> polygonOffsetFillState.isEnabled();
case GL11.GL_POLYGON_SMOOTH -> polygonSmoothState.isEnabled();
case GL11.GL_POLYGON_STIPPLE -> polygonStippleState.isEnabled();
case GL12.GL_RESCALE_NORMAL -> rescaleNormalState.isEnabled();
case GL13.GL_SAMPLE_ALPHA_TO_COVERAGE -> sampleAlphaToCoverageState.isEnabled();
case GL13.GL_SAMPLE_ALPHA_TO_ONE -> sampleAlphaToOneState.isEnabled();
case GL13.GL_SAMPLE_COVERAGE -> sampleCoverageState.isEnabled();
case GL11.GL_SCISSOR_TEST -> scissorTest.isEnabled();
case GL11.GL_STENCIL_TEST -> stencilTest.isEnabled();
case GL11.GL_TEXTURE_1D -> textures.getTexture1DStates(activeTextureUnit.getValue()).isEnabled();
case GL11.GL_TEXTURE_2D -> textures.getTextureUnitStates(activeTextureUnit.getValue()).isEnabled();
case GL12.GL_TEXTURE_3D -> textures.getTexture3DStates(activeTextureUnit.getValue()).isEnabled();
case GL11.GL_TEXTURE_GEN_S -> textures.getTexGenSStates(activeTextureUnit.getValue()).isEnabled();
case GL11.GL_TEXTURE_GEN_T -> textures.getTexGenTStates(activeTextureUnit.getValue()).isEnabled();
case GL11.GL_TEXTURE_GEN_R -> textures.getTexGenRStates(activeTextureUnit.getValue()).isEnabled();
case GL11.GL_TEXTURE_GEN_Q -> textures.getTexGenQStates(activeTextureUnit.getValue()).isEnabled();
default -> GL11.glGetBoolean(pname);
};
}
public static void glGetBoolean(int pname, ByteBuffer params) {
if(shouldBypassCache()) {
GL11.glGetBoolean(pname, params);
return;
}
switch (pname) {
case GL11.GL_COLOR_WRITEMASK -> {
params.put((byte) (colorMask.red ? GL11.GL_TRUE : GL11.GL_FALSE));
params.put((byte) (colorMask.green ? GL11.GL_TRUE : GL11.GL_FALSE));
params.put((byte) (colorMask.blue ? GL11.GL_TRUE : GL11.GL_FALSE));
params.put((byte) (colorMask.alpha ? GL11.GL_TRUE : GL11.GL_FALSE));
}
default -> {
if(!HAS_MULTIPLE_SET.contains(pname)) {
params.put(0, (byte) (glGetBoolean(pname) ? GL11.GL_TRUE : GL11.GL_FALSE));
} else {
GL11.glGetBoolean(pname, params);
}
}
}
}
@SneakyThrows
public static int getMatrixStackDepth(Matrix4fStack stack) {
// JOML's curr is 0-based (0 = no pushes), but OpenGL starts at 1 (base matrix counts)
return (int) MAT4_STACK_CURR_DEPTH.invokeExact(stack) + 1;
}
public static int glGetInteger(int pname) {
if(shouldBypassCache()) {
return GL11.glGetInteger(pname);
}
return switch (pname) {
case GL11.GL_ALPHA_TEST_FUNC -> alphaState.getFunction();
case GL11.GL_DEPTH_FUNC -> depthState.getFunc();
case GL11.GL_LIST_MODE -> DisplayListManager.getListMode();
case GL11.GL_MATRIX_MODE -> matrixMode.getMode();
case GL11.GL_SHADE_MODEL -> shadeModelState.getValue();
case GL11.GL_TEXTURE_BINDING_2D -> getBoundTextureForServerState();
case GL14.GL_BLEND_DST_ALPHA -> blendState.getDstAlpha();
case GL14.GL_BLEND_DST_RGB -> blendState.getDstRgb();
case GL14.GL_BLEND_SRC_ALPHA -> blendState.getSrcAlpha();
case GL14.GL_BLEND_SRC_RGB -> blendState.getSrcRgb();
case GL11.GL_COLOR_MATERIAL_FACE -> colorMaterialFace.getValue();
case GL11.GL_COLOR_MATERIAL_PARAMETER -> colorMaterialParameter.getValue();
case GL20.GL_CURRENT_PROGRAM -> activeProgram;
case GL11.GL_MODELVIEW_STACK_DEPTH -> getMatrixStackDepth(modelViewMatrix);
case GL11.GL_PROJECTION_STACK_DEPTH -> getMatrixStackDepth(projectionMatrix);
default -> GL11.glGetInteger(pname);
};
}
public static void glGetInteger(int pname, IntBuffer params) {
if(shouldBypassCache()) {
GL11.glGetInteger(pname, params);
return;
}
switch (pname) {
case GL11.GL_VIEWPORT -> viewportState.get(params);
default -> {
if(!HAS_MULTIPLE_SET.contains(pname)) {
params.put(0, glGetInteger(pname));
} else {
GL11.glGetInteger(pname, params);
}
}
}
}
public static void glGetMaterial(int face, int pname, FloatBuffer params) {
if (shouldBypassCache()) {
GL11.glGetMaterial(face, pname, params);
return;
}
final MaterialStateStack state;
if (face == GL11.GL_FRONT) {
state = frontMaterial;
} else if (face == GL11.GL_BACK) {
state = backMaterial;
} else {
throw new RuntimeException("Invalid face parameter specified to glGetMaterial: " + face);
}
switch (pname) {
case GL11.GL_AMBIENT -> state.ambient.get(0, params);
case GL11.GL_DIFFUSE -> state.diffuse.get(0, params);
case GL11.GL_SPECULAR -> state.specular.get(0, params);
case GL11.GL_EMISSION -> state.emission.get(0, params);
case GL11.GL_SHININESS -> params.put(state.shininess);
case GL11.GL_COLOR_INDEXES -> state.colorIndexes.get(0, params);
default -> GL11.glGetMaterial(face, pname, params);
}
}
public static void glGetLight(int light, int pname, FloatBuffer params) {
if (shouldBypassCache()) {
GL11.glGetLight(light, pname, params);
return;
}
final LightStateStack state = lightDataStates[light - GL11.GL_LIGHT0];
switch (pname) {
case GL11.GL_AMBIENT -> state.ambient.get(0, params);
case GL11.GL_DIFFUSE -> state.diffuse.get(0, params);
case GL11.GL_SPECULAR -> state.specular.get(0, params);
case GL11.GL_POSITION -> state.position.get(0, params);
case GL11.GL_SPOT_DIRECTION -> state.spotDirection.get(0, params);
case GL11.GL_SPOT_EXPONENT -> params.put(state.spotExponent);
case GL11.GL_SPOT_CUTOFF -> params.put(state.spotCutoff);
case GL11.GL_CONSTANT_ATTENUATION -> params.put(state.constantAttenuation);
case GL11.GL_LINEAR_ATTENUATION -> params.put(state.linearAttenuation);
case GL11.GL_QUADRATIC_ATTENUATION -> params.put(state.quadraticAttenuation);
default -> GL11.glGetLight(light, pname, params);
}
}
public static void glGetFloat(int pname, FloatBuffer params) {
if(shouldBypassCache()) {
GL11.glGetFloat(pname, params);
return;
}
switch (pname) {
case GL11.GL_MODELVIEW_MATRIX -> modelViewMatrix.get(0, params);
case GL11.GL_PROJECTION_MATRIX -> projectionMatrix.get(0, params);
// case GL11.GL_TEXTURE_MATRIX -> textures.getTextureUnitMatrix(getActiveTextureUnit()).get(0, params);
case GL11.GL_COLOR_CLEAR_VALUE -> clearColor.get(params);
case GL11.GL_CURRENT_COLOR -> color.get(params);
default -> {
if(!HAS_MULTIPLE_SET.contains(pname)) {
params.put(0, glGetFloat(pname));
} else {
GL11.glGetFloat(pname, params);
}
}
}
}
public static float glGetFloat(int pname) {
return GL11.glGetFloat(pname);
}
// GLStateManager Functions
public static void glBlendColor(float red, float green, float blue, float alpha) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordBlendColor(red, green, blue, alpha);
if (mode == RecordMode.COMPILE) {
return;
}
}
GL14.glBlendColor(red, green, blue, alpha);
}
public static void enableBlend() {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordEnable(GL11.GL_BLEND);
if (mode == RecordMode.COMPILE) {
return;
}
}
if (Iris.enabled) {
if (BlendModeStorage.isBlendLocked()) {
BlendModeStorage.deferBlendModeToggle(true);
return;
}
}
blendMode.enable();
}
public static void disableBlend() {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordDisable(GL11.GL_BLEND);
if (mode == RecordMode.COMPILE) {
return;
}
}
if (Iris.enabled) {
if (BlendModeStorage.isBlendLocked()) {
BlendModeStorage.deferBlendModeToggle(false);
return;
}
}
blendMode.disable();
}
public static void enableScissorTest() {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordEnable(GL11.GL_SCISSOR_TEST);
if (mode == RecordMode.COMPILE) {
return;
}
}
scissorTest.enable();
}
public static void disableScissorTest() {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordDisable(GL11.GL_SCISSOR_TEST);
if (mode == RecordMode.COMPILE) {
return;
}
}
scissorTest.disable();
}
public static void glBlendFunc(int srcFactor, int dstFactor) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordBlendFunc(srcFactor, dstFactor, srcFactor, dstFactor);
if (mode == RecordMode.COMPILE) {
return;
}
}
if (Iris.enabled) {
if (BlendModeStorage.isBlendLocked()) {
BlendModeStorage.deferBlendFunc(srcFactor, dstFactor, srcFactor, dstFactor);
return;
}
}
// Cache thread check - only update state on main thread, but always make GL call if needed
final boolean caching = isCachingEnabled();
if (HUDCaching.renderingCacheOverride) {
if (caching) blendState.setAll(srcFactor, dstFactor, GL11.GL_ONE, GL11.GL_ONE_MINUS_SRC_ALPHA);
OpenGlHelper.glBlendFunc(srcFactor, dstFactor, GL11.GL_ONE, GL11.GL_ONE_MINUS_SRC_ALPHA);
return;
}
final boolean bypass = BYPASS_CACHE || !caching;
if (bypass || blendState.getSrcRgb() != srcFactor || blendState.getDstRgb() != dstFactor) {
if (caching) blendState.setSrcDstRgb(srcFactor, dstFactor);
GL11.glBlendFunc(srcFactor, dstFactor);
}
// Iris
if (blendFuncListener != null) blendFuncListener.run();
}
public static void glBlendEquation(int mode) {
if (DisplayListManager.isRecording()) {
throw new UnsupportedOperationException("glBlendEquation in display lists not yet implemented - if you see this, please report!");
}
GL14.glBlendEquation(mode);
}
public static void glBlendEquationSeparate(int modeRGB, int modeAlpha) {
if (DisplayListManager.isRecording()) {
throw new UnsupportedOperationException("glBlendEquationSeparate in display lists not yet implemented - if you see this, please report!");
}
GL20.glBlendEquationSeparate(modeRGB, modeAlpha);
}
public static void tryBlendFuncSeparate(int srcRgb, int dstRgb, int srcAlpha, int dstAlpha) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordBlendFunc(srcRgb, dstRgb, srcAlpha, dstAlpha);
if (mode == RecordMode.COMPILE) {
return;
}
}
if (Iris.enabled) {
if (BlendModeStorage.isBlendLocked()) {
BlendModeStorage.deferBlendFunc(srcRgb, dstRgb, srcAlpha, dstAlpha);
return;
}
}
if (HUDCaching.renderingCacheOverride && dstAlpha != GL11.GL_ONE_MINUS_SRC_ALPHA) {
srcAlpha = GL11.GL_ONE;
dstAlpha = GL11.GL_ONE_MINUS_SRC_ALPHA;
}
// Cache thread check - only update state on main thread, but always make GL call if needed
final boolean caching = isCachingEnabled();
final boolean bypass = BYPASS_CACHE || !caching;
if (bypass || blendState.getSrcRgb() != srcRgb || blendState.getDstRgb() != dstRgb || blendState.getSrcAlpha() != srcAlpha || blendState.getDstAlpha() != dstAlpha) {
if (caching) blendState.setAll(srcRgb, dstRgb, srcAlpha, dstAlpha);
OpenGlHelper.glBlendFunc(srcRgb, dstRgb, srcAlpha, dstAlpha);
}
// Iris
if (blendFuncListener != null) blendFuncListener.run();
}
public static void checkCompiling() {
checkCompiling("");
}
public static void checkCompiling(String name) {
if (DisplayListManager.isRecording()) {
throw new UnsupportedOperationException("Not yet implemented (" + name + ")");
}
}
public static void glNormal3b(byte nx, byte ny, byte nz) {
if (DisplayListManager.isRecording()) {
final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder();
if (recorder != null) {
recorder.setNormal(b2f(nx), b2f(ny), b2f(nz));
}
return;
}
GL11.glNormal3b(nx, ny, nz);
}
public static void glNormal3d(double nx, double ny, double nz) {
if (DisplayListManager.isRecording()) {
final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder();
if (recorder != null) {
recorder.setNormal((float) nx, (float) ny, (float) nz);
}
return;
}
GL11.glNormal3d(nx, ny, nz);
}
public static void glNormal3f(float nx, float ny, float nz) {
if (DisplayListManager.isRecording()) {
final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder();
if (recorder != null) {
recorder.setNormal(nx, ny, nz);
}
return;
}
GL11.glNormal3f(nx, ny, nz);
}
public static void glNormal3i(int nx, int ny, int nz) {
if (DisplayListManager.isRecording()) {
final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder();
if (recorder != null) {
recorder.setNormal((float) nx, (float) ny, (float) nz);
}
return;
}
GL11.glNormal3i(nx, ny, nz);
}
public static void glDepthFunc(int func) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordDepthFunc(func);
if (mode == RecordMode.COMPILE) {
return;
}
}
final boolean caching = isCachingEnabled();
if (BYPASS_CACHE || !caching || func != depthState.getFunc()) {
if (caching) depthState.setFunc(func);
GL11.glDepthFunc(func);
}
}
public static void glDepthMask(boolean mask) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordDepthMask(mask);
if (mode == RecordMode.COMPILE) {
return;
}
}
if (Iris.enabled) {
if (DepthColorStorage.isDepthColorLocked()) {
DepthColorStorage.deferDepthEnable(mask);
return;
}
}
final boolean caching = isCachingEnabled();
if (BYPASS_CACHE || !caching || mask != depthState.isEnabled()) {
if (caching) depthState.setEnabled(mask);
GL11.glDepthMask(mask);
}
}
public static void glEdgeFlag(boolean flag) {
GL11.glEdgeFlag(flag);
}
public static void glColor4f(float red, float green, float blue, float alpha) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordColor(red, green, blue, alpha);
if (mode == RecordMode.COMPILE) {
return;
}
}
if (changeColor(red, green, blue, alpha)) {
GL11.glColor4f(red, green, blue, alpha);
}
}
public static void glColor4d(double red, double green, double blue, double alpha) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordColor((float) red, (float) green, (float) blue, (float) alpha);
if (mode == RecordMode.COMPILE) {
return;
}
}
if (changeColor((float) red, (float) green, (float) blue, (float) alpha)) {
GL11.glColor4d(red, green, blue, alpha);
}
}
public static void glColor4b(byte red, byte green, byte blue, byte alpha) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordColor(b2f(red), b2f(green), b2f(blue), b2f(alpha));
if (mode == RecordMode.COMPILE) {
return;
}
}
if (changeColor(b2f(red), b2f(green), b2f(blue), b2f(alpha))) {
GL11.glColor4b(red, green, blue, alpha);
}
}
public static void glColor4ub(byte red, byte green, byte blue, byte alpha) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordColor(ub2f(red), ub2f(green), ub2f(blue), ub2f(alpha));
if (mode == RecordMode.COMPILE) {
return;
}
}
if (changeColor(ub2f(red), ub2f(green), ub2f(blue), ub2f(alpha))) {
GL11.glColor4ub(red, green, blue, alpha);
}
}
public static void glColor3f(float red, float green, float blue) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordColor(red, green, blue, 1.0F);
if (mode == RecordMode.COMPILE) {
return;
}
}
if (changeColor(red, green, blue, 1.0F)) {
GL11.glColor3f(red, green, blue);
}
}
public static void glColor3d(double red, double green, double blue) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordColor((float) red, (float) green, (float) blue, 1.0F);
if (mode == RecordMode.COMPILE) {
return;
}
}
if (changeColor((float) red, (float) green, (float) blue, 1.0F)) {
GL11.glColor3d(red, green, blue);
}
}
public static void glColor3b(byte red, byte green, byte blue) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordColor(b2f(red), b2f(green), b2f(blue), 1.0F);
if (mode == RecordMode.COMPILE) {
return;
}
}
if (changeColor(b2f(red), b2f(green), b2f(blue), 1.0F)) {
GL11.glColor3b(red, green, blue);
}
}
public static void glColor3ub(byte red, byte green, byte blue) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordColor(ub2f(red), ub2f(green), ub2f(blue), 1.0F);
if (mode == RecordMode.COMPILE) {
return;
}
}
if (changeColor(ub2f(red), ub2f(green), ub2f(blue), 1.0F)) {
GL11.glColor3ub(red, green, blue);
}
}
private static float ub2f(byte b) {
return (b & 0xFF) / 255.0F;
}
private static float b2f(byte b) {
return ((b - Byte.MIN_VALUE) & 0xFF) / 255.0F;
}
public static float i2f(int i) { return ((i - Integer.MIN_VALUE) & 0xFFFFFFFFL) / 4294967295.0F; }
private static boolean changeColor(float red, float green, float blue, float alpha) {
// Helper function for glColor*
final boolean caching = isCachingEnabled();
if (BYPASS_CACHE || !caching || red != color.getRed() || green != color.getGreen() || blue != color.getBlue() || alpha != color.getAlpha()) {
if (caching) {
color.setRed(red);
color.setGreen(green);
color.setBlue(blue);
color.setAlpha(alpha);
}
return true;
}
return false;
}
private static final Color4 DirtyColor = new Color4(-1.0F, -1.0F, -1.0F, -1.0F);
public static void clearCurrentColor() {
// Marks the cache dirty, doesn't actually reset the color
color.set(DirtyColor);
}
public static void glColorMask(boolean red, boolean green, boolean blue, boolean alpha) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordColorMask(red, green, blue, alpha);
if (mode == RecordMode.COMPILE) {
return;
}
}
if (Iris.enabled) {
if (DepthColorStorage.isDepthColorLocked()) {
DepthColorStorage.deferColorMask(red, green, blue, alpha);
return;
}
}
// Cache thread check - only update state on main thread, but always make GL call if needed
final boolean caching = isCachingEnabled();
final boolean bypass = BYPASS_CACHE || !caching;
if (bypass || red != colorMask.red || green != colorMask.green || blue != colorMask.blue || alpha != colorMask.alpha) {
if (caching) colorMask.setAll(red, green, blue, alpha);
GL11.glColorMask(red, green, blue, alpha);
}
}
// Clear Color
public static void glClearColor(float red, float green, float blue, float alpha) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordClearColor(red, green, blue, alpha);
if (mode == RecordMode.COMPILE) {
return;
}
}
final boolean caching = isCachingEnabled();
if (BYPASS_CACHE || !caching || red != clearColor.getRed() || green != clearColor.getGreen() || blue != clearColor.getBlue() || alpha != clearColor.getAlpha()) {
if (caching) {
clearColor.setRed(red);
clearColor.setGreen(green);
clearColor.setBlue(blue);
clearColor.setAlpha(alpha);
}
GL11.glClearColor(red, green, blue, alpha);
}
}
public static void glClearDepth(double depth) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordClearDepth(depth);
if (mode == RecordMode.COMPILE) {
return;
}
}
GL11.glClearDepth(depth);
}
// ALPHA
public static void enableAlphaTest() {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordEnable(GL11.GL_ALPHA_TEST);
if (mode == RecordMode.COMPILE) {
return;
}
}
if (Iris.enabled) {
if (AlphaTestStorage.isAlphaTestLocked()) {
AlphaTestStorage.deferAlphaTestToggle(true);
return;
}
}
alphaTest.enable();
}
public static void disableAlphaTest() {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordDisable(GL11.GL_ALPHA_TEST);
if (mode == RecordMode.COMPILE) {
return;
}
}
if (Iris.enabled) {
if (AlphaTestStorage.isAlphaTestLocked()) {
AlphaTestStorage.deferAlphaTestToggle(false);
return;
}
}
alphaTest.disable();
}
public static void glAlphaFunc(int function, float reference) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordAlphaFunc(function, reference);
if (mode == RecordMode.COMPILE) {
return;
}
}
if (Iris.enabled) {
if (AlphaTestStorage.isAlphaTestLocked()) {
AlphaTestStorage.deferAlphaFunc(function, reference);
return;
}
}
if (isCachingEnabled()) {
alphaState.setFunction(function);
alphaState.setReference(reference);
}
GL11.glAlphaFunc(function, reference);
}
// Textures
public static void glActiveTexture(int texture) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordActiveTexture(texture);
if (mode == RecordMode.COMPILE) {
return;
}
}
final int newTexture = texture - GL13.GL_TEXTURE0;
final boolean caching = isCachingEnabled();
if (BYPASS_CACHE || !caching || getActiveTextureUnit() != newTexture) {
if (caching) activeTextureUnit.setValue(newTexture);
GL13.glActiveTexture(texture);
}
}
public static void glActiveTextureARB(int texture) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordActiveTexture(texture);
if (mode == RecordMode.COMPILE) {
return;
}
}
final int newTexture = texture - GL13.GL_TEXTURE0;
final boolean caching = isCachingEnabled();
if (BYPASS_CACHE || !caching || getActiveTextureUnit() != newTexture) {
if (caching) activeTextureUnit.setValue(newTexture);
ARBMultitexture.glActiveTextureARB(texture);
}
}
private static int getBoundTexture() {
return getBoundTexture(activeTextureUnit.getValue());
}
private static int getBoundTexture(int unit) {
return textures.getTextureUnitBindings(unit).getBinding();
}
public static void glBindTexture(int target, int texture) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordBindTexture(target, texture);
if (mode == RecordMode.COMPILE) {
return;
}
}
if (target != GL11.GL_TEXTURE_2D) {
// We're only supporting 2D textures for now
GL11.glBindTexture(target, texture);
LOGGER.info("SKIPPING glBindTexture for target {}", target);
return;
}
if (!isCachingEnabled()) {
GL11.glBindTexture(target, texture);
return;
}
final int activeUnit = GLStateManager.activeTextureUnit.getValue();
final TextureBinding textureUnit = textures.getTextureUnitBindings(activeUnit);
final int cachedBinding = textureUnit.getBinding();
if (cachedBinding != texture) {
GL11.glBindTexture(target, texture);
textureUnit.setBinding(texture);
TextureTracker.INSTANCE.onBindTexture(texture);
}
}
public static void glTexImage2D(int target, int level, int internalformat, int width, int height, int border, int format, int type, IntBuffer pixels) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordComplexCommand(TexImage2DCmd.fromIntBuffer(target, level, internalformat, width, height, border, format, type, pixels));
if (mode == RecordMode.COMPILE) {
return;
}
}
TextureInfoCache.INSTANCE.onTexImage2D(target, level, internalformat, width, height, border, format, type, pixels);
if (shouldUseDSA(target)) {
// Use DSA to upload directly to the texture
RenderSystem.textureImage2D(getBoundTextureForServerState(), target, level, internalformat, width, height, border, format, type, pixels);
} else {
// Non-main thread or proxy texture - use direct GL call
GL11.glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels);
}
}
public static void glTexImage2D(int target, int level, int internalformat, int width, int height, int border, int format, int type, FloatBuffer pixels) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordComplexCommand(TexImage2DCmd.fromFloatBuffer(target, level, internalformat, width, height, border, format, type, pixels));
if (mode == RecordMode.COMPILE) {
return;
}
}
TextureInfoCache.INSTANCE.onTexImage2D(target, level, internalformat, width, height, border, format, type, pixels);
// FloatBuffer not in DSA interface - use direct GL call
GL11.glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels);
}
public static void glTexImage2D(int target, int level, int internalformat, int width, int height, int border, int format, int type, DoubleBuffer pixels) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordComplexCommand(TexImage2DCmd.fromDoubleBuffer(target, level, internalformat, width, height, border, format, type, pixels));
if (mode == RecordMode.COMPILE) {
return;
}
}
TextureInfoCache.INSTANCE.onTexImage2D(target, level, internalformat, width, height, border, format, type, pixels);
// DoubleBuffer not in DSA interface - use direct GL call
GL11.glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels);
}
public static void glTexImage2D(int target, int level, int internalformat, int width, int height, int border, int format, int type, ByteBuffer pixels) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordComplexCommand(TexImage2DCmd.fromByteBuffer(target, level, internalformat, width, height, border, format, type, pixels));
if (mode == RecordMode.COMPILE) {
return;
}
}
TextureInfoCache.INSTANCE.onTexImage2D(target, level, internalformat, width, height, border, format, type, pixels != null ? pixels.asIntBuffer() : null);
if (shouldUseDSA(target)) {
// Use DSA to upload directly to the texture - keeps GL binding state unchanged
RenderSystem.textureImage2D(getBoundTextureForServerState(), target, level, internalformat, width, height, border, format, type, pixels);
} else {
// Non-main thread or proxy texture - use direct GL call
GL11.glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels);
}
}
public static void glTexImage2D(int target, int level, int internalformat, int width, int height, int border, int format, int type, long pixels_buffer_offset) {
if (DisplayListManager.isRecording()) {
throw new UnsupportedOperationException("glTexImage2D with buffer offset in display lists not yet supported");
}
TextureInfoCache.INSTANCE.onTexImage2D(target, level, internalformat, width, height, border, format, type, pixels_buffer_offset);
GL11.glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels_buffer_offset);
}
public static void glTexCoord1f(float s) {
if (DisplayListManager.isRecording()) {
final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder();
if (recorder != null) {
recorder.setTexCoord(s, 0.0f);
}
return;
}
GL11.glTexCoord1f(s);
}
public static void glTexCoord1d(double s) {
if (DisplayListManager.isRecording()) {
final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder();
if (recorder != null) {
recorder.setTexCoord((float) s, 0.0f);
}
return;
}
GL11.glTexCoord1d(s);
}
public static void glTexCoord2f(float s, float t) {
if (DisplayListManager.isRecording()) {
final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder();
if (recorder != null) {
recorder.setTexCoord(s, t);
}
return;
}
GL11.glTexCoord2f(s, t);
}
public static void glTexCoord2d(double s, double t) {
if (DisplayListManager.isRecording()) {
final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder();
if (recorder != null) {
recorder.setTexCoord((float) s, (float) t);
}
return;
}
GL11.glTexCoord2d(s, t);
}
public static void glTexCoord3f(float s, float t, float r) {
if (DisplayListManager.isRecording()) {
final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder();
if (recorder != null) {
recorder.setTexCoord(s, t); // Only track s,t for 2D textures
}
return;
}
GL11.glTexCoord3f(s, t, r);
}
public static void glTexCoord3d(double s, double t, double r) {
if (DisplayListManager.isRecording()) {
final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder();
if (recorder != null) {
recorder.setTexCoord((float) s, (float) t);
}
return;
}
GL11.glTexCoord3d(s, t, r);
}
public static void glTexCoord4f(float s, float t, float r, float q) {
if (DisplayListManager.isRecording()) {
final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder();
if (recorder != null) {
recorder.setTexCoord(s, t);
}
return;
}
GL11.glTexCoord4f(s, t, r, q);
}
public static void glTexCoord4d(double s, double t, double r, double q) {
if (DisplayListManager.isRecording()) {
final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder();
if (recorder != null) {
recorder.setTexCoord((float) s, (float) t);
}
return;
}
GL11.glTexCoord4d(s, t, r, q);
}
public static void glDeleteTextures(int id) {
onDeleteTexture(id);
GL11.glDeleteTextures(id);
}
public static void glDeleteTextures(IntBuffer ids) {
for(int i = 0; i < ids.remaining(); i++) {
onDeleteTexture(ids.get(i));
}
GL11.glDeleteTextures(ids);
}
public static void enableTexture() {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordEnable(GL11.GL_TEXTURE_2D);
if (mode == RecordMode.COMPILE) {
return;
}
}
final int textureUnit = getActiveTextureUnit();
if (Iris.enabled) {
// Iris
boolean updatePipeline = false;
if (textureUnit == IrisSamplers.ALBEDO_TEXTURE_UNIT) {
StateTracker.INSTANCE.albedoSampler = true;
updatePipeline = true;
} else if (textureUnit == IrisSamplers.LIGHTMAP_TEXTURE_UNIT) {
StateTracker.INSTANCE.lightmapSampler = true;
updatePipeline = true;
}
if (updatePipeline) {
Iris.getPipelineManager().getPipeline().ifPresent(p -> p.setInputs(StateTracker.INSTANCE.getInputs()));
}
}
textures.getTextureUnitStates(textureUnit).enable();
}
public static void disableTexture() {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordDisable(GL11.GL_TEXTURE_2D);
if (mode == RecordMode.COMPILE) {
return;
}
}
final int textureUnit = getActiveTextureUnit();
if (Iris.enabled) {
// Iris
boolean updatePipeline = false;
if (textureUnit == IrisSamplers.ALBEDO_TEXTURE_UNIT) {
StateTracker.INSTANCE.albedoSampler = false;
updatePipeline = true;
} else if (textureUnit == IrisSamplers.LIGHTMAP_TEXTURE_UNIT) {
StateTracker.INSTANCE.lightmapSampler = false;
updatePipeline = true;
}
if (updatePipeline) {
Iris.getPipelineManager().getPipeline().ifPresent(p -> p.setInputs(StateTracker.INSTANCE.getInputs()));
}
}
textures.getTextureUnitStates(textureUnit).disable();
}
public static void glRasterPos2f(float x, float y) {
if (DisplayListManager.isRecording()) {
throw new UnsupportedOperationException("glRasterPos in display lists not yet implemented");
}
GL11.glRasterPos2f(x, y);
}
public static void glRasterPos2d(double x, double y) {
if (DisplayListManager.isRecording()) {
throw new UnsupportedOperationException("glRasterPos in display lists not yet implemented");
}
GL11.glRasterPos2d(x, y);
}
public static void glRasterPos2i(int x, int y) {
if (DisplayListManager.isRecording()) {
throw new UnsupportedOperationException("glRasterPos in display lists not yet implemented");
}
GL11.glRasterPos2i(x, y);
}
public static void glRasterPos3f(float x, float y, float z) {
if (DisplayListManager.isRecording()) {
throw new UnsupportedOperationException("glRasterPos in display lists not yet implemented");
}
GL11.glRasterPos3f(x, y, z);
}
public static void glRasterPos3d(double x, double y, double z) {
if (DisplayListManager.isRecording()) {
throw new UnsupportedOperationException("glRasterPos in display lists not yet implemented");
}
GL11.glRasterPos3d(x, y, z);
}
public static void glRasterPos3i(int x, int y, int z) {
if (DisplayListManager.isRecording()) {
throw new UnsupportedOperationException("glRasterPos in display lists not yet implemented");
}
GL11.glRasterPos3i(x, y, z);
}
public static void glRasterPos4f(float x, float y, float z, float w) {
checkCompiling("glRasterPos");
GL11.glRasterPos4f(x, y, z, w);
}
public static void glRasterPos4d(double x, double y, double z, double w) {
checkCompiling("glRasterPos");
GL11.glRasterPos4d(x, y, z, w);
}
public static void glRasterPos4i(int x, int y, int z, int w) {
checkCompiling("glRasterPos");
GL11.glRasterPos4i(x, y, z, w);
}
public static void setFilter(boolean bilinear, boolean mipmap) {
final int i, j;
if (bilinear) {
i = mipmap ? GL11.GL_LINEAR_MIPMAP_LINEAR : GL11.GL_LINEAR;
j = GL11.GL_LINEAR;
} else {
i = mipmap ? GL11.GL_LINEAR_MIPMAP_LINEAR : GL11.GL_NEAREST;
j = GL11.GL_NEAREST;
}
glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, i);
glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, j);
}
public static void trySyncProgram() {
if (Iris.enabled) {
Iris.getPipelineManager().getPipeline().ifPresent(WorldRenderingPipeline::syncProgram);
}
}
public static void glBegin(int mode) {
if (DisplayListManager.isRecording()) {
// Record to immediate mode recorder
final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder();
if (recorder != null) {
recorder.begin(mode);
}
return; // Don't call actual GL during recording
}
trySyncProgram();
GL11.glBegin(mode);
}
public static void glEnd() {
if (DisplayListManager.isRecording()) {
// Record to immediate mode recorder and flush geometry immediately
final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder();
if (recorder != null) {
// end() returns quads immediately (like tessellator callback)
final ImmediateModeRecorder.Result result = recorder.end();
if (result != null) {
// Add draw at current command position for correct interleaving
DisplayListManager.addImmediateModeDraw(result);
}
}
return; // Don't call actual GL during recording
}
GL11.glEnd();
}
// Vertex methods for display list recording
private static boolean loggedVertex = false;
public static void glVertex2f(float x, float y) {
final boolean recording = DisplayListManager.isRecording();
if (recording) {
final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder();
if (recorder != null) {
recorder.vertex(x, y, 0.0f);
}
return;
}
GL11.glVertex2f(x, y);
}
public static void glVertex2d(double x, double y) {
if (DisplayListManager.isRecording()) {
final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder();
if (recorder != null) {
recorder.vertex((float) x, (float) y, 0.0f);
}
return;
}
GL11.glVertex2d(x, y);
}
public static void glVertex3f(float x, float y, float z) {
if (DisplayListManager.isRecording()) {
final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder();
if (recorder != null) {
recorder.vertex(x, y, z);
}
return;
}
GL11.glVertex3f(x, y, z);
}
public static void glVertex3d(double x, double y, double z) {
if (DisplayListManager.isRecording()) {
final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder();
if (recorder != null) {
recorder.vertex((float) x, (float) y, (float) z);
}
return;
}
GL11.glVertex3d(x, y, z);
}
public static void glDrawElements(int mode, ByteBuffer indices) {
if (DisplayListManager.isRecording()) {
throw new UnsupportedOperationException("glDrawElements in display lists not yet implemented - if you see this, please report!");
}
trySyncProgram();
GL11.glDrawElements(mode, indices);
}
public static void glDrawElements(int mode, IntBuffer indices) {
if (DisplayListManager.isRecording()) {
throw new UnsupportedOperationException("glDrawElements in display lists not yet implemented - if you see this, please report!");
}
trySyncProgram();
GL11.glDrawElements(mode, indices);
}
public static void glDrawElements(int mode, ShortBuffer indices) {
if (DisplayListManager.isRecording()) {
throw new UnsupportedOperationException("glDrawElements in display lists not yet implemented - if you see this, please report!");
}
trySyncProgram();
GL11.glDrawElements(mode, indices);
}
public static void glDrawElements(int mode, int indices_count, int type, long indices_buffer_offset) {
if (DisplayListManager.isRecording()) {
throw new UnsupportedOperationException("glDrawElements in display lists not yet implemented - if you see this, please report!");
}
trySyncProgram();
GL11.glDrawElements(mode, indices_count, type, indices_buffer_offset);
}
public static void glDrawElements(int mode, int count, int type, ByteBuffer indices) {
if (DisplayListManager.isRecording()) {
throw new UnsupportedOperationException("glDrawElements in display lists not yet implemented - if you see this, please report!");
}
trySyncProgram();
GL11.glDrawElements(mode, count, type, indices);
}
public static void glDrawBuffer(int mode) {
final RecordMode recordMode = DisplayListManager.getRecordMode();
if (recordMode != RecordMode.NONE) {
DisplayListManager.recordDrawBuffer(mode);
if (recordMode == RecordMode.COMPILE) {
return;
}
}
trySyncProgram();
GL11.glDrawBuffer(mode);
}
public static void glDrawArrays(int mode, int first, int count) {
if (DisplayListManager.isRecording()) {
final ImmediateModeRecorder recorder = DisplayListManager.getImmediateModeRecorder();
if (recorder != null) {
final ImmediateModeRecorder.Result result = recorder.processDrawArrays(mode, first, count);
if (result != null) {
DisplayListManager.addImmediateModeDraw(result);
}
}
return;
}
trySyncProgram();
GL11.glDrawArrays(mode, first, count);
}
// Client array state interception methods (for glDrawArrays conversion)
// State is tracked globally in clientArrayState, which ImmediateModeRecorder reads from directly.
public static void glVertexPointer(int size, int stride, FloatBuffer pointer) {
clientArrayState.setVertexPointer(size, GL11.GL_FLOAT, stride, pointer);
GL11.glVertexPointer(size, stride, pointer);
}
public static void glVertexPointer(int size, int type, int stride, ByteBuffer pointer) {
clientArrayState.setVertexPointer(size, type, stride, pointer);
GL11.glVertexPointer(size, type, stride, pointer);
}
public static void glVertexPointer(int size, int type, int stride, long pointer_buffer_offset) {
// VBO offset - can't track buffer reference, clear it
clientArrayState.setVertexPointer(size, type, stride, null);
GL11.glVertexPointer(size, type, stride, pointer_buffer_offset);
}
public static void glColorPointer(int size, int stride, FloatBuffer pointer) {
clientArrayState.setColorPointer(size, GL11.GL_FLOAT, stride, pointer);
GL11.glColorPointer(size, stride, pointer);
}
public static void glColorPointer(int size, int type, int stride, ByteBuffer pointer) {
clientArrayState.setColorPointer(size, type, stride, pointer);
GL11.glColorPointer(size, type, stride, pointer);
}
public static void glColorPointer(int size, boolean unsigned, int stride, ByteBuffer pointer) {
final int type = unsigned ? GL11.GL_UNSIGNED_BYTE : GL11.GL_BYTE;
clientArrayState.setColorPointer(size, type, stride, pointer);
GL11.glColorPointer(size, unsigned, stride, pointer);
}
public static void glColorPointer(int size, int type, int stride, long pointer_buffer_offset) {
// VBO offset - can't track buffer reference, clear it
clientArrayState.setColorPointer(size, type, stride, null);
GL11.glColorPointer(size, type, stride, pointer_buffer_offset);
}
public static void glEnableClientState(int cap) {
if (cap == GL11.GL_VERTEX_ARRAY) clientArrayState.setVertexArrayEnabled(true);
else if (cap == GL11.GL_COLOR_ARRAY) clientArrayState.setColorArrayEnabled(true);
GL11.glEnableClientState(cap);
}
public static void glDisableClientState(int cap) {
if (cap == GL11.GL_VERTEX_ARRAY) clientArrayState.setVertexArrayEnabled(false);
else if (cap == GL11.GL_COLOR_ARRAY) clientArrayState.setColorArrayEnabled(false);
GL11.glDisableClientState(cap);
}
public static void glLogicOp(int opcode) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordLogicOp(opcode);
if (mode == RecordMode.COMPILE) {
return;
}
}
GL11.glLogicOp(opcode);
}
public static void defaultBlendFunc() {
tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO);
}
public static void enableCull() {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordEnable(GL11.GL_CULL_FACE);
if (mode == RecordMode.COMPILE) {
return;
}
}
cullState.enable();
}
public static void disableCull() {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordDisable(GL11.GL_CULL_FACE);
if (mode == RecordMode.COMPILE) {
return;
}
}
cullState.disable();
}
public static void enableDepthTest() {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordEnable(GL11.GL_DEPTH_TEST);
if (mode == RecordMode.COMPILE) {
return;
}
}
depthTest.enable();
}
public static void disableDepthTest() {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordDisable(GL11.GL_DEPTH_TEST);
if (mode == RecordMode.COMPILE) {
return;
}
}
depthTest.disable();
}
public static void enableLighting() {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordEnable(GL11.GL_LIGHTING);
if (mode == RecordMode.COMPILE) {
return;
}
}
lightingState.enable();
}
public static void enableLight(int light) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordEnable(GL11.GL_LIGHT0 + light);
if (mode == RecordMode.COMPILE) {
return;
}
}
lightStates[light].enable();
}
public static void enableColorMaterial() {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordEnable(GL11.GL_COLOR_MATERIAL);
if (mode == RecordMode.COMPILE) {
return;
}
}
colorMaterial.enable();
float r = getColor().getRed();
float g = getColor().getGreen();
float b = getColor().getBlue();
float a = getColor().getAlpha();
if (colorMaterialFace.getValue() == GL11.GL_FRONT || colorMaterialFace.getValue() == GL11.GL_FRONT_AND_BACK) {
switch (colorMaterialParameter.getValue()) {
case GL11.GL_AMBIENT_AND_DIFFUSE -> {
frontMaterial.ambient.set(r, g, b, a);
frontMaterial.diffuse.set(r, g, b, a);
}
case GL11.GL_AMBIENT -> frontMaterial.ambient.set(r, g, b, a);
case GL11.GL_DIFFUSE -> frontMaterial.diffuse.set(r, g, b, a);
case GL11.GL_SPECULAR -> frontMaterial.specular.set(r, g, b, a);
case GL11.GL_EMISSION -> frontMaterial.emission.set(r, g, b, a);
}
}
if (colorMaterialFace.getValue() == GL11.GL_BACK || colorMaterialFace.getValue() == GL11.GL_FRONT_AND_BACK) {
switch (colorMaterialParameter.getValue()) {
case GL11.GL_AMBIENT_AND_DIFFUSE -> {
backMaterial.ambient.set(r, g, b, a);
backMaterial.diffuse.set(r, g, b, a);
}
case GL11.GL_AMBIENT -> backMaterial.ambient.set(r, g, b, a);
case GL11.GL_DIFFUSE -> backMaterial.diffuse.set(r, g, b, a);
case GL11.GL_SPECULAR -> backMaterial.specular.set(r, g, b, a);
case GL11.GL_EMISSION -> backMaterial.emission.set(r, g, b, a);
}
}
}
public static void disableColorMaterial() {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordDisable(GL11.GL_COLOR_MATERIAL);
if (mode == RecordMode.COMPILE) {
return;
}
}
colorMaterial.disable();
}
public static void disableLighting() {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordDisable(GL11.GL_LIGHTING);
if (mode == RecordMode.COMPILE) {
return;
}
}
lightingState.disable();
}
public static void disableLight(int light) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordDisable(GL11.GL_LIGHT0 + light);
if (mode == RecordMode.COMPILE) {
return;
}
}
lightStates[light].disable();
}
public static void enableRescaleNormal() {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordEnable(GL12.GL_RESCALE_NORMAL);
if (mode == RecordMode.COMPILE) {
return;
}
}
rescaleNormalState.enable();
}
public static void disableRescaleNormal() {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordDisable(GL12.GL_RESCALE_NORMAL);
if (mode == RecordMode.COMPILE) {
return;
}
}
rescaleNormalState.disable();
}
public static void enableFog() {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordEnable(GL11.GL_FOG);
if (mode == RecordMode.COMPILE) {
return;
}
}
fogMode.enable();
if (fogToggleListener != null) {
fogToggleListener.run();
}
}
public static void disableFog() {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordDisable(GL11.GL_FOG);
if (mode == RecordMode.COMPILE) {
return;
}
}
fogMode.disable();
if (fogToggleListener != null) {
fogToggleListener.run();
}
}
public static void glFog(int pname, FloatBuffer param) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordFog(pname, param);
if (mode == RecordMode.COMPILE) {
return;
}
}
// TODO: Iris Notifier
if (HAS_MULTIPLE_SET.contains(pname)) {
GL11.glFog(pname, param);
if (pname == GL11.GL_FOG_COLOR && isCachingEnabled()) {
final float red = param.get(0);
final float green = param.get(1);
final float blue = param.get(2);
fogState.getFogColor().set(red, green, blue);
fogState.setFogAlpha(param.get(3));
fogState.getFogColorBuffer().clear();
fogState.getFogColorBuffer().put((FloatBuffer) param.position(0)).flip();
}
} else {
GLStateManager.glFogf(pname, param.get(0));
}
}
public static Vector3d getFogColor() {
return fogState.getFogColor();
}
private static final FloatBuffer fogColorTempBuffer = BufferUtils.createFloatBuffer(4);
public static void fogColor(float red, float green, float blue, float alpha) {
final boolean caching = isCachingEnabled();
if (BYPASS_CACHE || !caching || red != fogState.getFogColor().x || green != fogState.getFogColor().y || blue != fogState.getFogColor().z || alpha != fogState.getFogAlpha()) {
if (caching) {
fogState.getFogColor().set(red, green, blue);
fogState.setFogAlpha(alpha);
fogState.getFogColorBuffer().clear();
fogState.getFogColorBuffer().put(red).put(green).put(blue).put(alpha).flip();
GL11.glFog(GL11.GL_FOG_COLOR, fogState.getFogColorBuffer());
} else {
// Use temp buffer for non-main thread to avoid corrupting shared state
fogColorTempBuffer.clear();
fogColorTempBuffer.put(red).put(green).put(blue).put(alpha).flip();
GL11.glFog(GL11.GL_FOG_COLOR, fogColorTempBuffer);
}
}
}
public static void glFogf(int pname, float param) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordFogf(pname, param);
if (mode == RecordMode.COMPILE) {
return;
}
}
GL11.glFogf(pname, param);
// Note: Does not handle GL_FOG_INDEX
// Only update cached state when caching is enabled
if (isCachingEnabled()) {
switch (pname) {
case GL11.GL_FOG_DENSITY -> {
fogState.setDensity(param);
if (fogDensityListener != null) {
fogDensityListener.run();
}
}
case GL11.GL_FOG_START -> {
fogState.setStart(param);
if (fogStartListener != null) {
fogStartListener.run();
}
}
case GL11.GL_FOG_END -> {
fogState.setEnd(param);
if (fogEndListener != null) {
fogEndListener.run();
}
}
}
}
}
public static void glFogi(int pname, int param) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordFogi(pname, param);
if (mode == RecordMode.COMPILE) {
return;
}
}
GL11.glFogi(pname, param);
// Only update cached state when caching is enabled
if (isCachingEnabled() && pname == GL11.GL_FOG_MODE) {
fogState.setFogMode(param);
if (fogModeListener != null) {
fogModeListener.run();
}
}
}
public static void setFogBlack() {
glFogf(GL11.GL_FOG_COLOR, 0.0F);
}
public static void glShadeModel(int mode) {
final RecordMode recordMode = DisplayListManager.getRecordMode();
if (recordMode != RecordMode.NONE) {
DisplayListManager.recordShadeModel(mode);
if (recordMode == RecordMode.COMPILE) {
return;
}
}
final boolean caching = isCachingEnabled();
final int oldValue = shadeModelState.getValue();
final boolean needsUpdate = BYPASS_CACHE || !caching || oldValue != mode;
if (needsUpdate) {
if (caching) {
shadeModelState.setValue(mode);
}
GL11.glShadeModel(mode);
}
}
// Iris Functions
private static void onDeleteTexture(int id) {
TextureTracker.INSTANCE.onDeleteTexture(id);
TextureInfoCache.INSTANCE.onDeleteTexture(id);
if (Iris.enabled) {
PBRTextureManager.INSTANCE.onDeleteTexture(id);
}
// Only update cached texture bindings on main thread
if (isCachingEnabled()) {
for (int i = 0; i < GLStateManager.MAX_TEXTURE_UNITS; i++) {
if (textures.getTextureUnitBindings(i).getBinding() == id) {
textures.getTextureUnitBindings(i).setBinding(0);
}
}
}
}
public static void makeCurrent(Drawable drawable) throws LWJGLException {
drawable.makeCurrent();
CurrentThread = Thread.currentThread();
// During splash, track which thread holds DrawableGL for caching
if (!splashComplete && sharedDrawable != null) {
if (drawable == sharedDrawable) {
// Switching to SharedDrawable - disable caching for this thread
if (drawableGLHolder == CurrentThread) {
drawableGLHolder = null;
}
} else {
// Switching to DrawableGL - enable caching for this thread
drawableGLHolder = CurrentThread;
}
}
}
/**
* Set whether the current thread holds DrawableGL (the main display context).
* Called by mixins at context switch points during splash.
*/
public static void setCachingEnabled(boolean enabled) {
final Thread current = Thread.currentThread();
if (enabled) {
drawableGLHolder = current;
} else if (drawableGLHolder == current) {
drawableGLHolder = null;
}
}
/**
* Mark splash as complete - enables fast path that always caches.
* Called when finish() permanently switches to DrawableGL for the main game loop.
*/
public static void markSplashComplete() {
splashComplete = true;
drawableGLHolder = null;
sharedDrawable = null;
}
public static void glNewList(int list, int mode) {
DisplayListManager.glNewList(list, mode);
}
public static void glEndList() {
DisplayListManager.glEndList();
}
/**
* Check if we're currently recording a display list.
*/
public static boolean isRecordingDisplayList() {
return DisplayListManager.isRecording();
}
public static int getRecordingDisplayListId() {
return DisplayListManager.getRecordingListId();
}
/**
* Delete display lists and free their VBO resources.
*/
public static void glDeleteLists(int list, int range) {
DisplayListManager.glDeleteLists(list, range);
}
/**
* Get a compiled display list from the cache.
* Used for executing nested display lists.
* @param list The display list ID
* @return The CompiledDisplayList, or null if not found
*/
public static CompiledDisplayList getDisplayList(int list) {
return DisplayListManager.getDisplayList(list);
}
public static void glCallList(int list) {
GLDebug.pushGroup("glCallList " + list);
DisplayListManager.glCallList(list);
GLDebug.popGroup();
}
public static void pushState(int mask) {
if (attribDepth >= MAX_ATTRIB_STACK_DEPTH) {
throw new IllegalStateException("Attrib stack overflow: max depth " + MAX_ATTRIB_STACK_DEPTH + " reached");
}
attribs.push(mask);
// Clear modified list for this depth level
modifiedAtDepth[attribDepth].clear();
attribDepth++;
// Only iterate non-boolean stacks - BooleanStateStack uses global depth tracking
// so pushDepth() is a no-op for them
final IStateStack<?>[] nonBooleanStacks = Feature.maskToNonBooleanStacks(mask);
for (IStateStack<?> stack : nonBooleanStacks) {
stack.pushDepth();
}
}
public static void popState() {
final int mask = attribs.popInt();
attribDepth--;
// First: restore BooleanStateStack states that were actually modified (fast path)
// These use lazy copy-on-write with global depth tracking
final List<IStateStack<?>> modified = modifiedAtDepth[attribDepth];
for (int i = 0; i < modified.size(); i++) {
modified.get(i).popDepth();
}
modified.clear();
// Second: restore non-boolean state stacks the traditional way
final IStateStack<?>[] nonBooleanStacks = Feature.maskToNonBooleanStacks(mask);
for (IStateStack<?> stack : nonBooleanStacks) {
stack.popDepth();
}
}
public static void glClear(int mask) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordClear(mask);
if (mode == RecordMode.COMPILE) {
return;
}
}
GL11.glClear(mask);
}
public static void glPushAttrib(int mask) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordPushAttrib(mask);
if (mode == RecordMode.COMPILE) {
return;
}
}
GLDebug.pushGroup("pushState");
GL11.glPushAttrib(mask);
if (isCachingEnabled()) {
pushState(mask);
}
}
public static void glPopAttrib() {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordPopAttrib();
if (mode == RecordMode.COMPILE) {
return;
}
}
GL11.glPopAttrib();
GLDebug.popGroup();
if (isCachingEnabled()) {
poppingAttributes = true;
GLDebug.pushGroup("popState");
popState();
GLDebug.popGroup();
poppingAttributes = false;
}
}
// Matrix Operations
public static void glMatrixMode(int mode) {
final RecordMode recordMode = DisplayListManager.getRecordMode();
if (recordMode != RecordMode.NONE) {
DisplayListManager.recordMatrixMode(mode);
DisplayListManager.resetRelativeTransform(); // Mode switch is a barrier - reset delta tracking
if (recordMode == RecordMode.COMPILE) {
return;
}
}
GL11.glMatrixMode(mode);
matrixMode.setMode(mode);
}
public static void glLoadMatrix(FloatBuffer m) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
final Matrix4f matrix = new Matrix4f().set(m);
m.rewind();
DisplayListManager.recordLoadMatrix(matrix);
// Reset relative transform - subsequent transforms are relative to loaded matrix
DisplayListManager.resetRelativeTransform();
if (mode == RecordMode.COMPILE) {
return;
}
}
if (isCachingEnabled()) getMatrixStack().set(m);
GL11.glLoadMatrix(m);
}
public static void glLoadMatrix(DoubleBuffer m) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
// Convert double buffer to float buffer for recording
conversionMatrix4d.set(m);
m.rewind();
final Matrix4f floatMatrix = new Matrix4f();
floatMatrix.set(conversionMatrix4d);
DisplayListManager.recordLoadMatrix(floatMatrix);
// Reset relative transform - subsequent transforms are relative to loaded matrix
DisplayListManager.resetRelativeTransform();
if (mode == RecordMode.COMPILE) {
return;
}
}
if (isCachingEnabled()) {
conversionMatrix4d.set(m);
getMatrixStack().set(conversionMatrix4d);
}
GL11.glLoadMatrix(m);
}
public static Matrix4fStack getMatrixStack() {
switch (matrixMode.getMode()) {
case GL11.GL_MODELVIEW -> {
return modelViewMatrix;
}
case GL11.GL_PROJECTION -> {
return projectionMatrix;
}
case GL11.GL_TEXTURE -> {
return textures.getTextureUnitMatrix(getActiveTextureUnit());
}
default -> throw new IllegalStateException("Unknown matrix mode: " + matrixMode.getMode());
}
}
public static void glLoadIdentity() {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordLoadIdentity();
// Reset relative transform - accumulated transforms are discarded (overwritten by load)
DisplayListManager.resetRelativeTransform();
if (mode == RecordMode.COMPILE) {
return;
}
}
GL11.glLoadIdentity();
if (isCachingEnabled()) getMatrixStack().identity();
}
public static void glTranslatef(float x, float y, float z) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.updateRelativeTransform(x, y, z, DisplayListManager.TransformOp.TRANSLATE, null);
return;
}
GL11.glTranslatef(x, y, z);
if (isCachingEnabled()) getMatrixStack().translate(x, y, z);
}
public static void glTranslated(double x, double y, double z) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.updateRelativeTransform((float) x, (float) y, (float) z, DisplayListManager.TransformOp.TRANSLATE, null);
return;
}
GL11.glTranslated(x, y, z);
if (isCachingEnabled()) getMatrixStack().translate((float) x, (float) y, (float) z);
}
public static void glScalef(float x, float y, float z) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.updateRelativeTransform(x, y, z, DisplayListManager.TransformOp.SCALE, null);
return;
}
GL11.glScalef(x, y, z);
if (isCachingEnabled()) getMatrixStack().scale(x, y, z);
}
public static void glScaled(double x, double y, double z) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.updateRelativeTransform((float) x, (float) y, (float) z, DisplayListManager.TransformOp.SCALE, null);
return;
}
GL11.glScaled(x, y, z);
if (isCachingEnabled()) getMatrixStack().scale((float) x, (float) y, (float) z);
}
private static final Matrix4f multMatrix = new Matrix4f();
public static void glMultMatrix(FloatBuffer floatBuffer) {
multMatrix.set(floatBuffer);
final int currentMode = matrixMode.getMode();
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.updateRelativeTransform(multMatrix);
return;
}
GL11.glMultMatrix(floatBuffer);
if (isCachingEnabled()) getMatrixStack().mul(multMatrix);
}
public static final Matrix4d conversionMatrix4d = new Matrix4d();
public static final Matrix4f conversionMatrix4f = new Matrix4f();
public static void glMultMatrix(DoubleBuffer matrix) {
conversionMatrix4d.set(matrix);
conversionMatrix4f.set(conversionMatrix4d);
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.updateRelativeTransform(conversionMatrix4f);
return;
}
GL11.glMultMatrix(matrix);
if (isCachingEnabled()) getMatrixStack().mul(conversionMatrix4f);
}
private static final Vector3f rotation = new Vector3f();
public static void glRotatef(float angle, float x, float y, float z) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
rotation.set(x, y, z).normalize();
DisplayListManager.updateRelativeTransform(angle, 0, 0, DisplayListManager.TransformOp.ROTATE, rotation);
return;
}
GL11.glRotatef(angle, x, y, z);
if (isCachingEnabled()) {
rotation.set(x, y, z).normalize();
getMatrixStack().rotate((float)Math.toRadians(angle), rotation);
}
}
public static void glRotated(double angle, double x, double y, double z) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
rotation.set((float) x, (float) y, (float) z).normalize();
DisplayListManager.updateRelativeTransform((float) angle, 0, 0, DisplayListManager.TransformOp.ROTATE, rotation);
return;
}
GL11.glRotated(angle, x, y, z);
if (isCachingEnabled()) {
rotation.set((float) x, (float) y, (float) z).normalize();
getMatrixStack().rotate((float)Math.toRadians(angle), rotation);
}
}
public static void glOrtho(double left, double right, double bottom, double top, double zNear, double zFar) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.updateRelativeTransformOrtho(left, right, bottom, top, zNear, zFar);
return; // Transform accumulated, will be emitted at barriers
}
GL11.glOrtho(left, right, bottom, top, zNear, zFar);
if (isCachingEnabled()) getMatrixStack().ortho((float)left, (float)right, (float)bottom, (float)top, (float)zNear, (float)zFar);
}
public static void glFrustum(double left, double right, double bottom, double top, double zNear, double zFar) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.updateRelativeTransformFrustum(left, right, bottom, top, zNear, zFar);
return; // Transform accumulated, will be emitted at barriers
}
GL11.glFrustum(left, right, bottom, top, zNear, zFar);
if (isCachingEnabled()) getMatrixStack().frustum((float)left, (float)right, (float)bottom, (float)top, (float)zNear, (float)zFar);
}
public static void glPushMatrix() {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordPushMatrix(); // Handles flush + relativeTransform stack
if (mode == RecordMode.COMPILE) {
return;
}
}
GL11.glPushMatrix();
// Only track stack on main thread (splash thread has separate GL context)
if (isCachingEnabled()) {
try {
getMatrixStack().pushMatrix();
} catch(IllegalStateException ignored) {
if(AngelicaMod.lwjglDebug)
AngelicaTweaker.LOGGER.warn("Matrix stack overflow ", new Throwable());
}
}
}
public static void glPopMatrix() {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordPopMatrix(); // Handles flush + relativeTransform stack + lastRecordedTransform sync
if (mode == RecordMode.COMPILE) {
return;
}
}
GL11.glPopMatrix();
// Only track stack on main thread (splash thread has separate GL context)
if (isCachingEnabled()) {
try {
getMatrixStack().popMatrix();
} catch(IllegalStateException ignored) {
if(AngelicaMod.lwjglDebug)
AngelicaTweaker.LOGGER.warn("Matrix stack underflow ", new Throwable());
}
}
}
private static final Matrix4f perspectiveMatrix = new Matrix4f();
private static final FloatBuffer perspectiveBuffer = BufferUtils.createFloatBuffer(16);
public static void gluPerspective(float fovy, float aspect, float zNear, float zFar) {
perspectiveMatrix.identity().perspective((float)Math.toRadians(fovy), aspect, zNear, zFar);
perspectiveMatrix.get(0, perspectiveBuffer);
GLStateManager.glMultMatrix(perspectiveBuffer);
}
public static void glViewport(int x, int y, int width, int height) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordViewport(x, y, width, height);
if (mode == RecordMode.COMPILE) {
return;
}
}
GL11.glViewport(x, y, width, height);
// Only update cached state when caching is enabled
if (isCachingEnabled()) {
viewportState.setViewPort(x, y, width, height);
}
}
public static int getActiveTextureUnit() {
return activeTextureUnit.getValue();
}
public static int getListMode() {
return DisplayListManager.getListMode();
}
public static boolean updateTexParameteriCache(int target, int texture, int pname, int param) {
if (target != GL11.GL_TEXTURE_2D) {
return true;
}
final TextureInfo info = TextureInfoCache.INSTANCE.getInfo(texture);
if (info == null) {
return true;
}
switch (pname) {
case GL11.GL_TEXTURE_MIN_FILTER -> {
if(info.getMinFilter() == param && !shouldBypassCache()) return false;
info.setMinFilter(param);
}
case GL11.GL_TEXTURE_MAG_FILTER -> {
if(info.getMagFilter() == param && !shouldBypassCache()) return false;
info.setMagFilter(param);
}
case GL11.GL_TEXTURE_WRAP_S -> {
if(info.getWrapS() == param && !shouldBypassCache()) return false;
info.setWrapS(param);
}
case GL11.GL_TEXTURE_WRAP_T -> {
if(info.getWrapT() == param && !shouldBypassCache()) return false;
info.setWrapT(param);
}
case GL12.GL_TEXTURE_MAX_LEVEL -> {
if(info.getMaxLevel() == param && !shouldBypassCache()) return false;
info.setMaxLevel(param);
}
case GL12.GL_TEXTURE_MIN_LOD -> {
if(info.getMinLod() == param && !shouldBypassCache()) return false;
info.setMinLod(param);
}
case GL12.GL_TEXTURE_MAX_LOD -> {
if(info.getMaxLod() == param && !shouldBypassCache()) return false;
info.setMaxLod(param);
}
}
return true;
}
public static void glTexParameter(int target, int pname, IntBuffer params) {
if (target != GL11.GL_TEXTURE_2D || params.remaining() != 1 ) {
GL11.glTexParameter(target, pname, params);
return;
}
if(!updateTexParameteriCache(target, getBoundTextureForServerState(), pname, params.get(0))) return;
GL11.glTexParameter(target, pname, params);
}
public static void glTexParameter(int target, int pname, FloatBuffer params) {
if (target != GL11.GL_TEXTURE_2D || params.remaining() != 1 ) {
GL11.glTexParameter(target, pname, params);
return;
}
if(!updateTexParameterfCache(target, getBoundTextureForServerState(), pname, params.get(0))) return;
GL11.glTexParameter(target, pname, params);
}
public static void glTexParameteri(int target, int pname, int param) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordTexParameteri(target, pname, param);
if (mode == RecordMode.COMPILE) {
return;
}
}
if (target != GL11.GL_TEXTURE_2D) {
GL11.glTexParameteri(target, pname, param);
return;
}
if (!updateTexParameteriCache(target, getBoundTextureForServerState(), pname, param)) return;
GL11.glTexParameteri(target, pname, param);
}
public static boolean updateTexParameterfCache(int target, int texture, int pname, float param) {
if (target != GL11.GL_TEXTURE_2D) {
return true;
}
final TextureInfo info = TextureInfoCache.INSTANCE.getInfo(texture);
if (info == null) {
return true;
}
switch (pname) {
case EXTTextureFilterAnisotropic.GL_TEXTURE_MAX_ANISOTROPY_EXT -> {
if(info.getMaxAnisotropy() == param && !shouldBypassCache()) return false;
info.setMaxAnisotropy(param);
}
case GL14.GL_TEXTURE_LOD_BIAS -> {
if(info.getLodBias() == param && !shouldBypassCache()) return false;
info.setLodBias(param);
}
}
return true;
}
public static void glTexParameterf(int target, int pname, float param) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordTexParameterf(target, pname, param);
if (mode == RecordMode.COMPILE) {
return;
}
}
if (target != GL11.GL_TEXTURE_2D) {
GL11.glTexParameterf(target, pname, param);
return;
}
if (!updateTexParameterfCache(target, getBoundTextureForServerState(), pname, param)) return;
GL11.glTexParameterf(target, pname, param);
}
public static int getTexParameterOrDefault(int texture, int pname, IntSupplier defaultSupplier) {
final TextureInfo info = TextureInfoCache.INSTANCE.getInfo(texture);
if (info == null) {
if (isRecordingDisplayList()) {
throw new IllegalStateException(String.format(
"glGetTexParameteri called during display list recording with no cached TextureInfo for texture %d. " +
"Cannot query OpenGL state during compilation!", texture));
}
return defaultSupplier.getAsInt();
}
return switch (pname) {
case GL11.GL_TEXTURE_MIN_FILTER -> info.getMinFilter();
case GL11.GL_TEXTURE_MAG_FILTER -> info.getMagFilter();
case GL11.GL_TEXTURE_WRAP_S -> info.getWrapS();
case GL11.GL_TEXTURE_WRAP_T -> info.getWrapT();
case GL12.GL_TEXTURE_MAX_LEVEL -> info.getMaxLevel();
case GL12.GL_TEXTURE_MIN_LOD -> info.getMinLod();
case GL12.GL_TEXTURE_MAX_LOD -> info.getMaxLod();
default -> {
if (isRecordingDisplayList()) {
throw new IllegalStateException(String.format(
"glGetTexParameteri called during display list recording with uncached pname 0x%s for texture %d. " +
"Cannot query OpenGL state during compilation!", Integer.toHexString(pname), texture));
}
yield defaultSupplier.getAsInt();
}
};
}
public static int glGetTexParameteri(int target, int pname) {
if (target != GL11.GL_TEXTURE_2D || shouldBypassCache()) {
return GL11.glGetTexParameteri(target, pname);
}
return getTexParameterOrDefault(getBoundTextureForServerState(), pname, () -> GL11.glGetTexParameteri(target, pname));
}
public static float glGetTexParameterf(int target, int pname) {
if (target != GL11.GL_TEXTURE_2D || shouldBypassCache()) {
return GL11.glGetTexParameterf(target, pname);
}
final int boundTexture = getBoundTextureForServerState();
final TextureInfo info = TextureInfoCache.INSTANCE.getInfo(boundTexture);
if(info == null) {
if (isRecordingDisplayList()) {
throw new IllegalStateException(String.format(
"glGetTexParameterf called during display list recording with no cached TextureInfo for texture %d. " +
"Cannot query OpenGL state during compilation!", boundTexture));
}
return GL11.glGetTexParameterf(target, pname);
}
return switch (pname) {
case EXTTextureFilterAnisotropic.GL_TEXTURE_MAX_ANISOTROPY_EXT -> info.getMaxAnisotropy();
case GL14.GL_TEXTURE_LOD_BIAS -> info.getLodBias();
default -> {
if (isRecordingDisplayList()) {
throw new IllegalStateException(String.format(
"glGetTexParameterf called during display list recording with uncached pname 0x%s for texture %d. " +
"Cannot query OpenGL state during compilation!", Integer.toHexString(pname), boundTexture));
}
yield GL11.glGetTexParameterf(target, pname);
}
};
}
public static int glGetTexLevelParameteri(int target, int level, int pname) {
if (target != GL11.GL_TEXTURE_2D || shouldBypassCache()) {
return GL11.glGetTexLevelParameteri(target, level, pname);
}
final TextureInfo info = TextureInfoCache.INSTANCE.getInfo(getBoundTextureForServerState());
if (info == null) {
if (isRecordingDisplayList()) {
throw new IllegalStateException(String.format(
"glGetTexLevelParameteri called during display list recording with no cached TextureInfo for texture %d. " +
"Cannot query OpenGL state during compilation!", getBoundTextureForServerState()));
}
return GL11.glGetTexLevelParameteri(target, level, pname);
}
return switch (pname) {
case GL11.GL_TEXTURE_WIDTH -> info.getWidth();
case GL11.GL_TEXTURE_HEIGHT -> info.getHeight();
case GL11.GL_TEXTURE_INTERNAL_FORMAT -> info.getInternalFormat();
default -> {
if (isRecordingDisplayList()) {
throw new IllegalStateException(String.format(
"glGetTexLevelParameteri called during display list recording with uncached pname 0x%s for texture %d. " +
"Cannot query OpenGL state during compilation!", Integer.toHexString(pname), getBoundTextureForServerState()));
}
yield GL11.glGetTexLevelParameteri(target, level, pname);
}
};
}
private static void glMaterialFront(int pname, FloatBuffer params) {
switch (pname) {
case GL11.GL_AMBIENT -> frontMaterial.setAmbient(params);
case GL11.GL_DIFFUSE -> frontMaterial.setDiffuse(params);
case GL11.GL_SPECULAR -> frontMaterial.setSpecular(params);
case GL11.GL_EMISSION -> frontMaterial.setEmission(params);
case GL11.GL_SHININESS -> frontMaterial.setShininess(params);
case GL11.GL_AMBIENT_AND_DIFFUSE -> {
frontMaterial.setAmbient(params);
frontMaterial.setDiffuse(params);
}
case GL11.GL_COLOR_INDEXES -> frontMaterial.setColorIndexes(params);
}
}
private static void glMaterialBack(int pname, FloatBuffer params) {
switch (pname) {
case GL11.GL_AMBIENT -> backMaterial.setAmbient(params);
case GL11.GL_DIFFUSE -> backMaterial.setDiffuse(params);
case GL11.GL_SPECULAR -> backMaterial.setSpecular(params);
case GL11.GL_EMISSION -> backMaterial.setEmission(params);
case GL11.GL_SHININESS -> backMaterial.setShininess(params);
case GL11.GL_AMBIENT_AND_DIFFUSE -> {
backMaterial.setAmbient(params);
backMaterial.setDiffuse(params);
}
case GL11.GL_COLOR_INDEXES -> backMaterial.setColorIndexes(params);
}
}
private static void glMaterialFront(int pname, IntBuffer params) {
switch (pname) {
case GL11.GL_AMBIENT -> frontMaterial.setAmbient(params);
case GL11.GL_DIFFUSE -> frontMaterial.setDiffuse(params);
case GL11.GL_SPECULAR -> frontMaterial.setSpecular(params);
case GL11.GL_EMISSION -> frontMaterial.setEmission(params);
case GL11.GL_SHININESS -> frontMaterial.setShininess(params);
case GL11.GL_AMBIENT_AND_DIFFUSE -> {
frontMaterial.setAmbient(params);
frontMaterial.setDiffuse(params);
}
case GL11.GL_COLOR_INDEXES -> frontMaterial.setColorIndexes(params);
}
}
private static void glMaterialBack(int pname, IntBuffer params) {
switch (pname) {
case GL11.GL_AMBIENT -> backMaterial.setAmbient(params);
case GL11.GL_DIFFUSE -> backMaterial.setDiffuse(params);
case GL11.GL_SPECULAR -> backMaterial.setSpecular(params);
case GL11.GL_EMISSION -> backMaterial.setEmission(params);
case GL11.GL_SHININESS -> backMaterial.setShininess(params);
case GL11.GL_AMBIENT_AND_DIFFUSE -> {
backMaterial.setAmbient(params);
backMaterial.setDiffuse(params);
}
case GL11.GL_COLOR_INDEXES -> backMaterial.setColorIndexes(params);
}
}
public static void glMaterial(int face, int pname, FloatBuffer params) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordMaterial(face, pname, params);
if (mode == RecordMode.COMPILE) {
return;
}
}
if (face == GL11.GL_FRONT) {
glMaterialFront(pname, params);
} else if (face == GL11.GL_BACK) {
glMaterialBack(pname, params);
} else if (face == GL11.GL_FRONT_AND_BACK) {
glMaterialFront(pname, params);
glMaterialBack(pname, params);
} else {
throw new RuntimeException("Unsupported face value for glMaterial: " + face);
}
}
public static void glMaterial(int face, int pname, IntBuffer params) {
// For IntBuffer version, we need to convert to float for recording
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
// Convert int params to float for recording
final float[] floatParams = new float[params.remaining()];
params.mark();
for (int i = 0; i < floatParams.length; i++) {
floatParams[i] = GLStateManager.i2f(params.get());
}
params.reset();
DisplayListManager.recordMaterial(face, pname, java.nio.FloatBuffer.wrap(floatParams));
if (mode == RecordMode.COMPILE) {
return;
}
}
if (face == GL11.GL_FRONT) {
glMaterialFront(pname, params);
} else if (face == GL11.GL_BACK) {
glMaterialBack(pname, params);
} else if (face == GL11.GL_FRONT_AND_BACK) {
glMaterialFront(pname, params);
glMaterialBack(pname, params);
} else {
throw new RuntimeException("Unsupported face value for glMaterial: " + face);
}
}
public static void glMaterialf(int face, int pname, float val) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordMaterialf(face, pname, val);
if (mode == RecordMode.COMPILE) {
return;
}
}
if (pname != GL11.GL_SHININESS) {
// it is only valid to call glMaterialf for the GL_SHININESS parameter
return;
}
if (face == GL11.GL_FRONT) {
frontMaterial.setShininess(val);
} else if (face == GL11.GL_BACK) {
backMaterial.setShininess(val);
} else if (face == GL11.GL_FRONT_AND_BACK) {
frontMaterial.setShininess(val);
backMaterial.setShininess(val);
} else {
throw new RuntimeException("Unsupported face value for glMaterial: " + face);
}
}
public static void glMateriali(int face, int pname, int val) {
// This will end up no-opping if pname != GL_SHININESS, it is invalid to call this with another pname
// Command recording happens in glMaterialf
glMaterialf(face, pname, (float) val);
}
public static void glLight(int light, int pname, FloatBuffer params) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordLight(light, pname, params);
if (mode == RecordMode.COMPILE) {
return;
}
}
final LightStateStack lightState = lightDataStates[light - GL11.GL_LIGHT0];
switch (pname) {
case GL11.GL_AMBIENT -> lightState.setAmbient(params);
case GL11.GL_DIFFUSE -> lightState.setDiffuse(params);
case GL11.GL_SPECULAR -> lightState.setSpecular(params);
case GL11.GL_POSITION -> lightState.setPosition(params);
case GL11.GL_SPOT_DIRECTION -> lightState.setSpotDirection(params);
case GL11.GL_SPOT_EXPONENT -> lightState.setSpotExponent(params);
case GL11.GL_SPOT_CUTOFF -> lightState.setSpotCutoff(params);
case GL11.GL_CONSTANT_ATTENUATION -> lightState.setConstantAttenuation(params);
case GL11.GL_LINEAR_ATTENUATION -> lightState.setLinearAttenuation(params);
case GL11.GL_QUADRATIC_ATTENUATION -> lightState.setQuadraticAttenuation(params);
default -> GL11.glLight(light, pname, params);
}
}
public static void glLight(int light, int pname, IntBuffer params) {
// For IntBuffer version, we need to convert to float for recording
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
// Convert int params to float for recording
final float[] floatParams = new float[params.remaining()];
params.mark();
for (int i = 0; i < floatParams.length; i++) {
floatParams[i] = GLStateManager.i2f(params.get());
}
params.reset();
DisplayListManager.recordLight(light, pname, java.nio.FloatBuffer.wrap(floatParams));
if (mode == RecordMode.COMPILE) {
return;
}
}
final LightStateStack lightState = lightDataStates[light - GL11.GL_LIGHT0];
switch (pname) {
case GL11.GL_AMBIENT -> lightState.setAmbient(params);
case GL11.GL_DIFFUSE -> lightState.setDiffuse(params);
case GL11.GL_SPECULAR -> lightState.setSpecular(params);
case GL11.GL_POSITION -> lightState.setPosition(params);
case GL11.GL_SPOT_DIRECTION -> lightState.setSpotDirection(params);
case GL11.GL_SPOT_EXPONENT -> lightState.setSpotExponent(params);
case GL11.GL_SPOT_CUTOFF -> lightState.setSpotCutoff(params);
case GL11.GL_CONSTANT_ATTENUATION -> lightState.setConstantAttenuation(params);
case GL11.GL_LINEAR_ATTENUATION -> lightState.setLinearAttenuation(params);
case GL11.GL_QUADRATIC_ATTENUATION -> lightState.setQuadraticAttenuation(params);
default -> GL11.glLight(light, pname, params);
}
}
public static void glLightf(int light, int pname, float param) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordLightf(light, pname, param);
if (mode == RecordMode.COMPILE) {
return;
}
}
final LightStateStack lightState = lightDataStates[light - GL11.GL_LIGHT0];
switch (pname) {
case GL11.GL_SPOT_EXPONENT -> lightState.setSpotExponent(param);
case GL11.GL_SPOT_CUTOFF -> lightState.setSpotCutoff(param);
case GL11.GL_CONSTANT_ATTENUATION -> lightState.setConstantAttenuation(param);
case GL11.GL_LINEAR_ATTENUATION -> lightState.setLinearAttenuation(param);
case GL11.GL_QUADRATIC_ATTENUATION -> lightState.setQuadraticAttenuation(param);
default -> GL11.glLightf(light, pname, param);
}
}
public static void glLighti(int light, int pname, int param) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordLighti(light, pname, param);
if (mode == RecordMode.COMPILE) {
return;
}
}
final LightStateStack lightState = lightDataStates[light - GL11.GL_LIGHT0];
switch (pname) {
case GL11.GL_SPOT_EXPONENT -> lightState.setSpotExponent(param);
case GL11.GL_SPOT_CUTOFF -> lightState.setSpotCutoff(param);
case GL11.GL_CONSTANT_ATTENUATION -> lightState.setConstantAttenuation(param);
case GL11.GL_LINEAR_ATTENUATION -> lightState.setLinearAttenuation(param);
case GL11.GL_QUADRATIC_ATTENUATION -> lightState.setQuadraticAttenuation(param);
default -> GL11.glLighti(light, pname, param);
}
}
public static void glLightModel(int pname, FloatBuffer params) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordLightModel(pname, params);
if (mode == RecordMode.COMPILE) {
return;
}
}
switch (pname) {
case GL11.GL_LIGHT_MODEL_AMBIENT -> lightModel.setAmbient(params);
case GL11.GL_LIGHT_MODEL_LOCAL_VIEWER -> lightModel.setLocalViewer(params);
case GL11.GL_LIGHT_MODEL_TWO_SIDE -> lightModel.setTwoSide(params);
default -> GL11.glLightModel(pname, params);
}
}
public static void glLightModel(int pname, IntBuffer params) {
// For IntBuffer version, we need to convert to float for recording
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
// Convert int params to float for recording
final float[] floatParams = new float[params.remaining()];
params.mark();
for (int i = 0; i < floatParams.length; i++) {
floatParams[i] = GLStateManager.i2f(params.get());
}
params.reset();
DisplayListManager.recordLightModel(pname, java.nio.FloatBuffer.wrap(floatParams));
if (mode == RecordMode.COMPILE) {
return;
}
}
switch (pname) {
case GL11.GL_LIGHT_MODEL_AMBIENT -> lightModel.setAmbient(params);
case GL12.GL_LIGHT_MODEL_COLOR_CONTROL -> lightModel.setColorControl(params);
case GL11.GL_LIGHT_MODEL_LOCAL_VIEWER -> lightModel.setLocalViewer(params);
case GL11.GL_LIGHT_MODEL_TWO_SIDE -> lightModel.setTwoSide(params);
default -> GL11.glLightModel(pname, params);
}
}
public static void glLightModelf(int pname, float param) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordLightModelf(pname, param);
if (mode == RecordMode.COMPILE) {
return;
}
}
if (isCachingEnabled()) {
switch (pname) {
case GL11.GL_LIGHT_MODEL_LOCAL_VIEWER -> lightModel.setLocalViewer(param);
case GL11.GL_LIGHT_MODEL_TWO_SIDE -> lightModel.setTwoSide(param);
default -> GL11.glLightModelf(pname, param);
}
} else {
GL11.glLightModelf(pname, param);
}
}
public static void glLightModeli(int pname, int param) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordLightModeli(pname, param);
if (mode == RecordMode.COMPILE) {
return;
}
}
if (isCachingEnabled()) {
switch (pname) {
case GL12.GL_LIGHT_MODEL_COLOR_CONTROL -> lightModel.setColorControl(param);
case GL11.GL_LIGHT_MODEL_LOCAL_VIEWER -> lightModel.setLocalViewer(param);
case GL11.GL_LIGHT_MODEL_TWO_SIDE -> lightModel.setTwoSide(param);
default -> GL11.glLightModeli(pname, param);
}
} else {
GL11.glLightModeli(pname, param);
}
}
public static void glColorMaterial(int face, int mode) {
final RecordMode recordMode = DisplayListManager.getRecordMode();
if (recordMode != RecordMode.NONE) {
DisplayListManager.recordColorMaterial(face, mode);
if (recordMode == RecordMode.COMPILE) {
return;
}
}
final boolean caching = isCachingEnabled();
if (BYPASS_CACHE || !caching || colorMaterialFace.getValue() != face || colorMaterialParameter.getValue() != mode) {
if (caching) {
colorMaterialFace.setValue(face);
colorMaterialParameter.setValue(mode);
}
GL11.glColorMaterial(face, mode);
}
}
public static void glDepthRange(double near, double far) {
GL11.glDepthRange(near, far);
}
public static void glUseProgram(int program) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordUseProgram(program);
if (mode == RecordMode.COMPILE) {
return;
}
}
final boolean caching = isCachingEnabled();
if (BYPASS_CACHE || !caching || program != activeProgram) {
if (caching) {
activeProgram = program;
}
if (AngelicaMod.lwjglDebug) {
final String programName = GLDebug.getObjectLabel(KHRDebug.GL_PROGRAM, program);
GLDebug.debugMessage("Activating Program - " + program + ":" + programName);
}
GL20.glUseProgram(program);
}
}
// Missing GL commands from Mesa cross-check
public static void glTexImage1D(int target, int level, int internalformat, int width, int border, int format, int type, ByteBuffer pixels) {
if (DisplayListManager.isRecording()) {
throw new UnsupportedOperationException("glTexImage1D in display lists not yet implemented");
}
GL11.glTexImage1D(target, level, internalformat, width, border, format, type, pixels);
}
public static void glTexImage3D(int target, int level, int internalformat, int width, int height, int depth, int border, int format, int type, ByteBuffer pixels) {
if (DisplayListManager.isRecording()) {
throw new UnsupportedOperationException("glTexImage3D in display lists not yet implemented");
}
GL12.glTexImage3D(target, level, internalformat, width, height, depth, border, format, type, pixels);
}
public static void glTexSubImage1D(int target, int level, int xoffset, int width, int format, int type, ByteBuffer pixels) {
if (DisplayListManager.isRecording()) {
throw new UnsupportedOperationException("glTexSubImage1D in display lists not yet implemented");
}
GL11.glTexSubImage1D(target, level, xoffset, width, format, type, pixels);
}
public static void glLineWidth(float width) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordLineWidth(width);
if (mode == RecordMode.COMPILE) {
return;
}
}
final boolean caching = isCachingEnabled();
if (BYPASS_CACHE || !caching || lineState.getWidth() != width) {
if (caching) {
lineState.setWidth(width);
}
GL11.glLineWidth(width);
}
}
// Texture commands
public static void glTexSubImage2D(int target, int level, int xoffset, int yoffset, int width, int height, int format, int type, ByteBuffer pixels) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordComplexCommand(TexSubImage2DCmd.fromByteBuffer(target, level, xoffset, yoffset, width, height, format, type, pixels));
if (mode == RecordMode.COMPILE) {
return;
}
}
if (shouldUseDSA(target)) {
// Use DSA to upload directly to the texture - keeps GL binding state unchanged
RenderSystem.textureSubImage2D(getBoundTextureForServerState(), target, level, xoffset, yoffset, width, height, format, type, pixels);
} else {
// Non-main thread or proxy texture - use direct GL call
GL11.glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels);
}
}
public static void glTexSubImage2D(int target, int level, int xoffset, int yoffset, int width, int height, int format, int type, IntBuffer pixels) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordComplexCommand(TexSubImage2DCmd.fromIntBuffer(target, level, xoffset, yoffset, width, height, format, type, pixels));
if (mode == RecordMode.COMPILE) {
return;
}
}
if (shouldUseDSA(target)) {
// Use DSA to upload directly to the texture
RenderSystem.textureSubImage2D(getBoundTextureForServerState(), target, level, xoffset, yoffset, width, height, format, type, pixels);
} else {
// Non-main thread or proxy texture - use direct GL call
GL11.glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels);
}
}
public static void glTexSubImage2D(int target, int level, int xoffset, int yoffset, int width, int height, int format, int type, long pixels_buffer_offset) {
if (DisplayListManager.isRecording()) {
throw new UnsupportedOperationException("glTexSubImage2D with buffer offset in display lists not yet supported");
}
GL11.glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels_buffer_offset);
}
public static void glTexSubImage3D(int target, int level, int xoffset, int yoffset, int zoffset, int width, int height, int depth, int format, int type, ByteBuffer pixels) {
if (DisplayListManager.isRecording()) {
throw new UnsupportedOperationException("glTexSubImage3D in display lists not yet implemented - if you see this, please report!");
}
GL12.glTexSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, pixels);
}
public static void glCopyTexImage1D(int target, int level, int internalFormat, int x, int y, int width, int border) {
if (DisplayListManager.isRecording()) {
throw new UnsupportedOperationException("glCopyTexImage1D in display lists not yet implemented - if you see this, please report!");
}
GL11.glCopyTexImage1D(target, level, internalFormat, x, y, width, border);
}
public static void glCopyTexImage2D(int target, int level, int internalFormat, int x, int y, int width, int height, int border) {
if (DisplayListManager.isRecording()) {
throw new UnsupportedOperationException("glCopyTexImage2D in display lists not yet implemented - if you see this, please report!");
}
GL11.glCopyTexImage2D(target, level, internalFormat, x, y, width, height, border);
}
public static void glCopyTexSubImage1D(int target, int level, int xoffset, int x, int y, int width) {
if (DisplayListManager.isRecording()) {
throw new UnsupportedOperationException("glCopyTexSubImage1D in display lists not yet implemented - if you see this, please report!");
}
GL11.glCopyTexSubImage1D(target, level, xoffset, x, y, width);
}
public static void glCopyTexSubImage2D(int target, int level, int xoffset, int yoffset, int x, int y, int width, int height) {
if (DisplayListManager.isRecording()) {
throw new UnsupportedOperationException("glCopyTexSubImage2D in display lists not yet implemented - if you see this, please report!");
}
GL11.glCopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height);
}
public static void glCopyTexSubImage3D(int target, int level, int xoffset, int yoffset, int zoffset, int x, int y, int width, int height) {
if (DisplayListManager.isRecording()) {
throw new UnsupportedOperationException("glCopyTexSubImage3D in display lists not yet implemented - if you see this, please report!");
}
GL12.glCopyTexSubImage3D(target, level, xoffset, yoffset, zoffset, x, y, width, height);
}
// State commands
public static void glCullFace(int mode) {
final RecordMode recordMode = DisplayListManager.getRecordMode();
if (recordMode != RecordMode.NONE) {
DisplayListManager.recordCullFace(mode);
if (recordMode == RecordMode.COMPILE) {
return;
}
}
final boolean caching = isCachingEnabled();
if (BYPASS_CACHE || !caching || polygonState.getCullFaceMode() != mode) {
if (caching) {
polygonState.setCullFaceMode(mode);
}
GL11.glCullFace(mode);
}
}
public static void glFrontFace(int mode) {
final RecordMode recordMode = DisplayListManager.getRecordMode();
if (recordMode != RecordMode.NONE) {
DisplayListManager.recordFrontFace(mode);
if (recordMode == RecordMode.COMPILE) {
return;
}
}
final boolean caching = isCachingEnabled();
if (BYPASS_CACHE || !caching || polygonState.getFrontFace() != mode) {
if (caching) {
polygonState.setFrontFace(mode);
}
GL11.glFrontFace(mode);
}
}
public static void glHint(int target, int hint) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordHint(target, hint);
if (mode == RecordMode.COMPILE) {
return;
}
}
GL11.glHint(target, hint);
}
public static void glLineStipple(int factor, short pattern) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordLineStipple(factor, pattern);
if (mode == RecordMode.COMPILE) {
return;
}
}
final boolean caching = isCachingEnabled();
if (BYPASS_CACHE || !caching || lineState.getStippleFactor() != factor || lineState.getStipplePattern() != pattern) {
if (caching) {
lineState.setStippleFactor(factor);
lineState.setStipplePattern(pattern);
}
GL11.glLineStipple(factor, pattern);
}
}
public static void glPointSize(float size) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordPointSize(size);
if (mode == RecordMode.COMPILE) {
return;
}
}
final boolean caching = isCachingEnabled();
if (BYPASS_CACHE || !caching || pointState.getSize() != size) {
if (caching) {
pointState.setSize(size);
}
GL11.glPointSize(size);
}
}
public static void glPolygonMode(int face, int polygonMode) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordPolygonMode(face, polygonMode);
if (mode == RecordMode.COMPILE) {
return;
}
}
final boolean caching = isCachingEnabled();
final boolean needsUpdate;
if (face == GL11.GL_FRONT) {
needsUpdate = BYPASS_CACHE || !caching || polygonState.getFrontMode() != polygonMode;
if (caching && needsUpdate) polygonState.setFrontMode(polygonMode);
} else if (face == GL11.GL_BACK) {
needsUpdate = BYPASS_CACHE || !caching || polygonState.getBackMode() != polygonMode;
if (caching && needsUpdate) polygonState.setBackMode(polygonMode);
} else { // GL_FRONT_AND_BACK
needsUpdate = BYPASS_CACHE || !caching || polygonState.getFrontMode() != polygonMode || polygonState.getBackMode() != polygonMode;
if (caching && needsUpdate) {
polygonState.setFrontMode(polygonMode);
polygonState.setBackMode(polygonMode);
}
}
if (needsUpdate) {
GL11.glPolygonMode(face, polygonMode);
}
}
public static void glPolygonOffset(float factor, float units) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordPolygonOffset(factor, units);
if (mode == RecordMode.COMPILE) {
return;
}
}
final boolean caching = isCachingEnabled();
if (BYPASS_CACHE || !caching || polygonState.getOffsetFactor() != factor || polygonState.getOffsetUnits() != units) {
if (caching) {
polygonState.setOffsetFactor(factor);
polygonState.setOffsetUnits(units);
}
GL11.glPolygonOffset(factor, units);
}
}
public static void glReadBuffer(int mode) {
if (DisplayListManager.isRecording()) {
throw new UnsupportedOperationException("glReadBuffer in display lists not yet implemented - if you see this, please report!");
}
GL11.glReadBuffer(mode);
}
public static void glScissor(int x, int y, int width, int height) {
if (DisplayListManager.isRecording()) {
throw new UnsupportedOperationException("glScissor in display lists not yet implemented - if you see this, please report!");
}
GL11.glScissor(x, y, width, height);
}
public static void glStencilFunc(int func, int ref, int mask) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordStencilFunc(func, ref, mask);
if (mode == RecordMode.COMPILE) {
return;
}
}
final boolean caching = isCachingEnabled();
if (BYPASS_CACHE || !caching || stencilState.getFuncFront() != func || stencilState.getRefFront() != ref || stencilState.getValueMaskFront() != mask) {
if (caching) {
stencilState.setFunc(func, ref, mask);
}
GL11.glStencilFunc(func, ref, mask);
}
}
public static void glStencilMask(int mask) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordStencilMask(mask);
if (mode == RecordMode.COMPILE) {
return;
}
}
final boolean caching = isCachingEnabled();
if (BYPASS_CACHE || !caching || stencilState.getWriteMaskFront() != mask) {
if (caching) {
stencilState.setWriteMask(mask);
}
GL11.glStencilMask(mask);
}
}
public static void glStencilOp(int fail, int zfail, int zpass) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordStencilOp(fail, zfail, zpass);
if (mode == RecordMode.COMPILE) {
return;
}
}
final boolean caching = isCachingEnabled();
if (BYPASS_CACHE || !caching || stencilState.getFailOpFront() != fail || stencilState.getZFailOpFront() != zfail || stencilState.getZPassOpFront() != zpass) {
if (caching) {
stencilState.setOp(fail, zfail, zpass);
}
GL11.glStencilOp(fail, zfail, zpass);
}
}
public static void glPixelStorei(int pname, int param) {
if (DisplayListManager.isRecording()) {
throw new UnsupportedOperationException("glPixelStorei in display lists not yet implemented - if you see this, please report!");
}
GL11.glPixelStorei(pname, param);
}
public static void glPixelStoref(int pname, float param) {
if (DisplayListManager.isRecording()) {
throw new UnsupportedOperationException("glPixelStoref in display lists not yet implemented - if you see this, please report!");
}
GL11.glPixelStoref(pname, param);
}
// Display List Commands
public static void glCallLists(IntBuffer lists) {
if (DisplayListManager.isRecording()) {
throw new UnsupportedOperationException("glCallLists in display lists not yet implemented - if you see this, please report!");
}
GL11.glCallLists(lists);
}
public static void glCallLists(ByteBuffer lists) {
if (DisplayListManager.isRecording()) {
throw new UnsupportedOperationException("glCallLists in display lists not yet implemented - if you see this, please report!");
}
GL11.glCallLists(lists);
}
public static void glListBase(int base) {
if (DisplayListManager.isRecording()) {
throw new UnsupportedOperationException("glListBase in display lists not yet implemented - if you see this, please report!");
}
GL11.glListBase(base);
}
// Clip Plane Commands
public static void glClipPlane(int plane, DoubleBuffer equation) {
if (DisplayListManager.isRecording()) {
throw new UnsupportedOperationException("glClipPlane in display lists not yet implemented - if you see this, please report!");
}
GL11.glClipPlane(plane, equation);
}
// Clear Commands
public static void glClearStencil(int s) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordClearStencil(s);
if (mode == RecordMode.COMPILE) {
return;
}
}
final boolean caching = isCachingEnabled();
if (BYPASS_CACHE || !caching || stencilState.getClearValue() != s) {
if (caching) {
stencilState.setClearValue(s);
}
GL11.glClearStencil(s);
}
}
// Draw Buffer Commands (GL 2.0+)
public static void glDrawBuffers(int buffer) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordDrawBuffers(1, buffer);
if (mode == RecordMode.COMPILE) {
return;
}
}
GL20.glDrawBuffers(buffer);
}
public static void glDrawBuffers(IntBuffer bufs) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordDrawBuffers(bufs.remaining(), bufs);
if (mode == RecordMode.COMPILE) {
return;
}
}
GL20.glDrawBuffers(bufs);
}
// Multisample Commands
public static void glSampleCoverage(float value, boolean invert) {
if (DisplayListManager.isRecording()) {
throw new UnsupportedOperationException("glSampleCoverage in display lists not yet implemented - if you see this, please report!");
}
GL13.glSampleCoverage(value, invert);
}
// Stencil Separate Functions (GL 2.0+)
public static void glStencilFuncSeparate(int face, int func, int ref, int mask) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordStencilFuncSeparate(face, func, ref, mask);
if (mode == RecordMode.COMPILE) {
return;
}
}
final boolean caching = isCachingEnabled();
boolean needsUpdate = BYPASS_CACHE || !caching;
if (!needsUpdate) {
if (face == GL11.GL_FRONT || face == GL11.GL_FRONT_AND_BACK) {
needsUpdate = stencilState.getFuncFront() != func || stencilState.getRefFront() != ref || stencilState.getValueMaskFront() != mask;
}
if (!needsUpdate && (face == GL11.GL_BACK || face == GL11.GL_FRONT_AND_BACK)) {
needsUpdate = stencilState.getFuncBack() != func || stencilState.getRefBack() != ref || stencilState.getValueMaskBack() != mask;
}
}
if (needsUpdate) {
if (caching) {
if (face == GL11.GL_FRONT || face == GL11.GL_FRONT_AND_BACK) {
stencilState.setFuncFront(func);
stencilState.setRefFront(ref);
stencilState.setValueMaskFront(mask);
}
if (face == GL11.GL_BACK || face == GL11.GL_FRONT_AND_BACK) {
stencilState.setFuncBack(func);
stencilState.setRefBack(ref);
stencilState.setValueMaskBack(mask);
}
}
GL20.glStencilFuncSeparate(face, func, ref, mask);
}
}
public static void glStencilMaskSeparate(int face, int mask) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordStencilMaskSeparate(face, mask);
if (mode == RecordMode.COMPILE) {
return;
}
}
final boolean caching = isCachingEnabled();
boolean needsUpdate = BYPASS_CACHE || !caching;
if (!needsUpdate) {
if (face == GL11.GL_FRONT || face == GL11.GL_FRONT_AND_BACK) {
needsUpdate = stencilState.getWriteMaskFront() != mask;
}
if (!needsUpdate && (face == GL11.GL_BACK || face == GL11.GL_FRONT_AND_BACK)) {
needsUpdate = stencilState.getWriteMaskBack() != mask;
}
}
if (needsUpdate) {
if (caching) {
if (face == GL11.GL_FRONT || face == GL11.GL_FRONT_AND_BACK) {
stencilState.setWriteMaskFront(mask);
}
if (face == GL11.GL_BACK || face == GL11.GL_FRONT_AND_BACK) {
stencilState.setWriteMaskBack(mask);
}
}
GL20.glStencilMaskSeparate(face, mask);
}
}
public static void glStencilOpSeparate(int face, int sfail, int dpfail, int dppass) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordStencilOpSeparate(face, sfail, dpfail, dppass);
if (mode == RecordMode.COMPILE) {
return;
}
}
final boolean caching = isCachingEnabled();
boolean needsUpdate = BYPASS_CACHE || !caching;
if (!needsUpdate) {
if (face == GL11.GL_FRONT || face == GL11.GL_FRONT_AND_BACK) {
needsUpdate = stencilState.getFailOpFront() != sfail || stencilState.getZFailOpFront() != dpfail || stencilState.getZPassOpFront() != dppass;
}
if (!needsUpdate && (face == GL11.GL_BACK || face == GL11.GL_FRONT_AND_BACK)) {
needsUpdate = stencilState.getFailOpBack() != sfail || stencilState.getZFailOpBack() != dpfail || stencilState.getZPassOpBack() != dppass;
}
}
if (needsUpdate) {
if (caching) {
if (face == GL11.GL_FRONT || face == GL11.GL_FRONT_AND_BACK) {
stencilState.setFailOpFront(sfail);
stencilState.setZFailOpFront(dpfail);
stencilState.setZPassOpFront(dppass);
}
if (face == GL11.GL_BACK || face == GL11.GL_FRONT_AND_BACK) {
stencilState.setFailOpBack(sfail);
stencilState.setZFailOpBack(dpfail);
stencilState.setZPassOpBack(dppass);
}
}
GL20.glStencilOpSeparate(face, sfail, dpfail, dppass);
}
}
public static boolean vendorIsAMD() {
return VENDOR == AMD;
}
public static boolean vendorIsIntel() {
return VENDOR == INTEL;
}
public static boolean vendorIsMesa() {
return VENDOR == MESA;
}
public static boolean vendorIsNVIDIA() {
return VENDOR == NVIDIA;
}
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\glsm\LineBuffer.java
|
package com.gtnewhorizons.angelica.glsm;
import com.gtnewhorizon.gtnhlib.client.renderer.vao.VAOManager;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat;
import com.gtnewhorizons.angelica.glsm.recording.AccumulatedLineDraw;
import com.gtnewhorizons.angelica.glsm.recording.ImmediateModeRecorder;
import org.joml.Matrix4f;
import org.lwjgl.opengl.GL11;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
/**
* Accumulates line geometry during display list compilation.
* All line draws are collected here, then compiled into a single VBO.
* <p>
* Lines all use the same format (POSITION_COLOR), so no format-based grouping needed.
* <p>
* Tracks two types of ranges:
* <ul>
* <li><b>mergedRanges</b>: Consecutive same-transform draws merged for optimized path</li>
* <li><b>perDrawRanges</b>: One range per input draw for unoptimized path (1:1 with addDraw calls)</li>
* </ul>
*/
class LineBuffer {
final List<ImmediateModeRecorder.LineVertex> allVertices = new ArrayList<>();
// Merged ranges for optimized path (consecutive same-transform draws combined)
final List<DrawRange> mergedRanges = new ArrayList<>();
// Per-draw ranges for unoptimized path (1:1 with input draws)
final List<DrawRange> perDrawRanges = new ArrayList<>();
int currentVertexOffset = 0;
// Track the current range being built for merging consecutive same-transform draws
private int pendingStartVertex = -1;
private int pendingVertexCount = 0;
private Matrix4f pendingTransform = null;
private int pendingCommandIndex = -1;
private int pendingStateGen = -1;
/**
* Add a line draw to this buffer.
* Tracks both merged (for optimized) and per-draw (for unoptimized) ranges.
*/
void addDraw(AccumulatedLineDraw draw) {
int vertexCount = draw.lines.size(); // Each LineVertex is one vertex, lines come in pairs
// Always track per-draw range for unoptimized path
perDrawRanges.add(new DrawRange(currentVertexOffset, vertexCount, draw.transform, draw.commandIndex));
// Merge logic for optimized path:
// - same transform
// - same stateGeneration = no state commands (draw barriers) between draws
boolean canMerge = pendingTransform != null
&& pendingTransform.equals(draw.transform)
&& pendingStateGen == draw.stateGeneration;
if (canMerge) {
// Extend the pending range
pendingVertexCount += vertexCount;
} else {
// Flush pending range if any
flushPendingRange();
// Start new pending range
pendingStartVertex = currentVertexOffset;
pendingVertexCount = vertexCount;
pendingTransform = new Matrix4f(draw.transform);
pendingCommandIndex = draw.commandIndex;
pendingStateGen = draw.stateGeneration;
}
allVertices.addAll(draw.lines);
currentVertexOffset += vertexCount;
}
private void flushPendingRange() {
if (pendingTransform != null) {
mergedRanges.add(new DrawRange(pendingStartVertex, pendingVertexCount, pendingTransform, pendingCommandIndex));
pendingTransform = null;
pendingStateGen = -1;
}
}
/**
* Compile all accumulated line vertices into a single VBO.
* @return The compiled buffer with VBO and both range types, or null if empty
*/
CompiledLineBuffer finish() {
if (allVertices.isEmpty()) {
return null;
}
// Flush any remaining pending range
flushPendingRange();
VertexBuffer vbo = compileLinesToVBO(allVertices);
return new CompiledLineBuffer(
vbo,
mergedRanges.toArray(new DrawRange[0]),
perDrawRanges.toArray(new DrawRange[0])
);
}
/**
* Compile line vertices into a VertexBuffer (VAO or VBO).
* Lines use POSITION_COLOR format (x, y, z, color).
*/
private static VertexBuffer compileLinesToVBO(List<ImmediateModeRecorder.LineVertex> lines) {
final VertexFormat format = DefaultVertexFormat.POSITION_COLOR;
final VertexBuffer vao = VAOManager.createVAO(format, GL11.GL_LINES);
// POSITION_COLOR format: 3 floats (12 bytes) + 4 bytes color = 16 bytes per vertex
final int vertexSize = format.getVertexSize();
final ByteBuffer buffer = org.lwjgl.BufferUtils.createByteBuffer(vertexSize * lines.size());
for (ImmediateModeRecorder.LineVertex v : lines) {
buffer.putFloat(v.x);
buffer.putFloat(v.y);
buffer.putFloat(v.z);
buffer.putInt(v.color);
}
buffer.flip();
vao.upload(buffer);
return vao;
}
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\glsm\OptimizedListResult.java
|
package com.gtnewhorizons.angelica.glsm;
import com.github.bsideup.jabel.Desugar;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer;
import com.gtnewhorizons.angelica.glsm.recording.commands.DisplayListCommand;
/**
* Result of building an optimized display list.
* Contains both the commands and the shared VBOs that need lifecycle management.
*/
@Desugar
record OptimizedListResult(DisplayListCommand[] commands, VertexBuffer[] ownedVbos) {}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\glsm\RenderSystem.java
|
package com.gtnewhorizons.angelica.glsm;
import com.gtnewhorizons.angelica.glsm.dsa.DSAARB;
import com.gtnewhorizons.angelica.glsm.dsa.DSAAccess;
import com.gtnewhorizons.angelica.glsm.dsa.DSACore;
import com.gtnewhorizons.angelica.glsm.dsa.DSAUnsupported;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.Nullable;
import org.joml.Matrix4f;
import org.joml.Vector3i;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.EXTShaderImageLoadStore;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL15;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL30;
import org.lwjgl.opengl.GL40;
import org.lwjgl.opengl.GL42;
import org.lwjgl.opengl.GL43;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
/**
* This class is responsible for abstracting calls to OpenGL and asserting that calls are run on the render thread.
*/
public class RenderSystem {
private static final Logger LOGGER = LogManager.getLogger("RenderSystem");
private static DSAAccess dsaState;
private static boolean supportsCompute;
private RenderSystem() {}
public static void initRenderer() {
try {
if (GLStateManager.capabilities.OpenGL45) {
dsaState = new DSACore();
LOGGER.info("OpenGL 4.5 detected, enabling DSA.");
}
} catch (NoSuchFieldError ignored) {}
try {
if (dsaState == null && GLStateManager.capabilities.GL_ARB_direct_state_access) {
dsaState = new DSAARB();
LOGGER.info("ARB_direct_state_access detected, enabling DSA.");
}
} catch (NoSuchFieldError ignored) {}
if (dsaState == null) {
dsaState = new DSAUnsupported();
LOGGER.info("No DSA support detected, falling back to legacy OpenGL.");
}
supportsCompute = supportsCompute();
}
public static void generateMipmaps(int texture, int mipmapTarget) {
dsaState.generateMipmaps(texture, mipmapTarget);
}
public static void bindAttributeLocation(int program, int index, CharSequence name) {
GL20.glBindAttribLocation(program, index, name);
}
public static void texImage2D(int texture, int target, int level, int internalformat, int width, int height, int border, int format, int type, @Nullable ByteBuffer pixels) {
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texture);
GLStateManager.glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels);
}
public static void uniformMatrix4fv(int location, boolean transpose, FloatBuffer matrix) {
GL20.glUniformMatrix4(location, transpose, matrix);
}
public static void copyTexImage2D(int target, int level, int internalFormat, int x, int y, int width, int height, int border) {
GL11.glCopyTexImage2D(target, level, internalFormat, x, y, width, height, border);
}
public static void uniform1f(int location, float v0) {
GL20.glUniform1f(location, v0);
}
public static void uniform1i(int location, int v0) {
GL20.glUniform1i(location, v0);
}
public static void uniform2f(int location, float v0, float v1) {
GL20.glUniform2f(location, v0, v1);
}
public static void uniform2i(int location, int v0, int v1) {
GL20.glUniform2i(location, v0, v1);
}
public static void uniform3f(int location, float v0, float v1, float v2) {
GL20.glUniform3f(location, v0, v1, v2);
}
public static void uniform3i(int location, int v0, int v1, int v2) { GL20.glUniform3i(location, v0, v1, v2); }
public static void uniform4f(int location, float v0, float v1, float v2, float v3) {
GL20.glUniform4f(location, v0, v1, v2, v3);
}
public static void uniform4i(int location, int v0, int v1, int v2, int v3) {
GL20.glUniform4i(location, v0, v1, v2, v3);
}
public static int getAttribLocation(int programId, String name) {
return GL20.glGetAttribLocation(programId, name);
}
public static int getUniformLocation(int programId, String name) {
return GL20.glGetUniformLocation(programId, name);
}
public static void texParameteriv(int texture, int target, int pname, IntBuffer params) {
dsaState.texParameteriv(texture, target, pname, params);
}
public static void copyTexSubImage2D(int destTexture, int target, int i, int i1, int i2, int i3, int i4, int width, int height) {
dsaState.copyTexSubImage2D(destTexture, target, i, i1, i2, i3, i4, width, height);
}
public static void texParameteri(int texture, int target, int pname, int param) {
dsaState.texParameteri(texture, target, pname, param);
}
public static void texParameterf(int texture, int target, int pname, float param) {
dsaState.texParameterf(texture, target, pname, param);
}
public static void textureImage2D(int texture, int target, int level, int internalformat, int width, int height, int border, int format, int type, ByteBuffer pixels) {
dsaState.textureImage2D(texture, target, level, internalformat, width, height, border, format, type, pixels);
}
public static void textureImage2D(int texture, int target, int level, int internalformat, int width, int height, int border, int format, int type, IntBuffer pixels) {
dsaState.textureImage2D(texture, target, level, internalformat, width, height, border, format, type, pixels);
}
public static void textureSubImage2D(int texture, int target, int level, int xoffset, int yoffset, int width, int height, int format, int type, ByteBuffer pixels) {
dsaState.textureSubImage2D(texture, target, level, xoffset, yoffset, width, height, format, type, pixels);
}
public static void textureSubImage2D(int texture, int target, int level, int xoffset, int yoffset, int width, int height, int format, int type, IntBuffer pixels) {
dsaState.textureSubImage2D(texture, target, level, xoffset, yoffset, width, height, format, type, pixels);
}
public static String getProgramInfoLog(int program) {
return GL20.glGetProgramInfoLog(program, GL20.glGetProgrami(program, GL20.GL_INFO_LOG_LENGTH));
}
public static String getShaderInfoLog(int shader) {
return GL20.glGetShaderInfoLog(shader, GL20.glGetShaderi(shader, GL20.GL_INFO_LOG_LENGTH));
}
public static void drawBuffers(int framebuffer, IntBuffer buffers) {
dsaState.drawBuffers(framebuffer, buffers);
}
public static void readBuffer(int framebuffer, int buffer) {
dsaState.readBuffer(framebuffer, buffer);
}
public static String getActiveUniform(int program, int index, int maxLength, IntBuffer sizeType) {
return GL20.glGetActiveUniform(program, index, maxLength, sizeType);
}
public static void readPixels(int x, int y, int width, int height, int format, int type, FloatBuffer pixels) {
GL11.glReadPixels(x, y, width, height, format, type, pixels);
}
public static void bufferData(int target, FloatBuffer data, int usage) {
GL15.glBufferData(target, data, usage);
}
public static int bufferStorage(int target, FloatBuffer data, int usage) {
return dsaState.bufferStorage(target, data, usage);
}
public static void vertexAttrib4f(int index, float v0, float v1, float v2, float v3) {
GL20.glVertexAttrib4f(index, v0, v1, v2, v3);
}
public static void detachShader(int program, int shader) {
GL20.glDetachShader(program, shader);
}
public static void framebufferTexture2D(int fb, int fbtarget, int attachment, int target, int texture, int levels) {
dsaState.framebufferTexture2D(fb, fbtarget, attachment, target, texture, levels);
}
public static int getTexParameteri(int texture, int target, int pname) {
return dsaState.getTexParameteri(texture, target, pname);
}
public static int getTexLevelParameteri(int texture, int level, int pname) {
return dsaState.getTexLevelParameteri(texture, level, pname);
}
public static void bindImageTexture(int unit, int texture, int level, boolean layered, int layer, int access, int format) {
if (GLStateManager.capabilities.OpenGL42) {
GL42.glBindImageTexture(unit, texture, level, layered, layer, access, format);
} else {
EXTShaderImageLoadStore.glBindImageTextureEXT(unit, texture, level, layered, layer, access, format);
}
}
public static int getMaxImageUnits() {
if (GLStateManager.capabilities.OpenGL42) {
return GL11.glGetInteger(GL42.GL_MAX_IMAGE_UNITS);
} else if (GLStateManager.capabilities.GL_EXT_shader_image_load_store) {
return GL11.glGetInteger(EXTShaderImageLoadStore.GL_MAX_IMAGE_UNITS_EXT);
} else {
return 0;
}
}
public static void getProgramiv(int program, int value, IntBuffer storage) {
GL20.glGetProgram(program, value, storage);
}
public static void dispatchCompute(int workX, int workY, int workZ) {
GL43.glDispatchCompute(workX, workY, workZ);
}
public static void dispatchCompute(Vector3i workGroups) {
GL43.glDispatchCompute(workGroups.x, workGroups.y, workGroups.z);
}
public static void memoryBarrier(int barriers) {
if (supportsCompute) {
GL42.glMemoryBarrier(barriers);
}
}
public static boolean supportsBufferBlending() {
return GLStateManager.capabilities.GL_ARB_draw_buffers_blend || GLStateManager.capabilities.OpenGL40;
}
public static void disableBufferBlend(int buffer) {
GL30.glDisablei(GL11.GL_BLEND, buffer);
}
public static void enableBufferBlend(int buffer) {
GL30.glEnablei(GL11.GL_BLEND, buffer);
}
public static void blendFuncSeparatei(int buffer, int srcRGB, int dstRGB, int srcAlpha, int dstAlpha) {
GL40.glBlendFuncSeparatei(buffer, srcRGB, dstRGB, srcAlpha, dstAlpha);
}
public static void bindTextureToUnit(int unit, int texture) {
dsaState.bindTextureToUnit(unit, texture);
}
public static final FloatBuffer PROJECTION_MATRIX_BUFFER = BufferUtils.createFloatBuffer(16);
public static void setupProjectionMatrix(Matrix4f matrix) {
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glPushMatrix();
matrix.get(0, PROJECTION_MATRIX_BUFFER);
GL11.glLoadMatrix(PROJECTION_MATRIX_BUFFER);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
}
public static void restoreProjectionMatrix() {
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glPopMatrix();
GL11.glMatrixMode(GL11.GL_MODELVIEW);
}
public static void blitFramebuffer(int source, int dest, int offsetX, int offsetY, int width, int height, int offsetX2, int offsetY2, int width2, int height2, int bufferChoice, int filter) {
dsaState.blitFramebuffer(source, dest, offsetX, offsetY, width, height, offsetX2, offsetY2, width2, height2, bufferChoice, filter);
}
public static int createFramebuffer() {
return dsaState.createFramebuffer();
}
public static int createTexture(int target) {
return dsaState.createTexture(target);
}
// TODO: Proper notification of compute support
public static boolean supportsCompute() {
try {
return GLStateManager.capabilities.GL_ARB_compute_shader;
} catch(Exception ignored) {
return false;
}
}
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\glsm\TessellatorPrimitiveBuffer.java
|
package com.gtnewhorizons.angelica.glsm;
import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.line.ModelLine;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.primitive.ModelPrimitiveView;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.tri.ModelTriangle;
import com.gtnewhorizon.gtnhlib.client.renderer.vao.VAOManager;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat;
import com.gtnewhorizons.angelica.glsm.recording.AccumulatedPrimitiveDraw;
import org.joml.Matrix4f;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
/**
* Accumulates tessellator primitives (lines, triangles) for a single vertex format during display list compilation.
* Similar to FormatBuffer but handles ModelPrimitiveView instances instead of quads.
* <p>
* Unlike LineBuffer which handles ImmediateModeRecorder.LineVertex (fixed 16-byte: pos+color),
* this handles ModelLine/ModelTriangle from the tessellator with format-optimized vertex size.
* <p>
* Primitives are separated by draw mode (GL_LINES, GL_TRIANGLES) into separate VBOs.
*/
class TessellatorPrimitiveBuffer {
final CapturingTessellator.Flags flags;
// Accumulated primitives separated by type
final List<ModelLine> allLines = new ArrayList<>();
final List<ModelTriangle> allTriangles = new ArrayList<>();
// Ranges for lines
final List<DrawRange> lineMergedRanges = new ArrayList<>();
final List<DrawRange> linePerDrawRanges = new ArrayList<>();
int currentLineVertexOffset = 0;
private int pendingLineStartVertex = -1;
private int pendingLineVertexCount = 0;
private Matrix4f pendingLineTransform = null;
private int pendingLineCommandIndex = -1;
private int pendingLineStateGen = -1;
// Ranges for triangles
final List<DrawRange> triangleMergedRanges = new ArrayList<>();
final List<DrawRange> trianglePerDrawRanges = new ArrayList<>();
int currentTriangleVertexOffset = 0;
private int pendingTriangleStartVertex = -1;
private int pendingTriangleVertexCount = 0;
private Matrix4f pendingTriangleTransform = null;
private int pendingTriangleCommandIndex = -1;
private int pendingTriangleStateGen = -1;
TessellatorPrimitiveBuffer(CapturingTessellator.Flags flags) {
this.flags = flags;
}
/**
* Add a primitive draw to this buffer.
* Separates lines and triangles, tracking ranges for both merged and per-draw paths.
*/
void addDraw(AccumulatedPrimitiveDraw draw) {
final List<ModelPrimitiveView> primitives = draw.primitives;
final int size = primitives.size();
// Single pass: count and collect primitives by type
int lineCount = 0;
int triangleCount = 0;
for (int i = 0; i < size; i++) {
final ModelPrimitiveView prim = primitives.get(i);
if (prim instanceof ModelLine ml) {
allLines.add(ml);
lineCount++;
} else if (prim instanceof ModelTriangle mt) {
allTriangles.add(mt);
triangleCount++;
}
}
// Process lines
if (lineCount > 0) {
final int lineVertexCount = lineCount * 2; // 2 vertices per line
linePerDrawRanges.add(new DrawRange(currentLineVertexOffset, lineVertexCount, draw.transform, draw.commandIndex));
// Merge logic for optimized path:
// - same transform
// - same stateGeneration = no state commands (draw barriers) between draws
boolean canMerge = pendingLineTransform != null
&& pendingLineTransform.equals(draw.transform)
&& pendingLineStateGen == draw.stateGeneration;
if (canMerge) {
pendingLineVertexCount += lineVertexCount;
} else {
flushPendingLineRange();
pendingLineStartVertex = currentLineVertexOffset;
pendingLineVertexCount = lineVertexCount;
pendingLineTransform = new Matrix4f(draw.transform);
pendingLineCommandIndex = draw.commandIndex;
pendingLineStateGen = draw.stateGeneration;
}
currentLineVertexOffset += lineVertexCount;
}
// Process triangles
if (triangleCount > 0) {
final int triangleVertexCount = triangleCount * 3; // 3 vertices per triangle
trianglePerDrawRanges.add(new DrawRange(currentTriangleVertexOffset, triangleVertexCount, draw.transform, draw.commandIndex));
// Merge logic for optimized path:
// - same transform
// - same stateGeneration = no state commands (draw barriers) between draws
boolean canMerge = pendingTriangleTransform != null
&& pendingTriangleTransform.equals(draw.transform)
&& pendingTriangleStateGen == draw.stateGeneration;
if (canMerge) {
pendingTriangleVertexCount += triangleVertexCount;
} else {
flushPendingTriangleRange();
pendingTriangleStartVertex = currentTriangleVertexOffset;
pendingTriangleVertexCount = triangleVertexCount;
pendingTriangleTransform = new Matrix4f(draw.transform);
pendingTriangleCommandIndex = draw.commandIndex;
pendingTriangleStateGen = draw.stateGeneration;
}
currentTriangleVertexOffset += triangleVertexCount;
}
}
private void flushPendingLineRange() {
if (pendingLineTransform != null) {
lineMergedRanges.add(new DrawRange(pendingLineStartVertex, pendingLineVertexCount, pendingLineTransform, pendingLineCommandIndex));
pendingLineTransform = null;
pendingLineStateGen = -1;
}
}
private void flushPendingTriangleRange() {
if (pendingTriangleTransform != null) {
triangleMergedRanges.add(new DrawRange(pendingTriangleStartVertex, pendingTriangleVertexCount, pendingTriangleTransform, pendingTriangleCommandIndex));
pendingTriangleTransform = null;
pendingTriangleStateGen = -1;
}
}
/**
* Compile all accumulated primitives into VBOs using optimal vertex format.
* @return The compiled buffers with separate VBOs for lines and triangles, or null if empty
*/
CompiledPrimitiveBuffers finish() {
flushPendingLineRange();
flushPendingTriangleRange();
if (allLines.isEmpty() && allTriangles.isEmpty()) {
return null;
}
// Use optimal format based on flags (same logic as quads)
final VertexFormat format = DisplayListManager.selectOptimalFormat(flags);
final VertexBuffer lineVbo = allLines.isEmpty() ? null : compileLinesToVBO(format);
final VertexBuffer triangleVbo = allTriangles.isEmpty() ? null : compileTrianglesToVBO(format);
return new CompiledPrimitiveBuffers(
flags,
lineVbo,
lineMergedRanges.toArray(new DrawRange[0]),
linePerDrawRanges.toArray(new DrawRange[0]),
triangleVbo,
triangleMergedRanges.toArray(new DrawRange[0]),
trianglePerDrawRanges.toArray(new DrawRange[0])
);
}
private VertexBuffer compileLinesToVBO(VertexFormat format) {
final int vertexSize = format.getVertexSize();
final int size = allLines.size();
final ByteBuffer buffer = BufferUtils.createByteBuffer(vertexSize * size * 2);
for (int i = 0; i < size; i++) {
writePrimitiveToBuffer(allLines.get(i), buffer);
}
buffer.flip();
final VertexBuffer vbo = VAOManager.createVAO(format, GL11.GL_LINES);
vbo.upload(buffer);
return vbo;
}
private VertexBuffer compileTrianglesToVBO(VertexFormat format) {
final int vertexSize = format.getVertexSize();
final int size = allTriangles.size();
final ByteBuffer buffer = BufferUtils.createByteBuffer(vertexSize * size * 3);
for (int i = 0; i < size; i++) {
writePrimitiveToBuffer(allTriangles.get(i), buffer);
}
buffer.flip();
final VertexBuffer vbo = VAOManager.createVAO(format, GL11.GL_TRIANGLES);
vbo.upload(buffer);
return vbo;
}
/**
* Write a primitive's vertices to the buffer using the format specified by flags.
* Only writes attributes that are present in the format.
*/
private void writePrimitiveToBuffer(ModelPrimitiveView prim, ByteBuffer buffer) {
final int vertexCount = prim.getVertexCount();
final boolean hasTexture = flags.hasTexture;
final boolean hasBrightness = flags.hasBrightness;
final boolean hasColor = flags.hasColor;
final boolean hasNormals = flags.hasNormals;
for (int i = 0; i < vertexCount; i++) {
// Position (always present) - 12 bytes
buffer.putFloat(prim.getX(i));
buffer.putFloat(prim.getY(i));
buffer.putFloat(prim.getZ(i));
// Color (4 bytes, ABGR) - if present
if (hasColor) {
buffer.putInt(prim.getColor(i));
}
// Texture (2 floats = 8 bytes) - if present
if (hasTexture) {
buffer.putFloat(prim.getTexU(i));
buffer.putFloat(prim.getTexV(i));
}
// Light/Brightness (4 bytes, packed) - if present
if (hasBrightness) {
buffer.putInt(prim.getLight(i));
}
// Normal (4 bytes, packed) - if present
if (hasNormals) {
buffer.putInt(prim.getForgeNormal(i));
}
}
}
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\glsm\ThreadedBlockData.java
|
package com.gtnewhorizons.angelica.glsm;
import net.minecraft.block.Block;
/**
* Used to store the block bounds fields in a thread-safe manner, as instance fields don't work correctly
* on multiple threads.
*/
public class ThreadedBlockData {
public double minX, minY, minZ, maxX, maxY, maxZ;
public ThreadedBlockData() {}
public ThreadedBlockData(ThreadedBlockData other) {
this.minX = other.minX;
this.minY = other.minY;
this.minZ = other.minZ;
this.maxX = other.maxX;
this.maxY = other.maxY;
this.maxZ = other.maxZ;
}
public static ThreadedBlockData get(Block block) {
return ((Getter)block).angelica$getThreadData();
}
public interface Getter {
ThreadedBlockData angelica$getThreadData();
}
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\glsm\TransformOptimizer.java
|
package com.gtnewhorizons.angelica.glsm;
import com.gtnewhorizons.angelica.glsm.recording.commands.DisplayListCommand;
import com.gtnewhorizons.angelica.glsm.recording.commands.MultMatrixCmd;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.joml.Matrix4f;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.List;
/**
* Helper class for tracking and collapsing matrix transforms during optimization.
* Implements the transform accumulation and emission strategy:
* <ul>
* <li>accumulated: total relative transform (what GL matrix should be)</li>
* <li>lastEmitted: what we've emitted (what GL matrix is)</li>
* <li>stack: saved accumulated values at Push points</li>
* </ul>
*/
class TransformOptimizer {
private static final Logger LOGGER = LogManager.getLogger("TransformOptimizer");
private final Matrix4f accumulated = new Matrix4f(); // Current accumulated transform
private final Matrix4f lastEmitted = new Matrix4f(); // Last emitted transform
private final Deque<Matrix4f> stack = new ArrayDeque<>(); // For Push/Pop
private final int listId; // For logging
private boolean absoluteMatrixFlag = false; // True after LoadMatrix, cleared by LoadIdentity emit
TransformOptimizer(int listId) {
this.listId = listId;
accumulated.identity();
lastEmitted.identity();
}
Matrix4f getAccumulated() {
return accumulated;
}
void loadIdentity() {
accumulated.identity();
}
void pushTransform() {
stack.push(new Matrix4f(accumulated));
}
void popTransform() {
if (!stack.isEmpty()) {
final Matrix4f popped = stack.pop();
accumulated.set(popped);
// After Pop, GL state is restored to the pushed value so lastEmitted should also reflect this
lastEmitted.set(accumulated);
} else {
LOGGER.warn("[TransformOptimizer] list={} Pop with empty stack - resetting to identity", listId);
accumulated.identity();
lastEmitted.identity();
}
}
boolean isIdentity() {
return DisplayListManager.isIdentity(accumulated);
}
/**
* Check if there's a pending transform that hasn't been emitted yet.
*/
boolean hasPendingTransform() {
return !accumulated.equals(lastEmitted);
}
/**
* Emit a MultMatrix command if accumulated differs from lastEmitted.
* Updates lastEmitted to match accumulated after emission.
*/
void emitPendingTransform(List<DisplayListCommand> output) {
if (!accumulated.equals(lastEmitted)) {
emitTransformTo(output, accumulated);
}
}
/**
* Emit a MultMatrix command to make GL state match a target transform.
* Used when a draw expects a specific transform that may differ from accumulated.
* Updates lastEmitted to match target after emission.
*
* @param output The command list to emit to
* @param target The target transform to reach
*/
void emitTransformTo(List<DisplayListCommand> output, Matrix4f target) {
if (target.equals(lastEmitted)) {
// Already at target - nothing to emit
return;
}
// Calculate delta: what we need to multiply to go from lastEmitted to target
// delta = inverse(lastEmitted) * target
// But for simplicity, if lastEmitted is identity, just emit target
if (DisplayListManager.isIdentity(lastEmitted)) {
// Simple case: just emit target
output.add(MultMatrixCmd.create(target));
} else {
// Need to emit delta: inv(lastEmitted) * target
final Matrix4f delta = new Matrix4f(lastEmitted).invert().mul(target);
output.add(MultMatrixCmd.create(delta));
}
lastEmitted.set(target);
}
/**
* Check if a draw's expected transform differs from what we've emitted.
*/
boolean needsTransformForDraw(Matrix4f drawTransform) {
return !drawTransform.equals(lastEmitted);
}
/**
* Mark that the GL matrix is at an absolute value (after LoadMatrix).
* Subsequent LoadIdentity commands must be emitted to actually reset GL to identity.
*/
void markAbsoluteMatrix() {
absoluteMatrixFlag = true;
}
/**
* Check if the GL matrix is at an absolute value and clear the flag.
* Used to determine if LoadIdentity needs to emit.
* @return true if LoadMatrix was called and not yet reset by LoadIdentity
*/
boolean checkAndClearAbsoluteMatrix() {
boolean was = absoluteMatrixFlag;
absoluteMatrixFlag = false;
return was;
}
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\glsm\Vendor.java
|
package com.gtnewhorizons.angelica.glsm;
/// Matches
public enum Vendor {
AMD("amd"),
INTEL("intel"),
MESA("mesa"),
NVIDIA("nvidia"),
UNKNOWN("");
final String[] names;
Vendor(String... names) {
this.names = names;
}
public static Vendor getVendor(String vendorString) {
for (var v : values()) {
for (var name : v.names) {
if (vendorString.contains(name)) return v;
}
}
// Shouldn't be needed as "" matches everything, but sanity checks good.
return UNKNOWN;
}
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\helpers\LoadControllerHelper.java
|
package com.gtnewhorizons.angelica.helpers;
import com.google.common.collect.ListMultimap;
import com.google.common.eventbus.EventBus;
import cpw.mods.fml.common.LoadController;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.MetadataCollection;
import cpw.mods.fml.common.ModContainer;
import cpw.mods.fml.common.ModMetadata;
import cpw.mods.fml.common.ObfuscationReflectionHelper;
import cpw.mods.fml.common.versioning.ArtifactVersion;
import cpw.mods.fml.common.versioning.VersionRange;
import java.io.File;
import java.security.cert.Certificate;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
public class LoadControllerHelper {
private static LoadController loadController;
private static ListMultimap<String, ModContainer> packageOwners;
static {
loadController = ObfuscationReflectionHelper.getPrivateValue(Loader.class, Loader.instance(), "modController");
packageOwners = ObfuscationReflectionHelper.getPrivateValue(LoadController.class, loadController, "packageOwners");
}
private static ConcurrentHashMap<Class<?>, ModContainer> owningModForClass = new ConcurrentHashMap<>();
public static ModContainer getOwningMod(Class<?> clz) {
ModContainer container = owningModForClass.computeIfAbsent(clz, c -> {
if(clz.getName().startsWith("net.minecraft."))
return Loader.instance().getMinecraftModContainer();
int lastDot = clz.getName().lastIndexOf('.');
if(lastDot == -1)
return NONE;
String pkgName = clz.getName().substring(0, lastDot);
if(packageOwners.containsKey(pkgName))
return packageOwners.get(pkgName).get(0);
else
return NONE;
});
if(container == NONE)
return null;
return container;
}
private static final ModContainer NONE = new ModContainer() {
@Override
public String getModId() {
return null;
}
@Override
public String getName() {
return null;
}
@Override
public String getVersion() {
return null;
}
@Override
public File getSource() {
return null;
}
@Override
public ModMetadata getMetadata() {
return null;
}
@Override
public void bindMetadata(MetadataCollection mc) {
}
@Override
public void setEnabledState(boolean enabled) {
}
@Override
public Set<ArtifactVersion> getRequirements() {
return null;
}
@Override
public List<ArtifactVersion> getDependencies() {
return null;
}
@Override
public List<ArtifactVersion> getDependants() {
return null;
}
@Override
public String getSortingRules() {
return null;
}
@Override
public boolean registerBus(EventBus bus, LoadController controller) {
return false;
}
@Override
public boolean matches(Object mod) {
return false;
}
@Override
public Object getMod() {
return null;
}
@Override
public ArtifactVersion getProcessedVersion() {
return null;
}
@Override
public boolean isImmutable() {
return false;
}
@Override
public String getDisplayVersion() {
return null;
}
@Override
public VersionRange acceptableMinecraftVersionRange() {
return null;
}
@Override
public Certificate getSigningCertificate() {
return null;
}
@Override
public Map<String, String> getCustomModProperties() {
return null;
}
@Override
public Class<?> getCustomResourcePackClass() {
return null;
}
@Override
public Map<String, String> getSharedModDescriptor() {
return null;
}
@Override
public Disableable canBeDisabled() {
return null;
}
@Override
public String getGuiClassName() {
return null;
}
@Override
public List<String> getOwnedPackages() {
return null;
}
};
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\hudcaching\HUDCaching.java
|
package com.gtnewhorizons.angelica.hudcaching;
import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator;
import com.gtnewhorizon.gtnhlib.client.renderer.TessellatorManager;
import com.gtnewhorizon.gtnhlib.client.renderer.postprocessing.CustomFramebuffer;
import com.gtnewhorizon.gtnhlib.client.renderer.postprocessing.SharedDepthFramebuffer;
import com.gtnewhorizon.gtnhlib.client.renderer.vao.VertexArrayBuffer;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat;
import com.gtnewhorizons.angelica.compat.ModStatus;
import com.gtnewhorizons.angelica.compat.holoinventory.HoloInventoryReflectionCompat;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.mixins.interfaces.GuiIngameAccessor;
import com.gtnewhorizons.angelica.mixins.interfaces.GuiIngameForgeAccessor;
import com.gtnewhorizons.angelica.mixins.interfaces.RenderGameOverlayEventAccessor;
import com.kentington.thaumichorizons.common.ThaumicHorizons;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.gui.GuiIngame;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.client.renderer.EntityRenderer;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraftforge.client.GuiIngameForge;
import net.minecraftforge.client.event.RenderGameOverlayEvent;
import org.lwjgl.opengl.GL11;
import thaumcraft.common.Thaumcraft;
import xaero.common.core.XaeroMinimapCore;
// See LICENSE-HUDCaching.md for license information.
public class HUDCaching {
private static final Minecraft mc = Minecraft.getMinecraft();
public static SharedDepthFramebuffer framebuffer;
private static boolean dirty = true;
private static long nextHudRefresh;
private static VertexBuffer quadVAO;
private static float quadWidth;
private static float quadHeight;
public static boolean renderingCacheOverride;
/*
* Some HUD features cause problems/inaccuracies when being rendered into cache.
* We capture those and render them later
*/
// Vignette texture has no alpha
public static boolean renderVignetteCaptured;
// Helmet & portal are chances other mods render vignette
// For example Thaumcraft renders warp effect during this
public static boolean renderHelmetCaptured;
public static float renderPortalCapturedTicks;
// Crosshairs need to be blended with the scene
public static boolean renderCrosshairsCaptured;
private final static RenderGameOverlayEvent fakeTextEvent = new RenderGameOverlayEvent.Text(new RenderGameOverlayEvent(0, null, 0, 0), null, null);
private final static RenderGameOverlayEvent.Post fakePostEvent = new RenderGameOverlayEvent.Post(new RenderGameOverlayEvent(0, null, 0, 0), RenderGameOverlayEvent.ElementType.HELMET);
public static void init() {
framebuffer = new SharedDepthFramebuffer(CustomFramebuffer.STENCIL_BUFFER);
}
public static void renderCachedHud(EntityRenderer renderer, GuiIngame ingame, float partialTicks, boolean hasScreen, int mouseX, int mouseY) {
if (ModStatus.isXaerosMinimapLoaded && ingame instanceof GuiIngameForge) {
// this used to be called by asming into renderGameOverlay, but we removed it
XaeroMinimapCore.beforeIngameGuiRender(partialTicks);
}
if (!OpenGlHelper.isFramebufferEnabled()) {
ingame.renderGameOverlay(partialTicks, hasScreen, mouseX, mouseY);
return;
}
if (System.currentTimeMillis() > nextHudRefresh) {
dirty = true;
}
if (dirty) {
dirty = false;
nextHudRefresh = System.currentTimeMillis() + (1000 / AngelicaConfig.hudCachingFPS);
if (framebuffer.framebufferWidth != mc.displayWidth || framebuffer.framebufferHeight != mc.displayHeight) {
framebuffer.createBindFramebuffer(mc.displayWidth, mc.displayHeight);
} else {
framebuffer.clearBindFramebuffer();
}
renderingCacheOverride = true;
ingame.renderGameOverlay(partialTicks, hasScreen, mouseX, mouseY);
renderingCacheOverride = false;
mc.getFramebuffer().bindFramebuffer(false);
} else {
renderer.setupOverlayRendering();
}
ScaledResolution resolution = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight);
int width = resolution.getScaledWidth();
int height = resolution.getScaledHeight();
GLStateManager.enableBlend();
// reset the color that may be applied by some items
GLStateManager.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
// render bits that were captured when rendering into cache
GuiIngameAccessor gui = (GuiIngameAccessor) ingame;
if (renderVignetteCaptured) {
gui.callRenderVignette(mc.thePlayer.getBrightness(partialTicks), width, height);
} else {
GLStateManager.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, 1, 0);
}
if (ingame instanceof GuiIngameForge) {
GuiIngameForgeAccessor guiForge = ((GuiIngameForgeAccessor) ingame);
if (renderHelmetCaptured) {
guiForge.callRenderHelmet(resolution, partialTicks, hasScreen, mouseX, mouseY);
if (ModStatus.isHoloInventoryLoaded) {
HoloInventoryReflectionCompat.setAngelicaOverride(false);
// only settings the partial ticks as mouseX and mouseY are not used in renderEvent
((RenderGameOverlayEventAccessor) fakePostEvent).setPartialTicks(partialTicks);
HoloInventoryReflectionCompat.renderEvent(fakePostEvent);
}
}
if (renderPortalCapturedTicks > 0) {
guiForge.callRenderPortal(width, height, partialTicks);
}
if (renderCrosshairsCaptured) {
if (ModStatus.isXaerosMinimapLoaded) {
// this fixes the crosshair going invisible when no lines are being drawn under the minimap
GLStateManager.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
}
guiForge.callRenderCrosshairs(width, height);
}
if (ModStatus.isThaumcraftLoaded || ModStatus.isThaumicHorizonsLoaded) {
((RenderGameOverlayEventAccessor) fakeTextEvent).setPartialTicks(partialTicks);
((RenderGameOverlayEventAccessor) fakeTextEvent).setResolution(resolution);
((RenderGameOverlayEventAccessor) fakeTextEvent).setMouseX(mouseX);
((RenderGameOverlayEventAccessor) fakeTextEvent).setMouseY(mouseY);
if (ModStatus.isThaumcraftLoaded) {
Thaumcraft.instance.renderEventHandler.renderOverlay(fakeTextEvent);
}
if (ModStatus.isThaumicHorizonsLoaded) {
ThaumicHorizons.instance.renderEventHandler.renderOverlay(fakeTextEvent);
}
}
} else {
if (renderHelmetCaptured) {
gui.callRenderPumpkinBlur(width, height);
}
if (renderPortalCapturedTicks > 0) {
gui.callRenderPortal(renderPortalCapturedTicks, width, height);
}
}
// render cached frame
GLStateManager.enableBlend();
GLStateManager.tryBlendFuncSeparate(GL11.GL_ONE, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ONE_MINUS_SRC_ALPHA);
GLStateManager.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
framebuffer.bindFramebufferTexture();
drawTexturedRect((float) resolution.getScaledWidth_double(), (float) resolution.getScaledHeight_double());
GLStateManager.tryBlendFuncSeparate(GL11.GL_ONE, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO);
mc.getTextureManager().bindTexture(Gui.icons);
}
/**
* We are skipping certain render calls when rendering into cache,
* however, we cannot skip the GL state changes. This will fix
* the state before we start rendering
*/
public static void fixGLStateBeforeRenderingCache() {
GLStateManager.glDepthMask(true);
GLStateManager.enableDepthTest();
GLStateManager.enableAlphaTest();
GLStateManager.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO);
GLStateManager.disableBlend();
}
private static void drawTexturedRect(float width, float height) {
if (quadWidth != width || quadHeight != height) {
quadWidth = width;
quadHeight = height;
rebuildVAO(width, height);
}
GLStateManager.disableDepthTest();
GLStateManager.enableTexture();
quadVAO.render();
GLStateManager.enableDepthTest();
}
private static void rebuildVAO(float width, float height) {
final CapturingTessellator tessellator = TessellatorManager.startCapturingAndGet();
tessellator.startDrawingQuads();
tessellator.addVertexWithUV(0, height, 0.0, 0, 0);
tessellator.addVertexWithUV(width, height, 0.0, 1, 0);
tessellator.addVertexWithUV(width, 0, 0.0, 1, 1);
tessellator.addVertexWithUV(0, 0, 0.0, 0, 1);
tessellator.draw();
quadVAO = TessellatorManager.stopCapturingToVAO(quadVAO, DefaultVertexFormat.POSITION_TEXTURE);
}
public static void disableHoloInventory() {
if (ModStatus.isHoloInventoryLoaded) {
HoloInventoryReflectionCompat.setAngelicaOverride(true);
}
}
@SuppressWarnings("unused") // called via ASM
public static class HUDCachingHooks {
public static boolean shouldReturnEarly() {
return renderingCacheOverride;
}
}
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\loading\AngelicaTweaker.java
|
package com.gtnewhorizons.angelica.loading;
import com.gtnewhorizon.gtnhlib.config.ConfigException;
import com.gtnewhorizon.gtnhlib.config.ConfigurationManager;
import com.gtnewhorizon.gtnhmixins.IEarlyMixinLoader;
import com.gtnewhorizon.gtnhmixins.builders.IMixins;
import com.gtnewhorizon.gtnhmixins.builders.ITransformers;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import com.gtnewhorizons.angelica.config.CompatConfig;
import com.gtnewhorizons.angelica.config.FontConfig;
import com.gtnewhorizons.angelica.mixins.Mixins;
import com.gtnewhorizons.angelica.loading.fml.compat.CompatHandlers;
import cpw.mods.fml.relauncher.FMLLaunchHandler;
import cpw.mods.fml.relauncher.IFMLLoadingPlugin;
import jss.notfine.asm.AsmTransformers;
import jss.notfine.asm.mappings.Namer;
import jss.notfine.config.MCPatcherForgeConfig;
import jss.notfine.config.NotFineConfig;
import net.minecraft.launchwrapper.Launch;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.LoggerConfig;
import org.spongepowered.asm.launch.GlobalProperties;
import org.spongepowered.asm.service.mojang.MixinServiceLaunchWrapper;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
// ================== Important ==================
// Due to a bug caused by this class both implementing
// IFMLLoadingPlugin and IEarlyMixinLoader,
// the IClassTransformer registered in this class
// will not respect the sorting index defined.
// They will instead use default index 0 which means they will see
// obfuscated mappings and not SRG mappings when running outside of dev env.
// ===============================================
//@IFMLLoadingPlugin.SortingIndex(Integer.MAX_VALUE - 5)
@IFMLLoadingPlugin.MCVersion("1.7.10")
@IFMLLoadingPlugin.TransformerExclusions({
"jss.notfine.asm",
"com.gtnewhorizons.angelica.loading",
"com.gtnewhorizons.angelica.glsm.GLStateManager"})
public class AngelicaTweaker implements IFMLLoadingPlugin, IEarlyMixinLoader {
private static Boolean OBF_ENV;
public static final Logger LOGGER = LogManager.getLogger("Angelica");
private String[] transformerClasses;
public AngelicaTweaker() {
try {
// Angelica Config
ConfigurationManager.registerConfig(AngelicaConfig.class);
ConfigurationManager.registerConfig(CompatConfig.class);
ConfigurationManager.registerConfig(FontConfig.class);
MCPatcherForgeConfig.registerConfig();
final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
final Configuration config = ctx.getConfiguration();
final LoggerConfig loggerConfig = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME);
if (AngelicaConfig.enableDebugLogging) {
loggerConfig.setLevel(Level.DEBUG);
}
ctx.updateLoggers();
// Debug features
AngelicaConfig.enableTestBlocks = Boolean.getBoolean("angelica.enableTestBlocks");
} catch (ConfigException e) {
throw new RuntimeException(e);
}
verifyDependencies();
}
private static void verifyDependencies() {
if (AngelicaTweaker.class.getResource("/it/unimi/dsi/fastutil/ints/Int2ObjectMap.class") == null) {
throw new RuntimeException("Missing dependency: Angelica requires GTNHLib 0.2.1 or newer! Download: https://modrinth.com/mod/gtnhlib");
}
}
@Override
public String[] getASMTransformerClass() {
if (transformerClasses == null) {
final List<String> transformers = new ArrayList<>();
transformers.addAll(CompatHandlers.getTransformers());
// Add NotFine transformers
final List<String> notFineTransformers = Arrays.asList(ITransformers.getTransformers(AsmTransformers.class));
if (!notFineTransformers.isEmpty()) Namer.initNames();
transformers.addAll(notFineTransformers);
transformerClasses = transformers.toArray(new String[0]);
}
return transformerClasses;
}
@Override
public String getModContainerClass() {
return null;
}
@Override
public String getSetupClass() {
return null;
}
@Override
public void injectData(Map<String, Object> data) {
OBF_ENV = (Boolean) data.get("runtimeDeobfuscationEnabled");
// Directly add this to the MixinServiceLaunchWrapper tweaker's list of Tweak Classes
final List<String> tweaks = GlobalProperties.get(MixinServiceLaunchWrapper.BLACKBOARD_KEY_TWEAKCLASSES);
if (tweaks != null) {
tweaks.add("com.gtnewhorizons.angelica.loading.fml.tweakers.IncompatibleModsDisablerTweaker");
if (AngelicaConfig.enableHudCaching) {
tweaks.add("com.gtnewhorizons.angelica.loading.fml.tweakers.XaerosTransformerDisablerTweaker");
}
if (FMLLaunchHandler.side().isClient()) {
// We register ITweakers that will run last in order to register
// specific IClassTransformers that will run last in the transformer chain.
// If we were to register them normally in getASMTransformerClass(),
// they would be sorted at index 0 which we do not want.
boolean rfbLoaded = Launch.blackboard.getOrDefault("angelica.rfbPluginLoaded", Boolean.FALSE) == Boolean.TRUE;
if (!rfbLoaded) {
tweaks.add("com.gtnewhorizons.angelica.loading.fml.tweakers.AngelicaLateTweaker");
if (AngelicaConfig.enableSodium) {
tweaks.add("com.gtnewhorizons.angelica.loading.fml.tweakers.SodiumLateTweaker");
}
}
}
}
}
@Override
public String getAccessTransformerClass() {
return null;
}
@Override
public String getMixinConfig() {
return "mixins.angelica.early.json";
}
@Override
public List<String> getMixins(Set<String> loadedCoreMods) {
NotFineConfig.loadSettings();
//This may be possible to handle differently or fix.
if (loadedCoreMods.contains("cofh.asm.LoadingPlugin")) {
MCPatcherForgeConfig.ExtendedHD.hdFont = false;
}
return IMixins.getEarlyMixins(Mixins.class, loadedCoreMods);
}
/**
* Returns true if we are in an obfuscated environment, returns false in dev environment.
*/
public static boolean isObfEnv() {
if (OBF_ENV == null) {
throw new IllegalStateException("Obfuscation state has been accessed too early!");
}
return OBF_ENV;
}
/**
* Returns the appropriate name according to current environment's obfuscation
*/
public static String obf(String deobf, String obf) {
if (OBF_ENV == null) {
throw new IllegalStateException("Obfuscation state has been accessed too early!");
}
if (OBF_ENV) {
return obf;
}
return deobf;
}
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\mixins\Mixins.java
|
package com.gtnewhorizons.angelica.mixins;
import com.gtnewhorizon.gtnhmixins.builders.IMixins;
import com.gtnewhorizon.gtnhmixins.builders.MixinBuilder;
import com.gtnewhorizons.angelica.AngelicaMod;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import com.gtnewhorizons.angelica.config.CompatConfig;
import jss.notfine.config.MCPatcherForgeConfig;
import jss.notfine.config.NotFineConfig;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import java.util.ArrayList;
import java.util.List;
@Getter
@RequiredArgsConstructor
public enum Mixins implements IMixins {
ANGELICA_STARTUP(new MixinBuilder()
.setPhase(Phase.EARLY)
.addClientMixins(
"angelica.startup.MixinInitGLStateManager"
)
),
ANGELICA(new MixinBuilder()
.setPhase(Phase.EARLY)
.addClientMixins(
"angelica.MixinActiveRenderInfo"
, "angelica.MixinEntityRenderer"
, "angelica.MixinGameSettings"
, "angelica.MixinMinecraft"
, "angelica.MixinMinecraftServer"
, "angelica.optimizations.MixinRendererLivingEntity"
, "angelica.MixinFMLClientHandler"
, "angelica.bugfixes.MixinRenderGlobal_DestroyBlock"
, "angelica.glsm.MixinSplashProgressCaching"
)
),
ANGELICA_VBO_CLOUDS(
new MixinBuilder()
.setApplyIf(() -> AngelicaConfig.enableVBOClouds)
.setPhase(Phase.EARLY)
.addClientMixins("angelica.vbo.MixinRenderGlobal")
),
ANGELICA_FONT_RENDERER(new MixinBuilder()
.setPhase(Phase.EARLY)
.setApplyIf(() -> AngelicaConfig.enableFontRenderer)
.addClientMixins(
"angelica.fontrenderer.MixinGuiIngameForge"
, "angelica.fontrenderer.MixinFontRenderer"
, "angelica.fontrenderer.MixinMCResourceAccessor"
)
),
ANGELICA_ENABLE_DEBUG(new MixinBuilder()
.setPhase(Phase.EARLY)
.setApplyIf(() -> AngelicaMod.lwjglDebug)
.addClientMixins(
"angelica.debug.MixinProfiler"
, "angelica.debug.MixinSplashProgress"
, "angelica.debug.MixinTextureManager"
)
),
ANGELICA_DYNAMIC_LIGHTS(new MixinBuilder()
.setPhase(Phase.EARLY)
.setApplyIf(() -> AngelicaConfig.enableDynamicLights)
.addClientMixins(
"angelica.dynamiclights.MixinEntityRenderer"
, "angelica.dynamiclights.MixinEntity"
, "angelica.dynamiclights.MixinWorld"
, "angelica.dynamiclights.MixinItemRenderer"
)
),
ANGELICA_FIX_BLOCK_CRACK(
new MixinBuilder("Block corners and edges between chunks might have \"cracks\" in them. This option fixes it")
.setPhase(Phase.EARLY)
.addClientMixins("angelica.bugfixes.MixinRenderBlocks_CrackFix")
.addExcludedMod(TargetedMod.FALSETWEAKS)
.setApplyIf(() -> AngelicaConfig.fixBlockCrack)),
ANGELICA_FIX_FLUID_RENDERER_CHECKING_BLOCK_AGAIN(
new MixinBuilder("Fix RenderBlockFluid reading the block type from the world access multiple times")
.setPhase(Phase.EARLY)
.addClientMixins("angelica.bugfixes.MixinRenderBlockFluid")
.setApplyIf(() -> AngelicaConfig.fixFluidRendererCheckingBlockAgain)),
ANGELICA_LIMIT_DROPPED_ITEM_ENTITIES(new MixinBuilder()
.setPhase(Phase.EARLY)
.addClientMixins("angelica.optimizations.MixinRenderGlobal_ItemRenderDist")
.setApplyIf(() -> AngelicaConfig.dynamicItemRenderDistance)),
ANGELICA_ITEM_RENDERER_OPTIMIZATION(new MixinBuilder("Optimizes in-world item rendering")
.setPhase(Phase.EARLY)
.addClientMixins("angelica.itemrenderer.MixinItemRenderer")
.setApplyIf(() -> AngelicaConfig.optimizeInWorldItemRendering)),
ANGELICA_OPTIMIZE_GLALLOCATION(new MixinBuilder("Replace HashMap with fastutil Int2IntMap in GLAllocation")
.setPhase(Phase.EARLY)
.addClientMixins("angelica.optimizations.MixinGLAllocation")),
// Not compatible with the lwjgl debug callbacks, so disable if that's enabled
ARCHAIC_SPLASH(new MixinBuilder()
.setPhase(Phase.EARLY)
.setApplyIf(() -> AngelicaConfig.showSplashMemoryBar && !AngelicaMod.lwjglDebug)
.addClientMixins(
"angelica.archaic.MixinSplashProgress$3",
"angelica.archaic.AccessorSplashProgress"
)
),
ARCHAIC_CORE(new MixinBuilder()
.addExcludedMod(TargetedMod.ARCHAICFIX)
.setPhase(Phase.EARLY)
.addClientMixins(
"angelica.archaic.MixinBlockFence"
, "angelica.archaic.MixinFMLClientHandler"
, "angelica.archaic.MixinGuiIngameForge"
, "angelica.archaic.MixinNetHandlerPlayClient"
, "angelica.archaic.MixinThreadDownloadImageData"
)
),
IRIS_STARTUP(new MixinBuilder()
.setPhase(Phase.EARLY)
.setApplyIf(() -> AngelicaConfig.enableIris)
.addClientMixins(
"shaders.startup.MixinGameSettings"
, "shaders.startup.MixinMinecraft"
, "shaders.startup.MixinInitRenderer"
, "shaders.startup.MixinAbstractTexture"
, "shaders.startup.MixinTextureAtlasSprite"
, "shaders.startup.MixinTextureMap"
)
),
SODIUM(new MixinBuilder()
.setPhase(Phase.EARLY)
.setApplyIf(() -> AngelicaConfig.enableSodium)
.addClientMixins(
"sodium.MixinBlock"
, "sodium.MixinBlockFluidBase"
, "sodium.AccessorBiomeColorEvent"
, "sodium.MixinBiomeGenBase"
, "sodium.MixinChunk"
, "sodium.MixinChunkProviderServer"
, "sodium.MixinClientRegistry"
, "sodium.MixinEntity_RenderDist"
, "sodium.MixinEntityItem_RenderDist"
, "sodium.MixinRenderManager"
, "sodium.MixinEntityRenderer"
, "sodium.MixinFMLClientHandler"
, "sodium.MixinForgeHooksClient"
, "sodium.MixinGameSettings"
, "sodium.MixinFrustrum"
, "sodium.MixinMinecraft"
, "sodium.MixinRenderBlocks"
, "sodium.MixinRenderGlobal"
, "sodium.MixinWorldClient"
, "sodium.MixinTileEntity"
, "sodium.MixinTileEntityMobSpawner"
, "sodium.MixinEffectRenderer"
, "sodium.MixinTileEntityRendererDispatcher"
, "sodium.MixinLongHashMap"
, "sodium.MixinRenderingRegistry"
, "sodium.MixinPlayerManager"
)
),
IRIS_SHADERS(new MixinBuilder()
.setPhase(Phase.EARLY)
.setApplyIf(() -> AngelicaConfig.enableIris)
.addClientMixins(
"shaders.MixinEntityRenderer"
, "shaders.MixinGuiIngameForge"
, "shaders.MixinFramebuffer"
, "shaders.MixinItem"
, "shaders.MixinLocale"
, "shaders.MixinOpenGlHelper"
, "shaders.MixinRender"
, "shaders.MixinRenderEntityFlame"
, "shaders.MixinRendererLivingEntity"
, "shaders.MixinRenderGlobal"
, "shaders.MixinTileEntityBeaconRenderer"
)
),
IRIS_RENDERING_NOBACKHAND(new MixinBuilder("Iris Hand Shaders")
.setPhase(Phase.EARLY)
.setApplyIf(() -> AngelicaConfig.enableIris)
.addExcludedMod(TargetedMod.BACKHAND)
.addClientMixins(
"shaders.MixinItemRenderer"
)
),
IRIS_RENDERING_BACKHAND(new MixinBuilder("Iris Hand Shaders (Backhand)")
.addRequiredMod(TargetedMod.BACKHAND)
.setPhase(Phase.EARLY)
.setApplyIf(() -> AngelicaConfig.enableIris)
.addClientMixins(
"shaders.MixinItemRendererBackhand"
)
),
ANGELICA_TEXTURE(new MixinBuilder()
.setPhase(Phase.EARLY)
.setApplyIf(() -> AngelicaConfig.enableIris || AngelicaConfig.enableSodium)
.addClientMixins(
"angelica.textures.MixinTextureAtlasSprite"
, "angelica.textures.MixinTextureUtil"
)),
ANGELICA_ZOOM(new MixinBuilder()
.setPhase(Phase.EARLY)
.setApplyIf(() -> AngelicaConfig.enableZoom)
.addClientMixins(
"angelica.zoom.MixinEntityRenderer_Zoom",
"angelica.zoom.MixinMinecraft_Zoom",
"angelica.zoom.MixinMouseFilter"
)),
HUD_CACHING(new MixinBuilder()
.setPhase(Phase.EARLY)
.setApplyIf(() -> AngelicaConfig.enableHudCaching)
.addClientMixins(
"angelica.hudcaching.MixinGuiIngame",
"angelica.hudcaching.MixinGuiIngameForge",
"angelica.hudcaching.MixinRenderGameOverlayEvent",
"angelica.hudcaching.MixinEntityRenderer_HUDCaching",
"angelica.hudcaching.MixinFramebuffer_HUDCaching",
"angelica.hudcaching.MixinGuiIngame_HUDCaching",
"angelica.hudcaching.MixinGuiIngameForge_HUDCaching",
"angelica.hudcaching.MixinRenderItem")
),
OPTIMIZE_WORLD_UPDATE_LIGHT(new MixinBuilder()
.setPhase(Phase.EARLY)
.addExcludedMod(TargetedMod.ARCHAICFIX)
.setApplyIf(() -> AngelicaConfig.optimizeWorldUpdateLight)
.addCommonMixins("angelica.lighting.MixinWorld_FixLightUpdateLag")),
SPEEDUP_VANILLA_ANIMATIONS(new MixinBuilder()
.setPhase(Phase.EARLY)
.setApplyIf(() -> AngelicaConfig.speedupAnimations)
.addClientMixins(
"angelica.animation.MixinTextureAtlasSprite",
"angelica.animation.MixinTextureMap",
"angelica.animation.MixinBlockFire",
"angelica.animation.MixinMinecraftForgeClient",
"angelica.animation.MixinChunkCache",
"angelica.animation.MixinRenderBlocks",
"angelica.animation.MixinRenderBlockFluid",
"angelica.animation.MixinWorldRenderer",
"angelica.animation.MixinRenderItem")),
SCALED_RESOUTION_UNICODE_FIX(new MixinBuilder("Removes unicode languages gui scaling being forced to even values")
.setPhase(Phase.EARLY)
.setApplyIf(() -> AngelicaConfig.removeUnicodeEvenScaling)
.addClientMixins("angelica.bugfixes.MixinScaledResolution_UnicodeFix")),
SECURITYCRAFT_COMPAT(new MixinBuilder("Fix reflection in SecurityCraft for compat with Angelica")
.setPhase(Phase.LATE)
.addRequiredMod(TargetedMod.SECURITYCRAFT)
.setApplyIf(() -> CompatConfig.fixSecurityCraft)
.addClientMixins(
"client.securitycraft.MixinBlockReinforcedFenceGate",
"client.securitycraft.MixinBlockReinforcedIronBars"
)),
EXTRA_UTILITIES_THREAD_SAFETY(new MixinBuilder("Enable thread safety fixes in Extra Utilities")
.setPhase(Phase.LATE)
.addRequiredMod(TargetedMod.EXTRAUTILS)
.setApplyIf(() -> CompatConfig.fixExtraUtils)
.addClientMixins(
"client.extrautils.MixinRenderBlockConnectedTextures",
"client.extrautils.MixinRenderBlockConnectedTexturesEthereal",
"client.extrautils.MixinIconConnectedTexture")),
MFR_THREAD_SAFETY(new MixinBuilder("Enable thread safety fixes for MineFactory Reloaded")
.setPhase(Phase.LATE)
.addRequiredMod(TargetedMod.MINEFACTORY_RELOADED)
.setApplyIf(() -> CompatConfig.fixMinefactoryReloaded)
.addClientMixins("client.minefactoryreloaded.MixinRedNetCableRenderer")),
NTM_SPACE_TWEAKS(new MixinBuilder("Support for 'Disable Horizon' & 'disableAltitudePlanetRenderer' options in NTM:Space")
.setPhase(Phase.LATE)
.addRequiredMod(TargetedMod.NTM_SPACE)
.setApplyIf(() -> CompatConfig.tweakNTMSpace)
.addClientMixins("client.ntmSpace.MixinSkyProviderCelestial_Tweaks")),
NTM_SPACE_SHADER_COMPAT(new MixinBuilder("Multiple shader fixes for NTM:Space")
.setPhase(Phase.LATE)
.addRequiredMod(TargetedMod.NTM_SPACE)
.setApplyIf(() -> CompatConfig.fixNTMSpace && AngelicaConfig.enableIris)
.addClientMixins("client.ntmSpace.MixinSkyProviderCelestial_ShaderCompat")),
SPEEDUP_CAMPFIRE_BACKPORT_ANIMATIONS(new MixinBuilder("Add animation speedup support to Campfire Backport")
.setPhase(Phase.LATE)
.addRequiredMod(TargetedMod.CAMPFIRE_BACKPORT)
.setApplyIf(() -> AngelicaConfig.speedupAnimations)
.addClientMixins("client.campfirebackport.MixinRenderBlockCampfire")),
IC2_FLUID_RENDER_FIX(new MixinBuilder()
.setPhase(Phase.EARLY)
.addRequiredMod(TargetedMod.IC2)
.setApplyIf(() -> AngelicaConfig.speedupAnimations)
.addClientMixins("angelica.textures.ic2.MixinRenderLiquidCell")),
OPTIMIZE_TEXTURE_LOADING(new MixinBuilder()
.setPhase(Phase.EARLY)
.addClientMixins("angelica.textures.MixinTextureUtil_OptimizeMipmap")
.setApplyIf(() -> AngelicaConfig.optimizeTextureLoading)),
//From NotFine
NOTFINE_BASE_MOD(new MixinBuilder()
.setPhase(Phase.EARLY)
.setApplyIf(() -> AngelicaConfig.enableNotFineFeatures)
.addClientMixins(addPrefix("notfine.",
"clouds.MixinEntityRenderer",
"clouds.MixinGameSettings",
//"clouds.MixinRenderGlobal",
"clouds.MixinWorldType",
"fix.MixinRenderItem",
"gui.MixinGuiSlot",
"glint.MixinRenderBiped",
"glint.MixinRenderPlayer",
"optimization.MixinRenderItemFrame",
"leaves.MixinBlockLeaves",
"leaves.MixinBlockLeavesBase",
"particles.MixinBlockEnchantmentTable",
"particles.MixinEffectRenderer",
"particles.MixinWorldClient",
"renderer.MixinRenderGlobal",
"toggle.MixinEntityRenderer",
"toggle.MixinGuiIngame",
"toggle.MixinRender",
"toggle.MixinRenderItem",
"interpolatedtexturemap.MixinTextureMap"
))
),
BETTER_FACE_CULLING(new MixinBuilder()
.setPhase(Phase.EARLY)
.setApplyIf(() -> NotFineConfig.betterBlockFaceCulling)
.addClientMixins(addPrefix("notfine.faceculling.",
"MixinBlock",
"MixinBlockCactus",
"MixinBlockCarpet",
"MixinBlockEnchantmentTable",
"MixinBlockFarmland",
"MixinBlockSlab",
"MixinBlockSnow",
"MixinBlockStairs",
"MixinRenderBlocks"
))
),
NOTFINE_NO_DYNAMIC_SURROUNDINGS(new MixinBuilder()
.setPhase(Phase.EARLY)
.addExcludedMod(TargetedMod.DYNAMIC_SURROUNDINGS_MIST)
.addExcludedMod(TargetedMod.DYNAMIC_SURROUNDINGS_ORIGINAL)
.addClientMixins("notfine.toggle.MixinEntityRenderer$RenderRainSnow")
),
NOTFINE_NO_CUSTOM_ITEM_TEXTURES(new MixinBuilder()
.setPhase(Phase.EARLY)
.addExcludedMod(TargetedMod.DRAGON_API)
.setApplyIf(() -> !AngelicaConfig.enableMCPatcherForgeFeatures || !MCPatcherForgeConfig.CustomItemTextures.enabled)
.addClientMixins(addPrefix("notfine.glint.",
"MixinItemRenderer",
"MixinRenderItem"
))
),
NOTFINE_NATURA_COMPAT(new MixinBuilder()
.setPhase(Phase.LATE)
.setApplyIf(() -> AngelicaConfig.enableNotFineFeatures)
.addRequiredMod(TargetedMod.NATURA)
.addClientMixins(addPrefix("notfine.leaves.natura.",
"MixinBerryBush",
"MixinNetherBerryBush"
))
),
NOTFINE_THAUMCRAFT_COMPAT(new MixinBuilder()
.setPhase(Phase.LATE)
.setApplyIf(() -> AngelicaConfig.enableNotFineFeatures)
.addRequiredMod(TargetedMod.THAUMCRAFT)
.addClientMixins("notfine.leaves.thaumcraft.MixinBlockMagicalLeaves")
),
THAUMCRAFT_BETTER_FACE_CULLING(new MixinBuilder()
.setPhase(Phase.LATE)
.setApplyIf(() -> NotFineConfig.betterBlockFaceCulling)
.addRequiredMod(TargetedMod.THAUMCRAFT)
.addClientMixins(addPrefix("notfine.faceculling.thaumcraft.",
"MixinBlockWoodenDevice",
"MixinBlockStoneDevice",
"MixinBlockTable"
))
),
NOTFINE_TINKERS_CONSTRUCT_COMPAT(new MixinBuilder()
.setPhase(Phase.LATE)
.setApplyIf(() -> AngelicaConfig.enableNotFineFeatures)
.addRequiredMod(TargetedMod.TINKERS_CONSTRUCT)
.addClientMixins("notfine.leaves.tconstruct.MixinOreberryBush")
),
NOTFINE_WITCHERY_COMPAT(new MixinBuilder()
.setPhase(Phase.LATE)
.setApplyIf(() -> AngelicaConfig.enableNotFineFeatures)
.addRequiredMod(TargetedMod.WITCHERY)
.addClientMixins("notfine.leaves.witchery.MixinBlockWitchLeaves")
),
NOTFINE_TWILIGHT_FOREST_COMPAT(new MixinBuilder()
.setPhase(Phase.LATE)
.setApplyIf(() -> AngelicaConfig.enableNotFineFeatures)
.addRequiredMod(TargetedMod.TWILIGHT_FOREST)
.addClientMixins(addPrefix("notfine.leaves.twilightforest.",
"MixinBlockTFLeaves",
"MixinBlockTFLeaves3",
// TODO: Verify 2.3.8.18 or later to support non NH builds?
"MixinBlockTFMagicLeaves"
))
),
MCPATCHER_FORGE(new MixinBuilder()
.setPhase(Phase.EARLY)
.setApplyIf(() -> AngelicaConfig.enableMCPatcherForgeFeatures)
.addClientMixins(addPrefix("mcpatcherforge.",
"base.MixinBlockGrass",
"base.MixinBlockMycelium",
"base.MixinAbstractTexture",
"base.MixinTextureAtlasSprite",
"base.MixinSimpleReloadableResourceManager",
"base.MixinMinecraft"
))
),
MCPATCHER_FORGE_RENDERPASS_BASE(new MixinBuilder()
.setPhase(Phase.EARLY)
.setApplyIf(() -> NotFineConfig.renderPass)
.addClientMixins(addPrefix("mcpatcherforge.renderpass.",
"MixinEntityRenderer",
"MixinRenderBlocks",
"MixinWorldRenderer"
))
),
MCPATCHER_FORGE_RENDERPASS_DISPLAYLIST(new MixinBuilder("RenderPass display list allocation increase")
.setPhase(Phase.EARLY)
.setApplyIf(() -> NotFineConfig.renderPass && !AngelicaConfig.enableSodium)
.addClientMixins("mcpatcherforge.renderpass.MixinRenderGlobal_DisplayLists")
),
MCPATCHER_FORGE_RENDERPASS_FEATURES(new MixinBuilder("RenderPass rendering features")
.setPhase(Phase.EARLY)
.setApplyIf(() -> NotFineConfig.renderPass && !AngelicaConfig.enableSodium)
.addClientMixins("mcpatcherforge.renderpass.MixinRenderGlobal_Features")
),
MCPATCHER_FORGE_CUSTOM_COLORS(new MixinBuilder()
.setPhase(Phase.EARLY)
.setApplyIf(() -> AngelicaConfig.enableMCPatcherForgeFeatures && MCPatcherForgeConfig.CustomColors.enabled)
.addClientMixins(addPrefix("mcpatcherforge.cc.",
"block.material.MixinMapColor",
"block.MixinBlock",
"block.MixinBlockDoublePlant",
"block.MixinBlockGrass",
"block.MixinBlockLeaves",
"block.MixinBlockLilyPad",
"block.MixinBlockLiquid",
"block.MixinBlockOldLeaf",
"block.MixinBlockRedstoneWire",
"block.MixinBlockReed",
"block.MixinBlockStem",
"block.MixinBlockTallGrass",
"block.MixinBlockVine",
"client.particle.MixinEntityAuraFX",
"client.particle.MixinEntityBubbleFX",
"client.particle.MixinEntityDropParticleFX",
"client.particle.MixinEntityPortalFX",
"client.particle.MixinEntityRainFX",
"client.particle.MixinEntityRedDustFX",
"client.particle.MixinEntitySplashFX",
"client.particle.MixinEntitySuspendFX",
"client.renderer.entity.MixinRenderWolf",
"client.renderer.entity.MixinRenderXPOrb",
"client.renderer.tileentity.MixinTileEntitySignRenderer",
"client.renderer.MixinEntityRenderer",
"client.renderer.MixinItemRenderer",
"client.renderer.MixinRenderBlocks",
"client.renderer.MixinRenderGlobal",
"entity.MixinEntityList",
"item.crafting.MixinRecipesArmorDyes",
"item.MixinItemArmor",
"item.MixinItemBlock",
"item.MixinItemMonsterPlacer",
"potion.MixinPotion",
"potion.MixinPotionHelper",
"world.MixinWorld",
"world.MixinWorldProvider",
"world.MixinWorldProviderEnd",
"world.MixinWorldProviderHell"
))
),
MCPATCHER_FORGE_CUSTOM_ITEM_TEXTURES(new MixinBuilder()
.setPhase(Phase.EARLY)
.addExcludedMod(TargetedMod.DRAGON_API)
.setApplyIf(() -> AngelicaConfig.enableMCPatcherForgeFeatures && MCPatcherForgeConfig.CustomItemTextures.enabled)
.addClientMixins(addPrefix("mcpatcherforge.cit.",
"client.renderer.entity.MixinRenderBiped",
"client.renderer.entity.MixinRenderEntityLiving",
"client.renderer.entity.MixinRenderItem",
"client.renderer.entity.MixinRenderPlayer",
"client.renderer.entity.MixinRenderSnowball",
"client.renderer.MixinItemRenderer",
"client.renderer.MixinRenderGlobal",
"entity.MixinEntityLivingBase",
"item.MixinItem",
"nbt.MixinNBTTagCompound",
"nbt.MixinNBTTagList",
"world.MixinWorld"
))
),
MCPATCHER_FORGE_CONNECTED_TEXTURES(new MixinBuilder()
.setPhase(Phase.EARLY)
.setApplyIf(() -> AngelicaConfig.enableMCPatcherForgeFeatures && MCPatcherForgeConfig.ConnectedTextures.enabled)
.addClientMixins("mcpatcherforge.ctm.MixinRenderBlocks")
),
MCPATCHER_FORGE_EXTENDED_HD(new MixinBuilder()
.setPhase(Phase.EARLY)
.setApplyIf(() -> AngelicaConfig.enableMCPatcherForgeFeatures && MCPatcherForgeConfig.ExtendedHD.enabled)
.addClientMixins(addPrefix("mcpatcherforge.hd.",
"MixinTextureClock",
"MixinTextureCompass",
"MixinTextureManager"
))
),
MCPATCHER_FORGE_EXTENDED_HD_FONT(new MixinBuilder()
.setPhase(Phase.EARLY)
.setApplyIf(() -> (AngelicaConfig.enableMCPatcherForgeFeatures && MCPatcherForgeConfig.ExtendedHD.enabled && MCPatcherForgeConfig.ExtendedHD.hdFont))
.addExcludedMod(TargetedMod.COFHCORE)
.addClientMixins("mcpatcherforge.hd.MixinFontRenderer")
),
MCPATCHER_FORGE_RANDOM_MOBS(new MixinBuilder()
.setPhase(Phase.EARLY)
.setApplyIf(() -> AngelicaConfig.enableMCPatcherForgeFeatures && MCPatcherForgeConfig.RandomMobs.enabled)
.addClientMixins(addPrefix("mcpatcherforge.mob.",
"MixinRender",
"MixinRenderEnderman",
"MixinRenderFish",
"MixinRenderLiving",
"MixinRenderMooshroom",
"MixinRenderSheep",
"MixinRenderSnowMan",
"MixinRenderSpider",
"MixinRenderWolf",
"MixinEntityLivingBase"
))
),
MCPATCHER_FORGE_SKY(new MixinBuilder()
.setPhase(Phase.EARLY)
.setApplyIf(() -> AngelicaConfig.enableMCPatcherForgeFeatures && MCPatcherForgeConfig.BetterSkies.enabled)
.addClientMixins(addPrefix("mcpatcherforge.sky.",
"MixinEffectRenderer",
"MixinRenderGlobal"
))
),
MCPATCHER_FORGE_CC_NO_CTM(new MixinBuilder("MCP:F Custom Colors, no Connected Textures")
.setPhase(Phase.EARLY)
.setApplyIf(() -> AngelicaConfig.enableMCPatcherForgeFeatures
&& !MCPatcherForgeConfig.ConnectedTextures.enabled
&& MCPatcherForgeConfig.CustomColors.enabled)
.addClientMixins("mcpatcherforge.ctm_cc.MixinRenderBlocksNoCTM")
),
MCPATCHER_FORGE_CTM_NO_CC(new MixinBuilder("MCP:F Connected Textures, no Custom Colours")
.setPhase(Phase.EARLY)
.setApplyIf(() -> AngelicaConfig.enableMCPatcherForgeFeatures
&& MCPatcherForgeConfig.ConnectedTextures.enabled
&& !MCPatcherForgeConfig.CustomColors.enabled)
.addClientMixins("mcpatcherforge.ctm_cc.MixinRenderBlocksNoCC")
),
MCPATCHER_FORGE_CTM_AND_CC(new MixinBuilder("MCP:F Connected Textures and Custom Colors")
.setPhase(Phase.EARLY)
.setApplyIf(() -> AngelicaConfig.enableMCPatcherForgeFeatures
&& MCPatcherForgeConfig.ConnectedTextures.enabled
&& MCPatcherForgeConfig.CustomColors.enabled)
.addClientMixins("mcpatcherforge.ctm_cc.MixinRenderBlocks")
),
MCPATCHER_FORGE_CTM_OR_CC(new MixinBuilder("MCP:F Connected Textures or Custom Colors")
.setPhase(Phase.EARLY)
.setApplyIf(() -> AngelicaConfig.enableMCPatcherForgeFeatures
&& MCPatcherForgeConfig.ConnectedTextures.enabled
|| MCPatcherForgeConfig.CustomColors.enabled)
.addClientMixins("mcpatcherforge.ctm_cc.MixinTextureMap")
),
//End from NotFine
;
private final MixinBuilder builder;
private static String[] addPrefix(String prefix, String... values) {
List<String> list = new ArrayList<>(values.length);
for (String s : values) {
list.add(prefix + s);
}
return list.toArray(new String[values.length]);
}
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\mixins\TargetedMod.java
|
package com.gtnewhorizons.angelica.mixins;
import com.gtnewhorizon.gtnhmixins.builders.ITargetMod;
import com.gtnewhorizon.gtnhmixins.builders.TargetModBuilder;
import lombok.Getter;
@Getter
public enum TargetedMod implements ITargetMod {
ARCHAICFIX("org.embeddedt.archaicfix.ArchaicCore", "archaicfix"),
BACKHAND("xonin.backhand.coremod.BackhandLoadingPlugin", "backhand"),
CAMPFIRE_BACKPORT(null, "campfirebackport"),
COFHCORE( "cofh.asm.LoadingPlugin", "CoFHCore"),
DYNAMIC_SURROUNDINGS_MIST("org.blockartistry.mod.DynSurround.mixinplugin.DynamicSurroundingsEarlyMixins", "dsurround"),
DYNAMIC_SURROUNDINGS_ORIGINAL("org.blockartistry.mod.DynSurround.asm.TransformLoader", "dsurround"),
DRAGON_API("Reika.DragonAPI.Auxiliary.DragonAPIASMHandler", "DragonAPI"),
EXTRAUTILS(null, "ExtraUtilities"),
FALSETWEAKS("com.falsepattern.falsetweaks.asm.CoreLoadingPlugin", "falsetweaks"),
MINEFACTORY_RELOADED(null, "MineFactoryReloaded"),
NTM_SPACE("com.hbm.dim.SolarSystem"),
IC2("ic2.core.coremod.IC2core", "IC2"),
NATURA(null, "Natura"),
SECURITYCRAFT(null, "securitycraft"),
THAUMCRAFT(null, "Thaumcraft"),
TINKERS_CONSTRUCT(null, "TConstruct"),
TWILIGHT_FOREST(null, "TwilightForest"),
WITCHERY(null, "witchery");
private final TargetModBuilder builder;
TargetedMod(String targetClass) {
this.builder = new TargetModBuilder().setTargetClass(targetClass);
}
TargetedMod(String coreModClass, String modId) {
this.builder = new TargetModBuilder().setCoreModClass(coreModClass).setModId(modId);
}
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\models\VanillaModels.java
| |
Angelica
|
src\main\java\com\gtnewhorizons\angelica\proxy\ClientProxy.java
|
package com.gtnewhorizons.angelica.proxy;
import static com.gtnewhorizons.angelica.AngelicaMod.MOD_ID;
import static com.gtnewhorizons.angelica.loading.AngelicaTweaker.LOGGER;
import com.google.common.base.Objects;
import com.gtnewhorizon.gtnhlib.client.model.loading.ModelRegistry;
import com.gtnewhorizon.gtnhlib.client.renderer.vao.VAOManager;
import com.gtnewhorizons.angelica.compat.ModStatus;
import com.gtnewhorizons.angelica.compat.bettercrashes.BetterCrashesCompat;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import com.gtnewhorizons.angelica.config.CompatConfig;
import com.gtnewhorizons.angelica.debug.F3Direction;
import com.gtnewhorizons.angelica.debug.FrametimeGraph;
import com.gtnewhorizons.angelica.debug.TPSGraph;
import com.gtnewhorizons.angelica.dynamiclights.DynamicLights;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.debug.OpenGLDebugging;
import com.gtnewhorizons.angelica.hudcaching.HUDCaching;
import com.gtnewhorizons.angelica.mixins.interfaces.IGameSettingsExt;
import com.gtnewhorizons.angelica.render.CloudRenderer;
import com.gtnewhorizons.angelica.rendering.AngelicaBlockSafetyRegistry;
import com.gtnewhorizons.angelica.zoom.Zoom;
import cpw.mods.fml.client.registry.ClientRegistry;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.eventhandler.EventPriority;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.TickEvent;
import cpw.mods.fml.common.registry.GameData;
import cpw.mods.fml.relauncher.ReflectionHelper;
import java.lang.management.ManagementFactory;
import java.util.Locale;
import java.util.concurrent.ConcurrentHashMap;
import jss.notfine.core.Settings;
import me.jellysquid.mods.sodium.client.SodiumDebugScreenHandler;
import net.coderbot.iris.Iris;
import net.coderbot.iris.client.IrisDebugScreenHandler;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.gui.GuiMainMenu;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.client.network.NetHandlerPlayClient;
import net.minecraft.client.settings.GameSettings;
import net.minecraft.client.settings.KeyBinding;
import net.minecraft.server.integrated.IntegratedServer;
import net.minecraft.util.Direction;
import net.minecraft.util.MathHelper;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.world.EnumSkyBlock;
import net.minecraft.world.chunk.Chunk;
import net.minecraftforge.client.event.EntityViewRenderEvent;
import net.minecraftforge.client.event.FOVUpdateEvent;
import net.minecraftforge.client.event.GuiOpenEvent;
import net.minecraftforge.client.event.RenderGameOverlayEvent;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.world.WorldEvent;
import org.lwjgl.input.Keyboard;
public class ClientProxy extends CommonProxy {
final Minecraft mc = Minecraft.getMinecraft();
final FrametimeGraph frametimeGraph = new FrametimeGraph();
final TPSGraph tpsGraph = new TPSGraph();
@Override
public void preInit(FMLPreInitializationEvent event) {
super.preInit(event);
FMLCommonHandler.instance().bus().register(this);
MinecraftForge.EVENT_BUS.register(this);
ModelRegistry.registerModid(MOD_ID);
}
@SubscribeEvent
public void worldLoad(WorldEvent.Load event) {
if (GLStateManager.isRunningSplash()) {
GLStateManager.setRunningSplash(false);
LOGGER.info("World loaded - Enabling GLSM Cache");
}
if (AngelicaConfig.enableSodium) {
// Register all blocks. Because blockids are unique to a world, this must be done each load
GameData.getBlockRegistry().typeSafeIterable().forEach(o -> {
AngelicaBlockSafetyRegistry.canBlockRenderOffThread(o, true, true);
AngelicaBlockSafetyRegistry.canBlockRenderOffThread(o, false, true);
});
}
}
private static KeyBinding glsmKeyBinding;
@Override
public void init(FMLInitializationEvent event) {
super.init(event);
if (AngelicaConfig.enableHudCaching) {
HUDCaching.init();
}
if (AngelicaConfig.enableSodium) {
MinecraftForge.EVENT_BUS.register(SodiumDebugScreenHandler.INSTANCE);
}
if (AngelicaConfig.enableIris) {
MinecraftForge.EVENT_BUS.register(IrisDebugScreenHandler.INSTANCE);
Iris.INSTANCE.fmlInitEvent();
FMLCommonHandler.instance().bus().register(Iris.INSTANCE);
MinecraftForge.EVENT_BUS.register(Iris.INSTANCE);
}
if (!AngelicaConfig.enableVAO) {
VAOManager.disableVao();
}
FMLCommonHandler.instance().bus().register(this);
MinecraftForge.EVENT_BUS.register(this);
glsmKeyBinding = new KeyBinding("Print GLSM Debug", Keyboard.KEY_NONE, "Angelica");
ClientRegistry.registerKeyBinding(glsmKeyBinding);
if (ModStatus.isBetterCrashesLoaded) {
BetterCrashesCompat.init();
}
if (AngelicaConfig.enableZoom) {
Zoom.init();
}
}
private boolean wasGLSMKeyPressed;
@SubscribeEvent
public void onKeypress(TickEvent.ClientTickEvent event) {
final boolean isPressed = glsmKeyBinding.getKeyCode() != 0 && GameSettings.isKeyDown(glsmKeyBinding);
if (isPressed && !wasGLSMKeyPressed) {
OpenGLDebugging.checkGLSM();
}
wasGLSMKeyPressed = isPressed;
}
@Override
public void postInit(FMLPostInitializationEvent event) {
super.postInit(event);
if (ModStatus.isLotrLoaded && AngelicaConfig.enableSodium && CompatConfig.fixLotr) {
try {
Class<?> lotrRendering = Class.forName("lotr.common.coremod.LOTRReplacedMethods$BlockRendering");
ReflectionHelper.setPrivateValue(lotrRendering, null, new ConcurrentHashMap<>(), "naturalBlockClassTable");
ReflectionHelper.setPrivateValue(lotrRendering, null, new ConcurrentHashMap<>(), "naturalBlockTable");
ReflectionHelper.setPrivateValue(lotrRendering, null, new ConcurrentHashMap<>(), "cachedNaturalBlocks");
} catch (ClassNotFoundException e) {
LOGGER.error("Could not replace LOTR handle render code with thread safe version");
}
}
}
float lastIntegratedTickTime;
@SubscribeEvent
public void onTick(TickEvent.ServerTickEvent event) {
if (FMLCommonHandler.instance().getSide().isClient() && event.phase == TickEvent.Phase.END) {
IntegratedServer srv = Minecraft.getMinecraft().getIntegratedServer();
if (srv != null) {
long currentTickTime = srv.tickTimeArray[srv.getTickCounter() % 100];
lastIntegratedTickTime = lastIntegratedTickTime * 0.8F + (float) currentTickTime / 1000000.0F * 0.2F;
} else lastIntegratedTickTime = 0;
}
}
@SubscribeEvent(priority = EventPriority.LOWEST)
public void onRenderOverlay(RenderGameOverlayEvent.Pre event) {
if (event.isCanceled() || !mc.gameSettings.showDebugInfo) return;
if (AngelicaConfig.modernizeF3Screen && event.type == RenderGameOverlayEvent.ElementType.CROSSHAIRS) {
F3Direction.renderWorldDirectionsEvent(mc, event);
event.setCanceled(true);
}
}
@SubscribeEvent(priority = EventPriority.LOWEST)
public void onRenderOverlay(RenderGameOverlayEvent.Text event) {
Minecraft mc = Minecraft.getMinecraft();
if (event.isCanceled() || !mc.gameSettings.showDebugInfo || event.left.isEmpty()) return;
NetHandlerPlayClient cl = mc.getNetHandler();
if (cl != null) {
IntegratedServer srv = mc.getIntegratedServer();
if (srv != null) {
String s = String.format("Integrated server @ %.0f ms ticks", lastIntegratedTickTime);
event.left.add(Math.min(event.left.size(), 1), s);
}
}
if (AngelicaConfig.showBlockDebugInfo && mc.objectMouseOver != null && mc.objectMouseOver.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) {
if (!event.right.isEmpty() && !Objects.firstNonNull(event.right.get(event.right.size() - 1), "").isEmpty()) event.right.add("");
Block block = mc.theWorld.getBlock(mc.objectMouseOver.blockX, mc.objectMouseOver.blockY, mc.objectMouseOver.blockZ);
int meta = mc.theWorld.getBlockMetadata(mc.objectMouseOver.blockX, mc.objectMouseOver.blockY, mc.objectMouseOver.blockZ);
event.right.add(Block.blockRegistry.getNameForObject(block));
event.right.add("meta: " + meta);
}
if (DynamicLights.isEnabled()) {
var builder = new StringBuilder("Dynamic Light Sources: ");
DynamicLights dl = DynamicLights.get();
builder.append(dl.getLightSourcesCount()).append(" (U: ").append(dl.getLastUpdateCount()).append(')');
event.right.add(builder.toString());
}
if (AngelicaConfig.modernizeF3Screen) {
boolean hasReplacedXYZ = false;
for (int i = 0; i < event.left.size() - 3; i++) {
/* These checks should not be inefficient as most of the time the first one will already fail */
if (!hasReplacedXYZ && Objects.firstNonNull(event.left.get(i), "").startsWith("x:") && Objects.firstNonNull(event.left.get(i + 1), "")
.startsWith("y:") && Objects.firstNonNull(event.left.get(i + 2), "").startsWith("z:") && Objects.firstNonNull(event.left.get(i + 3), "")
.startsWith("f:")) {
hasReplacedXYZ = true;
int heading = MathHelper.floor_double((double) (mc.thePlayer.rotationYaw * 4.0F / 360.0F) + 0.5D) & 3;
String heading_str = switch (heading) {
case 0 -> "Towards positive Z";
case 1 -> "Towards negative X";
case 2 -> "Towards negative Z";
case 3 -> "Towards positive X";
default -> throw new RuntimeException();
};
event.left.set(i, String.format("XYZ: %.3f / %.5f / %.3f", mc.thePlayer.posX, mc.thePlayer.boundingBox.minY, mc.thePlayer.posZ));
int bX = MathHelper.floor_double(mc.thePlayer.posX);
int bY = MathHelper.floor_double(mc.thePlayer.boundingBox.minY);
int bZ = MathHelper.floor_double(mc.thePlayer.posZ);
event.left.set(i + 1, String.format("Block: %d %d %d [%d %d %d]", bX, bY, bZ, bX & 15, bY & 15, bZ & 15));
event.left.set(i + 2, String.format("Chunk: %d %d %d", bX >> 4, bY >> 4, bZ >> 4));
event.left.set(i + 3, String.format(
"Facing: %s (%s) (%.1f / %.1f)",
Direction.directions[heading].toLowerCase(Locale.ROOT),
heading_str,
MathHelper.wrapAngleTo180_float(mc.thePlayer.rotationYaw),
MathHelper.wrapAngleTo180_float(mc.thePlayer.rotationPitch)));
Chunk chunk = this.mc.theWorld.getChunkFromBlockCoords(bX, bZ);
event.left.set(i + 4, String.format(
"lc: %d b: %s bl: %d sl: %d rl: %d",
chunk.getTopFilledSegment() + 15,
chunk.getBiomeGenForWorldCoords(bX & 15, bZ & 15, mc.theWorld.getWorldChunkManager()).biomeName,
chunk.getSavedLightValue(EnumSkyBlock.Block, bX & 15, MathHelper.clamp_int(bY, 0, 255), bZ & 15),
chunk.getSavedLightValue(EnumSkyBlock.Sky, bX & 15, MathHelper.clamp_int(bY, 0, 255), bZ & 15),
chunk.getBlockLightValue(bX & 15, MathHelper.clamp_int(bY, 0, 255), bZ & 15, 0)));
}
}
event.setCanceled(true);
// TODO don't cancel the event and render here,
// instead mixin into the vanilla code and add a background to it
/* render ourselves for modern background */
FontRenderer fontrenderer = mc.fontRenderer;
int fontColor = 0xe0e0e0;
int rectColor = 0x90505050;
for (int x = 0; x < event.left.size(); x++) {
String msg = event.left.get(x);
if (msg == null) continue;
int strX = 2;
int strY = 2 + x * fontrenderer.FONT_HEIGHT;
Gui.drawRect(1, strY - 1, strX + fontrenderer.getStringWidth(msg) + 1, strY + fontrenderer.FONT_HEIGHT - 1, rectColor);
fontrenderer.drawString(msg, strX, strY, fontColor);
}
int width = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight).getScaledWidth();
for (int x = 0; x < event.right.size(); x++) {
String msg = event.right.get(x);
if (msg == null) continue;
int w = fontrenderer.getStringWidth(msg);
int strX = width - w - 2;
int strY = 2 + x * fontrenderer.FONT_HEIGHT;
Gui.drawRect(strX - 1, strY - 1, strX + w + 1, strY + fontrenderer.FONT_HEIGHT - 1, rectColor);
fontrenderer.drawString(msg, strX, strY, fontColor);
}
// Draw a frametime graph
if (((IGameSettingsExt)mc.gameSettings).angelica$showFpsGraph()) {
frametimeGraph.render();
if (Minecraft.getMinecraft().isSingleplayer()) {
tpsGraph.render();
}
}
}
}
private float gameStartTime = -1;
@SubscribeEvent(priority = EventPriority.LOWEST)
public void onGuiOpen(GuiOpenEvent event) {
if (!event.isCanceled()) {
if (event.gui instanceof GuiMainMenu && gameStartTime == -1 ) {
gameStartTime = ManagementFactory.getRuntimeMXBean().getUptime() / 1000f;
LOGGER.info("The game loaded in {} seconds.", gameStartTime);
}
// force reset zoom when a GUI is opened
if (AngelicaConfig.enableZoom && event.gui != null) Zoom.resetZoom();
}
}
/* coerce NaN fog values back to 0 (https://bugs.mojang.com/browse/MC-10480) - from ArchaicFix */
@SubscribeEvent(priority = EventPriority.LOWEST)
public void onFogColor(EntityViewRenderEvent.FogColors event) {
if (Float.isNaN(event.red)) event.red = 0f;
if (Float.isNaN(event.green)) event.green = 0f;
if (Float.isNaN(event.blue)) event.blue = 0f;
}
@SubscribeEvent
public void onTick(TickEvent.ClientTickEvent event) {
if (event.phase == TickEvent.Phase.END && mc.theWorld != null) {
CloudRenderer.getCloudRenderer().checkSettings();
}
}
// This is a bit of a hack to prevent the FOV from being modified by other mods
@SubscribeEvent(priority = EventPriority.LOWEST)
public void onFOVModifierUpdate(FOVUpdateEvent event) {
if (!(boolean) Settings.DYNAMIC_FOV.option.getStore()) {
event.newfov = 1.0F;
}
}
@Override
public void putFrametime(long time) {
frametimeGraph.putSample(time);
}
@Override
public void putTicktime(long time) {
tpsGraph.putSample(time);
}
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\proxy\CommonProxy.java
|
package com.gtnewhorizons.angelica.proxy;
import com.gtnewhorizons.angelica.common.BlockTest;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.registry.GameRegistry;
public class CommonProxy {
public void preInit(FMLPreInitializationEvent event) {
if (AngelicaConfig.enableTestBlocks){
GameRegistry.registerBlock(new BlockTest(), "test_block");
}
}
public void init(FMLInitializationEvent event) {}
public void postInit(FMLPostInitializationEvent event) {}
// Only present on the client!
public void putFrametime(long time) { throw new UnsupportedOperationException(); }
public void putTicktime(long time) { throw new UnsupportedOperationException(); }
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\render\CloudRenderer.java
|
/*
* Backported from Minecraft Forge 1.12 under the LGPL 2.1
*
* Minecraft Forge
* Copyright (c) 2016.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.gtnewhorizons.angelica.render;
import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator;
import com.gtnewhorizon.gtnhlib.client.renderer.TessellatorManager;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import jss.notfine.core.Settings;
import jss.notfine.gui.options.named.GraphicsQualityOff;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.EntityRenderer;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.renderer.texture.DynamicTexture;
import net.minecraft.client.resources.IReloadableResourceManager;
import net.minecraft.client.resources.IResourceManager;
import net.minecraft.client.resources.IResourceManagerReloadListener;
import net.minecraft.entity.Entity;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.Vec3;
import org.lwjgl.opengl.GL11;
public class CloudRenderer implements IResourceManagerReloadListener {
// Shared constants.
private static final float PX_SIZE = 1 / 256F;
// Building constants.
private static final VertexFormat FORMAT = DefaultVertexFormat.POSITION_TEXTURE_COLOR;
private static final int TOP_SECTIONS = 12; // Number of slices a top face will span.
private static final int HEIGHT = 4;
private static final float INSET = 0.001F;
private static final float ALPHA = 0.8F;
// Debug
private static final boolean WIREFRAME = false;
// Instance fields
private final Minecraft mc = Minecraft.getMinecraft();
private final ResourceLocation texture = new ResourceLocation("textures/environment/clouds.png");
private VertexBuffer vbo;
private int cloudMode = -1;
private int renderDistance = -1;
private int cloudElevation = -1;
private int scaleMult = -1;
private DynamicTexture COLOR_TEX = null;
private int texColor;
private int texW;
private int texH;
public CloudRenderer() {
// Resource manager should always be reloadable.
((IReloadableResourceManager) mc.getResourceManager()).registerReloadListener(this);
}
private static CloudRenderer instance;
public static CloudRenderer getCloudRenderer() {
if (instance == null)
instance = new CloudRenderer();
return instance;
}
private int getScale() {
return (cloudMode == 2 ? 12 : 8) * scaleMult;
}
private float ceilToScale(float value) {
float scale = getScale();
return (float)Math.ceil(value / scale) * scale;
}
private void vertices(CapturingTessellator tessellator) {
GraphicsQualityOff cloudGraphicsQuality = (GraphicsQualityOff)Settings.MODE_CLOUDS.option.getStore();
boolean fancy = cloudGraphicsQuality == GraphicsQualityOff.FANCY || cloudGraphicsQuality == GraphicsQualityOff.DEFAULT && mc.gameSettings.fancyGraphics;
float scale = getScale();
float CULL_DIST = 2 * scale;
float bCol = fancy ? 0.7F : 1F;
float sectEnd = ceilToScale((renderDistance * 2) * 16);
float sectStart = -sectEnd;
float sectStep = ceilToScale(sectEnd * 2 / TOP_SECTIONS);
float sectPx = PX_SIZE / scale;
tessellator.startDrawingQuads();
float sectX0 = sectStart;
float sectX1 = sectX0;
while (sectX1 < sectEnd) {
sectX1 += sectStep;
if (sectX1 > sectEnd)
sectX1 = sectEnd;
float sectZ0 = sectStart;
float sectZ1 = sectZ0;
while (sectZ1 < sectEnd) {
sectZ1 += sectStep;
if (sectZ1 > sectEnd)
sectZ1 = sectEnd;
float u0 = sectX0 * sectPx;
float u1 = sectX1 * sectPx;
float v0 = sectZ0 * sectPx;
float v1 = sectZ1 * sectPx;
// Bottom
tessellator.pos(sectX0, 0, sectZ0).tex(u0, v0).color(bCol, bCol, bCol, ALPHA).endVertex();
tessellator.pos(sectX1, 0, sectZ0).tex(u1, v0).color(bCol, bCol, bCol, ALPHA).endVertex();
tessellator.pos(sectX1, 0, sectZ1).tex(u1, v1).color(bCol, bCol, bCol, ALPHA).endVertex();
tessellator.pos(sectX0, 0, sectZ1).tex(u0, v1).color(bCol, bCol, bCol, ALPHA).endVertex();
if (fancy) {
final int height = HEIGHT * scaleMult;
// Top
tessellator.pos(sectX0, height, sectZ0).tex(u0, v0).color(1, 1, 1, ALPHA).endVertex();
tessellator.pos(sectX0, height, sectZ1).tex(u0, v1).color(1, 1, 1, ALPHA).endVertex();
tessellator.pos(sectX1, height, sectZ1).tex(u1, v1).color(1, 1, 1, ALPHA).endVertex();
tessellator.pos(sectX1, height, sectZ0).tex(u1, v0).color(1, 1, 1, ALPHA).endVertex();
float slice;
float sliceCoord0;
float sliceCoord1;
for (slice = sectX0; slice < sectX1; ) {
sliceCoord0 = slice * sectPx;
sliceCoord1 = sliceCoord0 + PX_SIZE;
// X sides
if (slice > -CULL_DIST) {
slice += INSET;
tessellator.pos(slice, 0, sectZ1).tex(sliceCoord0, v1).color(0.9F, 0.9F, 0.9F, ALPHA).endVertex();
tessellator.pos(slice, height, sectZ1).tex(sliceCoord1, v1).color(0.9F, 0.9F, 0.9F, ALPHA).endVertex();
tessellator.pos(slice, height, sectZ0).tex(sliceCoord1, v0).color(0.9F, 0.9F, 0.9F, ALPHA).endVertex();
tessellator.pos(slice, 0, sectZ0).tex(sliceCoord0, v0).color(0.9F, 0.9F, 0.9F, ALPHA).endVertex();
slice -= INSET;
}
slice += scale;
if (slice <= CULL_DIST) {
slice -= INSET;
tessellator.pos(slice, 0, sectZ0).tex(sliceCoord0, v0).color(0.9F, 0.9F, 0.9F, ALPHA).endVertex();
tessellator.pos(slice, height, sectZ0).tex(sliceCoord1, v0).color(0.9F, 0.9F, 0.9F, ALPHA).endVertex();
tessellator.pos(slice, height, sectZ1).tex(sliceCoord1, v1).color(0.9F, 0.9F, 0.9F, ALPHA).endVertex();
tessellator.pos(slice, 0, sectZ1).tex(sliceCoord0, v1).color(0.9F, 0.9F, 0.9F, ALPHA).endVertex();
slice += INSET;
}
}
for (slice = sectZ0; slice < sectZ1; ) {
sliceCoord0 = slice * sectPx;
sliceCoord1 = sliceCoord0 + PX_SIZE;
// Z sides
if (slice > -CULL_DIST) {
slice += INSET;
tessellator.pos(sectX0, 0, slice).tex(u0, sliceCoord0).color(0.8F, 0.8F, 0.8F, ALPHA).endVertex();
tessellator.pos(sectX0, height, slice).tex(u0, sliceCoord1).color(0.8F, 0.8F, 0.8F, ALPHA).endVertex();
tessellator.pos(sectX1, height, slice).tex(u1, sliceCoord1).color(0.8F, 0.8F, 0.8F, ALPHA).endVertex();
tessellator.pos(sectX1, 0, slice).tex(u1, sliceCoord0).color(0.8F, 0.8F, 0.8F, ALPHA).endVertex();
slice -= INSET;
}
slice += scale;
if (slice <= CULL_DIST) {
slice -= INSET;
tessellator.pos(sectX1, 0, slice).tex(u1, sliceCoord0).color(0.8F, 0.8F, 0.8F, ALPHA).endVertex();
tessellator.pos(sectX1, height, slice).tex(u1, sliceCoord1).color(0.8F, 0.8F, 0.8F, ALPHA).endVertex();
tessellator.pos(sectX0, height, slice).tex(u0, sliceCoord1).color(0.8F, 0.8F, 0.8F, ALPHA).endVertex();
tessellator.pos(sectX0, 0, slice).tex(u0, sliceCoord0).color(0.8F, 0.8F, 0.8F, ALPHA).endVertex();
slice += INSET;
}
}
}
sectZ0 = sectZ1;
}
sectX0 = sectX1;
}
}
private void dispose() {
if (vbo != null) {
vbo.close();
vbo = null;
}
}
private void build() {
CapturingTessellator tess = TessellatorManager.startCapturingAndGet();
vertices(tess);
this.vbo = TessellatorManager.stopCapturingToVAO(FORMAT);
}
private int fullCoord(double coord, int scale) { // Corrects misalignment of UV offset when on negative coords.
return ((int) coord / scale) - (coord < 0 ? 1 : 0);
}
private boolean isBuilt() {
return vbo != null;
}
public void checkSettings() {
GraphicsQualityOff cloudGraphicsQuality = (GraphicsQualityOff)Settings.MODE_CLOUDS.option.getStore();
final int cloudQualitySetting = cloudGraphicsQuality == GraphicsQualityOff.FANCY
|| cloudGraphicsQuality == GraphicsQualityOff.DEFAULT && mc.gameSettings.fancyGraphics ? 2 : 1;
final boolean newEnabled = cloudGraphicsQuality != GraphicsQualityOff.OFF
&& mc.gameSettings.shouldRenderClouds()
&& mc.theWorld != null
&& mc.theWorld.provider.isSurfaceWorld();
final int targetDistance = Math.max(mc.gameSettings.renderDistanceChunks, (int)Settings.RENDER_DISTANCE_CLOUDS.option.getStore());
final int cloudScaleMult = (int)Settings.CLOUD_SCALE.option.getStore();
if (isBuilt()
&& (!newEnabled
|| cloudQualitySetting != cloudMode
|| targetDistance != renderDistance
|| cloudScaleMult != scaleMult)) {
dispose();
}
cloudMode = cloudQualitySetting;
renderDistance = targetDistance;
scaleMult = cloudScaleMult;
cloudElevation = mc.theWorld == null ? 128 : (int)mc.theWorld.provider.getCloudHeight();
//Allows the setting to work with RFG and similar without hardcoding.
//The minimum height check is so stuff like Aether cloud height doesn't get messed up.
if(cloudElevation >= 96) {
cloudElevation = (int)Settings.CLOUD_HEIGHT.option.getStore();
}
if (newEnabled && !isBuilt()) {
build();
}
}
public boolean render(int cloudTicks, float partialTicks) {
if (!isBuilt())
return false;
Entity entity = mc.renderViewEntity;
double totalOffset = cloudTicks + partialTicks;
double x = entity.prevPosX + (entity.posX - entity.prevPosX) * partialTicks + totalOffset * 0.03;
double y = cloudElevation - (entity.lastTickPosY + (entity.posY - entity.lastTickPosY) * partialTicks) + 0.33;
double z = entity.prevPosZ + (entity.posZ - entity.prevPosZ) * partialTicks;
int scale = getScale();
if (cloudMode == 2)
z += 0.33 * scale;
// Integer UVs to translate the texture matrix by.
int offU = fullCoord(x, scale);
int offV = fullCoord(z, scale);
GLStateManager.glPushMatrix();
// Translate by the remainder after the UV offset.
GLStateManager.glTranslated((offU * scale) - x, y, (offV * scale) - z);
// Modulo to prevent texture samples becoming inaccurate at extreme offsets.
offU = offU % texW;
offV = offV % texH;
// Translate the texture.
GLStateManager.glMatrixMode(GL11.GL_TEXTURE);
GLStateManager.glTranslatef(offU * PX_SIZE, offV * PX_SIZE, 0);
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
GLStateManager.disableCull();
GLStateManager.enableBlend();
GLStateManager.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO);
// Color multiplier.
Vec3 color = mc.theWorld.getCloudColour(partialTicks);
float r = (float) color.xCoord;
float g = (float) color.yCoord;
float b = (float) color.zCoord;
if (mc.gameSettings.anaglyph) {
float tempR = r * 0.3F + g * 0.59F + b * 0.11F;
float tempG = r * 0.3F + g * 0.7F;
float tempB = r * 0.3F + b * 0.7F;
r = tempR;
g = tempG;
b = tempB;
}
// Apply a color multiplier through a texture upload if shaders aren't supported.
final int newColor = 0xFF000000
| ((int) (r * 255)) << 16
| ((int) (g * 255)) << 8
| (int) (b * 255);
if (texColor != newColor) {
if (COLOR_TEX == null) {
COLOR_TEX = new DynamicTexture(1, 1);
}
COLOR_TEX.getTextureData()[0] = newColor;
COLOR_TEX.updateDynamicTexture();
texColor = newColor;
}
GLStateManager.glActiveTexture(OpenGlHelper.lightmapTexUnit);
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, COLOR_TEX.getGlTextureId());
GLStateManager.enableTexture();
// Bind the clouds texture last so the shader's sampler2D is correct.
GLStateManager.glActiveTexture(OpenGlHelper.defaultTexUnit);
mc.renderEngine.bindTexture(texture);
vbo.setupState();
// Depth pass to prevent insides rendering from the outside.
GLStateManager.glColorMask(false, false, false, false);
vbo.draw();
// Full render.
if (!mc.gameSettings.anaglyph) {
GLStateManager.glColorMask(true, true, true, true);
} else {
switch (EntityRenderer.anaglyphField) {
case 0:
GLStateManager.glColorMask(false, true, true, true);
break;
case 1:
GLStateManager.glColorMask(true, false, false, true);
break;
}
}
// Wireframe for debug.
if (WIREFRAME) {
GL11.glPolygonMode(GL11.GL_FRONT_AND_BACK, GL11.GL_LINE);
GL11.glLineWidth(2.0F);
GLStateManager.disableTexture();
GLStateManager.glDepthMask(false);
GLStateManager.disableFog();
vbo.draw();
GL11.glPolygonMode(GL11.GL_FRONT_AND_BACK, GL11.GL_FILL);
GLStateManager.glDepthMask(true);
GLStateManager.enableTexture();
GLStateManager.enableFog();
}
vbo.draw();
vbo.cleanupState(); // Unbind buffer and disable pointers.
// Disable our coloring.
GLStateManager.glActiveTexture(OpenGlHelper.lightmapTexUnit);
GLStateManager.disableTexture();
GLStateManager.glActiveTexture(OpenGlHelper.defaultTexUnit);
// Reset texture matrix.
GLStateManager.glMatrixMode(GL11.GL_TEXTURE);
GLStateManager.glLoadIdentity();
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
GLStateManager.disableBlend();
GLStateManager.enableCull();
GLStateManager.glPopMatrix();
return true;
}
private void reloadTextures() {
if (mc.renderEngine != null) {
mc.renderEngine.bindTexture(texture);
texW = GL11.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_WIDTH);
texH = GL11.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_HEIGHT);
}
}
@Override
public void onResourceManagerReload(IResourceManager resourceManager) {
reloadTextures();
}
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\rendering\AngelicaBlockSafetyRegistry.java
|
package com.gtnewhorizons.angelica.rendering;
import com.gtnewhorizons.angelica.api.ThreadSafeISBRH;
import com.gtnewhorizons.angelica.api.ThreadSafeISBRHFactory;
import com.gtnewhorizons.angelica.mixins.interfaces.IRenderingRegistryExt;
import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler;
import cpw.mods.fml.client.registry.RenderingRegistry;
import it.unimi.dsi.fastutil.objects.Reference2BooleanMap;
import it.unimi.dsi.fastutil.objects.Reference2BooleanOpenHashMap;
import net.minecraft.block.Block;
import java.util.concurrent.locks.StampedLock;
public class AngelicaBlockSafetyRegistry {
private static final Reference2BooleanMap<Block> BLOCK_SAFETY_MAP = new Reference2BooleanOpenHashMap<>();
private static final Reference2BooleanMap<Block> ISBRH_SAFETY_MAP = new Reference2BooleanOpenHashMap<>();
private static final StampedLock LOCK = new StampedLock();
/**
* This method is threadsafe to read, and threadsafe to write, but NOT if both could happen at the same time.
*/
public static boolean canBlockRenderOffThread(Block block, boolean checkISBRH, boolean shouldPopulate) {
final Reference2BooleanMap<Block> map = checkISBRH ? ISBRH_SAFETY_MAP : BLOCK_SAFETY_MAP;
if (shouldPopulate)
return populateCanRenderOffThread(block, map);
return map.getBoolean(block);
}
private static boolean populateCanRenderOffThread(Block block, Reference2BooleanMap<Block> map) {
final boolean canBeOffThread;
if(map == ISBRH_SAFETY_MAP) {
@SuppressWarnings("deprecation")
final ISimpleBlockRenderingHandler isbrh = ((IRenderingRegistryExt)RenderingRegistry.instance()).getISBRH(block.getRenderType());
canBeOffThread = isbrh != null
&& (isbrh.getClass().isAnnotationPresent(ThreadSafeISBRH.class)
|| isbrh instanceof ThreadSafeISBRHFactory);
} else {
// Check blacklist here
// !(block.getClass().getName().startsWith("com.github.bartimaeusnek."));
canBeOffThread = true;
}
final long stamp = LOCK.writeLock();
try {
map.put(block, canBeOffThread);
} finally {
LOCK.unlock(stamp);
}
return canBeOffThread;
}
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\rendering\AngelicaRenderQueue.java
|
package com.gtnewhorizons.angelica.rendering;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;
import java.util.function.BooleanSupplier;
public class AngelicaRenderQueue {
private static final Thread MAIN_THREAD = Thread.currentThread();
private static final Queue<Runnable> TASKS = new ConcurrentLinkedQueue<>();
private static final Executor EXECUTOR = (runnable) -> {
if(Thread.currentThread() == MAIN_THREAD) {
runnable.run();
} else {
TASKS.add(runnable);
LockSupport.unpark(MAIN_THREAD);
}
};
public static Executor executor() {
return EXECUTOR;
}
public static int processTasks(int max) {
int tasksRun = 0;
while(tasksRun < max) {
Runnable r = TASKS.poll();
if(r == null)
break;
r.run();
tasksRun++;
}
return tasksRun;
}
public static int processTasks() {
return processTasks(Integer.MAX_VALUE);
}
private static final long WAIT_TIME = TimeUnit.MILLISECONDS.toNanos(50);
public static void managedBlock(BooleanSupplier isDone) {
while(!isDone.getAsBoolean()) {
if(AngelicaRenderQueue.processTasks(1) == 0) {
LockSupport.parkNanos(WAIT_TIME);
}
}
}
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\rendering\ItemRenderListManager.java
|
/*
* This file is part of FalseTweaks.
*
* Copyright (C) 2022-2024 FalsePattern
* All Rights Reserved
*
* Modifications by Angelica in accordance with LGPL v3.0
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* FalseTweaks is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FalseTweaks is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with FalseTweaks. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gtnewhorizons.angelica.rendering;
import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator;
import com.gtnewhorizon.gtnhlib.client.renderer.TessellatorManager;
import com.gtnewhorizon.gtnhlib.client.renderer.vao.VAOManager;
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import it.unimi.dsi.fastutil.HashCommon;
import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap;
import java.nio.ByteBuffer;
import lombok.Data;
import lombok.NoArgsConstructor;
import net.minecraft.client.Minecraft;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
public class ItemRenderListManager {
// Least used element is at position 0. This is in theory slightly faster.
private static final Object2ObjectLinkedOpenHashMap<ItemProp, CachedVBO> vboCache = new Object2ObjectLinkedOpenHashMap<>(64);
// Formula: (widthSubdivisions * 2 + heightSubdivisions * 2 + 2) * 4 * vertexSize
// Using 256 as both variables due to enchants, to prevent later re-allocations.
private static ByteBuffer quadBuffer = BufferUtils.createByteBuffer(
(1026 * DefaultVertexFormat.POSITION_TEXTURE_NORMAL.getVertexSize()) << 2
);
// 1 minute
private static final int EXPIRY_TICKS = 1_200;
private static int smallestExpiry;
private static final ItemProp prop = new ItemProp();
public static VertexBuffer pre(float minU, float minV, float maxU, float maxV, int widthSubdivisions, int heightSubdivisions, float thickness) {
prop.set(minU, minV, maxU, maxV, widthSubdivisions, heightSubdivisions, thickness);
if (!vboCache.isEmpty()) {
final CachedVBO vbo = vboCache.getAndMoveToLast(prop);
if (vbo != null) {
final int time = getElapsedTicks();
vbo.render(time);
// Prevent constant map lookups by only storing the expiry of the least recently used entry
if (time > smallestExpiry && time > (smallestExpiry = (vboCache.get(vboCache.firstKey()).expiry + 20))) {
vboCache.removeFirst().delete();
if (!vboCache.isEmpty()) {
smallestExpiry = vboCache.get(vboCache.firstKey()).expiry + 20;
}
}
return null;
}
}
final CachedVBO vbo;
if (vboCache.size() >= AngelicaConfig.itemRendererCacheSize) {
final ItemProp oldestProp = vboCache.firstKey();
vbo = vboCache.removeFirst();
oldestProp.set(prop);
vboCache.put(oldestProp, vbo);
} else {
vbo = new CachedVBO();
vboCache.put(new ItemProp(prop), vbo);
}
vbo.expiry = getElapsedTicks() + EXPIRY_TICKS;
TessellatorManager.startCapturing();
return vbo.vertexBuffer;
}
public static void post(CapturingTessellator tessellator, VertexBuffer vbo) {
final var quads = TessellatorManager.stopCapturingToPooledQuads();
final int size = quads.size();
final int needed = (DefaultVertexFormat.POSITION_TEXTURE_NORMAL.getVertexSize() * size) << 2;
if (quadBuffer.capacity() < needed) {
quadBuffer = BufferUtils.createByteBuffer(HashCommon.nextPowerOfTwo(needed));
}
for (int i = 0; i < size; i++) {
DefaultVertexFormat.POSITION_TEXTURE_NORMAL.writeQuad(quads.get(i), quadBuffer);
}
quadBuffer.flip();
vbo.upload(quadBuffer);
quadBuffer.clear();
tessellator.clearQuads();
vbo.render();
}
private static int getElapsedTicks() {
return Minecraft.getMinecraft().thePlayer.ticksExisted;
}
private static final class CachedVBO {
private VertexBuffer vertexBuffer;
private int expiry;
public CachedVBO() {
this.vertexBuffer = VAOManager.createVAO(DefaultVertexFormat.POSITION_TEXTURE_NORMAL, GL11.GL_QUADS);
}
private void render(int elapsedTicks) {
vertexBuffer.render();
expiry = elapsedTicks + EXPIRY_TICKS;
}
private void delete() {
vertexBuffer.close();
vertexBuffer = null;
}
}
@NoArgsConstructor
@Data
private static final class ItemProp {
private float minU;
private float minV;
private float maxU;
private float maxV;
private int widthSubdivisions;
private int heightSubdivisions;
private float thickness;
public ItemProp(ItemProp old) {
set(
old.minU, old.minV,
old.maxU, old.maxV,
old.widthSubdivisions, old.heightSubdivisions,
old.thickness
);
}
public void set(ItemProp other) {
set(
other.minU, other.minV,
other.maxU, other.maxV,
other.widthSubdivisions, other.heightSubdivisions,
other.thickness
);
}
public void set(float minU, float minV, float maxU, float maxV, int widthSubdivisions, int heightSubdivisions, float thickness) {
this.minU = minU;
this.minV = minV;
this.maxU = maxU;
this.maxV = maxV;
this.widthSubdivisions = widthSubdivisions;
this.heightSubdivisions = heightSubdivisions;
this.thickness = thickness;
}
}
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\rendering\RenderingState.java
|
package com.gtnewhorizons.angelica.rendering;
import lombok.Getter;
import lombok.Setter;
import org.joml.Matrix4f;
import org.joml.Vector3d;
import org.lwjgl.BufferUtils;
import java.nio.FloatBuffer;
public class RenderingState {
public static final RenderingState INSTANCE = new RenderingState();
@Getter
private final Vector3d cameraPosition = new Vector3d();
@Getter
private final FloatBuffer projectionBuffer = BufferUtils.createFloatBuffer(16);
@Getter
private final FloatBuffer modelViewBuffer = BufferUtils.createFloatBuffer(16);
@Getter
private final Matrix4f projectionMatrix = new Matrix4f().identity();
@Getter
private final Matrix4f modelViewMatrix = new Matrix4f().identity();
@Getter
@Setter
private float fov;
public void setCameraPosition(double x, double y, double z) {
cameraPosition.set(x, y, z);
}
public void setProjectionMatrix(FloatBuffer projection) {
projectionMatrix.set(projection);
projectionMatrix.get(0, projectionBuffer);
}
public void setModelViewMatrix(FloatBuffer modelview) {
modelViewMatrix.set(modelview);
modelViewMatrix.get(0, modelViewBuffer);
}
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\utils\AnimationMode.java
|
package com.gtnewhorizons.angelica.utils;
public enum AnimationMode {
NONE,
VISIBLE_ONLY,
ALL
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\utils\AnimationsRenderUtils.java
|
package com.gtnewhorizons.angelica.utils;
import java.util.ArrayDeque;
import com.gtnewhorizons.angelica.mixins.interfaces.IPatchedTextureAtlasSprite;
import com.gtnewhorizons.angelica.mixins.interfaces.ITexturesCache;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.util.IIcon;
import net.minecraft.world.IBlockAccess;
public class AnimationsRenderUtils {
public static void markBlockTextureForUpdate(IIcon icon) {
markBlockTextureForUpdate(icon, null);
}
public static void markBlockTextureForUpdate(IIcon icon, IBlockAccess blockAccess) {
final TextureMap textureMap = Minecraft.getMinecraft().getTextureMapBlocks();
final TextureAtlasSprite textureAtlasSprite = textureMap.getAtlasSprite(icon.getIconName());
if (textureAtlasSprite != null && textureAtlasSprite.hasAnimationMetadata()) {
// null if called by anything but chunk render cache update (for example to get blocks rendered as items in
// inventory)
if (blockAccess instanceof ITexturesCache texturesCache) {
texturesCache.getRenderedTextures().add(textureAtlasSprite);
} else if(textureAtlasSprite instanceof IPatchedTextureAtlasSprite patchedSprite){
patchedSprite.markNeedsAnimationUpdate();
}
}
}
private final static ThreadLocal<ArrayDeque<ITexturesCache>> TEXTURE_CACHE_STACK = ThreadLocal.withInitial(ArrayDeque::new);
public static void onSpriteUsed(IPatchedTextureAtlasSprite sprite) {
ArrayDeque<ITexturesCache> stack = TEXTURE_CACHE_STACK.get();
if (stack == null || stack.isEmpty()) {
// icon was used outside of chunk building, it's probably an item in an inventory or something
sprite.markNeedsAnimationUpdate();
return;
}
stack.peek().track(sprite);
}
public static void pushCache(ITexturesCache cache) {
TEXTURE_CACHE_STACK.get().push(cache);
}
public static void popCache() {
TEXTURE_CACHE_STACK.get().pop();
}
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\utils\BufferUtil.java
|
package com.gtnewhorizons.angelica.utils;
import org.lwjgl.BufferUtils;
import java.nio.FloatBuffer;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAddress;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAllocFloat;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memCopy;
/**
* Utility class for buffer operations in display list commands.
*/
public final class BufferUtil {
private BufferUtil() {} // Prevent instantiation
/**
* Creates a copy of a FloatBuffer.
* The source buffer's position is preserved.
*
* @param src The source buffer to copy
* @return A new FloatBuffer containing a copy of the data
*/
public static FloatBuffer copyBuffer(FloatBuffer src) {
final FloatBuffer dst = BufferUtils.createFloatBuffer(src.remaining());
final int pos = src.position();
dst.put(src);
dst.flip();
src.position(pos);
return dst;
}
/**
* Creates a copy of a direct FloatBuffer using native memory.
* Caller is responsible for freeing the returned buffer with memFree().
*
* @param src Direct FloatBuffer to copy (must be direct)
* @return New direct FloatBuffer with copied data
*/
public static FloatBuffer copyDirectBuffer(FloatBuffer src) {
final int count = src.remaining();
final FloatBuffer dst = memAllocFloat(count);
memCopy(memAddress(src), memAddress(dst), (long) count * Float.BYTES);
return dst;
}
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\utils\Callback.java
|
package com.gtnewhorizons.angelica.utils;
import java.util.concurrent.Callable;
/**
* Both {@link Runnable} and {@link Callable} are meant for off-thread/concurrent execution. This is just a callback, no
* more, no less.
*/
@FunctionalInterface
public interface Callback {
void run();
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\utils\EventUtils.java
|
package com.gtnewhorizons.angelica.utils;
import cpw.mods.fml.common.eventhandler.Event;
import cpw.mods.fml.common.eventhandler.EventPriority;
import cpw.mods.fml.relauncher.ReflectionHelper;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
public class EventUtils {
private static final MethodHandle EVENT_PHASE;
static {
try {
EVENT_PHASE = MethodHandles.publicLookup().unreflectSetter(ReflectionHelper.findField(Event.class, "phase"));
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
public static void clearPhase(Event e) {
try {
EVENT_PHASE.invokeExact(e, (EventPriority)null);
} catch(Throwable ex) {
throw new RuntimeException(ex);
}
}
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\utils\ManagedEnum.java
|
package com.gtnewhorizons.angelica.utils;
public class ManagedEnum<T extends Enum<?>> {
private final T[] allValues;
private T value;
public ManagedEnum(T initialValue) {
if (initialValue == null) throw new IllegalArgumentException();
value = initialValue;
@SuppressWarnings("unchecked")
T[] allValues = (T[]) value.getClass().getEnumConstants();
this.allValues = allValues;
}
public boolean is(T value) {
return this.value == value;
}
public T next() {
value = allValues[(value.ordinal() + 1) % allValues.length];
return value;
}
public void set(T value) {
this.value = value;
}
public void set(int ordinal) {
this.value = allValues[Math.min(Math.max(0, ordinal), allValues.length - 1)];
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ManagedEnum<?> that = (ManagedEnum<?>) o;
return value == that.value;
}
@Override
public int hashCode() {
return value.hashCode();
}
@Override
public String toString() {
return value.toString();
}
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\utils\Mipmaps.java
|
package com.gtnewhorizons.angelica.utils;
public class Mipmaps {
private static final float[] VALS = new float[256];
public static float get(int i) {
return VALS[i & 0xFF];
}
public static int getColorComponent(int one, int two, int three, int four, int bits) {
final float f = Mipmaps.get(one >> bits);
final float g = Mipmaps.get(two >> bits);
final float h = Mipmaps.get(three >> bits);
final float i = Mipmaps.get(four >> bits);
final float j = (float) Math.pow((f + g + h + i) * 0.25, 0.45454545454545453);
return (int) (j * 255.0);
}
static {
for (int i = 0; i < VALS.length; ++i) {
VALS[i] = (float) Math.pow((float) i / 255.0F, 2.2);
}
}
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\zoom\IMouseFilterExt.java
|
package com.gtnewhorizons.angelica.zoom;
public interface IMouseFilterExt {
void angelica$reset();
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\zoom\Zoom.java
|
package com.gtnewhorizons.angelica.zoom;
import cpw.mods.fml.client.registry.ClientRegistry;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.InputEvent;
import lombok.Getter;
import net.minecraft.client.Minecraft;
import net.minecraft.client.settings.KeyBinding;
import net.minecraft.util.MathHelper;
import org.lwjgl.input.Mouse;
public class Zoom {
public static final float ZOOM_MIN = 1.0F;
public static final float ZOOM_MAX = 64.0F;
public static final float ZOOM_STEP = 1.2F;
public static final float ZOOM_DEFAULT = 4.0F;
@Getter
private static float zoom = ZOOM_DEFAULT;
@Getter
private static final KeyBinding zoomKey = new KeyBinding("Zoom", 0, "key.categories.misc");
private static boolean zoomEnabled = false;
public static void init() {
ClientRegistry.registerKeyBinding(zoomKey);
FMLCommonHandler.instance().bus().register(new Zoom());
}
public static boolean isZoomedIn() {
return zoomEnabled;
}
public static void modifyZoom(int eventDWheel) {
if (eventDWheel == 0) return;
zoom = MathHelper.clamp_float((float) (zoom * Math.pow(ZOOM_STEP, Integer.signum(eventDWheel))), ZOOM_MIN, ZOOM_MAX);
}
private static void resetMouseFilters(Minecraft mc) {
if (mc.entityRenderer != null) {
((IMouseFilterExt) mc.entityRenderer.mouseFilterXAxis).angelica$reset();
((IMouseFilterExt) mc.entityRenderer.mouseFilterYAxis).angelica$reset();
}
}
public static void resetZoom() {
final Minecraft mc = Minecraft.getMinecraft();
zoomEnabled = false;
zoom = ZOOM_DEFAULT;
resetMouseFilters(mc);
}
private void handleKeyEvent() {
if (zoomKey.getKeyCode() == 0) return;
final Minecraft mc = Minecraft.getMinecraft();
if (mc.currentScreen != null) return;
if (zoomKey.getIsKeyPressed()) {
zoomEnabled = true;
} else if (zoomEnabled) {
resetZoom();
}
}
@SubscribeEvent
public void onKeyPress(InputEvent.KeyInputEvent e) {
handleKeyEvent();
}
@SubscribeEvent
public void onMouseKeyPress(InputEvent.MouseInputEvent e) {
// MouseInputEvent is also fired on mouse movement, which we don't care about, only mouse button presses, so
// ensure that before any further key processing.
if (Mouse.getEventButton() >= 0) {
handleKeyEvent();
}
}
}
|
Angelica
|
src\main\java\com\gtnewhorizons\angelica\client\font\BatchingFontRenderer.java
|
package com.gtnewhorizons.angelica.client.font;
import com.google.common.collect.ImmutableSet;
import com.gtnewhorizon.gtnhlib.util.font.GlyphReplacements;
import com.gtnewhorizons.angelica.config.FontConfig;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.mixins.interfaces.FontRendererAccessor;
import cpw.mods.fml.client.SplashProgress;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import net.coderbot.iris.gl.program.Program;
import net.coderbot.iris.gl.program.ProgramBuilder;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.util.MathHelper;
import net.minecraft.util.ResourceLocation;
import org.apache.commons.io.IOUtils;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL20;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Comparator;
import java.util.Objects;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.*;
/**
* A batching replacement for {@code FontRenderer}
*
* @author eigenraven
*/
public class BatchingFontRenderer {
/** The underlying FontRenderer object that's being accelerated */
protected FontRenderer underlying;
/** Array of width of all the characters in default.png */
protected int[] charWidth = new int[256];
/** Array of the start/end column (in upper/lower nibble) for every glyph in the /font directory. */
protected byte[] glyphWidth;
/**
* Array of RGB triplets defining the 16 standard chat colors followed by 16 darker version of the same colors for
* drop shadows.
*/
private int[] colorCode;
/** Location of the primary font atlas to bind. */
protected final ResourceLocation locationFontTexture;
private final int AAMode;
private final int AAStrength;
private final int texBoundAttrLocation;
private final int fontShaderId;
final boolean isSGA;
final boolean isSplash;
private static class FontAAShader {
private static Program fontShader = null;
public static Program getProgram() {
if (fontShader == null) {
String vsh, fsh;
try {
fsh = new String(IOUtils.toByteArray(Objects.requireNonNull(FontAAShader.class.getResourceAsStream("/assets/angelica/shaders/fontFilter.fsh"))), StandardCharsets.UTF_8);
vsh = new String(IOUtils.toByteArray(Objects.requireNonNull(FontAAShader.class.getResourceAsStream("/assets/angelica/shaders/fontFilter.vsh"))), StandardCharsets.UTF_8);
} catch (IOException e) {
throw new RuntimeException(e);
}
ProgramBuilder builder = ProgramBuilder.begin("fontFilter", vsh, null, fsh, ImmutableSet.of(0));
fontShader = builder.build();
}
return fontShader;
}
}
public BatchingFontRenderer(FontRenderer underlying, int[] charWidth, byte[] glyphWidth,
int[] colorCode, ResourceLocation locationFontTexture) {
this.underlying = underlying;
this.charWidth = charWidth;
this.glyphWidth = glyphWidth;
this.colorCode = colorCode;
this.locationFontTexture = locationFontTexture;
for (int i = 0; i < 64; i++) {
batchCommandPool.add(new FontDrawCmd());
}
this.isSGA = Objects.equals(this.locationFontTexture.getResourcePath(), "textures/font/ascii_sga.png");
this.isSplash = FontStrategist.isSplashFontRendererActive(underlying);
FontProviderMC.get(this.isSGA).charWidth = this.charWidth;
FontProviderMC.get(this.isSGA).locationFontTexture = this.locationFontTexture;
FontProviderUnicode.get().glyphWidth = this.glyphWidth;
//noinspection deprecation
fontShaderId = FontAAShader.getProgram().getProgramId();
AAMode = GL20.glGetUniformLocation(fontShaderId, "aaMode");
AAStrength = GL20.glGetUniformLocation(fontShaderId, "strength");
texBoundAttrLocation = GL20.glGetAttribLocation(fontShaderId, "texBounds");
}
// === Batched rendering
private int batchDepth = 0;
private int vtxWriterIndex = 0;
private int idxWriterIndex = 0;
private static final int INITIAL_BATCH_SIZE = 256;
private static final ResourceLocation DUMMY_RESOURCE_LOCATION = new ResourceLocation("angelica$dummy",
"this is invalid!");
private FloatBuffer batchVtxPositions = memAllocFloat(INITIAL_BATCH_SIZE * 2);
private ByteBuffer batchVtxColors = memAlloc(INITIAL_BATCH_SIZE * 4);
private FloatBuffer batchVtxTexCoords = memAllocFloat(INITIAL_BATCH_SIZE * 2);
private IntBuffer batchIndices = memAllocInt(INITIAL_BATCH_SIZE / 2 * 3);
private FloatBuffer batchVtxTexBounds = memAllocFloat(INITIAL_BATCH_SIZE * 4);
private final ObjectArrayList<FontDrawCmd> batchCommands = ObjectArrayList.wrap(new FontDrawCmd[64], 0);
private final ObjectArrayList<FontDrawCmd> batchCommandPool = ObjectArrayList.wrap(new FontDrawCmd[64], 0);
private int blendSrcRGB = GL11.GL_SRC_ALPHA;
private int blendDstRGB = GL11.GL_ONE_MINUS_SRC_ALPHA;
/** */
private void pushVtx(float x, float y, int rgba, float u, float v, float uMin, float uMax, float vMin, float vMax) {
final int oldCap = batchVtxPositions.capacity() / 2;
if (vtxWriterIndex >= oldCap) {
final int newCap = oldCap * 2;
batchVtxPositions = memRealloc(batchVtxPositions, newCap * 2);
batchVtxColors = memRealloc(batchVtxColors, newCap * 4);
batchVtxTexCoords = memRealloc(batchVtxTexCoords, newCap * 2);
batchVtxTexBounds = memRealloc(batchVtxTexBounds, newCap * 4);
final int oldIdxCap = batchIndices.capacity();
final int newIdxCap = oldIdxCap * 2;
batchIndices = memRealloc(batchIndices, newIdxCap);
}
final int idx = vtxWriterIndex;
final int idx2 = idx * 2;
final int idx4 = idx * 4;
batchVtxPositions.put(idx2, x);
batchVtxPositions.put(idx2 + 1, y);
// 0xAARRGGBB
batchVtxColors.put(idx4, (byte) ((rgba >> 16) & 0xFF));
batchVtxColors.put(idx4 + 1, (byte) ((rgba >> 8) & 0xFF));
batchVtxColors.put(idx4 + 2, (byte) (rgba & 0xFF));
batchVtxColors.put(idx4 + 3, (byte) ((rgba >> 24) & 0xFF));
batchVtxTexCoords.put(idx2, u);
batchVtxTexCoords.put(idx2 + 1, v);
batchVtxTexBounds.put(idx4, uMin);
batchVtxTexBounds.put(idx4 + 1, uMax);
batchVtxTexBounds.put(idx4 + 2, vMin);
batchVtxTexBounds.put(idx4 + 3, vMax);
vtxWriterIndex++;
}
private void pushUntexRect(float x, float y, float w, float h, int rgba) {
final int vtxId = vtxWriterIndex;
pushVtx(x, y, rgba, 0, 0, 0, 0, 0, 0);
pushVtx(x, y + h, rgba, 0, 0, 0, 0, 0, 0);
pushVtx(x + w, y, rgba, 0, 0, 0, 0, 0, 0);
pushVtx(x + w, y + h, rgba, 0, 0, 0, 0, 0, 0);
pushQuadIdx(vtxId);
}
private void pushTexRect(float x, float y, float w, float h, float itOff, int rgba, float uStart, float vStart, float uSz, float vSz) {
final int vtxId = vtxWriterIndex;
pushVtx(x + itOff, y, rgba, uStart, vStart, uStart, uStart + uSz, vStart, vStart + vSz);
pushVtx(x - itOff, y + h, rgba, uStart, vStart + vSz, uStart, uStart + uSz, vStart, vStart + vSz);
pushVtx(x + itOff + w, y, rgba, uStart + uSz, vStart, uStart, uStart + uSz, vStart, vStart + vSz);
pushVtx(x - itOff + w, y + h, rgba, uStart + uSz, vStart + vSz, uStart, uStart + uSz, vStart, vStart + vSz);
pushQuadIdx(vtxId);
}
private int pushQuadIdx(int startV) {
final int idx = idxWriterIndex;
batchIndices.put(idx, startV);
batchIndices.put(idx + 1, startV + 1);
batchIndices.put(idx + 2, startV + 2);
//
batchIndices.put(idx + 3, startV + 2);
batchIndices.put(idx + 4, startV + 1);
batchIndices.put(idx + 5, startV + 3);
idxWriterIndex += 6;
return idx;
}
private void pushDrawCmd(int startIdx, int idxCount, ResourceLocation texture, boolean isUnicode) {
if (!batchCommands.isEmpty()) {
final FontDrawCmd lastCmd = batchCommands.get(batchCommands.size() - 1);
final int prevEndVtx = lastCmd.startVtx + lastCmd.idxCount;
if (prevEndVtx == startIdx && lastCmd.texture == texture) {
// Coalesce into one
lastCmd.idxCount += idxCount;
return;
}
}
if (batchCommandPool.isEmpty()) {
for (int i = 0; i < 64; i++) {
batchCommandPool.add(new FontDrawCmd());
}
}
final FontDrawCmd cmd = batchCommandPool.pop();
cmd.reset(startIdx, idxCount, texture, isUnicode);
batchCommands.add(cmd);
}
private static final class FontDrawCmd {
public int startVtx;
public int idxCount;
public boolean isUnicode;
public ResourceLocation texture;
public void reset(int startVtx, int vtxCount, ResourceLocation texture, boolean isUnicode) {
this.startVtx = startVtx;
this.idxCount = vtxCount;
this.texture = texture;
this.isUnicode = isUnicode;
}
@Override
public boolean equals(Object obj) {
if (obj == this) return true;
if (obj == null || obj.getClass() != this.getClass()) return false;
var that = (FontDrawCmd) obj;
return this.startVtx == that.startVtx && this.idxCount == that.idxCount && Objects.equals(this.texture,
that.texture);
}
@Override
public int hashCode() {
return Objects.hash(startVtx, idxCount, texture);
}
@Override
public String toString() {
return "FontDrawCmd["
+ "startVtx="
+ startVtx
+ ", "
+ "vtxCount="
+ idxCount
+ ", "
+ "texture="
+ texture
+ ']';
}
public static final Comparator<FontDrawCmd> DRAW_ORDER_COMPARATOR = Comparator.comparing((FontDrawCmd fdc) -> fdc.texture,
Comparator.nullsLast(Comparator.comparing(ResourceLocation::getResourceDomain)
.thenComparing(ResourceLocation::getResourcePath))).thenComparing(fdc -> fdc.startVtx);
}
/**
* Starts a new batch of font rendering operations. Can be called from within another batch with a matching end, to
* allow for easier optimizing of blocks of font rendering code.
*/
public void beginBatch() {
if (batchDepth == Integer.MAX_VALUE) {
throw new StackOverflowError("More than Integer.MAX_VALUE nested font rendering batch operations");
}
batchDepth++;
}
public void endBatch() {
if (batchDepth <= 0) {
batchDepth = 0;
return;
}
batchDepth--;
if (batchDepth == 0) {
// We finished any nested batches
flushBatch();
}
}
int lastActiveProgram;
int fontAAModeLast = -1;
int fontAAStrengthLast = -1;
private void flushBatch() {
final int prevProgram = GLStateManager.glGetInteger(GL20.GL_CURRENT_PROGRAM);
// Sort&Draw
batchCommands.sort(FontDrawCmd.DRAW_ORDER_COMPARATOR);
final boolean isTextureEnabledBefore = GLStateManager.glIsEnabled(GL11.GL_TEXTURE_2D);
final int boundTextureBefore = GLStateManager.glGetInteger(GL11.GL_TEXTURE_BINDING_2D);
boolean textureChanged = false;
ResourceLocation lastTexture = DUMMY_RESOURCE_LOCATION;
GLStateManager.enableTexture();
GLStateManager.enableAlphaTest();
GLStateManager.enableBlend();
GLStateManager.tryBlendFuncSeparate(blendSrcRGB, blendDstRGB, GL11.GL_ONE, GL11.GL_ZERO);
GLStateManager.glShadeModel(GL11.GL_FLAT);
final boolean canUseAA = FontConfig.fontAAMode != 0 && prevProgram == 0;
if (canUseAA) {
GL20.glVertexAttribPointer(texBoundAttrLocation, 4, false, 0, batchVtxTexBounds);
GL20.glEnableVertexAttribArray(texBoundAttrLocation);
lastActiveProgram = prevProgram;
GLStateManager.glUseProgram(fontShaderId);
if (FontConfig.fontAAMode != fontAAModeLast) {
fontAAModeLast = FontConfig.fontAAMode;
GL20.glUniform1i(AAMode, FontConfig.fontAAMode);
}
if (FontConfig.fontAAStrength != fontAAStrengthLast) {
fontAAStrengthLast = FontConfig.fontAAStrength;
GL20.glUniform1f(AAStrength, FontConfig.fontAAStrength / 120.f);
}
}
GL13.glClientActiveTexture(GL13.GL_TEXTURE0);
GL11.glTexCoordPointer(2, 0, batchVtxTexCoords);
GL11.glEnableClientState(GL11.GL_TEXTURE_COORD_ARRAY);
GL11.glColorPointer(4, GL11.GL_UNSIGNED_BYTE, 0, batchVtxColors);
GL11.glEnableClientState(GL11.GL_COLOR_ARRAY);
GL11.glVertexPointer(2, 0, batchVtxPositions);
GL11.glEnableClientState(GL11.GL_VERTEX_ARRAY);
GLStateManager.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
GL11.glDisableClientState(GL11.GL_NORMAL_ARRAY);
GL11.glNormal3f(0.0f, 0.0f, 1.0f);
// Use plain for loop to avoid allocations
final FontDrawCmd[] cmdsData = batchCommands.elements();
final int cmdsSize = batchCommands.size();
for (int i = 0; i < cmdsSize; i++) {
final FontDrawCmd cmd = cmdsData[i];
if (!Objects.equals(lastTexture, cmd.texture)) {
if (lastTexture == null) {
GLStateManager.glEnable(GL11.GL_TEXTURE_2D);
} else if (cmd.texture == null) {
GLStateManager.glDisable(GL11.GL_TEXTURE_2D);
}
if (cmd.texture != null) {
((FontRendererAccessor) underlying).angelica$bindTexture(cmd.texture);
textureChanged = true;
}
lastTexture = cmd.texture;
}
batchIndices.limit(cmd.startVtx + cmd.idxCount);
batchIndices.position(cmd.startVtx);
GL11.glDrawElements(GL11.GL_TRIANGLES, batchIndices);
}
if (canUseAA) {
GLStateManager.glUseProgram(lastActiveProgram);
GL20.glDisableVertexAttribArray(texBoundAttrLocation);
}
GL11.glDisableClientState(GL11.GL_TEXTURE_COORD_ARRAY);
GL11.glDisableClientState(GL11.GL_COLOR_ARRAY);
GL11.glDisableClientState(GL11.GL_VERTEX_ARRAY);
if (isTextureEnabledBefore) {
GLStateManager.glEnable(GL11.GL_TEXTURE_2D);
}
if (textureChanged) {
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, boundTextureBefore);
}
// Clear for the next batch
batchCommandPool.addAll(batchCommands);
batchCommands.clear();
vtxWriterIndex = 0;
idxWriterIndex = 0;
batchIndices.limit(batchIndices.capacity());
batchIndices.position(0);
}
// === Actual text mesh generation
public static boolean charInRange(char what, char fromInclusive, char toInclusive) {
return (what >= fromInclusive) && (what <= toInclusive);
}
public boolean forceDefaults() {
return this.isSGA || this.isSplash;
}
public float getGlyphScaleX() {
return forceDefaults() ? 1 : (float) (FontConfig.glyphScale * Math.pow(2, FontConfig.glyphAspect));
}
public float getGlyphScaleY() {
return forceDefaults() ? 1 : (float) (FontConfig.glyphScale / Math.pow(2, FontConfig.glyphAspect));
}
public float getGlyphSpacing() {
return forceDefaults() ? 0 : FontConfig.glyphSpacing;
}
public float getWhitespaceScale() {
return forceDefaults() ? 1 : FontConfig.whitespaceScale;
}
public float getShadowOffset() {
return forceDefaults() ? 1 : FontConfig.fontShadowOffset;
}
private static final char FORMATTING_CHAR = 167; // §
public float drawString(final float anchorX, final float anchorY, final int color, final boolean enableShadow,
final boolean unicodeFlag, final CharSequence string, int stringOffset, int stringLength) {
// noinspection SizeReplaceableByIsEmpty
if (string == null || string.length() == 0) {
return anchorX + (enableShadow ? 1.0f : 0.0f);
}
final int shadowColor = (color & 0xfcfcfc) >> 2 | color & 0xff000000;
FontProviderMC.get(this.isSGA).charWidth = this.charWidth;
FontProviderMC.get(this.isSGA).locationFontTexture = this.locationFontTexture;
this.beginBatch();
float curX = anchorX;
try {
final int totalStringLength = string.length();
stringOffset = MathHelper.clamp_int(stringOffset, 0, totalStringLength);
stringLength = MathHelper.clamp_int(stringLength, 0, totalStringLength - stringOffset);
if (stringLength <= 0) {
return 0;
}
final int stringEnd = stringOffset + stringLength;
int curColor = color;
int curShadowColor = shadowColor;
boolean curItalic = false;
boolean curRandom = false;
boolean curBold = false;
boolean curStrikethrough = false;
boolean curUnderline = false;
float glyphScaleY = getGlyphScaleY();
float heightNorth = anchorY + (underlying.FONT_HEIGHT - 1.0f) * (0.5f - glyphScaleY / 2);
final float underlineY = heightNorth + (underlying.FONT_HEIGHT - 1.0f) * glyphScaleY;
float underlineStartX = 0.0f;
float underlineEndX = 0.0f;
final float strikethroughY = heightNorth + ((float) (underlying.FONT_HEIGHT / 2) - 1.0f) * glyphScaleY;
float strikethroughStartX = 0.0f;
float strikethroughEndX = 0.0f;
for (int charIdx = stringOffset; charIdx < stringEnd; charIdx++) {
char chr = string.charAt(charIdx);
if (chr == FORMATTING_CHAR && (charIdx + 1) < stringEnd) {
final char fmtCode = Character.toLowerCase(string.charAt(charIdx + 1));
charIdx++;
if (curUnderline && underlineStartX != underlineEndX) {
final int ulIdx = idxWriterIndex;
pushUntexRect(underlineStartX, underlineY, underlineEndX - underlineStartX, glyphScaleY, curColor);
pushDrawCmd(ulIdx, 6, null, false);
underlineStartX = underlineEndX;
}
if (curStrikethrough && strikethroughStartX != strikethroughEndX) {
final int ulIdx = idxWriterIndex;
pushUntexRect(
strikethroughStartX,
strikethroughY,
strikethroughEndX - strikethroughStartX,
glyphScaleY,
curColor);
pushDrawCmd(ulIdx, 6, null, false);
strikethroughStartX = strikethroughEndX;
}
final boolean is09 = charInRange(fmtCode, '0', '9');
final boolean isAF = charInRange(fmtCode, 'a', 'f');
if (is09 || isAF) {
curRandom = false;
curBold = false;
curStrikethrough = false;
curUnderline = false;
curItalic = false;
final int colorIdx = is09 ? (fmtCode - '0') : (fmtCode - 'a' + 10);
final int rgb = this.colorCode[colorIdx];
curColor = (curColor & 0xFF000000) | (rgb & 0x00FFFFFF);
final int shadowRgb = this.colorCode[colorIdx + 16];
curShadowColor = (curShadowColor & 0xFF000000) | (shadowRgb & 0x00FFFFFF);
} else if (fmtCode == 'k') {
curRandom = true;
} else if (fmtCode == 'l') {
curBold = true;
} else if (fmtCode == 'm') {
curStrikethrough = true;
strikethroughStartX = curX - 1.0f;
strikethroughEndX = strikethroughStartX;
} else if (fmtCode == 'n') {
curUnderline = true;
underlineStartX = curX - 1.0f;
underlineEndX = underlineStartX;
} else if (fmtCode == 'o') {
curItalic = true;
} else if (fmtCode == 'r') {
curRandom = false;
curBold = false;
curStrikethrough = false;
curUnderline = false;
curItalic = false;
curColor = color;
curShadowColor = shadowColor;
}
continue;
}
if (FontConfig.enableCustomFont) {
String chrReplacement = GlyphReplacements.customGlyphs.get(String.valueOf(chr));
if (chrReplacement != null) {
chr = chrReplacement.charAt(0);
}
}
if (curRandom) {
chr = FontProviderMC.get(this.isSGA).getRandomReplacement(chr);
}
FontProvider fontProvider = FontStrategist.getFontProvider(this, chr, FontConfig.enableCustomFont, unicodeFlag);
heightNorth = anchorY + (underlying.FONT_HEIGHT - 1.0f) * (0.5f - glyphScaleY * fontProvider.getYScaleMultiplier() / 2);
float heightSouth = (underlying.FONT_HEIGHT - 1.0f) * glyphScaleY * fontProvider.getYScaleMultiplier();
// Check ASCII space, NBSP, NNBSP
if (chr == ' ' || chr == '\u00A0' || chr == '\u202F') {
curX += 4 * this.getWhitespaceScale();
continue;
}
final float uStart = fontProvider.getUStart(chr);
final float vStart = fontProvider.getVStart(chr);
final float xAdvance = fontProvider.getXAdvance(chr) * getGlyphScaleX();
final float glyphW = fontProvider.getGlyphW(chr) * getGlyphScaleX();
final float uSz = fontProvider.getUSize(chr);
final float vSz = fontProvider.getVSize(chr);
final float itOff = curItalic ? 1.0F : 0.0F; // italic offset
final float shadowOffset = fontProvider.getShadowOffset();
final float xShift = (fontProvider instanceof FontProviderCustom ? getGlyphScaleX() * FontConfig.customFontScale : 0.0f); // corrective factor to improve text alignment
final int shadowCopies = FontConfig.shadowCopies;
final int boldCopies = FontConfig.boldCopies;
final ResourceLocation texture = fontProvider.getTexture(chr);
final int idxId = idxWriterIndex;
if (enableShadow) {
for (int n = 1; n <= shadowCopies; n++) {
final float shadowOffsetPart = shadowOffset * ((float) n / shadowCopies);
pushTexRect(curX + shadowOffsetPart - xShift, heightNorth + shadowOffsetPart, glyphW - 1.0f, heightSouth, itOff, curShadowColor, uStart, vStart, uSz, vSz);
if (curBold) {
pushTexRect(curX + 2.0f * shadowOffsetPart - xShift, heightNorth + shadowOffsetPart, glyphW - 1.0f, heightSouth, itOff, curShadowColor, uStart, vStart, uSz, vSz);
}
}
}
pushTexRect(curX - xShift, heightNorth, glyphW - 1.0f, heightSouth, itOff, curColor, uStart, vStart, uSz, vSz);
if (curBold) {
for (int n = 1; n <= boldCopies; n++) {
final float shadowOffsetPart = shadowOffset * ((float) n / boldCopies);
pushTexRect(curX + shadowOffsetPart - xShift, heightNorth, glyphW - 1.0f, heightSouth, itOff, curColor, uStart, vStart, uSz, vSz);
}
}
/*
Vertex-per-char counts for different configurations
default: 4
shadow only: 4(1 + shadowCopies)
bold only: 4(1 + boldCopies)
both: 4(1 + 2 * shadowCopies + boldCopies)
*/
int charCount = 1;
if (enableShadow) { charCount += shadowCopies * (curBold ? 2 : 1); }
if (curBold) { charCount += boldCopies; }
final int vtxCount = 4 * charCount;
pushDrawCmd(idxId, vtxCount / 2 * 3, texture, chr > 255);
curX += (xAdvance + (curBold ? shadowOffset : 0.0f)) + getGlyphSpacing();
underlineEndX = curX;
strikethroughEndX = curX;
}
if (curUnderline && underlineStartX != underlineEndX) {
final int ulIdx = idxWriterIndex;
pushUntexRect(underlineStartX, underlineY, underlineEndX - underlineStartX, glyphScaleY, curColor);
pushDrawCmd(ulIdx, 6, null, false);
}
if (curStrikethrough && strikethroughStartX != strikethroughEndX) {
final int ulIdx = idxWriterIndex;
pushUntexRect(
strikethroughStartX,
strikethroughY,
strikethroughEndX - strikethroughStartX,
glyphScaleY,
curColor);
pushDrawCmd(ulIdx, 6, null, false);
}
} finally {
this.endBatch();
}
return curX + (enableShadow ? 1.0f : 0.0f);
}
public float getCharWidthFine(char chr) {
if (chr == FORMATTING_CHAR) { return -1; }
if (chr == ' ' || chr == '\u00A0' || chr == '\u202F') {
return 4 * this.getWhitespaceScale();
}
FontProvider fp = FontStrategist.getFontProvider(this, chr, FontConfig.enableCustomFont, underlying.getUnicodeFlag());
return fp.getXAdvance(chr) * this.getGlyphScaleX();
}
public void overrideBlendFunc(int srcRgb, int dstRgb) {
blendSrcRGB = srcRgb;
blendDstRGB = dstRgb;
}
public void resetBlendFunc() {
blendSrcRGB = GL11.GL_SRC_ALPHA;
blendDstRGB = GL11.GL_ONE_MINUS_SRC_ALPHA;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.