REPENTOGON phase 0 (e2c5aec, GPL-2): ISAAC_REPENTOGON option (on), src/repentogon/ with the hidden REPENTOGON global switch, callback ids 1000-1499 with REPENTOGON's enable state and dispatch (priorities, optional and two-parameter filters, isolated errors), its scripts loaded from assets/repentogon/scripts, its options store and a vanilla-parity switch (on) in the overlay, scripts/repentogon_coverage.py and analysis/repentogon_coverage.tsv (2,834 rows)

This commit is contained in:
shweet committed 2026-11-24 03:23:39 -05:00
1 parent 78cb0775b0
commit 2cc082f6ee
31 files changed
+12954 -148

No files matched your search

+10
View File
@@ -79,6 +79,10 @@ if(ISAAC_OVERLAY)
target_compile_options(imgui PRIVATE -w)
endif()
# REPENTOGON's modding API built in natively (src/repentogon/, its scripts in assets/repentogon/): inert without mods,
# with every change to the vanilla game behind its options and the vanilla parity switch. OFF builds the vanilla game.
option(ISAAC_REPENTOGON "Build REPENTOGON's modding API into the game" ON)
# The curated game: every .cpp under src/, sorted into subsystem folders and including each other by path from src/,
# written on top of the declarations generated-src/classes.h holds for every class.
# generated-src/'s own bodies stay out until they compile (scripts/source_tree.py --check reports how many do).
@@ -88,6 +92,9 @@ file(GLOB_RECURSE SOURCES CONFIGURE_DEPENDS src/*.cpp)
if(NOT ISAAC_OVERLAY)
list(FILTER SOURCES EXCLUDE REGEX "/src/ui/overlay/")
endif()
if(NOT ISAAC_REPENTOGON)
list(FILTER SOURCES EXCLUDE REGEX "/src/repentogon/")
endif()
add_executable(isaac ${SOURCES} generated-src/stubs.cpp)
target_include_directories(isaac PRIVATE src)
target_include_directories(isaac SYSTEM PRIVATE generated-src external/stb)
@@ -96,3 +103,6 @@ if(ISAAC_OVERLAY)
target_compile_definitions(isaac PRIVATE ISAAC_OVERLAY)
target_link_libraries(isaac PRIVATE imgui)
endif()
if(ISAAC_REPENTOGON)
target_compile_definitions(isaac PRIVATE ISAAC_REPENTOGON)
endif()
+4 -1
View File
@@ -31,7 +31,8 @@ scripts/ decompile.sh (print decompiled C for a function, by name regex or
and Python helpers they use
tools/ gitignored local tools: the resource importer and the test harness (tools/harness/)
external/ static submodules: SDL3, Lua 5.3, simdjson, Ogg, Vorbis, Theora, stb, Dear ImGui (docking)
assets/ files the repository ships itself (git-lfs): the overlay's fonts, with their licences
assets/ files the repository ships itself: the overlay's fonts (git-lfs), with their licences, and REPENTOGON's Lua
scripts (assets/repentogon/, GPL-2), adapted where they reach API not ported yet
repentogon/ shallow clone of TeamREPENTOGON/REPENTOGON (libzhl/functions/*.zhl = sigs, structs, enums)
bin/ private copy of the exe (analysis input; also used to read constants)
jdk/ ghidra_12.2_PUBLIC/ Temurin 21 (system java is 8, too old) and Ghidra
@@ -86,6 +87,8 @@ ui/ HUDs, popups, pause screen, cutscenes, console
with the Console, Game Options, Mods and Debug windows on Dear ImGui
lua/ the Lua engine, API bindings and callbacks
online/ online-only code, kept as offline stubs
repentogon/ REPENTOGON's modding API built in (CMake option ISAAC_REPENTOGON, on by default, OFF builds the vanilla
game): its scripts' loading, its options store and the vanilla parity switch, inert without mods
```
### Test harness
File diff suppressed because it is too large. Load diff
+339
View File
@@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,49 @@
---@type table<string, integer>
local s_groupNames = {}
local s_nextGroupId = 0
local ModManager = _GetModule("repentogon_extras.mod_manager")
---@param groupName string
---@return integer groupId
local function CreateGroup(groupName)
if type(groupName) ~= "string" then
error(string.format("bad argument #%d (string expected, got %s)", 1, type(groupName)), 2)
end
local existingId = s_groupNames[groupName]
if existingId then
if not ModManager.ModsLoaded() then
Console.PrintWarning(string.format("[WARN] [RGON] group \"%s\" already exists", groupName))
end
return existingId
end
if ModManager.ModsLoaded() then
error("groups can only be created during Mod Load", 2)
end
local groupId = s_nextGroupId
s_nextGroupId = s_nextGroupId + 1
if s_nextGroupId == RoomGroup.GROUP_ULTRA_SECRET then
s_nextGroupId = s_nextGroupId + 1
end
s_groupNames[groupName] = groupId
return groupId
end
---@param groupName string
---@return integer? groupId
local function GetGroupByName(groupName)
if type(groupName) ~= "string" then
error(string.format("bad argument #%d (string expected, got %s)", 1, type(groupName)), 2)
end
return s_groupNames[groupName]
end
rawset(RoomDescriptor, "CreateGroup", CreateGroup)
rawset(RoomDescriptor, "GetGroupByName", GetGroupByName)
@@ -0,0 +1,30 @@
error("This file should not have been included")
---@class REPENTOGON._CBindings
---@field ESSM REPENTOGON._CBindings.ESSM
---@field RaiseModError fun(modName: string)
---@field GetModId fun(mod: ModReference): string?
---@field HasModData fun(mod: ModReference, fileName: string): boolean
---@field SaveModData fun(mod: ModReference, fileName: string, data: string): boolean
---@field LoadModData fun(mod: ModReference, fileName: string): string?
---@field RemoveModData fun(mod: ModReference, fileName: string)
---@field RemoveAllData fun(fileName: string)
---@field ModReference_HasModFile fun(mod: ModReference, fileName: string): boolean
---@field ModReference_SaveModFile fun(mod: ModReference, fileName: string, data: string): boolean
---@field ModReference_LoadModFile fun(mod: ModReference, fileName: string): string?
---@field ModReference_RemoveModFile fun(mod: ModReference, fileName: string)
---@class REPENTOGON._CBindings.ESSM
---@field GetEntitySaveStateId fun(ess: EntitiesSaveState): integer
---@field SaveData fun(mod: ModReference, fileName: string, data: string)
---@field LoadData fun(mod: ModReference, fileName: string): string?
---@field DeleteData fun(mod: ModReference, fileName: string)
---@class REPENTOGON.GameStateInfo
---@field checksum integer
---@field fileName string
---@type REPENTOGON._CBindings
---@diagnostic disable-next-line: missing-fields
_G._CBindings = {}
@@ -0,0 +1,116 @@
-- save copy of original enums, to make it harder for mods to mess with the repentogon features
local _ModCallbacks = ModCallbacks
local _MainMenuType = MainMenuType
local _ButtonAction = ButtonAction
local _SoundEffect = SoundEffect
local BestiaryMenuRep = {
BestiarySheetSprite = Sprite(),
BestiarySheetSpritePos = Vector(5, 28),
ArrowSprite = Sprite(),
PageWidgetPos = Vector(84, 238),
PageTextPos = Vector(84, 231)
}
local font = Font()
font:Load("font/teammeatex/teammeatex10.fnt")
local fontcolor = KColor(0.20, 0.15, 0.1, 1)
local MaxPollCIdx = 3
local function UpdateMaxPollCIdx()
local str=Input.GetDeviceNameByIdx(0)
local i=0
while (str~=nil) do
i=i+1
str=Input.GetDeviceNameByIdx(i)
end
MaxPollCIdx=i
end
local function IsActionTriggeredAll(action)
for i = 0, MaxPollCIdx do
if Input.IsActionTriggered(action, i) then
return true,i
end
end
return false
end
local function BoolToNum(value)
return value and 1 or 0
end
local function LoadAssets()
if #BestiaryMenuRep.BestiarySheetSprite:GetDefaultAnimation() <= 0 then
BestiaryMenuRep.BestiarySheetSprite:Load("gfx/ui/bestiary_tabs.anm2", true)
BestiaryMenuRep.BestiarySheetSprite:SetFrame("Tabs", 0)
BestiaryMenuRep.ArrowSprite:Load("gfx/ui/leaderboardmenu.anm2", true)
BestiaryMenuRep.ArrowSprite:SetFrame("Idle", 0)
end
if not font:IsLoaded() then
font:Load("font/teammeatex/teammeatex10.fnt")
end
if font:IsLoaded() and #(BestiaryMenuRep.BestiarySheetSprite:GetDefaultAnimation()) > 0 then
Isaac.RemoveCallback(REPENTOGON, _ModCallbacks.MC_MAIN_MENU_RENDER, LoadAssets)
end
end
Isaac.AddCallback(REPENTOGON, _ModCallbacks.MC_MAIN_MENU_RENDER, LoadAssets)
local function RenderBestiaryMenu()
local selectedPage = BestiaryMenu.GetSelectedPage()
local lastEnemyPage = BestiaryMenu.GetNumMonsterPages()
local totalPages = BestiaryMenu.GetNumPages()
local isEnemyPage = selectedPage <= lastEnemyPage
local inputController=-1
if MenuManager:GetActiveMenu() == _MainMenuType.BESTIARY then
UpdateMaxPollCIdx()
local scrollBy=0
local leftInputIdx,rightInputIdx
local scrollLeft,scrollRight
scrollLeft,leftInputIdx=IsActionTriggeredAll(_ButtonAction.ACTION_PILLCARD)
scrollRight,rightInputIdx=IsActionTriggeredAll(_ButtonAction.ACTION_BOMB)
inputController = leftInputIdx or rightInputIdx or -1
scrollBy=BoolToNum(scrollRight)-BoolToNum(scrollLeft)
if inputController>0 then scrollBy=scrollBy*-1.0 end --flip gamepad inputs
if IsActionTriggeredAll(_ButtonAction.ACTION_MENUTAB) then
SFXManager():Play(_SoundEffect.SOUND_PAPER_IN)
if isEnemyPage then
BestiaryMenu.SetSelectedPage(lastEnemyPage+1)
else
BestiaryMenu.SetSelectedPage(0)
end
BestiaryMenu.SetSelectedElement(0)
elseif IsActionTriggeredAll(_ButtonAction.ACTION_BOMB) then
if selectedPage < BestiaryMenu.GetNumPages() then -- last page reached
SFXManager():Play(_SoundEffect.SOUND_PAPER_IN)
BestiaryMenu.SetSelectedPage(selectedPage + 1)
BestiaryMenu.SetSelectedElement(0)
end
elseif IsActionTriggeredAll(_ButtonAction.ACTION_PILLCARD) then
if selectedPage > 0 then -- first page
SFXManager():Play(_SoundEffect.SOUND_PAPER_IN)
BestiaryMenu.SetSelectedPage(selectedPage - 1)
BestiaryMenu.SetSelectedElement(0)
end
end
end
-- render stat page over original stat page, to allow for custom content
BestiaryMenuRep.BestiarySheetSprite:SetFrame("Tabs", isEnemyPage and 0 or 1)
local posSheet = Isaac.WorldToMenuPosition(_MainMenuType.BESTIARY, BestiaryMenuRep.BestiarySheetSpritePos)
BestiaryMenuRep.BestiarySheetSprite:Render(posSheet)
BestiaryMenuRep.BestiarySheetSprite:SetFrame("PageWidget", 0)
local posPageSheet = Isaac.WorldToMenuPosition(_MainMenuType.BESTIARY, BestiaryMenuRep.PageWidgetPos)
BestiaryMenuRep.BestiarySheetSprite:Render(posPageSheet)
local pos = Isaac.WorldToMenuPosition(_MainMenuType.BESTIARY, BestiaryMenuRep.PageTextPos)
local text = "Page: "..tostring(selectedPage + 1).."/"..tostring(totalPages + 1)
local width = font:GetStringWidthUTF8(text)
font:DrawStringUTF8(text, pos.X-width/2, pos.Y, fontcolor, 0, false)
end
REPENTOGON.Extras.BestiaryMenu = BestiaryMenuRep
Isaac.AddCallback(REPENTOGON, _ModCallbacks.MC_MAIN_MENU_RENDER, RenderBestiaryMenu)
@@ -0,0 +1,343 @@
-- save copy of original enums, to make it harder for mods to mess with the repentogon features
local _ModCallbacks = ModCallbacks
local _MainMenuType = MainMenuType
local _ButtonAction = ButtonAction
local _Keyboard = Keyboard
local _SoundEffect = SoundEffect
local ChangeLog = {
["AssetsLoaded"] = false,
["NoteOffset"] = Vector(275, 190),
["PaperOffset"] = Vector(-37, -15),
["VersionOffset"] = Vector(238, 240),
["ChangelogSprite"] = Sprite(),
["NoteSprite"] = Sprite(),
["Font"] = Font(),
["VersionFont"] = Font(),
["FontColor"] = KColor(0.20, 0.15, 0.1, 1),
["LineHeight"] = 12,
["ScrollMargin"] = 5,
["ScrollSpeed"] = 1,
["ScrollSpeedFast"] = 2.5,
["ScrollItertia"] = 0.8,
["CurrentSheet"] = 1,
["Sheets"] = --TODO: implement the ability to have multiple sheets with unique sprites and stuff
{},
}
local Cl = ChangeLog
local function TextSplit(inputstr, sep) --shamelessly stolen from the stackoverflow
if sep == nil then
sep = "%s"
end
local t = {}
for str in string.gmatch(inputstr, "([^" .. sep .. "]+)") do
table.insert(t, str)
end
return t
end
function SplitStringByLength(str, max_length)
local result = {}
local line = ""
for word in string.gmatch(str, "%S+") do
if #line + #word + 1 > max_length then
table.insert(result, line)
line = word
else
if line == "" then
line = word
else
line = line .. " " .. word
end
end
end
if line ~= "" then
table.insert(result, line)
end
return result
end
function ChangeLog.EvaluateText()
for i = 1, #Cl.Sheets do
local temparray = TextSplit(Cl.Sheets[i].Text, "\n")
for k, v in pairs(temparray) do
temparray[k] = string.gsub(v, "/newline/", " ") --new
temparray[k] = string.gsub(temparray[k], "/fade/", "/f/")
--line support
temparray[k] = string.gsub(temparray[k], "https://%S+", "(...)") --replace links with three dots
end
local finalarray = {}
for _, v in pairs(temparray) do
local splitbywords = string.gmatch(v, "%w+")
local wordcount = 0
for _ in splitbywords do
wordcount = wordcount + 1
end
local limitedarray = {}
if wordcount > 0 then
limitedarray = SplitStringByLength(v, 29)
for _, str in pairs(limitedarray) do
table.insert(finalarray, str)
end
else
table.insert(finalarray, v)
end
end
Cl.Sheets[i].TextArray = finalarray
end
end
local ShouldBeRendered = false --render of the changelog isn't attempted
local ScrollVelocity = 0
local CurrentPage = 1
local ScrollOffset = Cl.ScrollMargin
local MaxPollCIdx = 3
local UseFade = false
local function UpdateMaxPollCIdx()
local str=Input.GetDeviceNameByIdx(0)
local i=0
while (str~=nil) do
i=i+1
str=Input.GetDeviceNameByIdx(i)
end
MaxPollCIdx=i
end
local function IsActionTriggeredAll(action)
for i = 0, MaxPollCIdx do
if Input.IsActionTriggered(action, i) then
return true
end
end
return false
end
local function IsActionPressedAll(action)
for i = 0, MaxPollCIdx do
if Input.IsActionPressed(action, i) then
return true
end
end
return false
end
local function IsKeyboardPressedAll(input)
for i = 0, MaxPollCIdx do
if Input.IsButtonPressed(input, i) then
return true
end
end
return false
end
function ChangeLog.MenuRender()
if not Cl.AssetsLoaded then
return
end
Cl.NoteSprite:Render(Isaac.WorldToMenuPosition(_MainMenuType.TITLE, Cl.NoteOffset))
local versionPosition = Isaac.WorldToMenuPosition(_MainMenuType.TITLE, Cl.VersionOffset)
local versionString = "REPENTOGON " .. REPENTOGON.Version
Cl.VersionFont:DrawStringUTF8(versionString, versionPosition.X + 1, versionPosition.Y + 1,
KColor(0, 0, 0, 0.3), 200) -- shadow
Cl.VersionFont:DrawStringUTF8(versionString, versionPosition.X, versionPosition.Y,
KColor(67 / 255, 5 / 255, 5 / 255, 1), 200) -- text
local ActiveMenu=MenuManager:GetActiveMenu()
if ActiveMenu == _MainMenuType.TITLE or ActiveMenu==0 then --reserve menu id 0 for changelog to prevent inputs, mdoders: please do not use that specific id, you already have almost 2^32 of them!...
UpdateMaxPollCIdx()
if IsActionTriggeredAll(_ButtonAction.ACTION_MAP) then
Cl.CurrentState = not Cl.CurrentState
if Cl.CurrentState == true then
SFXManager():Play(_SoundEffect.SOUND_PAPER_IN)
Cl.ChangelogSprite:Play("SwapIn")
MenuManager.SetActiveMenu(0) --block inputs
else
SFXManager():Play(_SoundEffect.SOUND_PAPER_OUT)
Cl.ChangelogSprite:Play("SwapOut")
MenuManager.SetActiveMenu(1) --unblock inputs
end
ShouldBeRendered = true
elseif IsActionTriggeredAll(_ButtonAction.ACTION_MENUBACK) and Cl.CurrentState==true then
Cl.CurrentState=false
SFXManager():Play(_SoundEffect.SOUND_PAPER_OUT)
Cl.ChangelogSprite:Play("SwapOut")
MenuManager.SetActiveMenu(1) --unblock inputs
elseif IsActionTriggeredAll(_ButtonAction.ACTION_MENURIGHT) and Cl.CurrentState then
CurrentPage = CurrentPage + 1
if CurrentPage < #ChangeLog.Sheets then
SFXManager():Play(_SoundEffect.SOUND_PAPER_IN)
ScrollOffset = 5
else
CurrentPage = #ChangeLog.Sheets
end
elseif IsActionTriggeredAll(_ButtonAction.ACTION_MENULEFT) and Cl.CurrentState then
CurrentPage = CurrentPage - 1
if CurrentPage > 0 then
SFXManager():Play(_SoundEffect.SOUND_PAPER_IN)
ScrollOffset = 5
else
CurrentPage = 1
end
end
if ShouldBeRendered then
local LogRenderPosition = Isaac.WorldToMenuPosition(_MainMenuType.TITLE, Cl.PaperOffset)
Cl.ChangelogSprite:RenderLayer(3, LogRenderPosition)
local TextGuideNull = Cl.ChangelogSprite:GetNullFrame("UpdateText")
local Height = 0
local BoxSize = 200
if TextGuideNull then
local NullPos = TextGuideNull:GetPos()
local NullScale = TextGuideNull:GetScale()
local YOffset = 0
local MinOffset = LogRenderPosition.Y + NullPos.Y + 40 * NullScale.Y --40 is a static offset for the "Change Log" title
local MaxOffset = MinOffset + 170 * NullScale.Y --170 is a total height of the paper, should get it exposed in the table
local TextStretchFactor = 0
for _, iterline in pairs(Cl.Sheets[CurrentPage].TextArray) do
if string.find(iterline, "/f/") then
UseFade = true
elseif iterline == " " then
UseFade = false
end
local line = string.gsub(iterline, "/f/", "")
local XOffset = (-BoxSize / 2) * NullScale.X
local FullY = LogRenderPosition.Y + NullPos.Y + 40 * NullScale.Y + YOffset * NullScale.Y + ScrollOffset
-- if FullY<500 then
-- print(line,"fully-minoffset",FullY - MinOffset,",minoffset:",(MinOffset + Cl.ScrollMargin * NullScale.Y),",maxoffset:",(MaxOffset - Cl.ScrollMargin * NullScale.Y)) end
-- print("checking",FullY-MinOffset)
if ((MaxOffset - FullY) < 0.0) or ((FullY - MinOffset) < 0.0) then
goto skiptonextline
end
if FullY < (MinOffset + Cl.ScrollMargin * NullScale.Y) or FullY > (MaxOffset - Cl.ScrollMargin * NullScale.Y) then
if FullY - MinOffset < Cl.ScrollMargin * NullScale.Y then
Cl.FontColor.Alpha = (FullY - MinOffset) / Cl.ScrollMargin
end
if (MaxOffset - FullY) < Cl.ScrollMargin * NullScale.Y then
Cl.FontColor.Alpha = (MaxOffset - FullY) / Cl.ScrollMargin
end
else
Cl.FontColor.Alpha = 1
end
if UseFade then
Cl.FontColor.Alpha = Cl.FontColor.Alpha * 0.75
end
TextStretchFactor=math.min(1.0, BoxSize/Cl.Font:GetStringWidthUTF8(line) ) --this way the long lines of text get squished horizontally
Cl.Font:DrawStringScaledUTF8(line, LogRenderPosition.X + NullPos.X + XOffset, FullY, NullScale.X*TextStretchFactor,
NullScale.Y, Cl.FontColor, 0, false)
::skiptonextline::
YOffset = YOffset + Cl.LineHeight
Height = YOffset
end
end
-- Scroll faster when holding SHIFT or DROP
local speed = (IsActionPressedAll(_ButtonAction.ACTION_DROP) or IsKeyboardPressedAll(_Keyboard.KEY_LEFT_SHIFT))
and Cl.ScrollSpeedFast or Cl.ScrollSpeed
if IsActionPressedAll(_ButtonAction.ACTION_MENUUP) then
ScrollVelocity = ScrollVelocity + speed
end
if IsActionPressedAll(_ButtonAction.ACTION_MENUDOWN) and -ScrollOffset < Height - (BoxSize / 2) then
ScrollVelocity = ScrollVelocity - speed
end
if Cl.ChangelogSprite:IsFinished("SwapOut") then
ShouldBeRendered = false
ScrollOffset = 5
ScrollVelocity = 0
end
if ScrollOffset + ScrollVelocity > Cl.ScrollMargin then
ScrollOffset = Cl.ScrollMargin
ScrollVelocity = 0
end
ScrollOffset = ScrollOffset + ScrollVelocity
ScrollVelocity = ScrollVelocity * 0.8
Cl.ChangelogSprite:Update()
end
elseif ShouldBeRendered then
ShouldBeRendered = false
Cl.CurrentState = false
ScrollOffset = Cl.ScrollMargin
ScrollVelocity = 0
Cl.ChangelogSprite:Play("SwapOut")
end
end
REPENTOGON.Extras.ChangeLog = ChangeLog
local curattempt=0
function ChangeLog.LoadAssets()
if #Cl.ChangelogSprite:GetDefaultAnimation() <= 0 then
Cl.ChangelogSprite:Load("gfx/ui/changelog.anm2", true)
Cl.ChangelogSprite:Play("SwapOut")
Cl.ChangelogSprite.PlaybackSpeed = 0.5 --correct speed for doing Update() inside of xxx_RENDER callback
Cl.NoteSprite:Load("gfx/ui/changelog_tab_paper.anm2", true)
Cl.NoteSprite:Play("Idle")
curattempt=curattempt+1
if curattempt>5 then
Isaac.RemoveCallback(REPENTOGON, _ModCallbacks.MC_MAIN_MENU_RENDER, ChangeLog.LoadAssets)
Isaac.RemoveCallback(REPENTOGON, _ModCallbacks.MC_MAIN_MENU_RENDER, Cl.MenuRender)
Isaac.AddCallback(REPENTOGON,_ModCallbacks.MC_MAIN_MENU_RENDER,REPENTOGON.Extras.Misc.NoRPTGNFldrErr)
end
end
if not Cl.Font:IsLoaded() then
Cl.Font:Load("font/teammeatex/teammeatex10.fnt")
end
if not Cl.VersionFont:IsLoaded() then
Cl.VersionFont:Load("font/luamini.fnt")
end
if Cl.Font:IsLoaded() and Cl.VersionFont:IsLoaded() and #(Cl.ChangelogSprite:GetDefaultAnimation()) > 0 then
-- Separate sheets by version
-- Also, Lua doesn't have a way to separate strings by words. Only with patterns.
-- This makes me very sad.
local rawChangelog = Isaac.RGON_GetChangelog()
local entireChangelog = TextSplit(rawChangelog, "\n")
local chunk = ""
for _, word in ipairs(entireChangelog) do
if word == "/versionseparator/" then
table.insert(Cl.Sheets, {
["Text"] = chunk,
["TextArray"] = {},
})
chunk = ""
else
chunk = chunk .. word .. "\n"
end
end
-- Just a failsafe if the log somehow doesn't have any version separators.
-- Mainly just for dev environments.
if #Cl.Sheets == 0 then
table.insert(Cl.Sheets, {
["Text"] = rawChangelog,
["TextArray"] = {}
})
end
Cl.EvaluateText()
Isaac.RemoveCallback(REPENTOGON, _ModCallbacks.MC_MAIN_MENU_RENDER, ChangeLog.LoadAssets)
Cl.AssetsLoaded = true
end
end
Isaac.AddCallback(REPENTOGON, _ModCallbacks.MC_MAIN_MENU_RENDER, ChangeLog.LoadAssets)
Isaac.AddCallback(REPENTOGON, _ModCallbacks.MC_MAIN_MENU_RENDER, Cl.MenuRender)
@@ -0,0 +1,20 @@
return [[
Have a nice sample text!
/newline/
;D
/newline/
/newline/
/newline/
/newline/
/newline/
/newline/
/newline/
/newline/
/newline/
/newline/
/newline/
/newline/
/newline/
Thanks for scrolling!
-im_tem
]]
@@ -0,0 +1,156 @@
-- save copy of original enums, to make it harder for mods to mess with the repentogon features
local _EventCounter = EventCounter
local _ModCallbacks = ModCallbacks
local _MainMenuType = MainMenuType
local WinStreak = 0
local TotalDailies = 0
local GetStageGoal = 0
local isAltPath = false
local isHardMode = false
local isMegaSatan = false
local diffOffsetFrameNum = 0
local ScheduleRefresh = true
--local StreakSheet = Sprite()
local TotalSheet = Sprite()
--local GoalDestinationIcon = Sprite()
--local HardModeIcon = Sprite()
local LeaderboardSprite = Sprite()
local StreakPos = Vector(428, 110) + Vector(36, 24)
--StreakSheet.Offset = Vector(-36, -24)
local TotalStreakText = "Total Runs: 0"
local TextLen = 38
local font = Font()
font:Load("font/teammeatex/teammeatex10.fnt")
local fontcolor = KColor(0.20, 0.15, 0.1, 1)
local function RefreshDailyStats()
ScheduleRefresh = true
end
local function GetGoalDestination(stage, altPath)
local goalMap = {
[6] = 0,
[8] = {
[false] = 1,
[true] = 8,
},
[10] = {
[false] = 2,
[true] = 3,
},
[11] = {
[false] = 4,
[true] = 5,
},
[12] = 7,
[13] = 9,
}
if goalMap[stage] then
if type(goalMap[stage]) == "table" then
if goalMap[stage][altPath] then
return goalMap[stage][altPath]
end
else
return goalMap[stage]
end
end
return 0
end
local function LoadAssets()
if #TotalSheet:GetDefaultAnimation() <= 0 then
--StreakSheet:Load("gfx/ui/main menu/winstreakwidget.anm2", true)
--StreakSheet:SetFrame("Idle", 0)
TotalSheet:Load("gfx/ui/main menu/seedselectionwidget.anm2", true)
TotalSheet:SetFrame("Eggs", 0)
--GoalDestinationIcon:Load("gfx/ui/hudpickups.anm2", true)
--GoalDestinationIcon:SetAnimation("Destination", true)
--GoalDestinationIcon:SetFrame(7)
--HardModeIcon:Load("gfx/ui/hudpickups.anm2", true)
--HardModeIcon:SetAnimation("Idle", true)
--HardModeIcon:SetFrame(4)
LeaderboardSprite:Load("gfx/ui/daily_destinations.anm2", true)
LeaderboardSprite:SetAnimation("Destination", true)
LeaderboardSprite:SetFrame(0)
end
if not font:IsLoaded() then
font:Load("font/teammeatex/teammeatex10.fnt")
end
if font:IsLoaded() and #(TotalSheet:GetDefaultAnimation()) > 0 then
TextLen = font:GetStringWidthUTF8(TotalStreakText) / 2
Isaac.RemoveCallback(REPENTOGON, _ModCallbacks.MC_MAIN_MENU_RENDER, LoadAssets)
end
end
Isaac.AddCallback(REPENTOGON, _ModCallbacks.MC_MAIN_MENU_RENDER, LoadAssets)
local function RenderDailyStats()
if ScheduleRefresh and MenuManager:GetActiveMenu() == _MainMenuType.DAILYRUN then
local dailyChallenge = DailyChallenge
local challengeParam = dailyChallenge.GetChallengeParams()
WinStreak = Isaac.GetPersistentGameData():GetEventCounter(_EventCounter.DAILYS_STREAK)
TotalDailies = Isaac.GetPersistentGameData():GetEventCounter(_EventCounter.DAILYS_PLAYED)
GetStageGoal = challengeParam:GetEndStage()
isAltPath = challengeParam:IsSecretPath() or (GetStageGoal >= LevelStage.STAGE5 and challengeParam:IsAltPath())
isBrokenBeastPath = challengeParam:IsBeastPath() and challengeParam:GetEndStage() ~= LevelStage.STAGE8
--[[if WinStreak > 0 then
StreakSheet:SetFrame("Good", 0)
elseif WinStreak < 0 then
StreakSheet:SetFrame("Bad", 0)
else
StreakSheet:SetFrame("Idle", 0)
end]]
TotalStreakText = "Total Runs: " .. TotalDailies
TextLen = font:GetStringWidthUTF8(TotalStreakText) / 2
--StageGoalText = "Goal Stage: "..GetStageGoal
isHardMode = challengeParam:GetDifficulty() == 1
isMegaSatan = challengeParam:IsMegaSatanRun()
diffOffsetFrameNum = isHardMode and 10 or 0
end
if DailyChallengeMenu:IsLeaderboardVisible() then
return
end
local pos = Isaac.WorldToMenuPosition(_MainMenuType.DAILYRUN, StreakPos)
--StreakSheet:Render(pos)
font:DrawString(WinStreak, pos.X, pos.Y, fontcolor, 0, false)
pos = Isaac.WorldToMenuPosition(_MainMenuType.DAILYRUN, Vector(160, 230))
TotalSheet:RenderLayer(0, pos)
local goalPosition = Isaac.WorldToMenuPosition(_MainMenuType.DAILYRUN, Vector(258, 80))
local goalFrame = GetGoalDestination(GetStageGoal, isAltPath) + diffOffsetFrameNum
if isMegaSatan then
LeaderboardSprite:SetFrame(6 + diffOffsetFrameNum)
LeaderboardSprite:RenderLayer(0, goalPosition)
LeaderboardSprite:SetFrame(goalFrame)
LeaderboardSprite:RenderLayer(0, goalPosition - Vector(16, 0)) --alr variant -8,48
else
if isBrokenBeastPath then
goalFrame = 9 + diffOffsetFrameNum
end
LeaderboardSprite:SetFrame(goalFrame)
LeaderboardSprite:RenderLayer(0, goalPosition)
end
--GoalDestinationIcon:RenderLayer(0, Vector(pos.X + 69, pos.Y - 32))
--[[if isHardMode then
HardModeIcon:RenderLayer(0, Vector(pos.X + 75, pos.Y - 82))
end]]
font:DrawStringUTF8(TotalStreakText, pos.X - TextLen, pos.Y - 9, fontcolor, 0, false)
end
Isaac.AddCallback(REPENTOGON, _ModCallbacks.MC_PRE_GAME_EXIT, RefreshDailyStats)
Isaac.AddCallback(REPENTOGON, _ModCallbacks.MC_MAIN_MENU_RENDER, RenderDailyStats)
@@ -0,0 +1,455 @@
--#region Data
---@class REPENTOGON._Internals.ESSM.ModLookup
---@field entityData table<integer, table>
---@field saveStateData table<integer, table>
---@class REPENTOGON._Internals.ESSM.SaveData
---@field version integer
---@field checksum integer
---@field data REPENTOGON.SerializedTable
local SAVE_DATA_VERSION = 1
---Map of registered mod ids and it's name, used to check if a modId has been registered and for some debug messages.
---@type table<string, string>
local s_registeredMods = {}
---Set of entities PtrHash that exist
---@type table<integer, true|nil>
local s_validEntities = {}
---Persistent mod data for existing entities
---@type table<string, table<integer, table>>
local s_entityData = {}
---Persistent mod data for entity save states
---@type table<string, table<integer, table>>
local s_saveStateData = {}
---Lookup for individual ModReference.
---mod references for the same mod point to the same data.
---@type table<ModReference, REPENTOGON._Internals.ESSM.ModLookup>
local s_modLookup = {}
setmetatable(s_modLookup, { __mode = "k" })
--#endregion
local json = require("json")
local ModManager = _GetModule("repentogon_extras.mod_manager")
local TableUtils = _GetModule("repentogon_extras.table_utils")
local type = type
local pairs = pairs
local error = error
local assert = assert
local pcall = pcall
local tostring = tostring
local getmetatable = getmetatable
local string_format = string.format
local json_encode = json.encode
local json_decode = json.decode
local GetPtrHash = GetPtrHash
local Isaac_DebugString = Isaac.DebugString
local GetEntitySaveStateId = _CBindings.ESSM.GetEntitySaveStateId
local SaveEntityData = _CBindings.ESSM.SaveData
local LoadEntityData = _CBindings.ESSM.LoadData
local DeleteEntityData = _CBindings.ESSM.DeleteData
---@param mod ModReference
---@param modId string
local function register_mod_id(mod, modId)
local exists = s_registeredMods[modId] ~= nil
local entityData
local saveStateData
if not exists then
s_registeredMods[modId] = mod.Name
entityData = {}
saveStateData = {}
s_entityData[modId] = entityData
s_saveStateData[modId] = saveStateData
else
entityData = s_entityData[modId]
saveStateData = s_saveStateData[modId]
end
s_modLookup[mod] = {entityData = entityData, saveStateData = saveStateData}
end
---@param mod table
---@return boolean, string
local function register_mod(mod)
local varType = type(mod)
local modId = ModManager.GetModIdByReference(mod)
if not modId then
return false, string_format("ModReference expected, got %s", varType)
end
register_mod_id(mod, modId)
return true, "success"
end
--#region Internals
---@param entityId integer
local function _OnDeleteEntity(entityId)
local exists = s_validEntities[entityId] ~= nil
s_validEntities[entityId] = nil
if not exists then
return
end
for _, entityTbl in pairs(s_entityData) do
entityTbl[entityId] = nil
end
end
---@param entityId integer
local function _OnNewEntity(entityId)
if s_validEntities[entityId] then
_OnDeleteEntity(entityId)
end
s_validEntities[entityId] = true
end
---@param entityId integer
---@param saveStateId integer
local function _OnStoreEntity(entityId, saveStateId)
for modId, entityTbl in pairs(s_entityData) do
local entityData = entityTbl[entityId]
if entityData then
s_saveStateData[modId][saveStateId] = TableUtils.DeepCopy(entityData)
end
end
end
---@param entityId integer
---@param saveStateId integer
local function _OnRestoreEntity(entityId, saveStateId)
for modId, saveStateTbl in pairs(s_saveStateData) do
local stateData = saveStateTbl[saveStateId]
local data = nil
if stateData then
data = TableUtils.DeepCopy(stateData)
end
s_entityData[modId][entityId] = data
end
end
---@param saveStateIds integer[]
local function _OnClearSaveStates(saveStateIds)
for _, saveStateTbl in pairs(s_saveStateData) do
for i = 1, #saveStateIds, 1 do
local id = saveStateIds[i]
saveStateTbl[id] = nil
end
end
end
---@param sourceIds integer[]
---@param destIds integer[]
local function _OnCopySaveStates(sourceIds, destIds)
assert(#sourceIds == #destIds)
for _, saveStateTbl in pairs(s_saveStateData) do
for i = 1, #sourceIds, 1 do
local sourceTbl = saveStateTbl[sourceIds[i]]
local dest = destIds[i]
if sourceTbl then
saveStateTbl[dest] = TableUtils.DeepCopy(sourceTbl)
end
end
end
end
---@param saveStateTbl table<integer, table>
---@param idMap table<integer, integer>
---@param checksum integer
---@return string data
local function serialize_data(saveStateTbl, idMap, checksum)
local remappedData = {}
for serializationId, id in pairs(idMap) do
remappedData[serializationId] = saveStateTbl[id]
end
local serializedTable = TableUtils.Serialize(remappedData)
---@type REPENTOGON._Internals.ESSM.SaveData
local saveData = {
version = SAVE_DATA_VERSION,
checksum = checksum,
data = serializedTable,
}
local data = json_encode(saveData)
return data
end
---@param idMap table<integer, integer>
---@param fileName string
---@param checksum integer
local function _Serialize(idMap, fileName, checksum)
for modId, saveStateTbl in pairs(s_saveStateData) do
local mod = ModManager.GetModReferenceById(modId)
if not mod then
local modName = s_registeredMods[modId] -- use the first ever registered mod reference name
Isaac_DebugString(string_format("[ERROR] [ESSM] Registered mod \"%s\" no longer has a valid ModReference, cannot save data", modName))
goto continue
end
local success, result = pcall(serialize_data, saveStateTbl, idMap, checksum)
if not success then
Isaac_DebugString(string_format("[ERROR] [ESSM] Unable to save data for Mod \"%s\" in \"%s\": %s", mod.Name, fileName, result))
DeleteEntityData(mod, fileName)
else
SaveEntityData(mod, fileName, result)
end
::continue::
end
end
-- Register mods forcefully so that the system works as expected, even
-- if a mod has not accessed any data yet.
---@param mods ModReference[]
---@param modIds string[]
local function _PreDeserialize(mods, modIds)
for i = 1, #mods, 1 do
local modId = modIds[i]
if not s_registeredMods[modId] then
register_mod_id(mods[i], modId)
end
end
end
---@param serializedIds integer[]
---@param destIds integer[]
---@param encodedData string
---@param checksum integer
---@param outData table
---@return boolean, string
local function deserialize_data(serializedIds, destIds, encodedData, checksum, outData)
---@type boolean, REPENTOGON._Internals.ESSM.SaveData
local decodeSuccess, decodedData = pcall(json_decode, encodedData)
if not decodeSuccess then
return false, string_format("Unable to decode data: %s", decodedData)
end
if type(decodedData) ~= "table" then
return false, "decoded data is not a table"
end
local tblChecksum = decodedData.checksum
if not tblChecksum or tblChecksum ~= checksum then
return false, "checksum mismatch"
end
local data = decodedData.data
if type(data) ~= "table" then
return false, "decoded data does not have any data"
end
local deserializeSuccess, deserializedData = TableUtils.Deserialize(data)
if not deserializeSuccess then
return false, string_format("Unable to deserialize data: %s", deserializedData)
end
---@cast deserializedData table
for i = 1, #serializedIds, 1 do
local sourceId = serializedIds[i]
local deserialized = deserializedData[sourceId]
if type(deserialized) == "table" then
local id = destIds[i]
outData[id] = deserialized
end
end
return true, "success"
end
---@param serializedIds integer[]
---@param destIds integer[]
---@param fileName string
---@param checksum integer
local function _Deserialize(serializedIds, destIds, fileName, checksum)
assert(#serializedIds, #destIds)
for modId, saveStateTbl in pairs(s_saveStateData) do
local mod = ModManager.GetModReferenceById(modId)
if not mod then
local modName = s_registeredMods[modId] -- use the first ever registered mod reference name
Isaac_DebugString(string_format("[ERROR] [ESSM] Registered mod \"%s\" no longer has a valid ModReference, cannot load data", modName))
goto continue
end
local data = LoadEntityData(mod, fileName)
if not data then
Isaac_DebugString(string_format("[INFO] [ESSM] Mod '%s' does not have any data for '%s'", mod.Name, fileName))
goto continue
end
local success, err = deserialize_data(serializedIds, destIds, data, checksum, saveStateTbl)
if not success then
Isaac_DebugString(string_format("[ERROR] [ESSM] Unable to load data for Mod '%s' in '%s': %s", mod.Name, fileName, tostring(err)))
DeleteEntityData(mod, fileName)
end
::continue::
end
end
--#endregion
--#region API
local VALID_ENTITY_USERDATA = {
["Entity"] = true,
["EntityPlayer"] = true,
["EntityFamiliar"] = true,
["EntityTear"] = true,
["EntityBomb"] = true,
["EntityPickup"] = true,
["EntitySlot"] = true,
["EntityProjectile"] = true,
["EntityKnife"] = true,
["EntityLaser"] = true,
["EntityNPC"] = true,
["EntityEffect"] = true,
}
---@param dataTable table
---@param id integer
---@return table
---@return boolean
local function get_data(dataTable, id)
local entityData = dataTable[id]
local exists = true
if not entityData then
exists = false
entityData = {}
dataTable[id] = entityData
end
return entityData, exists
end
---@param mod ModReference
---@param entity Entity
---@param errLevel integer
---@return table, integer
local function get_entity_params(mod, entity, errLevel)
local modLookup = s_modLookup[mod]
if not modLookup then
local success, err = register_mod(mod)
modLookup = s_modLookup[mod]
if not success then
error(string_format("bad argument #1 (%s)", err), errLevel + 1)
end
end
local entityArgType = type(entity)
if entityArgType ~= "userdata" then
error(string_format("bad argument #2 (expected userdata, got %s)", entityArgType), errLevel + 1)
end
local id = GetPtrHash(entity)
if not s_validEntities[id] then
local specificError
local metatable = getmetatable(entity)
local userdataName = metatable.__name or metatable.__type
if not VALID_ENTITY_USERDATA[userdataName] then
specificError = string_format("got %s", userdataName)
else
specificError = "Entity no longer exists"
end
error(string_format("bad argument #2 (got invalid Entity, %s)", specificError), errLevel + 1)
end
return modLookup.entityData, id
end
---@param mod ModReference
---@param ess EntitiesSaveState
---@param errLevel integer
---@return table, integer
local function get_entity_save_state_params(mod, ess, errLevel)
local modLookup = s_modLookup[mod]
if not modLookup then
local success, err = register_mod(mod)
modLookup = s_modLookup[mod]
if not success then
error(string_format("bad argument #1 (%s)", err), errLevel + 1)
end
end
local essArgType = type(ess)
if essArgType ~= "userdata" then
error(string_format("bad argument #2 (expected userdata, got %s)", essArgType), errLevel + 1)
end
local userdataName = getmetatable(ess).__name
if userdataName ~= "EntitySaveState" then
error(string_format("bad argument #2 (expected EntitySaveState, got %s)", userdataName), errLevel + 1)
end
---@cast ess EntitiesSaveState
return modLookup.saveStateData, GetEntitySaveStateId(ess)
end
---@param mod ModReference
---@param entity Entity
---@return table
---@return boolean
local function GetEntityData(mod, entity)
local dataTable, id = get_entity_params(mod, entity, 2)
return get_data(dataTable, id)
end
---@param mod ModReference
---@param ess EntitiesSaveState
---@return table
---@return boolean
local function GetEntitySaveStateData(mod, ess)
local dataTable, id = get_entity_save_state_params(mod, ess, 2)
return get_data(dataTable, id)
end
---@param mod ModReference
---@param entity Entity
---@return table?
local function TryGetEntityData(mod, entity)
local dataTable, id = get_entity_params(mod, entity, 2)
return dataTable[id]
end
---@param mod ModReference
---@param ess EntitiesSaveState
---@return table?
local function TryGetEntitySaveStateData(mod, ess)
local dataTable, id = get_entity_save_state_params(mod, ess, 2)
return dataTable[id]
end
--#endregion
local Module = {}
Module._OnNewEntity = _OnNewEntity
Module._OnDeleteEntity = _OnDeleteEntity
Module._OnStoreEntity = _OnStoreEntity
Module._OnRestoreEntity = _OnRestoreEntity
Module._OnCopySaveStates = _OnCopySaveStates
Module._OnClearSaveStates = _OnClearSaveStates
Module._Serialize = _Serialize
Module._PreDeserialize = _PreDeserialize
Module._Deserialize = _Deserialize
Module.GetEntityData = GetEntityData
Module.GetEntitySaveStateData = GetEntitySaveStateData
Module.TryGetEntityData = TryGetEntityData
Module.TryGetEntitySaveStateData = TryGetEntitySaveStateData
return Module
@@ -0,0 +1,98 @@
---@alias REPENTOGON.ModId string
---@class REPENTOGON.ModData
--#region Data
---@type table<ModReference, REPENTOGON.ModId>
local s_modIds = {}
---@type table<REPENTOGON.ModId, ModReference[]>
local s_modReferences = {}
local s_modsLoaded = false
--#endregion
local table_insert = table.insert
local table_remove = table.remove
local GetModId = _CBindings.GetModId
---@param modReference ModReference
local function _RegisterMod(modReference)
local id = GetModId(modReference)
if not id then
return
end
assert(s_modIds[modReference] == nil, "The same mod has been registered multiple times")
s_modIds[modReference] = id
local modReferences = s_modReferences[id]
if not modReferences then
modReferences = {}
s_modReferences[id] = modReferences
end
table_insert(modReferences, modReference)
end
---@param modReference ModReference
local function _UnloadMod(modReference)
local id = s_modIds[modReference]
if not id then
return
end
s_modIds[modReference] = nil
local modReferences = s_modReferences[id]
for i = 1, #modReferences, 1 do
if modReferences[i] == modReference then
table_remove(modReferences, i)
break -- there should never be multiple of the same mod references in the list
end
end
end
local function _OnModsLoaded()
s_modsLoaded = true
end
---@param modReference ModReference
---@return REPENTOGON.ModId?
local function GetModIdByReference(modReference)
return s_modIds[modReference]
end
---@param modId REPENTOGON.ModId
---@return ModReference?
local function GetModReferenceById(modId)
local modReferences = s_modReferences[modId]
if modReferences then
return modReferences[1]
end
end
---@return fun(table: table<REPENTOGON.ModId, ModReference[]>, index?: REPENTOGON.ModId): REPENTOGON.ModId, ModReference[]
---@return table
local function GetModIterator()
return pairs(s_modReferences)
end
---@return boolean
local function ModsLoaded()
return s_modsLoaded
end
---@class REPENTOGON.Scripts.ModManager
local Module = {}
Module.detail = {}
Module.detail.RegisterMod = _RegisterMod
Module.detail.UnloadMod = _UnloadMod
Module.detail.OnModsLoaded = _OnModsLoaded
Module.GetModIdByReference = GetModIdByReference
Module.GetModReferenceById = GetModReferenceById
Module.ModsLoaded = ModsLoaded
Module.GetModIterator = GetModIterator
return Module
@@ -0,0 +1,53 @@
-- save copy of original enums, to make it harder for mods to mess with the repentogon features
local _ModCallbacks = ModCallbacks
local _MainMenuType = MainMenuType
local _ButtonAction = ButtonAction
local _Keyboard = Keyboard
local MaxPollCIdx = 3
local function UpdateMaxPollCIdx()
local str=Input.GetDeviceNameByIdx(0)
local i=0
while (str~=nil) do
i=i+1
str=Input.GetDeviceNameByIdx(i)
end
MaxPollCIdx=i
end
local function IsActionTriggeredAll(action)
for i = 0, MaxPollCIdx do
if Input.IsActionTriggered(action, i) then
return true
end
end
return false
end
local function IsButtonTriggeredAll(action)
for i = 0, MaxPollCIdx do
if Input.IsButtonTriggered(action, i) then
return true
end
end
return false
end
local function TweakModsMenu()
-- The values are automatically clamped so there's not much to worry about here
if MenuManager.GetActiveMenu() == _MainMenuType.MODS then
UpdateMaxPollCIdx()
if IsActionTriggeredAll(_ButtonAction.ACTION_MENULEFT) then
ModsMenu.SetSelectedElement(ModsMenu.GetSelectedElement() - 3)
elseif IsActionTriggeredAll(_ButtonAction.ACTION_MENURIGHT) then
ModsMenu.SetSelectedElement(ModsMenu.GetSelectedElement() + 3)
end
if IsButtonTriggeredAll(_Keyboard.KEY_PAGE_UP) or IsButtonTriggeredAll(_ButtonAction.ACTION_MENULT) then
ModsMenu.SetSelectedElement(ModsMenu.GetSelectedElement() - 10)
elseif IsButtonTriggeredAll(_Keyboard.KEY_PAGE_DOWN) or IsActionTriggeredAll(_ButtonAction.ACTION_MENURT) then
ModsMenu.SetSelectedElement(ModsMenu.GetSelectedElement() + 10)
end
end
end
Isaac.AddCallback(REPENTOGON, _ModCallbacks.MC_MAIN_MENU_RENDER, TweakModsMenu)
@@ -0,0 +1,306 @@
-- save copy of original enums, to make it harder for mods to mess with the repentogon features
local _ImGuiElement = _ImGuiElement
local _ImGuiCallback = ImGuiCallback
local _ModCallbacks = ModCallbacks
local _RoomTransitionAnim = RoomTransitionAnim
local _Direction = Direction
REPENTOGON.Extras.OnlineRNG=RNG()
local rng=REPENTOGON.Extras.OnlineRNG
local stubvec=Vector(-1,-1)
rng:SetSeed(1) --placeholder seed
local isonline=false
local checkonline=true
local con=nil
if REPENTOGON.NoOnlineStub then
return
end
function REPENTOGON.Extras.UnlinkCB() local cnt=0 for _,_ in pairs(_ModCallbacks) do cnt=cnt+1 end for i=0,cnt do local cb=Isaac.GetCallbacks(i,false) print(cb) while #(cb)~=0 do table.remove(cb,1) Isaac.SetBuiltInCallbackState(i, false) end end for _,ent in pairs(Isaac.GetRoomEntities()) do for entry,_ in pairs(ent:GetData()) do ent:GetData()[entry]=nil end end end --temporary, used to bypass mod unload callbacks since actions done there are just way too nasty for us!
local function CheckOnlineCoop()
if not Isaac.GetPlayer() then
print("[onlinestub] player not initialized yet!")
return false
end
for i=0, Game():GetNumPlayers() do
if (not Isaac.GetPlayer(i):IsLocalPlayer()) then
return true
end
end
return false
end
-- if Isaac.GetPlayer()==nil or (not CheckOnlineCoop()) then
-- REPENTOGON.Extras.OnlineStubReturned=true
-- return --preventing the thing from running in scenario when we aren't netstarting
-- end
if Isaac.GetPlayer() and CheckOnlineCoop() then
isonline=true
checkonline=false
else
Isaac.DebugString("[onlinestub] Assuming no netstart for now!")
end
local stubdata={}
REPENTOGON.Extras.UnsafeFuncs={}
REPENTOGON.Extras.UnsafeFuncs.MathRandom=math.random
REPENTOGON.Extras.UnsafeFuncs.Random=Random
REPENTOGON.Extras.UnsafeFuncs.RandomVector=RandomVector
REPENTOGON.Extras.UnsafeFuncs.ActionValue=Input.GetActionValue
REPENTOGON.Extras.UnsafeFuncs.ButtonValue=Input.GetButtonValue
REPENTOGON.Extras.UnsafeFuncs.KeyPress=Input.IsButtonPressed
REPENTOGON.Extras.UnsafeFuncs.KeyTrigger=Input.IsButtonTriggered
REPENTOGON.Extras.UnsafeFuncs.ActionPress=Input.IsActionPressed
REPENTOGON.Extras.UnsafeFuncs.ActionTrigger=Input.IsActionTriggered
REPENTOGON.Extras.UnsafeFuncs.MousePos=Input.GetMousePosition
REPENTOGON.Extras.UnsafeFuncs.MouseInput=Input.IsMouseBtnPressed
REPENTOGON.Extras.UnsafeFuncs.HasData=Isaac.HasModData
REPENTOGON.Extras.UnsafeFuncs.SaveData=Isaac.SaveModData
REPENTOGON.Extras.UnsafeFuncs.LoadData=Isaac.LoadModData
REPENTOGON.Extras.UnsafeFuncs.RemoveData=Isaac.RemoveModData
function Input.GetActionValue(act,cidx)
if (not isonline) or cidx~=0 then
return REPENTOGON.Extras.UnsafeFuncs.ActionValue(act,cidx)
end
local pl=Isaac.GetPlayer()
if pl then return REPENTOGON.Extras.UnsafeFuncs.ActionValue(act,pl.ControllerIndex) else return 0.0 end
end
function Input.GetButtonValue(act,cidx)
if (not isonline) or cidx~=0 then
return REPENTOGON.Extras.UnsafeFuncs.ButtonValue(act,cidx)
end
return 0.0
end
function Input.IsButtonPressed(act,cidx)
if (not isonline) or cidx~=0 then
return REPENTOGON.Extras.UnsafeFuncs.KeyPress(act,cidx)
end
return false
end
function Input.IsButtonTriggered(act,cidx)
if (not isonline) or cidx~=0 then
return REPENTOGON.Extras.UnsafeFuncs.KeyTrigger(act,cidx)
end
return false
end
function Input.IsActionPressed(act,cidx)
if (not isonline) or cidx~=0 then
return REPENTOGON.Extras.UnsafeFuncs.ActionPress(act,cidx)
end
local pl=Isaac.GetPlayer()
if pl then return REPENTOGON.Extras.UnsafeFuncs.ActionPress(act,pl.ControllerIndex) else return false end
end
function Input.IsActionTriggered(act,cidx)
if (not isonline) or cidx~=0 then
return REPENTOGON.Extras.UnsafeFuncs.ActionTrigger(act,cidx)
end
local pl=Isaac.GetPlayer()
if pl then return REPENTOGON.Extras.UnsafeFuncs.ActionTriggerda(act,pl.ControllerIndex) else return false end
end
function Isaac.HasModData(modref)
if not isonline then
return REPENTOGON.Extras.UnsafeFuncs.HasData(modref)
end
if stubdata[modref] then
return true
end
return false
end
function Isaac.LoadModData(modref)
if not isonline then
return REPENTOGON.Extras.UnsafeFuncs.LoadData(modref)
end
if stubdata[modref]~=nil then
return stubdata[modref]
end
return "" --stub
end
function Isaac.SaveModData(modref,data)
if not isonline then
return REPENTOGON.Extras.UnsafeFuncs.SaveData(modref,data)
end
stubdata[modref]=data
return false --stub
end
function Isaac.RemoveModData(modref)
if not isonline then
return REPENTOGON.Extras.UnsafeFuncs.RemoveData(modref)
end --stub
stubdata[modref]=nil
end
function Input.GetMousePosition(gamecoords)
if not isonline then
return REPENTOGON.Extras.UnsafeFuncs.MousePos(gamecoords)
end
if gamecoords then
return Isaac.ScreenToWorld(stubvec)
end
return stubvec --stub
end
function Input.IsMouseBtnPressed(button)
if not isonline then
return REPENTOGON.Extras.UnsafeFuncs.MouseInput(button)
end
return 0 --stub
end
function math.random(...)
local args={...}
local min=args[1]
local max=args[2]
if not isonline then
return REPENTOGON.Extras.UnsafeFuncs.MathRandom(...)
end
if min==nil and max==nil then
return rng:RandomFloat()
end
if min~=nil and max==nil then
return rng:RandomInt(min)+1
end
return rng:RandomInt(max-min+1)+min
end
function Random()
if not isonline then
return REPENTOGON.Extras.UnsafeFuncs.Random()
end
return rng:RandomInt(2^32 - 1) --might not be 100% accurate but eh, good enough
end
function RandomVector()
if not isonline then
return REPENTOGON.Extras.UnsafeFuncs.RandomVector()
end
return Vector.FromAngle(math.random()*360)
end
function REPENTOGON.Extras.IsOnlineStub()
return isonline
end
local function ScheduleLuaReset()
if Game():GetFrameCount()>30 then
Isaac.RemoveCallback(REPENTOGON, _ModCallbacks.MC_POST_UPDATE,ScheduleLuaReset)
print('Please, run the "luareset" debug command :)')
if not REPENTOGON.Extras.NoImGui then
local imgui = Isaac.GetImGui()
imgui:CreateWindow("luareset-warning","A rather important message!")
imgui:AddElement("luareset-warning","luareset-text",_ImGuiElement.Text,'Hey, folks, can you please have one person run the "luareset" command for me?')
imgui:AddElement("luareset-warning","luareset-okay",_ImGuiElement.Button,"Okay, I will!")
imgui:AddCallback("luareset-okay", _ImGuiCallback.Clicked, function() imgui:RemoveWindow("luareset-warning") imgui:Hide() end)
imgui:SetVisible("luareset-warning",true)
imgui:Show()
end
-- Isaac.ExecuteCommand("luareset")
end
end
local function ScheduleRestart()
if Game():GetFrameCount()>1 then
Isaac.ExecuteCommand("seed "..Game():GetSeeds():GetStartSeedString())
Isaac.RemoveCallback(REPENTOGON, _ModCallbacks.MC_POST_UPDATE,ScheduleRestart)
Isaac.AddCallback(REPENTOGON, _ModCallbacks.MC_POST_UPDATE,ScheduleLuaReset)
end
end
local function SetOnlineRNG()
if not checkonline then
return
end
checkonline=false
stubdata={}
isonline=CheckOnlineCoop() --will be set to false on local only runs
rng:SetSeed(Game():GetSeeds():GetStartSeed(),35)
if isonline then
REPENTOGON.Extras.UnlinkCB()
Isaac.AddCallback(REPENTOGON, _ModCallbacks.MC_POST_UPDATE,ScheduleRestart)
end
end
local function ResetStubData()
stubdata={}
checkonline=true
end
function REPENTOGON.Extras.SetOnlineStub(val)
isonline=val
checkonline=false
end
local function render()
if isonline then
Isaac.RenderScaledText("Online stubber enabled!",5,Isaac.GetScreenHeight()-8,0.5,0.5,1,1,1,0.5)
end
end
local function TeleportToBeast()
Isaac.ExecuteCommand("goto x.itemdungeon.666")
Game():StartRoomTransition(-3, _Direction.NO_DIRECTION, _RoomTransitionAnim.FADE,nil,-1)
Isaac.RemoveCallback(REPENTOGON, _ModCallbacks.MC_POST_UPDATE,TeleportToBeast)
end
local function DelayDogmaTeleport(_,npc)
if npc:GetSprite():GetFrame()>=110 then
Isaac.AddCallback(REPENTOGON, _ModCallbacks.MC_POST_UPDATE,TeleportToBeast)
Isaac.RemoveCallback(REPENTOGON, _ModCallbacks.MC_POST_NPC_RENDER,DelayDogmaTeleport)
end
end
local function DogmaStub(_,npc)
if isonline and npc.Variant==2 and Game():GetLevel():GetStage()==13 and Game():GetLevel():GetStageType()>0 and Game():GetLevel():GetCurrentRoomIndex()==109 then
Isaac.AddCallback(REPENTOGON, _ModCallbacks.MC_POST_NPC_RENDER,DelayDogmaTeleport)
end
end
local function DesyncDetect()
if isonline and not REPENTOGON.Extras.NoImGui then
if not con then con=Game():GetConsole() end
local conhist=con:GetHistory()
local imgui = Isaac.GetImGui()
for i=1,5 do
if string.match(conhist[i],"Checksum mismatch") then
print("\n\n\n\n\n")
imgui:CreateWindow("desync-warning","Fuck.")
imgui:AddElement("desync-warning","desync-text", _ImGuiElement.Text,'Shit just happened, want to try a "rewind"? Maybe a "restart"?')
imgui:AddElement("desync-warning","desync-rewind", _ImGuiElement.Button,"Please rewind!")
imgui:AddElement("desync-warning","desync-restart", _ImGuiElement.Button,"I choose a restart")
imgui:AddCallback("desync-rewind", _ImGuiCallback.Clicked,function() imgui:RemoveWindow("desync-warning") imgui:Hide() Isaac.ExecuteCommand("rewind") end)
imgui:AddCallback("desync-restart", _ImGuiCallback.Clicked,function() imgui:RemoveWindow("desync-warning") imgui:Hide() Isaac.ExecuteCommand("restart") end)
imgui:SetVisible("desync-warning",true)
imgui:Show()
break
end
end
end
end
function REPENTOGON.Extras.StubCallbacks()
Isaac.AddCallback(REPENTOGON, _ModCallbacks.MC_POST_UPDATE, DesyncDetect)
Isaac.AddCallback(REPENTOGON, _ModCallbacks.MC_POST_ENTITY_KILL, DogmaStub,950)
Isaac.AddCallback(REPENTOGON, _ModCallbacks.MC_POST_RENDER, render)
Isaac.AddCallback(REPENTOGON, _ModCallbacks.MC_PRE_GAME_EXIT, ResetStubData)
Isaac.AddCallback(REPENTOGON, _ModCallbacks.MC_POST_NEW_ROOM, SetOnlineRNG) --because new room triggers before anything else :skull:
end
REPENTOGON.Extras.StubCallbacks()
@@ -0,0 +1,220 @@
---@class REPENTOGON._Internals.SSM.ModData
---@field gameData table
---@field gameStates table[]
---@class REPENTOGON.SSM.SaveData
---@field version integer
---@field checksum integer
---@field gameData REPENTOGON.SerializedTable
--#region Data
---@type table<REPENTOGON.ModId, REPENTOGON._Internals.SSM.ModData>
local s_modData = {}
--#endregion
local MAIN_GAME_STATE = 0
local SAVE_DATA_VERSION = 1
local json = require("json")
local ModManager = _GetModule("repentogon_extras.mod_manager")
local TableUtils = _GetModule("repentogon_extras.table_utils")
local HasModData = _CBindings.HasModData
local SaveModData = _CBindings.SaveModData
local LoadModData = _CBindings.LoadModData
local RemoveModData = _CBindings.RemoveModData
local RemoveAllData = _CBindings.RemoveAllData
---@param fileName string
---@return string
local function get_file_name(fileName)
return "SaveStateManager/" .. fileName .. ".dat"
end
---Tries to initialize mod's gameData and returns.
---@param modId REPENTOGON.ModId
---@return REPENTOGON._Internals.SSM.ModData
local function get_data(modId)
local modData = s_modData[modId]
if not modData then
modData = {gameData = {}, gameStates = {}}
s_modData[modId] = modData
end
return modData
end
---Gets the mod's gameData
---@param mod ModReference
local function GetGameData(mod)
local modId = ModManager.GetModIdByReference(mod)
if not modId then
error(string.format("bad argument #1 (ModReference expected, got %s)", type(mod)), 2)
end
local modData = get_data(modId)
return modData.gameData
end
---Resets the mod's gameData
---@param mod ModReference
local function ClearGameData(mod)
local modId = ModManager.GetModIdByReference(mod)
if not modId then
error(string.format("bad argument #1 (ModReference expected, got %s)", type(mod)), 2)
end
local modData = get_data(modId)
modData.gameData = {}
end
---Copies all mods' gameData to gameState
---@param gameStateId integer
local function StoreGameState(gameStateId)
for _, modData in pairs(s_modData) do
modData.gameStates[gameStateId] = TableUtils.DeepCopy(modData.gameData)
end
end
---Copies all mods' gameState to gameData
---@param gameStateId integer
local function RestoreGameState(gameStateId)
for _, modData in pairs(s_modData) do
local state = modData.gameStates[gameStateId] or {}
modData.gameData = TableUtils.DeepCopy(state)
end
end
---Clears all mods' gameState
---@param gameStateId integer
local function ClearGameState(gameStateId)
for _, modData in pairs(s_modData) do
modData.gameStates[gameStateId] = nil
end
end
---Serializes mods' main gameState and saves it to a file in the 'data' folder
---@param gameStateInfo REPENTOGON.GameStateInfo
local function SerializeGameState(gameStateInfo)
for modId, modData in pairs(s_modData) do
local gameData = modData.gameStates[MAIN_GAME_STATE] or {}
local serializedData = TableUtils.Serialize(gameData)
---@type REPENTOGON.SSM.SaveData
local saveData = {
version = SAVE_DATA_VERSION,
checksum = gameStateInfo.checksum,
gameData = serializedData
}
local modReference = ModManager.GetModReferenceById(modId)
if not modReference then
goto continue
end
local fileName = get_file_name(gameStateInfo.fileName)
local success = SaveModData(modReference, fileName, json.encode(saveData))
if not success then
Isaac.DebugString(string.format("[ERROR] [SSM] Unable to Save mod data for '%s'", tostring(modReference.Name)))
end
::continue::
end
end
---@param gameStateInfo REPENTOGON.GameStateInfo
---@param serializedData string
---@return boolean ok
---@return table | string
local function deserialize_game_state(gameStateInfo, serializedData)
local ok, saveData = pcall(json.decode, serializedData)
if not ok then
return false, saveData
end
if type(saveData) ~= "table" then
return false, "decoded data is not a table"
end
---@cast saveData REPENTOGON.SSM.SaveData
if saveData.checksum ~= gameStateInfo.checksum then
return false, "checksum mismatch"
end
local gameData = saveData.gameData
if type(gameData) ~= "table" then
return false, "no mod data found"
end
local ok, data = TableUtils.Deserialize(gameData)
if not ok then
return false, data
end
return true, data
end
---Clears each mod's main gameState and tries to load the game state file.
---If successful it loads the data into the main gameState.
---@param gameStateInfo REPENTOGON.GameStateInfo
local function DeserializeGameState(gameStateInfo)
for modId, modReferences in ModManager.GetModIterator() do
local modRef = modReferences[1]
if not modRef then
goto continue
end
local fileName = get_file_name(gameStateInfo.fileName)
local noDataInit = not s_modData[modId] and not HasModData(modRef, fileName)
if noDataInit then
goto continue
end
local modData = get_data(modId)
modData.gameStates[MAIN_GAME_STATE] = nil
local serializedData = LoadModData(modRef, fileName)
if not serializedData then
goto continue
end
local ok, data = deserialize_game_state(gameStateInfo, serializedData)
if not ok then
Isaac.DebugString(string.format("[ERROR] [SSM] Unable to decode mod data for '%s' in '%s': %s", tostring(modRef.Name), fileName, data))
RemoveModData(modRef, fileName)
goto continue
end
---@cast data table
modData.gameStates[MAIN_GAME_STATE] = data
::continue::
end
end
---Delete all mod files for that fileName
---@param fileName string
local function DeleteGameState(fileName)
RemoveAllData(get_file_name(fileName))
end
---Reset game data for all mods
local function CleanupState()
for _, modData in pairs(s_modData) do
modData.gameData = {}
end
end
---@class REPENTOGON.Scripts.SSM
local Module = {}
Module.GetGameData = GetGameData
Module.ClearGameData = ClearGameData
Module._StoreGameState = StoreGameState
Module._RestoreGameState = RestoreGameState
Module._ClearGameState = ClearGameState
Module._SerializeGameState = SerializeGameState
Module._DeserializeGameState = DeserializeGameState
Module._DeleteGameState = DeleteGameState
Module._CleanupState = CleanupState
return Module
@@ -0,0 +1,258 @@
-- save copy of original enums, to make it harder for mods to mess with the repentogon features
local _Achievement = Achievement
local _EventCounter = EventCounter
local _ModCallbacks = ModCallbacks
local _CollectibleType = CollectibleType
local _MainMenuType = MainMenuType
local _ButtonAction = ButtonAction
local _SoundEffect = SoundEffect
local _ButtonActionBitwise = ButtonActionBitwise
local StatsMenuRep = {
StatPageAngleOffsetX = -2,
StatPageNumberOffsetX = 120,
StatSheetSprite = Sprite(),
StatSheetSpritePos = Vector(-39, -15),
ArrowSprite = Sprite(),
LeftArrowSpritePos = Vector(-93, -33),
RightArrowSpritePos = Vector(-169, -25),
ScheduleRefresh = true,
CurrentlyDisplayedCategoryID = 1,
-- data structure: {category name, {stat name (string or table of lines), EventCounter enum or custom function to calculate stat, current value, value text width/2}}
Stats = {
{
"GAME STATS", {
{ "deaths", _EventCounter.DEATHS },
{ "items", function()
local gameData = Isaac.GetPersistentGameData()
local itemconfig = Isaac.GetItemConfig()
local sum = 0
local unlocked = 0
for id = 1, 732 do --this wont work for modded items for now so hardcoded 732 it is
local configEntry = itemconfig:GetCollectible(id)
if configEntry and not configEntry.Hidden then
sum = sum + 1
if gameData:IsItemInCollection(id) then
unlocked = unlocked + 1
end
end
end
return unlocked .. "/" .. sum
end },
{ "mom kills", _EventCounter.MOM_KILLS },
{ "secrets", function()
local gameData = Isaac.GetPersistentGameData()
local sum = 0
local unlocked = 0
local previousValues = {}
for _, value in pairs(_Achievement) do
if not previousValues[value] then
sum = sum + 1
previousValues[value] = true
if gameData:Unlocked(value) then
unlocked = unlocked + 1
end
end
end
return unlocked .. "/" .. sum
end },
{ "best streak", _EventCounter.BEST_STREAK },
{ "best online streak", _EventCounter.ONLINE_BEST_STREAK },
{ "", function() return "" end }, -- spacer
{ "eden tokens", _EventCounter.EDEN_TOKENS },
{ "", function() return "" end }, -- spacer
{ "dailys played", _EventCounter.DAILYS_PLAYED },
{ "dailys won", _EventCounter.DAILYS_WON },
} },
{
"BOSS KILLS", {
{ "isaac kills", _EventCounter.ISAAC_KILLS },
{ "satan kills", _EventCounter.SATAN_KILLS },
{ "blue baby kills", _EventCounter.BLUE_BABY_KILLS },
{ "lamb kills", _EventCounter.LAMB_KILLS },
{ "hush kills", _EventCounter.HUSH_KILLS },
{ "delirium kills", _EventCounter.DELIRIUM_KILLS },
{ "mega satan kills", _EventCounter.MEGA_SATAN_KILLS },
{ "mother kills", _EventCounter.MOTHER_KILLS },
{ "beast kills", _EventCounter.BEAST_KILLS },
{ "baby plum kills", _EventCounter.BABY_PLUM_KILLS },
{ "boss rushs cleared", _EventCounter.BOSSRUSHS_CLEARED },
} },
{
"SHOPPING", {
{ "shopkeeper killed", _EventCounter.SHOPKEEPER_KILLED },
{ "items bought", _EventCounter.SHOP_ITEMS_BOUGHT },
{ "angel deals taken", _EventCounter.ANGEL_DEALS_TAKEN },
{ "devil deals taken", _EventCounter.DEVIL_DEALS_TAKEN },
{ "", function() return "" end }, -- spacer
{ { "donation machine", "coins" }, _EventCounter.DONATION_MACHINE_COUNTER },
{ { "greed donation", "machine coins" }, _EventCounter.GREED_DONATION_MACHINE_COUNTER },
} },
{
"GAMBLING", {
{ "arcades entered", _EventCounter.ARCADES_ENTERED },
{ "shellgames played", _EventCounter.SHELLGAMES_PLAYED },
{ { "blood donation", "machine used" }, _EventCounter.BLOOD_DONATION_MACHINE_USED },
{ { "slot machines", "broken" }, _EventCounter.SLOT_MACHINES_BROKEN },
{ { "golden chests", "opened" }, _EventCounter.CHESTS_OPENED_WITH_KEY },
{ { "secret room", "walls broken" }, _EventCounter.SECRET_ROOMS_WALLS_OPENED },
} },
{
"CHAOS", {
{ "rocks destroyed", _EventCounter.ROCKS_DESTROYED },
{ { "tinted rocks", "destroyed" }, _EventCounter.TINTED_ROCKS_DESTROYED },
{ { "super special", "rocks destroyed" }, _EventCounter.SUPER_SPECIAL_ROCKS_DESTROYED },
{ "poop destroyed", _EventCounter.POOP_DESTROYED },
{ { "rainbow poop", "destroyed" }, _EventCounter.RAINBOW_POOP_DESTROYED },
{ "pills eaten", _EventCounter.PILLS_EATEN },
{ "cards used", _EventCounter.CARDS_USED },
{ "batteries collected", _EventCounter.BATTERIES_COLLECTED },
{ "battery bums killed", _EventCounter.BATTERY_BUMS_KILLED },
} },
{
"MISC", {
{ "beds used", _EventCounter.BEDS_USED },
{ { "battery bum", "collectible payouts" }, _EventCounter.BATTERY_BUM_COLLECTIBLE_PAYOUTS },
} },
}
}
local StatsMenuPos = Vector(35, 34)
local MaxCategoryID = 1
local font = Font()
font:Load("font/teammeatex/teammeatex10.fnt")
local fontcolor = KColor(0.20, 0.15, 0.1, 1)
local MaxPollCIdx = 3
local function UpdateMaxPollCIdx()
local str=Input.GetDeviceNameByIdx(0)
local i=0
while (str~=nil) do
i=i+1
str=Input.GetDeviceNameByIdx(i)
end
MaxPollCIdx=i
end
local function IsActionTriggeredAll(action)
for i = 0, MaxPollCIdx do
if Input.IsActionTriggered(action, i) then
return true
end
end
return false
end
local function RefreshExtraStats()
StatsMenuRep.ScheduleRefresh = true
end
local function LoadAssets()
if #StatsMenuRep.StatSheetSprite:GetDefaultAnimation() <= 0 then
StatsMenuRep.StatSheetSprite:Load("gfx/ui/main menu/statsmenu.anm2", true)
StatsMenuRep.StatSheetSprite:SetFrame("Idle", 0)
StatsMenuRep.ArrowSprite:Load("gfx/ui/leaderboardmenu.anm2", true)
StatsMenuRep.ArrowSprite:SetFrame("Idle", 0)
end
if not font:IsLoaded() then
font:Load("font/teammeatex/teammeatex10.fnt")
end
if font:IsLoaded() and #(StatsMenuRep.StatSheetSprite:GetDefaultAnimation()) > 0 then
Isaac.RemoveCallback(REPENTOGON, _ModCallbacks.MC_MAIN_MENU_RENDER, LoadAssets)
end
end
Isaac.AddCallback(REPENTOGON, _ModCallbacks.MC_MAIN_MENU_RENDER, LoadAssets)
local function RenderExtraStats()
if StatsMenu:IsSecretsMenuVisible() then
StatsMenu:GetStatsMenuSprite():GetLayer("Paper1"):SetVisible(true)
return
end
if MenuManager:GetActiveMenu() == _MainMenuType.SAVES then StatsMenuRep.ScheduleRefresh = true end
if MenuManager:GetActiveMenu() == _MainMenuType.STATS then
UpdateMaxPollCIdx()
if StatsMenuRep.ScheduleRefresh then
local gameData = Isaac.GetPersistentGameData()
MaxCategoryID = #StatsMenuRep.Stats + 1
for i, categoryData in ipairs(StatsMenuRep.Stats) do
for j, stat in ipairs(categoryData[2]) do
if type(stat[2]) == "function" then
StatsMenuRep.Stats[i][2][j][3] = stat[2]()
else
StatsMenuRep.Stats[i][2][j][3] = gameData:GetEventCounter(stat[2])
end
StatsMenuRep.Stats[i][2][j][4] = font:GetStringWidthUTF8(tostring(StatsMenuRep.Stats[i][2][j][3])) / 2
end
end
StatsMenuRep.ScheduleRefresh = false
end
if IsActionTriggeredAll(_ButtonAction.ACTION_MENULEFT) and MenuManager.GetInputMask() & _ButtonActionBitwise.ACTION_MENULEFT ~= 0 then
SFXManager():Play(_SoundEffect.SOUND_PAPER_IN)
StatsMenuRep.CurrentlyDisplayedCategoryID = (StatsMenuRep.CurrentlyDisplayedCategoryID - 1) % MaxCategoryID
if StatsMenuRep.CurrentlyDisplayedCategoryID == 0 then
StatsMenuRep.CurrentlyDisplayedCategoryID = MaxCategoryID - 1
end
elseif IsActionTriggeredAll(_ButtonAction.ACTION_MENURIGHT) and MenuManager.GetInputMask() & _ButtonActionBitwise.ACTION_MENURIGHT ~= 0 then
SFXManager():Play(_SoundEffect.SOUND_PAPER_IN)
StatsMenuRep.CurrentlyDisplayedCategoryID = math.max(
(StatsMenuRep.CurrentlyDisplayedCategoryID + 1) % MaxCategoryID, 1)
end
end
StatsMenu:GetStatsMenuSprite():GetLayer("Paper1"):SetVisible(false)
-- render stat page over original stat page, to allow for custom content
local posSheet = Isaac.WorldToMenuPosition(_MainMenuType.STATS, StatsMenuRep.StatSheetSpritePos)
StatsMenuRep.StatSheetSprite:RenderLayer(1, posSheet)
local posLeftArrow = Isaac.WorldToMenuPosition(_MainMenuType.STATS, StatsMenuRep.LeftArrowSpritePos)
StatsMenuRep.ArrowSprite:RenderLayer(6, posLeftArrow)
local posRightArrow = Isaac.WorldToMenuPosition(_MainMenuType.STATS, StatsMenuRep.RightArrowSpritePos)
StatsMenuRep.ArrowSprite:RenderLayer(7, posRightArrow)
local nextLineOffsetX = 0
local nextLineOffsetY = 0
local pos = Isaac.WorldToMenuPosition(_MainMenuType.STATS, StatsMenuPos)
local categoryData = StatsMenuRep.Stats[StatsMenuRep.CurrentlyDisplayedCategoryID]
font:DrawStringUTF8(categoryData[1], pos.X, pos.Y + nextLineOffsetY, fontcolor, 0, false)
nextLineOffsetY = nextLineOffsetY + 12
for _, stat in ipairs(categoryData[2]) do
-- text
local statValue = tostring(stat[3] or 0)
local statValueWidth = stat[4] or 0
if type(stat[1]) == "table" then
nextLineOffsetY = nextLineOffsetY + 2 -- some padding aboth
for i, text in ipairs(stat[1]) do
font:DrawStringUTF8(text, pos.X + nextLineOffsetX, pos.Y + nextLineOffsetY, fontcolor, 0, false)
if i ~= #stat[1] then
nextLineOffsetY = nextLineOffsetY + 12
nextLineOffsetX = nextLineOffsetX + StatsMenuRep.StatPageAngleOffsetX
end
end
-- value
font:DrawStringUTF8(statValue, pos.X + nextLineOffsetX + StatsMenuRep.StatPageNumberOffsetX - statValueWidth,
pos.Y + nextLineOffsetY - 5, fontcolor, 0, false)
nextLineOffsetY = nextLineOffsetY + 2 -- some padding below
else
font:DrawStringUTF8(stat[1], pos.X + nextLineOffsetX, pos.Y + nextLineOffsetY, fontcolor, 0, false)
-- value
font:DrawStringUTF8(statValue, pos.X + nextLineOffsetX + StatsMenuRep.StatPageNumberOffsetX - statValueWidth,
pos.Y + nextLineOffsetY + 2, fontcolor, 0, false)
end
nextLineOffsetY = nextLineOffsetY + 12
nextLineOffsetX = nextLineOffsetX + StatsMenuRep.StatPageAngleOffsetX
end
end
REPENTOGON.Extras.StatsMenu = StatsMenuRep
Isaac.AddCallback(REPENTOGON, _ModCallbacks.MC_PRE_GAME_EXIT, RefreshExtraStats)
Isaac.AddCallback(REPENTOGON, _ModCallbacks.MC_MAIN_MENU_RENDER, RenderExtraStats)
@@ -0,0 +1,196 @@
---@class REPENTOGON.SerializedTable
---@field _data table -- connects a string key to plain data
---@field _links table -- connects a string key to a table id
---@field _specialKeyData table -- connects a special key (number and boolean) to plain data
---@field _specialKeyLinks table -- connects a special key (number and boolean) to a table id
local NON_SERIALIZABLE_KEYS = {
["userdata"] = true,
["table"] = true,
["function"] = true,
["thread"] = true,
}
local NON_SERIALIZABLE_VALUES = {
["userdata"] = true,
["function"] = true,
["thread"] = true,
}
-- the json library does not properly restore these types of json keys
local SPECIAL_JSON_KEYS = {
["boolean"] = true,
["number"] = true,
}
---@param tbl table
---@param memoTable table<table, table>
---@return table
local function deep_copy(tbl, memoTable)
local memo = memoTable[tbl]
if memo then
return memo
end
local copy = {}
memoTable[tbl] = copy
for key, value in pairs(tbl) do
local keyType = type(key)
local valueType = type(value)
if NON_SERIALIZABLE_KEYS[keyType] then
goto continue
end
if NON_SERIALIZABLE_VALUES[valueType] then
goto continue
end
if valueType == "table" then
copy[key] = deep_copy(value, memoTable)
else
copy[key] = value
end
::continue::
end
return copy
end
---@param tbl table
---@return table
local function DeepCopy(tbl)
return deep_copy(tbl, {})
end
---@param tbl table
---@param saveData REPENTOGON.SerializedTable
---@param memoTable table<table, integer>
---@return integer
local function serialize_table(tbl, saveData, memoTable)
local memoId = memoTable[tbl]
if memoId then
return memoId
end
local tables = saveData._data
local id = #tables + 1
memoTable[tbl] = id
local plainData = {}
local links = {}
local specialKeyPlainData = {}
local specialKeyLinks = {}
table.insert(tables, plainData)
table.insert(saveData._links, links)
table.insert(saveData._specialKeyData, specialKeyPlainData)
table.insert(saveData._specialKeyLinks, specialKeyLinks)
for key, value in pairs(tbl) do
local keyType = type(key)
local valueType = type(value)
if NON_SERIALIZABLE_KEYS[keyType] then
goto continue
end
if NON_SERIALIZABLE_VALUES[valueType] then
goto continue
end
local dataTable = plainData
local specialKey = SPECIAL_JSON_KEYS[keyType] ~= nil
if valueType == "table" then
value = serialize_table(value, saveData, memoTable)
if specialKey then
dataTable = specialKeyLinks
else
dataTable = links
end
elseif specialKey then
dataTable = specialKeyPlainData
end
if specialKey then
table.insert(dataTable, {key, value})
else
dataTable[key] = value
end
::continue::
end
return id
end
---@param tbl table
---@return REPENTOGON.SerializedTable
local function Serialize(tbl)
---@type REPENTOGON.SerializedTable
local serializedTable = {
_data = {},
_specialKeyData = {},
_links = {},
_specialKeyLinks = {},
}
serialize_table(tbl, serializedTable, {})
return serializedTable
end
---@param serializeTable REPENTOGON.SerializedTable
local function assert_serialized_table_size(serializeTable)
local size = #serializeTable._data
if size == #serializeTable._specialKeyData and
size == #serializeTable._links and
size == #serializeTable._specialKeyLinks then
return true
end
return false
end
---@param serializeTable REPENTOGON.SerializedTable
---@return boolean ok
---@return table | string -- table or error
local function Deserialize(serializeTable)
if not assert_serialized_table_size(serializeTable) then
return false, "table is corrupted (sizes don't match)"
end
local tables = serializeTable._data
for i = 1, #tables, 1 do
local tbl = tables[i]
local specialTbl = serializeTable._specialKeyData[i]
local links = serializeTable._links[i]
local specialLinks = serializeTable._specialKeyLinks[i]
for j = 1, #specialTbl, 1 do
local keyVal = specialTbl[j]
tbl[keyVal[1]] = keyVal[2]
end
for k, v in pairs(links) do
tbl[k] = tables[v]
end
for j = 1, #specialLinks, 1 do
local keyVal = specialLinks[j]
tbl[keyVal[1]] = tables[keyVal[2]]
end
end
return true, tables[1]
end
---@class REPENTOGON.Scripts.TableUtils
local Module = {}
Module.DeepCopy = DeepCopy
Module.Serialize = Serialize
Module.Deserialize = Deserialize
return Module
File diff suppressed because it is too large. Load diff
+7 -1
View File
@@ -12,6 +12,9 @@
#include "level/room_transition.h"
#include "engine/kage_input.h"
#include "engine/texture_cache.h"
#ifdef ISAAC_REPENTOGON
#include "repentogon/options.h"
#endif
#include <SDL3/SDL_mouse.h>
#include <SDL3/SDL_video.h>
#include <algorithm>
@@ -522,7 +525,7 @@ static void daily_challenge_clear(DailyChallenge& daily)
// lobby from the command line are offline.
// The import tool's resources/ replaces the packed archives, their mount points and their load timing.
// Lua uses the system allocator, so --luaheapsize is ignored. LuaEngine's inlined construction is its own, run by new
// once taken over.
// once taken over. REPENTOGON's options load first, as its scripts read them.
void IsaacStartup(int argc, uint8_t** argv)
{
StartupArguments arguments;
@@ -533,6 +536,9 @@ void IsaacStartup(int argc, uint8_t** argv)
if (argument == LUA_DEBUG_FLAG) arguments.luaMode = LUA_MODE_DEBUG;
else if (argument == NETWORK_TEST_FLAG) isNetworkTestRequested = true;
}
#ifdef ISAAC_REPENTOGON
repentogonOptions.load();
#endif
LuaEngine* luaEngine = new LuaEngine();
g_luaEngine = luaEngine;
luaEngine->Init(arguments.luaMode);
+14 -9
View File
@@ -18,6 +18,9 @@
#include "engine/platform.h"
#include "level/room.h"
#include "level/room_grid.h"
#ifdef ISAAC_REPENTOGON
#include "repentogon/repentogon.h"
#endif
#include <SDL3/SDL_mouse.h>
#include <algorithm>
#include <cctype>
@@ -286,8 +289,8 @@ static int mod_data_remove(lua_State* state)
}
// 0085f0f0 The file a module name is in: dots become folders and .lua is added, searched in resources/scripts/, the
// running script's folder, and that folder under the mods folder. The name is lowercased, as the import tool lowercases
// every path a mod ships. Empty when none exists, with tried listing them.
// running script's folder, and that folder under the mods folder, with REPENTOGON's scripts folder first. The name is
// lowercased, as the import tool lowercases every path a mod ships. Empty when none exists, with tried listing them.
static std::string module_path_find(std::string_view name, std::string& tried)
{
std::string module(name);
@@ -299,7 +302,11 @@ static std::string module_path_find(std::string_view name, std::string& tried)
std::string scriptPath = lua_engine_get().scriptPath;
std::string local = scriptPath.substr(0, scriptPath.find_last_of(PATH_SEPARATORS)) + "/" + module;
for (const std::string& path : {resource_path(SCRIPTS_FOLDER + module), local, platform.modsDirectory + local})
for (const std::string& path : {
#ifdef ISAAC_REPENTOGON
repentogon_script_path(module),
#endif
resource_path(SCRIPTS_FOLDER + module), local, platform.modsDirectory + local})
{
std::error_code error;
if (std::filesystem::exists(path, error)) return path;
@@ -500,12 +507,10 @@ static void isaac_register(lua_State* state)
EntityList& list = g_game->room->entityList;
return std::max(list.bossCount + list.pendingBossCount, 0);
});
lua_method(state, "SetBuiltInCallbackState", [](int callback, bool isEnabled) {
if ((uint32_t)callback < LUA_CALLBACK_COUNT) lua_engine_get().enabledCallbacks[callback] = isEnabled;
});
lua_method(state, "GetBuiltInCallbackState", [](int callback) {
return (uint32_t)callback < LUA_CALLBACK_COUNT && lua_engine_get().enabledCallbacks[callback];
});
lua_method(state, "SetBuiltInCallbackState",
[](int callback, bool isEnabled) { lua_engine_get().callback_state_set(callback, isEnabled); });
lua_method(state, "GetBuiltInCallbackState",
[](int callback) { return lua_engine_get().is_callback_enabled(callback); });
lua_method(state, "WorldToScreen", [](Vector position) {
if (!g_game) return position;
+139
View File
@@ -0,0 +1,139 @@
#pragma once
#include "lua/api.h"
#include <optional>
// One run of a callback: the name its errors log, its id, and the parameter mods filter it by, nil when it has none.
// A REPENTOGON callback may filter by a second parameter, which runs it through _RunCallbackWithTwoParams.
struct CallbackRun
{
const char* name;
int id;
std::optional<int> param = CALLBACK_PARAM_NONE;
std::optional<int> secondParam;
};
// Pushes a filter parameter, nil when there is none.
inline void param_push(lua_State* state, std::optional<int> param)
{
if (param) lua_pushinteger(state, *param);
else lua_pushnil(state);
}
// Calls _RunCallback (_RunCallbackWithTwoParams for two filter parameters) with a callback's id, its filter parameters
// and its arguments when a mod added a function for it, leaving its one result on the stack. Whether it ran, false
// without a function or on an error, which is logged.
// The callers, result readers and error throws the original instantiates per callback are this and its readers
// (00872980, 00872c60, 00873470, 00873980, 00873d00, 00873fc0, 00874120, 00874210, 00874310, 00874a10, 00874f60)
// (0085c080, 008727d0, 0086130e, 00861225, 00861d96, 00861e7f, 008623a6, 0086248f, 008628b6, 0086299f, 00864453)
// (0086453c, 00865bbc, 00872a20, 00872b10, 00872ff0, 008730e0, 00873890, 00873ac0, 00873bb0, 00873e40, 008746b0)
// (00874860, 00874910, 00874ac0, 00874d20, 00874dd0, 00874e90, 00865a04, 0085bfd0, 0085bff0, 0085c270, 00873f40)
// (00872da0, 00872e90, 00873230, 00873320, 00873560, 00873650, 00873740, 00874400, 00874550, 00875050, 008663b6)
// (00872820, 00872860, 00872910, 00861c23, 00862233, 00862d53, 00865aad, 00865c61, 00866474, 00872a0c, 00872af1)
// (00872c43, 00872d80, 00872e71, 00872fc3, 008730c1, 00873213, 00873301, 00873453, 00873541, 00873631, 00873721)
// (00873873, 00873961, 00873aa0, 00873b91, 00873ce3, 00873e20, 00873f26, 00874103, 008741f1, 008742f7, 008743eb)
// (00874533, 0087469a, 00874846, 008748f6, 008749f7, 00874aa8, 00874bbb, 00874d0a, 00874db6, 00874e7e, 00874f4a)
// (00861bda, 008621ea, 00862d0a, 0085c250, 0085c2d0, 0085c300, 0085c340, 0085bf50, 0085c1d0, 0085c200, 0085c210)
// (0085da70)
// and their catches log through lua_error_log
// (00860ea3, 008611da, 0086191f, 00861d4b, 0086235b, 0086286b, 00862ea4, 008632e1)
// (00863706, 00863b6a, 00863e31, 00863f1e, 008640de, 00864408, 00864f6e, 00865b69, 008661cc, 00860826, 0086090e)
// (00860a70, 00860b4b, 00860c36, 00860d1e, 008613bf, 0086149f, 00861587, 00862a4c, 00862b2f, 00862cb8, 00862f8c)
// (0086306c, 00863154, 0086354b, 00863fff, 00864a6a, 00864bb8, 00864d16, 00865209, 008652e9, 00865424, 008659a7)
// (00865d53, 00865e99, 00865fe8, 008660ec)
// (00860f8b, 00861076, 0086166f, 0086174f, 00861837, 008619ff, 00861b88, 00861f2f, 0086200f, 00862198, 0086253f)
// (0086261f, 00862707, 0086362b, 00863879, 00863c6e, 00863d4e, 008641bb, 008642a4, 00864682, 00864e6d, 0086504e)
// (0086512e, 008655b7, 00866364, 0086675e, 008668e0).
template <typename... Args>
bool callback_run(LuaEngine& engine, CallbackRun run, Args... args)
{
if (!engine.is_callback_enabled(run.id)) return false;
lua_State* state = engine.state;
bool isTwoParams = run.secondParam.has_value();
lua_rawgeti(state, LUA_REGISTRYINDEX, isTwoParams ? engine.runCallbackTwoParamsRef : engine.runCallbackRef);
lua_pushinteger(state, run.id);
param_push(state, run.param);
if (isTwoParams) param_push(state, run.secondParam);
(lua_push(state, args), ...);
if (lua_pcall(state, sizeof...(Args) + 2 + isTwoParams, 1, 0) == LUA_OK) return true;
lua_error_log(state, run.name);
return false;
}
// Runs a callback whose result the game ignores.
template <typename... Args>
void callback_notify(LuaEngine& engine, CallbackRun run, Args... args)
{
if (callback_run(engine, run, args...)) lua_pop(engine.state, 1);
}
// Runs a callback whose result is an integer that replaces fallback.
// The original aborts on a result that is neither nil nor an integer. This keeps fallback instead.
template <typename... Args>
int callback_integer_run(LuaEngine& engine, CallbackRun run, int fallback, Args... args)
{
if (!callback_run(engine, run, args...)) return fallback;
int isInteger = 0;
lua_Integer result = lua_tointegerx(engine.state, -1, &isInteger);
lua_pop(engine.state, 1);
return isInteger ? (int)result : fallback;
}
// Runs a callback whose result, when not nil, is a boolean that replaces fallback.
template <typename... Args>
bool callback_boolean_run(LuaEngine& engine, CallbackRun run, bool fallback, Args... args)
{
if (!callback_run(engine, run, args...)) return fallback;
bool result = lua_isnil(engine.state, -1) ? fallback : lua_toboolean(engine.state, -1);
lua_pop(engine.state, 1);
return result;
}
// Runs a Pre*Collision callback for an entity and what it hits, and reads its result as true, false or nothing.
template <typename T>
LuaResult collision_run(LuaEngine& engine, CallbackRun run, T* entity, Entity* collider, bool isLow)
{
if (!callback_run(engine, run, entity, collider, isLow)) return LUA_RESULT_NIL;
LuaResult result = lua_isnil(engine.state, -1) ? LUA_RESULT_NIL
: lua_toboolean(engine.state, -1) ? LUA_RESULT_TRUE
: LUA_RESULT_FALSE;
lua_pop(engine.state, 1);
return result;
}
// Sets value to a field of the table on top of the stack, when the field is not nil.
inline void field_read(lua_State* state, const char* key, bool& value)
{
lua_getfield(state, -1, key);
if (!lua_isnil(state, -1)) value = lua_toboolean(state, -1);
lua_pop(state, 1);
}
// Sets value to an element of the table on top of the stack, when the element is not nil. Whether it was not.
// The original aborts on an element that is not an integer. This keeps the value instead.
template <typename T>
bool element_read(lua_State* state, int key, T& value)
{
int isInteger = 0;
bool isSet = lua_geti(state, -1, key) != LUA_TNIL;
lua_Integer element = lua_tointegerx(state, -1, &isInteger);
if (isInteger) value = (T)element;
lua_pop(state, 1);
return isSet;
}
// Pops a callback's result, and when it is a table sets values in order to its elements 1, 2 ... Whether any was set.
template <typename... T>
bool elements_pop(lua_State* state, T&... values)
{
int key = 1;
bool isChanged = false;
if (lua_istable(state, -1)) ((isChanged |= element_read(state, key++, values)), ...);
lua_pop(state, 1);
return isChanged;
}
+1 -125
View File
@@ -1,4 +1,4 @@
#include "lua/engine.h"
#include "lua/callback_run.h"
#include "classes.h"
#include "entity/weapon/bomb.h"
#include "entity/effect/effect.h"
@@ -11,134 +11,10 @@
#include "entity/weapon/projectile.h"
#include "entity/weapon/tear.h"
#include "game/game.h"
#include "lua/api.h"
#include "level/room_config.h"
constexpr int PILL_EFFECT_UNCHANGED = -1;
// One run of a callback: the name its errors log, its id, and the parameter mods filter it by.
struct CallbackRun
{
const char* name;
LuaCallback id;
int param = CALLBACK_PARAM_NONE;
};
// Calls _RunCallback with a callback's id, its filter parameter and its arguments when a mod added a function for it,
// leaving its one result on the stack. Whether it ran, false without a function or on an error, which is logged.
// The callers, result readers and error throws the original instantiates per callback are this and its readers
// (00872980, 00872c60, 00873470, 00873980, 00873d00, 00873fc0, 00874120, 00874210, 00874310, 00874a10, 00874f60)
// (0085c080, 008727d0, 0086130e, 00861225, 00861d96, 00861e7f, 008623a6, 0086248f, 008628b6, 0086299f, 00864453)
// (0086453c, 00865bbc, 00872a20, 00872b10, 00872ff0, 008730e0, 00873890, 00873ac0, 00873bb0, 00873e40, 008746b0)
// (00874860, 00874910, 00874ac0, 00874d20, 00874dd0, 00874e90, 00865a04, 0085bfd0, 0085bff0, 0085c270, 00873f40)
// (00872da0, 00872e90, 00873230, 00873320, 00873560, 00873650, 00873740, 00874400, 00874550, 00875050, 008663b6)
// (00872820, 00872860, 00872910, 00861c23, 00862233, 00862d53, 00865aad, 00865c61, 00866474, 00872a0c, 00872af1)
// (00872c43, 00872d80, 00872e71, 00872fc3, 008730c1, 00873213, 00873301, 00873453, 00873541, 00873631, 00873721)
// (00873873, 00873961, 00873aa0, 00873b91, 00873ce3, 00873e20, 00873f26, 00874103, 008741f1, 008742f7, 008743eb)
// (00874533, 0087469a, 00874846, 008748f6, 008749f7, 00874aa8, 00874bbb, 00874d0a, 00874db6, 00874e7e, 00874f4a)
// (00861bda, 008621ea, 00862d0a, 0085c250, 0085c2d0, 0085c300, 0085c340, 0085bf50, 0085c1d0, 0085c200, 0085c210)
// (0085da70)
// and their catches log through lua_error_log
// (00860ea3, 008611da, 0086191f, 00861d4b, 0086235b, 0086286b, 00862ea4, 008632e1)
// (00863706, 00863b6a, 00863e31, 00863f1e, 008640de, 00864408, 00864f6e, 00865b69, 008661cc, 00860826, 0086090e)
// (00860a70, 00860b4b, 00860c36, 00860d1e, 008613bf, 0086149f, 00861587, 00862a4c, 00862b2f, 00862cb8, 00862f8c)
// (0086306c, 00863154, 0086354b, 00863fff, 00864a6a, 00864bb8, 00864d16, 00865209, 008652e9, 00865424, 008659a7)
// (00865d53, 00865e99, 00865fe8, 008660ec)
// (00860f8b, 00861076, 0086166f, 0086174f, 00861837, 008619ff, 00861b88, 00861f2f, 0086200f, 00862198, 0086253f)
// (0086261f, 00862707, 0086362b, 00863879, 00863c6e, 00863d4e, 008641bb, 008642a4, 00864682, 00864e6d, 0086504e)
// (0086512e, 008655b7, 00866364, 0086675e, 008668e0).
template <typename... Args>
static bool callback_run(LuaEngine& engine, CallbackRun run, Args... args)
{
if (!engine.enabledCallbacks[run.id]) return false;
lua_State* state = engine.state;
lua_rawgeti(state, LUA_REGISTRYINDEX, engine.runCallbackRef);
lua_push(state, (int)run.id);
lua_push(state, run.param);
(lua_push(state, args), ...);
if (lua_pcall(state, sizeof...(Args) + 2, 1, 0) == LUA_OK) return true;
lua_error_log(state, run.name);
return false;
}
// Runs a callback whose result the game ignores.
template <typename... Args>
static void callback_notify(LuaEngine& engine, CallbackRun run, Args... args)
{
if (callback_run(engine, run, args...)) lua_pop(engine.state, 1);
}
// Runs a callback whose result is an integer that replaces fallback.
// The original aborts on a result that is neither nil nor an integer. This keeps fallback instead.
template <typename... Args>
static int callback_integer_run(LuaEngine& engine, CallbackRun run, int fallback, Args... args)
{
if (!callback_run(engine, run, args...)) return fallback;
int isInteger = 0;
lua_Integer result = lua_tointegerx(engine.state, -1, &isInteger);
lua_pop(engine.state, 1);
return isInteger ? (int)result : fallback;
}
// Runs a callback whose result, when not nil, is a boolean that replaces fallback.
template <typename... Args>
static bool callback_boolean_run(LuaEngine& engine, CallbackRun run, bool fallback, Args... args)
{
if (!callback_run(engine, run, args...)) return fallback;
bool result = lua_isnil(engine.state, -1) ? fallback : lua_toboolean(engine.state, -1);
lua_pop(engine.state, 1);
return result;
}
// Runs a Pre*Collision callback for an entity and what it hits, and reads its result as true, false or nothing.
template <typename T>
static LuaResult collision_run(LuaEngine& engine, CallbackRun run, T* entity, Entity* collider, bool isLow)
{
if (!callback_run(engine, run, entity, collider, isLow)) return LUA_RESULT_NIL;
LuaResult result = lua_isnil(engine.state, -1) ? LUA_RESULT_NIL
: lua_toboolean(engine.state, -1) ? LUA_RESULT_TRUE
: LUA_RESULT_FALSE;
lua_pop(engine.state, 1);
return result;
}
// Sets value to a field of the table on top of the stack, when the field is not nil.
static void field_read(lua_State* state, const char* key, bool& value)
{
lua_getfield(state, -1, key);
if (!lua_isnil(state, -1)) value = lua_toboolean(state, -1);
lua_pop(state, 1);
}
// Sets value to an element of the table on top of the stack, when the element is not nil. Whether it was not.
// The original aborts on an element that is not an integer. This keeps the value instead.
template <typename T>
static bool element_read(lua_State* state, int key, T& value)
{
int isInteger = 0;
bool isSet = lua_geti(state, -1, key) != LUA_TNIL;
lua_Integer element = lua_tointegerx(state, -1, &isInteger);
if (isInteger) value = (T)element;
lua_pop(state, 1);
return isSet;
}
// Pops a callback's result, and when it is a table sets values in order to its elements 1, 2 ... Whether any was set.
template <typename... T>
static bool elements_pop(lua_State* state, T&... values)
{
int key = 1;
bool isChanged = false;
if (lua_istable(state, -1)) ((isChanged |= element_read(state, key++, values)), ...);
lua_pop(state, 1);
return isChanged;
}
// 00862250 Runs MC_PRE_BOMB_COLLISION, filtered by the bomb's variant.
LuaResult LuaEngine::PreBombCollision(Entity_Bomb* bomb, Entity* collider, bool isLow)
{
+32 -4
View File
@@ -5,6 +5,9 @@
#include "game/game.h"
#include "game/manager.h"
#include "engine/platform.h"
#ifdef ISAAC_REPENTOGON
#include "repentogon/repentogon.h"
#endif
#include <algorithm>
#include <cstdio>
#include <cstdlib>
@@ -169,6 +172,9 @@ void LuaEngine::Init(LuaMode luaMode)
RegisterAPI();
RunScript(resource_path(ENUMS_SCRIPT));
RunScript(resource_path(MAIN_SCRIPT));
#ifdef ISAAC_REPENTOGON
repentogon_scripts_run(*this);
#endif
runCallbackRef = global_take(state, RUN_CALLBACK);
unloadModRef = global_take(state, UNLOAD_MOD);
}
@@ -193,10 +199,11 @@ void LuaEngine::destroy()
for (LuaMod& mod : mods) mod_unload(*this, mod);
mods.clear();
luaL_unref(state, LUA_REGISTRYINDEX, runCallbackRef);
luaL_unref(state, LUA_REGISTRYINDEX, unloadModRef);
runCallbackRef = LUA_REF_NONE;
unloadModRef = LUA_REF_NONE;
for (int* ref : {&runCallbackRef, &runCallbackTwoParamsRef, &unloadModRef})
{
luaL_unref(state, LUA_REGISTRYINDEX, *ref);
*ref = LUA_REF_NONE;
}
lua_close(state);
state = nullptr;
}
@@ -296,6 +303,27 @@ void LuaEngine::gc_update()
lua_gc(state, LUA_GCSTEP, gcStepSize);
}
// Whether a mod added a function for a callback, by its id: the original's, or with REPENTOGON one of its own.
bool LuaEngine::is_callback_enabled(int callback)
{
if ((uint32_t)callback < LUA_CALLBACK_COUNT) return enabledCallbacks[callback];
#ifdef ISAAC_REPENTOGON
uint32_t index = (uint32_t)(callback - REPENTOGON_CALLBACK_FIRST);
if (index < REPENTOGON_CALLBACK_COUNT) return enabledRepentogonCallbacks[index];
#endif
return false;
}
// Sets whether a callback runs, for the API's SetBuiltInCallbackState. Any other id is ignored.
void LuaEngine::callback_state_set(int callback, bool isEnabled)
{
if ((uint32_t)callback < LUA_CALLBACK_COUNT) enabledCallbacks[callback] = isEnabled;
#ifdef ISAAC_REPENTOGON
uint32_t index = (uint32_t)(callback - REPENTOGON_CALLBACK_FIRST);
if (index < REPENTOGON_CALLBACK_COUNT) enabledRepentogonCallbacks[index] = isEnabled;
#endif
}
// 0086f640 A collectible's id by its name, -1 for none. The original searches a copy of the name map.
int LuaEngine::Isaac_GetItemIdByName(std::string_view name)
{
+9 -1
View File
@@ -34,6 +34,9 @@ constexpr int LUA_MEMORY_HISTORY_SIZE = 128;
constexpr int LUA_REF_NONE = -2;
// A callback registered for every parameter.
constexpr int CALLBACK_PARAM_NONE = -1;
// REPENTOGON's callback ids, from 1000 up (enums_ex.lua's ModCallbacks), with room for as many as it tracks.
constexpr int REPENTOGON_CALLBACK_FIRST = 1000;
constexpr int REPENTOGON_CALLBACK_COUNT = 500;
// The input hooks of MC_INPUT_ACTION (Lua's InputHook).
enum InputHook : int
@@ -132,13 +135,15 @@ struct LuaMod
// The mod scripting host: the Lua 5.3 state, the game's scripts in resources/scripts/, the mods scripts register, and
// the entry points that run mods' callbacks. A callback runs only while enabledCallbacks has its id, which the API's
// SetBuiltInCallbackState sets once a mod adds a function for it. Lua errors are logged, never fatal.
// SetBuiltInCallbackState sets once a mod adds a function for it, REPENTOGON's ids from 1000 up in a set of their own.
// Lua errors are logged, never fatal.
// Construction is inlined in IsaacStartup, and the original never destroys the engine.
struct LuaEngine
{
std::array<int, LUA_MEMORY_HISTORY_SIZE> memoryHistory{};
std::array<int, LUA_GC_HISTORY_SIZE> gcGrowth{};
std::bitset<LUA_CALLBACK_COUNT> enabledCallbacks;
std::bitset<REPENTOGON_CALLBACK_COUNT> enabledRepentogonCallbacks;
std::list<LuaMod> mods;
std::string scriptPath;
lua_State* state = nullptr;
@@ -151,6 +156,7 @@ struct LuaEngine
int memoryHistoryIndex = 0;
int memoryHistoryTimer = 0;
int runCallbackRef = LUA_REF_NONE;
int runCallbackTwoParamsRef = LUA_REF_NONE;
int scriptApiVersion = -1;
int unloadModRef = LUA_REF_NONE;
uint32_t pointerMask = 0;
@@ -161,6 +167,8 @@ struct LuaEngine
bool RunScript(std::string_view path);
bool LuamodCMD(std::string_view modName);
void gc_update();
bool is_callback_enabled(int callback);
void callback_state_set(int callback, bool isEnabled);
static int Isaac_GetItemIdByName(std::string_view name);
LuaResult PreBombCollision(Entity_Bomb* bomb, Entity* collider, bool isLow);
+93
View File
@@ -0,0 +1,93 @@
#include "repentogon/options.h"
#include "engine/platform.h"
#include <SDL3/SDL_filesystem.h>
#include <SDL3/SDL_stdinc.h>
#include <algorithm>
#include <charconv>
#include <filesystem>
#include <fstream>
constexpr const char* OPTIONS_FILE = "Repentogon/options.ini";
constexpr std::string_view WHITESPACE = " \t\r";
constexpr int FONT_SIZES[] = {13, 16, 14, 8, 8};
constexpr int FONT_SIZE_DEFAULT = 8;
// The keys a new options.ini gets besides the options, which REPENTOGON writes but no longer reads.
constexpr const char* UNREAD_KEYS[][3] = {{"VanillaTweaks", "FastLasers", "0"},
{"internal", "DidModReset", "0"},
{"internal", "EnableUnifont", "1"},
{"internal", "UnifontRenderMode", "0"}};
RepentogonOptions repentogonOptions;
// The text without the whitespace around it.
static std::string_view text_trim(std::string_view text)
{
size_t start = text.find_first_not_of(WHITESPACE);
if (start == text.npos) return {};
return text.substr(start, text.find_last_not_of(WHITESPACE) + 1 - start);
}
// Sets value to a key's leading digits, kept when the key is missing or has none, as REPENTOGON's defstoi reads it.
template <typename T> static void value_read(RepentogonOptions& options, const char* section, const char* key, T& value)
{
auto keys = options.ini.find(section);
if (keys == options.ini.end() || !keys->second.contains(key)) return;
std::string& text = keys->second[key];
int number = 0;
if (std::from_chars(text.data(), text.data() + text.size(), number).ec == std::errc()) value = (T)number;
}
// Reads options.ini's sections, writing a new one with the defaults when there is none, then every option it holds.
// FontSize defaults by the old UnifontRenderMode, and the Mars double tap window is clamped.
void RepentogonOptions::load()
{
char* folder = SDL_GetPrefPath("", SAVE_FOLDER.data());
path = std::string(folder ? folder : "") + OPTIONS_FILE;
SDL_free(folder);
std::ifstream file(path);
std::string section;
for (std::string line; std::getline(file, line);)
{
std::string_view text = text_trim(line);
size_t equals = text.find('=');
if (text.starts_with('[') && text.ends_with(']')) section = text.substr(1, text.size() - 2);
else if (equals != text.npos && !text.starts_with(';'))
ini[section][std::string(text_trim(text.substr(0, equals)))] = text_trim(text.substr(equals + 1));
}
bool isNew = !file.is_open();
if (isNew)
for (auto [fileSection, key, value] : UNREAD_KEYS) ini[fileSection][key] = value;
int renderMode = -1;
value_read(*this, "internal", "UnifontRenderMode", renderMode);
fontSize = (uint32_t)renderMode < std::size(FONT_SIZES) ? FONT_SIZES[renderMode] : FONT_SIZE_DEFAULT;
repentogon_options_visit(*this, [&](const char* fileSection, const char* key, auto& value) {
value_read(*this, fileSection, key, value);
});
marsDoubleTapWindow = std::clamp(marsDoubleTapWindow, MARS_DOUBLE_TAP_WINDOW_MIN, MARS_DOUBLE_TAP_WINDOW_MAX);
if (isNew) save();
}
// Writes every option into its section of options.ini, with the keys it read but does not know.
void RepentogonOptions::save()
{
repentogon_options_visit(*this, [&](const char* section, const char* key, auto value) {
ini[section][key] = std::to_string((int)value);
});
std::error_code error;
std::filesystem::create_directories(std::filesystem::path(path).parent_path(), error);
std::ofstream file(path);
for (auto& [section, keys] : ini)
{
file << '[' << section << "]\n";
for (auto& [key, value] : keys) file << key << '=' << value << '\n';
file << '\n';
}
if (!file) log_printf(LOG_INFO, "[warn] could not write %s\n", path.c_str());
}
+84
View File
@@ -0,0 +1,84 @@
#pragma once
#include <map>
#include <string>
constexpr int MARS_DOUBLE_TAP_WINDOW_MIN = 2;
constexpr int MARS_DOUBLE_TAP_WINDOW_MAX = 20;
// REPENTOGON's own options (REPENTOGONOptions), kept by section in Repentogon/options.ini in the save folder, with its
// defaults, plus the rebuild's vanilla parity switch, which keeps the game's behaviour exactly the original's.
// Keys it does not know are kept as read. Only the parity switch changes anything yet: the callback dispatch.
struct RepentogonOptions
{
std::map<std::string, std::map<std::string, std::string>> ini;
std::string path;
int consoleAutofillLimit = 10;
int consoleKeyMode = 0;
int consoleKeyScancode = 41;
int consoleKeyVK = 192;
int fontRenderStyle = 0;
int fontSize = 8;
int imGuiScale = 0;
int lastSaveFile = 0;
int marsDoubleTapWindow = 10;
bool isBetterVoidGeneration = false;
bool isBlockUnknownDevices = false;
bool isDidInputConfigsImport = false;
bool isDisableExitPrompt = false;
bool isEcoMode = false;
bool isEnableDocking = true;
bool isEnableImGuiMultiView = false;
bool isFileMap = true;
bool isHushLaserSpeedFix = true;
bool isInterpolV2 = false;
bool isPreventModUpdates = false;
bool isQuickRoomClear = false;
bool isRenderDebugFindInRadius = false;
bool isSkipArchiveChecks = false;
bool isSkipIntro = false;
bool isStatHudPlanetarium = true;
bool isSyncModsEnabled = true;
bool isSyncVanillaOptions = true;
bool isVanillaParity = true;
void load();
void save();
};
// Calls visit with each option's section, key and value, in the order REPENTOGON saves them, the parity switch first.
template <typename Visit> void repentogon_options_visit(RepentogonOptions& options, Visit visit)
{
visit("Rebuild", "VanillaParity", options.isVanillaParity);
visit("OptionsSyncing", "SyncVanillaOptions", options.isSyncVanillaOptions);
visit("OptionsSyncing", "SyncModsEnabled", options.isSyncModsEnabled);
visit("VanillaTweaks", "BetterVoidGeneration", options.isBetterVoidGeneration);
visit("VanillaTweaks", "HushLaserSpeedFix", options.isHushLaserSpeedFix);
visit("VanillaTweaks", "QuickRoomClear", options.isQuickRoomClear);
visit("VanillaTweaks", "PreventModUpdates", options.isPreventModUpdates);
visit("VanillaTweaks", "StatHUDPlanetarium", options.isStatHudPlanetarium);
visit("VanillaTweaks", "SkipIntro", options.isSkipIntro);
visit("VanillaTweaks", "InterpolV2", options.isInterpolV2);
visit("VanillaTweaks", "MarsDoubleTapWindow", options.marsDoubleTapWindow);
visit("VanillaTweaks", "ConsoleAutofillLimit", options.consoleAutofillLimit);
visit("VanillaTweaks", "ConsoleKeyMode", options.consoleKeyMode);
visit("VanillaTweaks", "ConsoleKeyVK", options.consoleKeyVK);
visit("VanillaTweaks", "ConsoleKeyScancode", options.consoleKeyScancode);
visit("VanillaTweaks", "EcoMode", options.isEcoMode);
visit("VanillaTweaks", "DisableExitPrompt", options.isDisableExitPrompt);
visit("VanillaTweaks", "BlockUnknownDevices", options.isBlockUnknownDevices);
visit("internal", "LastSaveFile", options.lastSaveFile);
visit("internal", "FileMap", options.isFileMap);
visit("internal", "ImGuiScale", options.imGuiScale);
visit("internal", "RenderDebugFindInRadius", options.isRenderDebugFindInRadius);
visit("internal", "SkipArchiveChecks", options.isSkipArchiveChecks);
visit("internal", "DidInputConfigsImport", options.isDidInputConfigsImport);
visit("internal", "FontSize", options.fontSize);
visit("internal", "FontRenderStyle", options.fontRenderStyle);
visit("internal", "EnableImGuiMultiView", options.isEnableImGuiMultiView);
visit("internal", "EnableDocking", options.isEnableDocking);
}
extern RepentogonOptions repentogonOptions;
+88
View File
@@ -0,0 +1,88 @@
#include "repentogon/repentogon.h"
#include "engine/data.h"
#include "engine/platform.h"
#include "lua/api.h"
#include "repentogon/options.h"
constexpr const char* SCRIPTS_FOLDER = "repentogon/scripts/";
constexpr const char* ENUMS_SCRIPT = "enums_ex.lua";
constexpr const char* MAIN_SCRIPT = "main_ex.lua";
constexpr const char* BINDINGS = "_CBindings";
constexpr const char* GLOBAL = "REPENTOGON";
constexpr const char* RUN_CALLBACK_TWO_PARAMS = "_RunCallbackWithTwoParams";
// Logs that a mod's callback failed, where REPENTOGON raises its error display.
static int mod_error_raise(lua_State* state)
{
log_printf(LOG_INFO, "%s is causing errors!\n", luaL_checkstring(state, 1));
return 0;
}
// The main.lua path of the mod a table was registered for, nil for none.
static int mod_id_get(lua_State* state)
{
luaL_checktype(state, 1, LUA_TTABLE);
for (LuaMod& mod : lua_engine_get().mods)
{
lua_rawgeti(state, LUA_REGISTRYINDEX, mod.tableRef);
bool isMod = lua_rawequal(state, 1, -1);
lua_pop(state, 1);
if (!isMod) continue;
lua_pushstring(state, mod.scriptPath.c_str());
return 1;
}
lua_pushnil(state);
return 1;
}
// Whether the vanilla parity option is on, read at each callback run.
static int vanilla_parity_get(lua_State* state)
{
lua_pushboolean(state, repentogonOptions.isVanillaParity);
return 1;
}
// Where one of REPENTOGON's scripts lives: under assets/repentogon/scripts/.
std::string repentogon_script_path(std::string_view path)
{
return asset_path(SCRIPTS_FOLDER + std::string(path));
}
// Runs REPENTOGON's enums_ex.lua and main_ex.lua after the game's own scripts, as its LuaEngine::Init hook does.
// debug opens again for them (main.lua closed it), os too unless vanilla parity is on, and _CBindings holds the
// internals main_ex.lua takes, cleared after. main_ex.lua replaces _RunCallback and _UnloadMod, which Init then takes,
// and adds _RunCallbackWithTwoParams. The REPENTOGON global is cleared while it is not exposed.
void repentogon_scripts_run(LuaEngine& engine)
{
lua_State* state = engine.state;
for (luaL_Reg library : {luaL_Reg{LUA_DBLIBNAME, luaopen_debug}, {LUA_OSLIBNAME, luaopen_os}})
{
if (library.func == luaopen_os && repentogonOptions.isVanillaParity) continue;
luaL_requiref(state, library.name, library.func, 1);
lua_pop(state, 1);
}
lua_newtable(state);
for (auto [name, function] : {std::pair{"RaiseModError", mod_error_raise}, {"GetModId", mod_id_get},
{"IsVanillaParity", vanilla_parity_get}})
{
lua_pushcfunction(state, function);
lua_table_set(state, -2, name);
}
lua_pushboolean(state, IS_REPENTOGON_EXPOSED);
lua_table_set(state, -2, "IsExposed");
lua_setglobal(state, BINDINGS);
engine.RunScript(repentogon_script_path(ENUMS_SCRIPT));
engine.RunScript(repentogon_script_path(MAIN_SCRIPT));
lua_pushnil(state);
lua_setglobal(state, BINDINGS);
lua_getglobal(state, RUN_CALLBACK_TWO_PARAMS);
engine.runCallbackTwoParamsRef = luaL_ref(state, LUA_REGISTRYINDEX);
if (IS_REPENTOGON_EXPOSED) return;
lua_pushnil(state);
lua_setglobal(state, GLOBAL);
}
+12
View File
@@ -0,0 +1,12 @@
#pragma once
#include <string>
#include <string_view>
struct LuaEngine;
// Whether mods see the REPENTOGON global and its version. It stays off until the whole API is ported, which flips it.
constexpr bool IS_REPENTOGON_EXPOSED = false;
std::string repentogon_script_path(std::string_view path);
void repentogon_scripts_run(LuaEngine& engine);
+63 -7
View File
@@ -5,6 +5,9 @@
#include "game/options_config.h"
#include "game/sfx_manager.h"
#include "game/string_table.h"
#ifdef ISAAC_REPENTOGON
#include "repentogon/options.h"
#endif
#include "ui/hud.h"
#include "ui/menu/key_config.h"
#include <imgui.h>
@@ -24,11 +27,18 @@ enum OptionsTab
OPTIONS_TAB_CONSOLE,
OPTIONS_TAB_ONLINE,
OPTIONS_TAB_SYSTEM,
#ifdef ISAAC_REPENTOGON
OPTIONS_TAB_REPENTOGON,
#endif
OPTIONS_TAB_COUNT
};
constexpr const char* OPTIONS_TAB_NAMES[OPTIONS_TAB_COUNT] = {"Audio", "Video", "HUD", "Gameplay",
"Console", "Online", "System"};
"Console", "Online", "System",
#ifdef ISAAC_REPENTOGON
"REPENTOGON"
#endif
};
// Where an options.ini setting sits: its tab and label, the range of a number (a slider when it has one, else typed),
// and for a choice its labels, each standing for min plus its index.
@@ -93,7 +103,39 @@ constexpr OptionSpec OPTION_SPECS[] = {
{"SteamCloud", "Steam Cloud", OPTIONS_TAB_SYSTEM},
{"TryImportSave", "Import save", OPTIONS_TAB_SYSTEM},
{"AcceptedPublicBeta_v1.9.7.17", "Public beta accepted", OPTIONS_TAB_SYSTEM},
{"AcceptedDataCollectionDisclaimer", "Data collection accepted", OPTIONS_TAB_SYSTEM}};
{"AcceptedDataCollectionDisclaimer", "Data collection accepted", OPTIONS_TAB_SYSTEM},
#ifdef ISAAC_REPENTOGON
{"VanillaParity", "Vanilla parity", OPTIONS_TAB_REPENTOGON},
{"SyncVanillaOptions", "Sync vanilla options", OPTIONS_TAB_REPENTOGON},
{"SyncModsEnabled", "Sync enabled mods", OPTIONS_TAB_REPENTOGON},
{"BetterVoidGeneration", "Better Void generation", OPTIONS_TAB_REPENTOGON},
{"HushLaserSpeedFix", "Hush laser speed fix", OPTIONS_TAB_REPENTOGON},
{"QuickRoomClear", "Quick room clear", OPTIONS_TAB_REPENTOGON},
{"PreventModUpdates", "Prevent mod updates", OPTIONS_TAB_REPENTOGON},
{"StatHUDPlanetarium", "Planetarium chance on stat HUD", OPTIONS_TAB_REPENTOGON},
{"SkipIntro", "Skip intro", OPTIONS_TAB_REPENTOGON},
{"InterpolV2", "Interpolation v2", OPTIONS_TAB_REPENTOGON},
{"MarsDoubleTapWindow", "Mars double tap window", OPTIONS_TAB_REPENTOGON, MARS_DOUBLE_TAP_WINDOW_MIN,
MARS_DOUBLE_TAP_WINDOW_MAX},
{"ConsoleAutofillLimit", "Console autofill limit", OPTIONS_TAB_REPENTOGON},
{"ConsoleKeyMode", "Console key mode", OPTIONS_TAB_REPENTOGON, 0, 1, "Virtual key\0Scancode\0"},
{"ConsoleKeyVK", "Console virtual key", OPTIONS_TAB_REPENTOGON},
{"ConsoleKeyScancode", "Console scancode", OPTIONS_TAB_REPENTOGON},
{"EcoMode", "Eco mode", OPTIONS_TAB_REPENTOGON},
{"DisableExitPrompt", "Disable exit prompt", OPTIONS_TAB_REPENTOGON},
{"BlockUnknownDevices", "Block unknown devices", OPTIONS_TAB_REPENTOGON},
{"LastSaveFile", "Last save file", OPTIONS_TAB_REPENTOGON},
{"FileMap", "File map", OPTIONS_TAB_REPENTOGON},
{"ImGuiScale", "ImGui scale", OPTIONS_TAB_REPENTOGON},
{"RenderDebugFindInRadius", "Draw FindInRadius", OPTIONS_TAB_REPENTOGON},
{"SkipArchiveChecks", "Skip archive checks", OPTIONS_TAB_REPENTOGON},
{"DidInputConfigsImport", "Input configs imported", OPTIONS_TAB_REPENTOGON},
{"FontSize", "Font size", OPTIONS_TAB_REPENTOGON},
{"FontRenderStyle", "Font render style", OPTIONS_TAB_REPENTOGON},
{"EnableImGuiMultiView", "ImGui multi-viewport", OPTIONS_TAB_REPENTOGON},
{"EnableDocking", "ImGui docking", OPTIONS_TAB_REPENTOGON},
#endif
};
static const OptionSpec* spec_find(std::string_view key)
{
@@ -146,8 +188,8 @@ template <typename T> static bool is_option_edited(const OptionSpec& spec, T& va
}
}
// Every setting options.ini holds, a tab each by subject, then the key bindings. A change applies at once and is saved
// to options.ini as the game saves it, once no widget is held.
// Every setting options.ini holds, a tab each by subject, REPENTOGON's own options in theirs, then the key bindings.
// A change applies at once and is saved as the game saves it, once no widget is held.
void Overlay::options_render()
{
OptionsConfig& config = g_manager->optionsConfig;
@@ -173,7 +215,7 @@ void Overlay::options_render()
ImGui::TextDisabled("Language: %s (read only)", language.c_str());
}
options_visit(config, [&](const char* key, auto& value) {
auto optionRender = [&](const char* file, const char* key, auto& value) {
const OptionSpec* spec = spec_find(key);
if (!spec || spec->tab != tab) return;
@@ -183,11 +225,22 @@ void Overlay::options_render()
option_apply(key);
isOptionsSavePending = true;
}
ImGui::SetItemTooltip("options.ini: %s", key);
ImGui::SetItemTooltip("%s: %s", file, key);
ImGui::PopID();
});
};
options_visit(config, [&](const char* key, auto& value) { optionRender("options.ini", key, value); });
if (tab == OPTIONS_TAB_CONSOLE)
ImGui::TextDisabled("**The overlay's console works whatever these say. They drive the original's.");
#ifdef ISAAC_REPENTOGON
if (tab == OPTIONS_TAB_REPENTOGON)
{
ImGui::TextDisabled("**Only vanilla parity does anything yet. On, the original's callbacks run as the "
"original runs them.");
repentogon_options_visit(repentogonOptions, [&](const char* section, const char* key, auto& value) {
optionRender(section, key, value);
});
}
#endif
ImGui::PopItemWidth();
ImGui::EndTabItem();
}
@@ -200,6 +253,9 @@ void Overlay::options_render()
if (!isOptionsSavePending || ImGui::IsAnyItemActive()) return;
config.Save();
#ifdef ISAAC_REPENTOGON
repentogonOptions.save();
#endif
isOptionsSavePending = false;
}