Compare commits

...
197 Commits
Author SHA1 Message Date
33 e94f4b0e99 Release: 14.14 2022-10-19 11:35:43 +08:00
33 5ee2eee382 Add: LICENSE 2022-08-27 10:42:38 +08:00
ZekerZhayard 3063de7ff0 Support 1.19.2. Remove Vanilla 1.19.1. (#220) 2022-08-17 10:47:26 +08:00
33 583bf1fe6a Tweak: calculate correct hash for base64 texture 2022-07-29 02:29:15 +08:00
33 a3de21497d Fix: MinecraftCapesAPI 2022-07-29 02:15:19 +08:00
33 51aec265be Tweak: LegacyLoader UUID fallback logic 2022-07-29 01:14:50 +08:00
33 52caeb3bdc Tweak: compatible with authlib 3.11.50 2022-07-29 00:07:04 +08:00
33 a3fa4e47c6 Fix: MinecraftCapesAPI load profile only with existing UUID 2022-07-29 00:05:51 +08:00
33 e1cde0afc7 Tweak: correct MinecraftCapesAPI name 2022-07-28 11:04:27 +08:00
33 3f379f3cbe Tweak: register MinecraftCapesAPI 2022-07-28 11:03:27 +08:00
33 f50640139a Add: MinecraftCapesAPI 2022-07-28 10:59:54 +08:00
ZekerZhayard 46b8635e10 Support 1.19.1. Remove Vanilla 1.19. (#218) 2022-07-28 09:24:44 +08:00
33 02b24229f3 Update: LittleSkin root url 2022-07-28 08:44:30 +08:00
33 941b421d86 Fix: CDN cache wasn't be updated correctly 2022-07-28 08:43:41 +08:00
33 a67ed507ec Fix: CurseForge metadata json 2022-07-27 20:32:55 +08:00
33 851fa81f31 Tweak: change log level in build 2022-07-27 19:47:12 +08:00
33 5bb16ededa Fix: CurseForge uploading 2022-07-27 19:31:32 +08:00
33 1e5bfcd1e7 Fix: Minecraft version getting logic 2022-07-27 17:23:50 +08:00
ZekerZhayard 1b85fa8ff9 Convert all build scripts to buildSrc. (#216) 2022-07-20 23:11:48 +08:00
33 e1e5319bdb Add: detail.json with detailed downloading information 2022-07-19 22:22:14 +08:00
33 187be47e88 Add: Custom Gradle Plugin in buildSrc 2022-07-19 20:40:53 +08:00
ZekerZhayard b2f8d2cc38 Support 1.19, Remove Vanilla 1.17.1 (#211) 2022-06-09 10:00:10 +08:00
ZekerZhayard 8b641e0227 Support Fabric 22w14a. (#208) 2022-04-14 19:52:11 +08:00
ZekerZhayard c90cea3721 Remove transformers of SkullTileEntity (#207)
* Bump to 14.14

* Remove transformers of SkullTileEntity
2022-04-01 13:56:20 +08:00
33 b0c11d11c6 Fix curseforge and modrinth release 2022-03-17 11:07:25 +08:00
33 c77ac58f6d Release CustomSkinLoader 14.13 2022-03-17 10:41:59 +08:00
ZekerZhayard 16fadc56b4 Support Forge/Fabric/Vanilla 1.18.2. Remove Vanilla 1.18.1. (#206) 2022-03-03 17:31:20 +08:00
33 fc6c43bac9 Fix standalone elytra url (#204) 2022-02-22 17:38:53 +08:00
ZekerZhayard b6fc1610bc Fix skull not loading if not need to judge type. (#201) 2022-01-24 13:58:06 +08:00
ZekerZhayard c7d04976e6 Fix skin type judgement from cache. (#200)
Signed-off-by: ZekerZhayard <[email protected]>
2022-01-09 21:58:59 +08:00
ZekerZhayard 0eaf1960bf Support Fabric/Forge/Vanilla 1.18.1. (#196)
* Support Fabric and Vanilla 1.18.

Signed-off-by: ZekerZhayard <[email protected]>

* Support Fabric and Vanilla 1.18.

Signed-off-by: ZekerZhayard <[email protected]>

* Support Fabric, Forge and Vanilla 1.18.1.

Signed-off-by: ZekerZhayard <[email protected]>
2021-12-11 16:27:36 +08:00
ZekerZhayard cff5846e7f Fix NPE if type is null. (#195)
* Fix NPE if type is null.

Signed-off-by: ZekerZhayard <[email protected]>

* Forge does not support Java 18 for now.

Signed-off-by: ZekerZhayard <[email protected]>
2021-11-28 02:17:38 +08:00
ZekerZhayard c8fb6e216e Finish loader names for Modrinth. (#193)
Signed-off-by: ZekerZhayard <[email protected]>
2021-11-12 19:14:07 +08:00
ZekerZhayard a5d466e0a7 Added support for automatic upload to CurseForge and Modrinth. (#190)
* Added support for automatic upload to CurseForge and Modrinth.

Signed-off-by: ZekerZhayard <[email protected]>

* Fix defining environment variable in circle ci.

Signed-off-by: ZekerZhayard <[email protected]>

* Fix defining environment variable in circle ci.

Signed-off-by: ZekerZhayard <[email protected]>

* Finish fixing defining environment.

Signed-off-by: ZekerZhayard <[email protected]>
2021-11-04 14:55:59 +08:00
Uriel 31fffa5d23 support tlauncher (#188)
* support tlauncher

* it works

* Update README.md

* simplify things

* undo wildcard

* facepalm

* update tlauncher info
2021-11-04 14:52:05 +08:00
ZekerZhayard 7e9f7fa498 Compatible with fabric-loader-0.12.x in development environment. (#189)
Signed-off-by: ZekerZhayard <[email protected]>
2021-10-16 01:41:54 +08:00
ZekerZhayard f51b55be6e Fix compatible with OptiFine 1.17.1. (#186) 2021-10-03 18:06:58 +08:00
ZekerZhayard 584c7b7518 Improve skin loading logic. (#180) 2021-09-24 11:19:06 +08:00
ZekerZhayard 51c8900562 Support Forge 1.17.1. (#177) 2021-07-25 15:48:50 +08:00
ZekerZhayard ab7aebb753 Support Vanilla and Fabric 1.17.1. Remove Vanilla 1.17. (#175) 2021-07-07 00:21:36 +08:00
ZekerZhayard dc5ecfb576 Support Vanilla and Fabric 1.17. Remove Vanilla 1.15.2. (#171)
* Support Fabric 1.17-rc2.

* Support Vanilla and Fabric 1.17. Remove Vanilla 1.15.2.
2021-06-09 14:55:20 +08:00
ZekerZhayard 04899ff676 Support Fabric 1.17-pre1. (#170) 2021-05-29 18:53:27 +08:00
ZekerZhayard 4df8ce38d6 Fix CustomSkinAPIPlus loading incorrectly. Fix unable to complete config with default value. (#168) 2021-05-25 12:55:42 +08:00
ZekerZhayard 3e001c4cdf Fix elytra can not be rendered when the cape doesn't contain elytra. (#160)
* Fix elytra can not be rendered when the cape doesn't contain elytra.

* Fix typo.

* Streamline IFakeThreadDownloadImageData.

* Fix wrong arguments.

* Add compatible with other custom player model mods, such as tr7zw/FirstPersonModel
2021-05-07 17:15:45 +08:00
ZekerZhayard d5dea652ff Induce users to download the pre-release version. (#164)
* Induce users to download the pre-release version.

* Add contact us.

* Some versions of forge-1.13.2 is not compatible because of the strong limitation of CoreMods-0.3.0.
2021-05-07 17:10:01 +08:00
ZekerZhayard 2a4226527d Prevent authlib-injector from modifying urls. (#159) 2021-05-01 22:46:02 +08:00
ZekerZhayard 6c9494970f Enhanced default skin loaders. (#157)
* Enhance ICustomSkinLoaderPlugin.

* Support auto update config file per snapshot. Fix crash with forge 1.14.2 ~ 1.15.2.

* ElyByAPI should check root now.

* Remove unnecessary packages, add some deprecated loaders.

* Reformat imports.

* Move forge stuffs to another commit.

* Fix config updating incorrectly.
2021-04-24 10:33:18 +08:00
ZekerZhayard c84f506af1 Fix crash with forge 1.14.2~1.16.2. Upgrade forge maven. (#158)
* Fix crash with forge 1.14.2~1.16.2. Upgrade forge maven.

* Update forge maven url.
2021-04-23 22:07:53 +08:00
ZekerZhayard a0e31ed883 Change Mixin priority to prevent potential Mixin conflict. (#154) 2021-04-22 11:03:06 +08:00
ZekerZhayard 8befcb32d8 No longer remove any elements in SkinManager. (#151) 2021-03-27 19:32:00 +08:00
ZekerZhayard fb50a3db6d Support Fabric 21w10a. (#148) 2021-03-13 19:47:18 +08:00
ZekerZhayard 4daacd18e8 Make it easier to build the development environment. (Phase 2) (#147)
* Make it easier to build the development environment. (Phase 2)

* Provide sources jar.

* Add development guide.

* Improve development guide.
2021-03-13 19:46:51 +08:00
ZekerZhayard 98681e8251 Remove updateGameProfile transformer. (#143)
* Add an option to control updateGameProfile transformer.

* Remove unnecessary FrameNodes
2021-02-08 11:37:04 +08:00
ZekerZhayard ea5d890992 Support 1.16.5. Remove 1.16.4 Vanilla. (#141) 2021-01-17 01:57:36 +08:00
ZekerZhayard f5135872cc Fix rendering transparent capes for Forge 1.15+. (#140) 2021-01-12 22:59:14 +08:00
ZekerZhayard 5d736dd4b5 Fix sign jar. (#137) 2021-01-04 15:29:34 +08:00
ZekerZhayard 1b2a4dc260 Make it easier to build the development environment. (#133)
* Fix the warning about removing duplicate source roots when open the project with Intellij IDEA.

* Add Gradle wrapper.

* CustomSkinLoader can be loaded in Forge development environment now.

* CustomSkinLoader can be loaded in Fabric development environment now.
2021-01-03 02:53:57 +08:00
ZekerZhayard 855131d1aa Fix DefaultFMLPlatform can't be loaded when other FML platform being used. (#132) 2020-12-20 01:02:07 +08:00
ZekerZhayard 581a2dddea Change the ordinal of FMLLoadingPlugin to fix the crash with BetterFps before Minecraft 1.10.2. (#131)
Clean up codes.
2020-12-15 21:17:10 +08:00
ZekerZhayard a1b52eb7ac Fix version.json parser, compatible with 20w45a. (#128) 2020-11-05 21:54:43 +08:00
Alexander Xia 0ed371fdc1 Remove GitHub maven temporarily 2020-11-05 18:08:26 +08:00
ZekerZhayard ee7e57cf78 Support 1.16.4. Remove 1.16.3 Vanilla. (#127) 2020-11-05 11:53:12 +08:00
ZekerZhayard 90ed224dd8 Fix ResourceLocation characters limitation for Minecraft 1.13+ (#126) 2020-11-05 11:52:49 +08:00
ZekerZhayard a65445e989 Make sure the mod being absent on the other network side does not cause the client to display the server as incompatible after forge-1.13.2-25.0.107. (#124) 2020-11-05 11:52:36 +08:00
ZekerZhayard da79597a16 Fix crash on launch with forge-1.16.3-34.1.27. (#122) 2020-10-27 21:52:29 +08:00
ZekerZhayard 9c6102a813 Fix incorrect method descriptions. (#119) 2020-09-29 21:19:15 +08:00
ZekerZhayard 573c5e4a20 Fabric and vanilla jars can be signed now. (#118) 2020-09-27 16:57:36 +08:00
ZekerZhayard 12441cc379 Fix rendering transparent skins and capes for 19w41a+. (#117)
* Support 1.16.3. Remove 1.16.2 Vanilla.

* Fix rendering transparent skins and capes for 19w41a+.
2020-09-20 21:12:14 +08:00
ZekerZhayard 7df6336b56 Support 1.16.3. Remove 1.16.2 Vanilla. (#116) 2020-09-11 22:55:26 +08:00
ZekerZhayard 2dd69e08da Fix InvalidMixinException before 1.15-snapshot. (#115) 2020-09-02 12:30:25 +08:00
ZekerZhayard 67fbcf5cec Fix crashes caused by incorrect stack frames. (#114) 2020-09-02 12:29:54 +08:00
ZekerZhayard f898831276 Prepare for compatibility with 1.7.10. (#113) 2020-08-29 17:20:44 +08:00
ZekerZhayard 83042f45bd Allow APortingCore to load CustomSkinLoader. (#112) 2020-08-24 11:52:23 +08:00
ZekerZhayard dc6d135699 Add the function to print the System and Java version to the log file. (#111) 2020-08-21 12:51:59 +08:00
Alexander Xia f42496e04c Tweak cache config 2020-08-16 22:18:25 +08:00
Alexander Xia f003d57ddf Tweak thread pool 2020-08-16 21:55:06 +08:00
Alexander Xia b64700b9fb Add forceDisableCache 2020-08-16 21:07:22 +08:00
ZekerZhayard f64af50a07 Improve downloading http textures. (#108) 2020-08-16 19:50:19 +08:00
Alexander XiaandZekerZhayard a8c8edaf20 Support 1.16.2 Fabric, Forge and Vanilla. Remove 1.16.1 Vanilla. (#107)
* Support 1.16.2 Fabric, Forge and Vanilla. Remove 1.16.1 Vanilla.

* Delete build.properties

* Create build.properties

Co-authored-by: ZekerZhayard <[email protected]>
2020-08-13 16:22:16 +08:00
Alexander Xia 5ebee1f1e0 Bump 14.12 2020-07-06 23:01:40 +08:00
Alexander Xia 1eb8db550f Fix custom launchwrapper 2020-07-06 22:57:31 +08:00
Alexander Xia 52a232f982 Update custom launchwrapper version 2020-07-06 22:54:49 +08:00
ZekerZhayard eeebc30b58 Apply custom launchwrapper. (#102) 2020-07-02 01:08:24 +08:00
Evan Goode 46bccadca2 Escape URLs, for usernames with spaces (#100) 2020-07-01 22:47:47 +08:00
ZekerZhayard d7f207177c Apply ModSystemTweaker when another tweaker being applied. (#101) 2020-07-01 22:47:40 +08:00
ZekerZhayard 339e30247a Add "launchermeta" to "latest.json". (#99) 2020-06-30 23:45:37 +08:00
ZekerZhayard ba8d86789d Support Vanilla 1.8.9, 1.12.2, 1.15.2, 1.16.1. (#98)
* Support Vanilla 1.8.9, 1.12.2, 1.15.2, 1.16.1.

* Move vanilla specific version folders to "Vanilla" folder.

* Fix launchwrapper dependency.

* Update profile.

* Move customskinloader.fabric.mixin to customskinloader.mixin
2020-06-29 01:33:53 +08:00
ZekerZhayard a9f19cfc8d Allow users to customize the size of thread pools. (#86)
* Increase compatible Java version to 8.

* Support Forge & Fabric 1.15.2

* Fix lag spike while loading player skull textures.

* Allow users to customize the size of thread pools.

* Use the old scheme about loading skulls to avoid blocking the thread pool when "enableUpdateSkull" is true.

* Fix merge.
2020-06-29 00:57:42 +08:00
ZekerZhayard 8b1400ef0d Support Forge 1.16.x. (#97)
* Support Forge 1.16.x.

* Add Minecraft versions.
2020-06-29 00:56:41 +08:00
Steven Qiu 82c2e80e76 Update LittleSkin's API Root (#96) 2020-06-23 21:16:20 +08:00
ZekerZhayard 8146773354 Fix legacy model auto judge for 1.15.x (#93) 2020-05-21 10:30:45 +08:00
Alexander Xia 5ac6aa1865 Fix legacy model auto judge
Thanks to @ZekerZhayard
2020-05-21 02:37:51 +08:00
Alexander Xia dab8e3dd22 Fix legacy model auto judge 2020-05-20 18:38:31 +08:00
ZekerZhayard fdceb08a2c Fix skull loading lag for Minecraft 1.13.2 or older version. (#91) 2020-05-15 22:51:04 +08:00
ZekerZhayard ad846f37a2 Support Fabric 20w17a. (#90) 2020-05-12 17:07:30 +08:00
ZekerZhayard b8ce13606b Fix SkullTileEntityTransformer. (#88) 2020-04-17 20:19:23 +08:00
Steven Qiu 2fbd3965e0 Update LittleSkin's API root (#87) 2020-04-17 11:21:54 +08:00
Alexander Xia a714670b9a Fix GitHub publish in pull request 2020-03-29 22:57:28 +08:00
Alexander Xia c5460624e3 Fix typo 2020-03-29 19:56:52 +08:00
Alexander Xia 9f63a770c3 Fix concurrent issue 2020-03-26 10:22:20 +08:00
ZekerZhayard 4d234762d2 Fix lag spike while loading player skull textures. (#84)
* Increase compatible Java version to 8.

* Support Forge & Fabric 1.15.2

* Fix lag spike while loading player skull textures.
2020-03-25 11:58:01 +08:00
Alexander Xia 730b565c59 Fix transform script 2020-03-25 10:54:31 +08:00
Alexander Xia 4d12d70bf0 Fix skull loading lag
#79
2020-03-25 10:17:28 +08:00
Alexander Xia 42adcb5b27 Add thread pool to load skull
#79
2020-03-24 11:46:11 +08:00
Alexander Xia 77ddcc8bf5 Add GitHub Packages 2020-03-11 17:26:28 +08:00
Alexander Xia d46adaac5e Tweak transformer to avoid repeated modification 2020-03-04 15:51:54 +08:00
Alexander Xia a6666b53a1 Fix UniSkinAPI elytra 2020-02-22 03:05:38 +08:00
ZekerZhayard 958860ecce Support Forge & Fabric 1.15.2 (#78)
* Increase compatible Java version to 8.

* Support Forge & Fabric 1.15.2
2020-01-24 16:56:26 +08:00
ZekerZhayard 6fab945eb1 Support Forge for Minecraft 1.15.x (#77) 2019-12-18 15:07:46 +08:00
ZekerZhayard e19b9d860f Support Fabric for Minecraft 1.15.x (#75)
* Support Fabric for Minecraft 1.15.x

* Remove unused imports
2019-12-11 18:53:57 +08:00
ZekerZhayard 7adb0f9ef7 Fix PlayerTab for 1.14+ in Fabric. (#72) 2019-12-10 12:52:55 +08:00
Alexander Xia 1bb130bb87 Add latest.json 2019-12-10 03:10:26 +08:00
Alexander Xia 779e25f837 Init CustomSkinLoader earlier 2019-12-09 23:47:29 +08:00
Alexander Xia 3a2d8f9caf Fix PlayerTab in 1.14+ again 2019-12-09 23:20:52 +08:00
Alexander Xia 0c91fb3975 Fix PlayerTab in 1.14+ 2019-12-09 23:10:27 +08:00
Alexander Xia 290cbb63d8 Support UUID in Legacy Loader
Update copyright statement
#65 #66
2019-10-03 15:30:46 +08:00
Alexander Xia 100e661ac5 Add 1.14.4 vanilla 2019-09-20 22:07:58 +08:00
Alexander Xia c490631f2c Fix spelling mistake 2019-09-20 16:33:04 +08:00
Alexander Xia c519d09be4 Fix content type which causes 415 2019-09-20 11:44:07 +08:00
Alexander Xia e5a31ae49e Add custom Yggdrasil api & sessionserver root 2019-09-18 22:50:04 +08:00
Alexander Xia 68615ba724 Add custom Yggdrasil root 2019-09-18 22:15:58 +08:00
Alexander Xia 10e57fe349 Bump 14.11 2019-08-27 17:55:49 +08:00
Alexander Xia 9f70ad0159 Update upload url 2019-06-25 15:24:14 +08:00
ZekerZhayard 0d5538a110 Support for forge 1.14.2 (#59)
* Support for forge 1.14.2

* Delete unnecessary code.
2019-06-25 14:38:40 +08:00
Alexander Xia 27efbbfeb0 Fix addScheduledTask method not found 2019-06-24 20:07:48 +08:00
Alexander Xia 7fad8c602d Add 1.14.2 forge suport 2019-06-24 19:52:02 +08:00
Alexander Xia 29a0952bc4 Fix compatibility with ModLauncher 1.1 (#57) 2019-06-15 17:37:48 +08:00
Alexander Xia b7107b7172 Remove 1.13.2 vanilla 2019-05-24 00:06:35 +08:00
Alexander Xia 2adbc25f69 Fix gradle upload 2019-05-23 23:47:33 +08:00
ZekerZhayard 3bee9281ec Fix remapJar (#55) 2019-05-23 23:35:56 +08:00
ZekerZhayard 917f9f650b Support Fabric for 1.14.1 (#53)
* Fix ClassCastException

* Support Fabric for 1.14.1

* Support Fabric for 1.14.1

* Use mapping file instead of hard code
2019-05-22 23:47:59 +08:00
LionZXY edf6e241e4 Add GlitchlessAPI (#51)
* Add GlitchlessAPI

* Fix build and move GlitchlessSkin to down
2019-05-10 16:20:39 +08:00
Alexander Xia d2c65f00c9 Remove meaningless log 2019-04-26 13:59:08 +08:00
Alexander Xia 95ee345441 Fix 1.14 skin load 2019-04-26 13:56:22 +08:00
Alexander Xia 3ade4867d4 Add 1.14 to settings.gradle 2019-04-26 10:36:20 +08:00
Alexander Xia 2d1951774d Add 1.14 support 2019-04-26 10:34:31 +08:00
ZekerZhayard cc3616a074 Add CSLPluginsLoader (#48)
* Add CSLPluginsLoader

* Remove plugin loader. Add some events.

* Use ServiceLoader to load plugins

* Remove PluginClassLoader.
2019-03-08 13:38:44 +08:00
xfl03 42c48c5c2e Bump 14.10a 2019-03-05 19:33:09 +08:00
xfl03 030daf12a2 Fix 1.8 forge support 2019-03-04 20:12:13 +08:00
xfl03 88763d64ef Bump 14.10 2019-03-03 12:20:28 +08:00
xfl03 4f2b5edf84 Fix incorrect response code judgement 2019-03-03 11:53:48 +08:00
xfl03 cbe07b9003 Fix http redirect to https 2019-03-03 11:34:54 +08:00
xfl03 b2867a0dbf Add support for 1.13.2 forge 2019-03-02 12:26:53 +08:00
xfl03 65dacd8527 Fix javascript cannot expand 2019-03-01 20:31:23 +08:00
xfl03 d2d425e96e Remove 1.13 & 1.13.1 in settings.gradle 2019-03-01 20:10:50 +08:00
xfl03 0762e3e339 Remove support for vanilla 1.13 & 1.13.1 2019-03-01 20:08:22 +08:00
xfl03 4cb1e348bb Try to support 1.13 forge 2019-03-01 14:59:02 +08:00
Alexander Xia 7bbfd19bfd Fix no content cache 2019-02-06 00:39:17 +08:00
Alexander Xia be8b80bd55 Tweak CircleCI Docker Image 2019-01-05 00:20:22 +08:00
Alexander Xia 47de6d3a89 Add workaround for #42 2019-01-05 00:12:42 +08:00
Alexander Xia f78a3b2565 Add disable cape feature 2018-11-26 15:16:07 +08:00
Alexander Xia 016249c6ca Fix version display again 2018-11-25 02:33:12 +08:00
Alexander Xia 860edd2e1a Fix version display 2018-11-25 02:13:55 +08:00
Alexander Xia 3e6e444857 Fix gradle script buid again 2018-11-25 02:08:54 +08:00
Alexander Xia d67b7c6296 Fix gradle script buid again 2018-11-25 02:04:36 +08:00
Alexander Xia 94f6044c9a Fix gradle script build error 2018-11-25 01:53:28 +08:00
Alexander Xia 6b3531964e Tweak version json name 2018-11-25 01:44:06 +08:00
Alexander Xia fbd06f147a Modify gradle script 2018-11-24 01:38:49 +08:00
Alexander Xia e3020dad00 Add Upload Version json to COS 2018-11-23 03:23:17 +08:00
Alexander Xia 49fb976a2c Fix COS upload path 2018-11-23 02:48:19 +08:00
Alexander Xia 78bc4b5f7e Try to upload file to COS 2018-11-23 02:43:30 +08:00
Alexander Xia 7a3dc4f9c2 Support for 1.13.2 2018-11-02 14:48:07 +08:00
Alexander Xia 2087f7bb94 Tweak: Change Profile.json mirror 2018-09-23 23:44:25 +08:00
Alexander Xia e95edb16ac Add: Vanilla Support for 1.13.1 2018-09-23 23:00:34 +08:00
Alexander Xia 3b07b5ccca Update config version checker
Update config output
Add enableCape in config
2018-09-02 15:57:08 +08:00
xfl03 a3fb3cd770 Fix Build 2018-08-26 07:16:37 +08:00
xfl03 b7b59c0b85 Support ModLauncher 2018-08-26 07:04:25 +08:00
Alexander Xia db6b54732e Update MCP map to stable 2018-08-22 03:42:50 +08:00
Alexander Xia 09e3b81552 Fix path for ForgePlugin.log 2018-08-20 19:23:47 +08:00
Alexander Xia 2f494d295e Update Forge Version 2018-08-13 05:15:32 +08:00
Alexander Xia e8e3a72ae7 Add Fingerprint Violation 2018-08-13 05:11:47 +08:00
Alexander Xia ca8bd4e83d Add Profile.json for vanilla edition
Remove CustomSkinAPIPlusPrivacy
Fix typo in ReadMe
Update mcp map
2018-08-11 07:34:13 +08:00
Alexander Xia d789119c8f Get Ready for Forge 1.13 2018-07-26 20:50:41 +08:00
Alexander Xia bfd1b41ecc Update ReadMe
Thanks for @HeartyYF
2018-07-26 13:19:33 +08:00
Alexander Xia 5807acb34a Bump 14.9 2018-07-25 21:16:59 +08:00
Alexander Xia f319d535ae Merge branch '1.13-dev' into csl-14 2018-07-25 21:08:10 +08:00
Alexander Xia f669d095b6 Add Support for 1.13!
Thanks for MinecraftForge/MCPConfig.
2018-07-25 21:06:16 +08:00
Alexander Xia ca8b0ba185 Add FakeImage 2018-07-25 15:55:03 +08:00
Alexander Xia 7acef4d987 Fix Support for Java9
Add ElyBy in default load list
2018-07-20 23:23:37 +08:00
Alexander Xia 79404f659c Merge pull request #36 from andylizi/pr-replace
Replace the unnecessary `replaceAll` calls with `replace`
2018-07-13 22:36:31 +08:00
andylizi 85c86ff375 Replace the unnecessary replaceAll calls with replace 2018-07-13 19:48:02 +08:00
Alexander Xia f4030701ee Fix Legacy Texture cannot refresh in cache 2018-07-12 15:18:13 +08:00
Alexander Xia a36eca2a53 Add ElyByAPI 2018-07-09 19:53:35 +08:00
Alexander Xia 6ffdf2aafb Fix Spectator Menu totally 2018-07-02 00:15:03 +08:00
Alexander Xia fba9f7ca28 Fix head in Spectator Menu 2018-07-01 23:25:57 +08:00
Alexander Xia 2d157e3d5b Fix head is not loaded first time open Spectator Menu 2018-07-01 23:15:06 +08:00
Alexander Xia 055aef17db Fix ForgePlugin log 2018-06-25 00:56:47 +08:00
Alexander Xia 622e834d26 Make Code Better 2018-06-25 00:34:32 +08:00
Alexander Xia 469c8b62a9 Fix Noname skull load 2018-06-24 23:07:51 +08:00
Alexander Xia 1558ec819a Fix Crash in Spectator Menu 2018-06-24 22:59:46 +08:00
Alexander Xia 883e7b45fc Add skin model auto judge 2018-05-18 21:06:28 +08:00
Alexander Xia f30d3319b0 Reuse Vanilla Code 2018-05-06 01:10:55 +08:00
Alexander Xia 58276a7a0c Reuse Vanilla Code 2018-05-06 01:09:48 +08:00
Alexander Xia 883fb39380 Update Gradle Script
Fix local jsonAPI bug
https://minecraft.curseforge.com/projects/customskinloader?comment=10
2018-05-05 23:07:20 +08:00
Alexander Xia 1358a99f51 Merge pull request #35 from tnqzh123/csl-14
Update LittleSkin's API root
2018-04-10 23:39:31 +08:00
LittleStudio-Little_Qiu 47ea01dc39 Update API root 2018-04-10 23:29:45 +08:00
LittleStudio-Little_Qiu ee36f2f42a Update README.md
change link
2018-04-10 23:28:27 +08:00
183 changed files with 8272 additions and 2834 deletions

No files matched your search

+12 -2
View File
@@ -3,7 +3,7 @@ version: 2
jobs: jobs:
build: build:
docker: docker:
- image: circleci/openjdk:8-jdk - image: circleci/openjdk@sha256:7be33522f6f0ca65c2e78b22b1ef3e6739038494c1de1b8fb6d96da400dccf53
working_directory: ~/repo working_directory: ~/repo
@@ -25,7 +25,17 @@ jobs:
# Gradle # Gradle
- run: gradle --version - run: gradle --version
- run: gradle clean build - run:
name: Build
command: |
export GIT_COMMIT_DESC=$(git log --format=%B -n 1 $CIRCLE_SHA1)
gradle clean build
- run:
name: Publish
command: |
export GIT_COMMIT_DESC=$(git log --format=%B -n 1 $CIRCLE_SHA1)
gradle upload --info
# - run: gradle publishGprPublicationToGitHubPackagesRepository
- store_artifacts: - store_artifacts:
path: ./build/libs path: ./build/libs
+18 -8
View File
@@ -1,26 +1,36 @@
# Java
*.class *.class
# Mobile Tools for Java (J2ME) # Mobile Tools for Java (J2ME)
.mtj.tmp/ .mtj.tmp/
# Package Files #
*.jar
*.war
*.ear
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid* hs_err_pid*
#VSCode # VSCode
.vscode/ .vscode/
#eclipse # eclipse
bin/
*/.classpath */.classpath
.classpath .classpath
*/.project */.project
.project .project
.settings/ .settings/
*.launch
#gradle # gradle
.gradle/ .gradle/
build/ build/
logs/
run/
# IDEA
.idea/
*.iml
*.ipr
*.iws
out/
#mac OS
.DS_Store
-3
View File
@@ -1,3 +0,0 @@
/build/
/src/main/
-6
View File
@@ -1,6 +0,0 @@
minecraft_version=1.12
minecraft_full_versions=1.12
#forge gradle needs forge version
forge_mc_version=1.12
forge_version=14.21.1.2387
mappings_version=snapshot_20180203
@@ -1,402 +0,0 @@
package net.minecraft.client.gui;
import com.google.common.collect.ComparisonChain;
import com.google.common.collect.Ordering;
import com.mojang.authlib.GameProfile;
import java.util.Comparator;
import java.util.List;
import javax.annotation.Nullable;
import net.minecraft.client.Minecraft;
import net.minecraft.client.network.NetHandlerPlayClient;
import net.minecraft.client.network.NetworkPlayerInfo;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EnumPlayerModelParts;
import net.minecraft.scoreboard.IScoreCriteria;
import net.minecraft.scoreboard.ScoreObjective;
import net.minecraft.scoreboard.ScorePlayerTeam;
import net.minecraft.scoreboard.Scoreboard;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.world.GameType;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class GuiPlayerTabOverlay extends Gui
{
private static final Ordering<NetworkPlayerInfo> ENTRY_ORDERING = Ordering.from(new GuiPlayerTabOverlay.PlayerComparator());
private final Minecraft mc;
private final GuiIngame guiIngame;
private ITextComponent footer;
private ITextComponent header;
/** The last time the playerlist was opened (went from not being renderd, to being rendered) */
private long lastTimeOpened;
/** Weither or not the playerlist is currently being rendered */
private boolean isBeingRendered;
public GuiPlayerTabOverlay(Minecraft mcIn, GuiIngame guiIngameIn)
{
this.mc = mcIn;
this.guiIngame = guiIngameIn;
}
/**
* Returns the name that should be renderd for the player supplied
*/
public String getPlayerName(NetworkPlayerInfo networkPlayerInfoIn)
{
return networkPlayerInfoIn.getDisplayName() != null ? networkPlayerInfoIn.getDisplayName().getFormattedText() : ScorePlayerTeam.formatPlayerName(networkPlayerInfoIn.getPlayerTeam(), networkPlayerInfoIn.getGameProfile().getName());
}
/**
* Called by GuiIngame to update the information stored in the playerlist, does not actually render the list,
* however.
*/
public void updatePlayerList(boolean willBeRendered)
{
if (willBeRendered && !this.isBeingRendered)
{
this.lastTimeOpened = Minecraft.getSystemTime();
}
this.isBeingRendered = willBeRendered;
}
/**
* Renders the playerlist, its background, headers and footers.
*/
public void renderPlayerlist(int width, Scoreboard scoreboardIn, @Nullable ScoreObjective scoreObjectiveIn)
{
NetHandlerPlayClient nethandlerplayclient = this.mc.player.connection;
List<NetworkPlayerInfo> list = ENTRY_ORDERING.<NetworkPlayerInfo>sortedCopy(nethandlerplayclient.getPlayerInfoMap());
int i = 0;
int j = 0;
for (NetworkPlayerInfo networkplayerinfo : list)
{
int k = this.mc.fontRenderer.getStringWidth(this.getPlayerName(networkplayerinfo));
i = Math.max(i, k);
if (scoreObjectiveIn != null && scoreObjectiveIn.getRenderType() != IScoreCriteria.EnumRenderType.HEARTS)
{
k = this.mc.fontRenderer.getStringWidth(" " + scoreboardIn.getOrCreateScore(networkplayerinfo.getGameProfile().getName(), scoreObjectiveIn).getScorePoints());
j = Math.max(j, k);
}
}
list = list.subList(0, Math.min(list.size(), 80));
int l3 = list.size();
int i4 = l3;
int j4;
for (j4 = 1; i4 > 20; i4 = (l3 + j4 - 1) / j4)
{
++j4;
}
//boolean flag = this.mc.isIntegratedServerRunning() || this.mc.getConnection().getNetworkManager().isEncrypted();
boolean flag = true;//Modified
int l;
if (scoreObjectiveIn != null)
{
if (scoreObjectiveIn.getRenderType() == IScoreCriteria.EnumRenderType.HEARTS)
{
l = 90;
}
else
{
l = j;
}
}
else
{
l = 0;
}
int i1 = Math.min(j4 * ((flag ? 9 : 0) + i + l + 13), width - 50) / j4;
int j1 = width / 2 - (i1 * j4 + (j4 - 1) * 5) / 2;
int k1 = 10;
int l1 = i1 * j4 + (j4 - 1) * 5;
List<String> list1 = null;
if (this.header != null)
{
list1 = this.mc.fontRenderer.listFormattedStringToWidth(this.header.getFormattedText(), width - 50);
for (String s : list1)
{
l1 = Math.max(l1, this.mc.fontRenderer.getStringWidth(s));
}
}
List<String> list2 = null;
if (this.footer != null)
{
list2 = this.mc.fontRenderer.listFormattedStringToWidth(this.footer.getFormattedText(), width - 50);
for (String s1 : list2)
{
l1 = Math.max(l1, this.mc.fontRenderer.getStringWidth(s1));
}
}
if (list1 != null)
{
drawRect(width / 2 - l1 / 2 - 1, k1 - 1, width / 2 + l1 / 2 + 1, k1 + list1.size() * this.mc.fontRenderer.FONT_HEIGHT, Integer.MIN_VALUE);
for (String s2 : list1)
{
int i2 = this.mc.fontRenderer.getStringWidth(s2);
this.mc.fontRenderer.drawStringWithShadow(s2, (float)(width / 2 - i2 / 2), (float)k1, -1);
k1 += this.mc.fontRenderer.FONT_HEIGHT;
}
++k1;
}
drawRect(width / 2 - l1 / 2 - 1, k1 - 1, width / 2 + l1 / 2 + 1, k1 + i4 * 9, Integer.MIN_VALUE);
for (int k4 = 0; k4 < l3; ++k4)
{
int l4 = k4 / i4;
int i5 = k4 % i4;
int j2 = j1 + l4 * i1 + l4 * 5;
int k2 = k1 + i5 * 9;
drawRect(j2, k2, j2 + i1, k2 + 8, 553648127);
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
GlStateManager.enableAlpha();
GlStateManager.enableBlend();
GlStateManager.tryBlendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ZERO);
if (k4 < list.size())
{
NetworkPlayerInfo networkplayerinfo1 = list.get(k4);
GameProfile gameprofile = networkplayerinfo1.getGameProfile();
if (flag)
{
EntityPlayer entityplayer = ((net.minecraft.world.World)this.mc.world).getPlayerEntityByUUID(gameprofile.getId());//Modified
boolean flag1 = entityplayer != null && entityplayer.isWearing(EnumPlayerModelParts.CAPE) && ("Dinnerbone".equals(gameprofile.getName()) || "Grumm".equals(gameprofile.getName()));
this.mc.getTextureManager().bindTexture(networkplayerinfo1.getLocationSkin());
int l2 = 8 + (flag1 ? 8 : 0);
int i3 = 8 * (flag1 ? -1 : 1);
Gui.drawScaledCustomSizeModalRect(j2, k2, 8.0F, (float)l2, 8, i3, 8, 8, 64.0F, 64.0F);
if (entityplayer != null && entityplayer.isWearing(EnumPlayerModelParts.HAT))
{
int j3 = 8 + (flag1 ? 8 : 0);
int k3 = 8 * (flag1 ? -1 : 1);
Gui.drawScaledCustomSizeModalRect(j2, k2, 40.0F, (float)j3, 8, k3, 8, 8, 64.0F, 64.0F);
}
j2 += 9;
}
String s4 = this.getPlayerName(networkplayerinfo1);
if (networkplayerinfo1.getGameType() == GameType.SPECTATOR)
{
this.mc.fontRenderer.drawStringWithShadow(TextFormatting.ITALIC + s4, (float)j2, (float)k2, -1862270977);
}
else
{
this.mc.fontRenderer.drawStringWithShadow(s4, (float)j2, (float)k2, -1);
}
if (scoreObjectiveIn != null && networkplayerinfo1.getGameType() != GameType.SPECTATOR)
{
int k5 = j2 + i + 1;
int l5 = k5 + l;
if (l5 - k5 > 5)
{
this.drawScoreboardValues(scoreObjectiveIn, k2, gameprofile.getName(), k5, l5, networkplayerinfo1);
}
}
this.drawPing(i1, j2 - (flag ? 9 : 0), k2, networkplayerinfo1);
}
}
if (list2 != null)
{
k1 = k1 + i4 * 9 + 1;
drawRect(width / 2 - l1 / 2 - 1, k1 - 1, width / 2 + l1 / 2 + 1, k1 + list2.size() * this.mc.fontRenderer.FONT_HEIGHT, Integer.MIN_VALUE);
for (String s3 : list2)
{
int j5 = this.mc.fontRenderer.getStringWidth(s3);
this.mc.fontRenderer.drawStringWithShadow(s3, (float)(width / 2 - j5 / 2), (float)k1, -1);
k1 += this.mc.fontRenderer.FONT_HEIGHT;
}
}
}
protected void drawPing(int p_175245_1_, int p_175245_2_, int p_175245_3_, NetworkPlayerInfo networkPlayerInfoIn)
{
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
this.mc.getTextureManager().bindTexture(ICONS);
int i = 0;
int j;
if (networkPlayerInfoIn.getResponseTime() < 0)
{
j = 5;
}
else if (networkPlayerInfoIn.getResponseTime() < 150)
{
j = 0;
}
else if (networkPlayerInfoIn.getResponseTime() < 300)
{
j = 1;
}
else if (networkPlayerInfoIn.getResponseTime() < 600)
{
j = 2;
}
else if (networkPlayerInfoIn.getResponseTime() < 1000)
{
j = 3;
}
else
{
j = 4;
}
this.zLevel += 100.0F;
this.drawTexturedModalRect(p_175245_2_ + p_175245_1_ - 11, p_175245_3_, 0, 176 + j * 8, 10, 8);
this.zLevel -= 100.0F;
}
private void drawScoreboardValues(ScoreObjective objective, int p_175247_2_, String name, int p_175247_4_, int p_175247_5_, NetworkPlayerInfo info)
{
int i = objective.getScoreboard().getOrCreateScore(name, objective).getScorePoints();
if (objective.getRenderType() == IScoreCriteria.EnumRenderType.HEARTS)
{
this.mc.getTextureManager().bindTexture(ICONS);
if (this.lastTimeOpened == info.getRenderVisibilityId())
{
if (i < info.getLastHealth())
{
info.setLastHealthTime(Minecraft.getSystemTime());
info.setHealthBlinkTime((long)(this.guiIngame.getUpdateCounter() + 20));
}
else if (i > info.getLastHealth())
{
info.setLastHealthTime(Minecraft.getSystemTime());
info.setHealthBlinkTime((long)(this.guiIngame.getUpdateCounter() + 10));
}
}
if (Minecraft.getSystemTime() - info.getLastHealthTime() > 1000L || this.lastTimeOpened != info.getRenderVisibilityId())
{
info.setLastHealth(i);
info.setDisplayHealth(i);
info.setLastHealthTime(Minecraft.getSystemTime());
}
info.setRenderVisibilityId(this.lastTimeOpened);
info.setLastHealth(i);
int j = MathHelper.ceil((float)Math.max(i, info.getDisplayHealth()) / 2.0F);
int k = Math.max(MathHelper.ceil((float)(i / 2)), Math.max(MathHelper.ceil((float)(info.getDisplayHealth() / 2)), 10));
boolean flag = info.getHealthBlinkTime() > (long)this.guiIngame.getUpdateCounter() && (info.getHealthBlinkTime() - (long)this.guiIngame.getUpdateCounter()) / 3L % 2L == 1L;
if (j > 0)
{
float f = Math.min((float)(p_175247_5_ - p_175247_4_ - 4) / (float)k, 9.0F);
if (f > 3.0F)
{
for (int l = j; l < k; ++l)
{
this.drawTexturedModalRect((float)p_175247_4_ + (float)l * f, (float)p_175247_2_, flag ? 25 : 16, 0, 9, 9);
}
for (int j1 = 0; j1 < j; ++j1)
{
this.drawTexturedModalRect((float)p_175247_4_ + (float)j1 * f, (float)p_175247_2_, flag ? 25 : 16, 0, 9, 9);
if (flag)
{
if (j1 * 2 + 1 < info.getDisplayHealth())
{
this.drawTexturedModalRect((float)p_175247_4_ + (float)j1 * f, (float)p_175247_2_, 70, 0, 9, 9);
}
if (j1 * 2 + 1 == info.getDisplayHealth())
{
this.drawTexturedModalRect((float)p_175247_4_ + (float)j1 * f, (float)p_175247_2_, 79, 0, 9, 9);
}
}
if (j1 * 2 + 1 < i)
{
this.drawTexturedModalRect((float)p_175247_4_ + (float)j1 * f, (float)p_175247_2_, j1 >= 10 ? 160 : 52, 0, 9, 9);
}
if (j1 * 2 + 1 == i)
{
this.drawTexturedModalRect((float)p_175247_4_ + (float)j1 * f, (float)p_175247_2_, j1 >= 10 ? 169 : 61, 0, 9, 9);
}
}
}
else
{
float f1 = MathHelper.clamp((float)i / 20.0F, 0.0F, 1.0F);
int i1 = (int)((1.0F - f1) * 255.0F) << 16 | (int)(f1 * 255.0F) << 8;
String s = "" + (float)i / 2.0F;
if (p_175247_5_ - this.mc.fontRenderer.getStringWidth(s + "hp") >= p_175247_4_)
{
s = s + "hp";
}
this.mc.fontRenderer.drawStringWithShadow(s, (float)((p_175247_5_ + p_175247_4_) / 2 - this.mc.fontRenderer.getStringWidth(s) / 2), (float)p_175247_2_, i1);
}
}
}
else
{
String s1 = TextFormatting.YELLOW + "" + i;
this.mc.fontRenderer.drawStringWithShadow(s1, (float)(p_175247_5_ - this.mc.fontRenderer.getStringWidth(s1)), (float)p_175247_2_, 16777215);
}
}
public void setFooter(@Nullable ITextComponent footerIn)
{
this.footer = footerIn;
}
public void setHeader(@Nullable ITextComponent headerIn)
{
this.header = headerIn;
}
public void resetFooterHeader()
{
this.header = null;
this.footer = null;
}
@SideOnly(Side.CLIENT)
static class PlayerComparator implements Comparator<NetworkPlayerInfo>
{
private PlayerComparator()
{
}
public int compare(NetworkPlayerInfo p_compare_1_, NetworkPlayerInfo p_compare_2_)
{
ScorePlayerTeam scoreplayerteam = p_compare_1_.getPlayerTeam();
ScorePlayerTeam scoreplayerteam1 = p_compare_2_.getPlayerTeam();
return ComparisonChain.start().compareTrueFirst(p_compare_1_.getGameType() != GameType.SPECTATOR, p_compare_2_.getGameType() != GameType.SPECTATOR).compare(scoreplayerteam != null ? scoreplayerteam.getName() : "", scoreplayerteam1 != null ? scoreplayerteam1.getName() : "").compare(p_compare_1_.getGameProfile().getName(), p_compare_2_.getGameProfile().getName()).result();
}
}
}
@@ -1,54 +0,0 @@
package net.minecraft.client.gui.spectator;
import com.mojang.authlib.GameProfile;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.AbstractClientPlayer;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.network.play.client.CPacketSpectate;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextComponentString;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class PlayerMenuObject implements ISpectatorMenuObject
{
private final GameProfile profile;
private final ResourceLocation resourceLocation;
public PlayerMenuObject(GameProfile profileIn)
{
this.profile = profileIn;
/*
this.resourceLocation = AbstractClientPlayer.getLocationSkin(profileIn.getName());
AbstractClientPlayer.getDownloadImageSkin(this.resourceLocation, profileIn.getName());
*/
this.resourceLocation = customskinloader.fake.FakeClientPlayer.getLocationSkin(profileIn.getName());
customskinloader.fake.FakeClientPlayer.getDownloadImageSkin(this.resourceLocation, profileIn.getName());
}
public void selectItem(SpectatorMenu menu)
{
Minecraft.getMinecraft().getConnection().sendPacket(new CPacketSpectate(this.profile.getId()));
}
public ITextComponent getSpectatorName()
{
return new TextComponentString(this.profile.getName());
}
public void renderIcon(float brightness, int alpha)
{
Minecraft.getMinecraft().getTextureManager().bindTexture(this.resourceLocation);
GlStateManager.color(1.0F, 1.0F, 1.0F, (float)alpha / 255.0F);
Gui.drawScaledCustomSizeModalRect(2, 2, 8.0F, 8.0F, 8, 8, 12, 12, 64.0F, 64.0F);
Gui.drawScaledCustomSizeModalRect(2, 2, 40.0F, 8.0F, 8, 8, 12, 12, 64.0F, 64.0F);
}
public boolean isEnabled()
{
return true;
}
}
@@ -1,90 +0,0 @@
package net.minecraft.client.resources;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.Maps;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.minecraft.InsecureTextureException;
import com.mojang.authlib.minecraft.MinecraftProfileTexture;
import com.mojang.authlib.minecraft.MinecraftSessionService;
import com.mojang.authlib.minecraft.MinecraftProfileTexture.Type;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.IImageBuffer;
import net.minecraft.client.renderer.ImageBufferDownload;
import net.minecraft.client.renderer.ThreadDownloadImageData;
import net.minecraft.client.renderer.texture.ITextureObject;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.util.ResourceLocation;
public class SkinManager
{
private static final ExecutorService THREAD_POOL = new ThreadPoolExecutor(0, 2, 1L, TimeUnit.MINUTES, new LinkedBlockingQueue());
private final TextureManager textureManager;
private final File skinCacheDir;
private final MinecraftSessionService sessionService;
private final LoadingCache<GameProfile, Map<Type, MinecraftProfileTexture>> skinCacheLoader;
private customskinloader.fake.FakeSkinManager fakeManager;//Fake Skin Manager
public SkinManager(TextureManager textureManagerInstance, File skinCacheDirectory, MinecraftSessionService sessionService)
{
this.textureManager = textureManagerInstance;
this.skinCacheDir = skinCacheDirectory;
this.sessionService = sessionService;
this.skinCacheLoader = CacheBuilder.newBuilder().expireAfterAccess(15L, TimeUnit.SECONDS).<GameProfile, Map<Type, MinecraftProfileTexture>>build(new CacheLoader<GameProfile, Map<Type, MinecraftProfileTexture>>()
{
public Map<Type, MinecraftProfileTexture> load(GameProfile p_load_1_) throws Exception
{
try
{
return Minecraft.getMinecraft().getSessionService().getTextures(p_load_1_, false);
}
catch (Throwable var3)
{
return Maps.<Type, MinecraftProfileTexture>newHashMap();
}
}
});
this.fakeManager=new customskinloader.fake.FakeSkinManager(textureManagerInstance,skinCacheDirectory,sessionService);
}
/**
* Used in the Skull renderer to fetch a skin. May download the skin if it's not in the cache
*/
public ResourceLocation loadSkin(MinecraftProfileTexture profileTexture, Type textureType)
{
return this.loadSkin(profileTexture, textureType, (SkinManager.SkinAvailableCallback)null);
}
/**
* May download the skin if its not in the cache, can be passed a SkinManager#SkinAvailableCallback for handling
*/
public ResourceLocation loadSkin(final MinecraftProfileTexture profileTexture, final Type textureType, @Nullable final SkinManager.SkinAvailableCallback skinAvailableCallback)
{
return this.fakeManager.loadSkin(profileTexture, textureType, skinAvailableCallback);
}
public void loadProfileTextures(final GameProfile profile, final SkinManager.SkinAvailableCallback skinAvailableCallback, final boolean requireSecure)
{
this.fakeManager.loadProfileTextures(profile, skinAvailableCallback, requireSecure);
}
public Map<Type, MinecraftProfileTexture> loadSkinFromCache(GameProfile profile)
{
return this.fakeManager.loadSkinFromCache(profile);
}
public interface SkinAvailableCallback
{
void skinAvailable(Type typeIn, ResourceLocation location, MinecraftProfileTexture profileTexture);
}
}
-2
View File
@@ -1,2 +0,0 @@
/build/
/src/main/
-6
View File
@@ -1,6 +0,0 @@
minecraft_version=1.12.1
minecraft_full_versions=1.12.1,1.12.2
#forge gradle needs forge version
forge_mc_version=1.12.2
forge_version=14.23.2.2611
mappings_version=snapshot_20180210
@@ -1,402 +0,0 @@
package net.minecraft.client.gui;
import com.google.common.collect.ComparisonChain;
import com.google.common.collect.Ordering;
import com.mojang.authlib.GameProfile;
import java.util.Comparator;
import java.util.List;
import javax.annotation.Nullable;
import net.minecraft.client.Minecraft;
import net.minecraft.client.network.NetHandlerPlayClient;
import net.minecraft.client.network.NetworkPlayerInfo;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EnumPlayerModelParts;
import net.minecraft.scoreboard.IScoreCriteria;
import net.minecraft.scoreboard.ScoreObjective;
import net.minecraft.scoreboard.ScorePlayerTeam;
import net.minecraft.scoreboard.Scoreboard;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.world.GameType;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class GuiPlayerTabOverlay extends Gui
{
private static final Ordering<NetworkPlayerInfo> ENTRY_ORDERING = Ordering.from(new GuiPlayerTabOverlay.PlayerComparator());
private final Minecraft mc;
private final GuiIngame guiIngame;
private ITextComponent footer;
private ITextComponent header;
/** The last time the playerlist was opened (went from not being renderd, to being rendered) */
private long lastTimeOpened;
/** Weither or not the playerlist is currently being rendered */
private boolean isBeingRendered;
public GuiPlayerTabOverlay(Minecraft mcIn, GuiIngame guiIngameIn)
{
this.mc = mcIn;
this.guiIngame = guiIngameIn;
}
/**
* Returns the name that should be renderd for the player supplied
*/
public String getPlayerName(NetworkPlayerInfo networkPlayerInfoIn)
{
return networkPlayerInfoIn.getDisplayName() != null ? networkPlayerInfoIn.getDisplayName().getFormattedText() : ScorePlayerTeam.formatPlayerName(networkPlayerInfoIn.getPlayerTeam(), networkPlayerInfoIn.getGameProfile().getName());
}
/**
* Called by GuiIngame to update the information stored in the playerlist, does not actually render the list,
* however.
*/
public void updatePlayerList(boolean willBeRendered)
{
if (willBeRendered && !this.isBeingRendered)
{
this.lastTimeOpened = Minecraft.getSystemTime();
}
this.isBeingRendered = willBeRendered;
}
/**
* Renders the playerlist, its background, headers and footers.
*/
public void renderPlayerlist(int width, Scoreboard scoreboardIn, @Nullable ScoreObjective scoreObjectiveIn)
{
NetHandlerPlayClient nethandlerplayclient = this.mc.player.connection;
List<NetworkPlayerInfo> list = ENTRY_ORDERING.<NetworkPlayerInfo>sortedCopy(nethandlerplayclient.getPlayerInfoMap());
int i = 0;
int j = 0;
for (NetworkPlayerInfo networkplayerinfo : list)
{
int k = this.mc.fontRenderer.getStringWidth(this.getPlayerName(networkplayerinfo));
i = Math.max(i, k);
if (scoreObjectiveIn != null && scoreObjectiveIn.getRenderType() != IScoreCriteria.EnumRenderType.HEARTS)
{
k = this.mc.fontRenderer.getStringWidth(" " + scoreboardIn.getOrCreateScore(networkplayerinfo.getGameProfile().getName(), scoreObjectiveIn).getScorePoints());
j = Math.max(j, k);
}
}
list = list.subList(0, Math.min(list.size(), 80));
int l3 = list.size();
int i4 = l3;
int j4;
for (j4 = 1; i4 > 20; i4 = (l3 + j4 - 1) / j4)
{
++j4;
}
//boolean flag = this.mc.isIntegratedServerRunning() || this.mc.getConnection().getNetworkManager().isEncrypted();
boolean flag = true;//Modified
int l;
if (scoreObjectiveIn != null)
{
if (scoreObjectiveIn.getRenderType() == IScoreCriteria.EnumRenderType.HEARTS)
{
l = 90;
}
else
{
l = j;
}
}
else
{
l = 0;
}
int i1 = Math.min(j4 * ((flag ? 9 : 0) + i + l + 13), width - 50) / j4;
int j1 = width / 2 - (i1 * j4 + (j4 - 1) * 5) / 2;
int k1 = 10;
int l1 = i1 * j4 + (j4 - 1) * 5;
List<String> list1 = null;
if (this.header != null)
{
list1 = this.mc.fontRenderer.listFormattedStringToWidth(this.header.getFormattedText(), width - 50);
for (String s : list1)
{
l1 = Math.max(l1, this.mc.fontRenderer.getStringWidth(s));
}
}
List<String> list2 = null;
if (this.footer != null)
{
list2 = this.mc.fontRenderer.listFormattedStringToWidth(this.footer.getFormattedText(), width - 50);
for (String s1 : list2)
{
l1 = Math.max(l1, this.mc.fontRenderer.getStringWidth(s1));
}
}
if (list1 != null)
{
drawRect(width / 2 - l1 / 2 - 1, k1 - 1, width / 2 + l1 / 2 + 1, k1 + list1.size() * this.mc.fontRenderer.FONT_HEIGHT, Integer.MIN_VALUE);
for (String s2 : list1)
{
int i2 = this.mc.fontRenderer.getStringWidth(s2);
this.mc.fontRenderer.drawStringWithShadow(s2, (float)(width / 2 - i2 / 2), (float)k1, -1);
k1 += this.mc.fontRenderer.FONT_HEIGHT;
}
++k1;
}
drawRect(width / 2 - l1 / 2 - 1, k1 - 1, width / 2 + l1 / 2 + 1, k1 + i4 * 9, Integer.MIN_VALUE);
for (int k4 = 0; k4 < l3; ++k4)
{
int l4 = k4 / i4;
int i5 = k4 % i4;
int j2 = j1 + l4 * i1 + l4 * 5;
int k2 = k1 + i5 * 9;
drawRect(j2, k2, j2 + i1, k2 + 8, 553648127);
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
GlStateManager.enableAlpha();
GlStateManager.enableBlend();
GlStateManager.tryBlendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ZERO);
if (k4 < list.size())
{
NetworkPlayerInfo networkplayerinfo1 = list.get(k4);
GameProfile gameprofile = networkplayerinfo1.getGameProfile();
if (flag)
{
EntityPlayer entityplayer = ((net.minecraft.world.World)this.mc.world).getPlayerEntityByUUID(gameprofile.getId());//Modified
boolean flag1 = entityplayer != null && entityplayer.isWearing(EnumPlayerModelParts.CAPE) && ("Dinnerbone".equals(gameprofile.getName()) || "Grumm".equals(gameprofile.getName()));
this.mc.getTextureManager().bindTexture(networkplayerinfo1.getLocationSkin());
int l2 = 8 + (flag1 ? 8 : 0);
int i3 = 8 * (flag1 ? -1 : 1);
Gui.drawScaledCustomSizeModalRect(j2, k2, 8.0F, (float)l2, 8, i3, 8, 8, 64.0F, 64.0F);
if (entityplayer != null && entityplayer.isWearing(EnumPlayerModelParts.HAT))
{
int j3 = 8 + (flag1 ? 8 : 0);
int k3 = 8 * (flag1 ? -1 : 1);
Gui.drawScaledCustomSizeModalRect(j2, k2, 40.0F, (float)j3, 8, k3, 8, 8, 64.0F, 64.0F);
}
j2 += 9;
}
String s4 = this.getPlayerName(networkplayerinfo1);
if (networkplayerinfo1.getGameType() == GameType.SPECTATOR)
{
this.mc.fontRenderer.drawStringWithShadow(TextFormatting.ITALIC + s4, (float)j2, (float)k2, -1862270977);
}
else
{
this.mc.fontRenderer.drawStringWithShadow(s4, (float)j2, (float)k2, -1);
}
if (scoreObjectiveIn != null && networkplayerinfo1.getGameType() != GameType.SPECTATOR)
{
int k5 = j2 + i + 1;
int l5 = k5 + l;
if (l5 - k5 > 5)
{
this.drawScoreboardValues(scoreObjectiveIn, k2, gameprofile.getName(), k5, l5, networkplayerinfo1);
}
}
this.drawPing(i1, j2 - (flag ? 9 : 0), k2, networkplayerinfo1);
}
}
if (list2 != null)
{
k1 = k1 + i4 * 9 + 1;
drawRect(width / 2 - l1 / 2 - 1, k1 - 1, width / 2 + l1 / 2 + 1, k1 + list2.size() * this.mc.fontRenderer.FONT_HEIGHT, Integer.MIN_VALUE);
for (String s3 : list2)
{
int j5 = this.mc.fontRenderer.getStringWidth(s3);
this.mc.fontRenderer.drawStringWithShadow(s3, (float)(width / 2 - j5 / 2), (float)k1, -1);
k1 += this.mc.fontRenderer.FONT_HEIGHT;
}
}
}
protected void drawPing(int p_175245_1_, int p_175245_2_, int p_175245_3_, NetworkPlayerInfo networkPlayerInfoIn)
{
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
this.mc.getTextureManager().bindTexture(ICONS);
int i = 0;
int j;
if (networkPlayerInfoIn.getResponseTime() < 0)
{
j = 5;
}
else if (networkPlayerInfoIn.getResponseTime() < 150)
{
j = 0;
}
else if (networkPlayerInfoIn.getResponseTime() < 300)
{
j = 1;
}
else if (networkPlayerInfoIn.getResponseTime() < 600)
{
j = 2;
}
else if (networkPlayerInfoIn.getResponseTime() < 1000)
{
j = 3;
}
else
{
j = 4;
}
this.zLevel += 100.0F;
this.drawTexturedModalRect(p_175245_2_ + p_175245_1_ - 11, p_175245_3_, 0, 176 + j * 8, 10, 8);
this.zLevel -= 100.0F;
}
private void drawScoreboardValues(ScoreObjective objective, int p_175247_2_, String name, int p_175247_4_, int p_175247_5_, NetworkPlayerInfo info)
{
int i = objective.getScoreboard().getOrCreateScore(name, objective).getScorePoints();
if (objective.getRenderType() == IScoreCriteria.EnumRenderType.HEARTS)
{
this.mc.getTextureManager().bindTexture(ICONS);
if (this.lastTimeOpened == info.getRenderVisibilityId())
{
if (i < info.getLastHealth())
{
info.setLastHealthTime(Minecraft.getSystemTime());
info.setHealthBlinkTime((long)(this.guiIngame.getUpdateCounter() + 20));
}
else if (i > info.getLastHealth())
{
info.setLastHealthTime(Minecraft.getSystemTime());
info.setHealthBlinkTime((long)(this.guiIngame.getUpdateCounter() + 10));
}
}
if (Minecraft.getSystemTime() - info.getLastHealthTime() > 1000L || this.lastTimeOpened != info.getRenderVisibilityId())
{
info.setLastHealth(i);
info.setDisplayHealth(i);
info.setLastHealthTime(Minecraft.getSystemTime());
}
info.setRenderVisibilityId(this.lastTimeOpened);
info.setLastHealth(i);
int j = MathHelper.ceil((float)Math.max(i, info.getDisplayHealth()) / 2.0F);
int k = Math.max(MathHelper.ceil((float)(i / 2)), Math.max(MathHelper.ceil((float)(info.getDisplayHealth() / 2)), 10));
boolean flag = info.getHealthBlinkTime() > (long)this.guiIngame.getUpdateCounter() && (info.getHealthBlinkTime() - (long)this.guiIngame.getUpdateCounter()) / 3L % 2L == 1L;
if (j > 0)
{
float f = Math.min((float)(p_175247_5_ - p_175247_4_ - 4) / (float)k, 9.0F);
if (f > 3.0F)
{
for (int l = j; l < k; ++l)
{
this.drawTexturedModalRect((float)p_175247_4_ + (float)l * f, (float)p_175247_2_, flag ? 25 : 16, 0, 9, 9);
}
for (int j1 = 0; j1 < j; ++j1)
{
this.drawTexturedModalRect((float)p_175247_4_ + (float)j1 * f, (float)p_175247_2_, flag ? 25 : 16, 0, 9, 9);
if (flag)
{
if (j1 * 2 + 1 < info.getDisplayHealth())
{
this.drawTexturedModalRect((float)p_175247_4_ + (float)j1 * f, (float)p_175247_2_, 70, 0, 9, 9);
}
if (j1 * 2 + 1 == info.getDisplayHealth())
{
this.drawTexturedModalRect((float)p_175247_4_ + (float)j1 * f, (float)p_175247_2_, 79, 0, 9, 9);
}
}
if (j1 * 2 + 1 < i)
{
this.drawTexturedModalRect((float)p_175247_4_ + (float)j1 * f, (float)p_175247_2_, j1 >= 10 ? 160 : 52, 0, 9, 9);
}
if (j1 * 2 + 1 == i)
{
this.drawTexturedModalRect((float)p_175247_4_ + (float)j1 * f, (float)p_175247_2_, j1 >= 10 ? 169 : 61, 0, 9, 9);
}
}
}
else
{
float f1 = MathHelper.clamp((float)i / 20.0F, 0.0F, 1.0F);
int i1 = (int)((1.0F - f1) * 255.0F) << 16 | (int)(f1 * 255.0F) << 8;
String s = "" + (float)i / 2.0F;
if (p_175247_5_ - this.mc.fontRenderer.getStringWidth(s + "hp") >= p_175247_4_)
{
s = s + "hp";
}
this.mc.fontRenderer.drawStringWithShadow(s, (float)((p_175247_5_ + p_175247_4_) / 2 - this.mc.fontRenderer.getStringWidth(s) / 2), (float)p_175247_2_, i1);
}
}
}
else
{
String s1 = TextFormatting.YELLOW + "" + i;
this.mc.fontRenderer.drawStringWithShadow(s1, (float)(p_175247_5_ - this.mc.fontRenderer.getStringWidth(s1)), (float)p_175247_2_, 16777215);
}
}
public void setFooter(@Nullable ITextComponent footerIn)
{
this.footer = footerIn;
}
public void setHeader(@Nullable ITextComponent headerIn)
{
this.header = headerIn;
}
public void resetFooterHeader()
{
this.header = null;
this.footer = null;
}
@SideOnly(Side.CLIENT)
static class PlayerComparator implements Comparator<NetworkPlayerInfo>
{
private PlayerComparator()
{
}
public int compare(NetworkPlayerInfo p_compare_1_, NetworkPlayerInfo p_compare_2_)
{
ScorePlayerTeam scoreplayerteam = p_compare_1_.getPlayerTeam();
ScorePlayerTeam scoreplayerteam1 = p_compare_2_.getPlayerTeam();
return ComparisonChain.start().compareTrueFirst(p_compare_1_.getGameType() != GameType.SPECTATOR, p_compare_2_.getGameType() != GameType.SPECTATOR).compare(scoreplayerteam != null ? scoreplayerteam.getName() : "", scoreplayerteam1 != null ? scoreplayerteam1.getName() : "").compare(p_compare_1_.getGameProfile().getName(), p_compare_2_.getGameProfile().getName()).result();
}
}
}
@@ -1,54 +0,0 @@
package net.minecraft.client.gui.spectator;
import com.mojang.authlib.GameProfile;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.AbstractClientPlayer;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.network.play.client.CPacketSpectate;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextComponentString;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class PlayerMenuObject implements ISpectatorMenuObject
{
private final GameProfile profile;
private final ResourceLocation resourceLocation;
public PlayerMenuObject(GameProfile profileIn)
{
this.profile = profileIn;
/*
this.resourceLocation = AbstractClientPlayer.getLocationSkin(profileIn.getName());
AbstractClientPlayer.getDownloadImageSkin(this.resourceLocation, profileIn.getName());
*/
this.resourceLocation = customskinloader.fake.FakeClientPlayer.getLocationSkin(profileIn.getName());
customskinloader.fake.FakeClientPlayer.getDownloadImageSkin(this.resourceLocation, profileIn.getName());
}
public void selectItem(SpectatorMenu menu)
{
Minecraft.getMinecraft().getConnection().sendPacket(new CPacketSpectate(this.profile.getId()));
}
public ITextComponent getSpectatorName()
{
return new TextComponentString(this.profile.getName());
}
public void renderIcon(float brightness, int alpha)
{
Minecraft.getMinecraft().getTextureManager().bindTexture(this.resourceLocation);
GlStateManager.color(1.0F, 1.0F, 1.0F, (float)alpha / 255.0F);
Gui.drawScaledCustomSizeModalRect(2, 2, 8.0F, 8.0F, 8, 8, 12, 12, 64.0F, 64.0F);
Gui.drawScaledCustomSizeModalRect(2, 2, 40.0F, 8.0F, 8, 8, 12, 12, 64.0F, 64.0F);
}
public boolean isEnabled()
{
return true;
}
}
@@ -1,91 +0,0 @@
package net.minecraft.client.resources;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.Maps;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.minecraft.InsecureTextureException;
import com.mojang.authlib.minecraft.MinecraftProfileTexture;
import com.mojang.authlib.minecraft.MinecraftSessionService;
import com.mojang.authlib.minecraft.MinecraftProfileTexture.Type;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.IImageBuffer;
import net.minecraft.client.renderer.ImageBufferDownload;
import net.minecraft.client.renderer.ThreadDownloadImageData;
import net.minecraft.client.renderer.texture.ITextureObject;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.util.ResourceLocation;
//From 1.12-mcp940
public class SkinManager
{
private static final ExecutorService THREAD_POOL = new ThreadPoolExecutor(0, 2, 1L, TimeUnit.MINUTES, new LinkedBlockingQueue());
private final TextureManager textureManager;
private final File skinCacheDir;
private final MinecraftSessionService sessionService;
private final LoadingCache<GameProfile, Map<Type, MinecraftProfileTexture>> skinCacheLoader;
private customskinloader.fake.FakeSkinManager fakeManager;//Fake Skin Manager
public SkinManager(TextureManager textureManagerInstance, File skinCacheDirectory, MinecraftSessionService sessionService)
{
this.textureManager = textureManagerInstance;
this.skinCacheDir = skinCacheDirectory;
this.sessionService = sessionService;
this.skinCacheLoader = CacheBuilder.newBuilder().expireAfterAccess(15L, TimeUnit.SECONDS).<GameProfile, Map<Type, MinecraftProfileTexture>>build(new CacheLoader<GameProfile, Map<Type, MinecraftProfileTexture>>()
{
public Map<Type, MinecraftProfileTexture> load(GameProfile p_load_1_) throws Exception
{
try
{
return Minecraft.getMinecraft().getSessionService().getTextures(p_load_1_, false);
}
catch (Throwable var3)
{
return Maps.<Type, MinecraftProfileTexture>newHashMap();
}
}
});
this.fakeManager=new customskinloader.fake.FakeSkinManager(textureManagerInstance,skinCacheDirectory,sessionService);
}
/**
* Used in the Skull renderer to fetch a skin. May download the skin if it's not in the cache
*/
public ResourceLocation loadSkin(MinecraftProfileTexture profileTexture, Type textureType)
{
return this.loadSkin(profileTexture, textureType, (SkinManager.SkinAvailableCallback)null);
}
/**
* May download the skin if its not in the cache, can be passed a SkinManager#SkinAvailableCallback for handling
*/
public ResourceLocation loadSkin(final MinecraftProfileTexture profileTexture, final Type textureType, @Nullable final SkinManager.SkinAvailableCallback skinAvailableCallback)
{
return this.fakeManager.loadSkin(profileTexture, textureType, skinAvailableCallback);
}
public void loadProfileTextures(final GameProfile profile, final SkinManager.SkinAvailableCallback skinAvailableCallback, final boolean requireSecure)
{
this.fakeManager.loadProfileTextures(profile, skinAvailableCallback, requireSecure);
}
public Map<Type, MinecraftProfileTexture> loadSkinFromCache(GameProfile profile)
{
return this.fakeManager.loadSkinFromCache(profile);
}
public interface SkinAvailableCallback
{
void skinAvailable(Type typeIn, ResourceLocation location, MinecraftProfileTexture profileTexture);
}
}
+152
View File
@@ -0,0 +1,152 @@
# Development and Contribution
## Building
1. Run `./gradlew setupDecompWorkspace clean build` command.
1. The built jars are all in `${rootprojectDir}/build/libs` folder.
*NOTICE: The jar file with specific Minecraft version is for the vanilla edition without Forge and Fabric. The json files are launcher profiles which only work when building with our CI server.*
## Running and Testing
For now, CustomSkinLoader is unable to run under self development environment, so it needs to add to another development environment as a library.
There are the available versions in different environments below:
| | Forge | Fabric |
|:-----------------------:|:-----------------------------------------------------------------------------------------------------------------------:|:----------------------------------------------------------------------------------------------------------------------------:|
| Runtime Environment | forge-1.8-11.14.0.1237 ~ 1.13.2-25.0.22<br/> forge-1.13.2-25.0.42 ~ latest | fabric-loader-0.4.3+build.134 ~ latest<br/> Minecraft 18w43b ~ latest<br/> *fabric-api is not required* |
| Development Environment | ForgeGradle-2.1-SNAPSHOT ~ latest<br/> forge-1.8-11.14.3.1503 ~ 1.12.2-14.23.5.2855<br/> forge-1.13.2-25.0.198 ~ latest | fabric-loom-(?) ~ latest<br/> fabric-loader-0.12.0 ~ latest<br/> Minecraft 18w49a ~ latest<br/> *fabric-api is not required* |
### Preliminary steps for testing local builds
1. Create a new empty minecraft development environment.
1. Add below contents to `build.gradle`:
```gradle
repositories {
maven {
url = "file:/${projectDir}/local-repo"
}
}
```
1. Create these folders in the new project directory, then copy the built jar and source jar into it:
```
Forge 1.8 ~ 1.16.5: ./local-repo/mods/CustomSkinLoader_ForgeLegacy/${version}
Forge 1.17.1 ~ latest: ./local-repo/mods/CustomSkinLoader_ForgeActive/${version}
Fabric: ./local-repo/mods/CustomSkinLoader_Fabric/${version}
```
*`${version}` should be repalced with something like `14.14-SNAPSHOT-00` manually*
1. Create a pom file in the same folder:
- Forge 1.8 ~ 1.16.5: `CustomSkinLoader_ForgeLegacy-${version}.pom`
```xml
<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>mods</groupId>
<artifactId>CustomSkinLoader_ForgeLegacy</artifactId>
<!-- `${version}` should be repalced with something like `14.14-SNAPSHOT-00` manually -->
<version>${version}</version>
</project>
```
- Forge 1.17.1 ~ latest: `CustomSkinLoader_ForgeActive-${version}.pom`
```xml
<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>mods</groupId>
<artifactId>CustomSkinLoader_ForgeActive</artifactId>
<!-- `${version}` should be repalced with something like `14.14-SNAPSHOT-00` manually -->
<version>${version}</version>
</project>
```
- Fabric: `CustomSkinLoader_Fabric-${version}.pom`
```xml
<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>mods</groupId>
<artifactId>CustomSkinLoader_Fabric</artifactId>
<!-- `${version}` should be repalced with something like `14.14-SNAPSHOT-00` manually -->
<version>${version}</version>
</project>
```
### For ForgeGradle 2.x ( forge-1.8-11.14.3.1503 ~ forge-1.12.2-14.23.5.2847 )
1. Add below contents to `build.gradle`:
```gradle
dependencies {
deobfCompile "mods:CustomSkinLoader_ForgeLegacy:14.14-SNAPSHOT-00"
}
minecraft {
clientRunArgs += ["--tweakClass", "customskinloader.forge.ForgeDevTweaker", "--username", "<Your username>"]
}
```
1. Run `./gradlew setupDecompWorkspace eclipse` command.
1. Due to the run configurations which generated by ForgeGradle 2 has not been compatible with IntelliJ IDEA 2020 and above, we recommend to install [Eclipser](https://plugins.jetbrains.com/plugin/7153-eclipser) plugin. It can convert Eclipse run configurations to IDEA. (Right click to `*.launch` file in project folder, then select `Convert with Eclipser`, then a new IDEA run configuration will be created.)
1. For IDEA, open `Run/Debug Configurations` dialog, change classpath of module to the name contains `.main`.
1. Add `--tweakClass customskinloader.forge.ForgeDevTweaker --username <Your username>` to CLI arguments in `Run/Debug Configurations` dialog.
1. Then you can debug the mod in IDE or through `./gradlew runClient` command.
### For ForgeGradle 3.x ~ 5.x ( forge-1.12.2-14.23.5.2851 ~ latest )
1. Add below contents to `build.gradle`:
```gradle
dependencies {
implementation fg.deobf("mods:CustomSkinLoader_ForgeLegacy:14.14-SNAPSHOT-00") // Only required for MinecraftForge 1.8 ~ 1.16.5
implementation fg.deobf("mods:CustomSkinLoader_ForgeActive:14.14-SNAPSHOT-00") // Only required for MinecraftForge 1.17.1 ~ latest
}
minecraft {
runs {
client {
args += ["--username", "<Your username>"]
args += ["--tweakClass", "customskinloader.forge.ForgeDevTweaker"] // Only required for MinecraftForge 1.12.2
}
}
}
```
1. Setup the development environment and run the game as usual.
### For fabric-loom ( fabric-loader-0.12.0 ~ latest )
1. Add below contents to `build.gradle`:
```gradle
dependencies {
modImplementation "mods:CustomSkinLoader_Fabric:14.14-SNAPSHOT-00"
}
tasks.runClient {
args += ["--username", "<Your username>"]
}
```
1. Add `--username <Your username>` to CLI arguments in `Run/Debug Configurations` dialog.
1. Run the game in IDE or through `./gradlew runClient` command..
## Depend on release builds
1. Check the latest version in https://littlesk.in/csl-latest .
1. Add below contents to `build.gradle`:
```gradle
// Before Gradle 5.x
repositories {
ivy {
url = "https://csl.littleservice.cn/"
layout "pattern", {
artifact "[organisation]/[artifact]-[revision](-[classifier])(.[ext])"
}
}
}
// After Gradle 6.x
repositories {
ivy {
url = "https://csl.littleservice.cn/"
metadataSources {
artifact()
}
patternLayout {
artifact "[organisation]/[artifact]-[revision](-[classifier])(.[ext])"
}
}
}
```
1. Follow the same steps in **Running and Testing**.
## Developing
- CustomSkinLoader is based on forge-1.12.2-14.23.5.2768 currently, including Fabric edition. We use custom reobfuscation mappings such as [Fabric.tsrg](Fabric/Fabric.tsrg) and [mixin.tsrg](Fabric/mixin.tsrg) to generate different editions jar and Mixin reference jsons.
- The source codes are all in `${projectDir}/sources` and resource files are in `${projectDir}/resources` instead of `src/main/java` and `src/main/resources`.
- Do not add other required mods.
Binary file not shown.
+5
View File
@@ -0,0 +1,5 @@
forge_mc_version=1.12.2
forge_version=14.23.5.2768
mappings_version=stable_39
# this subproject is only to provide dependency for other subprojects.
is_real_project=false
+2 -1
View File
@@ -6,5 +6,6 @@
"mcFullVersions": "${mcFullVersions}", "mcFullVersions": "${mcFullVersions}",
"forgeVersion": "${forgeVersion}", "forgeVersion": "${forgeVersion}",
"gitVersion": "${gitVersion}", "gitVersion": "${gitVersion}",
"buildUrl": "${buildUrl}" "buildUrl": "${buildUrl}",
"buildTime": "${releaseTime}"
} }
@@ -2,17 +2,22 @@ package customskinloader;
import java.io.File; import java.io.File;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
import com.mojang.authlib.GameProfile; import com.mojang.authlib.GameProfile;
import com.mojang.authlib.minecraft.MinecraftProfileTexture; import com.mojang.authlib.minecraft.MinecraftProfileTexture;
import com.mojang.authlib.minecraft.MinecraftProfileTexture.Type;
import customskinloader.config.Config; import customskinloader.config.Config;
import customskinloader.config.SkinSiteProfile; import customskinloader.config.SkinSiteProfile;
import customskinloader.loader.*; import customskinloader.loader.ProfileLoader;
import customskinloader.profile.DynamicSkullManager; import customskinloader.profile.DynamicSkullManager;
import customskinloader.profile.ModelManager0; import customskinloader.profile.ModelManager0;
import customskinloader.profile.ProfileCache; import customskinloader.profile.ProfileCache;
@@ -21,122 +26,161 @@ import customskinloader.utils.MinecraftUtil;
/** /**
* Custom skin loader mod for Minecraft. * Custom skin loader mod for Minecraft.
* @author (C) Jeremy Lam [JLChnToZ] 2013 & Alexander Xia [xfl03] 2014-2018 *
* @author (C) Jeremy Lam [JLChnToZ] 2013-2014 & Alexander Xia [xfl03] 2014-2020
* @version @MOD_FULL_VERSION@ * @version @MOD_FULL_VERSION@
*/ */
public class CustomSkinLoader { public class CustomSkinLoader {
public static final String CustomSkinLoader_VERSION="@MOD_VERSION@"; public static final String CustomSkinLoader_VERSION = "@MOD_VERSION@";
public static final String CustomSkinLoader_FULL_VERSION="@MOD_FULL_VERSION@"; public static final String CustomSkinLoader_FULL_VERSION = "@MOD_FULL_VERSION@";
public static final int CustomSkinLoader_BUILD_NUMBER = Integer.parseInt("@MOD_BUILD_NUMBER@");
public static final File DATA_DIR=new File(MinecraftUtil.getMinecraftDataDir(),"CustomSkinLoader"), public static final File
LOG_FILE=new File(DATA_DIR,"CustomSkinLoader.log"), DATA_DIR = new File(MinecraftUtil.getMinecraftDataDir(), "CustomSkinLoader"),
CONFIG_FILE=new File(DATA_DIR,"CustomSkinLoader.json"); LOG_FILE = new File(DATA_DIR, "CustomSkinLoader.log"),
public static final SkinSiteProfile[] DEFAULT_LOAD_LIST={ CONFIG_FILE = new File(DATA_DIR, "CustomSkinLoader.json");
SkinSiteProfile.createMojangAPI("Mojang"),
SkinSiteProfile.createCustomSkinAPI("LittleSkin","https://mcskin.littleservice.cn/"),
SkinSiteProfile.createCustomSkinAPI("BlessingSkin","http://skin.prinzeugen.net/"),
//OneSkin has been removed temporarily
//SkinSiteProfile.createCustomSkinAPI("OneSkin","http://fleey.cn/skin/skin_user/skin_json.php/"),
//Minecrack could not load skin correctly
//SkinSiteProfile.creatLegacy("Minecrack","http://minecrack.fr.nf/mc/skinsminecrackd/{USERNAME}.png","http://minecrack.fr.nf/mc/cloaksminecrackd/{USERNAME}.png",null),
SkinSiteProfile.createUniSkinAPI("SkinMe","http://www.skinme.cc/uniskin/"),
SkinSiteProfile.createLegacy("LocalSkin","LocalSkin/skins/{USERNAME}.png","LocalSkin/capes/{USERNAME}.png","LocalSkin/elytras/{USERNAME}.png")};
public static final Gson GSON=new GsonBuilder().setPrettyPrinting().create(); public static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
public static final Logger logger=initLogger(); public static final Logger logger = initLogger();
public static final Config config=Config.loadConfig0(); public static final Config config = Config.loadConfig0();
private static final ProfileCache profileCache=new ProfileCache(); private static final ProfileCache profileCache = new ProfileCache();
private static final DynamicSkullManager dynamicSkullManager=new DynamicSkullManager(); private static final DynamicSkullManager dynamicSkullManager = new DynamicSkullManager();
private static final ExecutorService THREAD_POOL = new ThreadPoolExecutor(config.threadPoolSize, config.threadPoolSize, 1L, TimeUnit.MINUTES, new LinkedBlockingQueue<>());
//Correct thread name in thread pool
private static final ThreadFactory defaultFactory = Executors.defaultThreadFactory();
private static final ThreadFactory customFactory = r -> {
Thread t = defaultFactory.newThread(r);
if (r instanceof Thread) {
t.setName(((Thread) r).getName());
}
return t;
};
//Thread pool will discard oldest task when queue reaches 333 tasks
private static final ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
config.threadPoolSize, config.threadPoolSize, 1L, TimeUnit.MINUTES,
new LinkedBlockingQueue<>(333), customFactory, new ThreadPoolExecutor.DiscardOldestPolicy()
);
public static void loadProfileTextures(Runnable runnable) {
THREAD_POOL.execute(runnable);
}
public static void loadProfileLazily(GameProfile gameProfile, Consumer<Map<MinecraftProfileTexture.Type, MinecraftProfileTexture>> consumer) {
String username = gameProfile.getName();
String credential = MinecraftUtil.getCredential(gameProfile);
// Fix: http://hopper.minecraft.net/crashes/minecraft/MCX-2773713
if (username == null) {
logger.warning("Could not load profile: username is null.");
consumer.accept(Maps.newHashMap());
return;
}
String tempName = Thread.currentThread().getName();
Thread.currentThread().setName(username); // Change Thread Name
if (profileCache.isLoading(credential)) {
profileCache.putLoader(credential, consumer);
Thread.currentThread().setName(tempName);
return;
}
consumer.accept(loadProfile(gameProfile));
Thread.currentThread().setName(tempName);
profileCache.getLastLoader(credential).ifPresent(c -> loadProfileLazily(gameProfile, c));
}
//For User Skin //For User Skin
public static Map loadProfile(GameProfile gameProfile){ public static Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> loadProfile(GameProfile gameProfile) {
String username=gameProfile.getName(); String credential = MinecraftUtil.getCredential(gameProfile);
String credential=MinecraftUtil.getCredential(gameProfile); UserProfile profile;
//Fix: http://hopper.minecraft.net/crashes/minecraft/MCX-2773713 if (profileCache.isReady(credential)) {
if(username==null){
logger.warning("Could not load profile: username is null.");
return Maps.newHashMap();
}
String tempName=Thread.currentThread().getName();
Thread.currentThread().setName(username);//Change Thread Name
UserProfile profile=null;
if(profileCache.isReady(credential)){
logger.info("Cached profile will be used."); logger.info("Cached profile will be used.");
profile=profileCache.getProfile(credential); profile = profileCache.getProfile(credential);
if(profile==null){ if (profile == null) {
logger.warning("(!Cached Profile is empty!) Expiry:"+profileCache.getExpiry(credential)); logger.warning("(Cached Profile is empty!) Expiry: " + profileCache.getExpiry(credential));
if(profileCache.isExpired(credential))//force load if (profileCache.isExpired(credential)) { // force load
profile=loadProfile0(gameProfile); profile = loadProfile0(gameProfile, false);
} }
else } else {
logger.info(profile.toString(profileCache.getExpiry(credential))); logger.info(profile.toString(profileCache.getExpiry(credential)));
}else{ }
} else {
profileCache.setLoading(credential, true); profileCache.setLoading(credential, true);
profile=loadProfile0(gameProfile); profile = loadProfile0(gameProfile, false);
} }
Thread.currentThread().setName(tempName);
return ModelManager0.fromUserProfile(profile); return ModelManager0.fromUserProfile(profile);
} }
//Core //Core
public static UserProfile loadProfile0(GameProfile gameProfile){ public static UserProfile loadProfile0(GameProfile gameProfile, boolean isSkull) {
String username=gameProfile.getName(); String username = gameProfile.getName();
String credential=MinecraftUtil.getCredential(gameProfile); String credential = MinecraftUtil.getCredential(gameProfile);
profileCache.setLoading(credential, true); profileCache.setLoading(credential, true);
logger.info("Loading "+username+"'s profile."); logger.info("Loading " + username + "'s profile.");
if(config.loadlist==null||config.loadlist.isEmpty()){ if (config.loadlist == null || config.loadlist.isEmpty()) {
logger.info("LoadList is Empty."); logger.info("LoadList is Empty.");
return null; return null;
} }
UserProfile profile0=new UserProfile(); UserProfile profile0 = new UserProfile();
for(int i=0;i<config.loadlist.size();i++){ for (int i = 0; i < config.loadlist.size(); i++) {
SkinSiteProfile ssp=config.loadlist.get(i); SkinSiteProfile ssp = config.loadlist.get(i);
logger.info((i+1)+"/"+config.loadlist.size()+" Try to load profile from '"+ssp.name+"'."); logger.info((i + 1) + "/" + config.loadlist.size() + " Try to load profile from '" + ssp.name + "'.");
ProfileLoader.IProfileLoader loader=ProfileLoader.LOADERS.get(ssp.type.toLowerCase()); if (ssp.type == null) {
if(loader==null){ logger.info("The type of '" + ssp.name + "' is null.");
logger.info("Type '"+ssp.type+"' is not defined.");
continue; continue;
} }
UserProfile profile=null; ProfileLoader.IProfileLoader loader = ProfileLoader.LOADERS.get(ssp.type.toLowerCase());
try{ if (loader == null) {
profile=loader.loadProfile(ssp, gameProfile); logger.info("Type '" + ssp.type + "' is not defined.");
}catch(Exception e){ continue;
}
UserProfile profile = null;
try {
profile = loader.loadProfile(ssp, gameProfile);
} catch (Exception e) {
logger.warning("Exception occurs while loading."); logger.warning("Exception occurs while loading.");
logger.warning(e); logger.warning(e);
if(e.getCause()!=null) { if (e.getCause() != null) {
logger.warning("Caused By:"); logger.warning("Caused By:");
logger.warning(e.getCause()); logger.warning(e.getCause());
} }
} }
if(profile==null) if (profile == null) {
continue; continue;
if(!config.forceLoadAllTextures){
profile0=profile;
break;
} }
profile0.mix(profile); profile0.mix(profile);
if(profile0.isFull()) if (isSkull && !profile0.hasSkinUrl()) {
continue;
}
if (!config.forceLoadAllTextures) {
break; break;
}
if (profile0.isFull()) {
break;
}
} }
if(!profile0.isEmpty()){ if (!profile0.isEmpty()) {
logger.info(username+"'s profile loaded."); logger.info(username + "'s profile loaded.");
if (!config.enableCape) {
profile0.capeUrl = null;
}
profileCache.updateCache(credential, profile0); profileCache.updateCache(credential, profile0);
profileCache.setLoading(credential, false); profileCache.setLoading(credential, false);
logger.info(profile0.toString(profileCache.getExpiry(credential))); logger.info(profile0.toString(profileCache.getExpiry(credential)));
return profile0; return profile0;
} }
logger.info(username+"'s profile not found in load list."); logger.info(username + "'s profile not found in load list.");
if(config.enableLocalProfileCache){ if (config.enableLocalProfileCache) {
UserProfile profile=profileCache.getLocalProfile(credential); UserProfile profile = profileCache.getLocalProfile(credential);
if(profile==null) if (profile == null) {
logger.info(username+"'s LocalProfile not found."); logger.info(username + "'s LocalProfile not found.");
else{ } else {
profileCache.updateCache(credential, profile, false); profileCache.updateCache(credential, profile, false);
profileCache.setLoading(credential, false); profileCache.setLoading(credential, false);
logger.info(username+"'s LocalProfile will be used."); logger.info(username + "'s LocalProfile will be used.");
logger.info(profile.toString(profileCache.getExpiry(credential))); logger.info(profile.toString(profileCache.getExpiry(credential)));
return profile; return profile;
} }
@@ -146,32 +190,44 @@ public class CustomSkinLoader {
} }
//For Skull //For Skull
public static Map<Type, MinecraftProfileTexture> loadProfileFromCache(final GameProfile gameProfile) { public static Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> loadProfileFromCache(final GameProfile gameProfile) {
String username=gameProfile.getName(); String username = gameProfile.getName();
String credential=MinecraftUtil.getCredential(gameProfile); String credential = MinecraftUtil.getCredential(gameProfile);
if(credential==null) //CustomSkinLoader needs username to load standard skin, if username not exist, only textures in NBT can be used
//Authlib 3.11.50 makes empty username to "\u0020"
if (username == null || username.isEmpty() || username.equals("\u0020") || credential == null) {
return dynamicSkullManager.getTexture(gameProfile); return dynamicSkullManager.getTexture(gameProfile);
if(config.enableUpdateSkull?profileCache.isReady(credential):profileCache.isExist(credential)){ }
UserProfile profile=profileCache.getProfile(credential); if (config.forceUpdateSkull ? profileCache.isReady(credential) : profileCache.isExist(credential)) {
UserProfile profile = profileCache.getProfile(credential);
return ModelManager0.fromUserProfile(profile); return ModelManager0.fromUserProfile(profile);
} }
//profileCache.setLoading(username, true); if (!profileCache.isLoading(credential)) {
Thread loadThread=new Thread(){ profileCache.setLoading(credential, true);
public void run(){ Runnable loadThread = () -> {
loadProfile0(gameProfile);//Load in thread String tempName = Thread.currentThread().getName();
Thread.currentThread().setName(username + "'s skull");
loadProfile0(gameProfile, true);//Load in thread
Thread.currentThread().setName(tempName);
};
if (config.forceUpdateSkull) {
new Thread(loadThread).start();
} else {
threadPool.execute(loadThread);
} }
}; }
loadThread.setName(username+"'s skull");
loadThread.start();
return Maps.newHashMap(); return Maps.newHashMap();
} }
private static Logger initLogger() { private static Logger initLogger() {
Logger logger=new Logger(LOG_FILE); Logger logger = new Logger(LOG_FILE);
logger.info("CustomSkinLoader "+CustomSkinLoader_FULL_VERSION); logger.info("CustomSkinLoader " + CustomSkinLoader_FULL_VERSION);
logger.info("DataDir: "+DATA_DIR.getAbsolutePath()); logger.info("DataDir: " + DATA_DIR.getAbsolutePath());
logger.info("Minecraft: "+MinecraftUtil.getMinecraftMainVersion()+"("+MinecraftUtil.getMinecraftVersionText()+")"); logger.info("Operating System: " + System.getProperty("os.name") + " (" + System.getProperty("os.arch") + ") version " + System.getProperty("os.version"));
logger.info("Java Version: " + System.getProperty("java.version") + ", " + System.getProperty("java.vendor"));
logger.info("Java VM Version: " + System.getProperty("java.vm.name") + " (" + System.getProperty("java.vm.info") + "), " + System.getProperty("java.vm.vendor"));
logger.info("Minecraft: " + MinecraftUtil.getMinecraftMainVersion());
return logger; return logger;
} }
} }
+24 -13
View File
@@ -4,9 +4,12 @@ import java.io.BufferedWriter;
import java.io.File; import java.io.File;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.OutputStreamWriter; import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
@SuppressWarnings("ResultOfMethodCallIgnored")
public class Logger { public class Logger {
private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public enum Level{ public enum Level{
@@ -32,6 +35,9 @@ public class Logger {
public Logger(){ public Logger(){
//Logger isn't created. //Logger isn't created.
} }
public Logger(String logFile) {
this(new File(logFile));
}
public Logger(File logFile){ public Logger(File logFile){
try { try {
if(!logFile.getParentFile().exists()){ if(!logFile.getParentFile().exists()){
@@ -42,6 +48,8 @@ public class Logger {
writer = new BufferedWriter(new OutputStreamWriter( writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(logFile), "UTF-8")); new FileOutputStream(logFile), "UTF-8"));
System.out.println("Log Path: " + logFile.getAbsolutePath());
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
@@ -59,18 +67,14 @@ public class Logger {
public void log(Level level,String msg){ public void log(Level level,String msg){
if(!level.display()&&writer==null) if(!level.display()&&writer==null)
return; return;
StringBuilder sb=new StringBuilder(); String sb = String.format("[%s %s] %s", Thread.currentThread().getName(), level.getName(), msg);
sb.append("[").append(Thread.currentThread().getName()).append(" ").append(level.getName()).append("] ");
sb.append(msg);
if(level.display()) if(level.display())
System.out.println(sb.toString()); System.out.println(sb);
if(writer==null) if(writer==null)
return; return;
try { try {
StringBuilder sb2=new StringBuilder(); String sb2 = String.format("[%s] %s\r\n", DATE_FORMAT.format(new Date()), sb);
sb2.append("[").append(DATE_FORMAT.format(new Date())).append("] "); writer.write(sb2);
sb2.append(sb.toString()).append("\r\n");
writer.write(sb2.toString());
writer.flush(); writer.flush();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
@@ -79,17 +83,24 @@ public class Logger {
public void debug(String msg){ public void debug(String msg){
log(Level.DEBUG,msg); log(Level.DEBUG,msg);
} }
public void debug(String format, Object... objs) {
debug(String.format(format, objs));
}
public void info(String msg){ public void info(String msg){
log(Level.INFO,msg); log(Level.INFO,msg);
} }
public void info(String format, Object... objs){
info(String.format(format, objs));
}
public void warning(String msg){ public void warning(String msg){
log(Level.WARNING,msg); log(Level.WARNING,msg);
} }
public void warning(String format, Object... objs){
warning(String.format(format, objs));
}
public void warning(Throwable e){ public void warning(Throwable e){
log(Level.WARNING,"Exception: "+e.toString()); StringWriter sw = new StringWriter();
StackTraceElement[] stes=e.getStackTrace(); e.printStackTrace(new PrintWriter(sw));
for(StackTraceElement ste : stes){ log(Level.WARNING,"Exception: "+sw.toString());
log(Level.WARNING,ste.toString());
}
} }
} }
+124 -67
View File
@@ -1,41 +1,58 @@
package customskinloader.config; package customskinloader.config;
import java.io.File; import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Collection;
import java.util.Comparator;
import java.util.List; import java.util.List;
import java.util.Objects;
import org.apache.commons.io.Charsets;
import org.apache.commons.io.FileUtils;
import customskinloader.CustomSkinLoader; import customskinloader.CustomSkinLoader;
import customskinloader.loader.ProfileLoader; import customskinloader.loader.ProfileLoader;
import customskinloader.plugin.ICustomSkinLoaderPlugin;
import customskinloader.plugin.PluginLoader;
import customskinloader.utils.HttpRequestUtil; import customskinloader.utils.HttpRequestUtil;
import customskinloader.utils.HttpTextureUtil; import customskinloader.utils.HttpTextureUtil;
import customskinloader.utils.HttpUtil0; import customskinloader.utils.HttpUtil0;
import customskinloader.utils.Version;
import org.apache.commons.io.FileUtils;
@SuppressWarnings("ResultOfMethodCallIgnored")
public class Config { public class Config {
//Program //Program
public String version; public String version;
public int buildNumber;
public List<SkinSiteProfile> loadlist; public List<SkinSiteProfile> loadlist;
//Function //Function
public boolean enableDynamicSkull=true; public boolean enableDynamicSkull=true;
public boolean enableTransparentSkin=true; public boolean enableTransparentSkin=true;
public boolean ignoreHttpsCertificate=false; public boolean forceIgnoreHttpsCertificate = false;
public boolean forceLoadAllTextures=false; public boolean forceLoadAllTextures=false;
public boolean enableCape = true;
public int threadPoolSize = 3;
public int retryTime = 1;
//Cache //Profile Cache
public int cacheExpiry=20; public int cacheExpiry=30;
public boolean enableUpdateSkull=false; public boolean forceUpdateSkull = false;
public boolean enableLocalProfileCache=false; public boolean enableLocalProfileCache=false;
public boolean enableCacheAutoClean=false;
//Network Cache
public boolean enableCacheAutoClean=false;
public boolean forceDisableCache = false;
// Used by Gson to create an instance with default value.
public Config() {
this(new ArrayList<>());
}
//Init config //Init config
public Config(SkinSiteProfile[] loadlist){ public Config(List<SkinSiteProfile> loadlist){
this.version=CustomSkinLoader.CustomSkinLoader_VERSION; this.version=CustomSkinLoader.CustomSkinLoader_VERSION;
this.loadlist=Arrays.asList(loadlist); this.buildNumber=CustomSkinLoader.CustomSkinLoader_BUILD_NUMBER;
this.loadlist=loadlist;
} }
public static Config loadConfig0() { public static Config loadConfig0() {
@@ -53,8 +70,11 @@ public class Config {
//Init program //Init program
config.loadExtraList(); config.loadExtraList();
config.updateLoadlist();
config.initLocalFolder(); config.initLocalFolder();
if(config.ignoreHttpsCertificate) config.threadPoolSize = Math.max(config.threadPoolSize, 1);
config.retryTime = Math.max(config.retryTime, 0);
if(config.forceIgnoreHttpsCertificate)
HttpUtil0.ignoreHttpsCertificate(); HttpUtil0.ignoreHttpsCertificate();
if(config.enableCacheAutoClean && !config.enableLocalProfileCache){ if(config.enableCacheAutoClean && !config.enableLocalProfileCache){
try{ try{
@@ -66,31 +86,23 @@ public class Config {
} }
} }
//Output config
CustomSkinLoader.logger.info("EnableDynamicSkull:"+config.enableDynamicSkull+
", EnableTranSkin:"+config.enableTransparentSkin+
", IgnoreHttpsCertificate:"+config.ignoreHttpsCertificate+
", CacheExpiry:"+config.cacheExpiry+
", EnableUpdateSkull:"+config.enableUpdateSkull+
", EnableLocalProfileCache:"+config.enableLocalProfileCache+
", EnableCacheAutoClean:"+config.enableCacheAutoClean+
", LoadList:"+(config.loadlist==null?0:config.loadlist.size()));
//Check config version //Check config version
float floatVersion=0f; Version configVersion = Version.of(config.version);
float configVersion=0f; if (CustomSkinLoader.CustomSkinLoader_BUILD_NUMBER == 0 // Custom builds
try{ || configVersion.compareTo(CustomSkinLoader.CustomSkinLoader_VERSION) < 0
floatVersion=Float.parseFloat(CustomSkinLoader.CustomSkinLoader_VERSION); || config.buildNumber < CustomSkinLoader.CustomSkinLoader_BUILD_NUMBER) {
configVersion=Float.parseFloat(config.version); CustomSkinLoader.logger.info("Config File is out of date: " + config.version + ", build number: " + config.buildNumber);
if(configVersion==15.1f)//To avoid some bug config.version = CustomSkinLoader.CustomSkinLoader_VERSION;
configVersion=14.6f; config.buildNumber = CustomSkinLoader.CustomSkinLoader_BUILD_NUMBER;
}catch (Exception e){
CustomSkinLoader.logger.warning("Exception occurs while parsing version: "+e.toString());
} }
if(config.version==null || configVersion==0f || floatVersion > configVersion){ writeConfig(config, true);
CustomSkinLoader.logger.info("Config File is out of date: "+config.version);
config.version=CustomSkinLoader.CustomSkinLoader_VERSION; //Output config
writeConfig(config,true); for (Field field : config.getClass().getDeclaredFields()) {
try {
Object value = field.get(config);
CustomSkinLoader.logger.info(field.getName() + " : " + value);
} catch (Exception ignored) { }
} }
return config; return config;
@@ -104,16 +116,13 @@ public class Config {
} }
try { try {
CustomSkinLoader.logger.info("Try to load config."); CustomSkinLoader.logger.info("Try to load config.");
String json=FileUtils.readFileToString(CustomSkinLoader.CONFIG_FILE,Charsets.UTF_8); String json=FileUtils.readFileToString(CustomSkinLoader.CONFIG_FILE, "UTF-8");
Config config=CustomSkinLoader.GSON.fromJson(json, Config.class); Config config=Objects.requireNonNull(CustomSkinLoader.GSON.fromJson(json, Config.class));
CustomSkinLoader.logger.info("Successfully load config."); CustomSkinLoader.logger.info("Successfully load config.");
return config; return config;
}catch (Exception e) { }catch (Exception e) {
CustomSkinLoader.logger.info("Failed to load config, use default instead.("+e.toString()+")"); CustomSkinLoader.logger.info("Failed to load config, use default instead.("+e.toString()+")");
File brokenFile=new File(CustomSkinLoader.DATA_DIR,"BROKEN-CustomSkinLoader.json"); createBrokenFile(CustomSkinLoader.CONFIG_FILE);
if(brokenFile.exists())
brokenFile.delete();
CustomSkinLoader.CONFIG_FILE.renameTo(brokenFile);
return initConfig(); return initConfig();
} }
} }
@@ -126,67 +135,115 @@ public class Config {
} }
List<SkinSiteProfile> adds=new ArrayList<SkinSiteProfile>(); List<SkinSiteProfile> adds=new ArrayList<SkinSiteProfile>();
File[] files=listAddition.listFiles(); File[] files=listAddition.listFiles();
for(File file:files){ for(File file: files != null ? files : new File[0]){
if(!file.getName().toLowerCase().endsWith(".json")&&!file.getName().toLowerCase().endsWith(".txt")) if(!file.getName().toLowerCase().endsWith(".json")&&!file.getName().toLowerCase().endsWith(".txt"))
continue; continue;
try { try {
CustomSkinLoader.logger.info("Try to load Extra List.("+file.getName()+")"); CustomSkinLoader.logger.info("Try to load Extra List.("+file.getName()+")");
String json=FileUtils.readFileToString(file,Charsets.UTF_8); String json=FileUtils.readFileToString(file, "UTF-8");
SkinSiteProfile ssp=CustomSkinLoader.GSON.fromJson(json, SkinSiteProfile.class); SkinSiteProfile ssp=CustomSkinLoader.GSON.fromJson(json, SkinSiteProfile.class);
CustomSkinLoader.logger.info("Successfully load Extra List."); CustomSkinLoader.logger.info("Successfully load Extra List.");
file.delete(); if (ssp.type != null) {
ProfileLoader.IProfileLoader loader=ProfileLoader.LOADERS.get(ssp.type.toLowerCase()); ProfileLoader.IProfileLoader loader = ProfileLoader.LOADERS.get(ssp.type.toLowerCase());
if(loader==null){ if (loader == null) {
CustomSkinLoader.logger.info("Extra List will be ignore: Type '"+ssp.type+"' is not defined."); CustomSkinLoader.logger.info("Extra List will be ignored: Type '" + ssp.type + "' is not defined.");
continue;
}
boolean duplicate=false;
for(SkinSiteProfile ssp0:this.loadlist){
if(!ssp0.type.equalsIgnoreCase(ssp.type))
continue; continue;
if(loader.compare(ssp0, ssp)){
duplicate=true;
break;
} }
} boolean duplicate = false;
if(!duplicate){ for (SkinSiteProfile ssp0 : this.loadlist) {
adds.add(ssp); if (!ssp0.type.equalsIgnoreCase(ssp.type))
CustomSkinLoader.logger.info("Successfully apply Extra List.("+ssp.name+")"); continue;
}else{ if (loader.compare(ssp0, ssp)) {
CustomSkinLoader.logger.info("Extra List will be ignore: Duplicate.("+ssp.name+")"); duplicate = true;
break;
}
}
if (!duplicate) {
adds.add(ssp);
CustomSkinLoader.logger.info("Successfully apply Extra List.(" + ssp.name + ")");
} else {
CustomSkinLoader.logger.info("Extra List will be ignored: Duplicate.(" + ssp.name + ")");
}
file.delete();
} else {
CustomSkinLoader.logger.info("Extra List is invalid: Type is not defined.(" + file.getName() + ")");
createBrokenFile(file);
} }
}catch (Exception e) { }catch (Exception e) {
CustomSkinLoader.logger.info("Failed to load Extra List.("+e.toString()+")"); CustomSkinLoader.logger.info("Failed to load Extra List.("+e.toString()+")");
createBrokenFile(file);
} }
} }
if(adds.size()!=0){ if(adds.size()!=0){
adds.addAll(this.loadlist); adds.addAll(this.loadlist);
this.loadlist=adds; this.loadlist=adds;
writeConfig(this,true);
} }
} }
private void updateLoadlist() {
PluginLoader.PLUGINS.stream()
.map(ICustomSkinLoaderPlugin::getDefaultProfiles)
.filter(Objects::nonNull)
.flatMap(Collection::stream)
.forEach(profile -> this.loadlist.stream()
.filter(ssp -> profile.getName().equals(ssp.name))
.forEach(profile::updateSkinSiteProfile));
}
private void initLocalFolder(){ private void initLocalFolder(){
for(SkinSiteProfile ssp:this.loadlist){ for(SkinSiteProfile ssp:this.loadlist){
if(ssp.type==null)
continue;
ProfileLoader.IProfileLoader loader=ProfileLoader.LOADERS.get(ssp.type.toLowerCase()); ProfileLoader.IProfileLoader loader=ProfileLoader.LOADERS.get(ssp.type.toLowerCase());
if(loader==null) if(loader==null)
continue; continue;
loader.initLocalFolder(ssp); loader.init(ssp);
} }
} }
private static void createBrokenFile(File file) {
try {
File brokenFile = new File(file.getParentFile(), file.getName() + ".broken");
if (brokenFile.exists()) {
brokenFile.delete();
}
file.renameTo(brokenFile);
} catch (Exception e) {
CustomSkinLoader.logger.warning("Failed to create broken file. (" + file.getName() + ")");
CustomSkinLoader.logger.warning(e);
}
}
// The config file does not exist or was broken.
private static Config initConfig() { private static Config initConfig() {
Config config=new Config(CustomSkinLoader.DEFAULT_LOAD_LIST); List<ICustomSkinLoaderPlugin.IDefaultProfile> profiles = new ArrayList<>();
writeConfig(config,false); for (ICustomSkinLoaderPlugin plugin : PluginLoader.PLUGINS) {
List<ICustomSkinLoaderPlugin.IDefaultProfile> defaultProfiles = plugin.getDefaultProfiles();
if (defaultProfiles != null) {
profiles.addAll(defaultProfiles);
}
}
profiles.sort(Comparator.comparingInt(ICustomSkinLoaderPlugin.IDefaultProfile::getPriority));
List<SkinSiteProfile> loadlist = new ArrayList<>();
for (ICustomSkinLoaderPlugin.IDefaultProfile profile : profiles) {
SkinSiteProfile ssp = new SkinSiteProfile();
ssp.name = profile.getName();
profile.updateSkinSiteProfile(ssp);
loadlist.add(ssp);
}
Config config = new Config(loadlist);
writeConfig(config, false);
return config; return config;
} }
private static void writeConfig(Config config,boolean update){ private static void writeConfig(Config config, boolean update){
String json=CustomSkinLoader.GSON.toJson(config); String json=CustomSkinLoader.GSON.toJson(config);
if(CustomSkinLoader.CONFIG_FILE.exists()) if(CustomSkinLoader.CONFIG_FILE.exists())
CustomSkinLoader.CONFIG_FILE.delete(); CustomSkinLoader.CONFIG_FILE.delete();
try { try {
CustomSkinLoader.CONFIG_FILE.createNewFile(); CustomSkinLoader.CONFIG_FILE.createNewFile();
FileUtils.write(CustomSkinLoader.CONFIG_FILE, json, Charsets.UTF_8); FileUtils.write(CustomSkinLoader.CONFIG_FILE, json, "UTF-8");
CustomSkinLoader.logger.info("Successfully "+(update?"update":"create")+" config."); CustomSkinLoader.logger.info("Successfully "+(update?"update":"create")+" config.");
} catch (Exception e) { } catch (Exception e) {
CustomSkinLoader.logger.info("Failed to "+(update?"update":"create")+" config.("+e.toString()+")"); CustomSkinLoader.logger.info("Failed to "+(update?"update":"create")+" config.("+e.toString()+")");
@@ -1,64 +1,44 @@
package customskinloader.config; package customskinloader.config;
import customskinloader.loader.jsonapi.CustomSkinAPIPlus.CustomSkinAPIPlusPrivacy; import java.lang.reflect.Field;
public class SkinSiteProfile { public class SkinSiteProfile {
//Common
public String name; public String name;
public String type; public String type;
public String userAgent; public String userAgent;
public String root; //Mojang API
public CustomSkinAPIPlusPrivacy privacy; public String apiRoot;
public String sessionRoot;
//Json API
public String root;
//Legacy
public Boolean checkPNG;//Not suitable for local skin public Boolean checkPNG;//Not suitable for local skin
public String skin; public String skin;
public String model; public String model;
public String cape; public String cape;
public String elytra; public String elytra;
public static SkinSiteProfile createMojangAPI(String name){ @Override
SkinSiteProfile ssp=new SkinSiteProfile(); public String toString() {
ssp.name=name; StringBuilder sb = new StringBuilder("{ ");
ssp.type="MojangAPI"; Field[] fields = SkinSiteProfile.class.getDeclaredFields();
return ssp; boolean first = true;
} for (Field field : fields) {
public static SkinSiteProfile createCustomSkinAPI(String name,String root){ try {
SkinSiteProfile ssp=new SkinSiteProfile(); Object value = field.get(this);
ssp.name=name; if (value == null) continue;
ssp.type="CustomSkinAPI"; if (first) {
ssp.root=root; first = false;
return ssp; } else {
} sb.append(", ");
public static SkinSiteProfile creatCustomSkinAPIPlus(String name,String root){ }
SkinSiteProfile ssp=new SkinSiteProfile(); sb.append("\"").append(field.getName()).append("\": \"").append(value).append("\"");
ssp.name=name; } catch (Exception ignored) { }
ssp.type="CustomSkinAPIPlus"; }
ssp.root=root; return sb.append(" }").toString();
ssp.privacy=new CustomSkinAPIPlusPrivacy();
return ssp;
}
public static SkinSiteProfile createUniSkinAPI(String name,String root){
SkinSiteProfile ssp=new SkinSiteProfile();
ssp.name=name;
ssp.type="UniSkinAPI";
ssp.root=root;
return ssp;
}
public static SkinSiteProfile createLegacy(String name,String skin,String cape,String elytra){
SkinSiteProfile ssp=new SkinSiteProfile();
ssp.name=name;
ssp.type="Legacy";
ssp.checkPNG=false;
ssp.skin=skin;
ssp.model="default";
ssp.cape=cape;
ssp.elytra=elytra;
return ssp;
}
public static SkinSiteProfile createElfSkin(String name){
SkinSiteProfile ssp=new SkinSiteProfile();
ssp.name=name;
ssp.type="ElfSkin";
return ssp;
} }
} }
@@ -0,0 +1,207 @@
package customskinloader.fake;
import java.io.IOException;
import java.io.InputStream;
import java.util.NoSuchElementException;
import java.util.function.BiPredicate;
import java.util.function.Predicate;
import customskinloader.fake.itf.FakeInterfaceManager;
import customskinloader.fake.texture.FakeBufferedImage;
import customskinloader.fake.texture.FakeImage;
import customskinloader.utils.MinecraftUtil;
import net.minecraft.client.Minecraft;
import net.minecraft.util.ResourceLocation;
public class FakeCapeBuffer extends FakeSkinBuffer {
private static final ResourceLocation TEXTURE_ELYTRA = new ResourceLocation("textures/entity/elytra.png");
private static int loadedGlobal = 0;
private static FakeImage elytraImage;
private static FakeImage loadElytra(FakeImage originalImage) {
loadedGlobal++;
try {
InputStream is = FakeInterfaceManager.IResource_getInputStream(FakeInterfaceManager.IResourceManager_getResource(FakeInterfaceManager.Minecraft_getResourceManager(Minecraft.getMinecraft()), TEXTURE_ELYTRA).get());
if (is != null) {
FakeImage image = originalImage.createImage(is);
if (image.getWidth() % 64 != 0 || image.getHeight() % 32 != 0) { // wtf?
return elytraImage;
}
image = resetImageFormat(image, 22, 0, 46, 22);
return image;
}
} catch (IOException | NoSuchElementException ignored) { }
return null;
}
private int loaded = 0;
private double ratioX = -1;
private double ratioY = -1;
private ResourceLocation location;
private String type = null;
public FakeCapeBuffer(ResourceLocation location) {
this.location = location;
}
@Override
public FakeImage parseUserSkin(FakeImage image) {
if (image == null) return null;
this.image = image;
// When resource packs were changed, the elytra image needs to be reloaded, and here will be entered again
if (this.loaded == loadedGlobal) {
elytraImage = loadElytra(image);
}
this.loaded = loadedGlobal;
if (elytraImage != null) {
if (this.ratioX < 0)
this.ratioX = this.image.getWidth() / 64.0D;
if (this.ratioY < 0)
this.ratioY = this.image.getHeight() / 32.0D;
if (this.type == null)
this.type = this.judgeType();
if ("cape".equals(this.type)) {
this.image = resetImageFormat(this.image, 0, 0, 22, 17);
this.attachElytra(elytraImage);
if (this.image instanceof FakeBufferedImage) { // before 1.12.2
this.refreshTexture((FakeBufferedImage) this.image);
}
}
}
return this.image;
}
/**
* Judge the cape type
*
* @return "elytra" if the cape contains elytra texture, otherwise "cape"
*/
@Override
public String judgeType() {
if (this.image != null && elytraImage != null) {
// If all the pixels in ((22, 0), (45, 21)) is same as background, it means the cape doesn't contain elytra
Predicate<Integer> predicate = EQU_BG.apply(this.image.getRGBA(this.image.getWidth() - 1, this.image.getHeight() - 1));
return withElytraPixels((x, y) -> !predicate.test(this.image.getRGBA(x, y)), "elytra", "cape");
}
return "cape";
}
private void attachElytra(FakeImage elytraImage) {
if (this.image != null) {
int capeW = this.image.getWidth(), capeH = this.image.getHeight();
int elytraW = elytraImage.getWidth(), elytraH = elytraImage.getHeight();
// scale cape and elytra to the same size
// cape part ((0, 0), (21, 16)) -> (22 * 17)
if (capeW < elytraW) {
this.image = scaleImage(this.image, true, elytraW / (double) capeW, 1, capeW / 64.0D, capeH / 32.0D, elytraW, capeH, 0, 0, 22, 17);
capeW = elytraW;
}
if (capeH < elytraH) {
this.image = scaleImage(this.image, true, 1, elytraH / (double) capeH, capeW / 64.0D, capeH / 32.0D, capeW, elytraH, 0, 0, 22, 17);
capeH = elytraH;
}
// elytra part ((22, 0), (45, 21)) -> (24 * 22)
if (elytraW < capeW) {
elytraImage = scaleImage(elytraImage, false, capeW / (double) elytraW, 1, elytraW / 64.0D, elytraH / 32.0D, capeW, elytraH, 22, 0, 46, 22);
elytraW = capeW;
}
if (elytraH < capeH) {
elytraImage = scaleImage(elytraImage, false, 1, capeH / (double) elytraH, elytraW / 64.0D, elytraH / 32.0D, elytraW, capeH, 22, 0, 46, 22);
elytraH = capeH;
}
this.ratioX = capeW / 64.0D;
this.ratioY = capeH / 32.0D;
// Overwrite pixels from elytra to cape
FakeImage finalElytraImage = elytraImage;
withElytraPixels((x, y) -> {
this.image.setRGBA(x, y, finalElytraImage.getRGBA(x, y));
return false;
}, null, null);
}
}
/**
* Traverse every elytra pixel
* @param predicate the predicate with x and y
* @param returnValue if the condition flag equals the condition, then return this value
* @param defaultReturnValue otherwise return this value
*/
private <R> R withElytraPixels(BiPredicate<Integer, Integer> predicate, R returnValue, R defaultReturnValue) {
int startX = (int) Math.ceil(22 * ratioX), endX = (int) Math.ceil(46 * ratioX);
int startY = (int) Math.ceil(0 * ratioY), endY = (int) Math.ceil(22 * ratioY);
int excludeX0 = (int) Math.ceil(24 * ratioX), excludeX1 = (int) Math.ceil(44 * ratioX);
int excludeY = (int) Math.ceil(2 * ratioY);
for (int x = startX; x < endX; ++x) {
for (int y = startY; y < endY; ++y) {
if (y < excludeY && (x < excludeX0 || x >= excludeX1)) continue;
if (predicate.test(x, y)) {
return returnValue;
}
}
}
return defaultReturnValue;
}
// TextureID won't be regenerated when changing resource packs before 1.12.2
private void refreshTexture(FakeBufferedImage image) {
Object textureObj = MinecraftUtil.getTextureManager().getTexture(this.location);
if (textureObj != null) {
// NOTICE: OptiFine modified the upload process of the texture from ThreadDownloadImageData
// Therefore, it may not be correct to simply copy the vanilla behavior
FakeInterfaceManager.ThreadDownloadImageData_resetNewBufferedImage(textureObj, image.getImage());
}
}
// Some cape image doesn't support alpha channel, so reset image format to ARGB
private static FakeImage resetImageFormat(FakeImage image, int startX, int startY, int endX, int endY) {
if (image != null) {
int width = image.getWidth(), height = image.getHeight();
image = scaleImage(image, true, 1, 1, width / 64.0D, height / 32.0D, width, height, startX, startY, endX, endY);
}
return image;
}
/**
* Scale image
* @param image the image to scale.
* @param closeOldImage whether close old image
* @param scaleWidth width enlargement ratio
* @param scaleHeight height enlargement ratio
* @param ratioX the ratio of 64 of the old image width
* @param ratioY the ratio of 32 of the old image height
* @param width the width after scaling.
* @param height the height after scaling.
* @param startX the x where start to copy.
* @param startY the y where start to copy.
* @param endX the x where end to copy.
* @param endY the y where end to copy.
* @return the image after scaling.
*/
private static FakeImage scaleImage(FakeImage image, boolean closeOldImage, double scaleWidth, double scaleHeight, double ratioX, double ratioY, int width, int height, int startX, int startY, int endX, int endY) {
FakeImage newImage = image.createImage(width, height);
startX = (int) (startX * ratioX); endX = (int) (endX * ratioX);
startY = (int) (startY * ratioY); endY = (int) (endY * ratioY);
int x0 = (int) (startX * scaleWidth), x1 = (int) ((startX + 1) * scaleWidth), dx0 = x1 - x0;
for (int x = startX; x < endX; ++x) {
int y0 = (int) (startY * scaleHeight), y1 = (int) ((startY + 1) * scaleHeight), dy0 = y1 - y0;
for (int y = startY; y < endY; ++y) {
int rgba = image.getRGBA(x, y);
for (int dx = 0; dx < dx0; dx++) {
for (int dy = 0; dy < dy0; dy++) {
newImage.setRGBA(x0 + dx, y0 + dy, rgba);
}
}
y0 = y1; y1 = (int) ((y + 2) * scaleHeight); dy0 = y1 - y0;
}
x0 = x1; x1 = (int) ((x + 2) * scaleWidth); dx0 = x1 - x0;
}
if (closeOldImage)
image.close();
return newImage;
}
}
@@ -1,13 +1,15 @@
package customskinloader.fake; package customskinloader.fake;
import java.util.Map;
import java.util.UUID; import java.util.UUID;
import com.google.common.collect.Maps;
import com.mojang.authlib.GameProfile; import com.mojang.authlib.GameProfile;
import com.mojang.authlib.minecraft.MinecraftProfileTexture; import com.mojang.authlib.minecraft.MinecraftProfileTexture;
import com.mojang.authlib.minecraft.MinecraftProfileTexture.Type; import com.mojang.authlib.minecraft.MinecraftProfileTexture.Type;
import customskinloader.CustomSkinLoader; import customskinloader.CustomSkinLoader;
import net.minecraft.client.Minecraft; import customskinloader.utils.MinecraftUtil;
import net.minecraft.client.renderer.ThreadDownloadImageData; import net.minecraft.client.renderer.ThreadDownloadImageData;
import net.minecraft.client.renderer.texture.ITextureObject; import net.minecraft.client.renderer.texture.ITextureObject;
import net.minecraft.client.renderer.texture.SimpleTexture; import net.minecraft.client.renderer.texture.SimpleTexture;
@@ -15,72 +17,73 @@ import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.client.resources.DefaultPlayerSkin; import net.minecraft.client.resources.DefaultPlayerSkin;
import net.minecraft.client.resources.SkinManager; import net.minecraft.client.resources.SkinManager;
import net.minecraft.client.resources.SkinManager.SkinAvailableCallback; import net.minecraft.client.resources.SkinManager.SkinAvailableCallback;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.ResourceLocation; import net.minecraft.util.ResourceLocation;
import net.minecraft.util.StringUtils; import net.minecraft.util.StringUtils;
public class FakeClientPlayer { public class FakeClientPlayer {
//For Legacy Skin //For Legacy Skin
public static ThreadDownloadImageData getDownloadImageSkin(ResourceLocation resourceLocationIn, String username) public static ThreadDownloadImageData getDownloadImageSkin(ResourceLocation resourceLocationIn, String username) {
{ //CustomSkinLoader.logger.debug("FakeClientPlayer/getDownloadImageSkin "+username);
//CustomSkinLoader.logger.debug("FakeClientPlayer/getDownloadImageSkin "+username); TextureManager textman = MinecraftUtil.getTextureManager();
TextureManager textman = Minecraft.getMinecraft().getTextureManager(); ITextureObject ito = textman.getTexture(resourceLocationIn);
ITextureObject ito = textman.getTexture(resourceLocationIn);
if (ito == null || !(ito instanceof ThreadDownloadImageData)) if (ito == null || !(ito instanceof ThreadDownloadImageData)) {
{ //if Legacy Skin for username not loaded yet
//if Legacy Skin for username not loaded yet SkinManager skinman = MinecraftUtil.getSkinManager();
SkinManager skinman = Minecraft.getMinecraft().getSkinManager(); UUID offlineUUID = getOfflineUUID(username);
UUID offlineUUID=EntityPlayer.getOfflineUUID(username); GameProfile offlineProfile = new GameProfile(offlineUUID, username);
GameProfile offlineProfile=new GameProfile(offlineUUID,username);
//Load Default Skin //Load Default Skin
ResourceLocation defaultSkin=DefaultPlayerSkin.getDefaultSkin(offlineUUID); ResourceLocation defaultSkin = DefaultPlayerSkin.getDefaultSkin(offlineUUID);
ITextureObject defaultSkinObj=new SimpleTexture(defaultSkin); ITextureObject defaultSkinObj = new SimpleTexture(defaultSkin);
textman.loadTexture(resourceLocationIn, defaultSkinObj); textman.loadTexture(resourceLocationIn, defaultSkinObj);
//Load Skin from SkinManager //Load Skin from SkinManager
skinman.loadProfileTextures(offlineProfile, new LegacyBuffer(resourceLocationIn), false); skinman.loadProfileTextures(offlineProfile, new LegacyBuffer(resourceLocationIn), false);
}
if(ito instanceof ThreadDownloadImageData)
return (ThreadDownloadImageData)ito;
else
return null;
} }
public static ResourceLocation getLocationSkin(String username) if (ito instanceof ThreadDownloadImageData)
{ return (ThreadDownloadImageData) ito;
//CustomSkinLoader.logger.debug("FakeClientPlayer/getLocationSkin "+username); else
return new ResourceLocation("skins/legacy-" + StringUtils.stripControlCodes(username)); return null;
}
public static ResourceLocation getLocationSkin(String username) {
//CustomSkinLoader.logger.debug("FakeClientPlayer/getLocationSkin "+username);
return new ResourceLocation("skins/legacy-" + StringUtils.stripControlCodes(username));
}
public static UUID getOfflineUUID(String username) {
return UUID.nameUUIDFromBytes(("OfflinePlayer:" + username).getBytes());
}
public static Map<ResourceLocation, ITextureObject> textureCache = Maps.newHashMap();
public static class LegacyBuffer implements SkinAvailableCallback {
ResourceLocation resourceLocationIn;
boolean loaded = false;
public LegacyBuffer(ResourceLocation resourceLocationIn) {
CustomSkinLoader.logger.debug("Loading Legacy Texture (" + resourceLocationIn + ")");
this.resourceLocationIn = resourceLocationIn;
} }
private static class LegacyBuffer implements SkinAvailableCallback{ @Override
ResourceLocation resourceLocationIn; public void skinAvailable(Type typeIn, ResourceLocation location, MinecraftProfileTexture profileTexture) {
boolean loaded=false; if (typeIn != Type.SKIN || loaded)
return;
public LegacyBuffer(ResourceLocation resourceLocationIn) { TextureManager textman = MinecraftUtil.getTextureManager();
CustomSkinLoader.logger.debug("Loading Legacy Texture ("+resourceLocationIn+")"); ITextureObject ito = textman.getTexture(location);
this.resourceLocationIn=resourceLocationIn; if (ito == null)
} ito = textureCache.get(location);
if (ito == null)
@Override return;
public void skinAvailable(Type typeIn, ResourceLocation location, MinecraftProfileTexture profileTexture) {
if(typeIn!=Type.SKIN || loaded)
return;
loaded=true;
TextureManager textman = Minecraft.getMinecraft().getTextureManager();
ITextureObject ito = textman.getTexture(location);
if(ito!=null)
textman.loadTexture(resourceLocationIn, ito);
CustomSkinLoader.logger.debug("Legacy Texture ("+resourceLocationIn+") Loaded as "+
ito==null?null:ito.toString()+" ("+location+")");
//textman.bindTexture(resourceLocationIn);
}
loaded = true;
textman.loadTexture(resourceLocationIn, ito);
CustomSkinLoader.logger.debug("Legacy Texture (" + resourceLocationIn + ") Loaded as " +
ito.toString() + " (" + location + ")");
} }
}
} }
@@ -1,117 +1,186 @@
package customskinloader.fake; package customskinloader.fake;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt; import java.util.function.Function;
import java.awt.image.ImageObserver; import java.util.function.Predicate;
public class FakeSkinBuffer implements net.minecraft.client.renderer.IImageBuffer { import customskinloader.CustomSkinLoader;
import customskinloader.fake.texture.FakeBufferedImage;
import customskinloader.fake.texture.FakeImage;
import customskinloader.fake.texture.FakeNativeImage;
import net.minecraft.client.renderer.IImageBuffer;
import net.minecraft.client.renderer.texture.NativeImage;
private int[] imageData; public class FakeSkinBuffer implements IImageBuffer {
private int ratio=1; private int ratio = 1;
FakeImage image = null;
@Override //parseUserSkin for 1.15+
public BufferedImage parseUserSkin(BufferedImage image) { public static NativeImage processLegacySkin(NativeImage image, Runnable processTask, Function<NativeImage, NativeImage> processLegacySkin) {
if(image==null) if (processTask instanceof IImageBuffer) {
return null; return ((IImageBuffer) processTask).func_195786_a(image);
ratio = image.getWidth() / 64;
BufferedImage bufferedimage = new BufferedImage(64 * ratio, 64 * ratio, 2);
Graphics graphics = bufferedimage.getGraphics();
graphics.setColor(new Color(0,0,0,0));
graphics.fillRect(0,0,64,64);
graphics.drawImage(image,0,0,(ImageObserver)null);
if (image.getHeight() == 32 * ratio){//Single Layer
//Revert to original algorithm
//Right Leg -> Left Leg
graphics.drawImage(bufferedimage, 24 * ratio, 48 * ratio, 20 * ratio, 52 * ratio, 4 * ratio, 16 * ratio, 8 * ratio, 20 * ratio, (ImageObserver)null);//Top
graphics.drawImage(bufferedimage, 28 * ratio, 48 * ratio, 24 * ratio, 52 * ratio, 8 * ratio, 16 * ratio, 12 * ratio, 20 * ratio, (ImageObserver)null);//Bottom
graphics.drawImage(bufferedimage, 20 * ratio, 52 * ratio, 16 * ratio, 64 * ratio, 8 * ratio, 20 * ratio, 12 * ratio, 32 * ratio, (ImageObserver)null);//Left
graphics.drawImage(bufferedimage, 24 * ratio, 52 * ratio, 20 * ratio, 64 * ratio, 4 * ratio, 20 * ratio, 8 * ratio, 32 * ratio, (ImageObserver)null);//Front
graphics.drawImage(bufferedimage, 28 * ratio, 52 * ratio, 24 * ratio, 64 * ratio, 0 * ratio, 20 * ratio, 4 * ratio, 32 * ratio, (ImageObserver)null);//Right
graphics.drawImage(bufferedimage, 32 * ratio, 52 * ratio, 28 * ratio, 64 * ratio, 12 * ratio, 20 * ratio, 16 * ratio, 32 * ratio, (ImageObserver)null);//Back
//Right Arm -> Left Arm
graphics.drawImage(bufferedimage, 40 * ratio, 48 * ratio, 36 * ratio, 52 * ratio, 44 * ratio, 16 * ratio, 48 * ratio, 20 * ratio, (ImageObserver)null);//Top
graphics.drawImage(bufferedimage, 44 * ratio, 48 * ratio, 40 * ratio, 52 * ratio, 48 * ratio, 16 * ratio, 52 * ratio, 20 * ratio, (ImageObserver)null);//Bottom
graphics.drawImage(bufferedimage, 36 * ratio, 52 * ratio, 32 * ratio, 64 * ratio, 48 * ratio, 20 * ratio, 52 * ratio, 32 * ratio, (ImageObserver)null);//Left
graphics.drawImage(bufferedimage, 40 * ratio, 52 * ratio, 36 * ratio, 64 * ratio, 44 * ratio, 20 * ratio, 48 * ratio, 32 * ratio, (ImageObserver)null);//Front
graphics.drawImage(bufferedimage, 44 * ratio, 52 * ratio, 40 * ratio, 64 * ratio, 40 * ratio, 20 * ratio, 44 * ratio, 32 * ratio, (ImageObserver)null);//Right
graphics.drawImage(bufferedimage, 48 * ratio, 52 * ratio, 44 * ratio, 64 * ratio, 52 * ratio, 20 * ratio, 56 * ratio, 32 * ratio, (ImageObserver)null);//Back
} }
graphics.dispose(); return processLegacySkin.apply(image);
this.imageData = ((DataBufferInt)bufferedimage.getRaster().getDataBuffer()).getData(); }
setAreaDueToConfig( 0 * ratio, 0 * ratio,32 * ratio,16 * ratio);//Head - 1 //parseUserSkin for 1.13+
setAreaTransparent(32 * ratio, 0 * ratio,64 * ratio,16 * ratio);//Head - 2 public NativeImage func_195786_a(NativeImage image) {
if (image == null)
return null;
setAreaDueToConfig( 0 * ratio,16 * ratio,16 * ratio,32 * ratio);//Right Leg - 1 FakeImage img = parseUserSkin(new FakeNativeImage(image));
setAreaDueToConfig(16 * ratio,16 * ratio,40 * ratio,32 * ratio);//Body - 1 if (img instanceof FakeNativeImage)
setAreaDueToConfig(40 * ratio,16 * ratio,56 * ratio,32 * ratio);//Right Arm - 1 return ((FakeNativeImage) img).getImage();
setAreaTransparent( 0 * ratio,32 * ratio,16 * ratio,48 * ratio);//Right Leg - 2 CustomSkinLoader.logger.warning("Failed to parseUserSkin(func_195786_a).");
setAreaTransparent(16 * ratio,32 * ratio,40 * ratio,48 * ratio);//Body - 2 return null;
setAreaTransparent(40 * ratio,32 * ratio,56 * ratio,48 * ratio);//Right Arm - 2 }
setAreaTransparent( 0 * ratio,48 * ratio,16 * ratio,64 * ratio);//Left Leg - 2 //parseUserSkin for 1.12.2-
setAreaDueToConfig(16 * ratio,48 * ratio,32 * ratio,64 * ratio);//Left Leg - 1 public BufferedImage parseUserSkin(BufferedImage image) {
setAreaDueToConfig(32 * ratio,48 * ratio,48 * ratio,64 * ratio);//Left Arm - 1 if (image == null)
setAreaTransparent(48 * ratio,48 * ratio,64 * ratio,64 * ratio);//Left Arm - 2 return null;
return bufferedimage; FakeImage img = parseUserSkin(new FakeBufferedImage(image));
if (img instanceof FakeBufferedImage)
return ((FakeBufferedImage) img).getImage();
CustomSkinLoader.logger.warning("Failed to parseUserSkin.");
return null;
}
public FakeImage parseUserSkin(FakeImage image) {
if (image == null) return null;
this.ratio = image.getWidth() / 64;
if (image.getHeight() != image.getWidth()) {//Single Layer
//Create a new image and copy origin image data
FakeImage img = image.createImage(64 * ratio, 64 * ratio);
img.copyImageData(image);
image.close();
image = img;
image.fillArea(0 * ratio, 32 * ratio, 64 * ratio, 32 * ratio);
//Right Leg -> Left Leg
image.copyArea(4 * ratio, 16 * ratio, 16 * ratio, 32 * ratio, 4 * ratio, 4 * ratio, true, false);//Top
image.copyArea(8 * ratio, 16 * ratio, 16 * ratio, 32 * ratio, 4 * ratio, 4 * ratio, true, false);//Bottom
image.copyArea(0 * ratio, 20 * ratio, 24 * ratio, 32 * ratio, 4 * ratio, 12 * ratio, true, false);//Right
image.copyArea(4 * ratio, 20 * ratio, 16 * ratio, 32 * ratio, 4 * ratio, 12 * ratio, true, false);//Front
image.copyArea(8 * ratio, 20 * ratio, 8 * ratio, 32 * ratio, 4 * ratio, 12 * ratio, true, false);//Left
image.copyArea(12 * ratio, 20 * ratio, 16 * ratio, 32 * ratio, 4 * ratio, 12 * ratio, true, false);//Back
//Right Arm -> Left Arm
image.copyArea(44 * ratio, 16 * ratio, -8 * ratio, 32 * ratio, 4 * ratio, 4 * ratio, true, false);//Top
image.copyArea(48 * ratio, 16 * ratio, -8 * ratio, 32 * ratio, 4 * ratio, 4 * ratio, true, false);//Bottom
image.copyArea(40 * ratio, 20 * ratio, 0 * ratio, 32 * ratio, 4 * ratio, 12 * ratio, true, false);//Right
image.copyArea(44 * ratio, 20 * ratio, -8 * ratio, 32 * ratio, 4 * ratio, 12 * ratio, true, false);//Front
image.copyArea(48 * ratio, 20 * ratio, -16 * ratio, 32 * ratio, 4 * ratio, 12 * ratio, true, false);//Left
image.copyArea(52 * ratio, 20 * ratio, -8 * ratio, 32 * ratio, 4 * ratio, 12 * ratio, true, false);//Back
}
this.image = image;
setAreaDueToConfig(0 * ratio, 0 * ratio, 32 * ratio, 16 * ratio);//Head - 1
setAreaTransparent(32 * ratio, 0 * ratio, 64 * ratio, 16 * ratio);//Head - 2
setAreaDueToConfig(16 * ratio, 16 * ratio, 40 * ratio, 32 * ratio);//Body - 1
setAreaTransparent(16 * ratio, 32 * ratio, 40 * ratio, 48 * ratio);//Body - 2
setAreaDueToConfig(40 * ratio, 16 * ratio, 56 * ratio, 32 * ratio);//Right Arm - 1
setAreaTransparent(40 * ratio, 32 * ratio, 56 * ratio, 48 * ratio);//Right Arm - 2
setAreaDueToConfig(0 * ratio, 16 * ratio, 16 * ratio, 32 * ratio);//Right Leg - 1
setAreaTransparent(0 * ratio, 32 * ratio, 16 * ratio, 48 * ratio);//Right Leg - 2
setAreaDueToConfig(32 * ratio, 48 * ratio, 48 * ratio, 64 * ratio);//Left Arm - 1
setAreaTransparent(48 * ratio, 48 * ratio, 64 * ratio, 64 * ratio);//Left Arm - 2
setAreaDueToConfig(16 * ratio, 48 * ratio, 32 * ratio, 64 * ratio);//Left Leg - 1
setAreaTransparent(0 * ratio, 48 * ratio, 16 * ratio, 64 * ratio);//Left Leg - 2
return image;
}
/** Judge if the color is transparent or same with background */
static final Function<Integer, Predicate<Integer>> EQU_BG = bgColor -> getA(bgColor) == 0 ? (c) -> getA(c) == 0 : (c) -> c.equals(bgColor);
/**
* Judge the type of skin
* Must be called after parseUserSkin
*
* @return type of skin (slim / default)
* @since 14.9
*/
public String judgeType() {
if (this.image == null)
return "default";
int bgColor = image.getRGBA(63 * ratio, 20 * ratio);
/*
* If background is transparent, all the pixels in ((54, 20), (55, 31)) areas is transparent,
* which means it is Alex model.
* If background is opaque, all the pixels in ((54, 20), (55, 31)) areas is same with background,
* which means it is Alex model.
* Otherwise, it is Steve model.
* */
Predicate<Integer> predicate = EQU_BG.apply(bgColor);
for (int x = 54 * ratio; x <= 55 * ratio; ++x) {
for (int y = 20 * ratio; y <= 31 * ratio; ++y) {
int color = image.getRGBA(x, y);
if (!predicate.test(color)) {
return "default";
}
}
}
return "slim";
} }
/* 2^24-1 /* 2^24-1
* 00000000 11111111 11111111 11111111 */ * 00000000 11111111 11111111 11111111 */
private static final int A=16777215; private static final int A = 16777215;
private static final int WHITE=getARGB(255,255,255,255); private static final int WHITE = getARGB(255, 255, 255, 255);
private static final int BLACK=getARGB(255,0,0,0); private static final int BLACK = getARGB(255, 0, 0, 0);
private boolean isFilled(int x0,int y0,int x1,int y1){
int data=this.imageData[getPosition(x0,y0)]; private boolean isFilled(int x0, int y0, int x1, int y1) {
if(data!=WHITE && data!=BLACK) int data = image.getRGBA(x0, y0);
if (data != WHITE && data != BLACK)
return false; return false;
for (int x=x0;x<x1;++x) for (int x = x0; x < x1; ++x)
for (int y=y0;y<y1;++y) for (int y = y0; y < y1; ++y)
if(this.imageData[getPosition(x,y)]!=data) if (image.getRGBA(x, y) != data)
return false; return false;
return true; return true;
} }
private void setAreaTransparent(int x0,int y0,int x1,int y1){
if(!isFilled(x0,y0,x1,y1)) private void setAreaTransparent(int x0, int y0, int x1, int y1) {
if (!isFilled(x0, y0, x1, y1))
return; return;
for (int x=x0;x<x1;++x) for (int x = x0; x < x1; ++x)
for (int y=y0;y<y1;++y) for (int y = y0; y < y1; ++y)
this.imageData[getPosition(x,y)] &= A; image.setRGBA(x, y, image.getRGBA(x, y) & A);
} }
/* -2^24 /* -2^24
* 00000001 00000000 00000000 00000000 -> * 00000001 00000000 00000000 00000000 ->
* 11111110 11111111 11111111 11111111 -> * 11111110 11111111 11111111 11111111 ->
* 11111111 00000000 00000000 00000000 */ * 11111111 00000000 00000000 00000000 */
private static final int B=-16777216; private static final int B = -16777216;
private void setAreaOpaque(int x0,int y0,int x1,int y1){
for (int x=x0;x<x1;++x) private void setAreaOpaque(int x0, int y0, int x1, int y1) {
for (int y=y0;y<y1;++y) for (int x = x0; x < x1; ++x)
this.imageData[getPosition(x,y)] |= B; for (int y = y0; y < y1; ++y)
image.setRGBA(x, y, image.getRGBA(x, y) | B);
} }
private void setAreaDueToConfig(int x0,int y0,int x1,int y1){ private void setAreaDueToConfig(int x0, int y0, int x1, int y1) {
if(customskinloader.CustomSkinLoader.config.enableTransparentSkin) if (customskinloader.CustomSkinLoader.config.enableTransparentSkin)
setAreaTransparent(x0,y0,x1,y1); setAreaTransparent(x0, y0, x1, y1);
else else
setAreaOpaque(x0,y0,x1,y1); setAreaOpaque(x0, y0, x1, y1);
} }
public void skinAvailable() {
@Override //A callback when skin loaded, nothing to do
public void skinAvailable(){
//A callback when skin loaded
} }
private static int getARGB(int a,int r,int g,int b){ private static int getARGB(int a, int r, int g, int b) {
return (a << 24) | (r << 16) | (g << 8) | b; return (a << 24) | (r << 16) | (g << 8) | b;
} }
private int getPosition(int x,int y){ private static int getA(int argb) {
return x+y*64*ratio; return (argb & B) >>> 24;
} }
} }
@@ -2,106 +2,150 @@ package customskinloader.fake;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.io.File; import java.io.File;
import java.util.Iterator;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
import com.google.common.hash.Hashing;
import com.mojang.authlib.GameProfile; import com.mojang.authlib.GameProfile;
import com.mojang.authlib.minecraft.MinecraftProfileTexture; import com.mojang.authlib.minecraft.MinecraftProfileTexture;
import com.mojang.authlib.minecraft.MinecraftProfileTexture.Type;
import com.mojang.authlib.minecraft.MinecraftSessionService; import com.mojang.authlib.minecraft.MinecraftSessionService;
import customskinloader.CustomSkinLoader; import customskinloader.CustomSkinLoader;
import customskinloader.fake.itf.FakeInterfaceManager;
import customskinloader.utils.HttpTextureUtil; import customskinloader.utils.HttpTextureUtil;
import customskinloader.utils.HttpTextureUtil.HttpTextureInfo;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.IImageBuffer; import net.minecraft.client.renderer.IImageBuffer;
import net.minecraft.client.renderer.ThreadDownloadImageData; import net.minecraft.client.renderer.texture.SimpleTexture;
import net.minecraft.client.renderer.texture.ITextureObject;
import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.client.resources.DefaultPlayerSkin; import net.minecraft.client.resources.DefaultPlayerSkin;
import net.minecraft.client.resources.SkinManager.SkinAvailableCallback; import net.minecraft.client.resources.SkinManager;
import net.minecraft.util.ResourceLocation; import net.minecraft.util.ResourceLocation;
public class FakeSkinManager{ public class FakeSkinManager {
private static final ExecutorService THREAD_POOL = new ThreadPoolExecutor(0, 2, 1L, TimeUnit.MINUTES, new LinkedBlockingQueue());
private final TextureManager textureManager; private final TextureManager textureManager;
private final Map<ResourceLocation, MinecraftProfileTexture> modelCache = new ConcurrentHashMap<>();
public FakeSkinManager(TextureManager textureManagerInstance, File skinCacheDirectory, MinecraftSessionService sessionService) { public FakeSkinManager(TextureManager textureManagerInstance, File skinCacheDirectory, MinecraftSessionService sessionService) {
this.textureManager=textureManagerInstance; this.textureManager = textureManagerInstance;
HttpTextureUtil.defaultCacheDir=skinCacheDirectory; HttpTextureUtil.defaultCacheDir = skinCacheDirectory;
} }
public ResourceLocation loadSkin(MinecraftProfileTexture profileTexture, Type textureType){ public ResourceLocation loadSkin(MinecraftProfileTexture profileTexture, MinecraftProfileTexture.Type textureType) {
return this.loadSkin(profileTexture, textureType, null); return this.loadSkin(profileTexture, textureType, null);
} }
public ResourceLocation loadSkin(final MinecraftProfileTexture profileTexture, final Type textureType, final SkinAvailableCallback skinAvailableCallback){
HttpTextureInfo info=HttpTextureUtil.toHttpTextureInfo(profileTexture.getUrl());
final ResourceLocation resourcelocation = new ResourceLocation("skins/" + info.hash); public ResourceLocation loadSkin(final MinecraftProfileTexture profileTexture, final MinecraftProfileTexture.Type textureType, final SkinManager.SkinAvailableCallback skinAvailableCallback) {
ITextureObject itextureobject = this.textureManager.getTexture(resourcelocation); return this.loadSkin(profileTexture, HttpTextureUtil.toHttpTextureInfo(profileTexture.getUrl()), textureType, skinAvailableCallback);
}
if (itextureobject != null)//Have already loaded private ResourceLocation loadSkin(final MinecraftProfileTexture profileTexture, final HttpTextureUtil.HttpTextureInfo info, final MinecraftProfileTexture.Type textureType, final SkinManager.SkinAvailableCallback skinAvailableCallback) {
makeCallback(skinAvailableCallback,textureType, resourcelocation, profileTexture); final ResourceLocation resourcelocation = new ResourceLocation("skins/" + Hashing.sha1().hashUnencodedChars(info.hash).toString());
else{
ThreadDownloadImageData threaddownloadimagedata = new ThreadDownloadImageData(info.cacheFile, info.url, DefaultPlayerSkin.getDefaultSkinLegacy(), if (FakeInterfaceManager.TextureManager_getTexture(this.textureManager, resourcelocation, null) != null) {//Have already loaded
new BaseBuffer(skinAvailableCallback, textureType, resourcelocation, profileTexture)); makeCallback(skinAvailableCallback, textureType, resourcelocation, modelCache.getOrDefault(resourcelocation, profileTexture));
this.textureManager.loadTexture(resourcelocation, threaddownloadimagedata); } else {
SimpleTexture threaddownloadimagedata = FakeThreadDownloadImageData.createThreadDownloadImageData(info.cacheFile, info.url, DefaultPlayerSkin.getDefaultSkinLegacy(), new BaseBuffer(skinAvailableCallback, textureType, resourcelocation, profileTexture), textureType);
if (skinAvailableCallback instanceof FakeClientPlayer.LegacyBuffer)//Cache for client player
FakeClientPlayer.textureCache.put(resourcelocation, threaddownloadimagedata);
FakeInterfaceManager.TextureManager_loadTexture(this.textureManager, resourcelocation, threaddownloadimagedata);
} }
return resourcelocation; return resourcelocation;
} }
public void loadProfileTextures(final GameProfile profile, final SkinAvailableCallback skinAvailableCallback, final boolean requireSecure){
THREAD_POOL.submit(new Runnable(){
public void run(){
final Map<Type, MinecraftProfileTexture> map = Maps.<Type, MinecraftProfileTexture>newHashMap();
map.putAll(customskinloader.CustomSkinLoader.loadProfile(profile));
Minecraft.getMinecraft().addScheduledTask(new Runnable(){ public void loadProfileTextures(final GameProfile profile, final SkinManager.SkinAvailableCallback skinAvailableCallback, final boolean requireSecure) {
public void run(){ CustomSkinLoader.loadProfileTextures(() -> CustomSkinLoader.loadProfileLazily(profile, m -> {
for(Type type:Type.values()) final Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> map = Maps.newHashMap();
if(map.containsKey(type)) map.putAll(m);
FakeSkinManager.this.loadSkin((MinecraftProfileTexture)map.get(type), type, skinAvailableCallback);
} for (MinecraftProfileTexture.Type type : MinecraftProfileTexture.Type.values()) {
}); MinecraftProfileTexture profileTexture = map.get(type);
if (profileTexture != null) {
HttpTextureUtil.HttpTextureInfo info = HttpTextureUtil.toHttpTextureInfo(profileTexture.getUrl());
FakeThreadDownloadImageData.downloadTexture(info.cacheFile, info.url);
FakeInterfaceManager.Minecraft_addScheduledTask(Minecraft.getMinecraft(), () -> {
CustomSkinLoader.logger.debug("Loading type: " + type);
try {
this.loadSkin(profileTexture, info, type, skinAvailableCallback);
} catch (Throwable t) {
CustomSkinLoader.logger.warning(t);
}
});
}
} }
}); }));
}
public Map<Type, MinecraftProfileTexture> loadSkinFromCache(GameProfile profile){
return CustomSkinLoader.loadProfileFromCache(profile);
} }
private static void makeCallback(SkinAvailableCallback callback,Type type, ResourceLocation location, MinecraftProfileTexture texture){ public Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> loadSkinFromCache(GameProfile profile) {
if(callback!=null) Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> map = CustomSkinLoader.loadProfileFromCache(profile);
for (Iterator<Map.Entry<MinecraftProfileTexture.Type, MinecraftProfileTexture>> it = map.entrySet().iterator(); it.hasNext(); ) {
Map.Entry<MinecraftProfileTexture.Type, MinecraftProfileTexture> entry = it.next();
MinecraftProfileTexture texture = entry.getValue();
if (shouldJudgeType(texture)) {
texture = this.modelCache.get(this.loadSkin(texture, entry.getKey()));
if (texture == null) { // remove texture if was not loaded before
it.remove();
} else {
map.put(entry.getKey(), texture);
}
}
}
return map;
}
private static void makeCallback(SkinManager.SkinAvailableCallback callback, MinecraftProfileTexture.Type type, ResourceLocation location, MinecraftProfileTexture texture) {
if (callback != null)
callback.skinAvailable(type, location, texture); callback.skinAvailable(type, location, texture);
} }
private class BaseBuffer implements IImageBuffer{
private static boolean shouldJudgeType(MinecraftProfileTexture texture) {
return texture != null && "auto".equals(texture.getMetadata("model"));
}
private class BaseBuffer implements IImageBuffer {
private IImageBuffer buffer; private IImageBuffer buffer;
private SkinAvailableCallback callback; private SkinManager.SkinAvailableCallback callback;
private Type type; private MinecraftProfileTexture.Type type;
private ResourceLocation location; private ResourceLocation location;
private MinecraftProfileTexture texture; private MinecraftProfileTexture texture;
public BaseBuffer(SkinAvailableCallback callback,Type type,ResourceLocation location,MinecraftProfileTexture texture){
this.buffer=(type==Type.SKIN?new FakeSkinBuffer():null);
this.callback=callback; public BaseBuffer(SkinManager.SkinAvailableCallback callback, MinecraftProfileTexture.Type type, ResourceLocation location, MinecraftProfileTexture texture) {
this.type=type; switch (type) {
this.location=location; case SKIN: this.buffer = new FakeSkinBuffer(); break;
this.texture=texture; case CAPE: this.buffer = new FakeCapeBuffer(location); break;
}
this.callback = callback;
this.type = type;
this.location = location;
this.texture = texture;
} }
public BufferedImage parseUserSkin(BufferedImage image){ public net.minecraft.client.renderer.texture.NativeImage func_195786_a(net.minecraft.client.renderer.texture.NativeImage image) {
return buffer==null?image:buffer.parseUserSkin(image); return buffer instanceof FakeSkinBuffer ? ((FakeSkinBuffer) buffer).func_195786_a(image) : image;
} }
public void skinAvailable(){
if (buffer != null) public BufferedImage parseUserSkin(BufferedImage image) {
return buffer instanceof FakeSkinBuffer ? ((FakeSkinBuffer) buffer).parseUserSkin(image) : image;
}
public void skinAvailable() {
if (buffer != null) {
buffer.skinAvailable(); buffer.skinAvailable();
if (shouldJudgeType(texture) && buffer instanceof FakeSkinBuffer) {
//Auto judge skin type
Map<String, String> metadata = Maps.newHashMap();
String type = ((FakeSkinBuffer) buffer).judgeType();
metadata.put("model", type);
texture = new MinecraftProfileTexture(texture.getUrl(), metadata);
FakeSkinManager.this.modelCache.put(location, texture);
}
}
FakeSkinManager.makeCallback(callback,type, location, texture); FakeSkinManager.makeCallback(callback, type, location, texture);
} }
} }
} }
@@ -0,0 +1,101 @@
package customskinloader.fake;
import java.io.File;
import java.util.EnumMap;
import java.util.function.Supplier;
import com.mojang.authlib.minecraft.MinecraftProfileTexture;
import customskinloader.CustomSkinLoader;
import customskinloader.utils.HttpRequestUtil;
import net.minecraft.client.renderer.IImageBuffer;
import net.minecraft.client.renderer.ThreadDownloadImageData;
import net.minecraft.client.renderer.texture.DownloadingTexture;
import net.minecraft.client.renderer.texture.SimpleTexture;
import net.minecraft.util.ResourceLocation;
public class FakeThreadDownloadImageData {
private static IThreadDownloadImageDataBuilder builder;
public static SimpleTexture createThreadDownloadImageData(File cacheFileIn, String imageUrlIn, ResourceLocation textureResourceLocationIn, IImageBuffer imageBufferIn, MinecraftProfileTexture.Type textureTypeIn) {
SimpleTexture texture = null;
if (FakeThreadDownloadImageData.builder == null) {
EnumMap<ThreadDownloadImageDataBuilder, Throwable> throwables = new EnumMap<>(ThreadDownloadImageDataBuilder.class);
for (ThreadDownloadImageDataBuilder builder : ThreadDownloadImageDataBuilder.values()) {
try {
FakeThreadDownloadImageData.builder = builder.get().get();
texture = FakeThreadDownloadImageData.builder.build(cacheFileIn, imageUrlIn, textureResourceLocationIn, imageBufferIn, textureTypeIn);
CustomSkinLoader.logger.info("ThreadDownloadImageData Class: %s", texture.getClass().getName());
break;
} catch (Throwable t) {
throwables.put(builder, t);
}
}
if (texture == null) {
CustomSkinLoader.logger.warning("Unable to get ThreadDownloadImageData Class: ");
throwables.forEach((k, v) -> {
CustomSkinLoader.logger.warning("Caused by: (%s)", k.name());
CustomSkinLoader.logger.warning(v);
});
throw new RuntimeException("Unable to get ThreadDownloadImageData Class!");
}
} else {
texture = builder.build(cacheFileIn, imageUrlIn, textureResourceLocationIn, imageBufferIn, textureTypeIn);
}
return texture;
}
public static void downloadTexture(File cacheFile, String imageUrl) {
HttpRequestUtil.HttpRequest request = new HttpRequestUtil.HttpRequest(imageUrl).setLoadContent(false).setCacheTime(0).setCacheFile(cacheFile);
for (int i = 0; i <= CustomSkinLoader.config.retryTime; i++) {
if (i != 0) {
CustomSkinLoader.logger.debug("Retry to download texture %s (%s)", imageUrl, i);
}
if (HttpRequestUtil.makeHttpRequest(request).success) {
break;
}
}
}
private interface IThreadDownloadImageDataBuilder {
SimpleTexture build(File cacheFile, String imageUrl, ResourceLocation textureResourceLocation, IImageBuffer imageBuffer, MinecraftProfileTexture.Type textureType);
}
private enum ThreadDownloadImageDataBuilder {
// DO NOT replace new IThreadDownloadImageDataBuilder() with lambda.
V1(() -> new IThreadDownloadImageDataBuilder() { // Forge 1.8.x~1.12.x
@Override
public SimpleTexture build(File cacheFile, String imageUrl, ResourceLocation textureResourceLocation, IImageBuffer imageBuffer, MinecraftProfileTexture.Type textureType) {
return new ThreadDownloadImageData(cacheFile, imageUrl, textureResourceLocation, imageBuffer);
}
}),
V2(() -> new IThreadDownloadImageDataBuilder() { // Forge 1.13.x
@Override
public SimpleTexture build(File cacheFile, String imageUrl, ResourceLocation textureResourceLocation, IImageBuffer imageBuffer, MinecraftProfileTexture.Type textureType) {
return new net.minecraft.client.renderer.texture.ThreadDownloadImageData(cacheFile, imageUrl, textureResourceLocation, imageBuffer);
}
}),
V3(() -> new IThreadDownloadImageDataBuilder() { // Forge 1.14.x
@Override
public SimpleTexture build(File cacheFile, String imageUrl, ResourceLocation textureResourceLocation, IImageBuffer imageBuffer, MinecraftProfileTexture.Type textureType) {
return new DownloadingTexture(cacheFile, imageUrl, textureResourceLocation, imageBuffer);
}
}),
V4(() -> new IThreadDownloadImageDataBuilder() { // Forge 1.15.x~1.16.x
@Override
public SimpleTexture build(File cacheFile, String imageUrl, ResourceLocation textureResourceLocation, IImageBuffer imageBuffer, MinecraftProfileTexture.Type textureType) {
return new DownloadingTexture(cacheFile, imageUrl, textureResourceLocation, true, imageBuffer);
}
});
private final Supplier<IThreadDownloadImageDataBuilder> builder;
ThreadDownloadImageDataBuilder(Supplier<IThreadDownloadImageDataBuilder> builder) {
this.builder = builder;
}
public Supplier<IThreadDownloadImageDataBuilder> get() {
return this.builder;
}
}
}
@@ -0,0 +1,43 @@
package customskinloader.fake.itf;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.util.Optional;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.texture.Texture;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.client.resources.IResource;
import net.minecraft.client.resources.IResourceManager;
import net.minecraft.util.ResourceLocation;
public class FakeInterfaceManager {
public static InputStream IResource_getInputStream(Object resource) {
return ((IFakeIResource.V2) resource).open();
}
public static Optional<IResource> IResourceManager_getResource(Object resourceManager, ResourceLocation location) throws IOException {
return ((IFakeIResourceManager) resourceManager).getResource(location);
}
public static IResourceManager Minecraft_getResourceManager(Minecraft minecraft) {
return (IResourceManager) ((IFakeMinecraft) minecraft).func_195551_G();
}
public static void Minecraft_addScheduledTask(Minecraft minecraft, Runnable runnable) {
((IFakeMinecraft) minecraft).execute(runnable);
}
public static void TextureManager_loadTexture(TextureManager textureManager, ResourceLocation textureLocation, Object textureObj) {
((IFakeTextureManager.V2) textureManager).func_229263_a_(textureLocation, (Texture) textureObj);
}
public static Texture TextureManager_getTexture(TextureManager textureManager, ResourceLocation textureLocation, Object textureObj) {
return ((IFakeTextureManager.V1) textureManager).getTexture(textureLocation, (Texture) textureObj);
}
public static void ThreadDownloadImageData_resetNewBufferedImage(Object threadDownloadImageData, BufferedImage image) {
((IFakeThreadDownloadImageData) threadDownloadImageData).resetNewBufferedImage(image);
}
}
@@ -0,0 +1,22 @@
package customskinloader.fake.itf;
import java.io.InputStream;
import net.minecraft.client.resources.IResource;
/** {@link net.minecraft.client.resources.IResource} is no longer an interface since 22w14a */
public interface IFakeIResource {
// 1.13.2 ~ 22w13a
interface V1 {
default InputStream func_199027_b() {
return ((IResource) this).getInputStream();
}
}
// 22w14a+
interface V2 {
default InputStream open() {
return ((IFakeIResource.V1) this).func_199027_b();
}
}
}
@@ -0,0 +1,20 @@
package customskinloader.fake.itf;
import java.io.IOException;
import java.util.Optional;
import net.minecraft.client.resources.IResourceManager;
import net.minecraft.resources.IResource;
import net.minecraft.util.ResourceLocation;
public interface IFakeIResourceManager {
// 1.13.2 ~ 22w13a
default IResource func_199002_a(ResourceLocation location) throws IOException {
return (IResource) ((IResourceManager) this).getResource(location);
}
// 22w14a+
default Optional getResource(ResourceLocation location) throws IOException {
return Optional.ofNullable(this.func_199002_a(location));
}
}
@@ -0,0 +1,16 @@
package customskinloader.fake.itf;
import net.minecraft.client.Minecraft;
import net.minecraft.resources.IResourceManager;
public interface IFakeMinecraft {
// 1.13.2+
default IResourceManager func_195551_G() {
return (IResourceManager) ((Minecraft) this).getResourceManager();
}
// 1.14+
default void execute(Runnable runnable) {
((Minecraft) this).addScheduledTask(runnable);
}
}
@@ -0,0 +1,28 @@
package customskinloader.fake.itf;
import net.minecraft.client.renderer.texture.ITextureObject;
import net.minecraft.client.renderer.texture.Texture;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.util.ResourceLocation;
public interface IFakeTextureManager {
interface V1 {
default boolean func_229263_a_(ResourceLocation textureLocation, Texture textureObj) {
return ((TextureManager) this).loadTexture(textureLocation, (ITextureObject) textureObj);
}
default Texture func_229267_b_(ResourceLocation textureLocation) {
return (Texture) ((TextureManager) this).getTexture(textureLocation);
}
default Texture getTexture(ResourceLocation textureLocation, Texture textureObj) {
return func_229267_b_(textureLocation);
}
}
interface V2 {
default void func_229263_a_(ResourceLocation textureLocation, Texture textureObj) {
((IFakeTextureManager.V1) this).func_229263_a_(textureLocation, textureObj);
}
}
}
@@ -0,0 +1,12 @@
package customskinloader.fake.itf;
import java.awt.image.BufferedImage;
// This interface is only available before 1.12.2
public interface IFakeThreadDownloadImageData {
/**
* Reset {@link net.minecraft.client.renderer.ThreadDownloadImageData#bufferedImage} and
* {@link net.minecraft.client.renderer.ThreadDownloadImageData#textureUploaded} to false to refresh texture.
*/
void resetNewBufferedImage(BufferedImage image);
}
@@ -0,0 +1,75 @@
package customskinloader.fake.texture;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO;
public class FakeBufferedImage implements FakeImage {
private BufferedImage image;
private Graphics graphics;
public FakeBufferedImage(int width, int height) {
this(new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB));
}
public FakeBufferedImage(BufferedImage image) {
this.image = image;
graphics = image.getGraphics();
}
public BufferedImage getImage() {
graphics.dispose();
return image;
}
public FakeImage createImage(int width, int height) {
return new FakeBufferedImage(width, height);
}
public FakeImage createImage(InputStream is) throws IOException {
return new FakeBufferedImage(ImageIO.read(is));
}
public int getWidth() {
return image.getWidth();
}
public int getHeight() {
return image.getHeight();
}
public int getRGBA(int x, int y) {
return image.getRGB(x, y);
}
public void setRGBA(int x, int y, int rgba) {
image.setRGB(x, y, rgba);
}
public void copyImageData(FakeImage image) {
if (!(image instanceof FakeBufferedImage)) return;
BufferedImage img = ((FakeBufferedImage) image).getImage();
graphics.drawImage(img, 0, 0, null);
}
public void fillArea(int x0, int y0, int width, int height) {
graphics.setColor(new Color(0, 0, 0, 0));
graphics.fillRect(x0, y0, width, height);
}
public void copyArea(int x0, int y0, int dx, int dy, int width, int height, boolean reversex, boolean reversey) {
int x1 = x0 + width, x2 = x0 + dx, x3 = x2 + width;
int y1 = y0 + height, y2 = y0 + dy, y3 = y2 + height;
graphics.drawImage(image,
reversex ? x3 : x2, reversey ? y3 : y2,
reversex ? x2 : x3, reversey ? y2 : y3,
x0, y0, x1, y1, null);
}
public void close() {
graphics.dispose();
}
}
@@ -0,0 +1,26 @@
package customskinloader.fake.texture;
import java.io.IOException;
import java.io.InputStream;
public interface FakeImage {
FakeImage createImage(int width, int height);
FakeImage createImage(InputStream is) throws IOException;
int getWidth();
int getHeight();
int getRGBA(int x, int y);
void setRGBA(int x, int y, int rgba);
void copyImageData(FakeImage image);
void fillArea(int x0, int y0, int width, int height);
void copyArea(int x0, int y0, int dx, int dy, int width, int height, boolean reversex, boolean reversey);
void close();
}
@@ -0,0 +1,61 @@
package customskinloader.fake.texture;
import java.io.InputStream;
import net.minecraft.client.renderer.texture.NativeImage;
public class FakeNativeImage implements FakeImage {
private NativeImage image;
public FakeNativeImage(int width, int height) {
this(new NativeImage(width, height, true));
}
public FakeNativeImage(NativeImage image) {
this.image = image;
}
public NativeImage getImage() {
return image;
}
public FakeImage createImage(int width, int height) {
return new FakeNativeImage(width, height);
}
public FakeImage createImage(InputStream is) {
return new FakeNativeImage(NativeImage.func_195713_a(is));
}
public int getWidth() {
return image.func_195702_a();
}
public int getHeight() {
return image.func_195714_b();
}
public int getRGBA(int x, int y) {
return image.func_195709_a(x, y);
}
public void setRGBA(int x, int y, int rgba) {
image.func_195700_a(x, y, rgba);
}
public void copyImageData(FakeImage image) {
if (!(image instanceof FakeNativeImage)) return;
this.image.func_195703_a(((FakeNativeImage) image).getImage());
}
public void fillArea(int x0, int y0, int width, int height) {
image.func_195715_a(x0, y0, width, height, 0);
}
public void copyArea(int x0, int y0, int dx, int dy, int width, int height, boolean reversex, boolean reversey) {
image.func_195699_a(x0, y0, dx, dy, width, height, reversex, reversey);
}
public void close() {
}
}
@@ -1,100 +1,137 @@
package customskinloader.loader; package customskinloader.loader;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import org.apache.commons.io.IOUtils; import java.util.List;
import org.apache.commons.lang3.StringUtils;
import com.mojang.authlib.GameProfile; import com.mojang.authlib.GameProfile;
import customskinloader.CustomSkinLoader; import customskinloader.CustomSkinLoader;
import customskinloader.config.SkinSiteProfile; import customskinloader.config.SkinSiteProfile;
import customskinloader.loader.jsonapi.*; import customskinloader.plugin.ICustomSkinLoaderPlugin;
import customskinloader.profile.UserProfile; import customskinloader.profile.UserProfile;
import customskinloader.utils.HttpRequestUtil; import customskinloader.utils.HttpRequestUtil;
import customskinloader.utils.HttpUtil0; import customskinloader.utils.HttpUtil0;
import customskinloader.utils.HttpRequestUtil.HttpRequest; import org.apache.commons.io.IOUtils;
import customskinloader.utils.HttpRequestUtil.HttpResponce; import org.apache.commons.lang3.StringUtils;
public class JsonAPILoader implements ProfileLoader.IProfileLoader { public class JsonAPILoader implements ICustomSkinLoaderPlugin, ProfileLoader.IProfileLoader {
public interface IJsonAPI { public interface IJsonAPI {
public String toJsonUrl(String root,String username); List<IDefaultProfile> getDefaultProfiles(JsonAPILoader loader);
public String getPayload(SkinSiteProfile ssp);
public UserProfile toUserProfile(String root,String json,boolean local); String toJsonUrl(String root, String username);
public String getName();
String getPayload(SkinSiteProfile ssp);
UserProfile toUserProfile(String root, String json, boolean local);
String getName();
} }
public static class ErrorProfile{
public static class ErrorProfile {
public int errno; public int errno;
public String msg; public String msg;
} }
public static enum Type{
CustomSkinAPI(new CustomSkinAPI()),CustomSkinAPIPlus(new CustomSkinAPIPlus()),UniSkinAPI(new UniSkinAPI()); private final IJsonAPI jsonAPI;
public IJsonAPI jsonAPI;
private Type(IJsonAPI jsonAPI){ public JsonAPILoader(IJsonAPI jsonAPI) {
this.jsonAPI=jsonAPI; this.jsonAPI = jsonAPI;
}
} }
private Type type; // === ICustomSkinLoaderPlugin ===
public JsonAPILoader(Type type){
this.type=type; @Override
public ProfileLoader.IProfileLoader getProfileLoader() {
return this;
} }
@Override
public List<IDefaultProfile> getDefaultProfiles() {
return this.jsonAPI.getDefaultProfiles(this);
}
public abstract static class DefaultProfile implements ICustomSkinLoaderPlugin.IDefaultProfile {
protected final JsonAPILoader loader;
public DefaultProfile(JsonAPILoader loader) {
this.loader = loader;
}
@Override
public void updateSkinSiteProfile(SkinSiteProfile ssp) {
ssp.type = this.loader.getName();
ssp.root = this.getRoot();
}
public abstract String getRoot();
}
// === IProfileLoader ===
@Override @Override
public UserProfile loadProfile(SkinSiteProfile ssp, GameProfile gameProfile) throws Exception { public UserProfile loadProfile(SkinSiteProfile ssp, GameProfile gameProfile) throws Exception {
String username=gameProfile.getName(); String username = gameProfile.getName();
boolean local=HttpUtil0.isLocal(ssp.root); if (StringUtils.isEmpty(ssp.root)) {
if(ssp.root==null||ssp.root.equals("")){
CustomSkinLoader.logger.info("Root not defined."); CustomSkinLoader.logger.info("Root not defined.");
return null; return null;
} }
String jsonUrl=type.jsonAPI.toJsonUrl(ssp.root, username); boolean local = HttpUtil0.isLocal(ssp.root);
String jsonUrl = this.jsonAPI.toJsonUrl(ssp.root, username);
//Some API like MinecraftCapesAPI won't load profile at sometime
if (jsonUrl == null) {
CustomSkinLoader.logger.info("Profile url not found.");
return null;
}
String json; String json;
if(local){ if (local) {
File jsonFile=new File(jsonUrl); File jsonFile = new File(CustomSkinLoader.DATA_DIR, jsonUrl);
if(!jsonFile.exists()){ if (!jsonFile.exists()) {
CustomSkinLoader.logger.info("Profile File not found."); CustomSkinLoader.logger.info("Profile File not found.");
return null; return null;
} }
json=IOUtils.toString(new FileInputStream(jsonFile)); json = IOUtils.toString(Files.newInputStream(jsonFile.toPath()), StandardCharsets.UTF_8);
}else{ } else {
HttpResponce responce=HttpRequestUtil.makeHttpRequest(new HttpRequest(jsonUrl).setCacheTime(90).setUserAgent(ssp.userAgent).setPayload(type.jsonAPI.getPayload(ssp))); HttpRequestUtil.HttpResponce responce = HttpRequestUtil.makeHttpRequest(new HttpRequestUtil.HttpRequest(jsonUrl).setCacheTime(90).setUserAgent(ssp.userAgent).setPayload(this.jsonAPI.getPayload(ssp)));
json=responce.content; json = responce.content;
} }
if(json==null||json.equals("")){ if (json == null || json.equals("")) {
CustomSkinLoader.logger.info("Profile not found."); CustomSkinLoader.logger.info("Profile not found.");
return null; return null;
} }
ErrorProfile profile=CustomSkinLoader.GSON.fromJson(json, ErrorProfile.class); ErrorProfile profile = CustomSkinLoader.GSON.fromJson(json, ErrorProfile.class);
if(profile.errno!=0){ if (profile.errno != 0) {
CustomSkinLoader.logger.info("Error "+profile.errno+": "+profile.msg); CustomSkinLoader.logger.info("Error " + profile.errno + ": " + profile.msg);
return null; return null;
} }
UserProfile p=type.jsonAPI.toUserProfile(ssp.root, json, local); UserProfile p = this.jsonAPI.toUserProfile(ssp.root, json, local);
if(p==null||p.isEmpty()){ if (p == null || p.isEmpty()) {
CustomSkinLoader.logger.info("Both skin and cape not found."); CustomSkinLoader.logger.info("Both skin and cape not found.");
return null; return null;
}else{ } else {
return p; return p;
} }
} }
@Override @Override
public boolean compare(SkinSiteProfile ssp0, SkinSiteProfile ssp1) { public boolean compare(SkinSiteProfile ssp0, SkinSiteProfile ssp1) {
return StringUtils.isNoneEmpty(ssp0.root)?ssp0.root.equalsIgnoreCase(ssp1.root):true; return !StringUtils.isNoneEmpty(ssp0.root) || ssp0.root.equalsIgnoreCase(ssp1.root);
} }
@Override @Override
public String getName() { public String getName() {
return type.jsonAPI.getName(); return this.jsonAPI.getName();
} }
@Override @Override
public void initLocalFolder(SkinSiteProfile ssp) { public void init(SkinSiteProfile ssp) {
if(HttpUtil0.isLocal(ssp.root)){ if (HttpUtil0.isLocal(ssp.root)) {
File f=new File(ssp.root); File f = new File(ssp.root);
if(!f.exists()) if (!f.exists())
//noinspection ResultOfMethodCallIgnored
f.mkdirs(); f.mkdirs();
} }
} }
@@ -1,94 +1,200 @@
package customskinloader.loader; package customskinloader.loader;
import java.io.File; import java.io.File;
import java.util.Collections;
import org.apache.commons.lang3.StringUtils; import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
import com.mojang.authlib.GameProfile; import com.mojang.authlib.GameProfile;
import customskinloader.CustomSkinLoader; import customskinloader.CustomSkinLoader;
import customskinloader.config.SkinSiteProfile; import customskinloader.config.SkinSiteProfile;
import customskinloader.profile.ModelManager0; import customskinloader.plugin.ICustomSkinLoaderPlugin;
import customskinloader.profile.UserProfile; import customskinloader.profile.UserProfile;
import customskinloader.utils.HttpRequestUtil; import customskinloader.utils.HttpRequestUtil;
import customskinloader.utils.HttpRequestUtil.HttpRequest;
import customskinloader.utils.HttpRequestUtil.HttpResponce;
import customskinloader.utils.HttpTextureUtil; import customskinloader.utils.HttpTextureUtil;
import customskinloader.utils.HttpUtil0; import customskinloader.utils.HttpUtil0;
public class LegacyLoader implements ProfileLoader.IProfileLoader { public class LegacyLoader implements ICustomSkinLoaderPlugin, ProfileLoader.IProfileLoader {
public static final String USERNAME_REGEX="\\{USERNAME\\}";
@Override @Override
public UserProfile loadProfile(SkinSiteProfile ssp, GameProfile gameProfile) throws Exception { public ProfileLoader.IProfileLoader getProfileLoader() {
String username=gameProfile.getName(); return this;
UserProfile profile=new UserProfile(); }
if(StringUtils.isNoneEmpty(ssp.skin)){
String skin=ssp.skin.replaceAll(USERNAME_REGEX, username); @Override
if(HttpUtil0.isLocal(ssp.skin)){ public List<IDefaultProfile> getDefaultProfiles() {
File skinFile=new File(CustomSkinLoader.DATA_DIR,skin); return Collections.singletonList(new LocalSkin(this));
if(skinFile.exists()&&skinFile.isFile()) }
profile.skinUrl=HttpTextureUtil.getLocalLegacyFakeUrl(skin, HttpTextureUtil.getHash(skin, skinFile.length(), skinFile.lastModified()));
}else{ public abstract static class DefaultProfile implements ICustomSkinLoaderPlugin.IDefaultProfile {
HttpResponce responce=HttpRequestUtil.makeHttpRequest(new HttpRequest(skin).setUserAgent(ssp.userAgent).setCheckPNG(ssp.checkPNG!=null&&ssp.checkPNG!=false).setLoadContent(false).setCacheTime(90)); protected final LegacyLoader loader;
if(responce.success)
profile.skinUrl=HttpTextureUtil.getLegacyFakeUrl(skin); public DefaultProfile(LegacyLoader loader) {
} this.loader = loader;
profile.model=profile.hasSkinUrl()?ssp.model:null;
} }
if(StringUtils.isNoneEmpty(ssp.cape)){
String cape=ssp.cape.replaceAll(USERNAME_REGEX, username); @Override
if(HttpUtil0.isLocal(ssp.cape)){ public void updateSkinSiteProfile(SkinSiteProfile ssp) {
File capeFile=new File(CustomSkinLoader.DATA_DIR,cape); ssp.type = this.loader.getName();
if(capeFile.exists()&&capeFile.isFile()) if (ssp.checkPNG == null) {
profile.capeUrl=HttpTextureUtil.getLocalLegacyFakeUrl(cape, HttpTextureUtil.getHash(cape, capeFile.length(), capeFile.lastModified())); ssp.checkPNG = false;
}else{ }
HttpResponce responce=HttpRequestUtil.makeHttpRequest(new HttpRequest(cape).setUserAgent(ssp.userAgent).setCheckPNG(ssp.checkPNG!=null&&ssp.checkPNG!=false).setLoadContent(false).setCacheTime(90)); if (ssp.model == null) {
if(responce.success) ssp.model = "auto";
profile.capeUrl=HttpTextureUtil.getLegacyFakeUrl(cape); }
//Set texture url when it is empty
//Remote texture url could be changed, it will be auto updated here
if (ssp.skin == null || !HttpUtil0.isLocal(this.getSkinRoot())) {
ssp.skin = this.getSkinRoot();
}
if (ssp.cape == null || !HttpUtil0.isLocal(this.getCapeRoot())) {
ssp.cape = this.getCapeRoot();
}
if (ssp.elytra == null || !HttpUtil0.isLocal(this.getElytraRoot())) {
ssp.elytra = this.getElytraRoot();
} }
} }
if(ModelManager0.isElytraSupported()&&StringUtils.isNoneEmpty(ssp.elytra)){
String elytra=ssp.elytra.replaceAll(USERNAME_REGEX, username); public abstract String getSkinRoot();
if(HttpUtil0.isLocal(ssp.elytra)){
File elytraFile=new File(CustomSkinLoader.DATA_DIR,elytra); public abstract String getCapeRoot();
if(elytraFile.exists()&&elytraFile.isFile())
profile.elytraUrl=HttpTextureUtil.getLocalLegacyFakeUrl(elytra, HttpTextureUtil.getHash(elytra, elytraFile.length(), elytraFile.lastModified())); public abstract String getElytraRoot();
}else{ }
HttpResponce responce=HttpRequestUtil.makeHttpRequest(new HttpRequest(elytra).setUserAgent(ssp.userAgent).setCheckPNG(ssp.checkPNG!=null&&ssp.checkPNG!=false).setLoadContent(false).setCacheTime(90));
if(responce.success) public static class LocalSkin extends LegacyLoader.DefaultProfile {
profile.elytraUrl=HttpTextureUtil.getLegacyFakeUrl(elytra); public LocalSkin(LegacyLoader loader) {
} super(loader);
} }
if(profile.isEmpty()){
CustomSkinLoader.logger.info("Both skin and cape not found."); @Override
public String getName() {
return "LocalSkin";
}
@Override
public int getPriority() {
return 600;
}
@Override
public String getSkinRoot() {
return "LocalSkin/skins/{USERNAME}.png";
}
@Override
public String getCapeRoot() {
return "LocalSkin/capes/{USERNAME}.png";
}
@Override
public String getElytraRoot() {
return "LocalSkin/elytras/{USERNAME}.png";
}
}
// // Minecrack could not load skin correctly
// public static class Minecrack extends LegacyLoader.DefaultProfile {
// public Minecrack(LegacyLoader loader) { super(loader); }
// @Override public String getName() { return "Minecrack"; }
// @Override public int getPriority() { return 600; }
// @Override public String getSkinRoot() { return "http://minecrack.fr.nf/mc/skinsminecrackd/{USERNAME}.png"; }
// @Override public String getCapeRoot() { return "http://minecrack.fr.nf/mc/cloaksminecrackd/{USERNAME}.png"; }
// @Override public String getElytraRoot() { return null; }
// }
public static final String USERNAME_PLACEHOLDER = "{USERNAME}";
public static final String UUID_PLACEHOLDER = "{UUID}";
@Override
public UserProfile loadProfile(SkinSiteProfile ssp, GameProfile gameProfile) {
UserProfile profile = new UserProfile();
//Try to load all textures
getTextureUrl(ssp, gameProfile, ssp.skin, it -> {
profile.skinUrl = it;
profile.model = ssp.model;
});
getTextureUrl(ssp, gameProfile, ssp.cape, it -> profile.capeUrl = it);
getTextureUrl(ssp, gameProfile, ssp.elytra, it -> profile.elytraUrl = it);
if (profile.isEmpty()) {
CustomSkinLoader.logger.info("No texture could be found.");
return null; return null;
} }
return profile; return profile;
} }
private void getTextureUrl(
SkinSiteProfile ssp, GameProfile gameProfile, String baseUrl, Consumer<String> onSuccess) {
//Base URL is empty
if (baseUrl == null || baseUrl.isEmpty()) {
return;
}
String url = expandURL(baseUrl, gameProfile.getName());
//No texture can be loaded
if (url == null) {
return;
}
//Local texture file logic
if (HttpUtil0.isLocal(url)) {
File file = new File(CustomSkinLoader.DATA_DIR, url);
if (file.exists() && file.isFile()) {
String fakeUrl = HttpTextureUtil.getLocalLegacyFakeUrl(url,
HttpTextureUtil.getHash(url, file.length(), file.lastModified()));
onSuccess.accept(fakeUrl);
}
return;
}
//Remote texture logic
HttpRequestUtil.HttpResponce responce = HttpRequestUtil.makeHttpRequest(new HttpRequestUtil.HttpRequest(url)
.setUserAgent(ssp.userAgent).setCheckPNG(ssp.checkPNG != null && ssp.checkPNG).setLoadContent(false));
if (responce.success) {
onSuccess.accept(HttpTextureUtil.getLegacyFakeUrl(url));
}
}
@Override @Override
public boolean compare(SkinSiteProfile ssp0, SkinSiteProfile ssp1) { public boolean compare(SkinSiteProfile ssp0, SkinSiteProfile ssp1) {
return (StringUtils.isNoneEmpty(ssp0.skin)?ssp0.skin.equalsIgnoreCase(ssp1.skin):true) || (StringUtils.isNoneEmpty(ssp0.cape)?ssp0.cape.equalsIgnoreCase(ssp1.cape):true); return Objects.equals(ssp0.skin, ssp1.skin) && Objects.equals(ssp0.cape, ssp1.cape) &&
Objects.equals(ssp0.elytra, ssp1.elytra);
} }
@Override @Override
public String getName() { public String getName() {
return "Legacy"; return "Legacy";
} }
@Override @Override
public void initLocalFolder(SkinSiteProfile ssp) { public void init(SkinSiteProfile ssp) {
if(HttpUtil0.isLocal(ssp.skin)) initFolder(ssp.skin);
initFolder(ssp.skin); initFolder(ssp.cape);
if(HttpUtil0.isLocal(ssp.cape)) initFolder(ssp.elytra);
initFolder(ssp.cape);
if(HttpUtil0.isLocal(ssp.elytra))
initFolder(ssp.elytra);
} }
private void initFolder(String target){
String file=target.replaceAll(USERNAME_REGEX, "init"); @SuppressWarnings("ResultOfMethodCallIgnored")
File folder=new File(CustomSkinLoader.DATA_DIR,file).getParentFile(); private void initFolder(String target) {
if(folder!=null&&!folder.exists()) //Only local skin should init folder
if (!HttpUtil0.isLocal(target)) {
return;
}
String file = target.replace(USERNAME_PLACEHOLDER, "init");
File folder = new File(CustomSkinLoader.DATA_DIR, file).getParentFile();
if (folder != null && !folder.exists()) {
folder.mkdirs(); folder.mkdirs();
}
}
private String expandURL(String url, String username) {
String t = url.replace(USERNAME_PLACEHOLDER, username);
if (!t.contains(UUID_PLACEHOLDER)) {
return t;
}
String uuid = MojangAPILoader.getMojangUuidByUsername(username);
//If Mojang uuid not found, won't load the texture
if (uuid == null) {
return null;
}
return t.replace(UUID_PLACEHOLDER, uuid);
} }
} }
@@ -1,119 +1,223 @@
package customskinloader.loader; package customskinloader.loader;
import java.util.HashMap; import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
import org.apache.commons.codec.Charsets;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
import com.mojang.authlib.GameProfile; import com.mojang.authlib.GameProfile;
import com.mojang.authlib.minecraft.MinecraftProfileTexture; import com.mojang.authlib.minecraft.MinecraftProfileTexture;
import com.mojang.authlib.minecraft.MinecraftSessionService;
import com.mojang.authlib.properties.Property; import com.mojang.authlib.properties.Property;
import com.mojang.authlib.properties.PropertyMap; import com.mojang.authlib.properties.PropertyMap;
import com.mojang.authlib.yggdrasil.response.MinecraftProfilePropertiesResponse; import com.mojang.authlib.yggdrasil.response.MinecraftProfilePropertiesResponse;
import com.mojang.authlib.yggdrasil.response.MinecraftTexturesPayload; import com.mojang.authlib.yggdrasil.response.MinecraftTexturesPayload;
import com.mojang.util.UUIDTypeAdapter; import com.mojang.util.UUIDTypeAdapter;
import customskinloader.CustomSkinLoader; import customskinloader.CustomSkinLoader;
import customskinloader.config.SkinSiteProfile; import customskinloader.config.SkinSiteProfile;
import customskinloader.plugin.ICustomSkinLoaderPlugin;
import customskinloader.profile.ModelManager0; import customskinloader.profile.ModelManager0;
import customskinloader.profile.UserProfile; import customskinloader.profile.UserProfile;
import customskinloader.utils.HttpRequestUtil; import customskinloader.utils.HttpRequestUtil;
import customskinloader.utils.HttpRequestUtil.HttpRequest; import org.apache.commons.codec.Charsets;
import customskinloader.utils.HttpRequestUtil.HttpResponce; import org.apache.commons.codec.binary.Base64;
import customskinloader.utils.MinecraftUtil; import org.apache.commons.lang3.StringUtils;
public class MojangAPILoader implements ProfileLoader.IProfileLoader { public class MojangAPILoader implements ICustomSkinLoaderPlugin, ProfileLoader.IProfileLoader {
public static final MinecraftSessionService defaultSessionService=MinecraftUtil.getSessionService();
@Override @Override
public UserProfile loadProfile(SkinSiteProfile ssp, GameProfile gameProfile) throws Exception { public ProfileLoader.IProfileLoader getProfileLoader() {
Map<MinecraftProfileTexture.Type,MinecraftProfileTexture> map=getTextures(gameProfile); return this;
if(!map.isEmpty()){ }
@Override
public List<IDefaultProfile> getDefaultProfiles() {
return Lists.newArrayList(new Mojang(this));
}
public abstract static class DefaultProfile implements ICustomSkinLoaderPlugin.IDefaultProfile {
protected final MojangAPILoader loader;
public DefaultProfile(MojangAPILoader loader) {
this.loader = loader;
}
@Override
public void updateSkinSiteProfile(SkinSiteProfile ssp) {
ssp.type = this.loader.getName();
ssp.apiRoot = this.getAPIRoot();
ssp.sessionRoot = this.getSessionRoot();
}
public abstract String getAPIRoot();
public abstract String getSessionRoot();
}
public static class Mojang extends MojangAPILoader.DefaultProfile {
public Mojang(MojangAPILoader loader) {
super(loader);
}
@Override
public String getName() {
return "Mojang";
}
@Override
public int getPriority() {
return 100;
}
@Override
public String getAPIRoot() {
return getMojangApiRoot();
}
@Override
public String getSessionRoot() {
return getMojangSessionRoot();
}
}
@Override
public UserProfile loadProfile(SkinSiteProfile ssp, GameProfile gameProfile) {
Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> map = getTextures(gameProfile);
if (!map.isEmpty()) {
CustomSkinLoader.logger.info("Default profile will be used."); CustomSkinLoader.logger.info("Default profile will be used.");
return ModelManager0.toUserProfile(map); return ModelManager0.toUserProfile(map);
} }
String username=gameProfile.getName(); String username = gameProfile.getName();
GameProfile newGameProfile=loadGameProfile(username); GameProfile newGameProfile = loadGameProfile(ssp.apiRoot, username);
if(newGameProfile==null){ if (newGameProfile == null) {
CustomSkinLoader.logger.info("Profile not found.("+username+"'s profile not found.)"); CustomSkinLoader.logger.info("Profile not found.(" + username + "'s profile not found.)");
return null; return null;
} }
newGameProfile=fillGameProfile(newGameProfile); newGameProfile = fillGameProfile(ssp.sessionRoot, newGameProfile);
map=getTextures(newGameProfile); map = getTextures(newGameProfile);
if(!map.isEmpty()){ if (!map.isEmpty()) {
gameProfile.getProperties().putAll(newGameProfile.getProperties()); gameProfile.getProperties().putAll(newGameProfile.getProperties());
return ModelManager0.toUserProfile(map); return ModelManager0.toUserProfile(map);
} }
CustomSkinLoader.logger.info("Profile not found.("+username+" doesn't have skin/cape.)"); CustomSkinLoader.logger.info("Profile not found.(" + username + " doesn't have skin/cape.)");
return null; return null;
} }
//Username -> UUID //Username -> UUID
public static GameProfile loadGameProfile(String username) throws Exception{ public static GameProfile loadGameProfile(String apiRoot, String username) {
//Doc (http://wiki.vg/Mojang_API#Username_-.3E_UUID_at_time) //Doc (https://wiki.vg/Mojang_API#Playernames_-.3E_UUIDs)
HttpResponce responce=HttpRequestUtil.makeHttpRequest(new HttpRequest("https://api.mojang.com/users/profiles/minecraft/"+username).setCacheTime(0)); Gson gson = new GsonBuilder().registerTypeAdapter(UUID.class, new UUIDTypeAdapter()).create();
if(StringUtils.isEmpty(responce.content))
return null;
Gson gson=new GsonBuilder().registerTypeAdapter(UUID.class, new UUIDTypeAdapter()).create(); HttpRequestUtil.HttpResponce responce = HttpRequestUtil.makeHttpRequest(
GameProfile gameProfile=gson.fromJson(responce.content, GameProfile.class); new HttpRequestUtil.HttpRequest(apiRoot + "profiles/minecraft")
.setCacheTime(600).setPayload(gson.toJson(Collections.singletonList(username)))
if(gameProfile.getId()==null) );
if (StringUtils.isEmpty(responce.content)) {
return null; return null;
return new GameProfile(gameProfile.getId(),gameProfile.getName()); }
GameProfile[] profiles = gson.fromJson(responce.content, GameProfile[].class);
if (profiles.length == 0) {
return null;
}
GameProfile gameProfile = profiles[0];
if (gameProfile.getId() == null) {
return null;
}
return new GameProfile(gameProfile.getId(), gameProfile.getName());
} }
//UUID -> Profile
public static GameProfile fillGameProfile(GameProfile profile) throws Exception{
//Doc (http://wiki.vg/Mojang_API#UUID_-.3E_Profile_.2B_Skin.2FCape)
HttpResponce responce=HttpRequestUtil.makeHttpRequest(new HttpRequest("https://sessionserver.mojang.com/session/minecraft/profile/"+UUIDTypeAdapter.fromUUID(profile.getId())).setCacheTime(90));
if(StringUtils.isEmpty(responce.content))
return profile;
Gson gson=new GsonBuilder() /**
* Get Mojang UUID by username.
*
* @param username username to query
* @return UUID in Mojang API style string. Returns {@code null} if username not found in Mojang API.
*/
public static String getMojangUuidByUsername(String username) {
GameProfile profile = loadGameProfile(getMojangApiRoot(), username);
if (profile == null) {
return null;
}
return UUIDTypeAdapter.fromUUID(profile.getId());
}
//UUID -> Profile
public static GameProfile fillGameProfile(String sessionRoot, GameProfile profile) {
//Doc (http://wiki.vg/Mojang_API#UUID_-.3E_Profile_.2B_Skin.2FCape)
HttpRequestUtil.HttpResponce responce = HttpRequestUtil.makeHttpRequest(
new HttpRequestUtil.HttpRequest(sessionRoot + "session/minecraft/profile/"
+ UUIDTypeAdapter.fromUUID(profile.getId())).setCacheTime(90));
if (StringUtils.isEmpty(responce.content)) {
return profile;
}
Gson gson = new GsonBuilder()
.registerTypeAdapter(UUID.class, new UUIDTypeAdapter()) .registerTypeAdapter(UUID.class, new UUIDTypeAdapter())
.registerTypeAdapter(PropertyMap.class, new PropertyMap.Serializer()) .registerTypeAdapter(PropertyMap.class, new PropertyMap.Serializer())
.create(); .create();
MinecraftProfilePropertiesResponse propertiesResponce=gson.fromJson(responce.content, MinecraftProfilePropertiesResponse.class); MinecraftProfilePropertiesResponse propertiesResponce = gson.fromJson(responce.content, MinecraftProfilePropertiesResponse.class);
GameProfile newGameProfile=new GameProfile(propertiesResponce.getId(),propertiesResponce.getName()); GameProfile newGameProfile = new GameProfile(propertiesResponce.getId(), propertiesResponce.getName());
newGameProfile.getProperties().putAll(propertiesResponce.getProperties()); newGameProfile.getProperties().putAll(propertiesResponce.getProperties());
return newGameProfile; return newGameProfile;
} }
public static Map<MinecraftProfileTexture.Type,MinecraftProfileTexture> getTextures(GameProfile gameProfile) throws Exception{ public static Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> getTextures(GameProfile gameProfile) {
if(gameProfile==null) if (gameProfile == null) {
return new HashMap(); return Maps.newHashMap();
Property textureProperty=(Property)Iterables.getFirst(gameProfile.getProperties().get("textures"), null); }
if (textureProperty==null) Property textureProperty = Iterables.getFirst(gameProfile.getProperties().get("textures"), null);
return new HashMap(); if (textureProperty == null) {
String value=textureProperty.getValue(); return Maps.newHashMap();
if(StringUtils.isBlank(value)) }
return new HashMap(); String value = textureProperty.getValue();
String json=new String(Base64.decodeBase64(value),Charsets.UTF_8); if (StringUtils.isBlank(value)) {
Gson gson=new GsonBuilder().registerTypeAdapter(UUID.class,new UUIDTypeAdapter()).create(); return Maps.newHashMap();
MinecraftTexturesPayload result=gson.fromJson(json,MinecraftTexturesPayload.class); }
if (result==null||result.getTextures()==null) String json = new String(Base64.decodeBase64(value), StandardCharsets.UTF_8);
return new HashMap(); Gson gson = new GsonBuilder().registerTypeAdapter(UUID.class, new UUIDTypeAdapter()).create();
MinecraftTexturesPayload result = gson.fromJson(json, MinecraftTexturesPayload.class);
if (result == null || result.getTextures() == null) {
return Maps.newHashMap();
}
return result.getTextures(); return result.getTextures();
} }
@Override @Override
public boolean compare(SkinSiteProfile ssp0, SkinSiteProfile ssp1) { public boolean compare(SkinSiteProfile ssp0, SkinSiteProfile ssp1) {
return true; return (!StringUtils.isNoneEmpty(ssp0.apiRoot) || ssp0.apiRoot.equalsIgnoreCase(ssp1.apiRoot)) ||
(!StringUtils.isNoneEmpty(ssp0.sessionRoot) || ssp0.sessionRoot.equalsIgnoreCase(ssp1.sessionRoot));
} }
@Override @Override
public String getName() { public String getName() {
return "MojangAPI"; return "MojangAPI";
} }
@Override @Override
public void initLocalFolder(SkinSiteProfile ssp) { public void init(SkinSiteProfile ssp) {
//Init default api & session root for Mojang API
if (ssp.apiRoot == null)
ssp.apiRoot = getMojangApiRoot();
if (ssp.sessionRoot == null)
ssp.sessionRoot = getMojangSessionRoot();
}
// Prevent authlib-injector (https://github.com/yushijinhun/authlib-injector) from modifying these strings
private static final String MOJANG_API_ROOT = "https://api{DO_NOT_MODIFY}.mojang.com/";
private static final String MOJANG_SESSION_ROOT = "https://sessionserver{DO_NOT_MODIFY}.mojang.com/";
public static String getMojangApiRoot() {
return MOJANG_API_ROOT.replace("{DO_NOT_MODIFY}", "");
}
public static String getMojangSessionRoot() {
return MOJANG_SESSION_ROOT.replace("{DO_NOT_MODIFY}", "");
} }
} }
@@ -3,32 +3,31 @@ package customskinloader.loader;
import java.util.HashMap; import java.util.HashMap;
import com.mojang.authlib.GameProfile; import com.mojang.authlib.GameProfile;
import customskinloader.CustomSkinLoader;
import customskinloader.config.SkinSiteProfile; import customskinloader.config.SkinSiteProfile;
import customskinloader.plugin.ICustomSkinLoaderPlugin;
import customskinloader.plugin.PluginLoader;
import customskinloader.profile.UserProfile; import customskinloader.profile.UserProfile;
public class ProfileLoader { public class ProfileLoader {
private static final IProfileLoader[] DEFAULT_LOADERS={ public static final HashMap<String, IProfileLoader> LOADERS = initLoaders();
new MojangAPILoader(),
new JsonAPILoader(JsonAPILoader.Type.CustomSkinAPI),
new JsonAPILoader(JsonAPILoader.Type.CustomSkinAPIPlus),
new LegacyLoader(),
new JsonAPILoader(JsonAPILoader.Type.UniSkinAPI)};
public static final HashMap<String,IProfileLoader> LOADERS=initLoaders();
private static HashMap<String, IProfileLoader> initLoaders() { private static HashMap<String, IProfileLoader> initLoaders() {
HashMap<String, IProfileLoader> loaders=new HashMap<String, IProfileLoader>(); HashMap<String, ProfileLoader.IProfileLoader> profileLoaders = new HashMap<>();
for(IProfileLoader loader:DEFAULT_LOADERS){ for (ICustomSkinLoaderPlugin plugin : PluginLoader.PLUGINS) {
loaders.put(loader.getName().toLowerCase(), loader); ProfileLoader.IProfileLoader profileLoader = plugin.getProfileLoader();
if (profileLoader != null) {
profileLoaders.put(profileLoader.getName().toLowerCase(), profileLoader);
CustomSkinLoader.logger.info("Add a profile loader: " + profileLoader.getName());
}
} }
return loaders; return profileLoaders;
} }
public interface IProfileLoader { public interface IProfileLoader {
public UserProfile loadProfile(SkinSiteProfile ssp,GameProfile gameProfile) throws Exception; UserProfile loadProfile(SkinSiteProfile ssp,GameProfile gameProfile) throws Exception;
public boolean compare(SkinSiteProfile ssp0,SkinSiteProfile ssp1); boolean compare(SkinSiteProfile ssp0,SkinSiteProfile ssp1);
public String getName(); String getName();
public void initLocalFolder(SkinSiteProfile ssp); void init(SkinSiteProfile ssp);
} }
} }
@@ -1,25 +1,54 @@
package customskinloader.loader.jsonapi; package customskinloader.loader.jsonapi;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map; import java.util.Map;
import org.apache.commons.lang3.StringUtils; import com.google.common.collect.Lists;
import customskinloader.CustomSkinLoader; import customskinloader.CustomSkinLoader;
import customskinloader.config.SkinSiteProfile; import customskinloader.config.SkinSiteProfile;
import customskinloader.loader.JsonAPILoader.IJsonAPI; import customskinloader.loader.JsonAPILoader;
import customskinloader.plugin.ICustomSkinLoaderPlugin;
import customskinloader.profile.ModelManager0; import customskinloader.profile.ModelManager0;
import customskinloader.profile.ModelManager0.Model;
import customskinloader.profile.UserProfile; import customskinloader.profile.UserProfile;
import customskinloader.utils.HttpTextureUtil; import customskinloader.utils.HttpTextureUtil;
import org.apache.commons.lang3.StringUtils;
public class CustomSkinAPI implements JsonAPILoader.IJsonAPI {
public static class LittleSkin extends JsonAPILoader.DefaultProfile {
public LittleSkin(JsonAPILoader loader) { super(loader); }
@Override public String getName() { return "LittleSkin"; }
@Override public int getPriority() { return 200; }
@Override public String getRoot() { return "https://littleskin.cn/csl/"; }
}
public static class BlessingSkin extends JsonAPILoader.DefaultProfile {
public BlessingSkin(JsonAPILoader loader) { super(loader); }
@Override public String getName() { return "BlessingSkin"; }
@Override public int getPriority() { return 300; }
@Override public String getRoot() { return "https://skin.prinzeugen.net/"; }
}
// // OneSkin has been removed temporarily
// public static class OneSkin extends JsonAPILoader.DefaultProfile {
// public OneSkin(JsonAPILoader loader) { super(loader); }
// @Override public String getName() { return "OneSkin"; }
// @Override public int getPriority() { return 500; }
// @Override public String getRoot() { return "http://fleey.cn/skin/skin_user/skin_json.php/"; }
// }
public class CustomSkinAPI implements IJsonAPI {
private static final String TEXTURES="textures/"; private static final String TEXTURES="textures/";
private static final String SUFFIX=".json"; private static final String SUFFIX=".json";
@Override
public List<ICustomSkinLoaderPlugin.IDefaultProfile> getDefaultProfiles(JsonAPILoader loader) {
return Lists.newArrayList(new LittleSkin(loader), new BlessingSkin(loader));
}
@Override @Override
public String toJsonUrl(String root, String username) { public String toJsonUrl(String root, String username) {
return new StringBuilder().append(root).append(username).append(SUFFIX).toString(); return root + username + SUFFIX;
} }
@Override @Override
@@ -43,7 +72,7 @@ public class CustomSkinAPI implements IJsonAPI {
p.elytraUrl=HttpTextureUtil.getLocalFakeUrl(p.elytraUrl); p.elytraUrl=HttpTextureUtil.getLocalFakeUrl(p.elytraUrl);
} }
Map<String,String> textures=new LinkedHashMap<String,String>(); Map<String,String> textures=new LinkedHashMap<>();
if(profile.skins!=null) if(profile.skins!=null)
textures.putAll(profile.skins); textures.putAll(profile.skins);
if(profile.textures!=null) if(profile.textures!=null)
@@ -53,7 +82,7 @@ public class CustomSkinAPI implements IJsonAPI {
boolean hasSkin=false; boolean hasSkin=false;
for(String model:textures.keySet()){ for(String model:textures.keySet()){
Model enumModel=ModelManager0.getEnumModel(model); ModelManager0.Model enumModel=ModelManager0.getEnumModel(model);
if(enumModel==null||StringUtils.isEmpty(textures.get(model))) if(enumModel==null||StringUtils.isEmpty(textures.get(model)))
continue; continue;
if(ModelManager0.isSkin(enumModel)) if(ModelManager0.isSkin(enumModel))
@@ -69,7 +98,7 @@ public class CustomSkinAPI implements IJsonAPI {
return p; return p;
} }
private class CustomSkinAPIProfile{ private static class CustomSkinAPIProfile{
public String username; public String username;
public LinkedHashMap<String,String> textures; public LinkedHashMap<String,String> textures;
@@ -1,20 +1,19 @@
package customskinloader.loader.jsonapi; package customskinloader.loader.jsonapi;
import java.io.File; import java.io.File;
import java.util.List;
import java.util.UUID; import java.util.UUID;
import org.apache.commons.io.FileUtils; import com.google.common.collect.Lists;
import com.google.gson.Gson; import com.google.gson.Gson;
import customskinloader.CustomSkinLoader; import customskinloader.CustomSkinLoader;
import customskinloader.config.SkinSiteProfile; import customskinloader.config.SkinSiteProfile;
import customskinloader.loader.JsonAPILoader; import customskinloader.loader.JsonAPILoader;
import customskinloader.loader.JsonAPILoader.IJsonAPI; import customskinloader.plugin.ICustomSkinLoaderPlugin;
import customskinloader.profile.UserProfile;
import customskinloader.utils.MinecraftUtil; import customskinloader.utils.MinecraftUtil;
import org.apache.commons.io.FileUtils;
public class CustomSkinAPIPlus implements IJsonAPI { public class CustomSkinAPIPlus extends CustomSkinAPI {
private static String clientID=null; private static String clientID=null;
public CustomSkinAPIPlus(){ public CustomSkinAPIPlus(){
@@ -22,34 +21,28 @@ public class CustomSkinAPIPlus implements IJsonAPI {
if(clientIDFile.isFile()) if(clientIDFile.isFile())
try{ try{
clientID=FileUtils.readFileToString(clientIDFile); clientID=FileUtils.readFileToString(clientIDFile, "UTF-8");
}catch(Exception e){ }catch(Exception e){
e.printStackTrace(); e.printStackTrace();
} }
if(clientID==null){ if(clientID==null){
clientID=UUID.randomUUID().toString(); clientID=UUID.randomUUID().toString();
try { try {
FileUtils.write(clientIDFile, clientID); FileUtils.write(clientIDFile, clientID, "UTF-8");
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
} }
@Override @Override
public String toJsonUrl(String root, String username) { public List<ICustomSkinLoaderPlugin.IDefaultProfile> getDefaultProfiles(JsonAPILoader loader) {
return JsonAPILoader.Type.CustomSkinAPI.jsonAPI.toJsonUrl(root, username); return Lists.newArrayList();
} }
@Override @Override
public String getPayload(SkinSiteProfile ssp) { public String getPayload(SkinSiteProfile ssp) {
if(ssp.privacy==null) return new Gson().toJson(new CustomSkinAPIPlusPayload());
ssp.privacy=new CustomSkinAPIPlusPrivacy();
return new Gson().toJson(new CustomSkinAPIPlusPayload(ssp.privacy));
}
@Override
public UserProfile toUserProfile(String root, String json, boolean local) {
return JsonAPILoader.Type.CustomSkinAPI.jsonAPI.toUserProfile(root, json, local);
} }
@Override @Override
@@ -58,25 +51,15 @@ public class CustomSkinAPIPlus implements IJsonAPI {
} }
public static class CustomSkinAPIPlusPayload{ public static class CustomSkinAPIPlusPayload{
public String gameVersion;//minecraft version String gameVersion;//minecraft version
public String modVersion;//mod version String modVersion;//mod version
public String serverAddress;//ip:port String serverAddress;//ip:port
public String clientID;//Minecraft Client ID String clientID;//Minecraft Client ID
public CustomSkinAPIPlusPayload(CustomSkinAPIPlusPrivacy privacy){ CustomSkinAPIPlusPayload(){
if(privacy.gameVersion) gameVersion = MinecraftUtil.getMinecraftMainVersion();
gameVersion=MinecraftUtil.getMinecraftMainVersion(); modVersion = CustomSkinLoader.CustomSkinLoader_VERSION;
if(privacy.modVersion) serverAddress = MinecraftUtil.isLanServer() ? null : MinecraftUtil.getStandardServerAddress();
modVersion=CustomSkinLoader.CustomSkinLoader_VERSION; clientID = CustomSkinAPIPlus.clientID;
if(privacy.serverAddress)
serverAddress=MinecraftUtil.isLanServer()?null:MinecraftUtil.getStandardServerAddress();
if(privacy.clientID)
clientID=CustomSkinAPIPlus.clientID;
} }
} }
public static class CustomSkinAPIPlusPrivacy{
public boolean gameVersion=true;
public boolean modVersion=true;
public boolean serverAddress=true;
public boolean clientID=true;
}
} }
@@ -0,0 +1,57 @@
package customskinloader.loader.jsonapi;
import java.util.List;
import java.util.Map;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.mojang.authlib.minecraft.MinecraftProfileTexture;
import customskinloader.config.SkinSiteProfile;
import customskinloader.loader.JsonAPILoader;
import customskinloader.plugin.ICustomSkinLoaderPlugin;
import customskinloader.profile.ModelManager0;
import customskinloader.profile.UserProfile;
public class ElyByAPI implements JsonAPILoader.IJsonAPI {
public static class ElyBy extends JsonAPILoader.DefaultProfile {
public ElyBy(JsonAPILoader loader) { super(loader); }
@Override public String getName() { return "ElyBy"; }
@Override public int getPriority() { return 400; }
@Override public String getRoot() { return "http://skinsystem.ely.by/textures/"; }
}
public static class TLauncher extends JsonAPILoader.DefaultProfile {
public TLauncher(JsonAPILoader loader) { super(loader); }
@Override public String getName() { return "TLauncher"; }
@Override public int getPriority() { return 550; }
@Override public String getRoot() { return "https://auth.tlauncher.org/skin/profile/texture/login/"; }
}
@Override
public List<ICustomSkinLoaderPlugin.IDefaultProfile> getDefaultProfiles(JsonAPILoader loader) {
return Lists.newArrayList(new ElyBy(loader), new TLauncher(loader));
}
@Override
public String toJsonUrl(String root, String username) {
return root + username;
}
@Override
public UserProfile toUserProfile(String root, String json, boolean local) {
Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> result = new Gson().fromJson(json, new TypeToken<Map<MinecraftProfileTexture.Type, MinecraftProfileTexture>>() { }.getType());
return ModelManager0.toUserProfile(result);
}
@Override
public String getPayload(SkinSiteProfile ssp) {
return null;
}
@Override
public String getName() {
return "ElyByAPI";
}
}
@@ -0,0 +1,56 @@
package customskinloader.loader.jsonapi;
import java.util.List;
import java.util.Map;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.mojang.authlib.minecraft.MinecraftProfileTexture;
import customskinloader.config.SkinSiteProfile;
import customskinloader.loader.JsonAPILoader;
import customskinloader.plugin.ICustomSkinLoaderPlugin;
import customskinloader.profile.ModelManager0;
import customskinloader.profile.UserProfile;
public class GlitchlessAPI implements JsonAPILoader.IJsonAPI {
public static class GlitchlessGames extends JsonAPILoader.DefaultProfile {
public GlitchlessGames(JsonAPILoader loader) { super(loader); }
@Override public String getName() { return "GlitchlessGames"; }
@Override public int getPriority() { return 700; }
@Override public String getRoot() { return "https://games.glitchless.ru/api/minecraft/users/profiles/textures/?nickname="; }
}
@Override
public List<ICustomSkinLoaderPlugin.IDefaultProfile> getDefaultProfiles(JsonAPILoader loader) {
return Lists.newArrayList(new GlitchlessGames(loader));
}
@Override
public String toJsonUrl(String root, String username) {
return root + username;
}
@Override
public UserProfile toUserProfile(String root, String json, boolean local) {
GlitchlessApiResponse result = new Gson().fromJson(json, GlitchlessApiResponse.class);
if (!result.textures.containsKey(MinecraftProfileTexture.Type.SKIN))
return null;
return ModelManager0.toUserProfile(result.textures);
}
@Override
public String getPayload(SkinSiteProfile ssp) {
return null;
}
@Override
public String getName() {
return "GlitchlessAPI";
}
public static class GlitchlessApiResponse {
protected Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> textures;
}
}
@@ -0,0 +1,110 @@
package customskinloader.loader.jsonapi;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.mojang.authlib.minecraft.MinecraftProfileTexture;
import customskinloader.CustomSkinLoader;
import customskinloader.Logger;
import customskinloader.config.SkinSiteProfile;
import customskinloader.loader.JsonAPILoader;
import customskinloader.loader.MojangAPILoader;
import customskinloader.plugin.ICustomSkinLoaderPlugin;
import customskinloader.profile.ModelManager0;
import customskinloader.profile.UserProfile;
import customskinloader.utils.HttpTextureUtil;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.util.List;
import java.util.Map;
public class MinecraftCapesAPI implements JsonAPILoader.IJsonAPI {
public static class MinecraftCapes extends JsonAPILoader.DefaultProfile {
public MinecraftCapes(JsonAPILoader loader) {
super(loader);
}
@Override
public String getName() {
return "MinecraftCapes";
}
@Override
public int getPriority() {
return 800;
}
@Override
public String getRoot() {
return "https://minecraftcapes.net/profile/";
}
}
@Override
public List<ICustomSkinLoaderPlugin.IDefaultProfile> getDefaultProfiles(JsonAPILoader loader) {
return Lists.newArrayList(new MinecraftCapes(loader));
}
@Override
public String toJsonUrl(String root, String username) {
String uuid = MojangAPILoader.getMojangUuidByUsername(username);
//If uuid cannot be found, we won't load profile in this API.
if (uuid == null) {
return null;
}
//API url is `${root}${uuid}`
return root + uuid;
}
@Override
public UserProfile toUserProfile(String root, String json, boolean local) {
MinecraftCapesApiResponse result = new Gson().fromJson(json, MinecraftCapesApiResponse.class);
if (result.textures == null || result.textures.cape == null) {
return null;
}
String capeBase64 = result.textures.cape;
byte[] capeBytes = Base64.decodeBase64(capeBase64);
String hash = HttpTextureUtil.getHash(capeBytes);
File cacheFile = HttpTextureUtil.getCacheFile(hash);
String fakeUrl = HttpTextureUtil.getBase64FakeUrl(hash);
//Save base64 image to cache file
try {
FileUtils.writeByteArrayToFile(cacheFile, capeBytes);
CustomSkinLoader.logger.info("Saved base64 image to " + cacheFile);
} catch (Exception e) {
CustomSkinLoader.logger.warning("Error parsing base64 image: " + capeBase64);
return null;
}
UserProfile profile = new UserProfile();
profile.capeUrl = fakeUrl;
return profile;
}
@Override
public String getPayload(SkinSiteProfile ssp) {
return null;
}
@Override
public String getName() {
return "MinecraftCapesAPI";
}
public static class MinecraftCapesApiResponse {
public boolean animatedCape;
public boolean capeGlint;
public boolean upsideDown;
public MinecraftCapesApiTexture textures;
public static class MinecraftCapesApiTexture {
public String cape;
public String ears;
}
}
}
@@ -3,23 +3,36 @@ package customskinloader.loader.jsonapi;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.apache.commons.lang3.StringUtils; import com.google.common.collect.Lists;
import customskinloader.CustomSkinLoader; import customskinloader.CustomSkinLoader;
import customskinloader.config.SkinSiteProfile; import customskinloader.config.SkinSiteProfile;
import customskinloader.loader.JsonAPILoader.IJsonAPI; import customskinloader.loader.JsonAPILoader;
import customskinloader.plugin.ICustomSkinLoaderPlugin;
import customskinloader.profile.ModelManager0; import customskinloader.profile.ModelManager0;
import customskinloader.profile.UserProfile; import customskinloader.profile.UserProfile;
import customskinloader.profile.ModelManager0.Model;
import customskinloader.utils.HttpTextureUtil; import customskinloader.utils.HttpTextureUtil;
import org.apache.commons.lang3.StringUtils;
public class UniSkinAPI implements JsonAPILoader.IJsonAPI {
public static class SkinMe extends JsonAPILoader.DefaultProfile {
public SkinMe(JsonAPILoader loader) { super(loader); }
@Override public String getName() { return "SkinMe"; }
@Override public int getPriority() { return 500; }
@Override public String getRoot() { return "http://www.skinme.cc/uniskin/"; }
}
public class UniSkinAPI implements IJsonAPI {
private static final String TEXTURES="textures/"; private static final String TEXTURES="textures/";
private static final String SUFFIX=".json"; private static final String SUFFIX=".json";
@Override
public List<ICustomSkinLoaderPlugin.IDefaultProfile> getDefaultProfiles(JsonAPILoader loader) {
return Lists.newArrayList(new SkinMe(loader));
}
@Override @Override
public String toJsonUrl(String root, String username) { public String toJsonUrl(String root, String username) {
return new StringBuilder().append(root).append(username).append(SUFFIX).toString(); return root + username + SUFFIX;
} }
@Override @Override
@@ -40,7 +53,7 @@ public class UniSkinAPI implements IJsonAPI {
boolean hasSkin=false; boolean hasSkin=false;
for(String model:profile.model_preference){ for(String model:profile.model_preference){
Model enumModel=ModelManager0.getEnumModel(model); ModelManager0.Model enumModel=ModelManager0.getEnumModel(model);
if(enumModel==null||StringUtils.isEmpty(profile.skins.get(model))) if(enumModel==null||StringUtils.isEmpty(profile.skins.get(model)))
continue; continue;
if(ModelManager0.isSkin(enumModel)) if(ModelManager0.isSkin(enumModel))
@@ -0,0 +1,35 @@
package customskinloader.plugin;
import java.util.List;
import customskinloader.config.SkinSiteProfile;
import customskinloader.loader.ProfileLoader;
public interface ICustomSkinLoaderPlugin {
/**
* @return return a non-null value if need to add a new profile loader, otherwise return null.
*/
ProfileLoader.IProfileLoader getProfileLoader();
/**
* @return the default implementations which import by {@link ICustomSkinLoaderPlugin#getProfileLoader()}.
*/
List<IDefaultProfile> getDefaultProfiles();
interface IDefaultProfile {
/**
* @return the name of {@link SkinSiteProfile#name}.
*/
String getName();
/**
* @return the lower the number, the first to load.
*/
int getPriority();
/**
* Complete the {@link SkinSiteProfile} from config and write to config.
*/
void updateSkinSiteProfile(SkinSiteProfile ssp);
}
}
@@ -0,0 +1,54 @@
package customskinloader.plugin;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.ServiceLoader;
import com.google.common.collect.Lists;
import customskinloader.CustomSkinLoader;
import customskinloader.loader.JsonAPILoader;
import customskinloader.loader.LegacyLoader;
import customskinloader.loader.MojangAPILoader;
import customskinloader.loader.jsonapi.*;
import org.apache.commons.io.FileUtils;
public class PluginLoader {
public static final ICustomSkinLoaderPlugin[] DEFAULT_PLUGINS = new ICustomSkinLoaderPlugin[]{
new MojangAPILoader(),
new LegacyLoader(),
new JsonAPILoader(new CustomSkinAPI()),
new JsonAPILoader(new CustomSkinAPIPlus()),
new JsonAPILoader(new UniSkinAPI()),
new JsonAPILoader(new ElyByAPI()),
new JsonAPILoader(new GlitchlessAPI()),
new JsonAPILoader(new MinecraftCapesAPI())
};
public static final ArrayList<ICustomSkinLoaderPlugin> PLUGINS = loadPlugins();
private static ArrayList<ICustomSkinLoaderPlugin> loadPlugins() {
File pluginsDir = new File(CustomSkinLoader.DATA_DIR, "Plugins");
ArrayList<URL> urls = new ArrayList<>();
if (!pluginsDir.isDirectory()) {
//noinspection ResultOfMethodCallIgnored
pluginsDir.mkdirs();
} else {
for (File plugin : FileUtils.listFiles(pluginsDir, new String[]{"jar", "zip"}, false)) {
try {
urls.add(plugin.toURI().toURL());
CustomSkinLoader.logger.info("Found a jar or zip file: " + plugin.getName());
} catch (MalformedURLException ignored) {
}
}
}
ArrayList<ICustomSkinLoaderPlugin> plugins = Lists.newArrayList(DEFAULT_PLUGINS);
ServiceLoader<ICustomSkinLoaderPlugin> sl = ServiceLoader.load(ICustomSkinLoaderPlugin.class, new URLClassLoader(urls.toArray(new URL[0]), PluginLoader.class.getClassLoader()));
for (ICustomSkinLoaderPlugin plugin : sl) {
plugins.add(plugin);
}
return plugins;
}
}
@@ -1,12 +1,10 @@
package customskinloader.profile; package customskinloader.profile;
import java.io.File; import java.io.File;
import java.util.ArrayList; import java.util.*;
import java.util.HashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import com.google.common.collect.Lists;
import org.apache.commons.codec.Charsets; import org.apache.commons.codec.Charsets;
import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
@@ -41,38 +39,39 @@ public class DynamicSkullManager {
public long startTime; public long startTime;
public int period; public int period;
} }
private Map<GameProfile,SkullTexture> dynamicTextures=new HashMap<GameProfile,SkullTexture>(); private Map<GameProfile, SkullTexture> dynamicTextures = new ConcurrentHashMap<>();
private Map<GameProfile,Map<Type,MinecraftProfileTexture>> staticTextures=new HashMap<GameProfile,Map<Type,MinecraftProfileTexture>>(); private Map<GameProfile, Map<Type, MinecraftProfileTexture>> staticTextures = new ConcurrentHashMap<>();
private List<GameProfile> loadingList=new ArrayList<GameProfile>(); private List<GameProfile> loadingList=new ArrayList<GameProfile>();
private void parseGameProfile(GameProfile profile){ private void parseGameProfile(GameProfile profile){
Property textureProperty=(Property)Iterables.getFirst(profile.getProperties().get("textures"), null); Property textureProperty = Iterables.getFirst(profile.getProperties().get("textures"), null);
if (textureProperty==null){ if (textureProperty==null){
staticTextures.put(profile, new HashMap()); staticTextures.put(profile, Maps.<Type, MinecraftProfileTexture>newHashMap());
return; return;
} }
String value=textureProperty.getValue(); String value=textureProperty.getValue();
if(StringUtils.isBlank(value)){ if(StringUtils.isBlank(value)){
staticTextures.put(profile, new HashMap()); staticTextures.put(profile, Maps.<Type, MinecraftProfileTexture>newHashMap());
return; return;
} }
String json=new String(Base64.decodeBase64(value),Charsets.UTF_8); @SuppressWarnings("deprecation") String json = new String(Base64.decodeBase64(value), Charsets.UTF_8);
Gson gson=new GsonBuilder().registerTypeAdapter(UUID.class,new UUIDTypeAdapter()).create(); Gson gson=new GsonBuilder().registerTypeAdapter(UUID.class,new UUIDTypeAdapter()).create();
SkullTexture result=gson.fromJson(json,SkullTexture.class); SkullTexture result=gson.fromJson(json,SkullTexture.class);
if(result==null){ if(result==null){
staticTextures.put(profile, new HashMap()); staticTextures.put(profile, Maps.<Type, MinecraftProfileTexture>newHashMap());
return; return;
} }
staticTextures.put(profile, (result.textures==null||!result.textures.containsKey(Type.SKIN))?new HashMap():parseTextures(result.textures)); staticTextures.put(profile, (result.textures==null || !result.textures.containsKey(Type.SKIN)) ?
Maps.<Type, MinecraftProfileTexture>newHashMap() : parseTextures(result.textures));
if(StringUtils.isNotEmpty(result.index)){ if(StringUtils.isNotEmpty(result.index)){
File indexFile=new File(CustomSkinLoader.DATA_DIR,result.index); File indexFile=new File(CustomSkinLoader.DATA_DIR,result.index);
try{ try{
String index=FileUtils.readFileToString(indexFile, Charsets.UTF_8); String index=FileUtils.readFileToString(indexFile, "UTF-8");
if(StringUtils.isNotEmpty(index)){ if(StringUtils.isNotEmpty(index)){
ArrayList<String> skins=CustomSkinLoader.GSON.fromJson(index, ArrayList.class); String[] skins = CustomSkinLoader.GSON.fromJson(index, String[].class);
if(skins!=null&&!skins.isEmpty()) if(skins != null && skins.length != 0)
result.skins=skins; result.skins = Lists.newArrayList(skins);
} }
}catch(Exception e){ }catch(Exception e){
CustomSkinLoader.logger.warning("Exception occurs while parsing index file: "+e.toString()); CustomSkinLoader.logger.warning("Exception occurs while parsing index file: "+e.toString());
@@ -96,7 +95,6 @@ public class DynamicSkullManager {
}else{ }else{
//Could not find skin //Could not find skin
result.skins.remove(i--); result.skins.remove(i--);
continue;
} }
}else{ }else{
//Online Skin //Online Skin
@@ -104,7 +102,6 @@ public class DynamicSkullManager {
if(!responce.success){ if(!responce.success){
//Could not load skin //Could not load skin
result.skins.remove(i--); result.skins.remove(i--);
continue;
} }
} }
} }
@@ -130,7 +127,7 @@ public class DynamicSkullManager {
return textures; return textures;
File skinFile=new File(CustomSkinLoader.DATA_DIR,skinUrl); File skinFile=new File(CustomSkinLoader.DATA_DIR,skinUrl);
if(!skinFile.isFile()) if(!skinFile.isFile())
return new HashMap(); return Maps.newHashMap();
textures.put(Type.SKIN, ModelManager0.getProfileTexture(HttpTextureUtil.getLocalFakeUrl(skinUrl), null)); textures.put(Type.SKIN, ModelManager0.getProfileTexture(HttpTextureUtil.getLocalFakeUrl(skinUrl), null));
return textures; return textures;
} }
@@ -139,7 +136,7 @@ public class DynamicSkullManager {
if(staticTextures.get(profile)!=null) if(staticTextures.get(profile)!=null)
return staticTextures.get(profile); return staticTextures.get(profile);
if(loadingList.contains(profile)) if(loadingList.contains(profile))
return new HashMap(); return Maps.newHashMap();
if(dynamicTextures.containsKey(profile)){ if(dynamicTextures.containsKey(profile)){
SkullTexture texture=dynamicTextures.get(profile); SkullTexture texture=dynamicTextures.get(profile);
long time=System.currentTimeMillis()-texture.startTime; long time=System.currentTimeMillis()-texture.startTime;
@@ -158,6 +155,6 @@ public class DynamicSkullManager {
}; };
loadThread.setName("Skull "+profile.hashCode()); loadThread.setName("Skull "+profile.hashCode());
loadThread.start(); loadThread.start();
return new HashMap(); return Maps.newHashMap();
} }
} }
@@ -13,97 +13,107 @@ import com.mojang.authlib.minecraft.MinecraftProfileTexture.Type;
* Model Manager for 1.8 and higher. * Model Manager for 1.8 and higher.
* A manager to check if model is available. * A manager to check if model is available.
* It is the only class in package 'customskinloader' which has differences in different Minecraft version. * It is the only class in package 'customskinloader' which has differences in different Minecraft version.
*
* @since 13.1 * @since 13.1
*/ */
public class ModelManager0 { public class ModelManager0 {
public static enum Model{ public enum Model {
SKIN_DEFAULT, SKIN_DEFAULT,
SKIN_SLIM, SKIN_SLIM,
CAPE, CAPE,
ELYTRA ELYTRA
} }
private static HashMap<String,Model> models=new HashMap<String,Model>();
private static Type typeElytra=null; private static HashMap<String, Model> models = new HashMap<String, Model>();
static{ private static Type typeElytra = null;
for(Type type:Type.values()){
if(type.ordinal()==2)//ELYTRA static {
typeElytra=type; for (Type type : Type.values()) {
if (type.ordinal() == 2)//ELYTRA
typeElytra = type;
} }
models.put("default", Model.SKIN_DEFAULT); models.put("default", Model.SKIN_DEFAULT);
models.put("slim", Model.SKIN_SLIM); models.put("slim", Model.SKIN_SLIM);
models.put("cape", Model.CAPE); models.put("cape", Model.CAPE);
if(typeElytra!=null) if (typeElytra != null) {
models.put("elytra", Model.ELYTRA); models.put("elytra", Model.ELYTRA);
models.put("elytron", Model.ELYTRA);
}
} }
/** /**
* Get enum for the model. * Get enum for the model.
*
* @param model - string model * @param model - string model
* @since 14.5 * @since 14.5
*/ */
public static Model getEnumModel(String model){ public static Model getEnumModel(String model) {
return models.get(model); return models.get(model);
} }
/** /**
* Check if model is skin. * Check if model is skin.
*
* @since 14.5 * @since 14.5
* */ */
public static boolean isSkin(Model model){ public static boolean isSkin(Model model) {
return model==Model.SKIN_DEFAULT||model==Model.SKIN_SLIM; return model == Model.SKIN_DEFAULT || model == Model.SKIN_SLIM;
} }
/** /**
* Check if elytra is supported. * Check if elytra is supported.
*
* @since 14.5 * @since 14.5
*/ */
public static boolean isElytraSupported(){ public static boolean isElytraSupported() {
return typeElytra!=null; return typeElytra != null;
} }
/** /**
* Parse hashMapProfile to UserProfile * Parse hashMapProfile to UserProfile
*
* @param profile - hashMapProfile (HashMap<String,MinecraftProfileTexture>) * @param profile - hashMapProfile (HashMap<String,MinecraftProfileTexture>)
* @return profile - UserProfile instance * @return profile - UserProfile instance
* @since 13.1 * @since 13.1
*/ */
public static UserProfile toUserProfile(Map profile){ public static UserProfile toUserProfile(Map<Type, MinecraftProfileTexture> profile) {
UserProfile userProfile=new UserProfile(); UserProfile userProfile = new UserProfile();
if(profile==null) if (profile == null)
return userProfile; return userProfile;
MinecraftProfileTexture skin=(MinecraftProfileTexture)profile.get(Type.SKIN); MinecraftProfileTexture skin = profile.get(Type.SKIN);
userProfile.skinUrl= skin==null?null:skin.getUrl();//Avoid NullPointerException userProfile.skinUrl = skin == null ? null : skin.getUrl();//Avoid NullPointerException
userProfile.model= skin==null?null:skin.getMetadata("model"); userProfile.model = skin == null ? null : skin.getMetadata("model");
if(StringUtils.isEmpty(userProfile.model)) if (StringUtils.isEmpty(userProfile.model))
userProfile.model="default"; userProfile.model = "default";
MinecraftProfileTexture cape=(MinecraftProfileTexture)profile.get(Type.CAPE); MinecraftProfileTexture cape = profile.get(Type.CAPE);
userProfile.capeUrl= cape==null?null:cape.getUrl(); userProfile.capeUrl = cape == null ? null : cape.getUrl();
return userProfile; return userProfile;
} }
/** /**
* Parse UserProfile to hashMapProfile * Parse UserProfile to hashMapProfile
*
* @param profile - UserProfile instance * @param profile - UserProfile instance
* @return profile - hashMapProfile (HashMap<String,MinecraftProfileTexture>) * @return profile - hashMapProfile (HashMap<String,MinecraftProfileTexture>)
* @since 13.1 * @since 13.1
*/ */
public static Map fromUserProfile(UserProfile profile){ public static Map<Type, MinecraftProfileTexture> fromUserProfile(UserProfile profile) {
Map map=Maps.newHashMap(); Map<Type, MinecraftProfileTexture> map = Maps.newHashMap();
if(profile==null) if (profile == null)
return map; return map;
if(profile.skinUrl!=null){ if (profile.skinUrl != null) {
Map metadata=null; Map<String, String> metadata = null;
if(profile.model!=null&&profile.model.equals("slim")){ if ("slim".equals(profile.model) || "auto".equals(profile.model)) {
metadata = Maps.newHashMap(); metadata = Maps.newHashMap();
metadata.put("model", "slim"); metadata.put("model", profile.model);
} }
map.put(Type.SKIN, getProfileTexture(profile.skinUrl,metadata)); map.put(Type.SKIN, getProfileTexture(profile.skinUrl, metadata));
} }
if(profile.capeUrl!=null) if (profile.capeUrl != null)
map.put(Type.CAPE, getProfileTexture(profile.capeUrl,null)); map.put(Type.CAPE, getProfileTexture(profile.capeUrl, null));
if(typeElytra!=null && profile.elytraUrl!=null) if (typeElytra != null && profile.elytraUrl != null)
map.put(typeElytra, getProfileTexture(profile.elytraUrl,null)); map.put(typeElytra, getProfileTexture(profile.elytraUrl, null));
return map; return map;
} }
@@ -111,11 +121,11 @@ public class ModelManager0 {
* Parse url to MinecraftProfileTexture * Parse url to MinecraftProfileTexture
* *
* @param url - textureUrl * @param url - textureUrl
* metadata - metadata * @param metadata - metadata
* @return MinecraftProfileTexture * @return MinecraftProfileTexture
* @since 14.5 * @since 14.5
*/ */
public static MinecraftProfileTexture getProfileTexture(String url,Map metadata){ public static MinecraftProfileTexture getProfileTexture(String url, Map<String, String> metadata) {
return new MinecraftProfileTexture(url,metadata); return new MinecraftProfileTexture(url, metadata);
} }
} }
@@ -1,21 +1,26 @@
package customskinloader.profile; package customskinloader.profile;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.util.Deque;
import java.io.FileOutputStream; import java.util.Map;
import java.util.HashMap; import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.io.IOUtils; import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.function.Consumer;
import com.mojang.authlib.minecraft.MinecraftProfileTexture;
import customskinloader.CustomSkinLoader; import customskinloader.CustomSkinLoader;
import customskinloader.utils.TimeUtil; import customskinloader.utils.TimeUtil;
import org.apache.commons.io.FileUtils;
public class ProfileCache { public class ProfileCache {
public static File PROFILE_CACHE_DIR=new File(CustomSkinLoader.DATA_DIR,"ProfileCache"); public static File PROFILE_CACHE_DIR=new File(CustomSkinLoader.DATA_DIR,"ProfileCache");
private HashMap<String,CachedProfile> cachedProfiles=new HashMap<String,CachedProfile>(); private Map<String, CachedProfile> cachedProfiles = new ConcurrentHashMap<>();
private HashMap<String,UserProfile> localProfiles=new HashMap<String,UserProfile>(); private Map<String, UserProfile> localProfiles = new ConcurrentHashMap<>();
private Map<String, Deque<Consumer<Map<MinecraftProfileTexture.Type, MinecraftProfileTexture>>>> profileLoaders = new ConcurrentHashMap<>();
@SuppressWarnings("ResultOfMethodCallIgnored")
public ProfileCache(){ public ProfileCache(){
if(!PROFILE_CACHE_DIR.exists()) if(!PROFILE_CACHE_DIR.exists())
PROFILE_CACHE_DIR.mkdir(); PROFILE_CACHE_DIR.mkdir();
@@ -24,13 +29,17 @@ public class ProfileCache {
public boolean isExist(String username){ public boolean isExist(String username){
return cachedProfiles.containsKey(username.toLowerCase()); return cachedProfiles.containsKey(username.toLowerCase());
} }
public boolean isLoading(String username) {
CachedProfile cp=cachedProfiles.get(username.toLowerCase());
return cp != null && cp.loading;
}
public boolean isReady(String username){ public boolean isReady(String username){
CachedProfile cp=cachedProfiles.get(username.toLowerCase()); CachedProfile cp=cachedProfiles.get(username.toLowerCase());
return cp==null?false:(cp.loading||cp.expiryTime>TimeUtil.getCurrentUnixTimestamp()); return cp != null && (cp.loading || cp.expiryTime > TimeUtil.getCurrentUnixTimestamp());
} }
public boolean isExpired(String username){ public boolean isExpired(String username){
CachedProfile cp=cachedProfiles.get(username.toLowerCase()); CachedProfile cp=cachedProfiles.get(username.toLowerCase());
return cp==null?true:(cp.expiryTime<=TimeUtil.getCurrentUnixTimestamp()); return cp == null || (cp.expiryTime <= TimeUtil.getCurrentUnixTimestamp());
} }
public UserProfile getProfile(String username){ public UserProfile getProfile(String username){
@@ -44,6 +53,13 @@ public class ProfileCache {
return localProfiles.get(username.toLowerCase()); return localProfiles.get(username.toLowerCase());
return loadLocalProfile(username); return loadLocalProfile(username);
} }
public Optional<Consumer<Map<MinecraftProfileTexture.Type, MinecraftProfileTexture>>> getLastLoader(String username) {
Deque<Consumer<Map<MinecraftProfileTexture.Type, MinecraftProfileTexture>>> deque = this.profileLoaders.get(username);
if (deque != null) {
return Optional.ofNullable(deque.pollLast());
}
return Optional.empty();
}
public void setLoading(String username,boolean loading){ public void setLoading(String username,boolean loading){
getCachedProfile(username).loading=loading; getCachedProfile(username).loading=loading;
@@ -54,11 +70,15 @@ public class ProfileCache {
public void updateCache(String username,UserProfile profile,boolean saveLocalProfile){ public void updateCache(String username,UserProfile profile,boolean saveLocalProfile){
CachedProfile cp=getCachedProfile(username); CachedProfile cp=getCachedProfile(username);
cp.profile=profile; cp.profile=profile;
cp.expiryTime=TimeUtil.getUnixTimestampRandomDelay(CustomSkinLoader.config.cacheExpiry); cp.expiryTime=TimeUtil.getUnixTimestamp(CustomSkinLoader.config.cacheExpiry);
if(!saveLocalProfile) if(!saveLocalProfile)
return; return;
saveLocalProfile(username,profile); saveLocalProfile(username,profile);
} }
public void putLoader(String username, Consumer<Map<MinecraftProfileTexture.Type, MinecraftProfileTexture>> loader) {
this.profileLoaders.putIfAbsent(username, new ConcurrentLinkedDeque<>());
this.profileLoaders.get(username).offerLast(loader);
}
private CachedProfile getCachedProfile(String username){ private CachedProfile getCachedProfile(String username){
CachedProfile cp=cachedProfiles.get(username.toLowerCase()); CachedProfile cp=cachedProfiles.get(username.toLowerCase());
@@ -74,7 +94,7 @@ public class ProfileCache {
localProfiles.put(username.toLowerCase(), null); localProfiles.put(username.toLowerCase(), null);
} }
try{ try{
String json=IOUtils.toString(new FileInputStream(localProfile)); String json = FileUtils.readFileToString(localProfile, "UTF-8");
UserProfile profile=CustomSkinLoader.GSON.fromJson(json, UserProfile.class); UserProfile profile=CustomSkinLoader.GSON.fromJson(json, UserProfile.class);
localProfiles.put(username.toLowerCase(), profile); localProfiles.put(username.toLowerCase(), profile);
CustomSkinLoader.logger.info("Successfully load LocalProfile."); CustomSkinLoader.logger.info("Successfully load LocalProfile.");
@@ -85,14 +105,14 @@ public class ProfileCache {
} }
return null; return null;
} }
private void saveLocalProfile(String username,UserProfile profile){ @SuppressWarnings("ResultOfMethodCallIgnored")
private void saveLocalProfile(String username, UserProfile profile){
String json=CustomSkinLoader.GSON.toJson(profile); String json=CustomSkinLoader.GSON.toJson(profile);
File localProfile=new File(PROFILE_CACHE_DIR,username+".json"); File localProfile=new File(PROFILE_CACHE_DIR,username+".json");
if(localProfile.exists()) if(localProfile.exists())
localProfile.delete(); localProfile.delete();
try { try {
localProfile.createNewFile(); FileUtils.write(localProfile, json, "UTF-8");
IOUtils.write(json, new FileOutputStream(localProfile));
CustomSkinLoader.logger.info("Successfully save LocalProfile."); CustomSkinLoader.logger.info("Successfully save LocalProfile.");
} catch (Exception e) { } catch (Exception e) {
CustomSkinLoader.logger.info("Failed to save LocalProfile.("+e.toString()+")"); CustomSkinLoader.logger.info("Failed to save LocalProfile.("+e.toString()+")");
@@ -51,8 +51,7 @@ public class UserProfile {
this.capeUrl=url; this.capeUrl=url;
return; return;
case ELYTRA: case ELYTRA:
this.capeUrl=url; this.elytraUrl = url;
return;
} }
} }
@@ -92,8 +91,10 @@ public class UserProfile {
public void mix(UserProfile profile){ public void mix(UserProfile profile){
if(profile==null) if(profile==null)
return; return;
if(StringUtils.isEmpty(this.skinUrl)) if(StringUtils.isEmpty(this.skinUrl)) {
this.skinUrl=profile.skinUrl; this.skinUrl = profile.skinUrl;
this.model = profile.model;
}
if(StringUtils.isEmpty(this.capeUrl)) if(StringUtils.isEmpty(this.capeUrl))
this.capeUrl=profile.capeUrl; this.capeUrl=profile.capeUrl;
if(StringUtils.isEmpty(this.elytraUrl)) if(StringUtils.isEmpty(this.elytraUrl))
@@ -1,125 +0,0 @@
package customskinloader.tweaker;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.apache.commons.io.IOUtils;
import customskinloader.utils.MinecraftUtil;
import net.minecraft.launchwrapper.IClassTransformer;
public class ClassTransformer implements IClassTransformer {
private ZipFile zipFile = null;
private ArrayList<String> classes=new ArrayList<String>();
public ClassTransformer() {
ModSystemTweaker.logger.info("ClassTransformer Begin");
try {
URLClassLoader ucl = (URLClassLoader)this.getClass().getClassLoader();
URL urls[] = ucl.getURLs();
for (URL url : urls) {
if(MinecraftUtil.isCoreFile(url)){
ModSystemTweaker.logger.debug(url.toString()+" : SKIP (core file).");
continue;
}
if(MinecraftUtil.isLibraryFile(url)){
ModSystemTweaker.logger.debug(url.toString()+" : SKIP (library file).");
continue;
}
File file = new File(url.toURI());
if(file==null||!file.isFile()){
ModSystemTweaker.logger.info(url.toString()+" : EXCEPTION (file not found).");
continue;
}
ZipFile tempZipFile = getZipFile(file);
if(tempZipFile==null){
ModSystemTweaker.logger.info(url.toString()+" : EXCEPTION (^ Message ^).");
continue;
}
if (tempZipFile.getEntry("customskinloader/tweaker/ClassTransformer.class") == null){
tempZipFile.close();
ModSystemTweaker.logger.debug(url.toString()+" : FINISH (not target).");
continue;
}
zipFile = tempZipFile;
Enumeration<ZipEntry> entries=(Enumeration<ZipEntry>) zipFile.entries();
StringBuilder sb=new StringBuilder();
while(entries.hasMoreElements()){
ZipEntry entry=entries.nextElement();
String name=entry.getName();
if(name.endsWith(".class")&&(!name.contains("/")||name.startsWith("net"))){
classes.add(name);
sb.append(" ");
sb.append(name);
}
}
ModSystemTweaker.logger.info(url.toString()+" : CHOOSE.");
ModSystemTweaker.logger.info("Classes:" + sb.toString());
break;
}
} catch (Exception e) {
ModSystemTweaker.logger.warning(e);
}
if (zipFile == null) {
ModSystemTweaker.logger.info("Can not find JAR in the classpath.");
}
}
private static ZipFile getZipFile(File file)
{
ZipFile zipFile0=null;
try {
zipFile0 = new ZipFile(file);
return zipFile0;
} catch (Exception e) {
ModSystemTweaker.logger.warning(e);
}
return null;
}
public byte[] transform(String name, String transformedName, byte bytes[]) {
if (zipFile == null)
return bytes;
String fullName = new StringBuilder().append(name.startsWith("net") ? name.replaceAll("\\.", "\\/") : name).append(".class").toString();//Notch(Run)/MCP(Dev) Class Name
if(!classes.contains(fullName)){//Check Name
if(name.equals(transformedName))
return bytes;
fullName = new StringBuilder().append(transformedName.replaceAll("\\.", "\\/")).append(".class").toString();//MCP Class Name
if(!classes.contains(fullName))//check Again
return bytes;
}
ZipEntry ze = zipFile.getEntry(fullName);
if (ze == null)
return bytes;
byte diBytes[] = getClass(ze);
if (diBytes != null) {
ModSystemTweaker.logger.info("Class '" + name + "'("+transformedName+") transformed.");
return diBytes;
}
else
return bytes;
}
private byte[] getClass(ZipEntry ze) {
try {
InputStream is = zipFile.getInputStream(ze);
byte[] bytes = IOUtils.toByteArray(is);
if ((long)bytes.length == ze.getSize())
return bytes;
ModSystemTweaker.logger.info("Failed: " + ze.getName() + " " + bytes.length + " / " + ze.getSize());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
@@ -7,12 +7,12 @@ import java.io.OutputStream;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import java.net.URI; import java.net.URI;
import java.net.URL; import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream; import java.util.zip.GZIPInputStream;
import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.Charsets;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
@@ -20,88 +20,127 @@ import org.apache.commons.lang3.StringUtils;
import customskinloader.CustomSkinLoader; import customskinloader.CustomSkinLoader;
public class HttpRequestUtil { public class HttpRequestUtil {
public static class HttpRequest{ public static class HttpRequest {
public String url; public String url;
public String userAgent=null; public String userAgent = null;
public String payload=null; public String payload = null;
public boolean loadContent=true; public boolean loadContent = true;
public boolean checkPNG=false; public boolean checkPNG = false;
public int cacheTime=600;//-1=No Cache 0=Always Cache t=Default Cache Time(second) /**
public File cacheFile=null;//Default Cache File * Cache Time
* -1=No Cache 0=Always Cache t=Default Cache Time(second)
*/
public int cacheTime = 600;
public File cacheFile = null;//Default Cache File
public HttpRequest(String url){ public HttpRequest(String url) {
this.url=url; this.url = url;
} }
public HttpRequest setUserAgent(String userAgent){
this.userAgent=userAgent; public HttpRequest setUserAgent(String userAgent) {
this.userAgent = userAgent;
return this; return this;
} }
public HttpRequest setPayload(String payload){
this.payload=payload; public HttpRequest setPayload(String payload) {
this.payload = payload;
return this; return this;
} }
public HttpRequest setLoadContent(boolean loadContent){
this.loadContent=loadContent; public HttpRequest setLoadContent(boolean loadContent) {
this.loadContent = loadContent;
return this; return this;
} }
public HttpRequest setCheckPNG(boolean checkPNG){
this.checkPNG=checkPNG; public HttpRequest setCheckPNG(boolean checkPNG) {
this.checkPNG = checkPNG;
return this; return this;
} }
public HttpRequest setCacheTime(int cacheTime){
this.cacheTime=cacheTime; public HttpRequest setCacheTime(int cacheTime) {
this.cacheTime = cacheTime;
return this; return this;
} }
public HttpRequest setCacheFile(File cacheFile){
this.cacheFile=cacheFile; public HttpRequest setCacheFile(File cacheFile) {
this.cacheFile = cacheFile;
return this; return this;
} }
} }
public static class HttpResponce{
public String content=null; public static class HttpResponce {
public int responceCode=-1; public String content = null;
public boolean success=false; public int responceCode = -1;
public boolean fromCache=false; public boolean success = false;
public boolean fromCache = false;
} }
public static class CacheInfo{
public static class CacheInfo {
public String url; public String url;
public String etag=null; public String etag = null;
public long lastModified=-1;//ms public long lastModified = -1;//ms
public long expire=-1;//UNIX timestamp public long expire = -1;//UNIX timestamp
} }
public static final File CACHE_DIR=new File(CustomSkinLoader.DATA_DIR,"caches");
public static HttpResponce makeHttpRequest(HttpRequest request){ public static final File CACHE_DIR = new File(CustomSkinLoader.DATA_DIR, "caches");
try{
CustomSkinLoader.logger.debug("Try to request '"+request.url+(request.userAgent==null?"'.":"' with user agent '"+request.userAgent+"'.")); public static HttpResponce makeHttpRequest(HttpRequest request) {
//Check Cache return makeHttpRequest(request, 0);
if(StringUtils.isNotEmpty(request.payload)) }
request.cacheTime=-1;//No Cache
File cacheInfoFile=null; public static HttpResponce makeHttpRequest(HttpRequest request, int redirectTime) {
CacheInfo cacheInfo=new CacheInfo(); try {
if(request.cacheFile==null && request.cacheTime>=0){ //No url provided, try to load from special cache file
String hash=DigestUtils.sha1Hex(request.url); if (request.url == null || request.url.isEmpty()) {
request.cacheFile=new File(CACHE_DIR,hash); CustomSkinLoader.logger.debug("Try to read cache '" + request.cacheFile + "'.");
cacheInfoFile=new File(CACHE_DIR,hash+".json"); return loadFromCache(request, new HttpResponce());
} }
if(request.cacheTime==0 && request.cacheFile.isFile()) CustomSkinLoader.logger.debug("Try to request '" + request.url + (request.userAgent == null ? "'." : "' with user agent '" + request.userAgent + "'."));
return loadFromCache(request,new HttpResponce()); //Check Cache
if(cacheInfoFile!=null&&cacheInfoFile.isFile()){ if (StringUtils.isNotEmpty(request.payload) || CustomSkinLoader.config.forceDisableCache) {
String json=FileUtils.readFileToString(cacheInfoFile); request.cacheTime = -1;//No Cache
if(StringUtils.isNotEmpty(json)) }
cacheInfo=CustomSkinLoader.GSON.fromJson(json, CacheInfo.class); File cacheInfoFile = null;
if(cacheInfo==null) CacheInfo cacheInfo = new CacheInfo();
cacheInfo=new CacheInfo(); if (request.cacheFile == null && request.cacheTime >= 0) {
if(cacheInfo.expire>=TimeUtil.getCurrentUnixTimestamp()) String hash = DigestUtils.sha1Hex(request.url);
return loadFromCache(request,new HttpResponce(),cacheInfo.expire); request.cacheFile = new File(CACHE_DIR, hash);
cacheInfoFile = new File(CACHE_DIR, hash + ".json");
}
//noinspection BulkFileAttributesRead
if (request.cacheTime == 0 && request.cacheFile.isFile()) {
return loadFromCache(request, new HttpResponce());
}
if (cacheInfoFile != null && cacheInfoFile.isFile()) {
String json = FileUtils.readFileToString(cacheInfoFile, "UTF-8");
if (StringUtils.isNotEmpty(json)) {
cacheInfo = CustomSkinLoader.GSON.fromJson(json, CacheInfo.class);
}
if (cacheInfo == null) {
cacheInfo = new CacheInfo();
}
if (cacheInfo.expire >= TimeUtil.getCurrentUnixTimestamp()) {
return loadFromCache(request, new HttpResponce(), cacheInfo.expire);
}
} }
//Init Connection //Init Connection
String url=new URI(request.url).toASCIIString(); URL rawUrl = new URL(request.url);
if(!url.equalsIgnoreCase(request.url)) URI uri = new URI(
CustomSkinLoader.logger.debug("Encoded URL: "+url); rawUrl.getProtocol(),
rawUrl.getUserInfo(),
rawUrl.getHost(),
rawUrl.getPort(),
rawUrl.getPath(),
rawUrl.getQuery(),
rawUrl.getRef()
);
String url = uri.toASCIIString();
if (!url.equalsIgnoreCase(request.url)) {
CustomSkinLoader.logger.debug("Encoded URL: " + url);
}
HttpURLConnection c = (HttpURLConnection) (new URL(url)).openConnection(); HttpURLConnection c = (HttpURLConnection) (new URL(url)).openConnection();
c.setReadTimeout(1000 * 10); c.setReadTimeout(1000 * 10);
c.setConnectTimeout(1000 * 10); c.setConnectTimeout(1000 * 10);
@@ -110,104 +149,133 @@ public class HttpRequestUtil {
c.setInstanceFollowRedirects(true); c.setInstanceFollowRedirects(true);
//Make Connection //Make Connection
if(cacheInfo.lastModified>=0) if (cacheInfo.lastModified >= 0) {
c.setIfModifiedSince(cacheInfo.lastModified); c.setIfModifiedSince(cacheInfo.lastModified);
if(cacheInfo.etag!=null) }
c.setRequestProperty("If-None-Match",cacheInfo.etag); if (cacheInfo.etag != null) {
c.setRequestProperty("Accept-Encoding","gzip"); c.setRequestProperty("If-None-Match", cacheInfo.etag);
if(request.userAgent!=null) }
c.setRequestProperty("User-Agent",request.userAgent); c.setRequestProperty("Accept-Encoding", "gzip");
if(StringUtils.isNotEmpty(request.payload)){ if (request.userAgent != null) {
CustomSkinLoader.logger.info("Payload: "+request.payload); c.setRequestProperty("User-Agent", request.userAgent);
}
if (StringUtils.isNotEmpty(request.payload)) {
CustomSkinLoader.logger.info("Payload: " + request.payload);
c.setRequestProperty("Content-Type", "application/json");
c.setDoOutput(true); c.setDoOutput(true);
OutputStream os=c.getOutputStream(); OutputStream os = c.getOutputStream();
IOUtils.write(request.payload, os); IOUtils.write(request.payload, os, "UTF-8");
IOUtils.closeQuietly(os); IOUtils.closeQuietly(os);
} }
c.connect(); c.connect();
//Check Connection //Check Connection
HttpResponce responce=new HttpResponce(); HttpResponce responce = new HttpResponce();
responce.responceCode=c.getResponseCode(); responce.responceCode = c.getResponseCode();
int res=c.getResponseCode()/100; int res = c.getResponseCode();
if(res==4||res==5){//Failed if (res / 100 == 4 || res / 100 == 5) {//Failed
CustomSkinLoader.logger.debug("Failed to request (Response Code: "+c.getResponseCode()+")"); CustomSkinLoader.logger.debug("Failed to request (Response Code: " + res + ")");
return responce; return responce;
} }
responce.success=true; if (res == HttpURLConnection.HTTP_MOVED_PERM || res == HttpURLConnection.HTTP_MOVED_TEMP) {
CustomSkinLoader.logger.debug("Successfully request (Response Code: "+c.getResponseCode()+" , Content Length: "+c.getContentLength()+")"); //Redirect
if(responce.responceCode==HttpURLConnection.HTTP_NOT_MODIFIED) if (redirectTime >= 4) {
return loadFromCache(request,responce); CustomSkinLoader.logger.debug("Failed to request (Too many redirection)");
return responce;
}
request.url = c.getHeaderField("Location");//Get redirecting location
if (request.url == null) {
CustomSkinLoader.logger.debug("Failed to request (Redirecting location not found)");
return responce;
}
CustomSkinLoader.logger.debug("Redirect to: " + request.url);
return makeHttpRequest(request, redirectTime + 1);//Recursion
}
responce.success = true;
CustomSkinLoader.logger.debug("Successfully request (Response Code: " + res + " , Content Length: " + c.getContentLength() + ")");
if (responce.responceCode == HttpURLConnection.HTTP_NOT_MODIFIED) {
return loadFromCache(request, responce);
}
if (responce.responceCode == HttpURLConnection.HTTP_NO_CONTENT) {
request.cacheTime = 3600;
}
//Load Content //Load Content
InputStream is="gzip".equals(c.getContentEncoding())?new GZIPInputStream(c.getInputStream()):c.getInputStream(); InputStream is = "gzip".equals(c.getContentEncoding()) ? new GZIPInputStream(c.getInputStream()) : c.getInputStream();
byte [] bytes = IOUtils.toByteArray(is); byte[] bytes = IOUtils.toByteArray(is);
if(request.checkPNG&&(bytes.length<=4||bytes[1]!=(byte)'P'||bytes[2]!=(byte)'N'||bytes[3]!=(byte)'G')){ if (request.checkPNG && (bytes.length <= 4 || bytes[1] != (byte) 'P' || bytes[2] != (byte) 'N' || bytes[3] != (byte) 'G')) {
CustomSkinLoader.logger.debug("Failed to request (Not Standard PNG)"); CustomSkinLoader.logger.debug("Failed to request (Not Standard PNG)");
responce.success=false; responce.success = false;
return responce; return responce;
} }
if(request.cacheFile!=null){ if (request.cacheFile != null) {
FileUtils.writeByteArrayToFile(request.cacheFile, bytes); FileUtils.writeByteArrayToFile(request.cacheFile, bytes);
if(cacheInfoFile!=null){ if (cacheInfoFile != null) {
cacheInfo.url=request.url; cacheInfo.url = request.url;
cacheInfo.etag=c.getHeaderField("ETag"); cacheInfo.etag = c.getHeaderField("ETag");
cacheInfo.lastModified=c.getLastModified(); cacheInfo.lastModified = c.getLastModified();
cacheInfo.expire=getExpire(c,request.cacheTime); cacheInfo.expire = getExpire(c, request.cacheTime);
FileUtils.write(cacheInfoFile, CustomSkinLoader.GSON.toJson(cacheInfo)); FileUtils.write(cacheInfoFile, CustomSkinLoader.GSON.toJson(cacheInfo), "UTF-8");
} }
CustomSkinLoader.logger.debug("Saved to cache (Length: "+request.cacheFile.length()+" , Path: '"+request.cacheFile.getAbsolutePath()+"' , Expire: "+cacheInfo.expire+")"); //noinspection BulkFileAttributesRead
CustomSkinLoader.logger.debug("Saved to cache (Length: " + request.cacheFile.length() + " , Path: '" + request.cacheFile.getAbsolutePath() + "' , Expire: " + cacheInfo.expire + ")");
} }
if(!request.loadContent) if (!request.loadContent) {
return responce; return responce;
responce.content=new String(bytes,Charsets.UTF_8); }
CustomSkinLoader.logger.debug("Content: "+responce.content); responce.content = new String(bytes, StandardCharsets.UTF_8);
CustomSkinLoader.logger.debug("Content: " + responce.content);
return responce; return responce;
}catch(Exception e){ } catch (Exception e) {
CustomSkinLoader.logger.debug("Failed to request (Exception: "+e.toString()+")"); CustomSkinLoader.logger.debug("Failed to request " + request.url + " (Exception: " + e + ")");
return loadFromCache(request,new HttpResponce()); return loadFromCache(request, new HttpResponce());
} }
} }
public static File getCacheFile(String hash){ public static File getCacheFile(String hash) {
return new File(CACHE_DIR,hash); return new File(CACHE_DIR, hash);
} }
private static HttpResponce loadFromCache(HttpRequest request,HttpResponce responce){
return loadFromCache(request,responce,0);
}
private static HttpResponce loadFromCache(HttpRequest request,HttpResponce responce,long expireTime){
if(request.cacheFile==null||!request.cacheFile.isFile())
return responce;
CustomSkinLoader.logger.debug("Cache file found (Length: "+request.cacheFile.length()+" , Path: '"+request.cacheFile.getAbsolutePath()+"' , Expire: "+expireTime+"')");
responce.fromCache=true;
responce.success=true;
if(!request.loadContent)
return responce;
CustomSkinLoader.logger.info("Try to load from cache '"+request.cacheFile.getAbsolutePath()+"'."); private static HttpResponce loadFromCache(HttpRequest request, HttpResponce responce) {
return loadFromCache(request, responce, 0);
}
private static HttpResponce loadFromCache(HttpRequest request, HttpResponce responce, long expireTime) {
if (request.cacheFile == null || !request.cacheFile.isFile()) {
return responce;
}
CustomSkinLoader.logger.debug("Cache file found (Length: " + request.cacheFile.length() + " , Path: '" + request.cacheFile.getAbsolutePath() + "' , Expire: " + expireTime + ")");
responce.fromCache = true;
responce.success = true;
if (!request.loadContent) {
return responce;
}
CustomSkinLoader.logger.info("Try to load from cache '" + request.cacheFile.getAbsolutePath() + "'.");
try { try {
responce.content=FileUtils.readFileToString(request.cacheFile); responce.content = FileUtils.readFileToString(request.cacheFile, "UTF-8");
CustomSkinLoader.logger.debug("Successfully load from cache"); CustomSkinLoader.logger.debug("Successfully load from cache");
CustomSkinLoader.logger.debug("Content: "+responce.content); CustomSkinLoader.logger.debug("Content: " + responce.content);
} catch (IOException e) { } catch (IOException e) {
CustomSkinLoader.logger.debug("Failed to load from cache (Exception: "+e.toString()+")"); CustomSkinLoader.logger.debug("Failed to load from cache (Exception: " + e + ")");
responce.success=false; responce.success = false;
} }
return responce; return responce;
} }
private final static Pattern MAX_AGE_PATTERN = Pattern.compile(".*?max-age=(\\d+).*?"); private final static Pattern MAX_AGE_PATTERN = Pattern.compile(".*?max-age=(\\d+).*?");
private static long getExpire(HttpURLConnection connection,int cacheTime){
String cacheControl=connection.getHeaderField("Cache-Control"); private static long getExpire(HttpURLConnection connection, int cacheTime) {
if(StringUtils.isNotEmpty(cacheControl)){ String cacheControl = connection.getHeaderField("Cache-Control");
Matcher m=MAX_AGE_PATTERN.matcher(cacheControl); if (StringUtils.isNotEmpty(cacheControl)) {
if(m!=null && m.matches()) Matcher m = MAX_AGE_PATTERN.matcher(cacheControl);
if (m.matches())
return TimeUtil.getUnixTimestamp(Long.parseLong(m.group(m.groupCount()))); return TimeUtil.getUnixTimestamp(Long.parseLong(m.group(m.groupCount())));
} }
long expires=connection.getExpiration(); long expires = connection.getExpiration();
if(expires>0) if (expires > 0)
return expires/1000; return expires / 1000;
return TimeUtil.getUnixTimestampRandomDelay(cacheTime==0 ? 86400 : cacheTime); return TimeUtil.getUnixTimestampRandomDelay(cacheTime == 0 ? 2592000 : cacheTime);
} }
} }
@@ -8,75 +8,100 @@ import org.apache.commons.io.FilenameUtils;
import customskinloader.CustomSkinLoader; import customskinloader.CustomSkinLoader;
public class HttpTextureUtil { public class HttpTextureUtil {
public static class HttpTextureInfo{ public static class HttpTextureInfo {
public String url=""; public String url = "";
public File cacheFile; public File cacheFile;
public String hash; public String hash;
} }
private static final String private static final String
LEGACY_MARK="(LEGACY)", LEGACY_MARK = "(LEGACY)",
LOCAL_MARK="(LOCAL)", LOCAL_MARK = "(LOCAL)",
LOCAL_LEGACY_MARK="(LOCAL_LEGACY)"; LOCAL_LEGACY_MARK = "(LOCAL_LEGACY)",
BASE64_MARK = "(BASE64)";
public static File defaultCacheDir; public static File defaultCacheDir;
public static void cleanCacheDir(){
if(defaultCacheDir!=null){ @SuppressWarnings("ResultOfMethodCallIgnored")
public static void cleanCacheDir() {
if (defaultCacheDir != null) {
defaultCacheDir.delete(); defaultCacheDir.delete();
defaultCacheDir.mkdirs(); defaultCacheDir.mkdirs();
} }
} }
public static File getCacheDir(){
return defaultCacheDir==null?new File(MinecraftUtil.getMinecraftDataDir(),"assets/skins"):defaultCacheDir; public static File getCacheDir() {
return defaultCacheDir == null ? new File(MinecraftUtil.getMinecraftDataDir(), "assets/skins") : defaultCacheDir;
} }
public static HttpTextureInfo toHttpTextureInfo(String fakeUrl){ public static HttpTextureInfo toHttpTextureInfo(String fakeUrl) {
HttpTextureInfo info=new HttpTextureInfo(); HttpTextureInfo info = new HttpTextureInfo();
if(fakeUrl.startsWith("http")){ if (fakeUrl.startsWith("http")) {
info.url=fakeUrl; info.url = fakeUrl;
info.hash=FilenameUtils.getBaseName(fakeUrl); info.hash = FilenameUtils.getBaseName(fakeUrl);
info.cacheFile=getCacheFile(info.hash); info.cacheFile = getCacheFile(info.hash);
return info; return info;
} }
if(fakeUrl.startsWith(LOCAL_LEGACY_MARK)){ if (fakeUrl.startsWith(LOCAL_LEGACY_MARK)) {
fakeUrl=fakeUrl.replace(LOCAL_LEGACY_MARK, ""); fakeUrl = fakeUrl.replace(LOCAL_LEGACY_MARK, "");
String[] t=fakeUrl.split(",",2); String[] t = fakeUrl.split(",", 2);
if(t.length!=2) if (t.length != 2)
return info; return info;
info.cacheFile=new File(CustomSkinLoader.DATA_DIR,t[1]); info.cacheFile = new File(CustomSkinLoader.DATA_DIR, t[1]);
info.hash=t[0]; info.hash = t[0];
return info; return info;
} }
if(fakeUrl.startsWith(LOCAL_MARK)){ if (fakeUrl.startsWith(LOCAL_MARK)) {
fakeUrl=fakeUrl.replace(LOCAL_MARK, ""); fakeUrl = fakeUrl.replace(LOCAL_MARK, "");
info.cacheFile=new File(CustomSkinLoader.DATA_DIR,fakeUrl); info.cacheFile = new File(CustomSkinLoader.DATA_DIR, fakeUrl);
info.hash=FilenameUtils.getBaseName(fakeUrl); info.hash = FilenameUtils.getBaseName(fakeUrl);
return info; return info;
} }
if(fakeUrl.startsWith(LEGACY_MARK)){ if (fakeUrl.startsWith(LEGACY_MARK)) {
fakeUrl=fakeUrl.replace(LEGACY_MARK, ""); fakeUrl = fakeUrl.replace(LEGACY_MARK, "");
info.url=fakeUrl; info.url = fakeUrl;
info.hash=DigestUtils.sha1Hex(info.url);; info.hash = DigestUtils.sha1Hex(info.url);
info.cacheFile=HttpTextureUtil.getCacheFile(info.hash); info.cacheFile = HttpRequestUtil.getCacheFile(info.hash);
return info;
}
//Base64 fake url format: `(BASE64)${hash}`
if (fakeUrl.startsWith(BASE64_MARK)) {
fakeUrl = fakeUrl.replace(BASE64_MARK, "");
info.hash = fakeUrl;
info.cacheFile = getCacheFile(info.hash);
return info; return info;
} }
return info; return info;
} }
public static String getLegacyFakeUrl(String url){ public static String getLegacyFakeUrl(String url) {
return LEGACY_MARK+url; return LEGACY_MARK + url;
} }
public static String getLocalFakeUrl(String path){
return LOCAL_MARK+path; public static String getLocalFakeUrl(String path) {
return LOCAL_MARK + path;
} }
public static String getLocalLegacyFakeUrl(String path,String hash){
return LOCAL_LEGACY_MARK+hash+","+path; public static String getLocalLegacyFakeUrl(String path, String hash) {
return LOCAL_LEGACY_MARK + hash + "," + path;
} }
public static String getHash(String url,long size,long lastModified){
return DigestUtils.sha1Hex(size+url+lastModified); public static String getBase64FakeUrl(String hash) {
return BASE64_MARK + hash;
} }
public static File getCacheFile(String hash){
return getCacheFile(defaultCacheDir,hash); public static String getHash(String url, long size, long lastModified) {
return DigestUtils.sha1Hex(size + url + lastModified);
} }
public static File getCacheFile(File cacheDir,String hash){
return new File(new File(cacheDir,hash.length()>2?hash.substring(0,2):"xx"), hash); public static String getHash(byte[] bytes) {
return DigestUtils.sha256Hex(bytes);
}
public static File getCacheFile(String hash) {
return getCacheFile(defaultCacheDir, hash);
}
public static File getCacheFile(File cacheDir, String hash) {
return new File(new File(cacheDir, hash.length() > 2 ? hash.substring(0, 2) : "xx"), hash);
} }
} }
@@ -1,13 +1,15 @@
package customskinloader.utils; package customskinloader.utils;
import java.io.IOException;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import java.security.cert.X509Certificate; import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext; import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager; import javax.net.ssl.X509TrustManager;
@@ -15,7 +17,7 @@ import org.apache.commons.lang3.StringUtils;
public class HttpUtil0 { public class HttpUtil0 {
public static boolean isLocal(String url){ public static boolean isLocal(String url){
return url==null? false : !url.startsWith("http"); return url != null && !url.startsWith("http://") && !url.startsWith("https://");
} }
//From: http://blog.csdn.net/xiyushiyi/article/details/46685387 //From: http://blog.csdn.net/xiyushiyi/article/details/46685387
@@ -37,7 +39,8 @@ public class HttpUtil0 {
try { try {
SSLContext sc = SSLContext.getInstance("TLS"); SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom()); sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); //HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultSSLSocketFactory(new SSLSocketFactoryFacade());
HttpsURLConnection.setDefaultHostnameVerifier(doNotVerify); HttpsURLConnection.setDefaultHostnameVerifier(doNotVerify);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
@@ -76,4 +79,49 @@ public class HttpUtil0 {
num+=Integer.parseInt(ips[i])*(256^(3-i)); num+=Integer.parseInt(ips[i])*(256^(3-i));
return num; return num;
} }
//https://stackoverflow.com/questions/30817934/extended-server-name-sni-extension-not-sent-with-jdk1-8-0-but-send-with-jdk1-7
public static class SSLSocketFactoryFacade extends SSLSocketFactory {
SSLSocketFactory sslsf;
public SSLSocketFactoryFacade() {
sslsf = (SSLSocketFactory) SSLSocketFactory.getDefault();;
}
@Override
public String[] getDefaultCipherSuites() {
return sslsf.getDefaultCipherSuites();
}
@Override
public String[] getSupportedCipherSuites() {
return sslsf.getSupportedCipherSuites();
}
@Override
public Socket createSocket(Socket socket, String s, int i, boolean b) throws IOException {
return sslsf.createSocket(socket, s, i, b);
}
@Override
public Socket createSocket(String s, int i) throws IOException, UnknownHostException {
return sslsf.createSocket(s, i);
}
@Override
public Socket createSocket(String s, int i, InetAddress inetAddress, int i1) throws IOException, UnknownHostException {
return sslsf.createSocket(s, i, inetAddress, i1);
}
@Override
public Socket createSocket(InetAddress inetAddress, int i) throws IOException {
return createSocket(inetAddress, i);
}
@Override
public Socket createSocket(InetAddress inetAddress, int i, InetAddress inetAddress1, int i1) throws IOException {
return createSocket(inetAddress, i, inetAddress1, i1);
}
}
} }
@@ -0,0 +1,34 @@
package customskinloader.utils;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.LinkedList;
public class JavaUtil {
public static URL[] getClasspath() {
if (JavaUtil.class.getClassLoader() instanceof URLClassLoader) {
//Java 8-
//Use URLClassLoader Directly
URLClassLoader ucl = (URLClassLoader) JavaUtil.class.getClassLoader();
return ucl.getURLs();
} else {
//Java 9+
//It uses APPClassLoader instead of URLClassLoader
//Get Classpath from properties and parse it to URL array
String classpath = System.getProperty("java.class.path");
String[] elements = classpath.split(File.pathSeparator);
if (elements.length == 0)
return new URL[0];
LinkedList<URL> urls = new LinkedList<URL>();
for (String ele : elements) {
try {
urls.add(new File(ele).toURI().toURL());
} catch (Exception ignored) {
}
}
return urls.toArray(new URL[0]);
}
}
}
@@ -1,130 +1,99 @@
package customskinloader.utils; package customskinloader.utils;
import java.io.File; import java.io.File;
import java.io.FileReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Field;
import java.net.URL; import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils; import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.mojang.authlib.GameProfile; import com.mojang.authlib.GameProfile;
import com.mojang.authlib.minecraft.MinecraftSessionService; import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.client.resources.SkinManager;
import net.minecraft.realms.RealmsSharedConstants;
import org.apache.commons.lang3.StringUtils;
/** /**
* @author Alexander Xia * @author Alexander Xia
* @since 13.6 * @since 13.6
*
*/ */
public class MinecraftUtil { public class MinecraftUtil {
public static File getMinecraftDataDir(){ public static File getMinecraftDataDir() {
return net.minecraft.client.Minecraft.getMinecraft().mcDataDir; return Minecraft.getMinecraft().gameDir;
}
public static MinecraftSessionService getSessionService(){
return net.minecraft.client.Minecraft.getMinecraft().getSessionService();
}
public static TextureManager getTextureManager(){
return net.minecraft.client.Minecraft.getMinecraft().getTextureManager();
} }
private static ArrayList<String> minecraftVersion=new ArrayList<String>(); public static TextureManager getTextureManager() {
private static String minecraftMainVersion=null; return Minecraft.getMinecraft().getTextureManager();
private final static Pattern MINECRAFT_VERSION_PATTERN = Pattern.compile(".*?(\\d+\\.\\d+[\\.]?\\d*).*?");
public static ArrayList<String> getMinecraftVersions(){
if(minecraftVersion!=null&&!minecraftVersion.isEmpty())
return minecraftVersion;
testProbe();
return minecraftVersion;
} }
public static String getMinecraftVersionText(){
StringBuilder sb=new StringBuilder(); public static SkinManager getSkinManager() {
for(String version:getMinecraftVersions()) return Minecraft.getMinecraft().getSkinManager();
sb.append(version).append(" ");
return StringUtils.trim(sb.toString());
} }
public static String getMinecraftMainVersion(){ private static String minecraftMainVersion = null;
if(minecraftMainVersion!=null)
public static String getMinecraftMainVersion() {
//Check if cached version found
if (minecraftMainVersion != null) {
return minecraftMainVersion; return minecraftMainVersion;
for(String version:getMinecraftVersions()){
Matcher m = null;
try{
m=MINECRAFT_VERSION_PATTERN.matcher(version);
}catch(Exception e){
e.printStackTrace();
}
if(m==null || !m.matches())
continue;
minecraftMainVersion=m.group(m.groupCount());
break;
} }
return minecraftMainVersion;
//version.json can be found in 1.14+
URL versionFile = MinecraftUtil.class.getResource("/version.json");
if (versionFile != null) {
try (
InputStream is = versionFile.openStream();
InputStreamReader isr = new InputStreamReader(is)
) {
JsonObject obj = new JsonParser().parse(isr).getAsJsonObject();
minecraftMainVersion = obj.get("name").getAsString();
return minecraftMainVersion;
} catch (Exception ignored) {
}
}
//RealmsSharedConstants.VERSION_STRING is available in 1.16-
try {
Class<?> realmsSharedConstants = Class.forName("net.minecraft.realms.RealmsSharedConstants");
MethodHandle mh = MethodHandles.publicLookup().findStaticGetter(realmsSharedConstants, "VERSION_STRING", String.class);
minecraftMainVersion = (String) mh.invoke();
return minecraftMainVersion;
} catch (Throwable ignored) {
}
//No version can be found
return "unknown";
} }
// (domain|ip)(:port) // (domain|ip)(:port)
public static String getServerAddress(){ public static String getServerAddress() {
net.minecraft.client.multiplayer.ServerData data=net.minecraft.client.Minecraft.getMinecraft().getCurrentServerData(); net.minecraft.client.multiplayer.ServerData data = Minecraft.getMinecraft().getCurrentServerData();
if(data==null)//Single Player if (data == null)//Single Player
return null; return null;
return data.serverIP; return data.serverIP;
} }
// ip:port // ip:port
public static String getStandardServerAddress(){ public static String getStandardServerAddress() {
return HttpUtil0.parseAddress(getServerAddress()); return HttpUtil0.parseAddress(getServerAddress());
} }
public static boolean isLanServer(){
public static boolean isLanServer() {
return HttpUtil0.isLanServer(getStandardServerAddress()); return HttpUtil0.isLanServer(getStandardServerAddress());
} }
public static String getCurrentUsername(){
return net.minecraft.client.Minecraft.getMinecraft().getSession().getProfile().getName();
}
private final static Pattern MINECRAFT_CORE_FILE_PATTERN = Pattern.compile("^(.*?)/versions/([^\\/\\\\]*?)/([^\\/\\\\]*?).jar$");
private static void testProbe(){
minecraftVersion.clear();
URLClassLoader ucl = (URLClassLoader)new MinecraftUtil().getClass().getClassLoader();
URL urls[] = ucl.getURLs();
for(URL url:urls){
Matcher m = null;
try{
m=MINECRAFT_CORE_FILE_PATTERN.matcher(URLDecoder.decode(url.getPath(),"UTF-8"));
}catch(Exception e){
e.printStackTrace();
}
if(m==null || !m.matches())
continue;
minecraftVersion.add(m.group(2));
}
}
public static boolean isCoreFile(URL url){
Matcher m = null;
try{
m=MINECRAFT_CORE_FILE_PATTERN.matcher(URLDecoder.decode(url.getPath(),"UTF-8"));
}catch(Exception e){
e.printStackTrace();
return false;
}
return m!=null && m.matches();
}
private final static Pattern LIBRARY_FILE_PATTERN = Pattern.compile("^(.*?)/libraries/(.*?)/([^\\/\\\\]*?).jar$");
public static boolean isLibraryFile(URL url){
Matcher m = null;
try{
m=LIBRARY_FILE_PATTERN.matcher(URLDecoder.decode(url.getPath(),"UTF-8"));
}catch(Exception e){
e.printStackTrace();
return false;
}
return m!=null && m.matches();
}
public static String getCredential(GameProfile profile) { public static String getCredential(GameProfile profile) {
return (profile==null || profile.hashCode()==0) ? null : return (profile == null || profile.hashCode() == 0) ? null :
(profile.getId()==null ? profile.getName() : String.format("%s-%s", profile.getName(),profile.getId())); (profile.getId() == null ? profile.getName() : String.format("%s-%s", profile.getName(), profile.getId()));
} }
} }
@@ -2,7 +2,7 @@ package customskinloader.utils;
public class TimeUtil { public class TimeUtil {
public static long getCurrentUnixTimestamp(){ public static long getCurrentUnixTimestamp(){
return System.currentTimeMillis()/1000l; return System.currentTimeMillis() / 1000L;
} }
public static long getUnixTimestamp(long offset){ public static long getUnixTimestamp(long offset){
return getCurrentUnixTimestamp()+offset; return getCurrentUnixTimestamp()+offset;
@@ -0,0 +1,50 @@
package customskinloader.utils;
import org.apache.commons.lang3.StringUtils;
public class Version implements Comparable {
private String version;
private int sub[];
public Version(String version) {
if (version == null) version = "";
this.version = version;
//Parse Subversion
String[] split = version.split("\\.");
sub = new int[split.length];
for (int i = 0; i < split.length; i++) {
if (StringUtils.isNumeric(split[i]))
sub[i] = Integer.parseInt(split[i]);
}
}
public static Version of(String version) {
return new Version(version);
}
public static int compare(String version, String anotherVersion) {
return Version.of(version).compareTo(anotherVersion);
}
@Override
public String toString() {
return version;
}
@Override
public int compareTo(Object o) {
if (o instanceof String) o = Version.of((String) o);//Parse String version
if (!(o instanceof Version)) throw new IllegalArgumentException(String.format("'%s' is not a Version.", o));
Version v = (Version) o;
int i = 0;
//Skip same subversion
while (i < sub.length && i < v.sub.length && sub[i] == v.sub[i]) i++;
//Compare first non-equal number
if (i < sub.length && i < v.sub.length)
return (sub[i] < v.sub[i]) ? -1 : ((sub[i] == v.sub[i]) ? 0 : 1); //Integer.compare(sub[i], v.sub[i]);
//Compare length if all subversion is same
return Integer.signum(sub.length - v.sub.length);
}
}
@@ -0,0 +1,18 @@
package net.minecraft.client.renderer;
import java.awt.image.BufferedImage;
import net.minecraft.client.renderer.texture.NativeImage;
public interface IImageBuffer extends Runnable {
BufferedImage parseUserSkin(BufferedImage image);
NativeImage func_195786_a(NativeImage image);
void skinAvailable();
@Override
default void run() {
this.skinAvailable();
}
}
@@ -0,0 +1,16 @@
package net.minecraft.client.renderer.texture;
import java.io.File;
import net.minecraft.client.renderer.IImageBuffer;
import net.minecraft.util.ResourceLocation;
public class DownloadingTexture extends SimpleTexture {
public DownloadingTexture(File cacheFileIn, String imageUrlIn, ResourceLocation textureResourceLocation, IImageBuffer imageBufferIn) {
super(textureResourceLocation);
}
public DownloadingTexture(File cacheFileIn, String imageUrlIn, ResourceLocation textureResourceLocation, boolean legacySkinIn, Runnable processTaskIn) {
super(textureResourceLocation);
}
}
@@ -0,0 +1,63 @@
package net.minecraft.client.renderer.texture;
import java.io.InputStream;
/**
* Empty stack for NativeImage
*/
public class NativeImage {
public static NativeImage func_195713_a(InputStream inputStreamIn) {
return null;
}
public NativeImage(int p_i48122_1_, int p_i48122_2_, boolean p_i48122_3_) {
}
/**
* getWidth
*/
public int func_195702_a() {
return 0;
}
/**
* getHeight
*/
public int func_195714_b() {
return 0;
}
/**
* copyImage image
*/
public void func_195703_a(NativeImage p_195703_1_) {
}
/**
* fillAreaRGBA x0 y0 weight height rgba
*/
public void func_195715_a(int p_195715_1_, int p_195715_2_, int p_195715_3_, int p_195715_4_, int p_195715_5_) {
}
/**
* copyAreaRGBA x0 y0 dx dy weight height reversex reversey
*/
public void func_195699_a(int p_195699_1_, int p_195699_2_, int p_195699_3_, int p_195699_4_, int p_195699_5_, int p_195699_6_, boolean p_195699_7_, boolean p_195699_8_) {
}
/**
* getPixelRGBA x y
*/
public int func_195709_a(int p_195709_1_, int p_195709_2_) {
return 0;
}
/**
* setPixelRGBA x y rgba
*/
public void func_195700_a(int p_195700_1_, int p_195700_2_, int p_195700_3_) {
}
public void close() {
}
}
@@ -0,0 +1,5 @@
package net.minecraft.client.renderer.texture;
// exclude
public interface Texture {
}
@@ -0,0 +1,12 @@
package net.minecraft.client.renderer.texture;
import java.io.File;
import net.minecraft.client.renderer.IImageBuffer;
import net.minecraft.util.ResourceLocation;
public class ThreadDownloadImageData extends SimpleTexture {
public ThreadDownloadImageData(File cacheFileIn, String imageUrlIn, ResourceLocation textureResourceLocation, IImageBuffer imageBufferIn) {
super(textureResourceLocation);
}
}
@@ -0,0 +1,8 @@
package net.minecraft.client.resources;
import java.io.InputStream;
// this class shouldn't be created by ASM because of modlauncher issue.
public interface IResource {
InputStream getInputStream();
}
@@ -0,0 +1,10 @@
package net.minecraft.client.resources;
import java.io.IOException;
import net.minecraft.util.ResourceLocation;
// this class shouldn't be created by ASM because of modlauncher issue.
public interface IResourceManager {
IResource getResource(ResourceLocation location) throws IOException;
}
@@ -0,0 +1,6 @@
package net.minecraft.resources;
// exclude
public interface IResource {
}
@@ -0,0 +1,6 @@
package net.minecraft.resources;
// exclude
public interface IResourceManager {
}
+70
View File
@@ -0,0 +1,70 @@
customskinloader/fake/itf/IFakeIResource$V1 customskinloader/fake/itf/IFakeIResource$V1
func_199027_b ()Ljava/io/InputStream; method_14482
customskinloader/fake/itf/IFakeIResource$V2 customskinloader/fake/itf/IFakeIResource$V2
open ()Ljava/io/InputStream; method_14482
customskinloader/fake/itf/IFakeIResourceManager customskinloader/fake/itf/IFakeIResourceManager
func_199002_a (Lnet/minecraft/util/ResourceLocation;)Lnet/minecraft/resources/IResource; method_14486
getResource (Lnet/minecraft/util/ResourceLocation;)Ljava/util/Optional; method_14486
customskinloader/fake/itf/IFakeMinecraft customskinloader/fake/itf/IFakeMinecraft
func_195551_G ()Lnet/minecraft/resources/IResourceManager; method_1478
customskinloader/fake/itf/IFakeTextureManager$V1 customskinloader/fake/itf/IFakeTextureManager$V1
func_229263_a_ (Lnet/minecraft/util/ResourceLocation;Lnet/minecraft/client/renderer/texture/Texture;)Z method_4616
func_229267_b_ (Lnet/minecraft/util/ResourceLocation;)Lnet/minecraft/client/renderer/texture/Texture; method_4619
getTexture (Lnet/minecraft/util/ResourceLocation;Lnet/minecraft/client/renderer/texture/Texture;)Lnet/minecraft/client/renderer/texture/Texture; method_34590
customskinloader/fake/itf/IFakeTextureManager$V2 customskinloader/fake/itf/IFakeTextureManager$V2
func_229263_a_ (Lnet/minecraft/util/ResourceLocation;Lnet/minecraft/client/renderer/texture/Texture;)V method_4616
net/minecraft/client/Minecraft net/minecraft/class_310
gameDir field_1697
addScheduledTask (Ljava/lang/Runnable;)Lcom/google/common/util/concurrent/ListenableFuture; func_152344_a
getCurrentServerData ()Lnet/minecraft/client/multiplayer/ServerData; method_1558
getMinecraft ()Lnet/minecraft/client/Minecraft; method_1551
getResourceManager ()Lnet/minecraft/client/resources/IResourceManager; method_1478
getSessionService ()Lcom/mojang/authlib/minecraft/MinecraftSessionService; method_1495
getSkinManager ()Lnet/minecraft/client/resources/SkinManager; method_1582
getTextureManager ()Lnet/minecraft/client/renderer/texture/TextureManager; method_1531
net/minecraft/client/gui/GuiPlayerTabOverlay net/minecraft/class_355
net/minecraft/client/gui/spectator/PlayerMenuObject net/minecraft/class_530
net/minecraft/client/multiplayer/ServerData net/minecraft/class_642
serverIP field_3761
net/minecraft/client/renderer/RenderType net/minecraft/class_1921
func_228644_e_ (Lnet/minecraft/util/ResourceLocation;)Lnet/minecraft/client/renderer/RenderType; method_23580
net/minecraft/client/renderer/IImageBuffer net/minecraft/class_760
func_195786_a (Lnet/minecraft/client/renderer/texture/NativeImage;)Lnet/minecraft/client/renderer/texture/NativeImage; method_3237
parseUserSkin (Ljava/awt/image/BufferedImage;)Ljava/awt/image/BufferedImage; func_78432_a
skinAvailable ()V method_3238
net/minecraft/client/renderer/ThreadDownloadImageData net/minecraft/class_1046
net/minecraft/client/renderer/entity/RenderPlayer net/minecraft/class_1007
net/minecraft/client/renderer/entity/layers/LayerCape net/minecraft/class_972
net/minecraft/client/renderer/texture/DownloadingTexture net/minecraft/class_1046
net/minecraft/client/renderer/texture/ITextureObject net/minecraft/class_1062
net/minecraft/client/renderer/texture/NativeImage net/minecraft/class_1011
func_195699_a (IIIIIIZZ)V method_4304
func_195700_a (III)V method_4305
func_195702_a ()I method_4307
func_195703_a (Lnet/minecraft/client/renderer/texture/NativeImage;)V method_4317
func_195709_a (II)I method_4315
func_195713_a (Ljava/io/InputStream;)Lnet/minecraft/client/renderer/texture/NativeImage; method_4309
func_195714_b ()I method_4323
func_195715_a (IIIII)V method_4326
net/minecraft/client/renderer/texture/SimpleTexture net/minecraft/class_1049
net/minecraft/client/renderer/texture/Texture net/minecraft/class_1044
net/minecraft/client/renderer/texture/TextureManager net/minecraft/class_1060
getTexture (Lnet/minecraft/util/ResourceLocation;)Lnet/minecraft/client/renderer/texture/ITextureObject; method_4619
loadTexture (Lnet/minecraft/util/ResourceLocation;Lnet/minecraft/client/renderer/texture/ITextureObject;)Z method_4616
net/minecraft/client/renderer/texture/ThreadDownloadImageData net/minecraft/class_1046
net/minecraft/client/resources/DefaultPlayerSkin net/minecraft/class_1068
getDefaultSkin (Ljava/util/UUID;)Lnet/minecraft/util/ResourceLocation; method_4648
getDefaultSkinLegacy ()Lnet/minecraft/util/ResourceLocation; method_4649
net/minecraft/client/resources/IResource net/minecraft/class_3298
getInputStream ()Ljava/io/InputStream; method_14482
net/minecraft/client/resources/IResourceManager net/minecraft/class_3300
getResource (Lnet/minecraft/util/ResourceLocation;)Lnet/minecraft/client/resources/IResource; method_14486
net/minecraft/client/resources/SkinManager net/minecraft/class_1071
loadProfileTextures (Lcom/mojang/authlib/GameProfile;Lnet/minecraft/client/resources/SkinManager$SkinAvailableCallback;Z)V method_4652
net/minecraft/client/resources/SkinManager$SkinAvailableCallback net/minecraft/class_1071$class_1072
skinAvailable (Lcom/mojang/authlib/minecraft/MinecraftProfileTexture$Type;Lnet/minecraft/util/ResourceLocation;Lcom/mojang/authlib/minecraft/MinecraftProfileTexture;)V onSkinTextureAvailable
net/minecraft/resources/IResource net/minecraft/class_3298
net/minecraft/resources/IResourceManager net/minecraft/class_3300
net/minecraft/util/ResourceLocation net/minecraft/class_2960
net/minecraft/util/StringUtils net/minecraft/class_3544
stripControlCodes (Ljava/lang/String;)Ljava/lang/String; method_15440
+77
View File
@@ -0,0 +1,77 @@
jar {
exclude 'customskinloader/tweaker/**'
exclude 'net/minecraft/client/renderer/RenderType.class'
exclude 'net/minecraft/client/renderer/texture/**'
exclude 'net/minecraft/client/resources/**'
exclude 'net/minecraft/resources/**'
exclude 'Profile.json'
}
sourceJar {
exclude 'customskinloader/tweaker/**'
exclude 'net/**'
exclude 'Profile.json'
}
repositories {
maven {
name = "fabric"
url = "https://maven.fabricmc.net/"
}
}
dependencies {
// This is the minimum version number that the mod should dependent in the development environment.
implementation "net.fabricmc:fabric-loader:0.12.0"
}
import customskinloader.gradle.util.RemapUtil
import customskinloader.gradle.util.SourceUtil
import groovy.json.JsonSlurper
SourceUtil.addDependencies project, project(":Common"), project(":Vanilla/Common")
RemapUtil.remapSources project
// Resolve snapshot versions
tasks.publishModrinth.doFirst {
def snapshot = []
gameVersions.groupBy { v -> v.endsWith("-Snapshot") }.with {
this.tasks.publishModrinth.gameVersions = it[false]
snapshot = it[true]
}
// The CustomSkinLoader Fabric edition should support all Minecraft snapshot edition.
def jsonSlurper = new JsonSlurper()
def officialVersionList = [] as Set
plugins.withId "net.minecraftforge.gradle.forge", { plugin ->
def currentRelease = null
// Get version manifest json.
// https://github.com/MinecraftForge/ForgeGradle/blob/fc67182a61926f0bdb0d12da5fba7f4322f64d86/src/main/java/net/minecraftforge/gradle/common/BasePlugin.java#L229
jsonSlurper.parse(plugin.cacheFile("McManifest.json")).versions.each { version ->
if (version.type == "snapshot") {
// If the first version is a snapshot, assume the target release version is the same as the assets version.
if (currentRelease == null) {
currentRelease = jsonSlurper.parse(new URL(version.url)).assets.with {
it.toString().split($/\./$).with { "${it[0]}.${it[1]}" }
}
}
} else if (version.type == "release") {
currentRelease = version.id.with {
it.toString().split($/\./$).with { "${it[0]}.${it[1]}" }
}
} else {
// We do not care about other types.
return
}
if (snapshot.contains("${currentRelease}-Snapshot".toString())) {
officialVersionList << version.id
}
}
}
jsonSlurper.parse(new URL("https://meta.fabricmc.net/v2/versions/game")).each { version ->
// Exclude experimental editions which is not support in Modrinth.
if (!version.stable && officialVersionList.contains(version.version)) {
gameVersions << version.version.replace(" ", "-").replace("Pre-Release-", "pre") // Fix the id of the earlier preview versions of 1.14.
}
}
}
+8
View File
@@ -0,0 +1,8 @@
minecraft_version=1.14
minecraft_full_versions=1.14-Snapshot,1.14,1.14.1,1.14.2,1.14.3,1.14.4,1.15-Snapshot,1.15,1.15.1,1.15.2,1.16-Snapshot,1.16,1.16.1,1.16.2,1.16.3,1.16.4,1.16.5,1.17-Snapshot,1.17,1.17.1,1.18-Snapshot,1.18,1.18.1,1.18.2,1.19-Snapshot,1.19,1.19.1,1.19.2
java_full_versions=8,9,10,11,12,13,14,15,16,17,18
#forge gradle needs forge version
forge_mc_version=1.12.2
forge_version=14.23.5.2768
mappings_version=stable_39
srg_notch_map=Fabric.tsrg
+35
View File
@@ -0,0 +1,35 @@
com/mojang/blaze3d/matrix/MatrixStack net/minecraft/class_4587
net/minecraft/client/Minecraft net/minecraft/class_310
isIntegratedServerRunning ()Z method_1542
net/minecraft/client/entity/AbstractClientPlayer net/minecraft/class_742
getDownloadImageSkin (Lnet/minecraft/util/ResourceLocation;Ljava/lang/String;)Lnet/minecraft/client/renderer/ThreadDownloadImageData; method_3120
getLocationSkin (Ljava/lang/String;)Lnet/minecraft/util/ResourceLocation; method_3124
net/minecraft/client/gui/GuiPlayerTabOverlay net/minecraft/class_355
renderPlayerlist (ILnet/minecraft/scoreboard/Scoreboard;Lnet/minecraft/scoreboard/ScoreObjective;)V method_1919
renderPlayerlist (Lcom/mojang/blaze3d/matrix/MatrixStack;ILnet/minecraft/scoreboard/Scoreboard;Lnet/minecraft/scoreboard/ScoreObjective;)V method_1919
net/minecraft/client/model/ModelRenderer net/minecraft/class_630
net/minecraft/client/renderer/IRenderTypeBuffer net/minecraft/class_4597
net/minecraft/client/renderer/RenderType net/minecraft/class_1921
getEntitySolid (Lnet/minecraft/util/ResourceLocation;)Lnet/minecraft/client/renderer/RenderType; method_23572
net/minecraft/client/renderer/ThreadDownloadImageData net/minecraft/class_1046
bufferedImage field_110560_d
textureUploaded field_5215
processTask field_20843
loadTexture (Ljava/io/InputStream;)Lnet/minecraft/client/renderer/texture/NativeImage; method_22795
processLegacySkin (Lnet/minecraft/client/renderer/texture/NativeImage;)Lnet/minecraft/client/renderer/texture/NativeImage; method_22798
net/minecraft/client/renderer/entity/RenderPlayer net/minecraft/class_1007
renderItem (Lcom/mojang/blaze3d/matrix/MatrixStack;Lnet/minecraft/client/renderer/IRenderTypeBuffer;ILnet/minecraft/client/entity/AbstractClientPlayer;Lnet/minecraft/client/model/ModelRenderer;Lnet/minecraft/client/model/ModelRenderer;)V method_23205
renderItem (Lcom/mojang/blaze3d/matrix/MatrixStack;Lnet/minecraft/client/renderer/IRenderTypeBuffer;Lnet/minecraft/client/entity/AbstractClientPlayer;Lnet/minecraft/client/model/ModelRenderer;Lnet/minecraft/client/model/ModelRenderer;)V method_23205
net/minecraft/client/renderer/entity/layers/LayerCape net/minecraft/class_972
doRenderLayer (Lcom/mojang/blaze3d/matrix/MatrixStack;Lnet/minecraft/client/renderer/IRenderTypeBuffer;ILnet/minecraft/client/entity/AbstractClientPlayer;FFFFFF)V method_4177
doRenderLayer (Lcom/mojang/blaze3d/matrix/MatrixStack;Lnet/minecraft/client/renderer/IRenderTypeBuffer;ILnet/minecraft/client/entity/AbstractClientPlayer;FFFFFFF)V method_4177
net/minecraft/client/renderer/texture/NativeImage net/minecraft/class_1011
net/minecraft/client/renderer/texture/TextureManager net/minecraft/class_1060
net/minecraft/client/resources/SkinManager net/minecraft/class_1071
loadProfileTextures (Lcom/mojang/authlib/GameProfile;Lnet/minecraft/client/resources/SkinManager$SkinAvailableCallback;Z)V method_4652
loadSkin (Lcom/mojang/authlib/minecraft/MinecraftProfileTexture;Lcom/mojang/authlib/minecraft/MinecraftProfileTexture$Type;Lnet/minecraft/client/resources/SkinManager$SkinAvailableCallback;)Lnet/minecraft/util/ResourceLocation; method_4651
loadSkinFromCache (Lcom/mojang/authlib/GameProfile;)Ljava/util/Map; method_4654
net/minecraft/client/resources/SkinManager$SkinAvailableCallback net/minecraft/class_1071$class_1072
net/minecraft/scoreboard/ScoreObjective net/minecraft/class_266
net/minecraft/scoreboard/Scoreboard net/minecraft/class_269
net/minecraft/util/ResourceLocation net/minecraft/class_2960
+20
View File
@@ -0,0 +1,20 @@
{
"schemaVersion": 1,
"id": "customskinloader",
"version": "${modFullVersion}",
"name": "CustomSkinLoader",
"description": "Custom Skin Loader for Minecraft",
"authors": ["xfl03", "JLChnToZ"],
"contact": {
"homepage": "https://github.com/xfl03/MCCustomSkinLoader",
"issues": "https://github.com/xfl03/MCCustomSkinLoader/issues",
"sources": "https://github.com/xfl03/MCCustomSkinLoader"
},
"license": "GPL-3.0-only",
"environment": "client",
"mixins": [
"mixins.customskinloader.json"
]
}
@@ -0,0 +1,22 @@
{
"compatibilityLevel": "JAVA_8",
"mixinPriority": 1010,
"package": "customskinloader.mixin",
"client": [
"MixinGuiPlayerTabOverlay",
"MixinIResource",
"MixinIResourceManager",
"MixinLayerCape",
"MixinMinecraft",
"MixinRenderPlayer",
"MixinSkinManager",
"MixinTextureManager",
"MixinThreadDownloadImageDataV2",
"MixinThreadDownloadImageDataV3"
],
"refmap": "mixins.customskinloader.refmap.json",
"plugin": "customskinloader.fabric.MixinConfigPlugin",
"injectors": {
"defaultRequire": 1
}
}
@@ -0,0 +1,123 @@
package customskinloader.fabric;
import java.lang.reflect.Field;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import com.google.common.collect.Lists;
import net.fabricmc.loader.api.FabricLoader;
import net.fabricmc.loader.impl.FabricLoaderImpl;
import net.fabricmc.loader.impl.game.patch.GameTransformer;
import org.apache.commons.io.IOUtils;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Type;
import org.objectweb.asm.commons.ClassRemapper;
import org.objectweb.asm.commons.SimpleRemapper;
import org.objectweb.asm.tree.ClassNode;
public class DevEnvRemapper extends SimpleRemapper {
// key: correct method owner names,
// value:
// left: fake method owner names,
// right: other classes which contain fake methods.
private static Map<String, Map.Entry<List<String>, List<String>>> remappedClasses = new HashMap<>();
static {
remappedClasses.put(
"net.minecraft.class_310",
new AbstractMap.SimpleEntry<>(
Lists.newArrayList("customskinloader.fake.itf.IFakeMinecraft"),
Lists.newArrayList("customskinloader.fake.itf.FakeInterfaceManager")
)
);
remappedClasses.put(
"net.minecraft.class_1060",
new AbstractMap.SimpleEntry<>(
Lists.newArrayList("customskinloader.fake.itf.IFakeTextureManager$V1", "customskinloader.fake.itf.IFakeTextureManager$V2"),
Lists.newArrayList("customskinloader.fake.itf.FakeInterfaceManager")
)
);
remappedClasses.put(
"net.minecraft.class_3298",
new AbstractMap.SimpleEntry<>(
Lists.newArrayList("customskinloader.fake.itf.IFakeIResource"),
Lists.newArrayList("customskinloader.fake.itf.FakeInterfaceManager")
)
);
remappedClasses.put(
"net.minecraft.class_3300",
new AbstractMap.SimpleEntry<>(
Lists.newArrayList("customskinloader.fake.itf.IFakeIResourceManager"),
Lists.newArrayList("customskinloader.fake.itf.FakeInterfaceManager")
)
);
}
@SuppressWarnings("unchecked")
public static void initRemapper() {
try {
if (FabricLoader.getInstance().isDevelopmentEnvironment()) {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
Field patchedClassesField = GameTransformer.class.getDeclaredField("patchedClasses");
patchedClassesField.setAccessible(true);
Map<String, byte[]> patchedClasses = (Map<String, byte[]>) patchedClassesField.get(FabricLoaderImpl.INSTANCE.getGameProvider().getEntrypointTransformer());
for (Map.Entry<String, Map.Entry<List<String>, List<String>>> entry : remappedClasses.entrySet()) {
List<String> targetClasses = new ArrayList<>(entry.getValue().getKey());
targetClasses.addAll(entry.getValue().getValue());
for (String clazz : targetClasses) {
byte[] classBytes = patchedClasses.get(clazz);
if (classBytes == null) {
classBytes = IOUtils.toByteArray(Objects.requireNonNull(cl.getResourceAsStream(clazz.replace(".", "/") + ".class")));
}
patchedClasses.put(clazz, remapClass(entry.getKey(), classBytes));
}
}
}
} catch (Throwable t) {
MixinConfigPlugin.logger.warning(t);
}
}
// Remap all method names with specific method owner name.
public static byte[] remapClass(String owner, byte[] bytes) {
ClassNode cn = new ClassNode();
new ClassReader(bytes).accept(new ClassRemapper(cn, new DevEnvRemapper(owner)), ClassReader.EXPAND_FRAMES);
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
cn.accept(cw);
return cw.toByteArray();
}
private final String owner;
private final SimpleRemapper remapper = new SimpleRemapper(new HashMap<>()) {
@Override
public String map(String key) {
return FabricLoader.getInstance().getMappingResolver().unmapClassName("intermediary", Type.getType("L" + key + ";").getClassName()).replace(".", "/");
}
};
public DevEnvRemapper(String owner) {
super(new HashMap<>());
this.owner = owner;
}
@Override
public String mapMethodName(String owner, String name, String desc) {
// Method desc should be unmapped in the development environment.
desc = this.remapper.mapDesc(desc);
String s = this.isFakeOwner(owner) ? FabricLoader.getInstance().getMappingResolver().mapMethodName("intermediary", this.owner, name, desc) : name;
return s == null ? name : s;
}
private boolean isFakeOwner(String owner) {
return remappedClasses.get(this.owner).getKey().contains(owner.replace("/", "."));
}
}
@@ -0,0 +1,97 @@
package customskinloader.fabric;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.List;
import java.util.Set;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import customskinloader.Logger;
import org.objectweb.asm.tree.ClassNode;
import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin;
import org.spongepowered.asm.mixin.extensibility.IMixinInfo;
public class MixinConfigPlugin implements IMixinConfigPlugin {
public static Logger logger = new Logger(new File("./CustomSkinLoader/FabricPlugin.log"));
private long world_version;
private long protocol_version;
@Override
public void onLoad(String mixinPackage) {
URL versionJson = this.getClass().getResource("/version.json");
if (versionJson != null) {
logger.info("\"version.json\": " + versionJson.toString());
try (
InputStream is = versionJson.openStream();
InputStreamReader isr = new InputStreamReader(is)
) {
JsonObject object = new JsonParser().parse(isr).getAsJsonObject();
String name = object.get("name").getAsString();
this.world_version = object.get("world_version").getAsLong();
this.protocol_version = object.get("protocol_version").getAsLong();
logger.info("MinecraftVersion: {name='" + name + "', world_version='" + this.world_version + "', protocol_version='" + this.protocol_version + "'}");
} catch (Throwable t) {
logger.warning("An exception occurred when reading \"version.json\"!");
logger.warning(t);
}
} else {
logger.warning("Can't read \"version.json\"! Ignore this message if the version you start is earlier than 18w47b.");
}
// This mod will remap extra classes when in the development environment.
DevEnvRemapper.initRemapper();
}
@Override
public String getRefMapperConfig() {
return null;
}
@Override
public boolean shouldApplyMixin(String targetClassName, String mixinClassName) {
boolean result = true;
if (mixinClassName.endsWith(".MixinThreadDownloadImageDataV2")) {
result = (this.world_version >= 2205 && this.world_version <= 2722) && ((this.protocol_version >= 554 && this.protocol_version <= 754) || (this.protocol_version >= 801 && this.protocol_version <= 803) || (this.protocol_version >= 0x40000001 && this.protocol_version <= 0x40000022)); // 19w38a ~ 1.17-rc1
} else if (mixinClassName.endsWith(".MixinLayerCape") || mixinClassName.endsWith(".MixinRenderPlayer")) {
result = this.world_version >= 2210 && this.protocol_version >= 558; // 19w41a+
} else if (mixinClassName.endsWith(".MixinThreadDownloadImageDataV3")) {
result = this.world_version >= 2723 && ((this.protocol_version >= 755 && this.protocol_version < 801) || (this.protocol_version > 803 && this.protocol_version < 0x40000001) || this.protocol_version >= 0x40000023); // 1.17-rc2+
}
logger.info("target: " + targetClassName + ", mixin: " + mixinClassName + ", result: " + result);
return result;
}
@Override
public void acceptTargets(Set<String> myTargets, Set<String> otherTargets) {
}
@Override
public List<String> getMixins() {
return null;
}
@Override
public void preApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) {
}
@Override
public void postApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) {
}
// To be compatible with 0.7.11
public void preApply(String targetClassName, org.spongepowered.asm.lib.tree.ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) {
}
// To be compatible with 0.7.11
public void postApply(String targetClassName, org.spongepowered.asm.lib.tree.ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) {
}
}
-2
View File
@@ -1,2 +0,0 @@
/bin/
/build/
+70
View File
@@ -0,0 +1,70 @@
customskinloader/fake/itf/IFakeIResource$V1 customskinloader/fake/itf/IFakeIResource$V1
func_199027_b ()Ljava/io/InputStream; m_6679_
customskinloader/fake/itf/IFakeIResource$V2 customskinloader/fake/itf/IFakeIResource$V2
open ()Ljava/io/InputStream; m_215507_
customskinloader/fake/itf/IFakeIResourceManager customskinloader/fake/itf/IFakeIResourceManager
func_199002_a (Lnet/minecraft/util/ResourceLocation;)Lnet/minecraft/resources/IResource; m_142591_
getResource (Lnet/minecraft/util/ResourceLocation;)Ljava/util/Optional; m_213713_
customskinloader/fake/itf/IFakeMinecraft customskinloader/fake/itf/IFakeMinecraft
func_195551_G ()Lnet/minecraft/resources/IResourceManager; m_91098_
customskinloader/fake/itf/IFakeTextureManager$V1 customskinloader/fake/itf/IFakeTextureManager$V1
func_229263_a_ (Lnet/minecraft/util/ResourceLocation;Lnet/minecraft/client/renderer/texture/Texture;)Z func_229263_a_
func_229267_b_ (Lnet/minecraft/util/ResourceLocation;)Lnet/minecraft/client/renderer/texture/Texture; m_118506_
getTexture (Lnet/minecraft/util/ResourceLocation;Lnet/minecraft/client/renderer/texture/Texture;)Lnet/minecraft/client/renderer/texture/Texture; m_174786_
customskinloader/fake/itf/IFakeTextureManager$V2 customskinloader/fake/itf/IFakeTextureManager$V2
func_229263_a_ (Lnet/minecraft/util/ResourceLocation;Lnet/minecraft/client/renderer/texture/Texture;)V m_118495_
net/minecraft/client/Minecraft net/minecraft/client/Minecraft
gameDir f_91069_
addScheduledTask (Ljava/lang/Runnable;)Lcom/google/common/util/concurrent/ListenableFuture; func_152344_a
getCurrentServerData ()Lnet/minecraft/client/multiplayer/ServerData; m_91089_
getMinecraft ()Lnet/minecraft/client/Minecraft; m_91087_
getResourceManager ()Lnet/minecraft/client/resources/IResourceManager; m_91098_
getSessionService ()Lcom/mojang/authlib/minecraft/MinecraftSessionService; m_91108_
getSkinManager ()Lnet/minecraft/client/resources/SkinManager; m_91109_
getTextureManager ()Lnet/minecraft/client/renderer/texture/TextureManager; m_91097_
net/minecraft/client/gui/GuiPlayerTabOverlay net/minecraft/client/gui/components/PlayerTabOverlay
net/minecraft/client/gui/spectator/PlayerMenuObject net/minecraft/client/gui/spectator/PlayerMenuItem
net/minecraft/client/multiplayer/ServerData net/minecraft/client/multiplayer/ServerData
serverIP f_105363_
net/minecraft/client/renderer/RenderType net/minecraft/client/renderer/RenderType
func_228644_e_ (Lnet/minecraft/util/ResourceLocation;)Lnet/minecraft/client/renderer/RenderType; m_110473_
net/minecraft/client/renderer/IImageBuffer customskinloader/fake/IFakeImageBuffer
func_195786_a (Lnet/minecraft/client/renderer/texture/NativeImage;)Lnet/minecraft/client/renderer/texture/NativeImage; func_195786_a
parseUserSkin (Ljava/awt/image/BufferedImage;)Ljava/awt/image/BufferedImage; parseUserSkin
skinAvailable ()V skinAvailable
net/minecraft/client/renderer/ThreadDownloadImageData net/minecraft/client/renderer/texture/HttpTexture
net/minecraft/client/renderer/entity/RenderPlayer net/minecraft/client/renderer/entity/player/PlayerRenderer
net/minecraft/client/renderer/entity/layers/LayerCape net/minecraft/client/renderer/entity/layers/CapeLayer
net/minecraft/client/renderer/texture/DownloadingTexture net/minecraft/client/renderer/texture/HttpTexture
net/minecraft/client/renderer/texture/ITextureObject net/minecraft/client/renderer/texture/ITextureObject
net/minecraft/client/renderer/texture/NativeImage com/mojang/blaze3d/platform/NativeImage
func_195699_a (IIIIIIZZ)V m_85025_
func_195700_a (III)V m_84988_
func_195702_a ()I m_84982_
func_195703_a (Lnet/minecraft/client/renderer/texture/NativeImage;)V m_85054_
func_195709_a (II)I m_84985_
func_195713_a (Ljava/io/InputStream;)Lnet/minecraft/client/renderer/texture/NativeImage; m_85058_
func_195714_b ()I m_85084_
func_195715_a (IIIII)V m_84997_
net/minecraft/client/renderer/texture/SimpleTexture net/minecraft/client/renderer/texture/SimpleTexture
net/minecraft/client/renderer/texture/Texture net/minecraft/client/renderer/texture/AbstractTexture
net/minecraft/client/renderer/texture/TextureManager net/minecraft/client/renderer/texture/TextureManager
getTexture (Lnet/minecraft/util/ResourceLocation;)Lnet/minecraft/client/renderer/texture/ITextureObject; func_110581_b
loadTexture (Lnet/minecraft/util/ResourceLocation;Lnet/minecraft/client/renderer/texture/ITextureObject;)Z func_110579_a
net/minecraft/client/renderer/texture/ThreadDownloadImageData net/minecraft/client/renderer/texture/HttpTexture
net/minecraft/client/resources/DefaultPlayerSkin net/minecraft/client/resources/DefaultPlayerSkin
getDefaultSkin (Ljava/util/UUID;)Lnet/minecraft/util/ResourceLocation; m_118627_
getDefaultSkinLegacy ()Lnet/minecraft/util/ResourceLocation; m_118626_
net/minecraft/client/resources/IResource net/minecraft/server/packs/resources/Resource
getInputStream ()Ljava/io/InputStream; m_6679_
net/minecraft/client/resources/IResourceManager net/minecraft/server/packs/resources/ResourceManager
getResource (Lnet/minecraft/util/ResourceLocation;)Lnet/minecraft/client/resources/IResource; m_142591_
net/minecraft/client/resources/SkinManager net/minecraft/client/resources/SkinManager
loadProfileTextures (Lcom/mojang/authlib/GameProfile;Lnet/minecraft/client/resources/SkinManager$SkinAvailableCallback;Z)V m_118817_
net/minecraft/client/resources/SkinManager$SkinAvailableCallback net/minecraft/client/resources/SkinManager$SkinTextureCallback
skinAvailable (Lcom/mojang/authlib/minecraft/MinecraftProfileTexture$Type;Lnet/minecraft/util/ResourceLocation;Lcom/mojang/authlib/minecraft/MinecraftProfileTexture;)V m_118856_
net/minecraft/resources/IResource net/minecraft/server/packs/resources/Resource
net/minecraft/resources/IResourceManager net/minecraft/server/packs/resources/ResourceManager
net/minecraft/util/ResourceLocation net/minecraft/resources/ResourceLocation
net/minecraft/util/StringUtils net/minecraft/util/StringUtil
stripControlCodes (Ljava/lang/String;)Ljava/lang/String; m_14406_
+27
View File
@@ -0,0 +1,27 @@
jar {
manifest {
attributes([
"Automatic-Module-Name" : "customskinloader"
])
}
exclude 'net/minecraft/client/renderer/RenderType.class'
exclude 'net/minecraft/client/renderer/texture/**'
exclude 'net/minecraft/client/resources/**'
exclude 'net/minecraft/resources/**'
}
sourceJar {
exclude 'com/**'
exclude 'net/**'
}
dependencies {
implementation project(":Forge/Common")
}
import customskinloader.gradle.util.RemapUtil
import customskinloader.gradle.util.SourceUtil
RemapUtil.remapSources project
SourceUtil.addDependencies project, project(":Common")
+8
View File
@@ -0,0 +1,8 @@
minecraft_version=1.17.1
minecraft_full_versions=1.17.1,1.18,1.18.1,1.18.2,1.19,1.19.1,1.19.2
java_full_versions=16,17,18
#forge gradle needs forge version
forge_mc_version=1.12.2
forge_version=14.23.5.2768
mappings_version=stable_39
srg_notch_map=Forge.tsrg
@@ -0,0 +1,3 @@
{
"transformers": "transformers.js"
}
+25
View File
@@ -0,0 +1,25 @@
modLoader="javafml"
loaderVersion="[37,)"
license="GPL-3.0-only"
issueTrackerURL="https://github.com/xfl03/MCCustomSkinLoader/issues"
[[mods]]
modId="customskinloader"
version="${modFullVersion}"
displayName="CustomSkinLoader"
description='''
Custom Skin Loader for Minecraft
'''
displayURL="https://github.com/xfl03/MCCustomSkinLoader"
authors=["xfl03", "JLChnToZ"]
[[dependencies.customskinloader]]
modId="forge"
mandatory=true
versionRange="[37,)"
ordering="NONE"
side="CLIENT"
[[dependencies.customskinloader]]
modId="minecraft"
mandatory=true
versionRange="[1.17.1,)"
ordering="NONE"
side="CLIENT"
+6
View File
@@ -0,0 +1,6 @@
{
"pack": {
"description": "CustomSkinLoader resources",
"pack_format": 7
}
}
+197
View File
@@ -0,0 +1,197 @@
var ASMAPI = getJavaType('net.minecraftforge.coremod.api.ASMAPI');
var Handle = getJavaType('org.objectweb.asm.Handle');
var Opcodes = getJavaType('org.objectweb.asm.Opcodes');
var Type = getJavaType('org.objectweb.asm.Type');
var FieldInsnNode = getJavaType('org.objectweb.asm.tree.FieldInsnNode');
var FieldNode = getJavaType('org.objectweb.asm.tree.FieldNode');
var InsnNode = getJavaType('org.objectweb.asm.tree.InsnNode');
var InvokeDynamicInsnNode = getJavaType('org.objectweb.asm.tree.InvokeDynamicInsnNode');
var MethodInsnNode = getJavaType('org.objectweb.asm.tree.MethodInsnNode');
var TypeInsnNode = getJavaType('org.objectweb.asm.tree.TypeInsnNode');
var VarInsnNode = getJavaType('org.objectweb.asm.tree.VarInsnNode');
function getJavaType(name) {
return Java.type(name);
}
// Compare method and field names.
function checkName(name, srgName) {
return name.equals(mapName(srgName));
}
// De-obfuscate method and field names.
function mapName(srgName) {
if (srgName.startsWith("f_")) return ASMAPI.mapField(srgName);
if (srgName.startsWith("m_")) return ASMAPI.mapMethod(srgName);
return srgName;
}
function initializeCoreMod() {
return {
'SkinManagerTransformer': {
'target': {
'type': 'CLASS',
'name': 'net/minecraft/client/resources/SkinManager'
},
'transformer': function (cn) {
cn.fields.removeIf(function (fn) {
return fn.name.equals("fakeManager") && fn.desc.equals("Lcustomskinloader/fake/FakeSkinManager;");
});
cn.fields.add(new FieldNode(Opcodes.ACC_PRIVATE, "fakeManager", "Lcustomskinloader/fake/FakeSkinManager;", null, null));
cn.methods.forEach(function (mn) {
if (checkName(mn.name, "<init>") && mn.desc.equals("(Lnet/minecraft/client/renderer/texture/TextureManager;Ljava/io/File;Lcom/mojang/authlib/minecraft/MinecraftSessionService;)V")) {
for (var iterator = mn.instructions.iterator(); iterator.hasNext();) {
var node = iterator.next();
if (node.getOpcode() === Opcodes.RETURN) {
mn.instructions.insertBefore(node, new VarInsnNode(Opcodes.ALOAD, 0));
mn.instructions.insertBefore(node, new TypeInsnNode(Opcodes.NEW, "customskinloader/fake/FakeSkinManager"));
mn.instructions.insertBefore(node, new InsnNode(Opcodes.DUP));
mn.instructions.insertBefore(node, new VarInsnNode(Opcodes.ALOAD, 1));
mn.instructions.insertBefore(node, new VarInsnNode(Opcodes.ALOAD, 2));
mn.instructions.insertBefore(node, new VarInsnNode(Opcodes.ALOAD, 3));
mn.instructions.insertBefore(node, new MethodInsnNode(Opcodes.INVOKESPECIAL, "customskinloader/fake/FakeSkinManager", "<init>", "(Lnet/minecraft/client/renderer/texture/TextureManager;Ljava/io/File;Lcom/mojang/authlib/minecraft/MinecraftSessionService;)V", false));
mn.instructions.insertBefore(node, new FieldInsnNode(Opcodes.PUTFIELD, "net/minecraft/client/resources/SkinManager", "fakeManager", "Lcustomskinloader/fake/FakeSkinManager;"));
}
}
} else if (checkName(mn.name, "m_118828_") && mn.desc.equals("(Lcom/mojang/authlib/minecraft/MinecraftProfileTexture;Lcom/mojang/authlib/minecraft/MinecraftProfileTexture$Type;Lnet/minecraft/client/resources/SkinManager$SkinTextureCallback;)Lnet/minecraft/resources/ResourceLocation;")) {
var first = mn.instructions.getFirst();
mn.instructions.insertBefore(first, new VarInsnNode(Opcodes.ALOAD, 0));
mn.instructions.insertBefore(first, new FieldInsnNode(Opcodes.GETFIELD, "net/minecraft/client/resources/SkinManager", "fakeManager", "Lcustomskinloader/fake/FakeSkinManager;"));
mn.instructions.insertBefore(first, new VarInsnNode(Opcodes.ALOAD, 1));
mn.instructions.insertBefore(first, new VarInsnNode(Opcodes.ALOAD, 2));
mn.instructions.insertBefore(first, new VarInsnNode(Opcodes.ALOAD, 3));
mn.instructions.insertBefore(first, new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "customskinloader/fake/FakeSkinManager", "loadSkin", "(Lcom/mojang/authlib/minecraft/MinecraftProfileTexture;Lcom/mojang/authlib/minecraft/MinecraftProfileTexture$Type;Lnet/minecraft/client/resources/SkinManager$SkinTextureCallback;)Lnet/minecraft/resources/ResourceLocation;", false));
mn.instructions.insertBefore(first, new InsnNode(Opcodes.ARETURN));
} else if (checkName(mn.name, "m_118817_") && mn.desc.equals("(Lcom/mojang/authlib/GameProfile;Lnet/minecraft/client/resources/SkinManager$SkinTextureCallback;Z)V")) {
var first = mn.instructions.getFirst();
mn.instructions.insertBefore(first, new VarInsnNode(Opcodes.ALOAD, 0));
mn.instructions.insertBefore(first, new FieldInsnNode(Opcodes.GETFIELD, "net/minecraft/client/resources/SkinManager", "fakeManager", "Lcustomskinloader/fake/FakeSkinManager;"));
mn.instructions.insertBefore(first, new VarInsnNode(Opcodes.ALOAD, 1));
mn.instructions.insertBefore(first, new VarInsnNode(Opcodes.ALOAD, 2));
mn.instructions.insertBefore(first, new VarInsnNode(Opcodes.ILOAD, 3));
mn.instructions.insertBefore(first, new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "customskinloader/fake/FakeSkinManager", "loadProfileTextures", "(Lcom/mojang/authlib/GameProfile;Lnet/minecraft/client/resources/SkinManager$SkinTextureCallback;Z)V", false));
mn.instructions.insertBefore(first, new InsnNode(Opcodes.RETURN));
} else if (checkName(mn.name, "m_118815_") && mn.desc.equals("(Lcom/mojang/authlib/GameProfile;)Ljava/util/Map;")) {
var first = mn.instructions.getFirst();
mn.instructions.insertBefore(first, new VarInsnNode(Opcodes.ALOAD, 0));
mn.instructions.insertBefore(first, new FieldInsnNode(Opcodes.GETFIELD, "net/minecraft/client/resources/SkinManager", "fakeManager", "Lcustomskinloader/fake/FakeSkinManager;"));
mn.instructions.insertBefore(first, new VarInsnNode(Opcodes.ALOAD, 1));
mn.instructions.insertBefore(first, new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "customskinloader/fake/FakeSkinManager", "loadSkinFromCache", "(Lcom/mojang/authlib/GameProfile;)Ljava/util/Map;", false));
mn.instructions.insertBefore(first, new InsnNode(Opcodes.ARETURN));
}
});
return cn;
}
},
'IResourceTransformer': {
'target': {
'type': 'CLASS',
'name': 'net/minecraft/server/packs/resources/Resource'
},
'transformer': function (cn) {
cn.interfaces.add("customskinloader/fake/itf/IFakeIResource$V1");
cn.interfaces.add("customskinloader/fake/itf/IFakeIResource$V2");
return cn;
}
},
'IResourceManagerTransformer': {
'target': {
'type': 'CLASS',
'name': 'net/minecraft/server/packs/resources/ResourceManager'
},
'transformer': function (cn) {
cn.interfaces.add("customskinloader/fake/itf/IFakeIResourceManager");
return cn;
}
},
'MinecraftTransformer': {
'target': {
'type': 'CLASS',
'name': 'net/minecraft/client/Minecraft'
},
'transformer': function (cn) {
cn.interfaces.add("customskinloader/fake/itf/IFakeMinecraft");
return cn;
}
},
'TextureManagerTransformer': {
'target': {
'type': 'CLASS',
'name': 'net/minecraft/client/renderer/texture/TextureManager'
},
'transformer': function (cn) {
cn.interfaces.add("customskinloader/fake/itf/IFakeTextureManager$V1");
cn.interfaces.add("customskinloader/fake/itf/IFakeTextureManager$V2");
return cn;
}
},
'RenderPlayer_LayerCapeTransformer': {
'target': {
'type': 'CLASS',
'names': function (target) {
return ['net/minecraft/client/renderer/entity/player/PlayerRenderer', 'net/minecraft/client/renderer/entity/layers/CapeLayer'];
}
},
'transformer': function (cn) {
cn.methods.forEach(function (mn) {
if ((checkName(mn.name, "m_117775_") && mn.desc.equals("(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;ILnet/minecraft/client/player/AbstractClientPlayer;Lnet/minecraft/client/model/geom/ModelPart;Lnet/minecraft/client/model/geom/ModelPart;)V")) // PlayerRenderer.renderHand
|| (checkName(mn.name, "m_6494_") && mn.desc.equals("(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;ILnet/minecraft/client/player/AbstractClientPlayer;FFFFFF)V"))) { // CapeLayer.render
for (var iterator = mn.instructions.iterator(); iterator.hasNext();) {
var node = iterator.next();
if (node.getOpcode() === Opcodes.INVOKESTATIC && node.owner.equals("net/minecraft/client/renderer/RenderType") && checkName(node.name, "m_110446_") && node.desc.equals("(Lnet/minecraft/resources/ResourceLocation;)Lnet/minecraft/client/renderer/RenderType;")) { // RenderType.entitySolid
node.name = mapName("m_110473_"); // RenderType.entityTranslucent
}
}
}
});
return cn;
}
},
'HttpTextureTransformer': {
'target': {
'type': 'METHOD',
'class': 'net/minecraft/client/renderer/texture/HttpTexture',
'methodName': 'm_118018_',
'methodDesc': '(Ljava/io/InputStream;)Lcom/mojang/blaze3d/platform/NativeImage;'
},
'transformer': function (mn) {
for (var iterator = mn.instructions.iterator(); iterator.hasNext();) {
var node = iterator.next();
if ((node.getOpcode() === Opcodes.INVOKEVIRTUAL || node.getOpcode() === Opcodes.INVOKESPECIAL) && node.owner.equals("net/minecraft/client/renderer/texture/HttpTexture") && checkName(node.name, "m_118032_") && node.desc.equals("(Lcom/mojang/blaze3d/platform/NativeImage;)Lcom/mojang/blaze3d/platform/NativeImage;")) {
// FakeSkinBuffer.processLegacySkin(image, this.onDownloaded, this::processLegacySkin);
mn.instructions.insertBefore(node, new InsnNode(Opcodes.SWAP));
mn.instructions.insertBefore(node, new FieldInsnNode(Opcodes.GETFIELD, "net/minecraft/client/renderer/texture/HttpTexture", mapName("f_117997_"), "Ljava/lang/Runnable;"));
mn.instructions.insertBefore(node, new VarInsnNode(Opcodes.ALOAD, 0));
mn.instructions.insertBefore(node, new InvokeDynamicInsnNode("apply", "(Lnet/minecraft/client/renderer/texture/HttpTexture;)Ljava/util/function/Function;",
/* bsm */ new Handle(Opcodes.H_INVOKESTATIC, "java/lang/invoke/LambdaMetafactory", "metafactory", "(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;", false),
/* bsmArgs */ Type.getType("(Ljava/lang/Object;)Ljava/lang/Object;"),
/* bsmArgs */ new Handle(Opcodes.H_INVOKEVIRTUAL, "net/minecraft/client/renderer/texture/HttpTexture", mapName("m_118032_"), "(Lcom/mojang/blaze3d/platform/NativeImage;)Lcom/mojang/blaze3d/platform/NativeImage;", false),
/* bsmArgs */ Type.getType("(Lcom/mojang/blaze3d/platform/NativeImage;)Lcom/mojang/blaze3d/platform/NativeImage;")));
iterator.set(new MethodInsnNode(Opcodes.INVOKESTATIC, "customskinloader/fake/FakeSkinBuffer", "processLegacySkin", "(Lcom/mojang/blaze3d/platform/NativeImage;Ljava/lang/Runnable;Ljava/util/function/Function;)Lcom/mojang/blaze3d/platform/NativeImage;", false));
}
}
return mn;
}
},
'PlayerTabOverlayTransformer': {
'target': {
'type': 'METHOD',
'class': 'net/minecraft/client/gui/components/PlayerTabOverlay',
'methodName': 'm_94544_',
'methodDesc': '(Lcom/mojang/blaze3d/vertex/PoseStack;ILnet/minecraft/world/scores/Scoreboard;Lnet/minecraft/world/scores/Objective;)V'
},
'transformer': function (mn) {
for (var iterator = mn.instructions.iterator(); iterator.hasNext();) {
var node = iterator.next();
if (node.getOpcode() === Opcodes.INVOKEVIRTUAL && node.owner.equals("net/minecraft/client/Minecraft") && checkName(node.name, "m_91090_") && node.desc.equals("()Z")) {
mn.instructions.insertBefore(node, new InsnNode(Opcodes.POP));
mn.instructions.set(node, new InsnNode(Opcodes.ICONST_1));
}
}
return mn;
}
},
};
}
@@ -0,0 +1,16 @@
package customskinloader.forge;
import net.minecraftforge.fml.IExtensionPoint;
import net.minecraftforge.fml.ModLoadingContext;
import net.minecraftforge.fml.common.Mod;
@Mod("customskinloader")
public class ForgeMod {
public ForgeMod() {
this.setExtensionPoint();
}
private void setExtensionPoint() {
ModLoadingContext.get().registerExtensionPoint(IExtensionPoint.DisplayTest.class, () -> new IExtensionPoint.DisplayTest(() -> "customskinloader", (remote, isServer) -> isServer));
}
}
+5
View File
@@ -0,0 +1,5 @@
forge_mc_version=1.12.2
forge_version=14.23.5.2768
mappings_version=stable_39
# this subproject is only to provide dependency for other subprojects.
is_real_project=false
@@ -0,0 +1,10 @@
package net.minecraftforge.fml;
import java.util.function.BiPredicate;
import java.util.function.Supplier;
import org.apache.commons.lang3.tuple.Pair;
public class ExtensionPoint<T> {
public static ExtensionPoint<Pair<Supplier<String>, BiPredicate<String, Boolean>>> DISPLAYTEST;
}
@@ -0,0 +1,10 @@
package net.minecraftforge.fml;
import java.util.function.BiPredicate;
import java.util.function.Supplier;
public interface IExtensionPoint<T> {
class DisplayTest implements IExtensionPoint<DisplayTest> {
public DisplayTest(Supplier<String> suppliedVersion, BiPredicate<String, Boolean> remoteVersionTest) {}
}
}
@@ -0,0 +1,17 @@
package net.minecraftforge.fml;
import java.util.function.Supplier;
public class ModLoadingContext {
public static ModLoadingContext get() {
return null;
}
public <T> void registerExtensionPoint(ExtensionPoint<T> point, Supplier<T> extension) {
}
public <T> void registerExtensionPoint(Class<? extends IExtensionPoint<T>> point, Supplier<T> extension) {
}
}
@@ -0,0 +1,34 @@
package net.minecraftforge.fml.common;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
//https://github.com/MinecraftForge/MinecraftForge/blob/1.13.x/src/main/java/net/minecraftforge/fml/common/Mod.java
//https://github.com/MinecraftForge/MinecraftForge/blob/1.12.x/src/main/java/net/minecraftforge/fml/common/Mod.java
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Mod {
String value();
String modid() default "";
String name() default "";
String version() default "";
boolean clientSideOnly() default false;
String acceptedMinecraftVersions() default "";
String acceptableRemoteVersions() default "";
String certificateFingerprint() default "";
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface EventHandler {
}
}
+33
View File
@@ -0,0 +1,33 @@
jar {
manifest {
attributes([
"TweakClass": "customskinloader.forge.ForgeTweaker",
"TweakOrder": -10
])
}
exclude 'net/minecraft/client/renderer/texture/**'
exclude 'net/minecraft/client/resources/SkinManager.class'
exclude 'net/minecraft/client/resources/SkinManager$ISkinAvailableCallback.class'
exclude 'net/minecraft/resources/**'
}
sourceJar {
exclude 'net/**'
}
tasks.signJar {
// To prevent modlauncher from checking signer information about Minecraft classes in CustomSkinLoader jar after forge-1.16.3-34.1.27.
exclude "net/minecraft/client/**"
}
dependencies {
implementation project(":Forge/Common")
}
minecraft {
replaceIn 'ForgeMod.java'
}
import customskinloader.gradle.util.SourceUtil
SourceUtil.addDependencies project, project(":Common")
+7
View File
@@ -0,0 +1,7 @@
minecraft_version=1.12.2
minecraft_full_versions=1.8,1.8.8,1.8.9,1.9,1.9.4,1.10,1.10.2,1.11,1.11.2,1.12,1.12.1,1.12.2,1.13.2,1.14.2,1.14.3,1.14.4,1.15,1.15.1,1.15.2,1.16.1,1.16.2,1.16.3,1.16.4,1.16.5
java_full_versions=8,9,10,11,12,13,14,15,16,17,18
#forge gradle needs forge version
forge_mc_version=1.12.2
forge_version=14.23.5.2768
mappings_version=stable_39
@@ -0,0 +1,3 @@
{
"transformers": "transformers.js"
}
+25
View File
@@ -0,0 +1,25 @@
modLoader="javafml"
loaderVersion="[25,37)"
license="GPL-3.0-only"
issueTrackerURL="https://github.com/xfl03/MCCustomSkinLoader/issues"
[[mods]]
modId="customskinloader"
version="${modFullVersion}"
displayName="CustomSkinLoader"
description='''
Custom Skin Loader for Minecraft
'''
displayURL="https://github.com/xfl03/MCCustomSkinLoader"
authors=["xfl03", "JLChnToZ"]
[[dependencies.customskinloader]]
modId="forge"
mandatory=true
versionRange="[25.0.9,25.0.22],[25.0.42,37.0.0)" # incompatible with CoreMods-0.3.0
ordering="NONE"
side="CLIENT"
[[dependencies.customskinloader]]
modId="minecraft"
mandatory=true
versionRange="[1.13.2,1.17.0)"
ordering="NONE"
side="CLIENT"
@@ -0,0 +1 @@
customskinloader.forge.platform.DefaultFMLPlatform
+10
View File
@@ -0,0 +1,10 @@
[
{
"modid": "customskinloader",
"name": "CustomSkinLoader",
"description": "Custom Skin Loader for Minecraft",
"version": "${modFullVersion}",
"url": "https://github.com/xfl03/MCCustomSkinLoader",
"authorList": ["xfl03", "JLChnToZ"]
}
]
+6
View File
@@ -0,0 +1,6 @@
{
"pack": {
"description": "CustomSkinLoader resources",
"pack_format": 4
}
}
+258
View File
@@ -0,0 +1,258 @@
var ASMAPI = getJavaType('net.minecraftforge.coremod.api.ASMAPI');
var Handle = getJavaType('org.objectweb.asm.Handle');
var Opcodes = getJavaType('org.objectweb.asm.Opcodes');
var Type = getJavaType('org.objectweb.asm.Type');
var FieldInsnNode = getJavaType('org.objectweb.asm.tree.FieldInsnNode');
var FieldNode = getJavaType('org.objectweb.asm.tree.FieldNode');
var InsnNode = getJavaType('org.objectweb.asm.tree.InsnNode');
var InvokeDynamicInsnNode = getJavaType('org.objectweb.asm.tree.InvokeDynamicInsnNode');
var JumpInsnNode = getJavaType('org.objectweb.asm.tree.JumpInsnNode');
var LabelNode = getJavaType('org.objectweb.asm.tree.LabelNode');
var MethodInsnNode = getJavaType('org.objectweb.asm.tree.MethodInsnNode');
var MethodNode = getJavaType('org.objectweb.asm.tree.MethodNode');
var TypeInsnNode = getJavaType('org.objectweb.asm.tree.TypeInsnNode');
var VarInsnNode = getJavaType('org.objectweb.asm.tree.VarInsnNode');
function getJavaType(name) {
try {
return Java.type(name);
} catch (ignored) {
// forge-1.13.2-25.0.23 ~ 1.13.2-25.0.41
return null;
}
}
// Compare method and field names, doesn't support forge-1.13.2-25.0.194 and earlier version.
function checkName(name, srgName) {
return name.equals(mapName(srgName));
}
// De-obfuscate method and field names.
function mapName(srgName) {
try {
if (srgName.startsWith("field_")) return ASMAPI.mapField(srgName);
if (srgName.startsWith("func_")) return ASMAPI.mapMethod(srgName);
} catch (ignored) {
// Before forge-1.13.2-25.0.194
}
return srgName;
}
function initializeCoreMod() {
return {
'SkinManagerTransformer': {
'target': {
'type': 'CLASS',
'name': 'net/minecraft/client/resources/SkinManager'
},
'transformer': function (cn) {
cn.fields.removeIf(function (fn) {
return fn.name.equals("fakeManager") && fn.desc.equals("Lcustomskinloader/fake/FakeSkinManager;");
});
cn.fields.add(new FieldNode(Opcodes.ACC_PRIVATE, "fakeManager", "Lcustomskinloader/fake/FakeSkinManager;", null, null));
cn.methods.forEach(function (mn) {
if (checkName(mn.name, "<init>") && mn.desc.equals("(Lnet/minecraft/client/renderer/texture/TextureManager;Ljava/io/File;Lcom/mojang/authlib/minecraft/MinecraftSessionService;)V")) {
for (var iterator = mn.instructions.iterator(); iterator.hasNext();) {
var node = iterator.next();
if (node.getOpcode() === Opcodes.RETURN) {
mn.instructions.insertBefore(node, new VarInsnNode(Opcodes.ALOAD, 0));
mn.instructions.insertBefore(node, new TypeInsnNode(Opcodes.NEW, "customskinloader/fake/FakeSkinManager"));
mn.instructions.insertBefore(node, new InsnNode(Opcodes.DUP));
mn.instructions.insertBefore(node, new VarInsnNode(Opcodes.ALOAD, 1));
mn.instructions.insertBefore(node, new VarInsnNode(Opcodes.ALOAD, 2));
mn.instructions.insertBefore(node, new VarInsnNode(Opcodes.ALOAD, 3));
mn.instructions.insertBefore(node, new MethodInsnNode(Opcodes.INVOKESPECIAL, "customskinloader/fake/FakeSkinManager", "<init>", "(Lnet/minecraft/client/renderer/texture/TextureManager;Ljava/io/File;Lcom/mojang/authlib/minecraft/MinecraftSessionService;)V", false));
mn.instructions.insertBefore(node, new FieldInsnNode(Opcodes.PUTFIELD, "net/minecraft/client/resources/SkinManager", "fakeManager", "Lcustomskinloader/fake/FakeSkinManager;"));
}
}
} else if (checkName(mn.name, "func_152789_a")
&& (mn.desc.equals("(Lcom/mojang/authlib/minecraft/MinecraftProfileTexture;Lcom/mojang/authlib/minecraft/MinecraftProfileTexture$Type;Lnet/minecraft/client/resources/SkinManager$SkinAvailableCallback;)Lnet/minecraft/util/ResourceLocation;") // 1.13.2-
|| mn.desc.equals("(Lcom/mojang/authlib/minecraft/MinecraftProfileTexture;Lcom/mojang/authlib/minecraft/MinecraftProfileTexture$Type;Lnet/minecraft/client/resources/SkinManager$ISkinAvailableCallback;)Lnet/minecraft/util/ResourceLocation;"))) { // 1.14.2+
var first = mn.instructions.getFirst();
mn.instructions.insertBefore(first, new VarInsnNode(Opcodes.ALOAD, 0));
mn.instructions.insertBefore(first, new FieldInsnNode(Opcodes.GETFIELD, "net/minecraft/client/resources/SkinManager", "fakeManager", "Lcustomskinloader/fake/FakeSkinManager;"));
mn.instructions.insertBefore(first, new VarInsnNode(Opcodes.ALOAD, 1));
mn.instructions.insertBefore(first, new VarInsnNode(Opcodes.ALOAD, 2));
mn.instructions.insertBefore(first, new VarInsnNode(Opcodes.ALOAD, 3));
mn.instructions.insertBefore(first, new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "customskinloader/fake/FakeSkinManager", "loadSkin", "(Lcom/mojang/authlib/minecraft/MinecraftProfileTexture;Lcom/mojang/authlib/minecraft/MinecraftProfileTexture$Type;Lnet/minecraft/client/resources/SkinManager$SkinAvailableCallback;)Lnet/minecraft/util/ResourceLocation;", false));
mn.instructions.insertBefore(first, new InsnNode(Opcodes.ARETURN));
} else if (checkName(mn.name, "func_152790_a")
&& (mn.desc.equals("(Lcom/mojang/authlib/GameProfile;Lnet/minecraft/client/resources/SkinManager$SkinAvailableCallback;Z)V") // 1.13.2-
|| mn.desc.equals("(Lcom/mojang/authlib/GameProfile;Lnet/minecraft/client/resources/SkinManager$ISkinAvailableCallback;Z)V"))) { // 1.14.2+
var first = mn.instructions.getFirst();
mn.instructions.insertBefore(first, new VarInsnNode(Opcodes.ALOAD, 0));
mn.instructions.insertBefore(first, new FieldInsnNode(Opcodes.GETFIELD, "net/minecraft/client/resources/SkinManager", "fakeManager", "Lcustomskinloader/fake/FakeSkinManager;"));
mn.instructions.insertBefore(first, new VarInsnNode(Opcodes.ALOAD, 1));
mn.instructions.insertBefore(first, new VarInsnNode(Opcodes.ALOAD, 2));
mn.instructions.insertBefore(first, new VarInsnNode(Opcodes.ILOAD, 3));
mn.instructions.insertBefore(first, new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "customskinloader/fake/FakeSkinManager", "loadProfileTextures", "(Lcom/mojang/authlib/GameProfile;Lnet/minecraft/client/resources/SkinManager$SkinAvailableCallback;Z)V", false));
mn.instructions.insertBefore(first, new InsnNode(Opcodes.RETURN));
} else if (checkName(mn.name, "func_152788_a") && mn.desc.equals("(Lcom/mojang/authlib/GameProfile;)Ljava/util/Map;")) {
var first = mn.instructions.getFirst();
mn.instructions.insertBefore(first, new VarInsnNode(Opcodes.ALOAD, 0));
mn.instructions.insertBefore(first, new FieldInsnNode(Opcodes.GETFIELD, "net/minecraft/client/resources/SkinManager", "fakeManager", "Lcustomskinloader/fake/FakeSkinManager;"));
mn.instructions.insertBefore(first, new VarInsnNode(Opcodes.ALOAD, 1));
mn.instructions.insertBefore(first, new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "customskinloader/fake/FakeSkinManager", "loadSkinFromCache", "(Lcom/mojang/authlib/GameProfile;)Ljava/util/Map;", false));
mn.instructions.insertBefore(first, new InsnNode(Opcodes.ARETURN));
}
});
return cn;
}
},
'PlayerTabTransformer': {
'target': {
'type': 'CLASS',
'names': function (target) {
return ['net/minecraft/client/gui/GuiPlayerTabOverlay', 'net/minecraft/client/gui/overlay/PlayerTabOverlayGui'];
}
},
'transformer': function (cn) {
cn.methods.forEach(function (mn) {
if ((checkName(mn.name, "func_175249_a") && mn.desc.equals("(ILnet/minecraft/scoreboard/Scoreboard;Lnet/minecraft/scoreboard/ScoreObjective;)V")) // 1.15.2-
|| (checkName(mn.name, "func_238523_a_") && mn.desc.equals("(Lcom/mojang/blaze3d/matrix/MatrixStack;ILnet/minecraft/scoreboard/Scoreboard;Lnet/minecraft/scoreboard/ScoreObjective;)V"))) { // 1.16.1+
for (var iterator = mn.instructions.iterator(); iterator.hasNext();) {
var node = iterator.next();
if (node.getOpcode() === Opcodes.INVOKEVIRTUAL && node.owner.equals("net/minecraft/client/Minecraft") && checkName(node.name, "func_71387_A") && node.desc.equals("()Z")) {
mn.instructions.insertBefore(node, new InsnNode(Opcodes.POP));
mn.instructions.set(node, new InsnNode(Opcodes.ICONST_1));
}
}
}
});
return cn;
}
},
// For 1.13+
'AbstractTextureTransformer': {
'target': {
'type': 'CLASS',
'name': 'net/minecraft/client/renderer/texture/AbstractTexture'
},
'transformer': function (cn) {
cn.interfaces.add("net/minecraft/client/renderer/texture/Texture");
return cn;
}
},
'TextureTransformer': {
'target': {
'type': 'CLASS',
'name': 'net/minecraft/client/renderer/texture/Texture'
},
'transformer': function (cn) {
if (cn.access === 0) {
cn.access = Opcodes.ACC_PUBLIC | Opcodes.ACC_INTERFACE | Opcodes.ACC_ABSTRACT;
}
return cn;
}
},
// For 1.14+
'MinecraftTransformer': {
'target': {
'type': 'CLASS',
'name': 'net/minecraft/client/Minecraft'
},
'transformer': function (cn) {
cn.interfaces.add("customskinloader/fake/itf/IFakeMinecraft");
return cn;
}
},
'IResourceTransformer': {
'target': {
'type': 'CLASS',
'name': 'net/minecraft/resources/IResource'
},
'transformer': function (cn) {
cn.interfaces.add("customskinloader/fake/itf/IFakeIResource$V1");
cn.interfaces.add("customskinloader/fake/itf/IFakeIResource$V2");
cn.interfaces.add("net/minecraft/client/resources/IResource");
return cn;
}
},
'IResourceManagerTransformer': {
'target': {
'type': 'CLASS',
'name': 'net/minecraft/resources/IResourceManager'
},
'transformer': function (cn) {
cn.interfaces.add("customskinloader/fake/itf/IFakeIResourceManager");
cn.interfaces.add("net/minecraft/client/resources/IResourceManager");
return cn;
}
},
'ISkinAvailableCallbackTransformer': {
'target': {
'type': 'CLASS',
'name': 'net/minecraft/client/resources/SkinManager$ISkinAvailableCallback'
},
'transformer': function (cn) {
cn.interfaces.add("net/minecraft/client/resources/SkinManager$SkinAvailableCallback");
return cn;
}
},
// For 1.15+
'TextureManagerTransformer': {
'target': {
'type': 'CLASS',
'name': 'net/minecraft/client/renderer/texture/TextureManager'
},
'transformer': function (cn) {
cn.interfaces.add("customskinloader/fake/itf/IFakeTextureManager$V1");
cn.interfaces.add("customskinloader/fake/itf/IFakeTextureManager$V2");
return cn;
}
},
'DownloadingTextureTransformer': {
'target': {
'type': 'CLASS',
'name': 'net/minecraft/client/renderer/texture/DownloadingTexture'
},
'transformer': function (cn) {
cn.methods.forEach(function (mn) {
if (checkName(mn.name, "func_229159_a_") && mn.desc.equals("(Ljava/io/InputStream;)Lnet/minecraft/client/renderer/texture/NativeImage;")) {
for (var iterator = mn.instructions.iterator(); iterator.hasNext();) {
var node = iterator.next();
if (node.getOpcode() === Opcodes.INVOKESTATIC && node.owner.equals("net/minecraft/client/renderer/texture/DownloadingTexture") && checkName(node.name, "func_229163_c_") && node.desc.equals("(Lnet/minecraft/client/renderer/texture/NativeImage;)Lnet/minecraft/client/renderer/texture/NativeImage;")) {
// FakeSkinBuffer.processLegacySkin(image, this.processTask, DownloadingTexture::processLegacySkin);
mn.instructions.insertBefore(node, new VarInsnNode(Opcodes.ALOAD, 0));
mn.instructions.insertBefore(node, new FieldInsnNode(Opcodes.GETFIELD, "net/minecraft/client/renderer/texture/DownloadingTexture", mapName("field_229155_i_"), "Ljava/lang/Runnable;"));
mn.instructions.insertBefore(node, new InvokeDynamicInsnNode("apply", "()Ljava/util/function/Function;",
/* bsm */ new Handle(Opcodes.H_INVOKESTATIC, "java/lang/invoke/LambdaMetafactory", "metafactory", "(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;", false),
/* bsmArgs */ Type.getType("(Ljava/lang/Object;)Ljava/lang/Object;"),
/* bsmArgs */ new Handle(Opcodes.H_INVOKESTATIC, "net/minecraft/client/renderer/texture/DownloadingTexture", mapName("func_229163_c_"), "(Lnet/minecraft/client/renderer/texture/NativeImage;)Lnet/minecraft/client/renderer/texture/NativeImage;", false),
/* bsmArgs */ Type.getType("(Lnet/minecraft/client/renderer/texture/NativeImage;)Lnet/minecraft/client/renderer/texture/NativeImage;")));
iterator.set(new MethodInsnNode(Opcodes.INVOKESTATIC, "customskinloader/fake/FakeSkinBuffer", "processLegacySkin", "(Lnet/minecraft/client/renderer/texture/NativeImage;Ljava/lang/Runnable;Ljava/util/function/Function;)Lnet/minecraft/client/renderer/texture/NativeImage;", false));
}
}
}
});
return cn;
}
},
'RenderPlayer_LayerCapeTransformer': {
'target': {
'type': 'CLASS',
'names': function (target) {
return ['net/minecraft/client/renderer/entity/PlayerRenderer', 'net/minecraft/client/renderer/entity/layers/CapeLayer'];
}
},
'transformer': function (cn) {
cn.methods.forEach(function (mn) {
if ((checkName(mn.name, "func_229145_a_") && mn.desc.equals("(Lcom/mojang/blaze3d/matrix/MatrixStack;Lnet/minecraft/client/renderer/IRenderTypeBuffer;ILnet/minecraft/client/entity/player/AbstractClientPlayerEntity;Lnet/minecraft/client/renderer/model/ModelRenderer;Lnet/minecraft/client/renderer/model/ModelRenderer;)V")) // PlayerRenderer.renderItem
|| (checkName(mn.name, "func_225628_a_") && mn.desc.equals("(Lcom/mojang/blaze3d/matrix/MatrixStack;Lnet/minecraft/client/renderer/IRenderTypeBuffer;ILnet/minecraft/client/entity/player/AbstractClientPlayerEntity;FFFFFF)V"))) { // CapeLayer.render
for (var iterator = mn.instructions.iterator(); iterator.hasNext();) {
var node = iterator.next();
if (node.getOpcode() === Opcodes.INVOKESTATIC && node.owner.equals("net/minecraft/client/renderer/RenderType") && checkName(node.name, "func_228634_a_") && node.desc.equals("(Lnet/minecraft/util/ResourceLocation;)Lnet/minecraft/client/renderer/RenderType;")) { // RenderType.getEntitySolid
node.name = mapName("func_228644_e_"); // RenderType.getEntityTranslucent
}
}
}
});
return cn;
}
}
};
}
@@ -0,0 +1,35 @@
package customskinloader.forge;
import java.io.File;
import java.util.List;
import net.minecraft.launchwrapper.ITweaker;
import net.minecraft.launchwrapper.Launch;
import net.minecraft.launchwrapper.LaunchClassLoader;
/**
* The tweaker for development environment.
*/
public class ForgeDevTweaker implements ITweaker {
@Override
public void acceptOptions(List<String> args, File gameDir, File assetsDir, String profile) {
}
@Override
@SuppressWarnings("unchecked")
public void injectIntoClassLoader(LaunchClassLoader classLoader) {
// ForgeTweaker should be added after FMLTweaker being initialized.
((List<String>) Launch.blackboard.get("TweakClasses")).add(ForgeTweaker.class.getName());
}
@Override
public String getLaunchTarget() {
return "";
}
@Override
public String[] getLaunchArguments() {
return new String[0];
}
}
@@ -0,0 +1,55 @@
package customskinloader.forge;
import customskinloader.CustomSkinLoader;
import net.minecraft.launchwrapper.Launch;
import net.minecraftforge.fml.ExtensionPoint;
import net.minecraftforge.fml.ModLoadingContext;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.event.FMLFingerprintViolationEvent;
import org.apache.commons.lang3.tuple.Pair;
/**
* Forge Mod Container
*/
@Mod(
value = "customskinloader",
modid = "customskinloader",
name = "CustomSkinLoader",
version = "@MOD_FULL_VERSION@",
clientSideOnly = true,
acceptedMinecraftVersions = "[1.8,1.13)",
acceptableRemoteVersions = "*",
certificateFingerprint = "52885f395e68f42e9b3b629ba56ecf606f7d4269"
)//1.13-
public class ForgeMod {
public ForgeMod() {
try {
this.setExtensionPoint();
} catch (Throwable ignored) {
// before forge-1.13.2-25.0.103
}
}
@Mod.EventHandler
public void fingerprintError(FMLFingerprintViolationEvent event) {
if ((boolean) Launch.blackboard.get("fml.deobfuscatedEnvironment") || event.isDirectory()) return;//Development Environment
CustomSkinLoader.logger.warning("!!!Fingerprint ERROR!!!");
CustomSkinLoader.logger.warning("Failed to check fingerprint in file '" + event.getSource().getAbsolutePath() + "'.");
CustomSkinLoader.logger.warning("Excepted Fingerprint: " + event.getExpectedFingerprint());
if (event.getFingerprints().isEmpty()) {
CustomSkinLoader.logger.warning("No Fingerprint Founded.");
} else {
CustomSkinLoader.logger.warning("Founded Fingerprint: ");
for (String s : event.getFingerprints())
CustomSkinLoader.logger.warning(s);
}
throw new RuntimeException("Fingerprint ERROR, please **DO NOT MODIFY** any mod.");
}
// Make sure the mod being absent on the other network side does not cause the client to display the server as incompatible after forge-1.13.2-25.0.107.
private void setExtensionPoint() {
ModLoadingContext.get().registerExtensionPoint(ExtensionPoint.DISPLAYTEST, () -> Pair.of(() -> "customskinloader", (remote, isServer) -> isServer));
}
}
@@ -4,11 +4,13 @@ import java.util.Map;
import net.minecraftforge.fml.relauncher.IFMLLoadingPlugin; import net.minecraftforge.fml.relauncher.IFMLLoadingPlugin;
@IFMLLoadingPlugin.Name("CustomSkinLoader")
@IFMLLoadingPlugin.SortingIndex(-10)
public class ForgePlugin implements IFMLLoadingPlugin { public class ForgePlugin implements IFMLLoadingPlugin {
@Override @Override
public String[] getASMTransformerClass() { public String[] getASMTransformerClass() {
return new String[] {TransformerManager.class.getName()}; return new String[]{"customskinloader.forge.loader.LaunchWrapper"};//LaunchWrapper
} }
@Override @Override
@@ -23,6 +25,7 @@ public class ForgePlugin implements IFMLLoadingPlugin {
@Override @Override
public void injectData(Map<String, Object> data) { public void injectData(Map<String, Object> data) {
TransformerManager.isDevelopmentEnvironment = !(boolean) data.get("runtimeDeobfuscationEnabled");
} }
@Override @Override
Loaded 100 of 183 files, more files were not shown because too many files have changed in this diff. Show more