From 2f94d51dd516f96395ff0cbe7180a7502c07f1ea Mon Sep 17 00:00:00 2001 From: Torben H Date: Sat, 1 Jul 2023 02:47:21 +0200 Subject: [PATCH] Updating master (#125) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * #42 Added version file extraction pattern. * #42 Fixing not necessary $ in labelNames. * #42 Trying to commit and push changed version to the specific pull request. * #42 labelNames wasn't set. git push didn't work, because no branch was checked out? "fatal: You are not currently on a branch. To push the history leading to the current (detached HEAD). state now, use 'git push origin HEAD:'" * #42 Trying to get the branch name within github action. * #42 Found the head_ref branch name. Is '$' necessary? * #42 '$' is necessary! * #42 Adding commits count to version! * #42 "[detached HEAD 1345a7c] Updated version of this PR to 2.4.0-alpha. 1 file changed, 1 insertion(+), 1 deletion(-) To https://github.com/Ismoh/NoitaMP ! [rejected] HEAD -> 42-developer-want-to-add-github-workflow-action-to-automatically-increase-the-version-of-noitamp (fetch first) error: failed to push some refs to 'https://github.com/Ismoh/NoitaMP' hint: Updates were rejected because the remote contains work that you do hint: not have locally. This is usually caused by another repository pushing hint: to the same ref. You may want to first integrate the remote changes hint: (e.g., 'git pull ...') before pushing again. hint: See the 'Note about fast-forwards' in 'git push --help' for details." * #42 "You are not currently on a branch. Please specify which branch you want to merge with. See git-pull(1) for details. git pull " * #42 "You have divergent branches and need to specify how to reconcile them." Use ref for using the merge and not the initial branch * #42 Does "actions/checkout@v3" help? * #42 Error: .github#L1: a step cannot have both the `uses` and `run` keys * #42 You are not currently on a branch. Please specify which branch you want to merge with. See git-pull(1) for details. git pull * #42 You are not currently on a branch. Please specify which branch you want to merge with. See git-pull(1) for details. git pull 2 * Updated version of this PR to 2.4.0-alpha * #42 It's working fine, besides overwriting .version file. Should work now. * Updated version of this PR to 2.4.0-alpha * #42 I want githubs icon on the commit * Updated version of this PR to 2.5.0-alpha * #42 Fixed version * #42 Doesnt work when merged * #42 Use base ref instead. * #42 Adding comment to the pull request. * #42 Fixing syntax. * #42 Fixing syntax 2 * #42 Fixing syntax 3 * #42 Fixing syntax 4 * #42 Fixing syntax 5 * #42 Fixing syntax 6 * #42 Fixing syntax 7 * #42 Fixing syntax 8 * #42 Fixing syntax 9 * #42 Fixing syntax 10 * #42 Fixing syntax 11 * #42 Fixing syntax 12 * #42 Fixing syntax 13 * #42 Escaping everything! * #42 Escaping everything! doesnt help * #42 Escaping everything! doesnt help 2 * #42 Escaping everything! doesnt help 3 * #42 Escaping everything! doesnt help 4 * #42 Found the issue. * #42 Found the issue. 2 * #42 Found the issue. 3 * #42 Found the issue. 4 * #42 Found the issue. 5 * #42 polishing * #42 polishing 2 * #42 polishing 3 * #42 Colon is fycking up the json body. * #42 Colon is fycking up the json body. 2 * #42 Colon is fycking up the json body. 3 * #42 Colon is fycking up the json body. 4 * #42 Triple escape characters. * #42 Head ref doesnt exist, after merge. * #42 merged flag is false? * #42 merged flag is false? * #42 merged flag is false? 2 * #42 merged flag is false? 2 * Updated version of https://github.com/Ismoh/NoitaMP/pull/65 to v2.4.0-alpha+1040 * #42 Polishing! * #42 Made a mistake. Fixing version manually. * Updated version to v2.4.0-alpha+1045 in https://github.com/Ismoh/NoitaMP/pull/66 * Bump HardNorth/github-version-generate from 1.1.2 to 1.2.0 Bumps [HardNorth/github-version-generate](https://github.com/HardNorth/github-version-generate) from 1.1.2 to 1.2.0. - [Release notes](https://github.com/HardNorth/github-version-generate/releases) - [Changelog](https://github.com/HardNorth/github-version-generate/blob/develop/CHANGELOG.md) - [Commits](https://github.com/HardNorth/github-version-generate/compare/v1.1.2...v1.2.0) --- updated-dependencies: - dependency-name: HardNorth/github-version-generate dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * #72 Added changelog generator in a separated yaml file and in version.yml. * #72 Removed changelog generator in version.yml. * #72 Fixed non-existing tag key in changelog-generator.yml * #72 Added changelog generator to version.yml * #72 Fixed not working changelog generator workflow action. * #72 Trying to get the directories working?! * #72 Still trying to find out, where CHANGELOG.md is created. * #72 Typo in yaml. * #72 Changed branch from github.base_ref to github.head_ref, because CHANGELOG.md has to be changed in the PR-branch itself. * Updated CHANGELOG.md in https://github.com/Ismoh/NoitaMP/pull/73 * #72 Fixed order of workflow steps, to create first a tag, then updating CHANGELOG.md into the merged branch (github.base_ref) * #72 Changed wording and added version file name. * #72 Removed CHANGELOG.md, because it was generated not correctly. * #72 Removed not working changelog-generator.yml. Renamed version.yml to version-and-changelog-update.yml. * #72 Changed wording and order of steps for a better reading * Updated version to v2.5.0-alpha+1065 in https://github.com/Ismoh/NoitaMP/pull/73 * Updated CHANGELOG.md in https://github.com/Ismoh/NoitaMP/pull/73 * Integrate gource.io because its fun (#75) * #69 Added gource, because it's fun! * #69 Fixed 'ERROR: No Git repository found' * Updated version to v2.6.0-alpha+1070 in https://github.com/Ismoh/NoitaMP/pull/75 * Updated CHANGELOG.md in https://github.com/Ismoh/NoitaMP/pull/75 * Version and changelog update on pull requests fails (#80) * #78 Simply echoing toJSON of github context to find the "development" section info/object on a pull request. * #78 There is no build-in GitHub API endpoint or a context variable, which contains linked issues. That's why yet another action is added to simply check if an issue is linked to the PR. * #78 Adding comment when there is no linked issue. * #78 Fixed workflow: Repo needs to be checked out! * Update version-and-changelog-update.yml * #78 Trying to polish stuff, by using gh cli and api endpoints. * #78 Moved gh cli command to the correct workflow step. * #78 Changed command and quoting. * #78 Added GitHub token to be allowed to execute gh cli commands. * #78 Added gh cli to get all comments regarding versioning and removing them to add a comment with the latest version. * #78 Fixed wrong jq command. * #78 Fixed missing quotes on jq command. Changed gource.io only running on develop. * #78 Fixed broken jq command. * #78 Fixed broken workflow * #78 Fixed GitHub API url and changed wording slightly. * #78 Fixed quoting again. * #78 Changed escaped body to non-escaped. * #78 Fixed new line. Added comment for changelog. * #78 Fixed removing old comments and typos. Added removing changelog comments and adding a new changelog comment. * #78 Missed GitHub token. * #78 Eeeh, new line in markdown with gh string: Fun fun fun ! * #78 Eeeh, new line in markdown with gh string: Fun fun fun ! [space][space][enter] ? * #78 Eeeh, new line in markdown with gh string: Fun fun fun ! \ ? * #78 Eeeh, new line in markdown with gh string: Fun fun fun !
? * #78 Playing around with escaping $CHANGELOG. * #78 Fixed non-created changelog. * #78 Fixed wrong output usage. * #78 Getting rid of 'Unreleased' for this specific pull request. Next version is used instead. * #78 Fixed typo on env usage. Fixed deletion of previous comments. * #78 Where is the env gone? * #78 Adding global environment variable to have access on it between jobs. * #78 Why is this environment variable not set? * #78 Why is this environment variable still not set? * #78 Why is this environment variable still not set? * #78 Why is this environment variable still not set? * #78 Global environments aren't working. Using GitHubs output now. * #78 Fixed outputs. * #78 Fixed naming. * #78 Added deletion of not linked issue. * #78 Where is the $ coming from? * #78 Fixed typo, where unnecessary $ was added. * #78 Fixed usage of env. Misled by typo. * #78 Getting headache from syntax differences. * #78 Does env adds the $? * #78 Last try to get this annoying $ removed! * #78 Fixed typo! Finally, found the unnecessary $! * #78 Clean up! * #78 Making it pretty! * #78 Polishing! * Updated version to v2.6.1-alpha+1073 in https://github.com/Ismoh/NoitaMP/pull/80 * Updated CHANGELOG.md in https://github.com/Ismoh/NoitaMP/pull/80 * develop Hotfix for version workflow! * develop Hotfix for version workflow! Permissions were missing. * develop Hotfix for version workflow! Permissions were missing. * develop Hotfix for version workflow! Permissions were missing. Using PAT instead of GITHUB_TOKEN * develop Hotfix for version workflow! Permissions were missing. Using PAT instead of GITHUB_TOKEN * develop Hotfix for version workflow! Permissions were missing. gh login with PAT * develop Hotfix for version workflow! Permissions were missing. gh login with PAT. Authorised app on GitHub! Hopefully it shouldn't be done each workflow run! * develop Hotfix for version workflow! Unable to set PAT on gh cli. * develop Hotfix for version workflow! Trying out authorization header on api requests. * develop Hotfix for version workflow! Typo! * develop Hotfix for version workflow! Yet another typo! * develop Hotfix for version workflow! Let's try to use 'token' instead of 'Bearer'. * develop Hotfix for version workflow! Let's try to use 'token' instead of 'Bearer'. Variable isn't resolved correctly. * develop Hotfix for version workflow! Switched back to curl, because gh cli sucks! * develop Hotfix for version workflow! Switched back to curl, because gh cli sucks! Removed Bearer. * develop Hotfix for version workflow! Switched back to curl, because gh cli sucks! Fixed auth. * develop Hotfix for version workflow! Still need to use PAT? * develop Hotfix for version workflow! Still need to use PAT? with Bearer? * develop Hotfix for version workflow! Authentication with username and token(PAT). * develop Hotfix for version workflow! Authentication with username and token(PAT). * develop Hotfix for version workflow! Extended curl command. * develop Escaped body of curl. * Get rid of -i * develop Add pull_request_target for forked pull requests * develop Fixed curl data. * develop Fixed body of curl * develop Added fromJSON * Added jq for parsing string * develop Fixed string parsing with jq * develop printf? * develop echo pipe jq into variable * develop String escaped manually * develop Fixed escaping string by simply doing it manually * develop Fixed quote typos * develop Fixed escaped quote typos * develop Added pull_request_target. Added nektos/act. Added powershell script for running GitHub actions locally. * develop Fixed wrong json formatting. Added nektos/act for being able to run actions locally, which isn't working atm. * develop Fixed wrong json formatting with 'jq -Rsa .'. * develop Yet another string concatenation try! * develop Yet another string concatenation try! 2 * develop Yet another string concatenation try! 3 * develop Quoting! * develop Finally using jq! * develop Finally using jq! Still didnt work. * develop Finally using jq! Still didn't work either. * develop This one looks promising. Tested locally on wsl. * develop Tidying up! * develop Tidying up! * develop Print GitHub context! * develop I think, that's it! Final workflow hotfix commit? * develop I think, that's it! Final workflow hotfix commit? * develop I think, that's it! Final workflow hotfix commit? * replace wiki links, fandom.com->wiki.gg per official migration (#79) Co-authored-by: Torben H * Updated version to v2.6.2-alpha+1130 in https://github.com/Ismoh/NoitaMP/pull/79 * Updated CHANGELOG.md in https://github.com/Ismoh/NoitaMP/pull/79 * develop Hotfix changelog workflow * Bump actions/upload-artifact from 2 to 3 (#77) Bumps [actions/upload-artifact](https://github.com/actions/upload-artifact) from 2 to 3. - [Release notes](https://github.com/actions/upload-artifact/releases) - [Commits](https://github.com/actions/upload-artifact/compare/v2...v3) --- updated-dependencies: - dependency-name: actions/upload-artifact dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Torben H * Updated version to v2.6.3-alpha+1134 in https://github.com/Ismoh/NoitaMP/pull/77 * Updated CHANGELOG.md in https://github.com/Ismoh/NoitaMP/pull/77 * develop Hotfix changelog workflow. * Bump actions/checkout from 2 to 3.1.0 (#82) Bumps [actions/checkout](https://github.com/actions/checkout) from 2 to 3.1.0. - [Release notes](https://github.com/actions/checkout/releases) - [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md) - [Commits](https://github.com/actions/checkout/compare/v2...v3.1.0) --- updated-dependencies: - dependency-name: actions/checkout dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Torben H * Updated version to v2.6.4-alpha+1138 in https://github.com/Ismoh/NoitaMP/pull/82 * Updated CHANGELOG.md in https://github.com/Ismoh/NoitaMP/pull/82 * develop Hotfix clean up. * Bump HardNorth/github-version-generate from 1.2.0 to 1.3.0 (#83) * Bump HardNorth/github-version-generate from 1.2.0 to 1.3.0 Bumps [HardNorth/github-version-generate](https://github.com/HardNorth/github-version-generate) from 1.2.0 to 1.3.0. - [Release notes](https://github.com/HardNorth/github-version-generate/releases) - [Changelog](https://github.com/HardNorth/github-version-generate/blob/develop/CHANGELOG.md) - [Commits](https://github.com/HardNorth/github-version-generate/compare/v1.2.0...v1.3.0) --- updated-dependencies: - dependency-name: HardNorth/github-version-generate dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * Removed trigger pull_request_target is enough. Removed pull_request trigger. Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Torben H * Updated version to v2.6.5-alpha+1143 in https://github.com/Ismoh/NoitaMP/pull/83 * Updated CHANGELOG.md in https://github.com/Ismoh/NoitaMP/pull/83 * Update README.md Added additional info about current progress * Added roadmap sketchup with draw.io * Updated NoitaMP-Roadmap * Updated NoitaMP-Roadmap * Updated NoitaMP-Roadmap * NoitaMP-Roadmap updated * NoitaMP-Roadmap finished * NoitaMP-Roadmap.svg added * NoitaMP-Roadmap.drawio.svg updated * NoitaMP-Roadmap.drawio.svg updated * Added roadmap to README.md * NoitaMP-Roadmap finished * NoitaMP-Roadmap updated * NoitaMP-Roadmap.drawio.svg finalised * Delete NoitaMP-Roadmap.svg * Rename NoitaMP-Roadmap.drawio.svg to NoitaMP-Roadmap.svg * Bump HarshCasper/validate-issues-over-pull-requests from 0.1.1 to 0.1.2 (#86) Bumps [HarshCasper/validate-issues-over-pull-requests](https://github.com/HarshCasper/validate-issues-over-pull-requests) from 0.1.1 to 0.1.2. - [Release notes](https://github.com/HarshCasper/validate-issues-over-pull-requests/releases) - [Commits](https://github.com/HarshCasper/validate-issues-over-pull-requests/compare/v0.1.1...v0.1.2) --- updated-dependencies: - dependency-name: HarshCasper/validate-issues-over-pull-requests dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Updated version to v2.6.6-alpha+1162 in https://github.com/Ismoh/NoitaMP/pull/86 * Updated CHANGELOG.md in https://github.com/Ismoh/NoitaMP/pull/86 * Fixed old label name for "help wanted" to "help_wanted" * Create snyk-container.yml * Delete snyk-container.yml * Update windows-latest-lua-unit-testing.yml * #48 Updated version string to json format * Update .version * Update README.md * Add renovate.json (#90) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> * Merge rework of client and server classes into develop (#110) * Quick and dirty rework of Client and Server Developer want to rework client and server modules/classes #48 * A lot Client and Server rework. Tried EZGUI. #48 * Dependabot?! * Renamed username to name. Extended logger with log channel. #48 * Reworked sock.lua and updated EZGUI to 0.1.2 * Trying to add lfs * Little bit UI. SaveSlot. Logger. #48 * Clean up #48 * world seed does not load #48 * Seed synced * Reworking client/server. #48 * Reworking client/server. 2 #48 * Updated EZGUI to v0.2.0 * ui changes #48 * new ui class added #48 * ui changes #48 * Fixing unit tests #48 * Fixing and extending unit tests #48 * Fixing unit tests #48 * Fixing unit tests #48 * Fixing unit tests #48 * Fixing unit tests #48 * Ui changes #48 * Ui changes #48 * Ui changes #48 * Ui changes #48 * RTT halved and UI update #48 * Commit before updating EZGUI * Trying to fix Ezgui #48 * ezgui fixed #48 * newNuid #48 * need nuid #48 * need nuid 2 #48 * need nuid 3 #48 * need nuid 4 #48 * need nuid 5 #48 * Adding luacheck * Fix missing owner The localOwner is stored in {name=, guid=} format When server sends local entities, clients recieve the localOwner * Only consider root entities for syncing Some entities have multiple sub entities, but come from one file This fixes the infinite minas bug * Better velocity handling Check if component exists to prevent generating empty tables Rework spawning to prevent false warning * #48 Small guid changes. * #48 Let me do my own acknowledgement! * #48 Let me do my own acknowledgement! 2 * #48 Added a lot of checks. * #48 Still duplicated entities. * #48 Guid and entityData * #48 entityData * #48 Trying to fix 'alreadySent' * #48 New teaser gif added. * #48 Added polymorphism and version. * #48 Hopefully fixed public ip issue. * Add silent os.execute and io.popen Prevents several cmd windows from opening * Block FFI extension on Linux * #48 Added profiler.lua for being able to find bottlenecks! * #48 Added new de-/serializer (MessagePack) and de-/compressor (ZStandard) for network messages. In addition to this polymorphism is now synced. * #48 Fixed removing AiComponents. Removed some profiler hacks. Added tick rate for better performance. Added debug ui for detecting in-/exclude entities. Changed detections of dead entities/nuid by multiplying entityId with -1 instead of -99. Improved default mod setting values. * #48 Adding custom testing map. * #48 Fixed non-working custom map/biome. * #48 Changed custom map. Reworking GUID, because locally same GUID can be generated. Added range to detect changes. Fixed clients modSettings for insert servers ip. * #69 Added CustomProfiler.lua to profile NoitaMP scripts only! Changed testing map to add more enemies. Disabled logging at all for testing performance issues. * #69 Added profiling of Noita API ModSetting* functions. Changed CustomProfiler threshold to 1ms. * #48 Fixed bug where zstd wasn't able to be loaded. * #48 Fixed libraries issue. Added ModSetting for dis-/enable logger at all. Started to rework detection of entities by using coroutines. Disabled Client and Server updateVariables. Added EntityUtils cache. Removed Ubuntu lua testing workflow. * #48 Fixed 'not enough memory'. Refactored profiler and plotly.lua to be able to profile at runtime. Disabled some profiling function, to avoid stack overflow! * Updated plotly.js version from 2.9.0 to 2.16.0 * Added bar chart settings * Added bar chart entry text * #48 Extended profiling to find the FPS drop issue. * #48 Added garbage collector functions. Added git submodules updater. Fixed math extensions. Added fileUtil function for getting Windows desktop directory path. * #48 Updated git submodules updater. * #38 Add synchronisation for client and server mods (#85) * Added roadmap sketchup with draw.io * Updated NoitaMP-Roadmap * Updated NoitaMP-Roadmap * Updated NoitaMP-Roadmap * NoitaMP-Roadmap updated * NoitaMP-Roadmap finished * NoitaMP-Roadmap.svg added * NoitaMP-Roadmap.drawio.svg updated * NoitaMP-Roadmap.drawio.svg updated * Added roadmap to README.md * NoitaMP-Roadmap finished * NoitaMP-Roadmap updated * NoitaMP-Roadmap.drawio.svg finalised * Delete NoitaMP-Roadmap.svg * Rename NoitaMP-Roadmap.drawio.svg to NoitaMP-Roadmap.svg * implement server onNeedModList function and add needModList/Content events * Finish implementing server side mod sync functions and add onNeedModContent * make modListCached a prop on Server class * make onNeedModContent also return workshop id to avoid overwriting workshop mods * Finish implementing mod synchronisation * make onNeedModList run on connection to server * move mod conflict gui into drawModConflictWarning function * disable auto formatting * fix Client.lua formatting and add CustomProfiler to onNeedModList/Content Co-authored-by: Torben H * Updated version to v2.6.6-alpha+1223 in https://github.com/Ismoh/NoitaMP/pull/85 * Updated CHANGELOG.md in https://github.com/Ismoh/NoitaMP/pull/85 * Fixed non working version workflow manually * #48 Changed CustomProfiler.lua settings. Added comments regarding possible memory leak! * #48 Reworking entity processing for networking. Removed one of x caches. Added a new small cache for transform. Changed small wordings. Changed code formatting. * #48 Added destroying entities on client. Added workaround to get __len on lua5.1. Added removing dead entities on transformCache. Added check to see if entityId is a remoteMinä. Added check if entity changed (health, rotation, velocity, x, y) depending on threshold set in ModSettings. Added simple and stupid UI text, if transformCache got huge! Fixed broken modSetting for change detection threshold. * #48 Fixed assigning metatable. Hopefully fixed annoying broken windows lua testing workflow. * #48 Added table metamethod function to set default metamethods to a table. Added table.metamethods test. Added EntityUtils transform cache. Removed Server and Client cache. Removed EntityUtils entity cache. * #48 Fixed broken windows lua testing workflow * #48 Fixed missing directory on Windows lua testing workflow, because it's Windoof/Winstupid instead Windows. * #48 Fixed missing directory on Windows lua testing workflow, because it's Windoof/Winstupid instead Windows. The second :) * #48 Fixed usage of logger when running on GitHub. * #48 Fixed order of checks when defining metamethods. * #48 Fixed table metamethods 'table_extensions.lua:179: stack overflow'. * #48 Fixed errors after rework. * #48 Added logging to unit test. * #48 Added metamethods to cache tables. (Doesn't seem to work!) Added memory usage to CustomProfiler.lua. Fixed Velocity bug when calculating any changes. * #48 Rework no.3. Server FPS drops are gone. Looks promising! Client still broken, will be fixed soon. Improved CustomProfiler.lua. * #48 Fixed missing stops of CustomProfiler, which was leading to memory overflow. Got rid of EntityGetRootEntity, which was also leading to problems and not synced entities, like Minäs wands. * #48 Added possibility to send readable tables via sock.lua. Removed not used files anymore! Reworked cache on Server and Client. Server does have a cache now for each client. Reworked 'alreadySent', but isn't working yet. Small cleaning code. Fixed missing nuid on Servers Minä. Changed version to json format. Fixed needModList- and needModContent schemas. Added function in NuidUtils.lua to clean cache on Server and Client; still not working. Added cache sizes to UI. Changed log level order. * #48 Added resendIdentifier to NetworkUtils events. Reworked acknowledgment cache for Server and Client. Reworked resend mechanism based on new acknowledgment cache. Reworked displaying cache size. Simplified table.size(). Fixed GlobalsUtils for getting and setting dead nuids. Fixed EntityUtils.destroyByNuid. Need to fix removing entries of acknowledgment cache, when an entity died. * #48 Tried to add lua unit testing locally. Didn't work! * #48 Added unit test templates. Fixed several nil bugs. * Update windows-latest-lua-unit-testing.yml * Update windows-latest-lua-unit-testing.yml * #48 Improved sock.lua being able to receive non index based tables. Fixed timing issues when sending playerInfo. Removed cache from Server, because Server send by its Client copies. Reordering nuid_debugger. Added functions for detecting if entity is a child. Changed playerInfo schema. Added resendIdentifier (optional - improves performance) for needNuid schema. Removed enabling disabled components and added tags instead. * rework type annotations for most files and minor bugfixing around type issues * rollback some changes and ensure critical functions do not silently fail * #48 Several bug fixes. Additionally, parent and child spawning. * #48 Moved child adding. Added clearing cache. * #48 Added luarocks, because I am sick of this dependency problems. In addition, I want to run unit tests easily. Messed around with broken paths in test lua files. Fixed sending acknowledgements. Added removing cache entries when entity died. Removed metamethod.mode! Tried to fix 'alreadySent', still doesn't work. Need unit tests for this! * #48 Quick fix for unreasonable cache entries for events, which must not be cached and acknowledged. * Developer want to use luarocks for dependencies (#100) * #92 Added luarocks installation files. * #92 Added all-in-one luarocks executable. Added README.md how to use luarocks init in NoitaMP repo. Fixed smaller bugs on existing files. * #92 Looks like luarocks is working. package.paths aren't fully working yet. * #92 Updated README.md. Updated rockspec. Removed lfs.lua, which is using FFI. * #92 Reworking init_package_loading.lua. Need to know how to use LuaJIT in luarocks! * #92 Set LuaJIT-2.0.4 as lua interpreter for luarocks! * #92 Trying to add NSEW as a luarocks dependency, but doesn't like it atm. * #92 It's not possible to install, make or build dependencies on others repositories. Need to fork NSEW and add luarocks there. Damn it! * #92 Change Noita-Synchronise-Expansive-Worlds dependency name to nsew * #92 Changed rockspec. Removed NSEW rockspec. Trying to get tests running. * #92 Moved files regarding luarocks directory structure. * #92 Fixed broken test files fetching. Still trying to run tests. Changed rockspec as file names changed. * #92 Fixed broken test files fetching. Changed rockspec as file names changed. Tests are running locally, but some fail! Fixed broken badges and added new ones. * #92 Fixed execution of unit tests, they are now running as expected. * #92 Updated LuaRocks README.md * #92 Fixing GitHub actions. Need to know paths, that's why a dirty commit and push is done. * #92 Fixed GitHub action for unit testing. * #92 Fixed GitHub action Installing and initialising LuaRocks and configuring LuaJIT. * #92 Fixed missing Lua interpreter. * #92 Fixed typo in path. * #92 GitHub still doesn't like the path. * #92 Fixed lua interpreter not found. * #92 Fixed LuaRocks paths with `luarocks config ..` * #92 Fixed LuaRocks paths with `luarocks config --local ..` * #92 Fixed LuaRocks paths with `luarocks config --local ..` * #92 Fixed LuaRocks paths with `luarocks config --scope="project" ..` * #92 Fixed LuaRocks paths with `luarocks init noita-mp` * #92 Make sure luarocks does have any installed lua version. * #92 Make sure luarocks does have any installed lua version. Removed git submodule updater. * #92 LuaJIT is already set. * #92 Fixed wrong path and coveralls. * #92 Missing luarocks install packages. * #92 Fixed luacov path issue. * #92 Removed unnecessary installs. * #92 Added mingw32-gcc for lfs building. * #92 Install LuaJIT to fix LuaRocks not finding any Lua installation. * #92 Moved JIT modules and fixed missing directories on GitHub. * #92 Fixed paths. * #92 Moved Noitas lua51.dll into LuaJIT ones, to see if `luajit.exe: error loading module 'enet' from file 'D:\a\NoitaMP\NoitaMP\mods\noita-mp\lua_modules\lib\lua\5.1\enet.dll':%1 is not a valid Win32 application.` is fixed then. Because locally it's working fine! * #92 Don't use Luas dll, use Noitas dll instead. * #92 LuaRocks don't like Noitas dll. * #92 Make sure MSYS2 uses mingw32 with i686 to see if enet is recognised as a 32bit library. In addition, added -m32 flag. * #92 Remove mingw32 flags. * #92 Replaced MSYS2 with Visual Studio x86 * #92 Missed `shell: cmd`. * #92 MSYS2 or better to say MINGW32 is necessary for luarocks dependency installs. Changed LauJIT build and install action. * #92 Fixed wrong package name for MSYS2/MINGW32 installation. * #92 Let's see what LuaRocks is using! * #92 Trying to fix wrong gcc flags by keeping LuaRocks config the same as local. * #92 Where is mingw32-gcc installed? * #92 It's all about naming! * #92 Set a location to install msys2 into workspace directory. * #92 Fixed path to i686-w64-mingw32-gcc.exe * #92 Try it as it's working locally. * #92 `'D:\a\NoitaMP\NoitaMP\msys64\mingw32\bin\gcc.exe' is not recognized as an internal or external command, operable program or batch file.` * #92 `'D:\a\NoitaMP\NoitaMP\msys64\mingw32\bin\gcc.exe' is not recognized as an internal or external command, operable program or batch file.` * #92 `'D:\a\NoitaMP\NoitaMP\msys64\mingw32\bin\gcc.exe' is not recognized as an internal or external command, operable program or batch file.` * #92 `'D:\a\NoitaMP\NoitaMP\msys64\mingw32\bin\gcc.exe' is not recognized as an internal or external command, operable program or batch file.` * #92 Fucking stupid LuaRocks! * #92 Fucking stupid LuaRocks! * Update windows-latest-lua-unit-testing.yml * Make use of MVSC prompt * Updated path with ${{ github.workspace }} * Looks like luarocks forgot his own config file * Use luajit.exe * Update windows-latest-lua-unit-testing.yml * Update LPATH and CPATH * Update windows-latest-lua-unit-testing.yml * Update windows-latest-lua-unit-testing.yml * Exit? * Update windows-latest-lua-unit-testing.yml * Update windows-latest-lua-unit-testing.yml * Update windows-latest-lua-unit-testing.yml * Added new LuaCov config file * Changed luacov-coveralls command * Changed luacov and luacov-coveralls commands * Where is the report file? * Update windows-latest-lua-unit-testing.yml * Update windows-latest-lua-unit-testing.yml * Update windows-latest-lua-unit-testing.yml * #92 Ran luacov and luacov-coveralls installation manually locally and everything is working fine. GitHub what's wrong? * #92 Ran luacov and luacov-coveralls installation manually locally and everything is working fine. GitHub what's wrong? * #92 I think MSVC logging isn't properly working. * #92 Fixed wrong path. * #92 Fixed wrong shell version. * #92 Fixed paths using GitHubs variable. * #92 Fixed powershell commands. * #92 Fixed powershell command. Let's keep it complicated! * #92 Fixed powershell command. Let's keep it complicated! * #92 Fixed powershell command. Let's keep it complicated! * #92 Fixed powershell command. Let's keep it complicated! * #92 Fixed powershell command. Let's keep it complicated! * #92 Fixed wrong luarocks path. * Fixed wrong windows command * #92 Fixed wrong luarocks path. * #92 Fixed wrong luarocks path. * #92 Fixed wrong luarocks path. * #92 Fixed wrong luarocks path. * #92 Fixed wrong luarocks path. * #92 Fixed CodeCov path. Coveralls still didn't work. * #92 Where is the log going? Uff * #92 luajit.exe instead of lua.bat? * #92 Let's try powershell again. * #92 Path issues again! * #92 Looks like `shell: cmd` isn't working properly, when using LuaRocks, because after the first `luarocks` command the shell/bash is exited. That's why I am using powershell now. * #92 Fixed formatting. * Update windows-latest-lua-unit-testing.yml * #92 Make sure necessary files are available. * #92 CMD again.. Trying `call`. * #92 Added exit code, when necessary files are missing. Using cmd with `call ...` now. Looks promising. * #92 Fixed cmd command issue. * #92 Fixed cmd command issue. Added custom GitHub error messages. * #92 Fixed cmd command issue. * #92 Fixed cmd command issue. * #92 Fixed cmd command issue. * Update windows-latest-lua-unit-testing.yml * Update windows-latest-lua-unit-testing.yml * Update windows-latest-lua-unit-testing.yml * Update windows-latest-lua-unit-testing.yml * #92 Added LuaRocks path to GitHub path. * #92 Added LuaRocks path to GitHub path. What's happening? * #92 Does GitHub know LUA_PATHs now? What is inside lua.bat? * #92 Does GitHub know LUA_PATHs now? What is inside lua.bat? * #92 Write LuaRocks path directly in $GITHUB_PATH * #92 Does setx work? * #92 Does setx work? * #92 Use powershell again. * #92 Use powershell again. * #92 Use powershell again. * #92 Added `LUA_PATH` and `LUA_CPATH` as global environment to be able to set those environment variables. * #92 Powershell is fun! * #92 Powershell is fun! * #92 Powershell is fun! * #92 Fixed setting GitHub environment variable. * Update windows-latest-lua-unit-testing.yml * Update windows-latest-lua-unit-testing.yml * #92 What's happening with the key? * #92 What's wrong with json.lua? * #92 LuaRocks is now working fine! Fixed several unit test and reworked guid.lua using uuid.lua now! Temporary disabled NetworkUtils_test.lua. Extended README.md for LuaRocks setup. * #92 Don't stop unit test workflow, when coverage isn't working anymore. * #92 luacov.stats.out exists, but luacov.report.out doesn't? * #92 Fixing Codecov coverage. * #92 Fixing Codecov coverage. * #92 Fixing Codecov coverage. * #92 Does Codecov path fixes work? * #92 Does Codecov path fixes work? * #92 Does Codecov path fixes work? * #92 Does Codecov path fixes work? * #92 Does Codecov path fixes work? * Update windows-latest-lua-unit-testing.yml * Update codecov.yml * Update codecov.yml * Update codecov.yml * Update codecov.yml https://codecov.freshdesk.com/support/solutions/articles/43000593943-files-not-showing-in-codecov-fixing-paths- * #92 CodeCov fixes for paths doesn't work. Trying to do it myself. * Update windows-latest-lua-unit-testing.yml * #92 Fixed paths with `sed` instead of using CodeCov `fixes`. * #92 Fixed paths with `sed` instead of using CodeCov `fixes`. * #92 Fixed paths with `sed` instead of using CodeCov `fixes`. * #92 Does fix luacov-coveralls ? * #92 Updating README.md for more usability. * #92 Fixed coveralls `base-path` or `root`-path. * Update windows-latest-lua-unit-testing.yml * Update windows-latest-lua-unit-testing.yml * #92 Changed README.md * #92 Testing failed and errored unit tests. * #92 Testing failed and errored unit tests. Missed `cmd`! * #92 Testing failed and errored unit tests. Missed `cmd`! * #92 Testing failed and errored unit tests. Missed `cmd`! * #92 Re- and moved all unnecessary files. * Update windows-latest-lua-unit-testing.yml * Update windows-latest-lua-unit-testing.yml * Update windows-latest-lua-unit-testing.yml * Update windows-latest-lua-unit-testing.yml * Update version-and-changelog-update.yml * Update windows-latest-lua-unit-testing.yml * Update windows-latest-lua-unit-testing.yml * Update windows-latest-lua-unit-testing.yml * Update windows-latest-lua-unit-testing.yml * Update windows-latest-lua-unit-testing.yml * Update windows-latest-lua-unit-testing.yml * Update windows-latest-lua-unit-testing.yml * Update windows-latest-lua-unit-testing.yml * Update windows-latest-lua-unit-testing.yml * Update windows-latest-lua-unit-testing.yml * Update windows-latest-lua-unit-testing.yml * Update windows-latest-lua-unit-testing.yml * Update windows-latest-lua-unit-testing.yml * Update windows-latest-lua-unit-testing.yml * Update version-and-changelog-update.yml * Update version-and-changelog-update.yml * Update version-and-changelog-update.yml * #92 Does this finally fix this bitchy cmd syntax? * Finally fixed workflow! * Changed version back to 0.1.1 * 0.1.0 * Update version-and-changelog-update.yml * #92 Testing Ismoh-Games/find-linked-issues * #92 Testing Ismoh-Games/find-linked-issues v0.0.2-alpha * #92 Testing Ismoh-Games/find-linked-issues v0.0.2-alpha * #92 Testing Ismoh-Games/find-linked-issues v0.0.4 * #92 Testing Ismoh-Games/find-linked-issues v0.0.4 with PAT. * #92 Moved and updated actions/checkout * #92 Why isn't my latest workflow.yml used? * #92 Updated Ismoh-Games/find-linked-issues to v0.0.5 * #92 Fixed `version-file-extraction-pattern`. * #92 Fixed `version-file-extraction-pattern`. * #92 Fixed `version-file-extraction-pattern`. Co-authored-by: Ismoh <12631485+Ismoh@users.noreply.github.com> * Updated version to v3.0.0-alpha+1285 in https://github.com/Ismoh/NoitaMP/pull/100 * Updated CHANGELOG.md in https://github.com/Ismoh/NoitaMP/pull/100 * Added NoitaMP contributing flow chart * Unbenanntes Diagramm.drawio.png eingefügt * Unbenanntes Diagramm.drawio.png eingefügt * #92 Updating CONTRIBUTING.md. Fixed version update issues. * FlowChart-work-around.drawio.png eingefügt * #92 Updating CONTRIBUTING.md. * #92 Updating CONTRIBUTING.md. * Update CONTRIBUTING.md * #92 Updating CONTRIBUTING.md. * #48 Updated CONTRIBUTING.md * Update init_package_loading.lua (#104) * Update init_package_loading.lua on game start, there was an error "The current directory is not inside the noita-mp". fixed it, io.popen("cd"):read("*a") were return Noita directory, not mod also don't think we need to check for correct directory, it can't be uncorrect now it works(how i think) as it supposed to be. P.S: there are still error about libs, if i understood correctly, you want to move all libs from \lua_modules to \files\lib\external\ , so i didn't touch it (kinda strange that it's already defined in mod, but still not moved) * Update init_package_loading.lua keep directory check * Rework network and entity caches to use the C API (#105) * Create cache.c and add CMakeList file * add lua51 lib file for linking * add solution file and update gitignore * move cache file to be in the main folder and push dll * make cache.c export the required dll functions * disable precompiled headers as they are not needed * make linker use an absolute path for lua51.lib * add setCache function to cache.c * add cache read functions * change luaL_checknumber to luaL_checkinteger * move dll output to be in mods/noita-mp * implement delete functions * switch entityutils to use new cache system * change order of params to cache.set call * max cache.c check for duplicates before adding data * update Ui.lua to use new cache system * change cache build outdir * fix incorrect types being used for guid * fix nil check in NoitaComponentUtils.getEntityData * allow nil nuids * fix client and server still using old cache funcs * rename cache to EntityCache * Fix _crtisvalidheappointer(block) error * add cacheusage func to get current memory usage * add checks before entitycache calls to avoid fatal errors * prefix entity cache functions with entityCache * Add network cache C implementation * add remove oldest function to network cache * Mostly implemented new network caching system * fix bug in network cache profiling function * actually remember to compile the dll :skull: * Fix bug in checksum function and other small bugs * move cache.c to building folder and update msbuild file * #89 Fixed package.path|cpath issues. Fixed some small bugs. Changed requirements: Used require instead of dofile_once. Added NetworkUtils_test.lua. * #89 Removed logging.lua and associated files. Added new Logger class. Changed old logging to new one. Changed unit test initialization and executing. * #89 Added new restart function, thanks to dextercd. Fixed using old logger. * #89 Removed old and unused files. Removed unnecessary logging. Fixed and added Logger errors. Extended tests. * #89 Renamed guid.lua to GuidUtils.lua. Renamed clientCacheID to _Id. Changed getClientCacheID to simply use peers guid, but recalculated to a number based on 16: A = 11, etc. pp. Fixed bugs while adding tests. * #89 Changed clientCacheId to GuidUtils.toNumber * #89 Added NetworkCacheUtils to have testable function and all functions regarding NetworkCache in one class. Moved both calculation of 'sum' into one function (DRY). Added NetworkCacheUtils_test. Fixed GuidUtils bug. Fixed some tests. * #89 Reinstalled lfs and removed lfs_ffi. Fixed test. Fixed unit test workflow. * #89 Updated zstandard library to version v1.5.2 win32. Hopefully fix GitHub issue, when running tests. * #89 Rebuild libzstd locally with `call "build.generic.cmd" VS2019 Win32 Release v140`. * #89 Removed building zstd on GitHub. * #89 Installed luajit-zstd with luarocks. Replaced libzstd.dll with a fresh build from Visual Studio 2015 Win32. Let's see, if this helps on GitHub. * #89 Let's see, if this helps on GitHub. * #89 Added x64 of zstd. Changed zstd.lua with wacky hacky loading. Let's see, if this helps on GitHub. I don't think so. * #89 Does MSVC help? * #89 Fixed wrong pcall? * #89 Is LuaJIT x86/32bit ? * #89 Added table.contentToString, which simply concat table values with a comma. Moved all md5 and NetworkCache function into NetworkCacheUtils.lua. Added checks to NetworkCacheUtils.lua. Added table.contentToString test. Extended NetworkCacheUtils_test.lua with additional tests. * #89 Fixed typos. * #89 Added hint regarding pairs order. * #89 Fixed several bugs. NeedNuid event still broken. * #89 Fixed several bugs. Added cache logging. * #89 Added checks for data consistency. Added sendNewGuid. Added new tests. Added overwritten API functions for being able to use two noita instances, without having guid issues. * #89 Updated zstandard to 1.5.2 per GitHub release. * #89 Trying to fix zstd ffi.load * #89 Simply put zstd version into repo dir for reference, since no library provides versions? * #89 Removed zstd files and added version command. * fixed bug where noita_root_directory_path could be nil * fix zstd paths * add logic for network event resendIdentifiers * #89 Added resendIdentifier for checking if network message has to be send again. * #89 No need to deepcopy the data table. * #89 Small changes. * remove resendindentifier declaration from events without any * #89 Added mocked functions. Fixed path issues on different systems. Renamed function for being more clear. Adjusted test related to path issues. Still trying to get alreadySend working. * add check for nil resendIdentifiers * #89 Fixed newNuid alreadySent * make contentToString clean whitespace * #89 Trying to fix alreadySent issues. * #89 Removed logging from table_extensions.lua. Changed whoAmI(). Added ackedAt to acknowledgement event. Fixed caching issue, where some networkMessages aren't cached correctly. Changed reading NoitaMP .version. Do not remove networkMessageId when event is acknowledgement. Acknowledgement networkMessages won't be cached, because those will only be sent in callbacks. Changed tests a bit in general. Finally fixed alreadySent tests and issues. * #89 Change alreadySent tests for being more reliable. Change some Server send functions to return true or false for a small check if message was sent. Added check if inUsedGuids are valid guids. * #89 Added some tests for alreadySent! * fix tests for mod content events * #89 Added NoitaMpSettings.lua, which will replace ModSettings in the future; ModSettings now read and write from NoitaMpSettings.lua! Added MinaUtils.lua. Added winapi.dll for getting processId. Added and changed tests slightly. Moved *localPlayer* function from EntityUtils into MinaUtils. Clean up! * rename cache.c to the more generic luaExtensions.c, as we can add non-cache funcs * rename dll to luaExtensions.dll * remove old dll * add tests for entityCache * #89 Change require order. Removed EntityCache from Lua context. Changed tests a bit. * #89 Added version update for rockspec. Added building luaExtensions.dll when there are changes in the specific luaExtensions.c. Applying PR suggestions. * #89 Added version update for rockspec. * #89 Added version update for rockspec. * #89 Added version update for rockspec. * #89 Added version update for rockspec. * #89 Added version update for rockspec. * #89 Added version update for rockspec. * #89 Added version update for rockspec. * #89 Added version update for rockspec. * #89 Added version update for rockspec. * Update version-and-changelog-update.yml * Update version-and-changelog-update.yml * Update windows-latest-lua-unit-testing.yml * Update windows-latest-lua-unit-testing.yml * #89 Changed EntityCache_test.lua slightly. * rebuild luaExtensions dll * #89 Rebuild luaExtensions.dll * #89 Changed EntityCache_test.lua, because setUp() seemed to be broken? There were plenty of entries in cache, although there should only be 5? * #89 Formatting only. * #89 Wrong wording. --------- Co-authored-by: Ismoh <12631485+Ismoh@users.noreply.github.com> Co-authored-by: Torben H * Updated version to v4.0.0-alpha+1302 in https://github.com/Ismoh/NoitaMP/pull/105 --------- Co-authored-by: Ismoh Co-authored-by: BlueAmulet <43395286+BlueAmulet@users.noreply.github.com> Co-authored-by: Torben H Co-authored-by: Ismoh <12631485+Ismoh@users.noreply.github.com> Co-authored-by: github-actions Co-authored-by: Scrymmery <49278078+Scrymmery@users.noreply.github.com> * Merge branch 'master' into develop Clean up! * develop Updated find-linked-issues * develop Changed commiting into base_ref. Changed README.md * Fixed tag creation and updating changelog * Fixed tag creation and updating changelog * Merge "113-improve-and-clean-codebase" into develop (#114) * rename file_util to FileUtils to follow the naming pattern * rename util.lua to Utils.lua * refactor the noita component scripts * cleanup init files * ensure consistent naming of extension files * rename test files * clean Ui file * fix custom profiler using old fileutils path * fix failing tests * #113 Added some logging. * Updated version to v4.1.0-alpha+1184 in https://github.com/Ismoh/NoitaMP/pull/114 * Updated version to v4.1.0-alpha+1195 in https://github.com/Ismoh/NoitaMP/pull/114 * Updated CHANGELOG.md in https://github.com/Ismoh/NoitaMP/pull/114 * remove line causing test env to fail * #113 Fixed os detections. * #113 Manually fixed version, because of workflow issue some days ago. * Change way that the test files are run * Delete init_logger_test.lua Not needed anymore * Update unitTestRunner.lua Slightly reformatting * remove output.txt * remove unneeded luaunit call * remove mocking and require calls from each test file that should be moved to the main file * #113 Fixed ffiExtensions issue where it was loaded more than once. Added lfs_ffi again, but will be removed soon again, I assume. * #113 Fixed recursive unitTestRunner execution. * #113 Removed unnecessary lfs_ffi again. Removed hack, for not loading ffiExtensions more than once, but this hided the initial error. * #113 Fixed Logger. --------- Co-authored-by: Ismoh <12631485+Ismoh@users.noreply.github.com> Co-authored-by: github-actions Co-authored-by: Torben H * # Conflicts: # .github/workflows/version-and-changelog-update.yml * develop Fixed several issues on dependency-updater.yml * develop Fixed wildcard in powershell * develop Changed wildcard.. * develop Fixed path issues. Missed `$` * develop Fixed `Expand-Archive` and paths. * develop Fixed path again. * develop Fixed `Remove-Item`. * develop Added missing `git add`. Clean up. * develop Fixed `git add` with force. Needs to double check `Expand-Archive` output. * develop Fixed missing directory. Fixed `git push`. * develop Fixed git. * develop Fixed missing `"` * develop Fixed git command order. * develop Fixed git command order and added `origin`. * develop Stil trying to fix git issues. * develop Stil trying to fix git issues. * develop Stil trying to fix git issues. * develop Stil trying to fix git issues. * develop Trying to fix git commands. * develop Trying to fix git commands. * develop Ignore LuaRocks for now! * develop Still git! * develop Still git! * develop Still git! * develop Still git! * develop Still git! * develop Still git! * develop Fixed `gh pr` * develop Finalised. * develop Added version file by tagName. Added check, if PR already exists. * develop Finalised: Do this only on schedule. * develop Added `git add` for version files. * develop Finalised dependency-updater.yml * develop Finished dependency-updater.yml * develop Finished dependency-updater.yml --------- Signed-off-by: dependabot[bot] Co-authored-by: github-actions Co-authored-by: github-actions Co-authored-by: github-actions Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Ismoh <12631485+Ismoh@users.noreply.github.com> Co-authored-by: quiddity-wp Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> Co-authored-by: ofoxsmith <77560533+ofoxsmith@users.noreply.github.com> Co-authored-by: BlueAmulet <43395286+BlueAmulet@users.noreply.github.com> Co-authored-by: Scrymmery <49278078+Scrymmery@users.noreply.github.com> --- .github/workflows/dependency-updater.yml | 240 +++++++------ .vscode/settings.json | 2 +- CHANGELOG.md | 16 + README.md | 7 +- mods/noita-mp/.version | 2 +- mods/noita-mp/config.lua | 14 +- .../files/scripts/NoitaMpSettings.lua | 24 +- mods/noita-mp/files/scripts/Ui.lua | 44 ++- .../{ffi_extensions.lua => ffiExtensions.lua} | 97 +++--- ...ng_extensions.lua => stringExtensions.lua} | 0 ...ble_extensions.lua => tableExtensions.lua} | 4 +- mods/noita-mp/files/scripts/init/init_.lua | 13 +- .../files/scripts/init/init_logger.lua | 2 +- .../scripts/init/init_package_loading.lua | 92 ++--- mods/noita-mp/files/scripts/net/Client.lua | 150 ++++---- mods/noita-mp/files/scripts/net/Server.lua | 160 ++++----- .../lua_component_enabler.lua | 7 +- .../scripts/noita-components/name_tags.lua | 29 +- .../scripts/noita-components/nuid_debug.lua | 33 +- .../scripts/noita-components/nuid_updater.lua | 49 +-- .../files/scripts/util/CustomProfiler.lua | 10 +- .../files/scripts/util/EntityUtils.lua | 18 +- .../util/{file_util.lua => FileUtils.lua} | 323 +++++++++--------- .../noita-mp/files/scripts/util/GuidUtils.lua | 8 +- mods/noita-mp/files/scripts/util/Logger.lua | 8 +- .../noita-mp/files/scripts/util/MinaUtils.lua | 6 +- .../files/scripts/util/NetworkCacheUtils.lua | 54 +-- .../files/scripts/util/NetworkUtils.lua | 4 +- .../files/scripts/util/NetworkVscUtils.lua | 14 +- .../scripts/util/NoitaComponentUtils.lua | 2 +- .../noita-mp/files/scripts/util/NuidUtils.lua | 6 +- .../scripts/util/{util.lua => Utils.lua} | 25 +- mods/noita-mp/init.lua | 46 ++- .../lua_modules/share/lua/5.1/os_name.lua | 1 + .../lua_modules/share/lua/5.1/profiler.lua | 2 +- .../lua_modules/share/lua/5.1/sock.lua | 16 +- .../lua_modules/share/lua/5.1/zstd.lua | 2 +- ...0-3.rockspec => noita-mp-4.0.1-4.rockspec} | 115 ++++--- mods/noita-mp/tests/config_test.lua | 15 - .../files/scripts/NoitaMpSettings_test.lua | 15 +- ...ons_test.lua => stringExtensions_test.lua} | 6 - ...ions_test.lua => tableExtensions_test.lua} | 24 +- .../tests/files/scripts/init/init__test.lua | 6 - .../files/scripts/init/init_logger_test.lua | 15 - .../init/init_package_loading_test.lua | 7 +- .../tests/files/scripts/net/Server_test.lua | 6 - .../files/scripts/util/EntityCache_test.lua | 8 +- .../files/scripts/util/EntityUtils_test.lua | 6 - ...{file_util_test.lua => FileUtils_test.lua} | 106 +++--- .../files/scripts/util/GlobalsUtils_test.lua | 6 - .../files/scripts/util/GuidUtils_test.lua | 14 +- .../tests/files/scripts/util/Logger_test.lua | 19 +- .../scripts/util/NetworkCacheUtils_test.lua | 59 +--- .../files/scripts/util/NetworkUtils_test.lua | 54 +-- .../scripts/util/NetworkVscUtils_test.lua | 6 - .../files/scripts/util/NuidUtils_test.lua | 8 +- .../util/{util_test.lua => Utils_test.lua} | 21 +- mods/noita-mp/tests/init_test.lua | 15 - ...ializeUnitTests.lua => unitTestRunner.lua} | 21 +- 59 files changed, 896 insertions(+), 1186 deletions(-) rename mods/noita-mp/files/scripts/extensions/{ffi_extensions.lua => ffiExtensions.lua} (66%) rename mods/noita-mp/files/scripts/extensions/{string_extensions.lua => stringExtensions.lua} (100%) rename mods/noita-mp/files/scripts/extensions/{table_extensions.lua => tableExtensions.lua} (99%) rename mods/noita-mp/files/scripts/util/{file_util.lua => FileUtils.lua} (64%) rename mods/noita-mp/files/scripts/util/{util.lua => Utils.lua} (88%) rename mods/noita-mp/{noita-mp-3.0.0-3.rockspec => noita-mp-4.0.1-4.rockspec} (51%) delete mode 100644 mods/noita-mp/tests/config_test.lua rename mods/noita-mp/tests/files/scripts/extensions/{string_extensions_test.lua => stringExtensions_test.lua} (93%) rename mods/noita-mp/tests/files/scripts/extensions/{table_extensions_test.lua => tableExtensions_test.lua} (85%) delete mode 100644 mods/noita-mp/tests/files/scripts/init/init_logger_test.lua rename mods/noita-mp/tests/files/scripts/util/{file_util_test.lua => FileUtils_test.lua} (79%) rename mods/noita-mp/tests/files/scripts/util/{util_test.lua => Utils_test.lua} (64%) delete mode 100644 mods/noita-mp/tests/init_test.lua rename mods/noita-mp/tests/{_initializeUnitTests.lua => unitTestRunner.lua} (88%) diff --git a/.github/workflows/dependency-updater.yml b/.github/workflows/dependency-updater.yml index cd6325525..d4dfb8178 100644 --- a/.github/workflows/dependency-updater.yml +++ b/.github/workflows/dependency-updater.yml @@ -1,175 +1,189 @@ -name: Update dependecies now and then +name: Update dependecies every saturday at 00:00 UTC on: schedule: - # Weekly on saturday + # Weekly on saturday at 00:00 UTC - cron: "0 0 * * 6" push: + branches: + - develop jobs: update-dependencies: name: Update dependencies runs-on: windows-latest - + steps: - uses: actions/checkout@v3 + with: + ref: develop + fetch-depth: 0 - - name: Create new branch - run: | - git config --local user.email "action@github.com" - git config --local user.name "github-actions" - git checkout -b dependency-updates master || git checkout dependency-updates - - - name: Install and init luarocks - shell: cmd - run: | - git config --local user.email "action@github.com" - git config --local user.name "github-actions" - git checkout -b dependency-updates master || git checkout dependency-updates - - cd ${{ github.workspace}}\mods\noita-mp\ - set INIT_PATH=%CD% - REM // resolve absolute path - set REL_PATH=..\..\.building\luarocks-3.9.1-windows-32 - set ABS_PATH= - rem // Save current directory and change to target directory - pushd %REL_PATH% - rem // Save value of CD variable (current directory) - set ABS_PATH=%CD% - rem // Restore original directory - popd - echo Relative path: %REL_PATH% - echo Maps to path: %ABS_PATH% - - REM // init luarocks - %ABS_PATH%\luarocks --lua-dir="${{ github.workspace}}\LuaJIT-2.0.4" --lua-version="5.1" init noita-mp --output="${{ github.workspace}}\mods\noita-mp" --homepage="https://github.com/Ismoh/NoitaMP" --lua-versions="5.1" --license="GNU GPL v3" - - REM // change luarocks projects config - %ABS_PATH%\luarocks config --scope="project" lua_interpreter luajit.exe - %ABS_PATH%\luarocks config --scope="project" lua_dir ${{ github.workspace}}\LuaJIT-2.0.4 - %ABS_PATH%\luarocks config --scope="project" variables.LUA_BINDIR ${{ github.workspace}}\LuaJIT-2.0.4\bin - %ABS_PATH%\luarocks config --scope="project" variables.LUA_DIR ${{ github.workspace}}\LuaJIT-2.0.4 - %ABS_PATH%\luarocks config --scope="project" variables.LUA_INCDIR ${{ github.workspace}}\LuaJIT-2.0.4\include - %ABS_PATH%\luarocks config --scope="project" variables.CFLAGS "GODDAMNIT" - %ABS_PATH%\luarocks config - - if exist lua.bat ( - echo "LuaRocks project init successfully" - ) else ( - echo "::error::LuaRocks project init failed. Unable to find lua.bat" - exit 1 - ) - if exist luarocks.bat ( - echo "LuaRocks project init successfully" - ) else ( - echo "::error::LuaRocks project init failed. Unable to find luarocks.bat" - exit 1 - ) - - - name: Fix LuaRocks bug + - name: Checkout or create new branch 'dependency-updates' env: GH_TOKEN: ${{ github.token }} run: | git config --local user.email "action@github.com" git config --local user.name "github-actions" - git checkout -b dependency-updates master || git checkout dependency-updates - - cd ${{ github.workspace}}\mods\noita-mp\.luarocks - sed -i 's/GODDAMNIT/\-v \-O2/g' config-5.1.lua - cat config-5.1.lua - - - name: Update LuaRocks - # env: - # GH_TOKEN: ${{ github.token }} - shell: cmd - run: | - git config --local user.email "action@github.com" - git config --local user.name "github-actions" - - git checkout -b dependency-updates master || git checkout dependency-updates - call "C:\Program Files\Microsoft Visual Studio\2022\Enterprise\VC\Auxiliary\Build\vcvarsall.bat" x86 10.0.22000.0 -vcvars_ver=14 - cd ${{ github.workspace }}\mods\noita-mp\ - # luarocks install --only-deps ${{ github.workspace }}\mods\noita-mp\noita-mp-3.0.0-3.rockspec - - git commit -m "Update LuaRocks dependencies" -a || echo "No changes to commit" + git remote update + git fetch + git checkout -b dependency-updates origin/develop + + # - name: Install and init luarocks + # shell: cmd + # run: | + # cd ${{ github.workspace}}\mods\noita-mp\ + # set INIT_PATH=%CD% + # REM // resolve absolute path + # set REL_PATH=..\..\.building\luarocks-3.9.1-windows-32 + # set ABS_PATH= + # rem // Save current directory and change to target directory + # pushd %REL_PATH% + # rem // Save value of CD variable (current directory) + # set ABS_PATH=%CD% + # rem // Restore original directory + # popd + # echo Relative path: %REL_PATH% + # echo Maps to path: %ABS_PATH% + + # REM // init luarocks + # %ABS_PATH%\luarocks --lua-dir="${{ github.workspace}}\LuaJIT-2.0.4" --lua-version="5.1" init noita-mp --output="${{ github.workspace}}\mods\noita-mp" --homepage="https://github.com/Ismoh/NoitaMP" --lua-versions="5.1" --license="GNU GPL v3" + + # REM // change luarocks projects config + # %ABS_PATH%\luarocks config --scope="project" lua_interpreter luajit.exe + # %ABS_PATH%\luarocks config --scope="project" lua_dir ${{ github.workspace}}\LuaJIT-2.0.4 + # %ABS_PATH%\luarocks config --scope="project" variables.LUA_BINDIR ${{ github.workspace}}\LuaJIT-2.0.4\bin + # %ABS_PATH%\luarocks config --scope="project" variables.LUA_DIR ${{ github.workspace}}\LuaJIT-2.0.4 + # %ABS_PATH%\luarocks config --scope="project" variables.LUA_INCDIR ${{ github.workspace}}\LuaJIT-2.0.4\include + # %ABS_PATH%\luarocks config --scope="project" variables.CFLAGS "GODDAMNIT" + # %ABS_PATH%\luarocks config + + # if exist lua.bat ( + # echo "LuaRocks project init successfully" + # ) else ( + # echo "::error::LuaRocks project init failed. Unable to find lua.bat" + # exit 1 + # ) + # if exist luarocks.bat ( + # echo "LuaRocks project init successfully" + # ) else ( + # echo "::error::LuaRocks project init failed. Unable to find luarocks.bat" + # exit 1 + # ) + + # - name: Fix LuaRocks bug + # env: + # GH_TOKEN: ${{ github.token }} + # run: | + # cd ${{ github.workspace}}\mods\noita-mp\.luarocks + # sed -i 's/GODDAMNIT/\-v \-O2/g' config-5.1.lua + # cat config-5.1.lua + + # - name: Update LuaRocks + # # env: + # # GH_TOKEN: ${{ github.token }} + # shell: cmd + # run: | + # call "C:\Program Files\Microsoft Visual Studio\2022\Enterprise\VC\Auxiliary\Build\vcvarsall.bat" x86 10.0.22000.0 -vcvars_ver=14 + # cd ${{ github.workspace }}\mods\noita-mp\ + # # luarocks install --only-deps ${{ github.workspace }}\mods\noita-mp\noita-mp-3.0.0-3.rockspec + + # git commit -m "Updated LuaRocks dependencies" -a || echo "No changes to commit" - name: Update NoitaPatcher env: - GH_TOKEN: ${{ github.token }} + GH_TOKEN: ${{ github.token }} run: | - git config --local user.email "action@github.com" - git config --local user.name "github-actions" - git checkout -b dependency-updates master || git checkout dependency-updates - $noitaptacherPath = "${{ github.workspace }}\mods\noita-mp\lua_modules\lib\lua\5.1\noitapatcher.dll" if ([System.IO.File]::Exists($noitaptacherPath)) { - $lastModifiedDate = (Get-Item $noitapatcherPath).CreationTime.ToString("yyyy-MM-ddThh:mm:ssZ") + $creationTime = (Get-Item $noitapatcherPath).CreationTime.ToString("yyyy-MM-ddThh:mm:ssZ") } else { - $lastModifiedDate = "2021-11-10T00:00:00Z" + $creationTime = "2021-11-10T00:00:00Z" } - $lastModifiedDate = [Datetime]::ParseExact($lastModifiedDate, "yyyy-MM-ddThh:mm:ssZ", $null) + $creationTime = [Datetime]::ParseExact($creationTime, "yyyy-MM-ddThh:mm:ssZ", $null) $releaseCreatedAt = gh release view --repo dextercd/NoitaPatcher --json createdAt --jq .createdAt $releaseCreatedAt = [Datetime]$releaseCreatedAt - if ($releaseCreatedAt -lt $lastModifiedDate) { + echo "NoitaPatcher was created at $creationTime" + echo "Latest release was created at $releaseCreatedAt" + echo ($releaseCreatedAt -lt $creationTime) + + if ($releaseCreatedAt -lt $creationTime) { echo "NoitaPatcher is up to date" exit 0 } else { - gh release download --repo dextercd/NoitaPatcher --pattern "*.zip" --dir "{{ github.workspace }}\temp" + gh release download --repo dextercd/NoitaPatcher --pattern "*.zip" --dir "${{ github.workspace }}\temp" } - Expand-Archive -Path "${{ github.workspace }}\temp\*.zip" -DestinationPath "{{ github.workspace }}\temp" - Copy-Item -Path "${{ github.workspace }}\temp\noitapatcher.dll" -Destination $noitaptacherPath -Force - Copy-Item -Path "${{ github.workspace }}\temp\modules\noitapatcher.lua" -Destination "{{ github.workspace }}\.debug\lua-definitions" -Force + $tagName = gh release view --repo dextercd/NoitaPatcher --json tagName --jq .tagName + $tagName | Out-File -FilePath ${{ github.workspace }}\mods\noita-mp\lua_modules\lib\lua\5.1\noitapatcher.version + + Expand-Archive -Path "${{ github.workspace }}\temp\NoitaPatcher*.zip" -DestinationPath "${{ github.workspace }}\temp" -Force + Copy-Item -Path "${{ github.workspace }}\temp\NoitaPatcher\noitapatcher.dll" -Destination $noitaptacherPath -Force + Copy-Item -Path "${{ github.workspace }}\temp\NoitaPatcher\modules\noitapatcher.lua" -Destination "${{ github.workspace }}\.debug\lua-definitions" -Force + cd ${{ github.workspace }} # go back to root otherwise we cannot delete the temp folder Remove-Item -Path "${{ github.workspace }}\temp" -Recurse -Force - git commit -m "Update NoitaPatcher dependencies" -a || echo "No changes to commit" + git add ${{ github.workspace }}\mods\noita-mp\lua_modules\lib\lua\5.1\noitapatcher.version + git add -f $noitaptacherPath + git add "${{ github.workspace }}\.debug\lua-definitions\noitapatcher.lua" + git commit -m "Updated NoitaPatcher dependencies" -a || echo "No changes to commit" - - name: Update NSEW + - name: Update Noita-Synchronise-Expansive-Worlds env: GH_TOKEN: ${{ github.token }} run: | - git config --local user.email "action@github.com" - git config --local user.name "github-actions" - git checkout -b dependency-updates master || git checkout dependency-updates - $nsewPath = "${{ github.workspace }}\mods\noita-mp\lua_modules\lib\lua\5.1\nsew_native.dll" if ([System.IO.File]::Exists($neswPath)) { - $lastModifiedDate = (Get-Item $nsewPath).CreationTime.ToString("yyyy-MM-ddThh:mm:ssZ") + $creationTime = (Get-Item $nsewPath).CreationTime.ToString("yyyy-MM-ddThh:mm:ssZ") } else { - $lastModifiedDate = "2021-11-10T00:00:00Z" + $creationTime = "2021-11-10T00:00:00Z" } - $lastModifiedDate = [Datetime]::ParseExact($lastModifiedDate, "yyyy-MM-ddThh:mm:ssZ", $null) + $creationTime = [Datetime]::ParseExact($creationTime, "yyyy-MM-ddThh:mm:ssZ", $null) $releaseCreatedAt = gh release view --repo dextercd/Noita-Synchronise-Expansive-Worlds --json createdAt --jq .createdAt $releaseCreatedAt = [Datetime]$releaseCreatedAt - if ($releaseCreatedAt -lt $lastModifiedDate) { + echo "Noita-Synchronise-Expansive-Worlds was created at $creationTime" + echo "Latest release was created at $releaseCreatedAt" + echo ($releaseCreatedAt -lt $creationTime) + + if ($releaseCreatedAt -lt $creationTime) { echo "Noita-Synchronise-Expansive-Worlds is up to date" exit 0 } else { - git config --local user.email "action@github.com" - git config --local user.name "github-actions" - git checkout -b dependency-updates master || git checkout dependency-updates - gh release download --repo dextercd/Noita-Synchronise-Expansive-Worlds --pattern "*.zip" --dir "{{ github.workspace }}\temp" + gh release download --repo dextercd/Noita-Synchronise-Expansive-Worlds --pattern "*.zip" --dir "${{ github.workspace }}\temp" } - Expand-Archive -Path "${{ github.workspace }}\temp\*.zip" -DestinationPath "{{ github.workspace }}\temp" - Copy-Item -Path "${{ github.workspace }}\temp\nsew\nsew_native.dll" -Destination $nsewPath -Force - Copy-Item -Path "${{ github.workspace }}\temp\nsew\*.lua" -Destination "{{ github.workspace }}\mods\noita-mp\lua_modules\share\lua\5.1\nsew" -Force + $tagName = gh release view --repo dextercd/Noita-Synchronise-Expansive-Worlds --json tagName --jq .tagName + $tagName | Out-File -FilePath ${{ github.workspace }}\mods\noita-mp\lua_modules\lib\lua\5.1\nsew.version + + Expand-Archive -Path "${{ github.workspace }}\temp\nsew-*.zip" -DestinationPath "${{ github.workspace }}\temp\nsew" -Force + Copy-Item -Path "${{ github.workspace }}\temp\nsew\nsew\nsew_native.dll" -Destination $nsewPath -Force + if (![System.IO.File]::Exists("${{ github.workspace }}\mods\noita-mp\lua_modules\share\lua\5.1\nsew")) { + New-Item -Path "${{ github.workspace }}\mods\noita-mp\lua_modules\share\lua\5.1\nsew" -ItemType Directory -Force + } + Copy-Item -Path "${{ github.workspace }}\temp\nsew\nsew\*.lua" -Destination "${{ github.workspace }}\mods\noita-mp\lua_modules\share\lua\5.1\nsew" -Force + cd ${{ github.workspace }} # go back to root otherwise we cannot delete the temp folder Remove-Item -Path "${{ github.workspace }}\temp" -Recurse -Force - git commit -m "Update nsew dependencies" -a || echo "No changes to commit" + git add ${{ github.workspace }}\mods\noita-mp\lua_modules\lib\lua\5.1\nsew.version + git add -f $nsewPath + git add -f "${{ github.workspace }}\mods\noita-mp\lua_modules\share\lua\5.1\nsew\*.lua" + git commit -m "Updated nsew dependencies" -a || echo "No changes to commit" - - name: Push changes + - name: Push changes and create a pull request env: GH_TOKEN: ${{ github.token }} run: | - git config --local user.email "action@github.com" - git config --local user.name "github-actions" - git checkout -b dependency-updates master || git checkout dependency-updates - + git pull origin dependency-updates git push origin dependency-updates - gh pr create --title "Update dependencies" --body "This PR was automatically created by the dependency updater workflow. Resolves #117" --base master --head dependency-updates || echo "PR already exists" + + $prTitleArray = gh pr list --head "dependency-updates" --json "title" | ConvertFrom-Json + if ($prTitleArray.Count -gt 0) { + echo "PR already exists. Nothing to do!" + } else { + gh pr create --title "Update dependencies" --body "This PR was automatically created by the dependency updater workflow. Resolves #117" --base develop --head dependency-updates --assignee Ismoh --reviewer Ismoh + } diff --git a/.vscode/settings.json b/.vscode/settings.json index 5501bc012..76dabaa0b 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -44,7 +44,7 @@ }, "Lua.diagnostics.disable": [ "lowercase-global", - "undefined-field" + "deprecated" ], "files.associations": { "stdbool.h": "c", diff --git a/CHANGELOG.md b/CHANGELOG.md index 10c16ab52..cfb454292 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,21 @@ # Changelog +## [v4.1.0-alpha+1195](https://github.com/Ismoh/NoitaMP/tree/v4.1.0-alpha+1195) (05.03.2023) + +[Full Changelog](https://github.com/Ismoh/NoitaMP/compare/v4.1.0-alpha+1184...v4.1.0-alpha+1195) + +## [v4.1.0-alpha+1184](https://github.com/Ismoh/NoitaMP/tree/v4.1.0-alpha+1184) (05.03.2023) + +[Full Changelog](https://github.com/Ismoh/NoitaMP/compare/v4.0.1-alpha+792...v4.1.0-alpha+1184) + +**Implemented enhancements:** + +- Developer want to sync children and components [\#107](https://github.com/Ismoh/NoitaMP/issues/107) [[enhancement](https://github.com/Ismoh/NoitaMP/labels/enhancement)] + +**Closed issues:** + +- Update CHANGELOG.md [\#112](https://github.com/Ismoh/NoitaMP/issues/112) [[documentation](https://github.com/Ismoh/NoitaMP/labels/documentation)] [[github_actions](https://github.com/Ismoh/NoitaMP/labels/github_actions)] + ## [v4.0.1-alpha+792](https://github.com/Ismoh/NoitaMP/tree/v4.0.1-alpha+792) (17.02.2023) [Full Changelog](https://github.com/Ismoh/NoitaMP/compare/v4.0.0-alpha+1302...v4.0.1-alpha+792) diff --git a/README.md b/README.md index 44dba489f..ac00ffdaa 100644 --- a/README.md +++ b/README.md @@ -82,9 +82,12 @@ I wouldn't be able to create this mod without the help by - [@ofoxsmith](https://github.com/ofoxsmith) -I also want to say thank you to the supporter of this project on [Github](https://github.com/sponsors/Ismoh) or [Patreon](https://www.patreon.com/ismoh): +I also want to say thank you to the supporter of this project on [GitHub](https://github.com/sponsors/Ismoh) or [Patreon](https://www.patreon.com/ismoh): -- [stefnotch](https://github.com/stefnotch) one-time 20$ 18.11.22 +| Name | Amount | Type | Start | +|:-------------------------------------------:|:--------:|:----------:|:--------------:| +| [stefnotch](https://github.com/stefnotch) | 20$ | one-time | Nov 18, 2022 | +| [den3606](https://github.com/den3606) | 1$ | monthly | Feb 8, 2023 | If you spot anything I should mention, feel free to create an issue or get in touch with [me](https://github.com/Ismoh)! diff --git a/mods/noita-mp/.version b/mods/noita-mp/.version index ee77ebac6..6f6bee8b7 100644 --- a/mods/noita-mp/.version +++ b/mods/noita-mp/.version @@ -1 +1 @@ -{"version":"v4.0.1-alpha+792"} +{"version":"v4.0.1-alpha+1195"} diff --git a/mods/noita-mp/config.lua b/mods/noita-mp/config.lua index 003259143..0869e597d 100644 --- a/mods/noita-mp/config.lua +++ b/mods/noita-mp/config.lua @@ -48,13 +48,13 @@ local NoitaApiModSettingGet = ModSettingGet local NoitaApiModSettingSetNextValue = ModSettingSetNextValue local NoitaApiModSettingGetNextValue = ModSettingGetNextValue -if not util then +if not Utils then if require then - util = require("util") + Utils = require("Utils") else -- when NoitaComponents with their own restricted LuaContext load this file, -- util isn't available! - util = dofile_once("mods/noita-mp/files/scripts/util/util.lua") + Utils = dofile_once("mods/noita-mp/files/scripts/util/Utils.lua") if not MinaUtils and not require then MinaUtils = dofile_once("mods/noita-mp/files/scripts/util/MinaUtils.lua") end @@ -74,7 +74,7 @@ end ModSettingGet = function(id) if id == "noita-mp.name" then local name = MinaUtils.getLocalMinaName() - if not util.IsEmpty(name) then + if not Utils.IsEmpty(name) then return name else name = NoitaApiModSettingGet(id) @@ -84,7 +84,7 @@ ModSettingGet = function(id) end if id == "noita-mp.guid" then local guid = MinaUtils.getLocalMinaGuid() - if not util.IsEmpty(guid) then + if not Utils.IsEmpty(guid) then return guid else guid = NoitaApiModSettingGet(id) @@ -108,13 +108,13 @@ end ModSettingGetNextValue = function(id) if id == "noita-mp.name" and name then local name = MinaUtils.getLocalMinaName() - if not util.IsEmpty(name) then + if not Utils.IsEmpty(name) then return name end end if id == "noita-mp.guid" and guid then local guid = MinaUtils.getLocalMinaGuid() - if not util.IsEmpty(guid) then + if not Utils.IsEmpty(guid) then return guid end end diff --git a/mods/noita-mp/files/scripts/NoitaMpSettings.lua b/mods/noita-mp/files/scripts/NoitaMpSettings.lua index 2d81139f3..df9765657 100644 --- a/mods/noita-mp/files/scripts/NoitaMpSettings.lua +++ b/mods/noita-mp/files/scripts/NoitaMpSettings.lua @@ -10,11 +10,11 @@ ------------------------------------------------------------------------------------------------------------------------ --- 'Imports' ------------------------------------------------------------------------------------------------------------------------ -local fu = require("file_util") +local fu = require("FileUtils") local lfs = require("lfs") local winapi = require("winapi") local json = require("json") -local util = require("util") +local Utils = require("Utils") ------------------------------------------------------------------------------------------------------------------------ --- NoitaMpSettings @@ -23,9 +23,9 @@ NoitaMpSettings = {} function NoitaMpSettings.clearAndCreateSettings() local cpc = CustomProfiler.start("NoitaMpSettings.clearAndCreateSettings") - local settingsDir = fu.getAbsolutePathOfNoitaMpSettingsDirectory() - if fu.exists(settingsDir) then - fu.removeContentOfDirectory(settingsDir) + local settingsDir = fu.GetAbsolutePathOfNoitaMpSettingsDirectory() + if fu.Exists(settingsDir) then + fu.RemoveContentOfDirectory(settingsDir) Logger.info(Logger.channels.initialize, ("Removed old settings in '%s'!"):format(settingsDir)) else lfs.mkdir(settingsDir) @@ -36,11 +36,11 @@ end function NoitaMpSettings.writeSettings(key, value) local cpc = CustomProfiler.start("NoitaMpSettings.writeSettings") - if util.IsEmpty(key) or type(key) ~= "string" then + if Utils.IsEmpty(key) or type(key) ~= "string" then error(("'key' must not be nil or is not type of string!"):format(key), 2) end - if util.IsEmpty(value) or type(value) ~= "string" then + if Utils.IsEmpty(value) or type(value) ~= "string" then error(("'value' must not be nil or is not type of string!"):format(value), 2) end @@ -51,9 +51,9 @@ function NoitaMpSettings.writeSettings(key, value) who = whoAmI() end local settingsFile = ("%s%s%s%s.json") - :format(fu.getAbsolutePathOfNoitaMpSettingsDirectory(), pathSeparator, pid, who) + :format(fu.GetAbsolutePathOfNoitaMpSettingsDirectory(), pathSeparator, pid, who) - if not fu.exists(settingsFile) then + if not fu.Exists(settingsFile) then fu.WriteFile(settingsFile, "{}") end @@ -75,16 +75,16 @@ function NoitaMpSettings.getSetting(key) local pid = winapi.get_current_pid() local settingsFile = ("%s%s%s%s.json") - :format(fu.getAbsolutePathOfNoitaMpSettingsDirectory(), pathSeparator, pid, whoAmI()) + :format(fu.GetAbsolutePathOfNoitaMpSettingsDirectory(), pathSeparator, pid, whoAmI()) - if not fu.exists(settingsFile) then + if not fu.Exists(settingsFile) then fu.WriteFile(settingsFile, "{}") end local contentString = fu.ReadFile(settingsFile) local contentJson = json.decode(contentString) - if util.IsEmpty(contentJson[key]) then + if Utils.IsEmpty(contentJson[key]) then error(("Unable to find '%s' in NoitaMpSettings: %s"):format(key, contentString), 2) end local value = contentJson[key] diff --git a/mods/noita-mp/files/scripts/Ui.lua b/mods/noita-mp/files/scripts/Ui.lua index 86608c5d9..968c699f8 100644 --- a/mods/noita-mp/files/scripts/Ui.lua +++ b/mods/noita-mp/files/scripts/Ui.lua @@ -6,15 +6,16 @@ ---------------------------------------- -- 'Imports' ---------------------------------------- -local renderEzgui = dofile_once("mods/noita-mp/lua_modules/share/lua/5.1/ezgui/EZGUI.lua").init("mods/noita-mp/lua_modules/share/lua/5.1/ezgui") -local fu = require("file_util") +local renderEzgui = dofile_once("mods/noita-mp/lua_modules/share/lua/5.1/ezgui/EZGUI.lua").init( + "mods/noita-mp/lua_modules/share/lua/5.1/ezgui") +local fu = require("FileUtils") ---------------------------------------------------------------------------------------------------- --- Ui --- @see PlayerList.xml --- @see FoldingMenu.xml ---------------------------------------------------------------------------------------------------- -Ui = {} +Ui = {} ---------------------------------------- -- Global private variables: @@ -50,7 +51,7 @@ end --- Ui constructor ---------------------------------------------------------------------------------------------------- function Ui.new() - local self = {} + local self = {} ------------------------------------ -- Private variables: @@ -87,31 +88,31 @@ function Ui.new() cellWidth = 50, }, methods = { - toggleAddress = function() + toggleAddress = function() showAddress = not showAddress end, - copyAddress = function() - util.copyToClipboard(("%s:%s"):format(_G.Server:getAddress(), _G.Server:getPort())) + copyAddress = function() + Utils.copyToClipboard(("%s:%s"):format(_G.Server:getAddress(), _G.Server:getPort())) end, - kick = function(data, element, arg1) + kick = function(data, element, arg1) _G.Server.kick(arg1) end, - ban = function(data, element, arg1) + ban = function(data, element, arg1) _G.Server.ban(arg1) end, - start = function() + start = function() _G.Server.start(nil, nil) end, - stop = function() + stop = function() _G.Server.stop() end, - connect = function() + connect = function() _G.Client.connect() end, - disconnect = function() + disconnect = function() _G.Client.disconnect() end, - toggleDebug = function() + toggleDebug = function() debug = not debug end, reportCustomProfiler = function() @@ -150,12 +151,12 @@ function Ui.new() local text = "" if foldingOpen then self.ezguiFoldingData.data.text = ("[- NoitaMP] %s eCache:%s pCache:%s nCache:%s %s") - :format(fu.getVersionByFile(), EntityCache.size(), CustomProfiler.getSize(), - NetworkUtils.getClientOrServer().getAckCacheSize(), GameGetFrameNum()) + :format(fu.GetVersionByFile(), EntityCache.size(), CustomProfiler.getSize(), + NetworkUtils.getClientOrServer().getAckCacheSize(), GameGetFrameNum()) else self.ezguiFoldingData.data.text = ("[+ NoitaMP] eCache:%s pCache:%s nCache:%s %s") - :format(EntityCache.size(), CustomProfiler.getSize(), - NetworkUtils.getClientOrServer().getAckCacheSize(), GameGetFrameNum()) + :format(EntityCache.size(), CustomProfiler.getSize(), + NetworkUtils.getClientOrServer().getAckCacheSize(), GameGetFrameNum()) end renderEzgui(0, height - 10, "mods/noita-mp/files/data/ezgui/FoldingMenu.xml", self.ezguiFoldingData) @@ -181,9 +182,6 @@ function Ui.new() }) table.insertAllButNotDuplicates(player, _G.Server.clients) for i = 2, #player do - --player[i].name = string.ExtendOrCutStringToLength(player[i].name, 12, ".", true) - --player[i].health = { current = i, max = 2 } - --player[i].transform = { x = 123, y = 12334 } player[i].rtt = player[i]:getRoundTripTime() end else @@ -271,7 +269,7 @@ function Ui.new() if clicked then missingModGuiDismissed = true Client:send(NetworkUtils.events.needModContent.name, - { NetworkUtils.getNextNetworkMessageId(), Client.missingMods }) + { NetworkUtils.getNextNetworkMessageId(), Client.missingMods }) end if hovered then missingModGuiButton1Hovered = true @@ -318,7 +316,6 @@ function Ui.new() GuiZSetForNextWidget(gui, 110) GuiImageNinePiece(gui, npID, 73, 73, w + 3, y - 71) end - end ------------------------------------ @@ -328,7 +325,6 @@ function Ui.new() drawFolding() drawMenu() drawModConflictWarning() - if EntityCache.size() >= EntityUtils.maxPoolSize then gui = gui or GuiCreate() GuiStartFrame(gui) diff --git a/mods/noita-mp/files/scripts/extensions/ffi_extensions.lua b/mods/noita-mp/files/scripts/extensions/ffiExtensions.lua similarity index 66% rename from mods/noita-mp/files/scripts/extensions/ffi_extensions.lua rename to mods/noita-mp/files/scripts/extensions/ffiExtensions.lua index 85534ed9f..a239d8112 100644 --- a/mods/noita-mp/files/scripts/extensions/ffi_extensions.lua +++ b/mods/noita-mp/files/scripts/extensions/ffiExtensions.lua @@ -6,9 +6,9 @@ end local ffi = require("ffi") -local C = ffi.C +local C = ffi.C -ffi.cdef[[ +ffi.cdef [[ typedef bool BOOL; typedef uint16_t WORD; typedef uint32_t DWORD; @@ -95,37 +95,37 @@ BOOL ReadFile( DWORD GetLastError(); ]] -local EXIT_FAILURE = 1 +local EXIT_FAILURE = 1 local STARTF_USESHOWWINDOW = 1 local STARTF_USESTDHANDLES = 0x100 -local SW_HIDE = 0 -local CREATE_NO_WINDOW = 0x8000000 -local INFINITE = -1 -local HANDLE_FLAG_INHERIT = 1 -local STD_INPUT_HANDLE = -10 -local STD_ERROR_HANDLE = -12 -local ERROR_BROKEN_PIPE = 109 +local SW_HIDE = 0 +local CREATE_NO_WINDOW = 0x8000000 +local INFINITE = -1 +local HANDLE_FLAG_INHERIT = 1 +local STD_INPUT_HANDLE = -10 +local STD_ERROR_HANDLE = -12 +local ERROR_BROKEN_PIPE = 109 function os.execute(commandLine) - local si = ffi.new("STARTUPINFOA") - si.cb = ffi.sizeof(si) - si.dwFlags = STARTF_USESHOWWINDOW + local si = ffi.new("STARTUPINFOA") + si.cb = ffi.sizeof(si) + si.dwFlags = STARTF_USESHOWWINDOW si.wShowWindow = SW_HIDE - local pi = ffi.new("PROCESS_INFORMATION") + local pi = ffi.new("PROCESS_INFORMATION") if not C.CreateProcessA(nil, "cmd /C " .. commandLine, nil, nil, 0, CREATE_NO_WINDOW, nil, nil, si, pi) then return EXIT_FAILURE end C.WaitForSingleObject(pi.hProcess, INFINITE) local exitcode = ffi.new("DWORD[1]") - local ok = C.GetExitCodeProcess(pi.hProcess, exitcode) + local ok = C.GetExitCodeProcess(pi.hProcess, exitcode) C.CloseHandle(pi.hProcess) C.CloseHandle(pi.hThread) return ok and exitcode[0] or EXIT_FAILURE end -local pfile = {} -local pfile_mt = {__index = pfile} +local pfile = {} +local pfile_mt = { __index = pfile } local function checkclosed(pfile) if pfile.pi == nil then @@ -152,33 +152,39 @@ function pfile:read(n) end if type(n) == "number" then - if not fetch(function() return #self.buffer < n end) then + if not fetch(function() + return #self.buffer < n + end) then return nil end - local out = self.buffer:sub(1, n) + local out = self.buffer:sub(1, n) self.buffer = self.buffer:sub(n + 1) if out == "" then out = nil end return out elseif n == "*a" then - if not fetch(function() return true end) then + if not fetch(function() + return true + end) then return nil end - local out = self.buffer + local out = self.buffer self.buffer = "" return out elseif n == "*l" then - if not fetch(function() return not self.buffer:find("\n", nil, true) end) then + if not fetch(function() + return not self.buffer:find("\n", nil, true) + end) then return nil end local out local npos = self.buffer:find("\n", nil, true) if npos then - out = self.buffer:sub(1, npos-1) - self.buffer = self.buffer:sub(npos+1) + out = self.buffer:sub(1, npos - 1) + self.buffer = self.buffer:sub(npos + 1) else - out = self.buffer + out = self.buffer self.buffer = "" if out == "" then out = nil @@ -192,7 +198,9 @@ end function pfile:lines() checkclosed(self) - return function() return self:read("*l") end + return function() + return self:read("*l") + end end function pfile:close() @@ -201,27 +209,28 @@ function pfile:close() C.CloseHandle(self.pipe_outRd[0]) C.WaitForSingleObject(pi.hProcess, INFINITE) local res = C.CloseHandle(pi.hProcess) and C.CloseHandle(pi.hThread) - self.pi = nil + self.pi = nil return res end function io.popen(commandLine) - local sa = ffi.new("SECURITY_ATTRIBUTES", ffi.sizeof("SECURITY_ATTRIBUTES"), nil, true) + local sa = ffi.new("SECURITY_ATTRIBUTES", ffi.sizeof("SECURITY_ATTRIBUTES"), nil, true) - local pipe_outRd, pipe_outWr=ffi.new("HANDLE[1]"), ffi.new("HANDLE[1]") - if not C.CreatePipe(pipe_outRd, pipe_outWr, sa, 0) or not C.SetHandleInformation(pipe_outRd[0], HANDLE_FLAG_INHERIT, 0) then + local pipe_outRd, pipe_outWr = ffi.new("HANDLE[1]"), ffi.new("HANDLE[1]") + if not C.CreatePipe(pipe_outRd, pipe_outWr, sa, 0) or not C.SetHandleInformation(pipe_outRd[0], HANDLE_FLAG_INHERIT, + 0) then return end - local si = ffi.new("STARTUPINFOA") - si.cb = ffi.sizeof(si) - si.dwFlags = STARTF_USESHOWWINDOW + STARTF_USESTDHANDLES + local si = ffi.new("STARTUPINFOA") + si.cb = ffi.sizeof(si) + si.dwFlags = STARTF_USESHOWWINDOW + STARTF_USESTDHANDLES si.wShowWindow = SW_HIDE - si.hStdInput = C.GetStdHandle(STD_INPUT_HANDLE) - si.hStdOutput = pipe_outWr[0] - si.hStdError = C.GetStdHandle(STD_ERROR_HANDLE) + si.hStdInput = C.GetStdHandle(STD_INPUT_HANDLE) + si.hStdOutput = pipe_outWr[0] + si.hStdError = C.GetStdHandle(STD_ERROR_HANDLE) - local pi = ffi.new("PROCESS_INFORMATION") + local pi = ffi.new("PROCESS_INFORMATION") if not C.CreateProcessA(nil, "cmd /C " .. commandLine, nil, nil, 1, CREATE_NO_WINDOW, nil, nil, si, pi) then return end @@ -229,11 +238,11 @@ function io.popen(commandLine) local size = 4096 return setmetatable({ - pi = pi, - pipe_outRd = pipe_outRd, - size = size, - byteBuf = ffi.new("char[?]", size), - bytesRead = ffi.new("DWORD[1]"), - buffer = "" - }, pfile_mt) + pi = pi, + pipe_outRd = pipe_outRd, + size = size, + byteBuf = ffi.new("char[?]", size), + bytesRead = ffi.new("DWORD[1]"), + buffer = "" + }, pfile_mt) end diff --git a/mods/noita-mp/files/scripts/extensions/string_extensions.lua b/mods/noita-mp/files/scripts/extensions/stringExtensions.lua similarity index 100% rename from mods/noita-mp/files/scripts/extensions/string_extensions.lua rename to mods/noita-mp/files/scripts/extensions/stringExtensions.lua diff --git a/mods/noita-mp/files/scripts/extensions/table_extensions.lua b/mods/noita-mp/files/scripts/extensions/tableExtensions.lua similarity index 99% rename from mods/noita-mp/files/scripts/extensions/table_extensions.lua rename to mods/noita-mp/files/scripts/extensions/tableExtensions.lua index d3d2b0f5f..eb3ee52b9 100644 --- a/mods/noita-mp/files/scripts/extensions/table_extensions.lua +++ b/mods/noita-mp/files/scripts/extensions/tableExtensions.lua @@ -210,8 +210,8 @@ function table.contentToString(tbl) if not tbl or type(tbl) ~= "table" then error("'tbl' must not be nil and type of table!", 2) end - if not util then - util = require("util") + if not Utils then + Utils = require("Utils") end --Logger.trace(Logger.channels.testing, ("tbl = %s"):format(util.pformat(tbl))) diff --git a/mods/noita-mp/files/scripts/init/init_.lua b/mods/noita-mp/files/scripts/init/init_.lua index cc6cf24fb..da885eb3a 100644 --- a/mods/noita-mp/files/scripts/init/init_.lua +++ b/mods/noita-mp/files/scripts/init/init_.lua @@ -1,7 +1,6 @@ -- Init lua scripts to set necessary defaults, like lua paths, logger init and extensions print("Initialise paths, globals and extensions..") local varargs = { ... } - if varargs and #varargs > 0 then if require then print("ERROR: Do not add any arguments when running this script in-game!") @@ -13,17 +12,13 @@ else print("no 'varargs' set.") end -dofile("mods/noita-mp/files/scripts/extensions/table_extensions.lua") -dofile("mods/noita-mp/files/scripts/extensions/string_extensions.lua") +dofile("mods/noita-mp/files/scripts/extensions/tableExtensions.lua") +dofile("mods/noita-mp/files/scripts/extensions/stringExtensions.lua") dofile("mods/noita-mp/files/scripts/extensions/mathExtensions.lua") -dofile("mods/noita-mp/files/scripts/extensions/ffi_extensions.lua") +dofile("mods/noita-mp/files/scripts/extensions/ffiExtensions.lua") dofile("mods/noita-mp/files/scripts/extensions/globalExtensions.lua") - dofile("mods/noita-mp/files/scripts/init/init_package_loading.lua") dofile("mods/noita-mp/files/scripts/init/init_logger.lua") - --- We simply want to load all dependencies, when inGame and in init.lua-Context, --- and when in NoitaComponents or in unit testing!Ø require("MinaUtils") require("luaExtensions") require("NetworkCacheUtils") @@ -47,4 +42,4 @@ _G.whoAmI = function() return Client.iAm end return "UNKNOWN" -end \ No newline at end of file +end diff --git a/mods/noita-mp/files/scripts/init/init_logger.lua b/mods/noita-mp/files/scripts/init/init_logger.lua index 5d9b59463..95ed342e1 100644 --- a/mods/noita-mp/files/scripts/init/init_logger.lua +++ b/mods/noita-mp/files/scripts/init/init_logger.lua @@ -6,5 +6,5 @@ if not _G.Logger then end Logger.info(Logger.channels.initialize, "_G.Logger initialised!") else - error("ERROR: Unable to init Logger! _G.Logger is nil.", 2) + Logger.info(Logger.channels.initialize, "_G.Logger was already initialised!") end diff --git a/mods/noita-mp/files/scripts/init/init_package_loading.lua b/mods/noita-mp/files/scripts/init/init_package_loading.lua index 48c5a921b..0c2b9e5e6 100644 --- a/mods/noita-mp/files/scripts/init/init_package_loading.lua +++ b/mods/noita-mp/files/scripts/init/init_package_loading.lua @@ -7,7 +7,7 @@ function getNoitaMpRootDirectory() -- Check if we are inside of noita-mp directory. Don't forget to escape the dash! local startsAtI, endsAtI = string.find(currentDirectory, - "noita%-mp") -- https://stackoverflow.com/a/20223010/3493998 + "noita%-mp") -- https://stackoverflow.com/a/20223010/3493998 local noitaMpRootDirectory = nil if not startsAtI then error("The current directory is not inside the noita-mp directory. Please run it again somewhere inside the noita-mp directory.") @@ -35,15 +35,15 @@ package.path = package.path .. "mods\\noita-mp\\files\\scripts\\util\\?.lua;" print("package.path = " .. package.path) package.cpath = package.cpath .. ";" .. - -- [[ LuaRocks libraries ]]-- - noitaMpRootDirectory .. "\\lua_modules\\lib\\lua\\5.1\\?.dll;" .. - "mods\\noita-mp\\lua_modules\\lib\\lua\\5.1\\?.dll;" + -- [[ LuaRocks libraries ]]-- + noitaMpRootDirectory .. "\\lua_modules\\lib\\lua\\5.1\\?.dll;" .. + "mods\\noita-mp\\lua_modules\\lib\\lua\\5.1\\?.dll;" print("package.cpath = " .. package.cpath) -local fu = require("file_util") +local fu = require("FileUtils") --[[ NoitaMP additions ]] -- A list of paths to lua script modules -local paths = { +local paths = { -- [[ LuaRocks modules, running outside of noita.exe ]]-- noitaMpRootDirectory .. "/lua_modules/share/lua/5.1/{module}", noitaMpRootDirectory .. "/lua_modules/lib/lua/5.1/{module}", @@ -68,14 +68,14 @@ local paths = { } -- A list of paths to binary Lua modules -local module_paths = { +local module_paths = { "?.{extension}", "?/init.{extension}", "?/core.{extension}", } -- List of supported OS paired with binary file extension name -local extensions = { +local extensions = { Windows = "dll", Linux = "so", Mac = "dylib" @@ -83,34 +83,36 @@ local extensions = { -- os_name is a supplemental module for -- OS and CPU architecture detection -local os_name = require("os_name") +local os_name = require("os_name") --[[ NoitaMP additions ]] -package.path = default_package_path +package.path = default_package_path --[[ NoitaMP additions ]] -- A dot character represent current working directory local root_dir = "." -local current_platform, current_architecture = os_name.getOS() - -local cpaths, lpaths = {}, {} -local current_clib_extension = extensions[current_platform] --[[ NoitaMP additions ]] -_G.os_name = current_platform -_G.os_arch = current_architecture - --- https://stackoverflow.com/a/14425862/3493998 -_G.pathSeparator = tostring(package.config:sub(1, 1)) - -if _G.os_name == "Windows" then +_G.is_windows = true +_G.is_linux = false +_G.pathSeparator = tostring(package.config:sub(1, 1)) +local current_platform, current_architecture = os_name.getOS() +if current_platform == "Windows" then _G.is_windows = true -end -if _G.os_name == "Linux" then + _G.is_linux = false + _G.pathSeparator = "\\" +else + _G.is_windows = false _G.is_linux = true + _G.pathSeparator = "/" end +_G.os_name = current_platform +_G.os_arch = current_architecture + +local cpaths, lpaths = {}, {} +local current_clib_extension = extensions[current_platform] print("init_package_loading.lua | Detected OS " .. _G.os_name .. - "(" .. _G.os_arch .. ") with path separator '" .. _G.pathSeparator .. "'.") +"(" .. _G.os_arch .. ") with path separator '" .. _G.pathSeparator .. "'.") --[[ NoitaMP additions ]] if current_clib_extension then @@ -122,30 +124,30 @@ if current_clib_extension then -- make a substitution for each module file path. for _, raw_module_path in ipairs(module_paths) do local module_path = path:gsub( - "{(%w+)}", - { - module = raw_module_path - } + "{(%w+)}", + { + module = raw_module_path + } ) -- add path for binary module cpaths[#cpaths + 1] = module_path:gsub( - "{(%w+)}", - { - extension = current_clib_extension - } + "{(%w+)}", + { + extension = current_clib_extension + } ) -- add paths for platform independent lua and luac modules lpaths[#lpaths + 1] = module_path:gsub( - "{(%w+)}", - { - extension = "lua" - } + "{(%w+)}", + { + extension = "lua" + } ) lpaths[#lpaths + 1] = module_path:gsub( - "{(%w+)}", - { - extension = "luac" - } + "{(%w+)}", + { + extension = "luac" + } ) end end @@ -161,20 +163,22 @@ if current_clib_extension then if destination_path then print("destination_path was set to export LPATH and CPATH!") - local lua_path_file = fu.RemoveTrailingPathSeparator(destination_path) .. _G.pathSeparator .. "lua_path.txt" + local lua_path_file = fu.RemoveTrailingPathSeparator(destination_path) .. + _G.pathSeparator .. "lua_path.txt" local lua_path_file_content = ";" .. package.path - local lua_cpath_file = fu.RemoveTrailingPathSeparator(destination_path) .. _G.pathSeparator .. "lua_cpath.txt" + local lua_cpath_file = fu.RemoveTrailingPathSeparator(destination_path) .. + _G.pathSeparator .. "lua_cpath.txt" local lua_cpath_file_content = ";" .. package.cpath fu.WriteFile(lua_path_file, lua_path_file_content) print("init_package_loading.lua | File (" .. lua_path_file .. - ") created with content: " .. lua_path_file_content) + ") created with content: " .. lua_path_file_content) fu.WriteFile(lua_cpath_file, lua_cpath_file_content) print("init_package_loading.lua | File (" .. lua_cpath_file .. - ") created with content: " .. lua_cpath_file_content) + ") created with content: " .. lua_cpath_file_content) else print("destination_path was not set. Export LPATH and CPATH will be skipped!") end diff --git a/mods/noita-mp/files/scripts/net/Client.lua b/mods/noita-mp/files/scripts/net/Client.lua index e208c7e12..c493f03da 100644 --- a/mods/noita-mp/files/scripts/net/Client.lua +++ b/mods/noita-mp/files/scripts/net/Client.lua @@ -7,10 +7,10 @@ --- 'Imports' ---------------------------------------- local sock = require("sock") -local util = require("util") +local Utils = require("Utils") local zstandard = require("zstd") local messagePack = require("MessagePack") -local fu = require("file_util") +local fu = require("FileUtils") ---------------------------------------------------------------------------------------------------- --- Client @@ -147,7 +147,7 @@ function Client.new(sockClient) end local data = { networkMessageId, event, NetworkUtils.events.acknowledgement.ack, os.clock() } self:send(NetworkUtils.events.acknowledgement.name, data) - Logger.debug(Logger.channels.network, ("Sent ack with data = %s"):format(util.pformat(data))) + Logger.debug(Logger.channels.network, ("Sent ack with data = %s"):format(Utils.pformat(data))) CustomProfiler.stop("Client.sendAck", cpc2) end @@ -156,26 +156,26 @@ function Client.new(sockClient) ------------------------------------------------------------------------------------------------ local function onAcknowledgement(data) local cpc3 = CustomProfiler.start("Client.onAcknowledgement") - Logger.debug(Logger.channels.network, "onAcknowledgement: Acknowledgement received.", util.pformat(data)) + Logger.debug(Logger.channels.network, "onAcknowledgement: Acknowledgement received.", Utils.pformat(data)) - if util.IsEmpty(data.networkMessageId) then + if Utils.IsEmpty(data.networkMessageId) then error(("onAcknowledgement data.networkMessageId is empty: %s"):format(data.networkMessageId), 2) end if not data.networkMessageId then error(("Unable to get acknowledgement with networkMessageId = %s, data = %s, peer = %s") - :format(networkMessageId, util.pformat(data), util.pformat(self)), 2) + :format(networkMessageId, Utils.pformat(data), Utils.pformat(self)), 2) end - if util.IsEmpty(data.event) then + if Utils.IsEmpty(data.event) then error(("onAcknowledgement data.event is empty: %s"):format(data.event), 2) end - if util.IsEmpty(data.status) then + if Utils.IsEmpty(data.status) then error(("onAcknowledgement data.status is empty: %s"):format(data.status), 2) end - if util.IsEmpty(data.ackedAt) then + if Utils.IsEmpty(data.ackedAt) then error(("onAcknowledgement data.ackedAt is empty: %s"):format(data.ackedAt), 2) end @@ -201,9 +201,9 @@ function Client.new(sockClient) --- @param data number not in use atm local function onConnect(data) local cpc4 = CustomProfiler.start("Client.onConnect") - Logger.debug(Logger.channels.network, "Connected to server!", util.pformat(data)) + Logger.debug(Logger.channels.network, "Connected to server!", Utils.pformat(data)) - if util.IsEmpty(data) then + if Utils.IsEmpty(data) then error(("onConnect data is empty: %s"):format(data), 3) end @@ -213,7 +213,7 @@ function Client.new(sockClient) local nuid = localPlayerInfo.nuid -- Could be nil. Timing issue. Will be set after this. self:send(NetworkUtils.events.playerInfo.name, - { NetworkUtils.getNextNetworkMessageId(), name, guid, fu.getVersionByFile(), nuid }) + { NetworkUtils.getNextNetworkMessageId(), name, guid, fu.GetVersionByFile(), nuid }) self:send(NetworkUtils.events.needModList.name, { NetworkUtils.getNextNetworkMessageId(), nil, nil}) @@ -229,17 +229,17 @@ function Client.new(sockClient) --- @param data table data = { "name", "guid" } @see NetworkUtils.events.connect2.schema local function onConnect2(data) local cpc5 = CustomProfiler.start("Client.onConnect2") - Logger.debug(Logger.channels.network, "Another client connected.", util.pformat(data)) + Logger.debug(Logger.channels.network, "Another client connected.", Utils.pformat(data)) - if util.IsEmpty(data.networkMessageId) then + if Utils.IsEmpty(data.networkMessageId) then error(("onConnect2 data.networkMessageId is empty: %s"):format(data.networkMessageId), 3) end - if util.IsEmpty(data.name) then + if Utils.IsEmpty(data.name) then error(("onConnect2 data.name is empty: %s"):format(data.name), 3) end - if util.IsEmpty(data.guid) then + if Utils.IsEmpty(data.guid) then error(("onConnect2 data.guid is empty: %s"):format(data.guid), 3) end @@ -256,9 +256,9 @@ function Client.new(sockClient) --- @param data number data(.code) = 0 local function onDisconnect(data) local cpc6 = CustomProfiler.start("Client.onDisconnect") - Logger.debug(Logger.channels.network, "Disconnected from server!", util.pformat(data)) + Logger.debug(Logger.channels.network, "Disconnected from server!", Utils.pformat(data)) - if util.IsEmpty(data) then + if Utils.IsEmpty(data) then error(("onDisconnect data is empty: %s"):format(data), 3) end @@ -285,17 +285,17 @@ function Client.new(sockClient) --- @param data table data { "name", "guid" } @see NetworkUtils.events.disconnect2.schema local function onDisconnect2(data) local cpc7 = CustomProfiler.start("Client.onDisconnect2") - Logger.debug(Logger.channels.network, "onDisconnect2: Another client disconnected.", util.pformat(data)) + Logger.debug(Logger.channels.network, "onDisconnect2: Another client disconnected.", Utils.pformat(data)) - if util.IsEmpty(data.networkMessageId) then + if Utils.IsEmpty(data.networkMessageId) then error(("onDisconnect2 data.networkMessageId is empty: %s"):format(data.networkMessageId), 3) end - if util.IsEmpty(data.name) then + if Utils.IsEmpty(data.name) then error(("onDisconnect2 data.name is empty: %s"):format(data.name), 3) end - if util.IsEmpty(data.guid) then + if Utils.IsEmpty(data.guid) then error(("onDisconnect2 data.guid is empty: %s"):format(data.guid), 3) end @@ -314,25 +314,25 @@ function Client.new(sockClient) --- @param data table data { networkMessageId, name, guid } local function onPlayerInfo(data) local cpc8 = CustomProfiler.start("Client.onPlayerInfo") - Logger.debug(Logger.channels.network, "onPlayerInfo: Player info received.", util.pformat(data)) + Logger.debug(Logger.channels.network, "onPlayerInfo: Player info received.", Utils.pformat(data)) - if util.IsEmpty(data.networkMessageId) then + if Utils.IsEmpty(data.networkMessageId) then error(("onPlayerInfo data.networkMessageId is empty: %s"):format(data.networkMessageId), 3) end - if util.IsEmpty(data.name) then + if Utils.IsEmpty(data.name) then error(("onPlayerInfo data.name is empty: %s"):format(data.name), 3) end - if util.IsEmpty(data.guid) then + if Utils.IsEmpty(data.guid) then error(("onPlayerInfo data.guid is empty: %s"):format(data.guid), 3) end - if util.IsEmpty(data.nuid) then + if Utils.IsEmpty(data.nuid) then error(("onPlayerInfo data.nuid is empty: %s"):format(data.nuid), 3) end - if util.IsEmpty(data.version) then + if Utils.IsEmpty(data.version) then error(("onPlayerInfo data.version is empty: %s"):format(data.version), 3) end @@ -341,9 +341,9 @@ function Client.new(sockClient) ("onPlayerInfo: Clients GUID %s isn't unique! Server will fix this!"):format(self.guid)) end - if fu.getVersionByFile() ~= tostring(data.version) then + if fu.GetVersionByFile() ~= tostring(data.version) then error(("Version mismatch: NoitaMP version of Server: %s and your version: %s") - :format(data.version, fu.getVersionByFile()), 3) + :format(data.version, fu.GetVersionByFile()), 3) self:disconnect() end @@ -362,23 +362,23 @@ function Client.new(sockClient) --- @param data table data { "networkMessageId", "oldGuid", "newGuid" } local function onNewGuid(data) local cpc9 = CustomProfiler.start("Client.onNewGuid") - Logger.debug(Logger.channels.network, ("onNewGuid: New GUID from server received."):format(util.pformat(data))) + Logger.debug(Logger.channels.network, ("onNewGuid: New GUID from server received."):format(Utils.pformat(data))) - if util.IsEmpty(data.networkMessageId) then + if Utils.IsEmpty(data.networkMessageId) then error(("onNewGuid data.networkMessageId is empty: %s"):format(data.networkMessageId), 2) end - if util.IsEmpty(data.oldGuid) then + if Utils.IsEmpty(data.oldGuid) then error(("onNewGuid data.oldGuid is empty: %s"):format(data.oldGuid), 2) end - if util.IsEmpty(data.newGuid) then + if Utils.IsEmpty(data.newGuid) then error(("onNewGuid data.newGuid is empty: %s"):format(data.newGuid), 2) end if data.oldGuid == self.guid then local entityId = MinaUtils.getLocalMinaInformation().entityId - local compOwnerName, compOwnerGuid, compNuid = NetworkVscUtils.getAllVcsValuesByEntityId(entityId) + local compOwnerName, compOwnerGuid, compNuid = NetworkVscUtils.getAllVscValuesByEntityId(entityId) self.guid = data.newGuid local cpc27 = CustomProfiler.start("ModSettingSet") @@ -407,13 +407,13 @@ function Client.new(sockClient) --- @param data table data { networkMessageId, seed } local function onSeed(data) local cpc10 = CustomProfiler.start("Client.onSeed") - Logger.debug(Logger.channels.network, "onSeed: Seed from server received.", util.pformat(data)) + Logger.debug(Logger.channels.network, "onSeed: Seed from server received.", Utils.pformat(data)) - if util.IsEmpty(data.networkMessageId) then + if Utils.IsEmpty(data.networkMessageId) then error(("onSeed data.networkMessageId is empty: %s"):format(data.networkMessageId), 3) end - if util.IsEmpty(data.seed) then + if Utils.IsEmpty(data.seed) then error(("onSeed data.seed is empty: %s"):format(data.seed), 3) end @@ -424,7 +424,7 @@ function Client.new(sockClient) local localSeed = tonumber(StatsGetValue("world_seed")) if localSeed ~= serversSeed then - --util.reloadMap(serversSeed) TODO enable again, when custom map/biome isn't used anymore + --Utils.reloadMap(serversSeed) TODO enable again, when custom map/biome isn't used anymore end local localPlayerInfo = MinaUtils.getLocalMinaInformation() @@ -434,7 +434,7 @@ function Client.new(sockClient) local entityId = localPlayerInfo.entityId self:send(NetworkUtils.events.playerInfo.name, - { NetworkUtils.getNextNetworkMessageId(), name, guid, fu.getVersionByFile(), nuid }) + { NetworkUtils.getNextNetworkMessageId(), name, guid, fu.GetVersionByFile(), nuid }) if not NetworkVscUtils.hasNetworkLuaComponents(entityId) then NetworkVscUtils.addOrUpdateAllVscs(entityId, name, guid, nil) @@ -456,49 +456,49 @@ function Client.new(sockClient) --- velocity { x, y }, filename } local function onNewNuid(data) local cpc11 = CustomProfiler.start("Client.onNewNuid") - Logger.debug(Logger.channels.network, ("Received a new nuid! data = %s"):format(util.pformat(data))) + Logger.debug(Logger.channels.network, ("Received a new nuid! data = %s"):format(Utils.pformat(data))) - if util.IsEmpty(data.networkMessageId) then + if Utils.IsEmpty(data.networkMessageId) then error(("onNewNuid data.networkMessageId is empty: %s"):format(data.networkMessageId), 3) end - if util.IsEmpty(data.owner) then - error(("onNewNuid data.owner is empty: %s"):format(util.pformat(data.owner)), 3) + if Utils.IsEmpty(data.owner) then + error(("onNewNuid data.owner is empty: %s"):format(Utils.pformat(data.owner)), 3) end - if util.IsEmpty(data.localEntityId) then + if Utils.IsEmpty(data.localEntityId) then error(("onNewNuid data.localEntityId is empty: %s"):format(data.localEntityId), 3) end - if util.IsEmpty(data.newNuid) then + if Utils.IsEmpty(data.newNuid) then error(("onNewNuid data.newNuid is empty: %s"):format(data.newNuid), 3) end - if util.IsEmpty(data.x) then + if Utils.IsEmpty(data.x) then error(("onNewNuid data.x is empty: %s"):format(data.x), 3) end - if util.IsEmpty(data.y) then + if Utils.IsEmpty(data.y) then error(("onNewNuid data.y is empty: %s"):format(data.y), 3) end - if util.IsEmpty(data.rotation) then + if Utils.IsEmpty(data.rotation) then error(("onNewNuid data.rotation is empty: %s"):format(data.rotation), 3) end - if util.IsEmpty(data.velocity) then - error(("onNewNuid data.velocity is empty: %s"):format(util.pformat(data.velocity)), 3) + if Utils.IsEmpty(data.velocity) then + error(("onNewNuid data.velocity is empty: %s"):format(Utils.pformat(data.velocity)), 3) end - if util.IsEmpty(data.filename) then + if Utils.IsEmpty(data.filename) then error(("onNewNuid data.filename is empty: %s"):format(data.filename), 3) end - if util.IsEmpty(data.health) then + if Utils.IsEmpty(data.health) then error(("onNewNuid data.health is empty: %s"):format(data.health), 3) end - if util.IsEmpty(data.isPolymorphed) then + if Utils.IsEmpty(data.isPolymorphed) then error(("onNewNuid data.isPolymorphed is empty: %s"):format(data.isPolymorphed), 3) end @@ -529,41 +529,41 @@ function Client.new(sockClient) local function onEntityData(data) local cpc12 = CustomProfiler.start("Client.onEntityData") Logger.debug(Logger.channels.network, ("Received entityData for nuid = %s! data = %s") - :format(data.nuid, util.pformat(data))) + :format(data.nuid, Utils.pformat(data))) - if util.IsEmpty(data.networkMessageId) then + if Utils.IsEmpty(data.networkMessageId) then error(("onNewNuid data.networkMessageId is empty: %s"):format(data.networkMessageId), 3) end - if util.IsEmpty(data.owner) then - error(("onNewNuid data.owner is empty: %s"):format(util.pformat(data.owner)), 3) + if Utils.IsEmpty(data.owner) then + error(("onNewNuid data.owner is empty: %s"):format(Utils.pformat(data.owner)), 3) end - --if util.IsEmpty(data.localEntityId) then + --if Utils.IsEmpty(data.localEntityId) then -- error(("onNewNuid data.localEntityId is empty: %s"):format(data.localEntityId), 3) --end - if util.IsEmpty(data.nuid) then + if Utils.IsEmpty(data.nuid) then error(("onNewNuid data.nuid is empty: %s"):format(data.nuid), 3) end - if util.IsEmpty(data.x) then + if Utils.IsEmpty(data.x) then error(("onNewNuid data.x is empty: %s"):format(data.x), 3) end - if util.IsEmpty(data.y) then + if Utils.IsEmpty(data.y) then error(("onNewNuid data.y is empty: %s"):format(data.y), 3) end - if util.IsEmpty(data.rotation) then + if Utils.IsEmpty(data.rotation) then error(("onNewNuid data.rotation is empty: %s"):format(data.rotation), 3) end - if util.IsEmpty(data.velocity) then - error(("onNewNuid data.velocity is empty: %s"):format(util.pformat(data.velocity)), 3) + if Utils.IsEmpty(data.velocity) then + error(("onNewNuid data.velocity is empty: %s"):format(Utils.pformat(data.velocity)), 3) end - if util.IsEmpty(data.health) then + if Utils.IsEmpty(data.health) then error(("onNewNuid data.health is empty: %s"):format(data.health), 3) end @@ -580,7 +580,7 @@ function Client.new(sockClient) NoitaComponentUtils.setEntityData(localEntityId, x, y, rotation, velocity, health) else Logger.warn(Logger.channels.network, ("Received entityData for self.nuid = %s! data = %s") - :format(data.nuid, util.pformat(data))) + :format(data.nuid, Utils.pformat(data))) end -- sendAck(data.networkMessageId) do not send ACK for position data, network will explode @@ -592,7 +592,7 @@ function Client.new(sockClient) local deadNuids = data.deadNuids or data or {} for i = 1, #deadNuids do local deadNuid = deadNuids[i] - if util.IsEmpty(deadNuid) or deadNuid == "nil" then + if Utils.IsEmpty(deadNuid) or deadNuid == "nil" then error(("onDeadNuids deadNuid is empty: %s"):format(deadNuid), 2) else EntityUtils.destroyByNuid(self, deadNuid) @@ -638,8 +638,6 @@ function Client.new(sockClient) end local function onNeedModContent(data) - ---@module "file_util" - local fu = dofile_once("mods/noita-mp/files/scripts/util/file_util.lua") local cpc = CustomProfiler.start("Client.onNeedModContent") for _, v in ipairs(data.items) do local modName = v.name @@ -669,7 +667,7 @@ function Client.new(sockClient) -- self:on( -- "entityAlive", -- function(data) - -- logger:debug(util.pformat(data)) + -- logger:debug(Utils.pformat(data)) -- em:DespawnEntity(data.owner, data.localEntityId, data.nuid, data.isAlive) -- end @@ -678,7 +676,7 @@ function Client.new(sockClient) -- self:on( -- "entityState", -- function(data) - -- logger:debug(util.pformat(data)) + -- logger:debug(Utils.pformat(data)) -- local nc = em:GetNetworkComponent(data.owner, data.localEntityId, data.nuid) -- if nc then @@ -895,7 +893,7 @@ function Client.new(sockClient) if NetworkUtils.alreadySent(self, event, data) then Logger.debug(Logger.channels.network, ("Network message for %s for data %s already was acknowledged.") - :format(event, util.pformat(data))) + :format(event, Utils.pformat(data))) CustomProfiler.stop("Client.send", cpc19) return false end @@ -936,7 +934,7 @@ function Client.new(sockClient) } if isTestLuaContext then - print(("Sending need nuid for entity %s with data %s"):format(entityId, util.pformat(data))) + print(("Sending need nuid for entity %s with data %s"):format(entityId, Utils.pformat(data))) end self:send(NetworkUtils.events.needNuid.name, data) @@ -957,13 +955,13 @@ function Client.new(sockClient) return end - --local compOwnerName, compOwnerGuid, compNuid = NetworkVscUtils.getAllVcsValuesByEntityId(entityId) + --local compOwnerName, compOwnerGuid, compNuid = NetworkVscUtils.getAllVscValuesByEntityId(entityId) local compOwnerName, compOwnerGuid, compNuid, filename, health, rotation, velocity, x, y = NoitaComponentUtils.getEntityData(entityId) local data = { NetworkUtils.getNextNetworkMessageId(), { compOwnerName, compOwnerGuid }, compNuid, x, y, rotation, velocity, health } - if util.IsEmpty(compNuid) then + if Utils.IsEmpty(compNuid) then -- this can happen, when entity spawned on client and network is slow Logger.debug(Logger.channels.network, "Unable to send entity data, because nuid is empty.") self.sendNeedNuid(compOwnerName, compOwnerGuid, entityId) diff --git a/mods/noita-mp/files/scripts/net/Server.lua b/mods/noita-mp/files/scripts/net/Server.lua index 31129f9e6..7110fa43b 100644 --- a/mods/noita-mp/files/scripts/net/Server.lua +++ b/mods/noita-mp/files/scripts/net/Server.lua @@ -7,8 +7,8 @@ --- 'Imports' ---------------------------------------- local sock = require("sock") -local util = require("util") -local fu = require("file_util") +local Utils = require("Utils") +local fu = require("FileUtils") local zstandard = require("zstd") local messagePack = require("MessagePack") @@ -143,7 +143,7 @@ function Server.new(sockServer) end local data = { networkMessageId, event, NetworkUtils.events.acknowledgement.ack, os.clock() } self:sendToPeer(peer, NetworkUtils.events.acknowledgement.name, data) - Logger.debug(Logger.channels.network, ("Sent ack with data = %s"):format(util.pformat(data))) + Logger.debug(Logger.channels.network, ("Sent ack with data = %s"):format(Utils.pformat(data))) CustomProfiler.stop("Server.sendAck", cpc02) end @@ -152,9 +152,9 @@ function Server.new(sockServer) ------------------------------------------------------------------------------------------------ local function onAcknowledgement(data, peer) local cpc03 = CustomProfiler.start("Server.onAcknowledgement") - Logger.debug(Logger.channels.network, "onAcknowledgement: Acknowledgement received.", util.pformat(data)) + Logger.debug(Logger.channels.network, "onAcknowledgement: Acknowledgement received.", Utils.pformat(data)) - if util.IsEmpty(data.networkMessageId) then + if Utils.IsEmpty(data.networkMessageId) then error(("onAcknowledgement data.networkMessageId is empty: %s"):format(data.networkMessageId), 2) end @@ -163,15 +163,15 @@ function Server.new(sockServer) :format(networkMessageId, data, peer), 2) end - if util.IsEmpty(data.event) then + if Utils.IsEmpty(data.event) then error(("onAcknowledgement data.event is empty: %s"):format(data.event), 2) end - if util.IsEmpty(data.status) then + if Utils.IsEmpty(data.status) then error(("onAcknowledgement data.status is empty: %s"):format(data.status), 2) end - if util.IsEmpty(data.ackedAt) then + if Utils.IsEmpty(data.ackedAt) then error(("onAcknowledgement data.ackedAt is empty: %s"):format(data.ackedAt), 2) end @@ -199,13 +199,13 @@ function Server.new(sockServer) local function onConnect(data, peer) local cpc04 = CustomProfiler.start("Server.onConnect") Logger.debug(Logger.channels.network, ("Peer %s connected! data = %s") - :format(util.pformat(peer), util.pformat(data))) + :format(Utils.pformat(peer), Utils.pformat(data))) - if util.IsEmpty(peer) then + if Utils.IsEmpty(peer) then error(("onConnect peer is empty: %s"):format(peer), 3) end - if util.IsEmpty(data) then + if Utils.IsEmpty(data) then error(("onConnect data is empty: %s"):format(data), 3) end @@ -214,7 +214,7 @@ function Server.new(sockServer) local guid = localPlayerInfo.guid local entityId = localPlayerInfo.entityId local isPolymorphed = EntityUtils.isEntityPolymorphed(entityId) - local ownerName, ownerGuid, nuid = NetworkVscUtils.getAllVcsValuesByEntityId(entityId) + local ownerName, ownerGuid, nuid = NetworkVscUtils.getAllVscValuesByEntityId(entityId) if not nuid then nuid = NuidUtils.getNextNuid() @@ -228,7 +228,7 @@ function Server.new(sockServer) end self:send(peer, NetworkUtils.events.playerInfo.name, - { NetworkUtils.getNextNetworkMessageId(), name, guid, fu.getVersionByFile(), nuid }) + { NetworkUtils.getNextNetworkMessageId(), name, guid, fu.GetVersionByFile(), nuid }) self:send(peer, NetworkUtils.events.seed.name, { NetworkUtils.getNextNetworkMessageId(), StatsGetValue("world_seed") }) @@ -251,17 +251,17 @@ function Server.new(sockServer) --- @param peer table local function onDisconnect(data, peer) local cpc05 = CustomProfiler.start("Server.onDisconnect") - Logger.debug(Logger.channels.network, "Disconnected from server!", util.pformat(data)) + Logger.debug(Logger.channels.network, "Disconnected from server!", Utils.pformat(data)) - if util.IsEmpty(peer) then + if Utils.IsEmpty(peer) then error(("onConnect peer is empty: %s"):format(peer), 3) end - if util.IsEmpty(data) then + if Utils.IsEmpty(data) then error(("onDisconnect data is empty: %s"):format(data), 3) end - Logger.debug(Logger.channels.network, "Disconnected from server!", util.pformat(data)) + Logger.debug(Logger.channels.network, "Disconnected from server!", Utils.pformat(data)) -- Let the other clients know, that one client disconnected self:sendToAllBut(peer, NetworkUtils.events.disconnect2.name, { NetworkUtils.getNextNetworkMessageId(), peer.name, peer.guid, peer.nuid }) @@ -286,35 +286,35 @@ function Server.new(sockServer) --- @param data table data { networkMessageId, name, guid } local function onPlayerInfo(data, peer) local cpc06 = CustomProfiler.start("Server.onPlayerInfo") - Logger.debug(Logger.channels.network, "onPlayerInfo: Player info received.", util.pformat(data)) + Logger.debug(Logger.channels.network, "onPlayerInfo: Player info received.", Utils.pformat(data)) - if util.IsEmpty(peer) then + if Utils.IsEmpty(peer) then error(("onConnect peer is empty: %s"):format(peer), 3) end - if util.IsEmpty(data.networkMessageId) then + if Utils.IsEmpty(data.networkMessageId) then error(("onPlayerInfo data.networkMessageId is empty: %s"):format(data.networkMessageId), 3) end - if util.IsEmpty(data.name) then + if Utils.IsEmpty(data.name) then error(("onPlayerInfo data.name is empty: %s"):format(data.name), 3) end - if util.IsEmpty(data.guid) then + if Utils.IsEmpty(data.guid) then error(("onPlayerInfo data.guid is empty: %s"):format(data.guid), 3) end - --if util.IsEmpty(data.nuid) then + --if Utils.IsEmpty(data.nuid) then -- error(("onPlayerInfo data.nuid is empty: %s"):format(data.nuid), 3) --end - if util.IsEmpty(data.version) then + if Utils.IsEmpty(data.version) then error(("onPlayerInfo data.version is empty: %s"):format(data.version), 3) end - if fu.getVersionByFile() ~= tostring(data.version) then + if fu.GetVersionByFile() ~= tostring(data.version) then error(("Version mismatch: NoitaMP version of Client: %s and your version: %s") - :format(data.version, fu.getVersionByFile()), 3) + :format(data.version, fu.GetVersionByFile()), 3) peer:disconnect() end @@ -349,49 +349,49 @@ function Server.new(sockServer) local function onNeedNuid(data, peer) local cpc07 = CustomProfiler.start("Server.onNeedNuid") Logger.debug(Logger.channels.network, ("Peer %s needs a new nuid. data = %s") - :format(util.pformat(peer), util.pformat(data))) + :format(Utils.pformat(peer), Utils.pformat(data))) - if util.IsEmpty(peer) then - error(("onNeedNuid peer is empty: %s"):format(util.pformat(peer)), 3) + if Utils.IsEmpty(peer) then + error(("onNeedNuid peer is empty: %s"):format(Utils.pformat(peer)), 3) end - if util.IsEmpty(data.networkMessageId) then + if Utils.IsEmpty(data.networkMessageId) then error(("onNewNuid data.networkMessageId is empty: %s"):format(data.networkMessageId), 3) end - if util.IsEmpty(data.owner) then - error(("onNewNuid data.owner is empty: %s"):format(util.pformat(data.owner)), 3) + if Utils.IsEmpty(data.owner) then + error(("onNewNuid data.owner is empty: %s"):format(Utils.pformat(data.owner)), 3) end - if util.IsEmpty(data.localEntityId) then + if Utils.IsEmpty(data.localEntityId) then error(("onNewNuid data.localEntityId is empty: %s"):format(data.localEntityId), 3) end - if util.IsEmpty(data.x) then + if Utils.IsEmpty(data.x) then error(("onNewNuid data.x is empty: %s"):format(data.x), 3) end - if util.IsEmpty(data.y) then + if Utils.IsEmpty(data.y) then error(("onNewNuid data.y is empty: %s"):format(data.y), 3) end - if util.IsEmpty(data.rotation) then + if Utils.IsEmpty(data.rotation) then error(("onNewNuid data.rotation is empty: %s"):format(data.rotation), 3) end - if util.IsEmpty(data.velocity) then - error(("onNewNuid data.velocity is empty: %s"):format(util.pformat(data.velocity)), 3) + if Utils.IsEmpty(data.velocity) then + error(("onNewNuid data.velocity is empty: %s"):format(Utils.pformat(data.velocity)), 3) end - if util.IsEmpty(data.filename) then + if Utils.IsEmpty(data.filename) then error(("onNewNuid data.filename is empty: %s"):format(data.filename), 3) end - if util.IsEmpty(data.health) then + if Utils.IsEmpty(data.health) then error(("onNewNuid data.health is empty: %s"):format(data.health), 3) end - if util.IsEmpty(data.isPolymorphed) then + if Utils.IsEmpty(data.isPolymorphed) then error(("onNewNuid data.isPolymorphed is empty: %s"):format(data.isPolymorphed), 3) end @@ -420,18 +420,18 @@ function Server.new(sockServer) local function onLostNuid(data, peer) local cpc08 = CustomProfiler.start("Server.onLostNuid") Logger.debug(Logger.channels.network, ("Peer %s lost a nuid and ask for the entity to spawn. data = %s") - :format(util.pformat(peer), util.pformat(data))) + :format(Utils.pformat(peer), Utils.pformat(data))) - if util.IsEmpty(peer) then - error(("onLostNuid peer is empty: %s"):format(util.pformat(peer)), 3) + if Utils.IsEmpty(peer) then + error(("onLostNuid peer is empty: %s"):format(Utils.pformat(peer)), 3) end - if util.IsEmpty(data.networkMessageId) then + if Utils.IsEmpty(data.networkMessageId) then error(("onLostNuid data.networkMessageId is empty: %s"):format(data.networkMessageId), 3) end - if util.IsEmpty(data.nuid) then - error(("onLostNuid data.nuid is empty: %s"):format(util.pformat(data.nuid)), 3) + if Utils.IsEmpty(data.nuid) then + error(("onLostNuid data.nuid is empty: %s"):format(Utils.pformat(data.nuid)), 3) end local nuid, entityId = GlobalsUtils.getNuidEntityPair(data.nuid) @@ -444,7 +444,7 @@ function Server.new(sockServer) return end - --local compOwnerName, compOwnerGuid, compNuid = NetworkVscUtils.getAllVcsValuesByEntityId(entityId) + --local compOwnerName, compOwnerGuid, compNuid = NetworkVscUtils.getAllVscValuesByEntityId(entityId) local compOwnerName, compOwnerGuid, compNuid, filename, health, rotation, velocity, x, y = NoitaComponentUtils.getEntityData(entityId) local isPolymorphed = EntityUtils.isEntityPolymorphed(entityId) @@ -459,41 +459,41 @@ function Server.new(sockServer) local function onEntityData(data, peer) local cpc09 = CustomProfiler.start("Server.onEntityData") Logger.debug(Logger.channels.network, ("Received entityData for nuid = %s! data = %s") - :format(data.nuid, util.pformat(data))) + :format(data.nuid, Utils.pformat(data))) - if util.IsEmpty(data.networkMessageId) then + if Utils.IsEmpty(data.networkMessageId) then error(("onNewNuid data.networkMessageId is empty: %s"):format(data.networkMessageId), 3) end - if util.IsEmpty(data.owner) then - error(("onNewNuid data.owner is empty: %s"):format(util.pformat(data.owner)), 3) + if Utils.IsEmpty(data.owner) then + error(("onNewNuid data.owner is empty: %s"):format(Utils.pformat(data.owner)), 3) end - --if util.IsEmpty(data.localEntityId) then + --if Utils.IsEmpty(data.localEntityId) then -- error(("onNewNuid data.localEntityId is empty: %s"):format(data.localEntityId), 3) --end - if util.IsEmpty(data.nuid) then + if Utils.IsEmpty(data.nuid) then error(("onNewNuid data.nuid is empty: %s"):format(data.nuid), 3) end - if util.IsEmpty(data.x) then + if Utils.IsEmpty(data.x) then error(("onNewNuid data.x is empty: %s"):format(data.x), 3) end - if util.IsEmpty(data.y) then + if Utils.IsEmpty(data.y) then error(("onNewNuid data.y is empty: %s"):format(data.y), 3) end - if util.IsEmpty(data.rotation) then + if Utils.IsEmpty(data.rotation) then error(("onNewNuid data.rotation is empty: %s"):format(data.rotation), 3) end - if util.IsEmpty(data.velocity) then - error(("onNewNuid data.velocity is empty: %s"):format(util.pformat(data.velocity)), 3) + if Utils.IsEmpty(data.velocity) then + error(("onNewNuid data.velocity is empty: %s"):format(Utils.pformat(data.velocity)), 3) end - if util.IsEmpty(data.health) then + if Utils.IsEmpty(data.health) then error(("onNewNuid data.health is empty: %s"):format(data.health), 3) end @@ -519,7 +519,7 @@ function Server.new(sockServer) local deadNuids = data.deadNuids or data or {} for i = 1, #deadNuids do local deadNuid = deadNuids[i] - if util.IsEmpty(deadNuid) or deadNuid == "nil" then + if Utils.IsEmpty(deadNuid) or deadNuid == "nil" then error(("onDeadNuids deadNuid is empty: %s"):format(deadNuid), 2) else if peer then @@ -631,7 +631,7 @@ function Server.new(sockServer) -- Called when someone connects to the server -- self:on("connect", function(data, peer) - -- logger:debug(logger.channels.network, "Someone connected to the server:", util.pformat(data)) + -- logger:debug(logger.channels.network, "Someone connected to the server:", Utils.pformat(data)) -- local local_player_id = MinaUtils.getLocalMinaEntityId() -- local x, y, rot, scale_x, scale_y = EntityGetTransform(local_player_id) @@ -644,8 +644,8 @@ function Server.new(sockServer) -- self:on( -- "clientInfo", -- function(data, peer) - -- logger:debug(logger.channels.network, "on_clientInfo: data =", util.pformat(data)) - -- logger:debug(logger.channels.network, "on_clientInfo: peer =", util.pformat(peer)) + -- logger:debug(logger.channels.network, "on_clientInfo: data =", Utils.pformat(data)) + -- logger:debug(logger.channels.network, "on_clientInfo: peer =", Utils.pformat(peer)) -- setClientInfo(data, peer) -- end -- ) @@ -653,8 +653,8 @@ function Server.new(sockServer) -- self:on( -- "worldFilesFinished", -- function(data, peer) - -- logger:debug(logger.channels.network, "on_worldFilesFinished: data =", util.pformat(data)) - -- logger:debug(logger.channels.network, "on_worldFilesFinished: peer =", util.pformat(peer)) + -- logger:debug(logger.channels.network, "on_worldFilesFinished: data =", Utils.pformat(data)) + -- logger:debug(logger.channels.network, "on_worldFilesFinished: peer =", Utils.pformat(peer)) -- -- Send restart command -- peer:send("restart", { "Restart now!" }) -- end @@ -664,7 +664,7 @@ function Server.new(sockServer) -- self:on( -- "disconnect", -- function(data) - -- logger:debug(logger.channels.network, "on_disconnect: data =", util.pformat(data)) + -- logger:debug(logger.channels.network, "on_disconnect: data =", Utils.pformat(data)) -- end -- ) @@ -672,16 +672,16 @@ function Server.new(sockServer) -- self:on( -- "receive", -- function(data, channel, client) - -- logger:debug(logger.channels.network, "on_receive: data =", util.pformat(data)) - -- logger:debug(logger.channels.network, "on_receive: channel =", util.pformat(channel)) - -- logger:debug(logger.channels.network, "on_receive: client =", util.pformat(client)) + -- logger:debug(logger.channels.network, "on_receive: data =", Utils.pformat(data)) + -- logger:debug(logger.channels.network, "on_receive: channel =", Utils.pformat(channel)) + -- logger:debug(logger.channels.network, "on_receive: client =", Utils.pformat(client)) -- end -- ) -- self:on( -- "needNuid", -- function(data) - -- logger:debug(logger.channels.network, "%s (%s) needs a new nuid.", data.owner.name, data.owner.guid, util.pformat(data)) + -- logger:debug(logger.channels.network, "%s (%s) needs a new nuid.", data.owner.name, data.owner.guid, Utils.pformat(data)) -- local new_nuid = NuidUtils.getNextNuid() -- -- tell the clients that there is a new entity, they have to spawn, besides the client, who sent the request @@ -694,7 +694,7 @@ function Server.new(sockServer) -- self:on( -- "newNuid", -- function(data) - -- logger:debug(logger.channels.network, util.pformat(data)) + -- logger:debug(logger.channels.network, Utils.pformat(data)) -- if self.guid == data.owner.guid then -- logger:debug(logger.channels.network, @@ -711,7 +711,7 @@ function Server.new(sockServer) -- self:on( -- "entityAlive", -- function(data) - -- logger:debug(logger.channels.network, util.pformat(data)) + -- logger:debug(logger.channels.network, Utils.pformat(data)) -- self:sendToAll2("entityAlive", data) -- em:DespawnEntity(data.owner, data.localEntityId, data.nuid, data.isAlive) @@ -721,7 +721,7 @@ function Server.new(sockServer) -- self:on( -- "entityState", -- function(data) - -- logger:debug(logger.channels.network, util.pformat(data)) + -- logger:debug(logger.channels.network, Utils.pformat(data)) -- local nc = em:GetNetworkComponent(data.owner, data.localEntityId, data.nuid) -- if nc then @@ -842,7 +842,7 @@ function Server.new(sockServer) if NetworkUtils.alreadySent(peer, event, data) then Logger.debug(Logger.channels.network, ("Network message for %s for data %s already was acknowledged.") - :format(event, util.pformat(data))) + :format(event, Utils.pformat(data))) CustomProfiler.stop("Server.send", cpc022) return false end @@ -862,14 +862,14 @@ function Server.new(sockServer) function self:sendToAll(event, data) local cpc023 = CustomProfiler.start("Server.sendToAll") local sent = false - if util.IsEmpty(self.clients) then + if Utils.IsEmpty(self.clients) then Logger.trace(Logger.channels.testing, - ("Unable to send anything, when there are no clients %s!"):format(util.pformat(self.clients))) + ("Unable to send anything, when there are no clients %s!"):format(Utils.pformat(self.clients))) return sent end for i = 1, #self.clients do Logger.trace(Logger.channels.testing, - ("Sending event '%s' with data '%s' to client.name '%s'!"):format(event, util.pformat(data), + ("Sending event '%s' with data '%s' to client.name '%s'!"):format(event, Utils.pformat(data), self.clients[i].name)) sent = self:send(self.clients[i], event, data) end @@ -1020,13 +1020,13 @@ function Server.new(sockServer) return end - --local compOwnerName, compOwnerGuid, compNuid = NetworkVscUtils.getAllVcsValuesByEntityId(entityId) + --local compOwnerName, compOwnerGuid, compNuid = NetworkVscUtils.getAllVscValuesByEntityId(entityId) local compOwnerName, compOwnerGuid, compNuid, filename, health, rotation, velocity, x, y = NoitaComponentUtils.getEntityData(entityId) local data = { NetworkUtils.getNextNetworkMessageId(), { compOwnerName, compOwnerGuid }, compNuid, x, y, rotation, velocity, health } - if util.IsEmpty(compNuid) then + if Utils.IsEmpty(compNuid) then ---- nuid must not be empty, when Server! --logger:error(logger.channels.network, "Unable to send entity data, because nuid is empty.") --return diff --git a/mods/noita-mp/files/scripts/noita-components/lua_component_enabler.lua b/mods/noita-mp/files/scripts/noita-components/lua_component_enabler.lua index dd88e19e4..295ce6dd6 100644 --- a/mods/noita-mp/files/scripts/noita-components/lua_component_enabler.lua +++ b/mods/noita-mp/files/scripts/noita-components/lua_component_enabler.lua @@ -2,14 +2,9 @@ dofile_once("mods/noita-mp/files/scripts/init/init_logger.lua") EntityUtils = dofile_once("mods/noita-mp/files/scripts/util/EntityUtils.lua") NetworkVscUtils = dofile_once("mods/noita-mp/files/scripts/util/NetworkVscUtils.lua") - function enabled_changed(entityId, isEnabled) - if not EntityUtils.isEntityAlive(entityId) then - return - end - + if not EntityUtils.isEntityAlive(entityId) then return end if isEnabled == true then - if NetworkVscUtils.isNetworkEntityByNuidVsc(entityId) then NetworkVscUtils.enableComponents(entityId) end diff --git a/mods/noita-mp/files/scripts/noita-components/name_tags.lua b/mods/noita-mp/files/scripts/noita-components/name_tags.lua index 1488e205e..4684f0890 100644 --- a/mods/noita-mp/files/scripts/noita-components/name_tags.lua +++ b/mods/noita-mp/files/scripts/noita-components/name_tags.lua @@ -6,35 +6,20 @@ function PlayerNameFunction(entity_id, playerName) GuiStartFrame(gui) local screenWidth, screenHeight = GuiGetScreenDimensions(gui) screenWidth, screenHeight = screenWidth / 2, screenHeight / 2 + local x, y = EntityGetTransform(entity_id) + local camX, camY = GameGetCameraPos() - local x, y = EntityGetTransform(entity_id) - - local function getEntityPositionOnScreen() - local camX, camY = GameGetCameraPos() - return screenWidth + ((x - camX) * 1.5), screenHeight + ((y - camY) * 1.5) - end - - local entityX, entityY = getEntityPositionOnScreen() - local playerNameLength = string.len(playerName) - local playerNameMid = entityX - (playerNameLength * 2) - - GuiText(gui, playerNameMid, entityY, playerName) + GuiText(gui, ((screenWidth + ((x - camX) * 1.5)) - (string.len(playerName) * 2)), + (screenHeight + ((y - camY) * 1.5)), playerName) end local entityId = GetUpdatedEntityID() - -if not EntityUtils.isEntityAlive(entityId) then - return -end - +if not EntityUtils.isEntityAlive(entityId) then return end name = name or nil - if not name then local vsc = EntityGetComponentIncludingDisabled(entityId, "VariableStorageComponent") or {} for i = 1, #vsc do - local variable_storage_component_name = ComponentGetValue2(vsc[i], "name") or nil - if variable_storage_component_name == "noita-mp.nc_owner.name" then - -- see NetworkComponent.component_name_owner_username = "noita-mp.nc_owner.username" + if ComponentGetValue2(vsc[i], "name") == "noita-mp.nc_owner.name" then name = ComponentGetValue2(vsc[i], "value_string") end end @@ -42,4 +27,4 @@ end if name then PlayerNameFunction(entityId, name) -end +end \ No newline at end of file diff --git a/mods/noita-mp/files/scripts/noita-components/nuid_debug.lua b/mods/noita-mp/files/scripts/noita-components/nuid_debug.lua index 5979f7c60..2f0c39cb9 100644 --- a/mods/noita-mp/files/scripts/noita-components/nuid_debug.lua +++ b/mods/noita-mp/files/scripts/noita-components/nuid_debug.lua @@ -1,34 +1,19 @@ dofile_once("mods/noita-mp/files/scripts/init/init_logger.lua") -dofile_once("mods/noita-mp/files/scripts/extensions/table_extensions.lua") +dofile_once("mods/noita-mp/files/scripts/extensions/tableExtensions.lua") +dofile_once("mods/noita-mp/files/scripts/extensions/mathExtensions.lua") EntityUtils = dofile_once("mods/noita-mp/files/scripts/util/EntityUtils.lua") NetworkVscUtils = dofile_once("mods/noita-mp/files/scripts/util/NetworkVscUtils.lua") NoitaComponentUtils = dofile_once("mods/noita-mp/files/scripts/util/NoitaComponentUtils.lua") - -function math.sign(v) - return (v >= 0 and 1) or -1 -end - -function math.round(v, bracket) - bracket = bracket or 1 - return math.floor(v / bracket + math.sign(v) * 0.5) * bracket -end - if ModSettingGet("noita-mp.toggle_debug") then - local entityId = GetUpdatedEntityID() - - if not EntityUtils.isEntityAlive(entityId) then - return - end + if not EntityUtils.isEntityAlive(entityId) then return end gui = gui or GuiCreate() GuiStartFrame(gui) - - local screenWidth, screenHeight = GuiGetScreenDimensions(gui) - screenWidth, screenHeight = screenWidth / 2, screenHeight / 2 + local screenWidth, screenHeight = GuiGetScreenDimensions(gui) + screenWidth, screenHeight = screenWidth / 2, screenHeight / 2 local compOwnerName, compOwnerGuid, compNuid, filename, health, rotation, velocity, x, y = NoitaComponentUtils.getEntityData(entityId) - local function getEntityPositionOnScreen() local camX, camY = GameGetCameraPos() return screenWidth + ((x - camX) * 1.5), screenHeight + ((y - camY) * 1.5) @@ -36,20 +21,21 @@ if ModSettingGet("noita-mp.toggle_debug") then local data = { owner = compOwnerName, - --guid = compOwnerGuid, + --guid = compOwnerGuid, nuid = compNuid, filename = filename, healthCurrent = health.current, healthMax = health.max, - --rotation = rotation, + --rotation = rotation, vX = velocity.x, vY = velocity.y, x = x, y = y } - table.setNoitaMpDefaultMetaMethods(data, "kv") + table.setNoitaMpDefaultMetaMethods(data, "kv") local i = 0 + for name, value in pairs(data) do local entityX, entityY = getEntityPositionOnScreen() local text = ("%s: %s"):format(name, value) @@ -58,6 +44,5 @@ if ModSettingGet("noita-mp.toggle_debug") then GuiText(gui, textMid, entityY + (i * 6), text) i = i + 1 end - data = nil end diff --git a/mods/noita-mp/files/scripts/noita-components/nuid_updater.lua b/mods/noita-mp/files/scripts/noita-components/nuid_updater.lua index 3e017a0db..d6d1db74a 100644 --- a/mods/noita-mp/files/scripts/noita-components/nuid_updater.lua +++ b/mods/noita-mp/files/scripts/noita-components/nuid_updater.lua @@ -1,37 +1,28 @@ dofile_once("mods/noita-mp/files/scripts/init/init_logger.lua") -dofile_once("mods/noita-mp/files/scripts/extensions/string_extensions.lua") +dofile_once("mods/noita-mp/files/scripts/extensions/stringExtensions.lua") EntityUtils = dofile_once("mods/noita-mp/files/scripts/util/EntityUtils.lua") NetworkVscUtils = dofile_once("mods/noita-mp/files/scripts/util/NetworkVscUtils.lua") GlobalsUtils = dofile_once("mods/noita-mp/files/scripts/util/GlobalsUtils.lua") +local executeOnAdded = GetValueBool("executeOnAdded", 1) -local executeOnAdded = GetValueBool("executeOnAdded", true) - ---#region local functions - ---#endregion - ---#region executeOnAdded = added() and executeOnRemove = remove() - -local function added() +if executeOnAdded then Logger.debug(Logger.channels.nuid, "nuid_updater.lua added..") local currentEntityId = GetUpdatedEntityID() - if not EntityUtils.isEntityAlive(currentEntityId) then - return - end - local ownerName, ownerGuid, nuid = NetworkVscUtils.getAllVcsValuesByEntityId(currentEntityId) + if not EntityUtils.isEntityAlive(currentEntityId) then return end + local ownerName, ownerGuid, nuid = NetworkVscUtils.getAllVscValuesByEntityId(currentEntityId) local globalsNuid, globalsEntityId = GlobalsUtils.getNuidEntityPair(nuid) - if currentEntityId ~= globalsEntityId then GlobalsUtils.setNuid(nuid, currentEntityId) Logger.debug(Logger.channels.nuid, ("nuid in noitas global storage was set: nuid = %s and entity_id = %s") - :format(nuid, currentEntityId)) + :format(nuid, currentEntityId)) end + SetValueBool("executeOnAdded", 0) end -local function remove() +if not executeOnAdded then Logger.debug(Logger.channels.nuid, "nuid_updater.lua remove..") local currentEntityId = GetUpdatedEntityID() - local ownerName, ownerGuid, nuid = NetworkVscUtils.getAllVcsValuesByEntityId(currentEntityId) + local ownerName, ownerGuid, nuid = NetworkVscUtils.getAllVscValuesByEntityId(currentEntityId) local globalsNuid, globalsEntityId = GlobalsUtils.getNuidEntityPair(nuid) if not globalsEntityId then @@ -41,24 +32,6 @@ local function remove() GlobalsUtils.setNuid(nuid, tonumber(currentEntityId * -1)) GlobalsUtils.setDeadNuid(nuid) Logger.debug(Logger.channels.nuid, - ("Entity (%s) was killed and nuid (%s) in noitas global storage was updated: old=%s and new=-%s") - :format(currentEntityId, nuid, globalsEntityId, tonumber(globalsEntityId * -1))) -end - ---#endregion - - ---#region Decision maker if executed on added or remove - -if executeOnAdded then - -- this was executed on added - added() - SetValueBool("executeOnAdded", false) + ("Entity (%s) was killed and nuid (%s) in noitas global storage was updated: old=%s and new=-%s") + :format(currentEntityId, nuid, globalsEntityId, tonumber(globalsEntityId * -1))) end - -if not executeOnAdded then - -- this was executed on remove - remove() -end - ---#endregion diff --git a/mods/noita-mp/files/scripts/util/CustomProfiler.lua b/mods/noita-mp/files/scripts/util/CustomProfiler.lua index 7e6f36788..2dfea10aa 100644 --- a/mods/noita-mp/files/scripts/util/CustomProfiler.lua +++ b/mods/noita-mp/files/scripts/util/CustomProfiler.lua @@ -9,8 +9,8 @@ local json = require("dkjson") local plotly = require("plotly") -local util = require("util") -local fu = require("file_util") +local Utils = require("Utils") +local fu = require("FileUtils") ---@class CustomProfiler CustomProfiler = {} @@ -20,7 +20,7 @@ CustomProfiler.threshold = 16.5 --ms = 60.60 fps CustomProfiler.ceiling = 1001 -- ms CustomProfiler.maxEntries = 25 -- entries per trace CustomProfiler.reportDirectory = ("%s%sNoitaMP-Reports%s%s") - :format(fu.getDesktopDirectory(), pathSeparator, pathSeparator, os.date("%Y-%m-%d_%H-%M-%S", os.time())) + :format(fu.GetDesktopDirectory(), pathSeparator, pathSeparator, os.date("%Y-%m-%d_%H-%M-%S", os.time())) CustomProfiler.reportFilename = "report.html" CustomProfiler.reportJsonFilenamePattern = "%s.json" @@ -83,7 +83,7 @@ function CustomProfiler.stop(functionName, customProfilerCounter) return 0 end - if util.IsEmpty(CustomProfiler.reportCache) then + if Utils.IsEmpty(CustomProfiler.reportCache) then return end @@ -147,7 +147,7 @@ function CustomProfiler.stop(functionName, customProfilerCounter) CustomProfiler.reportCache[functionName]["size"] and CustomProfiler.reportCache[functionName]["size"] >= CustomProfiler.maxEntries then - if not fu.exists(CustomProfiler.reportDirectory) then + if not fu.Exists(CustomProfiler.reportDirectory) then fu.MkDir(CustomProfiler.reportDirectory) end diff --git a/mods/noita-mp/files/scripts/util/EntityUtils.lua b/mods/noita-mp/files/scripts/util/EntityUtils.lua index b4e50ed9b..cb6664201 100644 --- a/mods/noita-mp/files/scripts/util/EntityUtils.lua +++ b/mods/noita-mp/files/scripts/util/EntityUtils.lua @@ -14,11 +14,11 @@ dofile("mods/noita-mp/config.lua") --- This is done by the following code: ------------------------------------------------------------------------------------------------------------------------ if require then - util = require("util") + Utils = require("Utils") else -- Fix stupid Noita sandbox issue. Noita Components does not have access to require. - if not util then - util = dofile("mods/noita-mp/files/scripts/util/util.lua") + if not Utils then + Utils = dofile("mods/noita-mp/files/scripts/util/Utils.lua") end if not EntityCache then @@ -198,7 +198,7 @@ function EntityUtils.isRemoteMinae(entityId) local client = clients[i] local clientsNuid = client.nuid local nuidRemote, entityIdRemote = GlobalsUtils.getNuidEntityPair(clientsNuid) - if not util.IsEmpty(entityIdRemote) and entityIdRemote == entityId then + if not Utils.IsEmpty(entityIdRemote) and entityIdRemote == entityId then CustomProfiler.stop("EntityUtils.isRemoteMinae", cpc) return true end @@ -213,7 +213,7 @@ function EntityUtils.isRemoteMinae(entityId) local client = Client.otherClients[i] local clientsNuid = client.nuid local nuidRemote, entityIdRemote = GlobalsUtils.getNuidEntityPair(clientsNuid) - if not util.IsEmpty(entityIdRemote) and entityIdRemote == entityId then + if not Utils.IsEmpty(entityIdRemote) and entityIdRemote == entityId then CustomProfiler.stop("EntityUtils.isRemoteMinae", cpc) return true end @@ -260,7 +260,7 @@ function EntityUtils.processAndSyncEntityNetworking() otherwise nuid isn't set when extracting parents. ]]-- for i = 1, #entityIds do local childEntityIds = EntityGetAllChildren(entityIds[i]) - if not util.IsEmpty(childEntityIds) then + if not Utils.IsEmpty(childEntityIds) then table.insertAllButNotDuplicates(entityIds, childEntityIds) end end @@ -479,7 +479,7 @@ function EntityUtils.spawnEntity(owner, nuid, x, y, rotation, velocity, filename -- double check, if there is already an entity with this NUID and return the entity_id if EntityUtils.isEntityAlive(localEntityId) and NetworkVscUtils.hasNetworkLuaComponents(localEntityId) then - local ownerNameByVsc, ownerGuidByVsc, nuidByVsc = NetworkVscUtils.getAllVcsValuesByEntityId(localEntityId) + local ownerNameByVsc, ownerGuidByVsc, nuidByVsc = NetworkVscUtils.getAllVscValuesByEntityId(localEntityId) -- if guid is not equal, but nuid is the same, then something is broken for sure! if ownerGuidByVsc ~= remoteGuid and nuidByVsc == nuid then error(("Trying to spawn entity(%s) locally, but owner does not match: remoteOwner(%s) ~= localOwner(%s). remoteNuid(%s) ~= localNuid(%s)") @@ -536,11 +536,11 @@ function EntityUtils.destroyByNuid(peer, nuid) local cpc = CustomProfiler.start("EntityUtils.destroyByNuid") if not peer or type(peer) ~= "table" then - error(("EntityUtils.destroyByNuid: peer is not a table: %s"):format(util.pformat(peer)), 2) + error(("EntityUtils.destroyByNuid: peer is not a table: %s"):format(Utils.pformat(peer)), 2) end if not nuid then - error(("EntityUtils.destroyByNuid: nuid must not be nil: %s"):format(util.pformat(nuid)), 2) + error(("EntityUtils.destroyByNuid: nuid must not be nil: %s"):format(Utils.pformat(nuid)), 2) end if type(nuid) ~= "number" then diff --git a/mods/noita-mp/files/scripts/util/file_util.lua b/mods/noita-mp/files/scripts/util/FileUtils.lua similarity index 64% rename from mods/noita-mp/files/scripts/util/file_util.lua rename to mods/noita-mp/files/scripts/util/FileUtils.lua index 850d456f8..e3555c51d 100644 --- a/mods/noita-mp/files/scripts/util/file_util.lua +++ b/mods/noita-mp/files/scripts/util/FileUtils.lua @@ -1,23 +1,21 @@ -local fu = {} -local ffi = require("ffi") -local watcher = require("watcher") -local lfs = require("lfs") -local json = require("json") -local util = require("util") - ------------------------------------------------------------------------------------------------------------------------ ---- Version ------------------------------------------------------------------------------------------------------------------------ -function fu.getVersionByFile() - local modsPath = fu.GetAbsoluteDirectoryPathOfNoitaMP() +---@class FileUtils +local FileUtils = {} +local ffi = require("ffi") +local watcher = require("watcher") +local lfs = require("lfs") +local json = require("json") +local Utils = require("Utils") + +--- @return string +function FileUtils.GetVersionByFile() + local modsPath = FileUtils.GetAbsoluteDirectoryPathOfNoitaMP() local versionAbsFilePath = ("%s%s.version"):format(modsPath, pathSeparator) - local content = fu.ReadFile(versionAbsFilePath, "*l") - if not content or util.IsEmpty(content) then + local content = FileUtils.ReadFile(versionAbsFilePath, "*l") + if not content or Utils.IsEmpty(content) then error(("Unable to read NoitaMP version. Check if '%s' exists!") - :format(fu.GetAbsolutePathOfNoitaRootDirectory() + "/.version"), 2) + :format(FileUtils.GetAbsolutePathOfNoitaRootDirectory() + "/.version"), 2) end - local jsonTable = json.decode(content) - local version = jsonTable.version + local version = json.decode(content).version Logger.info(Logger.channels.initialize, ("NoitaMP %s"):format(version)) return version end @@ -30,33 +28,27 @@ end --- Error if path is not a string. --- @param path string --- @return string path -function fu.ReplacePathSeparator(path) - if type(path) ~= "string" then - error("path is not a string") - end - if _G.is_windows then - --logger:debug("file_util.lua | windows detected replace / with \\") - path = string.gsub(path, "/", "\\") - elseif _G.is_linux then - --logger:debug("file_util.lua | unix detected replace \\ with /") - path = string.gsub(path, "\\", "/") - else +function FileUtils.ReplacePathSeparator(path) + if type(path) == "string" then + if (_G.is_windows) then + ---@diagnostic disable-next-line: redundant-return-value + return path:gsub("/", "\\") + elseif (_G.is_linux) then + ---@diagnostic disable-next-line: redundant-return-value + return path:gsub("\\", "/") + end error( - ("file_util.lua | Unable to detect OS(%s[%s]), therefore not able to replace path separator!"):format( - _G.os_name, - _G.os_arch - ), - 2 - ) + ("Unable to detect OS(%s[%s]), therefore not able to replace path separator!"):format(_G.os_name, _G.os_arch), + 2) end - return path + error("path is not a string", 2) end --- Removes trailing path separator in a string: \persistent\flags\ -> \persistent\flags. --- Error if path is not a string. --- @param path string any string, i.e. \persistent\flags\ --- @return string path \persistent\flags -function fu.RemoveTrailingPathSeparator(path) +function FileUtils.RemoveTrailingPathSeparator(path) if type(path) ~= "string" then error("path is not a string") end @@ -69,12 +61,8 @@ end ----------------------------------------------------------------------------------------------------------------------- --- eNet specific commands ----------------------------------------------------------------------------------------------------------------------- -function fu.getPidOfRunningEnetHostByPort() - --if _G.whoAmI() == _G.Client.iAm then - -- error("Makes no sense to get PID of eNet, when client!", 2) - -- return - --end - +--- @return number? +function FileUtils.GetPidOfRunningEnetHostByPort() local command = nil if _G.is_windows then command = ('netstat -abon | find /i "%s"'):format(_G.Server:getPort()) @@ -91,7 +79,7 @@ function fu.getPidOfRunningEnetHostByPort() return tonumber(pid) end -function fu.killProcess(pid) +function FileUtils.KillProcess(pid) local command = nil if _G.is_windows then command = ('taskkill /PID %s /F'):format(pid) @@ -107,40 +95,34 @@ end ---------------------------------------------------------------------------------------------------- local noitaRootDirectory = nil --- Sets root directory of noita.exe, i.e. C:\Program Files (x86)\Steam\steamapps\common\Noita -function fu.SetAbsolutePathOfNoitaRootDirectory() +function FileUtils.SetAbsolutePathOfNoitaRootDirectory() if _G.is_windows then noitaRootDirectory = assert(io.popen("cd"):read("*l"), - "Unable to run windows command 'cd' to get Noitas root directory!") + "Unable to run windows command 'cd' to get Noitas root directory!") elseif _G.is_linux then noitaRootDirectory = assert(io.popen("pwd"):read("*l"), - "Unable to run ubuntu command 'pwd' to get Noitas root directory!") + "Unable to run ubuntu command 'pwd' to get Noitas root directory!") else - error( - ("file_util.lua | Unable to detect OS(%s[%s]), therefore not able to replace path separator!"):format( - _G.os_name, - _G.os_arch - ), - 2 - ) + error(("FileUtils.lua | Unable to detect OS(%s[%s]), therefore not able to replace path separator!") + :format(_G.os_name, _G.os_arch), 2) end - - noitaRootDirectory = fu.ReplacePathSeparator(noitaRootDirectory) - + noitaRootDirectory = FileUtils.ReplacePathSeparator(noitaRootDirectory) if isTestLuaContext then Logger.trace(Logger.channels.testing, - ("Absolute path of Noitas root directory set to %s, but we need to fix path! Removing \\mods\\noita-mp.") - :format(noitaRootDirectory)) + ("Absolute path of Noitas root directory set to %s, but we need to fix path! Removing \\mods\\noita-mp.") + :format(noitaRootDirectory)) local i, _ = string.find(noitaRootDirectory, "mods") noitaRootDirectory = string.sub(noitaRootDirectory, 0, i - 1) Logger.trace(Logger.channels.testing, - ("NEW absolute path of Noitas root directory set to %s.") - :format(noitaRootDirectory)) + ("NEW absolute path of Noitas root directory set to %s.") + :format(noitaRootDirectory)) end end -function fu.GetAbsolutePathOfNoitaRootDirectory() +---@return string +function FileUtils.GetAbsolutePathOfNoitaRootDirectory() if not noitaRootDirectory then - fu.SetAbsolutePathOfNoitaRootDirectory() + FileUtils.SetAbsolutePathOfNoitaRootDirectory() end return noitaRootDirectory end @@ -153,7 +135,7 @@ end --- If DebugGetIsDevBuild() then Noitas installation path is returned: 'C:\Program Files (x86)\Steam\steamapps\common\Noita' --- otherwise it will return: '%appdata%\..\LocalLow\Nolla_Games_Noita' on windows --- @return string save06_parent_directory_path string of absolute path to '..\Noita' or '..\Nolla_Games_Noita' -function fu.GetAbsoluteDirectoryPathOfParentSave() +function FileUtils.GetAbsoluteDirectoryPathOfParentSave() local file = nil local command = nil local find_directory_name = nil @@ -178,7 +160,7 @@ function fu.GetAbsoluteDirectoryPathOfParentSave() local line = "" while line ~= nil do line = file:read("*l") - --logger:debug("file_util.lua | GetAbsoluteDirectoryPathOfParentSave line = " .. line) + --logger:debug("FileUtils.lua | GetAbsoluteDirectoryPathOfParentSave line = " .. line) if string.find(line, find_directory_name) then save06_parent_directory_path = line break @@ -188,73 +170,73 @@ function fu.GetAbsoluteDirectoryPathOfParentSave() if save06_parent_directory_path == nil or save06_parent_directory_path == "" then GamePrintImportant( - "Unable to find world files", - "Do yourself a favour and save&quit the game and start it again!", "" + "Unable to find world files", + "Do yourself a favour and save&quit the game and start it again!", "" ) end - save06_parent_directory_path = fu.ReplacePathSeparator(save06_parent_directory_path) + save06_parent_directory_path = FileUtils.ReplacePathSeparator(save06_parent_directory_path) return save06_parent_directory_path end --- Returns fullpath of save06 directory on devBuild or release --- @return string directory_path_of_save06 : noita installation path\save06 or %appdata%\..\LocalLow\Nolla_Games_Noita\save06 on windows and unknown for unix systems -function fu.GetAbsoluteDirectoryPathOfSave06() - local directory_path_of_save06 = fu.GetAbsoluteDirectoryPathOfParentSave() .. _G.pathSeparator .. "save06" +function FileUtils.GetAbsoluteDirectoryPathOfSave06() + local directory_path_of_save06 = FileUtils.GetAbsoluteDirectoryPathOfParentSave() .. _G.pathSeparator .. "save06" return directory_path_of_save06 end --- Returns the ABSOLUTE path of the mods folder. --- If fu.GetAbsolutePathOfNoitaRootDirectory() is not set yet, then it will be --- @return string fu.GetAbsolutePathOfNoitaRootDirectory() .. "/mods/noita-mp" -function fu.GetAbsoluteDirectoryPathOfNoitaMP() - if not fu.GetAbsolutePathOfNoitaRootDirectory() then - fu.SetAbsolutePathOfNoitaRootDirectory() +function FileUtils.GetAbsoluteDirectoryPathOfNoitaMP() + if not FileUtils.GetAbsolutePathOfNoitaRootDirectory() then + FileUtils.SetAbsolutePathOfNoitaRootDirectory() end - local p = fu.GetAbsolutePathOfNoitaRootDirectory() .. "/mods/noita-mp" - p = fu.ReplacePathSeparator(p) + local p = FileUtils.GetAbsolutePathOfNoitaRootDirectory() .. "/mods/noita-mp" + p = FileUtils.ReplacePathSeparator(p) return p end --- Returns the RELATIVE path of the mods folder. --- @return string "mods/noita-mp" -function fu.GetRelativeDirectoryPathOfNoitaMP() +function FileUtils.GetRelativeDirectoryPathOfNoitaMP() local p = "mods/noita-mp" - p = fu.ReplacePathSeparator(p) + p = FileUtils.ReplacePathSeparator(p) return p end --- Returns the RELATIVE path of the library folder required for this mod. --- @return string "/mods/noita-mp/files/libs" -function fu.GetRelativeDirectoryPathOfRequiredLibs() +function FileUtils.GetRelativeDirectoryPathOfRequiredLibs() local p = "mods/noita-mp/files/libs" - p = fu.ReplacePathSeparator(p) + p = FileUtils.ReplacePathSeparator(p) return p end --- Returns the ABSOLUTE path of the library folder required for this mod. --- If fu.GetAbsolutePathOfNoitaRootDirectory() is not set yet, then it will be --- @return string fu.GetAbsolutePathOfNoitaRootDirectory() .. "/mods/noita-mp/files/libs" -function fu.GetAbsoluteDirectoryPathOfRequiredLibs() - if not fu.GetAbsolutePathOfNoitaRootDirectory() then - fu.SetAbsolutePathOfNoitaRootDirectory() +function FileUtils.GetAbsoluteDirectoryPathOfRequiredLibs() + if not FileUtils.GetAbsolutePathOfNoitaRootDirectory() then + FileUtils.SetAbsolutePathOfNoitaRootDirectory() end - local p = fu.GetAbsolutePathOfNoitaRootDirectory() .. "/mods/noita-mp/files/libs" - p = fu.ReplacePathSeparator(p) + local p = FileUtils.GetAbsolutePathOfNoitaRootDirectory() .. "/mods/noita-mp/files/libs" + p = FileUtils.ReplacePathSeparator(p) return p end --- There is a world_state.xml per each saveSlot directory, which contains Globals. Nuid are stored in Globals. --- @param saveSlotAbsDirectoryPath string Absolute directory path to the current selected save slot. --- @return string absPath world_state.xml absolute file path -function fu.GetAbsDirPathOfWorldStateXml(saveSlotAbsDirectoryPath) +function FileUtils.GetAbsDirPathOfWorldStateXml(saveSlotAbsDirectoryPath) return ("%s%s%s"):format(saveSlotAbsDirectoryPath, pathSeparator, "world_state.xml") end --- see _G.saveSlotMeta ---@return table -function fu.getLastModifiedSaveSlots() - local save0 = fu.GetAbsoluteDirectoryPathOfParentSave() .. pathSeparator .. "save0" +function FileUtils.GetLastModifiedSaveSlots() + local save0 = FileUtils.GetAbsoluteDirectoryPathOfParentSave() .. pathSeparator .. "save0" local saveSlotLastModified = {} for i = 0, 6, 1 do @@ -263,7 +245,7 @@ function fu.getLastModifiedSaveSlots() watcher(save0X, function(lastModified) if lastModified > 0 then Logger.debug(Logger.channels.initialize, - ("SaveSlot(%s) directory was last modified at %s."):format("save0" .. i, lastModified)) + ("SaveSlot(%s) directory was last modified at %s."):format("save0" .. i, lastModified)) table.insert(saveSlotLastModified, { dir = save0X, lastModified = lastModified, slot = i }) end end) @@ -273,8 +255,8 @@ end --- Returns absolute path of NoitaMP settings directory, --- @return string absPath i.e. "C:\Program Files (x86)\Steam\steamapps\common\Noita\mods\noita-mp\settings" -function fu.getAbsolutePathOfNoitaMpSettingsDirectory() - return fu.GetAbsoluteDirectoryPathOfNoitaMP() .. pathSeparator .. "settings" +function FileUtils.GetAbsolutePathOfNoitaMpSettingsDirectory() + return FileUtils.GetAbsoluteDirectoryPathOfNoitaMP() .. pathSeparator .. "settings" end ---------------------------------------------------------------------------------------------------- @@ -284,7 +266,7 @@ end --- Checks if FILE or DIRECTORY exists --- @param absolutePath string full path --- @return boolean -function fu.exists(absolutePath) +function FileUtils.Exists(absolutePath) -- https://stackoverflow.com/a/21637809/3493998 if type(absolutePath) ~= "string" then error("Parameter 'absolutePath' '" .. tostring(absolutePath) .. "' is not type of string!", 2) @@ -293,13 +275,15 @@ function fu.exists(absolutePath) return exists end -function fu.IsFile(full_path) +--- @param full_path string +--- @return boolean +function FileUtils.IsFile(full_path) -- https://stackoverflow.com/a/21637809/3493998 if type(full_path) ~= "string" then - error("file_util.lua | Parameter full_path '" .. tostring(full_path) .. "' is not type of string!") + error("FileUtils.lua | Parameter full_path '" .. tostring(full_path) .. "' is not type of string!") end - if not fu.exists(full_path) then - --logger:debug("file_util.lua | Path '" .. tostring(full_path) .. "' does not exist!") + if not FileUtils.Exists(full_path) then + --logger:debug("FileUtils.lua | Path '" .. tostring(full_path) .. "' does not exist!") return false end local f = io.open(full_path) @@ -310,23 +294,27 @@ function fu.IsFile(full_path) return false end -function fu.IsDirectory(full_path) +--- @param full_path string +--- @return boolean +function FileUtils.IsDirectory(full_path) -- https://stackoverflow.com/a/21637809/3493998 if type(full_path) ~= "string" then - error("file_util.lua | Parameter full_path '" .. tostring(full_path) .. "' is not type of string!") + error("FileUtils.lua | Parameter full_path '" .. tostring(full_path) .. "' is not type of string!") end - local exists = fu.exists(full_path) - --logger:debug("file_util.lua | Directory " .. full_path .. " exists = " .. tostring(exists)) - local is_file = fu.IsFile(full_path) - --logger:debug("file_util.lua | Is the directory a file? " .. full_path .. " is_file = " .. tostring(is_file)) + local exists = FileUtils.Exists(full_path) + --logger:debug("FileUtils.lua | Directory " .. full_path .. " exists = " .. tostring(exists)) + local is_file = FileUtils.IsFile(full_path) + --logger:debug("FileUtils.lua | Is the directory a file? " .. full_path .. " is_file = " .. tostring(is_file)) return (exists and not is_file) end -function fu.ReadBinaryFile(file_fullpath) +--- @param file_fullpath string +--- @return string|number +function FileUtils.ReadBinaryFile(file_fullpath) if type(file_fullpath) ~= "string" then - error("file_util.lua | Parameter file_fullpath '" .. tostring(file_fullpath) .. "' is not type of string!") + error("FileUtils.lua | Parameter file_fullpath '" .. tostring(file_fullpath) .. "' is not type of string!") end - file_fullpath = fu.ReplacePathSeparator(file_fullpath) + file_fullpath = FileUtils.ReplacePathSeparator(file_fullpath) -- https://stackoverflow.com/a/31857671/3493998 local file = io.open(file_fullpath, "rb") -- r read mode and b binary mode if not file then @@ -337,11 +325,13 @@ function fu.ReadBinaryFile(file_fullpath) return content end -function fu.WriteBinaryFile(file_fullpath, file_content) +--- @param file_fullpath string +--- @param file_content any +function FileUtils.WriteBinaryFile(file_fullpath, file_content) if type(file_fullpath) ~= "string" then - error("file_util.lua | Parameter file_fullpath '" .. tostring(file_fullpath) .. "' is not type of string!") + error("FileUtils.lua | Parameter file_fullpath '" .. tostring(file_fullpath) .. "' is not type of string!") end - file_fullpath = fu.ReplacePathSeparator(file_fullpath) + file_fullpath = FileUtils.ReplacePathSeparator(file_fullpath) -- http://lua-users.org/wiki/FileInputOutput local fh = assert(io.open(file_fullpath, "wb")) fh:write(file_content) @@ -349,15 +339,17 @@ function fu.WriteBinaryFile(file_fullpath, file_content) fh:close() end -function fu.ReadFile(file_fullpath, mode) +--- @param file_fullpath string +--- @param mode string? +function FileUtils.ReadFile(file_fullpath, mode) if mode == nil then mode = "*a" end if type(file_fullpath) ~= "string" then - error("file_util.lua | Parameter file_fullpath '" .. tostring(file_fullpath) .. "' is not type of string!") + error("FileUtils.lua | Parameter file_fullpath '" .. tostring(file_fullpath) .. "' is not type of string!") end - file_fullpath = fu.ReplacePathSeparator(file_fullpath) + file_fullpath = FileUtils.ReplacePathSeparator(file_fullpath) -- https://stackoverflow.com/a/31857671/3493998 local file = io.open(file_fullpath, "r") if not file then @@ -368,11 +360,13 @@ function fu.ReadFile(file_fullpath, mode) return content end -function fu.WriteFile(file_fullpath, file_content) +--- @param file_fullpath string +---@param file_content string +function FileUtils.WriteFile(file_fullpath, file_content) if type(file_fullpath) ~= "string" then - error("file_util.lua | Parameter file_fullpath '" .. tostring(file_fullpath) .. "' is not type of string!") + error("FileUtils.lua | Parameter file_fullpath '" .. tostring(file_fullpath) .. "' is not type of string!") end - file_fullpath = fu.ReplacePathSeparator(file_fullpath) + file_fullpath = FileUtils.ReplacePathSeparator(file_fullpath) local segments = string.split(file_fullpath, pathSeparator) or {} local pathPerSegments = "" @@ -380,10 +374,10 @@ function fu.WriteFile(file_fullpath, file_content) -- recursively create directories local segment = segments[i] pathPerSegments = pathPerSegments .. segment .. pathSeparator - if not fu.exists(pathPerSegments) then + if not FileUtils.Exists(pathPerSegments) then if not pathPerSegments:contains(".") then -- dump check if it's a file - fu.MkDir(pathPerSegments) + FileUtils.MkDir(pathPerSegments) end end end @@ -395,12 +389,13 @@ function fu.WriteFile(file_fullpath, file_content) fh:close() end -function fu.MkDir(full_path) +--- @param full_path string +function FileUtils.MkDir(full_path) if type(full_path) ~= "string" then - error("file_util.lua | Parameter file_fullpath '" .. tostring(full_path) .. "' is not type of string!") + error("FileUtils.lua | Parameter file_fullpath '" .. tostring(full_path) .. "' is not type of string!") end -- https://stackoverflow.com/a/1690932/3493998 - full_path = fu.ReplacePathSeparator(full_path) + full_path = FileUtils.ReplacePathSeparator(full_path) local command = nil if _G.is_windows then @@ -411,8 +406,9 @@ function fu.MkDir(full_path) os.execute(command) end -function fu.AppendToFile(filenameAbsolutePath, appendContent) - -- TODO rework: have a look on plotly.lua ">>" +--- @param filenameAbsolutePath string +---@param appendContent string +function FileUtils.AppendToFile(filenameAbsolutePath, appendContent) local isEmpty = true local file = io.open(filenameAbsolutePath, "a+") for line in io.lines(filenameAbsolutePath) do @@ -427,18 +423,18 @@ function fu.AppendToFile(filenameAbsolutePath, appendContent) file:close() end ----comment --- http://lua-users.org/wiki/SplitJoin -> Example: Split a file path string into components. ---@param str any ---@return unknown -function fu.splitPath(str) +function FileUtils.SplitPath(str) return string.split(str, '[\\/]+') -- TODO: differ between windows and unix --parts = split_path("/usr/local/bin") --> {'usr','local','bin'} end -- Lua implementation of PHP scandir function -function fu.scanDir(directory) +--- @return string[] +function FileUtils.ScanDir(directory) local i, t, popen = 0, {}, io.popen local pfile = nil @@ -456,16 +452,14 @@ function fu.scanDir(directory) return t end -function fu.removeContentOfDirectory(absolutePath) +function FileUtils.RemoveContentOfDirectory(absolutePath) local successRmDir, errorRmDir = lfs.rmdir(absolutePath) - if not successRmDir or errorRmDir then local command = ('rmdir /s /q "%s"'):format(absolutePath) local success, exitCode, code = os.execute(command) Logger.debug(Logger.channels.testing, - ("Tried to remove directory. success=%s, exitCode=%s, code=%s"):format(success, exitCode, code)) + ("Tried to remove directory. success=%s, exitCode=%s, code=%s"):format(success, exitCode, code)) end - lfs.mkdir(absolutePath) end @@ -473,28 +467,29 @@ end --- 7zip stuff ---------------------------------------------------------------------------------------------------- -function fu.Find7zipExecutable() +function FileUtils.Find7zipExecutable() if is_windows then local f = io.popen("where.exe 7z", "r") if not f then error( - "Unable to find 7z.exe, please install 7z via https://7-zip.de/download.html and restart the Noita!", - 2 + "Unable to find 7z.exe, please install 7z via https://7-zip.de/download.html and restart the Noita!", + 2 ) os.exit() end local response = f:read("*a") - _G.seven_zip = tostring(fu.ReplacePathSeparator(response)) - Logger.debug(Logger.channels.testing, "file_util.lua | Found 7z.exe: " .. _G.seven_zip) + _G.seven_zip = tostring(FileUtils.ReplacePathSeparator(response)) + Logger.debug(Logger.channels.testing, "FileUtils.lua | Found 7z.exe: " .. _G.seven_zip) else error( - "Unfortunately unix systems aren't supported yet. Please consider https://github.com/Ismoh/NoitaMP/issues!", - 2 + "Unfortunately unix systems aren't supported yet. Please consider https://github.com/Ismoh/NoitaMP/issues!", + 2 ) end end -function fu.exists7zip() +--- @return boolean +function FileUtils.Exists7zip() if _G.seven_zip then return true else @@ -502,58 +497,56 @@ function fu.exists7zip() end end ----comment ---@param archive_name string server_save06_98-09-16_23:48:10 - without file extension (*.7z) ---@param absolute_directory_path_to_add_archive string "C:\Users\Ismoh-PC\AppData\LocalLow\Nolla_Games_Noita\save06" ---@param absolute_destination_path string "C:\Program Files (x86)\Steam\steamapps\common\Noita\mods\noita-mp\_" ---@return string|number content binary content of archive -function fu.Create7zipArchive(archive_name, absolute_directory_path_to_add_archive, absolute_destination_path) +function FileUtils.Create7zipArchive(archive_name, absolute_directory_path_to_add_archive, absolute_destination_path) assert( - fu.exists7zip(), - "Unable to find 7z.exe, please install 7z via https://7-zip.de/download.html and restart the Noita!" + FileUtils.Exists7zip(), + "Unable to find 7z.exe, please install 7z via https://7-zip.de/download.html and restart the Noita!" ) if type(archive_name) ~= "string" then - error("file_util.lua | Parameter archive_name '" .. tostring(archive_name) .. "' is not type of string!") + error("FileUtils.lua | Parameter archive_name '" .. tostring(archive_name) .. "' is not type of string!") end if type(absolute_directory_path_to_add_archive) ~= "string" then error( - "file_util.lua | Parameter absolute_directory_path_to_add_archive '" .. - tostring(absolute_directory_path_to_add_archive) .. "' is not type of string!" + "FileUtils.lua | Parameter absolute_directory_path_to_add_archive '" .. + tostring(absolute_directory_path_to_add_archive) .. "' is not type of string!" ) end if type(absolute_destination_path) ~= "string" then error( - "file_util.lua | Parameter absolute_destination_path '" .. - tostring(absolute_destination_path) .. "' is not type of string!" + "FileUtils.lua | Parameter absolute_destination_path '" .. + tostring(absolute_destination_path) .. "' is not type of string!" ) end - absolute_directory_path_to_add_archive = fu.ReplacePathSeparator(absolute_directory_path_to_add_archive) - absolute_destination_path = fu.ReplacePathSeparator(absolute_destination_path) + absolute_directory_path_to_add_archive = FileUtils.ReplacePathSeparator(absolute_directory_path_to_add_archive) + absolute_destination_path = FileUtils.ReplacePathSeparator(absolute_destination_path) local command = 'cd "' .. - absolute_destination_path .. - '" && 7z.exe a -t7z ' .. archive_name .. ' "' .. absolute_directory_path_to_add_archive .. '"' - Logger.debug(Logger.channels.testing, "file_util.lua | Running: " .. command) + absolute_destination_path .. + '" && 7z.exe a -t7z ' .. archive_name .. ' "' .. absolute_directory_path_to_add_archive .. '"' + Logger.debug(Logger.channels.testing, "FileUtils.lua | Running: " .. command) os.execute(command) local archive_full_path = absolute_destination_path .. _G.pathSeparator .. archive_name .. ".7z" - return fu.ReadBinaryFile(archive_full_path) + return FileUtils.ReadBinaryFile(archive_full_path) end ----comment ---@param archive_absolute_directory_path string path to archive location like "C:\Program Files (x86)\Steam\steamapps\common\Noita\mods\noita-mp\_" ---@param archive_name string server_save06_98-09-16_23:48:10.7z - with file extension (*.7z) ---@param extract_absolute_directory_path string "C:\Users\Ismoh-PC\AppData\LocalLow\Nolla_Games_Noita" -function fu.Extract7zipArchive(archive_absolute_directory_path, archive_name, extract_absolute_directory_path) - archive_absolute_directory_path = fu.ReplacePathSeparator(archive_absolute_directory_path) - extract_absolute_directory_path = fu.ReplacePathSeparator(extract_absolute_directory_path) +function FileUtils.Extract7zipArchive(archive_absolute_directory_path, archive_name, extract_absolute_directory_path) + archive_absolute_directory_path = FileUtils.ReplacePathSeparator(archive_absolute_directory_path) + extract_absolute_directory_path = FileUtils.ReplacePathSeparator(extract_absolute_directory_path) local command = 'cd "' .. - archive_absolute_directory_path .. - '" && 7z.exe x -aoa ' .. archive_name .. ' -o"' .. extract_absolute_directory_path .. '"' - Logger.debug(Logger.channels.testing, "file_util.lua | Running: " .. command) + archive_absolute_directory_path .. + '" && 7z.exe x -aoa ' .. archive_name .. ' -o"' .. extract_absolute_directory_path .. '"' + Logger.debug(Logger.channels.testing, "FileUtils.lua | Running: " .. command) os.execute(command) end @@ -564,25 +557,25 @@ end ---------------------------------------------------------------------------------------------------- --- Credits to dextercd! -function fu.restartNoita() +function FileUtils.FestartNoita() require("ffi").cast("void(__fastcall*)()", 0x0066e120)() end -function fu.killNoitaAndRestart() +function FileUtils.KillNoitaAndRestart() local exe = "noita.exe" if DebugGetIsDevBuild() then exe = "noita_dev.exe" end - fu.removeContentOfDirectory(_G.saveSlotMeta.dir) + FileUtils.RemoveContentOfDirectory(_G.saveSlotMeta.dir) os.execute(('start "" %s -no_logo_splashes -save_slot %s -gamemode 4'):format(exe, - _G.saveSlotMeta.slot)) -- -gamemode 0 + _G.saveSlotMeta.slot)) -- -gamemode 0 os.exit() end --- This executes c code to sent SDL_QUIT command to the app -function fu.saveAndRestartNoita() +function FileUtils.SaveAndRestartNoita() ffi.cdef [[ typedef union SDL_Event { @@ -607,10 +600,10 @@ function fu.saveAndRestartNoita() exe = "noita_dev.exe" end os.execute(('start "" %s -no_logo_splashes -save_slot %s -gamemode 4'):format(exe, - _G.saveSlotMeta.slot)) -- -gamemode 0 + _G.saveSlotMeta.slot)) -- -gamemode 0 end -function fu.getAllFilesInDirectory(directory, fileExtension) +function FileUtils.GetAllFilesInDirectory(directory, fileExtension) local command = nil if _G.is_windows then command = "for /f tokens^=* %i in ('where /r \"" .. directory .. "\" *" .. fileExtension .. "')do @echo/ %~nxi" @@ -629,7 +622,7 @@ function fu.getAllFilesInDirectory(directory, fileExtension) return filenames end -function fu.getDesktopDirectory() +function FileUtils.GetDesktopDirectory() local command = nil if _G.is_windows then command = "echo %USERPROFILE%\\Desktop" @@ -644,4 +637,4 @@ function fu.getDesktopDirectory() return string.trim(content) end -return fu +return FileUtils diff --git a/mods/noita-mp/files/scripts/util/GuidUtils.lua b/mods/noita-mp/files/scripts/util/GuidUtils.lua index f6767100b..07093fbc2 100644 --- a/mods/noita-mp/files/scripts/util/GuidUtils.lua +++ b/mods/noita-mp/files/scripts/util/GuidUtils.lua @@ -1,4 +1,4 @@ -local util = require("util") +local Utils = require("Utils") local socket = require("socket") local uuid = require("uuid") @@ -51,7 +51,7 @@ end --- @return string guid function GuidUtils:getGuid(inUsedGuids) local cpc = CustomProfiler.start("GuidUtils:getGuid") - if not util.IsEmpty(inUsedGuids) and #inUsedGuids > 0 then + if not Utils.IsEmpty(inUsedGuids) and #inUsedGuids > 0 then for i = 1, #inUsedGuids do if not GuidUtils.isPatternValid(inUsedGuids[i]) then error(("Already in used guid '%s' is not a valid guid!"):format(inUsedGuids[i]), 2) @@ -60,7 +60,7 @@ function GuidUtils:getGuid(inUsedGuids) ---@cast inUsedGuids table table.insertAllButNotDuplicates(self.cached_guid, inUsedGuids) - Logger.debug(Logger.channels.guid, ("Guid:getGuid() - inUsedGuids: %s"):format(util.pformat(inUsedGuids))) + Logger.debug(Logger.channels.guid, ("Guid:getGuid() - inUsedGuids: %s"):format(Utils.pformat(inUsedGuids))) end repeat @@ -81,7 +81,7 @@ function GuidUtils.isPatternValid(guid) if type(guid) ~= "string" then return false end - if util.IsEmpty(guid) then + if Utils.IsEmpty(guid) then return false end diff --git a/mods/noita-mp/files/scripts/util/Logger.lua b/mods/noita-mp/files/scripts/util/Logger.lua index 6799b6058..49e6bc8bf 100644 --- a/mods/noita-mp/files/scripts/util/Logger.lua +++ b/mods/noita-mp/files/scripts/util/Logger.lua @@ -65,7 +65,7 @@ function Logger.log(level, channel, message) error("There is a directive (%) in your log message. Use string.format! Message = '" .. message .. "'", 2) end - if level == "off" then + if string.lower(level) == "off" then return false end @@ -94,11 +94,9 @@ function Logger.log(level, channel, message) -- add file name to logs: https://stackoverflow.com/a/48469960/3493998 local file_name = debug.getinfo(2, "S").source:sub(2) file_name = file_name:match("^.*/(.*)$") or file_name - msg = ("%s [%s][%s] %s \n(in %s)") - :format(time, level, channel, message, file_name) + msg = ("%s [%s][%s] %s \n(in %s)"):format(time, level, channel, message, file_name) else - msg = ("%s [%s][%s] %s") - :format("--:--:--", level, channel, message) + msg = ("%s [%s][%s] %s"):format("--:--:--", level, channel, message) end print(msg) diff --git a/mods/noita-mp/files/scripts/util/MinaUtils.lua b/mods/noita-mp/files/scripts/util/MinaUtils.lua index 4c6493959..9a83cf87a 100644 --- a/mods/noita-mp/files/scripts/util/MinaUtils.lua +++ b/mods/noita-mp/files/scripts/util/MinaUtils.lua @@ -78,7 +78,7 @@ function MinaUtils.getLocalMinaEntityId() local playerEntityIds = EntityGetWithTag("player_unit") for i = 1, #playerEntityIds do if NetworkVscUtils.hasNetworkLuaComponents(playerEntityIds[i]) then - local compOwnerName, compOwnerGuid, compNuid = NetworkVscUtils.getAllVcsValuesByEntityId(playerEntityIds[i]) + local compOwnerName, compOwnerGuid, compNuid = NetworkVscUtils.getAllVscValuesByEntityId(playerEntityIds[i]) if compOwnerGuid == localMinaGuid then EntityUtils.localPlayerEntityId = playerEntityIds[i] CustomProfiler.stop("MinaUtils.getLocalMinaEntityId", cpc) @@ -122,7 +122,7 @@ function MinaUtils.getLocalMinaInformation() NetworkVscUtils.addOrUpdateAllVscs(entityId, ownerName, ownerGuid, nuid) end - local _, _, nuid = NetworkVscUtils.getAllVcsValuesByEntityId(entityId) + local _, _, nuid = NetworkVscUtils.getAllVscValuesByEntityId(entityId) CustomProfiler.stop("MinaUtils.getLocalMinaInformation", cpc) return { name = ownerName, @@ -144,7 +144,7 @@ function MinaUtils.isLocalMinaPolymorphed() for c = 1, #componentIds do local isPlayer = ComponentGetValue2(componentIds[c], "is_player") if isPlayer then - local compOwnerName, compOwnerGuid, compNuid = NetworkVscUtils.getAllVcsValuesByEntityId(polymorphedEntityIds[e]) + local compOwnerName, compOwnerGuid, compNuid = NetworkVscUtils.getAllVscValuesByEntityId(polymorphedEntityIds[e]) if compOwnerGuid == localMinaGuid then EntityUtils.localPlayerEntityIdPolymorphed = polymorphedEntityIds[e] CustomProfiler.stop("MinaUtils.isLocalMinaPolymorphed", cpc) diff --git a/mods/noita-mp/files/scripts/util/NetworkCacheUtils.lua b/mods/noita-mp/files/scripts/util/NetworkCacheUtils.lua index 44a600a01..5bce4fe0a 100644 --- a/mods/noita-mp/files/scripts/util/NetworkCacheUtils.lua +++ b/mods/noita-mp/files/scripts/util/NetworkCacheUtils.lua @@ -10,7 +10,7 @@ ------------------------------------------------------------------------------------------------------------------------ --- 'Imports' ------------------------------------------------------------------------------------------------------------------------ -local util = require("util") +local Utils = require("Utils") local md5 = require("md5") ------------------------------------------------------------------------------------------------------------------------ @@ -20,11 +20,11 @@ NetworkCacheUtils = {} function NetworkCacheUtils.getSum(event, data) local cpc = CustomProfiler.start("NetworkCacheUtils.getSum") - Logger.trace(Logger.channels.testing, "getSum: " .. util.pformat(data)) - if not event or util.IsEmpty(event) or type(event) ~= "string" then + Logger.trace(Logger.channels.testing, "getSum: " .. Utils.pformat(data)) + if not event or Utils.IsEmpty(event) or type(event) ~= "string" then error(("Unable to calculate sum, when event is nil or not a string: '%s'"):format(event), 2) end - if not data or util.IsEmpty(data) or type(data) ~= "table" then + if not data or Utils.IsEmpty(data) or type(data) ~= "table" then error(("Unable to calculate sum, when data is nil or not a table: '%s'"):format(data), 2) end @@ -32,15 +32,15 @@ function NetworkCacheUtils.getSum(event, data) error(("Event '%s' shouldn't be cached!"):format(event), 2) end - Logger.trace(Logger.channels.testing, "data: " .. util.pformat(data)) + Logger.trace(Logger.channels.testing, "data: " .. Utils.pformat(data)) local dataCopy = NetworkUtils.getClientOrServer().zipTable(data, NetworkUtils.events[event].schema, event) - Logger.trace(Logger.channels.testing, "dataCopy zipped: " .. util.pformat(dataCopy)) + Logger.trace(Logger.channels.testing, "dataCopy zipped: " .. Utils.pformat(dataCopy)) if event ~= NetworkUtils.events.acknowledgement.name then -- when event is NOT acknowledgement, remove networkMessageId, -- but we need the networkMessageId to find the previous cached network message, when the event is acknowledgement dataCopy.networkMessageId = nil end - Logger.trace(Logger.channels.testing, "dataCopy without networkMessageId: " .. util.pformat(dataCopy)) + Logger.trace(Logger.channels.testing, "dataCopy without networkMessageId: " .. Utils.pformat(dataCopy)) local sum = "" if NetworkUtils.events[event].resendIdentifiers ~= nil then local newData = {} @@ -55,7 +55,7 @@ function NetworkCacheUtils.getSum(event, data) else sum = table.contentToString(dataCopy) end - Logger.trace(Logger.channels.testing, ("sum from %s = %s"):format(util.pformat(dataCopy), sum)) + Logger.trace(Logger.channels.testing, ("sum from %s = %s"):format(Utils.pformat(dataCopy), sum)) CustomProfiler.stop("NetworkCacheUtils.getSum", cpc) return sum end @@ -66,26 +66,26 @@ end --- function NetworkCacheUtils.set(peerGuid, networkMessageId, event, status, ackedAt, sendAt, data) local cpc = CustomProfiler.start("NetworkCacheUtils.set") - if not peerGuid or util.IsEmpty(peerGuid) or type(peerGuid) ~= "string" then + if not peerGuid or Utils.IsEmpty(peerGuid) or type(peerGuid) ~= "string" then error(("peerGuid '%s' must not be nil or empty or isn't type of string!"):format(peerGuid), 2) end - if not networkMessageId or util.IsEmpty(networkMessageId) or type(networkMessageId) ~= "number" then + if not networkMessageId or Utils.IsEmpty(networkMessageId) or type(networkMessageId) ~= "number" then error(("networkMessageId '%s' must not be nil or empty or isn't type of number!"):format(networkMessageId), 2) end - if not event or util.IsEmpty(event) or type(event) ~= "string" then + if not event or Utils.IsEmpty(event) or type(event) ~= "string" then error(("event '%s' must not be nil or empty or isn't type of string!"):format(event), 2) end - if not status or util.IsEmpty(status) or type(status) ~= "string" then + if not status or Utils.IsEmpty(status) or type(status) ~= "string" then error(("status '%s' must not be nil or empty or isn't type of string!"):format(status), 2) end - if not ackedAt or util.IsEmpty(ackedAt) or type(ackedAt) ~= "number" then + if not ackedAt or Utils.IsEmpty(ackedAt) or type(ackedAt) ~= "number" then error(("ackedAt '%s' must not be nil or empty or isn't type of number!"):format(ackedAt), 2) end - if not sendAt or util.IsEmpty(sendAt) or type(sendAt) ~= "number" then + if not sendAt or Utils.IsEmpty(sendAt) or type(sendAt) ~= "number" then error(("sendAt '%s' must not be nil or empty or isn't type of number!"):format(sendAt), 2) end - if not data or util.IsEmpty(data) or type(data) ~= "table" then - error(("data '%s' must not be nil or empty or isn't type of table!"):format(util.pformat(data)), 2) + if not data or Utils.IsEmpty(data) or type(data) ~= "table" then + error(("data '%s' must not be nil or empty or isn't type of table!"):format(Utils.pformat(data)), 2) end if not NetworkUtils.events[event].isCacheable then @@ -111,13 +111,13 @@ end --- @return table data { ackedAt, dataChecksum, event, messageId, sentAt, status} function NetworkCacheUtils.get(peerGuid, networkMessageId, event) local cpc = CustomProfiler.start("NetworkCacheUtils.get") - if not peerGuid or util.IsEmpty(peerGuid) or type(peerGuid) ~= "string" then + if not peerGuid or Utils.IsEmpty(peerGuid) or type(peerGuid) ~= "string" then error(("peerGuid '%s' must not be nil or empty or isn't type of string!"):format(peerGuid), 2) end - if not networkMessageId or util.IsEmpty(networkMessageId) or type(networkMessageId) ~= "number" then + if not networkMessageId or Utils.IsEmpty(networkMessageId) or type(networkMessageId) ~= "number" then error(("networkMessageId '%s' must not be nil or empty or isn't type of number!"):format(networkMessageId), 2) end - if not event or util.IsEmpty(event) or type(event) ~= "string" then + if not event or Utils.IsEmpty(event) or type(event) ~= "string" then error(("event '%s' must not be nil or empty or isn't type of string!"):format(event), 2) end @@ -138,7 +138,7 @@ function NetworkCacheUtils.get(peerGuid, networkMessageId, event) local data = NetworkCache.get(clientCacheId, event, tonumber(networkMessageId)) Logger.info(Logger.channels.cache, ("Get nCache by clientCacheId %s, event %s, networkMessageId %s, data %s") - :format(clientCacheId, event, networkMessageId, util.pformat(data))) + :format(clientCacheId, event, networkMessageId, Utils.pformat(data))) CustomProfiler.stop("NetworkCacheUtils.get", cpc) return data end @@ -146,14 +146,14 @@ end --- @return table cacheData { ackedAt, dataChecksum, event, messageId, sentAt, status} function NetworkCacheUtils.getByChecksum(peerGuid, event, data) local cpc = CustomProfiler.start("NetworkCacheUtils.getByChecksum") - if not peerGuid or util.IsEmpty(peerGuid) or type(peerGuid) ~= "string" then - error(("peerGuid '%s' must not be nil or empty or isn't type of string!"):format(util.pformat(peerGuid)), 2) + if not peerGuid or Utils.IsEmpty(peerGuid) or type(peerGuid) ~= "string" then + error(("peerGuid '%s' must not be nil or empty or isn't type of string!"):format(Utils.pformat(peerGuid)), 2) end - if not event or util.IsEmpty(event) or type(event) ~= "string" then - error(("event '%s' must not be nil or empty or isn't type of string!"):format(util.pformat(event)), 2) + if not event or Utils.IsEmpty(event) or type(event) ~= "string" then + error(("event '%s' must not be nil or empty or isn't type of string!"):format(Utils.pformat(event)), 2) end - if not data or util.IsEmpty(data) or type(data) ~= "table" then - error(("data '%s' must not be nil or empty or isn't type of table!"):format(util.pformat(data)), 2) + if not data or Utils.IsEmpty(data) or type(data) ~= "table" then + error(("data '%s' must not be nil or empty or isn't type of table!"):format(Utils.pformat(data)), 2) end if not NetworkUtils.events[event].isCacheable then @@ -166,7 +166,7 @@ function NetworkCacheUtils.getByChecksum(peerGuid, event, data) local cacheData = NetworkCache.getChecksum(clientCacheId, dataChecksum) Logger.info(Logger.channels.cache, ("Get nCache by clientCacheId %s, dataChecksum %s, event %s, cacheData %s") - :format(clientCacheId, dataChecksum, event, util.pformat(cacheData))) + :format(clientCacheId, dataChecksum, event, Utils.pformat(cacheData))) CustomProfiler.stop("NetworkCacheUtils.getByChecksum", cpc) return cacheData end diff --git a/mods/noita-mp/files/scripts/util/NetworkUtils.lua b/mods/noita-mp/files/scripts/util/NetworkUtils.lua index 36ab0e59e..98cbe3975 100644 --- a/mods/noita-mp/files/scripts/util/NetworkUtils.lua +++ b/mods/noita-mp/files/scripts/util/NetworkUtils.lua @@ -6,7 +6,7 @@ ------------------------------------------------------------------------------------------------------------------------ --- 'Imports' ------------------------------------------------------------------------------------------------------------------------ -local util = require("util") +local Utils = require("Utils") ------------------------------------------------------------------------------------------------------------------------ --- NetworkUtils @@ -201,7 +201,7 @@ function NetworkUtils.alreadySent(peer, event, data) if not data then error("'data' must not be nil!", 2) end - if util.IsEmpty(peer.clientCacheId) then + if Utils.IsEmpty(peer.clientCacheId) then Logger.info(Logger.channels.testing, ("peer.guid = '%s'"):format(peer.guid)) peer.clientCacheId = GuidUtils.toNumber(peer.guid) --error("peer.clientCacheId must not be nil!", 2) end diff --git a/mods/noita-mp/files/scripts/util/NetworkVscUtils.lua b/mods/noita-mp/files/scripts/util/NetworkVscUtils.lua index 930055a0f..35138cd34 100644 --- a/mods/noita-mp/files/scripts/util/NetworkVscUtils.lua +++ b/mods/noita-mp/files/scripts/util/NetworkVscUtils.lua @@ -373,18 +373,18 @@ end --- Returns all Network Vsc values by its entity id. --- @param entityId number Entity Id provided by Noita --- @return string? ownerName, string? ownerGuid, number? nuid - nuid can be nil -function NetworkVscUtils.getAllVcsValuesByEntityId(entityId) - local cpc = CustomProfiler.start("NetworkVscUtils.getAllVcsValuesByEntityId") +function NetworkVscUtils.getAllVscValuesByEntityId(entityId) + local cpc = CustomProfiler.start("NetworkVscUtils.getAllVscValuesByEntityId") if not EntityUtils.isEntityAlive(entityId) then - CustomProfiler.stop("NetworkVscUtils.getAllVcsValuesByEntityId", cpc) + CustomProfiler.stop("NetworkVscUtils.getAllVscValuesByEntityId", cpc) return end local ownerNameCompId, ownerGuidCompId, nuidCompId, _, _ = getNetworkComponents(entityId) - CustomProfiler.stop("NetworkVscUtils.getAllVcsValuesByEntityId", cpc) + CustomProfiler.stop("NetworkVscUtils.getAllVscValuesByEntityId", cpc) if ownerNameCompId and ownerGuidCompId then return NetworkVscUtils.getAllVcsValuesByComponentIds(ownerNameCompId, ownerGuidCompId, nuidCompId) else - error(("getAllVcsValuesByEntityId: Got unexpected nil id. entityId, = %s ownerNameCompId = %s, ownerGuidCompId = %s, nuidCompId = %s") + error(("getAllVscValuesByEntityId: Got unexpected nil id. entityId, = %s ownerNameCompId = %s, ownerGuidCompId = %s, nuidCompId = %s") :format(entityId, ownerNameCompId, ownerGuidCompId, nuidCompId), 2) end end @@ -402,10 +402,10 @@ function NetworkVscUtils.getAllVcsValuesByComponentIds(ownerNameCompId, ownerGui local compOwnerGuid = ComponentGetValue2(ownerGuidCompId, NetworkVscUtils.valueString) local compNuid = ComponentGetValue2(nuidCompId, NetworkVscUtils.valueString) - if util.IsEmpty(compOwnerName) then + if Utils.IsEmpty(compOwnerName) then error(("Something really bad went wrong! compOwnerName must not be empty: %s"):format(compOwnerName), 2) end - if util.IsEmpty(compOwnerGuid) then + if Utils.IsEmpty(compOwnerGuid) then error(("Something really bad went wrong! compOwnerGuid must not be empty: %s"):format(compOwnerGuid), 2) end diff --git a/mods/noita-mp/files/scripts/util/NoitaComponentUtils.lua b/mods/noita-mp/files/scripts/util/NoitaComponentUtils.lua index d0240d828..fb1f06707 100644 --- a/mods/noita-mp/files/scripts/util/NoitaComponentUtils.lua +++ b/mods/noita-mp/files/scripts/util/NoitaComponentUtils.lua @@ -48,7 +48,7 @@ end --- @return string ownername, string ownerguid, number nuid, string filename, EntityHealthData health, number rotation, Vec2 velocity, number x, number y function NoitaComponentUtils.getEntityData(entityId) local cpc = CustomProfiler.start("NoitaComponentUtils.getEntityData") - local compOwnerName, compOwnerGuid, compNuid = NetworkVscUtils.getAllVcsValuesByEntityId(entityId) + local compOwnerName, compOwnerGuid, compNuid = NetworkVscUtils.getAllVscValuesByEntityId(entityId) local hpCompId = EntityGetFirstComponentIncludingDisabled(entityId, "DamageModelComponent") local health = { current = 0, max = 0 } diff --git a/mods/noita-mp/files/scripts/util/NuidUtils.lua b/mods/noita-mp/files/scripts/util/NuidUtils.lua index e8af3a0b4..b518e0c59 100644 --- a/mods/noita-mp/files/scripts/util/NuidUtils.lua +++ b/mods/noita-mp/files/scripts/util/NuidUtils.lua @@ -6,7 +6,7 @@ ---------------------------------------- --- 'Imports' ---------------------------------------- -local fu = require("file_util") +local fu = require("FileUtils") local nxml = require("nxml") ----------------- @@ -27,7 +27,7 @@ local function getNextNuid() -- Are there any nuids saved in globals, if so get the highest nuid? if not xmlParsed then local worldStateXmlAbsPath = fu.GetAbsDirPathOfWorldStateXml(_G.saveSlotMeta.dir) - if fu.exists(worldStateXmlAbsPath) then + if fu.Exists(worldStateXmlAbsPath) then local f = io.open(worldStateXmlAbsPath, "r") local xml = nxml.parse(f:read("*a")) f:close() @@ -64,7 +64,7 @@ function NuidUtils.getEntityIdsByKillIndicator() local cpc = CustomProfiler.start("NuidUtils.getEntityIdsByKillIndicator") local deadNuids = GlobalsUtils.getDeadNuids() local worldStateXmlAbsPath = fu.GetAbsDirPathOfWorldStateXml(_G.saveSlotMeta.dir) - if fu.exists(worldStateXmlAbsPath) then + if fu.Exists(worldStateXmlAbsPath) then local f = io.open(worldStateXmlAbsPath, "r") local xml = nxml.parse(f:read("*a")) f:close() diff --git a/mods/noita-mp/files/scripts/util/util.lua b/mods/noita-mp/files/scripts/util/Utils.lua similarity index 88% rename from mods/noita-mp/files/scripts/util/util.lua rename to mods/noita-mp/files/scripts/util/Utils.lua index e79ef6fbe..a41bac73e 100644 --- a/mods/noita-mp/files/scripts/util/util.lua +++ b/mods/noita-mp/files/scripts/util/Utils.lua @@ -8,11 +8,12 @@ else pprint.defaults = {} end -local util = {} +--- @class Utils +local Utils = {} --- Wait for n seconds. ---@param s number seconds to wait -function util.Sleep(s) +function Utils.Sleep(s) if type(s) ~= "number" then error("Unable to wait if parameter 'seconds' isn't a number: " .. type(s)) end @@ -22,9 +23,9 @@ function util.Sleep(s) until os.clock() > ntime end -function util.IsEmpty(var) +function Utils.IsEmpty(var) -- if you change this also change NetworkVscUtils.lua - -- if you change this also change table_extensions.lua + -- if you change this also change tableExtensions.lua if var == nil then return true end @@ -38,14 +39,14 @@ function util.IsEmpty(var) end --https://noita.wiki.gg/wiki/Modding:_Utilities#Easier_entity_debugging -function util.str(var) +function Utils.Str(var) if type(var) == "table" then local s = "{ " for k, v in pairs(var) do if type(k) ~= "number" then k = '"' .. k .. '"' end - s = s .. "[" .. k .. "] = " .. util.str(v) .. "," + s = s .. "[" .. k .. "] = " .. Utils.Str(v) .. "," end return s .. "} " end @@ -53,7 +54,7 @@ function util.str(var) end --https://noita.wiki.gg/wiki/Modding:_Utilities#Easier_entity_debugging -function util.debug_entity(e) +function Utils.DebugEntity(e) local parent = EntityGetParent(e) local children = EntityGetAllChildren(e) local comps = EntityGetAllComponents(e) @@ -61,7 +62,7 @@ function util.debug_entity(e) local msg = "--- ENTITY DATA ---\n" msg = msg .. ("Parent: [" .. parent .. "] name = " .. (EntityGetName(parent) or "") .. "\n") - msg = msg .. (" Entity: [" .. util.str(e) .. "] name = " .. (EntityGetName(e) or "") .. "\n") + msg = msg .. (" Entity: [" .. Utils.Str(e) .. "] name = " .. (EntityGetName(e) or "") .. "\n") msg = msg .. (" Tags: " .. (EntityGetTags(e) or "") .. "\n") if (comps ~= nil) then for _, comp in ipairs(comps) do @@ -97,18 +98,18 @@ function util.debug_entity(e) Logger.debug(Logger.channels.testing, msg) end -function util.pformat(var) +function Utils.pformat(var) return pprint.pformat(var, pprint.defaults) end --- Reloads the whole world with a specific seed. No need to restart the game and use magic numbers. ---@param seed number max = 4294967295 -function util.reloadMap(seed) +function Utils.ReloadMap(seed) SetWorldSeed(seed) BiomeMapLoad_KeepPlayer("mods/noita-mp/files/scripts/DefaultBiomeMap.lua", "data/biome/_pixel_scenes.xml") end -function util.copyToClipboard(copy) +function Utils.CopyToClipboard(copy) local command = nil if _G.is_windows then command = ('echo "%s" | clip'):format(copy) @@ -118,4 +119,4 @@ function util.copyToClipboard(copy) os.execute(command) end -return util +return Utils diff --git a/mods/noita-mp/init.lua b/mods/noita-mp/init.lua index e29c833bb..0ce244a02 100644 --- a/mods/noita-mp/init.lua +++ b/mods/noita-mp/init.lua @@ -6,10 +6,9 @@ end --- Imports by dofile, dofile_once and require ---------------------------------------------------------------------------------------------------- dofile("mods/noita-mp/files/scripts/init/init_.lua") -local util = require("util") -local fu = require("file_util") -local ui = require("Ui").new() - +local Utils = require("Utils") +local fu = require("FileUtils") +local ui = require("Ui").new() Logger.debug(Logger.channels.initialize, "Starting to load noita-mp init.lua..") ---------------------------------------------------------------------------------------------------- @@ -20,7 +19,7 @@ NoitaMpSettings.clearAndCreateSettings() -- Is used to stop Noita pausing game, when focus is gone (tab out game) ModMagicNumbersFileAdd("mods/noita-mp/files/data/magic_numbers.xml") fu.Find7zipExecutable() -local saveSlotsLastModifiedBeforeWorldInit = fu.getLastModifiedSaveSlots() +local saveSlotsLastModifiedBeforeWorldInit = fu.GetLastModifiedSaveSlots() ---------------------------------------------------------------------------------------------------- --- NoitaMP functions @@ -36,14 +35,14 @@ local function setSeedIfConnectedSecondTime() Logger.debug(Logger.channels.initialize, ("Servers world seed = %s"):format(seed)) if not seed and seed > 0 then if DebugGetIsDevBuild() then - util.Sleep(5) -- needed to be able to attach debugger again + Utils.Sleep(5) -- needed to be able to attach debugger again end local cpc1 = CustomProfiler.start("ModSettingGet") local saveSlotMetaDirectory = ModSettingGet("noita-mp.saveSlotMetaDirectory") CustomProfiler.stop("ModSettingGet", cpc1) if saveSlotMetaDirectory then - fu.removeContentOfDirectory(saveSlotMetaDirectory) + fu.RemoveContentOfDirectory(saveSlotMetaDirectory) else error("Unable to emptying selected save slot!", 2) end @@ -73,14 +72,15 @@ function OnWorldInitialized() local archive_name = "server_save06_" .. os.date("%Y-%m-%d_%H-%M-%S") local destination = fu.GetAbsoluteDirectoryPathOfNoitaMP() .. pathSeparator .. "_" local archive_content = fu.Create7zipArchive(archive_name .. "_from_server", - fu.GetAbsoluteDirectoryPathOfSave06(), destination) - local msg = ("init.lua | Server savegame [%s] was zipped with 7z to location [%s]."):format(archive_name, - destination) + fu.GetAbsoluteDirectoryPathOfSave06(), destination) + local msg = ("init.lua | Server savegame [%s] was zipped with 7z to location [%s]."):format( + archive_name, + destination) Logger.debug(Logger.channels.initialize, msg) GamePrint(msg) local cpc1 = CustomProfiler.start("ModSettingSetNextValue") ModSettingSetNextValue("noita-mp.server_start_7zip_savegame", false, - false) -- automatically start the server again + false) -- automatically start the server again CustomProfiler.stop("ModSettingSetNextValue", cpc1) end CustomProfiler.stop("init.OnWorldInitialized", cpc) @@ -94,11 +94,11 @@ function OnPlayerSpawned(player_entity) if not GameHasFlagRun("nameTags_script_applied") then GameAddFlagRun("nameTags_script_applied") EntityAddComponent2(player_entity, - "LuaComponent", - { - script_source_file = "mods/noita-mp/files/scripts/noita-components/name_tags.lua", - execute_every_n_frame = 1, - }) + "LuaComponent", + { + script_source_file = "mods/noita-mp/files/scripts/noita-components/name_tags.lua", + execute_every_n_frame = 1, + }) end CustomProfiler.stop("init.OnPlayerSpawned", cpc) end @@ -124,7 +124,7 @@ function OnWorldPreUpdate() EntityUtils.addOrChangeDetectionRadiusDebug(MinaUtils.getLocalMinaInformation().entityId) if not _G.saveSlotMeta then - local saveSlotsLastModifiedAfterWorldInit = fu.getLastModifiedSaveSlots() + local saveSlotsLastModifiedAfterWorldInit = fu.GetLastModifiedSaveSlots() for i = 1, #saveSlotsLastModifiedBeforeWorldInit do for j = 1, #saveSlotsLastModifiedAfterWorldInit do local saveSlotMeta @@ -141,7 +141,7 @@ function OnWorldPreUpdate() ModSettingSetNextValue("noita-mp.saveSlotMetaDirectory", _G.saveSlotMeta.dir, false) CustomProfiler.stop("ModSettingSetNextValue", cpc1) Logger.info(Logger.channels.initialize, - ("Save slot found in '%s'"):format(util.pformat(_G.saveSlotMeta))) + ("Save slot found in '%s'"):format(Utils.pformat(_G.saveSlotMeta))) end end end @@ -149,7 +149,6 @@ function OnWorldPreUpdate() Server.update() Client.update() - ui.update() local cpc1 = CustomProfiler.start("init.OnWorldPreUpdate.collectgarbage.count") @@ -162,14 +161,7 @@ function OnWorldPreUpdate() collectgarbage("collect") CustomProfiler.stop("init.OnWorldPreUpdate.collectgarbage.collect", cpc2) end - CustomProfiler.stop("init.OnWorldPreUpdate.collectgarbage.count", cpc1) + CustomProfiler.stop("init.OnWorldPreUpdate.collectgarbage.count", cpc1) CustomProfiler.stop("init.OnWorldPreUpdate", cpc) end - ---function OnWorldPostUpdate() --- local cpc = CustomProfiler.start("init.OnWorldPostUpdate") --- Server.update() --- Client.update() --- CustomProfiler.stop("init.OnWorldPostUpdate", cpc) ---end diff --git a/mods/noita-mp/lua_modules/share/lua/5.1/os_name.lua b/mods/noita-mp/lua_modules/share/lua/5.1/os_name.lua index 51c116796..6f1c8eb2f 100644 --- a/mods/noita-mp/lua_modules/share/lua/5.1/os_name.lua +++ b/mods/noita-mp/lua_modules/share/lua/5.1/os_name.lua @@ -27,6 +27,7 @@ local function getOS() raw_os_name = (raw_os_name):lower() raw_arch_name = (raw_arch_name):lower() + print(("Detected os '%s' on arch '%s'!"):format(raw_os_name, raw_arch_name)) local os_patterns = { ["windows"] = "Windows", diff --git a/mods/noita-mp/lua_modules/share/lua/5.1/profiler.lua b/mods/noita-mp/lua_modules/share/lua/5.1/profiler.lua index d79b07312..445f485b5 100644 --- a/mods/noita-mp/lua_modules/share/lua/5.1/profiler.lua +++ b/mods/noita-mp/lua_modules/share/lua/5.1/profiler.lua @@ -77,7 +77,7 @@ new table using the matched key names: `profiler.configuration(overrides) ]] -local fu = require("file_util") +local fu = require("FileUtils") --[[ Configuration ]]-- diff --git a/mods/noita-mp/lua_modules/share/lua/5.1/sock.lua b/mods/noita-mp/lua_modules/share/lua/5.1/sock.lua index c918062bf..dae0658ab 100644 --- a/mods/noita-mp/lua_modules/share/lua/5.1/sock.lua +++ b/mods/noita-mp/lua_modules/share/lua/5.1/sock.lua @@ -33,8 +33,8 @@ local sock = { } local enet = require("enet") -local util = require("util") -local fu = require("file_util") +local Utils = require("Utils") +local fu = require("FileUtils") _G.Logger.info(_G.Logger.channels.initialize, "lua-enet version = master branch 21.10.2015") _G.Logger.info(_G.Logger.channels.initialize, "enet version = " .. enet.linked_version()) -- 1.3.17 @@ -71,7 +71,7 @@ local function zipTable(items, keys, event) if not key then error(("Missing data key for event '%s'! items = %s schema = %s") - :format(event, util.pformat(items), util.pformat(keys)), 2) + :format(event, Utils.pformat(items), Utils.pformat(keys)), 2) end data[key] = value @@ -150,7 +150,7 @@ function Logger:log(event, data) local time = os.date("%X") -- something like 24:59:59 local shortLine = ("%s [%s] %s"):format(time, event, data) local fullLine = ("%s [%s %s] %s"):format(time, self.source, event, - util.pformat(data)) --local fullLine = ("[%s][%s][%s] %s"):format(self.source, time, event, data) + Utils.pformat(data)) --local fullLine = ("[%s][%s][%s] %s"):format(self.source, time, event, data) -- The printed message may or may not be the full message local line = fullLine @@ -264,8 +264,8 @@ function Server:start(ip, port) if not self.host then --error("Failed to create the host. Is there another server running on :" .. self.port .. "?") self:log("", { "Failed to create the host. Is there another server running on :" .. self.port .. "?" }) - local pid = fu.getPidOfRunningEnetHostByPort() - fu.killProcess(pid) + local pid = fu.GetPidOfRunningEnetHostByPort() + fu.KillProcess(pid) return false end @@ -451,7 +451,7 @@ end function Server:sendToPeer(peer, event, data) local cpc = CustomProfiler.start("Server:sendToPeer") local networkMessageId = data[1] or data.networkMessageId - if util.IsEmpty(networkMessageId) then + if Utils.IsEmpty(networkMessageId) then error("networkMessageId is empty!", 3) end self.packetsSent = self.packetsSent + 1 @@ -967,7 +967,7 @@ end -- @param data The data to send. function Client:send(event, data) local networkMessageId = data[1] or data.networkMessageId - if util.IsEmpty(networkMessageId) then + if Utils.IsEmpty(networkMessageId) then error("networkMessageId is empty!", 3) end diff --git a/mods/noita-mp/lua_modules/share/lua/5.1/zstd.lua b/mods/noita-mp/lua_modules/share/lua/5.1/zstd.lua index a45063b5a..5594c34cf 100644 --- a/mods/noita-mp/lua_modules/share/lua/5.1/zstd.lua +++ b/mods/noita-mp/lua_modules/share/lua/5.1/zstd.lua @@ -88,7 +88,7 @@ local arr_utint8_t = ffi_typeof "uint8_t[?]" local ptr_zstd_inbuffer_t = ffi_typeof "ZSTD_inBuffer[1]" local ptr_zstd_outbuffer_t = ffi_typeof "ZSTD_outBuffer[1]" -local fu = require("file_util") +local fu = require("FileUtils") local zstd = ffi_load(fu.GetAbsolutePathOfNoitaRootDirectory() .. "\\mods\\noita-mp\\lua_modules\\lib\\lua\\5.1\\libzstd") local file = assert(io.popen("zstd -vV", "r")) local zstdVersion = file:read("*a") diff --git a/mods/noita-mp/noita-mp-3.0.0-3.rockspec b/mods/noita-mp/noita-mp-4.0.1-4.rockspec similarity index 51% rename from mods/noita-mp/noita-mp-3.0.0-3.rockspec rename to mods/noita-mp/noita-mp-4.0.1-4.rockspec index e021e7f1f..79f64ab2a 100644 --- a/mods/noita-mp/noita-mp-3.0.0-3.rockspec +++ b/mods/noita-mp/noita-mp-4.0.1-4.rockspec @@ -1,6 +1,6 @@ rockspec_format = "3.0" package = "noita-mp" -version = "3.0.0-3" -- Needs to be updated manually and the same as in `.version` file. +version = "4.0.1-4" -- Needs to be updated manually and the same as in `.version` file. source = { url = "git+https://github.com/Ismoh/NoitaMP.git" } @@ -9,66 +9,75 @@ description = { license = "GNU GPL v3" } dependencies = { - "lua ~> 5.1", + "lua = 5.1", + "dkjson = 2.6-1", + "lua-path = 0.3.1-2", + "luacov = 0.15.0-1", + "luacov-coveralls = 0.2.3-1", "luafilesystem = 1.8.0-1", + "luajit-zstd = 0.2.3-1", + "luaposix = 36.1-1", + "luasocket = 3.1.0-1", "luaunit = 3.4-1", + "uuid = 0.3-1", + "winapi = 1.4.2-1" } build = { type = "builtin", modules = { -- change this to copy_directories? Does package path work without `modules`? - config = "config.lua", - ["files.scripts.DefaultBiomeMap"] = "files/scripts/DefaultBiomeMap.lua", - ["files.scripts.Ui"] = "files/scripts/Ui.lua", - ["files.scripts.biome.testingRoom"] = "files/scripts/biome/testingRoom.lua", - ["files.scripts.extensions.ffi_extensions"] = "files/scripts/extensions/ffi_extensions.lua", - ["files.scripts.extensions.globalExtensions"] = "files/scripts/extensions/globalExtensions.lua", - ["files.scripts.extensions.mathExtensions"] = "files/scripts/extensions/mathExtensions.lua", - ["files.scripts.extensions.string_extensions"] = "files/scripts/extensions/string_extensions.lua", - ["files.scripts.extensions.table_extensions"] = "files/scripts/extensions/table_extensions.lua", - ["files.scripts.init.init_"] = "files/scripts/init/init_.lua", - ["files.scripts.init.init_logger"] = "files/scripts/init/init_logger.lua", - ["files.scripts.init.init_package_loading"] = "files/scripts/init/init_package_loading.lua", - ["files.scripts.net.Client"] = "files/scripts/net/Client.lua", - ["files.scripts.net.Server"] = "files/scripts/net/Server.lua", - ["files.scripts.noita-components.dump_logger"] = "files/scripts/noita-components/dump_logger.lua", - ["files.scripts.noita-components.lua_component_enabler"] = "files/scripts/noita-components/lua_component_enabler.lua", - ["files.scripts.noita-components.name_tags"] = "files/scripts/noita-components/name_tags.lua", - ["files.scripts.noita-components.nuid_debug"] = "files/scripts/noita-components/nuid_debug.lua", - ["files.scripts.noita-components.nuid_updater"] = "files/scripts/noita-components/nuid_updater.lua", - ["files.scripts.util.CoroutineUtils"] = "files/scripts/util/CoroutineUtils.lua", - ["files.scripts.util.CustomProfiler"] = "files/scripts/util/CustomProfiler.lua", - ["files.scripts.util.EntityUtils"] = "files/scripts/util/EntityUtils.lua", - ["files.scripts.util.GlobalsUtils"] = "files/scripts/util/GlobalsUtils.lua", - ["files.scripts.util.NetworkUtils"] = "files/scripts/util/NetworkUtils.lua", - ["files.scripts.util.NetworkVscUtils"] = "files/scripts/util/NetworkVscUtils.lua", - ["files.scripts.util.NoitaComponentUtils"] = "files/scripts/util/NoitaComponentUtils.lua", - ["files.scripts.util.NuidUtils"] = "files/scripts/util/NuidUtils.lua", - ["files.scripts.util.file_util"] = "files/scripts/util/file_util.lua", - ["files.scripts.util.GuidUtils"] = "files/scripts/util/GuidUtils.lua", - ["files.scripts.util.util"] = "files/scripts/util/util.lua", - init = "init.lua", - modSettingsUpdater = "modSettingsUpdater.lua", - settings = "settings.lua", - ["tests.config_test"] = "tests/config_test.lua", - ["tests.files.scripts.extensions.string_extensions_test"] = "tests/files/scripts/extensions/string_extensions_test.lua", - ["tests.files.scripts.extensions.table_extensions_test"] = "tests/files/scripts/extensions/table_extensions_test.lua", - ["tests.files.scripts.init.init__test"] = "tests/files/scripts/init/init__test.lua", - ["tests.files.scripts.init.init_logger_test"] = "tests/files/scripts/init/init_logger_test.lua", - ["tests.files.scripts.init.init_package_loading_test"] = "tests/files/scripts/init/init_package_loading_test.lua", - ["tests.files.scripts.net.Server_test"] = "tests/files/scripts/net/Server_test.lua", - ["tests.files.scripts.util.EntityUtils_test"] = "tests/files/scripts/util/EntityUtils_test.lua", - ["tests.files.scripts.util.GlobalsUtils_test"] = "tests/files/scripts/util/GlobalsUtils_test.lua", - ["tests.files.scripts.util.NetworkUtils_test"] = "tests/files/scripts/util/NetworkUtils_test.lua", - ["tests.files.scripts.util.NetworkVscUtils_test"] = "tests/files/scripts/util/NetworkVscUtils_test.lua", - ["tests.files.scripts.util.NuidUtils_test"] = "tests/files/scripts/util/NuidUtils_test.lua", - ["tests.files.scripts.util.file_util_test"] = "tests/files/scripts/util/file_util_test.lua", - ["tests.files.scripts.util.GuidUtils_test"] = "tests/files/scripts/util/GuidUtils_test.lua", - ["tests.files.scripts.util.util_test"] = "tests/files/scripts/util/util_test.lua", - ["tests.init_test"] = "tests/init_test.lua", - ["tests._initializeUnitTests"] = "tests/_initializeUnitTests.lua" + config = "config.lua", + ["files.scripts.DefaultBiomeMap"] = "files/scripts/DefaultBiomeMap.lua", + ["files.scripts.Ui"] = "files/scripts/Ui.lua", + ["files.scripts.biome.testingRoom"] = "files/scripts/biome/testingRoom.lua", + ["files.scripts.extensions.ffiExtensions"] = "files/scripts/extensions/ffiExtensions.lua", + ["files.scripts.extensions.globalExtensions"] = "files/scripts/extensions/globalExtensions.lua", + ["files.scripts.extensions.mathExtensions"] = "files/scripts/extensions/mathExtensions.lua", + ["files.scripts.extensions.stringExtensions"] = "files/scripts/extensions/stringExtensions.lua", + ["files.scripts.extensions.tableExtensions"] = "files/scripts/extensions/tableExtensions.lua", + ["files.scripts.init.init_"] = "files/scripts/init/init_.lua", + ["files.scripts.init.init_logger"] = "files/scripts/init/init_logger.lua", + ["files.scripts.init.init_package_loading"] = "files/scripts/init/init_package_loading.lua", + ["files.scripts.net.Client"] = "files/scripts/net/Client.lua", + ["files.scripts.net.Server"] = "files/scripts/net/Server.lua", + ["files.scripts.noita-components.dump_logger"] = "files/scripts/noita-components/dump_logger.lua", + ["files.scripts.noita-components.lua_component_enabler"] = "files/scripts/noita-components/lua_component_enabler.lua", + ["files.scripts.noita-components.name_tags"] = "files/scripts/noita-components/name_tags.lua", + ["files.scripts.noita-components.nuid_debug"] = "files/scripts/noita-components/nuid_debug.lua", + ["files.scripts.noita-components.nuid_updater"] = "files/scripts/noita-components/nuid_updater.lua", + ["files.scripts.util.CoroutineUtils"] = "files/scripts/util/CoroutineUtils.lua", + ["files.scripts.util.CustomProfiler"] = "files/scripts/util/CustomProfiler.lua", + ["files.scripts.util.EntityUtils"] = "files/scripts/util/EntityUtils.lua", + ["files.scripts.util.GlobalsUtils"] = "files/scripts/util/GlobalsUtils.lua", + ["files.scripts.util.NetworkUtils"] = "files/scripts/util/NetworkUtils.lua", + ["files.scripts.util.NetworkVscUtils"] = "files/scripts/util/NetworkVscUtils.lua", + ["files.scripts.util.NoitaComponentUtils"] = "files/scripts/util/NoitaComponentUtils.lua", + ["files.scripts.util.NuidUtils"] = "files/scripts/util/NuidUtils.lua", + ["files.scripts.util.FileUtils"] = "files/scripts/util/FileUtils.lua", + ["files.scripts.util.GuidUtils"] = "files/scripts/util/GuidUtils.lua", + ["files.scripts.util.util"] = "files/scripts/util/util.lua", + init = "init.lua", + modSettingsUpdater = "modSettingsUpdater.lua", + settings = "settings.lua", + ["tests.config_test"] = "tests/config_test.lua", + ["tests.files.scripts.extensions.stringExtensions_test"] = "tests/files/scripts/extensions/stringExtensions_test.lua", + ["tests.files.scripts.extensions.tableExtensions_test"] = "tests/files/scripts/extensions/tableExtensions_test.lua", + ["tests.files.scripts.init.init__test"] = "tests/files/scripts/init/init__test.lua", + ["tests.files.scripts.init.init_logger_test"] = "tests/files/scripts/init/init_logger_test.lua", + ["tests.files.scripts.init.init_package_loading_test"] = "tests/files/scripts/init/init_package_loading_test.lua", + ["tests.files.scripts.net.Server_test"] = "tests/files/scripts/net/Server_test.lua", + ["tests.files.scripts.util.EntityUtils_test"] = "tests/files/scripts/util/EntityUtils_test.lua", + ["tests.files.scripts.util.GlobalsUtils_test"] = "tests/files/scripts/util/GlobalsUtils_test.lua", + ["tests.files.scripts.util.NetworkUtils_test"] = "tests/files/scripts/util/NetworkUtils_test.lua", + ["tests.files.scripts.util.NetworkVscUtils_test"] = "tests/files/scripts/util/NetworkVscUtils_test.lua", + ["tests.files.scripts.util.NuidUtils_test"] = "tests/files/scripts/util/NuidUtils_test.lua", + ["tests.files.scripts.util.FileUtils_test"] = "tests/files/scripts/util/FileUtils_test.lua", + ["tests.files.scripts.util.GuidUtils_test"] = "tests/files/scripts/util/GuidUtils_test.lua", + ["tests.files.scripts.util.util_test"] = "tests/files/scripts/util/util_test.lua", + ["tests.init_test"] = "tests/init_test.lua", + ["tests.unitTestRunner"] = "tests/unitTestRunner.lua" }, } test = { type = "command", - script = "tests/_initializeUnitTests.lua", + script = "tests/unitTestRunner.lua", } diff --git a/mods/noita-mp/tests/config_test.lua b/mods/noita-mp/tests/config_test.lua deleted file mode 100644 index dc7690ad4..000000000 --- a/mods/noita-mp/tests/config_test.lua +++ /dev/null @@ -1,15 +0,0 @@ -local params = ... - -local lu = require("luaunit") - -TestConfig = {} - -function TestConfig:setUp() - -end - -function TestConfig:tearDown() - -end - -lu.LuaUnit.run(params) diff --git a/mods/noita-mp/tests/files/scripts/NoitaMpSettings_test.lua b/mods/noita-mp/tests/files/scripts/NoitaMpSettings_test.lua index dbf4d663f..264f047d4 100644 --- a/mods/noita-mp/tests/files/scripts/NoitaMpSettings_test.lua +++ b/mods/noita-mp/tests/files/scripts/NoitaMpSettings_test.lua @@ -1,11 +1,4 @@ ---- ---- Created by Ismoh. ---- DateTime: 14.02.2023 12:01 ---- -local params = ... - -local lu = require("luaunit") -local fu = require("file_util") +local fu = require("FileUtils") TestNoitaMpSettings = {} @@ -17,7 +10,7 @@ end function TestNoitaMpSettings:testClearAndCreateSettings() NoitaMpSettings.clearAndCreateSettings() - local files = fu.getAllFilesInDirectory(fu.getAbsolutePathOfNoitaMpSettingsDirectory(), "json") + local files = fu.GetAllFilesInDirectory(fu.GetAbsolutePathOfNoitaMpSettingsDirectory(), "json") lu.assertEquals(files, {}, "Settings directory wasn't empty!") end @@ -42,6 +35,4 @@ function TestNoitaMpSettings:testGetSetting() NoitaMpSettings.writeSettings("name", name) local nameSetting = NoitaMpSettings.getSetting("name") lu.assertEquals(nameSetting, name) -end - -lu.LuaUnit.run(params) +end \ No newline at end of file diff --git a/mods/noita-mp/tests/files/scripts/extensions/string_extensions_test.lua b/mods/noita-mp/tests/files/scripts/extensions/stringExtensions_test.lua similarity index 93% rename from mods/noita-mp/tests/files/scripts/extensions/string_extensions_test.lua rename to mods/noita-mp/tests/files/scripts/extensions/stringExtensions_test.lua index 0c0c2ae38..535a73c2e 100644 --- a/mods/noita-mp/tests/files/scripts/extensions/string_extensions_test.lua +++ b/mods/noita-mp/tests/files/scripts/extensions/stringExtensions_test.lua @@ -1,7 +1,3 @@ -local params = ... - -local lu = require("luaunit") - TestStringExtensions = {} function TestStringExtensions:setUp() @@ -32,5 +28,3 @@ function TestStringExtensions:testContains() lu.assertIsTrue(string.contains("noita-mp.log_level_testing", "noita-mp.log_level_")) lu.assertIsFalse(string.contains("ASDF", "Noita is nice, but abandoned!")) end - -lu.LuaUnit.run(params) diff --git a/mods/noita-mp/tests/files/scripts/extensions/table_extensions_test.lua b/mods/noita-mp/tests/files/scripts/extensions/tableExtensions_test.lua similarity index 85% rename from mods/noita-mp/tests/files/scripts/extensions/table_extensions_test.lua rename to mods/noita-mp/tests/files/scripts/extensions/tableExtensions_test.lua index b10eb29f3..21cea47ac 100644 --- a/mods/noita-mp/tests/files/scripts/extensions/table_extensions_test.lua +++ b/mods/noita-mp/tests/files/scripts/extensions/tableExtensions_test.lua @@ -1,25 +1,7 @@ -local params = ... - -local lu = require("luaunit") - TestTableExtensions = {} function TestTableExtensions:setUp() - -- Make absolutely sure, that the already mocked Noita API function is not overwritten - local mockedModSettingGet = ModSettingGet - ModSettingGet = function(id) - if string.contains(id, "noita-mp.log_level_") then - return { "off", "OFF" } - end - if id == "noita-mp.name" then - return "testName" - end - if id == "noita-mp.guid" then - return GuidUtils:getGuid() - end - - mockedModSettingGet(id) - end + end function TestTableExtensions:tearDown() @@ -120,6 +102,4 @@ function TestTableExtensions:testContentToString() local expectedStr4 = "test,guid,1234,3,1.2,3.4,0.5,12,3" local str4 = table.contentToString(tbl4) lu.assertEquals(str4, expectedStr4) -end - -lu.LuaUnit.run(params) +end \ No newline at end of file diff --git a/mods/noita-mp/tests/files/scripts/init/init__test.lua b/mods/noita-mp/tests/files/scripts/init/init__test.lua index 34849eb0e..8f08e7508 100644 --- a/mods/noita-mp/tests/files/scripts/init/init__test.lua +++ b/mods/noita-mp/tests/files/scripts/init/init__test.lua @@ -1,7 +1,3 @@ -local params = ... - -local lu = require("luaunit") - TestInit_ = {} function TestInit_:setUp() @@ -11,5 +7,3 @@ end function TestInit_:tearDown() end - -lu.LuaUnit.run(params) diff --git a/mods/noita-mp/tests/files/scripts/init/init_logger_test.lua b/mods/noita-mp/tests/files/scripts/init/init_logger_test.lua deleted file mode 100644 index c3f84168a..000000000 --- a/mods/noita-mp/tests/files/scripts/init/init_logger_test.lua +++ /dev/null @@ -1,15 +0,0 @@ -local params = ... - -local lu = require("luaunit") - -TestInitLogger = {} - -function TestInitLogger:setUp() - -end - -function TestInitLogger:tearDown() - -end - -lu.LuaUnit.run(params) diff --git a/mods/noita-mp/tests/files/scripts/init/init_package_loading_test.lua b/mods/noita-mp/tests/files/scripts/init/init_package_loading_test.lua index 78ed3e7dd..9113aaf38 100644 --- a/mods/noita-mp/tests/files/scripts/init/init_package_loading_test.lua +++ b/mods/noita-mp/tests/files/scripts/init/init_package_loading_test.lua @@ -1,6 +1,3 @@ -local params = ... - -local lu = require("luaunit") TestInitPackageLoading = {} @@ -10,6 +7,4 @@ end function TestInitPackageLoading:tearDown() -end - -lu.LuaUnit.run(params) +end \ No newline at end of file diff --git a/mods/noita-mp/tests/files/scripts/net/Server_test.lua b/mods/noita-mp/tests/files/scripts/net/Server_test.lua index 3d3d72753..0963cd58d 100644 --- a/mods/noita-mp/tests/files/scripts/net/Server_test.lua +++ b/mods/noita-mp/tests/files/scripts/net/Server_test.lua @@ -1,7 +1,3 @@ -local params = ... - -local lu = require("luaunit") - TestServer = {} function TestServer:setUp() @@ -15,5 +11,3 @@ end function TestServer:test() -- end - -lu.LuaUnit.run(params) \ No newline at end of file diff --git a/mods/noita-mp/tests/files/scripts/util/EntityCache_test.lua b/mods/noita-mp/tests/files/scripts/util/EntityCache_test.lua index 73cd10b10..7a1fd36b7 100644 --- a/mods/noita-mp/tests/files/scripts/util/EntityCache_test.lua +++ b/mods/noita-mp/tests/files/scripts/util/EntityCache_test.lua @@ -1,7 +1,3 @@ -local params = ... -local lu = require("luaunit") -require("luaExtensions") - TestEntityCache = {} local guid1 = GuidUtils:getGuid() @@ -103,6 +99,4 @@ function TestEntityCache:testUsage() EntityCache.delete(4) EntityCache.delete(5) -end - -lu.LuaUnit.run(params) \ No newline at end of file +end \ No newline at end of file diff --git a/mods/noita-mp/tests/files/scripts/util/EntityUtils_test.lua b/mods/noita-mp/tests/files/scripts/util/EntityUtils_test.lua index 503953a83..bb56d6855 100644 --- a/mods/noita-mp/tests/files/scripts/util/EntityUtils_test.lua +++ b/mods/noita-mp/tests/files/scripts/util/EntityUtils_test.lua @@ -1,7 +1,3 @@ -local params = ... - -local lu = require("luaunit") - TestEntityUtils = {} function TestEntityUtils:setUp() @@ -11,5 +7,3 @@ end function TestEntityUtils:tearDown() end - -lu.LuaUnit.run(params) diff --git a/mods/noita-mp/tests/files/scripts/util/file_util_test.lua b/mods/noita-mp/tests/files/scripts/util/FileUtils_test.lua similarity index 79% rename from mods/noita-mp/tests/files/scripts/util/file_util_test.lua rename to mods/noita-mp/tests/files/scripts/util/FileUtils_test.lua index 7bbe7ee51..714152a1d 100644 --- a/mods/noita-mp/tests/files/scripts/util/file_util_test.lua +++ b/mods/noita-mp/tests/files/scripts/util/FileUtils_test.lua @@ -1,26 +1,8 @@ -local params = ... - ---- Make absolutely sure, that the already mocked Noita API function is not overwritten -local mockedModSettingGet = ModSettingGet -ModSettingGet = function(id) - if string.contains(id, "noita-mp.log_level_") then - return { "trace, debug, info, warn", "TRACE" } - end - - if mockedModSettingGet then - mockedModSettingGet(id) - end - - error(("Mod setting '%s' is not mocked! Add it!"):format(id), 2) -end - -local lu = require("luaunit") -local fu = require("file_util") - -TestFileUtil = {} +local os_name = require("os_name") +local fu = require("FileUtils") +TestFileUtil = {} function TestFileUtil:setUp() - -- Mock Noita Api global functions _G.DebugGetIsDevBuild = function() return false @@ -32,7 +14,20 @@ function TestFileUtil:setUp() end function TestFileUtil:tearDown() - + -- Make sure OS detection isn't broken, when changed in tests + _G.is_windows = true + _G.is_linux = false + _G.pathSeparator = tostring(package.config:sub(1, 1)) + local current_platform, current_architecture = os_name.getOS() + if current_platform == "Windows" then + _G.is_windows = true + _G.is_linux = false + _G.pathSeparator = "\\" + else + _G.is_windows = false + _G.is_linux = true + _G.pathSeparator = "/" + end end ---------------------------------------------------------------------------------------------------- @@ -40,58 +35,45 @@ end ---------------------------------------------------------------------------------------------------- function TestFileUtil:testReplacePathSeparatorOnWindows() - local old_is_windows = _G.is_windows - local old_is_linux = _G.is_linux + local old_is_windows = _G.is_windows + local old_is_linux = _G.is_linux local old_pathSeparator = _G.pathSeparator - _G.is_windows = true -- TODO: is there a better way to mock? - _G.is_linux = false -- TODO: is there a better way to mock? + _G.is_windows = true -- TODO: is there a better way to mock? + _G.is_linux = false -- TODO: is there a better way to mock? _G.pathSeparator = "\\" -- TODO: is there a better way to mock? - local path_unix = "/test/path/123" - local path_windows = fu.ReplacePathSeparator(path_unix) + local path_unix = "/test/path/123" + local path_windows = fu.ReplacePathSeparator(path_unix) lu.assertNotEquals(path_unix, path_windows) lu.assertEquals([[\test\path\123]], path_windows) - _G.is_windows = old_is_windows - _G.is_linux = old_is_linux + _G.is_windows = old_is_windows + _G.is_linux = old_is_linux _G.pathSeparator = old_pathSeparator end function TestFileUtil:testReplacePathSeparatorOnUnix() - local old_is_windows = _G.is_windows - local old_is_linux = _G.is_linux + local old_is_windows = _G.is_windows + local old_is_linux = _G.is_linux local old_pathSeparator = _G.pathSeparator - _G.is_windows = false -- TODO: is there a better way to mock? - _G.is_linux = true -- TODO: is there a better way to mock? + _G.is_windows = false -- TODO: is there a better way to mock? + _G.is_linux = true -- TODO: is there a better way to mock? _G.pathSeparator = "/" -- TODO: is there a better way to mock? - local path_windows = "\\test\\path\\123" - local path_unix = fu.ReplacePathSeparator(path_windows) + local path_windows = "\\test\\path\\123" + local path_unix = fu.ReplacePathSeparator(path_windows) lu.assertNotEquals(path_windows, path_unix) lu.assertEquals("/test/path/123", path_unix) - _G.is_windows = old_is_windows - _G.is_linux = old_is_linux + _G.is_windows = old_is_windows + _G.is_linux = old_is_linux _G.pathSeparator = old_pathSeparator end -function TestFileUtil:testReplacePathSeparatorUnknownOs() - local old_is_windows = _G.is_windows - local old_is_linux = _G.is_linux - - _G.is_windows = false -- TODO: is there a better way to mock? - _G.is_linux = false -- TODO: is there a better way to mock? - - lu.assertErrorMsgContains("file_util.lua | Unable to detect OS", fu.ReplacePathSeparator, "path doesnt matter") - - _G.is_windows = old_is_windows - _G.is_linux = old_is_linux -end - function TestFileUtil:testRemoveTrailingPathSeparator() local path = tostring(_G.pathSeparator .. "persistent" .. _G.pathSeparator .. "flags" .. _G.pathSeparator) local result = fu.RemoveTrailingPathSeparator(path) @@ -118,7 +100,7 @@ function TestFileUtil:testSetAbsolutePathOfNoitaRootDirectoryUnknownOs() _G.is_windows = false -- TODO: is there a better way to mock? _G.is_linux = false -- TODO: is there a better way to mock? - lu.assertErrorMsgContains("file_util.lua | Unable to detect OS", fu.SetAbsolutePathOfNoitaRootDirectory, + lu.assertErrorMsgContains("FileUtils.lua | Unable to detect OS", fu.SetAbsolutePathOfNoitaRootDirectory, "path doesnt matter") _G.is_windows = old_is_windows @@ -126,6 +108,8 @@ function TestFileUtil:testSetAbsolutePathOfNoitaRootDirectoryUnknownOs() end function TestFileUtil:testGetAbsolutePathOfNoitaRootDirectory() + Logger.trace(Logger.channels.testing, + ("Need to verify absolute path of root noita: %s"):format(fu.GetAbsolutePathOfNoitaRootDirectory())) lu.assertStrContains(fu.GetAbsolutePathOfNoitaRootDirectory(), _G.pathSeparator) -- TODO: Need a better test for this! end @@ -215,9 +199,9 @@ end ---------------------------------------------------------------------------------------------------- function TestFileUtil:testExists() - lu.assertNotIsTrue(fu.exists("nonexistingfile.asdf")) - lu.assertErrorMsgContains("is not type of string!", fu.exists) - lu.assertIsTrue(fu.exists(fu.GetAbsoluteDirectoryPathOfNoitaMP() .. "/mod.xml")) + lu.assertNotIsTrue(fu.Exists("nonexistingfile.asdf")) + lu.assertErrorMsgContains("is not type of string!", fu.Exists) + lu.assertIsTrue(fu.Exists(fu.GetAbsoluteDirectoryPathOfNoitaMP() .. "/mod.xml")) end function TestFileUtil:testIsFile() @@ -245,7 +229,7 @@ function TestFileUtil:testWriteBinaryFile() local full_path = fu.GetAbsolutePathOfNoitaRootDirectory() .. "/write-temporary-binary-test-file.txt" fu.WriteBinaryFile(full_path, "File Content") - lu.assertIsTrue(fu.exists(full_path)) + lu.assertIsTrue(fu.Exists(full_path)) os.remove(full_path) end @@ -262,7 +246,7 @@ function TestFileUtil:testWriteFile() local full_path = fu.GetAbsolutePathOfNoitaRootDirectory() .. "/write-temporary-test-file.txt" fu.WriteFile(full_path, "File Content") - lu.assertIsTrue(fu.exists(full_path)) + lu.assertIsTrue(fu.Exists(full_path)) os.remove(full_path) end @@ -283,14 +267,12 @@ end function TestFileUtil:testExists7zip() local old = _G.seven_zip _G.seven_zip = false -- mock - lu.assertNotIsTrue(fu.exists7zip()) + lu.assertNotIsTrue(fu.Exists7zip()) _G.seven_zip = true -- mock - lu.assertIsTrue(fu.exists7zip()) + lu.assertIsTrue(fu.Exists7zip()) _G.seven_zip = old end function TestFileUtil:testCreate7zipArchive() --fu.Create7zipArchive() -end - -lu.LuaUnit.run(params) \ No newline at end of file +end \ No newline at end of file diff --git a/mods/noita-mp/tests/files/scripts/util/GlobalsUtils_test.lua b/mods/noita-mp/tests/files/scripts/util/GlobalsUtils_test.lua index 2b8be53a7..e99d41bad 100644 --- a/mods/noita-mp/tests/files/scripts/util/GlobalsUtils_test.lua +++ b/mods/noita-mp/tests/files/scripts/util/GlobalsUtils_test.lua @@ -1,7 +1,3 @@ -local params = ... - -local lu = require("luaunit") - TestGlobalsUtils = {} function TestGlobalsUtils:setUp() @@ -11,5 +7,3 @@ end function TestGlobalsUtils:tearDown() end - -lu.LuaUnit.run(params) diff --git a/mods/noita-mp/tests/files/scripts/util/GuidUtils_test.lua b/mods/noita-mp/tests/files/scripts/util/GuidUtils_test.lua index db33101fb..a6f4d5fa5 100644 --- a/mods/noita-mp/tests/files/scripts/util/GuidUtils_test.lua +++ b/mods/noita-mp/tests/files/scripts/util/GuidUtils_test.lua @@ -1,17 +1,7 @@ -local params = ... - -local lu = require("luaunit") -local GuidUtils = require("GuidUtils") - TestGuidUtils = {} function TestGuidUtils:setUp() - -- Make absolutely sure, that the already mocked Noita API function is not overwritten - local mockedDebugGetIsDevBuild = DebugGetIsDevBuild - -- Mock Noita Api global functions - DebugGetIsDevBuild = function() - return DebugGetIsDevBuild or false - end + end function TestGuidUtils:tearDown() @@ -45,5 +35,3 @@ function TestGuidUtils:testToNumber() lu.assertNotIsNil(number) lu.assertIsTrue(type(number) == "number", "GuidUtils.toNumber didn't return a number!") end - -lu.LuaUnit.run(params) diff --git a/mods/noita-mp/tests/files/scripts/util/Logger_test.lua b/mods/noita-mp/tests/files/scripts/util/Logger_test.lua index 06536249b..95647e64f 100644 --- a/mods/noita-mp/tests/files/scripts/util/Logger_test.lua +++ b/mods/noita-mp/tests/files/scripts/util/Logger_test.lua @@ -1,29 +1,18 @@ ---- ---- Created by Ismoh-PC. ---- DateTime: 22.01.2023 01:15 ---- -local params = ... - -local lu = require("luaunit") - TestLogger = {} TestLogger.mockedLogLevel = { "trace, debug, info, warn", "TRACE" } +local globalModSettingsGet = ModSettingGet function TestLogger:setUp() - -- Make absolutely sure, that the already mocked Noita API function is not overwritten - local mockedModSettingGet = ModSettingGet - ---@param id string ModSettingGet = function(id) if string.contains(id, "noita-mp.log_level_") then return TestLogger.mockedLogLevel end - mockedModSettingGet(id) + globalModSettingsGet(id) end - end function TestLogger:tearDown() - + ModSettingGet = globalModSettingsGet end function TestLogger:errors() @@ -78,5 +67,3 @@ function TestLogger:testWarn() lu.assertIsFalse(Logger.info(Logger.channels.testing, "This should NOT be logged!")) lu.assertIsTrue(Logger.warn(Logger.channels.testing, "This should be logged, warn level!")) end - -lu.LuaUnit.run(params) diff --git a/mods/noita-mp/tests/files/scripts/util/NetworkCacheUtils_test.lua b/mods/noita-mp/tests/files/scripts/util/NetworkCacheUtils_test.lua index c802d7565..cbc12f146 100644 --- a/mods/noita-mp/tests/files/scripts/util/NetworkCacheUtils_test.lua +++ b/mods/noita-mp/tests/files/scripts/util/NetworkCacheUtils_test.lua @@ -1,55 +1,3 @@ ---- ---- Created by Ismoh-PC. ---- DateTime: 23.01.2023 17:37 ---- -local params = ... - ---- Make absolutely sure, that the already mocked Noita API function is not overwritten -local mockedModSettingGetNextValue = ModSettingGetNextValue -ModSettingGetNextValue = function(id) - if id == "noita-mp.guid" then - return GuidUtils:getGuid() - end - - if mockedModSettingGetNextValue then - mockedModSettingGetNextValue(id) - end - - error(("Trying to access '%s', but it isn't mocked yet!"):format(id), 2) -end - -if not ModSettingSetNextValue then - ModSettingSetNextValue = function(id) - Logger.trace(Logger.channels.testing, ("Mocked ModSettingSetNextValue id %s."):format(id)) - return id - end -end - ---- Make absolutely sure, that the already mocked Noita API function is not overwritten -local mockedModSettingGet = ModSettingGet -ModSettingGet = function(id) - if string.contains(id, "noita-mp.log_level_") then - return { "trace, debug, info, warn", "TRACE" } - end - if id == "noita-mp.name" then - return "noita-mp.name" - end - if id == "noita-mp.guid" then - return GuidUtils:getGuid() - end - - if mockedModSettingGet then - mockedModSettingGet(id) - end - - error(("Mod setting '%s' is not mocked! Add it!"):format(id), 2) -end - --- [[ require ]] -- -require("NetworkUtils") -require("NetworkCacheUtils") -require("luaExtensions") -require("CustomProfiler") if not Server then require("Server") end @@ -57,9 +5,6 @@ if not Client then require("Client") end -local lu = require("luaunit") - --- [[ Test ]] -- TestNetworkCacheUtils = {} --- Setup function for each test. @@ -112,6 +57,4 @@ end function TestNetworkCacheUtils:testGet() --local guid = GuidUtils:getGuid() --NetworkCacheUtils.get(guid, networkMessageId, event) -end - -lu.LuaUnit.run(params) \ No newline at end of file +end \ No newline at end of file diff --git a/mods/noita-mp/tests/files/scripts/util/NetworkUtils_test.lua b/mods/noita-mp/tests/files/scripts/util/NetworkUtils_test.lua index c7ad444e9..0d2b97d10 100644 --- a/mods/noita-mp/tests/files/scripts/util/NetworkUtils_test.lua +++ b/mods/noita-mp/tests/files/scripts/util/NetworkUtils_test.lua @@ -1,19 +1,3 @@ -local params = ... - --- [[ Mock Noita API functions, which are needed before/during require is used ]] -- -mockedModSettingGetNextValue = ModSettingGetNextValue -ModSettingGetNextValue = function(id) - if mockedModSettingGetNextValue then - mockedModSettingGetNextValue(id) - end -end - --- [[ require ]] -- -require("luaExtensions") -require("EntityUtils") -require("NetworkUtils") -require("GuidUtils") -require("CustomProfiler") if not Server then require("Server") end @@ -21,10 +5,6 @@ if not Client then require("Client") end -local lu = require("luaunit") -local util = require("util") - --- [[ Test ]] -- TestNetworkUtils = {} --- Setup function for each test. @@ -115,7 +95,7 @@ function TestNetworkUtils:testAlreadySentConnect2() Client.connection.send = function(serializedMessage, sendChannel, sendMode) Logger.trace(Logger.channels.testing, ("Mocked 'self.connection:send(serializedMessage %s, self.sendChannel, self.sendMode)' executed!") - :format(util.pformat(serializedMessage))) + :format(Utils.pformat(serializedMessage))) end -- [[ Send message ]] -- @@ -167,7 +147,7 @@ function TestNetworkUtils:testAlreadySentDisconnect2() Client.connection.send = function(serializedMessage, sendChannel, sendMode) Logger.trace(Logger.channels.testing, ("Mocked 'self.connection:send(serializedMessage %s, self.sendChannel, self.sendMode)' executed!") - :format(util.pformat(serializedMessage))) + :format(Utils.pformat(serializedMessage))) end -- [[ Send message ]] -- @@ -221,7 +201,7 @@ function TestNetworkUtils:testAlreadySentSeed() Client.connection.send = function(serializedMessage, sendChannel, sendMode) Logger.trace(Logger.channels.testing, ("Mocked 'self.connection:send(serializedMessage %s, self.sendChannel, self.sendMode)' executed!") - :format(util.pformat(serializedMessage))) + :format(Utils.pformat(serializedMessage))) end -- [[ Send message ]] -- @@ -241,13 +221,13 @@ function TestNetworkUtils:testAlreadySentSeed() end function TestNetworkUtils:testAlreadySentPlayerInfo() - local fu = require("file_util") + local fu = require("FileUtils") -- [[ Prepare mocked data for sending PlayerInfo! ]] -- local networkMessageId = NetworkUtils.getNextNetworkMessageId() local name = "ClientOwnerName" local guid = GuidUtils:getGuid() - local version = fu.getVersionByFile() + local version = fu.GetVersionByFile() local nuid = nil local data = { @@ -278,7 +258,7 @@ function TestNetworkUtils:testAlreadySentPlayerInfo() Client.connection.send = function(serializedMessage, sendChannel, sendMode) Logger.trace(Logger.channels.testing, ("Mocked 'self.connection:send(serializedMessage %s, self.sendChannel, self.sendMode)' executed!") - :format(util.pformat(serializedMessage))) + :format(Utils.pformat(serializedMessage))) end -- [[ Send message ]] -- @@ -329,7 +309,7 @@ function TestNetworkUtils:testAlreadySentNewGuid() Client.connection.send = function(serializedMessage, sendChannel, sendMode) Logger.trace(Logger.channels.testing, ("Mocked 'self.connection:send(serializedMessage %s, self.sendChannel, self.sendMode)' executed!") - :format(util.pformat(serializedMessage))) + :format(Utils.pformat(serializedMessage))) end -- [[ Send message ]] -- @@ -398,7 +378,7 @@ function TestNetworkUtils:testAlreadySentNewNuid() Client.connection.send = function(serializedMessage, sendChannel, sendMode) Logger.trace(Logger.channels.testing, ("Mocked 'self.connection:send(serializedMessage %s, self.sendChannel, self.sendMode)' executed!") - :format(util.pformat(serializedMessage))) + :format(Utils.pformat(serializedMessage))) end -- [[ Send message ]] -- @@ -463,7 +443,7 @@ function TestNetworkUtils:testAlreadySentNeedNuidShouldReturnTrue() filename, health, EntityUtils.isEntityPolymorphed(entityId) } - print(("Let's see if this was already sent: entity %s with data %s"):format(entityId, util.pformat(data))) + print(("Let's see if this was already sent: entity %s with data %s"):format(entityId, Utils.pformat(data))) -- [[ Check if the message was already sent ]] -- lu.assertIs(NetworkUtils.alreadySent(Client, "needNuid", data), true, "The message was already sent, but the function NetworkUtils.alreadySent() returned false!") @@ -519,7 +499,7 @@ function TestNetworkUtils:testAlreadySentNeedNuidShouldReturnFalse() filename, health, EntityUtils.isEntityPolymorphed(entityId) } - print(("Let's see if this WASN'T already sent: entity %s with data %s"):format(entityId, util.pformat(data))) + print(("Let's see if this WASN'T already sent: entity %s with data %s"):format(entityId, Utils.pformat(data))) -- [[ Check if the message WASN'T already sent ]] -- lu.assertIs(NetworkUtils.alreadySent(Client, event, data), false, "The message WASN'T already sent, but the function NetworkUtils.alreadySent() returned true!") @@ -554,7 +534,7 @@ function TestNetworkUtils:testAlreadySentLostNuid() Client.connection.send = function(serializedMessage, sendChannel, sendMode) Logger.trace(Logger.channels.testing, ("Mocked 'self.connection:send(serializedMessage %s, self.sendChannel, self.sendMode)' executed!") - :format(util.pformat(serializedMessage))) + :format(Utils.pformat(serializedMessage))) end -- [[ Send message ]] -- @@ -604,13 +584,13 @@ function TestNetworkUtils:testAlreadySentDeadNuids() Client.connection.send = function(serializedMessage, sendChannel, sendMode) Logger.trace(Logger.channels.testing, ("Mocked 'self.connection:send(serializedMessage %s, self.sendChannel, self.sendMode)' executed!") - :format(util.pformat(serializedMessage))) + :format(Utils.pformat(serializedMessage))) end local originalDestroyByNuid = EntityUtils.destroyByNuid EntityUtils.destroyByNuid = function(peer, deadNuid) Logger.trace(Logger.channels.testing, ("Mocked 'EntityUtils.destroyByNuid' on '%s' destroyed a dead nuid '%s'!") - :format(util.pformat(peer), deadNuid)) + :format(Utils.pformat(peer), deadNuid)) end require("GlobalsUtils") local originalRemoveDeadNuid = GlobalsUtils.removeDeadNuid @@ -691,7 +671,7 @@ function TestNetworkUtils:testAlreadySentNeedModList() Client.connection.send = function(serializedMessage, sendChannel, sendMode) Logger.trace(Logger.channels.testing, ("Mocked 'self.connection:send(serializedMessage %s, self.sendChannel, self.sendMode)' executed!") - :format(util.pformat(serializedMessage))) + :format(Utils.pformat(serializedMessage))) end -- [[ Send message ]] -- @@ -759,7 +739,7 @@ function TestNetworkUtils:testAlreadySentNeedModContent() Client.connection.send = function(serializedMessage, sendChannel, sendMode) Logger.trace(Logger.channels.testing, ("Mocked 'self.connection:send(serializedMessage %s, self.sendChannel, self.sendMode)' executed!") - :format(util.pformat(serializedMessage))) + :format(Utils.pformat(serializedMessage))) end -- [[ Send message ]] -- @@ -776,6 +756,4 @@ function TestNetworkUtils:testAlreadySentNeedModContent() local alreadySent = NetworkUtils.alreadySent(Client, event, data) lu.assertIsTrue(alreadySent, "NetworkMessage was already send, but NetworkUtils.alreadySent didn't find it in the cache?") -end - -lu.LuaUnit.run(params) +end \ No newline at end of file diff --git a/mods/noita-mp/tests/files/scripts/util/NetworkVscUtils_test.lua b/mods/noita-mp/tests/files/scripts/util/NetworkVscUtils_test.lua index ed98fe9d2..ca4c16160 100644 --- a/mods/noita-mp/tests/files/scripts/util/NetworkVscUtils_test.lua +++ b/mods/noita-mp/tests/files/scripts/util/NetworkVscUtils_test.lua @@ -1,7 +1,3 @@ -local params = ... - -local lu = require("luaunit") - TestNetworkVscUtils = {} function TestNetworkVscUtils:setUp() @@ -11,5 +7,3 @@ end function TestNetworkVscUtils:tearDown() end - -lu.LuaUnit.run(params) diff --git a/mods/noita-mp/tests/files/scripts/util/NuidUtils_test.lua b/mods/noita-mp/tests/files/scripts/util/NuidUtils_test.lua index bab5b6cb5..d3b962393 100644 --- a/mods/noita-mp/tests/files/scripts/util/NuidUtils_test.lua +++ b/mods/noita-mp/tests/files/scripts/util/NuidUtils_test.lua @@ -1,7 +1,3 @@ -local params = ... - -local lu = require("luaunit") - TestNuidUtils = {} function TestNuidUtils:setUp() @@ -10,6 +6,4 @@ end function TestNuidUtils:tearDown() -end - -lu.LuaUnit.run(params) +end \ No newline at end of file diff --git a/mods/noita-mp/tests/files/scripts/util/util_test.lua b/mods/noita-mp/tests/files/scripts/util/Utils_test.lua similarity index 64% rename from mods/noita-mp/tests/files/scripts/util/util_test.lua rename to mods/noita-mp/tests/files/scripts/util/Utils_test.lua index b7e028e7a..f1cdbbf47 100644 --- a/mods/noita-mp/tests/files/scripts/util/util_test.lua +++ b/mods/noita-mp/tests/files/scripts/util/Utils_test.lua @@ -1,8 +1,3 @@ -local params = ... - -local lu = require("luaunit") -local util = require("util") - TestUtil = {} function TestUtil:setUp() @@ -14,11 +9,11 @@ function TestUtil:tearDown() end function TestUtil:testSleep() - lu.assertErrorMsgContains("Unable to wait if parameter 'seconds' isn't a number:", util.Sleep, "seconds") + lu.assertErrorMsgContains("Unable to wait if parameter 'seconds' isn't a number:", Utils.Sleep, "seconds") local seconds_to_wait = 4 local timestamp_before = os.clock() - util.Sleep(seconds_to_wait) + Utils.Sleep(seconds_to_wait) local timestamp_after = os.clock() local diff = timestamp_before + seconds_to_wait Logger.debug(Logger.channels.testing,("timestamp_before=%s, timestamp_after=%s, diff=%s"):format(timestamp_before, timestamp_after, diff)) @@ -28,11 +23,9 @@ end function TestUtil:testIsEmpty() local tbl = {} table.insert(tbl, "1234") - lu.assertIsFalse(util.IsEmpty(tbl)) - - lu.assertIsTrue(util.IsEmpty(nil)) - lu.assertIsTrue(util.IsEmpty("")) - lu.assertIsTrue(util.IsEmpty({})) -end + lu.assertIsFalse(Utils.IsEmpty(tbl)) -lu.LuaUnit.run(params) + lu.assertIsTrue(Utils.IsEmpty(nil)) + lu.assertIsTrue(Utils.IsEmpty("")) + lu.assertIsTrue(Utils.IsEmpty({})) +end \ No newline at end of file diff --git a/mods/noita-mp/tests/init_test.lua b/mods/noita-mp/tests/init_test.lua deleted file mode 100644 index d21eeed7a..000000000 --- a/mods/noita-mp/tests/init_test.lua +++ /dev/null @@ -1,15 +0,0 @@ -local params = ... - -local lu = require("luaunit") - -TestInit = {} - -function TestInit:setUp() - -end - -function TestInit:tearDown() - -end - -lu.LuaUnit.run(params) diff --git a/mods/noita-mp/tests/_initializeUnitTests.lua b/mods/noita-mp/tests/unitTestRunner.lua similarity index 88% rename from mods/noita-mp/tests/_initializeUnitTests.lua rename to mods/noita-mp/tests/unitTestRunner.lua index 60cae0d40..dd5450876 100644 --- a/mods/noita-mp/tests/_initializeUnitTests.lua +++ b/mods/noita-mp/tests/unitTestRunner.lua @@ -1,14 +1,15 @@ _G.isTestLuaContext = true - +local params = ... dofile("../noita-mp/files/scripts/init/init_package_loading.lua") local lfs = require("lfs") +lu = require("luaunit") --- Returns a list of all files in a directory function getAllFilesInside(folder) local files = {} for entry in lfs.dir(folder) do - if entry ~= "." and entry ~= ".." and not entry:find("_initializeUnitTests") then + if entry ~= "." and entry ~= ".." and not entry:find("unitTestRunner") then local path = folder .. "/" .. entry local mode = lfs.attributes(path, "mode") if mode == "file" then @@ -41,14 +42,14 @@ if not ModSettingGet then end if id == "noita-mp.name" then local name = MinaUtils.getLocalMinaName() - if util.IsEmpty(name) then + if Utils.IsEmpty(name) then name = "initializeUnitTests" end return name end if id == "noita-mp.guid" then local guid = MinaUtils.getLocalMinaGuid() - if util.IsEmpty(guid) then + if Utils.IsEmpty(guid) then guid = GuidUtils:getGuid() end return guid @@ -93,10 +94,8 @@ end dofile("mods/noita-mp/files/scripts/init/init_.lua") for _, testFile in ipairs(testFiles) do - print("") - print("") - print("##################################################") - print("Running test: " .. testFile) - --dofile(testFile) - assert(loadfile(testFile))("--verbose", "--error", "--failure") -end \ No newline at end of file + dofile(testFile) + print("Loaded test " .. _ .. " " .. testFile) +end + +lu.LuaUnit.run(params)