Initial release

This commit is contained in:
simeonvartik 2026-06-15 06:11:26 +02:00
commit e2f3f4759d
679 changed files with 156544 additions and 0 deletions

30
.gitignore vendored Normal file
View file

@ -0,0 +1,30 @@
*
!/.gitignore
!/README.md
!/LICENSE
!/CREDITS.md
!/build.gradle.kts
!/settings.gradle.kts
!/gradle.properties
!/gradlew
!/gradlew.bat
!/gradle/
!/gradle/**
!/src/
!/src/**
# Build-time icon sources used by generateVanillaUiAssets.
!/assets/
!/assets/icons/
!/assets/icons/**
!/addon-templates/
!/addon-templates/**
/addon-templates/**/.gradle/
/addon-templates/**/build/
/mc-src*/
/.gradle/
/build/
/out/
/run/
/src/main/resources/assets/template/

41
CREDITS.md Normal file
View file

@ -0,0 +1,41 @@
# Credits
AUTISM Client includes original code written for this project, but it also uses, references, or derives ideas/code from other open-source Minecraft client projects.
Huge credit to the following developers and projects:
## OpSec by aurickk
Parts of AUTISM Client related to client privacy, mod detection protection, compatibility handling, and anti-fingerprinting behavior are inspired by or derived from OpSec.
Project: https://github.com/aurickk/OpSec
License: GPL-3.0
## Meteor Client
AUTISM Client uses ideas, structure, APIs, or source-code references from Meteor Client, especially around Fabric client architecture, modules, utilities, and client-side systems.
Project: https://github.com/MeteorDevelopment/meteor-client
License: GPL-3.0
## Wurst Client
AUTISM Client uses ideas, references, or code patterns from Wurst Client, one of the long-running open-source Minecraft utility clients.
Project: https://github.com/Wurst-Imperium/Wurst7
License: GPL-3.0
## ExploitPreventer by NikOverflow
AUTISM Client uses ideas, references, or derived logic from ExploitPreventer for protection against known client-side exploits.
Project: https://github.com/NikOverflow/ExploitPreventer
License: MIT
## License Notice
Because AUTISM Client uses and/or derives from GPL-licensed projects, AUTISM Client is released under the GNU General Public License v3.0.
Source code must stay available to users, and any redistributed modified versions must follow the same GPL-3.0 license terms.
If any credit is missing or inaccurate, contact the maintainers so it can be corrected.

121
LICENSE Normal file
View file

@ -0,0 +1,121 @@
Creative Commons Legal Code
CC0 1.0 Universal
CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
HEREUNDER.
Statement of Purpose
The laws of most jurisdictions throughout the world automatically confer
exclusive Copyright and Related Rights (defined below) upon the creator
and subsequent owner(s) (each and all, an "owner") of an original work of
authorship and/or a database (each, a "Work").
Certain owners wish to permanently relinquish those rights to a Work for
the purpose of contributing to a commons of creative, cultural and
scientific works ("Commons") that the public can reliably and without fear
of later claims of infringement build upon, modify, incorporate in other
works, reuse and redistribute as freely as possible in any form whatsoever
and for any purposes, including without limitation commercial purposes.
These owners may contribute to the Commons to promote the ideal of a free
culture and the further production of creative, cultural and scientific
works, or to gain reputation or greater distribution for their Work in
part through the use and efforts of others.
For these and/or other purposes and motivations, and without any
expectation of additional consideration or compensation, the person
associating CC0 with a Work (the "Affirmer"), to the extent that he or she
is an owner of Copyright and Related Rights in the Work, voluntarily
elects to apply CC0 to the Work and publicly distribute the Work under its
terms, with knowledge of his or her Copyright and Related Rights in the
Work and the meaning and intended legal effect of CC0 on those rights.
1. Copyright and Related Rights. A Work made available under CC0 may be
protected by copyright and related or neighboring rights ("Copyright and
Related Rights"). Copyright and Related Rights include, but are not
limited to, the following:
i. the right to reproduce, adapt, distribute, perform, display,
communicate, and translate a Work;
ii. moral rights retained by the original author(s) and/or performer(s);
iii. publicity and privacy rights pertaining to a person's image or
likeness depicted in a Work;
iv. rights protecting against unfair competition in regards to a Work,
subject to the limitations in paragraph 4(a), below;
v. rights protecting the extraction, dissemination, use and reuse of data
in a Work;
vi. database rights (such as those arising under Directive 96/9/EC of the
European Parliament and of the Council of 11 March 1996 on the legal
protection of databases, and under any national implementation
thereof, including any amended or successor version of such
directive); and
vii. other similar, equivalent or corresponding rights throughout the
world based on applicable law or treaty, and any national
implementations thereof.
2. Waiver. To the greatest extent permitted by, but not in contravention
of, applicable law, Affirmer hereby overtly, fully, permanently,
irrevocably and unconditionally waives, abandons, and surrenders all of
Affirmer's Copyright and Related Rights and associated claims and causes
of action, whether now known or unknown (including existing as well as
future claims and causes of action), in the Work (i) in all territories
worldwide, (ii) for the maximum duration provided by applicable law or
treaty (including future time extensions), (iii) in any current or future
medium and for any number of copies, and (iv) for any purpose whatsoever,
including without limitation commercial, advertising or promotional
purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
member of the public at large and to the detriment of Affirmer's heirs and
successors, fully intending that such Waiver shall not be subject to
revocation, rescission, cancellation, termination, or any other legal or
equitable action to disrupt the quiet enjoyment of the Work by the public
as contemplated by Affirmer's express Statement of Purpose.
3. Public License Fallback. Should any part of the Waiver for any reason
be judged legally invalid or ineffective under applicable law, then the
Waiver shall be preserved to the maximum extent permitted taking into
account Affirmer's express Statement of Purpose. In addition, to the
extent the Waiver is so judged Affirmer hereby grants to each affected
person a royalty-free, non transferable, non sublicensable, non exclusive,
irrevocable and unconditional license to exercise Affirmer's Copyright and
Related Rights in the Work (i) in all territories worldwide, (ii) for the
maximum duration provided by applicable law or treaty (including future
time extensions), (iii) in any current or future medium and for any number
of copies, and (iv) for any purpose whatsoever, including without
limitation commercial, advertising or promotional purposes (the
"License"). The License shall be deemed effective as of the date CC0 was
applied by Affirmer to the Work. Should any part of the License for any
reason be judged legally invalid or ineffective under applicable law, such
partial invalidity or ineffectiveness shall not invalidate the remainder
of the License, and in such case Affirmer hereby affirms that he or she
will not (i) exercise any of his or her remaining Copyright and Related
Rights in the Work or (ii) assert any associated claims and causes of
action with respect to the Work, in either case contrary to Affirmer's
express Statement of Purpose.
4. Limitations and Disclaimers.
a. No trademark or patent rights held by Affirmer are waived, abandoned,
surrendered, licensed or otherwise affected by this document.
b. Affirmer offers the Work as-is and makes no representations or
warranties of any kind concerning the Work, express, implied,
statutory or otherwise, including without limitation warranties of
title, merchantability, fitness for a particular purpose, non
infringement, or the absence of latent or other defects, accuracy, or
the present or absence of errors, whether or not discoverable, all to
the greatest extent permissible under applicable law.
c. Affirmer disclaims responsibility for clearing rights of other persons
that may apply to the Work or any use thereof, including without
limitation any person's Copyright and Related Rights in the Work.
Further, Affirmer disclaims responsibility for obtaining any necessary
consents, permissions or other rights required for any use of the
Work.
d. Affirmer understands and acknowledges that Creative Commons is not a
party to this document and has no duty or obligation with respect to
this CC0 or use of the Work.

79
README.md Normal file
View file

@ -0,0 +1,79 @@
# AUTISM Client
AUTISM Client is the best Duping/Debugging client built for people who actually want control over what actions server recieves.
It is not trying to be a bloated all-in-one mess with 400 random buttons nobody uses. The point is simple: useful modules, a strong macro system, clean addon support, and tools that make testing, automation, and server interaction less painful.
This client is built around speed, control, and not pretending that users are too stupid to touch advanced features.
## What It Includes
AUTISM Client includes the normal client stuff you would expect, but the main focus is on systems that are actually useful.
Main features include:
* module system
* macro editor
* custom macro actions
* custom macro conditions
* addon support
* addon presets
* LAN sync tools
* custom payload sender
* NBT viewer
* packet and payload testing tools
* HUD elements
* commands
* event system
The client is made to be expandable. If the base client is not enough, addons can add their own modules, macro actions, conditions, presets, HUD elements, commands, events, and mixins.
---
# Credits
AUTISM Client includes original code written for this project, but it also uses, references, or derives ideas/code from other open-source Minecraft client projects.
Huge credit to the following developers and projects:
## OpSec by aurickk
Parts of AUTISM Client related to client privacy, mod detection protection, compatibility handling, and anti-fingerprinting behavior are inspired by or derived from OpSec.
Project: https://github.com/aurickk/OpSec
License: GPL-3.0
## Meteor Client
AUTISM Client uses ideas, structure, APIs, or source-code references from Meteor Client, especially around Fabric client architecture, modules, utilities, and client-side systems.
Project: https://github.com/MeteorDevelopment/meteor-client
License: GPL-3.0
## Wurst Client
AUTISM Client uses ideas, references, or code patterns from Wurst Client, one of the long-running open-source Minecraft utility clients.
Project: https://github.com/Wurst-Imperium/Wurst7
License: GPL-3.0
## ExploitPreventer by NikOverflow
AUTISM Client uses ideas, references, or derived logic from ExploitPreventer for protection against known client-side exploits.
Project: https://github.com/NikOverflow/ExploitPreventer
License: MIT
## Dupe Radar by ErneTalu
The Radar idea is credited to Dupe Radar by ErneTalu.
Project: https://github.com/ErneTalu/Dupe-Radar
## License Notice
Because AUTISM Client uses and/or derives from GPL-licensed projects, AUTISM Client is released under the GNU General Public License v3.0.
Source code must stay available to users, and any redistributed modified versions must follow the same GPL-3.0 license terms.
If any credit is missing or inaccurate, contact the maintainers so it can be corrected.

121
addon-templates/README.md Normal file
View file

@ -0,0 +1,121 @@
# AUTISM Client Addon Templates
These are the official addon templates for AUTISM Client.
Put these in the same repo as the client source. They are standalone Fabric mod projects, but they depend on the AUTISM Client API being published to your local Maven repo first.
This is not some magical separate SDK. Build the client API locally, then build your addon.
## Templates
- `minimal/` - This is the one you should probably start with.
It gives you the clean basic setup without throwing the entire client architecture at your face. It includes:
one module
one simple macro action
one simple wait condition
the beginner-friendly API setup
It is intentionally small. You can actually read it without needing to reverse engineer the entire client.
- `advanced/` - This is the full reference template.
Use this when you want to see how the bigger stuff is supposed to be wired. It includes:
modules
macro actions
macro conditions
presets
commands
HUD elements
events
a mixin
Addon presets are fully supported. They show up in the macro editor `Presets` picker under your addon's
own category, the same way addon modules/actions/conditions do.
Category names are intentionally simple: your addon name is the public category. If an API lets you pass a
custom category label, treat that as local organization only. The user-facing UI still groups your stuff under
the addon name so the menu does not turn into a junk drawer.
Use this when you want to see how everything works together, or when the minimal template stops being enough.
## Build Flow
From the main AUTISM Client folder, publish the API locally:
.\gradlew.bat publishToMavenLocal --no-daemon
Then build the template you want.
Minimal:
cd addon-templates\minimal
.\gradlew.bat build --no-daemon
Advanced:
cd addon-templates\advanced
.\gradlew.bat build --no-daemon
Your addon jar will be in:
build/libs/
That is the file you load as the addon.
## Toolkit
There is a toolkit script because renaming addon projects by hand is where people start creating cursed broken projects.
Run it from the main client folder:
.\addon-templates\addon-toolkit.ps1
Direct commands:
.\addon-templates\addon-toolkit.ps1 -Action Setup -Template minimal -OutputPath ..\MyAddon
.\addon-templates\addon-toolkit.ps1 -Action Scan -ProjectPath ..\MyAddon
.\addon-templates\addon-toolkit.ps1 -Action BuildAll
Setup asks for:
addon name
output folder
version
author
If you leave the version blank, it bumps the current template version by one.
It also generates the annoying stuff automatically:
addon id
package name
Maven group
jar name
description
Fabric entrypoints
mixin references
This matters because half renaming a mod is one of the easiest ways to make Gradle look like it hates you personally.
If you want to set every value yourself, use:
.\addon-templates\addon-toolkit.ps1 -Action Setup -Template advanced -Advanced
Do that only if you actually need control over everything. Or edit the files directly.
## Public Repo Rule
Commit the source, Gradle wrapper files, and config files.
Do not commit:
.gradle/
build/
They are already ignored by the root .gitignore.
If it is generated trash from your machine, it probably does not belong in the repo.

View file

@ -0,0 +1,908 @@
param(
[ValidateSet("Menu", "Setup", "Scan", "Validate", "PublishApi", "Build", "BuildAll", "Clean")]
[string] $Action = "Menu",
[ValidateSet("minimal", "advanced")]
[string] $Template = "minimal",
[string] $ProjectPath,
[string] $OutputPath,
[string] $AddonId,
[string] $AddonName,
[string] $AddonVersion,
[string] $Package,
[string] $Author,
[string] $Description,
[string] $MavenGroup,
[string] $ArchiveName,
[switch] $Advanced,
[switch] $DebugStack,
[switch] $NoPublish,
[switch] $Yes,
[switch] $NonInteractive
)
$ErrorActionPreference = "Stop"
$RepoRoot = Split-Path -Parent $PSScriptRoot
function Write-Info([string] $Message) {
Write-Host "[AUTISM] $Message" -ForegroundColor DarkGray
}
function Write-Ok([string] $Message) {
Write-Host "[OK] $Message" -ForegroundColor Green
}
function Write-Warn([string] $Message) {
Write-Host "[WARN] $Message" -ForegroundColor DarkYellow
}
function Write-Bad([string] $Message) {
Write-Host "[FAIL] $Message" -ForegroundColor White -BackgroundColor Red
}
function Write-PathLine([string] $Label, [string] $Path) {
Write-Host "${Label}:" -ForegroundColor DarkGray
Write-Host $Path -ForegroundColor White
}
function Write-FailureItem([string] $Message) {
if ($Message -match "^[A-Za-z]:[\\/]" -or $Message -match "^/" -or $Message -match "^[.]{1,2}[\\/]") {
Write-PathLine "Path" $Message
} else {
Write-Bad " - $Message"
}
}
function Resolve-FullPath([string] $Path) {
if ([string]::IsNullOrWhiteSpace($Path)) {
return $null
}
if ([System.IO.Path]::IsPathRooted($Path)) {
return [System.IO.Path]::GetFullPath($Path)
}
return [System.IO.Path]::GetFullPath((Join-Path $RepoRoot $Path))
}
function Test-ShippedTemplatePath([string] $Path) {
if ([string]::IsNullOrWhiteSpace($Path)) {
return $false
}
$full = [System.IO.Path]::GetFullPath($Path).TrimEnd("\", "/")
foreach ($templateName in @("minimal", "advanced")) {
$templatePath = [System.IO.Path]::GetFullPath((Join-Path $RepoRoot "addon-templates/$templateName")).TrimEnd("\", "/")
if ([string]::Equals($full, $templatePath, [System.StringComparison]::OrdinalIgnoreCase)) {
return $true
}
}
return $false
}
function ConvertTo-FolderName([string] $Name) {
if ([string]::IsNullOrWhiteSpace($Name)) {
return "MyAddon"
}
$parts = [regex]::Matches($Name, "[A-Za-z0-9]+") | ForEach-Object { $_.Value }
if (-not $parts -or $parts.Count -eq 0) {
return "MyAddon"
}
$folder = (($parts | ForEach-Object {
if ($_.Length -eq 1) {
$_.ToUpperInvariant()
} else {
$_.Substring(0, 1).ToUpperInvariant() + $_.Substring(1)
}
}) -join "")
if ($folder.Length -gt 48) {
$folder = $folder.Substring(0, 48)
}
return $folder
}
function ConvertTo-PackageSegment([string] $Value) {
$segment = $Value.ToLowerInvariant() -replace "[^a-z0-9]+", ""
if ([string]::IsNullOrWhiteSpace($segment)) {
$segment = "myaddon"
}
if ($segment[0] -notmatch "[a-z]") {
$segment = "addon$segment"
}
return $segment
}
function Get-DefaultAuthor {
if (-not [string]::IsNullOrWhiteSpace($env:USERNAME)) {
return $env:USERNAME
}
return "You"
}
function Get-DefaultAddonOutputPath([string] $TemplateName, [string] $Name) {
$baseName = if ([string]::IsNullOrWhiteSpace($Name)) {
if ($TemplateName -eq "advanced") { "MyAdvancedAddon" } else { "MyAddon" }
} else {
ConvertTo-FolderName $Name
}
return Resolve-FullPath (Join-Path ".." $baseName)
}
function Read-Value([string] $Prompt, [string] $Default, [scriptblock] $Validator) {
while ($true) {
$suffix = if ([string]::IsNullOrWhiteSpace($Default)) { "" } else { " [$Default]" }
$value = Read-Host "$Prompt$suffix"
if ([string]::IsNullOrWhiteSpace($value)) {
$value = $Default
}
if ($null -eq $Validator -or (& $Validator $value)) {
return $value
}
Write-Warn "Bad value. Fix it."
}
}
function Read-VersionValue([string] $Current) {
$base = if ([string]::IsNullOrWhiteSpace($Current)) { "1.0.0" } else { $Current }
$next = Step-Version $base
while ($true) {
$value = Read-Host "Version current $base, blank = $next"
if ([string]::IsNullOrWhiteSpace($value)) {
return $next
}
if (Test-Version $value) {
return $value
}
Write-Warn "Bad version. Fix it."
}
}
function Test-ModId([string] $Value) {
return $Value -match "^[a-z][a-z0-9_-]{1,63}$"
}
function Test-JavaPackage([string] $Value) {
return $Value -match "^[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)+$"
}
function Test-Version([string] $Value) {
return $Value -match "^[0-9A-Za-z][0-9A-Za-z._+-]*$"
}
function Step-Version([string] $Version) {
if ([string]::IsNullOrWhiteSpace($Version)) {
return "1.0.0"
}
$match = [regex]::Match($Version, "^(.*?)(\d+)(\D*)$")
if (-not $match.Success) {
return "$Version.1"
}
$prefix = $match.Groups[1].Value
$digits = $match.Groups[2].Value
$suffix = $match.Groups[3].Value
$next = ([int64] $digits) + 1
$nextText = [string] $next
if ($digits.Length -gt 1 -and $nextText.Length -lt $digits.Length) {
$nextText = $nextText.PadLeft($digits.Length, "0")
}
return "$prefix$nextText$suffix"
}
function ConvertTo-ModId([string] $Name) {
$id = $Name.ToLowerInvariant() -replace "[^a-z0-9_-]+", "-"
$id = $id.Trim("-_")
if ([string]::IsNullOrWhiteSpace($id)) {
return "my-autism-addon"
}
if ($id[0] -notmatch "[a-z]") {
$id = "addon-$id"
}
if ($id.Length -gt 64) {
$id = $id.Substring(0, 64).Trim("-_")
}
return $id
}
function Get-TextFile([string] $Path) {
return Get-Content -LiteralPath $Path -Raw
}
function Set-TextFile([string] $Path, [string] $Text) {
$fullPath = if (Test-Path -LiteralPath $Path) {
(Resolve-Path -LiteralPath $Path).Path
} else {
[System.IO.Path]::GetFullPath($Path)
}
$encoding = New-Object System.Text.UTF8Encoding($false)
[System.IO.File]::WriteAllText($fullPath, $Text, $encoding)
}
function Get-JsonFile([string] $Path) {
return Get-Content -LiteralPath $Path -Raw | ConvertFrom-Json
}
function Save-JsonFile([string] $Path, $Json) {
$text = $Json | ConvertTo-Json -Depth 64
$text = $text.Replace("\u003c", "<").Replace("\u003e", ">").Replace("\u0026", "&")
Set-TextFile $Path ($text + [Environment]::NewLine)
}
function Get-TomlVersion([string] $Path, [string] $Key) {
$text = Get-TextFile $Path
$match = [regex]::Match($text, "(?m)^\s*$([regex]::Escape($Key))\s*=\s*`"([^`"]+)`"")
if ($match.Success) {
return $match.Groups[1].Value
}
return ""
}
function Set-TomlVersion([string] $Path, [string] $Key, [string] $Value) {
$text = Get-TextFile $Path
$pattern = "(?m)^(\s*$([regex]::Escape($Key))\s*=\s*)`"[^`"]*`""
if ($text -match $pattern) {
$text = [regex]::Replace($text, $pattern, "`${1}`"$Value`"")
} else {
$text += [Environment]::NewLine + "$Key = `"$Value`"" + [Environment]::NewLine
}
Set-TextFile $Path $text
}
function Set-PropertiesValue([string] $Path, [string] $Key, [string] $Value) {
$text = Get-TextFile $Path
$pattern = "(?m)^$([regex]::Escape($Key))=.*$"
if ($text -match $pattern) {
$text = [regex]::Replace($text, $pattern, "$Key=$Value")
} else {
$text += [Environment]::NewLine + "$Key=$Value" + [Environment]::NewLine
}
Set-TextFile $Path $text
}
function Set-RootProjectName([string] $Path, [string] $Name) {
$text = Get-TextFile $Path
$pattern = "(?m)^(rootProject\.name\s*=\s*)`"[^`"]*`""
if ($text -match $pattern) {
$text = [regex]::Replace($text, $pattern, "`${1}`"$Name`"")
} else {
$text += [Environment]::NewLine + "rootProject.name = `"$Name`"" + [Environment]::NewLine
}
Set-TextFile $Path $text
}
function Get-FirstJavaPackage([string] $Project) {
$entry = Join-Path $Project "src/main/resources/fabric.mod.json"
if (Test-Path -LiteralPath $entry -PathType Leaf) {
$json = Get-JsonFile $entry
$classes = @()
if ($json.entrypoints.client) { $classes += @($json.entrypoints.client) }
if ($json.entrypoints.autism) { $classes += @($json.entrypoints.autism) }
foreach ($class in $classes) {
if ($class -match "^(.+)\.[^.]+$") {
return $matches[1]
}
}
}
$java = Get-ChildItem -LiteralPath (Join-Path $Project "src/main/java") -Recurse -Filter *.java -ErrorAction SilentlyContinue | Select-Object -First 1
if ($java) {
$match = [regex]::Match((Get-TextFile $java.FullName), "(?m)^\s*package\s+([^;]+);")
if ($match.Success) {
return $match.Groups[1].Value.Trim()
}
}
return "com.example.addon"
}
function Get-ClassSimpleName([string] $ClassName, [string] $Fallback) {
if ($ClassName -match "\.([^.]+)$") {
return $matches[1]
}
return $Fallback
}
function Replace-InProjectFiles([string] $Project, [string] $Old, [string] $New) {
if ([string]::IsNullOrWhiteSpace($Old) -or $Old -eq $New) {
return
}
$extensions = @(".java", ".json", ".kts", ".toml", ".properties", ".md", ".yml", ".yaml")
$files = Get-ChildItem -LiteralPath $Project -Recurse -File -Force | Where-Object {
$_.FullName -notmatch "\\(build|\.gradle)\\" -and $extensions -contains $_.Extension
}
foreach ($file in $files) {
$text = Get-TextFile $file.FullName
if ($text.Contains($Old)) {
Set-TextFile $file.FullName ($text.Replace($Old, $New))
}
}
}
function Move-JavaPackage([string] $Project, [string] $OldPackage, [string] $NewPackage) {
if ($OldPackage -eq $NewPackage) {
return
}
$srcRoot = Join-Path $Project "src/main/java"
$oldPath = Join-Path $srcRoot ($OldPackage.Replace(".", [System.IO.Path]::DirectorySeparatorChar))
$newPath = Join-Path $srcRoot ($NewPackage.Replace(".", [System.IO.Path]::DirectorySeparatorChar))
if (-not (Test-Path -LiteralPath $oldPath -PathType Container)) {
return
}
if (Test-Path -LiteralPath $newPath) {
Write-Warn "Package path already exists. Not moving files."
Write-PathLine "Path" $newPath
return
}
New-Item -ItemType Directory -Force -Path (Split-Path -Parent $newPath) | Out-Null
Move-Item -LiteralPath $oldPath -Destination $newPath
$cursor = Split-Path -Parent $oldPath
while ($cursor -and $cursor.StartsWith($srcRoot) -and $cursor -ne $srcRoot) {
$children = Get-ChildItem -LiteralPath $cursor -Force
if ($children.Count -gt 0) {
break
}
$next = Split-Path -Parent $cursor
Remove-Item -LiteralPath $cursor
$cursor = $next
}
}
function Copy-AddonTemplate([string] $TemplateName, [string] $TargetPath) {
$source = Join-Path $RepoRoot "addon-templates/$TemplateName"
if (-not (Test-Path -LiteralPath $source -PathType Container)) {
Write-PathLine "Missing template" $source
throw "Template not found."
}
if (Test-Path -LiteralPath $TargetPath) {
Write-Warn "Output already exists. Editing it in place."
Write-PathLine "Path" $TargetPath
return
}
New-Item -ItemType Directory -Force -Path $TargetPath | Out-Null
$sourceFull = [System.IO.Path]::GetFullPath($source)
$targetFull = [System.IO.Path]::GetFullPath($TargetPath)
Get-ChildItem -LiteralPath $sourceFull -Recurse -Force | Where-Object {
$_.FullName -notmatch "\\(build|\.gradle)($|\\)"
} | ForEach-Object {
$relative = $_.FullName.Substring($sourceFull.Length).TrimStart("\", "/")
$destination = Join-Path $targetFull $relative
if ($_.PSIsContainer) {
New-Item -ItemType Directory -Force -Path $destination | Out-Null
} else {
New-Item -ItemType Directory -Force -Path (Split-Path -Parent $destination) | Out-Null
Copy-Item -LiteralPath $_.FullName -Destination $destination -Force
}
}
}
function Get-AddonProjectPath {
if (-not [string]::IsNullOrWhiteSpace($ProjectPath)) {
return Resolve-FullPath $ProjectPath
}
if (-not [string]::IsNullOrWhiteSpace($OutputPath)) {
$target = Resolve-FullPath $OutputPath
Copy-AddonTemplate $Template $target
return $target
}
return Join-Path $RepoRoot "addon-templates/$Template"
}
function Get-SetupProjectPath([string] $NameForOutput) {
if (-not [string]::IsNullOrWhiteSpace($ProjectPath)) {
$project = Resolve-FullPath $ProjectPath
if (Test-ShippedTemplatePath $project) {
throw "No. The shipped templates stay clean. Use -OutputPath to copy one, or pick a real addon folder."
}
return $project
}
if ([string]::IsNullOrWhiteSpace($OutputPath)) {
$OutputPath = Read-Value "Output folder" (Get-DefaultAddonOutputPath $Template $NameForOutput) { param($v) -not [string]::IsNullOrWhiteSpace($v) }
}
$target = Resolve-FullPath $OutputPath
if (Test-ShippedTemplatePath $target) {
throw "No. The shipped templates stay clean. Pick a different output folder."
}
Copy-AddonTemplate $Template $target
return $target
}
function Configure-Addon {
if ([string]::IsNullOrWhiteSpace($AddonName)) {
$defaultName = if ($Template -eq "advanced") { "My Advanced Addon" } else { "My Addon" }
$AddonName = Read-Value "Addon name" $defaultName { param($v) -not [string]::IsNullOrWhiteSpace($v) }
}
$project = Get-SetupProjectPath $AddonName
if (-not (Test-Path -LiteralPath $project -PathType Container)) {
Write-PathLine "Missing addon folder" $project
throw "Addon project not found."
}
$fabricPath = Join-Path $project "src/main/resources/fabric.mod.json"
$versionsPath = Join-Path $project "gradle/libs.versions.toml"
$propertiesPath = Join-Path $project "gradle.properties"
$settingsPath = Join-Path $project "settings.gradle.kts"
foreach ($required in @($fabricPath, $versionsPath, $propertiesPath, $settingsPath)) {
if (-not (Test-Path -LiteralPath $required -PathType Leaf)) {
Write-PathLine "Missing file" $required
throw "Missing required addon file."
}
}
$fabric = Get-JsonFile $fabricPath
$oldId = [string] $fabric.id
$oldName = [string] $fabric.name
$oldPackage = Get-FirstJavaPackage $project
$oldVersion = Get-TomlVersion $versionsPath "mod-version"
$oldClientClass = if ($fabric.entrypoints.client) { [string] @($fabric.entrypoints.client)[0] } else { "$oldPackage.Init" }
$oldAddonClass = if ($fabric.entrypoints.autism) { [string] @($fabric.entrypoints.autism)[0] } else { "$oldPackage.Addon" }
$originalMixinName = if ($fabric.mixins -and @($fabric.mixins).Count -gt 0) { [string] @($fabric.mixins)[0] } else { "" }
$clientSimple = Get-ClassSimpleName $oldClientClass "Init"
$addonSimple = Get-ClassSimpleName $oldAddonClass "Addon"
if ([string]::IsNullOrWhiteSpace($AddonId)) {
$suggestedId = if ($oldId -match "template") { ConvertTo-ModId $AddonName } else { $oldId }
if ($Advanced) {
$AddonId = Read-Value "Addon id" $suggestedId { param($v) Test-ModId $v }
} else {
$AddonId = $suggestedId
}
}
if ([string]::IsNullOrWhiteSpace($AddonVersion)) {
$suggestedVersion = if ([string]::IsNullOrWhiteSpace($oldVersion)) { "1.0.0" } else { $oldVersion }
$AddonVersion = Read-VersionValue $suggestedVersion
}
if ([string]::IsNullOrWhiteSpace($Package)) {
$suggestedPackage = "com.$(ConvertTo-PackageSegment $AddonId).addon"
if ($Advanced) {
$Package = Read-Value "Java package" $suggestedPackage { param($v) Test-JavaPackage $v }
} else {
$Package = $suggestedPackage
}
}
if ([string]::IsNullOrWhiteSpace($MavenGroup)) {
if ($Advanced) {
$MavenGroup = Read-Value "Maven group" $Package { param($v) Test-JavaPackage $v }
} else {
$MavenGroup = $Package
}
}
if ([string]::IsNullOrWhiteSpace($ArchiveName)) {
if ($Advanced) {
$ArchiveName = Read-Value "Jar/archive base name" $AddonId { param($v) Test-ModId $v }
} else {
$ArchiveName = $AddonId
}
}
if ([string]::IsNullOrWhiteSpace($Author)) {
$Author = Read-Value "Author" (Get-DefaultAuthor) { param($v) -not [string]::IsNullOrWhiteSpace($v) }
}
if ([string]::IsNullOrWhiteSpace($Description)) {
$suggestedDescription = "$AddonName addon for AUTISM Client."
if ($Advanced) {
$Description = Read-Value "Description" $suggestedDescription { param($v) -not [string]::IsNullOrWhiteSpace($v) }
} else {
$Description = $suggestedDescription
}
}
Replace-InProjectFiles $project $oldPackage $Package
Replace-InProjectFiles $project $oldId $AddonId
Move-JavaPackage $project $oldPackage $Package
$fabric = Get-JsonFile $fabricPath
$fabric.id = $AddonId
$fabric.name = $AddonName
$fabric.version = '${version}'
$fabric.description = $Description
$fabric.authors = @($Author)
if (-not $fabric.entrypoints) {
$fabric | Add-Member -MemberType NoteProperty -Name entrypoints -Value ([pscustomobject]@{})
}
$fabric.entrypoints.client = @("$Package.$clientSimple")
$fabric.entrypoints.autism = @("$Package.$addonSimple")
if ($fabric.mixins -and @($fabric.mixins).Count -gt 0) {
$oldMixinName = if ([string]::IsNullOrWhiteSpace($originalMixinName)) { [string] @($fabric.mixins)[0] } else { $originalMixinName }
$newMixinName = "$AddonId.mixins.json"
$resourceDir = Join-Path $project "src/main/resources"
$oldMixinPath = Join-Path $resourceDir $oldMixinName
$newMixinPath = Join-Path $resourceDir $newMixinName
if ((Test-Path -LiteralPath $oldMixinPath -PathType Leaf) -and $oldMixinPath -ne $newMixinPath) {
Move-Item -LiteralPath $oldMixinPath -Destination $newMixinPath -Force
}
if (Test-Path -LiteralPath $newMixinPath -PathType Leaf) {
$mixinJson = Get-JsonFile $newMixinPath
$mixinJson.package = "$Package.mixin"
Save-JsonFile $newMixinPath $mixinJson
}
$fabric.mixins = @($newMixinName)
}
Save-JsonFile $fabricPath $fabric
Set-TomlVersion $versionsPath "mod-version" $AddonVersion
Set-PropertiesValue $propertiesPath "maven_group" $MavenGroup
Set-PropertiesValue $propertiesPath "archives_base_name" $ArchiveName
Set-RootProjectName $settingsPath $AddonId
Write-Ok "Addon rewritten."
Write-PathLine "Addon folder" $project
Write-Host " id: $AddonId"
Write-Host " name: $AddonName"
Write-Host " version: $AddonVersion"
Write-Host " package: $Package"
Write-Host ""
Write-Host "Next:" -ForegroundColor Red
Write-Host ".\addon-templates\addon-toolkit.ps1 -Action Build -ProjectPath `"$project`"" -ForegroundColor White
Write-PathLine "Jar folder" (Join-Path $project "build\libs")
$script:LastConfiguredProject = $project
}
function Add-Failure([System.Collections.Generic.List[string]] $Failures, [string] $Message) {
$Failures.Add($Message) | Out-Null
}
function Add-Warning([System.Collections.Generic.List[string]] $Warnings, [string] $Message) {
$Warnings.Add($Message) | Out-Null
}
function Test-AddonProject([string] $Project, [switch] $AllowTemplateNames) {
$failures = New-Object System.Collections.Generic.List[string]
$warnings = New-Object System.Collections.Generic.List[string]
if (-not (Test-Path -LiteralPath $Project -PathType Container)) {
Add-Failure $failures "Project folder does not exist."
Add-Failure $failures $Project
return [pscustomobject]@{ Failures = $failures; Warnings = $warnings }
}
$required = @(
"build.gradle.kts",
"settings.gradle.kts",
"gradle.properties",
"gradle/libs.versions.toml",
"gradlew.bat",
"src/main/resources/fabric.mod.json"
)
foreach ($item in $required) {
if (-not (Test-Path -LiteralPath (Join-Path $Project $item) -PathType Leaf)) {
Add-Failure $failures "Missing $item"
}
}
$fabricPath = Join-Path $Project "src/main/resources/fabric.mod.json"
if (Test-Path -LiteralPath $fabricPath -PathType Leaf) {
try {
$fabric = Get-JsonFile $fabricPath
if (-not (Test-ModId ([string] $fabric.id))) {
Add-Failure $failures "fabric.mod.json id is invalid: $($fabric.id)"
}
if ([string]::IsNullOrWhiteSpace([string] $fabric.name)) {
Add-Failure $failures "fabric.mod.json name is empty."
}
if (-not $fabric.entrypoints.autism) {
Add-Failure $failures "Missing autism entrypoint in fabric.mod.json."
} else {
foreach ($entry in @($fabric.entrypoints.autism)) {
$path = Join-Path $Project ("src/main/java/" + ([string] $entry).Replace(".", "/") + ".java")
if (-not (Test-Path -LiteralPath $path -PathType Leaf)) {
Add-Failure $failures "Autism entrypoint class file is missing: $entry"
}
}
}
if (-not $fabric.depends.autism) {
Add-Failure $failures "fabric.mod.json must depend on autism."
}
if (-not $AllowTemplateNames) {
if ([string] $fabric.id -match "template|example") {
Add-Warning $warnings "Addon id still looks like a template/example."
}
if ([string] $fabric.name -match "Template|Example") {
Add-Warning $warnings "Addon name still looks like a template/example."
}
if (@($fabric.authors) -contains "You") {
Add-Warning $warnings "Author is still 'You'."
}
}
} catch {
Add-Failure $failures "fabric.mod.json is not valid JSON: $($_.Exception.Message)"
}
}
$versionsPath = Join-Path $Project "gradle/libs.versions.toml"
if (Test-Path -LiteralPath $versionsPath -PathType Leaf) {
$addonVersion = Get-TomlVersion $versionsPath "mod-version"
$hostVersion = Get-TomlVersion $versionsPath "autism"
if (-not (Test-Version $addonVersion)) {
Add-Failure $failures "Addon mod-version is missing or invalid."
}
if ([string]::IsNullOrWhiteSpace($hostVersion)) {
Add-Failure $failures "AUTISM dependency version is missing from gradle/libs.versions.toml."
}
}
if (Test-Path -LiteralPath (Join-Path $Project ".gradle")) {
Add-Warning $warnings ".gradle cache exists locally. Ignored; do not upload it."
}
if (Test-Path -LiteralPath (Join-Path $Project "build")) {
Add-Warning $warnings "build output exists locally. Ignored; do not upload it."
}
if (Test-Path -LiteralPath (Join-Path $Project ".github")) {
Add-Warning $warnings ".github exists inside this addon project. Fine for a copied template, but it is not root repo CI unless you move it."
}
$files = Get-ChildItem -LiteralPath $Project -Recurse -File -Force | Where-Object {
$_.FullName -notmatch "\\(build|\.gradle)\\" -and
$_.Extension -in @(".java", ".json", ".md", ".kts", ".toml", ".properties", ".yml", ".yaml")
}
$templateLeftovers = @(
"autism-minimal-addon-template",
"autism-advanced-addon-template",
"AUTISM Minimal Addon Template",
"AUTISM Advanced Addon Template"
)
foreach ($file in $files) {
$text = Get-TextFile $file.FullName
if ($text -match "[\u00C2\u00C3\u00E2]") {
Add-Warning $warnings "Mojibake-looking text in $($file.FullName)"
}
if (-not $AllowTemplateNames) {
foreach ($leftover in $templateLeftovers) {
if ($text.Contains($leftover)) {
Add-Warning $warnings "Template leftover '$leftover' in $($file.FullName)"
break
}
}
}
}
return [pscustomobject]@{ Failures = $failures; Warnings = $warnings }
}
function Scan-Addon {
$project = Get-AddonProjectPath
$result = Test-AddonProject $project
Write-Info "Scanned addon project."
Write-PathLine "Addon folder" $project
foreach ($warning in $result.Warnings) {
Write-Warn "Heads up: $warning"
}
if ($result.Failures.Count -gt 0) {
Write-Bad "Scan found broken stuff:"
foreach ($failure in $result.Failures) {
Write-FailureItem $failure
}
throw "Scan failed."
}
Write-Ok "Scan clean."
}
function Validate-AddonSystem {
$failures = New-Object System.Collections.Generic.List[string]
$warnings = New-Object System.Collections.Generic.List[string]
$rootRequired = @(
"src/main/java/autismclient/addons/AddonManager.java",
"src/main/java/autismclient/api/AutismAddon.java",
"src/main/java/autismclient/api/SimpleAddon.java",
"src/main/java/autismclient/api/AutismAddons.java",
"src/main/java/autismclient/api/ApiVersion.java",
"src/main/java/autismclient/api/module/SimpleModule.java",
"src/main/java/autismclient/api/macro/SimpleAction.java",
"src/main/java/autismclient/api/macro/SimpleCondition.java",
"src/main/java/autismclient/api/macro/MacroActionRegistry.java",
"src/main/java/autismclient/api/macro/MacroPresetRegistry.java",
"src/main/java/autismclient/api/hud/HudElements.java",
"src/main/java/autismclient/api/event/AddonEvents.java",
"src/main/java/autismclient/gui/screen/AutismAddonsScreen.java",
"src/main/java/autismclient/util/macro/MissingAddonAction.java",
"addon-templates/README.md",
"addon-templates/addon-toolkit.ps1"
)
foreach ($file in $rootRequired) {
if (-not (Test-Path -LiteralPath (Join-Path $RepoRoot $file) -PathType Leaf)) {
Add-Failure $failures "Missing $file"
}
}
$gitignore = Join-Path $RepoRoot ".gitignore"
if (Test-Path -LiteralPath $gitignore -PathType Leaf) {
$ignoreText = Get-TextFile $gitignore
foreach ($pattern in @("!/src/", "!/addon-templates/", "!/addon-templates/**", "/addon-templates/**/build/", "/addon-templates/**/.gradle/", "/mc-src*/")) {
if (-not $ignoreText.Contains($pattern)) {
Add-Failure $failures ".gitignore is missing $pattern"
}
}
} else {
Add-Failure $failures "Missing .gitignore"
}
$mainVersion = Get-TomlVersion (Join-Path $RepoRoot "gradle/libs.versions.toml") "mod-version"
foreach ($templateName in @("minimal", "advanced")) {
$project = Join-Path $RepoRoot "addon-templates/$templateName"
$result = Test-AddonProject $project -AllowTemplateNames
foreach ($failure in $result.Failures) {
Add-Failure $failures "$templateName template: $failure"
}
foreach ($warning in $result.Warnings) {
Add-Warning $warnings "$templateName template: $warning"
}
$targetVersion = Get-TomlVersion (Join-Path $project "gradle/libs.versions.toml") "autism"
if ($mainVersion -and $targetVersion -and $mainVersion -ne $targetVersion) {
Add-Failure $failures "$templateName template targets AUTISM $targetVersion, main client is $mainVersion."
}
}
foreach ($warning in $warnings) {
Write-Warn "Heads up: $warning"
}
if ($failures.Count -gt 0) {
Write-Bad "Addon system is broken:"
foreach ($failure in $failures) {
Write-FailureItem $failure
}
throw "Addon system validation failed."
}
Write-Ok "Addon system clean."
}
function Invoke-Gradle([string] $Project, [string[]] $GradleArgs) {
$gradlew = Join-Path $Project "gradlew.bat"
if (-not (Test-Path -LiteralPath $gradlew -PathType Leaf)) {
Write-PathLine "Missing Gradle wrapper" $gradlew
throw "Missing Gradle wrapper."
}
Push-Location $Project
try {
& $gradlew @GradleArgs
if ($LASTEXITCODE -ne 0) {
Write-PathLine "Gradle project" $Project
throw "Gradle failed with exit code $LASTEXITCODE."
}
} finally {
Pop-Location
}
}
function Publish-Api {
Write-Info "Publishing client API to Maven Local."
Invoke-Gradle $RepoRoot @("publishToMavenLocal", "--no-daemon")
Write-Ok "Client API published."
}
function Build-Addon {
$project = Get-AddonProjectPath
if (-not (Test-Path -LiteralPath $project -PathType Container)) {
Write-PathLine "Addon folder" $project
throw "Wrong addon folder."
}
$gradlew = [System.IO.Path]::Combine($project, "gradlew.bat")
if (-not (Test-Path -LiteralPath $gradlew -PathType Leaf)) {
Write-PathLine "Addon folder" $project
throw "No Gradle wrapper there. Wrong addon folder."
}
if (-not $NoPublish) {
Publish-Api
}
Write-Info "Building addon."
Write-PathLine "Addon folder" $project
Invoke-Gradle $project @("build", "--no-daemon")
Write-Ok "Addon built."
Write-PathLine "Addon folder" $project
Write-PathLine "Jar folder" (Join-Path $project "build\libs")
}
function Build-AllTemplates {
if (-not $NoPublish) {
Publish-Api
}
foreach ($templateName in @("minimal", "advanced")) {
$project = Join-Path $RepoRoot "addon-templates/$templateName"
Write-Info "Building $templateName template."
Invoke-Gradle $project @("build", "--no-daemon")
Write-Ok "$templateName template built."
}
}
function Clean-Addon {
$project = Get-AddonProjectPath
foreach ($folder in @(".gradle", "build")) {
$path = Join-Path $project $folder
if (Test-Path -LiteralPath $path) {
if ($Yes -or ((Read-Host "Remove $path ? Type YES") -eq "YES")) {
Remove-Item -LiteralPath $path -Recurse -Force
Write-Ok "Deleted local build junk."
Write-PathLine "Path" $path
}
}
}
}
function Invoke-MenuChoice([scriptblock] $Body) {
try {
& $Body
} catch {
Write-Bad $_.Exception.Message
if ($DebugStack -and $_.ScriptStackTrace) {
Write-Warn $_.ScriptStackTrace
}
[void] (Read-Host "Press Enter. The error stays here until you do")
}
}
function Show-Menu {
$script:LastAddonPath = ""
while ($true) {
Write-Host ""
Write-Host "AUTISM ADDON KIT" -ForegroundColor Red
Write-Host "1. New addon"
Write-Host "2. Build addon"
Write-Host "3. Scan addon"
Write-Host "4. Test shipped templates"
Write-Host "5. Publish client API"
Write-Host "6. Delete local build junk"
Write-Host "0. Leave"
$choice = Read-Host ">"
switch ($choice) {
"1" {
Invoke-MenuChoice {
$script:Template = Read-Value "Template minimal/advanced" $Template { param($v) $v -in @("minimal", "advanced") }
$script:ProjectPath = ""
$script:OutputPath = ""
Configure-Addon
$script:LastAddonPath = $script:LastConfiguredProject
}
}
"2" {
Invoke-MenuChoice {
$defaultPath = if ([string]::IsNullOrWhiteSpace($script:LastAddonPath)) { Get-DefaultAddonOutputPath $Template "" } else { $script:LastAddonPath }
$script:ProjectPath = Read-Value "Addon folder" $defaultPath { param($v) -not [string]::IsNullOrWhiteSpace($v) }
Build-Addon
}
}
"3" {
Invoke-MenuChoice {
$defaultPath = if ([string]::IsNullOrWhiteSpace($script:LastAddonPath)) { Get-DefaultAddonOutputPath $Template "" } else { $script:LastAddonPath }
$script:ProjectPath = Read-Value "Addon folder" $defaultPath { param($v) -not [string]::IsNullOrWhiteSpace($v) }
Scan-Addon
}
}
"4" { Invoke-MenuChoice { Validate-AddonSystem; Build-AllTemplates } }
"5" { Invoke-MenuChoice { Publish-Api } }
"6" {
Invoke-MenuChoice {
$defaultPath = if ([string]::IsNullOrWhiteSpace($script:LastAddonPath)) { Get-DefaultAddonOutputPath $Template "" } else { $script:LastAddonPath }
$script:ProjectPath = Read-Value "Addon folder" $defaultPath { param($v) -not [string]::IsNullOrWhiteSpace($v) }
Clean-Addon
}
}
"0" { return }
default { Write-Warn "Bad choice." }
}
}
}
function Invoke-RequestedAction {
switch ($Action) {
"Menu" { Show-Menu }
"Setup" { Configure-Addon }
"Scan" { Scan-Addon }
"Validate" { Validate-AddonSystem }
"PublishApi" { Publish-Api }
"Build" { Build-Addon }
"BuildAll" { Build-AllTemplates }
"Clean" { Clean-Addon }
}
}
try {
Invoke-RequestedAction
} catch {
Write-Bad $_.Exception.Message
if ($DebugStack -and $_.ScriptStackTrace) {
Write-Warn $_.ScriptStackTrace
}
if ($Action -eq "Menu" -or (-not $NonInteractive -and -not $env:CI)) {
[void] (Read-Host "Press Enter. The error stays here until you do")
}
exit 1
}

View file

@ -0,0 +1,15 @@
root = true
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
indent_style = space
indent_size = 4
[*.{json,yml,yaml}]
indent_size = 2
[*.md]
trim_trailing_whitespace = false

View file

@ -0,0 +1,45 @@
name: Build
on:
push:
pull_request:
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up JDK 25
uses: actions/setup-java@v4
with:
distribution: 'temurin'
java-version: 25
- name: Set up Gradle
uses: gradle/actions/setup-gradle@v4
# NOTE: the build needs the AUTISM Client API artifact (com.autismclient:autism) to be resolvable.
# mavenLocal() is empty on a fresh CI runner, so make it available one of these ways:
# - publish AUTISM to a maven repo your build.gradle.kts lists (GitHub Packages, a maven server), or
# - commit the AUTISM jar into a `libs/` folder and add `flatDir { dirs("libs") }` to repositories.
- name: Build
run: ./gradlew build --stacktrace
- name: Upload artifact
uses: actions/upload-artifact@v4
with:
name: addon-jar
path: build/libs/*.jar
- name: Release dev build
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
uses: softprops/action-gh-release@v2
with:
tag_name: dev
name: Dev Build
prerelease: true
files: build/libs/*.jar

4
addon-templates/advanced/.gitignore vendored Normal file
View file

@ -0,0 +1,4 @@
.gradle/
build/
run/
*.log

View file

@ -0,0 +1,93 @@
# AUTISM Advanced Addon Template
A standalone reference addon for AUTISM Client. It registers one of each supported extension point, so
you can copy it when you need the full API surface.
Start small: keep `ExampleModule`, build once, then add macro actions, commands, HUD elements, events,
or mixins as needed.
## What It Demonstrates
| Extension point | File |
| --- | --- |
| Addon lifecycle | `ExampleAddon` |
| Module | `modules/ExampleModule` |
| Macro action | `macro/ExampleSayAction` |
| Macro condition | `macro/ExampleHeightCondition` + `macro/ExampleCondition` |
| Macro preset | `macro/ExamplePresets` |
| Command | `commands/ExampleCommand` |
| HUD element | `hud/ExampleHud` |
| Event hooks | `events/ExampleEvents` |
| Mixin | `mixin/ExampleMixin` + `autism-advanced-addon-template.mixins.json` |
Presets are first-class addon entries. `ExamplePresets` appears in the macro editor `Presets` picker
under this addon's category, and it can insert any normal stack of macro actions.
Your modules, macro actions, conditions and presets automatically group under a category named after
your addon from `fabric.mod.json`. Custom categories are scoped under your addon so they cannot collide
with built-ins or another addon.
## Build
1. In the AUTISM Client project, publish the API to your local Maven repo:
```sh
./gradlew publishToMavenLocal
```
2. Make sure the `autism` version in `gradle/libs.versions.toml` matches what you published.
3. Build this addon:
```sh
./gradlew build
```
The addon jar lands in `build/libs/`.
## Run
Drop both jars into your `mods/` folder:
- the AUTISM Client jar;
- this addon's jar from `build/libs/`.
## Make It Yours
Recommended:
```powershell
..\addon-toolkit.ps1 -Action Setup -Template advanced -OutputPath ..\..\..\MyAdvancedAddon
```
The toolkit asks for the addon name, output folder, version, and author. Blank version bumps the current
template version by one patch step. It derives the boring stuff and rewrites Gradle files, package paths,
`fabric.mod.json`, entrypoints, and the mixin config in one shot.
Manual path:
1. Rename the package `com.example.addon`.
2. Change `ExampleAddon.ID`.
3. Update `src/main/resources/fabric.mod.json`: `id`, `name`, `entrypoints`, `mixins`, and `autism:color`.
4. Rename `autism-advanced-addon-template.mixins.json` and update its `package`.
5. Keep `apiVersion()` and the `autism` dependency range honest for the client version you target.
## Project Structure
```text
addon-templates/advanced/
|-- gradle/
|-- src/main/java/com/example/addon/
| |-- ExampleAddon.java
| |-- ExampleInit.java
| |-- modules/ExampleModule.java
| |-- macro/ExampleSayAction.java
| |-- macro/ExampleHeightCondition.java
| |-- macro/ExampleCondition.java
| |-- macro/ExamplePresets.java
| |-- commands/ExampleCommand.java
| |-- hud/ExampleHud.java
| |-- events/ExampleEvents.java
| `-- mixin/ExampleMixin.java
|-- src/main/resources/
| |-- fabric.mod.json
| `-- autism-advanced-addon-template.mixins.json
|-- build.gradle.kts
`-- gradle.properties
```

View file

@ -0,0 +1,65 @@
plugins {
alias(libs.plugins.fabric.loom)
}
base {
archivesName = properties["archives_base_name"] as String
version = libs.versions.mod.version.get()
group = properties["maven_group"] as String
}
repositories {
// AUTISM Client is consumed from your local Maven repo. In the AUTISM project run:
// ./gradlew publishToMavenLocal
mavenLocal()
maven("https://maven.fabricmc.net/") { name = "Fabric" }
mavenCentral()
}
dependencies {
// Mirrors the AUTISM Client build: official Mojang mappings are implicit for 26.1.2, so there is no
// explicit `mappings(...)` line and dependencies use plain `implementation`.
minecraft(libs.minecraft)
implementation(libs.fabric.loader)
implementation(libs.fabric.api)
// The AUTISM Client API (published to mavenLocal from the AUTISM project).
implementation(libs.autism)
}
// Turns an exact Minecraft version (e.g. "26.1.2") into a patch-compatible range ("~26.1") so the addon
// keeps loading across patch releases instead of pinning one exact build.
fun toMinecraftCompat(version: String): String {
val m = Regex("""^(\d+)\.(\d+)(?:\.(\d+))?$""").matchEntire(version)
?: return version
val (year, drop, _) = m.destructured
return "~$year.$drop"
}
tasks {
processResources {
val propertyMap = mapOf(
"version" to project.version,
"mc_version" to libs.versions.minecraft.get(),
"mc_compat" to toMinecraftCompat(libs.versions.minecraft.get())
)
inputs.properties(propertyMap)
filteringCharset = "UTF-8"
filesMatching("fabric.mod.json") {
expand(propertyMap)
}
}
java {
sourceCompatibility = JavaVersion.VERSION_25
targetCompatibility = JavaVersion.VERSION_25
toolchain {
languageVersion.set(JavaLanguageVersion.of(25))
}
}
withType<JavaCompile> {
options.encoding = "UTF-8"
options.release.set(25)
}
}

View file

@ -0,0 +1,7 @@
org.gradle.jvmargs=-Xmx2G
org.gradle.parallel=true
org.gradle.caching=true
org.gradle.configuration-cache=false
maven_group=com.example.addon
archives_base_name=autism-advanced-addon-template

View file

@ -0,0 +1,19 @@
# Mirror these versions with the AUTISM Client release you are building against.
[versions]
mod-version = "1.0.0"
minecraft = "26.1.2"
fabric-loader = "0.18.4"
fabric-api = "0.147.0+26.1.2"
autism = "2.3"
loom = "1.16-SNAPSHOT"
[libraries]
minecraft = { module = "com.mojang:minecraft", version.ref = "minecraft" }
fabric-loader = { module = "net.fabricmc:fabric-loader", version.ref = "fabric-loader" }
fabric-api = { module = "net.fabricmc.fabric-api:fabric-api", version.ref = "fabric-api" }
autism = { module = "com.autismclient:autism", version.ref = "autism" }
[plugins]
fabric-loom = { id = "net.fabricmc.fabric-loom", version.ref = "loom" }

Binary file not shown.

View file

@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.0-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

248
addon-templates/advanced/gradlew vendored Normal file
View file

@ -0,0 +1,248 @@
#!/bin/sh
#
# Copyright © 2015 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

93
addon-templates/advanced/gradlew.bat vendored Normal file
View file

@ -0,0 +1,93 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View file

@ -0,0 +1,9 @@
pluginManagement {
repositories {
maven("https://maven.fabricmc.net/") { name = "Fabric" }
mavenCentral()
gradlePluginPortal()
}
}
rootProject.name = "autism-advanced-addon-template"

View file

@ -0,0 +1,53 @@
package com.example.addon;
import autismclient.api.AutismAddon;
import autismclient.api.AutismAddons;
import autismclient.api.ApiVersion;
import autismclient.api.macro.MacroActionEntry;
import com.example.addon.commands.ExampleCommand;
import com.example.addon.events.ExampleEvents;
import com.example.addon.hud.ExampleHud;
import com.example.addon.macro.ExampleHeightCondition;
import com.example.addon.macro.ExamplePresets;
import com.example.addon.macro.ExampleSayAction;
import com.example.addon.modules.ExampleModule;
// Addon entrypoint (the "autism" entrypoint in fabric.mod.json). Start small:
// register only ExampleModule first, launch the client, then add macro/actions/HUD/events as needed.
// Modules, actions, conditions and presets all auto-group under a category named after this addon.
public final class ExampleAddon extends AutismAddon {
public static final String ID = "autism-advanced-addon-template";
@Override
public int apiVersion() {
return ApiVersion.CURRENT;
}
@Override
public void onInitialize() {
AutismAddons.modules().register(new ExampleModule());
// Action: appears in the "add action" picker.
AutismAddons.macroActions().register(MacroActionEntry.local("say", ExampleSayAction::new)
.picker("Say", "Send a chat message.")
.build());
// Condition: appears in the "add condition" picker (it waits).
AutismAddons.macroActions().register(MacroActionEntry.local("wait-height", ExampleHeightCondition::new)
.condition("Wait Height", "Wait until the player is at or above a Y level.")
.build());
AutismAddons.presets().register("Reach Height", "Wait for Y 80, then say.",
ExamplePresets::reachHeightThenSay);
AutismAddons.commands().register(new ExampleCommand());
AutismAddons.hud().register(new ExampleHud());
ExampleEvents.register();
}
@Override
public String getPackage() {
return "com.example.addon";
}
}

View file

@ -0,0 +1,9 @@
package com.example.addon;
import net.fabricmc.api.ClientModInitializer;
// Fabric's required client entrypoint. The addon's real work is in ExampleAddon.
public final class ExampleInit implements ClientModInitializer {
@Override
public void onInitializeClient() {}
}

View file

@ -0,0 +1,29 @@
package com.example.addon.commands;
import autismclient.commands.AutismCommandSource;
import autismclient.commands.Command;
import autismclient.util.AutismClientMessaging;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.builder.RequiredArgumentBuilder;
// A Brigadier command. Users run it with the command prefix, e.g. .example or .example hi.
public final class ExampleCommand extends Command {
public ExampleCommand() {
super("example", "Example addon command.");
}
@Override
public void build(LiteralArgumentBuilder<AutismCommandSource> root) {
root.executes(ctx -> {
AutismClientMessaging.sendPrefixed("\u00a7dExample addon command works!");
return SUCCESS;
});
root.then(RequiredArgumentBuilder.<AutismCommandSource, String>argument("text", StringArgumentType.greedyString())
.executes(ctx -> {
AutismClientMessaging.sendPrefixed("\u00a7dYou said: \u00a7f" + StringArgumentType.getString(ctx, "text"));
return SUCCESS;
}));
}
}

View file

@ -0,0 +1,15 @@
package com.example.addon.events;
import autismclient.api.AutismAddons;
import autismclient.util.AutismClientMessaging;
// Event hooks. Register listeners once in onInitialize().
// Available: onTick, onPacketSend (return true to cancel), onPacketReceive, onGameJoin, onGameLeft.
public final class ExampleEvents {
private ExampleEvents() {}
public static void register() {
AutismAddons.events().onGameJoin(() ->
AutismClientMessaging.sendPrefixed("\u00a7a[Example] joined a world!"));
}
}

View file

@ -0,0 +1,43 @@
package com.example.addon.hud;
import com.example.addon.ExampleAddon;
import autismclient.api.hud.HudElementProvider;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Font;
import net.minecraft.client.gui.GuiGraphicsExtractor;
// A HUD element. Report your size via width()/height(); draw in render() with the GuiGraphicsExtractor
// (ctx.text / ctx.fill). The defaultX/Y/anchor/enabled are used until the user moves it in the HUD editor.
public final class ExampleHud implements HudElementProvider {
private static final int MIN_WIDTH = 94;
private static final int TEXT_PAD = 2;
@Override public String id() { return ExampleAddon.ID + ":clock"; }
@Override public String label() { return "Example Clock"; }
@Override public String description() { return "Shows the in-game tick."; }
@Override
public int width() {
Font font = Minecraft.getInstance().font;
String text = text();
int textWidth = font != null ? font.width(text) : text.length() * 6;
return Math.max(MIN_WIDTH, textWidth + TEXT_PAD * 2);
}
@Override public int height() { return 10; }
@Override
public void render(GuiGraphicsExtractor ctx, Font font, int x, int y, float alpha) {
ctx.text(font, text(), x + TEXT_PAD, y, 0xFFFFD7FF);
}
private static String text() {
long tick = Minecraft.getInstance().level != null ? Minecraft.getInstance().level.getGameTime() : 0L;
return "Addon tick: " + tick;
}
@Override public boolean defaultEnabled() { return false; }
@Override public String defaultAnchor() { return "TOP_LEFT"; }
@Override public int defaultX() { return 4; }
@Override public int defaultY() { return 120; }
}

View file

@ -0,0 +1,18 @@
package com.example.addon.macro;
import autismclient.api.macro.AddonCondition;
import net.minecraft.client.Minecraft;
// A reusable predicate: implement check(). A waiting step blocks on it via ctx.awaitCondition(...).
public final class ExampleCondition extends AddonCondition {
private final double minY;
public ExampleCondition(double minY) {
this.minY = minY;
}
@Override
public boolean check(Minecraft mc) {
return mc.player != null && mc.player.getY() >= minY;
}
}

View file

@ -0,0 +1,50 @@
package com.example.addon.macro;
import com.example.addon.ExampleAddon;
import autismclient.api.macro.ActionSchema;
import autismclient.api.macro.AddonContextAction;
import autismclient.api.macro.MacroExecutionContext;
import net.minecraft.nbt.CompoundTag;
// A macro condition: a step that waits. Extend AddonContextAction and block in run(), e.g. with
// ctx.awaitCondition(...). Register it with .condition(...) so it lands in the condition picker.
public final class ExampleHeightCondition extends AddonContextAction {
public static final String TYPE_ID = ExampleAddon.ID + ":wait-height";
public double minY = 64.0;
public ExampleHeightCondition() {
super(TYPE_ID);
}
@Override
public void run(MacroExecutionContext ctx) throws InterruptedException {
ctx.setStatus("Waiting until Y >= " + minY);
ctx.awaitCondition(new ExampleCondition(minY));
}
@Override
protected void save(CompoundTag tag) {
putDouble(tag, "minY", minY);
}
@Override
protected void load(CompoundTag tag) {
minY = getDouble(tag, "minY", minY);
}
@Override
protected ActionSchema schema() {
return ActionSchema.builder().decimal("minY", "Min Y").decRange(-64, 320).build();
}
@Override
public String getDisplayName() {
return "Wait until Y >= " + minY;
}
@Override
public String getIcon() {
return "Y";
}
}

View file

@ -0,0 +1,26 @@
package com.example.addon.macro;
import autismclient.util.macro.MacroAction;
import java.util.ArrayList;
import java.util.List;
// Presets insert a ready-made stack of steps. Return a fresh list each call; don't reuse instances.
public final class ExamplePresets {
private ExamplePresets() {}
// Wait until the player is high up, then announce it.
public static List<MacroAction> reachHeightThenSay() {
List<MacroAction> stack = new ArrayList<>();
ExampleHeightCondition waitForHeight = new ExampleHeightCondition();
waitForHeight.minY = 80.0;
stack.add(waitForHeight);
ExampleSayAction say = new ExampleSayAction();
say.message = "Reached Y 80!";
stack.add(say);
return stack;
}
}

View file

@ -0,0 +1,50 @@
package com.example.addon.macro;
import com.example.addon.ExampleAddon;
import autismclient.api.macro.ActionSchema;
import autismclient.api.macro.AddonAction;
import autismclient.util.AutismClientMessaging;
import net.minecraft.client.Minecraft;
import net.minecraft.nbt.CompoundTag;
// A macro action: runs once when the step is reached. Extend AddonAction and pass a namespaced id.
public final class ExampleSayAction extends AddonAction {
public static final String TYPE_ID = ExampleAddon.ID + ":say";
public String message = "Hello from an addon!";
public ExampleSayAction() {
super(TYPE_ID);
}
@Override
protected void run(Minecraft mc) {
AutismClientMessaging.sendPrefixed("\u00a7d[Example] " + message);
}
// Field keys here, in load(), and in the schema must match.
@Override
protected void save(CompoundTag tag) {
putString(tag, "message", message);
}
@Override
protected void load(CompoundTag tag) {
message = getString(tag, "message", message);
}
@Override
protected ActionSchema schema() {
return ActionSchema.builder().text("message", "Say").build();
}
@Override
public String getDisplayName() {
return "Say: " + message;
}
@Override
public String getIcon() {
return "S";
}
}

View file

@ -0,0 +1,19 @@
package com.example.addon.mixin;
import com.example.addon.ExampleAddon;
import net.minecraft.client.Minecraft;
import net.minecraft.client.main.GameConfig;
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;
// Example mixin. List your mixin classes in autism-advanced-addon-template.mixins.json (referenced from
// fabric.mod.json). An @Inject handler matches the target method's params, then CallbackInfo.
@Mixin(Minecraft.class)
public abstract class ExampleMixin {
@Inject(method = "<init>", at = @At("TAIL"))
private void onClientInit(GameConfig gameConfig, CallbackInfo ci) {
org.slf4j.LoggerFactory.getLogger(ExampleAddon.ID).info("Hello from ExampleMixin!");
}
}

View file

@ -0,0 +1,28 @@
package com.example.addon.modules;
import com.example.addon.ExampleAddon;
import autismclient.modules.PackModule;
import autismclient.modules.PackModuleOption;
import autismclient.util.AutismClientMessaging;
// A toggleable module. With no category it auto-lands under a menu column named after your addon.
// Read option values with bool/integer/decimal/choice/text/list(id). Group options with .group("...").
public final class ExampleModule extends PackModule {
public ExampleModule() {
super(ExampleAddon.ID + ":example", "Example", "Demonstrates an AUTISM addon module.");
option(PackModuleOption.bool("greet", "Greet on enable", true).group("General"));
option(PackModuleOption.integer("amount", "Amount", 3, 1, 10, 1).group("General"));
option(PackModuleOption.enumChoice("style", "Style", "Friendly", "Friendly", "Loud").group("Display"));
option(PackModuleOption.bool("shout", "Shout in caps", false).group("Display"));
}
@Override
public void onEnable() {
if (bool("greet")) {
String msg = "[Example] enabled - amount " + integer("amount") + ", style " + choice("style");
if (bool("shout")) msg = msg.toUpperCase(java.util.Locale.ROOT);
AutismClientMessaging.sendPrefixed("\u00a7b" + msg);
}
}
}

View file

@ -0,0 +1,11 @@
{
"required": true,
"package": "com.example.addon.mixin",
"compatibilityLevel": "JAVA_25",
"client": [
"ExampleMixin"
],
"injectors": {
"defaultRequire": 1
}
}

View file

@ -0,0 +1,37 @@
{
"schemaVersion": 1,
"id": "autism-advanced-addon-template",
"version": "${version}",
"name": "AUTISM Advanced",
"description": "Reference addon for AUTISM Client: a module, macro action, preset, condition, command, HUD element, and event hook.",
"authors": [
"You"
],
"custom": {
"autism:color": "255,80,80",
"modmenu": {
"parent": {
"id": "autism"
}
}
},
"environment": "client",
"entrypoints": {
"client": [
"com.example.addon.ExampleInit"
],
"autism": [
"com.example.addon.ExampleAddon"
]
},
"mixins": [
"autism-advanced-addon-template.mixins.json"
],
"depends": {
"java": ">=25",
"minecraft": "${mc_compat}",
"fabricloader": ">=0.18.4",
"fabric-api": "*",
"autism": ">=2.3"
}
}

View file

@ -0,0 +1,15 @@
root = true
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
indent_style = space
indent_size = 4
[*.{json,yml,yaml}]
indent_size = 2
[*.md]
trim_trailing_whitespace = false

4
addon-templates/minimal/.gitignore vendored Normal file
View file

@ -0,0 +1,4 @@
.gradle/
build/
run/
*.log

View file

@ -0,0 +1,42 @@
# AUTISM Minimal Addon Template
Smallest useful AUTISM addon example:
- one module;
- one macro action;
- one macro condition.
This template uses the easy API (`SimpleAddon`, `SimpleModule`, `simpleAction`, `simpleCondition`).
Use `../advanced` when you need commands, HUD elements, events, raw custom macro serialization, or mixins.
## Build
1. From the AUTISM Client project, publish the API locally:
```powershell
.\gradlew.bat publishToMavenLocal --no-daemon
```
2. From this folder, build the addon:
```powershell
.\gradlew.bat build --no-daemon
```
The jar lands in `build/libs/`.
## Customize
Recommended:
```powershell
..\addon-toolkit.ps1 -Action Setup -Template minimal -OutputPath ..\..\..\MyAddon
```
The toolkit asks for the addon name, output folder, version, and author. Blank version bumps the current
template version by one patch step. It derives the boring stuff and rewrites Gradle files, package paths,
`fabric.mod.json`, and entrypoints in one shot.
Manual path:
1. Rename package `com.example.minimal`.
2. Change `MinimalAddon.ID`.
3. Update `src/main/resources/fabric.mod.json`.
4. Change names/descriptions in `MinimalAddon`.

View file

@ -0,0 +1,65 @@
plugins {
alias(libs.plugins.fabric.loom)
}
base {
archivesName = properties["archives_base_name"] as String
version = libs.versions.mod.version.get()
group = properties["maven_group"] as String
}
repositories {
// AUTISM Client is consumed from your local Maven repo. In the AUTISM project run:
// ./gradlew publishToMavenLocal
mavenLocal()
maven("https://maven.fabricmc.net/") { name = "Fabric" }
mavenCentral()
}
dependencies {
// Mirrors the AUTISM Client build: official Mojang mappings are implicit for 26.1.2, so there is no
// explicit `mappings(...)` line and dependencies use plain `implementation`.
minecraft(libs.minecraft)
implementation(libs.fabric.loader)
implementation(libs.fabric.api)
// The AUTISM Client API (published to mavenLocal from the AUTISM project).
implementation(libs.autism)
}
// Turns an exact Minecraft version (e.g. "26.1.2") into a patch-compatible range ("~26.1") so the addon
// keeps loading across patch releases instead of pinning one exact build.
fun toMinecraftCompat(version: String): String {
val m = Regex("""^(\d+)\.(\d+)(?:\.(\d+))?$""").matchEntire(version)
?: return version
val (year, drop, _) = m.destructured
return "~$year.$drop"
}
tasks {
processResources {
val propertyMap = mapOf(
"version" to project.version,
"mc_version" to libs.versions.minecraft.get(),
"mc_compat" to toMinecraftCompat(libs.versions.minecraft.get())
)
inputs.properties(propertyMap)
filteringCharset = "UTF-8"
filesMatching("fabric.mod.json") {
expand(propertyMap)
}
}
java {
sourceCompatibility = JavaVersion.VERSION_25
targetCompatibility = JavaVersion.VERSION_25
toolchain {
languageVersion.set(JavaLanguageVersion.of(25))
}
}
withType<JavaCompile> {
options.encoding = "UTF-8"
options.release.set(25)
}
}

View file

@ -0,0 +1,7 @@
org.gradle.jvmargs=-Xmx2G
org.gradle.parallel=true
org.gradle.caching=true
org.gradle.configuration-cache=false
maven_group=com.example.addon
archives_base_name=autism-minimal-addon-template

View file

@ -0,0 +1,19 @@
# Mirror these versions with the AUTISM Client release you are building against.
[versions]
mod-version = "1.0.0"
minecraft = "26.1.2"
fabric-loader = "0.18.4"
fabric-api = "0.147.0+26.1.2"
autism = "2.3"
loom = "1.16-SNAPSHOT"
[libraries]
minecraft = { module = "com.mojang:minecraft", version.ref = "minecraft" }
fabric-loader = { module = "net.fabricmc:fabric-loader", version.ref = "fabric-loader" }
fabric-api = { module = "net.fabricmc.fabric-api:fabric-api", version.ref = "fabric-api" }
autism = { module = "com.autismclient:autism", version.ref = "autism" }
[plugins]
fabric-loom = { id = "net.fabricmc.fabric-loom", version.ref = "loom" }

Binary file not shown.

View file

@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.0-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

248
addon-templates/minimal/gradlew vendored Normal file
View file

@ -0,0 +1,248 @@
#!/bin/sh
#
# Copyright © 2015 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

93
addon-templates/minimal/gradlew.bat vendored Normal file
View file

@ -0,0 +1,93 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View file

@ -0,0 +1,9 @@
pluginManagement {
repositories {
maven("https://maven.fabricmc.net/") { name = "Fabric" }
mavenCentral()
gradlePluginPortal()
}
}
rootProject.name = "autism-minimal-addon-template"

View file

@ -0,0 +1,35 @@
package com.example.minimal;
import autismclient.api.ApiVersion;
import autismclient.api.SimpleAddon;
import autismclient.api.macro.MacroActionEntry;
import autismclient.api.module.SimpleModule;
import autismclient.util.AutismClientMessaging;
public final class MinimalAddon extends SimpleAddon {
public static final String ID = "autism-minimal-addon-template";
public MinimalAddon() {
super(ApiVersion.CURRENT, "com.example.minimal");
}
@Override
protected void initialize() {
SimpleModule module = new SimpleModule("hello-module", "Hello Module", "Tiny example addon module.")
.addBool("greet", "Greet On Enable", true)
.addText("message", "Message", "Hello from my addon")
.onEnabled(self -> {
if (self.getBool("greet")) {
AutismClientMessaging.sendPrefixed("\u00a7a" + self.getText("message"));
}
});
registerModule(module);
registerAction(simpleAction("say-hello", "Say Hello", "Send a short addon message.", "S", mc ->
AutismClientMessaging.sendPrefixed("\u00a7aHello from the minimal addon!")));
MacroActionEntry condition = simpleCondition("wait-player", "Wait Player", "Wait until the local player exists.",
"Waiting for player", "P", mc -> mc.player != null);
registerAction(condition);
}
}

View file

@ -0,0 +1,8 @@
package com.example.minimal;
import net.fabricmc.api.ClientModInitializer;
public final class MinimalInit implements ClientModInitializer {
@Override
public void onInitializeClient() {}
}

View file

@ -0,0 +1,34 @@
{
"schemaVersion": 1,
"id": "autism-minimal-addon-template",
"version": "${version}",
"name": "AUTISM Minimal Addon Template",
"description": "Small AUTISM Client addon example: one module, one macro action, and one macro condition.",
"authors": [
"You"
],
"custom": {
"autism:color": "80,220,120",
"modmenu": {
"parent": {
"id": "autism"
}
}
},
"environment": "client",
"entrypoints": {
"client": [
"com.example.minimal.MinimalInit"
],
"autism": [
"com.example.minimal.MinimalAddon"
]
},
"depends": {
"java": ">=25",
"minecraft": "${mc_compat}",
"fabricloader": ">=0.18.4",
"fabric-api": "*",
"autism": ">=2.3"
}
}

View file

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg id="Layer_1" xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 500 500">
<!-- Generator: Adobe Illustrator 30.2.1, SVG Export Plug-In . SVG Version: 2.1.1 Build 1) -->
<defs>
<style>
.st0 {
fill: #ec2027;
stroke: #ec2027;
stroke-miterlimit: 10;
stroke-width: 40px;
}
</style>
</defs>
<g id="_x35_3">
<path class="st0" d="M474.1,289.8c-28.2-5.4-59.1-10.9-83.3-28.5-6.7-12.2,4-23.1,12.1-32.6,20.2-28.5,36.3-54.3,44.3-88.2,1.3-9.5-2.7-23.1-13.4-21.7-21.5,19-48.4,33.9-76.6,38-6.7,1.4-10.8-5.4-12.1-10.9-4-38-14.8-74.6-29.6-108.6-4-8.1-12.1-14.9-21.5-14.9-9.4,1.4-6.7,13.6-8.1,20.4-5.4,24.4-10.8,47.5-25.5,66.5-4,5.4-10.8,2.7-16.1,0-33.6-24.4-64.5-46.1-103.5-57-6.7-1.4-12.1,1.4-17.5,4.1-5.4,2.7-2.7,6.8-2.7,9.5,14.8,25.8,33.6,47.5,37.6,77.3,0,6.8-5.4,10.9-10.8,10.9-39,5.4-73.9,14.9-108.9,31.2-9.4,5.4-17.5,16.3-12.1,27.1,28.2,4.1,55.1,9.5,80.6,25.8,5.4,2.7,8.1,8.1,5.4,13.6-14.8,25.8-33.6,47.5-45.7,74.6-5.4,12.2-9.4,23.1-13.4,35.3-1.3,8.1,1.3,16.3,8.1,20.4,2.7,1.4,6.7,1.4,9.4-1.4,1.3-1.4,2.7-2.7,4-4.1,4-1.4,6.7-4.1,9.4-6.8,20.2-10.9,37.6-25.8,60.5-24.4,4,0,8.1,0,9.4,5.4,4,16.3,4,31.2,8.1,47.5,1.3,5.4,2.7,9.5,4,14.9,6.7,19,10.8,38,22.8,55.6,4,6.8,13.4,13.6,22.8,8.1,5.4-23.1,8.1-44.8,17.5-66.5,5.4-9.5,10.8-24.4,22.8-19,6.7,2.7,13.4,8.1,20.2,13.6,26.9,20.4,56.4,33.9,87.4,44.8,5.4,1.4,10.8,0,14.8-2.7,2.7-2.7,9.4-6.8,6.7-10.9-17.5-24.4-33.6-50.2-39-78.7,2.7-10.9,14.8-12.2,24.2-12.2,34.9-4.1,67.2-14.9,99.5-31.2,6.7-4.1,14.8-16.3,8.1-24.4Z"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

View file

@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg id="Layer_1" xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 500 500">
<!-- Generator: Adobe Illustrator 30.2.1, SVG Export Plug-In . SVG Version: 2.1.1 Build 1) -->
<defs>
<style>
.st0 {
fill: #ec2027;
}
</style>
</defs>
<rect class="st0" x="6.7" y="7.9" width="484.2" height="44.1"/>
<rect class="st0" x="6.7" y="154.3" width="484.2" height="44.1"/>
<rect class="st0" x="6.7" y="300.7" width="484.2" height="44.1"/>
<rect class="st0" x="6.7" y="447.2" width="484.2" height="44.1"/>
<rect class="st0" x="7.1" y="7.5" width="44.1" height="484.2"/>
<rect class="st0" x="153.5" y="7.5" width="44.1" height="484.2"/>
<rect class="st0" x="300" y="7.5" width="44.1" height="484.2"/>
<rect class="st0" x="446.4" y="7.5" width="44.1" height="484.2"/>
</svg>

After

Width:  |  Height:  |  Size: 859 B

12
assets/icons/Filter.svg Normal file
View file

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg id="Layer_1" xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 500 500">
<!-- Generator: Adobe Illustrator 30.2.1, SVG Export Plug-In . SVG Version: 2.1.1 Build 1) -->
<defs>
<style>
.st0 {
fill: #ec2027;
}
</style>
</defs>
<path class="st0" d="M384.7,70.7L318.8,4.8l-64.5,64.5L189.4,4.4l-65.4,65.4,65,65-47.9,47.9-65-65L10.7,183.1l65,65L11.1,312.6l65.8,65.8,64.5-64.5,48.2,48.2-64.5,64.5,65.8,65.8,64.5-64.5,65,65,65.4-65.4-65-65,47.9-47.9,65,65,65.4-65.4-65-65,64.5-64.5-65.8-65.8-64.5,64.5-48.2-48.2,64.5-64.5ZM302.9,248.8l-47.9,47.9-48.2-48.2,47.9-47.9,48.2,48.2Z"/>
</svg>

After

Width:  |  Height:  |  Size: 670 B

26
assets/icons/Keybinds.svg Normal file
View file

@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg id="Layer_1" xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 500 500">
<!-- Generator: Adobe Illustrator 30.2.1, SVG Export Plug-In . SVG Version: 2.1.1 Build 1) -->
<defs>
<style>
.st0 {
stroke-width: 80px;
}
.st0, .st1 {
fill: #ec2027;
stroke: #ec2027;
stroke-miterlimit: 10;
}
.st1 {
stroke-width: 30px;
}
</style>
</defs>
<path class="st1" d="M267.1,22.2C127.4,13.3,11.7,128.6,20.6,267.9c7.4,115.1,100.7,208.1,216.2,215.4,139.7,8.9,255.4-106.4,246.5-245.6-7.4-115.1-100.7-208.1-216.2-215.4ZM266.1,468.4c-130.7,8.3-238.9-99.5-230.5-229.7,6.9-107.7,94.2-194.6,202.2-201.5,130.7-8.3,238.9,99.5,230.5,229.7-6.9,107.7-94.2,194.6-202.2,201.5Z"/>
<path class="st0" d="M146.5,290.3v-75.1c0-5.3-5.8-8.7-10.5-6l-65.3,37.6c-4.6,2.7-4.6,9.4,0,12l65.3,37.6c4.6,2.7,10.5-.7,10.5-6Z"/>
<path class="st0" d="M357.4,215.2v75.1c0,5.3,5.8,8.7,10.5,6l65.3-37.6c4.6-2.7,4.6-9.4,0-12l-65.3-37.6c-4.6-2.7-10.5.7-10.5,6Z"/>
<path class="st0" d="M258,432.9l37.7-65c2.7-4.6-.7-10.4-6-10.4h-75.4c-5.4,0-8.7,5.8-6,10.4l37.7,65c2.7,4.6,9.4,4.6,12.1,0Z"/>
<path class="st0" d="M214.3,147.3h75.4c5.4,0,8.7-5.8,6-10.4l-37.7-65c-2.7-4.6-9.4-4.6-12.1,0l-37.7,65c-2.7,4.6.7,10.4,6,10.4Z"/>
</svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

21
assets/icons/Lansync.svg Normal file
View file

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg id="Layer_1" xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 500 500">
<!-- Generator: Adobe Illustrator 30.2.1, SVG Export Plug-In . SVG Version: 2.1.1 Build 1) -->
<defs>
<style>
.st0 {
fill: #ec2027;
stroke: #ec2027;
stroke-miterlimit: 10;
stroke-width: 20px;
}
</style>
</defs>
<path class="st0" d="M410.8,119.5V12H12.4v367.2h76.3v107.5h398.4V119.5h-76.3ZM471.9,193.2H103.8v-59.7h368.1v59.7ZM395.6,25.9v59l-368.1.7V25.9h368.1ZM27.5,365.2V99.6l368.1-.7v20.6H88.6v245.7H27.5ZM103.8,472.7V207.1h368.1v265.6H103.8Z"/>
<path class="st0" d="M139,176.8c10.2,1.4,18.9-6.5,17.3-15.9-1-5.9-6.2-10.6-12.5-11.5-10.2-1.4-18.9,6.5-17.3,15.9,1,5.9,6.2,10.6,12.5,11.5Z"/>
<path class="st0" d="M183.3,176.8c10.2,1.4,18.9-6.5,17.3-15.9-1-5.9-6.2-10.6-12.5-11.5-10.2-1.4-18.9,6.5-17.3,15.9,1,5.9,6.2,10.6,12.5,11.5Z"/>
<path class="st0" d="M229.5,176.8c10.2,1.4,18.9-6.5,17.3-15.9-1-5.9-6.2-10.6-12.5-11.5-10.2-1.4-18.9,6.5-17.3,15.9,1,5.9,6.2,10.6,12.5,11.5Z"/>
<path class="st0" d="M62.7,69.3c10.2,1.4,18.9-6.5,17.3-15.9-1-5.9-6.2-10.6-12.5-11.5-10.2-1.4-18.9,6.5-17.3,15.9,1,5.9,6.2,10.6,12.5,11.5Z"/>
<path class="st0" d="M107.1,69.3c10.2,1.4,18.9-6.5,17.3-15.9-1-5.9-6.2-10.6-12.5-11.5-10.2-1.4-18.9,6.5-17.3,15.9,1,5.9,6.2,10.6,12.5,11.5Z"/>
<path class="st0" d="M153.2,69.3c10.2,1.4,18.9-6.5,17.3-15.9-1-5.9-6.2-10.6-12.5-11.5-10.2-1.4-18.9,6.5-17.3,15.9,1,5.9,6.2,10.6,12.5,11.5Z"/>
</svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

15
assets/icons/Macros.svg Normal file
View file

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg id="Layer_1" xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 500 500">
<!-- Generator: Adobe Illustrator 30.2.1, SVG Export Plug-In . SVG Version: 2.1.1 Build 1) -->
<defs>
<style>
.st0 {
fill: #ec2027;
stroke: #ec2027;
stroke-miterlimit: 10;
stroke-width: 20px;
}
</style>
</defs>
<path class="st0" d="M385,288c-7,3.9-15.6,2.7-21.2-3l-34.9-35.5,35.5-36c5.6-5.7,14.3-6.9,21.2-3,25.5,14.3,58.3,10.4,79.9-11.5,27.1-27.5,26.2-72.7-2.6-99-25.9-23.6-66.3-22.9-91.4,1.6-22.5,22-26.6,55.8-12.3,82.1,3.8,7,2.7,15.8-2.9,21.5l-35.5,36-65.9-66.9v-.5h-.6v-12c0-8.1,5.3-15.1,12.9-17.3,28-8.2,48.5-34.4,48.5-65.5S283.4,8.8,244.6,10.9c-34.8,1.9-62.9,31.4-63.6,66.7-.6,31.7,20.1,58.5,48.5,66.9,7.6,2.2,12.9,9.3,12.9,17.3v12l-65.9,66.9-34.9-35.5c-5.6-5.7-6.8-14.4-2.9-21.5,14.3-26.3,10.2-60.1-12.3-82.1-25.1-24.5-65.6-25.2-91.4-1.6-28.9,26.4-29.7,71.5-2.6,99,21.6,22,54.4,25.8,79.9,11.5,7-3.9,15.6-2.7,21.2,3l34.9,35.5-35.5,36c-5.6,5.7-14.3,6.9-21.2,3-25.5-14.3-58.2-10.4-79.9,11.5-27.1,27.5-26.2,72.7,2.6,99,25.9,23.6,66.3,22.9,91.4-1.6,22.5-22,26.6-55.8,12.3-82.1-3.8-7-2.7-15.8,2.9-21.5l35.5-36,65.9,66.9v.5h.6v12c0,8.1-5.3,15.1-12.9,17.3-28,8.2-48.5,34.4-48.5,65.5s32.1,70.2,70.9,68.1c34.8-1.9,62.9-31.4,63.6-66.7.6-31.7-20.1-58.5-48.5-66.9-7.6-2.2-12.9-9.3-12.9-17.3v-12l65.9-66.9,34.9,35.5c5.6,5.7,6.8,14.4,2.9,21.5-14.3,26.3-10.2,60.1,12.3,82.1,25.1,24.5,65.6,25.2,91.4,1.6,28.9-26.4,29.7-71.5,2.6-99-21.6-22-54.4-25.8-79.9-11.5ZM242.4,307.6l-57.7-58.6,57.7-58.6v117.2ZM254.6,308.2v-117.2l57.7,58.6-57.7,58.6Z"/>
</svg>

After

Width:  |  Height:  |  Size: 1.6 KiB

View file

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg id="Layer_1" xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 500 500">
<!-- Generator: Adobe Illustrator 30.2.1, SVG Export Plug-In . SVG Version: 2.1.1 Build 1) -->
<defs>
<style>
.st0 {
fill: #ec2027;
stroke: #ec2027;
stroke-miterlimit: 10;
stroke-width: 60px;
}
</style>
</defs>
<g id="_x37_3">
<polygon class="st0" points="318.4 85.3 314.2 186.7 413.9 179.2 340.3 248.8 415 315.1 315.2 312.2 321.2 413.3 253.6 339.5 187.3 416.3 191.5 314.9 91.8 322.4 165.4 252.8 90.7 186.5 190.5 189.4 184.5 88.3 252.1 162.1 318.4 85.3"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 663 B

View file

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg id="Layer_1" xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 500 500">
<!-- Generator: Adobe Illustrator 30.2.1, SVG Export Plug-In . SVG Version: 2.1.1 Build 1) -->
<defs>
<style>
.st0 {
fill: #ec2027;
stroke: #ec2027;
stroke-miterlimit: 10;
stroke-width: 30px;
}
</style>
</defs>
<path class="st0" d="M484.3,246.9c0-60.4-46-110-104.9-115.7l47.5-47.5-5.1-5.4c-.3-.3-.6-.6-.9-1-46.3-46.3-120.5-48.2-169.2-5.8V15.4c-.4,0-.7,0-1.1,0-60.4,0-110,46-115.7,104.9l-47.5-47.5-5.4,5.1c-.3.3-.6.6-.9.9l5.4,5.5-5.4-5.5h0c-23.4,23.4-36.3,54.6-36.3,87.7s10.8,58.9,30.5,81.5H19.1c0,.4,0,.7,0,1.1,0,60.4,46,110,104.9,115.7l-47.5,47.5,5.1,5.4c.3.3.6.6.9,1,24.2,24.2,55.9,36.3,87.7,36.3s58.2-10.2,81.5-30.5v56.1c.4,0,.7,0,1.1,0,60.4,0,110-46,115.7-104.9l47.5,47.5,5.4-5.1c.3-.3.6-.6,1-.9,46.3-46.3,48.2-120.5,5.8-169.2h56.1c0-.4,0-.7,0-1.1ZM256.4,88.2c21.2-21.2,49-31.8,76.8-31.8s51.5,9.1,72,27.2l-47.4,47.4c-56,4.9-100.6,49.5-105.5,105.5l-.3.3c0,0,0-.1-.1-.2V93.2c1.5-1.7,3-3.4,4.7-5ZM91.9,243.3c-20.5-20.5-31.8-47.8-31.8-76.8s9.6-52.1,27.3-72l47.4,47.4c4.9,56,49.5,100.6,105.5,105.5l.3.3c0,0-.1,0-.2.1H96.9c-1.7-1.5-3.4-3.1-5-4.7ZM247,407.8c-40.8,40.8-106.2,42.3-148.8,4.5l47.4-47.4c56-4.9,100.6-49.5,105.5-105.5l.3-.3c0,0,0,.1.1.2v143.6c-1.5,1.7-3.1,3.4-4.7,5ZM411.5,252.7c40.8,40.8,42.3,106.2,4.5,148.8l-47.4-47.4c-4.9-56-49.5-100.6-105.5-105.5l-.3-.3c0,0,.1,0,.2-.1h143.6c1.7,1.5,3.4,3.1,5,4.7Z"/>
</svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

View file

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg id="Layer_1" xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 500 500">
<!-- Generator: Adobe Illustrator 30.2.1, SVG Export Plug-In . SVG Version: 2.1.1 Build 1) -->
<defs>
<style>
.st0 {
fill: #ec2027;
}
</style>
</defs>
<rect class="st0" x="11.3" y="14.8" width="55" height="479.3"/>
<rect class="st0" x="95.7" y="14.8" width="55" height="479.3"/>
<rect class="st0" x="264.6" y="14.8" width="55" height="479.3"/>
<rect class="st0" x="433.5" y="14.8" width="55" height="479.3"/>
<rect class="st0" x="180.2" y="136.5" width="55" height="357.6"/>
<rect class="st0" x="349.1" y="14.8" width="55" height="357.6"/>
</svg>

After

Width:  |  Height:  |  Size: 722 B

View file

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg id="Layer_1" xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 500 500">
<!-- Generator: Adobe Illustrator 30.2.1, SVG Export Plug-In . SVG Version: 2.1.1 Build 1) -->
<defs>
<style>
.st0 {
fill: #ec2027;
stroke: #ec2027;
stroke-miterlimit: 10;
stroke-width: 40px;
}
</style>
</defs>
<g id="_x33_1">
<path class="st0" d="M250.2,29.6c-125.9,0-228.3,99.6-228.3,221.9s102.4,221.9,228.3,221.9,228.3-99.6,228.3-221.9S376.1,29.6,250.2,29.6ZM250.2,41.1c116,0,210.9,89.1,216.2,200.5-23.3-22-110.3-96.8-216.2-96.8S57.3,219.6,34,241.7c5.3-111.5,100.3-200.5,216.2-200.5ZM459.8,251.6c-19.5,18.4-106.7,95.1-209.6,95.1S60.1,270,40.6,251.6c19.5-18.4,106.7-95.1,209.6-95.1s190.1,76.7,209.6,95.1ZM250.2,462c-116,0-210.9-89.1-216.2-200.5,23.3,22,110.3,96.8,216.2,96.8s192.9-74.7,216.2-96.8c-5.3,111.5-100.3,200.5-216.2,200.5Z"/>
<path class="st0" d="M214.8,251.6c0,19,15.9,34.4,35.4,34.4s35.4-15.4,35.4-34.4-15.9-34.4-35.4-34.4-35.4,15.4-35.4,34.4Z"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1 KiB

View file

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg id="Layer_1" xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 500 500">
<!-- Generator: Adobe Illustrator 30.2.1, SVG Export Plug-In . SVG Version: 2.1.1 Build 1) -->
<defs>
<style>
.st0 {
fill: #ec2027;
}
</style>
</defs>
<path class="st0" d="M1.2,225.8h223.5V2.3C106.7,14.1,12.9,107.9,1.2,225.8Z"/>
<path class="st0" d="M224.7,499.5v-223.5H1.2c11.8,118,105.6,211.8,223.5,223.5Z"/>
<path class="st0" d="M274.8,499.5c118-11.8,211.8-105.6,223.5-223.5h-223.5v223.5Z"/>
<path class="st0" d="M274.8,2.3v223.5h223.5C486.6,107.9,392.8,14.1,274.8,2.3Z"/>
</svg>

After

Width:  |  Height:  |  Size: 654 B

View file

@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg id="Layer_1" xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 500 500">
<!-- Generator: Adobe Illustrator 30.2.1, SVG Export Plug-In . SVG Version: 2.1.1 Build 1) -->
<defs>
<style>
.st0 {
fill: #ec2027;
}
</style>
</defs>
<g id="_x30_9">
<path class="st0" d="M189.9,357.2c19.8-5.5,40.5-8.4,61.3-8.4s39.5,2.6,58.4,7.6c10.8-29.2,17.3-61.6,18.5-94.9h-156.8c1.2,33.8,7.6,66.4,18.5,95.7Z"/>
<path class="st0" d="M248.3,130.4c17.9,0,35.7-2.4,52.7-7.2-13.2-28.2-30.6-52.7-51.3-71.5-21,18.4-38.6,43.3-51.9,72.1,16.4,4.3,33.3,6.6,50.4,6.6Z"/>
<path class="st0" d="M217.8,51.5c-33.2,5.3-63.8,18.9-89.5,38.5,14.6,11.1,30.6,20.1,47.5,26.7,11.1-24.6,25.3-46.8,42-65.2Z"/>
<path class="st0" d="M351.5,238.2h98.9c-3-52.8-26.6-100.2-62.8-134.4-16.5,13.4-35.5,24.4-55.9,32.6,11.7,31.4,18.6,66.1,19.8,101.8Z"/>
<path class="st0" d="M167.5,137c-20.3-7.8-39.4-18.5-56.7-32-35.5,34.1-58.6,81-61.6,133.2h98.9c1.2-35.4,8-69.9,19.4-101.2Z"/>
<path class="st0" d="M369.7,88.8c-25.5-19.1-55.7-32.3-88.5-37.4,16.6,18.4,30.7,40.2,41.9,64.4,16.6-6.8,32.3-15.8,46.7-26.9Z"/>
<path class="st0" d="M309.7,143.9c-19.3,5.5-39.5,8.4-59.9,8.4s-40.7-2.7-60.2-8.1c-10.6,28.9-16.9,61-18.2,94h156.8c-1.2-33.3-7.7-65.3-18.5-94.3Z"/>
<path class="st0" d="M148.1,261.5H49.2c3.1,52.9,26.7,100.4,63.1,134.6,17.1-13.3,36-23.9,56.1-31.7-11.9-31.7-19-66.7-20.3-102.9Z"/>
<path class="st0" d="M249.8.7C112.2.7.6,112.3.6,249.8s111.5,249.1,249.1,249.1,249.1-111.5,249.1-249.1S387.4.7,249.8.7ZM402.2,414.3c-.3,1.6-1.1,3.2-2.4,4.5-2.6,1.7-4.6,2.9-6.8,3.6-38.5,32-87.9,51.4-141.8,51.7-.5,0-.9,0-1.4,0-54.9,0-105.2-19.8-144.2-52.6-.6-.4-1.3-1-1.8-1.6-47.9-41.1-78.2-102.1-78.2-170.1C25.5,126.1,126,25.6,249.8,25.6s224.2,100.5,224.2,224.2-27.7,123.5-71.9,164.4Z"/>
<path class="st0" d="M281.7,448.2c32.5-5.2,62.4-18.3,87.8-37.2-14.4-10.9-30-19.7-46.5-26.3-11,23.9-24.9,45.5-41.3,63.5Z"/>
<path class="st0" d="M331.7,363.5c20.3,7.6,39.5,18.2,56.8,31.4,35.6-34.1,58.8-81.1,61.8-133.4h-98.9c-1.2,35.7-8.1,70.5-19.7,102Z"/>
<path class="st0" d="M249.8,370.7c-17.5,0-34.7,2.3-51.4,6.8,13,27.7,30.3,51.8,51.4,70.4,20.6-18.1,37.9-42.3,51.1-70.4-16.6-4.4-33.7-6.7-51.1-6.7Z"/>
<path class="st0" d="M130,411c25.5,19,55.6,32.1,88.3,37.3-16.4-18.2-30.4-39.7-41.5-63.6-16.6,6.6-32.3,15.4-46.8,26.4Z"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 2.3 KiB

542
build.gradle.kts Normal file
View file

@ -0,0 +1,542 @@
import java.io.OutputStream
import java.util.zip.ZipFile
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.apache.xmlgraphics:batik-transcoder:1.17")
classpath("org.apache.xmlgraphics:batik-codec:1.17")
}
}
plugins {
alias(libs.plugins.fabric.loom)
`maven-publish`
}
base {
archivesName = properties["archives_base_name"] as String
version = libs.versions.mod.version.get()
group = properties["maven_group"] as String
}
repositories {
maven {
name = "meteor-maven"
url = uri("https://maven.meteordev.org/releases")
}
mavenCentral()
}
dependencies {
minecraft(libs.minecraft)
implementation(libs.fabric.loader)
implementation(libs.fabric.api)
implementation("net.java.dev.jna:jna:5.13.0")
implementation("net.java.dev.jna:jna-platform:5.13.0")
implementation("io.netty:netty-handler-proxy:4.1.118.Final")
implementation("io.netty:netty-codec-socks:4.1.118.Final")
include("io.netty:netty-handler-proxy:4.1.118.Final")
include("io.netty:netty-codec-socks:4.1.118.Final")
implementation("de.florianreuth:waybackauthlib:1.1.0")
include("de.florianreuth:waybackauthlib:1.1.0")
implementation("com.github.weisj:jsvg:2.1.0")
include("com.github.weisj:jsvg:2.1.0")
// Bundle a newer MixinExtras (jar-in-jar) so Fabric Loader loads it over the old 0.5.0 it ships
// with. Required because ViaFabricPlus (and our own WrapOperation/ModifyExpressionValue mixins)
// need MixinExtras >= 0.5.3; without this, joining a server crashes during mixin application.
implementation("io.github.llamalad7:mixinextras-fabric:0.5.4")
include("io.github.llamalad7:mixinextras-fabric:0.5.4")
}
val generatedAutismResourcesDir = layout.buildDirectory.dir("generated/resources/autism/main")
data class SourceFile(val path: String, val text: String)
data class FieldSpec(val name: String, val type: String, val kind: String, val editable: Boolean)
data class PacketSpec(
val className: String,
val protocol: String,
val direction: String,
val codecStyle: String,
val packetType: String,
val source: String,
val complete: Boolean,
val fields: List<FieldSpec>
)
sourceSets {
main {
resources.srcDir(generatedAutismResourcesDir)
}
}
val generateVanillaUiAssets by tasks.registering {
// Semantic feature icons used by the vanilla-friendly UI. Structural
// actions such as close and reorder are rendered as text symbols.
val iconSourceDir = file("assets/icons")
val outputDir = generatedAutismResourcesDir.map { it.dir("assets/autismclient") }
inputs.dir(iconSourceDir)
outputs.dir(outputDir)
doLast {
val targetRoot = outputDir.get().asFile
targetRoot.parentFile.resolve("yu" + "ng" + "light").deleteRecursively()
targetRoot.deleteRecursively()
val iconTargetDir = targetRoot.resolve("textures/gui/vanillaui/icons")
iconTargetDir.mkdirs()
val pngTranscoderClass = Class.forName("org.apache.batik.transcoder.image.PNGTranscoder")
val transcoderInputClass = Class.forName("org.apache.batik.transcoder.TranscoderInput")
val transcoderOutputClass = Class.forName("org.apache.batik.transcoder.TranscoderOutput")
val transcodingHintsKeyClass = Class.forName("org.apache.batik.transcoder.TranscodingHints\$Key")
val transcoder = pngTranscoderClass.getDeclaredConstructor().newInstance()
val widthField = pngTranscoderClass.getField("KEY_WIDTH")
val heightField = pngTranscoderClass.getField("KEY_HEIGHT")
val addHint = pngTranscoderClass.getMethod("addTranscodingHint", transcodingHintsKeyClass, Any::class.java)
addHint.invoke(transcoder, widthField.get(null), 256f)
addHint.invoke(transcoder, heightField.get(null), 256f)
val inputCtor = transcoderInputClass.getConstructor(String::class.java)
val outputCtor = transcoderOutputClass.getConstructor(OutputStream::class.java)
val transcode = pngTranscoderClass.getMethod("transcode", transcoderInputClass, transcoderOutputClass)
iconSourceDir.listFiles { file -> file.isFile && file.extension.equals("svg", ignoreCase = true) }
?.sortedBy { it.name.lowercase() }
?.forEach { svg ->
val outputFile = iconTargetDir.resolve(svg.nameWithoutExtension.lowercase() + ".png")
outputFile.outputStream().use { out ->
val input = inputCtor.newInstance(svg.toURI().toString())
val output = outputCtor.newInstance(out)
transcode.invoke(transcoder, input, output)
}
}
}
}
val generateAutismInspectorMappings by tasks.registering {
val mappingFiles = fileTree(".gradle/loom-cache/source_mappings") {
include("**/*.tiny")
}
val outputFile = generatedAutismResourcesDir.map { it.file("autism-inspector-mappings.tsv") }
inputs.files(mappingFiles)
outputs.file(outputFile)
doLast {
run {
val target = outputFile.get().asFile
target.parentFile.mkdirs()
target.writeText(
"# Official Mojang mappings are used for Minecraft 26.1.2; no Yarn aliases are generated.\n",
Charsets.UTF_8
)
return@doLast
}
val tinyFile = mappingFiles.files
.filter { it.isFile }
.maxByOrNull { it.lastModified() }
?: error("Missing Loom source mappings under ${project.file(".gradle/loom-cache/source_mappings").absolutePath}")
val lines = tinyFile.readLines(Charsets.UTF_8)
val header = lines.firstOrNull { it.startsWith("tiny\t") }
?: error("Invalid tiny mapping file: ${tinyFile.absolutePath}")
val namespaces = header.split('\t').drop(3)
val namedIndex = namespaces.indexOf("named")
val intermediaryIndex = namespaces.indexOf("intermediary")
require(namedIndex >= 0 && intermediaryIndex >= 0) {
"Tiny mapping header must expose named and intermediary namespaces: $header"
}
fun readNamespace(parts: List<String>, baseOffset: Int, namespaceIndex: Int): String {
val index = baseOffset + namespaceIndex
return if (index in parts.indices) parts[index].trim() else ""
}
val namedToIntermediary = linkedMapOf<String, String>()
val classAliases = linkedMapOf<String, String>()
for (raw in lines) {
val trimmed = raw.trimStart('\t')
if (!trimmed.startsWith("c\t")) continue
val parts = trimmed.split('\t')
val namedName = readNamespace(parts, 1, namedIndex)
val intermediaryName = readNamespace(parts, 1, intermediaryIndex)
if (namedName.isBlank() || intermediaryName.isBlank()) continue
namedToIntermediary[namedName] = intermediaryName
classAliases[intermediaryName.replace('/', '.')] = namedName.substringAfterLast('/').replace('$', '.')
}
fun remapDescriptorToIntermediary(descriptor: String): String {
if (descriptor.isBlank()) return descriptor
val classRef = Regex("L([^;]+);")
return classRef.replace(descriptor) { match ->
val namedInternalName = match.groupValues[1]
val intermediaryInternalName = namedToIntermediary[namedInternalName] ?: namedInternalName
"L$intermediaryInternalName;"
}
}
fun storeAlias(
target: MutableMap<String, String>,
ambiguous: MutableSet<String>,
key: String,
alias: String
) {
if (key.isBlank() || alias.isBlank() || ambiguous.contains(key)) return
val existing = target[key]
if (existing == null) {
target[key] = alias
return
}
if (existing != alias) {
target.remove(key)
ambiguous.add(key)
}
}
val fieldAliases = linkedMapOf<String, String>()
val methodAliases = linkedMapOf<String, String>()
val ambiguousFieldKeys = linkedSetOf<String>()
val ambiguousMethodKeys = linkedSetOf<String>()
var currentOwner = ""
for (raw in lines) {
val trimmed = raw.trimStart('\t')
if (trimmed.isBlank()) continue
val parts = trimmed.split('\t')
when (parts.firstOrNull()) {
"c" -> {
currentOwner = readNamespace(parts, 1, intermediaryIndex).replace('/', '.')
}
"f" -> {
if (currentOwner.isBlank()) continue
val descriptor = if (parts.size > 1) remapDescriptorToIntermediary(parts[1]) else ""
val namedName = readNamespace(parts, 2, namedIndex)
val intermediaryName = readNamespace(parts, 2, intermediaryIndex)
if (namedName.isBlank() || intermediaryName.isBlank()) continue
storeAlias(fieldAliases, ambiguousFieldKeys, "$currentOwner#$intermediaryName#$descriptor", namedName)
}
"m" -> {
if (currentOwner.isBlank()) continue
val descriptor = if (parts.size > 1) remapDescriptorToIntermediary(parts[1]) else ""
val namedName = readNamespace(parts, 2, namedIndex)
val intermediaryName = readNamespace(parts, 2, intermediaryIndex)
if (namedName.isBlank() || intermediaryName.isBlank()) continue
if (namedName == "<init>" || namedName == "<clinit>") continue
storeAlias(methodAliases, ambiguousMethodKeys, "$currentOwner#$intermediaryName#$descriptor", namedName)
}
}
}
val authAliasFragments = listOf(
"session", "accesstoken", "refreshtoken", "authtoken",
"clientsession", "playersession", "publicsession"
)
fun isAuthAlias(alias: String): Boolean {
val normalized = alias.lowercase().replace(Regex("[^a-z0-9]"), "")
return authAliasFragments.any { normalized.contains(it) }
}
val filteredClassAliases = classAliases.filter { (_, alias) -> !isAuthAlias(alias) }
val blockedOwners = classAliases.keys.filter { owner ->
val alias = classAliases[owner] ?: return@filter false
isAuthAlias(alias)
}.toSet()
val target = outputFile.get().asFile
target.parentFile.mkdirs()
target.printWriter(Charsets.UTF_8).use { out ->
out.println("# Yarn deobfuscation mappings")
filteredClassAliases.toSortedMap().forEach { (owner, alias) ->
out.println("C\t$owner\t$alias")
}
fieldAliases.toSortedMap().forEach { (key, alias) ->
val parts = key.split('#', limit = 3)
if (parts.size == 3 && !blockedOwners.contains(parts[0]) && !isAuthAlias(alias)) {
out.println("F\t${parts[0]}\t${parts[1]}\t${parts[2]}\t$alias")
}
}
methodAliases.toSortedMap().forEach { (key, alias) ->
val parts = key.split('#', limit = 3)
if (parts.size == 3 && !blockedOwners.contains(parts[0]) && !isAuthAlias(alias)) {
out.println("M\t${parts[0]}\t${parts[1]}\t${parts[2]}\t$alias")
}
}
}
}
}
val generateAutismPacketSchemas by tasks.registering {
val minecraftVersion = libs.versions.minecraft.get()
val outputFile = generatedAutismResourcesDir.map { it.file("autism-packet-schemas.tsv") }
outputs.file(outputFile)
doLast {
fun normalizeWhitespace(value: String): String = value.replace(Regex("\\s+"), " ").trim()
fun splitTopLevelComma(value: String): List<String> {
val out = mutableListOf<String>()
var depth = 0
var start = 0
for (i in value.indices) {
when (value[i]) {
'<', '(', '[', '{' -> depth++
'>', ')', ']', '}' -> if (depth > 0) depth--
',' -> if (depth == 0) {
out += value.substring(start, i).trim()
start = i + 1
}
}
}
val tail = value.substring(start).trim()
if (tail.isNotBlank()) out += tail
return out
}
fun protocolFromPath(path: String): String {
val normalized = path.replace('\\', '/')
val marker = "/network/protocol/"
val idx = normalized.indexOf(marker)
val tail = if (idx >= 0) normalized.substring(idx + marker.length) else normalized.substringAfter("net/minecraft/network/protocol/", "")
return tail.substringBefore('/').ifBlank { "unknown" }
}
fun directionFromName(simpleName: String): String = when {
simpleName.startsWith("Clientbound") -> "S2C"
simpleName.startsWith("Serverbound") -> "C2S"
else -> "ANY"
}
fun kindForType(type: String): String {
val lower = type.lowercase()
return when {
lower == "byte" || lower == "short" || lower == "int" || lower == "long" || lower == "float" || lower == "double" -> "number"
lower == "boolean" -> "boolean"
lower == "string" -> "string"
lower.contains("itemstack") || lower.contains("hashedstack") -> "item"
lower.contains("component") -> "component"
lower.contains("identifier") || lower.contains("resourcekey") -> "identifier"
lower.contains("holder<") || lower == "holder" -> "holder"
lower.contains("blockpos") || lower.contains("chunkpos") -> "position"
lower.contains("vec3") || lower.contains("positionmoverotation") -> "vector"
lower.contains("uuid") -> "uuid"
lower.startsWith("optional<") || lower.contains(".optional<") -> "optional"
lower.startsWith("list<") || lower.startsWith("set<") || lower.contains("list<") || lower.contains("set<") -> "list"
lower.startsWith("map<") || lower.contains("map<") || lower.contains("int2objectmap") -> "map"
lower.contains("bitset") -> "bitset"
lower.contains("enumset") || lower.contains("relative") || lower.contains("containerinput") -> "enum"
else -> "object"
}
}
fun editableFor(kind: String): Boolean = kind in setOf("number", "boolean", "string", "identifier", "enum", "uuid")
fun parseComponent(raw: String): FieldSpec? {
val cleaned = normalizeWhitespace(raw)
.replace(Regex("^@[\\w.]+(?:\\([^)]*\\))?\\s+"), "")
val idx = cleaned.lastIndexOf(' ')
if (idx <= 0 || idx >= cleaned.length - 1) return null
val type = cleaned.substring(0, idx).trim()
val name = cleaned.substring(idx + 1).trim().removeSuffix("...")
if (!name.matches(Regex("[A-Za-z_$][A-Za-z0-9_$]*"))) return null
val kind = kindForType(type)
return FieldSpec(name, type, kind, editableFor(kind))
}
fun parseFields(text: String): Pair<String, List<FieldSpec>> {
val record = Regex("""public\s+record\s+\w+\s*\((.*?)\)\s*implements""", setOf(RegexOption.DOT_MATCHES_ALL))
.find(text)
if (record != null) {
val fields = splitTopLevelComma(record.groupValues[1]).mapNotNull(::parseComponent)
return "record" to fields
}
val fields = Regex("""(?m)^\s*(?:private|protected)\s+final\s+([^;=]+?)\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*;""")
.findAll(text)
.mapNotNull { match ->
val type = normalizeWhitespace(match.groupValues[1])
val name = match.groupValues[2]
val kind = kindForType(type)
FieldSpec(name, type, kind, editableFor(kind))
}
.toList()
return if (fields.isNotEmpty()) "fields" to fields else "fallback" to emptyList()
}
fun loadSources(): List<SourceFile> {
val sourcesJar = file("${System.getProperty("user.home")}/.gradle/caches/fabric-loom/minecraftMaven/net/minecraft/minecraft-merged-deobf/$minecraftVersion/minecraft-merged-deobf-$minecraftVersion-sources.jar")
if (sourcesJar.isFile) {
ZipFile(sourcesJar).use { zip ->
return zip.entries().asSequence()
.filter { !it.isDirectory }
.filter { it.name.startsWith("net/minecraft/network/protocol/") && it.name.endsWith("Packet.java") }
.map { entry ->
SourceFile(entry.name, zip.getInputStream(entry).bufferedReader(Charsets.UTF_8).use { it.readText() })
}
.toList()
}
}
val localRoot = file("mc-src$minecraftVersion/libs/net.minecraft.minecraft-merged-deobf/net/minecraft/network/protocol")
if (localRoot.isDirectory) {
return localRoot.walkTopDown()
.filter { it.isFile && it.name.endsWith("Packet.java") }
.map { file ->
SourceFile(file.relativeTo(localRoot.parentFile.parentFile.parentFile.parentFile).invariantSeparatorsPath, file.readText(Charsets.UTF_8))
}
.toList()
}
error("Missing Minecraft deobf sources jar and local mc-src fallback for $minecraftVersion")
}
fun packetTypeOf(text: String): String {
return Regex("""return\s+([A-Za-z0-9_]+PacketTypes\.[A-Z0-9_]+)\s*;""")
.find(text)
?.groupValues
?.get(1)
?: ""
}
fun codecStyleOf(text: String): String = when {
text.contains("StreamCodec.unit") -> "UNIT"
text.contains("StreamCodec.composite") -> "COMPOSITE"
text.contains("Packet.codec") -> "PACKET_CODEC"
else -> "CUSTOM"
}
fun escape(value: String): String = value
.replace('\t', ' ')
.replace('\n', ' ')
.replace('|', '/')
.replace('~', '-')
val specs = loadSources().mapNotNull { source ->
val pkg = Regex("""package\s+([A-Za-z0-9_.]+)\s*;""").find(source.text)?.groupValues?.get(1) ?: return@mapNotNull null
val simpleName = Regex("""public\s+(?:abstract\s+)?(?:record|class)\s+([A-Za-z0-9_]+Packet)\b""")
.find(source.text)
?.groupValues
?.get(1)
?: return@mapNotNull null
val codecStyle = codecStyleOf(source.text)
val parsed = parseFields(source.text)
val sourceKind = if (codecStyle == "UNIT") "unit" else parsed.first
val complete = codecStyle == "UNIT" || parsed.second.isNotEmpty()
PacketSpec(
"$pkg.$simpleName",
protocolFromPath(source.path),
directionFromName(simpleName),
codecStyle,
packetTypeOf(source.text),
sourceKind,
complete,
if (codecStyle == "UNIT") emptyList() else parsed.second
)
}.sortedBy { it.className }
val target = outputFile.get().asFile
target.parentFile.mkdirs()
target.printWriter(Charsets.UTF_8).use { out ->
out.println("# Generated from Minecraft $minecraftVersion packet sources. Fields preserve source/record order where available.")
out.println("# class\tprotocol\tdirection\tcodec\tpacketType\tsource\tcomplete\tfields(name~type~kind~editable|...)")
for (spec in specs) {
val fields = spec.fields.joinToString("|") { field ->
listOf(field.name, field.type, field.kind, field.editable.toString()).joinToString("~", transform = ::escape)
}
val columns = listOf(
spec.className,
spec.protocol,
spec.direction,
spec.codecStyle,
spec.packetType,
spec.source,
spec.complete.toString()
).joinToString("\t", transform = ::escape)
out.println("$columns\t$fields")
}
}
}
}
tasks {
processResources {
dependsOn(generateAutismInspectorMappings)
dependsOn(generateAutismPacketSchemas)
dependsOn(generateVanillaUiAssets)
val propertyMap = mapOf(
"version" to project.version,
"mc_version" to libs.versions.minecraft.get()
)
inputs.properties(propertyMap)
filteringCharset = "UTF-8"
exclude("addon-template.mixins.json")
exclude("assets/template/**")
filesMatching("fabric.mod.json") {
expand(propertyMap)
}
}
jar {
inputs.property("archivesName", project.base.archivesName.get())
from("LICENSE") {
rename { "${it}_${inputs.properties["archivesName"]}" }
}
// ModMenu API is a compile-only soft dependency: we ship local stubs of its two API
// interfaces so we can compile the integration without a cross-version ModMenu artifact, but
// we must NOT bundle them — at runtime the real ModMenu provides them (and if ModMenu is
// absent, our integration entrypoint is simply never loaded).
exclude("com/terraformersmc/**")
}
java {
sourceCompatibility = JavaVersion.VERSION_25
targetCompatibility = JavaVersion.VERSION_25
toolchain {
languageVersion.set(JavaLanguageVersion.of(25))
}
}
withType<JavaCompile> {
options.encoding = "UTF-8"
options.release.set(25)
options.compilerArgs.add("-Xlint:deprecation")
options.compilerArgs.add("-Xlint:unchecked")
options.compilerArgs.add("-Xlint:-restricted")
}
}
// Publish the Loom-remapped jar to the local Maven repo so the standalone addon-template (and any
// third-party addon) can depend on it via `modImplementation("com.autismclient:autism:<version>")`.
// Run: ./gradlew publishToMavenLocal
publishing {
publications {
create<MavenPublication>("mavenJava") {
groupId = "com.autismclient"
artifactId = "autism"
version = project.version.toString()
from(components["java"])
}
}
repositories {
mavenLocal()
}
}

5
gradle.properties Normal file
View file

@ -0,0 +1,5 @@
org.gradle.jvmargs=-Xmx2G
org.gradle.configuration-cache=false
maven_group=com.autismclient
archives_base_name=AUTISM Client

17
gradle/libs.versions.toml Normal file
View file

@ -0,0 +1,17 @@
[versions]
mod-version = "2.5"
minecraft = "26.1.2"
fabric-loader = "0.18.4"
fabric-api = "0.147.0+26.1.2"
loom = "1.16-SNAPSHOT"
[libraries]
minecraft = { module = "com.mojang:minecraft", version.ref = "minecraft" }
fabric-loader = { module = "net.fabricmc:fabric-loader", version.ref = "fabric-loader" }
fabric-api = { module = "net.fabricmc.fabric-api:fabric-api", version.ref = "fabric-api" }
[plugins]
fabric-loom = { id = "net.fabricmc.fabric-loom", version.ref = "loom" }

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View file

@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.0-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

248
gradlew vendored Normal file
View file

@ -0,0 +1,248 @@
#!/bin/sh
#
# Copyright © 2015 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

93
gradlew.bat vendored Normal file
View file

@ -0,0 +1,93 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

12
settings.gradle.kts Normal file
View file

@ -0,0 +1,12 @@
pluginManagement {
repositories {
maven {
name = "Fabric"
url = uri("https://maven.fabricmc.net/")
}
mavenCentral()
gradlePluginPortal()
}
}
rootProject.name = "YungLightUI"

View file

@ -0,0 +1,17 @@
package autismclient;
import com.mojang.logging.LogUtils;
import net.fabricmc.loader.api.FabricLoader;
import org.slf4j.Logger;
public final class AutismClientAddon {
public static final Logger LOG = LogUtils.getLogger();
public static final String MOD_ID = "autism";
public static final java.io.File FOLDER = FabricLoader.getInstance().getConfigDir().resolve("autism").toFile();
static {
FOLDER.mkdirs();
}
private AutismClientAddon() {}
}

View file

@ -0,0 +1,102 @@
package autismclient;
import autismclient.gui.vanillaui.components.UiText;
import autismclient.modules.PackAutoReconnectState;
import autismclient.modules.AutismModule;
import autismclient.security.AutismProtector;
import autismclient.security.AutismProtectorPackStrip;
import autismclient.security.AutismProtectorServerPackFailureGuard;
import autismclient.security.AutismProtectorTracker;
import autismclient.security.AutismProtectorVanillaKeys;
import autismclient.util.AutismInstaBreakRenderer;
import autismclient.util.AutismFakeGamemode;
import autismclient.util.AutismJoinMacroController;
import autismclient.util.AutismLANSync;
import autismclient.util.AutismOverlayManager;
import autismclient.util.AutismSvgHudLogo;
import autismclient.util.AutismWindowBranding;
import autismclient.util.AutismSharedState;
import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents;
import net.fabricmc.fabric.api.client.item.v1.ItemTooltipCallback;
import net.fabricmc.fabric.api.client.networking.v1.ClientConfigurationConnectionEvents;
import net.fabricmc.fabric.api.client.networking.v1.ClientPlayConnectionEvents;
import net.fabricmc.fabric.api.resource.ResourceManagerHelper;
import net.minecraft.server.packs.PackType;
public final class AutismClientMod implements ClientModInitializer {
@Override
@SuppressWarnings("deprecation")
public void onInitializeClient() {
AutismClientAddon.FOLDER.mkdirs();
AutismModule.get().initialize();
AutismProtectorTracker.bootstrap();
if (!AutismProtector.isOverlapExternalProtectorPresent()) {
AutismProtectorVanillaKeys.primeAsync();
}
if (AutismProtector.isFullExternalProtectorPresent()) {
AutismClientAddon.LOG.info(
"[AutismProtector] External protection mod detected; deferring all anti-fingerprint mixins to it.");
} else if (AutismProtector.isExploitPreventerPresent()) {
AutismClientAddon.LOG.info(
"[AutismProtector] ExploitPreventer detected; deferring overlapping protections while keeping brand/channel hiding active.");
} else {
AutismClientAddon.LOG.info(
"[AutismProtector] Built-in anti-fingerprint layer active.");
}
AutismInstaBreakRenderer.initialize();
autismclient.commands.AutismCommands.init();
autismclient.addons.AddonManager.init();
ResourceManagerHelper.get(PackType.CLIENT_RESOURCES).registerReloadListener(new net.fabricmc.fabric.api.resource.SimpleSynchronousResourceReloadListener() {
@Override
public net.minecraft.resources.Identifier getFabricId() {
return net.minecraft.resources.Identifier.fromNamespaceAndPath("autismclient", "ui_assets");
}
@Override
public void onResourceManagerReload(net.minecraft.server.packs.resources.ResourceManager manager) {
UiText.onClientResourceReload();
AutismSvgHudLogo.clear();
}
});
ClientTickEvents.END_CLIENT_TICK.register(client -> {
AutismInstaBreakRenderer.tickPlacePreview();
AutismWindowBranding.apply(client);
AutismModule.get().tick();
AutismJoinMacroController.onClientTick(client);
});
ClientTickEvents.END_LEVEL_TICK.register(level -> AutismLANSync.getInstance().onLevelTick(level.getGameTime()));
ClientConfigurationConnectionEvents.INIT.register((listener, client) -> AutismModule.get().onConfigurationConnectionStarted());
ClientConfigurationConnectionEvents.DISCONNECT.register((listener, client) -> {
AutismFakeGamemode.clear();
AutismInstaBreakRenderer.clear();
AutismProtectorServerPackFailureGuard.clear();
AutismOverlayManager.get().hideAllInteractiveOverlays();
AutismModule.get().onGameLeft();
});
ClientPlayConnectionEvents.JOIN.register((handler, sender, client) -> {
PackAutoReconnectState.remember(client.getCurrentServer());
AutismModule.get().onGameJoin();
AutismJoinMacroController.onPlayJoin();
autismclient.addons.AddonManager.surfaceFailuresOnJoin();
});
ClientPlayConnectionEvents.DISCONNECT.register((handler, client) -> {
AutismFakeGamemode.clear();
AutismInstaBreakRenderer.clear();
AutismProtectorPackStrip.clearAll();
AutismProtectorServerPackFailureGuard.clear();
AutismOverlayManager.get().hideAllInteractiveOverlays();
AutismJoinMacroController.onGameLeft();
AutismModule.get().onGameLeft();
});
ItemTooltipCallback.EVENT.register((stack, tooltipContext, tooltipType, lines) ->
AutismModule.get().appendTooltip(stack, lines)
);
}
}

View file

@ -0,0 +1,507 @@
package autismclient.addons;
import autismclient.AutismClientAddon;
import autismclient.api.ApiVersion;
import autismclient.api.AutismAddon;
import autismclient.util.AutismConfig;
import autismclient.util.AutismNotifications;
import net.fabricmc.loader.api.FabricLoader;
import net.fabricmc.loader.api.ModContainer;
import net.fabricmc.loader.api.entrypoint.EntrypointContainer;
import net.fabricmc.loader.api.metadata.CustomValue;
import net.fabricmc.loader.api.metadata.ModMetadata;
import net.fabricmc.loader.api.metadata.Person;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.stream.Collectors;
public final class AddonManager {
private static final int MAX_UI_ADDON_NAME_LENGTH = 22;
private static final List<AutismAddon> LOADED = new ArrayList<>();
private static final Map<String, AddonReport> REPORTS = new LinkedHashMap<>();
private static String currentAddonId = null;
private static String currentAddonName = null;
private static boolean failuresSurfaced = false;
private AddonManager() {}
public static void init() {
LOADED.clear();
REPORTS.clear();
failuresSurfaced = false;
AutismConfig config = AutismConfig.getGlobal();
List<LoadedAddon> accepted = new ArrayList<>();
for (EntrypointContainer<AutismAddon> container : FabricLoader.getInstance()
.getEntrypointContainers("autism", AutismAddon.class)) {
ModContainer mod;
try {
mod = container.getProvider();
} catch (Throwable t) {
AutismClientAddon.LOG.error("[Addons] Failed to inspect an addon entrypoint", t);
continue;
}
String modId = mod.getMetadata().getId();
AddonReport report = ensureReport(mod.getMetadata());
if (isDisabledOnRestart(modId)) {
report.markDisabled("Disabled in AUTISM config. Enable it and restart to load.");
continue;
}
AutismAddon addon;
try {
addon = container.getEntrypoint();
} catch (Throwable t) {
report.markFailed("construct", "Failed to construct entrypoint: " + shortError(t));
AutismClientAddon.LOG.error("[Addons] Failed to construct addon '{}'", modId, t);
continue;
}
try {
int declared = addon.apiVersion();
report.setApiVersion(declared);
if (declared <= 0) {
report.markFailed("apiVersion", "Invalid API version " + declared + ".");
AutismClientAddon.LOG.warn("[Addons] Addon '{}' declared invalid API v{}; skipping it.", modId, declared);
continue;
}
if (declared > ApiVersion.CURRENT) {
report.markNeedsNewerApi("Needs API v" + declared + ", host provides v" + ApiVersion.CURRENT + ".");
AutismClientAddon.LOG.warn("[Addons] Addon '{}' needs API v{} but this client provides v{}; skipping it.",
modId, declared, ApiVersion.CURRENT);
continue;
}
if (declared < ApiVersion.CURRENT) {
AutismClientAddon.LOG.info("[Addons] Addon '{}' built against API v{} (current v{}); loading.",
modId, declared, ApiVersion.CURRENT);
}
applyMetadata(addon, mod.getMetadata());
report.copyRuntimeMetadata(addon);
accepted.add(new LoadedAddon(modId, addon));
} catch (AbstractMethodError e) {
report.markMissingApiVersion("Missing apiVersion() override.");
AutismClientAddon.LOG.error("[Addons] Addon '{}' does not declare apiVersion(); skipping it.", modId, e);
} catch (Throwable t) {
report.markFailed("prepare", "Failed to prepare: " + shortError(t));
AutismClientAddon.LOG.error("[Addons] Error preparing addon '{}'", modId, t);
}
}
List<LoadedAddon> categoryReady = new ArrayList<>();
for (LoadedAddon la : accepted) {
if (runPhase(la, "onRegisterCategories", la.addon::onRegisterCategories)) {
categoryReady.add(la);
} else {
rollbackRegistrations(la.modId);
}
}
for (LoadedAddon la : categoryReady) {
if (runPhase(la, "onInitialize", la.addon::onInitialize)) {
LOADED.add(la.addon);
AddonReport report = REPORTS.get(la.modId);
if (report != null) report.markLoaded();
} else {
rollbackRegistrations(la.modId);
}
}
if (!LOADED.isEmpty()) {
AutismClientAddon.LOG.info("[Addons] Loaded {} addon(s).", LOADED.size());
}
if (config.disabledAddonIds != null) {
for (String id : config.disabledAddonIds) {
if (id == null || id.isBlank() || REPORTS.containsKey(id)) continue;
AddonReport report = new AddonReport(id.trim(), id.trim(), "", "", 0xFFAA66FF);
report.markDisabled("Disabled in AUTISM config, but no matching addon entrypoint was discovered.");
REPORTS.put(report.modId(), report);
}
}
}
private static boolean runPhase(LoadedAddon la, String phase, Runnable body) {
currentAddonId = la.modId;
currentAddonName = la.addon.name == null || la.addon.name.isBlank() ? la.modId : la.addon.name;
AddonReport report = REPORTS.get(la.modId);
if (report != null) report.setPhase(phase);
try {
body.run();
return true;
} catch (Throwable t) {
if (report != null) report.markFailed(phase, "Threw during " + phase + ": " + shortError(t));
AutismClientAddon.LOG.error("[Addons] Addon '{}' threw during {}", la.modId, phase, t);
return false;
} finally {
currentAddonId = null;
currentAddonName = null;
}
}
private static void rollbackRegistrations(String addonId) {
if (addonId == null || addonId.isBlank()) return;
AddonReport report = REPORTS.get(addonId);
rollbackStep(addonId, report, "macro actions", () -> autismclient.api.macro.MacroActionRegistry.unregisterAddon(addonId));
rollbackStep(addonId, report, "presets", () -> autismclient.api.macro.MacroPresetRegistry.unregisterAddon(addonId));
rollbackStep(addonId, report, "events", () -> autismclient.api.event.AddonEvents.unregisterAddon(addonId));
rollbackStep(addonId, report, "hud", () -> autismclient.api.hud.HudElements.unregisterAddon(addonId));
rollbackStep(addonId, report, "modules", () -> autismclient.modules.PackModuleRegistry.unregisterAddonModules(addonId));
rollbackStep(addonId, report, "commands", () -> autismclient.commands.AutismCommands.unregisterAddonCommands(addonId));
if (report != null) report.addRollback("Rolled back partial registrations after load failure.");
}
private static void rollbackStep(String addonId, AddonReport report, String kind, Runnable body) {
try {
body.run();
} catch (Throwable t) {
String detail = "Failed to rollback " + kind + ": " + shortError(t);
if (report != null) report.addRollback(detail);
AutismClientAddon.LOG.warn("[Addons] Addon '{}' rollback failed for {}", addonId, kind, t);
}
}
private static AddonReport ensureReport(ModMetadata meta) {
String modId = meta.getId();
AddonReport existing = REPORTS.get(modId);
if (existing != null) return existing;
AddonReport report = new AddonReport(
modId,
meta.getName() == null || meta.getName().isBlank() ? modId : meta.getName(),
meta.getVersion().getFriendlyString(),
meta.getAuthors().stream().map(Person::getName).collect(Collectors.joining(", ")),
metadataColor(meta, 0xFFAA66FF)
);
REPORTS.put(modId, report);
return report;
}
private static void applyMetadata(AutismAddon addon, ModMetadata meta) {
addon.name = meta.getName();
addon.authors = meta.getAuthors().stream().map(Person::getName).collect(Collectors.joining(", "));
addon.color = metadataColor(meta, addon.color);
}
private static int metadataColor(ModMetadata meta, int fallback) {
CustomValue color = meta.containsCustomValue("autism:color") ? meta.getCustomValue("autism:color") : null;
if (color != null && color.getType() == CustomValue.CvType.STRING) {
return parseColor(color.getAsString(), fallback);
}
return fallback;
}
private static int parseColor(String raw, int fallback) {
try {
String[] parts = raw.split(",");
if (parts.length != 3) return fallback;
int r = clamp(Integer.parseInt(parts[0].trim()));
int g = clamp(Integer.parseInt(parts[1].trim()));
int b = clamp(Integer.parseInt(parts[2].trim()));
return 0xFF000000 | (r << 16) | (g << 8) | b;
} catch (Exception e) {
return fallback;
}
}
private static int clamp(int v) { return Math.max(0, Math.min(255, v)); }
public static String currentAddonId() {
return currentAddonId;
}
public static boolean isLifecycleActive() {
return currentAddonId != null && !currentAddonId.isBlank();
}
public static String currentAddonName() {
return currentAddonName;
}
public static String normalizedAddonName(String name, String fallback) {
String value = name == null ? "" : name.replaceAll("\\s+", " ").trim();
if (value.isBlank()) value = fallback == null ? "" : fallback.replaceAll("\\s+", " ").trim();
return value.isBlank() ? "Addon" : value;
}
public static String compactAddonName(String name, String fallback) {
String value = normalizedAddonName(name, fallback);
if (value.length() <= MAX_UI_ADDON_NAME_LENGTH) return value;
return value.substring(0, Math.max(1, MAX_UI_ADDON_NAME_LENGTH - 3)).trim() + "...";
}
public static String scopedId(String rawId) {
String raw = rawId == null ? "" : rawId.trim();
if (raw.contains(":")) return raw;
String owner = currentAddonId;
if (owner == null || owner.isBlank()) return raw;
return owner + ":" + raw;
}
public static String scopedCategoryLabel(String customLabel) {
String name = currentAddonName;
if (name == null || name.isBlank()) name = currentAddonId;
return compactAddonName(name, currentAddonId);
}
public static List<AutismAddon> loaded() {
return Collections.unmodifiableList(LOADED);
}
public static List<AddonReport> reports() {
return Collections.unmodifiableList(new ArrayList<>(REPORTS.values()));
}
public static AddonReport report(String addonId) {
return addonId == null ? null : REPORTS.get(addonId);
}
public static File modsFolder() {
return FabricLoader.getInstance().getGameDir().resolve("mods").toFile();
}
public static boolean isDisabledOnRestart(String addonId) {
if (addonId == null || addonId.isBlank()) return false;
AutismConfig config = AutismConfig.getGlobal();
if (config.disabledAddonIds == null) return false;
String needle = addonId.trim().toLowerCase(Locale.ROOT);
for (String id : config.disabledAddonIds) {
if (id != null && needle.equals(id.trim().toLowerCase(Locale.ROOT))) return true;
}
return false;
}
public static void setDisabledOnRestart(String addonId, boolean disabled) {
if (addonId == null || addonId.isBlank()) return;
AutismConfig config = AutismConfig.getGlobal();
if (config.disabledAddonIds == null) config.disabledAddonIds = new ArrayList<>();
String normalized = addonId.trim();
boolean currently = isDisabledOnRestart(normalized);
if (disabled && !currently) {
config.disabledAddonIds.add(normalized);
} else if (!disabled && currently) {
config.disabledAddonIds.removeIf(id -> id != null && normalized.equalsIgnoreCase(id.trim()));
}
config.save();
}
public static void recordAcceptedRegistration(String kind, String id) {
AddonReport report = REPORTS.get(currentAddonId);
if (report != null) report.recordAccepted(kind, id);
}
public static void recordRejectedRegistration(String addonId, String kind, String id, String reason) {
AddonReport report = REPORTS.get(addonId == null || addonId.isBlank() ? currentAddonId : addonId);
if (report != null) report.recordRejected(kind, id, reason);
}
public static void recordRuntimeError(String addonId, String detail) {
AddonReport report = REPORTS.get(addonId);
if (report != null) report.recordRuntimeError(detail);
}
public static void surfaceFailuresOnJoin() {
if (failuresSurfaced) return;
int issues = issueCount();
if (issues <= 0) return;
failuresSurfaced = true;
AutismNotifications.warning(issues + " addon issue(s). Open Addons for details.");
}
private static int issueCount() {
int count = 0;
for (AddonReport report : REPORTS.values()) {
if (report.status().isIssue()) count++;
}
return count;
}
private static String shortError(Throwable t) {
if (t == null) return "Unknown error";
String msg = t.getMessage();
return msg == null || msg.isBlank() ? t.getClass().getSimpleName() : t.getClass().getSimpleName() + ": " + msg;
}
private record LoadedAddon(String modId, AutismAddon addon) {}
public enum AddonLoadStatus {
LOADED("Loaded", false),
DISABLED("Disabled on restart", false),
FAILED("Failed", true),
NEEDS_NEWER_API("Needs newer API", true),
MISSING_API_VERSION("Missing apiVersion", true);
private final String label;
private final boolean issue;
AddonLoadStatus(String label, boolean issue) {
this.label = label;
this.issue = issue;
}
public String label() { return label; }
public boolean isIssue() { return issue; }
}
public static final class AddonReport {
private final String modId;
private String name;
private String version;
private String authors;
private int color;
private int apiVersion = -1;
private int hostApiVersion = ApiVersion.CURRENT;
private AddonLoadStatus status = AddonLoadStatus.FAILED;
private String phase = "discovered";
private String failureReason = "";
private final Map<String, Integer> accepted = new LinkedHashMap<>();
private final Map<String, Integer> rejected = new LinkedHashMap<>();
private final List<String> rejectionDetails = new ArrayList<>();
private final List<String> rollbackDetails = new ArrayList<>();
private int runtimeErrors;
private String lastRuntimeError = "";
private AddonReport(String modId, String name, String version, String authors, int color) {
this.modId = modId == null ? "" : modId;
this.name = name == null || name.isBlank() ? this.modId : name;
this.version = version == null ? "" : version;
this.authors = authors == null ? "" : authors;
this.color = color;
}
private void copyRuntimeMetadata(AutismAddon addon) {
if (addon == null) return;
if (addon.name != null && !addon.name.isBlank()) this.name = addon.name;
if (addon.authors != null && !addon.authors.isBlank()) this.authors = addon.authors;
this.color = addon.color;
}
private void setApiVersion(int apiVersion) {
this.apiVersion = apiVersion;
}
private void setPhase(String phase) {
this.phase = phase == null || phase.isBlank() ? this.phase : phase;
}
private void markLoaded() {
this.status = AddonLoadStatus.LOADED;
this.phase = "loaded";
this.failureReason = "";
}
private void markDisabled(String reason) {
this.status = AddonLoadStatus.DISABLED;
this.phase = "disabled";
this.failureReason = reason == null ? "" : reason;
}
private void markFailed(String phase, String reason) {
this.status = AddonLoadStatus.FAILED;
this.phase = phase == null || phase.isBlank() ? "failed" : phase;
this.failureReason = reason == null ? "" : reason;
}
private void markNeedsNewerApi(String reason) {
this.status = AddonLoadStatus.NEEDS_NEWER_API;
this.phase = "apiVersion";
this.failureReason = reason == null ? "" : reason;
}
private void markMissingApiVersion(String reason) {
this.status = AddonLoadStatus.MISSING_API_VERSION;
this.phase = "apiVersion";
this.failureReason = reason == null ? "" : reason;
}
private void recordAccepted(String kind, String id) {
String key = kind == null || kind.isBlank() ? "item" : kind;
accepted.merge(key, 1, Integer::sum);
}
private void recordRejected(String kind, String id, String reason) {
String key = kind == null || kind.isBlank() ? "item" : kind;
rejected.merge(key, 1, Integer::sum);
String detail = key + (id == null || id.isBlank() ? "" : " " + id) + ": "
+ (reason == null || reason.isBlank() ? "rejected" : reason);
rejectionDetails.add(detail);
}
private void addRollback(String detail) {
if (detail != null && !detail.isBlank()) rollbackDetails.add(detail);
}
private void recordRuntimeError(String detail) {
runtimeErrors++;
lastRuntimeError = detail == null || detail.isBlank() ? "Runtime error" : detail;
}
public String modId() { return modId; }
public String name() { return name; }
public String version() { return version; }
public String authors() { return authors; }
public int color() { return color; }
public int apiVersion() { return apiVersion; }
public int hostApiVersion() { return hostApiVersion; }
public AddonLoadStatus status() { return status; }
public String phase() { return phase; }
public String failureReason() { return failureReason; }
public int runtimeErrors() { return runtimeErrors; }
public String lastRuntimeError() { return lastRuntimeError; }
public Map<String, Integer> accepted() { return Collections.unmodifiableMap(accepted); }
public Map<String, Integer> rejected() { return Collections.unmodifiableMap(rejected); }
public List<String> rejectionDetails() { return Collections.unmodifiableList(rejectionDetails); }
public List<String> rollbackDetails() { return Collections.unmodifiableList(rollbackDetails); }
public int acceptedTotal() {
int total = 0;
for (int value : accepted.values()) total += value;
return total;
}
public int rejectedTotal() {
int total = 0;
for (int value : rejected.values()) total += value;
return total;
}
public String summaryCounts() {
if (accepted.isEmpty()) return "No registered extensions";
List<String> parts = new ArrayList<>();
for (Map.Entry<String, Integer> entry : accepted.entrySet()) {
parts.add(entry.getValue() + " " + entry.getKey());
}
return String.join(", ", parts);
}
public String copyReport() {
StringBuilder sb = new StringBuilder();
sb.append("Addon: ").append(name).append('\n');
sb.append("ID: ").append(modId).append('\n');
if (!version.isBlank()) sb.append("Version: ").append(version).append('\n');
if (!authors.isBlank()) sb.append("Authors: ").append(authors).append('\n');
sb.append("Status: ").append(status.label()).append('\n');
sb.append("Phase: ").append(phase).append('\n');
sb.append("API: addon v").append(apiVersion < 0 ? "unknown" : Integer.toString(apiVersion))
.append(", host v").append(hostApiVersion).append('\n');
sb.append("Disabled on restart: ").append(isDisabledOnRestart(modId)).append('\n');
if (!failureReason.isBlank()) sb.append("Reason: ").append(failureReason).append('\n');
sb.append("Accepted: ").append(accepted).append('\n');
if (!rejected.isEmpty()) sb.append("Rejected: ").append(rejected).append('\n');
for (String detail : rejectionDetails) sb.append("- ").append(detail).append('\n');
for (String detail : rollbackDetails) sb.append("- ").append(detail).append('\n');
if (runtimeErrors > 0) {
sb.append("Runtime errors: ").append(runtimeErrors).append('\n');
sb.append("Last runtime error: ").append(lastRuntimeError).append('\n');
}
return sb.toString();
}
}
}

View file

@ -0,0 +1,15 @@
package autismclient.api;
public record AddonRegistrationResult(boolean accepted, String kind, String id, String reason) {
public static AddonRegistrationResult accepted(String kind, String id) {
return new AddonRegistrationResult(true, clean(kind), clean(id), "Accepted");
}
public static AddonRegistrationResult rejected(String kind, String id, String reason) {
return new AddonRegistrationResult(false, clean(kind), clean(id), clean(reason));
}
private static String clean(String value) {
return value == null || value.isBlank() ? "" : value.trim();
}
}

View file

@ -0,0 +1,8 @@
package autismclient.api;
public final class ApiVersion {
public static final int CURRENT = 1;
private ApiVersion() {}
}

View file

@ -0,0 +1,18 @@
package autismclient.api;
public abstract class AutismAddon {
public String name = "";
public String authors = "";
public int color = 0xFFFFFFFF;
public abstract int apiVersion();
public void onRegisterCategories() {}
public abstract void onInitialize();
public abstract String getPackage();
}

View file

@ -0,0 +1,147 @@
package autismclient.api;
import autismclient.addons.AddonManager;
import autismclient.api.event.AddonEvents;
import autismclient.api.hud.HudElementProvider;
import autismclient.api.hud.HudElements;
import autismclient.api.macro.MacroActionEntry;
import autismclient.api.macro.MacroActionRegistry;
import autismclient.api.macro.MacroPresetRegistry;
import autismclient.commands.Command;
import autismclient.modules.PackModule;
import autismclient.modules.PackModuleCategory;
import autismclient.modules.PackModuleRegistry;
import autismclient.util.macro.MacroAction;
import net.minecraft.client.Minecraft;
import net.minecraft.network.protocol.Packet;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.Supplier;
public final class AutismAddons {
private AutismAddons() {}
public static Modules modules() { return Modules.INSTANCE; }
public static Commands commands() { return Commands.INSTANCE; }
public static MacroActions macroActions() { return MacroActions.INSTANCE; }
public static Presets presets() { return Presets.INSTANCE; }
public static Hud hud() { return Hud.INSTANCE; }
public static Events events() { return Events.INSTANCE; }
public static List<AutismAddon> list() { return AddonManager.loaded(); }
public static String id(String localId) { return AddonManager.scopedId(localId); }
public static final class Modules {
static final Modules INSTANCE = new Modules();
private Modules() {}
public boolean register(PackModule module) {
return PackModuleRegistry.registerAddonModule(module, AddonManager.currentAddonId());
}
public AddonRegistrationResult registerDetailed(PackModule module) {
return PackModuleRegistry.registerAddonModuleDetailed(module, AddonManager.currentAddonId());
}
public PackModuleCategory autoCategory() {
return PackModuleCategory.registerAddon(AddonManager.currentAddonId(),
AddonManager.scopedCategoryLabel(null));
}
public PackModuleCategory registerCategory(String label) {
return PackModuleCategory.registerAddon(AddonManager.currentAddonId(),
AddonManager.scopedCategoryLabel(label));
}
}
public static final class Commands {
static final Commands INSTANCE = new Commands();
private Commands() {}
public void register(Command command) {
autismclient.commands.AutismCommands.registerAddonCommand(command, AddonManager.currentAddonId());
}
public AddonRegistrationResult registerDetailed(Command command) {
return autismclient.commands.AutismCommands.registerAddonCommandDetailed(command, AddonManager.currentAddonId());
}
}
public static final class MacroActions {
static final MacroActions INSTANCE = new MacroActions();
private MacroActions() {}
public boolean register(MacroActionEntry entry) {
return MacroActionRegistry.register(entry);
}
public AddonRegistrationResult registerDetailed(MacroActionEntry entry) {
return MacroActionRegistry.registerDetailed(entry);
}
public void registerCategory(String id, String label, int color) {
MacroActionRegistry.registerScopedCategory(id, label, color);
}
}
public static final class Presets {
static final Presets INSTANCE = new Presets();
private Presets() {}
public void registerCategory(String id, String label) {
MacroPresetRegistry.registerScopedCategory(id, label);
}
public void register(String label, String tip, Supplier<List<MacroAction>> builder) {
MacroPresetRegistry.register(MacroPresetRegistry.ensureScopedCategory(null), label, tip, builder);
}
public AddonRegistrationResult registerDetailed(String label, String tip, Supplier<List<MacroAction>> builder) {
return MacroPresetRegistry.registerDetailed(MacroPresetRegistry.ensureScopedCategory(null), label, tip, builder);
}
public void register(String categoryId, String label, String tip, Supplier<List<MacroAction>> builder) {
MacroPresetRegistry.register(MacroPresetRegistry.ensureScopedCategory(categoryId), label, tip, builder);
}
public AddonRegistrationResult registerDetailed(String categoryId, String label, String tip, Supplier<List<MacroAction>> builder) {
return MacroPresetRegistry.registerDetailed(MacroPresetRegistry.ensureScopedCategory(categoryId), label, tip, builder);
}
}
public static final class Hud {
static final Hud INSTANCE = new Hud();
private Hud() {}
public boolean register(HudElementProvider provider) {
return HudElements.register(provider);
}
public AddonRegistrationResult registerDetailed(HudElementProvider provider) {
return HudElements.registerDetailed(provider);
}
}
public static final class Events {
static final Events INSTANCE = new Events();
private Events() {}
public void onTick(Consumer<Minecraft> listener) { AddonEvents.onTick(listener); }
public void onPacketSend(Predicate<Packet<?>> listener) { AddonEvents.onPacketSend(listener); }
public void onPacketReceive(Consumer<Packet<?>> listener) { AddonEvents.onPacketReceive(listener); }
public void onGameJoin(Runnable listener) { AddonEvents.onGameJoin(listener); }
public void onGameLeft(Runnable listener) { AddonEvents.onGameLeft(listener); }
}
}

View file

@ -0,0 +1,84 @@
package autismclient.api;
import autismclient.api.macro.MacroActionEntry;
import autismclient.api.macro.MacroPresetRegistry;
import autismclient.api.macro.SimpleAction;
import autismclient.api.macro.SimpleCondition;
import autismclient.modules.PackModule;
import autismclient.util.macro.MacroAction;
import net.minecraft.client.Minecraft;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.Supplier;
public abstract class SimpleAddon extends AutismAddon {
private final int apiVersion;
private final String rootPackage;
protected SimpleAddon(int apiVersion, String rootPackage) {
this.apiVersion = apiVersion;
this.rootPackage = rootPackage == null ? "" : rootPackage;
}
@Override
public final int apiVersion() {
return apiVersion;
}
@Override
public final String getPackage() {
return rootPackage;
}
@Override
public final void onInitialize() {
initialize();
}
protected abstract void initialize();
protected final String id(String localId) {
return AutismAddons.id(localId);
}
protected final AddonRegistrationResult registerModule(PackModule module) {
return AutismAddons.modules().registerDetailed(module);
}
protected final AddonRegistrationResult registerAction(MacroActionEntry entry) {
return AutismAddons.macroActions().registerDetailed(entry);
}
protected final AddonRegistrationResult registerPreset(String label, String tip, Supplier<List<MacroAction>> builder) {
return AutismAddons.presets().registerDetailed(label, tip, builder);
}
protected final MacroActionEntry simpleAction(
String localId,
String label,
String tip,
String icon,
Consumer<Minecraft> runner
) {
String typeId = id(localId);
return MacroActionEntry.builder(typeId, () -> new SimpleAction(typeId, label, icon, runner))
.picker(label, tip)
.build();
}
protected final MacroActionEntry simpleCondition(
String localId,
String label,
String tip,
String status,
String icon,
Predicate<Minecraft> predicate
) {
String typeId = id(localId);
return MacroActionEntry.builder(typeId, () -> new SimpleCondition(typeId, label, status, icon, predicate))
.condition(label, tip)
.build();
}
}

View file

@ -0,0 +1,145 @@
package autismclient.api.event;
import autismclient.AutismClientAddon;
import autismclient.addons.AddonManager;
import net.minecraft.client.Minecraft;
import net.minecraft.network.protocol.Packet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.Consumer;
import java.util.function.Predicate;
public final class AddonEvents {
private static final List<OwnedConsumer<Minecraft>> TICK = new CopyOnWriteArrayList<>();
private static final List<OwnedPredicate<Packet<?>>> PACKET_SEND = new CopyOnWriteArrayList<>();
private static final List<OwnedConsumer<Packet<?>>> PACKET_RECEIVE = new CopyOnWriteArrayList<>();
private static final List<OwnedRunnable> GAME_JOIN = new CopyOnWriteArrayList<>();
private static final List<OwnedRunnable> GAME_LEFT = new CopyOnWriteArrayList<>();
private static final long ERROR_LOG_INTERVAL_MS = 5_000L;
private static final Map<String, Long> LAST_ERROR_LOG_MS = new ConcurrentHashMap<>();
private AddonEvents() {}
public static void onTick(Consumer<Minecraft> listener) {
String owner = ownerOrReject("tick");
if (owner != null && listener != null) {
TICK.add(new OwnedConsumer<>(owner, listener));
AddonManager.recordAcceptedRegistration("event", "tick");
}
}
public static void onPacketSend(Predicate<Packet<?>> listener) {
String owner = ownerOrReject("packetSend");
if (owner != null && listener != null) {
PACKET_SEND.add(new OwnedPredicate<>(owner, listener));
AddonManager.recordAcceptedRegistration("event", "packetSend");
}
}
public static void onPacketReceive(Consumer<Packet<?>> listener) {
String owner = ownerOrReject("packetReceive");
if (owner != null && listener != null) {
PACKET_RECEIVE.add(new OwnedConsumer<>(owner, listener));
AddonManager.recordAcceptedRegistration("event", "packetReceive");
}
}
public static void onGameJoin(Runnable listener) {
String owner = ownerOrReject("gameJoin");
if (owner != null && listener != null) {
GAME_JOIN.add(new OwnedRunnable(owner, listener));
AddonManager.recordAcceptedRegistration("event", "gameJoin");
}
}
public static void onGameLeft(Runnable listener) {
String owner = ownerOrReject("gameLeft");
if (owner != null && listener != null) {
GAME_LEFT.add(new OwnedRunnable(owner, listener));
AddonManager.recordAcceptedRegistration("event", "gameLeft");
}
}
private static String ownerOrReject(String event) {
String owner = AddonManager.currentAddonId();
if (owner == null || owner.isBlank()) {
AutismClientAddon.LOG.warn("[Addons] Rejecting {} listener outside an addon lifecycle", event);
AddonManager.recordRejectedRegistration(owner, "event", event, "registration outside an addon lifecycle");
return null;
}
return owner;
}
public static void unregisterAddon(String addonId) {
if (addonId == null || addonId.isBlank()) return;
TICK.removeIf(listener -> addonId.equals(listener.owner()));
PACKET_SEND.removeIf(listener -> addonId.equals(listener.owner()));
PACKET_RECEIVE.removeIf(listener -> addonId.equals(listener.owner()));
GAME_JOIN.removeIf(listener -> addonId.equals(listener.owner()));
GAME_LEFT.removeIf(listener -> addonId.equals(listener.owner()));
LAST_ERROR_LOG_MS.keySet().removeIf(key -> key.startsWith(addonId + ":"));
}
public static void fireTick(Minecraft mc) {
if (TICK.isEmpty()) return;
for (OwnedConsumer<Minecraft> l : TICK) {
try { l.listener().accept(mc); } catch (Throwable t) { logThrottled(l.owner(), "tick", t); }
}
}
public static boolean hasTickListeners() {
return !TICK.isEmpty();
}
public static boolean hasPacketListeners() {
return !PACKET_SEND.isEmpty() || !PACKET_RECEIVE.isEmpty();
}
public static boolean firePacketSend(Packet<?> packet) {
if (PACKET_SEND.isEmpty()) return false;
boolean cancel = false;
for (OwnedPredicate<Packet<?>> l : PACKET_SEND) {
try { cancel |= l.listener().test(packet); } catch (Throwable t) { logThrottled(l.owner(), "packetSend", t); }
}
return cancel;
}
public static void firePacketReceive(Packet<?> packet) {
if (PACKET_RECEIVE.isEmpty()) return;
for (OwnedConsumer<Packet<?>> l : PACKET_RECEIVE) {
try { l.listener().accept(packet); } catch (Throwable t) { logThrottled(l.owner(), "packetReceive", t); }
}
}
public static void fireGameJoin() {
if (GAME_JOIN.isEmpty()) return;
for (OwnedRunnable l : GAME_JOIN) {
try { l.listener().run(); } catch (Throwable t) { logThrottled(l.owner(), "gameJoin", t); }
}
}
public static void fireGameLeft() {
if (GAME_LEFT.isEmpty()) return;
for (OwnedRunnable l : GAME_LEFT) {
try { l.listener().run(); } catch (Throwable t) { logThrottled(l.owner(), "gameLeft", t); }
}
}
private static void logThrottled(String owner, String event, Throwable t) {
long now = System.currentTimeMillis();
String key = owner + ":" + event + ":" + t.getClass().getName();
Long last = LAST_ERROR_LOG_MS.get(key);
if (last != null && now - last < ERROR_LOG_INTERVAL_MS) return;
LAST_ERROR_LOG_MS.put(key, now);
AddonManager.recordRuntimeError(owner, event + " listener threw " + t.getClass().getSimpleName());
AutismClientAddon.LOG.warn("[Addons] Addon '{}' {} event listener threw", owner, event, t);
}
private record OwnedConsumer<T>(String owner, Consumer<T> listener) {}
private record OwnedPredicate<T>(String owner, Predicate<T> listener) {}
private record OwnedRunnable(String owner, Runnable listener) {}
}

View file

@ -0,0 +1,27 @@
package autismclient.api.hud;
import net.minecraft.client.gui.Font;
import net.minecraft.client.gui.GuiGraphicsExtractor;
public interface HudElementProvider {
String id();
String label();
default String description() { return ""; }
int width();
int height();
void render(GuiGraphicsExtractor ctx, Font font, int x, int y, float alpha);
default boolean defaultEnabled() { return false; }
default String defaultAnchor() { return "TOP_LEFT"; }
default int defaultX() { return 0; }
default int defaultY() { return 0; }
}

View file

@ -0,0 +1,104 @@
package autismclient.api.hud;
import autismclient.AutismClientAddon;
import autismclient.api.AddonRegistrationResult;
import autismclient.addons.AddonManager;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public final class HudElements {
private static final Map<String, HudElementProvider> PROVIDERS = new LinkedHashMap<>();
private static final Map<String, String> OWNERS = new LinkedHashMap<>();
private static int revision;
private HudElements() {}
public static int revision() {
return revision;
}
public static boolean register(HudElementProvider provider) {
return registerDetailed(provider).accepted();
}
public static AddonRegistrationResult registerDetailed(HudElementProvider provider) {
if (provider == null) return AddonRegistrationResult.rejected("hud", "", "provider was null");
String ownerAddonId = AddonManager.currentAddonId();
if (ownerAddonId == null || ownerAddonId.isBlank()) {
return reject(ownerAddonId, "", "registration outside an addon lifecycle");
}
String id = provider.id();
if (id == null || !id.contains(":")) {
return reject(ownerAddonId, id, "non-namespaced id");
}
if (!id.startsWith(ownerAddonId + ":")) {
return reject(ownerAddonId, id, "foreign namespace");
}
if (PROVIDERS.containsKey(id)) {
return reject(ownerAddonId, id, "duplicate id");
}
AddonRegistrationResult sizeCheck = validateSize(ownerAddonId, id, provider);
if (!sizeCheck.accepted()) return sizeCheck;
PROVIDERS.put(id, provider);
OWNERS.put(id, ownerAddonId);
revision++;
AddonManager.recordAcceptedRegistration("hud", id);
return AddonRegistrationResult.accepted("hud", id);
}
private static AddonRegistrationResult validateSize(String ownerAddonId, String id, HudElementProvider provider) {
int width;
int height;
try {
width = provider.width();
height = provider.height();
} catch (Throwable t) {
AutismClientAddon.LOG.warn("[Hud] Rejecting HUD element '{}': sizing threw", id, t);
AddonManager.recordRejectedRegistration(ownerAddonId, "hud", id, "sizing threw " + t.getClass().getSimpleName());
return AddonRegistrationResult.rejected("hud", id, "sizing threw " + t.getClass().getSimpleName());
}
if (width <= 0) return reject(ownerAddonId, id, "width must be positive");
if (height <= 0) return reject(ownerAddonId, id, "height must be positive");
return AddonRegistrationResult.accepted("hud", id);
}
private static AddonRegistrationResult reject(String ownerAddonId, String id, String reason) {
AutismClientAddon.LOG.warn("[Hud] Rejecting HUD element '{}': {}", id, reason);
AddonManager.recordRejectedRegistration(ownerAddonId, "hud", id, reason);
return AddonRegistrationResult.rejected("hud", id, reason);
}
public static void unregisterAddon(String addonId) {
if (addonId == null || addonId.isBlank()) return;
List<String> remove = new ArrayList<>();
for (Map.Entry<String, String> owner : OWNERS.entrySet()) {
if (addonId.equals(owner.getValue())) remove.add(owner.getKey());
}
if (remove.isEmpty()) return;
for (String id : remove) {
PROVIDERS.remove(id);
OWNERS.remove(id);
}
revision++;
}
public static HudElementProvider get(String id) {
return id == null ? null : PROVIDERS.get(id);
}
public static boolean isAddon(String id) {
return id != null && PROVIDERS.containsKey(id);
}
public static List<String> ids() {
return Collections.unmodifiableList(new ArrayList<>(PROVIDERS.keySet()));
}
public static boolean isEmpty() {
return PROVIDERS.isEmpty();
}
}

View file

@ -0,0 +1,81 @@
package autismclient.api.macro;
import autismclient.gui.macro.editor.ActionFieldSchema;
public final class ActionSchema {
private final ActionFieldSchema internal;
private ActionSchema(ActionFieldSchema internal) {
this.internal = internal;
}
public ActionFieldSchema internal() {
return internal;
}
public static Builder builder() {
return new Builder();
}
public static final class Builder {
private final ActionFieldSchema.Builder delegate = ActionFieldSchema.builder();
private Builder() {}
public Builder toggle(String key, String label) { delegate.toggle(key, label); return this; }
public Builder number(String key, String label) { delegate.number(key, label); return this; }
public Builder decimal(String key, String label) { delegate.decimal(key, label); return this; }
public Builder text(String key, String label) { delegate.text(key, label); return this; }
public Builder macroSelect(String key, String label) { delegate.macroSelect(key, label); return this; }
public Builder enumField(String key, String label, String... options) { delegate.enumField(key, label, options); return this; }
public Builder stringList(String key, String label) { delegate.stringList(key, label); return this; }
public Builder slot(String key, String label) { delegate.slot(key, label); return this; }
public Builder targetSummary(String key, String label) { delegate.targetSummary(key, label); return this; }
public Builder capturePacketClick(String key, String label) { delegate.capturePacketClick(key, label); return this; }
public Builder blockPos(String key, String label) { delegate.blockPos(key, label); return this; }
public Builder range(int min, int max) { delegate.range(min, max); return this; }
public Builder decRange(double min, double max) { delegate.decRange(min, max); return this; }
public Builder showWhen(String key) { delegate.showWhen(key); return this; }
public Builder hideWhen(String key) { delegate.hideWhen(key); return this; }
public Builder showWhenEnum(String key, String value) { delegate.showWhenEnum(key, value); return this; }
public Builder hideWhenEnum(String key, String value) { delegate.hideWhenEnum(key, value); return this; }
public Builder addLabel(String label) { delegate.addLabel(label); return this; }
public Builder xyzKeys(String... keys) { delegate.xyzKeys(keys); return this; }
public Builder xyzDouble(boolean value) { delegate.xyzDouble(value); return this; }
public Builder captureBlock() { delegate.captureBlock(); return this; }
public Builder captureEntity() { delegate.captureEntity(); return this; }
public Builder captureCatalog() { delegate.captureCatalog(); return this; }
public Builder captureItemSlot() { delegate.captureItemSlot(); return this; }
public Builder capturePacketName() { delegate.capturePacketName(); return this; }
public Builder exclusiveWith(String... keys) { delegate.exclusiveWith(keys); return this; }
public ActionSchema build() {
return new ActionSchema(delegate.build());
}
}
}

View file

@ -0,0 +1,61 @@
package autismclient.api.macro;
import autismclient.util.macro.MacroAction;
import net.minecraft.nbt.CompoundTag;
public abstract class AddonAction implements MacroAction {
private final String typeId;
protected AddonAction(String typeId) {
this.typeId = typeId;
}
protected abstract void run(net.minecraft.client.Minecraft mc);
protected void save(CompoundTag tag) {}
protected void load(CompoundTag tag) {}
protected ActionSchema schema() {
return null;
}
@Override
public final void execute(net.minecraft.client.Minecraft mc) {
run(mc);
}
@Override
public final String getTypeId() {
return typeId;
}
@Override
public final CompoundTag toTag() {
CompoundTag tag = new CompoundTag();
tag.putString("type", typeId);
save(tag);
return tag;
}
@Override
public final void fromTag(CompoundTag tag) {
load(tag);
}
protected static void putString(CompoundTag tag, String key, String value) { tag.putString(key, value == null ? "" : value); }
protected static void putInt(CompoundTag tag, String key, int value) { tag.putInt(key, value); }
protected static void putDouble(CompoundTag tag, String key, double value) { tag.putDouble(key, value); }
protected static void putBool(CompoundTag tag, String key, boolean value) { tag.putBoolean(key, value); }
protected static String getString(CompoundTag tag, String key, String def) { return tag.getStringOr(key, def); }
protected static int getInt(CompoundTag tag, String key, int def) { return tag.getIntOr(key, def); }
protected static double getDouble(CompoundTag tag, String key, double def) { return tag.getDoubleOr(key, def); }
protected static boolean getBool(CompoundTag tag, String key, boolean def) { return tag.getBooleanOr(key, def); }
public static ActionSchema schemaOf(MacroAction action) {
return action instanceof AddonAction a ? a.schema()
: action instanceof AddonContextAction c ? c.schemaInternal()
: null;
}
}

View file

@ -0,0 +1,10 @@
package autismclient.api.macro;
import net.minecraft.client.Minecraft;
public abstract class AddonCondition {
public abstract boolean check(Minecraft mc);
public void onComplete() {}
}

View file

@ -0,0 +1,51 @@
package autismclient.api.macro;
import net.minecraft.nbt.CompoundTag;
public abstract class AddonContextAction implements ContextMacroAction {
private final String typeId;
protected AddonContextAction(String typeId) {
this.typeId = typeId;
}
protected void save(CompoundTag tag) {}
protected void load(CompoundTag tag) {}
protected ActionSchema schema() {
return null;
}
ActionSchema schemaInternal() {
return schema();
}
@Override
public final String getTypeId() {
return typeId;
}
@Override
public final CompoundTag toTag() {
CompoundTag tag = new CompoundTag();
tag.putString("type", typeId);
save(tag);
return tag;
}
@Override
public final void fromTag(CompoundTag tag) {
load(tag);
}
protected static void putString(CompoundTag tag, String key, String value) { tag.putString(key, value == null ? "" : value); }
protected static void putInt(CompoundTag tag, String key, int value) { tag.putInt(key, value); }
protected static void putDouble(CompoundTag tag, String key, double value) { tag.putDouble(key, value); }
protected static void putBool(CompoundTag tag, String key, boolean value) { tag.putBoolean(key, value); }
protected static String getString(CompoundTag tag, String key, String def) { return tag.getStringOr(key, def); }
protected static int getInt(CompoundTag tag, String key, int def) { return tag.getIntOr(key, def); }
protected static double getDouble(CompoundTag tag, String key, double def) { return tag.getDoubleOr(key, def); }
protected static boolean getBool(CompoundTag tag, String key, boolean def) { return tag.getBooleanOr(key, def); }
}

View file

@ -0,0 +1,14 @@
package autismclient.api.macro;
import autismclient.util.macro.MacroAction;
import net.minecraft.client.Minecraft;
public interface ContextMacroAction extends MacroAction {
void run(MacroExecutionContext ctx) throws InterruptedException;
@Override
default void execute(Minecraft mc) {
}
}

View file

@ -0,0 +1,103 @@
package autismclient.api.macro;
import autismclient.addons.AddonManager;
import autismclient.gui.macro.editor.ActionFieldSchema;
import autismclient.util.macro.MacroAction;
import java.util.function.Supplier;
public final class MacroActionEntry {
public enum Kind { ACTION, CONDITION }
private final String typeId;
private final Supplier<MacroAction> factory;
private final ActionFieldSchema schema;
private String pickerCategory;
private final String pickerLabel;
private final String pickerTip;
private final Kind kind;
private MacroActionEntry(Builder b) {
this.typeId = b.typeId;
this.factory = b.factory;
this.schema = b.schema;
this.pickerCategory = b.pickerCategory;
this.pickerLabel = b.pickerLabel;
this.pickerTip = b.pickerTip;
this.kind = b.kind;
}
public String typeId() { return typeId; }
public Supplier<MacroAction> factory() { return factory; }
public ActionFieldSchema schema() { return schema; }
public boolean hasPicker() { return pickerCategory != null && pickerLabel != null; }
boolean wantsPicker() { return pickerLabel != null; }
public String pickerCategory() { return pickerCategory; }
public String pickerLabel() { return pickerLabel; }
public String pickerTip() { return pickerTip == null ? "" : pickerTip; }
public Kind kind() { return kind; }
public boolean isCondition() { return kind == Kind.CONDITION; }
void setPickerCategory(String categoryId) {
this.pickerCategory = categoryId;
}
public static Builder builder(String typeId, Supplier<MacroAction> factory) {
return new Builder(typeId, factory);
}
public static Builder local(String localId, Supplier<MacroAction> factory) {
return new Builder(AddonManager.scopedId(localId), factory);
}
public static final class Builder {
private final String typeId;
private final Supplier<MacroAction> factory;
private ActionFieldSchema schema;
private String pickerCategory;
private String pickerLabel;
private String pickerTip;
private Kind kind = Kind.ACTION;
private Builder(String typeId, Supplier<MacroAction> factory) {
this.typeId = typeId;
this.factory = factory;
}
public Builder schema(ActionSchema schema) {
this.schema = schema == null ? null : schema.internal();
return this;
}
public Builder picker(String label, String tip) {
return picker(null, label, tip);
}
public Builder picker(String categoryId, String label, String tip) {
this.pickerCategory = categoryId;
this.pickerLabel = label;
this.pickerTip = tip;
this.kind = Kind.ACTION;
return this;
}
public Builder condition(String label, String tip) {
return condition(null, label, tip);
}
public Builder condition(String categoryId, String label, String tip) {
this.pickerCategory = categoryId;
this.pickerLabel = label;
this.pickerTip = tip;
this.kind = Kind.CONDITION;
return this;
}
public MacroActionEntry build() {
return new MacroActionEntry(this);
}
}
}

View file

@ -0,0 +1,230 @@
package autismclient.api.macro;
import autismclient.AutismClientAddon;
import autismclient.api.AddonRegistrationResult;
import autismclient.addons.AddonManager;
import autismclient.gui.macro.editor.ActionFieldSchema;
import autismclient.util.macro.MacroAction;
import autismclient.util.macro.MacroActionType;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.function.Supplier;
public final class MacroActionRegistry {
private static final Map<String, MacroActionEntry> ENTRIES = new LinkedHashMap<>();
private static final Map<String, ActionCategory> CATEGORIES = new LinkedHashMap<>();
private static final Map<String, String> ENTRY_OWNERS = new LinkedHashMap<>();
private static final Map<String, String> CATEGORY_OWNERS = new LinkedHashMap<>();
private static final Map<String, ActionFieldSchema> RESOLVED_SCHEMAS = new LinkedHashMap<>();
public record ActionCategory(String id, String label, int color) {}
public static final int ADDON_AUTO_CATEGORY_COLOR = 0xFFAA66FF;
private static final String ADDON_CAT_PREFIX = "addon:";
private MacroActionRegistry() {}
public static String scopeCategoryId(String rawId) {
if (AddonManager.isLifecycleActive()) {
String addonId = AddonManager.currentAddonId();
return ADDON_CAT_PREFIX + (addonId == null || addonId.isBlank() ? "shared" : addonId);
}
if (rawId != null && rawId.startsWith(ADDON_CAT_PREFIX)) return rawId;
String addonId = AddonManager.currentAddonId();
String base = addonId == null || addonId.isBlank() ? "shared" : addonId;
return rawId == null || rawId.isBlank()
? ADDON_CAT_PREFIX + base
: ADDON_CAT_PREFIX + base + "/" + rawId;
}
public static String ensureScopedCategory(String rawId) {
String scopedId = scopeCategoryId(rawId);
if (!CATEGORIES.containsKey(scopedId)) {
registerCategoryInternal(scopedId, AddonManager.scopedCategoryLabel(null), ADDON_AUTO_CATEGORY_COLOR,
AddonManager.currentAddonId());
}
return scopedId;
}
public static void registerScopedCategory(String rawId, String label, int color) {
String visible = AddonManager.isLifecycleActive() ? AddonManager.scopedCategoryLabel(null) : label;
registerCategoryInternal(scopeCategoryId(rawId), visible, color,
AddonManager.currentAddonId());
}
public static void registerCategory(String id, String label, int color) {
registerCategoryInternal(id, label, color, null);
}
private static void registerCategoryInternal(String id, String label, int color, String ownerAddonId) {
if (id == null || id.isBlank()) return;
CATEGORIES.put(id, new ActionCategory(id, label == null || label.isBlank() ? id : label, color));
if (ownerAddonId != null && !ownerAddonId.isBlank()) CATEGORY_OWNERS.put(id, ownerAddonId);
}
public static ActionCategory category(String id) {
return id == null ? null : CATEGORIES.get(id);
}
public static boolean register(MacroActionEntry entry) {
return registerDetailed(entry).accepted();
}
public static AddonRegistrationResult registerDetailed(MacroActionEntry entry) {
if (entry == null) return AddonRegistrationResult.rejected("macro action", "", "entry was null");
String ownerAddonId = AddonManager.currentAddonId();
if (ownerAddonId == null || ownerAddonId.isBlank()) {
return reject(ownerAddonId, "macro action", "", "registration outside an addon lifecycle");
}
String typeId = entry.typeId();
if (typeId == null || !typeId.contains(":")) {
return reject(ownerAddonId, "macro action", typeId, "non-namespaced type id");
}
if (!typeId.startsWith(ownerAddonId + ":")) {
return reject(ownerAddonId, "macro action", typeId, "foreign namespace");
}
if (entry.factory() == null) {
return reject(ownerAddonId, "macro action", typeId, "missing factory");
}
if (isBuiltinName(typeId)) {
return reject(ownerAddonId, "macro action", typeId, "collides with a built-in type");
}
if (ENTRIES.containsKey(typeId)) {
return reject(ownerAddonId, "macro action", typeId, "duplicate type id");
}
if (entry.wantsPicker()) {
entry.setPickerCategory(ensureScopedCategory(entry.pickerCategory()));
}
ActionFieldSchema effectiveSchema = entry.schema();
MacroAction probe;
try {
probe = entry.factory().get();
} catch (Throwable t) {
AutismClientAddon.LOG.warn("[MacroActions] Rejecting action '{}' because its factory threw during validation", typeId, t);
return reject(ownerAddonId, "macro action", typeId, "factory threw: " + errorName(t));
}
if (probe == null) {
return reject(ownerAddonId, "macro action", typeId, "factory returned null");
}
if (effectiveSchema == null) {
ActionSchema declared = AddonAction.schemaOf(probe);
if (declared != null) effectiveSchema = declared.internal();
}
String validationError = validateProbe(typeId, entry, probe, effectiveSchema);
if (validationError != null) return reject(ownerAddonId, "macro action", typeId, validationError);
ENTRIES.put(typeId, entry);
ENTRY_OWNERS.put(typeId, ownerAddonId);
if (effectiveSchema != null) RESOLVED_SCHEMAS.put(typeId, effectiveSchema);
AddonManager.recordAcceptedRegistration("macro action", typeId);
return AddonRegistrationResult.accepted("macro action", typeId);
}
private static AddonRegistrationResult reject(String ownerAddonId, String kind, String id, String reason) {
AutismClientAddon.LOG.warn("[MacroActions] Rejecting {} '{}': {}", kind, id, reason);
AddonManager.recordRejectedRegistration(ownerAddonId, kind, id, reason);
return AddonRegistrationResult.rejected(kind, id, reason);
}
private static String validateProbe(String typeId, MacroActionEntry entry, MacroAction probe, ActionFieldSchema schema) {
String writtenType;
net.minecraft.nbt.CompoundTag tag;
try {
tag = probe.toTag();
writtenType = tag.getStringOr("type", "");
} catch (Throwable t) {
AutismClientAddon.LOG.warn("[MacroActions] Rejecting '{}' because toTag() threw", typeId, t);
return "toTag() threw: " + errorName(t);
}
if (!typeId.equals(writtenType)) {
return "writes type=\"" + writtenType + "\" instead of \"" + typeId + "\"";
}
if (schema != null) {
for (autismclient.gui.macro.editor.FieldDef field : schema.fields()) {
String key = field.key();
if (field.type() == autismclient.gui.macro.editor.FieldType.BLOCK_POS) {
for (String axisKey : field.xyzKeys()) {
if (axisKey != null && !axisKey.isEmpty() && !tag.contains(axisKey)) {
return "schema field '" + axisKey + "' is not written by toTag()/save()";
}
}
} else if (key != null && !key.isEmpty() && !tag.contains(key)) {
return "schema field '" + key + "' is not written by toTag()/save()";
}
}
}
if (entry.isCondition() && !(probe instanceof ContextMacroAction)) {
return "conditions must implement ContextMacroAction";
}
return null;
}
public static void unregisterAddon(String addonId) {
if (addonId == null || addonId.isBlank()) return;
List<String> removeTypes = new ArrayList<>();
for (Map.Entry<String, String> owner : ENTRY_OWNERS.entrySet()) {
if (addonId.equals(owner.getValue())) removeTypes.add(owner.getKey());
}
for (String typeId : removeTypes) {
ENTRIES.remove(typeId);
RESOLVED_SCHEMAS.remove(typeId);
ENTRY_OWNERS.remove(typeId);
}
List<String> removeCategories = new ArrayList<>();
for (Map.Entry<String, String> owner : CATEGORY_OWNERS.entrySet()) {
if (addonId.equals(owner.getValue())) removeCategories.add(owner.getKey());
}
for (String categoryId : removeCategories) {
CATEGORIES.remove(categoryId);
CATEGORY_OWNERS.remove(categoryId);
}
}
public static Supplier<MacroAction> factory(String typeId) {
MacroActionEntry e = typeId == null ? null : ENTRIES.get(typeId);
return e == null ? null : e.factory();
}
public static ActionFieldSchema schema(String typeId) {
return typeId == null ? null : RESOLVED_SCHEMAS.get(typeId);
}
public static boolean isCondition(String typeId) {
MacroActionEntry e = typeId == null ? null : ENTRIES.get(typeId);
return e != null && e.isCondition();
}
public static String ownerOf(String typeId) {
return typeId == null ? null : ENTRY_OWNERS.get(typeId);
}
public static List<MacroActionEntry> entries() {
return Collections.unmodifiableList(new ArrayList<>(ENTRIES.values()));
}
private static boolean isBuiltinName(String typeId) {
try {
MacroActionType.valueOf(typeId.toUpperCase(Locale.ROOT));
return true;
} catch (IllegalArgumentException e) {
return false;
}
}
private static String errorName(Throwable t) {
if (t == null) return "unknown";
String message = t.getMessage();
return message == null || message.isBlank() ? t.getClass().getSimpleName() : t.getClass().getSimpleName() + ": " + message;
}
}

View file

@ -0,0 +1,28 @@
package autismclient.api.macro;
import net.minecraft.client.Minecraft;
import net.minecraft.network.protocol.Packet;
import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;
public interface MacroExecutionContext {
Minecraft mc();
void runOnClientThread(Runnable r);
<T> T callOnClientThread(Supplier<T> s);
void waitTicks(int ticks);
void awaitCondition(CompletableFuture<Void> future);
void awaitCondition(AddonCondition condition);
boolean isActive();
void setStatus(String status);
void sendPacket(Packet<?> packet);
}

View file

@ -0,0 +1,115 @@
package autismclient.api.macro;
import autismclient.AutismClientAddon;
import autismclient.api.AddonRegistrationResult;
import autismclient.addons.AddonManager;
import autismclient.util.macro.MacroAction;
import java.util.ArrayList;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
public final class MacroPresetRegistry {
public record PresetEntry(String categoryId, String label, String tip, Supplier<List<MacroAction>> builder) {}
private static final List<PresetEntry> ENTRIES = new ArrayList<>();
private static final Map<PresetEntry, String> ENTRY_OWNERS = new IdentityHashMap<>();
private static final Map<String, String> CATEGORY_LABELS = new LinkedHashMap<>();
private static final Map<String, String> CATEGORY_OWNERS = new LinkedHashMap<>();
private MacroPresetRegistry() {}
public static void registerCategory(String id, String label) {
registerCategory(id, label, AddonManager.currentAddonId());
}
public static String ensureScopedCategory(String rawId) {
String scopedId = MacroActionRegistry.scopeCategoryId(rawId);
if (!CATEGORY_LABELS.containsKey(scopedId)) {
registerCategory(scopedId, AddonManager.scopedCategoryLabel(null), AddonManager.currentAddonId());
}
return scopedId;
}
public static void registerScopedCategory(String rawId, String label) {
String visible = AddonManager.isLifecycleActive() ? AddonManager.scopedCategoryLabel(null) : label;
registerCategory(MacroActionRegistry.scopeCategoryId(rawId), visible,
AddonManager.currentAddonId());
}
private static void registerCategory(String id, String label, String ownerAddonId) {
if (id == null || id.isBlank()) return;
CATEGORY_LABELS.put(id, label == null || label.isBlank() ? id : label);
if (ownerAddonId != null && !ownerAddonId.isBlank()) CATEGORY_OWNERS.put(id, ownerAddonId);
}
public static void register(String categoryId, String label, String tip, Supplier<List<MacroAction>> builder) {
registerDetailed(categoryId, label, tip, builder);
}
public static AddonRegistrationResult registerDetailed(String categoryId, String label, String tip, Supplier<List<MacroAction>> builder) {
String ownerAddonId = AddonManager.currentAddonId();
if (ownerAddonId == null || ownerAddonId.isBlank()) {
return reject(ownerAddonId, label, "registration outside an addon lifecycle");
}
if (categoryId == null || categoryId.isBlank()) return reject(ownerAddonId, label, "missing category");
if (label == null || label.isBlank()) return reject(ownerAddonId, label, "missing label");
if (builder == null) return reject(ownerAddonId, label, "missing builder");
AddonRegistrationResult validation = validateBuilder(ownerAddonId, label, builder);
if (!validation.accepted()) return validation;
PresetEntry entry = new PresetEntry(categoryId, label, tip == null ? "" : tip, builder);
ENTRIES.add(entry);
ENTRY_OWNERS.put(entry, ownerAddonId);
AddonManager.recordAcceptedRegistration("preset", label);
return AddonRegistrationResult.accepted("preset", label);
}
private static AddonRegistrationResult validateBuilder(String ownerAddonId, String label, Supplier<List<MacroAction>> builder) {
List<MacroAction> actions;
try {
actions = builder.get();
} catch (Throwable t) {
AutismClientAddon.LOG.warn("[MacroPresets] Rejecting preset '{}': builder threw", label, t);
AddonManager.recordRejectedRegistration(ownerAddonId, "preset", label, "builder threw " + t.getClass().getSimpleName());
return AddonRegistrationResult.rejected("preset", label, "builder threw " + t.getClass().getSimpleName());
}
if (actions == null) return reject(ownerAddonId, label, "builder returned null");
for (int i = 0; i < actions.size(); i++) {
if (actions.get(i) == null) {
return reject(ownerAddonId, label, "builder returned null action at index " + i);
}
}
return AddonRegistrationResult.accepted("preset", label);
}
private static AddonRegistrationResult reject(String ownerAddonId, String label, String reason) {
AutismClientAddon.LOG.warn("[MacroPresets] Rejecting preset '{}': {}", label, reason);
AddonManager.recordRejectedRegistration(ownerAddonId, "preset", label, reason);
return AddonRegistrationResult.rejected("preset", label, reason);
}
public static void unregisterAddon(String addonId) {
if (addonId == null || addonId.isBlank()) return;
List<PresetEntry> remove = new ArrayList<>();
for (PresetEntry entry : ENTRIES) {
if (addonId.equals(ENTRY_OWNERS.get(entry))) remove.add(entry);
}
ENTRIES.removeAll(remove);
for (PresetEntry entry : remove) ENTRY_OWNERS.remove(entry);
CATEGORY_LABELS.entrySet().removeIf(entry -> addonId.equals(CATEGORY_OWNERS.get(entry.getKey())));
CATEGORY_OWNERS.entrySet().removeIf(entry -> addonId.equals(entry.getValue()));
}
public static List<PresetEntry> entries() {
return Collections.unmodifiableList(ENTRIES);
}
public static String categoryLabel(String id) {
return CATEGORY_LABELS.get(id);
}
}

View file

@ -0,0 +1,33 @@
package autismclient.api.macro;
import net.minecraft.client.Minecraft;
import java.util.function.Consumer;
public final class SimpleAction extends AddonAction {
private final String displayName;
private final String icon;
private final Consumer<Minecraft> runner;
public SimpleAction(String typeId, String displayName, String icon, Consumer<Minecraft> runner) {
super(typeId);
this.displayName = displayName == null || displayName.isBlank() ? typeId : displayName;
this.icon = icon == null || icon.isBlank() ? "*" : icon;
this.runner = runner;
}
@Override
protected void run(Minecraft mc) {
if (runner != null) runner.accept(mc);
}
@Override
public String getDisplayName() {
return displayName;
}
@Override
public String getIcon() {
return icon;
}
}

View file

@ -0,0 +1,41 @@
package autismclient.api.macro;
import net.minecraft.client.Minecraft;
import java.util.function.Predicate;
public final class SimpleCondition extends AddonContextAction {
private final String displayName;
private final String status;
private final String icon;
private final Predicate<Minecraft> predicate;
public SimpleCondition(String typeId, String displayName, String status, String icon, Predicate<Minecraft> predicate) {
super(typeId);
this.displayName = displayName == null || displayName.isBlank() ? typeId : displayName;
this.status = status == null || status.isBlank() ? this.displayName : status;
this.icon = icon == null || icon.isBlank() ? "?" : icon;
this.predicate = predicate;
}
@Override
public void run(MacroExecutionContext ctx) {
ctx.setStatus(status);
ctx.awaitCondition(new AddonCondition() {
@Override
public boolean check(Minecraft mc) {
return predicate != null && predicate.test(mc);
}
});
}
@Override
public String getDisplayName() {
return displayName;
}
@Override
public String getIcon() {
return icon;
}
}

View file

@ -0,0 +1,102 @@
package autismclient.api.module;
import autismclient.api.AutismAddons;
import autismclient.modules.PackModule;
import autismclient.modules.PackModuleOption;
import java.util.Locale;
import java.util.function.Consumer;
public class SimpleModule extends PackModule {
private Consumer<SimpleModule> enableHandler;
private Consumer<SimpleModule> disableHandler;
private Consumer<SimpleModule> tickHandler;
public SimpleModule(String localId, String name, String description) {
super(AutismAddons.id(localId), name, description);
}
public final SimpleModule onEnabled(Consumer<SimpleModule> handler) {
this.enableHandler = handler;
return this;
}
public final SimpleModule onDisabled(Consumer<SimpleModule> handler) {
this.disableHandler = handler;
return this;
}
public final SimpleModule onTick(Consumer<SimpleModule> handler) {
this.tickHandler = handler;
return this;
}
public final SimpleModule addBool(String id, String label, boolean defaultValue) {
option(PackModuleOption.bool(id, label, defaultValue));
return this;
}
public final SimpleModule addInt(String id, String label, int defaultValue, int min, int max, int step) {
option(PackModuleOption.integer(id, label, defaultValue, min, max, step));
return this;
}
public final SimpleModule addDouble(String id, String label, double defaultValue, double min, double max, double step) {
option(PackModuleOption.decimal(id, label, defaultValue, min, max, step));
return this;
}
public final SimpleModule addChoice(String id, String label, String defaultValue, String... choices) {
option(PackModuleOption.enumChoice(id, label, defaultValue, choices));
return this;
}
public final SimpleModule addText(String id, String label, String defaultValue) {
option(PackModuleOption.text(id, label, defaultValue));
return this;
}
public final SimpleModule addColor(String id, String label, int defaultArgb) {
option(PackModuleOption.color(id, label, defaultArgb));
return this;
}
public final boolean getBool(String id) {
return bool(id);
}
public final int getInt(String id) {
return integer(id);
}
public final double getDouble(String id) {
return decimal(id);
}
public final String getText(String id) {
return text(id);
}
public final String getChoice(String id) {
return choice(id);
}
@Override
public void onEnable() {
if (enableHandler != null) enableHandler.accept(this);
}
@Override
public void onDisable() {
if (disableHandler != null) disableHandler.accept(this);
}
@Override
public void tick() {
if (tickHandler != null) tickHandler.accept(this);
}
protected final String upper(String value) {
return value == null ? "" : value.toUpperCase(Locale.ROOT);
}
}

View file

@ -0,0 +1,18 @@
package autismclient.commands;
import net.minecraft.client.Minecraft;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.client.multiplayer.ClientPacketListener;
public final class AutismCommandSource {
public static final AutismCommandSource INSTANCE = new AutismCommandSource();
private AutismCommandSource() {}
public Minecraft mc() { return Minecraft.getInstance(); }
public LocalPlayer player() { return Minecraft.getInstance().player; }
public ClientPacketListener connection() { return Minecraft.getInstance().getConnection(); }
public boolean hasPlayer() { return Minecraft.getInstance().player != null; }
public boolean hasConnection() { return Minecraft.getInstance().getConnection() != null; }
}

View file

@ -0,0 +1,222 @@
package autismclient.commands;
import autismclient.AutismClientAddon;
import autismclient.api.AddonRegistrationResult;
import autismclient.modules.PackHideState;
import autismclient.util.AutismClientMessaging;
import autismclient.util.AutismCompatManager;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Locale;
import java.util.Set;
public final class AutismCommands {
private static final CommandDispatcher<AutismCommandSource> DISPATCHER = new CommandDispatcher<>();
private static final List<Command> ALL = new ArrayList<>();
private static final Map<String, Command> BY_NAME = new LinkedHashMap<>();
private static final Map<String, String> ADDON_COMMAND_OWNERS = new LinkedHashMap<>();
private static final Map<Command, String> ADDON_COMMAND_OBJECT_OWNERS = new IdentityHashMap<>();
private static final Set<String> DISABLED_ADDON_COMMAND_NAMES = new HashSet<>();
private static boolean initialized = false;
private AutismCommands() {}
public static synchronized void init() {
if (initialized) return;
initialized = true;
register(new autismclient.commands.impl.ToggleCommand());
register(new autismclient.commands.impl.MacroCommand());
register(new autismclient.commands.impl.DelayCommand());
register(new autismclient.commands.impl.SendCommand());
register(new autismclient.commands.impl.VClipCommand());
register(new autismclient.commands.impl.HClipCommand());
register(new autismclient.commands.impl.NbtCommand());
register(new autismclient.commands.impl.ServerCommand());
register(new autismclient.commands.impl.PluginsCommand());
register(new autismclient.commands.impl.PrefixCommand());
register(new autismclient.commands.impl.CommandsCommand());
register(new autismclient.commands.impl.HelpCommand());
register(new autismclient.commands.impl.ModulesCommand());
register(new autismclient.commands.impl.BindsCommand());
register(new autismclient.commands.impl.BindCommand());
register(new autismclient.commands.impl.DismountCommand());
register(new autismclient.commands.impl.DisconnectCommand());
register(new autismclient.commands.impl.SayCommand());
register(new autismclient.commands.impl.DropCommand());
register(new autismclient.commands.impl.GamemodeCommand());
register(new autismclient.commands.impl.GiveCommand());
register(new autismclient.commands.impl.DamageCommand());
register(new autismclient.commands.impl.XCarryCommand());
}
private static void register(Command command) {
registerWithName(command, command.name(), true);
}
private static List<String> registerWithName(Command command, String primaryName, boolean registerAliases) {
List<String> registeredNames = new ArrayList<>();
ALL.add(command);
LiteralArgumentBuilder<AutismCommandSource> primary = LiteralArgumentBuilder.literal(primaryName);
command.build(primary);
DISPATCHER.register(primary);
BY_NAME.put(primaryName.toLowerCase(Locale.ROOT), command);
DISABLED_ADDON_COMMAND_NAMES.remove(primaryName.toLowerCase(Locale.ROOT));
registeredNames.add(primaryName.toLowerCase(Locale.ROOT));
if (!registerAliases) return registeredNames;
for (String alias : command.aliases()) {
if (alias == null || alias.isBlank()) continue;
if (BY_NAME.containsKey(alias.toLowerCase(Locale.ROOT))) continue;
LiteralArgumentBuilder<AutismCommandSource> aliasBuilder = LiteralArgumentBuilder.literal(alias);
command.build(aliasBuilder);
DISPATCHER.register(aliasBuilder);
BY_NAME.put(alias.toLowerCase(Locale.ROOT), command);
DISABLED_ADDON_COMMAND_NAMES.remove(alias.toLowerCase(Locale.ROOT));
registeredNames.add(alias.toLowerCase(Locale.ROOT));
}
return registeredNames;
}
public static synchronized void registerAddonCommand(Command command, String addonId) {
registerAddonCommandDetailed(command, addonId);
}
public static synchronized AddonRegistrationResult registerAddonCommandDetailed(Command command, String addonId) {
if (command == null) return AddonRegistrationResult.rejected("command", "", "command was null");
if (addonId == null || addonId.isBlank()) {
return rejectAddonCommand(addonId, "", "registration outside an addon lifecycle");
}
String name = command.name();
if (name == null || name.isBlank()) {
return rejectAddonCommand(addonId, "", "blank command name");
}
List<String> registered;
boolean collision = BY_NAME.containsKey(name.toLowerCase(Locale.ROOT));
if (collision) {
String namespaced = (addonId == null || addonId.isBlank() ? "addon" : addonId) + ":" + name;
AutismClientAddon.LOG.warn("[Commands] Command name '{}' from addon '{}' collides with an existing "
+ "command; registering it as '{}' instead", name, addonId, namespaced);
registered = registerWithName(command, namespaced, false);
} else {
registered = registerWithName(command, name, true);
}
ADDON_COMMAND_OBJECT_OWNERS.put(command, addonId);
for (String registeredName : registered) {
ADDON_COMMAND_OWNERS.put(registeredName, addonId);
}
String id = registered.isEmpty() ? name : registered.get(0);
autismclient.addons.AddonManager.recordAcceptedRegistration("command", id);
return AddonRegistrationResult.accepted("command", id);
}
private static AddonRegistrationResult rejectAddonCommand(String addonId, String id, String reason) {
AutismClientAddon.LOG.warn("[Commands] Rejecting addon command '{}': {}", id, reason);
autismclient.addons.AddonManager.recordRejectedRegistration(addonId, "command", id, reason);
return AddonRegistrationResult.rejected("command", id, reason);
}
public static synchronized void unregisterAddonCommands(String addonId) {
if (addonId == null || addonId.isBlank()) return;
List<String> removeNames = new ArrayList<>();
for (Map.Entry<String, String> owner : ADDON_COMMAND_OWNERS.entrySet()) {
if (addonId.equals(owner.getValue())) removeNames.add(owner.getKey());
}
for (String name : removeNames) {
BY_NAME.remove(name);
ADDON_COMMAND_OWNERS.remove(name);
DISABLED_ADDON_COMMAND_NAMES.add(name);
}
ALL.removeIf(command -> addonId.equals(ADDON_COMMAND_OBJECT_OWNERS.get(command)));
ADDON_COMMAND_OBJECT_OWNERS.entrySet().removeIf(entry -> addonId.equals(entry.getValue()));
}
public static CommandDispatcher<AutismCommandSource> dispatcher() { return DISPATCHER; }
public static List<Command> all() { return Collections.unmodifiableList(ALL); }
public static Command find(String nameOrAlias) {
if (nameOrAlias == null) return null;
return BY_NAME.get(nameOrAlias.trim().toLowerCase(Locale.ROOT));
}
public static String effectivePrefix() { return AutismCompatManager.effectiveCommandPrefix(); }
public static boolean isAutismCommandMessage(String message) {
if (commandsBlockedByPanic()) return false;
if (message == null || message.isBlank()) return false;
String trimmed = message.trim();
String prefix = effectivePrefix();
return !prefix.isEmpty() && trimmed.startsWith(prefix);
}
public static boolean commandsBlockedByPanic() {
return PackHideState.isActive();
}
public static boolean isBlockedPanicCommandMessage(String message) {
return commandsBlockedByPanic() && isAutismCommandMessage(message);
}
public static String commandBody(String message) {
if (!isAutismCommandMessage(message)) return "";
String trimmed = message.trim();
int prefixLength = effectivePrefix().length();
return trimmed.length() <= prefixLength ? "" : trimmed.substring(prefixLength).trim();
}
public static boolean dispatch(String body) {
if (commandsBlockedByPanic()) return true;
if (body == null) return false;
String trimmed = body.trim();
if (trimmed.isEmpty()) return false;
if (DISABLED_ADDON_COMMAND_NAMES.contains(firstToken(trimmed).toLowerCase(Locale.ROOT))) {
sendSyntaxError(trimmed, CommandSyntaxException.BUILT_IN_EXCEPTIONS.dispatcherUnknownCommand().create());
return true;
}
try {
DISPATCHER.execute(trimmed, AutismCommandSource.INSTANCE);
return true;
} catch (CommandSyntaxException e) {
sendSyntaxError(trimmed, e);
return true;
} catch (Exception e) {
AutismClientAddon.LOG.warn("[Commands] dispatch failed for '{}'", trimmed, e);
AutismClientMessaging.sendPrefixed("§cCommand error: "
+ (e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage()));
return true;
}
}
private static void sendSyntaxError(String body, CommandSyntaxException e) {
String first = firstToken(body);
Command command = find(first);
String prefix = effectivePrefix();
if (command == null) {
AutismClientMessaging.sendPrefixed("§cUnknown AUTISM command: §f" + first);
AutismClientMessaging.sendPrefixed("§7Use §f" + prefix + "commands §7or §f" + prefix + "help§7.");
return;
}
String message = e.getMessage();
if (message == null || message.isBlank()) message = "Incomplete or invalid command.";
AutismClientMessaging.sendPrefixed("§c" + message);
AutismClientMessaging.sendPrefixed("§7Use §f" + prefix + "help " + command.name() + "§7.");
}
private static String firstToken(String body) {
if (body == null) return "";
String trimmed = body.trim();
if (trimmed.isEmpty()) return "";
int space = trimmed.indexOf(' ');
return space < 0 ? trimmed : trimmed.substring(0, space);
}
}

View file

@ -0,0 +1,33 @@
package autismclient.commands;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.context.CommandContext;
public abstract class Command {
public static final int SUCCESS = 1;
private final String name;
private final String description;
private final String[] aliases;
protected Command(String name, String description, String... aliases) {
this.name = name;
this.description = description == null ? "" : description;
this.aliases = aliases == null ? new String[0] : aliases.clone();
}
public final String name() { return name; }
public final String description() { return description; }
public final String[] aliases() { return aliases.clone(); }
public abstract void build(LiteralArgumentBuilder<AutismCommandSource> builder);
public int run(CommandContext<AutismCommandSource> ctx) {
autismclient.util.AutismClientMessaging.sendPrefixed(
"§eUsage: " + AutismCommands.effectivePrefix() + name + (aliases.length > 0 ? " (alias: " + aliases[0] + ")" : ""));
if (!description.isEmpty()) {
autismclient.util.AutismClientMessaging.sendPrefixed("§7" + description);
}
return SUCCESS;
}
}

View file

@ -0,0 +1,65 @@
package autismclient.commands;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.resources.Identifier;
import java.util.Locale;
import java.util.concurrent.CompletableFuture;
public final class CommandSuggest {
private CommandSuggest() {}
public static <S> CompletableFuture<Suggestions> literals(SuggestionsBuilder builder, String... values) {
String remaining = builder.getRemaining().toLowerCase(Locale.ROOT);
for (String value : values) {
if (value != null && value.toLowerCase(Locale.ROOT).startsWith(remaining)) builder.suggest(value);
}
return builder.buildFuture();
}
public static <S> CompletableFuture<Suggestions> state(CommandContext<S> ignored, SuggestionsBuilder builder) {
return literals(builder, "on", "off", "toggle", "enable", "disable");
}
public static <S> CompletableFuture<Suggestions> offsets(CommandContext<S> ignored, SuggestionsBuilder builder) {
return literals(builder, "1", "5", "10", "50", "100", "-1", "-5", "-10", "-50", "-100");
}
public static <S> CompletableFuture<Suggestions> vclipSegments(CommandContext<S> ignored, SuggestionsBuilder builder) {
return literals(builder, "1", "5", "10", "20", "50");
}
public static <S> CompletableFuture<Suggestions> vclipPacketLimits(CommandContext<S> ignored, SuggestionsBuilder builder) {
return literals(builder, "1", "5", "10", "20", "40", "100");
}
public static <S> CompletableFuture<Suggestions> damage(CommandContext<S> ignored, SuggestionsBuilder builder) {
return literals(builder, "1", "2", "4", "8", "20");
}
public static <S> CompletableFuture<Suggestions> counts(CommandContext<S> ignored, SuggestionsBuilder builder) {
return literals(builder, "1", "16", "32", "64");
}
public static <S> CompletableFuture<Suggestions> gamemodes(CommandContext<S> ignored, SuggestionsBuilder builder) {
return literals(builder, "survival", "creative", "adventure", "spectator", "reset", "0", "1", "2", "3");
}
public static <S> CompletableFuture<Suggestions> prefixes(CommandContext<S> ignored, SuggestionsBuilder builder) {
return literals(builder, ".", "%", "-", "_", "*", "#", "@", "&", "=");
}
public static <S> CompletableFuture<Suggestions> itemIds(CommandContext<S> ignored, SuggestionsBuilder builder) {
String remaining = builder.getRemaining().toLowerCase(Locale.ROOT);
for (Identifier id : BuiltInRegistries.ITEM.keySet()) {
String full = id.toString();
String shortId = id.getNamespace().equals("minecraft") ? id.getPath() : full;
if (full.toLowerCase(Locale.ROOT).startsWith(remaining)) builder.suggest(full);
if (!shortId.equals(full) && shortId.toLowerCase(Locale.ROOT).startsWith(remaining)) builder.suggest(shortId);
}
return builder.buildFuture();
}
}

View file

@ -0,0 +1,72 @@
package autismclient.commands.args;
import autismclient.commands.AutismCommandSource;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import net.minecraft.network.chat.Component;
import org.lwjgl.glfw.GLFW;
import java.lang.reflect.Field;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
public class KeyArgumentType implements ArgumentType<Integer> {
private static final Map<String, Integer> NAMES = new LinkedHashMap<>();
private static final SimpleCommandExceptionType UNKNOWN = new SimpleCommandExceptionType(Component.literal("Unknown key"));
static {
for (Field f : GLFW.class.getDeclaredFields()) {
String n = f.getName();
if (!n.startsWith("GLFW_KEY_")) continue;
try {
int code = f.getInt(null);
NAMES.put(n.substring("GLFW_KEY_".length()).toUpperCase(Locale.ROOT), code);
} catch (Throwable ignored) {}
}
}
public static KeyArgumentType key() { return new KeyArgumentType(); }
public static int get(CommandContext<AutismCommandSource> ctx, String name) {
return ctx.getArgument(name, Integer.class);
}
public static String keyName(int code) {
if (code < 0) return "NONE";
for (Map.Entry<String, Integer> e : NAMES.entrySet()) {
if (e.getValue() == code) return e.getKey();
}
return "KEY_" + code;
}
@Override
public Integer parse(StringReader reader) throws CommandSyntaxException {
String raw = reader.readUnquotedString();
String upper = raw.toUpperCase(Locale.ROOT);
Integer code = NAMES.get(upper);
if (code != null) return code;
if (upper.length() == 1) {
char c = upper.charAt(0);
if (c >= 'A' && c <= 'Z') return GLFW.GLFW_KEY_A + (c - 'A');
if (c >= '0' && c <= '9') return GLFW.GLFW_KEY_0 + (c - '0');
}
throw UNKNOWN.create();
}
@Override
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> context, SuggestionsBuilder builder) {
String remaining = builder.getRemaining().toUpperCase(Locale.ROOT);
for (String n : NAMES.keySet()) {
if (n.startsWith(remaining)) builder.suggest(n);
}
return builder.buildFuture();
}
}

View file

@ -0,0 +1,41 @@
package autismclient.commands.args;
import autismclient.commands.AutismCommandSource;
import autismclient.util.AutismMacroManager;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import java.util.Locale;
import java.util.concurrent.CompletableFuture;
public class MacroArgumentType implements ArgumentType<String> {
public static MacroArgumentType macroName() { return new MacroArgumentType(); }
public static String get(CommandContext<AutismCommandSource> ctx, String name) {
return ctx.getArgument(name, String.class);
}
@Override
public String parse(StringReader reader) throws CommandSyntaxException {
if (reader.canRead() && reader.peek() == '"') return reader.readQuotedString();
return reader.readUnquotedString();
}
@Override
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> context, SuggestionsBuilder builder) {
String remaining = builder.getRemaining().toLowerCase(Locale.ROOT);
for (autismclient.util.AutismMacro macro : AutismMacroManager.get().getAll()) {
if (macro == null || macro.name == null) continue;
String n = macro.name;
if (n.toLowerCase(Locale.ROOT).startsWith(remaining)) {
builder.suggest(n.contains(" ") ? "\"" + n + "\"" : n);
}
}
return builder.buildFuture();
}
}

View file

@ -0,0 +1,41 @@
package autismclient.commands.args;
import autismclient.commands.AutismCommandSource;
import autismclient.modules.PackModuleRegistry;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import java.util.Locale;
import java.util.concurrent.CompletableFuture;
public class ModuleArgumentType implements ArgumentType<String> {
public static ModuleArgumentType moduleName() { return new ModuleArgumentType(); }
public static String get(CommandContext<AutismCommandSource> ctx, String name) {
return ctx.getArgument(name, String.class);
}
@Override
public String parse(StringReader reader) throws CommandSyntaxException {
return reader.readUnquotedString();
}
@Override
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> context, SuggestionsBuilder builder) {
String remaining = builder.getRemaining().toLowerCase(Locale.ROOT);
for (String name : PackModuleRegistry.names()) {
if (name == null) continue;
if (name.toLowerCase(Locale.ROOT).startsWith(remaining)) {
builder.suggest(name);
}
}
if ("all".startsWith(remaining)) builder.suggest("all");
if ("hud".startsWith(remaining)) builder.suggest("hud");
return builder.buildFuture();
}
}

View file

@ -0,0 +1,39 @@
package autismclient.commands.args;
import autismclient.commands.AutismCommandSource;
import autismclient.util.AutismPacketRegistry;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import net.minecraft.network.protocol.Packet;
import java.util.Locale;
import java.util.concurrent.CompletableFuture;
public class PacketClassArgumentType implements ArgumentType<String> {
public static PacketClassArgumentType packetClass() { return new PacketClassArgumentType(); }
public static String get(CommandContext<AutismCommandSource> ctx, String name) {
return ctx.getArgument(name, String.class);
}
@Override
public String parse(StringReader reader) throws CommandSyntaxException {
return reader.readUnquotedString();
}
@Override
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> context, SuggestionsBuilder builder) {
String remaining = builder.getRemaining().toLowerCase(Locale.ROOT);
for (Class<? extends Packet<?>> cls : AutismPacketRegistry.getC2SPackets()) {
String name = AutismPacketRegistry.getName(cls);
if (name == null) continue;
if (name.toLowerCase(Locale.ROOT).contains(remaining)) builder.suggest(name);
}
return builder.buildFuture();
}
}

View file

@ -0,0 +1,65 @@
package autismclient.commands.args;
import autismclient.commands.AutismCommandSource;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import net.minecraft.network.chat.Component;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
public class XCarrySlotArgumentType implements ArgumentType<Integer> {
public static final int CURSOR = Integer.MIN_VALUE;
private static final Map<String, Integer> TOKENS = new LinkedHashMap<>();
static {
TOKENS.put("craft1", 1);
TOKENS.put("craft2", 2);
TOKENS.put("craft3", 3);
TOKENS.put("craft4", 4);
TOKENS.put("helmet", 5);
TOKENS.put("chestplate", 6);
TOKENS.put("leggings", 7);
TOKENS.put("boots", 8);
TOKENS.put("offhand", 45);
TOKENS.put("cursor", CURSOR);
}
private static final SimpleCommandExceptionType UNKNOWN =
new SimpleCommandExceptionType(Component.literal("Unknown XCarry slot — use craft1..craft4 / helmet / chestplate / leggings / boots / offhand / cursor."));
public static XCarrySlotArgumentType slot() { return new XCarrySlotArgumentType(); }
public static int get(CommandContext<AutismCommandSource> ctx, String name) {
return ctx.getArgument(name, Integer.class);
}
public static String displayName(int slotId) {
for (Map.Entry<String, Integer> e : TOKENS.entrySet()) if (e.getValue() == slotId) return e.getKey();
return "slot " + slotId;
}
@Override
public Integer parse(StringReader reader) throws CommandSyntaxException {
String raw = reader.readUnquotedString().toLowerCase(Locale.ROOT);
Integer id = TOKENS.get(raw);
if (id == null) throw UNKNOWN.create();
return id;
}
@Override
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> context, SuggestionsBuilder builder) {
String remaining = builder.getRemaining().toLowerCase(Locale.ROOT);
for (String name : TOKENS.keySet()) {
if (name.startsWith(remaining)) builder.suggest(name);
}
return builder.buildFuture();
}
}

View file

@ -0,0 +1,42 @@
package autismclient.commands.impl;
import autismclient.commands.Command;
import autismclient.commands.AutismCommandSource;
import autismclient.commands.AutismCommands;
import autismclient.commands.args.KeyArgumentType;
import autismclient.modules.AutismModule;
import autismclient.util.AutismClientMessaging;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.builder.RequiredArgumentBuilder;
public class BindCommand extends Command {
public BindCommand() { super("bind", "Bind a key to a command. Usage: bind <key> <command…> | bind clear <key>"); }
@Override
public void build(LiteralArgumentBuilder<AutismCommandSource> root) {
root.executes(ctx -> {
String prefix = AutismCommands.effectivePrefix();
AutismClientMessaging.sendPrefixed("§eUsage: §f" + prefix + "bind <key> <command>");
AutismClientMessaging.sendPrefixed("§7Example: §f" + prefix + "bind G " + prefix + "macro myMacro");
return SUCCESS;
});
root.then(LiteralArgumentBuilder.<AutismCommandSource>literal("clear")
.then(RequiredArgumentBuilder.<AutismCommandSource, Integer>argument("key", KeyArgumentType.key())
.executes(ctx -> {
int key = KeyArgumentType.get(ctx, "key");
AutismModule.get().clearCommandBind(key);
AutismClientMessaging.sendPrefixed("§eCleared bind for §f" + KeyArgumentType.keyName(key));
return SUCCESS;
})));
root.then(RequiredArgumentBuilder.<AutismCommandSource, Integer>argument("key", KeyArgumentType.key())
.then(RequiredArgumentBuilder.<AutismCommandSource, String>argument("command", StringArgumentType.greedyString())
.executes(ctx -> {
int key = KeyArgumentType.get(ctx, "key");
String cmd = StringArgumentType.getString(ctx, "command");
AutismModule.get().setCommandBind(key, cmd);
AutismClientMessaging.sendPrefixed("§aBound §f" + KeyArgumentType.keyName(key) + "§a → §f" + cmd);
return SUCCESS;
})));
}
}

View file

@ -0,0 +1,27 @@
package autismclient.commands.impl;
import autismclient.commands.Command;
import autismclient.commands.AutismCommandSource;
import autismclient.commands.args.KeyArgumentType;
import autismclient.modules.AutismModule;
import autismclient.util.AutismClientMessaging;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import java.util.Map;
public class BindsCommand extends Command {
public BindsCommand() { super("binds", "List command keybinds (set with `bind`)."); }
@Override
public void build(LiteralArgumentBuilder<AutismCommandSource> root) {
root.executes(ctx -> {
Map<Integer, String> binds = AutismModule.get().getCommandBinds();
if (binds.isEmpty()) { AutismClientMessaging.sendPrefixed("§eNo command keybinds set."); return SUCCESS; }
AutismClientMessaging.sendPrefixed("§e" + binds.size() + " command keybinds:");
for (Map.Entry<Integer, String> e : binds.entrySet()) {
AutismClientMessaging.sendPrefixed("§b" + KeyArgumentType.keyName(e.getKey()) + "§7 → §f" + e.getValue());
}
return SUCCESS;
});
}
}

View file

@ -0,0 +1,28 @@
package autismclient.commands.impl;
import autismclient.commands.Command;
import autismclient.commands.AutismCommandSource;
import autismclient.commands.AutismCommands;
import autismclient.util.AutismClientMessaging;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
public class CommandsCommand extends Command {
public CommandsCommand() { super("commands", "List all available commands.", "cmds"); }
@Override
public void build(LiteralArgumentBuilder<AutismCommandSource> root) {
root.executes(ctx -> {
String prefix = AutismCommands.effectivePrefix();
AutismClientMessaging.sendPrefixed("§e" + AutismCommands.all().size() + " commands (prefix §f" + prefix + "§e):");
StringBuilder line = new StringBuilder();
for (Command c : AutismCommands.all()) {
if (line.length() > 0) line.append("§7, ");
line.append("§f").append(c.name());
if (line.length() > 200) { AutismClientMessaging.sendPrefixed(line.toString()); line.setLength(0); }
}
if (line.length() > 0) AutismClientMessaging.sendPrefixed(line.toString());
AutismClientMessaging.sendPrefixed("§7Type §f" + prefix + "help <command>§7 for details.");
return SUCCESS;
});
}
}

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