mirror of
https://github.com/MinecraftForge/MinecraftForge.git
synced 2026-11-14 09:05:17 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d00953b220 |
No files matched your search
@@ -1,27 +0,0 @@
|
||||
* text eol=lf
|
||||
*.bat text eol=crlf
|
||||
*.patch text eol=lf
|
||||
*.java text eol=lf
|
||||
*.gradle text eol=crlf
|
||||
**/MANIFEST.MF text eol=crlf
|
||||
*.png binary
|
||||
*.gif binary
|
||||
*.exe binary
|
||||
*.dll binary
|
||||
*.jar binary
|
||||
*.lzma binary
|
||||
*.zip binary
|
||||
*.pyd binary
|
||||
*.cfg text eol=lf
|
||||
*.py text eol=lf
|
||||
*.jks binary
|
||||
|
||||
# Disable autocrlf on generated files, they always generate with LF
|
||||
src/generated/**/.cache/cache text eol=lf
|
||||
src/generated/**/*.json text eol=lf
|
||||
src/generated_test/**/.cache/cache text eol=lf
|
||||
src/generated_test/**/*.json text eol=lf
|
||||
|
||||
# We force eclipse to use unix line endings
|
||||
ide/eclipse/template/.settings/*.prefs text eol=lf
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
---
|
||||
name: Feature request
|
||||
about: Want to request a feature?
|
||||
title: ''
|
||||
labels: Feature
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
<!-- Please note, feature requests that are submitted as GitHub issues here are rarely implemented. -->
|
||||
<!-- If you'd like to see something in Forge, you should be ready to implement it as a PR. -->
|
||||
<!-- If you're not sure, open a Draft PR or discuss it in the Discord server. -->
|
||||
<!-- Discord: https://discord..minecraftforge.net/ -->
|
||||
@@ -1,27 +0,0 @@
|
||||
---
|
||||
name: Issue report
|
||||
about: Visit the forum first for issues with crashes.
|
||||
title: ''
|
||||
labels: Triage
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
<!-- Thank you for reporting! -->
|
||||
|
||||
<!-- For support with crashes and issues, please create a post on the forum instead: -->
|
||||
<!-- https://www.minecraftforge.net/forum/forum/18-support-bug-reports/ -->
|
||||
<!-- You can also use the discord for support, https://discord.minecraftforge.net/ -->
|
||||
|
||||
**Minecraft Version:** {Minecraft version}
|
||||
|
||||
**Forge Version:** {Forge version. *Version number, not latest/rb*}
|
||||
|
||||
**Logs:** {Link(s) to GitHub Gist with full latest.log and/or crash report}
|
||||
|
||||
**Steps to Reproduce:**
|
||||
1. Do this
|
||||
2. Then do that
|
||||
3. ...
|
||||
|
||||
**Description of issue:**
|
||||
@@ -1,43 +0,0 @@
|
||||
# Configuration for probot-stale - https://github.com/probot/stale
|
||||
|
||||
# Label to use when marking as stale
|
||||
staleLabel: Stale
|
||||
# Comment to post when removing the stale label. Set to `false` to disable
|
||||
unmarkComment: false
|
||||
# Limit the number of actions per hour, from 1-30. Default is 30
|
||||
limitPerRun: 1
|
||||
# Issues with these labels will never be considered stale. Set to `[]` to disable
|
||||
exemptLabels:
|
||||
- Assigned
|
||||
|
||||
pulls:
|
||||
# Number of days of inactivity before a Pull Request becomes stale
|
||||
daysUntilStale: 60
|
||||
# Number of days of inactivity before a stale Pull Request is closed
|
||||
daysUntilClose: 14
|
||||
# Comment to post when marking as stale. Set to `false` to disable
|
||||
markComment: >
|
||||
This pull request has been automatically marked as stale because it has not had recent
|
||||
activity, and will be closed if no further activity occurs. If this pull request was
|
||||
overlooked, forgotten, or should remain open for any other reason, please reply
|
||||
here to call attention to it and remove the stale status. Thank you for your contributions.
|
||||
# Comment to post when closing a stale Pull Request. Set to `false` to disable
|
||||
closeComment: >
|
||||
This pull request has been automatically closed because it has not had
|
||||
recent activity. Please feel free to update or reopen it.
|
||||
issues:
|
||||
# Number of days of inactivity before an Issue becomes stale
|
||||
daysUntilStale: 180
|
||||
# Number of days of inactivity before a stale Issue is closed
|
||||
daysUntilClose: 14
|
||||
# Comment to post when marking as stale. Set to `false` to disable
|
||||
markComment: >
|
||||
This issue has been automatically marked as stale because it has not had activity
|
||||
in a long time. If this issue is still relevant and should remain open, please reply
|
||||
with a short explanation (e.g. "I have checked the code and this issue is still relevant because ___."
|
||||
or "Here's a screenshot of this issue on the latest version").
|
||||
Thank you for your contributions!
|
||||
# Comment to post when closing a stale Issue. Set to `false` to disable
|
||||
closeComment: >
|
||||
This issue has been automatically closed because it has not had
|
||||
activity in a long time. Please feel free to reopen it or create a new issue.
|
||||
@@ -1,16 +0,0 @@
|
||||
name: 'Comment actions'
|
||||
|
||||
on: issue_comment
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
issues: write
|
||||
pull-requests: write
|
||||
discussions: write
|
||||
|
||||
jobs:
|
||||
labels:
|
||||
uses: MinecraftForge/SharedActions/.github/workflows/comment_actions.yml@main
|
||||
secrets:
|
||||
GH_APP_KEY: ${{ secrets.GH_APP_KEY }}
|
||||
GH_APP_NAME: ${{ secrets.GH_APP_NAME }}
|
||||
@@ -1,16 +0,0 @@
|
||||
name: 'Issue actions'
|
||||
|
||||
on: issues
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
issues: write
|
||||
pull-requests: write
|
||||
discussions: write
|
||||
|
||||
jobs:
|
||||
labels:
|
||||
uses: MinecraftForge/SharedActions/.github/workflows/issue_actions.yml@main
|
||||
secrets:
|
||||
GH_APP_KEY: ${{ secrets.GH_APP_KEY }}
|
||||
GH_APP_NAME: ${{ secrets.GH_APP_NAME }}
|
||||
@@ -1,28 +0,0 @@
|
||||
name: Publish
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ '26.3' ]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
build:
|
||||
uses: MinecraftForge/SharedActions/.github/workflows/gradle.yml@main
|
||||
with:
|
||||
java: 21
|
||||
gradle_setup: './gradlew setup'
|
||||
gradle_tasks: 'build publish'
|
||||
artifact_name: 'forge'
|
||||
secrets:
|
||||
DISCORD_WEBHOOK: ${{ secrets.DISCORD_WEBHOOK }}
|
||||
PROMOTE_ARTIFACT_WEBHOOK: ${{ secrets.PROMOTE_ARTIFACT_WEBHOOK }}
|
||||
PROMOTE_ARTIFACT_USERNAME: ${{ secrets.PROMOTE_ARTIFACT_USERNAME }}
|
||||
PROMOTE_ARTIFACT_PASSWORD: ${{ secrets.PROMOTE_ARTIFACT_PASSWORD }}
|
||||
MAVEN_USER: ${{ secrets.MAVEN_USER }}
|
||||
MAVEN_PASSWORD: ${{ secrets.MAVEN_PASSWORD }}
|
||||
SIGN_KEY_ALIAS: ${{ secrets.SIGN_KEY_ALIAS }}
|
||||
SIGN_KEY_PASSWORD: ${{ secrets.SIGN_KEY_PASSWORD }}
|
||||
SIGN_KEYSTORE_PASSWORD: ${{ secrets.SIGN_KEYSTORE_PASSWORD }}
|
||||
SIGN_KEYSTORE_DATA: ${{ secrets.SIGN_KEYSTORE_DATA }}
|
||||
@@ -1,13 +0,0 @@
|
||||
name: 'PR Review'
|
||||
|
||||
on: pull_request_review
|
||||
|
||||
jobs:
|
||||
upload_payload:
|
||||
name: Upload payload
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/upload-artifact@v4 # Payload artifact is consumed in Actionable
|
||||
with:
|
||||
name: payload
|
||||
path: ${{ github.event_path }}
|
||||
@@ -1,13 +0,0 @@
|
||||
name: 'PR Review Comment'
|
||||
|
||||
on: pull_request_review_comment
|
||||
|
||||
jobs:
|
||||
upload_payload:
|
||||
name: Upload payload
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/upload-artifact@v4 # Payload artifact is consumed in Actionable
|
||||
with:
|
||||
name: payload
|
||||
path: ${{ github.event_path }}
|
||||
@@ -1,20 +0,0 @@
|
||||
name: 'Pull Request Review Comment actions'
|
||||
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: [PR Review Comment]
|
||||
types:
|
||||
- completed
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
issues: write
|
||||
pull-requests: write
|
||||
discussions: write
|
||||
|
||||
jobs:
|
||||
labels:
|
||||
uses: MinecraftForge/SharedActions/.github/workflows/pr_review_comment_actions.yml@main
|
||||
secrets:
|
||||
GH_APP_KEY: ${{ secrets.GH_APP_KEY }}
|
||||
GH_APP_NAME: ${{ secrets.GH_APP_NAME }}
|
||||
@@ -1,20 +0,0 @@
|
||||
name: 'Pull Request Review actions'
|
||||
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: [PR Review]
|
||||
types:
|
||||
- completed
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
issues: write
|
||||
pull-requests: write
|
||||
discussions: write
|
||||
|
||||
jobs:
|
||||
labels:
|
||||
uses: MinecraftForge/SharedActions/.github/workflows/pr_review_actions.yml@main
|
||||
secrets:
|
||||
GH_APP_KEY: ${{ secrets.GH_APP_KEY }}
|
||||
GH_APP_NAME: ${{ secrets.GH_APP_NAME }}
|
||||
@@ -1,18 +0,0 @@
|
||||
name: 'Pull Request actions'
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
types: [assigned, unassigned, labeled, unlabeled, opened, edited, closed, reopened, synchronize, converted_to_draft, ready_for_review, locked, unlocked, review_requested, review_request_removed, auto_merge_enabled, auto_merge_disabled]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
issues: write
|
||||
pull-requests: write
|
||||
discussions: write
|
||||
|
||||
jobs:
|
||||
labels:
|
||||
uses: MinecraftForge/SharedActions/.github/workflows/pr_actions.yml@main
|
||||
secrets:
|
||||
GH_APP_KEY: ${{ secrets.GH_APP_KEY }}
|
||||
GH_APP_NAME: ${{ secrets.GH_APP_NAME }}
|
||||
@@ -1,16 +0,0 @@
|
||||
name: 'Push actions'
|
||||
|
||||
on: push
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
issues: write
|
||||
pull-requests: write
|
||||
discussions: write
|
||||
|
||||
jobs:
|
||||
labels:
|
||||
uses: MinecraftForge/SharedActions/.github/workflows/push_actions.yml@main
|
||||
secrets:
|
||||
GH_APP_KEY: ${{ secrets.GH_APP_KEY }}
|
||||
GH_APP_NAME: ${{ secrets.GH_APP_NAME }}
|
||||
-59
@@ -1,59 +0,0 @@
|
||||
#forgedev dev if the folder exists in here
|
||||
forgedev
|
||||
|
||||
#eclipse
|
||||
**/bin
|
||||
**/.settings
|
||||
**/.classpath
|
||||
*.project
|
||||
|
||||
#In case people make their workspace in the repo
|
||||
/eclipse/
|
||||
|
||||
#idea
|
||||
**/.idea
|
||||
/*/out
|
||||
/classes
|
||||
*.iml
|
||||
|
||||
# We however WANT the ide folder as it has tempaltes/configs for developing Forge.
|
||||
!ide/**
|
||||
|
||||
#gradle
|
||||
/build
|
||||
/.gradle
|
||||
/*/build
|
||||
/*/.gradle
|
||||
|
||||
# Minecraft
|
||||
/run
|
||||
/*.launch
|
||||
|
||||
# Projects repo, either ignore it, or ignore patches.
|
||||
src/minecraft
|
||||
|
||||
#occupational hazards
|
||||
/*/runs/
|
||||
/repo/
|
||||
/rejects-*/
|
||||
**/src/*/generated/**/.cache/
|
||||
**/*.launch
|
||||
**/.project_info.properties
|
||||
|
||||
# Generated by gradle every import
|
||||
**/src/main/resources/META-INF/MANIFEST.MF
|
||||
/fmlloader/src/main/resources/forge_version.json
|
||||
|
||||
/ForgeRoot.ipr
|
||||
/ForgeRoot.iws
|
||||
|
||||
# APT stuff
|
||||
/*/.gitignore
|
||||
/*/.factorypath
|
||||
/*/.apt_generated/
|
||||
/fmlcore/logs/
|
||||
/lib/
|
||||
/_actual/
|
||||
/runs/
|
||||
/forge.ipr
|
||||
/forge.iws
|
||||
@@ -1,2 +0,0 @@
|
||||
Copyright (c) Forge Development LLC and contributors
|
||||
SPDX-License-Identifier: LGPL-2.1-only
|
||||
-523
@@ -1,523 +0,0 @@
|
||||
Unless noted below, Minecraft Forge, Forge Mod Loader, and all
|
||||
parts herein are licensed under the terms of the LGPL 2.1 found
|
||||
here http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt and
|
||||
copied below.
|
||||
|
||||
Homepage: https://minecraftforge.net/
|
||||
https://github.com/MinecraftForge/MinecraftForge
|
||||
|
||||
|
||||
A note on authorship:
|
||||
All source artifacts are property of their original author, with
|
||||
the exclusion of the contents of the patches directory and others
|
||||
copied from it from time to time. Authorship of the contents of
|
||||
the patches directory is retained by the Minecraft Forge project.
|
||||
This is because the patches are partially machine generated
|
||||
artifacts, and are changed heavily due to the way forge works.
|
||||
Individual attribution within them is impossible.
|
||||
|
||||
Consent:
|
||||
All contributions to Forge must consent to the release of any
|
||||
patch content to the Forge project.
|
||||
|
||||
A note on infectivity:
|
||||
The LGPL is chosen specifically so that projects may depend on Forge
|
||||
features without being infected with its license. That is the
|
||||
purpose of the LGPL. Mods and others using this code via ordinary
|
||||
Java mechanics for referencing libraries are specifically not bound
|
||||
by Forge's license for the Mod code.
|
||||
|
||||
|
||||
=== MCP Data ===
|
||||
This software includes data from the Minecraft Coder Pack (MCP), with kind permission
|
||||
from them. The license to MCP data is not transitive - distribution of this data by
|
||||
third parties requires independent licensing from the MCP team. This data is not
|
||||
redistributable without permission from the MCP team.
|
||||
|
||||
=== Sharing ===
|
||||
I grant permission for some parts of FML to be redistributed outside the terms of the LGPL, for the benefit of
|
||||
the minecraft modding community. All contributions to these parts should be licensed under the same additional grant.
|
||||
|
||||
-- Runtime patcher --
|
||||
License is granted to redistribute the runtime patcher code (src/main/java/net/minecraftforge/fml/common/patcher
|
||||
and subdirectories) under any alternative open source license as classified by the OSI (http://opensource.org/licenses)
|
||||
|
||||
-- ASM transformers --
|
||||
License is granted to redistribute the ASM transformer code (src/main/java/net/minecraftforge/common/asm/ and subdirectories)
|
||||
under any alternative open source license as classified by the OSI (http://opensource.org/licenses)
|
||||
|
||||
=========================================================================
|
||||
This software includes portions from the Apache Maven project at
|
||||
http://maven.apache.org/ specifically the ComparableVersion.java code. It is
|
||||
included based on guidelines at
|
||||
http://www.softwarefreedom.org/resources/2007/gpl-non-gpl-collaboration.html
|
||||
with notices intact. The only change is a non-functional change of package name.
|
||||
|
||||
This software contains a partial repackaging of javaxdelta, a BSD licensed program for generating
|
||||
binary differences and applying them, sourced from the subversion at http://sourceforge.net/projects/javaxdelta/
|
||||
authored by genman, heikok, pivot.
|
||||
The only changes are to replace some Trove collection types with standard Java collections, and repackaged.
|
||||
|
||||
This software includes the Monocraft font from https://github.com/IdreesInc/Monocraft/ for use in the early loading
|
||||
display.
|
||||
=========================================================================
|
||||
|
||||
|
||||
GNU LESSER GENERAL PUBLIC LICENSE
|
||||
Version 2.1, February 1999
|
||||
|
||||
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
[This is the first released version of the Lesser GPL. It also counts
|
||||
as the successor of the GNU Library Public License, version 2, hence
|
||||
the version number 2.1.]
|
||||
|
||||
Preamble
|
||||
|
||||
The licenses for most software are designed to take away your
|
||||
freedom to share and change it. By contrast, the GNU General Public
|
||||
Licenses are intended to guarantee your freedom to share and change
|
||||
free software--to make sure the software is free for all its users.
|
||||
|
||||
This license, the Lesser General Public License, applies to some
|
||||
specially designated software packages--typically libraries--of the
|
||||
Free Software Foundation and other authors who decide to use it. You
|
||||
can use it too, but we suggest you first think carefully about whether
|
||||
this license or the ordinary General Public License is the better
|
||||
strategy to use in any particular case, based on the explanations below.
|
||||
|
||||
When we speak of free software, we are referring to freedom of use,
|
||||
not price. Our General Public Licenses are designed to make sure that
|
||||
you have the freedom to distribute copies of free software (and charge
|
||||
for this service if you wish); that you receive source code or can get
|
||||
it if you want it; that you can change the software and use pieces of
|
||||
it in new free programs; and that you are informed that you can do
|
||||
these things.
|
||||
|
||||
To protect your rights, we need to make restrictions that forbid
|
||||
distributors to deny you these rights or to ask you to surrender these
|
||||
rights. These restrictions translate to certain responsibilities for
|
||||
you if you distribute copies of the library or if you modify it.
|
||||
|
||||
For example, if you distribute copies of the library, whether gratis
|
||||
or for a fee, you must give the recipients all the rights that we gave
|
||||
you. You must make sure that they, too, receive or can get the source
|
||||
code. If you link other code with the library, you must provide
|
||||
complete object files to the recipients, so that they can relink them
|
||||
with the library after making changes to the library and recompiling
|
||||
it. And you must show them these terms so they know their rights.
|
||||
|
||||
We protect your rights with a two-step method: (1) we copyright the
|
||||
library, and (2) we offer you this license, which gives you legal
|
||||
permission to copy, distribute and/or modify the library.
|
||||
|
||||
To protect each distributor, we want to make it very clear that
|
||||
there is no warranty for the free library. Also, if the library is
|
||||
modified by someone else and passed on, the recipients should know
|
||||
that what they have is not the original version, so that the original
|
||||
author's reputation will not be affected by problems that might be
|
||||
introduced by others.
|
||||
|
||||
Finally, software patents pose a constant threat to the existence of
|
||||
any free program. We wish to make sure that a company cannot
|
||||
effectively restrict the users of a free program by obtaining a
|
||||
restrictive license from a patent holder. Therefore, we insist that
|
||||
any patent license obtained for a version of the library must be
|
||||
consistent with the full freedom of use specified in this license.
|
||||
|
||||
Most GNU software, including some libraries, is covered by the
|
||||
ordinary GNU General Public License. This license, the GNU Lesser
|
||||
General Public License, applies to certain designated libraries, and
|
||||
is quite different from the ordinary General Public License. We use
|
||||
this license for certain libraries in order to permit linking those
|
||||
libraries into non-free programs.
|
||||
|
||||
When a program is linked with a library, whether statically or using
|
||||
a shared library, the combination of the two is legally speaking a
|
||||
combined work, a derivative of the original library. The ordinary
|
||||
General Public License therefore permits such linking only if the
|
||||
entire combination fits its criteria of freedom. The Lesser General
|
||||
Public License permits more lax criteria for linking other code with
|
||||
the library.
|
||||
|
||||
We call this license the "Lesser" General Public License because it
|
||||
does Less to protect the user's freedom than the ordinary General
|
||||
Public License. It also provides other free software developers Less
|
||||
of an advantage over competing non-free programs. These disadvantages
|
||||
are the reason we use the ordinary General Public License for many
|
||||
libraries. However, the Lesser license provides advantages in certain
|
||||
special circumstances.
|
||||
|
||||
For example, on rare occasions, there may be a special need to
|
||||
encourage the widest possible use of a certain library, so that it becomes
|
||||
a de-facto standard. To achieve this, non-free programs must be
|
||||
allowed to use the library. A more frequent case is that a free
|
||||
library does the same job as widely used non-free libraries. In this
|
||||
case, there is little to gain by limiting the free library to free
|
||||
software only, so we use the Lesser General Public License.
|
||||
|
||||
In other cases, permission to use a particular library in non-free
|
||||
programs enables a greater number of people to use a large body of
|
||||
free software. For example, permission to use the GNU C Library in
|
||||
non-free programs enables many more people to use the whole GNU
|
||||
operating system, as well as its variant, the GNU/Linux operating
|
||||
system.
|
||||
|
||||
Although the Lesser General Public License is Less protective of the
|
||||
users' freedom, it does ensure that the user of a program that is
|
||||
linked with the Library has the freedom and the wherewithal to run
|
||||
that program using a modified version of the Library.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow. Pay close attention to the difference between a
|
||||
"work based on the library" and a "work that uses the library". The
|
||||
former contains code derived from the library, whereas the latter must
|
||||
be combined with the library in order to run.
|
||||
|
||||
GNU LESSER GENERAL PUBLIC LICENSE
|
||||
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
|
||||
|
||||
0. This License Agreement applies to any software library or other
|
||||
program which contains a notice placed by the copyright holder or
|
||||
other authorized party saying it may be distributed under the terms of
|
||||
this Lesser General Public License (also called "this License").
|
||||
Each licensee is addressed as "you".
|
||||
|
||||
A "library" means a collection of software functions and/or data
|
||||
prepared so as to be conveniently linked with application programs
|
||||
(which use some of those functions and data) to form executables.
|
||||
|
||||
The "Library", below, refers to any such software library or work
|
||||
which has been distributed under these terms. A "work based on the
|
||||
Library" means either the Library or any derivative work under
|
||||
copyright law: that is to say, a work containing the Library or a
|
||||
portion of it, either verbatim or with modifications and/or translated
|
||||
straightforwardly into another language. (Hereinafter, translation is
|
||||
included without limitation in the term "modification".)
|
||||
|
||||
"Source code" for a work means the preferred form of the work for
|
||||
making modifications to it. For a library, complete source code means
|
||||
all the source code for all modules it contains, plus any associated
|
||||
interface definition files, plus the scripts used to control compilation
|
||||
and installation of the library.
|
||||
|
||||
Activities other than copying, distribution and modification are not
|
||||
covered by this License; they are outside its scope. The act of
|
||||
running a program using the Library is not restricted, and output from
|
||||
such a program is covered only if its contents constitute a work based
|
||||
on the Library (independent of the use of the Library in a tool for
|
||||
writing it). Whether that is true depends on what the Library does
|
||||
and what the program that uses the Library does.
|
||||
|
||||
1. You may copy and distribute verbatim copies of the Library's
|
||||
complete source code as you receive it, in any medium, provided that
|
||||
you conspicuously and appropriately publish on each copy an
|
||||
appropriate copyright notice and disclaimer of warranty; keep intact
|
||||
all the notices that refer to this License and to the absence of any
|
||||
warranty; and distribute a copy of this License along with the
|
||||
Library.
|
||||
|
||||
You may charge a fee for the physical act of transferring a copy,
|
||||
and you may at your option offer warranty protection in exchange for a
|
||||
fee.
|
||||
|
||||
2. You may modify your copy or copies of the Library or any portion
|
||||
of it, thus forming a work based on the Library, and copy and
|
||||
distribute such modifications or work under the terms of Section 1
|
||||
above, provided that you also meet all of these conditions:
|
||||
|
||||
a) The modified work must itself be a software library.
|
||||
|
||||
b) You must cause the files modified to carry prominent notices
|
||||
stating that you changed the files and the date of any change.
|
||||
|
||||
c) You must cause the whole of the work to be licensed at no
|
||||
charge to all third parties under the terms of this License.
|
||||
|
||||
d) If a facility in the modified Library refers to a function or a
|
||||
table of data to be supplied by an application program that uses
|
||||
the facility, other than as an argument passed when the facility
|
||||
is invoked, then you must make a good faith effort to ensure that,
|
||||
in the event an application does not supply such function or
|
||||
table, the facility still operates, and performs whatever part of
|
||||
its purpose remains meaningful.
|
||||
|
||||
(For example, a function in a library to compute square roots has
|
||||
a purpose that is entirely well-defined independent of the
|
||||
application. Therefore, Subsection 2d requires that any
|
||||
application-supplied function or table used by this function must
|
||||
be optional: if the application does not supply it, the square
|
||||
root function must still compute square roots.)
|
||||
|
||||
These requirements apply to the modified work as a whole. If
|
||||
identifiable sections of that work are not derived from the Library,
|
||||
and can be reasonably considered independent and separate works in
|
||||
themselves, then this License, and its terms, do not apply to those
|
||||
sections when you distribute them as separate works. But when you
|
||||
distribute the same sections as part of a whole which is a work based
|
||||
on the Library, the distribution of the whole must be on the terms of
|
||||
this License, whose permissions for other licensees extend to the
|
||||
entire whole, and thus to each and every part regardless of who wrote
|
||||
it.
|
||||
|
||||
Thus, it is not the intent of this section to claim rights or contest
|
||||
your rights to work written entirely by you; rather, the intent is to
|
||||
exercise the right to control the distribution of derivative or
|
||||
collective works based on the Library.
|
||||
|
||||
In addition, mere aggregation of another work not based on the Library
|
||||
with the Library (or with a work based on the Library) on a volume of
|
||||
a storage or distribution medium does not bring the other work under
|
||||
the scope of this License.
|
||||
|
||||
3. You may opt to apply the terms of the ordinary GNU General Public
|
||||
License instead of this License to a given copy of the Library. To do
|
||||
this, you must alter all the notices that refer to this License, so
|
||||
that they refer to the ordinary GNU General Public License, version 2,
|
||||
instead of to this License. (If a newer version than version 2 of the
|
||||
ordinary GNU General Public License has appeared, then you can specify
|
||||
that version instead if you wish.) Do not make any other change in
|
||||
these notices.
|
||||
|
||||
Once this change is made in a given copy, it is irreversible for
|
||||
that copy, so the ordinary GNU General Public License applies to all
|
||||
subsequent copies and derivative works made from that copy.
|
||||
|
||||
This option is useful when you wish to copy part of the code of
|
||||
the Library into a program that is not a library.
|
||||
|
||||
4. You may copy and distribute the Library (or a portion or
|
||||
derivative of it, under Section 2) in object code or executable form
|
||||
under the terms of Sections 1 and 2 above provided that you accompany
|
||||
it with the complete corresponding machine-readable source code, which
|
||||
must be distributed under the terms of Sections 1 and 2 above on a
|
||||
medium customarily used for software interchange.
|
||||
|
||||
If distribution of object code is made by offering access to copy
|
||||
from a designated place, then offering equivalent access to copy the
|
||||
source code from the same place satisfies the requirement to
|
||||
distribute the source code, even though third parties are not
|
||||
compelled to copy the source along with the object code.
|
||||
|
||||
5. A program that contains no derivative of any portion of the
|
||||
Library, but is designed to work with the Library by being compiled or
|
||||
linked with it, is called a "work that uses the Library". Such a
|
||||
work, in isolation, is not a derivative work of the Library, and
|
||||
therefore falls outside the scope of this License.
|
||||
|
||||
However, linking a "work that uses the Library" with the Library
|
||||
creates an executable that is a derivative of the Library (because it
|
||||
contains portions of the Library), rather than a "work that uses the
|
||||
library". The executable is therefore covered by this License.
|
||||
Section 6 states terms for distribution of such executables.
|
||||
|
||||
When a "work that uses the Library" uses material from a header file
|
||||
that is part of the Library, the object code for the work may be a
|
||||
derivative work of the Library even though the source code is not.
|
||||
Whether this is true is especially significant if the work can be
|
||||
linked without the Library, or if the work is itself a library. The
|
||||
threshold for this to be true is not precisely defined by law.
|
||||
|
||||
If such an object file uses only numerical parameters, data
|
||||
structure layouts and accessors, and small macros and small inline
|
||||
functions (ten lines or less in length), then the use of the object
|
||||
file is unrestricted, regardless of whether it is legally a derivative
|
||||
work. (Executables containing this object code plus portions of the
|
||||
Library will still fall under Section 6.)
|
||||
|
||||
Otherwise, if the work is a derivative of the Library, you may
|
||||
distribute the object code for the work under the terms of Section 6.
|
||||
Any executables containing that work also fall under Section 6,
|
||||
whether or not they are linked directly with the Library itself.
|
||||
|
||||
6. As an exception to the Sections above, you may also combine or
|
||||
link a "work that uses the Library" with the Library to produce a
|
||||
work containing portions of the Library, and distribute that work
|
||||
under terms of your choice, provided that the terms permit
|
||||
modification of the work for the customer's own use and reverse
|
||||
engineering for debugging such modifications.
|
||||
|
||||
You must give prominent notice with each copy of the work that the
|
||||
Library is used in it and that the Library and its use are covered by
|
||||
this License. You must supply a copy of this License. If the work
|
||||
during execution displays copyright notices, you must include the
|
||||
copyright notice for the Library among them, as well as a reference
|
||||
directing the user to the copy of this License. Also, you must do one
|
||||
of these things:
|
||||
|
||||
a) Accompany the work with the complete corresponding
|
||||
machine-readable source code for the Library including whatever
|
||||
changes were used in the work (which must be distributed under
|
||||
Sections 1 and 2 above); and, if the work is an executable linked
|
||||
with the Library, with the complete machine-readable "work that
|
||||
uses the Library", as object code and/or source code, so that the
|
||||
user can modify the Library and then relink to produce a modified
|
||||
executable containing the modified Library. (It is understood
|
||||
that the user who changes the contents of definitions files in the
|
||||
Library will not necessarily be able to recompile the application
|
||||
to use the modified definitions.)
|
||||
|
||||
b) Use a suitable shared library mechanism for linking with the
|
||||
Library. A suitable mechanism is one that (1) uses at run time a
|
||||
copy of the library already present on the user's computer system,
|
||||
rather than copying library functions into the executable, and (2)
|
||||
will operate properly with a modified version of the library, if
|
||||
the user installs one, as long as the modified version is
|
||||
interface-compatible with the version that the work was made with.
|
||||
|
||||
c) Accompany the work with a written offer, valid for at
|
||||
least three years, to give the same user the materials
|
||||
specified in Subsection 6a, above, for a charge no more
|
||||
than the cost of performing this distribution.
|
||||
|
||||
d) If distribution of the work is made by offering access to copy
|
||||
from a designated place, offer equivalent access to copy the above
|
||||
specified materials from the same place.
|
||||
|
||||
e) Verify that the user has already received a copy of these
|
||||
materials or that you have already sent this user a copy.
|
||||
|
||||
For an executable, the required form of the "work that uses the
|
||||
Library" must include any data and utility programs needed for
|
||||
reproducing the executable from it. However, as a special exception,
|
||||
the materials to be distributed need not include anything that is
|
||||
normally distributed (in either source or binary form) with the major
|
||||
components (compiler, kernel, and so on) of the operating system on
|
||||
which the executable runs, unless that component itself accompanies
|
||||
the executable.
|
||||
|
||||
It may happen that this requirement contradicts the license
|
||||
restrictions of other proprietary libraries that do not normally
|
||||
accompany the operating system. Such a contradiction means you cannot
|
||||
use both them and the Library together in an executable that you
|
||||
distribute.
|
||||
|
||||
7. You may place library facilities that are a work based on the
|
||||
Library side-by-side in a single library together with other library
|
||||
facilities not covered by this License, and distribute such a combined
|
||||
library, provided that the separate distribution of the work based on
|
||||
the Library and of the other library facilities is otherwise
|
||||
permitted, and provided that you do these two things:
|
||||
|
||||
a) Accompany the combined library with a copy of the same work
|
||||
based on the Library, uncombined with any other library
|
||||
facilities. This must be distributed under the terms of the
|
||||
Sections above.
|
||||
|
||||
b) Give prominent notice with the combined library of the fact
|
||||
that part of it is a work based on the Library, and explaining
|
||||
where to find the accompanying uncombined form of the same work.
|
||||
|
||||
8. You may not copy, modify, sublicense, link with, or distribute
|
||||
the Library except as expressly provided under this License. Any
|
||||
attempt otherwise to copy, modify, sublicense, link with, or
|
||||
distribute the Library is void, and will automatically terminate your
|
||||
rights under this License. However, parties who have received copies,
|
||||
or rights, from you under this License will not have their licenses
|
||||
terminated so long as such parties remain in full compliance.
|
||||
|
||||
9. You are not required to accept this License, since you have not
|
||||
signed it. However, nothing else grants you permission to modify or
|
||||
distribute the Library or its derivative works. These actions are
|
||||
prohibited by law if you do not accept this License. Therefore, by
|
||||
modifying or distributing the Library (or any work based on the
|
||||
Library), you indicate your acceptance of this License to do so, and
|
||||
all its terms and conditions for copying, distributing or modifying
|
||||
the Library or works based on it.
|
||||
|
||||
10. Each time you redistribute the Library (or any work based on the
|
||||
Library), the recipient automatically receives a license from the
|
||||
original licensor to copy, distribute, link with or modify the Library
|
||||
subject to these terms and conditions. You may not impose any further
|
||||
restrictions on the recipients' exercise of the rights granted herein.
|
||||
You are not responsible for enforcing compliance by third parties with
|
||||
this License.
|
||||
|
||||
11. If, as a consequence of a court judgment or allegation of patent
|
||||
infringement or for any other reason (not limited to patent issues),
|
||||
conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot
|
||||
distribute so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you
|
||||
may not distribute the Library at all. For example, if a patent
|
||||
license would not permit royalty-free redistribution of the Library by
|
||||
all those who receive copies directly or indirectly through you, then
|
||||
the only way you could satisfy both it and this License would be to
|
||||
refrain entirely from distribution of the Library.
|
||||
|
||||
If any portion of this section is held invalid or unenforceable under any
|
||||
particular circumstance, the balance of the section is intended to apply,
|
||||
and the section as a whole is intended to apply in other circumstances.
|
||||
|
||||
It is not the purpose of this section to induce you to infringe any
|
||||
patents or other property right claims or to contest validity of any
|
||||
such claims; this section has the sole purpose of protecting the
|
||||
integrity of the free software distribution system which is
|
||||
implemented by public license practices. Many people have made
|
||||
generous contributions to the wide range of software distributed
|
||||
through that system in reliance on consistent application of that
|
||||
system; it is up to the author/donor to decide if he or she is willing
|
||||
to distribute software through any other system and a licensee cannot
|
||||
impose that choice.
|
||||
|
||||
This section is intended to make thoroughly clear what is believed to
|
||||
be a consequence of the rest of this License.
|
||||
|
||||
12. If the distribution and/or use of the Library is restricted in
|
||||
certain countries either by patents or by copyrighted interfaces, the
|
||||
original copyright holder who places the Library under this License may add
|
||||
an explicit geographical distribution limitation excluding those countries,
|
||||
so that distribution is permitted only in or among countries not thus
|
||||
excluded. In such case, this License incorporates the limitation as if
|
||||
written in the body of this License.
|
||||
|
||||
13. The Free Software Foundation may publish revised and/or new
|
||||
versions of the Lesser General Public License from time to time.
|
||||
Such new versions will be similar in spirit to the present version,
|
||||
but may differ in detail to address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the Library
|
||||
specifies a version number of this License which applies to it and
|
||||
"any later version", you have the option of following the terms and
|
||||
conditions either of that version or of any later version published by
|
||||
the Free Software Foundation. If the Library does not specify a
|
||||
license version number, you may choose any version ever published by
|
||||
the Free Software Foundation.
|
||||
|
||||
14. If you wish to incorporate parts of the Library into other free
|
||||
programs whose distribution conditions are incompatible with these,
|
||||
write to the author to ask for permission. For software which is
|
||||
copyrighted by the Free Software Foundation, write to the Free
|
||||
Software Foundation; we sometimes make exceptions for this. Our
|
||||
decision will be guided by the two goals of preserving the free status
|
||||
of all derivatives of our free software and of promoting the sharing
|
||||
and reuse of software generally.
|
||||
|
||||
NO WARRANTY
|
||||
|
||||
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
|
||||
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
|
||||
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
|
||||
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
|
||||
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
|
||||
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
|
||||
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
|
||||
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
|
||||
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
|
||||
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
|
||||
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
|
||||
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
|
||||
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
|
||||
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
|
||||
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
|
||||
DAMAGES.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
@@ -1,42 +0,0 @@
|
||||
plugins {
|
||||
id("groovy-gradle-plugin")
|
||||
alias(libs.plugins.licenser)
|
||||
}
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
gradlePluginPortal()
|
||||
maven { url = 'https://maven.minecraftforge.net/' }
|
||||
//mavenLocal()
|
||||
}
|
||||
|
||||
dependencies {
|
||||
compileOnly gradleApi()
|
||||
|
||||
// Manually import plugins so that we can apply them by id.
|
||||
implementation plugin('licenser')
|
||||
implementation plugin('gradleutils')
|
||||
implementation plugin('gitversion')
|
||||
implementation plugin('changelog')
|
||||
implementation plugin('forgedev')
|
||||
}
|
||||
|
||||
gradlePlugin {
|
||||
plugins {
|
||||
register('convention') {
|
||||
id = 'net.minecraftforge.forge.build.convention'
|
||||
implementationClass = 'net.minecraftforge.forge.build.ConventionPlugin'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final Provider<String> plugin(String alias) {
|
||||
return (Provider<String>)project.extensions.getByType(VersionCatalogsExtension)
|
||||
.named("libs")
|
||||
.findPlugin(alias).get()
|
||||
.map { it.pluginId + ":" + it.pluginId + ".gradle.plugin:" + it.version }
|
||||
}
|
||||
|
||||
license {
|
||||
header = file('../LICENSE-header.txt')
|
||||
}
|
||||
BIN
Binary file not shown.
@@ -1,7 +0,0 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-9.7.1-bin.zip
|
||||
networkTimeout=10000
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
Vendored
-251
@@ -1,251 +0,0 @@
|
||||
#!/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
|
||||
|
||||
CLASSPATH="\\\"\\\""
|
||||
|
||||
|
||||
# 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" )
|
||||
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||
|
||||
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" \
|
||||
-classpath "$CLASSPATH" \
|
||||
-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" "$@"
|
||||
Vendored
-94
@@ -1,94 +0,0 @@
|
||||
@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
|
||||
|
||||
set CLASSPATH=
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -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
|
||||
@@ -1,30 +0,0 @@
|
||||
pluginManagement {
|
||||
|
||||
repositories {
|
||||
gradlePluginPortal()
|
||||
maven { url = 'https://maven.minecraftforge.net/' }
|
||||
mavenLocal()
|
||||
}
|
||||
}
|
||||
|
||||
plugins {
|
||||
id 'org.gradle.toolchains.foojay-resolver-convention' version '1.0.0'
|
||||
}
|
||||
|
||||
//enableFeaturePreview 'TYPESAFE_PROJECT_ACCESSORS'
|
||||
|
||||
dependencyResolutionManagement.versionCatalogs {
|
||||
register('bootLibs') {
|
||||
description = 'Important version numbers that are externally declared for easy modification.'
|
||||
from(files('../minecraft.versions.toml'))
|
||||
}
|
||||
|
||||
create('libs') {
|
||||
description = 'Libraries used by Forge and its subprojects.'
|
||||
from(files("../gradle/libs.versions.toml"))
|
||||
}
|
||||
}
|
||||
|
||||
if (new File('forgedev/settings.gradle').exists())
|
||||
includeBuild '../forgedev'
|
||||
|
||||
-166
@@ -1,166 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.forge.build
|
||||
|
||||
import groovy.transform.CompileStatic
|
||||
import org.gradle.api.Action
|
||||
import org.gradle.api.Project
|
||||
import org.gradle.api.Task
|
||||
import org.gradle.api.artifacts.ExternalModuleDependencyBundle
|
||||
import org.gradle.api.artifacts.MinimalExternalModuleDependency
|
||||
import org.gradle.api.model.ObjectFactory
|
||||
import org.gradle.api.provider.Provider
|
||||
import org.gradle.api.provider.ProviderFactory
|
||||
import org.gradle.api.publish.maven.MavenPublication
|
||||
import org.gradle.api.tasks.TaskProvider
|
||||
import org.gradle.jvm.tasks.Jar
|
||||
|
||||
import javax.inject.Inject
|
||||
|
||||
@CompileStatic
|
||||
abstract class ConventionExtension implements Meta {
|
||||
private final Project project;
|
||||
private final Runs runs
|
||||
|
||||
protected abstract @Inject ObjectFactory getObjects()
|
||||
protected abstract @Inject ProviderFactory getProviders()
|
||||
|
||||
@Inject
|
||||
ConventionExtension(Project project) {
|
||||
this.project = project
|
||||
this.runs = objects.newInstance(Runs, this)
|
||||
}
|
||||
|
||||
@Override
|
||||
Project getProject() {
|
||||
this.project
|
||||
}
|
||||
|
||||
void manifest(String pkg) {
|
||||
this.project.tasks.named('jar', Jar).configure {
|
||||
this.gradleutils.manifestDefaults(it.manifest, pkg)
|
||||
}
|
||||
}
|
||||
void manifest(String pkg, Map<String, String> info) {
|
||||
manifest(pkg)
|
||||
this.project.tasks.named('jar', Jar).configure {
|
||||
it.manifest.getAttributes().with {
|
||||
for (var entry : info.entrySet())
|
||||
put(entry.key, entry.value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// region Maven publishing ==============================================================
|
||||
void publish() {
|
||||
publish(pub -> pub.from(project.components.getByName('java')))
|
||||
}
|
||||
void publish(Action<MavenPublication> config) {
|
||||
project.with {
|
||||
publishing.with {
|
||||
repositories.with {
|
||||
maven gradleutils.publishingForgeMaven
|
||||
}
|
||||
publications.register('mavenJava', MavenPublication) {
|
||||
changelog.publish(it)
|
||||
gradleutils.promote(it)
|
||||
|
||||
// The actual artifacts to be published should be configured, so run the config
|
||||
config.execute(it)
|
||||
|
||||
it.pom.with {
|
||||
description = project.description
|
||||
gradleutils.pom.addRemoteDetails(it)
|
||||
license.with {
|
||||
gradleutils.pom.licenses.LGPLv2_1
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// endregion
|
||||
|
||||
// region Runs ================================================================
|
||||
private TaskProvider<Task> genAllData = null
|
||||
TaskProvider<Task> getGenAllData() {
|
||||
if (genAllData == null)
|
||||
genAllData = this.project.tasks.register('genAllData')
|
||||
return genAllData
|
||||
}
|
||||
TaskProvider<Task> getGenAllData(Action<Task> config) {
|
||||
getGenAllData().configure(config)
|
||||
return getGenAllData()
|
||||
}
|
||||
|
||||
Runs getRuns() {
|
||||
return this.runs
|
||||
}
|
||||
Runs runs(Action<Runs> config) {
|
||||
config.execute(this.runs)
|
||||
return this.runs
|
||||
}
|
||||
Runs basicRuns() {
|
||||
return basicRuns({})
|
||||
}
|
||||
Runs basicRuns(Action<Runs> config) {
|
||||
this.runs.main(null, null)
|
||||
config.execute(this.runs)
|
||||
return getRuns()
|
||||
}
|
||||
Runs basicRuns(String mods, File output) {
|
||||
return basicRuns(mods, output, {})
|
||||
}
|
||||
Runs basicRuns(String mods, File output, Action<Runs> config) {
|
||||
this.runs.main(mods, output)
|
||||
config.execute(this.runs)
|
||||
return getRuns()
|
||||
}
|
||||
Runs testRuns(String mods, File output) {
|
||||
return testRuns(mods, output, {})
|
||||
}
|
||||
Runs testRuns(String mods, File output, Action<Runs> config) {
|
||||
this.runs.test(mods, output)
|
||||
config.execute(this.runs)
|
||||
return getRuns()
|
||||
}
|
||||
// endregion
|
||||
|
||||
// region Forge Version Json ===================================================
|
||||
private TaskProvider<WriteForgeVersionJson> writeForgeVersionJson = null
|
||||
TaskProvider<WriteForgeVersionJson> getForgeVersionJson() {
|
||||
if (writeForgeVersionJson == null) {
|
||||
writeForgeVersionJson = this.project.tasks.register('writeForgeVersionJson', WriteForgeVersionJson)
|
||||
final versions = this.versions
|
||||
writeForgeVersionJson.configure {
|
||||
it.forgeVersion.set(versions.forge)
|
||||
it.minecraftVersion.set(versions.minecraft)
|
||||
it.mcpVersion.set(versions.mcp)
|
||||
}
|
||||
}
|
||||
return writeForgeVersionJson
|
||||
}
|
||||
TaskProvider<WriteForgeVersionJson> forgeVersionJson(Action<WriteForgeVersionJson> config) {
|
||||
forgeVersionJson.configure(config)
|
||||
return forgeVersionJson
|
||||
}
|
||||
// endregion
|
||||
|
||||
// region Natives helper =========================================================
|
||||
// See gradle/gradle#35070 (https://github.com/gradle/gradle/issues/35070)
|
||||
// We are making the list of providers first BEFORE mapping them to a provider of the resolved objects so
|
||||
// that they can be finalized after configuration.
|
||||
List<MinimalExternalModuleDependency> nativeVariants(Provider<ExternalModuleDependencyBundle> bundle) {
|
||||
final natives = "natives-" + forgedev.os
|
||||
final deps = this.project.dependencies
|
||||
bundle.get().collect { dep ->
|
||||
(deps.variantOf(providers.provider { (MinimalExternalModuleDependency)dep }) {
|
||||
it.classifier(natives)
|
||||
}).get()
|
||||
}
|
||||
}
|
||||
// endregion
|
||||
}
|
||||
@@ -1,96 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.forge.build
|
||||
|
||||
import groovy.transform.CompileStatic
|
||||
import org.gradle.api.Plugin
|
||||
import org.gradle.api.Project
|
||||
import org.gradle.api.tasks.compile.JavaCompile
|
||||
import org.gradle.jvm.toolchain.JavaLanguageVersion
|
||||
|
||||
@CompileStatic
|
||||
class ConventionPlugin implements Plugin<Project>, Meta {
|
||||
Project project
|
||||
@Override
|
||||
Project getProject() {
|
||||
this.project
|
||||
}
|
||||
|
||||
@Override
|
||||
void apply(Project project) {
|
||||
this.project = project
|
||||
project.with {
|
||||
pluginManager.with {
|
||||
apply 'java-library'
|
||||
apply 'maven-publish'
|
||||
apply pluginId('licenser')
|
||||
apply pluginId('gradleutils')
|
||||
apply pluginId('gitversion')
|
||||
apply pluginId('changelog')
|
||||
apply pluginId('forgedev')
|
||||
}
|
||||
|
||||
final versions = extensions.create("versions", VersionsExtension, project)
|
||||
final convention = extensions.create('convention', ConventionExtension, project)
|
||||
|
||||
logger.lifecycle(name + " " + version)
|
||||
|
||||
gradleutils.with {
|
||||
vendor.set('Forge Development LLC')
|
||||
version.set(gitversion.version)
|
||||
}
|
||||
project.setGroup('net.minecraftforge')
|
||||
|
||||
java.with {
|
||||
toolchain.languageVersion.set(JavaLanguageVersion.of(versions.java))
|
||||
// This is needed for IDE runtime classpath to be correct/not have multiple of the same artifact
|
||||
consistentResolution {
|
||||
it.useCompileClasspathVersions()
|
||||
}
|
||||
// Forge needs to build its own sources jar due to patching, everything else should use the default
|
||||
if (project != rootProject)
|
||||
it.withSourcesJar()
|
||||
}
|
||||
|
||||
tasks.withType(JavaCompile).configureEach {
|
||||
it.options.with {
|
||||
encoding = 'UTF-8'
|
||||
compilerArgs << '-Xlint:-unchecked' // This is mainly for vanilla code, but just makes it quiet down outside the IDE
|
||||
}
|
||||
}
|
||||
|
||||
// NOTE: We are adding dependencies to projects instead of through settings, so we don't have to apply forgedev in settings.
|
||||
// Applying forgedev in settings will break IDE linting support, which makes it very hard to work with.
|
||||
// We can reconsider this if/when JetBrains gets their shit together.
|
||||
// - I doubt they will ever fix their shit 8/28/2006 - Lex
|
||||
repositories.with {
|
||||
// Libraries has to be before maven central because Mojang hosts a classifer that central doesn't (org.lwjgl:lwjgl-freetype:3.3.3:natives-macos-patch)
|
||||
maven { url = 'https://libraries.minecraft.net/' }
|
||||
mavenCentral()
|
||||
maven gradleutils.forgeMaven
|
||||
project.pluginManager.withPlugin('net.minecraftforge.forgedev') {
|
||||
maven forgedev.mavenizer
|
||||
}
|
||||
|
||||
mavenLocal()
|
||||
}
|
||||
|
||||
changelog.with {
|
||||
from versions.changelogBase
|
||||
}
|
||||
|
||||
license.with {
|
||||
header = rootProject.file('LICENSE-header.txt')
|
||||
exclude('.project_info.properties')
|
||||
}
|
||||
|
||||
// Common dependencies,
|
||||
project.dependencies.with {
|
||||
add('compileOnly', libs.findLibrary('jetbrains.annotations').get())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.forge.build
|
||||
|
||||
import groovy.transform.CompileStatic
|
||||
import net.minecraftforge.forgedev.ForgeDevExtension
|
||||
import net.minecraftforge.gitversion.gradle.GitVersionExtension
|
||||
import net.minecraftforge.gitversion.gradle.changelog.ChangelogExtension
|
||||
import net.minecraftforge.gradleutils.GradleUtilsExtensionForProject
|
||||
import net.minecraftforge.licenser.LicenseExtension
|
||||
import org.gradle.api.Project
|
||||
import org.gradle.api.artifacts.VersionCatalog
|
||||
import org.gradle.api.artifacts.VersionCatalogsExtension
|
||||
import org.gradle.api.plugins.ExtraPropertiesExtension
|
||||
import org.gradle.api.plugins.JavaPluginExtension
|
||||
import org.gradle.api.publish.PublishingExtension
|
||||
|
||||
@CompileStatic
|
||||
interface Meta {
|
||||
Project getProject();
|
||||
|
||||
default VersionCatalog getLibs() {
|
||||
project.extensions.getByType(VersionCatalogsExtension).named("libs")
|
||||
}
|
||||
|
||||
default ExtraPropertiesExtension getExt() {
|
||||
project.extensions.getByType(ExtraPropertiesExtension)
|
||||
}
|
||||
|
||||
default JavaPluginExtension getJava() {
|
||||
project.extensions.getByType(JavaPluginExtension)
|
||||
}
|
||||
|
||||
default GradleUtilsExtensionForProject getGradleutils() {
|
||||
project.extensions.getByType(GradleUtilsExtensionForProject)
|
||||
}
|
||||
|
||||
default GitVersionExtension getGitversion() {
|
||||
project.extensions.getByType(GitVersionExtension)
|
||||
}
|
||||
|
||||
default ForgeDevExtension getForgedev() {
|
||||
project.extensions.getByType(ForgeDevExtension)
|
||||
}
|
||||
|
||||
default ChangelogExtension getChangelog() {
|
||||
project.extensions.getByType(ChangelogExtension)
|
||||
}
|
||||
|
||||
default LicenseExtension getLicense() {
|
||||
project.extensions.getByType(LicenseExtension)
|
||||
}
|
||||
|
||||
default PublishingExtension getPublishing() {
|
||||
project.extensions.getByType(PublishingExtension)
|
||||
}
|
||||
|
||||
default VersionsExtension getVersions() {
|
||||
project.extensions.getByType(VersionsExtension)
|
||||
}
|
||||
|
||||
default ConventionExtension getConvention() {
|
||||
project.extensions.getByType(ConventionExtension)
|
||||
}
|
||||
|
||||
default String pluginId(String alias) {
|
||||
getLibs().findPlugin(alias).orElseThrow { new IllegalStateException("Could not find plugin " + alias) }.get().pluginId
|
||||
}
|
||||
}
|
||||
@@ -1,220 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.forge.build
|
||||
|
||||
import groovy.transform.CompileStatic
|
||||
import net.minecraftforge.licenser.LicenseExtension
|
||||
import net.minecraftforge.licenser.tasks.LicenseCheck
|
||||
import org.gradle.api.Action
|
||||
import org.gradle.api.Project
|
||||
import org.gradle.api.tasks.SourceSet
|
||||
import org.gradle.api.tasks.TaskProvider
|
||||
import org.gradle.api.tasks.WriteProperties
|
||||
import org.jspecify.annotations.Nullable
|
||||
|
||||
import javax.inject.Inject
|
||||
import javax.naming.spi.ObjectFactory
|
||||
|
||||
@CompileStatic
|
||||
class Runs implements Meta {
|
||||
private final ConventionExtension ext
|
||||
private boolean hasDependency = false
|
||||
|
||||
@Inject
|
||||
Runs(ConventionExtension ext) {
|
||||
this.ext = ext
|
||||
}
|
||||
|
||||
@Override
|
||||
Project getProject() {
|
||||
this.ext.project
|
||||
}
|
||||
|
||||
void main(@Nullable String mods, @Nullable File output) {
|
||||
final project = this.project
|
||||
final genAllData = this.ext.genAllData
|
||||
|
||||
project.with {
|
||||
final SourceSet sourceSet = getJava().getSourceSets().named("main").get()
|
||||
if (!hasDependency && project != project.rootProject) {
|
||||
dependencies.with {
|
||||
add('implementation', it.project(':')) // Root project is forge itself
|
||||
}
|
||||
hasDependency = true
|
||||
}
|
||||
if (output != null)
|
||||
sourceSet.resources.with { srcDir output }
|
||||
|
||||
forgedev.runs.with {
|
||||
final File existing = sourceSet.getResources().getSrcDirs()[0]
|
||||
|
||||
configureEach {
|
||||
it.with {
|
||||
cache.set(project.layout.projectDirectory.dir('runs/cache'))
|
||||
eclipsePrefix = project.name
|
||||
|
||||
// If we're not forge, we need to get the metadata from the forge project
|
||||
if (project != project.rootProject)
|
||||
metadata = project.files(getForgedev().consumeFile('metadata', project.rootProject))
|
||||
|
||||
var runName = it.name.toLowerCase(Locale.ENGLISH)
|
||||
|
||||
if (runName.contains('client') || runName.contains('data')) {
|
||||
options.with {
|
||||
// LWJGL needs native access, Mojang gets away with just saying 'ALL-UNNAMED' because it doesnt boot into module land
|
||||
// We need a system to translate that to module names
|
||||
//jvmArgs '--enable-native-access=ALL-UNNAMED', '--add-exports', 'java.base/jdk.internal.misc=ALL-UNNAMED'
|
||||
args '--assetsDir', '{assets_root}', '--assetIndex', '{asset_index}'
|
||||
systemProperty 'org.lwjgl.system.SharedLibraryExtractDirectory', 'lwjgl_dll'
|
||||
}
|
||||
}
|
||||
|
||||
if (runName.contains('data')) {
|
||||
options.with(sourceSet).with {
|
||||
systemProperties.put("forge.project.list", getProjectList().flatMap { it.destinationFile.map{ it.asFile.absolutePath } })
|
||||
if (mods != null) args('--mod', mods)
|
||||
if (output != null) args('--output', output)
|
||||
}
|
||||
}
|
||||
|
||||
options.with {
|
||||
getWorkingDir().set(project.layout.projectDirectory.dir("runs/$name"))
|
||||
getMainClass().set('net.minecraftforge.bootstrap.ForgeBootstrap')
|
||||
args '--gameDir', '.'
|
||||
jvmArgs '-Djava.net.preferIPv6Addresses=system', '-XX:+UseCompactObjectHeaders', '-XX:StackShadowPages=32'
|
||||
|
||||
//systemProperty 'forge.logging.marker.registries', 'ACCEPT'
|
||||
//systemProperty 'forge.logging.console.level', 'debug'
|
||||
systemProperty 'bsl.debug', 'true'
|
||||
systemProperty 'terminal.jline', 'true'
|
||||
systemProperty 'forge.enableGameTest', 'true'
|
||||
systemProperty 'eventbus.api.strictRuntimeChecks', 'true'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
maybeCreate('client').with {
|
||||
options.with {
|
||||
args '--launchTarget', 'forge_dev_client',
|
||||
'--username', 'Dev',
|
||||
'--version', project.name,
|
||||
'--accessToken', '0',
|
||||
'--userType', 'mojang',
|
||||
'--versionType', 'release'
|
||||
}
|
||||
}
|
||||
|
||||
maybeCreate('server').with {
|
||||
options.with {
|
||||
args '--launchTarget', 'forge_dev_server'
|
||||
}
|
||||
}
|
||||
|
||||
maybeCreate('gameTestServer').with {
|
||||
options.with {
|
||||
args '--launchTarget', 'forge_dev_server_gametest',
|
||||
'--uniqueWorld' // Unique world is used so that the world regenerates, as well as the world config isn't influenced by other runs
|
||||
}
|
||||
}
|
||||
|
||||
maybeCreate('data').with {
|
||||
options.with {
|
||||
args '--launchTarget', 'forge_dev_data',
|
||||
'--all',
|
||||
'--existing', existing
|
||||
}
|
||||
}
|
||||
|
||||
maybeCreate('clientData').with {
|
||||
options.with {
|
||||
args '--launchTarget', 'forge_dev_client_data',
|
||||
'--all',
|
||||
'--existing', existing
|
||||
}
|
||||
}
|
||||
}
|
||||
genAllData.configure {
|
||||
it.dependsOn forgedev.runs.getByName('data').with(sourceSet).run, forgedev.runs.getByName('clientData').with(sourceSet).run
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void test(@Nullable String mods, @Nullable File output) {
|
||||
final project = this.project
|
||||
final genAllData = this.ext.genAllData
|
||||
|
||||
project.with {
|
||||
final SourceSet sourceSet = getJava().getSourceSets().named("test").get()
|
||||
forgedev.runs.with {
|
||||
final File existing = sourceSet.getResources().getSrcDirs()[0]
|
||||
|
||||
configureEach {
|
||||
it.with {
|
||||
var runName = it.name.toLowerCase(Locale.ENGLISH)
|
||||
options.with(sourceSet).with {
|
||||
systemProperty 'forgedev.enableTestMods', 'true'
|
||||
}
|
||||
|
||||
if (runName.contains('data')) {
|
||||
options.with(sourceSet).with {
|
||||
if (mods != null) args('--mod', mods)
|
||||
if (output != null) args('--output', output)
|
||||
args('--existing', existing)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
genAllData.configure {
|
||||
it.dependsOn forgedev.runs.getByName('data').with(sourceSet).run, forgedev.runs.getByName('clientData').with(sourceSet).run
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private TaskProvider<WriteProperties> projectInfo = null
|
||||
TaskProvider<WriteProperties> getProjectInfo() {
|
||||
if (projectInfo == null) {
|
||||
projectInfo = this.project.tasks.register("writeProjectInfo", WriteProperties)
|
||||
projectInfo.configure {
|
||||
it.destinationFile.set(this.project.file('src/main/resources/.project_info.properties'))
|
||||
it.property('name', this.project.rootProject.name + this.project.isolated.path.replaceAll(':', '.'))
|
||||
it.property('output', 'src/main/generated')
|
||||
}
|
||||
this.project.tasks.named("generateResources").configure { it.dependsOn(projectInfo) }
|
||||
this.project.tasks.withType(LicenseCheck).configureEach {
|
||||
it.dependsOn(projectInfo)
|
||||
}
|
||||
}
|
||||
return projectInfo
|
||||
}
|
||||
TaskProvider<WriteProperties> projectInfo(Action<? extends WriteProperties> action) {
|
||||
getProjectInfo().configure(action)
|
||||
return getProjectInfo()
|
||||
}
|
||||
void setFlat(boolean value) {
|
||||
projectInfo(task -> task.property('flat', value))
|
||||
}
|
||||
|
||||
private TaskProvider<WriteProperties> projectList = null
|
||||
TaskProvider<WriteProperties> getProjectList() {
|
||||
if (projectList == null) {
|
||||
projectList = this.project.tasks.register("writeProjectList", WriteProperties)
|
||||
projectList.configure { task ->
|
||||
task.destinationFile.set(this.project.layout.buildDirectory.file('project_list.properties'))
|
||||
task.encoding = 'UTF-8'
|
||||
final root = this.project.rootProject.name
|
||||
this.project.rootProject.allprojects.forEach { p ->
|
||||
task.property(root + p.isolated.path.replaceAll(':', '.'), p.isolated.projectDirectory.asFile.absolutePath)
|
||||
}
|
||||
}
|
||||
}
|
||||
return projectList
|
||||
}
|
||||
TaskProvider<WriteProperties> projectList(Action<? extends WriteProperties> action) {
|
||||
getProjectList().configure(action)
|
||||
return getProjectList()
|
||||
}
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.forge.build;
|
||||
|
||||
import net.minecraftforge.gitversion.gradle.GitVersionExtension;
|
||||
import org.gradle.api.Project;
|
||||
import org.gradle.api.artifacts.VersionCatalog;
|
||||
import org.gradle.api.artifacts.VersionCatalogsExtension;
|
||||
|
||||
import javax.inject.Inject;
|
||||
|
||||
public abstract class VersionsExtension {
|
||||
private final VersionCatalog libs;
|
||||
|
||||
public final String java, minecraft, forge, forgeSpec, minecraftNext, mcp, changelogBase;
|
||||
|
||||
@Inject
|
||||
public VersionsExtension(Project project) {
|
||||
final var extensions = project.getExtensions();
|
||||
final var gitversion = extensions.getByType(GitVersionExtension.class);
|
||||
libs = extensions.getByType(VersionCatalogsExtension.class).named("bootLibs");
|
||||
java = get("java");
|
||||
minecraft = get("minecraft");
|
||||
minecraftNext = get("minecraft.next");
|
||||
mcp = get("mcp");
|
||||
changelogBase = get("changelog.base");
|
||||
forge = gitversion.of(project.getRootProject()).getVersion();
|
||||
forgeSpec = forge.split("\\.")[0];
|
||||
project.setVersion(minecraft + '-' + gitversion.getVersion());
|
||||
}
|
||||
|
||||
private String get(String name) {
|
||||
var ver = this.libs.findVersion(name);
|
||||
if (ver.isEmpty())
|
||||
throw new IllegalStateException("No version found for " + name);
|
||||
return ver.get().toString();
|
||||
}
|
||||
}
|
||||
-42
@@ -1,42 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.forge.build
|
||||
|
||||
import groovy.json.JsonBuilder
|
||||
import groovy.transform.CompileDynamic
|
||||
import groovy.transform.CompileStatic
|
||||
import org.gradle.api.DefaultTask
|
||||
import org.gradle.api.file.RegularFileProperty
|
||||
import org.gradle.api.provider.Property
|
||||
import org.gradle.api.tasks.Input
|
||||
import org.gradle.api.tasks.OutputFile
|
||||
import org.gradle.api.tasks.TaskAction
|
||||
|
||||
import javax.inject.Inject
|
||||
|
||||
@CompileStatic
|
||||
abstract class WriteForgeVersionJson extends DefaultTask {
|
||||
abstract @Input Property<String> getForgeVersion()
|
||||
abstract @Input Property<String> getMinecraftVersion()
|
||||
abstract @Input Property<String> getMcpVersion()
|
||||
|
||||
abstract @OutputFile RegularFileProperty getOutputFile()
|
||||
|
||||
@Inject
|
||||
WriteForgeVersionJson() {}
|
||||
|
||||
@TaskAction
|
||||
@CompileDynamic
|
||||
void exec() {
|
||||
var json = new JsonBuilder()
|
||||
json {
|
||||
forge this.forgeVersion.get()
|
||||
mc this.minecraftVersion.get()
|
||||
mcp this.mcpVersion.get()
|
||||
}
|
||||
this.outputFile.asFile.get().text = json.toPrettyString()
|
||||
}
|
||||
}
|
||||
-590
@@ -1,590 +0,0 @@
|
||||
import org.apache.tools.ant.filters.ReplaceTokens
|
||||
|
||||
plugins {
|
||||
id 'eclipse'
|
||||
alias libs.plugins.versions
|
||||
alias libs.plugins.jarsigner
|
||||
alias libs.plugins.forgedev
|
||||
id 'net.minecraftforge.forge.build.convention'
|
||||
}
|
||||
|
||||
gradleutils.displayName = 'Forge'
|
||||
description = 'Modifications to Minecraft to enable mod developers.'
|
||||
|
||||
jarSigner.autoDetect('forge')
|
||||
|
||||
// We have to tell ForgeDev to use the exact versions of tools we ship in the installer
|
||||
fdtools {
|
||||
configure('binpatcher') {
|
||||
version = buildLibs.binarypatcher.get().version
|
||||
}
|
||||
configure('installertools') {
|
||||
version = buildLibs.installertools.get().version
|
||||
}
|
||||
configure('jarcompatibilitychecker') {
|
||||
javaLauncher = javaToolchains.launcherFor(java.toolchain)
|
||||
}
|
||||
}
|
||||
|
||||
/* This is used for debugging, comparing all published artifacts against actual production
|
||||
forgedev.validatePublish {
|
||||
task {
|
||||
baseBranch = 'upstream/26.1.2'
|
||||
versionPrefix = versions.minecraft
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
||||
final minecraftFiles = forgedev.minecraftFiles(versions.minecraft)
|
||||
|
||||
final mcpBase = forgedev.mcpBase {
|
||||
mcpVersion = "${versions.minecraft}-${versions.mcp}"
|
||||
accessTransformers.from file('src/main/resources/META-INF/accesstransformer.cfg')
|
||||
sideAnnotationStrippers.from file('src/main/resources/forge.sas')
|
||||
}
|
||||
forgedev.provideFile('metadata', mcpBase.metadata)
|
||||
|
||||
forgedev.patches {
|
||||
base = mcpBase
|
||||
patches = file('patches/minecraft')
|
||||
patched = file('src/minecraft/java')
|
||||
sourceSets.main.java.srcDir patched
|
||||
}
|
||||
|
||||
tasks.register('setup') {
|
||||
dependsOn forgedev.patches.apply
|
||||
}
|
||||
|
||||
license {
|
||||
include 'net/minecraftforge/'
|
||||
exclude 'net/minecraftforge/common/LenientUnboundedMapCodec.java'
|
||||
}
|
||||
|
||||
changelog {
|
||||
publishAll = false
|
||||
}
|
||||
|
||||
// TODO [ForgeDev] Support compileOnlyApi, runtimeOnly, and a consumable annotation processor configuration
|
||||
configurations {
|
||||
// Don't pull all libraries, if we're missing something, add it to the installer list so the installer knows to download it.
|
||||
register('bootstrap') {
|
||||
transitive = false
|
||||
canBeDeclared = true
|
||||
canBeResolved = true
|
||||
}
|
||||
|
||||
register('installer') {
|
||||
transitive = false
|
||||
canBeDeclared = true
|
||||
canBeResolved = true
|
||||
extendsFrom(bootstrap)
|
||||
}
|
||||
|
||||
named('api') {
|
||||
extendsFrom(installer)
|
||||
// Inherit vanilla Minecraft's dependencies, and let downstream access them
|
||||
extendsFrom(mcpBase.dependencyConfiguration)
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
// These need to actually be on the classpath at the start. This is only used for the server shim jar.
|
||||
// And this is only needed because custom file systems are REQUIRED to be on the boot classloader.
|
||||
// This has ASM/BootStrap/Unsafe all because I haven't gotten around to moving UnionFileSystem out to its own project.
|
||||
bootstrap libs.jarjar.fs // JarInJar file system
|
||||
bootstrap libs.roimfs // JarInJar File System - FileSystems need to be on boot loader.
|
||||
bootstrap libs.bundles.jimfs // In memory file system used for ForgeDev launches
|
||||
bootstrap libs.securemodules // Has Union file system in it
|
||||
bootstrap libs.unsafe // Needed by securemodules
|
||||
bootstrap libs.bundles.asm // Needed by securemodules
|
||||
|
||||
implementation libs.jopt.simple
|
||||
|
||||
installer libs.bootstrap
|
||||
installer libs.bootstrap.api // Needed by securemodules
|
||||
installer libs.accesstransformers
|
||||
installer libs.eventbus
|
||||
installer libs.jspecify // Dep of EventBus
|
||||
installer libs.forgespi
|
||||
installer libs.coremods.api
|
||||
installer libs.modlauncher
|
||||
installer libs.mergetool.api
|
||||
installer libs.bundles.night.config
|
||||
installer libs.maven.artifact
|
||||
installer libs.bundles.terminalconsoleappender
|
||||
installer libs.mixin
|
||||
installer libs.mixinextras.forge
|
||||
installer libs.bundles.jarjar
|
||||
installer libs.roimfs
|
||||
|
||||
installer projects.fmlcore
|
||||
installer projects.fmlloader
|
||||
installer projects.fmlearlydisplay
|
||||
installer projects.javafmllanguage
|
||||
installer projects.lowcodelanguage
|
||||
installer projects.mclanguage
|
||||
installer projects.forgeTransformers
|
||||
|
||||
runtimeOnly files(mcpBase.extra)
|
||||
|
||||
runtimeOnly libs.bootstrap
|
||||
runtimeOnly libs.bootstrap.dev
|
||||
|
||||
annotationProcessor libs.eventbus.validator
|
||||
}
|
||||
|
||||
convention.basicRuns('forge', file('src/main/generated/'))
|
||||
|
||||
final EXTRA_TXTS = [
|
||||
file('LICENSE.txt'),
|
||||
changelog.task.flatMap(task -> task.outputFile)
|
||||
]
|
||||
|
||||
final serverShim = forgedev.shim {
|
||||
config {
|
||||
mainClass = 'net.minecraftforge.bootstrap.ForgeBootstrap'
|
||||
args = ['--launchTarget', 'forge_server']
|
||||
}
|
||||
classpath {
|
||||
libraries configurations.installer
|
||||
library tasks.named('universalJar', Jar)
|
||||
library forgedev.binaryPatches('server').apply, 'server'
|
||||
serverBundle.fileProvider(minecraftFiles.server)
|
||||
}
|
||||
bootstrapClasspath(configurations.bootstrap)
|
||||
jar {
|
||||
jarSigner.sign(it)
|
||||
}
|
||||
}
|
||||
|
||||
final finalizeSpawn = forgedev.methodCallFinder('findFinalizeSpawnTargets') {
|
||||
jar.fileProvider(mcpBase.classes)
|
||||
output = rootProject.file('forge-transformers/src/main/resources/coremods/finalize_spawn_targets.json')
|
||||
blacklist 'net/minecraft/world/level/BaseSpawner' // Ignore this class as we special case it.
|
||||
invokeVirtual('finalizeSpawn', '(Lnet/minecraft/world/level/ServerLevelAccessor;Lnet/minecraft/world/DifficultyInstance;Lnet/minecraft/world/entity/EntitySpawnReason;Lnet/minecraft/world/entity/SpawnGroupData;)Lnet/minecraft/world/entity/SpawnGroupData;')
|
||||
}
|
||||
|
||||
forgedev.validateDeprecations(tasks.named('jar', Jar)) {
|
||||
mcVersion = versions.minecraft
|
||||
}
|
||||
|
||||
forgedev.checks() {
|
||||
base = mcpBase
|
||||
ats {}
|
||||
sas {}
|
||||
execs {}
|
||||
|
||||
patches {
|
||||
dependsOn forgedev.patches.make
|
||||
patchDir = forgedev.patches.patches
|
||||
patchesWithS2SArtifact = [
|
||||
'minecraft/net/minecraft/client/renderer/ViewArea.java.patch',
|
||||
'minecraft/net/minecraft/data/models/blockstates/Variant.java.patch',
|
||||
]
|
||||
}
|
||||
|
||||
fix {
|
||||
dependsOn finalizeSpawn
|
||||
}
|
||||
|
||||
forgedev.patches.make.configure {
|
||||
finalizedBy forgedev.checks.patches.fix
|
||||
}
|
||||
}
|
||||
|
||||
final crowdin = forgedev.crowdin // Create the crowdin tasks
|
||||
tasks.named('jar', Jar) {
|
||||
from(EXTRA_TXTS)
|
||||
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
|
||||
exclude '.cache'
|
||||
|
||||
from(zipTree(crowdin.flatMap { it.output } )) {
|
||||
include 'assets/forge/lang/*.json'
|
||||
}
|
||||
|
||||
manifest {
|
||||
attributes([
|
||||
'Automatic-Module-Name': 'net.minecraftforge.forge'
|
||||
])
|
||||
gradleutils.manifestDefaults(it, 'net/minecraftforge/versions/forge/')
|
||||
gradleutils.manifestDefaults(it, 'net/minecraftforge/versions/mcp/', [
|
||||
'Specification-Title' : 'Minecraft',
|
||||
'Specification-Version' : versions.minecraft,
|
||||
'Implementation-Title' : 'MCP',
|
||||
'Implementation-Version': versions.mcp
|
||||
])
|
||||
}
|
||||
jarSigner.sign(it)
|
||||
}
|
||||
|
||||
final universalJar = tasks.register('universalJar', Jar) {
|
||||
from (zipTree(tasks.named('jar', Jar).flatMap { it.archiveFile } )) {
|
||||
exclude(forgedev.filterVanilla(mcpBase.classes))
|
||||
}
|
||||
manifest = tasks.named('jar', Jar).get().manifest
|
||||
archiveClassifier = 'universal'
|
||||
jarSigner.sign(it)
|
||||
}
|
||||
|
||||
final sourcesJarAll = tasks.register('sourcesJarAll', Jar) {
|
||||
archiveClassifier = 'sources-all'
|
||||
from(sourceSets.main.allJava.srcDirs)
|
||||
}
|
||||
|
||||
// Our sources, plus the patches we do to Vanilla Minecraft
|
||||
final sourcesJar = tasks.register('sourcesJar', Jar) {
|
||||
archiveClassifier = 'sources'
|
||||
from(sourceSets.main.allJava.srcDirs - forgedev.patches.patched.asFile.get())
|
||||
mustRunAfter(forgedev.patches.make)
|
||||
from(forgedev.patches.patches) {
|
||||
into 'patches/'
|
||||
}
|
||||
}
|
||||
|
||||
forgedev.userDev {
|
||||
base(mcpBase)
|
||||
|
||||
config {
|
||||
universal universalJar
|
||||
sources sourcesJar
|
||||
addLibraries(configurations.installer)
|
||||
// TODO [ForgeDev][UserDev] Split API/Runtime elements in userdev config
|
||||
// so we don't gotta keep making exceptions for MixinExtras
|
||||
addCompileDependency(libs.mixinextras.common)
|
||||
addAnnotationProcessorDependency(libs.mixinextras.common)
|
||||
|
||||
// TODO [ForgeDev] Consolidate Patcher + UserDev Config runs in a sane way
|
||||
runs {
|
||||
configureEach {
|
||||
parents = []
|
||||
main = 'net.minecraftforge.bootstrap.ForgeBootstrap'
|
||||
args '--gameDir', '.'
|
||||
jvmArgs '-Djava.net.preferIPv6Addresses=system', '-XX:+UseCompactObjectHeaders', '-XX:StackShadowPages=32'
|
||||
client = it.name.containsIgnoreCase('client')
|
||||
environment 'MCP_MAPPINGS', '{mcp_mappings}'
|
||||
}
|
||||
|
||||
register('clientData') {
|
||||
args '--launchTarget', "forge_userdev_client_data"
|
||||
args '--assetIndex', '{asset_index}'
|
||||
args '--assetsDir', '{assets_root}'
|
||||
}
|
||||
|
||||
register('client') {
|
||||
property 'forge.enableGameTest', 'true'
|
||||
args '--launchTarget', "forge_userdev_client"
|
||||
args '--version', 'MOD_DEV'
|
||||
args '--assetIndex', '{asset_index}'
|
||||
args '--assetsDir', '{assets_root}'
|
||||
}
|
||||
|
||||
register('server') {
|
||||
property 'forge.enableGameTest', 'true'
|
||||
args '--launchTarget', "forge_userdev_server"
|
||||
}
|
||||
|
||||
register('gameTestServer') {
|
||||
args '--launchTarget', "forge_userdev_server_gametest"
|
||||
}
|
||||
|
||||
register('data') {
|
||||
args '--launchTarget', "forge_userdev_data"
|
||||
args '--assetIndex', '{asset_index}'
|
||||
args '--assetsDir', '{assets_root}'
|
||||
}
|
||||
}
|
||||
}
|
||||
patches {
|
||||
modified.setFrom(sourcesJarAll.flatMap { it.archiveFile })
|
||||
}
|
||||
binaryPatches {
|
||||
mustRunAfter(forgedev.patches.make)
|
||||
patches.setFrom(forgedev.patches.patches)
|
||||
dirty.setFrom(tasks.named('jar', Jar).flatMap { it.archiveFile })
|
||||
}
|
||||
}
|
||||
|
||||
forgedev.userdevCompatibility(versions.minecraft) {
|
||||
clean = mcpBase.classes
|
||||
dirty = tasks.named('jar', Jar)
|
||||
}
|
||||
|
||||
// region Installer tasks, Not needed when we simplify the installer/remove obf
|
||||
final clientBinPatches = forgedev.binaryPatches('client') {
|
||||
clean = minecraftFiles.client
|
||||
// Workaround for 3rd party launcher issues, marker needed to locate MC, store needed to fix zlib-ng issues
|
||||
apply {
|
||||
store = true
|
||||
marker = '.forge_patched_minecraft'
|
||||
}
|
||||
}
|
||||
final serverBinPatches = forgedev.binaryPatches('server') {
|
||||
clean = minecraftFiles.serverExtracted
|
||||
apply { store = true }
|
||||
}
|
||||
// endregion
|
||||
|
||||
forgedev.installer {
|
||||
dev = !forgedev.ci
|
||||
offline = false
|
||||
baseVersion = buildLibs.installer.get().version.toString()
|
||||
|
||||
// Add extra libraries
|
||||
pack serverShim.jar // The Server executable jar IS needed to be packed, as the installer would need a spec bump in order to download it
|
||||
pack universalJar // I don't think this is strictly needed to be packed anymore, will need to double check later
|
||||
|
||||
launcherLibrary universalJar
|
||||
// We configure the launcher here to keep the order for easier diff, after publishing, move this to the LauncherJson configuration below
|
||||
launcherJson {
|
||||
// We create this during install, so it's not downloadable
|
||||
generated(clientBinPatches.apply, 'client')
|
||||
}
|
||||
|
||||
launcherLibraries configurations.installer
|
||||
|
||||
final launcherId = "${versions.minecraft}-${project.name}-${versions.forge}"
|
||||
final installertools = tool(buildLibs.installertools)
|
||||
final binarypatcher = tool(buildLibs.binarypatcher)
|
||||
|
||||
jar {
|
||||
from(EXTRA_TXTS)
|
||||
from(rootProject.file('/forge_installer_logo.png')) {
|
||||
rename { 'big_logo.png' }
|
||||
}
|
||||
from(clientBinPatches.create.flatMap { t -> t.output }) {
|
||||
rename { 'data/client.lzma' }
|
||||
}
|
||||
from(serverBinPatches.create.flatMap { t -> t.output }) {
|
||||
rename { 'data/server.lzma' }
|
||||
}
|
||||
|
||||
final argsFile = rootProject.file('server_files/args.txt')
|
||||
final tokens = [tokens: [
|
||||
SHIM_JAR_FILE: serverShim.jar.get().archiveFileName.get(),
|
||||
MAVEN_PATH: forgedev.mavenArtifact.directory
|
||||
]]
|
||||
from(argsFile) {
|
||||
filter(tokens, ReplaceTokens)
|
||||
into 'data'
|
||||
rename { 'unix_args.txt' }
|
||||
}
|
||||
from(argsFile) {
|
||||
filter(tokens, ReplaceTokens)
|
||||
into 'data'
|
||||
rename { 'win_args.txt' }
|
||||
}
|
||||
|
||||
from(rootProject.file('server_files')) {
|
||||
filter(tokens, ReplaceTokens)
|
||||
into 'data'
|
||||
exclude 'args.txt'
|
||||
}
|
||||
|
||||
jarSigner.sign(it)
|
||||
}
|
||||
json {
|
||||
icon = rootProject.file('icon.ico')
|
||||
executable serverShim.jar
|
||||
minecraft = versions.minecraft
|
||||
profileVersion = launcherId
|
||||
|
||||
final projectArtifact = "${project.group}:${project.name}:${project.version}"
|
||||
|
||||
data 'MC_UNPACKED', "[net.minecraft:client:${versions.minecraft}]", "[net.minecraft:server:${versions.minecraft}:unpacked]"
|
||||
data 'MC_UNPACKED_SHA', minecraftFiles.client, minecraftFiles.serverExtracted
|
||||
|
||||
data 'BINPATCH', '/data/client.lzma', '/data/server.lzma'
|
||||
data 'PATCHED', "[$projectArtifact:client]", "[$projectArtifact:server]"
|
||||
data 'PATCHED_SHA', clientBinPatches.apply.flatMap { it.output }, serverBinPatches.apply.flatMap { it.output }
|
||||
|
||||
steps = [
|
||||
extract(installertools) {
|
||||
side = 'server'
|
||||
archive '{INSTALLER}'
|
||||
extract 'data/README.txt', '{ROOT}/README.txt'
|
||||
extract 'data/run.sh', '{ROOT}/run.sh'
|
||||
executable '{ROOT}/run.sh'
|
||||
extract 'data/run.bat', '{ROOT}/run.bat'
|
||||
optional 'data/user_jvm_args.txt', '{ROOT}/user_jvm_args.txt'
|
||||
extract 'data/unix_args.txt', "{ROOT}/libraries/${forgedev.mavenArtifact.directory}/unix_args.txt"
|
||||
extract 'data/win_args.txt', "{ROOT}/libraries/${forgedev.mavenArtifact.directory}/win_args.txt"
|
||||
},
|
||||
extractBundle(installertools) {
|
||||
side = 'server'
|
||||
libraries()
|
||||
},
|
||||
extractBundle(installertools) {
|
||||
side = 'server'
|
||||
jar '{MINECRAFT_JAR}', '{MC_UNPACKED}'
|
||||
cache '{MC_UNPACKED}', '{MC_UNPACKED_SHA}'
|
||||
},
|
||||
step(binarypatcher) {
|
||||
side = 'server'
|
||||
args = [
|
||||
'--clean', '{MC_UNPACKED}',
|
||||
'--output', '{PATCHED}',
|
||||
'--apply', '{BINPATCH}',
|
||||
'--data', '--unpatched',
|
||||
'--store'
|
||||
]
|
||||
cache '{PATCHED}', '{PATCHED_SHA}'
|
||||
},
|
||||
step(binarypatcher) {
|
||||
side = 'client'
|
||||
args = [
|
||||
'--clean', '{MINECRAFT_JAR}',
|
||||
'--output', '{PATCHED}',
|
||||
'--apply', '{BINPATCH}',
|
||||
'--data', '--unpatched',
|
||||
'--store',
|
||||
'--marker', '.forge_patched_minecraft'
|
||||
]
|
||||
cache '{PATCHED}', '{PATCHED_SHA}'
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
launcherJson {
|
||||
// These are flags to preserve glitchy old behavior to make diffing easier, removing when migrating to production is recommended
|
||||
sortLibraries = false // Don't sort, makes things non-deterministic, but easier to diff old versions
|
||||
duplicateLibraries = true // Our 'bootstrap' layer go added twice
|
||||
librariesLast = false // Makes libraries be added before args
|
||||
|
||||
id = launcherId
|
||||
inheritsFrom = versions.minecraft
|
||||
mainClass = 'net.minecraftforge.bootstrap.ForgeBootstrap'
|
||||
gameArgs = [ '--launchTarget', 'forge_client' ]
|
||||
jvmArgs = [ '-Djava.net.preferIPv6Addresses=system', '-XX:+UseCompactObjectHeaders', '-XX:StackShadowPages=32' ]
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
tasks.named('javadoc', Javadoc) {
|
||||
description = 'Generates the combined javadocs for the FML projects and the main Forge project'
|
||||
var includedProjects = [ ':fmlcore', ':fmlloader', ':javafmllanguage', ':mclanguage', ':forge-transformers' ]
|
||||
source includedProjects.collect { project(it).sourceSets.main.allJava }
|
||||
classpath = classpath + files(includedProjects.collect { project(it).sourceSets.main.compileClasspath })
|
||||
|
||||
var docsDir = rootProject.file('src/docs/')
|
||||
inputs.dir(docsDir)
|
||||
.withPropertyName('docs resources directory')
|
||||
.withPathSensitivity(PathSensitivity.RELATIVE)
|
||||
.optional()
|
||||
|
||||
failOnError = false
|
||||
|
||||
// Exclude the Minecraft classes if not enabled
|
||||
if (!project.hasProperty('generateAllDocumentation')) {
|
||||
exclude 'net/minecraft/**'
|
||||
exclude 'com/mojang/**'
|
||||
}
|
||||
exclude 'mcp/**'
|
||||
|
||||
options {
|
||||
stylesheetFile = new File(docsDir, 'stylesheet.css')
|
||||
|
||||
tags = [
|
||||
'apiNote:a:<em>API Note:</em>',
|
||||
'implSpec:a:<em>Implementation Requirements:</em>',
|
||||
'implNote:a:<em>Implementation Note:</em>'
|
||||
]
|
||||
|
||||
groups = [
|
||||
'Forge Mod Loader': [
|
||||
'net.minecraftforge.fml.common.asm*',
|
||||
'net.minecraftforge.fml.loading*',
|
||||
'net.minecraftforge.fml.server*'
|
||||
],
|
||||
'FML Core': [
|
||||
'net.minecraftforge.fml',
|
||||
'net.minecraftforge.fml.config*',
|
||||
'net.minecraftforge.fml.event*',
|
||||
'net.minecraftforge.fml.util*'
|
||||
],
|
||||
'FML Common': [
|
||||
'net.minecraftforge.fml.core',
|
||||
'net.minecraftforge.fml.event.config',
|
||||
'net.minecraftforge.fml.event.lifecycle'
|
||||
],
|
||||
'FML Java/MC Language Providers': [
|
||||
'net.minecraftforge.fml.common',
|
||||
'net.minecraftforge.fml.javafmlmod',
|
||||
'net.minecraftforge.fml.mclanguageprovider'
|
||||
],
|
||||
'Minecraft Forge API': [
|
||||
'net.minecraftforge*'
|
||||
]
|
||||
]
|
||||
|
||||
author = false
|
||||
noSince = true
|
||||
noHelp = true
|
||||
|
||||
bottom = "Minecraft Forge is an open source modding API for Minecraft: Java Edition, licensed under the Lesser GNU General Public License, version 2.1."
|
||||
windowTitle = "Minecraft Forge API ${version}"
|
||||
docTitle = "Minecraft Forge API - ${versions.forge} for Minecraft ${versions.minecraft}"
|
||||
header = "<div style=\"margin-top: 9px;padding: 5px 6px;\"><strong>${versions.forge} for Minecraft ${versions.minecraft}</strong></div>"
|
||||
}
|
||||
|
||||
doLast {
|
||||
project.copy {
|
||||
from docsDir
|
||||
exclude '/stylesheet.css'
|
||||
into destinationDir
|
||||
}
|
||||
}
|
||||
}
|
||||
*/
|
||||
final mdkZip = forgedev.consumeFile("mdkZip", project(':forge-mdk'))
|
||||
convention.publish {
|
||||
artifact universalJar
|
||||
artifact forgedev.installer.jar
|
||||
artifact(mdkZip.map { it.singleFile }) {
|
||||
builtBy mdkZip
|
||||
classifier = "mdk"
|
||||
extension = "zip"
|
||||
}
|
||||
artifact forgedev.userDev.jar
|
||||
artifact sourcesJar
|
||||
artifact serverShim.jar
|
||||
}
|
||||
|
||||
/*
|
||||
// These are debugging tasks that are only used when developing ForgeDevPlugin, to bulk test task's config/caching
|
||||
// region ForgeDev Tests
|
||||
def all = tasks.register('all') {}
|
||||
afterEvaluate {
|
||||
if (gradle.startParameter.taskNames.contains('all')) {
|
||||
tasks.forEach { task -> // This forces everything to be realized, which is why we have the startParameter check
|
||||
if (!gradle.startParameter.isTaskGraph() && task.name.startsWith('run')) return
|
||||
if (task.name in [all.name, 'dependencyInsight', 'dependencies', 'dependencyUpdates', 'init', 'buildEnvironment', 'idea',
|
||||
'eclipse', 'javaToolchains', 'outgoingVariants', 'projects', 'properties', 'resolvableConfigurations', 'tasks', 'updateDaemonJvm',
|
||||
'generateActionsWorkflow'
|
||||
]) return
|
||||
if (task.name.startsWith('clean')) return
|
||||
if (task.name == 'checkJarCompatibility') return // This doesn't work in FG6 dev, I think it's cuz we check vs srg names. Will need to look at later
|
||||
all.configure { dependsOn(task) }
|
||||
}
|
||||
}
|
||||
}
|
||||
*/
|
||||
// endregion
|
||||
// We dont have any unit tests, so disable this error
|
||||
tasks.withType(AbstractTestTask).configureEach {
|
||||
failOnNoDiscoveredTests = false
|
||||
}
|
||||
// This shouldn't be needed according to the Gradle devs, as we never run these commands together.
|
||||
// But in another case of Gradle being gradle, here we are
|
||||
[ 'makePatches', 'compileJava', 'checkLicenseMain', 'updateLicenseMain', 'sourcesJar', 'sourcesJarAll' ]
|
||||
.each{ tasks.named(it).configure{ mustRunAfter forgedev.patches.apply }}
|
||||
forgedev.runs.configureEach {
|
||||
run.configure { dependsOn finalizeSpawn }
|
||||
}
|
||||
// run gradlew dependencyUpdates --no-parallel
|
||||
//noinspection UnnecessaryQualifiedReference
|
||||
tasks.named('dependencyUpdates', com.github.benmanes.gradle.versions.updates.DependencyUpdatesTask) {
|
||||
resolutionStrategy {
|
||||
mcpBase.dependencies.get().forEach {dep -> force(dep) } // Force all vanilla dependencies to their correct versions
|
||||
force(earlyDisplayLibs.slf4j.jdk14) // Force slf4j implementation, its tied to the api from the manifest
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
Contributing to Forge
|
||||
=====================
|
||||
|
||||
1) Keep patches to Minecraft classes together. If you need a lot of things done, you may either add to relevant forge classes or make a new class. Try not to spread out your patches across multiple disjoint lines, as this makes maintenance of your patches difficult.
|
||||
|
||||
2) TODO: Test Mods
|
||||
|
||||
3) Follow the code style of the class you're working in (braces on newlines & spaces instead of tabs in Forge classes, inline brackets in patches, etc).
|
||||
|
||||
For more information, refer to [the wiki][Wiki].
|
||||
|
||||
|
||||
Contributor License Agreement
|
||||
=============================
|
||||
- You grant Forge a license to use your code contributed to the primary codebase (everything **not** under patches) in Forge, under the LGPLv2.1 license.
|
||||
- You assign copyright ownership of your contributions to the patches codebase (everything under patches) to Forge, where it will be licensed under the LGPLv2.1 license.
|
||||
|
||||
"Forge" is Forge Development LLC, a legally incorporated entity in Oregon, USA.
|
||||
|
||||
[Wiki]: https://github.com/MinecraftForge/MinecraftForge/wiki/If-you-want-to-contribute-to-Forge
|
||||
-103
@@ -1,103 +0,0 @@
|
||||

|
||||
|
||||
MinecraftForge
|
||||
=============
|
||||
[][Download]
|
||||
[][Download] [][Discord] [][Patreon]
|
||||
|
||||
Forge is a free, open-source modding API all of your favourite mods use!
|
||||
|
||||
| Version | Support |
|
||||
|--------------|-----------------------------|
|
||||
| All versions | [Supported][Support-Policy] |
|
||||
|
||||
* [Download]
|
||||
* [Forum]
|
||||
* [Discord]
|
||||
* [Documentation]
|
||||
|
||||
# Installing Forge
|
||||
|
||||
Go to [the Forge website][Download]
|
||||
and select the Minecraft version you wish to get Forge for from the list.
|
||||
|
||||
You can download the installer for the *Recommended Build* or the
|
||||
*Latest build* there. Latest builds may have newer features but may be
|
||||
more unstable as a result. The installer will attempt to install Forge
|
||||
into your vanilla launcher environment, where you can then create a new
|
||||
profile using that version and play the game!
|
||||
|
||||
For support and questions, visit [the Support Forum][Support-Forum] or [the Forge Discord server][Discord].
|
||||
|
||||
## Required Java Versions
|
||||
|
||||
We require the version of Java that Minecraft requires, which is currently:
|
||||
|
||||
| Minecraft | Java |
|
||||
|------------------|-------------------|
|
||||
| 26.1+ | [25][Adoptium-25] |
|
||||
| 1.20.6 - 1.21.11 | [21][Adoptium-21] |
|
||||
| 1.18 - 1.20.4 | [17][Adoptium-17] |
|
||||
| 1.17.1 | [16][Adoptium-16] |
|
||||
| 1.16.5- | [8][Adoptium-8] |
|
||||
|
||||
**If you are on Windows and have difficulty using Java to launch JAR files, consider using [Jarfix by Johann Löfflmann][Jarfix].**
|
||||
|
||||
# Creating Mods
|
||||
|
||||
[See the "Getting Started" section in the Forge Documentation][Getting-Started].
|
||||
|
||||
# Contribute to Forge
|
||||
|
||||
If you wish to actually inspect Forge, submit PRs or otherwise work
|
||||
with Forge itself, you're in the right place!
|
||||
|
||||
[See the guide to setting up a Forge workspace][ForgeDev].
|
||||
|
||||
### Pull requests
|
||||
|
||||
[See the "Making Changes and Pull Requests" section in the Forge documentation][Pull-Requests].
|
||||
|
||||
Please read the contributing guidelines found [here][Contributing] before making a pull request.
|
||||
|
||||
### Contributor License Agreement
|
||||
We require all contributors to acknowledge the [Forge Contributor License Agreement][CLA].
|
||||
Please ensure you have a valid email address associated with your GitHub account to do this. If you have previously
|
||||
signed it, you should be OK.
|
||||
|
||||
#### Donate
|
||||
*Forge is a large project with many collaborators working on it around the clock. Forge is and will always remain free
|
||||
to use and modify. However, it costs money to run such a large project as this, so please consider
|
||||
[becoming a patron][Patreon].*
|
||||
|
||||
### Thanks
|
||||
[](https://www.yourkit.com/)
|
||||
|
||||
YourKit for providing us accesss to their [YourKit Java Profiler] which helps identify bottlenecks and places for improvement.
|
||||
|
||||
[Contributing]: ./CONTRIBUTING.md
|
||||
[CLA]: https://cla-assistant.io/MinecraftForge/MinecraftForge
|
||||
|
||||
[Download]: https://files.minecraftforge.net/
|
||||
|
||||
[Adoptium-25]: https://adoptium.net/temurin/releases/?version=25
|
||||
[Adoptium-21]: https://adoptium.net/temurin/releases/?version=21
|
||||
[Adoptium-17]: https://adoptium.net/temurin/releases/?version=17
|
||||
[Adoptium-16]: https://adoptium.net/temurin/releases/?version=16
|
||||
[Adoptium-8]: https://adoptium.net/temurin/releases/?version=8
|
||||
[Jarfix]: https://johann.loefflmann.net/en/software/jarfix/index.html
|
||||
|
||||
[Forum]: https://forums.minecraftforge.net/
|
||||
[Support-Forum]: https://forums.minecraftforge.net/forum/18-support-bug-reports/
|
||||
[Support-Policy]: https://forums.minecraftforge.net/topic/144690-new-tiered-support-policy
|
||||
|
||||
[Discord]: https://discord.minecraftforge.net/
|
||||
|
||||
[Documentation]: https://docs.minecraftforge.net/
|
||||
[Getting-Started]: https://docs.minecraftforge.net/en/latest/gettingstarted/
|
||||
[ForgeDev]: https://docs.minecraftforge.net/en/latest/forgedev/
|
||||
[Pull-Requests]: https://docs.minecraftforge.net/en/latest/forgedev/#making-changes-and-pull-requests
|
||||
|
||||
[Patreon]: https://www.patreon.com/LexManos
|
||||
[YourKit Java Profiler]: https://www.yourkit.com/java/profiler/
|
||||
-154
@@ -1,154 +0,0 @@
|
||||
Getting Support Surrounding Forge
|
||||
=================================
|
||||
|
||||
**If you do not want to read the following wall of text, no matter its relevance for helping get your issue resolved quickly, please refer to the [Forge Forums][Bug-Reports] for support.**
|
||||
|
||||
Before reporting an issue on this repository's bug tracker, please carefully read this document. There are various resources that are more likely to be able to help you with certain kinds of issues. This document provides instructions on how to determine which place best to report to.
|
||||
|
||||
*Note: While this guide generally is more geared towards end-user problems, modders should also read it before reporting any issue with Forge in order to ensure it actually is one. This does of course not cover feature suggestions.*
|
||||
|
||||
### Contents
|
||||
|
||||
1. [Identifying the Source of a Problem](#identifying-the-source-of-a-problem)
|
||||
1. [Analyzing a Stacktrace](#analyzing-a-stacktrace)
|
||||
2. [Isolating an Issue](#isolating-an-issue)
|
||||
2. [Choosing the Correct Support Channel](#choosing-the-correct-support-channel)
|
||||
1. [Forge Support](#forge-support)
|
||||
2. [Mod Support](#mod-support)
|
||||
3. [Vanilla Support](#vanilla-support)
|
||||
3. [Writing a Helpful Bug Report](#writing-a-helpful-bug-report)
|
||||
1. [Preventing Duplicates and Unnecessary Reports](#preventing-duplicates-and-unnecessary-reports)
|
||||
2. [Required Information](#required-information)
|
||||
3. [Markdown Issue Template](#markdown-issue-template)
|
||||
4. [Waiting for an Issue to Be Resolved](#waiting-for-an-issue-to-be-resolved)
|
||||
|
||||
Identifying the Source of a Problem
|
||||
-----------------------------------
|
||||
|
||||
You're most likely to get fast and valuable responses to your issues if you report them in the correct place. For this, you need to find the root cause of the problem.
|
||||
|
||||
The most important source for this information are the log files Forge creates for every run of the game. You can find them in the `logs` subdirectory of your Minecraft game directory. The most important log file is `latest.log` which contains all of Forge's and any mod's output for `info` of above. `debug.log` contains all the logs in `latest.log` plus the `debug` logs for more detailed debugging.
|
||||
|
||||
If you're faced by a crash, consult these logs files first. Near the end of the log should be a section labelled 'Minecraft Crash Report', and after it, one about `a detailed walkthrough of the error, ...`. In these sections, you'll see a bunch of lines that look like
|
||||
|
||||
```
|
||||
at some.words.related.to.a.mod.MoreWords(MoreWords.java:number)
|
||||
```
|
||||
|
||||
These lines are the most important part of a crash log, called the stacktrace, because they pinpoint the place in the code where something went irrecoverably wrong. Mod authors usually name their code so that these lines describe what the game was doing when it crashed. The further down one of these lines is, the earlier that piece of code ran, so at the bottom you'll see the place where Minecraft started, and at the top is where it stopped. You should use this information to figure out who to report the bug to.
|
||||
|
||||
### Analyzing a Stacktrace
|
||||
|
||||
You can generally tell pretty quickly what caused the error at the head of your stacktrace, simply follow these rules:
|
||||
|
||||
1. If you can find the name of a mod in the trace, that mod most likely is the culprit.
|
||||
- Be aware that you may find multiple mods as participants of a crash. In that case, you can either report to both or try to reason (using the names in the stacktrace) about which mod is at fault.
|
||||
2. If you can only find Forge (usually starting with `net.minecraftforge`) alongside Vanilla (usually starting with `net.minecraft`) references, chances are that you have found a bug in Forge. In this case, use one of the various [support channels](#forge-support) listed below.
|
||||
- The occurrence of a single call to Forge somewhere in the stacktrace *does not* warrant a report to Forge if there are mods present in the crash report.
|
||||
3. If there's no mention of Forge or a mod, but any Vanilla class, you might have found a Vanilla bug. You should probably still report it via the Forge channels first, however, due the nature of modded environments and the rarity of Vanilla crash bugs.
|
||||
4. Always check whether there's a mention of coremods at the beginning of a crash report. If there is and you can't find any clear culprit, consider reporting to these coremods first, since they are free to change any of the code executed in your environment.
|
||||
|
||||
The rules are numbered in decreasing priority, which means that you should always prefer finding a mod in a crash report over directly jumping to conclusions about Forge or even Vanilla.
|
||||
|
||||
### Isolating an Issue
|
||||
|
||||
A significant step of reporting an issue, after having found the involved parties, is reliably reproducing it to identify potential incompatibilities or weird interactions between mods. If you're unable to pinpoint a bug to a set of mods and just randomly report it to any mod, chances are it won't get much attention and hence not a fix.
|
||||
|
||||
Reliable methods of isolating the issue are listed below:
|
||||
|
||||
- **Retrace your last steps before the crash/bug occurred.** It might sound too simple, but a big part of reliably reproducing an issue is determining the steps required to trigger it. If you can't exactly remember what you last did, looking at the stacktrace again can also help you a bit, since there are often descriptive names in there which reflect an action you could take, such as using an item or placing a block.
|
||||
- **Reduce the number of mod interactions.** You can achieve this in multiple ways. One of them is simply disabling any compatibility layers between involved mods via configuration files. The other one, which takes a little more effort, is actually removing mods from your instance. But don't be afraid, you won't have to remove mods one-by-one if you follow these steps (known as a binary search):
|
||||
1. Move half the mods out of your instance (obviously keep those definitely participating in the issue).
|
||||
2. If the issue persists after another try of reproducing it, repeat from step 1 one by halving the mod list again.
|
||||
3. If the issue does not occur anymore without the other half, repeat from step 1 but instead discard the half you just used and split the other one (plus any definitely required mods).
|
||||
4. Repeat these steps until you can't remove any more mods from your instance without also 'solving' the issue. This set of mods can serve as a basis for your issue report.
|
||||
|
||||
Choosing the Correct Support Channel
|
||||
-------------------------------------
|
||||
|
||||
The place you need to report issues to varies depending on the source of the problem. Below you can find a list of support channels you can usually consult for each of the sources listed in the previous section.
|
||||
|
||||
Please note that this list has to be considered incomplete as there is a large number of sub-communities within the Minecraft modding world. You should always prefer channels you know and have access to over any of those listed below which would require extra effort on your part.
|
||||
|
||||
### Forge Support
|
||||
|
||||
If you're certain you've found an issue that is directly caused by Forge, you have the following three platforms available for dealing with it, with decreasing relevance for end-users:
|
||||
|
||||
1. **Forge Forums:** There's a dedicated [Support & Bug Report][Bug-Reports] section on the Forge forums, which is led by team of moderators and volunteers who will try to deal with your reports as quickly as possible. *As a player you should probably report here first.*
|
||||
- For modders, there also is a separate [Modder Support][Modder-Support] section where you can ask all your development-related questions. *You should prefer this section for coding help.*
|
||||
2. **Forge Discord Server:** You can find a lot of help on the official [Discord Server][Discord], especially smaller issues that you quickly need help with. *Be aware that the channel is more suited towards development questions, so while you may get support there as a player, you should almost always prefer the forums.*
|
||||
3. **Forge Issue Tracker:** If you're absolutely certain that you've found an issue in the Forge codebase (e.g. you're a modder yourself and have analyzed the stacktrace and relevant code), don't refrain from reporting it on this repository's [issue tracker](https://github.com/MinecraftForge/MinecraftForge/issues). *Please do not use the issues as a means of getting coding help. For developers, the IRC and the [official documentation][Documentation] are the best sources of information.*
|
||||
|
||||
### Mod Support
|
||||
|
||||
A lot of mods also use GitHub or other source management systems and their integrated issue trackers. The following options will give you the best chances of reporting your issue in the right place:
|
||||
|
||||
- **CurseForge:** Many mods are hosted on the [CurseForge platform](https://minecraft.curseforge.com) nowadays. Chances are you already downloaded them from there or as a part of a modpack hosted there. Projects may specify an issue reporting link on their own page, so simply look for it on the mod's project page and you should be directed to the preferred means of error reporting.
|
||||
- **Modrinth:** Some modders use [Modrinth](https://modrinth.com/mods) to host their mods, but be mindful that not all mods on this platform are for the Forge modloader.
|
||||
- **Searching for a repository directly:** You may need to try and find a repository directly on source control sites. The most common ones are [GitHub](https://github.com), [GitLab](https://gitlab.com), and [BitBucket](https://bitbucket.org). Both come with search capabilities, so simply try to search for the mod's name.
|
||||
|
||||
### Vanilla Support
|
||||
|
||||
Just like Forge or mods, Mojang has its own issue tracker for Vanilla Minecraft. This official [bug tracker](https://bugs.mojang.com/projects/MC/issues/) has the exclusive purpose of managing any concrete issues with the game's code and functionality. It is *not* a place for requesting any features or getting help with playing the game, similar to the Forge issue tracker.
|
||||
|
||||
Writing a Helpful Bug Report
|
||||
----------------------------
|
||||
|
||||
Now that you've identified the source of your issue and decided on the correct support channel, it's time to actually write your report. Before you actually try to blindly create it, however, you should first check if the problem was noticed or even fixed already.
|
||||
|
||||
### Preventing Duplicates and Unnecessary Reports
|
||||
Use the target issue tracker's search functionality to look for issues which have descriptions similar to yours, but make sure to also search for already closed issues. If you can find one, verify it is in fact the same (or a very similar issue) and simply comment on it if you have anything else to contribute to the discussion, such as other steps to reproduce it. *Do not create duplicates of an existing issue, since it only puts extra effort on maintainers to recognize and close/mark them.*
|
||||
|
||||
Additionally, always check the *latest* changelogs of Forge and participating mods to find out if the bug was already noticed and fixed by the developer. Often the maintainer may only support newer versions of the game, so also check the changelogs for versions of Minecraft you don't actually actively play. If the issue was addressed already, *do not report it*, even if the fix only exists for a newer version of the game, since the developer probably had a good reason to do so. If your issue only exists with versions of a mod that are for very old versions of the game, also refrain from reporting them, considering most modders only support the two latest versions of Minecraft, if at all.
|
||||
|
||||
### Required Information
|
||||
If you're certain that your issue went unnoticed up until now, you can get to actually writing up the report. Below you can find a list of the *required* information any bug report should contain:
|
||||
|
||||
- **Minecraft Version:** Although many developers can deduce the Minecraft version in use from the mod's version, it is still an important piece of information to include, since it helps maintainers more easily decide whether to look into your issue at all or whether to close it right away due to being for an outdated version.
|
||||
- **Forge Version:** The Forge API is in constant flux and while breaking changes are limited to major Minecraft updates, new bugs or regressions might creep in during active development or newer versions than a mod was built with might change semantics slightly that manifest themselves for this mod.
|
||||
- **Mod Version:** Just like the Forge and Minecraft version, this is crucial for quickly telling where an issue might come from. *If you're reporting an issue caused by Forge that only occurs with a certain mod installed, include this mod here. No mod version is required if it's a pure Forge bug.*
|
||||
- **Complete List of Mods:** In order to reliably analyze a bug, developers need the exact same context as you do when trying to find its cause. Hence, you should always include a *full list of mods with their corresponding version* in your report. Note that you should probably only include the ones you found by [isolating the issue](#isolating-an-issue).
|
||||
- **Steps to Reproduce:** You should always include a list of steps required to provoke an issue to occur. Without it, developers can only take rough guesses at what might cause the bug. Try to reduce the amount of steps to a bare minimum, to make reproducing the issue easier. If you require a sophisticated setup to get even close to the issue, you might want to consider including your save file in your report.
|
||||
- **Full Log:** This is probably the most important part of your bug report. You *always* have to include the full log (`debug.log` from earlier), since it is the only way of telling what has caused an issue in code. *Do not* paste the full log as plain text in your report, but use [GitHub Gist](https://gist.github.com) instead and link to that from your report.
|
||||
|
||||
### Markdown Issue Template
|
||||
GitHub and BitBucket allow you to use the Markdown format for writing your issues. Below you can find a simple template that you can copy and fill in with your data. `{variables}` are written in braces and are supposed to be replaced by you with the information the variable name indicates. Everything behind two slashes (`//`) has to be interpreted as a comment and should be removed. If you want to include any link, you have to write in the `[title](url)` form. For further information on Markdown, see [this cheatsheet](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet).
|
||||
|
||||
```markdown
|
||||
**Minecraft Version:** {mc version}
|
||||
|
||||
**Forge Version:** {forge version}
|
||||
|
||||
**Mod Version:** {mod version} // Remove this line if you're reporting to Forge and no specific mod is involved
|
||||
|
||||
[**Full Log**]({link to gist/pastebin with full log})
|
||||
|
||||
**Mods in This Instance:**
|
||||
| Name | Version |
|
||||
| ------------------------ | ----------- |
|
||||
| [{mod 1}]({download 1}) | {version 1} | // The download links are entirely optional
|
||||
| {mod 2} | {version 2} |
|
||||
| {mod 3} | {version 3} |
|
||||
| ... | ... |
|
||||
|
||||
**Steps to Reproduce:**
|
||||
1. Do this
|
||||
2. Then do that
|
||||
3. ...
|
||||
```
|
||||
|
||||
*Note: The mod list here is formatted as table for easy reading (when displayed) and to look nice in text. Markdown does not care about any alignment of the spaces, so you can simply write individual rows of the table as* `| {mod name} | {version} |` *without having to care about the spacing.*
|
||||
|
||||
### Waiting for an Issue to Be Resolved
|
||||
After you have written your bug report, it is time to *wait*. Please be *patient* after submitting your issue, since it probably isn't the only one. If there's no response after 5 minutes or even a day of writing it, *do not* try to bump the issue by commenting on it, people *will* read it in due time. The only excuse for bumping a report is if it is a *critical* bug that prevents you from playing the game.
|
||||
|
||||
Every project has a different way of dealing with issues, so don't wonder if there's no comment on it, but somebody "labels" it with certain markers. This helps developers to more easily keep track of bugs and priorities. When any further input from you is required, you will be asked specifically. Do not bug anyone through other channels about resolving your issue.
|
||||
|
||||
Once your issue is closed, you will know whether it was valid or turned out to be unreproducible. If you included all of the data from above in your report, chances are that the latter won't be the case.
|
||||
|
||||
[Bug-Reports]: https://forums.minecraftforge.net/forum/18-support-bug-reports/
|
||||
[Modder-Support]: https://forums.minecraftforge.net/forum/70-modder-support/
|
||||
|
||||
[Discord]: https://discord.minecraftforge.net/
|
||||
|
||||
[Documentation]: https://docs.minecraftforge.net/
|
||||
@@ -1,7 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" viewBox="164.072 372.466 294.41 46.56">
|
||||
<g fill="#DFA86A">
|
||||
<path d="M266.16 417.99h10.96v-16.94h17.97v-10.27h-17.97v-7.01h19.06V373.5h-30.02zM337.33 378.7c-2.103-2.057-4.629-3.64-7.51-4.704-2.743-1.015-5.786-1.528-9.041-1.528l-.356.002c-3.362 0-6.503.556-9.338 1.651-2.857 1.106-5.357 2.707-7.434 4.761-2.073 2.052-3.714 4.559-4.877 7.45-1.158 2.876-1.748 6.104-1.748 9.59 0 3.417.59 6.582 1.753 9.403 1.163 2.829 2.807 5.297 4.88 7.329 2.073 2.03 4.572 3.621 7.425 4.724 2.834 1.096 5.975 1.651 9.339 1.651h.023c3.402-.043 6.57-.639 9.42-1.772 2.863-1.142 5.375-2.757 7.465-4.804 2.091-2.051 3.742-4.524 4.91-7.358 1.162-2.823 1.75-5.987 1.75-9.402 0-3.487-.588-6.705-1.748-9.568-1.168-2.874-2.82-5.371-4.913-7.425zm-4.644 16.762c0 1.96-.302 3.782-.896 5.413-.587 1.607-1.42 3.011-2.479 4.167-1.05 1.147-2.335 2.065-3.821 2.728-1.479.656-3.164.99-5.008.99-1.84 0-3.514-.333-4.973-.988-1.47-.662-2.747-1.578-3.799-2.729-1.062-1.156-1.895-2.559-2.479-4.167-.595-1.63-.896-3.451-.896-5.413 0-1.801.298-3.497.887-5.044.584-1.536 1.419-2.894 2.479-4.037 1.048-1.132 2.323-2.03 3.792-2.674 1.465-.642 3.145-.968 4.988-.968 1.848 0 3.539.326 5.025.971 1.481.643 2.766 1.541 3.812 2.671 1.062 1.143 1.896 2.501 2.479 4.036.589 1.548.889 3.245.889 5.044zM376.27 395.65c1.902-2.327 2.867-5.221 2.867-8.603 0-2.614-.508-4.84-1.506-6.613-.997-1.762-2.354-3.188-4.035-4.234-1.603-.995-3.445-1.705-5.482-2.114-1.938-.388-3.969-.583-6.037-.583h-16.021v44.487h10.961v-17.282h2.35l9.447 17.282h13.127l-11.199-18.646c2.262-.728 4.116-1.964 5.528-3.694zm-19.254-12.223h4.426c.844 0 1.73.054 2.636.16.784.094 1.503.283 2.132.568.496.225.888.553 1.193.998.283.415.428 1.031.428 1.836 0 .931-.16 1.643-.459 2.06-.34.472-.771.813-1.32 1.046-.686.289-1.459.477-2.301.554-.975.089-1.963.136-2.938.136h-3.795l-.002-7.358z"/>
|
||||
<path d="M394.82 386.38c1.05-1.132 2.325-2.03 3.793-2.674 1.464-.642 3.144-.968 4.988-.968 1.843 0 3.611.311 5.26.921 1.609.599 2.992 1.449 4.107 2.531l1.314 1.278 8.019-8.105-1.454-1.298c-2.355-2.103-5.066-3.586-8.058-4.407-2.879-.789-5.987-1.189-9.247-1.189-3.361 0-6.503.556-9.339 1.651-2.856 1.106-5.355 2.707-7.431 4.761-2.074 2.052-3.716 4.559-4.88 7.45-1.158 2.876-1.746 6.104-1.746 9.59 0 3.417.59 6.582 1.752 9.403 1.164 2.829 2.807 5.297 4.88 7.329 2.073 2.03 4.572 3.621 7.425 4.724 2.832 1.096 5.975 1.651 9.339 1.651 6.501 0 12.475-1.432 17.751-4.25l.979-.522v-23.814h-19.313v10.27h8.354v6.639c-.871.397-1.834.709-2.881.933-1.5.314-3.127.478-4.83.478-1.841 0-3.514-.333-4.973-.988-1.472-.662-2.748-1.578-3.801-2.729-1.06-1.156-1.893-2.559-2.478-4.167-.595-1.63-.896-3.451-.896-5.413 0-1.801.299-3.497.887-5.044.586-1.54 1.421-2.897 2.479-4.041zM437.69 407.72v-7.36h18.72v-10.27h-18.72v-6.32h19.75V373.5h-30.72v44.49h31.76v-10.27z"/>
|
||||
</g>
|
||||
<path fill="#1E2D41" d="m243.63 379.09-37.842-1.852 46.229-.034v-3.727h-52.125l-.001 7.798v6.201c0 .115-1.52-9.144-1.87-11.734h-4.098v13.029c0 .123-1.753-10.888-1.939-12.264H164.07c1.902 1.648 12.401 10.598 19.865 14.28 3.741 1.846 8.33 1.86 12.414 1.974 2.075.06 4.25.217 5.803 1.754 2.255 2.236 2.758 5.704.814 8.33-1.922 2.594-7.335 3.156-7.335 3.156l-4.509 5.531v6.424h10.251l.319-6.348 8.863-6.285c-.946.757-3.058 2.783-6.229 7.666-.717 1.102-1.275 2.306-1.711 3.49 2.238-1.896 6.84-3.194 12.153-3.194 5.307 0 9.903 1.295 12.146 3.188-.437-1.185-.994-2.385-1.709-3.483-3.172-4.883-5.284-6.909-6.229-7.666l8.863 6.285.32 6.348h9.565v-6.424l-4.507-5.531s-6.675-.425-8.423-3.156c-5.032-7.869 2.115-20.082 18.836-23.756z"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 3.5 KiB |
@@ -1,24 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
for file in $(find repo | grep --invert-match -e md5 -e sha | grep -e .jar -e .zip); do
|
||||
file_path=$(realpath $file)
|
||||
file_name=$(basename $file)
|
||||
|
||||
echo "$file_name"
|
||||
files=$(unzip -l $file | awk '{print $4}')
|
||||
for f in $files; do
|
||||
out="_actual/$file_name/$f"
|
||||
parent=$(dirname "$out")
|
||||
echo $out
|
||||
|
||||
if [ ! -d "$parent" ]; then
|
||||
mkdir -p "$parent"
|
||||
fi
|
||||
|
||||
if [[ $f == *.class ]]; then
|
||||
javap -v -p jar:file://$file_path!/$f | tail -n +4 >$out.txt
|
||||
elif [[ $f != */ && $f != "Name" && $f != "----" ]]; then
|
||||
unzip -o -q $file $f -d _actual/$file_name
|
||||
fi
|
||||
done
|
||||
done
|
||||
@@ -1,20 +0,0 @@
|
||||
plugins {
|
||||
id 'net.minecraftforge.forge.build.convention'
|
||||
}
|
||||
|
||||
gradleutils.displayName = 'FML'
|
||||
description = 'Core library used for Forge ModLoader.'
|
||||
|
||||
dependencies {
|
||||
api libs.eventbus
|
||||
|
||||
implementation projects.fmlloader
|
||||
implementation libs.commons.io
|
||||
}
|
||||
|
||||
convention.manifest('net/minecraftforge/fml/', [
|
||||
'Automatic-Module-Name': 'net.minecraftforge.fmlcore',
|
||||
'FMLModType' : 'LIBRARY'
|
||||
])
|
||||
|
||||
convention.publish()
|
||||
@@ -1,43 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
import net.minecraftforge.eventbus.api.bus.BusGroup;
|
||||
import net.minecraftforge.fml.config.IConfigEvent;
|
||||
import net.minecraftforge.fml.loading.FMLLoader;
|
||||
|
||||
import java.util.ServiceConfigurationError;
|
||||
import java.util.ServiceLoader;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* Used to allow access to certain things from the game layer
|
||||
*/
|
||||
public final class Bindings {
|
||||
private Bindings() {}
|
||||
|
||||
/**
|
||||
* The provider of the bindings
|
||||
* @implNote May also throw a {@link ServiceConfigurationError}
|
||||
*/
|
||||
private static final IBindingsProvider PROVIDER = ServiceLoader.load(FMLLoader.getGameLayer(), IBindingsProvider.class)
|
||||
.findFirst().orElseThrow(() -> new IllegalStateException("Could not find bindings provider"));
|
||||
|
||||
/**
|
||||
* @return A supplier of {@link BusGroup#DEFAULT}
|
||||
*/
|
||||
public static Supplier<BusGroup> getForgeBus() {
|
||||
return PROVIDER.getForgeBusSupplier();
|
||||
}
|
||||
|
||||
public static Supplier<I18NParser> getMessageParser() {
|
||||
return PROVIDER.getMessageParser();
|
||||
}
|
||||
|
||||
public static Supplier<IConfigEvent.ConfigConfig> getConfigConfiguration() {
|
||||
return PROVIDER.getConfigConfiguration();
|
||||
}
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
import com.mojang.logging.LogUtils;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.function.BooleanSupplier;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public class CrashReportCallables {
|
||||
private static final Logger LOGGER = LogUtils.getLogger();
|
||||
private static final List<ISystemReportExtender> crashCallables = Collections.synchronizedList(new ArrayList<>());
|
||||
|
||||
/**
|
||||
* Register a custom {@link ISystemReportExtender}
|
||||
*/
|
||||
public static void registerCrashCallable(ISystemReportExtender callable) {
|
||||
crashCallables.add(callable);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a {@link ISystemReportExtender system report extender} with the given header name and content
|
||||
* generator, which will always be appended to the system report
|
||||
* @param headerName The name of the system report entry
|
||||
* @param reportGenerator The report generator to be called when a crash report is built
|
||||
*/
|
||||
public static void registerCrashCallable(String headerName, Supplier<String> reportGenerator) {
|
||||
registerCrashCallable(new ISystemReportExtender() {
|
||||
@Override
|
||||
public String getLabel() {
|
||||
return headerName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String get() {
|
||||
return reportGenerator.get();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a {@link ISystemReportExtender system report extender} with the given header name and content
|
||||
* generator, which will only be appended to the system report when the given {@link BooleanSupplier} returns true
|
||||
* @param headerName The name of the system report entry
|
||||
* @param reportGenerator The report generator to be called when a crash report is built
|
||||
* @param active The supplier of the flag to be checked when a crash report is built
|
||||
*/
|
||||
public static void registerCrashCallable(String headerName, Supplier<String> reportGenerator, BooleanSupplier active) {
|
||||
registerCrashCallable(new ISystemReportExtender() {
|
||||
@Override
|
||||
public String getLabel() {
|
||||
return headerName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String get() {
|
||||
return reportGenerator.get();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isActive() {
|
||||
try {
|
||||
return active.getAsBoolean();
|
||||
} catch (Throwable t) {
|
||||
LOGGER.warn("CrashCallable '{}' threw an exception while checking the active flag, disabling", headerName, t);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public static List<ISystemReportExtender> allCrashCallables() {
|
||||
return List.copyOf(crashCallables);
|
||||
}
|
||||
}
|
||||
@@ -1,128 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
import static net.minecraftforge.fml.Logging.LOADING;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.ConcurrentLinkedDeque;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import com.google.common.base.Stopwatch;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
/**
|
||||
* Utility for running code on the main launch thread at the next available
|
||||
* opportunity. There is no guaranteed order that work from various mods will be
|
||||
* run, but your own work will be run sequentially.
|
||||
* <p>
|
||||
* <strong>Use of this class after startup is not possible.</strong> At that
|
||||
* point, {@code ReentrantBlockableEventLoop} should be used instead.
|
||||
* <p>
|
||||
* Exceptions from tasks will be handled gracefully, causing a mod loading
|
||||
* error. Tasks that take egregiously long times to run will be logged.
|
||||
*/
|
||||
public class DeferredWorkQueue
|
||||
{
|
||||
private static final Logger LOGGER = LogManager.getLogger();
|
||||
|
||||
private static final Map<ModLoadingStage, DeferredWorkQueue> workQueues = new HashMap<>();
|
||||
|
||||
private final ConcurrentLinkedDeque<TaskInfo> tasks = new ConcurrentLinkedDeque<>();
|
||||
private final ModLoadingStage modLoadingStage;
|
||||
|
||||
public DeferredWorkQueue(ModLoadingStage modLoadingStage) {
|
||||
this.modLoadingStage = modLoadingStage;
|
||||
workQueues.put(modLoadingStage, this);
|
||||
}
|
||||
|
||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
||||
public static Optional<DeferredWorkQueue> lookup(Optional<ModLoadingStage> parallelClass) {
|
||||
return Optional.ofNullable(workQueues.get(parallelClass.orElse(null)));
|
||||
}
|
||||
|
||||
public void runTasks() {
|
||||
if (tasks.isEmpty()) return;
|
||||
LOGGER.debug(LOADING, "Dispatching synchronous work for work queue {}: {} jobs", modLoadingStage, tasks.size());
|
||||
RuntimeException aggregate = new RuntimeException();
|
||||
Stopwatch timer = Stopwatch.createStarted();
|
||||
for (TaskInfo t : tasks) {
|
||||
makeRunnable(t, Runnable::run, aggregate);
|
||||
}
|
||||
timer.stop();
|
||||
if (aggregate.getSuppressed().length > 0) {
|
||||
LOGGER.fatal(
|
||||
LOADING,
|
||||
"Synchronous work queue completed exceptionally in {}, see suppressed exceptions for details:",
|
||||
timer,
|
||||
aggregate
|
||||
);
|
||||
throw aggregate;
|
||||
} else {
|
||||
LOGGER.debug(LOADING, "Synchronous work queue completed in {}", timer);
|
||||
}
|
||||
}
|
||||
|
||||
private static void makeRunnable(TaskInfo ti, Executor executor, RuntimeException aggregate) {
|
||||
executor.execute(() -> {
|
||||
Stopwatch timer = Stopwatch.createStarted();
|
||||
ModLoadingContext.get().setActiveContainer(ti.owner);
|
||||
try {
|
||||
ti.future.exceptionally(t -> captureException(ti.owner.getModId(), aggregate, t));
|
||||
ti.task.run();
|
||||
} finally {
|
||||
ModLoadingContext.get().setActiveContainer(null);
|
||||
}
|
||||
timer.stop();
|
||||
if (timer.elapsed(TimeUnit.SECONDS) >= 1) {
|
||||
LOGGER.warn(LOADING, "Mod '{}' took {} to run a deferred task.", ti.owner.getModId(), timer);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static <T> T captureException(String modId, RuntimeException aggregate, Throwable throwable) {
|
||||
if (throwable instanceof CompletionException ce) {
|
||||
throwable = ce.getCause();
|
||||
}
|
||||
aggregate.addSuppressed(throwable);
|
||||
LOGGER.error("Mod '{}' encountered an error in a deferred task:", modId, throwable);
|
||||
return null;
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> enqueueWork(final ModContainer modInfo, final Runnable work) {
|
||||
return enqueueWork(modInfo, taskInfo -> CompletableFuture.runAsync(work, r -> taskInfo.task = r));
|
||||
}
|
||||
|
||||
public <T> CompletableFuture<T> enqueueWork(final ModContainer modInfo, final Supplier<T> work) {
|
||||
return enqueueWork(modInfo, taskInfo -> CompletableFuture.supplyAsync(work, r -> taskInfo.task = r));
|
||||
}
|
||||
|
||||
private <T> CompletableFuture<T> enqueueWork(final ModContainer modInfo, Function<TaskInfo, CompletableFuture<T>> futureGen) {
|
||||
TaskInfo taskInfo = new TaskInfo(modInfo);
|
||||
CompletableFuture<T> future = futureGen.apply(taskInfo);
|
||||
taskInfo.future = future;
|
||||
tasks.add(taskInfo);
|
||||
return future;
|
||||
}
|
||||
|
||||
private static final class TaskInfo {
|
||||
private final ModContainer owner;
|
||||
private Runnable task;
|
||||
private CompletableFuture<?> future;
|
||||
|
||||
private TaskInfo(ModContainer owner) {
|
||||
this.owner = owner;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
public interface I18NParser {
|
||||
String parseMessage(String i18nMessage, Object... args);
|
||||
String stripControlCodes(String toStrip);
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
import net.minecraftforge.eventbus.api.bus.BusGroup;
|
||||
import net.minecraftforge.fml.config.IConfigEvent;
|
||||
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public interface IBindingsProvider {
|
||||
Supplier<BusGroup> getForgeBusSupplier();
|
||||
Supplier<I18NParser> getMessageParser();
|
||||
Supplier<IConfigEvent.ConfigConfig> getConfigConfiguration();
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
@@ -1,121 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
import java.util.function.BiPredicate;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* An extension point for a mod container.
|
||||
*
|
||||
* <p>An extension point can be registered for a mod container using {@link ModContainer#registerExtensionPoint(Class, Supplier)}
|
||||
* and retrieved (if present) using {@link ModContainer#getCustomExtension(Class)}. An extension point allows a mod to
|
||||
* supply an arbitrary value as a record class to another mod or framework through their mod container class, avoiding
|
||||
* the use of {@link InterModComms} or other external frameworks to pass around these values.</p>
|
||||
*
|
||||
* <p>The usual way to declare an extension point is to implement this interface on a record class, with the type
|
||||
* parameter being a reference to the class itself. For example, {@code record MyExtension(...) extends
|
||||
* IExtensionPoint<MyExtension>} would declare an extension point which supplies a {@code MyExtension} object. However,
|
||||
* there is no hard requirement that an extension point's type parameter must be in reference to itself; the type
|
||||
* parameter may reference another record class instead.</p>
|
||||
*
|
||||
* @param <T> the type of the record which is held by the extension point
|
||||
*/
|
||||
@SuppressWarnings("unused") // Type parameter T
|
||||
// TODO: Complete re-write, this hasnt actually be used in a generic way by mods and we could make it a lot simpler.
|
||||
public interface IExtensionPoint<T extends Record>
|
||||
{
|
||||
/**
|
||||
* Extension point for the compatibility display test used on the server selection screen.
|
||||
*
|
||||
* <em>Note: "server" and "client" refers to the {@linkplain net.minecraftforge.api.distmarker.Dist#DEDICATED_SERVER dedicated server}
|
||||
* and {@linkplain net.minecraftforge.api.distmarker.Dist#CLIENT game client} physical distributions, rather than the
|
||||
* {@linkplain LogicalSide logical server and client}.</em>
|
||||
*
|
||||
* <p>The {@link Supplier} provides the local compatibility version, which is sent from the server to the client
|
||||
* for multiplayer connections or stored to disk for the world save. The {@link BiPredicate} accepts the remote
|
||||
* compatibility version and a boolean indicating whether the remote version is from the server or a world save,
|
||||
* where {@code true} means it is from the server and {@code false} means it is from the world save. The return
|
||||
* value of the predicate determines whether the remote version is "compatible" for the purposes of the display test.</p>
|
||||
*
|
||||
* <p>The local compatibility version may be of the value {@link DisplayTest#IGNORESERVERONLY},
|
||||
* in which case clients will ignore the mod's presence if it is present on the server but not on the client.
|
||||
* However, the remote version test predicate must still accept this value as a remote version in order to display
|
||||
* as compatible if the mod is present on the client.</p>
|
||||
*
|
||||
* <p><strong>The compatibility display test does not necessarily indicate the success or failure of an actual
|
||||
* connection attempt.</strong> Factors such as display test extension misconfiguration, truncation of ping data,
|
||||
* difference of registry data or network channels between server and client, and others may cause the result of the
|
||||
* compatibility test to not reflect the actual likelihood of a connection successfully being established between
|
||||
* the server and the client.</p>
|
||||
*
|
||||
* <p>An example declaration of a display test extension registration for a regular mod (requires to be present on
|
||||
* server and client) is as follows:</p>
|
||||
* <pre>{@code
|
||||
* String compatibilityVersion = "1"; // Could be linked with a network channel version or mod version
|
||||
* ModLoadingContext.get().registerExtensionPoint(IExtensionPoint.DisplayTest.class,
|
||||
* () -> new IExtensionPoint.DisplayTest(
|
||||
* () -> compatibilityVersion,
|
||||
* (remoteVersion, isFromServer) -> remoteVersion.equals(compatibilityVersion)
|
||||
* )
|
||||
* );
|
||||
* }</pre>
|
||||
*
|
||||
* <p>An example declaration of a display test extension registration for a <em>server-side-only</em> mod (does not
|
||||
* require to be present on the client) is as follows:</p>
|
||||
* <pre>{@code
|
||||
* ModLoadingContext.get().registerExtensionPoint(IExtensionPoint.DisplayTest.class,
|
||||
* () -> new IExtensionPoint.DisplayTest(
|
||||
* // Ignore this mod if not present on the client
|
||||
* () -> NetworkConstants.IGNORESERVERONLY,
|
||||
* // If present on the client, accept any version if from a server
|
||||
* (remoteVersion, isFromServer) -> isFromServer
|
||||
* )
|
||||
* );
|
||||
* }</pre>
|
||||
*
|
||||
* <p>An example declaration of a display test extension registration for a <em>client-side-only</em> mod (does not
|
||||
* require to be present on the server) is as follows:</p>
|
||||
* <pre>{@code
|
||||
* ModLoadingContext.get().registerExtensionPoint(IExtensionPoint.DisplayTest.class,
|
||||
* () -> new IExtensionPoint.DisplayTest(
|
||||
* // Send any version from server to client, since we will be accepting any version as well
|
||||
* () -> "dQw4w9WgXcQ",
|
||||
* // Accept any version on the client, from server or from save
|
||||
* (remoteVersion, isFromServer) -> true
|
||||
* )
|
||||
* );
|
||||
* }</pre>
|
||||
*
|
||||
* @see net.minecraftforge.network.ServerStatusPing
|
||||
* @see net.minecraftforge.client.ForgeHooksClient#processForgeListPingData(net.minecraft.network.protocol.status.ServerStatus, net.minecraft.client.multiplayer.ServerData)
|
||||
*/
|
||||
@SuppressWarnings("JavadocReference") // reference to NetworkConstants, ForgeHooksClient
|
||||
record DisplayTest(Supplier<String> suppliedVersion, BiPredicate<String, Boolean> remoteVersionTest) implements IExtensionPoint<DisplayTest> {
|
||||
public static final String IGNORESERVERONLY = "SERVER_ONLY";
|
||||
|
||||
/**
|
||||
* Ignores any version information coming from the server - use for server only mods
|
||||
*/
|
||||
public static final Supplier<DisplayTest> IGNORE_SERVER_VERSION = () -> new DisplayTest(IGNORESERVERONLY, (remoteVersion, isFromServer) -> true);
|
||||
|
||||
/**
|
||||
* Ignores all information and provides no information
|
||||
* <p>Note: If your mod is purely client-side and has no multiplayer functionality (be it dedicated servers or
|
||||
* Open to LAN), consider setting {@code clientSideOnly=true} in the root of your mods.toml.</p>
|
||||
*/
|
||||
public static final Supplier<DisplayTest> IGNORE_ALL_VERSION = () -> new DisplayTest("", (remoteVersion, isFromServer) -> true);
|
||||
|
||||
/**
|
||||
* An optional alternative to {@link #DisplayTest(Supplier, BiPredicate)} which accepts a constant version string
|
||||
* instead of a {@link Supplier}.
|
||||
* <p>Internally, the provided version string is wrapped in a Supplier for you.</p>
|
||||
*/
|
||||
public DisplayTest(String version, BiPredicate<String, Boolean> remoteVersionTest) {
|
||||
this(() -> version, remoteVersionTest);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,99 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
import net.minecraftforge.fml.loading.progress.ProgressMeter;
|
||||
import org.jspecify.annotations.NullMarked;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.IntSupplier;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* A mod loading state. During mod loading, the mod loader transitions between states in a defined sorted list of states,
|
||||
* grouped into various {@link ModLoadingPhase phases}.
|
||||
*
|
||||
* @see IModStateProvider
|
||||
*/
|
||||
@NullMarked
|
||||
public interface IModLoadingState {
|
||||
/**
|
||||
* {@return the name of this state}
|
||||
*/
|
||||
String name();
|
||||
|
||||
/**
|
||||
* {@return the name of the state immediately previous to this state} This may be a blank name, which indicates this
|
||||
* is either the first mod loading state or an exceptional mod loading state (such as a situation where errors
|
||||
* prevent the loading process from continuing normally).
|
||||
*/
|
||||
String previous();
|
||||
|
||||
/**
|
||||
* {@return the mod loading phase this state belongs to} For exceptional mod loading states, this should be
|
||||
* {@link ModLoadingPhase#ERROR}.
|
||||
*/
|
||||
ModLoadingPhase phase();
|
||||
|
||||
/**
|
||||
* {@return a function returning a human-friendly message for this state}
|
||||
*/
|
||||
Supplier<String> message();
|
||||
|
||||
/**
|
||||
* @return a function that computes the size of this transition based on the size of the modlist.
|
||||
* Used to compute progress.
|
||||
*/
|
||||
default IntSupplier size() {
|
||||
return ModList::size;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@return an optional runnable, which runs before starting the transition from this state to the next}
|
||||
* @see #buildTransition(Executor, Executor, ProgressMeter, Function, Function)
|
||||
*/
|
||||
@Nullable Runnable inlineRunnable();
|
||||
|
||||
/**
|
||||
* Builds the transition task for this state with a blank pre-sync and post-sync task.
|
||||
*
|
||||
* @param syncExecutor a synchronous executor
|
||||
* @param parallelExecutor a parallel executor
|
||||
* @param progressBar a progress meter for tracking progress
|
||||
* @return a transition task for this state
|
||||
* @see #buildTransition(Executor, Executor, ProgressMeter, Function, Function)
|
||||
*/
|
||||
default @Nullable CompletableFuture<Void> buildTransition(
|
||||
final Executor syncExecutor,
|
||||
final Executor parallelExecutor,
|
||||
final ProgressMeter progressBar
|
||||
) {
|
||||
return buildTransition(syncExecutor, parallelExecutor, progressBar,
|
||||
_ -> CompletableFuture.completedFuture(null),
|
||||
_ -> CompletableFuture.completedFuture(null)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the transition task for this state. The pre-sync and post-sync task functions allow the transition builder
|
||||
* to run these tasks on the same executor as the actual event dispatch and pre/post hooks.
|
||||
*
|
||||
* @param syncExecutor a synchronous executor
|
||||
* @param parallelExecutor a parallel executor
|
||||
* @param progressBar a progress meter for tracking progress
|
||||
* @param preSyncTask a function which returns a task to run before event pre-dispatch hook
|
||||
* @param postSyncTask a function which returns a task to run after event post-dispatch hook
|
||||
* @return a transition task for this state
|
||||
*/
|
||||
@Nullable CompletableFuture<Void> buildTransition(final Executor syncExecutor,
|
||||
final Executor parallelExecutor,
|
||||
final ProgressMeter progressBar,
|
||||
final Function<Executor, CompletableFuture<Void>> preSyncTask,
|
||||
final Function<Executor, CompletableFuture<Void>> postSyncTask);
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Provides a list of mod loading states which the mod loader may transition between.
|
||||
*
|
||||
* <p>There may be multiple mod state providers in a single application, where all states from each provider is
|
||||
* combined into a single list and ordered.</p>
|
||||
*/
|
||||
public interface IModStateProvider {
|
||||
/**
|
||||
* {@return the list of mod loading states known to this provider}
|
||||
*/
|
||||
List<IModLoadingState> getAllStates();
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
import net.minecraftforge.fml.event.IModBusEvent;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.function.Function;
|
||||
|
||||
import net.minecraftforge.fml.loading.progress.ProgressMeter;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public interface IModStateTransition {
|
||||
static IModStateTransition buildNoopTransition() {
|
||||
return ModStateTransitionHelper.NOOP;
|
||||
}
|
||||
|
||||
default CompletableFuture<Void> build(
|
||||
final String name,
|
||||
final Executor syncExecutor,
|
||||
final Executor parallelExecutor,
|
||||
final ProgressMeter progressBar,
|
||||
final Function<Executor, CompletableFuture<Void>> preSyncTask,
|
||||
final Function<Executor, CompletableFuture<Void>> postSyncTask
|
||||
) {
|
||||
return ModStateTransitionHelper.build(this, name, syncExecutor, parallelExecutor, progressBar, preSyncTask, postSyncTask);
|
||||
}
|
||||
|
||||
default BiFunction<ModLoadingStage, Throwable, ModLoadingStage> nextModLoadingStage() {
|
||||
return ModLoadingStage::nextState;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
default <T extends IModBusEvent> EventGenerator<T> eventFunction() {
|
||||
return null;
|
||||
}
|
||||
|
||||
ThreadSelector threadSelector();
|
||||
BiFunction<Executor, CompletableFuture<Void>, CompletableFuture<Void>> finalActivityGenerator();
|
||||
|
||||
interface EventGenerator<T extends IModBusEvent> extends Function<ModContainer, T> {
|
||||
static <FN extends IModBusEvent> EventGenerator<FN> fromFunction(Function<ModContainer, FN> fn) {
|
||||
return fn::apply;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public interface ISystemReportExtender extends Supplier<String> {
|
||||
String getLabel();
|
||||
|
||||
default boolean isActive() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -1,117 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.Spliterator;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentLinkedQueue;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Stream;
|
||||
import java.util.stream.StreamSupport;
|
||||
|
||||
public final class InterModComms {
|
||||
public record IMCMessage(String senderModId, String modId, String method, Supplier<?> messageSupplier) {}
|
||||
|
||||
private static final ConcurrentHashMap<String, ConcurrentLinkedQueue<IMCMessage>> containerQueues = new ConcurrentHashMap<>();
|
||||
|
||||
/**
|
||||
* Send IMC to remote. Sender will default to the active modcontainer, or minecraft if not.
|
||||
*
|
||||
* @param modId the mod id to send to
|
||||
* @param method the method name to send
|
||||
* @param thing the thing associated with the method name
|
||||
* @return true if the message was enqueued for sending (the target modid is loaded)
|
||||
*/
|
||||
public static boolean sendTo(final String modId, final String method, final Supplier<?> thing) {
|
||||
if (!ModList.isLoaded(modId)) return false;
|
||||
containerQueues.computeIfAbsent(modId, _ -> new ConcurrentLinkedQueue<>())
|
||||
.add(new IMCMessage(ModLoadingContext.get().getContainer().getModId(), modId, method, thing));
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Send IMC to remote.
|
||||
*
|
||||
* @param senderModId the mod id you are sending from
|
||||
* @param modId the mod id to send to
|
||||
* @param method the method name to send
|
||||
* @param thing the thing associated with the method name
|
||||
* @return true if the message was enqueued for sending (the target modid is loaded)
|
||||
*/
|
||||
public static boolean sendTo(final String senderModId, final String modId, final String method, final Supplier<?> thing) {
|
||||
if (!ModList.isLoaded(modId)) return false;
|
||||
containerQueues.computeIfAbsent(modId, _ -> new ConcurrentLinkedQueue<>())
|
||||
.add(new IMCMessage(senderModId, modId, method, thing));
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve pending messages for your modid. Use the predicate to filter the method name.
|
||||
*
|
||||
* @param modId the modid you are querying for
|
||||
* @param methodMatcher a predicate for the method you are interested in
|
||||
* @return All messages passing the supplied method predicate
|
||||
*/
|
||||
public static Stream<IMCMessage> getMessages(final String modId, final Predicate<String> methodMatcher) {
|
||||
ConcurrentLinkedQueue<IMCMessage> queue = containerQueues.get(modId);
|
||||
if (queue == null) return Stream.empty();
|
||||
return StreamSupport.stream(new QueueFilteringSpliterator(queue, methodMatcher), false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve all message for your modid.
|
||||
*
|
||||
* @param modId the modid you are querying for
|
||||
* @return All messages
|
||||
*/
|
||||
public static Stream<IMCMessage> getMessages(final String modId) {
|
||||
return getMessages(modId, _ -> true);
|
||||
}
|
||||
|
||||
private record QueueFilteringSpliterator(
|
||||
ConcurrentLinkedQueue<IMCMessage> queue,
|
||||
Predicate<String> methodFilter,
|
||||
Iterator<IMCMessage> iterator
|
||||
) implements Spliterator<IMCMessage> {
|
||||
|
||||
public QueueFilteringSpliterator(final ConcurrentLinkedQueue<IMCMessage> queue, final Predicate<String> methodFilter) {
|
||||
this(queue, methodFilter, queue.iterator());
|
||||
}
|
||||
|
||||
@Override
|
||||
public int characteristics() {
|
||||
return Spliterator.CONCURRENT | Spliterator.NONNULL | Spliterator.ORDERED;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long estimateSize() {
|
||||
return queue.size();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean tryAdvance(final Consumer<? super IMCMessage> action) {
|
||||
IMCMessage next;
|
||||
do {
|
||||
if (!iterator.hasNext()) {
|
||||
return false;
|
||||
}
|
||||
next = this.iterator.next();
|
||||
}
|
||||
while (!methodFilter.test(next.method));
|
||||
action.accept(next);
|
||||
this.iterator.remove();
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Spliterator<IMCMessage> trySplit() {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class LoadingFailedException extends RuntimeException {
|
||||
private final List<ModLoadingException> loadingExceptions;
|
||||
|
||||
public LoadingFailedException(final List<ModLoadingException> loadingExceptions) {
|
||||
this.loadingExceptions = loadingExceptions;
|
||||
}
|
||||
|
||||
public List<ModLoadingException> getErrors() {
|
||||
return this.loadingExceptions;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getMessage() {
|
||||
return "Loading errors encountered: " + this.loadingExceptions.stream().map(ModLoadingException::getMessage).collect(Collectors.joining(",\n\t", "[\n\t", "\n]"));
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
import org.apache.logging.log4j.Marker;
|
||||
import org.apache.logging.log4j.MarkerManager;
|
||||
|
||||
public class Logging
|
||||
{
|
||||
// Lots of markers
|
||||
public static final Marker CORE = MarkerManager.getMarker("CORE");
|
||||
public static final Marker LOADING = MarkerManager.getMarker("LOADING");
|
||||
public static final Marker SCAN = MarkerManager.getMarker("SCAN");
|
||||
public static final Marker SPLASH = MarkerManager.getMarker("SPLASH");
|
||||
public static final Marker CAPABILITIES = MarkerManager.getMarker("CAPABILITIES");
|
||||
public static final Marker MODELLOADING = MarkerManager.getMarker("MODELLOADING");
|
||||
public static final Marker FORGEMOD = MarkerManager.getMarker("FORGEMOD").addParents(LOADING);
|
||||
|
||||
// --log CORE:+DEBUG,SCAN:-OFF
|
||||
// forge log debug 5
|
||||
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
import net.minecraftforge.api.distmarker.Dist;
|
||||
|
||||
/**
|
||||
* A logical side of the Minecraft game.
|
||||
* <p>
|
||||
* The {@linkplain Dist#CLIENT client distribution} has a copy of the logical client and the logical server, while the
|
||||
* {@linkplain Dist#DEDICATED_SERVER dedicated server distribution} only holds
|
||||
* the logical server.
|
||||
*
|
||||
* @see Dist
|
||||
*/
|
||||
public enum LogicalSide {
|
||||
/**
|
||||
* The logical client of the Minecraft game, which interfaces with the player's inputs and renders the player's
|
||||
* viewpoint.
|
||||
* <p>
|
||||
* The logical client is only shipped with the client distribution of the game.
|
||||
*
|
||||
* @see Dist#CLIENT
|
||||
*/
|
||||
CLIENT,
|
||||
|
||||
/**
|
||||
* The logical server of the Minecraft game, responsible for connecting to clients and running the simulation logic
|
||||
* on the level.
|
||||
* <p>
|
||||
* The logical server is shipped with both client and dedicated server distributions. The client distribution runs
|
||||
* the logical server for singleplayer mode and LAN play.
|
||||
*
|
||||
* @see Dist#DEDICATED_SERVER
|
||||
*/
|
||||
SERVER;
|
||||
|
||||
/**
|
||||
* {@return if this logical side is the server}
|
||||
*/
|
||||
public boolean isServer() {
|
||||
return !isClient();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@return if the logical side is the client}
|
||||
*/
|
||||
public boolean isClient() {
|
||||
return this == CLIENT;
|
||||
}
|
||||
}
|
||||
@@ -1,163 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
import net.minecraftforge.eventbus.api.bus.BusGroup;
|
||||
import net.minecraftforge.fml.config.IConfigEvent;
|
||||
import net.minecraftforge.fml.config.ModConfig;
|
||||
import net.minecraftforge.fml.event.IModBusEvent;
|
||||
import net.minecraftforge.forgespi.language.IModInfo;
|
||||
|
||||
import java.util.EnumMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.IdentityHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.function.BiPredicate;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* The container that wraps around mods in the system.
|
||||
* <p>
|
||||
* The philosophy is that individual mod implementation technologies should not
|
||||
* impact the actual loading and management of mod code. This class provides
|
||||
* a mechanism by which we can wrap actual mod code so that the loader and other
|
||||
* facilities can treat mods at arms length.
|
||||
* </p>
|
||||
*/
|
||||
public abstract class ModContainer {
|
||||
protected final String modId;
|
||||
protected final String namespace;
|
||||
protected final IModInfo modInfo;
|
||||
protected ModLoadingStage modLoadingStage;
|
||||
protected Supplier<?> contextExtension;
|
||||
protected final Map<ModLoadingStage, Runnable> activityMap = new EnumMap<>(ModLoadingStage.class);
|
||||
protected final Map<Class<? extends IExtensionPoint<?>>, Supplier<?>> extensionPoints = new IdentityHashMap<>();
|
||||
protected final EnumMap<ModConfig.Type, ModConfig> configs = new EnumMap<>(ModConfig.Type.class);
|
||||
final Set<ModContainer> dependencies = new HashSet<>();
|
||||
|
||||
public ModContainer(IModInfo info) {
|
||||
this.modId = info.getModId();
|
||||
// TODO: Currently not reading namespace from configuration..
|
||||
this.namespace = this.modId;
|
||||
this.modInfo = info;
|
||||
this.modLoadingStage = ModLoadingStage.CONSTRUCT;
|
||||
|
||||
final String displayTestString = info.getConfig().<String>getConfigElement("displayTest")
|
||||
.orElseGet(() -> info.getOwningFile().isClientSideOnly() ? "IGNORE_ALL_VERSION" : "MATCH_VERSION");
|
||||
Supplier<IExtensionPoint.DisplayTest> displayTestSupplier = switch (displayTestString) {
|
||||
case "MATCH_VERSION" -> // default displaytest checks for version string match
|
||||
() -> new IExtensionPoint.DisplayTest(() -> this.modInfo.getVersion().toString(),
|
||||
(incoming, _) -> Objects.equals(incoming, this.modInfo.getVersion().toString()));
|
||||
case "IGNORE_SERVER_VERSION" -> // Ignores any version information coming from the server - use for server only mods
|
||||
IExtensionPoint.DisplayTest.IGNORE_SERVER_VERSION;
|
||||
case "IGNORE_ALL_VERSION" -> // Ignores all information and provides no information
|
||||
IExtensionPoint.DisplayTest.IGNORE_ALL_VERSION;
|
||||
case "NONE" -> null; // NO display test at all - use this if you're going to do your own display test
|
||||
default -> // any other value throws an exception
|
||||
throw new IllegalArgumentException("Invalid displayTest value supplied in mods.toml");
|
||||
};
|
||||
if (displayTestSupplier != null)
|
||||
registerExtensionPoint(IExtensionPoint.DisplayTest.class, displayTestSupplier);
|
||||
else
|
||||
extensionPoints.remove(IExtensionPoint.DisplayTest.class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Errored container state, used for filtering. Does nothing.
|
||||
*/
|
||||
ModContainer() {
|
||||
this.modLoadingStage = ModLoadingStage.ERROR;
|
||||
modId = "BROKEN";
|
||||
namespace = "BROKEN";
|
||||
modInfo = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the modid for this mod
|
||||
*/
|
||||
public final String getModId() {
|
||||
return modId;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the resource prefix for the mod
|
||||
*/
|
||||
public final String getNamespace() {
|
||||
return namespace;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return The current loading stage for this mod
|
||||
*/
|
||||
public ModLoadingStage getCurrentState() {
|
||||
return modLoadingStage;
|
||||
}
|
||||
|
||||
public IModInfo getModInfo() {
|
||||
return modInfo;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T extends Record> Optional<T> getCustomExtension(Class<? extends IExtensionPoint<T>> point) {
|
||||
return Optional.ofNullable((T)extensionPoints.getOrDefault(point,()-> null).get());
|
||||
}
|
||||
|
||||
public <T extends Record & IExtensionPoint<T>> void registerExtensionPoint(Class<? extends IExtensionPoint<T>> point, Supplier<T> extension) {
|
||||
extensionPoints.put(point, extension);
|
||||
}
|
||||
|
||||
public void registerDisplayTest(IExtensionPoint.DisplayTest displayTest) {
|
||||
registerExtensionPoint(IExtensionPoint.DisplayTest.class, () -> displayTest);
|
||||
}
|
||||
|
||||
public void registerDisplayTest(Supplier<IExtensionPoint.DisplayTest> displayTest) {
|
||||
registerExtensionPoint(IExtensionPoint.DisplayTest.class, displayTest);
|
||||
}
|
||||
|
||||
public void registerDisplayTest(String version, BiPredicate<String, Boolean> remoteVersionTest) {
|
||||
registerDisplayTest(new IExtensionPoint.DisplayTest(version, remoteVersionTest));
|
||||
}
|
||||
|
||||
public void registerDisplayTest(Supplier<String> suppliedVersion, BiPredicate<String, Boolean> remoteVersionTest) {
|
||||
registerDisplayTest(new IExtensionPoint.DisplayTest(suppliedVersion, remoteVersionTest));
|
||||
}
|
||||
|
||||
public void addConfig(final ModConfig modConfig) {
|
||||
configs.put(modConfig.getType(), modConfig);
|
||||
}
|
||||
|
||||
public void dispatchConfigEvent(IConfigEvent event) {}
|
||||
|
||||
/**
|
||||
* Does this mod match the supplied mod?
|
||||
*
|
||||
* @param mod to compare
|
||||
* @return if the mod matches
|
||||
*/
|
||||
public abstract boolean matches(Object mod);
|
||||
|
||||
/**
|
||||
* @return the mod object instance
|
||||
*/
|
||||
public abstract Object getMod();
|
||||
|
||||
/**
|
||||
* @return the mod bus group for this specific mod, or null if there is none.
|
||||
* Leave null if you use {@link BusGroup#DEFAULT} for your mod lifecycle events.
|
||||
*/
|
||||
public BusGroup getModBusGroup() {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Accept an arbitrary event for processing by the mod. Probably posted to an event bus in the lower level container.
|
||||
* @param e Event to accept
|
||||
*/
|
||||
protected <T extends IModBusEvent> void acceptEvent(T e) {}
|
||||
}
|
||||
@@ -1,160 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
import net.minecraftforge.fml.loading.LoadingModList;
|
||||
import net.minecraftforge.forgespi.language.IModFileInfo;
|
||||
import net.minecraftforge.forgespi.language.IModInfo;
|
||||
import net.minecraftforge.forgespi.language.ModFileScanData;
|
||||
import net.minecraftforge.fml.loading.moddiscovery.ModFile;
|
||||
import net.minecraftforge.fml.loading.moddiscovery.ModFileInfo;
|
||||
import net.minecraftforge.forgespi.locating.IModFile;
|
||||
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* Master list of all mods - game-side version. This is classloaded in the game scope and
|
||||
* can dispatch game level events as a result.
|
||||
*/
|
||||
public final class ModList {
|
||||
private ModList() {}
|
||||
|
||||
private static final List<IModFileInfo> MOD_FILES;
|
||||
private static final List<IModInfo> SORTED_LIST;
|
||||
private static final Map<String, IModFileInfo> FILE_BY_ID;
|
||||
private static List<ModContainer> mods;
|
||||
private static Map<String, ModContainer> indexedMods;
|
||||
private static List<ModContainer> sortedContainers;
|
||||
|
||||
static {
|
||||
var loadingModFiles = LoadingModList.getModFiles().stream().map(ModFileInfo::getFile).toList();
|
||||
var loadingSortedList = LoadingModList.getMods();
|
||||
|
||||
var modFileInfos = MOD_FILES = loadingModFiles.stream().map(ModFile::getModFileInfo).toList();
|
||||
SORTED_LIST = loadingSortedList.stream().map(IModInfo.class::cast).toList();
|
||||
var byId = new HashMap<String, IModFileInfo>();
|
||||
for (var file : modFileInfos) {
|
||||
for (var mod : file.getMods())
|
||||
byId.put(mod.getModId(), mod.getOwningFile());
|
||||
}
|
||||
FILE_BY_ID = Map.copyOf(byId);
|
||||
CrashReportCallables.registerCrashCallable("Mod List", ModList::crashReport);
|
||||
}
|
||||
|
||||
private static String getModContainerState(String modId) {
|
||||
return getModContainerById(modId).map(ModContainer::getCurrentState).map(Object::toString).orElse("NONE");
|
||||
}
|
||||
|
||||
private static String fileToLine(IModFile mf) {
|
||||
var mainMod = mf.getModInfos().getFirst();
|
||||
return String.format(Locale.ENGLISH, "%-50.50s|%-30.30s|%-30.30s|%-20.20s|%-10.10s|Manifest: %s", mf.getFileName(),
|
||||
mainMod.getDisplayName(),
|
||||
mainMod.getModId(),
|
||||
mainMod.getVersion(),
|
||||
getModContainerState(mainMod.getModId()),
|
||||
((ModFileInfo)mf.getModFileInfo()).getCodeSigningFingerprint().orElse("NOSIGNATURE"));
|
||||
}
|
||||
|
||||
private static String crashReport() {
|
||||
return "\n" + applyForEachModFile(ModList::fileToLine).collect(Collectors.joining("\n\t\t", "\t\t", ""));
|
||||
}
|
||||
|
||||
public static void init() {}
|
||||
|
||||
public static List<IModFileInfo> getModFiles() {
|
||||
return MOD_FILES;
|
||||
}
|
||||
|
||||
public static IModFileInfo getModFileById(String modid) {
|
||||
return FILE_BY_ID.get(modid);
|
||||
}
|
||||
|
||||
static void setLoadedMods(final List<ModContainer> modContainers) {
|
||||
mods = modContainers;
|
||||
sortedContainers = modContainers.stream().sorted(Comparator.comparingInt(c -> SORTED_LIST.indexOf(c.getModInfo()))).toList();
|
||||
indexedMods = modContainers.stream().collect(Collectors.toUnmodifiableMap(ModContainer::getModId, Function.identity()));
|
||||
}
|
||||
|
||||
static void clearLoadedMods() {
|
||||
mods = List.of();
|
||||
indexedMods = Map.of();
|
||||
sortedContainers = List.of();
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <T> Optional<T> getModObjectById(String modId) {
|
||||
return getModContainerById(modId).map(ModContainer::getMod).map(o -> (T) o);
|
||||
}
|
||||
|
||||
public static Optional<? extends ModContainer> getModContainerById(String modId) {
|
||||
return Optional.ofNullable(indexedMods == null ? null : indexedMods.get(modId));
|
||||
}
|
||||
|
||||
public static Optional<? extends ModContainer> getModContainerByObject(Object obj) {
|
||||
return mods.stream().filter(mc -> mc.getMod() == obj).findFirst();
|
||||
}
|
||||
|
||||
public static List<IModInfo> getMods() {
|
||||
return SORTED_LIST;
|
||||
}
|
||||
|
||||
public static boolean isLoaded(String modTarget) {
|
||||
return indexedMods.containsKey(modTarget);
|
||||
}
|
||||
|
||||
public static int size() {
|
||||
return mods.size();
|
||||
}
|
||||
|
||||
public static List<ModFileScanData> getAllScanData() {
|
||||
final class LazyInit {
|
||||
private LazyInit() {}
|
||||
private static final List<ModFileScanData> MOD_FILE_SCAN_DATA = SORTED_LIST.stream()
|
||||
.map(IModInfo::getOwningFile)
|
||||
.filter(Objects::nonNull)
|
||||
.map(IModFileInfo::getFile)
|
||||
.distinct()
|
||||
.map(IModFile::getScanResult)
|
||||
.toList();
|
||||
}
|
||||
return LazyInit.MOD_FILE_SCAN_DATA;
|
||||
}
|
||||
|
||||
public static void forEachModFile(Consumer<IModFile> fileConsumer) {
|
||||
MOD_FILES.stream().map(IModFileInfo::getFile).forEach(fileConsumer);
|
||||
}
|
||||
|
||||
public static <T> Stream<T> applyForEachModFile(Function<IModFile, T> function) {
|
||||
return MOD_FILES.stream().map(IModFileInfo::getFile).map(function);
|
||||
}
|
||||
|
||||
public static void forEachModContainer(BiConsumer<String, ModContainer> modContainerConsumer) {
|
||||
indexedMods.forEach(modContainerConsumer);
|
||||
}
|
||||
|
||||
public static void forEachModInOrder(Consumer<ModContainer> containerConsumer) {
|
||||
sortedContainers.forEach(containerConsumer);
|
||||
}
|
||||
|
||||
public static List<ModContainer> getLoadedMods() {
|
||||
return sortedContainers;
|
||||
}
|
||||
|
||||
public static <T> Stream<T> applyForEachModContainer(Function<ModContainer, T> function) {
|
||||
return indexedMods.values().stream().map(function);
|
||||
}
|
||||
}
|
||||
@@ -1,432 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
import net.minecraftforge.eventbus.api.bus.BusGroup;
|
||||
import net.minecraftforge.fml.event.IModBusEvent;
|
||||
import net.minecraftforge.fml.loading.*;
|
||||
import net.minecraftforge.fml.loading.moddiscovery.InvalidModIdentifier;
|
||||
import net.minecraftforge.fml.loading.moddiscovery.ModFileInfo;
|
||||
import net.minecraftforge.fml.loading.progress.ProgressMeter;
|
||||
import net.minecraftforge.fml.loading.progress.StartupNotificationManager;
|
||||
import net.minecraftforge.forgespi.language.IModInfo;
|
||||
import net.minecraftforge.forgespi.language.IModLanguageProvider;
|
||||
import net.minecraftforge.forgespi.locating.ForgeFeature;
|
||||
import net.minecraftforge.forgespi.locating.IModFile;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
import static net.minecraftforge.fml.Logging.CORE;
|
||||
import static net.minecraftforge.fml.Logging.LOADING;
|
||||
|
||||
/**
|
||||
* Loads mods.
|
||||
*
|
||||
* Dispatch cycle is seen in {@code #loadMods()} and {@code #finishMods()}
|
||||
*
|
||||
* Overall sequence for loadMods is:
|
||||
* <dl>
|
||||
* <dt>CONSTRUCT</dt>
|
||||
* <dd>Constructs the mod instance. Mods can typically setup basic environment such as Event listeners
|
||||
* and Configuration specifications here.</dd>
|
||||
* <dt>Automated dispatches</dt>
|
||||
* <dd>Dispatches automated elements : {@code net.minecraftforge.fml.common.Mod.EventBusSubscriber},
|
||||
* {@code net.minecraftforge.event.RegistryEvent}, {@code net.minecraftforge.common.capabilities.CapabilityInject}
|
||||
* and others</dd>
|
||||
* <dt>CONFIG_LOAD</dt>
|
||||
* <dd>Dispatches ConfigLoadEvent to mods</dd>
|
||||
* <dt>COMMON_SETUP</dt>
|
||||
* <dd>Dispatches {@code net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent} to mods</dd>
|
||||
* <dt>SIDED_SETUP</dt>
|
||||
* <dd>Dispatches {@code net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent} or
|
||||
* {@code net.minecraftforge.fml.event.lifecycle.FMLDedicatedServerSetupEvent} to mods</dd>
|
||||
* </dl>
|
||||
*
|
||||
* Overall sequence for finishMods is:
|
||||
* <dl>
|
||||
* <dt>ENQUEUE_IMC</dt>
|
||||
* <dd>Dispatches {@code net.minecraftforge.fml.event.lifecycle.InterModEnqueueEvent} to mods,
|
||||
* for enqueuing {@link InterModComms} messages for other mods to receive subsequently</dd>
|
||||
* <dt>PROCESS_IMC</dt>
|
||||
* <dd>Dispatches {@code net.minecraftforge.fml.event.lifecycle.InterModProcessEvent} to mods,
|
||||
* for processing {@link InterModComms} messages received from other mods prior to this event</dd>
|
||||
* <dt>COMPLETE</dt>
|
||||
* <dd>Dispatches {@code net.minecraftforge.fml.event.lifecycle.FMLLoadCompleteEvent} to mods,
|
||||
* and completes the mod loading sequence.</dd>
|
||||
* </dl>
|
||||
*/
|
||||
public final class ModLoader {
|
||||
private ModLoader() {}
|
||||
|
||||
private static final Logger LOGGER = LogManager.getLogger();
|
||||
private static final ArrayList<ModLoadingException> LOADING_EXCEPTIONS = new ArrayList<>();
|
||||
private static final ArrayList<ModLoadingWarning> LOADING_WARNINGS = new ArrayList<>();
|
||||
private static final Consumer<String> STATUS_CONSUMER = StartupNotificationManager.modLoaderConsumer().orElse(_ -> {});
|
||||
private static final HashSet<IModLoadingState> COMPLETED_STATES = new HashSet<>();
|
||||
private static boolean loadingStateValid;
|
||||
|
||||
private static String computeLanguageList() {
|
||||
return "\n" + LanguageLoadingProvider
|
||||
.applyForEach(lp -> lp.name() + '@' + lp.getClass().getPackage().getImplementationVersion())
|
||||
.collect(Collectors.joining("\n\t\t", "\t\t", ""));
|
||||
}
|
||||
|
||||
private static String computeModLauncherServiceList() {
|
||||
final List<Map<String, String>> mods = FMLLoader.modLauncherModList();
|
||||
return "\n" + mods.stream().map(mod -> mod.getOrDefault("file","nofile") +
|
||||
' ' + mod.getOrDefault("name", "missing") +
|
||||
' ' + mod.getOrDefault("type","NOTYPE") +
|
||||
' ' + mod.getOrDefault("description", "")).
|
||||
collect(Collectors.joining("\n\t\t","\t\t",""));
|
||||
}
|
||||
|
||||
/**
|
||||
* Run on the primary starting thread by ClientModLoader and ServerModLoader
|
||||
* @param syncExecutor An executor to run tasks on the main thread
|
||||
* @param parallelExecutor An executor to run tasks on a parallel loading thread pool
|
||||
* @param periodicTask Optional periodic task to perform on the main thread while other activities run
|
||||
*/
|
||||
public static void gatherAndInitializeMods(final ModWorkManager.DrivenExecutor syncExecutor, final Executor parallelExecutor, final Runnable periodicTask) {
|
||||
var loadingExceptions = LoadingModList.getErrors().stream()
|
||||
.flatMap(ModLoadingException::fromEarlyException)
|
||||
.toList();
|
||||
ModLoader.LOADING_EXCEPTIONS.addAll(loadingExceptions);
|
||||
LOADING_WARNINGS.addAll(LoadingModList.getBrokenFiles().stream()
|
||||
.map(file -> new ModLoadingWarning(null, ModLoadingStage.VALIDATE, InvalidModIdentifier.identifyJarProblem(file.getFilePath()).orElse("fml.modloading.brokenfile"), file.getFileName()))
|
||||
.toList());
|
||||
Set<IModInfo> erroredModInfos;
|
||||
if (loadingExceptions.isEmpty()) {
|
||||
erroredModInfos = Collections.emptySet();
|
||||
} else {
|
||||
erroredModInfos = Collections.newSetFromMap(new IdentityHashMap<>());
|
||||
erroredModInfos.addAll(loadingExceptions.stream().map(ModLoadingException::getModInfo).toList());
|
||||
}
|
||||
LoadingModList.getModFiles().stream()
|
||||
.filter(ModFileInfo::missingLicense)
|
||||
.filter(modFileInfo -> modFileInfo.getMods().stream().noneMatch(erroredModInfos::contains)) //Ignore files where any other mod already encountered an error
|
||||
.map(modFileInfo -> new ModLoadingException(null, ModLoadingStage.VALIDATE, "fml.modloading.missinglicense", null, modFileInfo.getFile()))
|
||||
.forEach(LOADING_EXCEPTIONS::add);
|
||||
CrashReportCallables.registerCrashCallable("ModLauncher", FMLLoader::getLauncherInfo);
|
||||
CrashReportCallables.registerCrashCallable("ModLauncher launch target", FMLLoader::launcherHandlerName);
|
||||
CrashReportCallables.registerCrashCallable("ModLauncher naming", FMLLoader::getNaming);
|
||||
CrashReportCallables.registerCrashCallable("ModLauncher services", ModLoader::computeModLauncherServiceList);
|
||||
CrashReportCallables.registerCrashCallable("FML Language Providers", ModLoader::computeLanguageList);
|
||||
|
||||
ForgeFeature.registerFeature("javaVersion", ForgeFeature.VersionFeatureTest.forVersionString(IModInfo.DependencySide.BOTH, System.getProperty("java.version")));
|
||||
ForgeFeature.registerFeature("openGLVersion", ForgeFeature.VersionFeatureTest.forVersionString(IModInfo.DependencySide.CLIENT, ImmediateWindowHandler.getGLVersion()));
|
||||
loadingStateValid = true;
|
||||
FMLLoader.backgroundScanHandler.waitForScanToComplete(periodicTask);
|
||||
if (!LOADING_EXCEPTIONS.isEmpty()) {
|
||||
LOGGER.fatal(CORE, "Error during pre-loading phase", LOADING_EXCEPTIONS.getFirst());
|
||||
STATUS_CONSUMER.accept("ERROR DURING MOD LOADING");
|
||||
ModList.clearLoadedMods();
|
||||
loadingStateValid = false;
|
||||
throw new LoadingFailedException(LOADING_EXCEPTIONS);
|
||||
}
|
||||
var failedBounds = new ArrayList<ForgeFeature.Bound>();
|
||||
for (var mod : LoadingModList.getMods()) {
|
||||
for (var feature : mod.getForgeFeatures()) {
|
||||
if (!ForgeFeature.testFeature(FMLEnvironment.dist, feature))
|
||||
failedBounds.add(feature);
|
||||
}
|
||||
}
|
||||
|
||||
if (!failedBounds.isEmpty()) {
|
||||
LOGGER.fatal(CORE, "Failed to validate feature bounds for mods: {}", failedBounds);
|
||||
STATUS_CONSUMER.accept("ERROR DURING MOD LOADING");
|
||||
ModList.clearLoadedMods();
|
||||
loadingStateValid = false;
|
||||
throw new LoadingFailedException(failedBounds.stream()
|
||||
.map(fb -> new ModLoadingException(fb.modInfo(), ModLoadingStage.CONSTRUCT, "fml.modloading.feature.missing", null, fb, ForgeFeature.featureValue(fb)))
|
||||
.toList());
|
||||
}
|
||||
|
||||
final var modContainers = new HashMap<String, ModContainer>();
|
||||
for (var file : LoadingModList.getModFiles()) {
|
||||
var containers = buildMods(file.getFile());
|
||||
for (var container : containers)
|
||||
modContainers.put(container.getModId(), container);
|
||||
}
|
||||
|
||||
if (!LOADING_EXCEPTIONS.isEmpty()) {
|
||||
LOGGER.fatal(CORE, "Failed to initialize mod containers", LOADING_EXCEPTIONS.getFirst());
|
||||
STATUS_CONSUMER.accept("ERROR DURING MOD LOADING");
|
||||
ModList.clearLoadedMods();
|
||||
loadingStateValid = false;
|
||||
throw new LoadingFailedException(LOADING_EXCEPTIONS);
|
||||
}
|
||||
|
||||
// Gather all dependencies, so we can make sure they have finished their transition events before we fire ours
|
||||
for (var mod : modContainers.values()) {
|
||||
for (var dep : mod.getModInfo().getDependencies()) {
|
||||
var target = modContainers.get(dep.getModId());
|
||||
if (target == null)
|
||||
continue;
|
||||
|
||||
switch (dep.getOrdering()) {
|
||||
case AFTER:
|
||||
mod.dependencies.add(target);
|
||||
break;
|
||||
case BEFORE:
|
||||
target.dependencies.add(mod);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ModList.setLoadedMods(modContainers.values().stream().toList());
|
||||
var stateList = ModStateManager.getStates(ModLoadingPhase.GATHER);
|
||||
var progress = StartupMessageManager.addProgressBar("Mod Gather", stateList.stream().mapToInt(mls -> mls.size().getAsInt()).sum());
|
||||
for (IModLoadingState mls : stateList) {
|
||||
dispatchAndHandleError(mls, syncExecutor, parallelExecutor, periodicTask, progress);
|
||||
}
|
||||
progress.complete();
|
||||
}
|
||||
|
||||
public static void loadMods(final ModWorkManager.DrivenExecutor syncExecutor, final Executor parallelExecutor, final Runnable periodicTask) {
|
||||
var stateList = ModStateManager.getStates(ModLoadingPhase.LOAD);
|
||||
var progress = StartupMessageManager.addProgressBar("Mod Loading", stateList.stream().mapToInt(mls -> mls.size().getAsInt()).sum());
|
||||
for (IModLoadingState mls : stateList) {
|
||||
dispatchAndHandleError(mls, syncExecutor, parallelExecutor, periodicTask, progress);
|
||||
}
|
||||
progress.complete();
|
||||
}
|
||||
|
||||
public static void finishMods(final ModWorkManager.DrivenExecutor syncExecutor, final Executor parallelExecutor, final Runnable periodicTask) {
|
||||
var stateList = ModStateManager.getStates(ModLoadingPhase.COMPLETE);
|
||||
var progress = StartupMessageManager.addProgressBar("Mod Complete", stateList.stream().mapToInt(mls -> mls.size().getAsInt()).sum());
|
||||
for (IModLoadingState mls : stateList) {
|
||||
dispatchAndHandleError(mls, syncExecutor, parallelExecutor, periodicTask, progress);
|
||||
}
|
||||
|
||||
var modBusGroups = Set.of(
|
||||
ModList.getLoadedMods().stream()
|
||||
.map(ModContainer::getModBusGroup)
|
||||
.filter(Objects::nonNull)
|
||||
.toArray(BusGroup[]::new)
|
||||
);
|
||||
for (var modBusGroup : modBusGroups) {
|
||||
parallelExecutor.execute(modBusGroup::trim);
|
||||
}
|
||||
parallelExecutor.execute(BusGroup.DEFAULT::trim);
|
||||
|
||||
STATUS_CONSUMER.accept("Mod loading complete - %d mods loaded".formatted(ModList.size()));
|
||||
progress.complete();
|
||||
}
|
||||
|
||||
private static void dispatchAndHandleError(IModLoadingState state, ModWorkManager.DrivenExecutor syncExecutor, Executor parallelExecutor, final Runnable ticker, final ProgressMeter progressBar) {
|
||||
if (!isLoadingStateValid()) {
|
||||
LOGGER.error("Cowardly refusing to process mod state change request from {}", state);
|
||||
return;
|
||||
}
|
||||
progressBar.label(progressBar.name() + " working");
|
||||
syncExecutor.drive(ticker);
|
||||
|
||||
var inlineRunnable = state.inlineRunnable();
|
||||
if (inlineRunnable != null) handleInlineTransition(inlineRunnable, state, syncExecutor, ticker);
|
||||
|
||||
var transition = state.buildTransition(syncExecutor, parallelExecutor, progressBar);
|
||||
if (transition != null) waitForTransition(state, syncExecutor, ticker, transition);
|
||||
|
||||
COMPLETED_STATES.add(state);
|
||||
}
|
||||
|
||||
private static void handleInlineTransition(final Runnable transition, final IModLoadingState state, final ModWorkManager.DrivenExecutor syncExecutor, final Runnable ticker) {
|
||||
var pb = StartupMessageManager.addProgressBar("State transition " + state.name() + " running", 0);
|
||||
syncExecutor.drive(ticker);
|
||||
transition.run();
|
||||
syncExecutor.drive(ticker);
|
||||
pb.complete();
|
||||
syncExecutor.drive(ticker);
|
||||
}
|
||||
|
||||
private static void waitForTransition(final IModLoadingState state, final ModWorkManager.DrivenExecutor syncExecutor, final Runnable ticker, final CompletableFuture<Void> transition) {
|
||||
while (!transition.isDone()) {
|
||||
syncExecutor.drive(ticker);
|
||||
}
|
||||
|
||||
try {
|
||||
transition.join();
|
||||
} catch (CompletionException e) {
|
||||
loadingStateValid = false;
|
||||
Throwable t = e.getCause();
|
||||
boolean hasNotModLoadingEx = Arrays.stream(t.getSuppressed())
|
||||
.anyMatch(obj -> !(obj instanceof ModLoadingException));
|
||||
if (hasNotModLoadingEx) {
|
||||
LOGGER.fatal("Encountered non-modloading exceptions!", e);
|
||||
STATUS_CONSUMER.accept("ERROR DURING MOD LOADING");
|
||||
throw e;
|
||||
}
|
||||
|
||||
final List<ModLoadingException> modLoadingExceptions = Arrays.stream(t.getSuppressed())
|
||||
.filter(ModLoadingException.class::isInstance)
|
||||
.map(ModLoadingException.class::cast)
|
||||
.toList();
|
||||
LOGGER.fatal(LOADING,"Failed to complete lifecycle event {}, {} errors found", state.name(), modLoadingExceptions.size());
|
||||
STATUS_CONSUMER.accept("ERROR DURING MOD LOADING");
|
||||
throw new LoadingFailedException(modLoadingExceptions);
|
||||
}
|
||||
}
|
||||
|
||||
private static List<ModContainer> buildMods(final IModFile modFile) {
|
||||
final Map<String, IModInfo> modInfoMap = new HashMap<>();
|
||||
for (var mod : modFile.getModFileInfo().getMods())
|
||||
modInfoMap.put(mod.getModId(), mod);
|
||||
|
||||
LOGGER.trace(LOADING, "ModContainer is {}", ModContainer.class.getClassLoader());
|
||||
final List<ModContainer> containers = new ArrayList<>();
|
||||
for (var entry : modFile.getScanResult().getTargets().entrySet()) {
|
||||
var container = buildModContainerFromTOML(modFile, modInfoMap, entry.getKey(), entry.getValue());
|
||||
if (container != null)
|
||||
containers.add(container);
|
||||
}
|
||||
|
||||
if (containers.size() != modInfoMap.size()) {
|
||||
var modIds = modInfoMap.values().stream().map(IModInfo::getModId).sorted().toList();
|
||||
var containerIds = containers.stream().map(c -> c != null ? c.getModId() : "(null)").sorted().toList();
|
||||
|
||||
LOGGER.fatal(LOADING, "File {} constructed {} mods: {}, but had {} mods specified: {}",
|
||||
modFile.getFilePath(),
|
||||
containers.size(), containerIds,
|
||||
modInfoMap.size(), modIds);
|
||||
|
||||
var missingClasses = new ArrayList<>(modIds);
|
||||
missingClasses.removeAll(containerIds);
|
||||
LOGGER.fatal(LOADING, "The following classes are missing, but are reported in the mods.toml: {}", missingClasses);
|
||||
|
||||
var missingMods = new ArrayList<>(containerIds);
|
||||
missingMods.removeAll(modIds);
|
||||
LOGGER.fatal(LOADING, "The following mods are missing, but have classes in the jar: {}", missingMods);
|
||||
|
||||
LOADING_EXCEPTIONS.add(new ModLoadingException(null, ModLoadingStage.CONSTRUCT, "fml.modloading.missingclasses", null, modFile.getFilePath()));
|
||||
}
|
||||
|
||||
// remove errored mod containers
|
||||
return containers.stream().filter(mc -> mc.modLoadingStage != ModLoadingStage.ERROR).toList();
|
||||
}
|
||||
|
||||
private static ModContainer buildModContainerFromTOML(final IModFile modFile, final Map<String, IModInfo> modInfoMap,
|
||||
final String modId, final IModLanguageProvider.IModLanguageLoader languageLoader
|
||||
) {
|
||||
try {
|
||||
IModInfo info = modInfoMap.get(modId);
|
||||
// throw a missing metadata error if there is no matching modid in the modInfoMap from the mods.toml file
|
||||
if (info == null)
|
||||
throw new ModLoadingException(null, ModLoadingStage.CONSTRUCT, "fml.modloading.missingmetadata", null, modId);
|
||||
|
||||
return languageLoader.loadMod(info, modFile.getScanResult(), FMLLoader.getGameLayer());
|
||||
} catch (ModLoadingException mle) {
|
||||
// exceptions are caught and added to the error list for later handling
|
||||
LOADING_EXCEPTIONS.add(mle);
|
||||
// return an errored container instance here, because we tried and failed building a container.
|
||||
return new ErroredModContainer();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return If the current mod loading state is valid. Use if you interact with vanilla systems directly during loading
|
||||
* and don't want to cause extraneous crashes due to trying to do things that aren't possible in a "broken load"
|
||||
*/
|
||||
public static boolean isLoadingStateValid() {
|
||||
return loadingStateValid;
|
||||
}
|
||||
|
||||
public static boolean hasCompletedState(IModLoadingState state) {
|
||||
return COMPLETED_STATES.contains(state);
|
||||
}
|
||||
|
||||
public static <T extends IModBusEvent> void runEventGenerator(Function<ModContainer, T> generator) {
|
||||
if (!loadingStateValid) {
|
||||
LOGGER.error("Cowardly refusing to send event generator to a broken mod state");
|
||||
return;
|
||||
}
|
||||
for (var mod : ModList.getLoadedMods())
|
||||
mod.acceptEvent(generator.apply(mod));
|
||||
}
|
||||
|
||||
public static <T extends IModBusEvent> void postEvent(T e) {
|
||||
if (!loadingStateValid) {
|
||||
LOGGER.error("Cowardly refusing to send event {} to a broken mod state", e.getClass().getName());
|
||||
return;
|
||||
}
|
||||
for (var mod : ModList.getLoadedMods())
|
||||
mod.acceptEvent(e);
|
||||
}
|
||||
|
||||
public static <T extends IModBusEvent> void postEvent(ModContainer mod, T e) {
|
||||
mod.acceptEvent(e);
|
||||
}
|
||||
|
||||
public static <T extends IModBusEvent> T postEventWithReturn(T e) {
|
||||
if (!loadingStateValid) {
|
||||
LOGGER.error("Cowardly refusing to send event {} to a broken mod state", e.getClass().getName());
|
||||
return e;
|
||||
}
|
||||
for (var mod : ModList.getLoadedMods())
|
||||
mod.acceptEvent(e);
|
||||
return e;
|
||||
}
|
||||
|
||||
@SuppressWarnings("removal")
|
||||
public static <T extends IModBusEvent> void postEventWrapContainerInModOrder(T event) {
|
||||
postEventWithWrapInModOrder(event,
|
||||
(mc, _) -> ModLoadingContext.get().setActiveContainer(mc),
|
||||
(_, _) -> ModLoadingContext.get().setActiveContainer(null)
|
||||
);
|
||||
}
|
||||
|
||||
public static <T extends IModBusEvent> void postEventWithWrapInModOrder(T e, BiConsumer<ModContainer, T> pre, BiConsumer<ModContainer, T> post) {
|
||||
if (!loadingStateValid) {
|
||||
LOGGER.error("Cowardly refusing to send event {} to a broken mod state", e.getClass().getName());
|
||||
return;
|
||||
}
|
||||
for (var mod : ModList.getLoadedMods()) {
|
||||
pre.accept(mod, e);
|
||||
mod.acceptEvent(e);
|
||||
post.accept(mod, e);
|
||||
}
|
||||
}
|
||||
|
||||
public static List<ModLoadingWarning> getWarnings() {
|
||||
return List.copyOf(LOADING_WARNINGS);
|
||||
}
|
||||
|
||||
public static void addWarning(ModLoadingWarning warning) {
|
||||
LOADING_WARNINGS.add(warning);
|
||||
}
|
||||
|
||||
private static boolean runningDataGen = false;
|
||||
|
||||
public static boolean isDataGenRunning () {
|
||||
return runningDataGen;
|
||||
}
|
||||
|
||||
private static final class ErroredModContainer extends ModContainer {
|
||||
public ErroredModContainer() {
|
||||
super();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean matches(final Object mod) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getMod() {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,126 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
import com.mojang.logging.LogUtils;
|
||||
import net.minecraftforge.fml.config.IConfigSpec;
|
||||
import net.minecraftforge.fml.config.ModConfig;
|
||||
import org.slf4j.Logger;
|
||||
import java.util.function.BiPredicate;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public class ModLoadingContext {
|
||||
private static final Logger LOGGER = LogUtils.getLogger();
|
||||
private static final ThreadLocal<ModLoadingContext> context = ThreadLocal.withInitial(ModLoadingContext::new);
|
||||
private ModContainer activeContainer;
|
||||
private Object languageExtension;
|
||||
|
||||
/**
|
||||
* @deprecated Use the context provided by your language loader in your mod's constructor. Example for Java mods: {@snippet :
|
||||
* @Mod("examplemod")
|
||||
* public final class ExampleMod {
|
||||
* public ExampleMod(FMLJavaModLoadingContext context) {
|
||||
* // Use context from the param instead of FMLJavaModLoadingContext.get() or ModLoadingContext.get()
|
||||
* }
|
||||
* }}
|
||||
*/
|
||||
@Deprecated(forRemoval = true, since="1.21.1")
|
||||
public static ModLoadingContext get() {
|
||||
return context.get();
|
||||
}
|
||||
|
||||
void setActiveContainer(final ModContainer container) {
|
||||
this.activeContainer = container;
|
||||
this.languageExtension = container == null ? null : container.contextExtension.get();
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Going to be moved to ForgeHooks for Internal use.
|
||||
*/
|
||||
@Deprecated(forRemoval = true, since="1.21.1")
|
||||
public String getActiveNamespace() {
|
||||
return activeContainer == null ? "minecraft" : activeContainer.getNamespace();
|
||||
}
|
||||
|
||||
public ModContainer getContainer() {
|
||||
return activeContainer == null
|
||||
? ModList.getModContainerById("minecraft").orElseThrow(()->new RuntimeException("Where is minecraft???!"))
|
||||
: activeContainer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Register an {@link IExtensionPoint} with the mod container.
|
||||
* @param point The extension point to register
|
||||
* @param extension An extension operator
|
||||
* @param <T> The type signature of the extension operator
|
||||
*/
|
||||
public <T extends Record & IExtensionPoint<T>> void registerExtensionPoint(Class<? extends IExtensionPoint<T>> point, Supplier<T> extension) {
|
||||
getContainer().registerExtensionPoint(point, extension);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a {@link IExtensionPoint.DisplayTest} with the mod container.
|
||||
* <p>A shorthand for registering a DisplayTest with {@link #registerExtensionPoint(Class, Supplier)}.</p>
|
||||
* @param displayTest The {@link IExtensionPoint.DisplayTest} to register
|
||||
*/
|
||||
public void registerDisplayTest(IExtensionPoint.DisplayTest displayTest) {
|
||||
getContainer().registerDisplayTest(() -> displayTest);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a {@link IExtensionPoint.DisplayTest} with the mod container.
|
||||
* <p>A shorthand for registering a DisplayTest supplier with {@link #registerExtensionPoint(Class, Supplier)}.</p>
|
||||
* @param displayTest The {@link Supplier<IExtensionPoint.DisplayTest>} to register
|
||||
*/
|
||||
public void registerDisplayTest(Supplier<IExtensionPoint.DisplayTest> displayTest) {
|
||||
getContainer().registerDisplayTest(displayTest);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a {@link IExtensionPoint.DisplayTest} with the mod container.
|
||||
* <p>A shorthand for registering a DisplayTest with {@link #registerExtensionPoint(Class, Supplier)} that also
|
||||
* creates the DisplayTest instance for you using the provided parameters.</p>
|
||||
* @see IExtensionPoint.DisplayTest#DisplayTest(String, BiPredicate)
|
||||
*/
|
||||
public void registerDisplayTest(String version, BiPredicate<String, Boolean> remoteVersionTest) {
|
||||
getContainer().registerDisplayTest(new IExtensionPoint.DisplayTest(version, remoteVersionTest));
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a {@link IExtensionPoint.DisplayTest} with the mod container.
|
||||
* <p>A shorthand for registering a DisplayTest with {@link #registerExtensionPoint(Class, Supplier)} that also
|
||||
* creates the DisplayTest instance for you using the provided parameters.</p>
|
||||
* @see IExtensionPoint.DisplayTest#DisplayTest(Supplier, BiPredicate)
|
||||
*/
|
||||
public void registerDisplayTest(Supplier<String> suppliedVersion, BiPredicate<String, Boolean> remoteVersionTest) {
|
||||
getContainer().registerDisplayTest(new IExtensionPoint.DisplayTest(suppliedVersion, remoteVersionTest));
|
||||
}
|
||||
|
||||
public void registerConfig(ModConfig.Type type, IConfigSpec<?> spec) {
|
||||
if (spec.isEmpty()) {
|
||||
// This handles the case where a mod tries to register a config, without any options configured inside it.
|
||||
LOGGER.debug("Attempted to register an empty config for type {} on mod {}", type, getContainer().getModId());
|
||||
return;
|
||||
}
|
||||
|
||||
getContainer().addConfig(new ModConfig(type, spec, getContainer()));
|
||||
}
|
||||
|
||||
public void registerConfig(ModConfig.Type type, IConfigSpec<?> spec, String fileName) {
|
||||
if (spec.isEmpty()) {
|
||||
// This handles the case where a mod tries to register a config, without any options configured inside it.
|
||||
LOGGER.debug("Attempted to register an empty config for type {} on mod {} using file name {}", type, getContainer().getModId(), fileName);
|
||||
return;
|
||||
}
|
||||
|
||||
getContainer().addConfig(new ModConfig(type, spec, getContainer(), fileName));
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T> T extension() {
|
||||
return (T)languageExtension;
|
||||
}
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
import com.google.common.collect.Streams;
|
||||
import net.minecraftforge.fml.loading.EarlyLoadingException;
|
||||
import net.minecraftforge.forgespi.language.IModInfo;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* General purpose mod loading error message
|
||||
*/
|
||||
public class ModLoadingException extends RuntimeException
|
||||
{
|
||||
private static final long serialVersionUID = 2048947398536935507L;
|
||||
/**
|
||||
* Mod Info for mod with issue
|
||||
*/
|
||||
private final IModInfo modInfo;
|
||||
/**
|
||||
* The stage where this error was encountered
|
||||
*/
|
||||
private final ModLoadingStage errorStage;
|
||||
|
||||
/**
|
||||
* I18N message to use for display
|
||||
*/
|
||||
private final String i18nMessage;
|
||||
|
||||
/**
|
||||
* Context for message display
|
||||
*/
|
||||
private final List<Object> context;
|
||||
|
||||
public ModLoadingException(final IModInfo modInfo, final ModLoadingStage errorStage, final String i18nMessage, final Throwable originalException, Object... context) {
|
||||
super("Mod Loading Exception", originalException);
|
||||
this.modInfo = modInfo;
|
||||
this.errorStage = errorStage;
|
||||
this.i18nMessage = i18nMessage;
|
||||
this.context = Arrays.asList(context);
|
||||
}
|
||||
|
||||
static Stream<ModLoadingException> fromEarlyException(final EarlyLoadingException e) {
|
||||
return e.getAllData().stream().map(ed->new ModLoadingException(ed.getModInfo(), ModLoadingStage.VALIDATE, ed.getI18message(), e.getCause(), ed.getArgs()));
|
||||
}
|
||||
|
||||
public String getI18NMessage() {
|
||||
return i18nMessage;
|
||||
}
|
||||
|
||||
public Object[] getContext() {
|
||||
return context.toArray();
|
||||
}
|
||||
|
||||
public String formatToString() {
|
||||
return Bindings.getMessageParser().get().parseMessage(i18nMessage, Streams.concat(Stream.of(modInfo, errorStage, getCause()), context.stream()).toArray());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getMessage() {
|
||||
return formatToString();
|
||||
}
|
||||
|
||||
public IModInfo getModInfo() {
|
||||
return modInfo;
|
||||
}
|
||||
public String getCleanMessage() {
|
||||
return Bindings.getMessageParser().get().stripControlCodes(formatToString());
|
||||
}
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
/**
|
||||
* Phases of mod loading, for grouping mod loading states.
|
||||
*/
|
||||
public enum ModLoadingPhase {
|
||||
/**
|
||||
* Special phase for exceptional situations and error handling, where mod loading cannot continue normally.
|
||||
*
|
||||
* <p>There is conventionally only one state with this phase.</p>
|
||||
*/
|
||||
ERROR, // Special state for error handling
|
||||
/**
|
||||
* Phase for discovering and gathering mods for loading.
|
||||
*/
|
||||
GATHER,
|
||||
/**
|
||||
* Phase for the loading of mods found from mod discovery.
|
||||
*
|
||||
* @see #GATHER
|
||||
*/
|
||||
LOAD,
|
||||
/**
|
||||
* Phase after mod loading has completed, for post-loading tasks.
|
||||
*
|
||||
* @see #LOAD
|
||||
*/
|
||||
COMPLETE,
|
||||
/**
|
||||
* Marker phase for the last state in the full mod loading process.
|
||||
*/
|
||||
DONE
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
/**
|
||||
* Mod loading stage of mod containers during the mod loading process. These will have a corresponding {@link ModLoadingState}
|
||||
* in the basic mod loading process provided by FML.
|
||||
*
|
||||
* <p>Each mod loading stage has a global {@link DeferredWorkQueue}, which is populated during the execution of the state
|
||||
* associated with this stage and emptied at the end of the state's execution.</p>
|
||||
*/
|
||||
public enum ModLoadingStage
|
||||
{
|
||||
/**
|
||||
* Special stage for exceptional situations and error handling.
|
||||
*/
|
||||
ERROR,
|
||||
/**
|
||||
* Validation of the mod list.
|
||||
* TODO: figure out where this is used and why this exists instead of CONSTRUCT being the first normal stage
|
||||
*/
|
||||
VALIDATE,
|
||||
/**
|
||||
* Default stage of mod containers after construction.
|
||||
*/
|
||||
CONSTRUCT,
|
||||
/**
|
||||
* Common (non-side-specific) setup and initialization.
|
||||
*/
|
||||
COMMON_SETUP,
|
||||
/**
|
||||
* Side-specific setup and initialization.
|
||||
*
|
||||
* @see net.minecraftforge.api.distmarker.Dist
|
||||
*/
|
||||
SIDED_SETUP,
|
||||
/**
|
||||
* Stage for enqueuing {@link net.minecraftforge.fml.InterModComms} messages for later processing.
|
||||
*/
|
||||
ENQUEUE_IMC,
|
||||
/**
|
||||
* Stage for processing received messages though {@link net.minecraftforge.fml.InterModComms}.
|
||||
*/
|
||||
PROCESS_IMC,
|
||||
/**
|
||||
* Marks the completion of mod loading for this container.
|
||||
*/
|
||||
COMPLETE,
|
||||
/**
|
||||
* Marks the completion of the full mod loading process.
|
||||
*/
|
||||
DONE;
|
||||
|
||||
private final DeferredWorkQueue deferredWorkQueue;
|
||||
|
||||
ModLoadingStage() {
|
||||
deferredWorkQueue = new DeferredWorkQueue(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@return the next stage after this stage, or {@link #ERROR} if the exception is not {@code null}}
|
||||
*
|
||||
* @param exception the exception that occurred during this stage, may be {@code null}
|
||||
*/
|
||||
ModLoadingStage nextState(Throwable exception) {
|
||||
return exception != null ? ERROR : values()[this.ordinal()+1];
|
||||
}
|
||||
|
||||
/**
|
||||
* {@return this stage, or {@link #ERROR} if the exception is not {@code null}}
|
||||
*
|
||||
* @param exception the exception that occurred during this stage, may be {@code null}
|
||||
*/
|
||||
public ModLoadingStage currentState(Throwable exception) {
|
||||
return exception != null ? ERROR : this;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@return the deferred work queue for this stage}
|
||||
*/
|
||||
public DeferredWorkQueue getDeferredWorkQueue() {
|
||||
return deferredWorkQueue;
|
||||
}
|
||||
}
|
||||
@@ -1,181 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
import net.minecraftforge.fml.loading.progress.ProgressMeter;
|
||||
import org.jspecify.annotations.NullMarked;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.IntSupplier;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* Implementation of the {@link IModLoadingState} interface.
|
||||
*
|
||||
* @param name the name of this state
|
||||
* @param previous the name of the state immediately previous to this state
|
||||
* @param message a function returning a human-friendly message for this state
|
||||
* @param phase the mod loading phase this state belongs to
|
||||
* @param inlineRunnable an optional runnable, which runs before starting the transition from this state to the next
|
||||
* @param transition optional state transition information
|
||||
*/
|
||||
@NullMarked
|
||||
public record ModLoadingState(
|
||||
String name,
|
||||
String previous,
|
||||
Supplier<String> message,
|
||||
IntSupplier size,
|
||||
ModLoadingPhase phase,
|
||||
@Nullable Runnable inlineRunnable,
|
||||
@Nullable IModStateTransition transition
|
||||
) implements IModLoadingState {
|
||||
@Override
|
||||
public @Nullable CompletableFuture<Void> buildTransition(
|
||||
final Executor syncExecutor,
|
||||
final Executor parallelExecutor,
|
||||
final ProgressMeter progressBar,
|
||||
final Function<Executor, CompletableFuture<Void>> preSyncTask,
|
||||
final Function<Executor, CompletableFuture<Void>> postSyncTask
|
||||
) {
|
||||
if (transition == null) return null;
|
||||
return transition.build(name, syncExecutor, parallelExecutor, progressBar, preSyncTask, postSyncTask);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@return an empty mod loading state} The mod loading state has a blank human-readable message, no inline runnable,
|
||||
* and no state transition information.
|
||||
*
|
||||
* @param name the name of the state
|
||||
* @param previous the name of the immediately previous state to this state
|
||||
* @param phase the mod loading phase the state belongs to
|
||||
*
|
||||
* @deprecated Use the builder
|
||||
*/
|
||||
@Deprecated(since = "1.21.3", forRemoval = true)
|
||||
public static ModLoadingState empty(final String name, final String previous, final ModLoadingPhase phase) {
|
||||
return new ModLoadingState(name, previous, () -> "", () -> 0, phase, null, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a mod loading state with state transition information and a default human-friendly message of
|
||||
* {@code Processing transition [name]}.
|
||||
*
|
||||
* @param name the name of the state
|
||||
* @param previous the name of the immediately previous state to this state
|
||||
* @param phase the mod loading phase the state belongs to
|
||||
* @param transition the state transition information
|
||||
*
|
||||
* @deprecated Use the builder
|
||||
*/
|
||||
@Deprecated(since = "1.21.3", forRemoval = true)
|
||||
public static ModLoadingState withTransition(final String name, final String previous, final ModLoadingPhase phase,
|
||||
final IModStateTransition transition) {
|
||||
return of(name, phase).after(previous).withTransition(transition);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a mod loading state with state transition information and a custom human-friendly message function.
|
||||
*
|
||||
* @param name the name of the state
|
||||
* @param previous the name of the immediately previous state to this state
|
||||
* @param message a function returning a human-friendly message for this state
|
||||
* @param phase the mod loading phase the state belongs to
|
||||
* @param transition the state transition information
|
||||
* @return a mod loading state with state transition information and a custom message
|
||||
*
|
||||
* @deprecated Use the builder
|
||||
*/
|
||||
@Deprecated(since = "1.21.3", forRemoval = true)
|
||||
public static ModLoadingState withTransition(final String name, final String previous,
|
||||
final Supplier<String> message, final ModLoadingPhase phase,
|
||||
final IModStateTransition transition) {
|
||||
return of(name, phase).after(previous).message(message).withTransition(transition);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a mod loading state with an inline runnable and a default human-friendly message of {@code Processing
|
||||
* work [name]}.
|
||||
*
|
||||
* @param name the name of the state
|
||||
* @param previous the name of the immediately previous state to this state
|
||||
* @param phase the mod loading phase the state belongs to
|
||||
* @param inline an optional runnable, which runs before starting the transition from this state to the next
|
||||
* @return a mod loading state with an inline runnable and default message
|
||||
*
|
||||
* @deprecated Use the builder
|
||||
*/
|
||||
@Deprecated(since = "1.21.3", forRemoval = true)
|
||||
public static ModLoadingState withInline(final String name, final String previous, final ModLoadingPhase phase,
|
||||
final Runnable inline) {
|
||||
return of(name, phase).after(previous).withInline(inline);
|
||||
}
|
||||
|
||||
public static Builder of(final String name, final ModLoadingPhase phase) {
|
||||
return new Builder(name, phase);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
return o instanceof ModLoadingState that
|
||||
&& this.phase == that.phase
|
||||
&& this.name.equals(that.name)
|
||||
&& this.previous.equals(that.previous);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int result = phase.hashCode();
|
||||
result = 31 * result + name.hashCode();
|
||||
result = 31 * result + previous.hashCode();
|
||||
return result;
|
||||
}
|
||||
|
||||
public static final class Builder {
|
||||
private final String name;
|
||||
private final ModLoadingPhase phase;
|
||||
private String after = "";
|
||||
private @Nullable Supplier<String> message = null;
|
||||
private @Nullable IntSupplier size = null;
|
||||
|
||||
private Builder(final String name, final ModLoadingPhase phase) {
|
||||
this.name = name;
|
||||
this.phase = phase;
|
||||
}
|
||||
|
||||
public Builder after(final ModLoadingState value) { return after(value.name()); }
|
||||
public Builder after(final String value) {
|
||||
this.after = value;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder message(final String value) { return message(() -> value); }
|
||||
public Builder message(final Supplier<String> value) {
|
||||
this.message = value;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder size(final int value) { return size(() -> value); }
|
||||
public Builder size(final IntSupplier value) {
|
||||
this.size = value;
|
||||
return this;
|
||||
}
|
||||
|
||||
public ModLoadingState empty() {
|
||||
return new ModLoadingState(name, after, message != null ? message : () -> "", size != null ? size : () -> 0, phase, null, null);
|
||||
}
|
||||
|
||||
public ModLoadingState withTransition(final IModStateTransition transition) {
|
||||
return new ModLoadingState(name, after, message != null ? message : () -> "Processing transition " + name, size != null ? size : ModList::size, phase, null, transition);
|
||||
}
|
||||
|
||||
public ModLoadingState withInline(final Runnable inline) {
|
||||
return new ModLoadingState(name, after, message != null ? message : () -> "Processing work " + name, size != null ? size : () -> 0, phase, inline, null);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
import net.minecraftforge.forgespi.language.IModInfo;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* @param modInfo Mod info for mod with warning
|
||||
* @param warningStage The stage where this warning was encountered
|
||||
* @param i18nMessage I18N message to use for display
|
||||
* @param context Context for message display
|
||||
*/
|
||||
public record ModLoadingWarning(IModInfo modInfo, ModLoadingStage warningStage, String i18nMessage, List<Object> context) {
|
||||
public ModLoadingWarning(final IModInfo modInfo, final ModLoadingStage warningStage, final String i18nMessage, Object... context) {
|
||||
this(modInfo, warningStage, i18nMessage, List.of(context));
|
||||
}
|
||||
|
||||
public ModLoadingWarning {
|
||||
context = List.copyOf(context);
|
||||
}
|
||||
|
||||
public String formatToString() {
|
||||
return Bindings.getMessageParser().get().parseMessage(i18nMessage, Stream.concat(Stream.of(modInfo, warningStage), context.stream()).toArray());
|
||||
}
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
import com.google.common.graph.GraphBuilder;
|
||||
import cpw.mods.modlauncher.util.ServiceLoaderUtils;
|
||||
import net.minecraftforge.fml.loading.FMLLoader;
|
||||
import net.minecraftforge.fml.loading.toposort.TopologicalSort;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@SuppressWarnings("UnstableApiUsage")
|
||||
public final class ModStateManager {
|
||||
private ModStateManager() {}
|
||||
private static final EnumMap<ModLoadingPhase, List<IModLoadingState>> stateMap;
|
||||
|
||||
static {
|
||||
final var sp = ServiceLoader.load(FMLLoader.getGameLayer(), IModStateProvider.class);
|
||||
stateMap = ServiceLoaderUtils.streamWithErrorHandling(sp, _ -> {})
|
||||
.map(IModStateProvider::getAllStates)
|
||||
.flatMap(List::stream)
|
||||
.collect(Collectors.groupingBy(IModLoadingState::phase, () -> new EnumMap<>(ModLoadingPhase.class), Collectors.toUnmodifiableList()));
|
||||
}
|
||||
|
||||
public static List<IModLoadingState> getStates(final ModLoadingPhase phase) {
|
||||
var nodes = stateMap.get(phase);
|
||||
var lookup = nodes.stream().collect(Collectors.toMap(IModLoadingState::name, Function.identity()));
|
||||
|
||||
var graph = GraphBuilder.directed().allowsSelfLoops(false).<IModLoadingState>build();
|
||||
var dummy = ModLoadingState.empty("", "", phase);
|
||||
nodes.forEach(graph::addNode);
|
||||
graph.addNode(dummy);
|
||||
for (IModLoadingState node : nodes) {
|
||||
graph.putEdge(lookup.getOrDefault(node.previous(), dummy), node);
|
||||
}
|
||||
return TopologicalSort.topologicalSort(graph, Comparator.comparingInt(nodes::indexOf)).stream().filter(st->st!=dummy).toList();
|
||||
}
|
||||
|
||||
public static IModLoadingState findState(final String stateName) {
|
||||
var result = stateMap.values()
|
||||
.stream()
|
||||
.flatMap(List::stream)
|
||||
.filter(mls -> mls.name().equals(stateName))
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
if (result != null) return result;
|
||||
else throw new IllegalArgumentException("Unknown IModLoadingState: " + stateName);
|
||||
}
|
||||
}
|
||||
@@ -1,180 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.function.Function;
|
||||
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
|
||||
import net.minecraftforge.fml.IModStateTransition.EventGenerator;
|
||||
import net.minecraftforge.fml.event.IModBusEvent;
|
||||
import net.minecraftforge.fml.loading.progress.ProgressMeter;
|
||||
|
||||
@ApiStatus.Internal
|
||||
final class ModStateTransitionHelper {
|
||||
static final IModStateTransition NOOP = new NoopTransition();
|
||||
record NoopTransition() implements IModStateTransition {
|
||||
@Override
|
||||
public ThreadSelector threadSelector() {
|
||||
return ThreadSelector.SYNC;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BiFunction<Executor, CompletableFuture<Void>, CompletableFuture<Void>> finalActivityGenerator() {
|
||||
return (e, t) -> t.thenApplyAsync(Function.identity(), e);
|
||||
}
|
||||
}
|
||||
|
||||
static <V> CompletionStage<Void> completableFutureFromExceptionList(List<FutureResult<V>> t) {
|
||||
if (t.stream().noneMatch(e -> e.exception() != null)) {
|
||||
return CompletableFuture.completedFuture(null);
|
||||
} else {
|
||||
final var throwables = t.stream().map(FutureResult::exception).filter(Objects::nonNull).toList();
|
||||
CompletableFuture<Void> cf = new CompletableFuture<>();
|
||||
final RuntimeException accumulator = new RuntimeException();
|
||||
cf.completeExceptionally(accumulator);
|
||||
for (Throwable exception : throwables) {
|
||||
if (exception instanceof CompletionException) {
|
||||
exception = exception.getCause();
|
||||
}
|
||||
if (exception.getSuppressed().length != 0) {
|
||||
for (Throwable throwable : exception.getSuppressed()) {
|
||||
accumulator.addSuppressed(throwable);
|
||||
}
|
||||
} else {
|
||||
accumulator.addSuppressed(exception);
|
||||
}
|
||||
}
|
||||
return cf;
|
||||
}
|
||||
}
|
||||
|
||||
/// Same as [#completableFutureFromExceptionList(List)] but specialised for a single future
|
||||
static <V> CompletionStage<Void> completableFutureFromException(FutureResult<V> t) {
|
||||
if (t.exception() == null) {
|
||||
return CompletableFuture.completedFuture(null);
|
||||
} else {
|
||||
var exception = t.exception();
|
||||
CompletableFuture<Void> cf = new CompletableFuture<>();
|
||||
RuntimeException accumulator = new RuntimeException();
|
||||
cf.completeExceptionally(accumulator);
|
||||
if (exception instanceof CompletionException) {
|
||||
exception = exception.getCause();
|
||||
}
|
||||
if (exception.getSuppressed().length != 0) {
|
||||
for (Throwable throwable : exception.getSuppressed()) {
|
||||
accumulator.addSuppressed(throwable);
|
||||
}
|
||||
} else {
|
||||
accumulator.addSuppressed(exception);
|
||||
}
|
||||
return cf;
|
||||
}
|
||||
}
|
||||
|
||||
record FutureResult<V>(V value, Throwable exception) {}
|
||||
|
||||
static <V> CompletableFuture<List<FutureResult<V>>> gather(Collection<? extends CompletableFuture<? extends V>> futures) {
|
||||
var list = new ArrayList<FutureResult<V>>(futures.size());
|
||||
var results = new CompletableFuture[futures.size()];
|
||||
|
||||
for (var future : futures) {
|
||||
int i = list.size();
|
||||
list.add(null);
|
||||
@SuppressWarnings("unchecked") // Bypass a weird javac error with generic by forcing it to be the exact type we want.
|
||||
var raw = ((CompletableFuture<V>)future);
|
||||
results[i] = raw.whenComplete((result, exception) -> list.set(i, new FutureResult<>(result, exception)));
|
||||
}
|
||||
|
||||
return CompletableFuture.allOf(results).handle((_, _)->null).thenApply(_ -> list);
|
||||
}
|
||||
|
||||
private static <T extends IModBusEvent> CompletableFuture<Void> addCompletableFutureTaskForModDispatch(
|
||||
final Executor executor,
|
||||
final ProgressMeter progressBar,
|
||||
final EventGenerator<T> eventGenerator,
|
||||
final BiFunction<ModLoadingStage, Throwable, ModLoadingStage> nextState
|
||||
) {
|
||||
var modFutures = new LinkedHashMap<String, CompletableFuture<Void>>();
|
||||
for (var mod : ModList.getLoadedMods()) {
|
||||
|
||||
CompletableFuture<Void> parent = null;
|
||||
if (mod.dependencies.isEmpty()) {
|
||||
parent = CompletableFuture.allOf();
|
||||
} else {
|
||||
var deps = new CompletableFuture[mod.dependencies.size()];
|
||||
int idx = 0;
|
||||
for (var depContainer : mod.dependencies) {
|
||||
var future = modFutures.get(depContainer.getModId());
|
||||
if (future == null)
|
||||
throw new IllegalStateException("Could not find dependency future " + depContainer.getModId() + " for " + mod.getModId());
|
||||
deps[idx++] = future;
|
||||
}
|
||||
parent = CompletableFuture.allOf(deps);
|
||||
}
|
||||
|
||||
@SuppressWarnings("removal")
|
||||
var dispatch = parent
|
||||
.thenRunAsync(() -> {
|
||||
ModLoadingContext.get().setActiveContainer(mod);
|
||||
var handler = mod.activityMap.get(mod.modLoadingStage);
|
||||
if (handler != null)
|
||||
handler.run();
|
||||
mod.acceptEvent(eventGenerator.apply(mod));
|
||||
}, executor)
|
||||
.whenComplete((_, exception) -> {
|
||||
mod.modLoadingStage = nextState.apply(mod.modLoadingStage, exception);
|
||||
progressBar.increment();
|
||||
ModLoadingContext.get().setActiveContainer(null);
|
||||
});
|
||||
|
||||
modFutures.put(mod.getModId(), dispatch);
|
||||
}
|
||||
|
||||
return gather(modFutures.values()).thenComposeAsync(ModStateTransitionHelper::completableFutureFromExceptionList, executor);
|
||||
}
|
||||
|
||||
static <T extends IModBusEvent> CompletableFuture<Void> build(
|
||||
final IModStateTransition transition,
|
||||
final String name,
|
||||
final Executor syncExecutor,
|
||||
final Executor parallelExecutor,
|
||||
final ProgressMeter progressBar,
|
||||
final Function<Executor, CompletableFuture<Void>> preSyncTask,
|
||||
final Function<Executor, CompletableFuture<Void>> postSyncTask
|
||||
) {
|
||||
CompletableFuture<Void> future;
|
||||
final var executor = transition.threadSelector().apply(syncExecutor, parallelExecutor);
|
||||
|
||||
final CompletableFuture<Void> preSyncTaskCF = preSyncTask.apply(syncExecutor);
|
||||
CompletableFuture<Void> postEventDispatchCF = preSyncTaskCF
|
||||
.thenRunAsync(() -> progressBar.label(progressBar.name() + ": dispatching " + name), parallelExecutor);
|
||||
|
||||
var eventGenerator = transition.eventFunction();
|
||||
if (eventGenerator != null) {
|
||||
BiFunction<ModLoadingStage, Throwable, ModLoadingStage> state = transition.nextModLoadingStage();
|
||||
future = addCompletableFutureTaskForModDispatch(executor, progressBar, eventGenerator, state);
|
||||
|
||||
final CompletableFuture<Void> eventDispatchCF = future.handle(FutureResult::new)
|
||||
.thenCompose(ModStateTransitionHelper::completableFutureFromException);
|
||||
postEventDispatchCF = postEventDispatchCF.thenComposeAsync(_ -> eventDispatchCF, parallelExecutor);
|
||||
}
|
||||
|
||||
postEventDispatchCF = postEventDispatchCF.thenRun(() -> postSyncTask.apply(syncExecutor));
|
||||
|
||||
return transition.finalActivityGenerator().apply(syncExecutor, postEventDispatchCF);
|
||||
}
|
||||
}
|
||||
@@ -1,97 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
import net.minecraftforge.fml.loading.FMLConfig;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
import java.util.concurrent.*;
|
||||
import java.util.concurrent.locks.LockSupport;
|
||||
|
||||
import static net.minecraftforge.fml.Logging.LOADING;
|
||||
|
||||
public final class ModWorkManager {
|
||||
private static final Logger LOGGER = LogManager.getLogger();
|
||||
private static final long PARK_TIME = TimeUnit.MILLISECONDS.toNanos(1);
|
||||
|
||||
public sealed interface DrivenExecutor extends Executor {
|
||||
void drive(Runnable ticker);
|
||||
}
|
||||
|
||||
private record SyncExecutor(ConcurrentLinkedDeque<Runnable> tasks) implements DrivenExecutor {
|
||||
public SyncExecutor() {
|
||||
this(new ConcurrentLinkedDeque<>());
|
||||
}
|
||||
|
||||
private boolean driveOne() {
|
||||
final Runnable task = tasks.pollFirst();
|
||||
if (task != null) {
|
||||
task.run();
|
||||
}
|
||||
return task != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(final Runnable command) {
|
||||
tasks.addLast(command);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void drive(Runnable ticker) {
|
||||
ticker.run();
|
||||
while (true) {
|
||||
if (!driveOne()) break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private record WrappingExecutor(Executor wrapped) implements DrivenExecutor {
|
||||
@Override
|
||||
public void execute(final Runnable command) {
|
||||
wrapped.execute(command);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void drive(Runnable ticker) {
|
||||
// Park for a bit so other threads can schedule
|
||||
LockSupport.parkNanos(PARK_TIME);
|
||||
}
|
||||
}
|
||||
|
||||
private static final SyncExecutor syncExecutor = new SyncExecutor();
|
||||
|
||||
public static DrivenExecutor syncExecutor() {
|
||||
return syncExecutor;
|
||||
}
|
||||
|
||||
public static DrivenExecutor wrappedExecutor(Executor executor) {
|
||||
return new WrappingExecutor(executor);
|
||||
}
|
||||
|
||||
public static Executor parallelExecutor() {
|
||||
return LazyInit.PARALLEL_EXECUTOR;
|
||||
}
|
||||
|
||||
private static ForkJoinWorkerThread newForkJoinWorkerThread(ForkJoinPool pool) {
|
||||
ForkJoinWorkerThread thread = ForkJoinPool.defaultForkJoinWorkerThreadFactory.newThread(pool);
|
||||
thread.setName("modloading-worker-" + thread.getPoolIndex());
|
||||
// The default sets it to the SystemClassloader, so copy the current one.
|
||||
thread.setContextClassLoader(Thread.currentThread().getContextClassLoader());
|
||||
return thread;
|
||||
}
|
||||
|
||||
private static final class LazyInit {
|
||||
private LazyInit() {}
|
||||
private static final ForkJoinPool PARALLEL_EXECUTOR;
|
||||
|
||||
static {
|
||||
final int loadingThreadCount = FMLConfig.getIntConfigValue(FMLConfig.ConfigValue.MAX_THREADS);
|
||||
LOGGER.debug(LOADING, "Using {} threads for parallel mod-loading", loadingThreadCount);
|
||||
PARALLEL_EXECUTOR = new ForkJoinPool(loadingThreadCount, ModWorkManager::newForkJoinWorkerThread, null, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,227 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public final class OptionalMod<T>
|
||||
{
|
||||
private final String modId;
|
||||
private T value;
|
||||
private boolean searched;
|
||||
|
||||
public static <M> OptionalMod<M> of(final String modId) {
|
||||
return new OptionalMod<>(modId);
|
||||
}
|
||||
|
||||
private static final OptionalMod<?> EMPTY = new OptionalMod<>(true);
|
||||
private static <T> OptionalMod<T> empty() {
|
||||
@SuppressWarnings("unchecked")
|
||||
OptionalMod<T> t = (OptionalMod<T>) EMPTY;
|
||||
return t;
|
||||
}
|
||||
|
||||
private OptionalMod(boolean searched) {
|
||||
this.searched = searched;
|
||||
this.modId = "";
|
||||
}
|
||||
|
||||
private OptionalMod(String modId)
|
||||
{
|
||||
this.modId = modId;
|
||||
}
|
||||
|
||||
private T getValue()
|
||||
{
|
||||
if (!searched) {
|
||||
this.value = ModList.<T>getModObjectById(this.modId).orElse(null);
|
||||
searched = true;
|
||||
}
|
||||
return this.value;
|
||||
}
|
||||
|
||||
/**
|
||||
* If a mod is present in this {@code OptionalMod}, returns the value,
|
||||
* otherwise throws {@code NoSuchElementException}.
|
||||
*
|
||||
* @return the modobject held by this {@code OptionalMod}
|
||||
* @throws NoSuchElementException if there is no modobject present
|
||||
*
|
||||
* @see Optional#isPresent()
|
||||
*/
|
||||
public T get() {
|
||||
if (getValue() == null) {
|
||||
throw new NoSuchElementException("No value present");
|
||||
}
|
||||
return getValue();
|
||||
}
|
||||
|
||||
public String getModId() {
|
||||
return this.modId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return {@code true} if there is a mod object present, otherwise {@code false}.
|
||||
*
|
||||
* @return {@code true} if there is a mod object present, otherwise {@code false}
|
||||
*/
|
||||
public boolean isPresent() {
|
||||
return getValue() != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* If a mod object is present, invoke the specified consumer with the object,
|
||||
* otherwise do nothing.
|
||||
*
|
||||
* @param consumer block to be executed if a mod object is present
|
||||
* @throws NullPointerException if mod object is present and {@code consumer} is
|
||||
* null
|
||||
*/
|
||||
public void ifPresent(Consumer<? super T> consumer) {
|
||||
if (getValue() != null)
|
||||
consumer.accept(getValue());
|
||||
}
|
||||
|
||||
/**
|
||||
* If a mod object is present, and the mod object matches the given predicate,
|
||||
* return an {@code OptionalMod} describing the value, otherwise return an
|
||||
* empty {@code OptionalMod}.
|
||||
*
|
||||
* @param predicate a predicate to apply to the mod object, if present
|
||||
* @return an {@code OptionalMod} describing the value of this {@code OptionalMod}
|
||||
* if a mod object is present and the mod object matches the given predicate,
|
||||
* otherwise an empty {@code OptionalMod}
|
||||
* @throws NullPointerException if the predicate is null
|
||||
*/
|
||||
public OptionalMod<T> filter(Predicate<? super T> predicate) {
|
||||
Objects.requireNonNull(predicate);
|
||||
if (!isPresent())
|
||||
return this;
|
||||
else
|
||||
return predicate.test(getValue()) ? this : empty();
|
||||
}
|
||||
|
||||
/**
|
||||
* If a mod object is present, apply the provided mapping function to it,
|
||||
* and if the result is non-null, return an {@code Optional} describing the
|
||||
* result. Otherwise return an empty {@code Optional}.
|
||||
*
|
||||
* @apiNote This method supports post-processing on optional values, without
|
||||
* the need to explicitly check for a return status.
|
||||
*
|
||||
* @param <U> The type of the result of the mapping function
|
||||
* @param mapper a mapping function to apply to the mod object, if present
|
||||
* @return an {@code Optional} describing the result of applying a mapping
|
||||
* function to the mod object of this {@code OptionalMod}, if a mod object is present,
|
||||
* otherwise an empty {@code Optional}
|
||||
* @throws NullPointerException if the mapping function is null
|
||||
*/
|
||||
public<U> Optional<U> map(Function<? super T, ? extends U> mapper) {
|
||||
Objects.requireNonNull(mapper);
|
||||
if (!isPresent())
|
||||
return Optional.empty();
|
||||
else {
|
||||
return Optional.ofNullable(mapper.apply(getValue()));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* If a value is present, apply the provided {@code Optional}-bearing
|
||||
* mapping function to it, return that result, otherwise return an empty
|
||||
* {@code Optional}. This method is similar to {@link #map(Function)},
|
||||
* but the provided mapper is one whose result is already an {@code Optional},
|
||||
* and if invoked, {@code flatMap} does not wrap it with an additional
|
||||
* {@code Optional}.
|
||||
*
|
||||
* @param <U> The type parameter to the {@code Optional} returned by
|
||||
* @param mapper a mapping function to apply to the mod object, if present
|
||||
* the mapping function
|
||||
* @return the result of applying an {@code Optional}-bearing mapping
|
||||
* function to the value of this {@code Optional}, if a value is present,
|
||||
* otherwise an empty {@code Optional}
|
||||
* @throws NullPointerException if the mapping function is null or returns
|
||||
* a null result
|
||||
*/
|
||||
public<U> Optional<U> flatMap(Function<? super T, Optional<U>> mapper) {
|
||||
Objects.requireNonNull(mapper);
|
||||
if (!isPresent())
|
||||
return Optional.empty();
|
||||
else {
|
||||
return Objects.requireNonNull(mapper.apply(getValue()));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the mod object if present, otherwise return {@code other}.
|
||||
*
|
||||
* @param other the mod object to be returned if there is no mod object present, may
|
||||
* be null
|
||||
* @return the mod object, if present, otherwise {@code other}
|
||||
*/
|
||||
public T orElse(T other) {
|
||||
return getValue() != null ? getValue() : other;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the mod object if present, otherwise invoke {@code other} and return
|
||||
* the result of that invocation.
|
||||
*
|
||||
* @param other a {@code Supplier} whose result is returned if no mod object
|
||||
* is present
|
||||
* @return the mod object if present otherwise the result of {@code other.get()}
|
||||
* @throws NullPointerException if mod object is not present and {@code other} is
|
||||
* null
|
||||
*/
|
||||
public T orElseGet(Supplier<? extends T> other) {
|
||||
return getValue() != null ? getValue() : other.get();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the contained mod object, if present, otherwise throw an exception
|
||||
* to be created by the provided supplier.
|
||||
*
|
||||
* @apiNote A method reference to the exception constructor with an empty
|
||||
* argument list can be used as the supplier. For example,
|
||||
* {@code IllegalStateException::new}
|
||||
*
|
||||
* @param <X> Type of the exception to be thrown
|
||||
* @param exceptionSupplier The supplier which will return the exception to
|
||||
* be thrown
|
||||
* @return the present mod object
|
||||
* @throws X if there is no mod object present
|
||||
* @throws NullPointerException if no mod object is present and
|
||||
* {@code exceptionSupplier} is null
|
||||
*/
|
||||
public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X {
|
||||
if (getValue() != null) {
|
||||
return getValue();
|
||||
} else {
|
||||
throw exceptionSupplier.get();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj)
|
||||
{
|
||||
if (this == obj) return true;
|
||||
if (obj instanceof OptionalMod<?> optionalMod) {
|
||||
return Objects.equals(optionalMod.modId, modId);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode()
|
||||
{
|
||||
return Objects.hashCode(modId);
|
||||
}
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
import net.minecraftforge.fml.loading.progress.ProgressMeter;
|
||||
import net.minecraftforge.fml.loading.progress.StartupNotificationManager;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class StartupMessageManager {
|
||||
public static void addModMessage(final String message) {
|
||||
StartupNotificationManager.addModMessage(message);
|
||||
}
|
||||
|
||||
public static Optional<Consumer<String>> modLoaderConsumer() {
|
||||
return StartupNotificationManager.modLoaderConsumer();
|
||||
}
|
||||
|
||||
public static Optional<Consumer<String>> mcLoaderConsumer() {
|
||||
return StartupNotificationManager.mcLoaderConsumer();
|
||||
}
|
||||
|
||||
public static ProgressMeter addProgressBar(final String barName, final int count) {
|
||||
return StartupNotificationManager.addProgressBar(barName, count);
|
||||
}
|
||||
|
||||
public static ProgressMeter prependProgressBar(final String barName, final int count) {
|
||||
return StartupNotificationManager.prependProgressBar(barName, count);
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.function.BinaryOperator;
|
||||
|
||||
public enum ThreadSelector implements BinaryOperator<Executor> {
|
||||
SYNC((sync, _) -> sync),
|
||||
PARALLEL((_, parallel) -> parallel);
|
||||
|
||||
private final BinaryOperator<Executor> selector;
|
||||
|
||||
ThreadSelector(final BinaryOperator<Executor> selector) {
|
||||
this.selector = selector;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Executor apply(final Executor sync, final Executor parallel) {
|
||||
return this.selector.apply(sync, parallel);
|
||||
}
|
||||
}
|
||||
@@ -1,239 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import net.minecraftforge.fml.loading.FMLConfig;
|
||||
import net.minecraftforge.forgespi.language.IModInfo;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.apache.maven.artifact.versioning.ComparableVersion;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.URL;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.zip.GZIPInputStream;
|
||||
|
||||
import static net.minecraftforge.fml.VersionChecker.Status.*;
|
||||
|
||||
public class VersionChecker {
|
||||
private static final Logger LOGGER = LogManager.getLogger();
|
||||
private static final int MAX_HTTP_REDIRECTS = Integer.getInteger("http.maxRedirects", 20);
|
||||
private static final int HTTP_TIMEOUT_SECS = Integer.getInteger("http.timeoutSecs", 15);
|
||||
|
||||
public enum Status {
|
||||
PENDING(),
|
||||
FAILED(),
|
||||
UP_TO_DATE(),
|
||||
OUTDATED(3, true, true),
|
||||
AHEAD(),
|
||||
BETA(),
|
||||
BETA_OUTDATED(6, true, true);
|
||||
|
||||
private final int sheetOffset;
|
||||
private final boolean draw, animated;
|
||||
|
||||
Status() {
|
||||
this(0, false, false);
|
||||
}
|
||||
|
||||
Status(int sheetOffset, boolean draw, boolean animated) {
|
||||
this.sheetOffset = sheetOffset;
|
||||
this.draw = draw;
|
||||
this.animated = animated;
|
||||
}
|
||||
|
||||
public int getSheetOffset() {
|
||||
return sheetOffset;
|
||||
}
|
||||
|
||||
public boolean shouldDraw() {
|
||||
return draw;
|
||||
}
|
||||
|
||||
public boolean isAnimated() {
|
||||
return animated;
|
||||
}
|
||||
|
||||
public boolean isOutdated() {
|
||||
return this == OUTDATED || this == BETA_OUTDATED;
|
||||
}
|
||||
}
|
||||
|
||||
public record CheckResult(VersionChecker.Status status, ComparableVersion target, Map<ComparableVersion, String> changes, String url) {}
|
||||
|
||||
public static void startVersionCheck() {
|
||||
new Thread("Forge Version Check") {
|
||||
private HttpClient client;
|
||||
private String mcVersion;
|
||||
private String agent;
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
if (!FMLConfig.getBoolConfigValue(FMLConfig.ConfigValue.VERSION_CHECK)) {
|
||||
LOGGER.info("Global Forge version check system disabled, no further processing.");
|
||||
return;
|
||||
}
|
||||
|
||||
var mc = ModList.getModContainerById("minecraft");
|
||||
var forge = ModList.getModContainerById("forge");
|
||||
this.mcVersion = mc.get().getModInfo().getVersion().toString();
|
||||
|
||||
this.agent = "Java-http-client/" + System.getProperty("java.version")
|
||||
+ " MinecraftForge/" + mcVersion + '-' + forge.get().getModInfo().getVersion();
|
||||
|
||||
client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(HTTP_TIMEOUT_SECS)).build();
|
||||
gatherMods().forEach(this::process);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the response body as a String for the given URL while following redirects
|
||||
*/
|
||||
private String openUrlString(URL url, IModInfo mod) throws IOException, URISyntaxException, InterruptedException {
|
||||
URL currentUrl = url;
|
||||
var userAgent = this.agent + ' ' + mod.getModId() + '/' + mod.getVersion();
|
||||
|
||||
for (int redirects = 0; redirects < MAX_HTTP_REDIRECTS; redirects++) {
|
||||
var request = HttpRequest.newBuilder()
|
||||
.uri(currentUrl.toURI())
|
||||
.timeout(Duration.ofSeconds(HTTP_TIMEOUT_SECS))
|
||||
.setHeader("Accept-Encoding", "gzip")
|
||||
.setHeader("User-Agent", userAgent)
|
||||
.GET()
|
||||
.build();
|
||||
|
||||
final HttpResponse<InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());
|
||||
|
||||
int responseCode = response.statusCode();
|
||||
if (responseCode >= 300 && responseCode <= 399) {
|
||||
String newLocation = response.headers().firstValue("Location")
|
||||
.orElseThrow(() -> new IOException("Got a 3xx response code but Location header was null while trying to fetch " + url));
|
||||
currentUrl = new URL(currentUrl, newLocation);
|
||||
continue;
|
||||
}
|
||||
|
||||
final boolean isGzipEncoded = response.headers().firstValue("Content-Encoding").orElse("").equals("gzip");
|
||||
|
||||
final String bodyStr;
|
||||
try (var inStream = isGzipEncoded ? new GZIPInputStream(response.body()) : response.body();
|
||||
var bufferedReader = new BufferedReader(new InputStreamReader(inStream))
|
||||
) {
|
||||
bodyStr = bufferedReader.lines().collect(Collectors.joining("\n"));
|
||||
}
|
||||
return bodyStr;
|
||||
}
|
||||
throw new IOException("Too many redirects while trying to fetch " + url);
|
||||
}
|
||||
|
||||
private void process(IModInfo mod) {
|
||||
Status status = PENDING;
|
||||
ComparableVersion target = null;
|
||||
Map<ComparableVersion, String> changes = null;
|
||||
String display_url = null;
|
||||
try {
|
||||
if (mod.getUpdateURL().isEmpty()) return;
|
||||
URL url = mod.getUpdateURL().get();
|
||||
LOGGER.info("[{}] Starting version check at {}", mod.getModId(), url.toString());
|
||||
|
||||
String data = openUrlString(url, mod);
|
||||
|
||||
LOGGER.debug("[{}] Received version check data:\n{}", mod.getModId(), data);
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> json = new Gson().fromJson(data, Map.class);
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, String> promos = (Map<String, String>)json.get("promos");
|
||||
display_url = (String)json.get("homepage");
|
||||
|
||||
String rec = promos.get(mcVersion + "-recommended");
|
||||
String lat = promos.get(mcVersion + "-latest");
|
||||
ComparableVersion current = new ComparableVersion(mod.getVersion().toString());
|
||||
|
||||
if (rec != null) {
|
||||
ComparableVersion recommended = new ComparableVersion(rec);
|
||||
int diff = recommended.compareTo(current);
|
||||
|
||||
if (diff == 0)
|
||||
status = UP_TO_DATE;
|
||||
else if (diff < 0) {
|
||||
status = AHEAD;
|
||||
if (lat != null) {
|
||||
ComparableVersion latest = new ComparableVersion(lat);
|
||||
if (current.compareTo(latest) < 0) {
|
||||
status = OUTDATED;
|
||||
target = latest;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
status = OUTDATED;
|
||||
target = recommended;
|
||||
}
|
||||
} else if (lat != null) {
|
||||
ComparableVersion latest = new ComparableVersion(lat);
|
||||
status = current.compareTo(latest) < 0 ? BETA_OUTDATED : BETA;
|
||||
target = latest;
|
||||
} else
|
||||
status = BETA;
|
||||
|
||||
LOGGER.info("[{}] Found status: {} Current: {} Target: {}", mod.getModId(), status, current, target);
|
||||
|
||||
changes = new LinkedHashMap<>();
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, String> tmp = (Map<String, String>)json.get(mcVersion);
|
||||
if (tmp != null) {
|
||||
List<ComparableVersion> ordered = new ArrayList<>();
|
||||
for (String key : tmp.keySet()) {
|
||||
ComparableVersion ver = new ComparableVersion(key);
|
||||
if (ver.compareTo(current) > 0 && (target == null || ver.compareTo(target) < 1))
|
||||
ordered.add(ver);
|
||||
}
|
||||
Collections.sort(ordered);
|
||||
|
||||
for (ComparableVersion ver : ordered) {
|
||||
changes.put(ver, tmp.get(ver.toString()));
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOGGER.warn("Failed to process update information", e);
|
||||
status = FAILED;
|
||||
}
|
||||
RESULTS.put(mod, new CheckResult(status, target, changes, display_url));
|
||||
}
|
||||
}.start();
|
||||
}
|
||||
|
||||
// Gather a list of mods that have opted in to this update system by providing a URL.
|
||||
private static List<IModInfo> gatherMods() {
|
||||
List<IModInfo> ret = new LinkedList<>();
|
||||
for (IModInfo info : ModList.getMods()) {
|
||||
if (info.getUpdateURL().isPresent())
|
||||
ret.add(info);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
private static final Map<IModInfo, CheckResult> RESULTS = new ConcurrentHashMap<>();
|
||||
private static final CheckResult PENDING_CHECK = new CheckResult(PENDING, null, null, null);
|
||||
|
||||
public static CheckResult getResult(IModInfo mod) {
|
||||
return RESULTS.getOrDefault(mod, PENDING_CHECK);
|
||||
}
|
||||
}
|
||||
@@ -1,214 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.config;
|
||||
|
||||
import com.electronwill.nightconfig.core.ConfigFormat;
|
||||
import com.electronwill.nightconfig.core.file.CommentedFileConfig;
|
||||
import com.electronwill.nightconfig.core.file.FileWatcher;
|
||||
import com.electronwill.nightconfig.core.io.ParsingException;
|
||||
import com.electronwill.nightconfig.core.io.WritingMode;
|
||||
import com.mojang.logging.LogUtils;
|
||||
import net.minecraftforge.fml.loading.FMLConfig;
|
||||
import net.minecraftforge.fml.loading.FMLPaths;
|
||||
import org.apache.commons.io.FilenameUtils;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.function.Function;
|
||||
|
||||
import static net.minecraftforge.fml.config.ConfigTracker.CONFIG;
|
||||
|
||||
public class ConfigFileTypeHandler {
|
||||
private static final Logger LOGGER = LogUtils.getLogger();
|
||||
private static final Path defaultConfigPath = FMLPaths.GAMEDIR.get().resolve(FMLConfig.getConfigValue(FMLConfig.ConfigValue.DEFAULT_CONFIG_PATH));
|
||||
|
||||
private static final ConfigFileTypeHandler CLIENT = new ConfigFileTypeHandler(ModConfig.Type.CLIENT);
|
||||
private static final ConfigFileTypeHandler COMMON = new ConfigFileTypeHandler(ModConfig.Type.COMMON);
|
||||
private static final ConfigFileTypeHandler SERVER = new ConfigFileTypeHandler(ModConfig.Type.SERVER);
|
||||
|
||||
private final @Nullable ModConfig.Type type;
|
||||
private @Nullable FileWatcher watcher;
|
||||
|
||||
// exists for bin compat
|
||||
public ConfigFileTypeHandler() {
|
||||
this(null);
|
||||
}
|
||||
|
||||
private ConfigFileTypeHandler(@Nullable ModConfig.Type type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the handler for the given {@link ModConfig.Type}.
|
||||
*
|
||||
* @param type The type to get the handler for
|
||||
* @return The handler
|
||||
*/
|
||||
static ConfigFileTypeHandler get(ModConfig.Type type) {
|
||||
return switch (type) {
|
||||
case CLIENT -> CLIENT;
|
||||
case COMMON -> COMMON;
|
||||
case SERVER -> SERVER;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the {@link FileWatcher} for this handler, creating it if it doesn't exist and/or has been stopped.
|
||||
*
|
||||
* @return The watcher
|
||||
*
|
||||
* @apiNote This is package-private so modders can't just call {@link FileWatcher#stop()} and fuck up everything.
|
||||
*/
|
||||
FileWatcher getWatcher() {
|
||||
if (this.watcher == null) {
|
||||
LOGGER.debug(CONFIG, "Starting watcher for handler: {}", this);
|
||||
this.watcher = new FileWatcher();
|
||||
}
|
||||
|
||||
return this.watcher;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops the {@link FileWatcher} for this handler, and sets it to null afterward. Use this instead of
|
||||
* {@link FileWatcher#stop()}.
|
||||
*/
|
||||
void stopWatcher() {
|
||||
if (this.watcher == null) return;
|
||||
|
||||
LOGGER.debug(CONFIG, "Stopping watcher for hander: {}", this);
|
||||
this.watcher.stop();
|
||||
this.watcher = null;
|
||||
}
|
||||
|
||||
public Function<ModConfig, CommentedFileConfig> reader(Path configBasePath) {
|
||||
return (c) -> {
|
||||
final Path configPath = configBasePath.resolve(c.getFileName());
|
||||
final CommentedFileConfig configData = CommentedFileConfig.builder(configPath).sync().
|
||||
preserveInsertionOrder().
|
||||
autosave().
|
||||
onFileNotFound((newfile, configFormat)-> setupConfigFile(c, newfile, configFormat)).
|
||||
writingMode(WritingMode.REPLACE).
|
||||
build();
|
||||
LOGGER.debug(CONFIG, "Built TOML config for {}", configPath);
|
||||
try
|
||||
{
|
||||
configData.load();
|
||||
}
|
||||
catch (ParsingException ex)
|
||||
{
|
||||
throw new ConfigLoadingException(c, ex);
|
||||
}
|
||||
LOGGER.debug(CONFIG, "Loaded TOML config file {}", configPath);
|
||||
this.getWatcher().addWatch(configPath, new ConfigWatcher(c, configData, Thread.currentThread().getContextClassLoader()));
|
||||
LOGGER.debug(CONFIG, "Watching TOML config file {} for changes", configPath);
|
||||
return configData;
|
||||
};
|
||||
}
|
||||
|
||||
public void unload(Path configBasePath, ModConfig config) {
|
||||
Path configPath = configBasePath.resolve(config.getFileName());
|
||||
try {
|
||||
this.getWatcher().removeWatch(configPath);
|
||||
} catch (RuntimeException e) {
|
||||
LOGGER.error("Failed to remove config {} from tracker!", configPath, e);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean setupConfigFile(final ModConfig modConfig, final Path file, final ConfigFormat<?> conf) throws IOException {
|
||||
if (!Files.isDirectory(file.getParent())) {
|
||||
Files.createDirectories(file.getParent());
|
||||
}
|
||||
Path p = defaultConfigPath.resolve(modConfig.getFileName());
|
||||
if (Files.exists(p)) {
|
||||
LOGGER.info(CONFIG, "Loading default config file from path {}", p);
|
||||
Files.copy(p, file);
|
||||
} else {
|
||||
Files.createFile(file);
|
||||
conf.initEmptyFile(file);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static void backUpConfig(final CommentedFileConfig commentedFileConfig)
|
||||
{
|
||||
backUpConfig(commentedFileConfig, 5); //TODO: Think of a way for mods to set their own preference (include a sanity check as well, no disk stuffing)
|
||||
}
|
||||
|
||||
public static void backUpConfig(final CommentedFileConfig commentedFileConfig, final int maxBackups)
|
||||
{
|
||||
Path bakFileLocation = commentedFileConfig.getNioPath().getParent();
|
||||
String bakFileName = FilenameUtils.removeExtension(commentedFileConfig.getFile().getName());
|
||||
String bakFileExtension = FilenameUtils.getExtension(commentedFileConfig.getFile().getName()) + ".bak";
|
||||
Path bakFile = bakFileLocation.resolve(bakFileName + "-1" + "." + bakFileExtension);
|
||||
try
|
||||
{
|
||||
for(int i = maxBackups; i > 0; i--)
|
||||
{
|
||||
Path oldBak = bakFileLocation.resolve(bakFileName + "-" + i + "." + bakFileExtension);
|
||||
if(Files.exists(oldBak))
|
||||
{
|
||||
if(i >= maxBackups)
|
||||
Files.delete(oldBak);
|
||||
else
|
||||
Files.move(oldBak, bakFileLocation.resolve(bakFileName + "-" + (i + 1) + "." + bakFileExtension));
|
||||
}
|
||||
}
|
||||
Files.copy(commentedFileConfig.getNioPath(), bakFile);
|
||||
}
|
||||
catch (IOException exception)
|
||||
{
|
||||
LOGGER.warn(CONFIG, "Failed to back up config file {}", commentedFileConfig.getNioPath(), exception);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ConfigFileTypeHandler[" + (type != null ? type : "UNKNOWN") + "]";
|
||||
}
|
||||
|
||||
private record ConfigWatcher(
|
||||
ModConfig modConfig,
|
||||
CommentedFileConfig commentedFileConfig,
|
||||
ClassLoader realClassLoader
|
||||
) implements Runnable {
|
||||
@Override
|
||||
public void run() {
|
||||
// Force the regular classloader onto the special thread
|
||||
Thread.currentThread().setContextClassLoader(realClassLoader);
|
||||
if (!this.modConfig.getSpec().isCorrecting()) {
|
||||
try
|
||||
{
|
||||
this.commentedFileConfig.load();
|
||||
if(!this.modConfig.getSpec().isCorrect(commentedFileConfig))
|
||||
{
|
||||
LOGGER.warn(CONFIG, "Configuration file {} is not correct. Correcting", commentedFileConfig.getFile().getAbsolutePath());
|
||||
ConfigFileTypeHandler.backUpConfig(commentedFileConfig);
|
||||
this.modConfig.getSpec().correct(commentedFileConfig);
|
||||
commentedFileConfig.save();
|
||||
}
|
||||
}
|
||||
catch (ParsingException ex)
|
||||
{
|
||||
throw new ConfigLoadingException(modConfig, ex);
|
||||
}
|
||||
LOGGER.debug(CONFIG, "Config file {} changed, sending notifies", this.modConfig.getFileName());
|
||||
this.modConfig.getSpec().afterReload();
|
||||
this.modConfig.fireEvent(IConfigEvent.reloading(this.modConfig));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static class ConfigLoadingException extends RuntimeException
|
||||
{
|
||||
public ConfigLoadingException(ModConfig config, Exception cause)
|
||||
{
|
||||
super("Failed loading config file " + config.getFileName() + " of type " + config.getType() + " for modid " + config.getModId(), cause);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,116 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.config;
|
||||
|
||||
import com.electronwill.nightconfig.core.CommentedConfig;
|
||||
import com.electronwill.nightconfig.core.file.CommentedFileConfig;
|
||||
import com.mojang.logging.LogUtils;
|
||||
import net.minecraftforge.fml.loading.FMLEnvironment;
|
||||
import net.minecraftforge.fml.loading.FMLPaths;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.Marker;
|
||||
import org.slf4j.MarkerFactory;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
public final class ConfigTracker {
|
||||
private ConfigTracker() {}
|
||||
|
||||
private static final Logger LOGGER = LogUtils.getLogger();
|
||||
static final Marker CONFIG = MarkerFactory.getMarker("CONFIG");
|
||||
private static final ConcurrentHashMap<String, ModConfig> FILE_MAP = new ConcurrentHashMap<>();
|
||||
private static final Map<ModConfig.Type, Set<ModConfig>> CONFIG_SETS = Map.of(
|
||||
ModConfig.Type.CLIENT, Collections.synchronizedSet(new LinkedHashSet<>()),
|
||||
ModConfig.Type.COMMON, Collections.synchronizedSet(new LinkedHashSet<>()),
|
||||
ModConfig.Type.SERVER, Collections.synchronizedSet(new LinkedHashSet<>())
|
||||
);
|
||||
private static final ConcurrentHashMap<String, Map<ModConfig.Type, ModConfig>> CONFIGS_BY_MOD = new ConcurrentHashMap<>();
|
||||
|
||||
static void trackConfig(final ModConfig config) {
|
||||
if (FILE_MAP.containsKey(config.getFileName())) {
|
||||
LOGGER.error(CONFIG,"Detected config file conflict {} between {} and {}", config.getFileName(), FILE_MAP.get(config.getFileName()).getModId(), config.getModId());
|
||||
throw new RuntimeException("Config conflict detected!");
|
||||
}
|
||||
FILE_MAP.put(config.getFileName(), config);
|
||||
CONFIG_SETS.get(config.getType()).add(config);
|
||||
CONFIGS_BY_MOD.computeIfAbsent(config.getModId(), _ -> new EnumMap<>(ModConfig.Type.class)).put(config.getType(), config);
|
||||
LOGGER.debug(CONFIG, "Config file {} for {} tracking", config.getFileName(), config.getModId());
|
||||
}
|
||||
|
||||
public static void loadConfigs(ModConfig.Type type, Path configBasePath) {
|
||||
LOGGER.debug(CONFIG, "Loading configs type {}", type);
|
||||
for (ModConfig config : CONFIG_SETS.get(type)) {
|
||||
openConfig(config, configBasePath);
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: [FML] This is only called for the server (outside of forceUnload)
|
||||
// rethink config implementation for eventual FML rewrite
|
||||
public static void unloadConfigs(ModConfig.Type type, Path configBasePath) {
|
||||
LOGGER.debug(CONFIG, "Unloading configs type {}", type);
|
||||
for (ModConfig config : CONFIG_SETS.get(type)) {
|
||||
closeConfig(config, configBasePath);
|
||||
}
|
||||
ConfigFileTypeHandler.get(type).stopWatcher();
|
||||
}
|
||||
|
||||
// If there is a better way to do this, please tell me. Because this is FUCKED
|
||||
public static void forceUnload() {
|
||||
// This is how ModStateProvider handles loading configs. So we're doing the same but with unloadConfigs instead
|
||||
if (FMLEnvironment.dist.isClient())
|
||||
unloadConfigs(ModConfig.Type.CLIENT, FMLPaths.CONFIGDIR.get());
|
||||
|
||||
unloadConfigs(ModConfig.Type.COMMON, FMLPaths.CONFIGDIR.get());
|
||||
|
||||
// just in case server watcher is still alive somehow...
|
||||
ConfigFileTypeHandler.get(ModConfig.Type.SERVER).stopWatcher();
|
||||
}
|
||||
|
||||
private static void openConfig(final ModConfig config, final Path configBasePath) {
|
||||
LOGGER.trace(CONFIG, "Loading config file type {} at {} for {}", config.getType(), config.getFileName(), config.getModId());
|
||||
final CommentedFileConfig configData = config.getHandler().reader(configBasePath).apply(config);
|
||||
config.setConfigData(configData);
|
||||
config.fireEvent(IConfigEvent.loading(config));
|
||||
config.save();
|
||||
}
|
||||
|
||||
private static void closeConfig(final ModConfig config, final Path configBasePath) {
|
||||
if (config.getConfigData() != null) {
|
||||
LOGGER.trace(CONFIG, "Closing config file type {} at {} for {}", config.getType(), config.getFileName(), config.getModId());
|
||||
// stop the filewatcher before we save the file and close it, so reload doesn't fire
|
||||
config.getHandler().unload(configBasePath, config);
|
||||
var unloading = IConfigEvent.unloading(config);
|
||||
if (unloading != null)
|
||||
config.fireEvent(unloading);
|
||||
config.save();
|
||||
config.setConfigData(null);
|
||||
}
|
||||
}
|
||||
|
||||
public static void loadDefaultServerConfigs() {
|
||||
CONFIG_SETS.get(ModConfig.Type.SERVER).forEach(modConfig -> {
|
||||
final CommentedConfig commentedConfig = CommentedConfig.inMemory();
|
||||
modConfig.getSpec().correct(commentedConfig);
|
||||
modConfig.setConfigData(commentedConfig);
|
||||
modConfig.fireEvent(IConfigEvent.loading(modConfig));
|
||||
});
|
||||
}
|
||||
|
||||
public static String getConfigFileName(String modId, ModConfig.Type type) {
|
||||
return Optional.ofNullable(CONFIGS_BY_MOD.getOrDefault(modId, Collections.emptyMap()).getOrDefault(type, null)).
|
||||
map(ModConfig::getFullPath).map(Object::toString).orElse(null);
|
||||
}
|
||||
|
||||
public static Map<ModConfig.Type, Set<ModConfig>> configSets() {
|
||||
return CONFIG_SETS;
|
||||
}
|
||||
|
||||
public static ConcurrentHashMap<String, ModConfig> fileMap() {
|
||||
return FILE_MAP;
|
||||
}
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.config;
|
||||
|
||||
import net.minecraftforge.eventbus.api.event.InheritableEvent;
|
||||
import net.minecraftforge.fml.Bindings;
|
||||
|
||||
import java.util.function.Function;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public interface IConfigEvent {
|
||||
// TODO: [FML] Get rid of this indirection somehow
|
||||
record ConfigConfig(Function<ModConfig, IConfigEvent> loading, Function<ModConfig, IConfigEvent> reloading, @Nullable Function<ModConfig, IConfigEvent> unloading) {}
|
||||
|
||||
ConfigConfig CONFIGCONFIG = Bindings.getConfigConfiguration().get();
|
||||
|
||||
static IConfigEvent reloading(ModConfig modConfig) {
|
||||
return CONFIGCONFIG.reloading().apply(modConfig);
|
||||
}
|
||||
static IConfigEvent loading(ModConfig modConfig) {
|
||||
return CONFIGCONFIG.loading().apply(modConfig);
|
||||
}
|
||||
@Nullable static IConfigEvent unloading(ModConfig modConfig) {
|
||||
return CONFIGCONFIG.unloading() == null ? null : CONFIGCONFIG.unloading().apply(modConfig);
|
||||
}
|
||||
ModConfig getConfig();
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
default <T extends InheritableEvent & IConfigEvent> T self() {
|
||||
return (T) this;
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.config;
|
||||
|
||||
import com.electronwill.nightconfig.core.CommentedConfig;
|
||||
import com.electronwill.nightconfig.core.UnmodifiableConfig;
|
||||
|
||||
public interface IConfigSpec<T extends IConfigSpec<T>> extends UnmodifiableConfig {
|
||||
@SuppressWarnings("unchecked")
|
||||
default T self() {
|
||||
return (T) this;
|
||||
}
|
||||
|
||||
void acceptConfig(CommentedConfig data);
|
||||
|
||||
boolean isCorrecting();
|
||||
|
||||
boolean isCorrect(CommentedConfig commentedFileConfig);
|
||||
|
||||
int correct(CommentedConfig commentedFileConfig);
|
||||
|
||||
void afterReload();
|
||||
}
|
||||
@@ -1,126 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.config;
|
||||
|
||||
import com.electronwill.nightconfig.core.CommentedConfig;
|
||||
import com.electronwill.nightconfig.core.file.CommentedFileConfig;
|
||||
import com.electronwill.nightconfig.toml.TomlFormat;
|
||||
import net.minecraftforge.fml.ModContainer;
|
||||
import net.minecraftforge.fml.loading.StringUtils;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.nio.file.Path;
|
||||
|
||||
public class ModConfig
|
||||
{
|
||||
private final Type type;
|
||||
private final IConfigSpec<?> spec;
|
||||
private final String fileName;
|
||||
private final ModContainer container;
|
||||
private final ConfigFileTypeHandler configHandler;
|
||||
private CommentedConfig configData;
|
||||
|
||||
public ModConfig(final Type type, final IConfigSpec<?> spec, final ModContainer container, final String fileName) {
|
||||
this.type = type;
|
||||
this.spec = spec;
|
||||
this.fileName = fileName;
|
||||
this.container = container;
|
||||
this.configHandler = ConfigFileTypeHandler.get(type);
|
||||
ConfigTracker.trackConfig(this);
|
||||
}
|
||||
|
||||
public ModConfig(final Type type, final IConfigSpec<?> spec, final ModContainer activeContainer) {
|
||||
this(type, spec, activeContainer, defaultConfigName(type, activeContainer.getModId()));
|
||||
}
|
||||
|
||||
private static String defaultConfigName(Type type, String modId) {
|
||||
// config file name would be "forge-client.toml" and "forge-server.toml"
|
||||
return modId + '-' + type.extension() + ".toml";
|
||||
}
|
||||
|
||||
public Type getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public String getFileName() {
|
||||
return fileName;
|
||||
}
|
||||
|
||||
public ConfigFileTypeHandler getHandler() {
|
||||
return configHandler;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T extends IConfigSpec<T>> IConfigSpec<T> getSpec() {
|
||||
return (IConfigSpec<T>) spec;
|
||||
}
|
||||
|
||||
public String getModId() {
|
||||
return container.getModId();
|
||||
}
|
||||
|
||||
public CommentedConfig getConfigData() {
|
||||
return this.configData;
|
||||
}
|
||||
|
||||
void setConfigData(final CommentedConfig configData) {
|
||||
this.configData = configData;
|
||||
this.spec.acceptConfig(this.configData);
|
||||
}
|
||||
|
||||
void fireEvent(final IConfigEvent configEvent) {
|
||||
this.container.dispatchConfigEvent(configEvent);
|
||||
}
|
||||
|
||||
public void save() {
|
||||
((CommentedFileConfig)this.configData).save();
|
||||
}
|
||||
|
||||
public Path getFullPath() {
|
||||
return ((CommentedFileConfig)this.configData).getNioPath();
|
||||
}
|
||||
|
||||
public void acceptSyncedConfig(byte[] bytes) {
|
||||
setConfigData(TomlFormat.instance().createParser().parse(new ByteArrayInputStream(bytes)));
|
||||
fireEvent(IConfigEvent.reloading(this));
|
||||
}
|
||||
|
||||
public enum Type {
|
||||
/**
|
||||
* Common mod config for configuration that needs to be loaded on both environments.
|
||||
* Loaded on both servers and clients.
|
||||
* Stored in the global config directory.
|
||||
* Not synced.
|
||||
* Suffix is "-common" by default.
|
||||
*/
|
||||
COMMON,
|
||||
/**
|
||||
* Client config is for configuration affecting the ONLY client state such as graphical options.
|
||||
* Only loaded on the client side.
|
||||
* Stored in the global config directory.
|
||||
* Not synced.
|
||||
* Suffix is "-client" by default.
|
||||
*/
|
||||
CLIENT,
|
||||
// /**
|
||||
// * Player type config is configuration that is associated with a player.
|
||||
// * Preferences around machine states, for example.
|
||||
// */
|
||||
// PLAYER,
|
||||
/**
|
||||
* Server type config is configuration that is associated with a server instance.
|
||||
* Only loaded during server startup.
|
||||
* Stored in a server/save specific "serverconfig" directory.
|
||||
* Synced to clients during connection.
|
||||
* Suffix is "-server" by default.
|
||||
*/
|
||||
SERVER;
|
||||
|
||||
public String extension() {
|
||||
return StringUtils.toLowerCase(name());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.event;
|
||||
|
||||
import net.minecraftforge.eventbus.api.bus.BusGroup;
|
||||
import net.minecraftforge.eventbus.api.bus.EventBus;
|
||||
import net.minecraftforge.eventbus.api.event.InheritableEvent;
|
||||
import org.jspecify.annotations.NonNull;
|
||||
|
||||
/**
|
||||
* Marker interface for mod lifecycle events dispatched on the
|
||||
* {@linkplain net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext#getModBusGroup() mod BusGroup} instead
|
||||
* of the {@linkplain BusGroup#DEFAULT default BusGroup}.
|
||||
*
|
||||
* @apiNote Each mod gets its own unique mod BusGroup instance, obtained from the mod loading context. Most events
|
||||
* should go on the default BusGroup.
|
||||
*/
|
||||
public interface IModBusEvent extends InheritableEvent {
|
||||
/**
|
||||
* @param modEventBusGroup Obtained from {@link net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext#getModBusGroup()} or your language provider's equivalent.
|
||||
* @param eventClass The event type you want to get the associated bus for.
|
||||
*/
|
||||
static <T extends IModBusEvent> @NonNull EventBus<@NonNull T> getBus(@NonNull BusGroup modEventBusGroup, @NonNull Class<T> eventClass) {
|
||||
// Do not copy! Temporary solution until the FML rewrite is complete. May throw in future
|
||||
// without prior notice.
|
||||
//
|
||||
// Mods creating their own events should directly assign the result of the create method to a
|
||||
// static final field in their event class, without wrapping or calling multiple times.
|
||||
//
|
||||
// Mods using existing events should instead use the existing static final BUS field in the
|
||||
// event class (for most events) or getBus(BusGroup) method (for mod bus events).
|
||||
return EventBus.create(modEventBusGroup, eventClass);
|
||||
}
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.util;
|
||||
|
||||
import com.google.common.collect.ImmutableList;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.cert.Certificate;
|
||||
|
||||
public class CertificateHelper {
|
||||
|
||||
private static final String HEXES = "0123456789abcdef";
|
||||
|
||||
public static ImmutableList<String> getFingerprints(Certificate[] certificates)
|
||||
{
|
||||
int len = 0;
|
||||
if (certificates != null)
|
||||
{
|
||||
len = certificates.length;
|
||||
}
|
||||
ImmutableList.Builder<String> certBuilder = ImmutableList.builder();
|
||||
for (int i = 0; i < len; i++)
|
||||
{
|
||||
certBuilder.add(CertificateHelper.getFingerprint(certificates[i]));
|
||||
}
|
||||
return certBuilder.build();
|
||||
}
|
||||
|
||||
public static String getFingerprint(Certificate certificate)
|
||||
{
|
||||
if (certificate == null)
|
||||
{
|
||||
return "NO VALID CERTIFICATE FOUND";
|
||||
}
|
||||
try
|
||||
{
|
||||
MessageDigest md = MessageDigest.getInstance("SHA-1");
|
||||
byte[] der = certificate.getEncoded();
|
||||
md.update(der);
|
||||
byte[] digest = md.digest();
|
||||
return hexify(digest);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
return "CERTIFICATE FINGERPRINT EXCEPTION";
|
||||
}
|
||||
}
|
||||
|
||||
public static String getFingerprint(ByteBuffer buffer)
|
||||
{
|
||||
try
|
||||
{
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-1");
|
||||
digest.update(buffer);
|
||||
byte[] chksum = digest.digest();
|
||||
return hexify(chksum);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
return "CERTIFICATE FINGERPRINT EXCEPTION";
|
||||
}
|
||||
}
|
||||
|
||||
private static String hexify(byte[] chksum)
|
||||
{
|
||||
final StringBuilder hex = new StringBuilder( 2 * chksum.length );
|
||||
for ( final byte b : chksum ) {
|
||||
hex.append(HEXES.charAt((b & 0xF0) >> 4))
|
||||
.append(HEXES.charAt((b & 0x0F)));
|
||||
}
|
||||
return hex.toString();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.util;
|
||||
|
||||
import java.io.PrintStream;
|
||||
import java.io.PrintWriter;
|
||||
import java.io.StringWriter;
|
||||
|
||||
/**
|
||||
* RuntimeException that gives subclasses the simple opportunity to write extra data when printing the stack trace.
|
||||
* Mainly a helper class as printsStackTrace has multiple signatures.
|
||||
*/
|
||||
public abstract class EnhancedRuntimeException extends RuntimeException
|
||||
{
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public EnhancedRuntimeException() { super(); }
|
||||
public EnhancedRuntimeException(String message) { super(message); }
|
||||
public EnhancedRuntimeException(String message, Throwable cause) { super(message, cause); }
|
||||
public EnhancedRuntimeException(Throwable cause) { super(cause); }
|
||||
|
||||
@Override
|
||||
public String getMessage()
|
||||
{
|
||||
StackTraceElement[] stack = Thread.currentThread().getStackTrace();
|
||||
if (stack.length > 2 && stack[2].getClassName().startsWith("org.apache.logging.log4j."))
|
||||
{
|
||||
// This is a bit of a hack to force ourselves to be able to give a extended description when log4j prints this out.
|
||||
// Sadly this text is displayed AFTER the initial exception line, and before the stack trace. But as the intention
|
||||
// is to print this to the end user this is what we need to do.
|
||||
final StringWriter buf = new StringWriter();
|
||||
|
||||
String msg = super.getMessage();
|
||||
if (msg != null)
|
||||
buf.append(msg);
|
||||
|
||||
buf.append('\n');
|
||||
this.printStackTrace(new WrappedPrintStream()
|
||||
{
|
||||
@Override
|
||||
public void println(String line)
|
||||
{
|
||||
buf.append(line).append('\n');
|
||||
}
|
||||
});
|
||||
return buf.toString();
|
||||
}
|
||||
return super.getMessage();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void printStackTrace(final PrintWriter s)
|
||||
{
|
||||
printStackTrace(new WrappedPrintStream()
|
||||
{
|
||||
@Override
|
||||
public void println(String line)
|
||||
{
|
||||
s.println(line);
|
||||
}
|
||||
});
|
||||
super.printStackTrace(s);
|
||||
}
|
||||
@Override
|
||||
public void printStackTrace(final PrintStream s)
|
||||
{
|
||||
printStackTrace(new WrappedPrintStream()
|
||||
{
|
||||
@Override
|
||||
public void println(String line)
|
||||
{
|
||||
s.println(line);
|
||||
}
|
||||
});
|
||||
super.printStackTrace(s);
|
||||
}
|
||||
|
||||
protected abstract void printStackTrace(WrappedPrintStream stream);
|
||||
|
||||
public static abstract class WrappedPrintStream
|
||||
{
|
||||
public abstract void println(String line);
|
||||
}
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.util;
|
||||
|
||||
|
||||
public class LoaderException extends EnhancedRuntimeException
|
||||
{
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = -5675297950958861378L;
|
||||
|
||||
public LoaderException(Throwable wrapped)
|
||||
{
|
||||
super(wrapped);
|
||||
}
|
||||
|
||||
public LoaderException()
|
||||
{
|
||||
}
|
||||
public LoaderException(String message)
|
||||
{
|
||||
super(message);
|
||||
}
|
||||
public LoaderException(String message, Throwable cause)
|
||||
{
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
@Override protected void printStackTrace(WrappedPrintStream stream){}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.util;
|
||||
|
||||
/**
|
||||
* Prevent LoaderException from adding its own stack trace to the wrapped throwable's stack trace.
|
||||
*/
|
||||
public class LoaderExceptionModCrash extends LoaderException
|
||||
{
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public LoaderExceptionModCrash(String message, Throwable cause)
|
||||
{
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized Throwable fillInStackTrace()
|
||||
{
|
||||
return this;
|
||||
}
|
||||
}
|
||||
@@ -1,262 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.util;
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.StringJoiner;
|
||||
|
||||
import cpw.mods.modlauncher.api.INameMappingService;
|
||||
import net.minecraftforge.fml.loading.FMLLoader;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.apache.logging.log4j.Marker;
|
||||
import org.apache.logging.log4j.MarkerManager;
|
||||
|
||||
import com.google.common.base.Preconditions;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* Some reflection helper code.
|
||||
* This may not work properly in Java 9 with its new, more restrictive, reflection management.
|
||||
* As such, if issues are encountered, please report them and we can see what we can do to expand
|
||||
* the compatibility.
|
||||
*
|
||||
* In other cases, AccessTransformers may be used.
|
||||
*
|
||||
* All field and method names should be passed in as SRG names, and this will automatically resolve if MCP mappings are detected.
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings({"serial", "unchecked", "unused", "WeakerAccess"})
|
||||
public class ObfuscationReflectionHelper
|
||||
{
|
||||
private static final Logger LOGGER = LogManager.getLogger();
|
||||
private static final Marker REFLECTION = MarkerManager.getMarker("REFLECTION");
|
||||
|
||||
/**
|
||||
* Remaps a name using the SRG naming function
|
||||
* @param domain The {@link INameMappingService.Domain} to use to remap the name.
|
||||
* @param name The name to try and remap.
|
||||
* @return The remapped name, or the original name if it couldn't be remapped.
|
||||
*/
|
||||
@NotNull
|
||||
public static String remapName(INameMappingService.Domain domain, String name)
|
||||
{
|
||||
return FMLLoader.getNameFunction("srg").map(f->f.apply(domain, name)).orElse(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value a field with the specified name in the given class.
|
||||
* Note: For performance, use {@link #findField(Class, String)} if you are getting the value more than once.
|
||||
* <p>
|
||||
* Throws an exception if the field is not found or the value of the field cannot be gotten.
|
||||
*
|
||||
* @param classToAccess The class to find the field on.
|
||||
* @param instance The instance of the {@code classToAccess}.
|
||||
* @param fieldName The SRG (unmapped) name of the field to find (e.g. "f_46443_").
|
||||
* @param <T> The type of the value.
|
||||
* @param <E> The type of the {@code classToAccess}.
|
||||
* @return The value of the field with the specified name in the {@code classToAccess}.
|
||||
* @throws UnableToAccessFieldException If there was a problem getting the field.
|
||||
* @throws UnableToAccessFieldException If there was a problem getting the value.
|
||||
*/
|
||||
@Nullable
|
||||
public static <T, E> T getPrivateValue(Class<? super E> classToAccess, E instance, String fieldName)
|
||||
{
|
||||
try
|
||||
{
|
||||
return (T) findField(classToAccess, fieldName).get(instance);
|
||||
}
|
||||
catch (UnableToFindFieldException e)
|
||||
{
|
||||
LOGGER.error(REFLECTION,"Unable to locate field {} ({}) on type {}", fieldName, remapName(INameMappingService.Domain.FIELD, fieldName), classToAccess.getName(), e);
|
||||
throw e;
|
||||
}
|
||||
catch (IllegalAccessException e)
|
||||
{
|
||||
LOGGER.error(REFLECTION,"Unable to access field {} ({}) on type {}", fieldName, remapName(INameMappingService.Domain.FIELD, fieldName), classToAccess.getName(), e);
|
||||
throw new UnableToAccessFieldException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value a field with the specified name in the given class.
|
||||
* Note: For performance, use {@link #findField(Class, String)} if you are setting the value more than once.
|
||||
* <p>
|
||||
* Throws an exception if the field is not found or the value of the field cannot be set.
|
||||
*
|
||||
* @param classToAccess The class to find the field on.
|
||||
* @param instance The instance of the {@code classToAccess}.
|
||||
* @param value The new value for the field
|
||||
* @param fieldName The name of the field in the {@code classToAccess}.
|
||||
* @param <T> The type of the value.
|
||||
* @param <E> The type of the {@code classToAccess}.
|
||||
* @throws UnableToFindFieldException If there was a problem getting the field.
|
||||
* @throws UnableToAccessFieldException If there was a problem setting the value of the field.
|
||||
*/
|
||||
public static <T, E> void setPrivateValue(@NotNull final Class<? super T> classToAccess, @NotNull final T instance, @Nullable final E value, @NotNull final String fieldName)
|
||||
{
|
||||
try
|
||||
{
|
||||
findField(classToAccess, fieldName).set(instance, value);
|
||||
}
|
||||
catch (UnableToFindFieldException e)
|
||||
{
|
||||
LOGGER.error("Unable to locate any field {} on type {}", fieldName, classToAccess.getName(), e);
|
||||
throw e;
|
||||
}
|
||||
catch (IllegalAccessException e)
|
||||
{
|
||||
LOGGER.error("Unable to set any field {} on type {}", fieldName, classToAccess.getName(), e);
|
||||
throw new UnableToAccessFieldException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds a method with the specified name and parameters in the given class and makes it accessible.
|
||||
* Note: For performance, store the returned value and avoid calling this repeatedly.
|
||||
* <p>
|
||||
* Throws an exception if the method is not found.
|
||||
*
|
||||
* @param clazz The class to find the method on.
|
||||
* @param methodName The SRG (unmapped) name of the method to find (e.g. "m_5776_").
|
||||
* @param parameterTypes The parameter types of the method to find.
|
||||
* @return The method with the specified name and parameters in the given class.
|
||||
* @throws NullPointerException If {@code clazz} is null.
|
||||
* @throws NullPointerException If {@code methodName} is null.
|
||||
* @throws IllegalArgumentException If {@code methodName} is empty.
|
||||
* @throws NullPointerException If {@code parameterTypes} is null.
|
||||
* @throws UnableToFindMethodException If the method could not be found.
|
||||
*/
|
||||
@NotNull
|
||||
public static Method findMethod(@NotNull final Class<?> clazz, @NotNull final String methodName, @NotNull final Class<?>... parameterTypes)
|
||||
{
|
||||
Preconditions.checkNotNull(clazz, "Class to find method on cannot be null.");
|
||||
Preconditions.checkNotNull(methodName, "Name of method to find cannot be null.");
|
||||
Preconditions.checkArgument(!methodName.isEmpty(), "Name of method to find cannot be empty.");
|
||||
Preconditions.checkNotNull(parameterTypes, "Parameter types of method to find cannot be null.");
|
||||
|
||||
try
|
||||
{
|
||||
Method m = clazz.getDeclaredMethod(remapName(INameMappingService.Domain.METHOD, methodName), parameterTypes);
|
||||
m.setAccessible(true);
|
||||
return m;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
throw new UnableToFindMethodException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds a constructor with the specified parameter types in the given class and makes it accessible.
|
||||
* Note: For performance, store the returned value and avoid calling this repeatedly.
|
||||
* <p>
|
||||
* Throws an exception if the constructor is not found.
|
||||
*
|
||||
* @param clazz The class to find the constructor in.
|
||||
* @param parameterTypes The parameter types of the constructor.
|
||||
* @param <T> The type.
|
||||
* @return The constructor with the specified parameters in the given class.
|
||||
* @throws NullPointerException If {@code clazz} is null.
|
||||
* @throws NullPointerException If {@code parameterTypes} is null.
|
||||
* @throws UnknownConstructorException If the constructor could not be found.
|
||||
*/
|
||||
@NotNull
|
||||
public static <T> Constructor<T> findConstructor(@NotNull final Class<T> clazz, @NotNull final Class<?>... parameterTypes)
|
||||
{
|
||||
Preconditions.checkNotNull(clazz, "Class to find constructor on cannot be null.");
|
||||
Preconditions.checkNotNull(parameterTypes, "Parameter types of constructor to find cannot be null.");
|
||||
|
||||
try
|
||||
{
|
||||
Constructor<T> constructor = clazz.getDeclaredConstructor(parameterTypes);
|
||||
constructor.setAccessible(true);
|
||||
return constructor;
|
||||
}
|
||||
catch (final NoSuchMethodException e)
|
||||
{
|
||||
final StringBuilder desc = new StringBuilder();
|
||||
desc.append(clazz.getSimpleName());
|
||||
|
||||
StringJoiner joiner = new StringJoiner(", ", "(", ")");
|
||||
for (Class<?> type : parameterTypes)
|
||||
{
|
||||
joiner.add(type.getSimpleName());
|
||||
}
|
||||
desc.append(joiner);
|
||||
|
||||
throw new UnknownConstructorException("Could not find constructor '" + desc.toString() + "' in " + clazz);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds a field with the specified name in the given class and makes it accessible.
|
||||
* Note: For performance, store the returned value and avoid calling this repeatedly.
|
||||
* <p>
|
||||
* Throws an exception if the field is not found.
|
||||
*
|
||||
* @param clazz The class to find the field on.
|
||||
* @param fieldName The SRG (unmapped) name of the field to find (e.g. "f_46443_").
|
||||
* @param <T> The type.
|
||||
* @return The constructor with the specified parameters in the given class.
|
||||
* @throws NullPointerException If {@code clazz} is null.
|
||||
* @throws NullPointerException If {@code fieldName} is null.
|
||||
* @throws IllegalArgumentException If {@code fieldName} is empty.
|
||||
* @throws UnableToFindFieldException If the field could not be found.
|
||||
*/
|
||||
@NotNull
|
||||
public static <T> Field findField(@NotNull final Class<? super T> clazz, @NotNull final String fieldName)
|
||||
{
|
||||
Preconditions.checkNotNull(clazz, "Class to find field on cannot be null.");
|
||||
Preconditions.checkNotNull(fieldName, "Name of field to find cannot be null.");
|
||||
Preconditions.checkArgument(!fieldName.isEmpty(), "Name of field to find cannot be empty.");
|
||||
|
||||
try
|
||||
{
|
||||
Field f = clazz.getDeclaredField(remapName(INameMappingService.Domain.FIELD, fieldName));
|
||||
f.setAccessible(true);
|
||||
return f;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
throw new UnableToFindFieldException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static class UnableToAccessFieldException extends RuntimeException
|
||||
{
|
||||
private UnableToAccessFieldException(Exception e)
|
||||
{
|
||||
super(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static class UnableToFindFieldException extends RuntimeException
|
||||
{
|
||||
private UnableToFindFieldException(Exception e)
|
||||
{
|
||||
super(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static class UnableToFindMethodException extends RuntimeException
|
||||
{
|
||||
public UnableToFindMethodException(Throwable failed)
|
||||
{
|
||||
super(failed);
|
||||
}
|
||||
}
|
||||
|
||||
public static class UnknownConstructorException extends RuntimeException
|
||||
{
|
||||
public UnknownConstructorException(final String message)
|
||||
{
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.util.thread;
|
||||
|
||||
import net.minecraftforge.fml.LogicalSide;
|
||||
|
||||
/**
|
||||
* Attempts to determine the effect side of the current thread, based on know threads in networking.
|
||||
* This is not guaranteed to be correct, and modders should use other methods to determine the logical side when possible.
|
||||
*/
|
||||
public class EffectiveSide {
|
||||
public static LogicalSide get() {
|
||||
final ThreadGroup group = Thread.currentThread().getThreadGroup();
|
||||
return group instanceof SidedThreadGroup ? ((SidedThreadGroup) group).getSide() : LogicalSide.CLIENT;
|
||||
}
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.util.thread;
|
||||
|
||||
import net.minecraftforge.fml.LogicalSide;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.concurrent.ThreadFactory;
|
||||
|
||||
/**
|
||||
* A thread group and factory combination which belongs to a {@link LogicalSide}.
|
||||
*/
|
||||
public final class SidedThreadGroup extends ThreadGroup implements ThreadFactory
|
||||
{
|
||||
private final LogicalSide side;
|
||||
|
||||
SidedThreadGroup(final LogicalSide side)
|
||||
{
|
||||
super(side.name());
|
||||
this.side = side;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the side this sided thread group belongs to.
|
||||
*
|
||||
* @return the side
|
||||
*/
|
||||
public LogicalSide getSide()
|
||||
{
|
||||
return this.side;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Thread newThread(@NotNull final Runnable runnable)
|
||||
{
|
||||
return new Thread(this, runnable);
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.util.thread;
|
||||
|
||||
import net.minecraftforge.fml.LogicalSide;
|
||||
|
||||
public final class SidedThreadGroups {
|
||||
public static final SidedThreadGroup CLIENT = new SidedThreadGroup(LogicalSide.CLIENT);
|
||||
public static final SidedThreadGroup SERVER = new SidedThreadGroup(LogicalSide.SERVER);
|
||||
|
||||
public static SidedThreadGroup get(boolean client) {
|
||||
return client ? CLIENT : SERVER;
|
||||
}
|
||||
|
||||
private SidedThreadGroups() { }
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
import org.gradle.api.plugins.jvm.JvmTestSuite
|
||||
|
||||
plugins {
|
||||
id 'jvm-test-suite'
|
||||
id 'net.minecraftforge.forge.build.convention'
|
||||
}
|
||||
|
||||
gradleutils.displayName = 'FML Early Display'
|
||||
description = 'A pretty looking, but prone to erroring screen displayed during Forge loading.'
|
||||
|
||||
dependencies {
|
||||
implementation projects.fmlloader
|
||||
implementation projects.fmlcore
|
||||
implementation libs.bundles.lwjgl
|
||||
implementation earlyDisplayLibs.slf4j.api
|
||||
implementation libs.jopt.simple
|
||||
}
|
||||
|
||||
testing.suites.named('test', JvmTestSuite) {
|
||||
useJUnitJupiter('5.8.2')
|
||||
|
||||
dependencies {
|
||||
implementation earlyDisplayTestLibs.powermock.core
|
||||
runtimeOnly earlyDisplayLibs.slf4j.jdk14
|
||||
runtimeOnly.bundle convention.nativeVariants(earlyDisplayTestLibs.bundles.lwjgl)
|
||||
}
|
||||
}
|
||||
|
||||
convention.manifest('net/minecraftforge/fml/earlydisplay/', [
|
||||
'Automatic-Module-Name': 'net.minecraftforge.earlydisplay',
|
||||
'Forge-Module-Layer' : 'boot'
|
||||
])
|
||||
|
||||
convention.publish()
|
||||
@@ -1,43 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.earlydisplay;
|
||||
|
||||
public enum ColourScheme {
|
||||
RED(new Colour(239, 50, 61), new Colour(255, 255, 255)),
|
||||
BLACK(new Colour(0, 0, 0), new Colour(255, 255, 255));
|
||||
|
||||
private final Colour background;
|
||||
private final Colour foreground;
|
||||
|
||||
ColourScheme(final Colour background, final Colour foreground) {
|
||||
this.background = background;
|
||||
this.foreground = foreground;
|
||||
}
|
||||
|
||||
public Colour background() {
|
||||
return background;
|
||||
}
|
||||
|
||||
public Colour foreground() {
|
||||
return foreground;
|
||||
}
|
||||
|
||||
public record Colour(int red, int green, int blue) {
|
||||
public float redf() {
|
||||
return ((float)red)/255f;
|
||||
}
|
||||
public float greenf() {
|
||||
return ((float)green)/255f;
|
||||
}
|
||||
public float bluef() {
|
||||
return ((float)blue)/255f;
|
||||
}
|
||||
|
||||
public int packedint(int a) {
|
||||
return ((a & 0xff) << 24) | ((blue & 0xff) << 16) | ((green & 0xff) << 8) | (red & 0xff);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,716 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.earlydisplay;
|
||||
|
||||
import joptsimple.OptionParser;
|
||||
import net.minecraftforge.fml.loading.FMLConfig;
|
||||
import net.minecraftforge.fml.loading.FMLLoader;
|
||||
import net.minecraftforge.fml.loading.FMLPaths;
|
||||
import net.minecraftforge.fml.loading.ImmediateWindowHandler;
|
||||
import net.minecraftforge.fml.loading.ImmediateWindowProvider;
|
||||
import net.minecraftforge.fml.loading.progress.StartupNotificationManager;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.lwjgl.opengl.GL;
|
||||
import org.lwjgl.sdl.SDLError;
|
||||
import org.lwjgl.sdl.SDLVideo;
|
||||
import org.lwjgl.sdl.SDL_Event;
|
||||
import org.lwjgl.sdl.SDL_Rect;
|
||||
import org.lwjgl.system.MemoryStack;
|
||||
import org.lwjgl.util.tinyfd.TinyFileDialogs;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.awt.Desktop;
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.net.URI;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Calendar;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
import java.util.concurrent.Semaphore;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.IntConsumer;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import static org.lwjgl.opengl.GL32C.*;
|
||||
|
||||
import static org.lwjgl.sdl.SDLError.*;
|
||||
import static org.lwjgl.sdl.SDLEvents.*;
|
||||
import static org.lwjgl.sdl.SDLHints.*;
|
||||
import static org.lwjgl.sdl.SDLInit.*;
|
||||
import static org.lwjgl.sdl.SDLVideo.*;
|
||||
|
||||
/**
|
||||
* The Loading Window that is opened Immediately after Forge starts.
|
||||
* It is called from the ModDirTransformerDiscoverer, the soonest method that ModLauncher calls into Forge code.
|
||||
* In this way, we can be sure that this will not run before any transformer or injection.
|
||||
*
|
||||
* The window itself is spun off into a secondary thread, and is handed off to the main game by Forge.
|
||||
*
|
||||
* Because it is created so early, this thread will "absorb" the context from OpenGL.
|
||||
* Therefore, it is of utmost importance that the Context is made Current for the main thread before handoff,
|
||||
* otherwise OS X will crash out.
|
||||
*
|
||||
* Based on the prior ClientVisualization, with some personal touches.
|
||||
*/
|
||||
public class DisplayWindow implements ImmediateWindowProvider {
|
||||
private static final int[][] GL_VERSIONS = new int[][] {{4,6}, {4,5}, {4,4}, {4,3}, {4,2}, {4,1}, {4,0}, {3,3}};
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger("EARLYDISPLAY");
|
||||
private final AtomicBoolean animationTimerTrigger = new AtomicBoolean(true);
|
||||
|
||||
private ColourScheme colourScheme = ColourScheme.RED;
|
||||
private ElementShader elementShader;
|
||||
|
||||
private RenderElement.DisplayContext context;
|
||||
private List<RenderElement> elements;
|
||||
private int framecount;
|
||||
private EarlyFramebuffer framebuffer;
|
||||
private ScheduledFuture<?> windowTick;
|
||||
private ScheduledFuture<?> initializationFuture;
|
||||
|
||||
private PerformanceInfo performanceInfo;
|
||||
// The GL ID of the window. Used for all operations
|
||||
private long window;
|
||||
// The SDL Context we use for switching between threads
|
||||
private long sdlContext;
|
||||
// The thread that contains and ticks the window while Forge is loading mods
|
||||
private static final ScheduledExecutorService renderScheduler = Executors.newSingleThreadScheduledExecutor(r -> {
|
||||
final var thread = Executors.defaultThreadFactory().newThread(r);
|
||||
thread.setName("EarlyDisplay");
|
||||
thread.setDaemon(true);
|
||||
return thread;
|
||||
});
|
||||
private int fbWidth;
|
||||
private int fbHeight;
|
||||
private int fbScale;
|
||||
private int winWidth;
|
||||
private int winHeight;
|
||||
private int winX;
|
||||
private int winY;
|
||||
|
||||
private final Semaphore renderLock = new Semaphore(1);
|
||||
private boolean maximized;
|
||||
private String glVersion;
|
||||
private SimpleFont font;
|
||||
private Runnable repaintTick = ()->{};
|
||||
|
||||
@Override
|
||||
public String name() {
|
||||
return "fmlearlywindow";
|
||||
}
|
||||
|
||||
@Override
|
||||
public ImmediateWindowProvider selectBackend(String backend) {
|
||||
// We only support opengl
|
||||
//if ("default".equals(backend) || "opengl".equals(backend))
|
||||
// return this;
|
||||
return ImmediateWindowProvider.getFallbackHandler();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Runnable initialize(String[] arguments) {
|
||||
String mcVersion = FMLLoader.versionInfo().mcVersion();
|
||||
String forgeVersion = FMLLoader.versionInfo().forgeVersion();
|
||||
|
||||
final OptionParser parser = new OptionParser();
|
||||
var widthopt = parser.accepts("width")
|
||||
.withRequiredArg().ofType(Integer.class)
|
||||
.defaultsTo(FMLConfig.getIntConfigValue(FMLConfig.ConfigValue.EARLY_WINDOW_WIDTH));
|
||||
var heightopt = parser.accepts("height")
|
||||
.withRequiredArg().ofType(Integer.class)
|
||||
.defaultsTo(FMLConfig.getIntConfigValue(FMLConfig.ConfigValue.EARLY_WINDOW_HEIGHT));
|
||||
var maximizedopt = parser.accepts("earlywindow.maximized");
|
||||
parser.allowsUnrecognizedOptions();
|
||||
var parsed = parser.parse(arguments);
|
||||
winWidth = parsed.valueOf(widthopt);
|
||||
winHeight = parsed.valueOf(heightopt);
|
||||
FMLConfig.updateConfig(FMLConfig.ConfigValue.EARLY_WINDOW_WIDTH, winWidth);
|
||||
FMLConfig.updateConfig(FMLConfig.ConfigValue.EARLY_WINDOW_HEIGHT, winHeight);
|
||||
fbScale = FMLConfig.getIntConfigValue(FMLConfig.ConfigValue.EARLY_WINDOW_FBSCALE);
|
||||
if (System.getenv("FML_EARLY_WINDOW_DARK") != null) {
|
||||
this.colourScheme = ColourScheme.BLACK;
|
||||
} else {
|
||||
try {
|
||||
// check the options file for the color scheme
|
||||
var optionLines = Files.readAllLines(FMLPaths.GAMEDIR.get().resolve(Path.of("options.txt")));
|
||||
var keyName = "darkMojangStudiosBackground:";
|
||||
for (String line : optionLines) {
|
||||
if (line.startsWith(keyName)) {
|
||||
this.colourScheme = line.startsWith("true", keyName.length()) ? ColourScheme.BLACK : ColourScheme.RED;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
this.colourScheme = ColourScheme.RED; // fallback to red colourScheme
|
||||
}
|
||||
}
|
||||
this.maximized = parsed.has(maximizedopt) || FMLConfig.getBoolConfigValue(FMLConfig.ConfigValue.EARLY_WINDOW_MAXIMIZED);
|
||||
|
||||
StartupNotificationManager.modLoaderConsumer().ifPresent(c->c.accept("Forge loading " + FMLLoader.versionInfo().forgeVersion()));
|
||||
performanceInfo = new PerformanceInfo();
|
||||
return start(mcVersion, forgeVersion);
|
||||
}
|
||||
|
||||
private static final long MINFRAMETIME = TimeUnit.MILLISECONDS.toNanos(10); // This is the FPS cap on the window - note animation is capped at 20FPS via the tickTimer
|
||||
private long nextFrameTime = 0;
|
||||
/**
|
||||
* The main render loop.
|
||||
* renderThread executes this.
|
||||
*
|
||||
* Performs initialization and then ticks the screen at 20 fps.
|
||||
* When the thread is killed, context is destroyed.
|
||||
*/
|
||||
private void renderThreadFunc() {
|
||||
if (!renderLock.tryAcquire()) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
long nt;
|
||||
if ((nt = System.nanoTime()) < nextFrameTime) {
|
||||
return;
|
||||
}
|
||||
nextFrameTime = nt + MINFRAMETIME;
|
||||
SDL_GL_MakeCurrent(window, sdlContext);
|
||||
framebuffer.activate();
|
||||
glViewport(0, 0, this.context.scaledWidth(), this.context.scaledHeight());
|
||||
this.context.elementShader().activate();
|
||||
this.context.elementShader().updateScreenSizeUniform(this.context.scaledWidth(), this.context.scaledHeight());
|
||||
glClearColor(colourScheme.background().redf(), colourScheme.background().greenf(), colourScheme.background().bluef(), 1f);
|
||||
paintFramebuffer();
|
||||
this.context.elementShader().clear();
|
||||
framebuffer.deactivate();
|
||||
glViewport(0, 0, fbWidth, fbHeight);
|
||||
framebuffer.draw(this.fbWidth, this.fbHeight);
|
||||
// Swap buffers; we're done
|
||||
SDL_GL_SwapWindow(window);
|
||||
} catch (Throwable t) {
|
||||
LOGGER.error("BARF", t);
|
||||
} finally {
|
||||
if (this.windowTick != null)
|
||||
SDL_GL_MakeCurrent(window, 0); // we release the gl context IF we're running off the main thread
|
||||
renderLock.release();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Render initialization methods called by the Render Thread.
|
||||
* It compiles the fragment and vertex shaders for rendering text with STB, and sets up basic render framework.
|
||||
*
|
||||
* Nothing fancy, we just want to draw and render text.
|
||||
*/
|
||||
private void initRender(final @Nullable String mcVersion, final String forgeVersion) {
|
||||
this.sdlContext = SDL_GL_CreateContext(window);
|
||||
if (sdlContext == 0)
|
||||
throw new IllegalStateException("Failed to create OpenGL context: " + SDL_GetError());
|
||||
|
||||
// This thread owns the GL render context now. We should make a note of that.
|
||||
bindGlContext();
|
||||
GL.createCapabilities();
|
||||
|
||||
// Wait for one frame to be complete before swapping; enable vsync in other words.
|
||||
SDL_GL_SetSwapInterval(1);
|
||||
|
||||
LOGGER.info("GL info: " + glGetString(GL_RENDERER) + " GL version " + glGetString(GL_VERSION) + ", " + glGetString(GL_VENDOR));
|
||||
|
||||
elementShader = new ElementShader();
|
||||
try {
|
||||
elementShader.init();
|
||||
} catch (Throwable t) {
|
||||
LOGGER.error("Crash during shader initialization", t);
|
||||
crashElegantly("An error occurred initializing shaders.");
|
||||
}
|
||||
|
||||
// Set the clear color based on the color scheme
|
||||
glClearColor(colourScheme.background().redf(), colourScheme.background().greenf(), colourScheme.background().bluef(), 1f);
|
||||
|
||||
// we always render to an 854x480 texture and then fit that to the screen - with a scale factor
|
||||
this.context = new RenderElement.DisplayContext(854, 480, fbScale, elementShader, colourScheme, performanceInfo);
|
||||
framebuffer = new EarlyFramebuffer(this.context);
|
||||
try {
|
||||
this.font = new SimpleFont("Monocraft.ttf", fbScale, 200000, 1 + RenderElement.INDEX_TEXTURE_OFFSET);
|
||||
} catch (Throwable t) {
|
||||
LOGGER.error("Crash during font initialization", t);
|
||||
crashElegantly("An error occurred initializing a font for rendering. "+t.getMessage());
|
||||
}
|
||||
this.elements = new ArrayList<>(List.of(
|
||||
RenderElement.anvil(font),
|
||||
RenderElement.logMessageOverlay(font),
|
||||
RenderElement.forgeVersionOverlay(font, mcVersion + "-" + forgeVersion),
|
||||
RenderElement.performanceBar(font),
|
||||
RenderElement.progressBars(font)
|
||||
));
|
||||
|
||||
var date = Calendar.getInstance();
|
||||
if (FMLConfig.getBoolConfigValue(FMLConfig.ConfigValue.EARLY_WINDOW_SQUIR) || (date.get(Calendar.MONTH) == Calendar.APRIL && date.get(Calendar.DAY_OF_MONTH) == 1))
|
||||
this.elements.addFirst(RenderElement.squir());
|
||||
|
||||
glEnable(GL_BLEND);
|
||||
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
|
||||
|
||||
releaseGlContext();
|
||||
|
||||
this.windowTick = renderScheduler.scheduleAtFixedRate(this::renderThreadFunc, 50, 50, TimeUnit.MILLISECONDS);
|
||||
|
||||
// Update the performance information every 1/2 second
|
||||
renderScheduler.scheduleAtFixedRate(performanceInfo::update, 0, 500, TimeUnit.MILLISECONDS);
|
||||
// schedule a 50 ms ticker to try and smooth out the rendering
|
||||
//renderScheduler.scheduleAtFixedRate(() -> animationTimerTrigger.set(true), 1, 50, TimeUnit.MILLISECONDS);
|
||||
}
|
||||
|
||||
/**
|
||||
* Called every frame by the Render Thread to draw to the screen.
|
||||
*/
|
||||
void paintFramebuffer() {
|
||||
// Clear the screen to our color
|
||||
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
|
||||
glEnable(GL_BLEND);
|
||||
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
|
||||
|
||||
for (var itr = this.elements.iterator(); itr.hasNext(); ) {
|
||||
var element = itr.next();
|
||||
if (!element.render(context, framecount))
|
||||
itr.remove();
|
||||
}
|
||||
if (animationTimerTrigger.compareAndSet(true, false)) // we only increment the framecount on a periodic basis
|
||||
framecount++;
|
||||
}
|
||||
|
||||
|
||||
public void render(int alpha) {
|
||||
var currentVAO = glGetInteger(GL_VERTEX_ARRAY_BINDING);
|
||||
var currentFB = glGetInteger(GL_READ_FRAMEBUFFER_BINDING);
|
||||
glViewport(0, 0, this.context.scaledWidth(), this.context.scaledHeight());
|
||||
RenderElement.globalAlpha = alpha;
|
||||
framebuffer.activate();
|
||||
glClearColor(colourScheme.background().redf(), colourScheme.background().greenf(), colourScheme.background().bluef(), alpha / 255f);
|
||||
elementShader.activate();
|
||||
elementShader.updateScreenSizeUniform(this.context.scaledWidth(), this.context.scaledHeight());
|
||||
paintFramebuffer();
|
||||
elementShader.clear();
|
||||
framebuffer.deactivate();
|
||||
glBindVertexArray(currentVAO);
|
||||
glBindFramebuffer(GL_FRAMEBUFFER, currentFB);
|
||||
}
|
||||
|
||||
/**
|
||||
* Start the window and Render Thread; we're ready to go.
|
||||
*/
|
||||
public Runnable start(@Nullable String mcVersion, final String forgeVersion) {
|
||||
initWindow(mcVersion);
|
||||
this.initializationFuture = renderScheduler.schedule(() -> initRender(mcVersion, forgeVersion), 1, TimeUnit.MILLISECONDS);
|
||||
return this::periodicTick;
|
||||
}
|
||||
|
||||
private static final String ERROR_URL = "https://links.minecraftforge.net/early-display-errors";
|
||||
@Override
|
||||
public String getGLVersion() {
|
||||
return this.glVersion;
|
||||
}
|
||||
|
||||
private static void crashElegantly(String errorDetails) {
|
||||
StringBuilder msgBuilder = new StringBuilder(2000);
|
||||
msgBuilder.append("Failed to initialize graphics window with current settings.\n");
|
||||
msgBuilder.append("\n\n");
|
||||
msgBuilder.append("Failure details:\n");
|
||||
msgBuilder.append(errorDetails);
|
||||
msgBuilder.append("\n\n");
|
||||
msgBuilder.append("If you click yes, we will try and open " + ERROR_URL + " in your default browser");
|
||||
LOGGER.error("ERROR DISPLAY\n"+msgBuilder);
|
||||
// we show the display on a new dedicated thread
|
||||
Executors.newSingleThreadExecutor().submit(()-> {
|
||||
var res = TinyFileDialogs.tinyfd_messageBox("Minecraft: Forge", msgBuilder.toString(), "yesno", "error", 0);
|
||||
if (res != 0) {
|
||||
try {
|
||||
Desktop.getDesktop().browse(URI.create(ERROR_URL));
|
||||
} catch (IOException ioe) {
|
||||
TinyFileDialogs.tinyfd_messageBox("Minecraft: Forge", "Sadly, we couldn't open your browser.\nVisit " + ERROR_URL, "ok", "error", 0);
|
||||
}
|
||||
}
|
||||
System.exit(1);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Called to initialize the window when preparing for the Render Thread.
|
||||
*
|
||||
* The act of calling glfwInit here creates a concurrency issue; GL doesn't know whether we're gonna call any
|
||||
* GL functions from the secondary thread and the main thread at the same time.
|
||||
*
|
||||
* It's then our job to make sure this doesn't happen, only calling GL functions where the Context is Current.
|
||||
* As long as we can verify that, then GL (and things like OS X) have no complaints with doing this.
|
||||
*
|
||||
* @param mcVersion Minecraft Version
|
||||
*/
|
||||
public void initWindow(@Nullable String mcVersion) {
|
||||
// Initialize a time guard, in case something goes wrong
|
||||
long initBegin = System.nanoTime();
|
||||
if (!SDL_Init(SDL_INIT_VIDEO)) {
|
||||
crashElegantly("We are unable to initialize the graphics system.\nSDL_Init failed.\n");
|
||||
throw new IllegalStateException("Unable to initialize SDL");
|
||||
}
|
||||
long initEnd = System.nanoTime();
|
||||
|
||||
if (initEnd - initBegin > 1e9)
|
||||
LOGGER.error("WARNING : Window init took {} seconds to start.", (initEnd - initBegin) / 1.0e9);
|
||||
|
||||
// Set window hints for the new window we're gonna create.
|
||||
SDL_ResetHints();
|
||||
|
||||
String vanillaWindowTitle = "Minecraft* ";
|
||||
if (mcVersion != null)
|
||||
vanillaWindowTitle += mcVersion;
|
||||
|
||||
var primaryMonitor = SDL_GetPrimaryDisplay();
|
||||
if (primaryMonitor == 0) {
|
||||
LOGGER.error("Failed to find a primary monitor - this means LWJGL isn't working properly");
|
||||
crashElegantly("Failed to locate a primary monitor.\nSDL_GetPrimaryDisplay failed.\n");
|
||||
throw new IllegalStateException("Can't find a primary monitor");
|
||||
}
|
||||
|
||||
var vidmode = SDL_GetDesktopDisplayMode(primaryMonitor);
|
||||
if (vidmode == null) {
|
||||
LOGGER.error("Failed to get the current display video mode.");
|
||||
crashElegantly("Failed to get current display resolution.\nSDL_GetDesktopDisplayMode failed.\n");
|
||||
throw new IllegalStateException("Can't get a resolution");
|
||||
}
|
||||
|
||||
long window = 0;
|
||||
var successfulWindow = new AtomicBoolean(false);
|
||||
var windowFailFuture = renderScheduler.schedule(() -> {
|
||||
if (!successfulWindow.get())
|
||||
crashElegantly("Timed out trying to setup the Game Window.");
|
||||
}, 10, TimeUnit.SECONDS);
|
||||
|
||||
var skipVersions = FMLConfig.<String>getListConfigValue(FMLConfig.ConfigValue.EARLY_WINDOW_SKIP_GL_VERSIONS);
|
||||
boolean showHelpLog = FMLConfig.getBoolConfigValue(FMLConfig.ConfigValue.EARLY_WINDOW_LOG_HELP_MSG);
|
||||
|
||||
record Attempt(String vesion, String error) {}
|
||||
final List<Attempt> attempts = new ArrayList<>();
|
||||
String requestedVersion = null;
|
||||
|
||||
for (int x = 0; x < GL_VERSIONS.length; x++) {
|
||||
var version = GL_VERSIONS[x];
|
||||
requestedVersion = version[0] + "." + version[1];
|
||||
|
||||
if (skipVersions.contains(requestedVersion)) {
|
||||
LOGGER.info("Skipping GL version " + requestedVersion + " because of configuration");
|
||||
continue;
|
||||
}
|
||||
|
||||
LOGGER.info("Trying GL version " + requestedVersion);
|
||||
if (showHelpLog && x == 0) {
|
||||
LOGGER.info("""
|
||||
If this message is the only thing at the bottom of your log before a crash, you probably have a driver issue.
|
||||
|
||||
Possible solutions:
|
||||
A) Make sure Minecraft is set to prefer high performance graphics in the OS and/or driver control panel
|
||||
B) Check for driver updates on the graphics brand's website
|
||||
C) Try reinstalling your graphics drivers
|
||||
D) If still not working after trying all of the above, ask for further help on the Forge forums or Discord
|
||||
|
||||
You can safely ignore this message if the game starts up successfully.""");
|
||||
}
|
||||
|
||||
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, version[0]);
|
||||
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, version[1]);
|
||||
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
|
||||
SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG);
|
||||
SDL_GL_SetAttribute(SDL_GL_FRAMEBUFFER_SRGB_CAPABLE, GL_TRUE);
|
||||
window = SDL_CreateWindow(vanillaWindowTitle, winWidth, winHeight,
|
||||
SDL_WINDOW_OPENGL
|
||||
| SDL_WINDOW_RESIZABLE
|
||||
| SDL_WINDOW_HIGH_PIXEL_DENSITY
|
||||
);
|
||||
|
||||
if (window == 0) {
|
||||
var error = Objects.requireNonNullElse(SDLError.SDL_GetError(), "<no error>");
|
||||
attempts.add(new Attempt(requestedVersion, error));
|
||||
LOGGER.trace("Failed to create window using %d.%d: %s", version[0], version[1], error);
|
||||
} else {
|
||||
SDLVideo.SDL_SetWindowMinimumSize(window, 320, 240);
|
||||
LOGGER.info("Created window using SDL video driver: {}", SDLVideo.SDL_GetCurrentVideoDriver());
|
||||
break; // We got a valid window!
|
||||
}
|
||||
}
|
||||
|
||||
if (window == 0) {
|
||||
LOGGER.error("Failed to find any valid GLFW profile.");
|
||||
var message = new StringBuilder()
|
||||
.append("Failed to find a valid GLFW profile.\n");
|
||||
|
||||
if (attempts.isEmpty()) {
|
||||
message.append("All GL Versions were skipped");
|
||||
} else {
|
||||
message.append("We tried:");
|
||||
for (var attempt : attempts)
|
||||
message.append("\n\t").append(attempt.vesion).append(':').append(attempt.error);
|
||||
}
|
||||
|
||||
crashElegantly(message.toString());
|
||||
throw new IllegalStateException("Failed to create a GLFW window with any profile");
|
||||
}
|
||||
|
||||
successfulWindow.set(true);
|
||||
if (!windowFailFuture.cancel(true))
|
||||
throw new IllegalStateException("We died but didn't somehow?");
|
||||
|
||||
try (var stack = org.lwjgl.system.MemoryStack.stackPush()) {
|
||||
var majBuf = stack.mallocInt(1);
|
||||
var minBuf = stack.mallocInt(1);
|
||||
SDL_GL_GetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, majBuf);
|
||||
SDL_GL_GetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, minBuf);
|
||||
this.glVersion = majBuf.get(0) + "." + minBuf.get(0);
|
||||
}
|
||||
|
||||
LOGGER.info("Requested GL version " + requestedVersion + " got version " + this.glVersion);
|
||||
this.window = window;
|
||||
|
||||
if (showHelpLog)
|
||||
FMLConfig.updateConfig(FMLConfig.ConfigValue.EARLY_WINDOW_LOG_HELP_MSG, false);
|
||||
|
||||
if (this.maximized)
|
||||
SDL_MaximizeWindow(window);
|
||||
|
||||
var size = getWindowSize(window);
|
||||
this.onWindowResize(size.x, size.y);
|
||||
|
||||
var monitor = getMonitorSize(primaryMonitor);
|
||||
if (monitor != null)
|
||||
SDL_SetWindowPosition(window, (monitor.width - size.x) / 2 + monitor.x, (monitor.height - size.y) / 2 + monitor.y);
|
||||
|
||||
pollEvents();
|
||||
|
||||
SDL_ShowWindow(window);
|
||||
}
|
||||
|
||||
private record Point(int x, int y) {}
|
||||
private record Rect(int x, int y, int width, int height) {}
|
||||
|
||||
private static @Nullable Rect getMonitorSize(int monitor) {
|
||||
try (var bounds = SDL_Rect.malloc()) {
|
||||
// Fetch the display bounds for the current index
|
||||
if (SDL_GetDisplayBounds(monitor, bounds)) {
|
||||
int x = bounds.x();
|
||||
int y = bounds.y();
|
||||
int width = bounds.w();
|
||||
int height = bounds.h();
|
||||
LOGGER.info("Display {} Bounds -> X: {}, Y: {}, Width: {}, Height: {}", monitor, x, y, width, height);
|
||||
return new Rect(x, y, width, height);
|
||||
} else {
|
||||
LOGGER.warn("Could not get bounds for display: " + SDL_GetError());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static Point getWindowSize(long window) {
|
||||
try (var stack = MemoryStack.stackPush()) {
|
||||
var width = stack.mallocInt(1);
|
||||
var height = stack.mallocInt(1);
|
||||
SDL_GetWindowSize(window, width, height);
|
||||
return new Point(width.get(0), height.get(0));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Hand-off the window to the vanilla game.
|
||||
* Called on the main thread instead of the game's initialization.
|
||||
*
|
||||
* @return the Window we own.
|
||||
*/
|
||||
@Override
|
||||
public long setupMinecraftWindow(final int width, final int height, final String title, final Supplier<Object> backend) {
|
||||
// wait for the window to actually be initialized
|
||||
try {
|
||||
this.initializationFuture.get(30, TimeUnit.SECONDS);
|
||||
} catch (InterruptedException | ExecutionException e) {
|
||||
throw new RuntimeException(e);
|
||||
} catch (TimeoutException e) {
|
||||
Thread.dumpStack();
|
||||
crashElegantly("We seem to be having trouble initializing the window, waited for 30 seconds");
|
||||
}
|
||||
|
||||
// we have to spin wait for the window ticker
|
||||
ImmediateWindowHandler.updateProgress("Initializing Game Graphics");
|
||||
while (!this.windowTick.isDone()) {
|
||||
this.windowTick.cancel(false);
|
||||
}
|
||||
var tries = 0;
|
||||
var renderlockticket = false;
|
||||
do {
|
||||
try {
|
||||
renderlockticket = renderLock.tryAcquire(100, TimeUnit.MILLISECONDS);
|
||||
if (++tries > 9) {
|
||||
Thread.dumpStack();
|
||||
crashElegantly("We seem to be having trouble handing off the window, tried for 1 second");
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
Thread.interrupted();
|
||||
}
|
||||
} while (!renderlockticket);
|
||||
// we don't want the lock, just making sure it's back on the main thread
|
||||
renderLock.release();
|
||||
|
||||
SDL_GL_MakeCurrent(window, sdlContext);
|
||||
// Set the title to what the game wants
|
||||
SDL_SetWindowTitle(window, title);
|
||||
SDL_GL_SetSwapInterval(0); // Disable vsync, let Minecraft control it
|
||||
this.repaintTick = this::renderThreadFunc; // the repaint will continue to be called until the overlay takes over
|
||||
this.windowTick = null; // this tells the render thread that the async ticker is done
|
||||
return window;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean positionWindow(final Optional<Object> monitor, final IntConsumer widthSetter, final IntConsumer heightSetter, final IntConsumer xSetter, final IntConsumer ySetter) {
|
||||
widthSetter.accept(this.winWidth);
|
||||
heightSetter.accept(this.winHeight);
|
||||
xSetter.accept(this.winX);
|
||||
ySetter.accept(this.winY);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateFramebufferSize(final IntConsumer width, final IntConsumer height) {
|
||||
width.accept(this.fbWidth);
|
||||
height.accept(this.fbHeight);
|
||||
}
|
||||
|
||||
private Method loadingOverlay;
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Override
|
||||
public <T> Supplier<T> loadingOverlay(final Supplier<?> mc, final Supplier<?> ri, final Consumer<Optional<Throwable>> ex, final boolean fade) {
|
||||
try {
|
||||
return (Supplier<T>)loadingOverlay.invoke(null, mc, ri, ex, this);
|
||||
} catch (Throwable e) {
|
||||
throw new IllegalStateException("How did you get here?", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateModuleReads(final ModuleLayer layer) {
|
||||
final var FORGE_MODULE = "net.minecraftforge.forge";
|
||||
var forge_module = layer.findModule(FORGE_MODULE).orElse(null);
|
||||
if (forge_module == null)
|
||||
throw new IllegalStateException("Could not find " + FORGE_MODULE + " in " + layer);
|
||||
|
||||
getClass().getModule().addReads(forge_module);
|
||||
|
||||
|
||||
var clz = Class.forName(forge_module, "net.minecraftforge.client.loading.ForgeLoadingOverlay");
|
||||
|
||||
for (var mtd : clz.getDeclaredMethods()) {
|
||||
if (Modifier.isStatic(mtd.getModifiers()) && "newInstance".equals(mtd.getName())) {
|
||||
this.loadingOverlay = mtd;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (loadingOverlay == null)
|
||||
throw new IllegalStateException("Could not find static newInstace method in " + clz.getName());
|
||||
}
|
||||
|
||||
public int getFramebufferTextureId() {
|
||||
return framebuffer.getTexture();
|
||||
}
|
||||
|
||||
public RenderElement.DisplayContext context() {
|
||||
return this.context;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void periodicTick() {
|
||||
pollEvents();
|
||||
repaintTick.run();
|
||||
}
|
||||
|
||||
public void addMojangTexture(final int textureId) {
|
||||
this.elements.addFirst(RenderElement.mojang(textureId, framecount));
|
||||
}
|
||||
|
||||
public void close() {
|
||||
// Close the Render Scheduler thread
|
||||
renderScheduler.shutdown();
|
||||
this.framebuffer.close();
|
||||
this.context.elementShader().close();
|
||||
SimpleBufferBuilder.destroy();
|
||||
}
|
||||
|
||||
private void bindGlContext() {
|
||||
SDL_GL_MakeCurrent(window, sdlContext);
|
||||
//if (!SDL_GL_MakeCurrent(window, sdlContext))
|
||||
// throw new IllegalStateException("Failed to make OpenGL context current: " + SDL_GetError());
|
||||
}
|
||||
|
||||
private void releaseGlContext() {
|
||||
SDL_GL_MakeCurrent(window, 0);
|
||||
}
|
||||
|
||||
|
||||
private void pollEvents() {
|
||||
try (var event = SDL_Event.malloc()) {
|
||||
while (SDL_PollEvent(event)) {
|
||||
switch (event.type()) {
|
||||
case SDL_EVENT_WINDOW_MOVED:
|
||||
this.onWindowMove(event.window().data1(), event.window().data2());
|
||||
break;
|
||||
case SDL_EVENT_WINDOW_RESIZED:
|
||||
this.onWindowResize(event.window().data1(), event.window().data2());
|
||||
break;
|
||||
case SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED:
|
||||
this.onFrameBufferResize(event.window().data1(), event.window().data2());
|
||||
break;
|
||||
|
||||
/*
|
||||
We were told to quit for some reason, find a way to abort?
|
||||
case SDL_EVENT_QUIT:
|
||||
case SDL_EVENT_WINDOW_CLOSE_REQUESTED:
|
||||
case SDL_EVENT_TERMINATING:
|
||||
|
||||
Window was minimized or restored, maybe stop rendering?
|
||||
case SDL_EVENT_WINDOW_MINIMIZED:
|
||||
case SDL_EVENT_WINDOW_MAXIMIZED:
|
||||
case SDL_EVENT_WINDOW_RESTORED:
|
||||
*/
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void onWindowResize(int width, int height) {
|
||||
if (width == 0 || height == 0)
|
||||
return;
|
||||
|
||||
this.winWidth = width;
|
||||
this.winHeight = height;
|
||||
}
|
||||
|
||||
private void onFrameBufferResize(int width, int height) {
|
||||
if (width == 0 || height == 0)
|
||||
return;
|
||||
|
||||
this.fbWidth = width;
|
||||
this.fbHeight = height;
|
||||
}
|
||||
|
||||
private void onWindowMove(int x, int y) {
|
||||
this.winX = x;
|
||||
this.winY = y;
|
||||
}
|
||||
|
||||
}
|
||||
-67
@@ -1,67 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.earlydisplay;
|
||||
|
||||
import java.nio.IntBuffer;
|
||||
|
||||
import static net.minecraftforge.fml.earlydisplay.RenderElement.clamp;
|
||||
import static org.lwjgl.opengl.GL32C.*;
|
||||
|
||||
public class EarlyFramebuffer {
|
||||
private final int framebuffer;
|
||||
private final int texture;
|
||||
|
||||
private final RenderElement.DisplayContext context;
|
||||
|
||||
EarlyFramebuffer(final RenderElement.DisplayContext context) {
|
||||
this.context = context;
|
||||
this.framebuffer = glGenFramebuffers();
|
||||
this.texture = glGenTextures();
|
||||
glBindFramebuffer(GL_FRAMEBUFFER, this.framebuffer);
|
||||
glActiveTexture(GL_TEXTURE0);
|
||||
glBindTexture(GL_TEXTURE_2D, this.texture);
|
||||
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, context.width() * context.scale(), context.height() * context.scale(), 0, GL_RGBA, GL_UNSIGNED_BYTE, (IntBuffer)null);
|
||||
glTexParameterIi(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
|
||||
glTexParameterIi(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
|
||||
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, this.texture, 0);
|
||||
glBindFramebuffer(GL_FRAMEBUFFER, 0);
|
||||
}
|
||||
|
||||
void activate() {
|
||||
glBindFramebuffer(GL_FRAMEBUFFER, this.framebuffer);
|
||||
}
|
||||
|
||||
void deactivate() {
|
||||
glBindFramebuffer(GL_FRAMEBUFFER, 0);
|
||||
}
|
||||
|
||||
void draw(int windowFBWidth, int windowFBHeight) {
|
||||
var wscale = ((float)windowFBWidth / this.context.width());
|
||||
var hscale = ((float)windowFBHeight / this.context.height());
|
||||
var scale = this.context.scale() * Math.min(wscale, hscale) / 2f;
|
||||
var wleft = (int)(windowFBWidth * 0.5f - scale * this.context.width());
|
||||
var wtop = (int)(windowFBHeight * 0.5f - scale * this.context.height());
|
||||
var wright = (int)(windowFBWidth * 0.5f + scale * this.context.width());
|
||||
var wbottom = (int)(windowFBHeight * 0.5f + scale * this.context.height());
|
||||
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
|
||||
glBindFramebuffer(GL_READ_FRAMEBUFFER, this.framebuffer);
|
||||
final var colour = this.context.colourScheme().background();
|
||||
glClearColor(colour.redf(), colour.greenf(), colour.bluef(), 1f);
|
||||
glClear(GL_COLOR_BUFFER_BIT);
|
||||
// src Y are flipped, since our FB is flipped
|
||||
glBlitFramebuffer(0, this.context.height() * this.context.scale(), this.context.width() * this.context.scale(), 0, clamp(wleft, 0, windowFBWidth), clamp(wtop, 0, windowFBHeight), clamp(wright, 0, windowFBWidth), clamp(wbottom, 0, windowFBHeight), GL_COLOR_BUFFER_BIT, GL_NEAREST);
|
||||
glBindFramebuffer(GL_FRAMEBUFFER, 0);
|
||||
}
|
||||
|
||||
int getTexture() {
|
||||
return this.texture;
|
||||
}
|
||||
|
||||
public void close() {
|
||||
glDeleteTextures(this.texture);
|
||||
glDeleteFramebuffers(this.framebuffer);
|
||||
}
|
||||
}
|
||||
@@ -1,117 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.earlydisplay;
|
||||
|
||||
|
||||
import static org.lwjgl.opengl.GL32C.*;
|
||||
|
||||
public class ElementShader {
|
||||
private int program;
|
||||
private int textureUniform;
|
||||
private int screenSizeUniform;
|
||||
private int renderTypeUniform;
|
||||
|
||||
public void init() {
|
||||
int vertexShader = glCreateShader(GL_VERTEX_SHADER);
|
||||
int fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
|
||||
|
||||
// Bind the source of our shaders to the ones created above
|
||||
glShaderSource(fragmentShader, """
|
||||
#version 150 core
|
||||
uniform sampler2D tex;
|
||||
uniform int rendertype;
|
||||
in vec2 fTex;
|
||||
in vec4 fColour;
|
||||
out vec4 fragColor;
|
||||
|
||||
void main() {
|
||||
if (rendertype == 0)
|
||||
fragColor = vec4(1,1,1,texture(tex, fTex).r) * fColour;
|
||||
if (rendertype == 1)
|
||||
fragColor = texture(tex, fTex) * fColour;
|
||||
if (rendertype == 2)
|
||||
fragColor = fColour;
|
||||
}
|
||||
""");
|
||||
glShaderSource(vertexShader, """
|
||||
#version 150 core
|
||||
in vec2 position;
|
||||
in vec2 tex;
|
||||
in vec4 colour;
|
||||
uniform vec2 screenSize;
|
||||
out vec2 fTex;
|
||||
out vec4 fColour;
|
||||
void main() {
|
||||
fTex = tex;
|
||||
fColour = colour;
|
||||
gl_Position = vec4((position/screenSize) * 2 - 1, 0.0, 1.0);
|
||||
}
|
||||
""");
|
||||
|
||||
// Compile the vertex and fragment elementShader so that we can use them
|
||||
glCompileShader(vertexShader);
|
||||
if (glGetShaderi(vertexShader, GL_COMPILE_STATUS) == GL_FALSE) {
|
||||
throw new IllegalStateException("VertexShader linkage failure. \n" + glGetShaderInfoLog(vertexShader));
|
||||
}
|
||||
glCompileShader(fragmentShader);
|
||||
if (glGetShaderi(fragmentShader, GL_COMPILE_STATUS) == GL_FALSE) {
|
||||
throw new IllegalStateException("FragmentShader linkage failure. \n" + glGetShaderInfoLog(fragmentShader));
|
||||
}
|
||||
|
||||
var program = glCreateProgram();
|
||||
glBindAttribLocation(program, 0, "position");
|
||||
glBindAttribLocation(program, 1, "tex");
|
||||
glBindAttribLocation(program, 2, "colour");
|
||||
glAttachShader(program, vertexShader);
|
||||
glAttachShader(program, fragmentShader);
|
||||
glLinkProgram(program);
|
||||
if (glGetProgrami(program, GL_LINK_STATUS) == GL_FALSE) {
|
||||
throw new RuntimeException("ShaderProgram linkage failure. \n" + glGetProgramInfoLog(program));
|
||||
}
|
||||
this.program = program;
|
||||
|
||||
glDetachShader(program, vertexShader);
|
||||
glDetachShader(program, fragmentShader);
|
||||
glDeleteShader(vertexShader);
|
||||
glDeleteShader(fragmentShader);
|
||||
textureUniform = glGetUniformLocation(program, "tex");
|
||||
screenSizeUniform = glGetUniformLocation(program, "screenSize");
|
||||
renderTypeUniform = glGetUniformLocation(program, "rendertype");
|
||||
|
||||
activate();
|
||||
}
|
||||
|
||||
public void activate() {
|
||||
glUseProgram(program);
|
||||
}
|
||||
public void updateTextureUniform(int textureNumber) {
|
||||
glUniform1i(textureUniform, textureNumber);
|
||||
}
|
||||
|
||||
public void updateScreenSizeUniform(int width, int height) {
|
||||
glUniform2f(screenSizeUniform, width, height);
|
||||
}
|
||||
|
||||
public void updateRenderTypeUniform(RenderType type) {
|
||||
glUniform1i(renderTypeUniform, type.ordinal());
|
||||
}
|
||||
|
||||
public void clear() {
|
||||
glUseProgram(0);
|
||||
}
|
||||
|
||||
public void close() {
|
||||
glDeleteProgram(program);
|
||||
}
|
||||
|
||||
public enum RenderType {
|
||||
FONT, TEXTURE, BAR;
|
||||
}
|
||||
|
||||
public int program() {
|
||||
return program;
|
||||
}
|
||||
}
|
||||
-56
@@ -1,56 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.earlydisplay;
|
||||
|
||||
import com.sun.management.OperatingSystemMXBean;
|
||||
import net.minecraftforge.fml.loading.FMLConfig;
|
||||
|
||||
import java.lang.management.ManagementFactory;
|
||||
import java.lang.management.MemoryMXBean;
|
||||
import java.lang.management.MemoryUsage;
|
||||
|
||||
public class PerformanceInfo {
|
||||
private static final MemoryMXBean MEMORY_BEAN = ManagementFactory.getMemoryMXBean();
|
||||
|
||||
private final boolean showCPUUsage;
|
||||
private final OperatingSystemMXBean osBean;
|
||||
|
||||
private float memory;
|
||||
private String text;
|
||||
|
||||
PerformanceInfo() {
|
||||
showCPUUsage = FMLConfig.getBoolConfigValue(FMLConfig.ConfigValue.EARLY_WINDOW_SHOW_CPU);
|
||||
osBean = showCPUUsage ? ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class) : null;
|
||||
}
|
||||
|
||||
void update() {
|
||||
final MemoryUsage heapusage = MEMORY_BEAN.getHeapMemoryUsage();
|
||||
memory = (float) heapusage.getUsed() / heapusage.getMax();
|
||||
|
||||
if (!showCPUUsage) {
|
||||
text = "Memory: %d/%dMB (%.1f%%)".formatted(heapusage.getUsed() >>> 20, heapusage.getMax() >>> 20, memory * 100f);
|
||||
return;
|
||||
}
|
||||
|
||||
var cpuLoad = osBean.getProcessCpuLoad();
|
||||
String cpuText;
|
||||
if (cpuLoad == -1) {
|
||||
cpuText = "*CPU: %.1f%%".formatted(osBean.getCpuLoad() * 100f);
|
||||
} else {
|
||||
cpuText = "CPU: %.1f%%".formatted(cpuLoad * 100f);
|
||||
}
|
||||
|
||||
text = "Memory: %d/%dMB (%.1f%%) %s".formatted(heapusage.getUsed() >>> 20, heapusage.getMax() >>> 20, memory * 100f, cpuText);
|
||||
}
|
||||
|
||||
String text() {
|
||||
return text;
|
||||
}
|
||||
|
||||
float memory() {
|
||||
return memory;
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.earlydisplay;
|
||||
|
||||
public class QuadHelper {
|
||||
public static void loadQuad(SimpleBufferBuilder bb, float x0, float x1, float y0, float y1, float u0, float u1, float v0, float v1, int colour) {
|
||||
bb.pos(x0, y0).tex(u0, v0).colour(colour).endVertex();
|
||||
bb.pos(x1, y0).tex(u1, v0).colour(colour).endVertex();
|
||||
bb.pos(x0, y1).tex(u0, v1).colour(colour).endVertex();
|
||||
bb.pos(x1, y1).tex(u1, v1).colour(colour).endVertex();
|
||||
}
|
||||
|
||||
public static void loadQuad(SimpleBufferBuilder bb, float x0, float x1, float y0, float y1, float u0, float u1, float v0, float v1) {
|
||||
bb.pos(x0, y0).tex(u0, v0).endVertex();
|
||||
bb.pos(x1, y0).tex(u1, v0).endVertex();
|
||||
bb.pos(x0, y1).tex(u0, v1).endVertex();
|
||||
bb.pos(x1, y1).tex(u1, v1).endVertex();
|
||||
}
|
||||
}
|
||||
@@ -1,327 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.earlydisplay;
|
||||
|
||||
import net.minecraftforge.fml.loading.progress.Message;
|
||||
import net.minecraftforge.fml.loading.progress.ProgressMeter;
|
||||
import net.minecraftforge.fml.loading.progress.StartupNotificationManager;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import static org.lwjgl.opengl.GL32C.*;
|
||||
|
||||
public class RenderElement {
|
||||
static final int INDEX_TEXTURE_OFFSET = 5;
|
||||
private final SimpleBufferBuilder bb;
|
||||
private final Renderer renderer;
|
||||
static int globalAlpha = 255;
|
||||
private int retireCount;
|
||||
|
||||
@FunctionalInterface
|
||||
interface Renderer {
|
||||
void accept(SimpleBufferBuilder bb, DisplayContext context, int frame);
|
||||
|
||||
default Renderer then(Renderer r) {
|
||||
if (r == null) return this;
|
||||
return (bb, ctx, frame) -> {
|
||||
r.accept(bb, ctx, frame);
|
||||
this.accept(bb, ctx, frame);
|
||||
};
|
||||
}
|
||||
}
|
||||
@FunctionalInterface
|
||||
interface TextureRenderer {
|
||||
void accept(SimpleBufferBuilder bb, DisplayContext context, int[] size, int frame);
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
interface TextGenerator {
|
||||
void accept(SimpleBufferBuilder bb, SimpleFont fh, DisplayContext ctx);
|
||||
}
|
||||
|
||||
public record DisplayContext(int width, int height, int scale, ElementShader elementShader, ColourScheme colourScheme, PerformanceInfo performance) {
|
||||
public int scaledWidth() {
|
||||
return scale() * width();
|
||||
}
|
||||
|
||||
public int scaledHeight() {
|
||||
return scale() * height();
|
||||
}
|
||||
}
|
||||
|
||||
public RenderElement(Renderer renderer) {
|
||||
this.bb = new SimpleBufferBuilder(1);
|
||||
this.renderer = renderer;
|
||||
}
|
||||
|
||||
public boolean render(DisplayContext ctx, int count) {
|
||||
this.renderer.accept(bb, ctx, count);
|
||||
return this.retireCount == 0 || this.retireCount < count;
|
||||
}
|
||||
|
||||
public void retire(final int frame) {
|
||||
this.retireCount = frame;
|
||||
}
|
||||
|
||||
private static void startupLogMessages(SimpleBufferBuilder bb, SimpleFont font, DisplayContext context) {
|
||||
List<StartupNotificationManager.AgeMessage> messages = StartupNotificationManager.getMessages();
|
||||
List<SimpleFont.DisplayText> texts = new ArrayList<>();
|
||||
for (int i = messages.size() - 1; i >= 0; i--) {
|
||||
final StartupNotificationManager.AgeMessage pair = messages.get(i);
|
||||
final float fade = Math.clamp((4000.0f - (float) pair.age() - ( i - 4 ) * 1000.0f) / 5000.0f, 0.0f, 1.0f);
|
||||
if (fade <0.01f) continue;
|
||||
Message msg = pair.message();
|
||||
int colour = Math.min((int)(fade * 255f), globalAlpha) << 24 | 0xFFFFFF;
|
||||
texts.add(new SimpleFont.DisplayText(msg.getText()+"\n", colour));
|
||||
}
|
||||
|
||||
font.generateVerticesForTexts(10, context.scaledHeight() - texts.size() * font.lineSpacing() + font.descent() - 10, bb, texts.toArray(SimpleFont.DisplayText[]::new));
|
||||
}
|
||||
|
||||
public static RenderElement mojang(final int textureId, final int frameStart) {
|
||||
return new RenderElement((bb, ctx, frame) -> {
|
||||
var size = 256 * ctx.scale();
|
||||
var x0 = (ctx.scaledWidth() - 2 * size) / 2;
|
||||
var y0 = 64 * ctx.scale() + 32;
|
||||
ctx.elementShader().updateTextureUniform(0);
|
||||
ctx.elementShader().updateRenderTypeUniform(ElementShader.RenderType.TEXTURE);
|
||||
var fade = Math.min((frame - frameStart) * 10, 255);
|
||||
glBindTexture(GL_TEXTURE_2D, textureId);
|
||||
bb.begin(SimpleBufferBuilder.Format.POS_TEX_COLOR, SimpleBufferBuilder.Mode.QUADS);
|
||||
QuadHelper.loadQuad(bb, x0, x0+size, y0, y0+size/2f, 0f, 1f, 0f, 0.5f, (fade << 24) | 0xFFFFFF);
|
||||
QuadHelper.loadQuad(bb, x0+size, x0+2*size, y0, y0+size/2f, 0f, 1f, 0.5f, 1f, (fade << 24) | 0xFFFFFF);
|
||||
bb.draw();
|
||||
glBindTexture(GL_TEXTURE_2D, 0);
|
||||
});
|
||||
}
|
||||
public static RenderElement logMessageOverlay(SimpleFont font) {
|
||||
return new RenderElement(RenderElement.initializeText(font, RenderElement::startupLogMessages));
|
||||
}
|
||||
|
||||
public static RenderElement forgeVersionOverlay(SimpleFont font, String version) {
|
||||
return new RenderElement(RenderElement.initializeText(font, (bb, _, ctx)->
|
||||
font.generateVerticesForTexts(ctx.scaledWidth() - font.stringWidth(version) - 10,
|
||||
ctx.scaledHeight() - font.lineSpacing() + font.descent() - 10, bb,
|
||||
new SimpleFont.DisplayText(version, ctx.colourScheme.foreground().packedint(RenderElement.globalAlpha)))));
|
||||
}
|
||||
public static RenderElement squir() {
|
||||
return new RenderElement(RenderElement.initializeTexture("squirrel.png", 45000, 3, (bb, context, size, frame) -> {
|
||||
var inset = 5f;
|
||||
var x0 = inset;
|
||||
var x1 = inset + size[0] * context.scale();
|
||||
var y0 = inset;
|
||||
var y1 = inset + size[1] * context.scale();
|
||||
int fade = (int) (Math.cos(frame * Math.PI / 16) * 16) + 16;
|
||||
// int fade = 0xff;
|
||||
var colour = (Math.min(fade, globalAlpha) & 0xff) << 24 | 0xffffff;
|
||||
QuadHelper.loadQuad(bb, x0, x1, y0, y1, 0f, 1f, 0f, 1f, colour);
|
||||
}));
|
||||
}
|
||||
|
||||
public static RenderElement anvil(SimpleFont font) {
|
||||
return new RenderElement(RenderElement.initializeTexture("forge_anvil.png", 20000, 2, (bb, context, size, frame) -> {
|
||||
var x0 = context.scaledWidth() - size[0] * context.scale();
|
||||
var x1 = context.scaledWidth();
|
||||
var y0 = context.scaledHeight() - size[0] * context.scale() - font.descent() - font.lineSpacing();
|
||||
var y1 = context.scaledHeight() - font.descent() - font.lineSpacing();
|
||||
int frameidx = frame % 32;
|
||||
float framepos = (frameidx * (float)size[0]) / size[1];
|
||||
float framesize = size[0] / (float)size[1];
|
||||
QuadHelper.loadQuad(bb, x0, x1, y0, y1, 0f, 1f, framepos, framepos+framesize, globalAlpha << 24 | 0xFFFFFF);
|
||||
}));
|
||||
}
|
||||
public static RenderElement progressBars(SimpleFont font) {
|
||||
return new RenderElement((bb, ctx, frame) -> RenderElement.startupProgressBars(font, bb, ctx, frame));
|
||||
}
|
||||
|
||||
public static RenderElement performanceBar(SimpleFont font) {
|
||||
return new RenderElement((bb, ctx, frame) -> RenderElement.memoryInfo(font, bb, ctx, frame));
|
||||
}
|
||||
|
||||
public static void startupProgressBars(SimpleFont font, final SimpleBufferBuilder buffer, final DisplayContext context, final int frameNumber) {
|
||||
Renderer acc = null;
|
||||
var barCount = 2;
|
||||
List<ProgressMeter> currentProgress = StartupNotificationManager.getCurrentProgress();
|
||||
var size = currentProgress.size();
|
||||
var alpha = 0xFF;
|
||||
for (int i = 0; i < barCount && i < size; i++) {
|
||||
final ProgressMeter pm = currentProgress.get(i);
|
||||
Renderer barRenderer = barRenderer(i, alpha, font, pm, context);
|
||||
acc = barRenderer.then(acc);
|
||||
alpha >>= 1;
|
||||
}
|
||||
if (acc != null)
|
||||
acc.accept(buffer, context, frameNumber);
|
||||
}
|
||||
private static final int BAR_HEIGHT = 20;
|
||||
private static final int BAR_WIDTH = 400;
|
||||
private static Renderer barRenderer(int cnt, int alpha, SimpleFont font, ProgressMeter pm, DisplayContext context) {
|
||||
var barSpacing = font.lineSpacing() - font.descent() + BAR_HEIGHT;
|
||||
var y = 250 * context.scale() + cnt * barSpacing;
|
||||
var colour = (alpha << 24) | 0xFFFFFF;
|
||||
Renderer bar;
|
||||
if (pm.steps() == 0) {
|
||||
bar = progressBar(ctx->new int[] {(ctx.scaledWidth() - BAR_WIDTH * ctx.scale()) / 2, y + font.lineSpacing() - font.descent(), BAR_WIDTH * ctx.scale()}, _->colour, frame -> indeterminateBar(frame, cnt == 0));
|
||||
} else {
|
||||
bar = progressBar(ctx -> new int[]{(ctx.scaledWidth() - BAR_WIDTH * ctx.scale()) / 2, y + font.lineSpacing() - font.descent(), BAR_WIDTH * ctx.scale()}, _ -> colour, _ -> new float[]{0f, pm.progress()});
|
||||
}
|
||||
Renderer label = (bb, ctx, _) -> renderText(font, text((ctx.scaledWidth() - BAR_WIDTH * ctx.scale()) / 2, y, pm.label().getText(), colour), bb, ctx);
|
||||
return bar.then(label);
|
||||
}
|
||||
private static float[] indeterminateBar(int frame, boolean isActive) {
|
||||
if (RenderElement.globalAlpha != 0xFF || !isActive) {
|
||||
return new float[] { 0f, 1f };
|
||||
} else {
|
||||
int progress = frame % 100;
|
||||
return new float[] { Math.clamp((progress - 2) / 100f, 0f, 1f), Math.clamp((progress + 2) / 100f, 0f, 1f) };
|
||||
}
|
||||
}
|
||||
|
||||
private static void memoryInfo(SimpleFont font, final SimpleBufferBuilder buffer, final DisplayContext context, final int frameNumber) {
|
||||
var y = 10 * context.scale();
|
||||
PerformanceInfo pi = context.performance();
|
||||
final int colour = hsvToRGB((1.0f - (float)Math.pow(pi.memory(), 1.5f)) / 3f, 1.0f, 0.5f);
|
||||
var bar = progressBar(ctx -> new int[]{(ctx.scaledWidth() - BAR_WIDTH * ctx.scale()) / 2, y, BAR_WIDTH * ctx.scale()}, _ -> colour, _ -> new float[]{0f, pi.memory()});
|
||||
var width = font.stringWidth(pi.text());
|
||||
Renderer label = (bb, ctx, _) -> renderText(font, text(ctx.scaledWidth() / 2 - width / 2, y + 18, pi.text(), context.colourScheme.foreground().packedint(globalAlpha)), bb, ctx);
|
||||
bar.then(label).accept(buffer, context, frameNumber);
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
interface ColourFunction {
|
||||
int colour(int frame);
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
interface ProgressDisplay {
|
||||
float[] progress(int frame);
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
interface BarPosition {
|
||||
int[] location(DisplayContext context);
|
||||
}
|
||||
public static Renderer progressBar(BarPosition position, ColourFunction colourFunction, ProgressDisplay progressDisplay) {
|
||||
return (bb, context, frame) -> {
|
||||
var colour = colourFunction.colour(frame);
|
||||
var alpha = (colour & 0xFF000000) >> 24;
|
||||
context.elementShader().updateTextureUniform(0);
|
||||
context.elementShader().updateRenderTypeUniform(ElementShader.RenderType.BAR);
|
||||
var progress = progressDisplay.progress(frame);
|
||||
bb.begin(SimpleBufferBuilder.Format.POS_TEX_COLOR, SimpleBufferBuilder.Mode.QUADS);
|
||||
var inset = 2;
|
||||
var pos = position.location(context);
|
||||
var x0 = pos[0];
|
||||
var x1 = pos[0] + pos[2] + 4 * inset;
|
||||
var y0 = pos[1];
|
||||
var y1 = y0 + BAR_HEIGHT;
|
||||
QuadHelper.loadQuad(bb, x0, x1, y0, y1, 0f, 0f, 0f, 0f, context.colourScheme().foreground().packedint(alpha));
|
||||
|
||||
x0 += inset;
|
||||
x1 -= inset;
|
||||
y0 += inset;
|
||||
y1 -= inset;
|
||||
QuadHelper.loadQuad(bb, x0, x1, y0, y1, 0f, 0f, 0f, 0f, context.colourScheme().background().packedint(RenderElement.globalAlpha));
|
||||
|
||||
x1 = x0 + inset + (int)(progress[1] * pos[2]);
|
||||
x0 += inset + progress[0] * pos[2];
|
||||
y0 += inset;
|
||||
y1 -= inset;
|
||||
QuadHelper.loadQuad(bb, x0, x1, y0, y1, 0f, 0f, 0f, 0f, colour);
|
||||
bb.draw();
|
||||
};
|
||||
}
|
||||
|
||||
private static Renderer initializeText(SimpleFont font, TextGenerator textGenerator) {
|
||||
return (bb, context, _) -> renderText(font, textGenerator, bb, context);
|
||||
}
|
||||
|
||||
private static void renderText(final SimpleFont font, final TextGenerator textGenerator, final SimpleBufferBuilder bb, final DisplayContext context) {
|
||||
context.elementShader().updateTextureUniform(font.textureNumber());
|
||||
context.elementShader().updateRenderTypeUniform(ElementShader.RenderType.FONT);
|
||||
bb.begin(SimpleBufferBuilder.Format.POS_TEX_COLOR, SimpleBufferBuilder.Mode.QUADS);
|
||||
textGenerator.accept(bb, font, context);
|
||||
bb.draw();
|
||||
}
|
||||
|
||||
private static TextGenerator text(int x, int y, String text, int colour) {
|
||||
return (bb, font, _) -> font.generateVerticesForTexts(x, y, bb, new SimpleFont.DisplayText(text, colour));
|
||||
}
|
||||
|
||||
private static Renderer initializeTexture(final String textureFileName, int size, int textureNumber, TextureRenderer positionAndColour) {
|
||||
int[] imgSize = STBHelper.loadTextureFromClasspath(textureFileName, size, GL_TEXTURE0 + textureNumber + INDEX_TEXTURE_OFFSET);
|
||||
return (bb, ctx, frame) -> {
|
||||
ctx.elementShader().updateTextureUniform(textureNumber + INDEX_TEXTURE_OFFSET);
|
||||
ctx.elementShader().updateRenderTypeUniform(ElementShader.RenderType.TEXTURE);
|
||||
renderTexture(bb, ctx, frame, imgSize, positionAndColour);
|
||||
};
|
||||
}
|
||||
|
||||
private static void renderTexture(SimpleBufferBuilder bb, DisplayContext context, int frame, int[] size, TextureRenderer positionAndColour) {
|
||||
bb.begin(SimpleBufferBuilder.Format.POS_TEX_COLOR, SimpleBufferBuilder.Mode.QUADS);
|
||||
positionAndColour.accept(bb, context, size, frame);
|
||||
bb.draw();
|
||||
}
|
||||
|
||||
@Deprecated(since = "1.21.5", forRemoval = true)
|
||||
public static float clamp(float num, float min, float max) {
|
||||
return Math.clamp(num, min, max);
|
||||
}
|
||||
|
||||
public static int clamp(int num, int min, int max) {
|
||||
return Math.min(max, Math.max(num, min));
|
||||
}
|
||||
|
||||
public static int hsvToRGB(float hue, float saturation, float value) {
|
||||
int i = (int)(hue * 6.0F) % 6;
|
||||
float f = hue * 6.0F - (float)i;
|
||||
float f1 = value * (1.0F - saturation);
|
||||
float f2 = value * (1.0F - f * saturation);
|
||||
float f3 = value * (1.0F - (1.0F - f) * saturation);
|
||||
float f4;
|
||||
float f5;
|
||||
float f6;
|
||||
switch(i) {
|
||||
case 0:
|
||||
f4 = value;
|
||||
f5 = f3;
|
||||
f6 = f1;
|
||||
break;
|
||||
case 1:
|
||||
f4 = f2;
|
||||
f5 = value;
|
||||
f6 = f1;
|
||||
break;
|
||||
case 2:
|
||||
f4 = f1;
|
||||
f5 = value;
|
||||
f6 = f3;
|
||||
break;
|
||||
case 3:
|
||||
f4 = f1;
|
||||
f5 = f2;
|
||||
f6 = value;
|
||||
break;
|
||||
case 4:
|
||||
f4 = f3;
|
||||
f5 = f1;
|
||||
f6 = value;
|
||||
break;
|
||||
case 5:
|
||||
f4 = value;
|
||||
f5 = f1;
|
||||
f6 = f2;
|
||||
break;
|
||||
default:
|
||||
throw new RuntimeException("Something went wrong when converting from HSV to RGB. Input was " + hue + ", " + saturation + ", " + value);
|
||||
}
|
||||
|
||||
int j = clamp((int)(f4 * 255.0F), 0, 255);
|
||||
int k = clamp((int)(f5 * 255.0F), 0, 255);
|
||||
int l = clamp((int)(f6 * 255.0F), 0, 255);
|
||||
return 0xFF << 24 | j << 16 | k << 8 | l;
|
||||
}
|
||||
}
|
||||
@@ -1,65 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.earlydisplay;
|
||||
|
||||
import org.lwjgl.BufferUtils;
|
||||
import org.lwjgl.stb.STBImage;
|
||||
import org.lwjgl.system.MemoryUtil;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.Channels;
|
||||
import java.util.Objects;
|
||||
|
||||
import static org.lwjgl.opengl.GL32C.*;
|
||||
|
||||
public class STBHelper {
|
||||
public static ByteBuffer readFromClasspath(final String name, int initialCapacity) {
|
||||
ByteBuffer buf;
|
||||
try (var channel = Channels.newChannel(
|
||||
Objects.requireNonNull(STBHelper.class.getClassLoader().getResourceAsStream(name), "The resource "+name+" cannot be found"))) {
|
||||
buf = BufferUtils.createByteBuffer(initialCapacity);
|
||||
while (true) {
|
||||
var readbytes = channel.read(buf);
|
||||
if (readbytes == -1) break;
|
||||
if (buf.remaining() == 0) { // extend the buffer by 50%
|
||||
var newBuf = BufferUtils.createByteBuffer(buf.capacity() * 3 / 2);
|
||||
buf.flip();
|
||||
newBuf.put(buf);
|
||||
buf = newBuf;
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
buf.flip();
|
||||
return MemoryUtil.memSlice(buf); // we trim the final buffer to the size of the content
|
||||
}
|
||||
|
||||
public static int[] loadTextureFromClasspath(String file, int size, int textureNumber) {
|
||||
int[] lw = new int[1];
|
||||
int[] lh = new int[1];
|
||||
int[] lc = new int[1];
|
||||
var img = loadImageFromClasspath(file, size, lw, lh, lc);
|
||||
var texid = glGenTextures();
|
||||
glActiveTexture(textureNumber);
|
||||
glBindTexture(GL_TEXTURE_2D, texid);
|
||||
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
|
||||
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
|
||||
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, lw[0], lh[0], 0, GL_RGBA, GL_UNSIGNED_BYTE, img);
|
||||
glActiveTexture(GL_TEXTURE0);
|
||||
MemoryUtil.memFree(img);
|
||||
return new int[] {lw[0], lh[0]};
|
||||
}
|
||||
|
||||
public static ByteBuffer loadImageFromClasspath(String file, int size, int[] width, int[] height, int[] channels) {
|
||||
ByteBuffer buf = STBHelper.readFromClasspath(file, size);
|
||||
return STBImage.stbi_load_from_memory(buf, width, height, channels, 4);
|
||||
}
|
||||
}
|
||||
-517
@@ -1,517 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.earlydisplay;
|
||||
|
||||
import org.lwjgl.system.MemoryUtil;
|
||||
|
||||
import java.io.Closeable;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.Arrays;
|
||||
|
||||
import static org.lwjgl.opengl.GL32C.*;
|
||||
|
||||
/**
|
||||
* A very simple, Mojang inspired BufferBuilder.
|
||||
* <em>This has been customized for 2d rendering such as text and simple planar textures</em>
|
||||
* <p>
|
||||
* Not bound to any specific format, ideally should be held onto for re-use.
|
||||
* <p>
|
||||
* Can be used for 'immediate mode' style rendering using {@link #draw()}, or
|
||||
* upload to external vertex arrays for proper instancing using {@link #finishAndUpload()}.
|
||||
* <p>
|
||||
* This is a Triangles only buffer, all data uploaded is in Triangles.
|
||||
* Quads are converted to triangles using {@code 0, 1, 2, 0, 2, 3}.
|
||||
* <p>
|
||||
* Any given {@link Format} should have its individual {@link Element} components
|
||||
* buffered in the order specified by the {@link Format},
|
||||
* followed by an {@link #endVertex()} call to prepare for the next vertex.
|
||||
* <p>
|
||||
* It is illegal to buffer primitives in any format other than the one specified to
|
||||
* {@link #begin(Format, Mode)}.
|
||||
*
|
||||
* @author covers1624
|
||||
*/
|
||||
public class SimpleBufferBuilder implements Closeable {
|
||||
|
||||
private static final MemoryUtil.MemoryAllocator ALLOCATOR = MemoryUtil.getAllocator(false);
|
||||
|
||||
private static final int[] VERTEX_ARRAYS = new int[Format.values().length];
|
||||
private static final int[] VERTEX_BUFFERS = new int[Format.values().length];
|
||||
private static final int[] VERTEX_BUFFER_LENGTHS = new int[Format.values().length];
|
||||
private static int elementBuffer = 0;
|
||||
private static int elementBufferVertexLength = 0;
|
||||
|
||||
static {
|
||||
Arrays.fill(VERTEX_ARRAYS, 0);
|
||||
Arrays.fill(VERTEX_BUFFERS, 0);
|
||||
Arrays.fill(VERTEX_BUFFER_LENGTHS, 0);
|
||||
}
|
||||
|
||||
private long bufferAddr; // Pointer to the backing buffer.
|
||||
private ByteBuffer buffer; // ByteBuffer view of the backing buffer.
|
||||
|
||||
private Format format; // The current format we are buffering.
|
||||
private Mode mode; // The current mode we are buffering.
|
||||
private boolean building; // If we are building the buffer.
|
||||
private int elementIndex; // The current element index we are buffering. if elementIndex == format.types.length, we expect 'endVertex'
|
||||
private int index; // The current index into the buffer we are writing to.
|
||||
private int vertices; // The number of complete vertices we have buffered.
|
||||
|
||||
/**
|
||||
* Create a new SimpleBufferBuilder with an initial capacity.
|
||||
* <p>
|
||||
* The buffer will be doubled as required.
|
||||
* <p>
|
||||
* Generally picking a small number, around 128/256 should be a
|
||||
* safe bet. Provided you cache your buffers, it should not mean much overall.
|
||||
*
|
||||
* @param capacity The initial capacity in bytes.
|
||||
*/
|
||||
public SimpleBufferBuilder(int capacity) {
|
||||
bufferAddr = ALLOCATOR.malloc(capacity);
|
||||
buffer = MemoryUtil.memByteBuffer(bufferAddr, capacity);
|
||||
}
|
||||
|
||||
public static void destroy() {
|
||||
glDeleteBuffers(VERTEX_BUFFERS);
|
||||
glDeleteBuffers(elementBuffer);
|
||||
glDeleteVertexArrays(VERTEX_ARRAYS);
|
||||
}
|
||||
|
||||
private static void ensureElementBufferLength(int vertices) {
|
||||
if (elementBufferVertexLength >= vertices) {
|
||||
return;
|
||||
}
|
||||
|
||||
// treating it as immutable storage, even though it's not
|
||||
final var newElementBuffer = glGenBuffers();
|
||||
var newElementBufferVertexLength = Math.max(1024, elementBufferVertexLength);
|
||||
while (newElementBufferVertexLength < vertices) {
|
||||
newElementBufferVertexLength *= 2;
|
||||
}
|
||||
|
||||
final var oldIndexCount = elementBufferVertexLength + elementBufferVertexLength / 2;
|
||||
final var newIndexCount = newElementBufferVertexLength + newElementBufferVertexLength / 2;
|
||||
|
||||
// allocate new buffer
|
||||
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, newElementBuffer);
|
||||
glBufferData(GL_ELEMENT_ARRAY_BUFFER, newIndexCount * 4L, GL_STATIC_DRAW);
|
||||
|
||||
// mapping avoids creating additional CPU copies of the data
|
||||
// unsynchronized is fine because this is a brand-new buffer, and the old contents will be copied in afterward
|
||||
// also can invalidate the whole buffer too, similarly because brand new, don't care what was there before
|
||||
final var mappingOffset = oldIndexCount * 4;
|
||||
final var mappingSize = (newIndexCount - oldIndexCount) * 4;
|
||||
final var mappedBuffer = glMapBufferRange(GL_ELEMENT_ARRAY_BUFFER, mappingOffset, mappingSize, GL_MAP_WRITE_BIT | GL_MAP_UNSYNCHRONIZED_BIT | GL_MAP_INVALIDATE_BUFFER_BIT);
|
||||
|
||||
if(mappedBuffer == null){
|
||||
throw new NullPointerException("OpenGL buffer mapping failed");
|
||||
}
|
||||
|
||||
final int quads = newElementBufferVertexLength / 4;
|
||||
final int oldQuads = elementBufferVertexLength / 4;
|
||||
// generate indices for the extension to the buffer
|
||||
for (int i = oldQuads; i < quads; i++) {
|
||||
// Quads are a bit different, we need to emit 2 triangles such that
|
||||
// when combined they make up a single quad.
|
||||
mappedBuffer.putInt(i * 4 + 0).putInt(i * 4 + 1).putInt(i * 4 + 2);
|
||||
mappedBuffer.putInt(i * 4 + 1).putInt(i * 4 + 3).putInt(i * 4 + 2);
|
||||
}
|
||||
|
||||
glUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER);
|
||||
|
||||
if (elementBuffer != 0) {
|
||||
// copy old data from previous element buffer
|
||||
glBindBuffer(GL_COPY_READ_BUFFER, elementBuffer);
|
||||
glCopyBufferSubData(GL_COPY_READ_BUFFER, GL_ELEMENT_ARRAY_BUFFER, 0, 0, mappingOffset);
|
||||
glBindBuffer(GL_COPY_READ_BUFFER, 0);
|
||||
}
|
||||
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
|
||||
|
||||
glDeleteBuffers(elementBuffer);
|
||||
elementBuffer = newElementBuffer;
|
||||
elementBufferVertexLength = newElementBufferVertexLength;
|
||||
}
|
||||
|
||||
/**
|
||||
* Start building a new set of vertex data in the
|
||||
* given format and mode.
|
||||
*
|
||||
* @param format The format to start building in.
|
||||
* @param mode The mode to start building in.
|
||||
*/
|
||||
public SimpleBufferBuilder begin(Format format, Mode mode) {
|
||||
if (bufferAddr == MemoryUtil.NULL) {
|
||||
throw new IllegalStateException("Buffer has been freed."); // You already free'd the buffer
|
||||
}
|
||||
if (building) {
|
||||
throw new IllegalStateException("Already building."); // Your already building verticies.
|
||||
}
|
||||
this.format = format;
|
||||
this.mode = mode;
|
||||
building = true;
|
||||
elementIndex = 0;
|
||||
ensureSpace(format.stride);
|
||||
// Rewind ready for new data.
|
||||
buffer.rewind();
|
||||
buffer.limit(buffer.capacity());
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Buffer a position element.
|
||||
*
|
||||
* @param x The x.
|
||||
* @param y The y.
|
||||
* @param z The z.
|
||||
* @return The same builder.
|
||||
*/
|
||||
public SimpleBufferBuilder pos(float x, float y) {
|
||||
if (!building) throw new IllegalStateException("Not building."); // You did not call begin.
|
||||
|
||||
if (elementIndex == format.types.length) throw new IllegalStateException("Expected endVertex"); // we have reached the end of elements to buffer for this vertex, we expected an endVertex call.
|
||||
if (format.types[elementIndex] != Element.POS) throw new IllegalArgumentException("Expected " + format.types[elementIndex]); // You called the wrong method for the format order.
|
||||
|
||||
// Assumes that our POS element specifies the FLOAT data type.
|
||||
buffer.putFloat(index + 0, x);
|
||||
buffer.putFloat(index + 4, y);
|
||||
|
||||
// Increment index for the number of bytes we wrote and increment the element index.
|
||||
index += format.types[elementIndex].width;
|
||||
elementIndex++;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Buffer a texture element.
|
||||
*
|
||||
* @param u The u.
|
||||
* @param v The v.
|
||||
* @return The same builder.
|
||||
*/
|
||||
public SimpleBufferBuilder tex(float u, float v) {
|
||||
if (!building) throw new IllegalStateException("Not building."); // You did not call begin.
|
||||
|
||||
if (elementIndex == format.types.length) throw new IllegalStateException("Expected endVertex"); // we have reached the end of elements to buffer for this vertex, we expected an endVertex call.
|
||||
if (format.types[elementIndex] != Element.TEX) throw new IllegalArgumentException("Expected " + format.types[elementIndex]); // You called the wrong method for the format order.
|
||||
|
||||
// Assumes our TEX element specifies the FLOAT data type.
|
||||
buffer.putFloat(index + 0, u);
|
||||
buffer.putFloat(index + 4, v);
|
||||
|
||||
// Increment index for the number of bytes we wrote and increment the element index.
|
||||
index += format.types[elementIndex].width;
|
||||
elementIndex++;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Buffer a color element.
|
||||
*
|
||||
* @param r The red component. (0-1)
|
||||
* @param g The green component. (0-1)
|
||||
* @param b The blue component. (0-1)
|
||||
* @param a The alpha component. (0-1)
|
||||
* @return The same buffer.
|
||||
*/
|
||||
public SimpleBufferBuilder colour(float r, float g, float b, float a) {
|
||||
// Expand floats to 0-255 and forward.
|
||||
return colour((byte) (r * 255F), (byte) (g * 255F), (byte) (b * 255F), (byte) (a * 255F));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see ColourScheme.Colour#packedint(int)
|
||||
* @param packedColor an ABGR packed int
|
||||
* @return the same buffer.
|
||||
*/
|
||||
public SimpleBufferBuilder colour(int packedColor) {
|
||||
if (!building) throw new IllegalStateException("Not building."); // You did not call begin.
|
||||
|
||||
if (elementIndex == format.types.length) throw new IllegalStateException("Expected endVertex"); // we have reached the end of elements to buffer for this vertex, we expected an endVertex call.
|
||||
if (format.types[elementIndex] != Element.COLOR) throw new IllegalArgumentException("Expected " + format.types[elementIndex]); // You called the wrong method for the format order.
|
||||
|
||||
// Assumes our COLOR element specifies the UNSIGNED_BYTE data type.
|
||||
buffer.putInt(index + 0, packedColor);
|
||||
|
||||
// Increment index for the number of bytes we wrote and increment the element index.
|
||||
index += format.types[elementIndex].width;
|
||||
elementIndex++;
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Buffer a color element.
|
||||
*
|
||||
* @param r The red component. (0-255)
|
||||
* @param g The green component. (0-255)
|
||||
* @param b The blue component. (0-255)
|
||||
* @param a The alpha component. (0-255)
|
||||
* @return The same buffer.
|
||||
*/
|
||||
public SimpleBufferBuilder colour(byte r, byte g, byte b, byte a) {
|
||||
if (!building) throw new IllegalStateException("Not building."); // You did not call begin.
|
||||
|
||||
if (elementIndex == format.types.length) throw new IllegalStateException("Expected endVertex"); // we have reached the end of elements to buffer for this vertex, we expected an endVertex call.
|
||||
if (format.types[elementIndex] != Element.COLOR) throw new IllegalArgumentException("Expected " + format.types[elementIndex]); // You called the wrong method for the format order.
|
||||
|
||||
// Assumes our COLOR element specifies the UNSIGNED_BYTE data type.
|
||||
buffer.put(index + 0, r);
|
||||
buffer.put(index + 1, g);
|
||||
buffer.put(index + 2, b);
|
||||
buffer.put(index + 3, a);
|
||||
|
||||
// Increment index for the number of bytes we wrote and increment the element index.
|
||||
index += format.types[elementIndex].width;
|
||||
elementIndex++;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* End building the current vertex and prepare for the next.
|
||||
*
|
||||
* @return The same builder.
|
||||
*/
|
||||
public SimpleBufferBuilder endVertex() {
|
||||
if (!building) throw new IllegalStateException("Not building."); // You did not call begin.
|
||||
|
||||
if (elementIndex != format.types.length) throw new IllegalStateException("Expected " + format.types[elementIndex]); // You did not finish building the vertex.
|
||||
|
||||
// Reset elementIndex
|
||||
elementIndex = 0;
|
||||
// Increment the number of vertices we have so far buffered.
|
||||
vertices++;
|
||||
// Make sure there is space for the next vertex.
|
||||
ensureSpace(format.stride);
|
||||
return this;
|
||||
}
|
||||
|
||||
// Checks there is enough space in the buffer for specified number of bytes.
|
||||
// If there is not enough space, the buffer is increased by 50%.
|
||||
private void ensureSpace(int newBytes) {
|
||||
int cap = buffer.capacity();
|
||||
if (index + newBytes > cap) {
|
||||
int newCap = Math.max(3 * cap / 2, 3 * newBytes / 2);
|
||||
bufferAddr = ALLOCATOR.realloc(bufferAddr, newCap);
|
||||
buffer = MemoryUtil.memByteBuffer(bufferAddr, newCap);
|
||||
buffer.rewind();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload the current buffer.
|
||||
* <p>
|
||||
* This will bind a {@link org.lwjgl.opengl.GL32C#GL_ARRAY_BUFFER} and {@link org.lwjgl.opengl.GL32C#GL_ELEMENT_ARRAY_BUFFER}
|
||||
* <p>
|
||||
* The vertex data and index data is uploaded to their respective buffers.
|
||||
* <p>
|
||||
* Uploading the buffers finishes drawing and resets for the next buffer operation.
|
||||
* <p>
|
||||
* This should not be called in conjunction with {@link #draw()}
|
||||
*
|
||||
* @return The number of indexes that were uploaded.
|
||||
*/
|
||||
public int finishAndUpload() {
|
||||
if (!building) throw new IllegalStateException("Not building.");
|
||||
|
||||
int indices;
|
||||
try {
|
||||
if (elementIndex == format.types.length) throw new IllegalStateException("Expected endVertex"); // You didn't finish building your vertex.
|
||||
if (elementIndex != 0) throw new IllegalStateException("Not finished building vertex, Expected: " + format.types[elementIndex]); // You didn't finish building your vertex data.
|
||||
if (vertices == 0) return 0; // No vertices buffered, lets not do anything.
|
||||
if (vertices % mode.vertices != 0) throw new IllegalStateException("Does not contain vertices aligned to " + mode); // You did not put in enough vertices to cleanly slice the data into TRIANGLES/QUADS
|
||||
|
||||
// Reset position to 0, limit the buffer to our index.
|
||||
buffer.position(0);
|
||||
buffer.limit(index);
|
||||
|
||||
// Upload the raw vertex data in dynamic mode.
|
||||
final int vbo = VERTEX_BUFFERS[format.ordinal()];
|
||||
final int vboSize = VERTEX_BUFFER_LENGTHS[format.ordinal()];
|
||||
glBindBuffer(GL_ARRAY_BUFFER, vbo);
|
||||
if (vboSize < index) {
|
||||
// expand buffer, it's not big enough
|
||||
var newVBOSize = Math.max(1024, vboSize);
|
||||
while (newVBOSize < index){
|
||||
newVBOSize *= 2;
|
||||
}
|
||||
// because everything is overwritten anyway, we can do an in-place reallocation
|
||||
glBufferData(GL_ARRAY_BUFFER, newVBOSize, GL_DYNAMIC_DRAW);
|
||||
VERTEX_BUFFER_LENGTHS[format.ordinal()] = newVBOSize;
|
||||
}
|
||||
glBufferSubData(GL_ARRAY_BUFFER, 0, buffer);
|
||||
|
||||
// The number of indices for triangles is equal to our vertex count, as that is
|
||||
// what we operate in. However, for Quads, we have exactly vertices + vertices / 2
|
||||
// vertices once we convert the quads to triangles.
|
||||
indices = mode == Mode.TRIANGLES ? vertices : vertices + vertices / 2;
|
||||
|
||||
if (mode == Mode.QUADS) {
|
||||
ensureElementBufferLength(vertices);
|
||||
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementBuffer);
|
||||
}
|
||||
|
||||
return indices;
|
||||
} finally {
|
||||
// Reset builder state for next begin call.
|
||||
building = false;
|
||||
vertices = 0;
|
||||
index = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload and draw this buffer using one of a number of re-usable set of buffers.
|
||||
* <p>
|
||||
* This will immediately upload the buffer, resetting this builder for the next
|
||||
* buffer operation, and draw the uploaded data.
|
||||
* <p>
|
||||
* You will need to bind shaders, textures, etc, before calling this function.
|
||||
*/
|
||||
public void draw() {
|
||||
if (!building) throw new IllegalStateException("Not building.");
|
||||
|
||||
int vao = VERTEX_ARRAYS[format.ordinal()];
|
||||
int vbo = VERTEX_BUFFERS[format.ordinal()];
|
||||
|
||||
if (vao == 0) {
|
||||
// These 3 buffers are paired, you can't allocate one without the others.
|
||||
assert vbo == 0;
|
||||
|
||||
// Make new vertex array and buffers!
|
||||
vao = glGenVertexArrays();
|
||||
vbo = glGenBuffers();
|
||||
|
||||
// Cache the vertex array and buffers for future re-use.
|
||||
VERTEX_ARRAYS[format.ordinal()] = vao;
|
||||
VERTEX_BUFFERS[format.ordinal()] = vbo;
|
||||
|
||||
// Ask our Format to set up its data layout for the vertex array.
|
||||
// but only once, the VAO saves this state
|
||||
glBindVertexArray(vao);
|
||||
glBindBuffer(GL_ARRAY_BUFFER, vbo);
|
||||
format.bind();
|
||||
format.enable();
|
||||
}
|
||||
// Bind the vertex array and buffers!
|
||||
glBindVertexArray(vao);
|
||||
|
||||
// Upload the data.
|
||||
int indices = finishAndUpload();
|
||||
|
||||
if (mode == Mode.QUADS) {
|
||||
glDrawElements(GL_TRIANGLES, indices, GL_UNSIGNED_INT, 0);
|
||||
} else {
|
||||
glDrawArrays(GL_TRIANGLES, 0, indices);
|
||||
}
|
||||
|
||||
// Unbind the vertex array.
|
||||
glBindVertexArray(0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear this builder's cached buffer.
|
||||
* <p>
|
||||
* If you are completely done, call {@link #destroy()}
|
||||
*/
|
||||
@Override
|
||||
public void close() {
|
||||
ALLOCATOR.free(bufferAddr);
|
||||
bufferAddr = MemoryUtil.NULL;
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents a primitive mode that this builder is capable of buffering in.
|
||||
*/
|
||||
public enum Mode {
|
||||
TRIANGLES(3),
|
||||
QUADS(4),
|
||||
;
|
||||
|
||||
public final int vertices;
|
||||
|
||||
Mode(int vertices) {
|
||||
this.vertices = vertices;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Specifies a vertex element with a specific data type, number of primitives and a size in bytes.
|
||||
*/
|
||||
public enum Element {
|
||||
POS(GL_FLOAT, 2, 2 * 4),
|
||||
TEX(GL_FLOAT, 2, 2 * 4),
|
||||
COLOR(GL_UNSIGNED_BYTE, 4, 4);
|
||||
|
||||
public final int glType;
|
||||
public final int count;
|
||||
public final int width;
|
||||
|
||||
Element(int glType, int count, int width) {
|
||||
this.glType = glType;
|
||||
this.count = count;
|
||||
this.width = width;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Specifies a combination of vertex elements.
|
||||
*/
|
||||
public enum Format {
|
||||
POS(Element.POS),
|
||||
POS_TEX(Element.POS, Element.TEX),
|
||||
POS_COLOR(Element.POS, Element.COLOR),
|
||||
POS_TEX_COLOR(Element.POS, Element.TEX, Element.COLOR);
|
||||
|
||||
private final Element[] types;
|
||||
public final int stride;
|
||||
|
||||
Format(Element... types) {
|
||||
this.types = types;
|
||||
|
||||
// Stride is the width of each vertex in bytes.
|
||||
stride = Arrays.stream(types).mapToInt(e -> e.width).sum();
|
||||
}
|
||||
|
||||
/**
|
||||
* set up the attribute pointers for this format.
|
||||
* <p>
|
||||
* Assumes that an array buffer is already bound and ready to go.
|
||||
*/
|
||||
public void bind() {
|
||||
int offset = 0;
|
||||
|
||||
// Set up the pointers that tell GL where our interleaved
|
||||
// vertex data is in the buffers.
|
||||
for (int i = 0; i < types.length; i++) {
|
||||
Element type = types[i];
|
||||
switch (type.glType) {
|
||||
case GL_FLOAT -> glVertexAttribPointer(i, type.count, GL_FLOAT, false, stride, offset);
|
||||
case GL_UNSIGNED_BYTE -> glVertexAttribPointer(i, type.count, GL_UNSIGNED_BYTE, true, stride, offset);
|
||||
default -> throw new IllegalStateException("Unknown glType, I don't know how to bind this vertex element: " + type);
|
||||
}
|
||||
// add to the offset for the next element.
|
||||
offset += type.width;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Enables the vertex attributes this format contains.
|
||||
*/
|
||||
public void enable() {
|
||||
for (int i = 0; i < types.length; i++) {
|
||||
glEnableVertexAttribArray(i);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Disables the vertex attributes this format contains.
|
||||
*/
|
||||
public void disable() {
|
||||
for (int i = 0; i < types.length; i++) {
|
||||
glDisableVertexAttribArray(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,180 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.earlydisplay;
|
||||
|
||||
import org.lwjgl.BufferUtils;
|
||||
import org.lwjgl.stb.STBTTAlignedQuad;
|
||||
import org.lwjgl.stb.STBTTFontinfo;
|
||||
import org.lwjgl.stb.STBTTPackContext;
|
||||
import org.lwjgl.stb.STBTTPackRange;
|
||||
import org.lwjgl.stb.STBTTPackedchar;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
import static org.lwjgl.opengl.GL32C.*;
|
||||
import static org.lwjgl.stb.STBTruetype.*;
|
||||
import static org.lwjgl.system.MemoryUtil.NULL;
|
||||
|
||||
public class SimpleFont {
|
||||
private final int textureNumber;
|
||||
private final int lineSpacing;
|
||||
private final int descent;
|
||||
private static final int GLYPH_COUNT = 127 - 32;
|
||||
private final Glyph[] glyphs;
|
||||
|
||||
private record Glyph(char c, int charwidth, int[] pos, float[] uv) {
|
||||
Pos loadQuad(Pos pos, int colour, SimpleBufferBuilder bb) {
|
||||
final var x0 = pos.x() + pos()[0];
|
||||
final var y0 = pos.y() + pos()[1];
|
||||
final var x1 = pos.x() + pos()[2];
|
||||
final var y1 = pos.y() + pos()[3];
|
||||
bb.pos(x0, y0).tex(uv()[0], uv()[1]).colour(colour).endVertex();
|
||||
bb.pos(x1, y0).tex(uv()[2], uv()[1]).colour(colour).endVertex();
|
||||
bb.pos(x0, y1).tex(uv()[0], uv()[3]).colour(colour).endVertex();
|
||||
bb.pos(x1, y1).tex(uv()[2], uv()[3]).colour(colour).endVertex();
|
||||
return new Pos(pos.x()+charwidth(), pos.y(), pos.minx());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the font and store it in the textureNumber location
|
||||
*/
|
||||
public SimpleFont(String fontName, int scale, int bufferSize, int textureNumber) {
|
||||
ByteBuffer buf = STBHelper.readFromClasspath(fontName, bufferSize);
|
||||
var info = STBTTFontinfo.create();
|
||||
if (!stbtt_InitFont(info, buf)) {
|
||||
throw new IllegalStateException("Bad font");
|
||||
}
|
||||
|
||||
var ascent = new float[1];
|
||||
var descent = new float[1];
|
||||
var lineGap = new float[1];
|
||||
int fontSize = 24;
|
||||
stbtt_GetScaledFontVMetrics(buf, 0, fontSize, ascent, descent, lineGap);
|
||||
this.lineSpacing = (int)(ascent[0] - descent[0] + lineGap[0]);
|
||||
this.descent = (int)Math.floor(descent[0]);
|
||||
int fontTextureId = glGenTextures();
|
||||
glActiveTexture(GL_TEXTURE0+textureNumber);
|
||||
this.textureNumber = textureNumber;
|
||||
glBindTexture(GL_TEXTURE_2D, fontTextureId);
|
||||
try (var packedchars = STBTTPackedchar.malloc(GLYPH_COUNT)) {
|
||||
int texwidth = 256;
|
||||
int texheight = 128;
|
||||
try (STBTTPackRange.Buffer packRanges = STBTTPackRange.malloc(1)) {
|
||||
var bitmap = BufferUtils.createByteBuffer(texwidth * texheight);
|
||||
try (STBTTPackRange packRange = STBTTPackRange.malloc()) {
|
||||
packRanges.put(packRange.set(fontSize, 32, null, GLYPH_COUNT, packedchars, (byte) 1, (byte) 1));
|
||||
packRanges.flip();
|
||||
}
|
||||
|
||||
try (STBTTPackContext pc = STBTTPackContext.malloc()) {
|
||||
stbtt_PackBegin(pc, bitmap, texwidth, texheight, 0, 1, NULL);
|
||||
stbtt_PackSetOversampling(pc, 1, 1);
|
||||
stbtt_PackSetSkipMissingCodepoints(pc, true);
|
||||
stbtt_PackFontRanges(pc, buf, 0, packRanges);
|
||||
stbtt_PackEnd(pc);
|
||||
glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, texwidth, texheight, 0, GL_RED, GL_UNSIGNED_BYTE, bitmap);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
|
||||
}
|
||||
}
|
||||
glActiveTexture(GL_TEXTURE0);
|
||||
try (var q = STBTTAlignedQuad.malloc()) {
|
||||
float[] x = new float[1];
|
||||
float[] y = new float[1];
|
||||
glyphs = new Glyph[GLYPH_COUNT];
|
||||
|
||||
for (int i = 0; i < GLYPH_COUNT; i++) {
|
||||
x[0] = 0f;
|
||||
y[0] = fontSize;
|
||||
stbtt_GetPackedQuad(packedchars, texwidth, texheight, i, x, y, q, true);
|
||||
glyphs[i] = new Glyph((char) (i + 32), (int) (x[0] - 0f), new int[]{(int) q.x0(), (int) q.y0(), (int) q.x1(), (int) q.y1()}, new float[]{q.s0(), q.t0(), q.s1(), q.t1()});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int lineSpacing() {
|
||||
return lineSpacing;
|
||||
}
|
||||
|
||||
int textureNumber() {
|
||||
return textureNumber;
|
||||
}
|
||||
|
||||
int descent() {
|
||||
return descent;
|
||||
}
|
||||
|
||||
public int stringWidth(String text) {
|
||||
var bytes = text.getBytes(StandardCharsets.US_ASCII);
|
||||
int len = 0;
|
||||
for (int i = 0; i < bytes.length; i++) {
|
||||
final byte c = bytes[i];
|
||||
len += switch (c) {
|
||||
case '\n', '\t' -> 0;
|
||||
case ' ' -> glyphs[0].charwidth();
|
||||
default -> {
|
||||
if (c - 32 < GLYPH_COUNT && c > 32) {
|
||||
yield this.glyphs[c - 32].charwidth();
|
||||
} else {
|
||||
yield 0;
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
return len;
|
||||
}
|
||||
private record Pos(int x, int y, int minx) {}
|
||||
|
||||
/**
|
||||
* A piece of text to display
|
||||
*
|
||||
* @param string The text
|
||||
* @param colour The colour of the text as an RGBA packed int
|
||||
*/
|
||||
public record DisplayText(String string, int colour) {
|
||||
private byte[] asBytes() {
|
||||
return string.getBytes(StandardCharsets.US_ASCII);
|
||||
}
|
||||
|
||||
Pos generateStringArray(SimpleFont font, Pos pos, SimpleBufferBuilder bb) {
|
||||
for (int i = 0; i < asBytes().length; i++) {
|
||||
byte c = asBytes()[i];
|
||||
pos = switch (c) {
|
||||
case '\n' -> new Pos(pos.minx(), pos.y()+font.lineSpacing(), pos.minx());
|
||||
case '\t' -> new Pos(pos.x()+font.glyphs[0].charwidth() * 4, pos.y(), pos.minx());
|
||||
case ' ' -> new Pos(pos.x()+font.glyphs[0].charwidth(), pos.y(), pos.minx());
|
||||
default -> {
|
||||
if (c-32 < GLYPH_COUNT && c > 32) {
|
||||
pos = font.glyphs[c - 32].loadQuad(pos, colour(), bb);
|
||||
}
|
||||
yield pos;
|
||||
}
|
||||
};
|
||||
}
|
||||
return pos;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate vertices for a set of display texts
|
||||
* @param x The starting screen x coordinate
|
||||
* @param y The starting screen y coordinate
|
||||
* @param texts Some {@link DisplayText} to display
|
||||
* @return a {@link SimpleBufferBuilder} that can draw the texts
|
||||
*/
|
||||
public SimpleBufferBuilder generateVerticesForTexts(int x, int y, SimpleBufferBuilder textBB, DisplayText... texts) {
|
||||
var pos = new Pos(x, y, x);
|
||||
for (DisplayText text : texts) {
|
||||
pos = text.generateStringArray(this, pos, textBB);
|
||||
}
|
||||
return textBB;
|
||||
}
|
||||
|
||||
}
|
||||
-1
@@ -1 +0,0 @@
|
||||
net.minecraftforge.fml.earlydisplay.DisplayWindow
|
||||
Binary file not shown.
Binary file not shown.
|
Before Width: | Height: | Size: 11 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 11 KiB |
@@ -1,13 +0,0 @@
|
||||
█▀▀▀▀▀█ ▀▄▄▄▀█ █ █▀▀▀▀▀█
|
||||
█ ███ █ ███ ▀███▀ █ ███ █
|
||||
█ ▀▀▀ █ ▀ ▄ ███▀█ █ ▀▀▀ █
|
||||
▀▀▀▀▀▀▀ ▀ █ ▀ ▀▄█ ▀▀▀▀▀▀▀
|
||||
█▀█▀▄▄▀▄▀ █▄▀▄ ▀▀▀ ▄▀▀▀▄▀
|
||||
▄█▄▄ ▀▀███▀██▄ █▀ ▀▄▄
|
||||
▀█▄▀ ▀▀▄▄▀▀ █▀█▄▄████ ▀▀█
|
||||
▄▀▀▄▀ ▀▄▀▄█ ▀ ▀▀▀▄█ ▀▀▄
|
||||
▀ ▀▀ ▄ ▄██▀ ▄█▀▀▀█▀█▀█
|
||||
█▀▀▀▀▀█ ▄█▄▄▀▀▄█ ▀ █ ▀▀▀
|
||||
█ ███ █ ▄▄ ▄ █ ▀██▀██▄██
|
||||
█ ▀▀▀ █ ██▄███▀█ █ █ █▀
|
||||
▀▀▀▀▀▀▀ ▀▀ ▀▀▀ ▀▀▀▀▀▀▀▀
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 43 KiB |
@@ -1,95 +0,0 @@
|
||||
import net.minecraftforge.forgedev.legacy.tasks.JarJarMetadataOptions
|
||||
import org.gradle.api.plugins.jvm.JvmTestSuite
|
||||
|
||||
plugins {
|
||||
id 'jvm-test-suite'
|
||||
id 'net.minecraftforge.forge.build.convention'
|
||||
alias libs.plugins.apt
|
||||
}
|
||||
|
||||
gradleutils.displayName = 'FMLLoader'
|
||||
description = 'Mod Locator and manager for Minecraft Forge.'
|
||||
|
||||
dependencies {
|
||||
// TODO [FMLLoader] Figure out a better way to lock transitive dependencies to the explicit versions shipped by the installer
|
||||
api(libs.bundles.asm ){ transitive = false } // Needed by all the black magic
|
||||
api(libs.forgespi ){ transitive = false }
|
||||
api(libs.mergetool.api ){ transitive = false }
|
||||
api(libs.log4j.api ){ transitive = false }
|
||||
api(libs.slf4j.api ){ transitive = false }
|
||||
api(libs.guava ){ transitive = false }
|
||||
api(libs.gson ){ transitive = false }
|
||||
api(libs.maven.artifact ){ transitive = false }
|
||||
api(libs.apache.commons ){ transitive = false }
|
||||
api(libs.bundles.night.config){ transitive = false }
|
||||
api(libs.modlauncher ){ transitive = false }
|
||||
api(libs.mojang.logging ){ transitive = false }
|
||||
api(libs.jarjar.selector ){ transitive = false }
|
||||
api(libs.jarjar.meta ){ transitive = false }
|
||||
|
||||
implementation(libs.jopt.simple ){ transitive = false }
|
||||
implementation(libs.securemodules ){ transitive = false }
|
||||
implementation(libs.accesstransformers ){ transitive = false }
|
||||
implementation(libs.terminalconsoleappender){ transitive = false }
|
||||
implementation(libs.roimfs ){ transitive = false }
|
||||
|
||||
// Needed because we have a custom log4j plugin, and they removed package scanning and require a data file to be generated
|
||||
implementation(libs.log4j.core ){ transitive = false }
|
||||
annotationProcessor(libs.bundles.log4j){ transitive = false }
|
||||
}
|
||||
|
||||
testing.suites.named('test', JvmTestSuite) {
|
||||
dependencies {
|
||||
compileOnly libs.jetbrains.annotations
|
||||
runtimeOnly libs.bootstrap
|
||||
}
|
||||
}
|
||||
|
||||
convention.manifest('net/minecraftforge/fml/loading/', [
|
||||
'Automatic-Module-Name': 'net.minecraftforge.fmlloader',
|
||||
'Forge-Module-Layer' : 'boot'
|
||||
])
|
||||
|
||||
convention.publish()
|
||||
|
||||
final forgeJson = convention.forgeVersionJson {
|
||||
outputFile = file('src/main/resources/forge_version.json')
|
||||
}
|
||||
|
||||
final jarJarJson = tasks.register('jarJarOptionsJson', JarJarMetadataOptions) {
|
||||
metadataFile = file('src/main/resources/jarjar_options.json')
|
||||
// This is resolved too early by cpw.mods.modlauncher.TransformationServicesHandler.discoverServices(DiscoveryData) But eventually...
|
||||
//add(libs.mixin, 'org/spongepowered/asm/mixin/Mixin.class')
|
||||
add(libs.mixinextras.forge) {
|
||||
containedJarMetadata {
|
||||
path = ''
|
||||
}
|
||||
resource = 'com/llamalad7/mixinextras/platform/forge/MixinExtrasConfigPlugin.class'
|
||||
layer = 'GAMELIBRARY'
|
||||
id = 'mixinextras'
|
||||
nested = true
|
||||
}
|
||||
}
|
||||
|
||||
tasks.named('generateResources') {
|
||||
dependsOn(
|
||||
tasks.named('eclipseJdt'),
|
||||
tasks.named('eclipseJdtApt'),
|
||||
tasks.named('eclipseFactorypath'),
|
||||
forgeJson,
|
||||
jarJarJson
|
||||
)
|
||||
}
|
||||
|
||||
eclipse.classpath {
|
||||
// We need to set the default output directory for the log4j annotation processor
|
||||
// Ideally we'd just set the value, but the eclipse plugin deduplicates the output directories
|
||||
// So we have to do a hacky whenMerged
|
||||
//defaultOutputDir = file('bin/main')
|
||||
file.whenMerged {
|
||||
entries.each { entry ->
|
||||
if (entry.kind == 'output' && entry.hasProperty('path'))
|
||||
entry.path = 'bin/main'
|
||||
}
|
||||
}
|
||||
}
|
||||
-111
@@ -1,111 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.common.asm;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Deque;
|
||||
import java.util.EnumSet;
|
||||
|
||||
import org.objectweb.asm.Opcodes;
|
||||
import org.objectweb.asm.Type;
|
||||
import org.objectweb.asm.signature.SignatureReader;
|
||||
import org.objectweb.asm.signature.SignatureVisitor;
|
||||
import org.objectweb.asm.tree.ClassNode;
|
||||
import org.objectweb.asm.tree.MethodNode;
|
||||
|
||||
import cpw.mods.modlauncher.serviceapi.ILaunchPluginService;
|
||||
|
||||
/**
|
||||
* Implements getType() in CapabilityToken subclasses.
|
||||
*
|
||||
* Using the class's signature to determine the generic type of TypeToken, and then implements getType() using that value.
|
||||
* <pre>
|
||||
* Example:
|
||||
*
|
||||
* <code>new CapabilityToken<String>(){}</code>
|
||||
* Has the signature <code>"CapabilityToken<Ljava/lang/String;>"</code>
|
||||
*
|
||||
* Implements the method:
|
||||
* <code>public String getType() {
|
||||
* return "java/lang/String";
|
||||
* }</code>
|
||||
* </pre>
|
||||
*/
|
||||
public final class CapabilityTokenSubclass implements ILaunchPluginService {
|
||||
private static final String FUNC_NAME = "getType";
|
||||
private static final String FUNC_DESC = "()Ljava/lang/String;";
|
||||
private static final String CAP_INJECT = "net/minecraftforge/common/capabilities/CapabilityToken"; // Don't directly reference this to prevent class loading.
|
||||
|
||||
@Override
|
||||
public String name() {
|
||||
return "capability_token_subclass";
|
||||
}
|
||||
|
||||
private static final EnumSet<Phase> YAY = EnumSet.of(Phase.AFTER);
|
||||
private static final EnumSet<Phase> NAY = EnumSet.noneOf(Phase.class);
|
||||
|
||||
@Override
|
||||
public EnumSet<Phase> handlesClass(Type classType, boolean isEmpty) {
|
||||
if (isEmpty)
|
||||
return NAY;
|
||||
|
||||
String internalName = classType.getInternalName();
|
||||
if (internalName.startsWith("net/minecraft/") || internalName.startsWith("com/mojang/"))
|
||||
return NAY;
|
||||
|
||||
if (internalName.startsWith("net/minecraftforge/common/capabilities/"))
|
||||
return YAY;
|
||||
|
||||
return internalName.contains("$") ? YAY : NAY; // Anonymous subclasses only
|
||||
}
|
||||
|
||||
@Override
|
||||
public int processClassWithFlags(final Phase phase, final ClassNode classNode, final Type classType, final String reason) {
|
||||
if (CAP_INJECT.equals(classNode.name)) {
|
||||
for (MethodNode mtd : classNode.methods) {
|
||||
if (FUNC_NAME.equals(mtd.name) && FUNC_DESC.equals(mtd.desc)) {
|
||||
mtd.access &= ~Opcodes.ACC_FINAL; // We have it final in code so people don't override it, cuz that'd be stupid, and make our transformer more complicated.
|
||||
}
|
||||
}
|
||||
return ComputeFlags.SIMPLE_REWRITE;
|
||||
} else if (CAP_INJECT.equals(classNode.superName)) {
|
||||
var cls = new Object() { String value = null; };
|
||||
|
||||
SignatureReader reader = new SignatureReader(classNode.signature); // Having a node version of this would probably be useful.
|
||||
reader.accept(new SignatureVisitor(Opcodes.ASM9) {
|
||||
final Deque<String> stack = new ArrayDeque<>();
|
||||
|
||||
@Override
|
||||
public void visitClassType(final String name) {
|
||||
stack.push(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitInnerClassType(final String name) {
|
||||
stack.push(stack.pop() + '$' + name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitEnd() {
|
||||
var val = stack.pop();
|
||||
if (!stack.isEmpty() && CAP_INJECT.equals(stack.peek()))
|
||||
cls.value = val;
|
||||
}
|
||||
});
|
||||
|
||||
if (cls.value == null)
|
||||
throw new IllegalStateException("Could not find signature for CapabilityToken on " + classNode.name + " from " + classNode.signature);
|
||||
|
||||
var mtd = classNode.visitMethod(Opcodes.ACC_PUBLIC, FUNC_NAME, FUNC_DESC, null, new String[0]);
|
||||
mtd.visitLdcInsn(cls.value);
|
||||
mtd.visitInsn(Opcodes.ARETURN);
|
||||
mtd.visitEnd();
|
||||
return ComputeFlags.COMPUTE_MAXS;
|
||||
} else {
|
||||
return ComputeFlags.NO_REWRITE;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,248 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.common.asm;
|
||||
|
||||
import java.util.EnumSet;
|
||||
import java.util.List;
|
||||
|
||||
import com.mojang.logging.LogUtils;
|
||||
import net.minecraftforge.fml.loading.LoadingModList;
|
||||
import org.objectweb.asm.Label;
|
||||
import org.objectweb.asm.Opcodes;
|
||||
import org.objectweb.asm.Type;
|
||||
import org.objectweb.asm.commons.InstructionAdapter;
|
||||
import org.objectweb.asm.tree.ClassNode;
|
||||
import org.objectweb.asm.tree.FieldNode;
|
||||
import org.objectweb.asm.tree.MethodNode;
|
||||
|
||||
import cpw.mods.modlauncher.serviceapi.ILaunchPluginService;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
/**
|
||||
* Modifies specified enums to allow runtime extension by making the $VALUES field non-final and
|
||||
* injecting constructor calls which are not valid in normal java code.
|
||||
*/
|
||||
public class RuntimeEnumExtender implements ILaunchPluginService {
|
||||
|
||||
private static final Logger LOGGER = LogUtils.getLogger();
|
||||
private static final Type STRING = Type.getType(String.class);
|
||||
private static final Type ENUM = Type.getType(Enum.class);
|
||||
private static final Type MARKER_IFACE = Type.getType("Lnet/minecraftforge/common/IExtensibleEnum;");
|
||||
private static final Type ARRAY_UTILS = Type.getType("Lorg/apache/commons/lang3/ArrayUtils;"); //Don't directly reference this to prevent class loading.
|
||||
private static final String ADD_DESC = Type.getMethodDescriptor(Type.getType(Object[].class), Type.getType(Object[].class), Type.getType(Object.class));
|
||||
private static final Type UNSAFE_HACKS = Type.getType("Lnet/minecraftforge/fml/unsafe/UnsafeHacks;"); //Again, not direct reference to prevent class loading.
|
||||
private static final String CLEAN_DESC = Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(Class.class));
|
||||
private static final String NAME_DESC = Type.getMethodDescriptor(STRING);
|
||||
private static final String EQUALS_DESC = Type.getMethodDescriptor(Type.BOOLEAN_TYPE, STRING);
|
||||
private static final int FLAGS = Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL | Opcodes.ACC_SYNTHETIC;
|
||||
|
||||
@Override
|
||||
public String name() {
|
||||
return "runtime_enum_extender";
|
||||
}
|
||||
|
||||
private static final EnumSet<Phase> YAY = EnumSet.of(Phase.AFTER);
|
||||
private static final EnumSet<Phase> NAY = EnumSet.noneOf(Phase.class);
|
||||
|
||||
private static final class LazyInit {
|
||||
private LazyInit() {}
|
||||
private static final boolean ANY_MODS = LoadingModList.getMods().size() > 2; // 2: forge, minecraft
|
||||
}
|
||||
|
||||
@Override
|
||||
public EnumSet<Phase> handlesClass(Type classType, boolean isEmpty) {
|
||||
if (isEmpty || !LazyInit.ANY_MODS)
|
||||
return NAY;
|
||||
|
||||
String internalName = classType.getInternalName();
|
||||
if (internalName.startsWith("net/minecraft/client/model") || internalName.startsWith("net/minecraft/world"))
|
||||
return YAY;
|
||||
|
||||
return NAY;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int processClassWithFlags(final Phase phase, final ClassNode classNode, final Type classType, final String reason)
|
||||
{
|
||||
if ((classNode.access & Opcodes.ACC_ENUM) == 0)
|
||||
return ComputeFlags.NO_REWRITE;
|
||||
|
||||
if (!classNode.interfaces.contains(MARKER_IFACE.getInternalName()))
|
||||
return ComputeFlags.NO_REWRITE;
|
||||
|
||||
Type array = Type.getType("[" + classType.getDescriptor());
|
||||
String arrayDesc = array.getDescriptor();
|
||||
|
||||
FieldNode values = classNode.fields.stream().filter(f -> f.desc.equals(arrayDesc) && ((f.access & FLAGS) == FLAGS)).findFirst().orElse(null);
|
||||
|
||||
//Static methods named "create" with first argument as a string
|
||||
List<MethodNode> candidates = classNode.methods.stream()
|
||||
.filter(m -> ((m.access & Opcodes.ACC_STATIC) != 0) && m.name.equals("create"))
|
||||
.toList();
|
||||
|
||||
if (candidates.isEmpty()) {
|
||||
throw new IllegalStateException("IExtensibleEnum has no candidate factory methods: " + classType.getClassName());
|
||||
}
|
||||
|
||||
for (var mtd : candidates)
|
||||
{
|
||||
Type[] args = Type.getArgumentTypes(mtd.desc);
|
||||
if (args.length == 0 || !args[0].equals(STRING)) {
|
||||
if (LOGGER.isErrorEnabled(LogUtils.FATAL_MARKER))
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("Enum has create method without String as first parameter:\n");
|
||||
sb.append(" Enum: ").append(classType.getDescriptor()).append("\n");
|
||||
sb.append(" Target: ").append(mtd.name).append(mtd.desc).append("\n");
|
||||
LOGGER.error(LogUtils.FATAL_MARKER, sb.toString());
|
||||
}
|
||||
throw new IllegalStateException("Enum has create method without String as first parameter: " + mtd.name + mtd.desc);
|
||||
}
|
||||
|
||||
Type ret = Type.getReturnType(mtd.desc);
|
||||
if (!ret.equals(classType)) {
|
||||
if (LOGGER.isErrorEnabled(LogUtils.FATAL_MARKER))
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("Enum has create method with incorrect return type:\n");
|
||||
sb.append(" Enum: ").append(classType.getDescriptor()).append("\n");
|
||||
sb.append(" Target: ").append(mtd.name).append(mtd.desc).append("\n");
|
||||
sb.append(" Found: ").append(ret.getClassName()).append(", Expected: ").append(classType.getClassName());
|
||||
LOGGER.error(LogUtils.FATAL_MARKER, sb.toString());
|
||||
}
|
||||
throw new IllegalStateException("Enum has create method with incorrect return type: " + mtd.name + mtd.desc);
|
||||
}
|
||||
|
||||
Type[] ctrArgs = new Type[args.length + 1];
|
||||
ctrArgs[0] = STRING;
|
||||
ctrArgs[1] = Type.INT_TYPE;
|
||||
System.arraycopy(args, 1, ctrArgs, 2, args.length - 1);
|
||||
|
||||
String desc = Type.getMethodDescriptor(Type.VOID_TYPE, ctrArgs);
|
||||
|
||||
MethodNode ctr = classNode.methods.stream().filter(m -> m.name.equals("<init>") && m.desc.equals(desc)).findFirst().orElse(null);
|
||||
if (ctr == null)
|
||||
{
|
||||
if (LOGGER.isErrorEnabled(LogUtils.FATAL_MARKER))
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("Enum has create method with no matching constructor:\n");
|
||||
sb.append(" Enum: ").append(classType.getDescriptor()).append("\n");
|
||||
sb.append(" Candidate: ").append(mtd.desc).append("\n");
|
||||
sb.append(" Target: ").append(desc).append("\n");
|
||||
classNode.methods.stream().filter(m -> m.name.equals("<init>")).forEach(m -> sb.append(" : ").append(m.desc).append("\n"));
|
||||
LOGGER.error(LogUtils.FATAL_MARKER, sb.toString());
|
||||
}
|
||||
throw new IllegalStateException("Enum has create method with no matching constructor: " + classType.getClassName() + " " + desc);
|
||||
}
|
||||
|
||||
if (values == null)
|
||||
{
|
||||
if (LOGGER.isErrorEnabled(LogUtils.FATAL_MARKER))
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("Enum has create method but we could not find $VALUES. Found:\n");
|
||||
classNode.fields.stream().filter(f -> (f.access & Opcodes.ACC_STATIC) != 0).
|
||||
forEach(m -> sb.append(" ").append(m.name).append(" ").append(m.desc).append("\n"));
|
||||
LOGGER.error(LogUtils.FATAL_MARKER, sb.toString());
|
||||
}
|
||||
throw new IllegalStateException("Enum has create method but we could not find $VALUES");
|
||||
}
|
||||
|
||||
values.access &= values.access & ~Opcodes.ACC_FINAL; //Strip the final so JITer doesn't inline things.
|
||||
|
||||
mtd.access |= Opcodes.ACC_SYNCHRONIZED;
|
||||
mtd.instructions.clear();
|
||||
mtd.localVariables.clear();
|
||||
if (mtd.tryCatchBlocks != null)
|
||||
{
|
||||
mtd.tryCatchBlocks.clear();
|
||||
}
|
||||
if (mtd.visibleLocalVariableAnnotations != null)
|
||||
{
|
||||
mtd.visibleLocalVariableAnnotations.clear();
|
||||
}
|
||||
if (mtd.invisibleLocalVariableAnnotations != null)
|
||||
{
|
||||
mtd.invisibleLocalVariableAnnotations.clear();
|
||||
}
|
||||
InstructionAdapter ins = new InstructionAdapter(mtd);
|
||||
|
||||
int vars = 0;
|
||||
for (Type arg : args)
|
||||
vars += arg.getSize();
|
||||
|
||||
{
|
||||
vars += 1; //int x
|
||||
Label for_start = new Label();
|
||||
Label for_condition = new Label();
|
||||
Label for_inc = new Label();
|
||||
|
||||
ins.iconst(0);
|
||||
ins.store(vars, Type.INT_TYPE);
|
||||
ins.goTo(for_condition);
|
||||
//if (!VALUES[x].name().equalsIgnoreCase(name)) goto for_inc
|
||||
ins.mark(for_start);
|
||||
ins.getstatic(classType.getInternalName(), values.name, values.desc);
|
||||
ins.load(vars, Type.INT_TYPE);
|
||||
ins.aload(array);
|
||||
ins.invokevirtual(ENUM.getInternalName(), "name", NAME_DESC, false);
|
||||
ins.load(0, STRING);
|
||||
ins.invokevirtual(STRING.getInternalName(), "equalsIgnoreCase", EQUALS_DESC, false);
|
||||
ins.ifeq(for_inc);
|
||||
//return VALUES[x];
|
||||
ins.getstatic(classType.getInternalName(), values.name, values.desc);
|
||||
ins.load(vars, Type.INT_TYPE);
|
||||
ins.aload(array);
|
||||
ins.areturn(classType);
|
||||
//x++
|
||||
ins.mark(for_inc);
|
||||
ins.iinc(vars, 1);
|
||||
//if (x < VALUES.length) goto for_start
|
||||
ins.mark(for_condition);
|
||||
ins.load(vars, Type.INT_TYPE);
|
||||
ins.getstatic(classType.getInternalName(), values.name, values.desc);
|
||||
ins.arraylength();
|
||||
ins.ificmplt(for_start);
|
||||
}
|
||||
|
||||
{
|
||||
vars += 1; //enum ret;
|
||||
//ret = new ThisType(name, VALUES.length, args..)
|
||||
ins.anew(classType);
|
||||
ins.dup();
|
||||
ins.load(0, STRING);
|
||||
ins.getstatic(classType.getInternalName(), values.name, values.desc);
|
||||
ins.arraylength();
|
||||
int idx = 1;
|
||||
for (int x = 1; x < args.length; x++)
|
||||
{
|
||||
ins.load(idx, args[x]);
|
||||
idx += args[x].getSize();
|
||||
}
|
||||
ins.invokespecial(classType.getInternalName(), "<init>", desc, false);
|
||||
ins.store(vars, classType);
|
||||
// VALUES = ArrayUtils.add(VALUES, ret)
|
||||
ins.getstatic(classType.getInternalName(), values.name, values.desc);
|
||||
ins.load(vars, classType);
|
||||
ins.invokestatic(ARRAY_UTILS.getInternalName(), "add", ADD_DESC, false);
|
||||
ins.checkcast(array);
|
||||
ins.putstatic(classType.getInternalName(), values.name, values.desc);
|
||||
//EnumHelper.cleanEnumCache(ThisType.class)
|
||||
ins.visitLdcInsn(classType);
|
||||
ins.invokestatic(UNSAFE_HACKS.getInternalName(), "cleanEnumCache", CLEAN_DESC, false);
|
||||
//init ret
|
||||
ins.load(vars, classType);
|
||||
ins.invokeinterface(MARKER_IFACE.getInternalName(), "init", "()V");
|
||||
//return ret
|
||||
ins.load(vars, classType);
|
||||
ins.areturn(classType);
|
||||
}
|
||||
}
|
||||
return ComputeFlags.COMPUTE_FRAMES;
|
||||
}
|
||||
|
||||
}
|
||||
Loaded 100 of 3061 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user