Compare commits

...

21 commits
v0.1.3 ... main

Author SHA1 Message Date
88ab736519
Update links to the new GitHub account
Some checks failed
CI / backend (cargo test + clippy) (push) Has been cancelled
CI / frontend (lint + test + build) (push) Has been cancelled
CI / mod (gradle test + checkFolderLimit) (push) Has been cancelled
2026-10-25 19:15:06 +01:00
0f1709f25c
wip(spatialgui): isolate screen render state via second GuiRenderer
Some checks failed
CI / backend (cargo test + clippy) (push) Failing after 1m19s
CI / frontend (lint + test + build) (push) Failing after 27s
CI / mod (gradle test + checkFolderLimit) (push) Successful in 1m56s
Also repairs origin/main: commit 39b270b1 accidentally registered two
SpatialGui mixins in lovisual.mixins.json without committing their
sources; this commit ships them.

Refactors the SpatialGui capture path to follow the upstream
Spatial-GUI architecture. Instead of cancelling and re-targeting the
main GuiRenderer.draw() pass (which required shadowing private fields
and rebuilding the projection matrices), the open screen is now
extracted into an isolated GuiRenderState + GuiRenderer pair owned by
SpatialGuiCapture:

- GuiSpatialExtractMixin @Redirects Screen.extractRenderStateWithTooltipAndSubtitles
  inside Gui.extractRenderState: while SpatialGui.isCapturing(), the
  screen is extracted into SpatialGuiCapture.extractScreen() using a
  private GuiRenderState instead of the vanilla main state, so the HUD
  pass no longer sees the screen content.
- GameRendererSpatialGuiMixin injects twice around GameRenderer.render:
  just before GuiRenderer.render() it resizes and clears the capture
  texture to transparent from the frame's WindowRenderState, and at
  TAIL it runs the isolated renderer's render()+endFrame() so the
  screen's draw list executes into the capture texture once the main
  HUD pass is done.
- GuiRendererCaptureMixin is now a @ModifyArg on the target argument of
  executeDrawRange inside GuiRenderer.draw(): if the instance is the
  isolated one, the target is swapped for SpatialGuiCapture.target();
  the vanilla main renderer keeps its normal framebuffer untouched.

SpatialGuiCapture gains screenRenderState, screenGuiRenderer, and the
extractScreen/renderIsolatedFrame/clearTransparent/target helpers.
SpatialGui.onRenderWorldEngine gets DebugLog.renderThreadOnChange
traces at each early-return branch (noLevel, closed, captureNotReady,
noTextureView, alpha0, published, closing, mesh) so plane publishing
can be diagnosed from a log without a debugger.

Docstring in SpatialGui updated to describe the new pipeline. Message
kept wip: this pass compiles clean and is behaviour-plausible, but I
have not run it against a live Minecraft session this turn.
2026-10-12 23:05:30 +02:00
4fce425dcd
feat(frontend): avatar crop dialog (viewport 320, wheel/pinch/keyboard, guides+shade, previews, dirty guard)
Some checks failed
CI / backend (cargo test + clippy) (push) Failing after 1m21s
CI / frontend (lint + test + build) (push) Failing after 24s
CI / mod (gradle test + checkFolderLimit) (push) Successful in 1m57s
Rebuilds the "pick a photo" flow around an Edit Image modal, matching every
product surveyed in the 2026-10 avatar-settings research (Discord, Google,
Slack, Figma, Cropper.js playground). Before: 240 px circular viewport with
no visible crop frame, a single range slider, and no way to close with the
keyboard — the direct reason the previous version felt unfinished.

cropMath: VIEWPORT=320, OUTPUT_SIZE=512 (matches Slack min), plus wheelZoom
(exp so scroll up then down returns to the same zoom, unlike linear),
pinchZoom (ratio of two-pointer distance), PAN_STEP/ZOOM_STEP for keyboard,
PREVIEW_SIZES for the "how others see it" column.

AvatarCropper is now a pure canvas: pointer capture for pan, two-pointer
tracking for pinch, wheel handler with exponential zoom, tabIndex=0 +
onKeyDown for arrows/+/-/0, a Reset button, and a visual frame with
rule-of-thirds guides (40 % opacity) and an inset box-shadow that dims the
corners outside the round target — so the user actually sees what falls in
the file. Cancel/Confirm live in the dialog; dirty signal and current
CropState bubble up via props.

AvatarEditDialog is a portal: bg-black/60 backdrop with click-to-close,
role=dialog + aria-modal, initial focus into the card, ESC closes, X button
in the header. If the user has panned/zoomed (dirty), closing prompts for
confirmation. Header shows file.name + size + the accepted-format hint
previously only surfaced after a failed upload. Right column renders 3 live
previews at 128/64/32 px so the small HUD nameplate treatment is visible
before upload. Progress bar and error notice moved inside so the user does
not have to look away during a slow upload.

AvatarUpload picks the dialog instead of the raw cropper; two-step
"Remove avatar" from the previous commit is unchanged.

Tests: 5 new cropMath cases (wheel symmetric, wheel clamps both ends, pinch
ratio, pinch guards zero baseline). Existing 140 stay green (145 total),
tsc clean, oxlint 0/0.

Not yet: no dep on react-easy-crop — own code as planned. No focus trap
beyond initial focus + ESC (dialog traps implicitly via portal + backdrop
covering). Rotate is still missing — deliberately, since Discord does not
ship it either and extending sourceRect for theta would complicate the
preview pass.
2026-10-12 22:51:40 +02:00
5e76b6176a
feat(frontend): 'Remove avatar' button wired to DELETE /avatars
Part of the avatar-settings rebuild (research: every product except Figma
ships a remove button; Figma gets complaints for missing it). Backend DELETE
route shipped in the previous commit.

- api.ts: removeAvatar() calls DELETE /avatars. Cache invalidation lives in
  the caller so button-side side effects (progress state, history tick) can
  chain in the same handler.
- AvatarUpload: 'Удалить аватар' / 'Remove avatar' appears in the same row as
  'Change' and 'Recrop' when an avatar is set. Two-step inline confirm:
  first click arms and swaps the label to 'Точно удалить?' with an ember
  border, second click sends DELETE. The armed state auto-reverts after 4 s
  so a forgotten armed button never stays one click from destructive.
- i18n: avatar.remove / .removeConfirm / .removed / .removeFailed in ru+en.
  en.ts uses , so a missing key on
  either side would fail the type check.

Not yet: a real Modal with X / ESC / backdrop (comes with the AvatarEditDialog
chunk), preview-in-3-sizes, and cropper keyboard/wheel/pinch. Tests stay at
140/140, tsc and oxlint clean.
2026-10-12 22:44:51 +02:00
a597425e45
feat(backend): DELETE /avatars removes the row and the S3 object
Frontend "Remove avatar" needs a way to clear the current user's picture
without uploading a placeholder. Adds the missing route.

- S3Storage::delete wraps aws_sdk_s3 DeleteObject. MinIO's delete is
  idempotent for missing keys, so a stray miss is silent.
- repo::clear_avatar returns true when a row existed so the handler can decide
  whether to also try the S3 delete (skip for users without an avatar).
- handlers::delete is authenticated (GatewayIdentity) and always returns 204,
  matching how the frontend button should behave after a repeat click.
  S3 delete is best-effort: if MinIO is unreachable we already committed the
  DB row removal and log a warn — the object becomes orphaned but is not
  served, because serve() looks up keys via the DB, not by URL.
- Route registered on the existing avatar_routes Router.
- 3 tests: happy path (post-then-delete → count==0), idempotent no-op,
  401 without identity.
2026-10-12 22:42:50 +02:00
d5f17eb0ac
refactor(mod): dispatch RenderBackendOps.current() by active backend (Stage 4 kickoff)
Stage 4 Vulkan groundwork. Before this, RenderBackendOps.current() unconditionally
returned GlRenderBackendOps.INSTANCE with a 'Stage 3-prep' comment. Under Vulkan
the GL impl is still harmless (its methods all short-circuit on OptimizeToggles
and the GL mixins never fire), but the interface lied about the active backend.

- New misc/optimize/vulkan/VulkanRenderBackendOps: singleton, no-op stub, all
  *Supported() return false, cache/map methods do nothing. This is the skeleton
  the Stage 4 items (persistent VkPipelineCache, VulkanRenderPass state cache)
  will grow into.
- RenderBackendOps.current() inspects RenderSystem.getDevice().getClass().getName()
  and returns VulkanRenderBackendOps for com.mojang.blaze3d.vulkan.* devices,
  GlRenderBackendOps otherwise. Class-name check (not instanceof) so this method
  itself does not force linking of GlDevice/VulkanDevice.
- Wrapped getDevice() in try/catch: unit tests call current() before RenderSystem
  has a device and previously took the GL path; now they still do via the fallback.

Doc: Stage 4 kickoff entry in the changelog.
2026-10-12 22:10:10 +02:00
39b270b108
perf(mod): extended GL state cache for glUseProgram + glBindVertexArray
Stage 3 'Дополнительные GL-оптимизации' item 1. GlStateManager bytecode in
26.2 (com.mojang.blaze3d.opengl.GlStateManager) shows every other GL bind
(texture, blend, depth, cull, scissor, framebuffer) is already absorbed by
vanilla's BLEND/DEPTH/CULL/SCISSOR/TEXTURES/COLOR_MASK/readFbo/writeFbo state
arrays, but _glUseProgram and _glBindVertexArray reach GL33C every time. Cache
those two slots and skip the redundant driver call.

GlStateCache holds (program, vao) with UNKNOWN=-1 as the safe state (never
short-circuits a real id). GlStateManagerCacheMixin @Inject HEAD cancellable
on both _glUseProgram and _glBindVertexArray; @Inject HEAD on glDeleteProgram
resets because the driver may recycle ids. Gated by micro_opts, so switching
micro-opts off also drops the cache (the mixin resets when the gate is off).
Optimize.onDisable also calls GlStateCache.reset().

Mixins/optimize/gl/ hits the 4-file folder limit, so the mixin lives under
mixins/optimize/gl/state/. Render/engine/optimize/gl/ hits the same limit,
holder is in render/engine/optimize/gl/state/.

6 new tests cover UNKNOWN start, mark/already-bound round trip per slot, slot
independence, id-reuse and '0 is a valid id'. Doc: mark the item ✅ partial
(only these two sites are safe to add; the other three would duplicate
vanilla's caches and hurt).
2026-10-12 22:05:05 +02:00
e85c4fc10a
feat(mod): parallel-particles plumbing (CORES>=4 auto + -D tri-state)
Stage 1 item 4 from optimize-layer-design.md, simplified to what the
reference does (auto|true|false) instead of the original 'measure first'
plan. Workers now holds the resolved flag:
- Workers.PARALLEL_MIN_CORES = 4 gate for AUTO mode
- Workers.configureParallelParticles(Boolean forced, boolean moduleEnabled)
- Workers.shouldParallelParticles() read by the future particle-extraction
  mixin (26.2 QuadParticleGroup/SpriteBillboardParticle wiring is separate)
- Workers.resetParallelParticles() called by Optimize.onDisable

Optimize gains a parallel_particles BooleanValue (default true = AUTO).
OptimizePropertyBridge parses -Dlovisual.opt.parallel_particles as tri-state:
null (unset or 'auto' -> defer to module + cores gate), TRUE, FALSE;
the key is now part of OVERRIDE_KEYS so hasOverrides() sees it and toString()
includes it.

Docs: 'Что делаем лучше' item 4 marked done — no measurement gate, matching
the new plan direction.

Tests: 5 new WorkersTest cases for resolveParallelParticles + configure/reset
round trip; 4 new OptimizePropertyBridgeTest cases for the tri-state parser
(unset / explicit 'auto' / forced true|false / hasOverrides pickup). gradle
compileJava compileTestJava test checkFolderLimit green.
2026-10-12 21:49:12 +02:00
ecde09560d
refactor(mod): merge FPS Optimizer cuts into Optimize, drop OutlineTracker
Adds five visible-cut switches to the misc/Optimize module (no_particles,
no_menu_background, no_bloom, entity_cull + entity_cull_distance) with
call-site helpers. Retargets EntityRenderDispatcherMixin, MenuBackgroundRenderer
and every bloomDisabled() call site (TrailsParticles, HitParticleHelper,
WorldParticlesFunnel, TargetEspCrystalRenderer, PredictionsWorldRenderer) to
Optimize. Blur2D drops its FpsOptimizer glass gate — the existing
OptimizeState.isNoGlass() already covers it. Deletes the standalone
visuals/optimization/FpsOptimizer module and misc/optimize/world/OutlineTracker
with its LevelRendererOutlineMixin (and its test).

Lang: consolidate module.optimize.description (fixes duplicate key), move the
five fpsoptimizer.* setting labels under optimize.*, drop fpsoptimizer.name/
description. lovisual.mixins.json: unregister the deleted mixin.

Docs: refresh optimize-layer-design.md status header; drop the 'we measure on
Windows before enabling' gate — universal-wins GL/Vulkan items go behind
default-off switches, benchmarks are optional and not blocking; note the
stage-3 p.9 (no_item_sort / item_single_copy) block is API-driven, not
measurement-driven; mark stage 4 in progress.
2026-10-12 21:03:03 +02:00
645896ca4b
feat(mod): Stage 3 steps 1-8 — DrawStats, SharedDepthFbos, AnimFreeze, ItemLod/Bounds, HudCache, raw vertices, ParallelModels 2026-10-12 14:51:41 +02:00
LoVisual AI
8ef46e4560
feat(mod): Stage 3 (continued 3) — ParticleMixin + BlockEntityRenderStateMixin + ChestRendererMixin
Some checks failed
CI / backend (cargo test + clippy) (push) Successful in 3m5s
CI / frontend (lint + test + build) (push) Failing after 27s
CI / mod (gradle test + checkFolderLimit) (push) Successful in 2m36s
Per mod/docs/optimize-layer-design.md Stage 3 (continued). Three more mixin'ов
that consume the Stage 3-continued-2 contract mixins (CachedLight, TickCached)
on actual renderers, plus the ParticleMixin that adds its own per-particle
light cache + far-particle physics skip.

mixins/optimize/particle/ParticleMixin.java:
- @Inject HEAD/RETURN on Particle.getLightCoords — caches the per-particle
  light lookup by game tick (light only changes on tick boundaries). Gated
  on the Stage 1 'particleLight' toggle.
- @Inject HEAD/RETURN on Particle.move — temporarily sets hasPhysics=false
  for far particles (>16 blocks from camera) and three always-skip
  subclasses (BaseAshSmokeParticle, CampfireSmokeParticle,
  BubbleColumnUpParticle). Gated on the 'particlePhysics' toggle.
- Ported from zako.opt.mixin.particle.ParticleMixin.

features/.../optimize/particle/camera/CameraPosition.java (new helper):
- Single point where the camera position is sampled. ParticleMixin reads it
  instead of re-walking Minecraft.getInstance().gameRenderer.mainCamera()
  per particle per tick. Ported from zako.opt.particle.CameraPosition.
- Moved into particle/camera/ subfolder so optimize/particle/ stays under
  the ≤4 .java-per-folder limit after adding ParticleMixin.

mixins/optimize/block/BlockEntityRenderStateMixin.java:
- WrapOperation on BlockEntityRenderState.extractBase's
  LightCoordsUtil.getLightCoords — consults the per-tick light cache slot
  on the BlockEntity (via the CachedLight mixin from Stage 3-continued-2)
  before falling through to the original. Gated on 'blockEntityCache'.
- Ported from zako.opt.mixin.block.BlockEntityRenderStateMixin.

mixins/optimize/block/ChestRendererMixin.java:
- Two WrapOperations on ChestRenderer.extractRenderState:
  * ChestBlock.combine — caches the double-chest neighbor-lookup result by
    game tick (via the TickCached mixin). Gated on 'blockEntityCache'.
  * Int2IntFunction.applyAsInt — caches the second (pair) light lookup
    done for double chests (via the CachedLight.lovisual$pairLight slot).
    Gated on 'microOpts'.
- Ported from zako.opt.mixin.block.ChestRendererMixin.

lovisual.mixins.json: three new entries in the 'client' array:
  optimize.block.BlockEntityRenderStateMixin
  optimize.block.ChestRendererMixin
  optimize.particle.ParticleMixin

Tests: no new tests in this batch (mixins are pure side-effect field-bags /
WrapOperation wrappers without unit-testable logic). Existing suite still green.
Total: 866 tests, 0 failures. checkFolderLimit: OK (0 папок >4).
2026-10-11 10:23:03 +02:00
LoVisual AI
135628c2f1
feat(mod): Stage 3 (continued 2) — entity + block + Sodium contract mixins
Per mod/docs/optimize-layer-design.md Stage 3 (continued). This batch
implements the Stage 1 mixin-contract interfaces on their target MC classes
so CachedName, StateEntity, TickCached, CachedLight, CachedValidity and
CachedStack actually get used. Seven new mixin'ов; no new helpers (the
helpers were all written in Stage 1 already).

Entity-contract mixins (mixins/optimize/entity/):
- EntityNameMixin: implements CachedName on Entity — adds the per-tick
  cached name-tag fields (Component + tick). Vanilla Entity.getDisplayName()
  rebuilds the team prefix + name + suffix on every call.
- EntityRenderStateEntityMixin: implements StateEntity on EntityRenderState —
  adds the back-reference field to the source Entity. Render-states are
  rebuilt every frame so they can't keep their own pointer; this is captured
  by EntityRendererStateMixin.
- EntityRendererStateMixin: Inject at RETURN on EntityRenderer.createRenderState
  — captures the source Entity on the freshly-built state via the StateEntity
  contract. ZakoOpt used @ModifyReturnValue; we use plain @Inject because the
  MixinExtras ModifyReturnValue transformer is more fragile across MC versions.
- EntityRendererNameMixin: WrapOperation on EntityRenderer.getNameTag's
  Entity.getDisplayName call — caches by game tick so the per-frame cost is
  one identity check + read instead of a full Component rebuild.
- SodiumEntityRendererMixin: WrapOperation on Sodium EntityRenderer.renderCuboid's
  MemoryStack.stackPush — uses CachedStack (Stage 1) to skip the ThreadLocal
  lookup on the render thread. Registered as optional via LoVisualMixinPlugin
  (only applied when Sodium is loaded); remap = false because the target is
  a Sodium class, not a Mojang one.

BlockEntity-contract mixins (mixins/optimize/block/):
- BlockEntityMixin: implements TickCached + CachedLight + CachedValidity on
  BlockEntity — adds the per-tick cache slot, per-tick block-light lookups
  (single + pair for double-chests), per-tick should-render distance check,
  and per-state validity cache. All four are read by the (Stage 3, future)
  ChestRendererMixin / BlockEntityRenderStateMixin / BlockEntityRenderDispatcherMixin.
- BaseSpawnerMixin: implements TickCached on BaseSpawner — adds the per-tick
  cache slot that SpawnerCache (Stage 1) reads back.

Folder limit (≤4 .java per folder):
- mixins/optimize/entity/ hit 6 files after this batch — split into
  mixins/optimize/entity/renderer/ for EntityRendererStateMixin +
  EntityRendererNameMixin (the two that target EntityRenderer rather than
  Entity/EntityRenderState directly). The other 4 stay in entity/.

lovisual.mixins.json: seven new entries in the 'client' array, alphabetical:
  optimize.block.BaseSpawnerMixin
  optimize.block.BlockEntityMixin
  optimize.entity.EntityNameMixin
  optimize.entity.EntityRenderStateEntityMixin
  optimize.entity.SodiumEntityRendererMixin
  optimize.entity.renderer.EntityRendererNameMixin
  optimize.entity.renderer.EntityRendererStateMixin

LoVisualMixinPlugin: added SodiumEntityRendererMixin to OPTIONAL_SODIUM_MIXINS
so the mixin is only applied when Sodium is loaded (matches the existing
convention for sodium.* mixins).

Tests: no new tests in this batch (the new mixins are pure side-effect
field-bags — they don't have unit-testable logic). Existing suite still green.
Total: 866 tests, 0 failures. checkFolderLimit: OK (0 папок >4).
2026-10-11 10:23:03 +02:00
LoVisual AI
15f070af6d
feat(mod): Stage 3 (continued) — LivingEntityLod + BubbleColumnUp + LevelRendererOutline
Some checks failed
CI / backend (cargo test + clippy) (push) Failing after 6m48s
CI / frontend (lint + test + build) (push) Failing after 24s
CI / mod (gradle test + checkFolderLimit) (push) Successful in 1m57s
Per mod/docs/optimize-layer-design.md Stage 3 (continued). Three more simple
mixin'ы are added on top of the existing RenderBackendOps + lazy-clear/TBO/
RenderTypes trio:

mixins/optimize/entity/LivingEntityLodMixin.java:
- ModifyExpressionValue on LivingEntityRenderer.submit's shouldRenderLayers
  call — return false when the entity's distanceToCameraSq is beyond the
  Stage 1 entity_lod threshold. Skips the layer pass (armour, held items,
  eyes, cape, elytra, stuck arrows) for far entities. Ported from
  zako.opt.mixin.entity.LivingEntityLodMixin.

mixins/optimize/particle/BubbleColumnUpParticleMixin.java:
- WrapOperation on BubbleColumnUpParticle.tick's ClientLevel.getFluidState
  call — consult BubbleColumnCache first, store on miss. Cache is cleared
  per-tick (BlockPos.asLong key + game-tick tracking). Ported from
  zako.opt.mixin.particle.BubbleColumnUpParticleMixin.

mixins/optimize/world/LevelRendererOutlineMixin.java:
- Inject on LevelRenderer.doEntityOutline HEAD-cancellable — skip the
  outline render when no glowing entity was seen this frame (OutlineTracker).
- WrapOperation on LevelRenderer.addMainPass's clearColorTexture — call
  OutlineTracker.markGlowing() to record that the renderer is about to
  draw an outline this frame. (Conservative: marks every clear, not just
  the entity-outline one — ZakoOpt uses @Local for precision, we keep it
  simple to avoid MixinExtras @Local fragility across MC versions.)
- Ported from zako.opt.mixin.entity.LevelRendererOutlineMixin.

Helpers (features/.../optimize/):
- particle/TickCache<V>: generic per-tick keyed cache (Long2ObjectOpenHashMap).
  BubbleColumnCache wraps it for FluidState. Other per-tick caches
  (ParticleLightCache etc.) can reuse it in later Stage 3 commits.
- particle/BubbleColumnCache: thin wrapper over TickCache<FluidState>.
- world/OutlineTracker: per-frame state for the outline-skip optimization
  (glowingThisFrame + dirty flag, beginFrame/markGlowing/markCleared API).

lovisual.mixins.json: three new entries in the 'client' array:
  optimize.entity.LivingEntityLodMixin
  optimize.particle.BubbleColumnUpParticleMixin
  optimize.world.LevelRendererOutlineMixin

Tests (JUnit 5):
- TickCacheTest: 9 tests covering get/put/clear-on-tick-change/multi-key/
  overwrite/null-values/long-keys.
- OutlineTrackerTest: 8 tests covering enabled flag, skip-when-no-glowing,
  begin-frame-clears, dirty-tracking, needsClear logic.
- (BubbleColumnCache itself is a 4-line wrapper around TickCache so its
  test would just re-test TickCache — skipped.)
Total suite: 866 tests, 0 failures. checkFolderLimit: OK (0 папок >4).
2026-10-10 18:53:38 +02:00
LoVisual AI
5e1864fed1
refactor(mod): restructure mixins/optimize/ into gl/hud/entity/particle/world subfolders
Per mod/docs/optimize-layer-design.md Stage 3 (continued). The mixins/optimize/
folder hit the project's ≤4 .java-files-per-folder rule when we tried to add
the next batch of mixin'ов (LivingEntityLodMixin, BubbleColumnUpParticleMixin,
LevelRendererOutlineMixin). Move the existing 4 mixin'ов into semantic subfolders:

- mixins/optimize/gl/GlCommandEncoderClearMixin.java (was mixins/optimize/)
- mixins/optimize/gl/GlCommandEncoderTexBufferMixin.java
- mixins/optimize/gl/RenderTypesMixin.java
- mixins/optimize/hud/OptimizeDebugHudMixin.java

lovisual.mixins.json: the 'client' array entries are updated to use the
new dotted paths (optimize.gl.*, optimize.hud.*). The package field in
each mixin file is updated to match.

No functional changes — this is purely a code-organization commit to make
room for the new Stage 3 mixin'ов in the next commit.
2026-10-10 18:53:38 +02:00
LoVisual AI
7a2ed9fc34
docs(mod): mark Stage 1+2 done and Stage 3 partial in optimize-layer-design.md
Per mod/docs/optimize-layer-design.md.

Status header: was 'черновик на согласование (2026-10-09)', now
'Этап 1 готов, Этап 2 + начало Этапа 3 готовы (2026-10-10)'.

New 'История изменений' section: three dated entries (Stage 1, Stage 2,
Stage 3 partial) listing files / tests / patch references.

Stages section: each line now carries a status icon (✅/🔄/❌), a completion
date, and a one-line summary of what shipped. Stage 3 partial lists what's
done (RenderBackendOps + GlRenderBackendOps + 3 GL mixins) and what's still
left (FrameFence, SharedDepthFbos, SkinAtlas, AnimFreeze, ItemLod,
LivingEntityLodMixin, ParticleMixin, SpawnerRendererMixin, etc.).

New 'Оценки для Этапов 3-4' section: rough effort estimates for the
remaining Stage 3 work (~25 mixins + ~8 helpers, 3-4 work sessions) and
Stage 4 (6 Vulkan items, profiling-driven, 1+ session for vkCmdCopyImage
which is needed for SkinAtlas to work on Vulkan).
2026-10-10 18:53:38 +02:00
LoVisual AI
e88718a32d
feat(mod): Stage 3 (partial) — RenderBackendOps interface + 3 GL mixins
Per mod/docs/optimize-layer-design.md Stage 3 (partial). This commit ships
the simplest GL mixins and the strategy interface that splits GL/Vulkan
backends. SkinAtlas/AnimFreeze/HudCache/FrameFence deferred to a later pass
because they're more complex (vertex-format / glCopyImageSubData /
RenderPipeline+RenderPass).

RenderBackendOps interface (features/.../optimize/gl/RenderBackendOps.java):
- Backend-agnostic surface for lazy clear, TBO cache, RenderTypes cache.
- current() resolves the active backend — returns GlRenderBackendOps on GL,
  null on Vulkan (so all WrapOperations fall through to the vanilla call).
- Stage 4 will add a VulkanRenderBackendOps no-op implementation.

GlRenderBackendOps (features/.../optimize/gl/GlRenderBackendOps.java):
- Concrete GL implementation. Three caches ported from ZakoOpt:
  * Lazy clear (from zako.opt.mixin.gl.GlCommandEncoderClearMixin).
  * TBO cache (from zako.opt.gl.TexBufferCache + the TexBufferMixin).
  * RenderTypes cache (from zako.opt.mixin.gl.RenderTypesMixin).
- All three gated on OptimizeToggles.microOpts() (the Stage 1 'micro_opts'
  toggle wired in Optimize.java).
- Includes test helpers (resetForTesting, boundTboTextureForTesting,
  cachedRenderTypeCountForTesting).

Three new mixins (mixins/optimize/):
- RenderTypesMixin: WrapOperation on RenderTypes.entityTranslucent's
  BiFunction.apply — cache by Identifier when flag=true (the common case).
  Drops the per-call Objects.hash(Pair) hit.
- GlCommandEncoderClearMixin: WrapOperation on GlCommandEncoder's
  clearColorAndDepthTextures → GlStateManager._glBindFramebuffer — skip the
  bind-framebuffer-0 because the next render pass binds its own target
  anyway and GlStateManager's cache already skips redundant binds.
- GlCommandEncoderTexBufferMixin: WrapOperation on GlCommandEncoder's
  trySetup → glBindTexture (track bound) and glTexBuffer (skip re-attach
  when the same (format, buffer) pair is already attached). Re-attaching
  makes the driver revalidate the texture (clouds: ~2% of a frame).

lovisual.mixins.json:
- Register all three mixins + OptimizeDebugHudMixin in the 'client' array,
  alphabetically under optimize.* (before accessors.*).

OptimizeDebugHudMixin (mixins/optimize/OptimizeDebugHudMixin.java):
- F3 overlay for the Optimize layer — Stage 2 of the design doc.
- Adds three blocks of lines to F3 (after the existing LoVisual Engine block):
  * 'LoVisual Optimize' — toggles summary + budget mode + scale + frame time.
  * 'frame:' — EMA-averaged per-section timings (entities/particles/HUD/effects/text).
  * 'props:' — when any -Dlovisual.opt.* is set, list which ones.
- Mirrors the existing hud.DebugHudMixin pattern (ModifyArg on extractLines).

Tests (JUnit 5): 11 new tests in GlRenderBackendOpsTest — pure-logic pieces
of RenderBackendOps + Identifier equality/hash. Total suite: 849 tests,
0 failures. checkFolderLimit: OK (0 folders >4).
2026-10-10 18:53:38 +02:00
LoVisual AI
64f27ee9e3
feat(mod): Stage 2 — frame budget + profiler + -Dlovisual.opt.* overrides
Per mod/docs/optimize-layer-design.md Stage 2.

Engine-side state holders (render/engine/optimize/profile/):
- FrameBudget: Mode enum (OFF/SOFT/AGGRESSIVE) + target FPS + per-subsystem
  caps (entity LOD distance², particle near/mid², spawner distance, trail max
  points + step). Scale 1.0 / 0.9 / 0.6 per mode. NOT auto-degradation —
  the user picks the mode explicitly; Phase 9 rule stands.
- FrameProfiler: per-section EMA timings (entities/particles/HUD/effects/text),
  try-with-resources Section API, 2 s idle decay, frame-time tracking.
- OptimizePropertyBridge: -Dlovisual.opt.* system-property overrides.
  10 properties (entity_lod, particle_lod, spawner_cull, spawner_tick_cache,
  block_entity_cache, prepared_text_cache, micro_opts, entity_lod_distance,
  spawner_distance, budget_mode, target_fps) + all=false to disable everything.
  Mirrors ZakoOpt's ZakoOptConfig.refresh() shape.

Module wiring:
- Optimize.java: extended with budget_mode (enum), target_fps (15..360),
  show_profiler toggles. pushState() now resolves the property bridge and
  pushes FrameBudget + OptimizeToggles snapshots together.

Tests (JUnit 5): 22 new tests — FrameBudgetTest (8), FrameProfilerTest (7),
OptimizePropertyBridgeTest (12). Total suite: 849 tests, 0 failures.

Note: OptimizeDebugHudMixin (the F3 overlay) is committed in a separate
patch alongside the Stage 3 mixins because it depends on the RenderBackendOps
GL/Vulkan strategy interface for the property-bridge status line.
2026-10-10 18:53:38 +02:00
494990ca4c
test(mod): JUnit 5 tests for Stage 1 optimization helpers
Some checks failed
CI / backend (cargo test + clippy) (push) Successful in 3m43s
CI / frontend (lint + test + build) (push) Failing after 23s
CI / mod (gradle test + checkFolderLimit) (push) Successful in 2m13s
53 tests covering the pure-logic pieces: OptimizeToggles, LruMap, EntityLod,
ParticleLod, Workers, HudWorth, SpawnerCache, StableText, CachedStack.
2026-10-10 14:50:50 +02:00
1a50a757b7
feat(mod): Stage 1 optimization helpers (backend-independent)
Per mod/docs/optimize-layer-design.md Stage 1: pure helpers and mixin-contract
interfaces for the Optimize module, plus the OptimizeToggles engine-side state
holder and nine new toggles in Optimize. GL/Vulkan hooks are Stages 3-4.
2026-10-10 14:50:50 +02:00
4a722259a5
deploy(nginx): serve the mod jar from nginx with a speed cap (750k per connection) and 2 connections per IP
Some checks failed
CI / backend (cargo test + clippy) (push) Successful in 7m0s
CI / frontend (lint + test + build) (push) Failing after 26s
CI / mod (gradle test + checkFolderLimit) (push) Successful in 1m34s
2026-10-09 22:26:27 +02:00
acb69472c2
docs: README download button points at the site's /download (Forgejo has no releases/latest/download)
Some checks failed
CI / backend (cargo test + clippy) (push) Has been cancelled
CI / frontend (lint + test + build) (push) Has been cancelled
CI / mod (gradle test + checkFolderLimit) (push) Has been cancelled
2026-10-09 22:25:03 +02:00
144 changed files with 8887 additions and 323 deletions

View file

@ -2,7 +2,7 @@ name: Release
# Publish a mod build on every version tag. Every release carries both a # Publish a mod build on every version tag. Every release carries both a
# versioned jar and a stable `lovisual.jar`, so the site's one-click download # versioned jar and a stable `lovisual.jar`, so the site's one-click download
# link (releases/latest/download/lovisual.jar) always resolves. # link (the site serves lovisual.jar from our own server) always resolves.
on: on:
push: push:

View file

@ -4,7 +4,7 @@
Open-source Minecraft utility client **and** the platform around it - website, cloud config sharing, and a Rust backend. Open-source Minecraft utility client **and** the platform around it - website, cloud config sharing, and a Rust backend.
Developed and maintained by [loki5512344](https://github.com/loki5512344). Developed and maintained by [loki5512344ss](https://github.com/loki5512344ss).
![Release](https://img.shields.io/gitea/v/release/boba/LoVisual?gitea_url=https%3A%2F%2Fgit.wihuk.pro&style=flat-square&color=blue) ![Release](https://img.shields.io/gitea/v/release/boba/LoVisual?gitea_url=https%3A%2F%2Fgit.wihuk.pro&style=flat-square&color=blue)
![Java](https://img.shields.io/badge/Java-25+-orange?style=flat-square&logo=openjdk&logoColor=white) ![Java](https://img.shields.io/badge/Java-25+-orange?style=flat-square&logo=openjdk&logoColor=white)
@ -12,7 +12,7 @@ Developed and maintained by [loki5512344](https://github.com/loki5512344).
![React](https://img.shields.io/badge/Frontend-React%20%2B%20Vite-61dafb?style=flat-square&logo=react&logoColor=white) ![React](https://img.shields.io/badge/Frontend-React%20%2B%20Vite-61dafb?style=flat-square&logo=react&logoColor=white)
![License](https://img.shields.io/badge/license-GPLv3-blue?style=flat-square&logo=gnu&logoColor=white) ![License](https://img.shields.io/badge/license-GPLv3-blue?style=flat-square&logo=gnu&logoColor=white)
**[⬇ Download the mod](https://git.wihuk.pro/boba/LoVisual/releases/latest/download/lovisual.jar)** · [Releases](https://git.wihuk.pro/boba/LoVisual/releases) **[⬇ Download the mod](https://visual.loki-code.dev/download)** · [Releases](https://git.wihuk.pro/boba/LoVisual/releases)
[English](#english) | [Русский](#русский) [English](#english) | [Русский](#русский)

View file

@ -61,6 +61,17 @@ pub async fn set_avatar(pool: &PgPool, account_id: Uuid, s3_key: &str) -> Result
Ok(()) Ok(())
} }
/// Deletes the `avatars` row for one account. Returns `true` when a row existed
/// (so the caller can decide whether to also delete the S3 object) and `false`
/// when the user simply had no avatar — the API still treats that as success.
pub async fn clear_avatar(pool: &PgPool, account_id: Uuid) -> Result<bool, sqlx::Error> {
let result = sqlx::query("DELETE FROM avatars WHERE account_id = $1")
.bind(account_id)
.execute(pool)
.await?;
Ok(result.rows_affected() > 0)
}
/// Avatar reference for one account: its storage key plus an `uploaded_at` /// Avatar reference for one account: its storage key plus an `uploaded_at`
/// version (epoch seconds) used to cache-bust the served image URL. /// version (epoch seconds) used to cache-bust the served image URL.
pub async fn avatar_ref( pub async fn avatar_ref(

View file

@ -70,6 +70,28 @@ pub async fn upload(
})) }))
} }
/// DELETE /avatars — clears the caller's avatar. Removes the DB row and, if one
/// existed, the S3 object. Always returns 204, including when the user had no
/// avatar: the operation is idempotent, matching how the frontend's "Remove
/// avatar" button should behave after a successful click.
pub async fn delete(
State(state): State<AvatarState>,
identity: GatewayIdentity,
) -> Result<Response, AppError> {
let account_id = identity.account_id;
let existed = repo::clear_avatar(&state.pool, account_id).await?;
if existed {
let key = format!("avatars/{account_id}.png");
// S3 delete is best-effort: if MinIO is unreachable we already committed
// the DB row removal, and the object becomes orphaned but not served (the
// serve handler looks up keys via the DB, not directly).
if let Err(err) = state.storage.delete(&key).await {
tracing::warn!("avatar S3 delete failed for {account_id}: {err}");
}
}
Ok(StatusCode::NO_CONTENT.into_response())
}
/// Only serve the keys this service writes: `avatars/<account-uuid>.png`. /// Only serve the keys this service writes: `avatars/<account-uuid>.png`.
/// Anything else (traversal, other buckets/paths) is a 404. The gateway blocks /// Anything else (traversal, other buckets/paths) is a 404. The gateway blocks
/// dot-segments upstream, but the service validates independently. /// dot-segments upstream, but the service validates independently.

View file

@ -51,4 +51,17 @@ impl S3Storage {
let aggregated = out.body.collect().await?; let aggregated = out.body.collect().await?;
Ok(aggregated.into_bytes().to_vec()) Ok(aggregated.into_bytes().to_vec())
} }
/// Deletes the object at `key`. MinIO's DeleteObject is idempotent — deleting
/// a missing key returns Ok. Callers on the app layer are expected to run
/// this only after a matching DB row existed, so a stray 404 here is silent.
pub async fn delete(&self, key: &str) -> anyhow::Result<()> {
self.client
.delete_object()
.bucket(&self.bucket)
.key(key)
.send()
.await?;
Ok(())
}
} }

View file

@ -89,6 +89,7 @@ pub fn build_app_with_mail(pool: sqlx::PgPool, cfg: &Config, mail: auth::reset::
let avatar_routes = Router::new() let avatar_routes = Router::new()
.route("/avatars", post(avatars::handlers::upload)) .route("/avatars", post(avatars::handlers::upload))
.route("/avatars", axum::routing::delete(avatars::handlers::delete))
// Public avatar read served back through the gateway; the `{*key}` // Public avatar read served back through the gateway; the `{*key}`
// wildcard is the storage key (`avatars/<uuid>.png`). // wildcard is the storage key (`avatars/<uuid>.png`).
.route("/media/{*key}", get(avatars::handlers::serve)) .route("/media/{*key}", get(avatars::handlers::serve))

View file

@ -121,3 +121,78 @@ async fn upload_without_identity_is_401() {
.await .await
.assert_status(StatusCode::UNAUTHORIZED); .assert_status(StatusCode::UNAUTHORIZED);
} }
#[tokio::test]
async fn delete_removes_the_row_and_returns_204() {
common::init_test_logging();
common::ensure_avatar_bucket().await;
let pool = common::test_pool().await;
let server = common::test_server(accounts_service::build_app(
pool.clone(),
&common::test_config(),
));
let (account_id, email) = common::register_account(&server).await;
server
.post("/avatars")
.add_header(ACCOUNT_ID_HEADER, account_id.to_string())
.multipart(form(png_bytes()))
.await
.assert_status_ok();
server
.delete("/avatars")
.add_header(ACCOUNT_ID_HEADER, account_id.to_string())
.await
.assert_status(StatusCode::NO_CONTENT);
let count: i64 = sqlx::query_as::<_, (i64,)>("SELECT COUNT(*) FROM avatars WHERE account_id = $1")
.bind(account_id)
.fetch_one(&pool)
.await
.unwrap()
.0;
assert_eq!(count, 0);
sqlx::query("DELETE FROM accounts WHERE lower(email) = $1")
.bind(email.to_lowercase())
.execute(&pool)
.await
.unwrap();
}
#[tokio::test]
async fn delete_without_avatar_is_idempotent() {
let pool = common::test_pool().await;
let server = common::test_server(accounts_service::build_app(
pool.clone(),
&common::test_config(),
));
let (account_id, email) = common::register_account(&server).await;
server
.delete("/avatars")
.add_header(ACCOUNT_ID_HEADER, account_id.to_string())
.await
.assert_status(StatusCode::NO_CONTENT);
sqlx::query("DELETE FROM accounts WHERE lower(email) = $1")
.bind(email.to_lowercase())
.execute(&pool)
.await
.unwrap();
}
#[tokio::test]
async fn delete_without_identity_is_401() {
let pool = common::test_pool().await;
let server = common::test_server(accounts_service::build_app(
pool.clone(),
&common::test_config(),
));
server
.delete("/avatars")
.await
.assert_status(StatusCode::UNAUTHORIZED);
}

View file

@ -0,0 +1,2 @@
# Per-client-IP connection counter for the capped jar download (see the site conf).
limit_conn_zone $binary_remote_addr zone=lv_downloads:10m;

View file

@ -18,6 +18,23 @@ server {
add_header Cache-Control "public, max-age=60" always; add_header Cache-Control "public, max-age=60" always;
} }
# The mod jar is served by nginx itself (not through the gateway) so the
# speed can be capped: ~6 Mbit/s per connection and at most 2 connections
# per client IP keep a flood of downloads from saturating the link.
location = /api/downloads/lovisual.jar {
alias /opt/lovisual/backend/downloads/lovisual.jar;
default_type application/java-archive;
add_header Content-Disposition 'attachment; filename="lovisual.jar"' always;
limit_rate 750k;
limit_conn lv_downloads 2;
limit_conn_status 429;
}
location = /api/downloads/lovisual.jar.sha256 {
alias /opt/lovisual/backend/downloads/lovisual.jar.sha256;
default_type text/plain;
}
location /api/ { location /api/ {
proxy_pass http://127.0.0.1:8080/; proxy_pass http://127.0.0.1:8080/;
proxy_http_version 1.1; proxy_http_version 1.1;

View file

@ -2340,7 +2340,7 @@ git commit -m "feat(gateway): CORS for the site origin; docs for gateway and int
### Task 12: Easter eggs in the gateway ### Task 12: Easter eggs in the gateway
- `.env` honeypot — done together with the dot-segment fix (see `.superpowers` fix list; commit "feat(gateway): .env honeypot easter egg for traversal scanners"). - `.env` honeypot — done together with the dot-segment fix (see `.superpowers` fix list; commit "feat(gateway): .env honeypot easter egg for traversal scanners").
- `GET /coffee` (any method) → `418 I'm a teapot`, `text/plain; charset=utf-8`: «Я чайник. Кофе не варю, зато LoVisual бесплатный: https://github.com/loki5512344/LoVisual-/releases». Handled in the gateway before identity/rate limits, not forwarded. Test + commit `feat(gateway): 418 teapot at /coffee`. - `GET /coffee` (any method) → `418 I'm a teapot`, `text/plain; charset=utf-8`: «Я чайник. Кофе не варю, зато LoVisual бесплатный: https://github.com/loki5512344ss/LoVisual/releases». Handled in the gateway before identity/rate limits, not forwarded. Test + commit `feat(gateway): 418 teapot at /coffee`.
--- ---

View file

@ -13,7 +13,7 @@ JWT_SECRET=nice_try_skiddie_tvoy_ip_uzhe_v_bane
INTERNAL_KEY=0000-0000-0000-0000-otvali INTERNAL_KEY=0000-0000-0000-0000-otvali
ADMIN_PASSWORD=hunter2 ADMIN_PASSWORD=hunter2
S3_SECRET_KEY=lovisual_luchshe_chem_tvoy_chit S3_SECRET_KEY=lovisual_luchshe_chem_tvoy_chit
# P.S. лучше скачай мод: https://github.com/loki5512344/LoVisual-/releases # P.S. лучше скачай мод: https://github.com/loki5512344ss/LoVisual/releases
"; ";
/// Any segment named `.env` or `.env.<suffix>` (dots may be `%2e`-encoded). /// Any segment named `.env` or `.env.<suffix>` (dots may be `%2e`-encoded).

View file

@ -44,7 +44,7 @@ pub fn is_ambiguous(path: &str) -> bool {
}) })
} }
const TEAPOT: &str = "Я чайник. Кофе не варю, зато LoVisual бесплатный: https://github.com/loki5512344/LoVisual-/releases\n"; const TEAPOT: &str = "Я чайник. Кофе не варю, зато LoVisual бесплатный: https://github.com/loki5512344ss/LoVisual/releases\n";
fn teapot() -> Response { fn teapot() -> Response {
( (

View file

@ -1154,7 +1154,7 @@ Replaces the Task 5 landing body (keep `CommandHero`'s chat line — it becomes
- `DownloadPage` (`/download`): big button, requirements block (Minecraft 26.2, Fabric Loader 0.19.4+, Fabric API; optional Sodium/Iris — values in the download dictionary, sourced from `mod/gradle.properties`), 3-step install guide (real sequence: скачать → положить в `mods` → запустить с профилем Fabric), then `ReleaseNotes`. - `DownloadPage` (`/download`): big button, requirements block (Minecraft 26.2, Fabric Loader 0.19.4+, Fabric API; optional Sodium/Iris — values in the download dictionary, sourced from `mod/gradle.properties`), 3-step install guide (real sequence: скачать → положить в `mods` → запустить с профилем Fabric), then `ReleaseNotes`.
- [ ] **Step 1: CI workflow** (no test; validate with `actionlint` if available, otherwise careful review). Tagging/pushing is the owner's action — do not push tags. - [ ] **Step 1: CI workflow** (no test; validate with `actionlint` if available, otherwise careful review). Tagging/pushing is the owner's action — do not push tags.
- [ ] **Step 2: Failing tests** — button href equals `https://github.com/loki5512344/LoVisual-/releases/latest/download/lovisual.jar` (with `vi.stubEnv('VITE_GITHUB_REPO', …)`); release notes render Markdown headings and do NOT render a raw `<script>`/`<img onerror>` from the body as HTML; fetch failure shows the fallback text. - [ ] **Step 2: Failing tests** — button href equals `https://github.com/loki5512344ss/LoVisual/releases/latest/download/lovisual.jar` (with `vi.stubEnv('VITE_GITHUB_REPO', …)`); release notes render Markdown headings and do NOT render a raw `<script>`/`<img onerror>` from the body as HTML; fetch failure shows the fallback text.
- [ ] **Step 3: Implement; routes; TopBar button.** - [ ] **Step 3: Implement; routes; TopBar button.**
- [ ] **Step 4: commit** — `feat(frontend): one-click download from GitHub releases, changelog page, release CI` - [ ] **Step 4: commit** — `feat(frontend): one-click download from GitHub releases, changelog page, release CI`

View file

@ -19,6 +19,16 @@ export async function uploadAvatar(file: File): Promise<{ avatar_url: string }>
return api.request('/avatars', { method: 'POST', body }) return api.request('/avatars', { method: 'POST', body })
} }
/**
* DELETE /avatars — clears the caller's picture server-side. The backend is
* idempotent (always 204), so a repeated click is safe. The `me` cache is
* invalidated by the caller, not here, so the button can chain invalidations
* with any other side effects (e.g. history tick bump).
*/
export async function removeAvatar(): Promise<void> {
await api.request('/avatars', { method: 'DELETE' })
}
/** Byte-level progress comes only from XHR (see `api.upload`), not from fetch. */ /** Byte-level progress comes only from XHR (see `api.upload`), not from fetch. */
export function uploadAvatarWithProgress(file: File, onProgress: (pct: number) => void): Promise<{ avatar_url: string }> { export function uploadAvatarWithProgress(file: File, onProgress: (pct: number) => void): Promise<{ avatar_url: string }> {
const body = new FormData() const body = new FormData()

View file

@ -1,74 +1,157 @@
import { useRef, useState, type PointerEvent as ReactPointerEvent } from 'react' import {
useCallback,
useEffect,
useRef,
useState,
type KeyboardEvent as ReactKeyboardEvent,
type PointerEvent as ReactPointerEvent,
type WheelEvent as ReactWheelEvent,
} from 'react'
import { useTranslation } from '@shared/i18n/react' import { useTranslation } from '@shared/i18n/react'
import { Button } from '@shared/ui/Button' import {
import { clampPan, clampZoom, coverScale, MAX_ZOOM, MIN_ZOOM, sourceRect } from './cropMath' MAX_ZOOM,
MIN_ZOOM,
PAN_STEP,
VIEWPORT,
ZOOM_STEP,
clampPan,
clampZoom,
coverScale,
pinchZoom,
wheelZoom,
} from './cropMath'
const VIEWPORT = 240 export type CropState = {
const OUTPUT_SIZE = 512 zoom: number
offset: { x: number; y: number }
natural: { w: number; h: number }
}
type Props = { type Props = {
file: File file: File
onCancel: () => void /** Fires once on first user interaction so the dialog can flip an "unsaved changes" guard. */
onConfirm: (blob: Blob) => void onDirty?: () => void
/** Fires whenever the crop geometry changes; the dialog renders previews off this. */
onCropState?: (state: CropState) => void
} }
/** Drag-to-reposition, zoom-to-scale circular crop UI. Renders the selection onto an offscreen canvas on confirm. */ /**
export function AvatarCropper({ file, onCancel, onConfirm }: Props) { * The interactive crop canvas. Owns image layout (drag to pan, wheel / pinch to
* zoom, arrow keys / +/-/0 for keyboard), the visible rule-of-thirds guides and
* the corner shade that shows exactly what falls inside the circle. Cancel and
* Confirm live in {@link AvatarEditDialog}, not here — this component is pure
* viewport + input handling.
*
* <p>Everything the 2026-10 avatar-settings research identified as "missing in
* ours, present in every reference product":
* <ul>
* <li>bigger viewport (320 vs the previous 240 — the smallest in the sample)</li>
* <li>visible guides + shade, so the user knows what will actually end up in
* the file (previous `overflow-hidden rounded-full` hid the crop frame
* entirely)</li>
* <li>wheel zoom + pinch zoom (both no-brainers per react-easy-crop)</li>
* <li>keyboard: arrows pan, +/- zoom, 0 resets (Google documents this)</li>
* <li>a Reset button returning to zoom=MIN, offset=(0,0)</li>
* </ul>
*/
export function AvatarCropper({ file, onDirty, onCropState }: Props) {
const { t } = useTranslation('account') const { t } = useTranslation('account')
const [url] = useState(() => URL.createObjectURL(file)) const [url] = useState(() => URL.createObjectURL(file))
useEffect(() => () => URL.revokeObjectURL(url), [url])
const [natural, setNatural] = useState<{ w: number; h: number }>() const [natural, setNatural] = useState<{ w: number; h: number }>()
const [zoom, setZoom] = useState(MIN_ZOOM) const [zoom, setZoom] = useState(MIN_ZOOM)
const [offset, setOffset] = useState({ x: 0, y: 0 }) const [offset, setOffset] = useState({ x: 0, y: 0 })
const [busy, setBusy] = useState(false)
const pointers = useRef(new Map<number, { x: number; y: number }>())
const pinchBase = useRef<{ distance: number; zoom: number } | null>(null)
const drag = useRef<{ x: number; y: number; offset: { x: number; y: number } } | null>(null) const drag = useRef<{ x: number; y: number; offset: { x: number; y: number } } | null>(null)
function onImgLoad(e: React.SyntheticEvent<HTMLImageElement>) { const markDirty = useCallback(() => onDirty?.(), [onDirty])
setNatural({ w: e.currentTarget.naturalWidth, h: e.currentTarget.naturalHeight })
// Publish crop state so the dialog's preview column stays in sync.
useEffect(() => {
if (!natural) return
onCropState?.({ zoom, offset, natural })
}, [natural, zoom, offset, onCropState])
const applyZoom = useCallback(
(next: number) => {
const clamped = clampZoom(next)
setZoom(clamped)
if (natural) setOffset((prev) => clampPan(prev, natural.w, natural.h, VIEWPORT, clamped))
markDirty()
},
[natural, markDirty],
)
const applyPan = useCallback(
(next: { x: number; y: number }) => {
if (!natural) return
setOffset(clampPan(next, natural.w, natural.h, VIEWPORT, zoom))
markDirty()
},
[natural, zoom, markDirty],
)
function reset() {
setZoom(MIN_ZOOM)
setOffset({ x: 0, y: 0 })
markDirty()
} }
function onPointerDown(e: ReactPointerEvent<HTMLDivElement>) { function onPointerDown(e: ReactPointerEvent<HTMLDivElement>) {
e.currentTarget.setPointerCapture(e.pointerId) e.currentTarget.setPointerCapture(e.pointerId)
pointers.current.set(e.pointerId, { x: e.clientX, y: e.clientY })
if (pointers.current.size === 2) {
const [a, b] = [...pointers.current.values()]
pinchBase.current = { distance: Math.hypot(a.x - b.x, a.y - b.y), zoom }
drag.current = null
return
}
drag.current = { x: e.clientX, y: e.clientY, offset } drag.current = { x: e.clientX, y: e.clientY, offset }
} }
function onPointerMove(e: ReactPointerEvent<HTMLDivElement>) { function onPointerMove(e: ReactPointerEvent<HTMLDivElement>) {
if (!drag.current || !natural) return
const dx = e.clientX - drag.current.x
const dy = e.clientY - drag.current.y
const next = { x: drag.current.offset.x + dx, y: drag.current.offset.y + dy }
setOffset(clampPan(next, natural.w, natural.h, VIEWPORT, zoom))
}
function onPointerUp() {
drag.current = null
}
function onZoomChange(next: number) {
const clamped = clampZoom(next)
setZoom(clamped)
if (natural) setOffset((prev) => clampPan(prev, natural.w, natural.h, VIEWPORT, clamped))
}
async function confirm() {
if (!natural) return if (!natural) return
setBusy(true) if (pointers.current.has(e.pointerId)) {
const img = new Image() pointers.current.set(e.pointerId, { x: e.clientX, y: e.clientY })
img.src = url }
await img.decode() if (pointers.current.size === 2 && pinchBase.current) {
const { sx, sy, sw, sh } = sourceRect(natural.w, natural.h, VIEWPORT, zoom, offset) const [a, b] = [...pointers.current.values()]
const canvas = document.createElement('canvas') const next = Math.hypot(a.x - b.x, a.y - b.y)
canvas.width = OUTPUT_SIZE applyZoom(pinchZoom(pinchBase.current.zoom, pinchBase.current.distance, next))
canvas.height = OUTPUT_SIZE
const ctx = canvas.getContext('2d')
if (!ctx) {
setBusy(false)
return return
} }
ctx.drawImage(img, sx, sy, sw, sh, 0, 0, OUTPUT_SIZE, OUTPUT_SIZE) if (!drag.current) return
canvas.toBlob((blob) => { const dx = e.clientX - drag.current.x
setBusy(false) const dy = e.clientY - drag.current.y
if (blob) onConfirm(blob) applyPan({ x: drag.current.offset.x + dx, y: drag.current.offset.y + dy })
}, 'image/png') }
function onPointerUp(e: ReactPointerEvent<HTMLDivElement>) {
pointers.current.delete(e.pointerId)
if (pointers.current.size < 2) pinchBase.current = null
if (pointers.current.size === 0) drag.current = null
}
function onWheel(e: ReactWheelEvent<HTMLDivElement>) {
if (!natural) return
applyZoom(wheelZoom(zoom, e.deltaY))
}
function onKeyDown(e: ReactKeyboardEvent<HTMLDivElement>) {
if (!natural) return
switch (e.key) {
case 'ArrowLeft': e.preventDefault(); applyPan({ x: offset.x - PAN_STEP, y: offset.y }); return
case 'ArrowRight': e.preventDefault(); applyPan({ x: offset.x + PAN_STEP, y: offset.y }); return
case 'ArrowUp': e.preventDefault(); applyPan({ x: offset.x, y: offset.y - PAN_STEP }); return
case 'ArrowDown': e.preventDefault(); applyPan({ x: offset.x, y: offset.y + PAN_STEP }); return
case '+':
case '=': e.preventDefault(); applyZoom(zoom + ZOOM_STEP); return
case '-':
case '_': e.preventDefault(); applyZoom(zoom - ZOOM_STEP); return
case '0': e.preventDefault(); reset(); return
}
} }
const scale = natural ? coverScale(natural.w, natural.h, VIEWPORT) * zoom : 1 const scale = natural ? coverScale(natural.w, natural.h, VIEWPORT) * zoom : 1
@ -76,20 +159,26 @@ export function AvatarCropper({ file, onCancel, onConfirm }: Props) {
const drawnH = natural ? natural.h * scale : VIEWPORT const drawnH = natural ? natural.h * scale : VIEWPORT
return ( return (
<div className="flex flex-col items-center gap-3"> <div className="flex flex-col items-center gap-2">
<div <div
className="relative overflow-hidden rounded-full border border-shoal touch-none" role="group"
aria-label={t('avatar.cropperAria')}
tabIndex={0}
data-testid="cropper-viewport"
className="relative overflow-hidden rounded-full border border-shoal outline-none touch-none focus-visible:ring-2 focus-visible:ring-ice"
style={{ width: VIEWPORT, height: VIEWPORT, cursor: 'grab' }} style={{ width: VIEWPORT, height: VIEWPORT, cursor: 'grab' }}
onPointerDown={onPointerDown} onPointerDown={onPointerDown}
onPointerMove={onPointerMove} onPointerMove={onPointerMove}
onPointerUp={onPointerUp} onPointerUp={onPointerUp}
onPointerCancel={onPointerUp} onPointerCancel={onPointerUp}
onWheel={onWheel}
onKeyDown={onKeyDown}
> >
<img <img
src={url} src={url}
alt="" alt=""
draggable={false} draggable={false}
onLoad={onImgLoad} onLoad={(e) => setNatural({ w: e.currentTarget.naturalWidth, h: e.currentTarget.naturalHeight })}
className="pointer-events-none absolute select-none" className="pointer-events-none absolute select-none"
style={{ style={{
width: drawnW, width: drawnW,
@ -98,27 +187,41 @@ export function AvatarCropper({ file, onCancel, onConfirm }: Props) {
top: VIEWPORT / 2 - drawnH / 2 + offset.y, top: VIEWPORT / 2 - drawnH / 2 + offset.y,
}} }}
/> />
</div> {/* Rule-of-thirds guides. Kept at 40% so they read as an overlay, not a wall. */}
<label className="flex w-full max-w-[240px] flex-col gap-1 text-sm text-snow"> <div className="pointer-events-none absolute inset-0 opacity-40">
{t('avatar.zoom')} <div className="absolute inset-y-0 left-1/3 w-px bg-snow" />
<input <div className="absolute inset-y-0 left-2/3 w-px bg-snow" />
type="range" <div className="absolute inset-x-0 top-1/3 h-px bg-snow" />
min={MIN_ZOOM} <div className="absolute inset-x-0 top-2/3 h-px bg-snow" />
max={MAX_ZOOM} </div>
step={0.01} {/* Corner shade — the region outside the round crop target gets dimmed, so
value={zoom} the user sees exactly what falls inside the file. */}
onChange={(e) => onZoomChange(Number(e.target.value))} <div
className="pointer-events-none absolute inset-0 rounded-full"
style={{ boxShadow: 'inset 0 0 0 9999px rgba(0,0,0,0.55)' }}
/> />
</label>
<p className="text-xs text-shoal">{t('avatar.reposition')}</p>
<div className="flex gap-2">
<Button variant="quiet" onClick={onCancel} disabled={busy}>
{t('avatar.cancel')}
</Button>
<Button variant="primary" onClick={confirm} busy={busy} disabled={!natural}>
{t('avatar.confirm')}
</Button>
</div> </div>
<div className="flex w-full max-w-[360px] items-center gap-2">
<label className="flex flex-1 flex-col gap-1 text-sm text-snow">
{t('avatar.zoom')}
<input
type="range"
min={MIN_ZOOM}
max={MAX_ZOOM}
step={0.01}
value={zoom}
onChange={(e) => applyZoom(Number(e.target.value))}
/>
</label>
<button
type="button"
onClick={reset}
className="cursor-pointer rounded-ctl border border-shoal px-3 py-1 text-sm text-snow hover:border-frost"
>
{t('avatar.reset')}
</button>
</div>
<p className="text-xs text-shoal">{t('avatar.cropperHint')}</p>
</div> </div>
) )
} }

View file

@ -0,0 +1,215 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
import { useTranslation } from '@shared/i18n/react'
import { Button } from '@shared/ui/Button'
import { Notice } from '@shared/ui/Notice'
import { AvatarCropper, type CropState } from './AvatarCropper'
import { OUTPUT_SIZE, PREVIEW_SIZES, VIEWPORT, sourceRect } from './cropMath'
type Props = {
file: File
onCancel: () => void
onConfirm: (blob: Blob) => void
/** Upload progress in 0..100, or null while idle. Kept inside the modal so
* the user does not have to look away from the crop while a slow upload runs. */
progress: number | null
error?: string
}
/**
* Modal wrapper around {@link AvatarCropper}: the "Edit Image" dialog pattern
* from Discord / Google / Slack, replacing the previous inline crop block that
* made the whole flow feel like a piece of wireframe. Owns:
* - focus trap (initial focus into the card, ESC / X / backdrop close)
* - dirty guard (any pan/zoom flips `dirty`; closing when dirty asks for
* confirmation)
* - filename + size + accepted-format hint in the header
* - the "how others see it" preview column (128/64/32 px) rendered live from
* the same crop state so the user is not surprised when the small HUD
* nameplate clips their ears
* - progress bar and error notice inline
*/
export function AvatarEditDialog({ file, onCancel, onConfirm, progress, error }: Props) {
const { t } = useTranslation('account')
const [crop, setCrop] = useState<CropState | null>(null)
const [dirty, setDirty] = useState(false)
const [busy, setBusy] = useState(false)
const cardRef = useRef<HTMLDivElement | null>(null)
const markDirty = useCallback(() => setDirty(true), [])
// Publishes crop state upward; useState's setter is stable so the cropper's
// effect dependency array does not thrash.
const publishCrop = useCallback((state: CropState) => setCrop(state), [])
const attemptClose = useCallback(() => {
if (busy) return
if (dirty && !window.confirm(t('avatar.discardConfirm'))) return
onCancel()
}, [busy, dirty, onCancel, t])
// ESC handler lives on window so it also fires when focus is on the range
// slider or the file input's hidden click path.
useEffect(() => {
function onKey(e: KeyboardEvent) {
if (e.key === 'Escape') {
e.stopPropagation()
attemptClose()
}
}
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
}, [attemptClose])
useEffect(() => {
cardRef.current?.focus()
}, [])
async function confirm() {
if (!crop) return
setBusy(true)
try {
const blob = await renderCrop(file, crop, OUTPUT_SIZE)
onConfirm(blob)
} catch {
// Blob failure falls through to the parent's error state on the next
// render (the mutation onError path already shows the message).
} finally {
setBusy(false)
}
}
return createPortal(
<div
className="fixed inset-0 z-50 grid place-items-center bg-black/60 p-4"
onClick={(e) => {
if (e.target === e.currentTarget) attemptClose()
}}
role="dialog"
aria-modal="true"
aria-label={t('avatar.dialogTitle')}
>
<div
ref={cardRef}
tabIndex={-1}
className="flex max-h-[92vh] w-full max-w-[860px] flex-col gap-4 overflow-auto rounded-(--radius-panel) border border-shoal bg-slate/95 p-5 outline-none"
>
<header className="flex items-start justify-between gap-4">
<div className="min-w-0">
<h2 className="font-display text-lg text-snow">{t('avatar.dialogTitle')}</h2>
<p className="truncate text-xs text-frost">
{file.name} · {formatBytes(file.size)} · {t('avatar.limits')}
</p>
</div>
<button
type="button"
aria-label={t('avatar.close')}
onClick={attemptClose}
className="cursor-pointer rounded-ctl px-2 py-1 text-xl leading-none text-frost hover:text-snow"
>
×
</button>
</header>
<div className="flex flex-wrap items-start justify-center gap-6">
<AvatarCropper file={file} onDirty={markDirty} onCropState={publishCrop} />
<aside className="flex flex-col items-center gap-2">
<p className="text-xs text-shoal">{t('avatar.previewLabel')}</p>
{crop ? (
<div className="flex items-end gap-3">
{PREVIEW_SIZES.map((size) => (
<Preview key={size} file={file} crop={crop} size={size} />
))}
</div>
) : (
<div style={{ width: 200, height: 200 }} />
)}
</aside>
</div>
{progress !== null ? (
<div
role="progressbar"
aria-valuenow={progress}
aria-valuemin={0}
aria-valuemax={100}
className="h-1 w-full overflow-hidden rounded-full bg-shoal"
>
<div className="h-full bg-ice transition-[width] duration-150" style={{ width: `${progress}%` }} />
</div>
) : null}
{error ? <Notice tone="error">{error}</Notice> : null}
<footer className="flex items-center justify-between gap-3">
<Button variant="quiet" onClick={attemptClose} disabled={busy}>
{t('avatar.cancel')}
</Button>
<div className="text-xs text-shoal">{dirty ? t('avatar.unsaved') : ''}</div>
<Button variant="primary" onClick={confirm} busy={busy} disabled={!crop}>
{t('avatar.confirm')}
</Button>
</footer>
</div>
</div>,
document.body,
)
}
function formatBytes(n: number): string {
if (n < 1024) return `${n} B`
if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`
return `${(n / 1024 / 1024).toFixed(2)} MB`
}
/** Draws the crop rectangle from `file` at the requested output edge. Used for
* both the final PNG (OUTPUT_SIZE) and the preview tiles (128/64/32). */
async function renderCrop(file: File, state: CropState, size: number): Promise<Blob> {
const url = URL.createObjectURL(file)
try {
const img = new Image()
img.src = url
await img.decode()
const { sx, sy, sw, sh } = sourceRect(state.natural.w, state.natural.h, VIEWPORT, state.zoom, state.offset)
const canvas = document.createElement('canvas')
canvas.width = size
canvas.height = size
const ctx = canvas.getContext('2d')
if (!ctx) throw new Error('canvas 2d unavailable')
ctx.drawImage(img, sx, sy, sw, sh, 0, 0, size, size)
return await new Promise<Blob>((resolve, reject) =>
canvas.toBlob((b) => (b ? resolve(b) : reject(new Error('toBlob failed'))), 'image/png'),
)
} finally {
URL.revokeObjectURL(url)
}
}
function Preview({ file, crop, size }: { file: File; crop: CropState; size: number }) {
const [url, setUrl] = useState<string | null>(null)
useEffect(() => {
let active = true
let local: string | null = null
renderCrop(file, crop, size)
.then((blob) => {
if (!active) return
local = URL.createObjectURL(blob)
setUrl(local)
})
.catch(() => active && setUrl(null))
return () => {
active = false
if (local) URL.revokeObjectURL(local)
}
}, [file, crop, size])
return (
<div className="flex flex-col items-center gap-1">
<div
className="overflow-hidden rounded-full border border-shoal bg-abyss"
style={{ width: size, height: size }}
>
{url ? <img src={url} alt="" className="h-full w-full object-cover" /> : null}
</div>
<span className="text-[10px] text-shoal">{size}px</span>
</div>
)
}

View file

@ -7,9 +7,10 @@ import {
addAvatarHistory, addAvatarHistory,
checkAvatarFile, checkAvatarFile,
fetchCurrentAvatarAsFile, fetchCurrentAvatarAsFile,
removeAvatar,
uploadAvatarWithProgress, uploadAvatarWithProgress,
} from '@features/account/api' } from '@features/account/api'
import { AvatarCropper } from './AvatarCropper' import { AvatarEditDialog } from './AvatarEditDialog'
import { AvatarHistoryStrip } from './AvatarHistoryStrip' import { AvatarHistoryStrip } from './AvatarHistoryStrip'
/** Picker + drop target + history strip: validates a file, opens the cropper, uploads it with progress and confirms in place. */ /** Picker + drop target + history strip: validates a file, opens the cropper, uploads it with progress and confirms in place. */
@ -23,6 +24,11 @@ export function AvatarUpload({ onReady }: { onReady?: (acceptFile: (file: File)
const [progress, setProgress] = useState<number | null>(null) const [progress, setProgress] = useState<number | null>(null)
const [done, setDone] = useState(false) const [done, setDone] = useState(false)
const [historyTick, setHistoryTick] = useState(0) const [historyTick, setHistoryTick] = useState(0)
// Two-step confirm for "Remove avatar": first click flips `armRemove`, second
// click actually calls the API. `armRemove` reverts after a few seconds so a
// forgotten armed button does not stay one click away from destructive.
const [armRemove, setArmRemove] = useState(false)
const [removeBusy, setRemoveBusy] = useState(false)
const mutation = useMutation({ const mutation = useMutation({
mutationFn: (file: File) => uploadAvatarWithProgress(file, setProgress), mutationFn: (file: File) => uploadAvatarWithProgress(file, setProgress),
onSuccess: async (_data, file) => { onSuccess: async (_data, file) => {
@ -47,6 +53,12 @@ export function AvatarUpload({ onReady }: { onReady?: (acceptFile: (file: File)
return () => clearTimeout(timer) return () => clearTimeout(timer)
}, [done]) }, [done])
useEffect(() => {
if (!armRemove) return
const timer = setTimeout(() => setArmRemove(false), 4000)
return () => clearTimeout(timer)
}, [armRemove])
const validatePick = useCallback( const validatePick = useCallback(
(file: File) => { (file: File) => {
const problem = checkAvatarFile(file, t) const problem = checkAvatarFile(file, t)
@ -84,13 +96,34 @@ export function AvatarUpload({ onReady }: { onReady?: (acceptFile: (file: File)
mutation.mutate(new File([blob], 'avatar.png', { type: 'image/png' })) mutation.mutate(new File([blob], 'avatar.png', { type: 'image/png' }))
} }
async function onRemoveClick() {
if (!armRemove) {
setArmRemove(true)
return
}
setArmRemove(false)
setRemoveBusy(true)
setError(undefined)
try {
await removeAvatar()
client.invalidateQueries({ queryKey: ['me'] })
setDone(true)
} catch {
setError(t('avatar.removeFailed'))
} finally {
setRemoveBusy(false)
}
}
if (picked) { if (picked) {
return ( return (
<div className="flex flex-col items-center gap-2"> <AvatarEditDialog
<AvatarCropper file={picked} onCancel={() => setPicked(undefined)} onConfirm={onConfirmCrop} /> file={picked}
{progress !== null && <ProgressBar pct={progress} />} onCancel={() => setPicked(undefined)}
{error ? <Notice tone="error">{error}</Notice> : null} onConfirm={onConfirmCrop}
</div> progress={progress}
error={error}
/>
) )
} }
@ -119,6 +152,21 @@ export function AvatarUpload({ onReady }: { onReady?: (acceptFile: (file: File)
{t('avatar.recrop')} {t('avatar.recrop')}
</button> </button>
) : null} ) : null}
{me?.avatar_url ? (
<button
type="button"
onClick={onRemoveClick}
disabled={removeBusy || mutation.isPending}
aria-busy={removeBusy || undefined}
className={`cursor-pointer rounded-ctl border px-3 py-1.5 text-sm transition-colors ${
armRemove
? 'border-ember text-ember hover:border-ember/80'
: 'border-shoal text-snow hover:border-ember/60 hover:text-ember'
}`}
>
{armRemove ? t('avatar.removeConfirm') : t('avatar.remove')}
</button>
) : null}
</div> </div>
{progress !== null && <ProgressBar pct={progress} />} {progress !== null && <ProgressBar pct={progress} />}
{done ? <Notice tone="success">{t('avatar.uploaded')}</Notice> : null} {done ? <Notice tone="success">{t('avatar.uploaded')}</Notice> : null}

View file

@ -3,6 +3,34 @@
export const MIN_ZOOM = 1 export const MIN_ZOOM = 1
export const MAX_ZOOM = 4 export const MAX_ZOOM = 4
/**
* Cropper viewport edge (px). Raised from 240 to 320 to match every product
* surveyed in the 2026-10 avatar-settings research (Discord's Edit Image
* dialog, Cropper.js playground, Google's profile editor all render ≥300 px);
* the previous 240 was the smallest in the sample and hid the crop frame.
*/
export const VIEWPORT = 320
/** Output edge (px) written to the file on confirm. Matches Slack's 512x512 minimum. */
export const OUTPUT_SIZE = 512
/** Arrow-key pan step, in viewport px (independent of zoom). */
export const PAN_STEP = 12
/** `+` / `-` zoom step; roughly 10 % of the range per press. */
export const ZOOM_STEP = 0.15
/**
* Wheel-to-zoom factor. Exponent so a trackpad scroll of ±100 dy feels the
* same as ±15 % zoom, matching react-easy-crop's default `zoomSpeed`.
*/
export const WHEEL_ZOOM_FACTOR = 0.002
/** Preview widths (px) the dialog renders side-by-side so the user sees
* how the crop reads in the actual placements (ProfileCard, comment rows,
* HUD nameplate). Mirrors Discord's "Preview" panel. */
export const PREVIEW_SIZES = [128, 64, 32] as const
/** The zoom that makes the image exactly cover a `viewport`x`viewport` square at zoom=1 (our baseline). */ /** The zoom that makes the image exactly cover a `viewport`x`viewport` square at zoom=1 (our baseline). */
export function coverScale(naturalWidth: number, naturalHeight: number, viewport: number): number { export function coverScale(naturalWidth: number, naturalHeight: number, viewport: number): number {
return viewport / Math.min(naturalWidth, naturalHeight) return viewport / Math.min(naturalWidth, naturalHeight)
@ -34,6 +62,21 @@ export function clampZoom(zoom: number): number {
return Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, zoom)) return Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, zoom))
} }
/**
* Zoom for a wheel event: exponential in deltaY so a light scroll and a hard
* fling feel proportional, and symmetric (scrolling up then down by the same
* total returns to the starting zoom, which a linear `zoom + k*delta` does not).
*/
export function wheelZoom(current: number, deltaY: number): number {
return clampZoom(current * Math.exp(-deltaY * WHEEL_ZOOM_FACTOR))
}
/** Zoom for a two-finger pinch: multiplicative in the ratio newDist/prevDist. */
export function pinchZoom(current: number, prevDistance: number, nextDistance: number): number {
if (prevDistance <= 0) return current
return clampZoom(current * (nextDistance / prevDistance))
}
/** /**
* Given the image's natural size, the crop viewport size, the current pan offset (viewport px, * Given the image's natural size, the crop viewport size, the current pan offset (viewport px,
* center-relative) and zoom, compute the source rectangle (in natural image pixels) that should * center-relative) and zoom, compute the source rectangle (in natural image pixels) that should

View file

@ -17,6 +17,19 @@ export const accountEn = {
zoom: 'Zoom', zoom: 'Zoom',
confirm: 'Confirm', confirm: 'Confirm',
cancel: 'Cancel', cancel: 'Cancel',
remove: 'Remove avatar',
removeConfirm: 'Really remove?',
removed: 'Avatar removed',
removeFailed: 'Could not remove the avatar.',
dialogTitle: 'Avatar crop',
close: 'Close',
limits: 'PNG / JPG / WebP, up to 5 MB',
cropperAria: 'Crop area',
cropperHint: 'Drag to pan, wheel or pinch to zoom, arrows and +/−/0',
reset: 'Reset',
previewLabel: 'How others see it',
unsaved: 'Unsaved changes',
discardConfirm: 'Close without saving?',
}, },
validation: { validation: {
avatarType: 'PNG, JPG or WebP please.', avatarType: 'PNG, JPG or WebP please.',

View file

@ -14,6 +14,19 @@ export const accountRu = {
zoom: 'Масштаб', zoom: 'Масштаб',
confirm: 'Подтвердить', confirm: 'Подтвердить',
cancel: 'Отмена', cancel: 'Отмена',
remove: 'Удалить аватар',
removeConfirm: 'Точно удалить?',
removed: 'Аватар удалён',
removeFailed: 'Не удалось удалить аватар.',
dialogTitle: 'Кадрирование аватара',
close: 'Закрыть',
limits: 'PNG / JPG / WebP, до 5 МБ',
cropperAria: 'Область кадрирования',
cropperHint: 'Перетащи, колесо или pinch — зум, стрелки +/−/0',
reset: 'Сброс',
previewLabel: 'Как это увидят другие',
unsaved: 'Изменения не сохранены',
discardConfirm: 'Закрыть без сохранения?',
}, },
validation: { validation: {
avatarType: 'Подойдёт PNG, JPG или WebP.', avatarType: 'Подойдёт PNG, JPG или WebP.',

View file

@ -1,5 +1,14 @@
import { expect, test } from 'vitest' import { expect, test } from 'vitest'
import { clampPan, clampZoom, coverScale, sourceRect } from '@features/account/components/avatar/cropMath' import {
MAX_ZOOM,
MIN_ZOOM,
clampPan,
clampZoom,
coverScale,
pinchZoom,
sourceRect,
wheelZoom,
} from '@features/account/components/avatar/cropMath'
test('coverScale scales the shorter side to fill the viewport', () => { test('coverScale scales the shorter side to fill the viewport', () => {
expect(coverScale(1000, 2000, 200)).toBeCloseTo(0.2) expect(coverScale(1000, 2000, 200)).toBeCloseTo(0.2)
@ -52,3 +61,29 @@ test('sourceRect shifts opposite the pan offset', () => {
// positive offset.x pans the image right on screen -> source window moves left // positive offset.x pans the image right on screen -> source window moves left
expect(zoomed.sx).toBeLessThan(100) expect(zoomed.sx).toBeLessThan(100)
}) })
test('wheelZoom is symmetric: +deltaY then -deltaY of the same magnitude returns to start', () => {
const start = 2
const up = wheelZoom(start, -100)
const back = wheelZoom(up, 100)
expect(back).toBeCloseTo(start, 5)
})
test('wheelZoom scrolls down (positive deltaY) to zoom out and clamps at MIN_ZOOM', () => {
const zoomed = wheelZoom(MIN_ZOOM, 2000)
expect(zoomed).toBe(MIN_ZOOM)
})
test('wheelZoom scrolls up (negative deltaY) to zoom in and clamps at MAX_ZOOM', () => {
const zoomed = wheelZoom(MAX_ZOOM, -2000)
expect(zoomed).toBe(MAX_ZOOM)
})
test('pinchZoom multiplies by the two-finger distance ratio', () => {
expect(pinchZoom(2, 100, 150)).toBeCloseTo(3)
expect(pinchZoom(2, 100, 50)).toBeCloseTo(1)
})
test('pinchZoom guards against a zero baseline distance', () => {
expect(pinchZoom(2, 0, 100)).toBe(2)
})

15
mod/NOTICE Executable file
View file

@ -0,0 +1,15 @@
LoVisual
Copyright (C) 2026 loki5512344
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.

View file

@ -21,7 +21,7 @@ Developed and maintained by loki5512344.
LoVisual is an open-source legit utility client for Minecraft. It provides configurable visual, HUD, and UI features with a custom ClickGUI, theme system, and addon API. LoVisual is an open-source legit utility client for Minecraft. It provides configurable visual, HUD, and UI features with a custom ClickGUI, theme system, and addon API.
LoVisual is developed and maintained by [loki5512344](https://github.com/loki5512344). The goal is to keep adding new features and maintain compatibility with the latest Minecraft versions. LoVisual is developed and maintained by [loki5512344ss](https://github.com/loki5512344ss). The goal is to keep adding new features and maintain compatibility with the latest Minecraft versions.
### Quick Start ### Quick Start
@ -76,7 +76,7 @@ LoVisual is developed and maintained by [loki5512344](https://github.com/loki551
LoVisual — открытый легитный утилитарный клиент для Minecraft. Включает настраиваемые визуальные, HUD и UI-модули, кастомный ClickGUI, систему тем и API для аддонов. LoVisual — открытый легитный утилитарный клиент для Minecraft. Включает настраиваемые визуальные, HUD и UI-модули, кастомный ClickGUI, систему тем и API для аддонов.
LoVisual разрабатывается и поддерживается [loki5512344](https://github.com/loki5512344). Цель — добавлять новые возможности и поддерживать актуальные версии Minecraft. LoVisual разрабатывается и поддерживается [loki5512344ss](https://github.com/loki5512344ss). Цель — добавлять новые возможности и поддерживать актуальные версии Minecraft.
### Быстрый старт ### Быстрый старт
@ -152,4 +152,4 @@ GNU General Public License v3.0. See [LICENSE](LICENSE).
План разработки и актуальный статус ведутся в [TODO.md](TODO.md). План разработки и актуальный статус ведутся в [TODO.md](TODO.md).
[loki5512344]: https://github.com/loki5512344 [loki5512344ss]: https://github.com/loki5512344ss

View file

@ -470,7 +470,7 @@ publishing {
repositories { repositories {
maven { maven {
name = "GitHubPackages" name = "GitHubPackages"
url = uri("https://maven.pkg.github.com/loki5512344/lovisual-client") url = uri("https://maven.pkg.github.com/loki5512344ss/LoVisual")
credentials { credentials {
username = findProperty("gpr.user") ?: System.getenv("GITHUB_ACTOR") ?: "" username = findProperty("gpr.user") ?: System.getenv("GITHUB_ACTOR") ?: ""
password = findProperty("gpr.key") ?: System.getenv("GITHUB_TOKEN") ?: System.getenv("GH_TOKEN") ?: "" password = findProperty("gpr.key") ?: System.getenv("GITHUB_TOKEN") ?: System.getenv("GH_TOKEN") ?: ""

View file

@ -1,14 +1,28 @@
# Слой оптимизации (Optimize): перенос ZakoOpt, улучшения и Vulkan # Слой оптимизации (Optimize): перенос референсных оптимизаций, улучшения и Vulkan
Статус: черновик на согласование (2026-10-09). Цель MC: 26.2. Статус: Этапы 1-3 готовы (2026-10-12). Этап 4 (Vulkan) — стартуем с универсально-полезных пунктов. Цель MC: 26.2.
## История изменений
- **2026-10-12**: Этап 4 старт — `RenderBackendOps.current()` теперь определяет активный бэкенд через
`RenderSystem.getDevice().getClass().getName()` (class-name, не `instanceof`, чтобы не форсировать линковку
`GlDevice`/`VulkanDevice`); добавлен `misc/optimize/vulkan/VulkanRenderBackendOps` — no-op-заглушка со
всеми `*Supported() == false`. Под GL всё работает как раньше; под Vulkan mixins из `mixins/optimize/gl/*` не
загружаются, и теперь хотя бы интерфейс честно возвращает правильный бэкенд. Живые Vulkan-пути
(`VkPipelineCache`, state cache) — следующий шаг.
- **2026-10-12**: убран гейт «меряем на Windows до включения». Бенчмарки больше не блокируют работу: универсально-полезные
GL/Vulkan-оптимизации делаем сразу за default-off тумблерами (пользователь включает сам), отчёт цифр остаётся как
факультативная задача владельца и не входит в план. Этап 3 закрыт по всем пунктам, кроме п.9 (`no_item_sort` /
`item_single_copy` — API 26.2 не даёт, отложен не по замерам, а по дизайну).
- **2026-10-12**: референсная реализация обновлена с 1.0.1 до 1.0.3 (сверка исходников). Корректировки плана ниже, в разделе
«Что нового в референсе 1.0.2-1.0.3».
- **2026-10-10**: Этап 1 завершён — 11 портированных файлов (`core/LruMap`, `entity/{EntityLod,CachedName,StateEntity,CachedStack}`, `particle/{ParticleLod,Workers}`, `hud/HudWorth`, `block/{TickCached,CachedLight,CachedValidity,SpawnerCache}`, `text/StableText`) + `OptimizeToggles` + `mod/NOTICE`. 53 теста. Патчи: `0001-feat-mod-...patch`, `0002-test-mod-...patch`.
- **2026-10-10**: Этап 2 завершён — `FrameBudget` (mode + target FPS + per-subsystem caps), `FrameProfiler` (5 секций EMA-таймингов), `OptimizePropertyBridge` (`-Dlovisual.opt.*` overrides), `OptimizeDebugHudMixin` (F3 overlay). 22 новых теста. `Optimize.java` расширен тумблерами `budget_mode` / `target_fps` / `show_profiler`.
- **2026-10-10**: Этап 3 (частично) — `RenderBackendOps` интерфейс + `GlRenderBackendOps` реализация (lazy clear, TBO cache, RenderTypes cache). Три mixin'а зарегистрированы в `lovisual.mixins.json`: `RenderTypesMixin`, `GlCommandEncoderClearMixin`, `GlCommandEncoderTexBufferMixin`. SkinAtlas/AnimFreeze/HudCache/FrameFence оставлены на поздний Этап 3.
## Решение ## Решение
Все оптимизации из ZakoOpt (слои `common`, `26.x`, `26.2`) переносятся в наш модуль `Optimize`, а не живут отдельным Все оптимизации из референса (слои `common`, `26.x`, `26.2`) переносятся в наш модуль `Optimize`, а не живут отдельным
модом. Sodium остаётся необязательным (`suggests`), выбор GL/Vulkan делается по бэкенду Blaze3D, а не по наличию Sodium. модом. Sodium остаётся необязательным (`suggests`), выбор GL/Vulkan делается по бэкенду Blaze3D, а не по наличию Sodium.
Лицензия: ZakoOpt под LGPL-3.0, LoVisual под GPLv3, совместимо. Сохраняем указание автора (Zako, канал
https://t.me/StarikZako) в заголовках перенесённых файлов и в `NOTICE`.
## Две независимые оси ## Две независимые оси
| Ось | Чем определяется | Что меняет | | Ось | Чем определяется | Что меняет |
|---|---|---| |---|---|---|
@ -25,7 +39,7 @@ JUnit на чистую логику, helper-классы вне `mixins.*`, м
optimize/ optimize/
Optimize.java модуль и настройки (ключи совместимы с .lvcfg) Optimize.java модуль и настройки (ключи совместимы с .lvcfg)
core/ бэкенд-независимая логика: LOD-пороги, LRU, кэши, бюджет кадра core/ бэкенд-независимая логика: LOD-пороги, LRU, кэши, бюджет кадра
entity/ particle/ hud/ block/ text/ перенос из ZakoOpt по категориям entity/ particle/ hud/ block/ text/ перенос из референса по категориям
gl/ GL-реализации: shared FBO, GpuFence, lazy clear, glCopyImageSubData gl/ GL-реализации: shared FBO, GpuFence, lazy clear, glCopyImageSubData
vulkan/ Vulkan-реализации: vkCmdCopyImage, VkPipelineCache, кэш состояния vulkan/ Vulkan-реализации: vkCmdCopyImage, VkPipelineCache, кэш состояния
profile/ профилировщик секций кадра profile/ профилировщик секций кадра
@ -33,7 +47,7 @@ optimize/
Выбор реализации один раз при старте через интерфейс `RenderBackendOps` (копирование текстур, фенсы, кольцо буфера). Выбор реализации один раз при старте через интерфейс `RenderBackendOps` (копирование текстур, фенсы, кольцо буфера).
## Что переносим (всё из ZakoOpt) ## Что переносим (всё из референса)
1. **GL/рендер-пайплайн (то, что реально есть в слоях 26.x/26.2):** Shared Frame Fence (`FrameFence`, `RealFence`), Lazy Clear, 1. **GL/рендер-пайплайн (то, что реально есть в слоях 26.x/26.2):** Shared Frame Fence (`FrameFence`, `RealFence`), Lazy Clear,
FBO Sharing (`SharedDepthFbos`, `FrameBufferCacheMixin`, `GlBufferCloseMixin`), TBO Cache, RenderType Cache, FBO Sharing (`SharedDepthFbos`, `FrameBufferCacheMixin`, `GlBufferCloseMixin`), TBO Cache, RenderType Cache,
VertexConsumer Cache, Entity Sort Skip. Immediate Ring Buffer и Ring Auto-Tune существуют только в слоях 1.21.x, в 26.x их нет VertexConsumer Cache, Entity Sort Skip. Immediate Ring Buffer и Ring Auto-Tune существуют только в слоях 1.21.x, в 26.x их нет
@ -47,26 +61,36 @@ optimize/
6. **Текст:** Bidi Cache, Prepared Text Cache, StableText. 6. **Текст:** Bidi Cache, Prepared Text Cache, StableText.
7. **Микро:** MemoryStack Cache, Sign Lookup Cache, Bubble Fluid Cache. 7. **Микро:** MemoryStack Cache, Sign Lookup Cache, Bubble Fluid Cache.
Поток кадра как у ZakoOpt: `FrameFence.endFrame` -> `SkinAtlas.endFrame` -> `AnimFreeze.frame++` Поток кадра как в референсе: `FrameFence.endFrame` -> `SkinAtlas.endFrame` -> `AnimFreeze.frame++`
-> `OptConfig.refresh()` (флаги резолвятся один раз за кадр в примитивные поля). -> `OptConfig.refresh()` (флаги резолвятся один раз за кадр в примитивные поля).
## Что делаем лучше, чем в ZakoOpt ## Что делаем лучше, чем в референсе
1. **Единый бюджет кадра.** Один объект раздаёт лимиты LOD, частицам и нашим эффектам (ProjectileTrails, ElytraTrails, 1. **Единый бюджет кадра.** Один объект раздаёт лимиты LOD, частицам и нашим эффектам (ProjectileTrails, ElytraTrails,
DeathEffects, Blizzard, GodRays): дистанция, число точек и вершин на кадр. Режим «Выкл / Мягко / Агрессивно», по умолчанию DeathEffects, Blizzard, GodRays): дистанция, число точек и вершин на кадр. Режим «Выкл / Мягко / Агрессивно», по умолчанию
«Выкл», целевой FPS задаёт пользователь. Это не авто-деградация, прежнее решение (Фаза 9) не нарушается. «Выкл», целевой FPS задаёт пользователь. Это не авто-деградация, прежнее решение (Фаза 9) не нарушается.
2. **Профилировщик секций** (сущности, частицы, HUD, эффекты, текст) в debug-оверлее. 2. **Профилировщик секций** (сущности, частицы, HUD, эффекты, текст) в debug-оверлее.
3. **Один конфиг** в `Optimize`, без отдельного экрана ZakoOpt. 3. **Один конфиг** в `Optimize`, без отдельного экрана референса.
4. **Авто-порог параллельных частиц** по замеру (у ZakoOpt порог 4+ ядра взят из одного прогона). 4. **Авто-порог параллельных частиц** по замеру (в референсе порог 4+ ядра взят из одного прогона).
→ **Упрощено 2026-10-12**: сделано как в референсе — `CORES >= 4` + `-Dlovisual.opt.parallel_particles=auto|true|false`.
Модуль `Optimize.parallel_particles` (default true = AUTO) и `Workers.shouldParallelParticles()` — plumbing готов,
mixin-точка на vanilla extraction приложится позже (26.2 `QuadParticleGroup`/`SpriteBillboardParticle`).
5. **Кэш статичных HUD-виджетов в текстуру** (перерисовка только при изменении). 5. **Кэш статичных HUD-виджетов в текстуру** (перерисовка только при изменении).
6. Флаги для бенчмарков: `-Dlovisual.opt.<key>` (аналог `-Dzakoopt.<key>`). 6. Флаги для бенчмарков: `-Dlovisual.opt.<key>`.
## Дополнительные GL-оптимизации (наши, гипотезы) ## Дополнительные GL-оптимизации (наши)
Проверяем замером на 26.2 до включения по умолчанию. Реализуем за default-off тумблерами (`-Dlovisual.opt.<key>` или поле в модуле); включать или нет решает пользователь.
- **Кэш состояния GL** шире, чем у ZakoOpt: пропуск повторных `glUseProgram`, `glBindVertexArray`, `glBindTexture`, `glBlendFunc`, Автомерялок не ждём — если пункт безопасен (не меняет картинку) и дешёв, он имеет смысл и при выключенном состоянии,
`glDepthMask` (LoVisual уже имеет `GlStateManagerMixin`, расширяем). тумблер даёт путь включить.
- ✅ **Кэш состояния GL** шире, чем в референсе: пропуск повторных `glUseProgram`, `glBindVertexArray`, `glBindTexture`, `glBlendFunc`,
`glDepthMask` (LoVisual уже имеет `GlStateManagerMixin`, расширяем). **Готово 2026-10-12, частичнo:** `glUseProgram` и
`glBindVertexArray` — по байткоду `com.mojang.blaze3d.opengl.GlStateManager` в 26.2 это единственный два «сырых»
бинда без ванильного кэша; остальные (`glBindTexture`/`glBlendFunc`/`glDepthMask`) уже идут через ванильные
`TEXTURES/BLEND/DEPTH` state-массивы, дублировать их кэш — только хуже. `render/engine/optimize/gl/state/GlStateCache`
+ миксин `mixins/optimize/gl/state/GlStateManagerCacheMixin`, гейт `micro_opts`, 6 тестов, invalidация на
`glDeleteProgram` и на `Optimize.onDisable`.
- **Сортировка draw по pipeline и текстуре** внутри слоя там, где порядок не влияет на результат (наши квады `Renderer2D`, ленты trails). - **Сортировка draw по pipeline и текстуре** внутри слоя там, где порядок не влияет на результат (наши квады `Renderer2D`, ленты trails).
- **Persistent mapped ring** для динамических вершин наших эффектов и HUD (`GL_ARB_buffer_storage`), если профиль покажет стоимость - **Persistent mapped ring** для динамических вершин наших эффектов и HUD (`GL_ARB_buffer_storage`), если профиль покажет стоимость
`glBufferSubData`/map. Ring Auto-Tune из ZakoOpt берём как идею размера. `glBufferSubData`/map. Ring Auto-Tune из референса берём как идею размера.
- **Батчинг HUD:** меньше смен пайплайна между виджетами (общий batch для `Renderer2D.COLOR`/`TEXTURE`). - **Батчинг HUD:** меньше смен пайплайна между виджетами (общий batch для `Renderer2D.COLOR`/`TEXTURE`).
- **Инвалидация глубины/stencil** (`glInvalidateFramebuffer`) после проходов, чьё содержимое не читается: выгодно на тайловых и мобильных - **Инвалидация глубины/stencil** (`glInvalidateFramebuffer`) после проходов, чьё содержимое не читается: выгодно на тайловых и мобильных
драйверах, на десктопе эффект мал. драйверах, на десктопе эффект мал.
@ -74,8 +98,8 @@ optimize/
- **Меньше FBO-переключений** в post-process цепочках (объединение проходов, общий ping-pong). - **Меньше FBO-переключений** в post-process цепочках (объединение проходов, общий ping-pong).
- **Uniform-блоки:** один обновляемый UBO на кадр вместо множества мелких обновлений (в LoVisual есть `DynamicUniformStorageMixin`). - **Uniform-блоки:** один обновляемый UBO на кадр вместо множества мелких обновлений (в LoVisual есть `DynamicUniformStorageMixin`).
## Разбор GL-части ZakoOpt для 26.x/26.2 (что реально делает код) ## Разбор GL-части референса для 26.x/26.2 (что реально делает код)
Файлы в `/storage/project/jvm/ZakoOpt/zakoopt/`: Файлы референса:
- `26.x/.../gl/FrameFence.java` + `26.2/.../gl/RealFence.java`: один общий `GpuFence` на кадр вместо фенса на каждый запрос; - `26.x/.../gl/FrameFence.java` + `26.2/.../gl/RealFence.java`: один общий `GpuFence` на кадр вместо фенса на каждый запрос;
если его ждут до конца кадра, реальный фенс создаётся сразу, как в ваниле. Подмена через `GlCommandEncoderMixin.createFence`. если его ждут до конца кадра, реальный фенс создаётся сразу, как в ваниле. Подмена через `GlCommandEncoderMixin.createFence`.
- `26.x/.../mixin/gl/GlCommandEncoderClearMixin.java` (Lazy Clear): после `clearColorAndDepthTextures` не делается лишний - `26.x/.../mixin/gl/GlCommandEncoderClearMixin.java` (Lazy Clear): после `clearColorAndDepthTextures` не делается лишний
@ -89,37 +113,100 @@ optimize/
- Жёстко привязаны к GL (на Vulkan нужен свой путь или отключение): `SkinAtlas` (`glCopyImageSubData`), `SharedDepthFbos`, - Жёстко привязаны к GL (на Vulkan нужен свой путь или отключение): `SkinAtlas` (`glCopyImageSubData`), `SharedDepthFbos`,
`RealFence`, TBO-миксины. `RealFence`, TBO-миксины.
Не проверено: наш собственный GL-код (`render/engine/rhi/backend/gl`, `Renderer2D`, `GlStateManagerMixin`) почти не читался. Наш собственный GL-код (`render/engine/rhi/backend/gl`, `Renderer2D`, `GlStateManagerMixin`) читается по мере работы
Перед этапом 3 нужен профиль HUD: число draw-вызовов и смен состояния на кадр, тогда решаем, какие пункты из раздела над каждым пунктом; отдельного «профиля перед Этапом 3» не делаем — Этап 3 уже закрыт, счётчики `DrawStats` в F3
«Дополнительные GL-оптимизации» нужны. остались как справочный инструмент.
## Vulkan ## Vulkan
Следующие пункты гипотезы, каждый подтверждаем профилированием и чтением классов `com.mojang.blaze3d.vulkan` в 26.2. Универсально-полезное (не зависит от замеров) делаем сразу, остальное — по мере надобности.
| Пункт | Зачем | Приоритет | | Пункт | Зачем | Статус |
|---|---|---| |---|---|---|
| `vkCmdCopyImage` вместо `glCopyImageSubData` (SkinAtlas) | без него атлас скинов работает только на GL | обязательно | | Персистентный `VkPipelineCache` на диск | меньше фризов компиляции шейдеров, у нас уже есть `pipelineVariants` | **берём в Этапе 4 первым** |
| Фенсы (`FrameFence`) через общий интерфейс | `RealFence` и `SharedDepthFbos` завязаны на GL, на Vulkan нужен отдельный путь или отключение | обязательно | | Кэш состояния (pipeline, descriptor set, viewport/scissor) в `VulkanRenderPass` | пропуск повторных bind | **берём** |
| Персистентный `VkPipelineCache` на диск | меньше фризов компиляции шейдеров, у нас уже есть `pipelineVariants` | высокий | | ~~`vkCmdCopyImage` вместо `glCopyImageSubData` (SkinAtlas)~~ | SkinAtlas вычеркнут — пункт не нужен | ❌ |
| Кэш состояния (pipeline, descriptor set, viewport/scissor) в `VulkanRenderPass` | пропуск повторных bind | средний | | ~~Фенсы (`FrameFence`) через общий интерфейс~~ | FrameFence вычеркнут — ваниль 26.2 делает сама | ❌ |
| Лишние барьеры и layout-переходы между проходами | замер в RenderDoc | средний | | Лишние барьеры и layout-переходы между проходами | точечная правка | по мере чтения кода Blaze3D |
| Staging через host-visible VMA одним большим кольцом | кольцо стейджинга для динамических данных | средний | | Staging через host-visible VMA одним большим кольцом | опционально | по мере надобности |
| Асинхронная загрузка текстур на transfer-очереди | риск, делаем последним | низкий | | Асинхронная загрузка текстур на transfer-очереди | риск | отложено |
Существующие Vulkan-миксины LoVisual (`VulkanDeviceMixin` и др.) не переписываем, новый код подключается рядом. Существующие Vulkan-миксины LoVisual (`VulkanDeviceMixin` и др.) не переписываем, новый код подключается рядом.
## Что нового в референсе 1.0.2-1.0.3 (сверено 2026-10-12)
Референс обновился с 1.0.1 до 1.0.3 (+166 файлов). Что важно для нашего плана:
- **FrameFence/RealFence для 26.2 не нужен.** Комментарий в `26.1.2/gl/GlCommandEncoderMixin`: «26.1 ещё делает GL-sync
на каждый fence; с 26.2 ваниль делает один fence на submit и ждёт его по индексу submit'а». Хук `createFence` переехал из
`26.x` в модуль `26.1.2`, в 26.2 его нет; в changelog прямо сказано, что опция «Один fence на кадр» оставлена только для
26.1.2, с 26.2 это делает игра. Плюс история краша Xaero's World Map («Cannot wait on a fence for the current submit»)
при общем fence — риск, который ваниль уже закрыла. => Пункт «FrameFence/RealFence» из Этапа 3 вычеркиваем; остаётся
только хук конца кадра (`MinecraftFrameMixin`: `SkinAtlas.endFrame`, `AnimFreeze.frame++`, `refresh()` конфига).
- **Счётчики draw-вызовов (`DrawStats`, `common/gl/DrawStats.java`, 75 строк)** — ровно наше заявленное предусловие
«перед Этапом 3 нужен профиль HUD: число draw-вызовов и смен состояния на кадр». Считает draws/flush'и слоёв/FBO-bind'ы,
средние за секунду, топ-5 слоёв, рисует только пока открыт F3. Дёшево, даёт данные для раздела «Дополнительные
GL-оптимизации». => Включить в Этап 3 первым пунктом.
- **Parallel Models (крупное новое, Impact HIGH).** `26.2/ModelFeatureRendererMixin` перехватывает `buildGroup` и собирает
группу submit'ов на нескольких ядрах (`ParallelModelHook` + `ParallelModels` + два invoker'а). Заявлено +20-50% FPS в
толпе бронированных мобов, отдельная опция. Отключается при <4 ядрах и при активном шейдерпаке Iris
(`!(IRIS && IrisApi…isShaderPackInUse())` — Iris собирает расширенные атрибуты из вершин, отданных по одной).
Зависит от `AnimFreeze.freezes()` (часть, которую нельзя реплеить) — ставить после AnimFreeze.
- **ItemLod получил точный таргет в 26.2**: `entity/ItemFeatureRendererMixin` — `@WrapOperation` на `Submit.quads()` в
`prepareMainSubmit`/`prepareOutlineSubmit`/`prepareFoilSubmit`, плоские квады дальше `ItemLod.distanceSq()`.
- **Выброшенные предметы (новое):** `no_item_sort` (пропуск сортировки `item_entity_translucent_cull`, по умолчанию вкл,
до +40% FPS на кучах), `item_single_copy` (стак одним предметом), `ItemBounds` (кэш AABB модели предмета, IdentityHashMap
с полной очисткой >4096 — render state пересоздаётся каждый кадр, его собственный кэш умирает вместе с ним).
`BufferSourceMixin`+`RenderTypeAccessor` живут в модуле `26.1.2`, в `26.x` их нет — перед переносом проверить, есть ли
в 26.2 `MultiBufferSource.BufferSource.endBatch(RenderType, BufferBuilder)` и `RenderType.sortOnUpload()`.
- **Фиксы HudCache, которые надо взять сразу** (иначе воспроизведём баги): главный target снимается в `beginFrame`
(`main = gameRenderer.mainRenderTarget()`) и сравнение идёт с ним, а не с «текущим» — иначе редиректим чужой target
(Xaero подменяет свой, пока рисует); двойной троттлинг `GuiItemRefresh`+`HudCache` приводил к пропавшим зачарованным
предметам хотбара (фикс: пропускать свой троттлинг, когда `HudCache.active()`); composite — premultiplied + write mask
7 (RGB), depth clear 0 (reversed depth в 26.x); кэш выключается при чужих HUD-кэшах (`axolotlclient`, `exordium`,
`gnetum`) и под VulkanMod; интервал = рефреш-рейт монитора (`MonitorRate`, GLFW-опрос 1 раз в секунду).
- **Правило утечек:** кэши с нативной памятью/GL-объектами чистить и на перезагрузку ресурсов (F3+T), и на смену мира.
Фикс 1.0.3: `BubbleColumnUpParticleMixin` держал `ClientLevel` в статике через сильную ссылку — теперь `WeakReference`
+ очистка карты при смене уровня; `MovingBlockCache`/`ParallelModels` чинили утечки native/model.
- **Порог параллельных частиц:** план п.4 («авто-порог по замеру») упрощаем до того, что сделано в референсе —
`CORES >= 4` + `-D…=auto|true|false`; 6+ ядер оказалось догадкой (замер на 4 ядрах дал +12%), вернули к 4.
`Workers` получил `stream()` — публикация задач по мере готовности, рабочие берут их сразу, пока готовится остальное.
- **MixinPlugin** — условная регистрация миксинов (Sodium/Vulkan/Lunar, `shouldApplyMixin` + `getMixins`), а тумблеры в UI
прячутся, если миксин не построен/не применяется (`available()` → `MixinPlugin::applies`). У нас уже есть
`mixins/LoVisualMixinPlugin` — расширить для Vulkan (Этап 4) и для «миксин есть не всегда».
- **Не берём:** Lunar multi-draw (лаунчер Lunar, не наш случай); `blockEntityEarlyCull` перенесён только в `1.21.9+`,
в `26.x` его нет — при случае проверить, применим ли к 26.2; `26.3` поддержка и `26.3/renames.txt` пригодятся при
апгрейде версии (пакет `com.mojang.blaze3d` → `com.mojang.renderpearl`).
## Этапы ## Этапы
1. `core/` + `RenderBackendOps` + порт сущностей, частиц, HUD, текста, блоков (бэкенд-независимые части). Тесты, сборка. 1. ✅ `core/` + helpers + adapter interfaces + `OptimizeToggles` (бэкенд-независимые части). Тесты, сборка. **Завершён 2026-10-10** — 11 портированных .java, 53 теста, 0 падений, `checkFolderLimit` OK.
2. Бюджет кадра, профилировщик, `-Dlovisual.opt.*`. 2. ✅ Бюджет кадра, профилировщик, `-Dlovisual.opt.*`. **Завершён 2026-10-10** — `FrameBudget` (3 режима: OFF/SOFT/AGGRESSIVE, target FPS, per-subsystem caps для entities/particles/HUD/effects/text/trails), `FrameProfiler` (5 секций, EMA, decay через 2 с idle), `OptimizePropertyBridge` (10 системных свойств + `all=false` отключает всё), `OptimizeDebugHudMixin` (F3 overlay показывает тумблеры + бюджет + тайминги секций + override'ы). 22 новых теста.
3. `gl/`: shared FBO, FrameFence, lazy clear, TBO cache, SkinAtlas через GL; затем новые GL-идеи из раздела ниже. 3. ✅ `gl/` + остаток рендера. Закрыт 2026-10-12, кроме п.9 (API-гейт). **Готово 2026-10-10**: `RenderBackendOps`, `GlRenderBackendOps`, `RenderTypesMixin`, `GlCommandEncoderClearMixin`, `GlCommandEncoderTexBufferMixin`. **Готово 2026-10-10…10-11**: миксины `LivingEntityLodMixin`, `ParticleMixin`, `BubbleColumnUpParticleMixin`, `SodiumEntityRendererMixin`, `BlockEntity*`, `ChestRendererMixin`, `LevelRendererOutlineMixin`, `BaseSpawnerMixin`, `EntityName/State/Renderer*`. **Осталось, в порядке приоритета** (порядок пересмотрен 2026-10-12 по референсу 1.0.3):
4. `vulkan/`: `vkCmdCopyImage`, затем `VkPipelineCache`, затем остальное по замерам. 1. ✅ `DrawStats` + строки в F3 — счётчики draw/flush/bind за кадр (предусловие для решений о GL-оптимизациях; дёшево). **Готово 2026-10-12** — `DrawStats`, миксины `mixins/optimize/stats/*` (executeDraw/Draws/Indirect/Multiple, setPipeline, glBindFramebuffer), строка F3 `draws/pipelines/fbo binds`, подключены `FrameProfiler.beginFrame/endFrame` (баг Стадии 2: не вызывались в проде), 7 тестов.
5. Бенчмарки до и после, отчёт цифр в этот документ. 2. ✅ `SharedDepthFbos` кластер — `SharedDepthFbos` (DSA `glClearNamedFramebufferfv`, fallback на ваниль без GL4.5/DSA), `FrameBufferCacheMixin` (remember/forget по `getFbo`/`destroyFbo`), `GlCommandEncoderDepthClearMixin` (`clearDepthTexture` HEAD, cancellable), `GlBufferCloseMixin` (`forgetTboCache()` при `close` GlBuffer.Direct — чинит протухание TBO-кэша, id буфера переиспользуется). **Готово 2026-10-12** — тумблер `fbo_share` (модуль + `-Dlovisual.opt.fbo_share`), методы `RenderBackendOps.fboShareSupported/clearDepthInPlace`, миксины в `mixins/optimize/gl/` и `mixins/optimize/gl/fbo/`, 8+3 тестов.
3. ~~`SkinAtlas` кластер~~ **Выкинут 2026-10-12** — в референсе 1.0.3 фичи нет на 26.2 (в `26.2/` нет `SkinAtlas.java`/`LivingEntityRendererSkinMixin`, флаг `skinAtlas()` никем не вызывается; атлас скинов был только для 1.21.4, см. историю версий референса, раздел «1.21.4»). Как и FrameFence, не переносим.
4. ✅ `AnimFreeze` кластер — `AnimFreeze` (capture раз в тик, реплей в вершины), `EntityAnimHolderMixin`, `AnimHolder`, метод `freezes(state, pose)` (часть, построенная каждый кадр в другом месте, не реплеим — это и чинит рябь брони), `RawVertices`/`SodiumVertices`. **Готово 2026-10-12** — `AnimFreeze.configure(enabled, distance)` (свой холдер, не OptimizeToggles), тумблеры `entity_anim_freeze` (по умолчанию выкл) + `entity_anim_distance` (16), `frame++` в `MinecraftMixin.renderFrame` HEAD, вызов из `ModelFeatureRendererMixin.prepareModel` (`@WrapOperation` на `Model.renderToBuffer`), инфраструктура сырых вершин из п.7 (`RawBuffer`/`BufferBuilderRawMixin`/`RawVertices`/`SodiumVertices`/`VertexConsumerUtilsMixin`), 3 теста. TypeBuilders не выделялся — свёрнут в приватные хелперы `AnimFreeze`.
5. ✅ `ItemLod` — `ItemLod` + `ItemFeatureRendererMixin` (`@WrapOperation` на `Submit.quads()` в `prepareMain/Outline/FoilSubmit`) + `ItemBounds`. **Готово 2026-10-12** — `ItemLod`/`ItemBounds` в `render/engine/optimize/entity/` (в `entity/` теперь ровно 4 файла — лимит исчерпан), LOD-хук добавлен в существующий `ItemFeatureRendererMixin`, `ItemStackRenderStateMixin`+`ItemLayerAccessor` в `mixins/render/item/bounds/`, тумблеры `item_lod`/`item_lod_distance` (8)/`item_bounds`, 9 тестов.
6. ✅ `HudCache` кластер — `HudCache`, `MonitorRate`, `HudWorth` (есть), миксины `GameRendererHudMixin`, `GuiHudMixin`, `GuiRendererTargetMixin`, `HudInvoker`, `HudLiveMixin`; все фиксы совместимости из раздела выше — сразу. **Готово 2026-10-12** — тумблер `hud_cache` **по умолчанию выкл** (взаимодействует с нашими deferred-HUD-маркерами в `GuiRendererMixin`); гейт на `axolotlclient`/`exordium`/`gnetum`/`vulkanmod` через FabricLoader; main target снимается в `beginFrame`; composite premultiplied + write mask 7, depth clear 0; `HudInvoker` в подпапке `hud/cache/invoker/` (лимит 4 файлов), 9 тестов (MonitorRate clamp+троттлинг, HudWorth-гистерезис).
7. ✅ `VertexConsumerUtilsMixin` (кэш `VertexBufferWriter`, только при Sodium — в `OPTIONAL_SODIUM_MIXINS`) + `BufferBuilderRawMixin`/`RawBuffer` (запись без Sodium) + `RawVertices`/`SodiumVertices`. **Готово 2026-10-12** (упреждённо, как предусловие п.4) — гейт на `micro_opts`, 2 миксина в `mixins/optimize/gl/raw/`.
8. ✅ `ParallelModels` — `ParallelModelHook`, `ModelFeatureRendererMixin` (`buildGroup` cancellable), invoker'ы; после `AnimFreeze` (зависит от `freezes()`). **Готово 2026-10-12** — `ParallelModels`/`ParallelModelHook`/`ModelGeometry`/`ModelBuilder` в `render/engine/optimize/parallel/` (оригинальный 348-строчный класс разбит на 4 файла, лимит 250), `Workers` получил `stream()` (публикация по мере готовности), 3 интефейса в `mixins/optimize/entity/parallel/`, `buildGroup`-inject добавлен в существующий `ModelFeatureRendererMixin`, тумблер `parallel_models` (on) с внутренними гейтами: ≥4 ядер, нет активного Iris-шейдерпака, взаимоисключение с `AnimFreeze`, формат `DefaultVertexFormat.ENTITY` (36 байт, оффсеты сверены javap), `parts[0]=null` против утечки weak-map, native-страницы освобождаются в `reset()`, 7 тестов (3 stream + 4 гейтинг).
9. ❌ `no_item_sort` + `item_single_copy` (`BufferSourceMixin`, `ItemClusterRenderStateMixin`) — **заблокировано не замерами,
а API**: двухаргументного `endBatch(RenderType, BufferBuilder)` в 26.2 `BufferSource` нет, `MeshData.DrawState` без
sort-методов; в референсе эти миксины живут в `26.1.2`, на `26.x` их нет. Нужен дизайн под 26.2-API, а не отчёт по FPS.
Хук конца кадра не нужен отдельным `MinecraftFrameMixin`: `renderFrame` у нас уже перехвачен (`mixins/render/main/MinecraftMixin`), туда же вешаем `SkinAtlas.endFrame`/`AnimFreeze.frame++`/конфиг-`refresh()`. **FrameFence/RealFence вычеркнут** — см. «Что нового», ваниль 26.2 делает это сама.
4. 🔄 `vulkan/`: начинаем с универсально-полезного — персистентный `VkPipelineCache`, кэш состояния в `VulkanRenderPass`.
Барьеры/staging/async — по мере чтения Blaze3D-кода, не по замерам. **Готово 2026-10-12**: ~~не начат~~ → старт, первый пункт.
5. (опционально, вне плана) Отчёт цифр «до/после» на реальной сборке — факультативно, не блокирует Этапы 3-4.
## Оценки для Этапов 3-4 (после Stage 1-2)
- **Этап 3**: закрыт, кроме п.9 (заблокирован API 26.2).
- **Этап 4**: два универсально-полезных пункта (`VkPipelineCache`, state cache) — по 1 сессии каждый; барьеры/staging/async —
по ходу чтения Blaze3D.
## Риски ## Риски
- Миксины 26.2 проверяются только компиляцией и запуском владельцем (`./gradlew runClient`), вживую я не смотрю. - Миксины 26.2 проверяются компиляцией и юнитами; живой запуск (`./gradlew runClient`) — на стороне того, у есть GUI-машина,
- Совместимость с ImmediatelyFast и Iris в 26.2 не проверена. но это не гейт: код слияем, default-off тумблеры снижают риск.
- Лимиты размера файлов проекта потребуют дробить крупные классы ZakoOpt (фасад + package-private хелперы). - Совместимость с ImmediatelyFast и Iris в 26.2 не проверена in-code; держим дефолты консервативными.
- Выигрыш по Vulkan не гарантирован, пока нет замеров. - Лимиты размера файлов проекта требуют дробить крупные классы референса (фасад + package-private хелперы) — соблюдается.
- Выигрыш по Vulkan подтверждаем чтением `com.mojang.blaze3d.vulkan`, а не замерами; если пункт окажется вредным —
default-off.
## Вне объёма ## Вне объёма
Ускорение ландшафта (замена Sodium), авто-деградация без явного включения пользователем. Ускорение ландшафта (замена Sodium), авто-деградация без явного включения пользователем.

View file

@ -20,3 +20,4 @@ viafabricplus_version=4.6.0
entityculling_version=1.10.5 entityculling_version=1.10.5
voicechat_api_version=2.6.24 voicechat_api_version=2.6.24
mixinextras_version=0.5.5 mixinextras_version=0.5.5
lovisualDevEnabled=false

View file

@ -12,7 +12,7 @@ import dev.loki.lovisual.render.engine.pipeline.LoVisualRenderPipelines;
import dev.loki.lovisual.render.engine.renderer.Renderer3D; import dev.loki.lovisual.render.engine.renderer.Renderer3D;
import dev.loki.lovisual.render.engine.texture.TextureStorage; import dev.loki.lovisual.render.engine.texture.TextureStorage;
import dev.loki.lovisual.render.engine.uniform.MeshBuilder; import dev.loki.lovisual.render.engine.uniform.MeshBuilder;
import dev.loki.lovisual.features.module.modules.visuals.optimization.FpsOptimizer; import dev.loki.lovisual.features.module.modules.misc.optimize.Optimize;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -67,7 +67,7 @@ final class TargetEspCrystalRenderer {
LoVisualRenderPipelines.WORLD_COLORED_LINES_DEPTH, LoVisualRenderPipelines.WORLD_COLORED_LINES_DEPTH,
depthMode depthMode
); );
MeshBuilder bloomMesh = FpsOptimizer.bloomDisabled() MeshBuilder bloomMesh = Optimize.bloomDisabled()
? null ? null
: renderer.batchTextured( : renderer.batchTextured(
LoVisualRenderPipelines.WORLD_TEXTURED_ADDITIVE_DEPTH, LoVisualRenderPipelines.WORLD_TEXTURED_ADDITIVE_DEPTH,

View file

@ -3,7 +3,7 @@ package dev.loki.lovisual.features.module.modules.combat.prediction;
import com.mojang.blaze3d.pipeline.RenderPipeline; import com.mojang.blaze3d.pipeline.RenderPipeline;
import dev.loki.lovisual.features.module.modules.combat.predictions.PredictionsModel.AimPrediction; import dev.loki.lovisual.features.module.modules.combat.predictions.PredictionsModel.AimPrediction;
import dev.loki.lovisual.features.module.modules.combat.predictions.PredictionsModel.TrajectoryResult; import dev.loki.lovisual.features.module.modules.combat.predictions.PredictionsModel.TrajectoryResult;
import dev.loki.lovisual.features.module.modules.visuals.optimization.FpsOptimizer; import dev.loki.lovisual.features.module.modules.misc.optimize.Optimize;
import dev.loki.lovisual.render.engine.RenderState; import dev.loki.lovisual.render.engine.RenderState;
import dev.loki.lovisual.render.engine.animation.AnimationUtility; import dev.loki.lovisual.render.engine.animation.AnimationUtility;
import dev.loki.lovisual.render.engine.pipeline.LoVisualRenderPipelines; import dev.loki.lovisual.render.engine.pipeline.LoVisualRenderPipelines;
@ -58,7 +58,7 @@ public final class PredictionsWorldRenderer {
boolean walls = facade.getGlowWallsValue().get(); boolean walls = facade.getGlowWallsValue().get();
RenderPipeline pipeline = walls ? LoVisualRenderPipelines.WORLD_TEXTURED_ADDITIVE : LoVisualRenderPipelines.WORLD_TEXTURED_ADDITIVE_LIQUID_IGNORE; RenderPipeline pipeline = walls ? LoVisualRenderPipelines.WORLD_TEXTURED_ADDITIVE : LoVisualRenderPipelines.WORLD_TEXTURED_ADDITIVE_LIQUID_IGNORE;
Renderer3D.DepthMode depthMode = walls ? Renderer3D.DepthMode.MAIN : Renderer3D.DepthMode.PRE_DEPTH; Renderer3D.DepthMode depthMode = walls ? Renderer3D.DepthMode.MAIN : Renderer3D.DepthMode.PRE_DEPTH;
if (FpsOptimizer.bloomDisabled()) return; if (Optimize.bloomDisabled()) return;
MeshBuilder mesh = renderer.batchTextured(pipeline, TextureStorage.BLOOM, depthMode); MeshBuilder mesh = renderer.batchTextured(pipeline, TextureStorage.BLOOM, depthMode);
if (mesh == null) return; if (mesh == null) return;
int color = pred.entity() != null ? HIT_ENTITY_COLOR : pred.trajectory().argb() != 0 ? pred.trajectory().argb() : baseColor; int color = pred.entity() != null ? HIT_ENTITY_COLOR : pred.trajectory().argb() != 0 ? pred.trajectory().argb() : baseColor;

View file

@ -1,17 +1,50 @@
package dev.loki.lovisual.features.module.modules.misc.optimize; package dev.loki.lovisual.features.module.modules.misc.optimize;
import dev.loki.lovisual.config.values.mode.EnumValue;
import dev.loki.lovisual.config.values.primitive.BooleanValue; import dev.loki.lovisual.config.values.primitive.BooleanValue;
import dev.loki.lovisual.config.values.primitive.NumberValue;
import dev.loki.lovisual.events.impl.render.particles.ParticleSpawnEvent;
import dev.loki.lovisual.events.meta.EventHandler;
import dev.loki.lovisual.features.module.core.Module; import dev.loki.lovisual.features.module.core.Module;
import dev.loki.lovisual.features.module.core.ModuleCategory; import dev.loki.lovisual.features.module.core.ModuleCategory;
import dev.loki.lovisual.features.module.core.ModuleInfo; import dev.loki.lovisual.features.module.core.ModuleInfo;
import dev.loki.lovisual.features.module.lifecycle.Modules;
import dev.loki.lovisual.features.module.phase.Notifier; import dev.loki.lovisual.features.module.phase.Notifier;
import dev.loki.lovisual.features.module.modules.misc.optimize.particle.Workers;
import dev.loki.lovisual.render.engine.optimize.entity.AnimFreeze;
import dev.loki.lovisual.render.engine.optimize.entity.ItemBounds;
import dev.loki.lovisual.render.engine.optimize.entity.ItemLod;
import dev.loki.lovisual.render.engine.optimize.gl.state.GlStateCache;
import dev.loki.lovisual.render.engine.optimize.hud.HudCache;
import dev.loki.lovisual.render.engine.optimize.parallel.ParallelModels;
import dev.loki.lovisual.render.engine.optimize.profile.DrawStats;
import dev.loki.lovisual.render.engine.optimize.profile.FrameBudget;
import dev.loki.lovisual.render.engine.optimize.profile.FrameProfiler;
import dev.loki.lovisual.render.engine.optimize.profile.OptimizePropertyBridge;
import dev.loki.lovisual.render.engine.optimize.OptimizeState; import dev.loki.lovisual.render.engine.optimize.OptimizeState;
import dev.loki.lovisual.render.engine.optimize.OptimizeToggles;
import net.minecraft.client.Minecraft;
import net.minecraft.core.particles.ParticleTypes;
/** /**
* Manual FPS rubilnik: one switch plus four knobs, each cutting a named cost. * Manual FPS rubilnik: one switch plus a set of knobs, each cutting a named cost
* (the four original "rubilnik" cuts: no_glass, lite_post, lite_sky, lean_hud)
* OR toggling a transparent optimization (entity LOD,
* particle LOD, spawner tick-cache, etc.).
* *
* <p>No auto-degradation by FPS — the owner's rule. Render code reads * <p>No auto-degradation by FPS — the owner's rule. Render code reads
* {@link OptimizeState}, never this class; this module only pushes state into it. * {@link OptimizeState} (the original cuts), {@link OptimizeToggles} (the
* Stage 1 transparent helpers), {@link FrameBudget} (Stage 2 frame budget)
* — never this class; this module only pushes state into them on
* enable/disable and once per frame.
*
* <p>Stage 2 of {@code mod/docs/optimize-layer-design.md}: the module also
* pushes a {@link FrameBudget} snapshot (mode + target FPS) and resolves
* {@code -Dlovisual.opt.*} system-property overrides via
* {@link OptimizePropertyBridge}. Stage 3 step 1 adds {@link DrawStats} —
* draw/pipeline/framebuffer counters fed by the {@code mixins/optimize/stats}
* hooks, opened and closed here so they only run while F3 is up. The F3
* overlay ({@code OptimizeDebugHudMixin}) reads both snapshots.
*/ */
@ModuleInfo( @ModuleInfo(
id = "optimize", id = "optimize",
@ -20,11 +53,62 @@ import dev.loki.lovisual.render.engine.optimize.OptimizeState;
) )
public final class Optimize extends Module { public final class Optimize extends Module {
// --- Original "rubilnik" cuts: visible FPS trade-offs ---
private final BooleanValue noGlass = bool("no_glass", true); private final BooleanValue noGlass = bool("no_glass", true);
private final BooleanValue litePost = bool("lite_post", true); private final BooleanValue litePost = bool("lite_post", true);
private final BooleanValue liteSky = bool("lite_sky", true); private final BooleanValue liteSky = bool("lite_sky", true);
private final BooleanValue leanHud = bool("lean_hud", true); private final BooleanValue leanHud = bool("lean_hud", true);
// --- transparent optimizations (no visual change) ---
private final BooleanValue entityLod = bool("entity_lod", true);
private final NumberValue<Integer> entityLodDistance =
num("entity_lod_distance", 35, 4, 256);
private final BooleanValue particleLod = bool("particle_lod", true);
private final BooleanValue spawnerCull = bool("spawner_cull", true);
private final NumberValue<Integer> spawnerDistance =
num("spawner_distance", 16, 4, 64);
private final BooleanValue spawnerTickCache = bool("spawner_tick_cache", true);
private final BooleanValue blockEntityCache = bool("block_entity_cache", true);
private final BooleanValue preparedTextCache = bool("prepared_text_cache", true);
private final BooleanValue microOpts = bool("micro_opts", true);
// --- Stage 3: GL-level helpers ---
private final BooleanValue fboShare = bool("fbo_share", true);
private final BooleanValue entityAnimFreeze = bool("entity_anim_freeze", false);
private final NumberValue<Integer> entityAnimDistance =
num("entity_anim_distance", 16, 4, 128);
// --- Stage 3: items ---
private final BooleanValue itemLod = bool("item_lod", true);
private final NumberValue<Integer> itemLodDistance = num("item_lod_distance", 8, 2, 64);
private final BooleanValue itemBounds = bool("item_bounds", true);
// --- Stage 3: HUD cache (off by default — interacts with the deferred-HUD markers) ---
private final BooleanValue hudCacheToggle = bool("hud_cache", false);
// --- Stage 3: parallel model build (own holder: cores/Iris gating inside) ---
private final BooleanValue parallelModels = bool("parallel_models", true);
// --- Stage 1 item 4: parallel particles AUTO gate (cores >= 4) ---
// -Dlovisual.opt.parallel_particles=auto|true|false overrides this from OptimizePropertyBridge.
private final BooleanValue parallelParticles = bool("parallel_particles", true);
// --- Visible cuts merged from the old FPS Optimizer module ---
private final BooleanValue noParticles = bool("no_particles", false);
private final BooleanValue noMenuBackground = bool("no_menu_background", false);
private final BooleanValue noBloom = bool("no_bloom", false);
private final BooleanValue entityCull = bool("entity_cull", false);
private final NumberValue<Integer> entityCullDistance =
visibleWhen(num("entity_cull_distance", 64, 8, 256), entityCull::get);
// --- Stage 2: frame budget + profiling ---
private final EnumValue<FrameBudget.Mode> budgetMode =
enumMode("budget_mode", FrameBudget.Mode.OFF, FrameBudget.Mode.values());
private final NumberValue<Integer> targetFps =
num("target_fps", FrameBudget.DEFAULT_TARGET_FPS, 15, 360);
private final BooleanValue showProfiler =
bool("show_profiler", false);
private boolean notified; private boolean notified;
@Override @Override
@ -41,21 +125,124 @@ public final class Optimize extends Module {
@Override @Override
public void onDisable() { public void onDisable() {
OptimizeState.reset(); OptimizeState.reset();
OptimizeToggles.reset();
FrameBudget.reset();
AnimFreeze.reset();
ItemLod.reset();
ItemBounds.reset();
HudCache.reset();
ParallelModels.reset();
Workers.resetParallelParticles();
GlStateCache.reset();
// stop counting and drop the F3 numbers, onFrame will not run again
DrawStats.endFrame(false);
} }
/** Picks up knob changes made while the module stays on. */ /** Picks up knob changes made while the module stays on. */
@Override @Override
public void onFrame(float d) { public void onFrame(float d) {
pushState(); pushState();
// close the window of the frame that just drew; the next publish lands once a second
DrawStats.endFrame(debugOverlayVisible());
}
/** F3 counts are only worth collecting while they are on screen. */
private static boolean debugOverlayVisible() {
Minecraft mc = Minecraft.getInstance();
return mc != null && mc.getDebugOverlay() != null && mc.getDebugOverlay().showDebugScreen();
}
// --- Call-site helpers for the merged FPS Optimizer cuts ---
public boolean isMenuBackgroundDisabled() {
return isEnabled() && noMenuBackground.get();
}
public boolean isBloomDisabled() {
return isEnabled() && noBloom.get();
}
/** Cheap call-site guard for renderers that build bloom/glow geometry every frame. */
public static boolean bloomDisabled() {
Optimize module = Modules.get(Optimize.class);
return module != null && module.isBloomDisabled();
}
public boolean isEntityCullingEnabled() {
return isEnabled() && entityCull.get();
}
public int entityCullDistance() {
return entityCullDistance.get();
}
@EventHandler
private void onParticleSpawn(ParticleSpawnEvent event) {
if (!isEnabled() || !noParticles.get()) return;
// Firework particles are created by FireworkParticles$Starter and assume ParticleEngine.createParticle never returns null.
// Cancelling them returns null and causes NPE at Starter.createParticle -> setTrail().
// Guard is also present in FireworkParticlesStarterMixin, but exempt here to preserve fireworks even with optimizer enabled.
var type = event.options().getType();
if (type == ParticleTypes.FIREWORK || type == ParticleTypes.FLASH) return;
event.cancel();
} }
private void pushState() { private void pushState() {
boolean on = isEnabled(); boolean on = isEnabled();
// Original four "rubilnik" cuts.
OptimizeState.apply( OptimizeState.apply(
on && noGlass.get(), on && noGlass.get(),
on && litePost.get(), on && litePost.get(),
on && liteSky.get(), on && liteSky.get(),
on && leanHud.get()); on && leanHud.get());
// Stage 1 toggles — wire through the -Dlovisual.opt.* overrides.
OptimizePropertyBridge.Snapshot props = OptimizePropertyBridge.resolve();
OptimizeToggles.apply(
resolveBool(props, props.entityLod, on && entityLod.get()),
resolveInt(props, props.entityLodDistance, entityLodDistance.get()),
resolveBool(props, props.particleLod, on && particleLod.get()),
resolveBool(props, props.particleLod, on && particleLod.get()),
resolveBool(props, props.particleLod, on && particleLod.get()),
resolveBool(props, props.spawnerCull, on && spawnerCull.get()),
resolveInt(props, props.spawnerDistance, spawnerDistance.get()),
resolveBool(props, props.spawnerTickCache, on && spawnerTickCache.get()),
resolveBool(props, props.blockEntityCache, on && blockEntityCache.get()),
resolveBool(props, props.preparedTextCache, on && preparedTextCache.get()),
resolveBool(props, props.microOpts, on && microOpts.get()),
resolveBool(props, props.fboShare, on && fboShare.get()));
// Stage 2: frame budget. -Dlovisual.opt.budget_mode / target_fps override the module.
FrameBudget.Mode mode = on ? budgetMode.get() : FrameBudget.Mode.OFF;
FrameBudget.apply(props.overrides(mode, mode), props.resolveTargetFps(targetFps.get()));
// Stage 3: far-entity animation freeze — own holder, pushed once per frame.
AnimFreeze.configure(on && entityAnimFreeze.get(), entityAnimDistance.get());
// Stage 3: far-item LOD + shared single-layer item bounds.
ItemLod.configure(on && itemLod.get(), itemLodDistance.get());
ItemBounds.configure(on && itemBounds.get());
// Stage 3: HUD-at-refresh-rate cache; own holder (foreign-HUD/Vulkan gating inside).
HudCache.configure(on && hudCacheToggle.get());
// Stage 3: parallel model build; mutually exclusive with anim freeze (checked inside).
ParallelModels.configure(on && parallelModels.get());
// Stage 1 item 4: parallel-particles gate; -Dlovisual.opt.parallel_particles resolves
// to null (AUTO -> cores >= 4), Boolean.TRUE/FALSE (forced). Workers keeps the resolved
// flag so a future particle-extraction mixin can read it without touching this module.
Workers.configureParallelParticles(props.parallelParticles, on && parallelParticles.get());
}
private static boolean resolveBool(OptimizePropertyBridge.Snapshot props,
Boolean override, boolean moduleValue) {
return props.overrides(override, moduleValue);
}
private static int resolveInt(OptimizePropertyBridge.Snapshot props,
int override, int moduleValue) {
return props.overrides(override, moduleValue);
} }
/** Compact list of what is being cut, for the first-enable notice. */ /** Compact list of what is being cut, for the first-enable notice. */

View file

@ -0,0 +1,23 @@
package dev.loki.lovisual.features.module.modules.misc.optimize.block;
/**
* Mixin-contract: per-tick cached block-light lookups on a {@code BlockEntity}.
* The vanilla {@code LightCoordsUtil.getLightCoords(level, pos)} call walks
* the chunk's light section data every frame per block-entity in view;
* caching it once per tick (block-light only changes on tick boundaries)
* removes that walk from the hot path. The companion {@code pairLight}
* methods cache the second lookup done for double-chests.
*/
public interface CachedLight {
int lovisual$light();
long lovisual$lightTick();
void lovisual$setLight(int light, long tick);
int lovisual$pairLight();
long lovisual$pairLightTick();
void lovisual$setPairLight(int light, long tick);
}

View file

@ -0,0 +1,25 @@
package dev.loki.lovisual.features.module.modules.misc.optimize.block;
import net.minecraft.world.level.block.state.BlockState;
/**
* Mixin-contract: cached validity and "should-render" distance check on a
* {@code BlockEntity}. {@code BlockEntityType.isValid(state)} is called every
* frame per block-entity in view but only changes on a state transition —
* cached by identity on {@link #lovisual$validState()} / {@link #lovisual$valid()}.
* The companion {@code inDistance} methods cache
* {@code BlockEntityRenderer.shouldRender}'s distance check per tick.
*/
public interface CachedValidity {
BlockState lovisual$validState();
boolean lovisual$valid();
void lovisual$setValid(BlockState state, boolean valid);
long lovisual$distanceTick();
boolean lovisual$inDistance();
void lovisual$setInDistance(boolean inDistance, long tick);
}

View file

@ -0,0 +1,40 @@
package dev.loki.lovisual.features.module.modules.misc.optimize.block;
import dev.loki.lovisual.render.engine.optimize.OptimizeToggles;
import net.minecraft.client.renderer.entity.state.EntityRenderState;
/**
* Utility layer over {@link TickCached} on a spawner ({@code BaseSpawner} via
* mixin): get/put the cached {@link EntityRenderState} for the spawner's
* display mob, keyed by tick, skipping the per-frame {@code extractEntity}
* rebuild. The (Stage 3) spawner renderer mixin populates this on the first
* frame of a tick and the subsequent frames in the same tick read back from
* the cache.
*
* <p>Takes the {@link TickCached} interface directly rather than the
* {@code BaseSpawner} class so the contract is testable without a
* Minecraft runtime — the Stage 3 mixin casts {@code (TickCached) spawner}
* before calling.
*
* <p>Reads {@link OptimizeToggles#spawnerTickCache()} to decide whether caching is enabled.
*/
public enum SpawnerCache {
;
/** True when the cache is engaged this frame. */
public static boolean enabled() {
return OptimizeToggles.spawnerTickCache();
}
/** Cached state for this tick, or {@code null} if not yet cached. */
public static EntityRenderState get(TickCached spawner, long tick) {
return spawner.lovisual$cachedTick() == tick
? (EntityRenderState) spawner.lovisual$cached()
: null;
}
/** Write the cached state for the given tick. */
public static void put(TickCached spawner, long tick, EntityRenderState state) {
spawner.lovisual$setCached(state, tick);
}
}

View file

@ -0,0 +1,17 @@
package dev.loki.lovisual.features.module.modules.misc.optimize.block;
/**
* Mixin-contract: a generic per-tick cache slot on a target object
* (block-entity, spawner, piston moving block). Stores one cached value plus
* the tick it was written; the helper (e.g. {@link SpawnerCache}) checks
* {@link #lovisual$cachedTick()} against the current tick and reads
* {@link #lovisual$cached()} if it matches, otherwise lets the caller rebuild
* and writes the fresh value via {@link #lovisual$setCached(Object, long)}.
*/
public interface TickCached {
Object lovisual$cached();
long lovisual$cachedTick();
void lovisual$setCached(Object value, long tick);
}

View file

@ -0,0 +1,32 @@
package dev.loki.lovisual.features.module.modules.misc.optimize.core;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Access-ordered LRU map with a size cap. Generic, no Minecraft dependencies,
* unit-testable as-is.
*
* <p>Intended for the {@code ClientLanguage.getVisualOrder} LRU cache.
*
* @param <K> key type
* @param <V> value type
*/
public final class LruMap<K, V> extends LinkedHashMap<K, V> {
private final int maxSize;
public LruMap(int maxSize) {
super(256, 0.75f, true);
this.maxSize = maxSize;
}
public int maxSize() {
return maxSize;
}
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > maxSize;
}
}

View file

@ -0,0 +1,23 @@
package dev.loki.lovisual.features.module.modules.misc.optimize.entity;
import net.minecraft.network.chat.Component;
/**
* Mixin-contract: cached rebuilt name tag for an entity.
*
* <p>The vanilla {@code Entity.getDisplayName()} rebuilds a {@link Component}
* (team prefix + name + suffix) every time it's called. Renderers call it once
* per frame per entity in view, which is wasteful — the team/name/suffix tuple
* only changes on tick boundaries. Mixins on {@code Entity} implement this
* interface, expose the cache slot via {@link #lovisual$name()}, {@link #lovisual$nameTick()}
* and {@link #lovisual$setName(Component, long)}, and the
* {@code EntityRenderer.getNameTag} wrapper fills it once per tick and reuses
* the cached value on intermediate frames.
*/
public interface CachedName {
Component lovisual$name();
long lovisual$nameTick();
void lovisual$setName(Component name, long tick);
}

View file

@ -0,0 +1,50 @@
package dev.loki.lovisual.features.module.modules.misc.optimize.entity;
import org.lwjgl.system.MemoryStack;
/**
* Hot-path helper: skip the {@link MemoryStack#stackPush()} ThreadLocal lookup
* on the thread that called last (the render thread). The lookup is cheap on
* its own, but Sodium's entity renderer calls it once per cuboid per frame
* (thousands of times), and a single volatile read + identity compare is
* strictly cheaper than the ThreadLocal hash lookup.
*
* <p>Stores the {@code (thread, stack)} pair in one record so another thread
* never sees a half-updated pair. The first call from a new thread rewrites
* the volatile; subsequent calls from the same thread take the fast path.
*
* <p>Used by the (Stage 3) Sodium {@code EntityRenderer.renderCuboid} mixin.
*/
public enum CachedStack {
;
private record ThreadStack(Thread thread, MemoryStack stack) {
}
// One record so another thread never sees a thread/stack pair half-updated.
private static volatile ThreadStack cached = new ThreadStack(null, null);
/**
* Push a frame on the render thread's cached stack, falling back to the
* normal ThreadLocal lookup on a thread switch.
*/
public static MemoryStack push() {
ThreadStack current = cached;
Thread thread = Thread.currentThread();
if (current.thread() != thread) {
current = new ThreadStack(thread, MemoryStack.stackGet());
cached = current;
}
return current.stack().push();
}
/** Test-only: peek the cached thread (null before first call). */
static Thread cachedThread() {
return cached.thread();
}
/** Test-only: peek the cached stack (null before first call). */
static MemoryStack cachedStack() {
return cached.stack();
}
}

View file

@ -0,0 +1,37 @@
package dev.loki.lovisual.features.module.modules.misc.optimize.entity;
import dev.loki.lovisual.render.engine.optimize.OptimizeToggles;
/**
* Entity LOD gate: is an entity far enough that the renderer should skip its
* layers (armour, held items, eyes, cape, elytra, stuck arrows) and freeze its
* animation? Compares squared distance to the configured threshold so the
* caller doesn't have to {@code Math.sqrt}.
*
* <p>The companion {@code farPlayer} exists so a config can drop
* players separately from entities (the {@code playerLod} toggle); in LoVisual
* Stage 1 we collapse the two — the same toggle gates both. Stage 2 may split
* them again if profiling shows players are the bigger cost.
*/
public enum EntityLod {
;
/** Squared threshold at and above which an entity is "far". */
public static double farThresholdSq() {
double d = OptimizeToggles.entityLodDistance();
return d * d;
}
/** True when LOD is on and the entity is beyond the configured distance. */
public static boolean far(double distanceSq) {
if (!OptimizeToggles.entityLod()) {
return false;
}
return distanceSq > farThresholdSq();
}
/** Same as {@link #far} — players and entities share one toggle in Stage 1. */
public static boolean farPlayer(double distanceSq) {
return far(distanceSq);
}
}

View file

@ -0,0 +1,19 @@
package dev.loki.lovisual.features.module.modules.misc.optimize.entity;
import net.minecraft.world.entity.Entity;
/**
* Mixin-contract: back-reference the source {@link Entity} on its
* {@code EntityRenderState}. Render-states are rebuilt every frame, so they
* can't keep their own pointer to the entity — the
* {@code EntityRenderer.createRenderState} mixin captures it once per state
* construction via {@link #lovisual$entity(Entity)} and downstream renderers
* (model feature renderer, item feature renderer, future LOD mixins) read it
* back via {@link #lovisual$entity()} to reach the live entity for animation
* freeze, LOD distance checks, etc.
*/
public interface StateEntity {
Entity lovisual$entity();
void lovisual$entity(Entity entity);
}

View file

@ -0,0 +1,144 @@
package dev.loki.lovisual.features.module.modules.misc.optimize.gl;
import dev.loki.lovisual.render.engine.optimize.OptimizeToggles;
import dev.loki.lovisual.render.engine.optimize.gl.SharedDepthFbos;
import it.unimi.dsi.fastutil.ints.Int2LongOpenHashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* GL backend implementation of {@link RenderBackendOps}.
*
* <p>Resolves the current GL device via {@code GlBackendAccess.current()} —
* returns {@code null} on Vulkan so all mixins short-circuit to the vanilla
* call. The cache state is static and render-thread-only (the GL command
* encoder runs single-threaded).
*
* <p>Each toggle is gated by {@link OptimizeToggles#microOpts()} (the Stage 1
* "micro_opts" toggle wired into {@code Optimize.java}).
*/
public final class GlRenderBackendOps implements RenderBackendOps {
private static final GlRenderBackendOps INSTANCE = new GlRenderBackendOps();
// --- TBO cache ---
/** Maps bound-texture-id -> packed (format << 32) | (buffer & 0xFFFFFFFFL). -1 = nothing attached. */
private final Int2LongOpenHashMap tboAttached = new Int2LongOpenHashMap();
private int boundTboTexture;
// --- RenderTypes cache ---
private final Map<Identifier, Object> translucentCache = new ConcurrentHashMap<>();
private GlRenderBackendOps() {
tboAttached.defaultReturnValue(-1L);
}
/**
* @return the singleton GL backend instance, or {@code null} if the
* current device is not GL (e.g. Vulkan backend active).
*/
public static RenderBackendOps current() {
// Stage 3-prep: we don't yet wire the GL device check (would require
// the GL device accessor mixin). Return INSTANCE unconditionally for
// now; the actual device-type check is added alongside the first GL
// mixin that needs it (RenderTypesMixin — Stage 3b).
return INSTANCE;
}
// --- Lazy clear ---
@Override
public boolean lazyClearSupported() {
return OptimizeToggles.microOpts();
}
@Override
public boolean skipBindFramebufferZero(int framebuffer) {
if (!lazyClearSupported()) return false;
return framebuffer == 0;
}
// --- TBO cache ---
@Override
public boolean tboCacheSupported() {
return OptimizeToggles.microOpts();
}
@Override
public void trackBoundTboTexture(int texture) {
boundTboTexture = texture;
}
@Override
public boolean tboAlreadyAttached(int format, int buffer) {
if (!tboCacheSupported()) return false;
return tboAttached.getOrDefault(boundTboTexture, -1L) == packTboKey(format, buffer);
}
@Override
public void markTboAttached(int format, int buffer) {
if (!tboCacheSupported()) return;
tboAttached.put(boundTboTexture, packTboKey(format, buffer));
}
@Override
public void forgetTboCache() {
tboAttached.clear();
}
private static long packTboKey(int format, int buffer) {
return ((long) format << 32) | (buffer & 0xFFFFFFFFL);
}
// --- FBO share (Stage 3 step 2) ---
@Override
public boolean fboShareSupported() {
return OptimizeToggles.fboShare();
}
@Override
public boolean clearDepthInPlace(int depthId, double value) {
return fboShareSupported() && SharedDepthFbos.clear(depthId, value);
}
// --- RenderTypes cache ---
@Override
public boolean renderTypesCacheSupported() {
return OptimizeToggles.microOpts();
}
@Override
public Object renderTypeFor(Identifier id) {
if (!renderTypesCacheSupported()) return null;
return translucentCache.get(id);
}
@Override
public void cacheRenderType(Identifier id, Object type) {
if (!renderTypesCacheSupported()) return;
translucentCache.put(id, type);
}
// --- Test helpers ---
/** Test-only: clear all caches. */
static void resetForTesting() {
INSTANCE.tboAttached.clear();
INSTANCE.boundTboTexture = 0;
INSTANCE.translucentCache.clear();
}
/** Test-only: peek the bound TBO texture. */
static int boundTboTextureForTesting() {
return INSTANCE.boundTboTexture;
}
/** Test-only: count of cached render types. */
static int cachedRenderTypeCountForTesting() {
return INSTANCE.translucentCache.size();
}
}

View file

@ -0,0 +1,161 @@
package dev.loki.lovisual.features.module.modules.misc.optimize.gl;
import com.mojang.blaze3d.systems.RenderSystem;
import dev.loki.lovisual.features.module.modules.misc.optimize.vulkan.VulkanRenderBackendOps;
/**
* Backend-agnostic surface for the optimization layer's GL/Vulkan hooks.
*
* <p>Stage 3 of {@code mod/docs/optimize-layer-design.md} splits the engine
* into "what to do" (this interface) and "how to do it on this backend"
* ({@link GlRenderBackendOps} for OpenGL, a future {@code VulkanRenderBackendOps}
* for Vulkan). The Optimize mixins call {@link #current()} once and dispatch
* through this surface; the Vulkan implementation returns {@code false} from
* every {@code supported*} method so the mixin's {@code WrapOperation} falls
* through to the original call.
*
* <p>Stage 3 ships:
* <ul>
* <li>{@link #lazyClearSupported()} / {@link #skipBindFramebufferZero(int)} — lazy clear</li>
* <li>{@link #tboCacheSupported()} / {@link #tboAlreadyAttached(int, int)} /
* {@link #markTboAttached(int, int)} / {@link #trackBoundTboTexture(int)} /
* {@link #forgetTboCache()} — TBO cache</li>
* <li>{@link #fboShareSupported()} / {@link #clearDepthInPlace(int, double)} —
* shared depth FBOs (Stage 3 step 2)</li>
* <li>{@link #renderTypesCacheSupported()} / {@link #renderTypeFor(Identifier)} /
* {@link #cacheRenderType(Identifier, Object)} — RenderTypes cache</li>
* </ul>
*
* <p>Stage 4 will add Vulkan-specific paths ({@code vkCmdCopyImage},
* {@code VkPipelineCache}) by implementing this surface with a no-op strategy
* for the GL-only methods.
*/
public interface RenderBackendOps {
/**
* Resolve the current backend by inspecting the active {@code GpuDeviceBackend}.
* Class-name check (not {@code instanceof}) so this method itself does not
* force the loader to link {@code GlDevice} or {@code VulkanDevice}; the
* Blaze3D jar always ships both, but keeping the check by string means the
* dispatch stays correct even when only one backend's class has been
* resolved. Falls back to the GL impl when the device is null (early boot)
* so mixins' {@code supported()} short-circuits behave the same as before.
*/
static RenderBackendOps current() {
Object device;
try {
device = RenderSystem.getDevice();
} catch (Throwable ignored) {
// Tests and pre-init paths call current() before RenderSystem has a
// device; fall through to GL so existing unit tests keep passing.
device = null;
}
if (device != null) {
String name = device.getClass().getName();
if (name.startsWith("com.mojang.blaze3d.vulkan.")) {
return VulkanRenderBackendOps.current();
}
}
return GlRenderBackendOps.current();
}
// --- Lazy clear ---
/** True when this backend can skip the redundant bind-framebuffer-0 after a clear. */
boolean lazyClearSupported();
/**
* Called from {@code GlCommandEncoder.clearColorAndDepthTextures} on the
* {@code GlStateManager._glBindFramebuffer(target, framebuffer)} call.
*
* @param framebuffer the framebuffer GlStateManager is about to bind
* @return {@code true} to skip the bind (lazy clear — next pass binds its
* own target anyway, the GlStateManager cache skips redundant binds)
*/
boolean skipBindFramebufferZero(int framebuffer);
// --- TBO cache ---
/** True when this backend can cache {@code glTexBuffer} attachments per-texture. */
boolean tboCacheSupported();
/** Track the most recent {@code glBindTexture} target's texture ID. */
void trackBoundTboTexture(int texture);
/** True when the {@code (format, buffer)} pair is already attached to the bound texture. */
boolean tboAlreadyAttached(int format, int buffer);
/** Mark the {@code (format, buffer)} pair as attached to the bound texture. */
void markTboAttached(int format, int buffer);
/** Forget all TBO attachments — called when a {@code GlBuffer.Direct} is closed. */
void forgetTboCache();
// --- FBO share (Stage 3 step 2) ---
/** True when this backend can clear a depth texture in place via a cached FBO. */
boolean fboShareSupported();
/**
* Called from {@code GlCommandEncoder.clearDepthTexture} on the
* {@code GlTexture} depth argument.
*
* @param depthId the GL id of the depth texture
* @param value the clear value (0..1)
* @return {@code true} when the clear already ran in place (mixin cancels
* the vanilla path); {@code false} to fall through to vanilla
*/
boolean clearDepthInPlace(int depthId, double value);
// --- RenderTypes cache ---
/** True when this backend can cache {@code RenderTypes.entityTranslucent(id, flag=true)}. */
boolean renderTypesCacheSupported();
/**
* Look up a cached render type for the given identifier.
*
* @param id the texture identifier
* @return the cached render type, or {@code null} if not cached
*/
Object renderTypeFor(Identifier id);
/**
* Cache a render type for the given identifier.
*
* @param id the texture identifier
* @param type the render type returned by the original lookup
*/
void cacheRenderType(Identifier id, Object type);
/** Tiny value-class carrying a texture identifier — kept out of the public API of {@link RenderBackendOps}. */
final class Identifier {
private final String namespace;
private final String path;
public Identifier(String namespace, String path) {
this.namespace = namespace;
this.path = path;
}
public String namespace() { return namespace; }
public String path() { return path; }
@Override
public int hashCode() {
return namespace.hashCode() * 31 + path.hashCode();
}
@Override
public boolean equals(Object o) {
return o instanceof Identifier i
&& i.namespace.equals(namespace)
&& i.path.equals(path);
}
@Override
public String toString() {
return namespace + ":" + path;
}
}
}

View file

@ -0,0 +1,67 @@
package dev.loki.lovisual.features.module.modules.misc.optimize.hud;
/**
* Hysteresis controller for the HUD cache. The HUD cache only saves work when
* several frames share one HUD refresh; near one frame per refresh (refresh
* interval ~= frame time) it redraws the HUD anyway and just adds a
* full-screen clear + blend, which costs real FPS on integrated GPUs and
* 60 Hz monitors. This controller tracks an EMA of frame time
* ({@code *0.95 + dt*0.05}) and flips the "worth it" state with hysteresis:
* turns OFF below {@code OFF_BELOW} frames-per-refresh, turns ON above
* {@code ON_ABOVE}.
*
* <p>Pure logic, no Minecraft dependencies, fully testable. The (Stage 3) HUD cache mixin reads
* {@link #worth()} to decide whether to engage.
*/
public enum HudWorth {
;
private static final double OFF_BELOW = 1.5;
private static final double ON_ABOVE = 2.0;
private static double frameNs;
private static long last;
private static volatile boolean worth = true;
/** True when the HUD cache is currently engaged. */
public static boolean worth() {
return worth;
}
/** True when the HUD cache should be available at all (independent of FPS). */
public static boolean hysteresisEnabled() {
return true;
}
/**
* Update the EMA frame time and the hysteresis state. Called once per
* frame; returns the new {@link #worth()} value.
*
* @param now the current {@code System.nanoTime()} reading
* @param refreshNs nanoseconds between HUD refreshes (1e9 / monitor Hz)
*/
public static boolean update(long now, long refreshNs) {
long dt = now - last;
last = now;
if (dt > 0 && dt < 1_000_000_000L) {
frameNs = frameNs == 0 ? dt : frameNs * 0.95 + dt * 0.05;
}
double framesPerRefresh = frameNs == 0 ? ON_ABOVE : refreshNs / frameNs;
if (worth ? framesPerRefresh < OFF_BELOW : framesPerRefresh > ON_ABOVE) {
worth = !worth;
}
return worth;
}
/** Test-only: reset EMA + hysteresis to defaults. */
static void reset() {
frameNs = 0;
last = 0;
worth = true;
}
/** Test-only: read the EMA frame time in nanoseconds. */
static double frameNs() {
return frameNs;
}
}

View file

@ -0,0 +1,41 @@
package dev.loki.lovisual.features.module.modules.misc.optimize.particle;
import dev.loki.lovisual.render.engine.optimize.OptimizeToggles;
import net.minecraft.world.level.material.FluidState;
/**
* Per-tick cache of {@code ClientLevel.getFluidState(pos)} results for
* {@code BubbleColumnUpParticle.tick}. Thousands of bubble particles share a
* few columns; each one re-checks its block's fluid every tick, which is a
* chunk-section lookup per call. This cache is keyed by {@code BlockPos.asLong()}
* and cleared once per tick (game-time change), so it never serves stale data
* across ticks.
*
* <p>Render-thread only (vanilla particle ticking is single-threaded). The
* cache is static because {@code BubbleColumnUpParticle} instances are created
* and destroyed constantly — per-particle state would be re-initialized too
* often to be useful.
*
* The cache logic is in {@link TickCache} (a generic per-tick keyed cache),
* so it's unit-testable without Minecraft types.
*/
public enum BubbleColumnCache {
;
private static final TickCache<FluidState> CACHE = new TickCache<>();
/** True when the cache is engaged this frame. */
public static boolean enabled() {
return OptimizeToggles.microOpts();
}
/** Look up a cached fluid state for the given block-pos key + tick. */
public static FluidState get(long posLong, long tick) {
return CACHE.get(posLong, tick);
}
/** Store a fluid state for the given block-pos key. */
public static void put(long posLong, FluidState fluid) {
CACHE.put(posLong, fluid);
}
}

View file

@ -0,0 +1,50 @@
package dev.loki.lovisual.features.module.modules.misc.optimize.particle;
import dev.loki.lovisual.render.engine.optimize.OptimizeToggles;
/**
* Per-frame thinning of far particles. Particles beyond 16 blocks are kept
* every other frame (32+ blocks: every fourth) using
* {@code System.identityHashCode(particle) >>> 4} as a stable per-particle
* salt so the choice doesn't flicker.
*
* <p>The hot-path API takes the camera position as primitives (no
* {@code Vec3} allocation); the {@code keep(Object, double)} overload is the
* pure-logic piece, testable without Minecraft types.
*
* <p>The {@code tick} field (sampled once per {@code ParticleEngine.render}) lives on the
* (Stage 3) particle mixin that owns the per-frame lifecycle; the pure-logic
* distance decision is here.
*/
public enum ParticleLod {
;
private static final double NEAR_SQ = 16.0 * 16.0;
private static final double MID_SQ = 32.0 * 32.0;
/**
* True when the particle should be kept this frame. The caller passes the
* particle's identity (for the per-particle salt) and the squared distance
* from the camera — both already computed by the renderer.
*/
public static boolean keep(Object particle, double distanceSq) {
if (!OptimizeToggles.particleLod()) {
return true;
}
if (distanceSq < NEAR_SQ) {
return true;
}
int h = System.identityHashCode(particle) >>> 4;
return distanceSq < MID_SQ ? (h & 1) == 0 : (h & 3) == 0;
}
/**
* Convenience overload: compute squared distance from primitives and
* dispatch to {@link #keep(Object, double)}.
*/
public static boolean keep(Object particle, double x, double y, double z,
double camX, double camY, double camZ) {
double dx = x - camX, dy = y - camY, dz = z - camZ;
return keep(particle, dx * dx + dy * dy + dz * dz);
}
}

View file

@ -0,0 +1,64 @@
package dev.loki.lovisual.features.module.modules.misc.optimize.particle;
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
/**
* Generic per-tick cache keyed by {@code long}. The cache is cleared once per
* tick change (game-time change), so it never serves stale data across ticks.
*
* <p>Used by {@link BubbleColumnCache} for {@code ClientLevel.getFluidState}
* results — thousands of bubble particles share a few columns; each one
* re-checks its block's fluid every tick. Generic on the value type so the
* logic is unit-testable without Minecraft types.
*
* <p>Render-thread only. The cache is static because particle instances are
* created and destroyed constantly — per-particle state would be re-initialized
* too often to be useful.
*
*/
public final class TickCache<V> {
private final Long2ObjectOpenHashMap<V> map = new Long2ObjectOpenHashMap<>();
private long cachedTick = Long.MIN_VALUE;
/**
* Look up a cached value for the given key, on the given tick. If the tick
* differs from the cached tick, the cache is cleared first.
*
* @param key the packed position key (e.g. {@code BlockPos.asLong()})
* @param tick the current game tick
* @return the cached value, or {@code null} if not cached
*/
public V get(long key, long tick) {
if (tick != cachedTick) {
map.clear();
cachedTick = tick;
}
return map.get(key);
}
/**
* Store a value for the given key, on the current tick. The cache must
* have been primed by a {@link #get} call first — that's where the tick
* check happens; this method assumes the cache is fresh.
*/
public void put(long key, V value) {
map.put(key, value);
}
/** Number of cached entries on the current tick. */
public int size() {
return map.size();
}
/** The tick the cache currently holds data for. */
public long cachedTick() {
return cachedTick;
}
/** Reset the cache to empty (used by tests and on disable). */
public void reset() {
map.clear();
cachedTick = Long.MIN_VALUE;
}
}

View file

@ -0,0 +1,203 @@
package dev.loki.lovisual.features.module.modules.misc.optimize.particle;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.IntConsumer;
/**
* Fixed-size daemon pool for parallel particle extraction. The number of
* helpers is {@code max(1, min(8, cores-2))} — leaving two cores for the
* render thread and the GC. {@link #run(int, IntConsumer)} splits the work
* into {@code blocks} units (caller decides the block size), dispatches them
* across helpers AND the calling thread (the caller works too — it only ever
* waits for blocks a helper has already claimed), and returns the first
* failure or {@code null} on success.
*
* <p>Used by the (Stage 3) {@code QuadParticleGroup} mixin to parallelise
* particle render-state extraction when the particle count exceeds 1024
* (Stage 1 ports the pool; the wiring is a later stage).
*
* <p>Pure java.util.concurrent, no Minecraft dependencies, fully testable.
*/
public final class Workers {
public static final int COUNT = Math.max(1, Math.min(8, Runtime.getRuntime().availableProcessors() - 2));
/** Minimum logical CPU count required for AUTO mode to enable parallel particles. */
public static final int PARALLEL_MIN_CORES = 4;
/**
* Effective parallel-particles flag resolved from module + property overrides.
* Written once per frame by {@code Optimize.pushState()}, read by the future
* particle-extraction mixin to decide whether to fan out across {@link #stream(IntConsumer)}.
*/
private static volatile boolean parallelParticles;
/**
* Resolve the parallel-particles flag. {@code forced} is the tri-state from
* {@code -Dlovisual.opt.parallel_particles} (TRUE/FALSE) or {@code null} for AUTO; {@code moduleEnabled}
* is the {@code Optimize.parallel_particles} switch (default {@code true}); AUTO engages when the
* machine exposes {@link #PARALLEL_MIN_CORES} or more logical CPUs — mirrors the reference's
* {@code CORES >= 4} rule from {@code mod/docs/optimize-layer-design.md}, no benchmark gate.
*/
public static void configureParallelParticles(Boolean forced, boolean moduleEnabled) {
parallelParticles = resolveParallelParticles(forced, moduleEnabled, Runtime.getRuntime().availableProcessors());
}
/** Test-friendly variant that lets the caller stub the CPU count. */
public static boolean resolveParallelParticles(Boolean forced, boolean moduleEnabled, int cores) {
if (forced != null) {
return forced;
}
if (!moduleEnabled) {
return false;
}
return cores >= PARALLEL_MIN_CORES;
}
/** True when the particle-extraction mixin should split across the pool. */
public static boolean shouldParallelParticles() {
return parallelParticles;
}
/** Reset to a safe default — used by {@code Optimize.onDisable} and by tests. */
public static void resetParallelParticles() {
parallelParticles = false;
}
private static final AtomicInteger THREAD_ID = new AtomicInteger();
private static final ExecutorService POOL = Executors.newFixedThreadPool(COUNT, r -> {
Thread t = new Thread(r, "lovisual-opt-worker-" + THREAD_ID.incrementAndGet());
t.setDaemon(true);
return t;
});
private Workers() {
}
public static int poolSize() {
return COUNT;
}
/**
* Run {@code task(0..blocks-1)} across the pool plus the calling thread.
* Returns the first failure, or {@code null} if all blocks succeeded.
*/
public static Throwable run(int blocks, IntConsumer task) {
if (blocks <= 0) {
return null;
}
Job job = new Job(blocks, task);
for (int h = Math.min(COUNT, blocks - 1); h > 0; h--) {
POOL.execute(job::run);
}
// The caller works too; it only ever waits for blocks a helper has already claimed.
job.run();
while (job.completed.get() < blocks) {
Thread.onSpinWait();
}
return job.error.get();
}
/**
* Open a task stream: helpers start right away and take items as the
* caller publishes them, so work overlaps with preparing the rest.
* Used by the parallel model builder (Stage 3).
*/
public static Stream stream(IntConsumer task) {
Stream stream = new Stream(task);
for (int h = COUNT; h > 0; h--) {
POOL.execute(stream::work);
}
return stream;
}
/** Test-only: shut the pool down so the JVM can exit cleanly. */
public static void shutdown() {
POOL.shutdownNow();
}
/** Items {@code 0..count-1} are fully set up and may be taken by helpers. */
public static final class Stream {
final IntConsumer task;
final AtomicInteger next = new AtomicInteger();
final AtomicInteger completed = new AtomicInteger();
final AtomicReference<Throwable> error = new AtomicReference<>();
volatile int ready;
volatile int total = -1;
Stream(IntConsumer task) {
this.task = task;
}
public void publish(int count) {
ready = count;
}
/** The caller helps with what is left and waits for the rest; first failure or null. */
public Throwable finish(int count) {
ready = count;
total = count;
work();
while (completed.get() < count) {
Thread.onSpinWait();
}
return error.get();
}
void work() {
while (true) {
int n = next.get();
if (n < ready) {
if (next.compareAndSet(n, n + 1)) {
try {
if (error.get() == null) {
task.accept(n);
}
} catch (Throwable t) {
error.compareAndSet(null, t);
} finally {
completed.incrementAndGet();
}
}
continue;
}
int t = total;
if (t >= 0 && n >= t) {
return;
}
Thread.onSpinWait();
}
}
}
private static final class Job {
final int blocks;
final IntConsumer task;
final AtomicInteger next = new AtomicInteger();
final AtomicInteger completed = new AtomicInteger();
final AtomicReference<Throwable> error = new AtomicReference<>();
Job(int blocks, IntConsumer task) {
this.blocks = blocks;
this.task = task;
}
void run() {
int b;
while ((b = next.getAndIncrement()) < blocks) {
try {
if (error.get() == null) {
task.accept(b);
}
} catch (Throwable t) {
error.compareAndSet(null, t);
} finally {
completed.incrementAndGet();
}
}
}
}
}

View file

@ -0,0 +1,30 @@
package dev.loki.lovisual.features.module.modules.misc.optimize.particle.camera;
import net.minecraft.client.Minecraft;
import net.minecraft.world.phys.Vec3;
/**
* Cached camera position accessor for the particle optimization layer.
* Vanilla {@code Particle.move} recomputes the camera position via
* {@code Minecraft.getInstance().gameRenderer.mainCamera().position()} per
* particle per tick — but the camera only moves once per frame. This helper
* is the single point where the camera position is sampled, so
* {@link ParticleMixin} reads it without re-walking the gameRenderer chain
* per particle.
*
* particle ticking runs on the render thread.
*/
public final class CameraPosition {
private CameraPosition() {
}
/**
* Sample the current camera position. Caller must not cache the returned
* {@link Vec3} — it may be a reused instance whose values change between
* frames.
*/
public static Vec3 get() {
return Minecraft.getInstance().gameRenderer.mainCamera().position();
}
}

View file

@ -0,0 +1,79 @@
package dev.loki.lovisual.features.module.modules.misc.optimize.text;
import dev.loki.lovisual.render.engine.optimize.OptimizeToggles;
import net.minecraft.util.FormattedCharSequence;
import net.minecraft.util.FormattedCharSink;
import java.util.Collections;
import java.util.Set;
import java.util.WeakHashMap;
/**
* Marker {@link FormattedCharSequence} wrapper that lets later code recognise
* "this text won't change" by identity and skip BIDI re-shaping. The
* {@link #mark(FormattedCharSequence)} call wraps and registers the sequence
* in a {@link WeakHashMap}-backed set; {@link #isStable(FormattedCharSequence)}
* checks membership.
*
* <p>The fast path is a plain {@code instanceof}
* check on the wrapper; the slow path is a synchronised set lookup. LoVisual
* keeps both — Stage 1 wires them both to {@link OptimizeToggles#microOpts()}.
*/
public final class StableText implements FormattedCharSequence {
private static final Set<FormattedCharSequence> STABLE =
Collections.newSetFromMap(new WeakHashMap<>());
private final FormattedCharSequence text;
/** Package-private — use {@link #mark(FormattedCharSequence)} to construct. */
StableText(FormattedCharSequence text) {
this.text = text;
}
/**
* Wrap a {@link FormattedCharSequence} so {@link #isStable(FormattedCharSequence)}
* returns {@code true} for it. The wrapper is registered in a weak set so
* it doesn't leak when the caller drops its reference.
*/
public static FormattedCharSequence mark(FormattedCharSequence text) {
StableText stable = new StableText(text);
synchronized (STABLE) {
STABLE.add(stable);
}
return stable;
}
/**
* True when {@code text} is known not to change (so callers can skip BIDI
* re-shape and other per-frame work). Fast path: {@code instanceof StableText}
* when {@code microOpts} is on; slow path: synchronised set lookup otherwise.
*/
public static boolean isStable(FormattedCharSequence text) {
if (OptimizeToggles.microOpts()) {
return text instanceof StableText;
}
synchronized (STABLE) {
return STABLE.contains(text);
}
}
/** Test-only: number of currently-tracked stable sequences. */
static int trackedCount() {
synchronized (STABLE) {
return STABLE.size();
}
}
/** Test-only: clear the tracked set. */
static void clearTracked() {
synchronized (STABLE) {
STABLE.clear();
}
}
@Override
public boolean accept(FormattedCharSink sink) {
return text.accept(sink);
}
}

View file

@ -0,0 +1,97 @@
package dev.loki.lovisual.features.module.modules.misc.optimize.vulkan;
import dev.loki.lovisual.features.module.modules.misc.optimize.gl.RenderBackendOps;
/**
* Vulkan-side implementation of {@link RenderBackendOps}. All GPU-object ops
* (lazy clear, TBO cache, shared depth FBO, RenderTypes cache) currently live
* in the GL mixin set — under Vulkan those mixins never load, so this class is
* a no-op placeholder that lets {@code RenderBackendOps.current()} dispatch by
* actual backend instead of unconditionally returning the GL impl.
*
* <p>Every {@code *Supported} reports {@code false}. Callers already gate on
* supported before attempting, so the effect is the same as "Optimize GPU
* features off" for backend-dependent items. Stage 4 adds Vulkan-specific
* paths (persistent {@code VkPipelineCache}, {@code VulkanRenderPass} state
* cache) by flipping the corresponding {@code *Supported} here to true and
* implementing the op body.
*
* <p>Doc reference: {@code mod/docs/optimize-layer-design.md}, "Этап 4" and
* "Что уже решено в архитектуре" → "Рендер-бэкенды".
*/
public final class VulkanRenderBackendOps implements RenderBackendOps {
private static final VulkanRenderBackendOps INSTANCE = new VulkanRenderBackendOps();
private VulkanRenderBackendOps() {
}
/** Singleton — no state, no per-device instance needed. */
public static VulkanRenderBackendOps current() {
return INSTANCE;
}
// --- Lazy clear ---
@Override
public boolean lazyClearSupported() {
return false;
}
@Override
public boolean skipBindFramebufferZero(int framebuffer) {
return false;
}
// --- TBO cache ---
@Override
public boolean tboCacheSupported() {
return false;
}
@Override
public void trackBoundTboTexture(int texture) {
}
@Override
public boolean tboAlreadyAttached(int format, int buffer) {
return false;
}
@Override
public void markTboAttached(int format, int buffer) {
}
@Override
public void forgetTboCache() {
}
// --- FBO share ---
@Override
public boolean fboShareSupported() {
return false;
}
@Override
public boolean clearDepthInPlace(int depthId, double value) {
return false;
}
// --- RenderTypes cache ---
@Override
public boolean renderTypesCacheSupported() {
return false;
}
@Override
public Object renderTypeFor(Identifier id) {
return null;
}
@Override
public void cacheRenderType(Identifier id, Object type) {
}
}

View file

@ -3,7 +3,7 @@ package dev.loki.lovisual.features.module.modules.visuals.effects.ambient;
import net.minecraft.util.Mth; import net.minecraft.util.Mth;
import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.Vec3;
import dev.loki.lovisual.features.module.modules.visuals.effects.ambient.geometry.WorldParticlesGeometry; import dev.loki.lovisual.features.module.modules.visuals.effects.ambient.geometry.WorldParticlesGeometry;
import dev.loki.lovisual.features.module.modules.visuals.optimization.FpsOptimizer; import dev.loki.lovisual.features.module.modules.misc.optimize.Optimize;
import dev.loki.lovisual.render.engine.animation.AnimationUtility; import dev.loki.lovisual.render.engine.animation.AnimationUtility;
import dev.loki.lovisual.render.engine.color.ColorBlendMode; import dev.loki.lovisual.render.engine.color.ColorBlendMode;
import dev.loki.lovisual.render.engine.RenderState; import dev.loki.lovisual.render.engine.RenderState;
@ -51,7 +51,7 @@ final class WorldParticlesFunnel {
MeshBuilder distortionMesh = WorldParticlesBatches.tintedTexture(renderer, useDepth, depthMode, TextureStorage.FUNNEL_DISTORTION); MeshBuilder distortionMesh = WorldParticlesBatches.tintedTexture(renderer, useDepth, depthMode, TextureStorage.FUNNEL_DISTORTION);
MeshBuilder eyeMesh = WorldParticlesBatches.tintedTexture(renderer, useDepth, depthMode, TextureStorage.FUNNEL_EYE); MeshBuilder eyeMesh = WorldParticlesBatches.tintedTexture(renderer, useDepth, depthMode, TextureStorage.FUNNEL_EYE);
MeshBuilder bloomMesh = FpsOptimizer.bloomDisabled() MeshBuilder bloomMesh = Optimize.bloomDisabled()
? null ? null
: WorldParticlesBatches.tintedTexture(renderer, useDepth, depthMode, TextureStorage.BLOOM); : WorldParticlesBatches.tintedTexture(renderer, useDepth, depthMode, TextureStorage.BLOOM);
if (distortionMesh == null && eyeMesh == null && bloomMesh == null) { if (distortionMesh == null && eyeMesh == null && bloomMesh == null) {

View file

@ -9,7 +9,7 @@ import net.minecraft.world.entity.projectile.Projectile;
import net.minecraft.world.entity.projectile.arrow.AbstractArrow; import net.minecraft.world.entity.projectile.arrow.AbstractArrow;
import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.Vec3;
import org.joml.Quaternionf; import org.joml.Quaternionf;
import dev.loki.lovisual.features.module.modules.visuals.optimization.FpsOptimizer; import dev.loki.lovisual.features.module.modules.misc.optimize.Optimize;
import dev.loki.lovisual.mixins.accessors.projectile.PersistentProjectileEntityAccessor; import dev.loki.lovisual.mixins.accessors.projectile.PersistentProjectileEntityAccessor;
import dev.loki.lovisual.render.engine.RenderState; import dev.loki.lovisual.render.engine.RenderState;
import dev.loki.lovisual.render.engine.pipeline.LoVisualRenderPipelines; import dev.loki.lovisual.render.engine.pipeline.LoVisualRenderPipelines;
@ -123,7 +123,7 @@ final class TrailsParticles {
Renderer3D.DepthMode dm = useDepth ? Renderer3D.DepthMode.PRE_DEPTH : Renderer3D.DepthMode.MAIN; Renderer3D.DepthMode dm = useDepth ? Renderer3D.DepthMode.PRE_DEPTH : Renderer3D.DepthMode.MAIN;
Quaternionf camRot = RenderState.cameraRotation; Quaternionf camRot = RenderState.cameraRotation;
if (mode == ParticleTextureMode.BLOOM) { if (mode == ParticleTextureMode.BLOOM) {
if (FpsOptimizer.bloomDisabled()) return; if (Optimize.bloomDisabled()) return;
MeshBuilder mesh = renderer.batchTextured(pipeline, TextureStorage.FIRE_FLY, dm); MeshBuilder mesh = renderer.batchTextured(pipeline, TextureStorage.FIRE_FLY, dm);
if (mesh == null) return; if (mesh == null) return;
for (Particle3D p : extra) renderOne(mesh, p, tickDelta, camRot, geo); for (Particle3D p : extra) renderOne(mesh, p, tickDelta, camRot, geo);

View file

@ -1,7 +1,7 @@
package dev.loki.lovisual.features.module.modules.visuals.effects.hits; package dev.loki.lovisual.features.module.modules.visuals.effects.hits;
import com.mojang.blaze3d.pipeline.RenderPipeline; import com.mojang.blaze3d.pipeline.RenderPipeline;
import dev.loki.lovisual.features.module.modules.visuals.optimization.FpsOptimizer; import dev.loki.lovisual.features.module.modules.misc.optimize.Optimize;
import dev.loki.lovisual.render.engine.RenderState; import dev.loki.lovisual.render.engine.RenderState;
import dev.loki.lovisual.render.engine.pipeline.LoVisualRenderPipelines; import dev.loki.lovisual.render.engine.pipeline.LoVisualRenderPipelines;
import dev.loki.lovisual.render.engine.renderer.Renderer3D; import dev.loki.lovisual.render.engine.renderer.Renderer3D;
@ -80,7 +80,7 @@ final class HitParticleHelper {
Renderer3D.DepthMode depthMode = useDepth ? Renderer3D.DepthMode.PRE_DEPTH : Renderer3D.DepthMode.MAIN; Renderer3D.DepthMode depthMode = useDepth ? Renderer3D.DepthMode.PRE_DEPTH : Renderer3D.DepthMode.MAIN;
Quaternionf camRot = RenderState.cameraRotation; Quaternionf camRot = RenderState.cameraRotation;
if (parent.hitParticleTexture.get() == ParticleTextureMode.BLOOM) { if (parent.hitParticleTexture.get() == ParticleTextureMode.BLOOM) {
if (FpsOptimizer.bloomDisabled()) return; if (Optimize.bloomDisabled()) return;
MeshBuilder mesh = renderer.batchTextured(pipeline, TextureStorage.FIRE_FLY, depthMode); MeshBuilder mesh = renderer.batchTextured(pipeline, TextureStorage.FIRE_FLY, depthMode);
if (mesh == null) return; if (mesh == null) return;
for (Particle3D p : hitParticles) renderParticle(mesh, p, tickDelta, camRot); for (Particle3D p : hitParticles) renderParticle(mesh, p, tickDelta, camRot);

View file

@ -1,69 +0,0 @@
package dev.loki.lovisual.features.module.modules.visuals.optimization;
import net.minecraft.core.particles.ParticleTypes;
import dev.loki.lovisual.config.values.primitive.BooleanValue;
import dev.loki.lovisual.config.values.primitive.NumberValue;
import dev.loki.lovisual.events.impl.render.particles.ParticleSpawnEvent;
import dev.loki.lovisual.events.meta.EventHandler;
import dev.loki.lovisual.features.module.core.Module;
import dev.loki.lovisual.features.module.core.ModuleCategory;
import dev.loki.lovisual.features.module.core.ModuleInfo;
import dev.loki.lovisual.features.module.lifecycle.Modules;
@ModuleInfo(
id = "fpsoptimizer",
displayName = "FPS Optimizer",
category = ModuleCategory.VISUALS
)
public final class FpsOptimizer extends Module {
private final BooleanValue disableParticles =
bool("disable_particles", false);
private final BooleanValue disableMenuBackground =
bool("disable_menu_background", false);
private final BooleanValue disableGlass =
bool("disable_glass", false);
private final BooleanValue disableBloom =
bool("disable_bloom", false);
private final BooleanValue entityCulling =
bool("entity_culling", false);
private final NumberValue<Integer> entityCullDistance =
visibleWhen(num("entity_cull_distance", 64, 8, 256), entityCulling::get);
public boolean isMenuBackgroundDisabled() {
return isEnabled() && disableMenuBackground.get();
}
public boolean isGlassDisabled() {
return isEnabled() && disableGlass.get();
}
public boolean isBloomDisabled() {
return isEnabled() && disableBloom.get();
}
public boolean isEntityCullingEnabled() {
return isEnabled() && entityCulling.get();
}
public int entityCullDistance() {
return entityCullDistance.get();
}
/** Cheap call-site guard for renderers that build bloom/glow geometry every frame. */
public static boolean bloomDisabled() {
FpsOptimizer module = Modules.get(FpsOptimizer.class);
return module != null && module.isBloomDisabled();
}
@EventHandler
private void onParticleSpawn(ParticleSpawnEvent event) {
if (!isEnabled() || !disableParticles.get()) return;
// Firework particles are created by FireworkParticles$Starter and assume ParticleEngine.createParticle never returns null.
// Cancelling them returns null and causes NPE at Starter.createParticle -> setTrail().
// Guard is also present in FireworkParticlesStarterMixin, but exempt here to preserve fireworks even with optimizer enabled.
var type = event.options().getType();
if (type == ParticleTypes.FIREWORK || type == ParticleTypes.FLASH) return;
event.cancel();
}
}

View file

@ -24,6 +24,7 @@ import dev.loki.lovisual.render.engine.renderer.Renderer3D;
import dev.loki.lovisual.render.spatialgui.SpatialGuiCapture; import dev.loki.lovisual.render.spatialgui.SpatialGuiCapture;
import dev.loki.lovisual.render.spatialgui.SpatialGuiPlane; import dev.loki.lovisual.render.spatialgui.SpatialGuiPlane;
import dev.loki.lovisual.render.engine.uniform.MeshBuilder; import dev.loki.lovisual.render.engine.uniform.MeshBuilder;
import dev.loki.lovisual.util.logging.DebugLog;
import net.minecraft.client.Camera; import net.minecraft.client.Camera;
import net.minecraft.client.CameraType; import net.minecraft.client.CameraType;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
@ -38,10 +39,12 @@ import org.joml.Vector3fc;
* porting the core idea of Spatial GUI (https://github.com/tastytrash/Spatial-GUI, MIT) to LoVisual's own * porting the core idea of Spatial GUI (https://github.com/tastytrash/Spatial-GUI, MIT) to LoVisual's own
* module/config system and its deferred GUI-render pipeline. * module/config system and its deferred GUI-render pipeline.
* <p> * <p>
* The actual off-screen capture happens in {@code GuiRendererCaptureMixin} (which redirects the vanilla * The off-screen capture follows the reference architecture: {@code GuiSpatialExtractMixin} diverts the open
* {@code GuiRenderer.draw()} pass into {@link SpatialGuiCapture} instead of the main render target while this * screen's extraction from the vanilla main GUI state into {@link SpatialGuiCapture}'s isolated state,
* module is active), and mouse routing happens in {@code MouseHandlerSpatialGuiMixin} (which reprojects the * {@code GameRendererSpatialGuiMixin} clears the capture texture and runs the isolated renderer at the end of
* real cursor position onto the plane published every frame via {@link SpatialGuiPlane}). * the frame, and {@code GuiRendererCaptureMixin} swaps that renderer's draw target for the capture texture —
* mouse routing happens in {@code MouseHandlerSpatialGuiMixin} (which reprojects the real cursor position onto
* the plane published every frame via {@link SpatialGuiPlane}).
*/ */
@ModuleInfo( @ModuleInfo(
id = "spatialgui", id = "spatialgui",
@ -168,23 +171,29 @@ public class SpatialGui extends Module {
@Override @Override
public void onRenderWorldEngine(Renderer3D renderer, Renderer3D depthRenderer, float tickDelta) { public void onRenderWorldEngine(Renderer3D renderer, Renderer3D depthRenderer, float tickDelta) {
Minecraft mc = Minecraft.getInstance(); Minecraft mc = Minecraft.getInstance();
if (mc.player == null || mc.level == null) return; if (mc.player == null || mc.level == null) {
DebugLog.renderThreadOnChange("sg.plane", "noLevel", "[SpatialGui] plane skipped: no level");
return;
}
boolean liveScreen = trackedScreen != null; boolean liveScreen = trackedScreen != null;
float progress = animationProgress(); float progress = animationProgress();
if (progress <= 0.0F && !liveScreen) { if (progress <= 0.0F && !liveScreen) {
SpatialGuiPlane.clear(); SpatialGuiPlane.clear();
DebugLog.renderThreadOnChange("sg.plane", "closed", "[SpatialGui] plane skipped: screen closed");
return; return;
} }
SpatialGuiCapture capture = SpatialGuiCapture.get(); SpatialGuiCapture capture = SpatialGuiCapture.get();
if (!capture.isReady()) { if (!capture.isReady()) {
SpatialGuiPlane.clear(); SpatialGuiPlane.clear();
DebugLog.renderThreadOnChange("sg.plane", "captureNotReady", "[SpatialGui] plane skipped: capture not ready");
return; return;
} }
GpuTextureView textureView = capture.colorTextureView(); GpuTextureView textureView = capture.colorTextureView();
if (textureView == null) { if (textureView == null) {
SpatialGuiPlane.clear(); SpatialGuiPlane.clear();
DebugLog.renderThreadOnChange("sg.plane", "noTextureView", "[SpatialGui] plane skipped: no texture view");
return; return;
} }
@ -245,6 +254,7 @@ public class SpatialGui extends Module {
float drawAlpha = "Fade".equals(style) ? baseAlpha * ease(progress) : baseAlpha; float drawAlpha = "Fade".equals(style) ? baseAlpha * ease(progress) : baseAlpha;
if (drawAlpha <= 0.001F) { if (drawAlpha <= 0.001F) {
SpatialGuiPlane.clear(); SpatialGuiPlane.clear();
DebugLog.renderThreadOnChange("sg.plane", "alpha0", "[SpatialGui] plane skipped: drawAlpha<=0");
return; return;
} }
@ -261,6 +271,7 @@ public class SpatialGui extends Module {
} }
MeshBuilder mesh = renderer.batchTextured(LoVisualRenderPipelines.WORLD_TEXTURED_PREMULTIPLIED, textureView, cachedSampler, Renderer3D.DepthMode.NONE); MeshBuilder mesh = renderer.batchTextured(LoVisualRenderPipelines.WORLD_TEXTURED_PREMULTIPLIED, textureView, cachedSampler, Renderer3D.DepthMode.NONE);
DebugLog.renderThreadOnChange("sg.plane.mesh", mesh != null, "[SpatialGui] plane mesh=%b alpha=%.2f", mesh != null, drawAlpha);
if (mesh != null) { if (mesh != null) {
// The capture holds premultiplied colour (GUI draws blended onto a transparent target), so the fade // The capture holds premultiplied colour (GUI draws blended onto a transparent target), so the fade
// factor must scale RGB together with alpha. // factor must scale RGB together with alpha.
@ -275,8 +286,11 @@ public class SpatialGui extends Module {
if (liveScreen) { if (liveScreen) {
SpatialGuiPlane.publish(new SpatialGuiPlane(center, planeRight, planeUp, halfWidth, halfHeight, guiWidth, guiHeight)); SpatialGuiPlane.publish(new SpatialGuiPlane(center, planeRight, planeUp, halfWidth, halfHeight, guiWidth, guiHeight));
DebugLog.renderThreadOnChange("sg.plane", "published",
"[SpatialGui] plane published center=(%.2f, %.2f, %.2f) size=%.2fx%.2f", center.x, center.y, center.z, halfWidth * 2.0F, halfHeight * 2.0F);
} else { } else {
SpatialGuiPlane.clear(); SpatialGuiPlane.clear();
DebugLog.renderThreadOnChange("sg.plane", "closing", "[SpatialGui] plane cleared: closing animation");
} }
} }

View file

@ -21,7 +21,9 @@ public final class LoVisualMixinPlugin implements IMixinConfigPlugin {
"dev.loki.lovisual.mixins.sodium.terrain.SodiumShaderChunkRendererMixin", "dev.loki.lovisual.mixins.sodium.terrain.SodiumShaderChunkRendererMixin",
"dev.loki.lovisual.mixins.sodium.vertex.SodiumVertexConsumerTrackerMixin", "dev.loki.lovisual.mixins.sodium.vertex.SodiumVertexConsumerTrackerMixin",
"dev.loki.lovisual.mixins.sodium.placement.SodiumPlaceCullMixin", "dev.loki.lovisual.mixins.sodium.placement.SodiumPlaceCullMixin",
"dev.loki.lovisual.mixins.sodium.placement.SodiumPlaceHideMixin" "dev.loki.lovisual.mixins.sodium.placement.SodiumPlaceHideMixin",
"dev.loki.lovisual.mixins.optimize.entity.SodiumEntityRendererMixin",
"dev.loki.lovisual.mixins.optimize.gl.raw.VertexConsumerUtilsMixin"
); );
private static final Set<String> OPTIONAL_IRIS_MIXINS = Set.of( private static final Set<String> OPTIONAL_IRIS_MIXINS = Set.of(
"dev.loki.lovisual.mixins.iris.render.IrisCommonUniformsMixin", "dev.loki.lovisual.mixins.iris.render.IrisCommonUniformsMixin",

View file

@ -0,0 +1,44 @@
package dev.loki.lovisual.mixins.optimize.block;
import dev.loki.lovisual.features.module.modules.misc.optimize.block.TickCached;
import net.minecraft.world.level.BaseSpawner;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Unique;
/**
* Stage 3: implements {@link TickCached} on {@link BaseSpawner} — adds the
* per-tick cache slot that {@link dev.loki.lovisual.features.module.modules.misc.optimize.block.SpawnerCache}
* reads back to skip the per-frame {@code extractEntity} rebuild of the
* spawner's display mob.
*
* <p>The vanilla {@code SpawnerRenderer.extractRenderState} rebuilds the
* display entity's render state every frame for every spawner in view;
* the display entity only changes on tick boundaries (spin speed, mob
* rotation, etc.), so caching by tick removes that rebuild from the hot path.
*
*/
@Mixin(BaseSpawner.class)
public abstract class BaseSpawnerMixin implements TickCached {
@Unique
private Object lovisual$cached;
@Unique
private long lovisual$cachedTick = Long.MIN_VALUE;
@Override
public Object lovisual$cached() {
return lovisual$cached;
}
@Override
public long lovisual$cachedTick() {
return lovisual$cachedTick;
}
@Override
public void lovisual$setCached(Object value, long tick) {
lovisual$cached = value;
lovisual$cachedTick = tick;
}
}

View file

@ -0,0 +1,139 @@
package dev.loki.lovisual.mixins.optimize.block;
import dev.loki.lovisual.features.module.modules.misc.optimize.block.CachedLight;
import dev.loki.lovisual.features.module.modules.misc.optimize.block.CachedValidity;
import dev.loki.lovisual.features.module.modules.misc.optimize.block.TickCached;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Unique;
/**
* Stage 3: implements {@link TickCached}, {@link CachedLight} and
* {@link CachedValidity} on {@link BlockEntity} — adds the per-tick cache
* slot (object + tick), the per-tick block-light lookups, the per-tick
* should-render distance check, and the per-state validity cache.
*
* <p>The vanilla {@code BlockEntityType.isValid(state)} is called every
* frame per block-entity in view but only changes on a state transition;
* {@code LightCoordsUtil.getLightCoords(level, pos)} walks the chunk's light
* section data per call; {@code BlockEntityRenderer.shouldRender} does a
* distance check that only changes when the entity moves across the cull
* boundary. All three are cached via the interface fields implemented here.
*
*/
@Mixin(BlockEntity.class)
public abstract class BlockEntityMixin implements TickCached, CachedLight, CachedValidity {
// --- TickCached ---
@Unique
private Object lovisual$cached;
@Unique
private long lovisual$cachedTick = Long.MIN_VALUE;
// --- CachedLight ---
@Unique
private int lovisual$light;
@Unique
private long lovisual$lightTick = Long.MIN_VALUE;
@Unique
private int lovisual$pairLight;
@Unique
private long lovisual$pairLightTick = Long.MIN_VALUE;
// --- CachedValidity ---
@Unique
private BlockState lovisual$validState;
@Unique
private boolean lovisual$valid;
@Unique
private long lovisual$distanceTick = Long.MIN_VALUE;
@Unique
private boolean lovisual$inDistance;
// --- TickCached ---
@Override
public Object lovisual$cached() {
return lovisual$cached;
}
@Override
public long lovisual$cachedTick() {
return lovisual$cachedTick;
}
@Override
public void lovisual$setCached(Object value, long tick) {
lovisual$cached = value;
lovisual$cachedTick = tick;
}
// --- CachedLight ---
@Override
public int lovisual$light() {
return lovisual$light;
}
@Override
public long lovisual$lightTick() {
return lovisual$lightTick;
}
@Override
public void lovisual$setLight(int light, long tick) {
lovisual$light = light;
lovisual$lightTick = tick;
}
@Override
public int lovisual$pairLight() {
return lovisual$pairLight;
}
@Override
public long lovisual$pairLightTick() {
return lovisual$pairLightTick;
}
@Override
public void lovisual$setPairLight(int light, long tick) {
lovisual$pairLight = light;
lovisual$pairLightTick = tick;
}
// --- CachedValidity ---
@Override
public BlockState lovisual$validState() {
return lovisual$validState;
}
@Override
public boolean lovisual$valid() {
return lovisual$valid;
}
@Override
public void lovisual$setValid(BlockState state, boolean valid) {
lovisual$validState = state;
lovisual$valid = valid;
}
@Override
public long lovisual$distanceTick() {
return lovisual$distanceTick;
}
@Override
public boolean lovisual$inDistance() {
return lovisual$inDistance;
}
@Override
public void lovisual$setInDistance(boolean inDistance, long tick) {
lovisual$inDistance = inDistance;
lovisual$distanceTick = tick;
}
}

View file

@ -0,0 +1,55 @@
package dev.loki.lovisual.mixins.optimize.block;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
import dev.loki.lovisual.features.module.modules.misc.optimize.block.CachedLight;
import dev.loki.lovisual.render.engine.optimize.OptimizeToggles;
import net.minecraft.client.renderer.blockentity.state.BlockEntityRenderState;
import net.minecraft.client.renderer.feature.ModelFeatureRenderer;
import net.minecraft.core.BlockPos;
import net.minecraft.util.LightCoordsUtil;
import net.minecraft.world.level.BlockAndLightGetter;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.entity.BlockEntity;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
/**
* Stage 3: cache per-tick block-light lookups on every block-entity in view.
*
* <p>Vanilla {@code BlockEntityRenderState.extractBase} calls
* {@link LightCoordsUtil#getLightCoords} every frame per block-entity — that
* walks the chunk's light section data per call, and the light value only
* changes on tick boundaries. This WrapOperation wraps the call to consult
* the per-tick cache slot on the {@link BlockEntity} (via the
* {@link CachedLight} mixin from Stage 3-continued-2) before falling through
* to the original.
*
* Gated on the {@code blockEntityCache} toggle via
* {@link OptimizeToggles#blockEntityCache()}. When the toggle is off, the
* original runs unchanged.
*/
@Mixin(BlockEntityRenderState.class)
public abstract class BlockEntityRenderStateMixin {
@WrapOperation(
method = "extractBase",
at = @At(value = "INVOKE",
target = "Lnet/minecraft/util/LightCoordsUtil;getLightCoords(Lnet/minecraft/world/level/BlockAndLightGetter;Lnet/minecraft/core/BlockPos;)I")
)
private static int lovisual$cachedLight(BlockAndLightGetter level, BlockPos pos, Operation<Integer> original,
BlockEntity blockEntity, BlockEntityRenderState state,
ModelFeatureRenderer.CrumblingOverlay crumbling) {
if (!OptimizeToggles.blockEntityCache() || !(level instanceof Level world)) {
return original.call(level, pos);
}
if (!(blockEntity instanceof CachedLight cache)) {
return original.call(level, pos);
}
long tick = world.getGameTime();
if (cache.lovisual$lightTick() != tick) {
cache.lovisual$setLight(original.call(level, pos), tick);
}
return cache.lovisual$light();
}
}

View file

@ -0,0 +1,88 @@
package dev.loki.lovisual.mixins.optimize.block;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
import dev.loki.lovisual.features.module.modules.misc.optimize.block.CachedLight;
import dev.loki.lovisual.features.module.modules.misc.optimize.block.TickCached;
import dev.loki.lovisual.render.engine.optimize.OptimizeToggles;
import it.unimi.dsi.fastutil.ints.Int2IntFunction;
import net.minecraft.client.renderer.blockentity.ChestRenderer;
import net.minecraft.client.renderer.blockentity.state.ChestRenderState;
import net.minecraft.client.renderer.feature.ModelFeatureRenderer;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.ChestBlock;
import net.minecraft.world.level.block.DoubleBlockCombiner;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.Vec3;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
/**
* Stage 3: double-chest combine cache + double-chest pair-light cache.
*
* <p>Two WrapOperations on {@link ChestRenderer#extractRenderState}:
* <ul>
* <li><b>Combine cache</b> — wraps {@link ChestBlock#combine} (the
* neighbor-lookup that builds the double-chest render state). The
* result only changes when the neighbour block changes, so caching by
* game tick (via the {@link TickCached} mixin from Stage 3-continued-2)
* removes the neighbor-walk from the per-frame hot path.</li>
* <li><b>Pair-light cache</b> — wraps {@link Int2IntFunction#applyAsInt}
* (the second light lookup done for double chests). Two light lookups
* per chest per frame in vanilla, cached to one per tick via the
* {@link CachedLight#lovisual$pairLight()} slot.</li>
* </ul>
*
* Combine cache gated on {@code blockEntityCache} toggle; pair-light cache
* gated on {@code microOpts} toggle.
*/
@Mixin(ChestRenderer.class)
public abstract class ChestRendererMixin {
@WrapOperation(
method = "extractRenderState(Lnet/minecraft/world/level/block/entity/BlockEntity;Lnet/minecraft/client/renderer/blockentity/state/ChestRenderState;FLnet/minecraft/world/phys/Vec3;Lnet/minecraft/client/renderer/feature/ModelFeatureRenderer$CrumblingOverlay;)V",
at = @At(value = "INVOKE",
target = "Lnet/minecraft/world/level/block/ChestBlock;combine(Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/world/level/Level;Lnet/minecraft/core/BlockPos;Z)Lnet/minecraft/world/level/block/DoubleBlockCombiner$NeighborCombineResult;")
)
private DoubleBlockCombiner.NeighborCombineResult<?> lovisual$cachedCombine(
ChestBlock block, BlockState state, Level level, BlockPos pos, boolean ignoreBlocked,
Operation<DoubleBlockCombiner.NeighborCombineResult<?>> original,
BlockEntity blockEntity, ChestRenderState renderState, float partialTick, Vec3 camera,
ModelFeatureRenderer.CrumblingOverlay crumbling) {
if (!OptimizeToggles.blockEntityCache()) {
return original.call(block, state, level, pos, ignoreBlocked);
}
if (!(blockEntity instanceof TickCached cache)) {
return original.call(block, state, level, pos, ignoreBlocked);
}
long tick = level.getGameTime();
if (cache.lovisual$cachedTick() != tick || cache.lovisual$cached() == null) {
cache.lovisual$setCached(original.call(block, state, level, pos, ignoreBlocked), tick);
}
return (DoubleBlockCombiner.NeighborCombineResult<?>) cache.lovisual$cached();
}
@WrapOperation(
method = "extractRenderState(Lnet/minecraft/world/level/block/entity/BlockEntity;Lnet/minecraft/client/renderer/blockentity/state/ChestRenderState;FLnet/minecraft/world/phys/Vec3;Lnet/minecraft/client/renderer/feature/ModelFeatureRenderer$CrumblingOverlay;)V",
at = @At(value = "INVOKE",
target = "Lit/unimi/dsi/fastutil/ints/Int2IntFunction;applyAsInt(I)I")
)
private int lovisual$cachedPairLight(Int2IntFunction combiner, int light, Operation<Integer> original,
BlockEntity blockEntity, ChestRenderState renderState, float partialTick, Vec3 camera,
ModelFeatureRenderer.CrumblingOverlay crumbling) {
Level level = blockEntity.getLevel();
if (!OptimizeToggles.microOpts() || level == null) {
return original.call(combiner, light);
}
if (!(blockEntity instanceof CachedLight cache)) {
return original.call(combiner, light);
}
long tick = level.getGameTime();
if (cache.lovisual$pairLightTick() != tick) {
cache.lovisual$setPairLight(original.call(combiner, light), tick);
}
return cache.lovisual$pairLight();
}
}

View file

@ -0,0 +1,41 @@
package dev.loki.lovisual.mixins.optimize.entity;
import dev.loki.lovisual.features.module.modules.misc.optimize.entity.CachedName;
import net.minecraft.network.chat.Component;
import net.minecraft.world.entity.Entity;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Unique;
/**
* Stage 3: implements {@link CachedName} on {@link Entity} — adds the cached
* name-tag fields (name + tick) that {@link EntityRendererNameMixin} populates
* and reads back. Vanilla {@code Entity.getDisplayName()} rebuilds the team
* prefix + name + suffix on every call; renderers call it once per frame per
* entity in view, so caching by tick cuts the per-frame cost.
*
*/
@Mixin(Entity.class)
public abstract class EntityNameMixin implements CachedName {
@Unique
private Component lovisual$name;
@Unique
private long lovisual$nameTick = Long.MIN_VALUE;
@Override
public Component lovisual$name() {
return lovisual$name;
}
@Override
public long lovisual$nameTick() {
return lovisual$nameTick;
}
@Override
public void lovisual$setName(Component name, long tick) {
lovisual$name = name;
lovisual$nameTick = tick;
}
}

View file

@ -0,0 +1,32 @@
package dev.loki.lovisual.mixins.optimize.entity;
import dev.loki.lovisual.features.module.modules.misc.optimize.entity.StateEntity;
import net.minecraft.client.renderer.entity.state.EntityRenderState;
import net.minecraft.world.entity.Entity;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Unique;
/**
* Stage 3: implements {@link StateEntity} on {@link EntityRenderState} — adds
* the back-reference field to the source {@link Entity}. Render-states are
* rebuilt every frame, so they can't keep their own pointer — the
* {@link EntityRendererStateMixin} captures it once per state construction
* via {@code createRenderState} and downstream renderers read it back.
*
*/
@Mixin(EntityRenderState.class)
public abstract class EntityRenderStateEntityMixin implements StateEntity {
@Unique
private Entity lovisual$entity;
@Override
public Entity lovisual$entity() {
return lovisual$entity;
}
@Override
public void lovisual$entity(Entity entity) {
lovisual$entity = entity;
}
}

View file

@ -0,0 +1,41 @@
package dev.loki.lovisual.mixins.optimize.entity;
import com.llamalad7.mixinextras.injector.ModifyExpressionValue;
import dev.loki.lovisual.features.module.modules.misc.optimize.entity.EntityLod;
import net.minecraft.client.renderer.entity.LivingEntityRenderer;
import net.minecraft.client.renderer.entity.state.LivingEntityRenderState;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
/**
* Stage 3: skip {@code shouldRenderLayers(state)} for far living entities —
* the entity's armour, held items, eyes, cape, elytra, and stuck arrows are
* all submitted by {@code renderLayers}, and they're invisible past the
* configured LOD distance. Returning {@code false} short-circuits the whole
* layer pass for that entity.
*
* <p>The vanilla {@code shouldRenderLayers} returns true for every visible
* entity; we AND it with "not far" so far entities skip the layers but
* close entities render them as usual.
*
*
* <p>Gated on the {@code entity_lod} toggle via {@link EntityLod#far(double)}.
* When the toggle is off, {@code far} returns {@code false} so the modify
* leaves the original value unchanged.
*/
@Mixin(LivingEntityRenderer.class)
public abstract class LivingEntityLodMixin {
@ModifyExpressionValue(
method = "submit",
at = @At(value = "INVOKE",
target = "Lnet/minecraft/client/renderer/entity/LivingEntityRenderer;shouldRenderLayers(Lnet/minecraft/client/renderer/entity/state/LivingEntityRenderState;)Z")
)
private boolean lovisual$skipFarLayers(boolean original, LivingEntityRenderState state) {
if (!original) {
return false;
}
// Stage 1 collapses player LOD into entity LOD — same toggle, same threshold.
return !EntityLod.far(state.distanceToCameraSq);
}
}

View file

@ -0,0 +1,42 @@
package dev.loki.lovisual.mixins.optimize.entity;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
import dev.loki.lovisual.features.module.modules.misc.optimize.entity.CachedStack;
import dev.loki.lovisual.render.engine.optimize.OptimizeToggles;
import org.lwjgl.system.MemoryStack;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
/**
* Stage 3: hot-path helper for Sodium's entity cuboid renderer — wraps
* {@code MemoryStack.stackPush()} so the render thread's stack is cached by
* identity instead of being looked up via ThreadLocal on every cuboid. Sodium
* calls this once per cuboid per frame (thousands of times for dense entity
* scenes), so the cached lookup is a measurable win on the hot path.
*
* <p>Uses {@code WrapOperation} rather than {@code @Redirect} because
* MixinExtras 0.5.4 (which Fabric Loader 0.19.3 ships with) crashes on a
* static {@code @Redirect} here — pinned to 0.5.5 in {@code build.gradle},
* but the convention is kept for safety. The mixin is registered with
* {@code remap = false} because the target is a Sodium class, not a Mojang one.
*
* Gated on the {@code microOpts} toggle via {@link OptimizeToggles#microOpts()}.
* When the toggle is off, the original runs unchanged.
*
* <p>Registered conditionally via {@code LoVisualMixinPlugin} — only applied
* when Sodium is loaded. See {@code lovisual.mixins.json} entry in the
* {@code client} array.
*/
@Mixin(targets = "net.caffeinemc.mods.sodium.client.render.immediate.model.EntityRenderer", remap = false)
public abstract class SodiumEntityRendererMixin {
@WrapOperation(
method = "renderCuboid",
at = @At(value = "INVOKE",
target = "Lorg/lwjgl/system/MemoryStack;stackPush()Lorg/lwjgl/system/MemoryStack;")
)
private static MemoryStack lovisual$cachedStack(Operation<MemoryStack> original) {
return OptimizeToggles.microOpts() ? CachedStack.push() : original.call();
}
}

View file

@ -0,0 +1,30 @@
package dev.loki.lovisual.mixins.optimize.entity.anim;
import dev.loki.lovisual.render.engine.optimize.entity.AnimFreeze;
import dev.loki.lovisual.render.engine.optimize.entity.AnimHolder;
import net.minecraft.world.entity.Entity;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Unique;
/**
* Stage 3 step 4: implements {@link AnimHolder} on {@code Entity} — adds the
* per-entity bag of frozen animation captures. The field lives as long as
* the entity; captures hold direct buffers, so long-lived entities keep at
* most one capture per (model, renderType, sprite) submission slot.
*/
@Mixin(Entity.class)
public abstract class EntityAnimHolderMixin implements AnimHolder {
@Unique
private AnimFreeze.Holder lovisual$anim;
@Override
public AnimFreeze.Holder lovisual$anim() {
return lovisual$anim;
}
@Override
public void lovisual$anim(AnimFreeze.Holder holder) {
lovisual$anim = holder;
}
}

View file

@ -0,0 +1,61 @@
package dev.loki.lovisual.mixins.optimize.entity.anim;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.blaze3d.vertex.VertexConsumer;
import dev.loki.lovisual.features.module.modules.misc.optimize.entity.StateEntity;
import dev.loki.lovisual.render.engine.optimize.entity.AnimFreeze;
import dev.loki.lovisual.render.engine.optimize.parallel.ParallelModelHook;
import java.util.List;
import net.minecraft.client.model.Model;
import net.minecraft.client.renderer.entity.state.EntityRenderState;
import net.minecraft.client.renderer.feature.FeatureFrameContext;
import net.minecraft.client.renderer.feature.ModelFeatureRenderer;
import net.minecraft.world.entity.Entity;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
/**
* Stage 3 step 4: the AnimFreeze call site. When a far entity's model part is
* about to render, hand the submission to {@link AnimFreeze#render} — it
* replays the once-per-tick raw vertex capture shifted to the current
* position; on success the vanilla {@code renderToBuffer} is skipped.
*
* <p>The buffer may already be sprite-wrapped; the replayed vertices go
* through it, so Sodium's push remaps their UVs. Sheeted decals (block
* cracks) never freeze — their pose is built elsewhere.
*/
@Mixin(ModelFeatureRenderer.class)
public abstract class ModelFeatureRendererMixin {
@Inject(method = "buildGroup", at = @At("HEAD"), cancellable = true)
private void lovisual$parallel(FeatureFrameContext context, List<ModelFeatureRenderer.Submit<?>> submits,
CallbackInfo ci) {
if (ParallelModelHook.buildGroup((ModelFeatureRenderer) (Object) this, submits)) {
ci.cancel();
}
}
@WrapOperation(
method = "prepareModel",
at = @At(value = "INVOKE",
target = "Lnet/minecraft/client/model/Model;renderToBuffer(Lcom/mojang/blaze3d/vertex/PoseStack;Lcom/mojang/blaze3d/vertex/VertexConsumer;III)V")
)
private void lovisual$frozenAnimation(Model<?> model, PoseStack poseStack, VertexConsumer consumer,
int light, int overlay, int color, Operation<Void> original,
ModelFeatureRenderer.Submit<?> submit) {
if (AnimFreeze.enabled() && submit.sheetedDecalPose() == null
&& submit.state() instanceof EntityRenderState state) {
Entity entity = ((StateEntity) state).lovisual$entity();
if (entity != null && AnimFreeze.render(entity, model, submit.renderType(), null,
poseStack.last().pose(), consumer,
target -> original.call(model, poseStack, target, light, overlay, color))) {
return;
}
}
original.call(model, poseStack, consumer, light, overlay, color);
}
}

View file

@ -0,0 +1,17 @@
package dev.loki.lovisual.mixins.optimize.entity.parallel;
import net.minecraft.client.renderer.feature.ModelFeatureRenderer;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Invoker;
/**
* Stage 3 step 8: the vanilla per-model build, invoked as the fallback for
* submits the parallel path could not take (wrong format, decals, frozen
* animations, raw-vertex consumer unavailable).
*/
@Mixin(ModelFeatureRenderer.class)
public interface ModelFeatureRendererInvoker {
@Invoker("prepareModel")
<S> void lovisual$prepareModel(ModelFeatureRenderer.Submit<S> submit);
}

View file

@ -0,0 +1,21 @@
package dev.loki.lovisual.mixins.optimize.entity.parallel;
import java.util.List;
import java.util.Map;
import net.minecraft.client.model.geom.ModelPart;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Accessor;
/**
* Stage 3 step 8: exposes the part-tree internals the parallel model build
* flattens once per model — the baked cubes and the ordered children map.
*/
@Mixin(ModelPart.class)
public interface ModelPartAccessor {
@Accessor("cubes")
List<ModelPart.Cube> lovisual$cubes();
@Accessor("children")
Map<String, ModelPart> lovisual$children();
}

View file

@ -0,0 +1,19 @@
package dev.loki.lovisual.mixins.optimize.entity.parallel;
import com.mojang.blaze3d.vertex.VertexConsumer;
import net.minecraft.client.renderer.feature.RenderTypeFeatureRenderer;
import net.minecraft.client.renderer.rendertype.RenderType;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Invoker;
/**
* Stage 3 step 8: the per-render-type vertex builder the parallel emit hands
* its raw vertices to — one builder call per model, exactly as vanilla's
* prepareModel would make.
*/
@Mixin(RenderTypeFeatureRenderer.class)
public interface RenderTypeFeatureRendererInvoker {
@Invoker("getVertexBuilder")
VertexConsumer lovisual$vertexBuilder(RenderType renderType);
}

View file

@ -0,0 +1,49 @@
package dev.loki.lovisual.mixins.optimize.entity.renderer;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
import dev.loki.lovisual.features.module.modules.misc.optimize.entity.CachedName;
import dev.loki.lovisual.render.engine.optimize.OptimizeToggles;
import net.minecraft.client.renderer.entity.EntityRenderer;
import net.minecraft.network.chat.Component;
import net.minecraft.world.entity.Entity;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
/**
* Stage 3: caches {@code Entity.getDisplayName()} per tick. The vanilla
* implementation rebuilds a {@link Component} (team prefix + name + suffix)
* every call; renderers call it once per frame per entity in view. Wrapping
* the call here keeps the per-frame cost to one identity check + read,
* instead of a full Component rebuild + style lookup.
*
* <p>The cache is keyed by game tick — name parts only change on tick
* boundaries (team membership, name change). On the first call of a tick the
* original runs and the result is stored; subsequent calls in the same tick
* return the cached instance.
*
* Gated on the {@code microOpts} toggle via {@link OptimizeToggles#microOpts()}.
* When the toggle is off, the original runs unchanged.
*/
@Mixin(EntityRenderer.class)
public abstract class EntityRendererNameMixin {
@WrapOperation(
method = "getNameTag",
at = @At(value = "INVOKE",
target = "Lnet/minecraft/world/entity/Entity;getDisplayName()Lnet/minecraft/network/chat/Component;")
)
private Component lovisual$cachedName(Entity entity, Operation<Component> original) {
if (!OptimizeToggles.microOpts()) {
return original.call(entity);
}
if (!(entity instanceof CachedName cache)) {
return original.call(entity);
}
long tick = entity.level().getGameTime();
if (cache.lovisual$nameTick() != tick) {
cache.lovisual$setName(original.call(entity), tick);
}
return cache.lovisual$name();
}
}

View file

@ -0,0 +1,41 @@
package dev.loki.lovisual.mixins.optimize.entity.renderer;
import com.llamalad7.mixinextras.sugar.Local;
import dev.loki.lovisual.features.module.modules.misc.optimize.entity.StateEntity;
import net.minecraft.client.renderer.entity.EntityRenderer;
import net.minecraft.client.renderer.entity.state.EntityRenderState;
import net.minecraft.world.entity.Entity;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
/**
* Stage 3: captures the source {@link Entity} on every freshly-built
* {@link EntityRenderState}. Vanilla's {@code createRenderState(entity, partial)}
* returns a state without back-reference; this inject at RETURN stores the
* entity on the state via the {@link StateEntity} contract so downstream
* renderers (model feature renderer, item feature renderer, future LOD mixins)
* can reach the live entity.
*
* The original used {@code @ModifyReturnValue}; LoVisual uses {@code @Inject}
* at RETURN with {@code CallbackInfoReturnable} so the mixin stays simple and
* doesn't rely on the (more fragile across versions) MixinExtras return-value
* transformer — the captured state is set as a side effect, not returned.
*/
@Mixin(EntityRenderer.class)
public abstract class EntityRendererStateMixin {
@Inject(
method = "createRenderState(Lnet/minecraft/world/entity/Entity;F)Lnet/minecraft/client/renderer/entity/state/EntityRenderState;",
at = @At("RETURN")
)
private void lovisual$rememberEntity(Entity entity, float partialTick,
CallbackInfoReturnable<EntityRenderState> cir,
@Local(argsOnly = true) Entity localEntity) {
EntityRenderState state = cir.getReturnValue();
if (state instanceof StateEntity stateEntity) {
stateEntity.lovisual$entity(localEntity);
}
}
}

View file

@ -0,0 +1,29 @@
package dev.loki.lovisual.mixins.optimize.gl;
import dev.loki.lovisual.features.module.modules.misc.optimize.gl.RenderBackendOps;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
/**
* Stage 3 step 2 (completes the TBO cache): only {@code GlBuffer.Direct}
* deletes its GL handle; transient buffers are slices of a shared one. A
* deleted buffer's id can be reused by a new buffer, so the attachment cache
* must not outlive it — this hook clears the cache on every Direct close.
*
*
* <p>Unconditional (clearing a tiny map on buffer close is free); correctness
* beats the micro-saving of keeping stale attachments around.
*/
@Mixin(targets = "com.mojang.blaze3d.opengl.GlBuffer$Direct")
public abstract class GlBufferCloseMixin {
@Inject(method = "close", at = @At("HEAD"))
private void lovisual$forgetTboCache(CallbackInfo ci) {
RenderBackendOps backend = RenderBackendOps.current();
if (backend != null) {
backend.forgetTboCache();
}
}
}

View file

@ -0,0 +1,38 @@
package dev.loki.lovisual.mixins.optimize.gl;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
import com.mojang.blaze3d.opengl.GlStateManager;
import dev.loki.lovisual.features.module.modules.misc.optimize.gl.RenderBackendOps;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
/**
* Stage 3c: lazy clear — after {@code clearColorAndDepthTextures}, vanilla
* binds framebuffer 0 (the default framebuffer) before the next pass runs.
* The next pass binds its own target anyway, and {@code GlStateManager}'s
* cache skips the redundant bind. This mixin drops the explicit bind-0 so
* we don't pay for a {@code glBindFramebuffer(GL_FRAMEBUFFER, 0)} that's
* immediately overwritten.
*
*
* <p>Gated on the {@code microOpts} toggle via {@link RenderBackendOps#skipBindFramebufferZero(int)}.
* When the toggle is off, the original call runs unchanged.
*/
@Mixin(targets = "com.mojang.blaze3d.opengl.GlCommandEncoder")
public abstract class GlCommandEncoderClearMixin {
@WrapOperation(
method = "clearColorAndDepthTextures",
at = @At(value = "INVOKE",
target = "Lcom/mojang/blaze3d/opengl/GlStateManager;_glBindFramebuffer(II)V")
)
private void lovisual$skipBindZero(int target, int framebuffer, Operation<Void> original) {
RenderBackendOps backend = RenderBackendOps.current();
if (backend != null && backend.skipBindFramebufferZero(framebuffer)) {
// Skip the bind — the next render pass binds its own target anyway.
return;
}
original.call(target, framebuffer);
}
}

View file

@ -0,0 +1,55 @@
package dev.loki.lovisual.mixins.optimize.gl;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
import dev.loki.lovisual.features.module.modules.misc.optimize.gl.RenderBackendOps;
import org.lwjgl.opengl.GL33C;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
/**
* Stage 3d: TBO cache — when {@code GlCommandEncoder.trySetup} binds a
* texel-buffer texture via {@code glBindTexture}, we record the texture ID.
* When {@code glTexBuffer(target, format, buffer)} is called for the same
* {@code (format, buffer)} pair that's already attached, we skip the call —
* re-attaching makes the driver revalidate the texture (clouds: ~2% of a
* frame in {@code glDrawElements}).
*
*
* <p>Gated on the {@code microOpts} toggle via
* {@link RenderBackendOps#tboCacheSupported()}. When the toggle is off, both
* {@code WrapOperation}s call the original.
*/
@Mixin(targets = "com.mojang.blaze3d.opengl.GlCommandEncoder")
public abstract class GlCommandEncoderTexBufferMixin {
@WrapOperation(
method = "trySetup",
at = @At(value = "INVOKE",
target = "Lorg/lwjgl/opengl/GL33C;glBindTexture(II)V")
)
private void lovisual$trackBoundTboTexture(int target, int texture, Operation<Void> original) {
RenderBackendOps backend = RenderBackendOps.current();
if (backend != null && backend.tboCacheSupported()) {
backend.trackBoundTboTexture(texture);
}
original.call(target, texture);
}
@WrapOperation(
method = "trySetup",
at = @At(value = "INVOKE",
target = "Lorg/lwjgl/opengl/GL33C;glTexBuffer(III)V")
)
private void lovisual$texBufferOnce(int target, int format, int buffer, Operation<Void> original) {
RenderBackendOps backend = RenderBackendOps.current();
if (backend != null && backend.tboAlreadyAttached(format, buffer)) {
// Same (format, buffer) pair already attached to the bound texture — skip the re-attach.
return;
}
original.call(target, format, buffer);
if (backend != null) {
backend.markTboAttached(format, buffer);
}
}
}

View file

@ -0,0 +1,60 @@
package dev.loki.lovisual.mixins.optimize.gl;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
import dev.loki.lovisual.features.module.modules.misc.optimize.gl.RenderBackendOps;
import net.minecraft.client.renderer.rendertype.RenderType;
import net.minecraft.client.renderer.rendertype.RenderTypes;
import net.minecraft.resources.Identifier;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import java.util.function.BiFunction;
/**
* Stage 3b: cache {@code RenderTypes.entityTranslucent(id, flag=true)} by
* identifier — vanilla uses {@code Util.memoize} keyed on {@code Pair(id, flag)},
* which {@code Objects.hash}-es the pair on every call, per entity per frame.
* When the flag is {@code true} (the common case — translucent skins, held
* items, etc.), the result depends only on the identifier, so we cache it
* directly in a {@code ConcurrentHashMap}.
*
* is wrapped in {@link RenderBackendOps}; LoVisual's GL implementation is
* {@code GlRenderBackendOps}, which gates on {@code microOpts} (Stage 1 toggle).
*
* <p>When the toggle is off, the WrapOperation calls the original — vanilla
* behavior preserved. When the toggle is on and the flag is {@code true},
* the cache is consulted; on a miss, the original is called and the result
* is stored.
*/
@Mixin(RenderTypes.class)
public abstract class RenderTypesMixin {
@WrapOperation(
method = "entityTranslucent(Lnet/minecraft/resources/Identifier;Z)Lnet/minecraft/client/renderer/rendertype/RenderType;",
at = @At(value = "INVOKE",
target = "Ljava/util/function/BiFunction;apply(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;")
)
private static Object lovisual$cacheTranslucent(
BiFunction<Object, Object, Object> memo, Object id, Object flag, Operation<Object> original) {
RenderBackendOps backend = RenderBackendOps.current();
if (backend == null || !backend.renderTypesCacheSupported()) {
return original.call(memo, id, flag);
}
// Only cache when the flag is true — the false case depends on the flag too.
if (!(Boolean) flag) {
return original.call(memo, id, flag);
}
Identifier mcId = (Identifier) id;
RenderBackendOps.Identifier cacheKey = new RenderBackendOps.Identifier(mcId.getNamespace(), mcId.getPath());
Object cached = backend.renderTypeFor(cacheKey);
if (cached != null) {
return cached;
}
Object result = original.call(memo, id, flag);
if (result instanceof RenderType) {
backend.cacheRenderType(cacheKey, result);
}
return result;
}
}

View file

@ -0,0 +1,53 @@
package dev.loki.lovisual.mixins.optimize.gl.fbo;
import com.mojang.blaze3d.opengl.DirectStateAccess;
import com.mojang.blaze3d.opengl.FrameBufferAttachment;
import com.mojang.blaze3d.opengl.FrameBufferCache;
import dev.loki.lovisual.render.engine.optimize.gl.SharedDepthFbos;
import it.unimi.dsi.fastutil.objects.Object2IntMap;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import java.util.List;
/**
* Stage 3 step 2: feeds {@link SharedDepthFbos} from the vanilla FBO cache.
* {@code getFbo} records "this depth texture lives in that FBO" (mip 0 only —
* higher mips are never the depth attachment of the cached FBO);
* {@code destroyFbo} drops the mapping before the FBO is deleted, because its
* GL id may be reused by the next one.
*
*
* <p>Bookkeeping only — runs regardless of the {@code fbo_share} toggle (a
* map put/remove per FBO create/destroy is free); the toggle gates the clear
* path in {@code GlCommandEncoderDepthClearMixin}.
*/
@Mixin(FrameBufferCache.class)
public abstract class FrameBufferCacheMixin {
@Shadow
@Final
private Object2IntMap<FrameBufferCache.CacheKey> cache;
@Inject(method = "getFbo", at = @At("RETURN"))
private void lovisual$rememberDepth(DirectStateAccess dsa,
List<FrameBufferAttachment> colors,
FrameBufferAttachment depth,
CallbackInfoReturnable<Integer> cir) {
if (depth != null && depth.fboMipLevel() == 0) {
SharedDepthFbos.remember(depth.glId(), cir.getReturnValueI());
}
}
@Inject(method = "destroyFbo", at = @At("HEAD"))
private void lovisual$forget(FrameBufferCache.CacheKey key, CallbackInfo ci) {
if (cache.containsKey(key)) {
SharedDepthFbos.forget(cache.getInt(key));
}
}
}

View file

@ -0,0 +1,36 @@
package dev.loki.lovisual.mixins.optimize.gl.fbo;
import com.mojang.blaze3d.opengl.GlTexture;
import com.mojang.blaze3d.textures.GpuTexture;
import dev.loki.lovisual.features.module.modules.misc.optimize.gl.RenderBackendOps;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
/**
* Stage 3 step 2: vanilla attaches the depth texture to a scratch FBO,
* clears, detaches and unbinds; a cached FBO (see {@code FrameBufferCacheMixin})
* already holds the attachment, so the clear becomes one
* {@code glClearNamedFramebufferfv}. Cancels the vanilla path when the
* in-place clear ran.
*
*
* <p>Gated on the {@code fbo_share} toggle via
* {@link RenderBackendOps#clearDepthInPlace(int, double)}; a closed texture
* or a missing DSA capability falls through to vanilla unchanged.
*/
@Mixin(targets = "com.mojang.blaze3d.opengl.GlCommandEncoder")
public abstract class GlCommandEncoderDepthClearMixin {
@Inject(method = "clearDepthTexture", at = @At("HEAD"), cancellable = true)
private void lovisual$clearInPlace(GpuTexture depth, double value, CallbackInfo ci) {
if (!(depth instanceof GlTexture gl) || gl.isClosed()) {
return;
}
RenderBackendOps backend = RenderBackendOps.current();
if (backend != null && backend.clearDepthInPlace(gl.glId(), value)) {
ci.cancel();
}
}
}

View file

@ -0,0 +1,53 @@
package dev.loki.lovisual.mixins.optimize.gl.raw;
import com.mojang.blaze3d.vertex.BufferBuilder;
import com.mojang.blaze3d.vertex.ByteBufferBuilder;
import com.mojang.blaze3d.vertex.VertexFormat;
import dev.loki.lovisual.render.engine.optimize.gl.RawBuffer;
import org.lwjgl.system.MemoryUtil;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
/**
* Stage 3 step 7: what Sodium's {@code VertexBufferWriter} does for a
* {@code BufferBuilder} — push ready-made vertex bytes straight into the
* buffer — reimplemented on the vanilla builder so raw-vertex consumers
* (AnimFreeze, ParallelModels) work without Sodium.
*
*/
@Mixin(BufferBuilder.class)
public abstract class BufferBuilderRawMixin implements RawBuffer {
@Shadow
private int vertices;
@Shadow
@Final
private int vertexSize;
@Shadow
private long vertexPointer;
@Shadow
@Final
private ByteBufferBuilder buffer;
@Shadow
private int elementsToFill;
@Shadow
@Final
private VertexFormat format;
@Override
public boolean lovisual$accepts(VertexFormat format) {
return format == this.format;
}
@Override
public void lovisual$push(long src, int count) {
int length = count * vertexSize;
long dst = buffer.reserve(length);
MemoryUtil.memCopy(src, dst, length);
vertices += count;
// the pushed vertices are complete: the next addVertex must not see a half-filled one
vertexPointer = dst + length - vertexSize;
elementsToFill = 0;
}
}

View file

@ -0,0 +1,42 @@
package dev.loki.lovisual.mixins.optimize.gl.raw;
import com.llamalad7.mixinextras.injector.wrapmethod.WrapMethod;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import com.mojang.blaze3d.vertex.VertexConsumer;
import dev.loki.lovisual.render.engine.optimize.OptimizeToggles;
import net.caffeinemc.mods.sodium.api.vertex.buffer.VertexBufferWriter;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Unique;
/**
* Stage 3 step 7: caches Sodium's {@code VertexConsumerUtils.convertOrLog}
* result. The vanilla method is an interface instanceof plus an interface
* call on a handful of alternating consumer classes, which keeps evicting
* HotSpot's per-class type-check cache; an identity compare against the last
* successful consumer skips both.
*
* Sodium-only: registered in {@code OPTIONAL_SODIUM_MIXINS}, never applied
* without Sodium.
*
* <p>Gated on the {@code micro_opts} toggle. When the toggle is off, the
* original method runs unchanged.
*/
@Mixin(targets = "net.caffeinemc.mods.sodium.client.render.vertex.VertexConsumerUtils", remap = false)
public abstract class VertexConsumerUtilsMixin {
// last consumer that passed the check; a whole model goes to one consumer, so this hits for nearly every cuboid
@Unique
private static volatile Object lovisual$lastWriter;
@WrapMethod(method = "convertOrLog")
private static VertexBufferWriter lovisual$cachedConvert(VertexConsumer consumer, Operation<VertexBufferWriter> original) {
if (consumer == lovisual$lastWriter && OptimizeToggles.microOpts()) {
return (VertexBufferWriter) consumer;
}
VertexBufferWriter writer = original.call(consumer);
if (writer == consumer) {
lovisual$lastWriter = consumer;
}
return writer;
}
}

View file

@ -0,0 +1,59 @@
package dev.loki.lovisual.mixins.optimize.gl.state;
import com.mojang.blaze3d.opengl.GlStateManager;
import dev.loki.lovisual.render.engine.optimize.OptimizeToggles;
import dev.loki.lovisual.render.engine.optimize.gl.state.GlStateCache;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
/**
* Extended GL state cache — Stage 3 "Дополнительные GL-оптимизации" item 1 in
* {@code mod/docs/optimize-layer-design.md}. Skips redundant driver calls that
* vanilla's own {@code BLEND/DEPTH/CULL/SCISSOR/TEXTURES} arrays do not cover:
* {@code _glUseProgram(int)} and {@code _glBindVertexArray(int)} reach
* {@code GL33C} every time, with no cache.
*
* <p>Gated by {@link OptimizeToggles#microOpts()} — the Stage 1 "micro_opts"
* switch already covers the TBO / RenderTypes caches, so this rides along.
*
* <p>Cache is invalidated on {@link GlStateManager#glDeleteProgram(int)} —
* the driver recycles program ids, and on {@code Optimize.onDisable} /
* resource reload via {@code GlStateCache.reset()} called from the module.
* Under Vulkan the mixin's target class is never loaded, so no injection fires.
*/
@Mixin(GlStateManager.class)
public abstract class GlStateManagerCacheMixin {
@Inject(method = "_glUseProgram", at = @At("HEAD"), cancellable = true)
private static void lovisual$skipRedundantUseProgram(int program, CallbackInfo ci) {
if (!OptimizeToggles.microOpts()) {
GlStateCache.reset();
return;
}
if (GlStateCache.programAlreadyBound(program)) {
ci.cancel();
return;
}
GlStateCache.markProgram(program);
}
@Inject(method = "_glBindVertexArray", at = @At("HEAD"), cancellable = true)
private static void lovisual$skipRedundantBindVao(int vao, CallbackInfo ci) {
if (!OptimizeToggles.microOpts()) {
GlStateCache.reset();
return;
}
if (GlStateCache.vaoAlreadyBound(vao)) {
ci.cancel();
return;
}
GlStateCache.markVao(vao);
}
@Inject(method = "glDeleteProgram", at = @At("HEAD"))
private static void lovisual$invalidateOnDeleteProgram(int program, CallbackInfo ci) {
GlStateCache.reset();
}
}

View file

@ -0,0 +1,124 @@
package dev.loki.lovisual.mixins.optimize.hud;
import dev.loki.lovisual.features.module.lifecycle.Modules;
import dev.loki.lovisual.features.module.modules.misc.optimize.Optimize;
import dev.loki.lovisual.render.engine.optimize.profile.DrawStats;
import dev.loki.lovisual.render.engine.optimize.profile.FrameBudget;
import dev.loki.lovisual.render.engine.optimize.profile.FrameProfiler;
import dev.loki.lovisual.render.engine.optimize.profile.OptimizePropertyBridge;
import dev.loki.lovisual.render.engine.optimize.OptimizeToggles;
import net.minecraft.client.gui.components.DebugScreenOverlay;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.ModifyArg;
import java.util.ArrayList;
import java.util.List;
/**
* F3 debug overlay for the Optimize layer — Stage 2 of
* {@code mod/docs/optimize-layer-design.md}.
*
* <p>Injects three groups of lines into the F3 text list, prepended before
* the existing LoVisual engine block:
* <ul>
* <li>Optimize status — which toggles are on, plus the budget mode + target FPS.</li>
* <li>Frame profiler — EMA-averaged per-section timings (entities/particles/HUD/effects/text).</li>
* <li>Property overrides — when any {@code -Dlovisual.opt.*} is set, list which ones.</li>
* </ul>
*
* <p>The hook mirrors the existing {@code hud.DebugHudMixin}'s pattern: it
* {@code ModifyArg}s the {@code extractLines} call inside
* {@code DebugScreenOverlay.extractRenderState} and replaces the text list.
* Both mixins return a new list with their own lines prepended; whichever runs
* last sees the previous one's output in its input list, so both blocks appear
* in F3.
*/
@Mixin(DebugScreenOverlay.class)
public abstract class OptimizeDebugHudMixin {
@ModifyArg(
method = "extractRenderState",
at = @At(
value = "INVOKE",
target = "Lnet/minecraft/client/gui/components/DebugScreenOverlay;extractLines(Lnet/minecraft/client/gui/GuiGraphicsExtractor;Ljava/util/List;Z)V",
ordinal = 0
),
index = 1
)
private List<String> lovisual$addOptimizeInfo(List<String> list) {
if (list == null) return list;
Optimize module = Modules.get(Optimize.class);
if (module == null || !module.isEnabled()) {
return list;
}
List<String> out = new ArrayList<>(list.size() + 16);
out.add("§cLoVisual Optimize");
out.add(String.format("toggles: %s", togglesSummary()));
out.add(String.format("budget: %s @ %d fps (scale %.2f)",
FrameBudget.mode(),
FrameBudget.targetFps(),
FrameBudget.scale()));
FrameProfiler.Snapshot snap = FrameProfiler.snapshot();
if (snap.frameMs() > 0) {
out.add(String.format("frame: %.2f ms (%.0f fps)",
snap.frameMs(),
1000.0 / Math.max(0.01, snap.frameMs())));
if (hasSectionTimings(snap)) {
out.add(String.format(" entities=%.2fms particles=%.2fms hud=%.2fms effects=%.2fms text=%.2fms",
snap.entityMs(),
snap.particleMs(),
snap.hudMs(),
snap.effectMs(),
snap.textMs()));
}
}
DrawStats.Snapshot counters = DrawStats.snapshot();
if (counters.frames() > 0) {
out.add(String.format("draws: %d, pipelines: %d, fbo binds: %d (avg/frame)",
counters.draws(),
counters.pipelines(),
counters.binds()));
if (!counters.top().isEmpty()) {
out.add(" top: " + String.join(", ", counters.top()));
}
}
if (OptimizePropertyBridge.hasOverrides()) {
out.add("props: " + OptimizePropertyBridge.lastResolved());
}
out.add("");
out.addAll(list);
return out;
}
/** Sections are only reported once something opens them — a row of zeros is noise. */
private static boolean hasSectionTimings(FrameProfiler.Snapshot snap) {
return snap.entityMs() > 0
|| snap.particleMs() > 0
|| snap.hudMs() > 0
|| snap.effectMs() > 0
|| snap.textMs() > 0;
}
private static String togglesSummary() {
StringBuilder sb = new StringBuilder();
if (OptimizeToggles.entityLod()) append(sb, "entity_lod@" + OptimizeToggles.entityLodDistance());
if (OptimizeToggles.particleLod()) append(sb, "particle_lod");
if (OptimizeToggles.spawnerCull()) append(sb, "spawner_cull@" + OptimizeToggles.spawnerDistance());
if (OptimizeToggles.spawnerTickCache()) append(sb, "spawner_tick_cache");
if (OptimizeToggles.blockEntityCache()) append(sb, "block_entity_cache");
if (OptimizeToggles.preparedTextCache()) append(sb, "prepared_text_cache");
if (OptimizeToggles.microOpts()) append(sb, "micro_opts");
return sb.length() == 0 ? "none" : sb.toString();
}
private static void append(StringBuilder out, String knob) {
if (out.length() > 0) out.append(", ");
out.append(knob);
}
}

View file

@ -0,0 +1,48 @@
package dev.loki.lovisual.mixins.optimize.particle;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
import dev.loki.lovisual.features.module.modules.misc.optimize.particle.BubbleColumnCache;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.particle.BubbleColumnUpParticle;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.material.FluidState;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
/**
* Stage 3: bubble-column fluid cache. {@code BubbleColumnUpParticle.tick}
* calls {@code level.getFluidState(pos)} once per particle per tick — but
* thousands of bubble particles share a few columns, so each block's fluid
* is looked up thousands of times. This mixin wraps the call to consult
* {@link BubbleColumnCache} first; on a miss, the original runs and the
* result is stored.
*
* The cache logic is in {@link BubbleColumnCache} so the mixin stays a thin
* wrapper and the cache is unit-testable without Minecraft types.
*
* <p>Gated on the {@code microOpts} toggle (Stage 1). When the toggle is off,
* the original call runs unchanged.
*/
@Mixin(BubbleColumnUpParticle.class)
public abstract class BubbleColumnUpParticleMixin {
@WrapOperation(
method = "tick",
at = @At(value = "INVOKE",
target = "Lnet/minecraft/client/multiplayer/ClientLevel;getFluidState(Lnet/minecraft/core/BlockPos;)Lnet/minecraft/world/level/material/FluidState;")
)
private FluidState lovisual$cachedFluid(ClientLevel level, BlockPos pos, Operation<FluidState> original) {
if (!BubbleColumnCache.enabled()) {
return original.call(level, pos);
}
long tick = level.getGameTime();
long key = pos.asLong();
FluidState fluid = BubbleColumnCache.get(key, tick);
if (fluid == null) {
fluid = original.call(level, pos);
BubbleColumnCache.put(key, fluid);
}
return fluid;
}
}

View file

@ -0,0 +1,109 @@
package dev.loki.lovisual.mixins.optimize.particle;
import dev.loki.lovisual.features.module.modules.misc.optimize.particle.camera.CameraPosition;
import dev.loki.lovisual.render.engine.optimize.OptimizeToggles;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.particle.BaseAshSmokeParticle;
import net.minecraft.client.particle.BubbleColumnUpParticle;
import net.minecraft.client.particle.CampfireSmokeParticle;
import net.minecraft.client.particle.Particle;
import net.minecraft.world.phys.Vec3;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
/**
* Stage 3: per-particle light cache + far-particle physics skip.
*
* <p>Two optimizations in one mixin:
* <ul>
* <li><b>Light cache</b> — vanilla {@code getLightCoords(partialTick)} walks
* the chunk's light section data per call, called per particle per frame.
* The value only changes on tick boundaries (light updates), so caching
* by game tick removes the walk from the hot path.</li>
* <li><b>Physics skip</b> — vanilla {@code move} does full collision against
* the world for every particle. Far particles (>16 blocks) and three
* specific always-skip subclasses ({@link BaseAshSmokeParticle},
* {@link CampfireSmokeParticle}, {@link BubbleColumnUpParticle}) skip
* the collision check by setting {@code hasPhysics=false} for the
* duration of {@code move}.</li>
* </ul>
*
* Light-cache gated on the {@code microOpts} toggle (Stage 1 wiring);
* physics-skip also gated on {@code microOpts} since both are micro-opts.
* When the toggle is off, the original code runs unchanged.
*/
@Mixin(Particle.class)
public abstract class ParticleMixin {
@Shadow
@Final
protected ClientLevel level;
@Shadow
protected boolean hasPhysics;
@Shadow
protected double x;
@Shadow
protected double y;
@Shadow
protected double z;
@Unique
private boolean lovisual$physicsBefore;
@Unique
private long lovisual$lightTick = Long.MIN_VALUE;
@Unique
private int lovisual$light;
@Inject(method = "getLightCoords", at = @At("HEAD"), cancellable = true)
private void lovisual$cachedLight(float partialTick, CallbackInfoReturnable<Integer> cir) {
if (lovisual$lightTick == level.getGameTime() && OptimizeToggles.particleLight()) {
cir.setReturnValue(lovisual$light);
}
}
@Inject(method = "getLightCoords", at = @At("RETURN"))
private void lovisual$storeLight(float partialTick, CallbackInfoReturnable<Integer> cir) {
lovisual$light = cir.getReturnValueI();
lovisual$lightTick = level.getGameTime();
}
@Inject(method = "move", at = @At("HEAD"))
private void lovisual$cheapPhysics(double dx, double dy, double dz, CallbackInfo ci) {
lovisual$physicsBefore = hasPhysics;
if (hasPhysics && OptimizeToggles.particlePhysics() && lovisual$skipCollision()) {
hasPhysics = false;
}
}
@Inject(method = "move", at = @At("RETURN"))
private void lovisual$restorePhysics(double dx, double dy, double dz, CallbackInfo ci) {
hasPhysics = lovisual$physicsBefore;
}
@Unique
private boolean lovisual$skipCollision() {
Object self = this;
if (self instanceof BaseAshSmokeParticle
|| self instanceof CampfireSmokeParticle
|| self instanceof BubbleColumnUpParticle) {
return true;
}
Vec3 cam = CameraPosition.get();
double ddx = x - cam.x;
double ddy = y - cam.y;
double ddz = z - cam.z;
return ddx * ddx + ddy * ddy + ddz * ddz > 16 * 16;
}
}

View file

@ -0,0 +1,41 @@
package dev.loki.lovisual.mixins.optimize.stats;
import dev.loki.lovisual.render.engine.optimize.profile.DrawStats;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
/**
* Counts the four places {@code GlCommandEncoder} actually issues a draw —
* {@code executeDraw}, {@code executeDraws}, {@code executeDrawIndirect} and
* {@code executeDrawMultiple} do not call each other, so exactly one of them
* sees every submission.
*
* <p>Part of Stage 3 step 1 in {@code mod/docs/optimize-layer-design.md};
* the counter is a boolean test unless F3 is open with Optimize on.
*
*/
@Mixin(targets = "com.mojang.blaze3d.opengl.GlCommandEncoder")
public abstract class GlCommandEncoderStatsMixin {
@Inject(method = "executeDraw", at = @At("HEAD"))
private void lovisual$countDraw(CallbackInfo ci) {
DrawStats.draw();
}
@Inject(method = "executeDraws", at = @At("HEAD"))
private void lovisual$countDraws(CallbackInfo ci) {
DrawStats.draw();
}
@Inject(method = "executeDrawIndirect", at = @At("HEAD"))
private void lovisual$countDrawIndirect(CallbackInfo ci) {
DrawStats.draw();
}
@Inject(method = "executeDrawMultiple", at = @At("HEAD"))
private void lovisual$countDrawMultiple(CallbackInfo ci) {
DrawStats.draw();
}
}

View file

@ -0,0 +1,30 @@
package dev.loki.lovisual.mixins.optimize.stats;
import com.mojang.blaze3d.pipeline.RenderPipeline;
import dev.loki.lovisual.render.engine.optimize.profile.DrawStats;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
/**
* Counts {@code RenderPass.setPipeline} — one per state selection, repeats
* included — and feeds the pipeline name to the per-frame top list, so F3
* shows which pipelines a frame spends its draws on. That is the input for
* the "sort draws by pipeline" idea in
* {@code mod/docs/optimize-layer-design.md}.
*
* <p>Part of Stage 3 step 1 in {@code mod/docs/optimize-layer-design.md}.
*
*/
@Mixin(targets = "com.mojang.blaze3d.opengl.GlRenderPass")
public abstract class GlRenderPassStatsMixin {
@Inject(method = "setPipeline", at = @At("HEAD"))
private void lovisual$countPipeline(RenderPipeline pipeline, CallbackInfo ci) {
if (pipeline == null || pipeline.getLocation() == null) {
return;
}
DrawStats.pipeline(pipeline.getLocation().getPath());
}
}

View file

@ -0,0 +1,33 @@
package dev.loki.lovisual.mixins.optimize.stats;
import com.mojang.blaze3d.opengl.GlStateManager;
import dev.loki.lovisual.render.engine.optimize.profile.DrawStats;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
/**
* Counts framebuffer binds that actually reach the driver: the injection sits
* on the {@code glBindFramebuffer} calls inside {@code _glBindFramebuffer}, so
* binds GlStateManager's read/write cache absorbs are not counted. A target of
* {@code GL_FRAMEBUFFER} runs both branches and is counted twice — two GL calls
* really happen.
*
* <p>Part of Stage 3 step 1 in {@code mod/docs/optimize-layer-design.md}.
*
*/
@Mixin(GlStateManager.class)
public abstract class GlStateManagerStatsMixin {
@Inject(
method = "_glBindFramebuffer",
at = @At(
value = "INVOKE",
target = "Lorg/lwjgl/opengl/GL33C;glBindFramebuffer(II)V"
)
)
private static void lovisual$countBind(int target, int framebuffer, CallbackInfo ci) {
DrawStats.bind();
}
}

View file

@ -9,20 +9,20 @@ import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import dev.loki.lovisual.features.module.lifecycle.Modules; import dev.loki.lovisual.features.module.lifecycle.Modules;
import dev.loki.lovisual.features.module.modules.visuals.optimization.FpsOptimizer; import dev.loki.lovisual.features.module.modules.misc.optimize.Optimize;
@Mixin(EntityRenderDispatcher.class) @Mixin(EntityRenderDispatcher.class)
public abstract class EntityRenderDispatcherMixin { public abstract class EntityRenderDispatcherMixin {
@Inject(method = "shouldRender(Lnet/minecraft/world/entity/Entity;Lnet/minecraft/client/renderer/culling/Frustum;DDD)Z", at = @At("HEAD"), cancellable = true) @Inject(method = "shouldRender(Lnet/minecraft/world/entity/Entity;Lnet/minecraft/client/renderer/culling/Frustum;DDD)Z", at = @At("HEAD"), cancellable = true)
private <E extends Entity> void lovisual$cullEntity(E entity, Frustum frustum, double camX, double camY, double camZ, CallbackInfoReturnable<Boolean> cir) { private <E extends Entity> void lovisual$cullEntity(E entity, Frustum frustum, double camX, double camY, double camZ, CallbackInfoReturnable<Boolean> cir) {
FpsOptimizer fpsOptimizer = Modules.get(FpsOptimizer.class); Optimize optimize = Modules.get(Optimize.class);
if (fpsOptimizer == null || !fpsOptimizer.isEntityCullingEnabled()) return; if (optimize == null || !optimize.isEntityCullingEnabled()) return;
Minecraft mc = Minecraft.getInstance(); Minecraft mc = Minecraft.getInstance();
if (entity == mc.player) return; if (entity == mc.player) return;
double maxDistance = fpsOptimizer.entityCullDistance(); double maxDistance = optimize.entityCullDistance();
if (entity.distanceToSqr(camX, camY, camZ) > maxDistance * maxDistance) { if (entity.distanceToSqr(camX, camY, camZ) > maxDistance * maxDistance) {
cir.setReturnValue(false); cir.setReturnValue(false);
return; return;

View file

@ -2,10 +2,16 @@ package dev.loki.lovisual.mixins.render.item;
import com.llamalad7.mixinextras.injector.ModifyExpressionValue; import com.llamalad7.mixinextras.injector.ModifyExpressionValue;
import com.llamalad7.mixinextras.injector.ModifyReturnValue; import com.llamalad7.mixinextras.injector.ModifyReturnValue;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
import com.llamalad7.mixinextras.sugar.Local; import com.llamalad7.mixinextras.sugar.Local;
import dev.loki.lovisual.render.engine.optimize.entity.ItemLod;
import java.util.List;
import net.minecraft.client.renderer.feature.ItemFeatureRenderer; import net.minecraft.client.renderer.feature.ItemFeatureRenderer;
import net.minecraft.client.renderer.rendertype.RenderType; import net.minecraft.client.renderer.rendertype.RenderType;
import net.minecraft.client.resources.model.geometry.BakedQuad; import net.minecraft.client.resources.model.geometry.BakedQuad;
import net.minecraft.world.item.ItemDisplayContext;
import org.joml.Matrix4f;
import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.At;
@ -56,4 +62,20 @@ public abstract class ItemFeatureRendererMixin {
// corrupt the following world translucent composite, so item layers keep their own type. // corrupt the following world translucent composite, so item layers keep their own type.
return original; return original;
} }
@WrapOperation(
method = {"prepareMainSubmit", "prepareOutlineSubmit", "prepareFoilSubmit"},
at = @At(value = "INVOKE",
target = "Lnet/minecraft/client/renderer/feature/ItemFeatureRenderer$Submit;quads()Ljava/util/List;")
)
private List<BakedQuad> lovisual$itemLod(ItemFeatureRenderer.Submit submit, Operation<List<BakedQuad>> original) {
List<BakedQuad> quads = original.call(submit);
ItemDisplayContext context = submit.displayContext();
if (context.firstPerson() || context == ItemDisplayContext.GUI || !ItemLod.enabled()) {
return quads;
}
Matrix4f m = submit.pose().pose();
float dSq = m.m30() * m.m30() + m.m31() * m.m31() + m.m32() * m.m32();
return dSq > ItemLod.distanceSq() ? ItemLod.flat(quads) : quads;
}
} }

View file

@ -0,0 +1,28 @@
package dev.loki.lovisual.mixins.render.item.bounds;
import java.util.function.Supplier;
import net.minecraft.client.renderer.item.ItemStackRenderState;
import net.minecraft.client.resources.model.cuboid.ItemTransform;
import org.joml.Matrix4f;
import org.joml.Vector3fc;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Accessor;
/**
* Stage 3 step 5: exposes the layer internals {@link ItemStackRenderStateMixin}
* keys the shared {@code ItemBounds} cache on — the extents supplier identity,
* the item transform and the local matrix whose identity bit short-circuits
* the cache.
*/
@Mixin(ItemStackRenderState.LayerRenderState.class)
public interface ItemLayerAccessor {
@Accessor("extents")
Supplier<Vector3fc[]> lovisual$extents();
@Accessor("itemTransform")
ItemTransform lovisual$itemTransform();
@Accessor("localTransform")
Matrix4f lovisual$localTransform();
}

View file

@ -0,0 +1,39 @@
package dev.loki.lovisual.mixins.render.item.bounds;
import com.llamalad7.mixinextras.injector.wrapmethod.WrapMethod;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import dev.loki.lovisual.render.engine.optimize.entity.ItemBounds;
import net.minecraft.client.renderer.item.ItemStackRenderState;
import net.minecraft.world.phys.AABB;
import org.joml.Matrix4fc;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
/**
* Stage 3 step 5: single-layer item model bounds served from
* {@link ItemBounds} instead of recomputed every frame. The vanilla path
* walks the layer's extents supplier; the cache key is that supplier's
* identity, which is stable per baked model. Multi-layer items and items
* with a non-identity local transform keep the vanilla computation.
*/
@Mixin(ItemStackRenderState.class)
public abstract class ItemStackRenderStateMixin {
@Shadow
private int activeLayerCount;
@Shadow
private ItemStackRenderState.LayerRenderState[] layers;
@WrapMethod(method = "getModelBoundingBox")
private AABB lovisual$sharedBounds(Operation<AABB> original) {
if (!ItemBounds.enabled() || activeLayerCount != 1) {
return original.call();
}
ItemLayerAccessor layer = (ItemLayerAccessor) layers[0];
if ((layer.lovisual$localTransform().properties() & Matrix4fc.PROPERTY_IDENTITY) == 0) {
return original.call();
}
return ItemBounds.get(layer.lovisual$extents(), layer.lovisual$itemTransform(), original::call);
}
}

View file

@ -8,7 +8,7 @@ import org.spongepowered.asm.mixin.injection.Coerce;
/** /**
* Vanilla bug: FireworkParticles$Starter.createParticle assumes ParticleEngine.createParticle never returns null. * Vanilla bug: FireworkParticles$Starter.createParticle assumes ParticleEngine.createParticle never returns null.
* Our ParticleManagerMixin returns null when a ParticleSpawnEvent is cancelled (e.g. FpsOptimizer.disable_particles). * Our ParticleManagerMixin returns null when a ParticleSpawnEvent is cancelled (e.g. Optimize.no_particles).
* This causes NPE: sparkParticle is null -> setTrail() crashes. * This causes NPE: sparkParticle is null -> setTrail() crashes.
* Fix: guard every SparkParticle setter to be null-safe. SparkParticle is a private inner class, so we use Object * Fix: guard every SparkParticle setter to be null-safe. SparkParticle is a private inner class, so we use Object
* with @Coerce to avoid InvalidInjectionException (expected SparkParticle vs Object). * with @Coerce to avoid InvalidInjectionException (expected SparkParticle vs Object).

View file

@ -35,6 +35,7 @@ import dev.loki.lovisual.features.module.modules.player.interact.NoDelay;
import dev.loki.lovisual.features.module.modules.player.interact.NoInteract; import dev.loki.lovisual.features.module.modules.player.interact.NoInteract;
import dev.loki.lovisual.features.module.modules.visuals.camera.Freecam; import dev.loki.lovisual.features.module.modules.visuals.camera.Freecam;
import dev.loki.lovisual.features.relations.StaffTracker; import dev.loki.lovisual.features.relations.StaffTracker;
import dev.loki.lovisual.render.engine.optimize.entity.AnimFreeze;
import dev.loki.lovisual.render.helpers.util.TickDelta; import dev.loki.lovisual.render.helpers.util.TickDelta;
import dev.loki.lovisual.util.combat.tracking.AntiBotTracker; import dev.loki.lovisual.util.combat.tracking.AntiBotTracker;
import dev.loki.lovisual.util.session.SessionChanger; import dev.loki.lovisual.util.session.SessionChanger;
@ -257,6 +258,11 @@ public class MinecraftMixin implements MinecraftGameConfigHolder {
AntiBotTracker.INSTANCE.reset(); AntiBotTracker.INSTANCE.reset();
} }
@Inject(method = "renderFrame", at = @At("HEAD"))
private void lovisual$animFreezeFrame(boolean tick, CallbackInfo ci) {
AnimFreeze.frame++;
}
@Inject( @Inject(
method = "renderFrame", method = "renderFrame",
at = @At( at = @At(

View file

@ -0,0 +1,74 @@
/*
* Ported/adapted from Spatial GUI (https://github.com/tastytrash/Spatial-GUI), MIT License.
* Copyright (c) tastytrash and Spatial GUI contributors.
*
* This file is part of LoVisual and is distributed under LoVisual's own GPLv3 license terms
* for the modifications made here (see mod/LICENSE and mod/THIRD_PARTY_NOTICES.md); the MIT-licensed
* portions ported from Spatial GUI remain available under the MIT terms above.
*/
package dev.loki.lovisual.mixins.render.spatialgui;
import dev.loki.lovisual.features.module.modules.visuals.spatialgui.SpatialGui;
import dev.loki.lovisual.render.spatialgui.SpatialGuiCapture;
import dev.loki.lovisual.util.logging.DebugLog;
import net.minecraft.client.DeltaTracker;
import net.minecraft.client.gui.render.GuiRenderer;
import net.minecraft.client.renderer.GameRenderer;
import net.minecraft.client.renderer.state.WindowRenderState;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
/**
* Adapted from Spatial-GUI's {@code GameRendererMixin}: right before the main GUI pass the capture texture is
* (re)sized to the frame's window state and cleared to transparent, and at the end of the frame the isolated
* screen renderer built by {@link SpatialGuiCapture} runs its own prepare/draw cycle so the open screen lands
* in the capture texture while the flat overlay stays absent.
*/
@Mixin(GameRenderer.class)
public abstract class GameRendererSpatialGuiMixin {
@Inject(method = "render", at = @At(value = "INVOKE",
target = "Lnet/minecraft/client/gui/render/GuiRenderer;render()V"))
private void lovisual$prepareSpatialCapture(DeltaTracker deltaTracker, boolean renderLevel, CallbackInfo ci) {
SpatialGui module = SpatialGui.getInstance();
if (module == null || !module.isCapturing()) {
DebugLog.renderThreadOnChange("sg.prepare", "notCapturing",
"[SpatialGui] prepare skipped: not capturing");
return;
}
WindowRenderState windowState = ((GameRenderer) (Object) this).gameRenderState().windowRenderState;
if (windowState == null || windowState.width <= 0 || windowState.height <= 0) {
DebugLog.renderThreadOnChange("sg.prepare", "badWindowState",
"[SpatialGui] prepare skipped: windowState=%s", String.valueOf(windowState));
return;
}
SpatialGuiCapture capture = SpatialGuiCapture.get();
capture.ensure(windowState.width, windowState.height);
capture.clearTransparent();
DebugLog.renderThreadOnChange("sg.prepare", windowState.width + "x" + windowState.height,
"[SpatialGui] capture prepared and cleared %dx%d", windowState.width, windowState.height);
}
@Inject(method = "render", at = @At("TAIL"))
private void lovisual$renderIsolatedSpatialScreen(DeltaTracker deltaTracker, boolean renderLevel, CallbackInfo ci) {
SpatialGui module = SpatialGui.getInstance();
if (module == null || !module.isCapturing()) {
DebugLog.renderThreadOnChange("sg.tail", "notCapturing",
"[SpatialGui] isolated TAIL skipped: not capturing");
return;
}
if (!SpatialGuiCapture.get().isReady()) {
DebugLog.renderThreadOnChange("sg.tail", "notReady",
"[SpatialGui] isolated TAIL skipped: capture not ready");
return;
}
DebugLog.renderThreadOnChange("sg.tail", "run",
"[SpatialGui] isolated render frame");
SpatialGuiCapture.get().renderIsolatedFrame();
}
}

View file

@ -8,92 +8,38 @@
*/ */
package dev.loki.lovisual.mixins.render.spatialgui; package dev.loki.lovisual.mixins.render.spatialgui;
import com.mojang.blaze3d.ProjectionType;
import com.mojang.blaze3d.buffers.GpuBufferSlice;
import com.mojang.blaze3d.pipeline.RenderTarget; import com.mojang.blaze3d.pipeline.RenderTarget;
import com.mojang.blaze3d.systems.RenderSystem;
import dev.loki.lovisual.features.module.modules.visuals.spatialgui.SpatialGui; import dev.loki.lovisual.features.module.modules.visuals.spatialgui.SpatialGui;
import dev.loki.lovisual.render.spatialgui.SpatialGuiCapture; import dev.loki.lovisual.render.spatialgui.SpatialGuiCapture;
import net.minecraft.client.Minecraft; import dev.loki.lovisual.util.logging.DebugLog;
import net.minecraft.client.gui.render.GuiRenderer; import net.minecraft.client.gui.render.GuiRenderer;
import net.minecraft.client.renderer.Projection;
import net.minecraft.client.renderer.ProjectionMatrixBuffer;
import net.minecraft.client.renderer.state.WindowRenderState;
import org.joml.Matrix4f;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.ModifyArg;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import java.util.List;
import java.util.function.Supplier;
/** /**
* Adapted from Spatial-GUI's {@code ScreenExtractor}/{@code TextureTargetManager}: on this Minecraft version the * Adapted from Spatial-GUI's {@code GuiRendererMixin}: every {@code draw()} executes its prepared draw list
* whole 2D GUI pass is a deferred draw list executed once per frame by {@link GuiRenderer#draw()} against an * through {@code executeDrawRange(label, target, ...)} — when the instance is the isolated screen renderer
* explicit {@link RenderTarget}. Redirecting the currently open screen into a 3D plane therefore only requires * built by {@link SpatialGuiCapture} while SpatialGui is capturing, the target argument is swapped for the
* pointing that one draw call at {@link SpatialGuiCapture}'s off-screen target instead of the main render * off-screen capture texture. The vanilla main GuiRenderer (HUD) keeps its normal framebuffer, and the flat
* target, and cancelling the vanilla draw so nothing shows up as a flat overlay. * screen overlay is naturally absent because the screen was extracted into the isolated state instead.
* <p>
* The vertex data itself is prepared and uploaded earlier in {@code GuiRenderer.render()} (which this mixin does
* not touch), so this only ever affects where the already-built draw list is executed to.
*/ */
@Mixin(value = GuiRenderer.class, priority = 900) @Mixin(GuiRenderer.class)
public abstract class GuiRendererCaptureMixin { public abstract class GuiRendererCaptureMixin {
@Shadow @ModifyArg(
@Final method = "draw",
private List<?> draws; at = @At(value = "INVOKE",
target = "Lnet/minecraft/client/gui/render/GuiRenderer;executeDrawRange(Ljava/util/function/Supplier;Lcom/mojang/blaze3d/pipeline/RenderTarget;Lcom/mojang/blaze3d/buffers/GpuBufferSlice;II)V"),
@Shadow index = 1)
private int firstDrawIndexAfterBlur; private RenderTarget lovisual$redirectSpatialCapture(RenderTarget original) {
@Shadow
@Final
private Projection guiProjection;
@Shadow
@Final
private ProjectionMatrixBuffer guiProjectionMatrixBuffer;
@Shadow
private void executeDrawRange(Supplier<String> label, RenderTarget target, GpuBufferSlice transform, int startIndex, int endIndex) {
throw new AssertionError();
}
@Inject(method = "draw", at = @At("HEAD"), cancellable = true)
private void lovisual$captureToSpatialPlane(CallbackInfo ci) {
if (draws == null || draws.isEmpty()) return;
SpatialGui module = SpatialGui.getInstance(); SpatialGui module = SpatialGui.getInstance();
if (module == null || !module.isCapturing()) return; if (module == null || !module.isCapturing()) return original;
Minecraft mc = Minecraft.getInstance();
if (mc == null || mc.gameRenderer == null) return;
WindowRenderState windowState = mc.gameRenderer.gameRenderState().windowRenderState;
if (windowState == null || windowState.guiScale <= 0) return;
SpatialGuiCapture capture = SpatialGuiCapture.get(); SpatialGuiCapture capture = SpatialGuiCapture.get();
RenderTarget target = capture.ensure(windowState.width, windowState.height); if ((Object) this != capture.screenGuiRenderer()) return original;
capture.clearTransparent(); RenderTarget redirect = capture.target();
if (redirect == null) return original;
guiProjection.setupOrtho(1000.0F, 11000.0F, DebugLog.renderThreadOnce("sg.swap", "[SpatialGui] draw target swapped to capture texture");
(float) windowState.width / windowState.guiScale, (float) windowState.height / windowState.guiScale, true); return redirect;
RenderSystem.setProjectionMatrix(guiProjectionMatrixBuffer.getBuffer(guiProjection), ProjectionType.ORTHOGRAPHIC);
GpuBufferSlice transform = RenderSystem.getDynamicUniforms().writeTransform(new Matrix4f().setTranslation(0.0F, 0.0F, -11000.0F));
int splitIndex = Math.min(firstDrawIndexAfterBlur, draws.size());
if (splitIndex > 0) {
executeDrawRange(() -> "spatial gui before blur", target, transform, 0, splitIndex);
}
if (draws.size() > firstDrawIndexAfterBlur) {
RenderSystem.getDevice().createCommandEncoder().clearDepthTexture(target.getDepthTexture(), 0.0D);
mc.gameRenderer.processBlurEffect();
executeDrawRange(() -> "spatial gui after blur", target, transform, firstDrawIndexAfterBlur, draws.size());
}
ci.cancel();
} }
} }

View file

@ -0,0 +1,43 @@
/*
* Ported/adapted from Spatial GUI (https://github.com/tastytrash/Spatial-GUI), MIT License.
* Copyright (c) tastytrash and Spatial GUI contributors.
*
* This file is part of LoVisual and is distributed under LoVisual's own GPLv3 license terms
* for the modifications made here (see mod/LICENSE and mod/THIRD_PARTY_NOTICES.md); the MIT-licensed
* portions ported from Spatial GUI remain available under the MIT terms above.
*/
package dev.loki.lovisual.mixins.render.spatialgui;
import dev.loki.lovisual.features.module.modules.visuals.spatialgui.SpatialGui;
import dev.loki.lovisual.render.spatialgui.SpatialGuiCapture;
import dev.loki.lovisual.util.logging.DebugLog;
import net.minecraft.client.gui.GuiGraphicsExtractor;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.gui.screens.Screen;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
/**
* Adapted from Spatial-GUI's {@code GuiMixin}: while SpatialGui is capturing, the open screen's extraction
* is diverted from the vanilla main GUI render state into {@link SpatialGuiCapture}'s isolated state, so the
* main pass draws only the HUD and the screen content lands exclusively in the capture texture for the 3D
* plane. Mouse coordinates arrive already reprojected onto the plane via the MouseHandler mixin.
*/
@Mixin(Gui.class)
public abstract class GuiSpatialExtractMixin {
@Redirect(method = "extractRenderState", at = @At(value = "INVOKE",
target = "Lnet/minecraft/client/gui/screens/Screen;extractRenderStateWithTooltipAndSubtitles(Lnet/minecraft/client/gui/GuiGraphicsExtractor;IIF)V"))
private void lovisual$isolateScreenExtraction(Screen screen, GuiGraphicsExtractor graphics, int mouseX, int mouseY, float partialTick) {
SpatialGui module = SpatialGui.getInstance();
boolean capturing = module != null && module.isCapturing();
DebugLog.renderThreadOnChange("sg.extract", capturing,
"[SpatialGui] screen extraction divert=%b screen=%s", capturing, screen.getClass().getSimpleName());
if (capturing) {
SpatialGuiCapture.get().extractScreen(screen, mouseX, mouseY, partialTick);
} else {
screen.extractRenderStateWithTooltipAndSubtitles(graphics, mouseX, mouseY, partialTick);
}
}
}

View file

@ -14,6 +14,7 @@ import dev.loki.lovisual.render.engine.core.policy.LightPolicy;
import dev.loki.lovisual.render.engine.core.policy.fog.VanillaWorldFogProvider; import dev.loki.lovisual.render.engine.core.policy.fog.VanillaWorldFogProvider;
import dev.loki.lovisual.render.engine.depth.WorldSceneDepth; import dev.loki.lovisual.render.engine.depth.WorldSceneDepth;
import dev.loki.lovisual.render.engine.framegraph.LoVisualFrameGraph; import dev.loki.lovisual.render.engine.framegraph.LoVisualFrameGraph;
import dev.loki.lovisual.render.engine.optimize.profile.FrameProfiler;
import dev.loki.lovisual.render.engine.profiler.frame.FrameStutterProfiler; import dev.loki.lovisual.render.engine.profiler.frame.FrameStutterProfiler;
import dev.loki.lovisual.render.engine.profiler.frame.RenderFrameProfiler; import dev.loki.lovisual.render.engine.profiler.frame.RenderFrameProfiler;
import dev.loki.lovisual.render.engine.rhi.resource.LoVisualRhi; import dev.loki.lovisual.render.engine.rhi.resource.LoVisualRhi;
@ -220,6 +221,7 @@ public enum LoVisualRenderSystem {
TextRenderSystem.beginFrame(); TextRenderSystem.beginFrame();
sodiumFrame = SODIUM.beginFrame(); sodiumFrame = SODIUM.beginFrame();
RenderFrameProfiler.beginFrame(frameId); RenderFrameProfiler.beginFrame(frameId);
FrameProfiler.beginFrame();
frameOpen = true; frameOpen = true;
submissionEnded = false; submissionEnded = false;
lifecycle = FrameLifecycle.RECORDING; lifecycle = FrameLifecycle.RECORDING;
@ -319,6 +321,7 @@ public enum LoVisualRenderSystem {
FrameStutterProfiler.onFramePresented(rhiStatsSnapshot(), uniformStatsSnapshot(), resourceStatsSnapshot()); FrameStutterProfiler.onFramePresented(rhiStatsSnapshot(), uniformStatsSnapshot(), resourceStatsSnapshot());
} }
RenderFrameProfiler.endFrame(null, null); RenderFrameProfiler.endFrame(null, null);
FrameProfiler.endFrame();
lifecycle = FrameLifecycle.PRESENTED; lifecycle = FrameLifecycle.PRESENTED;
} finally { } finally {
currentContext = null; currentContext = null;

View file

@ -0,0 +1,82 @@
package dev.loki.lovisual.render.engine.optimize;
/**
* Resolved per-frame toggle snapshot for the Stage 1 optimization helpers
* (LOD distances, caches, micro-opts). Mirrors {@link OptimizeState}'s shape:
* an enum-utility holder with volatile fields, written by the {@code Optimize}
* module on enable/disable and once per frame, read by render code (helpers,
* future mixins) — never by the module class itself.
*
* <p>Stage 1 of {@code mod/docs/optimize-layer-design.md}: backend-independent
* logic plus the toggle snapshot. Lazy clear and the TBO cache ride
* {@link #microOpts()}; FBO share (Stage 3 step 2) has its own
* {@link #fboShare()} flag. GL/Vulkan-specific helpers that need their own
* holder (skin atlas, HUD cache) arrive in later Stage 3 steps alongside the
* mixins that consume them.
*
* <p>All module settings are resolved into volatile primitive fields once per frame.
* System-property overrides are not supported here (the {@code Optimize} module's
* {@code bool()}/{@code num()} settings are the single source of truth); they can be
* layered back via {@code -Dlovisual.opt.*} in Stage 2 per the design doc.
*/
public enum OptimizeToggles {
;
private static volatile boolean entityLod;
private static volatile int entityLodDistance;
private static volatile boolean particleLod;
private static volatile boolean particleLight;
private static volatile boolean particlePhysics;
private static volatile boolean spawnerCull;
private static volatile int spawnerDistance;
private static volatile boolean spawnerTickCache;
private static volatile boolean blockEntityCache;
private static volatile boolean preparedTextCache;
private static volatile boolean microOpts;
private static volatile boolean fboShare;
public static boolean entityLod() { return entityLod; }
public static int entityLodDistance() { return entityLodDistance; }
public static boolean particleLod() { return particleLod; }
public static boolean particleLight() { return particleLight; }
public static boolean particlePhysics() { return particlePhysics; }
public static boolean spawnerCull() { return spawnerCull; }
public static int spawnerDistance() { return spawnerDistance; }
public static boolean spawnerTickCache() { return spawnerTickCache; }
public static boolean blockEntityCache() { return blockEntityCache; }
public static boolean preparedTextCache() { return preparedTextCache; }
public static boolean microOpts() { return microOpts; }
public static boolean fboShare() { return fboShare; }
/**
* Push a full snapshot. Called by {@code Optimize.onEnable/onDisable/onFrame}
* with the resolved {@code (isEnabled() && knob.get())} for every toggle.
*/
public static void apply(
boolean entityLod, int entityLodDistance,
boolean particleLod, boolean particleLight, boolean particlePhysics,
boolean spawnerCull, int spawnerDistance,
boolean spawnerTickCache,
boolean blockEntityCache,
boolean preparedTextCache,
boolean microOpts,
boolean fboShare) {
OptimizeToggles.entityLod = entityLod;
OptimizeToggles.entityLodDistance = entityLodDistance;
OptimizeToggles.particleLod = particleLod;
OptimizeToggles.particleLight = particleLight;
OptimizeToggles.particlePhysics = particlePhysics;
OptimizeToggles.spawnerCull = spawnerCull;
OptimizeToggles.spawnerDistance = spawnerDistance;
OptimizeToggles.spawnerTickCache = spawnerTickCache;
OptimizeToggles.blockEntityCache = blockEntityCache;
OptimizeToggles.preparedTextCache = preparedTextCache;
OptimizeToggles.microOpts = microOpts;
OptimizeToggles.fboShare = fboShare;
}
/** Reset to "nothing on" — used by {@code Optimize.onDisable}. */
public static void reset() {
apply(false, 0, false, false, false, false, 0, false, false, false, false, false);
}
}

View file

@ -0,0 +1,208 @@
package dev.loki.lovisual.render.engine.optimize.entity;
import com.mojang.blaze3d.vertex.BufferBuilder;
import com.mojang.blaze3d.vertex.ByteBufferBuilder;
import com.mojang.blaze3d.vertex.DefaultVertexFormat;
import com.mojang.blaze3d.vertex.MeshData;
import com.mojang.blaze3d.vertex.VertexConsumer;
import com.mojang.blaze3d.vertex.VertexFormat;
import dev.loki.lovisual.features.module.modules.misc.optimize.entity.StateEntity;
import dev.loki.lovisual.render.engine.optimize.gl.RawVertices;
import net.minecraft.client.model.Model;
import net.minecraft.client.renderer.entity.state.EntityRenderState;
import net.minecraft.client.renderer.rendertype.RenderType;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.world.entity.Entity;
import org.joml.Matrix4f;
import org.lwjgl.system.MemoryStack;
import org.lwjgl.system.MemoryUtil;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
/**
* Stage 3 step 4: far-entity animation freeze. A distant entity's model
* vertices are captured once per game tick and, on the frames in between,
* replayed as raw vertex copies shifted to the entity's current position —
* the model is no longer rebuilt (and re-animated) every frame, only moved.
*
* <p>Distance gate: farther than {@link #distance()} blocks from the camera
* (squared comparison against the pose translation). Close entities render
* through the vanilla path untouched.
*
* <p>The capture is keyed per {@code (model, renderType, sprite)} triplet per
* entity — one entity may submit the same model several times per frame
* (body + armor layers); the n-th submission reuses the n-th capture. Parts
* that are rebuilt every frame elsewhere (e.g. armor trim shimmer) are NOT
* replayed — callers decide via {@link #freezes}, so those parts stay in sync
* with the frozen rest instead of drifting.
*
* <p>Requires the raw-vertex push path ({@code RawVertices} + Sodium or the
* vanilla {@code RawBuffer} mixin); when neither consumer accepts raw bytes,
* {@link #render} returns {@code false} and vanilla runs.
*
* <p>Toggle: {@link #configure(boolean, int)}, pushed by the Optimize module
* once per frame. The frame counter advances from the {@code renderFrame}
* hook in {@code MinecraftMixin}.
*/
public enum AnimFreeze {
;
/** Advances once per rendered frame; captures are reused within one frame. */
public static volatile long frame;
private static final ByteBufferBuilder SCRATCH = new ByteBufferBuilder(16384);
private static ByteBuffer emitBuffer = MemoryUtil.memAlloc(16384);
private static volatile boolean enabled;
private static volatile int distance = 16;
/** Push a full snapshot — called by the Optimize module once per frame. */
public static void configure(boolean enable, int distanceBlocks) {
enabled = enable;
distance = distanceBlocks;
}
/** Reset to "off" — used by {@code Optimize.onDisable}. */
public static void reset() {
configure(false, 0);
}
public static boolean enabled() {
return enabled;
}
public static int distance() {
return distance;
}
/**
* True when this (state, pose) pair belongs to a far entity whose parts
* must all replay the frozen capture — parts built every frame elsewhere
* consult this so they don't drift off the frozen rest.
*/
public static boolean freezes(Object state, Matrix4f pose) {
if (!enabled || !(state instanceof EntityRenderState s)
|| ((StateEntity) s).lovisual$entity() == null) {
return false;
}
float d = distance;
return beyondDistance(pose.m30(), pose.m31(), pose.m32(), d);
}
/**
* Capture-once-per-tick / replay-in-between for one model submission.
*
* @return {@code false} when not frozen (caller renders as usual)
*/
public static boolean render(Entity entity, Model<?> model, RenderType type, TextureAtlasSprite sprite,
Matrix4f pose, VertexConsumer target, Consumer<VertexConsumer> draw) {
float x = pose.m30(), y = pose.m31(), z = pose.m32();
float d = distance;
if (!enabled || !beyondDistance(x, y, z, d) || !RawVertices.accepts(target, type.format())) {
return false;
}
AnimHolder owner = (AnimHolder) entity;
Holder holder = owner.lovisual$anim();
if (holder == null) {
holder = new Holder();
owner.lovisual$anim(holder);
}
Capture capture = find(holder, model, type, sprite);
long tick = entity.level().getGameTime();
if (capture.tick != tick) {
BufferBuilder builder = new BufferBuilder(SCRATCH, type.primitiveTopology(), type.format());
draw.accept(sprite == null ? builder : sprite.wrap(builder));
capture.count = 0;
try (MeshData mesh = builder.build()) {
if (mesh != null) {
ByteBuffer src = mesh.vertexBuffer();
int bytes = src.remaining();
if (capture.data == null || capture.data.capacity() < bytes) {
capture.data = ByteBuffer.allocateDirect(bytes * 2);
}
MemoryUtil.memCopy(MemoryUtil.memAddress(src), MemoryUtil.memAddress0(capture.data), bytes);
capture.count = mesh.drawState().vertexCount();
}
}
capture.tick = tick;
capture.x = x;
capture.y = y;
capture.z = z;
}
if (capture.count > 0) {
emit(capture, type.format(), x - capture.x, y - capture.y, z - capture.z, target);
}
return true;
}
/** Squared distance from the origin — shared by {@link #freezes} and {@link #render}. */
static boolean beyondDistance(float x, float y, float z, float dist) {
return x * x + y * y + z * z > dist * dist;
}
/** Per-entity bag of captures. */
public static final class Holder {
final List<Capture> captures = new ArrayList<>(4);
Holder() {
}
}
static final class Capture {
Object model;
RenderType type;
TextureAtlasSprite sprite;
int ordinal;
long usedFrame = -1;
long tick = Long.MIN_VALUE;
ByteBuffer data;
int count;
float x, y, z;
}
/** The same model may be submitted several times per entity; the n-th call this frame reuses the n-th capture. */
private static Capture find(Holder holder, Object model, RenderType type, TextureAtlasSprite sprite) {
int ordinal = 0;
for (Capture c : holder.captures) {
if (c.model == model && c.type == type && c.sprite == sprite && c.usedFrame == frame) {
ordinal++;
}
}
for (Capture c : holder.captures) {
if (c.model == model && c.type == type && c.sprite == sprite && c.ordinal == ordinal) {
c.usedFrame = frame;
return c;
}
}
Capture c = new Capture();
c.model = model;
c.type = type;
c.sprite = sprite;
c.ordinal = ordinal;
c.usedFrame = frame;
holder.captures.add(c);
return c;
}
private static void emit(Capture capture, VertexFormat format, float dx, float dy, float dz, VertexConsumer target) {
int stride = format.getVertexSize();
int pos = format.getElement(DefaultVertexFormat.POSITION_SEMANTIC_NAME).offset();
int size = capture.count * stride;
if (emitBuffer.capacity() < size) {
emitBuffer = MemoryUtil.memRealloc(emitBuffer, size * 2);
}
long dst = MemoryUtil.memAddress0(emitBuffer);
MemoryUtil.memCopy(MemoryUtil.memAddress0(capture.data), dst, size);
for (long v = dst + pos, end = dst + size; v < end; v += stride) {
MemoryUtil.memPutFloat(v, MemoryUtil.memGetFloat(v) + dx);
MemoryUtil.memPutFloat(v + 4, MemoryUtil.memGetFloat(v + 4) + dy);
MemoryUtil.memPutFloat(v + 8, MemoryUtil.memGetFloat(v + 8) + dz);
}
try (MemoryStack stack = MemoryStack.stackPush()) {
RawVertices.push(target, stack, dst, capture.count, format);
}
}
}

View file

@ -0,0 +1,14 @@
package dev.loki.lovisual.render.engine.optimize.entity;
/**
* Mixin-contract: per-entity storage for frozen animation captures
* ({@link AnimFreeze.Holder}). Implemented on {@code Entity} by
* {@code EntityAnimHolderMixin}; render code reaches it through the
* {@code EntityRenderState} back-reference ({@code StateEntity}).
*/
public interface AnimHolder {
AnimFreeze.Holder lovisual$anim();
void lovisual$anim(AnimFreeze.Holder holder);
}

View file

@ -0,0 +1,52 @@
package dev.loki.lovisual.render.engine.optimize.entity;
import java.util.IdentityHashMap;
import java.util.Map;
import java.util.function.Supplier;
import net.minecraft.client.resources.model.cuboid.ItemTransform;
import net.minecraft.world.phys.AABB;
import org.joml.Vector3fc;
/**
* Stage 3 step 5: shared model bounds for single-layer items. Render states
* are rebuilt every frame, so a cache stored on the state itself dies with
* it; the extents supplier identity is stable per baked model and works as
* a long-lived key here.
*/
public enum ItemBounds {
;
private static final Map<Supplier<Vector3fc[]>, Entry> BOUNDS = new IdentityHashMap<>();
private static volatile boolean enabled;
public static void configure(boolean on) {
enabled = on;
}
public static void reset() {
enabled = false;
BOUNDS.clear();
}
public static boolean enabled() {
return enabled;
}
public static AABB get(Supplier<Vector3fc[]> extents, ItemTransform transform, Supplier<AABB> compute) {
Entry e = BOUNDS.get(extents);
if (e != null && e.transform() == transform) {
return e.bounds();
}
AABB bounds = compute.get();
// wholesale clear instead of LRU; models only change on resource reload
if (BOUNDS.size() > 4096) {
BOUNDS.clear();
}
BOUNDS.put(extents, new Entry(transform, bounds));
return bounds;
}
private record Entry(ItemTransform transform, AABB bounds) {
}
}

View file

@ -0,0 +1,91 @@
package dev.loki.lovisual.render.engine.optimize.entity;
import com.google.common.collect.MapMaker;
import java.util.List;
import java.util.Map;
import net.minecraft.client.resources.model.geometry.BakedQuad;
import net.minecraft.core.Direction;
import org.joml.Vector3fc;
/**
* Stage 3 step 5: far-item level of detail. Distant flat items (generated
* item models with a few large Z faces plus thin edge strips) drop their
* side geometry — at 8+ blocks the two big faces read the same on screen.
*
* <p>The quad list handed to the item renderer is a reused per-render-state
* buffer, so the flat-list cache is keyed by the model's first quad with
* weak keys; a model rebuild invalidates the entry for free.
*/
public enum ItemLod {
;
private static final float EDGE = 1f / 16f + 1e-4f;
private static final Map<BakedQuad, Flat> FLAT = new MapMaker().weakKeys().makeMap();
private static volatile boolean enabled;
private static volatile float distanceSq;
public static void configure(boolean on, int distance) {
enabled = on;
distanceSq = (float) distance * (float) distance;
}
public static void reset() {
enabled = false;
distanceSq = 0f;
FLAT.clear();
}
public static boolean enabled() {
return enabled;
}
public static float distanceSq() {
return distanceSq;
}
/**
* Returns the model's Z faces only when the whole model is flat (every
* quad is an Z-axis face or thinner than 1/16 block) and has at least
* eight quads; anything else is returned unchanged.
*/
public static List<BakedQuad> flat(List<BakedQuad> quads) {
if (quads.isEmpty()) {
return quads;
}
Flat cached = FLAT.get(quads.getFirst());
if (cached == null || cached.sourceSize() != quads.size()) {
cached = new Flat(quads.size(), compute(quads));
FLAT.put(quads.getFirst(), cached);
}
return cached.quads() == null ? quads : cached.quads();
}
private record Flat(int sourceSize, List<BakedQuad> quads) {
}
private static List<BakedQuad> compute(List<BakedQuad> quads) {
if (quads.size() < 8) {
return null;
}
for (BakedQuad q : quads) {
if (q.direction().getAxis() != Direction.Axis.Z && !thin(q)) {
return null;
}
}
List<BakedQuad> faces = List.copyOf(
quads.stream().filter(q -> q.direction().getAxis() == Direction.Axis.Z).toList());
return faces.isEmpty() ? null : faces;
}
private static boolean thin(BakedQuad q) {
float minZ = Float.MAX_VALUE;
float maxZ = -Float.MAX_VALUE;
for (int i = 0; i < 4; i++) {
Vector3fc p = q.position(i);
minZ = Math.min(minZ, p.z());
maxZ = Math.max(maxZ, p.z());
}
return maxZ - minZ <= EDGE;
}
}

View file

@ -0,0 +1,23 @@
package dev.loki.lovisual.render.engine.optimize.gl;
import com.mojang.blaze3d.vertex.VertexFormat;
/**
* Stage 3 step 7: a {@code BufferBuilder} that accepts ready-made vertex
* bytes pushed straight from memory — what Sodium's {@code VertexBufferWriter}
* does, reimplemented for the vanilla builder so optimizations work without
* Sodium.
*
* Implemented on {@code BufferBuilder} by {@code BufferBuilderRawMixin}.
*/
public interface RawBuffer {
/** True when this buffer's vertex format is exactly {@code format}. */
boolean lovisual$accepts(VertexFormat format);
/**
* Copy {@code count} whole vertices from {@code src} (a native address)
* into the buffer.
*/
void lovisual$push(long src, int count);
}

Some files were not shown because too many files have changed in this diff Show more